@ecopages/core 0.2.0-rc.10 → 0.2.0-rc.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (159) hide show
  1. package/README.md +0 -9
  2. package/package.json +3 -144
  3. package/src/adapters/README.md +8 -2
  4. package/src/adapters/abstract/application-adapter.d.ts +6 -32
  5. package/src/adapters/abstract/application-adapter.js +6 -45
  6. package/src/adapters/abstract/ws-pattern-matcher.d.ts +0 -5
  7. package/src/adapters/abstract/ws-pattern-matcher.js +0 -9
  8. package/src/adapters/bun/create-app.d.ts +8 -12
  9. package/src/adapters/bun/create-app.js +13 -55
  10. package/src/adapters/bun/hmr-manager.d.ts +0 -1
  11. package/src/adapters/bun/hmr-manager.js +2 -4
  12. package/src/adapters/bun/server-adapter.d.ts +9 -19
  13. package/src/adapters/bun/server-adapter.js +19 -66
  14. package/src/adapters/bun/static-preview-host.d.ts +1 -0
  15. package/src/adapters/bun/static-preview-host.js +1 -1
  16. package/src/adapters/create-app.d.ts +1 -1
  17. package/src/adapters/create-app.js +2 -1
  18. package/src/adapters/node/create-app.d.ts +4 -8
  19. package/src/adapters/node/create-app.js +7 -12
  20. package/src/adapters/node/runtime-host.d.ts +10 -10
  21. package/src/adapters/node/runtime-host.js +4 -4
  22. package/src/adapters/node/server-adapter-dependencies.d.ts +2 -10
  23. package/src/adapters/node/server-adapter-dependencies.js +8 -13
  24. package/src/adapters/node/server-adapter.d.ts +25 -31
  25. package/src/adapters/node/server-adapter.js +43 -64
  26. package/src/adapters/shared/hmr/shared-hmr-manager.d.ts +0 -4
  27. package/src/adapters/shared/hmr/shared-hmr-manager.js +0 -12
  28. package/src/adapters/shared/http/api-request-pipeline.d.ts +27 -1
  29. package/src/adapters/shared/http/api-request-pipeline.js +31 -16
  30. package/src/adapters/shared/http/fs-server-response-factory.d.ts +0 -1
  31. package/src/adapters/shared/http/fs-server-response-factory.js +0 -3
  32. package/src/adapters/shared/runtime/collect-dev-prewarm-plan.d.ts +1 -3
  33. package/src/adapters/shared/runtime/collect-dev-prewarm-plan.js +1 -4
  34. package/src/adapters/shared/runtime/runtime-app-bootstrap.d.ts +0 -10
  35. package/src/adapters/shared/runtime/runtime-app-bootstrap.js +0 -7
  36. package/src/adapters/shared/runtime/runtime-host.d.ts +5 -2
  37. package/src/adapters/shared/runtime/runtime-server-lifecycle.d.ts +1 -1
  38. package/src/adapters/shared/runtime/runtime-server-lifecycle.js +1 -1
  39. package/src/adapters/shared/runtime/server-adapter.d.ts +13 -0
  40. package/src/adapters/shared/runtime/server-adapter.js +22 -0
  41. package/src/adapters/shared/ws/node-http-websocket-upgrades.d.ts +9 -1
  42. package/src/adapters/shared/ws/node-http-websocket-upgrades.js +8 -2
  43. package/src/build/README.md +5 -6
  44. package/src/build/cache/cache-constants.d.ts +0 -2
  45. package/src/build/cache/cache-constants.js +0 -2
  46. package/src/build/cache/cache-keys.d.ts +0 -2
  47. package/src/build/cache/cache-keys.js +0 -2
  48. package/src/build/cache/output-imports.d.ts +27 -0
  49. package/src/build/cache/output-imports.js +80 -0
  50. package/src/build/cache/pages-unified-graph-build.d.ts +6 -1
  51. package/src/build/cache/pages-unified-graph-build.js +42 -17
  52. package/src/build/cache/production-build-cache.d.ts +2 -2
  53. package/src/build/cache/production-build-cache.js +2 -2
  54. package/src/build/cache/server-entry-build-cache.d.ts +1 -2
  55. package/src/build/cache/server-entry-build-cache.js +4 -5
  56. package/src/build/contracts/build-contracts.d.ts +1 -13
  57. package/src/build/rolldown/runtime-build-output-normalizer.js +3 -6
  58. package/src/build/runtime/build-request-identity.d.ts +2 -6
  59. package/src/build/runtime/build-request-identity.js +2 -8
  60. package/src/build/runtime/deduping-build-executor.d.ts +0 -1
  61. package/src/build/runtime/deduping-build-executor.js +0 -1
  62. package/src/cache/index.d.ts +1 -1
  63. package/src/cache/index.js +1 -1
  64. package/src/cache/module-parse-cache.d.ts +2 -29
  65. package/src/cache/module-parse-cache.js +6 -39
  66. package/src/config/README.md +3 -3
  67. package/src/config/apply-user-config.d.ts +3 -1
  68. package/src/config/apply-user-config.js +3 -2
  69. package/src/config/config-builder.d.ts +1 -0
  70. package/src/config/config-builder.js +2 -2
  71. package/src/config/constants.d.ts +0 -4
  72. package/src/config/constants.js +0 -4
  73. package/src/config/index.d.ts +1 -1
  74. package/src/config/index.js +1 -1
  75. package/src/config/load-eco-config.d.ts +1 -1
  76. package/src/config/load-eco-config.js +18 -11
  77. package/src/config/resolve-eco-config-path.d.ts +9 -0
  78. package/src/config/resolve-eco-config-path.js +11 -0
  79. package/src/config/server-config-bundle.js +2 -2
  80. package/src/config/user-config-types.d.ts +9 -3
  81. package/src/dev/host-runtime.d.ts +0 -1
  82. package/src/dev/host-runtime.js +0 -3
  83. package/src/dev/sc-server.d.ts +4 -1
  84. package/src/dev/sc-server.js +11 -20
  85. package/src/dev/transform-server/dev-transform-import-rewriter.js +2 -2
  86. package/src/hmr/hmr-file-change-prep.d.ts +0 -1
  87. package/src/hmr/hmr-file-change-prep.js +2 -5
  88. package/src/hmr/hmr-strategy.d.ts +3 -8
  89. package/src/hmr/hmr-strategy.js +3 -8
  90. package/src/index.browser.d.ts +1 -2
  91. package/src/index.browser.js +1 -2
  92. package/src/index.d.ts +5 -6
  93. package/src/index.js +5 -6
  94. package/src/islands/island-host.d.ts +0 -9
  95. package/src/islands/island-host.js +1 -13
  96. package/src/plugins/component-import-discovery.js +2 -2
  97. package/src/plugins/eco-component-meta-plugin.js +5 -5
  98. package/src/plugins/integration-plugin.d.ts +0 -1
  99. package/src/plugins/integration-plugin.js +0 -4
  100. package/src/route-renderer/orchestration/document-shell/document-shell-render.service.js +1 -4
  101. package/src/route-renderer/orchestration/integration-renderer.d.ts +0 -6
  102. package/src/route-renderer/orchestration/integration-renderer.js +1 -11
  103. package/src/route-renderer/orchestration/integration-renderer.test-fixtures.js +1 -1
  104. package/src/route-renderer/orchestration/page-browser-graph/page-browser-graph-session.d.ts +1 -1
  105. package/src/route-renderer/orchestration/page-browser-graph/page-browser-graph-session.js +1 -1
  106. package/src/services/README.md +1 -1
  107. package/src/services/assets/browser-bundle.service.d.ts +1 -6
  108. package/src/services/error-pages/default-error-pages.d.ts +1 -6
  109. package/src/services/error-pages/default-error-pages.js +0 -8
  110. package/src/services/html/html-rewriter.d.ts +77 -0
  111. package/src/services/html/html-rewriter.js +751 -0
  112. package/src/services/html/html-rewriter.parity.test.bun.d.ts +1 -0
  113. package/src/services/html/html-rewriter.parity.test.bun.js +74 -0
  114. package/src/services/html/html-transformer.service.d.ts +26 -39
  115. package/src/services/html/html-transformer.service.js +81 -153
  116. package/src/services/invalidation/development-invalidation.service.d.ts +2 -19
  117. package/src/services/invalidation/development-invalidation.service.js +1 -39
  118. package/src/services/module-loading/README.md +1 -1
  119. package/src/services/module-loading/app-module-loader.service.d.ts +0 -2
  120. package/src/services/module-loading/app-server-module-transpiler.service.d.ts +1 -1
  121. package/src/services/module-loading/app-server-module-transpiler.service.js +0 -10
  122. package/src/services/module-loading/collection-server-module-build.service.d.ts +0 -1
  123. package/src/services/module-loading/collection-server-module-build.service.js +0 -3
  124. package/src/services/module-loading/host-module-loader-registry.d.ts +0 -1
  125. package/src/services/module-loading/host-module-loader-registry.js +0 -3
  126. package/src/services/module-loading/route-module-build-cache-registry.d.ts +0 -4
  127. package/src/services/module-loading/route-module-build-cache-registry.js +0 -4
  128. package/src/services/module-loading/route-module-build-cache.store.d.ts +3 -0
  129. package/src/services/module-loading/route-module-build-cache.store.js +18 -5
  130. package/src/services/module-loading/route-module-build-manifest.d.ts +6 -1
  131. package/src/services/module-loading/route-module-build-manifest.js +1 -2
  132. package/src/services/module-loading/route-module-dependency-hasher.d.ts +3 -2
  133. package/src/services/module-loading/server-module-transpiler.service.d.ts +1 -15
  134. package/src/services/module-loading/server-module-transpiler.service.js +0 -24
  135. package/src/services/runtime-state/entrypoint-dependency-graph.service.js +0 -12
  136. package/src/services/runtime-state/server-invalidation-state.service.d.ts +4 -2
  137. package/src/services/runtime-state/server-invalidation-state.service.js +7 -14
  138. package/src/types/internal-types.d.ts +0 -38
  139. package/src/types/public-types.d.ts +0 -112
  140. package/src/watchers/project-watcher.d.ts +0 -15
  141. package/src/watchers/project-watcher.js +1 -27
  142. package/src/watchers/project-watcher.test-helpers.d.ts +10 -1
  143. package/src/watchers/project-watcher.test-helpers.js +12 -0
  144. package/src/adapters/abstract/router-adapter.d.ts +0 -26
  145. package/src/adapters/abstract/router-adapter.js +0 -13
  146. package/src/adapters/bun/index.d.ts +0 -2
  147. package/src/adapters/bun/index.js +0 -2
  148. package/src/adapters/index.d.ts +0 -2
  149. package/src/adapters/index.js +0 -2
  150. package/src/eco/eco.utils.d.ts +0 -1
  151. package/src/eco/eco.utils.js +0 -1
  152. package/src/services/cache/index.d.ts +0 -9
  153. package/src/services/cache/index.js +0 -8
  154. package/src/services/html/html-rewriter-provider.service.d.ts +0 -40
  155. package/src/services/html/html-rewriter-provider.service.js +0 -68
  156. package/src/services/module-loading/route-module-build-cache.d.ts +0 -4
  157. package/src/services/module-loading/route-module-build-cache.js +0 -3
  158. package/src/services/runtime-state/dev-graph.service.d.ts +0 -118
  159. package/src/services/runtime-state/dev-graph.service.js +0 -170
@@ -0,0 +1,751 @@
1
+ /**
2
+ * Streaming HTML rewriter implementing the subset of Bun's `HTMLRewriter` API that
3
+ * Ecopages uses, so the same rewrite runs on Bun and Node without a wasm build of
4
+ * lol-html.
5
+ *
6
+ * @remarks
7
+ * Supported selectors are tag names and `*`; anything else throws so an
8
+ * unsupported selector never silently matches nothing. Handlers are synchronous.
9
+ *
10
+ * Output follows lol-html (checked against Bun's native `HTMLRewriter`) on the
11
+ * behaviour Ecopages relies on: comments, doctypes and the content of raw-text
12
+ * elements (`script` with its escape states, `style`, `textarea`, `title`,
13
+ * `noscript`, `iframe`, `xmp`, `noembed`, `noframes`, `plaintext`) never produce
14
+ * tags; `>` inside quoted attribute values does not end a tag; tag matching is
15
+ * case-insensitive; untouched attributes keep their original text.
16
+ *
17
+ * There is no tree construction. An end tag closes the nearest open element with
18
+ * the same name, and `append`/`after` content of elements that it closes
19
+ * implicitly, or that are still open at the end of the document, is dropped.
20
+ */
21
+ export class HtmlRewriter {
22
+ handlers = [];
23
+ on(selector, handlers) {
24
+ const tagName = selector.trim().toLowerCase();
25
+ if (tagName !== '*' && !/^[a-z][a-z0-9-]*$/.test(tagName)) {
26
+ throw new Error(`HtmlRewriter supports tag-name and "*" selectors only; got "${selector}".`);
27
+ }
28
+ this.handlers.push({ tagName, handlers });
29
+ return this;
30
+ }
31
+ transform(input) {
32
+ if (typeof input === 'string') {
33
+ const session = new RewriteSession(this.handlers);
34
+ return `${session.write(input)}${session.end()}`;
35
+ }
36
+ const headers = new Headers(input.headers);
37
+ headers.delete('content-length');
38
+ const init = { status: input.status, statusText: input.statusText, headers };
39
+ if (!input.body) {
40
+ return new Response(null, init);
41
+ }
42
+ const session = new RewriteSession(this.handlers);
43
+ const decoder = new TextDecoder();
44
+ const encoder = new TextEncoder();
45
+ const body = input.body.pipeThrough(new TransformStream({
46
+ transform(chunk, controller) {
47
+ const output = session.write(decoder.decode(chunk, { stream: true }));
48
+ if (output)
49
+ controller.enqueue(encoder.encode(output));
50
+ },
51
+ flush(controller) {
52
+ const output = `${session.write(decoder.decode())}${session.end()}`;
53
+ if (output)
54
+ controller.enqueue(encoder.encode(output));
55
+ },
56
+ }));
57
+ return new Response(body, init);
58
+ }
59
+ }
60
+ /**
61
+ * Rewrites the attributes of the first start tag that `isTarget` accepts and
62
+ * returns the rest of `html` unchanged.
63
+ *
64
+ * @remarks
65
+ * Uses the same tokenizer as {@link HtmlRewriter}, so tags inside comments, raw
66
+ * text and quoted attribute values never match. Scanning stops once the target
67
+ * is rewritten, so the cost grows with the markup before the target rather than
68
+ * with the whole document. Only attribute changes are offered: content placed
69
+ * with `append` or `after` needs the element's end tag, which is never reached.
70
+ *
71
+ * With `leadingOnly`, the target must directly follow the previous start tag
72
+ * (or the start of `html`), whitespace aside. When text, a comment or an end tag
73
+ * comes first, scanning stops and nothing is rewritten.
74
+ */
75
+ export function rewriteFirstElement(html, isTarget, rewrite, options = {}) {
76
+ const leadingOnly = options.leadingOnly ?? false;
77
+ const session = new RewriteSession([
78
+ {
79
+ tagName: '*',
80
+ handlers: {
81
+ element(element) {
82
+ if (!isTarget(element))
83
+ return;
84
+ if (!leadingOnly || !session.contentBeforeStartTag)
85
+ rewrite(element);
86
+ session.stop();
87
+ },
88
+ },
89
+ },
90
+ ], { trackLeadingText: leadingOnly });
91
+ return `${session.write(html)}${session.end()}`;
92
+ }
93
+ const VOID_ELEMENTS = new Set([
94
+ 'area',
95
+ 'base',
96
+ 'br',
97
+ 'col',
98
+ 'embed',
99
+ 'hr',
100
+ 'img',
101
+ 'input',
102
+ 'keygen',
103
+ 'link',
104
+ 'meta',
105
+ 'param',
106
+ 'source',
107
+ 'track',
108
+ 'wbr',
109
+ ]);
110
+ /** SVG and MathML elements whose children are parsed as HTML again. */
111
+ const HTML_INTEGRATION_POINTS = new Set(['foreignobject', 'desc', 'title', 'mi', 'mo', 'mn', 'ms', 'mtext']);
112
+ /** HTML start tags that end foreign (SVG or MathML) content. */
113
+ const FOREIGN_BREAKOUT_TAGS = new Set([
114
+ 'b',
115
+ 'big',
116
+ 'blockquote',
117
+ 'body',
118
+ 'br',
119
+ 'center',
120
+ 'code',
121
+ 'dd',
122
+ 'div',
123
+ 'dl',
124
+ 'dt',
125
+ 'em',
126
+ 'embed',
127
+ 'h1',
128
+ 'h2',
129
+ 'h3',
130
+ 'h4',
131
+ 'h5',
132
+ 'h6',
133
+ 'head',
134
+ 'hr',
135
+ 'i',
136
+ 'img',
137
+ 'li',
138
+ 'listing',
139
+ 'menu',
140
+ 'meta',
141
+ 'nobr',
142
+ 'ol',
143
+ 'p',
144
+ 'pre',
145
+ 'ruby',
146
+ 's',
147
+ 'small',
148
+ 'span',
149
+ 'strong',
150
+ 'strike',
151
+ 'sub',
152
+ 'sup',
153
+ 'table',
154
+ 'tt',
155
+ 'u',
156
+ 'ul',
157
+ 'var',
158
+ ]);
159
+ const RAW_TEXT_ELEMENTS = new Set([
160
+ 'script',
161
+ 'style',
162
+ 'textarea',
163
+ 'title',
164
+ 'noscript',
165
+ 'iframe',
166
+ 'xmp',
167
+ 'noembed',
168
+ 'noframes',
169
+ 'plaintext',
170
+ ]);
171
+ /**
172
+ * Incremental tokenizer state for one `transform()` call.
173
+ *
174
+ * @remarks
175
+ * `write()` consumes as much input as can be tokenized unambiguously and keeps
176
+ * the rest (an unfinished tag, comment, or possible raw-text end tag) buffered
177
+ * for the next chunk. `end()` flushes that remainder as-is.
178
+ *
179
+ * Foreign content follows lol-html: SVG and MathML children are foreign until an
180
+ * HTML integration point or a break-out start tag, and CDATA sections are
181
+ * recognised only in foreign content. Break-out end tags (`</p>`, `</br>`)
182
+ * are not modelled.
183
+ */
184
+ class RewriteSession {
185
+ buffer = '';
186
+ rawTextTag = null;
187
+ scriptState = 'data';
188
+ stopped = false;
189
+ markupSinceStartTag = false;
190
+ openElements = [];
191
+ handlers;
192
+ handledTags;
193
+ handlesAnyTag;
194
+ trackLeadingText;
195
+ /**
196
+ * @param options.trackLeadingText Also count non-whitespace text in
197
+ * {@link contentBeforeStartTag}. Off by default because it scans every text run.
198
+ */
199
+ constructor(handlers, options = {}) {
200
+ this.handlers = handlers;
201
+ this.handledTags = new Set(handlers.map((entry) => entry.tagName));
202
+ this.handlesAnyTag = this.handledTags.has('*');
203
+ this.trackLeadingText = options.trackLeadingText ?? false;
204
+ }
205
+ /**
206
+ * Whether a comment, end tag or other non-start-tag markup (and, when tracked,
207
+ * non-whitespace text) appeared between the previous start tag and the one
208
+ * whose handlers are running.
209
+ */
210
+ get contentBeforeStartTag() {
211
+ return this.markupSinceStartTag;
212
+ }
213
+ write(chunk) {
214
+ this.buffer += chunk;
215
+ return this.drain(false);
216
+ }
217
+ end() {
218
+ const output = this.drain(true);
219
+ this.openElements.length = 0;
220
+ return output;
221
+ }
222
+ /** Stops tokenizing after the current tag; the remaining input passes through verbatim. */
223
+ stop() {
224
+ this.stopped = true;
225
+ }
226
+ /**
227
+ * @remarks
228
+ * Unchanged markup is not copied token by token: `copied` trails `index`, and
229
+ * the source between them is appended in one slice when a rewritten token or
230
+ * the end of the chunk is reached.
231
+ */
232
+ drain(final) {
233
+ const source = this.buffer;
234
+ let output = '';
235
+ let copied = 0;
236
+ let index = 0;
237
+ while (index < source.length && !this.stopped) {
238
+ if (this.rawTextTag) {
239
+ const scan = this.rawTextTag === 'script'
240
+ ? this.scanScript(source, index, final)
241
+ : this.scanRawText(source, index, final);
242
+ index = scan.textEnd;
243
+ if (!scan.closed)
244
+ break;
245
+ this.rawTextTag = null;
246
+ continue;
247
+ }
248
+ const lt = source.indexOf('<', index);
249
+ const textEnd = lt === -1 ? source.length : lt;
250
+ if (this.trackLeadingText && !this.markupSinceStartTag && hasNonWhitespace(source, index, textEnd)) {
251
+ this.markupSinceStartTag = true;
252
+ }
253
+ if (lt === -1) {
254
+ index = source.length;
255
+ break;
256
+ }
257
+ index = lt;
258
+ const token = this.readMarkup(source, index, final);
259
+ if (!token)
260
+ break;
261
+ if (token.replacement !== undefined) {
262
+ output += `${source.slice(copied, index)}${token.replacement}`;
263
+ copied = token.end;
264
+ }
265
+ index = token.end;
266
+ }
267
+ output += source.slice(copied, index);
268
+ if (final || this.stopped) {
269
+ output += source.slice(index);
270
+ this.buffer = '';
271
+ }
272
+ else {
273
+ this.buffer = source.slice(index);
274
+ }
275
+ return output;
276
+ }
277
+ readMarkup(source, index, final) {
278
+ const next = source[index + 1];
279
+ if (next === undefined)
280
+ return null;
281
+ if (isAsciiAlpha(next)) {
282
+ const tag = scanTag(source, index);
283
+ if (!tag)
284
+ return null;
285
+ return { end: tag.end + 1, replacement: this.openElement(source, index, tag.end + 1, tag.selfClosing) };
286
+ }
287
+ const token = this.readNonStartTag(source, index, next, final);
288
+ if (token)
289
+ this.markupSinceStartTag = true;
290
+ return token;
291
+ }
292
+ /** Reads a comment, declaration, processing instruction, end tag or a stray `<`. */
293
+ readNonStartTag(source, index, next, final) {
294
+ if (next === '!')
295
+ return readDeclaration(source, index, final, this.inForeignContent());
296
+ if (next === '?')
297
+ return readUntilTagClose(source, index);
298
+ if (next === '/')
299
+ return this.readEndTag(source, index);
300
+ return { end: index + 1 };
301
+ }
302
+ readEndTag(source, index) {
303
+ const first = source[index + 2];
304
+ if (first === undefined)
305
+ return null;
306
+ if (first === '>')
307
+ return { end: index + 3 };
308
+ if (!isAsciiAlpha(first))
309
+ return readUntilTagClose(source, index);
310
+ const tag = scanTag(source, index);
311
+ if (!tag)
312
+ return null;
313
+ const end = tag.end + 1;
314
+ const closed = this.closeElement(readTagName(source, index + 2).toLowerCase());
315
+ if (!closed || (!closed.append && !closed.after))
316
+ return { end };
317
+ return { end, replacement: `${closed.append}${source.slice(index, end)}${closed.after}` };
318
+ }
319
+ inForeignContent() {
320
+ const current = this.openElements[this.openElements.length - 1];
321
+ return current !== undefined && current.foreign && !HTML_INTEGRATION_POINTS.has(current.name);
322
+ }
323
+ /**
324
+ * Resolves whether a new element is SVG/MathML.
325
+ *
326
+ * @remarks
327
+ * A break-out start tag implicitly closes the open foreign elements, so their
328
+ * pending `append`/`after` content is dropped, as for any element closed
329
+ * without its own end tag.
330
+ */
331
+ resolveForeign(name, source, index, end) {
332
+ if (name === 'svg' || name === 'math')
333
+ return true;
334
+ if (!this.inForeignContent())
335
+ return false;
336
+ if (!isForeignBreakout(name, source, index, end))
337
+ return true;
338
+ while (this.inForeignContent())
339
+ this.openElements.pop();
340
+ return false;
341
+ }
342
+ /** Tracks the start tag `source[index, end)` and returns its rewrite, if a handler matched. */
343
+ openElement(source, index, end, selfClosing) {
344
+ const name = readTagName(source, index + 1).toLowerCase();
345
+ const foreign = this.resolveForeign(name, source, index, end);
346
+ const isVoid = VOID_ELEMENTS.has(name) || (foreign && selfClosing);
347
+ const openElement = { name, foreign, append: '', after: '' };
348
+ let replacement;
349
+ if (this.handlesAnyTag || this.handledTags.has(name)) {
350
+ const element = new RewriterElement(source.slice(index, end), name, selfClosing, !isVoid);
351
+ for (const entry of this.handlers) {
352
+ if (entry.tagName === '*' || entry.tagName === name)
353
+ entry.handlers.element?.(element);
354
+ }
355
+ replacement = element.renderStart();
356
+ openElement.append = element.renderAppend();
357
+ openElement.after = element.renderAfter();
358
+ if (isVoid)
359
+ replacement += openElement.after;
360
+ }
361
+ this.markupSinceStartTag = false;
362
+ if (!isVoid) {
363
+ this.openElements.push(openElement);
364
+ if (!foreign && RAW_TEXT_ELEMENTS.has(name)) {
365
+ this.rawTextTag = name;
366
+ this.scriptState = 'data';
367
+ }
368
+ }
369
+ return replacement;
370
+ }
371
+ /** Pops the nearest open element named `name` and returns it, if any. */
372
+ closeElement(name) {
373
+ const top = this.openElements[this.openElements.length - 1];
374
+ if (top?.name === name)
375
+ return this.openElements.pop();
376
+ for (let position = this.openElements.length - 2; position >= 0; position--) {
377
+ const element = this.openElements[position];
378
+ if (element.name !== name)
379
+ continue;
380
+ this.openElements.length = position;
381
+ return element;
382
+ }
383
+ return undefined;
384
+ }
385
+ scanRawText(source, index, final) {
386
+ if (this.rawTextTag === 'plaintext')
387
+ return { textEnd: source.length, closed: false };
388
+ const endTag = `</${this.rawTextTag}`;
389
+ for (let lt = source.indexOf('<', index); lt !== -1; lt = source.indexOf('<', lt + 1)) {
390
+ const match = matchTag(source, lt, endTag, final);
391
+ if (match === 'more')
392
+ return { textEnd: lt, closed: false };
393
+ if (match === 'yes')
394
+ return { textEnd: lt, closed: true };
395
+ }
396
+ return { textEnd: source.length, closed: false };
397
+ }
398
+ /**
399
+ * Finds the end of script content, following the HTML script-data escape
400
+ * states so `</script>` inside `<!-- <script> … -->` does not close it.
401
+ */
402
+ scanScript(source, index, final) {
403
+ for (let position = index; position < source.length; position++) {
404
+ const char = source[position];
405
+ let step = 0;
406
+ if (char === '-' && this.scriptState !== 'data')
407
+ step = this.scanEscapeEnd(source, position, final);
408
+ else if (char === '<')
409
+ step = this.scanScriptMarkup(source, position, final);
410
+ if (step === 'more')
411
+ return { textEnd: position, closed: false };
412
+ if (step === 'closed')
413
+ return { textEnd: position, closed: true };
414
+ position += step;
415
+ }
416
+ return { textEnd: source.length, closed: false };
417
+ }
418
+ scanEscapeEnd(source, position, final) {
419
+ const match = matchLiteral(source, position, '-->', final);
420
+ if (match !== 'yes')
421
+ return match === 'more' ? 'more' : 0;
422
+ this.scriptState = 'data';
423
+ return 2;
424
+ }
425
+ scanScriptMarkup(source, position, final) {
426
+ const endTag = matchTag(source, position, '</script', final);
427
+ if (endTag === 'more')
428
+ return 'more';
429
+ if (endTag === 'yes') {
430
+ if (this.scriptState !== 'double-escaped')
431
+ return 'closed';
432
+ this.scriptState = 'escaped';
433
+ return 0;
434
+ }
435
+ if (this.scriptState === 'data') {
436
+ const match = matchLiteral(source, position, '<!--', final);
437
+ if (match !== 'yes')
438
+ return match === 'more' ? 'more' : 0;
439
+ this.scriptState = 'escaped';
440
+ return 1;
441
+ }
442
+ if (this.scriptState === 'escaped') {
443
+ const match = matchTag(source, position, '<script', final);
444
+ if (match === 'yes')
445
+ this.scriptState = 'double-escaped';
446
+ return match === 'more' ? 'more' : 0;
447
+ }
448
+ return 0;
449
+ }
450
+ }
451
+ class RewriterElement {
452
+ parsed = null;
453
+ beforeParts = [];
454
+ prependParts = [];
455
+ appendParts = [];
456
+ afterParts = [];
457
+ raw;
458
+ tagName;
459
+ selfClosing;
460
+ canHaveContent;
461
+ constructor(raw, tagName, selfClosing, canHaveContent) {
462
+ this.raw = raw;
463
+ this.tagName = tagName;
464
+ this.selfClosing = selfClosing;
465
+ this.canHaveContent = canHaveContent;
466
+ }
467
+ get attributes() {
468
+ return this.tag()
469
+ .attributes.filter((attribute) => attribute.state !== 'removed')
470
+ .map((attribute) => [attribute.name, attribute.value])[Symbol.iterator]();
471
+ }
472
+ getAttribute(name) {
473
+ return this.findAttribute(name)?.value ?? null;
474
+ }
475
+ hasAttribute(name) {
476
+ return this.findAttribute(name) !== undefined;
477
+ }
478
+ setAttribute(name, value) {
479
+ const existing = this.findAttribute(name);
480
+ if (existing) {
481
+ existing.value = value;
482
+ existing.state = 'changed';
483
+ }
484
+ else {
485
+ this.tag().attributes.push({
486
+ name: name.toLowerCase(),
487
+ value,
488
+ source: '',
489
+ rawName: name,
490
+ state: 'changed',
491
+ });
492
+ }
493
+ return this;
494
+ }
495
+ removeAttribute(name) {
496
+ const existing = this.findAttribute(name);
497
+ if (existing)
498
+ existing.state = 'removed';
499
+ return this;
500
+ }
501
+ before(content, options) {
502
+ this.beforeParts.push(toMarkup(content, options));
503
+ return this;
504
+ }
505
+ prepend(content, options) {
506
+ this.prependParts.push(toMarkup(content, options));
507
+ return this;
508
+ }
509
+ append(content, options) {
510
+ this.appendParts.push(toMarkup(content, options));
511
+ return this;
512
+ }
513
+ after(content, options) {
514
+ this.afterParts.push(toMarkup(content, options));
515
+ return this;
516
+ }
517
+ renderStart() {
518
+ const prepend = this.canHaveContent ? [...this.prependParts].reverse().join('') : '';
519
+ return `${this.beforeParts.join('')}${this.renderStartTag()}${prepend}`;
520
+ }
521
+ renderAppend() {
522
+ return this.canHaveContent ? this.appendParts.join('') : '';
523
+ }
524
+ renderAfter() {
525
+ return [...this.afterParts].reverse().join('');
526
+ }
527
+ /**
528
+ * @remarks
529
+ * An untouched tag is emitted verbatim. Once an attribute changes, the tag is
530
+ * re-serialised like lol-html: single spaces between attributes, untouched
531
+ * attributes as written, and `/>` (spaced after attributes) only for a
532
+ * self-closing tag that gained no content.
533
+ */
534
+ renderStartTag() {
535
+ if (!this.parsed || this.parsed.attributes.every((attribute) => attribute.state === 'original')) {
536
+ return this.raw;
537
+ }
538
+ const attributes = this.parsed.attributes
539
+ .filter((attribute) => attribute.state !== 'removed')
540
+ .map((attribute) => attribute.state === 'original'
541
+ ? ` ${attribute.source}`
542
+ : ` ${attribute.rawName}="${attribute.value.replaceAll('"', '&quot;')}"`)
543
+ .join('');
544
+ const gainedContent = this.canHaveContent && (this.prependParts.length > 0 || this.appendParts.length > 0);
545
+ const close = this.selfClosing && !gainedContent ? `${attributes ? ' ' : ''}/>` : '>';
546
+ return `<${this.parsed.rawName}${attributes}${close}`;
547
+ }
548
+ findAttribute(name) {
549
+ const normalized = name.toLowerCase();
550
+ return this.tag().attributes.find((attribute) => attribute.state !== 'removed' && attribute.name === normalized);
551
+ }
552
+ tag() {
553
+ this.parsed ??= parseStartTag(this.raw);
554
+ return this.parsed;
555
+ }
556
+ }
557
+ function parseStartTag(raw) {
558
+ const rawName = readTagName(raw, 1);
559
+ const attributes = [];
560
+ let index = 1 + rawName.length;
561
+ while (index < raw.length) {
562
+ index = skipWhile(raw, index, (char, at) => isWhitespace(char) || (char === '/' && raw[at + 1] !== '>'));
563
+ if (index >= raw.length || raw[index] === '>' || raw.startsWith('/>', index)) {
564
+ return { rawName, attributes };
565
+ }
566
+ const nameStart = index;
567
+ index = skipWhile(raw, index, (char, at) => !isWhitespace(char) && char !== '=' && char !== '>' && !raw.startsWith('/>', at));
568
+ const attributeName = raw.slice(nameStart, index);
569
+ const value = readAttributeValue(raw, index);
570
+ index = value.end;
571
+ attributes.push({
572
+ name: attributeName.toLowerCase(),
573
+ value: value.text,
574
+ source: raw.slice(nameStart, index),
575
+ rawName: attributeName,
576
+ state: 'original',
577
+ });
578
+ }
579
+ return { rawName, attributes };
580
+ }
581
+ /**
582
+ * Reads an optional `= value` after an attribute name.
583
+ *
584
+ * @remarks `end` stays at `index` when there is no `=`.
585
+ */
586
+ function readAttributeValue(raw, index) {
587
+ let position = skipWhile(raw, index, isWhitespace);
588
+ if (raw[position] !== '=')
589
+ return { text: '', end: index };
590
+ position = skipWhile(raw, position + 1, isWhitespace);
591
+ const quote = raw[position];
592
+ if (quote === '"' || quote === "'") {
593
+ const close = raw.indexOf(quote, position + 1);
594
+ const valueEnd = close === -1 ? raw.length - 1 : close;
595
+ return { text: raw.slice(position + 1, valueEnd), end: close === -1 ? valueEnd : close + 1 };
596
+ }
597
+ const valueEnd = skipWhile(raw, position, (char) => !isWhitespace(char) && char !== '>');
598
+ return { text: raw.slice(position, valueEnd), end: valueEnd };
599
+ }
600
+ function skipWhile(raw, index, predicate) {
601
+ let position = index;
602
+ while (position < raw.length && predicate(raw[position], position))
603
+ position++;
604
+ return position;
605
+ }
606
+ /**
607
+ * Reads a comment, CDATA section (foreign content only), doctype or bogus comment.
608
+ *
609
+ * @remarks Returns `null` to wait for more input while a short prefix could
610
+ * still become `<!--` or `<![CDATA[`.
611
+ */
612
+ function readDeclaration(source, index, final, foreign) {
613
+ if (source.startsWith('<!--', index)) {
614
+ const end = findCommentEnd(source, index);
615
+ return end === -1 ? null : { end };
616
+ }
617
+ if (foreign && source.startsWith('<![CDATA[', index)) {
618
+ const close = source.indexOf(']]>', index + 9);
619
+ return close === -1 ? null : { end: close + 3 };
620
+ }
621
+ const rest = source.slice(index);
622
+ const couldGrow = rest.length < 9 && ('<!--'.startsWith(rest) || (foreign && '<![CDATA['.startsWith(rest)));
623
+ if (!final && couldGrow)
624
+ return null;
625
+ return readUntilTagClose(source, index);
626
+ }
627
+ /**
628
+ * Finds the end of a comment opened at `index`.
629
+ *
630
+ * @remarks Accepts `-->` and `--!>`, including the abrupt `<!-->` and `<!--->`.
631
+ */
632
+ function findCommentEnd(source, index) {
633
+ for (let close = source.indexOf('>', index + 4); close !== -1; close = source.indexOf('>', close + 1)) {
634
+ if (source[close - 1] === '-' && source[close - 2] === '-')
635
+ return close + 1;
636
+ if (source[close - 1] === '!' &&
637
+ source[close - 2] === '-' &&
638
+ source[close - 3] === '-' &&
639
+ close - 3 >= index + 4) {
640
+ return close + 1;
641
+ }
642
+ }
643
+ return -1;
644
+ }
645
+ /**
646
+ * Scans a start or end tag from `index` to its closing `>`, skipping quoted
647
+ * attribute values.
648
+ *
649
+ * @remarks `selfClosing` is true only when the `/` before `>` is not part of an
650
+ * unquoted attribute value (`<div a=/>` is not self-closing).
651
+ */
652
+ function scanTag(source, index) {
653
+ let position = index + 1;
654
+ while (position < source.length && !isTagNameEnd(source[position]))
655
+ position++;
656
+ let afterEquals = false;
657
+ let inUnquotedValue = false;
658
+ for (; position < source.length; position++) {
659
+ const code = source.charCodeAt(position);
660
+ if (code === CHAR_GREATER_THAN) {
661
+ return { end: position, selfClosing: source.charCodeAt(position - 1) === CHAR_SLASH && !inUnquotedValue };
662
+ }
663
+ if (isWhitespaceCode(code)) {
664
+ inUnquotedValue = false;
665
+ continue;
666
+ }
667
+ if (afterEquals) {
668
+ afterEquals = false;
669
+ if (code === CHAR_DOUBLE_QUOTE || code === CHAR_SINGLE_QUOTE) {
670
+ position = source.indexOf(source[position], position + 1);
671
+ if (position === -1)
672
+ return null;
673
+ }
674
+ else {
675
+ inUnquotedValue = true;
676
+ }
677
+ continue;
678
+ }
679
+ if (code === CHAR_EQUALS && !inUnquotedValue)
680
+ afterEquals = true;
681
+ }
682
+ return null;
683
+ }
684
+ /** Whether the start tag `source[index, end)` named `name` ends foreign content. */
685
+ function isForeignBreakout(name, source, index, end) {
686
+ if (FOREIGN_BREAKOUT_TAGS.has(name))
687
+ return true;
688
+ return (name === 'font' &&
689
+ parseStartTag(source.slice(index, end)).attributes.some((attribute) => ['color', 'face', 'size'].includes(attribute.name)));
690
+ }
691
+ function readUntilTagClose(source, index) {
692
+ const close = source.indexOf('>', index + 1);
693
+ return close === -1 ? null : { end: close + 1 };
694
+ }
695
+ function readTagName(raw, from) {
696
+ let end = from;
697
+ while (end < raw.length && !isTagNameEnd(raw[end]))
698
+ end++;
699
+ return raw.slice(from, end);
700
+ }
701
+ /**
702
+ * Matches `prefix` case-insensitively at `index`, followed by a tag-name
703
+ * delimiter. Returns `'more'` when the input ends before the match is decided.
704
+ */
705
+ function matchTag(source, index, prefix, final) {
706
+ const available = source.slice(index, index + prefix.length).toLowerCase();
707
+ if (available.length < prefix.length)
708
+ return !final && prefix.startsWith(available) ? 'more' : 'no';
709
+ if (available !== prefix)
710
+ return 'no';
711
+ const delimiter = source[index + prefix.length];
712
+ if (delimiter === undefined)
713
+ return final ? 'no' : 'more';
714
+ return isTagNameEnd(delimiter) ? 'yes' : 'no';
715
+ }
716
+ function matchLiteral(source, index, literal, final) {
717
+ const available = source.slice(index, index + literal.length);
718
+ if (available.length < literal.length)
719
+ return !final && literal.startsWith(available) ? 'more' : 'no';
720
+ return available === literal ? 'yes' : 'no';
721
+ }
722
+ function toMarkup(content, options) {
723
+ if (options?.html)
724
+ return content;
725
+ return content.replaceAll('&', '&amp;').replaceAll('<', '&lt;').replaceAll('>', '&gt;');
726
+ }
727
+ function isAsciiAlpha(char) {
728
+ return (char >= 'a' && char <= 'z') || (char >= 'A' && char <= 'Z');
729
+ }
730
+ function isWhitespace(char) {
731
+ return char === ' ' || char === '\n' || char === '\t' || char === '\r' || char === '\f';
732
+ }
733
+ const CHAR_DOUBLE_QUOTE = 34;
734
+ const CHAR_SINGLE_QUOTE = 39;
735
+ const CHAR_SLASH = 47;
736
+ const CHAR_EQUALS = 61;
737
+ const CHAR_GREATER_THAN = 62;
738
+ function hasNonWhitespace(source, start, end) {
739
+ for (let position = start; position < end; position++) {
740
+ if (!isWhitespaceCode(source.charCodeAt(position)))
741
+ return true;
742
+ }
743
+ return false;
744
+ }
745
+ /** {@link isWhitespace} for a UTF-16 code unit, for the hot tag scanner. */
746
+ function isWhitespaceCode(code) {
747
+ return code === 32 || code === 10 || code === 9 || code === 13 || code === 12;
748
+ }
749
+ function isTagNameEnd(char) {
750
+ return isWhitespace(char) || char === '/' || char === '>';
751
+ }