@lucidkiln/core 1.7.0 → 1.8.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-tVX6J33O.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;
@@ -1708,18 +1778,18 @@ const islandProps = (run, span, value) => {
1708
1778
  const seen = /* @__PURE__ */ new Set();
1709
1779
  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
1780
  const charge = (count) => consumeAt(run, span, count);
1711
- const copyHash = (hash, path) => {
1781
+ const copyHash = (hash, path, depth) => {
1712
1782
  const result = {};
1713
1783
  const entries = hash instanceof Map ? [...hash] : Object.entries(hash);
1714
1784
  charge(entries.length);
1715
1785
  for (const [key, item] of entries) {
1716
1786
  if (typeof key !== "string") throw invalid(path, "a hash with a key that isn't a string");
1717
1787
  if (BLOCKED_NAMES.has(key)) continue;
1718
- result[key] = copy(item, path === "" ? key : `${path}.${key}`);
1788
+ result[key] = copy(item, path === "" ? key : `${path}.${key}`, depth + 1);
1719
1789
  }
1720
1790
  return result;
1721
1791
  };
1722
- const copy = (item, path) => {
1792
+ const copy = (item, path, depth) => {
1723
1793
  if (item === null || item === void 0) return null;
1724
1794
  if (typeof item === "string" || typeof item === "boolean") return item;
1725
1795
  if (typeof item === "number") {
@@ -1729,15 +1799,16 @@ const islandProps = (run, span, value) => {
1729
1799
  if (item instanceof Markup) throw invalid(path, "markup. Pass the data, and build the markup in the island");
1730
1800
  if (!Array.isArray(item) && !(item instanceof Map) && !isPlainObject(item)) throw invalid(path, `a ${typeName(item)}`);
1731
1801
  if (seen.has(item)) throw invalid(path, "a value that contains itself");
1802
+ if (depth > 1e3) throw fail(run, span, "too-deep", `"island" props cannot be nested more than ${MAX_DATA_DEPTH} levels deep`);
1732
1803
  seen.add(item);
1733
1804
  if (Array.isArray(item)) charge(item.length);
1734
- const result = Array.isArray(item) ? item.map((entry, index) => copy(entry, `${path}[${index}]`)) : copyHash(item, path);
1805
+ const result = Array.isArray(item) ? item.map((entry, index) => copy(entry, `${path}[${index}]`, depth + 1)) : copyHash(item, path, depth);
1735
1806
  seen.delete(item);
1736
1807
  return result;
1737
1808
  };
1738
1809
  if (value === null || value === void 0) return {};
1739
1810
  if (!(value instanceof Map) && !isPlainObject(value)) throw invalid("", `a ${typeName(value)}, not a hash`);
1740
- return copyHash(value, "");
1811
+ return copyHash(value, "", 1);
1741
1812
  };
1742
1813
  /** A 64-bit hash of `text` as 16 hex digits: two 32-bit multiply-xor lanes, mixed together at the end. */
1743
1814
  const hashId = (text) => {
@@ -1795,23 +1866,20 @@ const recordIsland = (run, span, islands, template, props) => {
1795
1866
  const streamIsland = (run, span, template, props, n) => {
1796
1867
  const page = run.state;
1797
1868
  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
- });
1869
+ lendSteps(page, state);
1804
1870
  const scope = childScope(page.globals);
1805
1871
  const passed = Object.keys(props);
1806
1872
  for (const key of passed) scope[key] = props[key] ?? null;
1807
1873
  addSlotFlags(scope, template, null);
1808
1874
  const out = emptyOut();
1809
1875
  state.root = out;
1810
- return Promise.resolve().then(() => renderTemplate(state, template, scope, out, run.depth + 1, null, passed, null, run, span)).then(() => {
1876
+ return Promise.resolve().then(() => renderTemplate(state, template, scope, out, run.depth + 1, null, passed, null, run.within(null), span)).then(() => {
1877
+ returnSteps(state);
1811
1878
  if (state.signal?.aborted) throw fail(run, span, "aborted", "Render was aborted");
1812
1879
  closeOutlets(state);
1813
1880
  return `<template>${takeOutput(state, out.s)}</template><kiln-island fill="${n}"></kiln-island>`;
1814
1881
  }, (error) => {
1882
+ returnSteps(state);
1815
1883
  throw markCaller(run, span, error);
1816
1884
  });
1817
1885
  };
@@ -1821,8 +1889,10 @@ const ISLAND_SCRIPT = `<script>${islandScript}<\/script>`;
1821
1889
  //#region src/runtime/macros.ts
1822
1890
  /**
1823
1891
  * Calls a macro: binds arguments to parameters in a scope that holds only globals, renders the body and returns it as markup.
1892
+ * A call whose arguments waited passes the capture it started before working them out, to keep its place in the order
1893
+ * of outlets' content.
1824
1894
  */
1825
- const callMacro = (run, span, macro, positional, named) => {
1895
+ const callMacro = (run, span, macro, positional, named, capture) => {
1826
1896
  step(run, span);
1827
1897
  const state = run.state;
1828
1898
  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 +1903,7 @@ const callMacro = (run, span, macro, positional, named) => {
1833
1903
  if (index !== -1 && index < positional.length) throw fail(run, span, "duplicate-argument", `Macro "${macro.name}" got "${key}" both by position and by name`);
1834
1904
  if (index === -1) throw fail(run, span, "unknown-argument", `Macro "${macro.name}" has no parameter "${key}"`, suggest(key, params.map((param) => param.name)));
1835
1905
  }
1836
- const capture = startCapture(run);
1906
+ capture ??= startCapture(run);
1837
1907
  const macroRun = new Run(state, macro.template, run.depth + 1, null, null, capture, run.blockDepth);
1838
1908
  const scope = childScope(state.globals);
1839
1909
  const bind = (index) => {
@@ -3667,7 +3737,10 @@ var Compiler = class {
3667
3737
  };
3668
3738
  Object.defineProperty(call, "length", { value: params.length });
3669
3739
  Object.defineProperty(fn, "length", { value: params.length });
3670
- templateFunctions.set(fn, call);
3740
+ templateFunctions.set(fn, {
3741
+ call,
3742
+ waits
3743
+ });
3671
3744
  return fn;
3672
3745
  },
3673
3746
  async: false,
@@ -3739,10 +3812,11 @@ var Compiler = class {
3739
3812
  named.push(this.#expr(arg.value));
3740
3813
  } else if (arg.type === "Spread") this.#error("invalid-spread", "Spread arguments cannot be passed to macros", arg.span);
3741
3814
  else positional.push(this.#expr(arg.value));
3742
- const values = evalAll([...positional, ...named]);
3815
+ const args = [...positional, ...named];
3816
+ const values = evalAll(args);
3743
3817
  const count = positional.length;
3744
3818
  const span = node.span;
3745
- const invoke = (run, list) => {
3819
+ const invoke = (run, list, capture) => {
3746
3820
  const macro = resolve(run);
3747
3821
  if (!macro) throw fail(run, span, "unknown-macro", `${label} does not exist`);
3748
3822
  let namedValues = null;
@@ -3750,10 +3824,17 @@ var Compiler = class {
3750
3824
  namedValues = {};
3751
3825
  for (let i = 0; i < namedNames.length; i++) setOwn(namedValues, namedNames[i], list[count + i]);
3752
3826
  }
3753
- return callMacro(run, span, macro, list.slice(0, count), namedValues);
3827
+ return callMacro(run, span, macro, list.slice(0, count), namedValues, capture);
3828
+ };
3829
+ if (!args.some((arg) => arg.async)) return {
3830
+ ev: (run, scope) => invoke(run, values(run, scope)),
3831
+ async: true
3754
3832
  };
3755
3833
  return {
3756
- ev: (run, scope) => after(values(run, scope), (list) => invoke(run, list)),
3834
+ ev: (run, scope) => {
3835
+ const capture = startCapture(run);
3836
+ return after(values(run.within(capture), scope), (list) => invoke(run, list, capture));
3837
+ },
3757
3838
  async: true
3758
3839
  };
3759
3840
  }
@@ -4267,9 +4348,13 @@ const loopItems = (run, span, value, wantKeys) => {
4267
4348
  if (typeof value === "object" && typeof value[Symbol.iterator] === "function") {
4268
4349
  const values = [];
4269
4350
  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");
4351
+ try {
4352
+ for (const item of value) {
4353
+ values.push(item);
4354
+ if (values.length > limit) throw fail(run, span, "limit-steps", "Iterable has more items than the step limit");
4355
+ }
4356
+ } catch (error) {
4357
+ throw locate(run, span, error, "Looping over the value");
4273
4358
  }
4274
4359
  return {
4275
4360
  values,
@@ -4284,7 +4369,7 @@ const isPrecompiled = (value) => typeof value === "object" && value !== null &&
4284
4369
  const mismatch = (name, detail) => new KilnRenderError("precompiled-mismatch", `Precompiled template "${name}" ${detail}. Precompile it again`, name);
4285
4370
  /** Compiles a precompiled template: its source, with the generated statements in place of the ones they cover. */
4286
4371
  const compilePrecompiled = (env, name, template) => {
4287
- if (template.kiln !== 5) throw mismatch(name, "was made by another version of Kiln");
4372
+ if (template.kiln !== 6) throw mismatch(name, "was made by another version of Kiln");
4288
4373
  if (template.autoescape !== env.autoescape) throw mismatch(name, "was compiled with another \"autoescape\" option");
4289
4374
  const runs = /* @__PURE__ */ new Map();
4290
4375
  const create = template.create;
@@ -4347,9 +4432,15 @@ const runtime = {
4347
4432
  getPrototypeOf: Object.getPrototypeOf,
4348
4433
  hasOwn: Object.hasOwn,
4349
4434
  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`);
4435
+ /**
4436
+ * Takes the steps counted in a local past `maxSteps`, as `step` does: saves them to `state.steps` and stops the
4437
+ * render, unless more steps can be had. Generated code then carries on from `state.steps`, which as a field read
4438
+ * keeps the local a small integer in optimised code.
4439
+ */
4440
+ stepLimit: (run, span, steps) => {
4441
+ const state = run.state;
4442
+ state.steps = steps;
4443
+ if (!moreSteps(state)) throw stepError(run, span);
4353
4444
  },
4354
4445
  /** Refuses a range longer than the step limit, as `range` does. */
4355
4446
  rangeLimit: (run, span, length) => {
@@ -4833,6 +4924,8 @@ const setsIn = (statements, names = /* @__PURE__ */ new Set()) => {
4833
4924
  } else if (statement.type === "Autoescape" || statement.type === "Slot") setsIn(statement.body, names);
4834
4925
  return names;
4835
4926
  };
4927
+ /** Whether statements place a component whose fills set variables, after which `#component` forgets every lookup. */
4928
+ const fillsSet = (statements) => containsNode(statements, (record) => record.type === "Component" && containsNode(record, (inner) => inner.type === "Set" || inner.type === "SetBlock"));
4836
4929
  /** Characters of text a loop gathers before writing them out. */
4837
4930
  const FLUSH_AT = 4096;
4838
4931
  /** Longest `else if` chain written as one. Longer chains become a flat labelled block. */
@@ -4882,6 +4975,11 @@ const isPlainCode = (value) => `(typeof ${value} === "object" && ${value} !== nu
4882
4975
  const access = (key) => IDENTIFIER$1.test(key) ? `.${key}` : `[${JSON.stringify(key)}]`;
4883
4976
  const isBlank = (statement) => statement.type === "Text" && statement.value.trim() === "";
4884
4977
  const indent = (lines) => lines.map((line) => `\t${line}`);
4978
+ /** Cuts a map or set back to its first `size` entries, which keep the order they were added in. */
4979
+ const keepFirst = (entries, size) => {
4980
+ let i = 0;
4981
+ for (const key of entries.keys()) if (i++ >= size) entries.delete(key);
4982
+ };
4885
4983
  /** Lines without `FORK` markers, for functions that never start passes ahead. */
4886
4984
  const dropForks = (lines) => lines.filter((line) => line.trim() !== FORK);
4887
4985
  var Generator = class {
@@ -4892,7 +4990,7 @@ var Generator = class {
4892
4990
  /** Start and end offsets of every span generated code refers to, flattened. */
4893
4991
  #spans = [];
4894
4992
  #spanIndex = /* @__PURE__ */ new Map();
4895
- /** Declarations made once when the module is loaded, such as built-ins and frozen option hashes. */
4993
+ /** Declarations made once when the module is loaded, such as built-ins and frozen option hashes, by their keys. */
4896
4994
  #constants = [];
4897
4995
  #constantNames = /* @__PURE__ */ new Map();
4898
4996
  #runs = [];
@@ -4905,7 +5003,10 @@ var Generator = class {
4905
5003
  #fn = newFunction();
4906
5004
  /** Plain-object flags of loop variables that generated code reads, so loops only set the ones used. */
4907
5005
  #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. */
5006
+ /**
5007
+ * Loops, slot scopes and labels so far, for local names unique in the module, so a fill's loops never hide the loop
5008
+ * around it, and a loop's own function never hides the names around it.
5009
+ */
4909
5010
  #loops = 0;
4910
5011
  #depth = 0;
4911
5012
  /**
@@ -4928,13 +5029,13 @@ var Generator = class {
4928
5029
  return [
4929
5030
  "// Precompiled by Kiln. Don't edit this file: precompile the template again.",
4930
5031
  "export default {",
4931
- `\tkiln: 5,`,
5032
+ `\tkiln: 6,`,
4932
5033
  `\tautoescape: ${JSON.stringify(this.#env.autoescape)},`,
4933
5034
  `\tsource: ${JSON.stringify(source)},`,
4934
5035
  " create(rt) {",
4935
5036
  `\t\tconst { ${HELPERS.join(", ")} } = rt;`,
4936
5037
  `\t\tconst S = rt.spans([${this.#spans.join(", ")}]);`,
4937
- ...this.#constants.map((line) => `\t\t${line}`),
5038
+ ...this.#constants.map(([, line]) => `\t\t${line}`),
4938
5039
  ...this.#declarations.map((line) => `\t\t${line}`),
4939
5040
  " return [",
4940
5041
  ...this.#runs,
@@ -4961,11 +5062,14 @@ var Generator = class {
4961
5062
  const effects = searchOnly ? [] : list.map((statement) => effectsOf([statement], this.#env));
4962
5063
  const plan = planOf(effects, false);
4963
5064
  const strict = planOf(effects, true);
4964
- const stops = [];
5065
+ let stops = [];
4965
5066
  if (top) list.forEach((statement, index) => {
4966
5067
  if (statement.type === "Block") stops.push(index - 1, index);
4967
5068
  });
4968
- const stopFrom = (index) => Math.min(list.length - 1, ...stops.filter((stop) => stop >= index));
5069
+ const stopFrom = (index) => {
5070
+ stops = stops.filter((stop) => stop >= index);
5071
+ return stops.reduce((first, stop) => stop < first ? stop : first, list.length - 1);
5072
+ };
4969
5073
  let i = 0;
4970
5074
  while (i < list.length) {
4971
5075
  if (searchOnly) {
@@ -5093,8 +5197,9 @@ var Generator = class {
5093
5197
  }
5094
5198
  /**
5095
5199
  * 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.
5200
+ * where the current run of text and outputs starts in `s`, see `#parts`, and `room` is how long `out` and `s` may
5201
+ * get before the output limit needs checking: none in output running ahead, which counts with the output it joins.
5202
+ * Checks the abort signal too, since a function may continue a run after a wait.
5098
5203
  */
5099
5204
  #start(span) {
5100
5205
  const fn = this.#fn;
@@ -5103,6 +5208,7 @@ var Generator = class {
5103
5208
  "const state = run.state;",
5104
5209
  "const maxSteps = state.maxSteps;",
5105
5210
  "const maxSize = state.maxSize;",
5211
+ "const room = out.ahead === null ? maxSize : -1;",
5106
5212
  "let steps = state.steps;",
5107
5213
  "const signal = state.signal;",
5108
5214
  `signal !== undefined && signal.aborted && aborted(run, ${span});`,
@@ -5126,24 +5232,26 @@ var Generator = class {
5126
5232
  return null;
5127
5233
  }
5128
5234
  }
5129
- /** Returns a function that forgets everything generated since, such as constants and queued lists. */
5235
+ /**
5236
+ * Returns a function that forgets everything generated since, such as constants and queued lists. Everything it
5237
+ * restores only grows, so it keeps sizes and cuts back to them, rather than copy what a long run has gathered.
5238
+ */
5130
5239
  #snapshot() {
5131
5240
  const constants = this.#constants.length;
5132
- const names = [...this.#constantNames.keys()];
5133
5241
  const pending = this.#pending.length;
5134
5242
  const declarations = this.#declarations.length;
5135
5243
  const fn = this.#fn;
5136
- const saved = {
5137
- ...fn,
5138
- variables: new Map(fn.variables),
5139
- plainUsed: new Set(fn.plainUsed)
5140
- };
5244
+ const { variables, plainUsed, ...counts } = fn;
5245
+ const variableCount = variables.size;
5246
+ const plainCount = plainUsed.size;
5141
5247
  return () => {
5142
- this.#constants.length = constants;
5143
- for (const key of this.#constantNames.keys()) if (!names.includes(key)) this.#constantNames.delete(key);
5248
+ for (const [key] of this.#constants.splice(constants)) this.#constantNames.delete(key);
5144
5249
  this.#pending.length = pending;
5145
5250
  this.#declarations.length = declarations;
5146
- this.#fn = saved;
5251
+ keepFirst(variables, variableCount);
5252
+ keepFirst(plainUsed, plainCount);
5253
+ Object.assign(fn, counts);
5254
+ this.#fn = fn;
5147
5255
  };
5148
5256
  }
5149
5257
  #children(statement, strategy) {
@@ -5190,7 +5298,7 @@ var Generator = class {
5190
5298
  if (name === void 0) {
5191
5299
  name = `${prefix}${this.#constantNames.size}`;
5192
5300
  this.#constantNames.set(key, name);
5193
- this.#constants.push(`const ${name} = ${value};`);
5301
+ this.#constants.push([key, `const ${name} = ${value};`]);
5194
5302
  }
5195
5303
  return name;
5196
5304
  }
@@ -5199,7 +5307,7 @@ var Generator = class {
5199
5307
  }
5200
5308
  /** Counts one step, as `step` does. */
5201
5309
  #step(span) {
5202
- return `++steps > maxSteps && stepLimit(run, ${span})`;
5310
+ return `++steps > maxSteps && (stepLimit(run, ${span}, steps), steps = state.steps)`;
5203
5311
  }
5204
5312
  /**
5205
5313
  * Counts a step and checks the abort signal, as `step` does: in loops, so a long render stops soon after an abort,
@@ -5284,7 +5392,8 @@ var Generator = class {
5284
5392
  * Checks the output limit where the closures do, given a list's statements and their lines. The closures print each
5285
5393
  * run of text and outputs as one string, see `printParts`: an output fails when that string alone is too long, and
5286
5394
  * 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.
5395
+ * `s` for longer, so it marks where each run starts in `b`, and checks the whole output after each run. Output
5396
+ * running ahead writes each run as the closures do, since others count with it. See `#start`.
5288
5397
  */
5289
5398
  #parts(list, groups) {
5290
5399
  const isPart = (statement) => statement.type === "Text" || statement.type === "Output" && !this.#isHostCall(statement.expression);
@@ -5302,8 +5411,8 @@ var Generator = class {
5302
5411
  if (list.slice(i, end).some((statement) => statement.type === "Output")) run[0] = ["b = s.length;", ...run[0]];
5303
5412
  const at = this.#span(list[i].span);
5304
5413
  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);
5414
+ run[last] = [...run[last], `if (out.s.length + s.length > room) { write(run, out, s, ${at}); s = ""; }`];
5415
+ for (const group of run) result.push(group);
5307
5416
  i = end;
5308
5417
  }
5309
5418
  return result;
@@ -5319,7 +5428,7 @@ var Generator = class {
5319
5428
  return unsupported();
5320
5429
  }
5321
5430
  };
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});`;
5431
+ 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
5432
  if (expression.type === "Literal") return [
5324
5433
  step,
5325
5434
  `s += ${emitted(expression.value)};`,
@@ -5428,14 +5537,15 @@ var Generator = class {
5428
5537
  };
5429
5538
  const looped = context.top && !context.inLoop && effectsOf(statement.body, this.#env).waits ? this.#loopFunction(statement, passContext, loop) : null;
5430
5539
  const range = looped ? null : literalRange(statement.iterable);
5431
- const paused = looped || range ? null : this.#loopGenerator(statement, passContext, loop);
5540
+ const paused = looped ? null : this.#loopGenerator(statement, passContext, loop, range);
5541
+ const generated = paused ? [...paused, ...this.#wait(span, `drive(LG${id}(run, out, 0, ${length}))`, context.top)] : null;
5432
5542
  const body = looped || paused ? [] : this.#body(statement.body, {
5433
5543
  ...passContext,
5434
5544
  inLoop: true
5435
5545
  });
5436
5546
  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)] : [
5547
+ if (range) return this.#rangeLoop(statement, context, loop, range, body, alternate, generated);
5548
+ const passes = looped ? this.#wait(span, `${looped}(run, ${context.scope}, out, ${values}, ${length}, 0, ${length}${hasKeys ? `, ${keys}` : ""})`, context.top) : generated ?? [
5439
5549
  `for (let ${index} = 0; ${index} < ${length}; ${index}++) {`,
5440
5550
  ...indent(this.#pass(loop, true)),
5441
5551
  ...indent(body),
@@ -5456,43 +5566,53 @@ var Generator = class {
5456
5566
  ...hasKeys ? [`\tconst ${keys} = ${items}.keys;`] : [],
5457
5567
  ...indent(passes),
5458
5568
  "}",
5459
- ...sets.flatMap((name) => this.#forget(name))
5569
+ ...(looped || paused) && fillsSet(statement.body) ? this.#forgetAll() : sets.flatMap((name) => this.#forget(name))
5460
5570
  ];
5461
5571
  }
5462
5572
  /**
5463
5573
  * 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.
5574
+ * range's steps and checks its length as `range` does. `generated` runs the passes when they may pause, see
5575
+ * `#loopGenerator`.
5465
5576
  */
5466
- #rangeLoop(statement, context, loop, range, body, alternate) {
5577
+ #rangeLoop(statement, context, loop, range, body, alternate, generated) {
5467
5578
  const node = statement.iterable;
5468
5579
  const rangeSpan = this.#span(node.span);
5469
5580
  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;
5581
+ const { span, length, index } = loop;
5472
5582
  return [
5473
5583
  this.#checkedStep(span),
5474
5584
  `const ${length} = ${count};`,
5475
5585
  `if (${length} > maxSteps) rangeLimit(run, ${rangeSpan}, ${length});`,
5476
- `if ((steps += ${length}) > maxSteps) stepLimit(run, ${rangeSpan});`,
5586
+ `if ((steps += ${length}) > maxSteps) { stepLimit(run, ${rangeSpan}, steps); steps = state.steps; }`,
5477
5587
  ...alternate.length > 0 ? [
5478
5588
  `if (${length} === 0) {`,
5479
5589
  ...indent(alternate),
5480
5590
  "}"
5481
5591
  ] : [],
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))
5592
+ ...generated ?? [
5593
+ `for (let ${index} = 0; ${index} < ${length}; ${index}++) {`,
5594
+ ...indent(this.#rangePass(loop, range)),
5595
+ ...indent(body),
5596
+ `\tif (s.length > ${FLUSH_AT}) {`,
5597
+ `\t\twrite(run, out, s, ${span});`,
5598
+ " s = \"\";",
5599
+ " }",
5600
+ "}"
5601
+ ],
5602
+ ...generated && fillsSet(statement.body) ? this.#forgetAll() : loop.sets.flatMap((name) => this.#forget(name))
5603
+ ];
5604
+ }
5605
+ /** The start of a pass over a range: counts a step, makes the pass's scope and binds the loop's variables. */
5606
+ #rangePass(loop, range) {
5607
+ const { span, index, value, key, hasKeys } = loop;
5608
+ const direction = range.to < range.from ? "-" : "+";
5609
+ return [
5610
+ this.#checkedStep(span),
5611
+ ...loop.scope ? [`const ${loop.scope} = childScope(${loop.outer});`, ...loop.sets.flatMap((name) => this.#forget(name))] : [],
5612
+ `const ${value} = ${range.from} ${direction} ${index};`,
5613
+ ...this.#plainUsed.has(`p${value}`) ? [`const p${value} = false;`] : [],
5614
+ ...hasKeys ? [`const ${key} = ${index};`] : [],
5615
+ ...hasKeys && this.#plainUsed.has(`p${key}`) ? [`const p${key} = false;`] : []
5496
5616
  ];
5497
5617
  }
5498
5618
  /**
@@ -5627,10 +5747,10 @@ var Generator = class {
5627
5747
  * 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
5748
  * the index to start at. It is declared where the loop is, so it reads the locals around it, such as the loops
5629
5749
  * 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.
5750
+ * see `startAhead`. The loop then stops after that pass and waits for them. A loop over a `range` counts its passes
5751
+ * rather than read its items. Returns the generator's lines, or null when no pass waits.
5632
5752
  */
5633
- #loopGenerator(statement, context, loop) {
5753
+ #loopGenerator(statement, context, loop, range) {
5634
5754
  if (!effectsOf(statement.body, this.#env).waits) return null;
5635
5755
  const outer = this.#fn;
5636
5756
  const restore = this.#snapshot();
@@ -5661,7 +5781,7 @@ var Generator = class {
5661
5781
  `${tabs}}`
5662
5782
  ];
5663
5783
  });
5664
- const pass = this.#pass(loop, true);
5784
+ const pass = range ? this.#rangePass(loop, range) : this.#pass(loop, true);
5665
5785
  const reads = this.#fn.reads;
5666
5786
  return [
5667
5787
  `const ${name} = function* (run, out, ${index}, stop) {`,
@@ -5688,6 +5808,7 @@ var Generator = class {
5688
5808
  " state.steps = steps;",
5689
5809
  ...reads ? [" at = null;"] : [],
5690
5810
  `\tyield ${ahead}.join();`,
5811
+ " steps = state.steps;",
5691
5812
  "}",
5692
5813
  "state.steps = steps;",
5693
5814
  `write(run, out, s, ${span});`
@@ -5720,8 +5841,12 @@ var Generator = class {
5720
5841
  }
5721
5842
  /** Writes out `FORGET_ALL`, once the current function's lookups are all known. */
5722
5843
  #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);
5844
+ let forget;
5845
+ return lines.map((line) => {
5846
+ if (!line.endsWith(FORGET_ALL)) return line;
5847
+ forget ??= [...this.#fn.variables.values()].map(({ value }) => `${value} = undefined;`).join(" ");
5848
+ return line.slice(0, -7) + forget;
5849
+ });
5725
5850
  }
5726
5851
  /** Forgets lookups of a variable that `set` may have changed. */
5727
5852
  #forget(name) {
@@ -5873,7 +5998,7 @@ var Generator = class {
5873
5998
  const passed = this.#constant(`passed:${JSON.stringify(keys)}`, "P", `Object.freeze(${JSON.stringify(keys)})`);
5874
5999
  return {
5875
6000
  lines,
5876
- charge: (span) => keys.length === 0 ? [] : [`if ((steps += ${keys.length}) > maxSteps) stepLimit(run, ${span});`],
6001
+ charge: (span) => keys.length === 0 ? [] : [`if ((steps += ${keys.length}) > maxSteps) { stepLimit(run, ${span}, steps); steps = state.steps; }`],
5877
6002
  embed: (span, name, slots, ignoreMissing) => {
5878
6003
  const rest = `${scope}, ${passed}, ${slots}, ${ignoreMissing})`;
5879
6004
  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 +6035,13 @@ var Generator = class {
5910
6035
  const span = this.#span(statement.span);
5911
6036
  const fill = this.#temp();
5912
6037
  const sets = [...setsIn(statement.body)];
5913
- const scope = sets.length > 0 ? this.#temp() : context.scope;
6038
+ const scope = sets.length > 0 ? `sl${this.#loops++}` : context.scope;
5914
6039
  let fallback = this.#body(statement.body, {
5915
6040
  ...context,
5916
6041
  scope
5917
6042
  });
5918
6043
  if (sets.length > 0) fallback = [
5919
- `${scope} = childScope(${context.scope});`,
6044
+ `const ${scope} = childScope(${context.scope});`,
5920
6045
  ...fallback,
5921
6046
  ...sets.flatMap((name) => this.#forget(name))
5922
6047
  ];
@@ -6276,1098 +6401,6 @@ const renderFills = (run) => {
6276
6401
  return from(0);
6277
6402
  };
6278
6403
  //#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
6404
  //#region src/html/options.ts
7372
6405
  const HTML_CHECKS = [
7373
6406
  "html-obsolete-element",
@@ -7569,19 +6602,105 @@ const FORMATTING_MARKERS = /* @__PURE__ */ new Set([
7569
6602
  "template",
7570
6603
  "th"
7571
6604
  ]);
6605
+ const TABLE_STOPS = /* @__PURE__ */ new Set([
6606
+ "table",
6607
+ "template",
6608
+ "html"
6609
+ ]);
6610
+ const ROW_STOPS = /* @__PURE__ */ new Set(["tr", ...TABLE_STOPS]);
6611
+ const SECTION_STOPS = /* @__PURE__ */ new Set([
6612
+ "thead",
6613
+ "tbody",
6614
+ "tfoot",
6615
+ ...TABLE_STOPS
6616
+ ]);
6617
+ /**
6618
+ * The searches the rules make through the open elements, innermost first. Each ends at the first element it accepts,
6619
+ * which the rule then reads. Searches for an element to end, as the HTML parser makes, also end at an unknown element.
6620
+ */
6621
+ const SEARCHES = {
6622
+ li: (name) => name === "li" || name === UNKNOWN || SPECIAL.has(name),
6623
+ definition: (name) => name === "dd" || name === "dt" || name === UNKNOWN || SPECIAL.has(name),
6624
+ cell: (name) => name === "td" || name === "th" || name === UNKNOWN || ROW_STOPS.has(name),
6625
+ row: (name) => name === "tr" || name === UNKNOWN || SECTION_STOPS.has(name),
6626
+ section: (name) => name === "thead" || name === "tbody" || name === "tfoot" || name === UNKNOWN || TABLE_STOPS.has(name),
6627
+ a: (name) => name === "a" || name === UNKNOWN || FORMATTING_MARKERS.has(name),
6628
+ button: (name) => name === "button" || name === UNKNOWN || BUTTON_SCOPE.has(name),
6629
+ paragraph: (name) => name === "p" || name === UNKNOWN || BUTTON_SCOPE.has(name),
6630
+ form: (name) => name === "form" || name === "template",
6631
+ label: (name) => name === "label" || name === "template",
6632
+ interactive: (name) => name === "a" || name === "button" || name === "template",
6633
+ headerOrFooter: (name) => name === "header" || name === "footer" || name === "template",
6634
+ notMainParent: (name) => name === "template" || name !== UNKNOWN && !MAIN_PARENTS.has(name) && !name.includes("-"),
6635
+ container: (name) => !TRANSPARENT.has(name)
6636
+ };
6637
+ const entry = (name, parent) => ({
6638
+ name,
6639
+ parent,
6640
+ depth: parent ? parent.depth + 1 : 0,
6641
+ found: {}
6642
+ });
6643
+ /** Where `search` from `from` ends. The bottom ends every search. */
6644
+ const find = (from, search) => {
6645
+ const accepts = SEARCHES[search];
6646
+ let at = from;
6647
+ let found = at.found[search];
6648
+ while (found === void 0) if (at.parent === null || accepts(at.name)) found = at;
6649
+ else {
6650
+ at = at.parent;
6651
+ found = at.found[search];
6652
+ }
6653
+ for (let walked = from; walked !== at; walked = walked.parent) walked.found[search] = found;
6654
+ at.found[search] = found;
6655
+ return found;
6656
+ };
7572
6657
  const fresh = () => ({
7573
- open: [{
7574
- name: UNKNOWN,
7575
- children: 0
7576
- }],
6658
+ top: entry(UNKNOWN, null),
6659
+ hasChildren: false,
6660
+ counts: /* @__PURE__ */ new Map(),
6661
+ ownsCounts: true,
7577
6662
  heading: null,
7578
6663
  endedParagraph: null
7579
6664
  });
7580
- const copy = (state) => ({
7581
- open: state.open.map((entry) => ({ ...entry })),
7582
- heading: state.heading,
7583
- endedParagraph: state.endedParagraph
7584
- });
6665
+ const copy = (state) => {
6666
+ state.ownsCounts = false;
6667
+ return { ...state };
6668
+ };
6669
+ const count = (state, name, change) => {
6670
+ if (!state.ownsCounts) {
6671
+ state.counts = new Map(state.counts);
6672
+ state.ownsCounts = true;
6673
+ }
6674
+ state.counts.set(name, (state.counts.get(name) ?? 0) + change);
6675
+ };
6676
+ const push = (state, name) => {
6677
+ state.top = entry(name, state.top);
6678
+ state.hasChildren = false;
6679
+ count(state, name, 1);
6680
+ };
6681
+ /** Ends `open` and the elements inside it. */
6682
+ const popThrough = (state, open) => {
6683
+ for (let at = state.top; at !== open.parent; at = at.parent) count(state, at.name, -1);
6684
+ state.top = open.parent;
6685
+ state.hasChildren = true;
6686
+ };
6687
+ /** The element `search` ends at, when `matches` accepts it. Searches never end at the bottom, which is unknown. */
6688
+ const findOpen = (state, search, matches) => {
6689
+ const found = find(state.top, search);
6690
+ return found.depth > 0 && matches(found.name) ? found : null;
6691
+ };
6692
+ /** How many of the leading open elements two states, which come from one state, agree on. */
6693
+ const agreeing = (a, b) => {
6694
+ while (a.depth > b.depth) a = a.parent;
6695
+ while (b.depth > a.depth) b = b.parent;
6696
+ let same = a.depth + 1;
6697
+ while (a !== b) {
6698
+ if (a.name !== b.name) same = a.depth;
6699
+ a = a.parent;
6700
+ b = b.parent;
6701
+ }
6702
+ return same;
6703
+ };
7585
6704
  const levelOf = (name) => HEADINGS.has(name) ? Number(name.slice(1)) : null;
7586
6705
  /** Lists names as `<a>`, `<a> and <b>`, or `<a>, <b> and <c>`. */
7587
6706
  const listOf = (names, joiner) => {
@@ -7638,75 +6757,44 @@ const checkNesting = (template, tags, report) => {
7638
6757
  /** Combines the states that branches end in. What they disagree on becomes unknown. */
7639
6758
  const merge = (state, ends) => {
7640
6759
  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
- });
6760
+ const length = first.top.depth + 1;
6761
+ let shared = length;
6762
+ for (const end of rest) shared = Math.min(shared, agreeing(first.top, end.top));
6763
+ const agree = ends.every((end) => end.top.depth + 1 === shared) && length === shared;
6764
+ state.top = first.top;
6765
+ state.hasChildren = first.hasChildren;
6766
+ state.counts = first.counts;
6767
+ state.ownsCounts = first.ownsCounts;
6768
+ if (shared < length) {
6769
+ let lowest = first.top;
6770
+ while (lowest.depth > shared) lowest = lowest.parent;
6771
+ popThrough(state, lowest);
6772
+ }
6773
+ if (!agree) push(state, UNKNOWN);
7653
6774
  state.heading = ends.every((end) => end.heading === first.heading) ? first.heading : null;
7654
6775
  state.endedParagraph = ends.every((end) => end.endedParagraph === first.endedParagraph) ? first.endedParagraph : null;
7655
6776
  };
7656
6777
  /** Content Kiln can't see, such as an include or an output. It may hold headings unless its parent can't. */
7657
6778
  const hole = (state, mayHoldHeadings) => {
7658
- const top = state.open.at(-1);
7659
- top.children++;
6779
+ state.hasChildren = true;
7660
6780
  if (mayHoldHeadings) state.heading = null;
7661
6781
  };
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;
6782
+ /** Ends the innermost open element `search` ends at, when `matches` accepts it. */
6783
+ const close = (state, search, matches) => {
6784
+ const open = findOpen(state, search, matches);
6785
+ if (open) popThrough(state, open);
7682
6786
  };
6787
+ const isCell = (name) => name === "td" || name === "th";
6788
+ const isSection = (name) => name === "thead" || name === "tbody" || name === "tfoot";
7683
6789
  /** Ends open elements the way the HTML parser does when `name` starts, for end tags that can be left out. */
7684
6790
  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]);
6791
+ if (state.top.name === "head" && !METADATA.has(name)) popThrough(state, state.top);
6792
+ if (name === "li") close(state, "li", (open) => open === "li");
6793
+ else if (name === "dd" || name === "dt") close(state, "definition", (open) => open === "dd" || open === "dt");
6794
+ else if (isCell(name)) close(state, "cell", isCell);
7702
6795
  else if (name === "tr") {
7703
- close(["td", "th"], ["tr", ...tableStops]);
7704
- close(["tr"], [
7705
- "thead",
7706
- "tbody",
7707
- "tfoot",
7708
- ...tableStops
7709
- ]);
6796
+ close(state, "cell", isCell);
6797
+ close(state, "row", (open) => open === "tr");
7710
6798
  } else if ([
7711
6799
  "thead",
7712
6800
  "tbody",
@@ -7714,75 +6802,62 @@ const checkNesting = (template, tags, report) => {
7714
6802
  "caption",
7715
6803
  "colgroup"
7716
6804
  ].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);
6805
+ close(state, "cell", isCell);
6806
+ close(state, "row", (open) => open === "tr");
6807
+ close(state, "section", isSection);
7729
6808
  } 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();
6809
+ if (state.top.name === "option") popThrough(state, state.top);
6810
+ if (name === "optgroup" && state.top.name === "optgroup") popThrough(state, state.top);
7732
6811
  } else if (name === "rt" || name === "rp") {
7733
- const top = state.open.at(-1)?.name;
7734
- if (top === "rt" || top === "rp") state.open.pop();
6812
+ const top = state.top.name;
6813
+ if (top === "rt" || top === "rp") popThrough(state, state.top);
7735
6814
  }
7736
6815
  };
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
- }
6816
+ /** The innermost open ancestor `search` ends at, among those Kiln knows of up to the nearest `<template>`. */
6817
+ const ancestor = (state, search) => {
6818
+ const found = find(state.top, search).name;
6819
+ return found === "template" || found === UNKNOWN ? void 0 : found;
7744
6820
  };
7745
6821
  const start = (tag, state) => {
7746
6822
  const { name, span } = tag;
7747
6823
  impliedEnds(state, name);
7748
6824
  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) {
6825
+ const open = findOpen(state, name, (open) => open === name);
6826
+ if (open) {
7751
6827
  report("html-nested-interactive", `<${name}> can't be inside another <${name}>, so the browser ends the first one here`, span);
7752
- popThrough(state, index);
6828
+ popThrough(state, open);
7753
6829
  }
7754
6830
  }
7755
- if (name === "form" && [...ancestors(state)].includes("form")) {
6831
+ if (name === "form" && ancestor(state, "form")) {
7756
6832
  report("html-permitted-content", "<form> can't be inside another <form>, so the browser ignores it", span);
7757
6833
  return;
7758
6834
  }
7759
6835
  if (FLOW.has(name)) {
7760
- const index = findOpen(state, ["p"], (open) => BUTTON_SCOPE.has(open));
7761
- if (index > 0) {
7762
- popThrough(state, index);
6836
+ const open = findOpen(state, "paragraph", (open) => open === "p");
6837
+ if (open) {
6838
+ popThrough(state, open);
7763
6839
  state.endedParagraph = name === "p" ? null : tag;
7764
6840
  }
7765
6841
  }
7766
6842
  if (name === "p") state.endedParagraph = null;
7767
- const parent = state.open.at(-1);
7768
- const holder = container(state);
6843
+ const parent = state.top;
6844
+ const holder = find(state.top, "container");
7769
6845
  const headingAllowed = HEADINGS.has(name) && (holder.name === "summary" || holder.name === "legend");
7770
6846
  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
6847
  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
6848
  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)];
6849
+ else if (FIRST_CHILD[name] === parent.name && state.hasChildren) report("html-permitted-content", `<${name}> must be the first child of <${parent.name}>`, span);
6850
+ if (HEADINGS.has(name) && HEADINGS.has(parent.name)) popThrough(state, parent);
7776
6851
  const isInteractive = interactive(tag);
7777
- const holderOfInteractive = above.find((open) => open === "a" || open === "button");
6852
+ const holderOfInteractive = ancestor(state, "interactive");
7778
6853
  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);
6854
+ else if (name === "label" && ancestor(state, "label")) report("html-nested-interactive", "<label> can't be inside another <label>", span);
7780
6855
  if (name === "header" || name === "footer") {
7781
- const outer = above.find((open) => open === "header" || open === "footer");
6856
+ const outer = ancestor(state, "headerOrFooter");
7782
6857
  if (outer) report("html-permitted-content", `<${name}> can't be inside <${outer}>`, span);
7783
6858
  }
7784
6859
  if (name === "main") {
7785
- const wrong = above.find((open) => !MAIN_PARENTS.has(open) && !open.includes("-"));
6860
+ const wrong = ancestor(state, "notMainParent");
7786
6861
  if (wrong) report("html-permitted-content", `<main> can't be inside <${wrong}>. It belongs in <body>, a <div> or a <form>`, span);
7787
6862
  }
7788
6863
  const level = levelOf(name);
@@ -7790,30 +6865,24 @@ const checkNesting = (template, tags, report) => {
7790
6865
  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
6866
  state.heading = level;
7792
6867
  }
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
- });
6868
+ state.hasChildren = true;
6869
+ if (!(VOID.has(name) || RAW_TEXT.has(name) || FOREIGN.has(name))) push(state, name);
7798
6870
  };
7799
6871
  const end = (name, state) => {
7800
6872
  if (name === "p") {
7801
- const index = findOpen(state, ["p"], (open) => BUTTON_SCOPE.has(open));
7802
- if (index > 0) popThrough(state, index);
6873
+ const open = findOpen(state, "paragraph", (open) => open === "p");
6874
+ if (open) popThrough(state, open);
7803
6875
  else if (state.endedParagraph) {
7804
6876
  report("html-permitted-content", `<${state.endedParagraph.name}> can't be inside <p>, so the browser ends the paragraph before it`, state.endedParagraph.span);
7805
6877
  state.endedParagraph = null;
7806
6878
  }
7807
6879
  return;
7808
6880
  }
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
- }
6881
+ const names = HEADINGS.has(name) ? [...HEADINGS] : [name];
6882
+ if (!names.some((open) => state.counts.get(open))) return;
6883
+ let open = state.top;
6884
+ while (!names.includes(open.name)) open = open.parent;
6885
+ popThrough(state, open);
7817
6886
  };
7818
6887
  /** Walks a body that renders somewhere else, such as a macro, so its parent is unknown. */
7819
6888
  const elsewhere = (body) => walk(body, fresh());
@@ -7837,7 +6906,7 @@ const checkNesting = (template, tags, report) => {
7837
6906
  }
7838
6907
  break;
7839
6908
  case "Output": {
7840
- const holder = container(state).name;
6909
+ const holder = find(state.top, "container").name;
7841
6910
  hole(state, !PHRASING_ONLY.has(holder) && holder !== "p");
7842
6911
  break;
7843
6912
  }