fragmentor 0.2.2 → 0.2.3

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.
@@ -50,7 +50,7 @@ export declare function lookup(components: Component[], type: string, ancestors:
50
50
  * reference leading to itself (a product card rendering its recommendations as cards, ...) would recurse until the stack
51
51
  * overflows. Real pages nest a handful of levels, this only stops runaway loops.
52
52
  */
53
- export declare const MAX_DEPTH = 32;
53
+ export declare const MAX_DEPTH = 16;
54
54
  /**
55
55
  * Renders a document (or any fragment) into HTML, recursively. For every fragment reached:
56
56
  * 1. Its component is looked up by _type and the _types it's nested in (see `lookup`).
@@ -60,7 +60,10 @@ function fallback(fragment, render, point) {
60
60
  * reference leading to itself (a product card rendering its recommendations as cards, ...) would recurse until the stack
61
61
  * overflows. Real pages nest a handful of levels, this only stops runaway loops.
62
62
  */
63
- export const MAX_DEPTH = 32;
63
+ export const MAX_DEPTH = 16;
64
+ /* What a parked fragment's comment starts with (see `draw`). Text can't forge one: serializing escapes its "<" */
65
+ const SLOT = "fragmentor-slot:";
66
+ const SLOTS = new RegExp(`<!--${SLOT}(\\d+)-->`, "g");
64
67
  /* Each component's template after `annotate` (dev only) and `extract`, indexed by `Number(dev)`. Weak, so it's freed with the components of a compile */
65
68
  const templates = [new WeakMap(), new WeakMap()];
66
69
  /**
@@ -126,10 +129,17 @@ export function render(document, components, parse, { dev = false, schemas, memo
126
129
  Object.assign(assets, template.assets);
127
130
  memo?.add(template.assets);
128
131
  const parsed = parse(template.html);
129
- apply(parsed, fragment, { evaluate: scoped, render: nested, mark });
132
+ /* A nested fragment is parked as a comment and spliced back into the output, so each parent doesn't parse and serialize it again */
133
+ const parked = [];
134
+ const park = (child) => {
135
+ const html = nested(child);
136
+ return html === undefined ? undefined : `<!--${SLOT}${parked.push(html) - 1}-->`;
137
+ };
138
+ apply(parsed, fragment, { evaluate: scoped, render: park, mark });
130
139
  for (const el of parsed.children)
131
140
  mark(el, fragment);
132
- return parsed.toString();
141
+ const out = parsed.toString();
142
+ return parked.length ? out.replace(SLOTS, (_, i) => parked[Number(i)]) : out;
133
143
  };
134
144
  return { html: go(document, []) ?? `<!-- unresolved type: ${String(document._type)} -->`, assets };
135
145
  }
@@ -10,7 +10,7 @@ type File = string | Buffer | null;
10
10
  * 3. Gives every `<img>` loading hints: the page's first one `fetchpriority="high"` (likely its largest paint), every other one `loading="lazy"` and
11
11
  * `decoding="async"`, and `sizes` along with a `srcset` ("auto" for a lazy one, so it picks by its rendered width). An attribute already set is kept.
12
12
  * esbuild and sharp are optional: without one, its step is skipped with a warning. A file that fails is kept as is with a warning, so nothing fails a build.
13
- * A page without images is left untouched, any other one is reserialized by `parse`.
13
+ * Only the `<img>` tags of a page are changed, each one parsed by `parse` (and once for all the pages that repeat it), the rest of the page stays as it is.
14
14
  * @param files Every output file by path: text, bytes, or null for a binary whose bytes live elsewhere.
15
15
  * @param options.parse Parses a page's HTML (linkedom).
16
16
  * @param options.read Reads a null file's bytes (e.g. from storage), by its output path.
@@ -6,6 +6,8 @@ export const IMAGES = "/_images";
6
6
  const WIDTHS = [640, 1280, 1920];
7
7
  /* Images worth re-encoding. GIF (animation), SVG (vector) and ICO stay as they are */
8
8
  const RASTER = /\.(png|jpe?g|webp)$/i;
9
+ /* What an <img> pass looks at, in order: comments and the raw text of script/style/textarea/title and the content of template (skipped), <picture> and </picture> (group 2 is the slash) and <img> tags, whose attributes may hold quoted ">" */
10
+ const MARKUP = /<!--[\s\S]*?-->|<(script|style|textarea|title|template)\b[\s\S]*?<\/\1\s*>|<(\/?)picture\b(?:"[^"]*"|'[^']*'|[^"'>])*>|<img(?=[\s/>])(?:"[^"]*"|'[^']*'|[^"'>])*>/gi;
9
11
  /* Text files esbuild minifies, except ones that already are (e.g. "/vendor/htmx.min.js") */
10
12
  const MINIFIABLE = /\.(css|m?js)$/i;
11
13
  const MINIFIED = /\.min\.(css|m?js)$/i;
@@ -46,7 +48,7 @@ async function variants(sharp, bytes) {
46
48
  * 3. Gives every `<img>` loading hints: the page's first one `fetchpriority="high"` (likely its largest paint), every other one `loading="lazy"` and
47
49
  * `decoding="async"`, and `sizes` along with a `srcset` ("auto" for a lazy one, so it picks by its rendered width). An attribute already set is kept.
48
50
  * esbuild and sharp are optional: without one, its step is skipped with a warning. A file that fails is kept as is with a warning, so nothing fails a build.
49
- * A page without images is left untouched, any other one is reserialized by `parse`.
51
+ * Only the `<img>` tags of a page are changed, each one parsed by `parse` (and once for all the pages that repeat it), the rest of the page stays as it is.
50
52
  * @param files Every output file by path: text, bytes, or null for a binary whose bytes live elsewhere.
51
53
  * @param options.parse Parses a page's HTML (linkedom).
52
54
  * @param options.read Reads a null file's bytes (e.g. from storage), by its output path.
@@ -77,49 +79,71 @@ export async function optimize(files, { parse, read }) {
77
79
  }
78
80
  /* Each image's variants by its path, encoded once however many pages show it. One at a time, since a large photo takes a lot of memory to decode */
79
81
  const encoded = new Map();
82
+ /* One <img>, tuned as the loading hints and encodings above describe. `first` is the page's first image, `pictured` one inside a <picture> */
83
+ const tune = async (img, first, pictured) => {
84
+ if (first && img.getAttribute("loading") === null && img.getAttribute("fetchpriority") === null)
85
+ img.setAttribute("fetchpriority", "high");
86
+ if (!first && img.getAttribute("loading") === null)
87
+ img.setAttribute("loading", "lazy");
88
+ if (!first && img.getAttribute("decoding") === null)
89
+ img.setAttribute("decoding", "async");
90
+ const src = local(img.getAttribute("src"));
91
+ if (!sharp || !src || !RASTER.test(src) || !(src in files) || img.getAttribute("srcset") !== null || pictured)
92
+ return;
93
+ let list = encoded.get(src);
94
+ if (!list) {
95
+ try {
96
+ const stored = files[src];
97
+ const bytes = Buffer.isBuffer(stored) ? stored : stored === null && read ? await read(src) : null;
98
+ const encodings = bytes ? await variants(sharp, bytes) : [];
99
+ for (const variant of encodings)
100
+ if (!(variant.path in out))
101
+ out[variant.path] = variant.data;
102
+ list = encodings;
103
+ }
104
+ catch (e) {
105
+ warnings.push(`${src}: not optimized, ${e.message}`);
106
+ list = [];
107
+ }
108
+ encoded.set(src, list);
109
+ }
110
+ if (!list.length)
111
+ return;
112
+ img.setAttribute("src", list[list.length - 1].path);
113
+ img.setAttribute("srcset", list.map((v) => `${v.path} ${v.width}w`).join(", "));
114
+ if (img.getAttribute("sizes") === null)
115
+ img.setAttribute("sizes", img.getAttribute("loading") === "lazy" ? "auto, 100vw" : "100vw");
116
+ };
117
+ /* Each <img> tag as written, tuned once however many pages repeat it (only its position on the page can differ, hence the key) */
118
+ const tags = new Map();
119
+ const retag = async (tag, first, pictured) => {
120
+ const key = `${+first}${+pictured}${tag}`;
121
+ let done = tags.get(key);
122
+ if (done === undefined) {
123
+ const parsed = parse(tag);
124
+ const [img] = parsed.querySelectorAll("img");
125
+ if (img)
126
+ await tune(img, first, pictured);
127
+ tags.set(key, (done = parsed.toString()));
128
+ }
129
+ return done;
130
+ };
131
+ /* Only <img> tags are edited, so they're found in the text, skipping comments and the raw text of <script>, <style> and the like, and tracking <picture> on the way. Pages are never parsed whole: that took longer than everything else together on a page with a long list */
80
132
  for (const [path, data] of Object.entries(files)) {
81
133
  if (data === null || !/\.html$/i.test(path))
82
134
  continue;
83
- const document = parse(text(data));
84
- const images = [...document.querySelectorAll("img")];
85
- if (!images.length)
86
- continue;
87
- const pictured = new Set(document.querySelectorAll("picture img"));
88
- for (const [i, img] of images.entries()) {
89
- if (i === 0 && img.getAttribute("loading") === null && img.getAttribute("fetchpriority") === null)
90
- img.setAttribute("fetchpriority", "high");
91
- if (i > 0 && img.getAttribute("loading") === null)
92
- img.setAttribute("loading", "lazy");
93
- if (i > 0 && img.getAttribute("decoding") === null)
94
- img.setAttribute("decoding", "async");
95
- const src = local(img.getAttribute("src"));
96
- if (!sharp || !src || !RASTER.test(src) || !(src in files) || img.getAttribute("srcset") !== null || pictured.has(img))
97
- continue;
98
- let list = encoded.get(src);
99
- if (!list) {
100
- try {
101
- const stored = files[src];
102
- const bytes = Buffer.isBuffer(stored) ? stored : stored === null && read ? await read(src) : null;
103
- const encodings = bytes ? await variants(sharp, bytes) : [];
104
- for (const variant of encodings)
105
- if (!(variant.path in out))
106
- out[variant.path] = variant.data;
107
- list = encodings;
108
- }
109
- catch (e) {
110
- warnings.push(`${src}: not optimized, ${e.message}`);
111
- list = [];
112
- }
113
- encoded.set(src, list);
135
+ const html = text(data);
136
+ let page = "", at = 0, depth = 0, count = 0;
137
+ for (const m of html.matchAll(MARKUP)) {
138
+ if (m[2] !== undefined)
139
+ depth += m[2] ? -1 : 1;
140
+ else if (m[0][1] === "i" || m[0][1] === "I") {
141
+ page += html.slice(at, m.index) + (await retag(m[0], count++ === 0, depth > 0));
142
+ at = m.index + m[0].length;
114
143
  }
115
- if (!list.length)
116
- continue;
117
- img.setAttribute("src", list[list.length - 1].path);
118
- img.setAttribute("srcset", list.map((v) => `${v.path} ${v.width}w`).join(", "));
119
- if (img.getAttribute("sizes") === null)
120
- img.setAttribute("sizes", img.getAttribute("loading") === "lazy" ? "auto, 100vw" : "100vw");
121
144
  }
122
- out[path] = same(data, document.toString());
145
+ if (count)
146
+ out[path] = same(data, page + html.slice(at));
123
147
  }
124
148
  return { files: out, warnings };
125
149
  }
@@ -28,15 +28,17 @@ export function resolve({ document, references }) {
28
28
  export function resolver({ references }) {
29
29
  const byId = new Map(references.map(d => [d._id, d]));
30
30
  const resolved = new Map();
31
- /* The object is registered before its fields are filled, so a reference back to it, at any depth, gets this same object */
31
+ /* Documents linked but not filled yet, with the object each one fills */
32
+ const pending = [];
33
+ /* The object is registered before its fields are filled, so a reference back to it, at any depth, gets this same object.
34
+ Filling waits in `pending` instead of recursing, so a long chain of references can't overflow the stack */
32
35
  const link = (doc) => {
33
36
  const existing = resolved.get(doc._id);
34
37
  if (existing)
35
38
  return existing;
36
39
  const target = {};
37
40
  resolved.set(doc._id, target);
38
- for (const [key, value] of Object.entries(doc))
39
- target[key] = walk(value);
41
+ pending.push([doc, target]);
40
42
  return target;
41
43
  };
42
44
  const walk = (value) => {
@@ -50,8 +52,17 @@ export function resolver({ references }) {
50
52
  return Object.fromEntries(Object.entries(value).map(([key, v]) => [key, walk(v)]));
51
53
  return value;
52
54
  };
53
- /* A document reached earlier through a reference is already linked, so it comes back as that same object */
54
- return (document) => link(document);
55
+ /* A document reached earlier through a reference is already linked, so it comes back as that same object.
56
+ Every document it reaches is filled before it's returned */
57
+ return (document) => {
58
+ const target = link(document);
59
+ for (let next = pending.pop(); next; next = pending.pop()) {
60
+ const [doc, object] = next;
61
+ for (const [key, value] of Object.entries(doc))
62
+ object[key] = walk(value);
63
+ }
64
+ return target;
65
+ };
55
66
  }
56
67
  /* Past this many documents, filling an empty references field without a max is a warning: every page that renders it renders them all */
57
68
  export const MANY_REFERENCES = 100;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "fragmentor",
3
- "version": "0.2.2",
3
+ "version": "0.2.3",
4
4
  "description": "The open-source build engine for Fragmentor.",
5
5
  "license": "MIT",
6
6
  "type": "module",