solid-optimizer 1.0.0-next.1 → 1.0.0-next.10

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,6 +1,7 @@
1
1
  import remapping from "@jridgewell/remapping";
2
- import MagicString from "magic-string";
3
2
  import { parseSync, rawTransferSupported, visitorKeys } from "oxc-parser";
3
+ import MagicString from "magic-string";
4
+ import { parse, parseFragment, serialize } from "parse5";
4
5
  //#region src/ast.ts
5
6
  /**
6
7
  * Keys that only hold TypeScript types. Types never run, so no pass reads or rewrites them.
@@ -65,9 +66,9 @@ function collectParents(program) {
65
66
  * is several times faster to read. It is not in the options' type yet.
66
67
  */
67
68
  const RAW_TRANSFER = rawTransferSupported();
68
- function parse(filename, code) {
69
+ function parse$1(filename, code) {
69
70
  const options = {
70
- lang: languageOf(filename),
71
+ lang: getLanguage(filename),
71
72
  sourceType: "module",
72
73
  preserveParens: true,
73
74
  experimentalRawTransfer: RAW_TRANSFER
@@ -77,7 +78,7 @@ function parse(filename, code) {
77
78
  if (error) throw new SyntaxError(`[solid-optimizer] ${filename}: ${error.codeframe ?? error.message}`);
78
79
  return result.program;
79
80
  }
80
- function languageOf(filename) {
81
+ function getLanguage(filename) {
81
82
  if (/\.tsx$/i.test(filename)) return "tsx";
82
83
  if (/\.[cm]?ts$/i.test(filename)) return "ts";
83
84
  return "jsx";
@@ -87,7 +88,7 @@ function languageOf(filename) {
87
88
  */
88
89
  function unwrap(node) {
89
90
  let current = node;
90
- while (current.type === "ParenthesizedExpression" || current.type === "TSAsExpression" || current.type === "TSSatisfiesExpression" || current.type === "TSNonNullExpression" || current.type === "TSTypeAssertion") current = current.expression;
91
+ while (current.type === "ParenthesizedExpression" || current.type === "TSAsExpression" || current.type === "TSSatisfiesExpression" || current.type === "TSNonNullExpression" || current.type === "TSTypeAssertion" || current.type === "TSInstantiationExpression") current = current.expression;
91
92
  return current;
92
93
  }
93
94
  function isFunctionNode(node) {
@@ -221,7 +222,7 @@ function recordSkip(context, pass, reason, name) {
221
222
  /**
222
223
  * The current text of `node`, including the edits made inside it so far.
223
224
  */
224
- function textOf(context, node) {
225
+ function getText(context, node) {
225
226
  return context.s.slice(node.start, node.end);
226
227
  }
227
228
  //#endregion
@@ -257,6 +258,30 @@ function isWithinScope(scope, ancestor) {
257
258
  }
258
259
  return false;
259
260
  }
261
+ /**
262
+ * Whether a parameter list holds an expression: a default value or a computed
263
+ * key, at any depth.
264
+ */
265
+ function hasParameterExpressions(params) {
266
+ for (const param of params) if (hasPatternExpression(param)) return true;
267
+ return false;
268
+ }
269
+ function hasPatternExpression(pattern) {
270
+ switch (pattern.type) {
271
+ case "AssignmentPattern": return true;
272
+ case "ObjectPattern":
273
+ for (const property of pattern.properties) if (property.type === "RestElement") {
274
+ if (hasPatternExpression(property.argument)) return true;
275
+ } else if (property.computed || hasPatternExpression(property.value)) return true;
276
+ return false;
277
+ case "ArrayPattern":
278
+ for (const element of pattern.elements) if (element && hasPatternExpression(element)) return true;
279
+ return false;
280
+ case "RestElement": return hasPatternExpression(pattern.argument);
281
+ case "TSParameterProperty": return hasPatternExpression(pattern.parameter);
282
+ default: return false;
283
+ }
284
+ }
260
285
  function exportName$1(name) {
261
286
  return name.type === "Literal" ? name.value : name.name;
262
287
  }
@@ -265,6 +290,7 @@ var Analyzer = class {
265
290
  this.scopes = /* @__PURE__ */ new Map();
266
291
  this.names = /* @__PURE__ */ new Set();
267
292
  this.pending = [];
293
+ this.bodies = /* @__PURE__ */ new Set();
268
294
  this.root = {
269
295
  node: program,
270
296
  parent: void 0,
@@ -302,7 +328,10 @@ var Analyzer = class {
302
328
  }
303
329
  declare(identifier, kind, declaration, source, imported) {
304
330
  let target = this.scope;
305
- if (kind === "var") while (!target.isFunction && target.parent) target = target.parent;
331
+ if (kind === "var") {
332
+ while (!target.isFunction && target.parent) target = target.parent;
333
+ if (this.bodies.has(target.node) && target.parent?.bindings.has(identifier.name)) target = target.parent;
334
+ }
306
335
  this.names.add(identifier.name);
307
336
  const existing = target.bindings.get(identifier.name);
308
337
  if (existing) {
@@ -398,10 +427,23 @@ var Analyzer = class {
398
427
  this.withScope(node, true, () => {
399
428
  if (node.type === "FunctionExpression" && node.id) this.declare(node.id, "other", node);
400
429
  for (const param of node.params) this.declarePattern(param, "param", node);
401
- if (node.body) {
402
- this.scopes.set(node.body, this.scope);
403
- this.visitStatements(node.body.body);
404
- }
430
+ if (node.body) this.visitBody(node.body, node.params);
431
+ });
432
+ }
433
+ /**
434
+ * Visits the block body of a function. When a parameter holds an expression,
435
+ * the body gets its own scope, so the expression cannot see the body's
436
+ * declarations.
437
+ */
438
+ visitBody(body, params) {
439
+ if (!hasParameterExpressions(params)) {
440
+ this.scopes.set(body, this.scope);
441
+ this.visitStatements(body.body);
442
+ return;
443
+ }
444
+ this.bodies.add(body);
445
+ this.withScope(body, true, () => {
446
+ this.visitStatements(body.body);
405
447
  });
406
448
  }
407
449
  visitClass(node) {
@@ -457,10 +499,8 @@ var Analyzer = class {
457
499
  case "ArrowFunctionExpression":
458
500
  this.withScope(node, true, () => {
459
501
  for (const param of node.params) this.declarePattern(param, "param", node);
460
- if (node.body.type === "BlockStatement") {
461
- this.scopes.set(node.body, this.scope);
462
- this.visitStatements(node.body.body);
463
- } else this.visit(node.body);
502
+ if (node.body.type === "BlockStatement") this.visitBody(node.body, node.params);
503
+ else this.visit(node.body);
464
504
  });
465
505
  break;
466
506
  case "ClassDeclaration":
@@ -561,13 +601,27 @@ var Analyzer = class {
561
601
  for (const child of node.children) this.visit(child);
562
602
  if (node.closingElement) this.visitJSXName(node.closingElement.name);
563
603
  break;
564
- case "TSEnumDeclaration":
565
604
  case "TSImportEqualsDeclaration":
566
605
  this.declare(node.id, "other", node);
567
606
  break;
568
- case "TSModuleDeclaration":
569
- if (node.id.type === "Identifier") this.declare(node.id, "other", node);
607
+ case "TSEnumDeclaration":
608
+ this.declare(node.id, "other", node);
609
+ if (node.declare) break;
610
+ this.withScope(node, false, () => {
611
+ for (const member of node.body.members) if (member.id.type === "Identifier") this.declare(member.id, "other", member);
612
+ for (const member of node.body.members) if (member.initializer) this.visit(member.initializer);
613
+ });
614
+ break;
615
+ case "TSModuleDeclaration": {
616
+ let id = node.id;
617
+ while (id.type === "TSQualifiedName") id = id.left;
618
+ if (id.type === "Identifier") this.declare(id, "other", node);
619
+ const { body } = node;
620
+ if (!node.declare && body) this.withScope(node, true, () => {
621
+ this.visitStatements(body.body);
622
+ });
570
623
  break;
624
+ }
571
625
  default: forEachChild(node, (child) => {
572
626
  this.visit(child);
573
627
  });
@@ -728,6 +782,10 @@ function truthiness(node, lookup) {
728
782
  const value = evaluate(node, lookup);
729
783
  return value ? !!value.value : void 0;
730
784
  }
785
+ function areSideEffectFree(nodes) {
786
+ for (const node of nodes) if (!isSideEffectFree(node)) return false;
787
+ return true;
788
+ }
731
789
  /**
732
790
  * Whether skipping `node` entirely loses nothing observable.
733
791
  *
@@ -743,14 +801,18 @@ function isSideEffectFree(node) {
743
801
  case "ArrowFunctionExpression":
744
802
  case "FunctionExpression": return true;
745
803
  case "ParenthesizedExpression": return isSideEffectFree(node.expression);
746
- case "TemplateLiteral": return node.expressions.every(isSideEffectFree);
804
+ case "TemplateLiteral": return areSideEffectFree(node.expressions);
747
805
  case "UnaryExpression": return node.operator !== "delete" && isSideEffectFree(node.argument);
748
806
  case "BinaryExpression": return node.operator !== "in" && node.operator !== "instanceof" && isSideEffectFree(node.left) && isSideEffectFree(node.right);
749
807
  case "LogicalExpression": return isSideEffectFree(node.left) && isSideEffectFree(node.right);
750
- case "SequenceExpression": return node.expressions.every(isSideEffectFree);
808
+ case "SequenceExpression": return areSideEffectFree(node.expressions);
751
809
  case "ConditionalExpression": return isSideEffectFree(node.test) && isSideEffectFree(node.consequent) && isSideEffectFree(node.alternate);
752
- case "ArrayExpression": return node.elements.every((element) => element === null || element.type !== "SpreadElement" && isSideEffectFree(element));
753
- case "ObjectExpression": return node.properties.every((property) => property.type === "Property" && (!property.computed || isSideEffectFree(property.key)) && isSideEffectFree(property.value));
810
+ case "ArrayExpression":
811
+ for (const element of node.elements) if (element !== null && (element.type === "SpreadElement" || !isSideEffectFree(element))) return false;
812
+ return true;
813
+ case "ObjectExpression":
814
+ for (const property of node.properties) if (property.type !== "Property" || property.computed && !isSideEffectFree(property.key) || !isSideEffectFree(property.value)) return false;
815
+ return true;
754
816
  default: return false;
755
817
  }
756
818
  }
@@ -771,7 +833,7 @@ function effectfulParts(node, parts = []) {
771
833
  function arrayLiteralLength(node) {
772
834
  if (node.type === "ParenthesizedExpression") return arrayLiteralLength(node.expression);
773
835
  if (node.type !== "ArrayExpression") return;
774
- if (node.elements.some((element) => element?.type === "SpreadElement")) return;
836
+ for (const element of node.elements) if (element?.type === "SpreadElement") return;
775
837
  return node.elements.length;
776
838
  }
777
839
  /**
@@ -806,7 +868,11 @@ function isLiteralForm(node) {
806
868
  //#region src/constants.ts
807
869
  function resolveImportedConstants(constants) {
808
870
  const result = /* @__PURE__ */ new Map();
809
- for (const [source, exports] of Object.entries(constants ?? {})) result.set(source, new Map(Object.entries(exports).map(([name, value]) => [name, { value }])));
871
+ for (const [source, exports] of Object.entries(constants ?? {})) {
872
+ const entries = /* @__PURE__ */ new Map();
873
+ for (const [name, value] of Object.entries(exports)) entries.set(name, { value });
874
+ result.set(source, entries);
875
+ }
810
876
  return result;
811
877
  }
812
878
  function globalValue(name) {
@@ -829,7 +895,7 @@ var ConstantTable = class {
829
895
  if (reference.type === "MemberExpression") return this.namespaceMember(scopes, reference) ?? this.globalMember(scopes, reference);
830
896
  if (!scopes.references.has(reference) || reference.type !== "Identifier") return;
831
897
  const binding = scopes.references.get(reference);
832
- if (binding) return this.constantOf(binding);
898
+ if (binding) return this.getConstant(binding);
833
899
  return this.globalConstant(reference.name) ?? globalValue(reference.name);
834
900
  };
835
901
  }
@@ -877,7 +943,7 @@ var ConstantTable = class {
877
943
  * A reference that runs before its declaration throws at runtime, and
878
944
  * folding turns it into the value. Minifiers make the same trade.
879
945
  */
880
- constantOf(binding) {
946
+ getConstant(binding) {
881
947
  const cached = this.constants.get(binding);
882
948
  if (cached !== void 0) return cached ?? void 0;
883
949
  let value;
@@ -911,6 +977,16 @@ function namedImportSources(program, scopes = analyzeScopes(program)) {
911
977
  return [...sources];
912
978
  }
913
979
  /**
980
+ * The modules a module still imports once its types are stripped: the
981
+ * sources of `namedImportSources`, and imports for side effects only, like
982
+ * `import './setup'`.
983
+ */
984
+ function runtimeImportSources(program, scopes = analyzeScopes(program)) {
985
+ const sources = new Set(namedImportSources(program, scopes));
986
+ for (const statement of program.body) if (statement.type === "ImportDeclaration" && statement.importKind !== "type" && statement.specifiers.length === 0) sources.add(statement.source.value);
987
+ return [...sources];
988
+ }
989
+ /**
914
990
  * Whether the module reads one of these import bindings as a value. Scope
915
991
  * analysis skips type positions, so a binding used only in types has no
916
992
  * references.
@@ -956,7 +1032,7 @@ function constantExports(program, options, scopes = analyzeScopes(program)) {
956
1032
  if (declaration?.type === "VariableDeclaration") {
957
1033
  for (const declarator of declaration.declarations) if (declarator.id.type === "Identifier") {
958
1034
  const binding = topLevel.bindings.get(declarator.id.name);
959
- add(declarator.id.name, binding ? table.constantOf(binding) : void 0);
1035
+ add(declarator.id.name, binding ? table.getConstant(binding) : void 0);
960
1036
  }
961
1037
  continue;
962
1038
  }
@@ -968,7 +1044,7 @@ function constantExports(program, options, scopes = analyzeScopes(program)) {
968
1044
  if (statement.source) add(exported, options.importedConstants.get(statement.source.value)?.get(local));
969
1045
  else {
970
1046
  const binding = topLevel.bindings.get(local);
971
- add(exported, binding ? table.constantOf(binding) : void 0);
1047
+ add(exported, binding ? table.getConstant(binding) : void 0);
972
1048
  }
973
1049
  }
974
1050
  }
@@ -979,9 +1055,241 @@ function constantExports(program, options, scopes = analyzeScopes(program)) {
979
1055
  return result;
980
1056
  }
981
1057
  //#endregion
1058
+ //#region src/text.ts
1059
+ const WRITTEN = 2147483648;
1060
+ const LOOSE = 4294967295;
1061
+ const LOOSE_UNITS = "￿￿";
1062
+ function encodeOrigin(value) {
1063
+ return String.fromCharCode(value >>> 16, value & 65535);
1064
+ }
1065
+ function decodeOrigin(origins, index) {
1066
+ return (origins.charCodeAt(index * 2) << 16 | origins.charCodeAt(index * 2 + 1)) >>> 0;
1067
+ }
1068
+ function repeatOrigin(value, length) {
1069
+ return encodeOrigin(value).repeat(length);
1070
+ }
1071
+ /** The line of the original that holds an offset. */
1072
+ function findLine(lineStarts, offset) {
1073
+ let low = 0;
1074
+ let high = lineStarts.length - 1;
1075
+ while (low < high) {
1076
+ const middle = low + high + 1 >> 1;
1077
+ if ((lineStarts[middle] ?? 0) <= offset) low = middle;
1078
+ else high = middle - 1;
1079
+ }
1080
+ return low;
1081
+ }
1082
+ let identityCode;
1083
+ let identity = "";
1084
+ /** The origins of unedited code: each character its own offset. */
1085
+ function createIdentity(code) {
1086
+ if (identityCode === code) return identity;
1087
+ const chunks = [];
1088
+ const units = new Uint16Array(Math.min(code.length, 4096) * 2);
1089
+ for (let start = 0; start < code.length; start += 4096) {
1090
+ const end = Math.min(code.length, start + 4096);
1091
+ for (let index = start; index < end; index += 1) {
1092
+ units[(index - start) * 2] = index >>> 16;
1093
+ units[(index - start) * 2 + 1] = index & 65535;
1094
+ }
1095
+ chunks.push(String.fromCharCode(...units.subarray(0, (end - start) * 2)));
1096
+ }
1097
+ identityCode = code;
1098
+ identity = chunks.join("");
1099
+ return identity;
1100
+ }
1101
+ /**
1102
+ * Code with the origin of each of its characters, so that the source map
1103
+ * can point a copied character back at the one it copies.
1104
+ *
1105
+ * `origins` is `undefined` when the compile writes no source map.
1106
+ */
1107
+ var Text = class {
1108
+ constructor(code, origins) {
1109
+ this.code = code;
1110
+ this.origins = origins;
1111
+ }
1112
+ toString() {
1113
+ return this.code;
1114
+ }
1115
+ };
1116
+ /** The code of a content. */
1117
+ function getCode(content) {
1118
+ return typeof content === "string" ? content : content.code;
1119
+ }
1120
+ /**
1121
+ * Joins contents into one text. The characters of a string take the offset
1122
+ * of the edit that writes the text.
1123
+ */
1124
+ function join(parts, separator = "") {
1125
+ let code = "";
1126
+ let origins = "";
1127
+ for (let index = 0; index < parts.length; index += 1) {
1128
+ const part = parts[index] ?? "";
1129
+ if (index > 0 && separator) {
1130
+ code += separator;
1131
+ if (origins !== void 0) origins += repeatOrigin(LOOSE, separator.length);
1132
+ }
1133
+ if (typeof part === "string") {
1134
+ code += part;
1135
+ if (origins !== void 0) origins += repeatOrigin(LOOSE, part.length);
1136
+ } else {
1137
+ code += part.code;
1138
+ origins = part.origins === void 0 ? void 0 : origins + part.origins;
1139
+ }
1140
+ }
1141
+ return new Text(code, origins);
1142
+ }
1143
+ /** Builds a text from a template, keeping the origins of the texts it holds. */
1144
+ function joinText(strings, ...values) {
1145
+ const parts = [];
1146
+ for (let index = 0; index < strings.length; index += 1) {
1147
+ parts.push(strings[index] ?? "");
1148
+ if (index < values.length) parts.push(values[index] ?? "");
1149
+ }
1150
+ return join(parts);
1151
+ }
1152
+ /** The origins of a content written at an offset. */
1153
+ function resolveOrigins(content, at) {
1154
+ if (typeof content === "string") return repeatOrigin(WRITTEN | at, content.length);
1155
+ const { origins } = content;
1156
+ if (origins === void 0) return repeatOrigin(WRITTEN | at, content.code.length);
1157
+ let result = "";
1158
+ let from = 0;
1159
+ const written = encodeOrigin(WRITTEN | at);
1160
+ let found = origins.indexOf(LOOSE_UNITS);
1161
+ while (found !== -1) {
1162
+ if (found % 2 === 1) {
1163
+ found = origins.indexOf(LOOSE_UNITS, found + 1);
1164
+ continue;
1165
+ }
1166
+ result += origins.slice(from, found) + written;
1167
+ from = found + 2;
1168
+ found = origins.indexOf(LOOSE_UNITS, from);
1169
+ }
1170
+ return from === 0 ? origins : result + origins.slice(from);
1171
+ }
1172
+ /**
1173
+ * Edits code like `MagicString`, and keeps the origin of each character of
1174
+ * the result.
1175
+ *
1176
+ * A second `MagicString` holds the origins, two code units per character,
1177
+ * and takes every edit the first one takes.
1178
+ */
1179
+ var Editor = class Editor {
1180
+ constructor(original, tracksOrigins) {
1181
+ this.original = original;
1182
+ this.tracksOrigins = tracksOrigins;
1183
+ this.s = new MagicString(original);
1184
+ }
1185
+ /** A new editor on the same original code, which keeps origins when this one does. */
1186
+ fresh() {
1187
+ return new Editor(this.original, this.tracksOrigins);
1188
+ }
1189
+ /** The origins to edit, or `undefined` when this editor keeps none. */
1190
+ editOrigins() {
1191
+ if (this.tracksOrigins && !this.o) this.o = new MagicString(createIdentity(this.original));
1192
+ return this.o;
1193
+ }
1194
+ /** Code that a pass writes in place of what is at `at`, mapped there. */
1195
+ written(code, at) {
1196
+ return new Text(code, this.tracksOrigins ? repeatOrigin(WRITTEN | at, code.length) : void 0);
1197
+ }
1198
+ overwrite(start, end, content) {
1199
+ this.s.overwrite(start, end, getCode(content));
1200
+ this.editOrigins()?.overwrite(start * 2, end * 2, resolveOrigins(content, start));
1201
+ return this;
1202
+ }
1203
+ remove(start, end) {
1204
+ this.s.remove(start, end);
1205
+ this.editOrigins()?.remove(start * 2, end * 2);
1206
+ return this;
1207
+ }
1208
+ prependLeft(index, content) {
1209
+ this.s.prependLeft(index, getCode(content));
1210
+ this.editOrigins()?.prependLeft(index * 2, resolveOrigins(content, index));
1211
+ return this;
1212
+ }
1213
+ prependRight(index, content) {
1214
+ this.s.prependRight(index, getCode(content));
1215
+ this.editOrigins()?.prependRight(index * 2, resolveOrigins(content, index));
1216
+ return this;
1217
+ }
1218
+ appendLeft(index, content) {
1219
+ this.s.appendLeft(index, getCode(content));
1220
+ this.editOrigins()?.appendLeft(index * 2, resolveOrigins(content, index));
1221
+ return this;
1222
+ }
1223
+ /** The edited code of characters `start` to `end` of the original, with origins. */
1224
+ slice(start, end) {
1225
+ let origins;
1226
+ if (this.o) origins = this.o.slice(start * 2, end * 2);
1227
+ else if (this.tracksOrigins) origins = createIdentity(this.original).slice(start * 2, end * 2);
1228
+ return new Text(this.s.slice(start, end), origins);
1229
+ }
1230
+ toString() {
1231
+ return this.s.toString();
1232
+ }
1233
+ /**
1234
+ * A map from the edited code to the original. A copied character maps to
1235
+ * the one it copies, and a written run maps to where it was written.
1236
+ */
1237
+ generateMap(source) {
1238
+ const code = this.s.toString();
1239
+ const origins = this.o?.toString() ?? createIdentity(this.original);
1240
+ const lineStarts = [0];
1241
+ for (let index = 0; index < this.original.length; index += 1) if (this.original.charCodeAt(index) === 10) lineStarts.push(index + 1);
1242
+ const mappings = [[]];
1243
+ let line = mappings[0] ?? [];
1244
+ let column = 0;
1245
+ let previous = LOOSE;
1246
+ let sourceLine = 0;
1247
+ let sourceColumn = 0;
1248
+ for (let index = 0; index < code.length; index += 1) {
1249
+ const origin = decodeOrigin(origins, index);
1250
+ if (origin < WRITTEN) {
1251
+ if (origin === previous + 1 && this.original.charCodeAt(previous) !== 10) sourceColumn += 1;
1252
+ else {
1253
+ sourceLine = findLine(lineStarts, origin);
1254
+ sourceColumn = origin - (lineStarts[sourceLine] ?? 0);
1255
+ }
1256
+ line.push([
1257
+ column,
1258
+ 0,
1259
+ sourceLine,
1260
+ sourceColumn
1261
+ ]);
1262
+ } else if (origin !== previous || column === 0) {
1263
+ const offset = origin - WRITTEN;
1264
+ const written = findLine(lineStarts, offset);
1265
+ line.push([
1266
+ column,
1267
+ 0,
1268
+ written,
1269
+ offset - (lineStarts[written] ?? 0)
1270
+ ]);
1271
+ }
1272
+ previous = origin;
1273
+ if (code.charCodeAt(index) === 10) {
1274
+ line = [];
1275
+ mappings.push(line);
1276
+ column = 0;
1277
+ } else column += 1;
1278
+ }
1279
+ return {
1280
+ version: 3,
1281
+ file: null,
1282
+ names: [],
1283
+ sources: [source],
1284
+ sourcesContent: [this.original],
1285
+ mappings
1286
+ };
1287
+ }
1288
+ };
1289
+ //#endregion
982
1290
  //#region src/jsx.ts
983
1291
  function keptPiece(node) {
984
- const text = node.type === "JSXText" ? node : void 0;
1292
+ const text = node.type === "JSXText" ? node.value : void 0;
985
1293
  return {
986
1294
  node,
987
1295
  text: void 0,
@@ -996,39 +1304,52 @@ function splicePiece(s, node, children) {
996
1304
  const first = children.at(0);
997
1305
  const last = children.at(-1);
998
1306
  if (!first || !last) return replacedPiece(node, "");
999
- return {
1000
- node,
1001
- text: s.slice(first.start, last.end),
1002
- startText: first.type === "JSXText" ? first : void 0,
1003
- endText: last.type === "JSXText" ? last : void 0
1004
- };
1307
+ return replacedPiece(node, s.slice(first.start, last.end));
1005
1308
  }
1309
+ /**
1310
+ * A piece that writes `text`, JSX children as source, in place of `node`.
1311
+ *
1312
+ * The texts it starts and ends with are read from `text` itself, not from
1313
+ * the children it came from. A fold inside them in the same round can have
1314
+ * turned a child that was an element into text, such as an inner `<Show>`.
1315
+ * JSX text holds no `<`, `>`, `{`, or `}`, so the first and last of those
1316
+ * mark where the text ends.
1317
+ */
1006
1318
  function replacedPiece(node, text) {
1319
+ const code = getCode(text);
1320
+ const start = code.search(/[<{]/);
1321
+ const end = Math.max(code.lastIndexOf(">"), code.lastIndexOf("}"));
1322
+ const startText = start === -1 ? code : code.slice(0, start);
1323
+ const endText = code.slice(end + 1);
1007
1324
  return {
1008
1325
  node,
1009
1326
  text,
1010
- startText: void 0,
1011
- endText: void 0
1327
+ startText: startText === "" ? void 0 : startText,
1328
+ endText: endText === "" ? void 0 : endText
1012
1329
  };
1013
1330
  }
1331
+ /** Whether JSX drops this text: whitespace that contains a line break. */
1332
+ function isDroppedText(text) {
1333
+ return /^\s*$/.test(text) && /[\r\n]/.test(text);
1334
+ }
1014
1335
  /**
1015
1336
  * Whether two texts render differently as one text node than apart.
1016
1337
  * Two texts that JSX drops, like line breaks and indentation, still drop together.
1017
1338
  */
1018
1339
  function mergeChangesText(before, after) {
1019
- return before !== void 0 && after !== void 0 && !(isFilteredText(before) && isFilteredText(after));
1340
+ return before !== void 0 && after !== void 0 && !(isDroppedText(before) && isDroppedText(after));
1020
1341
  }
1021
1342
  /**
1022
1343
  * Puts `{}` between two pieces that meet as text, on whichever side is replaced.
1023
1344
  */
1024
1345
  function separate(previous, next, emptiesBetween) {
1025
1346
  if (next.text !== void 0) {
1026
- next.text = `{}${next.text}`;
1347
+ next.text = joinText`{}${next.text}`;
1027
1348
  next.startText = void 0;
1028
1349
  return;
1029
1350
  }
1030
1351
  if (previous.text !== void 0) {
1031
- previous.text = `${previous.text}{}`;
1352
+ previous.text = joinText`${previous.text}{}`;
1032
1353
  previous.endText = void 0;
1033
1354
  return;
1034
1355
  }
@@ -1044,7 +1365,7 @@ function writePieces(s, pieces) {
1044
1365
  let previous;
1045
1366
  let emptiesSincePrevious = [];
1046
1367
  for (const piece of pieces) {
1047
- if (piece.text === "") {
1368
+ if (piece.text !== void 0 && getCode(piece.text) === "") {
1048
1369
  emptiesSincePrevious.push(piece);
1049
1370
  continue;
1050
1371
  }
@@ -1055,7 +1376,7 @@ function writePieces(s, pieces) {
1055
1376
  for (const piece of pieces) {
1056
1377
  if (piece.text === void 0) continue;
1057
1378
  changed = true;
1058
- if (piece.text === "") s.remove(piece.node.start, piece.node.end);
1379
+ if (getCode(piece.text) === "") s.remove(piece.node.start, piece.node.end);
1059
1380
  else s.overwrite(piece.node.start, piece.node.end, piece.text);
1060
1381
  }
1061
1382
  return changed;
@@ -1064,19 +1385,21 @@ function findAttribute(element, name) {
1064
1385
  for (const attribute of element.openingElement.attributes) if (attribute.type === "JSXAttribute" && attribute.name.type === "JSXIdentifier" && attribute.name.name === name) return attribute;
1065
1386
  }
1066
1387
  function hasSpreadAttribute(element) {
1067
- return element.openingElement.attributes.some((attribute) => attribute.type === "JSXSpreadAttribute");
1388
+ for (const attribute of element.openingElement.attributes) if (attribute.type === "JSXSpreadAttribute") return true;
1389
+ return false;
1068
1390
  }
1069
1391
  /**
1070
1392
  * Whether any child is a function, which the runtime may call with the
1071
1393
  * narrowed value. Folding one away would drop that call.
1072
1394
  */
1073
1395
  function hasCallbackChild(children) {
1074
- return children.some((child) => {
1075
- if (child.type !== "JSXExpressionContainer") return false;
1396
+ for (const child of children) {
1397
+ if (child.type !== "JSXExpressionContainer") continue;
1076
1398
  let expression = child.expression;
1077
1399
  while (expression.type === "ParenthesizedExpression") expression = expression.expression;
1078
- return expression.type === "ArrowFunctionExpression" || expression.type === "FunctionExpression";
1079
- });
1400
+ if (expression.type === "ArrowFunctionExpression" || expression.type === "FunctionExpression") return true;
1401
+ }
1402
+ return false;
1080
1403
  }
1081
1404
  /**
1082
1405
  * The text between an element's tags, or an empty string for a self-closing element.
@@ -1255,7 +1578,8 @@ var SizeEstimator = class {
1255
1578
  }
1256
1579
  } else size += name.length + GETTER + this.jsx(value, false);
1257
1580
  }
1258
- const significant = element.children.filter((child) => !isInsignificant(child));
1581
+ const significant = [];
1582
+ for (const child of element.children) if (!isInsignificant(child)) significant.push(child);
1259
1583
  if (significant.length > 0) size += 24 + this.children(significant);
1260
1584
  return size + (spread ? MERGE : 0);
1261
1585
  }
@@ -1286,6 +1610,18 @@ const EMPTY = { kind: "empty" };
1286
1610
  /** Solid's calls that only create a value, so the bundler can drop an unused one. */
1287
1611
  const PURE_CALLS = /* @__PURE__ */ new Set(["lazy", "createContext"]);
1288
1612
  /**
1613
+ * Solid's calls that only create a value when their first argument is not a
1614
+ * function. Given a function, they create a computation, which runs it.
1615
+ */
1616
+ const PURE_VALUE_CALLS = /* @__PURE__ */ new Set(["createSignal", "createStore"]);
1617
+ /** Expression types that are never a function. */
1618
+ const NOT_FUNCTION = /* @__PURE__ */ new Set([
1619
+ "Literal",
1620
+ "TemplateLiteral",
1621
+ "ObjectExpression",
1622
+ "ArrayExpression"
1623
+ ]);
1624
+ /**
1289
1625
  * The globals worth folding. They only apply to a reference that binds to
1290
1626
  * nothing, which is when the global is what runs.
1291
1627
  */
@@ -1335,6 +1671,29 @@ function containsHoistedDeclaration(statement) {
1335
1671
  visit(statement);
1336
1672
  return found;
1337
1673
  }
1674
+ /** The source text of each node. */
1675
+ function getTexts(context, nodes) {
1676
+ const texts = [];
1677
+ for (const node of nodes) texts.push(getText(context, node));
1678
+ return texts;
1679
+ }
1680
+ /** The children that are not whitespace-only text or an empty expression. */
1681
+ function getSignificant(children) {
1682
+ const significant = [];
1683
+ for (const child of children) if (!isInsignificant(child)) significant.push(child);
1684
+ return significant;
1685
+ }
1686
+ /** Whether the element has a `keyed` attribute that is not `{false}`. */
1687
+ function hasEnabledKeyed(element) {
1688
+ for (const attribute of element.openingElement.attributes) if (attribute.type === "JSXAttribute" && attribute.name.type === "JSXIdentifier" && attribute.name.name === "keyed" && !(attribute.value?.type === "JSXExpressionContainer" && attribute.value.expression.type === "Literal" && attribute.value.expression.value === false)) return true;
1689
+ return false;
1690
+ }
1691
+ /** The summed size estimate of the children of a fragment spliced into a template. */
1692
+ function estimateChildren(estimator, children) {
1693
+ let size = 0;
1694
+ for (const child of children) size += child.type === "JSXElement" ? estimator.jsx(child, true) : estimator.node(child);
1695
+ return size;
1696
+ }
1338
1697
  /**
1339
1698
  * Whether a statement starting with `text` could join the statement before
1340
1699
  * it when that one has no semicolon.
@@ -1347,6 +1706,12 @@ function keyName(node) {
1347
1706
  if (node.type === "Identifier") return node.name;
1348
1707
  return node.type === "Literal" && typeof node.value === "string" ? node.value : void 0;
1349
1708
  }
1709
+ /** Whether a call has no first argument, or one that is never a function. */
1710
+ function isValueArgument(call) {
1711
+ if (call.arguments.length === 0) return true;
1712
+ const first = call.arguments[0];
1713
+ return first.type !== "SpreadElement" && NOT_FUNCTION.has(unwrap(first).type);
1714
+ }
1350
1715
  /**
1351
1716
  * The text of an expression that always gives the same primitive: a literal
1352
1717
  * other than a regular expression, a template literal without expressions,
@@ -1356,9 +1721,9 @@ function primitiveText(context, node) {
1356
1721
  let expression = node;
1357
1722
  while (expression.type === "ParenthesizedExpression") expression = expression.expression;
1358
1723
  switch (expression.type) {
1359
- case "Literal": return "regex" in expression ? void 0 : textOf(context, expression);
1360
- case "TemplateLiteral": return expression.expressions.length === 0 ? textOf(context, expression) : void 0;
1361
- case "UnaryExpression": return expression.operator === "-" && expression.argument.type === "Literal" && typeof expression.argument.value === "number" ? textOf(context, expression) : void 0;
1724
+ case "Literal": return "regex" in expression ? void 0 : getText(context, expression);
1725
+ case "TemplateLiteral": return expression.expressions.length === 0 ? getText(context, expression) : void 0;
1726
+ case "UnaryExpression": return expression.operator === "-" && expression.argument.type === "Literal" && typeof expression.argument.value === "number" ? getText(context, expression) : void 0;
1362
1727
  default: return;
1363
1728
  }
1364
1729
  }
@@ -1388,9 +1753,11 @@ var Folder = class {
1388
1753
  constructor(context) {
1389
1754
  this.context = context;
1390
1755
  this.changed = false;
1756
+ this.removed = /* @__PURE__ */ new Set();
1391
1757
  this.lookup = new ConstantTable(context.scopes, context.options).lookup;
1392
1758
  }
1393
1759
  walk(node) {
1760
+ if (this.removed.has(node)) return;
1394
1761
  forEachChild(node, (child) => {
1395
1762
  this.walk(child);
1396
1763
  });
@@ -1433,14 +1800,16 @@ var Folder = class {
1433
1800
  case "MemberExpression":
1434
1801
  if (!isWriteTarget(node, this.context.parents)) this.foldConstant(node);
1435
1802
  break;
1436
- case "CallExpression": this.annotatePure(node);
1803
+ case "CallExpression":
1804
+ this.annotatePure(node);
1805
+ this.foldUntrack(node);
1437
1806
  }
1438
1807
  }
1439
1808
  isJSXChildOrAttribute(node) {
1440
1809
  return isJSXChild(node, this.context.parents) || this.context.parents.get(node)?.type === "JSXAttribute";
1441
1810
  }
1442
1811
  replace(node, text) {
1443
- if (textOf(this.context, node) === text) return;
1812
+ if (getText(this.context, node).code === getCode(text)) return;
1444
1813
  this.context.s.overwrite(node.start, node.end, text);
1445
1814
  this.changed = true;
1446
1815
  }
@@ -1450,20 +1819,39 @@ var Folder = class {
1450
1819
  * branch can leave it unused, and the annotation lets the bundler drop it
1451
1820
  * along with its dynamic import. `createContext` only creates the context,
1452
1821
  * which inlining can leave unused.
1822
+ *
1823
+ * `createSignal` and `createStore` with a first argument that is not a
1824
+ * function only create a node. It takes no owner and no hydration id, so
1825
+ * dropping an unused one changes nothing else.
1453
1826
  */
1454
1827
  annotatePure(call) {
1455
1828
  if (call.callee.type !== "Identifier") return;
1456
1829
  const binding = this.context.scopes.references.get(call.callee);
1457
1830
  const identity = binding ? solidExport(binding, this.context.options) : void 0;
1458
- if (identity === void 0 || !PURE_CALLS.has(identity)) return;
1831
+ if (identity === void 0) return;
1832
+ if (!PURE_CALLS.has(identity) && !(PURE_VALUE_CALLS.has(identity) && isValueArgument(call))) return;
1459
1833
  const before = this.context.code.slice(0, call.start).trimEnd();
1460
1834
  if (/(#|@)__PURE__\s*\*\/$/.test(before)) return;
1461
1835
  this.context.s.prependLeft(call.start, "/* @__PURE__ */ ");
1462
1836
  this.changed = true;
1463
1837
  }
1464
- foldConstant(node) {
1838
+ /**
1839
+ * `untrack(() => value)` is the value, when the value is a constant.
1840
+ * Nothing is read, so there is nothing to untrack. A component inlined
1841
+ * with a literal prop leaves this, like Kobalte's `untrack(() => props.as)`.
1842
+ */
1843
+ foldUntrack(call) {
1844
+ if (call.callee.type !== "Identifier" || call.arguments.length !== 1) return;
1845
+ const binding = this.context.scopes.references.get(call.callee);
1846
+ const identity = binding ? solidExport(binding, this.context.options) : void 0;
1847
+ const callback = call.arguments.at(0);
1848
+ if (identity !== "untrack" || callback?.type !== "ArrowFunctionExpression" || callback.async || callback.params.length > 0 || !callback.expression || callback.body.type === "BlockStatement") return;
1849
+ const value = evaluate(callback.body, this.lookup);
1850
+ if (value) this.foldConstant(call, value);
1851
+ }
1852
+ foldConstant(node, known) {
1465
1853
  if (isLiteralForm(node)) return;
1466
- const value = evaluate(node, this.lookup);
1854
+ const value = known ?? evaluate(node, this.lookup);
1467
1855
  if (!value) return;
1468
1856
  let text = literalText(value.value);
1469
1857
  if (text === void 0) return;
@@ -1486,12 +1874,12 @@ var Folder = class {
1486
1874
  keepAfter(target, discarded, value) {
1487
1875
  const parts = discarded ? effectfulParts(discarded) : [];
1488
1876
  if (parts.length === 0) {
1489
- const text = textOf(this.context, value);
1490
- return needsParensAt(target, value, this.context.parents) ? `(${text})` : text;
1877
+ const text = getText(this.context, value);
1878
+ return needsParensAt(target, value, this.context.parents) ? joinText`(${text})` : text;
1491
1879
  }
1492
- const texts = parts.map((part) => textOf(this.context, part));
1493
- texts.push(textOf(this.context, value));
1494
- return `(${texts.join(", ")})`;
1880
+ const texts = getTexts(this.context, parts);
1881
+ texts.push(getText(this.context, value));
1882
+ return joinText`(${join(texts, ", ")})`;
1495
1883
  }
1496
1884
  foldLogical(node) {
1497
1885
  const left = truthiness(node.left, this.lookup);
@@ -1608,27 +1996,38 @@ var Folder = class {
1608
1996
  if (value.value.includes("&")) return;
1609
1997
  return {
1610
1998
  kind: "expression",
1611
- text: JSON.stringify(value.value),
1999
+ text: this.context.s.written(JSON.stringify(value.value), value.start),
1612
2000
  primary: true
1613
2001
  };
1614
2002
  case "JSXElement":
1615
- case "JSXFragment": return {
1616
- kind: "jsx",
1617
- text: textOf(this.context, value)
1618
- };
2003
+ case "JSXFragment": return this.foldedJSX(value);
1619
2004
  default:
1620
2005
  if (value.expression.type === "JSXEmptyExpression") return EMPTY;
1621
- if (value.expression.type === "JSXElement" || value.expression.type === "JSXFragment") return {
1622
- kind: "jsx",
1623
- text: textOf(this.context, value.expression)
1624
- };
2006
+ if (value.expression.type === "JSXElement" || value.expression.type === "JSXFragment") return this.foldedJSX(value.expression);
1625
2007
  return {
1626
2008
  kind: "expression",
1627
- text: textOf(this.context, value.expression),
2009
+ text: getText(this.context, value.expression),
1628
2010
  primary: isPrimary(value.expression)
1629
2011
  };
1630
2012
  }
1631
2013
  }
2014
+ /**
2015
+ * What a JSX value renders, read after the folds of this round. A fold
2016
+ * inside it can have replaced it with an expression already, such as an
2017
+ * inner `<Show>` that became its string `fallback`.
2018
+ */
2019
+ foldedJSX(node) {
2020
+ const text = getText(this.context, node);
2021
+ if (text.code.startsWith("<")) return {
2022
+ kind: "jsx",
2023
+ text
2024
+ };
2025
+ return {
2026
+ kind: "expression",
2027
+ text,
2028
+ primary: false
2029
+ };
2030
+ }
1632
2031
  foldShow(element) {
1633
2032
  const when = this.attributeTruthiness(element, "when");
1634
2033
  if (when === void 0) return;
@@ -1660,11 +2059,11 @@ var Folder = class {
1660
2059
  * would run while the copy is made, so either one keeps the loop.
1661
2060
  */
1662
2061
  unrollFor(element, expression) {
1663
- if (element.openingElement.attributes.some((attribute) => attribute.type === "JSXAttribute" && attribute.name.type === "JSXIdentifier" && attribute.name.name === "keyed" && !(attribute.value?.type === "JSXExpressionContainer" && attribute.value.expression.type === "Literal" && attribute.value.expression.value === false))) return;
2062
+ if (hasEnabledKeyed(element)) return;
1664
2063
  const byIndex = findAttribute(element, "keyed") !== void 0;
1665
2064
  const list = this.constantList(expression);
1666
2065
  if (!list) return;
1667
- const significant = element.children.filter((child) => !isInsignificant(child));
2066
+ const significant = getSignificant(element.children);
1668
2067
  const only = significant.at(0);
1669
2068
  if (significant.length !== 1 || only?.type !== "JSXExpressionContainer") return;
1670
2069
  let row = only.expression;
@@ -1673,7 +2072,7 @@ var Folder = class {
1673
2072
  let body = row.body;
1674
2073
  while (body.type === "ParenthesizedExpression") body = body.expression;
1675
2074
  if (body.type !== "JSXElement" && body.type !== "JSXFragment" || hasRefOrSpread(body)) return;
1676
- if (this.context.s.slice(body.start, body.end) !== this.context.code.slice(body.start, body.end)) return;
2075
+ if (this.context.s.slice(body.start, body.end).code !== this.context.code.slice(body.start, body.end)) return;
1677
2076
  const scope = this.context.scopes.scopes.get(row);
1678
2077
  if (!scope) return;
1679
2078
  const params = [];
@@ -1686,11 +2085,11 @@ var Folder = class {
1686
2085
  const indexParam = params.at(1);
1687
2086
  const rows = [];
1688
2087
  for (const [index, item] of list.items.entries()) {
1689
- const copy = new MagicString(this.context.code);
2088
+ const copy = this.context.s.fresh();
1690
2089
  if (itemParam && !this.substituteItem(copy, itemParam, item, byIndex) || indexParam && !this.substituteIndex(copy, indexParam, index, !byIndex)) return;
1691
2090
  rows.push(copy.slice(body.start, body.end));
1692
2091
  }
1693
- const text = `<>${rows.join("")}</>`;
2092
+ const text = joinText`<>${join(rows)}</>`;
1694
2093
  if (!this.unrollingPays(element, text, list.declaration)) return;
1695
2094
  return {
1696
2095
  kind: "jsx",
@@ -1702,16 +2101,20 @@ var Folder = class {
1702
2101
  * `<For>` reads it.
1703
2102
  */
1704
2103
  constantList(expression) {
1705
- let node = expression;
1706
- while (node.type === "ParenthesizedExpression") node = node.expression;
2104
+ let node = unwrap(expression);
1707
2105
  let declaration;
1708
2106
  if (node.type === "Identifier") {
1709
2107
  const binding = this.context.scopes.references.get(node);
1710
2108
  if (binding?.declaration.type !== "VariableDeclarator" || binding.declaration.id !== binding.identifier || !binding.declaration.init || !isConstantDeclaration(binding, this.context.options)) return;
1711
2109
  const statement = this.context.parents.get(binding.declaration);
1712
- if ((statement ? this.context.parents.get(statement) : void 0)?.type === "ExportNamedDeclaration" || !binding.references.every((reference) => this.isForEach(reference))) return;
1713
- node = binding.declaration.init;
1714
- while (node.type === "ParenthesizedExpression") node = node.expression;
2110
+ const owner = statement ? this.context.parents.get(statement) : void 0;
2111
+ let onlyForEach = true;
2112
+ for (const reference of binding.references) if (!this.isForEach(reference)) {
2113
+ onlyForEach = false;
2114
+ break;
2115
+ }
2116
+ if (owner?.type === "ExportNamedDeclaration" || !onlyForEach) return;
2117
+ node = unwrap(binding.declaration.init);
1715
2118
  declaration = binding.references.length === 1 && statement?.type === "VariableDeclaration" && statement.declarations.length === 1 ? statement : void 0;
1716
2119
  }
1717
2120
  if (node.type !== "ArrayExpression") return;
@@ -1784,7 +2187,7 @@ var Folder = class {
1784
2187
  }
1785
2188
  /** A value's text in place of `node`, with parentheses unless it fills a JSX container. */
1786
2189
  valueAt(node, text) {
1787
- return this.context.parents.get(node)?.type === "JSXExpressionContainer" ? text : `(${text})`;
2190
+ return this.context.parents.get(node)?.type === "JSXExpressionContainer" ? text : joinText`(${text})`;
1788
2191
  }
1789
2192
  /** Writes an item's index over each read of the row's index parameter. */
1790
2193
  substituteIndex(copy, param, index, accessor) {
@@ -1806,12 +2209,12 @@ var Folder = class {
1806
2209
  unrollingPays(element, text, declaration) {
1807
2210
  const inTemplate = this.joinsParentTemplate(element);
1808
2211
  const loop = new SizeEstimator(this.context.code).jsx(element, inTemplate) + (declaration ? compactLength(this.context.code.slice(declaration.start, declaration.end)) : 0);
1809
- const code = `const __so_rows__ = ${text};`;
1810
- const statement = parse(this.context.filename, code).body.at(0);
2212
+ const code = `const __so_rows__ = ${text.code};`;
2213
+ const statement = parse$1(this.context.filename, code).body.at(0);
1811
2214
  const init = statement?.type === "VariableDeclaration" ? statement.declarations.at(0)?.init : void 0;
1812
2215
  if (init?.type !== "JSXFragment") return false;
1813
2216
  const estimator = new SizeEstimator(code);
1814
- return (inTemplate ? init.children.reduce((size, child) => size + (child.type === "JSXElement" ? estimator.jsx(child, true) : estimator.node(child)), 0) : estimator.jsx(init, false)) <= loop;
2217
+ return (inTemplate ? estimateChildren(estimator, init.children) : estimator.jsx(init, false)) <= loop;
1815
2218
  }
1816
2219
  /** Whether an element sits directly in an element or fragment whose template it joins. */
1817
2220
  joinsParentTemplate(element) {
@@ -1843,8 +2246,16 @@ var Folder = class {
1843
2246
  });
1844
2247
  }
1845
2248
  if (matches.length === 0) return;
1846
- const winner = matches.findIndex((item) => item.when === true);
1847
- if (winner !== -1 && matches.slice(0, winner).every((item) => item.when === false)) {
2249
+ let winner = -1;
2250
+ let allFalse = true;
2251
+ for (const [index, item] of matches.entries()) {
2252
+ if (item.when === true) {
2253
+ winner = index;
2254
+ break;
2255
+ }
2256
+ if (item.when !== false) allFalse = false;
2257
+ }
2258
+ if (winner !== -1 && allFalse) {
1848
2259
  const match = matches.at(winner);
1849
2260
  if (!match || hasCallbackChild(match.element.children)) return;
1850
2261
  return {
@@ -1852,7 +2263,7 @@ var Folder = class {
1852
2263
  children: match.element.children
1853
2264
  };
1854
2265
  }
1855
- if (matches.every((item) => item.when === false)) return this.fallback(element);
2266
+ if (winner === -1 && allFalse) return this.fallback(element);
1856
2267
  for (const item of matches) if (item.when === false) {
1857
2268
  this.context.s.remove(item.element.start, item.element.end);
1858
2269
  this.changed = true;
@@ -1883,11 +2294,12 @@ var Folder = class {
1883
2294
  }
1884
2295
  }
1885
2296
  if (tag === void 0) return;
1886
- const attributes = element.openingElement.attributes.filter((attribute) => attribute !== component).map((attribute) => textOf(this.context, attribute));
1887
- const opening = [tag, ...attributes].join(" ");
2297
+ const attributes = [tag];
2298
+ for (const attribute of element.openingElement.attributes) if (attribute !== component) attributes.push(getText(this.context, attribute));
2299
+ const opening = join(attributes, " ");
1888
2300
  return {
1889
2301
  kind: "jsx",
1890
- text: element.closingElement ? `<${opening}>${innerText(this.context.s, element)}</${tag}>` : `<${opening} />`
2302
+ text: element.closingElement ? joinText`<${opening}>${innerText(this.context.s, element)}</${tag}>` : joinText`<${opening} />`
1891
2303
  };
1892
2304
  }
1893
2305
  /**
@@ -1902,16 +2314,16 @@ var Folder = class {
1902
2314
  switch (resolved.kind) {
1903
2315
  case "empty": return "null";
1904
2316
  case "jsx": return resolved.text;
1905
- case "expression": return resolved.primary ? resolved.text : `(${resolved.text})`;
2317
+ case "expression": return resolved.primary ? resolved.text : joinText`(${resolved.text})`;
1906
2318
  default: {
1907
- const significant = resolved.children.filter((child) => !isInsignificant(child));
2319
+ const significant = getSignificant(resolved.children);
1908
2320
  const only = significant.at(0);
1909
2321
  if (only === void 0) return "null";
1910
- if (significant.length === 1 && (only.type === "JSXElement" || only.type === "JSXFragment")) return textOf(this.context, only);
2322
+ if (significant.length === 1 && (only.type === "JSXElement" || only.type === "JSXFragment")) return getText(this.context, only);
1911
2323
  const first = resolved.children.at(0);
1912
2324
  const last = resolved.children.at(-1);
1913
2325
  if (!first || !last) return "null";
1914
- return `<>${this.context.s.slice(first.start, last.end)}</>`;
2326
+ return joinText`<>${this.context.s.slice(first.start, last.end)}</>`;
1915
2327
  }
1916
2328
  }
1917
2329
  }
@@ -1947,7 +2359,7 @@ var Folder = class {
1947
2359
  pieces.push(replacedPiece(child, resolved.text));
1948
2360
  break;
1949
2361
  case "expression":
1950
- pieces.push(replacedPiece(child, `{${resolved.text}}`));
2362
+ pieces.push(replacedPiece(child, joinText`{${resolved.text}}`));
1951
2363
  break;
1952
2364
  default: pieces.push(replacedPiece(child, ""));
1953
2365
  }
@@ -1978,10 +2390,10 @@ var Folder = class {
1978
2390
  const { params } = callee;
1979
2391
  const args = expression.arguments;
1980
2392
  if (params.length !== args.length || hasRefOrSpread(body)) return;
1981
- if (this.context.s.slice(body.start, body.end) !== this.context.code.slice(body.start, body.end)) return;
2393
+ if (this.context.s.slice(body.start, body.end).code !== this.context.code.slice(body.start, body.end)) return;
1982
2394
  const scope = this.context.scopes.scopes.get(callee);
1983
2395
  if (!scope) return;
1984
- const copy = new MagicString(this.context.code);
2396
+ const copy = this.context.s.fresh();
1985
2397
  for (const [index, param] of params.entries()) {
1986
2398
  const arg = args.at(index);
1987
2399
  if (param.type !== "Identifier" || !arg || arg.type === "SpreadElement") return;
@@ -1992,7 +2404,7 @@ var Folder = class {
1992
2404
  if (arg.type === "Identifier" && lookup(scopeAt(this.context.scopes, this.context.parents, reference), arg.name) !== this.context.scopes.references.get(arg)) return;
1993
2405
  const parent = this.context.parents.get(reference);
1994
2406
  const shorthand = parent?.type === "Property" && parent.shorthand && parent.value === reference;
1995
- copy.overwrite(reference.start, reference.end, shorthand ? `${param.name}: ${text}` : text);
2407
+ copy.overwrite(reference.start, reference.end, shorthand ? joinText`${param.name}: ${text}` : text);
1996
2408
  }
1997
2409
  }
1998
2410
  return copy.slice(body.start, body.end);
@@ -2002,9 +2414,9 @@ var Folder = class {
2002
2414
  let node = arg;
2003
2415
  while (node.type === "ParenthesizedExpression") node = node.expression;
2004
2416
  switch (node.type) {
2005
- case "Literal": return "regex" in node ? void 0 : textOf(this.context, node);
2006
- case "TemplateLiteral": return node.expressions.length === 0 ? textOf(this.context, node) : void 0;
2007
- case "UnaryExpression": return node.operator === "-" && node.argument.type === "Literal" ? `(${textOf(this.context, node)})` : void 0;
2417
+ case "Literal": return "regex" in node ? void 0 : getText(this.context, node);
2418
+ case "TemplateLiteral": return node.expressions.length === 0 ? getText(this.context, node) : void 0;
2419
+ case "UnaryExpression": return node.operator === "-" && node.argument.type === "Literal" ? joinText`(${getText(this.context, node)})` : void 0;
2008
2420
  case "Identifier": {
2009
2421
  const binding = this.context.scopes.references.get(node);
2010
2422
  return binding && !binding.mutated ? node.name : void 0;
@@ -2026,18 +2438,73 @@ var Folder = class {
2026
2438
  const unreachable = statements.slice(terminator + 1);
2027
2439
  const first = unreachable.at(0);
2028
2440
  const last = unreachable.at(-1);
2029
- if (first && last && !unreachable.some(containsHoistedDeclaration)) {
2441
+ let hoists = false;
2442
+ for (const statement of unreachable) if (containsHoistedDeclaration(statement)) {
2443
+ hoists = true;
2444
+ break;
2445
+ }
2446
+ if (first && last && !hoists) {
2030
2447
  this.context.s.remove(first.start, last.end);
2031
2448
  this.changed = true;
2032
2449
  }
2033
2450
  }
2451
+ /**
2452
+ * Removes each declaration inside a function that nothing references. The
2453
+ * references are those of the code this pass parsed, so a binding whose last
2454
+ * read this pass folds is removed in the next round.
2455
+ */
2456
+ removeUnusedDeclarations() {
2457
+ for (const scope of this.context.scopes.scopes.values()) {
2458
+ if (scope === this.context.scopes.root) continue;
2459
+ for (const binding of scope.bindings.values()) {
2460
+ const declaration = this.unusedDeclaration(binding);
2461
+ if (declaration && !this.removed.has(declaration)) {
2462
+ this.removed.add(declaration);
2463
+ this.context.s.remove(declaration.start, declaration.end);
2464
+ this.changed = true;
2465
+ }
2466
+ }
2467
+ }
2468
+ }
2469
+ /**
2470
+ * The declaration statement of `binding` when every binding it declares is
2471
+ * unused and every initializer can be skipped.
2472
+ */
2473
+ unusedDeclaration(binding) {
2474
+ if (binding.declaration.type !== "VariableDeclarator") return;
2475
+ const statement = this.context.parents.get(binding.declaration);
2476
+ if (statement?.type !== "VariableDeclaration" || statement.kind !== "const" && statement.kind !== "let" || statement.declare) return;
2477
+ const container = this.context.parents.get(statement)?.type;
2478
+ if (container !== "BlockStatement" && container !== "StaticBlock" && container !== "SwitchCase") return;
2479
+ for (const declarator of statement.declarations) {
2480
+ if (declarator.id.type !== "Identifier") return;
2481
+ const declared = binding.scope.bindings.get(declarator.id.name);
2482
+ if (!declared || declared.mutated || declared.references.length > 0) return;
2483
+ if (declarator.init && !this.isSkippableInit(declarator.init)) return;
2484
+ }
2485
+ return statement;
2486
+ }
2487
+ /**
2488
+ * Whether an unused initializer can be dropped: an expression with no side
2489
+ * effects, or a Solid call that only creates a value from such arguments.
2490
+ */
2491
+ isSkippableInit(init) {
2492
+ if (isSideEffectFree(init)) return true;
2493
+ const call = unwrap(init);
2494
+ if (call.type !== "CallExpression" || call.callee.type !== "Identifier") return false;
2495
+ const callee = this.context.scopes.references.get(call.callee);
2496
+ const identity = callee ? solidExport(callee, this.context.options) : void 0;
2497
+ if (identity === void 0 || !PURE_CALLS.has(identity) && !(PURE_VALUE_CALLS.has(identity) && isValueArgument(call))) return false;
2498
+ for (const argument of call.arguments) if (argument.type === "SpreadElement" || !isSideEffectFree(argument)) return false;
2499
+ return true;
2500
+ }
2034
2501
  replaceStatement(statement, text) {
2035
- if (text === "") {
2502
+ if (getCode(text) === "") {
2036
2503
  this.context.s.remove(statement.start, statement.end);
2037
2504
  this.changed = true;
2038
2505
  return;
2039
2506
  }
2040
- this.replace(statement, continuesPreviousStatement(text) ? `;${text}` : text);
2507
+ this.replace(statement, continuesPreviousStatement(getCode(text)) ? joinText`;${text}` : text);
2041
2508
  }
2042
2509
  /**
2043
2510
  * A statement that keeps a discarded test's side effects, or `undefined`
@@ -2047,8 +2514,8 @@ var Folder = class {
2047
2514
  const parts = effectfulParts(test);
2048
2515
  const first = parts.at(0);
2049
2516
  if (first === void 0) return;
2050
- const text = parts.map((part) => textOf(this.context, part)).join(", ");
2051
- return startsLikeStatement(first) ? `(${text});` : `${text};`;
2517
+ const text = join(getTexts(this.context, parts), ", ");
2518
+ return startsLikeStatement(first) ? joinText`(${text});` : joinText`${text};`;
2052
2519
  }
2053
2520
  /**
2054
2521
  * Resolves an `if` with a constant test. Returns the kept branch, `null`
@@ -2064,8 +2531,8 @@ var Folder = class {
2064
2531
  const parts = [];
2065
2532
  const effect = this.discardedTest(statement.test);
2066
2533
  if (effect !== void 0) parts.push(effect);
2067
- if (kept) parts.push(textOf(this.context, kept));
2068
- this.replaceStatement(statement, parts.join(" "));
2534
+ if (kept) parts.push(getText(this.context, kept));
2535
+ this.replaceStatement(statement, join(parts, " "));
2069
2536
  return kept;
2070
2537
  }
2071
2538
  resolveWhile(statement) {
@@ -2079,6 +2546,7 @@ var Folder = class {
2079
2546
  */
2080
2547
  function fold(context) {
2081
2548
  const folder = new Folder(context);
2549
+ folder.removeUnusedDeclarations();
2082
2550
  folder.walk(context.program);
2083
2551
  return folder.changed;
2084
2552
  }
@@ -2120,7 +2588,7 @@ const ACCESSOR_PAIRS = /* @__PURE__ */ new Set([
2120
2588
  * `useContext` throws when the value and the default are both `undefined`,
2121
2589
  * so a value that could be `undefined` keeps its provider.
2122
2590
  */
2123
- function providerOf(context, element) {
2591
+ function findProvider(context, element) {
2124
2592
  const binding = contextBinding(context, element.openingElement.name);
2125
2593
  if (!binding || element.openingElement.selfClosing) return;
2126
2594
  const { attributes } = element.openingElement;
@@ -2180,7 +2648,7 @@ function isDefined(context, node, depth) {
2180
2648
  case "Identifier": {
2181
2649
  const binding = context.scopes.references.get(expression);
2182
2650
  if (!binding || binding.mutated || depth > 2) return false;
2183
- if (binding.kind === "function" || binding.kind === "class" || isAccessor(context, binding)) return true;
2651
+ if (binding.kind === "function" || binding.kind === "class" || isAccessor$1(context, binding)) return true;
2184
2652
  const { declaration } = binding;
2185
2653
  return isConstantDeclaration(binding, context.options) && declaration.type === "VariableDeclarator" && declaration.id === binding.identifier && declaration.init !== null && isDefined(context, declaration.init, depth + 1);
2186
2654
  }
@@ -2218,7 +2686,7 @@ function isHandlerFunction(attribute) {
2218
2686
  * Whether a binding is a signal or store getter or setter, or a memo, which
2219
2687
  * run no code of the app when called.
2220
2688
  */
2221
- function isAccessor(context, binding) {
2689
+ function isAccessor$1(context, binding) {
2222
2690
  if (binding.mutated) return false;
2223
2691
  const { declaration } = binding;
2224
2692
  if (declaration.type !== "VariableDeclarator") return false;
@@ -2228,8 +2696,8 @@ function isAccessor(context, binding) {
2228
2696
  const callee = solidCallee(context, call);
2229
2697
  if (id === binding.identifier) return callee === "createMemo";
2230
2698
  if (id.type !== "ArrayPattern" || callee === void 0 || !ACCESSOR_PAIRS.has(callee)) return false;
2231
- const index = id.elements.findIndex((element) => element === binding.identifier);
2232
- return index === 0 || index === 1;
2699
+ for (const [index, element] of id.elements.entries()) if (element === binding.identifier) return index === 0 || index === 1;
2700
+ return false;
2233
2701
  }
2234
2702
  /**
2235
2703
  * Whether all code that can run under `root` is visible, so a provider
@@ -2306,7 +2774,7 @@ function isClosed(context, root, options) {
2306
2774
  */
2307
2775
  function runsOutsideCode(context, binding, root, options, depth) {
2308
2776
  const { identifier, declaration } = binding;
2309
- if (binding === options.props || identifier.start >= root.start && identifier.end <= root.end || isAccessor(context, binding) || solidExport(binding, context.options) !== void 0) return false;
2777
+ if (binding === options.props || identifier.start >= root.start && identifier.end <= root.end || isAccessor$1(context, binding) || solidExport(binding, context.options) !== void 0) return false;
2310
2778
  if (binding.kind === "param" || binding.kind === "function" || depth > 4) return true;
2311
2779
  if (declaration.type !== "VariableDeclarator" || !declaration.init) return false;
2312
2780
  const init = unwrap(declaration.init);
@@ -2343,11 +2811,12 @@ function isOwnView(context, node, props, depth) {
2343
2811
  if (call?.type !== "CallExpression") return false;
2344
2812
  const callee = solidCallee(context, call);
2345
2813
  if (callee !== "merge" && callee !== "omit") return false;
2346
- return call.arguments.every((argument) => {
2814
+ for (const argument of call.arguments) {
2347
2815
  if (argument.type === "SpreadElement") return false;
2348
2816
  const inner = unwrap(argument);
2349
- return inner.type === "ObjectExpression" || inner.type === "Literal" && typeof inner.value === "string" || isOwnView(context, inner, props, depth + 1);
2350
- });
2817
+ if (inner.type !== "ObjectExpression" && !(inner.type === "Literal" && typeof inner.value === "string") && !isOwnView(context, inner, props, depth + 1)) return false;
2818
+ }
2819
+ return true;
2351
2820
  }
2352
2821
  function isVisibleElement(context, element, options) {
2353
2822
  const { name } = element.openingElement;
@@ -2378,13 +2847,13 @@ function isAccessorValue(context, node, options, depth) {
2378
2847
  const expression = unwrap(node);
2379
2848
  if (depth > 4) return false;
2380
2849
  if (expression.type === "CallExpression") {
2381
- const value = contextValueOf(context, expression, options);
2850
+ const value = findContextValue(context, expression, options);
2382
2851
  return value !== void 0 && isAccessorValue(context, value, options, depth + 1);
2383
2852
  }
2384
2853
  if (expression.type !== "Identifier") return false;
2385
2854
  const binding = context.scopes.references.get(expression);
2386
2855
  if (!binding) return false;
2387
- if (isAccessor(context, binding)) return true;
2856
+ if (isAccessor$1(context, binding)) return true;
2388
2857
  const init = constantInit(context, binding);
2389
2858
  return init !== void 0 && isAccessorValue(context, init, options, depth + 1);
2390
2859
  }
@@ -2399,7 +2868,7 @@ function constantInit(context, binding) {
2399
2868
  /**
2400
2869
  * The value `useContext(Ctx)` returns, when the provider is known.
2401
2870
  */
2402
- function contextValueOf(context, call, options) {
2871
+ function findContextValue(context, call, options) {
2403
2872
  const argument = call.arguments.at(0);
2404
2873
  if (solidCallee(context, call) !== "useContext" || call.arguments.length !== 1 || argument === void 0 || argument.type === "SpreadElement") return;
2405
2874
  const target = contextBinding(context, unwrap(argument));
@@ -2412,10 +2881,14 @@ function contextValueOf(context, call, options) {
2412
2881
  */
2413
2882
  function isVisibleMethod(context, member, options) {
2414
2883
  if (member.computed || member.property.type !== "Identifier" || member.optional) return false;
2415
- const object = objectLiteralOf(context, member.object, options, 0);
2416
- if (!object || object.properties.some((property) => property.type !== "Property")) return false;
2884
+ const object = findObjectLiteral(context, member.object, options, 0);
2885
+ if (!object) return false;
2417
2886
  const { name } = member.property;
2418
- const matches = object.properties.filter((property) => property.type === "Property" && !property.computed && property.key.type === "Identifier" && property.key.name === name);
2887
+ const matches = [];
2888
+ for (const property of object.properties) {
2889
+ if (property.type !== "Property") return false;
2890
+ if (!property.computed && property.key.type === "Identifier" && property.key.name === name) matches.push(property);
2891
+ }
2419
2892
  const property = matches.at(0);
2420
2893
  if (matches.length !== 1 || property?.type !== "Property" || property.kind !== "init") return false;
2421
2894
  const value = unwrap(property.value);
@@ -2430,18 +2903,18 @@ function isVisibleMethod(context, member, options) {
2430
2903
  * The object literal an expression evaluates to, through bindings that
2431
2904
  * never change and reads of a context whose value is known.
2432
2905
  */
2433
- function objectLiteralOf(context, node, options, depth) {
2906
+ function findObjectLiteral(context, node, options, depth) {
2434
2907
  const expression = unwrap(node);
2435
2908
  if (depth > 4) return;
2436
2909
  if (expression.type === "ObjectExpression") return expression;
2437
2910
  if (expression.type === "CallExpression") {
2438
- const value = contextValueOf(context, expression, options);
2439
- return value ? objectLiteralOf(context, value, options, depth + 1) : void 0;
2911
+ const value = findContextValue(context, expression, options);
2912
+ return value ? findObjectLiteral(context, value, options, depth + 1) : void 0;
2440
2913
  }
2441
2914
  if (expression.type !== "Identifier") return;
2442
2915
  const binding = context.scopes.references.get(expression);
2443
2916
  const init = binding ? constantInit(context, binding) : void 0;
2444
- return init ? objectLiteralOf(context, init, options, depth + 1) : void 0;
2917
+ return init ? findObjectLiteral(context, init, options, depth + 1) : void 0;
2445
2918
  }
2446
2919
  /**
2447
2920
  * The `useContext(Ctx)` calls under `root` that run under its owner, so
@@ -2486,7 +2959,7 @@ function findProviders(context) {
2486
2959
  const providers = [];
2487
2960
  const visit = (node) => {
2488
2961
  if (node.type === "JSXElement") {
2489
- const provider = providerOf(context, node);
2962
+ const provider = findProvider(context, node);
2490
2963
  if (provider) providers.push(provider);
2491
2964
  }
2492
2965
  forEachChild(node, visit);
@@ -2503,7 +2976,12 @@ var ProviderRemover = class {
2503
2976
  run() {
2504
2977
  for (const provider of findProviders(this.context)) {
2505
2978
  const { element } = provider;
2506
- if (this.removed.some((other) => element.start < other.end && other.start < element.end)) continue;
2979
+ let overlaps = false;
2980
+ for (const other of this.removed) if (element.start < other.end && other.start < element.end) {
2981
+ overlaps = true;
2982
+ break;
2983
+ }
2984
+ if (overlaps) continue;
2507
2985
  if (hasNestedProvider(this.context, provider)) this.skip(provider, "provider-nested");
2508
2986
  else if (this.tryRemove(provider)) this.removed.push(element);
2509
2987
  }
@@ -2520,7 +2998,7 @@ var ProviderRemover = class {
2520
2998
  const visit = (node) => {
2521
2999
  if (node.type === "JSXElement") {
2522
3000
  const binding = contextBinding(this.context, node.openingElement.name);
2523
- if (binding && !providerOf(this.context, node)) {
3001
+ if (binding && !findProvider(this.context, node)) {
2524
3002
  const { attributes } = node.openingElement;
2525
3003
  const attribute = attributes.at(0);
2526
3004
  const onlyValue = attributes.length === 1 && attribute?.type === "JSXAttribute" && attribute.name.type === "JSXIdentifier" && attribute.name.name === "value";
@@ -2535,17 +3013,24 @@ var ProviderRemover = class {
2535
3013
  const { element } = provider;
2536
3014
  const children = element.children;
2537
3015
  let reason = "open-other";
2538
- if (!children.every((child) => isClosed(this.context, child, {
3016
+ const closure = {
2539
3017
  component: () => false,
2540
3018
  contextValue: (target) => target === provider.context ? provider.value : void 0,
2541
3019
  onOpen: (open) => {
2542
3020
  reason = open;
2543
3021
  }
2544
- }))) {
3022
+ };
3023
+ let closed = true;
3024
+ for (const child of children) if (!isClosed(this.context, child, closure)) {
3025
+ closed = false;
3026
+ break;
3027
+ }
3028
+ if (!closed) {
2545
3029
  this.skip(provider, reason);
2546
3030
  return false;
2547
3031
  }
2548
- const reads = children.flatMap((child) => contextReads(this.context, child, provider.context));
3032
+ const reads = [];
3033
+ for (const child of children) reads.push(...contextReads(this.context, child, provider.context));
2549
3034
  const texts = [];
2550
3035
  for (const read of reads) {
2551
3036
  const text = stableValueText(this.context, provider, read);
@@ -2581,35 +3066,57 @@ function removeProviders(context) {
2581
3066
  //#endregion
2582
3067
  //#region src/copy-size.ts
2583
3068
  /**
2584
- * Measures a component's copy at a call site: folds it as the passes after
2585
- * inlining would, then estimates its size with `SizeEstimator`.
3069
+ * The name of the function a copy is wrapped in to be folded and measured.
3070
+ * It is capitalized, so the inline pass can move statements into it.
3071
+ */
3072
+ const WRAPPER = "SoSize$$";
3073
+ /**
3074
+ * How many copies are being measured inside each other. Components that
3075
+ * call each other would otherwise measure each other without end.
2586
3076
  */
2587
- /** The name of the function a copy is wrapped in to be folded and measured. */
2588
- const WRAPPER = "__so_size__";
3077
+ let depth = 0;
3078
+ const MAX_DEPTH = 3;
2589
3079
  /**
2590
3080
  * The size of a component's copy at one call site, once its props have
2591
3081
  * folded. `header` declares the names the fold pass needs to know, like
2592
- * imports of Solid. `inTemplate` is whether the call site sits directly in
2593
- * an element.
3082
+ * imports of Solid. `called` holds the module's components the copy calls,
3083
+ * which inline into it when its props resolve their call sites.
3084
+ * `inTemplate` is whether the call site sits directly in an element.
3085
+ * `measured` receives the code that was measured.
2594
3086
  */
2595
- function copySize(filename, header, copy, inTemplate, options) {
2596
- let code = `${header}\nfunction ${WRAPPER}() {\n${copy.statements.join("\n")}\nreturn (${copy.root});\n}\n`;
2597
- for (let round = 0; round < 3; round += 1) {
2598
- const program = parse(filename, code);
2599
- const s = new MagicString(code);
2600
- if (!fold({
2601
- code,
2602
- filename,
2603
- s,
2604
- program,
2605
- parents: collectParents(program),
2606
- scopes: analyzeScopes(program),
2607
- options,
2608
- skips: void 0
2609
- })) break;
2610
- code = s.toString();
2611
- }
2612
- const wrapper = parse(filename, code).body.at(-1);
3087
+ function copySize(filename, header, copy, inTemplate, options, called, measured) {
3088
+ const calls = depth < MAX_DEPTH ? called : void 0;
3089
+ let code = `${header}\n${calls?.declarations ?? ""}\nfunction ${WRAPPER}() {\n${join(copy.statements, "\n").code}\nreturn (${getCode(copy.root)});\n}\n`;
3090
+ for (let round = 0; round < 4; round += 1) {
3091
+ let changed = false;
3092
+ for (const pass of calls ? [fold, calls.inline] : [fold]) {
3093
+ const program = parse$1(filename, code);
3094
+ const s = new Editor(code, false);
3095
+ depth += 1;
3096
+ let passChanged;
3097
+ try {
3098
+ passChanged = pass({
3099
+ code,
3100
+ filename,
3101
+ s,
3102
+ program,
3103
+ parents: collectParents(program),
3104
+ scopes: analyzeScopes(program),
3105
+ options,
3106
+ skips: void 0
3107
+ });
3108
+ } finally {
3109
+ depth -= 1;
3110
+ }
3111
+ if (passChanged) {
3112
+ code = s.toString();
3113
+ changed = true;
3114
+ }
3115
+ }
3116
+ if (!changed) break;
3117
+ }
3118
+ if (measured) measured.code = code;
3119
+ const wrapper = parse$1(filename, code).body.at(-1);
2613
3120
  if (wrapper?.type !== "FunctionDeclaration" || !wrapper.body) return Number.POSITIVE_INFINITY;
2614
3121
  const estimator = new SizeEstimator(code);
2615
3122
  let size = 0;
@@ -2624,77 +3131,6 @@ function copySize(filename, header, copy, inTemplate, options) {
2624
3131
  }
2625
3132
  //#endregion
2626
3133
  //#region src/inline.ts
2627
- /**
2628
- * The inline pass: replaces a component call with the component's body.
2629
- *
2630
- * `<Card title="Hi" />` with `function Card(props) { return <div>{props.title}</div>; }`
2631
- * becomes `<div>{"Hi"}</div>`. The JSX transform then sees one tree instead of
2632
- * two, so it emits one template, one clone, and fewer hydration markers.
2633
- *
2634
- * A component inlines when its shape keeps the result equivalent:
2635
- *
2636
- * - It is declared once at the top level of the module, with a capitalized
2637
- * name, as a function declaration or a `const` bound to a function.
2638
- * - It takes no parameter, or one identifier that is only read as `props.name`,
2639
- * or spread onto an element as `{...props}`.
2640
- * - Its body is statements followed by one final `return` of JSX, or an arrow
2641
- * function whose body is JSX.
2642
- * - It does not use `this`, `arguments`, `new.target`, or `super`.
2643
- *
2644
- * A call site inlines when it passes plain attributes: no spread and no
2645
- * namespaced attribute. A `ref` moves to the element the component forwards
2646
- * `props.ref` to. See `refValue`.
2647
- *
2648
- * # How props keep their meaning
2649
- *
2650
- * Solid passes a dynamic prop as a getter, so every read of `props.name`
2651
- * evaluates the attribute's expression again. Inlining replaces each read
2652
- * with the expression itself, which does the same.
2653
- *
2654
- * A static prop, such as an identifier or a function, is evaluated once when
2655
- * the component is created. Its expression is substituted directly when that
2656
- * gives the same value, such as a literal or a binding nothing reassigns, or
2657
- * when the prop is read exactly once. Otherwise its value is stored in a
2658
- * `const` before the component body runs.
2659
- *
2660
- * # Where a component body can go
2661
- *
2662
- * A component whose body is only JSX inlines anywhere JSX can go.
2663
- *
2664
- * Statements, and stored props, have to run where the component would have
2665
- * been created. Solid runs a component untracked, so the statements move into
2666
- * the function whose returned JSX holds the call, when that function also
2667
- * runs untracked:
2668
- *
2669
- * - a component;
2670
- * - the child callback of `<For>` or `<Repeat>`, which runs once per item
2671
- * under its own owner;
2672
- * - the child callback of `<Show>` or `<Match>` that takes the value, which
2673
- * runs once each time the condition turns true;
2674
- * - the callback given to `render`, which runs once under its root.
2675
- *
2676
- * The call has to be in that returned JSX with only intrinsic elements and
2677
- * fragments around it, so it is created exactly once each time that function
2678
- * runs.
2679
- *
2680
- * A context provider is a component, so statements do not move out of it,
2681
- * and `useContext` still runs under it. The exception is a provider whose
2682
- * subtree only runs visible code. Statements move out through it, and each
2683
- * `useContext` of its context in a copy becomes its value. See `provider.ts`.
2684
- *
2685
- * The props can also be read through `merge()` and `omit()` views declared
2686
- * in the component. Each call site knows which props it passes, so a read
2687
- * of a view resolves to a prop, a literal default, or `undefined`, and a
2688
- * spread of a view becomes the attributes it holds.
2689
- *
2690
- * # Accepted differences
2691
- *
2692
- * - A prop that is a function and is called as `props.name()` runs with
2693
- * `this` set to its own receiver instead of the props object.
2694
- * - Statements moved into the host run before the host's JSX is created,
2695
- * instead of while it is created. The order of `onSettled` and effect
2696
- * registration across siblings can change.
2697
- */
2698
3134
  function isWithin(node, container) {
2699
3135
  return node.start >= container.start && node.end <= container.end;
2700
3136
  }
@@ -2708,7 +3144,8 @@ function inBodyOrder(sites) {
2708
3144
  const pending = [...sites];
2709
3145
  const ordered = [];
2710
3146
  while (pending.length > 0) {
2711
- const ready = pending.filter((site) => !pending.some((other) => other !== site && (isWithin(other.element, site.component.fn) || isWithin(other.element, site.element))));
3147
+ const ready = [];
3148
+ for (const site of pending) if (!hasPendingDependency(pending, site)) ready.push(site);
2712
3149
  const next = ready.length > 0 ? ready : pending;
2713
3150
  for (const site of next) {
2714
3151
  ordered.push(site);
@@ -2722,6 +3159,12 @@ const UNDEFINED = {
2722
3159
  text: "void 0",
2723
3160
  primary: false
2724
3161
  };
3162
+ /** The function a copy is wrapped in when it is measured. See `copy-size.ts`. */
3163
+ const COPY_WRAPPER = "function SoSize$$(";
3164
+ /** Whether code has a JSX tag named `name`. */
3165
+ function hasTag(code, name) {
3166
+ return new RegExp(`<${name.replaceAll("$", String.raw`\$`)}[\\s/>]`).test(code);
3167
+ }
2725
3168
  function isCapitalized(name) {
2726
3169
  return /^[A-Z]/.test(name);
2727
3170
  }
@@ -2777,6 +3220,38 @@ function containsReturn(node) {
2777
3220
  return found;
2778
3221
  }
2779
3222
  /**
3223
+ * Collects the nodes an assignment target writes through: an identifier, or
3224
+ * the root of a member chain, like `cache` in `cache.items[0] = x`. A root
3225
+ * that is not a name, like a call, is collected as it is.
3226
+ */
3227
+ function collectWriteRoots(target, roots) {
3228
+ switch (target.type) {
3229
+ case "MemberExpression":
3230
+ collectWriteRoots(target.object, roots);
3231
+ break;
3232
+ case "ParenthesizedExpression":
3233
+ case "TSAsExpression":
3234
+ case "TSSatisfiesExpression":
3235
+ case "TSNonNullExpression":
3236
+ case "TSTypeAssertion":
3237
+ collectWriteRoots(target.expression, roots);
3238
+ break;
3239
+ case "ObjectPattern":
3240
+ for (const property of target.properties) collectWriteRoots(property.type === "RestElement" ? property.argument : property.value, roots);
3241
+ break;
3242
+ case "ArrayPattern":
3243
+ for (const element of target.elements) if (element) collectWriteRoots(element, roots);
3244
+ break;
3245
+ case "AssignmentPattern":
3246
+ collectWriteRoots(target.left, roots);
3247
+ break;
3248
+ case "RestElement":
3249
+ collectWriteRoots(target.argument, roots);
3250
+ break;
3251
+ default: roots.push(target);
3252
+ }
3253
+ }
3254
+ /**
2780
3255
  * Whether Solid would pass an attribute expression as a getter. The JSX
2781
3256
  * transform wraps any expression that reads a member or calls a function.
2782
3257
  */
@@ -2827,7 +3302,7 @@ function acceptsAnyExpression(context, node) {
2827
3302
  /**
2828
3303
  * The function a top-level binding declares, if it declares one.
2829
3304
  */
2830
- function functionOf(binding, options) {
3305
+ function findComponentFunction(binding, options) {
2831
3306
  const { declaration } = binding;
2832
3307
  if (binding.kind === "function" && declaration.type === "FunctionDeclaration") return declaration;
2833
3308
  if (isConstantDeclaration(binding, options) && declaration.type === "VariableDeclarator" && declaration.id === binding.identifier && declaration.init) {
@@ -2838,10 +3313,10 @@ function functionOf(binding, options) {
2838
3313
  /**
2839
3314
  * The attributes of a call site by name, or `undefined` when one cannot be inlined.
2840
3315
  */
2841
- function attributesOf(element) {
3316
+ function getAttributes(context, element) {
2842
3317
  const attributes = /* @__PURE__ */ new Map();
2843
3318
  for (const attribute of element.openingElement.attributes) {
2844
- if (attribute.type !== "JSXAttribute" || attribute.name.type !== "JSXIdentifier" || attribute.name.name === "ref" && !isForwardableRef(attribute) || attributes.has(attribute.name.name)) return;
3319
+ if (attribute.type !== "JSXAttribute" || attribute.name.type !== "JSXIdentifier" || attribute.name.name === "ref" && !isForwardableRef(context, attribute) || attributes.has(attribute.name.name)) return;
2845
3320
  attributes.set(attribute.name.name, attribute);
2846
3321
  }
2847
3322
  return attributes;
@@ -2853,7 +3328,7 @@ function attributesOf(element) {
2853
3328
  */
2854
3329
  function isDataDeclaration(statement) {
2855
3330
  const declaration = statement.type === "ExportNamedDeclaration" ? statement.declaration : statement;
2856
- return declaration?.type === "VariableDeclaration" && !declaration.declare && (declaration.kind === "const" || declaration.kind === "var") && declaration.declarations.every((declarator) => declarator.id.type === "Identifier" && declarator.init !== null && isDataLiteral(declarator.init));
3331
+ return declaration?.type === "VariableDeclaration" && !declaration.declare && (declaration.kind === "const" || declaration.kind === "var") && areDataDeclarators(declaration.declarations);
2857
3332
  }
2858
3333
  /** Whether an expression is a literal, or an array or object literal of them. */
2859
3334
  function isDataLiteral(node) {
@@ -2864,8 +3339,8 @@ function isDataLiteral(node) {
2864
3339
  case "ParenthesizedExpression":
2865
3340
  case "TSAsExpression":
2866
3341
  case "TSSatisfiesExpression": return isDataLiteral(node.expression);
2867
- case "ArrayExpression": return node.elements.every((element) => element !== null && element.type !== "SpreadElement" && isDataLiteral(element));
2868
- case "ObjectExpression": return node.properties.every((property) => property.type === "Property" && property.kind === "init" && !property.method && !property.computed && isDataLiteral(property.value));
3342
+ case "ArrayExpression": return areDataElements(node.elements);
3343
+ case "ObjectExpression": return areDataProperties(node.properties);
2869
3344
  default: return false;
2870
3345
  }
2871
3346
  }
@@ -2878,19 +3353,36 @@ function isMemberRead(read) {
2878
3353
  * assigned the element, so it has to stay the name itself. Anything else
2879
3354
  * would be evaluated when the element is made, outside the `untrack` the
2880
3355
  * component's `ref` runs it in.
3356
+ *
3357
+ * Inside an array, `void 0` and `untrack(() => target)` count too. Solid
3358
+ * skips an empty entry of a ref array, and evaluates the whole `ref`
3359
+ * untracked. They come from a component that forwards `props.ref` in an
3360
+ * array, once a call site that passes no `ref` is inlined.
2881
3361
  */
2882
- function isForwardableRef(attribute) {
3362
+ function isForwardableRef(context, attribute) {
2883
3363
  const { value } = attribute;
2884
3364
  if (value?.type !== "JSXExpressionContainer" || value.expression.type === "JSXEmptyExpression") return false;
2885
- const isTarget = (node) => {
3365
+ const isTarget = (node, inArray) => {
2886
3366
  const inner = unwrap(node);
2887
- if (inner.type === "ArrayExpression") return inner.elements.every((element) => element !== null && element.type !== "SpreadElement" && isTarget(element));
3367
+ if (inner.type === "ArrayExpression") {
3368
+ for (const element of inner.elements) if (element === null || element.type === "SpreadElement" || !isTarget(element, true)) return false;
3369
+ return true;
3370
+ }
3371
+ if (inArray && isVoidZero(inner)) return true;
3372
+ if (inArray && inner.type === "CallExpression" && solidCallee(context, inner) === "untrack") {
3373
+ const callback = inner.arguments.at(0);
3374
+ return inner.arguments.length === 1 && callback?.type === "ArrowFunctionExpression" && callback.expression && callback.params.length === 0 && callback.body.type !== "BlockStatement" && isTarget(callback.body, true);
3375
+ }
2888
3376
  return inner.type === "Identifier" || inner.type === "ArrowFunctionExpression" || inner.type === "FunctionExpression";
2889
3377
  };
2890
- return isTarget(value.expression);
3378
+ return isTarget(value.expression, false);
3379
+ }
3380
+ /** Whether an expression is `void 0`. */
3381
+ function isVoidZero(node) {
3382
+ return node.type === "UnaryExpression" && node.operator === "void" && node.argument.type === "Literal" && node.argument.value === 0;
2891
3383
  }
2892
3384
  /**
2893
- * Why `attributesOf` turns down a call site, for the report.
3385
+ * Why `getAttributes` turns down a call site, for the report.
2894
3386
  */
2895
3387
  function callSiteReason(element) {
2896
3388
  const names = /* @__PURE__ */ new Set();
@@ -2928,6 +3420,9 @@ var Inliner = class {
2928
3420
  this.hosts = /* @__PURE__ */ new Map();
2929
3421
  this.transparent = /* @__PURE__ */ new Map();
2930
3422
  this.reason = "";
3423
+ this.components = [];
3424
+ this.sites = [];
3425
+ this.blocked = /* @__PURE__ */ new Map();
2931
3426
  }
2932
3427
  /**
2933
3428
  * Whether a binding holds a component made by Solid's `lazy`, for the
@@ -2950,7 +3445,7 @@ var Inliner = class {
2950
3445
  visit(loader);
2951
3446
  return imports;
2952
3447
  }
2953
- scopeOf(fn) {
3448
+ getScope(fn) {
2954
3449
  return this.context.scopes.scopes.get(fn);
2955
3450
  }
2956
3451
  /**
@@ -2963,13 +3458,34 @@ var Inliner = class {
2963
3458
  const statement = this.context.parents.get(declaration);
2964
3459
  if (statement?.type === "VariableDeclaration" && statement.declarations.length === 1 && this.context.parents.get(statement)?.type === "Program") return statement;
2965
3460
  }
3461
+ /**
3462
+ * Whether statements assign, update, or delete through a binding declared
3463
+ * outside `scope`, or through a global. Writes inside nested functions
3464
+ * count too, since a function can run right away, like a memo's.
3465
+ */
3466
+ writesOutside(statements, scope) {
3467
+ const roots = [];
3468
+ const visit = (node) => {
3469
+ if (node.type === "AssignmentExpression") collectWriteRoots(node.left, roots);
3470
+ else if (node.type === "UpdateExpression") collectWriteRoots(node.argument, roots);
3471
+ else if (node.type === "UnaryExpression" && node.operator === "delete") collectWriteRoots(node.argument, roots);
3472
+ forEachChild(node, visit);
3473
+ };
3474
+ for (const statement of statements) visit(statement);
3475
+ for (const root of roots) {
3476
+ if (root.type !== "Identifier") return true;
3477
+ const target = this.context.scopes.references.get(root);
3478
+ if (!target || !isWithinScope(target.scope, scope)) return true;
3479
+ }
3480
+ return false;
3481
+ }
2966
3482
  analyzeComponent(binding) {
2967
3483
  if (!isCapitalized(binding.name)) return;
2968
3484
  if (binding.mutated) {
2969
3485
  this.reason = "component-mutated";
2970
3486
  return;
2971
3487
  }
2972
- const fn = functionOf(binding, this.context.options);
3488
+ const fn = findComponentFunction(binding, this.context.options);
2973
3489
  if (!fn?.body) {
2974
3490
  this.reason = this.isLazy(binding) ? "lazy" : "not-a-function";
2975
3491
  return;
@@ -2982,7 +3498,7 @@ var Inliner = class {
2982
3498
  this.reason = "component-params";
2983
3499
  return;
2984
3500
  }
2985
- const scope = this.scopeOf(fn);
3501
+ const scope = this.getScope(fn);
2986
3502
  if (!scope) {
2987
3503
  this.reason = "not-a-function";
2988
3504
  return;
@@ -3019,6 +3535,10 @@ var Inliner = class {
3019
3535
  this.reason = "component-this";
3020
3536
  return;
3021
3537
  }
3538
+ if (this.writesOutside(statements, scope)) {
3539
+ this.reason = "component-write";
3540
+ return;
3541
+ }
3022
3542
  const param = fn.params.at(0);
3023
3543
  let paramBinding;
3024
3544
  if (param) {
@@ -3047,7 +3567,9 @@ var Inliner = class {
3047
3567
  }
3048
3568
  props.push(read);
3049
3569
  }
3050
- statements = statements.filter((statement) => !views.declarations.includes(statement));
3570
+ const kept = [];
3571
+ for (const statement of statements) if (!views.declarations.includes(statement)) kept.push(statement);
3572
+ statements = kept;
3051
3573
  const locals = [];
3052
3574
  const seen = /* @__PURE__ */ new Set();
3053
3575
  for (const inner of this.context.scopes.scopes.values()) {
@@ -3124,9 +3646,9 @@ var Inliner = class {
3124
3646
  const init = unwrap(declarator.init);
3125
3647
  const callee = init.type === "CallExpression" ? solidCallee(this.context, init) : void 0;
3126
3648
  if (init.type !== "CallExpression" || callee !== "merge" && callee !== "omit") continue;
3127
- const view = this.viewOf(callee, init, param, views, args);
3649
+ const view = this.resolveView(callee, init, param, views, args);
3128
3650
  if (view === null) continue;
3129
- const binding = scope.bindings.get(declarator.id.name);
3651
+ const binding = ((fn.body && this.context.scopes.scopes.get(fn.body)) ?? scope).bindings.get(declarator.id.name);
3130
3652
  if (!view || !binding || binding.mutated) return;
3131
3653
  views.set(binding, view);
3132
3654
  declarations.push(statement);
@@ -3191,12 +3713,12 @@ var Inliner = class {
3191
3713
  * take the props or another view, and `undefined` when it does but its
3192
3714
  * other arguments are not literal.
3193
3715
  */
3194
- viewOf(callee, call, param, views, args) {
3195
- const sourcesOf = (argument) => {
3716
+ resolveView(callee, call, param, views, args) {
3717
+ const resolveSources = (argument) => {
3196
3718
  if (argument.type === "CallExpression") {
3197
3719
  const nested = solidCallee(this.context, argument);
3198
3720
  if (nested !== "merge" && nested !== "omit") return;
3199
- return this.viewOf(nested, argument, param, views, args)?.sources;
3721
+ return this.resolveView(nested, argument, param, views, args)?.sources;
3200
3722
  }
3201
3723
  if (argument.type !== "Identifier") return;
3202
3724
  const binding = this.context.scopes.references.get(argument);
@@ -3206,13 +3728,18 @@ var Inliner = class {
3206
3728
  }];
3207
3729
  return binding ? views.get(binding)?.sources : void 0;
3208
3730
  };
3209
- if (!call.arguments.some((argument) => argument.type !== "SpreadElement" && sourcesOf(unwrap(argument)) !== void 0)) return null;
3731
+ let involved = false;
3732
+ for (const argument of call.arguments) if (argument.type !== "SpreadElement" && resolveSources(unwrap(argument)) !== void 0) {
3733
+ involved = true;
3734
+ break;
3735
+ }
3736
+ if (!involved) return null;
3210
3737
  if (callee === "omit") {
3211
3738
  const first = call.arguments.at(0);
3212
3739
  const keys = call.arguments.slice(1);
3213
3740
  if (first === void 0 || first.type === "SpreadElement") return;
3214
3741
  const target = unwrap(first);
3215
- const base = sourcesOf(target);
3742
+ const base = resolveSources(target);
3216
3743
  const hidden = [];
3217
3744
  for (const key of keys) {
3218
3745
  if (key.type !== "Literal" || typeof key.value !== "string") return;
@@ -3220,16 +3747,18 @@ var Inliner = class {
3220
3747
  }
3221
3748
  if (!base) return;
3222
3749
  args.add(target);
3223
- return { sources: base.map((source) => ({
3750
+ const hiddenSources = [];
3751
+ for (const source of base) hiddenSources.push({
3224
3752
  defaults: source.defaults,
3225
3753
  hidden: /* @__PURE__ */ new Set([...source.hidden, ...hidden])
3226
- })) };
3754
+ });
3755
+ return { sources: hiddenSources };
3227
3756
  }
3228
3757
  const sources = [];
3229
3758
  for (const argument of call.arguments) {
3230
3759
  if (argument.type === "SpreadElement") return;
3231
3760
  const inner = unwrap(argument);
3232
- const existing = sourcesOf(inner);
3761
+ const existing = resolveSources(inner);
3233
3762
  if (existing) {
3234
3763
  args.add(inner);
3235
3764
  sources.push(...existing);
@@ -3246,7 +3775,7 @@ var Inliner = class {
3246
3775
  const value = evaluate(property.value, () => void 0);
3247
3776
  const text = value ? literalText(value.value) : void 0;
3248
3777
  if (text === void 0 || isReservedPropName(key)) return;
3249
- defaults.set(key, text);
3778
+ defaults.set(key, this.context.s.written(text, property.value.start));
3250
3779
  }
3251
3780
  sources.push({
3252
3781
  defaults,
@@ -3284,7 +3813,7 @@ var Inliner = class {
3284
3813
  if (parent?.type === "CallExpression") return parent.arguments.at(0) === node && this.solidCallee(parent.callee) === "render";
3285
3814
  const element = parent?.type === "JSXExpressionContainer" ? this.context.parents.get(parent) : void 0;
3286
3815
  if (element?.type !== "JSXElement") return false;
3287
- const significant = element.children.filter((child) => !isInsignificant(child));
3816
+ const significant = getSignificantChildren(element.children);
3288
3817
  if (significant.length !== 1 || significant.at(0) !== parent) return false;
3289
3818
  switch (this.solidCallee(element.openingElement.name)) {
3290
3819
  case "For":
@@ -3307,7 +3836,7 @@ var Inliner = class {
3307
3836
  * returned JSX of a component, with only intrinsic elements, fragments,
3308
3837
  * and closed providers between it and the call.
3309
3838
  */
3310
- hostOf(element) {
3839
+ findHost(element) {
3311
3840
  let node = element;
3312
3841
  for (;;) {
3313
3842
  const parent = this.context.parents.get(node);
@@ -3316,7 +3845,7 @@ var Inliner = class {
3316
3845
  const { name } = parent.openingElement;
3317
3846
  if (!(this.assumedHosts?.has(parent) === true || name.type === "JSXIdentifier" && (isIntrinsicTag(name.name) || this.transparent.has(parent)))) return;
3318
3847
  const child = node;
3319
- if (!parent.children.some((item) => item === child)) return;
3848
+ if (!hasChild(parent.children, child)) return;
3320
3849
  } else if (parent.type === "ReturnStatement") {
3321
3850
  const list = this.context.parents.get(parent);
3322
3851
  if (list?.type !== "BlockStatement" && list?.type !== "SwitchCase") return;
@@ -3345,8 +3874,8 @@ var Inliner = class {
3345
3874
  }
3346
3875
  childrenValue(element, reads, fresh, snapshots) {
3347
3876
  const { children } = element;
3348
- if (children.some((child) => child.type === "JSXSpreadChild")) return;
3349
- const significant = children.filter((child) => !isInsignificant(child));
3877
+ if (hasSpreadChild(children)) return;
3878
+ const significant = getSignificantChildren(children);
3350
3879
  const only = significant.at(0);
3351
3880
  if (only === void 0) return {
3352
3881
  kind: "children",
@@ -3356,14 +3885,14 @@ var Inliner = class {
3356
3885
  };
3357
3886
  let text;
3358
3887
  let primary = true;
3359
- if (significant.length > 1 || only.type === "JSXText") text = `<>${this.context.s.slice(element.openingElement.end, element.closingElement?.start ?? element.end)}</>`;
3888
+ if (significant.length > 1 || only.type === "JSXText") text = joinText`<>${this.context.s.slice(element.openingElement.end, element.closingElement?.start ?? element.end)}</>`;
3360
3889
  else if (only.type === "JSXExpressionContainer") {
3361
3890
  if (only.expression.type === "JSXEmptyExpression") return;
3362
3891
  const value = this.expressionValue(only.expression, "children", reads, fresh, snapshots);
3363
- if (value.kind !== "expression" || value.text !== textOf(this.context, only.expression)) return value;
3892
+ if (value.kind !== "expression" || getCode(value.text) !== getText(this.context, only.expression).code) return value;
3364
3893
  text = value.text;
3365
3894
  primary = value.primary;
3366
- } else text = textOf(this.context, only);
3895
+ } else text = getText(this.context, only);
3367
3896
  return {
3368
3897
  kind: "children",
3369
3898
  children,
@@ -3390,7 +3919,7 @@ var Inliner = class {
3390
3919
  }
3391
3920
  return {
3392
3921
  kind: "expression",
3393
- text: textOf(this.context, value.expression),
3922
+ text: getText(this.context, value.expression),
3394
3923
  primary: true
3395
3924
  };
3396
3925
  }
@@ -3411,13 +3940,13 @@ var Inliner = class {
3411
3940
  if (value.value.includes("&")) return;
3412
3941
  return {
3413
3942
  kind: "expression",
3414
- text: JSON.stringify(value.value),
3943
+ text: this.context.s.written(JSON.stringify(value.value), value.start),
3415
3944
  primary: true
3416
3945
  };
3417
3946
  case "JSXElement":
3418
3947
  case "JSXFragment": return {
3419
3948
  kind: "jsx",
3420
- text: textOf(this.context, value),
3949
+ text: getText(this.context, value),
3421
3950
  primary: true
3422
3951
  };
3423
3952
  }
@@ -3430,7 +3959,7 @@ var Inliner = class {
3430
3959
  * How an expression passed as a prop reads in a copy of the component.
3431
3960
  */
3432
3961
  expressionValue(expression, name, reads, fresh, snapshots) {
3433
- const text = textOf(this.context, expression);
3962
+ const text = getText(this.context, expression);
3434
3963
  const inner = unwrap(expression);
3435
3964
  if (inner.type === "JSXElement" || inner.type === "JSXFragment") return {
3436
3965
  kind: "jsx",
@@ -3450,7 +3979,7 @@ var Inliner = class {
3450
3979
  primary
3451
3980
  };
3452
3981
  const local = fresh(name);
3453
- snapshots.push(`const ${local} = ${text};`);
3982
+ snapshots.push(joinText`const ${local} = ${text};`);
3454
3983
  return {
3455
3984
  kind: "expression",
3456
3985
  text: local,
@@ -3492,12 +4021,12 @@ var Inliner = class {
3492
4021
  * when it cannot be inlined there. Nothing is written until `commit`.
3493
4022
  */
3494
4023
  prepare(component, element) {
3495
- const attributes = attributesOf(element);
4024
+ const attributes = getAttributes(this.context, element);
3496
4025
  if (!attributes) {
3497
4026
  this.reason = callSiteReason(element);
3498
4027
  return;
3499
4028
  }
3500
- const hasChildren = element.children.some((child) => !isInsignificant(child));
4029
+ const hasChildren = getSignificantChildren(element.children).length > 0;
3501
4030
  if (hasChildren && attributes.has("children")) {
3502
4031
  this.reason = "call-children";
3503
4032
  return;
@@ -3543,7 +4072,7 @@ var Inliner = class {
3543
4072
  return;
3544
4073
  }
3545
4074
  const hoisted = component.statements.length > 0 || snapshots.length > 0;
3546
- const host = hoisted ? this.hostOf(element) : void 0;
4075
+ const host = hoisted ? this.findHost(element) : void 0;
3547
4076
  if (hoisted && !host) {
3548
4077
  this.reason = "no-host";
3549
4078
  return;
@@ -3553,7 +4082,7 @@ var Inliner = class {
3553
4082
  this.reason = "context-value";
3554
4083
  return;
3555
4084
  }
3556
- const copy = new MagicString(this.context.code);
4085
+ const copy = this.context.s.fresh();
3557
4086
  this.renameLocals(copy, component, fresh);
3558
4087
  this.substituteProps(copy, views.propReads, values);
3559
4088
  this.substituteViews(copy, component, element, views, values);
@@ -3561,7 +4090,10 @@ var Inliner = class {
3561
4090
  const statements = [...snapshots];
3562
4091
  const first = component.statements.at(0);
3563
4092
  const last = component.statements.at(-1);
3564
- if (first && last) statements.push(copy.slice(first.start, last.end));
4093
+ if (first && last) {
4094
+ const text = copy.slice(first.start, last.end);
4095
+ statements.push(text.code.endsWith(";") ? text : joinText`${text};`);
4096
+ }
3565
4097
  return {
3566
4098
  element,
3567
4099
  host,
@@ -3569,19 +4101,22 @@ var Inliner = class {
3569
4101
  root: copy.slice(component.root.start, component.root.end)
3570
4102
  };
3571
4103
  }
4104
+ /** Queues statements for a host. Each `return` gets its own, since their scopes can differ. */
4105
+ addToHost(found, texts) {
4106
+ const key = found.host.kind === "return" ? found.host.statement : found.fn;
4107
+ const entry = this.hosts.get(key) ?? {
4108
+ host: found.host,
4109
+ texts: []
4110
+ };
4111
+ entry.texts.push(...texts);
4112
+ this.hosts.set(key, entry);
4113
+ }
3572
4114
  /**
3573
4115
  * Writes a prepared copy over its call site.
3574
4116
  */
3575
4117
  commit(site) {
3576
4118
  this.context.s.overwrite(site.element.start, site.element.end, site.root);
3577
- if (site.host) {
3578
- const entry = this.hosts.get(site.host.fn) ?? {
3579
- host: site.host.host,
3580
- texts: []
3581
- };
3582
- entry.texts.push(...site.statements);
3583
- this.hosts.set(site.host.fn, entry);
3584
- }
4119
+ if (site.host) this.addToHost(site.host, site.statements);
3585
4120
  }
3586
4121
  /**
3587
4122
  * The context reads in a component's copy at `element` that a closed
@@ -3620,7 +4155,8 @@ var Inliner = class {
3620
4155
  * stored in a `const` of the host first, so every read gets the same one.
3621
4156
  */
3622
4157
  findTransparentProviders(components, sites) {
3623
- const byBinding = new Map(components.map((component) => [component.binding, component]));
4158
+ const byBinding = /* @__PURE__ */ new Map();
4159
+ for (const component of components) byBinding.set(component.binding, component);
3624
4160
  const closedUnder = (provider) => {
3625
4161
  const closedComponents = /* @__PURE__ */ new Map();
3626
4162
  const options = {
@@ -3645,22 +4181,22 @@ var Inliner = class {
3645
4181
  const changed = [];
3646
4182
  for (const provider of findProviders(this.context)) {
3647
4183
  const { element } = provider;
3648
- if (!sites.some((site) => isWithin(site.element, element) && site.element !== element)) continue;
4184
+ if (!hasSiteInside(sites, element)) continue;
3649
4185
  const isClosedNode = closedUnder(provider);
3650
- if (!element.children.every((child) => isClosedNode(child))) continue;
4186
+ let closed = true;
4187
+ for (const child of element.children) if (!isClosedNode(child)) {
4188
+ closed = false;
4189
+ break;
4190
+ }
4191
+ if (!closed) continue;
3651
4192
  if (stableValueText(this.context, provider, element) !== void 0) {
3652
4193
  this.transparent.set(element, { provider });
3653
4194
  continue;
3654
4195
  }
3655
- const host = this.hostOf(element);
4196
+ const host = this.findHost(element);
3656
4197
  if (!host) continue;
3657
4198
  const name = this.freshName(`${provider.context.name.charAt(0).toLowerCase()}${provider.context.name.slice(1)}Value`);
3658
- const entry = this.hosts.get(host.fn) ?? {
3659
- host: host.host,
3660
- texts: []
3661
- };
3662
- entry.texts.push(`const ${name} = ${textOf(this.context, provider.value)};`);
3663
- this.hosts.set(host.fn, entry);
4199
+ this.addToHost(host, [joinText`const ${name} = ${getText(this.context, provider.value)};`]);
3664
4200
  this.context.s.overwrite(provider.value.start, provider.value.end, name);
3665
4201
  this.transparent.set(element, {
3666
4202
  provider,
@@ -3705,7 +4241,8 @@ var Inliner = class {
3705
4241
  const order = [];
3706
4242
  for (const source of spread.view.sources) {
3707
4243
  const keys = source.defaults ? [...source.defaults.keys()] : callKeys;
3708
- for (const key of keys.filter((name) => !source.hidden.has(name))) {
4244
+ for (const key of keys) {
4245
+ if (source.hidden.has(key)) continue;
3709
4246
  const index = order.indexOf(key);
3710
4247
  if (index !== -1) order.splice(index, 1);
3711
4248
  order.push(key);
@@ -3714,7 +4251,7 @@ var Inliner = class {
3714
4251
  let names = taken.get(spread.element);
3715
4252
  if (!names) {
3716
4253
  names = /* @__PURE__ */ new Set();
3717
- for (const attribute of spread.element.openingElement.attributes) if (attribute.type === "JSXAttribute") names.add(attribute.name.type === "JSXIdentifier" ? attribute.name.name : textOf(this.context, attribute.name));
4254
+ for (const attribute of spread.element.openingElement.attributes) if (attribute.type === "JSXAttribute") names.add(attribute.name.type === "JSXIdentifier" ? attribute.name.name : getText(this.context, attribute.name).code);
3718
4255
  taken.set(spread.element, names);
3719
4256
  }
3720
4257
  const keys = /* @__PURE__ */ new Map();
@@ -3740,8 +4277,8 @@ var Inliner = class {
3740
4277
  */
3741
4278
  substituteViews(copy, component, element, views, values) {
3742
4279
  for (const [member, text] of views.texts) {
3743
- const bare = text !== "void 0" || acceptsAnyExpression(this.context, member);
3744
- copy.overwrite(member.start, member.end, bare ? text : `(${text})`);
4280
+ const bare = getCode(text) !== "void 0" || acceptsAnyExpression(this.context, member);
4281
+ copy.overwrite(member.start, member.end, bare ? text : joinText`(${text})`);
3745
4282
  }
3746
4283
  for (const { spread, keys } of views.spreads) {
3747
4284
  const parts = [];
@@ -3749,16 +4286,16 @@ var Inliner = class {
3749
4286
  for (const [key, text] of keys) {
3750
4287
  const value = values.get(key);
3751
4288
  if (key === "children") children = this.spreadChildren(element, text, value);
3752
- else parts.push(`${key}={${text ?? value?.text ?? "void 0"}}`);
4289
+ else parts.push(joinText`${key}={${text ?? value?.text ?? "void 0"}}`);
3753
4290
  }
3754
4291
  const { attribute } = spread;
3755
4292
  if (parts.length === 0) copy.remove(attribute.start, attribute.end);
3756
- else copy.overwrite(attribute.start, attribute.end, parts.join(" "));
4293
+ else copy.overwrite(attribute.start, attribute.end, join(parts, " "));
3757
4294
  if (children !== void 0) {
3758
4295
  const opening = spread.element.openingElement;
3759
- const tag = textOf(this.context, opening.name);
4296
+ const tag = copy.slice(opening.name.start, opening.name.end);
3760
4297
  const close = this.context.code.lastIndexOf("/>", opening.end);
3761
- copy.overwrite(close, opening.end, `>${children}</${tag}>`);
4298
+ copy.overwrite(close, opening.end, joinText`>${children}</${tag}>`);
3762
4299
  }
3763
4300
  }
3764
4301
  for (const declaration of component.viewDeclarations) copy.remove(declaration.start, declaration.end);
@@ -3768,10 +4305,10 @@ var Inliner = class {
3768
4305
  * children, or the value of a single expression or default.
3769
4306
  */
3770
4307
  spreadChildren(element, text, value) {
3771
- if (text !== void 0) return text === "void 0" ? void 0 : `{${text}}`;
4308
+ if (text !== void 0) return getCode(text) === "void 0" ? void 0 : joinText`{${text}}`;
3772
4309
  if (!value) return;
3773
4310
  if (value.kind === "children" && element.closingElement) return this.context.s.slice(element.openingElement.end, element.closingElement.start);
3774
- return `{${value.text}}`;
4311
+ return joinText`{${value.text}}`;
3775
4312
  }
3776
4313
  renameLocals(copy, component, fresh) {
3777
4314
  for (const local of component.locals) {
@@ -3801,22 +4338,16 @@ var Inliner = class {
3801
4338
  continue;
3802
4339
  }
3803
4340
  const bare = value.primary || acceptsAnyExpression(this.context, read.member);
3804
- copy.overwrite(read.member.start, read.member.end, bare ? value.text : `(${value.text})`);
4341
+ copy.overwrite(read.member.start, read.member.end, bare ? value.text : joinText`(${value.text})`);
4342
+ }
4343
+ for (const [parent, pieces] of spliced) {
4344
+ const children = [];
4345
+ for (const child of parent.children) children.push(pieces.get(child) ?? keptPiece(child));
4346
+ writePieces(copy, children);
3805
4347
  }
3806
- for (const [parent, pieces] of spliced) writePieces(copy, parent.children.map((child) => pieces.get(child) ?? keptPiece(child)));
3807
4348
  }
3808
4349
  splicedPiece(container, value) {
3809
- if (value.kind === "children") {
3810
- const first = value.children.at(0);
3811
- const last = value.children.at(-1);
3812
- if (!first || !last) return replacedPiece(container, "");
3813
- return {
3814
- node: container,
3815
- text: this.context.s.slice(first.start, last.end),
3816
- startText: first.type === "JSXText" ? first : void 0,
3817
- endText: last.type === "JSXText" ? last : void 0
3818
- };
3819
- }
4350
+ if (value.kind === "children") return splicePiece(this.context.s, container, value.children);
3820
4351
  return replacedPiece(container, value.text);
3821
4352
  }
3822
4353
  /**
@@ -3832,21 +4363,40 @@ var Inliner = class {
3832
4363
  byComponent.set(site.component, elements);
3833
4364
  }
3834
4365
  const result = /* @__PURE__ */ new Set();
3835
- if (this.context.options.alwaysInline) {
3836
- for (const component of byComponent.keys()) result.add(component);
3837
- return result;
4366
+ const { alwaysInline, alwaysInlineComponents } = this.context.options;
4367
+ for (const component of byComponent.keys()) if (alwaysInline || alwaysInlineComponents.has(component.binding.name)) {
4368
+ result.add(component);
4369
+ byComponent.delete(component);
3838
4370
  }
4371
+ if (byComponent.size === 0) return result;
3839
4372
  this.scratchNames = new Set(this.context.scopes.names);
3840
4373
  try {
3841
4374
  const copiesOf = /* @__PURE__ */ new Map();
3842
- for (const [component, elements] of byComponent) copiesOf.set(component, new Map(elements.map((element) => [element, this.prepare(component, element)])));
4375
+ for (const [component, elements] of byComponent) {
4376
+ const prepared = /* @__PURE__ */ new Map();
4377
+ for (const element of elements) prepared.set(element, this.prepare(component, element));
4378
+ copiesOf.set(component, prepared);
4379
+ }
4380
+ this.sites = sites;
4381
+ this.otherUses = otherUses;
4382
+ this.blocked = /* @__PURE__ */ new Map();
4383
+ for (const [inner, byElement] of copiesOf) for (const [element, copy] of byElement) {
4384
+ const outer = copy ? void 0 : findOuterComponent(this.components, inner, element);
4385
+ if (outer) {
4386
+ const list = this.blocked.get(outer) ?? [];
4387
+ list.push(inner);
4388
+ this.blocked.set(outer, list);
4389
+ }
4390
+ }
3843
4391
  for (const [component, byElement] of copiesOf) {
3844
- const copies = [...byElement.values()].filter((copy) => copy !== void 0);
4392
+ const copies = collectPrepared(byElement.values());
3845
4393
  if (copies.length === 0) continue;
3846
4394
  if (this.inliningGain(component, copies, this.removedShare(component, byElement, otherUses)) + this.enabledGain(component, copies, copiesOf, otherUses) >= 0) result.add(component);
3847
4395
  }
3848
4396
  } finally {
3849
4397
  this.scratchNames = void 0;
4398
+ this.otherUses = void 0;
4399
+ this.blocked = /* @__PURE__ */ new Map();
3850
4400
  }
3851
4401
  return result;
3852
4402
  }
@@ -3857,7 +4407,7 @@ var Inliner = class {
3857
4407
  * keeps it.
3858
4408
  */
3859
4409
  removedShare(component, copies, otherUses) {
3860
- if (component.declaration === void 0 || otherUses.get(component) !== 0 || [...copies.values()].some((copy) => copy === void 0)) return 0;
4410
+ if (component.declaration === void 0 || otherUses.get(component) !== 0 || hasMissingCopy(copies.values())) return 0;
3861
4411
  const users = this.context.options.sharedComponents.get(component.binding.name) ?? 1;
3862
4412
  return users > 0 ? 1 / users : 0;
3863
4413
  }
@@ -3867,7 +4417,8 @@ var Inliner = class {
3867
4417
  * element around its call to hoist them to.
3868
4418
  */
3869
4419
  enabledGain(component, copies, copiesOf, otherUses) {
3870
- const elements = copies.map((copy) => copy.element);
4420
+ const elements = [];
4421
+ for (const copy of copies) elements.push(copy.element);
3871
4422
  this.assumedHosts = new Set(elements);
3872
4423
  let gain = 0;
3873
4424
  try {
@@ -3875,14 +4426,14 @@ var Inliner = class {
3875
4426
  if (other === component) continue;
3876
4427
  const enabled = new Map(byElement);
3877
4428
  let changed = false;
3878
- for (const [element, copy] of byElement) if (!copy && elements.some((outer) => isWithin(element, outer))) {
4429
+ for (const [element, copy] of byElement) if (!copy && isWithinAny(element, elements)) {
3879
4430
  const next = this.prepare(other, element);
3880
4431
  enabled.set(element, next);
3881
4432
  changed ||= next !== void 0;
3882
4433
  }
3883
4434
  if (!changed) continue;
3884
- const now = [...byElement.values()].filter((copy) => copy !== void 0);
3885
- const then = [...enabled.values()].filter((copy) => copy !== void 0);
4435
+ const now = collectPrepared(byElement.values());
4436
+ const then = collectPrepared(enabled.values());
3886
4437
  const before = now.length > 0 ? Math.max(0, this.inliningGain(other, now, 0)) : 0;
3887
4438
  const after = this.inliningGain(other, then, this.removedShare(other, enabled, otherUses));
3888
4439
  gain += Math.max(0, after - before);
@@ -3901,14 +4452,54 @@ var Inliner = class {
3901
4452
  const estimator = this.estimator();
3902
4453
  let calls = share > 0 && component.declaration ? share * estimator.node(component.declaration) : 0;
3903
4454
  let inlined = 0;
4455
+ const blocked = this.blockedWithin(component);
4456
+ const kept = /* @__PURE__ */ new Set();
3904
4457
  for (const copy of copies) {
3905
4458
  const inTemplate = this.sitsInTemplate(copy.element);
3906
4459
  calls += estimator.jsx(copy.element, inTemplate);
3907
- inlined += copySize(this.context.filename, this.sizeHeader(), copy, inTemplate, this.context.options);
4460
+ const measured = { code: "" };
4461
+ inlined += copySize(this.context.filename, this.sizeHeader(), copy, inTemplate, this.context.options, blocked.length > 0 ? {
4462
+ declarations: this.createDeclarations(blocked),
4463
+ inline
4464
+ } : void 0, measured);
4465
+ const body = measured.code.slice(measured.code.lastIndexOf(COPY_WRAPPER));
4466
+ for (const inner of blocked) if (hasTag(body, inner.binding.name)) kept.add(inner);
4467
+ }
4468
+ if (share > 0) {
4469
+ for (const inner of blocked) if (!kept.has(inner) && inner.declaration && this.onlyUsedWithin(inner, component)) calls += share * estimator.node(inner.declaration);
3908
4470
  }
3909
4471
  return calls - inlined;
3910
4472
  }
3911
4473
  /**
4474
+ * The components whose calls in a component's body cannot be inlined
4475
+ * there, but may be in a copy, once the call site resolves the props
4476
+ * they are given. Those they call in turn count too.
4477
+ */
4478
+ blockedWithin(component) {
4479
+ const found = [];
4480
+ const pending = [component];
4481
+ for (let outer = pending.pop(); outer; outer = pending.pop()) for (const inner of this.blocked.get(outer) ?? []) if (inner !== component && !found.includes(inner)) {
4482
+ found.push(inner);
4483
+ pending.push(inner);
4484
+ }
4485
+ return found;
4486
+ }
4487
+ /** The declarations of components, for a copy measured on its own. */
4488
+ createDeclarations(components) {
4489
+ const texts = [];
4490
+ for (const component of components) {
4491
+ const statement = this.topLevelStatement(component.binding.declaration);
4492
+ if (statement) texts.push(getText(this.context, statement).code);
4493
+ }
4494
+ return texts.join("\n");
4495
+ }
4496
+ /** Whether every call of `inner` is in `outer`, and nothing else uses it. */
4497
+ onlyUsedWithin(inner, outer) {
4498
+ if (this.otherUses?.get(inner) !== 0) return false;
4499
+ for (const site of this.sites) if (site.component === inner && !isWithin(site.element, outer.fn)) return false;
4500
+ return true;
4501
+ }
4502
+ /**
3912
4503
  * Whether an element sits directly in an intrinsic element, whose
3913
4504
  * template its copy joins. A provider this pass makes transparent is
3914
4505
  * removed once its consumers are inlined, so the element above it counts.
@@ -3923,45 +4514,182 @@ var Inliner = class {
3923
4514
  this.sizeEstimator ??= new SizeEstimator(this.context.code);
3924
4515
  return this.sizeEstimator;
3925
4516
  }
4517
+ /** The top-level statement a node is part of, without an `export`. */
4518
+ topLevelStatement(node) {
4519
+ let current = node;
4520
+ for (let parent = this.context.parents.get(current); parent;) {
4521
+ if (parent.type === "Program") return current.type === "ExportNamedDeclaration" || current.type === "ExportDefaultDeclaration" ? current.declaration ?? void 0 : current;
4522
+ current = parent;
4523
+ parent = this.context.parents.get(current);
4524
+ }
4525
+ }
3926
4526
  /**
3927
4527
  * What a copy measured on its own needs to know: the module's imports,
3928
4528
  * and the names that alias Solid's exports.
3929
4529
  */
3930
4530
  sizeHeader() {
3931
4531
  if (this.header === void 0) {
3932
- const imports = this.context.program.body.filter((statement) => statement.type === "ImportDeclaration" || isDataDeclaration(statement)).map((statement) => this.context.code.slice(statement.start, statement.end));
4532
+ const imports = [];
4533
+ for (const statement of this.context.program.body) if (statement.type === "ImportDeclaration" || isDataDeclaration(statement)) imports.push(this.context.code.slice(statement.start, statement.end));
3933
4534
  const aliases = [...this.context.options.builtInAliases.keys()];
3934
4535
  if (aliases.length > 0) imports.push(`var ${aliases.join(", ")};`);
3935
4536
  this.header = imports.join("\n");
3936
4537
  }
3937
4538
  return this.header;
3938
4539
  }
3939
- run() {
3940
- const components = [];
3941
- const rejected = /* @__PURE__ */ new Map();
3942
- for (const binding of this.context.scopes.root.bindings.values()) {
3943
- this.reason = "not-a-function";
3944
- const component = this.analyzeComponent(binding);
3945
- if (component) components.push(component);
3946
- else rejected.set(binding, this.reason);
3947
- }
3948
- const siteReasons = /* @__PURE__ */ new Map();
3949
- if (components.length === 0) {
3950
- this.report(rejected, siteReasons);
4540
+ /**
4541
+ * The component a top-level alias like `const Button = ButtonRoot` names,
4542
+ * or `undefined` when the binding is not one.
4543
+ */
4544
+ aliasTarget(binding) {
4545
+ const { declaration } = binding;
4546
+ if (!isCapitalized(binding.name) || !isConstantDeclaration(binding, this.context.options) || declaration.type !== "VariableDeclarator" || declaration.id !== binding.identifier || !declaration.init) return;
4547
+ const init = unwrap(declaration.init);
4548
+ if (init.type !== "Identifier") return;
4549
+ const target = this.context.scopes.references.get(init);
4550
+ return target && target !== binding && target.scope.parent === void 0 && !target.mutated && isCapitalized(target.name) ? target : void 0;
4551
+ }
4552
+ /**
4553
+ * The parts of a compound component like Kobalte's
4554
+ * `const Dialog = Object.assign(DialogRoot, { Trigger: DialogTrigger })`,
4555
+ * or `undefined` when the binding is not one. `<Dialog>` is `<DialogRoot>`,
4556
+ * since `Object.assign` returns its first argument, and `<Dialog.Trigger>`
4557
+ * is `<DialogTrigger>` while nothing writes to a member of either.
4558
+ */
4559
+ compoundTarget(binding) {
4560
+ const { declaration } = binding;
4561
+ if (!isCapitalized(binding.name) || !isConstantDeclaration(binding, this.context.options) || declaration.type !== "VariableDeclarator" || declaration.id !== binding.identifier || !declaration.init) return;
4562
+ const init = unwrap(declaration.init);
4563
+ if (init.type !== "CallExpression" || init.optional || init.arguments.length !== 2 || !this.isObjectAssign(init.callee)) return;
4564
+ const [first, second] = init.arguments;
4565
+ if (first.type !== "Identifier" || second.type !== "ObjectExpression") return;
4566
+ const root = this.topLevelComponent(first);
4567
+ if (!root || root === binding || this.hasMemberWrite(binding) || this.hasMemberWrite(root)) return;
4568
+ const parts = /* @__PURE__ */ new Map();
4569
+ for (const property of second.properties) {
4570
+ if (property.type !== "Property" || property.kind !== "init" || property.computed || property.method || property.value.type !== "Identifier") return;
4571
+ const key = propertyKeyName(property.key);
4572
+ if (key === void 0) return;
4573
+ const part = this.topLevelComponent(property.value);
4574
+ if (part) parts.set(key, part);
4575
+ }
4576
+ return {
4577
+ root,
4578
+ parts
4579
+ };
4580
+ }
4581
+ /** Whether `callee` is the global `Object.assign`. */
4582
+ isObjectAssign(callee) {
4583
+ return callee.type === "MemberExpression" && !callee.computed && !callee.optional && callee.object.type === "Identifier" && callee.object.name === "Object" && !this.context.scopes.references.get(callee.object) && callee.property.type === "Identifier" && callee.property.name === "assign";
4584
+ }
4585
+ /** The top-level binding with a capitalized name that `reference` reads, when nothing reassigns it. */
4586
+ topLevelComponent(reference) {
4587
+ const target = this.context.scopes.references.get(reference);
4588
+ return target && target.scope.parent === void 0 && !target.mutated && isCapitalized(target.name) ? target : void 0;
4589
+ }
4590
+ /** Whether anything assigns to, updates, or deletes a member of the binding. */
4591
+ hasMemberWrite(binding) {
4592
+ for (const reference of binding.references) {
4593
+ const member = this.context.parents.get(reference);
4594
+ if (member?.type !== "MemberExpression" || member.object !== reference) continue;
4595
+ const use = this.context.parents.get(member);
4596
+ if (use?.type === "AssignmentExpression" && use.left === member || use?.type === "UpdateExpression" || use?.type === "UnaryExpression" && use.operator === "delete") return true;
4597
+ }
4598
+ return false;
4599
+ }
4600
+ /** Whether the code reads a member of the binding, like `DialogRoot.Trigger`. */
4601
+ hasMemberRead(binding) {
4602
+ for (const reference of binding.references) {
4603
+ const member = this.context.parents.get(reference);
4604
+ if ((member?.type === "MemberExpression" || member?.type === "JSXMemberExpression") && member.object === reference) return true;
4605
+ }
4606
+ return false;
4607
+ }
4608
+ /**
4609
+ * The statement of an alias nothing uses that `reference` is the value
4610
+ * of, like `const Separator = SeparatorRoot` once its tags are renamed.
4611
+ * It does not keep the component, and goes away with it. A compound
4612
+ * component counts too, when its tags are renamed and nothing reads the
4613
+ * members `Object.assign` gave its root.
4614
+ */
4615
+ unusedAlias(reference) {
4616
+ let declarator = this.context.parents.get(reference);
4617
+ if (declarator?.type === "Property") declarator = this.context.parents.get(declarator);
4618
+ if (declarator?.type === "ObjectExpression" || declarator?.type === "CallExpression") {
4619
+ const call = declarator.type === "CallExpression" ? declarator : this.context.parents.get(declarator);
4620
+ declarator = call ? this.context.parents.get(call) : void 0;
4621
+ }
4622
+ if (declarator?.type !== "VariableDeclarator" || declarator.id.type !== "Identifier") return;
4623
+ const alias = this.context.scopes.root.bindings.get(declarator.id.name);
4624
+ if (alias?.declaration !== declarator || alias.references.length > 0) return;
4625
+ const compound = this.compoundTarget(alias);
4626
+ if (this.aliasTarget(alias) === void 0 && (!compound || this.hasMemberRead(compound.root))) return;
4627
+ const statement = this.context.parents.get(declarator);
4628
+ return statement?.type === "VariableDeclaration" && statement.declarations.length === 1 && this.context.parents.get(statement)?.type === "Program" ? statement : void 0;
4629
+ }
4630
+ /**
4631
+ * Renames each tag of an alias to the component it names, where that name
4632
+ * means the same. Libraries often export a component under a second name,
4633
+ * like `const Separator = SeparatorRoot`. The next pass inlines the calls.
4634
+ */
4635
+ renameAliasTags() {
4636
+ let renamed = false;
4637
+ for (const binding of this.context.scopes.root.bindings.values()) {
4638
+ const compound = this.compoundTarget(binding);
4639
+ const target = this.aliasTarget(binding) ?? compound?.root;
4640
+ if (!target) continue;
4641
+ for (const reference of binding.references) {
4642
+ const parent = this.context.parents.get(reference);
4643
+ let tag = reference;
4644
+ let renamedTo = target;
4645
+ if (parent?.type === "JSXMemberExpression" && parent.object === reference) {
4646
+ const part = compound?.parts.get(parent.property.name);
4647
+ if (!part) continue;
4648
+ tag = parent;
4649
+ renamedTo = part;
4650
+ }
4651
+ const element = this.context.parents.get(tag);
4652
+ if (element?.type !== "JSXOpeningElement" && element?.type !== "JSXClosingElement" || element.name !== tag) continue;
4653
+ if (lookup(scopeAt(this.context.scopes, this.context.parents, reference), renamedTo.name) !== renamedTo) continue;
4654
+ this.context.s.overwrite(tag.start, tag.end, renamedTo.name);
4655
+ renamed = true;
4656
+ }
4657
+ }
4658
+ return renamed;
4659
+ }
4660
+ run() {
4661
+ if (this.renameAliasTags()) {
4662
+ this.changed = true;
4663
+ return;
4664
+ }
4665
+ const { components } = this;
4666
+ const rejected = /* @__PURE__ */ new Map();
4667
+ for (const binding of this.context.scopes.root.bindings.values()) {
4668
+ this.reason = "not-a-function";
4669
+ const component = this.analyzeComponent(binding);
4670
+ if (component) components.push(component);
4671
+ else rejected.set(binding, this.reason);
4672
+ }
4673
+ const siteReasons = /* @__PURE__ */ new Map();
4674
+ if (components.length === 0) {
4675
+ this.report(rejected, siteReasons);
3951
4676
  return;
3952
4677
  }
3953
4678
  const sites = [];
3954
4679
  const otherUses = /* @__PURE__ */ new Map();
4680
+ const aliases = /* @__PURE__ */ new Map();
3955
4681
  for (const component of components) {
3956
4682
  let uses = 0;
3957
4683
  for (const reference of component.binding.references) {
3958
4684
  const parent = this.context.parents.get(reference);
3959
4685
  if (parent?.type === "JSXClosingElement") continue;
3960
4686
  const element = parent ? this.context.parents.get(parent) : void 0;
4687
+ const alias = this.unusedAlias(reference);
3961
4688
  if (parent?.type === "JSXOpeningElement" && element?.type === "JSXElement") sites.push({
3962
4689
  component,
3963
4690
  element
3964
4691
  });
4692
+ else if (alias) aliases.set(component, [...aliases.get(component) ?? [], alias]);
3965
4693
  else uses += 1;
3966
4694
  }
3967
4695
  otherUses.set(component, uses);
@@ -3992,8 +4720,11 @@ var Inliner = class {
3992
4720
  this.report(rejected, siteReasons);
3993
4721
  const copied = [...inlined.keys()];
3994
4722
  for (const [component, elements] of inlined) {
3995
- const insideCopy = elements.some((element) => copied.some((other) => other !== component && element.start >= other.fn.start && element.end <= other.fn.end));
3996
- if (component.declaration && otherUses.get(component) === 0 && !insideCopy) this.context.s.remove(component.declaration.start, component.declaration.end);
4723
+ const insideCopy = isInsideOtherCopy(component, elements, copied);
4724
+ if (component.declaration && otherUses.get(component) === 0 && !insideCopy) {
4725
+ this.context.s.remove(component.declaration.start, component.declaration.end);
4726
+ for (const alias of aliases.get(component) ?? []) this.context.s.remove(alias.start, alias.end);
4727
+ }
3997
4728
  }
3998
4729
  }
3999
4730
  /**
@@ -4030,7 +4761,7 @@ var Inliner = class {
4030
4761
  const tag = element.openingElement.name;
4031
4762
  if (tag.type === "JSXMemberExpression") return {
4032
4763
  reason: "member-tag",
4033
- name: textOf(this.context, tag)
4764
+ name: getText(this.context, tag).code
4034
4765
  };
4035
4766
  if (tag.type !== "JSXIdentifier" || !isCapitalized(tag.name)) return;
4036
4767
  const { name } = tag;
@@ -4066,9 +4797,11 @@ var Inliner = class {
4066
4797
  writeHosts() {
4067
4798
  for (const { host, texts } of this.hosts.values()) if (host.kind === "return") {
4068
4799
  const indent = this.indentationAt(host.statement.start);
4069
- this.context.s.prependRight(host.statement.start, texts.map((text) => `${text}\n${indent}`).join(""));
4800
+ const written = [];
4801
+ for (const text of texts) written.push(text, `\n${indent}`);
4802
+ this.context.s.prependRight(host.statement.start, join(written));
4070
4803
  } else {
4071
- this.context.s.prependRight(host.body.start, `{ ${texts.join(" ")} return `);
4804
+ this.context.s.prependRight(host.body.start, joinText`{ ${join(texts, " ")} return `);
4072
4805
  this.context.s.appendLeft(host.body.end, "; }");
4073
4806
  }
4074
4807
  }
@@ -4081,6 +4814,65 @@ function inline(context) {
4081
4814
  inliner.run();
4082
4815
  return inliner.changed;
4083
4816
  }
4817
+ /** Whether another pending site must be done before this one. */
4818
+ function hasPendingDependency(pending, site) {
4819
+ for (const other of pending) if (other !== site && (isWithin(other.element, site.component.fn) || isWithin(other.element, site.element))) return true;
4820
+ return false;
4821
+ }
4822
+ function areDataDeclarators(declarators) {
4823
+ for (const declarator of declarators) if (declarator.id.type !== "Identifier" || declarator.init === null || !isDataLiteral(declarator.init)) return false;
4824
+ return true;
4825
+ }
4826
+ function areDataElements(elements) {
4827
+ for (const element of elements) if (element === null || element.type === "SpreadElement" || !isDataLiteral(element)) return false;
4828
+ return true;
4829
+ }
4830
+ function areDataProperties(properties) {
4831
+ for (const property of properties) if (property.type !== "Property" || property.kind !== "init" || property.method || property.computed || !isDataLiteral(property.value)) return false;
4832
+ return true;
4833
+ }
4834
+ function getSignificantChildren(children) {
4835
+ const significant = [];
4836
+ for (const child of children) if (!isInsignificant(child)) significant.push(child);
4837
+ return significant;
4838
+ }
4839
+ function hasSpreadChild(children) {
4840
+ for (const child of children) if (child.type === "JSXSpreadChild") return true;
4841
+ return false;
4842
+ }
4843
+ function hasSiteInside(sites, element) {
4844
+ for (const site of sites) if (isWithin(site.element, element) && site.element !== element) return true;
4845
+ return false;
4846
+ }
4847
+ function findOuterComponent(components, inner, element) {
4848
+ for (const item of components) if (item !== inner && isWithin(element, item.fn)) return item;
4849
+ }
4850
+ function collectPrepared(copies) {
4851
+ const prepared = [];
4852
+ for (const copy of copies) if (copy !== void 0) prepared.push(copy);
4853
+ return prepared;
4854
+ }
4855
+ function hasMissingCopy(copies) {
4856
+ for (const copy of copies) if (copy === void 0) return true;
4857
+ return false;
4858
+ }
4859
+ function isWithinAny(element, outers) {
4860
+ for (const outer of outers) if (isWithin(element, outer)) return true;
4861
+ return false;
4862
+ }
4863
+ function isInsideOtherCopy(component, elements, copied) {
4864
+ for (const element of elements) for (const other of copied) if (other !== component && element.start >= other.fn.start && element.end <= other.fn.end) return true;
4865
+ return false;
4866
+ }
4867
+ function hasChild(children, child) {
4868
+ for (const item of children) if (item === child) return true;
4869
+ return false;
4870
+ }
4871
+ /** The name a non-computed object key spells, like `Trigger` or `'Trigger'`. */
4872
+ function propertyKeyName(key) {
4873
+ if (key.type === "Identifier") return key.name;
4874
+ return key.type === "Literal" && typeof key.value === "string" ? key.value : void 0;
4875
+ }
4084
4876
  //#endregion
4085
4877
  //#region src/memo.ts
4086
4878
  /**
@@ -4093,29 +4885,81 @@ const TRACKED_PROPS = /* @__PURE__ */ new Map([
4093
4885
  ["Repeat", "count"]
4094
4886
  ]);
4095
4887
  /**
4888
+ * Global constructors whose instances are never thenable or async iterable.
4889
+ */
4890
+ const SYNC_CONSTRUCTORS = /* @__PURE__ */ new Set([
4891
+ "Array",
4892
+ "Date",
4893
+ "Error",
4894
+ "Map",
4895
+ "RegExp",
4896
+ "Set",
4897
+ "URL",
4898
+ "URLSearchParams",
4899
+ "WeakMap",
4900
+ "WeakSet"
4901
+ ]);
4902
+ /**
4903
+ * Whether an object literal can have a `then` method or `Symbol.asyncIterator`,
4904
+ * its own or from a `__proto__` it sets.
4905
+ */
4906
+ function mayBeThenable(node) {
4907
+ for (const property of node.properties) {
4908
+ if (property.type === "SpreadElement" || property.computed) return true;
4909
+ const { key } = property;
4910
+ let name;
4911
+ if (key.type === "Identifier") name = key.name;
4912
+ else if ("value" in key) name = key.value;
4913
+ if (name === "then" || name === "__proto__") return true;
4914
+ }
4915
+ return false;
4916
+ }
4917
+ /**
4096
4918
  * Whether evaluating `node` always creates a new value, which reference
4097
- * equality never finds equal to the last one.
4919
+ * equality never finds equal to the last one. The value is never a promise
4920
+ * or an async iterable, which a memo waits for and an inlined read does not.
4921
+ * `isGlobal` tells whether a name is one the module does not declare.
4098
4922
  */
4099
- function isFresh(node) {
4923
+ function isFresh(node, isGlobal) {
4100
4924
  switch (node.type) {
4101
- case "ObjectExpression":
4102
4925
  case "ArrayExpression":
4103
4926
  case "ArrowFunctionExpression":
4104
4927
  case "FunctionExpression":
4105
- case "ClassExpression":
4106
- case "NewExpression":
4107
4928
  case "JSXElement":
4108
4929
  case "JSXFragment": return true;
4109
- case "ParenthesizedExpression": return isFresh(node.expression);
4110
- case "ConditionalExpression": return isFresh(node.consequent) && isFresh(node.alternate);
4930
+ case "ObjectExpression": return !mayBeThenable(node);
4931
+ case "NewExpression": return node.callee.type === "Identifier" && SYNC_CONSTRUCTORS.has(node.callee.name) && isGlobal(node.callee);
4932
+ case "ParenthesizedExpression": return isFresh(node.expression, isGlobal);
4933
+ case "ConditionalExpression": return isFresh(node.consequent, isGlobal) && isFresh(node.alternate, isGlobal);
4111
4934
  case "SequenceExpression": {
4112
4935
  const last = node.expressions.at(-1);
4113
- return last !== void 0 && isFresh(last);
4936
+ return last !== void 0 && isFresh(last, isGlobal);
4114
4937
  }
4115
4938
  default: return false;
4116
4939
  }
4117
4940
  }
4118
4941
  /**
4942
+ * Whether `node` evaluates to a value that is never a promise or an async
4943
+ * iterable. A memo waits for one of those, and an inlined read does not.
4944
+ */
4945
+ function isSync(node, isGlobal) {
4946
+ switch (node.type) {
4947
+ case "Literal":
4948
+ case "TemplateLiteral":
4949
+ case "UnaryExpression":
4950
+ case "UpdateExpression":
4951
+ case "BinaryExpression": return true;
4952
+ case "ParenthesizedExpression": return isSync(node.expression, isGlobal);
4953
+ case "ConditionalExpression": return isSync(node.consequent, isGlobal) && isSync(node.alternate, isGlobal);
4954
+ case "LogicalExpression": return isSync(node.left, isGlobal) && isSync(node.right, isGlobal);
4955
+ case "SequenceExpression": {
4956
+ const last = node.expressions.at(-1);
4957
+ return last !== void 0 && isSync(last, isGlobal);
4958
+ }
4959
+ default: return isFresh(node, isGlobal);
4960
+ }
4961
+ }
4962
+ /**
4119
4963
  * The text of an expression that always gives the same primitive: a literal
4120
4964
  * other than a regular expression, a template literal without expressions,
4121
4965
  * or a negated number.
@@ -4123,9 +4967,9 @@ function isFresh(node) {
4123
4967
  function constantText(context, node) {
4124
4968
  const expression = unwrap(node);
4125
4969
  switch (expression.type) {
4126
- case "Literal": return "regex" in expression ? void 0 : textOf(context, expression);
4127
- case "TemplateLiteral": return expression.expressions.length === 0 ? textOf(context, expression) : void 0;
4128
- case "UnaryExpression": return expression.operator === "-" && expression.argument.type === "Literal" && typeof expression.argument.value === "number" ? textOf(context, expression) : void 0;
4970
+ case "Literal": return "regex" in expression ? void 0 : getText(context, expression);
4971
+ case "TemplateLiteral": return expression.expressions.length === 0 ? getText(context, expression) : void 0;
4972
+ case "UnaryExpression": return expression.operator === "-" && expression.argument.type === "Literal" && typeof expression.argument.value === "number" ? getText(context, expression) : void 0;
4129
4973
  default: return;
4130
4974
  }
4131
4975
  }
@@ -4141,6 +4985,7 @@ var MemoInliner = class {
4141
4985
  constructor(context) {
4142
4986
  this.context = context;
4143
4987
  this.changed = false;
4988
+ this.edited = [];
4144
4989
  this.reason = "";
4145
4990
  }
4146
4991
  /** Whether a callee is Solid's `createMemo` or `children`. */
@@ -4199,21 +5044,21 @@ var MemoInliner = class {
4199
5044
  };
4200
5045
  }
4201
5046
  /**
4202
- * Replaces every read of a memo whose computation is a literal with the
5047
+ * Replaces every read of a memo or signal whose value is a literal with the
4203
5048
  * literal. Each reference has to be a call after the declaration, since a
4204
5049
  * call before it would throw.
4205
5050
  */
4206
- inlineConstant(declarator, binding, text) {
5051
+ inlineConstant(declarator, binding, text, kind = "memo") {
4207
5052
  const statement = this.context.parents.get(declarator);
4208
5053
  if (statement?.type !== "VariableDeclaration" || statement.declarations.length !== 1) {
4209
- this.reason = "memo-declaration";
5054
+ this.reason = `${kind}-declaration`;
4210
5055
  return;
4211
5056
  }
4212
5057
  const calls = [];
4213
5058
  for (const reference of binding.references) {
4214
5059
  const call = this.context.parents.get(reference);
4215
5060
  if (call?.type !== "CallExpression" || call.callee !== reference || call.arguments.length > 0 || call.start < declarator.end) {
4216
- this.reason = "memo-constant";
5061
+ this.reason = `${kind}-constant`;
4217
5062
  return;
4218
5063
  }
4219
5064
  calls.push(call);
@@ -4221,22 +5066,24 @@ var MemoInliner = class {
4221
5066
  for (const call of calls) {
4222
5067
  const parent = this.context.parents.get(call);
4223
5068
  const bare = parent?.type === "JSXExpressionContainer" || parent?.type === "VariableDeclarator" || parent?.type === "ReturnStatement" || parent?.type === "ArrayExpression" || parent?.type === "Property" || parent?.type === "CallExpression" && parent.callee !== call;
4224
- this.context.s.overwrite(call.start, call.end, bare ? text : `(${text})`);
5069
+ this.context.s.overwrite(call.start, call.end, bare ? text : joinText`(${text})`);
5070
+ this.edited.push([call.start, call.end]);
4225
5071
  }
4226
5072
  this.context.s.remove(statement.start, statement.end);
5073
+ this.edited.push([statement.start, statement.end]);
4227
5074
  this.changed = true;
4228
5075
  return true;
4229
5076
  }
4230
5077
  /**
4231
5078
  * The function a node runs in.
4232
5079
  */
4233
- functionOf(node) {
5080
+ findEnclosingFunction(node) {
4234
5081
  let current = this.context.parents.get(node);
4235
5082
  while (current && !isFunctionNode(current)) current = this.context.parents.get(current);
4236
5083
  return current;
4237
5084
  }
4238
5085
  /** The JSX expression container a call is the whole of. */
4239
- containerOf(call) {
5086
+ findContainer(call) {
4240
5087
  let parent = this.context.parents.get(call);
4241
5088
  while (parent?.type === "ParenthesizedExpression") parent = this.context.parents.get(parent);
4242
5089
  return parent?.type === "JSXExpressionContainer" ? parent : void 0;
@@ -4269,11 +5116,11 @@ var MemoInliner = class {
4269
5116
  const tag = element.openingElement.name.name;
4270
5117
  if (isIntrinsicTag(tag)) {
4271
5118
  if (attribute.startsWith("on") || attribute === "ref") return false;
4272
- } else if (this.builtInOf(element.openingElement.name) !== tag || TRACKED_PROPS.get(tag) !== attribute) return false;
5119
+ } else if (this.getBuiltIn(element.openingElement.name) !== tag || TRACKED_PROPS.get(tag) !== attribute) return false;
4273
5120
  } else return false;
4274
5121
  return this.isStaticJSX(element, fn);
4275
5122
  }
4276
- builtInOf(name) {
5123
+ getBuiltIn(name) {
4277
5124
  if (name.type !== "JSXIdentifier") return;
4278
5125
  const { references } = this.context.scopes;
4279
5126
  if (!references.has(name)) return;
@@ -4298,7 +5145,7 @@ var MemoInliner = class {
4298
5145
  }
4299
5146
  case "JSXFragment":
4300
5147
  case "ParenthesizedExpression": break;
4301
- case "ReturnStatement": return this.functionOf(parent) === fn && !this.inLoop(parent, fn);
5148
+ case "ReturnStatement": return this.findEnclosingFunction(parent) === fn && !this.inLoop(parent, fn);
4302
5149
  default: return false;
4303
5150
  }
4304
5151
  node = parent;
@@ -4342,14 +5189,19 @@ var MemoInliner = class {
4342
5189
  } else {
4343
5190
  const constant = constantText(this.context, expression);
4344
5191
  if (constant !== void 0) return this.inlineConstant(declarator, binding, constant);
4345
- if (!alwaysNotifies && !isFresh(expression)) return;
5192
+ const isGlobal = (node) => this.context.scopes.references.get(node) === void 0;
5193
+ if (!alwaysNotifies && !isFresh(expression, isGlobal)) return;
5194
+ if (alwaysNotifies && !isSync(expression, isGlobal)) {
5195
+ this.reason = "memo-async";
5196
+ return;
5197
+ }
4346
5198
  }
4347
5199
  if (binding.references.length !== 1) {
4348
5200
  this.reason = "memo-reads";
4349
5201
  return;
4350
5202
  }
4351
5203
  const statement = this.context.parents.get(declarator);
4352
- const fn = this.functionOf(declarator);
5204
+ const fn = this.findEnclosingFunction(declarator);
4353
5205
  if (statement?.type !== "VariableDeclaration" || statement.declarations.length !== 1 || !fn) {
4354
5206
  this.reason = "memo-declaration";
4355
5207
  return;
@@ -4364,7 +5216,7 @@ var MemoInliner = class {
4364
5216
  this.reason = "memo-read-place";
4365
5217
  return;
4366
5218
  }
4367
- const container = this.containerOf(call);
5219
+ const container = this.findContainer(call);
4368
5220
  const owner = container ? this.context.parents.get(container) : void 0;
4369
5221
  if (kind === "children" && (!container || owner?.type !== "JSXElement" && owner?.type !== "JSXFragment")) {
4370
5222
  this.reason = "memo-read-place";
@@ -4374,18 +5226,91 @@ var MemoInliner = class {
4374
5226
  this.reason = "memo-scope";
4375
5227
  return;
4376
5228
  }
4377
- if (kind === "children" && container) this.context.s.overwrite(container.start, container.end, textOf(this.context, expression));
4378
- else this.context.s.overwrite(call.start, call.end, textOf(this.context, expression));
5229
+ if (kind === "children" && container) {
5230
+ this.context.s.overwrite(container.start, container.end, getText(this.context, expression));
5231
+ this.edited.push([container.start, container.end]);
5232
+ } else {
5233
+ this.context.s.overwrite(call.start, call.end, getText(this.context, expression));
5234
+ this.edited.push([call.start, call.end]);
5235
+ }
4379
5236
  this.context.s.remove(statement.start, statement.end);
5237
+ this.edited.push([statement.start, statement.end]);
4380
5238
  this.changed = true;
4381
5239
  return true;
4382
5240
  }
5241
+ /**
5242
+ * The literal a signal always holds: `const [get] = createSignal(literal)`,
5243
+ * or `const [get, set] = ...` with nothing referencing `set`. Options can
5244
+ * change what a read does, such as `unobserved`, so a signal with options
5245
+ * stays.
5246
+ */
5247
+ signalConstant(declarator, binding) {
5248
+ const pattern = declarator.id;
5249
+ const init = declarator.init ? unwrap(declarator.init) : void 0;
5250
+ if (pattern.type !== "ArrayPattern" || pattern.elements.at(0) !== binding.identifier || pattern.elements.length > 2 || init?.type !== "CallExpression" || init.callee.type !== "Identifier" || init.arguments.length !== 1) return;
5251
+ const callee = this.context.scopes.references.get(init.callee);
5252
+ if (!callee || solidExport(callee, this.context.options) !== "createSignal") return;
5253
+ const value = init.arguments.at(0);
5254
+ if (!value || value.type === "SpreadElement") return;
5255
+ const statement = this.context.parents.get(declarator);
5256
+ if (statement && this.context.parents.get(statement)?.type === "ExportNamedDeclaration") return;
5257
+ const setter = pattern.elements.at(1);
5258
+ if (setter) {
5259
+ const setterBinding = setter.type === "Identifier" ? binding.scope.bindings.get(setter.name) : void 0;
5260
+ if (setterBinding?.identifier !== setter || setterBinding.references.length > 0) return;
5261
+ }
5262
+ return constantText(this.context, value);
5263
+ }
5264
+ tryInlineSignal(declarator, binding) {
5265
+ const text = this.signalConstant(declarator, binding);
5266
+ if (text === void 0) return;
5267
+ this.reason = "";
5268
+ if (this.inlineConstant(declarator, binding, text, "signal") === void 0) recordSkip(this.context, "memos", this.reason, binding.name);
5269
+ }
5270
+ /**
5271
+ * Replaces every call of `const name = () => expression` with the
5272
+ * expression. Each reference has to be a call with no arguments after the
5273
+ * declaration, and every name in the body has to mean the same at the call.
5274
+ */
5275
+ tryInlineArrow(declarator, binding) {
5276
+ const fn = declarator.init ? unwrap(declarator.init) : void 0;
5277
+ if (fn?.type !== "ArrowFunctionExpression" || fn.async || fn.params.length > 0) return;
5278
+ const body = returnedExpression(fn);
5279
+ const statement = this.context.parents.get(declarator);
5280
+ if (!body || statement?.type !== "VariableDeclaration" || statement.declarations.length !== 1 || this.context.parents.get(statement)?.type === "ExportNamedDeclaration") return;
5281
+ const calls = [];
5282
+ for (const reference of binding.references) {
5283
+ const call = this.context.parents.get(reference);
5284
+ if (call?.type !== "CallExpression" || call.callee !== reference || call.optional || call.arguments.length > 0 || call.start < declarator.end) return;
5285
+ const parent = this.context.parents.get(call);
5286
+ if (parent?.type === "CallExpression" && parent.callee === call || parent?.type === "TaggedTemplateExpression" && parent.tag === call || parent?.type === "UnaryExpression" && parent.operator === "delete") return;
5287
+ calls.push(call);
5288
+ }
5289
+ if (calls.length === 0) return;
5290
+ for (const [start, end] of this.edited) if (start < statement.end && end > statement.start) return;
5291
+ const text = getText(this.context, body);
5292
+ const length = compactLength(text.code);
5293
+ if ((calls.length - 1) * length > calls.length * 3 + 13) return;
5294
+ if (usesFunctionContext(this.context, fn)) return;
5295
+ for (const call of calls) if (!this.resolvesSameAt(body, call, binding)) return;
5296
+ const bare = isPrimary(body);
5297
+ for (const call of calls) {
5298
+ const inContainer = this.context.parents.get(call)?.type === "JSXExpressionContainer" && body.type !== "SequenceExpression";
5299
+ this.context.s.overwrite(call.start, call.end, bare || inContainer ? text : joinText`(${text})`);
5300
+ this.edited.push([call.start, call.end]);
5301
+ }
5302
+ this.context.s.remove(statement.start, statement.end);
5303
+ this.edited.push([statement.start, statement.end]);
5304
+ this.changed = true;
5305
+ }
4383
5306
  run() {
4384
- for (const scope of new Set(this.context.scopes.scopes.values())) {
4385
- if (scope.parent === void 0) continue;
4386
- for (const binding of scope.bindings.values()) {
4387
- const { declaration } = binding;
4388
- if (binding.kind === "const" && !binding.mutated && declaration.type === "VariableDeclarator" && declaration.id === binding.identifier) this.tryInline(declaration, binding);
5307
+ for (const scope of new Set(this.context.scopes.scopes.values())) for (const binding of scope.bindings.values()) {
5308
+ const { declaration } = binding;
5309
+ if (binding.kind !== "const" || binding.mutated || declaration.type !== "VariableDeclarator") continue;
5310
+ if (declaration.id.type === "ArrayPattern") this.tryInlineSignal(declaration, binding);
5311
+ else if (declaration.id === binding.identifier) {
5312
+ this.tryInlineArrow(declaration, binding);
5313
+ if (scope.parent !== void 0) this.tryInline(declaration, binding);
4389
5314
  }
4390
5315
  }
4391
5316
  }
@@ -4399,6 +5324,581 @@ function inlineMemos(context) {
4399
5324
  return inliner.changed;
4400
5325
  }
4401
5326
  //#endregion
5327
+ //#region src/nesting.ts
5328
+ const VOID_ELEMENTS = /* @__PURE__ */ new Set([
5329
+ "area",
5330
+ "base",
5331
+ "br",
5332
+ "col",
5333
+ "embed",
5334
+ "hr",
5335
+ "img",
5336
+ "input",
5337
+ "keygen",
5338
+ "link",
5339
+ "meta",
5340
+ "param",
5341
+ "source",
5342
+ "track",
5343
+ "wbr"
5344
+ ]);
5345
+ const SVG_ELEMENTS = /* @__PURE__ */ new Set([
5346
+ "altGlyph",
5347
+ "altGlyphDef",
5348
+ "altGlyphItem",
5349
+ "animate",
5350
+ "animateColor",
5351
+ "animateMotion",
5352
+ "animateTransform",
5353
+ "circle",
5354
+ "clipPath",
5355
+ "cursor",
5356
+ "defs",
5357
+ "desc",
5358
+ "ellipse",
5359
+ "feBlend",
5360
+ "feColorMatrix",
5361
+ "feComponentTransfer",
5362
+ "feComposite",
5363
+ "feConvolveMatrix",
5364
+ "feDiffuseLighting",
5365
+ "feDisplacementMap",
5366
+ "feDistantLight",
5367
+ "feDropShadow",
5368
+ "feFlood",
5369
+ "feFuncA",
5370
+ "feFuncB",
5371
+ "feFuncG",
5372
+ "feFuncR",
5373
+ "feGaussianBlur",
5374
+ "feImage",
5375
+ "feMerge",
5376
+ "feMergeNode",
5377
+ "feMorphology",
5378
+ "feOffset",
5379
+ "fePointLight",
5380
+ "feSpecularLighting",
5381
+ "feSpotLight",
5382
+ "feTile",
5383
+ "feTurbulence",
5384
+ "filter",
5385
+ "font",
5386
+ "foreignObject",
5387
+ "g",
5388
+ "glyph",
5389
+ "glyphRef",
5390
+ "hkern",
5391
+ "image",
5392
+ "line",
5393
+ "linearGradient",
5394
+ "marker",
5395
+ "mask",
5396
+ "metadata",
5397
+ "mpath",
5398
+ "path",
5399
+ "pattern",
5400
+ "polygon",
5401
+ "polyline",
5402
+ "radialGradient",
5403
+ "rect",
5404
+ "set",
5405
+ "stop",
5406
+ "switch",
5407
+ "symbol",
5408
+ "text",
5409
+ "textPath",
5410
+ "tref",
5411
+ "tspan",
5412
+ "use",
5413
+ "view",
5414
+ "vkern"
5415
+ ]);
5416
+ function findElement(parent, name) {
5417
+ for (const child of parent.childNodes) if (child.nodeName === name && "childNodes" in child) return child;
5418
+ throw new Error(`[solid-optimizer] no <${name}> in an empty document`);
5419
+ }
5420
+ let body;
5421
+ /** What a browser makes of `html` set as the body's `innerHTML`. */
5422
+ function parseAsBody(html) {
5423
+ body ??= findElement(findElement(parse("<!DOCTYPE html><html><body></body></html>"), "html"), "body");
5424
+ return serialize(parseFragment(body, html, {}));
5425
+ }
5426
+ /** The tag of an intrinsic element, or `undefined` for a component or a namespaced tag. */
5427
+ function readIntrinsicTag(element) {
5428
+ const name = element.openingElement.name;
5429
+ return name.type === "JSXIdentifier" && isIntrinsicTag(name.name) ? name.name : void 0;
5430
+ }
5431
+ /**
5432
+ * The template rooted at `element`. Elements inside fragments join it.
5433
+ * Elements in expression containers or under a component start their own.
5434
+ */
5435
+ function collectTemplate(element, tag) {
5436
+ const node = {
5437
+ element,
5438
+ tag,
5439
+ children: []
5440
+ };
5441
+ addTemplateChildren(node, element.children);
5442
+ return node;
5443
+ }
5444
+ function addTemplateChildren(node, children) {
5445
+ for (const child of children) if (child.type === "JSXFragment") addTemplateChildren(node, child.children);
5446
+ else if (child.type === "JSXElement") {
5447
+ const tag = readIntrinsicTag(child);
5448
+ if (tag !== void 0) node.children.push(collectTemplate(child, tag));
5449
+ }
5450
+ }
5451
+ /**
5452
+ * The tags of a template, without text or attributes. Elements not in
5453
+ * `included` are left out with what they hold.
5454
+ */
5455
+ function writeTags(node, included) {
5456
+ if (VOID_ELEMENTS.has(node.tag)) return `<${node.tag}>`;
5457
+ let inner = "";
5458
+ for (const child of node.children) if (included.has(child)) inner += writeTags(child, included);
5459
+ return `<${node.tag}>${inner}</${node.tag}>`;
5460
+ }
5461
+ /**
5462
+ * Table parts parse only inside a table, and SVG parts only inside an
5463
+ * `<svg>`, so a template rooted at one is checked inside one, as Solid
5464
+ * creates it.
5465
+ */
5466
+ function placeInContext(tag, html) {
5467
+ if (SVG_ELEMENTS.has(tag)) return `<svg>${html}</svg>`;
5468
+ switch (tag) {
5469
+ case "td":
5470
+ case "th": return `<table><tbody><tr>${html}</tr></tbody></table>`;
5471
+ case "tr": return `<table><tbody>${html}</tbody></table>`;
5472
+ case "col": return `<table><colgroup>${html}</colgroup></table>`;
5473
+ case "thead":
5474
+ case "tbody":
5475
+ case "tfoot":
5476
+ case "colgroup":
5477
+ case "caption": return `<table>${html}</table>`;
5478
+ default: return html;
5479
+ }
5480
+ }
5481
+ /** Whether a `<template>` in the template holds an element, which Solid rejects. */
5482
+ function hasTemplateContent(node, included) {
5483
+ for (const child of node.children) if (included.has(child) && (node.tag === "template" || hasTemplateContent(child, included))) return true;
5484
+ return false;
5485
+ }
5486
+ function isValidTemplate(root, included) {
5487
+ if (hasTemplateContent(root, included)) return false;
5488
+ const html = placeInContext(root.tag, writeTags(root, included));
5489
+ return parseAsBody(html).toLowerCase() === html.toLowerCase();
5490
+ }
5491
+ function collectAll(node, into) {
5492
+ into.add(node);
5493
+ for (const child of node.children) collectAll(child, into);
5494
+ return into;
5495
+ }
5496
+ /**
5497
+ * Wraps the elements that make `root`'s template parse differently, and
5498
+ * returns the wrapped elements, each the root of a template of its own.
5499
+ */
5500
+ function wrapInvalidElements(context, root) {
5501
+ if (isValidTemplate(root, collectAll(root, /* @__PURE__ */ new Set()))) return [];
5502
+ const included = /* @__PURE__ */ new Set([root]);
5503
+ if (!isValidTemplate(root, included)) return [];
5504
+ const wrapped = [];
5505
+ const pending = [];
5506
+ pushChildren(pending, root);
5507
+ for (let node = pending.pop(); node; node = pending.pop()) {
5508
+ included.add(node);
5509
+ if (!isValidTemplate(root, included)) {
5510
+ included.delete(node);
5511
+ context.s.prependRight(node.element.start, "{");
5512
+ context.s.appendLeft(node.element.end, "}");
5513
+ wrapped.push(node);
5514
+ continue;
5515
+ }
5516
+ pushChildren(pending, node);
5517
+ }
5518
+ return wrapped;
5519
+ }
5520
+ /** Pushes the children of `node` so that they pop in source order. */
5521
+ function pushChildren(pending, node) {
5522
+ for (let index = node.children.length - 1; index >= 0; index -= 1) pending.push(node.children[index]);
5523
+ }
5524
+ function repairNesting(context) {
5525
+ const roots = [];
5526
+ const visit = (node, inTemplate) => {
5527
+ if (node.type === "JSXElement") {
5528
+ const tag = readIntrinsicTag(node);
5529
+ if (tag !== void 0 && !inTemplate) roots.push(collectTemplate(node, tag));
5530
+ for (const child of node.children) visit(child, tag !== void 0);
5531
+ for (const attribute of node.openingElement.attributes) visit(attribute, false);
5532
+ return;
5533
+ }
5534
+ if (node.type === "JSXFragment") {
5535
+ for (const child of node.children) visit(child, inTemplate);
5536
+ return;
5537
+ }
5538
+ forEachChild(node, (child) => {
5539
+ visit(child, false);
5540
+ });
5541
+ };
5542
+ visit(context.program, false);
5543
+ let changed = false;
5544
+ for (let root = roots.pop(); root; root = roots.pop()) {
5545
+ const wrapped = wrapInvalidElements(context, root);
5546
+ if (wrapped.length > 0) {
5547
+ changed = true;
5548
+ roots.push(...wrapped);
5549
+ }
5550
+ }
5551
+ return changed;
5552
+ }
5553
+ //#endregion
5554
+ //#region src/conditional.ts
5555
+ /**
5556
+ * Rewrites each `<Show>` and `<Switch>` that can be lowered. One inside
5557
+ * another that is lowered stays for the next run, since both would edit the
5558
+ * same text.
5559
+ */
5560
+ function lowerConditionals(context) {
5561
+ let changed = false;
5562
+ visit(context.program);
5563
+ return changed;
5564
+ function visit(node) {
5565
+ if (node.type === "JSXElement") {
5566
+ const ternary = ternaryOf(context, node);
5567
+ const form = ternary === void 0 ? void 0 : formAt(context, node);
5568
+ if (ternary !== void 0 && form !== void 0) {
5569
+ context.s.overwrite(node.start, node.end, form === "container" ? joinText`{${ternary}}` : joinText`<>{${ternary}}</>`);
5570
+ changed = true;
5571
+ return;
5572
+ }
5573
+ }
5574
+ forEachChild(node, visit);
5575
+ }
5576
+ }
5577
+ /**
5578
+ * The Solid built-in an element's tag resolves to, by the name Solid exports it under.
5579
+ */
5580
+ function builtInOf(context, element) {
5581
+ const { name } = element.openingElement;
5582
+ if (name.type !== "JSXIdentifier") return;
5583
+ const { references } = context.scopes;
5584
+ if (!references.has(name)) return;
5585
+ const binding = references.get(name);
5586
+ const identity = binding ? solidExport(binding, context.options) : name.name;
5587
+ return identity !== void 0 && context.options.builtIns.has(identity) ? identity : void 0;
5588
+ }
5589
+ /**
5590
+ * The ternary a `<Show>` or `<Switch>` lowers to, or `undefined` when its
5591
+ * props or children need the component.
5592
+ */
5593
+ function ternaryOf(context, element) {
5594
+ switch (builtInOf(context, element)) {
5595
+ case "Show": {
5596
+ const branch = branchOf(context, element, ["when", "fallback"]);
5597
+ if (branch === void 0) return;
5598
+ return joinText`${branch.when} ? ${branch.children} : ${branch.fallback ?? "undefined"}`;
5599
+ }
5600
+ case "Switch": return switchTernary(context, element);
5601
+ default: return;
5602
+ }
5603
+ }
5604
+ /**
5605
+ * A `<Switch>` whose children are all `<Match>`es that lower, as a chain of ternaries.
5606
+ */
5607
+ function switchTernary(context, element) {
5608
+ const props = propsOf(context, element, ["fallback"]);
5609
+ if (props === void 0) return;
5610
+ const chain = [];
5611
+ let count = 0;
5612
+ for (const child of significantChildren(element.children)) {
5613
+ if (child.type !== "JSXElement" || builtInOf(context, child) !== "Match") return;
5614
+ const branch = branchOf(context, child, ["when"]);
5615
+ if (branch === void 0) return;
5616
+ chain.push(branch.when, " ? ", branch.children, " : ");
5617
+ count += 1;
5618
+ }
5619
+ if (count === 0) return;
5620
+ return join([...chain, props.get("fallback") ?? "undefined"]);
5621
+ }
5622
+ /**
5623
+ * How a `<Show>` or `<Switch>` at this position is written once lowered, or `undefined`
5624
+ * when the position is not supported.
5625
+ */
5626
+ function formAt(context, element) {
5627
+ const parent = context.parents.get(element);
5628
+ if (parent === void 0) return "fragment";
5629
+ switch (parent.type) {
5630
+ case "JSXFragment": return "container";
5631
+ case "JSXElement": {
5632
+ const { name } = parent.openingElement;
5633
+ if (name.type === "JSXNamespacedName" || name.type === "JSXIdentifier" && isIntrinsicTag(name.name)) return "container";
5634
+ return isSoleChild(parent.children, element) ? "fragment" : void 0;
5635
+ }
5636
+ case "JSXExpressionContainer":
5637
+ case "JSXAttribute": return;
5638
+ default: return isInJSXExpression(context, parent) ? void 0 : "fragment";
5639
+ }
5640
+ }
5641
+ /**
5642
+ * Whether a node is part of an expression in a JSX container, such as
5643
+ * `{ok && <Show />}`, where a function boundary does not separate them.
5644
+ */
5645
+ function isInJSXExpression(context, node) {
5646
+ let current = node;
5647
+ while (current !== void 0 && !isFunctionNode(current)) {
5648
+ if (current.type === "JSXExpressionContainer") return true;
5649
+ current = context.parents.get(current);
5650
+ }
5651
+ return false;
5652
+ }
5653
+ function isSoleChild(children, element) {
5654
+ for (const child of children) if (child !== element && !isInsignificant(child)) return false;
5655
+ return true;
5656
+ }
5657
+ /**
5658
+ * The text of each prop of an element, or `undefined` when it has a prop
5659
+ * other than `names`, a spread, or a prop more than once. A repeated prop
5660
+ * takes its last value, and a spread could hold any prop, such as `keyed`.
5661
+ */
5662
+ function propsOf(context, element, names) {
5663
+ const props = /* @__PURE__ */ new Map();
5664
+ for (const attribute of element.openingElement.attributes) {
5665
+ if (attribute.type !== "JSXAttribute" || attribute.name.type !== "JSXIdentifier" || !names.includes(attribute.name.name) || props.has(attribute.name.name)) return;
5666
+ const text = expressionText(context, attribute);
5667
+ if (text === void 0) return;
5668
+ props.set(attribute.name.name, text);
5669
+ }
5670
+ return props;
5671
+ }
5672
+ /**
5673
+ * The condition and children of a `<Show>` or `<Match>`, or `undefined` when
5674
+ * the children could need the narrowed value.
5675
+ */
5676
+ function branchOf(context, element, names) {
5677
+ const props = propsOf(context, element, names);
5678
+ const when = props?.get("when");
5679
+ if (props === void 0 || when === void 0) return;
5680
+ const significant = significantChildren(element.children);
5681
+ const sole = significant.length === 1 ? significant[0] : void 0;
5682
+ const callback = sole?.type === "JSXExpressionContainer" && sole.expression.type !== "JSXEmptyExpression" ? unwrap(sole.expression) : void 0;
5683
+ if (callback?.type === "ArrowFunctionExpression") {
5684
+ const body = callbackBody(context, element, callback);
5685
+ return body === void 0 ? void 0 : {
5686
+ when,
5687
+ children: body,
5688
+ fallback: props.get("fallback")
5689
+ };
5690
+ }
5691
+ if (sole?.type === "JSXExpressionContainer" && sole.expression.type !== "JSXEmptyExpression" && !isNeverFunction(sole.expression)) return;
5692
+ for (const child of significant) if (child.type === "JSXExpressionContainer" && child.expression.type !== "JSXEmptyExpression" && isFunctionNode(unwrap(child.expression))) return;
5693
+ const { closingElement } = element;
5694
+ const inner = closingElement ? context.s.slice(element.openingElement.end, closingElement.start) : "";
5695
+ return {
5696
+ when,
5697
+ children: significant.length > 0 ? joinText`<>${inner}</>` : "undefined",
5698
+ fallback: props.get("fallback")
5699
+ };
5700
+ }
5701
+ /**
5702
+ * The body of a callback child with each read of its parameter written as
5703
+ * `when`, or `undefined` when that could change what the body renders.
5704
+ */
5705
+ function callbackBody(context, element, callback) {
5706
+ const param = callback.params.at(0);
5707
+ if (callback.async || callback.body.type === "BlockStatement" || callback.params.length !== 1 || param?.type !== "Identifier") return;
5708
+ const body = unwrap(callback.body);
5709
+ if (body.type !== "JSXElement" && body.type !== "JSXFragment") return;
5710
+ const value = findAttribute(element, "when")?.value;
5711
+ if (value?.type !== "JSXExpressionContainer" || value.expression.type === "JSXEmptyExpression" || !isPlainRead(context, value.expression)) return;
5712
+ const when = value.expression;
5713
+ const whenText = joinText`(${context.s.slice(when.start, when.end)})`;
5714
+ const names = [];
5715
+ collectReferences(context, when, names);
5716
+ const binding = lookup(scopeAt(context.scopes, context.parents, param), param.name);
5717
+ if (binding?.identifier !== param || binding.mutated || namesInTypes(body, param.name)) return;
5718
+ const edits = [];
5719
+ for (const reference of binding.references) {
5720
+ if (reference.type !== "Identifier") return;
5721
+ const scope = scopeAt(context.scopes, context.parents, reference);
5722
+ for (const name of names) if (name.type !== "Identifier" || lookup(scope, name.name) !== context.scopes.references.get(name)) return;
5723
+ const parent = context.parents.get(reference);
5724
+ if (parent?.type === "CallExpression" && parent.callee === reference && parent.arguments.length === 0 && !parent.optional) edits.push({
5725
+ start: parent.start,
5726
+ end: parent.end,
5727
+ text: whenText
5728
+ });
5729
+ else if (parent?.type === "Property" && parent.shorthand) return;
5730
+ else edits.push({
5731
+ start: reference.start,
5732
+ end: reference.end,
5733
+ text: joinText`(() => ${whenText})`
5734
+ });
5735
+ }
5736
+ edits.sort((a, b) => a.start - b.start);
5737
+ const parts = [];
5738
+ let at = body.start;
5739
+ for (const edit of edits) {
5740
+ parts.push(context.s.slice(at, edit.start), edit.text);
5741
+ at = edit.end;
5742
+ }
5743
+ parts.push(context.s.slice(at, body.end));
5744
+ return join(parts);
5745
+ }
5746
+ /**
5747
+ * Whether reading an expression again gives the same value, with nothing run
5748
+ * between the reads: names, members, literals, and operators, and calls of
5749
+ * a signal or a memo. Another call could change something or return
5750
+ * something new, and `this` changes inside a `function` in the body.
5751
+ */
5752
+ function isPlainRead(context, node) {
5753
+ switch (node.type) {
5754
+ case "Identifier":
5755
+ case "Literal": return true;
5756
+ case "ParenthesizedExpression":
5757
+ case "TSAsExpression":
5758
+ case "TSSatisfiesExpression":
5759
+ case "TSNonNullExpression":
5760
+ case "ChainExpression": return isPlainRead(context, node.expression);
5761
+ case "MemberExpression": return isPlainRead(context, node.object) && (!node.computed || isPlainRead(context, node.property));
5762
+ case "CallExpression": return node.arguments.length === 0 && isAccessor(context, node.callee);
5763
+ case "UnaryExpression": return node.operator !== "delete" && isPlainRead(context, node.argument);
5764
+ case "BinaryExpression":
5765
+ case "LogicalExpression": return isPlainRead(context, node.left) && isPlainRead(context, node.right);
5766
+ case "ConditionalExpression": return isPlainRead(context, node.test) && isPlainRead(context, node.consequent) && isPlainRead(context, node.alternate);
5767
+ default: return false;
5768
+ }
5769
+ }
5770
+ /**
5771
+ * Whether a callee is the getter of a `createSignal` or a `createMemo` from
5772
+ * Solid, declared with `const` and never written, which returns its current
5773
+ * value without running anything else.
5774
+ */
5775
+ function isAccessor(context, callee) {
5776
+ if (callee.type !== "Identifier") return false;
5777
+ const binding = context.scopes.references.get(callee);
5778
+ if (!binding || binding.mutated || binding.kind !== "const") return false;
5779
+ const { declaration } = binding;
5780
+ if (declaration.type !== "VariableDeclarator" || !declaration.init) return false;
5781
+ const init = unwrap(declaration.init);
5782
+ if (init.type !== "CallExpression" || init.callee.type !== "Identifier") return false;
5783
+ const factory = context.scopes.references.get(init.callee);
5784
+ const name = factory ? solidExport(factory, context.options) : void 0;
5785
+ if (name === "createMemo") return declaration.id === binding.identifier;
5786
+ return name === "createSignal" && declaration.id.type === "ArrayPattern" && declaration.id.elements.at(0) === binding.identifier;
5787
+ }
5788
+ /** Whether a TypeScript type in `node`, like `typeof v`, names `name`. */
5789
+ function namesInTypes(node, name) {
5790
+ if (typeof node !== "object" || node === null) return false;
5791
+ if (Array.isArray(node)) {
5792
+ for (const item of node) if (namesInTypes(item, name)) return true;
5793
+ return false;
5794
+ }
5795
+ if (Reflect.get(node, "type") === "TSTypeQuery") {
5796
+ const exprName = Reflect.get(node, "exprName");
5797
+ return typeof exprName === "object" && exprName !== null && Reflect.get(exprName, "name") === name;
5798
+ }
5799
+ for (const key of Object.keys(node)) if (key !== "parent" && namesInTypes(Reflect.get(node, key), name)) return true;
5800
+ return false;
5801
+ }
5802
+ /** The identifiers in an expression that refer to a binding or a global. */
5803
+ function collectReferences(context, node, out) {
5804
+ if (node.type === "Identifier" && context.scopes.references.has(node)) out.push(node);
5805
+ forEachChild(node, (child) => {
5806
+ collectReferences(context, child, out);
5807
+ });
5808
+ }
5809
+ /**
5810
+ * Whether an expression's value can never be a function: a literal, JSX, or
5811
+ * an operator that returns a string, number, or boolean.
5812
+ */
5813
+ function isNeverFunction(node) {
5814
+ switch (node.type) {
5815
+ case "Literal":
5816
+ case "TemplateLiteral":
5817
+ case "JSXElement":
5818
+ case "JSXFragment":
5819
+ case "BinaryExpression":
5820
+ case "UnaryExpression":
5821
+ case "UpdateExpression": return true;
5822
+ case "ParenthesizedExpression": return isNeverFunction(node.expression);
5823
+ case "ConditionalExpression": return isNeverFunction(node.consequent) && isNeverFunction(node.alternate);
5824
+ case "LogicalExpression": return isNeverFunction(node.left) && isNeverFunction(node.right);
5825
+ default: return false;
5826
+ }
5827
+ }
5828
+ function significantChildren(children) {
5829
+ const result = [];
5830
+ for (const child of children) if (!isInsignificant(child)) result.push(child);
5831
+ return result;
5832
+ }
5833
+ /**
5834
+ * The text of an attribute's value as an expression, or `undefined` when the
5835
+ * value is not supported.
5836
+ */
5837
+ function expressionText(context, attribute) {
5838
+ const { value } = attribute;
5839
+ if (value === null) return;
5840
+ switch (value.type) {
5841
+ case "JSXExpressionContainer":
5842
+ if (value.expression.type === "JSXEmptyExpression") return;
5843
+ return joinText`(${context.s.slice(value.expression.start, value.expression.end)})`;
5844
+ case "JSXElement":
5845
+ case "JSXFragment": return context.s.slice(value.start, value.end);
5846
+ default: return;
5847
+ }
5848
+ }
5849
+ //#endregion
5850
+ //#region src/terminate.ts
5851
+ const TERMINATED = /* @__PURE__ */ new Set([
5852
+ "BreakStatement",
5853
+ "ContinueStatement",
5854
+ "DebuggerStatement",
5855
+ "DoWhileStatement",
5856
+ "ExportAllDeclaration",
5857
+ "ExpressionStatement",
5858
+ "ImportDeclaration",
5859
+ "ReturnStatement",
5860
+ "ThrowStatement",
5861
+ "TSTypeAliasDeclaration",
5862
+ "VariableDeclaration"
5863
+ ]);
5864
+ const LOOP_HEADS = /* @__PURE__ */ new Set([
5865
+ "ForStatement",
5866
+ "ForInStatement",
5867
+ "ForOfStatement"
5868
+ ]);
5869
+ function isTerminated(node, context) {
5870
+ if (node.type === "VariableDeclaration") {
5871
+ const parent = context.parents.get(node);
5872
+ return !(parent && LOOP_HEADS.has(parent.type) && Reflect.get(parent, "body") !== node);
5873
+ }
5874
+ if (node.type === "ExportNamedDeclaration") return !node.declaration;
5875
+ if (node.type === "ExportDefaultDeclaration") {
5876
+ const { type } = node.declaration;
5877
+ return type !== "FunctionDeclaration" && type !== "ClassDeclaration";
5878
+ }
5879
+ return TERMINATED.has(node.type);
5880
+ }
5881
+ const TRIVIA = /(?:\s|\/\/[^\n\r\u2028\u2029]*|\/\*[\s\S]*?\*\/)*/y;
5882
+ /** Whether code other than the closing brace of a block follows `position`. */
5883
+ function hasCodeAfter(code, position) {
5884
+ TRIVIA.lastIndex = position;
5885
+ TRIVIA.exec(code);
5886
+ return TRIVIA.lastIndex < code.length && code[TRIVIA.lastIndex] !== "}";
5887
+ }
5888
+ function terminateStatements(context) {
5889
+ const { code, s } = context;
5890
+ let changed = false;
5891
+ const visit = (node) => {
5892
+ if (isTerminated(node, context) && code[node.end - 1] !== ";" && hasCodeAfter(code, node.end)) {
5893
+ s.appendLeft(node.end, ";");
5894
+ changed = true;
5895
+ }
5896
+ forEachChild(node, visit);
5897
+ };
5898
+ visit(context.program);
5899
+ return changed;
5900
+ }
5901
+ //#endregion
4402
5902
  //#region src/compile.ts
4403
5903
  const DEFAULT_BUILT_INS = [
4404
5904
  "For",
@@ -4414,6 +5914,8 @@ const DEFAULT_BUILT_INS = [
4414
5914
  ];
4415
5915
  const DEFAULT_MODULE_SOURCES = ["solid-js", "@solidjs/web"];
4416
5916
  function resolveOptions(options) {
5917
+ const importedContexts = /* @__PURE__ */ new Map();
5918
+ for (const [source, names] of Object.entries(options.importedContexts ?? {})) importedContexts.set(source, new Set(names));
4417
5919
  return {
4418
5920
  builtIns: new Set(options.builtIns ?? DEFAULT_BUILT_INS),
4419
5921
  moduleSources: options.moduleSources ?? DEFAULT_MODULE_SOURCES,
@@ -4421,13 +5923,14 @@ function resolveOptions(options) {
4421
5923
  constantVars: options.constantVars ?? false,
4422
5924
  importedConstants: resolveImportedConstants(options.importedConstants),
4423
5925
  globalConstants: new Map(Object.entries(options.globalConstants ?? {})),
4424
- importedContexts: new Map(Object.entries(options.importedContexts ?? {}).map(([source, names]) => [source, new Set(names)])),
5926
+ importedContexts,
4425
5927
  sharedComponents: new Map(Object.entries(options.sharedComponents ?? {})),
4426
- alwaysInline: options.alwaysInline ?? false
5928
+ alwaysInline: options.alwaysInline ?? false,
5929
+ alwaysInlineComponents: new Set(options.alwaysInlineComponents ?? [])
4427
5930
  };
4428
5931
  }
4429
5932
  function parseCode(code, filename) {
4430
- const program = parse(filename, code);
5933
+ const program = parse$1(filename, code);
4431
5934
  return {
4432
5935
  code,
4433
5936
  program,
@@ -4440,7 +5943,7 @@ function runPass(parsed, filename, options, sourceMap, pass, skips) {
4440
5943
  const context = {
4441
5944
  code,
4442
5945
  filename,
4443
- s: new MagicString(code),
5946
+ s: new Editor(code, sourceMap),
4444
5947
  program: parsed.program,
4445
5948
  parents: parsed.parents,
4446
5949
  scopes: {
@@ -4453,11 +5956,7 @@ function runPass(parsed, filename, options, sourceMap, pass, skips) {
4453
5956
  if (!pass(context)) return;
4454
5957
  return {
4455
5958
  code: context.s.toString(),
4456
- map: sourceMap ? context.s.generateMap({
4457
- source: filename,
4458
- hires: true,
4459
- includeContent: true
4460
- }).toString() : void 0
5959
+ map: sourceMap ? context.s.generateMap(filename) : void 0
4461
5960
  };
4462
5961
  }
4463
5962
  /**
@@ -4487,6 +5986,12 @@ function compile(code, options = {}) {
4487
5986
  if (parsed?.code !== current) parsed = parseCode(current, filename);
4488
5987
  return parsed;
4489
5988
  };
5989
+ const terminated = runPass(parsedCurrent(), filename, resolved, sourceMap, terminateStatements, void 0);
5990
+ if (terminated) {
5991
+ current = terminated.code;
5992
+ if (terminated.map !== void 0) maps.push(terminated.map);
5993
+ }
5994
+ const start = current;
4490
5995
  const maxPasses = options.maxPasses ?? 10;
4491
5996
  let skipped;
4492
5997
  for (let round = 0; round < maxPasses; round += 1) {
@@ -4502,7 +6007,25 @@ function compile(code, options = {}) {
4502
6007
  }
4503
6008
  if (!changed) break;
4504
6009
  }
6010
+ if (options.conditionals ?? true) for (let round = 0; round < maxPasses; round += 1) {
6011
+ const result = runPass(parsedCurrent(), filename, resolved, sourceMap, lowerConditionals, void 0);
6012
+ if (!result) break;
6013
+ current = result.code;
6014
+ if (result.map !== void 0) maps.push(result.map);
6015
+ }
6016
+ if (current !== start) {
6017
+ const result = runPass(parsedCurrent(), filename, resolved, sourceMap, repairNesting, void 0);
6018
+ if (result) {
6019
+ current = result.code;
6020
+ if (result.map !== void 0) maps.push(result.map);
6021
+ }
6022
+ }
4505
6023
  const report = skipped ? { skipped } : {};
6024
+ if (current === start) return {
6025
+ code,
6026
+ map: null,
6027
+ ...report
6028
+ };
4506
6029
  if (maps.length === 0) return {
4507
6030
  code: current,
4508
6031
  map: null,
@@ -4521,7 +6044,7 @@ function compile(code, options = {}) {
4521
6044
  * Only `filename`, `importedConstants`, and `globalConstants` of the options are used.
4522
6045
  */
4523
6046
  function readModuleConstants(code, options = {}) {
4524
- const program = parse(options.filename ?? "input.jsx", code);
6047
+ const program = parse$1(options.filename ?? "input.jsx", code);
4525
6048
  const scopes = analyzeScopes(program);
4526
6049
  return {
4527
6050
  imports: namedImportSources(program, scopes),
@@ -4529,6 +6052,6 @@ function readModuleConstants(code, options = {}) {
4529
6052
  };
4530
6053
  }
4531
6054
  //#endregion
4532
- export { lookup as a, forEachChild as c, unwrap as d, analyzeScopes as i, isIntrinsicTag as l, readModuleConstants as n, scopeAt as o, CONTEXT_SAFE_PRIMITIVES as r, collectParents as s, compile as t, parse as u };
6055
+ export { analyzeScopes as a, collectParents as c, parse$1 as d, unwrap as f, runtimeImportSources as i, forEachChild as l, readModuleConstants as n, lookup as o, CONTEXT_SAFE_PRIMITIVES as r, scopeAt as s, compile as t, isIntrinsicTag as u };
4533
6056
 
4534
- //# sourceMappingURL=compile-BpoiBa6b.mjs.map
6057
+ //# sourceMappingURL=compile-Cvjy2e11.mjs.map