@markless/bundler 0.8.0 → 0.10.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.
@@ -1,139 +1,10 @@
1
- import { joinURL, parsePath, withQuery, withoutLeadingSlash } from "ufo";
1
+ import { existsSync, readFileSync, readdirSync, realpathSync } from "node:fs";
2
+ import { dirname, isAbsolute, join, normalize, relative, resolve } from "pathe";
3
+ import { withQuery } from "ufo";
4
+ import { INLINE_RESUMER_PAGE_TOKEN, PRERENDER_INLINE_EVENT_NAMES_TOKEN, createInlineResumerDebugRegistrationSource, createInlineResumerSelfWakeSource, createInlineResumerSource, createPrerenderInlineResumerSource, createPrerenderSettleInlineResumerSource } from "@markless/web/inline/resumer";
5
+ import { minifySync, transformSync } from "rolldown/experimental";
2
6
  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
7
+ import { ASYNC_PROTOCOL_VERSION, protocolBoundSymbolPrefix } from "@markless/serializer";
137
8
  //#region src/execution-log.ts
138
9
  const MARKLESS_EXECUTION_LOG_MODULE_ID = "virtual:markless:dev-log";
139
10
  const MARKLESS_EXECUTION_LOG_GLOBAL = "__mxLog";
@@ -415,6 +286,532 @@ function executionLogActivationInjection(mode) {
415
286
  };
416
287
  }
417
288
  //#endregion
289
+ //#region ../web/src/debug-channel.ts
290
+ function installDebugChannelLayer(root, initialPhase, initiallyActive = true) {
291
+ const global = globalThis;
292
+ const previous = global.__MARKLESS_DEBUG__?.version === 1 ? global.__MARKLESS_DEBUG__ : void 0;
293
+ let priorRoot;
294
+ try {
295
+ priorRoot = previous?.explainInteraction(root, "__markless_debug_root__");
296
+ } catch {}
297
+ const priorContainer = priorRoot && "containerId" in priorRoot ? previous?.containers.find((entry) => entry.id === priorRoot.containerId) : void 0;
298
+ const seed = `${Date.now().toString(36)}:${Math.random().toString(36).slice(2)}`;
299
+ const id = priorContainer?.id ?? `container:${seed}`;
300
+ const rootKey = priorContainer?.root.key ?? `root:${seed}`;
301
+ const rootRef = new WeakRef(root);
302
+ const events = /* @__PURE__ */ new WeakMap();
303
+ const delegatedEvents = /* @__PURE__ */ new Set();
304
+ const keys = /* @__PURE__ */ new WeakMap();
305
+ const invalidated = /* @__PURE__ */ new WeakSet();
306
+ const routerSources = global[Symbol.for("markless.debug.channel.v1.router-sources")] ??= /* @__PURE__ */ new Set();
307
+ const ownViolations = [];
308
+ let phase = initialPhase;
309
+ let lifecycle = initiallyActive ? "active" : "registered";
310
+ let boundarySnapshots = Object.freeze([]);
311
+ let nextElement = 1;
312
+ let nextSequence = (previous?.violations.at(-1)?.sequence ?? 0) + 1;
313
+ let dropped = 0;
314
+ let pruned = false;
315
+ const freeze = (value) => Object.freeze(value);
316
+ const contains = (element) => {
317
+ const currentRoot = rootRef.deref();
318
+ return !!currentRoot && (currentRoot === element || currentRoot.contains?.(element) === true);
319
+ };
320
+ const keyFor = (element) => {
321
+ let key = keys.get(element);
322
+ if (!key) {
323
+ key = `${rootKey}:element:${nextElement++}`;
324
+ keys.set(element, key);
325
+ }
326
+ return key;
327
+ };
328
+ const eligibleAnchor = (element) => {
329
+ const anchor = element.closest?.("a[href]");
330
+ if (!anchor?.hasAttribute("data-markless-router-link") || anchor.hasAttribute("download")) return false;
331
+ const target = anchor.getAttribute("target");
332
+ if (target && target !== "_self" || anchor.relList?.contains("external")) return false;
333
+ try {
334
+ const base = global.location?.href ?? "http://localhost/";
335
+ return new URL(anchor.href ?? "", base).origin === new URL(base).origin;
336
+ } catch {
337
+ return false;
338
+ }
339
+ };
340
+ const none = (element, eventName, reason) => freeze({
341
+ kind: "none",
342
+ eventName,
343
+ reason,
344
+ containerId: id,
345
+ elementKey: keyFor(element)
346
+ });
347
+ const explain = (element, eventName) => {
348
+ if (lifecycle === "disposed" && (contains(element) || keys.has(element))) return none(element, eventName, "container-disposed");
349
+ if (!contains(element)) try {
350
+ return previous?.explainInteraction(element, eventName) ?? freeze({
351
+ kind: "none",
352
+ eventName,
353
+ reason: "outside-known-container"
354
+ });
355
+ } catch {
356
+ return freeze({
357
+ kind: "none",
358
+ eventName,
359
+ reason: "outside-known-container"
360
+ });
361
+ }
362
+ if (element.isConnected === false) return none(element, eventName, "element-disconnected");
363
+ if (eligibleAnchor(element)) {
364
+ const source = eventName === "navigate" && routerSources.has("navigation-event") ? "navigation-event" : eventName === "click" && routerSources.has("spa-click-listener") ? "spa-click-listener" : eventName === "click" && routerSources.has("ssr-link-bridge") ? "ssr-link-bridge" : void 0;
365
+ if (source) return freeze({
366
+ kind: "router-delegation",
367
+ source,
368
+ containerId: id,
369
+ elementKey: keyFor(element),
370
+ eventName
371
+ });
372
+ }
373
+ const interaction = events.get(element)?.get(eventName);
374
+ if (interaction) return freeze({ ...interaction });
375
+ if (delegatedEvents.has(eventName)) return freeze({
376
+ kind: "inline-resumer",
377
+ source: "ssr-inline",
378
+ containerId: id,
379
+ elementKey: keyFor(element),
380
+ eventName
381
+ });
382
+ if (invalidated.has(element)) return none(element, eventName, "not-registered");
383
+ try {
384
+ const prior = previous?.explainInteraction(element, eventName);
385
+ if (prior && prior.kind !== "none") return prior;
386
+ } catch {}
387
+ return none(element, eventName, "not-registered");
388
+ };
389
+ const cloneJson = (value, seen = /* @__PURE__ */ new Set()) => {
390
+ if (value === null) return null;
391
+ if (typeof value === "boolean" || typeof value === "string") return value;
392
+ if (typeof value === "number") return Number.isFinite(value) ? value : void 0;
393
+ if (!value || typeof value !== "object" || seen.has(value)) return void 0;
394
+ seen.add(value);
395
+ if (Array.isArray(value)) {
396
+ const copy = value.map((entry) => cloneJson(entry, seen));
397
+ return copy.some((entry) => entry === void 0) ? void 0 : freeze(copy);
398
+ }
399
+ if (Object.getPrototypeOf(value) !== Object.prototype) return void 0;
400
+ const copy = {};
401
+ for (const [name, entry] of Object.entries(value)) {
402
+ const cloned = cloneJson(entry, seen);
403
+ if (cloned === void 0) return void 0;
404
+ copy[name] = cloned;
405
+ }
406
+ return freeze(copy);
407
+ };
408
+ const pushViolation = (input) => {
409
+ const cloned = input.details === void 0 ? void 0 : cloneJson(input.details);
410
+ const details = cloned && !Array.isArray(cloned) && typeof cloned === "object" ? cloned : void 0;
411
+ const { details: _details, ...metadata } = input;
412
+ ownViolations.push(freeze({
413
+ ...metadata,
414
+ ...details ? { details } : {},
415
+ sequence: nextSequence++,
416
+ timestamp: Date.now()
417
+ }));
418
+ if (input.details !== void 0 && !details) ownViolations.push(freeze({
419
+ code: "MARKLESS_DEBUG_DETAILS_DROPPED",
420
+ message: "Debug violation details were not JSON-safe and were dropped.",
421
+ sequence: nextSequence++,
422
+ timestamp: Date.now()
423
+ }));
424
+ while (ownViolations.length > 100) {
425
+ ownViolations.shift();
426
+ dropped++;
427
+ }
428
+ };
429
+ const channel = freeze({
430
+ version: 1,
431
+ get containers() {
432
+ const inherited = previous?.containers.filter((entry) => entry.id !== id) ?? [];
433
+ if (pruned || lifecycle === "disposed") return freeze([...inherited]);
434
+ const currentRoot = rootRef.deref();
435
+ const connected = !!currentRoot && currentRoot.isConnected !== false;
436
+ const snapshot = freeze({
437
+ id,
438
+ phase,
439
+ lifecycle: connected ? lifecycle : "disposed",
440
+ root: freeze({
441
+ key: rootKey,
442
+ connected
443
+ }),
444
+ boundaries: freeze([...boundarySnapshots])
445
+ });
446
+ if (!connected) pruned = true;
447
+ return freeze([...inherited, snapshot]);
448
+ },
449
+ get violations() {
450
+ return freeze([...previous?.violations ?? [], ...ownViolations].slice(-100));
451
+ },
452
+ violationCapacity: 100,
453
+ get droppedViolationCount() {
454
+ return (previous?.droppedViolationCount ?? 0) + dropped;
455
+ },
456
+ explainInteraction: explain
457
+ });
458
+ Object.defineProperty(global, "__MARKLESS_DEBUG__", {
459
+ configurable: true,
460
+ enumerable: false,
461
+ value: channel,
462
+ writable: false
463
+ });
464
+ return {
465
+ start(nextPhase, active = true) {
466
+ phase = nextPhase === "ssr-resume" && phase === "csr" ? "csr" : nextPhase;
467
+ if (active) lifecycle = "active";
468
+ return id;
469
+ },
470
+ activate: () => void (lifecycle === "disposed" || (lifecycle = "active")),
471
+ dispose() {
472
+ lifecycle = "disposed";
473
+ boundarySnapshots = freeze([]);
474
+ },
475
+ invalidate(element) {
476
+ events.delete(element);
477
+ invalidated.add(element);
478
+ },
479
+ record(element, eventName, input) {
480
+ if (lifecycle === "disposed") return;
481
+ let byName = events.get(element);
482
+ if (!byName) events.set(element, byName = /* @__PURE__ */ new Map());
483
+ const symbolIds = "symbolIds" in input ? freeze([...input.symbolIds]) : void 0;
484
+ byName.set(eventName, freeze({
485
+ ...input,
486
+ ...symbolIds ? { symbolIds } : {},
487
+ containerId: id,
488
+ elementKey: keyFor(element),
489
+ eventName
490
+ }));
491
+ },
492
+ delegated(eventNames) {
493
+ if (lifecycle === "disposed") return;
494
+ for (const eventName of eventNames) delegatedEvents.add(eventName);
495
+ },
496
+ violation: pushViolation,
497
+ router: (source) => void routerSources.add(source),
498
+ boundaries(value) {
499
+ boundarySnapshots = freeze(value.map((entry) => freeze({ ...entry })));
500
+ },
501
+ disposed: () => lifecycle === "disposed"
502
+ };
503
+ }
504
+ function __marklessDebugBootstrapSource() {
505
+ return `((root,phase,active)=>{const controls=(${installDebugChannelLayer.toString()})(root,phase,active);return Object.freeze({record:(element,eventName,input)=>controls.record(element,eventName,input),delegated:(eventNames)=>controls.delegated(eventNames),router:(source)=>controls.router(source),activate:()=>controls.activate()})})`;
506
+ }
507
+ //#endregion
508
+ //#region ../serializer/src/protocol-event-names.ts
509
+ const PROTOCOL_VISIBLE_EVENT_NAME = "visible";
510
+ const PROTOCOL_IDLE_EVENT_NAME$1 = "idle";
511
+ //#endregion
512
+ //#region ../serializer/src/protocol-locator-paths.ts
513
+ /**
514
+ * The container attribute that lets resume find each located element by its
515
+ * position under its parent, so a node a third-party script adds or swaps
516
+ * elsewhere cannot shift it. Format: protocol-locator-paths-format.ts.
517
+ */
518
+ const PROTOCOL_LOCATOR_PATHS_ATTRIBUTE = "data-markless-paths";
519
+ //#endregion
520
+ //#region ../serializer/src/protocol-event-host.ts
521
+ /**
522
+ * The attribute the server writes on each served element that hosts an event
523
+ * record. The inline boot reads it from the event target up, so it finds a
524
+ * press's handler and sync policy without parsing a payload or knowing the
525
+ * element's position. Grammar: entries joined by `;`, each
526
+ * `name[:ref][!policy]`, where `ref` is the record's index in its region's event
527
+ * list (or `-` for an event an external delegate owns) and `policy` is `p`, `s`,
528
+ * `ps` or an index into the container's sync-policy table.
529
+ */
530
+ const PROTOCOL_EVENT_HOST_ATTRIBUTE = "m:on";
531
+ //#endregion
532
+ //#region ../serializer/src/protocol-page-markers.ts
533
+ const PROTOCOL_CONTAINER_START_COMMENT = "markless:page-start";
534
+ const PROTOCOL_CONTAINER_END_COMMENT = "markless:page-end";
535
+ const PROTOCOL_BLOCK_START_COMMENT = /^markless:(?:branch|arm-branch|async):/;
536
+ //#endregion
537
+ //#region ../serializer/src/protocol-stream-open.ts
538
+ const PROTOCOL_STREAM_OPEN_PROPERTY = "__mStreamOpen";
539
+ //#endregion
540
+ //#region ../web/src/inline/defer.ts
541
+ const PROTOCOL_EVENT_HOST_SELECTOR = PROTOCOL_EVENT_HOST_ATTRIBUTE.replace(":", "\\:");
542
+ /**
543
+ * The one startup helper deferred triggers share. Serialized whole into a served
544
+ * page that has one; a client mount and the runtime call it directly. Hosts are
545
+ * the elements whose event host attribute (`hostSelector`, escaped for a CSS
546
+ * attribute selector) names the lane's event with a record;
547
+ * `ownsRoot` adds the container itself, which hands records the runtime owns
548
+ * (arms, rows) to the runtime.
549
+ */
550
+ function createMarklessDefer(loadModule, pageStart, pageEnd, pathsAttribute, hostSelector, streamOpenProperty) {
551
+ const scope = globalThis;
552
+ const clockOf = (root) => root.__mClock || {
553
+ frame: (run) => requestAnimationFrame(run),
554
+ idle: (run) => scope.scheduler?.postTask ? scope.scheduler.postTask(run, { priority: "background" }) : typeof requestIdleCallback === "function" ? requestIdleCallback(run, { timeout: 2e3 }) : setTimeout(run, 200)
555
+ };
556
+ const census = (root) => {
557
+ const live = [root];
558
+ const walker = document.createTreeWalker(root, 129);
559
+ for (let next = walker.nextNode(); next; next = walker.nextNode()) if (next.nodeType !== 8) live.push(next);
560
+ else if (next.data === pageStart) live.length = 1;
561
+ else if (next.data === pageEnd) break;
562
+ const paths = pathsAttribute && root.getAttribute?.(pathsAttribute);
563
+ const order = paths && paths.split("|")[3];
564
+ let signature = 0;
565
+ if (order) for (const element of live.slice(1)) {
566
+ const name = element.localName ?? element.tagName ?? "";
567
+ signature = signature * 31 + name.length * 32 + (name.charCodeAt(0) | 32) | 0;
568
+ }
569
+ if (paths && (parseInt(paths) !== live.length || order && order !== (signature >>> 0).toString(36))) root.__marklessShifted = 1;
570
+ return live;
571
+ };
572
+ const idle = (root, run) => {
573
+ const clock = clockOf(root);
574
+ const next = () => clock.idle(() => root.__marklessArmRegistering?.size ? next() : run());
575
+ const loaded = () => clock.frame(() => scope.__mArm?.idle ? scope.__mArm.idle(next) : next());
576
+ const open = Reflect.get(document, streamOpenProperty);
577
+ if (open) open.then(loaded);
578
+ else if (document.readyState === "complete") loaded();
579
+ else addEventListener("load", loaded, { once: true });
580
+ };
581
+ const trigger = (target, lane, ownsRoot, eventName) => {
582
+ const root = target;
583
+ const url = document.currentScript?.getAttribute("data-markless-resume-module");
584
+ if (!root || !url) return;
585
+ const life = root.__mL ||= {};
586
+ const fired = root.__mFired ||= /* @__PURE__ */ new WeakSet();
587
+ const claimed = /* @__PURE__ */ new WeakSet();
588
+ let pending = 0;
589
+ const claim = (host) => {
590
+ if (fired.has(host) || claimed.has(host) || root.__mL !== life) return;
591
+ const input = {
592
+ root,
593
+ event: {
594
+ type: eventName,
595
+ target: host,
596
+ bubbles: false
597
+ },
598
+ element: host
599
+ };
600
+ const queue = root.__marklessDispatch;
601
+ if (!queue && root.__marklessDelegatedDispatch === true) return idle(root, () => claim(host));
602
+ claimed.add(host);
603
+ if (lane !== "visible") fired.add(host);
604
+ root.__marklessCensus ||= census(root);
605
+ root.__marklessDelegatedDispatch ||= eventName;
606
+ pending++;
607
+ (queue ? Promise.resolve(queue(input)) : (root.__mResume ||= loadModule(url)).then((module) => root.__mL === life && module.resumeContainerEvent(input))).then(() => {
608
+ if (root.__asyncResumeRuntimeStarted) return;
609
+ fired.add(host);
610
+ if (!--pending && root.__marklessDelegatedDispatch === eventName) root.__marklessDelegatedDispatch = void 0;
611
+ });
612
+ };
613
+ const hosts = ownsRoot ? [root] : [];
614
+ hosts.push(...root.querySelectorAll(`[${hostSelector}^="${eventName}:"],[${hostSelector}*=";${eventName}:"]`));
615
+ if (lane === "idle") return idle(root, () => hosts.forEach(claim));
616
+ const observer = new IntersectionObserver((entries) => {
617
+ if (root.__mL !== life) return observer.disconnect();
618
+ for (const entry of entries) if (entry.isIntersecting) {
619
+ observer.unobserve(entry.target);
620
+ claim(entry.target);
621
+ }
622
+ });
623
+ for (const host of hosts) observer.observe(host);
624
+ };
625
+ return Object.assign(trigger, { idle });
626
+ }
627
+ const INLINE_DEFER_LOADER_SOURCE = "(url) => import(/* @vite-ignore */ url)";
628
+ /** An expression that installs the helper once per document and evaluates to it; a build passes the factory minified. */
629
+ function inlineDeferSource(factory = createMarklessDefer.toString()) {
630
+ return `(globalThis.__mDefer||=(${factory})(${INLINE_DEFER_LOADER_SOURCE},${JSON.stringify(PROTOCOL_CONTAINER_START_COMMENT)},${JSON.stringify(PROTOCOL_CONTAINER_END_COMMENT)},${JSON.stringify(PROTOCOL_LOCATOR_PATHS_ATTRIBUTE)},${JSON.stringify(PROTOCOL_EVENT_HOST_SELECTOR)},${JSON.stringify(PROTOCOL_STREAM_OPEN_PROPERTY)}))`;
631
+ }
632
+ /** One lane's registration, appended only to a served page whose records name that lane's event. */
633
+ function createInlineDeferTriggerSource(lane, ownsRoot) {
634
+ const eventName = lane === "idle" ? PROTOCOL_IDLE_EVENT_NAME$1 : PROTOCOL_VISIBLE_EVENT_NAME;
635
+ return `;${inlineDeferSource()}(document.currentScript?.closest('[data-async-container]'),${JSON.stringify(lane)},${ownsRoot ? 1 : 0},${JSON.stringify(eventName)});`;
636
+ }
637
+ //#endregion
638
+ //#region src/inline-resumer.ts
639
+ const compiledSources = /* @__PURE__ */ new Map();
640
+ function compileInlineResumerSources(options) {
641
+ const cacheKey = `${options.debug ? "debug" : "production"}:${options.executionLog}`;
642
+ let compiled = compiledSources.get(cacheKey);
643
+ if (!compiled) {
644
+ compiled = compileInlineResumerSourceVariants(options);
645
+ compiledSources.set(cacheKey, compiled);
646
+ }
647
+ return compiled;
648
+ }
649
+ async function compileInlineResumerSourceVariants(options) {
650
+ const shared = {
651
+ debug: options.debug,
652
+ executionLog: options.executionLog
653
+ };
654
+ const [event, syncPolicy, graphSyncPolicyOwner, graphSyncPolicyConsumer] = await Promise.all([
655
+ compileInlineResumerSource({
656
+ ...shared,
657
+ graphSyncPolicy: false,
658
+ sharedGraphPolicy: false,
659
+ syncPolicy: false
660
+ }),
661
+ compileInlineResumerSource({
662
+ ...shared,
663
+ graphSyncPolicy: false,
664
+ sharedGraphPolicy: false,
665
+ syncPolicy: true
666
+ }),
667
+ compileInlineResumerSource({
668
+ ...shared,
669
+ graphSyncPolicy: true,
670
+ sharedGraphPolicy: true,
671
+ syncPolicy: true
672
+ }),
673
+ compileInlineResumerSource({
674
+ ...shared,
675
+ graphSyncPolicy: true,
676
+ sharedGraphPolicy: false,
677
+ syncPolicy: true
678
+ })
679
+ ]);
680
+ const defer = await compileDeferFactorySource();
681
+ return {
682
+ ...shared,
683
+ event,
684
+ syncPolicy,
685
+ graphSyncPolicyOwner,
686
+ graphSyncPolicyConsumer,
687
+ defer
688
+ };
689
+ }
690
+ async function compileDeferFactorySource() {
691
+ const binding = "var __marklessDeferFactory=";
692
+ const transformed = transformSync("markless-defer.js", `${binding}${createMarklessDefer.toString()};`, {
693
+ lang: "js",
694
+ sourceType: "script",
695
+ target: "es2020"
696
+ });
697
+ assertOxcResult("transform", transformed.errors);
698
+ const minified = minifySync("markless-defer.js", transformed.code, {
699
+ compress: true,
700
+ mangle: { toplevel: false },
701
+ module: false
702
+ });
703
+ assertOxcResult("minify", minified.errors);
704
+ const code = minified.code.trim().replace(/;$/, "");
705
+ if (!code.startsWith(binding)) throw new Error("MARKLESS_INLINE_DEFER_FACTORY_UNWRAPPABLE");
706
+ return code.slice(27);
707
+ }
708
+ async function compileInlineResumerSource(options) {
709
+ const source = createInlineResumerSource({
710
+ ...options,
711
+ ...options.debug ? {
712
+ debugBootstrapSource: __marklessDebugBootstrapSource(),
713
+ debugRegistrationSource: createInlineResumerDebugRegistrationSource()
714
+ } : {}
715
+ });
716
+ const transformed = transformSync("markless-inline-resumer.js", source, {
717
+ lang: "js",
718
+ sourceType: "script",
719
+ target: "es2020"
720
+ });
721
+ assertOxcResult("transform", transformed.errors);
722
+ const minified = minifySync("markless-inline-resumer.js", transformed.code, {
723
+ compress: true,
724
+ mangle: { toplevel: true },
725
+ module: false
726
+ });
727
+ assertOxcResult("minify", minified.errors);
728
+ const code = minified.code.trim();
729
+ if (!code.includes(INLINE_RESUMER_PAGE_TOKEN)) throw new Error("MARKLESS_INLINE_RESUMER_PAGE_TOKEN_FOLDED");
730
+ return code;
731
+ }
732
+ function assertOxcResult(phase, errors) {
733
+ if (errors.length === 0) return;
734
+ throw new Error(`MARKLESS_INLINE_RESUMER_${phase.toUpperCase()}_FAILED:\n${errors.map((error) => error.message).join("\n")}`);
735
+ }
736
+ const compiledPrerenderSources = /* @__PURE__ */ new Map();
737
+ function compilePrerenderInlineResumerSources() {
738
+ let compiled = compiledPrerenderSources.get("production");
739
+ if (!compiled) {
740
+ compiled = compilePrerenderVariants();
741
+ compiledPrerenderSources.set("production", compiled);
742
+ }
743
+ return compiled;
744
+ }
745
+ async function compilePrerenderVariants() {
746
+ const [prerender, prerenderSelfWake, prerenderSettle] = await Promise.all([
747
+ compilePrerenderInlineResumerSource(false),
748
+ compilePrerenderInlineResumerSource(true),
749
+ compilePrerenderInlineResumerSource("settle")
750
+ ]);
751
+ return {
752
+ prerender,
753
+ prerenderSelfWake,
754
+ prerenderSettle
755
+ };
756
+ }
757
+ async function compilePrerenderInlineResumerSource(selfWake) {
758
+ const source = parameterizedPrerenderInlineResumerSource(selfWake);
759
+ const transformed = transformSync("markless-prerender-inline-resumer.js", source, {
760
+ lang: "js",
761
+ sourceType: "script",
762
+ target: "es2020"
763
+ });
764
+ assertOxcResult("transform", transformed.errors);
765
+ const minified = minifySync("markless-prerender-inline-resumer.js", transformed.code, {
766
+ compress: true,
767
+ mangle: { toplevel: true },
768
+ module: false
769
+ });
770
+ assertOxcResult("minify", minified.errors);
771
+ const code = minified.code.trim();
772
+ if (code.split(PRERENDER_INLINE_EVENT_NAMES_TOKEN).length !== 2) throw new Error("MARKLESS_PRERENDER_INLINE_RESUMER_EVENT_NAMES_TOKEN_LOST");
773
+ return code;
774
+ }
775
+ function parameterizedPrerenderInlineResumerSource(selfWake) {
776
+ const placeholder = [PRERENDER_INLINE_EVENT_NAMES_TOKEN];
777
+ const literal = JSON.stringify(placeholder);
778
+ const plain = selfWake === "settle" ? createPrerenderSettleInlineResumerSource(placeholder, void 0) : createPrerenderInlineResumerSource(placeholder, void 0);
779
+ if (plain.split(literal).length !== 2) throw new Error("MARKLESS_PRERENDER_INLINE_RESUMER_EVENT_NAMES_UNPLACEABLE");
780
+ return `${plain.replace(literal, PRERENDER_INLINE_EVENT_NAMES_TOKEN)}${selfWake === true ? createInlineResumerSelfWakeSource(void 0) : ""}`;
781
+ }
782
+ //#endregion
783
+ //#region src/shared-inline-sources.ts
784
+ const SHARED_INLINE_RESUMER_SOURCES = "inlineResumerSources";
785
+ const SHARED_PRERENDER_BOOT = "prerenderBoot";
786
+ const PREFIX = "virtual:markless:inline-sources-";
787
+ const EXECUTION_LOG_MODES = /* @__PURE__ */ new Set([
788
+ "auto",
789
+ "never",
790
+ "always"
791
+ ]);
792
+ function sharedInlineSourcesModuleId(options) {
793
+ return `${PREFIX}${options.debug ? "debug" : "production"}-${options.executionLog}`;
794
+ }
795
+ function sharedInlineSourcesOptions(id) {
796
+ const bare = id.startsWith("\0") ? id.slice(1) : id;
797
+ if (!bare.startsWith(PREFIX)) return null;
798
+ const [flavour, executionLog] = bare.slice(32).split("-");
799
+ if (flavour !== "debug" && flavour !== "production" || !EXECUTION_LOG_MODES.has(executionLog)) return null;
800
+ return {
801
+ debug: flavour === "debug",
802
+ executionLog
803
+ };
804
+ }
805
+ function isSharedInlineSourcesModuleId(id) {
806
+ return sharedInlineSourcesOptions(id) !== null;
807
+ }
808
+ async function sharedInlineSourcesModuleSource(id) {
809
+ const options = sharedInlineSourcesOptions(id);
810
+ if (!options) return null;
811
+ const [sources, prerender] = await Promise.all([compileInlineResumerSources(options), compilePrerenderInlineResumerSources()]);
812
+ return [`export const ${SHARED_INLINE_RESUMER_SOURCES} = ${JSON.stringify(sources)};`, `export const ${SHARED_PRERENDER_BOOT} = ${JSON.stringify(prerender)};`].join("\n");
813
+ }
814
+ //#endregion
418
815
  //#region src/scalar-plan-loader.ts
419
816
  function emitScalarPlanLoader(actions, routes) {
420
817
  const ordered = routes.filter((route) => route.prefix.length > 0).toSorted((left, right) => right.prefix.length - left.prefix.length);
@@ -482,9 +879,9 @@ function emitSymbolRouteTable(input) {
482
879
  function boundEntry(boundSymbols, keyLists) {
483
880
  const entries = Object.entries(boundSymbols);
484
881
  const [firstKey, firstId] = entries[0];
485
- const head = `bound:${encodeURIComponent(firstKey)}:`;
882
+ const head = `${protocolBoundSymbolPrefix(firstKey)}:`;
486
883
  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);
884
+ if (suffix === void 0 || entries.some(([key, id]) => protocolBoundSymbolPrefix(key) !== `bound:${encodeURIComponent(key)}` || id !== `${protocolBoundSymbolPrefix(key)}:${suffix}`)) return JSON.stringify(boundSymbols);
488
885
  const keys = JSON.stringify(entries.map(([key]) => key));
489
886
  let index = keyLists.indexOf(keys);
490
887
  if (index < 0) index = keyLists.push(keys) - 1;
@@ -503,9 +900,6 @@ const SYMBOL_VIRTUAL_PREFIX = `${MARKLESS_VIRTUAL_PREFIX}symbol:`;
503
900
  function symbolVirtualModuleId(filename, symbolId) {
504
901
  return `${SYMBOL_VIRTUAL_PREFIX}${encodeURIComponent(filename)}:${encodeURIComponent(symbolId)}`;
505
902
  }
506
- function symbolEntryVirtualModuleId(filename, symbolId) {
507
- return `${symbolVirtualModuleId(filename, symbolId)}:entry`;
508
- }
509
903
  function encodedSymbolSource(filename) {
510
904
  return encodeURIComponent(filename);
511
905
  }
@@ -625,8 +1019,9 @@ function emitSourceModule(input) {
625
1019
  const emitsSsrBody = !!input.publicSsrModuleSource && !(input.environment === "client" && (symbolsOnly || !input.prerenderRecords && !input.dev));
626
1020
  const csrRootName = input.environment !== "server" && !symbolsOnly && !input.prerenderRecords && input.publicRenderRootExportName ? csrRootLocalName(input.publicRenderRootExportName) : null;
627
1021
  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 ${singleQuoted(input.renderDataId)};` : `import { marklessPrerenderData } from ${singleQuoted(input.renderDataId)};` : `import { marklessRenderData } from ${singleQuoted(input.renderDataId)};`,
1022
+ !input.publicSsrModuleSource && !input.publicRenderModuleSource || symbolsOnly || !input.renderDataId || input.environment === "client" && !input.publicRenderModuleSource && !input.prerenderRecords && !input.dev && !canonicalRenderData ? "" : canonicalRenderData ? emitsSsrBody ? `import { marklessPrerenderData, marklessRenderData } from ${singleQuoted(input.renderDataId)};` : input.lazyFullRenderDataId ? "" : `import { marklessPrerenderData } from ${singleQuoted(input.renderDataId)};` : `import { marklessRenderData } from ${singleQuoted(input.renderDataId)};`,
629
1023
  symbolsOnly ? "" : `import { state as payloadState, view as payloadView, runtimeDemandMap as payloadRuntimeDemandMap } from ${singleQuoted(input.payloadId)};`,
1024
+ sharedInlineSources(input) ? `import { ${SHARED_INLINE_RESUMER_SOURCES} as marklessInlineResumerSources, ${SHARED_PRERENDER_BOOT} as marklessPrerenderBoot } from ${singleQuoted(input.sharedInlineSourcesModuleId)};` : null,
630
1025
  input.environment === "client" && input.directCsr === true && input.hasComputedState === true ? ["import { installMarklessDerivedReconcile } from '@markless/web/fns/reconcile-plane';", "installMarklessDerivedReconcile();"].join("\n") : null,
631
1026
  input.environment === "client" && input.hasComputedState === true ? emitRosterResumeLoaderInstall() : null,
632
1027
  input.environment === "client" && input.hasOverlayMarks === true ? emitOverlayLoaderInstall() : null,
@@ -662,6 +1057,7 @@ function emitSourceModule(input) {
662
1057
  storageSeeds: input.storageSeeds,
663
1058
  inlineResumerSources: input.inlineResumerSources,
664
1059
  prerenderBoot: input.prerenderBoot,
1060
+ sharedInlineSources: sharedInlineSources(input),
665
1061
  resumeModuleUrl: input.resumeModuleUrl,
666
1062
  prerenderWakeModuleUrl: input.prerenderWakeModuleUrl,
667
1063
  rootExportName: input.publicRenderRootExportName,
@@ -670,6 +1066,7 @@ function emitSourceModule(input) {
670
1066
  ssrExportName: input.publicRenderSsrExportName,
671
1067
  ssrComponents: input.publicRenderSsrComponentExports ?? [],
672
1068
  canonicalRenderData,
1069
+ ...canonicalRenderData && !emitsSsrBody && input.lazyFullRenderDataId ? { lazyFullRenderDataId: input.lazyFullRenderDataId } : {},
673
1070
  prerenderRecords: input.prerenderRecords,
674
1071
  dev: input.dev
675
1072
  }),
@@ -796,10 +1193,16 @@ function componentRowLoader(input) {
796
1193
  if (input.linkedRowComponents || demandsKeyedRepeatModule(input.runtimeDemandMap, ROW_COMPONENT_MINT_RUNTIME_MODULE_ID)) return emitRowComponentMintLoaderInstall();
797
1194
  return input.linkedRowSlotReaders || demandsKeyedRepeatModule(input.runtimeDemandMap, ROW_SLOT_MINT_RUNTIME_MODULE_ID) ? emitRowSlotMintLoaderInstall() : void 0;
798
1195
  }
1196
+ function rowBranchesLoader(runtimeDemandMap, linked = false) {
1197
+ return linked || demandsKeyedRepeatModule(runtimeDemandMap, ROW_BRANCH_MINT_RUNTIME_MODULE_ID) ? "globalThis.__marklessRowBranches ??= () => import('@markless/web/fns/row-branch-mint').then((branches) => branches.marklessRowBranches());" : null;
1198
+ }
799
1199
  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;
1200
+ const lines = [
1201
+ demandsRowComponentMint(input.runtimeDemandMap) ? emitRowComponentMintLoaderInstall() : componentRowLoader(input) ?? (input.linkedRowTemplates || demandsRowMint(input.runtimeDemandMap) ? emitRowMintLoaderInstall() : null),
1202
+ nestedRepeatsLoader(input.runtimeDemandMap, input.linkedNestedRepeats),
1203
+ rowBranchesLoader(input.runtimeDemandMap, input.linkedRowBranches)
1204
+ ].filter((line) => line !== null);
1205
+ return lines.length > 0 ? lines.join("\n") : null;
803
1206
  }
804
1207
  function emitRowSlotMintLoaderInstall() {
805
1208
  return ["if (!globalThis.__marklessRowMint?.components) globalThis.__marklessRowMint = (...input) =>", " import('@markless/web/fns/row-slot-mint').then((mint) => mint.marklessRowSlotMint(...input));"].join("\n");
@@ -819,6 +1222,7 @@ const ROW_MINT_RUNTIME_MODULE_ID = "web/fns/row-mint";
819
1222
  const NESTED_REPEATS_RUNTIME_MODULE_ID = "web/fns/nested-repeats";
820
1223
  const ROW_COMPONENT_MINT_RUNTIME_MODULE_ID = "web/fns/row-component-mint";
821
1224
  const ROW_SLOT_MINT_RUNTIME_MODULE_ID = "web/fns/row-slot-mint";
1225
+ const ROW_BRANCH_MINT_RUNTIME_MODULE_ID = "web/fns/row-branch-mint";
822
1226
  /** True when the compiler recorded an `overlay` mark for this module. */
823
1227
  function demandsOverlay(runtimeDemandMap) {
824
1228
  const records = runtimeDemandMap?.payloadRecords;
@@ -833,7 +1237,7 @@ function emitResumeModule(input) {
833
1237
  runtimeDemandMap: input.servedScalarPlans
834
1238
  } : input);
835
1239
  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));
1240
+ 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.servedRenderDataId ?? 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
1241
  const closureImports = [
838
1242
  "marklessClosureRouted",
839
1243
  "marklessPrimeClosure",
@@ -855,6 +1259,7 @@ function emitResumeModule(input) {
855
1259
  input.hasIdleEvents ? emitIdleTriggerInstall() : null,
856
1260
  componentRowLoader(input) ?? (input.linkedRowTemplates || demandsRowMint(input.runtimeDemandMap) ? emitRowMintLoaderInstall() : null),
857
1261
  nestedRepeatsLoader(input.runtimeDemandMap, input.linkedNestedRepeats),
1262
+ rowBranchesLoader(input.runtimeDemandMap, input.linkedRowBranches),
858
1263
  scalarSpecializations.length > 0 ? [
859
1264
  "import { marklessDecodeScalarCell, marklessReadScalarCell, marklessScalarSpecializedError } from '@markless/web/fns/scalar-specialized';",
860
1265
  resumeContainerEvent.includes("marklessScalarServedOwner") ? `import { marklessScalarLocate, marklessScalarServedOwner, marklessScalarServedPrime${resumeContainerEvent.includes("marklessScalarServedRecord") ? ", marklessScalarServedRecord" : ""} } from '@markless/web/fns/scalar-served';` : "",
@@ -863,6 +1268,7 @@ function emitResumeModule(input) {
863
1268
  "import { marklessUpdateText } from '@markless/web/fns/update-text';"
864
1269
  ].join("\n") : "",
865
1270
  scalarSpecializations.length > 0 || stagedPrerender ? "import { marklessFindElementAtDomOrderIndex } from '@markless/web/fns/dom-order';" : "",
1271
+ input.prerenderTriggerGroups?.some((group) => group.hostPath) ? "import { marklessElementAt } from '@markless/web/fns/element-address';" : null,
866
1272
  "",
867
1273
  input.executionLog === "never" ? "" : emitExecutionLogLoader(),
868
1274
  input.installResumeSummary && input.executionLog !== "never" ? "if (globalThis.__mxLog) globalThis.__mxLoadLog().then(log => log.installMarklessExecutionLog());" : null,
@@ -891,21 +1297,21 @@ function emitQueuedResumeContainerEvent(source, { censusRepair = true } = {}) {
891
1297
  " if (input.eventIndex >= 0) input = { ...input, eventRecord: (root.__mE ||= JSON.parse(root.querySelector('script[type=\"markless/view\"]').textContent).events)[input.eventIndex] };",
892
1298
  censusRepair ? " if (root.__marklessShifted) return import('@markless/web/fns/served-census-repair').then((census) => (census.marklessRepairCensus(root), resumeContainerEvent(input)));" : "",
893
1299
  " if (!root.__marklessDispatch) {",
894
- " let handler = marklessResumeContainerEvent, tail = Promise.resolve(), done = tail, lastEvent = null, lastEventTime = undefined, seen = new WeakMap();",
1300
+ " let handler = marklessResumeContainerEvent, tail = Promise.resolve(), done = tail, lastEvent = null, lastEventTime = undefined, seen = new WeakMap(), life = root.__mL;",
895
1301
  " root.__marklessRegisterDispatch = next => {",
896
1302
  " const fallback = handler;",
897
1303
  " handler = input => next(input, fallback);",
898
1304
  " };",
899
1305
  " root.__marklessDispatch = next => {",
900
1306
  " const event = next.event, eventTime = event?.timeStamp;",
901
- " if (event && next.eventRecord && next.element) event.__marklessPressHost ??= next.element;",
1307
+ " if (event && next.eventRecord && next.element) event.__marklessPressPath ??= [next.element];",
902
1308
  " if ((event === lastEvent && eventTime === lastEventTime) || (seen.has(event) && seen.get(event) === eventTime)) return done;",
903
1309
  " if (Object(event) === event) seen.set(event, eventTime);",
904
1310
  " lastEvent = event;",
905
1311
  " lastEventTime = eventTime;",
906
1312
  " let release;",
907
1313
  " const started = new Promise(resolve => release = resolve);",
908
- " const run = () => (root.__marklessReleaseDispatch = release, handler(next));",
1314
+ " const run = () => root.__mL === life ? (root.__marklessReleaseDispatch = release, handler(next)) : release();",
909
1315
  " done = tail.then(run, run);",
910
1316
  " done.then(release, release);",
911
1317
  " tail = started;",
@@ -924,7 +1330,7 @@ function emitLazySymbolRouteFunction(routes, functionName, fallbackName = "loadS
924
1330
  return emitSymbolRouteTable({
925
1331
  routes: [...routes].sort((left, right) => right.prefix.length - left.prefix.length).map((route) => "importSource" in route ? {
926
1332
  ...route,
927
- importSource: symbolRouteImportSource$1(route.importSource, includeScalarActionPlans)
1333
+ importSource: symbolRouteImportSource(route.importSource, includeScalarActionPlans)
928
1334
  } : route),
929
1335
  functionName,
930
1336
  fallbackName,
@@ -958,21 +1364,29 @@ function emitClosurePlanRoute(routes, functionName, actions) {
958
1364
  `function ${functionName}(symbolId) {`,
959
1365
  ...ordered.flatMap((route) => [
960
1366
  ` if (symbolId.startsWith(${JSON.stringify(route.prefix)})) {`,
961
- "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};`,
1367
+ "importSource" in route ? ` return import(${JSON.stringify(symbolRouteImportSource(route.importSource))}).then((mod) => mod.loadClosureActionPlan?.(symbolId.slice(${route.prefix.length})));` : route.prefix.length > 0 ? ` return ${functionName}(symbolId.slice(${route.prefix.length}));` : ` return ${localLookup};`,
962
1368
  " }"
963
1369
  ]),
964
1370
  ` return ${localLookup};`,
965
1371
  "}"
966
1372
  ].filter(Boolean).join("\n");
967
1373
  }
968
- function symbolRouteImportSource$1(importSource, includeScalarActionPlans = false) {
1374
+ function symbolRouteImportSource(importSource, includeScalarActionPlans = false) {
969
1375
  if (includeScalarActionPlans) return scalarPlanSourceReference(importSource);
970
1376
  return importSource.includes("?") ? `${importSource}&markless-symbols` : `${importSource}?markless-symbols`;
971
1377
  }
1378
+ function sharedInlineSources(input) {
1379
+ return input.environment === "server" && !!input.sharedInlineSourcesModuleId && !!input.inlineResumerSources && !!input.prerenderBoot;
1380
+ }
1381
+ function sharedPrerenderBootSource(boot) {
1382
+ if (!boot.settle) return "marklessPrerenderBoot";
1383
+ const { boot: _boot, ...settle } = boot.settle;
1384
+ return `{ ...marklessPrerenderBoot, settle: { ...${JSON.stringify(settle)}, boot: marklessPrerenderBoot.prerenderSettle } }`;
1385
+ }
972
1386
  function emitCompiledAppDefault(input) {
973
1387
  const renderCsrEntry = input.csrRootName ? [` renderCsr: ${input.csrRootName},`] : [];
974
1388
  const symbolLoaderEntry = input.environment !== "server" && input.rootExportName === null ? [`\tloadSymbol: ${input.symbolLoaderName},`] : input.prerenderRecords === true ? [`\tloadSymbol: ${input.symbolLoaderName},`] : [];
975
- const renderDataEntry = input.canonicalRenderData ? [" renderData: marklessPrerenderData,"] : [];
1389
+ const renderDataEntry = !input.canonicalRenderData ? [] : input.lazyFullRenderDataId ? [`\trenderData: () => import(${singleQuoted(input.lazyFullRenderDataId)}).then((data) => data.marklessPrerenderData),`] : [" renderData: marklessPrerenderData,"];
976
1390
  const servesSsr = !!input.ssrExportName && (input.environment !== "client" || input.prerenderRecords || input.dev);
977
1391
  const renderSsrEntry = servesSsr ? [
978
1392
  " renderSsr(props, marklessRenderContext) {",
@@ -982,8 +1396,8 @@ function emitCompiledAppDefault(input) {
982
1396
  const renderSsrComponentsEntry = servesSsr && input.ssrComponents.length > 0 ? [` renderSsrComponents: { ${input.ssrComponents.map((component) => `${JSON.stringify(component.exportName)}: { renderSsr: ${component.ssrFunctionName} }`).join(", ")} },`] : [];
983
1397
  const resumeModuleEntry = input.resumeModuleUrl && input.environment !== "client" ? [` resumeModuleUrl: ${JSON.stringify(input.resumeModuleUrl)},`] : [];
984
1398
  const prerenderWakeModuleEntry = input.prerenderWakeModuleUrl && input.environment !== "client" ? [`\tprerenderWakeModuleUrl: ${JSON.stringify(input.prerenderWakeModuleUrl)},`] : [];
985
- const inlineResumerEntry = input.inlineResumerSources && input.environment !== "client" ? [`\tinlineResumerSources: ${JSON.stringify(input.inlineResumerSources)},`] : [];
986
- const prerenderBootEntry = input.prerenderBoot && input.environment !== "client" ? [`\tprerenderBoot: ${JSON.stringify(input.prerenderBoot)},`] : [];
1399
+ const inlineResumerEntry = input.inlineResumerSources && input.environment !== "client" ? [input.sharedInlineSources ? " inlineResumerSources: marklessInlineResumerSources," : `\tinlineResumerSources: ${JSON.stringify(input.inlineResumerSources)},`] : [];
1400
+ const prerenderBootEntry = input.prerenderBoot && input.environment !== "client" ? [input.sharedInlineSources ? `\tprerenderBoot: ${sharedPrerenderBootSource(input.prerenderBoot)},` : `\tprerenderBoot: ${JSON.stringify(input.prerenderBoot)},`] : [];
987
1401
  const headInjectionEntry = input.headInjections?.length && input.environment !== "client" ? [` headInjections: ${JSON.stringify(input.headInjections)},`] : [];
988
1402
  const storageSeedEntry = input.storageSeeds?.length && input.environment !== "client" ? [`\tstorageSeeds: ${JSON.stringify(input.storageSeeds)},`] : [];
989
1403
  const modulePreloadEntry = input.resumeModuleUrl && input.environment === "server" ? [` modulePreloads: [{ href: ${JSON.stringify(input.resumeModuleUrl)}, fetchPriority: "high" }],`] : [];
@@ -1062,21 +1476,32 @@ function emitComponentExports(input) {
1062
1476
  });
1063
1477
  }
1064
1478
  function emitResumeContainerEvent(loadSymbolName, needsFullResume, storageFreePayload, leanMode, scalarSpecializations, runtimeDemandMap, executionLogEnabled, prerenderDataId, stagedPrerender = false, componentRowRenderDataId, servedOnly = false, routedClosures = false, streamsArms = false) {
1065
- const armsOpen = (indent) => streamsArms ? [`${indent}const marklessArms = (await import('@markless/web/fns/streamed-arms')).marklessStreamedArms(handoff.root, ${loadSymbolName});`] : [];
1479
+ const lifeOpen = (indent) => `${indent}const marklessLife = handoff.root.__mL;`;
1480
+ const lifeCheck = (indent) => `${indent}if (handoff.root.__mL !== marklessLife) return;`;
1481
+ const armsOpen = (indent) => streamsArms ? [
1482
+ `${indent}const marklessArmsModule = await import('@markless/web/fns/streamed-arms');`,
1483
+ lifeCheck(indent),
1484
+ `${indent}const marklessArms = marklessArmsModule.marklessStreamedArms(handoff.root, ${loadSymbolName});`
1485
+ ] : [];
1066
1486
  const armsStarted = (indent) => streamsArms ? [`${indent}marklessArms.started();`] : [];
1067
1487
  const wakeLoadSymbol = streamsArms ? "marklessArms.loadSymbol" : loadSymbolName;
1068
1488
  const resumeEntry = storageFreePayload ? STORAGE_FREE_RESUME_ENTRY_SPECIFIER : RESUME_ENTRY_SPECIFIER;
1069
1489
  const renderDataEntry = (indent, expression) => componentRowRenderDataId ? [`${indent}renderData: () => ${expression},`] : [];
1070
1490
  const fullResumeHandoff = stagedPrerender && prerenderDataId ? [
1071
1491
  "async function marklessFullResumeHandoff(handoff) {",
1492
+ lifeOpen(" "),
1072
1493
  " handoff.root.__asyncResumeRuntimeStarted = true;",
1073
1494
  " const group = await marklessLoadPrerenderTriggerGroup(handoff);",
1074
1495
  " const { mergePrerenderPayloadRecords, resumePrerenderTriggerGroup } = await import('@markless/web/fns/prerender-trigger-resume');",
1496
+ lifeCheck(" "),
1075
1497
  " if (!group) {",
1076
1498
  " const { derivePrerenderResumeRecords, renderPrerenderBoundary, resumeFromPrerenderRecords } = await import('@markless/web/fns/prerender-resume');",
1499
+ lifeCheck(" "),
1077
1500
  " handoff.root.__marklessFullResumeRuntime ??= (async () => {",
1078
1501
  " const marklessPrerenderData = await marklessLoadPrerenderData();",
1079
- `\t\t\tconst fallbackRecords = mergePrerenderPayloadRecords(await derivePrerenderResumeRecords(marklessPrerenderData, ${loadSymbolName}), handoff.root);`,
1502
+ `\t\t\tconst derivedRecords = await derivePrerenderResumeRecords(marklessPrerenderData, ${loadSymbolName});`,
1503
+ lifeCheck(" "),
1504
+ " const fallbackRecords = mergePrerenderPayloadRecords(derivedRecords, handoff.root);",
1080
1505
  " return (await resumeFromPrerenderRecords({",
1081
1506
  " ...fallbackRecords,",
1082
1507
  " root: handoff.root,",
@@ -1086,6 +1511,7 @@ function emitResumeContainerEvent(loadSymbolName, needsFullResume, storageFreePa
1086
1511
  " })).runtime;",
1087
1512
  " })();",
1088
1513
  " const marklessFullRuntime = await handoff.root.__marklessFullResumeRuntime;",
1514
+ " if (!marklessFullRuntime) return;",
1089
1515
  " await marklessFullRuntime.dispatch(handoff.event, { syncPolicyAlreadyApplied: handoff.syncPolicyAlreadyApplied === true, ignoreUnmatched: true });",
1090
1516
  " return;",
1091
1517
  " }",
@@ -1098,11 +1524,13 @@ function emitResumeContainerEvent(loadSymbolName, needsFullResume, storageFreePa
1098
1524
  "}"
1099
1525
  ].join("\n") : prerenderDataId ? [
1100
1526
  "async function marklessFullResumeHandoff(handoff) {",
1527
+ lifeOpen(" "),
1101
1528
  " handoff.root.__marklessLinkedRenderDataBoot = true;",
1102
1529
  " handoff.root.__asyncResumeRuntimeStarted = true;",
1103
1530
  " const runtime = await (handoff.root.__marklessFullResumeRuntime ??= (async () => {",
1104
1531
  " const { derivePrerenderResumeRecords, mergePrerenderPayloadRecords, renderPrerenderBoundary, resumeFromPrerenderRecords } = await import('@markless/web/fns/prerender-resume');",
1105
1532
  `\t\tconst records = await derivePrerenderResumeRecords(marklessPrerenderData, ${loadSymbolName});`,
1533
+ lifeCheck(" "),
1106
1534
  " const mergedRecords = mergePrerenderPayloadRecords(records, handoff.root);",
1107
1535
  ...armsOpen(" "),
1108
1536
  streamsArms ? " const resumed = await resumeFromPrerenderRecords({" : " return (await resumeFromPrerenderRecords({",
@@ -1117,13 +1545,16 @@ function emitResumeContainerEvent(loadSymbolName, needsFullResume, storageFreePa
1117
1545
  " return resumed.runtime;"
1118
1546
  ] : [" })).runtime;"],
1119
1547
  " })());",
1548
+ " if (!runtime) return;",
1120
1549
  " await runtime.dispatch(handoff.event, { syncPolicyAlreadyApplied: handoff.syncPolicyAlreadyApplied === true, ignoreUnmatched: true });",
1121
1550
  "}"
1122
1551
  ].join("\n") : [
1123
1552
  "async function marklessFullResumeHandoff(handoff) {",
1553
+ lifeOpen(" "),
1124
1554
  " handoff.root.__asyncResumeRuntimeStarted = true;",
1125
1555
  ...armsOpen(" "),
1126
1556
  ` const { resumeFromPayloadDocument } = await import(${singleQuoted(resumeEntry)});`,
1557
+ lifeCheck(" "),
1127
1558
  " const { runtime } = await resumeFromPayloadDocument({",
1128
1559
  " document: handoff.document,",
1129
1560
  " root: handoff.root,",
@@ -1145,7 +1576,9 @@ function emitResumeContainerEvent(loadSymbolName, needsFullResume, storageFreePa
1145
1576
  ].join("\n");
1146
1577
  if (leanMode !== "none") {
1147
1578
  const row = [
1579
+ " const marklessLife = input.root.__mL;",
1148
1580
  " const { resumeScalarRowEventFromPayloadDocument } = await import('@markless/web/event-only-lean/row');",
1581
+ " if (input.root.__mL !== marklessLife) return;",
1149
1582
  " await resumeScalarRowEventFromPayloadDocument({",
1150
1583
  ...[
1151
1584
  " document: input.root,",
@@ -1210,10 +1643,9 @@ function emitPrerenderTriggerGroupLoader(groups) {
1210
1643
  " let within = false, done = false;",
1211
1644
  " 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; } };",
1212
1645
  " between(input.root);",
1213
- " let host = armNodes[hostPath[0]];",
1214
- " for (let index = 1; host && index < hostPath.length; index++) host = host.childNodes?.[hostPath[index]];",
1646
+ " const host = marklessElementAt({ childNodes: armNodes }, hostPath);",
1215
1647
  " const target = input.event?.target;",
1216
- " return host?.nodeType === 1 && (host === target || (!!target?.nodeType && typeof host.contains === \"function\" && host.contains(target)));",
1648
+ " return !!host && (host === target || (!!target?.nodeType && typeof host.contains === \"function\" && host.contains(target)));",
1217
1649
  "}",
1218
1650
  "function marklessLoadPrerenderTriggerGroup(input) {",
1219
1651
  ...groups.map((group) => {
@@ -1429,7 +1861,7 @@ function emitScalarAction(action, loadSymbolName, resolution) {
1429
1861
  ] : [],
1430
1862
  ...emitScalarWrite(action),
1431
1863
  ` const symbol = await Promise.resolve(${loadSymbolName}(${JSON.stringify(action.symbolId)}));`,
1432
- " 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 }));",
1864
+ " await Promise.resolve(symbol({ graph: { ...graph, write: (write) => write.value, 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 }));",
1433
1865
  " if (state.dirty) {",
1434
1866
  " state.dirty = false;",
1435
1867
  ...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;`),
@@ -1504,7 +1936,7 @@ function emitLoadSymbol(input, sourceReaderName) {
1504
1936
  function emitDirectSourceSymbolLoader(symbols, readerName = "readMarklessSourceSymbol") {
1505
1937
  return [
1506
1938
  "function loadSymbol(symbolId) {",
1507
- ...symbols.flatMap((symbol) => [` if (symbolId === ${JSON.stringify(symbol.id)}) return import(${singleQuoted(symbol.lazyChunk ?? symbol.chunk)})`, ` .then((mod) => ${readerName}(mod, ${JSON.stringify(symbol.exportName)}));`]),
1939
+ ...symbols.flatMap((symbol) => [` if (symbolId === ${JSON.stringify(symbol.id)}) return import(${singleQuoted(symbol.chunk)})`, ` .then((mod) => ${readerName}(mod, ${JSON.stringify(symbol.exportName)}));`]),
1508
1940
  " return Promise.reject(new Error(`Unknown async symbol ${symbolId}`));",
1509
1941
  "}",
1510
1942
  emitSourceSymbolExportReader(readerName)
@@ -1529,869 +1961,194 @@ function stringHash(value) {
1529
1961
  function singleQuoted(value) {
1530
1962
  return `'${String(value).replace(/[\\']/g, "\\$&").replace(/\n/g, "\\n").replace(/\r/g, "\\r")}'`;
1531
1963
  }
1532
- const MARKLESS_BUILD_PREFIX = `build/`;
1533
- const MARKLESS_BUNDLE_GRAPH = `${MARKLESS_BUILD_PREFIX}bundle-graph.json`;
1534
- const MARKLESS_EXECUTION_SIZES = `${MARKLESS_BUILD_PREFIX}execution-sizes.json`;
1535
- const MARKLESS_EXECUTION_DEMAND = `${MARKLESS_BUILD_PREFIX}execution-demand.json`;
1536
- const MARKLESS_INTERACTION_CLOSURES = `${MARKLESS_BUILD_PREFIX}interaction-closures.json`;
1537
- const MARKLESS_BYTE_ATTRIBUTION = `${MARKLESS_BUILD_PREFIX}byte-attribution.json`;
1538
- const MARKLESS_BUILD_METADATA_FILES = [
1539
- MARKLESS_BUNDLE_GRAPH,
1540
- MARKLESS_EXECUTION_SIZES,
1541
- MARKLESS_EXECUTION_DEMAND,
1542
- MARKLESS_INTERACTION_CLOSURES,
1543
- MARKLESS_BYTE_ATTRIBUTION
1544
- ];
1545
- const MARKLESS_PUBLIC_BUILD_METADATA_FILES = [MARKLESS_EXECUTION_SIZES];
1546
- const WEB_RUNTIME_CAPABILITY_GROUPS = [
1547
- {
1548
- name: "markless-direct-renderer",
1549
- test: fileBasenamePattern("direct")
1550
- },
1551
- {
1552
- name: "markless-resume-branches",
1553
- test: fileBasenamePattern("resume-branches", "resume-arm-records-lazy")
1554
- },
1555
- {
1556
- name: "markless-resume-behaviors",
1557
- test: fileBasenamePattern("resume-behaviors")
1558
- },
1559
- {
1560
- name: "markless-resume-repeats",
1561
- test: fileBasenamePattern("resume-keyed-repeats", "resume-keyed-repeats-lazy", "repeat-runtime")
1562
- },
1563
- {
1564
- name: "markless-resume-async",
1565
- test: fileBasenamePattern("resume-async-boundaries", "resume-async-wiring")
1566
- },
1567
- {
1568
- name: "markless-resume-shared-patch",
1569
- test: fileBasenamePattern("resume-shared-patch")
1570
- },
1571
- {
1572
- name: "markless-resume-runtime",
1573
- test: fileBasenamePattern("resume-runtime")
1574
- },
1575
- {
1576
- name: "markless-resume-runtime-start",
1577
- test: fileBasenamePattern("resume-runtime-start")
1578
- },
1579
- {
1580
- name: "markless-resume-runtime-shared",
1581
- test: fileBasenamePattern("resume-runtime-shared")
1582
- },
1583
- {
1584
- name: "markless-resume-events",
1585
- test: fileBasenamePattern("resume-events")
1586
- },
1587
- {
1588
- name: "markless-resume-handoff",
1589
- test: fileBasenamePattern("resume-handoff")
1590
- },
1591
- {
1592
- name: "markless-resume-locators",
1593
- test: fileBasenamePattern("resume-locators", "resume-census")
1594
- },
1595
- {
1596
- name: "markless-resume-errors",
1597
- test: fileBasenamePattern("resume-errors")
1598
- },
1599
- {
1600
- name: "markless-resume-sync-computed",
1601
- test: fileBasenamePattern("resume-sync-computed")
1602
- },
1603
- {
1604
- name: "markless-resume-sync-demand",
1605
- test: fileBasenamePattern("resume-sync-demand")
1606
- },
1607
- {
1608
- name: "markless-payload-full",
1609
- test: fileBasenamePattern("payload-full", "payload-full-storage-free")
1610
- },
1611
- {
1612
- name: "markless-payload-resume",
1613
- test: fileBasenamePattern("payload-resume", "payload-resume-lazy")
1614
- },
1615
- {
1616
- name: "markless-inline-payload-document",
1617
- test: /[/\\]web[/\\]src[/\\]inline[/\\]payload-document\.ts(?:[?#].*)?$/
1618
- },
1619
- {
1620
- name: "markless-payload-document",
1621
- test: fileBasenamePattern("payload-document", "payload-document-common", "payload-resume-registry")
1622
- },
1623
- {
1624
- name: "markless-payload-graph-construct",
1625
- test: fileBasenamePattern("payload-graph-construct")
1626
- },
1627
- {
1628
- name: "markless-dom-journal",
1629
- test: fileBasenamePattern("dom-journal")
1630
- },
1631
- {
1632
- name: "markless-protocol-decode",
1633
- test: fileBasenamePattern("protocol-client", "protocol-client-storage", "protocol-state", "storage-record-client")
1634
- },
1635
- {
1636
- name: "markless-value-decode",
1637
- test: fileBasenamePattern("value-decode-client", "value-decode-client-lazy", "value-decode-extensions")
1638
- },
1639
- {
1640
- name: "markless-payload-leaves",
1641
- test: fileBasenamePattern("payload", "payload-document")
1642
- },
1643
- {
1644
- name: "markless-dev-log",
1645
- test: EXECUTION_LOG_CHUNK_MODULE_PATTERN
1646
- },
1647
- {
1648
- name: "markless-resume-core",
1649
- test: fileBasenamePattern("resume")
1650
- },
1651
- {
1652
- name: "markless-runtime-graph-core",
1653
- test: fileBasenamePattern("graph-core")
1654
- },
1655
- {
1656
- name: "markless-runtime-graph-collections",
1657
- test: fileBasenamePattern("graph-collections")
1658
- },
1659
- {
1660
- name: "markless-runtime-graph-computed",
1661
- test: fileBasenamePattern("graph-computed")
1662
- },
1663
- {
1664
- name: "markless-runtime-graph-async",
1665
- test: fileBasenamePattern("graph-async")
1666
- },
1667
- {
1668
- name: "markless-runtime-graph-scheduler",
1669
- test: fileBasenamePattern("graph-scheduler")
1670
- },
1671
- {
1672
- name: "markless-runtime-graph-shared",
1673
- test: fileBasenamePattern("graph-shared")
1674
- },
1675
- {
1676
- name: "markless-graph",
1677
- test: /[/\\](?:runtime[/\\]src[/\\](?!graph-(?:core|collections|computed|async|scheduler|shared)\.ts)|core[/\\]src[/\\]runtime)[/\\]?/
1678
- },
1679
- {
1680
- name: "markless-serializer",
1681
- test: /[/\\]serializer[/\\]src[/\\](?!protocol-validation)/
1682
- }
1683
- ];
1684
- function fileBasenamePattern(...names) {
1685
- return new RegExp(`[/\\\\](?:${names.join("|")})\\.ts(?:[?#].*)?$`);
1686
- }
1687
- const MARKLESS_RUNTIME_GROUPS = [...WEB_RUNTIME_CAPABILITY_GROUPS, {
1688
- name: "markless-runtime",
1689
- test: /[/\\]@markless[/\\]runtime[/\\]/
1690
- }];
1691
- function outputDefaults(output, environment) {
1692
- if (environment === "lib") return output;
1693
- const next = {
1694
- ...output,
1695
- hoistTransitiveImports: false
1696
- };
1697
- if (environment === "server") {
1698
- next.entryFileNames ??= "[name].js";
1699
- next.chunkFileNames ??= "chunk-[hash].js";
1700
- next.codeSplitting = marklessCodeSplitting(next.codeSplitting);
1701
- return next;
1702
- }
1703
- next.entryFileNames ??= `${MARKLESS_BUILD_PREFIX}chunk-[hash].js`;
1704
- next.chunkFileNames ??= `${MARKLESS_BUILD_PREFIX}chunk-[hash].js`;
1705
- next.minifyInternalExports = true;
1706
- next.strictExecutionOrder = true;
1707
- next.codeSplitting = marklessCodeSplitting(next.codeSplitting);
1708
- return next;
1709
- }
1710
- function marklessCodeSplitting(codeSplitting) {
1711
- if (typeof codeSplitting === "boolean") throw new Error("@markless/bundler requires output.codeSplitting to be an object so runtime chunks can be grouped.");
1712
- return {
1713
- ...codeSplitting,
1714
- groups: [...MARKLESS_RUNTIME_GROUPS, ...codeSplitting?.groups ?? []]
1715
- };
1716
- }
1717
1964
  //#endregion
1718
- //#region src/bound-resolver.ts
1719
- function adaptImportedCaptureResolver(source, hasImportedRows) {
1720
- if (!hasImportedRows) return source;
1721
- const original = " return (context) => base({ ...context, capture: createCaptureContext(context, bound) });";
1722
- const replacement = [
1723
- " return async (context) => {",
1724
- " const pendingCallbacks = [];",
1725
- " const capture = createCaptureContext(context, bound);",
1726
- " const result = await base({ ...context, graph: createBoundGraph(context, bound, capture, pendingCallbacks), capture });",
1727
- " await Promise.all(pendingCallbacks);",
1728
- " return result;",
1729
- " };"
1730
- ].join("\n");
1731
- const helper = [
1732
- "function createBoundGraph(context, bound, capture, pendingCallbacks) {",
1733
- " const legacySlots = new Map(bound.captureSlots.flatMap((slot) => slot.legacyGraphRead ? [[JSON.stringify([slot.legacyGraphRead.graphNodeId, slot.legacyGraphRead.path ?? []]), slot]] : []));",
1734
- " let lastCallback = Promise.resolve();",
1735
- " return {",
1736
- " ...context.graph,",
1737
- " read(graphNodeId, path = []) {",
1738
- " const slot = legacySlots.get(JSON.stringify([graphNodeId, path]));",
1739
- " if (!slot) return context.graph.read(graphNodeId, path);",
1740
- " if (slot.route.kind === callbackRoute) return (...args) => {",
1741
- " const pending = lastCallback.then(() => capture.invoke(slot.slotId, args));",
1742
- " lastCallback = pending.catch(() => {});",
1743
- " pendingCallbacks.push(pending);",
1744
- " return pending;",
1745
- " };",
1746
- " return capture.read(slot.slotId);",
1747
- " },",
1748
- " };",
1749
- "}",
1750
- ""
1751
- ].join("\n");
1752
- return source.replace(original, replacement).replace("function createCaptureContext(context, bound) {", `${helper}function createCaptureContext(context, bound) {`);
1753
- }
1754
- //#endregion
1755
- //#region src/trigger-groups.ts
1756
- const EVENT_STAGES_BROWSER_TRIGGER = {
1757
- [PROTOCOL_EVENT_ACTION_KIND.event]: true,
1758
- [PROTOCOL_EVENT_ACTION_KIND.externalDelegate]: false
1759
- };
1760
- function triggerGroupVirtualModuleId(filename, index) {
1761
- return `virtual:markless:trigger-group:${encodeURIComponent(filename)}:${index}`;
1762
- }
1763
- function triggerGroupVirtualModuleSourceFile(moduleId) {
1764
- const bare = moduleId.startsWith("\0") ? moduleId.slice(1) : moduleId;
1765
- const match = /^virtual:markless:trigger-group:([^:]+):\d+$/.exec(bare);
1766
- if (!match?.[1]) return null;
1767
- try {
1768
- return decodeURIComponent(match[1]);
1769
- } catch {
1770
- return null;
1965
+ //#region src/build/machine-paths.ts
1966
+ const rootsByBuildRoot = /* @__PURE__ */ new Map();
1967
+ function machinePathRoots(root) {
1968
+ const cached = rootsByBuildRoot.get(root);
1969
+ if (cached) return cached;
1970
+ const roots = /* @__PURE__ */ new Set();
1971
+ for (const start of [normalize(root), realpathOrSelf(root)]) {
1972
+ roots.add(start);
1973
+ for (let directory = start; dirname(directory) !== directory; directory = dirname(directory)) if (existsSync(join(directory, "pnpm-workspace.yaml")) || existsSync(join(directory, ".git"))) {
1974
+ roots.add(directory);
1975
+ break;
1976
+ }
1771
1977
  }
1772
- }
1773
- function emitPrerenderTriggerGroupModule(input) {
1774
- const armRendererModuleId = input.armRendererModuleId ?? input.group.armRendererModuleId;
1775
- const ids = new Set(input.group.symbolIds);
1776
- const boundRows = input.boundRows.filter((row) => ids.has(row.id));
1777
- let source = emitSymbolResolverModule({
1778
- symbols: input.symbols.filter((symbol) => ids.has(symbol.id)),
1779
- boundSymbols: boundRows,
1780
- literalImports: input.literalImports,
1781
- bundlerVisibleImports: input.literalImports
1782
- });
1783
- const routes = (input.symbolRoutes ?? []).map((route) => route.boundSymbols ? {
1784
- ...route,
1785
- boundSymbols: Object.fromEntries(Object.entries(route.boundSymbols).filter(([, rowId]) => ids.has(rowId)))
1786
- } : route);
1787
- if (routes.length > 0) {
1788
- source = source.replaceAll("loadSymbol(", "marklessLoadLocalSymbol(");
1789
- source += "\n" + emitSymbolRouteTable({
1790
- routes: routes.map((route) => "importSource" in route ? {
1791
- ...route,
1792
- importSource: symbolRouteImportSource(route.importSource)
1793
- } : route),
1794
- functionName: "loadSymbol",
1795
- fallbackName: "marklessLoadLocalSymbol",
1796
- reboundName: "marklessLoadSymbolRebound",
1797
- exported: true
1798
- });
1978
+ const found = [...roots].filter((path) => path !== "/");
1979
+ rootsByBuildRoot.set(root, found);
1980
+ return found;
1981
+ }
1982
+ /** `text` with every checkout path removed, as spelled raw, URI-encoded, or as a bundler-minted identifier. */
1983
+ function withoutMachinePaths(text, root) {
1984
+ if (!root) return text;
1985
+ const asIdentifier = (value) => value.replace(/[^\w$]/g, "_");
1986
+ let stripped = text;
1987
+ for (const suffix of ["/", ""]) for (const path of machinePathRoots(root)) {
1988
+ const encoded = encodeURIComponent(`${path}${suffix}`);
1989
+ for (const spelling of [
1990
+ `${path}${suffix}`,
1991
+ encoded,
1992
+ encoded.replaceAll("%", "_"),
1993
+ asIdentifier(encoded),
1994
+ asIdentifier(`${path}${suffix}`)
1995
+ ]) stripped = stripped.split(spelling).join("");
1799
1996
  }
1800
- return [
1801
- armRendererModuleId ? [
1802
- `import { prepareBoundaryArm as marklessPrepareBoundaryArm, renderBoundaryArm as marklessRenderBoundaryArm } from ${JSON.stringify(armRendererModuleId)};`,
1803
- "export function prepareBoundaryArm(boundaryId, status, graph) {",
1804
- " return marklessPrepareBoundaryArm(boundaryId, status, graph, loadSymbol);",
1805
- "}",
1806
- "export function renderBoundaryArm(boundaryId, status, graph) {",
1807
- " return marklessRenderBoundaryArm(boundaryId, status, graph, loadSymbol);",
1808
- "}"
1809
- ].join("\n") : "",
1810
- adaptImportedCaptureResolver(source, boundRows.some((row) => row.loaderSymbolId !== void 0)),
1811
- `export const groupId=${JSON.stringify(input.group.id)};`,
1812
- `export const state=${JSON.stringify(input.group.state)};`,
1813
- `export const view=${JSON.stringify(input.group.view)};`,
1814
- `export const graphNodeIds=${JSON.stringify(input.group.graphNodeIds)};`
1815
- ].join("\n");
1816
- }
1817
- function emitPrerenderBoundaryRendererModule(renderDataId) {
1818
- return [
1819
- `import { marklessPrerenderData } from ${JSON.stringify(renderDataId)};`,
1820
- "import { renderPrerenderBoundary } from '@markless/web/fns/prerender-resume';",
1821
- "const marklessPreparedBoundaryArms = new WeakMap();",
1822
- "export async function prepareBoundaryArm(boundaryId, status, graph, loadSymbol) {",
1823
- " const rendered = await renderPrerenderBoundary(marklessPrerenderData, boundaryId, status, graph, loadSymbol);",
1824
- " if (!marklessPreparedBoundaryArms.has(graph)) marklessPreparedBoundaryArms.set(graph, new Map());",
1825
- " marklessPreparedBoundaryArms.get(graph).set(`${boundaryId}:${status}`, rendered);",
1826
- "}",
1827
- "export function renderBoundaryArm(boundaryId, status, graph) {",
1828
- " const key = `${boundaryId}:${status}`;",
1829
- " const prepared = marklessPreparedBoundaryArms.get(graph);",
1830
- " const rendered = prepared?.get(key);",
1831
- " if (!rendered) throw new Error(`Markless prerender arm ${key} was not prepared.`);",
1832
- " prepared.delete(key);",
1833
- " return rendered;",
1834
- "}"
1835
- ].join("\n");
1836
- }
1837
- function symbolRouteImportSource(importSource) {
1838
- return importSource.includes("?") ? `${importSource}&markless-symbols` : `${importSource}?markless-symbols`;
1997
+ return stripped;
1839
1998
  }
1840
- function planPrerenderTriggerGroups(input) {
1841
- const symbols = new Map(input.symbolResolver.symbols.map((symbol) => [symbol.id, symbol]));
1842
- const bounds = new Map(input.boundRows.map((row) => [row.id, row]));
1843
- const completeView = input.completeView ?? input.view;
1844
- const completeBoundaries = new Map(completeView.asyncBoundaries.map((boundary) => [boundary.id, boundary]));
1845
- const selfWakeBoundaries = unsettledAsyncBoundaryIndexes(input.state, input.view);
1846
- const groups = [
1847
- ...selfWakeBoundaries.length > 0 ? [{
1848
- event: {
1849
- hostNodeId: "self-wake",
1850
- eventName: "self-wake",
1851
- symbolIds: []
1852
- },
1853
- selfWakeBoundaries
1854
- }] : [],
1855
- ...input.view.events.filter((event) => EVENT_STAGES_BROWSER_TRIGGER[protocolEventActionKind(event)]).map((event) => ({ event })),
1856
- ...(input.view.branches ?? []).flatMap((branch, branchIndex) => {
1857
- const events = /* @__PURE__ */ new Map();
1858
- for (const arm of branch.armRecords ?? []) for (const event of arm.events) {
1859
- const key = `${event.eventName}:${event.hostPath.join(".")}`;
1860
- const route = events.get(key) ?? {
1861
- eventName: event.eventName,
1862
- hostPath: event.hostPath,
1863
- symbolIds: /* @__PURE__ */ new Set()
1864
- };
1865
- for (const symbolId of event.symbolIds ?? []) route.symbolIds.add(symbolId);
1866
- events.set(key, route);
1867
- }
1868
- return [...events.values()].map((route) => ({
1869
- event: {
1870
- hostNodeId: `branch:${branch.id}:${route.hostPath.join(".")}`,
1871
- eventName: route.eventName,
1872
- symbolIds: [...route.symbolIds]
1873
- },
1874
- branch,
1875
- branchIndex,
1876
- hostPath: route.hostPath
1877
- }));
1878
- })
1879
- ].flatMap(({ event, branch, branchIndex, hostPath, selfWakeBoundaries }) => {
1880
- const closureView = selfWakeBoundaries ? completeView : input.view;
1881
- const host = branch ? void 0 : input.view.locators.find((locator) => locator.hostNodeId === event.hostNodeId);
1882
- if (!host && !branch && !selfWakeBoundaries) return [];
1883
- const compilerGroup = input.triggerGroups.groups.find((group) => group.hostNodeId === event.hostNodeId && group.eventName === event.eventName);
1884
- const graphNodeIds = /* @__PURE__ */ new Set();
1885
- const symbolIds = new Set(event.symbolIds ?? []);
1886
- const selected = {
1887
- domUpdates: /* @__PURE__ */ new Set(),
1888
- behaviors: /* @__PURE__ */ new Set(),
1889
- branches: /* @__PURE__ */ new Set(),
1890
- boundaries: /* @__PURE__ */ new Set(),
1891
- repeats: /* @__PURE__ */ new Set(),
1892
- elementHandles: /* @__PURE__ */ new Set()
1893
- };
1894
- if (branch && branchIndex !== void 0) {
1895
- selected.branches.add(branchIndex);
1896
- if (branch.symbolId) symbolIds.add(branch.symbolId);
1897
- for (const read of branch.testReads ?? []) graphNodeIds.add(read.graphNodeId);
1898
- for (const arm of branch.armRecords ?? []) collectCompleteArmRecordClosure(arm, graphNodeIds, symbolIds);
1899
- }
1900
- const adoptedBoundaryIds = /* @__PURE__ */ new Set();
1901
- const escalatedHostNodeIds = /* @__PURE__ */ new Set();
1902
- for (const boundaryIndex of selfWakeBoundaries ?? []) {
1903
- const servedBoundary = input.view.asyncBoundaries[boundaryIndex];
1904
- selected.boundaries.add(boundaryIndex);
1905
- collectSettledBoundaryClosure(input, completeBoundaries.get(servedBoundary.id) ?? servedBoundary, graphNodeIds, symbolIds);
1906
- }
1907
- closureView.behaviors.forEach((behavior, index) => {
1908
- if (selfWakeBoundaries) return;
1909
- const recordId = `behavior:${behavior.hostNodeId}:${behavior.symbolId ?? ""}`;
1910
- if ((behavior.inputGraphReads?.length ?? 0) > 0 && !compilerGroup?.payloadRecordIds.includes(recordId)) return;
1911
- selected.behaviors.add(index);
1912
- if (behavior.symbolId) symbolIds.add(behavior.symbolId);
1913
- });
1914
- let changed = true;
1915
- while (changed) {
1916
- const before = closureSize(graphNodeIds, symbolIds, selected);
1917
- const currentSymbolIds = Array.from(symbolIds);
1918
- for (const symbolId of currentSymbolIds) {
1919
- const bound = bounds.get(symbolId);
1920
- if (bound) {
1921
- symbolIds.add(bound.loaderSymbolId ?? bound.baseSymbolId);
1922
- for (const slot of bound.captureSlots) {
1923
- if (slot.route.kind === "graph-reference") graphNodeIds.add(slot.route.graphNodeId);
1924
- if (slot.route.kind === "callback-route") symbolIds.add(slot.route.callbackSymbolId);
1925
- }
1926
- }
1927
- const symbol = symbols.get(symbolId);
1928
- if (!symbol) continue;
1929
- if ("reads" in symbol) for (const read of symbol.reads ?? []) graphNodeIds.add(read.graphNodeId);
1930
- if ("writes" in symbol) for (const write of symbol.writes ?? []) graphNodeIds.add(write.graphNodeId);
1931
- if (symbol.kind === "async-computed-runner" || symbol.kind === "sync-computed-derive") {
1932
- graphNodeIds.add(symbol.graphNodeId);
1933
- for (const dependency of symbol.dependencies ?? []) graphNodeIds.add(dependency.graphNodeId);
1934
- }
1935
- if ("elementHandleCalls" in symbol) for (const call of symbol.elementHandleCalls ?? []) closureView.elementHandles.forEach((handle, index) => {
1936
- if (handle.name === call.handleName) selected.elementHandles.add(index);
1937
- });
1938
- if ("elementHandleReads" in symbol) for (const read of symbol.elementHandleReads ?? []) closureView.elementHandles.forEach((handle, index) => {
1939
- if (handle.handleId === read.handleId || handle.name === read.handleName) selected.elementHandles.add(index);
1940
- });
1941
- }
1942
- closeComputedGraph(graphNodeIds, input.state);
1943
- for (const computed of input.state.computed) if (computed.deriveSymbolId && graphNodeIds.has(computed.graphNodeId)) symbolIds.add(computed.deriveSymbolId);
1944
- for (const graphNodeId of graphNodeIds) {
1945
- const runnerSymbolId = closureView.asyncRunners?.[graphNodeId];
1946
- if (runnerSymbolId) symbolIds.add(runnerSymbolId);
1947
- }
1948
- selectViewSubscribers(closureView, graphNodeIds, symbolIds, selected);
1949
- const escalatedBranchIds = /* @__PURE__ */ new Set();
1950
- for (const index of selected.branches) {
1951
- const record = closureView.branches?.[index];
1952
- if (record?.escalates) escalatedBranchIds.add(record.id);
1953
- }
1954
- for (const index of selected.boundaries) {
1955
- const served = closureView.asyncBoundaries[index];
1956
- for (const arm of boundaryArmRecordSets(completeBoundaries.get(served.id) ?? served)) collectEscalatedArmBranchIds(arm, escalatedBranchIds);
1957
- }
1958
- for (const branchId of escalatedBranchIds) collectEscalatedBranchClosure(input, branchId, graphNodeIds, symbolIds, escalatedHostNodeIds);
1959
- if (!selfWakeBoundaries) input.view.asyncBoundaries.forEach((servedBoundary, index) => {
1960
- if (adoptedBoundaryIds.has(servedBoundary.id)) return;
1961
- const boundary = completeBoundaries.get(servedBoundary.id) ?? servedBoundary;
1962
- if (!settledArmReadGraphNodeIds(input, boundary).some((graphNodeId) => graphNodeIds.has(graphNodeId))) return;
1963
- adoptedBoundaryIds.add(servedBoundary.id);
1964
- selected.boundaries.add(index);
1965
- collectSettledBoundaryClosure(input, boundary, graphNodeIds, symbolIds);
1966
- collectSettledArmHostRecordClosure(completeView, boundary, graphNodeIds, symbolIds);
1967
- });
1968
- if (selfWakeBoundaries || adoptedBoundaryIds.size > 0) {
1969
- for (const symbol of symbols.values()) if (symbol.kind === "state-initializer" && graphNodeIds.has(symbol.graphNodeId)) symbolIds.add(symbol.id);
1970
- }
1971
- changed = closureSize(graphNodeIds, symbolIds, selected) !== before;
1972
- }
1973
- dropEscalatedHostRecords(closureView, selected, escalatedHostNodeIds);
1974
- const neededHosts = new Set(branch ? [] : [event.hostNodeId]);
1975
- for (const index of selected.domUpdates) neededHosts.add(closureView.domUpdates[index].hostNodeId);
1976
- for (const index of selected.behaviors) neededHosts.add(closureView.behaviors[index].hostNodeId);
1977
- for (const index of selected.repeats) neededHosts.add(closureView.keyedRepeats[index].parentHostNodeId);
1978
- for (const index of selected.elementHandles) neededHosts.add(closureView.elementHandles[index].hostNodeId);
1979
- const selectedBoundaryIds = new Set([...selected.boundaries].map((index) => closureView.asyncBoundaries[index].id));
1980
- const view = {
1981
- ...input.view,
1982
- locators: closureView.locators.filter((locator) => neededHosts.has(locator.hostNodeId)),
1983
- events: branch || selfWakeBoundaries ? [] : [event],
1984
- domUpdates: closureView.domUpdates.filter((_, index) => selected.domUpdates.has(index)),
1985
- behaviors: closureView.behaviors.filter((_, index) => selected.behaviors.has(index)),
1986
- elementHandles: closureView.elementHandles.filter((_, index) => selected.elementHandles.has(index)),
1987
- keyedRepeats: closureView.keyedRepeats?.filter((_, index) => selected.repeats.has(index)),
1988
- branches: closureView.branches?.filter((_, index) => selected.branches.has(index)),
1989
- asyncBoundaries: closureView.asyncBoundaries.filter((boundary) => selectedBoundaryIds.has(boundary.id)).map((boundary) => adoptedBoundaryIds.has(boundary.id) ? completeBoundaries.get(boundary.id) ?? boundary : boundary),
1990
- ...closureView.asyncRunners ? { asyncRunners: Object.fromEntries(Object.entries(closureView.asyncRunners).filter(([graphNodeId]) => graphNodeIds.has(graphNodeId))) } : {}
1991
- };
1992
- const graphIds = [...graphNodeIds].sort();
1993
- return [{
1994
- id: selfWakeBoundaries ? "self-wake" : branch ? `branch:${branch.id}:${event.eventName}:${hostPath.join(".")}` : `${event.hostNodeId}:${event.eventName}`,
1995
- hostNodeId: event.hostNodeId,
1996
- eventName: event.eventName,
1997
- hostIndex: host?.index ?? -1,
1998
- hostTagName: host?.tagName ?? "*",
1999
- ...branch ? {
2000
- branchStartIndex: branch.startAnchor.index,
2001
- branchEndIndex: branch.endAnchor.index,
2002
- hostPath
2003
- } : {},
2004
- graphNodeIds: graphIds,
2005
- symbolIds: [...symbolIds].sort(),
2006
- state: filterState(input.state, new Set(graphIds)),
2007
- view,
2008
- ...adoptedBoundaryIds.size > 0 ? { adoptsSettledArm: true } : {}
2009
- }];
1999
+ /** Emitted files whose contents spell a machine path, raw, URI-encoded, or inside a bundler-minted identifier. */
2000
+ function machinePathLeaks(bundle, roots) {
2001
+ const asIdentifier = (value) => value.replace(/[^\w$]/g, "_");
2002
+ const needles = roots.flatMap((path) => {
2003
+ const encoded = encodeURIComponent(`${path}/`);
2004
+ return [
2005
+ `${path}/`,
2006
+ encoded,
2007
+ asIdentifier(encoded),
2008
+ asIdentifier(`${path}/`)
2009
+ ];
2010
2010
  });
2011
- const armRendererModuleId = groups.some((group) => group.id === "self-wake") ? triggerGroupVirtualModuleId(input.filename, groups.length) : void 0;
2012
- return groups.map(({ adoptsSettledArm, ...group }) => adoptsSettledArm && armRendererModuleId ? {
2013
- ...group,
2014
- armRendererModuleId
2015
- } : group);
2016
- }
2017
- function settledArmReadGraphNodeIds(input, boundary) {
2018
- const graphNodeIds = /* @__PURE__ */ new Set();
2019
- for (const arm of boundaryArmRecordSets(boundary)) collectCompleteArmRecordClosure(arm, graphNodeIds, /* @__PURE__ */ new Set());
2020
- for (const edge of input.componentEdges ?? []) if (edge.asyncBoundaryId === boundary.id) {
2021
- for (const prop of edge.props) if (prop.kind === "graph-reference") graphNodeIds.add(prop.graphNodeId);
2011
+ const leaks = [];
2012
+ for (const [fileName, output] of Object.entries(bundle)) {
2013
+ const item = output;
2014
+ const contents = item.type === "chunk" ? item.code : typeof item.source === "string" ? item.source : item.source instanceof Uint8Array ? new TextDecoder().decode(item.source) : void 0;
2015
+ if (contents && needles.some((needle) => contents.includes(needle))) leaks.push(fileName);
2022
2016
  }
2023
- return [...graphNodeIds];
2017
+ return leaks.sort();
2024
2018
  }
2025
- function collectSettledBoundaryClosure(input, boundary, graphNodeIds, symbolIds) {
2026
- if (boundary.updateSymbolId) symbolIds.add(boundary.updateSymbolId);
2027
- for (const read of boundary.asyncReads) {
2028
- graphNodeIds.add(read.graphNodeId);
2029
- if (read.runnerSymbolId) symbolIds.add(read.runnerSymbolId);
2030
- }
2031
- for (const arm of boundaryArmRecordSets(boundary)) collectCompleteArmRecordClosure(arm, graphNodeIds, symbolIds);
2032
- const settledEdgeIds = /* @__PURE__ */ new Set();
2033
- for (const edge of input.componentEdges ?? []) {
2034
- if (edge.asyncBoundaryId !== boundary.id) continue;
2035
- settledEdgeIds.add(edge.id);
2036
- for (const prop of edge.props) if (prop.kind === "graph-reference") graphNodeIds.add(prop.graphNodeId);
2037
- }
2038
- for (const row of input.boundRows) if (row.componentEdgePath.some((edgeId) => settledEdgeIds.has(edgeId))) symbolIds.add(row.id);
2039
- }
2040
- function collectSettledArmHostRecordClosure(completeView, boundary, graphNodeIds, symbolIds) {
2041
- const armHosts = /* @__PURE__ */ new Set();
2042
- for (const arm of boundaryArmRecordSets(boundary)) for (const locator of arm.locators ?? []) armHosts.add(locator.hostNodeId);
2043
- if (armHosts.size === 0) return;
2044
- for (const record of completeView.events) if (armHosts.has(record.hostNodeId)) for (const symbolId of record.symbolIds ?? []) symbolIds.add(symbolId);
2045
- for (const record of completeView.domUpdates) if (armHosts.has(record.hostNodeId)) {
2046
- graphNodeIds.add(record.graphNodeId);
2047
- if (record.symbolId) symbolIds.add(record.symbolId);
2048
- }
2049
- for (const record of completeView.behaviors) if (armHosts.has(record.hostNodeId)) {
2050
- for (const read of record.inputGraphReads ?? []) graphNodeIds.add(read.graphNodeId);
2051
- if (record.symbolId) symbolIds.add(record.symbolId);
2052
- }
2053
- for (const record of completeView.keyedRepeats ?? []) if (armHosts.has(record.parentHostNodeId)) {
2054
- if (record.collectionGraphNodeId) graphNodeIds.add(record.collectionGraphNodeId);
2055
- for (const rowEvent of record.rowEvents) for (const symbolId of rowEvent.symbolIds ?? []) symbolIds.add(symbolId);
2019
+ function realpathOrSelf(path) {
2020
+ try {
2021
+ return normalize(realpathSync(path));
2022
+ } catch {
2023
+ return normalize(path);
2056
2024
  }
2057
2025
  }
2058
- function dropEscalatedHostRecords(view, selected, hostNodeIds) {
2059
- if (hostNodeIds.size === 0) return;
2060
- const drop = (indexes, hostOf) => {
2061
- for (const index of indexes) if (hostNodeIds.has(hostOf(index) ?? "")) indexes.delete(index);
2062
- };
2063
- drop(selected.domUpdates, (index) => view.domUpdates[index]?.hostNodeId);
2064
- drop(selected.behaviors, (index) => view.behaviors[index]?.hostNodeId);
2065
- drop(selected.elementHandles, (index) => view.elementHandles[index]?.hostNodeId);
2066
- drop(selected.repeats, (index) => view.keyedRepeats?.[index]?.parentHostNodeId);
2067
- }
2068
- function collectEscalatedArmBranchIds(arm, branchIds) {
2069
- for (const branch of arm.branches ?? []) {
2070
- if (!branch.symbolId && (branch.testReads?.length ?? 0) > 0) branchIds.add(branch.id);
2071
- for (const nested of branch.armRecords ?? []) collectEscalatedArmBranchIds(nested, branchIds);
2026
+ function rootRelativeRegionComments(bundle, root) {
2027
+ if (!root) return;
2028
+ for (const output of Object.values(bundle)) {
2029
+ const chunk = output;
2030
+ if (chunk.type !== "chunk" || !chunk.code?.includes("//#region ")) continue;
2031
+ chunk.code = chunk.code.replace(/^(\/\/#region (?:\\0)?)(.+)$/gm, (_, prefix, id) => `${prefix}${rootRelativeId(id, root)}`);
2072
2032
  }
2073
2033
  }
2074
- function collectEscalatedBranchClosure(input, branchSiteId, graphNodeIds, symbolIds, hostNodeIds) {
2075
- const renderData = input.renderData;
2076
- const branch = renderData?.branches.find((candidate) => candidate.branchSiteId === branchSiteId);
2077
- if (!renderData || !branch) return;
2078
- const chunks = new Map(renderData.chunks.map((chunk) => [chunk.id, chunk]));
2079
- const edgeIds = /* @__PURE__ */ new Set();
2080
- const walked = /* @__PURE__ */ new Set();
2081
- const walk = (chunkId) => {
2082
- if (!chunkId || walked.has(chunkId)) return;
2083
- walked.add(chunkId);
2084
- const chunk = chunks.get(chunkId);
2085
- if (!chunk) return;
2086
- for (const host of chunk.hosts) hostNodeIds.add(host.hostNodeId);
2087
- for (const slot of chunk.slots) if (slot.kind === "child-component") {
2088
- edgeIds.add(slot.componentEdgeId);
2089
- walk(slot.childTemplateId);
2090
- walk(slot.projectionChunkId);
2091
- } else if (slot.kind === "branch") for (const armId of slot.armTemplateIds) walk(armId);
2092
- else if (slot.kind === "repeat") {
2093
- walk(slot.rowTemplateId);
2094
- walk(slot.emptyTemplateId);
2095
- } else if (slot.kind === "async") {
2096
- walk(slot.armTemplateIds.try);
2097
- walk(slot.armTemplateIds.pending);
2098
- walk(slot.armTemplateIds.catch);
2099
- } else if (slot.kind === "dynamic-host") walk(slot.childChunkId);
2100
- else if ("residue" in slot && slot.residue.kind === "graph-read") graphNodeIds.add(slot.residue.graphNodeId);
2101
- };
2102
- for (const armId of branch.armChunkIds) walk(armId);
2103
- for (const symbol of input.symbolResolver.symbols) if (symbol.kind === "dom-update" && hostNodeIds.has(symbol.hostNodeId)) graphNodeIds.add(symbol.graphNodeId);
2104
- 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);
2105
- for (const row of input.boundRows) if (row.componentEdgePath.some((edgeId) => edgeIds.has(edgeId))) symbolIds.add(row.id);
2106
- }
2107
- function boundaryArmRecordSets(boundary) {
2108
- return Array.isArray(boundary.armRecords) ? boundary.armRecords : boundary.armRecords ? [boundary.armRecords] : [];
2109
- }
2110
- function unsettledAsyncBoundaryIndexes(state, view) {
2111
- const computed = new Map(state.computed.map((record) => [record.graphNodeId, record]));
2112
- const runners = { ...view.asyncRunners };
2113
- for (const boundary of view.asyncBoundaries) for (const read of boundary.asyncReads) if (read.runnerSymbolId) runners[read.graphNodeId] ??= read.runnerSymbolId;
2114
- return view.asyncBoundaries.flatMap((boundary, index) => {
2115
- const reachable = new Set(boundary.asyncReads.map((read) => read.graphNodeId));
2116
- for (const graphNodeId of reachable) {
2117
- const record = computed.get(graphNodeId);
2118
- if (!record) continue;
2119
- if (runners[graphNodeId] && record.snapshot?.status !== "fulfilled" && record.snapshot?.status !== "rejected") return [index];
2120
- for (const dependency of record.dependencies ?? []) reachable.add(dependency.graphNodeId);
2121
- }
2122
- return [];
2123
- });
2124
- }
2125
- function selectViewSubscribers(view, graphNodeIds, symbolIds, selected) {
2126
- view.domUpdates.forEach((record, index) => {
2127
- if (!graphNodeIds.has(record.graphNodeId)) return;
2128
- selected.domUpdates.add(index);
2129
- if (record.symbolId) symbolIds.add(record.symbolId);
2130
- });
2131
- view.behaviors.forEach((record, index) => {
2132
- if (!(record.inputGraphReads ?? []).some((read) => graphNodeIds.has(read.graphNodeId))) return;
2133
- selected.behaviors.add(index);
2134
- if (record.symbolId) symbolIds.add(record.symbolId);
2135
- });
2136
- (view.branches ?? []).forEach((record, index) => {
2137
- if (!(record.testReads ?? []).some((read) => graphNodeIds.has(read.graphNodeId))) return;
2138
- selected.branches.add(index);
2139
- if (record.symbolId) symbolIds.add(record.symbolId);
2140
- for (const arm of record.armRecords ?? []) collectCompleteArmRecordClosure(arm, graphNodeIds, symbolIds);
2141
- });
2142
- view.asyncBoundaries.forEach((record, index) => {
2143
- if (!record.asyncReads.some((read) => graphNodeIds.has(read.graphNodeId))) return;
2144
- selected.boundaries.add(index);
2145
- if (record.updateSymbolId) symbolIds.add(record.updateSymbolId);
2146
- for (const read of record.asyncReads) if (read.runnerSymbolId) symbolIds.add(read.runnerSymbolId);
2147
- const arms = Array.isArray(record.armRecords) ? record.armRecords : record.armRecords ? [record.armRecords] : [];
2148
- for (const arm of arms) collectCompleteArmRecordClosure(arm, graphNodeIds, symbolIds);
2149
- });
2150
- (view.keyedRepeats ?? []).forEach((record, index) => {
2151
- if (!record.collectionGraphNodeId || !graphNodeIds.has(record.collectionGraphNodeId)) return;
2152
- selected.repeats.add(index);
2153
- for (const rowEvent of record.rowEvents) for (const symbolId of rowEvent.symbolIds ?? []) symbolIds.add(symbolId);
2154
- });
2155
- }
2156
- function collectCompleteArmRecordClosure(arm, graphNodeIds, symbolIds) {
2157
- for (const event of arm.events ?? []) for (const symbolId of event.symbolIds ?? []) symbolIds.add(symbolId);
2158
- for (const update of arm.domUpdates ?? []) {
2159
- if (typeof update.graphNodeId === "string") graphNodeIds.add(update.graphNodeId);
2160
- if (typeof update.symbolId === "string") symbolIds.add(update.symbolId);
2161
- }
2162
- for (const behavior of arm.behaviors ?? []) {
2163
- for (const read of behavior.inputGraphReads ?? []) if (typeof read.graphNodeId === "string") graphNodeIds.add(read.graphNodeId);
2164
- if (typeof behavior.symbolId === "string") symbolIds.add(behavior.symbolId);
2165
- }
2166
- for (const repeat of arm.keyedRepeats ?? []) {
2167
- if (repeat.collectionGraphNodeId) graphNodeIds.add(repeat.collectionGraphNodeId);
2168
- for (const event of repeat.rowEvents) for (const symbolId of event.symbolIds ?? []) symbolIds.add(symbolId);
2034
+ //#endregion
2035
+ //#region src/module-id.ts
2036
+ const linkedPackagesByRoot = /* @__PURE__ */ new Map();
2037
+ const mintedSources = /* @__PURE__ */ new Map();
2038
+ const mintedIds = /* @__PURE__ */ new Map();
2039
+ function moduleIdFor(filename, root) {
2040
+ if (!root || !isAbsolute(filename)) return filename;
2041
+ const key = `${root}\0${filename}`;
2042
+ let id = mintedIds.get(key);
2043
+ if (id === void 0) {
2044
+ const relativeId = relative(root, filename);
2045
+ id = !relativeId.startsWith("..") && !relativeId.includes("node_modules/") ? relativeId : packageRootedModuleId(filename, root) ?? (outsideCheckout(filename, root) ? namedPackageModuleId(filename) : null) ?? relativeId;
2046
+ mintedIds.set(key, id);
2169
2047
  }
2170
- for (const branch of arm.branches ?? []) {
2171
- if (branch.symbolId) symbolIds.add(branch.symbolId);
2172
- for (const read of branch.testReads ?? []) graphNodeIds.add(read.graphNodeId);
2173
- for (const nested of branch.armRecords ?? []) collectCompleteArmRecordClosure(nested, graphNodeIds, symbolIds);
2048
+ mintedSources.set(`${root}\0${id}`, filename);
2049
+ return id;
2050
+ }
2051
+ /** The file a module id names, spelled the way the bundler resolved it. */
2052
+ function sourceForModuleId(moduleId, root) {
2053
+ if (!root || isAbsolute(moduleId)) return moduleId;
2054
+ return mintedSources.get(`${root}\0${moduleId}`) ?? realpathOf(resolve(root, moduleId));
2055
+ }
2056
+ function packageRootedModuleId(filename, root) {
2057
+ const real = realpathOf(filename);
2058
+ for (const linked of linkedPackages(root)) {
2059
+ if (real === linked.real) return linked.id;
2060
+ if (real.startsWith(`${linked.real}/`)) return `${linked.id}${real.slice(linked.real.length)}`;
2174
2061
  }
2062
+ return null;
2175
2063
  }
2176
- function closeComputedGraph(graphNodeIds, state) {
2177
- let changed = true;
2178
- while (changed) {
2179
- changed = false;
2180
- for (const computed of state.computed) {
2181
- const dependencies = computed.dependencies ?? [];
2182
- if (!graphNodeIds.has(computed.graphNodeId) && !dependencies.some((dependency) => graphNodeIds.has(dependency.graphNodeId))) continue;
2183
- if (!graphNodeIds.has(computed.graphNodeId)) {
2184
- graphNodeIds.add(computed.graphNodeId);
2185
- changed = true;
2186
- }
2187
- for (const dependency of dependencies) if (!graphNodeIds.has(dependency.graphNodeId)) {
2188
- graphNodeIds.add(dependency.graphNodeId);
2189
- changed = true;
2190
- }
2064
+ function outsideCheckout(filename, root) {
2065
+ const real = realpathOf(filename);
2066
+ return !machinePathRoots(root).some((checkout) => filename.startsWith(`${checkout}/`) || real.startsWith(`${checkout}/`));
2067
+ }
2068
+ function namedPackageModuleId(filename) {
2069
+ const real = realpathOf(filename);
2070
+ for (let directory = dirname(real); dirname(directory) !== directory; directory = dirname(directory)) {
2071
+ let name;
2072
+ try {
2073
+ name = JSON.parse(readFileSync(join(directory, "package.json"), "utf8")).name;
2074
+ } catch {
2075
+ continue;
2191
2076
  }
2077
+ if (typeof name === "string" && name) return `node_modules/${name}${real.slice(directory.length)}`;
2192
2078
  }
2079
+ return null;
2080
+ }
2081
+ function linkedPackages(root) {
2082
+ const cached = linkedPackagesByRoot.get(root);
2083
+ if (cached) return cached;
2084
+ const directory = join(root, "node_modules");
2085
+ const packages = [];
2086
+ for (const name of packageNames(directory)) try {
2087
+ packages.push({
2088
+ id: `node_modules/${name}`,
2089
+ real: realpathOf(join(directory, name))
2090
+ });
2091
+ } catch {}
2092
+ packages.sort((a, b) => b.real.length - a.real.length);
2093
+ linkedPackagesByRoot.set(root, packages);
2094
+ return packages;
2193
2095
  }
2194
- function filterState(state, graphNodeIds) {
2195
- return {
2196
- ...state,
2197
- cells: state.cells.filter((cell) => graphNodeIds.has(cell.graphNodeId)),
2198
- computed: state.computed.filter((computed) => graphNodeIds.has(computed.graphNodeId)),
2199
- storage: state.storage?.filter((cell) => graphNodeIds.has(cell.graphNodeId)),
2200
- sharedDefinitions: state.sharedDefinitions?.filter((definition) => definition.graphNodeIds.some((graphNodeId) => graphNodeIds.has(graphNodeId)))
2201
- };
2202
- }
2203
- function closureSize(graphNodeIds, symbolIds, selected) {
2204
- return graphNodeIds.size + symbolIds.size + Object.values(selected).reduce((total, records) => total + records.size, 0);
2205
- }
2206
- //#endregion
2207
- //#region src/virtual-ids.ts
2208
- const TSRX_SOURCE_FILE = /\.tsrx(?:[?#].*)?$/;
2209
- const MARKLESS_SYMBOL_SOURCE_QUERY_RE = /[?&]markless-symbols(?:[&#]|$)/;
2210
- const MARKLESS_RESUME_SOURCE_QUERY_RE = /[?&]markless-resume(?:[&#]|$)/;
2211
- const MARKLESS_RENDER_DATA_SOURCE_QUERY_RE = /[?&]markless-render-data(?:[&#]|$)/;
2212
- const MARKLESS_REACHED_FROM_SOURCE_QUERY = "markless-reached-from";
2213
- const MARKLESS_REACHED_FROM_ROUTE = "route";
2214
- const MARKLESS_PRERENDER_WAKE_SOURCE_QUERY_RE = /[?&]markless-prerender-wake(?:[&#]|$)/;
2215
- const MARKLESS_ROUTE_SOURCE_QUERY_RE = /[?&]markless-route(?:[&#]|$)/;
2216
- const RESUME_VIRTUAL_ID_RE = /^virtual:markless:resume:([^:]+)$/;
2217
- const PRERENDER_WAKE_VIRTUAL_ID_RE = /^virtual:markless:prerender-wake:([^:]+)$/;
2218
- const SETTLE_VIRTUAL_ID_RE = /^virtual:markless:settle:([^:]+)$/;
2219
- const SYMBOL_VIRTUAL_STRING_RE = /(["'`])((?:virtual:markless:symbol:)[^"'`]+)\1/g;
2220
- function stripBuildPrefix(fileName) {
2221
- return fileName.startsWith("build/") ? fileName.slice(MARKLESS_BUILD_PREFIX.length) : fileName;
2222
- }
2223
- function virtualModuleSourceForLoad(module, options) {
2224
- if (!options.dev || module.type !== "resolver") return module.source;
2225
- if (!module.source.includes("moduleUrls[row[0]]")) return module.source;
2226
- return module.source.replace(SYMBOL_VIRTUAL_STRING_RE, (_match, _quote, virtualId) => JSON.stringify(devBrowserVirtualModuleUrl(virtualId, options.publicPath)));
2227
- }
2228
- function devBrowserSourceModuleUrl(source, _root, publicPath) {
2229
- const path = withQuery(joinURL("@fs", withoutLeadingSlash(source)), { import: null });
2230
- return publicPath ? publicPath(path) : joinURL("/", path);
2231
- }
2232
- function devBrowserVirtualModuleUrl(virtualId, publicPath) {
2233
- const path = joinURL("@id", resolveVirtualId(virtualId).replace("\0", "__x00__"));
2234
- return publicPath ? publicPath(path) : joinURL("/", path);
2235
- }
2236
- function clientSymbolEntries(input, root) {
2237
- if (!input || typeof input !== "object" || Array.isArray(input)) return [];
2238
- const sources = [];
2239
- for (const [name, value] of Object.entries(input)) {
2240
- if (!/symbol/i.test(name)) continue;
2241
- for (const entry of inputEntryValues(value)) if (typeof entry === "string" && TSRX_SOURCE_FILE.test(entry)) sources.push(normalizeInputSource(entry, root));
2096
+ function packageNames(directory) {
2097
+ let entries;
2098
+ try {
2099
+ entries = readdirSync(directory);
2100
+ } catch {
2101
+ return [];
2242
2102
  }
2243
- return sources;
2244
- }
2245
- function inputEntryValues(value) {
2246
- return Array.isArray(value) ? value.flatMap(inputEntryValues) : [value];
2247
- }
2248
- function normalizeInputSource(source, root) {
2249
- const path = pathname(source);
2250
- if (isAbsolute(path)) return path;
2251
- return pathname(resolve(root ?? "", path));
2252
- }
2253
- function isSymbolOnlySourceRequest(id) {
2254
- return MARKLESS_SYMBOL_SOURCE_QUERY_RE.test(id);
2255
- }
2256
- function isScalarPlanSourceRequest(id) {
2257
- return isSymbolOnlySourceRequest(id) && new URLSearchParams(parsePath(id).search).has("markless-scalar-plans");
2258
- }
2259
- function isResumeSourceRequest(id) {
2260
- return MARKLESS_RESUME_SOURCE_QUERY_RE.test(id);
2261
- }
2262
- function isRenderDataSourceRequest(id) {
2263
- return MARKLESS_RENDER_DATA_SOURCE_QUERY_RE.test(id);
2264
- }
2265
- function renderDataReachedFromQuery(id) {
2266
- return new URLSearchParams(parsePath(id).search).get(MARKLESS_REACHED_FROM_SOURCE_QUERY) ?? void 0;
2267
- }
2268
- function isRouteNavigationSourceRequest(id) {
2269
- return MARKLESS_ROUTE_SOURCE_QUERY_RE.test(id) || isRenderDataSourceRequest(id) && renderDataReachedFromQuery(id) === void 0;
2270
- }
2271
- function materializedReachedRenderDataSource(source) {
2272
- return withQuery(source, {
2273
- "markless-render-data": null,
2274
- [MARKLESS_REACHED_FROM_SOURCE_QUERY]: MARKLESS_REACHED_FROM_ROUTE
2275
- });
2276
- }
2277
- function sharedReachedRenderDataRequest(id) {
2278
- if (!isRenderDataSourceRequest(id)) return void 0;
2279
- const reachedFrom = renderDataReachedFromQuery(id);
2280
- return reachedFrom === void 0 || reachedFrom === MARKLESS_REACHED_FROM_ROUTE ? void 0 : withQuery(id, { [MARKLESS_REACHED_FROM_SOURCE_QUERY]: MARKLESS_REACHED_FROM_ROUTE });
2281
- }
2282
- function isPrerenderWakeSourceRequest(id) {
2283
- return MARKLESS_PRERENDER_WAKE_SOURCE_QUERY_RE.test(id);
2284
- }
2285
- function isClientPrimarySourceRequest(id) {
2286
- 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));
2287
- }
2288
- function clientRouteArtifactReference(source) {
2289
- const symbolSource = source.includes("?") ? `${source}&markless-symbols` : `${source}?markless-symbols`;
2290
- const renderDataSource = source.includes("?") ? `${source}&markless-render-data` : `${source}?markless-render-data`;
2291
- return [
2292
- `const [symbolModule, renderDataModule] = await Promise.all([import(${JSON.stringify(symbolSource)}), import(${JSON.stringify(renderDataSource)})]);`,
2293
- "const marklessRouteArtifact = {",
2294
- " renderData: renderDataModule.marklessPrerenderData,",
2295
- " loadSymbol: symbolModule.loadSymbol,",
2296
- "};",
2297
- "export default marklessRouteArtifact;"
2298
- ].join("\n");
2299
- }
2300
- function sourceForSymbolVirtualImporter(importer) {
2301
- if (!importer) return null;
2302
- return symbolVirtualModuleSourceFile(normalizeVirtualId(importer));
2303
- }
2304
- function sourceForResumeVirtualImporter(importer) {
2305
- if (!importer) return null;
2306
- const match = normalizeVirtualId(importer).match(RESUME_VIRTUAL_ID_RE);
2307
- return match?.[1] ? decodeURIComponent(match[1]) : null;
2308
- }
2309
- function resolverVirtualModuleSourceFile(id) {
2310
- const prefix = `${MARKLESS_VIRTUAL_PREFIX}resolver:`;
2311
- return id.startsWith(prefix) ? decodeURIComponent(id.slice(prefix.length)) : null;
2312
- }
2313
- function sourceForTriggerGroupVirtualImporter(importer) {
2314
- if (!importer) return null;
2315
- return triggerGroupVirtualModuleSourceFile(normalizeVirtualId(importer));
2316
- }
2317
- function sourceForPrerenderWakeVirtualImporter(importer) {
2318
- if (!importer) return null;
2319
- const match = normalizeVirtualId(importer).match(PRERENDER_WAKE_VIRTUAL_ID_RE);
2320
- return match?.[1] ? decodeURIComponent(match[1]) : null;
2321
- }
2322
- function sourceForSettleVirtualImporter(importer) {
2323
- if (!importer) return null;
2324
- const match = normalizeVirtualId(importer).match(SETTLE_VIRTUAL_ID_RE);
2325
- return match?.[1] ? decodeURIComponent(match[1]) : null;
2326
- }
2327
- function isRelativeImport(source) {
2328
- return source.startsWith("./") || source.startsWith("../");
2329
- }
2330
- function isMarklessRuntimeModule(id) {
2331
- const path = pathname(id);
2332
- return /[/\\](?:web|runtime|serializer)[/\\]src[/\\].+\.ts$/.test(path);
2333
- }
2334
- function executionLogRuntimeModuleId(id) {
2335
- const path = pathname(id);
2336
- const match = path.match(/[/\\](web|runtime|serializer)[/\\]src[/\\]([^?#]+)\.ts$/);
2337
- return match ? `${match[1]}:${match[2].replace(/[/\\]/g, "/")}` : path;
2338
- }
2339
- function normalizeVirtualId(id) {
2340
- const bare = id.startsWith("\0") ? id.slice(1) : id;
2341
- if (!bare.startsWith("virtual:markless:")) return bare;
2342
- const queryIndex = bare.indexOf("?");
2343
- const segments = (queryIndex === -1 ? bare : bare.slice(0, queryIndex)).slice(17).split(":").map((segment) => {
2103
+ return entries.flatMap((entry) => {
2104
+ if (entry.startsWith(".")) return [];
2105
+ if (!entry.startsWith("@")) return [entry];
2344
2106
  try {
2345
- return encodeURIComponent(decodeURIComponent(segment));
2107
+ return readdirSync(join(directory, entry)).map((scoped) => `${entry}/${scoped}`);
2346
2108
  } catch {
2347
- return segment;
2109
+ return [];
2348
2110
  }
2349
2111
  });
2350
- return `${MARKLESS_VIRTUAL_PREFIX}${segments.join(":")}`;
2351
2112
  }
2352
- function emittedBundleModuleIds(bundle) {
2353
- const ids = /* @__PURE__ */ new Set();
2354
- for (const output of Object.values(bundle)) {
2355
- if (!output || typeof output !== "object") continue;
2356
- const chunk = output;
2357
- if (chunk.type !== "chunk") continue;
2358
- if (typeof chunk.facadeModuleId === "string") ids.add(normalizeVirtualId(chunk.facadeModuleId));
2359
- if (Array.isArray(chunk.moduleIds)) {
2360
- for (const id of chunk.moduleIds) if (typeof id === "string") ids.add(normalizeVirtualId(id));
2361
- }
2113
+ function realpathOf(path) {
2114
+ try {
2115
+ return normalize(realpathSync(path));
2116
+ } catch {
2117
+ return normalize(path);
2362
2118
  }
2363
- return ids;
2364
2119
  }
2365
- function resolveVirtualId(id) {
2366
- if (id.startsWith("\0")) return id;
2367
- return `\0${id}`;
2120
+ /** A symbol module's execution-log identity: its virtual id with the source spelled root-relative. */
2121
+ function symbolExecutionLogId(virtualModuleId, root) {
2122
+ const bare = virtualModuleId.startsWith("\0") ? virtualModuleId.slice(1) : virtualModuleId;
2123
+ const source = symbolVirtualModuleSourceFile(bare);
2124
+ if (source === null) return bare;
2125
+ const encodedSymbolId = bare.slice(bare.lastIndexOf(":") + 1);
2126
+ return symbolVirtualModuleId(moduleIdFor(source, root), decodeURIComponent(encodedSymbolId));
2368
2127
  }
2369
- function pathname(id) {
2370
- return parsePath(id).pathname;
2371
- }
2372
- const CLIENT_ONLY_SOURCE_QUERY_KEYS = /* @__PURE__ */ new Set([
2373
- "markless-render-data",
2374
- "markless-reached-from",
2375
- "markless-symbols",
2376
- "markless-scalar-plans"
2377
- ]);
2378
- function serverSharedSourceRequest(id, environment) {
2379
- if (environment !== "server") return void 0;
2380
- const { pathname: path, search } = parsePath(id);
2381
- if (!search || !TSRX_SOURCE_FILE.test(path)) return void 0;
2382
- const keys = [...new URLSearchParams(search).keys()];
2383
- return keys.length > 0 && keys.every((key) => CLIENT_ONLY_SOURCE_QUERY_KEYS.has(key)) ? path : void 0;
2384
- }
2385
- //#endregion
2386
- //#region src/build/planned-landing.ts
2387
- const MARKLESS_INTERACTION_CLOSURES_ASSET = MARKLESS_INTERACTION_CLOSURES;
2388
- function plannedLandingFiles(bundle) {
2389
- const asset = bundle[MARKLESS_INTERACTION_CLOSURES_ASSET];
2390
- if (asset?.type !== "asset" || asset.source === void 0) return void 0;
2391
- const parsed = JSON.parse(typeof asset.source === "string" ? asset.source : new TextDecoder().decode(asset.source));
2392
- const planned = /* @__PURE__ */ new Map();
2393
- for (const route of parsed.routes) if (!route.fallback && route.files) planned.set(route.route, new Set(route.files.firstUse));
2394
- return planned;
2128
+ const EMBEDDED_SOURCE_RE = new RegExp(`^(${String.fromCharCode(0)}?(?:virtual:markless:[a-z-]+:|imported:))([^:?]*)(.*)$`, "s");
2129
+ /**
2130
+ * Any id a build writes into output, with the file it names spelled by `moduleIdFor`:
2131
+ * a bare path, `virtual:markless:<kind>:<source>...` or `imported:<source>:...`,
2132
+ * the source raw or URI-encoded. Other ids pass through unchanged.
2133
+ */
2134
+ function rootRelativeId(id, root) {
2135
+ if (!root) return id;
2136
+ if (isAbsolute(id)) {
2137
+ const query = id.search(/[?#]/);
2138
+ return query < 0 ? moduleIdFor(id, root) : `${moduleIdFor(id.slice(0, query), root)}${id.slice(query)}`;
2139
+ }
2140
+ const match = EMBEDDED_SOURCE_RE.exec(id);
2141
+ if (!match) return id;
2142
+ const [, prefix, spelled, rest] = match;
2143
+ let source;
2144
+ try {
2145
+ source = decodeURIComponent(spelled);
2146
+ } catch {
2147
+ return id;
2148
+ }
2149
+ if (!isAbsolute(source)) return id;
2150
+ const moduleId = moduleIdFor(source, root);
2151
+ return `${prefix}${spelled === source ? moduleId : encodeURIComponent(moduleId)}${rest}`;
2395
2152
  }
2396
2153
  //#endregion
2397
2154
  //#region src/build/warm-packs.ts
@@ -2417,7 +2174,8 @@ const PACK_COST_MODEL = {
2417
2174
  fileOverheadGzipKb: .5,
2418
2175
  lazySiblingOverheadGzipKb: 1,
2419
2176
  minDeferredGzipKb: 1,
2420
- sourceGzipRatio: .25
2177
+ sourceGzipRatio: .25,
2178
+ packedModuleWrapperBytes: 64
2421
2179
  };
2422
2180
  function estimatedGzipKb(sourceLength, model = PACK_COST_MODEL) {
2423
2181
  return sourceLength * model.sourceGzipRatio / 1024;
@@ -2622,7 +2380,77 @@ function planRoutePackGroups(input) {
2622
2380
  }
2623
2381
  }
2624
2382
  }
2625
- return input.pagesLoadOneRoute ? splitFrameworkFromApp(splitStartupPacksByStaticReach(groups, roots, sources, owners, input), input) : groups;
2383
+ for (const [id, pack] of alternativeDeferredPacks(input.modules, groups)) groups.set(id, pack);
2384
+ return splitOversizedLazyPacks(input.pagesLoadOneRoute ? splitOversizedStartupPacks(splitFrameworkFromApp(splitStartupPacksByStaticReach(groups, roots, sources, owners, input), input), input) : groups, input);
2385
+ }
2386
+ function splitOversizedStartupPacks(groups, input) {
2387
+ const cap = input.maxPackBytes;
2388
+ if (!cap) return groups;
2389
+ const packs = /* @__PURE__ */ new Map();
2390
+ for (const [id, group] of groups) if (isStartupPack(group)) push(packs, group, id);
2391
+ const sizeOf = (id) => (input.modules.get(id)?.size ?? 0) + PACK_COST_MODEL.packedModuleWrapperBytes;
2392
+ const routeRoots = [...input.routes.values()].flat();
2393
+ for (const [group, ids] of packs) {
2394
+ if (ids.reduce((sum, id) => sum + sizeOf(id), 0) <= cap) continue;
2395
+ const members = new Set(ids);
2396
+ const order = [];
2397
+ const seen = /* @__PURE__ */ new Set();
2398
+ const visit = (start) => {
2399
+ const stack = [[start, 0]];
2400
+ seen.add(start);
2401
+ while (stack.length) {
2402
+ const top = stack[stack.length - 1];
2403
+ const dependencies = input.modules.get(top[0])?.dependencies ?? [];
2404
+ const next = dependencies.slice(top[1]).findIndex((dependency) => members.has(dependency) && !seen.has(dependency));
2405
+ if (next < 0) {
2406
+ order.push(top[0]);
2407
+ stack.pop();
2408
+ continue;
2409
+ }
2410
+ const dependency = dependencies[top[1] + next];
2411
+ top[1] += next + 1;
2412
+ seen.add(dependency);
2413
+ stack.push([dependency, 0]);
2414
+ }
2415
+ };
2416
+ for (const id of [...routeRoots.filter((id) => members.has(id)), ...[...ids].sort()]) if (!seen.has(id)) visit(id);
2417
+ let piece = 1;
2418
+ let filled = 0;
2419
+ for (const id of order) {
2420
+ const size = sizeOf(id);
2421
+ if (filled > 0 && filled + size > cap) {
2422
+ piece++;
2423
+ filled = 0;
2424
+ }
2425
+ filled += size;
2426
+ if (piece > 1) groups.set(id, `${group}~${piece}`);
2427
+ }
2428
+ }
2429
+ return groups;
2430
+ }
2431
+ function splitOversizedLazyPacks(groups, input) {
2432
+ const cap = input.maxPackBytes;
2433
+ if (!cap) return groups;
2434
+ const packs = /* @__PURE__ */ new Map();
2435
+ for (const [id, group] of groups) if (!isStartupPack(group)) push(packs, group, id);
2436
+ const sizeOf = (id) => (input.modules.get(id)?.size ?? 0) + PACK_COST_MODEL.packedModuleWrapperBytes;
2437
+ for (const [group, ids] of packs) {
2438
+ if (ids.reduce((sum, id) => sum + sizeOf(id), 0) <= cap) continue;
2439
+ const bySource = /* @__PURE__ */ new Map();
2440
+ for (const id of ids) push(bySource, input.modules.get(id)?.source ?? id, id);
2441
+ let part = 0;
2442
+ let filled = Infinity;
2443
+ for (const [, members] of [...bySource].sort(([left], [right]) => left.localeCompare(right))) {
2444
+ const size = members.reduce((sum, id) => sum + sizeOf(id), 0);
2445
+ if (filled + size > cap) {
2446
+ part++;
2447
+ filled = 0;
2448
+ }
2449
+ filled += size;
2450
+ for (const id of members) groups.set(id, part === 1 ? group : `${group}${PACK_PART_MARK}${part}`);
2451
+ }
2452
+ }
2453
+ return groups;
2626
2454
  }
2627
2455
  function splitFrameworkFromApp(groups, input) {
2628
2456
  const halves = /* @__PURE__ */ new Map();
@@ -2653,6 +2481,15 @@ function splitStartupPacksByStaticReach(groups, roots, sources, owners, input) {
2653
2481
  return !!module && !module.navigationOnly && (!flagged || !!module.firstEvent);
2654
2482
  };
2655
2483
  const handler = (id) => !!input.modules.get(id)?.handler;
2484
+ const seedSiblings = /* @__PURE__ */ new Map();
2485
+ const seedSiblingsOf = (source) => {
2486
+ let list = seedSiblings.get(source);
2487
+ if (!list) seedSiblings.set(source, list = (sources.get(source) ?? []).filter(seed).map((id) => ({
2488
+ id,
2489
+ handler: handler(id)
2490
+ })));
2491
+ return list;
2492
+ };
2656
2493
  const closure = (route, start, path) => {
2657
2494
  const reached = /* @__PURE__ */ new Set();
2658
2495
  const handlers = /* @__PURE__ */ new Set();
@@ -2664,8 +2501,9 @@ function splitStartupPacksByStaticReach(groups, roots, sources, owners, input) {
2664
2501
  if (!module) continue;
2665
2502
  reached.add(id);
2666
2503
  pending.push(...module.dependencies);
2667
- for (const sibling of module.source ? sources.get(module.source) ?? [] : []) if (seed(sibling) && sibling !== id) if (handler(sibling)) handlers.add(sibling);
2668
- else pending.push(sibling);
2504
+ if (!module.source) continue;
2505
+ for (const sibling of seedSiblingsOf(module.source)) if (sibling.id !== id) if (sibling.handler) handlers.add(sibling.id);
2506
+ else pending.push(sibling.id);
2669
2507
  }
2670
2508
  return {
2671
2509
  reached,
@@ -2673,11 +2511,13 @@ function splitStartupPacksByStaticReach(groups, roots, sources, owners, input) {
2673
2511
  };
2674
2512
  };
2675
2513
  const staticReach = /* @__PURE__ */ new Set();
2514
+ const ownHandlers = /* @__PURE__ */ new Map();
2515
+ for (const [id, routes] of owners) if (routes.size === 1 && seed(id) && handler(id)) push(ownHandlers, [...routes][0], id);
2676
2516
  for (const [route, ids] of input.routes) {
2677
2517
  const visited = /* @__PURE__ */ new Set();
2678
2518
  const first = closure(route, ids.filter((id) => seed(id) && !handler(id)), visited);
2679
2519
  for (const id of first.reached) visited.add(id);
2680
- const candidates = [...first.handlers, ...[...owners].filter(([id, routes]) => routes.size === 1 && routes.has(route) && seed(id) && handler(id)).map(([id]) => id)];
2520
+ const candidates = [...first.handlers, ...ownHandlers.get(route) ?? []];
2681
2521
  while (candidates.length) {
2682
2522
  const id = candidates.pop();
2683
2523
  if (visited.has(id)) continue;
@@ -2723,6 +2563,14 @@ function startupPackOfLazy(name) {
2723
2563
  return name.replace(new RegExp(`^(route|shared)${LAZY_PACK_MARK}`), "$1");
2724
2564
  }
2725
2565
  const LAZY_PACK_MARK = "-lazy";
2566
+ const PACK_PART_MARK = "-part";
2567
+ function packOfPiece(name) {
2568
+ return name.replace(PACK_PIECES, "");
2569
+ }
2570
+ const PACK_PIECES = /(?:~\d+)+$/;
2571
+ function packOfPart(name) {
2572
+ return name.replace(new RegExp(`${PACK_PART_MARK}\\d+$`), "");
2573
+ }
2726
2574
  const FRAMEWORK_PIECE = "~1";
2727
2575
  const ROUTE_KEY_SEPARATOR = "\n";
2728
2576
  const SHARED_MARK = " ";
@@ -2747,5 +2595,45 @@ function push(map, key, value) {
2747
2595
  if (values) values.push(value);
2748
2596
  else map.set(key, [value]);
2749
2597
  }
2598
+ /**
2599
+ * An app module that imports several deferred targets picks one per run (a table of loaders), so
2600
+ * each target, with the code only it reaches, gets a deferred pack of its own instead of the one
2601
+ * every deferred module shares: choosing one never downloads the others.
2602
+ */
2603
+ function alternativeDeferredPacks(modules, groups) {
2604
+ const deferred = (id) => groups.get(id) === MARKLESS_DEFERRED_PACK;
2605
+ const alternatives = /* @__PURE__ */ new Set();
2606
+ const entries = /* @__PURE__ */ new Set();
2607
+ for (const [id, module] of modules) {
2608
+ const targets = (module.dynamicDependencies ?? []).filter(deferred);
2609
+ for (const target of targets) if (!deferred(id)) entries.add(target);
2610
+ if (!module.app || targets.length < 2) continue;
2611
+ for (const target of targets) if (modules.get(target)?.app) alternatives.add(target);
2612
+ }
2613
+ const packs = /* @__PURE__ */ new Map();
2614
+ if (alternatives.size === 0) return packs;
2615
+ const closure = (from, stop) => {
2616
+ const reached = /* @__PURE__ */ new Set();
2617
+ const pending = [from];
2618
+ for (let id = pending.pop(); id !== void 0; id = pending.pop()) {
2619
+ if (reached.has(id) || !deferred(id) || id !== from && stop(id)) continue;
2620
+ reached.add(id);
2621
+ const module = modules.get(id);
2622
+ pending.push(...module?.dependencies ?? [], ...module?.dynamicDependencies ?? []);
2623
+ }
2624
+ return reached;
2625
+ };
2626
+ const shared = /* @__PURE__ */ new Set();
2627
+ for (const entry of entries) if (!alternatives.has(entry)) for (const id of closure(entry, (id) => alternatives.has(id))) shared.add(id);
2628
+ const owner = /* @__PURE__ */ new Map();
2629
+ for (const root of alternatives) for (const id of closure(root, (id) => alternatives.has(id))) owner.set(id, owner.has(id) && owner.get(id) !== root ? null : root);
2630
+ const labels = /* @__PURE__ */ new Map();
2631
+ for (const [id, root] of owner) {
2632
+ if (root === null || shared.has(id) || !modules.get(id)?.app) continue;
2633
+ if (!labels.has(root)) labels.set(root, `${MARKLESS_DEFERRED_PACK}-alt${labels.size}`);
2634
+ packs.set(id, labels.get(root));
2635
+ }
2636
+ return packs;
2637
+ }
2750
2638
  //#endregion
2751
- 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 };
2639
+ export { EXECUTION_LOG_CHUNK_MODULE_PATTERN as $, emitSourceModule as A, symbolVirtualModuleSourceFile as B, MARKLESS_VIRTUAL_PREFIX as C, emitOverlayLoaderInstall as D, demandsOverlay as E, resumeVirtualModuleId as F, sharedInlineSourcesModuleId as G, emitSymbolRouteTable as H, rewriteSymbolModuleExport as I, compilePrerenderInlineResumerSources as J, sharedInlineSourcesModuleSource as K, scopedSymbolExportName as L, payloadModule as M, prerenderWakeVirtualModuleId as N, emitResumeModule as O, prerenderWakeVirtualModuleSourceFile as P, PROTOCOL_BLOCK_START_COMMENT as Q, settleVirtualModuleId as R, withoutMachinePaths as S, STORAGE_FREE_RESUME_ENTRY_SPECIFIER as T, MARKLESS_SCALAR_PLAN_SOURCE_QUERY as U, withoutFirstUse as V, isSharedInlineSourcesModuleId as W, createInlineDeferTriggerSource as X, INLINE_DEFER_LOADER_SOURCE as Y, inlineDeferSource as Z, sourceForModuleId as _, isStartupPack as a, hasExecutionLogModuleHook as at, machinePathRoots as b, packOfPart as c, normalizeExecutionLogMode as ct, startupPackOfLazy as d, EXECUTION_LOG_DISPATCH_MODULE_IDS as et, PACK_COST_MODEL as f, rootRelativeId as g, moduleIdFor as h, isMarklessNavigationPack as i, executionLogVirtualModuleSource as it, encodedSymbolSource as j, emitSettleModule as k, packOfPiece as l, requalifyExecutionLogModuleHook as lt, warmPacksSuffix as m, MARKLESS_NAVIGATION_PACK_PREFIX as n, MARKLESS_EXECUTION_LOG_MODULE_ID as nt, lazyStartupPackName as o, injectExecutionLogModuleHook as ot, warmEvaluatedImports as p, compileInlineResumerSources as q, isMarklessDeferredPack as r, executionLogActivationInjection as rt, marklessDeferredChunkFileNames as s, isExecutionLogChunk as st, MARKLESS_DEFERRED_PACK as t, MARKLESS_EXECUTION_LOG_GLOBAL as tt, planRoutePackGroups as u, symbolExecutionLogId as v, RESUME_ENTRY_SPECIFIER as w, rootRelativeRegionComments as x, machinePathLeaks as y, symbolVirtualModuleId as z };