@occluze/umber 0.3.0 → 0.4.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.
Files changed (87) hide show
  1. package/README.md +93 -47
  2. package/THIRD-PARTY-NOTICES.md +33 -0
  3. package/dist/chunks/badge.js +2 -2
  4. package/dist/chunks/basis.js +2 -2
  5. package/dist/chunks/batches.js +2 -0
  6. package/dist/chunks/capture.js +2 -2
  7. package/dist/chunks/covers.js +2 -2
  8. package/dist/chunks/curves.js +2 -2
  9. package/dist/chunks/flip.js +2 -2
  10. package/dist/chunks/fx.js +2 -2
  11. package/dist/chunks/gl.js +2 -2
  12. package/dist/chunks/glsl.js +2 -2
  13. package/dist/chunks/glyphs.js +2 -0
  14. package/dist/chunks/inspect.js +2 -2
  15. package/dist/chunks/instances.js +2 -2
  16. package/dist/chunks/layers.js +2 -2
  17. package/dist/chunks/licence.js +2 -2
  18. package/dist/chunks/morph.js +2 -2
  19. package/dist/chunks/pace.js +2 -0
  20. package/dist/chunks/patch.js +2 -2
  21. package/dist/chunks/prepared.js +2 -2
  22. package/dist/chunks/profiler.js +2 -2
  23. package/dist/chunks/recheck.js +2 -0
  24. package/dist/chunks/resize.js +2 -0
  25. package/dist/chunks/restore.js +2 -2
  26. package/dist/chunks/shapes.js +2 -2
  27. package/dist/chunks/sim.js +2 -2
  28. package/dist/chunks/text.js +2 -2
  29. package/dist/chunks/video.js +2 -2
  30. package/dist/chunks/vocabulary.js +2 -2
  31. package/dist/chunks/warm.js +2 -2
  32. package/dist/modules/debug.js +2 -2
  33. package/dist/modules/debug.mjs +2 -2
  34. package/dist/modules/handoff.js +2 -2
  35. package/dist/modules/handoff.mjs +2 -2
  36. package/dist/modules/input.js +2 -2
  37. package/dist/modules/input.mjs +2 -2
  38. package/dist/modules/scrollfx.js +2 -2
  39. package/dist/modules/scrollfx.mjs +2 -2
  40. package/dist/modules/scrub.js +2 -2
  41. package/dist/modules/scrub.mjs +2 -2
  42. package/dist/modules/three.js +2 -2
  43. package/dist/modules/three.mjs +2 -2
  44. package/dist/node/assets.mjs +4 -2
  45. package/dist/node/astro.mjs +26 -18
  46. package/dist/node/cli.mjs +63 -10
  47. package/dist/node/shared-P6KINBNR.mjs +2113 -0
  48. package/dist/node/{shared-4FIU6DYP.mjs → shared-VQKZUUXF.mjs} +106 -17
  49. package/dist/node/vite.mjs +7 -3
  50. package/dist/prepared.mjs +2 -0
  51. package/dist/umber.css +1 -1
  52. package/dist/umber.js +2 -2
  53. package/dist/umber.mjs +2 -2
  54. package/docs/AI-quick.md +43 -87
  55. package/docs/AI.md +1965 -1828
  56. package/docs/npm.md +13 -16
  57. package/package.json +31 -48
  58. package/types/assets.d.ts +109 -4
  59. package/types/astro.d.ts +20 -23
  60. package/types/debug.d.ts +1 -1
  61. package/types/esm.d.ts +2 -6
  62. package/types/input.d.ts +3 -3
  63. package/types/loop.d.ts +21 -9
  64. package/types/module.d.ts +0 -2
  65. package/types/scrollfx.d.ts +5 -41
  66. package/types/scrub.d.ts +2 -2
  67. package/types/three.d.ts +26 -1
  68. package/types/umber.d.ts +152 -155
  69. package/types/vite.d.ts +3 -3
  70. package/dist/chunks/views.js +0 -2
  71. package/dist/frameworks/astro.mjs +0 -2
  72. package/dist/frameworks/react.mjs +0 -2
  73. package/dist/frameworks/svelte.mjs +0 -2
  74. package/dist/frameworks/vue.mjs +0 -2
  75. package/dist/modules/router-swap.js +0 -2
  76. package/dist/modules/router.js +0 -2
  77. package/dist/modules/router.mjs +0 -2
  78. package/dist/modules/scroll-more.js +0 -2
  79. package/dist/modules/scroll-touch.js +0 -2
  80. package/dist/modules/scroll.js +0 -2
  81. package/dist/modules/scroll.mjs +0 -2
  82. package/dist/node/shared-3Q24RNIF.mjs +0 -602
  83. package/types/react.d.ts +0 -15
  84. package/types/router.d.ts +0 -223
  85. package/types/scroll.d.ts +0 -190
  86. package/types/svelte.d.ts +0 -16
  87. package/types/vue.d.ts +0 -14
@@ -1,602 +0,0 @@
1
- /*! Umber v0.3.0 asset tool | (c) Ravi Klaassens | UNLICENSED */
2
-
3
- // tools/assets/native.ts
4
- import { existsSync } from "node:fs";
5
- import { createRequire } from "node:module";
6
- import { fileURLToPath } from "node:url";
7
- function libc() {
8
- const report = process.report.getReport();
9
- return report.header.glibcVersionRuntime ? "gnu" : "musl";
10
- }
11
- function triple(platform = process.platform, arch = process.arch, c = process.platform === "linux" ? libc() : "gnu") {
12
- if (platform === "win32") return `win32-${arch}-msvc`;
13
- if (platform === "linux") return `linux-${arch}-${c}`;
14
- return `${platform}-${arch}`;
15
- }
16
- var PLATFORMS = [
17
- "win32-x64-msvc",
18
- "win32-arm64-msvc",
19
- "darwin-x64",
20
- "darwin-arm64",
21
- "linux-x64-gnu",
22
- "linux-arm64-gnu"
23
- ];
24
- var loaded = null;
25
- function loadNative() {
26
- if (loaded) return loaded;
27
- const require2 = createRequire(import.meta.url);
28
- const name = triple();
29
- const local = fileURLToPath(new URL(`../../crates/umber-assets-node/umber-assets.${name}.node`, import.meta.url));
30
- const found = existsSync(local) ? local : `@occluze/umber-assets-${name}`;
31
- try {
32
- loaded = require2(found);
33
- } catch (err) {
34
- const known = PLATFORMS.includes(name);
35
- throw new Error(
36
- known ? `Umber's asset tool for ${name} is not installed (@occluze/umber-assets-${name}). Install @occluze/umber again without --no-optional / --omit=optional.` : `Umber's asset tool has no build for ${name}. It runs on ${PLATFORMS.join(", ")}.`,
37
- { cause: err }
38
- );
39
- }
40
- return loaded;
41
- }
42
-
43
- // tools/assets/site.ts
44
- import { createHash } from "node:crypto";
45
- import { existsSync as existsSync3 } from "node:fs";
46
- import { copyFile, mkdir as mkdir2, readdir, readFile as readFile2, writeFile as writeFile2 } from "node:fs/promises";
47
- import { availableParallelism } from "node:os";
48
- import { join as join2, relative, sep } from "node:path";
49
-
50
- // tools/assets/fonts.ts
51
- import { existsSync as existsSync2 } from "node:fs";
52
- import { mkdir, readFile, writeFile } from "node:fs/promises";
53
- import { join } from "node:path";
54
-
55
- // tools/assets/html.ts
56
- var VOID = /* @__PURE__ */ new Set([
57
- "area",
58
- "base",
59
- "br",
60
- "col",
61
- "embed",
62
- "hr",
63
- "img",
64
- "input",
65
- "link",
66
- "meta",
67
- "param",
68
- "source",
69
- "track",
70
- "wbr"
71
- ]);
72
- var RAW = /* @__PURE__ */ new Set(["script", "style", "template", "textarea", "title"]);
73
- var ATTRIBUTE = /([^\s"'=<>/`]+)(?:\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s"'=<>`]+)))?/g;
74
- function attributes(body) {
75
- const found = /* @__PURE__ */ new Map();
76
- for (const match of body.matchAll(ATTRIBUTE)) {
77
- const name = match[1]?.toLowerCase();
78
- if (!name || found.has(name)) continue;
79
- found.set(name, decode(match[2] ?? match[3] ?? match[4] ?? ""));
80
- }
81
- return found;
82
- }
83
- function decode(value) {
84
- return value.replace(/&(amp|quot|apos|lt|gt|#39|#x27);/g, (_, entity) => {
85
- const words = { amp: "&", quot: '"', apos: "'", lt: "<", gt: ">", "#39": "'", "#x27": "'" };
86
- return words[entity] ?? "";
87
- });
88
- }
89
- var SPACE = /\s/;
90
- function skip(text, i, test) {
91
- while (i < text.length && test(text.charAt(i))) i++;
92
- return i;
93
- }
94
- function srcsetUrls(srcset) {
95
- const urls = [];
96
- let i = 0;
97
- while (i < srcset.length) {
98
- const start = skip(srcset, i, (char) => SPACE.test(char) || char === ",");
99
- i = skip(srcset, start, (char) => !SPACE.test(char));
100
- const url = srcset.slice(start, i);
101
- if (!url.endsWith(",")) i = skip(srcset, i, (char) => char !== ",");
102
- const clean = url.replace(/,+$/, "");
103
- if (clean) urls.push(clean);
104
- }
105
- return urls;
106
- }
107
- function close(stack, name) {
108
- const at = stack.map((open) => open.name).lastIndexOf(name);
109
- if (at >= 0) stack.length = at;
110
- }
111
- function pictureOf(parent, name, attrs) {
112
- const picture = parent?.name === "picture" ? parent.picture : void 0;
113
- if (picture && name === "source" && (attrs.has("media") || attrs.has("type"))) picture.chooses = true;
114
- return picture;
115
- }
116
- var PLANE_KINDS = /* @__PURE__ */ new Set(["image", "video", "text", "shader", "layer", "model", "group"]);
117
- var drawn = (words) => !!words && words.split(/\s+/).some((word) => PLANE_KINDS.has(word));
118
- var opened = (name, gl, end) => name === "picture" ? { name, gl, picture: { end, chooses: false } } : { name, gl };
119
- function glTags(html) {
120
- const tags = [];
121
- const stack = [];
122
- const lower = html.toLowerCase();
123
- const tag = /<!--[\s\S]*?-->|<(\/?)([a-zA-Z][\w:-]*)([^>]*)>/g;
124
- for (let match = tag.exec(html); match; match = tag.exec(html)) {
125
- const [, closing, rawName, body = ""] = match;
126
- const name = rawName?.toLowerCase();
127
- if (!name) continue;
128
- if (closing) {
129
- close(stack, name);
130
- continue;
131
- }
132
- const attrs = attributes(body);
133
- const parent = stack.at(-1);
134
- const picture = pictureOf(parent, name, attrs);
135
- const gl = drawn(attrs.get("data-umber")) || parent?.gl === true;
136
- if (gl) tags.push({ name, attrs, start: match.index, end: tag.lastIndex, picture });
137
- if (RAW.has(name)) {
138
- const end = lower.indexOf(`</${name}`, tag.lastIndex);
139
- tag.lastIndex = end < 0 ? html.length : end;
140
- } else if (!VOID.has(name) && !body.trimEnd().endsWith("/")) stack.push(opened(name, gl, tag.lastIndex));
141
- }
142
- return tags;
143
- }
144
- function drawnPictures(html) {
145
- const found = /* @__PURE__ */ new Set();
146
- for (const { name, attrs } of glTags(html)) collect(name, attrs, found);
147
- return [...found];
148
- }
149
- function collect(name, attrs, found) {
150
- const add = (url) => {
151
- if (url && !url.startsWith("data:") && !url.startsWith("blob:")) found.add(url);
152
- };
153
- add(attrs.get("data-umber-src"));
154
- if (name === "img") add(attrs.get("src"));
155
- if (name === "img" || name === "source" && attrs.get("type") !== "image/avif")
156
- for (const url of srcsetUrls(attrs.get("srcset") ?? "")) add(url);
157
- }
158
- var escape = (value) => value.replace(/&/g, "&amp;").replace(/"/g, "&quot;");
159
- function avifSrcset(attrs, replace) {
160
- const src = attrs.get("src") ?? "";
161
- const srcset = attrs.get("srcset") ?? "";
162
- let changed = srcset;
163
- for (const url of srcsetUrls(srcset)) changed = changed.replace(url, replace(url) ?? url);
164
- const implicit = src && !/\d\s*w\s*(,|$)|\s1x\s*(,|$)/.test(srcset);
165
- const fromSrc = implicit ? replace(src) : null;
166
- if (changed === srcset && !fromSrc) return null;
167
- return implicit ? [`${fromSrc ?? src}${srcset ? " 1x" : ""}`, changed].filter(Boolean).join(", ") : changed;
168
- }
169
- function tinySource(attrs, tiny) {
170
- const srcset = attrs.get("srcset") ?? "";
171
- const urls = srcsetUrls(srcset);
172
- const found = tiny([attrs.get("src"), urls.at(-1)].find(Boolean) ?? "");
173
- if (!found) return "";
174
- const widths = /\d\s*w\s*(,|$)/.test(srcset);
175
- const density = Math.round(found.width / found.fullWidth * 1e5) / 1e5;
176
- const sizes = attrs.get("sizes");
177
- const candidate = `${found.url} ${widths ? `${found.width}w` : `${density}x`}`;
178
- return `<source type="image/avif" media="(scripting: enabled)" srcset="${escape(candidate)}"${widths && sizes ? ` sizes="${escape(sizes)}"` : ""} data-umber-tiny>`;
179
- }
180
- function rewritePictures(html, replace, tiny) {
181
- const edits = [];
182
- for (const { name, attrs, start, end, picture } of glTags(html)) {
183
- if (name !== "img" || picture?.chooses) continue;
184
- const srcset = avifSrcset(attrs, replace);
185
- if (!srcset) continue;
186
- const sizes = attrs.get("sizes");
187
- const source = `${tiny ? tinySource(attrs, tiny) : ""}<source type="image/avif" srcset="${escape(srcset)}"${sizes ? ` sizes="${escape(sizes)}"` : ""}>`;
188
- if (picture) edits.push({ at: picture.end, end: picture.end, text: source });
189
- else edits.push({ at: start, end, text: `<picture data-umber-avif>${source}${html.slice(start, end)}</picture>` });
190
- }
191
- let out = "";
192
- let at = 0;
193
- for (const edit of edits.sort((a, b) => a.at - b.at)) {
194
- out += html.slice(at, edit.at) + edit.text;
195
- at = edit.end;
196
- }
197
- return out + html.slice(at);
198
- }
199
- var FALLBACK = `(()=>{const f=()=>{if(!window.__umber)for(const s of document.querySelectorAll("source[data-umber-tiny]")){const n=s.nextElementSibling,d=()=>{s.remove()};if(n&&s.parentNode.querySelector("img")?.naturalWidth){const i=new Image;i.sizes=n.sizes;i.srcset=n.srcset;i.decode().then(d,d)}else d()}},t=()=>{setTimeout(f,3e3)};document.readyState==="complete"?t():addEventListener("load",t,{once:!0})})();
200
- `;
201
- function withFallback(html, url) {
202
- const tag = `<script src="${url.replace(/"/g, "&quot;")}" defer data-umber="skip" data-umber-images></script>`;
203
- const existing = /<script[^>]*\bdata-umber-images\b[^>]*><\/script>/i;
204
- return existing.test(html) ? html.replace(existing, tag) : inHead(html, tag);
205
- }
206
- function withManifest(html, manifest) {
207
- const url = manifest.replace(/"/g, "&quot;");
208
- const tag = `<meta name="umber-assets" content="${url}"><link rel="preload" href="${url}" as="fetch" crossorigin data-umber-assets>`;
209
- const existing = /<meta\s+name=["']?umber-assets["']?[^>]*>(<link[^>]*data-umber-assets[^>]*>)?/i;
210
- return existing.test(html) ? html.replace(existing, tag) : inHead(html, tag);
211
- }
212
- function inHead(html, tag) {
213
- const head = /<\/head\s*>/i.exec(html);
214
- if (head) return `${html.slice(0, head.index)}${tag}${html.slice(head.index)}`;
215
- const open = /<head[^>]*>/i.exec(html);
216
- if (open) return `${html.slice(0, open.index + open[0].length)}${tag}${html.slice(open.index + open[0].length)}`;
217
- return `${tag}${html}`;
218
- }
219
-
220
- // tools/assets/fonts.ts
221
- var FORMATS = /^(woff2|woff|truetype|opentype)$/;
222
- var FILES = /\.(woff2?|ttf|otf)(?:[?#]|$)/i;
223
- function fontFaces(css) {
224
- const faces = [];
225
- for (const [, body = ""] of css.matchAll(/@font-face\s*\{([^}]*)\}/g)) {
226
- const read = (name) => new RegExp(`(?:^|;|\\s)${name}\\s*:\\s*([^;]+)`, "i").exec(body)?.[1]?.trim() ?? "";
227
- const family = read("font-family").replace(/^["']|["']$/g, "");
228
- const sources = [
229
- ...read("src").matchAll(/url\(\s*["']?([^"')]+)["']?\s*\)(?:\s*format\(\s*["']?([\w-]+)["']?\s*\))?/g)
230
- ];
231
- const pick = sources.find(([, url = "", format]) => format ? FORMATS.test(format) : FILES.test(url));
232
- const weightText = read("font-weight") || "400";
233
- if (!family || !pick?.[1]) continue;
234
- const weight = weightText === "bold" ? 700 : Number.parseInt(weightText, 10) || 400;
235
- const style = /italic|oblique/i.test(read("font-style")) ? "italic" : "normal";
236
- const range = /^(\d+)\s+(\d+)$/.exec(weightText);
237
- faces.push({
238
- family,
239
- weight,
240
- style,
241
- url: pick[1],
242
- ...range ? { range: [Number(range[1]), Number(range[2])] } : {}
243
- });
244
- }
245
- return faces;
246
- }
247
- var faceKey = (face) => `${face.family.toLowerCase()}|${face.weight}|${face.style}`;
248
- function stylesOf(html) {
249
- const blocks = [...html.matchAll(/<style[^>]*>([\s\S]*?)<\/style\s*>/gi)].map((match) => match[1] ?? "");
250
- const links = [];
251
- for (const [, body = ""] of html.matchAll(/<link\b([^>]*)>/gi)) {
252
- const attrs = attributes(body);
253
- if (/\bstylesheet\b/i.test(attrs.get("rel") ?? "") && attrs.get("href")) links.push(attrs.get("href") ?? "");
254
- }
255
- return { blocks, links };
256
- }
257
- var VOID2 = /^(img|br|hr|meta|link|input|source|wbr|area|base|col|embed|param|track)$/i;
258
- function glTextCharacters(html, into) {
259
- const stack = [];
260
- let inside = 0;
261
- const open = (body) => {
262
- const gl = (attributes(body).get("data-umber") ?? "").split(/\s+/).includes("text");
263
- stack.push(gl);
264
- if (gl) inside++;
265
- };
266
- const close2 = () => {
267
- if (stack.pop() === true) inside--;
268
- };
269
- for (const [, closing, name = "", body = "", text] of html.matchAll(TOKENS)) {
270
- if (text !== void 0) addText(inside ? text : "", into);
271
- else if (name && !VOID2.test(name)) {
272
- if (closing) close2();
273
- else open(body);
274
- }
275
- }
276
- }
277
- var TOKENS = /<!--[\s\S]*?-->|<(\/?)([a-zA-Z][\w:-]*)([^>]*)>|([^<]+)/g;
278
- function addText(text, into) {
279
- for (const char of decodeText(text)) into.add(char.codePointAt(0) ?? 32);
280
- }
281
- function decodeText(text) {
282
- return text.replace(/&#x([0-9a-f]+);/gi, (_, hex) => String.fromCodePoint(Number.parseInt(hex, 16))).replace(/&#(\d+);/g, (_, dec) => String.fromCodePoint(Number(dec))).replace(/&nbsp;/g, "\xA0").replace(/&amp;/g, "&").replace(/&lt;/g, "<").replace(/&gt;/g, ">").replace(/&quot;/g, '"');
283
- }
284
- function weightsIn(css, into) {
285
- into.add(400).add(700);
286
- for (const [, value = ""] of css.matchAll(/font-weight\s*:\s*([\w-]+)/gi)) {
287
- if (value === "bold") into.add(700);
288
- else if (/^\d+$/.test(value)) into.add(Number(value));
289
- }
290
- }
291
- async function siteFonts(pages, local) {
292
- const fonts = /* @__PURE__ */ new Map();
293
- const weights = /* @__PURE__ */ new Set();
294
- const variable = [];
295
- const sheets = /* @__PURE__ */ new Map();
296
- const read = (url) => {
297
- const file = local(url);
298
- if (!file) return Promise.resolve("");
299
- let css = sheets.get(file);
300
- if (!css) sheets.set(file, css = readFile(file, "utf8").catch(() => ""));
301
- return css;
302
- };
303
- const take = (css, base) => {
304
- weightsIn(css, weights);
305
- for (const face of fontFaces(css)) {
306
- const file = local(new URL(face.url, base));
307
- if (!file) continue;
308
- if (face.range) variable.push({ face, file });
309
- else if (!fonts.has(faceKey(face))) fonts.set(faceKey(face), { file });
310
- }
311
- };
312
- for (const { url, html } of pages) {
313
- const { blocks, links } = stylesOf(html);
314
- weightsIn(html.match(/style\s*=\s*"[^"]*"/gi)?.join(";") ?? "", weights);
315
- for (const block of blocks) take(block, url);
316
- for (const href of links) {
317
- const sheet = new URL(href, url);
318
- take(await read(sheet), sheet);
319
- }
320
- }
321
- for (const { face, file } of variable) {
322
- const [low, high] = face.range ?? [0, 0];
323
- for (const weight of weights) {
324
- const key = faceKey({ ...face, weight });
325
- if (weight >= low && weight <= high && !fonts.has(key)) fonts.set(key, { file, weight });
326
- }
327
- }
328
- return fonts;
329
- }
330
- var ASCII = Array.from({ length: 95 }, (_, i) => 32 + i);
331
- async function prepareFonts(fonts, chars, { native, folder, cache, skipped }) {
332
- const keep = [.../* @__PURE__ */ new Set([...ASCII, ...chars])].sort((a, b) => a - b);
333
- const out = {};
334
- for (const [face, { file, weight }] of fonts) {
335
- try {
336
- const bytes = await readFile(file);
337
- const key = native.fontKey(bytes, keep, weight);
338
- const cached = cache ? join(cache, `${key}.glyphs`) : "";
339
- const glyphs = cached && existsSync2(cached) ? await readFile(cached) : (await native.prepareFont(bytes, keep, weight)).bytes;
340
- if (cache && !existsSync2(cached)) {
341
- await mkdir(cache, { recursive: true });
342
- await writeFile(cached, glyphs);
343
- }
344
- await mkdir(folder, { recursive: true });
345
- await writeFile(join(folder, `${key}.glyphs`), glyphs);
346
- out[face] = key;
347
- } catch (err) {
348
- skipped.push(`font ${face.replace(/\|/g, " ")}: ${err instanceof Error ? err.message : String(err)}`);
349
- }
350
- }
351
- return out;
352
- }
353
-
354
- // tools/assets/site.ts
355
- var PICTURE = /\.(jpe?g|png|webp|gif)$/i;
356
- var VECTOR = /\.svg(?:[?#]|$)/i;
357
- var FLAGS = { bc7: 2, bc1: 2 | 32, astc: 4, etc2: 8, avif: 16 };
358
- var extension = (kind) => kind === "avif" ? ".avif" : `.${kind}.ktx2`;
359
- async function walk(dir, skip2) {
360
- const files = [];
361
- for (const entry of await readdir(dir, { withFileTypes: true })) {
362
- const path = join2(dir, entry.name);
363
- if (entry.isDirectory()) {
364
- if (path !== skip2 && entry.name !== "node_modules") files.push(...await walk(path, skip2));
365
- } else files.push(path);
366
- }
367
- return files;
368
- }
369
- var urlOf = (dir, file, baseUrl) => `${baseUrl}${relative(dir, file).split(sep).map(encodeURIComponent).join("/")}`;
370
- var localFile = (dir, baseUrl) => (url) => {
371
- const path = decodeURIComponent(url.pathname);
372
- if (url.origin !== "http://site" || !path.startsWith(baseUrl)) return null;
373
- const file = join2(dir, path.slice(baseUrl.length));
374
- return existsSync3(file) ? file : null;
375
- };
376
- async function findPictures(dir, folder, baseUrl, all) {
377
- const files = await walk(dir, folder);
378
- const pictures = /* @__PURE__ */ new Map();
379
- const pages = [];
380
- const skipped = [];
381
- const text = [];
382
- const chars = /* @__PURE__ */ new Set();
383
- for (const file of files.filter((path) => path.endsWith(".html"))) {
384
- const page = new URL(urlOf(dir, file, baseUrl), "http://site");
385
- const html = await readFile2(file, "utf8");
386
- let shows = /\bdata-umber\s*=\s*["']?(?:[^"'>]*\s)?text\b/.test(html);
387
- if (shows) {
388
- text.push({ url: page, html });
389
- glTextCharacters(html, chars);
390
- }
391
- for (const ref of drawnPictures(html).filter((name) => !VECTOR.test(name))) {
392
- const url = new URL(ref, page);
393
- const local = localFile(dir, baseUrl)(url);
394
- if (local && PICTURE.test(local)) pictures.set(url.pathname, local);
395
- else skipped.push(`${ref} (in ${relative(dir, file)}): not a JPEG, PNG, WebP or GIF in the site`);
396
- shows ||= Boolean(local && PICTURE.test(local));
397
- }
398
- if (shows || all) pages.push(file);
399
- }
400
- for (const file of files.filter((path) => all && PICTURE.test(path))) pictures.set(urlOf(dir, file, baseUrl), file);
401
- return { pictures, pages, skipped: [...new Set(skipped)], text, chars };
402
- }
403
- async function fromCache(cache, key) {
404
- const meta = join2(cache, `${key}.json`);
405
- if (!existsSync3(meta)) return null;
406
- const image = JSON.parse(await readFile2(meta, "utf8"));
407
- if (!image.sizes) return null;
408
- const files = [];
409
- for (const [i, kind] of image.kinds.entries()) {
410
- const path = join2(cache, `${key}${extension(kind)}`);
411
- if (!existsSync3(path)) return null;
412
- files.push({ kind, bytes: await readFile2(path), sizes: image.sizes[i] ?? [] });
413
- }
414
- return { ...image, files };
415
- }
416
- async function toCache(cache, image) {
417
- await mkdir2(cache, { recursive: true });
418
- for (const file of image.files) await writeFile2(join2(cache, `${image.key}${extension(file.kind)}`), file.bytes);
419
- const { files, ...meta } = image;
420
- const kinds = files.map((file) => file.kind);
421
- await writeFile2(
422
- join2(cache, `${image.key}.json`),
423
- JSON.stringify({ ...meta, kinds, sizes: files.map((file) => file.sizes) })
424
- );
425
- }
426
- async function pool(items, limit, work) {
427
- let next = 0;
428
- const run = async () => {
429
- while (next < items.length) {
430
- const item = items[next++];
431
- if (item !== void 0) await work(item);
432
- }
433
- };
434
- await Promise.all(Array.from({ length: Math.min(limit, items.length) }, run));
435
- }
436
- function check(options) {
437
- const formats = ["bc7", "astc", "etc2"];
438
- const bad = options.formats?.find((format) => !formats.includes(format));
439
- if (bad !== void 0) throw new Error(`unknown format "${bad}" (${formats.join(", ")})`);
440
- if (options.effort && !["fast", "normal", "best"].includes(options.effort))
441
- throw new Error(`unknown effort "${options.effort}" (fast, normal, best)`);
442
- if (options.domImages && !["tiny", "avif", "source"].includes(options.domImages))
443
- throw new Error(`unknown domImages "${options.domImages}" (tiny, avif, source)`);
444
- const whole = (value, low, high) => value === void 0 || Number.isInteger(value) && value >= low && value <= high;
445
- if (!whole(options.tinySize, 16, 4096)) throw new Error(`tinySize ${options.tinySize}: a whole number, 16 to 4096`);
446
- if (!whole(options.tinyQuality, 1, 100))
447
- throw new Error(`tinyQuality ${options.tinyQuality}: a whole number, 1 to 100`);
448
- }
449
- async function obtain(bytes, { native, settings, cache }, result) {
450
- const key = native.imageKey(bytes, settings);
451
- const kept = cache ? await fromCache(cache, key) : null;
452
- if (kept) {
453
- result.cached++;
454
- return kept;
455
- }
456
- const image = await native.prepareImage(bytes, settings);
457
- result.prepared++;
458
- if (cache) await toCache(cache, image);
459
- return image;
460
- }
461
- async function place(image, out, result) {
462
- let flags = image.alpha ? 1 : 0;
463
- for (const prepared of image.files) {
464
- flags |= FLAGS[prepared.kind];
465
- result.bytes[prepared.kind] = (result.bytes[prepared.kind] ?? 0) + prepared.bytes.length;
466
- const name = `${image.key}${extension(prepared.kind)}`;
467
- const cached = out.cache ? join2(out.cache, name) : "";
468
- if (cached && existsSync3(cached)) await copyFile(cached, join2(out.folder, name));
469
- else await writeFile2(join2(out.folder, name), prepared.bytes);
470
- }
471
- const sizes = [["bc7", "bc1"], ["astc"], ["etc2"]].map(
472
- (kinds) => image.files.find((made) => kinds.includes(made.kind))?.sizes ?? []
473
- );
474
- return [image.key, image.width, image.height, image.textureWidth, image.textureHeight, flags, image.astcBlock, sizes];
475
- }
476
- async function writePages(pages, options, manifestUrl, { smaller, tiny, fallback }) {
477
- const baseUrl = normalBase(options.baseUrl);
478
- for (const page of pages) {
479
- const html = await readFile2(page, "utf8");
480
- const pageUrl = new URL(urlOf(options.dir, page, baseUrl), "http://site");
481
- const shown = options.domImages === "source" ? html : rewritePictures(
482
- html,
483
- (ref) => smaller.get(new URL(ref, pageUrl).pathname) ?? null,
484
- tiny.size ? (ref) => tiny.get(new URL(ref, pageUrl).pathname) ?? null : void 0
485
- );
486
- const withTags = withManifest(shown, manifestUrl);
487
- const next = /<source[^>]*\bdata-umber-tiny\b/.test(withTags) ? withFallback(withTags, fallback) : withTags;
488
- if (next !== html) await writeFile2(page, next);
489
- }
490
- }
491
- async function placeholder({ bytes, key }, native, options, out) {
492
- const side = options.tinySize ?? 512;
493
- const quality = options.tinyQuality ?? 50;
494
- const name = `${key}.tiny${side}q${quality}.avif`;
495
- const kept = out.cache ? join2(out.cache, name) : "";
496
- const meta = `${kept}.json`;
497
- let made = null;
498
- if (kept && existsSync3(kept) && existsSync3(meta))
499
- made = {
500
- bytes: await readFile2(kept),
501
- width: JSON.parse(await readFile2(meta, "utf8")).width
502
- };
503
- if (!made) {
504
- const tiny = await native.tinyAvif(bytes, options.maxSize ?? 4096, side, quality);
505
- made = tiny;
506
- if (out.cache) {
507
- await mkdir2(out.cache, { recursive: true });
508
- await writeFile2(kept, tiny.bytes);
509
- await writeFile2(meta, JSON.stringify({ width: tiny.width, height: tiny.height }));
510
- }
511
- }
512
- await writeFile2(join2(out.folder, name), made.bytes);
513
- return { name, width: made.width, bytes: made.bytes.length };
514
- }
515
- var normalBase = (baseUrl = "/") => baseUrl.replace(/\/?$/, "/").replace(/^\/?/, "/");
516
- var nothing = () => ({
517
- manifest: null,
518
- prepared: 0,
519
- cached: 0,
520
- pages: 0,
521
- fonts: 0,
522
- skipped: [],
523
- bytes: { source: 0 }
524
- });
525
- function addon() {
526
- try {
527
- return loadNative();
528
- } catch (err) {
529
- return `all pictures: ${err instanceof Error ? err.message : String(err)} The site keeps its plain images.`;
530
- }
531
- }
532
- async function prepareSite(options) {
533
- check(options);
534
- const baseUrl = normalBase(options.baseUrl);
535
- const folderName = options.folder ?? "_umber";
536
- const folder = join2(options.dir, folderName);
537
- const log = options.log ?? (() => void 0);
538
- const cache = options.cache === false ? null : options.cache ?? join2("node_modules", ".cache", "umber-assets");
539
- const native = options.native ?? addon();
540
- if (typeof native === "string") return { ...nothing(), skipped: [native] };
541
- const { quality, formats, avif, avifQuality, effort, maxSize } = options;
542
- const settings = { quality, formats, avif, avifQuality, effort, maxSize };
543
- const found = await findPictures(options.dir, folder, baseUrl, options.all ?? false);
544
- const { pictures, pages, skipped } = found;
545
- const result = { ...nothing(), skipped };
546
- const fontFiles = options.fonts !== true ? /* @__PURE__ */ new Map() : await siteFonts(found.text, localFile(options.dir, baseUrl));
547
- if (!pictures.size && !fontFiles.size) return result;
548
- await mkdir2(folder, { recursive: true });
549
- const images = {};
550
- const fonts = await prepareFonts(fontFiles, found.chars, { native, folder, cache, skipped });
551
- result.fonts = Object.keys(fonts).length;
552
- const smaller = /* @__PURE__ */ new Map();
553
- const tiny = /* @__PURE__ */ new Map();
554
- const out = { folder, folderUrl: `${baseUrl}${folderName}/`, cache };
555
- const started = performance.now();
556
- await pool([...pictures], Math.max(1, Math.floor(availableParallelism() / 4)), async ([url, file]) => {
557
- const bytes = await readFile2(file);
558
- try {
559
- const image = await obtain(bytes, { native, settings, cache }, result);
560
- result.bytes.source = (result.bytes.source ?? 0) + bytes.length;
561
- const entry = images[url] = await place(image, out, result);
562
- const avifFile = image.files.find((made) => made.kind === "avif");
563
- if (avifFile && avifFile.bytes.length < bytes.length) {
564
- const avifUrl = `${out.folderUrl}${image.key}.avif`;
565
- images[avifUrl] = entry;
566
- smaller.set(url, avifUrl);
567
- if ((options.domImages ?? "tiny") === "tiny") {
568
- try {
569
- const made = await placeholder({ bytes, key: image.key }, native, options, out);
570
- const tinyUrl = `${out.folderUrl}${made.name}`;
571
- images[tinyUrl] = entry;
572
- result.bytes.tiny = (result.bytes.tiny ?? 0) + made.bytes;
573
- tiny.set(url, { url: tinyUrl, width: made.width, fullWidth: image.width });
574
- } catch (err) {
575
- log(`${url}: no placeholder (${err instanceof Error ? err.message : String(err)})`);
576
- }
577
- }
578
- }
579
- for (const note of image.notes) log(`${url}: ${note}`);
580
- } catch (err) {
581
- result.skipped.push(`${url}: ${err instanceof Error ? err.message : String(err)}`);
582
- }
583
- });
584
- const manifest = { v: 1, images: Object.fromEntries(Object.entries(images).sort()) };
585
- if (result.fonts) manifest.fonts = fonts;
586
- const text = JSON.stringify(manifest);
587
- const name = `assets.${createHash("sha256").update(text).digest("hex").slice(0, 10)}.json`;
588
- await writeFile2(join2(folder, name), text);
589
- result.manifest = `${out.folderUrl}${name}`;
590
- const fallback = `images.${createHash("sha256").update(FALLBACK).digest("hex").slice(0, 10)}.js`;
591
- if (tiny.size) await writeFile2(join2(folder, fallback), FALLBACK);
592
- await writePages(pages, options, result.manifest, { smaller, tiny, fallback: `${out.folderUrl}${fallback}` });
593
- result.pages = pages.length;
594
- const seconds = ((performance.now() - started) / 1e3).toFixed(1);
595
- log(`${pictures.size} pictures (${result.prepared} prepared, ${result.cached} from the cache) in ${seconds} s`);
596
- return result;
597
- }
598
-
599
- export {
600
- loadNative,
601
- prepareSite
602
- };
package/types/react.d.ts DELETED
@@ -1,15 +0,0 @@
1
- /**
2
- * Types for @occluze/umber/react: useScroll(), Lenis's useLenis() for Umber's umber.scroll.
3
- *
4
- * import { useScroll } from "@occluze/umber/react";
5
- * const scroll = useScroll((s) => setProgress(s.progress), []);
6
- */
7
-
8
- import type { ScrollApi } from "./scroll.js";
9
-
10
- /** umber.scroll (null until mounted, or without the scroll module); `callback` hears its "scroll" while mounted. The engine: the one on the page, or `gl`. */
11
- export declare function useScroll(
12
- callback?: (scroll: ScrollApi) => void,
13
- deps?: readonly unknown[],
14
- gl?: { readonly scroll?: ScrollApi } | null,
15
- ): ScrollApi | null;