elegance-js 2.1.37 → 3.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (138) hide show
  1. package/bin/bootstrap.js +18 -0
  2. package/bin/run.js +2 -0
  3. package/dist/build/common.d.ts +147 -0
  4. package/dist/build/common.d.ts.map +1 -0
  5. package/dist/build/common.js +599 -0
  6. package/dist/build/dev.d.ts +2 -0
  7. package/dist/build/dev.d.ts.map +1 -0
  8. package/dist/build/dev.js +234 -0
  9. package/dist/build/prod.d.ts +2 -0
  10. package/dist/build/prod.d.ts.map +1 -0
  11. package/dist/build/prod.js +212 -0
  12. package/dist/build/render.d.ts +29 -0
  13. package/dist/build/render.d.ts.map +1 -0
  14. package/dist/build/render.js +234 -0
  15. package/dist/client.d.ts +13 -0
  16. package/dist/client.d.ts.map +1 -0
  17. package/dist/client.js +677 -0
  18. package/dist/config.d.ts +7 -0
  19. package/dist/config.d.ts.map +1 -0
  20. package/dist/config.js +80 -0
  21. package/dist/constants.d.ts +10 -0
  22. package/dist/constants.d.ts.map +1 -0
  23. package/dist/constants.js +20 -0
  24. package/dist/elements.d.ts +2 -0
  25. package/dist/elements.d.ts.map +1 -0
  26. package/dist/elements.js +14 -0
  27. package/dist/error.d.ts +20 -0
  28. package/dist/error.d.ts.map +1 -0
  29. package/dist/error.js +123 -0
  30. package/dist/globals.d.ts +6 -0
  31. package/dist/globals.d.ts.map +1 -0
  32. package/dist/globals.js +106 -0
  33. package/dist/logger.d.ts +32 -0
  34. package/dist/logger.d.ts.map +1 -0
  35. package/dist/logger.js +72 -0
  36. package/dist/page-tools.d.ts +19 -0
  37. package/dist/page-tools.d.ts.map +1 -0
  38. package/dist/page-tools.js +141 -0
  39. package/dist/processing/oxc.d.ts +17 -0
  40. package/dist/processing/oxc.d.ts.map +1 -0
  41. package/dist/processing/oxc.js +938 -0
  42. package/dist/processing/taglist.d.ts +2 -0
  43. package/dist/processing/taglist.d.ts.map +1 -0
  44. package/dist/processing/taglist.js +215 -0
  45. package/dist/processing/tsx.d.ts +2 -0
  46. package/dist/processing/tsx.d.ts.map +1 -0
  47. package/dist/processing/tsx.js +131 -0
  48. package/dist/run.d.ts +3 -0
  49. package/dist/run.d.ts.map +1 -0
  50. package/dist/run.js +147 -0
  51. package/dist/server/dev.d.ts +2 -0
  52. package/dist/server/dev.d.ts.map +1 -0
  53. package/dist/server/dev.js +10 -0
  54. package/dist/server/prod.d.ts +2 -0
  55. package/dist/server/prod.d.ts.map +1 -0
  56. package/dist/server/prod.js +42 -0
  57. package/dist/server/security.d.ts +64 -0
  58. package/dist/server/security.d.ts.map +1 -0
  59. package/dist/server/security.js +120 -0
  60. package/dist/server/server.d.ts +73 -99
  61. package/dist/server/server.d.ts.map +1 -0
  62. package/dist/server/server.js +830 -680
  63. package/dist/types/component.d.ts +85 -0
  64. package/dist/types/component.d.ts.map +1 -0
  65. package/dist/types/component.js +0 -0
  66. package/dist/types/config.d.ts +12 -0
  67. package/dist/types/config.d.ts.map +1 -0
  68. package/dist/types/config.js +0 -0
  69. package/dist/types/elements.d.ts +412 -0
  70. package/dist/types/elements.d.ts.map +1 -0
  71. package/dist/types/elements.js +0 -0
  72. package/dist/types/index.d.ts +9 -0
  73. package/dist/types/index.d.ts.map +1 -0
  74. package/dist/types/index.js +5 -0
  75. package/dist/types/jsx.d.ts +976 -0
  76. package/dist/types/jsx.d.ts.map +1 -0
  77. package/dist/types/jsx.js +0 -0
  78. package/dist/types/server-actions.d.ts +60 -0
  79. package/dist/types/server-actions.d.ts.map +1 -0
  80. package/dist/types/server-actions.js +0 -0
  81. package/dist/user-utils.d.ts +23 -0
  82. package/dist/user-utils.d.ts.map +1 -0
  83. package/dist/user-utils.js +61 -0
  84. package/package.json +47 -28
  85. package/README.md +0 -4
  86. package/dist/client/effect.d.ts +0 -27
  87. package/dist/client/effect.js +0 -37
  88. package/dist/client/eventListener.d.ts +0 -39
  89. package/dist/client/eventListener.js +0 -52
  90. package/dist/client/loadHook.d.ts +0 -34
  91. package/dist/client/loadHook.js +0 -52
  92. package/dist/client/observer.d.ts +0 -36
  93. package/dist/client/observer.js +0 -66
  94. package/dist/client/runtime.d.ts +0 -105
  95. package/dist/client/runtime.js +0 -624
  96. package/dist/client/state.d.ts +0 -40
  97. package/dist/client/state.js +0 -110
  98. package/dist/compilation/compiler.d.ts +0 -163
  99. package/dist/compilation/compiler.js +0 -1164
  100. package/dist/components/ClientComponent.d.ts +0 -22
  101. package/dist/components/ClientComponent.js +0 -55
  102. package/dist/components/Link.d.ts +0 -16
  103. package/dist/components/Link.js +0 -21
  104. package/dist/components/Portal.d.ts +0 -2
  105. package/dist/components/Portal.js +0 -2
  106. package/dist/elements/element.d.ts +0 -87
  107. package/dist/elements/element.js +0 -33
  108. package/dist/elements/element_list.d.ts +0 -7
  109. package/dist/elements/element_list.js +0 -65
  110. package/dist/elements/raw.d.ts +0 -14
  111. package/dist/elements/raw.js +0 -78
  112. package/dist/elements/specific_props.d.ts +0 -750
  113. package/dist/elements/specific_props.js +0 -1
  114. package/dist/global.d.ts +0 -229
  115. package/dist/global.js +0 -1
  116. package/dist/index.d.ts +0 -16
  117. package/dist/index.js +0 -12
  118. package/dist/server/layout.d.ts +0 -34
  119. package/dist/server/layout.js +0 -6
  120. package/dist/server/log.d.ts +0 -12
  121. package/dist/server/log.js +0 -64
  122. package/dist/server/page.d.ts +0 -32
  123. package/dist/server/page.js +0 -6
  124. package/dist/server/runtime.d.ts +0 -6
  125. package/dist/server/runtime.js +0 -92
  126. package/scripts/bootstrap.js +0 -95
  127. package/scripts/bootstrap_files/elegance.txt +0 -40
  128. package/scripts/bootstrap_files/index.txt +0 -3
  129. package/scripts/bootstrap_files/layout.txt +0 -46
  130. package/scripts/bootstrap_files/middleware.txt +0 -18
  131. package/scripts/bootstrap_files/page.txt +0 -123
  132. package/scripts/bootstrap_files/route.txt +0 -6
  133. package/scripts/elegance_dev.ts +0 -42
  134. package/scripts/elegance_prod.ts +0 -42
  135. package/scripts/elegance_static.ts +0 -26
  136. package/scripts/prod.js +0 -13
  137. package/scripts/run.js +0 -13
  138. package/scripts/static.js +0 -13
@@ -0,0 +1,938 @@
1
+ import { parseSync } from "oxc-parser";
2
+ import { ALL_TAGS } from "./taglist.js";
3
+ import { createHash } from "node:crypto";
4
+ import { isBuiltin } from "node:module";
5
+ import { richError } from "../error.js";
6
+ const ALL_TAGS_SET = new Set(ALL_TAGS);
7
+ const CHILD_KEYS = {
8
+ Program: ["body"],
9
+ ExpressionStatement: ["expression"],
10
+ BlockStatement: ["body"],
11
+ ReturnStatement: ["argument"],
12
+ IfStatement: ["test", "consequent", "alternate"],
13
+ WhileStatement: ["test", "body"],
14
+ ForStatement: ["init", "test", "update", "body"],
15
+ ForInStatement: ["left", "right", "body"],
16
+ ForOfStatement: ["left", "right", "body"],
17
+ SwitchStatement: ["discriminant", "cases"],
18
+ SwitchCase: ["test", "consequent"],
19
+ TryStatement: ["block", "handler", "finalizer"],
20
+ CatchClause: ["param", "body"],
21
+ ThrowStatement: ["argument"],
22
+ LabeledStatement: ["body"],
23
+ VariableDeclaration: ["declarations"],
24
+ VariableDeclarator: ["id", "init"],
25
+ FunctionDeclaration: ["id", "params", "body"],
26
+ FunctionExpression: ["id", "params", "body"],
27
+ ArrowFunctionExpression: ["params", "body"],
28
+ ClassDeclaration: ["id", "superClass", "body"],
29
+ ClassExpression: ["id", "superClass", "body"],
30
+ ClassBody: ["body"],
31
+ MethodDefinition: ["key", "value"],
32
+ PropertyDefinition: ["key", "value"],
33
+ StaticBlock: ["body"],
34
+ CallExpression: ["callee", "arguments"],
35
+ NewExpression: ["callee", "arguments"],
36
+ MemberExpression: ["object", "property"],
37
+ StaticMemberExpression: ["object", "property"],
38
+ ComputedMemberExpression: ["object", "property"],
39
+ TaggedTemplateExpression: ["tag", "quasi"],
40
+ TemplateLiteral: ["quasis", "expressions"],
41
+ AssignmentExpression: ["left", "right"],
42
+ AssignmentPattern: ["left", "right"],
43
+ BinaryExpression: ["left", "right"],
44
+ LogicalExpression: ["left", "right"],
45
+ ConditionalExpression: ["test", "consequent", "alternate"],
46
+ SequenceExpression: ["expressions"],
47
+ UnaryExpression: ["argument"],
48
+ UpdateExpression: ["argument"],
49
+ SpreadElement: ["argument"],
50
+ RestElement: ["argument"],
51
+ YieldExpression: ["argument"],
52
+ AwaitExpression: ["argument"],
53
+ ObjectExpression: ["properties"],
54
+ Property: ["key", "value"],
55
+ ArrayExpression: ["elements"],
56
+ ArrayPattern: ["elements"],
57
+ ObjectPattern: ["properties"],
58
+ ImportDeclaration: ["specifiers"],
59
+ ImportSpecifier: ["imported", "local"],
60
+ ImportDefaultSpecifier: ["local"],
61
+ ImportNamespaceSpecifier: ["local"],
62
+ ExportNamedDeclaration: ["declaration", "specifiers"],
63
+ ExportDefaultDeclaration: ["declaration"],
64
+ ExportAllDeclaration: ["exported"],
65
+ ExportSpecifier: ["local", "exported"],
66
+ ChainExpression: ["expression"],
67
+ ParenthesizedExpression: ["expression"],
68
+ TSAsExpression: ["expression"],
69
+ TSSatisfiesExpression: ["expression"],
70
+ TSNonNullExpression: ["expression"],
71
+ TSTypeAssertion: ["expression"],
72
+ TSInstantiationExpression: ["expression"]
73
+ };
74
+ function generateAtomId(filePath, index) {
75
+ const normalized = filePath.replace(/\\/g, "/");
76
+ const str = `${normalized}::atom${index}`;
77
+ return createHash("sha256").update(str).digest("base64url").slice(0, 7);
78
+ }
79
+ function collectPatternNames(pattern, cb) {
80
+ if (!pattern) return;
81
+ switch (pattern.type) {
82
+ case "Identifier":
83
+ cb(pattern.name);
84
+ break;
85
+ case "ObjectPattern":
86
+ for (const prop of pattern.properties) {
87
+ collectPatternNames(
88
+ prop.type === "RestElement" ? prop.argument : prop.value,
89
+ cb
90
+ );
91
+ }
92
+ break;
93
+ case "ArrayPattern":
94
+ for (const el of pattern.elements) {
95
+ if (el) collectPatternNames(el, cb);
96
+ }
97
+ break;
98
+ case "AssignmentPattern":
99
+ collectPatternNames(pattern.left, cb);
100
+ break;
101
+ case "RestElement":
102
+ collectPatternNames(pattern.argument, cb);
103
+ break;
104
+ }
105
+ }
106
+ function forEachChild(node, cb) {
107
+ const keys = CHILD_KEYS[node.type];
108
+ if (!keys) return;
109
+ for (const key of keys) {
110
+ const val = node[key];
111
+ if (!val) continue;
112
+ if (Array.isArray(val)) {
113
+ for (const item of val) {
114
+ if (item && typeof item === "object" && typeof item.type === "string") cb(item);
115
+ }
116
+ } else if (typeof val === "object" && typeof val.type === "string") {
117
+ cb(val);
118
+ }
119
+ }
120
+ }
121
+ function collectAllIdentifiers(node, into) {
122
+ if (!node || typeof node !== "object") return;
123
+ if (node.type === "Identifier") {
124
+ into.add(node.name);
125
+ return;
126
+ }
127
+ if ((node.type === "MemberExpression" || node.type === "StaticMemberExpression") && !node.computed) {
128
+ collectAllIdentifiers(node.object, into);
129
+ return;
130
+ }
131
+ forEachChild(node, (child) => collectAllIdentifiers(child, into));
132
+ }
133
+ function collectIdentifiersWithOffsets(node, into) {
134
+ if (!node || typeof node !== "object") return;
135
+ if (node.type === "Identifier") {
136
+ if (!into.has(node.name)) {
137
+ into.set(node.name, node.start);
138
+ }
139
+ return;
140
+ }
141
+ if ((node.type === "MemberExpression" || node.type === "StaticMemberExpression") && !node.computed) {
142
+ collectIdentifiersWithOffsets(node.object, into);
143
+ return;
144
+ }
145
+ forEachChild(node, (child) => collectIdentifiersWithOffsets(child, into));
146
+ }
147
+ function offsetToLineCol(src, offset) {
148
+ let line = 1, col = 1;
149
+ const end = Math.min(offset, src.length);
150
+ for (let i = 0; i < end; i++) {
151
+ if (src[i] === "\n") {
152
+ line++;
153
+ col = 1;
154
+ } else {
155
+ col++;
156
+ }
157
+ }
158
+ return { line, col };
159
+ }
160
+ function getSourceLine(src, offset) {
161
+ const lineStart = src.lastIndexOf("\n", offset - 1) + 1;
162
+ const lineEnd = src.indexOf("\n", offset);
163
+ return src.slice(lineStart, lineEnd === -1 ? src.length : lineEnd);
164
+ }
165
+ function formatChainHop(src, filePath, _name, entry) {
166
+ const { line, col } = offsetToLineCol(src, entry.offset);
167
+ const sourceLine = getSourceLine(src, entry.offset);
168
+ const pipe = " | ";
169
+ const caretLine = `${pipe}${" ".repeat(col - 1)}^`;
170
+ return ` at ${entry.from} (${filePath}:${line}:${col})
171
+ ${pipe}${sourceLine}
172
+ ${caretLine}`;
173
+ }
174
+ function formatReachabilityChain(src, filePath, name, reachableFrom) {
175
+ const hops = [];
176
+ let cur = name;
177
+ const visited = /* @__PURE__ */ new Set();
178
+ while (reachableFrom.has(cur) && !visited.has(cur)) {
179
+ visited.add(cur);
180
+ const entry = reachableFrom.get(cur);
181
+ hops.unshift({ name: cur, entry });
182
+ cur = entry.from;
183
+ }
184
+ return hops.map(({ name: n, entry }) => formatChainHop(src, filePath, n, entry)).join("\n");
185
+ }
186
+ function applyEdits(source, edits) {
187
+ if (edits.length === 0) return source;
188
+ const sorted = [...edits].sort((a, b) => a.start - b.start);
189
+ for (let i = 0; i < sorted.length - 1; i++) {
190
+ if (sorted[i].end > sorted[i + 1].start) {
191
+ throw new Error(
192
+ `Overlapping edits: [${sorted[i].start},${sorted[i].end}) overlaps [${sorted[i + 1].start},${sorted[i + 1].end})`
193
+ );
194
+ }
195
+ }
196
+ const parts = [];
197
+ let cursor = 0;
198
+ for (const e of sorted) {
199
+ if (cursor < e.start) parts.push(source.slice(cursor, e.start));
200
+ if (e.replacement) parts.push(e.replacement);
201
+ cursor = e.end;
202
+ }
203
+ if (cursor < source.length) parts.push(source.slice(cursor));
204
+ return parts.join("");
205
+ }
206
+ function reconstructImport(node, reachableSpecs) {
207
+ const src = node.source.value;
208
+ const defaultSpec = reachableSpecs.find((s) => s.type === "ImportDefaultSpecifier");
209
+ const nsSpec = reachableSpecs.find((s) => s.type === "ImportNamespaceSpecifier");
210
+ const namedSpecs = reachableSpecs.filter((s) => s.type === "ImportSpecifier");
211
+ const parts = [];
212
+ if (defaultSpec) parts.push(defaultSpec.local.name);
213
+ if (nsSpec) parts.push(`* as ${nsSpec.local.name}`);
214
+ if (namedSpecs.length > 0) {
215
+ const named = namedSpecs.map((s) => {
216
+ const imp = s.imported.name ?? s.imported.value;
217
+ return imp !== s.local.name ? `${imp} as ${s.local.name}` : s.local.name;
218
+ });
219
+ parts.push(`{ ${named.join(", ")} }`);
220
+ }
221
+ return `import ${parts.join(", ")} from "${src}";`;
222
+ }
223
+ function extractDeclaredNames(node, into) {
224
+ switch (node.type) {
225
+ case "ImportDeclaration":
226
+ for (const spec of node.specifiers ?? []) into.add(spec.local.name);
227
+ break;
228
+ case "VariableDeclaration":
229
+ for (const decl of node.declarations) collectPatternNames(decl.id, (n) => into.add(n));
230
+ break;
231
+ case "FunctionDeclaration":
232
+ case "ClassDeclaration":
233
+ if (node.id?.name) into.add(node.id.name);
234
+ break;
235
+ case "ExportNamedDeclaration":
236
+ if (node.declaration) {
237
+ extractDeclaredNames(node.declaration, into);
238
+ } else {
239
+ for (const spec of node.specifiers ?? []) into.add(spec.local.name);
240
+ }
241
+ break;
242
+ case "ExportDefaultDeclaration":
243
+ if (node.declaration?.id?.name) into.add(node.declaration.id.name);
244
+ break;
245
+ }
246
+ }
247
+ function findContainingBodyNode(body, callStart, callEnd) {
248
+ let lo = 0, hi = body.length - 1, best = -1;
249
+ while (lo <= hi) {
250
+ const mid = lo + hi >> 1;
251
+ if (body[mid].start <= callStart) {
252
+ best = mid;
253
+ lo = mid + 1;
254
+ } else {
255
+ hi = mid - 1;
256
+ }
257
+ }
258
+ if (best === -1) return null;
259
+ const node = body[best];
260
+ return node.end >= callEnd ? node : null;
261
+ }
262
+ function nodeContainsAnyCall(sortedCalls, nodeStart, nodeEnd) {
263
+ let lo = 0, hi = sortedCalls.length - 1;
264
+ while (lo <= hi) {
265
+ const mid = lo + hi >> 1;
266
+ if (sortedCalls[mid].start < nodeStart) lo = mid + 1;
267
+ else hi = mid - 1;
268
+ }
269
+ return lo < sortedCalls.length && sortedCalls[lo].start >= nodeStart && sortedCalls[lo].end <= nodeEnd;
270
+ }
271
+ function findSpecialCalls(node, componentCalls, atomCalls, onPageLoadCalls) {
272
+ if (!node || typeof node !== "object") return;
273
+ if (node.type === "CallExpression" && node.callee?.type === "Identifier") {
274
+ const name = node.callee.name;
275
+ if (name === "component" && node.arguments?.length === 1 && node.arguments[0]?.type === "ObjectExpression") {
276
+ componentCalls.push(node);
277
+ } else if (name === "_getAtom") {
278
+ atomCalls.push(node);
279
+ return;
280
+ } else if (name === "onPageLoad") {
281
+ onPageLoadCalls.push(node);
282
+ return;
283
+ }
284
+ }
285
+ forEachChild(node, (child) => findSpecialCalls(child, componentCalls, atomCalls, onPageLoadCalls));
286
+ }
287
+ function applyReachabilityDCECore(source, ast, filePath, extraSeeds) {
288
+ const body = ast.program.body;
289
+ const bindingMap = /* @__PURE__ */ new Map();
290
+ for (const node of body) {
291
+ if (node.type === "ImportDeclaration") {
292
+ for (const spec of node.specifiers ?? []) bindingMap.set(spec.local.name, node);
293
+ } else if (node.type === "VariableDeclaration") {
294
+ for (const decl of node.declarations)
295
+ collectPatternNames(decl.id, (name) => bindingMap.set(name, node));
296
+ } else if (node.type === "FunctionDeclaration" && node.id) {
297
+ bindingMap.set(node.id.name, node);
298
+ } else if (node.type === "ClassDeclaration" && node.id) {
299
+ bindingMap.set(node.id.name, node);
300
+ } else if (node.type === "ExportDefaultDeclaration" && node.declaration?.type === "FunctionDeclaration" && node.declaration.id) {
301
+ bindingMap.set(node.declaration.id.name, node.declaration);
302
+ }
303
+ }
304
+ const CLIENT_ENTRY_PROPS = /* @__PURE__ */ new Set(["view", "onMount", "onUnmount", "onNavigate", "atoms"]);
305
+ const reachable = /* @__PURE__ */ new Set();
306
+ const reachableFrom = /* @__PURE__ */ new Map();
307
+ function addReachable(name, from, offset) {
308
+ if (!reachable.has(name)) {
309
+ reachable.add(name);
310
+ reachableFrom.set(name, { from, offset });
311
+ }
312
+ }
313
+ const componentCalls = [];
314
+ const atomCalls = [];
315
+ const onPageLoadCalls = [];
316
+ for (const node of body) {
317
+ findSpecialCalls(node, componentCalls, atomCalls, onPageLoadCalls);
318
+ }
319
+ const componentCallToVar = /* @__PURE__ */ new Map();
320
+ for (const call of componentCalls) {
321
+ const node = findContainingBodyNode(body, call.start, call.end);
322
+ if (node?.type === "VariableDeclaration") {
323
+ for (const decl of node.declarations) {
324
+ collectPatternNames(decl.id, (name) => {
325
+ if (!componentCallToVar.has(call)) componentCallToVar.set(call, name);
326
+ });
327
+ }
328
+ }
329
+ }
330
+ for (const call of componentCalls) {
331
+ const obj = call.arguments[0];
332
+ const componentVar = componentCallToVar.get(call) ?? "unknown";
333
+ for (const prop of obj.properties) {
334
+ if (prop.type === "Property" && prop.key?.type === "Identifier" && CLIENT_ENTRY_PROPS.has(prop.key.name)) {
335
+ const seedRefs = /* @__PURE__ */ new Map();
336
+ collectIdentifiersWithOffsets(prop.value, seedRefs);
337
+ const seedLabel = `${componentVar} component():${prop.key.name}`;
338
+ for (const [n, offset] of seedRefs) addReachable(n, seedLabel, offset);
339
+ }
340
+ }
341
+ }
342
+ for (const call of componentCalls) {
343
+ const node = findContainingBodyNode(body, call.start, call.end);
344
+ if (node?.type === "VariableDeclaration") {
345
+ for (const decl of node.declarations) {
346
+ collectPatternNames(
347
+ decl.id,
348
+ (name) => addReachable(name, "<component() declaration>", call.start)
349
+ );
350
+ }
351
+ }
352
+ }
353
+ for (const node of body) {
354
+ if (node.type === "ExportDefaultDeclaration" && node.declaration?.type === "FunctionDeclaration" && node.declaration.id?.name) {
355
+ addReachable(
356
+ node.declaration.id.name,
357
+ "<export default>",
358
+ node.declaration.id.start
359
+ );
360
+ }
361
+ }
362
+ for (const call of atomCalls) {
363
+ const node = findContainingBodyNode(body, call.start, call.end);
364
+ if (node?.type === "VariableDeclaration") {
365
+ for (const decl of node.declarations) {
366
+ collectPatternNames(
367
+ decl.id,
368
+ (name) => addReachable(name, "<_getAtom() declaration>", call.start)
369
+ );
370
+ }
371
+ }
372
+ }
373
+ for (const call of onPageLoadCalls) {
374
+ for (const arg of call.arguments ?? []) {
375
+ const seedRefs = /* @__PURE__ */ new Map();
376
+ collectIdentifiersWithOffsets(arg, seedRefs);
377
+ for (const [n, offset] of seedRefs) addReachable(n, "<onPageLoad()>", offset);
378
+ }
379
+ }
380
+ if (extraSeeds) {
381
+ for (const name of extraSeeds) addReachable(name, "<elementHandler>", 0);
382
+ }
383
+ const processed = /* @__PURE__ */ new Set();
384
+ const queue = [...reachable].filter((n) => bindingMap.has(n));
385
+ while (queue.length > 0) {
386
+ const name = queue.pop();
387
+ if (processed.has(name)) continue;
388
+ processed.add(name);
389
+ const decl = bindingMap.get(name);
390
+ if (!decl) continue;
391
+ const refs = /* @__PURE__ */ new Map();
392
+ collectIdentifiersWithOffsets(decl, refs);
393
+ for (const [ref, offset] of refs) {
394
+ if (!reachable.has(ref)) {
395
+ addReachable(ref, name, offset);
396
+ if (bindingMap.has(ref)) queue.push(ref);
397
+ }
398
+ }
399
+ }
400
+ {
401
+ const programComments = ast.comments ?? [];
402
+ const noBundleViolations = [];
403
+ for (const comment of programComments) {
404
+ if (comment.type !== "Line") continue;
405
+ if (comment.value.trim() !== "!no-bundle") continue;
406
+ const afterComment = comment.end;
407
+ const annotatedNode = body.find((n) => n.start >= afterComment);
408
+ if (!annotatedNode) continue;
409
+ const annotatedNames = /* @__PURE__ */ new Set();
410
+ extractDeclaredNames(annotatedNode, annotatedNames);
411
+ for (const name of annotatedNames) {
412
+ if (reachable.has(name)) {
413
+ noBundleViolations.push({
414
+ name,
415
+ chain: formatReachabilityChain(source, filePath, name, reachableFrom)
416
+ });
417
+ }
418
+ }
419
+ }
420
+ if (noBundleViolations.length > 0) {
421
+ const list = noBundleViolations.map(({ name, chain }) => ` \u2022 ${name}
422
+ ${chain}`).join("\n\n");
423
+ throw richError({
424
+ title: "Server Only Error",
425
+ cause: `\\The following declarations are marked server-only but were reached by the client bundle:${list}
426
+
427
+ The inclusion of server-only variables in client-side code is almost always unintentional.`,
428
+ hint: `\\If these are references you did not intend to mark server-only, you can remove the //!no-bundle flag above their declarations.
429
+ If that is not the case, remove the reference that cause their inclusion.`,
430
+ doShowStack: false
431
+ });
432
+ }
433
+ }
434
+ const removalEdits = [];
435
+ function trailingEnd(end) {
436
+ return end < source.length && source[end] === "\n" ? end + 1 : end;
437
+ }
438
+ for (const node of body) {
439
+ if (node.type === "ImportDeclaration") {
440
+ const specs = node.specifiers ?? [];
441
+ const reachableSpecs = specs.filter((s) => reachable.has(s.local.name));
442
+ if (reachableSpecs.length === specs.length) {
443
+ if (specs.length === 0 && isBuiltin(node.source.value)) {
444
+ removalEdits.push({ start: node.start, end: trailingEnd(node.end), replacement: "" });
445
+ }
446
+ continue;
447
+ }
448
+ if (reachableSpecs.length === 0) {
449
+ removalEdits.push({ start: node.start, end: trailingEnd(node.end), replacement: "" });
450
+ } else {
451
+ removalEdits.push({
452
+ start: node.start,
453
+ end: node.end,
454
+ replacement: reconstructImport(node, reachableSpecs)
455
+ });
456
+ }
457
+ } else if (node.type === "VariableDeclaration") {
458
+ const names = [];
459
+ for (const decl of node.declarations) {
460
+ collectPatternNames(decl.id, (n) => names.push(n));
461
+ }
462
+ if (names.length > 0 && names.every((n) => !reachable.has(n))) {
463
+ removalEdits.push({
464
+ start: node.start,
465
+ end: trailingEnd(node.end),
466
+ replacement: ""
467
+ });
468
+ }
469
+ } else if (node.type === "FunctionDeclaration" && node.id && !reachable.has(node.id.name) || node.type === "ClassDeclaration" && node.id && !reachable.has(node.id.name)) {
470
+ removalEdits.push({ start: node.start, end: trailingEnd(node.end), replacement: "" });
471
+ } else if (node.type === "ExpressionStatement") {
472
+ const containsComponentCall = nodeContainsAnyCall(componentCalls, node.start, node.end);
473
+ const containsOnPageLoadCall = nodeContainsAnyCall(onPageLoadCalls, node.start, node.end);
474
+ if (!containsComponentCall && !containsOnPageLoadCall) {
475
+ removalEdits.push({ start: node.start, end: trailingEnd(node.end), replacement: "" });
476
+ }
477
+ } else if (node.type === "ExportNamedDeclaration") {
478
+ if (node.declaration) {
479
+ const decl = node.declaration;
480
+ if (decl.type === "VariableDeclaration") {
481
+ const names = [];
482
+ for (const d of decl.declarations)
483
+ collectPatternNames(d.id, (n) => names.push(n));
484
+ if (names.length > 0 && names.every((n) => !reachable.has(n))) {
485
+ removalEdits.push({
486
+ start: node.start,
487
+ end: trailingEnd(node.end),
488
+ replacement: ""
489
+ });
490
+ }
491
+ } else if ((decl.type === "FunctionDeclaration" || decl.type === "ClassDeclaration") && decl.id && !reachable.has(decl.id.name)) {
492
+ removalEdits.push({ start: node.start, end: trailingEnd(node.end), replacement: "" });
493
+ }
494
+ } else {
495
+ const specs = node.specifiers ?? [];
496
+ if (specs.length > 0 && specs.every((s) => !reachable.has(s.local.name))) {
497
+ removalEdits.push({ start: node.start, end: trailingEnd(node.end), replacement: "" });
498
+ }
499
+ }
500
+ } else if (node.type === "ExportDefaultDeclaration") {
501
+ const decl = node.declaration;
502
+ const id = decl?.id?.name;
503
+ if (!id || !reachable.has(id)) {
504
+ removalEdits.push({ start: node.start, end: trailingEnd(node.end), replacement: "" });
505
+ }
506
+ }
507
+ }
508
+ return applyEdits(source, removalEdits);
509
+ }
510
+ function collectTransformEdits(source, ast, filePath) {
511
+ const sharedEdits = [];
512
+ const serverOnlyEdits = [];
513
+ const clientOnlyEdits = [];
514
+ const sourcePathMarkers = (ast.comments ?? []).filter((c) => c.type === "Line" && /^[\w./@-][^\s]*\.[a-z]+$/i.test(c.value.trim())).map((c) => ({ offset: c.start, path: c.value.trim() })).sort((a, b) => a.offset - b.offset);
515
+ function sourcePathAt(nodeStart) {
516
+ let result = filePath;
517
+ for (const marker of sourcePathMarkers) {
518
+ if (marker.offset <= nodeStart) result = marker.path;
519
+ else break;
520
+ }
521
+ return result;
522
+ }
523
+ const callIndexByPath = /* @__PURE__ */ new Map();
524
+ function nextCallIndex(path) {
525
+ const i = callIndexByPath.get(path) ?? 0;
526
+ callIndexByPath.set(path, i + 1);
527
+ return i;
528
+ }
529
+ let eidCounter = 0;
530
+ function visitNode(node, componentDepth) {
531
+ if (node.type === "CallExpression" && node.callee.type === "Identifier" && node.callee.name === "atom" && node.arguments.length >= 1) {
532
+ const sourcePath = sourcePathAt(node.start);
533
+ const atomId = generateAtomId(sourcePath, nextCallIndex(sourcePath));
534
+ const argStart = node.arguments[0].start;
535
+ serverOnlyEdits.push({ start: argStart, end: argStart, replacement: `"${atomId}", ` });
536
+ clientOnlyEdits.push({ start: node.start, end: node.end, replacement: `_getAtom("${atomId}")` });
537
+ }
538
+ if (node.type === "CallExpression" && node.callee.type === "Identifier" && node.callee.name === "component" && node.arguments.length === 1 && node.arguments[0].type === "ObjectExpression") {
539
+ const sourcePath = sourcePathAt(node.start);
540
+ const id = generateAtomId(sourcePath, nextCallIndex(sourcePath));
541
+ const obj = node.arguments[0];
542
+ const insertAt = obj.start + 1;
543
+ sharedEdits.push({ start: insertAt, end: insertAt, replacement: ` __id: "${id}",` });
544
+ for (const prop of obj.properties) {
545
+ if (prop.type === "Property" && prop.key?.type === "Identifier" && prop.key.name === "init") {
546
+ let end = prop.end;
547
+ let i = end;
548
+ while (i < source.length && (source[i] === "," || source[i] === " " || source[i] === " " || source[i] === "\n")) {
549
+ if (source[i] === ",") {
550
+ end = i + 1;
551
+ break;
552
+ }
553
+ i++;
554
+ }
555
+ clientOnlyEdits.push({ start: prop.start, end, replacement: "" });
556
+ }
557
+ }
558
+ forEachChild(node, (child) => visitNode(child, componentDepth + 1));
559
+ return;
560
+ }
561
+ if (node.type === "CallExpression" && node.callee.type === "Identifier" && node.callee.name === "serverAction" && node.arguments.length === 1 && node.arguments[0].type === "ObjectExpression") {
562
+ const sourcePath = sourcePathAt(node.start);
563
+ const id = generateAtomId(sourcePath, nextCallIndex(sourcePath));
564
+ const obj = node.arguments[0];
565
+ const insertAt = obj.start + 1;
566
+ sharedEdits.push({ start: insertAt, end: insertAt, replacement: ` id: "${id}",` });
567
+ return;
568
+ }
569
+ if (node.type === "CallExpression" && node.callee.type === "Identifier" && ALL_TAGS_SET.has(node.callee.name) && !["atom", "view", "component"].includes(node.callee.name)) {
570
+ sharedEdits.push({
571
+ start: node.callee.start,
572
+ end: node.callee.end,
573
+ replacement: `__tags.${node.callee.name}`
574
+ });
575
+ if (componentDepth === 0 && node.arguments.length >= 1 && node.arguments[0].type === "ObjectExpression") {
576
+ const optionsObj = node.arguments[0];
577
+ const hasHandler = optionsObj.properties.some((prop) => {
578
+ const key = prop.key?.type === "Identifier" ? prop.key.name : prop.key?.type === "Literal" ? String(prop.key.value) : "";
579
+ return key.startsWith("on");
580
+ });
581
+ if (hasHandler) {
582
+ const eid = eidCounter++;
583
+ sharedEdits.push({
584
+ start: optionsObj.start + 1,
585
+ end: optionsObj.start + 1,
586
+ replacement: ` __eid: ${eid},`
587
+ });
588
+ }
589
+ }
590
+ }
591
+ forEachChild(node, (child) => visitNode(child, componentDepth));
592
+ }
593
+ visitNode(ast.program, 0);
594
+ return { sharedEdits, serverOnlyEdits, clientOnlyEdits };
595
+ }
596
+ function transformBundle(source, filePath) {
597
+ const ast = parseSync(filePath, source, { sourceType: "module" });
598
+ const { sharedEdits, serverOnlyEdits, clientOnlyEdits } = collectTransformEdits(source, ast, filePath);
599
+ const serverCode = applyEdits(source, [...sharedEdits, ...serverOnlyEdits]);
600
+ const preClientCode = applyEdits(source, [...sharedEdits, ...clientOnlyEdits]);
601
+ return { serverCode, preClientCode };
602
+ }
603
+ function transformChunk(source, filePath) {
604
+ const ast = parseSync(filePath, source, { sourceType: "module" });
605
+ const { sharedEdits, clientOnlyEdits } = collectTransformEdits(source, ast, filePath);
606
+ return applyEdits(source, [...sharedEdits, ...clientOnlyEdits]);
607
+ }
608
+ function serializePropValue(value) {
609
+ if (value === null) return "null";
610
+ if (value === void 0) return "undefined";
611
+ if (typeof value === "boolean") return String(value);
612
+ if (typeof value === "number") return isFinite(value) ? String(value) : "undefined";
613
+ if (typeof value === "string") return JSON.stringify(value);
614
+ if (typeof value === "function") {
615
+ const name = value.name;
616
+ return name ? name : "undefined";
617
+ }
618
+ if (Array.isArray(value)) {
619
+ return `[${value.map(serializePropValue).join(", ")}]`;
620
+ }
621
+ if (typeof value === "object") {
622
+ const obj = value;
623
+ if (typeof obj.id === "string" && "value" in obj) {
624
+ return `_getAtom(${JSON.stringify(obj.id)}, ${serializePropValue(obj.value)})`;
625
+ }
626
+ const entries = Object.entries(value).map(
627
+ ([k, v]) => `${JSON.stringify(k)}: ${serializePropValue(v)}`
628
+ );
629
+ return `{ ${entries.join(", ")} }`;
630
+ }
631
+ return "undefined";
632
+ }
633
+ function propsComparisonKey(props) {
634
+ if (!props || Object.keys(props).length === 0) return "";
635
+ return Object.entries(props).sort(([a], [b]) => a.localeCompare(b)).map(([k, v]) => {
636
+ if (typeof v === "function") return `${k}=fn:${v.name ?? ""}`;
637
+ return `${k}=${JSON.stringify(v)}`;
638
+ }).join(",");
639
+ }
640
+ function serializePropsRecord(props) {
641
+ if (!props || Object.keys(props).length === 0) return "{}";
642
+ const entries = Object.entries(props).map(([k, v]) => `${JSON.stringify(k)}: ${serializePropValue(v)}`);
643
+ return `{ ${entries.join(", ")} }`;
644
+ }
645
+ function generateRegionsExpression(regions) {
646
+ const keyToVar = /* @__PURE__ */ new Map();
647
+ const keyToCode = /* @__PURE__ */ new Map();
648
+ let varCounter = 0;
649
+ const regionKeys = regions.map(
650
+ (descs) => descs.map((desc) => {
651
+ const props = desc.props;
652
+ const key = propsComparisonKey(props);
653
+ if (!keyToVar.has(key)) {
654
+ keyToVar.set(key, `_p${varCounter++}`);
655
+ keyToCode.set(key, serializePropsRecord(props));
656
+ }
657
+ return key;
658
+ })
659
+ );
660
+ const declarations = [...keyToVar.entries()].map(([key, varName]) => ` const ${varName} = ${keyToCode.get(key)};`).join("\n");
661
+ const regionParts = regions.map((descs, ri) => {
662
+ const keys = regionKeys[ri];
663
+ const rle = [];
664
+ for (let i = 0; i < descs.length; i++) {
665
+ const cid = descs[i].__componentId;
666
+ const propsKey = keys[i];
667
+ const last = rle[rle.length - 1];
668
+ if (last && last.cid === cid && last.propsKey === propsKey) {
669
+ last.count++;
670
+ } else {
671
+ rle.push({ cid, propsKey, count: 1 });
672
+ }
673
+ }
674
+ const parts = rle.map(
675
+ ({ cid, propsKey, count }) => `{ __cid: ${JSON.stringify(cid)}, props: ${keyToVar.get(propsKey)}, count: ${count} }`
676
+ );
677
+ return `[${parts.join(", ")}]`;
678
+ });
679
+ return { declarations, expression: `[${regionParts.join(", ")}]` };
680
+ }
681
+ function extractElementHandlersFromAst(preClientCode, ast) {
682
+ const handlerSets = [];
683
+ const seeds = /* @__PURE__ */ new Set();
684
+ let eidCounter = 0;
685
+ function src(node) {
686
+ return preClientCode.slice(node.start, node.end);
687
+ }
688
+ function walkNode(node, insideComponentDepth) {
689
+ if (!node || typeof node !== "object" || typeof node.type !== "string") return;
690
+ if (node.type === "CallExpression" && node.callee?.type === "Identifier" && node.callee.name === "component" && node.arguments?.length === 1 && node.arguments[0]?.type === "ObjectExpression") {
691
+ walkNode(node.arguments[0], insideComponentDepth + 1);
692
+ return;
693
+ }
694
+ if (node.type === "CallExpression" && (node.callee?.type === "StaticMemberExpression" || node.callee?.type === "MemberExpression") && node.callee.object?.type === "Identifier" && node.callee.object.name === "__tags" && node.arguments?.length >= 1 && node.arguments[0]?.type === "ObjectExpression") {
695
+ if (insideComponentDepth === 0) {
696
+ const optionsObj = node.arguments[0];
697
+ const onProps = [];
698
+ for (const prop of optionsObj.properties ?? []) {
699
+ if (prop.type !== "Property" && prop.type !== "ObjectProperty") continue;
700
+ const keyName = prop.key?.type === "Identifier" ? prop.key.name : prop.key?.type === "StringLiteral" ? prop.key.value : prop.key?.type === "Literal" ? String(prop.key.value) : "";
701
+ if (!keyName.startsWith("on")) continue;
702
+ const val = prop.value ?? prop;
703
+ if (val.type !== "ArrowFunctionExpression" && val.type !== "FunctionExpression" && val.type !== "Identifier") continue;
704
+ collectAllIdentifiers(val, seeds);
705
+ onProps.push({
706
+ event: keyName.slice(2).toLowerCase(),
707
+ fnSource: src(val)
708
+ });
709
+ }
710
+ if (onProps.length > 0) {
711
+ handlerSets.push({ eid: eidCounter++, handlers: onProps });
712
+ }
713
+ }
714
+ for (let i = 1; i < node.arguments.length; i++) {
715
+ walkNode(node.arguments[i], insideComponentDepth);
716
+ }
717
+ for (const prop of node.arguments[0]?.properties ?? []) {
718
+ const keyName = prop.key?.type === "Identifier" ? prop.key.name : prop.key?.type === "StringLiteral" ? prop.key.value : prop.key?.type === "Literal" ? String(prop.key.value) : "";
719
+ if (!keyName.startsWith("on")) {
720
+ walkNode(prop.value ?? prop, insideComponentDepth);
721
+ }
722
+ }
723
+ return;
724
+ }
725
+ forEachChild(node, (child) => walkNode(child, insideComponentDepth));
726
+ }
727
+ walkNode(ast.program, 0);
728
+ return { handlerSets, seeds };
729
+ }
730
+ function generateHandlersExpression(elementHandlers, seeds) {
731
+ if (!elementHandlers || elementHandlers.length === 0) {
732
+ return { declarations: "", expression: "[]", seeds: /* @__PURE__ */ new Set() };
733
+ }
734
+ function handlerSetKey(handlers) {
735
+ return handlers.map(({ event, fnSource }) => `${event}:\0${fnSource}`).join("");
736
+ }
737
+ function serializeHandlerSet(handlers) {
738
+ const entries = handlers.map(
739
+ ({ event, fnSource }) => `{ event: ${JSON.stringify(event)}, fn: ${fnSource} }`
740
+ );
741
+ return `[${entries.join(", ")}]`;
742
+ }
743
+ const keyToVar = /* @__PURE__ */ new Map();
744
+ const keyToCode = /* @__PURE__ */ new Map();
745
+ let hCounter = 0;
746
+ for (const { handlers } of elementHandlers) {
747
+ const key = handlerSetKey(handlers);
748
+ if (!keyToVar.has(key)) {
749
+ keyToVar.set(key, `_h${hCounter++}`);
750
+ keyToCode.set(key, serializeHandlerSet(handlers));
751
+ }
752
+ }
753
+ const declarations = [...keyToVar.entries()].map(([key, varName]) => ` const ${varName} = ${keyToCode.get(key)};`).join("\n");
754
+ const parts = elementHandlers.map(({ eid, handlers }) => {
755
+ const varName = keyToVar.get(handlerSetKey(handlers));
756
+ return `{ eid: ${eid}, h: ${varName} }`;
757
+ });
758
+ return { declarations, expression: `[${parts.join(", ")}]`, seeds };
759
+ }
760
+ function applyServerActionCallReplacements(source, ast) {
761
+ const varToId = /* @__PURE__ */ new Map();
762
+ for (const node of ast.program.body) {
763
+ if (node.type !== "VariableDeclaration") continue;
764
+ for (const decl of node.declarations) {
765
+ const init = decl.init;
766
+ if (init?.type !== "CallExpression" || init.callee?.type !== "Identifier" || init.callee.name !== "serverAction" || init.arguments?.length !== 1 || init.arguments[0]?.type !== "ObjectExpression") continue;
767
+ for (const prop of init.arguments[0].properties) {
768
+ if (prop.type === "Property" && prop.key?.type === "Identifier" && prop.key.name === "id" && prop.value?.type === "Literal" && typeof prop.value.value === "string") {
769
+ collectPatternNames(decl.id, (name) => {
770
+ if (!varToId.has(name)) varToId.set(name, prop.value.value);
771
+ });
772
+ break;
773
+ }
774
+ }
775
+ }
776
+ }
777
+ if (varToId.size === 0) return source;
778
+ const edits = [];
779
+ function visit(node) {
780
+ if (node.type === "CallExpression" && node.callee?.type === "Identifier" && varToId.has(node.callee.name)) {
781
+ const id = varToId.get(node.callee.name);
782
+ const args = node.arguments ?? [];
783
+ const argsStr = args.length > 0 ? ", " + source.slice(args[0].start, args[args.length - 1].end) : "";
784
+ edits.push({
785
+ start: node.start,
786
+ end: node.end,
787
+ replacement: `_action("${id}"${argsStr})`
788
+ });
789
+ return;
790
+ }
791
+ forEachChild(node, visit);
792
+ }
793
+ visit(ast.program);
794
+ return applyEdits(source, edits);
795
+ }
796
+ function generateLayoutBundle(preClientCode, filePath) {
797
+ let ast;
798
+ try {
799
+ ast = parseSync(filePath, preClientCode, { sourceType: "module" });
800
+ } catch (e) {
801
+ console.error("Failed to parse layout module", e);
802
+ return preClientCode;
803
+ }
804
+ const { handlerSets, seeds } = extractElementHandlersFromAst(preClientCode, ast);
805
+ const { declarations: handlerDecls, expression: handlersExpr, seeds: handlerSeeds } = generateHandlersExpression(handlerSets, seeds);
806
+ let defaultStart = -1;
807
+ let defaultEnd = -1;
808
+ for (const node of ast.program.body) {
809
+ if (node.type === "ExportDefaultDeclaration") {
810
+ defaultStart = node.start;
811
+ defaultEnd = node.end;
812
+ }
813
+ }
814
+ const replaced = applyServerActionCallReplacements(preClientCode, ast);
815
+ const withoutDefault = defaultStart >= 0 ? replaced.slice(0, defaultStart) + replaced.slice(defaultEnd) : replaced;
816
+ const syntheticFn = `
817
+ export default function __constructor() {
818
+ ${handlerDecls}
819
+ const regions = [];
820
+ const handlers = ${handlersExpr};
821
+ return { regions, handlers };
822
+ }
823
+ `;
824
+ const finalSource = withoutDefault + syntheticFn;
825
+ let dceAst;
826
+ try {
827
+ dceAst = parseSync(filePath, finalSource, { sourceType: "module" });
828
+ } catch (e) {
829
+ console.error("Failed to parse modified layout bundle", e);
830
+ return finalSource;
831
+ }
832
+ return applyReachabilityDCECore(finalSource, dceAst, filePath, handlerSeeds);
833
+ }
834
+ const syntheticBundleStaticCache = /* @__PURE__ */ new Map();
835
+ const SYNTHETIC_BUNDLE_CACHE_MAX = 256;
836
+ function syntheticBundleCacheKey(preClientCode, layoutCacheKeys) {
837
+ return preClientCode + "\0" + layoutCacheKeys.join(",");
838
+ }
839
+ function computeSyntheticBundleStaticParts(preClientCode, filePath, layoutCacheKeys) {
840
+ let ast;
841
+ try {
842
+ ast = parseSync(filePath, preClientCode, { sourceType: "module" });
843
+ } catch (e) {
844
+ console.error("Failed to parse a module", e);
845
+ return null;
846
+ }
847
+ const { handlerSets, seeds } = extractElementHandlersFromAst(preClientCode, ast);
848
+ const { declarations: handlerDecls, expression: handlersExpr, seeds: handlerSeeds } = generateHandlersExpression(handlerSets, seeds);
849
+ let defaultStart = -1;
850
+ let defaultEnd = -1;
851
+ for (const node of ast.program.body) {
852
+ if (node.type === "ExportDefaultDeclaration") {
853
+ defaultStart = node.start;
854
+ defaultEnd = node.end;
855
+ }
856
+ }
857
+ const replaced = applyServerActionCallReplacements(preClientCode, ast);
858
+ const withoutDefault = defaultStart >= 0 ? replaced.slice(0, defaultStart) + replaced.slice(defaultEnd) : replaced;
859
+ const layoutImports = layoutCacheKeys.map((lk, i) => `import { default as __l${i} } from "/chunks/${lk}.client.mjs";`).join("\n");
860
+ const layoutCalls = layoutCacheKeys.map((_, i) => ` const _l${i} = __l${i}();`).join("\n");
861
+ const regionsSpread = layoutCacheKeys.map((_, i) => `..._l${i}.regions`).join(", ");
862
+ const handlersSpread = layoutCacheKeys.map((_, i) => `..._l${i}.handlers`).join(", ");
863
+ const mergedRegions = regionsSpread ? `[${regionsSpread}, ...regions]` : `regions`;
864
+ const mergedHandlers = handlersSpread ? `[${handlersSpread}, ...handlers]` : `handlers`;
865
+ return {
866
+ withoutDefault,
867
+ handlerDecls,
868
+ handlersExpr,
869
+ handlerSeeds,
870
+ layoutImports,
871
+ layoutCalls,
872
+ mergedRegions,
873
+ mergedHandlers,
874
+ filePath
875
+ };
876
+ }
877
+ function getOrComputeStaticParts(preClientCode, filePath, layoutCacheKeys) {
878
+ const key = syntheticBundleCacheKey(preClientCode, layoutCacheKeys);
879
+ const cached = syntheticBundleStaticCache.get(key);
880
+ if (cached !== void 0) {
881
+ if (cached.filePath === filePath) return cached;
882
+ }
883
+ const parts = computeSyntheticBundleStaticParts(preClientCode, filePath, layoutCacheKeys);
884
+ if (parts === null) return null;
885
+ if (syntheticBundleStaticCache.size >= SYNTHETIC_BUNDLE_CACHE_MAX) {
886
+ syntheticBundleStaticCache.delete(syntheticBundleStaticCache.keys().next().value);
887
+ }
888
+ syntheticBundleStaticCache.set(key, parts);
889
+ return parts;
890
+ }
891
+ function invalidateSyntheticBundleCache(preClientCode, layoutCacheKeys) {
892
+ syntheticBundleStaticCache.delete(syntheticBundleCacheKey(preClientCode, layoutCacheKeys));
893
+ }
894
+ function generateSyntheticBundle(preClientCode, filePath, regions, layoutCacheKeys) {
895
+ const { declarations: propsDecls, expression: regionsExpr } = generateRegionsExpression(regions);
896
+ const staticParts = getOrComputeStaticParts(preClientCode, filePath, layoutCacheKeys);
897
+ if (staticParts === null) return preClientCode;
898
+ const {
899
+ withoutDefault,
900
+ handlerDecls,
901
+ handlersExpr,
902
+ handlerSeeds,
903
+ layoutImports,
904
+ layoutCalls,
905
+ mergedRegions,
906
+ mergedHandlers
907
+ } = staticParts;
908
+ const syntheticFn = `
909
+ export default function __constructor() {
910
+ ${propsDecls}
911
+ ${handlerDecls}
912
+ ${layoutCalls}
913
+ const regions = ${regionsExpr};
914
+ const handlers = ${handlersExpr};
915
+ return { regions: ${mergedRegions}, handlers: ${mergedHandlers} };
916
+ }
917
+ `;
918
+ const importSection = layoutImports ? layoutImports + "\n" : "";
919
+ const finalSource = importSection + withoutDefault + syntheticFn;
920
+ let dceAst;
921
+ try {
922
+ dceAst = parseSync(filePath, finalSource, { sourceType: "module" });
923
+ } catch (e) {
924
+ console.error("Failed to parse modified bundle", e);
925
+ return finalSource;
926
+ }
927
+ return applyReachabilityDCECore(finalSource, dceAst, filePath, handlerSeeds);
928
+ }
929
+ export {
930
+ applyEdits,
931
+ forEachChild,
932
+ generateLayoutBundle,
933
+ generateSyntheticBundle,
934
+ invalidateSyntheticBundleCache,
935
+ serializePropValue,
936
+ transformBundle,
937
+ transformChunk
938
+ };