@lucidkiln/core 1.7.1 → 1.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,5 +1,5 @@
1
- import { $ as compare, $t as escapeUrl, A as consume, At as additionsIn, B as loadTemplate, Bt as fillScope, C as getAttr, Ct as contentSets, D as after, Dt as passesFrom, E as addSlotFlags, Et as passesAhead, F as fail, Ft as RenderState, G as renderTemplate, Gt as sectionCopy, H as locating, Ht as childScope, I as hold, It as Run, J as unhold, Jt as suggest, K as silence, Kt as sectionScope, L as holdData, Lt as blockScope, M as embed, Mt as closeOutlets, N as embedKeyed, Nt as recordAddition, O as all, Ot as runAhead, P as embedScope, Pt as takeOutput, Q as MISSING, Qt as escapeHtml, R as importsFor, Rt as emptyOut, S as toTime, St as atFront, T as readableNames, Tt as mayRunAhead, U as markCaller, Ut as lookup$1, V as locate, Vt as startCapture, W as passData, Wt as ownerOf, X as write, Xt as isSafe, Y as withCaller, Yt as Markup, Z as FORMATTERS, Zt as safe, _ as markupText, _t as unwrap, a as operatorFunction, an as KilnSyntaxError, at as isHashLike, b as toPieces, bt as expose, c as checkDepth, ct as mapKeys, d as functionArgument, dt as templateFunctions, en as escapeWith, et as describeType, f as insertedPiece, ft as toNumber, g as mapContents, gt as typeName, h as listOf$1, ht as truthy, i as contains, in as KilnRenderError, it as isEmpty, j as consumeAt, jt as checkLate, k as checkLength, kt as runSequence, l as entriesOf, lt as matchesType, m as isHtmlStrategy, mt as toStringArgument, n as builtinFunctions, nn as resolveTemplateName, nt as equals, o as rangeOperator, on as createDiagnostic, ot as isPlainObject, p as integerArgument, pt as toStr, q as step, qt as variableNames, r as builtinTests, rn as KilnIssue, rt as hashKeys, s as Kept, sn as issue, st as literalOptions, t as Source, tn as TEMPLATE_EXTENSION, tt as describeValue, u as fromPieces, ut as setOwn, v as readProperty, vt as valueLabel, w as getMethod, wt as isRoot, x as toPlainData, xt as lookup, y as scanHtml, yt as BLOCKED_NAMES, z as isPromise, zt as endCapture } from "./source-DxHQeBEo.js";
2
- import { a as ESCAPE_STRATEGIES, i as DEFAULT_SLOT, r as scanParts, t as parse } from "./parser-BZpRlGWi.js";
1
+ import { $ as unhold, $t as variableNames, A as checkLength, An as VOID, At as isRoot, B as isPromise, Bt as takeOutput, C as toTime, Cn as ONLY_CHILDREN, Ct as unwrap, D as addSlotFlags, Dn as ROLES, Dt as lookup, E as readableNames, En as REQUIRED_PARENTS, Et as expose, F as embedScope, Fn as KilnSyntaxError, Ft as runSequence, G as markCaller, Gt as endCapture, H as loadTemplate, Ht as Run, I as fail, In as createDiagnostic, It as additionsIn, J as renderTemplate, Jt as childScope, K as moreSteps, Kt as fillScope, L as hold, Ln as issue, Lt as checkLate, M as consumeAt, Mn as resolveTemplateName, Mt as passesAhead, N as embed, Nn as KilnIssue, Nt as passesFrom, O as after, On as SPECIAL, Ot as atFront, P as embedKeyed, Pn as KilnRenderError, Pt as runAhead, Q as stepError, Qt as sectionScope, R as holdData, Rt as closeOutlets, S as toPlainData, Sn as OBSOLETE_ATTRIBUTES, St as typeName, T as getMethod, Tn as RAW_TEXT, Tt as BLOCKED_NAMES, U as locate, Ut as blockScope, V as lendSteps, Vt as RenderState, W as locating, Wt as emptyOut, X as silence, Xt as ownerOf, Y as returnSteps, Yt as lookup$1, Z as step, Zt as sectionCopy, _ as mapContents, _n as IMPLICIT_ROLES, _t as templateFunctions, a as operatorFunction, an as escapeUrl, at as compare, b as scanHtml, bn as METADATA, bt as toStringArgument, c as checkDepth, cn as ARIA_ATTRIBUTES, ct as equals, d as functionArgument, dn as BOOLEAN_ATTRIBUTES, dt as isHashLike, en as suggest, et as withCaller, f as insertedPiece, fn as BUTTON_SCOPE, ft as isPlainObject, g as listOf$1, gn as HEADINGS, gt as setOwn, h as keyName, hn as FOREIGN, ht as matchesType, i as contains, in as escapeHtml, it as MISSING, j as consume, jn as TEMPLATE_EXTENSION, jt as mayRunAhead, k as all, kn as TRANSPARENT, kt as contentSets, l as entriesOf, ln as ATTRIBUTE_VALUES, lt as hashKeys, m as isHtmlStrategy, mn as FLOW, mt as mapKeys, n as builtinFunctions, nn as isSafe, nt as FORMATTERS, o as rangeOperator, on as escapeWith, ot as describeType, p as integerArgument, pn as FIRST_CHILD, pt as literalOptions, q as passData, qt as startCapture, r as builtinTests, rn as safe, rt as MAX_DATA_DEPTH, s as Kept, sn as ABSTRACT_ROLES, st as describeValue, t as Source, tn as Markup, tt as write, u as fromPieces, un as BLOCK, ut as isEmpty, v as markupText, vn as INPUT_ROLES, vt as toNumber, w as getAttr, wn as PHRASING_ONLY, wt as valueLabel, x as toPieces, xn as OBSOLETE, xt as truthy, y as readProperty, yn as MAIN_PARENTS, yt as toStr, z as importsFor, zt as recordAddition } from "./source-DcWmJzQW.js";
2
+ import { a as DEFAULT_SLOT, i as scanParts, o as ESCAPE_STRATEGIES, t as parse } from "./parser-CRWl5Lka.js";
3
3
  //#region src/analyzer.ts
4
4
  const MAX_DEPTH$1 = 1e3;
5
5
  /** The statement lists nested inside a statement. */
@@ -55,21 +55,23 @@ const analyzeTemplate = (template, globals, reads) => {
55
55
  end: source.position(span.end)
56
56
  });
57
57
  };
58
- const scopes = [/* @__PURE__ */ new Set()];
58
+ const root = /* @__PURE__ */ new Set();
59
+ const scopes = [root];
59
60
  const declared = (name) => {
60
61
  for (let i = scopes.length - 1; i >= 0; i--) {
61
62
  const scope = scopes[i];
62
63
  if (scope === null) break;
63
- if (scope?.has(name)) return true;
64
+ if (scope === "any" || scope?.has(name)) return true;
64
65
  }
65
66
  return name in globals;
66
67
  };
67
68
  const declare = (name) => {
68
- if (!declared(name)) scopes[scopes.length - 1]?.add(name);
69
+ const scope = scopes[scopes.length - 1];
70
+ if (!declared(name) && scope instanceof Set) scope.add(name);
69
71
  };
70
72
  const withScope = (names, work, isolated = false) => {
71
73
  if (isolated) scopes.push(null);
72
- scopes.push(new Set(names));
74
+ scopes.push(names === "any" ? names : new Set(names));
73
75
  work();
74
76
  scopes.pop();
75
77
  if (isolated) scopes.pop();
@@ -100,14 +102,20 @@ const analyzeTemplate = (template, globals, reads) => {
100
102
  }
101
103
  };
102
104
  const guarded = (node) => {
103
- if (node.type === "Name") read(node.name, node.span, true);
104
- else if (node.type === "Member") {
105
- guarded(node.object);
106
- if (node.property.type !== "Literal") expression(node.property);
107
- } else if (node.type === "OptionalChain") guarded(node.expression);
108
- else expression(node);
105
+ if (depth >= MAX_DEPTH$1) return;
106
+ depth++;
107
+ try {
108
+ if (node.type === "Name") read(node.name, node.span, true);
109
+ else if (node.type === "Member") {
110
+ guarded(node.object);
111
+ if (node.property.type !== "Literal") expression(node.property);
112
+ } else if (node.type === "OptionalChain") guarded(node.expression);
113
+ else expression(node);
114
+ } finally {
115
+ depth--;
116
+ }
109
117
  };
110
- if (template.slotNames.length > 0 || template.parent) scopes[0]?.add("slots");
118
+ if (template.slotNames.length > 0 || template.parent) root.add("slots");
111
119
  let inExport = false;
112
120
  const read = (name, span, isGuarded) => {
113
121
  if (inExport || declared(name) || importAliases.has(name) || importedNames.has(name)) return;
@@ -281,8 +289,13 @@ const analyzeTemplate = (template, globals, reads) => {
281
289
  case "FromImport": return;
282
290
  case "With": {
283
291
  expression(node.value);
284
- const names = node.value.type === "Hash" ? node.value.entries.flatMap((entry) => entry.type === "Property" && entry.key.type === "Literal" && typeof entry.key.value === "string" ? [entry.key.value] : []) : [];
285
- withScope(names, () => statements(node.body));
292
+ const names = [];
293
+ for (const entry of node.value.type === "Hash" ? node.value.entries : []) {
294
+ if (entry.type !== "Property" || entry.key.type !== "Literal" || typeof entry.key.value !== "string") break;
295
+ names.push(entry.key.value);
296
+ }
297
+ const known = node.value.type === "Hash" && names.length === node.value.entries.length;
298
+ withScope(known ? names : "any", () => statements(node.body));
286
299
  return;
287
300
  }
288
301
  case "Add":
@@ -788,16 +801,26 @@ const capitalizePieces = (pieces) => {
788
801
  };
789
802
  /** Letters, marks, digits and apostrophes, so neither a combining accent nor the apostrophe in "o'neil" starts a word. */
790
803
  const WORD = /[\p{L}\p{M}\p{N}'’]+/gu;
791
- const STARTS_WITH_LETTER = /^\p{L}/u;
804
+ /** A word that starts with a letter, after any opening quotes, as in "'quick'". */
805
+ const STARTS_WITH_LETTER = /^['’]*\p{L}/u;
792
806
  const ENDS_IN_WORD = /[\p{L}\p{M}\p{N}'’]$/u;
793
807
  /** Starts each word with an upper-case letter and lower-cases the rest. The first word only when `boundary` is true. */
794
- const titleText = (text, boundary) => text.toLowerCase().replace(WORD, (word, offset) => (offset > 0 || boundary) && STARTS_WITH_LETTER.test(word) ? upperFirst(word) : word);
795
- /** `titleText` over pieces. Tags don't end a word, but kept entities do. */
808
+ const titleText = (text, boundary) => text.toLowerCase().replace(WORD, (word, offset) => {
809
+ if (offset === 0 && !boundary || !STARTS_WITH_LETTER.test(word)) return word;
810
+ let start = 0;
811
+ while (word[start] === "'" || word[start] === "’") start++;
812
+ return start === 0 ? upperFirst(word) : word.slice(0, start) + upperFirst(word.slice(start));
813
+ });
814
+ /**
815
+ * `titleText` over pieces. Inline tags, including unknown and custom elements, don't end a word, but block tags such
816
+ * as `<p>` and `<td>`, `<br>` and kept entities do.
817
+ */
796
818
  const titlePieces = (pieces) => {
797
819
  let boundary = true;
798
820
  return pieces.map((piece) => {
799
821
  if (typeof piece !== "string") {
800
- if (!piece.html.startsWith("<")) boundary = true;
822
+ const name = TAG_NAME.exec(piece.html)?.[2]?.toLowerCase();
823
+ if (!piece.html.startsWith("<") || name !== void 0 && (BLOCK.has(name) || name === "br")) boundary = true;
801
824
  return piece;
802
825
  }
803
826
  const text = titleText(piece, boundary);
@@ -874,6 +897,16 @@ const replacePairs = (run, text, pairs) => {
874
897
  if (start < text.length) pieces.push(text.slice(start));
875
898
  return pieces;
876
899
  };
900
+ /** `replace`'s hash of searches and replacements as pairs. Keys `keyName` can't name are left out. */
901
+ const replacementPairs = (run, search, insert) => {
902
+ const { values, keys } = entriesOf(run, search, "replace");
903
+ const pairs = [];
904
+ keys.forEach((key, index) => {
905
+ const name = keyName(key);
906
+ if (name !== null) pairs.push([name, insert(values[index])]);
907
+ });
908
+ return pairs;
909
+ };
877
910
  /** Elements that have no closing tag. */
878
911
  const VOID_ELEMENTS = /* @__PURE__ */ new Set([
879
912
  "area",
@@ -952,8 +985,9 @@ const queryString = (run, hash) => {
952
985
  seen.add(value);
953
986
  for (let i = 0; i < values.length; i++) {
954
987
  const item = values[i];
955
- if (item === null || item === void 0) continue;
956
- const key = prefix === null ? String(keys[i]) : `${prefix}[${String(keys[i])}]`;
988
+ const name = keyName(keys[i]);
989
+ if (item === null || item === void 0 || name === null) continue;
990
+ const key = prefix === null ? name : `${prefix}[${name}]`;
957
991
  if (Array.isArray(item) || isPlainObject(item) || item instanceof Map || item instanceof Set) {
958
992
  if (seen.has(item)) issue("invalid-argument", "\"urlEncode\" cannot encode a value that contains itself");
959
993
  add(item, key, depth + 1);
@@ -974,6 +1008,11 @@ const queryString = (run, hash) => {
974
1008
  const formatterCache = /* @__PURE__ */ new Map();
975
1009
  /** Longer cache keys aren't cached, so templates can't fill the cache with large strings. */
976
1010
  const MAX_FORMATTER_KEY = 512;
1011
+ /**
1012
+ * Steps charged for building a formatter that isn't cached. Building one takes about as long as 100 steps of other
1013
+ * work, so a template can't make many by varying the locale or options.
1014
+ */
1015
+ const FORMATTER_STEPS = 100;
977
1016
  const NUMBER_OPTIONS = /* @__PURE__ */ new Set([
978
1017
  "localeMatcher",
979
1018
  "style",
@@ -1073,6 +1112,7 @@ const cachedFormatter = (kind, run, options, names, defaults, create) => {
1073
1112
  const cacheable = key.length <= MAX_FORMATTER_KEY;
1074
1113
  let formatter = cacheable ? formatterCache.get(key) : void 0;
1075
1114
  if (!formatter) {
1115
+ consume(run, FORMATTER_STEPS);
1076
1116
  const settings = { ...base };
1077
1117
  for (const name of hashKeys(given)) if (name !== "locale") setOwn(settings, name, unwrap(given[name]));
1078
1118
  formatter = create(locale, settings);
@@ -1088,25 +1128,34 @@ const cachedFormatter = (kind, run, options, names, defaults, create) => {
1088
1128
  };
1089
1129
  return formatter;
1090
1130
  };
1091
- /** Calls a template callback for each item, then gathers the results, waiting only if one was a promise. */
1131
+ /**
1132
+ * Calls a template callback for each item, then gathers the results, waiting only if the callback can wait and one was
1133
+ * a promise. A promise from a callback that can't wait is from your data.
1134
+ */
1092
1135
  const mapEntries = (run, value, callback, what, gather) => {
1093
- const fn = functionArgument(callback, what);
1136
+ const { call, waits } = functionArgument(callback, what);
1094
1137
  const { values, keys, isHash } = entriesOf(run, value, what);
1095
1138
  const results = [];
1096
1139
  try {
1097
- for (let i = 0; i < values.length; i++) results.push(fn(values[i], keys[i]));
1140
+ for (let i = 0; i < values.length; i++) results.push(call(values[i], keys[i]));
1098
1141
  } catch (error) {
1099
1142
  for (const result of results) silence(result);
1100
1143
  throw error;
1101
1144
  }
1102
- if (results.some(isPromise)) return all(results).then((resolved) => hold(gather(resolved, values, keys, isHash)));
1145
+ if (waits && results.some(isPromise)) return all(results).then((resolved) => hold(gather(resolved, values, keys, isHash)));
1103
1146
  return gather(results, values, keys, isHash);
1104
1147
  };
1105
- const buildCollection = (isHash, keys, items) => {
1148
+ /**
1149
+ * The result of `map` or `filter`: a list, or a hash of the keys given. A `Map`, such as `sort` returns, gives an
1150
+ * ordered hash, so keys that look like numbers keep their place.
1151
+ */
1152
+ const buildCollection = (source, isHash, keys, items) => {
1106
1153
  if (!isHash) return items;
1154
+ if (source instanceof Map) return orderedHash(keys, items);
1107
1155
  const result = {};
1108
1156
  items.forEach((item, index) => {
1109
- setOwn(result, String(keys[index]), item);
1157
+ const name = keyName(keys[index]);
1158
+ if (name !== null) setOwn(result, name, item);
1110
1159
  });
1111
1160
  return result;
1112
1161
  };
@@ -1134,14 +1183,15 @@ const stripTags = (html) => {
1134
1183
  /** `sort`'s order: natural order without `by`, by a key with a one-parameter arrow, or with a comparator. */
1135
1184
  const sortBy = (items, read, by) => {
1136
1185
  if (by === void 0 || by === null) return items.sort((a, b) => compare(read(a), read(b)));
1137
- const fn = functionArgument(by, "sort");
1138
- if (fn.length >= 2) return items.sort((a, b) => {
1139
- const result = syncResult(fn(read(a), read(b)), "sort");
1140
- return typeof result === "number" ? result : issue("type-error", "\"sort\" comparator must return a number");
1186
+ const { call, waits } = functionArgument(by, "sort");
1187
+ const result = waits ? (value) => syncResult(value, "sort") : (value) => value;
1188
+ if (call.length >= 2) return items.sort((a, b) => {
1189
+ const order = result(call(read(a), read(b)));
1190
+ return typeof order === "number" ? order : issue("type-error", "\"sort\" comparator must return a number");
1141
1191
  });
1142
1192
  const keyed = items.map((item) => ({
1143
1193
  item,
1144
- key: syncResult(fn(read(item)), "sort")
1194
+ key: result(call(read(item)))
1145
1195
  }));
1146
1196
  keyed.sort((a, b) => compare(a.key, b.key));
1147
1197
  return keyed.map((entry) => entry.item);
@@ -1167,8 +1217,18 @@ const sortStrings = (items) => {
1167
1217
  }
1168
1218
  return items;
1169
1219
  };
1170
- /** A hash of keys and values in the order given. A `Map`, so keys that look like numbers keep their place too. */
1171
- const orderedHash = (keys, values) => new Map(keys.map((key, index) => [String(key), values[index]]));
1220
+ /**
1221
+ * A hash of keys and values in the order given. A `Map`, so keys that look like numbers keep their place too. Keys
1222
+ * `keyName` can't name are left out.
1223
+ */
1224
+ const orderedHash = (keys, values) => {
1225
+ const hash = /* @__PURE__ */ new Map();
1226
+ keys.forEach((key, index) => {
1227
+ const name = keyName(key);
1228
+ if (name !== null) hash.set(name, values[index]);
1229
+ });
1230
+ return hash;
1231
+ };
1172
1232
  const toUpper = (text) => text.toUpperCase();
1173
1233
  const toLower = (text) => text.toLowerCase();
1174
1234
  const upperPieces = (pieces) => mapText(pieces, toUpper);
@@ -1195,20 +1255,11 @@ const builtinFilters = {
1195
1255
  const isPairs = isPlainObject(search) || search instanceof Map;
1196
1256
  if (value instanceof Markup) {
1197
1257
  const { strategy } = value;
1198
- const pairs = [];
1199
- if (isPairs) {
1200
- const { values, keys } = entriesOf(run, search, "replace");
1201
- keys.forEach((key, index) => {
1202
- pairs.push([String(key), insertedPiece(values[index], strategy, "\"replace\"")]);
1203
- });
1204
- } else pairs.push([search instanceof Markup ? markupText(search) : toStringArgument(search, "\"replace\""), insertedPiece(replacement, strategy, "\"replace\"")]);
1258
+ const pairs = isPairs ? replacementPairs(run, search, (item) => insertedPiece(item, strategy, "\"replace\"")) : [[search instanceof Markup ? markupText(search) : toStringArgument(search, "\"replace\""), insertedPiece(replacement, strategy, "\"replace\"")]];
1205
1259
  return changeMarkup(run, value, (pieces) => pieces.flatMap((piece) => typeof piece === "string" ? replacePairs(run, piece, pairs) : [piece]));
1206
1260
  }
1207
1261
  const text = toStringArgument(value, "\"replace\"");
1208
- if (isPairs) {
1209
- const { values, keys } = entriesOf(run, search, "replace");
1210
- return joinText(replacePairs(run, text, keys.map((key, index) => [String(key), toStr(values[index])])));
1211
- }
1262
+ if (isPairs) return joinText(replacePairs(run, text, replacementPairs(run, search, toStr)));
1212
1263
  const needle = toStringArgument(search, "\"replace\"");
1213
1264
  if (needle === "") return text;
1214
1265
  const parts = text.split(needle);
@@ -1238,7 +1289,7 @@ const builtinFilters = {
1238
1289
  }, ["length", "ellipsis"]),
1239
1290
  stripTags: define((run, value) => {
1240
1291
  if (!(value instanceof Markup)) return stripTags(toStringArgument(value, "\"stripTags\""));
1241
- return isHtmlStrategy(value.strategy) ? new Markup(stripTags(value.value), value.strategy) : fromPieces(run, [stripTags(markupText(value))], value.strategy);
1292
+ return isHtmlStrategy(value.strategy) ? new Markup(stripTags(value.value).replaceAll("<", "&lt;"), value.strategy) : fromPieces(run, [stripTags(markupText(value))], value.strategy);
1242
1293
  }),
1243
1294
  nl2br: define((run, value) => {
1244
1295
  const html = value instanceof Markup ? value.value : escapeHtml(checkLength(run, toStr(value)));
@@ -1258,7 +1309,7 @@ const builtinFilters = {
1258
1309
  }),
1259
1310
  json: define((run, value, indent) => {
1260
1311
  if (indent !== void 0 && indent !== null && typeof indent !== "number" && typeof indent !== "string") return issue("type-error", "\"json\" indent must be a number or string");
1261
- const width = typeof indent === "number" ? Math.max(0, Math.min(10, Math.floor(indent))) : typeof indent === "string" ? Math.min(10, indent.length) : 0;
1312
+ const width = typeof indent === "number" ? Math.max(0, Math.min(10, Math.floor(indent))) || 0 : typeof indent === "string" ? Math.min(10, indent.length) : 0;
1262
1313
  const data = toPlainData(value, () => issue("invalid-argument", "\"json\" cannot serialise a value that contains itself"), {
1263
1314
  what: "json",
1264
1315
  charge: (count) => consume(run, count),
@@ -1351,15 +1402,20 @@ const builtinFilters = {
1351
1402
  for (const item of all) for (const entry of item) result.push(entry);
1352
1403
  return result;
1353
1404
  }
1354
- if (all.every((item) => isPlainObject(item) || item instanceof Map)) {
1405
+ if (all.every(isHashLike)) {
1406
+ const ordered = all.some((item) => item instanceof Map);
1355
1407
  const result = {};
1408
+ const map = /* @__PURE__ */ new Map();
1356
1409
  for (const item of all) {
1357
1410
  const { values, keys } = entriesOf(run, item, "merge");
1358
1411
  keys.forEach((key, index) => {
1359
- setOwn(result, String(key), values[index]);
1412
+ const name = keyName(key);
1413
+ if (name === null) return;
1414
+ if (ordered) map.set(name, values[index]);
1415
+ else setOwn(result, name, values[index]);
1360
1416
  });
1361
1417
  }
1362
- return result;
1418
+ return ordered ? map : result;
1363
1419
  }
1364
1420
  return issue("type-error", "\"merge\" needs all arrays or all hashes, not a mix");
1365
1421
  }),
@@ -1388,7 +1444,7 @@ const builtinFilters = {
1388
1444
  if ((by === void 0 || by === null) && allStrings(items)) return sortStrings(items);
1389
1445
  return sortBy(items, (item) => item, by);
1390
1446
  }, ["by"]),
1391
- map: define((run, value, callback) => mapEntries(run, value, callback, "map", (results, _values, keys, isHash) => buildCollection(isHash, keys, results)), ["callback"]),
1447
+ map: define((run, value, callback) => mapEntries(run, value, callback, "map", (results, _values, keys, isHash) => buildCollection(value, isHash, keys, results)), ["callback"]),
1392
1448
  filter: define((run, value, callback) => mapEntries(run, value, callback, "filter", (results, values, keys, isHash) => {
1393
1449
  const keptKeys = [];
1394
1450
  const kept = [];
@@ -1398,34 +1454,37 @@ const builtinFilters = {
1398
1454
  keptKeys.push(keys[index]);
1399
1455
  }
1400
1456
  });
1401
- return buildCollection(isHash, keptKeys, kept);
1457
+ return buildCollection(value, isHash, keptKeys, kept);
1402
1458
  }), ["callback"]),
1403
1459
  reduce: define((run, value, callback, initial = null) => {
1404
- const fn = functionArgument(callback, "reduce");
1460
+ const { call, waits } = functionArgument(callback, "reduce");
1405
1461
  const { values, keys } = entriesOf(run, value, "reduce");
1406
- const from = (index, carry) => {
1462
+ const from = (index, carry, waited) => {
1407
1463
  let current = carry;
1408
1464
  for (let i = index; i < values.length; i++) {
1409
- const result = fn(current, values[i], keys[i]);
1410
- if (isPromise(result)) return result.then((resolved) => hold(from(i + 1, unhold(resolved))));
1465
+ const result = call(current, values[i], keys[i]);
1466
+ if (waits && isPromise(result)) return result.then((resolved) => from(i + 1, unhold(resolved), true));
1411
1467
  current = result;
1412
1468
  }
1413
- return current;
1469
+ return waited ? holdData(current) : waits ? passData(current) : current;
1414
1470
  };
1415
- return from(0, initial);
1471
+ return from(0, initial, false);
1416
1472
  }, ["callback", "initial"]),
1417
1473
  find: define((run, value, callback) => {
1418
- const fn = functionArgument(callback, "find");
1474
+ const { call, waits } = functionArgument(callback, "find");
1419
1475
  const { values, keys } = entriesOf(run, value, "find");
1420
- const from = (index) => {
1476
+ const from = (index, waited) => {
1421
1477
  for (let i = index; i < values.length; i++) {
1422
- const result = fn(values[i], keys[i]);
1423
- if (isPromise(result)) return result.then((resolved) => hold(truthy(unhold(resolved)) ? values[i] ?? null : from(i + 1)));
1424
- if (truthy(result)) return values[i] ?? null;
1478
+ const result = call(values[i], keys[i]);
1479
+ if (waits && isPromise(result)) return result.then((resolved) => truthy(unhold(resolved)) ? holdData(values[i] ?? null) : from(i + 1, true));
1480
+ if (truthy(result)) {
1481
+ const found = values[i] ?? null;
1482
+ return waited ? holdData(found) : waits ? passData(found) : found;
1483
+ }
1425
1484
  }
1426
1485
  return null;
1427
1486
  };
1428
- return from(0);
1487
+ return from(0, false);
1429
1488
  }, ["callback"]),
1430
1489
  column: define((run, value, name) => {
1431
1490
  const key = unwrap(name);
@@ -1531,6 +1590,17 @@ const checkReferences = async (env, template) => {
1531
1590
  diagnostics.push(createDiagnostic(template.source, code, message, span, severity));
1532
1591
  };
1533
1592
  const ownProps = propsOf(template);
1593
+ /** The resolved name of a template written as a plain string. Reports a name rendering would reject. */
1594
+ const named = (expression) => {
1595
+ if (expression.type !== "Literal" || typeof expression.value !== "string") return null;
1596
+ try {
1597
+ return resolveTemplateName(expression.value, template.name);
1598
+ } catch (error) {
1599
+ if (!(error instanceof KilnIssue)) throw error;
1600
+ report(error.code, error.message, expression.span);
1601
+ return null;
1602
+ }
1603
+ };
1534
1604
  /** Loads a named template, reporting it when it doesn't exist. */
1535
1605
  const use = async (name, span, optional = false) => {
1536
1606
  const used = await env.load(name);
@@ -1538,7 +1608,7 @@ const checkReferences = async (env, template) => {
1538
1608
  return used;
1539
1609
  };
1540
1610
  const call = async (node) => {
1541
- const name = literalName(node.template, template.name);
1611
+ const name = named(node.template);
1542
1612
  if (!name) return;
1543
1613
  const used = await use(name, node.template.span, node.type === "Include" && node.ignoreMissing);
1544
1614
  if (!used || used.hasErrors || !env.strict) return;
@@ -1562,7 +1632,7 @@ const checkReferences = async (env, template) => {
1562
1632
  }
1563
1633
  };
1564
1634
  const layouts = async (node) => {
1565
- let name = literalName(node.template, template.name);
1635
+ let name = named(node.template);
1566
1636
  if (!name) return;
1567
1637
  let layout = await use(name, node.template.span);
1568
1638
  if (!ownProps || ownProps.rest !== null || !env.strict) return;
@@ -1668,12 +1738,13 @@ const unpackSaved = (value) => {
1668
1738
  * await writeFile("build/islands.json", JSON.stringify(islands.manifest));
1669
1739
  * ```
1670
1740
  */
1671
- const deferIslands = ({ url, script = true }) => {
1741
+ const deferIslands = ({ url, script = true, query = false }) => {
1672
1742
  if (typeof url !== "string") throw new TypeError("deferIslands needs a url");
1673
1743
  return {
1674
1744
  mode: "defer",
1675
1745
  url,
1676
1746
  script,
1747
+ query,
1677
1748
  manifest: {}
1678
1749
  };
1679
1750
  };
@@ -1694,12 +1765,13 @@ const streamIslands = ({ script = true } = {}) => ({
1694
1765
  * inline scripts, with `script: false`.
1695
1766
  *
1696
1767
  * - A deferred island's element fetches its `src`, and replaces itself with the response when it succeeds and is HTML.
1768
+ * With a `query` attribute, the page's query string follows the `src`'s own.
1697
1769
  * - A streamed island's HTML arrives in a `<template>`, followed by `<kiln-island fill="n">`, which moves it in place of
1698
1770
  * `<kiln-island stream="n">` once the template is parsed.
1699
1771
  *
1700
1772
  * Otherwise the fallback stays. Kept short and plain, since it is written into pages.
1701
1773
  */
1702
- const islandScript = "customElements.get(\"kiln-island\")||customElements.define(\"kiln-island\",class extends HTMLElement{connectedCallback(){if(this.k)return;this.k=1;this.style.display=\"contents\";const p=h=>document.createRange().createContextualFragment(h),f=this.getAttribute(\"fill\"),s=this.getAttribute(\"src\");if(f){const t=this.previousElementSibling,e=document.querySelector(`kiln-island[stream=\"${f}\"]`);if(e&&t&&t.localName==\"template\")e.replaceWith(p(t.innerHTML)),t.remove();this.remove()}else if(s)fetch(s).then(r=>r.ok&&/^text\\/html/.test(r.headers.get(\"content-type\"))?r.text():null).then(h=>{if(h!=null)this.replaceWith(p(h))},()=>{})}});";
1774
+ const islandScript = "customElements.get(\"kiln-island\")||customElements.define(\"kiln-island\",class extends HTMLElement{connectedCallback(){if(this.k)return;this.k=1;this.style.display=\"contents\";const p=h=>document.createRange().createContextualFragment(h),f=this.getAttribute(\"fill\"),s=this.getAttribute(\"src\"),q=this.hasAttribute(\"query\")?location.search.slice(1):\"\";if(f){const t=this.previousElementSibling,e=document.querySelector(`kiln-island[stream=\"${f}\"]`);if(e&&t&&t.localName==\"template\")e.replaceWith(p(t.innerHTML)),t.remove();this.remove()}else if(s)fetch(q?s+(s.includes(\"?\")?\"&\":\"?\")+q:s).then(r=>r.ok&&/^text\\/html/.test(r.headers.get(\"content-type\"))?r.text():null).then(h=>{if(h!=null)this.replaceWith(p(h))},()=>{})}});";
1703
1775
  /**
1704
1776
  * Copies an island's props as JSON values, or fails naming the first value that isn't one. Hashes may be maps, and
1705
1777
  * become plain objects.
@@ -1708,18 +1780,18 @@ const islandProps = (run, span, value) => {
1708
1780
  const seen = /* @__PURE__ */ new Set();
1709
1781
  const invalid = (path, problem) => fail(run, span, "type-error", `"island" props must be JSON values: null, booleans, numbers, strings, lists and hashes, but ${path === "" ? "they are" : `"${path}" is`} ${problem}`);
1710
1782
  const charge = (count) => consumeAt(run, span, count);
1711
- const copyHash = (hash, path) => {
1783
+ const copyHash = (hash, path, depth) => {
1712
1784
  const result = {};
1713
1785
  const entries = hash instanceof Map ? [...hash] : Object.entries(hash);
1714
1786
  charge(entries.length);
1715
1787
  for (const [key, item] of entries) {
1716
1788
  if (typeof key !== "string") throw invalid(path, "a hash with a key that isn't a string");
1717
1789
  if (BLOCKED_NAMES.has(key)) continue;
1718
- result[key] = copy(item, path === "" ? key : `${path}.${key}`);
1790
+ result[key] = copy(item, path === "" ? key : `${path}.${key}`, depth + 1);
1719
1791
  }
1720
1792
  return result;
1721
1793
  };
1722
- const copy = (item, path) => {
1794
+ const copy = (item, path, depth) => {
1723
1795
  if (item === null || item === void 0) return null;
1724
1796
  if (typeof item === "string" || typeof item === "boolean") return item;
1725
1797
  if (typeof item === "number") {
@@ -1729,15 +1801,16 @@ const islandProps = (run, span, value) => {
1729
1801
  if (item instanceof Markup) throw invalid(path, "markup. Pass the data, and build the markup in the island");
1730
1802
  if (!Array.isArray(item) && !(item instanceof Map) && !isPlainObject(item)) throw invalid(path, `a ${typeName(item)}`);
1731
1803
  if (seen.has(item)) throw invalid(path, "a value that contains itself");
1804
+ if (depth > 1e3) throw fail(run, span, "too-deep", `"island" props cannot be nested more than ${MAX_DATA_DEPTH} levels deep`);
1732
1805
  seen.add(item);
1733
1806
  if (Array.isArray(item)) charge(item.length);
1734
- const result = Array.isArray(item) ? item.map((entry, index) => copy(entry, `${path}[${index}]`)) : copyHash(item, path);
1807
+ const result = Array.isArray(item) ? item.map((entry, index) => copy(entry, `${path}[${index}]`, depth + 1)) : copyHash(item, path, depth);
1735
1808
  seen.delete(item);
1736
1809
  return result;
1737
1810
  };
1738
1811
  if (value === null || value === void 0) return {};
1739
1812
  if (!(value instanceof Map) && !isPlainObject(value)) throw invalid("", `a ${typeName(value)}, not a hash`);
1740
- return copyHash(value, "");
1813
+ return copyHash(value, "", 1);
1741
1814
  };
1742
1815
  /** A 64-bit hash of `text` as 16 hex digits: two 32-bit multiply-xor lanes, mixed together at the end. */
1743
1816
  const hashId = (text) => {
@@ -1795,23 +1868,20 @@ const recordIsland = (run, span, islands, template, props) => {
1795
1868
  const streamIsland = (run, span, template, props, n) => {
1796
1869
  const page = run.state;
1797
1870
  const state = new RenderState(page.env, page.globals, page.maxSteps, page.maxSize, page.maxDepth, page.locale, page.timeZone, page.userState, page.signal);
1798
- Object.defineProperty(state, "steps", {
1799
- get: () => page.steps,
1800
- set: (steps) => {
1801
- page.steps = steps;
1802
- }
1803
- });
1871
+ lendSteps(page, state);
1804
1872
  const scope = childScope(page.globals);
1805
1873
  const passed = Object.keys(props);
1806
1874
  for (const key of passed) scope[key] = props[key] ?? null;
1807
1875
  addSlotFlags(scope, template, null);
1808
1876
  const out = emptyOut();
1809
1877
  state.root = out;
1810
- return Promise.resolve().then(() => renderTemplate(state, template, scope, out, run.depth + 1, null, passed, null, run, span)).then(() => {
1878
+ return Promise.resolve().then(() => renderTemplate(state, template, scope, out, run.depth + 1, null, passed, null, run.within(null), span)).then(() => {
1879
+ returnSteps(state);
1811
1880
  if (state.signal?.aborted) throw fail(run, span, "aborted", "Render was aborted");
1812
1881
  closeOutlets(state);
1813
1882
  return `<template>${takeOutput(state, out.s)}</template><kiln-island fill="${n}"></kiln-island>`;
1814
1883
  }, (error) => {
1884
+ returnSteps(state);
1815
1885
  throw markCaller(run, span, error);
1816
1886
  });
1817
1887
  };
@@ -1821,8 +1891,10 @@ const ISLAND_SCRIPT = `<script>${islandScript}<\/script>`;
1821
1891
  //#region src/runtime/macros.ts
1822
1892
  /**
1823
1893
  * Calls a macro: binds arguments to parameters in a scope that holds only globals, renders the body and returns it as markup.
1894
+ * A call whose arguments waited passes the capture it started before working them out, to keep its place in the order
1895
+ * of outlets' content.
1824
1896
  */
1825
- const callMacro = (run, span, macro, positional, named) => {
1897
+ const callMacro = (run, span, macro, positional, named, capture) => {
1826
1898
  step(run, span);
1827
1899
  const state = run.state;
1828
1900
  if (run.depth + 1 > state.maxDepth) throw fail(run, span, "limit-depth", `Render stopped after nesting ${state.maxDepth} templates, macros or layouts deep`);
@@ -1833,7 +1905,7 @@ const callMacro = (run, span, macro, positional, named) => {
1833
1905
  if (index !== -1 && index < positional.length) throw fail(run, span, "duplicate-argument", `Macro "${macro.name}" got "${key}" both by position and by name`);
1834
1906
  if (index === -1) throw fail(run, span, "unknown-argument", `Macro "${macro.name}" has no parameter "${key}"`, suggest(key, params.map((param) => param.name)));
1835
1907
  }
1836
- const capture = startCapture(run);
1908
+ capture ??= startCapture(run);
1837
1909
  const macroRun = new Run(state, macro.template, run.depth + 1, null, null, capture, run.blockDepth);
1838
1910
  const scope = childScope(state.globals);
1839
1911
  const bind = (index) => {
@@ -3117,7 +3189,7 @@ var Compiler = class {
3117
3189
  const render = (run, out, scope, islands, template, props) => {
3118
3190
  if (islands.mode === "defer") {
3119
3191
  const id = recordIsland(run, span, islands, template.name, props);
3120
- return element(run, out, scope, islands, `src="${escapeHtml(islands.url + id)}"`);
3192
+ return element(run, out, scope, islands, `src="${escapeHtml(islands.url + id)}"${islands.query ? " query" : ""}`);
3121
3193
  }
3122
3194
  const state = run.state;
3123
3195
  const streamed = state.streamed ??= [];
@@ -3219,7 +3291,11 @@ var Compiler = class {
3219
3291
  const parts = Array.isArray(value) ? value.map((item) => part(run, item)) : [part(run, value)];
3220
3292
  const { locale, timeZone, islands } = run.state;
3221
3293
  const key = `${JSON.stringify(run.state.env.cacheNamespace)}|${templateName}|${locale}|${timeZone}|${JSON.stringify(parts)}`;
3222
- return islands?.mode === "defer" ? `${key}|islands|${JSON.stringify([islands.url, islands.script])}` : key;
3294
+ return islands?.mode === "defer" ? `${key}|islands|${JSON.stringify([
3295
+ islands.url,
3296
+ islands.script,
3297
+ islands.query
3298
+ ])}` : key;
3223
3299
  };
3224
3300
  const lifetime = (run, value) => {
3225
3301
  if (value === null || value === void 0) return null;
@@ -3667,7 +3743,10 @@ var Compiler = class {
3667
3743
  };
3668
3744
  Object.defineProperty(call, "length", { value: params.length });
3669
3745
  Object.defineProperty(fn, "length", { value: params.length });
3670
- templateFunctions.set(fn, call);
3746
+ templateFunctions.set(fn, {
3747
+ call,
3748
+ waits
3749
+ });
3671
3750
  return fn;
3672
3751
  },
3673
3752
  async: false,
@@ -3739,10 +3818,11 @@ var Compiler = class {
3739
3818
  named.push(this.#expr(arg.value));
3740
3819
  } else if (arg.type === "Spread") this.#error("invalid-spread", "Spread arguments cannot be passed to macros", arg.span);
3741
3820
  else positional.push(this.#expr(arg.value));
3742
- const values = evalAll([...positional, ...named]);
3821
+ const args = [...positional, ...named];
3822
+ const values = evalAll(args);
3743
3823
  const count = positional.length;
3744
3824
  const span = node.span;
3745
- const invoke = (run, list) => {
3825
+ const invoke = (run, list, capture) => {
3746
3826
  const macro = resolve(run);
3747
3827
  if (!macro) throw fail(run, span, "unknown-macro", `${label} does not exist`);
3748
3828
  let namedValues = null;
@@ -3750,10 +3830,17 @@ var Compiler = class {
3750
3830
  namedValues = {};
3751
3831
  for (let i = 0; i < namedNames.length; i++) setOwn(namedValues, namedNames[i], list[count + i]);
3752
3832
  }
3753
- return callMacro(run, span, macro, list.slice(0, count), namedValues);
3833
+ return callMacro(run, span, macro, list.slice(0, count), namedValues, capture);
3834
+ };
3835
+ if (!args.some((arg) => arg.async)) return {
3836
+ ev: (run, scope) => invoke(run, values(run, scope)),
3837
+ async: true
3754
3838
  };
3755
3839
  return {
3756
- ev: (run, scope) => after(values(run, scope), (list) => invoke(run, list)),
3840
+ ev: (run, scope) => {
3841
+ const capture = startCapture(run);
3842
+ return after(values(run.within(capture), scope), (list) => invoke(run, list, capture));
3843
+ },
3757
3844
  async: true
3758
3845
  };
3759
3846
  }
@@ -4267,9 +4354,13 @@ const loopItems = (run, span, value, wantKeys) => {
4267
4354
  if (typeof value === "object" && typeof value[Symbol.iterator] === "function") {
4268
4355
  const values = [];
4269
4356
  const limit = run.state.maxSteps;
4270
- for (const item of value) {
4271
- values.push(item);
4272
- if (values.length > limit) throw fail(run, span, "limit-steps", "Iterable has more items than the step limit");
4357
+ try {
4358
+ for (const item of value) {
4359
+ values.push(item);
4360
+ if (values.length > limit) throw fail(run, span, "limit-steps", "Iterable has more items than the step limit");
4361
+ }
4362
+ } catch (error) {
4363
+ throw locate(run, span, error, "Looping over the value");
4273
4364
  }
4274
4365
  return {
4275
4366
  values,
@@ -4284,7 +4375,7 @@ const isPrecompiled = (value) => typeof value === "object" && value !== null &&
4284
4375
  const mismatch = (name, detail) => new KilnRenderError("precompiled-mismatch", `Precompiled template "${name}" ${detail}. Precompile it again`, name);
4285
4376
  /** Compiles a precompiled template: its source, with the generated statements in place of the ones they cover. */
4286
4377
  const compilePrecompiled = (env, name, template) => {
4287
- if (template.kiln !== 5) throw mismatch(name, "was made by another version of Kiln");
4378
+ if (template.kiln !== 6) throw mismatch(name, "was made by another version of Kiln");
4288
4379
  if (template.autoescape !== env.autoescape) throw mismatch(name, "was compiled with another \"autoescape\" option");
4289
4380
  const runs = /* @__PURE__ */ new Map();
4290
4381
  const create = template.create;
@@ -4347,9 +4438,15 @@ const runtime = {
4347
4438
  getPrototypeOf: Object.getPrototypeOf,
4348
4439
  hasOwn: Object.hasOwn,
4349
4440
  step,
4350
- /** Stops a render that counted more steps than `maxSteps`, as `step` does. */
4351
- stepLimit: (run, span) => {
4352
- throw fail(run, span, "limit-steps", `Render stopped after ${run.state.maxSteps} steps`);
4441
+ /**
4442
+ * Takes the steps counted in a local past `maxSteps`, as `step` does: saves them to `state.steps` and stops the
4443
+ * render, unless more steps can be had. Generated code then carries on from `state.steps`, which as a field read
4444
+ * keeps the local a small integer in optimised code.
4445
+ */
4446
+ stepLimit: (run, span, steps) => {
4447
+ const state = run.state;
4448
+ state.steps = steps;
4449
+ if (!moreSteps(state)) throw stepError(run, span);
4353
4450
  },
4354
4451
  /** Refuses a range longer than the step limit, as `range` does. */
4355
4452
  rangeLimit: (run, span, length) => {
@@ -4833,6 +4930,8 @@ const setsIn = (statements, names = /* @__PURE__ */ new Set()) => {
4833
4930
  } else if (statement.type === "Autoescape" || statement.type === "Slot") setsIn(statement.body, names);
4834
4931
  return names;
4835
4932
  };
4933
+ /** Whether statements place a component whose fills set variables, after which `#component` forgets every lookup. */
4934
+ const fillsSet = (statements) => containsNode(statements, (record) => record.type === "Component" && containsNode(record, (inner) => inner.type === "Set" || inner.type === "SetBlock"));
4836
4935
  /** Characters of text a loop gathers before writing them out. */
4837
4936
  const FLUSH_AT = 4096;
4838
4937
  /** Longest `else if` chain written as one. Longer chains become a flat labelled block. */
@@ -4882,6 +4981,11 @@ const isPlainCode = (value) => `(typeof ${value} === "object" && ${value} !== nu
4882
4981
  const access = (key) => IDENTIFIER$1.test(key) ? `.${key}` : `[${JSON.stringify(key)}]`;
4883
4982
  const isBlank = (statement) => statement.type === "Text" && statement.value.trim() === "";
4884
4983
  const indent = (lines) => lines.map((line) => `\t${line}`);
4984
+ /** Cuts a map or set back to its first `size` entries, which keep the order they were added in. */
4985
+ const keepFirst = (entries, size) => {
4986
+ let i = 0;
4987
+ for (const key of entries.keys()) if (i++ >= size) entries.delete(key);
4988
+ };
4885
4989
  /** Lines without `FORK` markers, for functions that never start passes ahead. */
4886
4990
  const dropForks = (lines) => lines.filter((line) => line.trim() !== FORK);
4887
4991
  var Generator = class {
@@ -4892,7 +4996,7 @@ var Generator = class {
4892
4996
  /** Start and end offsets of every span generated code refers to, flattened. */
4893
4997
  #spans = [];
4894
4998
  #spanIndex = /* @__PURE__ */ new Map();
4895
- /** Declarations made once when the module is loaded, such as built-ins and frozen option hashes. */
4999
+ /** Declarations made once when the module is loaded, such as built-ins and frozen option hashes, by their keys. */
4896
5000
  #constants = [];
4897
5001
  #constantNames = /* @__PURE__ */ new Map();
4898
5002
  #runs = [];
@@ -4905,7 +5009,10 @@ var Generator = class {
4905
5009
  #fn = newFunction();
4906
5010
  /** Plain-object flags of loop variables that generated code reads, so loops only set the ones used. */
4907
5011
  #plainUsed = /* @__PURE__ */ new Set();
4908
- /** Loops so far, for local names unique in the module, so a fill's loops never hide the loop around it. */
5012
+ /**
5013
+ * Loops, slot scopes and labels so far, for local names unique in the module, so a fill's loops never hide the loop
5014
+ * around it, and a loop's own function never hides the names around it.
5015
+ */
4909
5016
  #loops = 0;
4910
5017
  #depth = 0;
4911
5018
  /**
@@ -4928,13 +5035,13 @@ var Generator = class {
4928
5035
  return [
4929
5036
  "// Precompiled by Kiln. Don't edit this file: precompile the template again.",
4930
5037
  "export default {",
4931
- `\tkiln: 5,`,
5038
+ `\tkiln: 6,`,
4932
5039
  `\tautoescape: ${JSON.stringify(this.#env.autoescape)},`,
4933
5040
  `\tsource: ${JSON.stringify(source)},`,
4934
5041
  " create(rt) {",
4935
5042
  `\t\tconst { ${HELPERS.join(", ")} } = rt;`,
4936
5043
  `\t\tconst S = rt.spans([${this.#spans.join(", ")}]);`,
4937
- ...this.#constants.map((line) => `\t\t${line}`),
5044
+ ...this.#constants.map(([, line]) => `\t\t${line}`),
4938
5045
  ...this.#declarations.map((line) => `\t\t${line}`),
4939
5046
  " return [",
4940
5047
  ...this.#runs,
@@ -4961,11 +5068,14 @@ var Generator = class {
4961
5068
  const effects = searchOnly ? [] : list.map((statement) => effectsOf([statement], this.#env));
4962
5069
  const plan = planOf(effects, false);
4963
5070
  const strict = planOf(effects, true);
4964
- const stops = [];
5071
+ let stops = [];
4965
5072
  if (top) list.forEach((statement, index) => {
4966
5073
  if (statement.type === "Block") stops.push(index - 1, index);
4967
5074
  });
4968
- const stopFrom = (index) => Math.min(list.length - 1, ...stops.filter((stop) => stop >= index));
5075
+ const stopFrom = (index) => {
5076
+ stops = stops.filter((stop) => stop >= index);
5077
+ return stops.reduce((first, stop) => stop < first ? stop : first, list.length - 1);
5078
+ };
4969
5079
  let i = 0;
4970
5080
  while (i < list.length) {
4971
5081
  if (searchOnly) {
@@ -5093,8 +5203,9 @@ var Generator = class {
5093
5203
  }
5094
5204
  /**
5095
5205
  * Declarations at the start of a generated function: steps are counted in a local, see `#function`, and `b` marks
5096
- * where the current run of text and outputs starts in `s`, see `#parts`. Checks the abort signal too, since a
5097
- * function may continue a run after a wait.
5206
+ * where the current run of text and outputs starts in `s`, see `#parts`, and `room` is how long `out` and `s` may
5207
+ * get before the output limit needs checking: none in output running ahead, which counts with the output it joins.
5208
+ * Checks the abort signal too, since a function may continue a run after a wait.
5098
5209
  */
5099
5210
  #start(span) {
5100
5211
  const fn = this.#fn;
@@ -5103,6 +5214,7 @@ var Generator = class {
5103
5214
  "const state = run.state;",
5104
5215
  "const maxSteps = state.maxSteps;",
5105
5216
  "const maxSize = state.maxSize;",
5217
+ "const room = out.ahead === null ? maxSize : -1;",
5106
5218
  "let steps = state.steps;",
5107
5219
  "const signal = state.signal;",
5108
5220
  `signal !== undefined && signal.aborted && aborted(run, ${span});`,
@@ -5126,24 +5238,26 @@ var Generator = class {
5126
5238
  return null;
5127
5239
  }
5128
5240
  }
5129
- /** Returns a function that forgets everything generated since, such as constants and queued lists. */
5241
+ /**
5242
+ * Returns a function that forgets everything generated since, such as constants and queued lists. Everything it
5243
+ * restores only grows, so it keeps sizes and cuts back to them, rather than copy what a long run has gathered.
5244
+ */
5130
5245
  #snapshot() {
5131
5246
  const constants = this.#constants.length;
5132
- const names = [...this.#constantNames.keys()];
5133
5247
  const pending = this.#pending.length;
5134
5248
  const declarations = this.#declarations.length;
5135
5249
  const fn = this.#fn;
5136
- const saved = {
5137
- ...fn,
5138
- variables: new Map(fn.variables),
5139
- plainUsed: new Set(fn.plainUsed)
5140
- };
5250
+ const { variables, plainUsed, ...counts } = fn;
5251
+ const variableCount = variables.size;
5252
+ const plainCount = plainUsed.size;
5141
5253
  return () => {
5142
- this.#constants.length = constants;
5143
- for (const key of this.#constantNames.keys()) if (!names.includes(key)) this.#constantNames.delete(key);
5254
+ for (const [key] of this.#constants.splice(constants)) this.#constantNames.delete(key);
5144
5255
  this.#pending.length = pending;
5145
5256
  this.#declarations.length = declarations;
5146
- this.#fn = saved;
5257
+ keepFirst(variables, variableCount);
5258
+ keepFirst(plainUsed, plainCount);
5259
+ Object.assign(fn, counts);
5260
+ this.#fn = fn;
5147
5261
  };
5148
5262
  }
5149
5263
  #children(statement, strategy) {
@@ -5190,7 +5304,7 @@ var Generator = class {
5190
5304
  if (name === void 0) {
5191
5305
  name = `${prefix}${this.#constantNames.size}`;
5192
5306
  this.#constantNames.set(key, name);
5193
- this.#constants.push(`const ${name} = ${value};`);
5307
+ this.#constants.push([key, `const ${name} = ${value};`]);
5194
5308
  }
5195
5309
  return name;
5196
5310
  }
@@ -5199,7 +5313,7 @@ var Generator = class {
5199
5313
  }
5200
5314
  /** Counts one step, as `step` does. */
5201
5315
  #step(span) {
5202
- return `++steps > maxSteps && stepLimit(run, ${span})`;
5316
+ return `++steps > maxSteps && (stepLimit(run, ${span}, steps), steps = state.steps)`;
5203
5317
  }
5204
5318
  /**
5205
5319
  * Counts a step and checks the abort signal, as `step` does: in loops, so a long render stops soon after an abort,
@@ -5284,7 +5398,8 @@ var Generator = class {
5284
5398
  * Checks the output limit where the closures do, given a list's statements and their lines. The closures print each
5285
5399
  * run of text and outputs as one string, see `printParts`: an output fails when that string alone is too long, and
5286
5400
  * the run fails when writing it makes the output too long, located at its start. Generated code gathers text in
5287
- * `s` for longer, so it marks where each run starts in `b`, and checks the whole output after each run.
5401
+ * `s` for longer, so it marks where each run starts in `b`, and checks the whole output after each run. Output
5402
+ * running ahead writes each run as the closures do, since others count with it. See `#start`.
5288
5403
  */
5289
5404
  #parts(list, groups) {
5290
5405
  const isPart = (statement) => statement.type === "Text" || statement.type === "Output" && !this.#isHostCall(statement.expression);
@@ -5302,8 +5417,8 @@ var Generator = class {
5302
5417
  if (list.slice(i, end).some((statement) => statement.type === "Output")) run[0] = ["b = s.length;", ...run[0]];
5303
5418
  const at = this.#span(list[i].span);
5304
5419
  const last = run.length - 1;
5305
- run[last] = [...run[last], `if (out.s.length + s.length > maxSize) write(run, out, s, ${at});`];
5306
- result.push(...run);
5420
+ run[last] = [...run[last], `if (out.s.length + s.length > room) { write(run, out, s, ${at}); s = ""; }`];
5421
+ for (const group of run) result.push(group);
5307
5422
  i = end;
5308
5423
  }
5309
5424
  return result;
@@ -5319,7 +5434,7 @@ var Generator = class {
5319
5434
  return unsupported();
5320
5435
  }
5321
5436
  };
5322
- const limit = this.#isHostCall(expression) ? `if (out.s.length + s.length > maxSize) write(run, out, s, ${span});` : `if (s.length - b > maxSize) write(run, out, s, ${span});`;
5437
+ const limit = this.#isHostCall(expression) ? `if (out.s.length + s.length > room) { write(run, out, s, ${span}); s = ""; }` : `if (s.length - b > maxSize) write(run, out, s, ${span});`;
5323
5438
  if (expression.type === "Literal") return [
5324
5439
  step,
5325
5440
  `s += ${emitted(expression.value)};`,
@@ -5428,14 +5543,15 @@ var Generator = class {
5428
5543
  };
5429
5544
  const looped = context.top && !context.inLoop && effectsOf(statement.body, this.#env).waits ? this.#loopFunction(statement, passContext, loop) : null;
5430
5545
  const range = looped ? null : literalRange(statement.iterable);
5431
- const paused = looped || range ? null : this.#loopGenerator(statement, passContext, loop);
5546
+ const paused = looped ? null : this.#loopGenerator(statement, passContext, loop, range);
5547
+ const generated = paused ? [...paused, ...this.#wait(span, `drive(LG${id}(run, out, 0, ${length}))`, context.top)] : null;
5432
5548
  const body = looped || paused ? [] : this.#body(statement.body, {
5433
5549
  ...passContext,
5434
5550
  inLoop: true
5435
5551
  });
5436
5552
  const alternate = statement.alternate ? this.#body(statement.alternate, context) : [];
5437
- if (range) return this.#rangeLoop(statement, context, loop, range, body, alternate);
5438
- const passes = looped ? this.#wait(span, `${looped}(run, ${context.scope}, out, ${values}, ${length}, 0, ${length}${hasKeys ? `, ${keys}` : ""})`, context.top) : paused ? [...paused, ...this.#wait(span, `drive(LG${id}(run, out, 0, ${length}))`, context.top)] : [
5553
+ if (range) return this.#rangeLoop(statement, context, loop, range, body, alternate, generated);
5554
+ const passes = looped ? this.#wait(span, `${looped}(run, ${context.scope}, out, ${values}, ${length}, 0, ${length}${hasKeys ? `, ${keys}` : ""})`, context.top) : generated ?? [
5439
5555
  `for (let ${index} = 0; ${index} < ${length}; ${index}++) {`,
5440
5556
  ...indent(this.#pass(loop, true)),
5441
5557
  ...indent(body),
@@ -5456,43 +5572,53 @@ var Generator = class {
5456
5572
  ...hasKeys ? [`\tconst ${keys} = ${items}.keys;`] : [],
5457
5573
  ...indent(passes),
5458
5574
  "}",
5459
- ...sets.flatMap((name) => this.#forget(name))
5575
+ ...(looped || paused) && fillsSet(statement.body) ? this.#forgetAll() : sets.flatMap((name) => this.#forget(name))
5460
5576
  ];
5461
5577
  }
5462
5578
  /**
5463
5579
  * A loop over a range of integer literals, such as `1..5`, counts instead of making the array. It charges the
5464
- * range's steps and checks its length as `range` does.
5580
+ * range's steps and checks its length as `range` does. `generated` runs the passes when they may pause, see
5581
+ * `#loopGenerator`.
5465
5582
  */
5466
- #rangeLoop(statement, context, loop, range, body, alternate) {
5583
+ #rangeLoop(statement, context, loop, range, body, alternate, generated) {
5467
5584
  const node = statement.iterable;
5468
5585
  const rangeSpan = this.#span(node.span);
5469
5586
  const count = Math.abs(range.to - range.from) + 1;
5470
- const direction = range.to < range.from ? "-" : "+";
5471
- const { span, length, index, value, key, hasKeys } = loop;
5587
+ const { span, length, index } = loop;
5472
5588
  return [
5473
5589
  this.#checkedStep(span),
5474
5590
  `const ${length} = ${count};`,
5475
5591
  `if (${length} > maxSteps) rangeLimit(run, ${rangeSpan}, ${length});`,
5476
- `if ((steps += ${length}) > maxSteps) stepLimit(run, ${rangeSpan});`,
5592
+ `if ((steps += ${length}) > maxSteps) { stepLimit(run, ${rangeSpan}, steps); steps = state.steps; }`,
5477
5593
  ...alternate.length > 0 ? [
5478
5594
  `if (${length} === 0) {`,
5479
5595
  ...indent(alternate),
5480
5596
  "}"
5481
5597
  ] : [],
5482
- `for (let ${index} = 0; ${index} < ${length}; ${index}++) {`,
5483
- `\t${this.#checkedStep(span)}`,
5484
- ...loop.scope ? [`\tconst ${loop.scope} = childScope(${loop.outer});`, ...indent(loop.sets.flatMap((name) => this.#forget(name)))] : [],
5485
- `\tconst ${value} = ${range.from} ${direction} ${index};`,
5486
- ...this.#plainUsed.has(`p${value}`) ? [`\tconst p${value} = false;`] : [],
5487
- ...hasKeys ? [`\tconst ${key} = ${index};`] : [],
5488
- ...hasKeys && this.#plainUsed.has(`p${key}`) ? [`\tconst p${key} = false;`] : [],
5489
- ...indent(body),
5490
- `\tif (s.length > ${FLUSH_AT}) {`,
5491
- `\t\twrite(run, out, s, ${span});`,
5492
- " s = \"\";",
5493
- " }",
5494
- "}",
5495
- ...loop.sets.flatMap((name) => this.#forget(name))
5598
+ ...generated ?? [
5599
+ `for (let ${index} = 0; ${index} < ${length}; ${index}++) {`,
5600
+ ...indent(this.#rangePass(loop, range)),
5601
+ ...indent(body),
5602
+ `\tif (s.length > ${FLUSH_AT}) {`,
5603
+ `\t\twrite(run, out, s, ${span});`,
5604
+ " s = \"\";",
5605
+ " }",
5606
+ "}"
5607
+ ],
5608
+ ...generated && fillsSet(statement.body) ? this.#forgetAll() : loop.sets.flatMap((name) => this.#forget(name))
5609
+ ];
5610
+ }
5611
+ /** The start of a pass over a range: counts a step, makes the pass's scope and binds the loop's variables. */
5612
+ #rangePass(loop, range) {
5613
+ const { span, index, value, key, hasKeys } = loop;
5614
+ const direction = range.to < range.from ? "-" : "+";
5615
+ return [
5616
+ this.#checkedStep(span),
5617
+ ...loop.scope ? [`const ${loop.scope} = childScope(${loop.outer});`, ...loop.sets.flatMap((name) => this.#forget(name))] : [],
5618
+ `const ${value} = ${range.from} ${direction} ${index};`,
5619
+ ...this.#plainUsed.has(`p${value}`) ? [`const p${value} = false;`] : [],
5620
+ ...hasKeys ? [`const ${key} = ${index};`] : [],
5621
+ ...hasKeys && this.#plainUsed.has(`p${key}`) ? [`const p${key} = false;`] : []
5496
5622
  ];
5497
5623
  }
5498
5624
  /**
@@ -5627,10 +5753,10 @@ var Generator = class {
5627
5753
  * A loop whose passes may pause anywhere, such as at a call to one of your functions, as a generator of its own over
5628
5754
  * the index to start at. It is declared where the loop is, so it reads the locals around it, such as the loops
5629
5755
  * outside. When a pass pauses, the passes after it start at once in another run of the generator, when they may;
5630
- * see `startAhead`. The loop then stops after that pass and waits for them. Returns the generator's lines, or null
5631
- * when no pass waits.
5756
+ * see `startAhead`. The loop then stops after that pass and waits for them. A loop over a `range` counts its passes
5757
+ * rather than read its items. Returns the generator's lines, or null when no pass waits.
5632
5758
  */
5633
- #loopGenerator(statement, context, loop) {
5759
+ #loopGenerator(statement, context, loop, range) {
5634
5760
  if (!effectsOf(statement.body, this.#env).waits) return null;
5635
5761
  const outer = this.#fn;
5636
5762
  const restore = this.#snapshot();
@@ -5661,7 +5787,7 @@ var Generator = class {
5661
5787
  `${tabs}}`
5662
5788
  ];
5663
5789
  });
5664
- const pass = this.#pass(loop, true);
5790
+ const pass = range ? this.#rangePass(loop, range) : this.#pass(loop, true);
5665
5791
  const reads = this.#fn.reads;
5666
5792
  return [
5667
5793
  `const ${name} = function* (run, out, ${index}, stop) {`,
@@ -5688,6 +5814,7 @@ var Generator = class {
5688
5814
  " state.steps = steps;",
5689
5815
  ...reads ? [" at = null;"] : [],
5690
5816
  `\tyield ${ahead}.join();`,
5817
+ " steps = state.steps;",
5691
5818
  "}",
5692
5819
  "state.steps = steps;",
5693
5820
  `write(run, out, s, ${span});`
@@ -5720,8 +5847,12 @@ var Generator = class {
5720
5847
  }
5721
5848
  /** Writes out `FORGET_ALL`, once the current function's lookups are all known. */
5722
5849
  #forgetLines(lines) {
5723
- const forget = [...this.#fn.variables.values()].map(({ value }) => `${value} = undefined;`).join(" ");
5724
- return lines.map((line) => line.endsWith(FORGET_ALL) ? line.slice(0, -7) + forget : line);
5850
+ let forget;
5851
+ return lines.map((line) => {
5852
+ if (!line.endsWith(FORGET_ALL)) return line;
5853
+ forget ??= [...this.#fn.variables.values()].map(({ value }) => `${value} = undefined;`).join(" ");
5854
+ return line.slice(0, -7) + forget;
5855
+ });
5725
5856
  }
5726
5857
  /** Forgets lookups of a variable that `set` may have changed. */
5727
5858
  #forget(name) {
@@ -5873,7 +6004,7 @@ var Generator = class {
5873
6004
  const passed = this.#constant(`passed:${JSON.stringify(keys)}`, "P", `Object.freeze(${JSON.stringify(keys)})`);
5874
6005
  return {
5875
6006
  lines,
5876
- charge: (span) => keys.length === 0 ? [] : [`if ((steps += ${keys.length}) > maxSteps) stepLimit(run, ${span});`],
6007
+ charge: (span) => keys.length === 0 ? [] : [`if ((steps += ${keys.length}) > maxSteps) { stepLimit(run, ${span}, steps); steps = state.steps; }`],
5877
6008
  embed: (span, name, slots, ignoreMissing) => {
5878
6009
  const rest = `${scope}, ${passed}, ${slots}, ${ignoreMissing})`;
5879
6010
  return name.kind === "keyed" ? `(${name.joined} === null ? embedKeyed(run, out, ${span}, ${JSON.stringify(name.prefix)}, ${name.key}, ${name.nameSpan}, ${rest} : embedScope(run, out, ${span}, ${name.joined}, ${rest})` : `embedScope(run, out, ${span}, ${name.js}, ${rest}`;
@@ -5910,13 +6041,13 @@ var Generator = class {
5910
6041
  const span = this.#span(statement.span);
5911
6042
  const fill = this.#temp();
5912
6043
  const sets = [...setsIn(statement.body)];
5913
- const scope = sets.length > 0 ? this.#temp() : context.scope;
6044
+ const scope = sets.length > 0 ? `sl${this.#loops++}` : context.scope;
5914
6045
  let fallback = this.#body(statement.body, {
5915
6046
  ...context,
5916
6047
  scope
5917
6048
  });
5918
6049
  if (sets.length > 0) fallback = [
5919
- `${scope} = childScope(${context.scope});`,
6050
+ `const ${scope} = childScope(${context.scope});`,
5920
6051
  ...fallback,
5921
6052
  ...sets.flatMap((name) => this.#forget(name))
5922
6053
  ];
@@ -6276,1098 +6407,6 @@ const renderFills = (run) => {
6276
6407
  return from(0);
6277
6408
  };
6278
6409
  //#endregion
6279
- //#region src/html/data.ts
6280
- /** Obsolete elements in the HTML standard, by what to use instead. */
6281
- const OBSOLETE = new Map(Object.entries({
6282
- "Use <abbr> instead": ["acronym"],
6283
- "Use <object> or <embed> instead": ["applet"],
6284
- "Use CSS instead": [
6285
- "basefont",
6286
- "big",
6287
- "blink",
6288
- "center",
6289
- "font",
6290
- "marquee",
6291
- "multicol",
6292
- "nobr",
6293
- "spacer"
6294
- ],
6295
- "Use <audio> instead": ["bgsound"],
6296
- "Use <ul> instead": ["dir"],
6297
- "Use <iframe>, or a layout with CSS, instead": [
6298
- "frame",
6299
- "frameset",
6300
- "noframes"
6301
- ],
6302
- "Use a form with a text field instead": ["isindex"],
6303
- "Use the Web Crypto API instead": ["keygen"],
6304
- "Use <pre> and <code> instead": [
6305
- "listing",
6306
- "plaintext",
6307
- "xmp"
6308
- ],
6309
- "Use a <button> inside <menu> instead": ["menuitem"],
6310
- "Remove it": ["nextid"],
6311
- "Use fallback content inside <object> instead": ["noembed"],
6312
- "Use attributes on <object> instead": ["param"],
6313
- "Use <ruby> with <rt> instead": ["rb", "rtc"],
6314
- "Use <s>, or <del> for removed text, instead": ["strike"],
6315
- "Use <code>, <kbd> or <samp> instead": ["tt"]
6316
- }).flatMap(([advice, names]) => names.map((name) => [name, advice])));
6317
- /** States and properties from WAI-ARIA 1.2, plus those the 1.3 draft adds. */
6318
- const ARIA_ATTRIBUTES = new Set([
6319
- "activedescendant",
6320
- "atomic",
6321
- "autocomplete",
6322
- "braillelabel",
6323
- "brailleroledescription",
6324
- "busy",
6325
- "checked",
6326
- "colcount",
6327
- "colindex",
6328
- "colindextext",
6329
- "colspan",
6330
- "controls",
6331
- "current",
6332
- "describedby",
6333
- "description",
6334
- "details",
6335
- "disabled",
6336
- "dropeffect",
6337
- "errormessage",
6338
- "expanded",
6339
- "flowto",
6340
- "grabbed",
6341
- "haspopup",
6342
- "hidden",
6343
- "invalid",
6344
- "keyshortcuts",
6345
- "label",
6346
- "labelledby",
6347
- "level",
6348
- "live",
6349
- "modal",
6350
- "multiline",
6351
- "multiselectable",
6352
- "orientation",
6353
- "owns",
6354
- "placeholder",
6355
- "posinset",
6356
- "pressed",
6357
- "readonly",
6358
- "relevant",
6359
- "required",
6360
- "roledescription",
6361
- "rowcount",
6362
- "rowindex",
6363
- "rowindextext",
6364
- "rowspan",
6365
- "selected",
6366
- "setsize",
6367
- "sort",
6368
- "valuemax",
6369
- "valuemin",
6370
- "valuenow",
6371
- "valuetext"
6372
- ].map((name) => `aria-${name}`));
6373
- /** Roles from WAI-ARIA 1.2, plus those the 1.3 draft adds. */
6374
- const ROLES = /* @__PURE__ */ new Set([
6375
- "alert",
6376
- "alertdialog",
6377
- "application",
6378
- "article",
6379
- "banner",
6380
- "blockquote",
6381
- "button",
6382
- "caption",
6383
- "cell",
6384
- "checkbox",
6385
- "code",
6386
- "columnheader",
6387
- "combobox",
6388
- "comment",
6389
- "complementary",
6390
- "contentinfo",
6391
- "definition",
6392
- "deletion",
6393
- "dialog",
6394
- "directory",
6395
- "document",
6396
- "emphasis",
6397
- "feed",
6398
- "figure",
6399
- "form",
6400
- "generic",
6401
- "grid",
6402
- "gridcell",
6403
- "group",
6404
- "heading",
6405
- "image",
6406
- "img",
6407
- "insertion",
6408
- "link",
6409
- "list",
6410
- "listbox",
6411
- "listitem",
6412
- "log",
6413
- "main",
6414
- "mark",
6415
- "marquee",
6416
- "math",
6417
- "menu",
6418
- "menubar",
6419
- "menuitem",
6420
- "menuitemcheckbox",
6421
- "menuitemradio",
6422
- "meter",
6423
- "navigation",
6424
- "none",
6425
- "note",
6426
- "option",
6427
- "paragraph",
6428
- "presentation",
6429
- "progressbar",
6430
- "radio",
6431
- "radiogroup",
6432
- "region",
6433
- "row",
6434
- "rowgroup",
6435
- "rowheader",
6436
- "scrollbar",
6437
- "search",
6438
- "searchbox",
6439
- "sectionfooter",
6440
- "sectionheader",
6441
- "separator",
6442
- "slider",
6443
- "spinbutton",
6444
- "status",
6445
- "strong",
6446
- "subscript",
6447
- "suggestion",
6448
- "superscript",
6449
- "switch",
6450
- "tab",
6451
- "table",
6452
- "tablist",
6453
- "tabpanel",
6454
- "term",
6455
- "textbox",
6456
- "time",
6457
- "timer",
6458
- "toolbar",
6459
- "tooltip",
6460
- "tree",
6461
- "treegrid",
6462
- "treeitem"
6463
- ]);
6464
- /** Roles that only organise the ARIA spec. Pages must not use them. */
6465
- const ABSTRACT_ROLES = /* @__PURE__ */ new Set([
6466
- "command",
6467
- "composite",
6468
- "input",
6469
- "landmark",
6470
- "range",
6471
- "roletype",
6472
- "section",
6473
- "sectionhead",
6474
- "select",
6475
- "structure",
6476
- "widget",
6477
- "window"
6478
- ]);
6479
- /** Elements whose content is text, so tags inside them aren't elements. */
6480
- const RAW_TEXT = /* @__PURE__ */ new Set([
6481
- "script",
6482
- "style",
6483
- "textarea",
6484
- "title",
6485
- "xmp",
6486
- "iframe",
6487
- "noembed",
6488
- "noframes",
6489
- "plaintext"
6490
- ]);
6491
- /** Elements whose content follows SVG or MathML rules instead of HTML's. */
6492
- const FOREIGN = /* @__PURE__ */ new Set(["svg", "math"]);
6493
- /** Elements with no content or end tag. */
6494
- const VOID = /* @__PURE__ */ new Set([
6495
- "area",
6496
- "base",
6497
- "basefont",
6498
- "bgsound",
6499
- "br",
6500
- "col",
6501
- "embed",
6502
- "frame",
6503
- "hr",
6504
- "img",
6505
- "input",
6506
- "keygen",
6507
- "link",
6508
- "meta",
6509
- "param",
6510
- "source",
6511
- "track",
6512
- "wbr"
6513
- ]);
6514
- /** What each obsolete attribute is replaced by, by element. Attributes missing from an element's list use CSS. */
6515
- const CSS = "Use CSS instead";
6516
- const REMOVE = "Remove it";
6517
- const USE_ID = "Use id instead";
6518
- const presentational = (...names) => Object.fromEntries(names.map((name) => [name, CSS]));
6519
- const cellAttributes = presentational("align", "bgcolor", "char", "charoff", "height", "nowrap", "valign", "width");
6520
- const rowGroupAttributes = presentational("align", "char", "charoff", "valign");
6521
- const OBSOLETE_ATTRIBUTES = {
6522
- a: {
6523
- charset: REMOVE,
6524
- coords: "Use <area> instead",
6525
- methods: REMOVE,
6526
- name: USE_ID,
6527
- rev: "Use rel instead",
6528
- shape: "Use <area> instead",
6529
- urn: REMOVE
6530
- },
6531
- area: {
6532
- nohref: "Leave out href instead",
6533
- type: REMOVE
6534
- },
6535
- body: presentational("alink", "background", "bgcolor", "bottommargin", "leftmargin", "link", "marginbottom", "marginheight", "marginleft", "marginright", "margintop", "marginwidth", "rightmargin", "text", "topmargin", "vlink"),
6536
- br: presentational("clear"),
6537
- caption: presentational("align"),
6538
- col: presentational("align", "char", "charoff", "valign", "width"),
6539
- div: presentational("align"),
6540
- dl: presentational("compact"),
6541
- embed: {
6542
- ...presentational("align", "hspace", "vspace"),
6543
- name: USE_ID
6544
- },
6545
- head: { profile: REMOVE },
6546
- hr: presentational("align", "color", "noshade", "size", "width"),
6547
- html: {
6548
- manifest: "Use a service worker instead",
6549
- version: REMOVE
6550
- },
6551
- ...Object.fromEntries([
6552
- "h1",
6553
- "h2",
6554
- "h3",
6555
- "h4",
6556
- "h5",
6557
- "h6",
6558
- "legend",
6559
- "p"
6560
- ].map((name) => [name, presentational("align")])),
6561
- iframe: {
6562
- ...presentational("align", "allowtransparency", "frameborder", "framespacing", "hspace", "marginheight", "marginwidth", "scrolling", "vspace"),
6563
- longdesc: "Link to the description instead"
6564
- },
6565
- img: {
6566
- ...presentational("align", "border", "hspace", "vspace"),
6567
- longdesc: "Link to the description instead",
6568
- lowsrc: "Use srcset instead",
6569
- name: USE_ID
6570
- },
6571
- input: {
6572
- ...presentational("align", "hspace", "vspace"),
6573
- ismap: "Use <img> for image maps instead",
6574
- usemap: "Use <img> for image maps instead"
6575
- },
6576
- li: presentational("type"),
6577
- link: {
6578
- charset: REMOVE,
6579
- rev: "Use rel instead",
6580
- target: REMOVE
6581
- },
6582
- menu: presentational("compact"),
6583
- meta: { scheme: REMOVE },
6584
- object: {
6585
- ...presentational("align", "border", "hspace", "vspace"),
6586
- archive: "Use data and type instead",
6587
- classid: "Use data and type instead",
6588
- code: "Use data and type instead",
6589
- codebase: "Use data and type instead",
6590
- codetype: "Use data and type instead",
6591
- declare: REMOVE,
6592
- standby: REMOVE
6593
- },
6594
- ol: presentational("compact"),
6595
- option: { name: USE_ID },
6596
- pre: presentational("width"),
6597
- script: {
6598
- charset: REMOVE,
6599
- event: REMOVE,
6600
- for: REMOVE,
6601
- language: REMOVE
6602
- },
6603
- table: {
6604
- ...presentational("align", "bgcolor", "border", "cellpadding", "cellspacing", "frame", "rules", "width"),
6605
- summary: "Use <caption> instead"
6606
- },
6607
- tbody: rowGroupAttributes,
6608
- thead: rowGroupAttributes,
6609
- tfoot: rowGroupAttributes,
6610
- tr: {
6611
- ...rowGroupAttributes,
6612
- bgcolor: CSS
6613
- },
6614
- td: {
6615
- ...cellAttributes,
6616
- abbr: "Use <th> with abbr instead",
6617
- axis: "Use scope on <th> instead",
6618
- scope: "Use <th> instead"
6619
- },
6620
- th: {
6621
- ...cellAttributes,
6622
- axis: "Use scope instead"
6623
- },
6624
- ul: presentational("compact", "type")
6625
- };
6626
- const FORM_METHODS = [
6627
- "get",
6628
- "post",
6629
- "dialog"
6630
- ];
6631
- const ENCTYPES = [
6632
- "application/x-www-form-urlencoded",
6633
- "multipart/form-data",
6634
- "text/plain"
6635
- ];
6636
- const TARGETS = [
6637
- "_blank",
6638
- "_parent",
6639
- "_self",
6640
- "_top",
6641
- "_unfencedTop"
6642
- ];
6643
- /** A target that isn't a keyword is a name, and names can't start with `_`. */
6644
- const targetName = (value) => !value.startsWith("_");
6645
- const ATTRIBUTE_VALUES = {
6646
- type: [
6647
- {
6648
- on: ["input"],
6649
- values: [
6650
- "button",
6651
- "checkbox",
6652
- "color",
6653
- "date",
6654
- "datetime-local",
6655
- "email",
6656
- "file",
6657
- "hidden",
6658
- "image",
6659
- "month",
6660
- "number",
6661
- "password",
6662
- "radio",
6663
- "range",
6664
- "reset",
6665
- "search",
6666
- "submit",
6667
- "tel",
6668
- "text",
6669
- "time",
6670
- "url",
6671
- "week"
6672
- ]
6673
- },
6674
- {
6675
- on: ["button"],
6676
- values: [
6677
- "button",
6678
- "reset",
6679
- "submit"
6680
- ]
6681
- },
6682
- {
6683
- on: ["ol"],
6684
- values: [
6685
- "1",
6686
- "a",
6687
- "A",
6688
- "i",
6689
- "I"
6690
- ],
6691
- caseSensitive: true
6692
- }
6693
- ],
6694
- method: [{
6695
- on: ["form"],
6696
- values: FORM_METHODS
6697
- }],
6698
- formmethod: [{
6699
- on: ["button", "input"],
6700
- values: FORM_METHODS
6701
- }],
6702
- enctype: [{
6703
- on: ["form"],
6704
- values: ENCTYPES
6705
- }],
6706
- formenctype: [{
6707
- on: ["button", "input"],
6708
- values: ENCTYPES
6709
- }],
6710
- autocomplete: [{
6711
- on: ["form"],
6712
- values: ["on", "off"]
6713
- }],
6714
- loading: [{
6715
- on: ["img", "iframe"],
6716
- values: ["eager", "lazy"]
6717
- }],
6718
- decoding: [{
6719
- on: ["img"],
6720
- values: [
6721
- "async",
6722
- "auto",
6723
- "sync"
6724
- ]
6725
- }],
6726
- fetchpriority: [{
6727
- on: [
6728
- "img",
6729
- "iframe",
6730
- "link",
6731
- "script"
6732
- ],
6733
- values: [
6734
- "auto",
6735
- "high",
6736
- "low"
6737
- ]
6738
- }],
6739
- crossorigin: [{
6740
- on: [
6741
- "audio",
6742
- "img",
6743
- "link",
6744
- "script",
6745
- "video"
6746
- ],
6747
- values: [
6748
- "",
6749
- "anonymous",
6750
- "use-credentials"
6751
- ]
6752
- }],
6753
- referrerpolicy: [{
6754
- on: [
6755
- "a",
6756
- "area",
6757
- "iframe",
6758
- "img",
6759
- "link",
6760
- "script"
6761
- ],
6762
- values: [
6763
- "",
6764
- "no-referrer",
6765
- "no-referrer-when-downgrade",
6766
- "origin",
6767
- "origin-when-cross-origin",
6768
- "same-origin",
6769
- "strict-origin",
6770
- "strict-origin-when-cross-origin",
6771
- "unsafe-url"
6772
- ]
6773
- }],
6774
- target: [{
6775
- on: [
6776
- "a",
6777
- "area",
6778
- "base",
6779
- "form"
6780
- ],
6781
- values: TARGETS,
6782
- other: targetName
6783
- }],
6784
- formtarget: [{
6785
- on: ["button", "input"],
6786
- values: TARGETS,
6787
- other: targetName
6788
- }],
6789
- preload: [{
6790
- on: ["audio", "video"],
6791
- values: [
6792
- "",
6793
- "auto",
6794
- "metadata",
6795
- "none"
6796
- ]
6797
- }],
6798
- scope: [{
6799
- on: ["th"],
6800
- values: [
6801
- "col",
6802
- "colgroup",
6803
- "row",
6804
- "rowgroup"
6805
- ]
6806
- }],
6807
- kind: [{
6808
- on: ["track"],
6809
- values: [
6810
- "captions",
6811
- "chapters",
6812
- "descriptions",
6813
- "metadata",
6814
- "subtitles"
6815
- ]
6816
- }],
6817
- wrap: [{
6818
- on: ["textarea"],
6819
- values: ["hard", "soft"]
6820
- }],
6821
- shape: [{
6822
- on: ["area"],
6823
- values: [
6824
- "circle",
6825
- "default",
6826
- "poly",
6827
- "rect"
6828
- ]
6829
- }],
6830
- capture: [{
6831
- on: ["input"],
6832
- values: ["environment", "user"]
6833
- }],
6834
- sandbox: [{
6835
- on: ["iframe"],
6836
- tokens: true,
6837
- values: [
6838
- "allow-downloads",
6839
- "allow-forms",
6840
- "allow-modals",
6841
- "allow-orientation-lock",
6842
- "allow-pointer-lock",
6843
- "allow-popups",
6844
- "allow-popups-to-escape-sandbox",
6845
- "allow-presentation",
6846
- "allow-same-origin",
6847
- "allow-scripts",
6848
- "allow-storage-access-by-user-activation",
6849
- "allow-top-navigation",
6850
- "allow-top-navigation-by-user-activation",
6851
- "allow-top-navigation-to-custom-protocols"
6852
- ]
6853
- }],
6854
- blocking: [{
6855
- on: [
6856
- "link",
6857
- "script",
6858
- "style"
6859
- ],
6860
- tokens: true,
6861
- values: ["render"]
6862
- }],
6863
- popovertargetaction: [{
6864
- on: ["button", "input"],
6865
- values: [
6866
- "hide",
6867
- "show",
6868
- "toggle"
6869
- ]
6870
- }],
6871
- command: [{
6872
- on: ["button"],
6873
- values: [
6874
- "close",
6875
- "hide-popover",
6876
- "request-close",
6877
- "show-modal",
6878
- "show-popover",
6879
- "toggle-popover"
6880
- ],
6881
- other: (value) => value.startsWith("--")
6882
- }],
6883
- shadowrootmode: [{
6884
- on: ["template"],
6885
- values: ["closed", "open"]
6886
- }],
6887
- dir: [{
6888
- on: "*",
6889
- values: [
6890
- "auto",
6891
- "ltr",
6892
- "rtl"
6893
- ]
6894
- }],
6895
- hidden: [{
6896
- on: "*",
6897
- values: [
6898
- "",
6899
- "hidden",
6900
- "until-found"
6901
- ]
6902
- }],
6903
- contenteditable: [{
6904
- on: "*",
6905
- values: [
6906
- "",
6907
- "false",
6908
- "plaintext-only",
6909
- "true"
6910
- ]
6911
- }],
6912
- draggable: [{
6913
- on: "*",
6914
- values: ["false", "true"]
6915
- }],
6916
- spellcheck: [{
6917
- on: "*",
6918
- values: [
6919
- "",
6920
- "false",
6921
- "true"
6922
- ]
6923
- }],
6924
- translate: [{
6925
- on: "*",
6926
- values: [
6927
- "",
6928
- "no",
6929
- "yes"
6930
- ]
6931
- }],
6932
- autocapitalize: [{
6933
- on: "*",
6934
- values: [
6935
- "characters",
6936
- "none",
6937
- "off",
6938
- "on",
6939
- "sentences",
6940
- "words"
6941
- ]
6942
- }],
6943
- inputmode: [{
6944
- on: "*",
6945
- values: [
6946
- "decimal",
6947
- "email",
6948
- "none",
6949
- "numeric",
6950
- "search",
6951
- "tel",
6952
- "text",
6953
- "url"
6954
- ]
6955
- }],
6956
- enterkeyhint: [{
6957
- on: "*",
6958
- values: [
6959
- "done",
6960
- "enter",
6961
- "go",
6962
- "next",
6963
- "previous",
6964
- "search",
6965
- "send"
6966
- ]
6967
- }],
6968
- popover: [{
6969
- on: "*",
6970
- values: [
6971
- "",
6972
- "auto",
6973
- "hint",
6974
- "manual"
6975
- ]
6976
- }]
6977
- };
6978
- /** Boolean attributes, which are on whenever they are present, by the elements that have them. `*` is any element. */
6979
- const BOOLEAN_ATTRIBUTES = {
6980
- allowfullscreen: ["iframe"],
6981
- async: ["script"],
6982
- autofocus: "*",
6983
- autoplay: ["audio", "video"],
6984
- checked: ["input"],
6985
- controls: ["audio", "video"],
6986
- default: ["track"],
6987
- defer: ["script"],
6988
- disabled: [
6989
- "button",
6990
- "fieldset",
6991
- "input",
6992
- "link",
6993
- "optgroup",
6994
- "option",
6995
- "select",
6996
- "textarea"
6997
- ],
6998
- formnovalidate: ["button", "input"],
6999
- inert: "*",
7000
- ismap: ["img"],
7001
- itemscope: "*",
7002
- loop: ["audio", "video"],
7003
- multiple: ["input", "select"],
7004
- muted: ["audio", "video"],
7005
- nomodule: ["script"],
7006
- novalidate: ["form"],
7007
- open: ["details", "dialog"],
7008
- playsinline: ["video"],
7009
- readonly: ["input", "textarea"],
7010
- required: [
7011
- "input",
7012
- "select",
7013
- "textarea"
7014
- ],
7015
- reversed: ["ol"],
7016
- selected: ["option"],
7017
- shadowrootclonable: ["template"],
7018
- shadowrootdelegatesfocus: ["template"],
7019
- shadowrootserializable: ["template"]
7020
- };
7021
- /** Roles elements always have, whatever their attributes. Lists are left out; see the docs on `html-redundant-role`. */
7022
- const IMPLICIT_ROLES = {
7023
- article: "article",
7024
- aside: "complementary",
7025
- blockquote: "blockquote",
7026
- button: "button",
7027
- caption: "caption",
7028
- code: "code",
7029
- datalist: "listbox",
7030
- del: "deletion",
7031
- details: "group",
7032
- dfn: "term",
7033
- dialog: "dialog",
7034
- em: "emphasis",
7035
- fieldset: "group",
7036
- figure: "figure",
7037
- h1: "heading",
7038
- h2: "heading",
7039
- h3: "heading",
7040
- h4: "heading",
7041
- h5: "heading",
7042
- h6: "heading",
7043
- hr: "separator",
7044
- html: "document",
7045
- ins: "insertion",
7046
- main: "main",
7047
- meter: "meter",
7048
- nav: "navigation",
7049
- optgroup: "group",
7050
- option: "option",
7051
- output: "status",
7052
- p: "paragraph",
7053
- progress: "progressbar",
7054
- search: "search",
7055
- strong: "strong",
7056
- sub: "subscript",
7057
- sup: "superscript",
7058
- table: "table",
7059
- tbody: "rowgroup",
7060
- textarea: "textbox",
7061
- tfoot: "rowgroup",
7062
- thead: "rowgroup",
7063
- time: "time",
7064
- tr: "row"
7065
- };
7066
- /** The roles `<input>` has for each `type`, when the role doesn't depend on other attributes. */
7067
- const INPUT_ROLES = {
7068
- button: "button",
7069
- checkbox: "checkbox",
7070
- image: "button",
7071
- number: "spinbutton",
7072
- radio: "radio",
7073
- range: "slider",
7074
- reset: "button",
7075
- submit: "button"
7076
- };
7077
- const HEADINGS = /* @__PURE__ */ new Set([
7078
- "h1",
7079
- "h2",
7080
- "h3",
7081
- "h4",
7082
- "h5",
7083
- "h6"
7084
- ]);
7085
- /** Elements that aren't phrasing content. Starting one ends an open `<p>`. */
7086
- const FLOW = /* @__PURE__ */ new Set([
7087
- "address",
7088
- "article",
7089
- "aside",
7090
- "blockquote",
7091
- "center",
7092
- "dd",
7093
- "details",
7094
- "dialog",
7095
- "dir",
7096
- "div",
7097
- "dl",
7098
- "dt",
7099
- "fieldset",
7100
- "figcaption",
7101
- "figure",
7102
- "footer",
7103
- "form",
7104
- ...HEADINGS,
7105
- "header",
7106
- "hgroup",
7107
- "hr",
7108
- "li",
7109
- "listing",
7110
- "main",
7111
- "menu",
7112
- "nav",
7113
- "ol",
7114
- "p",
7115
- "plaintext",
7116
- "pre",
7117
- "search",
7118
- "section",
7119
- "summary",
7120
- "table",
7121
- "ul",
7122
- "xmp"
7123
- ]);
7124
- /** Elements that only hold phrasing content: text and inline elements. `<p>` is left out, since the browser ends it. */
7125
- const PHRASING_ONLY = /* @__PURE__ */ new Set([
7126
- "abbr",
7127
- "b",
7128
- "bdi",
7129
- "bdo",
7130
- "button",
7131
- "cite",
7132
- "code",
7133
- "data",
7134
- "dfn",
7135
- "em",
7136
- ...HEADINGS,
7137
- "i",
7138
- "kbd",
7139
- "label",
7140
- "legend",
7141
- "mark",
7142
- "meter",
7143
- "output",
7144
- "pre",
7145
- "progress",
7146
- "q",
7147
- "rp",
7148
- "rt",
7149
- "ruby",
7150
- "s",
7151
- "samp",
7152
- "small",
7153
- "span",
7154
- "strong",
7155
- "sub",
7156
- "summary",
7157
- "sup",
7158
- "time",
7159
- "u",
7160
- "var"
7161
- ]);
7162
- /** Elements that take the content model of their parent, so their parent decides what they may hold. */
7163
- const TRANSPARENT = /* @__PURE__ */ new Set([
7164
- "a",
7165
- "audio",
7166
- "canvas",
7167
- "del",
7168
- "ins",
7169
- "map",
7170
- "noscript",
7171
- "object",
7172
- "slot",
7173
- "video"
7174
- ]);
7175
- const SCRIPT_SUPPORTING = ["script", "template"];
7176
- const TABLE_PARTS = [
7177
- "caption",
7178
- "colgroup",
7179
- "col",
7180
- "thead",
7181
- "tbody",
7182
- "tfoot",
7183
- "tr"
7184
- ];
7185
- /** Elements that only hold certain children. */
7186
- const ONLY_CHILDREN = {
7187
- ul: ["li", ...SCRIPT_SUPPORTING],
7188
- ol: ["li", ...SCRIPT_SUPPORTING],
7189
- menu: ["li", ...SCRIPT_SUPPORTING],
7190
- dl: [
7191
- "dt",
7192
- "dd",
7193
- "div",
7194
- ...SCRIPT_SUPPORTING
7195
- ],
7196
- table: [...TABLE_PARTS, ...SCRIPT_SUPPORTING],
7197
- thead: ["tr", ...SCRIPT_SUPPORTING],
7198
- tbody: ["tr", ...SCRIPT_SUPPORTING],
7199
- tfoot: ["tr", ...SCRIPT_SUPPORTING],
7200
- tr: [
7201
- "td",
7202
- "th",
7203
- ...SCRIPT_SUPPORTING
7204
- ],
7205
- colgroup: ["col", "template"],
7206
- picture: [
7207
- "source",
7208
- "img",
7209
- ...SCRIPT_SUPPORTING
7210
- ],
7211
- hgroup: [
7212
- "p",
7213
- ...HEADINGS,
7214
- ...SCRIPT_SUPPORTING
7215
- ]
7216
- };
7217
- /** What `<head>` holds. Anything else ends it, since `</head>` can be left out. */
7218
- const METADATA = /* @__PURE__ */ new Set([
7219
- "base",
7220
- "link",
7221
- "meta",
7222
- "noscript",
7223
- "script",
7224
- "style",
7225
- "template",
7226
- "title"
7227
- ]);
7228
- /** Elements that must sit directly inside certain parents. */
7229
- const REQUIRED_PARENTS = {
7230
- li: [
7231
- "ul",
7232
- "ol",
7233
- "menu"
7234
- ],
7235
- dt: ["dl", "div"],
7236
- dd: ["dl", "div"],
7237
- tr: [
7238
- "table",
7239
- "thead",
7240
- "tbody",
7241
- "tfoot"
7242
- ],
7243
- td: ["tr"],
7244
- th: ["tr"],
7245
- thead: ["table"],
7246
- tbody: ["table"],
7247
- tfoot: ["table"],
7248
- caption: ["table"],
7249
- colgroup: ["table"],
7250
- col: ["colgroup", "table"],
7251
- summary: ["details"],
7252
- legend: ["fieldset", "optgroup"],
7253
- figcaption: ["figure"],
7254
- source: [
7255
- "picture",
7256
- "audio",
7257
- "video"
7258
- ],
7259
- track: ["audio", "video"],
7260
- rt: ["ruby"],
7261
- rp: ["ruby"]
7262
- };
7263
- /** Elements that must be the first child of their parent. */
7264
- const FIRST_CHILD = {
7265
- summary: "details",
7266
- legend: "fieldset"
7267
- };
7268
- /** Where `<main>` may go, besides custom elements. */
7269
- const MAIN_PARENTS = /* @__PURE__ */ new Set([
7270
- "html",
7271
- "body",
7272
- "div",
7273
- "form",
7274
- "template"
7275
- ]);
7276
- /**
7277
- * The "special" elements of the HTML parser, which stop it looking further for an `<li>`, `<dd>` or `<dt>` to end.
7278
- * `address`, `div` and `p` are left out, as the parser looks past them.
7279
- */
7280
- const SPECIAL = /* @__PURE__ */ new Set([
7281
- "applet",
7282
- "area",
7283
- "article",
7284
- "aside",
7285
- "base",
7286
- "basefont",
7287
- "bgsound",
7288
- "blockquote",
7289
- "body",
7290
- "br",
7291
- "button",
7292
- "caption",
7293
- "center",
7294
- "col",
7295
- "colgroup",
7296
- "dd",
7297
- "details",
7298
- "dir",
7299
- "dl",
7300
- "dt",
7301
- "embed",
7302
- "fieldset",
7303
- "figcaption",
7304
- "figure",
7305
- "footer",
7306
- "form",
7307
- "frame",
7308
- "frameset",
7309
- ...HEADINGS,
7310
- "head",
7311
- "header",
7312
- "hgroup",
7313
- "hr",
7314
- "html",
7315
- "iframe",
7316
- "img",
7317
- "input",
7318
- "keygen",
7319
- "li",
7320
- "link",
7321
- "listing",
7322
- "main",
7323
- "marquee",
7324
- "menu",
7325
- "meta",
7326
- "nav",
7327
- "noembed",
7328
- "noframes",
7329
- "noscript",
7330
- "object",
7331
- "ol",
7332
- "param",
7333
- "plaintext",
7334
- "pre",
7335
- "script",
7336
- "search",
7337
- "section",
7338
- "select",
7339
- "source",
7340
- "style",
7341
- "summary",
7342
- "table",
7343
- "tbody",
7344
- "td",
7345
- "template",
7346
- "textarea",
7347
- "tfoot",
7348
- "th",
7349
- "thead",
7350
- "title",
7351
- "tr",
7352
- "track",
7353
- "ul",
7354
- "wbr",
7355
- "xmp"
7356
- ]);
7357
- /** Elements that end the search for an open `<p>` or `<button>`: the parser's "button scope". */
7358
- const BUTTON_SCOPE = /* @__PURE__ */ new Set([
7359
- "applet",
7360
- "button",
7361
- "caption",
7362
- "html",
7363
- "marquee",
7364
- "object",
7365
- "table",
7366
- "td",
7367
- "template",
7368
- "th"
7369
- ]);
7370
- //#endregion
7371
6410
  //#region src/html/options.ts
7372
6411
  const HTML_CHECKS = [
7373
6412
  "html-obsolete-element",
@@ -7569,19 +6608,105 @@ const FORMATTING_MARKERS = /* @__PURE__ */ new Set([
7569
6608
  "template",
7570
6609
  "th"
7571
6610
  ]);
6611
+ const TABLE_STOPS = /* @__PURE__ */ new Set([
6612
+ "table",
6613
+ "template",
6614
+ "html"
6615
+ ]);
6616
+ const ROW_STOPS = /* @__PURE__ */ new Set(["tr", ...TABLE_STOPS]);
6617
+ const SECTION_STOPS = /* @__PURE__ */ new Set([
6618
+ "thead",
6619
+ "tbody",
6620
+ "tfoot",
6621
+ ...TABLE_STOPS
6622
+ ]);
6623
+ /**
6624
+ * The searches the rules make through the open elements, innermost first. Each ends at the first element it accepts,
6625
+ * which the rule then reads. Searches for an element to end, as the HTML parser makes, also end at an unknown element.
6626
+ */
6627
+ const SEARCHES = {
6628
+ li: (name) => name === "li" || name === UNKNOWN || SPECIAL.has(name),
6629
+ definition: (name) => name === "dd" || name === "dt" || name === UNKNOWN || SPECIAL.has(name),
6630
+ cell: (name) => name === "td" || name === "th" || name === UNKNOWN || ROW_STOPS.has(name),
6631
+ row: (name) => name === "tr" || name === UNKNOWN || SECTION_STOPS.has(name),
6632
+ section: (name) => name === "thead" || name === "tbody" || name === "tfoot" || name === UNKNOWN || TABLE_STOPS.has(name),
6633
+ a: (name) => name === "a" || name === UNKNOWN || FORMATTING_MARKERS.has(name),
6634
+ button: (name) => name === "button" || name === UNKNOWN || BUTTON_SCOPE.has(name),
6635
+ paragraph: (name) => name === "p" || name === UNKNOWN || BUTTON_SCOPE.has(name),
6636
+ form: (name) => name === "form" || name === "template",
6637
+ label: (name) => name === "label" || name === "template",
6638
+ interactive: (name) => name === "a" || name === "button" || name === "template",
6639
+ headerOrFooter: (name) => name === "header" || name === "footer" || name === "template",
6640
+ notMainParent: (name) => name === "template" || name !== UNKNOWN && !MAIN_PARENTS.has(name) && !name.includes("-"),
6641
+ container: (name) => !TRANSPARENT.has(name)
6642
+ };
6643
+ const entry = (name, parent) => ({
6644
+ name,
6645
+ parent,
6646
+ depth: parent ? parent.depth + 1 : 0,
6647
+ found: {}
6648
+ });
6649
+ /** Where `search` from `from` ends. The bottom ends every search. */
6650
+ const find = (from, search) => {
6651
+ const accepts = SEARCHES[search];
6652
+ let at = from;
6653
+ let found = at.found[search];
6654
+ while (found === void 0) if (at.parent === null || accepts(at.name)) found = at;
6655
+ else {
6656
+ at = at.parent;
6657
+ found = at.found[search];
6658
+ }
6659
+ for (let walked = from; walked !== at; walked = walked.parent) walked.found[search] = found;
6660
+ at.found[search] = found;
6661
+ return found;
6662
+ };
7572
6663
  const fresh = () => ({
7573
- open: [{
7574
- name: UNKNOWN,
7575
- children: 0
7576
- }],
6664
+ top: entry(UNKNOWN, null),
6665
+ hasChildren: false,
6666
+ counts: /* @__PURE__ */ new Map(),
6667
+ ownsCounts: true,
7577
6668
  heading: null,
7578
6669
  endedParagraph: null
7579
6670
  });
7580
- const copy = (state) => ({
7581
- open: state.open.map((entry) => ({ ...entry })),
7582
- heading: state.heading,
7583
- endedParagraph: state.endedParagraph
7584
- });
6671
+ const copy = (state) => {
6672
+ state.ownsCounts = false;
6673
+ return { ...state };
6674
+ };
6675
+ const count = (state, name, change) => {
6676
+ if (!state.ownsCounts) {
6677
+ state.counts = new Map(state.counts);
6678
+ state.ownsCounts = true;
6679
+ }
6680
+ state.counts.set(name, (state.counts.get(name) ?? 0) + change);
6681
+ };
6682
+ const push = (state, name) => {
6683
+ state.top = entry(name, state.top);
6684
+ state.hasChildren = false;
6685
+ count(state, name, 1);
6686
+ };
6687
+ /** Ends `open` and the elements inside it. */
6688
+ const popThrough = (state, open) => {
6689
+ for (let at = state.top; at !== open.parent; at = at.parent) count(state, at.name, -1);
6690
+ state.top = open.parent;
6691
+ state.hasChildren = true;
6692
+ };
6693
+ /** The element `search` ends at, when `matches` accepts it. Searches never end at the bottom, which is unknown. */
6694
+ const findOpen = (state, search, matches) => {
6695
+ const found = find(state.top, search);
6696
+ return found.depth > 0 && matches(found.name) ? found : null;
6697
+ };
6698
+ /** How many of the leading open elements two states, which come from one state, agree on. */
6699
+ const agreeing = (a, b) => {
6700
+ while (a.depth > b.depth) a = a.parent;
6701
+ while (b.depth > a.depth) b = b.parent;
6702
+ let same = a.depth + 1;
6703
+ while (a !== b) {
6704
+ if (a.name !== b.name) same = a.depth;
6705
+ a = a.parent;
6706
+ b = b.parent;
6707
+ }
6708
+ return same;
6709
+ };
7585
6710
  const levelOf = (name) => HEADINGS.has(name) ? Number(name.slice(1)) : null;
7586
6711
  /** Lists names as `<a>`, `<a> and <b>`, or `<a>, <b> and <c>`. */
7587
6712
  const listOf = (names, joiner) => {
@@ -7638,75 +6763,44 @@ const checkNesting = (template, tags, report) => {
7638
6763
  /** Combines the states that branches end in. What they disagree on becomes unknown. */
7639
6764
  const merge = (state, ends) => {
7640
6765
  const [first, ...rest] = ends;
7641
- let shared = first.open.length;
7642
- for (const end of rest) {
7643
- let same = 0;
7644
- while (same < Math.min(shared, end.open.length) && end.open[same]?.name === first.open[same]?.name) same++;
7645
- shared = same;
7646
- }
7647
- const agree = ends.every((end) => end.open.length === shared) && first.open.length === shared;
7648
- state.open = first.open.slice(0, shared);
7649
- if (!agree) state.open.push({
7650
- name: UNKNOWN,
7651
- children: 0
7652
- });
6766
+ const length = first.top.depth + 1;
6767
+ let shared = length;
6768
+ for (const end of rest) shared = Math.min(shared, agreeing(first.top, end.top));
6769
+ const agree = ends.every((end) => end.top.depth + 1 === shared) && length === shared;
6770
+ state.top = first.top;
6771
+ state.hasChildren = first.hasChildren;
6772
+ state.counts = first.counts;
6773
+ state.ownsCounts = first.ownsCounts;
6774
+ if (shared < length) {
6775
+ let lowest = first.top;
6776
+ while (lowest.depth > shared) lowest = lowest.parent;
6777
+ popThrough(state, lowest);
6778
+ }
6779
+ if (!agree) push(state, UNKNOWN);
7653
6780
  state.heading = ends.every((end) => end.heading === first.heading) ? first.heading : null;
7654
6781
  state.endedParagraph = ends.every((end) => end.endedParagraph === first.endedParagraph) ? first.endedParagraph : null;
7655
6782
  };
7656
6783
  /** Content Kiln can't see, such as an include or an output. It may hold headings unless its parent can't. */
7657
6784
  const hole = (state, mayHoldHeadings) => {
7658
- const top = state.open.at(-1);
7659
- top.children++;
6785
+ state.hasChildren = true;
7660
6786
  if (mayHoldHeadings) state.heading = null;
7661
6787
  };
7662
- /** The nearest open element that decides what may go here: transparent elements such as `<a>` pass it to their parent. */
7663
- const container = (state) => {
7664
- for (let i = state.open.length - 1; i >= 0; i--) {
7665
- const entry = state.open[i];
7666
- if (!TRANSPARENT.has(entry.name)) return entry;
7667
- }
7668
- return state.open[0];
7669
- };
7670
- const popThrough = (state, index) => {
7671
- state.open.length = index;
7672
- };
7673
- /** The index of the innermost open element matching `names`, looking no further than an element in `stop`. */
7674
- const findOpen = (state, names, stop) => {
7675
- const has = (name) => "has" in names ? names.has(name) : names.includes(name);
7676
- for (let i = state.open.length - 1; i > 0; i--) {
7677
- const name = state.open[i].name;
7678
- if (has(name)) return i;
7679
- if (name === UNKNOWN || stop(name)) return -1;
7680
- }
7681
- return -1;
6788
+ /** Ends the innermost open element `search` ends at, when `matches` accepts it. */
6789
+ const close = (state, search, matches) => {
6790
+ const open = findOpen(state, search, matches);
6791
+ if (open) popThrough(state, open);
7682
6792
  };
6793
+ const isCell = (name) => name === "td" || name === "th";
6794
+ const isSection = (name) => name === "thead" || name === "tbody" || name === "tfoot";
7683
6795
  /** Ends open elements the way the HTML parser does when `name` starts, for end tags that can be left out. */
7684
6796
  const impliedEnds = (state, name) => {
7685
- const close = (names, stop) => {
7686
- const index = findOpen(state, names, (open) => stop.includes(open));
7687
- if (index > 0) popThrough(state, index);
7688
- };
7689
- const tableStops = [
7690
- "table",
7691
- "template",
7692
- "html"
7693
- ];
7694
- if (state.open.at(-1)?.name === "head" && !METADATA.has(name)) state.open.pop();
7695
- if (name === "li") {
7696
- const index = findOpen(state, ["li"], (open) => SPECIAL.has(open));
7697
- if (index > 0) popThrough(state, index);
7698
- } else if (name === "dd" || name === "dt") {
7699
- const index = findOpen(state, ["dd", "dt"], (open) => SPECIAL.has(open));
7700
- if (index > 0) popThrough(state, index);
7701
- } else if (name === "td" || name === "th") close(["td", "th"], ["tr", ...tableStops]);
6797
+ if (state.top.name === "head" && !METADATA.has(name)) popThrough(state, state.top);
6798
+ if (name === "li") close(state, "li", (open) => open === "li");
6799
+ else if (name === "dd" || name === "dt") close(state, "definition", (open) => open === "dd" || open === "dt");
6800
+ else if (isCell(name)) close(state, "cell", isCell);
7702
6801
  else if (name === "tr") {
7703
- close(["td", "th"], ["tr", ...tableStops]);
7704
- close(["tr"], [
7705
- "thead",
7706
- "tbody",
7707
- "tfoot",
7708
- ...tableStops
7709
- ]);
6802
+ close(state, "cell", isCell);
6803
+ close(state, "row", (open) => open === "tr");
7710
6804
  } else if ([
7711
6805
  "thead",
7712
6806
  "tbody",
@@ -7714,75 +6808,62 @@ const checkNesting = (template, tags, report) => {
7714
6808
  "caption",
7715
6809
  "colgroup"
7716
6810
  ].includes(name)) {
7717
- close(["td", "th"], ["tr", ...tableStops]);
7718
- close(["tr"], [
7719
- "thead",
7720
- "tbody",
7721
- "tfoot",
7722
- ...tableStops
7723
- ]);
7724
- close([
7725
- "thead",
7726
- "tbody",
7727
- "tfoot"
7728
- ], tableStops);
6811
+ close(state, "cell", isCell);
6812
+ close(state, "row", (open) => open === "tr");
6813
+ close(state, "section", isSection);
7729
6814
  } else if (name === "option" || name === "optgroup") {
7730
- if (state.open.at(-1)?.name === "option") state.open.pop();
7731
- if (name === "optgroup" && state.open.at(-1)?.name === "optgroup") state.open.pop();
6815
+ if (state.top.name === "option") popThrough(state, state.top);
6816
+ if (name === "optgroup" && state.top.name === "optgroup") popThrough(state, state.top);
7732
6817
  } else if (name === "rt" || name === "rp") {
7733
- const top = state.open.at(-1)?.name;
7734
- if (top === "rt" || top === "rp") state.open.pop();
6818
+ const top = state.top.name;
6819
+ if (top === "rt" || top === "rp") popThrough(state, state.top);
7735
6820
  }
7736
6821
  };
7737
- /** Open ancestors that Kiln knows of, innermost first, up to the nearest `<template>`. */
7738
- const ancestors = function* (state) {
7739
- for (let i = state.open.length - 1; i > 0; i--) {
7740
- const name = state.open[i].name;
7741
- if (name === "template") return;
7742
- if (name !== UNKNOWN) yield name;
7743
- }
6822
+ /** The innermost open ancestor `search` ends at, among those Kiln knows of up to the nearest `<template>`. */
6823
+ const ancestor = (state, search) => {
6824
+ const found = find(state.top, search).name;
6825
+ return found === "template" || found === UNKNOWN ? void 0 : found;
7744
6826
  };
7745
6827
  const start = (tag, state) => {
7746
6828
  const { name, span } = tag;
7747
6829
  impliedEnds(state, name);
7748
6830
  if (name === "a" || name === "button") {
7749
- const index = findOpen(state, [name], (open) => name === "a" ? FORMATTING_MARKERS.has(open) : BUTTON_SCOPE.has(open));
7750
- if (index > 0) {
6831
+ const open = findOpen(state, name, (open) => open === name);
6832
+ if (open) {
7751
6833
  report("html-nested-interactive", `<${name}> can't be inside another <${name}>, so the browser ends the first one here`, span);
7752
- popThrough(state, index);
6834
+ popThrough(state, open);
7753
6835
  }
7754
6836
  }
7755
- if (name === "form" && [...ancestors(state)].includes("form")) {
6837
+ if (name === "form" && ancestor(state, "form")) {
7756
6838
  report("html-permitted-content", "<form> can't be inside another <form>, so the browser ignores it", span);
7757
6839
  return;
7758
6840
  }
7759
6841
  if (FLOW.has(name)) {
7760
- const index = findOpen(state, ["p"], (open) => BUTTON_SCOPE.has(open));
7761
- if (index > 0) {
7762
- popThrough(state, index);
6842
+ const open = findOpen(state, "paragraph", (open) => open === "p");
6843
+ if (open) {
6844
+ popThrough(state, open);
7763
6845
  state.endedParagraph = name === "p" ? null : tag;
7764
6846
  }
7765
6847
  }
7766
6848
  if (name === "p") state.endedParagraph = null;
7767
- const parent = state.open.at(-1);
7768
- const holder = container(state);
6849
+ const parent = state.top;
6850
+ const holder = find(state.top, "container");
7769
6851
  const headingAllowed = HEADINGS.has(name) && (holder.name === "summary" || holder.name === "legend");
7770
6852
  if (FLOW.has(name) && PHRASING_ONLY.has(holder.name) && !headingAllowed) report("html-permitted-content", `<${name}> can't be inside <${holder.name}>, which only holds text and inline elements`, span);
7771
6853
  else if (ONLY_CHILDREN[parent.name]?.includes(name) === false) report("html-permitted-content", `<${name}> can't be inside <${parent.name}>, which only holds ${listOf(ONLY_CHILDREN[parent.name] ?? [], "and")}`, span);
7772
6854
  else if (parent.name !== UNKNOWN && parent.name !== "template" && REQUIRED_PARENTS[name]?.includes(parent.name) === false) report("html-permitted-content", `<${name}> must be inside ${listOf(REQUIRED_PARENTS[name] ?? [], "or")}`, span);
7773
- else if (FIRST_CHILD[name] === parent.name && parent.children > 0) report("html-permitted-content", `<${name}> must be the first child of <${parent.name}>`, span);
7774
- if (HEADINGS.has(name) && HEADINGS.has(parent.name)) state.open.pop();
7775
- const above = [...ancestors(state)];
6855
+ else if (FIRST_CHILD[name] === parent.name && state.hasChildren) report("html-permitted-content", `<${name}> must be the first child of <${parent.name}>`, span);
6856
+ if (HEADINGS.has(name) && HEADINGS.has(parent.name)) popThrough(state, parent);
7776
6857
  const isInteractive = interactive(tag);
7777
- const holderOfInteractive = above.find((open) => open === "a" || open === "button");
6858
+ const holderOfInteractive = ancestor(state, "interactive");
7778
6859
  if (isInteractive && holderOfInteractive) report("html-nested-interactive", `<${name}> can't be inside <${holderOfInteractive}>, since interactive elements can't hold each other`, span);
7779
- else if (name === "label" && above.includes("label")) report("html-nested-interactive", "<label> can't be inside another <label>", span);
6860
+ else if (name === "label" && ancestor(state, "label")) report("html-nested-interactive", "<label> can't be inside another <label>", span);
7780
6861
  if (name === "header" || name === "footer") {
7781
- const outer = above.find((open) => open === "header" || open === "footer");
6862
+ const outer = ancestor(state, "headerOrFooter");
7782
6863
  if (outer) report("html-permitted-content", `<${name}> can't be inside <${outer}>`, span);
7783
6864
  }
7784
6865
  if (name === "main") {
7785
- const wrong = above.find((open) => !MAIN_PARENTS.has(open) && !open.includes("-"));
6866
+ const wrong = ancestor(state, "notMainParent");
7786
6867
  if (wrong) report("html-permitted-content", `<main> can't be inside <${wrong}>. It belongs in <body>, a <div> or a <form>`, span);
7787
6868
  }
7788
6869
  const level = levelOf(name);
@@ -7790,30 +6871,24 @@ const checkNesting = (template, tags, report) => {
7790
6871
  if (state.heading !== null && level > state.heading + 1) report("html-heading-order", `<${name}> skips a level after <h${state.heading}>. Use <h${state.heading + 1}>`, span);
7791
6872
  state.heading = level;
7792
6873
  }
7793
- state.open.at(-1).children++;
7794
- if (!(VOID.has(name) || RAW_TEXT.has(name) || FOREIGN.has(name))) state.open.push({
7795
- name,
7796
- children: 0
7797
- });
6874
+ state.hasChildren = true;
6875
+ if (!(VOID.has(name) || RAW_TEXT.has(name) || FOREIGN.has(name))) push(state, name);
7798
6876
  };
7799
6877
  const end = (name, state) => {
7800
6878
  if (name === "p") {
7801
- const index = findOpen(state, ["p"], (open) => BUTTON_SCOPE.has(open));
7802
- if (index > 0) popThrough(state, index);
6879
+ const open = findOpen(state, "paragraph", (open) => open === "p");
6880
+ if (open) popThrough(state, open);
7803
6881
  else if (state.endedParagraph) {
7804
6882
  report("html-permitted-content", `<${state.endedParagraph.name}> can't be inside <p>, so the browser ends the paragraph before it`, state.endedParagraph.span);
7805
6883
  state.endedParagraph = null;
7806
6884
  }
7807
6885
  return;
7808
6886
  }
7809
- const names = HEADINGS.has(name) ? HEADINGS : [name];
7810
- for (let i = state.open.length - 1; i > 0; i--) {
7811
- const open = state.open[i].name;
7812
- if ("has" in names ? names.has(open) : names.includes(open)) {
7813
- popThrough(state, i);
7814
- return;
7815
- }
7816
- }
6887
+ const names = HEADINGS.has(name) ? [...HEADINGS] : [name];
6888
+ if (!names.some((open) => state.counts.get(open))) return;
6889
+ let open = state.top;
6890
+ while (!names.includes(open.name)) open = open.parent;
6891
+ popThrough(state, open);
7817
6892
  };
7818
6893
  /** Walks a body that renders somewhere else, such as a macro, so its parent is unknown. */
7819
6894
  const elsewhere = (body) => walk(body, fresh());
@@ -7837,7 +6912,7 @@ const checkNesting = (template, tags, report) => {
7837
6912
  }
7838
6913
  break;
7839
6914
  case "Output": {
7840
- const holder = container(state).name;
6915
+ const holder = find(state.top, "container").name;
7841
6916
  hole(state, !PHRASING_ONLY.has(holder) && holder !== "p");
7842
6917
  break;
7843
6918
  }