@blackbelt-technology/pi-dashboard-deck3d 0.8.0 → 0.10.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 (106) hide show
  1. package/.pi/skills/deck3d/SKILL.agent.md +78 -0
  2. package/.pi/skills/deck3d/SKILL.md +68 -0
  3. package/.pi/skills/deck3d/reference/effects.md +185 -2
  4. package/.pi/skills/deck3d/reference/ir-fields.md +26 -3
  5. package/.pi/skills/deck3d-from-pptx/SKILL.md +134 -0
  6. package/.pi/skills/deck3d-from-pptx/reference/steps.md +72 -0
  7. package/README.md +30 -2
  8. package/assets/preview/stub-chrome.png +0 -0
  9. package/assets/preview/stub-icon.json +59 -0
  10. package/assets/preview/stub-layout.json +195 -0
  11. package/assets/preview/stub-outline.json +48 -0
  12. package/dist/cli.js +11780 -5934
  13. package/dist/harvest/harness.js +4 -4
  14. package/dist/runtime.js +5916 -4007
  15. package/fixtures/business-2031/assets/stub-chrome.png +0 -0
  16. package/fixtures/business-2031/assets/stub-icon.json +59 -0
  17. package/fixtures/business-2031/assets/stub-layout.json +195 -0
  18. package/fixtures/business-2031/assets/stub-outline.json +48 -0
  19. package/fixtures/business-2031/build-overrides.mjs +58 -13
  20. package/fixtures/business-2031/deck.agent.md +60 -0
  21. package/fixtures/business-2031/deck.json +133 -8
  22. package/fixtures/business-2031/overrides.json +133 -8
  23. package/package.json +8 -4
  24. package/scripts/gen-stub-assets.ts +31 -0
  25. package/src/art/cutout.ts +97 -0
  26. package/src/art/decode.ts +169 -0
  27. package/src/art/icon.ts +380 -0
  28. package/src/art/png.ts +232 -0
  29. package/src/art/trace.ts +288 -0
  30. package/src/check/rules.ts +13 -8
  31. package/src/cli.ts +313 -51
  32. package/src/compare/index.ts +131 -0
  33. package/src/compare/ssim.ts +91 -0
  34. package/src/fx/art-geometry.ts +137 -0
  35. package/src/fx/art3d.meta.json +30 -0
  36. package/src/fx/art3d.ts +131 -0
  37. package/src/fx/bank.meta.json +26 -0
  38. package/src/fx/bank.ts +8 -0
  39. package/src/fx/compose.ts +5 -4
  40. package/src/fx/crane.meta.json +26 -0
  41. package/src/fx/crane.ts +8 -0
  42. package/src/fx/dolly.ts +5 -1
  43. package/src/fx/fade.ts +5 -1
  44. package/src/fx/flythrough.ts +5 -1
  45. package/src/fx/frame-chrome.meta.json +17 -0
  46. package/src/fx/frame-chrome.ts +134 -0
  47. package/src/fx/haze.meta.json +19 -0
  48. package/src/fx/haze.ts +91 -0
  49. package/src/fx/icon3d.meta.json +21 -0
  50. package/src/fx/icon3d.ts +167 -0
  51. package/src/fx/index.ts +96 -66
  52. package/src/fx/iris.ts +5 -1
  53. package/src/fx/meta.schema.json +10 -2
  54. package/src/fx/path.meta.json +25 -0
  55. package/src/fx/path.ts +8 -0
  56. package/src/fx/persistent.ts +11 -0
  57. package/src/fx/revolve.meta.json +26 -0
  58. package/src/fx/revolve.ts +8 -0
  59. package/src/fx/slide-layer.meta.json +26 -0
  60. package/src/fx/slide-layer.ts +557 -0
  61. package/src/fx/slide-space.ts +142 -0
  62. package/src/fx/stub-assets.ts +117 -0
  63. package/src/fx/swing.meta.json +26 -0
  64. package/src/fx/swing.ts +8 -0
  65. package/src/fx/types.ts +63 -2
  66. package/src/ir/merge.ts +5 -2
  67. package/src/ir/schema.json +140 -3
  68. package/src/ir/types.ts +54 -0
  69. package/src/ir/validate.ts +91 -3
  70. package/src/parse/harvest/index.ts +4 -1
  71. package/src/parse/markdown.ts +38 -7
  72. package/src/pptx/baseline.ts +183 -0
  73. package/src/pptx/extract.ts +161 -0
  74. package/src/pptx/fallback.ts +70 -0
  75. package/src/pptx/import.ts +256 -0
  76. package/src/pptx/master.ts +135 -0
  77. package/src/pptx/media.ts +81 -0
  78. package/src/pptx/package.ts +109 -0
  79. package/src/pptx/ref.ts +100 -0
  80. package/src/pptx/shapes.ts +276 -0
  81. package/src/pptx/stage.ts +82 -0
  82. package/src/pptx/text.ts +202 -0
  83. package/src/pptx/theme.ts +194 -0
  84. package/src/pptx/types.ts +159 -0
  85. package/src/pptx/xfrm.ts +93 -0
  86. package/src/pptx/xml.ts +106 -0
  87. package/src/pptx/zip.ts +239 -0
  88. package/src/render/assets.ts +57 -0
  89. package/src/render/build.ts +75 -0
  90. package/src/render/index.ts +7 -2
  91. package/src/render/template.html +1 -1
  92. package/src/runtime/assets.ts +75 -0
  93. package/src/runtime/fade.ts +110 -0
  94. package/src/runtime/hud.ts +37 -9
  95. package/src/runtime/index.ts +431 -67
  96. package/src/runtime/post.ts +11 -5
  97. package/src/runtime/scene.ts +25 -2
  98. package/src/runtime/transition.ts +222 -0
  99. package/src/runtime/types.ts +13 -2
  100. package/src/serve/index.ts +199 -16
  101. package/src/util/cleanup.ts +13 -0
  102. package/src/util/confine.ts +15 -0
  103. package/src/variants/pick.ts +282 -0
  104. package/src/variants/render.ts +179 -0
  105. package/src/variants/schema.json +48 -0
  106. package/src/variants/style.ts +318 -0
@@ -0,0 +1,169 @@
1
+ /**
2
+ * Sandboxed image decoding (design D2, spec deck3d-art-tooling "Sandboxed
3
+ * image decoding"). Images decode in a headless chromium page with page
4
+ * scripts disabled and every request other than the one serving the input
5
+ * aborted; the decoded RGBA returns to Node through Playwright's evaluate
6
+ * (which runs outside the page's own script engine). SVG is rasterised as an
7
+ * `<img>`, where scripts never run and external references never load.
8
+ */
9
+ import type { Browser, BrowserContext } from "playwright";
10
+ import { closeQuietly } from "../util/cleanup.js";
11
+ import { PNG_MAX_PIXELS, type RgbaImage } from "./png.js";
12
+
13
+ export const DECODE_MAX_BYTES = 20 * 1024 * 1024;
14
+ /**
15
+ * Decoded size is bounded separately from the input size: a few KB of PNG can
16
+ * claim 30000×30000 pixels, and decoding it allocates a canvas, an RGBA buffer
17
+ * and a base64 string of that size. 4096×4096 = 64 MiB of RGBA.
18
+ */
19
+ export const DECODE_MAX_PIXELS = PNG_MAX_PIXELS;
20
+
21
+ const ORIGIN = "https://deck3d-sandbox.invalid";
22
+
23
+ export class DecodeUnavailableError extends Error {
24
+ constructor() {
25
+ super("chromium missing (npx playwright install chromium)");
26
+ this.name = "DecodeUnavailableError";
27
+ }
28
+ }
29
+
30
+ export interface Sandbox {
31
+ decode(bytes: Uint8Array, mime: string, opts?: { size?: number }): Promise<RgbaImage>;
32
+ /** URLs the page tried to fetch other than the input (for tests/audits). */
33
+ blocked: string[];
34
+ close(): Promise<void>;
35
+ }
36
+
37
+ export function sniffMime(bytes: Uint8Array): string {
38
+ if (bytes[0] === 0x89 && bytes[1] === 0x50) return "image/png";
39
+ if (bytes[0] === 0xff && bytes[1] === 0xd8) return "image/jpeg";
40
+ if (bytes[0] === 0x47 && bytes[1] === 0x49 && bytes[2] === 0x46) return "image/gif";
41
+ if (bytes[0] === 0x52 && bytes[1] === 0x49 && bytes[8] === 0x57 && bytes[9] === 0x45) return "image/webp";
42
+ const head = new TextDecoder().decode(bytes.subarray(0, 512)).trimStart();
43
+ if (head.startsWith("<svg") || head.startsWith("<?xml")) return "image/svg+xml";
44
+ return "application/octet-stream";
45
+ }
46
+
47
+ /** Pixel dimensions from the container header alone (no decoding); undefined when unknown. */
48
+ export function peekDimensions(bytes: Uint8Array): { width: number; height: number } | undefined {
49
+ const v = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
50
+ if (bytes.length >= 24 && bytes[0] === 0x89 && bytes[1] === 0x50) return { width: v.getUint32(16), height: v.getUint32(20) };
51
+ if (bytes.length >= 10 && bytes[0] === 0x47 && bytes[1] === 0x49 && bytes[2] === 0x46) return { width: v.getUint16(6, true), height: v.getUint16(8, true) };
52
+ if (bytes.length >= 4 && bytes[0] === 0xff && bytes[1] === 0xd8) {
53
+ // Walk JPEG segments to the first start-of-frame marker.
54
+ let p = 2;
55
+ while (p + 9 < bytes.length) {
56
+ if (bytes[p] !== 0xff) return undefined;
57
+ const marker = bytes[p + 1];
58
+ if (marker >= 0xc0 && marker <= 0xcf && marker !== 0xc4 && marker !== 0xc8 && marker !== 0xcc) return { height: v.getUint16(p + 5), width: v.getUint16(p + 7) };
59
+ p += 2 + v.getUint16(p + 2);
60
+ }
61
+ return undefined;
62
+ }
63
+ if (bytes.length >= 30 && bytes[0] === 0x52 && bytes[8] === 0x57) {
64
+ const kind = String.fromCharCode(bytes[12], bytes[13], bytes[14], bytes[15]);
65
+ if (kind === "VP8X") return { width: 1 + (v.getUint8(24) | (v.getUint8(25) << 8) | (v.getUint8(26) << 16)), height: 1 + (v.getUint8(27) | (v.getUint8(28) << 8) | (v.getUint8(29) << 16)) };
66
+ if (kind === "VP8 ") return { width: v.getUint16(26, true) & 0x3fff, height: v.getUint16(28, true) & 0x3fff };
67
+ if (kind === "VP8L") {
68
+ const bits = v.getUint32(21, true);
69
+ return { width: (bits & 0x3fff) + 1, height: ((bits >> 14) & 0x3fff) + 1 };
70
+ }
71
+ }
72
+ return undefined;
73
+ }
74
+
75
+ /**
76
+ * Refuse an image that would decode past the pixel cap, from its header alone
77
+ * (raster) or its requested `--size` (SVG, rasterised at size × size at most).
78
+ */
79
+ export function assertDecodable(bytes: Uint8Array, mime: string, svgSize = 1024): void {
80
+ if (bytes.length > DECODE_MAX_BYTES) throw new Error(`input is ${bytes.length} bytes (limit ${DECODE_MAX_BYTES / 1024 / 1024} MB)`);
81
+ const dims = mime === "image/svg+xml" ? { width: svgSize, height: svgSize } : peekDimensions(bytes);
82
+ if (!dims) return;
83
+ if (dims.width * dims.height > DECODE_MAX_PIXELS) {
84
+ const mp = ((dims.width * dims.height) / 1e6).toFixed(1);
85
+ throw new Error(`image is ${dims.width}×${dims.height} (${mp} megapixels; limit ${(DECODE_MAX_PIXELS / 1e6).toFixed(1)} megapixels)`);
86
+ }
87
+ }
88
+
89
+ async function launchChromium(): Promise<Browser> {
90
+ const { chromium } = await import("playwright");
91
+ return chromium.launch({ channel: "chromium" });
92
+ }
93
+
94
+ /** Launch one sandbox browser; reuse it for many decodes, then `close()`. `launch` is a test seam. */
95
+ export async function openSandbox(launch: () => Promise<Browser> = launchChromium): Promise<Sandbox> {
96
+ let browser: Browser;
97
+ try {
98
+ browser = await launch();
99
+ } catch {
100
+ throw new DecodeUnavailableError();
101
+ }
102
+ const blocked: string[] = [];
103
+ let context: BrowserContext;
104
+ try {
105
+ context = await browser.newContext({ javaScriptEnabled: false, offline: false });
106
+ } catch (err) {
107
+ // The browser is running and this is the only handle to it: release it, or it leaks.
108
+ await closeQuietly(browser);
109
+ throw err;
110
+ }
111
+ return {
112
+ blocked,
113
+ async decode(bytes, mime, opts = {}) {
114
+ assertDecodable(bytes, mime, opts.size);
115
+ const page = await context.newPage();
116
+ try {
117
+ await page.route("**/*", (route) => {
118
+ const url = route.request().url();
119
+ if (url === `${ORIGIN}/`) {
120
+ return route.fulfill({ status: 200, contentType: "text/html", body: '<!doctype html><html><body><img id="i" src="/input"></body></html>' });
121
+ }
122
+ if (url === `${ORIGIN}/input`) return route.fulfill({ status: 200, contentType: mime, body: Buffer.from(bytes) });
123
+ blocked.push(url);
124
+ return route.abort();
125
+ });
126
+ await page.goto(`${ORIGIN}/`);
127
+ const size = opts.size ?? 1024;
128
+ const result = await page.evaluate(async (longest: number) => {
129
+ const img = document.getElementById("i") as HTMLImageElement;
130
+ if (!img.complete) await new Promise((res) => img.addEventListener("load", res, { once: true }));
131
+ await img.decode().catch(() => undefined);
132
+ if (!img.naturalWidth && !img.naturalHeight && !img.width) return { error: "image failed to decode" };
133
+ return { w: img.naturalWidth || longest, h: img.naturalHeight || longest };
134
+ }, size);
135
+ if ("error" in result) throw new Error(String(result.error));
136
+ let { w, h } = result as { w: number; h: number };
137
+ // Backstop for a header `peekDimensions` could not read: check what the page decoded
138
+ // BEFORE the canvas, the RGBA buffer and the base64 string are allocated.
139
+ if (w * h > DECODE_MAX_PIXELS && mime !== "image/svg+xml") throw new Error(`image is ${w}×${h} (${((w * h) / 1e6).toFixed(1)} megapixels; limit ${(DECODE_MAX_PIXELS / 1e6).toFixed(1)} megapixels)`);
140
+ if (mime === "image/svg+xml") {
141
+ const k = size / Math.max(w, h);
142
+ w = Math.max(1, Math.round(w * k));
143
+ h = Math.max(1, Math.round(h * k));
144
+ }
145
+ const b64 = await page.evaluate(
146
+ ([W, H]) => {
147
+ const img = document.getElementById("i") as HTMLImageElement;
148
+ const canvas = document.createElement("canvas");
149
+ canvas.width = W;
150
+ canvas.height = H;
151
+ const ctx = canvas.getContext("2d") as CanvasRenderingContext2D;
152
+ ctx.drawImage(img, 0, 0, W, H);
153
+ const data = ctx.getImageData(0, 0, W, H).data;
154
+ let s = "";
155
+ for (let i = 0; i < data.length; i += 0x8000) s += String.fromCharCode(...data.subarray(i, i + 0x8000));
156
+ return btoa(s);
157
+ },
158
+ [w, h] as [number, number],
159
+ );
160
+ return { width: w, height: h, data: new Uint8Array(Buffer.from(b64, "base64")) };
161
+ } finally {
162
+ await closeQuietly(page);
163
+ }
164
+ },
165
+ async close() {
166
+ await browser.close();
167
+ },
168
+ };
169
+ }
@@ -0,0 +1,380 @@
1
+ /**
2
+ * `art icon` (spec deck3d-art-tooling): an SVG parsed as DATA — no browser,
3
+ * no script, no entity expansion — flattened into polylines in viewBox space.
4
+ * Paths (`M L H V C S Q T A Z`, absolute and relative), lines, polylines,
5
+ * polygons, rects, circles and ellipses; group and element transforms
6
+ * composed. External references are ignored with a warning.
7
+ */
8
+
9
+ import { parseXml, type XNode } from "../pptx/xml.js";
10
+ import { hasDoctype } from "../pptx/zip.js";
11
+
12
+ export const ICON_LIMITS = { maxBytes: 2 * 1024 * 1024, maxElements: 50_000, maxPoints: 500_000 };
13
+
14
+ export type P2 = [number, number];
15
+
16
+ export interface IconPolyline {
17
+ points: P2[];
18
+ width: number;
19
+ closed: boolean;
20
+ }
21
+
22
+ export interface IconOutput {
23
+ version: 1;
24
+ viewBox: [number, number, number, number];
25
+ polylines: IconPolyline[];
26
+ }
27
+
28
+ export class IconLimitError extends Error {
29
+ constructor(message: string) {
30
+ super(message);
31
+ this.name = "IconLimitError";
32
+ }
33
+ }
34
+
35
+ /** Affine 2×3 matrix `[a, b, c, d, e, f]` (SVG order). */
36
+ type M = [number, number, number, number, number, number];
37
+ const I: M = [1, 0, 0, 1, 0, 0];
38
+ const mul = (m: M, n: M): M => [
39
+ m[0] * n[0] + m[2] * n[1],
40
+ m[1] * n[0] + m[3] * n[1],
41
+ m[0] * n[2] + m[2] * n[3],
42
+ m[1] * n[2] + m[3] * n[3],
43
+ m[0] * n[4] + m[2] * n[5] + m[4],
44
+ m[1] * n[4] + m[3] * n[5] + m[5],
45
+ ];
46
+ const apply = (m: M, [x, y]: P2): P2 => [m[0] * x + m[2] * y + m[4], m[1] * x + m[3] * y + m[5]];
47
+
48
+ export function parseTransform(src: string | undefined): M {
49
+ let m: M = I;
50
+ if (!src) return m;
51
+ for (const [, fn, args] of src.matchAll(/(\w+)\s*\(([^)]*)\)/g)) {
52
+ const a = (args.match(/-?[\d.]+(?:e-?\d+)?/gi) ?? []).map(Number);
53
+ let t: M = I;
54
+ if (fn === "matrix" && a.length === 6) t = a as M;
55
+ else if (fn === "translate") t = [1, 0, 0, 1, a[0] ?? 0, a[1] ?? 0];
56
+ else if (fn === "scale") t = [a[0] ?? 1, 0, 0, a[1] ?? a[0] ?? 1, 0, 0];
57
+ else if (fn === "rotate") {
58
+ const r = ((a[0] ?? 0) * Math.PI) / 180;
59
+ const rot: M = [Math.cos(r), Math.sin(r), -Math.sin(r), Math.cos(r), 0, 0];
60
+ t = a.length >= 3 ? mul(mul([1, 0, 0, 1, a[1], a[2]], rot), [1, 0, 0, 1, -a[1], -a[2]]) : rot;
61
+ } else if (fn === "skewX") t = [1, 0, Math.tan(((a[0] ?? 0) * Math.PI) / 180), 1, 0, 0];
62
+ else if (fn === "skewY") t = [1, Math.tan(((a[0] ?? 0) * Math.PI) / 180), 0, 1, 0, 0];
63
+ m = mul(m, t);
64
+ }
65
+ return m;
66
+ }
67
+
68
+ /** Flatness: max deviation of a flattened curve from the true curve, in user units. */
69
+ const TOL = 0.1;
70
+
71
+ /**
72
+ * Points still allowed across ONE SVG. Curves and arcs check their segment
73
+ * count against it BEFORE building anything, so hostile coordinates (1e12)
74
+ * fail fast instead of allocating millions of points first.
75
+ */
76
+ class PointBudget {
77
+ readonly limit: number;
78
+ left: number;
79
+ constructor(limit: number) {
80
+ this.limit = limit;
81
+ this.left = limit;
82
+ }
83
+ take(n: number): void {
84
+ if (!Number.isFinite(n) || n > this.left) throw new IconLimitError(`flattens to more than ${this.limit} points (limit)`);
85
+ this.left -= n;
86
+ }
87
+ }
88
+
89
+ function cubic(p0: P2, p1: P2, p2: P2, p3: P2, out: P2[], budget: PointBudget): void {
90
+ const len = Math.hypot(p1[0] - p0[0], p1[1] - p0[1]) + Math.hypot(p2[0] - p1[0], p2[1] - p1[1]) + Math.hypot(p3[0] - p2[0], p3[1] - p2[1]);
91
+ const n = Math.max(4, Math.ceil(Math.sqrt(len / TOL)));
92
+ budget.take(n);
93
+ for (let i = 1; i <= n; i++) {
94
+ const t = i / n;
95
+ const u = 1 - t;
96
+ out.push([
97
+ u * u * u * p0[0] + 3 * u * u * t * p1[0] + 3 * u * t * t * p2[0] + t * t * t * p3[0],
98
+ u * u * u * p0[1] + 3 * u * u * t * p1[1] + 3 * u * t * t * p2[1] + t * t * t * p3[1],
99
+ ]);
100
+ }
101
+ }
102
+
103
+ function quad(p0: P2, p1: P2, p2: P2, out: P2[], budget: PointBudget): void {
104
+ cubic(p0, [p0[0] + (2 / 3) * (p1[0] - p0[0]), p0[1] + (2 / 3) * (p1[1] - p0[1])], [p2[0] + (2 / 3) * (p1[0] - p2[0]), p2[1] + (2 / 3) * (p1[1] - p2[1])], p2, out, budget);
105
+ }
106
+
107
+ /** SVG elliptical arc (spec F.6.5 endpoint → centre parameterisation), sampled on the ellipse. */
108
+ export function arc(p0: P2, rxIn: number, ryIn: number, phiDeg: number, large: boolean, sweep: boolean, p1: P2, out: P2[], budget: PointBudget): void {
109
+ let rx = Math.abs(rxIn);
110
+ let ry = Math.abs(ryIn);
111
+ if (rx === 0 || ry === 0 || (p0[0] === p1[0] && p0[1] === p1[1])) {
112
+ out.push(p1);
113
+ return;
114
+ }
115
+ const phi = (phiDeg * Math.PI) / 180;
116
+ const cos = Math.cos(phi);
117
+ const sin = Math.sin(phi);
118
+ const dx = (p0[0] - p1[0]) / 2;
119
+ const dy = (p0[1] - p1[1]) / 2;
120
+ const x1 = cos * dx + sin * dy;
121
+ const y1 = -sin * dx + cos * dy;
122
+ const lambda = (x1 * x1) / (rx * rx) + (y1 * y1) / (ry * ry);
123
+ if (lambda > 1) {
124
+ rx *= Math.sqrt(lambda);
125
+ ry *= Math.sqrt(lambda);
126
+ }
127
+ const num = rx * rx * ry * ry - rx * rx * y1 * y1 - ry * ry * x1 * x1;
128
+ const den = rx * rx * y1 * y1 + ry * ry * x1 * x1;
129
+ const k = (large === sweep ? -1 : 1) * Math.sqrt(Math.max(0, num / den));
130
+ const cx1 = (k * rx * y1) / ry;
131
+ const cy1 = (-k * ry * x1) / rx;
132
+ const cx = cos * cx1 - sin * cy1 + (p0[0] + p1[0]) / 2;
133
+ const cy = sin * cx1 + cos * cy1 + (p0[1] + p1[1]) / 2;
134
+ const ang = (ux: number, uy: number, vx: number, vy: number) => {
135
+ const a = Math.atan2(ux * vy - uy * vx, ux * vx + uy * vy);
136
+ return a;
137
+ };
138
+ const t1 = ang(1, 0, (x1 - cx1) / rx, (y1 - cy1) / ry);
139
+ let dt = ang((x1 - cx1) / rx, (y1 - cy1) / ry, (-x1 - cx1) / rx, (-y1 - cy1) / ry);
140
+ if (!sweep && dt > 0) dt -= 2 * Math.PI;
141
+ else if (sweep && dt < 0) dt += 2 * Math.PI;
142
+ const r = Math.max(rx, ry);
143
+ const step = 2 * Math.acos(Math.max(-1, 1 - TOL / r));
144
+ const n = Math.max(2, Math.ceil(Math.abs(dt) / step));
145
+ budget.take(n);
146
+ for (let i = 1; i <= n; i++) {
147
+ const t = t1 + (dt * i) / n;
148
+ const ex = rx * Math.cos(t);
149
+ const ey = ry * Math.sin(t);
150
+ out.push(i === n ? p1 : [cos * ex - sin * ey + cx, sin * ex + cos * ey + cy]);
151
+ }
152
+ }
153
+
154
+ /** Flatten SVG path data into subpaths (`closed` per subpath). */
155
+ export function flattenPath(d: string, budget = new PointBudget(ICON_LIMITS.maxPoints)): Array<{ points: P2[]; closed: boolean }> {
156
+ const tokens = d.match(/[a-zA-Z]|-?(?:\d+\.?\d*|\.\d+)(?:e[-+]?\d+)?/gi) ?? [];
157
+ const subs: Array<{ points: P2[]; closed: boolean }> = [];
158
+ let cur: P2[] = [];
159
+ let pos: P2 = [0, 0];
160
+ let start: P2 = [0, 0];
161
+ let lastCtrl: P2 | undefined;
162
+ let lastCmd = "";
163
+ let i = 0;
164
+ let cmd = "";
165
+ const n = () => Number(tokens[i++]);
166
+ const flush = (closed: boolean) => {
167
+ if (cur.length > 1) subs.push({ points: cur, closed });
168
+ cur = [];
169
+ };
170
+ while (i < tokens.length) {
171
+ if (/[a-zA-Z]/.test(tokens[i])) cmd = tokens[i++];
172
+ else if (!cmd) break;
173
+ else if (cmd.toUpperCase() === "Z") {
174
+ // A number after `Z` has no command to belong to (Z takes no arguments);
175
+ // skip it, or the loop never advances.
176
+ i++;
177
+ continue;
178
+ }
179
+ const rel = cmd === cmd.toLowerCase();
180
+ const C = cmd.toUpperCase();
181
+ const at = (x: number, y: number): P2 => (rel ? [pos[0] + x, pos[1] + y] : [x, y]);
182
+ switch (C) {
183
+ case "M": {
184
+ flush(false);
185
+ pos = at(n(), n());
186
+ start = pos;
187
+ cur = [pos];
188
+ cmd = rel ? "l" : "L";
189
+ break;
190
+ }
191
+ case "L":
192
+ pos = at(n(), n());
193
+ cur.push(pos);
194
+ break;
195
+ case "H": {
196
+ const x = n();
197
+ pos = [rel ? pos[0] + x : x, pos[1]];
198
+ cur.push(pos);
199
+ break;
200
+ }
201
+ case "V": {
202
+ const y = n();
203
+ pos = [pos[0], rel ? pos[1] + y : y];
204
+ cur.push(pos);
205
+ break;
206
+ }
207
+ case "C": {
208
+ const c1 = at(n(), n());
209
+ const c2 = at(n(), n());
210
+ const p = at(n(), n());
211
+ cubic(pos, c1, c2, p, cur, budget);
212
+ lastCtrl = c2;
213
+ pos = p;
214
+ break;
215
+ }
216
+ case "S": {
217
+ const c1: P2 = lastCtrl && /[CS]/i.test(lastCmd) ? [2 * pos[0] - lastCtrl[0], 2 * pos[1] - lastCtrl[1]] : pos;
218
+ const c2 = at(n(), n());
219
+ const p = at(n(), n());
220
+ cubic(pos, c1, c2, p, cur, budget);
221
+ lastCtrl = c2;
222
+ pos = p;
223
+ break;
224
+ }
225
+ case "Q": {
226
+ const c = at(n(), n());
227
+ const p = at(n(), n());
228
+ quad(pos, c, p, cur, budget);
229
+ lastCtrl = c;
230
+ pos = p;
231
+ break;
232
+ }
233
+ case "T": {
234
+ const c: P2 = lastCtrl && /[QT]/i.test(lastCmd) ? [2 * pos[0] - lastCtrl[0], 2 * pos[1] - lastCtrl[1]] : pos;
235
+ const p = at(n(), n());
236
+ quad(pos, c, p, cur, budget);
237
+ lastCtrl = c;
238
+ pos = p;
239
+ break;
240
+ }
241
+ case "A": {
242
+ const rx = n();
243
+ const ry = n();
244
+ const phi = n();
245
+ const large = n() !== 0;
246
+ const sweep = n() !== 0;
247
+ const p = at(n(), n());
248
+ arc(pos, rx, ry, phi, large, sweep, p, cur, budget);
249
+ pos = p;
250
+ break;
251
+ }
252
+ case "Z":
253
+ pos = start;
254
+ flush(true);
255
+ cur = [pos];
256
+ break;
257
+ default:
258
+ i++;
259
+ }
260
+ lastCmd = C;
261
+ if (!/[CSQT]/.test(C)) lastCtrl = undefined;
262
+ }
263
+ flush(false);
264
+ return subs;
265
+ }
266
+
267
+ function attrNum(n: XNode, name: string, d = 0): number {
268
+ const v = Number.parseFloat(n.attrs[name] ?? "");
269
+ return Number.isFinite(v) ? v : d;
270
+ }
271
+
272
+ /** Presentation attribute or `style` declaration. */
273
+ function styleProp(n: XNode, name: string): string | undefined {
274
+ const m = new RegExp(`(?:^|;)\\s*${name}\\s*:\\s*([^;]+)`).exec(n.attrs.style ?? "");
275
+ return m?.[1].trim() ?? n.attrs[name];
276
+ }
277
+
278
+ function ellipsePoints(cx: number, cy: number, rx: number, ry: number, budget: PointBudget): P2[] {
279
+ const n = Math.max(12, Math.ceil((2 * Math.PI) / (2 * Math.acos(Math.max(-1, 1 - TOL / Math.max(rx, ry, 1e-6))))));
280
+ budget.take(n);
281
+ return Array.from({ length: n }, (_, i) => [cx + rx * Math.cos((2 * Math.PI * i) / n), cy + ry * Math.sin((2 * Math.PI * i) / n)] as P2);
282
+ }
283
+
284
+ export function svgToPolylines(bytes: Uint8Array, name = "input.svg"): { icon: IconOutput; warnings: string[] } {
285
+ if (bytes.length > ICON_LIMITS.maxBytes) throw new IconLimitError(`${name}: ${bytes.length} bytes exceeds the ${ICON_LIMITS.maxBytes / 1024 / 1024} MB limit`);
286
+ if (hasDoctype(bytes)) throw new IconLimitError(`${name}: contains <!DOCTYPE (DTDs and entities are rejected)`);
287
+ const text = new TextDecoder().decode(bytes);
288
+ const elements = (text.match(/<[A-Za-z]/g) ?? []).length;
289
+ if (elements > ICON_LIMITS.maxElements) throw new IconLimitError(`${name}: ${elements} elements exceeds the ${ICON_LIMITS.maxElements} element limit`);
290
+ const root = parseXml(text);
291
+ const warnings: string[] = [];
292
+ const vb = (root.attrs.viewBox ?? "").split(/[\s,]+/).map(Number);
293
+ const viewBox: [number, number, number, number] =
294
+ vb.length === 4 && vb.every(Number.isFinite) ? (vb as [number, number, number, number]) : [0, 0, attrNum(root, "width", 24), attrNum(root, "height", 24)];
295
+ const polylines: IconPolyline[] = [];
296
+ let points = 0;
297
+ const emit = (pts: P2[], closed: boolean, m: M, width: number) => {
298
+ points += pts.length;
299
+ if (points > ICON_LIMITS.maxPoints) throw new IconLimitError(`${name}: flattens to more than ${ICON_LIMITS.maxPoints} points (limit)`);
300
+ const scale = Math.sqrt(Math.abs(m[0] * m[3] - m[1] * m[2])) || 1;
301
+ polylines.push({ points: pts.map((p) => apply(m, p).map((v) => Math.round(v * 1000) / 1000) as P2), width: Math.round(width * scale * 1000) / 1000, closed });
302
+ };
303
+ const walk = (n: XNode, parent: M, inheritedWidth: number) => {
304
+ const local = n.name.replace(/^svg:/, "");
305
+ const m = mul(parent, parseTransform(n.attrs.transform));
306
+ const sw = Number.parseFloat(styleProp(n, "stroke-width") ?? "");
307
+ const width = Number.isFinite(sw) ? sw : inheritedWidth;
308
+ const href = n.attrs.href ?? n.attrs["xlink:href"];
309
+ if (href !== undefined && (local === "image" || local === "use" || local === "feImage")) {
310
+ warnings.push(`warning ${name}: <${local}> reference '${href}' ignored`);
311
+ return;
312
+ }
313
+ switch (local) {
314
+ case "path":
315
+ for (const s of flattenPath(n.attrs.d ?? "", new PointBudget(ICON_LIMITS.maxPoints - points))) emit(s.points, s.closed, m, width);
316
+ break;
317
+ case "line":
318
+ emit([[attrNum(n, "x1"), attrNum(n, "y1")], [attrNum(n, "x2"), attrNum(n, "y2")]], false, m, width);
319
+ break;
320
+ case "polyline":
321
+ case "polygon": {
322
+ const nums = (n.attrs.points ?? "").match(/-?(?:\d+\.?\d*|\.\d+)(?:e[-+]?\d+)?/gi)?.map(Number) ?? [];
323
+ const pts: P2[] = [];
324
+ for (let k = 0; k + 1 < nums.length; k += 2) pts.push([nums[k], nums[k + 1]]);
325
+ if (pts.length > 1) emit(pts, local === "polygon", m, width);
326
+ break;
327
+ }
328
+ case "rect": {
329
+ const x = attrNum(n, "x");
330
+ const y = attrNum(n, "y");
331
+ const w = attrNum(n, "width");
332
+ const h = attrNum(n, "height");
333
+ const rx = Math.min(w / 2, attrNum(n, "rx", attrNum(n, "ry")));
334
+ const ry = Math.min(h / 2, attrNum(n, "ry", rx));
335
+ if (rx > 0 && ry > 0) {
336
+ const d = `M${x + rx} ${y}H${x + w - rx}A${rx} ${ry} 0 0 1 ${x + w} ${y + ry}V${y + h - ry}A${rx} ${ry} 0 0 1 ${x + w - rx} ${y + h}H${x + rx}A${rx} ${ry} 0 0 1 ${x} ${y + h - ry}V${y + ry}A${rx} ${ry} 0 0 1 ${x + rx} ${y}Z`;
337
+ for (const s of flattenPath(d, new PointBudget(ICON_LIMITS.maxPoints - points))) emit(s.points, true, m, width);
338
+ } else
339
+ emit(
340
+ [
341
+ [x, y],
342
+ [x + w, y],
343
+ [x + w, y + h],
344
+ [x, y + h],
345
+ ],
346
+ true,
347
+ m,
348
+ width,
349
+ );
350
+ break;
351
+ }
352
+ case "circle":
353
+ emit(ellipsePoints(attrNum(n, "cx"), attrNum(n, "cy"), attrNum(n, "r"), attrNum(n, "r"), new PointBudget(ICON_LIMITS.maxPoints - points)), true, m, width);
354
+ break;
355
+ case "ellipse":
356
+ emit(ellipsePoints(attrNum(n, "cx"), attrNum(n, "cy"), attrNum(n, "rx"), attrNum(n, "ry"), new PointBudget(ICON_LIMITS.maxPoints - points)), true, m, width);
357
+ break;
358
+ case "defs":
359
+ case "clipPath":
360
+ case "mask":
361
+ case "style":
362
+ case "script":
363
+ case "metadata":
364
+ case "title":
365
+ case "desc":
366
+ return;
367
+ default:
368
+ break;
369
+ }
370
+ for (const c of n.children) walk(c, m, width);
371
+ };
372
+ try {
373
+ walk(root, I, 1);
374
+ } catch (err) {
375
+ // The budget fires deep inside a curve and does not know the file name.
376
+ if (err instanceof IconLimitError && !err.message.startsWith(name)) throw new IconLimitError(`${name}: ${err.message}`);
377
+ throw err;
378
+ }
379
+ return { icon: { version: 1, viewBox, polylines }, warnings };
380
+ }