@enhance-eng/enhance 0.1.37 → 0.1.39

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.
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import { $ as canvasRenderPendingSchema, At as PartialBatchError, B as canvasCaptureCapabilityInputSchema, Bn as applyCanvasOperationsOutputSchema, Bt as PROTOTYPE_ARTIFACT_MANIFEST_PATH, C as canvasSnapshotToken, Cn as canvasTextPropsWithContent, Dn as canvasPrototypePropsSchema, E as resolveCanvasSnapshot, En as canvasConversionMetadataSchema, Fn as DEFAULT_CANVAS_REFERENCE_PAGE_ID, G as canvasRenderCapabilityInputSchema, Gn as getCanvasDocumentOutputSchema, Gt as getPrototypePublishStatusOutputSchema, Hn as canvasLayoutWithoutCssProperties, Ht as createPrototypeArtifactOutputSchema, I as canvasDuplicateCapabilityInputSchema, In as canvasReferencePageOf, J as prototypePublishCapabilityInputSchema, Jn as canvasNodeStylePatchSchema, Jt as submitPrototypeArtifactOutputSchema, K as canvasWriteHtmlCapabilityInputSchema, Kt as prototypeArtifactManifestSchema, Ln as resolveCanvasReference, Mt as transcriptOutputSchema, N as canvasAssetImportOutputSchema, Nn as createCanvasPreparationOutputSchema, On as canvasRecordingPropsSchema, Ot as hasCanvasReferenceScope, P as canvasArrangeCapabilityInputSchema, Pn as getCanvasPreparationOutputSchema, Qn as canvasRenderStateSchema, Qt as createAgentTokenOutputSchema, Rn as PAGE_KIND, Rt as getRecordingOutputSchema, S as canvasExchangeDigest, Sn as canvasTextChangeBetween, St as canvasEditCapabilityInputSchema, T as encodeCanvasExchangeToken, Tn as canvasCaptureSchema, Tt as canvasReferenceNodeIds, U as canvasApplyCapabilityInputSchema, Un as textOf, Ut as foldPrototypeArtifactPath, Vn as getCanvasMutationOutputSchema, Vt as attachPrototypeArtifactOutputSchema, W as canvasReadCapabilityInputSchema, Wn as mapCanvasFontSources, Wt as getPrototypeArtifactCapabilitiesOutputSchema, X as transcriptReadCapabilityInputSchema, Xn as getCanvasConversionOutputSchema, Y as recordingSnapshotCapabilityInputSchema, Yn as createCanvasConversionOutputSchema, Yt as getMeOutputSchema, Z as canvasRenderBatchRequestSchema, Zt as cliAuthConfigurationSchema, _r as canvasImageAssetIdentityFromPath, ar as canvasReadableSceneDocumentSchema, bn as applyCanvasTypographyPatch, bt as canvasMakeEditableCapabilityInputSchema, cr as canvasAuthoredStyleDeclarations, dt as canvasTranscriptCursorSchema, en as listOrganisationsOutputSchema, fr as canvasCssValue, ft as canvasResourcesCursorSchema, gr as canvasFontAssetIdentityFromPath, gt as canvasFindInputSchema, hr as reserveCanvasAssetOutputSchema, ht as canvasFindCursorSchema, ir as getCanvasRenderOutputSchema, it as canvasRemoveCapabilityInputSchema, j as canvasAssetImportCapabilityInputSchema, jn as AGENT_CLIENT_HEADER, jt as CliError, k as operationStatusInputSchema, kn as beginCanvasActivityOutputSchema, kt as parseCanvasReference, lr as canvasAxisStyleProperties, lt as canvasUpdateHtmlCapabilityInputSchema, mr as reserveCanvasAssetInputSchema, nr as createRecordingSnapshotOutputSchema, nt as canvasRenderRequestSchema, or as canvasSceneDocumentSchema, ot as canvasOutlineCursorSchema, pr as canvasAssetUploadOutputSchema, q as commentAttentionCapabilityInputSchema, qt as prototypeArtifactPathSchema, rr as downloadCanvasRenderOutputSchema, rt as canvasRenderFileSchema, s as toRemoteError, st as canvasReadInputSchema, tr as createCanvasRenderOutputSchema, ut as canvasUpdateHtmlInputSchema, v as canvasPrototypeCapabilityInputSchema, vr as canvasAdditionalStyleSchema, vt as canvasInsertHtmlCapabilityInputSchema, w as decodeCanvasExchangeToken, wt as assertCanvasReferenceNodes, xn as canvasCssTypographyOwners, xr as listCanvasesOutputSchema, zn as applyCanvasOperationsInputSchema } from "./cli-output-identity.lib-i4KnVAYs.mjs";
2
+ import { $ as canvasRenderPendingSchema, $n as canvasNodeStylePatchSchema, An as canvasReferencePageOf, Ar as canvasBlendModeSchema, At as PartialBatchError, B as canvasCaptureCapabilityInputSchema, Bn as IMAGE_KIND, Bt as PROTOTYPE_ARTIFACT_MANIFEST_PATH, C as canvasSnapshotToken, Cn as canvasTextPropsWithContent, Cr as canvasImageAssetIdentityFromPath, Dn as canvasPrototypePropsSchema, Dr as CANVAS_RICH_TEXT_STYLE_PROPERTIES, E as resolveCanvasSnapshot, En as canvasConversionMetadataSchema, Er as hasCanvasRichTextPaints, G as canvasRenderCapabilityInputSchema, Gn as applyCanvasOperationsOutputSchema, Gt as getPrototypePublishStatusOutputSchema, Hn as RECTANGLE_KIND, Ht as createPrototypeArtifactOutputSchema, I as canvasDuplicateCapabilityInputSchema, In as createCanvasPreparationOutputSchema, J as prototypePublishCapabilityInputSchema, Jn as textOf, Jt as submitPrototypeArtifactOutputSchema, K as canvasWriteHtmlCapabilityInputSchema, Kn as getCanvasMutationOutputSchema, Kt as prototypeArtifactManifestSchema, Ln as getCanvasPreparationOutputSchema, Mn as beginCanvasActivityOutputSchema, Mt as transcriptOutputSchema, N as canvasAssetImportOutputSchema, On as canvasRecordingPropsSchema, Or as canvasAdditionalStyleSchema, Ot as hasCanvasReferenceScope, P as canvasArrangeCapabilityInputSchema, Pn as AGENT_CLIENT_HEADER, Pr as listCanvasesOutputSchema, Qt as createAgentTokenOutputSchema, Rn as FRAME_KIND, Rt as getRecordingOutputSchema, S as canvasExchangeDigest, Sn as canvasTextChangeBetween, Sr as canvasFontAssetIdentityFromPath, St as canvasEditCapabilityInputSchema, T as encodeCanvasExchangeToken, Tn as canvasCaptureSchema, Tr as canvasRichTextValueOf, Tt as canvasReferenceNodeIds, U as canvasApplyCapabilityInputSchema, Un as TEXT_KIND, Ut as foldPrototypeArtifactPath, Vn as PAGE_KIND, Vt as attachPrototypeArtifactOutputSchema, W as canvasReadCapabilityInputSchema, Wn as applyCanvasOperationsInputSchema, Wt as getPrototypeArtifactCapabilitiesOutputSchema, X as transcriptReadCapabilityInputSchema, Xn as getCanvasDocumentOutputSchema, Y as recordingSnapshotCapabilityInputSchema, Yn as mapCanvasFontSources, Yt as getMeOutputSchema, Z as canvasRenderBatchRequestSchema, Zt as cliAuthConfigurationSchema, _r as canvasCssTokens, bn as applyCanvasTypographyPatch, br as reserveCanvasAssetInputSchema, bt as canvasMakeEditableCapabilityInputSchema, cr as downloadCanvasRenderOutputSchema, dr as canvasSceneDocumentSchema, dt as canvasTranscriptCursorSchema, en as listOrganisationsOutputSchema, er as createCanvasConversionOutputSchema, ft as canvasResourcesCursorSchema, gt as canvasFindInputSchema, ht as canvasFindCursorSchema, it as canvasRemoveCapabilityInputSchema, j as canvasAssetImportCapabilityInputSchema, jn as resolveCanvasReference, jr as canvasPaintSchema, jt as CliError, k as operationStatusInputSchema, kn as DEFAULT_CANVAS_REFERENCE_PAGE_ID, kr as CANVAS_BLEND_MODES, kt as parseCanvasReference, lr as getCanvasRenderOutputSchema, lt as canvasUpdateHtmlCapabilityInputSchema, mr as canvasAxisStyleProperties, nt as canvasRenderRequestSchema, or as createCanvasRenderOutputSchema, ot as canvasOutlineCursorSchema, pr as canvasAuthoredStyleDeclarations, q as commentAttentionCapabilityInputSchema, qn as canvasLayoutWithoutCssProperties, qt as prototypeArtifactPathSchema, rr as canvasRenderStateSchema, rt as canvasRenderFileSchema, s as toRemoteError, sr as createRecordingSnapshotOutputSchema, st as canvasReadInputSchema, tr as getCanvasConversionOutputSchema, ur as canvasReadableSceneDocumentSchema, ut as canvasUpdateHtmlInputSchema, v as canvasPrototypeCapabilityInputSchema, vr as canvasCssValue, vt as canvasInsertHtmlCapabilityInputSchema, w as decodeCanvasExchangeToken, wr as canvasRichTextOf, wt as assertCanvasReferenceNodes, xn as canvasCssTypographyOwners, xr as reserveCanvasAssetOutputSchema, yr as canvasAssetUploadOutputSchema, zn as GROUP_KIND } from "./cli-output-identity.lib-DgHRuXTI.mjs";
3
3
  import process from "node:process";
4
4
  import { z } from "zod";
5
5
  import { homedir, tmpdir } from "node:os";
@@ -20,6 +20,14 @@ import { createTRPCUntypedClient, httpLink } from "@trpc/client";
20
20
  import { spawn } from "node:child_process";
21
21
  import { createServer } from "node:http";
22
22
 
23
+ //#region ../../packages/canvas-format/src/canvas-sort-key.lib.ts
24
+ /**
25
+ * Sibling order by sort key. Fractional keys compare by code unit, so "Zz" comes before "a0";
26
+ * locale collation would put them the other way round.
27
+ */
28
+ const compareCanvasSortKeys = (left, right) => left < right ? -1 : left > right ? 1 : 0;
29
+
30
+ //#endregion
23
31
  //#region ../../packages/contract/src/canvas/canvas-additional-style-patch.lib.ts
24
32
  const reorderedDeclarations = (declarations, order) => {
25
33
  const ordered = new Set(order);
@@ -69,6 +77,778 @@ const canvasAdditionalStylePatchBetween = (before, after) => {
69
77
  };
70
78
  };
71
79
 
80
+ //#endregion
81
+ //#region ../../packages/contract/src/canvas/canvas-color-css.lib.ts
82
+ const BYTE_MAX$1 = 255;
83
+ const CHANNEL_PRECISION = 1e6;
84
+ const roundedChannel = (value) => Math.round(value * BYTE_MAX$1 * CHANNEL_PRECISION) / CHANNEL_PRECISION;
85
+ const canvasColorCss = (color, opacity = 1) => {
86
+ const alpha = color.alpha * opacity;
87
+ if (color.space === "srgb") {
88
+ const channels = [
89
+ color.red,
90
+ color.green,
91
+ color.blue
92
+ ].map((channel) => String(roundedChannel(channel))).join(" ");
93
+ return alpha === 1 ? `rgb(${channels})` : `rgb(${channels} / ${String(alpha)})`;
94
+ }
95
+ const channels = `${String(color.red)} ${String(color.green)} ${String(color.blue)}`;
96
+ return `color(${color.space} ${channels} / ${String(alpha)})`;
97
+ };
98
+
99
+ //#endregion
100
+ //#region ../../packages/contract/src/canvas/canvas-gradient-field.lib.ts
101
+ const UNIT_BOUNDS = {
102
+ x: 0,
103
+ y: 0,
104
+ width: 1,
105
+ height: 1
106
+ };
107
+ const fieldPoint = (paint, point) => {
108
+ const [a, b, c, d, e, f] = paint.transform;
109
+ const determinant = a * d - b * c;
110
+ const x = point.x - e, y = point.y - f;
111
+ return {
112
+ x: (d * x - c * y) / determinant,
113
+ y: (a * y - b * x) / determinant
114
+ };
115
+ };
116
+ const canvasGradientFieldCoordinates = (paint, bounds = UNIT_BOUNDS) => [
117
+ {
118
+ x: bounds.x,
119
+ y: bounds.y
120
+ },
121
+ {
122
+ x: bounds.x + bounds.width,
123
+ y: bounds.y
124
+ },
125
+ {
126
+ x: bounds.x,
127
+ y: bounds.y + bounds.height
128
+ },
129
+ {
130
+ x: bounds.x + bounds.width,
131
+ y: bounds.y + bounds.height
132
+ }
133
+ ].flatMap((point) => {
134
+ const local = fieldPoint(paint, point);
135
+ return [local.x, local.y];
136
+ });
137
+
138
+ //#endregion
139
+ //#region ../../packages/contract/src/canvas/canvas-angular-gradient.lib.ts
140
+ const HALF$1 = .5;
141
+ const FULL_TURN$1 = 360;
142
+ const PERCENT$4 = 100;
143
+ const FIELD_UNIT = 1024;
144
+ const LINEAR_COEFFICIENTS = 4;
145
+ const gradient = (paint, center, isAlpha) => {
146
+ const stops = paint.stops.map((stop) => {
147
+ return `${isAlpha ? `rgb(255 255 255 / ${String(stop.color.alpha * paint.opacity)})` : canvasColorCss({
148
+ ...stop.color,
149
+ alpha: 1
150
+ })} ${String(stop.position * FULL_TURN$1)}deg`;
151
+ });
152
+ return `conic-gradient(from 90deg at ${String(center)}% ${String(center)}% in srgb, ${stops.join(", ")})`;
153
+ };
154
+ /** Separate alpha from color so translucent stops interpolate straight sRGB, as copied by Figma. */
155
+ const canvasAngularGradientField = (paint, bounds) => {
156
+ const coordinates = canvasGradientFieldCoordinates(paint, bounds);
157
+ const low = Math.min(0, ...coordinates);
158
+ const span = Math.max(1, ...coordinates) - low;
159
+ const center = (HALF$1 - low) / span * PERCENT$4;
160
+ const matrix = paint.transform.map((value, index) => index < LINEAR_COEFFICIENTS ? value / FIELD_UNIT : value);
161
+ const style = `width:100%;height:100%;background-image:${gradient(paint, center, false)};mask-image:${gradient(paint, center, true)};`;
162
+ return `<g transform="matrix(${matrix.map(String).join(" ")})"><foreignObject x="${String(low * FIELD_UNIT)}" y="${String(low * FIELD_UNIT)}" width="${String(span * FIELD_UNIT)}" height="${String(span * FIELD_UNIT)}" overflow="visible"><div xmlns="http://www.w3.org/1999/xhtml" style="${style}"></div></foreignObject></g>`;
163
+ };
164
+ const canvasAngularGradientSvg = (paint) => `<svg xmlns="http://www.w3.org/2000/svg" width="100%" height="100%" viewBox="0 0 1 1" preserveAspectRatio="none">${canvasAngularGradientField(paint)}</svg>`;
165
+
166
+ //#endregion
167
+ //#region ../../packages/contract/src/canvas/canvas-path-serialization.lib.ts
168
+ const areSamePoints = (left, right) => {
169
+ if (left === void 0 || right === void 0) return false;
170
+ return left.x === right.x && left.y === right.y;
171
+ };
172
+ const withoutClosingDuplicates = (points) => {
173
+ const result = [...points];
174
+ while (result.length > 1 && areSamePoints(result[0], result.at(-1))) result.pop();
175
+ while (result.length > 1 && areSamePoints(result[0], result[1])) result.splice(1, 1);
176
+ return result;
177
+ };
178
+ const straightPathTokens = (path) => {
179
+ const tokens = path.match(/[MLHVZ]|[+-]?\d*\.?\d+(?:e[+-]?\d+)?/giu) ?? [];
180
+ if (tokens.join("") !== path.replaceAll(/[\s,]/gu, "") || !/^M/iu.test(tokens[0] ?? "") || !/^Z$/iu.test(tokens.at(-1) ?? "")) return null;
181
+ return tokens;
182
+ };
183
+ const straightPoint = (command, tokens, index, current) => {
184
+ const kind = command.toUpperCase();
185
+ const first = Number(tokens[index]);
186
+ const second = ["M", "L"].includes(kind) ? Number(tokens[index + 1]) : first;
187
+ if (!Number.isFinite(first) || !Number.isFinite(second)) return null;
188
+ const origin = command === command.toLowerCase() ? current : {
189
+ x: 0,
190
+ y: 0
191
+ };
192
+ const point = {
193
+ x: kind === "V" ? current.x : origin.x + first,
194
+ y: kind === "H" ? current.y : origin.y + second
195
+ };
196
+ return Number.isFinite(point.x) && Number.isFinite(point.y) ? point : null;
197
+ };
198
+ /** Reads only a single straight contour; curves remain owned by the geometry engine. */
199
+ const canvasStraightPathVertices = (path) => {
200
+ const tokens = straightPathTokens(path);
201
+ if (tokens === null) return null;
202
+ const points = [];
203
+ let command = "M";
204
+ let index = 0;
205
+ let current = {
206
+ x: 0,
207
+ y: 0
208
+ };
209
+ while (index < tokens.length - 1) {
210
+ const token = tokens[index] ?? "";
211
+ if (/^[MLHV]$/iu.test(token)) {
212
+ command = token;
213
+ index += 1;
214
+ }
215
+ const kind = command.toUpperCase();
216
+ if (kind === "M" && points.length > 0) return null;
217
+ const point = straightPoint(command, tokens, index, current);
218
+ if (point === null) return null;
219
+ current = point;
220
+ points.push(current);
221
+ index += ["M", "L"].includes(kind) ? 2 : 1;
222
+ command = command.replace("M", "L").replace("m", "l");
223
+ }
224
+ return index === tokens.length - 1 ? withoutClosingDuplicates(points) : null;
225
+ };
226
+
227
+ //#endregion
228
+ //#region ../../packages/ui/src/geometry/corner-contour.lib.ts
229
+ const QUARTER_TURN$1 = Math.PI / 2;
230
+ const CUBIC_CONTROL_PARTS = 3;
231
+ const CONTOUR_PRECISION = 1e6;
232
+ const number = (value) => String(Math.round(value * CONTOUR_PRECISION) / CONTOUR_PRECISION);
233
+ const point = ([x, y]) => `${number(x)} ${number(y)}`;
234
+ const corner = (radius, [horizontalNeighbour, verticalNeighbour], { width, height }, smoothing) => {
235
+ if (radius <= 0) return {
236
+ radius: 0,
237
+ reach: 0,
238
+ smoothing: 0
239
+ };
240
+ const edgeBudget = (length, neighbour) => {
241
+ const product = length * radius;
242
+ const total = radius + neighbour;
243
+ if (Number.isFinite(product) && Number.isFinite(total)) return product / total;
244
+ const ratio = Math.min(radius, neighbour) / Math.max(radius, neighbour);
245
+ return (radius >= neighbour ? length : length * ratio) / (1 + ratio);
246
+ };
247
+ const budget = Math.min(edgeBudget(width, horizontalNeighbour), edgeBudget(height, verticalNeighbour));
248
+ const effectiveRadius = Math.min(radius, budget);
249
+ if (effectiveRadius === 0) return {
250
+ radius: 0,
251
+ reach: 0,
252
+ smoothing: 0
253
+ };
254
+ const effectiveSmoothing = Math.max(0, Math.min(smoothing, budget / effectiveRadius - 1));
255
+ return {
256
+ radius: effectiveRadius,
257
+ reach: effectiveRadius * (1 + effectiveSmoothing),
258
+ smoothing: effectiveSmoothing
259
+ };
260
+ };
261
+ const cornerCommands = (value, transform) => {
262
+ const { radius, reach, smoothing } = value;
263
+ const start = point(transform([reach, 0]));
264
+ if (radius === 0) return `L${start}`;
265
+ const angle = smoothing * QUARTER_TURN$1 / 2;
266
+ const x = radius * (1 - Math.sin(angle));
267
+ const y = radius * (1 - Math.cos(angle));
268
+ const tangent = angle === 0 ? 0 : y / Math.tan(angle);
269
+ const straightControl = (reach - x - tangent) / CUBIC_CONTROL_PARTS;
270
+ const firstControl = point(transform([reach - 2 * straightControl, 0]));
271
+ const secondControl = point(transform([x + tangent, 0]));
272
+ const arcStart = point(transform([x, y]));
273
+ const arcEnd = point(transform([y, x]));
274
+ const thirdControl = point(transform([0, x + tangent]));
275
+ const fourthControl = point(transform([0, reach - 2 * straightControl]));
276
+ const end = point(transform([0, reach]));
277
+ return `L${start}C${firstControl} ${secondControl} ${arcStart}${smoothing === 1 ? "" : `A${number(radius)} ${number(radius)} 0 0 1 ${arcEnd}`}C${thirdControl} ${fourthControl} ${end}`;
278
+ };
279
+ const cornersFrom = (radius, size) => {
280
+ const { topLeft, topRight, bottomRight, bottomLeft, smoothing = 0 } = radius;
281
+ return [
282
+ corner(topLeft, [topRight, bottomLeft], size, smoothing),
283
+ corner(topRight, [topLeft, bottomRight], size, smoothing),
284
+ corner(bottomRight, [bottomLeft, topRight], size, smoothing),
285
+ corner(bottomLeft, [bottomRight, topLeft], size, smoothing)
286
+ ];
287
+ };
288
+ const constrainedCornerRadii = (radius, size) => {
289
+ const [topLeft, topRight, bottomRight, bottomLeft] = cornersFrom(radius, {
290
+ width: Math.max(0, size.width),
291
+ height: Math.max(0, size.height)
292
+ });
293
+ return {
294
+ topLeft: topLeft.radius,
295
+ topRight: topRight.radius,
296
+ bottomRight: bottomRight.radius,
297
+ bottomLeft: bottomLeft.radius
298
+ };
299
+ };
300
+ /**
301
+ * @justified intent
302
+ * Figma's curve keeps its circle center while replacing the tangent ends with cubics.
303
+ * Edge budgets reduce smoothing before radius; independent corners share each edge
304
+ * in proportion to their radii. Native flattened Figma paths are the browser-test oracle.
305
+ */
306
+ const cornerContour = (radius, size, offset = [0, 0]) => {
307
+ const width = Math.max(0, size.width);
308
+ const height = Math.max(0, size.height);
309
+ if (width === 0 || height === 0) return "M0 0Z";
310
+ const [topLeft, topRight, bottomRight, bottomLeft] = cornersFrom(radius, {
311
+ width,
312
+ height
313
+ });
314
+ return [
315
+ `M${point([offset[0], topLeft.reach + offset[1]])}`,
316
+ cornerCommands(topLeft, ([x, y]) => [y + offset[0], x + offset[1]]),
317
+ cornerCommands(topRight, ([x, y]) => [width - x + offset[0], y + offset[1]]),
318
+ cornerCommands(bottomRight, ([x, y]) => [width - y + offset[0], height - x + offset[1]]),
319
+ cornerCommands(bottomLeft, ([x, y]) => [x + offset[0], height - y + offset[1]]),
320
+ "Z"
321
+ ].join("");
322
+ };
323
+
324
+ //#endregion
325
+ //#region ../../packages/ui/src/geometry/corner-contour-offset.lib.ts
326
+ const MAX_SUBDIVISIONS = 16;
327
+ const FLATNESS_DIVISOR = 8;
328
+ const ARC_ARGUMENTS_AFTER_RADIUS = 4;
329
+ const MIN_POLYGON_POINTS = 3;
330
+ const PRECISION = 1e5;
331
+ const FLATNESS = .01;
332
+ const EPSILON = 1e-9;
333
+ const midpoint = (a, b) => [(a[0] + b[0]) / 2, (a[1] + b[1]) / 2];
334
+ const distance = (a, b) => Math.hypot(a[0] - b[0], a[1] - b[1]);
335
+ const cross = (a, b) => a[0] * b[1] - a[1] * b[0];
336
+ const difference = (a, b) => [a[0] - b[0], a[1] - b[1]];
337
+ const stable = (value) => String(Math.round(value * PRECISION) / PRECISION);
338
+ const flattenCubic = (points, result, depth = 0) => {
339
+ const [a, b, c, d] = points;
340
+ const chord = distance(a, d);
341
+ if (depth >= MAX_SUBDIVISIONS || distance(a, b) + distance(b, c) + distance(c, d) - chord <= FLATNESS / FLATNESS_DIVISOR) {
342
+ result.push(d);
343
+ return;
344
+ }
345
+ const ab = midpoint(a, b);
346
+ const bc = midpoint(b, c);
347
+ const cd = midpoint(c, d);
348
+ const abc = midpoint(ab, bc);
349
+ const bcd = midpoint(bc, cd);
350
+ const middle = midpoint(abc, bcd);
351
+ flattenCubic([
352
+ a,
353
+ ab,
354
+ abc,
355
+ middle
356
+ ], result, depth + 1);
357
+ flattenCubic([
358
+ middle,
359
+ bcd,
360
+ cd,
361
+ d
362
+ ], result, depth + 1);
363
+ };
364
+ const flattenArc = (start, end, radius, result) => {
365
+ const delta = difference(end, start);
366
+ const length = distance(start, end);
367
+ if (length < EPSILON) return;
368
+ const centreDistance = Math.sqrt(Math.max(0, radius * radius - length * length / 4));
369
+ const centre = [(start[0] + end[0]) / 2 - delta[1] * centreDistance / length, (start[1] + end[1]) / 2 + delta[0] * centreDistance / length];
370
+ const first = Math.atan2(start[1] - centre[1], start[0] - centre[0]);
371
+ let sweep = Math.atan2(end[1] - centre[1], end[0] - centre[0]) - first;
372
+ if (sweep < 0) sweep += 2 * Math.PI;
373
+ const steps = Math.max(1, Math.ceil(sweep / (2 * Math.acos(Math.max(-1, 1 - FLATNESS / radius)))));
374
+ for (let index = 1; index <= steps; index += 1) {
375
+ const angle = first + sweep * index / steps;
376
+ result.push([centre[0] + radius * Math.cos(angle), centre[1] + radius * Math.sin(angle)]);
377
+ }
378
+ };
379
+ const flattenedContour = (path) => {
380
+ const tokens = path.match(/[MLCAZ]|-?(?:\d*\.)?\d+(?:e[-+]?\d+)?/giu) ?? [];
381
+ const points = [];
382
+ let cursor = 0;
383
+ const number = () => Number(tokens[cursor++]);
384
+ const readPoint = () => [number(), number()];
385
+ const readCommand = (command) => {
386
+ const start = points.at(-1) ?? [0, 0];
387
+ if (command === "M" || command === "L") {
388
+ points.push(readPoint());
389
+ return;
390
+ }
391
+ if (command === "C") {
392
+ flattenCubic([
393
+ start,
394
+ readPoint(),
395
+ readPoint(),
396
+ readPoint()
397
+ ], points);
398
+ return;
399
+ }
400
+ if (command === "A") {
401
+ const radius = number();
402
+ cursor += ARC_ARGUMENTS_AFTER_RADIUS;
403
+ flattenArc(start, readPoint(), radius, points);
404
+ }
405
+ };
406
+ while (cursor < tokens.length) readCommand(tokens[cursor++] ?? "Z");
407
+ return points.filter((point, index) => distance(point, points[(index + 1) % points.length] ?? point) > EPSILON);
408
+ };
409
+ const offsetEdge = (a, b, outset) => {
410
+ const [x, y] = difference(b, a);
411
+ const length = Math.hypot(x, y);
412
+ const shift = [y * outset / length, -x * outset / length];
413
+ return [[a[0] + shift[0], a[1] + shift[1]], [b[0] + shift[0], b[1] + shift[1]]];
414
+ };
415
+ const intersection = (a, b, c, d) => {
416
+ const ab = difference(b, a);
417
+ const cd = difference(d, c);
418
+ const divisor = cross(ab, cd);
419
+ if (Math.abs(divisor) < EPSILON) return midpoint(b, c);
420
+ const amount = cross(difference(c, a), cd) / divisor;
421
+ return [a[0] + amount * ab[0], a[1] + amount * ab[1]];
422
+ };
423
+ const insetPolygon = (points, outset) => {
424
+ let polygon = [...points];
425
+ for (const [index, point] of points.entries()) {
426
+ const next = points[(index + 1) % points.length];
427
+ if (next === void 0) continue;
428
+ const [a, b] = offsetEdge(point, next, outset);
429
+ const edge = difference(b, a);
430
+ const clipped = [];
431
+ for (const [candidateIndex, candidate] of polygon.entries()) {
432
+ const following = polygon[(candidateIndex + 1) % polygon.length] ?? candidate;
433
+ const isInside = cross(edge, difference(candidate, a)) >= -1e-9;
434
+ const isFollowingInside = cross(edge, difference(following, a)) >= -1e-9;
435
+ if (isInside) clipped.push(candidate);
436
+ if (isInside !== isFollowingInside) clipped.push(intersection(candidate, following, a, b));
437
+ }
438
+ polygon = clipped;
439
+ if (polygon.length === 0) break;
440
+ }
441
+ return polygon;
442
+ };
443
+ /** A parallel convex contour in CSS pixels; collapsed insets return an empty path. */
444
+ const offsetConvexContour = (contour, outset) => {
445
+ if (outset === 0) return contour;
446
+ const points = flattenedContour(contour);
447
+ const offset = outset < 0 ? insetPolygon(points, outset) : points.map((point, index) => {
448
+ const before = points[(index + points.length - 1) % points.length] ?? point;
449
+ const after = points[(index + 1) % points.length] ?? point;
450
+ const incoming = offsetEdge(before, point, outset);
451
+ const outgoing = offsetEdge(point, after, outset);
452
+ return intersection(...incoming, ...outgoing);
453
+ });
454
+ return offset.length < MIN_POLYGON_POINTS ? "" : offset.map((point, index) => `${index === 0 ? "M" : "L"}${stable(point[0])} ${stable(point[1])}`).join("") + "Z";
455
+ };
456
+ const offsetCornerContour = (radius, size, outset) => size.width <= 0 || size.height <= 0 ? "" : offsetConvexContour(cornerContour(radius, size), outset);
457
+
458
+ //#endregion
459
+ //#region ../../packages/contract/src/canvas/canvas-geometry-affine.lib.ts
460
+ const HALF_TURN = 180;
461
+ /** The same center-based affine transform is used by scene geometry and browser paint. */
462
+ const canvasGeometryLocalMatrixFor = (box, transform, residual) => {
463
+ const radians = (transform.rotation ?? 0) * Math.PI / HALF_TURN;
464
+ const cosine = Math.cos(radians);
465
+ const sine = Math.sin(radians);
466
+ const scaleX = transform.flipHorizontal === true ? -1 : 1;
467
+ const scaleY = transform.flipVertical === true ? -1 : 1;
468
+ const baseA = cosine * scaleX;
469
+ const baseB = sine * scaleX;
470
+ const baseC = -sine * scaleY;
471
+ const baseD = cosine * scaleY;
472
+ const a = residual === void 0 ? baseA : baseA * residual.a + baseC * residual.b;
473
+ const b = residual === void 0 ? baseB : baseB * residual.a + baseD * residual.b;
474
+ const c = residual === void 0 ? baseC : baseA * residual.c + baseC * residual.d;
475
+ const d = residual === void 0 ? baseD : baseB * residual.c + baseD * residual.d;
476
+ const centerX = box.width / 2;
477
+ const centerY = box.height / 2;
478
+ return {
479
+ a,
480
+ b,
481
+ c,
482
+ d,
483
+ e: box.x + centerX - a * centerX - c * centerY,
484
+ f: box.y + centerY - b * centerX - d * centerY
485
+ };
486
+ };
487
+ const MATRIX_COMPONENTS = 6;
488
+ const residualOf = (node) => {
489
+ const value = node.additionalStyles?.declarations.find((declaration) => declaration.enabled && declaration.property === "--enhance-group-affine-residual")?.value;
490
+ if (value === void 0) return;
491
+ const parts = /^matrix\(([^)]*)\)$/iu.exec(value)?.[1]?.split(",").map((part) => Number(part.trim()));
492
+ if (parts?.length !== MATRIX_COMPONENTS || parts.some((part) => !Number.isFinite(part))) return null;
493
+ const [a, b, c, d] = parts;
494
+ return a === void 0 || b === void 0 || c === void 0 || d === void 0 ? null : {
495
+ a,
496
+ b,
497
+ c,
498
+ d
499
+ };
500
+ };
501
+ /** A layer's placement in its parent: its box, rotation, flips and any group residual. */
502
+ const canvasNodeLocalMatrixOf = (node) => {
503
+ const residual = residualOf(node);
504
+ return residual === null || node.box === void 0 ? null : canvasGeometryLocalMatrixFor(node.box, node.layout ?? {}, residual);
505
+ };
506
+
507
+ //#endregion
508
+ //#region ../../packages/contract/src/canvas/canvas-polygon-geometry.lib.ts
509
+ const CUBIC_DEGREE = 3;
510
+ const ANGLE_DIVISOR = 4;
511
+ const shifted = (point, direction, distance) => ({
512
+ x: point.x + direction.x * distance,
513
+ y: point.y + direction.y * distance
514
+ });
515
+ const coordinates = (point) => `${String(point.x)} ${String(point.y)}`;
516
+ const unitTowards = (point, target, distance) => ({
517
+ x: (target.x - point.x) / distance,
518
+ y: (target.y - point.y) / distance
519
+ });
520
+ const polygonVertices = (node, width, height) => {
521
+ const isStar = node.innerRatio !== void 0;
522
+ const count = node.count;
523
+ const inner = node.innerRatio ?? 1;
524
+ const length = isStar ? count * 2 : count;
525
+ return Array.from({ length }, (_, index) => {
526
+ const radius = index % 2 === 0 ? 1 : inner;
527
+ const angle = -Math.PI / 2 + index * Math.PI * 2 / length;
528
+ return {
529
+ x: width / 2 + Math.cos(angle) * width * radius / 2,
530
+ y: height / 2 + Math.sin(angle) * height * radius / 2
531
+ };
532
+ });
533
+ };
534
+ const polygonCorner = (vertices, index) => {
535
+ const vertex = vertices[index];
536
+ const previous = vertices[(index + vertices.length - 1) % vertices.length];
537
+ const next = vertices[(index + 1) % vertices.length];
538
+ if (vertex === void 0 || previous === void 0 || next === void 0) return void 0;
539
+ const previousLength = Math.hypot(previous.x - vertex.x, previous.y - vertex.y);
540
+ const nextLength = Math.hypot(next.x - vertex.x, next.y - vertex.y);
541
+ if (previousLength === 0 || nextLength === 0) return void 0;
542
+ const before = unitTowards(vertex, previous, previousLength);
543
+ const after = unitTowards(vertex, next, nextLength);
544
+ const angle = Math.acos(Math.min(1, Math.max(-1, before.x * after.x + before.y * after.y)));
545
+ if (angle === 0 || angle === Math.PI) return void 0;
546
+ return {
547
+ vertex,
548
+ before,
549
+ after,
550
+ previousLength,
551
+ nextLength,
552
+ angle,
553
+ cotangent: 1 / Math.tan(angle / 2)
554
+ };
555
+ };
556
+ const cornerSide = (corner, direction, radius, smoothing) => {
557
+ const offset = radius * corner.cotangent;
558
+ const start = shifted(corner.vertex, direction, offset * (1 + smoothing));
559
+ const tangent = shifted(corner.vertex, direction, offset);
560
+ const center = shifted(corner.vertex, {
561
+ x: corner.before.x + corner.after.x,
562
+ y: corner.before.y + corner.after.y
563
+ }, radius / Math.sin(corner.angle));
564
+ const normal = unitTowards(tangent, center, radius);
565
+ const angle = (Math.PI - corner.angle) * smoothing / 2;
566
+ const end = shifted(shifted(tangent, direction, -radius * Math.sin(angle)), normal, radius * (1 - Math.cos(angle)));
567
+ const travel = {
568
+ x: -direction.x * Math.cos(angle) + normal.x * Math.sin(angle),
569
+ y: -direction.y * Math.cos(angle) + normal.y * Math.sin(angle)
570
+ };
571
+ const second = shifted(end, travel, -radius * Math.tan(angle / 2));
572
+ return {
573
+ start,
574
+ first: {
575
+ x: start.x + (second.x - start.x) * 2 / CUBIC_DEGREE,
576
+ y: start.y + (second.y - start.y) * 2 / CUBIC_DEGREE
577
+ },
578
+ second,
579
+ end,
580
+ travel
581
+ };
582
+ };
583
+ const cornerPath = (corner, radius, smoothing) => {
584
+ const before = cornerSide(corner, corner.before, radius, smoothing);
585
+ const after = cornerSide(corner, corner.after, radius, smoothing);
586
+ const handle = ANGLE_DIVISOR / CUBIC_DEGREE * radius * Math.tan((Math.PI - corner.angle) * (1 - smoothing) / ANGLE_DIVISOR);
587
+ const first = shifted(before.end, before.travel, handle);
588
+ const second = shifted(after.end, after.travel, handle);
589
+ const curve = (a, b, end) => `C${coordinates(a)} ${coordinates(b)} ${coordinates(end)}`;
590
+ return coordinates(before.start) + (smoothing > 0 ? curve(before.first, before.second, before.end) : "") + curve(first, second, after.end) + (smoothing > 0 ? curve(after.second, after.first, after.start) : "");
591
+ };
592
+ const canvasPolygonContour = (vertices, radii, smoothing) => {
593
+ const corners = vertices.map((_, index) => polygonCorner(vertices, index));
594
+ const radiusAt = (index) => typeof radii === "number" ? radii : radii[index] ?? 0;
595
+ return `${vertices.map((vertex, index) => {
596
+ const corner = corners[index];
597
+ const previousIndex = (index + vertices.length - 1) % vertices.length;
598
+ const nextIndex = (index + 1) % vertices.length;
599
+ const previous = corners[previousIndex];
600
+ const next = corners[nextIndex];
601
+ const radius = radiusAt(index);
602
+ const prefix = index === 0 ? "M" : "L";
603
+ if (radius === 0 || corner === void 0) return prefix + coordinates(vertex);
604
+ const maximum = Math.min(corner.previousLength / (corner.cotangent + (previous?.cotangent ?? 0) * (radiusAt(previousIndex) / radius)), corner.nextLength / (corner.cotangent + (next?.cotangent ?? 0) * (radiusAt(nextIndex) / radius)));
605
+ const limitedRadius = Math.min(radius, maximum);
606
+ const limitedSmoothing = Math.min(smoothing, Math.max(0, maximum / limitedRadius - 1));
607
+ return prefix + cornerPath(corner, limitedRadius, limitedSmoothing);
608
+ }).join("")}Z`;
609
+ };
610
+ const canvasPolygonPath = (node, width, height) => canvasPolygonContour(polygonVertices(node, width, height), node.cornerRadius, node.cornerSmoothing);
611
+
612
+ //#endregion
613
+ //#region ../../packages/contract/src/canvas/canvas-path-rounding.lib.ts
614
+ const RECTANGLE_CORNERS = 4;
615
+ const MINIMUM_POLYGON_CORNERS = 3;
616
+ const vertices = /* @__PURE__ */ new WeakMap();
617
+ const booleanVertices = /* @__PURE__ */ new WeakMap();
618
+ const booleanContours = (geometry) => {
619
+ if (booleanVertices.has(geometry)) return booleanVertices.get(geometry) ?? null;
620
+ const parts = geometry.result.path.match(/M[^M]*/gu) ?? [];
621
+ const contours = parts.map((path) => {
622
+ const points = canvasStraightPathVertices(path);
623
+ return {
624
+ path,
625
+ vertices: points !== null && points.length >= MINIMUM_POLYGON_CORNERS ? points : null
626
+ };
627
+ });
628
+ const result = parts.length > 0 && parts.join("") === geometry.result.path ? contours : null;
629
+ booleanVertices.set(geometry, result);
630
+ return result;
631
+ };
632
+ const canvasRoundedBooleanPath = (geometry, box, radius) => {
633
+ const original = {
634
+ kind: "path",
635
+ path: geometry.result.path,
636
+ fillRule: geometry.result.fillRule,
637
+ viewBox: {
638
+ x: 0,
639
+ y: 0,
640
+ width: box.width,
641
+ height: box.height
642
+ }
643
+ };
644
+ if (radius === void 0 || radius.topLeft === 0 || [
645
+ radius.topRight,
646
+ radius.bottomLeft,
647
+ radius.bottomRight
648
+ ].some((value) => value !== radius.topLeft)) return original;
649
+ const contours = booleanContours(geometry);
650
+ return contours === null ? original : {
651
+ ...original,
652
+ path: contours.map((contour) => contour.vertices === null ? contour.path : canvasPolygonContour(contour.vertices, radius.topLeft, radius.smoothing ?? 0)).join("")
653
+ };
654
+ };
655
+ const rectangleVertices = (geometry) => {
656
+ if (vertices.has(geometry)) return vertices.get(geometry) ?? null;
657
+ const points = canvasStraightPathVertices(geometry.path);
658
+ const result = points?.length === RECTANGLE_CORNERS && points.every((point, index) => {
659
+ const next = points[(index + 1) % RECTANGLE_CORNERS];
660
+ const after = points[(index + 2) % RECTANGLE_CORNERS];
661
+ return next !== void 0 && after !== void 0 && (next.x - point.x) * (after.y - next.y) > (next.y - point.y) * (after.x - next.x);
662
+ }) ? points : null;
663
+ vertices.set(geometry, result);
664
+ return result;
665
+ };
666
+ const canvasRoundedRectanglePath = (geometry, radius, box) => {
667
+ if (box.width <= 0 || box.height <= 0) return geometry;
668
+ const radii = [
669
+ radius.topLeft,
670
+ radius.topRight,
671
+ radius.bottomRight,
672
+ radius.bottomLeft
673
+ ];
674
+ if (radii.every((value) => value === 0) && geometry.viewBox.x === 0 && geometry.viewBox.y === 0 && box.width === geometry.viewBox.width && box.height === geometry.viewBox.height) return geometry;
675
+ const points = rectangleVertices(geometry);
676
+ if (points === null) return geometry;
677
+ const local = points.map((point) => ({
678
+ x: (point.x - geometry.viewBox.x) * box.width / geometry.viewBox.width,
679
+ y: (point.y - geometry.viewBox.y) * box.height / geometry.viewBox.height
680
+ }));
681
+ return {
682
+ ...geometry,
683
+ path: canvasPolygonContour(local, radii, radius.smoothing ?? 0),
684
+ viewBox: {
685
+ x: 0,
686
+ y: 0,
687
+ width: box.width,
688
+ height: box.height
689
+ }
690
+ };
691
+ };
692
+
693
+ //#endregion
694
+ //#region ../../packages/contract/src/canvas/canvas-composition-geometry.lib.ts
695
+ const PERCENT_BASE = 100;
696
+ const EMPTY_RADIUS = {
697
+ topLeft: 0,
698
+ topRight: 0,
699
+ bottomRight: 0,
700
+ bottomLeft: 0
701
+ };
702
+ const RADIUS_PROPERTIES = [
703
+ "border-top-left-radius",
704
+ "border-top-right-radius",
705
+ "border-bottom-right-radius",
706
+ "border-bottom-left-radius"
707
+ ];
708
+ const radiusValue = (value, size) => {
709
+ if (value === void 0) return 0;
710
+ if (typeof value === "number") return Number.isFinite(value) && value >= 0 ? value : null;
711
+ const match = /^\s*(\d+(?:\.\d+)?)(px|%)?\s*$/u.exec(value);
712
+ if (match === null) return null;
713
+ const amount = Number(match[1]);
714
+ return match[2] === "%" ? size * amount / PERCENT_BASE : amount;
715
+ };
716
+ const rectangleRadius = (node) => {
717
+ if (node.appearance?.radius !== void 0) return node.appearance.radius;
718
+ if (node.box === void 0) return null;
719
+ const base = node.styles["border-radius"];
720
+ const [topLeft, topRight, bottomRight, bottomLeft] = RADIUS_PROPERTIES.map((property) => radiusValue(node.styles[property] ?? base, Math.min(node.box?.width ?? 0, node.box?.height ?? 0)));
721
+ return topLeft === null || topRight === null || bottomRight === null || bottomLeft === null ? null : {
722
+ topLeft: topLeft ?? 0,
723
+ topRight: topRight ?? 0,
724
+ bottomRight: bottomRight ?? 0,
725
+ bottomLeft: bottomLeft ?? 0
726
+ };
727
+ };
728
+ const ellipsePath = (width, height) => {
729
+ const x = width / 2;
730
+ const y = height / 2;
731
+ return `M0 ${String(y)}A${String(x)} ${String(y)} 0 1 0 ${String(width)} ${String(y)}A${String(x)} ${String(y)} 0 1 0 0 ${String(y)}Z`;
732
+ };
733
+ const shapePathOf = (node, editable) => {
734
+ if (node.geometry?.kind === "path") return node.geometry;
735
+ const box = node.box;
736
+ if (box !== void 0 && node.geometry?.kind === "polygon" && box.width > 0 && box.height > 0) return {
737
+ kind: "path",
738
+ path: canvasPolygonPath(node.geometry, box.width, box.height),
739
+ fillRule: "nonzero",
740
+ viewBox: {
741
+ x: 0,
742
+ y: 0,
743
+ width: box.width,
744
+ height: box.height
745
+ }
746
+ };
747
+ if (box === void 0 || !["rectangle", "frame"].includes(node.component) || box.width <= 0 || box.height <= 0) return "Choose a closed shape or an editable vector path.";
748
+ const radius = rectangleRadius(node);
749
+ if (radius === null) return "This shape uses a corner expression that cannot be edited as a path.";
750
+ return {
751
+ kind: "path",
752
+ fillRule: "nonzero",
753
+ path: node.styles["border-radius"] === "50%" && node.appearance?.radius === void 0 && RADIUS_PROPERTIES.every((property) => node.styles[property] === void 0) ? ellipsePath(box.width, box.height) : cornerContour(editable && node.component === "rectangle" && node.appearance?.radius !== void 0 ? EMPTY_RADIUS : {
754
+ ...EMPTY_RADIUS,
755
+ ...radius
756
+ }, box),
757
+ viewBox: {
758
+ x: 0,
759
+ y: 0,
760
+ width: box.width,
761
+ height: box.height
762
+ }
763
+ };
764
+ };
765
+ const canvasShapePathOf = (node) => {
766
+ if (node.geometry?.kind === "boolean" && node.box !== void 0) return node.geometry.result.isEmpty ? "This shape has no closed geometry." : canvasRoundedBooleanPath(node.geometry, node.box, node.appearance?.radius);
767
+ const geometry = shapePathOf(node, false);
768
+ return typeof geometry !== "string" && node.geometry?.kind === "path" && node.component === "rectangle" && node.appearance?.radius !== void 0 && node.box !== void 0 ? canvasRoundedRectanglePath(geometry, node.appearance.radius, node.box) : geometry;
769
+ };
770
+ const canvasShapeOperandOf = (node) => {
771
+ const geometry = canvasShapePathOf(node);
772
+ if (typeof geometry === "string") return geometry;
773
+ if (node.box === void 0) return "The shape has no settled local box.";
774
+ const matrix = canvasNodeLocalMatrixOf(node);
775
+ if (matrix === null) return "The shape has an invalid affine transform.";
776
+ const scaleX = node.box.width / geometry.viewBox.width;
777
+ const scaleY = node.box.height / geometry.viewBox.height;
778
+ return {
779
+ path: geometry.path,
780
+ fillRule: geometry.fillRule,
781
+ matrix: [
782
+ matrix.a * scaleX,
783
+ matrix.b * scaleX,
784
+ matrix.c * scaleY,
785
+ matrix.d * scaleY,
786
+ matrix.e - matrix.a * scaleX * geometry.viewBox.x - matrix.c * scaleY * geometry.viewBox.y,
787
+ matrix.f - matrix.b * scaleX * geometry.viewBox.x - matrix.d * scaleY * geometry.viewBox.y
788
+ ]
789
+ };
790
+ };
791
+
792
+ //#endregion
793
+ //#region ../../packages/contract/src/canvas/canvas-diamond-gradient.lib.ts
794
+ const HALF = .5;
795
+ const QUARTER = .25;
796
+ /** Each quadrant is a linear field with slope 2*(abs(x-.5)+abs(y-.5)). */
797
+ const canvasDiamondGradientField = (paint, id = "field", bounds) => {
798
+ const coordinates = canvasGradientFieldCoordinates(paint, bounds);
799
+ const extent = Math.max(HALF, ...coordinates.map((value) => Math.abs(value - HALF))) + 1;
800
+ const low = HALF - extent, high = HALF + extent;
801
+ const quadrants = [
802
+ {
803
+ x: .75,
804
+ y: .75,
805
+ points: `.5,.5 ${String(high)},.5 ${String(high)},${String(high)} .5,${String(high)}`
806
+ },
807
+ {
808
+ x: QUARTER,
809
+ y: .75,
810
+ points: `.5,.5 .5,${String(high)} ${String(low)},${String(high)} ${String(low)},.5`
811
+ },
812
+ {
813
+ x: QUARTER,
814
+ y: QUARTER,
815
+ points: `.5,.5 ${String(low)},.5 ${String(low)},${String(low)} .5,${String(low)}`
816
+ },
817
+ {
818
+ x: .75,
819
+ y: QUARTER,
820
+ points: `.5,.5 .5,${String(low)} ${String(high)},${String(low)} ${String(high)},.5`
821
+ }
822
+ ];
823
+ const stops = paint.stops.map((stop) => `<stop offset="${String(stop.position)}" stop-color="${canvasColorCss({
824
+ ...stop.color,
825
+ alpha: 1
826
+ })}" stop-opacity="${String(stop.color.alpha * paint.opacity)}" />`).join("");
827
+ const definitions = quadrants.map((quadrant, index) => `<linearGradient id="${id}-${String(index)}" gradientUnits="userSpaceOnUse" x1=".5" y1=".5" x2="${String(quadrant.x)}" y2="${String(quadrant.y)}" color-interpolation="sRGB">${stops}</linearGradient>`).join("");
828
+ const fields = quadrants.map((quadrant, index) => `<polygon points="${quadrant.points}" fill="url(#${id}-${String(index)})" shape-rendering="crispEdges" />`).join("");
829
+ return `<defs>${definitions}</defs><g transform="matrix(${paint.transform.map(String).join(" ")})">${fields}</g>`;
830
+ };
831
+ const canvasDiamondGradientSvg = (paint) => `<svg xmlns="http://www.w3.org/2000/svg" width="100%" height="100%" viewBox="0 0 1 1" preserveAspectRatio="none">${canvasDiamondGradientField(paint)}</svg>`;
832
+
833
+ //#endregion
834
+ //#region ../../packages/contract/src/canvas/canvas-filter.lib.ts
835
+ const PERCENT$3 = 100;
836
+ /** Radius/2 preserves the existing Gaussian approximation, not native sampling parity. */
837
+ const canvasBlurStandardDeviation = (filter) => filter.parameter === "radius" ? filter.value / 2 : filter.value;
838
+ const filterCss = (filter) => {
839
+ switch (filter.kind) {
840
+ case "blur": return `blur(${String(canvasBlurStandardDeviation(filter))}px)`;
841
+ case "brightness":
842
+ case "contrast":
843
+ case "saturate": return `${filter.kind}(${String(filter.value)})`;
844
+ case "grayscale":
845
+ case "invert":
846
+ case "sepia": return `${filter.kind}(${String(filter.value * PERCENT$3)}%)`;
847
+ case "hue-rotate": return `hue-rotate(${String(filter.value)}deg)`;
848
+ }
849
+ };
850
+ const canvasFilterListCss = (filters) => filters.filter((filter) => filter.visible).map((filter) => filterCss(filter)).join(" ");
851
+
72
852
  //#endregion
73
853
  //#region ../../packages/contract/src/canvas/canvas-html-source.lib.ts
74
854
  const OMITTED_ELEMENTS = /* @__PURE__ */ new Set([
@@ -145,11 +925,11 @@ const mapCanvasNodeImageSources = (node, map) => {
145
925
  ...appearance.fills !== void 0 && { fills: appearance.fills.map((paint) => mapPaint(paint, map)) },
146
926
  ...appearance.border !== void 0 && { border: {
147
927
  ...appearance.border,
148
- paint: mapPaint(appearance.border.paint, map)
928
+ paints: appearance.border.paints.map((paint) => mapPaint(paint, map))
149
929
  } },
150
930
  ...appearance.outline !== void 0 && { outline: {
151
931
  ...appearance.outline,
152
- paint: mapPaint(appearance.outline.paint, map)
932
+ paints: appearance.outline.paints.map((paint) => mapPaint(paint, map))
153
933
  } }
154
934
  } },
155
935
  ...node.typography?.stroke !== void 0 && { typography: {
@@ -167,6 +947,89 @@ const mapCanvasNodeImageSources = (node, map) => {
167
947
  };
168
948
  };
169
949
 
950
+ //#endregion
951
+ //#region ../../packages/contract/src/canvas/canvas-linear-gradient.lib.ts
952
+ const canvasLinearGradientDefinition = (paint, id, units = "userSpaceOnUse") => {
953
+ const stops = paint.stops.map((stop) => `<stop offset="${String(stop.position)}" stop-color="${canvasColorCss({
954
+ ...stop.color,
955
+ alpha: 1
956
+ })}" stop-opacity="${String(stop.color.alpha * paint.opacity)}" />`).join("");
957
+ return `<linearGradient id="${id}" gradientUnits="${units}" x1="0" y1=".5" x2="1" y2=".5" gradientTransform="matrix(${paint.transform.map(String).join(" ")})" color-interpolation="sRGB">${stops}</linearGradient>`;
958
+ };
959
+ const canvasLinearGradientSvg = (paint) => {
960
+ return `<svg xmlns="http://www.w3.org/2000/svg" width="100%" height="100%" viewBox="0 0 1 1" preserveAspectRatio="none"><defs>${canvasLinearGradientDefinition(paint, "field")}</defs><path d="M0 0H1V1H0Z" fill="url(#field)" /></svg>`;
961
+ };
962
+
963
+ //#endregion
964
+ //#region ../../packages/contract/src/canvas/canvas-presentation-defaults.lib.ts
965
+ const emptySolidPaint = (id) => ({
966
+ id,
967
+ visible: false,
968
+ opacity: 1,
969
+ kind: "solid",
970
+ color: {
971
+ space: "srgb",
972
+ red: 0,
973
+ green: 0,
974
+ blue: 0,
975
+ alpha: 0
976
+ }
977
+ });
978
+ const emptyCanvasAppearance = () => ({
979
+ opacity: 1,
980
+ blendMode: "normal",
981
+ fills: [],
982
+ border: {
983
+ visible: false,
984
+ width: {
985
+ top: 0,
986
+ right: 0,
987
+ bottom: 0,
988
+ left: 0
989
+ },
990
+ style: "solid",
991
+ paints: [emptySolidPaint("empty-border")]
992
+ },
993
+ outline: {
994
+ visible: false,
995
+ width: 0,
996
+ offset: 0,
997
+ style: "solid",
998
+ paints: [emptySolidPaint("empty-outline")]
999
+ },
1000
+ radius: {
1001
+ topLeft: 0,
1002
+ topRight: 0,
1003
+ bottomRight: 0,
1004
+ bottomLeft: 0
1005
+ },
1006
+ shadows: [],
1007
+ filters: [],
1008
+ backdropFilters: []
1009
+ });
1010
+
1011
+ //#endregion
1012
+ //#region ../../packages/contract/src/canvas/canvas-radial-gradient.lib.ts
1013
+ const DIAMETER = 2;
1014
+ const transformFor = (paint) => paint.transform ?? [
1015
+ paint.radius.x * DIAMETER,
1016
+ 0,
1017
+ 0,
1018
+ paint.radius.y * DIAMETER,
1019
+ paint.center.x - paint.radius.x,
1020
+ paint.center.y - paint.radius.y
1021
+ ];
1022
+ const canvasRadialGradientDefinition = (paint, id, units = "userSpaceOnUse") => {
1023
+ const stops = paint.stops.map((stop) => `<stop offset="${String(stop.position)}" stop-color="${canvasColorCss({
1024
+ ...stop.color,
1025
+ alpha: 1
1026
+ })}" stop-opacity="${String(stop.color.alpha * paint.opacity)}" />`).join("");
1027
+ return `<radialGradient id="${id}" gradientUnits="${units}" cx=".5" cy=".5" r=".5" gradientTransform="matrix(${transformFor(paint).map(String).join(" ")})" color-interpolation="sRGB">${stops}</radialGradient>`;
1028
+ };
1029
+ const canvasRadialGradientSvg = (paint) => {
1030
+ return `<svg xmlns="http://www.w3.org/2000/svg" width="100%" height="100%" viewBox="0 0 1 1" preserveAspectRatio="none"><defs>${canvasRadialGradientDefinition(paint, "field")}</defs><path d="M0 0H1V1H0Z" fill="url(#field)" /></svg>`;
1031
+ };
1032
+
170
1033
  //#endregion
171
1034
  //#region src/application/auth.use-case.ts
172
1035
  const TOKEN = /^enh_[\w-]{43}$/;
@@ -545,7 +1408,7 @@ const union = (boxes) => {
545
1408
  const apply = async (remote, input) => {
546
1409
  const response = await remote.mutate(APPLY_PROCEDURE, {
547
1410
  ...input,
548
- documentFormatVersion: 11
1411
+ documentFormatVersion: 13
549
1412
  });
550
1413
  const parsed = applyCanvasOperationsOutputSchema.safeParse(response);
551
1414
  if (!parsed.success) throw new CliError("INTERNAL", "The API returned an invalid canvas apply response.", "Run `enhance doctor`; report the API and CLI versions if they differ.");
@@ -583,7 +1446,7 @@ const sceneAtVersion = async (input, canvasId, expectedVersion) => {
583
1446
  //#endregion
584
1447
  //#region src/application/canvas-structure-document.use-case.ts
585
1448
  const ROOT_CANVAS_NODE_ID = "root";
586
- const canvasChildIds = (document, parentId) => Object.entries(document.relationships).filter(([, relationship]) => relationship.parentId === parentId).toSorted(([leftId, left], [rightId, right]) => left.sortKey === right.sortKey ? leftId.localeCompare(rightId) : left.sortKey.localeCompare(right.sortKey)).map(([nodeId]) => nodeId);
1449
+ const canvasChildIds = (document, parentId) => Object.entries(document.relationships).filter(([, relationship]) => relationship.parentId === parentId).toSorted(([leftId, left], [rightId, right]) => left.sortKey === right.sortKey ? leftId.localeCompare(rightId) : compareCanvasSortKeys(left.sortKey, right.sortKey)).map(([nodeId]) => nodeId);
587
1450
  const canvasChildrenByParent = (document) => {
588
1451
  const children = /* @__PURE__ */ new Map();
589
1452
  for (const [id, relationship] of Object.entries(document.relationships)) {
@@ -803,46 +1666,2305 @@ const applyMove = (input, destination, state) => {
803
1666
  parentId: destination.parentId,
804
1667
  sortKey
805
1668
  };
806
- relationships[input.nodeId] = parentage;
807
- operations.push({
808
- op: "setParentage",
809
- nodeId: input.nodeId,
810
- parentage
811
- });
1669
+ relationships[input.nodeId] = parentage;
1670
+ operations.push({
1671
+ op: "setParentage",
1672
+ nodeId: input.nodeId,
1673
+ parentage
1674
+ });
1675
+ }
1676
+ children.splice(destination.index, 0, input.nodeId);
1677
+ state.children.set(destination.parentId, children);
1678
+ state.parentOf.set(input.nodeId, destination.parentId);
1679
+ state.affected.add(destination.parentId);
1680
+ return {
1681
+ operations,
1682
+ document: {
1683
+ ...state.document,
1684
+ relationships
1685
+ }
1686
+ };
1687
+ };
1688
+ const moveCanvasNodeOperations = (document, inputs) => {
1689
+ if (inputs.length === 0) throw new CliError("BAD_REQUEST", "No moves were provided.", "Pass at least one move operation.");
1690
+ const state = moveState(document);
1691
+ const moves = [];
1692
+ return {
1693
+ operations: inputs.flatMap((input) => {
1694
+ const destination = destinationFor(input, state);
1695
+ validateMove(input, destination, state);
1696
+ moves.push({
1697
+ nodeId: input.nodeId,
1698
+ ...destination
1699
+ });
1700
+ const applied = applyMove(input, destination, state);
1701
+ state.document = applied.document;
1702
+ return applied.operations;
1703
+ }),
1704
+ moves,
1705
+ affectedParents: Array.from(state.affected, (parentId) => ({
1706
+ parentId,
1707
+ children: [...state.children.get(parentId) ?? []]
1708
+ }))
1709
+ };
1710
+ };
1711
+
1712
+ //#endregion
1713
+ //#region ../../packages/canvas-document/src/canvas-color.lib.ts
1714
+ const HEX_RADIX = 16;
1715
+ const BYTE_MAX = 255;
1716
+ const PERCENT$2 = 100;
1717
+ const SHORT_HEX_LENGTH = 3;
1718
+ const SHORT_HEX_ALPHA_LENGTH = 4;
1719
+ const LONG_HEX_LENGTH = 6;
1720
+ const LONG_HEX_ALPHA_LENGTH = 8;
1721
+ const HEX_BYTE_LENGTH = 2;
1722
+ const BLUE_HEX_OFFSET = 4;
1723
+ const ratio = (value) => Math.min(1, Math.max(0, value));
1724
+ const byteRatio = (value) => ratio(Number(value) / BYTE_MAX);
1725
+ const hexColor = (value) => {
1726
+ const hex = value.slice(1);
1727
+ if (![
1728
+ SHORT_HEX_LENGTH,
1729
+ SHORT_HEX_ALPHA_LENGTH,
1730
+ LONG_HEX_LENGTH,
1731
+ LONG_HEX_ALPHA_LENGTH
1732
+ ].includes(hex.length) || !/^[\da-f]+$/iu.test(hex)) return null;
1733
+ const expanded = hex.length <= SHORT_HEX_ALPHA_LENGTH ? hex.replaceAll(/([\da-f])/giu, "$1$1") : hex;
1734
+ const channel = (offset) => Number.parseInt(expanded.slice(offset, offset + HEX_BYTE_LENGTH), HEX_RADIX) / BYTE_MAX;
1735
+ return {
1736
+ space: "srgb",
1737
+ red: channel(0),
1738
+ green: channel(2),
1739
+ blue: channel(BLUE_HEX_OFFSET),
1740
+ alpha: expanded.length === LONG_HEX_ALPHA_LENGTH ? channel(LONG_HEX_LENGTH) : 1
1741
+ };
1742
+ };
1743
+ const functionalColor = (value) => {
1744
+ const match = /^rgba?\(\s*([\d.]+)(%?)(?:\s*,\s*|\s+)([\d.]+)(%?)(?:\s*,\s*|\s+)([\d.]+)(%?)(?:\s*[,/]\s*([\d.]+)(%?))?\s*\)$/iu.exec(value);
1745
+ if (match === null) return null;
1746
+ const channel = (held, unit) => unit === "%" ? ratio(Number(held) / PERCENT$2) : byteRatio(held ?? "0");
1747
+ const alpha = match[7] === void 0 ? 1 : ratio(Number(match[7]) / (match[8] === "%" ? PERCENT$2 : 1));
1748
+ return {
1749
+ space: "srgb",
1750
+ red: channel(match[1], match[2]),
1751
+ green: channel(match[3], match[4]),
1752
+ blue: channel(match[5], match[6]),
1753
+ alpha
1754
+ };
1755
+ };
1756
+ const colorFunction = (value) => {
1757
+ const match = /^color\(\s*(srgb|display-p3)\s+([\d.]+)\s+([\d.]+)\s+([\d.]+)(?:\s*\/\s*([\d.]+))?\s*\)$/iu.exec(value);
1758
+ if (match === null) return null;
1759
+ return {
1760
+ space: match[1] === "display-p3" ? "display-p3" : "srgb",
1761
+ red: ratio(Number(match[2])),
1762
+ green: ratio(Number(match[3])),
1763
+ blue: ratio(Number(match[4])),
1764
+ alpha: ratio(match[5] === void 0 ? 1 : Number(match[5]))
1765
+ };
1766
+ };
1767
+ const canvasColorFromCss = (value) => {
1768
+ const normalized = value.trim().toLowerCase();
1769
+ if (normalized === "transparent") return {
1770
+ space: "srgb",
1771
+ red: 0,
1772
+ green: 0,
1773
+ blue: 0,
1774
+ alpha: 0
1775
+ };
1776
+ if (normalized.startsWith("#")) return hexColor(normalized);
1777
+ if (normalized.startsWith("rgb")) return functionalColor(normalized);
1778
+ if (normalized.startsWith("color(")) return colorFunction(normalized);
1779
+ return null;
1780
+ };
1781
+ const solidCanvasPaint = (id, color) => ({
1782
+ id,
1783
+ visible: true,
1784
+ opacity: 1,
1785
+ kind: "solid",
1786
+ color
1787
+ });
1788
+ const solidCanvasPaintFromCss = (id, value) => {
1789
+ const color = canvasColorFromCss(value);
1790
+ return color === null ? null : solidCanvasPaint(id, color);
1791
+ };
1792
+
1793
+ //#endregion
1794
+ //#region ../../node_modules/.pnpm/@noble+hashes@2.3.0/node_modules/@noble/hashes/_u64.js
1795
+ const fromNumH = (n) => n / 2 ** 32 | 0;
1796
+ const fromNumL = (n) => n >>> 0;
1797
+ function setU64FromNum(view, byteOffset, n, isLE) {
1798
+ const h = fromNumH(n);
1799
+ const l = fromNumL(n);
1800
+ view.setUint32(byteOffset, isLE ? l : h, isLE);
1801
+ view.setUint32(byteOffset + 4, isLE ? h : l, isLE);
1802
+ }
1803
+
1804
+ //#endregion
1805
+ //#region ../../node_modules/.pnpm/@noble+hashes@2.3.0/node_modules/@noble/hashes/utils.js
1806
+ /**
1807
+ * Checks if something is Uint8Array. Be careful: nodejs Buffer will return true.
1808
+ * @param a - value to test
1809
+ * @returns `true` when the value is a Uint8Array-compatible view.
1810
+ * @example
1811
+ * Check whether a value is a Uint8Array-compatible view.
1812
+ * ```ts
1813
+ * isBytes(new Uint8Array([1, 2, 3]));
1814
+ * ```
1815
+ */
1816
+ function isBytes(a) {
1817
+ return a instanceof Uint8Array || ArrayBuffer.isView(a) && a.constructor.name === "Uint8Array" && "BYTES_PER_ELEMENT" in a && a.BYTES_PER_ELEMENT === 1;
1818
+ }
1819
+ const atitle = (title) => title ? `"${title}" ` : "";
1820
+ /**
1821
+ * Asserts something is a non-negative integer.
1822
+ * @param n - number to validate
1823
+ * @param title - label included in thrown errors
1824
+ * @returns The validated number.
1825
+ * @throws On wrong argument types. {@link TypeError}
1826
+ * @throws On wrong argument ranges or values. {@link RangeError}
1827
+ * @example
1828
+ * Validate a non-negative integer option.
1829
+ * ```ts
1830
+ * anumber(32, 'length');
1831
+ * ```
1832
+ */
1833
+ function anumber(n, title = "") {
1834
+ if (typeof n !== "number") throw new TypeError(atitle(title) + "expected number, got " + typeof n);
1835
+ if (!Number.isSafeInteger(n) || n < 0) throw new RangeError(atitle(title) + "expected integer >= 0, got " + n);
1836
+ return n;
1837
+ }
1838
+ /**
1839
+ * Asserts something is Uint8Array.
1840
+ * @param value - value to validate
1841
+ * @param length - optional exact length constraint
1842
+ * @param title - label included in thrown errors
1843
+ * @returns The validated byte array.
1844
+ * @throws On wrong argument types. {@link TypeError}
1845
+ * @throws On wrong argument ranges or values. {@link RangeError}
1846
+ * @example
1847
+ * Validate that a value is a byte array.
1848
+ * ```ts
1849
+ * abytes(new Uint8Array([1, 2, 3]));
1850
+ * ```
1851
+ */
1852
+ function abytes(value, length, title = "") {
1853
+ if (isBytes(value) && (length === void 0 || value.length === length)) return value;
1854
+ if (length !== void 0) anumber(length, "length");
1855
+ const bytes = isBytes(value);
1856
+ const ofLen = length !== void 0 ? ` of length ${length}` : "";
1857
+ const got = bytes ? `length=${value.length}` : `type=${typeof value}`;
1858
+ const message = atitle(title) + "expected Uint8Array" + ofLen + ", got " + got;
1859
+ if (!bytes) throw new TypeError(message);
1860
+ throw new RangeError(message);
1861
+ }
1862
+ const aobject = (value, label) => {
1863
+ if (value === null || typeof value !== "object" || Array.isArray(value)) throw new TypeError((label === "object" ? "" : `"${label}" `) + "expected object, got type=" + typeof value);
1864
+ };
1865
+ /**
1866
+ * Asserts a hash instance has not been destroyed or finished.
1867
+ * @param instance - hash instance to validate
1868
+ * @param checkFinished - whether to reject finalized instances
1869
+ * @throws If the hash instance has already been destroyed or finalized. {@link Error}
1870
+ * @example
1871
+ * Validate that a hash instance is still usable.
1872
+ * ```ts
1873
+ * import { aexists } from '@noble/hashes/utils.js';
1874
+ * import { sha256 } from '@noble/hashes/sha2.js';
1875
+ * const hash = sha256.create();
1876
+ * aexists(hash);
1877
+ * ```
1878
+ */
1879
+ function aexists(instance, checkFinished = true) {
1880
+ if (instance.destroyed) throw new Error("hash was destroyed");
1881
+ if (checkFinished && instance.finished) throw new Error("digest() was already called");
1882
+ }
1883
+ /**
1884
+ * Asserts output is a sufficiently-sized byte array.
1885
+ * @param out - destination buffer
1886
+ * @param instance - hash instance providing output length
1887
+ * Oversized buffers are allowed; downstream code only promises to fill the first `outputLen` bytes.
1888
+ * @throws On wrong argument types. {@link TypeError}
1889
+ * @throws On wrong argument ranges or values. {@link RangeError}
1890
+ * @example
1891
+ * Validate a caller-provided digest buffer.
1892
+ * ```ts
1893
+ * import { aoutput } from '@noble/hashes/utils.js';
1894
+ * import { sha256 } from '@noble/hashes/sha2.js';
1895
+ * const hash = sha256.create();
1896
+ * aoutput(new Uint8Array(hash.outputLen), hash);
1897
+ * ```
1898
+ */
1899
+ function aoutput(out, instance) {
1900
+ abytes(out, void 0, "output");
1901
+ const min = instance.outputLen;
1902
+ if (!(out.length >= min)) throw new RangeError("\"output\" expected length >= " + min);
1903
+ }
1904
+ /**
1905
+ * Zeroizes typed arrays in place. Warning: JS provides no guarantees.
1906
+ * @param arrays - arrays to overwrite with zeros
1907
+ * @example
1908
+ * Zeroize sensitive buffers in place.
1909
+ * ```ts
1910
+ * clean(new Uint8Array([1, 2, 3]));
1911
+ * ```
1912
+ */
1913
+ function clean(...arrays) {
1914
+ for (let i = 0; i < arrays.length; i++) arrays[i].fill(0);
1915
+ }
1916
+ /**
1917
+ * Creates a DataView for byte-level manipulation.
1918
+ * @param arr - source typed array
1919
+ * @returns DataView over the same buffer region.
1920
+ * @example
1921
+ * Create a DataView over an existing buffer.
1922
+ * ```ts
1923
+ * createView(new Uint8Array(4));
1924
+ * ```
1925
+ */
1926
+ function createView(arr) {
1927
+ return new DataView(arr.buffer, arr.byteOffset, arr.byteLength);
1928
+ }
1929
+ /**
1930
+ * Rotate-right operation for uint32 values.
1931
+ * @param word - source word
1932
+ * @param shift - shift amount in bits
1933
+ * @returns Rotated word.
1934
+ * @example
1935
+ * Rotate a 32-bit word to the right.
1936
+ * ```ts
1937
+ * rotr(0x12345678, 8);
1938
+ * ```
1939
+ */
1940
+ function rotr(word, shift) {
1941
+ return word << 32 - shift | word >>> shift;
1942
+ }
1943
+ const hasHexBuiltin = /* @__PURE__ */ (() => typeof Uint8Array.from([]).toHex === "function" && typeof Uint8Array.fromHex === "function")();
1944
+ const hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, "0"));
1945
+ /**
1946
+ * Convert byte array to hex string.
1947
+ * Uses the built-in function when available and assumes it matches the tested
1948
+ * fallback semantics.
1949
+ * @param bytes - bytes to encode
1950
+ * @returns Lowercase hexadecimal string.
1951
+ * @throws On wrong argument types. {@link TypeError}
1952
+ * @example
1953
+ * Convert bytes to lowercase hexadecimal.
1954
+ * ```ts
1955
+ * bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])); // 'cafe0123'
1956
+ * ```
1957
+ */
1958
+ function bytesToHex(bytes) {
1959
+ abytes(bytes);
1960
+ if (hasHexBuiltin) return bytes.toHex();
1961
+ let hex = "";
1962
+ for (let i = 0; i < bytes.length; i++) hex += hexes[bytes[i]];
1963
+ return hex;
1964
+ }
1965
+ /**
1966
+ * Converts string to bytes using UTF8 encoding.
1967
+ * Built-in doesn't validate input to be string: we do the check.
1968
+ * Non-ASCII details are delegated to the platform `TextEncoder`.
1969
+ * @param str - string to encode
1970
+ * @returns UTF-8 encoded bytes.
1971
+ * @throws On wrong argument types. {@link TypeError}
1972
+ * @example
1973
+ * Encode a string as UTF-8 bytes.
1974
+ * ```ts
1975
+ * utf8ToBytes('abc'); // Uint8Array.from([97, 98, 99])
1976
+ * ```
1977
+ */
1978
+ function utf8ToBytes(str) {
1979
+ if (typeof str !== "string") throw new TypeError("string expected");
1980
+ return new Uint8Array(new TextEncoder().encode(str));
1981
+ }
1982
+ /**
1983
+ * Merges default options and passed options.
1984
+ * @param defaults - base option object
1985
+ * @param opts - user overrides
1986
+ * @param title - label included in thrown override errors
1987
+ * @returns Merged option object. The merge mutates `defaults` in place.
1988
+ * @throws On wrong argument types. {@link TypeError}
1989
+ * @example
1990
+ * Merge user overrides onto default options.
1991
+ * ```ts
1992
+ * checkOpts({ dkLen: 32 }, { asyncTick: 10 });
1993
+ * ```
1994
+ */
1995
+ function checkOpts(defaults, opts, title = "opts") {
1996
+ aobject(defaults, "defaults");
1997
+ if (opts !== void 0) aobject(opts, title);
1998
+ return Object.assign(defaults, opts);
1999
+ }
2000
+ /**
2001
+ * Creates a callable hash function from a stateful class constructor.
2002
+ * @param hashCons - hash constructor or factory
2003
+ * @param info - optional metadata such as DER OID
2004
+ * @returns Frozen callable hash wrapper with `.create()`.
2005
+ * Wrapper construction eagerly calls `hashCons(undefined)` once to read
2006
+ * `outputLen` / `blockLen`, so constructor side effects happen at module
2007
+ * init time.
2008
+ * @throws On wrong argument types. {@link TypeError}
2009
+ * @example
2010
+ * Wrap a stateful hash constructor into a callable helper.
2011
+ * ```ts
2012
+ * import { createHasher } from '@noble/hashes/utils.js';
2013
+ * import { sha256 } from '@noble/hashes/sha2.js';
2014
+ * const wrapped = createHasher(sha256.create, { oid: sha256.oid });
2015
+ * wrapped(new Uint8Array([1]));
2016
+ * ```
2017
+ */
2018
+ function createHasher(hashCons, info = {}) {
2019
+ if (typeof hashCons !== "function") throw new TypeError("\"hashCons\" expected function, got type=" + typeof hashCons);
2020
+ info = checkOpts({}, info, "info");
2021
+ const hashC = (msg, opts) => hashCons(opts).update(msg).digest();
2022
+ const tmp = hashCons(void 0);
2023
+ hashC.outputLen = tmp.outputLen;
2024
+ hashC.blockLen = tmp.blockLen;
2025
+ hashC.canXOF = tmp.canXOF;
2026
+ hashC.create = (opts) => hashCons(opts);
2027
+ Object.assign(hashC, info);
2028
+ return Object.freeze(hashC);
2029
+ }
2030
+ /**
2031
+ * Creates OID metadata for NIST hashes with prefix `06 09 60 86 48 01 65 03 04 02`.
2032
+ * @param suffix - final OID byte for the selected hash.
2033
+ * The helper accepts any byte even though only the documented NIST hash
2034
+ * suffixes are meaningful downstream.
2035
+ * @returns Object containing the DER-encoded OID.
2036
+ * @example
2037
+ * Build OID metadata for a NIST hash.
2038
+ * ```ts
2039
+ * oidNist(0x01);
2040
+ * ```
2041
+ */
2042
+ const oidNist = (suffix) => ({ oid: Uint8Array.from([
2043
+ 6,
2044
+ 9,
2045
+ 96,
2046
+ 134,
2047
+ 72,
2048
+ 1,
2049
+ 101,
2050
+ 3,
2051
+ 4,
2052
+ 2,
2053
+ suffix
2054
+ ]) });
2055
+
2056
+ //#endregion
2057
+ //#region ../../node_modules/.pnpm/@noble+hashes@2.3.0/node_modules/@noble/hashes/_md.js
2058
+ /**
2059
+ * Internal Merkle-Damgard hash utils.
2060
+ * @module
2061
+ */
2062
+ /**
2063
+ * Shared 32-bit conditional boolean primitive reused by SHA-256, SHA-1, and MD5 `F`.
2064
+ * Returns bits from `b` when `a` is set, otherwise from `c`.
2065
+ * The XOR form is equivalent to MD5's `F(X,Y,Z) = XY v not(X)Z` because the masked terms never
2066
+ * set the same bit.
2067
+ * @param a - selector word
2068
+ * @param b - word chosen when selector bit is set
2069
+ * @param c - word chosen when selector bit is clear
2070
+ * @returns Mixed 32-bit word.
2071
+ * @example
2072
+ * Combine three words with the shared 32-bit choice primitive.
2073
+ * ```ts
2074
+ * Chi(0xffffffff, 0x12345678, 0x87654321);
2075
+ * ```
2076
+ */
2077
+ function Chi(a, b, c) {
2078
+ return a & b ^ ~a & c;
2079
+ }
2080
+ /**
2081
+ * Shared 32-bit majority primitive reused by SHA-256 and SHA-1.
2082
+ * Returns bits shared by at least two inputs.
2083
+ * @param a - first input word
2084
+ * @param b - second input word
2085
+ * @param c - third input word
2086
+ * @returns Mixed 32-bit word.
2087
+ * @example
2088
+ * Combine three words with the shared 32-bit majority primitive.
2089
+ * ```ts
2090
+ * Maj(0xffffffff, 0x12345678, 0x87654321);
2091
+ * ```
2092
+ */
2093
+ function Maj(a, b, c) {
2094
+ return a & b ^ a & c ^ b & c;
2095
+ }
2096
+ /**
2097
+ * Merkle-Damgard hash construction base class.
2098
+ * Could be used to create MD5, RIPEMD, SHA1, SHA2.
2099
+ * Accepts only byte-aligned `Uint8Array` input, even when the underlying spec describes bit
2100
+ * strings with partial-byte tails.
2101
+ * @param blockLen - internal block size in bytes
2102
+ * @param outputLen - digest size in bytes
2103
+ * @param padOffset - trailing length field size in bytes
2104
+ * @param isLE - whether length and state words are encoded in little-endian
2105
+ * @example
2106
+ * Use a concrete subclass to get the shared Merkle-Damgard update/digest flow.
2107
+ * ```ts
2108
+ * import { _SHA1 } from '@noble/hashes/legacy.js';
2109
+ * const hash = new _SHA1();
2110
+ * hash.update(new Uint8Array([97, 98, 99]));
2111
+ * hash.digest();
2112
+ * ```
2113
+ */
2114
+ var HashMD = class {
2115
+ blockLen;
2116
+ outputLen;
2117
+ canXOF = false;
2118
+ padOffset;
2119
+ isLE;
2120
+ buffer;
2121
+ view;
2122
+ finished = false;
2123
+ length = 0;
2124
+ pos = 0;
2125
+ destroyed = false;
2126
+ constructor(blockLen, outputLen, padOffset, isLE) {
2127
+ this.blockLen = blockLen;
2128
+ this.outputLen = outputLen;
2129
+ this.padOffset = padOffset;
2130
+ this.isLE = isLE;
2131
+ this.buffer = new Uint8Array(blockLen);
2132
+ this.view = createView(this.buffer);
2133
+ }
2134
+ update(data) {
2135
+ aexists(this);
2136
+ abytes(data);
2137
+ const { view, buffer, blockLen } = this;
2138
+ const len = data.length;
2139
+ let processed = false;
2140
+ for (let pos = 0; pos < len;) {
2141
+ const take = Math.min(blockLen - this.pos, len - pos);
2142
+ if (take === blockLen) {
2143
+ const dataView = createView(data);
2144
+ for (; blockLen <= len - pos; pos += blockLen) this.process(dataView, pos);
2145
+ processed = true;
2146
+ continue;
2147
+ }
2148
+ buffer.set(pos === 0 && take === len ? data : data.subarray(pos, pos + take), this.pos);
2149
+ this.pos += take;
2150
+ pos += take;
2151
+ if (this.pos === blockLen) {
2152
+ this.process(view, 0);
2153
+ this.pos = 0;
2154
+ processed = true;
2155
+ }
2156
+ }
2157
+ this.length += data.length;
2158
+ if (processed) this.roundClean();
2159
+ return this;
2160
+ }
2161
+ digestInto(out) {
2162
+ aexists(this);
2163
+ aoutput(out, this);
2164
+ this.finished = true;
2165
+ const { buffer, view, blockLen, isLE } = this;
2166
+ let { pos } = this;
2167
+ buffer[pos++] = 128;
2168
+ buffer.fill(0, pos);
2169
+ if (this.padOffset > blockLen - pos) {
2170
+ this.process(view, 0);
2171
+ buffer.fill(0);
2172
+ }
2173
+ setU64FromNum(view, blockLen - 8, this.length * 8, isLE);
2174
+ this.process(view, 0);
2175
+ this.roundClean();
2176
+ const oview = out === buffer ? view : createView(out);
2177
+ const len = this.outputLen;
2178
+ const outLen = len / 4;
2179
+ const state = this.get();
2180
+ if (len % 4 || outLen > state.length) throw new Error("invalid outputLen");
2181
+ for (let i = 0; i < outLen; i++) oview.setUint32(4 * i, state[i], isLE);
2182
+ }
2183
+ digest() {
2184
+ const { buffer, outputLen } = this;
2185
+ this.digestInto(buffer);
2186
+ const res = buffer.slice(0, outputLen);
2187
+ this.destroy();
2188
+ return res;
2189
+ }
2190
+ _cloneIntoMeta(to) {
2191
+ const { buffer, length, finished, destroyed, pos } = this;
2192
+ to.destroyed = destroyed;
2193
+ to.finished = finished;
2194
+ to.length = length;
2195
+ to.pos = pos;
2196
+ if (pos) to.buffer.set(buffer);
2197
+ return to;
2198
+ }
2199
+ clone() {
2200
+ return this._cloneInto();
2201
+ }
2202
+ };
2203
+ /**
2204
+ * Initial SHA-2 state: fractional parts of square roots of first 16 primes 2..53.
2205
+ * Check out `test/misc/sha2-gen-iv.js` for recomputation guide.
2206
+ */
2207
+ /** Initial SHA256 state from RFC 6234 §6.1: the first 32 bits of the fractional parts of the
2208
+ * square roots of the first eight prime numbers. Exported as a shared table; callers must treat
2209
+ * it as read-only because constructors copy words from it by index. */
2210
+ const SHA256_IV = /* @__PURE__ */ Uint32Array.from([
2211
+ 1779033703,
2212
+ 3144134277,
2213
+ 1013904242,
2214
+ 2773480762,
2215
+ 1359893119,
2216
+ 2600822924,
2217
+ 528734635,
2218
+ 1541459225
2219
+ ]);
2220
+
2221
+ //#endregion
2222
+ //#region ../../node_modules/.pnpm/@noble+hashes@2.3.0/node_modules/@noble/hashes/sha2.js
2223
+ /**
2224
+ * SHA2 hash function. A.k.a. sha256, sha384, sha512, sha512_224, sha512_256.
2225
+ * SHA256 is the fastest hash implementable in JS, even faster than Blake3.
2226
+ * Check out {@link https://www.rfc-editor.org/rfc/rfc4634 | RFC 4634} and
2227
+ * {@link https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf | FIPS 180-4}.
2228
+ * @module
2229
+ */
2230
+ /**
2231
+ * SHA-224 / SHA-256 round constants from RFC 6234 §5.1: the first 32 bits
2232
+ * of the cube roots of the first 64 primes (2..311).
2233
+ */
2234
+ const SHA256_K = /* @__PURE__ */ Uint32Array.from([
2235
+ 1116352408,
2236
+ 1899447441,
2237
+ 3049323471,
2238
+ 3921009573,
2239
+ 961987163,
2240
+ 1508970993,
2241
+ 2453635748,
2242
+ 2870763221,
2243
+ 3624381080,
2244
+ 310598401,
2245
+ 607225278,
2246
+ 1426881987,
2247
+ 1925078388,
2248
+ 2162078206,
2249
+ 2614888103,
2250
+ 3248222580,
2251
+ 3835390401,
2252
+ 4022224774,
2253
+ 264347078,
2254
+ 604807628,
2255
+ 770255983,
2256
+ 1249150122,
2257
+ 1555081692,
2258
+ 1996064986,
2259
+ 2554220882,
2260
+ 2821834349,
2261
+ 2952996808,
2262
+ 3210313671,
2263
+ 3336571891,
2264
+ 3584528711,
2265
+ 113926993,
2266
+ 338241895,
2267
+ 666307205,
2268
+ 773529912,
2269
+ 1294757372,
2270
+ 1396182291,
2271
+ 1695183700,
2272
+ 1986661051,
2273
+ 2177026350,
2274
+ 2456956037,
2275
+ 2730485921,
2276
+ 2820302411,
2277
+ 3259730800,
2278
+ 3345764771,
2279
+ 3516065817,
2280
+ 3600352804,
2281
+ 4094571909,
2282
+ 275423344,
2283
+ 430227734,
2284
+ 506948616,
2285
+ 659060556,
2286
+ 883997877,
2287
+ 958139571,
2288
+ 1322822218,
2289
+ 1537002063,
2290
+ 1747873779,
2291
+ 1955562222,
2292
+ 2024104815,
2293
+ 2227730452,
2294
+ 2361852424,
2295
+ 2428436474,
2296
+ 2756734187,
2297
+ 3204031479,
2298
+ 3329325298
2299
+ ]);
2300
+ /** Reusable SHA-224 / SHA-256 message schedule buffer `W_t` from RFC 6234 §6.2 step 1. */
2301
+ const SHA256_W = /* @__PURE__ */ new Uint32Array(64);
2302
+ /** Internal SHA-224 / SHA-256 compression engine from RFC 6234 §6.2. */
2303
+ var SHA2_32B = class extends HashMD {
2304
+ A = 0;
2305
+ B = 0;
2306
+ C = 0;
2307
+ D = 0;
2308
+ E = 0;
2309
+ F = 0;
2310
+ G = 0;
2311
+ H = 0;
2312
+ constructor(outputLen, IV) {
2313
+ super(64, outputLen, 8, false);
2314
+ this.A = IV[0] | 0;
2315
+ this.B = IV[1] | 0;
2316
+ this.C = IV[2] | 0;
2317
+ this.D = IV[3] | 0;
2318
+ this.E = IV[4] | 0;
2319
+ this.F = IV[5] | 0;
2320
+ this.G = IV[6] | 0;
2321
+ this.H = IV[7] | 0;
2322
+ }
2323
+ get() {
2324
+ const { A, B, C, D, E, F, G, H } = this;
2325
+ return [
2326
+ A,
2327
+ B,
2328
+ C,
2329
+ D,
2330
+ E,
2331
+ F,
2332
+ G,
2333
+ H
2334
+ ];
2335
+ }
2336
+ set(A, B, C, D, E, F, G, H) {
2337
+ this.A = A | 0;
2338
+ this.B = B | 0;
2339
+ this.C = C | 0;
2340
+ this.D = D | 0;
2341
+ this.E = E | 0;
2342
+ this.F = F | 0;
2343
+ this.G = G | 0;
2344
+ this.H = H | 0;
2345
+ }
2346
+ _cloneInto(to) {
2347
+ (to ||= new this.constructor()).set(...this.get());
2348
+ return this._cloneIntoMeta(to);
2349
+ }
2350
+ process(view, offset) {
2351
+ for (let i = 0; i < 16; i++, offset += 4) SHA256_W[i] = view.getUint32(offset, false);
2352
+ for (let i = 16; i < 64; i++) {
2353
+ const W15 = SHA256_W[i - 15];
2354
+ const W2 = SHA256_W[i - 2];
2355
+ const s0 = rotr(W15, 7) ^ rotr(W15, 18) ^ W15 >>> 3;
2356
+ const s1 = rotr(W2, 17) ^ rotr(W2, 19) ^ W2 >>> 10;
2357
+ SHA256_W[i] = s1 + SHA256_W[i - 7] + s0 + SHA256_W[i - 16] | 0;
2358
+ }
2359
+ let { A, B, C, D, E, F, G, H } = this;
2360
+ for (let i = 0; i < 64; i++) {
2361
+ const sigma1 = rotr(E, 6) ^ rotr(E, 11) ^ rotr(E, 25);
2362
+ const T1 = H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i] | 0;
2363
+ const T2 = (rotr(A, 2) ^ rotr(A, 13) ^ rotr(A, 22)) + Maj(A, B, C) | 0;
2364
+ H = G;
2365
+ G = F;
2366
+ F = E;
2367
+ E = D + T1 | 0;
2368
+ D = C;
2369
+ C = B;
2370
+ B = A;
2371
+ A = T1 + T2 | 0;
2372
+ }
2373
+ A = A + this.A | 0;
2374
+ B = B + this.B | 0;
2375
+ C = C + this.C | 0;
2376
+ D = D + this.D | 0;
2377
+ E = E + this.E | 0;
2378
+ F = F + this.F | 0;
2379
+ G = G + this.G | 0;
2380
+ H = H + this.H | 0;
2381
+ this.set(A, B, C, D, E, F, G, H);
2382
+ }
2383
+ roundClean() {
2384
+ clean(SHA256_W);
2385
+ }
2386
+ destroy() {
2387
+ this.destroyed = true;
2388
+ this.set(0, 0, 0, 0, 0, 0, 0, 0);
2389
+ clean(this.buffer);
2390
+ }
2391
+ };
2392
+ /** Internal SHA-256 hash class grounded in RFC 6234 §6.2. */
2393
+ var _SHA256 = class extends SHA2_32B {
2394
+ constructor() {
2395
+ super(32, SHA256_IV);
2396
+ }
2397
+ };
2398
+ /**
2399
+ * SHA2-256 hash function from RFC 4634. In JS it's the fastest: even faster than Blake3. Some info:
2400
+ *
2401
+ * - Trying 2^128 hashes would get 50% chance of collision, using birthday attack.
2402
+ * - BTC network is doing 2^70 hashes/sec (2^95 hashes/year) as per 2025.
2403
+ * - Each sha256 hash is executing 2^18 bit operations.
2404
+ * - Good 2024 ASICs can do 200Th/sec with 3500 watts of power, corresponding to 2^36 hashes/joule.
2405
+ * @param msg - message bytes to hash
2406
+ * @param opts - Reserved hash options.
2407
+ * @returns Digest bytes.
2408
+ * @example
2409
+ * Hash a message with SHA2-256.
2410
+ * ```ts
2411
+ * sha256(new Uint8Array([97, 98, 99]));
2412
+ * ```
2413
+ */
2414
+ const sha256 = /* @__PURE__ */ createHasher(() => new _SHA256(), /* @__PURE__ */ oidNist(1));
2415
+
2416
+ //#endregion
2417
+ //#region ../../packages/canvas-document/src/node-relationships.lib.ts
2418
+ const inSortOrder = (left, right) => left.sortKey === right.sortKey ? left.childId.localeCompare(right.childId) : left.sortKey < right.sortKey ? -1 : 1;
2419
+ const indexChildren = (relationships) => {
2420
+ const seats = /* @__PURE__ */ new Map();
2421
+ for (const [childId, parentage] of Object.entries(relationships)) {
2422
+ const seated = {
2423
+ childId,
2424
+ sortKey: parentage.sortKey
2425
+ };
2426
+ const held = seats.get(parentage.parentId);
2427
+ if (held === void 0) seats.set(parentage.parentId, [seated]);
2428
+ else held.push(seated);
2429
+ }
2430
+ const byParent = /* @__PURE__ */ new Map();
2431
+ for (const [parentId, children] of seats) byParent.set(parentId, children.toSorted(inSortOrder).map((seated) => seated.childId));
2432
+ return byParent;
2433
+ };
2434
+ const heldIndexes = /* @__PURE__ */ new WeakMap();
2435
+ /**
2436
+ * @justified warning
2437
+ * Every parent's children, built once for a whole document.
2438
+ *
2439
+ * `childIdsOf` used to be a scan over every relationship to find one node's children, and
2440
+ * `CanvasNode` calls it while recursing from the root — so one render of a board of N did N
2441
+ * scans of N, a million entry tuples per frame of a pan at a thousand nodes. This is the same
2442
+ * answer in one pass, built per document and handed down.
2443
+ */
2444
+ const childIndexOf = (relationships) => {
2445
+ const held = heldIndexes.get(relationships);
2446
+ if (held !== void 0) return held;
2447
+ const index = indexChildren(relationships);
2448
+ if (Object.isFrozen(relationships)) heldIndexes.set(relationships, index);
2449
+ return index;
2450
+ };
2451
+ /** No children, shared: a leaf is the common case and each one would otherwise allocate. */
2452
+ const NO_CHILDREN = [];
2453
+ const childIdsIn = (index, parentId) => index.get(parentId) ?? NO_CHILDREN;
2454
+ /**
2455
+ * A parent's children when there is no index to hand. A held (frozen) document shares one index;
2456
+ * a document still being built gets a fresh one per call, so loops over one should build it once.
2457
+ */
2458
+ const childIdsOf = (relationships, parentId) => childIdsIn(childIndexOf(relationships), parentId);
2459
+
2460
+ //#endregion
2461
+ //#region ../../packages/canvas-document/src/canvas-image-resource.lib.ts
2462
+ const RESOURCE_PREFIX = "enhance-pending-image:";
2463
+ const isEmptyCanvasImageSource = (source) => source.trim() === "" || source.trim() === "about:blank";
2464
+ const isPendingCanvasImageSource = (source) => typeof source === "string" && source.startsWith(RESOURCE_PREFIX);
2465
+
2466
+ //#endregion
2467
+ //#region ../../packages/canvas-document/src/canvas-paint-projection.lib.ts
2468
+ const requiresCanvasImagePaintResource = (paint) => isPendingCanvasImageSource(paint.assetId) || paint.opacity !== 1 || paint.fit === "crop" && paint.transform !== void 0 || (paint.rotation ?? 0) !== 0 || paint.fit === "tile" && (paint.tileScale ?? 1) !== 1;
2469
+ const canvasImagePaintProperty = (paint) => `--canvas-image-paint-${bytesToHex(sha256(utf8ToBytes(JSON.stringify([
2470
+ paint.assetId,
2471
+ paint.opacity,
2472
+ paint.rotation ?? 0,
2473
+ paint.fit === "tile" ? paint.tileScale ?? 1 : 1,
2474
+ paint.fit === "crop" ? paint.transform : void 0
2475
+ ]))))}`;
2476
+ const canvasTextPaintStackProperty = (paints) => `--canvas-text-paints-${bytesToHex(sha256(utf8ToBytes(JSON.stringify(paints.filter((paint) => paint.visible), (key, value) => key === "id" ? void 0 : value))))}`;
2477
+ const PERCENT$1 = 100;
2478
+ const stopCss = (stop, opacity = 1) => `${canvasColorCss(stop.color, opacity)} ${String(stop.position * PERCENT$1)}%`;
2479
+ const canvasPaintImageUrl = (source) => `url("${encodeURI(source).replaceAll("\"", "%22")}")`;
2480
+ const canvasPaintLayerCss = (paint) => {
2481
+ switch (paint.kind) {
2482
+ case "solid": {
2483
+ const color = canvasColorCss(paint.color, paint.opacity);
2484
+ return `linear-gradient(${color}, ${color})`;
2485
+ }
2486
+ case "linear-gradient":
2487
+ if (paint.transform !== void 0) return `url("data:image/svg+xml,${encodeURIComponent(canvasLinearGradientSvg({
2488
+ ...paint,
2489
+ transform: paint.transform
2490
+ }))}")`;
2491
+ return `linear-gradient(${String(paint.angle)}deg, ${paint.stops.map((stop) => stopCss(stop, paint.opacity)).join(", ")})`;
2492
+ case "radial-gradient": {
2493
+ if (paint.transform !== void 0) return `url("data:image/svg+xml,${encodeURIComponent(canvasRadialGradientSvg(paint))}")`;
2494
+ const at = `${String(paint.center.x * PERCENT$1)}% ${String(paint.center.y * PERCENT$1)}%`;
2495
+ return `radial-gradient(ellipse ${String(paint.radius.x * PERCENT$1)}% ${String(paint.radius.y * PERCENT$1)}% at ${at}, ${paint.stops.map((stop) => stopCss(stop, paint.opacity)).join(", ")})`;
2496
+ }
2497
+ case "angular-gradient": return `url("data:image/svg+xml,${encodeURIComponent(canvasAngularGradientSvg(paint))}")`;
2498
+ case "diamond-gradient": return `url("data:image/svg+xml,${encodeURIComponent(canvasDiamondGradientSvg(paint))}")`;
2499
+ case "image":
2500
+ if (isEmptyCanvasImageSource(paint.assetId)) return "none";
2501
+ return requiresCanvasImagePaintResource(paint) ? `var(${canvasImagePaintProperty(paint)}, none)` : canvasPaintImageUrl(paint.assetId);
2502
+ }
2503
+ };
2504
+ const cropAxisPosition = (start, size) => size >= 1 ? 0 : start / (1 - size) * PERCENT$1;
2505
+ const cropDeclarations = (crop) => {
2506
+ if (crop === void 0) return {
2507
+ "background-position": "center",
2508
+ "background-size": "cover"
2509
+ };
2510
+ const width = Math.max(crop.width, Number.EPSILON);
2511
+ const height = Math.max(crop.height, Number.EPSILON);
2512
+ return {
2513
+ "background-position": `${String(cropAxisPosition(crop.x, width))}% ${String(cropAxisPosition(crop.y, height))}%`,
2514
+ "background-size": `${String(PERCENT$1 / width)}% ${String(PERCENT$1 / height)}%`
2515
+ };
2516
+ };
2517
+ const paintGeometry = (paint) => {
2518
+ if (paint.kind !== "image") return {
2519
+ "background-size": paint.kind === "angular-gradient" || paint.kind === "diamond-gradient" || (paint.kind === "linear-gradient" || paint.kind === "radial-gradient") && paint.transform !== void 0 ? "100% 100%" : "auto",
2520
+ "background-position": "center",
2521
+ "background-repeat": "no-repeat",
2522
+ "background-origin": "border-box"
2523
+ };
2524
+ const size = {
2525
+ fill: "100% 100%",
2526
+ cover: "cover",
2527
+ fit: "contain",
2528
+ crop: "cover",
2529
+ tile: "auto"
2530
+ }[paint.fit];
2531
+ return {
2532
+ ...paint.fit === "crop" && paint.transform !== void 0 ? {
2533
+ "background-position": "0% 0%",
2534
+ "background-size": "100% 100%"
2535
+ } : paint.fit === "crop" ? cropDeclarations(paint.crop) : {
2536
+ "background-position": paint.fit === "tile" && paint.tileOrigin === "top-left" ? "0% 0%" : "center",
2537
+ "background-size": size
2538
+ },
2539
+ "background-repeat": paint.fit === "tile" ? "repeat" : "no-repeat",
2540
+ "background-origin": "padding-box"
2541
+ };
2542
+ };
2543
+ const paintGeometryDeclarations = (paints) => {
2544
+ if (paints.length === 0) return {};
2545
+ const layers = paints.toReversed().map((paint) => paintGeometry(paint));
2546
+ return Object.fromEntries([
2547
+ "background-size",
2548
+ "background-position",
2549
+ "background-repeat",
2550
+ "background-origin"
2551
+ ].map((property) => [property, layers.map((layer) => layer[property]).join(", ")]));
2552
+ };
2553
+ /** The colour of a solid paint, for owners that have no blend: a stored mode is ignored. */
2554
+ const canvasSolidPaintColor = (paint) => paint.kind === "solid" && paint.visible ? canvasColorCss(paint.color, paint.opacity) : void 0;
2555
+ const isBlended = (paint) => paint.visible && (paint.blendMode ?? "normal") !== "normal";
2556
+ /**
2557
+ * The colour of a solid paint for a drawing shortcut of an owner that has a blend. A blended paint
2558
+ * has none, so it falls through to its paint element, ring or SVG paint group.
2559
+ */
2560
+ const canvasUnblendedSolidColor = (paint) => isBlended(paint) ? void 0 : canvasSolidPaintColor(paint);
2561
+ /** A CSS border or outline colour draws one visible solid paint; the paint element draws any other list. */
2562
+ const canvasStrokeCssColor = (paints) => {
2563
+ const visible = paints.filter((paint) => paint.visible);
2564
+ const [only] = visible;
2565
+ if (only === void 0 || visible.length !== 1) return "transparent";
2566
+ return canvasUnblendedSolidColor(only) ?? "transparent";
2567
+ };
2568
+ /** Paints as backgrounds of one element: they blend with nothing, so a blend never comes here. */
2569
+ const canvasPaintLayerDeclarations = (paints) => ({
2570
+ "background-image": paints.toReversed().map((paint) => canvasPaintLayerCss(paint)).join(", "),
2571
+ ...paintGeometryDeclarations(paints)
2572
+ });
2573
+ /** The layer's own fills; when one blends, its fill paint elements draw them all instead. */
2574
+ const canvasPaintDeclarations = (paints) => {
2575
+ const visible = paints.filter((paint) => paint.visible);
2576
+ if (visible.length === 0 || visible.some((paint) => isBlended(paint))) return { background: "none" };
2577
+ const [only] = visible;
2578
+ const color = only === void 0 ? void 0 : canvasUnblendedSolidColor(only);
2579
+ if (color !== void 0 && visible.length === 1) return {
2580
+ background: color,
2581
+ "background-image": "none"
2582
+ };
2583
+ return {
2584
+ "background-color": "transparent",
2585
+ ...canvasPaintLayerDeclarations(visible)
2586
+ };
2587
+ };
2588
+ const canvasTextPaintDeclarations = (paints) => {
2589
+ const visible = paints.filter((paint) => paint.visible);
2590
+ const [only] = visible;
2591
+ if (visible.length === 1 && only?.kind === "solid") return { color: canvasColorCss(only.color, only.opacity) };
2592
+ if (visible.length === 0) return { color: "transparent" };
2593
+ return {
2594
+ color: "transparent",
2595
+ ...visible.length > 1 ? {
2596
+ "background-image": `var(${canvasTextPaintStackProperty(visible)}, none)`,
2597
+ "background-size": "100% 100%",
2598
+ "background-position": "center",
2599
+ "background-repeat": "no-repeat"
2600
+ } : canvasPaintLayerDeclarations(visible),
2601
+ ...visible.some((paint) => paint.kind === "image" && paint.fit === "crop" && paint.transform !== void 0) && {
2602
+ "background-size": "100% var(--canvas-text-paint-height, 100%)",
2603
+ "background-position": "0% var(--canvas-text-paint-y, 0%)"
2604
+ },
2605
+ "background-clip": "text",
2606
+ "-webkit-background-clip": "text"
2607
+ };
2608
+ };
2609
+
2610
+ //#endregion
2611
+ //#region ../../packages/canvas-document/src/canvas-box-decoration.lib.ts
2612
+ const DECORATION_PROPERTIES = new Set(canvasNodeStylePatchSchema.keyof().options.filter((property) => /^(?:border|outline)(?:-|$)/u.test(property) && !property.includes("radius")));
2613
+ const isCanvasDecorationProperty = (control, property) => {
2614
+ const key = property.toLowerCase();
2615
+ return DECORATION_PROPERTIES.has(key) && (key === control || key.startsWith(`${control}-`));
2616
+ };
2617
+ const BORDER_SIDES = [
2618
+ "top",
2619
+ "right",
2620
+ "bottom",
2621
+ "left"
2622
+ ];
2623
+ const DECORATION_STYLES = [
2624
+ "solid",
2625
+ "dashed",
2626
+ "dotted"
2627
+ ];
2628
+ const DECORATION_PARTS = [
2629
+ "width",
2630
+ "style",
2631
+ "color"
2632
+ ];
2633
+ const decorationLength = (value, minimum = 0) => {
2634
+ if (value === void 0 || !/^-?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?(?:px)?$/iu.test(value)) return void 0;
2635
+ const parsed = Number(value.replace(/px$/iu, ""));
2636
+ if (parsed !== 0 && !/px$/iu.test(value)) return void 0;
2637
+ return Number.isFinite(parsed) && parsed >= minimum ? parsed : void 0;
2638
+ };
2639
+ const expandedDecoration = (property, value) => {
2640
+ const parts = canvasCssTokens(value);
2641
+ if (/^(?:border(?:-(?:top|right|bottom|left))?|outline)$/u.test(property)) {
2642
+ const width = parts.find((part) => decorationLength(part) !== void 0);
2643
+ const style = parts.find((part) => /^(?:none|hidden|solid|dashed|dotted|double|groove|ridge|inset|outset)$/u.test(part));
2644
+ const color = parts.find((part) => solidCanvasPaintFromCss("probe", part) !== null);
2645
+ if (width === void 0 || style === void 0 || color === void 0 || parts.length !== DECORATION_PARTS.length) return null;
2646
+ const owners = property === "border" ? BORDER_SIDES.map((side) => `border-${side}`) : [property];
2647
+ return Object.fromEntries(owners.flatMap((owner) => DECORATION_PARTS.map((key) => [`${owner}-${key}`, {
2648
+ width,
2649
+ style,
2650
+ color
2651
+ }[key]])));
2652
+ }
2653
+ if (/^border-(?:width|style|color)$/u.test(property)) {
2654
+ if (parts.length === 0 || parts.length > BORDER_SIDES.length) return null;
2655
+ const [top = "", right = top, bottom = top, left = right] = parts;
2656
+ return Object.fromEntries(BORDER_SIDES.map((side, index) => [`border-${side}-${property.slice(7)}`, [
2657
+ top,
2658
+ right,
2659
+ bottom,
2660
+ left
2661
+ ][index] ?? ""]));
2662
+ }
2663
+ return /^(?:border-(?:top|right|bottom|left)-(?:width|style|color)|outline-(?:width|style|color|offset))$/u.test(property) ? { [property]: value } : null;
2664
+ };
2665
+ const decorationDeclarationsOf = (node, control) => node.additionalStyles?.declarations.filter(({ property, value, enabled }) => isCanvasDecorationProperty(control, property) && (!enabled || value.trim() !== "" || node.appearance?.[control] === void 0)) ?? [];
2666
+ const decorationCssOf = (node, control) => {
2667
+ const additional = decorationDeclarationsOf(node, control);
2668
+ if (additional.some(({ enabled }) => !enabled)) return null;
2669
+ const controlled = new Set(additional.map(({ property }) => property.toLowerCase()));
2670
+ const entries = [...Object.entries(node.styles).filter(([property]) => !controlled.has(property.toLowerCase())), ...additional.map(({ property, value }) => [property, value])];
2671
+ const result = {};
2672
+ for (const [property, value] of entries) {
2673
+ if (!isCanvasDecorationProperty(control, property)) continue;
2674
+ const expanded = expandedDecoration(property.toLowerCase(), canvasCssValue(property, value).trim());
2675
+ if (expanded === null || String(value).includes("!")) return null;
2676
+ Object.assign(result, expanded);
2677
+ }
2678
+ return result;
2679
+ };
2680
+ const canvasBorderOf = (node) => {
2681
+ const css = decorationCssOf(node, "border");
2682
+ if (css === null) return { kind: "custom" };
2683
+ if (node.appearance?.border !== void 0 && decorationDeclarationsOf(node, "border").length === 0) return {
2684
+ kind: "native",
2685
+ value: node.appearance.border
2686
+ };
2687
+ if (node.appearance?.border !== void 0) return { kind: "custom" };
2688
+ if (Object.keys(css).length === 0) return { kind: "absent" };
2689
+ const sides = BORDER_SIDES.map((side) => ({
2690
+ width: decorationLength(css[`border-${side}-width`] ?? "0"),
2691
+ authoredStyle: css[`border-${side}-style`],
2692
+ authoredColor: css[`border-${side}-color`],
2693
+ style: DECORATION_STYLES.find((style) => style === css[`border-${side}-style`]),
2694
+ paint: solidCanvasPaintFromCss(`${node.id}-border`, css[`border-${side}-color`] ?? "")
2695
+ }));
2696
+ const first = sides.find((side) => side.width !== 0) ?? sides[0];
2697
+ if (first?.style === void 0 || first.paint === null || sides.some((side) => side.width === void 0 || side.authoredStyle !== void 0 && side.style === void 0 || side.authoredColor !== void 0 && side.paint === null || side.width !== 0 && (side.style !== first.style || JSON.stringify(side.paint) !== JSON.stringify(first.paint)) || side.width === 0 && (side.style !== void 0 && side.style !== first.style || side.paint !== null && JSON.stringify(side.paint) !== JSON.stringify(first.paint)))) return { kind: "custom" };
2698
+ const [top = 0, right = 0, bottom = 0, left = 0] = sides.map((side) => side.width);
2699
+ return {
2700
+ kind: "native",
2701
+ value: {
2702
+ visible: true,
2703
+ width: {
2704
+ top,
2705
+ right,
2706
+ bottom,
2707
+ left
2708
+ },
2709
+ style: first.style,
2710
+ paints: [first.paint]
2711
+ }
2712
+ };
2713
+ };
2714
+ const canvasOutlineOf = (node) => {
2715
+ const css = decorationCssOf(node, "outline");
2716
+ if (css === null) return { kind: "custom" };
2717
+ if (node.appearance?.outline !== void 0 && decorationDeclarationsOf(node, "outline").length === 0) return {
2718
+ kind: "native",
2719
+ value: node.appearance.outline
2720
+ };
2721
+ if (node.appearance?.outline !== void 0) return { kind: "custom" };
2722
+ if (Object.keys(css).length === 0) return { kind: "absent" };
2723
+ const width = decorationLength(css["outline-width"]);
2724
+ const offset = decorationLength(css["outline-offset"] ?? "0", -Infinity);
2725
+ const style = DECORATION_STYLES.find((held) => held === css["outline-style"]);
2726
+ const paint = solidCanvasPaintFromCss(`${node.id}-outline`, css["outline-color"] ?? "");
2727
+ return width === void 0 || offset === void 0 || style === void 0 || paint === null ? { kind: "custom" } : {
2728
+ kind: "native",
2729
+ value: {
2730
+ visible: true,
2731
+ width,
2732
+ offset,
2733
+ style,
2734
+ paints: [paint]
2735
+ }
2736
+ };
2737
+ };
2738
+ const ZERO_BORDER_WIDTHS = Object.freeze({
2739
+ top: 0,
2740
+ right: 0,
2741
+ bottom: 0,
2742
+ left: 0
2743
+ });
2744
+ /** Only an inside border takes layout space; a centre or outside border paints outside the box. */
2745
+ const canvasBorderLayoutWidths = (border) => border.alignment !== void 0 && border.alignment !== "inside" || border.layoutInclusion === "none" || border.layoutInclusion === "visible" && (!border.visible || border.paints.every((paint) => !paint.visible)) ? ZERO_BORDER_WIDTHS : border.width;
2746
+ const borderDeclarations = (border) => {
2747
+ const color = border.visible ? canvasStrokeCssColor(border.paints) : "transparent";
2748
+ const width = canvasBorderLayoutWidths(border);
2749
+ return {
2750
+ "border-style": border.style,
2751
+ "border-top-width": width.top,
2752
+ "border-right-width": width.right,
2753
+ "border-bottom-width": width.bottom,
2754
+ "border-left-width": width.left,
2755
+ "border-color": color
2756
+ };
2757
+ };
2758
+ const outlineDeclarations = (outline) => {
2759
+ if (!outline.visible) return { "outline-style": "none" };
2760
+ const color = canvasStrokeCssColor(outline.paints);
2761
+ return {
2762
+ "outline-style": outline.style,
2763
+ "outline-width": outline.width,
2764
+ "outline-offset": outline.offset,
2765
+ "outline-color": color
2766
+ };
2767
+ };
2768
+ const canvasBoxDecorationDeclarations = (appearance) => ({
2769
+ ...appearance.border !== void 0 && borderDeclarations(appearance.border),
2770
+ ...appearance.outline !== void 0 && outlineDeclarations(appearance.outline)
2771
+ });
2772
+
2773
+ //#endregion
2774
+ //#region ../../packages/canvas-document/src/canvas-corner-contour.lib.ts
2775
+ const hasCanvasRoundedBorderFallback = (node) => {
2776
+ if (node.geometry?.kind === "boolean") return false;
2777
+ if ((node.appearance?.radius?.smoothing ?? 0) <= 0) return false;
2778
+ const border = canvasBorderOf(node);
2779
+ return border.kind === "custom" || border.kind === "native" && border.value.style !== "solid";
2780
+ };
2781
+ const canvasCornerShapeDeclarations = (node, size = node.box) => {
2782
+ const radius = node.appearance?.radius;
2783
+ if (radius === void 0 || size === void 0 || node.geometry?.kind === "path" || node.geometry?.kind === "boolean") return {};
2784
+ if ((radius.smoothing ?? 0) <= 0 && radius.topLeft === radius.topRight && radius.topLeft === radius.bottomRight && radius.topLeft === radius.bottomLeft) return canvasCornerRadiusDeclarations(radius);
2785
+ const effective = constrainedCornerRadii(radius, size);
2786
+ const declarations = canvasCornerRadiusDeclarations(effective);
2787
+ if ((radius.smoothing ?? 0) <= 0) return declarations;
2788
+ if (hasCanvasRoundedBorderFallback(node)) return {};
2789
+ const outer = `path("${cornerContour(radius, size)}") border-box`;
2790
+ const border = canvasBorderOf(node);
2791
+ if (border.kind !== "native" || Object.values(canvasBorderLayoutWidths(border.value)).every((width) => width === 0)) return {
2792
+ ...declarations,
2793
+ "border-shape": outer
2794
+ };
2795
+ const { top, right, bottom, left } = canvasBorderLayoutWidths(border.value);
2796
+ const radii = [
2797
+ effective.topLeft,
2798
+ effective.topRight,
2799
+ effective.bottomRight,
2800
+ effective.bottomLeft
2801
+ ];
2802
+ const innerRadii = (sides) => radii.map((value, index) => `max(0px, ${String(value)}px - ${String(sides[index] ?? 0)}px)`).join(" ");
2803
+ const horizontal = innerRadii([
2804
+ left,
2805
+ right,
2806
+ right,
2807
+ left
2808
+ ]);
2809
+ const vertical = innerRadii([
2810
+ top,
2811
+ top,
2812
+ bottom,
2813
+ bottom
2814
+ ]);
2815
+ return {
2816
+ ...declarations,
2817
+ "border-shape": `${outer} inset(0 round ${horizontal} / ${vertical}) padding-box`
2818
+ };
2819
+ };
2820
+ const canvasCornerRadiusDeclarations = (radius) => ({
2821
+ "border-top-left-radius": radius.topLeft,
2822
+ "border-top-right-radius": radius.topRight,
2823
+ "border-bottom-right-radius": radius.bottomRight,
2824
+ "border-bottom-left-radius": radius.bottomLeft
2825
+ });
2826
+
2827
+ //#endregion
2828
+ //#region ../../packages/canvas-document/src/canvas-progressive-blur.lib.ts
2829
+ const OWNERS = /* @__PURE__ */ new Set([FRAME_KIND, RECTANGLE_KIND]);
2830
+ const isProgressive = (filter) => filter.visible && filter.kind === "blur" && filter.progression !== void 0;
2831
+ /** The layer's visible progressive background blur, drawn as stacked layers, if it has one. */
2832
+ const canvasProgressiveBlurOf = (node) => node.geometry === void 0 && OWNERS.has(node.component) ? (node.appearance?.backdropFilters ?? []).find((filter) => isProgressive(filter)) ?? null : null;
2833
+ /** The background filters the layer's own backdrop-filter draws: all but the progressive blur. */
2834
+ const canvasUniformBackdropFilters = (node, filters) => {
2835
+ const progressive = canvasProgressiveBlurOf(node);
2836
+ return progressive === null ? filters : filters.filter((filter) => filter !== progressive);
2837
+ };
2838
+
2839
+ //#endregion
2840
+ //#region ../../packages/canvas-document/src/canvas-paint-element-plan.lib.ts
2841
+ const BOX_LAYERS = /* @__PURE__ */ new Set([
2842
+ FRAME_KIND,
2843
+ GROUP_KIND,
2844
+ RECTANGLE_KIND,
2845
+ IMAGE_KIND
2846
+ ]);
2847
+ const STROKE_OWNERS = /* @__PURE__ */ new Set([
2848
+ FRAME_KIND,
2849
+ GROUP_KIND,
2850
+ RECTANGLE_KIND
2851
+ ]);
2852
+ const isCanvasBlendedPaint = (paint) => paint.visible && (paint.blendMode ?? "normal") !== "normal";
2853
+ const isPainted = (paint) => {
2854
+ if (!paint.visible || paint.opacity <= 0) return false;
2855
+ if (paint.kind === "solid") return paint.color.alpha > 0;
2856
+ if (paint.kind === "image") return true;
2857
+ return paint.stops.some((stop) => stop.color.alpha > 0);
2858
+ };
2859
+ const hasCapturedBox = (node) => {
2860
+ const source = node.props?.["source"];
2861
+ if (typeof source !== "object" || source === null) return false;
2862
+ const layout = Reflect.get(source, "layout");
2863
+ return typeof Reflect.get(source, "path") === "string" && typeof layout === "object" && layout !== null && typeof Reflect.get(layout, "tag") === "string";
2864
+ };
2865
+ /**
2866
+ * As in Figma, a rectangle casts its shadows from what it paints, so one with no fill, border or
2867
+ * outline that shows casts none. A frame, and a box captured from HTML, keep the box's shadow.
2868
+ */
2869
+ const canvasCastsNoShadow = (node) => {
2870
+ if (node.component !== "rectangle" || node.geometry !== void 0 || hasCapturedBox(node)) return false;
2871
+ const { fills = [], border, outline } = node.appearance ?? {};
2872
+ const strokes = [border, outline].filter((stroke) => stroke?.visible === true);
2873
+ return [...fills, ...strokes.flatMap((stroke) => stroke?.paints ?? [])].every((paint) => !isPainted(paint));
2874
+ };
2875
+ /** A native image is an `img`, which holds no element; an image drawn from its fills is a box. */
2876
+ const isBoxLayer = (node) => node.geometry === void 0 && BOX_LAYERS.has(node.component) && (node.component !== "image" || (typeof node.props?.["src"] !== "string" || node.props["src"] === "") && node.appearance?.fills !== void 0);
2877
+ const visibleStrokePaints = (stroke) => stroke?.visible === true ? stroke.paints.filter((paint) => paint.visible) : [];
2878
+ /** Plus darker and an image filter have no CSS background form; a blend reaches only so. */
2879
+ const fillNeedsElement = (paint) => isCanvasBlendedPaint(paint) || paint.kind === "image" && (paint.filters?.some((filter) => filter.visible) ?? false);
2880
+ /** The visible fills, when any of them needs its own element: then every fill is one, in order. */
2881
+ const fillElementsOf = (node) => {
2882
+ if (!isBoxLayer(node)) return [];
2883
+ const fills = (node.appearance?.fills ?? []).filter((paint) => paint.visible);
2884
+ return fills.some((paint) => fillNeedsElement(paint)) || fills.length > 0 && canvasProgressiveBlurOf(node) !== null ? fills : [];
2885
+ };
2886
+ /** A captured dashed border with no edited pattern stays CSS's, which the browser draws exactly. */
2887
+ const canvasBorderDrawsWithCssStyle = (border) => border.style === "solid" || border.dashOrigin === "css" && border.dashPattern === void 0 && border.dashCap === void 0;
2888
+ /**
2889
+ * One solid paint on an inside border with a CSS style stays CSS border-color on the layer. Anything
2890
+ * else is #469's border element: its paints stacked as backgrounds clipped to the border area.
2891
+ */
2892
+ const borderNeedsElement = (border) => {
2893
+ const paints = visibleStrokePaints(border);
2894
+ return paints.length > 0 && ((border.alignment ?? "inside") !== "inside" || !canvasBorderDrawsWithCssStyle(border) || paints.length > 1 || paints.some((paint) => paint.kind !== "solid"));
2895
+ };
2896
+ /** The border's ring elements: one per paint when a paint blends, so each blends on its own. */
2897
+ const borderElementsOf = (node, hasFillElements) => {
2898
+ const border = node.appearance?.border;
2899
+ if (border === void 0 || node.geometry !== void 0 || !STROKE_OWNERS.has(node.component)) return [];
2900
+ const paints = visibleStrokePaints(border);
2901
+ if (paints.some((paint) => isCanvasBlendedPaint(paint))) return paints.map((paint) => ({
2902
+ kind: "border",
2903
+ paints: [paint]
2904
+ }));
2905
+ return border.layoutInclusion === "none" || border.layoutInclusion === "visible" || borderNeedsElement(border) || hasFillElements && paints.length > 0 ? [{
2906
+ kind: "border",
2907
+ paints
2908
+ }] : [];
2909
+ };
2910
+ /**
2911
+ * One solid unblended paint around smoothed corners is the editor's contour outline, which follows
2912
+ * the smoothed shape and dashes it.
2913
+ */
2914
+ const isCanvasContourOutlinePaint = (node) => {
2915
+ const [only, ...others] = visibleStrokePaints(node.appearance?.outline);
2916
+ return (node.appearance?.radius?.smoothing ?? 0) > 0 && others.length === 0 && only?.kind === "solid" && !isCanvasBlendedPaint(only);
2917
+ };
2918
+ /** One solid paint on an undashed outline stays CSS outline-color; anything else is a ring. */
2919
+ const outlineElementsOf = (node) => {
2920
+ const outline = node.appearance?.outline;
2921
+ if (outline === void 0 || node.geometry !== void 0 || !STROKE_OWNERS.has(node.component) || outline.width <= 0 || isCanvasContourOutlinePaint(node)) return [];
2922
+ const paints = visibleStrokePaints(outline);
2923
+ if (paints.some((paint) => isCanvasBlendedPaint(paint))) return paints.map((paint) => ({
2924
+ kind: "outline",
2925
+ paints: [paint]
2926
+ }));
2927
+ return paints.length > 1 || outline.style !== "solid" || paints.some((paint) => paint.kind !== "solid") ? [{
2928
+ kind: "outline",
2929
+ paints
2930
+ }] : [];
2931
+ };
2932
+ /** The paint elements of a layer, in the order CSS paints a box, and whether it has any. */
2933
+ const canvasPaintElementPlanOf = (node) => {
2934
+ const fills = fillElementsOf(node);
2935
+ const shadows = isBoxLayer(node) && !canvasCastsNoShadow(node) ? (node.appearance?.shadows ?? []).filter((shadow) => shadow.visible) : [];
2936
+ const outer = shadows.filter((shadow) => shadow.kind === "outer" && isCanvasBlendedPaint(shadow));
2937
+ const inner = shadows.filter((shadow) => shadow.kind === "inner" && (fills.length > 0 || isCanvasBlendedPaint(shadow)));
2938
+ const underChildren = [
2939
+ ...outer.map((shadow) => ({
2940
+ kind: "outer-shadow",
2941
+ shadow
2942
+ })),
2943
+ ...fills.map((paint) => ({
2944
+ kind: "fill",
2945
+ paint
2946
+ })),
2947
+ ...inner.map((shadow) => ({
2948
+ kind: "inner-shadow",
2949
+ shadow
2950
+ }))
2951
+ ];
2952
+ return {
2953
+ elements: [
2954
+ ...underChildren,
2955
+ ...borderElementsOf(node, fills.length > 0),
2956
+ ...outlineElementsOf(node)
2957
+ ],
2958
+ hasPaintElements: underChildren.length > 0
2959
+ };
2960
+ };
2961
+ const canvasFillElementsOf = (plan) => plan.elements.flatMap((element) => element.kind === "fill" ? [element.paint] : []);
2962
+ const canvasShadowElementsOf = (plan, kind) => plan.elements.flatMap((element) => element.kind === kind ? [element.shadow] : []);
2963
+ const canvasStrokeElementsOf = (plan, kind) => plan.elements.flatMap((element) => element.kind === kind ? [element.paints] : []);
2964
+
2965
+ //#endregion
2966
+ //#region ../../packages/canvas-document/src/canvas-stroke-pattern.lib.ts
2967
+ const DASH_LENGTH_FACTOR = 3;
2968
+ /** A stroke's dash, from its stored pattern and cap or, without one, three widths on and two off. */
2969
+ const canvasGeometryStrokePatternOf = (style, width, stored = {}) => {
2970
+ if (style === "solid") return {
2971
+ dash: void 0,
2972
+ linecap: "butt"
2973
+ };
2974
+ if (stored.dashPattern !== void 0) return {
2975
+ dash: stored.dashPattern.map(String).join(" "),
2976
+ linecap: stored.dashCap === "round" ? "round" : stored.dashCap === "square" ? "square" : "butt"
2977
+ };
2978
+ return style === "dotted" ? {
2979
+ dash: `0 ${String(width * 2)}`,
2980
+ linecap: "round"
2981
+ } : {
2982
+ dash: `${String(width * DASH_LENGTH_FACTOR)} ${String(width * 2)}`,
2983
+ linecap: "butt"
2984
+ };
2985
+ };
2986
+
2987
+ //#endregion
2988
+ //#region ../../packages/canvas-document/src/canvas-box-stroke.lib.ts
2989
+ const NO_OUTSET = {
2990
+ top: 0,
2991
+ right: 0,
2992
+ bottom: 0,
2993
+ left: 0
2994
+ };
2995
+ /** How far past the layer's edge each alignment paints, as a share of the side's width. */
2996
+ const BORDER_OUTSET = {
2997
+ inside: 0,
2998
+ center: .5,
2999
+ outside: 1
3000
+ };
3001
+ const CORNERS$1 = [
3002
+ [
3003
+ "topLeft",
3004
+ "top-left",
3005
+ "left",
3006
+ "top"
3007
+ ],
3008
+ [
3009
+ "topRight",
3010
+ "top-right",
3011
+ "right",
3012
+ "top"
3013
+ ],
3014
+ [
3015
+ "bottomRight",
3016
+ "bottom-right",
3017
+ "right",
3018
+ "bottom"
3019
+ ],
3020
+ [
3021
+ "bottomLeft",
3022
+ "bottom-left",
3023
+ "left",
3024
+ "bottom"
3025
+ ]
3026
+ ];
3027
+ /** Whether the layer's border is drawn by paint elements, which the layer then leaves transparent. */
3028
+ const hasCanvasBoxStroke = (node) => canvasStrokeElementsOf(canvasPaintElementPlanOf(node), "border").length > 0;
3029
+ const canvasBoxStrokeRootDeclarations = (node, size = node.box) => {
3030
+ if (!hasCanvasBoxStroke(node)) return {};
3031
+ const declarations = { "border-color": "transparent" };
3032
+ const border = node.appearance?.border;
3033
+ const radius = node.appearance?.radius;
3034
+ if (radius === void 0 || size === void 0 || border?.style !== "solid" || node.geometry?.kind === "path") return declarations;
3035
+ const widths = canvasBorderLayoutWidths(border);
3036
+ if ((radius.smoothing ?? 0) <= 0 || Object.values(widths).every((width) => width === 0)) return declarations;
3037
+ const outer = cornerContour(radius, size);
3038
+ const inner = cornerContour(radius, size, [-widths.left, -widths.top]);
3039
+ return {
3040
+ ...declarations,
3041
+ "border-shape": `path("${outer}") border-box path("${inner}") padding-box`
3042
+ };
3043
+ };
3044
+ /** A rounded corner grows by the outset of its two sides; a square corner stays square. */
3045
+ const outsetRadiusDeclarations = (node, outset) => {
3046
+ const radius = node.appearance?.radius;
3047
+ if (radius === void 0) return { "border-radius": "inherit" };
3048
+ return Object.fromEntries(CORNERS$1.map(([corner, property, horizontal, vertical]) => {
3049
+ const value = radius[corner];
3050
+ return [`border-${property}-radius`, value <= 0 ? 0 : `${String(value + outset[horizontal])}px ${String(value + outset[vertical])}px`];
3051
+ }));
3052
+ };
3053
+ const SVG_PRECISION = 1e3;
3054
+ const svgNumber = (value) => String(Math.round(value * SVG_PRECISION) / SVG_PRECISION);
3055
+ /** A rounded rectangle, clockwise from the end of the top left corner, as SVG draws a rectangle. */
3056
+ const roundedRectanglePath = (width, height, corners) => {
3057
+ const fit = ([x, y]) => [Math.min(x, width / 2), Math.min(y, height / 2)];
3058
+ const [tl, tr, br, bl] = [
3059
+ fit(corners.topLeft),
3060
+ fit(corners.topRight),
3061
+ fit(corners.bottomRight),
3062
+ fit(corners.bottomLeft)
3063
+ ];
3064
+ const arc = ([x, y], toX, toY) => x === 0 || y === 0 ? `L${svgNumber(toX)} ${svgNumber(toY)}` : `A${svgNumber(x)} ${svgNumber(y)} 0 0 1 ${svgNumber(toX)} ${svgNumber(toY)}`;
3065
+ return [
3066
+ `M${svgNumber(tl[0])} 0`,
3067
+ `H${svgNumber(width - tr[0])}`,
3068
+ arc(tr, width, tr[1]),
3069
+ `V${svgNumber(height - br[1])}`,
3070
+ arc(br, width - br[0], height),
3071
+ `H${svgNumber(bl[0])}`,
3072
+ arc(bl, 0, height - bl[1]),
3073
+ `V${svgNumber(tl[1])}`,
3074
+ arc(tl, tl[0], 0),
3075
+ "Z"
3076
+ ].join("");
3077
+ };
3078
+ /**
3079
+ * A dashed ring is the solid ring cut by a mask that strokes its outer edge with the dash pattern
3080
+ * and cap, twice as wide as the ring's widest side so the stroke covers all of it.
3081
+ */
3082
+ const canvasDashMaskDeclarations = (ring) => {
3083
+ if (ring.stroke.style === "solid") return {};
3084
+ const pattern = canvasGeometryStrokePatternOf(ring.stroke.style, ring.widest, ring.stroke);
3085
+ const svg = `<svg xmlns="http://www.w3.org/2000/svg" width="${svgNumber(ring.width)}" height="${svgNumber(ring.height)}"><path d="${roundedRectanglePath(ring.width, ring.height, ring.corners)}" fill="none" stroke="#000" stroke-width="${svgNumber(ring.widest * 2)}" stroke-dasharray="${pattern.dash ?? "none"}" stroke-linecap="${pattern.linecap}"/></svg>`;
3086
+ return {
3087
+ "border-style": "solid",
3088
+ "mask-image": `url("data:image/svg+xml,${encodeURIComponent(svg)}")`,
3089
+ "mask-size": "100% 100%",
3090
+ "mask-repeat": "no-repeat",
3091
+ "mask-origin": "border-box"
3092
+ };
3093
+ };
3094
+ /** The border's dash mask, over its paint element: the layer grown by the alignment's outset. */
3095
+ const borderDashMaskDeclarations = (node, border, size, outset) => {
3096
+ if (size === void 0) return {};
3097
+ const radius = node.appearance?.radius;
3098
+ const grown = ([corner, , horizontal, vertical]) => {
3099
+ const value = radius?.[corner] ?? 0;
3100
+ return value <= 0 ? [0, 0] : [value + outset[horizontal], value + outset[vertical]];
3101
+ };
3102
+ return canvasDashMaskDeclarations({
3103
+ width: size.width + outset.left + outset.right,
3104
+ height: size.height + outset.top + outset.bottom,
3105
+ corners: {
3106
+ topLeft: grown(CORNERS$1[0]),
3107
+ topRight: grown(CORNERS$1[1]),
3108
+ bottomRight: grown(CORNERS$1[2]),
3109
+ bottomLeft: grown(CORNERS$1[3])
3110
+ },
3111
+ widest: Math.max(...Object.values(border.width)),
3112
+ stroke: border
3113
+ });
3114
+ };
3115
+ /**
3116
+ * One of the border's paint elements: a ring with the given paints, the border's whole paint list
3117
+ * unless a paint blends, when each paint has its own ring. It has no scene identity and never
3118
+ * takes part in child layout.
3119
+ */
3120
+ const canvasBoxStrokeDeclarations = (node, size = node.box, ringPaints) => {
3121
+ const border = node.appearance?.border;
3122
+ const [firstRing] = canvasStrokeElementsOf(canvasPaintElementPlanOf(node), "border");
3123
+ if (border === void 0 || firstRing === void 0) return null;
3124
+ const paints = ringPaints ?? firstRing;
3125
+ const widths = canvasBorderLayoutWidths(border);
3126
+ const share = BORDER_OUTSET[border.alignment ?? "inside"];
3127
+ const outset = {
3128
+ top: border.width.top * share,
3129
+ right: border.width.right * share,
3130
+ bottom: border.width.bottom * share,
3131
+ left: border.width.left * share
3132
+ };
3133
+ const appearance = {
3134
+ border: {
3135
+ ...border,
3136
+ alignment: "inside",
3137
+ layoutInclusion: "always"
3138
+ },
3139
+ radius: node.appearance?.radius
3140
+ };
3141
+ const [only] = paints;
3142
+ const isBorderColor = paints.length === 1 && only?.kind === "solid" && (only.blendMode ?? "normal") === "normal" && canvasBorderDrawsWithCssStyle(border) && share === 0;
3143
+ return {
3144
+ position: "absolute",
3145
+ inset: 0,
3146
+ top: -(widths.top + outset.top),
3147
+ right: -(widths.right + outset.right),
3148
+ bottom: -(widths.bottom + outset.bottom),
3149
+ left: -(widths.left + outset.left),
3150
+ "box-sizing": "border-box",
3151
+ "pointer-events": "none",
3152
+ ...share === 0 ? { "border-radius": "inherit" } : outsetRadiusDeclarations(node, outset),
3153
+ ...canvasBoxDecorationDeclarations({
3154
+ ...appearance,
3155
+ border: {
3156
+ ...appearance.border,
3157
+ paints: [...paints]
3158
+ }
3159
+ }),
3160
+ ...!isBorderColor && {
3161
+ "border-color": "transparent",
3162
+ ...canvasPaintLayerDeclarations(paints),
3163
+ "background-origin": "border-box",
3164
+ "background-clip": "border-area"
3165
+ },
3166
+ ...paints.length === 1 && only?.blendMode !== void 0 && only.blendMode !== "normal" && { "mix-blend-mode": only.blendMode },
3167
+ ...share === 0 && canvasCornerShapeDeclarations({
3168
+ ...node,
3169
+ styles: {},
3170
+ additionalStyles: void 0,
3171
+ appearance
3172
+ }, size),
3173
+ ...!isBorderColor && borderDashMaskDeclarations(node, border, size, share === 0 ? NO_OUTSET : outset)
3174
+ };
3175
+ };
3176
+
3177
+ //#endregion
3178
+ //#region ../../packages/canvas-document/src/canvas-effect-projection.lib.ts
3179
+ /** The shadows the layer element draws itself: those the plan does not give their own element. */
3180
+ const layerShadowsOf = (node, shadows) => {
3181
+ if (canvasCastsNoShadow(node)) return [];
3182
+ const plan = canvasPaintElementPlanOf(node);
3183
+ const elements = [...canvasShadowElementsOf(plan, "outer-shadow"), ...canvasShadowElementsOf(plan, "inner-shadow")];
3184
+ return elements.length === 0 ? shadows : shadows.filter((shadow) => !elements.includes(shadow));
3185
+ };
3186
+ const shadowCss = (shadow) => {
3187
+ return `${shadow.kind === "inner" ? "inset " : ""}${String(shadow.offsetX)}px ${String(shadow.offsetY)}px ${String(shadow.blur)}px ${String(shadow.spread)}px ${canvasColorCss(shadow.color)}`;
3188
+ };
3189
+ const textShadowCss = (shadow) => `${String(shadow.offsetX)}px ${String(shadow.offsetY)}px ${String(shadow.blur)}px ${canvasColorCss(shadow.color)}`;
3190
+ const canvasShadowDeclarations = (node, shadows) => {
3191
+ const visible = layerShadowsOf(node, shadows).filter((shadow) => shadow.visible);
3192
+ if (node.component === "text") {
3193
+ const textShadow = visible.filter((shadow) => shadow.kind === "outer" && shadow.spread === 0).map((shadow) => textShadowCss(shadow)).join(", ");
3194
+ return {
3195
+ "box-shadow": "none",
3196
+ "text-shadow": textShadow === "" ? "none" : textShadow
3197
+ };
3198
+ }
3199
+ const boxShadow = visible.map((shadow) => shadowCss(shadow)).join(", ");
3200
+ return { "box-shadow": boxShadow === "" ? "none" : boxShadow };
3201
+ };
3202
+ /** One shadow's paint element: the layer's border box casting only that shadow, with its blend. */
3203
+ const canvasShadowPaintDeclarations = (node, shadow) => {
3204
+ const border = node.appearance?.border;
3205
+ const widths = border === void 0 ? {
3206
+ top: 0,
3207
+ right: 0,
3208
+ bottom: 0,
3209
+ left: 0
3210
+ } : canvasBorderLayoutWidths(border);
3211
+ return {
3212
+ position: "absolute",
3213
+ top: -widths.top,
3214
+ right: -widths.right,
3215
+ bottom: -widths.bottom,
3216
+ left: -widths.left,
3217
+ "border-radius": "inherit",
3218
+ "pointer-events": "none",
3219
+ "box-shadow": shadowCss(shadow),
3220
+ "mix-blend-mode": shadow.blendMode ?? "normal"
3221
+ };
3222
+ };
3223
+
3224
+ //#endregion
3225
+ //#region ../../packages/canvas-document/src/canvas-css-fill.lib.ts
3226
+ const PERCENT = 100;
3227
+ const DEFAULT_ANGLE = 180;
3228
+ const gradientStops = (id, parts) => {
3229
+ const stops = parts.map((part, index) => {
3230
+ const [colorText = "", positionText, ...extra] = canvasCssTokens(part);
3231
+ const color = canvasColorFromCss(colorText);
3232
+ const position = positionText === void 0 ? index / (parts.length - 1) : /^\d+(?:\.\d+)?%$/u.test(positionText) ? Number(positionText.slice(0, -1)) / PERCENT : NaN;
3233
+ return color === null || extra.length > 0 ? null : {
3234
+ id: `${id}-stop-${String(index)}`,
3235
+ color,
3236
+ position
3237
+ };
3238
+ });
3239
+ if (stops.includes(null)) return null;
3240
+ return stops.filter((stop) => stop !== null);
3241
+ };
3242
+ const gradientPaint = (id, value) => {
3243
+ const match = /^(linear|radial)-gradient\((.*)\)$/su.exec(value);
3244
+ if (match === null) return null;
3245
+ const parts = [...canvasCssTokens(match[2] ?? "", ",")];
3246
+ const first = parts[0] ?? "";
3247
+ const angle = /^(-?(?:\d+(?:\.\d*)?|\.\d+))deg$/u.exec(first);
3248
+ const radial = /^ellipse ([\d.]+)% ([\d.]+)% at (-?[\d.]+)% (-?[\d.]+)%$/u.exec(first);
3249
+ if (angle !== null && match[1] !== "linear" || radial !== null && match[1] !== "radial") return null;
3250
+ if (angle !== null || radial !== null) parts.shift();
3251
+ const hasPositions = parts.map((part) => canvasCssTokens(part).length > 1);
3252
+ if (hasPositions.some(Boolean) && !hasPositions.every(Boolean)) return null;
3253
+ const stops = gradientStops(id, parts);
3254
+ if (stops === null) return null;
3255
+ const base = {
3256
+ id,
3257
+ visible: true,
3258
+ opacity: 1,
3259
+ stops
3260
+ };
3261
+ const result = canvasPaintSchema.safeParse(match[1] === "linear" ? {
3262
+ ...base,
3263
+ kind: "linear-gradient",
3264
+ angle: Number(angle?.[1] ?? DEFAULT_ANGLE)
3265
+ } : radial === null ? null : {
3266
+ ...base,
3267
+ kind: "radial-gradient",
3268
+ radius: {
3269
+ x: Number(radial[1]) / PERCENT,
3270
+ y: Number(radial[2]) / PERCENT
3271
+ },
3272
+ center: {
3273
+ x: Number(radial[3]) / PERCENT,
3274
+ y: Number(radial[4]) / PERCENT
3275
+ }
3276
+ });
3277
+ if (!result.success) return null;
3278
+ const paint = result.data;
3279
+ const firstStop = "stops" in paint ? paint.stops[0] : void 0;
3280
+ if (firstStop !== void 0 && paint.kind === "linear-gradient" && paint.stops.every((stop) => JSON.stringify(stop.color) === JSON.stringify(firstStop.color))) return {
3281
+ id,
3282
+ kind: "solid",
3283
+ visible: true,
3284
+ opacity: 1,
3285
+ color: firstStop.color
3286
+ };
3287
+ return paint;
3288
+ };
3289
+ const layerValue = (css, property, index, fallback) => {
3290
+ const parts = canvasCssTokens(css[property] ?? fallback, ",");
3291
+ return parts[index % parts.length] ?? fallback;
3292
+ };
3293
+ const imagePaint = (id, value, css, index) => {
3294
+ const match = /^url\((?:"([^"\\]*)"|'([^'\\]*)'|([^\s'"()\\]+))\)$/u.exec(value);
3295
+ const assetId = match?.[1] ?? match?.[2] ?? match?.[3];
3296
+ if (assetId === void 0 || assetId === "" || assetId.startsWith("data:image/svg+xml")) return null;
3297
+ const position = layerValue(css, "background-position", index, "0% 0%");
3298
+ const size = layerValue(css, "background-size", index, "auto");
3299
+ const repeat = layerValue(css, "background-repeat", index, "repeat");
3300
+ const isCentered = [
3301
+ "center",
3302
+ "center center",
3303
+ "50% 50%"
3304
+ ].includes(position);
3305
+ const base = {
3306
+ id,
3307
+ kind: "image",
3308
+ visible: true,
3309
+ opacity: 1,
3310
+ assetId
3311
+ };
3312
+ if (repeat === "repeat" && size === "auto" && (position === "0% 0%" || isCentered)) return {
3313
+ ...base,
3314
+ fit: "tile",
3315
+ tileOrigin: isCentered ? "center" : "top-left"
3316
+ };
3317
+ if (repeat !== "no-repeat" || !isCentered) return null;
3318
+ const mode = Object.entries({
3319
+ cover: "cover",
3320
+ contain: "fit",
3321
+ "100% 100%": "fill"
3322
+ }).find(([key]) => key === size)?.[1];
3323
+ return mode === void 0 ? null : {
3324
+ ...base,
3325
+ fit: mode
3326
+ };
3327
+ };
3328
+ /** Decode the lossless CSS forms emitted by the legacy importer; other syntax stays authored. */
3329
+ const canvasCssFills = (nodeId, css) => {
3330
+ const background = css["background"];
3331
+ const colorText = css["background-color"] ?? background;
3332
+ const color = colorText === void 0 || colorText === "none" ? null : solidCanvasPaintFromCss(`${nodeId}-background`, colorText);
3333
+ if (colorText !== void 0 && colorText !== "none" && color === null) return null;
3334
+ const image = css["background-image"];
3335
+ if (image === void 0 || image === "none") return color === null ? [] : [color];
3336
+ const layers = canvasCssTokens(image, ",").map((value, index) => {
3337
+ const id = `${nodeId}-fill-${String(index)}`;
3338
+ const gradient = gradientPaint(id, value);
3339
+ const size = layerValue(css, "background-size", index, "auto");
3340
+ if (gradient !== null && ![
3341
+ "auto",
3342
+ "auto auto",
3343
+ "100% 100%"
3344
+ ].includes(size)) return null;
3345
+ const paint = gradient ?? imagePaint(id, value, css, index);
3346
+ const mode = canvasBlendModeSchema.safeParse(layerValue(css, "background-blend-mode", index, "normal"));
3347
+ return paint === null || !mode.success ? null : {
3348
+ ...paint,
3349
+ blendMode: mode.data
3350
+ };
3351
+ });
3352
+ if (layers.includes(null)) return null;
3353
+ return [...color === null ? [] : [color], ...layers.filter((paint) => paint !== null).toReversed()];
3354
+ };
3355
+
3356
+ //#endregion
3357
+ //#region ../../packages/canvas-document/src/canvas-style-ownership.lib.ts
3358
+ /** The CSS properties each native appearance setting paints, and so is replaced by when written. */
3359
+ const APPEARANCE_OWNERS = [
3360
+ ["fills", /^background(?:-color|-image)?$/u],
3361
+ ["radius", /^border(?:-(?:top|bottom)-(?:left|right))?-radius$/u],
3362
+ ["border", /^border(?:-(?:top|right|bottom|left))?(?:-(?:width|style|color))?$|^border-(?:width|style|color)$/u],
3363
+ ["outline", /^outline(?:-(?:width|style|color|offset))?$/u],
3364
+ ["shadows", /^(?:box|text)-shadow$/u],
3365
+ ["filters", /^filter$/u],
3366
+ ["backdropFilters", /^backdrop-filter$/u],
3367
+ ["opacity", /^opacity$/u],
3368
+ ["blendMode", /^mix-blend-mode$/u]
3369
+ ];
3370
+ const TEXT_FILL_PROPERTIES = /* @__PURE__ */ new Set(["color", "-webkit-text-fill-color"]);
3371
+ /**
3372
+ * The native settings of a layer that written CSS replaces: each is cleared, so that the written
3373
+ * CSS paints instead of being drawn over. A text layer's fills are its colour, not a background.
3374
+ */
3375
+ const canvasAppearanceOwnedBy = (node, properties) => {
3376
+ const owned = /* @__PURE__ */ new Set();
3377
+ for (const written of properties) {
3378
+ const property = written.toLowerCase();
3379
+ const isText = node.component === "text";
3380
+ if (isText && TEXT_FILL_PROPERTIES.has(property)) owned.add("fills");
3381
+ for (const [setting, pattern] of APPEARANCE_OWNERS) if (pattern.test(property) && (!isText || setting !== "fills")) owned.add(setting);
3382
+ }
3383
+ return [...owned].filter((setting) => node.appearance?.[setting] !== void 0);
3384
+ };
3385
+
3386
+ //#endregion
3387
+ //#region ../../packages/canvas-document/src/canvas-fill-ownership.lib.ts
3388
+ const PAINT_PROPERTIES = /* @__PURE__ */ new Set([
3389
+ "background",
3390
+ "background-color",
3391
+ "background-image"
3392
+ ]);
3393
+ const GEOMETRY_PROPERTIES = /* @__PURE__ */ new Set([
3394
+ "background-position",
3395
+ "background-size",
3396
+ "background-repeat",
3397
+ "background-origin",
3398
+ "background-blend-mode"
3399
+ ]);
3400
+ const backgroundCss = (node) => {
3401
+ if ((node.additionalStyles?.declarations ?? []).some(({ property, enabled }) => property.toLowerCase().startsWith("background") && !enabled)) return null;
3402
+ if (Object.keys(node.styles).some((property) => property.toLowerCase().startsWith("background") && property !== property.toLowerCase())) return null;
3403
+ const entries = Object.entries(canvasAuthoredStyleDeclarations(node)).filter(([property, value]) => property.toLowerCase().startsWith("background") && value !== "").map(([property, value]) => [property.toLowerCase(), String(value).trim()]);
3404
+ if (entries.some(([, value]) => value.includes("!"))) return null;
3405
+ let css = {};
3406
+ for (const [property, value] of entries) {
3407
+ if (property === "background") {
3408
+ const blend = css["background-blend-mode"];
3409
+ css = blend === void 0 ? {} : { "background-blend-mode": blend };
3410
+ }
3411
+ css[property] = value;
3412
+ }
3413
+ return css;
3414
+ };
3415
+ /** Reading never mutates a legacy layer. Its first fill edit transfers the same paint atomically. */
3416
+ const canvasFillOwnershipOf = (node) => {
3417
+ const css = backgroundCss(node);
3418
+ if (css === null) return { kind: "custom" };
3419
+ const fills = node.appearance?.fills;
3420
+ if (fills !== void 0 && fills.every((paint) => !paint.visible) && css["background"] !== void 0 && css["background-image"] !== void 0 && css["background-image"] !== "none") return { kind: "custom" };
3421
+ if (fills !== void 0) return {
3422
+ kind: "native",
3423
+ fills,
3424
+ owned: PAINT_PROPERTIES
3425
+ };
3426
+ if (Object.entries(css).some(([property, value]) => !PAINT_PROPERTIES.has(property) && !GEOMETRY_PROPERTIES.has(property) && !["background-blend-mode", "background-clip"].includes(property) && value !== "") || css["background-origin"] !== void 0 && css["background-origin"] !== "padding-box" || css["background-clip"] !== void 0 && css["background-clip"] !== "border-box") return { kind: "custom" };
3427
+ const converted = canvasCssFills(node.id, css);
3428
+ if (converted === null) return { kind: "custom" };
3429
+ if (css["background-image"] !== void 0 && converted.some((paint) => paint.kind !== "image") && (node.appearance?.border !== void 0 || Object.keys(node.styles).some((property) => /^border(?:-|$)/u.test(property)))) return { kind: "custom" };
3430
+ const owned = new Set(PAINT_PROPERTIES);
3431
+ for (const property of GEOMETRY_PROPERTIES) owned.add(property);
3432
+ return {
3433
+ kind: "native",
3434
+ fills: converted,
3435
+ owned
3436
+ };
3437
+ };
3438
+
3439
+ //#endregion
3440
+ //#region ../../packages/canvas-document/src/canvas-fill-paint.lib.ts
3441
+ /**
3442
+ * The layer gives up its background when its fills are paint elements. Only a progressive blur
3443
+ * makes it a stacking context, for the blur layers that sit behind it.
3444
+ */
3445
+ const canvasFillOwnerDeclarations = (node) => ({
3446
+ ...canvasFillElementsOf(canvasPaintElementPlanOf(node)).length > 0 && { background: "none" },
3447
+ ...canvasProgressiveBlurOf(node) !== null && { isolation: "isolate" }
3448
+ });
3449
+ /** One fill's paint element: its paint as a background, with its own filter and blend. */
3450
+ const canvasFillPaintDeclarations = (paint) => ({
3451
+ position: "absolute",
3452
+ inset: 0,
3453
+ ...canvasPaintLayerDeclarations([paint]),
3454
+ ...paint.kind === "image" && paint.filters !== void 0 && { filter: canvasFilterListCss(paint.filters) },
3455
+ ...paint.blendMode !== void 0 && paint.blendMode !== "normal" && { "mix-blend-mode": paint.blendMode }
3456
+ });
3457
+
3458
+ //#endregion
3459
+ //#region ../../packages/canvas-document/src/canvas-outline-paint.lib.ts
3460
+ const CORNERS = [
3461
+ ["topLeft", "top-left"],
3462
+ ["topRight", "top-right"],
3463
+ ["bottomRight", "bottom-right"],
3464
+ ["bottomLeft", "bottom-left"]
3465
+ ];
3466
+ /** The outline drawn as rings of its paints, when CSS outline cannot draw them. */
3467
+ const hasCanvasOutlinePaint = (node) => canvasStrokeElementsOf(canvasPaintElementPlanOf(node), "outline").length > 0;
3468
+ /** The layer stops drawing its outline; the outline's paint element draws it. */
3469
+ const canvasOutlinePaintOwnerDeclarations = (node) => hasCanvasOutlinePaint(node) ? { "outline-style": "none" } : {};
3470
+ /**
3471
+ * Around smoothed corners the ring's paint shows only along the smoothed contour, as the editor's
3472
+ * contour outline draws it: a mask strokes the contour, with the outline's dashes.
3473
+ */
3474
+ const smoothedOutlineMaskDeclarations = (node, outline, size) => {
3475
+ const radius = node.appearance?.radius;
3476
+ if (radius === void 0) return {};
3477
+ const reach = outline.offset + outline.width;
3478
+ const pattern = canvasGeometryStrokePatternOf(outline.style, outline.width, outline);
3479
+ const contour = offsetCornerContour(radius, size, outline.offset + outline.width / 2);
3480
+ const svg = `<svg xmlns="http://www.w3.org/2000/svg" width="${String(size.width + 2 * reach)}" height="${String(size.height + 2 * reach)}"><path d="${contour}" transform="translate(${String(reach)} ${String(reach)})" fill="none" stroke="#000" stroke-width="${String(outline.width)}" stroke-dasharray="${pattern.dash ?? "none"}" stroke-linecap="${pattern.linecap}"/></svg>`;
3481
+ return {
3482
+ "background-clip": "border-box",
3483
+ "mask-image": `url("data:image/svg+xml,${encodeURIComponent(svg)}")`,
3484
+ "mask-size": "100% 100%",
3485
+ "mask-repeat": "no-repeat",
3486
+ "mask-origin": "border-box"
3487
+ };
3488
+ };
3489
+ /**
3490
+ * One of the outline's paint elements: a border of the outline's width, its offset outside the
3491
+ * layer's border box, with the given paints stacked as backgrounds on that ring.
3492
+ */
3493
+ const canvasOutlinePaintDeclarations = (node, size = node.box, ringPaints) => {
3494
+ const outline = node.appearance?.outline;
3495
+ const [firstRing] = canvasStrokeElementsOf(canvasPaintElementPlanOf(node), "outline");
3496
+ if (outline === void 0 || firstRing === void 0) return null;
3497
+ const reach = outline.offset + outline.width;
3498
+ const radius = node.appearance?.radius;
3499
+ const paints = ringPaints ?? firstRing;
3500
+ const [only] = paints;
3501
+ const border = node.appearance?.border;
3502
+ const widths = border === void 0 ? {
3503
+ top: 0,
3504
+ right: 0,
3505
+ bottom: 0,
3506
+ left: 0
3507
+ } : canvasBorderLayoutWidths(border);
3508
+ const grown = (corner) => {
3509
+ const value = radius?.[corner] ?? 0;
3510
+ return value <= 0 ? 0 : value + reach;
3511
+ };
3512
+ return {
3513
+ position: "absolute",
3514
+ top: -(widths.top + reach),
3515
+ right: -(widths.right + reach),
3516
+ bottom: -(widths.bottom + reach),
3517
+ left: -(widths.left + reach),
3518
+ "box-sizing": "border-box",
3519
+ "pointer-events": "none",
3520
+ "border-style": outline.style,
3521
+ "border-width": outline.width,
3522
+ "border-color": "transparent",
3523
+ ...Object.fromEntries(CORNERS.map(([corner, property]) => [`border-${property}-radius`, grown(corner)])),
3524
+ ...canvasPaintLayerDeclarations(paints),
3525
+ "background-origin": "border-box",
3526
+ "background-clip": "border-area",
3527
+ ...paints.length === 1 && only?.blendMode !== void 0 && only.blendMode !== "normal" && { "mix-blend-mode": only.blendMode },
3528
+ ...size !== void 0 && (radius?.smoothing ?? 0) > 0 && smoothedOutlineMaskDeclarations(node, outline, size),
3529
+ ...size !== void 0 && (radius?.smoothing ?? 0) <= 0 && canvasDashMaskDeclarations({
3530
+ width: size.width + 2 * reach,
3531
+ height: size.height + 2 * reach,
3532
+ corners: {
3533
+ topLeft: [grown("topLeft"), grown("topLeft")],
3534
+ topRight: [grown("topRight"), grown("topRight")],
3535
+ bottomRight: [grown("bottomRight"), grown("bottomRight")],
3536
+ bottomLeft: [grown("bottomLeft"), grown("bottomLeft")]
3537
+ },
3538
+ widest: outline.width,
3539
+ stroke: outline
3540
+ })
3541
+ };
3542
+ };
3543
+
3544
+ //#endregion
3545
+ //#region ../../packages/canvas-document/src/canvas-text-paint-layers.lib.ts
3546
+ /** Decorated paint stacks separate glyph paint from independently colored lines. */
3547
+ const hasCanvasTextRunPaints = (node) => {
3548
+ if (hasCanvasRichTextPaints(node)) return true;
3549
+ if (node.typography?.decoration === void 0) return false;
3550
+ const paints = node.appearance?.fills?.filter((paint) => paint.visible) ?? [];
3551
+ return paints.length > 1 || paints.some((paint) => paint.kind !== "solid");
3552
+ };
3553
+
3554
+ //#endregion
3555
+ //#region ../../packages/canvas-document/src/canvas-appearance.lib.ts
3556
+ const numericRatio = (value, fallback) => {
3557
+ const parsed = typeof value === "number" ? value : Number(value);
3558
+ return Number.isFinite(parsed) ? Math.min(1, Math.max(0, parsed)) : fallback;
3559
+ };
3560
+ const blendMode = (value) => CANVAS_BLEND_MODES.find((mode) => mode === value) ?? "normal";
3561
+ const boundedLength = (value, minimum) => {
3562
+ const parsed = Number(String(value ?? "").replace("px", ""));
3563
+ return Number.isFinite(parsed) ? Math.max(minimum, parsed) : 0;
3564
+ };
3565
+ const numericLength = (value) => boundedLength(value, 0);
3566
+ const nonZeroOr = (value, fallback) => value === 0 ? fallback : value;
3567
+ const radiusFromStyles = (styles) => {
3568
+ const [first = 0, second = first, third = first, fourth = second] = String(styles["border-radius"] ?? "0").split(/\s+/u).map((value) => numericLength(value));
3569
+ return {
3570
+ topLeft: nonZeroOr(numericLength(styles["border-top-left-radius"]), first),
3571
+ topRight: nonZeroOr(numericLength(styles["border-top-right-radius"]), second),
3572
+ bottomRight: nonZeroOr(numericLength(styles["border-bottom-right-radius"]), third),
3573
+ bottomLeft: nonZeroOr(numericLength(styles["border-bottom-left-radius"]), fourth)
3574
+ };
3575
+ };
3576
+ const canvasAppearanceOf = (node) => {
3577
+ const empty = emptyCanvasAppearance();
3578
+ const border = canvasBorderOf(node);
3579
+ const outline = canvasOutlineOf(node);
3580
+ const fill = solidCanvasPaintFromCss(`${node.id}-fill`, String(node.styles[node.component === "text" ? "color" : "background"] ?? ""));
3581
+ const fillOwner = node.component === "text" ? null : canvasFillOwnershipOf(node);
3582
+ return {
3583
+ ...empty,
3584
+ opacity: node.appearance?.opacity ?? numericRatio(node.styles["opacity"], 1),
3585
+ blendMode: node.appearance?.blendMode ?? blendMode(node.styles["mix-blend-mode"]),
3586
+ fills: fillOwner?.kind === "native" ? [...fillOwner.fills] : node.appearance?.fills ?? (fill === null ? [] : [fill]),
3587
+ border: border.kind === "native" ? border.value : node.appearance?.border ?? empty.border,
3588
+ outline: outline.kind === "native" ? outline.value : node.appearance?.outline ?? empty.outline,
3589
+ radius: node.appearance?.radius ?? radiusFromStyles(node.styles),
3590
+ ...node.appearance?.retainedBorder !== void 0 && { retainedBorder: node.appearance.retainedBorder },
3591
+ shadows: node.appearance?.shadows ?? [],
3592
+ filters: node.appearance?.filters ?? [],
3593
+ backdropFilters: node.appearance?.backdropFilters ?? []
3594
+ };
3595
+ };
3596
+ const fillDeclarations = (node) => {
3597
+ const fills = node.appearance?.fills;
3598
+ if (node.component === "text" && hasCanvasTextRunPaints(node)) return {
3599
+ ...fills !== void 0 && { color: canvasTextPaintDeclarations(fills)["color"] ?? "transparent" },
3600
+ "background-image": "none"
3601
+ };
3602
+ return fills === void 0 ? {} : node.component === "text" ? canvasTextPaintDeclarations(fills) : canvasPaintDeclarations(fills);
3603
+ };
3604
+ const canvasAppearanceDeclarations = (node) => {
3605
+ const appearance = node.appearance;
3606
+ const declarations = {
3607
+ ...fillDeclarations(node),
3608
+ ...canvasFillOwnerDeclarations(node)
3609
+ };
3610
+ if ((appearance?.opacity ?? numericRatio(node.styles["opacity"], 1)) === 0) declarations["pointer-events"] = "none";
3611
+ if (appearance === void 0) return declarations;
3612
+ if (appearance.opacity !== void 0) declarations["opacity"] = appearance.opacity;
3613
+ if (appearance.blendMode !== void 0) declarations["mix-blend-mode"] = appearance.blendMode;
3614
+ if (appearance.radius !== void 0 && node.geometry?.kind !== "path") Object.assign(declarations, canvasCornerRadiusDeclarations(appearance.radius), canvasCornerShapeDeclarations(node));
3615
+ Object.assign(declarations, canvasBoxDecorationDeclarations(appearance), canvasBoxStrokeRootDeclarations(node), canvasOutlinePaintOwnerDeclarations(node));
3616
+ if (appearance.filters !== void 0) declarations["filter"] = canvasFilterListCss(appearance.filters);
3617
+ if (appearance.shadows !== void 0) Object.assign(declarations, canvasShadowDeclarations(node, appearance.shadows));
3618
+ if (appearance.backdropFilters !== void 0) declarations["backdrop-filter"] = canvasFilterListCss(canvasUniformBackdropFilters(node, appearance.backdropFilters));
3619
+ return declarations;
3620
+ };
3621
+
3622
+ //#endregion
3623
+ //#region ../../packages/canvas-document/src/canvas-mask-source.lib.ts
3624
+ const hasSquareCorners = (node) => {
3625
+ const radius = canvasAppearanceOf(node).radius;
3626
+ return radius.topLeft === 0 && radius.topRight === 0 && radius.bottomRight === 0 && radius.bottomLeft === 0;
3627
+ };
3628
+ /** Text masks through background-clip, which shows only a layer's own fills. */
3629
+ const isFillOnly = (node) => {
3630
+ const appearance = canvasAppearanceOf(node);
3631
+ return canvasBorderOf(node).kind !== "native" && canvasOutlineOf(node).kind !== "native" && appearance.shadows.every((shadow) => !shadow.visible) && appearance.filters.every((filter) => !filter.visible) && appearance.backdropFilters.every((filter) => !filter.visible);
3632
+ };
3633
+ /** Whether text can mask the layer: an image or unrounded rectangle whose paint is fills only. */
3634
+ const canCanvasTextMask = (node) => node !== void 0 && (node.component === "image" || node.component === "rectangle" && hasSquareCorners(node)) && isFillOnly(node);
3635
+
3636
+ //#endregion
3637
+ //#region ../../packages/canvas-document/src/canvas-text-mask.lib.ts
3638
+ /** A native image layer's stored natural size, written when the image was added or imported. */
3639
+ const nativeImageSizeOf = (node) => {
3640
+ const width = node.props?.["naturalWidth"];
3641
+ const height = node.props?.["naturalHeight"];
3642
+ return typeof width === "number" && typeof height === "number" && width > 0 && height > 0 ? {
3643
+ width,
3644
+ height
3645
+ } : void 0;
3646
+ };
3647
+ const textMaskGroupOf = (document, node) => {
3648
+ if (node.component !== "text") return void 0;
3649
+ const parentId = document.relationships[node.id]?.parentId;
3650
+ const parent = parentId === void 0 ? void 0 : document.nodes[parentId];
3651
+ return parent?.geometry?.kind === "mask" && parent.geometry.maskId === node.id ? parent : void 0;
3652
+ };
3653
+ /**
3654
+ * The layers a text mask source shows through its letters, backmost first, when it masks only
3655
+ * images and unrounded rectangles whose paint is fills; otherwise null.
3656
+ */
3657
+ const canvasTextMaskContentsOf = (document, node) => {
3658
+ const group = textMaskGroupOf(document, node);
3659
+ if (group === void 0) return null;
3660
+ const contents = childIdsOf(document.relationships, group.id).flatMap((id) => id === node.id ? [] : document.nodes[id] ?? []);
3661
+ const text = node.box;
3662
+ return text !== void 0 && contents.length > 0 && contents.every((content) => canCanvasTextMask(content) && layersOf(content, text) !== null) ? contents : null;
3663
+ };
3664
+ /** Where an image of the given natural size draws within a box, for each fit. */
3665
+ const fittedBox = (fit, box, natural) => {
3666
+ const scale = (fit === "cover" ? Math.max : Math.min)(box.width / natural.width, box.height / natural.height);
3667
+ const width = natural.width * scale;
3668
+ const height = natural.height * scale;
3669
+ return {
3670
+ x: box.x + (box.width - width) / 2,
3671
+ y: box.y + (box.height - height) / 2,
3672
+ width,
3673
+ height
3674
+ };
3675
+ };
3676
+ /** One image fill placed in the content's box, or null when its natural size is unknown. */
3677
+ const imageLayer = (paint, box) => {
3678
+ const image = canvasPaintLayerCss(paint);
3679
+ if (paint.fit === "fill") return {
3680
+ image,
3681
+ box
3682
+ };
3683
+ if (paint.fit === "crop" && paint.crop !== void 0) {
3684
+ const width = box.width / Math.max(paint.crop.width, Number.EPSILON);
3685
+ const height = box.height / Math.max(paint.crop.height, Number.EPSILON);
3686
+ return {
3687
+ image,
3688
+ box: {
3689
+ x: box.x - paint.crop.x * width,
3690
+ y: box.y - paint.crop.y * height,
3691
+ width,
3692
+ height
3693
+ }
3694
+ };
3695
+ }
3696
+ const natural = paint.naturalSize;
3697
+ if (natural === void 0) return null;
3698
+ if (paint.fit === "tile") {
3699
+ const scale = paint.tileScale ?? 1;
3700
+ return {
3701
+ image,
3702
+ box: {
3703
+ x: box.x,
3704
+ y: box.y,
3705
+ width: natural.width * scale,
3706
+ height: natural.height * scale
3707
+ },
3708
+ repeat: "repeat"
3709
+ };
3710
+ }
3711
+ return {
3712
+ image,
3713
+ box: fittedBox(paint.fit === "fit" ? "fit" : "cover", box, natural)
3714
+ };
3715
+ };
3716
+ /** A native image layer's source placed in its box, or null when its natural size is unknown. */
3717
+ const nativeImageLayer = (node, box) => {
3718
+ const source = node.props?.["src"];
3719
+ if (typeof source !== "string" || source === "") return [];
3720
+ const image = canvasPaintImageUrl(source);
3721
+ const fit = node.props?.["fit"];
3722
+ if (fit !== "cover" && fit !== "contain") return [{
3723
+ image,
3724
+ box
3725
+ }];
3726
+ const natural = nativeImageSizeOf(node);
3727
+ return natural === void 0 ? null : [{
3728
+ image,
3729
+ box: fittedBox(fit === "cover" ? "cover" : "fit", box, natural)
3730
+ }];
3731
+ };
3732
+ /** A content layer's visible fills as layers in the text's box, topmost first. */
3733
+ const layersOf = (content, text) => {
3734
+ if (content.box === void 0) return [];
3735
+ const box = {
3736
+ ...content.box,
3737
+ x: content.box.x - text.x,
3738
+ y: content.box.y - text.y
3739
+ };
3740
+ if (content.component === "image" && content.appearance?.fills === void 0) return nativeImageLayer(content, box);
3741
+ const { opacity } = canvasAppearanceOf(content);
3742
+ const layers = [];
3743
+ const fills = canvasAppearanceOf(content).fills.filter((held) => held.visible).toReversed();
3744
+ for (const paint of fills) if (paint.kind === "image") {
3745
+ const layer = imageLayer(paint, box);
3746
+ if (layer === null) return null;
3747
+ layers.push(layer);
3748
+ } else layers.push({
3749
+ image: canvasPaintLayerCss({
3750
+ ...paint,
3751
+ opacity: paint.opacity * opacity
3752
+ }),
3753
+ box
3754
+ });
3755
+ return layers;
3756
+ };
3757
+
3758
+ //#endregion
3759
+ //#region ../../packages/canvas-document/src/canvas-geometry-clip.lib.ts
3760
+ const canvasMaskSourceOf = (document, node) => node.geometry?.kind === "mask" ? document.nodes[node.geometry.maskId] : void 0;
3761
+ const IDENTITY = {
3762
+ a: 1,
3763
+ b: 0,
3764
+ c: 0,
3765
+ d: 1,
3766
+ e: 0,
3767
+ f: 0
3768
+ };
3769
+ const multiplied = (left, right) => ({
3770
+ a: left.a * right.a + left.c * right.b,
3771
+ b: left.b * right.a + left.d * right.b,
3772
+ c: left.a * right.c + left.c * right.d,
3773
+ d: left.b * right.c + left.d * right.d,
3774
+ e: left.a * right.e + left.c * right.f + left.e,
3775
+ f: left.b * right.e + left.d * right.f + left.f
3776
+ });
3777
+ /** The alpha of a layer's own fills stacked over each other, then its opacity. */
3778
+ const fillAlphaOf = (node) => {
3779
+ const { fills, opacity } = canvasAppearanceOf(node);
3780
+ return (1 - fills.filter((paint) => paint.visible).reduce((held, paint) => held * (1 - paint.opacity * (paint.kind === "solid" ? paint.color.alpha : 1)), 1)) * opacity;
3781
+ };
3782
+ const maskShapeOf = (operand, parent, opacity) => {
3783
+ const [a, b, c, d, e, f] = operand.matrix;
3784
+ const placed = multiplied(parent, {
3785
+ a,
3786
+ b,
3787
+ c,
3788
+ d,
3789
+ e,
3790
+ f
3791
+ });
3792
+ return {
3793
+ path: operand.path,
3794
+ fillRule: operand.fillRule,
3795
+ transform: `matrix(${[
3796
+ placed.a,
3797
+ placed.b,
3798
+ placed.c,
3799
+ placed.d,
3800
+ placed.e,
3801
+ placed.f
3802
+ ].map(String).join(" ")})`,
3803
+ opacity
3804
+ };
3805
+ };
3806
+ /**
3807
+ * The shapes of a group mask source, placed in the space of the source's parent, backmost first.
3808
+ * A frame counts as its own box and fill, then its children. Null when the source is no group.
3809
+ */
3810
+ const canvasGroupMaskShapesOf = (document, source) => {
3811
+ if (source.component !== "group" || source.geometry !== void 0) return null;
3812
+ const shapes = [];
3813
+ const visit = (node, parent, alpha) => {
3814
+ if (node.visible === false) return;
3815
+ const isGroup = node.component === "group" && node.geometry === void 0;
3816
+ const operand = isGroup ? null : canvasShapeOperandOf(node);
3817
+ if (operand !== null && typeof operand !== "string") shapes.push(maskShapeOf(operand, parent, alpha * fillAlphaOf(node)));
3818
+ if (!isGroup && node.component !== "frame") return;
3819
+ const local = canvasNodeLocalMatrixOf(node);
3820
+ if (local === null) return;
3821
+ const placed = multiplied(parent, local);
3822
+ const opacity = alpha * canvasAppearanceOf(node).opacity;
3823
+ for (const childId of childIdsOf(document.relationships, node.id)) {
3824
+ const child = document.nodes[childId];
3825
+ if (child !== void 0) visit(child, placed, opacity);
3826
+ }
3827
+ };
3828
+ visit(source, IDENTITY, 1);
3829
+ return shapes;
3830
+ };
3831
+ const HASH_SEED = 2166136261;
3832
+ const HASH_PRIME = 16777619;
3833
+ const HASH_RADIX = 16;
3834
+ const clipIdentity = (encoded) => {
3835
+ let hash = HASH_SEED;
3836
+ for (const character of encoded) hash = Math.imul(hash ^ (character.codePointAt(0) ?? 0), HASH_PRIME);
3837
+ return (hash >>> 0).toString(HASH_RADIX);
3838
+ };
3839
+ /**
3840
+ * Text that masks images and filled rectangles shows them in its letters, so the group needs no
3841
+ * clip. Over other content, text clips it to the text's box.
3842
+ */
3843
+ const textMaskClipOf = (document, source, box) => {
3844
+ if (canvasTextMaskContentsOf(document, source) !== null) return null;
3845
+ const text = source.box;
3846
+ if (text === void 0) return {
3847
+ path: "",
3848
+ fillRule: "nonzero",
3849
+ matrix: [
3850
+ 1,
3851
+ 0,
3852
+ 0,
3853
+ 1,
3854
+ 0,
3855
+ 0
3856
+ ]
3857
+ };
3858
+ const { width, height } = text;
3859
+ return {
3860
+ path: `M0 0H${String(width)}V${String(height)}H0Z`,
3861
+ fillRule: "nonzero",
3862
+ matrix: [
3863
+ 1 / box.width,
3864
+ 0,
3865
+ 0,
3866
+ 1 / box.height,
3867
+ text.x / box.width,
3868
+ text.y / box.height
3869
+ ]
3870
+ };
3871
+ };
3872
+ const clipPartsOf = (document, node, maskSource) => {
3873
+ const geometry = node.geometry;
3874
+ const box = node.box;
3875
+ if (geometry === void 0 || box === void 0 || box.width <= 0 || box.height <= 0) return null;
3876
+ if (geometry.kind === "path" || geometry.kind === "polygon") {
3877
+ const contour = canvasShapePathOf(node);
3878
+ if (typeof contour === "string") return null;
3879
+ const view = contour.viewBox;
3880
+ return {
3881
+ path: contour.path,
3882
+ fillRule: contour.fillRule,
3883
+ matrix: [
3884
+ 1 / view.width,
3885
+ 0,
3886
+ 0,
3887
+ 1 / view.height,
3888
+ -view.x / view.width,
3889
+ -view.y / view.height
3890
+ ]
3891
+ };
812
3892
  }
813
- children.splice(destination.index, 0, input.nodeId);
814
- state.children.set(destination.parentId, children);
815
- state.parentOf.set(input.nodeId, destination.parentId);
816
- state.affected.add(destination.parentId);
3893
+ if (geometry.kind === "boolean") {
3894
+ const contour = canvasShapePathOf(node);
3895
+ return {
3896
+ path: typeof contour === "string" ? "" : contour.path,
3897
+ fillRule: geometry.result.fillRule,
3898
+ matrix: [
3899
+ 1 / box.width,
3900
+ 0,
3901
+ 0,
3902
+ 1 / box.height,
3903
+ 0,
3904
+ 0
3905
+ ]
3906
+ };
3907
+ }
3908
+ const source = maskSource ?? canvasMaskSourceOf(document, node);
3909
+ if (source?.component === "text" && source.visible !== false) return textMaskClipOf(document, source, box);
3910
+ const shapes = source === void 0 || source.visible === false ? null : canvasGroupMaskShapesOf(document, source);
3911
+ if (shapes !== null) return {
3912
+ path: "",
3913
+ fillRule: "nonzero",
3914
+ matrix: [
3915
+ 1 / box.width,
3916
+ 0,
3917
+ 0,
3918
+ 1 / box.height,
3919
+ 0,
3920
+ 0
3921
+ ],
3922
+ shapes
3923
+ };
3924
+ const operand = source === void 0 || source.visible === false ? null : canvasShapeOperandOf(source);
3925
+ if (operand === null || typeof operand === "string") return {
3926
+ path: "",
3927
+ fillRule: "nonzero",
3928
+ matrix: [
3929
+ 1,
3930
+ 0,
3931
+ 0,
3932
+ 1,
3933
+ 0,
3934
+ 0
3935
+ ]
3936
+ };
3937
+ const [a, b, c, d, e, f] = operand.matrix;
817
3938
  return {
818
- operations,
819
- document: {
820
- ...state.document,
821
- relationships
822
- }
3939
+ path: operand.path,
3940
+ fillRule: operand.fillRule,
3941
+ matrix: [
3942
+ a / box.width,
3943
+ b / box.height,
3944
+ c / box.width,
3945
+ d / box.height,
3946
+ e / box.width,
3947
+ f / box.height
3948
+ ]
823
3949
  };
824
3950
  };
825
- const moveCanvasNodeOperations = (document, inputs) => {
826
- if (inputs.length === 0) throw new CliError("BAD_REQUEST", "No moves were provided.", "Pass at least one move operation.");
827
- const state = moveState(document);
828
- const moves = [];
3951
+ const canvasGeometryClipOf = (document, node, maskSource) => {
3952
+ const parts = clipPartsOf(document, node, maskSource);
3953
+ if (parts === null) return null;
3954
+ const { path, fillRule, matrix, shapes } = parts;
3955
+ const transform = `matrix(${matrix.map(String).join(" ")})`;
829
3956
  return {
830
- operations: inputs.flatMap((input) => {
831
- const destination = destinationFor(input, state);
832
- validateMove(input, destination, state);
833
- moves.push({
834
- nodeId: input.nodeId,
835
- ...destination
836
- });
837
- const applied = applyMove(input, destination, state);
838
- state.document = applied.document;
839
- return applied.operations;
840
- }),
841
- moves,
842
- affectedParents: Array.from(state.affected, (parentId) => ({
843
- parentId,
844
- children: [...state.children.get(parentId) ?? []]
845
- }))
3957
+ id: `canvas-geometry-${encodeURIComponent(node.id).replaceAll("%", "_")}-${clipIdentity(JSON.stringify([
3958
+ path,
3959
+ fillRule,
3960
+ transform,
3961
+ shapes
3962
+ ]))}`,
3963
+ path,
3964
+ fillRule,
3965
+ transform,
3966
+ matrix,
3967
+ ...shapes !== void 0 && { shapes }
846
3968
  };
847
3969
  };
848
3970
 
@@ -928,14 +4050,11 @@ const operationsForNode = (document, node, source) => {
928
4050
  else next.styles[property] = value;
929
4051
  const layout = layoutOperation(document, node, next, source);
930
4052
  const typography = canvasTypographyOperation(node, styles);
931
- const clearFill = (node.component === "text" ? ["color"] : [
932
- "background",
933
- "background-color",
934
- "background-image"
935
- ]).some((property) => Object.hasOwn(styles, property)) && node.appearance?.fills !== void 0 ? [{
4053
+ const replaced = canvasAppearanceOwnedBy(node, Object.keys(styles));
4054
+ const clearNative = replaced.length > 0 ? [{
936
4055
  op: "setAppearance",
937
4056
  nodeId: node.id,
938
- appearance: { clear: ["fills"] }
4057
+ appearance: { clear: [...replaced] }
939
4058
  }] : [];
940
4059
  return [
941
4060
  ...Object.keys(stylePatch).length > 0 ? [{
@@ -943,7 +4062,7 @@ const operationsForNode = (document, node, source) => {
943
4062
  nodeId: node.id,
944
4063
  styles: canvasNodeStylePatchSchema.parse(stylePatch)
945
4064
  }] : [],
946
- ...clearFill,
4065
+ ...clearNative,
947
4066
  ...typography === null ? [] : [typography],
948
4067
  ...layout === null ? [] : [layout],
949
4068
  ...additional === null ? [] : [additional]
@@ -1325,7 +4444,7 @@ const createEditCanvasComposite = (remote) => ({ execute: async (input) => {
1325
4444
  const parsed = applyCanvasOperationsInputSchema.safeParse({
1326
4445
  canvasId: input.canvasId,
1327
4446
  mutationId: input.mutationId,
1328
- documentFormatVersion: 11,
4447
+ documentFormatVersion: 13,
1329
4448
  baseVersion: input.baseVersion,
1330
4449
  operations: plan.operations
1331
4450
  });
@@ -2731,7 +5850,7 @@ const commitPreparation = async (remote, input, job, fingerprint) => {
2731
5850
  const request = applyCanvasOperationsInputSchema.parse({
2732
5851
  canvasId: job.canvasId,
2733
5852
  mutationId: input.clientToken,
2734
- documentFormatVersion: 11,
5853
+ documentFormatVersion: 13,
2735
5854
  baseVersion: input.baseVersion,
2736
5855
  operations: job.result.operations,
2737
5856
  requestContext: {
@@ -2788,81 +5907,288 @@ const createPrepareCanvasCommandComposite = (remote) => ({ execute: async (input
2788
5907
  } });
2789
5908
 
2790
5909
  //#endregion
2791
- //#region src/application/canvas-editable-html.use-case.ts
5910
+ //#region ../../packages/canvas-document/src/canvas-path-transform.lib.ts
5911
+ const COMMAND = /^[MLHVCSQTAZ]$/iu;
5912
+ const TOKENS = /[MLHVCSQTAZ]|[+-]?(?:\d+\.?\d*|\.\d+)(?:e[+-]?\d+)?/giu;
5913
+ const ARGUMENTS = {
5914
+ M: 2,
5915
+ L: 2,
5916
+ H: 1,
5917
+ V: 1,
5918
+ C: 6,
5919
+ S: 4,
5920
+ Q: 4,
5921
+ T: 2,
5922
+ A: 7,
5923
+ Z: 0
5924
+ };
5925
+ /** The path's commands with their arguments; a command's repeated arguments are new segments. */
5926
+ const segmentsOf = (path) => {
5927
+ const tokens = path.match(TOKENS) ?? [];
5928
+ if (tokens.join("") !== path.replaceAll(/[\s,]/gu, "")) return null;
5929
+ const segments = [];
5930
+ let command = "";
5931
+ let index = 0;
5932
+ while (index < tokens.length) {
5933
+ const token = tokens[index] ?? "";
5934
+ if (COMMAND.test(token)) {
5935
+ command = token;
5936
+ index += 1;
5937
+ } else if (command === "" || command.toUpperCase() === "Z") return null;
5938
+ const count = ARGUMENTS[command.toUpperCase()] ?? 0;
5939
+ const values = tokens.slice(index, index + count).map(Number);
5940
+ if (values.length !== count || values.some((value) => !Number.isFinite(value))) return null;
5941
+ index += count;
5942
+ segments.push({
5943
+ command,
5944
+ values
5945
+ });
5946
+ if (command.toUpperCase() === "M") command = command === "M" ? "L" : "l";
5947
+ }
5948
+ return segments;
5949
+ };
5950
+ const applied = ([a, b, c, d, e, f], { x, y }) => ({
5951
+ x: a * x + c * y + e,
5952
+ y: b * x + d * y + f
5953
+ });
5954
+ const format = (point) => `${String(point.x)} ${String(point.y)}`;
5955
+ const HALF_TURN_DEGREES = 180;
5956
+ const QUARTERS = 4;
5957
+ const CUBIC_POINTS = 3;
5958
+ const QUARTER_TURN = Math.PI / 2;
5959
+ const FULL_TURN = Math.PI * 2;
5960
+ /** Below this, an arc's last quarter is rounding, not a turn. */
5961
+ const TURN_TOLERANCE = 1e-9;
5962
+ const turnBetween = (ux, uy, vx, vy) => Math.atan2(ux * vy - uy * vx, ux * vx + uy * vy);
5963
+ /**
5964
+ * The ellipse an arc lies on, as the matrix that places the unit circle there, and the turn the
5965
+ * arc makes on it from its start angle (SVG 2, appendix B.2.4, with radii scaled up to reach).
5966
+ */
5967
+ const arcEllipseOf = (from, values, end) => {
5968
+ const [rx0 = 0, ry0 = 0, degrees = 0, large = 0, sweep = 0] = values;
5969
+ const phi = degrees * Math.PI / HALF_TURN_DEGREES;
5970
+ const [cos, sin] = [Math.cos(phi), Math.sin(phi)];
5971
+ const [dx, dy] = [(from.x - end.x) / 2, (from.y - end.y) / 2];
5972
+ const [x1, y1] = [cos * dx + sin * dy, -sin * dx + cos * dy];
5973
+ const reach = Math.max(1, Math.hypot(x1 / rx0, y1 / ry0));
5974
+ const [rx, ry] = [Math.abs(rx0) * reach, Math.abs(ry0) * reach];
5975
+ const spread = rx * rx * y1 * y1 + ry * ry * x1 * x1;
5976
+ const root = (large === sweep ? -1 : 1) * Math.sqrt(Math.max(0, (rx * rx * ry * ry - spread) / spread));
5977
+ const [cx, cy] = [root * rx * y1 / ry, -root * ry * x1 / rx];
5978
+ const [ux, uy, vx, vy] = [
5979
+ (x1 - cx) / rx,
5980
+ (y1 - cy) / ry,
5981
+ (-x1 - cx) / rx,
5982
+ (-y1 - cy) / ry
5983
+ ];
5984
+ let turn = turnBetween(ux, uy, vx, vy);
5985
+ if (sweep === 0 && turn > 0) turn -= FULL_TURN;
5986
+ if (sweep === 1 && turn < 0) turn += FULL_TURN;
5987
+ return {
5988
+ ellipse: [
5989
+ cos * rx,
5990
+ sin * rx,
5991
+ -sin * ry,
5992
+ cos * ry,
5993
+ cos * cx - sin * cy + (from.x + end.x) / 2,
5994
+ sin * cx + cos * cy + (from.y + end.y) / 2
5995
+ ],
5996
+ start: turnBetween(1, 0, ux, uy),
5997
+ turn
5998
+ };
5999
+ };
6000
+ /**
6001
+ * An arc as cubic curves of at most a quarter turn each, as SVG renderers draw it; each is within
6002
+ * 0.03% of the radius of the true arc, and a matrix places curves exactly.
6003
+ */
6004
+ const arcCurves = (from, values, end) => {
6005
+ const [rx = 0, ry = 0] = values;
6006
+ if (rx === 0 || ry === 0 || from.x === end.x && from.y === end.y) return [
6007
+ from,
6008
+ end,
6009
+ end
6010
+ ];
6011
+ const { ellipse, start, turn } = arcEllipseOf(from, values, end);
6012
+ const count = Math.ceil(Math.abs(turn) / QUARTER_TURN - TURN_TOLERANCE);
6013
+ const step = turn / count;
6014
+ const handle = QUARTERS / CUBIC_POINTS * Math.tan(step / QUARTERS);
6015
+ const unit = (theta, length) => ({
6016
+ x: Math.cos(theta) - Math.sin(theta) * length,
6017
+ y: Math.sin(theta) + Math.cos(theta) * length
6018
+ });
6019
+ const points = [];
6020
+ for (let index = 0; index < count; index += 1) {
6021
+ const [before, after] = [start + step * index, start + step * (index + 1)];
6022
+ points.push(applied(ellipse, unit(before, handle)), applied(ellipse, unit(after, -handle)), index === count - 1 ? end : applied(ellipse, unit(after, 0)));
6023
+ }
6024
+ return points;
6025
+ };
6026
+ /** One segment in absolute coordinates of the matrix's space, and where it leaves the pen. */
6027
+ const placed = (segment, pen, matrix) => {
6028
+ const upper = segment.command.toUpperCase();
6029
+ const isRelative = segment.command !== upper;
6030
+ const { current } = pen;
6031
+ const at = (x = 0, y = 0) => isRelative ? {
6032
+ x: current.x + x,
6033
+ y: current.y + y
6034
+ } : {
6035
+ x,
6036
+ y
6037
+ };
6038
+ const [first = 0] = segment.values;
6039
+ if (upper === "Z") return {
6040
+ data: "Z",
6041
+ pen: {
6042
+ ...pen,
6043
+ current: pen.start
6044
+ }
6045
+ };
6046
+ if (upper === "A") {
6047
+ const end = at(segment.values[5], segment.values[6]);
6048
+ const points = arcCurves(current, segment.values, end);
6049
+ const curves = [];
6050
+ for (let offset = 0; offset < points.length; offset += CUBIC_POINTS) curves.push(`C${points.slice(offset, offset + CUBIC_POINTS).map((point) => format(applied(matrix, point))).join(" ")}`);
6051
+ return {
6052
+ data: curves.join(""),
6053
+ pen: {
6054
+ ...pen,
6055
+ current: end
6056
+ }
6057
+ };
6058
+ }
6059
+ if (upper === "H" || upper === "V") {
6060
+ const end = upper === "H" ? at(first, isRelative ? 0 : current.y) : at(isRelative ? 0 : current.x, first);
6061
+ return {
6062
+ data: `L${format(applied(matrix, end))}`,
6063
+ pen: {
6064
+ ...pen,
6065
+ current: end
6066
+ }
6067
+ };
6068
+ }
6069
+ const points = [];
6070
+ for (let offset = 0; offset < segment.values.length; offset += 2) points.push(at(segment.values[offset], segment.values[offset + 1]));
6071
+ const end = points.at(-1) ?? current;
6072
+ return {
6073
+ data: `${upper}${points.map((point) => format(applied(matrix, point))).join(" ")}`,
6074
+ pen: {
6075
+ current: end,
6076
+ start: upper === "M" ? end : pen.start
6077
+ }
6078
+ };
6079
+ };
6080
+ /**
6081
+ * The path drawn in the matrix's space, with absolute coordinates and arcs as cubic curves. Null
6082
+ * when the path cannot be read.
6083
+ */
6084
+ const canvasPathTransformedBy = (path, matrix) => {
6085
+ const segments = segmentsOf(path);
6086
+ if (segments === null) return null;
6087
+ const parts = [];
6088
+ let pen = {
6089
+ current: {
6090
+ x: 0,
6091
+ y: 0
6092
+ },
6093
+ start: {
6094
+ x: 0,
6095
+ y: 0
6096
+ }
6097
+ };
6098
+ for (const segment of segments) {
6099
+ const next = placed(segment, pen, matrix);
6100
+ parts.push(next.data);
6101
+ pen = next.pen;
6102
+ }
6103
+ return parts.join("");
6104
+ };
6105
+
6106
+ //#endregion
6107
+ //#region ../../packages/canvas-document/src/canvas-mask-css.lib.ts
6108
+ /**
6109
+ * A mask group's own element takes the CSS mask, computed from its source each time it is drawn:
6110
+ * the source's visible fills, with its opacity folded in, become mask layers at its box. An
6111
+ * outline mask uses only the clip of the source's shape; a group with no kind is an alpha mask.
6112
+ */
6113
+ const canvasMaskLayerDeclarations = (node, source) => {
6114
+ const geometry = node.geometry;
6115
+ if (geometry?.kind !== "mask" || geometry.mode === "outline" || source?.box === void 0 || source.component === "text") return {};
6116
+ const opacity = canvasAppearanceOf(source).opacity;
6117
+ const layers = canvasAppearanceOf(source).fills.filter((paint) => paint.visible).toReversed().map((paint) => canvasPaintLayerCss({
6118
+ ...paint,
6119
+ opacity: paint.opacity * opacity
6120
+ }));
6121
+ if (layers.length === 0) return {};
6122
+ const { x, y, width, height } = source.box;
6123
+ const each = (value) => layers.map(() => value).join(", ");
6124
+ return {
6125
+ "mask-image": layers.join(", "),
6126
+ "mask-mode": each(geometry.mode === "luminance" ? "luminance" : "alpha"),
6127
+ "mask-position": each(`${String(x)}px ${String(y)}px`),
6128
+ "mask-size": each(`${String(width)}px ${String(height)}px`),
6129
+ "mask-repeat": each("no-repeat")
6130
+ };
6131
+ };
6132
+ /**
6133
+ * The clip a mask group's element takes from its source's shape, written as a CSS path in the
6134
+ * group's own pixels: the editor draws the same contour through an SVG clip. A group of shapes
6135
+ * keeps each shape's alpha, which a CSS clip cannot, so it has none here; nor has text that shows
6136
+ * the content in its letters. Null when the shape cannot be written as a CSS path.
6137
+ */
6138
+ const canvasMaskClipDeclarations = (document, node) => {
6139
+ const clip = node.geometry?.kind === "mask" ? canvasGeometryClipOf(document, node) : null;
6140
+ const box = node.box;
6141
+ if (box === void 0 || clip === null || clip.shapes !== void 0) return {};
6142
+ if (clip.path === "") return { "clip-path": "inset(50%)" };
6143
+ const [a, b, c, d, e, f] = clip.matrix;
6144
+ const path = canvasPathTransformedBy(clip.path, [
6145
+ a * box.width,
6146
+ b * box.height,
6147
+ c * box.width,
6148
+ d * box.height,
6149
+ e * box.width,
6150
+ f * box.height
6151
+ ]);
6152
+ return path === null ? null : { "clip-path": `path(${clip.fillRule}, "${path}")` };
6153
+ };
6154
+
6155
+ //#endregion
6156
+ //#region src/application/canvas-editable-html-source.use-case.ts
2792
6157
  const ATTRIBUTES = /* @__PURE__ */ new Set([
2793
6158
  "data-enhance-id",
6159
+ "data-enhance-locked",
2794
6160
  "data-enhance-name",
2795
6161
  "data-enhance-opaque",
2796
6162
  "style"
2797
6163
  ]);
2798
- const fail = (message) => {
6164
+ const fail$1 = (message) => {
2799
6165
  throw new CliError("BAD_REQUEST", message, "Use a complete current editable read and preserve its identity and opaque markers.");
2800
6166
  };
2801
- const escape = (value) => value.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;").replaceAll("\"", "&quot;");
6167
+ /** An inline declaration list as one value per property, refusing what CSS cannot hold. */
2802
6168
  const styleValues = (source) => {
2803
6169
  const ast = parse(source, {
2804
6170
  context: "declarationList",
2805
- onParseError: (error) => fail(error.message)
6171
+ onParseError: (error) => fail$1(error.message)
2806
6172
  });
2807
- if (ast.type !== "DeclarationList") return fail("Expected an inline CSS declaration list.");
6173
+ if (ast.type !== "DeclarationList") return fail$1("Expected an inline CSS declaration list.");
2808
6174
  const styles = /* @__PURE__ */ new Map();
2809
6175
  ast.children.forEach((declaration) => {
2810
- if (declaration.type !== "Declaration" || declaration.important !== false) return fail("Use ordinary inline CSS properties without !important or at-rules.");
6176
+ if (declaration.type !== "Declaration" || declaration.important !== false) return fail$1("Use ordinary inline CSS properties without !important or at-rules.");
2811
6177
  const property = declaration.property.startsWith("--") ? declaration.property : declaration.property.toLowerCase();
2812
- if (styles.has(property)) return fail(`Duplicate CSS property: ${property}.`);
6178
+ if (styles.has(property)) return fail$1(`Duplicate CSS property: ${property}.`);
2813
6179
  styles.set(property, generate(declaration.value));
2814
6180
  });
2815
6181
  return Object.fromEntries(styles);
2816
6182
  };
2817
- const serialize$1 = (node) => {
2818
- const style = Object.entries(node.styles).toSorted(([left], [right]) => left.localeCompare(right)).map(([key, value]) => `${key}:${value}`).join(";");
2819
- const attrs = `data-enhance-id="${escape(node.id)}" data-enhance-name="${escape(node.label)}"${node.opaque ? " data-enhance-opaque=\"true\"" : ""}${style === "" ? "" : ` style="${escape(style)}"`}`;
2820
- return `<${node.tag} ${attrs}>${escape(node.text)}${node.children.map((child) => serialize$1(child)).join("")}</${node.tag}>`;
2821
- };
2822
- const projectCanvasEditableHtml = (document, rootNodeId) => {
2823
- const seen = /* @__PURE__ */ new Set();
2824
- const opaqueNodeIds = [];
2825
- const childrenByParent = canvasChildrenByParent(document);
2826
- const visit = (nodeId) => {
2827
- if (seen.has(nodeId)) return fail("The document contains repeated node identity.");
2828
- seen.add(nodeId);
2829
- const node = requireCanvasNode(document, nodeId);
2830
- const children = childrenByParent.get(nodeId) ?? [];
2831
- const isOpaque = isCanvasNodeLocked(document, nodeId) || node.component === "text" && children.length > 0 || ![
2832
- "root",
2833
- "frame",
2834
- "group",
2835
- "text"
2836
- ].includes(node.component);
2837
- if (isOpaque) opaqueNodeIds.push(node.id);
2838
- const styles = isOpaque ? {} : styleValues(Object.entries(canvasAuthoredStyleDeclarations(node)).map(([property, value]) => `${property}:${canvasCssValue(property, value)}`).join(";"));
2839
- return {
2840
- id: node.id,
2841
- tag: node.component === "text" ? "span" : "div",
2842
- label: node.label,
2843
- opaque: isOpaque,
2844
- styles,
2845
- text: isOpaque || node.component !== "text" ? "" : textOf(node) ?? "",
2846
- children: isOpaque ? [] : children.map((id) => visit(id))
2847
- };
2848
- };
2849
- const root = visit(rootNodeId);
2850
- return {
2851
- projectionVersion: 1,
2852
- root,
2853
- html: serialize$1(root),
2854
- opaqueNodeIds
2855
- };
2856
- };
2857
6183
  const elements = (children) => children.flatMap((child) => {
2858
6184
  if ("tagName" in child) return [child];
2859
6185
  if (child.nodeName === "#text" && "value" in child && child.value.trim() === "") return [];
2860
- return fail("Container content must contain identified elements; text belongs inside its retained span.");
6186
+ return fail$1("Container content must contain identified elements; text belongs inside its retained span.");
2861
6187
  });
2862
6188
  const canvasEditableHtmlFragment = (html) => {
2863
6189
  const fragment = parseFragment(html, {
2864
6190
  sourceCodeLocationInfo: true,
2865
- onParseError: (error) => fail(`Invalid HTML at line ${String(error.startLine)}: ${error.code}.`)
6191
+ onParseError: (error) => fail$1(`Invalid HTML at line ${String(error.startLine)}: ${error.code}.`)
2866
6192
  });
2867
6193
  const pending = [fragment];
2868
6194
  while (pending.length > 0) {
@@ -2877,42 +6203,623 @@ const canvasEditableHtmlFragment = (html) => {
2877
6203
  }
2878
6204
  return fragment;
2879
6205
  };
6206
+ const SVG_ATTRIBUTES = /* @__PURE__ */ new Set([
6207
+ ...ATTRIBUTES,
6208
+ "viewBox",
6209
+ "preserveAspectRatio"
6210
+ ]);
6211
+ /** A vector element holds exactly one path. */
6212
+ const parsedPath = (element, viewBox) => {
6213
+ const [path, ...rest] = elements(element.childNodes);
6214
+ if (path?.tagName !== "path" || rest.length > 0) return fail$1("A vector element must hold exactly one path.");
6215
+ const value = (name) => path.attrs.find((attribute) => attribute.name === name)?.value;
6216
+ const fillRule = value("fill-rule") ?? "nonzero";
6217
+ if (fillRule !== "nonzero" && fillRule !== "evenodd") return fail$1(`Unsupported fill-rule: ${fillRule}.`);
6218
+ return {
6219
+ d: value("d") ?? "",
6220
+ fillRule,
6221
+ fill: value("fill") ?? "none",
6222
+ viewBox
6223
+ };
6224
+ };
6225
+ /** An element's attributes, refusing any the agent's HTML does not carry. */
6226
+ const attributesOf = (element) => {
6227
+ const allowed = element.tagName === "svg" ? SVG_ATTRIBUTES : ATTRIBUTES;
6228
+ return Object.fromEntries(element.attrs.map((attr) => {
6229
+ if (!allowed.has(attr.name) || attr.namespace !== void 0) return fail$1(`Unsupported attribute: ${attr.name}.`);
6230
+ return [attr.name, attr.value];
6231
+ }));
6232
+ };
6233
+ /** The identity, name and markers every retained element carries. */
6234
+ const retainedOf = (attrs) => {
6235
+ const id = attrs["data-enhance-id"];
6236
+ const label = attrs["data-enhance-name"];
6237
+ if (id === void 0 || id === "" || label === void 0) return fail$1("Every retained element requires its identity and name.");
6238
+ const marker = attrs["data-enhance-opaque"];
6239
+ if (marker !== void 0 && marker !== "true") return fail$1(`Invalid opaque marker on ${id}.`);
6240
+ const locked = attrs["data-enhance-locked"];
6241
+ if (locked !== void 0 && locked !== "true") return fail$1(`Invalid locked marker on ${id}.`);
6242
+ return {
6243
+ id,
6244
+ label,
6245
+ opaque: marker === "true",
6246
+ locked: locked === "true",
6247
+ styles: styleValues(attrs["style"] ?? "")
6248
+ };
6249
+ };
6250
+ /** A layer's paint elements, which are no layers, apart from its retained children. */
6251
+ const paintsAndChildren = (element) => {
6252
+ const paints = [];
6253
+ const children = [];
6254
+ for (const child of elements(element.childNodes)) {
6255
+ const owner = child.attrs.find((attribute) => attribute.name === "data-enhance-paint")?.value;
6256
+ if (owner === void 0) {
6257
+ children.push(child);
6258
+ continue;
6259
+ }
6260
+ const style = child.attrs.find((attribute) => attribute.name === "style")?.value ?? "";
6261
+ paints.push(owner === "border" || owner === "outline" ? {
6262
+ owner,
6263
+ styles: styleValues(style)
6264
+ } : {
6265
+ owner: "paint",
6266
+ paintId: owner,
6267
+ styles: styleValues(style)
6268
+ });
6269
+ }
6270
+ return [paints, children];
6271
+ };
6272
+ /** A rich text layer's run spans, each marked with its place among the runs. */
6273
+ const runsOfSpan = (element, id) => elements(element.childNodes).map((run, index) => {
6274
+ const place = run.attrs.find((attribute) => attribute.name === "data-enhance-run")?.value;
6275
+ if (run.tagName !== "span" || place !== String(index)) return fail$1(`Text ${id} holds run spans only, each with its data-enhance-run place.`);
6276
+ const style = run.attrs.find((attribute) => attribute.name === "style")?.value ?? "";
6277
+ return {
6278
+ text: textOfSpan(run, id),
6279
+ styles: styleValues(style)
6280
+ };
6281
+ });
6282
+ const textOfSpan = (element, id) => element.childNodes.map((child) => {
6283
+ if ("value" in child) return child.value;
6284
+ return fail$1(`Retained text ${id} must contain text only; its existing rich formatting is preserved by the text owner.`);
6285
+ }).join("");
2880
6286
  const parseCanvasEditableHtml = (html) => {
2881
6287
  const fragment = canvasEditableHtmlFragment(html);
2882
6288
  const seen = /* @__PURE__ */ new Set();
2883
6289
  const visit = (element) => {
2884
- if (element.tagName !== "div" && element.tagName !== "span") return fail(`Unsupported retained element: ${element.tagName}.`);
2885
- const attrs = Object.fromEntries(element.attrs.map((attr) => {
2886
- if (!ATTRIBUTES.has(attr.name) || attr.namespace !== void 0) return fail(`Unsupported attribute: ${attr.name}.`);
2887
- return [attr.name, attr.value];
2888
- }));
2889
- const id = attrs["data-enhance-id"];
2890
- const label = attrs["data-enhance-name"];
2891
- if (id === void 0 || id === "" || label === void 0) return fail("Every retained element requires its identity and name.");
2892
- if (seen.has(id)) return fail(`Duplicate node identity: ${id}.`);
2893
- seen.add(id);
2894
- const marker = attrs["data-enhance-opaque"];
2895
- if (marker !== void 0 && marker !== "true") return fail(`Invalid opaque marker on ${id}.`);
2896
- const text = element.tagName === "span" ? element.childNodes.map((child) => {
2897
- if ("value" in child) return child.value;
2898
- return fail(`Retained text ${id} must contain text only; its existing rich formatting is preserved by the text owner.`);
2899
- }).join("") : "";
6290
+ if (element.tagName !== "div" && element.tagName !== "span" && element.tagName !== "svg") return fail$1(`Unsupported retained element: ${element.tagName}.`);
6291
+ const attrs = attributesOf(element);
6292
+ const retained = retainedOf(attrs);
6293
+ if (seen.has(retained.id)) return fail$1(`Duplicate node identity: ${retained.id}.`);
6294
+ seen.add(retained.id);
6295
+ if (element.tagName === "svg") return {
6296
+ ...retained,
6297
+ tag: "svg",
6298
+ path: parsedPath(element, attrs["viewBox"] ?? ""),
6299
+ text: "",
6300
+ children: []
6301
+ };
6302
+ const hasRuns = element.tagName === "span" && element.childNodes.some((child) => "tagName" in child);
6303
+ const [paints, children] = element.tagName === "span" ? [[], []] : paintsAndChildren(element);
2900
6304
  return {
2901
- id,
6305
+ ...retained,
2902
6306
  tag: element.tagName,
2903
- label,
2904
- opaque: marker === "true",
2905
- text,
2906
- styles: styleValues(attrs["style"] ?? ""),
2907
- children: element.tagName === "span" ? [] : elements(element.childNodes).map((child) => visit(child))
6307
+ ...hasRuns && { runs: runsOfSpan(element, retained.id) },
6308
+ ...paints.length > 0 && { paints },
6309
+ text: !hasRuns && element.tagName === "span" ? textOfSpan(element, retained.id) : "",
6310
+ children: children.map((child) => visit(child))
2908
6311
  };
2909
6312
  };
2910
6313
  const roots = elements(fragment.childNodes);
2911
6314
  const root = roots[0];
2912
- if (root === void 0 || roots.length !== 1) return fail("An editable update must contain exactly its original root.");
6315
+ if (root === void 0 || roots.length !== 1) return fail$1("An editable update must contain exactly its original root.");
2913
6316
  return visit(root);
2914
6317
  };
2915
6318
 
6319
+ //#endregion
6320
+ //#region src/application/canvas-editable-image.use-case.ts
6321
+ const invalid$6 = (message) => {
6322
+ throw new CliError("BAD_REQUEST", message, "Read the current editable subtree and apply only the intended change. No changes were committed.");
6323
+ };
6324
+ /** An image's fit as a background size; scale-down reads as contain, which it is for large images. */
6325
+ const SIZE_OF_FIT = {
6326
+ fill: "100% 100%",
6327
+ cover: "cover",
6328
+ contain: "contain",
6329
+ "scale-down": "contain",
6330
+ none: "auto"
6331
+ };
6332
+ const FIT_OF_SIZE = {
6333
+ "100% 100%": "fill",
6334
+ cover: "cover",
6335
+ contain: "contain",
6336
+ auto: "none"
6337
+ };
6338
+ const IMAGE_PROPERTY = /^background(?:-.+)?$/u;
6339
+ const URL$1 = /^url\((?:"([^"]*)"|'([^']*)'|([^"'()\s]*))\)$/u;
6340
+ /** A native image: one with its own source rather than fills. */
6341
+ const nativeSourceOf = (node) => {
6342
+ if (node.component !== "image") return void 0;
6343
+ const source = node.props?.["src"];
6344
+ return typeof source === "string" && source !== "" ? source : void 0;
6345
+ };
6346
+ /** A native image's CSS: its source painted once as the element's background. */
6347
+ const canvasEditableImageDeclarations = (node) => {
6348
+ const source = nativeSourceOf(node);
6349
+ if (source === void 0) return {};
6350
+ const fit = node.props?.["fit"];
6351
+ const position = node.props?.["position"];
6352
+ return {
6353
+ "background-image": `url(${JSON.stringify(source)})`,
6354
+ "background-size": SIZE_OF_FIT[typeof fit === "string" ? fit : "fill"] ?? "100% 100%",
6355
+ "background-position": typeof position === "string" ? position : "50% 50%",
6356
+ "background-repeat": "no-repeat"
6357
+ };
6358
+ };
6359
+ /** Whether the property belongs to a native image's own source, not to its CSS. */
6360
+ const isCanvasEditableImageProperty = (node, property) => nativeSourceOf(node) !== void 0 && IMAGE_PROPERTY.test(property);
6361
+ /** A written background on a native image sets its source, fit and position. */
6362
+ const canvasEditableImageOperations = (node, before, after) => {
6363
+ if (nativeSourceOf(node) === void 0) return [];
6364
+ const changed = [.../* @__PURE__ */ new Set([...Object.keys(before), ...Object.keys(after)])].filter((property) => IMAGE_PROPERTY.test(property) && before[property] !== after[property]);
6365
+ if (changed.length === 0) return [];
6366
+ if (changed.some((property) => ![
6367
+ "background-image",
6368
+ "background-size",
6369
+ "background-position"
6370
+ ].includes(property))) return invalid$6(`An image paints once from its source on ${node.id}; change only its background-image URL, background-size (100% 100%, cover, contain or auto) and background-position.`);
6371
+ const url = URL$1.exec(after["background-image"] ?? "");
6372
+ const source = url?.[1] ?? url?.[2] ?? url?.[3];
6373
+ const fit = FIT_OF_SIZE[after["background-size"] ?? ""];
6374
+ const position = after["background-position"];
6375
+ if (source === void 0 || source === "" || fit === void 0 || position === void 0) return invalid$6(`An image on ${node.id} needs a background-image URL, a background-size of 100% 100%, cover, contain or auto, and a background-position.`);
6376
+ return [{
6377
+ op: "setProps",
6378
+ nodeId: node.id,
6379
+ props: {
6380
+ ...node.props,
6381
+ ...changed.includes("background-image") && { src: source },
6382
+ ...changed.includes("background-size") && { fit },
6383
+ ...changed.includes("background-position") && { position }
6384
+ }
6385
+ }];
6386
+ };
6387
+
6388
+ //#endregion
6389
+ //#region src/application/canvas-editable-paint.use-case.ts
6390
+ const invalid$5 = (message) => {
6391
+ throw new CliError("BAD_REQUEST", message, "Read the current editable subtree and apply only the intended change. No changes were committed.");
6392
+ };
6393
+ /** The layer CSS a paint element takes over, and so leaves out of the layer's own read. */
6394
+ const TAKEN_OVER = {
6395
+ border: /^border(?:-(?:top|right|bottom|left))?(?:-(?:width|style|color))?$|^border-(?:width|style|color)$/u,
6396
+ outline: /^outline(?:-.+)?$/u,
6397
+ paint: /^$/u
6398
+ };
6399
+ /** In the order the HTML writes them, so a read compares equal to its own write-back. */
6400
+ const sortedStyles = (source) => Object.fromEntries(Object.entries(styleValues(source)).toSorted(([left], [right]) => left.localeCompare(right)));
6401
+ /** The paint element's CSS, written as the parser reads it back, without editor resources. */
6402
+ const readable = (styles) => sortedStyles(Object.entries(styles).flatMap(([property, value]) => {
6403
+ const css = canvasCssValue(property, value);
6404
+ return property.startsWith("--") || css.includes("var(--canvas") || css.includes("url(#") ? [] : [`${property}:${css}`];
6405
+ }).join(";"));
6406
+ /**
6407
+ * The layer's paint elements as the agent reads them, in the order they paint: its shadow and fill
6408
+ * elements with their paint's identity, then the border's and the outline's.
6409
+ */
6410
+ const canvasEditablePaints = (node) => {
6411
+ const plan = canvasPaintElementPlanOf(node);
6412
+ const shadow = (kind) => canvasShadowElementsOf(plan, kind).map((held) => ({
6413
+ owner: "paint",
6414
+ paintId: held.id,
6415
+ styles: readable(canvasShadowPaintDeclarations(node, held))
6416
+ }));
6417
+ const border = canvasBoxStrokeDeclarations(node);
6418
+ const outline = canvasOutlinePaintDeclarations(node);
6419
+ return [
6420
+ ...shadow("outer-shadow"),
6421
+ ...canvasFillElementsOf(plan).map((paint) => ({
6422
+ owner: "paint",
6423
+ paintId: paint.id,
6424
+ styles: readable(canvasFillPaintDeclarations(paint))
6425
+ })),
6426
+ ...shadow("inner-shadow"),
6427
+ ...border === null ? [] : [{
6428
+ owner: "border",
6429
+ styles: readable(border)
6430
+ }],
6431
+ ...outline === null ? [] : [{
6432
+ owner: "outline",
6433
+ styles: readable(outline)
6434
+ }]
6435
+ ];
6436
+ };
6437
+ /** Whether the layer's own read leaves a property to one of its paint elements. */
6438
+ const isCanvasPaintElementProperty = (paints, property) => paints.some((paint) => TAKEN_OVER[paint.owner].test(property));
6439
+ const blendOf = (value) => {
6440
+ return CANVAS_BLEND_MODES.find((held) => held === (value ?? "normal")) ?? invalid$5(`Unsupported mix-blend-mode: ${value ?? ""}.`);
6441
+ };
6442
+ const DASH_ATTRIBUTES = /stroke-(?:dasharray|linecap)="[^"]*"/gu;
6443
+ /** The dash mask's SVG, decoded from its data URL, with or without quotes around it. */
6444
+ const dashMaskSvg = (value) => {
6445
+ const data = /^url\(["']?data:image\/svg\+xml,(.*?)["']?\)$/u.exec(value ?? "")?.[1];
6446
+ return data === void 0 ? void 0 : decodeURIComponent(data);
6447
+ };
6448
+ /** A changed dash mask sets the stroke's dash pattern and cap; nothing else of it can change. */
6449
+ const dashOf = (node, held, written) => {
6450
+ const before = dashMaskSvg(held);
6451
+ const after = dashMaskSvg(written);
6452
+ if (after === void 0 || before?.replaceAll(DASH_ATTRIBUTES, "") !== after.replaceAll(DASH_ATTRIBUTES, "")) return invalid$5(`Only stroke-dasharray and stroke-linecap of the dash mask can change on ${node.id}.`);
6453
+ const pattern = (/stroke-dasharray="([^"]*)"/u.exec(after)?.[1] ?? "").split(/[\s,]+/u).filter((length) => length !== "").map(Number);
6454
+ if (pattern.length === 0 || pattern.some((length) => !Number.isFinite(length) || length < 0)) return invalid$5(`A dash pattern is one or more lengths of 0 or more, on ${node.id}.`);
6455
+ const cap = /stroke-linecap="([^"]*)"/u.exec(after)?.[1];
6456
+ if (cap !== "butt" && cap !== "round" && cap !== "square") return invalid$5(`A dash cap is butt, round or square, on ${node.id}.`);
6457
+ return {
6458
+ dashPattern: pattern,
6459
+ dashCap: cap === "butt" ? "none" : cap
6460
+ };
6461
+ };
6462
+ /** The one visible paint of the stroke takes the written blend. */
6463
+ const blendedPaints = (node, owner, stroke, written) => {
6464
+ const visible = stroke.paints.filter((paint) => paint.visible);
6465
+ const [only] = visible;
6466
+ if (only === void 0 || visible.length !== 1) return invalid$5(`Set a blend on one paint of the ${owner} of ${node.id} in the editor.`);
6467
+ const blendMode = blendOf(written);
6468
+ return stroke.paints.map((paint) => paint === only ? {
6469
+ ...paint,
6470
+ blendMode
6471
+ } : paint);
6472
+ };
6473
+ /** Written fill and shadow elements set the modes of their paints only, in one write each. */
6474
+ const paintBlendOperations = (node, modes) => {
6475
+ if (modes.size === 0) return [];
6476
+ const fills = node.appearance?.fills ?? [];
6477
+ const shadows = node.appearance?.shadows ?? [];
6478
+ for (const id of modes.keys()) if (fills.every((paint) => paint.id !== id) && shadows.every((shadow) => shadow.id !== id)) return invalid$5(`${node.id} has no fill or shadow ${id}.`);
6479
+ const blended = (items) => items.map((item) => modes.has(item.id) ? {
6480
+ ...item,
6481
+ blendMode: blendOf(modes.get(item.id))
6482
+ } : item);
6483
+ return [...fills.some((paint) => modes.has(paint.id)) ? [{
6484
+ op: "setAppearance",
6485
+ nodeId: node.id,
6486
+ appearance: { fills: blended(fills) }
6487
+ }] : [], ...shadows.some((shadow) => modes.has(shadow.id)) ? [{
6488
+ op: "setAppearance",
6489
+ nodeId: node.id,
6490
+ appearance: { shadows: blended(shadows) }
6491
+ }] : []];
6492
+ };
6493
+ /**
6494
+ * A written paint element changes only its paint: its blend is the paint's blend, and its dash
6495
+ * mask is the stroke's dash pattern and cap. The rest of it follows the border or outline, which
6496
+ * the agent changes on the layer.
6497
+ */
6498
+ const canvasEditablePaintOperations = (node, before, after) => {
6499
+ const identities = (paints) => JSON.stringify(paints.map((paint) => paint.paintId ?? paint.owner));
6500
+ const unknown = after.find((paint) => paint.paintId !== void 0 && before.every((held) => held.paintId !== paint.paintId));
6501
+ if (unknown?.paintId !== void 0) return invalid$5(`${node.id} has no fill or shadow ${unknown.paintId}.`);
6502
+ if (identities(before) !== identities(after)) return invalid$5(`Keep each paint element of ${node.id}.`);
6503
+ const modes = /* @__PURE__ */ new Map();
6504
+ return [...after.flatMap((written, index) => {
6505
+ const held = before[index];
6506
+ if (held === void 0 || JSON.stringify(held.styles) === JSON.stringify(written.styles)) return [];
6507
+ const changed = [.../* @__PURE__ */ new Set([...Object.keys(held.styles), ...Object.keys(written.styles)])].filter((key) => held.styles[key] !== written.styles[key]);
6508
+ if (written.owner === "paint" && written.paintId !== void 0) {
6509
+ if (changed.some((key) => key !== "mix-blend-mode")) return invalid$5(`The paint element ${written.paintId} of ${node.id} follows its paint, so only its mix-blend-mode can change there; change ${changed.join(", ")} through the appearance operation.`);
6510
+ modes.set(written.paintId, written.styles["mix-blend-mode"]);
6511
+ return [];
6512
+ }
6513
+ if (changed.some((key) => key !== "mix-blend-mode" && key !== "mask-image")) return invalid$5(`The ${written.owner}'s paint element of ${node.id} follows its ${written.owner}, so ${changed.join(", ")} cannot change there; change the ${written.owner} CSS on the layer, or the paint element's mix-blend-mode or dash mask.`);
6514
+ const owner = written.owner === "outline" ? "outline" : "border";
6515
+ const stroke = node.appearance?.[owner];
6516
+ if (stroke === void 0) return invalid$5(`The ${owner} of ${node.id} has no paint element to write.`);
6517
+ const paints = changed.includes("mix-blend-mode") ? blendedPaints(node, owner, stroke, written.styles["mix-blend-mode"]) : stroke.paints;
6518
+ const dash = changed.includes("mask-image") ? dashOf(node, held.styles["mask-image"], written.styles["mask-image"]) : {};
6519
+ return [{
6520
+ op: "setAppearance",
6521
+ nodeId: node.id,
6522
+ appearance: { [owner]: {
6523
+ ...stroke,
6524
+ paints,
6525
+ ...dash
6526
+ } }
6527
+ }];
6528
+ }), ...paintBlendOperations(node, modes)];
6529
+ };
6530
+
6531
+ //#endregion
6532
+ //#region src/application/canvas-editable-text.use-case.ts
6533
+ const TEXT_BLEND_REASON = "Text paints have no blend of their own. Set mix-blend-mode on the text layer.";
6534
+ const invalid$4 = (message) => {
6535
+ throw new CliError("BAD_REQUEST", message, "Read the current editable subtree and apply only the intended change. No changes were committed.");
6536
+ };
6537
+ /** A flat run: plain text, or one span of plain text with its own formatting. */
6538
+ const isFlatRun = (run) => run.kind === "text" || run.kind === "span" && run.children.every((child) => child.kind === "text");
6539
+ const runTextOf = (run) => canvasRichTextValueOf([run]);
6540
+ /** Run formatting is stored by its script name; the agent reads and writes its CSS name. */
6541
+ const cssPropertyOf = (property) => property.replaceAll(/[A-Z]/gu, (letter) => `-${letter.toLowerCase()}`);
6542
+ const storedPropertyOf = (property) => property.replaceAll(/-([a-z])/gu, (_match, letter) => letter.toUpperCase());
6543
+ const storedStylesOf = (written, index) => Object.fromEntries(Object.entries(written).map(([property, value]) => {
6544
+ const stored = storedPropertyOf(property);
6545
+ return CANVAS_RICH_TEXT_STYLE_PROPERTIES.has(stored) ? [stored, value] : invalid$4(`Run ${String(index + 1)} cannot hold ${property}; set it on the text layer.`);
6546
+ }));
6547
+ const runStylesOf = (run) => {
6548
+ if (run.kind !== "span") return {};
6549
+ const [fill, ...others] = (run.fills ?? []).filter((paint) => paint.visible);
6550
+ const color = fill === void 0 || others.length > 0 ? void 0 : canvasSolidPaintColor(fill);
6551
+ const declarations = [...Object.entries(run.styles).map(([property, value]) => {
6552
+ const css = cssPropertyOf(property);
6553
+ return `${css}:${canvasCssValue(css, value)}`;
6554
+ }), ...color === void 0 ? [] : [`color:${color}`]];
6555
+ return Object.fromEntries(Object.entries(styleValues(declarations.join(";"))).toSorted(([left], [right]) => left.localeCompare(right)));
6556
+ };
6557
+ /**
6558
+ * A rich text layer's runs as the agent reads them, one span each, or null when its text is plain
6559
+ * or its runs nest. A plain text layer is one span of text, as before.
6560
+ */
6561
+ const canvasEditableTextRuns = (node) => {
6562
+ const runs = canvasRichTextOf(node);
6563
+ if (runs.length === 0 || runs.some((run) => !isFlatRun(run))) return null;
6564
+ return runs.map((run) => ({
6565
+ text: runTextOf(run),
6566
+ styles: runStylesOf(run)
6567
+ }));
6568
+ };
6569
+ /** Whether the layer's rich text is something the agent's run spans cannot hold. */
6570
+ const hasCanvasNestedTextRuns = (node) => {
6571
+ return canvasRichTextOf(node).some((run) => !isFlatRun(run));
6572
+ };
6573
+ const writtenRun = (node, index, run, written) => {
6574
+ if ("mix-blend-mode" in written.styles) return invalid$4(TEXT_BLEND_REASON);
6575
+ const { color, ...writtenStyles } = written.styles;
6576
+ const styles = storedStylesOf(writtenStyles, index);
6577
+ const paint = color === void 0 ? void 0 : solidCanvasPaintFromCss(`${node.id}-run-${String(index)}`, color);
6578
+ if (color !== void 0 && paint === null) return invalid$4(`The color of run ${String(index + 1)} is not a colour.`);
6579
+ const { fills: held, ...rest } = run.kind === "span" ? run : {
6580
+ kind: "span",
6581
+ styles: {},
6582
+ children: []
6583
+ };
6584
+ const isUnshown = held !== void 0 && runStylesOf(run)["color"] === void 0;
6585
+ const fills = paint === void 0 || paint === null ? isUnshown ? held : void 0 : [paint];
6586
+ return {
6587
+ ...rest,
6588
+ styles,
6589
+ ...fills !== void 0 && { fills },
6590
+ children: [{
6591
+ kind: "text",
6592
+ text: written.text
6593
+ }]
6594
+ };
6595
+ };
6596
+ /** A written run span changes only that run: its words, its colour and its CSS. */
6597
+ const canvasEditableTextOperations = (node, before, after) => {
6598
+ if (before.length !== after.length) return invalid$4(`Keep each run span of ${node.id}; change a run's words or CSS in place.`);
6599
+ const runs = canvasRichTextOf(node);
6600
+ const next = runs.map((run, index) => {
6601
+ const was = before[index];
6602
+ const now = after[index];
6603
+ if (was === void 0 || now === void 0) return run;
6604
+ return JSON.stringify(was) === JSON.stringify(now) ? run : writtenRun(node, index, run, now);
6605
+ });
6606
+ if (next.every((run, index) => run === runs[index])) return [];
6607
+ const props = {
6608
+ ...node.props,
6609
+ richText: next,
6610
+ text: canvasRichTextValueOf(next)
6611
+ };
6612
+ return [{
6613
+ op: "editText",
6614
+ nodeId: node.id,
6615
+ change: canvasTextChangeBetween(node, {
6616
+ ...node,
6617
+ props
6618
+ })
6619
+ }];
6620
+ };
6621
+
6622
+ //#endregion
6623
+ //#region src/application/canvas-editable-vector.use-case.ts
6624
+ const VECTOR_GEOMETRY = /* @__PURE__ */ new Set([
6625
+ "path",
6626
+ "polygon",
6627
+ "boolean"
6628
+ ]);
6629
+ const PAINT_REASON = "A vector with a gradient, image or blended fill keeps its paint in the editor.";
6630
+ /** Vectors, polygons, stars and Boolean groups are one inline SVG path in the agent's HTML. */
6631
+ const isCanvasEditableVector = (node) => VECTOR_GEOMETRY.has(node.geometry?.kind ?? "");
6632
+ /**
6633
+ * Why a vector cannot be read as one path with one solid fill, or null when it can. A blended fill
6634
+ * has no plain colour, so the path's fill could only show it wrong.
6635
+ */
6636
+ const canvasVectorSealedReason = (node) => {
6637
+ const fills = (node.appearance?.fills ?? []).filter((paint) => paint.visible);
6638
+ return fills.length > 1 || fills.some((paint) => paint.kind !== "solid" || (paint.blendMode ?? "normal") !== "normal") ? PAINT_REASON : null;
6639
+ };
6640
+ /** The path a vector paints, with its one solid fill, or null when it has no closed path. */
6641
+ const canvasEditableVectorPath = (node) => {
6642
+ const shape = canvasShapePathOf(node);
6643
+ if (typeof shape === "string") return null;
6644
+ const fill = (node.appearance?.fills ?? []).find((paint) => paint.visible);
6645
+ const { x, y, width, height } = shape.viewBox;
6646
+ return {
6647
+ d: shape.path,
6648
+ fillRule: shape.fillRule,
6649
+ fill: fill === void 0 ? "none" : canvasSolidPaintColor(fill) ?? "none",
6650
+ viewBox: [
6651
+ x,
6652
+ y,
6653
+ width,
6654
+ height
6655
+ ].map(String).join(" ")
6656
+ };
6657
+ };
6658
+ const invalid$3 = (message) => {
6659
+ throw new CliError("BAD_REQUEST", message, "Read the current editable subtree and apply only the intended change. No changes were committed.");
6660
+ };
6661
+ const viewBoxOf = (value) => {
6662
+ const [x = 0, y = 0, width = 0, height = 0] = value.split(/\s+/u).map(Number);
6663
+ return width > 0 && height > 0 ? {
6664
+ x,
6665
+ y,
6666
+ width,
6667
+ height
6668
+ } : invalid$3(`Invalid viewBox: ${value}.`);
6669
+ };
6670
+ /** A written path makes the layer a vector with that path; a Boolean group gives up its operands. */
6671
+ const pathOperations = (document, node, path) => {
6672
+ if (path.d.trim() === "") return invalid$3(`The path of ${node.id} is empty.`);
6673
+ return [{
6674
+ op: "setGeometry",
6675
+ nodeId: node.id,
6676
+ geometry: {
6677
+ kind: "path",
6678
+ path: path.d,
6679
+ fillRule: path.fillRule,
6680
+ viewBox: viewBoxOf(path.viewBox)
6681
+ }
6682
+ }, ...node.geometry?.kind === "boolean" ? canvasChildIds(document, node.id).map((operandId) => ({
6683
+ op: "remove",
6684
+ nodeId: operandId
6685
+ })) : []];
6686
+ };
6687
+ /**
6688
+ * A written fill becomes the layer's one solid fill, or no fill for none. A colour written on a
6689
+ * stored solid fill keeps that paint's identity and mode.
6690
+ */
6691
+ const fillOperation = (node, fill) => {
6692
+ const stored = (node.appearance?.fills ?? []).find((held) => held.visible);
6693
+ const id = stored?.kind === "solid" ? stored.id : `${node.id}-fill`;
6694
+ const paint = fill === "none" ? null : solidCanvasPaintFromCss(id, fill);
6695
+ if (paint === null && fill !== "none") return invalid$3(`The fill of ${node.id} is not a colour.`);
6696
+ return {
6697
+ op: "setAppearance",
6698
+ nodeId: node.id,
6699
+ appearance: { fills: paint === null ? [] : [{
6700
+ ...paint,
6701
+ ...stored?.kind === "solid" && stored.blendMode !== void 0 && { blendMode: stored.blendMode }
6702
+ }] }
6703
+ };
6704
+ };
6705
+ const canvasEditableVectorOperations = (document, node, before, after) => [...before.d === after.d && before.fillRule === after.fillRule && before.viewBox === after.viewBox ? [] : pathOperations(document, node, after), ...before.fill === after.fill ? [] : [fillOperation(node, after.fill)]];
6706
+
6707
+ //#endregion
6708
+ //#region src/application/canvas-editable-html.use-case.ts
6709
+ const READABLE_KINDS = /* @__PURE__ */ new Set([
6710
+ "root",
6711
+ "frame",
6712
+ "group",
6713
+ "rectangle",
6714
+ "image",
6715
+ "text"
6716
+ ]);
6717
+ const SEALED_REASONS = {
6718
+ screen: "Its pixels come from a recorded page. Use Make editable to edit it as layers.",
6719
+ recording: "Its pixels come from a recording.",
6720
+ prototype: "Its pixels come from a running build."
6721
+ };
6722
+ /** A mask group's CSS mask, made from its source each time it is drawn. */
6723
+ const MASK_PROPERTY = /^(?:mask(?:-.+)?|clip-path)$/u;
6724
+ const UNREAD_REASON = "This layer kind has no editable HTML form yet; edit it in the editor.";
6725
+ const RICH_TEXT_REASON = "Text with nested layers or nested formatting keeps its formatting in the editor.";
6726
+ const MASK_SHAPE_REASON = "This mask's shape cannot be read; edit it in the editor.";
6727
+ /** Why a layer is sealed in the agent's HTML, or null when the agent reads and writes it. */
6728
+ const sealedReasonOf = (document, node, childCount) => {
6729
+ const sealed = SEALED_REASONS[node.component];
6730
+ if (sealed !== void 0) return sealed;
6731
+ if (canvasMaskClipDeclarations(document, node) === null) return MASK_SHAPE_REASON;
6732
+ if (node.component === "text" && (childCount > 0 || hasCanvasNestedTextRuns(node))) return RICH_TEXT_REASON;
6733
+ if (isCanvasEditableVector(node)) return canvasVectorSealedReason(node) ?? (canvasEditableVectorPath(node) === null ? UNREAD_REASON : null);
6734
+ return READABLE_KINDS.has(node.component) && (node.geometry === void 0 || node.geometry.kind === "mask") ? null : UNREAD_REASON;
6735
+ };
6736
+ /**
6737
+ * The CSS the editor paints for the layer's native appearance, under its authored CSS, so a read
6738
+ * shows what is drawn. Values that name the editor's own resources stay out of the read.
6739
+ */
6740
+ const paintedDeclarations = (document, node) => {
6741
+ const painted = {
6742
+ ...canvasAppearanceDeclarations(node),
6743
+ ...canvasMaskLayerDeclarations(node, canvasMaskSourceOf(document, node)),
6744
+ ...canvasMaskClipDeclarations(document, node)
6745
+ };
6746
+ const authored = canvasAuthoredStyleDeclarations(node);
6747
+ const entries = Object.entries(painted).flatMap(([property, value]) => {
6748
+ const css = canvasCssValue(property, value);
6749
+ return property.startsWith("--") || css.includes("var(--canvas") || css.includes("url(#") || canvasAppearanceOwnedBy(node, [property]).length === 0 && !MASK_PROPERTY.test(property) ? [] : [[property, css]];
6750
+ });
6751
+ return {
6752
+ ...Object.fromEntries(entries),
6753
+ ...canvasEditableImageDeclarations(node),
6754
+ ...Object.fromEntries(Object.entries(authored).map(([property, value]) => [property, canvasCssValue(property, value)]))
6755
+ };
6756
+ };
6757
+ const fail = (message) => {
6758
+ throw new CliError("BAD_REQUEST", message, "Use a complete current editable read and preserve its identity and opaque markers.");
6759
+ };
6760
+ const escape = (value) => value.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;").replaceAll("\"", "&quot;");
6761
+ const vectorPathOf = (node) => isCanvasEditableVector(node) ? canvasEditableVectorPath(node) : null;
6762
+ /** A vector's fill is its path's fill, not a background of its element. */
6763
+ const FILL_PROPERTY = /^background(?:-.+)?$/u;
6764
+ const pathMarkup = (path) => `<path d="${escape(path.d)}" fill-rule="${path.fillRule}" fill="${escape(path.fill)}"></path>`;
6765
+ const styleAttributeOf = (styles) => {
6766
+ const style = Object.entries(styles).toSorted(([left], [right]) => left.localeCompare(right)).map(([key, value]) => `${key}:${value}`).join(";");
6767
+ return style === "" ? "" : ` style="${escape(style)}"`;
6768
+ };
6769
+ const paintMarkup = (paint) => `<div data-enhance-paint="${escape(paint.paintId ?? paint.owner)}"${styleAttributeOf(paint.styles)}></div>`;
6770
+ const runMarkup = (run, index) => `<span data-enhance-run="${String(index)}"${styleAttributeOf(run.styles)}>${escape(run.text)}</span>`;
6771
+ const serialize$1 = (node) => {
6772
+ const style = Object.entries(node.styles).toSorted(([left], [right]) => left.localeCompare(right)).map(([key, value]) => `${key}:${value}`).join(";");
6773
+ const attrs = `data-enhance-id="${escape(node.id)}" data-enhance-name="${escape(node.label)}"${node.opaque ? " data-enhance-opaque=\"true\"" : ""}${node.locked ? " data-enhance-locked=\"true\"" : ""}${style === "" ? "" : ` style="${escape(style)}"`}`;
6774
+ if (node.path !== void 0) return `<svg ${attrs} viewBox="${escape(node.path.viewBox)}" preserveAspectRatio="none">${pathMarkup(node.path)}</svg>`;
6775
+ const runs = (node.runs ?? []).map((run, index) => runMarkup(run, index)).join("");
6776
+ const paints = (node.paints ?? []).map((paint) => paintMarkup(paint)).join("");
6777
+ return `<${node.tag} ${attrs}>${escape(node.text)}${runs}${paints}${node.children.map((child) => serialize$1(child)).join("")}</${node.tag}>`;
6778
+ };
6779
+ const projectCanvasEditableHtml = (document, rootNodeId) => {
6780
+ const seen = /* @__PURE__ */ new Set();
6781
+ const opaqueNodeIds = [];
6782
+ const sealedReasons = {};
6783
+ const childrenByParent = canvasChildrenByParent(document);
6784
+ const visit = (nodeId) => {
6785
+ if (seen.has(nodeId)) return fail("The document contains repeated node identity.");
6786
+ seen.add(nodeId);
6787
+ const node = requireCanvasNode(document, nodeId);
6788
+ const children = childrenByParent.get(nodeId) ?? [];
6789
+ const reason = sealedReasonOf(document, node, children.length);
6790
+ const isOpaque = reason !== null;
6791
+ if (isOpaque) {
6792
+ opaqueNodeIds.push(node.id);
6793
+ sealedReasons[node.id] = reason;
6794
+ }
6795
+ const path = isOpaque ? null : vectorPathOf(node);
6796
+ const runs = isOpaque || node.component !== "text" ? null : canvasEditableTextRuns(node);
6797
+ const paints = isOpaque || path !== null ? [] : canvasEditablePaints(node);
6798
+ const styles = isOpaque ? {} : styleValues(Object.entries(paintedDeclarations(document, node)).filter(([property]) => path === null || !FILL_PROPERTY.test(property)).filter(([property]) => !isCanvasPaintElementProperty(paints, property)).map(([property, value]) => `${property}:${value}`).join(";"));
6799
+ return {
6800
+ id: node.id,
6801
+ tag: path === null ? node.component === "text" ? "span" : "div" : "svg",
6802
+ ...path !== null && { path },
6803
+ label: node.label,
6804
+ opaque: isOpaque,
6805
+ locked: isCanvasNodeLocked(document, nodeId),
6806
+ styles,
6807
+ ...runs !== null && { runs },
6808
+ ...paints.length > 0 && { paints },
6809
+ text: runs !== null || isOpaque || node.component !== "text" ? "" : textOf(node) ?? "",
6810
+ children: isOpaque || path !== null ? [] : children.map((id) => visit(id))
6811
+ };
6812
+ };
6813
+ const root = visit(rootNodeId);
6814
+ return {
6815
+ projectionVersion: 2,
6816
+ root,
6817
+ html: serialize$1(root),
6818
+ opaqueNodeIds,
6819
+ sealedReasons
6820
+ };
6821
+ };
6822
+
2916
6823
  //#endregion
2917
6824
  //#region src/application/canvas-outline-read.use-case.ts
2918
6825
  const rootsFor = (input, reference, scene) => {
@@ -3295,6 +7202,7 @@ const editable = (input, snapshot) => {
3295
7202
  rootNodeId: input.rootNodeId,
3296
7203
  html: projection.html,
3297
7204
  opaqueNodeIds: [...projection.opaqueNodeIds],
7205
+ sealedReasons: { ...projection.sealedReasons },
3298
7206
  snapshotToken: canvasSnapshotToken({
3299
7207
  reference,
3300
7208
  version,
@@ -3364,7 +7272,7 @@ const createRevisionedCanvasCommandComposite = (remote) => ({ execute: async (in
3364
7272
  };
3365
7273
  const request = applyCanvasOperationsInputSchema.safeParse({
3366
7274
  canvasId,
3367
- documentFormatVersion: 11,
7275
+ documentFormatVersion: 13,
3368
7276
  mutationId: input.clientToken,
3369
7277
  baseVersion: input.baseVersion,
3370
7278
  operations,
@@ -3511,6 +7419,8 @@ const finishCanvasHtmlReconciliation = (document, prepared, compiled = EMPTY_COM
3511
7419
 
3512
7420
  //#endregion
3513
7421
  //#region src/application/canvas-html-update-source.use-case.ts
7422
+ /** A paint element belongs to its layer and carries no identity of its own. */
7423
+ const isPaintElement = (element) => element.attrs.some((attribute) => attribute.name === "data-enhance-paint");
3514
7424
  const identity = (element) => element.attrs.find((attribute) => attribute.name === "data-enhance-id")?.value;
3515
7425
  const invalid$1 = (message) => {
3516
7426
  throw new CliError("BAD_REQUEST", message, "Preserve retained identities and opaque placeholders. Add new populated subtrees without identity markers. No canvas changes were committed.");
@@ -3525,9 +7435,10 @@ const parseCanvasHtmlUpdate = (html) => {
3525
7435
  const fragments = [];
3526
7436
  const visit = (element, parentId) => {
3527
7437
  const id = identity(element);
7438
+ if (id !== void 0 && (element.tagName === "svg" || element.tagName === "span")) return element;
3528
7439
  if (id !== void 0) return {
3529
7440
  ...element,
3530
- childNodes: element.childNodes.map((child) => "tagName" in child ? visit(child, id) : child)
7441
+ childNodes: element.childNodes.map((child) => "tagName" in child && !isPaintElement(child) ? visit(child, id) : child)
3531
7442
  };
3532
7443
  if (parentId === void 0) return invalid$1("The submitted HTML must retain its original root identity.");
3533
7444
  if ([element, ...collectElements(element.childNodes)].some((node) => node.attrs.some((attribute) => ["data-enhance-id", "data-enhance-opaque"].includes(attribute.name)))) return invalid$1("A new HTML subtree cannot wrap retained identities or opaque placeholders. Insert the container and use canvas_arrange to move retained content into it.");
@@ -3598,9 +7509,28 @@ const removedIds = (before, after, roots, rootNodeId) => {
3598
7509
  for (const id of before.keys()) if (!after.has(id) && !removed.has(id)) return invalid(`Missing retained node ${id}; declare intentional deletion in removeNodeIds.`);
3599
7510
  return removed;
3600
7511
  };
7512
+ /** The changed CSS of a layer, written through its owners. */
7513
+ const styleChangeOperations = (document, node, before, after) => {
7514
+ const properties = /* @__PURE__ */ new Set([...Object.keys(before.styles), ...Object.keys(after.styles)]);
7515
+ const styles = Object.fromEntries([...properties].filter((key) => before.styles[key] !== after.styles[key]).filter((key) => !isCanvasEditableImageProperty(node, key)).map((key) => [key, after.styles[key] ?? null]));
7516
+ return [
7517
+ ...node.geometry?.kind === "mask" && Object.keys(styles).some((key) => MASK_PROPERTY.test(key)) ? [{
7518
+ op: "setGeometry",
7519
+ nodeId: node.id,
7520
+ geometry: "default"
7521
+ }] : [],
7522
+ ...canvasEditableImageOperations(node, before.styles, after.styles),
7523
+ ...Object.keys(styles).length === 0 ? [] : canvasStyleOperations(document, [{
7524
+ nodeIds: [node.id],
7525
+ styles
7526
+ }])
7527
+ ];
7528
+ };
3601
7529
  const fieldOperations = (document, before, after) => {
3602
- if (before.tag !== after.tag || before.opaque !== after.opaque) return invalid(`The kind or opaque marker of ${before.id} changed.`);
7530
+ if (before.tag !== after.tag || before.opaque !== after.opaque || before.locked !== after.locked) return invalid(`The kind, opaque marker or locked marker of ${before.id} changed.`);
3603
7531
  const hasStyleChange = !arePropertiesEqual(before.styles, after.styles);
7532
+ const hasPathChange = JSON.stringify(before.path) !== JSON.stringify(after.path) || JSON.stringify(before.runs) !== JSON.stringify(after.runs) || JSON.stringify(before.paints) !== JSON.stringify(after.paints);
7533
+ if (before.locked && (hasStyleChange || hasPathChange || before.label !== after.label || before.text !== after.text)) return invalid(`Locked node ${before.id} cannot be changed through HTML.`);
3604
7534
  if (before.opaque && (hasStyleChange || before.label !== after.label || before.text !== after.text || after.children.length > 0)) return invalid(`Opaque node ${before.id} cannot be changed through HTML.`);
3605
7535
  const node = document.nodes[before.id];
3606
7536
  if (node === void 0) return invalid(`Node ${before.id} no longer exists.`);
@@ -3619,14 +7549,10 @@ const fieldOperations = (document, before, after) => {
3619
7549
  props: canvasTextPropsWithContent(node, after.text)
3620
7550
  })
3621
7551
  });
3622
- if (hasStyleChange) {
3623
- const properties = /* @__PURE__ */ new Set([...Object.keys(before.styles), ...Object.keys(after.styles)]);
3624
- const styles = Object.fromEntries([...properties].filter((key) => before.styles[key] !== after.styles[key]).map((key) => [key, after.styles[key] ?? null]));
3625
- operations.push(...canvasStyleOperations(document, [{
3626
- nodeIds: [before.id],
3627
- styles
3628
- }]));
3629
- }
7552
+ operations.push(...canvasEditablePaintOperations(node, before.paints ?? [], after.paints ?? []));
7553
+ if (before.runs !== void 0 || after.runs !== void 0) operations.push(...canvasEditableTextOperations(node, before.runs ?? [], after.runs ?? []));
7554
+ if (before.path !== void 0 && after.path !== void 0) operations.push(...canvasEditableVectorOperations(document, node, before.path, after.path));
7555
+ if (hasStyleChange) operations.push(...styleChangeOperations(document, node, before, after));
3630
7556
  return operations;
3631
7557
  };
3632
7558
  const prepareCanvasHtmlReconciliation = (document, rootNodeId, html, removeNodeIds) => {
@@ -3655,7 +7581,7 @@ const prepareCanvasHtmlReconciliation = (document, rootNodeId, html, removeNodeI
3655
7581
  }
3656
7582
  for (const fragment of parsed.fragments) {
3657
7583
  const parent = before.get(fragment.parentNodeId);
3658
- if (parent === void 0 || parent.opaque || parent.tag !== "div") return invalid(`Node ${fragment.parentNodeId} cannot contain new HTML.`);
7584
+ if (parent === void 0 || parent.opaque || parent.locked || parent.tag !== "div") return invalid(`Node ${fragment.parentNodeId} cannot contain new HTML.`);
3659
7585
  }
3660
7586
  return {
3661
7587
  root: requested,
@@ -4720,4 +8646,4 @@ const createMutationKeyAdapter = () => {
4720
8646
  };
4721
8647
 
4722
8648
  //#endregion
4723
- export { createAuthUseCase as S, assertCanvasReferenceOperations as _, readRemoteMcpEnvironment as a, createCanvasActivityComposite as b, createPrototypeArtifactAdapter as c, createRenderFileAdapter as d, readCanvasReferenceScene as f, createEditCanvasComposite as g, fromCapabilityReference as h, readLocalMcpEnvironment as i, createPublishCanvasPrototypeComposite as l, boundedResultPage as m, createHttpRemoteAdapter as n, createOauthLoopbackAdapter as o, createWriteHtmlCanvasComposite as p, readCliEnvironment as r, createCapabilityInvocationAdapter as s, createMutationKeyAdapter as t, createImportCanvasAssetComposite as u, sceneAtVersion as v, createRenderCanvasComposite as x, createApplyCanvasComposite as y };
8649
+ export { canvasRadialGradientSvg as C, canvasAngularGradientSvg as D, canvasDiamondGradientSvg as E, canvasColorCss as O, createAuthUseCase as S, canvasFilterListCss as T, assertCanvasReferenceOperations as _, readRemoteMcpEnvironment as a, createCanvasActivityComposite as b, createPrototypeArtifactAdapter as c, createRenderFileAdapter as d, readCanvasReferenceScene as f, createEditCanvasComposite as g, fromCapabilityReference as h, readLocalMcpEnvironment as i, compareCanvasSortKeys as k, createPublishCanvasPrototypeComposite as l, boundedResultPage as m, createHttpRemoteAdapter as n, createOauthLoopbackAdapter as o, createWriteHtmlCanvasComposite as p, readCliEnvironment as r, createCapabilityInvocationAdapter as s, createMutationKeyAdapter as t, createImportCanvasAssetComposite as u, sceneAtVersion as v, canvasLinearGradientSvg as w, createRenderCanvasComposite as x, createApplyCanvasComposite as y };