@pixerate/editor 0.124.1 → 0.125.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (97) hide show
  1. package/dist/agent/index.cjs +3 -3
  2. package/dist/agent/index.cjs.map +1 -1
  3. package/dist/agent/index.js +3 -3
  4. package/dist/animation-editor/index.cjs +424 -85
  5. package/dist/animation-editor/index.cjs.map +1 -1
  6. package/dist/animation-editor/index.d.cts +174 -7
  7. package/dist/animation-editor/index.d.ts +174 -7
  8. package/dist/animation-editor/index.js +348 -9
  9. package/dist/animation-editor/index.js.map +1 -1
  10. package/dist/chunk-FJ3324TZ.js +59 -0
  11. package/dist/chunk-FJ3324TZ.js.map +1 -0
  12. package/dist/{chunk-5EO2IXQE.js → chunk-FPRIUR4T.js} +1 -1
  13. package/dist/chunk-FPRIUR4T.js.map +1 -0
  14. package/dist/{chunk-ORHMVUR6.js → chunk-G6WXWS4Y.js} +5 -3
  15. package/dist/{chunk-ORHMVUR6.js.map → chunk-G6WXWS4Y.js.map} +1 -1
  16. package/dist/{chunk-CN4PJHUG.cjs → chunk-IOXKXQNW.cjs} +3 -59
  17. package/dist/chunk-IOXKXQNW.cjs.map +1 -0
  18. package/dist/{chunk-NGYD3AMN.js → chunk-MPQAO33O.js} +2 -2
  19. package/dist/{chunk-PEHYWUVV.cjs → chunk-O5RVCDEC.cjs} +82 -82
  20. package/dist/{chunk-PEHYWUVV.cjs.map → chunk-O5RVCDEC.cjs.map} +1 -1
  21. package/dist/{chunk-FHYDQOPC.cjs → chunk-QDJKUBWE.cjs} +5 -5
  22. package/dist/{chunk-FHYDQOPC.cjs.map → chunk-QDJKUBWE.cjs.map} +1 -1
  23. package/dist/{chunk-5XXMLBH4.cjs → chunk-QQKTOA4U.cjs} +1 -1
  24. package/dist/chunk-QQKTOA4U.cjs.map +1 -0
  25. package/dist/{chunk-QEG3GRN2.js → chunk-TGKT5QAB.js} +2 -58
  26. package/dist/chunk-TGKT5QAB.js.map +1 -0
  27. package/dist/{chunk-4QQZV5Y5.cjs → chunk-UXFI3CDZ.cjs} +11 -9
  28. package/dist/chunk-UXFI3CDZ.cjs.map +1 -0
  29. package/dist/{chunk-WE25VLCO.cjs → chunk-V5YGPRCZ.cjs} +36 -36
  30. package/dist/{chunk-WE25VLCO.cjs.map → chunk-V5YGPRCZ.cjs.map} +1 -1
  31. package/dist/chunk-W6QTLHZ3.cjs +59 -0
  32. package/dist/chunk-W6QTLHZ3.cjs.map +1 -0
  33. package/dist/{chunk-WATAQ2Z2.js → chunk-WUDPFWAN.js} +2 -2
  34. package/dist/{chunk-JRXJTPES.js → chunk-XZWOLXWA.js} +4 -4
  35. package/dist/{chunk-JRXJTPES.js.map → chunk-XZWOLXWA.js.map} +1 -1
  36. package/dist/effects/index.cjs +61 -33
  37. package/dist/effects/index.cjs.map +1 -1
  38. package/dist/effects/index.d.cts +4 -5
  39. package/dist/effects/index.d.ts +4 -5
  40. package/dist/effects/index.js +32 -4
  41. package/dist/effects/index.js.map +1 -1
  42. package/dist/{export-WmYoWmLM.d.cts → export-Bp7ji2r4.d.cts} +1 -2
  43. package/dist/{export-BdfY_lH0.d.ts → export-C1s4eolZ.d.ts} +1 -1
  44. package/dist/{export-BGtXgMJ3.d.ts → export-DAyPY94f.d.ts} +1 -2
  45. package/dist/{export-CbpjwxaI.d.cts → export-DVl4fWy5.d.cts} +1 -1
  46. package/dist/generation/index.cjs +3 -3
  47. package/dist/generation/index.cjs.map +1 -1
  48. package/dist/generation/index.js +3 -3
  49. package/dist/helpers-BBLlekuM.d.ts +2009 -0
  50. package/dist/helpers-i95Ob6Vi.d.cts +2009 -0
  51. package/dist/image-editor/index.cjs +629 -627
  52. package/dist/image-editor/index.cjs.map +1 -1
  53. package/dist/image-editor/index.d.cts +5 -7
  54. package/dist/image-editor/index.d.ts +5 -7
  55. package/dist/image-editor/index.js +15 -13
  56. package/dist/image-editor/index.js.map +1 -1
  57. package/dist/paint-editor/index.cjs +12 -11
  58. package/dist/paint-editor/index.cjs.map +1 -1
  59. package/dist/paint-editor/index.d.cts +3 -5
  60. package/dist/paint-editor/index.d.ts +3 -5
  61. package/dist/paint-editor/index.js +6 -5
  62. package/dist/paint-editor/index.js.map +1 -1
  63. package/dist/{svg-BDrjRnL1.d.cts → svg-BkRL-fZJ.d.cts} +1 -1
  64. package/dist/{svg-C-vZ3q50.d.ts → svg-DJKriJ4A.d.ts} +1 -1
  65. package/dist/tools/index.cjs +2 -2
  66. package/dist/tools/index.cjs.map +1 -1
  67. package/dist/tools/index.js +3 -3
  68. package/dist/{tools-C7JtLYzo.d.ts → tools-CM8Oe8F3.d.ts} +1 -1
  69. package/dist/{tools-DHKGHiSK.d.cts → tools-DZCv2kX1.d.cts} +1 -1
  70. package/dist/vector/index.cjs +1032 -883
  71. package/dist/vector/index.cjs.map +1 -1
  72. package/dist/vector/index.d.cts +61 -6
  73. package/dist/vector/index.d.ts +61 -6
  74. package/dist/vector/index.js +155 -6
  75. package/dist/vector/index.js.map +1 -1
  76. package/dist/video-editor/index.cjs +273 -272
  77. package/dist/video-editor/index.cjs.map +1 -1
  78. package/dist/video-editor/index.d.cts +4 -6
  79. package/dist/video-editor/index.d.ts +4 -6
  80. package/dist/video-editor/index.js +7 -6
  81. package/dist/video-editor/index.js.map +1 -1
  82. package/package.json +1 -1
  83. package/skills/pixerate-animation-editor/SKILL.md +24 -1
  84. package/skills/pixerate-vector/SKILL.md +15 -0
  85. package/dist/chunk-4QQZV5Y5.cjs.map +0 -1
  86. package/dist/chunk-5EO2IXQE.js.map +0 -1
  87. package/dist/chunk-5XXMLBH4.cjs.map +0 -1
  88. package/dist/chunk-CN4PJHUG.cjs.map +0 -1
  89. package/dist/chunk-QEG3GRN2.js.map +0 -1
  90. package/dist/flair-CxB3fOcU.d.ts +0 -739
  91. package/dist/flair-D7BxyBwL.d.cts +0 -739
  92. package/dist/helpers-777mC6dc.d.cts +0 -253
  93. package/dist/helpers-DX2_7L5t.d.ts +0 -253
  94. package/dist/types-BcX7sCsn.d.ts +0 -993
  95. package/dist/types-CznabG7m.d.cts +0 -993
  96. /package/dist/{chunk-NGYD3AMN.js.map → chunk-MPQAO33O.js.map} +0 -0
  97. /package/dist/{chunk-WATAQ2Z2.js.map → chunk-WUDPFWAN.js.map} +0 -0
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/vector/types.ts","../src/vector/gradient.ts","../src/vector/shading.ts","../src/geom/affine.ts","../src/vector/corners.ts","../src/vector/width.ts","../src/vector/varstroke.ts","../src/vector/stroke.ts","../src/vector/paintLayers.ts","../src/vector/pathEffects.ts","../src/vector/pathMap.ts","../src/vector/frames.ts","../src/vector/pathCut.ts","../src/vector/filters.ts","../src/vector/mask.ts","../src/text/layout.ts","../src/text/shapers.ts","../src/vector/text.ts","../src/vector/symbols.ts","../src/geom/warp.ts","../src/vector/warp.ts","../src/vector/appearance.ts","../src/vector/connectors.ts","../src/vector/gradientStroke.ts","../src/vector/svg.ts","../src/vector/spatial.ts","../src/vector/geometry.ts","../src/vector/symmetry.ts"],"sourcesContent":["import type { CanvasGradientDef } from '../canvas/gradient.js';\nimport type { WarpMesh, WarpStyle } from '../geom/types.js';\n\n/** An affine matrix `[a, b, c, d, e, f]`: `x' = a·x + c·y + e`, `y' = b·x + d·y + f` (SVG order). */\nexport type VectorMatrix = readonly [number, number, number, number, number, number];\n\n/** A point in document coordinates. */\nexport interface Vec2 {\n\tx: number;\n\ty: number;\n}\n\n/**\n * How an anchor's handles relate:\n * - `corner`: handles move independently (or are absent).\n * - `smooth`: handles stay on one line through the anchor, lengths independent.\n * - `symmetric`: handles stay on one line with equal lengths.\n */\nexport type VectorAnchorType = 'corner' | 'smooth' | 'symmetric';\n\n/**\n * Live corner shapes: `round` (an arc tangent to both sides), `inverted` (an arc centred on\n * the corner, cut into the shape) and `chamfer` (a straight bevel).\n */\nexport type VectorCornerKind = 'round' | 'inverted' | 'chamfer';\n\nexport const VECTOR_CORNER_KINDS: readonly VectorCornerKind[] = ['round', 'inverted', 'chamfer'];\n\n/**\n * A live corner: drawn rounded (or cut) at render, hit-test, bounds, boolean, outline and export\n * time while the stored anchor stays sharp. The radius shrinks to fit when the sides are short:\n * the cut reaches at most halfway along each side.\n */\nexport interface VectorCorner {\n\tradius: number;\n\t/** Default `round`. */\n\tkind?: VectorCornerKind;\n\t/**\n\t * Corner smoothing (squircle, as in Figma and iOS), 0–1, round corners between straight sides\n\t * only: the cut reaches (1 + smoothing) times as far along each side and eases into a shorter arc,\n\t * so curvature builds up gradually. Default 0 (a circular arc).\n\t */\n\tsmoothing?: number;\n}\n\n/**\n * One anchor of a subpath. Handles are absolute document positions; a missing (or `null`)\n * handle sits on the anchor, so a segment with no handles at either end is a straight line.\n */\nexport interface VectorAnchor {\n\tx: number;\n\ty: number;\n\t/** Control point of the segment arriving at this anchor. */\n\tin?: Vec2 | null;\n\t/** Control point of the segment leaving this anchor. */\n\tout?: Vec2 | null;\n\t/** Default `corner`. */\n\ttype?: VectorAnchorType;\n\t/** Live corner radius. Ignored on smooth / symmetric anchors and the ends of open subpaths. */\n\tcorner?: VectorCorner | null;\n\t/**\n\t * A stable id, unique within its path, given when a constraint refers to the anchor (see\n\t * `VectorConstraint`). Edits that move or restyle the anchor keep it; edits that rebuild a path\n\t * drop it, and constraints on a dropped anchor are removed.\n\t */\n\tid?: string;\n}\n\n/** A chain of anchors joined by line or cubic Bézier segments. */\nexport interface VectorSubpath {\n\tanchors: VectorAnchor[];\n\t/** Joins the last anchor back to the first. */\n\tclosed: boolean;\n}\n\n/**\n * Gradient styles: `linear` (start → end), `radial` (centred on the start, reaching the end;\n * focal point and aspect), `conic` (an angle sweep around the start, from the end's direction\n * towards the aspect handle's: clockwise on screen), `reflected` (linear mirrored about the\n * start) and `diamond` (`|u| + |v|` in the gradient's frame: a rhombus through the end and the\n * aspect handle).\n */\nexport type VectorGradientType = 'linear' | 'radial' | 'conic' | 'reflected' | 'diamond';\nexport const VECTOR_GRADIENT_TYPES: readonly VectorGradientType[] = ['linear', 'radial', 'conic', 'reflected', 'diamond'];\n\n/** What a gradient paints past its ends: the end colours, mirrored periods or repeated periods. */\nexport type VectorGradientSpread = 'pad' | 'reflect' | 'repeat';\nexport const VECTOR_GRADIENT_SPREADS: readonly VectorGradientSpread[] = ['pad', 'reflect', 'repeat'];\n\n/** Where colours mix between stops: sRGB (SVG's own), linear light or Oklab. */\nexport type VectorGradientInterpolation = 'srgb' | 'linear' | 'oklab';\nexport const VECTOR_GRADIENT_INTERPOLATIONS: readonly VectorGradientInterpolation[] = ['srgb', 'linear', 'oklab'];\n\n/**\n * The space a gradient's points are in: fractions of the shape's bounding box (SVG's\n * `objectBoundingBox`, the default) or the node's own coordinates (`userSpaceOnUse`).\n */\nexport type VectorGradientUnits = 'objectBoundingBox' | 'userSpaceOnUse';\n\n/**\n * How a gradient lies on a stroke: `within` (laid over the stroke's area like a fill), `along`\n * (t runs from 0 at the start of each subpath to 1 at its end) or `across` (from the stroke's\n * left edge to its right edge, looking along the path).\n */\nexport type VectorStrokeGradientMode = 'within' | 'along' | 'across';\nexport const VECTOR_STROKE_GRADIENT_MODES: readonly VectorStrokeGradientMode[] = ['within', 'along', 'across'];\n\n/** A colour stop. `opacity` multiplies the colour's own alpha. */\nexport interface VectorGradientStop {\n\t/** 0–1. */\n\toffset: number;\n\tcolor: string;\n\t/** 0–1, default 1. */\n\topacity?: number;\n\t/**\n\t * Where, between this stop and the next (0–1 of the way), the colour is half-way between\n\t * them. Default 0.5 (an even mix).\n\t */\n\tmidpoint?: number;\n}\n\n/**\n * A gradient paint. `CanvasGradientDef` (the canvas package's linear `angle` / radial\n * `cx, cy, r` gradients) is a valid value: those fields are the shorthand form. Explicit\n * geometry (`start` / `end`, in `units`) wins over the shorthand.\n */\nexport interface VectorGradient {\n\ttype: VectorGradientType;\n\tstops: VectorGradientStop[];\n\t/**\n\t * Shorthand direction in degrees, CSS style (0 points up, clockwise): a linear or reflected\n\t * gradient's direction across the box (default 180), a conic gradient's start angle or a\n\t * diamond's turn (default 90).\n\t */\n\tangle?: number;\n\t/** Shorthand centre and radius of radial, conic and diamond gradients (fractions of the box, default 0.5). */\n\tcx?: number;\n\tcy?: number;\n\tr?: number;\n\t/** Where t = 0: a linear gradient's start, the centre of the other styles. */\n\tstart?: Vec2;\n\t/** Where t = 1 along the gradient's main axis (a radial gradient's radius). */\n\tend?: Vec2;\n\t/**\n\t * The end of the secondary axis (radial, conic and diamond): its distance from `start` over\n\t * the main axis' length is the aspect ratio. Absent: square to the main axis, as long.\n\t */\n\twidth?: Vec2 | null;\n\t/** A radial gradient's focal point (where t = 0); absent: the centre. */\n\tfocal?: Vec2 | null;\n\t/** Radius of the focal circle as a fraction of the radius (SVG `fr`, default 0). */\n\tfocalRadius?: number;\n\t/** Space of `start`, `end`, `width` and `focal` (default `objectBoundingBox`). */\n\tunits?: VectorGradientUnits;\n\t/** Default `pad`. */\n\tspread?: VectorGradientSpread;\n\t/** Default `srgb`. */\n\tinterpolation?: VectorGradientInterpolation;\n\t/**\n\t * 0–1: how far the colours follow a smooth spline through the stops instead of straight\n\t * lines (Photoshop's Smoothness). Default 0.\n\t */\n\tsmoothness?: number;\n\t/** On a stroke: how the gradient lies on it (default `within`). Ignored on fills. */\n\tstrokeMode?: VectorStrokeGradientMode;\n}\n\n/** A fill or stroke: any CSS colour, a gradient, or `null` / `'none'` for no paint. */\nexport type VectorPaint = string | VectorGradient | VectorMeshGradient | VectorFreeformGradient | CanvasGradientDef | null;\n\n/**\n * A gradient mesh (Illustrator's Gradient Mesh, PDF shading types 6 and 7): a lattice of\n * `(rows + 1) × (columns + 1)` points in the node's own space, row by row, each with a colour.\n * Each cell is a smooth patch whose sides are curves through the lattice and whose colour blends\n * between its four corners. Outside the patches the paint is transparent.\n */\nexport interface VectorMeshGradient {\n\ttype: 'mesh';\n\trows: number;\n\tcolumns: number;\n\t/** Lattice points, row by row (`(rows + 1) × (columns + 1)` of them). */\n\tpoints: Vec2[];\n\t/** A CSS colour per point. */\n\tcolors: string[];\n\t/** Opacity per point (0–1, default 1 each). */\n\topacities?: number[];\n}\n\n/** One colour point of a freeform gradient. */\nexport interface VectorFreeformPoint {\n\tx: number;\n\ty: number;\n\tcolor: string;\n\t/** 0–1, default 1. */\n\topacity?: number;\n\t/** Radius of the disc of pure colour round the point, as a fraction of half the box's longer side (0–1, default 0). */\n\tspread?: number;\n}\n\n/**\n * A freeform gradient (Illustrator's Freeform Gradient): colour points placed anywhere in the\n * node's own space, blended across the shape by distance, and optional smooth lines through some\n * of them that carry their colours along their length.\n */\nexport interface VectorFreeformGradient {\n\ttype: 'freeform';\n\tpoints: VectorFreeformPoint[];\n\t/** Each line runs smoothly through the points at these indices, in order. */\n\tlines?: number[][];\n}\n\nexport type VectorFillRule = 'nonzero' | 'evenodd';\nexport type VectorLineCap = 'butt' | 'round' | 'square';\nexport type VectorLineJoin = 'miter' | 'round' | 'bevel';\n/**\n * Where the stroke sits on the outline: centred on it, inside the shape or outside it. Only\n * shapes whose subpaths are all closed have an inside; open paths always stroke centred.\n */\nexport type VectorStrokeAlign = 'center' | 'inside' | 'outside';\n/** Arrowheads and end markers for the ends of open paths. */\nexport type VectorArrowhead = 'triangle' | 'arrow' | 'open' | 'circle' | 'square' | 'bar';\nexport const VECTOR_ARROWHEADS: readonly VectorArrowhead[] = ['triangle', 'arrow', 'open', 'circle', 'square', 'bar'];\n/**\n * `extend`: the head's tip sits past the end point and the path keeps its length; `tip`: the\n * tip sits on the end point and the stroke is shortened under the head.\n */\nexport type VectorArrowAlign = 'extend' | 'tip';\n\n/**\n * One point of a variable-width stroke profile. `t` is the position along the subpath by\n * length (0 at its start, 1 at its end); `left` and `right` are how far the stroke reaches on\n * each side, as multiples of half the stroke width (looking along the path on screen, y down).\n * A uniform stroke has 1 on both sides. Two points at the same `t` make a step.\n */\nexport interface VectorWidthPoint {\n\tt: number;\n\tleft: number;\n\tright: number;\n}\n\n/**\n * Blend modes of paint layers and nodes: the set SVG and CSS `mix-blend-mode` draw, named as the\n * image editor names them (`@pixerate/editor/image-editor` `BlendMode`). `linear-dodge` draws as\n * CSS `plus-lighter`. The image editor's other modes (linear burn, vivid light, pigment, …) have\n * no SVG equivalent and are not offered.\n */\nexport type VectorBlendMode =\n\t| 'normal'\n\t| 'darken'\n\t| 'multiply'\n\t| 'color-burn'\n\t| 'lighten'\n\t| 'screen'\n\t| 'color-dodge'\n\t| 'linear-dodge'\n\t| 'overlay'\n\t| 'soft-light'\n\t| 'hard-light'\n\t| 'difference'\n\t| 'exclusion'\n\t| 'hue'\n\t| 'saturation'\n\t| 'color'\n\t| 'luminosity';\n/** Every vector blend mode, in the image editor's (Photoshop's) menu order. */\nexport const VECTOR_BLEND_MODES: readonly VectorBlendMode[] = [\n\t'normal',\n\t'darken',\n\t'multiply',\n\t'color-burn',\n\t'lighten',\n\t'screen',\n\t'color-dodge',\n\t'linear-dodge',\n\t'overlay',\n\t'soft-light',\n\t'hard-light',\n\t'difference',\n\t'exclusion',\n\t'hue',\n\t'saturation',\n\t'color',\n\t'luminosity'\n];\n\n/** One fill of a path's fill stack (`VectorStyle.fills`). */\nexport interface VectorPaintLayer {\n\t/** A colour, a gradient, or `null` for none. */\n\tpaint: VectorPaint;\n\t/** 0–1, default 1. Multiplies the paint's own alpha. */\n\topacity?: number;\n\t/** How the layer mixes with what is under it (the layers below, then the backdrop). Default `normal`. */\n\tblendMode?: VectorBlendMode;\n\t/** Hidden layers are kept but not drawn or hit. Default true. */\n\tvisible?: boolean;\n}\n\n/** The settings each stroke layer has of its own (the stroke shorthand fields of `VectorStyle`). */\nexport type VectorStrokeSettings = Pick<\n\tVectorStyle,\n\t| 'strokeWidth'\n\t| 'strokeLinecap'\n\t| 'strokeLinejoin'\n\t| 'strokeDasharray'\n\t| 'strokeAlign'\n\t| 'startArrow'\n\t| 'endArrow'\n\t| 'arrowAlign'\n\t| 'startArrowScale'\n\t| 'endArrowScale'\n\t| 'strokeWidthProfile'\n>;\n\n/**\n * What a stroke layer draws. Only `paint` (a paint along the outline, the default) exists today.\n * Other kinds are the extension point for strokes drawn some other way, such as a raster\n * brushstroke from `@pixerate/editor/paint` laid along the path: a layer with an unknown kind is\n * kept through edits, load and SVG round trips, listed to agents, and skipped when drawing and\n * hit-testing.\n */\nexport type VectorStrokeLayerKind = 'paint';\n\n/** One stroke of a path's stroke stack (`VectorStyle.strokes`): a paint plus its own stroke settings. */\nexport interface VectorStrokeLayer extends VectorPaintLayer, VectorStrokeSettings {\n\t/** Default `paint`. See `VectorStrokeLayerKind`. */\n\tkind?: VectorStrokeLayerKind;\n}\n\n/** Paint and stroke settings of a path. */\nexport interface VectorStyle {\n\tfill?: VectorPaint;\n\tstroke?: VectorPaint;\n\t/** Default 1. */\n\tstrokeWidth?: number;\n\tstrokeLinecap?: VectorLineCap;\n\tstrokeLinejoin?: VectorLineJoin;\n\tstrokeDasharray?: number[];\n\t/** Default `nonzero`. */\n\tfillRule?: VectorFillRule;\n\t/** Default `center`. */\n\tstrokeAlign?: VectorStrokeAlign;\n\t/** Head at the start of the first subpath when it is open, or none. */\n\tstartArrow?: VectorArrowhead | null;\n\t/** Head at the end of the last subpath when it is open, or none. */\n\tendArrow?: VectorArrowhead | null;\n\t/** Default `extend`. */\n\tarrowAlign?: VectorArrowAlign;\n\t/** Size of the start head as a multiple of the stroke width (default 1: a head 4 widths long). */\n\tstartArrowScale?: number;\n\t/** Size of the end head (default 1). */\n\tendArrowScale?: number;\n\t/**\n\t * Variable width: side scales along each subpath, interpolated with a monotone cubic (see\n\t * `widthProfileAt`). Absent, empty or `null` strokes at a uniform width. A profiled stroke is\n\t * drawn as its filled outline.\n\t */\n\tstrokeWidthProfile?: VectorWidthPoint[] | null;\n\t/**\n\t * The fill stack, bottom to top. Absent: `fill` alone is the stack (one layer, or none without\n\t * a paint). Present: it is the truth, and `fill` mirrors its top layer's paint. The shorthand\n\t * stays writable: setting `fill` to a paint repaints the top layer, `null` clears the stack.\n\t * Stacks of one plain layer (full opacity, `normal`, visible) are stored as the shorthand.\n\t */\n\tfills?: VectorPaintLayer[] | null;\n\t/**\n\t * The stroke stack, bottom to top, drawn over every fill. Like `fills`: absent, `stroke` and the\n\t * stroke settings above are the one stroke; present, they mirror its top layer, and writing them\n\t * edits that layer (`stroke: null` clears the stack).\n\t */\n\tstrokes?: VectorStrokeLayer[] | null;\n}\n\ninterface VectorNodeBase {\n\tid: string;\n\tname?: string;\n\t/** Default true. */\n\tvisible?: boolean;\n\t/** Locked nodes are drawn but cannot be picked or edited on the canvas. */\n\tlocked?: boolean;\n\t/** 0–1, default 1. */\n\topacity?: number;\n\t/**\n\t * Placement in the parent's space: a rigid matrix (rotation + translation). Anchors and\n\t * children are in the node's own space. Omitted for unrotated nodes, whose positions are\n\t * stored directly. Scale and skew are never stored here — `transformVectorNode` bakes\n\t * them into the geometry, so stroke widths and the rotated selection box stay exact.\n\t */\n\ttransform?: VectorMatrix;\n\t/**\n\t * An in-between a blend group generated from its keys. Steps are rebuilt whenever a key or\n\t * the blend options change, and are locked (clicks select the blend group).\n\t */\n\tblendStep?: boolean;\n\t/**\n\t * Live path effects, applied top to bottom: each acts on every path above it (the node's own\n\t * outline, or a group's children, then the result of the effects before it), and effects after a\n\t * repeater act on its copies. The stored anchors and children never change.\n\t */\n\teffects?: VectorEffect[] | null;\n\t/**\n\t * As an operand of a live boolean group: how it combines with the result of the operands below\n\t * it. Absent: the group's `liveBoolean` operation.\n\t */\n\tbooleanOperation?: VectorBooleanOperation | null;\n\t/** How the whole node (all its paint, filters included) mixes with what is under it. Default `normal`. */\n\tblendMode?: VectorBlendMode;\n\t/**\n\t * Visual filters (drop and inner shadows, glows, blurs, feather), applied to everything the\n\t * node draws. Unlike path `effects` they never change geometry: bounds, hit-testing and\n\t * booleans ignore them.\n\t */\n\tfilters?: VectorFilter[] | null;\n\t/**\n\t * How the node follows its frame when the frame is resized (`VectorGroupNode.frame`): per\n\t * axis, pinned to the start (default `left` / `top`), the end, both (it stretches), the centre,\n\t * or scaled with the frame. Ignored outside frames.\n\t */\n\tresizing?: VectorResizing | null;\n}\n\n/** Horizontal resizing constraint of a frame's child (see `VectorNodeBase.resizing`). */\nexport type VectorHorizontalResizing = 'left' | 'right' | 'leftRight' | 'center' | 'scale';\n/** Vertical resizing constraint of a frame's child (see `VectorNodeBase.resizing`). */\nexport type VectorVerticalResizing = 'top' | 'bottom' | 'topBottom' | 'center' | 'scale';\nexport const VECTOR_HORIZONTAL_RESIZING: readonly VectorHorizontalResizing[] = ['left', 'right', 'leftRight', 'center', 'scale'];\nexport const VECTOR_VERTICAL_RESIZING: readonly VectorVerticalResizing[] = ['top', 'bottom', 'topBottom', 'center', 'scale'];\n\n/** A frame child's resizing constraints (Figma's \"constraints\"). */\nexport interface VectorResizing {\n\t/** Default `left`. */\n\thorizontal?: VectorHorizontalResizing;\n\t/** Default `top`. */\n\tvertical?: VectorVerticalResizing;\n}\n\n/**\n * Makes a group a frame (an artboard when top-level): a rectangle in the group's own space with an\n * optional fill drawn below the children, which by default it clips. Resizing the frame moves and\n * resizes its children by their `resizing` constraints instead of scaling them.\n */\nexport interface VectorFrame {\n\tx: number;\n\ty: number;\n\twidth: number;\n\theight: number;\n\t/** The frame's background, drawn below its children (default none). */\n\tfill?: VectorPaint;\n\t/** Clip the children to the frame (default true). */\n\tclip?: boolean;\n}\n\n/** A shape made of one or more subpaths (holes and compound shapes included). */\nexport interface VectorPathNode extends VectorNodeBase, VectorStyle {\n\ttype: 'path';\n\tsubpaths: VectorSubpath[];\n\t/**\n\t * Makes the path a connector: an open line whose ends may be glued to other objects'\n\t * connection sites. Its geometry is routed again after every edit, so it follows them.\n\t */\n\tconnector?: VectorConnector | null;\n}\n\n/**\n * Where a connector end meets an object: the middle of a side of the object's own (unrotated)\n * bounds, its centre, or `auto` (the side facing the connector's other end, chosen on every route).\n */\nexport type VectorConnectorSide = 'top' | 'right' | 'bottom' | 'left' | 'center' | 'auto';\nexport const VECTOR_CONNECTOR_SIDES: readonly VectorConnectorSide[] = ['auto', 'top', 'right', 'bottom', 'left', 'center'];\n\n/** How a connector runs between its ends: a straight line, right-angled elbows or an S-curve. */\nexport type VectorConnectorRoute = 'straight' | 'elbow' | 'curved';\nexport const VECTOR_CONNECTOR_ROUTES: readonly VectorConnectorRoute[] = ['straight', 'elbow', 'curved'];\n\n/** A glued connector end. */\nexport interface VectorConnectorEnd {\n\tnodeId: string;\n\t/** Default `auto`. */\n\tside?: VectorConnectorSide;\n}\n\n/** A connector's settings (`VectorPathNode.connector`). An end that is not glued stays where it is. */\nexport interface VectorConnector {\n\tstart?: VectorConnectorEnd | null;\n\tend?: VectorConnectorEnd | null;\n\t/** Default `straight`. */\n\troute?: VectorConnectorRoute;\n\t/** Corner radius of an elbow route's bends (document units, default 0). */\n\tradius?: number;\n\t/** How far an elbow or curve leaves a glued end straight out of its side before turning (document units, default 16). */\n\tgap?: number;\n}\n\n/**\n * How a blend spaces its in-betweens: a number of `steps` between each pair of keys, a fixed\n * `distance` between steps along the spine, or `smoothColor` (as many steps as the colours\n * need for a smooth ramp; by distance when the colours match).\n */\nexport type VectorBlendSpacing = 'steps' | 'distance' | 'smoothColor';\nexport const VECTOR_BLEND_SPACINGS: readonly VectorBlendSpacing[] = ['steps', 'distance', 'smoothColor'];\n\n/** Settings of a blend. */\nexport interface VectorBlendOptions {\n\t/** Default `steps`. */\n\tspacing?: VectorBlendSpacing;\n\t/** Steps between each pair of keys with `steps` spacing (default 5). */\n\tsteps?: number;\n\t/** Distance between steps along the spine with `distance` spacing (default 20). */\n\tdistance?: number;\n\t/** Turn the steps with the spine's direction (default `false`: they keep the keys' orientation). */\n\torientToSpine?: boolean;\n\t/** Move anchors in straight lines instead of the rotation-aware morph (default `false`). */\n\tlinear?: boolean;\n}\n\n/** A live blend: the group's keys plus how the in-betweens are made and laid out. */\nexport interface VectorBlend extends VectorBlendOptions {\n\t/**\n\t * A replaced spine in the group's space: the steps follow it instead of the straight lines\n\t * between the keys' centres (the keys sit along it, spread evenly by arc length).\n\t */\n\tspine?: VectorSubpath | null;\n\t/** The anchor of each key's first subpath its blend starts from, by key id (the Blend tool's clicks). */\n\tstarts?: Record<string, number>;\n}\n\n/**\n * How a mask group's mask (its first, bottom child) hides the rest: `clip` (a clipping mask: the\n * mask's outline, fully opaque; its paint is not drawn), `alpha` (an opacity mask by the mask's\n * drawn alpha: soft edges, gradients and opacity count) or `luminance` (by its brightness times\n * its alpha: white shows, black hides).\n */\nexport type VectorMaskType = 'clip' | 'alpha' | 'luminance';\nexport const VECTOR_MASK_TYPES: readonly VectorMaskType[] = ['clip', 'alpha', 'luminance'];\n\n/** A group's mask settings (`VectorGroupNode.mask`). */\nexport interface VectorMask {\n\ttype: VectorMaskType;\n\t/** Show the contents where the mask hides them and hide them where it shows them. Default false. */\n\tinvert?: boolean;\n}\n\n/** A group of nodes that select and transform together. */\n/**\n * A group drawn by a provider vector effect (see `@pixerate/editor/effects`): its children are the\n * effect's picture, made again when its values change. Kept as plain shapes without a provider.\n */\nexport interface VectorProviderEffect {\n\t/** The provider's effect id. */\n\teffect: string;\n\tprovider?: string;\n\tname?: string;\n\t/** Control values (over the effect's defaults). */\n\tvalues: Record<string, number | string | boolean | readonly number[]>;\n}\n\nexport interface VectorGroupNode extends VectorNodeBase {\n\ttype: 'group';\n\tchildren: VectorNode[];\n\t/** The provider vector effect this group shows (see `VectorProviderEffect`). */\n\tproviderEffect?: VectorProviderEffect | null;\n\t/**\n\t * Makes the group a live blend: its children that are not `blendStep`s are the keys, in\n\t * stacking order, and the steps between them are regenerated whenever a key changes.\n\t */\n\tblend?: VectorBlend | null;\n\t/**\n\t * Makes the group a live boolean: its children stay editable operands, folded bottom to top\n\t * (each by its own `booleanOperation` or this one), and the group draws as the result in the\n\t * bottom operand's style.\n\t */\n\tliveBoolean?: VectorBooleanOperation | null;\n\t/**\n\t * Makes the group a mask group: its first (bottom) child is the mask and the children above it\n\t * show only where the mask lets them (see `VectorMaskType`). Hit-testing, bounds, snapping and\n\t * booleans use the masked result. A hidden mask child turns the mask off (the contents draw\n\t * whole). The group's own opacity, blend mode and filters apply to the masked result, and its\n\t * path effects to the contents (not the mask). Ignored on blends and live booleans.\n\t */\n\tmask?: VectorMask | null;\n\t/**\n\t * Makes the group a frame (see `VectorFrame`): it draws its fill below the children, clips them,\n\t * selects and snaps by its rectangle, and lays its children out by their `resizing` constraints\n\t * when resized. Ignored on blends, live booleans and mask groups.\n\t */\n\tframe?: VectorFrame | null;\n\t/**\n\t * Makes the group a live symmetry group: it draws its children and their mirrored (or rotated)\n\t * copies, regenerated whenever a child changes. Ignored on blends, live booleans, mask groups\n\t * and frames.\n\t */\n\tsymmetry?: VectorSymmetry | null;\n}\n\n/**\n * How a symmetry group repeats its children: mirrored across a `vertical`, `horizontal` or\n * `diagonal` axis, across both axes (`dual`: four quarters), or `radial`ly round the centre\n * (`copies` turns, each mirrored too with `mirror`, like a kaleidoscope).\n */\nexport type VectorSymmetryMode = 'vertical' | 'horizontal' | 'dual' | 'diagonal' | 'radial';\nexport const VECTOR_SYMMETRY_MODES: readonly VectorSymmetryMode[] = ['vertical', 'horizontal', 'dual', 'diagonal', 'radial'];\n\n/** A symmetry group's settings (`VectorGroupNode.symmetry`). */\nexport interface VectorSymmetry {\n\tmode: VectorSymmetryMode;\n\t/** Where the axes cross (the group's own space). */\n\tcenter: Vec2;\n\t/** Turn of the axes, degrees clockwise (default 0). */\n\trotation?: number;\n\t/** Radial: how many turns round the circle (2–64, default 6). */\n\tcopies?: number;\n\t/** Radial: mirror each turn too (default false). */\n\tmirror?: boolean;\n}\n\n/**\n * The character style of text (a font and how it is set). Sizes are document units; `tracking` is in\n * 1/1000 em. Paint comes from the node's fills and strokes (and a run's own `fill`).\n */\nexport interface VectorCharacterStyle {\n\t/** Family name (\"Inter\"); a family the shaper lacks draws in a fallback and is listed as missing. */\n\tfontFamily: string;\n\t/** CSS weight, 1–1000 (400 regular, 700 bold). */\n\tfontWeight: number;\n\t/** Default false. */\n\titalic?: boolean;\n\tfontSize: number;\n\t/** Letter spacing in 1/1000 em (default 0). */\n\ttracking?: number;\n\t/** Baseline-to-baseline distance; absent: auto (`autoLeading` × size). */\n\tleading?: number;\n\t/** Raises (positive) or lowers the text (default 0). */\n\tbaselineShift?: number;\n\tunderline?: boolean;\n\tstrikethrough?: boolean;\n}\n\n/** Character style fields a run can set over the node's own style, plus its own fill. */\nexport type VectorTextRunStyle = Partial<VectorCharacterStyle> & {\n\t/** The run's fill: replaces the paint of the node's top fill for these characters. */\n\tfill?: VectorPaint;\n};\n\n/** A style over `length` UTF-16 code units of the text, in order. */\nexport interface VectorTextRun {\n\tlength: number;\n\tstyle: VectorTextRunStyle;\n}\n\nexport type VectorTextAlign = 'left' | 'center' | 'right' | 'justify';\nexport const VECTOR_TEXT_ALIGNS: readonly VectorTextAlign[] = ['left', 'center', 'right', 'justify'];\n\n/** Paragraph settings of a text node (all its paragraphs). Lengths in document units. */\nexport interface VectorParagraphStyle {\n\t/** Default `left`. `justify` stretches every line of area text but a paragraph's last; on a path it spreads the text over the path. */\n\talign?: VectorTextAlign;\n\t/** Auto leading as a multiple of the font size (default 1.2). */\n\tautoLeading?: number;\n\tfirstLineIndent?: number;\n\tstartIndent?: number;\n\tendIndent?: number;\n\tspaceBefore?: number;\n\tspaceAfter?: number;\n}\n\n/** Where text on a path sits across the path: its baseline, ascender, descender or centre on the line. */\nexport type VectorPathTextBaseline = 'baseline' | 'ascender' | 'descender' | 'center';\nexport const VECTOR_PATH_TEXT_BASELINES: readonly VectorPathTextBaseline[] = ['baseline', 'ascender', 'descender', 'center'];\n\n/**\n * Where a text node's text goes, in the node's own space:\n * - `point`: one line per paragraph, the first baseline starting at (`x`, `y`);\n * - `area`: lines wrapped inside the box at (`x`, `y`) of `width` × `height` (lines that do not fit\n * are hidden: the text overflows);\n * - `path`: one line set along `path` (paragraph breaks become spaces), from `start` to `end`\n * (distances from the path's ends), turned with the path (`orientation: 'rotate'`) or upright.\n * `flip` runs the text the other way, on the other side.\n */\nexport type VectorTextFrame =\n\t| { kind: 'point'; x: number; y: number }\n\t| { kind: 'area'; x: number; y: number; width: number; height: number }\n\t| {\n\t\t\tkind: 'path';\n\t\t\tpath: VectorSubpath;\n\t\t\t/** Margin from the path's start (default 0). */\n\t\t\tstart?: number;\n\t\t\t/** Margin from the path's end (default 0). */\n\t\t\tend?: number;\n\t\t\tflip?: boolean;\n\t\t\t/** Default `rotate`. */\n\t\t\torientation?: 'rotate' | 'upright';\n\t\t\t/** Default `baseline`. */\n\t\t\tbaseline?: VectorPathTextBaseline;\n\t };\n\n/**\n * Text: a string with a character style, optional styled runs and a paragraph style, set in a\n * frame. It paints with the node's fills and strokes like a path. Layout and glyphs come from the\n * editor's text shaper (`setVectorTextShaper`); with an outline shaper the text draws as glyph\n * outlines (so path effects, envelopes, booleans and Create Outlines work), otherwise as SVG text.\n */\nexport interface VectorTextNode extends VectorNodeBase, VectorStyle {\n\ttype: 'text';\n\ttext: string;\n\t/** The base character style. */\n\tfont: VectorCharacterStyle;\n\t/** Runs over the text, each overriding some fields of `font` (absent: one style throughout). */\n\truns?: VectorTextRun[] | null;\n\tparagraph?: VectorParagraphStyle | null;\n\tframe: VectorTextFrame;\n}\n\n/**\n * Per-instance changes to a symbol's art: every fill and / or stroke of the art painted with one\n * paint (a tint), and art nodes (by their id in the symbol) hidden.\n */\nexport interface VectorInstanceOverrides {\n\tfill?: VectorPaint;\n\tstroke?: VectorPaint;\n\t/** Ids of nodes of the symbol's art (top-level or nested) not drawn in this instance. */\n\thidden?: string[];\n}\n\n/**\n * A placed copy of a symbol (`VectorDocument.symbols`): it draws the symbol's art through its\n * `transform`, which, unlike other nodes', may scale and skew. Editing the symbol changes every\n * instance.\n */\nexport interface VectorInstanceNode extends VectorNodeBase {\n\ttype: 'instance';\n\tsymbolId: string;\n\t/** Strokes (and other lengths of the art's paint) scale with the instance (default true, as in Illustrator). */\n\tscaleStrokes?: boolean;\n\toverrides?: VectorInstanceOverrides | null;\n\t/**\n\t * The symbol's art, resolved by the editor (the same array as the symbol's `nodes`). Not part of\n\t * the stored document: `VectorEditorController.toJSON` and SVG export leave it out, and loading\n\t * resolves it again (`resolveVectorSymbols`).\n\t */\n\tart?: VectorNode[];\n}\n\nexport type VectorNode = VectorPathNode | VectorGroupNode | VectorTextNode | VectorInstanceNode;\n\n/** A symbol: reusable art its instances draw. */\nexport interface VectorSymbol {\n\tid: string;\n\tname: string;\n\t/** The art, bottom to top, in the symbol's own space (its origin is the registration point instances are placed by). */\n\tnodes: VectorNode[];\n}\n\n/** A vector drawing: an artboard and its nodes, bottom to top. */\nexport interface VectorDocument {\n\twidth: number;\n\theight: number;\n\t/** Artboard colour (default: transparent). */\n\tbackground?: string;\n\tnodes: VectorNode[];\n\t/** Symbols the document's instances draw (see `VectorInstanceNode`). */\n\tsymbols?: VectorSymbol[];\n\t/** Constraints between anchors, segments and circles, solved after every edit. */\n\tconstraints?: VectorConstraint[];\n\t/** Named values the constraints' expressions use. */\n\tparameters?: VectorParameter[];\n}\n\n/**\n * Constraint kinds (CAD-style parametric drawing). Geometric: `coincident` (two points, a point on\n * a segment's line, or a point on a circle), `collinear` (two segments on one line), `concentric`\n * (two circles, or a circle's centre on a point), `fix`, `parallel`, `perpendicular`, `horizontal`\n * / `vertical` (a segment, or two points level), `tangent` (a segment and a circle, two circles, or\n * G1 at an anchor: its handles in line), `smooth` (G2 at an anchor: G1 and equal curvature),\n * `symmetric` (two points about a segment's line) and `equal` (segment lengths or radii).\n * Dimensional (with a `value`): `distance`, `angle` (degrees), `radius` and `diameter`.\n */\nexport type VectorConstraintKind =\n\t| 'coincident'\n\t| 'collinear'\n\t| 'concentric'\n\t| 'fix'\n\t| 'parallel'\n\t| 'perpendicular'\n\t| 'horizontal'\n\t| 'vertical'\n\t| 'tangent'\n\t| 'smooth'\n\t| 'symmetric'\n\t| 'equal'\n\t| 'distance'\n\t| 'angle'\n\t| 'radius'\n\t| 'diameter';\nexport const VECTOR_CONSTRAINT_KINDS: readonly VectorConstraintKind[] = [\n\t'coincident',\n\t'collinear',\n\t'concentric',\n\t'fix',\n\t'parallel',\n\t'perpendicular',\n\t'horizontal',\n\t'vertical',\n\t'tangent',\n\t'smooth',\n\t'symmetric',\n\t'equal',\n\t'distance',\n\t'angle',\n\t'radius',\n\t'diameter'\n];\n\n/**\n * What a constraint refers to: an anchor of a path (by its stable `id`), one of the anchor's\n * handles, the segment from the anchor to the next one, or (no `anchor`) a whole path as a circle\n * (its centre and radius, for closed round paths).\n */\nexport interface VectorGeomRef {\n\tnodeId: string;\n\t/** The anchor's `id` (see `VectorAnchor.id`). */\n\tanchor?: string;\n\t/** With `anchor`: the handle instead of the anchor point. */\n\thandle?: 'in' | 'out';\n\t/** With `anchor`: the segment from it to the next anchor. */\n\tsegment?: boolean;\n\t/** Without `anchor`: the path as a circle. */\n\tcircle?: boolean;\n}\n\n/** A constraint kept by the document and solved after every edit. */\nexport interface VectorConstraint {\n\tid: string;\n\tkind: VectorConstraintKind;\n\trefs: VectorGeomRef[];\n\t/** Dimensional constraints: the value as an expression (document units, degrees for angles), e.g. `\"40\"` or `\"w / 2\"`. */\n\tvalue?: string;\n\t/** Dimensional constraints: a name other expressions can use (`d1`, `ang2`). */\n\tname?: string;\n\t/** `distance`: measured along the line between (default), or only horizontally or vertically. */\n\taxis?: 'aligned' | 'horizontal' | 'vertical';\n}\n\n/** A named value constraints' expressions can use. */\nexport interface VectorParameter {\n\tname: string;\n\t/** An expression (numbers, other names, `+ - * /`, parentheses, `pi`). */\n\tvalue: string;\n\tdescription?: string;\n}\n\n/** An axis-aligned rectangle. */\nexport interface VectorBounds {\n\tx: number;\n\ty: number;\n\twidth: number;\n\theight: number;\n}\n\n/** Identifies one anchor of a path node. */\nexport interface VectorAnchorRef {\n\tnodeId: string;\n\tsubpath: number;\n\tindex: number;\n}\n\n/** Identifies one handle of an anchor. */\nexport interface VectorHandleRef extends VectorAnchorRef {\n\thandle: 'in' | 'out';\n}\n\n/**\n * Canvas tools. `direct` edits anchors, handles and segments; the shape tools drag out a new\n * shape; `scissors` cuts a path at a point, `knife` cuts filled shapes along a freehand stroke,\n * `eraser` rubs out the area under one and `width` drags a stroke's width at a point.\n * `shapeBuilder` merges (Alt: deletes) the faces the selected shapes make, and `paintBucket`\n * fills the region the visible outlines enclose around a click with a new shape. `blend`\n * blends the shape clicked first into the one clicked next (clicking an anchor of a closed path\n * starts the blend there). `envelope` edits the mesh of the selection's envelope: drag its\n * anchors and handles, or inside a patch to pull the surface. `type` adds point text (click) or\n * area text (drag) and edits text it clicks; `typePath` sets text along the path it clicks. `frame`\n * drags out a frame (`VectorGroupNode.frame`), taking in the top-level objects it fully encloses.\n * `connector` drags a connector between objects, gluing each end to the side it starts or ends on.\n */\nexport type VectorTool =\n\t| 'select'\n\t| 'direct'\n\t| 'pen'\n\t| 'pencil'\n\t| 'rect'\n\t| 'ellipse'\n\t| 'polygon'\n\t| 'star'\n\t| 'line'\n\t| 'scissors'\n\t| 'knife'\n\t| 'eraser'\n\t| 'width'\n\t| 'shapeBuilder'\n\t| 'paintBucket'\n\t| 'blend'\n\t| 'gradient'\n\t| 'envelope'\n\t| 'type'\n\t| 'typePath'\n\t| 'frame'\n\t| 'connector';\n\nexport const VECTOR_TOOLS: readonly VectorTool[] = [\n\t'select',\n\t'direct',\n\t'pen',\n\t'pencil',\n\t'rect',\n\t'ellipse',\n\t'polygon',\n\t'star',\n\t'line',\n\t'scissors',\n\t'knife',\n\t'eraser',\n\t'width',\n\t'shapeBuilder',\n\t'paintBucket',\n\t'blend',\n\t'gradient',\n\t'envelope',\n\t'type',\n\t'typePath',\n\t'frame',\n\t'connector'\n];\n\n/** Keyboard modifiers held during a pointer event. */\nexport interface VectorModifiers {\n\tshift?: boolean;\n\talt?: boolean;\n\t/** Cmd on macOS, Ctrl elsewhere. */\n\tmod?: boolean;\n}\n\n/** The eight resize handles of a selection box and the rotation handle. */\nexport type VectorTransformHandle = 'nw' | 'n' | 'ne' | 'e' | 'se' | 's' | 'sw' | 'w' | 'rotate';\n\nexport const VECTOR_TRANSFORM_HANDLES: readonly VectorTransformHandle[] = ['nw', 'n', 'ne', 'e', 'se', 's', 'sw', 'w', 'rotate'];\n\n/** Pan and zoom of the canvas: `screen = document × zoom + (x, y)`. */\nexport interface VectorViewport {\n\t/** Screen position of the document origin, in screen pixels. */\n\tx: number;\n\ty: number;\n\tzoom: number;\n}\n\n/** What the next shape and pen path are drawn with. */\nexport interface VectorDefaults extends VectorStyle {\n\t/** Sides of the polygon tool (default 6). */\n\tpolygonSides?: number;\n\t/** Points of the star tool (default 5). */\n\tstarPoints?: number;\n\t/** Inner radius of the star tool as a fraction of the outer one (default 0.5). */\n\tstarInnerRatio?: number;\n\t/** Live corner radius the rectangle, polygon and star tools give their corners (default 0). */\n\tcornerRadius?: number;\n\t/** Corner kind of those tools (default `round`). */\n\tcornerKind?: VectorCornerKind;\n}\n\nexport type VectorAlign = 'left' | 'center' | 'right' | 'top' | 'middle' | 'bottom';\nexport type VectorDistribute = 'horizontal' | 'vertical';\nexport type VectorBooleanOperation = 'union' | 'subtract' | 'intersect' | 'exclude';\n/**\n * Pathfinder operations: `divide` (every face its own shape), `trim` (hidden parts removed),\n * `merge` (Trim, then touching parts of one fill joined), `crop` (the top shape crops the others),\n * `outline` (outlines cut into open strokes where they meet) and `minusBack` (the top shape minus\n * everything below it).\n */\nexport type VectorPathfinderOperation = 'divide' | 'trim' | 'merge' | 'crop' | 'outline' | 'minusBack';\nexport const VECTOR_PATHFINDER_OPERATIONS: readonly VectorPathfinderOperation[] = ['divide', 'trim', 'merge', 'crop', 'outline', 'minusBack'];\nexport type VectorArrange = 'front' | 'forward' | 'backward' | 'back';\n/** Average: line anchors up on a horizontal line (same y), a vertical one (same x), or both. */\nexport type VectorAverageAxis = 'horizontal' | 'vertical' | 'both';\n\n/**\n * Live path effects (After Effects' path operators): `trim` (Trim Paths), `roundCorners`,\n * `puckerBloat`, `twist`, `zigzag`, `wiggle` (Wiggle Paths), `offset` (Offset Paths), `merge`\n * (Merge Paths), `repeater`, `envelope` (an envelope distortion: a warp preset or a mesh),\n * `contour` (CorelDRAW's Contour: concentric offset steps blending toward end colours) and\n * `blockShadow` (CorelDRAW's Block Shadow: the shape swept along a direction, under it).\n */\nexport type VectorEffectType = 'trim' | 'roundCorners' | 'puckerBloat' | 'twist' | 'zigzag' | 'wiggle' | 'offset' | 'merge' | 'repeater' | 'envelope' | 'contour' | 'blockShadow';\nexport const VECTOR_EFFECT_TYPES: readonly VectorEffectType[] = ['trim', 'roundCorners', 'puckerBloat', 'twist', 'zigzag', 'wiggle', 'offset', 'merge', 'repeater', 'envelope', 'contour', 'blockShadow'];\n\n/** Warp presets (Photoshop's fifteen, in menu order); shared with the image editor (`src/geom`). */\nexport type VectorWarpStyle = WarpStyle;\n\n/**\n * A grid of bicubic Bézier patches mapping a source box onto the plane. `us` / `vs` are the patch\n * boundaries as fractions of the box (increasing, first 0, last 1); `points` is the\n * `(3·(us.length − 1) + 1) × (3·(vs.length − 1) + 1)` control grid, row by row, in the node's own\n * space. Neighbouring patches share their edge row: anchors sit where both indices are multiples\n * of 3, handles where one is. Shared with the image editor (`src/geom`).\n */\nexport type VectorWarpMesh = WarpMesh;\n\n/** Merge Paths modes: a compound path (no boolean), union, the first minus the others, intersection or exclusion. */\nexport type VectorMergeMode = 'merge' | 'add' | 'subtract' | 'intersect' | 'exclude';\nexport const VECTOR_MERGE_MODES: readonly VectorMergeMode[] = ['merge', 'add', 'subtract', 'intersect', 'exclude'];\n\n/** Parameters of each effect type. Lengths are in the node's own units, angles in degrees, percentages 0–100. */\nexport interface VectorEffectParamsMap {\n\ttrim: {\n\t\t/** Start and end of the kept part, percent of the length (swapped when start > end). */\n\t\tstart: number;\n\t\tend: number;\n\t\t/** Shifts both, in degrees (360° = once round). */\n\t\toffset: number;\n\t\t/**\n\t\t * `simultaneous`: every path trimmed by the same fractions of its own length;\n\t\t * `individual`: the paths laid end to end in stacking order and trimmed as one length.\n\t\t */\n\t\tmode: 'simultaneous' | 'individual';\n\t};\n\troundCorners: { radius: number };\n\t/** Percent, −100 (pucker: spiky) to 100 (bloat: bulging). */\n\tpuckerBloat: { amount: number };\n\ttwist: {\n\t\t/** Turn at the farthest point from the centre (none at the centre). */\n\t\tangle: number;\n\t\t/** The centre as an offset from the middle of the paths' bounds. */\n\t\tcenter: Vec2;\n\t};\n\tzigzag: {\n\t\t/** How far the points move to either side. */\n\t\tsize: number;\n\t\t/** Ridges per segment. */\n\t\tridges: number;\n\t\t/** Rounded waves instead of sharp zig zags. */\n\t\tsmooth: boolean;\n\t};\n\twiggle: {\n\t\t/** Largest displacement. */\n\t\tsize: number;\n\t\t/** Points added per segment. */\n\t\tdetail: number;\n\t\tsmooth: boolean;\n\t\t/** Wiggles per second. */\n\t\tspeed: number;\n\t\t/** Percent: how much neighbouring points move together. */\n\t\tcorrelation: number;\n\t\t/** Degrees (360° = one wiggle). */\n\t\tphase: number;\n\t\t/** The same seed (and time) always gives the same wiggle. */\n\t\tseed: number;\n\t\t/** Seconds: where along the wiggle's motion it is drawn. */\n\t\ttime: number;\n\t};\n\toffset: {\n\t\t/** Grows (positive) or shrinks (negative) the shapes. */\n\t\tamount: number;\n\t\tjoin: VectorLineJoin;\n\t\tmiterLimit: number;\n\t\t/** Copies, copy i offset by `amount · (i + 1 + copyOffset)`. */\n\t\tcopies: number;\n\t\tcopyOffset: number;\n\t};\n\tmerge: { mode: VectorMergeMode };\n\trepeater: {\n\t\t/** Copies, the original included; a fraction fades the last copy. */\n\t\tcopies: number;\n\t\t/** Shifts the copies along: copy i is transformed `i + offset` times. */\n\t\toffset: number;\n\t\t/** Each step: move, about `anchor` turn by `rotation` and scale by `scale` percent. */\n\t\tposition: Vec2;\n\t\t/** Offset from the middle of the paths' bounds. */\n\t\tanchor: Vec2;\n\t\trotation: number;\n\t\tscale: Vec2;\n\t\t/** Percent opacity of the first and last copies (in between interpolated). */\n\t\tstartOpacity: number;\n\t\tendOpacity: number;\n\t\t/** `below`: each copy draws under the one before it; `above`: over it. */\n\t\tcomposite: 'below' | 'above';\n\t};\n\t/**\n\t * Contour: concentric copies of each shape offset `offset` apart, `steps` of them `inside`,\n\t * `outside`, or `center` (inside until the shape is used up), their fill and stroke blending\n\t * from the shape's own colours to `fillColor` / `strokeColor` (null keeps the colour).\n\t * `acceleration` (−100…100) bunches the colour change toward the end (positive) or start.\n\t */\n\tcontour: {\n\t\tdirection: 'inside' | 'outside' | 'center';\n\t\tsteps: number;\n\t\toffset: number;\n\t\tjoin: VectorLineJoin;\n\t\tmiterLimit: number;\n\t\tfillColor: string | null;\n\t\tstrokeColor: string | null;\n\t\tacceleration: number;\n\t};\n\t/**\n\t * Block shadow (CorelDRAW's Block Shadow; a long shadow when it fades): each shape swept\n\t * `distance` along `angle` (degrees, 0 right, 90 down, in the node's own space) as one solid\n\t * shape under the art, in `color` (null: the shape's own solid fill) at `opacity` percent,\n\t * fading to `endOpacity` percent at the far end.\n\t */\n\tblockShadow: {\n\t\tangle: number;\n\t\tdistance: number;\n\t\tcolor: string | null;\n\t\topacity: number;\n\t\tendOpacity: number;\n\t};\n\t/**\n\t * Envelope distortion: the paths above it are mapped from their combined bounds through a warp\n\t * preset (bend and horizontal / vertical distortion in percent) or, with style `mesh`, through\n\t * `mesh` (null: the flat mesh of `columns × rows` patches over the bounds). The bounds are\n\t * taken afresh each time, so editing the contents keeps the envelope.\n\t */\n\tenvelope: {\n\t\tstyle: VectorWarpStyle | 'mesh';\n\t\tbend: number;\n\t\thorizontal: number;\n\t\tvertical: number;\n\t\torientation: 'horizontal' | 'vertical';\n\t\t/** Patches of the mesh (a preset turns into a mesh of this size when it is edited). */\n\t\trows: number;\n\t\tcolumns: number;\n\t\tmesh: VectorWarpMesh | null;\n\t};\n}\n\n/** One entry of an effect stack. */\nexport type VectorEffect = {\n\t[K in VectorEffectType]: {\n\t\t/** Unique within the node. */\n\t\tid: string;\n\t\ttype: K;\n\t\t/** Disabled effects are skipped. Default true. */\n\t\tenabled?: boolean;\n\t\tparams: VectorEffectParamsMap[K];\n\t};\n}[VectorEffectType];\n\n/** Identifies one segment of a path node: from anchor `segment` to the next. */\nexport interface VectorSegmentRef {\n\tnodeId: string;\n\tsubpath: number;\n\tsegment: number;\n}\n\n/**\n * Visual filters: `dropShadow` (the node's silhouette, offset and blurred, under it),\n * `innerShadow` (a shadow cast inside the edges), `outerGlow` / `innerGlow` (an unoffset glow\n * outside or inside the edges), `layerBlur` (the whole node blurred) and `feather` (edges faded\n * to transparent).\n */\nexport type VectorFilterType = 'dropShadow' | 'innerShadow' | 'outerGlow' | 'innerGlow' | 'layerBlur' | 'feather';\nexport const VECTOR_FILTER_TYPES: readonly VectorFilterType[] = ['dropShadow', 'innerShadow', 'outerGlow', 'innerGlow', 'layerBlur', 'feather'];\n\n/** A shadow or glow: colour, offset, blur and spread in the node's own units. */\ninterface VectorShadowParams {\n\tcolor: string;\n\t/** 0–1: multiplies the colour's own alpha. */\n\topacity: number;\n\t/** Blur radius (the SVG / CSS standard deviation is half of it). */\n\tblur: number;\n\t/** Grows the silhouette before blurring (inner effects: chokes it inwards). */\n\tspread: number;\n}\n\n/** Parameters of each filter type. Lengths are in the node's own units. */\nexport interface VectorFilterParamsMap {\n\tdropShadow: VectorShadowParams & { offsetX: number; offsetY: number };\n\tinnerShadow: VectorShadowParams & { offsetX: number; offsetY: number };\n\touterGlow: VectorShadowParams;\n\tinnerGlow: VectorShadowParams;\n\tlayerBlur: { radius: number };\n\t/** Fades the edges over `radius` inwards. */\n\tfeather: { radius: number };\n}\n\n/** One entry of a node's filter stack. */\nexport type VectorFilter = {\n\t[K in VectorFilterType]: {\n\t\t/** Unique within the node. */\n\t\tid: string;\n\t\ttype: K;\n\t\t/** Disabled filters are skipped. Default true. */\n\t\tenabled?: boolean;\n\t\tparams: VectorFilterParamsMap[K];\n\t};\n}[VectorFilterType];\n","/**\n * Vector gradients: sampling (stop midpoints, smoothness, sRGB / linear-light / Oklab\n * interpolation), geometry (a three-point frame: start, end and the secondary-axis \"width\"\n * point, in the shape's bounding box or its own space; focal point and radius), spread modes and\n * DOM-free SVG paint servers for every style.\n *\n * Linear and radial gradients become `<linearGradient>` / `<radialGradient>` in\n * `userSpaceOnUse` with a `gradientTransform` (so fill, stroke parts and effect copies share one\n * frame, and a box with no height still paints). Midpoints, smoothness and non-sRGB\n * interpolation are not native to SVG: they export as extra stops (`expandVectorGradientStops`)\n * close to the true curve. Reflected gradients are a linear gradient with mirrored stops (or\n * `spreadMethod=\"reflect\"`). Conic and diamond gradients have no SVG element: they become a\n * `<pattern>` in user space whose tiles each carry a linear gradient — 4 exact quadrants for a\n * diamond (t = |u| + |v| is linear in each), thin wedges for a conic gradient.\n *\n * Ported (re-expressed in TypeScript) from the ArtCraft apps (MIT OR Apache-2.0, see\n * THIRD_PARTY_NOTICES.md): vectorcraft `crates/color/src/gradient.rs` (`Gradient::sample_with`\n * midpoint mapping, `expanded_stops`, `reverse`, `span`, stop editing helpers and\n * `GradientGeom::param_at` / `set_focal`), photocraft `crates/compose/src/gradient_fill.rs`\n * (`midpoint_remap`, the Linear / Radial / Angle / Reflected / Diamond styles of `gradient_t`),\n * photocraft `crates/io/src/gradient_bake.rs` (`eval`: smoothness as a Catmull-Rom blend and the\n * interpolation spaces), effectcraft `crates/render/src/shapes.rs` (`GradientRamp::t`, the focal\n * ray), figcraft `crates/color/src/lib.rs` (`GradientKind` angular / diamond and the three-handle\n * unit-box frame) and vectorcraft `crates/svg/src/import/spread.rs` (`expand`: spread modes as\n * repeated stop periods).\n */\nimport { isVectorShadedPaint, mapVectorShadedPaint, transformVectorShadedPaint } from './shading.js';\nimport { hexToRgba, normalizeTokenColor, rgbaToHex } from '../tokens/color.js';\nimport { rgbToOklab, oklabToRgb } from '../animation/color.js';\nimport { angleToSvgLinearCoords, type SvgGradientDef, type SvgGradientStop } from '../canvas/gradient.js';\nimport type {\n\tVec2,\n\tVectorBounds,\n\tVectorGradient,\n\tVectorGradientInterpolation,\n\tVectorGradientSpread,\n\tVectorGradientStop,\n\tVectorGradientType,\n\tVectorGradientUnits,\n\tVectorMatrix,\n\tVectorPaint\n} from './types.js';\nimport { VECTOR_GRADIENT_INTERPOLATIONS, VECTOR_GRADIENT_SPREADS, VECTOR_GRADIENT_TYPES, VECTOR_STROKE_GRADIENT_MODES } from './types.js';\n\n\n// ---------------------------------------------------------------------------\n// Small maths\n// ---------------------------------------------------------------------------\n\nconst clamp = (v: number, lo: number, hi: number) => Math.min(hi, Math.max(lo, v));\nconst IDENTITY: VectorMatrix = [1, 0, 0, 1, 0, 0];\n/** `a` then `b`. */\nconst mul = (a: VectorMatrix, b: VectorMatrix): VectorMatrix => [\n\tb[0] * a[0] + b[2] * a[1],\n\tb[1] * a[0] + b[3] * a[1],\n\tb[0] * a[2] + b[2] * a[3],\n\tb[1] * a[2] + b[3] * a[3],\n\tb[0] * a[4] + b[2] * a[5] + b[4],\n\tb[1] * a[4] + b[3] * a[5] + b[5]\n];\nconst apply = (m: VectorMatrix, p: Vec2): Vec2 => ({ x: m[0] * p.x + m[2] * p.y + m[4], y: m[1] * p.x + m[3] * p.y + m[5] });\nconst invert = (m: VectorMatrix): VectorMatrix | null => {\n\tconst [a, b, c, d, e, f] = m;\n\tconst det = a * d - b * c;\n\tif (!Number.isFinite(det) || Math.abs(det) < 1e-18) return null;\n\treturn [d / det, -b / det, -c / det, a / det, (c * f - d * e) / det, (b * e - a * f) / det];\n};\nconst isIdentity = (m: VectorMatrix) => m[0] === 1 && m[1] === 0 && m[2] === 0 && m[3] === 1 && m[4] === 0 && m[5] === 0;\nconst sub = (a: Vec2, b: Vec2): Vec2 => ({ x: a.x - b.x, y: a.y - b.y });\nconst add = (a: Vec2, b: Vec2): Vec2 => ({ x: a.x + b.x, y: a.y + b.y });\nconst scale = (a: Vec2, k: number): Vec2 => ({ x: a.x * k, y: a.y * k });\nconst dot = (a: Vec2, b: Vec2) => a.x * b.x + a.y * b.y;\n/** 90° clockwise on screen (y down): the secondary axis of a frame. */\nconst perp = (v: Vec2): Vec2 => ({ x: -v.y, y: v.x });\nconst finitePoint = (p: unknown): p is Vec2 => !!p && typeof p === 'object' && Number.isFinite((p as Vec2).x) && Number.isFinite((p as Vec2).y);\n\nconst fmt = (n: number, digits = 4) => {\n\tconst k = 10 ** digits;\n\tconst v = Math.round(n * k) / k;\n\treturn Object.is(v, -0) ? '0' : String(v);\n};\nconst fmtMatrix = (m: VectorMatrix) => `matrix(${m.map((n) => fmt(n, 6)).join(' ')})`;\n\n/** True when `paint` is a gradient (any style). */\nexport function isVectorGradient(paint: VectorPaint | undefined): paint is VectorGradient {\n\treturn !!paint && typeof paint === 'object' && VECTOR_GRADIENT_TYPES.includes((paint as VectorGradient).type) && Array.isArray((paint as VectorGradient).stops);\n}\n\n// ---------------------------------------------------------------------------\n// Colours and interpolation spaces\n// ---------------------------------------------------------------------------\n\n/** Straight-alpha sRGB channels, 0–1. */\nexport type VectorRgba = [number, number, number, number];\n\n/** A CSS colour as 0–1 channels (hex, `rgb()`, `transparent`, `black`, `white`), or null. */\nexport function parseVectorColor(color: string): VectorRgba | null {\n\tconst hex = normalizeTokenColor(color);\n\tif (hex === null) return null;\n\tconst c = hexToRgba(hex)!;\n\treturn [c.r, c.g, c.b, c.a];\n}\n\nconst toLinear = (c: number) => (c <= 0.04045 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4);\nconst toGamma = (c: number) => {\n\tconst v = clamp(c, 0, 1);\n\treturn v <= 0.0031308 ? 12.92 * v : 1.055 * v ** (1 / 2.4) - 0.055;\n};\n\nfunction intoSpace(space: VectorGradientInterpolation, [r, g, b]: readonly number[]): [number, number, number] {\n\tif (space === 'linear') return [toLinear(r), toLinear(g), toLinear(b)];\n\tif (space === 'oklab') {\n\t\tconst c = rgbToOklab(r, g, b);\n\t\treturn [c.l, c.a, c.b];\n\t}\n\treturn [r, g, b];\n}\n\nfunction outOfSpace(space: VectorGradientInterpolation, [x, y, z]: readonly number[]): [number, number, number] {\n\tif (space === 'linear') return [toGamma(x), toGamma(y), toGamma(z)];\n\tif (space === 'oklab') {\n\t\tconst c = oklabToRgb({ l: x, a: y, b: z, alpha: 1 });\n\t\treturn [c.r, c.g, c.b];\n\t}\n\treturn [clamp(x, 0, 1), clamp(y, 0, 1), clamp(z, 0, 1)];\n}\n\n// ---------------------------------------------------------------------------\n// Stops\n// ---------------------------------------------------------------------------\n\n/** Least and most a midpoint can be (the stop editors clamp further, to 0.05–0.95). */\nconst MID_MIN = 0.01;\nconst MID_MAX = 0.99;\n/** Fewest stops a gradient keeps when one is removed. */\nexport const VECTOR_GRADIENT_MIN_STOPS = 2;\n\n/**\n * Where relative position `u` of a segment lands once its midpoint is `m` (0.5 = unchanged): the\n * colour is half-way at `m`, linear on either side (photocraft `midpoint_remap`).\n */\nexport function gradientMidpointRemap(u: number, m: number): number {\n\tconst mid = clamp(m, MID_MIN, MID_MAX);\n\tif (Math.abs(mid - 0.5) < 1e-6) return u;\n\treturn u <= mid ? (0.5 * u) / mid : 0.5 + (0.5 * (u - mid)) / (1 - mid);\n}\n\nconst hasMidpoint = (s: VectorGradientStop) => s.midpoint !== undefined && Number.isFinite(s.midpoint) && Math.abs(s.midpoint - 0.5) > 1e-3;\n\n/** The stops sorted by offset (stable), offsets clamped to 0–1, unreadable offsets dropped. */\nexport function sortedVectorGradientStops(g: Pick<VectorGradient, 'stops'>): VectorGradientStop[] {\n\treturn (g.stops ?? [])\n\t\t.filter((s) => s && Number.isFinite(s.offset) && typeof s.color === 'string')\n\t\t.map((s, i) => ({ s: { ...s, offset: clamp(s.offset, 0, 1) }, i }))\n\t\t.sort((a, b) => a.s.offset - b.s.offset || a.i - b.i)\n\t\t.map((e) => e.s);\n}\n\n/** Does the gradient need extra stops to look the same in SVG (midpoints, smoothness or a non-sRGB space)? */\nexport function vectorGradientNeedsExpansion(g: VectorGradient): boolean {\n\treturn (g.interpolation ?? 'srgb') !== 'srgb' || (g.smoothness ?? 0) > 0 || (g.stops ?? []).some(hasMidpoint);\n}\n\ninterface RampPoint {\n\tt: number;\n\t/** Colour channels in the interpolation space. */\n\tv: [number, number, number];\n\t/** Colour alpha × opacity. */\n\ta: number;\n\tmid: number;\n}\n\n/** A gradient's colour ramp, prepared for sampling. */\nexport interface VectorGradientRamp {\n\t/** Straight-alpha sRGB at `t` (clamped to 0–1). */\n\tsample(t: number): VectorRgba;\n}\n\n/**\n * The colour ramp of a gradient (midpoints, smoothness and interpolation space applied), or null\n * when a stop colour is not one `parseVectorColor` reads.\n */\nexport function vectorGradientRamp(g: Pick<VectorGradient, 'stops' | 'interpolation' | 'smoothness'>): VectorGradientRamp | null {\n\tconst space = g.interpolation && VECTOR_GRADIENT_INTERPOLATIONS.includes(g.interpolation) ? g.interpolation : 'srgb';\n\tconst smooth = clamp(Number.isFinite(g.smoothness) ? (g.smoothness as number) : 0, 0, 1);\n\tconst pts: RampPoint[] = [];\n\tfor (const s of sortedVectorGradientStops(g)) {\n\t\tconst c = parseVectorColor(s.color);\n\t\tif (!c) return null;\n\t\tpts.push({ t: s.offset, v: intoSpace(space, c), a: c[3] * clamp(s.opacity ?? 1, 0, 1), mid: s.midpoint ?? 0.5 });\n\t}\n\treturn {\n\t\tsample(t: number): VectorRgba {\n\t\t\tconst n = pts.length;\n\t\t\tif (!n) return [0, 0, 0, 0];\n\t\t\tconst first = pts[0];\n\t\t\tconst last = pts[n - 1];\n\t\t\tconst at = (p: RampPoint): VectorRgba => [...outOfSpace(space, p.v), p.a] as VectorRgba;\n\t\t\tif (!(t > first.t) || n < 2) return at(first);\n\t\t\tif (t >= last.t) return at(last);\n\t\t\tlet i = 0;\n\t\t\twhile (i + 2 < n && !(t >= pts[i].t && t <= pts[i + 1].t)) i++;\n\t\t\tconst p0 = pts[i];\n\t\t\tconst p1 = pts[i + 1];\n\t\t\tconst h = Math.max(p1.t - p0.t, 1e-6);\n\t\t\tconst u = gradientMidpointRemap((t - p0.t) / h, p0.mid);\n\t\t\tconst alpha = p0.a + (p1.a - p0.a) * u;\n\t\t\tif (smooth <= 0) return [...outOfSpace(space, [0, 1, 2].map((c) => p0.v[c] + (p1.v[c] - p0.v[c]) * u)), alpha] as VectorRgba;\n\t\t\t// Catmull-Rom tangents per unit t; the ends use half the chord slope (gradient_bake `eval`).\n\t\t\tconst tangent = (k: number) => {\n\t\t\t\tconst [a, b] = k === 0 ? [0, 1] : k === n - 1 ? [n - 2, n - 1] : [k - 1, k + 1];\n\t\t\t\tconst d = Math.max(pts[b].t - pts[a].t, 1e-6);\n\t\t\t\tconst half = k === 0 || k === n - 1 ? 0.5 : 1;\n\t\t\t\treturn [0, 1, 2].map((c) => ((pts[b].v[c] - pts[a].v[c]) / d) * half);\n\t\t\t};\n\t\t\tconst m0 = tangent(i);\n\t\t\tconst m1 = tangent(i + 1);\n\t\t\tconst u2 = u * u;\n\t\t\tconst u3 = u2 * u;\n\t\t\tconst h00 = 2 * u3 - 3 * u2 + 1;\n\t\t\tconst h10 = u3 - 2 * u2 + u;\n\t\t\tconst h01 = -2 * u3 + 3 * u2;\n\t\t\tconst h11 = u3 - u2;\n\t\t\tconst v = [0, 1, 2].map((c) => {\n\t\t\t\tconst linear = p0.v[c] + (p1.v[c] - p0.v[c]) * u;\n\t\t\t\tconst spline = h00 * p0.v[c] + h10 * h * m0[c] + h01 * p1.v[c] + h11 * h * m1[c];\n\t\t\t\tconst value = linear + (spline - linear) * smooth;\n\t\t\t\t// Smoothness bends the ramp without inventing colours outside the segment.\n\t\t\t\treturn clamp(value, Math.min(p0.v[c], p1.v[c]), Math.max(p0.v[c], p1.v[c]));\n\t\t\t});\n\t\t\treturn [...outOfSpace(space, v), alpha] as VectorRgba;\n\t\t}\n\t};\n}\n\n/** What the gradient paints at `t` (0–1 along its stops): `#rrggbb` and opacity. */\nexport function sampleVectorGradient(g: VectorGradient, t: number): { color: string; opacity: number } {\n\tconst ramp = vectorGradientRamp(g);\n\tif (ramp) {\n\t\tconst [r, gg, b, a] = ramp.sample(t);\n\t\treturn { color: rgbaToHex(r, gg, b), opacity: a };\n\t}\n\t// Unreadable colours: the nearest stop at or before `t`.\n\tconst stops = sortedVectorGradientStops(g);\n\tconst s = [...stops].reverse().find((x) => x.offset <= t) ?? stops[0];\n\treturn s ? { color: s.color, opacity: s.opacity ?? 1 } : { color: '#000000', opacity: 0 };\n}\n\nconst stopOf = (offset: number, c: VectorRgba): VectorGradientStop => {\n\tconst color = rgbaToHex(c[0], c[1], c[2]);\n\tconst opacity = Math.round(c[3] * 1e4) / 1e4;\n\treturn opacity < 1 ? { offset, color, opacity } : { offset, color };\n};\n\nconst maxDiff = (a: VectorRgba, b: VectorRgba) => Math.max(Math.abs(a[0] - b[0]), Math.abs(a[1] - b[1]), Math.abs(a[2] - b[2]), Math.abs(a[3] - b[3]));\nconst lerpRgba = (a: VectorRgba, b: VectorRgba, u: number): VectorRgba => [0, 1, 2, 3].map((c) => a[c] + (b[c] - a[c]) * u) as VectorRgba;\n\n/**\n * Plain stops (no midpoints) that SVG's sRGB interpolation turns into the gradient's colours:\n * the stops as they are when nothing needs expanding; one extra stop per off-centre midpoint for\n * sRGB without smoothness (exact: the midpoint makes each half linear); otherwise stops placed\n * adaptively until linear interpolation between them is within `tolerance` (0–1 per channel,\n * default half a level) of the true curve everywhere they were checked.\n */\nexport function expandVectorGradientStops(g: VectorGradient, options: { tolerance?: number } = {}): VectorGradientStop[] {\n\tconst stops = sortedVectorGradientStops(g);\n\tconst plain = () => stops.map(({ offset, color, opacity }) => (opacity !== undefined && opacity !== 1 ? { offset, color, opacity } : { offset, color }));\n\tif (!vectorGradientNeedsExpansion(g)) return plain();\n\tconst ramp = vectorGradientRamp(g);\n\tif (!ramp || stops.length < 2) return plain();\n\tconst tol = options.tolerance ?? 0.5 / 255;\n\tconst sRgbOnly = (g.interpolation ?? 'srgb') === 'srgb' && !((g.smoothness ?? 0) > 0);\n\tconst own = (s: VectorGradientStop): VectorRgba => {\n\t\tconst c = parseVectorColor(s.color)!;\n\t\treturn [c[0], c[1], c[2], c[3] * clamp(s.opacity ?? 1, 0, 1)];\n\t};\n\tconst out: VectorGradientStop[] = [];\n\tconst push = (offset: number, c: VectorRgba) => out.push(stopOf(offset, c));\n\tfor (let i = 0; i < stops.length; i++) {\n\t\tconst a = stops[i];\n\t\tconst b = stops[i + 1];\n\t\tpush(a.offset, own(a));\n\t\tif (!b || b.offset - a.offset < 1e-9) continue;\n\t\tconst knots = [a.offset];\n\t\tif (hasMidpoint(a)) knots.push(a.offset + (b.offset - a.offset) * clamp(a.midpoint!, MID_MIN, MID_MAX));\n\t\tknots.push(b.offset);\n\t\t// Samples just inside the segment (the ramp at its ends is the neighbouring segment's).\n\t\tconst inside = (t: number) => ramp.sample(clamp(t, a.offset + 1e-9, b.offset - 1e-9));\n\t\tfor (let k = 0; k + 1 < knots.length; k++) {\n\t\t\tconst t0 = knots[k];\n\t\t\tconst t1 = knots[k + 1];\n\t\t\tif (k > 0) push(t0, inside(t0));\n\t\t\tif (sRgbOnly) continue;\n\t\t\tconst refine = (x0: number, c0: VectorRgba, x1: number, c1: VectorRgba, depth: number) => {\n\t\t\t\tconst xm = (x0 + x1) / 2;\n\t\t\t\tconst cm = inside(xm);\n\t\t\t\t// Checked near the ends too: gamma curves bend hardest next to a black channel.\n\t\t\t\tconst ok = depth >= 8 || [0.03, 0.1, 0.25, 0.5, 0.75, 0.9, 0.97].every((f) => maxDiff(inside(x0 + (x1 - x0) * f), lerpRgba(c0, c1, f)) <= tol);\n\t\t\t\tif (ok) return;\n\t\t\t\trefine(x0, c0, xm, cm, depth + 1);\n\t\t\t\tpush(xm, cm);\n\t\t\t\trefine(xm, cm, x1, c1, depth + 1);\n\t\t\t};\n\t\t\trefine(t0, inside(t0), t1, inside(t1), 0);\n\t\t}\n\t}\n\treturn out;\n}\n\n/** Linear interpolation between plain stops (what SVG draws from them), straight alpha. */\nexport function samplePlainStops(stops: readonly VectorGradientStop[], t: number): VectorRgba {\n\tconst parsed = stops.map((s) => {\n\t\tconst c = parseVectorColor(s.color) ?? [0, 0, 0, 1];\n\t\treturn { t: s.offset, c: [c[0], c[1], c[2], c[3] * (s.opacity ?? 1)] as VectorRgba };\n\t});\n\tif (!parsed.length) return [0, 0, 0, 0];\n\tif (t <= parsed[0].t) return parsed[0].c;\n\tfor (let i = 0; i + 1 < parsed.length; i++) {\n\t\tconst a = parsed[i];\n\t\tconst b = parsed[i + 1];\n\t\tif (t <= b.t) return b.t - a.t < 1e-12 ? b.c : lerpRgba(a.c, b.c, (t - a.t) / (b.t - a.t));\n\t}\n\treturn parsed[parsed.length - 1].c;\n}\n\n/** The gradient with its stops reversed, each midpoint measured from the other side (vectorcraft `reverse`). */\nexport function reverseVectorGradient<T extends Pick<VectorGradient, 'stops'>>(g: T): T {\n\tconst stops = sortedVectorGradientStops(g).reverse();\n\tconst next = stops.map((s, i) => {\n\t\tconst following = stops[i + 1];\n\t\tconst mid = following ? 1 - (following.midpoint ?? 0.5) : 0.5;\n\t\tconst { midpoint: _m, ...rest } = s;\n\t\treturn { ...rest, offset: 1 - s.offset, ...(Math.abs(mid - 0.5) > 1e-6 ? { midpoint: mid } : {}) };\n\t});\n\treturn { ...g, stops: next };\n}\n\n/** Stops with `stop` placed by offset (after any at the same offset); returns its index. */\nfunction placeStop(stops: VectorGradientStop[], stop: VectorGradientStop): number {\n\tlet i = stops.findIndex((o) => o.offset > stop.offset);\n\tif (i < 0) i = stops.length;\n\tstops.splice(i, 0, stop);\n\treturn i;\n}\n\n/** A stop added at `offset` painting what the gradient paints there; returns the stops and its index. */\nexport function insertVectorGradientStop(g: VectorGradient, offset: number): { stops: VectorGradientStop[]; index: number } {\n\tconst at = clamp(offset, 0, 1);\n\tconst { color, opacity } = sampleVectorGradient(g, at);\n\tconst stops = sortedVectorGradientStops(g);\n\tconst index = placeStop(stops, opacity < 1 ? { offset: at, color, opacity } : { offset: at, color });\n\treturn { stops, index };\n}\n\n/** Stop `index` moved to `offset` (re-sorted); returns the stops and its new index. */\nexport function moveVectorGradientStop(stops: readonly VectorGradientStop[], index: number, offset: number): { stops: VectorGradientStop[]; index: number } {\n\tconst next = stops.map((s) => ({ ...s }));\n\tif (index < 0 || index >= next.length) return { stops: next, index };\n\tconst [s] = next.splice(index, 1);\n\treturn { stops: next, index: placeStop(next, { ...s, offset: clamp(offset, 0, 1) }) };\n}\n\n/** The stops without stop `index`, or null when that would leave fewer than two. */\nexport function removeVectorGradientStop(stops: readonly VectorGradientStop[], index: number): VectorGradientStop[] | null {\n\tif (stops.length <= VECTOR_GRADIENT_MIN_STOPS || index < 0 || index >= stops.length) return null;\n\treturn stops.filter((_, i) => i !== index);\n}\n\n/** Where (0–1 along the gradient) the midpoint after stop `index` sits, or null for the last stop. */\nexport function vectorGradientMidpointPosition(stops: readonly VectorGradientStop[], index: number): number | null {\n\tconst a = stops[index];\n\tconst b = stops[index + 1];\n\tif (!a || !b) return null;\n\treturn a.offset + (b.offset - a.offset) * (a.midpoint ?? 0.5);\n}\n\n/** The midpoint of stop `index` that puts it at position `pos` (clamped to 0.05–0.95), or null. */\nexport function vectorGradientMidpointFromPosition(stops: readonly VectorGradientStop[], index: number, pos: number): number | null {\n\tconst a = stops[index];\n\tconst b = stops[index + 1];\n\tif (!a || !b) return null;\n\tconst span = Math.max(b.offset - a.offset, 1e-6);\n\treturn clamp((pos - a.offset) / span, 0.05, 0.95);\n}\n\n/**\n * The part of the gradient from `from` to `to` (0–1, either order) as plain stops over 0–1\n * (vectorcraft `span`): the colours at both ends plus the expanded stops between them.\n */\nexport function spanVectorGradientStops(g: VectorGradient, from: number, to: number, expanded = expandVectorGradientStops(g)): VectorGradientStop[] {\n\tif (to < from) {\n\t\tconst s = spanVectorGradientStops(g, to, from, expanded);\n\t\treturn s.map((x) => ({ ...x, offset: 1 - x.offset })).reverse();\n\t}\n\tconst d = to - from;\n\tconst at = (offset: number, t: number) => stopOf(offset, samplePlainStops(expanded, t));\n\tconst out = [at(0, from)];\n\tif (d > 1e-9) for (const s of expanded) if (s.offset > from && s.offset < to) out.push({ ...s, offset: (s.offset - from) / d });\n\tout.push(at(1, to));\n\treturn out;\n}\n\n// ---------------------------------------------------------------------------\n// Geometry\n// ---------------------------------------------------------------------------\n\n/** A gradient's frame points, in its units (see `VectorGradient`). */\nexport interface VectorGradientPoints {\n\tstart: Vec2;\n\tend: Vec2;\n\twidth: Vec2;\n\tfocal: Vec2 | null;\n\tfocalRadius: number;\n\tunits: VectorGradientUnits;\n}\n\n/** Whether the gradient carries its own points (rather than the angle / centre shorthand). */\nexport const hasExplicitGradientGeometry = (g: VectorGradient) => finitePoint(g.start) && finitePoint(g.end);\n\n/** The shorthand of a gradient as points in its bounding box. */\nfunction shorthandPoints(g: VectorGradient): { start: Vec2; end: Vec2; width: Vec2 } {\n\tif (g.type === 'linear' || g.type === 'reflected') {\n\t\tconst c = angleToSvgLinearCoords(Number.isFinite(g.angle) ? (g.angle as number) : 180);\n\t\tconst start = g.type === 'linear' ? { x: c.x1, y: c.y1 } : { x: 0.5, y: 0.5 };\n\t\tconst end = { x: c.x2, y: c.y2 };\n\t\treturn { start, end, width: add(start, perp(sub(end, start))) };\n\t}\n\tconst start = { x: Number.isFinite(g.cx) ? (g.cx as number) : 0.5, y: Number.isFinite(g.cy) ? (g.cy as number) : 0.5 };\n\tconst r = Number.isFinite(g.r) ? (g.r as number) : 0.5;\n\tif (g.type === 'radial') return { start, end: { x: start.x + r, y: start.y }, width: { x: start.x, y: start.y + r } };\n\tconst a = ((Number.isFinite(g.angle) ? (g.angle as number) : 90) * Math.PI) / 180;\n\tconst dir = { x: Math.sin(a), y: -Math.cos(a) };\n\treturn { start, end: add(start, scale(dir, r)), width: add(start, scale(perp(dir), r)) };\n}\n\n/** The gradient's frame points in its units, the shorthand resolved (it is always in the box). */\nexport function vectorGradientPoints(g: VectorGradient): VectorGradientPoints {\n\tconst explicit = hasExplicitGradientGeometry(g);\n\tconst base = explicit ? null : shorthandPoints(g);\n\tconst start = explicit ? { x: g.start!.x, y: g.start!.y } : base!.start;\n\tconst end = explicit ? { x: g.end!.x, y: g.end!.y } : base!.end;\n\tconst width = explicit ? (finitePoint(g.width) ? { x: g.width.x, y: g.width.y } : add(start, perp(sub(end, start)))) : base!.width;\n\treturn {\n\t\tstart,\n\t\tend,\n\t\twidth,\n\t\tfocal: g.type === 'radial' && finitePoint(g.focal) ? { x: g.focal.x, y: g.focal.y } : null,\n\t\tfocalRadius: g.type === 'radial' ? clamp(Number.isFinite(g.focalRadius) ? (g.focalRadius as number) : 0, 0, 0.99) : 0,\n\t\tunits: explicit && g.units === 'userSpaceOnUse' ? 'userSpaceOnUse' : 'objectBoundingBox'\n\t};\n}\n\n/**\n * The unit box → `bounds` matrix of `objectBoundingBox` gradients. A side with no extent (a\n * horizontal or vertical line) takes the other side's, centred, so the gradient still paints\n * (SVG paints nothing there).\n */\nexport function vectorBoxMatrix(bounds: VectorBounds | null | undefined): VectorMatrix {\n\tif (!bounds) return IDENTITY;\n\tlet { x, y, width: w, height: h } = bounds;\n\tconst fallback = Math.max(w, h, 1e-9) > 1e-9 ? Math.max(w, h) : 1;\n\tif (!(w > 1e-9)) {\n\t\tx -= fallback / 2 - w / 2;\n\t\tw = fallback;\n\t}\n\tif (!(h > 1e-9)) {\n\t\ty -= fallback / 2 - h / 2;\n\t\th = fallback;\n\t}\n\treturn [w, 0, 0, h, x, y];\n}\n\n/** The matrix of frame points: unit frame (u along start → end, v along start → width) → their space. */\nconst framePointsMatrix = (p: Pick<VectorGradientPoints, 'start' | 'end' | 'width'>): VectorMatrix => [p.end.x - p.start.x, p.end.y - p.start.y, p.width.x - p.start.x, p.width.y - p.start.y, p.start.x, p.start.y];\n\n/** The gradient's units → node space (the box matrix for `objectBoundingBox`, else the identity). */\nexport function vectorGradientUnitsMatrix(g: VectorGradient, bounds: VectorBounds | null | undefined): VectorMatrix {\n\treturn vectorGradientPoints(g).units === 'objectBoundingBox' ? vectorBoxMatrix(bounds) : IDENTITY;\n}\n\n/** The gradient's unit frame → node space: u = 1 at the end, v = 1 at the width point. */\nexport function vectorGradientMatrix(g: VectorGradient, bounds: VectorBounds | null | undefined): VectorMatrix {\n\treturn mul(framePointsMatrix(vectorGradientPoints(g)), vectorGradientUnitsMatrix(g, bounds));\n}\n\n/** Most a focal point reaches towards the edge of the circle (vectorcraft `FOCAL_MAX`). */\nconst FOCAL_MAX = 0.99;\n\n/** The focal point in the unit frame, pulled inside the circle (or null). */\nfunction unitFocal(g: VectorGradient): { f: Vec2; fr: number } | null {\n\tconst p = vectorGradientPoints(g);\n\tif (!p.focal && !(p.focalRadius > 0)) return null;\n\tconst inv = invert(framePointsMatrix(p));\n\tif (!inv) return null;\n\tlet f = p.focal ? apply(inv, p.focal) : { x: 0, y: 0 };\n\tconst reach = FOCAL_MAX * (1 - p.focalRadius);\n\tconst r = Math.hypot(f.x, f.y);\n\tif (r > reach) f = scale(f, reach / r);\n\treturn { f, fr: p.focalRadius };\n}\n\n/**\n * t of a radial gradient at unit-frame point `q` with the focal circle centred on `f` with radius\n * `fr` and the end circle the unit circle (SVG's two-point conical gradient). With `fr = 0` this\n * is the focal ray: t is the distance from the focal point to `q` over the distance from it to\n * the circle along the same ray (effectcraft `GradientRamp::t`, vectorcraft `param_at`).\n */\nexport function vectorGradientFocalParam(q: Vec2, f: Vec2 = { x: 0, y: 0 }, fr = 0): number {\n\tconst d = sub(q, f);\n\tconst dr = 1 - fr;\n\tconst a = dot(f, f) - dr * dr;\n\tconst b = dot(d, f) - fr * dr;\n\tconst c = dot(d, d) - fr * fr;\n\tif (Math.abs(a) < 1e-12) return Math.abs(b) < 1e-12 ? 0 : -c / (2 * b);\n\treturn (-b - Math.sqrt(Math.max(0, b * b - a * c))) / a;\n}\n\n/**\n * The raw gradient parameter (before the spread) of a style at unit-frame point `q`: linear `u`,\n * reflected `|u|`, diamond `|u| + |v|`, conic the turn from the u axis towards the v axis (0–1),\n * radial the distance through the focal circle (photocraft `gradient_t`).\n */\nexport function vectorGradientParam(type: VectorGradientType, q: Vec2, focal?: { f: Vec2; fr: number } | null): number {\n\tswitch (type) {\n\t\tcase 'linear':\n\t\t\treturn q.x;\n\t\tcase 'reflected':\n\t\t\treturn Math.abs(q.x);\n\t\tcase 'diamond':\n\t\t\treturn Math.abs(q.x) + Math.abs(q.y);\n\t\tcase 'conic': {\n\t\t\tconst turn = Math.atan2(q.y, q.x) / (2 * Math.PI);\n\t\t\treturn turn - Math.floor(turn);\n\t\t}\n\t\tcase 'radial':\n\t\t\treturn focal ? vectorGradientFocalParam(q, focal.f, focal.fr) : Math.hypot(q.x, q.y);\n\t}\n}\n\n/** `t` folded into 0–1 by a spread mode. */\nexport function applyVectorGradientSpread(t: number, spread: VectorGradientSpread = 'pad'): number {\n\tif (!Number.isFinite(t)) return 0;\n\tif (spread === 'repeat') return t - Math.floor(t);\n\tif (spread === 'reflect') {\n\t\tconst m = ((t % 2) + 2) % 2;\n\t\treturn m <= 1 ? m : 2 - m;\n\t}\n\treturn clamp(t, 0, 1);\n}\n\n/** The gradient's t (spread applied) at node-space point `p` of a shape with box `bounds`. */\nexport function vectorGradientTAt(g: VectorGradient, bounds: VectorBounds | null | undefined, p: Vec2): number {\n\tconst inv = invert(vectorGradientMatrix(g, bounds));\n\tif (!inv) return 0;\n\tconst raw = vectorGradientParam(g.type, apply(inv, p), g.type === 'radial' ? unitFocal(g) : null);\n\treturn g.type === 'conic' ? raw : applyVectorGradientSpread(raw, g.spread ?? 'pad');\n}\n\n/** What the gradient paints at node-space point `p` (straight-alpha sRGB, 0–1). */\nexport function sampleVectorGradientAt(g: VectorGradient, bounds: VectorBounds | null | undefined, p: Vec2): VectorRgba {\n\tconst t = vectorGradientTAt(g, bounds, p);\n\tconst ramp = vectorGradientRamp(g);\n\treturn ramp ? ramp.sample(t) : samplePlainStops(sortedVectorGradientStops(g), t);\n}\n\n/** The main axis length over the secondary's: |width − start| / |end − start| (signed by side). */\nexport function vectorGradientAspect(g: VectorGradient): number {\n\tconst p = vectorGradientPoints(g);\n\tconst u = sub(p.end, p.start);\n\tconst l2 = dot(u, u);\n\treturn l2 > 1e-18 ? dot(sub(p.width, p.start), perp(u)) / l2 : 1;\n}\n\n/** The gradient with explicit points (in its units) replacing the shorthand. */\nexport function explicitVectorGradient(g: VectorGradient): VectorGradient {\n\tconst p = vectorGradientPoints(g);\n\tconst { angle: _a, cx: _cx, cy: _cy, r: _r, ...rest } = g;\n\treturn {\n\t\t...rest,\n\t\tstart: p.start,\n\t\tend: p.end,\n\t\twidth: p.width,\n\t\t...(p.focal ? { focal: p.focal } : {}),\n\t\tunits: p.units\n\t};\n}\n\n/**\n * The gradient in the node's own space (`userSpaceOnUse`), painting what it paints on a shape\n * with box `bounds` (vectorcraft `GradientPaint::pin`): its points mapped through the box.\n */\nexport function pinVectorGradient(g: VectorGradient, bounds: VectorBounds | null | undefined): VectorGradient {\n\tconst e = explicitVectorGradient(g);\n\tif (e.units === 'userSpaceOnUse') return e;\n\tconst m = vectorBoxMatrix(bounds);\n\treturn { ...e, start: apply(m, e.start!), end: apply(m, e.end!), width: apply(m, e.width!), ...(e.focal ? { focal: apply(m, e.focal) } : {}), units: 'userSpaceOnUse' };\n}\n\n/**\n * The gradient after the node's geometry is mapped by `m`: a `userSpaceOnUse` gradient's points\n * are mapped too (any affine map keeps every style's t, since t is measured in the frame the\n * three points span); a box gradient follows the box and is unchanged.\n */\nexport function transformVectorGradient(g: VectorGradient, m: VectorMatrix): VectorGradient {\n\tif (!hasExplicitGradientGeometry(g) || g.units !== 'userSpaceOnUse' || isIdentity(m)) return g;\n\tconst p = vectorGradientPoints(g);\n\treturn { ...g, start: apply(m, p.start), end: apply(m, p.end), width: apply(m, p.width), ...(p.focal ? { focal: apply(m, p.focal) } : {}) };\n}\n\n/**\n * A gradient after its node's geometry goes through a non-affine map `f` (Free Distort, an\n * envelope): handles in the node's own space (`userSpaceOnUse`) are mapped point by point, which\n * keeps the gradient's frame where the shape went; bounding-box gradients are left alone, as they\n * already follow the shape's new bounds.\n */\nexport function mapVectorGradient(g: VectorGradient, f: (p: Vec2) => Vec2): VectorGradient {\n\tif (!hasExplicitGradientGeometry(g) || g.units !== 'userSpaceOnUse') return g;\n\tconst p = vectorGradientPoints(g);\n\treturn { ...g, start: f(p.start), end: f(p.end), width: f(p.width), ...(p.focal ? { focal: f(p.focal) } : {}) };\n}\n\n/** A paint after its node's geometry goes through a non-affine map `f` (see `mapVectorGradient`). */\nexport function mapVectorPaint<T extends VectorPaint | undefined>(paint: T, f: (p: Vec2) => Vec2): T {\n\tif (isVectorShadedPaint(paint)) return mapVectorShadedPaint(paint, f) as T;\n\treturn (isVectorGradient(paint) ? mapVectorGradient(paint, f) : paint) as T;\n}\n\n/** A paint after its node's geometry is mapped by `m` (colours unchanged). */\nexport function transformVectorPaint<T extends VectorPaint | undefined>(paint: T, m: VectorMatrix): T {\n\tif (isVectorShadedPaint(paint)) return transformVectorShadedPaint(paint, m) as T;\n\treturn (isVectorGradient(paint) ? transformVectorGradient(paint, m) : paint) as T;\n}\n\n// ---------------------------------------------------------------------------\n// Handles (on-canvas editing)\n// ---------------------------------------------------------------------------\n\n/**\n * An on-canvas handle of a gradient: `start` (a radial, conic or diamond gradient's centre),\n * `end` (a linear or reflected gradient's end), `radius` (the end of the others), `aspect` (the\n * secondary axis' end) and `focal` (radial).\n */\nexport type VectorGradientHandle = 'start' | 'end' | 'radius' | 'aspect' | 'focal';\n\n/** Whether the style has a centre with a radius (rather than a start and an end). */\nexport const isCentredVectorGradient = (type: VectorGradientType) => type === 'radial' || type === 'conic' || type === 'diamond';\n\n/** The handles of a gradient in the space `toWorld` maps the node's space to (the document, the screen). */\nexport function vectorGradientHandles(\n\tg: VectorGradient,\n\tbounds: VectorBounds | null | undefined,\n\ttoWorld: VectorMatrix = IDENTITY\n): { start: Vec2; end: Vec2; aspect: Vec2 | null; focal: Vec2 | null } {\n\tconst p = vectorGradientPoints(g);\n\tconst m = mul(vectorGradientUnitsMatrix(g, bounds), toWorld);\n\tconst f = g.type === 'radial' ? unitFocal(g) : null;\n\tconst frame = mul(framePointsMatrix(p), m);\n\treturn {\n\t\tstart: apply(m, p.start),\n\t\tend: apply(m, p.end),\n\t\taspect: isCentredVectorGradient(g.type) ? apply(m, p.width) : null,\n\t\tfocal: g.type === 'radial' ? apply(frame, f?.f ?? { x: 0, y: 0 }) : null\n\t};\n}\n\n/** Keeps the width point (and focal point) where they were relative to the main axis when it moves. */\nfunction withMainAxis(p: VectorGradientPoints, start: Vec2, end: Vec2): Pick<VectorGradientPoints, 'start' | 'end' | 'width' | 'focal'> {\n\tconst before = invert(framePointsMatrix(p));\n\tconst u = sub(p.end, p.start);\n\tconst l2 = dot(u, u);\n\tconst w = sub(p.width, p.start);\n\tconst rel = l2 > 1e-18 ? { a: dot(w, u) / l2, b: dot(w, perp(u)) / l2 } : { a: 0, b: 1 };\n\tconst u2 = sub(end, start);\n\tconst width = add(start, add(scale(u2, rel.a), scale(perp(u2), rel.b)));\n\tconst next = { start, end, width };\n\tconst focal = p.focal && before ? apply(framePointsMatrix(next), apply(before, p.focal)) : p.focal;\n\treturn { ...next, focal };\n}\n\n/**\n * The gradient (pinned to the node's space) with a handle dragged to node-space point `to`.\n * `start` moves the whole gradient by `to − from`; `end` / `radius` move the end, the secondary\n * axis and focal point following; `aspect` sets the secondary axis' length square to the main\n * one; `focal` sets the focal point (pulled inside the circle; null centres it).\n */\nexport function moveVectorGradientHandle(\n\tg: VectorGradient,\n\tbounds: VectorBounds | null | undefined,\n\thandle: VectorGradientHandle,\n\tto: Vec2,\n\tfrom: Vec2 = to\n): VectorGradient {\n\tconst pinned = pinVectorGradient(g, bounds);\n\tconst p = vectorGradientPoints(pinned);\n\tconst set = (q: Partial<Pick<VectorGradient, 'start' | 'end' | 'width' | 'focal'>>) => {\n\t\tconst next = { ...pinned, ...q };\n\t\tif (next.focal === null || next.focal === undefined) delete next.focal;\n\t\treturn next;\n\t};\n\tswitch (handle) {\n\t\tcase 'start': {\n\t\t\tconst d = sub(to, from);\n\t\t\treturn set({ start: add(p.start, d), end: add(p.end, d), width: add(p.width, d), focal: p.focal ? add(p.focal, d) : null });\n\t\t}\n\t\tcase 'end':\n\t\tcase 'radius': {\n\t\t\tif (Math.hypot(to.x - p.start.x, to.y - p.start.y) < 1e-6) return pinned;\n\t\t\tconst n = withMainAxis(p, p.start, to);\n\t\t\treturn set({ end: n.end, width: n.width, focal: n.focal });\n\t\t}\n\t\tcase 'aspect': {\n\t\t\tconst u = sub(p.end, p.start);\n\t\t\tconst l2 = dot(u, u);\n\t\t\tif (l2 < 1e-18) return pinned;\n\t\t\tlet aspect = dot(sub(to, p.start), perp(u)) / l2;\n\t\t\tif (Math.abs(aspect) < 0.01) aspect = aspect < 0 ? -0.01 : 0.01;\n\t\t\tconst before = invert(framePointsMatrix(p));\n\t\t\tconst width = add(p.start, scale(perp(u), aspect));\n\t\t\tconst focal = p.focal && before ? apply(framePointsMatrix({ start: p.start, end: p.end, width }), apply(before, p.focal)) : null;\n\t\t\treturn set({ width, focal });\n\t\t}\n\t\tcase 'focal': {\n\t\t\tconst frame = framePointsMatrix(p);\n\t\t\tconst inv = invert(frame);\n\t\t\tif (!inv) return pinned;\n\t\t\tlet q = apply(inv, to);\n\t\t\tconst r = Math.hypot(q.x, q.y);\n\t\t\tif (r < 1e-6) return set({ focal: null });\n\t\t\tconst reach = FOCAL_MAX * (1 - p.focalRadius);\n\t\t\tif (r > reach) q = scale(q, reach / r);\n\t\t\treturn set({ focal: apply(frame, q) });\n\t\t}\n\t}\n}\n\n/** The gradient set to run from `start` to `end` (node space), its secondary axis square to it with its aspect kept. */\nexport function setVectorGradientVector(g: VectorGradient, bounds: VectorBounds | null | undefined, start: Vec2, end: Vec2): VectorGradient {\n\tconst pinned = pinVectorGradient(g, bounds);\n\tconst p = vectorGradientPoints(pinned);\n\tconst aspect = Math.abs(vectorGradientAspect(pinned)) > 1e-6 ? vectorGradientAspect(pinned) : 1;\n\tconst u = sub(end, start);\n\tconst width = add(start, scale(perp(u), aspect));\n\tconst before = invert(framePointsMatrix(p));\n\tconst focal = p.focal && before ? apply(framePointsMatrix({ start, end, width }), apply(before, p.focal)) : null;\n\tconst next: VectorGradient = { ...pinned, start, end, width };\n\tif (focal) next.focal = focal;\n\telse delete next.focal;\n\treturn next;\n}\n\n// ---------------------------------------------------------------------------\n// Spread as stop periods\n// ---------------------------------------------------------------------------\n\n/** Most periods a spread is expanded to (vectorcraft `MAX_PERIODS`). */\nexport const VECTOR_GRADIENT_MAX_PERIODS = 64;\n\n/** The stops of one period, from 0 to 1: the end colours held out to the ends (vectorcraft `whole_period`). */\nfunction wholePeriod(stops: readonly VectorGradientStop[]): VectorGradientStop[] {\n\tconst out = stops.map((s) => ({ ...s }));\n\tif (out.length && out[0].offset > 0) out.unshift({ ...out[0], offset: 0 });\n\tconst last = out[out.length - 1];\n\tif (last && last.offset < 1) out.push({ ...last, offset: 1 });\n\treturn out;\n}\n\n/**\n * Stops repeating the gradient's plain stops over periods `lo` … `hi` (integers, at most\n * `VECTOR_GRADIENT_MAX_PERIODS`), period `k` mirrored when `mirrored(k)`; offsets over 0–1 span\n * the whole range (vectorcraft `spread::expand`, which emulates `reflect` and `repeat` this way).\n */\nexport function periodicVectorGradientStops(stops: readonly VectorGradientStop[], lo: number, hi: number, mirrored: (k: number) => boolean): VectorGradientStop[] {\n\tconst period = wholePeriod(stops);\n\tconst back = reverseVectorGradient({ stops: period }).stops;\n\tconst n = Math.max(1, hi - lo);\n\tconst out: VectorGradientStop[] = [];\n\tfor (let j = 0; j < n; j++) {\n\t\tconst one = mirrored(lo + j) ? back : period;\n\t\tfor (const s of one) out.push({ ...s, offset: (j + s.offset) / n });\n\t}\n\treturn out;\n}\n\n/**\n * A linear or reflected gradient's spread as stop periods over `area` (node space), for\n * renderers (and combinations) without the spread mode: vectorcraft's SVG import emulates\n * `reflect` and `repeat` this way. Returns where the periods start and end and their stops, or\n * null when a linear gradient pads (nothing to repeat). Reflected gradients always get at least\n * the period either side of the start (the one before it mirrored). `from` / `to` are the\n * periods' ends along the frame's u axis (`matrix` maps the frame to node space).\n */\nexport function expandVectorGradientSpread(\n\tg: VectorGradient,\n\tbounds: VectorBounds | null | undefined,\n\tarea: VectorBounds\n): { start: Vec2; end: Vec2; from: number; to: number; matrix: VectorMatrix; stops: VectorGradientStop[]; capped: boolean } | null {\n\tconst m = vectorGradientMatrix(g, bounds);\n\tconst inv = invert(m);\n\tconst spread = g.spread ?? 'pad';\n\tconst reflected = g.type === 'reflected';\n\tif (!inv || (!reflected && spread === 'pad')) return null;\n\tconst odd = (k: number) => ((k % 2) + 2) % 2 === 1;\n\tconst stops = expandVectorGradientStops(g);\n\tconst along = (a: number, b: number, mirrored: (k: number) => boolean, capped = false) => ({\n\t\tstart: apply(m, { x: a, y: 0 }),\n\t\tend: apply(m, { x: b, y: 0 }),\n\t\tfrom: a,\n\t\tto: b,\n\t\tmatrix: m,\n\t\tstops: periodicVectorGradientStops(stops, a, b, mirrored),\n\t\tcapped\n\t});\n\tif (reflected && spread === 'pad') return along(-1, 1, (k) => k < 0);\n\tconst us = boxCorners(area).map((c) => apply(inv, c).x);\n\tlet lo = Math.floor(Math.min(...us));\n\tlet hi = Math.ceil(Math.max(...us));\n\tif (reflected) {\n\t\tlo = Math.min(lo, -1);\n\t\thi = Math.max(hi, 1);\n\t}\n\thi = Math.max(hi, lo + 1);\n\tif (!reflected && lo >= 0 && hi <= 1) return null;\n\tconst capped = hi - lo > VECTOR_GRADIENT_MAX_PERIODS;\n\tif (capped) {\n\t\tlo = Math.max(lo, -VECTOR_GRADIENT_MAX_PERIODS / 2);\n\t\thi = lo + VECTOR_GRADIENT_MAX_PERIODS;\n\t}\n\t// Period k covers u in [k, k + 1]. A reflected gradient runs |u|: before the start, periods run backwards.\n\tconst mirrored = reflected\n\t\t? (k: number) => {\n\t\t\t\tconst j = k >= 0 ? k : -k - 1;\n\t\t\t\tconst own = spread === 'reflect' && odd(j);\n\t\t\t\treturn k < 0 ? !own : own;\n\t\t\t}\n\t\t: (k: number) => spread === 'reflect' && odd(k);\n\treturn along(lo, hi, mirrored, capped);\n}\n\nconst boxCorners = (b: VectorBounds): Vec2[] => [\n\t{ x: b.x, y: b.y },\n\t{ x: b.x + b.width, y: b.y },\n\t{ x: b.x + b.width, y: b.y + b.height },\n\t{ x: b.x, y: b.y + b.height }\n];\n\n// ---------------------------------------------------------------------------\n// SVG paint servers\n// ---------------------------------------------------------------------------\n\n/**\n * A `<pattern>` paint server in user space: draw `gradients` (inside it or in `<defs>`) and then\n * each tile (`d` filled with `fill`) in order, all in the painted element's user space (the\n * `viewBox` in `attrs` matches the tile, so keep it). Conic and diamond gradients, and gradients along\n * or across a stroke, take this form.\n */\nexport interface VectorSvgPatternDef {\n\tid: string;\n\ttype: 'pattern';\n\t/** `x`, `y`, `width`, `height`, `patternUnits=\"userSpaceOnUse\"` and the matching `viewBox`. */\n\tattrs: Record<string, string | number>;\n\tgradients: SvgGradientDef[];\n\ttiles: { d: string; fill: string }[];\n}\n\n/** A paint server for `fill` / `stroke`: a gradient element or a pattern of gradient tiles. */\nexport type VectorPaintDef = SvgGradientDef | VectorSvgPatternDef;\n\nexport interface VectorGradientSvgOptions {\n\t/** The shape's box in its own space (for `objectBoundingBox` gradients). */\n\tbounds?: VectorBounds | null;\n\t/** The area the paint must cover (pattern tiles, spread periods); default `bounds` padded by 1. */\n\tarea?: VectorBounds | null;\n\t/** Wedges of a conic gradient (default 72: 5° each). */\n\twedges?: number;\n\tprecision?: number;\n}\n\nconst toSvgStops = (stops: readonly VectorGradientStop[]): SvgGradientStop[] =>\n\tstops.map((s) => ({ offset: `${fmt(s.offset * 100, 3)}%`, stopColor: s.color, ...(s.opacity !== undefined && s.opacity !== 1 ? { stopOpacity: Math.round(s.opacity * 1e4) / 1e4 } : {}) }));\n\nconst polygonD = (pts: readonly Vec2[], precision: number) => `M${pts.map((p) => `${fmt(p.x, precision)} ${fmt(p.y, precision)}`).join('L')}Z`;\n\nconst padBounds = (b: VectorBounds, pad: number): VectorBounds => ({ x: b.x - pad, y: b.y - pad, width: b.width + 2 * pad, height: b.height + 2 * pad });\n\n/** The area a gradient on a shape with box `bounds` paints (the box padded by 1). */\nexport const vectorGradientArea = (bounds: VectorBounds | null | undefined): VectorBounds => padBounds(bounds ?? { x: 0, y: 0, width: 1, height: 1 }, 1);\n\n/** The `gradientTransform` attribute of matrix `m` (none for the identity). */\nconst transformAttr = (m: VectorMatrix): Record<string, string> => (isIdentity(m) ? {} : { gradientTransform: fmtMatrix(m) });\n\n/** Smallest stretch of a matrix (the least singular value). */\nfunction minScale(m: VectorMatrix): number {\n\tconst [a, b, c, d] = m;\n\tconst p = a * a + b * b;\n\tconst q = c * c + d * d;\n\tconst r = a * c + b * d;\n\treturn Math.sqrt(Math.max(0, (p + q - Math.sqrt((p - q) ** 2 + 4 * r * r)) / 2));\n}\n\n/**\n * A user-space pattern tile over `area`. Without a `viewBox` SVG puts the content's origin at the\n * tile's corner; the matching `viewBox` keeps the content in the painted element's user space.\n */\nexport function patternAttrs(area: VectorBounds): Record<string, string> {\n\tconst [x, y, w, h] = [area.x, area.y, Math.max(area.width, 1e-3), Math.max(area.height, 1e-3)].map((n) => fmt(n, 3));\n\treturn { patternUnits: 'userSpaceOnUse', x, y, width: w, height: h, viewBox: `${x} ${y} ${w} ${h}` };\n}\n\n/** A pattern def over `area` with the given tiles. */\nfunction patternDef(id: string, area: VectorBounds, gradients: SvgGradientDef[], tiles: { d: string; fill: string }[]): VectorSvgPatternDef {\n\treturn {\n\t\tid,\n\t\ttype: 'pattern',\n\t\tattrs: patternAttrs(area),\n\t\tgradients,\n\t\ttiles\n\t};\n}\n\n/**\n * The SVG paint servers of a gradient on a shape: the first def's id is `id` (reference it as\n * `url(#id)`), any others are what it uses. All are in the user space of the element painted\n * (the node's own space).\n */\nexport function vectorGradientSvgDefs(g: VectorGradient, id: string, options: VectorGradientSvgOptions = {}): VectorPaintDef[] {\n\tconst precision = options.precision ?? 3;\n\tconst bounds = options.bounds ?? null;\n\tconst area = options.area ?? vectorGradientArea(bounds);\n\tconst spread = g.spread && VECTOR_GRADIENT_SPREADS.includes(g.spread) ? g.spread : 'pad';\n\tconst stops = expandVectorGradientStops(g);\n\tconst p = vectorGradientPoints(g);\n\tconst unitsM = vectorGradientUnitsMatrix(g, bounds);\n\tconst frameM = mul(framePointsMatrix(p), unitsM);\n\tconst spreadAttr = (s: VectorGradientSpread): Record<string, string> => (s === 'pad' ? {} : { spreadMethod: s });\n\tconst base = { gradientUnits: 'userSpaceOnUse' };\n\n\tswitch (g.type) {\n\t\tcase 'linear':\n\t\tcase 'reflected': {\n\t\t\tif (g.type === 'reflected' && spread !== 'reflect') {\n\t\t\t\t// Pad: mirrored stops over [2·start − end, end]; repeat: periods over the area, the ones before the start mirrored.\n\t\t\t\tconst ex = expandVectorGradientSpread(g, bounds, area);\n\t\t\t\tconst [a, b] = ex ? [ex.from, ex.to] : [-1, 1];\n\t\t\t\tconst st = ex?.stops ?? periodicVectorGradientStops(stops, -1, 1, (k) => k < 0);\n\t\t\t\treturn [{ id, type: 'linear', attrs: { ...base, x1: a, y1: 0, x2: b, y2: 0, gradientTransform: fmtMatrix(frameM) }, stops: toSvgStops(st) }];\n\t\t\t}\n\t\t\tconst u = sub(p.end, p.start);\n\t\t\tconst w = sub(p.width, p.start);\n\t\t\tconst square = Math.abs(dot(u, w)) <= 1e-9 * Math.max(dot(u, u), dot(w, w), 1e-18);\n\t\t\t// A skewed frame (a userSpaceOnUse gradient sheared with its shape) needs the frame as the transform.\n\t\t\tconst coords: Record<string, string | number> = square ? { x1: fmt(p.start.x, 6), y1: fmt(p.start.y, 6), x2: fmt(p.end.x, 6), y2: fmt(p.end.y, 6), ...transformAttr(unitsM) } : { x1: 0, y1: 0, x2: 1, y2: 0, gradientTransform: fmtMatrix(frameM) };\n\t\t\treturn [{ id, type: 'linear', attrs: { ...base, ...coords, ...spreadAttr(spread) }, stops: toSvgStops(stops) }];\n\t\t}\n\t\tcase 'radial': {\n\t\t\tconst f = unitFocal(g);\n\t\t\tconst attrs: Record<string, string | number> = { ...base, cx: 0, cy: 0, r: 1, gradientTransform: fmtMatrix(frameM), ...spreadAttr(spread) };\n\t\t\tif (f && (Math.abs(f.f.x) > 1e-9 || Math.abs(f.f.y) > 1e-9)) {\n\t\t\t\tattrs.fx = fmt(f.f.x, 6);\n\t\t\t\tattrs.fy = fmt(f.f.y, 6);\n\t\t\t}\n\t\t\tif (f && f.fr > 0) attrs.fr = fmt(f.fr, 6);\n\t\t\treturn [{ id, type: 'radial', attrs, stops: toSvgStops(stops) }];\n\t\t}\n\t\tcase 'diamond': {\n\t\t\tconst inv = invert(frameM);\n\t\t\tif (!inv) return [patternDef(id, area, [], [{ d: polygonD(boxCorners(area), precision), fill: stops[stops.length - 1]?.color ?? 'none' }])];\n\t\t\tconst reach = 2 * Math.max(...boxCorners(area).map((c) => {\n\t\t\t\tconst q = apply(inv, c);\n\t\t\t\treturn Math.abs(q.x) + Math.abs(q.y);\n\t\t\t})) + 1;\n\t\t\t// Each quadrant overlaps its neighbours by about 0.75 units, hiding anti-aliasing seams.\n\t\t\tconst delta = Math.min(0.05 * reach, 0.75 / Math.max(minScale(frameM), 1e-9));\n\t\t\tconst gradients: SvgGradientDef[] = [];\n\t\t\tconst tiles: { d: string; fill: string }[] = [];\n\t\t\t[[1, 1], [-1, 1], [-1, -1], [1, -1]].forEach(([sx, sy], k) => {\n\t\t\t\tconst gid = `${id}-q${k}`;\n\t\t\t\tgradients.push({ id: gid, type: 'linear', attrs: { ...base, x1: 0, y1: 0, x2: sx / 2, y2: sy / 2, gradientTransform: fmtMatrix(frameM), ...spreadAttr(spread) }, stops: toSvgStops(stops) });\n\t\t\t\tconst quad = [{ x: -delta * sx, y: -delta * sy }, { x: reach * sx, y: -delta * sy }, { x: -delta * sx, y: reach * sy }].map((q) => apply(frameM, q));\n\t\t\t\ttiles.push({ d: polygonD(quad, precision), fill: `url(#${gid})` });\n\t\t\t});\n\t\t\treturn [patternDef(id, area, gradients, tiles)];\n\t\t}\n\t\tcase 'conic':\n\t\t\treturn [conicPattern(id, frameM, stops, area, options.wedges ?? 72, precision)];\n\t}\n}\n\n/**\n * A conic gradient as thin wedges round the centre, each with a linear gradient across it\n * (along the tangent at its middle angle, exact on the unit circle of the frame: elsewhere a\n * point takes a colour from within its wedge). Stops inside a wedge keep sharp transitions.\n */\nfunction conicPattern(id: string, frameM: VectorMatrix, stops: readonly VectorGradientStop[], area: VectorBounds, wedges: number, precision: number): VectorSvgPatternDef {\n\tconst inv = invert(frameM);\n\tconst n = Math.max(8, Math.min(720, Math.round(wedges)));\n\tconst half = Math.PI / n;\n\tif (!inv || !stops.length) return patternDef(id, area, [], [{ d: polygonD(boxCorners(area), precision), fill: stops[0]?.color ?? 'none' }]);\n\tconst reach = (Math.max(...boxCorners(area).map((c) => Math.hypot(apply(inv, c).x, apply(inv, c).y))) + 1) / Math.cos(half);\n\tconst overlap = Math.min(half, 0.002);\n\tconst gradients: SvgGradientDef[] = [];\n\tconst tiles: { d: string; fill: string }[] = [];\n\tfor (let k = 0; k < n; k++) {\n\t\tconst a0 = (2 * Math.PI * k) / n;\n\t\tconst a1 = (2 * Math.PI * (k + 1)) / n;\n\t\tconst mid = (a0 + a1) / 2;\n\t\tconst tau = { x: -Math.sin(mid), y: Math.cos(mid) };\n\t\tconst s = Math.sin(half);\n\t\tconst at = (angle: number) => (Math.sin(angle - mid) / s + 1) / 2;\n\t\tconst t0 = k / n;\n\t\tconst t1 = (k + 1) / n;\n\t\tconst own: VectorGradientStop[] = [stopOf(0, samplePlainStops(stops, t0))];\n\t\tfor (const st of stops) if (st.offset > t0 && st.offset < t1) own.push({ ...st, offset: at(st.offset * 2 * Math.PI) });\n\t\town.push(stopOf(1, samplePlainStops(stops, t1)));\n\t\tconst gid = `${id}-w${k}`;\n\t\tgradients.push({\n\t\t\tid: gid,\n\t\t\ttype: 'linear',\n\t\t\tattrs: { gradientUnits: 'userSpaceOnUse', x1: fmt(-s * tau.x, 6), y1: fmt(-s * tau.y, 6), x2: fmt(s * tau.x, 6), y2: fmt(s * tau.y, 6), gradientTransform: fmtMatrix(frameM) },\n\t\t\tstops: toSvgStops(own)\n\t\t});\n\t\tconst from = a0 - (k === 0 ? 0 : overlap);\n\t\tconst pts = [{ x: 0, y: 0 }, { x: reach * Math.cos(from), y: reach * Math.sin(from) }, { x: reach * Math.cos(a1), y: reach * Math.sin(a1) }].map((q) => apply(frameM, q));\n\t\ttiles.push({ d: polygonD(pts, precision), fill: `url(#${gid})` });\n\t}\n\treturn patternDef(id, area, gradients, tiles);\n}\n\n// ---------------------------------------------------------------------------\n// Evaluating paint servers (tests, previews)\n// ---------------------------------------------------------------------------\n\nconst num = (v: string | number | undefined, fallback = 0) => {\n\tif (v === undefined) return fallback;\n\tconst n = typeof v === 'number' ? v : parseFloat(v);\n\treturn Number.isFinite(n) ? n : fallback;\n};\n\nconst parseMatrixAttr = (v: string | number | undefined): VectorMatrix => {\n\tconst m = typeof v === 'string' ? /^matrix\\(([^)]*)\\)$/.exec(v.trim()) : null;\n\tif (!m) return IDENTITY;\n\tconst n = m[1].split(/[\\s,]+/).map(Number);\n\treturn n.length === 6 && n.every(Number.isFinite) ? (n as unknown as VectorMatrix) : IDENTITY;\n};\n\nconst plainOf = (stops: readonly SvgGradientStop[]): VectorGradientStop[] =>\n\tstops.map((s) => ({ offset: parseFloat(s.offset) / (s.offset.endsWith('%') ? 100 : 1), color: s.stopColor, ...(s.stopOpacity !== undefined ? { opacity: s.stopOpacity } : {}) }));\n\n/** Point `p` inside a polygon tile (`M x y L … Z`), even-odd. */\nfunction inTile(d: string, p: Vec2): boolean {\n\tconst n = d.match(/-?[\\d.]+(?:e-?\\d+)?/gi)?.map(Number) ?? [];\n\tlet inside = false;\n\tfor (let i = 0, j = n.length - 2; i + 1 < n.length; j = i, i += 2) {\n\t\tconst [xi, yi, xj, yj] = [n[i], n[i + 1], n[j], n[j + 1]];\n\t\tif (yi > p.y !== yj > p.y && p.x < ((xj - xi) * (p.y - yi)) / (yj - yi) + xi) inside = !inside;\n\t}\n\treturn inside;\n}\n\n/**\n * What a `userSpaceOnUse` paint server from `vectorGradientSvgDefs` paints at point `p` (straight\n * alpha, 0–1) the way an SVG renderer would: a gradient's stops interpolated in sRGB, a pattern's\n * topmost tile containing `p`. Null for a point no tile covers.\n */\nexport function sampleVectorPaintDefAt(defs: readonly VectorPaintDef[], id: string, p: Vec2): VectorRgba | null {\n\tconst all = new Map<string, VectorPaintDef>();\n\tfor (const d of defs) {\n\t\tall.set(d.id, d);\n\t\tif (d.type === 'pattern') for (const gd of d.gradients) all.set(gd.id, gd);\n\t}\n\tconst paint = (ref: string, q: Vec2): VectorRgba | null => {\n\t\tconst url = /^url\\(#(.+)\\)$/.exec(ref);\n\t\tif (!url) return parseVectorColor(ref);\n\t\tconst def = all.get(url[1]);\n\t\tif (!def) return null;\n\t\tif (def.type === 'pattern') {\n\t\t\tfor (let i = def.tiles.length - 1; i >= 0; i--) if (inTile(def.tiles[i].d, q)) return paint(def.tiles[i].fill, q);\n\t\t\treturn null;\n\t\t}\n\t\tconst inv = invert(parseMatrixAttr(def.attrs.gradientTransform)) ?? IDENTITY;\n\t\tconst local = apply(inv, q);\n\t\tconst spread = (def.attrs.spreadMethod as VectorGradientSpread | undefined) ?? 'pad';\n\t\tlet t: number;\n\t\tif (def.type === 'radial') {\n\t\t\tconst r = num(def.attrs.r, 0.5);\n\t\t\tconst c = { x: num(def.attrs.cx), y: num(def.attrs.cy) };\n\t\t\tconst f = { x: num(def.attrs.fx, c.x), y: num(def.attrs.fy, c.y) };\n\t\t\tconst u = { x: (local.x - c.x) / r, y: (local.y - c.y) / r };\n\t\t\tt = vectorGradientFocalParam(u, { x: (f.x - c.x) / r, y: (f.y - c.y) / r }, num(def.attrs.fr) / r);\n\t\t} else {\n\t\t\tconst a = { x: num(def.attrs.x1), y: num(def.attrs.y1) };\n\t\t\tconst b = { x: num(def.attrs.x2, 1), y: num(def.attrs.y2) };\n\t\t\tconst v = sub(b, a);\n\t\t\tconst l2 = dot(v, v);\n\t\t\tt = l2 > 1e-18 ? dot(sub(local, a), v) / l2 : 0;\n\t\t}\n\t\treturn samplePlainStops(plainOf(def.stops), applyVectorGradientSpread(t, spread));\n\t};\n\treturn paint(`url(#${id})`, p);\n}\n\n// ---------------------------------------------------------------------------\n// Sanitizing (agents, import)\n// ---------------------------------------------------------------------------\n\nconst readPoint = (v: unknown): Vec2 | undefined => (finitePoint(v) ? { x: v.x, y: v.y } : undefined);\n\n/**\n * A gradient from untrusted input (agent commands, SVG data attributes), or null when it is not\n * one: unknown fields dropped, numbers clamped, at least one stop.\n */\nexport function sanitizeVectorGradient(input: unknown): VectorGradient | null {\n\tif (!input || typeof input !== 'object') return null;\n\tconst r = input as Record<string, unknown>;\n\tif (!VECTOR_GRADIENT_TYPES.includes(r.type as VectorGradientType) || !Array.isArray(r.stops)) return null;\n\tconst stops: VectorGradientStop[] = [];\n\tfor (const s of r.stops as unknown[]) {\n\t\tif (!s || typeof s !== 'object') continue;\n\t\tconst x = s as Record<string, unknown>;\n\t\tif (typeof x.color !== 'string' || typeof x.offset !== 'number' || !Number.isFinite(x.offset)) continue;\n\t\tconst stop: VectorGradientStop = { offset: clamp(x.offset, 0, 1), color: x.color.slice(0, 100) };\n\t\tif (typeof x.opacity === 'number' && Number.isFinite(x.opacity) && x.opacity !== 1) stop.opacity = clamp(x.opacity, 0, 1);\n\t\tif (typeof x.midpoint === 'number' && Number.isFinite(x.midpoint) && Math.abs(x.midpoint - 0.5) > 1e-6) stop.midpoint = clamp(x.midpoint, 0.05, 0.95);\n\t\tstops.push(stop);\n\t}\n\tif (!stops.length) return null;\n\tconst g: VectorGradient = { type: r.type as VectorGradientType, stops };\n\tfor (const k of ['angle', 'cx', 'cy', 'r'] as const) if (typeof r[k] === 'number' && Number.isFinite(r[k])) g[k] = r[k] as number;\n\tconst start = readPoint(r.start);\n\tconst end = readPoint(r.end);\n\tif (start && end) {\n\t\tg.start = start;\n\t\tg.end = end;\n\t\tconst width = readPoint(r.width);\n\t\tif (width) g.width = width;\n\t\tif (r.units === 'userSpaceOnUse' || r.units === 'objectBoundingBox') g.units = r.units;\n\t}\n\tconst focal = readPoint(r.focal);\n\tif (focal && g.type === 'radial') g.focal = focal;\n\tif (typeof r.focalRadius === 'number' && r.focalRadius > 0 && g.type === 'radial') g.focalRadius = clamp(r.focalRadius, 0, 0.99);\n\tif (VECTOR_GRADIENT_SPREADS.includes(r.spread as VectorGradientSpread) && r.spread !== 'pad') g.spread = r.spread as VectorGradientSpread;\n\tif (VECTOR_GRADIENT_INTERPOLATIONS.includes(r.interpolation as VectorGradientInterpolation) && r.interpolation !== 'srgb') g.interpolation = r.interpolation as VectorGradientInterpolation;\n\tif (typeof r.smoothness === 'number' && r.smoothness > 0) g.smoothness = clamp(r.smoothness, 0, 1);\n\tif (VECTOR_STROKE_GRADIENT_MODES.includes(r.strokeMode as never) && r.strokeMode !== 'within') g.strokeMode = r.strokeMode as VectorGradient['strokeMode'];\n\treturn g;\n}\n\n/**\n * A gradient changed to style `type`, keeping its stops, colour settings and placement: explicit\n * points stay where they are (a linear end becomes a radius), shorthand is redone for the style.\n */\nexport function convertVectorGradient(g: VectorGradient, type: VectorGradientType): VectorGradient {\n\tif (g.type === type) return g;\n\tconst next: VectorGradient = { ...g, type };\n\tif (type !== 'radial') {\n\t\tdelete next.focal;\n\t\tdelete next.focalRadius;\n\t}\n\tif (!hasExplicitGradientGeometry(g)) {\n\t\t// Shorthand fields mean different things per style: drop the ones the new style reads differently.\n\t\tif (isCentredVectorGradient(type) !== isCentredVectorGradient(g.type)) {\n\t\t\tdelete next.angle;\n\t\t\tdelete next.cx;\n\t\t\tdelete next.cy;\n\t\t\tdelete next.r;\n\t\t}\n\t}\n\treturn next;\n}\n\n/** A default gradient for a paint that was a colour (or nothing): the colour fading to white. */\nexport function defaultVectorGradient(type: VectorGradientType = 'linear', from?: VectorPaint): VectorGradient {\n\tif (isVectorGradient(from)) return convertVectorGradient(from, type);\n\tconst colour = typeof from === 'string' && parseVectorColor(from) ? from : '#000000';\n\treturn { type, stops: [{ offset: 0, color: colour }, { offset: 1, color: '#ffffff' }] };\n}\n\n/**\n * Changes to a gradient (`vector.setGradient`, the gradient editor): any gradient field, plus\n * `aspect` (the secondary axis' length over the main one, square to it) and `reverse`. `focal` or\n * `width` set to null removes them.\n */\nexport interface VectorGradientPatch extends Partial<Omit<VectorGradient, 'focal' | 'width'>> {\n\tfocal?: Vec2 | null;\n\twidth?: Vec2 | null;\n\taspect?: number;\n\treverse?: boolean;\n}\n\n/** `g` with `patch` applied (a style change converts it first), or null when the result is not a gradient. */\nexport function applyVectorGradientPatch(g: VectorGradient, patch: VectorGradientPatch): VectorGradient | null {\n\tconst { aspect, reverse, type, ...fields } = patch;\n\tlet next: VectorGradient = type && type !== g.type ? convertVectorGradient(g, type) : { ...g };\n\tconst record = next as unknown as Record<string, unknown>;\n\tfor (const [k, v] of Object.entries(fields)) {\n\t\tif (v === undefined) continue;\n\t\tif (v === null) delete record[k];\n\t\telse record[k] = v;\n\t}\n\t// Explicit points replace the shorthand (and the other way round).\n\tif ((fields.start || fields.end) && !hasExplicitGradientGeometry(next)) {\n\t\tconst p = vectorGradientPoints({ ...g, start: undefined, end: undefined });\n\t\tnext.start = next.start ?? p.start;\n\t\tnext.end = next.end ?? p.end;\n\t}\n\tif (aspect !== undefined && Number.isFinite(aspect)) {\n\t\tconst e = explicitVectorGradient(next);\n\t\tconst u = sub(e.end!, e.start!);\n\t\tconst a = Math.abs(aspect) < 0.01 ? (aspect < 0 ? -0.01 : 0.01) : aspect;\n\t\tnext = { ...e, width: add(e.start!, scale(perp(u), a)) };\n\t}\n\tif (reverse) next = reverseVectorGradient(next);\n\tconst clean = sanitizeVectorGradient(next);\n\tif (!clean) return null;\n\tclean.stops = sortedVectorGradientStops(clean);\n\treturn clean;\n}\n","/**\n * Gradient meshes and freeform gradients: paints that are not a function of one parameter, drawn\n * as SVG patterns of small flat tiles (as conic gradients are drawn as wedges).\n *\n * Meshes follow effectcraft's `crates/pdf/src/shading.rs` (PDF shading types 6 and 7: Coons patches\n * bounded by cubic sides, tessellated into small cells whose colours blend between the patch's\n * corners); here the lattice's sides are Catmull-Rom curves through its points, so a mesh stays\n * smooth across patches. Freeform gradients follow vectorcraft's `crates/color/src/freeform.rs`\n * (`Freeform`, `Field::sample`: each point paints a disc of pure colour of its spread and blends\n * into the others beyond it by inverse-square distance from the disc's edge; a line is a\n * Catmull-Rom curve whose pieces each act as a source weighted by their share of its length;\n * `auto` places a 2 × n grid of points inside the shape; `spread_scale`) (MIT OR Apache-2.0,\n * © ArtCraft Team and contributors; see THIRD_PARTY_NOTICES.md).\n */\n\nimport type { VectorBounds, VectorFreeformGradient, VectorFreeformPoint, VectorMeshGradient, VectorPaint, Vec2 } from './types.js';\nimport type { VectorMatrix } from './types.js';\nimport { parseVectorColor, patternAttrs, type VectorRgba, type VectorSvgPatternDef } from './gradient.js';\nimport type { SvgGradientDef, SvgGradientStop } from '../canvas/gradient.js';\n\n/** Whether the paint is a gradient mesh. */\nexport function isVectorMeshGradient(paint: VectorPaint | undefined): paint is VectorMeshGradient {\n\treturn !!paint && typeof paint === 'object' && (paint as VectorMeshGradient).type === 'mesh' && Array.isArray((paint as VectorMeshGradient).points);\n}\n\n/** Whether the paint is a freeform gradient. */\nexport function isVectorFreeformGradient(paint: VectorPaint | undefined): paint is VectorFreeformGradient {\n\treturn !!paint && typeof paint === 'object' && (paint as VectorFreeformGradient).type === 'freeform' && Array.isArray((paint as VectorFreeformGradient).points);\n}\n\n/** Whether the paint is a mesh or freeform gradient (drawn as tiles). */\nexport function isVectorShadedPaint(paint: VectorPaint | undefined): paint is VectorMeshGradient | VectorFreeformGradient {\n\treturn isVectorMeshGradient(paint) || isVectorFreeformGradient(paint);\n}\n\nconst lerp = (a: number, b: number, t: number) => a + (b - a) * t;\nconst rgbaOf = (color: string, opacity = 1): VectorRgba => {\n\tconst c = parseVectorColor(color) ?? [0, 0, 0, 1];\n\treturn [c[0], c[1], c[2], c[3] * opacity];\n};\nconst hex2 = (v: number) =>\n\tMath.round(Math.min(1, Math.max(0, v)) * 255)\n\t\t.toString(16)\n\t\t.padStart(2, '0');\n/** A CSS colour for straight-alpha channels: `#rrggbb`, or `rgba()` when not opaque. */\nexport function vectorRgbaToCss([r, g, b, a]: VectorRgba): string {\n\tif (a >= 0.9995) return `#${hex2(r)}${hex2(g)}${hex2(b)}`;\n\tconst c = (v: number) => Math.round(Math.min(1, Math.max(0, v)) * 255);\n\treturn `rgba(${c(r)},${c(g)},${c(b)},${Math.round(Math.max(0, a) * 1000) / 1000})`;\n}\n\n// ---------------------------------------------------------------------------\n// Meshes\n// ---------------------------------------------------------------------------\n\n/** The most rows or columns a mesh has. */\nexport const VECTOR_MESH_MAX = 32;\n\n/**\n * A mesh over `bounds` with `rows` × `columns` patches, its points evenly spread. Colours come from\n * `colors` row by row (one per point), or the four `corners` (top-left, top-right, bottom-right,\n * bottom-left) blended across, or white.\n */\nexport function createVectorMeshGradient(bounds: VectorBounds, rows: number, columns: number, colors: { colors?: readonly string[]; corners?: readonly [string, string, string, string] } = {}): VectorMeshGradient {\n\tconst r = Math.min(VECTOR_MESH_MAX, Math.max(1, Math.round(rows)));\n\tconst c = Math.min(VECTOR_MESH_MAX, Math.max(1, Math.round(columns)));\n\tconst points: Vec2[] = [];\n\tconst out: string[] = [];\n\tconst corners = colors.corners?.map((k) => rgbaOf(k));\n\tfor (let i = 0; i <= r; i++) {\n\t\tfor (let j = 0; j <= c; j++) {\n\t\t\tpoints.push({ x: bounds.x + (bounds.width * j) / c, y: bounds.y + (bounds.height * i) / r });\n\t\t\tconst k = i * (c + 1) + j;\n\t\t\tif (colors.colors?.[k]) out.push(colors.colors[k]);\n\t\t\telse if (corners) {\n\t\t\t\tconst u = j / c;\n\t\t\t\tconst v = i / r;\n\t\t\t\tconst top = corners[0].map((x, n) => lerp(x, corners[1][n], u));\n\t\t\t\tconst bottom = corners[3].map((x, n) => lerp(x, corners[2][n], u));\n\t\t\t\tout.push(vectorRgbaToCss(top.map((x, n) => lerp(x, bottom[n], v)) as VectorRgba));\n\t\t\t} else out.push('#ffffff');\n\t\t}\n\t}\n\treturn { type: 'mesh', rows: r, columns: c, points, colors: out };\n}\n\n/** A Catmull-Rom cubic through `p1` to `p2` (neighbours `p0`, `p3`): its four control points. */\nfunction catmull(p0: Vec2, p1: Vec2, p2: Vec2, p3: Vec2): [Vec2, Vec2, Vec2, Vec2] {\n\treturn [p1, { x: p1.x + (p2.x - p0.x) / 6, y: p1.y + (p2.y - p0.y) / 6 }, { x: p2.x - (p3.x - p1.x) / 6, y: p2.y - (p3.y - p1.y) / 6 }, p2];\n}\n\nfunction cubicAt(c: readonly Vec2[], t: number): Vec2 {\n\tconst s = 1 - t;\n\tconst a = s * s * s;\n\tconst b = 3 * s * s * t;\n\tconst d = 3 * s * t * t;\n\tconst e = t * t * t;\n\treturn { x: a * c[0].x + b * c[1].x + d * c[2].x + e * c[3].x, y: a * c[0].y + b * c[1].y + d * c[2].y + e * c[3].y };\n}\n\n/** A mesh with consistent arrays (rows / columns clamped, points and colours filled out), or null when it cannot be made so. */\nfunction meshOk(m: VectorMeshGradient): boolean {\n\tconst n = (m.rows + 1) * (m.columns + 1);\n\treturn m.rows >= 1 && m.columns >= 1 && m.points.length === n && m.colors.length === n;\n}\n\n/**\n * The mesh's lattice point at row `r`, column `c`, extended by one point past each edge in a\n * straight line (so the curves through an evenly spread edge run evenly to its end).\n */\nfunction meshLattice(m: VectorMeshGradient): (r: number, c: number) => Vec2 {\n\tconst cols = m.columns + 1;\n\tconst at = (r: number, c: number) => m.points[r * cols + c];\n\tconst ext = (a: Vec2, b: Vec2): Vec2 => ({ x: 2 * a.x - b.x, y: 2 * a.y - b.y });\n\tconst P = (r: number, c: number): Vec2 => {\n\t\tif (r < 0) return ext(P(0, c), P(1, c));\n\t\tif (r > m.rows) return ext(P(m.rows, c), P(m.rows - 1, c));\n\t\tif (c < 0) return ext(at(r, 0), at(r, 1));\n\t\tif (c > m.columns) return ext(at(r, m.columns), at(r, m.columns - 1));\n\t\treturn at(r, c);\n\t};\n\treturn P;\n}\n\n/** The point of the mesh's surface at patch (i, j), parameters (u, v) 0–1. */\nexport function vectorMeshPointAt(m: VectorMeshGradient, i: number, j: number, u: number, v: number): Vec2 {\n\tconst P = meshLattice(m);\n\t// The patch's sides: Catmull-Rom curves along its rows and columns of the lattice.\n\tconst top = catmull(P(i, j - 1), P(i, j), P(i, j + 1), P(i, j + 2));\n\tconst bottom = catmull(P(i + 1, j - 1), P(i + 1, j), P(i + 1, j + 1), P(i + 1, j + 2));\n\tconst left = catmull(P(i - 1, j), P(i, j), P(i + 1, j), P(i + 2, j));\n\tconst right = catmull(P(i - 1, j + 1), P(i, j + 1), P(i + 1, j + 1), P(i + 2, j + 1));\n\tconst t = cubicAt(top, u);\n\tconst b = cubicAt(bottom, u);\n\tconst l = cubicAt(left, v);\n\tconst r = cubicAt(right, v);\n\tconst [p00, p01, p11, p10] = [P(i, j), P(i, j + 1), P(i + 1, j + 1), P(i + 1, j)];\n\t// Coons: the two ruled surfaces minus the bilinear one.\n\tconst bl = (k: 'x' | 'y') => (1 - u) * (1 - v) * p00[k] + u * (1 - v) * p01[k] + u * v * p11[k] + (1 - u) * v * p10[k];\n\treturn { x: (1 - v) * t.x + v * b.x + (1 - u) * l.x + u * r.x - bl('x'), y: (1 - v) * t.y + v * b.y + (1 - u) * l.y + u * r.y - bl('y') };\n}\n\n/** The mesh's colour (straight alpha) at patch (i, j), parameters (u, v): its corners blended. */\nexport function vectorMeshColorAt(m: VectorMeshGradient, i: number, j: number, u: number, v: number): VectorRgba {\n\tconst cols = m.columns + 1;\n\tconst C = (r: number, c: number) => rgbaOf(m.colors[r * cols + c], m.opacities?.[r * cols + c] ?? 1);\n\tconst a = C(i, j);\n\tconst b = C(i, j + 1);\n\tconst c = C(i + 1, j + 1);\n\tconst d = C(i + 1, j);\n\treturn [0, 1, 2, 3].map((k) => (1 - u) * (1 - v) * a[k] + u * (1 - v) * b[k] + u * v * c[k] + (1 - u) * v * d[k]) as VectorRgba;\n}\n\n/** Each patch's outline (four Catmull-Rom sides), for drawing the mesh lines on the canvas: `M…C…` path data per row and column of the lattice. */\nexport function vectorMeshLines(m: VectorMeshGradient): { rows: Vec2[][][]; columns: Vec2[][][] } {\n\tconst P = meshLattice(m);\n\tconst rows: Vec2[][][] = [];\n\tfor (let i = 0; i <= m.rows; i++) rows.push(Array.from({ length: m.columns }, (_, j) => catmull(P(i, j - 1), P(i, j), P(i, j + 1), P(i, j + 2))));\n\tconst columns: Vec2[][][] = [];\n\tfor (let j = 0; j <= m.columns; j++) columns.push(Array.from({ length: m.rows }, (_, i) => catmull(P(i - 1, j), P(i, j), P(i + 1, j), P(i + 2, j))));\n\treturn { rows, columns };\n}\n\n// ---------------------------------------------------------------------------\n// Freeform gradients\n// ---------------------------------------------------------------------------\n\n/** Pieces each line segment is tessellated into for sampling. */\nconst LINE_STEPS = 16;\n\ninterface Source {\n\tx: number;\n\ty: number;\n\tc: VectorRgba;\n\tradius: number;\n}\n\nconst lerpSource = (a: Source, b: Source, t: number): Source => ({ x: lerp(a.x, b.x, t), y: lerp(a.y, b.y, t), c: a.c.map((v, k) => lerp(v, b.c[k], t)) as VectorRgba, radius: lerp(a.radius, b.radius, t) });\n\n/** The length freeform spreads are fractions of: half the longer side of the painted box. */\nexport function vectorFreeformSpreadScale(bounds: VectorBounds): number {\n\treturn Math.max(Math.abs(bounds.width), Math.abs(bounds.height)) / 2;\n}\n\n/** The cubic segments of line `line` of a freeform gradient (a Catmull-Rom curve through its points); empty for a line naming a missing point. */\nexport function vectorFreeformLineSegments(f: VectorFreeformGradient, line: number): [Vec2, Vec2, Vec2, Vec2][] {\n\tconst ix = f.lines?.[line];\n\tif (!ix) return [];\n\tconst pts = ix.map((i) => f.points[i]);\n\tif (pts.some((p) => !p)) return [];\n\tconst n = pts.length;\n\tconst out: [Vec2, Vec2, Vec2, Vec2][] = [];\n\tfor (let i = 0; i + 1 < n; i++) out.push(catmull(pts[Math.max(0, i - 1)], pts[i], pts[i + 1], pts[Math.min(n - 1, i + 2)]));\n\treturn out;\n}\n\n/** A freeform gradient ready to sample many spots (see `sampleVectorFreeform`). */\nexport interface VectorFreeformField {\n\tpoints: Source[];\n\tpieces: { a: Source; b: Source; share: number }[];\n\teps: number;\n}\n\n/** The colour field of a freeform gradient on a box whose spread scale is `scale` (lines tessellated once). */\nexport function vectorFreeformField(f: VectorFreeformGradient, scale: number): VectorFreeformField {\n\tconst src = (p: VectorFreeformPoint): Source => ({ x: p.x, y: p.y, c: rgbaOf(p.color, p.opacity ?? 1), radius: Math.min(1, Math.max(0, p.spread ?? 0)) * scale });\n\tconst points = f.points.map(src);\n\tconst pieces: VectorFreeformField['pieces'] = [];\n\t(f.lines ?? []).forEach((ix, l) => {\n\t\tconst v: Source[] = [];\n\t\tvectorFreeformLineSegments(f, l).forEach((c, s) => {\n\t\t\tconst a = points[ix[s]];\n\t\t\tconst b = points[ix[s + 1]];\n\t\t\tfor (let k = s === 0 ? 0 : 1; k <= LINE_STEPS; k++) {\n\t\t\t\tconst t = k / LINE_STEPS;\n\t\t\t\tconst at = cubicAt(c, t);\n\t\t\t\tv.push({ ...lerpSource(a, b, t), x: at.x, y: at.y });\n\t\t\t}\n\t\t});\n\t\tlet len = 0;\n\t\tfor (let k = 1; k < v.length; k++) len += Math.hypot(v[k].x - v[k - 1].x, v[k].y - v[k - 1].y);\n\t\tconst n = Math.max(1, v.length - 1);\n\t\tfor (let k = 1; k < v.length; k++) {\n\t\t\tconst d = Math.hypot(v[k].x - v[k - 1].x, v[k].y - v[k - 1].y);\n\t\t\tpieces.push({ a: v[k - 1], b: v[k], share: len > 0 ? d / len : 1 / n });\n\t\t}\n\t});\n\treturn { points, pieces, eps: 1e-9 * (Math.abs(scale) + 1) };\n}\n\n/** The freeform field's colour at `p` (straight alpha, 0–1). After vectorcraft's `Field::sample`. */\nexport function sampleVectorFreeform(field: VectorFreeformField, p: Vec2): VectorRgba {\n\tconst disc = { w: 0, c: [0, 0, 0, 0] };\n\tconst far = { w: 0, c: [0, 0, 0, 0] };\n\tconst add = (d: number, s: Source, share: number) => {\n\t\tlet acc: typeof disc;\n\t\tlet w: number;\n\t\tif (d < s.radius || d <= field.eps) {\n\t\t\t// The deeper inside a disc, the stronger: weights fade to nothing at its edge.\n\t\t\tacc = disc;\n\t\t\tw = (s.radius - d + field.eps) * share;\n\t\t} else {\n\t\t\tconst e = d - s.radius;\n\t\t\tacc = far;\n\t\t\tw = share / (e * e);\n\t\t}\n\t\tacc.w += w;\n\t\tfor (let k = 0; k < 4; k++) acc.c[k] += w * s.c[k];\n\t};\n\tfor (const s of field.points) add(Math.hypot(s.x - p.x, s.y - p.y), s, 1);\n\tfor (const piece of field.pieces) {\n\t\tconst vx = piece.b.x - piece.a.x;\n\t\tconst vy = piece.b.y - piece.a.y;\n\t\tconst l2 = vx * vx + vy * vy;\n\t\tconst t = l2 > 0 ? Math.min(1, Math.max(0, ((p.x - piece.a.x) * vx + (p.y - piece.a.y) * vy) / l2)) : 0;\n\t\tconst s = lerpSource(piece.a, piece.b, t);\n\t\tadd(Math.hypot(s.x - p.x, s.y - p.y), s, piece.share);\n\t}\n\tconst acc = disc.w > 0 ? disc : far;\n\tif (!(acc.w > 0 && Number.isFinite(acc.w))) return [0, 0, 0, 0];\n\treturn acc.c.map((v) => v / acc.w) as VectorRgba;\n}\n\n/**\n * The points a first freeform gradient gets on a shape with box `b`: a 2 × n grid (n = 2–4 along\n * the longer side), each moved to the nearest spot `inside` the shape when its place is not, coloured\n * along `colors` (first to last). After vectorcraft's `Freeform::auto`.\n */\nexport function autoVectorFreeformGradient(b: VectorBounds, colors: readonly string[], inside: (p: Vec2) => boolean = () => true): VectorFreeformGradient {\n\tconst w = Math.max(b.width, 1e-9);\n\tconst h = Math.max(b.height, 1e-9);\n\tconst long = Math.min(4, Math.max(2, Math.round((2 * Math.max(w, h)) / Math.min(w, h))));\n\tconst [cols, rows] = w >= h ? [long, 2] : [2, long];\n\tconst cell = (i: number, n: number) => (i + 0.5) / n;\n\tconst targets: Vec2[] = [];\n\t// Row by row, every other row backwards: neighbours in the list are neighbours on the art.\n\tfor (let j = 0; j < rows; j++) for (let k = 0; k < cols; k++) targets.push({ x: b.x + cell(j % 2 === 0 ? k : cols - 1 - k, cols) * w, y: b.y + cell(j, rows) * h });\n\tconst GRID = 24;\n\tconst candidates: Vec2[] = [];\n\tfor (let k = 0; k < GRID * GRID; k++) {\n\t\tconst p = { x: b.x + cell(k % GRID, GRID) * w, y: b.y + cell(Math.floor(k / GRID), GRID) * h };\n\t\tif (inside(p)) candidates.push(p);\n\t}\n\tconst apart = Math.min(w, h) * 0.15;\n\tconst placed: Vec2[] = [];\n\tfor (const t of targets) {\n\t\tlet at = t;\n\t\tif (!inside(t)) {\n\t\t\tlet best: Vec2 | null = null;\n\t\t\tlet bestD = Infinity;\n\t\t\tfor (const c of candidates) {\n\t\t\t\tif (!placed.every((q) => Math.hypot(q.x - c.x, q.y - c.y) >= apart)) continue;\n\t\t\t\tconst d = Math.hypot(c.x - t.x, c.y - t.y);\n\t\t\t\tif (d < bestD) {\n\t\t\t\t\tbest = c;\n\t\t\t\t\tbestD = d;\n\t\t\t\t}\n\t\t\t}\n\t\t\tat = best ?? t;\n\t\t}\n\t\tplaced.push(at);\n\t}\n\tconst palette = colors.length ? colors : ['#ffffff', '#000000'];\n\tconst n = placed.length;\n\tconst colorAt = (k: number) => {\n\t\tif (palette.length === 1) return palette[0];\n\t\tconst t = (k / Math.max(1, n - 1)) * (palette.length - 1);\n\t\tconst i = Math.min(palette.length - 2, Math.floor(t));\n\t\tconst a = rgbaOf(palette[i]);\n\t\tconst c = rgbaOf(palette[i + 1]);\n\t\treturn vectorRgbaToCss(a.map((v, q) => lerp(v, c[q], t - i)) as VectorRgba);\n\t};\n\treturn { type: 'freeform', points: placed.map((p, k) => ({ x: p.x, y: p.y, color: colorAt(k) })) };\n}\n\n// ---------------------------------------------------------------------------\n// Rendering\n// ---------------------------------------------------------------------------\n\nconst fmt = (n: number, digits: number) => {\n\tconst k = 10 ** digits;\n\tconst v = Math.round(n * k) / k;\n\treturn Object.is(v, -0) ? '0' : String(v);\n};\nconst quadD = (pts: readonly Vec2[], precision: number) => `M${pts.map((p) => `${fmt(p.x, precision)} ${fmt(p.y, precision)}`).join('L')}Z`;\n\n/** Options for `vectorShadedSvgDefs`. */\nexport interface VectorShadedSvgOptions {\n\t/** The shape's box in its own space (freeform spreads and cells). */\n\tbounds?: VectorBounds | null;\n\t/** The area the pattern covers (default `bounds` padded by 1). */\n\tarea?: VectorBounds | null;\n\t/** Cells per mesh patch side (default 8). */\n\tmeshCells?: number;\n\t/** Strips across a freeform gradient's longer side (default 96). */\n\tfreeformCells?: number;\n\tprecision?: number;\n}\n\n/**\n * A mesh or freeform paint as an SVG `<pattern>` of small flat tiles in the painted element's user\n * space (reference it as `url(#id)`). Each tile slightly overlaps the ones after it so no seams show\n * between them.\n */\nexport function vectorShadedSvgDefs(paint: VectorMeshGradient | VectorFreeformGradient, id: string, options: VectorShadedSvgOptions = {}): VectorSvgPatternDef[] {\n\tconst precision = options.precision ?? 3;\n\tconst bounds = options.bounds ?? null;\n\tconst area = options.area ?? (bounds ? { x: bounds.x - 1, y: bounds.y - 1, width: bounds.width + 2, height: bounds.height + 2 } : { x: 0, y: 0, width: 1, height: 1 });\n\tconst tiles: { d: string; fill: string }[] = [];\n\tconst gradients: SvgGradientDef[] = [];\n\tif (isVectorMeshGradient(paint)) {\n\t\tif (meshOk(paint)) {\n\t\t\tconst k = Math.max(1, Math.min(32, Math.round(options.meshCells ?? 8)));\n\t\t\tfor (let i = 0; i < paint.rows; i++) {\n\t\t\t\tfor (let j = 0; j < paint.columns; j++) {\n\t\t\t\t\tconst grid: Vec2[][] = [];\n\t\t\t\t\tfor (let a = 0; a <= k; a++) {\n\t\t\t\t\t\tconst row: Vec2[] = [];\n\t\t\t\t\t\tfor (let b = 0; b <= k; b++) row.push(vectorMeshPointAt(paint, i, j, b / k, a / k));\n\t\t\t\t\t\tgrid.push(row);\n\t\t\t\t\t}\n\t\t\t\t\tfor (let a = 0; a < k; a++) {\n\t\t\t\t\t\tfor (let b = 0; b < k; b++) {\n\t\t\t\t\t\t\tconst c = vectorMeshColorAt(paint, i, j, (b + 0.5) / k, (a + 0.5) / k);\n\t\t\t\t\t\t\tif (c[3] <= 0.0005) continue;\n\t\t\t\t\t\t\t// Grown a little past its right and bottom edges, over the cells drawn after it.\n\t\t\t\t\t\t\tconst q = [grid[a][b], grid[a][b + 1], grid[a + 1][b + 1], grid[a + 1][b]];\n\t\t\t\t\t\t\tconst cx = (q[0].x + q[1].x + q[2].x + q[3].x) / 4;\n\t\t\t\t\t\t\tconst cy = (q[0].y + q[1].y + q[2].y + q[3].y) / 4;\n\t\t\t\t\t\t\tconst grow = (p: Vec2) => ({ x: cx + (p.x - cx) * 1.12, y: cy + (p.y - cy) * 1.12 });\n\t\t\t\t\t\t\ttiles.push({ d: quadD(q.map(grow), precision), fill: vectorRgbaToCss(c) });\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t} else if (bounds && paint.points.length) {\n\t\t// Horizontal strips, each a linear gradient through the field sampled across it: smooth\n\t\t// along x, and strips thin enough that the steps between them do not show.\n\t\tconst field = vectorFreeformField(paint, vectorFreeformSpreadScale(bounds));\n\t\tconst n = Math.max(2, Math.min(256, Math.round(options.freeformCells ?? 96)));\n\t\tconst side = Math.max(area.width, area.height, 1e-9);\n\t\tconst rows = Math.max(2, Math.ceil((n * area.height) / side));\n\t\tconst samples = Math.max(2, Math.min(96, Math.ceil((n * area.width) / side) + 1));\n\t\tconst ch = area.height / rows;\n\t\tfor (let r = 0; r < rows; r++) {\n\t\t\tconst y = area.y + r * ch;\n\t\t\tconst stops: SvgGradientStop[] = [];\n\t\t\tfor (let k = 0; k < samples; k++) {\n\t\t\t\tconst t = k / (samples - 1);\n\t\t\t\tconst c = sampleVectorFreeform(field, { x: area.x + t * area.width, y: y + ch / 2 });\n\t\t\t\tconst opaque = vectorRgbaToCss([c[0], c[1], c[2], 1]);\n\t\t\t\tstops.push({ offset: `${fmt(t * 100, 3)}%`, stopColor: opaque, ...(c[3] < 0.9995 ? { stopOpacity: Math.round(Math.max(0, c[3]) * 1000) / 1000 } : {}) });\n\t\t\t}\n\t\t\tconst gid = `${id}-r${r}`;\n\t\t\tgradients.push({ id: gid, type: 'linear', attrs: { gradientUnits: 'userSpaceOnUse', x1: fmt(area.x, precision), y1: '0', x2: fmt(area.x + area.width, precision), y2: '0' }, stops });\n\t\t\t// Each strip reaches a quarter into the next, so no seam shows between them.\n\t\t\tconst h = r < rows - 1 ? ch * 1.25 : ch;\n\t\t\ttiles.push({ d: quadD([{ x: area.x, y }, { x: area.x + area.width, y }, { x: area.x + area.width, y: y + h }, { x: area.x, y: y + h }], precision), fill: `url(#${gid})` });\n\t\t}\n\t}\n\treturn [{ id, type: 'pattern', attrs: patternAttrs(area), gradients, tiles }];\n}\n\n// ---------------------------------------------------------------------------\n// Transforms, sanitizing and editing\n// ---------------------------------------------------------------------------\n\nconst apply = (m: VectorMatrix, p: Vec2): Vec2 => ({ x: m[0] * p.x + m[2] * p.y + m[4], y: m[1] * p.x + m[3] * p.y + m[5] });\n\n/** A mesh or freeform paint with every point mapped by `f`. */\nexport function mapVectorShadedPaint<T extends VectorMeshGradient | VectorFreeformGradient>(paint: T, f: (p: Vec2) => Vec2): T {\n\tif (isVectorMeshGradient(paint)) return { ...paint, points: paint.points.map((p) => f(p)) } as T;\n\treturn { ...paint, points: (paint as VectorFreeformGradient).points.map((p) => ({ ...p, ...f(p) })) } as T;\n}\n\n/** A mesh or freeform paint moved by `m` (it lives in the node's own space, like its geometry). */\nexport function transformVectorShadedPaint<T extends VectorMeshGradient | VectorFreeformGradient>(paint: T, m: VectorMatrix): T {\n\treturn mapVectorShadedPaint(paint, (p) => apply(m, p));\n}\n\nconst finite = (v: unknown): v is number => typeof v === 'number' && Number.isFinite(v);\nconst color = (v: unknown): string | null => (typeof v === 'string' && parseVectorColor(v) ? v : null);\n\n/** A mesh or freeform paint from untrusted input (agent commands, SVG data attributes), or null when it is malformed. */\nexport function sanitizeVectorShadedPaint(input: unknown): VectorMeshGradient | VectorFreeformGradient | null {\n\tif (!input || typeof input !== 'object') return null;\n\tconst r = input as Record<string, unknown>;\n\tif (r.type === 'mesh') {\n\t\tconst rows = r.rows;\n\t\tconst columns = r.columns;\n\t\tif (!finite(rows) || !finite(columns) || rows < 1 || columns < 1 || rows > VECTOR_MESH_MAX || columns > VECTOR_MESH_MAX || !Number.isInteger(rows) || !Number.isInteger(columns)) return null;\n\t\tconst n = (rows + 1) * (columns + 1);\n\t\tif (!Array.isArray(r.points) || !Array.isArray(r.colors) || r.points.length !== n || r.colors.length !== n) return null;\n\t\tconst points: Vec2[] = [];\n\t\tfor (const p of r.points as unknown[]) {\n\t\t\tconst q = p as Record<string, unknown>;\n\t\t\tif (!q || !finite(q.x) || !finite(q.y)) return null;\n\t\t\tpoints.push({ x: q.x, y: q.y });\n\t\t}\n\t\tconst colors: string[] = [];\n\t\tfor (const c of r.colors as unknown[]) {\n\t\t\tconst k = color(c);\n\t\t\tif (!k) return null;\n\t\t\tcolors.push(k);\n\t\t}\n\t\tconst out: VectorMeshGradient = { type: 'mesh', rows, columns, points, colors };\n\t\tif (Array.isArray(r.opacities) && r.opacities.length === n && r.opacities.every(finite)) out.opacities = (r.opacities as number[]).map((o) => Math.min(1, Math.max(0, o)));\n\t\treturn out;\n\t}\n\tif (r.type === 'freeform') {\n\t\tif (!Array.isArray(r.points) || !r.points.length) return null;\n\t\tconst points: VectorFreeformPoint[] = [];\n\t\tfor (const p of r.points as unknown[]) {\n\t\t\tconst q = p as Record<string, unknown>;\n\t\t\tconst c = q ? color(q.color) : null;\n\t\t\tif (!q || !finite(q.x) || !finite(q.y) || !c) return null;\n\t\t\tpoints.push({\n\t\t\t\tx: q.x,\n\t\t\t\ty: q.y,\n\t\t\t\tcolor: c,\n\t\t\t\t...(finite(q.opacity) && q.opacity < 1 ? { opacity: Math.max(0, q.opacity) } : {}),\n\t\t\t\t...(finite(q.spread) && q.spread > 0 ? { spread: Math.min(1, q.spread) } : {})\n\t\t\t});\n\t\t}\n\t\tconst out: VectorFreeformGradient = { type: 'freeform', points };\n\t\tif (Array.isArray(r.lines)) {\n\t\t\tconst lines = (r.lines as unknown[]).filter((l): l is number[] => Array.isArray(l) && l.length >= 2 && l.every((i) => Number.isInteger(i) && i >= 0 && i < points.length) && l.every((i, k) => k === 0 || i !== l[k - 1]));\n\t\t\tif (lines.length) out.lines = lines.map((l) => [...l]);\n\t\t}\n\t\treturn out;\n\t}\n\treturn null;\n}\n\n/** A freeform gradient with point `index` removed (lines through it close up; lines left with one point go), or null when it is the last point. */\nexport function removeVectorFreeformPoint(f: VectorFreeformGradient, index: number): VectorFreeformGradient | null {\n\tif (index < 0 || index >= f.points.length || f.points.length <= 1) return null;\n\tconst points = f.points.filter((_, k) => k !== index);\n\tconst lines = (f.lines ?? [])\n\t\t.map((l) =>\n\t\t\tl\n\t\t\t\t.filter((i) => i !== index)\n\t\t\t\t.map((i) => (i > index ? i - 1 : i))\n\t\t\t\t.filter((i, k, arr) => k === 0 || i !== arr[k - 1])\n\t\t)\n\t\t.filter((l) => l.length >= 2);\n\treturn { type: 'freeform', points, ...(lines.length ? { lines } : {}) };\n}\n\n/** The mesh lattice point nearest `p` within `radius`, or the freeform point: its index, or -1. */\nexport function nearestVectorShadingPoint(paint: VectorMeshGradient | VectorFreeformGradient, p: Vec2, radius: number): number {\n\tlet best = -1;\n\tlet bestD = radius;\n\tpaint.points.forEach((q, k) => {\n\t\tconst d = Math.hypot(q.x - p.x, q.y - p.y);\n\t\tif (d <= bestD) {\n\t\t\tbest = k;\n\t\t\tbestD = d;\n\t\t}\n\t});\n\treturn best;\n}\n","/**\n * Affine matrices in SVG order (`[a, b, c, d, e, f]`), shared by the vector and image editors.\n * Angles are degrees, clockwise on screen (y points down).\n */\nimport type { AffineMatrix, Vec2 } from './types';\n\nexport type { AffineMatrix };\n\nexport const IDENTITY_MATRIX: AffineMatrix = [1, 0, 0, 1, 0, 0];\n\n/** `a` then `b` (apply `a` first). */\nexport function multiplyMatrices(a: AffineMatrix, b: AffineMatrix): AffineMatrix {\n const [a0, a1, a2, a3, a4, a5] = a;\n const [b0, b1, b2, b3, b4, b5] = b;\n return [b0 * a0 + b2 * a1, b1 * a0 + b3 * a1, b0 * a2 + b2 * a3, b1 * a2 + b3 * a3, b0 * a4 + b2 * a5 + b4, b1 * a4 + b3 * a5 + b5];\n}\n\nexport const translateMatrix = (dx: number, dy: number): AffineMatrix => [1, 0, 0, 1, dx, dy];\n\nexport function scaleMatrix(sx: number, sy: number, origin: Vec2 = { x: 0, y: 0 }): AffineMatrix {\n return [sx, 0, 0, sy, origin.x - sx * origin.x, origin.y - sy * origin.y];\n}\n\n/** Rotation by `degrees` clockwise (y points down) around `origin`. */\nexport function rotateMatrix(degrees: number, origin: Vec2 = { x: 0, y: 0 }): AffineMatrix {\n const r = (degrees * Math.PI) / 180;\n const cos = Math.cos(r);\n const sin = Math.sin(r);\n return [cos, sin, -sin, cos, origin.x - cos * origin.x + sin * origin.y, origin.y - sin * origin.x - cos * origin.y];\n}\n\n/** `m` applied about `origin` instead of the coordinate origin. */\nexport function matrixAbout(m: AffineMatrix, origin: Vec2): AffineMatrix {\n return multiplyMatrices(multiplyMatrices(translateMatrix(-origin.x, -origin.y), m), translateMatrix(origin.x, origin.y));\n}\n\n/**\n * A skew by `ax` degrees horizontally (vertical lines lean right for positive angles:\n * x' = x + tan(ax)·y) and `ay` degrees vertically (y' = y + tan(ay)·x), about `origin`.\n */\nexport function skewMatrix(ax: number, ay: number, origin: Vec2 = { x: 0, y: 0 }): AffineMatrix {\n const tx = Math.tan((ax * Math.PI) / 180);\n const ty = Math.tan((ay * Math.PI) / 180);\n return matrixAbout([1, ty, tx, 1, 0, 0], origin);\n}\n\nexport function applyMatrix(m: AffineMatrix, p: Vec2): Vec2 {\n return { x: m[0] * p.x + m[2] * p.y + m[4], y: m[1] * p.x + m[3] * p.y + m[5] };\n}\n\nexport function isIdentityMatrix(m: AffineMatrix, eps = 1e-12): boolean {\n return Math.abs(m[0] - 1) < eps && Math.abs(m[1]) < eps && Math.abs(m[2]) < eps && Math.abs(m[3] - 1) < eps && Math.abs(m[4]) < eps && Math.abs(m[5]) < eps;\n}\n\n/** The inverse matrix (the identity for a singular one). */\nexport function invertMatrix(m: AffineMatrix): AffineMatrix {\n const [a, b, c, d, e, f] = m;\n const det = a * d - b * c;\n if (!det || !Number.isFinite(det)) return IDENTITY_MATRIX;\n return [d / det, -b / det, -c / det, a / det, (c * f - d * e) / det, (b * e - a * f) / det];\n}\n\n/** Applies only the linear part (for directions and offsets). */\nexport function applyMatrixLinear(m: AffineMatrix, v: Vec2): Vec2 {\n return { x: m[0] * v.x + m[2] * v.y, y: m[1] * v.x + m[3] * v.y };\n}\n\n/**\n * The rotation of a matrix in degrees, clockwise (y down), in (−180, 180]. For a mirrored\n * matrix it is the rotation left after undoing a horizontal flip, so a flipped rotated shape\n * keeps its angle.\n */\nexport function matrixRotation(m: AffineMatrix): number {\n const [a, b, c, d] = m;\n const mirrored = a * d - b * c < 0;\n const deg = ((mirrored ? Math.atan2(-b - c, d - a) : Math.atan2(b - c, a + d)) * 180) / Math.PI;\n return Math.abs(deg) < 1e-9 ? 0 : deg;\n}\n\n/**\n * Splits `m` into `residual` then `rigid` (`m = residual × rigid` in apply order): `rigid` is\n * the nearest rotation plus the translation, `residual` the linear rest (scale, skew,\n * reflection). An unrotated `m` gives an identity `rigid` and everything in `residual`.\n */\nexport function decomposeRigid(m: AffineMatrix): { rigid: AffineMatrix; residual: AffineMatrix } {\n const [a, b, c, d, e, f] = m;\n const deg = matrixRotation(m);\n if (deg === 0) return { rigid: IDENTITY_MATRIX, residual: m };\n const r = (deg * Math.PI) / 180;\n const cos = Math.cos(r);\n const sin = Math.sin(r);\n return {\n rigid: [cos, sin, -sin, cos, e, f],\n residual: [cos * a + sin * b, -sin * a + cos * b, cos * c + sin * d, -sin * c + cos * d, 0, 0],\n };\n}\n","/**\n * Live corners: a radius stored on an anchor, drawn as a round, inverted or chamfered cut when\n * the path is turned into curves. The stored anchors never change; `expandVectorCorners` is the\n * one place the cut geometry is made, and `subpathsToBezier` calls it, so rendering,\n * hit-testing, bounds, booleans, stroke outlines and SVG export all see the same shape.\n *\n * Ported from ArtCraft (MIT OR Apache-2.0, see THIRD_PARTY_NOTICES.md):\n * - figcraft `crates/doc/src/vector.rs` — `VectorNetwork::rounded` / `corner` and `trim`: each\n * side is trimmed by arc length (the radius clamped so a cut takes at most half of each\n * side) and the round cut is a cubic with handles `4/3 · tan(φ/4) · ρ` along the sides'\n * directions at the cut, φ the turn between them and ρ the radius of the circle through\n * both ends. That is exact at any angle and works where a curve meets a corner.\n * - vectorcraft `crates/geom/src/corners.rs` — `path_corners`, `Corner` (setback, max radius,\n * bisector and radius change for the drag widget) and `cut_corners` (inverted round and\n * chamfer kinds, trimming curved sides between cuts, a closed subpath whose first corner is\n * cut starting where that cut ends).\n */\nimport type { Point } from '../canvas/types.js';\nimport { segmentDerivative, segmentLength, segmentParamAtLength, segmentPoint, subSegment } from '../canvas/pathops/bezier.js';\nimport type { VectorAnchor, VectorCornerKind, VectorSubpath, Vec2 } from './types.js';\n\nconst EPS = 1e-9;\n/** Sides closer than this to straight on (or folded back), as the sine of their angle, make no corner. */\nconst MIN_SINE = 1e-6;\n\nconst sub = (a: Vec2, b: Vec2): Vec2 => ({ x: a.x - b.x, y: a.y - b.y });\nconst add = (a: Vec2, b: Vec2): Vec2 => ({ x: a.x + b.x, y: a.y + b.y });\nconst mul = (a: Vec2, k: number): Vec2 => ({ x: a.x * k, y: a.y * k });\nconst dot = (a: Vec2, b: Vec2) => a.x * b.x + a.y * b.y;\nconst cross = (a: Vec2, b: Vec2) => a.x * b.y - a.y * b.x;\nconst len = (a: Vec2) => Math.hypot(a.x, a.y);\nconst pt = (p: Vec2): Point => [p.x, p.y];\nconst vec = (p: Point): Vec2 => ({ x: p[0], y: p[1] });\nconst onAnchor = (a: VectorAnchor, h: Vec2 | null | undefined) => !h || (Math.abs(h.x - a.x) < EPS && Math.abs(h.y - a.y) < EPS);\n\n/** A side of a corner: the segment from the corner's anchor to a neighbour, as a cubic leaving the corner. */\nclass Side {\n\treadonly curve: Point[];\n\treadonly straight: boolean;\n\treadonly length: number;\n\tconstructor(a: VectorAnchor, h1: Vec2 | null | undefined, h2: Vec2 | null | undefined, b: VectorAnchor) {\n\t\tthis.straight = onAnchor(a, h1) && onAnchor(b, h2);\n\t\tthis.curve = this.straight ? [pt(a), pt(b)] : [pt(a), pt(h1 ?? a), pt(h2 ?? b), pt(b)];\n\t\tthis.length = this.straight ? Math.hypot(b.x - a.x, b.y - a.y) : segmentLength(this.curve);\n\t}\n\n\t/** Unit direction the side leaves the corner in (towards its first control point off the corner). */\n\tdirection(): Vec2 | null {\n\t\tconst p0 = vec(this.curve[0]);\n\t\tfor (const q of this.curve.slice(1)) {\n\t\t\tconst d = sub(vec(q), p0);\n\t\t\tconst l = len(d);\n\t\t\tif (l > EPS) return mul(d, 1 / l);\n\t\t}\n\t\treturn null;\n\t}\n\n\t/** The point `s` along the side from the corner: its parameter, position and the direction the side runs on in there. */\n\tat(s: number, u: Vec2): { t: number; p: Vec2; dir: Vec2 } {\n\t\tif (this.straight) {\n\t\t\tconst t = this.length > EPS ? Math.min(1, Math.max(0, s / this.length)) : 0;\n\t\t\treturn { t, p: add(vec(this.curve[0]), mul(u, s)), dir: u };\n\t\t}\n\t\tconst t = segmentParamAtLength(this.curve, s, this.length);\n\t\tconst d = vec(segmentDerivative(this.curve, t));\n\t\tconst l = len(d);\n\t\treturn { t, p: vec(segmentPoint(this.curve, t)), dir: l > EPS ? mul(d, 1 / l) : u };\n\t}\n}\n\n/**\n * A corner a live radius can cut: an anchor that is not smooth, where two sides (straight or\n * curved) meet at an angle. Positions are in the path node's own space.\n */\nexport interface VectorCornerInfo {\n\tsubpath: number;\n\tindex: number;\n\t/** Where the sides meet. */\n\tat: Vec2;\n\t/** Unit directions the sides leave the corner in: towards the previous anchor, then the next one. */\n\tu: Vec2;\n\tv: Vec2;\n\t/** The sides' lengths (along curves), in the same order. */\n\tlu: number;\n\tlv: number;\n\t/** Cosine and sine of the angle between the sides. */\n\tcos: number;\n\tsin: number;\n\t/** The angle between the sides in degrees (90 at a rectangle's corners). */\n\tangle: number;\n\t/** The largest radius that fits: its cut then reaches halfway along the shorter side. */\n\tmaxRadius: number;\n}\n\ninterface CornerData extends VectorCornerInfo {\n\tsideU: Side;\n\tsideV: Side;\n}\n\nfunction cornerOf(sp: VectorSubpath, s: number, i: number): CornerData | null {\n\tconst n = sp.anchors.length;\n\tif (n < 2 || (!sp.closed && (i === 0 || i === n - 1))) return null;\n\tif (n === 2 && sp.closed) return null;\n\tconst a = sp.anchors[i];\n\tif (a.type === 'smooth' || a.type === 'symmetric') return null;\n\tconst prev = sp.anchors[(i - 1 + n) % n];\n\tconst next = sp.anchors[(i + 1) % n];\n\tconst sideU = new Side(a, a.in, prev.out, prev);\n\tconst sideV = new Side(a, a.out, next.in, next);\n\tconst u = sideU.direction();\n\tconst v = sideV.direction();\n\tif (!u || !v) return null;\n\tconst lu = sideU.length;\n\tconst lv = sideV.length;\n\tif (!(lu > EPS && lv > EPS) || !Number.isFinite(lu) || !Number.isFinite(lv)) return null;\n\tconst cos = Math.max(-1, Math.min(1, dot(u, v)));\n\tconst sin = Math.abs(cross(u, v));\n\tif (sin <= MIN_SINE) return null;\n\treturn { subpath: s, index: i, at: { x: a.x, y: a.y }, u, v, lu, lv, cos, sin, angle: (Math.atan2(sin, cos) * 180) / Math.PI, maxRadius: ((Math.min(lu, lv) / 2) * sin) / (1 + cos), sideU, sideV };\n}\n\nconst strip = ({ sideU: _u, sideV: _v, ...info }: CornerData): VectorCornerInfo => info;\n\n/** The corner at anchor `index` of a subpath, or null when the anchor makes none (an open end, smooth, or straight on). */\nexport function vectorCornerAt(sp: VectorSubpath, index: number, subpath = 0): VectorCornerInfo | null {\n\tconst c = cornerOf(sp, subpath, index);\n\treturn c ? strip(c) : null;\n}\n\n/** Every corner of the subpaths that a live radius can cut, in anchor order. */\nexport function vectorCorners(subpaths: readonly VectorSubpath[]): VectorCornerInfo[] {\n\tconst out: VectorCornerInfo[] = [];\n\tsubpaths.forEach((sp, s) => {\n\t\tfor (let i = 0; i < sp.anchors.length; i++) {\n\t\t\tconst c = cornerOf(sp, s, i);\n\t\t\tif (c) out.push(strip(c));\n\t\t}\n\t});\n\treturn out;\n}\n\n/** How far from the corner a round cut of radius `r` meets each side: r / tan(angle / 2). */\nexport const cornerSetback = (c: Pick<VectorCornerInfo, 'cos' | 'sin'>, r: number) => (r * (1 + c.cos)) / c.sin;\n\n/** `radius` clamped to what the corner can draw (0 for negative or non-finite radii). */\nexport const fitCornerRadius = (c: Pick<VectorCornerInfo, 'maxRadius'>, radius: number) => (Number.isFinite(radius) ? Math.min(Math.max(0, radius), c.maxRadius) : 0);\n\n/** The point `k` along the corner's bisector, measured in (u + v): a round cut of radius r is centred at k = r / sin. */\nexport const cornerBisectorPoint = (c: VectorCornerInfo, k: number): Vec2 => add(c.at, mul(add(c.u, c.v), k));\n\n/** How much the radius grows when the round cut's centre moves by `d` (its part along the bisector, in radius units). */\nexport const cornerRadiusChange = (c: VectorCornerInfo, d: Vec2) => (dot(d, add(c.u, c.v)) * c.sin) / (2 + 2 * c.cos);\n\n/** Handle length per unit radius of a cubic arc spanning the angle whose cosine is `cos`: 4/3 · tan(angle / 4). */\nfunction arcHandle(cos: number): number {\n\tconst c = Math.max(-1, Math.min(1, cos));\n\tconst sinHalf = Math.sqrt(Math.max(0, (1 - c) / 2));\n\tconst cosHalf = Math.sqrt(Math.max(0, (1 + c) / 2));\n\treturn ((4 / 3) * sinHalf) / (1 + cosHalf);\n}\n\n/** The unit direction square to unit `a`, on `b`'s side. */\nfunction squareTo(a: Vec2, b: Vec2): Vec2 {\n\tconst w = sub(b, mul(a, dot(a, b)));\n\tconst l = len(w);\n\treturn l > EPS ? mul(w, 1 / l) : { x: 0, y: 0 };\n}\n\ninterface Cut {\n\t/** Parameters along each side (from the corner) where the cut meets it. */\n\ttu: number;\n\ttv: number;\n\tstart: Vec2;\n\t/** Handles of the cut's own segment (absent for a chamfer). */\n\tout: Vec2 | null;\n\tin: Vec2 | null;\n\tend: Vec2;\n\t/** Anchors between `start` and `end` (a smoothed corner's arc ends), with their handles. */\n\tinner?: VectorAnchor[];\n}\n\n/**\n * A smoothed round corner between straight sides (the squircle of figma-squircle and figcraft's\n * `corner_profile`, generalised from 90° to any angle): along each side it starts `(1 + s)` times\n * the round setback from the corner, eases in with a cubic whose second handle is where the arc's\n * tangent meets the side, follows a circular arc over `(1 − s)` of the turn, and eases out the same\n * way. Smoothing shrinks first when the cut would not fit halfway along the shorter side.\n */\nfunction smoothCut(c: CornerData, radius: number, smoothing: number): Cut | null {\n\tconst turn = Math.PI - Math.acos(Math.max(-1, Math.min(1, c.cos)));\n\tconst t = cornerSetback(c, radius);\n\tconst room = Math.min(c.lu, c.lv) / 2;\n\tlet s = Math.max(0, Math.min(1, smoothing));\n\tif ((1 + s) * t > room) s = Math.max(0, Math.min(s, room / t - 1));\n\tconst beta = (turn * s) / 2;\n\tif (!(beta > 1e-6) || !(t > EPS)) return null;\n\tconst p = Math.min((1 + s) * t, room);\n\tconst qa = radius * Math.tan(beta / 2);\n\tconst q = t - qa;\n\tconst side = (u: Vec2, v: Vec2) => {\n\t\tconst n = squareTo(u, v);\n\t\tconst e = add(c.at, mul(u, p));\n\t\tconst c1 = add(c.at, mul(u, (p + 2 * q) / 3));\n\t\tconst qp = add(c.at, mul(u, q));\n\t\tconst a = add(sub(qp, mul(u, qa * Math.cos(beta))), mul(n, qa * Math.sin(beta)));\n\t\treturn { e, c1, q: qp, a };\n\t};\n\tconst U = side(c.u, c.v);\n\tconst V = side(c.v, c.u);\n\t// The arc between the two ends, its handles along the tangents (away from the sides' crossings).\n\tconst sweep = turn * (1 - s);\n\tconst h = radius * (4 / 3) * Math.tan(sweep / 4);\n\tconst tanU = sub(U.a, U.q);\n\tconst tanV = sub(V.a, V.q);\n\tconst lu = len(tanU) || 1;\n\tconst lv = len(tanV) || 1;\n\tconst arcOut = add(U.a, mul(tanU, h / lu));\n\tconst arcIn = add(V.a, mul(tanV, h / lv));\n\tconst tu = c.sideU.at(p, c.u).t;\n\tconst tv = c.sideV.at(p, c.v).t;\n\treturn {\n\t\ttu,\n\t\ttv,\n\t\tstart: U.e,\n\t\tout: U.c1,\n\t\tinner: [\n\t\t\t{ x: U.a.x, y: U.a.y, in: U.q, out: arcOut },\n\t\t\t{ x: V.a.x, y: V.a.y, in: arcIn, out: V.q }\n\t\t],\n\t\tin: V.c1,\n\t\tend: V.e\n\t};\n}\n\nfunction cutCorner(c: CornerData, radius: number, kind: VectorCornerKind, smoothing = 0): Cut | null {\n\t// figcraft `corner`: trim each side by arc length, at most half of it.\n\tconst s = Math.min(cornerSetback(c, radius), Math.min(c.lu, c.lv) / 2);\n\tif (!(s > EPS)) return null;\n\tconst a = c.sideU.at(s, c.u);\n\tconst b = c.sideV.at(s, c.v);\n\tif (kind === 'chamfer') return { tu: a.t, tv: b.t, start: a.p, out: null, in: null, end: b.p };\n\tif (kind === 'inverted') {\n\t\t// vectorcraft `cut`: an arc centred on the corner through both ends, spanning the corner's angle.\n\t\tconst h = s * arcHandle(dot(a.dir, b.dir));\n\t\treturn { tu: a.t, tv: b.t, start: a.p, out: add(a.p, mul(squareTo(a.dir, b.dir), h)), in: add(b.p, mul(squareTo(b.dir, a.dir), h)), end: b.p };\n\t}\n\tif (smoothing > 0 && c.sideU.straight && c.sideV.straight) {\n\t\tconst smooth = smoothCut(c, radius, smoothing);\n\t\tif (smooth) return smooth;\n\t}\n\t// Round: d1, d2 point back towards the corner at the cut's ends; φ is the turn between them\n\t// and ρ the radius of the circle through both ends.\n\tconst d1 = mul(a.dir, -1);\n\tconst d2 = mul(b.dir, -1);\n\tconst turn = Math.acos(Math.max(-1, Math.min(1, -dot(d1, d2))));\n\tconst chord = len(sub(b.p, a.p));\n\tconst k = turn < 1e-9 ? chord / 3 : (((4 / 3) * Math.tan(turn / 4) * chord) / (2 * Math.sin(turn / 2)));\n\tif (!Number.isFinite(k)) return null;\n\treturn { tu: a.t, tv: b.t, start: a.p, out: add(a.p, mul(d1, k)), in: add(b.p, mul(d2, k)), end: b.p };\n}\n\nconst radiusOf = (a: VectorAnchor) => {\n\tconst r = a.corner?.radius;\n\treturn typeof r === 'number' && r > 0 && Number.isFinite(r) ? r : 0;\n};\n\n/** True when any anchor of the subpaths has a live corner radius. */\nexport function hasVectorCorners(subpaths: readonly VectorSubpath[]): boolean {\n\treturn subpaths.some((sp) => sp.anchors.some((a) => radiusOf(a) > 0));\n}\n\n/** One subpath with its corners cut; `sources[i]` is the stored anchor each output anchor comes from. */\nexport function expandVectorCornersOf(sp: VectorSubpath, subpath = 0): { subpath: VectorSubpath; sources: number[] } {\n\tconst n = sp.anchors.length;\n\tconst cuts: (Cut | null)[] = sp.anchors.map((a, i) => {\n\t\tconst r = radiusOf(a);\n\t\tif (!r) return null;\n\t\tconst c = cornerOf(sp, subpath, i);\n\t\tif (!c) return null;\n\t\tconst fitted = fitCornerRadius(c, r);\n\t\treturn fitted > EPS ? cutCorner(c, fitted, a.corner?.kind ?? 'round', a.corner?.smoothing ?? 0) : null;\n\t});\n\tif (!cuts.some(Boolean)) return { subpath: { closed: sp.closed, anchors: sp.anchors.map(plain) }, sources: sp.anchors.map((_, i) => i) };\n\t// Each segment from anchor j trimmed to what the cuts at its ends leave: its handles, or\n\t// undefined when it is untouched (null handles: a straight segment).\n\tconst trimmed: ({ out: Vec2 | null; in: Vec2 | null } | undefined)[] = sp.anchors.map((a, j) => {\n\t\tconst k = (j + 1) % n;\n\t\tif (k === 0 && !sp.closed) return undefined;\n\t\tconst b = sp.anchors[k];\n\t\tconst from = cuts[j];\n\t\tconst to = cuts[k];\n\t\tif (!from && !to) return undefined;\n\t\tif (onAnchor(a, a.out) && onAnchor(b, b.in)) return { out: null, in: null };\n\t\tconst s0 = from ? from.tv : 0;\n\t\tconst s1 = to ? 1 - to.tu : 1;\n\t\tconst seg: Point[] = [pt(a), pt(a.out ?? a), pt(b.in ?? b), pt(b)];\n\t\tconst part = subSegment(seg, s0, Math.max(s0, s1));\n\t\treturn { out: vec(part[1]), in: vec(part[2]) };\n\t});\n\tconst anchors: VectorAnchor[] = [];\n\tconst sources: number[] = [];\n\tlet closing: VectorAnchor | null = null;\n\tconst handleIn = (i: number, a: VectorAnchor) => {\n\t\tconst t = trimmed[(i - 1 + n) % n];\n\t\treturn t ? t.in : (a.in ?? null);\n\t};\n\tconst handleOut = (i: number, a: VectorAnchor) => {\n\t\tconst t = trimmed[i];\n\t\treturn t ? t.out : (a.out ?? null);\n\t};\n\tsp.anchors.forEach((a, i) => {\n\t\tconst c = cuts[i];\n\t\tif (!c) {\n\t\t\tanchors.push(withHandles({ x: a.x, y: a.y, ...(a.type ? { type: a.type } : {}) }, handleIn(i, a), handleOut(i, a)));\n\t\t\tsources.push(i);\n\t\t\treturn;\n\t\t}\n\t\tconst start = withHandles({ x: c.start.x, y: c.start.y }, handleIn(i, a), c.out);\n\t\tconst end = withHandles({ x: c.end.x, y: c.end.y }, c.in, handleOut(i, a));\n\t\tif (i === 0 && sp.closed) closing = start;\n\t\telse {\n\t\t\tanchors.push(start);\n\t\t\tsources.push(i);\n\t\t}\n\t\tfor (const inner of c.inner ?? []) {\n\t\t\tanchors.push({ ...inner });\n\t\t\tsources.push(i);\n\t\t}\n\t\tanchors.push(end);\n\t\tsources.push(i);\n\t});\n\tif (closing) {\n\t\tanchors.push(closing);\n\t\tsources.push(0);\n\t}\n\treturn { subpath: { closed: sp.closed, anchors }, sources };\n}\n\nfunction withHandles(a: VectorAnchor, hin: Vec2 | null, hout: Vec2 | null): VectorAnchor {\n\tif (hin && !onAnchor(a, hin)) a.in = { x: hin.x, y: hin.y };\n\tif (hout && !onAnchor(a, hout)) a.out = { x: hout.x, y: hout.y };\n\treturn a;\n}\n\nfunction plain(a: VectorAnchor): VectorAnchor {\n\tif (!('corner' in a)) return a;\n\tconst { corner: _c, ...rest } = a;\n\treturn rest;\n}\n\n/**\n * The subpaths with every live corner cut (round, inverted or chamfer), each radius no larger\n * than fits. A cut corner becomes two anchors and curved sides are trimmed to what the cuts\n * leave of them. Subpaths without corners come back unchanged.\n */\nexport function expandVectorCorners(subpaths: readonly VectorSubpath[]): VectorSubpath[] {\n\tif (!hasVectorCorners(subpaths)) return subpaths as VectorSubpath[];\n\treturn subpaths.map((sp, s) => (sp.anchors.some((a) => radiusOf(a) > 0) ? expandVectorCornersOf(sp, s).subpath : sp));\n}\n\n/**\n * Sets (or clears, with radius 0) the live corner of anchors. `kind` keeps each anchor's own\n * kind when omitted. Anchors that make no corner keep the radius too, so it applies once they do.\n */\nexport function setAnchorCorner(a: VectorAnchor, radius: number, kind?: VectorCornerKind, smoothing?: number): VectorAnchor {\n\tconst { corner, ...rest } = a;\n\tconst r = Number.isFinite(radius) ? Math.max(0, radius) : 0;\n\tconst k = kind ?? corner?.kind;\n\tconst s = Math.max(0, Math.min(1, smoothing ?? corner?.smoothing ?? 0));\n\tif (r <= 0 && !kind) return rest;\n\treturn { ...rest, corner: { radius: r, ...(k && k !== 'round' ? { kind: k } : {}), ...(s > 0 ? { smoothing: s } : {}) } };\n}\n\n/** The next corner kind (Alt-clicking a corner widget cycles round → inverted → chamfer). */\nexport function nextVectorCornerKind(kind: VectorCornerKind | undefined): VectorCornerKind {\n\treturn kind === 'inverted' ? 'chamfer' : kind === 'chamfer' ? 'round' : 'inverted';\n}\n\n/** Every anchor of a subpath given the same live corner (radius 0 clears them). */\nexport function setSubpathCorners(sp: VectorSubpath, radius: number, kind?: VectorCornerKind, smoothing?: number): VectorSubpath {\n\treturn { closed: sp.closed, anchors: sp.anchors.map((a) => setAnchorCorner(a, radius, kind, smoothing)) };\n}\n","/**\n * Variable-width stroke profiles: stroke widths at positions along a path (each subpath on its\n * own), interpolated smoothly and held flat before the first and after the last point. Each\n * point has a left and a right side scale (looking along the path on screen, y down), so a\n * stroke can grow on one side only.\n *\n * Ported from ArtCraft (MIT OR Apache-2.0, see THIRD_PARTY_NOTICES.md):\n * - figcraft `crates/doc/src/props.rs` — `WidthProfile` / `WidthPoint`: sanitising, side\n * scales, inserting and moving points, and the monotone cubic (Fritsch–Carlson) interpolation\n * that never overshoots its neighbouring points.\n * - vectorcraft `crates/doc/src/appearance.rs` — `WidthProfile` as `(t, left, right)` points,\n * discontinuous points (two points at one `t` make a step) and the profile presets.\n * - effectcraft `crates/path/src/varstroke.rs` — `width_factor`: the parametric Taper (lengths,\n * end widths, ease) and Wave (amount, cycles, phase) shapes, used here as profile generators.\n */\nimport type { VectorWidthPoint } from './types.js';\n\n/** The most points a profile keeps. */\nexport const VECTOR_WIDTH_PROFILE_MAX_POINTS = 64;\n/** The widest a side can be, as a multiple of the stroke width. */\nexport const VECTOR_WIDTH_PROFILE_MAX_SCALE = 1000;\n/** Positions closer than this are the same place (the two sides of a discontinuous point). */\nexport const VECTOR_WIDTH_SAME_T = 1e-6;\n\n/** Built-in profiles. `uniform` is the plain stroke (no profile). */\nexport type VectorWidthPreset = 'uniform' | 'taperStart' | 'taperEnd' | 'taperBoth' | 'bulge' | 'pinch' | 'teardrop' | 'wave' | 'pressure';\n\n/** One preset as a menu shows it. */\nexport interface VectorWidthPresetInfo {\n\tid: VectorWidthPreset;\n\tlabel: string;\n\tpoints: readonly VectorWidthPoint[];\n}\n\nconst sym = (t: number, s: number): VectorWidthPoint => ({ t, left: s, right: s });\n\n/** The built-in profiles, in menu order. */\nexport const VECTOR_WIDTH_PRESETS: readonly VectorWidthPresetInfo[] = [\n\t{ id: 'uniform', label: 'Uniform', points: [] },\n\t{ id: 'taperStart', label: 'Taper start', points: [sym(0, 0), sym(1, 1)] },\n\t{ id: 'taperEnd', label: 'Taper end', points: [sym(0, 1), sym(1, 0)] },\n\t{ id: 'taperBoth', label: 'Taper both', points: [sym(0, 0), sym(0.5, 1), sym(1, 0)] },\n\t// Full width at the ends, swelling to twice the width in the middle.\n\t{ id: 'bulge', label: 'Bulge', points: [sym(0, 1), sym(0.5, 2), sym(1, 1)] },\n\t// Full width at the ends, pinched to a quarter in the middle.\n\t{ id: 'pinch', label: 'Pinch', points: [sym(0, 1), sym(0.5, 0.25), sym(1, 1)] },\n\t// A round head a fifth of the way along, then a long taper to the end.\n\t{ id: 'teardrop', label: 'Teardrop', points: [sym(0, 0), sym(0.2, 1), sym(1, 0)] },\n\t// Two swells between narrow necks.\n\t{ id: 'wave', label: 'Wave', points: [sym(0, 0.3), sym(0.25, 1), sym(0.5, 0.3), sym(0.75, 1), sym(1, 0.3)] },\n\t// A pen stroke: a quick press, a slow lift.\n\t{ id: 'pressure', label: 'Pressure', points: [sym(0, 0.15), sym(0.12, 0.85), sym(0.45, 1), sym(0.8, 0.7), sym(1, 0.05)] }\n];\n\nexport const VECTOR_WIDTH_PRESET_IDS: readonly VectorWidthPreset[] = VECTOR_WIDTH_PRESETS.map((p) => p.id);\n\nconst clean = (v: unknown, max: number) => (typeof v === 'number' && Number.isFinite(v) ? Math.min(Math.max(v, 0), max) : null);\n\n/**\n * A profile as the outline uses it: finite points only, `t` in 0–1, side scales in 0–1000,\n * sorted by `t` (stable, so a step keeps its order), at most 64 points. Points missing a side\n * take the other side's scale.\n */\nexport function sanitizeWidthProfile(points: readonly Partial<VectorWidthPoint>[] | null | undefined): VectorWidthPoint[] {\n\tif (!Array.isArray(points)) return [];\n\tconst out: VectorWidthPoint[] = [];\n\tfor (const p of points) {\n\t\tif (!p || typeof p !== 'object') continue;\n\t\tconst t = clean(p.t, 1);\n\t\tconst l = clean(p.left, VECTOR_WIDTH_PROFILE_MAX_SCALE);\n\t\tconst r = clean(p.right, VECTOR_WIDTH_PROFILE_MAX_SCALE);\n\t\tif (t === null || (l === null && r === null)) continue;\n\t\tout.push({ t, left: l ?? r!, right: r ?? l! });\n\t\tif (out.length >= VECTOR_WIDTH_PROFILE_MAX_POINTS) break;\n\t}\n\treturn out.map((p, i) => [p, i] as const).sort((a, b) => a[0].t - b[0].t || a[1] - b[1]).map(([p]) => p);\n}\n\n/** True when the profile draws a plain stroke: no points, or every side at scale 1. */\nexport function isUniformWidthProfile(points: readonly VectorWidthPoint[] | null | undefined): boolean {\n\treturn !points?.length || points.every((p) => p.left === 1 && p.right === 1);\n}\n\n/** Slope of side `k` from point `i` to `i + 1` (0 when they share a position). */\nfunction secant(pts: readonly VectorWidthPoint[], i: number, k: 'left' | 'right'): number {\n\tconst a = pts[i];\n\tconst b = pts[i + 1];\n\treturn a && b && b.t - a.t > 1e-12 ? (b[k] - a[k]) / (b.t - a.t) : 0;\n}\n\n/** Fritsch–Carlson tangent: one-sided at the ends, the harmonic mean of the slopes inside, flat at local extremes. */\nfunction tangent(pts: readonly VectorWidthPoint[], i: number, k: 'left' | 'right'): number {\n\tconst last = pts.length - 1;\n\tif (i <= 0) return secant(pts, 0, k);\n\tif (i >= last) return secant(pts, last - 1, k);\n\tconst d0 = secant(pts, i - 1, k);\n\tconst d1 = secant(pts, i, k);\n\treturn d0 * d1 <= 0 ? 0 : (2 * d0 * d1) / (d0 + d1);\n}\n\nfunction interp(pts: readonly VectorWidthPoint[], t: number, k: 'left' | 'right'): number {\n\tconst first = pts[0];\n\tconst last = pts[pts.length - 1];\n\tif (!(t > first.t)) return first[k];\n\tif (t >= last.t) return last[k];\n\t// The last point at or before t (the second of a step at exactly t).\n\tlet i = 0;\n\twhile (i + 1 < pts.length && pts[i + 1].t <= t) i++;\n\tconst a = pts[i];\n\tconst b = pts[i + 1];\n\tconst h = b.t - a.t;\n\tif (h <= 1e-12) return b[k];\n\tconst u = (t - a.t) / h;\n\tconst u2 = u * u;\n\tconst u3 = u2 * u;\n\tconst w = (2 * u3 - 3 * u2 + 1) * a[k] + (u3 - 2 * u2 + u) * h * tangent(pts, i, k) + (3 * u2 - 2 * u3) * b[k] + (u3 - u2) * h * tangent(pts, i + 1, k);\n\treturn Math.max(0, w);\n}\n\n/**\n * The left and right side scales at `t` (0–1 along the subpath by length). Each side is\n * interpolated on its own with a monotone cubic, so the width never overshoots its points;\n * a profile without points is uniform (1, 1).\n */\nexport function widthProfileAt(points: readonly VectorWidthPoint[] | null | undefined, t: number): { left: number; right: number } {\n\tif (!points?.length) return { left: 1, right: 1 };\n\treturn { left: interp(points, t, 'left'), right: interp(points, t, 'right') };\n}\n\n/** The largest side scale (the interpolation never exceeds its points); 1 without a profile. */\nexport function widthProfileMaxScale(points: readonly VectorWidthPoint[] | null | undefined): number {\n\tif (!points?.length) return 1;\n\treturn points.reduce((m, p) => Math.max(m, p.left, p.right), 0);\n}\n\n/** The points of a preset (empty for `uniform`), or null for an unknown id. */\nexport function widthProfilePreset(id: string): VectorWidthPoint[] | null {\n\tconst p = VECTOR_WIDTH_PRESETS.find((q) => q.id === id);\n\treturn p ? p.points.map((q) => ({ ...q })) : null;\n}\n\n/** The preset a profile matches: `uniform` without one (or all at scale 1), `custom` when none matches. */\nexport function widthProfilePresetId(points: readonly VectorWidthPoint[] | null | undefined): VectorWidthPreset | 'custom' {\n\tif (isUniformWidthProfile(points)) return 'uniform';\n\tconst same = (a: readonly VectorWidthPoint[], b: readonly VectorWidthPoint[]) =>\n\t\ta.length === b.length && a.every((p, i) => Math.abs(p.t - b[i].t) < 1e-9 && Math.abs(p.left - b[i].left) < 1e-9 && Math.abs(p.right - b[i].right) < 1e-9);\n\treturn VECTOR_WIDTH_PRESETS.find((p) => p.points.length && same(points!, p.points))?.id ?? 'custom';\n}\n\n/** The profile of the reversed path: positions mirrored and the sides swapped. */\nexport function reverseWidthProfile(points: readonly VectorWidthPoint[]): VectorWidthPoint[] {\n\treturn points.map((p) => ({ t: 1 - p.t, left: p.right, right: p.left })).reverse();\n}\n\n/** The profile of a mirrored path (it runs the same way, but its sides swap). */\nexport function mirrorWidthProfile(points: readonly VectorWidthPoint[]): VectorWidthPoint[] {\n\treturn points.map((p) => ({ t: p.t, left: p.right, right: p.left }));\n}\n\n/** The points a profile edit starts from: the profile, or a uniform one with a point at each end. */\nfunction editable(points: readonly VectorWidthPoint[] | null | undefined): VectorWidthPoint[] {\n\treturn points?.length ? points.map((p) => ({ ...p })) : [sym(0, 1), sym(1, 1)];\n}\n\n/**\n * Adds a width point at `t` (side scales `left` / `right`, default: as wide as the stroke is\n * there) and returns the new profile and the point's index. Inserting at the position of an\n * existing point replaces it, unless `step` is set (which makes a discontinuous point).\n */\nexport function insertWidthPoint(\n\tpoints: readonly VectorWidthPoint[] | null | undefined,\n\tt: number,\n\tsides: { left?: number; right?: number } = {},\n\toptions: { step?: boolean } = {}\n): { points: VectorWidthPoint[]; index: number } {\n\tconst pts = editable(points);\n\tconst tt = Math.min(Math.max(Number.isFinite(t) ? t : 0, 0), 1);\n\tconst here = widthProfileAt(points?.length ? points : null, tt);\n\tconst p: VectorWidthPoint = {\n\t\tt: tt,\n\t\tleft: clean(sides.left, VECTOR_WIDTH_PROFILE_MAX_SCALE) ?? here.left,\n\t\tright: clean(sides.right, VECTOR_WIDTH_PROFILE_MAX_SCALE) ?? here.right\n\t};\n\tconst same = pts.findIndex((q) => Math.abs(q.t - tt) <= VECTOR_WIDTH_SAME_T);\n\tif (same >= 0 && !options.step) {\n\t\tpts[same] = { ...p, t: pts[same].t };\n\t\treturn { points: pts, index: same };\n\t}\n\tlet i = 0;\n\twhile (i < pts.length && pts[i].t <= tt) i++;\n\tif (pts.length >= VECTOR_WIDTH_PROFILE_MAX_POINTS) return { points: pts, index: Math.max(0, i - 1) };\n\tpts.splice(i, 0, p);\n\treturn { points: pts, index: i };\n}\n\n/**\n * Changes point `index`: moves it to `t` (kept between its neighbours, so indices stay put)\n * and / or sets its side scales. Out-of-range indices leave the profile as it is.\n */\nexport function setWidthPoint(points: readonly VectorWidthPoint[], index: number, patch: Partial<VectorWidthPoint>): VectorWidthPoint[] {\n\tconst pts = points.map((p) => ({ ...p }));\n\tconst p = pts[index];\n\tif (!p) return pts;\n\tif (typeof patch.t === 'number' && Number.isFinite(patch.t)) {\n\t\tconst lo = index > 0 ? pts[index - 1].t : 0;\n\t\tconst hi = index < pts.length - 1 ? pts[index + 1].t : 1;\n\t\tp.t = Math.min(Math.max(patch.t, lo), Math.max(hi, lo));\n\t}\n\tconst l = clean(patch.left, VECTOR_WIDTH_PROFILE_MAX_SCALE);\n\tconst r = clean(patch.right, VECTOR_WIDTH_PROFILE_MAX_SCALE);\n\tif (l !== null) p.left = l;\n\tif (r !== null) p.right = r;\n\treturn pts;\n}\n\n/** Removes the points at `indices`. */\nexport function removeWidthPoints(points: readonly VectorWidthPoint[], indices: readonly number[]): VectorWidthPoint[] {\n\tconst drop = new Set(indices);\n\treturn points.filter((_, i) => !drop.has(i)).map((p) => ({ ...p }));\n}\n\n// ---------------------------------------------------------------------------\n// Generators\n// ---------------------------------------------------------------------------\n\n/** effectcraft's ease from the tip (`u = 0`) to full width (`u = 1`): linear at 0, a quarter circle at 1. */\nfunction ease(u: number, e: number): number {\n\tconst x = Math.min(Math.max(u, 0), 1);\n\tconst round = Math.sqrt(Math.max(0, 1 - (1 - x) * (1 - x)));\n\treturn x + (round - x) * Math.min(Math.max(e, 0), 1);\n}\n\n/** A parametric taper (effectcraft's Stroke Taper), lengths as fractions of the path. */\nexport interface VectorTaperOptions {\n\t/** Fraction of the path the start taper covers (default 0). */\n\tstartLength?: number;\n\t/** Fraction the end taper covers (default 0). */\n\tendLength?: number;\n\t/** Width at the start as a fraction of the stroke width (default 0: a point). */\n\tstartWidth?: number;\n\tendWidth?: number;\n\t/** 0 linear, 1 a quarter circle bulging outwards (default 0). */\n\tstartEase?: number;\n\tendEase?: number;\n}\n\n/** A width wave (effectcraft's Stroke Wave): the width swings between `1 − amount` and 1. */\nexport interface VectorWaveOptions {\n\t/** 0–1 (default 0.5). */\n\tamount?: number;\n\t/** Whole cycles along the path (default 4). */\n\tcycles?: number;\n\t/** Degrees (default 0). */\n\tphase?: number;\n}\n\n/** The width factor at fraction `t` of a taper and / or a wave (effectcraft `width_factor`). */\nexport function taperWaveFactor(t: number, taper?: VectorTaperOptions | null, wave?: VectorWaveOptions | null): number {\n\tlet k = 1;\n\tif (taper) {\n\t\tlet ls = Math.max(0, taper.startLength ?? 0);\n\t\tlet le = Math.max(0, taper.endLength ?? 0);\n\t\t// Overlapping tapers share the path in proportion.\n\t\tif (ls + le > 1) {\n\t\t\tconst f = 1 / (ls + le);\n\t\t\tls *= f;\n\t\t\tle *= f;\n\t\t}\n\t\tconst sw = Math.min(Math.max(taper.startWidth ?? 0, 0), 1);\n\t\tconst ew = Math.min(Math.max(taper.endWidth ?? 0, 0), 1);\n\t\tif (ls > 0 && t < ls) k = Math.min(k, sw + (1 - sw) * ease(t / ls, taper.startEase ?? 0));\n\t\tif (le > 0 && t > 1 - le) k = Math.min(k, ew + (1 - ew) * ease((1 - t) / le, taper.endEase ?? 0));\n\t}\n\tif (wave) {\n\t\tconst cycles = wave.cycles ?? 4;\n\t\tconst amount = Math.min(Math.max(wave.amount ?? 0.5, 0), 1);\n\t\tif (cycles > 0 && amount > 0) {\n\t\t\tconst ph = 2 * Math.PI * t * cycles + ((wave.phase ?? 0) * Math.PI) / 180;\n\t\t\tk *= 1 - amount * (0.5 - 0.5 * Math.cos(ph));\n\t\t}\n\t}\n\treturn k;\n}\n\n/**\n * Samples a taper and / or wave into profile points (symmetric), simplified to within\n * `tolerance` of the factor (default 0.01). The monotone interpolation draws them back smoothly.\n */\nexport function generateWidthProfile(options: { taper?: VectorTaperOptions | null; wave?: VectorWaveOptions | null; samples?: number; tolerance?: number }): VectorWidthPoint[] {\n\tconst cycles = options.wave ? Math.max(0, options.wave.cycles ?? 4) : 0;\n\tconst n = Math.max(8, Math.min(VECTOR_WIDTH_PROFILE_MAX_POINTS * 4, options.samples ?? Math.ceil(32 + cycles * 16)));\n\tconst raw: [number, number][] = [];\n\tfor (let i = 0; i <= n; i++) raw.push([i / n, taperWaveFactor(i / n, options.taper, options.wave)]);\n\t// Keep the taper ends exactly.\n\tconst ts = [options.taper?.startLength, options.taper?.endLength !== undefined ? 1 - options.taper.endLength : undefined];\n\tfor (const t of ts) if (typeof t === 'number' && t > 0 && t < 1) raw.push([t, taperWaveFactor(t, options.taper, options.wave)]);\n\traw.sort((a, b) => a[0] - b[0]);\n\tconst kept = simplifySamples(raw, options.tolerance ?? 0.01, VECTOR_WIDTH_PROFILE_MAX_POINTS);\n\treturn kept.map(([t, k]) => sym(t, k));\n}\n\n/** Douglas–Peucker on (t, value) samples (vertical distance), then thinned to at most `max`. */\nfunction simplifySamples(samples: readonly [number, number][], tolerance: number, max: number): [number, number][] {\n\tif (samples.length <= 2) return samples.slice();\n\tconst keep = new Array(samples.length).fill(false);\n\tkeep[0] = keep[samples.length - 1] = true;\n\tconst stack: [number, number][] = [[0, samples.length - 1]];\n\twhile (stack.length) {\n\t\tconst [a, b] = stack.pop()!;\n\t\tconst [ta, va] = samples[a];\n\t\tconst [tb, vb] = samples[b];\n\t\tlet worst = -1;\n\t\tlet err = tolerance;\n\t\tfor (let i = a + 1; i < b; i++) {\n\t\t\tconst [t, v] = samples[i];\n\t\t\tconst lin = tb - ta > 1e-12 ? va + ((vb - va) * (t - ta)) / (tb - ta) : va;\n\t\t\tconst e = Math.abs(v - lin);\n\t\t\tif (e > err) {\n\t\t\t\terr = e;\n\t\t\t\tworst = i;\n\t\t\t}\n\t\t}\n\t\tif (worst >= 0) {\n\t\t\tkeep[worst] = true;\n\t\t\tstack.push([a, worst], [worst, b]);\n\t\t}\n\t}\n\tlet out = samples.filter((_, i) => keep[i]);\n\twhile (out.length > max) out = out.filter((_, i) => i === 0 || i === out.length - 1 || i % 2 === 0);\n\treturn out;\n}\n\n/** Pen pressure that draws the stroke's own width (a mouse reports 0.5 while a button is down). */\nexport const VECTOR_PRESSURE_NOMINAL = 0.5;\n\n/**\n * A profile from pen pressure recorded along a stroke: `(t, pressure 0–1)` samples in order.\n * The width scale is pressure ÷ 0.5 (so half pressure draws the stroke's width, full pressure\n * twice it), at least 0.05; the samples are simplified to within `tolerance` (default 0.02).\n * Returns an empty (uniform) profile when every sample is the same.\n */\nexport function pressureWidthProfile(samples: readonly { t: number; pressure: number }[], options: { tolerance?: number } = {}): VectorWidthPoint[] {\n\tconst raw: [number, number][] = samples\n\t\t.filter((s) => Number.isFinite(s.t) && Number.isFinite(s.pressure))\n\t\t.map((s) => [Math.min(Math.max(s.t, 0), 1), Math.max(0.05, Math.min(1, Math.max(0, s.pressure)) / VECTOR_PRESSURE_NOMINAL)] as [number, number]);\n\tif (raw.length < 2) return [];\n\tif (raw.every((s) => Math.abs(s[1] - raw[0][1]) < 1e-6)) return [];\n\treturn simplifySamples(raw, options.tolerance ?? 0.02, VECTOR_WIDTH_PROFILE_MAX_POINTS).map(([t, k]) => sym(t, Math.round(k * 1000) / 1000));\n}\n","/**\n * The outline of a variable-width stroke, as a clean filled Bézier path.\n *\n * Each subpath is flattened (finely enough for the width to vary smoothly) and the stroke is\n * the union of positively wound pieces: one trapezoid per flattened segment (its ends at the\n * local side widths), a wedge on the outer side of every bend (the style's join at the path's\n * own corners, round inside curves) and the caps. Filled with the non-zero rule the union is\n * exact whatever the profile does; it is built as the boundary those pieces add up to (see\n * `variableStrokeRings`), normalised with the polygon boolean engine, and every ring is refitted\n * with cubics (`fitCubics`) to within the tolerance — a real Bézier outline, not a polyline.\n *\n * Ported from ArtCraft effectcraft `crates/path/src/varstroke.rs` (`outline`, `dash_intervals`)\n * (MIT OR Apache-2.0, see THIRD_PARTY_NOTICES.md), with one-sided widths after figcraft\n * `crates/pathops/src/width.rs` (`variable_outline`).\n */\nimport type { Point } from '../canvas/types.js';\nimport { fitCubics, isStraightCubic } from '../canvas/curveFit.js';\nimport { polygonBoolean } from '../canvas/polygonBoolean.js';\nimport {\n\tflattenChain,\n\tpathToContours,\n\tsegmentLength,\n\tsegmentNearest,\n\tsegmentTangent,\n\ttype BezierPath,\n\ttype BezierSegment\n} from '../canvas/pathops/bezier.js';\nimport type { StrokeCap, StrokeJoin } from '../canvas/pathops/stroke.js';\nimport type { VectorWidthPoint } from './types.js';\nimport { widthProfileAt } from './width.js';\n\nexport interface VariableStrokeOptions {\n\t/** Stroke width: a side scale of 1 reaches half of it from the centre line. */\n\twidth: number;\n\tprofile: readonly VectorWidthPoint[];\n\t/** Joins at the path's own corners (default `miter`); bends inside curves are always round. */\n\tjoin?: StrokeJoin;\n\t/** Default `butt`. */\n\tcap?: StrokeCap;\n\t/** Default 4 (as SVG). */\n\tmiterLimit?: number;\n\t/** Dash pattern (as SVG); the profile still runs along the whole subpath. */\n\tdash?: readonly number[];\n\tdashOffset?: number;\n\t/** Largest distance of the result from the exact outline (default 0.05). */\n\ttolerance?: number;\n}\n\n/** Width samples per subpath at least (so the width varies smoothly along long straight runs). */\nconst SAMPLES_PER_SUBPATH = 128;\n/** The most dashes one subpath makes. */\nconst MAX_DASHES = 5000;\n\ntype Vec = [number, number];\nconst sub = (a: Point, b: Point): Vec => [a[0] - b[0], a[1] - b[1]];\nconst along = (p: Point, v: Vec, k: number): Point => [p[0] + v[0] * k, p[1] + v[1] * k];\nconst lerp = (a: Point, b: Point, u: number): Point => [a[0] + (b[0] - a[0]) * u, a[1] + (b[1] - a[1]) * u];\nconst dist = (a: Point, b: Point) => Math.hypot(a[0] - b[0], a[1] - b[1]);\nconst unitOf = (v: Vec): Vec => {\n\tconst l = Math.hypot(v[0], v[1]);\n\treturn l > 0 ? [v[0] / l, v[1] / l] : [1, 0];\n};\n/** The left normal of a direction on screen (y down): `(dy, −dx)`. */\nconst leftNormal = (d: Vec): Vec => [d[1], -d[0]];\n\n/** A flattened subpath: points, their arc lengths, and which are the path's own vertices. */\ninterface Poly {\n\tpts: Point[];\n\ts: number[];\n\tcorner: boolean[];\n\tclosed: boolean;\n}\n\nfunction flatten(segments: readonly BezierSegment[], closed: boolean, tol: number): Poly | null {\n\tconst pts: Point[] = [];\n\tconst corner: boolean[] = [];\n\tconst push = (p: Point, isCorner: boolean) => {\n\t\tconst last = pts[pts.length - 1];\n\t\tif (last && dist(last, p) <= 1e-9) {\n\t\t\tcorner[corner.length - 1] ||= isCorner;\n\t\t\treturn;\n\t\t}\n\t\tpts.push(p);\n\t\tcorner.push(isCorner);\n\t};\n\tfor (const seg of segments) {\n\t\tconst flat = flattenChain([seg], tol);\n\t\t// flattenChain drops a closing duplicate; segments that end where they start keep it.\n\t\tif (dist(seg[0], seg[seg.length - 1]) <= 1e-12 && flat.length > 1) flat.push(seg[seg.length - 1]);\n\t\tflat.forEach((p, i) => push(p, i === 0 || i === flat.length - 1));\n\t}\n\tif (closed && pts.length > 2 && dist(pts[0], pts[pts.length - 1]) > 1e-9) push(pts[0], true);\n\tif (pts.length < 2) return null;\n\t// Subdivide so no piece is longer than the width sampling step.\n\tlet total = 0;\n\tfor (let i = 1; i < pts.length; i++) total += dist(pts[i - 1], pts[i]);\n\tif (!(total > 0)) return null;\n\tconst step = Math.max(total / SAMPLES_PER_SUBPATH, tol);\n\tconst fine: Point[] = [pts[0]];\n\tconst fineCorner: boolean[] = [corner[0]];\n\tfor (let i = 1; i < pts.length; i++) {\n\t\tconst n = Math.max(1, Math.ceil(dist(pts[i - 1], pts[i]) / step));\n\t\tfor (let k = 1; k <= n; k++) {\n\t\t\tfine.push(k === n ? pts[i] : lerp(pts[i - 1], pts[i], k / n));\n\t\t\tfineCorner.push(k === n ? corner[i] : false);\n\t\t}\n\t}\n\tconst s = [0];\n\tfor (let i = 1; i < fine.length; i++) s.push(s[i - 1] + dist(fine[i - 1], fine[i]));\n\treturn { pts: fine, s, corner: fineCorner, closed };\n}\n\n/** Arc-length intervals that are \"on\" for a dash pattern on a path `len` long (effectcraft `dash_intervals`). */\nexport function dashIntervals(pattern: readonly number[], offset: number, len: number): [number, number][] {\n\tlet pat = pattern.map((v) => (Number.isFinite(v) ? Math.max(0, v) : 0));\n\tif (pat.length % 2 === 1) pat = [...pat, ...pat];\n\tconst period = pat.reduce((a, b) => a + b, 0);\n\tif (pat.length < 2 || !(period > 1e-9) || !(len > 0)) return [[0, len]];\n\tlet pos = (((Number.isFinite(offset) ? offset : 0) % period) + period) % period;\n\tlet idx = 0;\n\twhile (pos >= pat[idx]) {\n\t\tpos -= pat[idx];\n\t\tidx = (idx + 1) % pat.length;\n\t}\n\tconst out: [number, number][] = [];\n\tlet s = 0;\n\tlet guard = 0;\n\twhile (s < len && guard++ < MAX_DASHES * pat.length) {\n\t\tconst e = Math.min(s + pat[idx] - pos, len);\n\t\tif (idx % 2 === 0 && e >= s) out.push([s, e]);\n\t\ts += pat[idx] - pos;\n\t\tpos = 0;\n\t\tidx = (idx + 1) % pat.length;\n\t}\n\treturn out;\n}\n\n/** The point at arc length `t` of a polyline and the index of the segment it lies on. */\nfunction at(poly: Poly, t: number): [Point, number] {\n\tlet i = 1;\n\twhile (i < poly.pts.length - 1 && poly.s[i] <= t) i++;\n\tconst a = poly.s[i - 1];\n\tconst b = poly.s[i];\n\tconst u = b > a ? Math.min(Math.max((t - a) / (b - a), 0), 1) : 0;\n\treturn [lerp(poly.pts[i - 1], poly.pts[i], u), i];\n}\n\n/** Points of an arc around `c` from angle `a0` turning by `sweep`, radius going from `r0` to `r1` (ends excluded). */\nfunction arcPoints(c: Point, a0: number, sweep: number, r0: number, r1: number, tol: number): Point[] {\n\tconst r = Math.max(r0, r1);\n\tif (!(r > tol * 0.5) || !Number.isFinite(sweep)) return [];\n\tconst stepAngle = 2 * Math.acos(Math.min(Math.max(1 - tol / r, -1), 1));\n\tconst n = Math.min(128, Math.max(2, Math.ceil(Math.abs(sweep) / Math.max(stepAngle, 1e-3))));\n\tconst out: Point[] = [];\n\tfor (let k = 1; k < n; k++) {\n\t\tconst f = k / n;\n\t\tconst a = a0 + sweep * f;\n\t\tconst rr = r0 + (r1 - r0) * f;\n\t\tout.push([c[0] + Math.cos(a) * rr, c[1] + Math.sin(a) * rr]);\n\t}\n\treturn out;\n}\n\n/** Where segments `a0 → a1` and `b0 → b1` cross, if they do (strictly inside `b`, anywhere past the start of `a`). */\nfunction crossing(a0: Point, a1: Point, b0: Point, b1: Point): Point | null {\n\tconst r = sub(a1, a0);\n\tconst q = sub(b1, b0);\n\tconst den = r[0] * q[1] - r[1] * q[0];\n\tif (Math.abs(den) < 1e-12) return null;\n\tconst w = sub(b0, a0);\n\tconst t = (w[0] * q[1] - w[1] * q[0]) / den;\n\tconst u = (w[0] * r[1] - w[1] * r[0]) / den;\n\treturn t > 1e-9 && t <= 1 && u >= 0 && u < 1 - 1e-9 ? [a0[0] + r[0] * t, a0[1] + r[1] * t] : null;\n}\n\n/**\n * The rings of a variable-width stroke in the path's own space; filled with the non-zero rule\n * they are the stroke.\n *\n * effectcraft builds the stroke as a union of positively wound pieces: a trapezoid per flattened\n * segment (its ends at the local side widths), a wedge on the outer side of every bend and the\n * caps. Unioning thousands of overlapping pieces is slow, so each run is emitted as the boundary\n * those pieces add up to instead (winding numbers add, so the non-zero fill is the same): the\n * offset sides with the outer join between them, and on the inner side of a bend either the point\n * where the two offsets cross (the region cut off is covered by both trapezoids) or, when they do\n * not cross, a detour through the centre point (which keeps the winding right when segments are\n * shorter than the width). A closed subpath gives two rings, an open run one.\n */\nexport function variableStrokeRings(path: BezierPath, options: VariableStrokeOptions): Point[][] {\n\tconst half = options.width / 2;\n\tif (!(half > 0) || !Number.isFinite(half)) return [];\n\tconst tol = options.tolerance && options.tolerance > 0 ? options.tolerance : 0.05;\n\tconst join = options.join ?? 'miter';\n\tconst cap = options.cap ?? 'butt';\n\tconst miterLimit = options.miterLimit && options.miterLimit >= 1 ? options.miterLimit : 4;\n\tconst rings: Point[][] = [];\n\tconst push = (out: Point[], p: Point) => {\n\t\tconst last = out[out.length - 1];\n\t\tif (!last || dist(last, p) > 1e-12) out.push(p);\n\t};\n\tfor (const contour of pathToContours(path)) {\n\t\tif (!contour.segments.length) continue;\n\t\t// Chords of the offsets lose area on the outer side of a curve; a quarter of the tolerance keeps that well inside it.\n\t\tconst poly = flatten(contour.segments, contour.closed, Math.min(tol, half) / 4);\n\t\tif (!poly) continue;\n\t\tconst len = poly.s[poly.s.length - 1];\n\t\tconst sides = (s: number): [number, number] => {\n\t\t\tconst w = widthProfileAt(options.profile, s / len);\n\t\t\treturn [w.left * half, w.right * half];\n\t\t};\n\t\tconst intervals = options.dash?.some((v) => v > 0) ? dashIntervals(options.dash, options.dashOffset ?? 0, len) : [[0, len] as [number, number]];\n\t\tconst whole = intervals.length === 1 && intervals[0][0] <= 0 && intervals[0][1] >= len;\n\t\tfor (const [a, b] of intervals) {\n\t\t\tconst [pa, ia] = at(poly, a);\n\t\t\tconst [pb, ib] = at(poly, b);\n\t\t\tconst pts: { p: Point; s: number; corner: boolean }[] = [{ p: pa, s: a, corner: poly.corner[0] && a <= 0 }];\n\t\t\tfor (let i = ia; i < ib; i++) pts.push({ p: poly.pts[i], s: poly.s[i], corner: poly.corner[i] });\n\t\t\tpts.push({ p: pb, s: b, corner: false });\n\t\t\tconst run = pts.filter((q, i) => i === 0 || dist(q.p, pts[i - 1].p) > 1e-9);\n\t\t\tif (run.length < 2) {\n\t\t\t\t// A zero-length dash: only its caps show.\n\t\t\t\tconst [l, r] = sides(a);\n\t\t\t\tconst w = (l + r) / 2;\n\t\t\t\tif (cap === 'round' && w > 0) rings.push([[pa[0] + w, pa[1]], ...arcPoints(pa, 0, 2 * Math.PI, w, w, tol)]);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tconst closed = whole && poly.closed;\n\t\t\tconst m = run.length - 1;\n\t\t\tconst dirs: Vec[] = [];\n\t\t\tfor (let i = 0; i < m; i++) dirs.push(unitOf(sub(run[i + 1].p, run[i].p)));\n\t\t\tconst normals = dirs.map(leftNormal);\n\t\t\tconst w = run.map((q) => sides(q.s));\n\n\t\t\t/** One side (`sigma` +1 left, −1 right) along the run, joins included. */\n\t\t\tconst side = (sigma: 1 | -1): Point[] => {\n\t\t\t\tconst k = sigma > 0 ? 0 : 1;\n\t\t\t\tconst S = (i: number) => along(run[i].p, normals[i], sigma * w[i][k]);\n\t\t\t\tconst E = (i: number) => along(run[i + 1].p, normals[i], sigma * w[i + 1][k]);\n\t\t\t\tconst out: Point[] = [S(0)];\n\t\t\t\tfor (let i = 0; i < m; i++) {\n\t\t\t\t\tconst seam = i === m - 1;\n\t\t\t\t\tif (seam && !closed) {\n\t\t\t\t\t\tpush(out, E(i));\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\tconst j = seam ? 0 : i + 1;\n\t\t\t\t\tconst p = run[i + 1].p;\n\t\t\t\t\tconst d0 = dirs[i];\n\t\t\t\t\tconst d1 = dirs[j];\n\t\t\t\t\tconst cross = d0[0] * d1[1] - d0[1] * d1[0];\n\t\t\t\t\tconst dot = d0[0] * d1[0] + d0[1] * d1[1];\n\t\t\t\t\tconst r0 = w[i + 1][k];\n\t\t\t\t\tconst r1 = w[j][k];\n\t\t\t\t\tconst e = E(i);\n\t\t\t\t\tconst st = S(j);\n\t\t\t\t\tif (Math.abs(cross) < 1e-12 && dot > 0) {\n\t\t\t\t\t\tpush(out, e);\n\t\t\t\t\t\tif (!seam) push(out, st);\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t\tconst uturn = Math.abs(cross) < 1e-12;\n\t\t\t\t\t// Turning right on screen puts the left side outside the bend (a U-turn: the left side).\n\t\t\t\t\tconst outer = uturn ? sigma > 0 : cross * sigma > 0;\n\t\t\t\t\tif (!outer) {\n\t\t\t\t\t\tconst x = seam ? null : crossing(out[out.length - 1], e, st, E(j));\n\t\t\t\t\t\tif (x) push(out, x);\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tpush(out, e);\n\t\t\t\t\t\t\tpush(out, p);\n\t\t\t\t\t\t\tif (!seam) push(out, st);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t\tpush(out, e);\n\t\t\t\t\tconst theta = uturn ? Math.PI : Math.atan2(cross, dot);\n\t\t\t\t\tconst r = (r0 + r1) / 2;\n\t\t\t\t\tconst kind: StrokeJoin = run[i + 1].corner || (seam && poly.corner[0]) ? join : 'round';\n\t\t\t\t\tif (r > 1e-9) {\n\t\t\t\t\t\tif (kind === 'round') {\n\t\t\t\t\t\t\tif (r * (1 - Math.cos(Math.abs(theta) / 2)) > tol * 0.25) {\n\t\t\t\t\t\t\t\tfor (const q of arcPoints(p, Math.atan2(e[1] - p[1], e[0] - p[0]), theta, r0, r1, tol)) push(out, q);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t} else if (kind === 'miter') {\n\t\t\t\t\t\t\tconst halfCos = Math.cos(theta / 2);\n\t\t\t\t\t\t\tconst bis: Vec = [normals[i][0] + normals[j][0], normals[i][1] + normals[j][1]];\n\t\t\t\t\t\t\tconst bl = Math.hypot(bis[0], bis[1]);\n\t\t\t\t\t\t\tif (halfCos > 1e-6 && 1 / halfCos <= miterLimit && bl > 1e-9) push(out, along(p, bis, (sigma * r) / halfCos / bl));\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tif (!seam) push(out, st);\n\t\t\t\t}\n\t\t\t\tif (closed && out.length > 1 && dist(out[0], out[out.length - 1]) <= 1e-12) out.pop();\n\t\t\t\treturn out;\n\t\t\t};\n\t\t\tconst left = side(1);\n\t\t\tconst right = side(-1);\n\t\t\tif (closed) {\n\t\t\t\trings.push(left, right.reverse());\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\t// Caps: round or square around each end, from one side to the other.\n\t\t\tconst capPoints = (atStart: boolean): Point[] => {\n\t\t\t\tif (cap === 'butt') return [];\n\t\t\t\tconst i = atStart ? 0 : m;\n\t\t\t\tconst d = atStart ? dirs[0] : dirs[m - 1];\n\t\t\t\tconst [l, r] = w[i];\n\t\t\t\tif (!(l + r > 1e-9)) return [];\n\t\t\t\tconst p = run[i].p;\n\t\t\t\tconst n = leftNormal(d);\n\t\t\t\tconst L = along(p, n, l);\n\t\t\t\tconst R = along(p, n, -r);\n\t\t\t\tif (cap === 'round') {\n\t\t\t\t\t// Half a turn around the outside: right side to left at the start, left to right at the end.\n\t\t\t\t\tconst a0 = Math.atan2(d[1], d[0]) + (atStart ? Math.PI / 2 : -Math.PI / 2);\n\t\t\t\t\treturn arcPoints(p, a0, Math.PI, atStart ? r : l, atStart ? l : r, tol);\n\t\t\t\t}\n\t\t\t\tconst ext = (l + r) / 2;\n\t\t\t\tconst o: Vec = atStart ? [-d[0], -d[1]] : d;\n\t\t\t\treturn atStart ? [along(R, o, ext), along(L, o, ext)] : [along(L, o, ext), along(R, o, ext)];\n\t\t\t};\n\t\t\tconst ring: Point[] = [];\n\t\t\tfor (const q of [...left, ...capPoints(false), ...right.reverse(), ...capPoints(true)]) push(ring, q);\n\t\t\tif (ring.length > 2) rings.push(ring);\n\t\t}\n\t}\n\treturn rings;\n}\n\n/**\n * The outline of a variable-width stroke of `path` (side widths from `profile`), as a clean\n * Bézier path: overlaps removed, outer rings and holes, each refitted with cubics to within\n * `tolerance` of the exact outline. Fill it with the non-zero rule (either rule works).\n */\nexport function variableStrokeOutline(path: BezierPath, options: VariableStrokeOptions): BezierPath {\n\tconst pieces = variableStrokeRings(path, options);\n\tif (!pieces.length) return [];\n\tconst tol = options.tolerance && options.tolerance > 0 ? options.tolerance : 0.05;\n\tlet polygons;\n\ttry {\n\t\tpolygons = polygonBoolean('union', [{ rings: pieces, fillRule: 'nonzero' }]);\n\t} catch {\n\t\treturn [];\n\t}\n\tconst out: BezierPath = [];\n\tfor (const polygon of polygons) {\n\t\tfor (const ring of polygon) {\n\t\t\tif (ring.length < 3) continue;\n\t\t\tconst cubics = fitCubics(ring, tol, { closed: true, cornerAngleDeg: 25 });\n\t\t\tif (!cubics.length) continue;\n\t\t\tout.push({ type: 'M', x: cubics[0].p0[0], y: cubics[0].p0[1] });\n\t\t\tcubics.forEach((c, i) => {\n\t\t\t\tif (isStraightCubic(c, tol * 0.02)) {\n\t\t\t\t\tif (i < cubics.length - 1) out.push({ type: 'L', x: c.p3[0], y: c.p3[1] });\n\t\t\t\t} else out.push({ type: 'C', x1: c.p1[0], y1: c.p1[1], x2: c.p2[0], y2: c.p2[1], x: c.p3[0], y: c.p3[1] });\n\t\t\t});\n\t\t\tout.push({ type: 'Z' });\n\t\t}\n\t}\n\treturn out;\n}\n\n/**\n * Where point `p` lies relative to the stroke's centre line: the nearest point's contour,\n * its position `t` by length (0–1), the distance, and the side (`left` looking along the\n * path on screen) — what hit-testing and the width tool need.\n */\nexport function nearestStrokePosition(\n\tpath: BezierPath,\n\tp: Point,\n\t/** Only this contour (subpath) of the path. */\n\tonly?: number\n): { contour: number; t: number; distance: number; side: 'left' | 'right'; point: Point; tangent: Vec; length: number } | null {\n\tlet best: ReturnType<typeof nearestStrokePosition> = null;\n\tpathToContours(path).forEach((c, ci) => {\n\t\tif (!c.segments.length || (only !== undefined && ci !== only)) return;\n\t\tconst lengths = c.segments.map((s) => segmentLength(s));\n\t\tconst total = lengths.reduce((a, b) => a + b, 0);\n\t\tif (!(total > 0)) return;\n\t\tlet acc = 0;\n\t\tc.segments.forEach((seg, si) => {\n\t\t\tconst near = segmentNearest(seg, p);\n\t\t\tif (!best || near.distance < best.distance) {\n\t\t\t\tconst s = acc + segmentLength(seg, 0, near.t);\n\t\t\t\tconst tan = segmentTangent(seg, near.t);\n\t\t\t\tconst pt = seg.length === 2 ? lerp(seg[0], seg[1], near.t) : evalSeg(seg, near.t);\n\t\t\t\tconst n = leftNormal([tan[0], tan[1]]);\n\t\t\t\tconst side = (p[0] - pt[0]) * n[0] + (p[1] - pt[1]) * n[1] >= 0 ? 'left' : 'right';\n\t\t\t\tbest = { contour: ci, t: Math.min(Math.max(s / total, 0), 1), distance: near.distance, side, point: pt, tangent: [tan[0], tan[1]], length: total };\n\t\t\t}\n\t\t\tacc += lengths[si];\n\t\t});\n\t});\n\treturn best;\n}\n\nfunction evalSeg(seg: BezierSegment, t: number): Point {\n\t// de Casteljau\n\tlet pts = seg.map((q) => [q[0], q[1]] as Point);\n\twhile (pts.length > 1) pts = pts.slice(1).map((q, i) => lerp(pts[i], q, t));\n\treturn pts[0];\n}\n\n/** The point and unit tangent at position `t` (0–1 by length) of contour `index` of `path`. */\nexport function strokePositionPoint(path: BezierPath, index: number, t: number): { point: Point; tangent: Vec } | null {\n\tconst c = pathToContours(path)[index];\n\tif (!c?.segments.length) return null;\n\tconst lengths = c.segments.map((s) => segmentLength(s));\n\tconst total = lengths.reduce((a, b) => a + b, 0);\n\tlet want = Math.min(Math.max(t, 0), 1) * total;\n\tfor (let i = 0; i < c.segments.length; i++) {\n\t\tconst seg = c.segments[i];\n\t\tif (want <= lengths[i] + 1e-12 || i === c.segments.length - 1) {\n\t\t\t// Bisect the parameter for the remaining length.\n\t\t\tlet lo = 0;\n\t\t\tlet hi = 1;\n\t\t\tconst target = Math.min(want, lengths[i]);\n\t\t\tfor (let k = 0; k < 40; k++) {\n\t\t\t\tconst mid = (lo + hi) / 2;\n\t\t\t\tif (segmentLength(seg, 0, mid) < target) lo = mid;\n\t\t\t\telse hi = mid;\n\t\t\t}\n\t\t\tconst u = (lo + hi) / 2;\n\t\t\tconst tan = segmentTangent(seg, u);\n\t\t\treturn { point: evalSeg(seg, u), tangent: [tan[0], tan[1]] };\n\t\t}\n\t\twant -= lengths[i];\n\t}\n\treturn null;\n}\n","/**\n * Stroke options of vector paths: alignment (centre, inside, outside) and arrowheads at the\n * ends of open paths. Everything here works on a path's Bézier outline in one space (the\n * node's own, or the document's), so the canvases, hit-testing, SVG export and Outline Stroke\n * share it.\n *\n * Ported from ArtCraft (MIT OR Apache-2.0, see THIRD_PARTY_NOTICES.md):\n * - figcraft `crates/pathops/src/lib.rs` — `stroke_outline_of`: an inside stroke is a stroke of\n * twice the width intersected with the fill, an outside one twice the width minus the fill,\n * and only closed shapes have an inside (open paths stroke centred).\n * - vectorcraft `crates/effects/src/stroke/arrow.rs` — arrowhead shapes, sizes and insets (where\n * the stroke stops under each head), `tip` vs `extend` alignment and trimming the stroke by\n * arc length under the head.\n */\nimport type { Point } from '../canvas/types.js';\nimport {\n\tcontoursToPath,\n\tdistanceToBezierPath,\n\tpathToContours,\n\tpointInBezierPath,\n\tsegmentLength,\n\tsegmentTangent,\n\ttrimSegments,\n\ttype BezierContour,\n\ttype BezierPath,\n\ttype BezierSegment\n} from '../canvas/pathops/bezier.js';\nimport { pathBoolean, type PathOperandInput } from '../canvas/pathops/boolean.js';\nimport { outlineStroke } from '../canvas/pathops/stroke.js';\nimport type { VectorArrowhead, VectorStrokeAlign, VectorStyle, VectorWidthPoint, Vec2 } from './types.js';\nimport { nearestStrokePosition, variableStrokeOutline } from './varstroke.js';\nimport { isUniformWidthProfile, sanitizeWidthProfile, widthProfileAt, widthProfileMaxScale } from './width.js';\n\n/** Handle length that makes a cubic approximate a quarter circle. */\nconst KAPPA = 0.5522847498307936;\n/** Where the notch of the (notched) arrow sits, as a fraction of the head's length. */\nconst NOTCH = 0.7;\n\n/** One arrowhead: a filled outline (nonzero) painted with the stroke's paint. */\nexport interface VectorArrowheadShape {\n\tend: 'start' | 'end';\n\tkind: VectorArrowhead;\n\ttip: Vec2;\n\t/** Unit direction the head points in. */\n\tdir: Vec2;\n\t/** Distance from the tip back to where the stroke ends under the head. */\n\tinset: number;\n\tpath: BezierPath;\n}\n\n/** What the stroke of a path draws. */\nexport interface VectorStrokeParts {\n\t/** Where the stroke sits (`center` for open shapes, whatever the style says). */\n\talign: VectorStrokeAlign;\n\t/** The line the stroke follows: the outline, shortened under `tip`-aligned heads. */\n\tline: BezierPath;\n\t/** The stroke width to draw `line` with: twice the style's width for inside / outside (half is clipped away). */\n\tdrawWidth: number;\n\theads: VectorArrowheadShape[];\n}\n\n/** True when the path has subpaths and all of them are closed (only such shapes have an inside). */\nexport function isClosedBezierShape(path: BezierPath): boolean {\n\tconst contours = pathToContours(path).filter((c) => c.segments.length > 0);\n\treturn contours.length > 0 && contours.every((c) => c.closed);\n}\n\n/** The alignment a stroke is drawn with: the style's, or `center` for open shapes. */\nexport function effectiveStrokeAlign(style: Pick<VectorStyle, 'strokeAlign'>, closedShape: boolean): VectorStrokeAlign {\n\tconst a = style.strokeAlign ?? 'center';\n\treturn closedShape ? a : 'center';\n}\n\n/** The style's width profile, sanitised, or null when the stroke is uniform. */\nexport function strokeWidthProfileOf(style: Pick<VectorStyle, 'strokeWidthProfile'>): VectorWidthPoint[] | null {\n\tif (!style.strokeWidthProfile?.length) return null;\n\tconst p = sanitizeWidthProfile(style.strokeWidthProfile);\n\treturn isUniformWidthProfile(p) ? null : p;\n}\n\n/** True when the style asks for more than a plain centred stroke (an alignment, arrowheads or a width profile). */\nexport function hasStrokeExtras(style: VectorStyle): boolean {\n\treturn (style.strokeAlign ?? 'center') !== 'center' || !!style.startArrow || !!style.endArrow || !!strokeWidthProfileOf(style);\n}\n\n/**\n * The area of the stroke along `parts.line` before alignment clipping: SVG's stroke for a\n * uniform width, the variable-width outline (`variableStrokeOutline`) for a profiled one.\n */\nexport function vectorStrokeLineArea(parts: Pick<VectorStrokeParts, 'line' | 'drawWidth'>, style: VectorStyle, tolerance?: number): BezierPath {\n\tconst profile = strokeWidthProfileOf(style);\n\tconst dash = style.strokeDasharray?.length ? { dash: style.strokeDasharray } : {};\n\tconst join = style.strokeLinejoin ?? 'miter';\n\tconst cap = style.strokeLinecap ?? 'butt';\n\tif (profile) return variableStrokeOutline(parts.line, { width: parts.drawWidth, profile, join, cap, ...dash, ...(tolerance ? { tolerance } : {}) });\n\treturn outlineStroke(parts.line, { width: parts.drawWidth, join, cap, ...dash, ...(tolerance ? { tolerance } : {}) });\n}\n\nconst capExtent = (style: VectorStyle, width: number) => (style.strokeLinecap === 'round' || style.strokeLinecap === 'square' ? width / 2 : 0);\n\n/**\n * The weight of a head: the stroke's width just before it times the head's scale (at least\n * 0.25). A head is 4 weights long and wide. On a variable-width stroke the width there is the\n * profile's (the mean of its two sides at that end), floored at the stroke width, so a stroke\n * that tapers to nothing still gets a full-size head and one that swells gets a bigger one.\n */\nexport function arrowheadWeight(style: VectorStyle, end: 'start' | 'end'): number {\n\tconst scale = end === 'start' ? style.startArrowScale : style.endArrowScale;\n\tconst s = typeof scale === 'number' && scale > 0 && Number.isFinite(scale) ? scale : 1;\n\tconst width = style.strokeWidth ?? 1;\n\tconst profile = strokeWidthProfileOf(style);\n\tconst at = profile ? widthProfileAt(profile, end === 'start' ? 0 : 1) : null;\n\tconst here = at ? Math.max(width, (width * (at.left + at.right)) / 2) : width;\n\treturn Math.max(0.25, here * s);\n}\n\n/** Distance from the tip where the stroke ends, for a stroke whose cap reaches `cap` past its end. */\nexport function arrowheadInset(kind: VectorArrowhead, hw: number, cap: number): number {\n\tconst l = 4 * hw;\n\tconst solid = (back: number) => Math.max(back / 2, cap);\n\tswitch (kind) {\n\t\tcase 'triangle':\n\t\tcase 'circle':\n\t\tcase 'square':\n\t\t\treturn solid(l);\n\t\tcase 'arrow':\n\t\t\treturn solid(NOTCH * l);\n\t\tcase 'bar':\n\t\t\treturn solid(0.75 * hw);\n\t\tcase 'open':\n\t\t\t// The inner corner of the chevron: arm / sin(half angle).\n\t\t\treturn Math.max((hw * Math.sqrt(l * l + (l * l) / 4)) / (l / 2), cap);\n\t}\n}\n\nconst v = (x: number, y: number): Vec2 => ({ x, y });\nconst plus = (a: Vec2, b: Vec2, k = 1): Vec2 => ({ x: a.x + b.x * k, y: a.y + b.y * k });\nconst unit = (a: Vec2): Vec2 => {\n\tconst l = Math.hypot(a.x, a.y);\n\treturn l > 0 ? { x: a.x / l, y: a.y / l } : { x: 1, y: 0 };\n};\n\nfunction polygon(pts: Vec2[]): BezierPath {\n\treturn [{ type: 'M', x: pts[0].x, y: pts[0].y }, ...pts.slice(1).map((p) => ({ type: 'L' as const, x: p.x, y: p.y })), { type: 'Z' }];\n}\n\nfunction circle(c: Vec2, r: number): BezierPath {\n\tconst k = r * KAPPA;\n\tconst { x, y } = c;\n\treturn [\n\t\t{ type: 'M', x: x + r, y },\n\t\t{ type: 'C', x1: x + r, y1: y + k, x2: x + k, y2: y + r, x, y: y + r },\n\t\t{ type: 'C', x1: x - k, y1: y + r, x2: x - r, y2: y + k, x: x - r, y },\n\t\t{ type: 'C', x1: x - r, y1: y - k, x2: x - k, y2: y - r, x, y: y - r },\n\t\t{ type: 'C', x1: x + k, y1: y - r, x2: x + r, y2: y - k, x: x + r, y },\n\t\t{ type: 'Z' }\n\t];\n}\n\n/** The outline of a `kind` head of weight `hw` with its tip at `tip`, pointing along unit `dir`. */\nexport function arrowheadPath(kind: VectorArrowhead, tip: Vec2, dir: Vec2, hw: number): BezierPath {\n\tconst n = v(-dir.y, dir.x);\n\tconst l = 4 * hw;\n\tconst half = l / 2;\n\tconst base = plus(tip, dir, -l);\n\tswitch (kind) {\n\t\tcase 'triangle':\n\t\t\treturn polygon([tip, plus(base, n, half), plus(base, n, -half)]);\n\t\tcase 'arrow':\n\t\t\treturn polygon([tip, plus(base, n, half), plus(tip, dir, -NOTCH * l), plus(base, n, -half)]);\n\t\tcase 'open': {\n\t\t\t// Arms `hw` thick from the tip to the base corners, cut square at their ends.\n\t\t\tconst t = hw;\n\t\t\tconst a = plus(base, n, half);\n\t\t\tconst b = plus(base, n, -half);\n\t\t\tconst ua = unit(plus(a, tip, -1));\n\t\t\tconst ub = unit(plus(b, tip, -1));\n\t\t\tconst na = v(-ua.y, ua.x);\n\t\t\tconst nb = v(ub.y, -ub.x);\n\t\t\tconst inner = plus(tip, dir, -(t * Math.hypot(a.x - tip.x, a.y - tip.y)) / half);\n\t\t\treturn polygon([tip, a, plus(a, na, t), inner, plus(b, nb, t), b]);\n\t\t}\n\t\tcase 'circle':\n\t\t\treturn circle(plus(tip, dir, -half), half);\n\t\tcase 'square':\n\t\t\treturn polygon([plus(tip, n, half), plus(base, n, half), plus(base, n, -half), plus(tip, n, -half)]);\n\t\tcase 'bar': {\n\t\t\tconst t = 0.75 * hw;\n\t\t\treturn polygon([plus(tip, n, half), plus(plus(tip, n, half), dir, -t), plus(plus(tip, n, -half), dir, -t), plus(tip, n, -half)]);\n\t\t}\n\t}\n}\n\nconst toVec = (p: Point): Vec2 => ({ x: p[0], y: p[1] });\nconst segLen = (s: BezierSegment) => segmentLength(s);\n\n/** The end point of a contour and the unit direction pointing out of it there. */\nfunction endOf(segs: readonly BezierSegment[], atStart: boolean): { p: Vec2; out: Vec2 } {\n\tconst long = (s: BezierSegment) => segLen(s) > 1e-9;\n\tif (atStart) {\n\t\tconst s = segs.find(long) ?? segs[0];\n\t\tconst t = segmentTangent(s, 0);\n\t\treturn { p: toVec(segs[0][0]), out: v(-t[0], -t[1]) };\n\t}\n\tconst s = [...segs].reverse().find(long) ?? segs[segs.length - 1];\n\tconst t = segmentTangent(s, 1);\n\tconst last = segs[segs.length - 1];\n\treturn { p: toVec(last[last.length - 1]), out: v(t[0], t[1]) };\n}\n\n/** The point `dist` along the contour from its start (or back from its end), if it is that long. */\nfunction pointAlong(segs: readonly BezierSegment[], fromStart: boolean, dist: number): Vec2 | null {\n\tconst order = fromStart ? segs : [...segs].reverse();\n\tlet acc = 0;\n\tfor (const s of order) {\n\t\tconst l = segLen(s);\n\t\tif (acc + l >= dist) {\n\t\t\tconst want = fromStart ? dist - acc : l - (dist - acc);\n\t\t\tconst pts = trimSegments([s], 0, want);\n\t\t\tconst p = pts.length ? pts[0][pts[0].length - 1] : s[0];\n\t\t\treturn toVec(p);\n\t\t}\n\t\tacc += l;\n\t}\n\treturn null;\n}\n\n/**\n * The stroke of `path` as `style` draws it: its alignment, the line it follows (shortened under\n * `tip`-aligned heads) and its arrowheads. Heads go on the start of the first subpath and the\n * end of the last one, when those are open.\n */\nexport function vectorStrokeParts(path: BezierPath, style: VectorStyle): VectorStrokeParts {\n\tconst width = style.strokeWidth ?? 1;\n\tconst contours = pathToContours(path).filter((c) => c.segments.length > 0);\n\tconst closedShape = contours.length > 0 && contours.every((c) => c.closed);\n\tconst align = effectiveStrokeAlign(style, closedShape);\n\tconst drawWidth = align === 'center' ? width : width * 2;\n\tconst heads: VectorArrowheadShape[] = [];\n\tif (!contours.length || (!style.startArrow && !style.endArrow)) return { align, line: path, drawWidth, heads };\n\tconst first = contours[0];\n\tconst last = contours[contours.length - 1];\n\tconst cap = capExtent(style, width);\n\tconst tipMode = style.arrowAlign === 'tip';\n\tconst trims = contours.map(() => [0, 0]);\n\tconst place = (end: 'start' | 'end', contour: BezierContour, ci: number) => {\n\t\tconst kind = end === 'start' ? style.startArrow : style.endArrow;\n\t\tif (!kind || contour.closed) return;\n\t\tconst hw = arrowheadWeight(style, end);\n\t\tconst inset = arrowheadInset(kind, hw, cap);\n\t\tconst atStart = end === 'start';\n\t\tconst { p, out } = endOf(contour.segments, atStart);\n\t\tlet tip: Vec2;\n\t\tlet dir: Vec2;\n\t\tif (tipMode) {\n\t\t\t// Point along the chord from where the stroke now ends to the end point.\n\t\t\tconst q = pointAlong(contour.segments, atStart, inset);\n\t\t\tconst d = q ? v(p.x - q.x, p.y - q.y) : null;\n\t\t\tdir = d && Math.hypot(d.x, d.y) > 1e-9 ? unit(d) : out;\n\t\t\ttip = p;\n\t\t\ttrims[ci][atStart ? 0 : 1] = inset;\n\t\t} else {\n\t\t\ttip = plus(p, out, inset);\n\t\t\tdir = out;\n\t\t}\n\t\theads.push({ end, kind, tip, dir, inset, path: arrowheadPath(kind, tip, dir, hw) });\n\t};\n\tplace('start', first, 0);\n\tplace('end', last, contours.length - 1);\n\tif (!tipMode || !heads.length) return { align, line: path, drawWidth, heads };\n\tconst trimmed: BezierContour[] = contours.map((c, i) => {\n\t\tconst [s0, s1] = trims[i];\n\t\tif (!s0 && !s1) return c;\n\t\tconst lengths = c.segments.map(segLen);\n\t\tconst total = lengths.reduce((a, b) => a + b, 0);\n\t\treturn { closed: false, segments: total - s1 > s0 ? trimSegments(c.segments, s0, total - s1, lengths) : [] };\n\t});\n\treturn { align, line: contoursToPath(trimmed), drawWidth, heads };\n}\n\n/**\n * The area the stroke paints, as one filled path: the outlined stroke (joins, caps and dashes\n * as SVG) clipped by the alignment (against the fill, read with the style's `fillRule`), plus\n * the arrowheads.\n */\nexport function vectorStrokeOutlinePath(path: BezierPath, style: VectorStyle): BezierPath {\n\tconst parts = vectorStrokeParts(path, style);\n\tconst stroke = vectorStrokeLineArea(parts, style);\n\tconst fill: PathOperandInput = { path, fillRule: style.fillRule ?? 'nonzero' };\n\tlet area = stroke;\n\tif (parts.align === 'inside') area = pathBoolean('intersection', [stroke, fill]).path;\n\telse if (parts.align === 'outside') area = pathBoolean('difference', [stroke, fill]).path;\n\tif (!parts.heads.length) return area;\n\treturn pathBoolean('union', [area, ...parts.heads.map((h) => h.path)]).path;\n}\n\n/**\n * Whether point `p` hits the stroke of `path` (`tolerance` added on every side): within half\n * the width of the outline for a centred stroke, within the whole width on the inside or the\n * outside of the fill for an aligned one, or on an arrowhead.\n */\nexport function hitTestVectorStroke(path: BezierPath, p: Vec2, style: VectorStyle, tolerance = 0): boolean {\n\tconst parts = vectorStrokeParts(path, style);\n\tconst point: Point = [p.x, p.y];\n\tconst width = style.strokeWidth ?? 1;\n\tfor (const h of parts.heads) {\n\t\tif (pointInBezierPath(h.path, point) || (tolerance > 0 && distanceToBezierPath(h.path, point) <= tolerance)) return true;\n\t}\n\tif (!parts.line.length) return false;\n\tconst profile = strokeWidthProfileOf(style);\n\tlet d: number;\n\tlet reach = width / 2;\n\tif (profile) {\n\t\t// The side width at the nearest point of the centre line (twice it when aligned).\n\t\tconst near = nearestStrokePosition(parts.line, point);\n\t\tif (!near) return false;\n\t\td = near.distance;\n\t\tconst w = widthProfileAt(profile, near.t);\n\t\treach = (width / 2) * (near.side === 'left' ? w.left : w.right);\n\t\tif (parts.align !== 'center') reach *= 2;\n\t\tconst atEnd = near.t <= 1e-9 || near.t >= 1 - 1e-9;\n\t\tif (atEnd && (style.strokeLinecap === 'round' || style.strokeLinecap === 'square') && d > reach) {\n\t\t\t// Past an open end the cap reaches as far as the width there.\n\t\t\treach = Math.max(reach, ((width / 2) * (w.left + w.right)) / 2);\n\t\t}\n\t} else {\n\t\td = distanceToBezierPath(parts.line, point);\n\t\tif (parts.align !== 'center') reach = width;\n\t}\n\tif (parts.align === 'center') return d <= reach + tolerance;\n\tif (d > reach + tolerance) return false;\n\tif (d <= tolerance) return true;\n\tconst inside = pointInBezierPath(path, point, style.fillRule ?? 'nonzero');\n\treturn parts.align === 'inside' ? inside : !inside;\n}\n\n/** How far the stroke can reach past the outline (for padding bounds and masks). */\nexport function vectorStrokeReach(style: VectorStyle): number {\n\tconst width = (style.strokeWidth ?? 1) * widthProfileMaxScale(strokeWidthProfileOf(style));\n\tconst align = style.strokeAlign ?? 'center';\n\tlet reach = align === 'center' ? width / 2 : align === 'outside' ? width : 0;\n\tif (style.strokeLinejoin !== 'round' && style.strokeLinejoin !== 'bevel') reach *= 4;\n\tfor (const end of ['start', 'end'] as const) {\n\t\tif (end === 'start' ? style.startArrow : style.endArrow) reach = Math.max(reach, 8 * arrowheadWeight(style, end) + width);\n\t}\n\treturn reach;\n}\n","/**\n * Fill and stroke stacks: several paints per path, each with its own opacity, blend mode and\n * visibility, and each stroke with its own width, alignment, dashes, arrowheads and profile.\n *\n * The stacks live in `fills` / `strokes`, bottom to top; fills draw under strokes. The single\n * `fill` / `stroke` fields (and the stroke settings) stay as shorthands that mirror the top layer\n * of each stack, so everything written against one fill and one stroke — booleans, blends, the\n * gradient tool, agent commands, old documents — keeps working:\n *\n * - A node without `fills` has the one-layer stack its `fill` says (none without a paint); the\n * same for strokes. Stacks of one plain layer are stored that way, so old documents and simple\n * nodes look exactly as before.\n * - `normalizeVectorPaintStacks` reconciles the two forms. Loading prefers the stacks (the\n * shorthand is re-derived); editing prefers the shorthand: a node whose `fill` no longer matches\n * its top fill was written by shorthand code, so the top layer takes the new paint (`null`\n * clears the stack). The controller runs it after every change.\n *\n * Paint layers are drawn, hit-tested and exported through `vectorPaintLayerNodes`: one plain path\n * node per layer (the node with only that fill, or only that stroke and its settings), so the\n * existing paint, stroke-part and gradient code serves each layer unchanged.\n *\n * The data model follows figcraft `crates/color/src/lib.rs` (`Paint { kind, opacity, visible,\n * blend }` in a list per node) and vectorcraft `crates/doc/src/appearance.rs` (`FillLayer` /\n * `StrokeLayer`, each stroke with its own settings). Ported from ArtCraft (MIT OR Apache-2.0,\n * © ArtCraft Team and contributors; see THIRD_PARTY_NOTICES.md).\n */\nimport { sanitizeVectorShadedPaint } from './shading.js';\nimport { pointInBezierPath, distanceToBezierPath, type BezierPath } from '../canvas/pathops/bezier.js';\nimport { isVectorGradient, sanitizeVectorGradient } from './gradient.js';\nimport { hitTestVectorStroke, vectorStrokeReach } from './stroke.js';\nimport { sanitizeWidthProfile } from './width.js';\nimport {\n\tVECTOR_ARROWHEADS,\n\tVECTOR_BLEND_MODES,\n\ttype VectorArrowhead,\n\ttype VectorBlendMode,\n\ttype VectorPaint,\n\ttype VectorPaintLayer,\n\ttype VectorPathNode,\n\ttype VectorStrokeLayer,\n\ttype VectorStrokeSettings,\n\ttype VectorStyle,\n\ttype Vec2\n} from './types.js';\n\n/** The stroke settings each stroke layer has of its own, in `VectorStyle` field names. */\nexport const VECTOR_STROKE_SETTING_KEYS: readonly (keyof VectorStrokeSettings)[] = [\n\t'strokeWidth',\n\t'strokeLinecap',\n\t'strokeLinejoin',\n\t'strokeDasharray',\n\t'strokeAlign',\n\t'startArrow',\n\t'endArrow',\n\t'arrowAlign',\n\t'startArrowScale',\n\t'endArrowScale',\n\t'strokeWidthProfile'\n];\n\nexport const VECTOR_BLEND_MODE_LABELS: Readonly<Record<VectorBlendMode, string>> = {\n\tnormal: 'Normal',\n\tdarken: 'Darken',\n\tmultiply: 'Multiply',\n\t'color-burn': 'Color Burn',\n\tlighten: 'Lighten',\n\tscreen: 'Screen',\n\t'color-dodge': 'Color Dodge',\n\t'linear-dodge': 'Linear Dodge (Add)',\n\toverlay: 'Overlay',\n\t'soft-light': 'Soft Light',\n\t'hard-light': 'Hard Light',\n\tdifference: 'Difference',\n\texclusion: 'Exclusion',\n\thue: 'Hue',\n\tsaturation: 'Saturation',\n\tcolor: 'Color',\n\tluminosity: 'Luminosity'\n};\n\nexport function isVectorBlendMode(value: unknown): value is VectorBlendMode {\n\treturn typeof value === 'string' && (VECTOR_BLEND_MODES as readonly string[]).includes(value);\n}\n\n/** A blend mode as a CSS `mix-blend-mode` value, or undefined for `normal` (nothing to write). */\nexport function vectorBlendModeCss(mode: VectorBlendMode | null | undefined): string | undefined {\n\tif (!mode || mode === 'normal' || !isVectorBlendMode(mode)) return undefined;\n\treturn mode === 'linear-dodge' ? 'plus-lighter' : mode;\n}\n\n/** A CSS `mix-blend-mode` value back to a blend mode (`plus-lighter` is `linear-dodge`), or null when SVG offers it but we don't. */\nexport function vectorBlendModeFromCss(value: string | null | undefined): VectorBlendMode | null {\n\tconst v = (value ?? '').trim().toLowerCase();\n\tif (v === 'plus-lighter') return 'linear-dodge';\n\treturn isVectorBlendMode(v) ? v : null;\n}\n\n/** True when the paint draws something (not `null`, `'none'`, `'transparent'` or empty). */\nconst draws = (paint: VectorPaint | undefined): boolean => {\n\tif (paint === undefined || paint === null) return false;\n\tif (typeof paint === 'string') {\n\t\tconst p = paint.trim().toLowerCase();\n\t\treturn p !== '' && p !== 'none' && p !== 'transparent';\n\t}\n\treturn true;\n};\n\n/** A layer with full opacity, `normal` blending, visible and (strokes) a plain paint: what the shorthand alone can say. */\nexport function isPlainVectorPaintLayer(layer: VectorPaintLayer | VectorStrokeLayer): boolean {\n\treturn (\n\t\t(layer.opacity ?? 1) >= 1 &&\n\t\t(layer.blendMode ?? 'normal') === 'normal' &&\n\t\tlayer.visible !== false &&\n\t\t((layer as VectorStrokeLayer).kind ?? 'paint') === 'paint'\n\t);\n}\n\n/** Whether a layer is drawn: visible, a plain paint (strokes), a paint that draws something, above zero opacity. */\nexport function isDrawnVectorPaintLayer(layer: VectorPaintLayer | VectorStrokeLayer): boolean {\n\treturn layer.visible !== false && ((layer as VectorStrokeLayer).kind ?? 'paint') === 'paint' && draws(layer.paint) && (layer.opacity ?? 1) > 0;\n}\n\n/** The fill stack of a path (or style), bottom to top: `fills`, or the one layer `fill` makes. */\nexport function vectorFills(style: VectorStyle): VectorPaintLayer[] {\n\tif (Array.isArray(style.fills)) return style.fills;\n\treturn draws(style.fill) ? [{ paint: style.fill! }] : [];\n}\n\n/** The stroke settings a style gives its shorthand stroke (only those set). */\nexport function vectorStrokeSettings(style: VectorStyle): VectorStrokeSettings {\n\tconst out: VectorStrokeSettings = {};\n\tfor (const key of VECTOR_STROKE_SETTING_KEYS) {\n\t\tconst v = style[key];\n\t\tif (v !== undefined && v !== null) (out as Record<string, unknown>)[key] = v;\n\t}\n\treturn out;\n}\n\n/** The stroke stack of a path (or style), bottom to top: `strokes`, or the one layer `stroke` and the stroke settings make. */\nexport function vectorStrokes(style: VectorStyle): VectorStrokeLayer[] {\n\tif (Array.isArray(style.strokes)) return style.strokes;\n\treturn draws(style.stroke) ? [{ paint: style.stroke!, ...vectorStrokeSettings(style) }] : [];\n}\n\n/** Whether a style stores a stack (more than its shorthand can say). */\nexport function hasVectorPaintStacks(style: VectorStyle): boolean {\n\treturn Array.isArray(style.fills) || Array.isArray(style.strokes);\n}\n\n/** The node with `fills` as its fill stack, stored canonically (see the module comment). */\nexport function withVectorFills<T extends VectorStyle>(node: T, fills: readonly VectorPaintLayer[]): T {\n\tconst next = { ...node };\n\tif (fills.length === 0 || (fills.length === 1 && isPlainVectorPaintLayer(fills[0]))) {\n\t\tdelete next.fills;\n\t\tnext.fill = fills[0]?.paint ?? null;\n\t\treturn next;\n\t}\n\tnext.fills = fills.map((l) => ({ ...l }));\n\tnext.fill = fills[fills.length - 1].paint;\n\treturn next;\n}\n\n/** The node with `strokes` as its stroke stack, stored canonically; the shorthand mirrors the top layer. */\nexport function withVectorStrokes<T extends VectorStyle>(node: T, strokes: readonly VectorStrokeLayer[]): T {\n\tconst next = { ...node };\n\tif (strokes.length === 0) {\n\t\t// The settings stay, for a stroke added later through the shorthand.\n\t\tdelete next.strokes;\n\t\tnext.stroke = null;\n\t\treturn next;\n\t}\n\tconst top = strokes[strokes.length - 1];\n\tfor (const key of VECTOR_STROKE_SETTING_KEYS) delete next[key];\n\tObject.assign(next, vectorStrokeSettings(top as VectorStyle));\n\tnext.stroke = top.paint;\n\tif (strokes.length === 1 && isPlainVectorPaintLayer(top)) delete next.strokes;\n\telse next.strokes = strokes.map((l) => ({ ...l }));\n\treturn next;\n}\n\nconst json = (v: unknown) => JSON.stringify(v ?? null);\n\n/** The stroke fields of `node` that differ from what its top stroke layer says. */\nfunction strokeShorthandDiff(node: VectorStyle, top: VectorStrokeLayer | undefined): (keyof VectorStrokeSettings | 'stroke')[] {\n\tconst out: (keyof VectorStrokeSettings | 'stroke')[] = [];\n\tif (json(node.stroke) !== json(top?.paint)) out.push('stroke');\n\tfor (const key of VECTOR_STROKE_SETTING_KEYS) if (json(node[key]) !== json(top?.[key])) out.push(key);\n\treturn out;\n}\n\nconst checked = new WeakSet<object>();\n\n/**\n * A node with its stacks and shorthands reconciled and stored canonically (the same object when\n * they already are). `prefer: 'stack'` (loading) re-derives the shorthand from the stacks;\n * `'shorthand'` (after an edit, the default) reads a shorthand that disagrees with its stack's\n * top layer as an edit of that layer: a paint repaints it, a stroke setting changes it, `null`\n * clears the stack.\n */\nexport function normalizeVectorPaintStacks<T extends VectorStyle>(node: T, prefer: 'stack' | 'shorthand' = 'shorthand'): T {\n\tif (!hasVectorPaintStacks(node)) {\n\t\tif (!('fills' in node) && !('strokes' in node)) return node;\n\t\t// `fills: null` / `strokes: null`: no stack.\n\t\tconst next = { ...node };\n\t\tdelete next.fills;\n\t\tdelete next.strokes;\n\t\treturn next;\n\t}\n\tif (checked.has(node)) return node;\n\tlet next: T = node;\n\tif (Array.isArray(node.fills)) {\n\t\tlet fills: VectorPaintLayer[] = node.fills;\n\t\tconst top = fills[fills.length - 1];\n\t\tif (prefer === 'shorthand' && json(node.fill) !== json(top?.paint)) {\n\t\t\tif (!draws(node.fill)) fills = [];\n\t\t\telse fills = top ? [...fills.slice(0, -1), { ...top, paint: node.fill! }] : [{ paint: node.fill! }];\n\t\t}\n\t\tnext = withVectorFills(next, fills);\n\t}\n\tif (Array.isArray(node.strokes)) {\n\t\tlet strokes: VectorStrokeLayer[] = node.strokes;\n\t\tconst top = strokes[strokes.length - 1];\n\t\tconst diff = prefer === 'shorthand' ? strokeShorthandDiff(node, top) : [];\n\t\tif (diff.length) {\n\t\t\tif (diff.includes('stroke') && !draws(node.stroke)) strokes = [];\n\t\t\telse {\n\t\t\t\tconst layer: VectorStrokeLayer = top ? { ...top } : { paint: node.stroke ?? null };\n\t\t\t\tfor (const key of diff) {\n\t\t\t\t\tif (key === 'stroke') layer.paint = node.stroke ?? null;\n\t\t\t\t\telse if (node[key] === undefined || node[key] === null) delete layer[key];\n\t\t\t\t\telse (layer as unknown as Record<string, unknown>)[key] = node[key];\n\t\t\t\t}\n\t\t\t\tstrokes = top ? [...strokes.slice(0, -1), layer] : [layer];\n\t\t\t}\n\t\t}\n\t\tnext = withVectorStrokes(next, strokes);\n\t}\n\tconst keys = ['fill', 'fills', 'stroke', 'strokes', ...VECTOR_STROKE_SETTING_KEYS] as const;\n\tconst same = keys.every((k) => k in next === k in node && json(next[k]) === json(node[k]));\n\tconst out = same ? node : next;\n\tchecked.add(out);\n\treturn out;\n}\n\n// ---------------------------------------------------------------------------\n// Sanitizing\n// ---------------------------------------------------------------------------\n\nfunction sanitizePaint(value: unknown): VectorPaint {\n\tif (value === null || value === undefined) return null;\n\tif (typeof value === 'string') return value;\n\treturn sanitizeVectorShadedPaint(value) ?? sanitizeVectorGradient(value);\n}\n\nfunction sanitizeLayerBase(raw: Record<string, unknown>): VectorPaintLayer {\n\tconst out: VectorPaintLayer = { paint: sanitizePaint(raw.paint) };\n\tif (typeof raw.opacity === 'number' && Number.isFinite(raw.opacity) && raw.opacity < 1) out.opacity = Math.max(0, raw.opacity);\n\tif (isVectorBlendMode(raw.blendMode) && raw.blendMode !== 'normal') out.blendMode = raw.blendMode;\n\tif (raw.visible === false) out.visible = false;\n\treturn out;\n}\n\n/** Reads a fill stack from untrusted data (JSON, agent input, SVG): malformed layers are dropped. */\nexport function sanitizeVectorFills(value: unknown): VectorPaintLayer[] {\n\tif (!Array.isArray(value)) return [];\n\treturn value.filter((l): l is Record<string, unknown> => !!l && typeof l === 'object').map(sanitizeLayerBase);\n}\n\nconst ARROW_ALIGNS = ['extend', 'tip'];\n\n/** Stroke settings from untrusted data: wrong types and out-of-range values are dropped. */\nexport function sanitizeVectorStrokeSettings(raw: Record<string, unknown>): VectorStrokeSettings {\n\tconst out: VectorStrokeSettings = {};\n\tconst num = (v: unknown) => (typeof v === 'number' && Number.isFinite(v) ? v : undefined);\n\tconst width = num(raw.strokeWidth);\n\tif (width !== undefined && width >= 0) out.strokeWidth = width;\n\tif (raw.strokeLinecap === 'butt' || raw.strokeLinecap === 'round' || raw.strokeLinecap === 'square') out.strokeLinecap = raw.strokeLinecap;\n\tif (raw.strokeLinejoin === 'miter' || raw.strokeLinejoin === 'round' || raw.strokeLinejoin === 'bevel') out.strokeLinejoin = raw.strokeLinejoin;\n\tif (Array.isArray(raw.strokeDasharray)) {\n\t\tconst dash = raw.strokeDasharray.filter((n): n is number => typeof n === 'number' && Number.isFinite(n) && n >= 0);\n\t\tif (dash.length && dash.some((n) => n > 0)) out.strokeDasharray = dash;\n\t}\n\tif (raw.strokeAlign === 'center' || raw.strokeAlign === 'inside' || raw.strokeAlign === 'outside') out.strokeAlign = raw.strokeAlign;\n\tfor (const key of ['startArrow', 'endArrow'] as const) if (VECTOR_ARROWHEADS.includes(raw[key] as VectorArrowhead)) out[key] = raw[key] as VectorArrowhead;\n\tif (ARROW_ALIGNS.includes(raw.arrowAlign as string)) out.arrowAlign = raw.arrowAlign as 'extend' | 'tip';\n\tfor (const key of ['startArrowScale', 'endArrowScale'] as const) {\n\t\tconst n = num(raw[key]);\n\t\tif (n !== undefined && n > 0) out[key] = n;\n\t}\n\tif (Array.isArray(raw.strokeWidthProfile)) {\n\t\tconst p = sanitizeWidthProfile(raw.strokeWidthProfile as never);\n\t\tif (p.length) out.strokeWidthProfile = p;\n\t}\n\treturn out;\n}\n\n/**\n * Reads a stroke stack from untrusted data. Layers of a kind this version does not know are kept\n * as they are (a later version's brushstroke, say), so a round trip does not lose them.\n */\nexport function sanitizeVectorStrokes(value: unknown): VectorStrokeLayer[] {\n\tif (!Array.isArray(value)) return [];\n\treturn value\n\t\t.filter((l): l is Record<string, unknown> => !!l && typeof l === 'object')\n\t\t.map((raw) => {\n\t\t\tif (raw.kind !== undefined && raw.kind !== 'paint') return { ...(raw as unknown as VectorStrokeLayer) };\n\t\t\treturn { ...sanitizeLayerBase(raw), ...sanitizeVectorStrokeSettings(raw) };\n\t\t});\n}\n\n// ---------------------------------------------------------------------------\n// Layer nodes: one plain path per layer\n// ---------------------------------------------------------------------------\n\n/** One layer of a path's paint as a plain path node (see `vectorPaintLayerNodes`). */\nexport interface VectorPaintLayerNode {\n\tkind: 'fill' | 'stroke';\n\t/** Index in its stack, bottom to top. */\n\tindex: number;\n\tlayer: VectorPaintLayer | VectorStrokeLayer;\n\t/** The path with only this fill, or only this stroke and its settings (no stacks). */\n\tnode: VectorPathNode;\n\t/** Visible, a plain paint, painting something, above zero opacity. */\n\tdrawn: boolean;\n}\n\nconst layerNodeCache = new WeakMap<VectorPathNode, VectorPaintLayerNode[]>();\n\n/**\n * Every fill then every stroke of a path, bottom to top, each as the path painted by that layer\n * alone. Cached per node object (and the layer nodes are the same objects while it is), so the\n * paint and stroke-part caches keyed by node keep working per layer.\n */\nexport function vectorPaintLayerNodes(node: VectorPathNode): VectorPaintLayerNode[] {\n\tconst hit = layerNodeCache.get(node);\n\tif (hit) return hit;\n\tconst { fills: _f, strokes: _s, ...base } = node;\n\tconst plain = { ...base } as VectorPathNode;\n\tfor (const key of VECTOR_STROKE_SETTING_KEYS) delete plain[key];\n\tconst out: VectorPaintLayerNode[] = [];\n\tvectorFills(node).forEach((layer, index) => {\n\t\tout.push({ kind: 'fill', index, layer, node: { ...plain, fill: layer.paint, stroke: null }, drawn: isDrawnVectorPaintLayer(layer) });\n\t});\n\tvectorStrokes(node).forEach((layer, index) => {\n\t\tconst settings = (layer.kind ?? 'paint') === 'paint' ? vectorStrokeSettings(layer as VectorStyle) : {};\n\t\tout.push({ kind: 'stroke', index, layer, node: { ...plain, fill: null, ...settings, stroke: layer.paint }, drawn: isDrawnVectorPaintLayer(layer) });\n\t});\n\tlayerNodeCache.set(node, out);\n\treturn out;\n}\n\n/** Whether a path draws through its stacks rather than one fill and one stroke (several layers, or one with its own opacity, blend or visibility). */\nexport function needsVectorPaintLayers(node: VectorPathNode): boolean {\n\tif (!hasVectorPaintStacks(node)) return false;\n\tconst fills = vectorFills(node);\n\tconst strokes = vectorStrokes(node);\n\treturn fills.length > 1 || strokes.length > 1 || fills.some((l) => !isPlainVectorPaintLayer(l)) || strokes.some((l) => !isPlainVectorPaintLayer(l));\n}\n\n/** How far the drawn strokes of a path reach past its outline (the widest layer's reach; 0 without strokes). */\nexport function vectorStrokeStackReach(node: VectorPathNode): number {\n\tlet reach = 0;\n\tfor (const l of vectorPaintLayerNodes(node)) if (l.kind === 'stroke' && l.drawn) reach = Math.max(reach, vectorStrokeReach(l.node));\n\treturn reach;\n}\n\n/** The layer a point hits (see `hitTestVectorPaintLayer`). */\nexport interface VectorPaintLayerHit {\n\tkind: 'fill' | 'stroke';\n\tindex: number;\n}\n\n/**\n * The topmost drawn layer of a path that `p` hits, or null: strokes top to bottom (their\n * alignment, arrowheads and profiles respected, `tolerance` added), then fills. `path` is the\n * node's outline in the same space as `p` (`vectorPathWorldBezier`).\n */\nexport function hitTestVectorPaintLayer(node: VectorPathNode, path: BezierPath, p: Vec2, tolerance = 0): VectorPaintLayerHit | null {\n\tif (!path.length) return null;\n\tconst layers = vectorPaintLayerNodes(node);\n\tfor (let i = layers.length - 1; i >= 0; i--) {\n\t\tconst l = layers[i];\n\t\tif (!l.drawn) continue;\n\t\tif (l.kind === 'stroke') {\n\t\t\tif ((l.node.strokeWidth ?? 1) > 0 && hitTestVectorStroke(path, p, l.node, tolerance)) return { kind: 'stroke', index: l.index };\n\t\t} else if (pointInBezierPath(path, [p.x, p.y], node.fillRule ?? 'nonzero')) return { kind: 'fill', index: l.index };\n\t}\n\treturn null;\n}\n\n/**\n * Whether `p` hits a path as drawn by its stacks: on a drawn layer, or, when it draws no stroke,\n * within `tolerance` of its outline (so unpainted paths stay pickable).\n */\nexport function hitTestVectorPaintStack(node: VectorPathNode, path: BezierPath, p: Vec2, tolerance = 0): boolean {\n\tif (hitTestVectorPaintLayer(node, path, p, tolerance)) return true;\n\tif (vectorPaintLayerNodes(node).some((l) => l.kind === 'stroke' && l.drawn)) return false;\n\treturn distanceToBezierPath(path, [p.x, p.y]) <= tolerance;\n}\n\n/** Whether a fill or stroke stack holds a gradient anywhere (for transforms that move gradients). */\nexport function vectorStacksHaveGradient(style: VectorStyle): boolean {\n\treturn [...(style.fills ?? []), ...(style.strokes ?? [])].some((l) => isVectorGradient(l.paint));\n}\n\n/** Defaults of a new layer added to a stack (a stroke takes the settings of the stack's top stroke). */\nexport function newVectorStrokeLayer(node: VectorStyle, patch: Partial<VectorStrokeLayer> = {}): VectorStrokeLayer {\n\tconst top = vectorStrokes(node).at(-1);\n\tconst settings = top && (top.kind ?? 'paint') === 'paint' ? vectorStrokeSettings(top as VectorStyle) : { strokeWidth: node.strokeWidth ?? 1 };\n\treturn { paint: '#000000', ...settings, ...patch };\n}\n\n/**\n * The paint the gradient tool and editor work on: layer `layer` of the fill or stroke stack, or\n * (null, or an index the stack doesn't have) the shorthand, which is the top layer.\n */\nexport function vectorTargetPaint(style: VectorStyle, target: 'fill' | 'stroke', layer: number | null = null): VectorPaint | undefined {\n\tif (layer === null) return style[target];\n\tconst stack = target === 'fill' ? vectorFills(style) : vectorStrokes(style);\n\treturn stack[layer] ? stack[layer].paint : style[target];\n}\n\n/** The node with `paint` in the place `vectorTargetPaint` reads (stored canonically). */\nexport function withVectorTargetPaint<T extends VectorStyle>(node: T, target: 'fill' | 'stroke', layer: number | null, paint: VectorPaint): T {\n\tconst stack = target === 'fill' ? vectorFills(node) : vectorStrokes(node);\n\tif (layer === null || !stack[layer]) {\n\t\tif (!stack.length) return { ...node, [target]: paint };\n\t\tlayer = stack.length - 1;\n\t}\n\tconst next = stack.map((l, i) => (i === layer ? { ...l, paint } : l));\n\treturn target === 'fill' ? withVectorFills(node, next) : withVectorStrokes(node, next as VectorStrokeLayer[]);\n}\n","/**\n * Path operators of live path effects (After Effects' \"Add ▸\" path operations). Each maps a list\n * of paths to a list of the same length (one per shape above the operator), except `mergePaths`,\n * which combines them into one, and `repeatPaths`, which makes copies. Paths are in the space of\n * the node the effect belongs to.\n *\n * Ported from ArtCraft (MIT OR Apache-2.0, © ArtCraft Team and contributors; see\n * THIRD_PARTY_NOTICES.md): effectcraft `crates/path/src/ops.rs` — `trim`, `trim_individually`,\n * `trim_intervals`, `Measured::append`, `pucker_bloat`, `round_corners`, `offset`, `twist`,\n * `resample`, `emit`, `zigzag`, `WiggleParams`, `splitmix`, `hash`, `noise`, `wiggle`, `MergeMode`\n * and `merge`; and the `\"repeater\"` branch of `collect()` in `crates/render/src/shapes.rs` (copy\n * transforms, opacity ramp, fractional last copy, offset and composite order). Arc lengths come\n * from our own `segmentLength` / `segmentParamAtLength` / `trimSegments`, offsets from\n * `offsetPath`, booleans from `pathBoolean`, and Round Corners uses the live-corner maths in\n * `corners.ts` (a true radius, exact at any angle, where a curve meets a corner too).\n */\nimport type { Point } from '../canvas/types.js';\nimport {\n\tbezierPathBounds,\n\tcloseContour,\n\tcontoursToPath,\n\tflattenChain,\n\tpathToContours,\n\tsegmentDerivative,\n\tsegmentLength,\n\tsegmentParamAtLength,\n\tsegmentPoint,\n\tsubSegment,\n\ttransformBezierPath,\n\ttrimSegments,\n\ttype AffineMatrix,\n\ttype BezierPath,\n\ttype BezierSegment\n} from '../canvas/pathops/bezier.js';\nimport { pathBoolean } from '../canvas/pathops/boolean.js';\nimport { offsetPath } from '../canvas/pathops/stroke.js';\nimport { setSubpathCorners } from './corners.js';\nimport { bezierToSubpaths, multiplyMatrices, rotateMatrix, scaleMatrix, subpathsToBezier, translateMatrix } from './geometry.js';\nimport type { Vec2, VectorEffectParamsMap, VectorLineJoin, VectorMergeMode } from './types.js';\n\nconst EPS = 1e-9;\n\n// ---------------------------------------------------------------------------\n// Subpath helpers\n// ---------------------------------------------------------------------------\n\n/** One subpath as cubic or line segments (quadratics raised), the closing line included. */\ninterface Sub {\n\tsegs: Point[][];\n\tclosed: boolean;\n}\n\nconst degenerate = (s: BezierSegment) => s.every((p) => Math.abs(p[0] - s[0][0]) < EPS && Math.abs(p[1] - s[0][1]) < EPS);\n\nfunction raise(seg: BezierSegment): Point[] {\n\tif (seg.length !== 3) return seg.map((p) => [p[0], p[1]] as Point);\n\tconst [p0, p1, p2] = seg;\n\treturn [p0, [p0[0] + (2 / 3) * (p1[0] - p0[0]), p0[1] + (2 / 3) * (p1[1] - p0[1])], [p2[0] + (2 / 3) * (p1[0] - p2[0]), p2[1] + (2 / 3) * (p1[1] - p2[1])], p2];\n}\n\n/** The path's subpaths with at least one segment (a closed one's closing line included). */\nfunction subsOf(path: BezierPath): Sub[] {\n\treturn pathToContours(path)\n\t\t.map((c) => ({ segs: closeContour(c).filter((s) => !degenerate(s)).map(raise), closed: c.closed }))\n\t\t.filter((s) => s.segs.length > 0);\n}\n\nconst subsToPath = (subs: readonly Sub[]): BezierPath => contoursToPath(subs.map((s) => ({ segments: s.segs, closed: s.closed })));\n\nconst unit = (x: number, y: number): Point | null => {\n\tconst l = Math.hypot(x, y);\n\treturn l > 1e-12 && Number.isFinite(l) ? [x / l, y / l] : null;\n};\n\n/** Direction a segment leaves its start in (robust at a handle on its anchor). */\nfunction startTangent(s: BezierSegment): Point {\n\tfor (let i = 1; i < s.length; i++) {\n\t\tconst u = unit(s[i][0] - s[0][0], s[i][1] - s[0][1]);\n\t\tif (u) return u;\n\t}\n\treturn [1, 0];\n}\n\n/** Direction a segment arrives at its end in. */\nfunction endTangent(s: BezierSegment): Point {\n\tconst end = s[s.length - 1];\n\tfor (let i = s.length - 2; i >= 0; i--) {\n\t\tconst u = unit(end[0] - s[i][0], end[1] - s[i][1]);\n\t\tif (u) return u;\n\t}\n\treturn [1, 0];\n}\n\nfunction tangentAt(s: BezierSegment, t: number): Point {\n\tif (t <= 1e-9) return startTangent(s);\n\tif (t >= 1 - 1e-9) return endTangent(s);\n\tconst d = segmentDerivative(s, t);\n\treturn unit(d[0], d[1]) ?? startTangent(s);\n}\n\nconst perp = (v: Point): Point => [-v[1], v[0]];\n\n/** Total arc length of a path (closing lines included). */\nexport function effectPathLength(path: BezierPath): number {\n\tlet total = 0;\n\tfor (const s of subsOf(path)) for (const seg of s.segs) total += segmentLength(seg);\n\treturn total;\n}\n\n/** Number of on-curve points of a path (a closed subpath's start counted once). */\nexport function effectPathVertexCount(path: BezierPath): number {\n\treturn subsOf(path).reduce((n, s) => n + s.segs.length + (s.closed ? 0 : 1), 0);\n}\n\n// ---------------------------------------------------------------------------\n// Trim Paths\n// ---------------------------------------------------------------------------\n\n/** A path measured for trimming: its segments end to end and their lengths. */\nclass Measured {\n\treadonly segs: Point[][];\n\treadonly lens: number[];\n\treadonly total: number;\n\tconstructor(path: BezierPath) {\n\t\tthis.segs = subsOf(path).flatMap((s) => s.segs);\n\t\tthis.lens = this.segs.map((s) => segmentLength(s));\n\t\tthis.total = this.lens.reduce((a, b) => a + b, 0);\n\t}\n\n\t/**\n\t * Appends the part between lengths `sa` and `sb`, continuing the last piece when this one\n\t * starts where it ends (across the start of a closed path).\n\t */\n\tappend(sa: number, sb: number, out: Sub[]) {\n\t\tfor (const piece of trimSegments(this.segs, sa, sb, this.lens)) {\n\t\t\tif (degenerate(piece)) continue;\n\t\t\tconst last = out[out.length - 1]?.segs;\n\t\t\tconst end = last?.[last.length - 1]?.at(-1);\n\t\t\tif (!end || Math.hypot(end[0] - piece[0][0], end[1] - piece[0][1]) > 1e-6) out.push({ segs: [piece], closed: false });\n\t\t\telse last!.push(piece);\n\t\t}\n\t}\n}\n\n/** The fractions of the length a trim keeps, or null when it keeps everything. */\nexport function trimIntervals(start: number, end: number, offsetDegrees: number): [number, number][] | null {\n\tlet s = start / 100;\n\tlet e = end / 100;\n\tif (!Number.isFinite(s) || !Number.isFinite(e)) return null;\n\tif (s > e) [s, e] = [e, s];\n\ts = Math.min(1, Math.max(0, s));\n\te = Math.min(1, Math.max(0, e));\n\tif (e - s >= 1 - 1e-9) return null;\n\tif (e - s <= 1e-9) return [];\n\tconst off = Number.isFinite(offsetDegrees) ? (((offsetDegrees / 360) % 1) + 1) % 1 : 0;\n\ts += off;\n\te += off;\n\tif (e <= 1) return [[s, e]];\n\tif (s >= 1) return [[s - 1, e - 1]];\n\treturn [\n\t\t[s, 1],\n\t\t[0, e - 1]\n\t];\n}\n\n/**\n * Trim Paths, simultaneously: every path is trimmed by the same fractions of its own length.\n * `start` / `end` in percent, `offset` in degrees. Paths trimmed away entirely come back empty.\n */\nexport function trimPaths(paths: readonly BezierPath[], start: number, end: number, offsetDegrees = 0): BezierPath[] {\n\tconst iv = trimIntervals(start, end, offsetDegrees);\n\tif (!iv) return paths.slice();\n\treturn paths.map((p) => {\n\t\tconst m = new Measured(p);\n\t\tconst out: Sub[] = [];\n\t\tif (m.total > 0) for (const [a, b] of iv) m.append(a * m.total, b * m.total, out);\n\t\treturn subsToPath(out);\n\t});\n}\n\n/**\n * Trim Paths, individually: the paths are laid end to end in stacking order and trimmed as one\n * length, so they draw on one after another.\n */\nexport function trimPathsIndividually(paths: readonly BezierPath[], start: number, end: number, offsetDegrees = 0): BezierPath[] {\n\tconst iv = trimIntervals(start, end, offsetDegrees);\n\tif (!iv) return paths.slice();\n\tconst ms = paths.map((p) => new Measured(p));\n\tconst total = ms.reduce((n, m) => n + m.total, 0);\n\tlet base = 0;\n\treturn ms.map((m) => {\n\t\tconst out: Sub[] = [];\n\t\tfor (const [a, b] of iv) {\n\t\t\tconst la = Math.max(0, a * total - base);\n\t\t\tconst lb = Math.min(m.total, b * total - base);\n\t\t\tif (lb > la) m.append(la, lb, out);\n\t\t}\n\t\tbase += m.total;\n\t\treturn subsToPath(out);\n\t});\n}\n\n// ---------------------------------------------------------------------------\n// Pucker & Bloat\n// ---------------------------------------------------------------------------\n\n/**\n * Pucker & Bloat (`amount` in percent, −100 to 100). Positive (bloat) moves the points towards\n * the mean of a path's points and pushes the handles away from it, so the segments bulge\n * outwards; negative (pucker) does the opposite, giving spiky shapes.\n */\nexport function puckerBloatPaths(paths: readonly BezierPath[], amount: number): BezierPath[] {\n\tconst a = amount / 100;\n\tif (!a || !Number.isFinite(a)) return paths.slice();\n\treturn paths.map((p) => {\n\t\tconst verts = p.filter((c) => c.type !== 'Z') as Exclude<BezierPath[number], { type: 'Z' }>[];\n\t\tif (!verts.length) return p;\n\t\tconst cx = verts.reduce((s, c) => s + c.x, 0) / verts.length;\n\t\tconst cy = verts.reduce((s, c) => s + c.y, 0) / verts.length;\n\t\tconst mv = (x: number, y: number) => ({ x: x + (cx - x) * a, y: y + (cy - y) * a });\n\t\tconst mvh = (x: number, y: number) => ({ x: x + (x - cx) * a, y: y + (y - cy) * a });\n\t\tconst out: BezierPath = [];\n\t\tlet prev = { x: 0, y: 0 };\n\t\tlet start = { x: 0, y: 0 };\n\t\tconst curve = (c1: Vec2, c2: Vec2, q: Vec2) => {\n\t\t\tconst h1 = mvh(c1.x, c1.y);\n\t\t\tconst h2 = mvh(c2.x, c2.y);\n\t\t\tconst e = mv(q.x, q.y);\n\t\t\tout.push({ type: 'C', x1: h1.x, y1: h1.y, x2: h2.x, y2: h2.y, x: e.x, y: e.y });\n\t\t};\n\t\tfor (const c of p) {\n\t\t\tswitch (c.type) {\n\t\t\t\tcase 'M': {\n\t\t\t\t\tconst e = mv(c.x, c.y);\n\t\t\t\t\tout.push({ type: 'M', x: e.x, y: e.y });\n\t\t\t\t\tprev = start = { x: c.x, y: c.y };\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tcase 'L':\n\t\t\t\t\tcurve(prev, c, c);\n\t\t\t\t\tprev = { x: c.x, y: c.y };\n\t\t\t\t\tbreak;\n\t\t\t\tcase 'Q': {\n\t\t\t\t\tconst c1 = { x: prev.x + (2 / 3) * (c.x1 - prev.x), y: prev.y + (2 / 3) * (c.y1 - prev.y) };\n\t\t\t\t\tconst c2 = { x: c.x + (2 / 3) * (c.x1 - c.x), y: c.y + (2 / 3) * (c.y1 - c.y) };\n\t\t\t\t\tcurve(c1, c2, c);\n\t\t\t\t\tprev = { x: c.x, y: c.y };\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tcase 'C':\n\t\t\t\t\tcurve({ x: c.x1, y: c.y1 }, { x: c.x2, y: c.y2 }, c);\n\t\t\t\t\tprev = { x: c.x, y: c.y };\n\t\t\t\t\tbreak;\n\t\t\t\tcase 'Z':\n\t\t\t\t\t// The implicit closing line becomes a curve too.\n\t\t\t\t\tif (Math.hypot(prev.x - start.x, prev.y - start.y) > EPS) curve(prev, start, start);\n\t\t\t\t\tout.push({ type: 'Z' });\n\t\t\t\t\tprev = start;\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\treturn out;\n\t});\n}\n\n// ---------------------------------------------------------------------------\n// Round Corners\n// ---------------------------------------------------------------------------\n\n/**\n * Round Corners: every corner (where the direction jumps) gets a circular arc of `radius`,\n * shrunk to fit where the sides are short. Smooth points and the ends of open paths are kept.\n */\nexport function roundCornerPaths(paths: readonly BezierPath[], radius: number): BezierPath[] {\n\tif (!(radius > 0) || !Number.isFinite(radius)) return paths.slice();\n\treturn paths.map((p) => subpathsToBezier(bezierToSubpaths(p).map((sp) => setSubpathCorners(sp, radius))));\n}\n\n// ---------------------------------------------------------------------------\n// Offset Paths\n// ---------------------------------------------------------------------------\n\n/**\n * Offset Paths: grows (positive `amount`) or shrinks (negative) every path with the given join.\n * `copies` copies are made, copy i offset by `amount · (i + 1 + copyOffset)`, all in one path.\n */\nexport function offsetPaths(paths: readonly BezierPath[], amount: number, join: VectorLineJoin = 'miter', miterLimit = 4, copies = 1, copyOffset = 0): BezierPath[] {\n\tconst n = Math.min(1000, Math.max(1, Math.round(Number.isFinite(copies) ? copies : 1)));\n\treturn paths.map((p) => {\n\t\tconst out: BezierPath = [];\n\t\tfor (let i = 0; i < n; i++) out.push(...offsetPath(p, amount * (i + 1 + copyOffset), { join, miterLimit }));\n\t\treturn out;\n\t});\n}\n\n/**\n * The area a path covers when it slides `dx, dy` (its Minkowski sum with that segment): the path,\n * its moved copy and, for every edge (curves flattened within `tolerance`), the band the edge\n * sweeps, united into one path. Block and long shadows are drawn with it. Open subpaths are\n * closed, as for filling.\n */\nexport function sweepPath(path: BezierPath, dx: number, dy: number, fillRule: 'nonzero' | 'evenodd' = 'nonzero', tolerance = 0.25): BezierPath {\n\tif (!path.length) return [];\n\tif (!Number.isFinite(dx) || !Number.isFinite(dy) || Math.hypot(dx, dy) < 1e-9) return path.slice();\n\t// Every band runs the same way round, so nonzero unites the overlapping ones.\n\tconst bands: BezierPath = [];\n\tfor (const contour of pathToContours(path)) {\n\t\tconst ring = flattenChain(closeContour(contour, true), Math.max(1e-3, tolerance));\n\t\tfor (let i = 0; i < ring.length; i++) {\n\t\t\tlet p = ring[i];\n\t\t\tlet q = ring[(i + 1) % ring.length];\n\t\t\tconst turn = (q[0] - p[0]) * dy - (q[1] - p[1]) * dx;\n\t\t\tif (Math.abs(turn) < 1e-9) continue;\n\t\t\tif (turn < 0) [p, q] = [q, p];\n\t\t\tbands.push({ type: 'M', x: p[0], y: p[1] }, { type: 'L', x: q[0], y: q[1] }, { type: 'L', x: q[0] + dx, y: q[1] + dy }, { type: 'L', x: p[0] + dx, y: p[1] + dy }, { type: 'Z' });\n\t\t}\n\t}\n\tconst moved = transformBezierPath(path, [1, 0, 0, 1, dx, dy]);\n\treturn pathBoolean('union', [{ path, fillRule }, { path: moved, fillRule }, ...(bands.length ? [{ path: bands, fillRule: 'nonzero' as const }] : [])]).path;\n}\n\n// ---------------------------------------------------------------------------\n// Twist\n// ---------------------------------------------------------------------------\n\n/**\n * Twist: turns the paths about `center` by an angle growing with the distance from it, from 0\n * at the centre to `angle` degrees at the farthest point. Segments are subdivided and their\n * handles mapped through the warp's derivative, which keeps the result smooth.\n */\nexport function twistPaths(paths: readonly BezierPath[], angle: number, center: Vec2): BezierPath[] {\n\tlet rmax = 0;\n\tfor (const p of paths) for (const c of p) if (c.type !== 'Z') rmax = Math.max(rmax, Math.hypot(c.x - center.x, c.y - center.y));\n\tconst a = (angle * Math.PI) / 180;\n\tif (!a || rmax <= 1e-9 || !Number.isFinite(a)) return paths.slice();\n\tconst k = a / rmax;\n\tconst rot = (v: Point, th: number): Point => {\n\t\tconst s = Math.sin(th);\n\t\tconst co = Math.cos(th);\n\t\treturn [v[0] * co - v[1] * s, v[0] * s + v[1] * co];\n\t};\n\tconst map = (p: Point): Point => {\n\t\tconst v: Point = [p[0] - center.x, p[1] - center.y];\n\t\tconst r = rot(v, k * Math.hypot(v[0], v[1]));\n\t\treturn [center.x + r[0], center.y + r[1]];\n\t};\n\t// The warp's derivative at `p` applied to `dv`.\n\tconst jac = (p: Point, dv: Point): Point => {\n\t\tconst v: Point = [p[0] - center.x, p[1] - center.y];\n\t\tconst r = Math.hypot(v[0], v[1]);\n\t\tlet w = dv;\n\t\tif (r > 1e-12) {\n\t\t\tconst f = (k * (v[0] * dv[0] + v[1] * dv[1])) / r;\n\t\t\tw = [dv[0] - v[1] * f, dv[1] + v[0] * f];\n\t\t}\n\t\treturn rot(w, k * r);\n\t};\n\treturn paths.map((p) => {\n\t\tconst out: Sub[] = [];\n\t\tfor (const sub of subsOf(p)) {\n\t\t\tconst segs: Point[][] = [];\n\t\t\tfor (const seg of sub.segs) {\n\t\t\t\tconst cubic = seg.length === 2 ? [seg[0], seg[0], seg[1], seg[1]] : seg;\n\t\t\t\tconst len = segmentLength(seg);\n\t\t\t\tconst m = Math.min(64, Math.max(1, Math.ceil((Math.abs(a) * len) / rmax / 0.15 + len / 50)));\n\t\t\t\tfor (let i = 0; i < m; i++) {\n\t\t\t\t\tconst q = subSegment(cubic, i / m, (i + 1) / m);\n\t\t\t\t\tconst p0 = map(q[0]);\n\t\t\t\t\tconst p3 = map(q[3]);\n\t\t\t\t\tconst h1 = jac(q[0], [q[1][0] - q[0][0], q[1][1] - q[0][1]]);\n\t\t\t\t\tconst h2 = jac(q[3], [q[2][0] - q[3][0], q[2][1] - q[3][1]]);\n\t\t\t\t\tsegs.push([p0, [p0[0] + h1[0], p0[1] + h1[1]], [p3[0] + h2[0], p3[1] + h2[1]], p3]);\n\t\t\t\t}\n\t\t\t}\n\t\t\tout.push({ segs, closed: sub.closed });\n\t\t}\n\t\treturn subsToPath(out);\n\t});\n}\n\n// ---------------------------------------------------------------------------\n// Resampling (Zig Zag, Wiggle Paths)\n// ---------------------------------------------------------------------------\n\ninterface Sample {\n\tp: Point;\n\ttan: Point;\n\t/** Length of the piece before / after this sample. */\n\tlenPrev: number;\n\tlenNext: number;\n}\n\n/**\n * Splits every segment into `m` pieces of equal arc length. Original points get the average\n * of their incoming and outgoing directions (so a corner's normal is its bisector).\n */\nfunction resample(sub: Sub, m: number): Sample[] {\n\tconst segs = sub.segs;\n\tconst n = segs.length;\n\tconst lens = segs.map((s) => segmentLength(s));\n\tconst out: Sample[] = [];\n\tfor (let j = 0; j < n; j++) {\n\t\tconst piece = lens[j] / m;\n\t\tfor (let k = 0; k < m; k++) {\n\t\t\tif (k === 0) {\n\t\t\t\tconst tout = startTangent(segs[j]);\n\t\t\t\tconst prev = sub.closed || j > 0 ? (j + n - 1) % n : null;\n\t\t\t\tlet tan = tout;\n\t\t\t\tif (prev !== null) {\n\t\t\t\t\tconst tin = endTangent(segs[prev]);\n\t\t\t\t\ttan = unit(tin[0] + tout[0], tin[1] + tout[1]) ?? tout;\n\t\t\t\t}\n\t\t\t\tout.push({ p: segs[j][0], tan, lenPrev: prev === null ? 0 : lens[prev] / m, lenNext: piece });\n\t\t\t} else {\n\t\t\t\tconst t = segmentParamAtLength(segs[j], piece * k, lens[j]);\n\t\t\t\tout.push({ p: segmentPoint(segs[j], t), tan: tangentAt(segs[j], t), lenPrev: piece, lenNext: piece });\n\t\t\t}\n\t\t}\n\t}\n\tif (!sub.closed) {\n\t\tconst last = segs[n - 1];\n\t\tout.push({ p: last[last.length - 1], tan: endTangent(last), lenPrev: lens[n - 1] / m, lenNext: 0 });\n\t}\n\treturn out;\n}\n\n/** Displaced samples as corner (polyline) or smooth (tangent-aligned cubic) points; `handle` is a fraction of the pieces. */\nfunction emit(samples: readonly Sample[], disp: readonly Point[], closed: boolean, smooth: boolean, handle: number): Sub | null {\n\tconst n = samples.length;\n\tif (!n) return null;\n\tconst pt = (i: number): Point => [samples[i].p[0] + disp[i][0], samples[i].p[1] + disp[i][1]];\n\tconst segs: Point[][] = [];\n\tconst count = closed ? n : n - 1;\n\tfor (let i = 0; i < count; i++) {\n\t\tconst j = (i + 1) % n;\n\t\tconst a = samples[i];\n\t\tconst b = samples[j];\n\t\tconst p = pt(i);\n\t\tconst q = pt(j);\n\t\tif (smooth) segs.push([p, [p[0] + a.tan[0] * a.lenNext * handle, p[1] + a.tan[1] * a.lenNext * handle], [q[0] - b.tan[0] * b.lenPrev * handle, q[1] - b.tan[1] * b.lenPrev * handle], q]);\n\t\telse segs.push([p, q]);\n\t}\n\tif (!segs.length) return null;\n\treturn { segs, closed };\n}\n\n/**\n * Zig Zag: every segment gets `ridges` ridges: it is split into `ridges + 1` equal pieces and the\n * points (original ones included) are pushed alternately `size` to either side of the path.\n * `smooth` makes rounded waves. A closed path of n segments ends up with `n · (ridges + 1)` points\n * (an open one, one more).\n */\nexport function zigzagPaths(paths: readonly BezierPath[], size: number, ridges: number, smooth = false): BezierPath[] {\n\tconst m = Math.min(1000, Math.max(0, Math.round(Number.isFinite(ridges) ? ridges : 0))) + 1;\n\treturn paths.map((p) => {\n\t\tconst out: Sub[] = [];\n\t\tfor (const sub of subsOf(p)) {\n\t\t\tconst s = resample(sub, m);\n\t\t\tconst disp = s.map((x, i) => {\n\t\t\t\tconst n = perp(x.tan);\n\t\t\t\tconst d = i % 2 === 0 ? size : -size;\n\t\t\t\treturn [n[0] * d, n[1] * d] as Point;\n\t\t\t});\n\t\t\tconst e = emit(s, disp, sub.closed, smooth, 0.36);\n\t\t\tif (e) out.push(e);\n\t\t}\n\t\treturn subsToPath(out);\n\t});\n}\n\n// ---------------------------------------------------------------------------\n// Wiggle Paths\n// ---------------------------------------------------------------------------\n\nconst MASK64 = (1n << 64n) - 1n;\n\nfunction splitmix(x: bigint): bigint {\n\tx = (x + 0x9e3779b97f4a7c15n) & MASK64;\n\tlet z = x;\n\tz = ((z ^ (z >> 30n)) * 0xbf58476d1ce4e5b9n) & MASK64;\n\tz = ((z ^ (z >> 27n)) * 0x94d049bb133111ebn) & MASK64;\n\treturn z ^ (z >> 31n);\n}\n\n/** Deterministic hash → [−1, 1]. */\nfunction hash(seed: bigint, idx: bigint, t: number): number {\n\tconst h = splitmix(splitmix(splitmix(seed) ^ idx) ^ BigInt.asUintN(64, BigInt(t)));\n\treturn (Number(h >> 11n) / 2 ** 53) * 2 - 1;\n}\n\n/** Smooth 1D value noise in [−1, 1]: Catmull-Rom through hashed lattice values (C1 in time). */\nfunction noise(seed: bigint, idx: bigint, t: number): number {\n\tconst i = Math.floor(t);\n\tconst f = t - i;\n\tconst p0 = hash(seed, idx, i - 1);\n\tconst p1 = hash(seed, idx, i);\n\tconst p2 = hash(seed, idx, i + 1);\n\tconst p3 = hash(seed, idx, i + 2);\n\tconst v = 0.5 * (2 * p1 + (-p0 + p2) * f + (2 * p0 - 5 * p1 + 4 * p2 - p3) * f * f + (-p0 + 3 * p1 - 3 * p2 + p3) * f * f * f);\n\treturn Math.min(1, Math.max(-1, v));\n}\n\n/**\n * Wiggle Paths: subdivides the paths (`detail` points per segment) and moves every point by\n * smooth noise of up to `size` that evolves over `time` seconds at `speed` wiggles per second.\n * The same parameters always give the same result.\n */\nexport function wigglePaths(paths: readonly BezierPath[], w: VectorEffectParamsMap['wiggle']): BezierPath[] {\n\tif (!w.size || !Number.isFinite(w.size)) return paths.slice();\n\tconst m = Math.min(1000, Math.max(0, Math.round(Number.isFinite(w.detail) ? w.detail : 0))) + 1;\n\tconst seed = BigInt.asUintN(64, BigInt(Math.round(Number.isFinite(w.seed) ? w.seed : 0)));\n\tconst t = (Number.isFinite(w.time) ? w.time : 0) * (Number.isFinite(w.speed) ? w.speed : 0) + (Number.isFinite(w.phase) ? w.phase : 0) / 360;\n\tconst corr = Math.min(1, Math.max(0, (Number.isFinite(w.correlation) ? w.correlation : 0) / 100));\n\tconst sx = noise(seed, MASK64, t);\n\tconst sy = noise(seed, MASK64 - 1n, t);\n\tlet idx = 0;\n\treturn paths.map((p) => {\n\t\tconst out: Sub[] = [];\n\t\tfor (const sub of subsOf(p)) {\n\t\t\tconst s = resample(sub, m);\n\t\t\tconst disp = s.map(() => {\n\t\t\t\tconst i = BigInt(idx);\n\t\t\t\tconst ox = noise(seed, i * 2n, t + idx * 0.37);\n\t\t\t\tconst oy = noise(seed, i * 2n + 1n, t + idx * 0.61);\n\t\t\t\tidx++;\n\t\t\t\treturn [(sx * corr + ox * (1 - corr)) * w.size, (sy * corr + oy * (1 - corr)) * w.size] as Point;\n\t\t\t});\n\t\t\tconst e = emit(s, disp, sub.closed, w.smooth, 1 / 3);\n\t\t\tif (e) out.push(e);\n\t\t}\n\t\treturn subsToPath(out);\n\t});\n}\n\n// ---------------------------------------------------------------------------\n// Merge Paths\n// ---------------------------------------------------------------------------\n\nconst MERGE_OPS = { add: 'union', subtract: 'difference', intersect: 'intersection', exclude: 'xor' } as const;\n\n/** Merge Paths: the paths (in stacking order, each filled non-zero) combined into one path. */\nexport function mergePaths(paths: readonly BezierPath[], mode: VectorMergeMode = 'merge'): BezierPath {\n\tif (mode === 'merge' || !(mode in MERGE_OPS)) return paths.flat();\n\tconst inputs = paths.filter((p) => p.length > 0).map((path) => ({ path, fillRule: 'nonzero' as const }));\n\tif (!inputs.length) return [];\n\treturn pathBoolean(MERGE_OPS[mode as keyof typeof MERGE_OPS], inputs).path;\n}\n\n// ---------------------------------------------------------------------------\n// Repeater\n// ---------------------------------------------------------------------------\n\n/** One copy a repeater makes: its transform (node space) and opacity factor. */\nexport interface VectorRepeaterCopy {\n\t/** Copy number (0 is the original). */\n\tindex: number;\n\tmatrix: AffineMatrix;\n\topacity: number;\n}\n\n/**\n * The copies of a repeater around `pivot` (the anchor point in node space), in copy order.\n * Copy i is moved by `translate(position·k) · rotate(rotation·k) · scale^k` about the pivot with\n * `k = i + offset`; opacity runs from the start to the end opacity across the copies, and a\n * fractional copy count fades the last copy by its fraction.\n */\nexport function vectorRepeaterCopies(r: VectorEffectParamsMap['repeater'], pivot: Vec2): VectorRepeaterCopy[] {\n\tconst copies = Math.max(0, Number.isFinite(r.copies) ? Math.min(r.copies, 1000) : 0);\n\tconst n = Math.ceil(copies);\n\tconst offset = Number.isFinite(r.offset) ? r.offset : 0;\n\tconst so = (r.startOpacity ?? 100) / 100;\n\tconst eo = (r.endOpacity ?? 100) / 100;\n\tconst fract = copies - Math.floor(copies);\n\tconst out: VectorRepeaterCopy[] = [];\n\tfor (let i = 0; i < n; i++) {\n\t\tconst k = i + offset;\n\t\tlet m = translateMatrix(-pivot.x, -pivot.y);\n\t\tm = multiplyMatrices(m, scaleMatrix(Math.pow((r.scale?.x ?? 100) / 100, k), Math.pow((r.scale?.y ?? 100) / 100, k)));\n\t\tm = multiplyMatrices(m, rotateMatrix((r.rotation ?? 0) * k));\n\t\tm = multiplyMatrices(m, translateMatrix(pivot.x + (r.position?.x ?? 0) * k, pivot.y + (r.position?.y ?? 0) * k));\n\t\tconst t = n > 1 ? i / (n - 1) : 0;\n\t\tconst partial = i + 1 === n && fract > 0 ? fract : 1;\n\t\tout.push({ index: i, matrix: m, opacity: Math.min(1, Math.max(0, (so + (eo - so) * t) * partial)) });\n\t}\n\treturn out;\n}\n\n/** Each path repeated by `vectorRepeaterCopies` (copy order, the original first). */\nexport function repeatPaths(paths: readonly BezierPath[], r: VectorEffectParamsMap['repeater'], pivot: Vec2): { copy: VectorRepeaterCopy; paths: BezierPath[] }[] {\n\treturn vectorRepeaterCopies(r, pivot).map((copy) => ({ copy, paths: paths.map((p) => transformBezierPath(p, copy.matrix)) }));\n}\n\n/** The middle of the paths' bounds (the origin when they are empty). */\nexport function pathsCenter(paths: readonly BezierPath[]): Vec2 {\n\tconst b = bezierPathBounds(paths.flat());\n\treturn b ? { x: (b.minX + b.maxX) / 2, y: (b.minY + b.maxY) / 2 } : { x: 0, y: 0 };\n}\n","/**\n * Non-affine maps of paths, so shapes stay Bézier paths through Free Distort (a projective map)\n * and envelope warps.\n *\n * - `mapVectorPoints` sends every anchor and handle through the map and keeps the anchors as they\n * are. Under a projective map straight segments stay exactly straight; a curve keeps its exact\n * end tangents and approximates the (rational) image between.\n * - `mapVectorSubpaths` follows any smooth map: each segment is halved until its mapped control\n * points follow the mapped curve within a tolerance, so the result gains anchors where the map\n * bends it. Runs of pieces are then refitted with fewer cubics (`fitCubicRun`) where that stays\n * within the tolerance.\n *\n * Ported from ArtCraft (MIT OR Apache-2.0, © ArtCraft Team and contributors; see\n * THIRD_PARTY_NOTICES.md): photocraft `crates/vector/src/map.rs` (`map_points`, `map_path`,\n * `map_subpath`, `map_segment`, `split_mapped`, `halves`, `off_line`).\n */\nimport { fitCubicRun, type CubicSegment } from '../canvas/curveFit.js';\nimport { segmentNearest, type BezierPath, type BezierPathInput } from '../canvas/pathops/bezier.js';\nimport { bezierToSubpaths, subpathsToBezier } from './geometry.js';\nimport type { Vec2, VectorAnchor, VectorSubpath } from './types.js';\n\n/** A map of the plane (document or node space). */\nexport type VectorPointMap = (p: Vec2) => Vec2;\n\ntype Cubic = [Vec2, Vec2, Vec2, Vec2];\n\n/** Pieces a path may be split into in total: bounds the work on hostile input. */\nconst MAX_PIECES = 1 << 20;\n/** Deepest split of one segment (2^6 = 64 pieces). */\nconst MAX_DEPTH = 6;\nconst PROBES = [0.25, 0.5, 0.75];\n\nconst lerp = (a: Vec2, b: Vec2, t: number): Vec2 => ({ x: a.x + (b.x - a.x) * t, y: a.y + (b.y - a.y) * t });\nconst dist = (a: Vec2, b: Vec2) => Math.hypot(a.x - b.x, a.y - b.y);\nconst same = (a: Vec2, b: Vec2) => Math.abs(a.x - b.x) < 1e-9 && Math.abs(a.y - b.y) < 1e-9;\n\nfunction evalCubic(s: Cubic, t: number): Vec2 {\n\tconst ab = lerp(s[0], s[1], t);\n\tconst bc = lerp(s[1], s[2], t);\n\tconst cd = lerp(s[2], s[3], t);\n\treturn lerp(lerp(ab, bc, t), lerp(bc, cd, t), t);\n}\n\n/** De Casteljau split at t = ½. */\nfunction halves(s: Cubic): [Cubic, Cubic] {\n\tconst ab = lerp(s[0], s[1], 0.5);\n\tconst bc = lerp(s[1], s[2], 0.5);\n\tconst cd = lerp(s[2], s[3], 0.5);\n\tconst abc = lerp(ab, bc, 0.5);\n\tconst bcd = lerp(bc, cd, 0.5);\n\tconst m = lerp(abc, bcd, 0.5);\n\treturn [\n\t\t[s[0], ab, abc, m],\n\t\t[m, bcd, cd, s[3]]\n\t];\n}\n\n/** Distance from `p` to the line through `a` and `b` (to `a` when they coincide). */\nfunction offLine(p: Vec2, a: Vec2, b: Vec2): number {\n\tconst l = dist(a, b);\n\treturn l < 1e-12 ? dist(p, a) : Math.abs((b.x - a.x) * (a.y - p.y) - (a.x - p.x) * (b.y - a.y)) / l;\n}\n\nconst mapAnchorPoints = (a: VectorAnchor, f: VectorPointMap): VectorAnchor => {\n\tconst p = f(a);\n\treturn {\n\t\tx: p.x,\n\t\ty: p.y,\n\t\t...(a.in ? { in: f(a.in) } : {}),\n\t\t...(a.out ? { out: f(a.out) } : {}),\n\t\t...(a.type && a.type !== 'corner' ? { type: a.type } : {}),\n\t\t...(a.corner ? { corner: { ...a.corner } } : {}),\n\t\t...(a.id ? { id: a.id } : {})\n\t};\n};\n\n/** Every anchor and handle of `subpaths` through `f` (no subdivision). */\nexport function mapVectorPoints(subpaths: readonly VectorSubpath[], f: VectorPointMap): VectorSubpath[] {\n\treturn subpaths.map((sp) => ({ closed: sp.closed, anchors: sp.anchors.map((a) => mapAnchorPoints(a, f)) }));\n}\n\nfunction splitMapped(seg: Cubic, f: VectorPointMap, tol: number, depth: number, out: Cubic[]) {\n\tconst mapped = seg.map(f) as Cubic;\n\tconst fits = PROBES.every((t) => dist(f(evalCubic(seg, t)), evalCubic(mapped, t)) <= tol);\n\tif (fits || depth === 0) {\n\t\tout.push(mapped);\n\t\treturn;\n\t}\n\tconst [a, b] = halves(seg);\n\tsplitMapped(a, f, tol, depth - 1, out);\n\tsplitMapped(b, f, tol, depth - 1, out);\n}\n\nconst toPoint = (p: Vec2): [number, number] => [p.x, p.y];\nconst toVec = (p: readonly number[]): Vec2 => ({ x: p[0], y: p[1] });\n\n/**\n * The image of `seg` through `f` as fewer cubics than `pieces` when they stay within `tol` of it\n * (fitted to samples of the mapped curve with the pieces' end tangents), else `pieces`.\n */\nfunction refit(seg: Cubic, pieces: Cubic[], f: VectorPointMap, tol: number): Cubic[] {\n\tif (pieces.length < 3) return pieces;\n\tconst n = pieces.length * 4;\n\tconst samples: [number, number][] = [];\n\tfor (let i = 0; i <= n; i++) samples.push(toPoint(f(evalCubic(seg, i / n))));\n\tconst first = pieces[0];\n\tconst last = pieces[pieces.length - 1];\n\tconst t0 = !same(first[1], first[0]) ? first[1] : first[2];\n\tconst t1 = !same(last[2], last[3]) ? last[2] : last[1];\n\tconst fitted: CubicSegment[] = fitCubicRun(samples, tol / 2, [t0.x - first[0].x, t0.y - first[0].y], [last[3].x - t1.x, last[3].y - t1.y]);\n\tif (!fitted.length || fitted.length >= pieces.length) return pieces;\n\t// Check between the fitted samples too.\n\tconst chain = fitted.map((c) => [c.p0, c.p1, c.p2, c.p3]);\n\tfor (let i = 0; i < n; i++) {\n\t\tconst q = toPoint(f(evalCubic(seg, (i + 0.5) / n)));\n\t\tlet best = Infinity;\n\t\tfor (const c of chain) best = Math.min(best, segmentNearest(c, q).distance);\n\t\tif (best > tol) return pieces;\n\t}\n\treturn fitted.map((c) => [toVec(c.p0), toVec(c.p1), toVec(c.p2), toVec(c.p3)]);\n}\n\nfunction mapSegment(seg: Cubic, f: VectorPointMap, tol: number, depth: number, fit: boolean): Cubic[] {\n\t// A straight segment whose image is straight stays one.\n\tif (same(seg[1], seg[0]) && same(seg[2], seg[3])) {\n\t\tconst a = f(seg[0]);\n\t\tconst b = f(seg[3]);\n\t\tif (PROBES.every((t) => offLine(f(lerp(seg[0], seg[3], t)), a, b) <= tol)) return [[a, a, b, b]];\n\t\t// Bent by the map: the same line as an evenly parametrised cubic, then split.\n\t\tconst line: Cubic = [seg[0], lerp(seg[0], seg[3], 1 / 3), lerp(seg[0], seg[3], 2 / 3), seg[3]];\n\t\tconst out: Cubic[] = [];\n\t\tsplitMapped(line, f, tol, depth, out);\n\t\treturn fit ? refit(line, out, f, tol) : out;\n\t}\n\tconst out: Cubic[] = [];\n\tsplitMapped(seg, f, tol, depth, out);\n\treturn fit ? refit(seg, out, f, tol) : out;\n}\n\n/** Makes a smooth anchor's handles collinear again (a curved map can kink them slightly), keeping their lengths. */\nfunction realign(a: VectorAnchor): VectorAnchor {\n\tif (!a.in || !a.out || same(a.in, a) || same(a.out, a)) return a;\n\tconst li = dist(a.in, a);\n\tconst lo = dist(a.out, a);\n\tconst dx = (a.x - a.in.x) / li + (a.out.x - a.x) / lo;\n\tconst dy = (a.y - a.in.y) / li + (a.out.y - a.y) / lo;\n\tconst l = Math.hypot(dx, dy);\n\tif (l < 1e-12) return a;\n\tconst u = { x: dx / l, y: dy / l };\n\tconst type = a.type === 'symmetric' && Math.abs(li - lo) > 1e-6 * Math.max(li, lo) ? 'smooth' : a.type;\n\treturn { ...a, in: { x: a.x - u.x * li, y: a.y - u.y * li }, out: { x: a.x + u.x * lo, y: a.y + u.y * lo }, ...(type ? { type } : {}) };\n}\n\nconst segmentOf = (sp: VectorSubpath, i: number): Cubic => {\n\tconst a = sp.anchors[i];\n\tconst b = sp.anchors[(i + 1) % sp.anchors.length];\n\treturn [{ x: a.x, y: a.y }, a.out ?? { x: a.x, y: a.y }, b.in ?? { x: b.x, y: b.y }, { x: b.x, y: b.y }];\n};\n\nfunction mapSubpath(sp: VectorSubpath, f: VectorPointMap, tol: number, depth: number, fit: boolean): VectorSubpath {\n\tconst n = sp.anchors.length;\n\tconst count = n < 2 ? 0 : sp.closed ? n : n - 1;\n\tif (!count) return mapVectorPoints([sp], f)[0];\n\tconst pieces: Cubic[][] = [];\n\tfor (let i = 0; i < count; i++) pieces.push(mapSegment(segmentOf(sp, i), f, tol, depth, fit));\n\tconst anchors: VectorAnchor[] = [];\n\tconst put = (a: VectorAnchor) => {\n\t\tif (a.in && same(a.in, a)) delete a.in;\n\t\tif (a.out && same(a.out, a)) delete a.out;\n\t\tanchors.push(a.type === 'smooth' || a.type === 'symmetric' ? realign(a) : a);\n\t};\n\tsp.anchors.forEach((k, i) => {\n\t\tconst incoming = i > 0 ? pieces[i - 1] : sp.closed ? pieces[n - 1] : undefined;\n\t\tconst outgoing = pieces[i];\n\t\tconst p = f(k);\n\t\tconst a: VectorAnchor = { x: p.x, y: p.y };\n\t\tconst inCtrl = incoming ? incoming[incoming.length - 1][2] : k.in ? f(k.in) : null;\n\t\tconst outCtrl = outgoing ? outgoing[0][1] : k.out ? f(k.out) : null;\n\t\tif (inCtrl) a.in = inCtrl;\n\t\tif (outCtrl) a.out = outCtrl;\n\t\tif (k.type && k.type !== 'corner') a.type = k.type;\n\t\tif (k.corner) a.corner = { ...k.corner };\n\t\tput(a);\n\t\t// The anchors a split added inside segment i: smooth, as the curve runs through them.\n\t\tif (outgoing) for (let w = 1; w < outgoing.length; w++) put({ x: outgoing[w][0].x, y: outgoing[w][0].y, in: outgoing[w - 1][2], out: outgoing[w][1], type: 'smooth' });\n\t});\n\treturn { closed: sp.closed, anchors };\n}\n\nexport interface MapVectorSubpathsOptions {\n\t/** Refit runs of split pieces with fewer cubics where they stay within the tolerance (default true). */\n\trefit?: boolean;\n}\n\n/**\n * `subpaths` through a smooth, possibly non-linear map `f`: each segment is split in halves until\n * its mapped control points follow the mapped curve within `tolerance` (at most 64 pieces a\n * segment, fewer for huge paths), then refitted with fewer cubics where possible. A straight\n * segment whose image is straight stays a straight segment; anchors keep their types and live\n * corners, and the anchors added are smooth.\n */\nexport function mapVectorSubpaths(subpaths: readonly VectorSubpath[], f: VectorPointMap, tolerance = 0.1, options: MapVectorSubpathsOptions = {}): VectorSubpath[] {\n\tconst tol = Number.isFinite(tolerance) && tolerance > 0 ? tolerance : 0.1;\n\tconst segments = subpaths.reduce((s, sp) => s + sp.anchors.length, 0);\n\tlet depth = MAX_DEPTH;\n\twhile (depth > 0 && segments * 2 ** depth > MAX_PIECES) depth--;\n\treturn subpaths.map((sp) => mapSubpath(sp, f, tol, depth, options.refit !== false));\n}\n\n/** `mapVectorSubpaths` for Bézier commands (live corners are not involved). */\nexport function mapBezierPath(path: BezierPathInput, f: VectorPointMap, tolerance = 0.1, options: MapVectorSubpathsOptions = {}): BezierPath {\n\treturn subpathsToBezier(mapVectorSubpaths(bezierToSubpaths(path), f, tolerance, options), { corners: false });\n}\n","/**\n * Frames (artboards) and their children's resizing constraints.\n *\n * A frame is a group with `frame` set: a rectangle in the group's own space, a fill drawn below the\n * children and (by default) a clip. It draws, hit-tests and bounds through `vectorFrameDrawn`, an\n * equivalent clip group (or plain group without the clip), so rendering, masks, snapping and SVG\n * export reuse the mask group machinery. Resizing a frame lays out its children by their\n * `resizing` constraints (`vectorFrameChildMatrix`) instead of scaling them.\n *\n * The constraint rules follow figcraft's `crates/layout/src/lib.rs` `apply_constraints` (MIT OR\n * Apache-2.0, © ArtCraft Team and contributors; see THIRD_PARTY_NOTICES.md), as already ported for\n * the canvas package (`canvas/autoLayout.ts`): left / right / left and right / centre / scale\n * horizontally, top / bottom / top and bottom / centre / scale vertically.\n */\n\nimport type {\n\tVectorBounds,\n\tVectorDocument,\n\tVectorFrame,\n\tVectorGroupNode,\n\tVectorHorizontalResizing,\n\tVectorNode,\n\tVectorPathNode,\n\tVectorResizing,\n\tVectorVerticalResizing\n} from './types.js';\nimport { VECTOR_HORIZONTAL_RESIZING, VECTOR_VERTICAL_RESIZING } from './types.js';\nimport type { AffineMatrix } from '../geom/types.js';\n\n/** A frame group (its `frame` set, and not a blend, live boolean or mask group). */\nexport type VectorFrameGroup = VectorGroupNode & { frame: VectorFrame };\n\n/** Whether the node is a frame. */\nexport function isVectorFrame(node: VectorNode | null | undefined): node is VectorFrameGroup {\n\treturn node?.type === 'group' && !!node.frame && !node.blend && !node.liveBoolean && !node.mask;\n}\n\n/** The frame's rectangle as a closed four-anchor path (in the frame's own space). */\nexport function vectorFrameRectPath(frame: VectorFrame): VectorPathNode['subpaths'] {\n\tconst { x, y, width: w, height: h } = frame;\n\treturn [{ closed: true, anchors: [{ x, y }, { x: x + w, y }, { x: x + w, y: y + h }, { x, y: y + h }] }];\n}\n\nconst drawnCache = new WeakMap<VectorFrameGroup, VectorGroupNode>();\n\n/**\n * The frame as an equivalent plain group: a clip group (`mask: clip`) whose mask is the frame's\n * rectangle (`<id>~frame-clip`), then its fill (`<id>~frame-fill`) and its children; without the\n * clip, a group of the fill and the children. Same id, transform and appearance. Cached per node.\n */\nexport function vectorFrameDrawn(node: VectorFrameGroup): VectorGroupNode {\n\tlet hit = drawnCache.get(node);\n\tif (hit) return hit;\n\tconst { frame, ...group } = node;\n\tconst rect = vectorFrameRectPath(frame);\n\tconst fill = frame.fill !== undefined && frame.fill !== null && frame.fill !== 'none' ? [{ id: `${node.id}~frame-fill`, type: 'path' as const, fill: frame.fill, stroke: null, subpaths: rect }] : [];\n\thit =\n\t\tframe.clip === false\n\t\t\t? { ...group, children: [...fill, ...node.children] }\n\t\t\t: { ...group, mask: { type: 'clip' }, children: [{ id: `${node.id}~frame-clip`, type: 'path', fill: '#000000', stroke: null, subpaths: rect }, ...fill, ...node.children] };\n\tdrawnCache.set(node, hit);\n\treturn hit;\n}\n\n/** Whether `p` (in the frame's own space) lies in its rectangle, within `tolerance`. */\nexport function vectorFrameContains(frame: VectorFrame, p: { x: number; y: number }, tolerance = 0): boolean {\n\treturn p.x >= frame.x - tolerance && p.x <= frame.x + frame.width + tolerance && p.y >= frame.y - tolerance && p.y <= frame.y + frame.height + tolerance;\n}\n\ntype Axis = 'start' | 'end' | 'both' | 'center' | 'scale';\nconst H: Record<VectorHorizontalResizing, Axis> = { left: 'start', right: 'end', leftRight: 'both', center: 'center', scale: 'scale' };\nconst V: Record<VectorVerticalResizing, Axis> = { top: 'start', bottom: 'end', topBottom: 'both', center: 'center', scale: 'scale' };\n\n/** Where a child's span [a0, a1] goes when its frame's span [f0, f1] becomes [g0, g1]. */\nfunction placeSpan(rule: Axis, a0: number, a1: number, f0: number, f1: number, g0: number, g1: number): [number, number] {\n\tconst size = a1 - a0;\n\tswitch (rule) {\n\t\tcase 'start':\n\t\t\treturn [g0 + (a0 - f0), g0 + (a1 - f0)];\n\t\tcase 'end':\n\t\t\treturn [g1 - (f1 - a0), g1 - (f1 - a1)];\n\t\tcase 'both': {\n\t\t\tconst b0 = g0 + (a0 - f0);\n\t\t\t// Never narrower than nothing (a frame shrunk past the margins keeps the child a sliver).\n\t\t\treturn [b0, Math.max(b0 + Math.min(size, 1e-3), g1 - (f1 - a1))];\n\t\t}\n\t\tcase 'center': {\n\t\t\tconst c = (g0 + g1) / 2 + ((a0 + a1) / 2 - (f0 + f1) / 2);\n\t\t\treturn [c - size / 2, c + size / 2];\n\t\t}\n\t\tcase 'scale': {\n\t\t\tconst k = f1 - f0 > 1e-9 ? (g1 - g0) / (f1 - f0) : 1;\n\t\t\treturn [g0 + (a0 - f0) * k, g0 + (a1 - f0) * k];\n\t\t}\n\t}\n}\n\n/**\n * The matrix (in the frame's own space) that takes a child with bounds `box` from frame rectangle\n * `from` to `to` by the child's `resizing` constraints: a scale and translation per axis.\n */\nexport function vectorFrameChildMatrix(resizing: VectorResizing | null | undefined, box: VectorBounds, from: VectorFrame, to: VectorFrame): AffineMatrix {\n\tconst [x0, x1] = placeSpan(H[resizing?.horizontal ?? 'left'] ?? 'start', box.x, box.x + box.width, from.x, from.x + from.width, to.x, to.x + to.width);\n\tconst [y0, y1] = placeSpan(V[resizing?.vertical ?? 'top'] ?? 'start', box.y, box.y + box.height, from.y, from.y + from.height, to.y, to.y + to.height);\n\tconst sx = box.width > 1e-9 ? (x1 - x0) / box.width : 1;\n\tconst sy = box.height > 1e-9 ? (y1 - y0) / box.height : 1;\n\treturn [sx, 0, 0, sy, x0 - sx * box.x, y0 - sy * box.y];\n}\n\nconst finite = (v: unknown): v is number => typeof v === 'number' && Number.isFinite(v);\n\n/** Reads a frame from untrusted data (JSON, agent input, SVG import), or null. */\nexport function sanitizeVectorFrame(value: unknown): VectorFrame | null {\n\tif (!value || typeof value !== 'object') return null;\n\tconst r = value as Record<string, unknown>;\n\tif (!finite(r.x) || !finite(r.y) || !finite(r.width) || !finite(r.height) || r.width < 0 || r.height < 0) return null;\n\tconst out: VectorFrame = { x: r.x, y: r.y, width: r.width, height: r.height };\n\tif (typeof r.fill === 'string' || (r.fill && typeof r.fill === 'object')) out.fill = r.fill as VectorFrame['fill'];\n\tif (r.clip === false) out.clip = false;\n\treturn out;\n}\n\n/** Reads resizing constraints from untrusted data, or null (unknown values dropped). */\nexport function sanitizeVectorResizing(value: unknown): VectorResizing | null {\n\tif (!value || typeof value !== 'object') return null;\n\tconst r = value as Record<string, unknown>;\n\tconst out: VectorResizing = {};\n\tif (VECTOR_HORIZONTAL_RESIZING.includes(r.horizontal as VectorHorizontalResizing)) out.horizontal = r.horizontal as VectorHorizontalResizing;\n\tif (VECTOR_VERTICAL_RESIZING.includes(r.vertical as VectorVerticalResizing)) out.vertical = r.vertical as VectorVerticalResizing;\n\treturn out.horizontal || out.vertical ? out : null;\n}\n\n/** Labels for the resizing constraint pickers. */\nexport const VECTOR_HORIZONTAL_RESIZING_LABELS: Readonly<Record<VectorHorizontalResizing, string>> = {\n\tleft: 'Left',\n\tright: 'Right',\n\tleftRight: 'Left & right',\n\tcenter: 'Centre',\n\tscale: 'Scale'\n};\nexport const VECTOR_VERTICAL_RESIZING_LABELS: Readonly<Record<VectorVerticalResizing, string>> = {\n\ttop: 'Top',\n\tbottom: 'Bottom',\n\ttopBottom: 'Top & bottom',\n\tcenter: 'Centre',\n\tscale: 'Scale'\n};\n\n/** Whether `inner` lies wholly in `outer` (false for a missing box). */\nexport function vectorBoundsInside(inner: VectorBounds | null, outer: VectorBounds): boolean {\n\treturn !!inner && inner.x >= outer.x - 1e-9 && inner.y >= outer.y - 1e-9 && inner.x + inner.width <= outer.x + outer.width + 1e-9 && inner.y + inner.height <= outer.y + outer.height + 1e-9;\n}\n\n/** Top-level frames of a document (its artboards), bottom to top. */\nexport function vectorArtboards(doc: Pick<VectorDocument, 'nodes'>): VectorFrameGroup[] {\n\treturn doc.nodes.filter(isVectorFrame);\n}\n\n/**\n * A document of one frame on its own, sized to the frame with the frame's corner at the origin\n * (the frame's rotation undone), for exporting an artboard. Symbols, constraints' parameters and the\n * page background are carried over. Null when `id` is not a frame.\n */\nexport function vectorFrameDocument(doc: VectorDocument, id: string, find: (nodes: readonly VectorNode[], id: string) => VectorNode | null | undefined): VectorDocument | null {\n\tconst node = find(doc.nodes, id);\n\tif (!isVectorFrame(node)) return null;\n\tconst { transform: _t, ...rest } = node;\n\tconst { x, y, width, height } = node.frame;\n\tconst placed: VectorFrameGroup = x || y ? { ...rest, transform: [1, 0, 0, 1, -x, -y] } : rest;\n\treturn {\n\t\twidth,\n\t\theight,\n\t\t...(doc.background ? { background: doc.background } : {}),\n\t\tnodes: [placed],\n\t\t...(doc.symbols?.length ? { symbols: doc.symbols } : {})\n\t};\n}\n\n/** What the frame panel shows for the selection. */\nexport interface VectorFramePanel {\n\t/** The selected frame (the first, when several are), or null. */\n\tframe: { id: string; name: string; artboard: boolean; frame: VectorFrame } | null;\n\t/**\n\t * The resizing constraints of the selected objects that sit directly in a frame (null when none\n\t * does): each axis' value, or `mixed` when they differ.\n\t */\n\tresizing: { ids: string[]; horizontal: VectorHorizontalResizing | 'mixed'; vertical: VectorVerticalResizing | 'mixed' } | null;\n}\n\n/** The frame panel's data for a selection. */\nexport function getVectorFramePanel(state: { document: Pick<VectorDocument, 'nodes'>; selection: readonly string[] }): VectorFramePanel {\n\tconst parents = new Map<string, VectorNode | null>();\n\tconst nodes = new Map<string, VectorNode>();\n\tconst walk = (list: readonly VectorNode[], parent: VectorNode | null) => {\n\t\tfor (const n of list) {\n\t\t\tparents.set(n.id, parent);\n\t\t\tnodes.set(n.id, n);\n\t\t\tif (n.type === 'group') walk(n.children, n);\n\t\t}\n\t};\n\twalk(state.document.nodes, null);\n\tconst selected = state.selection.map((id) => nodes.get(id)).filter((n): n is VectorNode => !!n);\n\tconst f = selected.find(isVectorFrame);\n\tconst children = selected.filter((n) => isVectorFrame(parents.get(n.id)));\n\tconst one = <T>(values: T[]): T | 'mixed' => (values.every((v) => v === values[0]) ? values[0] : 'mixed');\n\treturn {\n\t\tframe: f ? { id: f.id, name: f.name ?? 'Frame', artboard: parents.get(f.id) === null, frame: f.frame } : null,\n\t\tresizing: children.length\n\t\t\t? { ids: children.map((c) => c.id), horizontal: one(children.map((c) => c.resizing?.horizontal ?? 'left')), vertical: one(children.map((c) => c.resizing?.vertical ?? 'top')) }\n\t\t\t: null\n\t};\n}\n","/**\n * Knife and eraser on Bézier paths, built on the curve booleans and `outlineStroke`.\n *\n * The knife cuts filled regions along a polyline with no gap: each stretch of the polyline\n * that crosses a region from boundary to boundary (a chord) splits the boundary loop it starts\n * and ends on into two loops sharing that chord, or, when it joins two loops (an outline and a\n * hole), merges them into one. Crossings are exact (line–cubic roots), and the pieces share\n * the cut edge exactly.\n *\n * The eraser removes the area of a round-capped stroke along a polyline: filled shapes lose it\n * by a boolean difference; outlines are cut where they cross the stroke's outline (exact\n * curve–curve intersections) and keep the parts outside it.\n *\n * Modelled on vectorcraft-main/crates/engine/src/cmd/draw2.rs (`knife`, `erase_region`,\n * `erase_outline`, `cut_subpath`; MIT OR Apache-2.0, © ArtCraft Team and contributors; see\n * THIRD_PARTY_NOTICES.md), without its fixed knife slit and its sampled crossing search.\n */\nimport type { Point } from '../canvas/types.js';\nimport {\n\tbezierPathBounds,\n\tcloseContour,\n\tcontourSignedArea,\n\tcontoursToPath,\n\tpathToContours,\n\tpointInBezierPath,\n\tsegmentBounds,\n\tsegmentPoint,\n\tsubSegment,\n\twindingNumber,\n\ttype BezierPath,\n\ttype BezierPathInput\n} from '../canvas/pathops/bezier.js';\nimport { normalizeBezierPath, pathBoolean, segmentIntersections } from '../canvas/pathops/boolean.js';\nimport { outlineStroke } from '../canvas/pathops/stroke.js';\nimport { inferAnchorType, subpathSegment, subpathSegmentCount } from './geometry.js';\nimport type { VectorAnchor, VectorSubpath } from './types.js';\n\ntype FillRule = 'nonzero' | 'evenodd';\n\n// ---------------------------------------------------------------------------\n// Faces: an outer loop with its holes\n// ---------------------------------------------------------------------------\n\ninterface Loop {\n\tsegs: Point[][];\n\t/** Which segments came from a knife chord (not sampled for containment). */\n\tchord: boolean[];\n}\n\ninterface Face {\n\tloops: Loop[];\n}\n\nconst loopArea = (l: Loop) => contourSignedArea(l.segs);\n\n/** A point on the loop that is not on a chord (chords are shared with a neighbouring piece). */\nfunction loopSample(l: Loop): Point {\n\tconst k = l.chord.findIndex((c) => !c);\n\treturn segmentPoint(l.segs[k >= 0 ? k : 0], 0.5);\n}\n\nconst contains = (l: Loop, p: Point) => windingNumber([l.segs], p) !== 0;\n\n/**\n * Groups non-crossing loops into faces: loops turning like the largest one are outlines, the\n * others holes of the smallest outline around them.\n */\nfunction groupFaces(loops: Loop[]): Face[] {\n\tconst usable = loops.filter((l) => l.segs.length && Math.abs(loopArea(l)) > 1e-12);\n\tif (!usable.length) return [];\n\tconst largest = usable.reduce((a, b) => (Math.abs(loopArea(b)) > Math.abs(loopArea(a)) ? b : a));\n\tconst sign = Math.sign(loopArea(largest));\n\tconst outers = usable.filter((l) => Math.sign(loopArea(l)) === sign).sort((a, b) => Math.abs(loopArea(a)) - Math.abs(loopArea(b)));\n\tconst faces = new Map<Loop, Face>(outers.map((o) => [o, { loops: [o] }]));\n\tfor (const hole of usable.filter((l) => Math.sign(loopArea(l)) !== sign)) {\n\t\tconst p = loopSample(hole);\n\t\tconst parent = outers.find((o) => Math.abs(loopArea(o)) > Math.abs(loopArea(hole)) && contains(o, p));\n\t\tif (parent) faces.get(parent)!.loops.push(hole);\n\t}\n\treturn outers.reverse().map((o) => faces.get(o)!);\n}\n\nfunction faceToPath(face: Face): BezierPath {\n\treturn contoursToPath(face.loops.map((l) => ({ segments: l.segs, closed: true })));\n}\n\n/** Simple, consistently oriented faces of a filled path. */\nfunction facesOf(path: BezierPathInput, fillRule: FillRule): Face[] {\n\tconst normalized = normalizeBezierPath(path, fillRule);\n\tconst loops = pathToContours(normalized).map((c) => {\n\t\tconst segs = closeContour(c, true).map((s) => s.slice());\n\t\treturn { segs, chord: segs.map(() => false) };\n\t});\n\treturn groupFaces(loops);\n}\n\n/** One path per face (an outline with its holes) of a filled path, largest first. */\nexport function splitIntoFaces(path: BezierPathInput, fillRule: FillRule = 'nonzero'): BezierPath[] {\n\treturn facesOf(path, fillRule).map(faceToPath);\n}\n\n// ---------------------------------------------------------------------------\n// Line × segment crossings\n// ---------------------------------------------------------------------------\n\n/** Real roots in [0, 1] of `a·t³ + b·t² + c·t + d` (monotone pieces, bisection). */\nfunction rootsInUnit(a: number, b: number, c: number, d: number, scale: number): number[] {\n\tconst f = (t: number) => ((a * t + b) * t + c) * t + d;\n\tconst tol = 1e-12 * Math.max(1, scale);\n\t// Critical points split [0, 1] into monotone pieces.\n\tconst cuts = [0];\n\tconst qa = 3 * a;\n\tconst qb = 2 * b;\n\tif (Math.abs(qa) > 1e-18) {\n\t\tconst disc = qb * qb - 4 * qa * c;\n\t\tif (disc >= 0) {\n\t\t\tconst r = Math.sqrt(disc);\n\t\t\tfor (const t of [(-qb - r) / (2 * qa), (-qb + r) / (2 * qa)].sort((x, y) => x - y)) if (t > 0 && t < 1) cuts.push(t);\n\t\t}\n\t} else if (Math.abs(qb) > 1e-18) {\n\t\tconst t = -c / qb;\n\t\tif (t > 0 && t < 1) cuts.push(t);\n\t}\n\tcuts.push(1);\n\tconst roots: number[] = [];\n\tconst push = (t: number) => {\n\t\tif (!roots.some((r) => Math.abs(r - t) < 1e-9)) roots.push(t);\n\t};\n\tfor (let i = 0; i < cuts.length - 1; i++) {\n\t\tlet lo = cuts[i];\n\t\tlet hi = cuts[i + 1];\n\t\tlet flo = f(lo);\n\t\tconst fhi = f(hi);\n\t\tif (Math.abs(flo) <= tol) push(lo);\n\t\tif (Math.abs(fhi) <= tol) push(hi);\n\t\tif (flo * fhi >= 0) continue;\n\t\tfor (let k = 0; k < 80; k++) {\n\t\t\tconst m = (lo + hi) / 2;\n\t\t\tconst fm = f(m);\n\t\t\tif (fm === 0) {\n\t\t\t\tlo = hi = m;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tif (fm * flo < 0) hi = m;\n\t\t\telse {\n\t\t\t\tlo = m;\n\t\t\t\tflo = fm;\n\t\t\t}\n\t\t}\n\t\tpush((lo + hi) / 2);\n\t}\n\treturn roots.sort((x, y) => x - y);\n}\n\n/** Where the line `p → q` crosses a segment: `s` on the line (0–1), `t` on the segment. Parallel overlaps are not crossings. */\nfunction lineHits(p: Point, q: Point, seg: readonly Point[]): { s: number; t: number; point: Point }[] {\n\tconst dx = q[0] - p[0];\n\tconst dy = q[1] - p[1];\n\tconst len2 = dx * dx + dy * dy;\n\tif (len2 < 1e-24) return [];\n\t// Signed distance (times |d|) of the segment from the line, as a polynomial in t.\n\tconst h = (pt: Point) => (pt[0] - p[0]) * -dy + (pt[1] - p[1]) * dx;\n\tlet coeffs: [number, number, number, number];\n\tif (seg.length === 2) coeffs = [0, 0, h(seg[1]) - h(seg[0]), h(seg[0])];\n\telse {\n\t\tconst [h0, h1, h2, h3] = seg.map(h);\n\t\tcoeffs = [-h0 + 3 * h1 - 3 * h2 + h3, 3 * h0 - 6 * h1 + 3 * h2, -3 * h0 + 3 * h1, h0];\n\t}\n\tif (coeffs.every((c) => Math.abs(c) < 1e-12 * Math.max(1, len2))) return [];\n\tconst scale = Math.sqrt(len2) * Math.max(1, ...seg.map((pt) => Math.abs(pt[0]) + Math.abs(pt[1])));\n\tconst out: { s: number; t: number; point: Point }[] = [];\n\tfor (const t of rootsInUnit(...coeffs, scale)) {\n\t\tconst point = segmentPoint(seg, t);\n\t\tconst s = ((point[0] - p[0]) * dx + (point[1] - p[1]) * dy) / len2;\n\t\tif (s >= -1e-9 && s <= 1 + 1e-9) out.push({ s: Math.min(1, Math.max(0, s)), t, point });\n\t}\n\treturn out;\n}\n\n// ---------------------------------------------------------------------------\n// Knife\n// ---------------------------------------------------------------------------\n\ninterface Hit {\n\t/** Knife position: segment index + parameter. */\n\ts: number;\n\tloop: number;\n\tseg: number;\n\tt: number;\n\tpoint: Point;\n}\n\nconst near = (a: Point, b: Point, eps: number) => Math.abs(a[0] - b[0]) <= eps && Math.abs(a[1] - b[1]) <= eps;\nconst degenerate = (seg: readonly Point[], eps: number) => seg.every((p) => near(p, seg[0], eps));\n\n/** The loop's pieces from (seg a, t a) forward to (seg b, t b); `full` goes all the way round when they coincide. */\nfunction arc(l: Loop, a: { seg: number; t: number }, b: { seg: number; t: number }, eps: number): { segs: Point[][]; chord: boolean[] } {\n\tconst n = l.segs.length;\n\tconst segs: Point[][] = [];\n\tconst chord: boolean[] = [];\n\tconst push = (k: number, t0: number, t1: number) => {\n\t\tconst piece = t0 <= 0 && t1 >= 1 ? l.segs[k].slice() : subSegment(l.segs[k], t0, t1);\n\t\tif (!degenerate(piece, eps)) {\n\t\t\tsegs.push(piece);\n\t\t\tchord.push(l.chord[k]);\n\t\t}\n\t};\n\tif (a.seg === b.seg && b.t >= a.t + 1e-12) {\n\t\tpush(a.seg, a.t, b.t);\n\t\treturn { segs, chord };\n\t}\n\tpush(a.seg, a.t, 1);\n\tfor (let k = (a.seg + 1) % n; k !== b.seg; k = (k + 1) % n) push(k, 0, 1);\n\tpush(b.seg, 0, b.t);\n\treturn { segs, chord };\n}\n\n/** Line segments through `points`. */\nfunction polySegs(points: readonly Point[], eps: number): Point[][] {\n\tconst out: Point[][] = [];\n\tfor (let i = 1; i < points.length; i++) if (!near(points[i - 1], points[i], eps)) out.push([points[i - 1], points[i]]);\n\treturn out;\n}\n\n/**\n * Cuts the filled path along the open polyline `knife`. Returns one path per resulting face\n * (an outline with its holes), or null when the knife crossed nothing from edge to edge. A\n * stretch of the knife that starts or ends inside the shape does not cut.\n */\nexport function knifePath(path: BezierPathInput, fillRule: FillRule, knife: readonly Point[]): BezierPath[] | null {\n\tconst pts = knife.filter((p) => Number.isFinite(p[0]) && Number.isFinite(p[1]));\n\tif (pts.length < 2) return null;\n\tlet faces = facesOf(path, fillRule);\n\tif (!faces.length) return null;\n\tconst b = bezierPathBounds(path);\n\tconst size = b ? Math.max(b.maxX - b.minX, b.maxY - b.minY, 1) : 1;\n\tconst eps = size * 1e-9;\n\tlet cursor = -Infinity;\n\tlet cuts = 0;\n\tfor (let guard = 0; guard < 512; guard++) {\n\t\tlet best: { face: number; from: Hit; to: Hit } | null = null;\n\t\tfaces.forEach((face, fi) => {\n\t\t\tconst hits: Hit[] = [];\n\t\t\tfor (let m = 0; m < pts.length - 1; m++) {\n\t\t\t\tif (m + 1 < cursor - 1e-9) continue;\n\t\t\t\tconst kb = { minX: Math.min(pts[m][0], pts[m + 1][0]), maxX: Math.max(pts[m][0], pts[m + 1][0]), minY: Math.min(pts[m][1], pts[m + 1][1]), maxY: Math.max(pts[m][1], pts[m + 1][1]) };\n\t\t\t\tface.loops.forEach((l, li) =>\n\t\t\t\t\tl.segs.forEach((seg, si) => {\n\t\t\t\t\t\tconst sb = segmentBounds(seg);\n\t\t\t\t\t\tif (sb.maxX < kb.minX - eps || sb.minX > kb.maxX + eps || sb.maxY < kb.minY - eps || sb.minY > kb.maxY + eps) return;\n\t\t\t\t\t\tfor (const h of lineHits(pts[m], pts[m + 1], seg)) {\n\t\t\t\t\t\t\tconst s = m + h.s;\n\t\t\t\t\t\t\tif (s >= cursor - 1e-9) hits.push({ s, loop: li, seg: si, t: h.t, point: h.point });\n\t\t\t\t\t\t}\n\t\t\t\t\t})\n\t\t\t\t);\n\t\t\t}\n\t\t\thits.sort((x, y) => x.s - y.s);\n\t\t\tconst unique = hits.filter((h, i) => i === 0 || h.s - hits[i - 1].s > 1e-9 || !near(h.point, hits[i - 1].point, eps * 10));\n\t\t\tconst inside = (s: number) => {\n\t\t\t\tconst m = Math.min(pts.length - 2, Math.floor(s));\n\t\t\t\tconst u = s - m;\n\t\t\t\tconst q: Point = [pts[m][0] + (pts[m + 1][0] - pts[m][0]) * u, pts[m][1] + (pts[m + 1][1] - pts[m][1]) * u];\n\t\t\t\treturn windingNumber(face.loops.map((l) => l.segs), q) !== 0;\n\t\t\t};\n\t\t\tfor (let i = 0; i < unique.length - 1; i++) {\n\t\t\t\tconst from = unique[i];\n\t\t\t\tconst to = unique[i + 1];\n\t\t\t\tif (near(from.point, to.point, eps * 10) || !inside((from.s + to.s) / 2)) continue;\n\t\t\t\tif (!best || from.s < best.from.s) best = { face: fi, from, to };\n\t\t\t\tbreak;\n\t\t\t}\n\t\t});\n\t\tif (!best) break;\n\t\tconst { face: fi, from, to } = best as { face: number; from: Hit; to: Hit };\n\t\tconst face = faces[fi];\n\t\t// The chord: the crossing points with the knife's corners between them.\n\t\tconst corners: Point[] = [from.point];\n\t\tfor (let m = Math.floor(from.s) + 1; m <= to.s - 1e-12 && m < pts.length; m++) if (m > from.s) corners.push(pts[m]);\n\t\tcorners.push(to.point);\n\t\tconst forward = polySegs(corners, eps);\n\t\tconst back = polySegs(corners.slice().reverse(), eps);\n\t\tconst la = face.loops[from.loop];\n\t\tconst loops = face.loops.filter((_, i) => i !== from.loop && i !== to.loop);\n\t\tif (from.loop === to.loop) {\n\t\t\tconst ab = arc(la, from, to, eps);\n\t\t\tconst ba = arc(la, to, from, eps);\n\t\t\tloops.push(\n\t\t\t\t{ segs: [...ab.segs, ...back], chord: [...ab.chord, ...back.map(() => true)] },\n\t\t\t\t{ segs: [...ba.segs, ...forward], chord: [...ba.chord, ...forward.map(() => true)] }\n\t\t\t);\n\t\t} else {\n\t\t\t// The chord joins two loops into one, with the chord on both sides of a zero-width slit.\n\t\t\tconst lb = face.loops[to.loop];\n\t\t\tconst roundA = arc(la, from, from, eps);\n\t\t\tconst roundB = arc(lb, to, to, eps);\n\t\t\tloops.push({\n\t\t\t\tsegs: [...roundA.segs, ...forward, ...roundB.segs, ...back],\n\t\t\t\tchord: [...roundA.chord, ...forward.map(() => true), ...roundB.chord, ...back.map(() => true)]\n\t\t\t});\n\t\t}\n\t\tfaces = [...faces.slice(0, fi), ...groupFaces(loops), ...faces.slice(fi + 1)];\n\t\tcursor = to.s;\n\t\tcuts++;\n\t}\n\treturn cuts ? faces.map(faceToPath) : null;\n}\n\n// ---------------------------------------------------------------------------\n// Eraser\n// ---------------------------------------------------------------------------\n\n/** The area a round eraser of diameter `width` covers along `points` (a disc for one point). */\nexport function eraserRegion(points: readonly Point[], width: number): BezierPath {\n\tconst pts = points.filter((p) => Number.isFinite(p[0]) && Number.isFinite(p[1]));\n\tconst r = width / 2;\n\tif (!pts.length || !(r > 0)) return [];\n\tconst moved = pts.some((p) => !near(p, pts[0], 1e-9));\n\tif (!moved) {\n\t\tconst [cx, cy] = pts[0];\n\t\tconst k = r * 0.5522847498307936;\n\t\treturn [\n\t\t\t{ type: 'M', x: cx, y: cy - r },\n\t\t\t{ type: 'C', x1: cx + k, y1: cy - r, x2: cx + r, y2: cy - k, x: cx + r, y: cy },\n\t\t\t{ type: 'C', x1: cx + r, y1: cy + k, x2: cx + k, y2: cy + r, x: cx, y: cy + r },\n\t\t\t{ type: 'C', x1: cx - k, y1: cy + r, x2: cx - r, y2: cy + k, x: cx - r, y: cy },\n\t\t\t{ type: 'C', x1: cx - r, y1: cy - k, x2: cx - k, y2: cy - r, x: cx, y: cy - r },\n\t\t\t{ type: 'Z' }\n\t\t];\n\t}\n\tconst line: BezierPath = [{ type: 'M', x: pts[0][0], y: pts[0][1] }, ...pts.slice(1).map((p) => ({ type: 'L' as const, x: p[0], y: p[1] }))];\n\treturn outlineStroke(line, { width, cap: 'round', join: 'round' });\n}\n\n/**\n * A filled path with `region` removed: one path per remaining face, or null when the region\n * does not overlap the fill.\n */\nexport function eraseFromFill(path: BezierPathInput, fillRule: FillRule, region: BezierPathInput): BezierPath[] | null {\n\tconst overlap = pathBoolean('intersection', [{ path, fillRule }, { path: region }]).path;\n\tif (!pathToContours(overlap).some((c) => Math.abs(contourSignedArea(closeContour(c, true))) > 1e-9)) return null;\n\tconst rest = pathBoolean('difference', [{ path, fillRule }, { path: region }]).path;\n\treturn splitIntoFaces(rest);\n}\n\n/**\n * The parts of a subpath's outline outside `region`, as open subpaths that keep the original\n * curves exactly; null when the outline does not enter the region. A closed subpath's last\n * and first parts join at its first anchor. With `keep: 'inside'` the parts inside the region are\n * kept instead (null when the outline never leaves it), as a clipping mask clips an open path.\n */\nexport function eraseFromOutline(sp: VectorSubpath, region: BezierPathInput, options: { keep?: 'outside' | 'inside'; fillRule?: FillRule } = {}): VectorSubpath[] | null {\n\tconst regionSegs = pathToContours(region).flatMap((c) => closeContour(c, true));\n\tif (!regionSegs.length) return null;\n\tconst rb = bezierPathBounds(region);\n\tconst count = subpathSegmentCount(sp);\n\tif (!rb || count === 0) return null;\n\tconst inside = options.keep === 'inside';\n\tconst removed = (p: Point) => pointInBezierPath(region, p, options.fillRule ?? 'nonzero') !== inside;\n\ttype Piece = { seg: number; t0: number; t1: number };\n\tconst runs: Piece[][] = [];\n\tlet cur: Piece[] = [];\n\tlet any = false;\n\tfor (let i = 0; i < count; i++) {\n\t\tconst seg = subpathSegment(sp, i);\n\t\tconst sb = segmentBounds(seg);\n\t\tconst ts = [0, 1];\n\t\tif (!(sb.maxX < rb.minX || sb.minX > rb.maxX || sb.maxY < rb.minY || sb.minY > rb.maxY)) {\n\t\t\tfor (const r of regionSegs) {\n\t\t\t\tconst b = segmentBounds(r);\n\t\t\t\tif (b.maxX < sb.minX || b.minX > sb.maxX || b.maxY < sb.minY || b.minY > sb.maxY) continue;\n\t\t\t\tfor (const hit of segmentIntersections(seg, r)) if (hit.ta > 1e-9 && hit.ta < 1 - 1e-9) ts.push(hit.ta);\n\t\t\t}\n\t\t}\n\t\tts.sort((a, b) => a - b);\n\t\tfor (let k = 0; k < ts.length - 1; k++) {\n\t\t\tconst t0 = ts[k];\n\t\t\tconst t1 = ts[k + 1];\n\t\t\tif (t1 - t0 < 1e-9) continue;\n\t\t\tif (removed(segmentPoint(seg, (t0 + t1) / 2))) {\n\t\t\t\tany = true;\n\t\t\t\tif (cur.length) runs.push(cur);\n\t\t\t\tcur = [];\n\t\t\t} else cur.push({ seg: i, t0, t1 });\n\t\t}\n\t}\n\tif (cur.length) runs.push(cur);\n\tif (!any) return null;\n\t// A closed path's last and first runs meet at anchor 0.\n\tif (sp.closed && runs.length >= 2) {\n\t\tconst first = runs[0][0];\n\t\tconst lastRun = runs[runs.length - 1];\n\t\tconst last = lastRun[lastRun.length - 1];\n\t\tif (first.seg === 0 && first.t0 === 0 && last.seg === count - 1 && last.t1 === 1) lastRun.push(...runs.shift()!);\n\t}\n\tconst out: VectorSubpath[] = [];\n\tfor (const run of runs) {\n\t\tconst anchors: VectorAnchor[] = [];\n\t\tfor (const { seg, t0, t1 } of run) {\n\t\t\tconst c = subSegment(subpathSegment(sp, seg), t0, t1);\n\t\t\tconst line = c.length === 2;\n\t\t\tconst start = c[0];\n\t\t\tconst end = c[c.length - 1];\n\t\t\tif (!anchors.length) anchors.push({ x: start[0], y: start[1] });\n\t\t\tif (!line) anchors[anchors.length - 1].out = { x: c[1][0], y: c[1][1] };\n\t\t\tconst next: VectorAnchor = { x: end[0], y: end[1] };\n\t\t\tif (!line) next.in = { x: c[2][0], y: c[2][1] };\n\t\t\tanchors.push(next);\n\t\t}\n\t\tif (anchors.length < 2) continue;\n\t\tfor (const a of anchors) {\n\t\t\tconst type = inferAnchorType(a);\n\t\t\tif (type !== 'corner') a.type = type;\n\t\t}\n\t\tout.push({ anchors, closed: false });\n\t}\n\treturn out;\n}\n\n/** Bounds of a point list (for picking the paths a knife or eraser stroke can reach). */\nexport function polylineBounds(points: readonly Point[], pad = 0): { x: number; y: number; width: number; height: number } | null {\n\tif (!points.length) return null;\n\tlet minX = Infinity;\n\tlet minY = Infinity;\n\tlet maxX = -Infinity;\n\tlet maxY = -Infinity;\n\tfor (const [x, y] of points) {\n\t\tminX = Math.min(minX, x);\n\t\tminY = Math.min(minY, y);\n\t\tmaxX = Math.max(maxX, x);\n\t\tmaxY = Math.max(maxY, y);\n\t}\n\treturn { x: minX - pad, y: minY - pad, width: maxX - minX + 2 * pad, height: maxY - minY + 2 * pad };\n}\n\n/** Ramer–Douglas–Peucker reduction of a polyline (keeps both ends). */\nexport function simplifyPolyline(points: readonly Point[], tolerance: number): Point[] {\n\tconst n = points.length;\n\tif (n < 3) return points.slice();\n\tconst keep = new Array<boolean>(n).fill(false);\n\tkeep[0] = keep[n - 1] = true;\n\tconst stack: [number, number][] = [[0, n - 1]];\n\twhile (stack.length) {\n\t\tconst [a, b] = stack.pop()!;\n\t\tconst [ax, ay] = points[a];\n\t\tconst dx = points[b][0] - ax;\n\t\tconst dy = points[b][1] - ay;\n\t\tconst len = Math.hypot(dx, dy);\n\t\tlet far = -1;\n\t\tlet farD = 0;\n\t\tfor (let i = a + 1; i < b; i++) {\n\t\t\tconst [px, py] = points[i];\n\t\t\tconst d = len < 1e-12 ? Math.hypot(px - ax, py - ay) : Math.abs((px - ax) * dy - (py - ay) * dx) / len;\n\t\t\tif (d > farD) {\n\t\t\t\tfarD = d;\n\t\t\t\tfar = i;\n\t\t\t}\n\t\t}\n\t\tif (far >= 0 && farD > tolerance) {\n\t\t\tkeep[far] = true;\n\t\t\tstack.push([a, far], [far, b]);\n\t\t}\n\t}\n\treturn points.filter((_, i) => keep[i]);\n}\n\n","/**\n * Visual filters of vector nodes: drop shadow, inner shadow, outer and inner glow, layer blur and\n * feather, drawn as one SVG `<filter>` per node (in the canvases and in SVG export alike).\n *\n * The filter takes everything the node draws (`SourceGraphic`) and its silhouette\n * (`SourceAlpha`) in the node's own space, and builds, in this order:\n *\n * 1. Inner shadows and inner glows, in stack order, over the body: the inverse of the silhouette\n * (offset for a shadow), grown by `spread` (which chokes the shadow inwards), blurred, coloured\n * and clipped to the silhouette.\n * 2. Feather: the body kept where the silhouette, eroded by half the radius and blurred by a\n * quarter of it, is, so the edge fades from about nothing at the outline to full strength\n * `radius` inside.\n * 3. Drop shadows and outer glows, in stack order, under the body: the silhouette grown by\n * `spread`, blurred, offset (shadows) and coloured.\n * 4. Layer blurs, over the whole result (shadows included).\n *\n * Blur radii are CSS / Figma blur radii: the Gaussian's standard deviation is half the radius, and\n * it reaches about 1.5 radii. Background blur needs the backdrop, which an SVG filter cannot read\n * (`BackgroundImage` was dropped from browsers) and which other SVG readers cannot either, so it is\n * left to the planned lens objects.\n *\n * The construction of feather, glows and inner shadows from blur, offset and clip follows\n * designcraft `crates/render/src/fx.rs` (`draw_item_fx`, `inner_edge`, `split`); the effect set,\n * defaults and reach follow figcraft `crates/doc/src/props.rs` (`EffectKind`, `Shadow`,\n * `Effect::reach`). Ported from ArtCraft (MIT OR Apache-2.0, © ArtCraft Team and contributors; see\n * THIRD_PARTY_NOTICES.md).\n */\nimport type { VectorEffectParamSpec } from './appearance.js';\nimport { VECTOR_FILTER_TYPES, type VectorBounds, type VectorFilter, type VectorFilterParamsMap, type VectorFilterType, type VectorNode } from './types.js';\n\n/** Default parameters of each filter type. */\nexport const VECTOR_FILTER_DEFAULTS: { readonly [K in VectorFilterType]: VectorFilterParamsMap[K] } = {\n\tdropShadow: { color: '#000000', opacity: 0.25, offsetX: 0, offsetY: 4, blur: 4, spread: 0 },\n\tinnerShadow: { color: '#000000', opacity: 0.25, offsetX: 0, offsetY: 4, blur: 4, spread: 0 },\n\touterGlow: { color: '#ffffbe', opacity: 0.75, blur: 10, spread: 0 },\n\tinnerGlow: { color: '#ffffbe', opacity: 0.75, blur: 10, spread: 0 },\n\tlayerBlur: { radius: 4 },\n\tfeather: { radius: 8 }\n};\n\nexport const VECTOR_FILTER_LABELS: Readonly<Record<VectorFilterType, string>> = {\n\tdropShadow: 'Drop Shadow',\n\tinnerShadow: 'Inner Shadow',\n\touterGlow: 'Outer Glow',\n\tinnerGlow: 'Inner Glow',\n\tlayerBlur: 'Layer Blur',\n\tfeather: 'Feather'\n};\n\n/** How a panel edits one filter parameter: an effect parameter spec, or a colour. */\nexport type VectorFilterParamSpec = VectorEffectParamSpec | { key: string; label: string; kind: 'color' };\n\nconst SHADOW_SPECS: VectorFilterParamSpec[] = [\n\t{ key: 'color', label: 'Color', kind: 'color' },\n\t{ key: 'opacity', label: 'Opacity', kind: 'number', min: 0, max: 1, step: 0.01, slider: true },\n\t{ key: 'offsetX', label: 'X', kind: 'number', min: -1000, max: 1000, step: 1 },\n\t{ key: 'offsetY', label: 'Y', kind: 'number', min: -1000, max: 1000, step: 1 },\n\t{ key: 'blur', label: 'Blur', kind: 'number', min: 0, max: 500, step: 1 },\n\t{ key: 'spread', label: 'Spread', kind: 'number', min: 0, max: 500, step: 1 }\n];\nconst GLOW_SPECS = SHADOW_SPECS.filter((s) => s.key !== 'offsetX' && s.key !== 'offsetY');\n\n/** The editable parameters of each filter type, in panel order. */\nexport const VECTOR_FILTER_PARAM_SPECS: Readonly<Record<VectorFilterType, readonly VectorFilterParamSpec[]>> = {\n\tdropShadow: SHADOW_SPECS,\n\tinnerShadow: SHADOW_SPECS.map((s) => (s.key === 'spread' ? { ...s, label: 'Choke' } : s)),\n\touterGlow: GLOW_SPECS,\n\tinnerGlow: GLOW_SPECS.map((s) => (s.key === 'spread' ? { ...s, label: 'Choke' } : s)),\n\tlayerBlur: [{ key: 'radius', label: 'Radius', kind: 'number', min: 0, max: 500, step: 1, slider: true }],\n\tfeather: [{ key: 'radius', label: 'Radius', kind: 'number', min: 0, max: 500, step: 1, slider: true }]\n};\n\nexport function isVectorFilterType(value: unknown): value is VectorFilterType {\n\treturn typeof value === 'string' && (VECTOR_FILTER_TYPES as readonly string[]).includes(value);\n}\n\n/**\n * Filter parameters with defaults (or `base`) filled in; values of the wrong type are dropped,\n * numbers clamped to their range, unknown keys ignored. Null for an unknown type.\n */\nexport function normalizeVectorFilterParams<K extends VectorFilterType>(type: K, params: Record<string, unknown> | null | undefined, base?: VectorFilterParamsMap[K]): VectorFilterParamsMap[K] | null {\n\tif (!isVectorFilterType(type)) return null;\n\tconst out: Record<string, unknown> = { ...VECTOR_FILTER_DEFAULTS[type], ...((base as Record<string, unknown> | undefined) ?? {}) };\n\tfor (const spec of VECTOR_FILTER_PARAM_SPECS[type]) {\n\t\tconst v = params?.[spec.key];\n\t\tif (v === undefined) continue;\n\t\tif (spec.kind === 'number' && typeof v === 'number' && Number.isFinite(v)) out[spec.key] = Math.min(spec.max ?? Infinity, Math.max(spec.min ?? -Infinity, v));\n\t\telse if (spec.kind === 'color' && typeof v === 'string' && v.trim()) out[spec.key] = v.trim();\n\t}\n\treturn out as VectorFilterParamsMap[K];\n}\n\n/** The parameter keys a filter type takes (for error messages). */\nexport function vectorFilterParamKeys(type: VectorFilterType): string[] {\n\treturn VECTOR_FILTER_PARAM_SPECS[type].map((s) => s.key);\n}\n\n/** A new filter of `type` (defaults merged with `params`), or null for an unknown type. */\nexport function createVectorFilter<K extends VectorFilterType>(type: K, id: string, params?: Partial<VectorFilterParamsMap[K]> | Record<string, unknown>): Extract<VectorFilter, { type: K }> | null {\n\tconst p = normalizeVectorFilterParams(type, params as Record<string, unknown>);\n\treturn p ? ({ id, type, params: p } as unknown as Extract<VectorFilter, { type: K }>) : null;\n}\n\n/**\n * Reads filters from untrusted data (JSON, agent input, SVG): unknown types and malformed entries\n * are dropped, parameters normalized, ids made unique.\n */\nexport function sanitizeVectorFilters(value: unknown): VectorFilter[] {\n\tif (!Array.isArray(value)) return [];\n\tconst out: VectorFilter[] = [];\n\tconst used = new Set<string>();\n\tfor (const raw of value) {\n\t\tif (!raw || typeof raw !== 'object') continue;\n\t\tconst r = raw as Record<string, unknown>;\n\t\tif (!isVectorFilterType(r.type)) continue;\n\t\tlet id = typeof r.id === 'string' && r.id && !used.has(r.id) ? r.id : '';\n\t\tfor (let k = out.length + 1; !id; k++) if (!used.has(`filter${k}`)) id = `filter${k}`;\n\t\tused.add(id);\n\t\tconst filter = createVectorFilter(r.type, id, (r.params as Record<string, unknown>) ?? {})!;\n\t\tout.push(r.enabled === false ? { ...filter, enabled: false } : filter);\n\t}\n\treturn out;\n}\n\n/** The node's filters that draw something (enabled, known, with a visible result). */\nexport function activeVectorFilters(node: Pick<VectorNode, 'filters'>): VectorFilter[] {\n\treturn (node.filters ?? []).filter((f) => {\n\t\tif (f.enabled === false || !isVectorFilterType(f.type)) return false;\n\t\tif (f.type === 'layerBlur' || f.type === 'feather') return f.params.radius > 0;\n\t\treturn f.params.opacity > 0;\n\t});\n}\n\n/** How far a node's filters can paint past what it draws, in its own units. */\nexport function vectorFilterReach(filters: readonly VectorFilter[]): number {\n\tlet outer = 0;\n\tlet blur = 0;\n\tfor (const f of filters) {\n\t\tswitch (f.type) {\n\t\t\tcase 'dropShadow':\n\t\t\tcase 'innerShadow':\n\t\t\t\touter = Math.max(outer, Math.max(Math.abs(f.params.offsetX), Math.abs(f.params.offsetY)) + f.params.blur * 1.5 + f.params.spread);\n\t\t\t\tbreak;\n\t\t\tcase 'outerGlow':\n\t\t\tcase 'innerGlow':\n\t\t\t\touter = Math.max(outer, f.params.blur * 1.5 + f.params.spread);\n\t\t\t\tbreak;\n\t\t\tcase 'layerBlur':\n\t\t\t\tblur += f.params.radius * 1.5;\n\t\t\t\tbreak;\n\t\t}\n\t}\n\treturn outer + blur;\n}\n\n/** One SVG filter primitive as data: a tag (`feGaussianBlur`, …), its attributes and children. */\nexport interface VectorFilterPrimitive {\n\ttag: string;\n\tattrs: Readonly<Record<string, string | number>>;\n\tchildren?: VectorFilterPrimitive[];\n}\n\n/**\n * A node's filter as data: draw `<filter id filterUnits=\"userSpaceOnUse\" x y width height\n * color-interpolation-filters=\"sRGB\">` with the primitives inside, and reference it with\n * `filter=\"url(#id)\"` on the node's element. The region is in the node's own space.\n */\nexport interface VectorRenderFilter {\n\tid: string;\n\tx: number;\n\ty: number;\n\twidth: number;\n\theight: number;\n\tprimitives: VectorFilterPrimitive[];\n}\n\nconst round = (n: number) => Math.round(n * 1000) / 1000;\nconst fe = (tag: string, attrs: Record<string, string | number>, children?: VectorFilterPrimitive[]): VectorFilterPrimitive => ({ tag, attrs, ...(children ? { children } : {}) });\n\n/**\n * The SVG filter for `filters` over a node whose drawing covers `bounds` (its own space, strokes\n * included), or null when none of them draws.\n */\nexport function vectorFilterSvg(filters: readonly VectorFilter[], id: string, bounds: VectorBounds | null): VectorRenderFilter | null {\n\tconst active = filters.filter((f) => activeVectorFilters({ filters: [f] }).length);\n\tif (!active.length || !bounds) return null;\n\tconst primitives: VectorFilterPrimitive[] = [];\n\tlet body = 'SourceGraphic';\n\tlet n = 0;\n\tconst name = (part: string) => `${part}${n}`;\n\t// Inner shadows and glows, over the body and clipped to the silhouette.\n\tfor (const f of active) {\n\t\tif (f.type !== 'innerShadow' && f.type !== 'innerGlow') continue;\n\t\tn++;\n\t\tconst p = f.params;\n\t\tprimitives.push(fe('feComponentTransfer', { in: 'SourceAlpha', result: name('inv') }, [fe('feFuncA', { type: 'table', tableValues: '1 0' })]));\n\t\tlet last = name('inv');\n\t\tif (f.type === 'innerShadow' && (f.params.offsetX || f.params.offsetY)) {\n\t\t\tprimitives.push(fe('feOffset', { in: last, dx: round(f.params.offsetX), dy: round(f.params.offsetY), result: name('off') }));\n\t\t\tlast = name('off');\n\t\t}\n\t\tif (p.spread > 0) {\n\t\t\tprimitives.push(fe('feMorphology', { in: last, operator: 'dilate', radius: round(p.spread), result: name('grow') }));\n\t\t\tlast = name('grow');\n\t\t}\n\t\tif (p.blur > 0) {\n\t\t\tprimitives.push(fe('feGaussianBlur', { in: last, stdDeviation: round(p.blur / 2), result: name('blur') }));\n\t\t\tlast = name('blur');\n\t\t}\n\t\tprimitives.push(fe('feFlood', { 'flood-color': p.color, 'flood-opacity': round(p.opacity), result: name('color') }));\n\t\tprimitives.push(fe('feComposite', { in: name('color'), in2: last, operator: 'in', result: name('tint') }));\n\t\tprimitives.push(fe('feComposite', { in: name('tint'), in2: 'SourceAlpha', operator: 'in', result: name('inner') }));\n\t\tprimitives.push(fe('feComposite', { in: name('inner'), in2: body, operator: 'over', result: name('body') }));\n\t\tbody = name('body');\n\t}\n\t// Feather: keep the body where the eroded, blurred silhouette is.\n\tfor (const f of active) {\n\t\tif (f.type !== 'feather') continue;\n\t\tn++;\n\t\tconst r = f.params.radius;\n\t\tprimitives.push(fe('feMorphology', { in: 'SourceAlpha', operator: 'erode', radius: round(r / 2), result: name('core') }));\n\t\tprimitives.push(fe('feGaussianBlur', { in: name('core'), stdDeviation: round(r / 4), result: name('fade') }));\n\t\tprimitives.push(fe('feComposite', { in: body, in2: name('fade'), operator: 'in', result: name('body') }));\n\t\tbody = name('body');\n\t}\n\t// Drop shadows and outer glows, under the body.\n\tconst under: string[] = [];\n\tfor (const f of active) {\n\t\tif (f.type !== 'dropShadow' && f.type !== 'outerGlow') continue;\n\t\tn++;\n\t\tconst p = f.params;\n\t\tlet last = 'SourceAlpha';\n\t\tif (p.spread > 0) {\n\t\t\tprimitives.push(fe('feMorphology', { in: last, operator: 'dilate', radius: round(p.spread), result: name('grow') }));\n\t\t\tlast = name('grow');\n\t\t}\n\t\tif (p.blur > 0) {\n\t\t\tprimitives.push(fe('feGaussianBlur', { in: last, stdDeviation: round(p.blur / 2), result: name('blur') }));\n\t\t\tlast = name('blur');\n\t\t}\n\t\tif (f.type === 'dropShadow' && (f.params.offsetX || f.params.offsetY)) {\n\t\t\tprimitives.push(fe('feOffset', { in: last, dx: round(f.params.offsetX), dy: round(f.params.offsetY), result: name('off') }));\n\t\t\tlast = name('off');\n\t\t}\n\t\tprimitives.push(fe('feFlood', { 'flood-color': p.color, 'flood-opacity': round(p.opacity), result: name('color') }));\n\t\tprimitives.push(fe('feComposite', { in: name('color'), in2: last, operator: 'in', result: name('shadow') }));\n\t\tunder.push(name('shadow'));\n\t}\n\tif (under.length) {\n\t\tn++;\n\t\tprimitives.push(fe('feMerge', { result: name('merged') }, [...under, body].map((i) => fe('feMergeNode', { in: i }))));\n\t\tbody = name('merged');\n\t}\n\t// Layer blurs, over everything.\n\tfor (const f of active) {\n\t\tif (f.type !== 'layerBlur') continue;\n\t\tn++;\n\t\tprimitives.push(fe('feGaussianBlur', { in: body, stdDeviation: round(f.params.radius / 2), result: name('body') }));\n\t\tbody = name('body');\n\t}\n\t// The last primitive is the filter's result; make sure it is the body.\n\tconst lastResult = primitives[primitives.length - 1]?.attrs.result;\n\tif (lastResult !== body) primitives.push(fe('feMerge', {}, [fe('feMergeNode', { in: body })]));\n\tconst pad = vectorFilterReach(active) + 2;\n\treturn {\n\t\tid,\n\t\tx: round(bounds.x - pad),\n\t\ty: round(bounds.y - pad),\n\t\twidth: round(bounds.width + 2 * pad),\n\t\theight: round(bounds.height + 2 * pad),\n\t\tprimitives\n\t};\n}\n\nconst escapeAttr = (value: string) => value.replace(/&/g, '&amp;').replace(/\"/g, '&quot;').replace(/</g, '&lt;').replace(/>/g, '&gt;');\n\nfunction primitiveMarkup(p: VectorFilterPrimitive): string {\n\tconst attrs = Object.entries(p.attrs)\n\t\t.map(([k, v]) => ` ${k}=\"${escapeAttr(String(v))}\"`)\n\t\t.join('');\n\treturn p.children?.length ? `<${p.tag}${attrs}>${p.children.map(primitiveMarkup).join('')}</${p.tag}>` : `<${p.tag}${attrs}/>`;\n}\n\n/** A render filter as SVG markup (`extra` is added to the `<filter>` element's attributes). */\nexport function vectorFilterMarkup(filter: VectorRenderFilter, extra = ''): string {\n\treturn `<filter id=\"${escapeAttr(filter.id)}\" filterUnits=\"userSpaceOnUse\" x=\"${filter.x}\" y=\"${filter.y}\" width=\"${filter.width}\" height=\"${filter.height}\" color-interpolation-filters=\"sRGB\"${extra}>${filter.primitives.map(primitiveMarkup).join('')}</filter>`;\n}\n\n/** Labels of the filter types, for menus. */\nexport const VECTOR_FILTER_MENU: readonly { type: VectorFilterType; label: string }[] = VECTOR_FILTER_TYPES.map((type) => ({ type, label: VECTOR_FILTER_LABELS[type] }));\n","/**\n * Masks and clipping. A group with `mask` set is a mask group: its first (bottom) child is the\n * mask and the children above it (the contents) show only where the mask lets them.\n *\n * - `clip`: a clipping mask, by the mask's outline (every path inside it, filled by its own fill\n * rule, whatever its paint; the mask's paint is not drawn). Drawn as an SVG `<clipPath>`.\n * - `alpha` / `luminance`: an opacity mask, by the mask's drawn alpha or its brightness (times its\n * alpha). Drawn as an SVG `<mask>` holding the mask as drawn (`mask-type=\"alpha\"` for alpha).\n * - `invert` swaps what shows and what hides. An inverted clip is the even-odd clip of a large\n * rectangle with the mask's outline (its boolean union) cut out of it, as pdfcraft's redaction\n * clips content out of a region; an inverted opacity mask draws the mask through a colour\n * matrix filter that turns its alpha (or brightness) upside down.\n *\n * Geometry uses the masked result: the contents' shapes clipped by the mask's region (its outline\n * for clips, its painted area for opacity masks) with our booleans, open paths cut where they\n * cross it. Bounds, hit-testing, snapping, outlines, booleans and the Pathfinder all read it\n * through `vectorAppearanceShapes`. An opacity mask is hit and bounded by where it paints at all,\n * not by how strongly: a dark luminance mask still counts.\n *\n * A hidden mask child turns the mask off and the contents draw whole (figcraft\n * `crates/doc/src/geometry.rs`: a hidden mask doesn't clip). The group's own opacity, blend mode\n * and filters apply after masking (its drop shadow follows the masked silhouette), and its path\n * effects act on the contents only, not on the mask.\n *\n * Extension point for lens objects: a lens is a shape that changes what is beneath it (blur,\n * magnify, recolour). It will reuse this module's pieces rather than the mask group model: the\n * region of a shape (`vectorMaskRegionShapes` with the lens as the source) clips a filtered copy\n * of the backdrop the way `vectorMaskRenderData` clips the contents, and hit-testing and bounds\n * stay those of the lens shape itself. See `VectorMaskRenderData` for where a renderer draws it.\n *\n * The mask model (`is_mask`, `MaskType`: alpha, vector, luminance; hidden masks off) follows\n * figcraft `crates/doc/src/node.rs` and `geometry.rs`; clipping a node's drawing to a shape layer\n * by layer follows designcraft `crates/render/src/fx.rs` (`push_clip_layer` around each body); the\n * inverted clip follows pdfcraft `crates/redact/src/interp.rs` (`clip_out`). Ported from ArtCraft\n * (MIT OR Apache-2.0, © ArtCraft Team and contributors; see THIRD_PARTY_NOTICES.md).\n */\nimport { bezierPathBounds, bezierPathToSvg, distanceToBezierPath, transformBezierPath, pointInBezierPath, type AffineMatrix, type BezierPath } from '../canvas/pathops/bezier.js';\nimport { pathBoolean } from '../canvas/pathops/boolean.js';\nimport { IDENTITY_MATRIX, isIdentityMatrix, multiplyMatrices } from '../geom/affine.js';\nimport { isVectorFrame, vectorFrameDrawn } from './frames.js';\nimport { applyVectorEffects, expandVectorAppearance, vectorAppearanceNodes, vectorAppearanceShapes, vectorChildAppearanceShapes, type VectorAppearanceShape } from './appearance.js';\nimport { bezierToSubpaths, hitTestVectorNode, nodeMatrix, subpathsToBezier, unionBounds, vectorNodeBounds } from './geometry.js';\nimport { vectorPaintLayerNodes, vectorStrokeStackReach } from './paintLayers.js';\nimport { eraseFromOutline } from './pathCut.js';\nimport { vectorStrokeOutlinePath } from './stroke.js';\nimport { activeVectorFilters, vectorFilterReach, type VectorFilterPrimitive, type VectorRenderFilter } from './filters.js';\nimport { VECTOR_MASK_TYPES, type VectorBounds, type VectorFillRule, type VectorGroupNode, type VectorMask, type VectorMaskType, type VectorNode, type Vec2 } from './types.js';\n\n/** A group whose `mask` takes effect (not a blend or live boolean, with a child to be the mask). */\nexport type VectorMaskGroup = VectorGroupNode & { mask: VectorMask };\n\n/** Whether `value` is a mask type. */\nexport function isVectorMaskType(value: unknown): value is VectorMaskType {\n\treturn typeof value === 'string' && (VECTOR_MASK_TYPES as readonly string[]).includes(value);\n}\n\n/** Reads mask settings from untrusted data (JSON, agent input, SVG data attributes); null when invalid. */\nexport function sanitizeVectorMask(value: unknown): VectorMask | null {\n\tif (!value || typeof value !== 'object') return null;\n\tconst r = value as Record<string, unknown>;\n\tif (!isVectorMaskType(r.type)) return null;\n\treturn r.invert === true ? { type: r.type, invert: true } : { type: r.type };\n}\n\n/** Whether a node is a mask group: a group with `mask`, at least one child, and not a blend or live boolean. */\nexport function isVectorMaskGroup(node: VectorNode | null | undefined): node is VectorMaskGroup {\n\treturn node?.type === 'group' && !!node.mask && isVectorMaskType(node.mask.type) && !node.blend && !node.liveBoolean && node.children.length > 0;\n}\n\n/** Whether a mask group's mask is on: its mask child is visible. */\nexport function isVectorMaskActive(node: VectorNode | null | undefined): node is VectorMaskGroup {\n\treturn isVectorMaskGroup(node) && node.children[0].visible !== false;\n}\n\n/** A mask group's mask (its first child), or null. */\nexport function vectorMaskSource(node: VectorNode | null | undefined): VectorNode | null {\n\treturn isVectorMaskGroup(node) ? node.children[0] : null;\n}\n\n/** The children a mask group masks (all but the first); a plain group's children. */\nexport function vectorMaskContents(group: VectorGroupNode): VectorNode[] {\n\treturn isVectorMaskGroup(group) ? group.children.slice(1) : group.children;\n}\n\n/** The mask group whose mask is `id`, or null. */\nexport function vectorMaskOwner(nodes: readonly VectorNode[], id: string): VectorMaskGroup | null {\n\tfor (const n of nodes) {\n\t\tif (n.type !== 'group') continue;\n\t\tif (isVectorMaskGroup(n) && n.children[0].id === id) return n;\n\t\tconst inner = vectorMaskOwner(n.children, id);\n\t\tif (inner) return inner;\n\t}\n\treturn null;\n}\n\n/** What agents and panels read about a mask group. */\nexport interface VectorMaskSummary {\n\ttype: VectorMaskType;\n\tinvert: boolean;\n\t/** Id of the mask (the group's first child). */\n\tmaskId: string;\n\t/** Ids of the masked contents, bottom to top. */\n\tcontents: string[];\n\t/** False while the mask child is hidden (the contents draw whole). */\n\tenabled: boolean;\n}\n\n/** A mask group's settings, mask and contents, or null for any other node. */\nexport function vectorMaskSummary(node: VectorNode | null | undefined): VectorMaskSummary | null {\n\tif (!isVectorMaskGroup(node)) return null;\n\treturn {\n\t\ttype: node.mask.type,\n\t\tinvert: !!node.mask.invert,\n\t\tmaskId: node.children[0].id,\n\t\tcontents: node.children.slice(1).map((c) => c.id),\n\t\tenabled: node.children[0].visible !== false\n\t};\n}\n\n// ---------------------------------------------------------------------------\n// Regions\n// ---------------------------------------------------------------------------\n\n/** One shape of a mask's region: a path (in the mask group's own space) and the rule that fills it. */\nexport interface VectorMaskRegionShape {\n\tpath: BezierPath;\n\tfillRule: VectorFillRule;\n}\n\nconst place = (path: BezierPath, m: AffineMatrix) => (isIdentityMatrix(m) ? path : transformBezierPath(path, m));\n\n/**\n * The area `node` covers as a mask of `type`, in the space `parent` maps it to: for a clip, the\n * outline of every visible path inside it (effects applied), whatever its paint; for an opacity\n * mask, where it paints (drawn fills, and drawn strokes as their outlines). A nested mask group\n * covers its masked result. `self` counts the node even when hidden (the mask itself).\n */\nexport function vectorMaskRegionShapes(node: VectorNode, type: VectorMaskType, parent: AffineMatrix = IDENTITY_MATRIX, self = true): VectorMaskRegionShape[] {\n\tif (!self && node.visible === false) return [];\n\t// A frame covers what it draws: its fill and its children, clipped to its rectangle.\n\tif (isVectorFrame(node)) node = vectorFrameDrawn(node);\n\tconst m = multiplyMatrices(nodeMatrix(node), parent);\n\tif (isVectorMaskActive(node) || (node.type === 'group' && node.effects?.length)) {\n\t\t// Drawn as shapes: a nested mask's masked result, or a group's effects applied.\n\t\treturn vectorAppearanceShapes(node).flatMap((s) => regionOfPath(s.path, s.source, type, m));\n\t}\n\tconst drawn = expandVectorAppearance(node);\n\tif (drawn.type === 'group') {\n\t\tconst inner = multiplyMatrices(nodeMatrix(drawn), parent);\n\t\treturn drawn.children.flatMap((c) => vectorMaskRegionShapes(c, type, inner, false));\n\t}\n\treturn regionOfPath(subpathsToBezier(drawn.subpaths), drawn, type, m);\n}\n\nfunction regionOfPath(path: BezierPath, style: VectorNode & { type: 'path' }, type: VectorMaskType, m: AffineMatrix): VectorMaskRegionShape[] {\n\tif (!path.length) return [];\n\tconst fillRule = style.fillRule ?? 'nonzero';\n\tif (type === 'clip') return [{ path: place(path, m), fillRule }];\n\tconst out: VectorMaskRegionShape[] = [];\n\tlet filled = false;\n\tfor (const l of vectorPaintLayerNodes(style)) {\n\t\tif (!l.drawn) continue;\n\t\tif (l.kind === 'fill') {\n\t\t\tif (!filled) out.push({ path: place(path, m), fillRule });\n\t\t\tfilled = true;\n\t\t} else if ((l.node.strokeWidth ?? 1) > 0) {\n\t\t\tconst area = vectorStrokeOutlinePath(path, l.node);\n\t\t\tif (area.length) out.push({ path: place(area, m), fillRule: 'nonzero' });\n\t\t}\n\t}\n\treturn out;\n}\n\nconst regionCache = new WeakMap<VectorMaskGroup, VectorMaskRegionShape[]>();\n\n/** The region of a mask group's mask in the group's own space (not inverted). Cached per group object. */\nexport function vectorMaskRegion(group: VectorMaskGroup): VectorMaskRegionShape[] {\n\tlet hit = regionCache.get(group);\n\tif (!hit) {\n\t\thit = vectorMaskRegionShapes(group.children[0], group.mask.type);\n\t\tregionCache.set(group, hit);\n\t}\n\treturn hit;\n}\n\nconst unionCache = new WeakMap<VectorMaskGroup, BezierPath>();\n\n/** The mask's region as one clean path (a boolean union, read nonzero or even-odd alike). Cached per group object. */\nexport function vectorMaskRegionPath(group: VectorMaskGroup): BezierPath {\n\tlet hit = unionCache.get(group);\n\tif (!hit) {\n\t\tconst shapes = vectorMaskRegion(group);\n\t\thit = !shapes.length ? [] : shapes.length === 1 && shapes[0].fillRule === 'nonzero' ? shapes[0].path : pathBoolean('union', shapes.map((s) => ({ path: s.path, fillRule: s.fillRule }))).path;\n\t\tunionCache.set(group, hit);\n\t}\n\treturn hit;\n}\n\n/** Whether a point (in the group's own space) is inside the mask's region, `tolerance` past its edge counting. */\nfunction inRegion(group: VectorMaskGroup, p: Vec2, tolerance: number): boolean {\n\tconst pt: [number, number] = [p.x, p.y];\n\tfor (const s of vectorMaskRegion(group)) {\n\t\tif (pointInBezierPath(s.path, pt, s.fillRule)) return true;\n\t\tif (tolerance > 0 && distanceToBezierPath(s.path, pt) <= tolerance) return true;\n\t}\n\treturn false;\n}\n\n/**\n * Whether a mask group's mask lets point `p` (the group's own space) through: inside its region,\n * or outside it when inverted. `tolerance` widens what counts as through (its edge, either way).\n * Always true while the mask is off.\n */\nexport function vectorMaskContains(group: VectorMaskGroup, p: Vec2, tolerance = 0): boolean {\n\tif (!isVectorMaskActive(group)) return true;\n\tif (group.mask.type !== 'clip') {\n\t\t// Opacity masks: where the mask paints, by its own hit-test (strokes, alignment, arrowheads).\n\t\tconst source = group.children[0];\n\t\tconst hit = hitTestVectorNode(source.visible === false ? { ...source, visible: true } : source, p, group.mask.invert ? 0 : tolerance);\n\t\treturn group.mask.invert ? !hit || (tolerance > 0 && hitNearEdge(group, p, tolerance)) : hit;\n\t}\n\tif (!group.mask.invert) return inRegion(group, p, tolerance);\n\treturn !inRegion(group, p, 0) || hitNearEdge(group, p, tolerance);\n}\n\nfunction hitNearEdge(group: VectorMaskGroup, p: Vec2, tolerance: number): boolean {\n\tif (tolerance <= 0) return false;\n\treturn vectorMaskRegion(group).some((s) => distanceToBezierPath(s.path, [p.x, p.y]) <= tolerance);\n}\n\n// ---------------------------------------------------------------------------\n// Masked shapes\n// ---------------------------------------------------------------------------\n\n/** A path's open subpaths cut by the region (kept inside it, or outside when inverted). */\nfunction clipOpen(path: BezierPath, region: BezierPath, invert: boolean): BezierPath {\n\tconst out: BezierPath = [];\n\tfor (const sp of bezierToSubpaths(path)) {\n\t\tconst pieces = eraseFromOutline(sp, region, { keep: invert ? 'outside' : 'inside' });\n\t\t// Null: the outline never crosses the region's edge, so it is all in or all out.\n\t\tif (pieces === null) {\n\t\t\tconst a = sp.anchors[0];\n\t\t\tconst inside = !!a && pointInBezierPath(region, [a.x, a.y], 'nonzero');\n\t\t\tif (inside !== invert) out.push(...subpathsToBezier([sp]));\n\t\t} else out.push(...subpathsToBezier(pieces));\n\t}\n\treturn out;\n}\n\n/** A shape's path clipped by the mask's region: booleans for its closed contours, cuts for its open ones. */\nfunction clipShapePath(path: BezierPath, fillRule: VectorFillRule, region: BezierPath, invert: boolean): BezierPath {\n\tconst subpaths = bezierToSubpaths(path);\n\tconst closed = subpaths.filter((sp) => sp.closed);\n\tconst open = subpaths.filter((sp) => !sp.closed);\n\tconst out: BezierPath = [];\n\tif (closed.length) {\n\t\tconst operands = [{ path: subpathsToBezier(closed), fillRule }, { path: region, fillRule: 'nonzero' as const }];\n\t\tout.push(...(region.length ? pathBoolean(invert ? 'difference' : 'intersection', operands).path : invert ? operands[0].path : []));\n\t}\n\tif (open.length) out.push(...(region.length ? clipOpen(subpathsToBezier(open), region, invert) : invert ? subpathsToBezier(open) : []));\n\treturn out;\n}\n\n/**\n * What a mask group draws as shapes in its own space: its contents' shapes (their own effects\n * applied, then the group's), each clipped by the mask's region. The appearance code calls this\n * for mask groups (`vectorAppearanceShapes`), so use that instead (it caches).\n */\nexport function vectorMaskedShapes(group: VectorMaskGroup): VectorAppearanceShape[] {\n\tconst contents = group.children.flatMap((c, i) => (i === 0 ? [] : vectorChildAppearanceShapes(c, i)));\n\tconst shapes = applyVectorEffects(contents, group.effects);\n\tif (!isVectorMaskActive(group)) return shapes;\n\tconst region = vectorMaskRegionPath(group);\n\tconst invert = !!group.mask.invert;\n\tconst out: VectorAppearanceShape[] = [];\n\tfor (const s of shapes) {\n\t\tconst path = clipShapePath(s.path, s.source.fillRule ?? 'nonzero', region, invert);\n\t\t// Keep the shape's evaluated paths in the clip's clean nonzero form.\n\t\tif (path.length) out.push({ ...s, path, source: s.source.fillRule === 'evenodd' ? { ...s.source, fillRule: 'nonzero' } : s.source });\n\t}\n\treturn out;\n}\n\n/**\n * The node with every working mask group inside it replaced by a plain group of its masked shapes\n * (ids `<group id>~fx<n>`, placement kept): the geometry booleans, the Pathfinder, the Shape\n * Builder and the paint bucket work with. The node itself when it holds no mask.\n */\nexport function vectorMaskedGeometry(node: VectorNode): VectorNode {\n\tif (node.type !== 'group') return node;\n\tif (isVectorMaskActive(node)) {\n\t\treturn {\n\t\t\tid: node.id,\n\t\t\ttype: 'group',\n\t\t\t...(node.transform ? { transform: node.transform } : {}),\n\t\t\t...(node.opacity !== undefined ? { opacity: node.opacity } : {}),\n\t\t\t...(node.visible === false ? { visible: false } : {}),\n\t\t\t...(node.locked ? { locked: true } : {}),\n\t\t\tchildren: vectorAppearanceNodes(node)\n\t\t};\n\t}\n\tlet changed = false;\n\tconst children = node.children.map((c) => {\n\t\tconst next = vectorMaskedGeometry(c);\n\t\tif (next !== c) changed = true;\n\t\treturn next;\n\t});\n\treturn changed ? { ...node, children } : node;\n}\n\n/** Bounds of a mask group's masked result in its own space (stroke widths not included), or null. */\nexport function vectorMaskedLocalBounds(group: VectorMaskGroup): VectorBounds | null {\n\tconst b = bezierPathBounds(vectorAppearanceShapes(group).flatMap((s) => s.path));\n\treturn b ? { x: b.minX, y: b.minY, width: b.maxX - b.minX, height: b.maxY - b.minY } : null;\n}\n\n// ---------------------------------------------------------------------------\n// Render data\n// ---------------------------------------------------------------------------\n\n/** How far anything inside a node draws past its geometry: strokes, and filters on the way down. */\nfunction paintReach(node: VectorNode): number {\n\tconst own = vectorFilterReach(activeVectorFilters(node));\n\tif (node.type === 'path') return own + vectorStrokeStackReach(node);\n\tif (node.type === 'text' || node.type === 'instance') return own + paintReach(expandVectorAppearance(node));\n\treturn own + Math.max(0, ...node.children.map(paintReach));\n}\n\n/**\n * The box a mask group's contents can draw over, in its own space (strokes and filters included,\n * with a margin): the `<mask>` region, the filter region of an inverted opacity mask and the\n * rectangle an inverted clip cuts the mask out of. Null without contents.\n */\nexport function vectorMaskContentBounds(group: VectorMaskGroup): VectorBounds | null {\n\tconst contents = group.children.slice(1);\n\tconst b = unionBounds(contents.map((c) => vectorNodeBounds(c, IDENTITY_MATRIX)));\n\tif (!b) return null;\n\tconst pad = Math.max(0, ...contents.map(paintReach)) + Math.max(b.width, b.height) * 0.05 + 4;\n\treturn { x: b.x - pad, y: b.y - pad, width: b.width + 2 * pad, height: b.height + 2 * pad };\n}\n\n/** One path of a clipping mask's `<clipPath>` (group space). */\nexport interface VectorMaskClipShape {\n\td: string;\n\tclipRule: VectorFillRule;\n}\n\n/**\n * How to draw a mask group's mask, in the group's own space. Draw the group's own `<g>` (transform,\n * opacity, blend mode, filter) holding an inner `<g>` with the contents, referencing:\n * - `clip`: a `<clipPath id>` holding each of `clip` as `<path d clip-rule>`;\n * - `alpha` / `luminance`: a `<mask id maskUnits=\"userSpaceOnUse\" x y width height>` over\n * `bounds` (with `mask-type=\"alpha\"` for alpha) holding the mask node as drawn, wrapped in\n * `<g filter={filter}>` when `filter` is set (an inverted mask).\n */\nexport interface VectorMaskRenderData {\n\ttype: VectorMaskType;\n\tinvert: boolean;\n\t/** Id of the `<clipPath>` or `<mask>` element. */\n\tid: string;\n\t/** Clip shapes (clipping masks). An inverted clip is one even-odd shape: a rectangle with the mask's outline cut out. */\n\tclip?: VectorMaskClipShape[];\n\t/** Region of the `<mask>` (opacity masks). */\n\tbounds?: VectorBounds;\n\t/** `url(#id)` of the inverting filter (inverted opacity masks; in `filters`). */\n\tfilter?: string;\n\t/** The inverting filter itself (inverted opacity masks). */\n\tinvertFilter?: VectorRenderFilter;\n}\n\nconst fe = (tag: string, attrs: Record<string, string | number>): VectorFilterPrimitive => ({ tag, attrs });\nconst LUMA = '-0.2125 -0.7154 -0.0721 0 1';\n\n/** The filter that inverts an opacity mask over `bounds`: alpha → 1 − alpha, or brightness → 1 − brightness over black. */\nfunction invertFilter(type: 'alpha' | 'luminance', id: string, bounds: VectorBounds): VectorRenderFilter {\n\tconst primitives =\n\t\ttype === 'alpha'\n\t\t\t? [fe('feColorMatrix', { in: 'SourceGraphic', type: 'matrix', values: '0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 -1 1' })]\n\t\t\t: [\n\t\t\t\t\t// Over black first, so a transparent area reads as dark (hidden) before inverting.\n\t\t\t\t\tfe('feFlood', { 'flood-color': '#000000', result: 'black' }),\n\t\t\t\t\tfe('feComposite', { in: 'SourceGraphic', in2: 'black', operator: 'over', result: 'flat' }),\n\t\t\t\t\tfe('feColorMatrix', { in: 'flat', type: 'matrix', values: `${LUMA} ${LUMA} ${LUMA} 0 0 0 0 1` })\n\t\t\t\t];\n\tconst r = (n: number) => Math.round(n * 1000) / 1000;\n\treturn { id, x: r(bounds.x), y: r(bounds.y), width: r(bounds.width), height: r(bounds.height), primitives };\n}\n\nconst rectPath = (b: VectorBounds): BezierPath => [\n\t{ type: 'M', x: b.x, y: b.y },\n\t{ type: 'L', x: b.x + b.width, y: b.y },\n\t{ type: 'L', x: b.x + b.width, y: b.y + b.height },\n\t{ type: 'L', x: b.x, y: b.y + b.height },\n\t{ type: 'Z' }\n];\n\n/**\n * A mask group's mask as render data with element id `id` (and `filterId` for an inverting\n * filter), or null when the mask is off or the group has no contents. Shared by the canvases and\n * SVG export.\n */\nexport function vectorMaskRenderData(group: VectorMaskGroup, id: string, filterId: string, precision = 3): VectorMaskRenderData | null {\n\tif (!isVectorMaskActive(group) || group.children.length < 2) return null;\n\tconst invert = !!group.mask.invert;\n\tconst bounds = vectorMaskContentBounds(group);\n\tif (group.mask.type === 'clip') {\n\t\tconst shapes = vectorMaskRegion(group);\n\t\tif (!invert) return { type: 'clip', invert, id, clip: shapes.map((s) => ({ d: bezierPathToSvg(s.path, { precision }), clipRule: s.fillRule })) };\n\t\t// Inverted (pdfcraft `clip_out`): a rectangle round the contents with the mask's union cut out, even-odd.\n\t\tconst box = bounds ?? { x: 0, y: 0, width: 0, height: 0 };\n\t\tconst region = vectorMaskRegionPath(group);\n\t\treturn { type: 'clip', invert, id, clip: [{ d: bezierPathToSvg([...rectPath(box), ...region], { precision }), clipRule: 'evenodd' }] };\n\t}\n\tif (!bounds) return null;\n\tif (!invert) return { type: group.mask.type, invert, id, bounds };\n\tconst filter = invertFilter(group.mask.type, filterId, bounds);\n\treturn { type: group.mask.type, invert, id, bounds, filter: `url(#${filterId})`, invertFilter: filter };\n}\n","// Portions ported from photocraft/crates/doc/src/text.rs (MIT OR Apache-2.0, © ArtCraft Team and contributors). See THIRD_PARTY_NOTICES.md.\n\n/**\n * Text layout shared by the image editor's type layers and the vector editor's text nodes: styled\n * runs, paragraphs, line breaking (at spaces and after break characters, and between wide CJK\n * characters), alignment and justification, tracking, leading, indents, spacing, baseline shift,\n * caret positions and hit testing. Everything that needs a font goes through a `TextShaper`, so\n * the same measurements give the same lines in every host.\n */\n\nimport type { BezierPath } from '../canvas/pathops/bezier';\nimport type { ParagraphRun, ParagraphStyle, TextAlign, TextFont, TextRect, TextShaper, TextStyle } from './types';\n\n/** What layout needs: the text, its character and paragraph runs and its frame. */\nexport interface TextBlock {\n text: string;\n runs: ReadonlyArray<{ length: number; style: TextStyle }>;\n paragraphs: readonly ParagraphRun[];\n /**\n * `point`: lines grow from the origin, one per paragraph; the first baseline is at y = 0, or one\n * ascent down with `origin: 'top'`. `box`: lines wrap inside `width` and the first baseline is one\n * ascent below the top (`height` bounds the layout's box; lines past it still lay out).\n */\n frame: { kind: 'point'; origin?: 'baseline' | 'top' } | { kind: 'box'; width: number; height: number };\n}\n\n// ---------------------------------------------------------------------------\n// Runs\n// ---------------------------------------------------------------------------\n\nexport const DEFAULT_TEXT_STYLE: TextStyle = { fontFamily: 'sans-serif', fontWeight: 400, fontSize: 24, color: '#000000' };\nexport const DEFAULT_AUTO_LEADING = 1.2;\n\nconst sameStyle = (a: object, b: object) => JSON.stringify(a) === JSON.stringify(b);\n\n/** Merges neighbouring runs with equal styles and drops empty ones. */\nfunction compact<R extends { length: number; style: object }>(runs: R[]): R[] {\n const out: R[] = [];\n for (const r of runs) {\n if (r.length <= 0) continue;\n const last = out[out.length - 1];\n if (last && sameStyle(last.style, r.style)) out[out.length - 1] = { ...last, length: last.length + r.length };\n else out.push({ ...r });\n }\n return out;\n}\n\n/** Runs fitted to a text of `length` (the last run stretches or is cut), never empty while there is text. */\nexport function fitRuns<R extends { length: number; style: object }>(runs: readonly R[], length: number, fallback: R['style']): R[] {\n const out: R[] = [];\n let left = length;\n for (const r of runs) {\n if (left <= 0) break;\n const n = Math.min(Math.max(0, Math.floor(r.length)), left);\n if (n > 0) out.push({ ...r, length: n });\n left -= n;\n }\n if (left > 0) {\n if (out.length) out[out.length - 1] = { ...out[out.length - 1], length: out[out.length - 1].length + left };\n else out.push({ length: left, style: runs[runs.length - 1]?.style ?? fallback } as R);\n }\n return compact(out);\n}\n\n/** The style of the run holding code unit `index` (the last run past the end). */\nexport function styleAt<S extends object>(runs: ReadonlyArray<{ length: number; style: S }>, index: number, fallback: S): S {\n let at = 0;\n for (const r of runs) {\n if (index < at + r.length) return r.style;\n at += r.length;\n }\n return runs[runs.length - 1]?.style ?? fallback;\n}\n\n/** Runs with `patch(style)` applied over [start, end). */\nexport function restyleRange<S extends object>(runs: ReadonlyArray<{ length: number; style: S }>, start: number, end: number, patch: (s: S) => S): Array<{ length: number; style: S }> {\n const out: Array<{ length: number; style: S }> = [];\n let at = 0;\n for (const r of runs) {\n const a = at;\n const b = at + r.length;\n at = b;\n const lo = Math.max(a, start);\n const hi = Math.min(b, end);\n if (hi <= lo) {\n out.push({ ...r });\n continue;\n }\n if (lo > a) out.push({ length: lo - a, style: r.style });\n out.push({ length: hi - lo, style: patch(r.style) });\n if (b > hi) out.push({ length: b - hi, style: r.style });\n }\n return compact(out);\n}\n\n/** Runs after replacing [start, end) of the text with `inserted` code units styled `style`. */\nexport function spliceRuns<S extends object>(runs: ReadonlyArray<{ length: number; style: S }>, start: number, end: number, inserted: number, style: S): Array<{ length: number; style: S }> {\n const out: Array<{ length: number; style: S }> = [];\n let at = 0;\n let placed = false;\n for (const r of runs) {\n const a = at;\n const b = at + r.length;\n at = b;\n if (b <= start) {\n out.push({ ...r });\n continue;\n }\n if (a < start) out.push({ length: start - a, style: r.style });\n if (!placed) {\n out.push({ length: inserted, style });\n placed = true;\n }\n if (b > end) out.push({ length: b - Math.max(end, a), style: r.style });\n }\n if (!placed) out.push({ length: inserted, style });\n return compact(out);\n}\n\n/** Paragraph ranges [start, end) of the text, the line break included in the paragraph it ends. */\nexport function paragraphRanges(text: string): Array<{ start: number; end: number; content: number }> {\n const out: Array<{ start: number; end: number; content: number }> = [];\n let start = 0;\n for (let i = 0; i < text.length; i++) {\n if (text[i] === '\\n') {\n out.push({ start, end: i + 1, content: i });\n start = i + 1;\n }\n }\n out.push({ start, end: text.length, content: text.length });\n return out;\n}\n\n/** Paragraph runs snapped to whole paragraphs: each paragraph takes the style at its start. */\nexport function fitParagraphRuns(runs: readonly ParagraphRun[], text: string): ParagraphRun[] {\n const fallback: ParagraphStyle = runs[0]?.style ?? {};\n const out = compact(paragraphRanges(text).map((p) => ({ length: p.end - p.start, style: styleAt(runs, p.start, fallback) })));\n return out.length ? out : [{ length: 0, style: fallback }];\n}\n\n\n// ---------------------------------------------------------------------------\n// Layout\n// ---------------------------------------------------------------------------\n\n/** One laid-out character. */\nexport interface LaidChar {\n /** Index in the text (UTF-16 code unit). */\n index: number;\n /** Text-space x of its start and its advance (tracking and justification included). */\n x: number;\n advance: number;\n}\n\n/** A run of characters on one line in one style. */\nexport interface LaidFragment {\n start: number;\n end: number;\n style: TextStyle;\n font: TextFont;\n /** The family the shaper draws it with. */\n family: string;\n x: number;\n /** Baseline in text space (baseline shift applied). */\n y: number;\n /** Per-character x positions relative to `x` (`end − start + 1` entries). */\n carets: number[];\n /** Whether characters are placed one by one (tracking or justification). */\n spaced: boolean;\n}\n\nexport interface LaidLine {\n start: number;\n /** End of the line's characters (line break and trailing spaces excluded from `width`). */\n end: number;\n baseline: number;\n ascent: number;\n descent: number;\n x: number;\n width: number;\n chars: LaidChar[];\n fragments: LaidFragment[];\n}\n\n/** A laid-out type layer in text space. */\nexport interface TextLayout {\n lines: LaidLine[];\n /** Bounds of the lines (ascent to descent), text space; the box for paragraph text. */\n bounds: TextRect;\n /** Families replaced by a fallback. */\n missingFonts: string[];\n}\n\nexport function fontOf(style: TextStyle): TextFont {\n const f: TextFont = { family: style.fontFamily, weight: style.fontWeight, italic: Boolean(style.italic), size: style.fontSize };\n if (style.postScriptName) f.postScriptName = style.postScriptName;\n return f;\n}\n\nconst isBreakAfter = (c: string) => c === ' ' || c === '\\t' || c === '-' || c === '‐' || c === '​';\n/** Whether a character is a space or tab (spaces hang at line ends and stretch when justifying). */\nexport const isTextSpace = (c: string) => c === ' ' || c === '\\t';\nconst isSpace = isTextSpace;\nconst isWide = (code: number) => (code >= 0x2e80 && code <= 0x9fff) || (code >= 0xac00 && code <= 0xd7af) || (code >= 0xf900 && code <= 0xfaff) || (code >= 0xff00 && code <= 0xffef);\n\ninterface ParaChar {\n index: number;\n ch: string;\n advance: number;\n style: TextStyle;\n}\n\nconst layoutCache = new WeakMap<object, Map<string, TextLayout>>();\n\n/** Lays out a type layer with `shaper` (memoised per layer object and shaper). */\nexport function layoutText(layer: TextBlock, shaper: TextShaper): TextLayout {\n let byShaper = layoutCache.get(layer);\n const hit = byShaper?.get(shaper.id);\n if (hit) return hit;\n const out = computeLayout(layer, shaper);\n if (!byShaper) {\n byShaper = new Map();\n layoutCache.set(layer, byShaper);\n }\n byShaper.set(shaper.id, out);\n return out;\n}\n\nfunction computeLayout(layer: TextBlock, shaper: TextShaper): TextLayout {\n const { text, frame } = layer;\n const runs = fitRuns(layer.runs, text.length, DEFAULT_TEXT_STYLE);\n const missing = new Set<string>();\n const resolved = new Map<string, string>();\n const familyOf = (font: TextFont) => {\n const key = `${font.family}|${font.weight}|${font.italic}|${font.postScriptName ?? ''}`;\n let fam = resolved.get(key);\n if (fam === undefined) {\n const r = shaper.resolve(font);\n fam = r.family;\n if (!r.available) missing.add(font.family);\n resolved.set(key, fam);\n }\n return fam;\n };\n const resolvedFont = (style: TextStyle): TextFont => ({ ...fontOf(style), family: familyOf(fontOf(style)) });\n const box = frame.kind === 'box' ? frame : null;\n const lines: LaidLine[] = [];\n let y = 0;\n let first = true;\n const paragraphs = paragraphRanges(text);\n paragraphs.forEach((para, pi) => {\n const pstyle = styleAt(layer.paragraphs, para.start, {} as ParagraphStyle);\n const autoLeading = pstyle.autoLeading ?? DEFAULT_AUTO_LEADING;\n if (pi > 0) y += pstyle.spaceBefore ?? 0;\n // Advances of the paragraph's characters, measured per style segment.\n const chars: ParaChar[] = [];\n let i = para.start;\n while (i < para.content) {\n const style = styleAt(runs, i, DEFAULT_TEXT_STYLE);\n let j = i + 1;\n while (j < para.content && styleAt(runs, j, DEFAULT_TEXT_STYLE) === style) j++;\n const seg = text.slice(i, j);\n const carets = shaper.measure(seg, resolvedFont(style));\n const track = ((style.tracking ?? 0) / 1000) * style.fontSize;\n for (let k = 0; k < seg.length; k++) chars.push({ index: i + k, ch: seg[k], advance: (carets[k + 1] ?? 0) - (carets[k] ?? 0) + track, style });\n i = j;\n }\n const startIndent = pstyle.startIndent ?? 0;\n const endIndent = pstyle.endIndent ?? 0;\n const firstIndent = pstyle.firstLineIndent ?? 0;\n // Break into lines.\n const breaks: Array<[number, number]> = [];\n if (!box || !chars.length) breaks.push([0, chars.length]);\n else {\n let s = 0;\n while (s < chars.length) {\n const avail = box.width - startIndent - endIndent - (breaks.length === 0 ? firstIndent : 0);\n let w = 0;\n let e = s;\n let lastBreak = -1;\n while (e < chars.length) {\n const c = chars[e];\n if (!isSpace(c.ch) && w + c.advance > avail && e > s) break;\n w += c.advance;\n if (isBreakAfter(c.ch) || isWide(c.ch.charCodeAt(0)) || (e + 1 < chars.length && isWide(chars[e + 1].ch.charCodeAt(0)))) lastBreak = e + 1;\n e++;\n }\n if (e < chars.length && lastBreak > s) e = lastBreak;\n // Spaces at a break hang past the edge.\n while (e < chars.length && isSpace(chars[e].ch)) e++;\n breaks.push([s, e]);\n s = e;\n }\n }\n const align: TextAlign = pstyle.align ?? 'left';\n breaks.forEach(([s, e], li) => {\n const lineChars = chars.slice(s, e);\n let visibleEnd = lineChars.length;\n while (visibleEnd > 0 && isSpace(lineChars[visibleEnd - 1].ch)) visibleEnd--;\n // Metrics: the tallest font on the line; an empty line uses the style where it starts.\n const styles = lineChars.length ? [...new Set(lineChars.map((c) => c.style))] : [styleAt(runs, Math.min(para.start, Math.max(0, text.length - 1)), DEFAULT_TEXT_STYLE)];\n let ascent = 0;\n let descent = 0;\n let leading = 0;\n for (const st of styles) {\n const m = shaper.metrics(resolvedFont(st));\n ascent = Math.max(ascent, m.ascent);\n descent = Math.max(descent, m.descent);\n leading = Math.max(leading, st.leading ?? autoLeading * st.fontSize);\n }\n if (first) {\n y = frame.kind === 'box' || (frame.kind === 'point' && frame.origin === 'top') ? ascent : 0;\n first = false;\n } else y += leading;\n const indent = startIndent + (li === 0 ? firstIndent : 0);\n let width = 0;\n for (let k = 0; k < visibleEnd; k++) width += lineChars[k].advance;\n const lastLine = li === breaks.length - 1;\n let extraPerSpace = 0;\n if (box && align === 'justify' && !lastLine) {\n const spaces = lineChars.slice(0, visibleEnd).filter((c) => isSpace(c.ch)).length;\n const avail = box.width - startIndent - endIndent - (li === 0 ? firstIndent : 0);\n if (spaces > 0 && avail > width) extraPerSpace = (avail - width) / spaces;\n }\n let x0: number;\n const fullWidth = width + extraPerSpace * lineChars.slice(0, visibleEnd).filter((c) => isSpace(c.ch)).length;\n if (box) {\n const avail = box.width - startIndent - endIndent - (li === 0 ? firstIndent : 0);\n x0 = indent + (align === 'center' ? (avail - fullWidth) / 2 : align === 'right' ? avail - fullWidth : 0);\n } else x0 = indent + (align === 'center' ? -fullWidth / 2 : align === 'right' ? -fullWidth : 0);\n const laid: LaidChar[] = [];\n let x = x0;\n for (const c of lineChars) {\n const adv = c.advance + (isSpace(c.ch) ? extraPerSpace : 0);\n laid.push({ index: c.index, x, advance: adv });\n x += adv;\n }\n // Fragments: same style, consecutive.\n const fragments: LaidFragment[] = [];\n let k = 0;\n while (k < lineChars.length) {\n const st = lineChars[k].style;\n let m = k + 1;\n while (m < lineChars.length && lineChars[m].style === st) m++;\n const font = resolvedFont(st);\n const fx = laid[k].x;\n const carets = [0];\n for (let q = k; q < m; q++) carets.push(laid[q].x + laid[q].advance - fx);\n fragments.push({\n start: lineChars[k].index,\n end: lineChars[m - 1].index + 1,\n style: st,\n font,\n family: font.family,\n x: fx,\n y: y - (st.baselineShift ?? 0),\n carets,\n spaced: Boolean(st.tracking) || extraPerSpace > 0,\n });\n k = m;\n }\n const lineStart = lineChars.length ? lineChars[0].index : para.start;\n lines.push({ start: lineStart, end: lineChars.length ? lineChars[lineChars.length - 1].index + 1 : para.start, baseline: y, ascent, descent, x: x0, width, chars: laid, fragments });\n });\n y += pstyle.spaceAfter ?? 0;\n });\n let bounds: TextRect;\n if (box) bounds = { x: 0, y: 0, width: box.width, height: box.height };\n else {\n let x0 = Infinity;\n let x1 = -Infinity;\n for (const l of lines) {\n x0 = Math.min(x0, l.x);\n x1 = Math.max(x1, l.x + l.width);\n }\n if (!Number.isFinite(x0)) x0 = x1 = 0;\n const top = lines.length ? lines[0].baseline - lines[0].ascent : 0;\n const last = lines[lines.length - 1];\n const bottom = last ? last.baseline + last.descent : 0;\n bounds = { x: x0, y: top, width: Math.max(0, x1 - x0), height: Math.max(0, bottom - top) };\n }\n return { lines, bounds, missingFonts: [...missing] };\n}\n\n/** The text index nearest a text-space point (for clicks): the line under it, then the closest caret. */\nexport function textIndexAt(layout: TextLayout, p: { x: number; y: number }): number {\n if (!layout.lines.length) return 0;\n let line = layout.lines[layout.lines.length - 1];\n for (const l of layout.lines) {\n if (p.y <= l.baseline + l.descent) {\n line = l;\n break;\n }\n }\n if (!line.chars.length) return line.start;\n for (const c of line.chars) if (p.x < c.x + c.advance / 2) return c.index;\n const lastChar = line.chars[line.chars.length - 1];\n return lastChar.index + 1;\n}\n\n/** The caret at text index `index`: its x and the line's top and bottom, text space. */\nexport function caretAt(layout: TextLayout, index: number): { x: number; top: number; bottom: number; line: number } {\n const lines = layout.lines;\n if (!lines.length) return { x: 0, top: 0, bottom: 0, line: 0 };\n for (let li = 0; li < lines.length; li++) {\n const l = lines[li];\n const next = lines[li + 1];\n if (next && index >= next.start && (next.chars.length || index > l.end || next.start > l.end)) continue;\n const c = l.chars.find((ch) => ch.index === index);\n const prev = l.chars.find((ch) => ch.index === index - 1);\n const x = c ? c.x : prev ? prev.x + prev.advance : l.x;\n return { x, top: l.baseline - l.ascent, bottom: l.baseline + l.descent, line: li };\n }\n const l = lines[lines.length - 1];\n return { x: l.x + l.width, top: l.baseline - l.ascent, bottom: l.baseline + l.descent, line: lines.length - 1 };\n}\n\n// ---------------------------------------------------------------------------\n// Outlines\n// ---------------------------------------------------------------------------\n\n/** Underline and strike-through bars of a fragment, text space, as rectangles. */\nexport function textDecorations(f: LaidFragment, l: LaidLine): TextRect[] {\n const out: TextRect[] = [];\n const t = Math.max(1, f.style.fontSize / 15);\n const w = f.carets[f.carets.length - 1];\n if (f.style.underline) out.push({ x: f.x, y: f.y + Math.max(t, l.descent * 0.35), width: w, height: t });\n if (f.style.strikethrough) out.push({ x: f.x, y: f.y - l.ascent * 0.3 - t / 2, width: w, height: t });\n return out;\n}\n\nexport const textRectPath = (r: TextRect): BezierPath => [\n { type: 'M', x: r.x, y: r.y },\n { type: 'L', x: r.x + r.width, y: r.y },\n { type: 'L', x: r.x + r.width, y: r.y + r.height },\n { type: 'L', x: r.x, y: r.y + r.height },\n { type: 'Z' },\n];\n\n/** The text of a fragment as outlines (one placement per character when spaced), text space. */\nexport function textFragmentOutline(shaper: TextShaper, text: string, f: LaidFragment): BezierPath {\n const s = text.slice(f.start, f.end);\n if (!f.spaced) return shaper.outline!(s, f.font, f.x, f.y);\n const out: BezierPath = [];\n for (let k = 0; k < s.length; k++) {\n if (isSpace(s[k])) continue;\n out.push(...shaper.outline!(s[k], f.font, f.x + f.carets[k], f.y));\n }\n return out;\n}\n\n","/**\n * Text shapers for type layers (see `TextShaper` in `text.ts`):\n *\n * - `createCanvasTextShaper`: the browser's own fonts and text drawing through Canvas 2D\n * (`measureText`, `fillText`). The default in browsers. It cannot give outlines.\n * - `createOutlineTextShaper`: glyph outlines from font objects the host loads, typed after\n * opentype.js's `Font` (`getPath`, `getAdvanceWidth`, `unitsPerEm`, …) without depending on it.\n * Pure: it renders anywhere (servers, workers, tests) and makes Convert to Shape possible.\n */\n\nimport type { BezierPath } from '../canvas/pathops/bezier';\nimport type { TextFont, TextShaper } from './types';\n\nconst GENERIC = new Set(['serif', 'sans-serif', 'monospace', 'cursive', 'fantasy', 'system-ui', 'ui-serif', 'ui-sans-serif', 'ui-monospace', 'ui-rounded', 'math', 'emoji', 'fangsong']);\n\n/** A family as it goes into a CSS `font` value: generics and lists as written, other names quoted when needed. */\nexport function cssFontFamily(family: string): string {\n const f = family.trim();\n if (GENERIC.has(f.toLowerCase()) || f.includes(',') || /^[\"']/.test(f)) return f;\n return /^[A-Za-z_-][\\w -]*$/.test(f) && !/\\s{2}/.test(f) ? f : `\"${f.replace(/\"/g, '\\\\\"')}\"`;\n}\n\n/** The CSS `font` shorthand for a font (`italic 700 24px Inter`). */\nexport function cssFont(font: TextFont, family = font.family): string {\n return `${font.italic ? 'italic ' : ''}${font.weight} ${font.size}px ${cssFontFamily(family)}`;\n}\n\nexport interface CanvasTextShaperOptions {\n /** A 1 × 1 canvas for measuring (default an `OffscreenCanvas`, else a DOM canvas). */\n createCanvas?(width: number, height: number): HTMLCanvasElement | OffscreenCanvas;\n /** Family used when one is missing (default `sans-serif`). */\n fallbackFamily?: string;\n}\n\n/**\n * A shaper over Canvas 2D. A family is missing when text set in it measures the same as in\n * both `monospace` and `serif` (the browser fell back), so web fonts must be loaded before use.\n * Returns `null` where there is no 2D canvas.\n */\nexport function createCanvasTextShaper(options: CanvasTextShaperOptions = {}): TextShaper | null {\n const make =\n options.createCanvas ??\n ((w: number, h: number) => {\n if (typeof OffscreenCanvas !== 'undefined') return new OffscreenCanvas(w, h);\n if (typeof document !== 'undefined') {\n const c = document.createElement('canvas');\n c.width = w;\n c.height = h;\n return c;\n }\n return null as unknown as HTMLCanvasElement;\n });\n const canvas = make(1, 1);\n const ctx = canvas?.getContext('2d') as CanvasRenderingContext2D | null;\n if (!ctx || typeof ctx.measureText !== 'function') return null;\n const fallback = options.fallbackFamily ?? 'sans-serif';\n const available = new Map<string, boolean>();\n const widths = new Map<string, number[]>();\n const metrics = new Map<string, { ascent: number; descent: number }>();\n const probe = 'mmmmmmmmmmlli1WQ@#';\n const width = (font: string, text: string) => {\n ctx.font = font;\n return ctx.measureText(text).width;\n };\n const isAvailable = (family: string) => {\n const f = family.trim();\n if (GENERIC.has(f.toLowerCase()) || f.includes(',')) return true;\n let hit = available.get(f);\n if (hit === undefined) {\n const q = cssFontFamily(f);\n hit = width(`72px ${q}, monospace`, probe) !== width('72px monospace', probe) || width(`72px ${q}, serif`, probe) !== width('72px serif', probe);\n available.set(f, hit);\n }\n return hit;\n };\n return {\n id: 'canvas',\n resolve(font) {\n const ok = isAvailable(font.family);\n return { family: ok ? font.family : fallback, available: ok };\n },\n metrics(font) {\n const key = cssFont(font);\n let m = metrics.get(key);\n if (!m) {\n ctx.font = key;\n ctx.textBaseline = 'alphabetic';\n const t = ctx.measureText('Hg') as TextMetrics & { emHeightAscent?: number; emHeightDescent?: number };\n // The em box, as `textBaseline: 'top'` places text (what text annotations used).\n const ascent = t.emHeightAscent ?? t.fontBoundingBoxAscent ?? font.size * 0.8;\n const descent = t.emHeightDescent ?? t.fontBoundingBoxDescent ?? font.size * 0.2;\n m = { ascent: Number.isFinite(ascent) ? ascent : font.size * 0.8, descent: Number.isFinite(descent) ? descent : font.size * 0.2 };\n metrics.set(key, m);\n }\n return m;\n },\n measure(text, font) {\n const key = `${cssFont(font)}|${text}`;\n let w = widths.get(key);\n if (!w) {\n ctx.font = cssFont(font);\n w = [0];\n for (let i = 1; i <= text.length; i++) w.push(ctx.measureText(text.slice(0, i)).width);\n if (widths.size > 2000) widths.clear();\n widths.set(key, w);\n }\n return w;\n },\n draw(target, text, font, x, y) {\n target.font = cssFont(font);\n target.textBaseline = 'alphabetic';\n target.textAlign = 'left';\n target.fillText(text, x, y);\n },\n families() {\n const out = new Set<string>(['sans-serif', 'serif', 'monospace']);\n const fonts = typeof document !== 'undefined' ? (document as Document & { fonts?: Iterable<FontFace> }).fonts : undefined;\n if (fonts && typeof (fonts as unknown as { forEach?: unknown }).forEach === 'function') (fonts as unknown as { forEach(cb: (f: FontFace) => void): void }).forEach((f) => out.add(f.family.replace(/^[\"']|[\"']$/g, '')));\n return [...out];\n },\n };\n}\n\n/** A path command as opentype.js returns it. */\nexport interface OutlinePathCommand {\n type: 'M' | 'L' | 'C' | 'Q' | 'Z';\n x?: number;\n y?: number;\n x1?: number;\n y1?: number;\n x2?: number;\n y2?: number;\n}\n\n/** The parts of an opentype.js `Font` the outline shaper uses. */\nexport interface OutlineFontFace {\n unitsPerEm: number;\n ascender: number;\n descender: number;\n getAdvanceWidth(text: string, fontSize: number, options?: { kerning?: boolean }): number;\n getPath(text: string, x: number, y: number, fontSize: number, options?: { kerning?: boolean }): { commands: OutlinePathCommand[] };\n names?: { fontFamily?: Record<string, string>; postScriptName?: Record<string, string> };\n tables?: { os2?: { usWeightClass?: number; fsSelection?: number } };\n}\n\n/** A face with its family, weight and style (read from the font's names when not given). */\nexport interface OutlineFontEntry {\n face: OutlineFontFace;\n family?: string;\n weight?: number;\n italic?: boolean;\n}\n\n/**\n * A shaper over outline fonts the host loads (opentype.js `Font` objects or anything with the same\n * methods). Fonts are matched by family (case-insensitive), then the nearest weight and the\n * italic flag; a missing family uses `fallback` (default the first font) and is reported missing.\n */\nexport function createOutlineTextShaper(fonts: ReadonlyArray<OutlineFontFace | OutlineFontEntry>, options: { fallback?: string; id?: string } = {}): TextShaper {\n if (!fonts.length) throw new Error('createOutlineTextShaper needs at least one font.');\n const entries = fonts.map((f) => {\n const e: OutlineFontEntry = 'face' in f ? f : { face: f };\n const names = e.face.names;\n const family = e.family ?? names?.fontFamily?.en ?? Object.values(names?.fontFamily ?? {})[0] ?? 'Font';\n const weight = e.weight ?? e.face.tables?.os2?.usWeightClass ?? 400;\n const italic = e.italic ?? Boolean((e.face.tables?.os2?.fsSelection ?? 0) & 1);\n const postScript = names?.postScriptName?.en ?? Object.values(names?.postScriptName ?? {})[0];\n return { face: e.face, family, key: family.toLowerCase(), weight, italic, postScript };\n });\n const fallbackKey = (options.fallback ?? entries[0].family).toLowerCase();\n const pick = (font: TextFont) => {\n if (font.postScriptName) {\n const exact = entries.find((e) => e.postScript === font.postScriptName);\n if (exact) return { entry: exact, available: true };\n }\n const key = font.family.trim().toLowerCase();\n let pool = entries.filter((e) => e.key === key);\n const available = pool.length > 0;\n if (!available) pool = entries.filter((e) => e.key === fallbackKey);\n if (!pool.length) pool = entries;\n const styled = pool.filter((e) => e.italic === font.italic);\n const list = styled.length ? styled : pool;\n const entry = list.reduce((best, e) => (Math.abs(e.weight - font.weight) < Math.abs(best.weight - font.weight) ? e : best));\n return { entry, available };\n };\n const toPath = (cmds: OutlinePathCommand[]): BezierPath => {\n const out: BezierPath = [];\n for (const c of cmds) {\n if (c.type === 'M' || c.type === 'L') out.push({ type: c.type, x: c.x!, y: c.y! });\n else if (c.type === 'C') out.push({ type: 'C', x1: c.x1!, y1: c.y1!, x2: c.x2!, y2: c.y2!, x: c.x!, y: c.y! });\n else if (c.type === 'Q') out.push({ type: 'Q', x1: c.x1!, y1: c.y1!, x: c.x!, y: c.y! });\n else out.push({ type: 'Z' });\n }\n return out;\n };\n return {\n id: options.id ?? `outline:${entries.map((e) => `${e.family}/${e.weight}${e.italic ? 'i' : ''}`).join(',')}`,\n resolve(font) {\n const { entry, available } = pick(font);\n return { family: entry.family, available };\n },\n metrics(font) {\n const { face } = pick(font).entry;\n const k = font.size / face.unitsPerEm;\n return { ascent: face.ascender * k, descent: -face.descender * k };\n },\n measure(text, font) {\n const { face } = pick(font).entry;\n const out = [0];\n for (let i = 1; i <= text.length; i++) out.push(face.getAdvanceWidth(text.slice(0, i), font.size, { kerning: true }));\n return out;\n },\n outline(text, font, x, y) {\n return toPath(pick(font).entry.face.getPath(text, x, y, font.size, { kerning: true }).commands);\n },\n families() {\n return [...new Set(entries.map((e) => e.family))];\n },\n };\n}\n\n/**\n * A shaper that needs no fonts: advances estimated per character class (narrow, wide, CJK), an\n * ascent of 0.8 em and a descent of 0.2 em. It cannot draw or outline. Layout then runs in any\n * host (servers, tests, agents without fonts) and gives stable, approximate lines; plug in a real\n * shaper to match the fonts. Every family counts as available, since it cannot tell.\n */\nexport function createMetricTextShaper(options: { id?: string } = {}): TextShaper {\n const narrow = new Set([...'iIjl.,:;!|\\'`']);\n const half = new Set([...' frt()[]{}-\"/\\\\']);\n const wide = new Set([...'mwMW@%']);\n const em = (c: string) => {\n const code = c.charCodeAt(0);\n if ((code >= 0x2e80 && code <= 0x9fff) || (code >= 0xac00 && code <= 0xd7af) || (code >= 0xff00 && code <= 0xffef)) return 1;\n if (code >= 0xdc00 && code <= 0xdfff) return 0;\n if (c === '\\n' || c === '\\r') return 0;\n if (narrow.has(c)) return 0.28;\n if (half.has(c)) return 0.36;\n if (wide.has(c)) return 0.85;\n if (c >= 'A' && c <= 'Z') return 0.66;\n if (c >= '0' && c <= '9') return 0.56;\n return 0.54;\n };\n return {\n id: options.id ?? 'metric',\n resolve: (font) => ({ family: font.family, available: true }),\n metrics: (font) => ({ ascent: font.size * 0.8, descent: font.size * 0.2 }),\n measure(text, font) {\n const out = [0];\n let x = 0;\n const k = font.size * (font.weight >= 600 ? 1.05 : 1);\n for (let i = 0; i < text.length; i++) {\n x += em(text[i]) * k;\n out.push(x);\n }\n return out;\n },\n };\n}\n","// Portions ported from effectcraft/crates/text/src/path_text.rs (MIT OR Apache-2.0, © ArtCraft Team and contributors). See THIRD_PARTY_NOTICES.md.\n\n/**\n * Text nodes: layout through the shared text engine (`src/text`, also used by the image editor's\n * type layers), glyph placement for point, area and path text, glyph outlines, and the pure edits\n * the controller and agent commands build on.\n *\n * Fonts come from one text shaper per page (`setVectorTextShaper`; the controller's `textShaper`\n * option sets it). In browsers the default is the Canvas 2D shaper (the browser's own fonts, no\n * outlines: text draws as SVG `<text>`), elsewhere a metric shaper that estimates advances. With an\n * outline shaper (`createOutlineTextShaper` over fonts read by `parseOpenTypeFont`), text draws as\n * its glyph outlines, so path effects, envelopes and Create Outlines work on it.\n */\n\nimport { toBezierPath, transformBezierPath, type BezierPath } from '../canvas/pathops/bezier.js';\nimport { caretAt, DEFAULT_AUTO_LEADING, fitRuns, isTextSpace, layoutText, restyleRange, spliceRuns, styleAt, textDecorations, textFragmentOutline, textIndexAt, textRectPath, type LaidFragment, type LaidLine, type TextLayout } from '../text/layout.js';\nimport { createCanvasTextShaper, createMetricTextShaper, cssFontFamily } from '../text/shapers.js';\nimport type { ParagraphStyle, TextFont, TextShaper, TextStyle } from '../text/types.js';\nimport { applyMatrix, isIdentityMatrix } from '../geom/affine.js';\nimport type { AffineMatrix } from '../geom/types.js';\nimport type {\n\tVec2,\n\tVectorBounds,\n\tVectorCharacterStyle,\n\tVectorPaint,\n\tVectorParagraphStyle,\n\tVectorPathNode,\n\tVectorPathTextBaseline,\n\tVectorSubpath,\n\tVectorTextFrame,\n\tVectorTextNode,\n\tVectorTextRun,\n\tVectorTextRunStyle\n} from './types.js';\nimport { VECTOR_PATH_TEXT_BASELINES, VECTOR_TEXT_ALIGNS } from './types.js';\n\n// ---------------------------------------------------------------------------\n// Shaper\n// ---------------------------------------------------------------------------\n\nlet current: TextShaper | null = null;\nlet generation = 0;\n\n/**\n * Sets the text shaper every vector editor on the page lays text out with (`null`: back to the\n * default). Text nodes already laid out with another shaper lay out again when next drawn.\n */\nexport function setVectorTextShaper(shaper: TextShaper | null): void {\n\tif (shaper === current) return;\n\tcurrent = shaper;\n\tgeneration++;\n}\n\n/** The text shaper in use: the one set, else the browser's (Canvas 2D), else the metric shaper. */\nexport function getVectorTextShaper(): TextShaper {\n\tif (!current) current = createCanvasTextShaper() ?? createMetricTextShaper();\n\treturn current;\n}\n\n/** Bumped whenever the shaper changes (part of every layout cache key). */\nexport function vectorTextShaperGeneration(): number {\n\treturn generation;\n}\n\n/** Whether the shaper gives glyph outlines (text then draws as paths, and Create Outlines works). */\nexport function vectorTextHasOutlines(): boolean {\n\treturn typeof getVectorTextShaper().outline === 'function';\n}\n\n/** Families the shaper can draw, when it can tell (always includes the generic families). */\nexport function vectorTextFamilies(): string[] {\n\treturn getVectorTextShaper().families?.() ?? ['sans-serif', 'serif', 'monospace'];\n}\n\n// ---------------------------------------------------------------------------\n// Styles and runs\n// ---------------------------------------------------------------------------\n\nexport const DEFAULT_VECTOR_FONT: Readonly<VectorCharacterStyle> = { fontFamily: 'sans-serif', fontWeight: 400, fontSize: 24 };\n\n/** Character style fields, in the order agents see them. */\nexport const VECTOR_CHARACTER_STYLE_KEYS = ['fontFamily', 'fontWeight', 'italic', 'fontSize', 'tracking', 'leading', 'baselineShift', 'underline', 'strikethrough'] as const;\n/** Paragraph style fields. */\nexport const VECTOR_PARAGRAPH_STYLE_KEYS = ['align', 'autoLeading', 'firstLineIndent', 'startIndent', 'endIndent', 'spaceBefore', 'spaceAfter'] as const;\n\nexport class VectorTextError extends Error {}\nconst fail = (message: string): never => {\n\tthrow new VectorTextError(message);\n};\n\n/** A resolved run: the node's style with the run's fields over it. */\nexport interface VectorResolvedRun {\n\tstart: number;\n\tend: number;\n\tstyle: VectorCharacterStyle;\n\t/** The run's own fill, when it has one. */\n\tfill?: VectorPaint;\n}\n\n/**\n * Runs fitted to a text of `length`: cut at its end, and text past the last run in the node's own\n * style (an empty override). Neighbours with equal styles merge.\n */\nexport function fitVectorTextRuns(runs: readonly VectorTextRun[], length: number): VectorTextRun[] {\n\tconst out: VectorTextRun[] = [];\n\tlet left = length;\n\tfor (const r of runs) {\n\t\tif (left <= 0) break;\n\t\tconst n = Math.min(Math.max(0, Math.floor(r.length)), left);\n\t\tif (n > 0) out.push({ length: n, style: r.style });\n\t\tleft -= n;\n\t}\n\tif (left > 0) out.push({ length: left, style: {} });\n\treturn fitRuns(out, length, {});\n}\n\n/** The node's runs fitted to its text, each with the full style it draws in. */\nexport function vectorTextRuns(node: Pick<VectorTextNode, 'text' | 'font' | 'runs'>): VectorResolvedRun[] {\n\tconst runs = fitVectorTextRuns(node.runs ?? [], node.text.length);\n\tconst out: VectorResolvedRun[] = [];\n\tlet at = 0;\n\tfor (const r of runs) {\n\t\tconst { fill, ...fields } = r.style;\n\t\tconst style = { ...node.font, ...stripUndefined(fields) } as VectorCharacterStyle;\n\t\tout.push({ start: at, end: at + r.length, style, ...(fill !== undefined ? { fill } : {}) });\n\t\tat += r.length;\n\t}\n\tif (!out.length) out.push({ start: 0, end: 0, style: { ...node.font } });\n\treturn out;\n}\n\nfunction stripUndefined<T extends object>(o: T): T {\n\tconst out = { ...o } as Record<string, unknown>;\n\tfor (const k of Object.keys(out)) if (out[k] === undefined) delete out[k];\n\treturn out as T;\n}\n\n/** The style at code unit `index` (the run holding it; past the end, the last run). */\nexport function vectorTextStyleAt(node: Pick<VectorTextNode, 'text' | 'font' | 'runs'>, index: number): VectorResolvedRun {\n\tconst runs = vectorTextRuns(node);\n\treturn runs.find((r) => index >= r.start && index < r.end) ?? runs[runs.length - 1];\n}\n\nconst paintKey = (paint: VectorPaint | undefined) => (paint === undefined ? '' : JSON.stringify(paint));\n\n// ---------------------------------------------------------------------------\n// Path measure (text on a path)\n// ---------------------------------------------------------------------------\n\n/** A subpath flattened and measured by arc length. */\nexport interface VectorPathMeasure {\n\tpoints: Vec2[];\n\t/** Cumulative length at each point. */\n\tlengths: number[];\n\tclosed: boolean;\n\tlength: number;\n}\n\nfunction flattenCommands(path: BezierPath): { points: Vec2[]; closed: boolean } {\n\tconst pts: Vec2[] = [];\n\tlet closed = false;\n\tlet cur: Vec2 = { x: 0, y: 0 };\n\tlet started = false;\n\tconst push = (p: Vec2) => {\n\t\tconst last = pts[pts.length - 1];\n\t\tif (!last || Math.hypot(last.x - p.x, last.y - p.y) > 1e-9) pts.push(p);\n\t};\n\tfor (const c of path) {\n\t\tif (c.type === 'M') {\n\t\t\tif (started) break;\n\t\t\tstarted = true;\n\t\t\tcur = { x: c.x, y: c.y };\n\t\t\tpush(cur);\n\t\t} else if (c.type === 'L') {\n\t\t\tcur = { x: c.x, y: c.y };\n\t\t\tpush(cur);\n\t\t} else if (c.type === 'Q' || c.type === 'C') {\n\t\t\tconst p0 = cur;\n\t\t\tconst ctrl = c.type === 'Q' ? [{ x: c.x1, y: c.y1 }] : [{ x: c.x1, y: c.y1 }, { x: c.x2, y: c.y2 }];\n\t\t\tconst p3 = { x: c.x, y: c.y };\n\t\t\tconst chord = [p0, ...ctrl, p3].reduce((s, p, i, a) => (i ? s + Math.hypot(p.x - a[i - 1].x, p.y - a[i - 1].y) : 0), 0);\n\t\t\tconst n = Math.max(4, Math.min(256, Math.ceil(chord / 2)));\n\t\t\tfor (let i = 1; i <= n; i++) {\n\t\t\t\tconst t = i / n;\n\t\t\t\tconst u = 1 - t;\n\t\t\t\tif (c.type === 'Q') push({ x: u * u * p0.x + 2 * u * t * c.x1 + t * t * p3.x, y: u * u * p0.y + 2 * u * t * c.y1 + t * t * p3.y });\n\t\t\t\telse\n\t\t\t\t\tpush({\n\t\t\t\t\t\tx: u * u * u * p0.x + 3 * u * u * t * c.x1 + 3 * u * t * t * c.x2 + t * t * t * p3.x,\n\t\t\t\t\t\ty: u * u * u * p0.y + 3 * u * u * t * c.y1 + 3 * u * t * t * c.y2 + t * t * t * p3.y\n\t\t\t\t\t});\n\t\t\t}\n\t\t\tcur = p3;\n\t\t} else if (c.type === 'Z') {\n\t\t\tclosed = true;\n\t\t\tif (pts.length > 1) push({ ...pts[0] });\n\t\t\tbreak;\n\t\t}\n\t}\n\treturn { points: pts, closed };\n}\n\n/** Measures a path's first subpath by arc length (reversed when `reverse`). */\nexport function measureVectorPath(path: BezierPath, reverse = false): VectorPathMeasure {\n\tconst { points, closed } = flattenCommands(path);\n\tif (reverse) points.reverse();\n\tconst lengths: number[] = [];\n\tlet acc = 0;\n\tpoints.forEach((p, i) => {\n\t\tif (i) acc += Math.hypot(p.x - points[i - 1].x, p.y - points[i - 1].y);\n\t\tlengths.push(acc);\n\t});\n\treturn { points, lengths, closed, length: acc };\n}\n\n/**\n * Point and unit tangent at arc length `s`. Closed paths wrap; open paths continue straight along\n * their end tangents past either end.\n */\nexport function vectorPathAt(m: VectorPathMeasure, s: number): { point: Vec2; tangent: Vec2 } {\n\tconst pts = m.points;\n\tif (pts.length < 2 || m.length <= 1e-9) return { point: pts[0] ?? { x: 0, y: 0 }, tangent: { x: 1, y: 0 } };\n\tif (m.closed) s = ((s % m.length) + m.length) % m.length;\n\tlet lo = 0;\n\tlet hi = pts.length - 1;\n\twhile (hi - lo > 1) {\n\t\tconst mid = (lo + hi) >> 1;\n\t\tif (m.lengths[mid] <= s) lo = mid;\n\t\telse hi = mid;\n\t}\n\tconst a = pts[lo];\n\tconst b = pts[lo + 1];\n\tconst seg = m.lengths[lo + 1] - m.lengths[lo];\n\tconst tangent = seg > 0 ? { x: (b.x - a.x) / seg, y: (b.y - a.y) / seg } : { x: 1, y: 0 };\n\tconst d = s - m.lengths[lo];\n\treturn { point: { x: a.x + tangent.x * d, y: a.y + tangent.y * d }, tangent };\n}\n\n/**\n * Arc-length positions for character pivots along a path: `xs` are the pivots along the line,\n * `[x0, x1]` the line's extent. `left` / `center` / `right` keep the spacing; `justify` spreads the\n * pivots over the path between the margins.\n */\nexport function vectorPathTextPositions(xs: readonly number[], line: [number, number], align: 'left' | 'center' | 'right' | 'justify', length: number, start: number, end: number): number[] {\n\tif (!xs.length) return [];\n\tif (align === 'justify') {\n\t\tconst a = start;\n\t\tconst b = length - end;\n\t\tconst x0 = xs[0];\n\t\tconst x1 = xs[xs.length - 1];\n\t\tif (Math.abs(x1 - x0) < 1e-9) return xs.map(() => a);\n\t\treturn xs.map((x) => a + ((b - a) * (x - x0)) / (x1 - x0));\n\t}\n\tif (align === 'center') {\n\t\tconst mid = (start + length - end) / 2;\n\t\tconst c = (line[0] + line[1]) / 2;\n\t\treturn xs.map((x) => mid + x - c);\n\t}\n\tif (align === 'right') return xs.map((x) => length - end - (line[1] - x));\n\treturn xs.map((x) => start + x - line[0]);\n}\n\n// ---------------------------------------------------------------------------\n// Layout\n// ---------------------------------------------------------------------------\n\n/** One placed character, in the node's own space. */\nexport interface VectorTextGlyph {\n\t/** Index of its first code unit in the text. */\n\tindex: number;\n\t/** The character (two code units for a surrogate pair). */\n\tchar: string;\n\t/** Its origin: the start of the character on the baseline. */\n\tx: number;\n\ty: number;\n\t/** Turn in degrees, clockwise on screen (0 for point and area text). */\n\tangle: number;\n\tadvance: number;\n\t/** The line's ascent and descent around the baseline. */\n\tascent: number;\n\tdescent: number;\n\t/** Index into `fragments`. */\n\tfragment: number;\n}\n\n/** A run of glyphs in one style on one line. */\nexport interface VectorTextFragment {\n\tstyle: VectorCharacterStyle;\n\t/** The font as the shaper resolved it (its family may be a fallback). */\n\tfont: TextFont;\n\tfill?: VectorPaint;\n\t/** Glyphs of this fragment: `glyphs.slice(from, to)`. */\n\tfrom: number;\n\tto: number;\n\tline: number;\n\t/** The shared engine's fragment and line (point and area text). */\n\tlaid?: { fragment: LaidFragment; line: LaidLine };\n}\n\n/** A laid-out text node. */\nexport interface VectorTextLayout {\n\t/** The shaper it was laid out with. */\n\tshaper: string;\n\tglyphs: VectorTextGlyph[];\n\tfragments: VectorTextFragment[];\n\t/** Lines: their text range and baseline (node space for point and area text). */\n\tlines: { start: number; end: number; baseline: number; x: number; width: number }[];\n\t/** Where text space (the shared layout's) starts in the node: the frame's origin. */\n\torigin: Vec2;\n\t/** The shared layout in text space (one line for path text). */\n\ttext: TextLayout;\n\t/** Bounds of the glyph boxes (or the frame box of area text), node space; null when empty. */\n\tbounds: VectorBounds | null;\n\t/** Text that does not fit (lines below an area's box, characters past a path's end). */\n\toverflow: boolean;\n\t/** Families drawn with a fallback. */\n\tmissingFonts: string[];\n}\n\n/** The node as the shared engine's text block (text space). */\nfunction textBlock(node: VectorTextNode): { text: string; runs: Array<{ length: number; style: TextStyle }>; paragraphs: Array<{ length: number; style: ParagraphStyle }>; frame: { kind: 'point' } | { kind: 'box'; width: number; height: number } } {\n\tconst runs = vectorTextRuns(node);\n\tconst keys: string[] = [];\n\tconst text = node.frame.kind === 'path' ? node.text.replace(/\\n/g, ' ') : node.text;\n\treturn {\n\t\ttext,\n\t\truns: runs.map((r) => {\n\t\t\tconst k = paintKey(r.fill);\n\t\t\tlet i = keys.indexOf(k);\n\t\t\tif (i < 0) i = keys.push(k) - 1;\n\t\t\t// `color` keeps runs of different fills apart (layout does not draw).\n\t\t\treturn { length: r.end - r.start, style: { ...r.style, color: `#${i}` } as TextStyle };\n\t\t}),\n\t\tparagraphs: [{ length: text.length, style: { ...(node.paragraph ?? {}), ...(node.frame.kind === 'path' ? { align: 'left' as const } : {}) } }],\n\t\tframe: node.frame.kind === 'area' ? { kind: 'box', width: Math.max(0, node.frame.width), height: Math.max(0, node.frame.height) } : { kind: 'point' }\n\t};\n}\n\n/** Code units of the character at `i` (2 for a surrogate pair). */\nconst charAt = (text: string, i: number) => {\n\tconst c = text.charCodeAt(i);\n\treturn c >= 0xd800 && c <= 0xdbff && i + 1 < text.length ? text.slice(i, i + 2) : text[i];\n};\n\nconst layoutCache = new WeakMap<object, { key: string; layout: VectorTextLayout }>();\n\n/** Lays out a text node with the current shaper (memoised per node object and shaper). */\nexport function layoutVectorText(node: VectorTextNode): VectorTextLayout {\n\tconst shaper = getVectorTextShaper();\n\tconst key = `${shaper.id}:${generation}`;\n\tconst hit = layoutCache.get(node);\n\tif (hit && hit.key === key) return hit.layout;\n\tconst layout = computeLayout(node, shaper);\n\tlayoutCache.set(node, { key, layout });\n\treturn layout;\n}\n\nfunction computeLayout(node: VectorTextNode, shaper: TextShaper): VectorTextLayout {\n\tconst block = textBlock(node);\n\tconst runs = vectorTextRuns(node);\n\tconst text = layoutText(block, shaper);\n\tconst frame = node.frame;\n\tconst origin = frame.kind === 'path' ? { x: 0, y: 0 } : { x: frame.x, y: frame.y };\n\tconst glyphs: VectorTextGlyph[] = [];\n\tconst fragments: VectorTextFragment[] = [];\n\tconst lines: VectorTextLayout['lines'] = [];\n\tlet overflow = false;\n\tconst fillOf = (f: LaidFragment) => runs.find((r) => f.start >= r.start && f.start < r.end)?.fill;\n\tconst styleOf = (f: LaidFragment): VectorCharacterStyle => {\n\t\tconst { color: _c, opacity: _o, postScriptName: _p, ...style } = f.style;\n\t\treturn style as VectorCharacterStyle;\n\t};\n\tif (frame.kind !== 'path') {\n\t\ttext.lines.forEach((l, li) => {\n\t\t\tif (frame.kind === 'area' && li > 0 && l.baseline + l.descent > frame.height + 1e-6) {\n\t\t\t\toverflow = true;\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tlines.push({ start: l.start, end: l.end, baseline: origin.y + l.baseline, x: origin.x + l.x, width: l.width });\n\t\t\tfor (const f of l.fragments) {\n\t\t\t\tconst from = glyphs.length;\n\t\t\t\tfor (let k = 0; k < f.end - f.start; k++) {\n\t\t\t\t\tconst index = f.start + k;\n\t\t\t\t\tconst ch = block.text[index];\n\t\t\t\t\tconst lo = ch.charCodeAt(0);\n\t\t\t\t\tif (lo >= 0xdc00 && lo <= 0xdfff && k > 0) {\n\t\t\t\t\t\t// The low half of a pair: its advance joins the high half's glyph.\n\t\t\t\t\t\tconst g = glyphs[glyphs.length - 1];\n\t\t\t\t\t\tif (g) g.advance += f.carets[k + 1] - f.carets[k];\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t\tglyphs.push({ index, char: charAt(block.text, index), x: origin.x + f.x + f.carets[k], y: origin.y + f.y, angle: 0, advance: f.carets[k + 1] - f.carets[k], ascent: l.ascent, descent: l.descent, fragment: fragments.length });\n\t\t\t\t}\n\t\t\t\tfragments.push({ style: styleOf(f), font: f.font, ...(fillOf(f) !== undefined ? { fill: fillOf(f) } : {}), from, to: glyphs.length, line: lines.length - 1, laid: { fragment: f, line: l } });\n\t\t\t}\n\t\t});\n\t} else {\n\t\tconst line = text.lines[0];\n\t\tconst measure = measureVectorPath(subpathPath(frame.path), !!frame.flip);\n\t\tconst align = node.paragraph?.align ?? 'left';\n\t\tconst start = Math.max(0, frame.start ?? 0);\n\t\tconst end = Math.max(0, frame.end ?? 0);\n\t\tconst upright = frame.orientation === 'upright';\n\t\tconst baselineOffset = pathBaselineOffset(frame.baseline ?? 'baseline', line?.ascent ?? 0, line?.descent ?? 0);\n\t\tif (line) {\n\t\t\tconst chars = line.chars.filter((c) => {\n\t\t\t\tconst lo = block.text.charCodeAt(c.index);\n\t\t\t\treturn !(lo >= 0xdc00 && lo <= 0xdfff && c.index > 0 && block.text.charCodeAt(c.index - 1) >= 0xd800 && block.text.charCodeAt(c.index - 1) <= 0xdbff);\n\t\t\t});\n\t\t\tconst advanceOf = (c: (typeof chars)[number]) => {\n\t\t\t\tconst pair = charAt(block.text, c.index).length === 2;\n\t\t\t\tconst low = pair ? line.chars.find((d) => d.index === c.index + 1) : undefined;\n\t\t\t\treturn c.advance + (low?.advance ?? 0);\n\t\t\t};\n\t\t\tconst pivots = chars.map((c) => c.x + advanceOf(c) / 2);\n\t\t\tconst positions = vectorPathTextPositions(pivots, [line.x, line.x + line.width], align, measure.length, start, end);\n\t\t\tconst limit = measure.length - end;\n\t\t\tlines.push({ start: line.start, end: line.end, baseline: 0, x: 0, width: line.width });\n\t\t\tfor (const f of line.fragments) {\n\t\t\t\tconst from = glyphs.length;\n\t\t\t\tconst shift = f.y - line.baseline;\n\t\t\t\tchars.forEach((c, k) => {\n\t\t\t\t\tif (c.index < f.start || c.index >= f.end) return;\n\t\t\t\t\tconst s = positions[k];\n\t\t\t\t\tconst adv = advanceOf(c);\n\t\t\t\t\tif (s - adv / 2 < start - 1e-6 || s + adv / 2 > limit + 1e-6) {\n\t\t\t\t\t\tif (!isTextSpace(block.text[c.index])) overflow = true;\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tconst { point, tangent } = vectorPathAt(measure, s);\n\t\t\t\t\tconst t = upright ? { x: 1, y: 0 } : tangent;\n\t\t\t\t\tconst n = upright ? { x: 0, y: 1 } : { x: -tangent.y, y: tangent.x };\n\t\t\t\t\tconst off = baselineOffset + shift;\n\t\t\t\t\tglyphs.push({\n\t\t\t\t\t\tindex: c.index,\n\t\t\t\t\t\tchar: charAt(block.text, c.index),\n\t\t\t\t\t\tx: point.x + n.x * off - (t.x * adv) / 2,\n\t\t\t\t\t\ty: point.y + n.y * off - (t.y * adv) / 2,\n\t\t\t\t\t\tangle: upright ? 0 : (Math.atan2(tangent.y, tangent.x) * 180) / Math.PI,\n\t\t\t\t\t\tadvance: adv,\n\t\t\t\t\t\tascent: line.ascent,\n\t\t\t\t\t\tdescent: line.descent,\n\t\t\t\t\t\tfragment: fragments.length\n\t\t\t\t\t});\n\t\t\t\t});\n\t\t\t\tfragments.push({ style: styleOf(f), font: f.font, ...(fillOf(f) !== undefined ? { fill: fillOf(f) } : {}), from, to: glyphs.length, line: 0 });\n\t\t\t}\n\t\t}\n\t}\n\tlet bounds: VectorBounds | null = null;\n\tif (frame.kind === 'area') bounds = { x: frame.x, y: frame.y, width: Math.max(0, frame.width), height: Math.max(0, frame.height) };\n\telse {\n\t\tlet x0 = Infinity;\n\t\tlet y0 = Infinity;\n\t\tlet x1 = -Infinity;\n\t\tlet y1 = -Infinity;\n\t\tfor (const g of glyphs) {\n\t\t\tfor (const p of glyphBox(g)) {\n\t\t\t\tx0 = Math.min(x0, p.x);\n\t\t\t\ty0 = Math.min(y0, p.y);\n\t\t\t\tx1 = Math.max(x1, p.x);\n\t\t\t\ty1 = Math.max(y1, p.y);\n\t\t\t}\n\t\t}\n\t\tif (x0 < Infinity) bounds = { x: x0, y: y0, width: x1 - x0, height: y1 - y0 };\n\t\telse if (frame.kind === 'point') {\n\t\t\t// Empty point text still has a place: a zero-width line at its origin.\n\t\t\tconst l = text.lines[0];\n\t\t\tbounds = { x: frame.x, y: frame.y - (l?.ascent ?? 0), width: 0, height: (l?.ascent ?? 0) + (l?.descent ?? 0) };\n\t\t}\n\t}\n\treturn { shaper: shaper.id, glyphs, fragments, lines, origin, text, bounds, overflow, missingFonts: text.missingFonts };\n}\n\nfunction pathBaselineOffset(baseline: VectorPathTextBaseline, ascent: number, descent: number): number {\n\tif (baseline === 'ascender') return ascent;\n\tif (baseline === 'descender') return -descent;\n\tif (baseline === 'center') return (ascent - descent) / 2;\n\treturn 0;\n}\n\n/** The anchors of a subpath as a Bézier path (no live corners: text follows the stored path). */\nfunction subpathPath(sp: VectorSubpath): BezierPath {\n\tconst a = sp.anchors;\n\tconst out: BezierPath = [];\n\tif (!a.length) return out;\n\tout.push({ type: 'M', x: a[0].x, y: a[0].y });\n\tconst seg = (p: (typeof a)[number], q: (typeof a)[number]) => {\n\t\tif (p.out || q.in) {\n\t\t\tconst c1 = p.out ?? p;\n\t\t\tconst c2 = q.in ?? q;\n\t\t\tout.push({ type: 'C', x1: c1.x, y1: c1.y, x2: c2.x, y2: c2.y, x: q.x, y: q.y });\n\t\t} else out.push({ type: 'L', x: q.x, y: q.y });\n\t};\n\tfor (let i = 1; i < a.length; i++) seg(a[i - 1], a[i]);\n\tif (sp.closed && a.length > 1) {\n\t\tseg(a[a.length - 1], a[0]);\n\t\tout.push({ type: 'Z' });\n\t}\n\treturn out;\n}\n\n/** The four corners of a glyph's box (origin, advance, ascent to descent), turned by its angle. */\nexport function glyphBox(g: VectorTextGlyph): Vec2[] {\n\tconst r = (g.angle * Math.PI) / 180;\n\tconst t = { x: Math.cos(r), y: Math.sin(r) };\n\tconst n = { x: -t.y, y: t.x };\n\tconst at = (u: number, v: number) => ({ x: g.x + t.x * u + n.x * v, y: g.y + t.y * u + n.y * v });\n\treturn [at(0, -g.ascent), at(g.advance, -g.ascent), at(g.advance, g.descent), at(0, g.descent)];\n}\n\n// ---------------------------------------------------------------------------\n// Outlines\n// ---------------------------------------------------------------------------\n\n/** The text as paths in the node's own space, one per fill (bottom to top in text order). */\nexport interface VectorTextPaths {\n\t/** `fill`: a run's own fill, or undefined for the node's paint. */\n\tparts: Array<{ fill?: VectorPaint; path: BezierPath }>;\n\t/** Whether these are glyph outlines (false: glyph boxes, for geometry without an outline shaper). */\n\toutlines: boolean;\n}\n\nconst pathsCache = new WeakMap<object, { key: string; paths: VectorTextPaths }>();\n\n/**\n * What a text node draws as geometry: its glyph outlines (plus underline and strike-through bars)\n * with an outline shaper, else a box per glyph (ascent to descent), which bounds, hit-testing and\n * snapping use. Memoised per node object and shaper.\n */\nexport function vectorTextPaths(node: VectorTextNode): VectorTextPaths {\n\tconst shaper = getVectorTextShaper();\n\tconst key = `${shaper.id}:${generation}`;\n\tconst hit = pathsCache.get(node);\n\tif (hit && hit.key === key) return hit.paths;\n\tconst layout = layoutVectorText(node);\n\tconst outlines = typeof shaper.outline === 'function';\n\tconst byFill = new Map<string, { fill?: VectorPaint; path: BezierPath }>();\n\tconst partFor = (fill: VectorPaint | undefined) => {\n\t\tconst k = paintKey(fill);\n\t\tlet p = byFill.get(k);\n\t\tif (!p) {\n\t\t\tp = { ...(fill !== undefined ? { fill } : {}), path: [] };\n\t\t\tbyFill.set(k, p);\n\t\t}\n\t\treturn p.path;\n\t};\n\tconst blockText = node.frame.kind === 'path' ? node.text.replace(/\\n/g, ' ') : node.text;\n\tlayout.fragments.forEach((f) => {\n\t\tconst out = partFor(f.fill);\n\t\tconst glyphs = layout.glyphs.slice(f.from, f.to);\n\t\tif (!glyphs.length) return;\n\t\tif (!outlines) {\n\t\t\tif (node.frame.kind === 'path') {\n\t\t\t\tfor (const g of glyphs) if (!isTextSpace(g.char)) out.push(...polygon(glyphBox(g)));\n\t\t\t} else {\n\t\t\t\tconst first = glyphs[0];\n\t\t\t\tconst last = glyphs[glyphs.length - 1];\n\t\t\t\tout.push(...polygon([{ x: first.x, y: first.y - first.ascent }, { x: last.x + last.advance, y: first.y - first.ascent }, { x: last.x + last.advance, y: first.y + first.descent }, { x: first.x, y: first.y + first.descent }]));\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\t\tif (node.frame.kind !== 'path') {\n\t\t\t// Point and area text: the shared engine's fragment outline, moved to the frame.\n\t\t\tif (!f.laid) return;\n\t\t\tlet path = textFragmentOutline(shaper, blockText, f.laid.fragment);\n\t\t\tfor (const r of textDecorations(f.laid.fragment, f.laid.line)) path = [...path, ...textRectPath(r)];\n\t\t\tout.push(...(layout.origin.x || layout.origin.y ? transformBezierPath(path, [1, 0, 0, 1, layout.origin.x, layout.origin.y]) : path));\n\t\t\treturn;\n\t\t}\n\t\tfor (const g of glyphs) {\n\t\t\tif (isTextSpace(g.char)) continue;\n\t\t\tconst glyph = shaper.outline!(g.char, f.font, 0, 0);\n\t\t\tconst r = (g.angle * Math.PI) / 180;\n\t\t\tconst c = Math.cos(r);\n\t\t\tconst s = Math.sin(r);\n\t\t\tout.push(...transformBezierPath(glyph, [c, s, -s, c, g.x, g.y]));\n\t\t}\n\t\t// Decorations along a path: a bar under each glyph.\n\t\tif (f.style.underline || f.style.strikethrough) {\n\t\t\tconst t = Math.max(1, f.style.fontSize / 15);\n\t\t\tfor (const g of glyphs) {\n\t\t\t\tconst bars: Array<[number, number]> = [];\n\t\t\t\tif (f.style.underline) bars.push([Math.max(t, g.descent * 0.35), t]);\n\t\t\t\tif (f.style.strikethrough) bars.push([-g.ascent * 0.3 - t / 2, t]);\n\t\t\t\tfor (const [v, h] of bars) out.push(...polygon(glyphBox({ ...g, ascent: -v, descent: v + h })));\n\t\t\t}\n\t\t}\n\t});\n\tconst paths: VectorTextPaths = { parts: [...byFill.values()].filter((p) => p.path.length), outlines };\n\tpathsCache.set(node, { key, paths });\n\treturn paths;\n}\n\nfunction polygon(pts: Vec2[]): BezierPath {\n\treturn [{ type: 'M', x: pts[0].x, y: pts[0].y }, ...pts.slice(1).map((p) => ({ type: 'L' as const, x: p.x, y: p.y })), { type: 'Z' }];\n}\n\n/**\n * The style a text node paints with as a path node (for the drawing machinery): its paint stacks,\n * stroke settings and fill rule, with `fill` replacing the top fill's paint when given.\n */\nexport function vectorTextPaintSource(node: VectorTextNode, fill?: VectorPaint, subpaths: VectorSubpath[] = []): VectorPathNode {\n\tconst { type: _t, text: _x, font: _f, runs: _r, paragraph: _p, frame: _fr, ...rest } = node;\n\tconst out: VectorPathNode = { ...rest, type: 'path', subpaths, fillRule: 'nonzero' };\n\tif (fill === undefined) return out;\n\tif (Array.isArray(out.fills) && out.fills.length) {\n\t\tconst fills = out.fills.map((l) => ({ ...l }));\n\t\tfills[fills.length - 1].paint = fill;\n\t\treturn { ...out, fills, fill };\n\t}\n\treturn { ...out, fill };\n}\n\n// ---------------------------------------------------------------------------\n// Carets and hit testing (editing)\n// ---------------------------------------------------------------------------\n\n/** A caret as a segment from the top of its line to the bottom, node space. */\nexport interface VectorTextCaret {\n\ttop: Vec2;\n\tbottom: Vec2;\n\t/** The line it is on. */\n\tline: number;\n}\n\n/** The caret before code unit `index` (after the last character at the end). */\nexport function vectorTextCaret(node: VectorTextNode, index: number): VectorTextCaret {\n\tconst layout = layoutVectorText(node);\n\tconst glyphs = layout.glyphs;\n\tconst at = (g: VectorTextGlyph, u: number): VectorTextCaret => {\n\t\tconst r = (g.angle * Math.PI) / 180;\n\t\tconst t = { x: Math.cos(r), y: Math.sin(r) };\n\t\tconst n = { x: -t.y, y: t.x };\n\t\tconst o = { x: g.x + t.x * u, y: g.y + t.y * u };\n\t\treturn { top: { x: o.x - n.x * g.ascent, y: o.y - n.y * g.ascent }, bottom: { x: o.x + n.x * g.descent, y: o.y + n.y * g.descent }, line: layout.fragments[g.fragment]?.line ?? 0 };\n\t};\n\tif (node.frame.kind !== 'path') {\n\t\t// Point and area text: the shared engine's caret (it knows empty lines and line ends).\n\t\tconst c = caretAt(layout.text, index);\n\t\tconst o = layout.origin;\n\t\treturn { top: { x: o.x + c.x, y: o.y + c.top }, bottom: { x: o.x + c.x, y: o.y + c.bottom }, line: c.line };\n\t}\n\tconst g = glyphs.find((x) => x.index >= index);\n\tif (g && g.index === index) return at(g, 0);\n\tconst prev = [...glyphs].reverse().find((x) => x.index < index);\n\tif (prev) return at(prev, prev.advance);\n\tif (g) return at(g, 0);\n\t// No glyphs: the start of the path.\n\tconst frame = node.frame;\n\tconst m = measureVectorPath(subpathPath(frame.path), !!frame.flip);\n\tconst { point, tangent } = vectorPathAt(m, frame.start ?? 0);\n\tconst size = node.font.fontSize;\n\tconst n = { x: -tangent.y, y: tangent.x };\n\treturn { top: { x: point.x - n.x * size * 0.8, y: point.y - n.y * size * 0.8 }, bottom: { x: point.x + n.x * size * 0.2, y: point.y + n.y * size * 0.2 }, line: 0 };\n}\n\n/** The text index nearest a node-space point (for clicks). */\nexport function vectorTextIndexAt(node: VectorTextNode, p: Vec2): number {\n\tconst layout = layoutVectorText(node);\n\tif (node.frame.kind !== 'path') return textIndexAt(layout.text, { x: p.x - layout.origin.x, y: p.y - layout.origin.y });\n\tlet best = node.text.length;\n\tlet bestD = Infinity;\n\tfor (const g of layout.glyphs) {\n\t\tconst r = (g.angle * Math.PI) / 180;\n\t\tconst t = { x: Math.cos(r), y: Math.sin(r) };\n\t\tconst dx = p.x - g.x;\n\t\tconst dy = p.y - g.y;\n\t\tconst u = dx * t.x + dy * t.y;\n\t\tconst v = -dx * t.y + dy * t.x;\n\t\tconst du = u < 0 ? -u : u > g.advance ? u - g.advance : 0;\n\t\tconst dv = v < -g.ascent ? -g.ascent - v : v > g.descent ? v - g.descent : 0;\n\t\tconst d = Math.hypot(du, dv);\n\t\tif (d < bestD) {\n\t\t\tbestD = d;\n\t\t\tbest = u < g.advance / 2 ? g.index : g.index + g.char.length;\n\t\t}\n\t}\n\treturn best;\n}\n\n/** Quads (node space) covering the glyphs of [start, end), one per line for point and area text. */\nexport function vectorTextSelectionQuads(node: VectorTextNode, start: number, end: number): Vec2[][] {\n\tif (end <= start) return [];\n\tconst layout = layoutVectorText(node);\n\tconst picked = layout.glyphs.filter((g) => g.index >= start && g.index < end);\n\tif (node.frame.kind === 'path') return picked.map(glyphBox);\n\tconst byLine = new Map<number, VectorTextGlyph[]>();\n\tfor (const g of picked) {\n\t\tconst line = layout.fragments[g.fragment].line;\n\t\tbyLine.set(line, [...(byLine.get(line) ?? []), g]);\n\t}\n\tconst out: Vec2[][] = [];\n\tfor (const gs of byLine.values()) {\n\t\tconst a = gs[0];\n\t\tconst b = gs[gs.length - 1];\n\t\tout.push(glyphBox({ ...a, advance: b.x + b.advance - a.x }));\n\t}\n\treturn out;\n}\n\n// ---------------------------------------------------------------------------\n// Validation\n// ---------------------------------------------------------------------------\n\nconst isNum = (v: unknown): v is number => typeof v === 'number' && Number.isFinite(v);\nfunction num(v: unknown, path: string, min: number, max: number): number {\n\tif (!isNum(v) || v < min || v > max) fail(`${path} must be a number from ${min} to ${max}, got ${JSON.stringify(v)}.`);\n\treturn v as number;\n}\n\n/**\n * A character style patch validated (`null` clears an optional field). With `full`, the result\n * must be a complete style (the node's own).\n */\nexport function patchVectorCharacterStyle<T extends Partial<VectorCharacterStyle>>(base: T, patch: Record<string, unknown>, path = 'style'): T {\n\tconst out = { ...base } as Record<string, unknown>;\n\tfor (const [k, v] of Object.entries(patch)) {\n\t\tif (v === undefined) continue;\n\t\tswitch (k) {\n\t\t\tcase 'fontFamily':\n\t\t\t\tif (typeof v !== 'string' || !v.trim()) fail(`${path}.fontFamily must be a font family name.`);\n\t\t\t\tout.fontFamily = (v as string).trim();\n\t\t\t\tbreak;\n\t\t\tcase 'fontWeight': {\n\t\t\t\tconst w = v === 'normal' ? 400 : v === 'bold' ? 700 : v;\n\t\t\t\tout.fontWeight = Math.round(num(w, `${path}.fontWeight`, 1, 1000));\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase 'fontSize':\n\t\t\t\tout.fontSize = num(v, `${path}.fontSize`, 0.5, 5000);\n\t\t\t\tbreak;\n\t\t\tcase 'italic':\n\t\t\tcase 'underline':\n\t\t\tcase 'strikethrough':\n\t\t\t\tif (typeof v !== 'boolean' && v !== null) fail(`${path}.${k} must be true or false.`);\n\t\t\t\tif (v) out[k] = true;\n\t\t\t\telse delete out[k];\n\t\t\t\tbreak;\n\t\t\tcase 'tracking':\n\t\t\tcase 'leading':\n\t\t\tcase 'baselineShift': {\n\t\t\t\tif (v === null) {\n\t\t\t\t\tdelete out[k];\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tconst [min, max] = k === 'tracking' ? [-1000, 10000] : k === 'leading' ? [0, 10000] : [-5000, 5000];\n\t\t\t\tconst value = num(v, `${path}.${k}`, min, max);\n\t\t\t\tif (k !== 'leading' && value === 0) delete out[k];\n\t\t\t\telse out[k] = value;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tdefault:\n\t\t\t\tfail(`${path}.${k} is not a character style field; use ${VECTOR_CHARACTER_STYLE_KEYS.join(', ')} (and fill for a range's colour).`);\n\t\t}\n\t}\n\treturn out as T;\n}\n\n/** A paragraph style patch validated (`null` clears a field). */\nexport function patchVectorParagraphStyle(base: VectorParagraphStyle, patch: Record<string, unknown>, path = 'paragraph'): VectorParagraphStyle {\n\tconst out = { ...base } as Record<string, unknown>;\n\tfor (const [k, v] of Object.entries(patch)) {\n\t\tif (v === undefined) continue;\n\t\tif (k === 'align') {\n\t\t\tif (v === null || v === 'left') delete out.align;\n\t\t\telse if (!VECTOR_TEXT_ALIGNS.includes(v as never)) fail(`${path}.align must be one of ${VECTOR_TEXT_ALIGNS.join(', ')}.`);\n\t\t\telse out.align = v;\n\t\t} else if ((VECTOR_PARAGRAPH_STYLE_KEYS as readonly string[]).includes(k)) {\n\t\t\tif (v === null) {\n\t\t\t\tdelete out[k];\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tconst value = k === 'autoLeading' ? num(v, `${path}.${k}`, 0.1, 10) : num(v, `${path}.${k}`, -10000, 10000);\n\t\t\tif ((k === 'autoLeading' && value === DEFAULT_AUTO_LEADING) || (k !== 'autoLeading' && value === 0)) delete out[k];\n\t\t\telse out[k] = value;\n\t\t} else fail(`${path}.${k} is not a paragraph style field; use ${VECTOR_PARAGRAPH_STYLE_KEYS.join(', ')}.`);\n\t}\n\treturn out as VectorParagraphStyle;\n}\n\n/** A frame from loose input, validated. */\nexport function sanitizeVectorTextFrame(value: unknown, path = 'frame'): VectorTextFrame {\n\tconst f = value as Record<string, unknown> | null;\n\tif (!f || typeof f !== 'object') return fail(`${path} must be an object with kind point, area or path.`);\n\tif (f.kind === 'point') return { kind: 'point', x: num(f.x, `${path}.x`, -1e7, 1e7), y: num(f.y, `${path}.y`, -1e7, 1e7) };\n\tif (f.kind === 'area')\n\t\treturn { kind: 'area', x: num(f.x, `${path}.x`, -1e7, 1e7), y: num(f.y, `${path}.y`, -1e7, 1e7), width: num(f.width, `${path}.width`, 0, 1e7), height: num(f.height, `${path}.height`, 0, 1e7) };\n\tif (f.kind === 'path') {\n\t\tconst sp = f.path as VectorSubpath | undefined;\n\t\tif (!sp || !Array.isArray(sp.anchors) || sp.anchors.length < 2 || !sp.anchors.every((a) => isNum(a?.x) && isNum(a?.y))) fail(`${path}.path must be a subpath with at least two anchors.`);\n\t\tconst out: VectorTextFrame = { kind: 'path', path: { closed: !!sp!.closed, anchors: sp!.anchors.map((a) => ({ ...a })) } };\n\t\tif (f.start !== undefined && f.start !== 0) out.start = num(f.start, `${path}.start`, 0, 1e7);\n\t\tif (f.end !== undefined && f.end !== 0) out.end = num(f.end, `${path}.end`, 0, 1e7);\n\t\tif (f.flip) out.flip = true;\n\t\tif (f.orientation !== undefined && f.orientation !== 'rotate') {\n\t\t\tif (f.orientation !== 'upright') fail(`${path}.orientation must be rotate or upright.`);\n\t\t\tout.orientation = 'upright';\n\t\t}\n\t\tif (f.baseline !== undefined && f.baseline !== 'baseline') {\n\t\t\tif (!VECTOR_PATH_TEXT_BASELINES.includes(f.baseline as never)) fail(`${path}.baseline must be one of ${VECTOR_PATH_TEXT_BASELINES.join(', ')}.`);\n\t\t\tout.baseline = f.baseline as VectorPathTextBaseline;\n\t\t}\n\t\treturn out;\n\t}\n\treturn fail(`${path}.kind must be point, area or path, got ${JSON.stringify(f.kind)}.`);\n}\n\n/** Normalised runs: fitted to the text, empty overrides dropped, `null` when there is one plain style. */\nexport function normalizeVectorTextRuns(text: string, runs: readonly VectorTextRun[] | null | undefined): VectorTextRun[] | null {\n\tif (!runs?.length) return null;\n\tconst cleaned = fitVectorTextRuns(\n\t\truns.map((r) => ({ length: r.length, style: stripUndefined(r.style) })),\n\t\ttext.length\n\t);\n\tif (cleaned.every((r) => !Object.keys(r.style).length)) return null;\n\treturn cleaned;\n}\n\n/** A text node read from untrusted data (JSON, SVG data attributes, agents): fields validated and normalised. */\nexport function sanitizeVectorTextFields(value: Record<string, unknown>): Pick<VectorTextNode, 'text' | 'font' | 'runs' | 'paragraph' | 'frame'> {\n\tconst text = typeof value.text === 'string' ? value.text.replace(/\\r\\n?/g, '\\n') : '';\n\tconst font = patchVectorCharacterStyle({ ...DEFAULT_VECTOR_FONT }, (value.font as Record<string, unknown>) ?? {}, 'font');\n\tconst runs = Array.isArray(value.runs)\n\t\t? normalizeVectorTextRuns(\n\t\t\t\ttext,\n\t\t\t\t(value.runs as VectorTextRun[])\n\t\t\t\t\t.filter((r) => r && isNum(r.length))\n\t\t\t\t\t.map((r) => {\n\t\t\t\t\t\tconst { fill, ...rest } = (r.style ?? {}) as VectorTextRunStyle;\n\t\t\t\t\t\treturn { length: r.length, style: { ...patchVectorCharacterStyle({}, rest as Record<string, unknown>, 'runs.style'), ...(fill !== undefined ? { fill } : {}) } };\n\t\t\t\t\t})\n\t\t\t)\n\t\t: null;\n\tconst paragraph = value.paragraph ? patchVectorParagraphStyle({}, value.paragraph as Record<string, unknown>) : null;\n\tconst frame = sanitizeVectorTextFrame(value.frame ?? { kind: 'point', x: 0, y: 0 });\n\treturn { text, font, ...(runs ? { runs } : {}), ...(paragraph && Object.keys(paragraph).length ? { paragraph } : {}), frame };\n}\n\n/** A range of the text from loose input: [start, end) in UTF-16 code units (default the whole text). */\nexport function vectorTextRange(text: string, start: unknown, end: unknown): [number, number] {\n\tconst s = start === undefined ? 0 : start;\n\tconst e = end === undefined ? text.length : end;\n\tif (!Number.isInteger(s) || !Number.isInteger(e) || (s as number) < 0 || (e as number) > text.length || (s as number) > (e as number)) {\n\t\tfail(`start and end must be whole numbers with 0 ≤ start ≤ end ≤ ${text.length} (the text's length in UTF-16 code units), got ${String(start)} and ${String(end)}.`);\n\t}\n\treturn [s as number, e as number];\n}\n\n// ---------------------------------------------------------------------------\n// Edits (pure)\n// ---------------------------------------------------------------------------\n\n/** The node with [start, end) of its text replaced by `insert` (styled like the character before it). */\nexport function replaceVectorText(node: VectorTextNode, start: number, end: number, insert: string): VectorTextNode {\n\tconst clean = insert.replace(/\\r\\n?/g, '\\n');\n\tconst text = node.text.slice(0, start) + clean + node.text.slice(end);\n\tlet runs: VectorTextRun[] | null = null;\n\tif (node.runs?.length) {\n\t\tconst fitted = fitVectorTextRuns(node.runs, node.text.length);\n\t\tconst style = styleAt(fitted, start > 0 ? start - 1 : start, {} as VectorTextRunStyle);\n\t\truns = normalizeVectorTextRuns(text, spliceRuns(fitted, start, end, clean.length, style));\n\t}\n\tconst next: VectorTextNode = { ...node, text };\n\tif (runs) next.runs = runs;\n\telse delete next.runs;\n\treturn next;\n}\n\n/**\n * The node with a character style patch (and `fill`) applied over [start, end). The whole text\n * changes the node's own style (and its `fill`) and drops those fields from its runs.\n */\nexport function styleVectorText(node: VectorTextNode, start: number, end: number, patch: Record<string, unknown>): VectorTextNode {\n\tconst { fill, ...fields } = patch as { fill?: VectorPaint } & Record<string, unknown>;\n\tconst whole = start <= 0 && end >= node.text.length;\n\tif (whole) {\n\t\tlet next: VectorTextNode = { ...node, font: patchVectorCharacterStyle(node.font, fields, 'style') };\n\t\tconst keys = Object.keys(fields).filter((k) => fields[k] !== undefined);\n\t\tif (next.runs?.length && (keys.length || fill !== undefined)) {\n\t\t\tconst runs = normalizeVectorTextRuns(\n\t\t\t\tnext.text,\n\t\t\t\tnext.runs.map((r) => {\n\t\t\t\t\tconst style = { ...r.style } as Record<string, unknown>;\n\t\t\t\t\tfor (const k of keys) delete style[k];\n\t\t\t\t\tif (fill !== undefined) delete style.fill;\n\t\t\t\t\treturn { length: r.length, style: style as VectorTextRunStyle };\n\t\t\t\t})\n\t\t\t);\n\t\t\tnext = { ...next };\n\t\t\tif (runs) next.runs = runs;\n\t\t\telse delete next.runs;\n\t\t}\n\t\tif (fill !== undefined) next = { ...next, fill };\n\t\treturn next;\n\t}\n\tif (end <= start) return node;\n\tconst fitted = fitVectorTextRuns(node.runs ?? [], node.text.length);\n\tconst restyled = restyleRange(fitted.length ? fitted : [{ length: node.text.length, style: {} }], start, end, (s) => {\n\t\tconst own = patchVectorCharacterStyle(s as Partial<VectorCharacterStyle>, fields, 'style') as VectorTextRunStyle;\n\t\t// A field set back to the node's own value is no override.\n\t\tfor (const k of VECTOR_CHARACTER_STYLE_KEYS) if (own[k] !== undefined && own[k] === node.font[k]) delete own[k];\n\t\tconst out: VectorTextRunStyle = { ...own };\n\t\tif (fill !== undefined) {\n\t\t\tif (fill === null && (s as VectorTextRunStyle).fill !== undefined) delete out.fill;\n\t\t\telse out.fill = fill;\n\t\t} else if ((s as VectorTextRunStyle).fill !== undefined) out.fill = (s as VectorTextRunStyle).fill;\n\t\treturn out;\n\t});\n\tconst runs = normalizeVectorTextRuns(node.text, restyled);\n\tconst next: VectorTextNode = { ...node };\n\tif (runs) next.runs = runs;\n\telse delete next.runs;\n\treturn next;\n}\n\n/**\n * The node with scale and skew of `m` baked in (its rigid part goes to `transform` elsewhere): the\n * frame's points map through `m`, font sizes scale by √|det| (text keeps its proportions), and an\n * area's box takes each axis' own scale.\n */\nexport function bakeVectorTextGeometry(node: VectorTextNode, m: AffineMatrix): VectorTextNode {\n\tif (isIdentityMatrix(m)) return node;\n\tconst k = Math.sqrt(Math.abs(m[0] * m[3] - m[1] * m[2])) || 1;\n\tconst scaleStyle = <S extends Partial<VectorCharacterStyle>>(s: S): S => ({\n\t\t...s,\n\t\t...(s.fontSize !== undefined ? { fontSize: s.fontSize * k } : {}),\n\t\t...(s.leading !== undefined ? { leading: s.leading * k } : {}),\n\t\t...(s.baselineShift !== undefined ? { baselineShift: s.baselineShift * k } : {})\n\t});\n\tconst font = scaleStyle(node.font);\n\tconst runs = node.runs?.map((r) => ({ length: r.length, style: scaleStyle(r.style) }));\n\tconst p = node.paragraph;\n\tconst paragraph = p\n\t\t? {\n\t\t\t\t...p,\n\t\t\t\t...(p.firstLineIndent ? { firstLineIndent: p.firstLineIndent * k } : {}),\n\t\t\t\t...(p.startIndent ? { startIndent: p.startIndent * k } : {}),\n\t\t\t\t...(p.endIndent ? { endIndent: p.endIndent * k } : {}),\n\t\t\t\t...(p.spaceBefore ? { spaceBefore: p.spaceBefore * k } : {}),\n\t\t\t\t...(p.spaceAfter ? { spaceAfter: p.spaceAfter * k } : {})\n\t\t\t}\n\t\t: p;\n\tlet frame: VectorTextFrame;\n\tconst f = node.frame;\n\tif (f.kind === 'point') {\n\t\tconst q = applyMatrix(m, f);\n\t\tframe = { kind: 'point', x: q.x, y: q.y };\n\t} else if (f.kind === 'area') {\n\t\tconst q = applyMatrix(m, f);\n\t\tconst sx = Math.hypot(m[0], m[1]);\n\t\tconst sy = Math.hypot(m[2], m[3]);\n\t\tframe = { kind: 'area', x: q.x, y: q.y, width: f.width * sx, height: f.height * sy };\n\t} else {\n\t\tconst map = (v: Vec2) => applyMatrix(m, v);\n\t\tframe = {\n\t\t\t...f,\n\t\t\tpath: { closed: f.path.closed, anchors: f.path.anchors.map((a) => ({ ...a, ...map(a), ...(a.in ? { in: map(a.in) } : {}), ...(a.out ? { out: map(a.out) } : {}) })) },\n\t\t\t...(f.start ? { start: f.start * k } : {}),\n\t\t\t...(f.end ? { end: f.end * k } : {})\n\t\t};\n\t}\n\treturn { ...node, font, ...(runs ? { runs } : {}), ...(paragraph ? { paragraph } : {}), frame };\n}\n\n/** The text of a node as a short name (\"Hello world…\"). */\nexport function vectorTextName(text: string): string {\n\tconst t = text.replace(/\\s+/g, ' ').trim();\n\treturn t ? (t.length > 24 ? `${t.slice(0, 24)}…` : t) : 'Text';\n}\n\n/** Parses loose path data for a path text frame (the first subpath). */\nexport function pathTextFrameFromBezier(path: BezierPath): VectorSubpath | null {\n\tconst cmds = toBezierPath(path);\n\tconst anchors: VectorSubpath['anchors'] = [];\n\tlet closed = false;\n\tfor (const c of cmds) {\n\t\tif (c.type === 'M') {\n\t\t\tif (anchors.length) break;\n\t\t\tanchors.push({ x: c.x, y: c.y });\n\t\t} else if (c.type === 'L') anchors.push({ x: c.x, y: c.y });\n\t\telse if (c.type === 'C') {\n\t\t\tanchors[anchors.length - 1].out = { x: c.x1, y: c.y1 };\n\t\t\tanchors.push({ x: c.x, y: c.y, in: { x: c.x2, y: c.y2 } });\n\t\t} else if (c.type === 'Q') {\n\t\t\tconst p = anchors[anchors.length - 1];\n\t\t\tanchors[anchors.length - 1].out = { x: p.x + ((c.x1 - p.x) * 2) / 3, y: p.y + ((c.y1 - p.y) * 2) / 3 };\n\t\t\tanchors.push({ x: c.x, y: c.y, in: { x: c.x + ((c.x1 - c.x) * 2) / 3, y: c.y + ((c.y1 - c.y) * 2) / 3 } });\n\t\t} else if (c.type === 'Z') {\n\t\t\tclosed = true;\n\t\t\tbreak;\n\t\t}\n\t}\n\treturn anchors.length >= 2 ? { anchors, closed } : null;\n}\n\n/**\n * The outline the editor shows for a text node (hover, selection), node space: an area's box, a\n * path text's path, or a box round each line of point text.\n */\nexport function vectorTextBoxOutline(node: VectorTextNode): BezierPath {\n\tconst f = node.frame;\n\tif (f.kind === 'area') return polygon([{ x: f.x, y: f.y }, { x: f.x + f.width, y: f.y }, { x: f.x + f.width, y: f.y + f.height }, { x: f.x, y: f.y + f.height }]);\n\tif (f.kind === 'path') return subpathPath(f.path);\n\tconst layout = layoutVectorText(node);\n\tconst out: BezierPath = [];\n\tlayout.text.lines.forEach((l, i) => {\n\t\tconst line = layout.lines[i];\n\t\tif (!line) return;\n\t\tconst top = line.baseline - l.ascent;\n\t\tconst bottom = line.baseline + l.descent;\n\t\tconst w = Math.max(l.width, 1);\n\t\tout.push(...polygon([{ x: line.x, y: top }, { x: line.x + w, y: top }, { x: line.x + w, y: bottom }, { x: line.x, y: bottom }]));\n\t});\n\treturn out;\n}\n\n/** One `<tspan>` of text drawn as SVG text: a fragment's characters, each placed on its own. */\nexport interface VectorTextSpan {\n\ttext: string;\n\t/** Per-character origins (node space) and turns (degrees; absent when all are 0). */\n\tx: number[];\n\ty: number[];\n\trotate?: number[];\n\tstyle: VectorCharacterStyle;\n\t/** The family to draw with (the resolved one, a fallback when the family is missing). */\n\tfamily: string;\n\t/** The run's own fill, if it has one. */\n\tfill?: VectorPaint;\n}\n\n/** The text as SVG text spans: one per fragment, every character placed by the layout. */\nexport function vectorTextSpans(node: VectorTextNode): VectorTextSpan[] {\n\tconst layout = layoutVectorText(node);\n\tconst out: VectorTextSpan[] = [];\n\tfor (const f of layout.fragments) {\n\t\tconst glyphs = layout.glyphs.slice(f.from, f.to);\n\t\tif (!glyphs.length) continue;\n\t\tconst turned = glyphs.some((g) => g.angle !== 0);\n\t\tout.push({\n\t\t\ttext: glyphs.map((g) => g.char).join(''),\n\t\t\tx: glyphs.map((g) => g.x),\n\t\t\ty: glyphs.map((g) => g.y),\n\t\t\t...(turned ? { rotate: glyphs.map((g) => g.angle) } : {}),\n\t\t\tstyle: f.style,\n\t\t\tfamily: f.font.family,\n\t\t\t...(f.fill !== undefined ? { fill: f.fill } : {})\n\t\t});\n\t}\n\treturn out;\n}\n\nconst geometryCache = new WeakMap<object, { key: string; node: VectorPathNode }>();\n\n/**\n * The text as one path node in its style: its geometry (glyph outlines, or glyph boxes) and paint\n * stacks. Paint servers and stroke layers of SVG text are computed on it.\n */\nexport function vectorTextGeometryNode(node: VectorTextNode): VectorPathNode {\n\tconst key = `${getVectorTextShaper().id}:${generation}`;\n\tconst hit = geometryCache.get(node);\n\tif (hit && hit.key === key) return hit.node;\n\tconst path = vectorTextPaths(node).parts.flatMap((p) => p.path);\n\tconst out = vectorTextPaintSource(node, undefined, bezierToSubpathsLite(path));\n\tgeometryCache.set(node, { key, node: out });\n\treturn out;\n}\n\n/** Polygon / Bézier commands to subpaths (anchors with absolute handles), without importing geometry. */\nfunction bezierToSubpathsLite(path: BezierPath): VectorSubpath[] {\n\tconst out: VectorSubpath[] = [];\n\tlet cur: VectorSubpath | null = null;\n\tfor (const c of path) {\n\t\tif (c.type === 'M') {\n\t\t\tcur = { anchors: [{ x: c.x, y: c.y }], closed: false };\n\t\t\tout.push(cur);\n\t\t} else if (!cur) continue;\n\t\telse if (c.type === 'L') cur.anchors.push({ x: c.x, y: c.y });\n\t\telse if (c.type === 'C') {\n\t\t\tcur.anchors[cur.anchors.length - 1].out = { x: c.x1, y: c.y1 };\n\t\t\tcur.anchors.push({ x: c.x, y: c.y, in: { x: c.x2, y: c.y2 } });\n\t\t} else if (c.type === 'Q') {\n\t\t\tconst p = cur.anchors[cur.anchors.length - 1];\n\t\t\tp.out = { x: p.x + ((c.x1 - p.x) * 2) / 3, y: p.y + ((c.y1 - p.y) * 2) / 3 };\n\t\t\tcur.anchors.push({ x: c.x, y: c.y, in: { x: c.x + ((c.x1 - c.x) * 2) / 3, y: c.y + ((c.y1 - c.y) * 2) / 3 } });\n\t\t} else if (c.type === 'Z') {\n\t\t\tconst a = cur.anchors;\n\t\t\tif (a.length > 1 && Math.abs(a[0].x - a[a.length - 1].x) < 1e-9 && Math.abs(a[0].y - a[a.length - 1].y) < 1e-9) {\n\t\t\t\tconst last = a.pop()!;\n\t\t\t\tif (last.in) a[0].in = last.in;\n\t\t\t}\n\t\t\tcur.closed = true;\n\t\t}\n\t}\n\treturn out.filter((sp) => sp.anchors.length);\n}\n\n/** One `<tspan>` as render data: per-character positions (space-separated lists) and its font. */\nexport interface VectorRenderTextSpan {\n\ttext: string;\n\tx: string;\n\ty: string;\n\t/** Per-character turns in degrees (text on a path). */\n\trotate?: string;\n\t/** A CSS `font-family` value. */\n\tfontFamily: string;\n\tfontSize: number;\n\tfontWeight: number;\n\tfontStyle?: 'italic';\n\t/** `underline`, `line-through` or both. */\n\ttextDecoration?: string;\n\t/** The run's own fill (a colour or `url(#id)`), for layers with `runFills`. */\n\tfill?: string;\n}\n\nconst fmt = (n: number) => Math.round(n * 1000) / 1000;\n\n/** A span as render data (positions as SVG number lists), with the run's fill as drawn. */\nexport function vectorTextSpanSvg(sp: VectorTextSpan, fill?: string): VectorRenderTextSpan {\n\tconst list = (v: number[]) => v.map(fmt).join(' ');\n\tconst deco = [sp.style.underline ? 'underline' : '', sp.style.strikethrough ? 'line-through' : ''].filter(Boolean).join(' ');\n\treturn {\n\t\ttext: sp.text,\n\t\tx: list(sp.x),\n\t\ty: sp.y.every((v) => v === sp.y[0]) ? String(fmt(sp.y[0])) : list(sp.y),\n\t\t...(sp.rotate ? { rotate: list(sp.rotate) } : {}),\n\t\tfontFamily: cssFontFamily(sp.family),\n\t\tfontSize: sp.style.fontSize,\n\t\tfontWeight: sp.style.fontWeight,\n\t\t...(sp.style.italic ? { fontStyle: 'italic' as const } : {}),\n\t\t...(deco ? { textDecoration: deco } : {}),\n\t\t...(fill !== undefined ? { fill } : {})\n\t};\n}\n","/**\n * Symbols and instances: reusable art (`VectorDocument.symbols`) drawn by `instance` nodes through\n * an affine transform that may scale and skew.\n *\n * The concepts follow vectorcraft's `Symbol { name, art }` and `SymbolInstance { symbol, xf }`\n * (`crates/doc/src/symbols.rs`, MIT OR Apache-2.0, © ArtCraft Team and contributors; see\n * THIRD_PARTY_NOTICES.md): instances measure and draw their symbol's art placed by their own\n * transform, nesting is bounded, and a symbol that would contain itself draws nothing. The\n * resolution and expansion here are our own.\n *\n * Instances carry their symbol's art resolved (`art`, the symbol's own `nodes` array) so that\n * geometry, rendering and export, which see one node at a time, can draw them. The editor resolves\n * after every change (`resolveVectorSymbols`); storage leaves it out (`stripVectorSymbolArt`).\n */\n\nimport { decomposeRigid, isIdentityMatrix, multiplyMatrices } from '../geom/affine.js';\nimport type { AffineMatrix } from '../geom/types.js';\nimport type { VectorDocument, VectorGroupNode, VectorInstanceNode, VectorInstanceOverrides, VectorNode, VectorPaint, VectorStrokeLayer, VectorSymbol } from './types.js';\n\n/** Instances inside symbols nest at most this deep; deeper ones draw nothing. */\nexport const VECTOR_SYMBOL_MAX_DEPTH = 16;\n\nconst visit = (nodes: readonly VectorNode[], fn: (n: VectorNode) => void) => {\n\tfor (const n of nodes) {\n\t\tfn(n);\n\t\tif (n.type === 'group') visit(n.children, fn);\n\t}\n};\n\n/** Ids of the symbols instances in `nodes` use (nested groups included, not through other symbols). */\nexport function vectorSymbolsUsedIn(nodes: readonly VectorNode[]): Set<string> {\n\tconst out = new Set<string>();\n\tvisit(nodes, (n) => {\n\t\tif (n.type === 'instance') out.add(n.symbolId);\n\t});\n\treturn out;\n}\n\n/** Whether symbol `symbolId`'s art reaches symbol `target` through its instances (a cycle when they are the same). */\nexport function vectorSymbolUses(symbols: readonly VectorSymbol[], symbolId: string, target: string): boolean {\n\tconst byId = new Map(symbols.map((s) => [s.id, s]));\n\tconst seen = new Set<string>();\n\tconst walk = (id: string, depth: number): boolean => {\n\t\tif (depth > VECTOR_SYMBOL_MAX_DEPTH || seen.has(id)) return false;\n\t\tseen.add(id);\n\t\tconst sym = byId.get(id);\n\t\tif (!sym) return false;\n\t\tfor (const used of vectorSymbolsUsedIn(sym.nodes)) if (used === target || walk(used, depth + 1)) return true;\n\t\treturn false;\n\t};\n\treturn walk(symbolId, 0);\n}\n\n/**\n * The document with every instance's `art` set to its symbol's art (instances inside symbols\n * included), the same object when nothing changed. An instance of a missing symbol, or one that\n * would draw its own symbol, gets no art.\n */\nexport function resolveVectorSymbols(doc: VectorDocument): VectorDocument {\n\tconst symbols = doc.symbols ?? [];\n\tif (!symbols.length && !hasInstances(doc.nodes)) return doc;\n\t// Symbols first: their own instances resolve to the (resolved) art of the symbols they use.\n\tconst resolved = new Map<string, VectorSymbol>();\n\tconst byId = new Map(symbols.map((s) => [s.id, s]));\n\tconst resolving = new Set<string>();\n\tconst symbolOf = (id: string): VectorSymbol | null => {\n\t\tconst hit = resolved.get(id);\n\t\tif (hit) return hit;\n\t\tconst sym = byId.get(id);\n\t\tif (!sym || resolving.has(id)) return null;\n\t\tresolving.add(id);\n\t\tconst nodes = resolveList(sym.nodes);\n\t\tresolving.delete(id);\n\t\tconst next = nodes === sym.nodes ? sym : { ...sym, nodes };\n\t\tresolved.set(id, next);\n\t\treturn next;\n\t};\n\tconst resolveNode = (n: VectorNode): VectorNode => {\n\t\tif (n.type === 'instance') {\n\t\t\tconst sym = symbolOf(n.symbolId);\n\t\t\tconst art = sym && !resolving.has(n.symbolId) ? sym.nodes : undefined;\n\t\t\tif (n.art === art) return n;\n\t\t\tconst next: VectorInstanceNode = { ...n };\n\t\t\tif (art) next.art = art;\n\t\t\telse delete next.art;\n\t\t\treturn next;\n\t\t}\n\t\tif (n.type === 'group') {\n\t\t\tconst children = resolveList(n.children);\n\t\t\treturn children === n.children ? n : { ...n, children };\n\t\t}\n\t\treturn n;\n\t};\n\tconst resolveList = (list: VectorNode[]): VectorNode[] => {\n\t\tlet changed = false;\n\t\tconst out = list.map((n) => {\n\t\t\tconst r = resolveNode(n);\n\t\t\tif (r !== n) changed = true;\n\t\t\treturn r;\n\t\t});\n\t\treturn changed ? out : list;\n\t};\n\tconst nextSymbols = symbols.map((s) => symbolOf(s.id) ?? s);\n\tconst nodes = resolveList(doc.nodes);\n\tconst symbolsChanged = nextSymbols.some((s, i) => s !== symbols[i]);\n\tif (nodes === doc.nodes && !symbolsChanged) return doc;\n\treturn { ...doc, nodes, ...(doc.symbols ? { symbols: symbolsChanged ? nextSymbols : doc.symbols } : {}) };\n}\n\nfunction hasInstances(nodes: readonly VectorNode[]): boolean {\n\tlet found = false;\n\tvisit(nodes, (n) => {\n\t\tif (n.type === 'instance') found = true;\n\t});\n\treturn found;\n}\n\n/** The document without resolved art on its instances (for storage). */\nexport function stripVectorSymbolArt(doc: VectorDocument): VectorDocument {\n\tconst strip = (list: VectorNode[]): VectorNode[] =>\n\t\tlist.map((n) => {\n\t\t\tif (n.type === 'instance' && n.art) {\n\t\t\t\tconst { art: _a, ...rest } = n;\n\t\t\t\treturn rest;\n\t\t\t}\n\t\t\tif (n.type === 'group') return { ...n, children: strip(n.children) };\n\t\t\treturn n;\n\t\t});\n\treturn { ...doc, nodes: strip(doc.nodes), ...(doc.symbols ? { symbols: doc.symbols.map((s) => ({ ...s, nodes: strip(s.nodes) })) } : {}) };\n}\n\n/** A node's stroke widths (every stroke layer, the shorthand and profiles are relative) times `k`; groups pass it on. */\nexport function scaleVectorStrokeWidths<T extends VectorNode>(node: T, k: number): T {\n\tif (k === 1 || !(k > 0)) return node;\n\tif (node.type === 'group') return { ...node, children: node.children.map((c) => scaleVectorStrokeWidths(c, k)) } as T;\n\tif (node.type === 'instance') return node;\n\tconst out = { ...node } as T & { strokeWidth?: number; stroke?: VectorPaint; strokes?: VectorStrokeLayer[] | null };\n\tif (out.strokeWidth !== undefined || out.stroke) out.strokeWidth = (out.strokeWidth ?? 1) * k;\n\tif (Array.isArray(out.strokes)) out.strokes = out.strokes.map((l) => ({ ...l, strokeWidth: (l.strokeWidth ?? 1) * k }));\n\treturn out;\n}\n\n/** A node's fills and / or strokes all painted with the overrides' paints (groups pass them on). */\nexport function tintVectorNode<T extends VectorNode>(node: T, overrides: Pick<VectorInstanceOverrides, 'fill' | 'stroke'>): T {\n\tif (overrides.fill === undefined && overrides.stroke === undefined) return node;\n\tif (node.type === 'group') return { ...node, children: node.children.map((c) => tintVectorNode(c, overrides)) } as T;\n\tif (node.type === 'instance') {\n\t\tconst own = node.overrides ?? {};\n\t\treturn { ...node, overrides: { ...own, ...(overrides.fill !== undefined ? { fill: overrides.fill } : {}), ...(overrides.stroke !== undefined ? { stroke: overrides.stroke } : {}) } } as T;\n\t}\n\tconst out = { ...node } as T & { fill?: VectorPaint; stroke?: VectorPaint; fills?: { paint: VectorPaint }[] | null; strokes?: { paint: VectorPaint }[] | null };\n\tconst has = (p: VectorPaint | undefined) => p !== undefined && p !== null && p !== 'none';\n\tif (overrides.fill !== undefined) {\n\t\tif (Array.isArray(out.fills)) out.fills = out.fills.map((l) => ({ ...l, paint: overrides.fill! }));\n\t\tif (has(out.fill) || Array.isArray(out.fills)) out.fill = overrides.fill;\n\t}\n\tif (overrides.stroke !== undefined) {\n\t\tif (Array.isArray(out.strokes)) out.strokes = out.strokes.map((l) => ({ ...l, paint: overrides.stroke! }));\n\t\tif (has(out.stroke) || Array.isArray(out.strokes)) out.stroke = overrides.stroke;\n\t}\n\treturn out;\n}\n\n/** Copies of `nodes` with ids prefixed `<prefix>~` (all the way down). */\nexport function prefixVectorIds(nodes: readonly VectorNode[], prefix: string): VectorNode[] {\n\treturn nodes.map((n) => {\n\t\tconst id = `${prefix}~${n.id}`;\n\t\tif (n.type === 'group') return { ...n, id, children: prefixVectorIds(n.children, prefix) };\n\t\treturn { ...n, id };\n\t});\n}\n\n/**\n * What an instance draws, as a plain group in its parent's space: its art placed through its\n * transform (the rotation on the group, scale and skew baked into the art so transforms stay\n * rigid), strokes scaled unless `scaleStrokes` is false, overrides applied, ids `<instance>~<art>`.\n * `bake(node, m)` is `transformVectorNode` (passed in to keep this module below geometry).\n */\nexport function vectorInstanceGroup(node: VectorInstanceNode, bake: (n: VectorNode, m: AffineMatrix) => VectorNode): VectorGroupNode {\n\tconst m = (node.transform ?? [1, 0, 0, 1, 0, 0]) as AffineMatrix;\n\tconst { rigid, residual } = decomposeRigid(m);\n\tconst k = Math.sqrt(Math.abs(residual[0] * residual[3] - residual[1] * residual[2]));\n\tconst hidden = new Set(node.overrides?.hidden ?? []);\n\tconst keep = (list: readonly VectorNode[]): VectorNode[] =>\n\t\tlist.filter((n) => !hidden.has(n.id)).map((n) => (n.type === 'group' ? { ...n, children: keep(n.children) } : n));\n\tlet children = prefixVectorIds(keep(node.art ?? []), node.id);\n\tif (!isIdentityMatrix(residual)) children = children.map((c) => bake(c, residual));\n\tif (node.scaleStrokes !== false && Math.abs(k - 1) > 1e-12) children = children.map((c) => scaleVectorStrokeWidths(c, k));\n\tif (node.overrides && (node.overrides.fill !== undefined || node.overrides.stroke !== undefined)) children = children.map((c) => tintVectorNode(c, node.overrides!));\n\tconst group: VectorGroupNode = { id: node.id, type: 'group', children };\n\tif (!isIdentityMatrix(rigid)) group.transform = rigid;\n\tif (node.name !== undefined) group.name = node.name;\n\tif (node.visible === false) group.visible = false;\n\tif (node.locked) group.locked = true;\n\tif (node.opacity !== undefined) group.opacity = node.opacity;\n\tif (node.blendMode) group.blendMode = node.blendMode;\n\tif (node.filters?.length) group.filters = node.filters;\n\tif (node.effects?.length) group.effects = node.effects;\n\tif (node.booleanOperation) group.booleanOperation = node.booleanOperation;\n\tif (node.blendStep) group.blendStep = true;\n\treturn group;\n}\n\n/** `a` then `b` (re-exported for callers that place art). */\nexport const composeVectorMatrices = (a: AffineMatrix, b: AffineMatrix): AffineMatrix => multiplyMatrices(a, b);\n","/**\n * Warp geometry shared by the vector editor's envelopes and the image editor's Free Transform\n * warp: preset warp styles and editable Bézier meshes, both forward maps from a source box onto\n * the plane.\n *\n * - **Presets** (`WarpStyle`, Photoshop's fifteen with bend and horizontal / vertical distortion\n * in percent): each is one bicubic Bézier patch whose 4 × 4 control grid follows the bend\n * (`warpPresetGrid`). Every preset is the identity at bend 0 and continuous in it.\n * - **Meshes** (`WarpMesh`): a grid of bicubic patches. Splitting a mesh (`splitWarpMeshU` / `V`)\n * is an exact de Casteljau subdivision, so it never changes the shape, and a preset turns into\n * an editable mesh of any size exactly.\n *\n * Ported from ArtCraft (MIT OR Apache-2.0, © ArtCraft Team and contributors; see\n * THIRD_PARTY_NOTICES.md): photocraft `crates/geom/src/warp.rs` (`WarpStyle`, `StyleWarp`,\n * `rest_grid`, `edge_arc`, `arc_grid`, `blend_rows`, `preset_grid`, `bernstein`, `split_cubic`,\n * `BERN_INV`, and `BezierMesh`: `identity`, `fit`, `eval`, `split_u`, `split_v`, `remove_split_u`,\n * `transpose`, `map_points`, `param_at`, `pull`, `smooth_lines`, `drag_point`, `control_bounds`;\n * `Warp::map` and `Warp::to_mesh`).\n */\nimport type { Box, Vec2, WarpMesh, WarpStyle } from './types';\n\nexport type { WarpMesh, WarpStyle };\n\ntype P = [number, number];\n/** A single patch's control grid, `[row][column]`, in box units (0–1, y down). */\ntype Grid = P[][];\n\n/** The fifteen presets in Photoshop's menu order. */\nexport const WARP_STYLES: readonly WarpStyle[] = [\n 'arc',\n 'arcLower',\n 'arcUpper',\n 'arch',\n 'bulge',\n 'shellLower',\n 'shellUpper',\n 'flag',\n 'wave',\n 'fish',\n 'rise',\n 'fisheye',\n 'inflate',\n 'squeeze',\n 'twist'\n];\n\nexport const WARP_STYLE_LABELS: Readonly<Record<WarpStyle, string>> = {\n arc: 'Arc',\n arcLower: 'Arc Lower',\n arcUpper: 'Arc Upper',\n arch: 'Arch',\n bulge: 'Bulge',\n shellLower: 'Shell Lower',\n shellUpper: 'Shell Upper',\n flag: 'Flag',\n wave: 'Wave',\n fish: 'Fish',\n rise: 'Rise',\n fisheye: 'Fisheye',\n inflate: 'Inflate',\n squeeze: 'Squeeze',\n twist: 'Twist'\n};\n\n/** The rest grid (no warp). */\nfunction restGrid(): Grid {\n return [0, 1, 2, 3].map((j) => [0, 1, 2, 3].map((i): P => [i / 3, j / 3]));\n}\n\n/**\n * A horizontal edge at height `y` (box units, 0–1 across) bent into a circular arc of `|b|·π`\n * that keeps its chord, bowing up when `up === (b > 0)`. `h` is the box's height over its width,\n * so the arc is circular in pixels.\n */\nfunction edgeArc(y: number, b: number, up: boolean, h: number): P[] {\n if (Math.abs(b) < 1e-9) return [0, 1, 2, 3].map((i): P => [i / 3, y]);\n const th = Math.abs(b) * Math.PI;\n const k = (((4 / 3) * Math.tan(th / 4)) * 0.5) / Math.sin(th / 2);\n const s = b > 0 === up ? -1 : 1;\n const c = Math.cos(th / 2);\n const n = Math.sin(th / 2);\n const dy = (s * k * n) / h;\n return [\n [0, y],\n [k * c, y + dy],\n [1 - k * c, y + dy],\n [1, y]\n ];\n}\n\n/**\n * Arc: every row is a circular arc of `|b|·π` around one centre; the edge on the inside of the\n * bend keeps its chord and the rows' radii grow by the box height towards the other edge. Worked\n * in units of the box width (`h` = height / width) so the arcs are circular in pixels.\n */\nfunction arcGrid(b: number, h: number): Grid {\n if (Math.abs(b) < 1e-9) return restGrid();\n const up = b > 0;\n const th = Math.abs(b) * Math.PI;\n const r = 0.5 / Math.sin(th / 2);\n const k = (4 / 3) * Math.tan(th / 4);\n const s = up ? -1 : 1;\n const cy = up ? h + r * Math.cos(th / 2) : -r * Math.cos(th / 2);\n return [0, 1, 2, 3].map((j) => {\n const v = j / 3;\n const big = r + h * (up ? 1 - v : v);\n const at = (a: number): P => [0.5 + big * Math.sin(a), cy + s * big * Math.cos(a)];\n const tangent = (a: number): P => [Math.cos(a), -s * Math.sin(a)];\n const p0 = at(-th / 2);\n const p3 = at(th / 2);\n const t0 = tangent(-th / 2);\n const t1 = tangent(th / 2);\n const l = k * big;\n const pts: P[] = [p0, [p0[0] + l * t0[0], p0[1] + l * t0[1]], [p3[0] - l * t1[0], p3[1] - l * t1[1]], p3];\n return pts.map((p): P => [p[0], p[1] / h]);\n });\n}\n\n/** Rows blended from `top` to `bottom`. */\nfunction blendRows(top: P[], bottom: P[]): Grid {\n return [0, 1, 2, 3].map((j) => {\n const t = j / 3;\n return [0, 1, 2, 3].map((i): P => [top[i][0] + (bottom[i][0] - top[i][0]) * t, top[i][1] + (bottom[i][1] - top[i][1]) * t]);\n });\n}\n\nconst INNER: [number, number, number, number][] = [\n [1, 1, -1, -1],\n [1, 2, 1, -1],\n [2, 1, -1, 1],\n [2, 2, 1, 1]\n];\n\n/**\n * A preset as a Bézier control grid (rows of `[x, y]` in box units, y down). `b`, `hd`, `vd` are\n * the bend and the horizontal / vertical distortion as fractions (−1…1); `aspect` is the box's\n * height over its width. The arc family stays circular in pixels, the other offsets scale with the\n * box, and a vertical warp is the horizontal one with the axes (and distortions) swapped.\n */\nexport function warpPresetGrid(style: WarpStyle, b: number, hd: number, vd: number, vertical: boolean, aspect: number): [number, number][][] {\n // Height over width of the box the bend runs along (the transposed box when vertical); in that\n // frame the two distortions trade places too.\n const h = vertical ? 1 / aspect : aspect;\n if (vertical) [hd, vd] = [vd, hd];\n let g = restGrid();\n switch (style) {\n case 'arc':\n g = arcGrid(b, h);\n break;\n case 'arch':\n g = [0, 1, 2, 3].map((j) => edgeArc(j / 3, b, true, h));\n break;\n case 'bulge':\n g = blendRows(edgeArc(0, b, true, h), edgeArc(1, b, false, h));\n break;\n case 'arcLower':\n g = blendRows(g[0], edgeArc(1, b, false, h));\n break;\n case 'arcUpper':\n g = blendRows(edgeArc(0, b, true, h), g[3]);\n break;\n // The bulging edge and the outer points of the row next to it come from Arc (bent the other\n // way for Shell Lower); the rest stays put.\n case 'shellLower': {\n const a = arcGrid(-b, h);\n g[3] = a[3];\n g[2][0] = a[2][0];\n g[2][3] = a[2][3];\n break;\n }\n case 'shellUpper': {\n const a = arcGrid(b, h);\n g[0] = a[0];\n g[1][0] = a[1][0];\n g[1][3] = a[1][3];\n break;\n }\n case 'flag':\n for (const row of g) {\n row[1][1] -= 2 * b;\n row[2][1] += 2 * b;\n }\n break;\n case 'wave':\n for (const row of g.slice(1, 3)) {\n row[1][1] += (4 / 3) * b;\n row[2][1] -= (4 / 3) * b;\n }\n break;\n case 'fish':\n [-2, -2 / 3, 2 / 3, 2].forEach((f, j) => {\n g[j][1][1] += f * b;\n g[j][2][1] -= f * b;\n });\n break;\n case 'rise':\n for (const row of g) {\n row[0][1] += 2 * b;\n row[1][1] += 2 * b;\n }\n break;\n case 'fisheye':\n for (const [j, i, dx, dy] of INNER) {\n g[j][i][0] += (dx * 2 * b) / 3;\n g[j][i][1] += (dy * 2 * b) / 3;\n }\n break;\n // Edge midpoints move out (Inflate) or the sides in (Squeeze) by b/3, the inner points by b/9.\n case 'inflate':\n case 'squeeze': {\n const s = style === 'inflate' ? 1 : -1;\n for (const p of g[0].slice(1, 3)) p[1] -= b / 3;\n for (const p of g[3].slice(1, 3)) p[1] += b / 3;\n for (const row of g.slice(1, 3)) {\n row[0][0] -= (s * b) / 3;\n row[3][0] += (s * b) / 3;\n }\n for (const [j, i, dx, dy] of INNER) {\n g[j][i][0] += (s * dx * b) / 9;\n g[j][i][1] += (dy * b) / 9;\n }\n break;\n }\n // The inner points turn round the centre (the other way for a negative bend).\n case 'twist': {\n const a = Math.abs(b);\n if (b >= 0) {\n g[1][1][0] += a;\n g[1][2][1] += a;\n g[2][1][1] -= a;\n g[2][2][0] -= a;\n } else {\n g[1][1][1] += a;\n g[1][2][0] -= a;\n g[2][1][0] += a;\n g[2][2][1] -= a;\n }\n break;\n }\n }\n // Vertical distortion: the top and bottom rows scale about their end points' midpoint (by\n // 1 ∓ vd) and the middle rows follow by the blend of those two moves.\n if (vd !== 0) {\n const moved = (row: P[], s: number): P[] => {\n const m: P = [(row[0][0] + row[3][0]) / 2, (row[0][1] + row[3][1]) / 2];\n return row.map((p): P => [m[0] + (p[0] - m[0]) * s - p[0], m[1] + (p[1] - m[1]) * s - p[1]]);\n };\n const d0 = moved(g[0], 1 - vd);\n const d3 = moved(g[3], 1 + vd);\n g.forEach((row, j) => {\n const t = j / 3;\n row.forEach((p, i) => {\n p[0] += d0[i][0] + (d3[i][0] - d0[i][0]) * t;\n p[1] += d0[i][1] + (d3[i][1] - d0[i][1]) * t;\n });\n });\n }\n // Horizontal distortion: each column scales about its end points' midpoint by 1 + hd·(2i/3 − 1).\n if (hd !== 0) {\n for (let i = 0; i < 4; i++) {\n const s = 1 + hd * ((2 * i) / 3 - 1);\n const m: P = [(g[0][i][0] + g[3][i][0]) / 2, (g[0][i][1] + g[3][i][1]) / 2];\n for (const row of g) row[i] = [m[0] + (row[i][0] - m[0]) * s, m[1] + (row[i][1] - m[1]) * s];\n }\n }\n // Vertical orientation: the same grid with the axes swapped.\n if (vertical) g = [0, 1, 2, 3].map((j) => [0, 1, 2, 3].map((i): P => [g[i][j][1], g[i][j][0]]));\n return g;\n}\n\nfunction bernstein(t: number): [number, number, number, number] {\n const s = 1 - t;\n return [s * s * s, 3 * s * s * t, 3 * s * t * t, t * t * t];\n}\n\nexport const lerpVec2 = (a: Vec2, b: Vec2, t: number): Vec2 => ({ x: a.x + (b.x - a.x) * t, y: a.y + (b.y - a.y) * t });\n\n/** De Casteljau split of a cubic at `t`: 7 points (left 0..3, right 3..6). */\nfunction splitCubic(p: readonly Vec2[], t: number): Vec2[] {\n const a = lerpVec2(p[0], p[1], t);\n const b = lerpVec2(p[1], p[2], t);\n const c = lerpVec2(p[2], p[3], t);\n const d = lerpVec2(a, b, t);\n const e = lerpVec2(b, c, t);\n return [p[0], a, d, lerpVec2(d, e, t), e, c, p[3]];\n}\n\n/** Inverse of the Bernstein interpolation matrix at t = 0, ⅓, ⅔, 1 (rows: control point, columns: sample). */\nconst BERN_INV = [\n [1, 0, 0, 0],\n [-5 / 6, 3, -1.5, 1 / 3],\n [1 / 3, -1.5, 3, -5 / 6],\n [0, 0, 0, 1]\n];\n\n// ---------------------------------------------------------------------------\n// Presets\n// ---------------------------------------------------------------------------\n\n/** A preset warp's settings (bend and distortions in percent, −100…100). */\nexport interface WarpPreset {\n style: WarpStyle;\n bend: number;\n horizontal?: number;\n vertical?: number;\n /** Bend along the vertical axis. */\n orientation?: 'horizontal' | 'vertical';\n}\n\nconst pct = (v: number | undefined) => (typeof v === 'number' && Number.isFinite(v) ? Math.min(1, Math.max(-1, v / 100)) : 0);\n\n/**\n * A preset as one Bézier patch over `bounds` (points in the bounds' space), or null when it\n * changes nothing (an unknown style, all-zero amounts, or an empty box).\n */\nexport function warpPresetMesh(preset: WarpPreset, bounds: Box): WarpMesh | null {\n if (!WARP_STYLES.includes(preset.style)) return null;\n const { x, y, width: w, height: h } = bounds;\n if (!(w > 0 && h > 0)) return null;\n const b = pct(preset.bend);\n const hd = pct(preset.horizontal);\n const vd = pct(preset.vertical);\n if (b === 0 && hd === 0 && vd === 0) return null;\n const grid = warpPresetGrid(preset.style, b, hd, vd, preset.orientation === 'vertical', h / w);\n return { us: [0, 1], vs: [0, 1], points: grid.flat().map((p) => ({ x: x + p[0] * w, y: y + p[1] * h })) };\n}\n\n// ---------------------------------------------------------------------------\n// Meshes\n// ---------------------------------------------------------------------------\n\n/** Control points per row. */\nexport const warpMeshColumns = (m: WarpMesh) => 3 * (m.us.length - 1) + 1;\n/** Control point rows. */\nexport const warpMeshRows = (m: WarpMesh) => 3 * (m.vs.length - 1) + 1;\n\n/** Whether a mesh is well formed: knots from 0 to 1 increasing, the right number of finite points. */\nexport function isValidWarpMesh(m: unknown): m is WarpMesh {\n if (!m || typeof m !== 'object') return false;\n const { us, vs, points } = m as WarpMesh;\n const knots = (k: unknown): k is number[] =>\n Array.isArray(k) && k.length >= 2 && k.length <= 65 && k[0] === 0 && k[k.length - 1] === 1 && k.every((v, i) => typeof v === 'number' && (i === 0 || v > k[i - 1]));\n if (!knots(us) || !knots(vs) || !Array.isArray(points)) return false;\n return points.length === (3 * (us.length - 1) + 1) * (3 * (vs.length - 1) + 1) && points.every((p) => !!p && Number.isFinite(p.x) && Number.isFinite(p.y));\n}\n\n/** Fits a mesh with patch boundaries `us` / `vs` to the map `f` (box fractions → output) by interpolating it at each patch's thirds. Exact for bicubic maps (affine maps included). */\nexport function fitWarpMesh(f: (s: number, t: number) => Vec2, us: readonly number[], vs: readonly number[]): WarpMesh {\n const pc = us.length - 1;\n const pr = vs.length - 1;\n const nx = 3 * pc + 1;\n const points: Vec2[] = new Array((3 * pr + 1) * nx);\n for (let pj = 0; pj < pr; pj++) {\n for (let pi = 0; pi < pc; pi++) {\n const s: Vec2[][] = [0, 1, 2, 3].map((j) =>\n [0, 1, 2, 3].map((i) => f(us[pi] + ((us[pi + 1] - us[pi]) * i) / 3, vs[pj] + ((vs[pj + 1] - vs[pj]) * j) / 3))\n );\n for (let j = 0; j < 4; j++) {\n for (let i = 0; i < 4; i++) {\n let x = 0;\n let y = 0;\n for (let a = 0; a < 4; a++) {\n for (let b = 0; b < 4; b++) {\n const k = BERN_INV[j][a] * BERN_INV[i][b];\n x += k * s[a][b].x;\n y += k * s[a][b].y;\n }\n }\n points[(3 * pj + j) * nx + 3 * pi + i] = { x, y };\n }\n }\n }\n }\n return { us: us.slice(), vs: vs.slice(), points };\n}\n\n/** `n + 1` evenly spaced knots from 0 to 1. */\nexport const evenKnots = (n: number) => Array.from({ length: n + 1 }, (_, i) => i / n);\n/** A patch count rounded and clamped to 1–64. */\nexport const clampMeshCount = (n: number) => Math.min(64, Math.max(1, Math.round(Number.isFinite(n) ? n : 1)));\n\n/** The identity mesh over `bounds` with `columns × rows` patches. */\nexport function identityWarpMesh(bounds: Box, columns = 1, rows = 1): WarpMesh {\n return fitWarpMesh((s, t) => ({ x: bounds.x + s * bounds.width, y: bounds.y + t * bounds.height }), evenKnots(clampMeshCount(columns)), evenKnots(clampMeshCount(rows)));\n}\n\n/**\n * The patch holding box fraction `s` and the parameter inside it. Outside 0–1 the end patches\n * extrapolate (their polynomials continue), so handles past the box map smoothly.\n */\nfunction locate(knots: readonly number[], s: number): [number, number] {\n const n = knots.length - 1;\n let i = 0;\n while (i + 1 < n && s > knots[i + 1]) i++;\n const w = knots[i + 1] - knots[i];\n return [i, w > 0 ? (s - knots[i]) / w : 0];\n}\n\n/** The surface at box fractions `(s, t)`. */\nexport function evalWarpMesh(m: WarpMesh, s: number, t: number): Vec2 {\n const [pi, a] = locate(m.us, s);\n const [pj, b] = locate(m.vs, t);\n const ba = bernstein(a);\n const bb = bernstein(b);\n const nx = warpMeshColumns(m);\n let x = 0;\n let y = 0;\n for (let j = 0; j < 4; j++) {\n for (let i = 0; i < 4; i++) {\n const p = m.points[(3 * pj + j) * nx + 3 * pi + i];\n const k = ba[i] * bb[j];\n x += p.x * k;\n y += p.y * k;\n }\n }\n return { x, y };\n}\n\nfunction transposeMesh(m: WarpMesh): WarpMesh {\n const nx = warpMeshColumns(m);\n const ny = warpMeshRows(m);\n const points: Vec2[] = new Array(nx * ny);\n for (let j = 0; j < ny; j++) for (let i = 0; i < nx; i++) points[i * ny + j] = m.points[j * nx + i];\n return { us: m.vs.slice(), vs: m.us.slice(), points };\n}\n\n/** The mesh with the patch column holding `s` split at `s` (exact). Null when `s` is on or too close to a boundary. */\nexport function splitWarpMeshU(m: WarpMesh, s: number): WarpMesh | null {\n const [pi, a] = locate(m.us, s);\n if (!(a >= 0.01 && a <= 0.99)) return null;\n const nx = warpMeshColumns(m);\n const ny = warpMeshRows(m);\n const points: Vec2[] = [];\n for (let j = 0; j < ny; j++) {\n const row = m.points.slice(j * nx, (j + 1) * nx);\n points.push(...row.slice(0, 3 * pi), ...splitCubic(row.slice(3 * pi, 3 * pi + 4), a), ...row.slice(3 * pi + 4));\n }\n const us = m.us.slice();\n us.splice(pi + 1, 0, Math.min(1, Math.max(0, s)));\n return { us, vs: m.vs.slice(), points };\n}\n\n/** The mesh with the patch row holding `t` split at `t` (exact). */\nexport function splitWarpMeshV(m: WarpMesh, t: number): WarpMesh | null {\n const out = splitWarpMeshU(transposeMesh(m), t);\n return out && transposeMesh(out);\n}\n\n/**\n * The mesh without interior vertical boundary `k` (1 … us.length − 2), its two patch columns\n * merged: exact when they came from an unedited split; otherwise the outer control points stay and\n * the inner handles are extrapolated.\n */\nexport function removeWarpMeshSplitU(m: WarpMesh, k: number): WarpMesh | null {\n if (k <= 0 || k + 1 >= m.us.length) return null;\n const a = (m.us[k] - m.us[k - 1]) / (m.us[k + 1] - m.us[k - 1]);\n const nx = warpMeshColumns(m);\n const ny = warpMeshRows(m);\n const c0 = 3 * (k - 1);\n const points: Vec2[] = [];\n for (let j = 0; j < ny; j++) {\n const row = m.points.slice(j * nx, (j + 1) * nx);\n const [p0, q1, r2, p3] = [row[c0], row[c0 + 1], row[c0 + 5], row[c0 + 6]];\n // De Casteljau inverse: q1 = lerpVec2(p0, p1, a), r2 = lerpVec2(p2, p3, a).\n const p1 = { x: (q1.x - (1 - a) * p0.x) / a, y: (q1.y - (1 - a) * p0.y) / a };\n const p2 = { x: (r2.x - a * p3.x) / (1 - a), y: (r2.y - a * p3.y) / (1 - a) };\n points.push(...row.slice(0, c0), p0, p1, p2, p3, ...row.slice(c0 + 7));\n }\n const us = m.us.slice();\n us.splice(k, 1);\n return { us, vs: m.vs.slice(), points };\n}\n\n/** Removes interior horizontal boundary `k`. */\nexport function removeWarpMeshSplitV(m: WarpMesh, k: number): WarpMesh | null {\n const out = removeWarpMeshSplitU(transposeMesh(m), k);\n return out && transposeMesh(out);\n}\n\n/** Every control point through `f` (exact for affine maps). */\nexport function mapWarpMeshPoints(m: WarpMesh, f: (p: Vec2) => Vec2): WarpMesh {\n return { us: m.us.slice(), vs: m.vs.slice(), points: m.points.map((p) => f(p)) };\n}\n\n/**\n * The mesh with `columns × rows` patches over the same surface: split exactly when its knots are\n * a subset of the new even ones (a one-patch mesh always is), otherwise refitted.\n */\nexport function resizeWarpMesh(m: WarpMesh, columns: number, rows: number): WarpMesh {\n const cols = clampMeshCount(columns);\n const rws = clampMeshCount(rows);\n if (m.us.length - 1 === cols && m.vs.length - 1 === rws) return m;\n const us = evenKnots(cols);\n const vs = evenKnots(rws);\n const has = (list: number[], v: number) => list.some((k) => Math.abs(k - v) < 1e-12);\n if (m.us.every((u) => has(us, u)) && m.vs.every((v) => has(vs, v))) {\n let out: WarpMesh | null = m;\n for (const u of us) if (!has(out.us, u)) out = splitWarpMeshU(out, u) ?? out;\n for (const v of vs) if (!has(out.vs, v)) out = splitWarpMeshV(out, v) ?? out;\n return out;\n }\n return fitWarpMesh((s, t) => evalWarpMesh(m, s, t), us, vs);\n}\n\n/** Bounding box of the control points (the surface lies inside it). */\nexport function warpMeshControlBounds(m: WarpMesh): Box {\n let minX = Infinity;\n let minY = Infinity;\n let maxX = -Infinity;\n let maxY = -Infinity;\n for (const p of m.points) {\n minX = Math.min(minX, p.x);\n minY = Math.min(minY, p.y);\n maxX = Math.max(maxX, p.x);\n maxY = Math.max(maxY, p.y);\n }\n return { x: minX, y: minY, width: maxX - minX, height: maxY - minY };\n}\n\n/** Box fractions `(s, t)` whose surface point is nearest `p` (a coarse search, then Newton steps). */\nexport function warpMeshParamAt(m: WarpMesh, p: Vec2): { s: number; t: number; distance: number } {\n const n = 48;\n let best = { s: 0.5, t: 0.5, d: Infinity };\n for (let j = 0; j <= n; j++) {\n for (let i = 0; i <= n; i++) {\n const q = evalWarpMesh(m, i / n, j / n);\n const d = (q.x - p.x) ** 2 + (q.y - p.y) ** 2;\n if (d < best.d) best = { s: i / n, t: j / n, d };\n }\n }\n let { s, t } = best;\n for (let k = 0; k < 12; k++) {\n const h = 1e-5;\n const q = evalWarpMesh(m, s, t);\n const qs = evalWarpMesh(m, s + h, t);\n const qt = evalWarpMesh(m, s, t + h);\n const a = (qs.x - q.x) / h;\n const b = (qt.x - q.x) / h;\n const c = (qs.y - q.y) / h;\n const d = (qt.y - q.y) / h;\n const det = a * d - b * c;\n if (Math.abs(det) < 1e-12) break;\n const ex = p.x - q.x;\n const ey = p.y - q.y;\n s = Math.min(1, Math.max(0, s + (d * ex - b * ey) / det));\n t = Math.min(1, Math.max(0, t + (a * ey - c * ex) / det));\n }\n const q = evalWarpMesh(m, s, t);\n return { s, t, distance: Math.hypot(q.x - p.x, q.y - p.y) };\n}\n\n/**\n * Makes the tangent equal on both sides of every interior grid line for the control points in\n * columns `i0..i1` and rows `j0..j1` (exclusive ends): each pair of handles takes the average of\n * the two tangents it had. In place.\n */\nfunction smoothLines(m: WarpMesh, i0: number, i1: number, j0: number, j1: number) {\n const nx = warpMeshColumns(m);\n i1 = Math.min(i1, nx);\n j1 = Math.min(j1, warpMeshRows(m));\n const triples: [number, number, number, number, number][] = [];\n for (let a = 1; a < m.us.length - 1; a++) {\n if (3 * a >= i0 && 3 * a < i1)\n for (let j = j0; j < j1; j++) triples.push([j * nx + 3 * a - 1, j * nx + 3 * a, j * nx + 3 * a + 1, m.us[a] - m.us[a - 1], m.us[a + 1] - m.us[a]]);\n }\n for (let b = 1; b < m.vs.length - 1; b++) {\n if (3 * b >= j0 && 3 * b < j1)\n for (let i = i0; i < i1; i++) triples.push([(3 * b - 1) * nx + i, 3 * b * nx + i, (3 * b + 1) * nx + i, m.vs[b] - m.vs[b - 1], m.vs[b + 1] - m.vs[b]]);\n }\n for (const [l, c, r, hl, hr] of triples) {\n const pl = m.points[l];\n const pc = m.points[c];\n const pr = m.points[r];\n const tx = ((pc.x - pl.x) / hl + (pr.x - pc.x) / hr) / 2;\n const ty = ((pc.y - pl.y) / hl + (pr.y - pc.y) / hr) / 2;\n m.points[l] = { x: pc.x - tx * hl, y: pc.y - ty * hl };\n m.points[r] = { x: pc.x + tx * hr, y: pc.y + ty * hr };\n }\n}\n\n/**\n * `base` with control point `index` dragged by `d`, keeping the surface smooth across the grid\n * lines: an anchor moves with the eight points around it as one block; a handle moves with the two\n * points beside it across its line, and the handle opposite it on the same anchor turns the other\n * way (with its two neighbours), so the line keeps passing straight through the anchor. An inner\n * point of a patch moves alone.\n */\nexport function dragWarpMeshPoint(base: WarpMesh, index: number, d: Vec2): WarpMesh {\n if (index < 0 || index >= base.points.length || !Number.isFinite(d.x) || !Number.isFinite(d.y)) return base;\n const out: WarpMesh = { us: base.us.slice(), vs: base.vs.slice(), points: base.points.slice() };\n const nx = warpMeshColumns(base);\n const ny = warpMeshRows(base);\n const i = index % nx;\n const j = Math.floor(index / nx);\n const shift = (ii: number, jj: number, v: Vec2) => {\n if (ii < 0 || jj < 0 || ii >= nx || jj >= ny) return;\n const p = out.points[jj * nx + ii];\n out.points[jj * nx + ii] = { x: p.x + v.x, y: p.y + v.y };\n };\n // Spans either side of interior knot `k`.\n const span = (knots: number[], k: number): [number, number] | null => (k > 0 && k + 1 < knots.length ? [knots[k] - knots[k - 1], knots[k + 1] - knots[k]] : null);\n const ri = i % 3;\n const rj = j % 3;\n if (ri === 0 && rj === 0) {\n for (let dj = -1; dj <= 1; dj++) for (let di = -1; di <= 1; di++) shift(i + di, j + dj, d);\n } else if (ri === 0) {\n // A handle along a vertical line: it takes the two points beside it across the line.\n for (let di = -1; di <= 1; di++) shift(i + di, j, d);\n // The opposite handle of the same anchor turns the other way.\n const sp = span(base.vs, Math.floor(j / 3) + (rj === 2 ? 1 : 0));\n if (sp) {\n const [other, k] = rj === 1 ? [j - 2, sp[0] / sp[1]] : [j + 2, sp[1] / sp[0]];\n for (let di = -1; di <= 1; di++) shift(i + di, other, { x: -d.x * k, y: -d.y * k });\n }\n } else if (rj === 0) {\n // A handle along a horizontal line, likewise.\n for (let dj = -1; dj <= 1; dj++) shift(i, j + dj, d);\n const sp = span(base.us, Math.floor(i / 3) + (ri === 2 ? 1 : 0));\n if (sp) {\n const [other, k] = ri === 1 ? [i - 2, sp[0] / sp[1]] : [i + 2, sp[1] / sp[0]];\n for (let dj = -1; dj <= 1; dj++) shift(other, j + dj, { x: -d.x * k, y: -d.y * k });\n }\n } else shift(i, j, d);\n return out;\n}\n\n/**\n * `base` with its surface point at box fractions `(s, t)` pulled by `d`, the way dragging inside a\n * patch works: interior anchors within about two cells follow by a share of `d` that fades with\n * distance (each with its block of handles, so grid lines stay smooth); the outer border stays\n * pinned unless the grab is near it, and then it bows; the four corners never move. The grabbed\n * patch's inner points (and, near the border, the border's handles) make up the rest, so the\n * grabbed point lands exactly at its start + `d`.\n */\nexport function pullWarpMesh(base: WarpMesh, s: number, t: number, d: Vec2): WarpMesh {\n /** Within this distance of the border (box fractions) a grab starts to drag the border with it. */\n const BORDER_ZONE = 0.12;\n /** Falloff radius, in the grabbed patch's size. */\n const REACH = 1.8;\n if (!Number.isFinite(d.x) || !Number.isFinite(d.y)) return base;\n const m: WarpMesh = { us: base.us.slice(), vs: base.vs.slice(), points: base.points.slice() };\n const cols = m.us.length - 1;\n const rows = m.vs.length - 1;\n const [pi, a] = locate(m.us, s);\n const [pj, b] = locate(m.vs, t);\n const ba = bernstein(a);\n const bb = bernstein(b);\n const nx = warpMeshColumns(m);\n const ny = warpMeshRows(m);\n const anchor = (ai: number, aj: number) => base.points[3 * aj * nx + 3 * ai] ?? { x: 0, y: 0 };\n const at0 = evalWarpMesh(base, s, t);\n const target = { x: at0.x + d.x, y: at0.y + d.y };\n // The grabbed patch's size and how far inside it the grab is (1 in the middle, 0 on its edges).\n let size = 1;\n for (const k of ['x', 'y'] as const) {\n const vals = [anchor(pi, pj)[k], anchor(pi + 1, pj)[k], anchor(pi, pj + 1)[k], anchor(pi + 1, pj + 1)[k]];\n size = Math.max(size, Math.max(...vals) - Math.min(...vals));\n }\n const radius = REACH * size;\n const innerW = (ba[1] + ba[2]) * (bb[1] + bb[2]);\n const interior = Math.min(1, Math.max(0, innerW / 0.5625));\n const toBorder = Math.min(s, 1 - s, t, 1 - t);\n const nearBorder = Math.min(1, Math.max(0, 1 - toBorder / BORDER_ZONE));\n const meshCorner = (ai: number, aj: number) => (ai === 0 || ai === cols) && (aj === 0 || aj === rows);\n const onBorder = (ai: number, aj: number) => ai === 0 || ai === cols || aj === 0 || aj === rows;\n const reach = (ai: number, aj: number, wa: number, wb: number) => (meshCorner(ai, aj) ? 0 : wa * wb * (onBorder(ai, aj) ? nearBorder : 1));\n const corner: [number, number, number][] = [\n [pi, pj, reach(pi, pj, ba[0] + ba[1], bb[0] + bb[1])],\n [pi + 1, pj, reach(pi + 1, pj, ba[2] + ba[3], bb[0] + bb[1])],\n [pi, pj + 1, reach(pi, pj + 1, ba[0] + ba[1], bb[2] + bb[3])],\n [pi + 1, pj + 1, reach(pi + 1, pj + 1, ba[2] + ba[3], bb[2] + bb[3])]\n ];\n // Share of `d` for each anchor.\n const share = new Array((cols + 1) * (rows + 1)).fill(0);\n for (let aj = 0; aj <= rows; aj++) {\n for (let ai = 0; ai <= cols; ai++) {\n const p = anchor(ai, aj);\n const x = Math.min(1, Math.max(0, Math.hypot(p.x - at0.x, p.y - at0.y) / radius));\n const fall = 0.5 * (1 + Math.cos(Math.PI * x));\n const edge = meshCorner(ai, aj) ? 0 : onBorder(ai, aj) ? nearBorder : 1;\n share[aj * (cols + 1) + ai] = fall * edge;\n }\n }\n // The grabbed patch's own corners: near one, that corner follows the pointer.\n for (const [ai, aj, w] of corner) share[aj * (cols + 1) + ai] = Math.max(share[aj * (cols + 1) + ai], (1 - interior) * w);\n const move = (idx: number, k: number, v: Vec2) => {\n const p = m.points[idx];\n m.points[idx] = { x: p.x + v.x * k, y: p.y + v.y * k };\n };\n // Every control point moves with the anchor it is closest to.\n for (let j = 0; j < ny; j++) {\n for (let i = 0; i < nx; i++) {\n const ai = Math.min(cols, Math.floor((i + 1) / 3));\n const aj = Math.min(rows, Math.floor((j + 1) / 3));\n move(j * nx + i, share[aj * (cols + 1) + ai], d);\n }\n }\n // Close the gap exactly with three groups that share the work: the grabbed patch's four inner\n // points, the corner blocks, and (near the border) the border's own handles. Closing nudges the\n // tangents across the grid lines, so they are evened out again and the gap re-closed.\n let norm = 0;\n for (const j of [1, 2]) for (const i of [1, 2]) norm += (ba[i] * bb[j]) ** 2;\n const cornerNorm = corner.reduce((acc, c) => acc + c[2] * c[2], 0);\n // With no free corner to help (a one-patch grid grabbed away from its border) the inner points do all of it.\n const innerPart = cornerNorm > 1e-12 ? Math.min(1, innerW / 0.15) : 1;\n const edgeHandles: [number, number][] = [];\n for (const k of [1, 2]) {\n if (pi === 0) edgeHandles.push([(3 * pj + k) * nx + 3 * pi, ba[0] * bb[k]]);\n if (pi + 1 === cols) edgeHandles.push([(3 * pj + k) * nx + 3 * pi + 3, ba[3] * bb[k]]);\n if (pj === 0) edgeHandles.push([3 * pj * nx + 3 * pi + k, ba[k] * bb[0]]);\n if (pj + 1 === rows) edgeHandles.push([(3 * pj + 3) * nx + 3 * pi + k, ba[k] * bb[3]]);\n }\n const edgeNorm = edgeHandles.reduce((acc, e) => acc + e[1] * e[1], 0);\n const edgePart = edgeNorm > 1e-12 ? nearBorder : 0;\n const innerShare = (1 - edgePart) * innerPart;\n const cornerShare = (1 - edgePart) * (1 - innerPart);\n for (let iter = 0; iter < 60; iter++) {\n const now = evalWarpMesh(m, s, t);\n const rem = { x: target.x - now.x, y: target.y - now.y };\n if (Math.hypot(rem.x, rem.y) < 1e-9) break;\n if (innerShare > 0 && norm > 0) for (const j of [1, 2]) for (const i of [1, 2]) move((3 * pj + j) * nx + 3 * pi + i, ((ba[i] * bb[j]) / norm) * innerShare, rem);\n if (edgePart > 0) for (const [idx, w] of edgeHandles) move(idx, (w / edgeNorm) * edgePart, rem);\n if (cornerShare > 0 && cornerNorm > 0) {\n for (const [ai, aj, w] of corner) {\n const k = (w / cornerNorm) * cornerShare;\n for (let dj = -1; dj <= 1; dj++) {\n for (let di = -1; di <= 1; di++) {\n const i = 3 * ai + di;\n const j = 3 * aj + dj;\n if (i >= 0 && j >= 0 && i < nx && j < ny) move(j * nx + i, k, rem);\n }\n }\n }\n }\n for (let k = 0; k < 3; k++) smoothLines(m, Math.max(0, 3 * pi - 3), 3 * pi + 7, Math.max(0, 3 * pj - 3), 3 * pj + 7);\n }\n return m;\n}\n\n/**\n * The control points an editor shows: the anchors (where grid lines cross) and the handles along\n * the grid lines, each with the anchor it belongs to. Points inside a patch are left out (drag\n * inside a patch to pull the surface instead).\n */\nexport function warpMeshEditPoints(m: WarpMesh): { anchors: number[]; handles: { index: number; anchor: number }[] } {\n const nx = warpMeshColumns(m);\n const ny = warpMeshRows(m);\n const anchors: number[] = [];\n const handles: { index: number; anchor: number }[] = [];\n for (let j = 0; j < ny; j++) {\n for (let i = 0; i < nx; i++) {\n const ri = i % 3;\n const rj = j % 3;\n if (ri === 0 && rj === 0) anchors.push(j * nx + i);\n else if (ri === 0) handles.push({ index: j * nx + i, anchor: (rj === 1 ? j - 1 : j + 1) * nx + i });\n else if (rj === 0) handles.push({ index: j * nx + i, anchor: j * nx + (ri === 1 ? i - 1 : i + 1) });\n }\n }\n return { anchors, handles };\n}\n\n/** The mesh's grid lines (patch borders) as cubics `[p0, p1, p2, p3]`. */\nexport function warpMeshGridCurves(m: WarpMesh): Vec2[][] {\n const nx = warpMeshColumns(m);\n const ny = warpMeshRows(m);\n const pt = (i: number, j: number) => m.points[j * nx + i];\n const out: Vec2[][] = [];\n for (let j = 0; j < ny; j += 3) for (let i = 0; i + 3 < nx; i += 3) out.push([pt(i, j), pt(i + 1, j), pt(i + 2, j), pt(i + 3, j)]);\n for (let i = 0; i < nx; i += 3) for (let j = 0; j + 3 < ny; j += 3) out.push([pt(i, j), pt(i, j + 1), pt(i, j + 2), pt(i, j + 3)]);\n return out;\n}\n","/**\n * Warp geometry for envelope distortion: preset warp styles and editable Bézier meshes, both\n * forward maps from a source box (the bounds of the paths an envelope bends) to the node's space.\n * The maths is shared with the image editor's Free Transform and lives in `src/geom/warp.ts`;\n * these are its vector-named exports, plus the envelope-from-outline helpers.\n *\n * The Coons patch of `vectorMeshFromOutline` is our own.\n */\nimport {\n\tclampMeshCount,\n\tevenKnots,\n\tfitWarpMesh,\n\tlerpVec2,\n\twarpMeshColumns,\n\twarpMeshRows\n} from '../geom/warp.js';\nimport type { Vec2, VectorSubpath, VectorWarpMesh } from './types.js';\n\nexport {\n\tWARP_STYLES as VECTOR_WARP_STYLES,\n\tWARP_STYLE_LABELS as VECTOR_WARP_STYLE_LABELS,\n\twarpPresetGrid as vectorWarpPresetGrid,\n\twarpPresetMesh as vectorWarpPresetMesh,\n\twarpMeshColumns as vectorMeshColumns,\n\twarpMeshRows as vectorMeshRows,\n\tisValidWarpMesh as isValidVectorMesh,\n\tfitWarpMesh as fitVectorMesh,\n\tidentityWarpMesh as vectorIdentityMesh,\n\tevalWarpMesh as evalVectorMesh,\n\tsplitWarpMeshU as splitVectorMeshU,\n\tsplitWarpMeshV as splitVectorMeshV,\n\tremoveWarpMeshSplitU as removeVectorMeshSplitU,\n\tremoveWarpMeshSplitV as removeVectorMeshSplitV,\n\tmapWarpMeshPoints as mapVectorMeshPoints,\n\tresizeWarpMesh as resizeVectorMesh,\n\twarpMeshControlBounds as vectorMeshControlBounds,\n\twarpMeshParamAt as vectorMeshParamAt,\n\tdragWarpMeshPoint as dragVectorMeshPoint,\n\tpullWarpMesh as pullVectorMesh,\n\twarpMeshEditPoints as vectorMeshEditPoints,\n\twarpMeshGridCurves as vectorMeshGridCurves\n} from '../geom/warp.js';\n\n/** A preset warp's settings (bend and distortions in percent, −100…100). */\nexport type { WarpPreset as VectorWarpPreset } from '../geom/warp.js';\n\n// ---------------------------------------------------------------------------\n// Envelope from an outline (Make with Top Object)\n// ---------------------------------------------------------------------------\n\n/** Points along a polyline by fraction of its length. */\nfunction polylineAt(pts: readonly Vec2[]): (u: number) => Vec2 {\n\tconst acc = [0];\n\tfor (let i = 1; i < pts.length; i++) acc.push(acc[i - 1] + Math.hypot(pts[i].x - pts[i - 1].x, pts[i].y - pts[i - 1].y));\n\tconst total = acc[acc.length - 1];\n\treturn (u) => {\n\t\tif (!(total > 0)) return pts[0];\n\t\tconst L = Math.min(1, Math.max(0, u)) * total;\n\t\tlet i = 1;\n\t\twhile (i < acc.length - 1 && acc[i] < L) i++;\n\t\tconst seg = acc[i] - acc[i - 1];\n\t\treturn lerpVec2(pts[i - 1], pts[i], seg > 0 ? (L - acc[i - 1]) / seg : 0);\n\t};\n}\n\nfunction sampleSubpath(sp: VectorSubpath, per = 24): Vec2[] {\n\tconst n = sp.anchors.length;\n\tconst out: Vec2[] = [];\n\tfor (let i = 0; i < n; i++) {\n\t\tconst a = sp.anchors[i];\n\t\tconst b = sp.anchors[(i + 1) % n];\n\t\tconst c = [{ x: a.x, y: a.y }, a.out ?? a, b.in ?? b, { x: b.x, y: b.y }];\n\t\tfor (let k = 0; k < per; k++) {\n\t\t\tconst t = k / per;\n\t\t\tconst ab = lerpVec2(c[0], c[1], t);\n\t\t\tconst bc = lerpVec2(c[1], c[2], t);\n\t\t\tconst cd = lerpVec2(c[2], c[3], t);\n\t\t\tout.push(lerpVec2(lerpVec2(ab, bc, t), lerpVec2(bc, cd, t), t));\n\t\t}\n\t}\n\treturn out;\n}\n\n/**\n * A mesh whose border follows a closed outline (Illustrator's Make with Top Object): the outline is\n * cut into four sides at the points nearest its bounding box's corners, and the interior is the\n * Coons patch of those sides, fitted with `columns × rows` patches. Null for an open or degenerate\n * outline.\n */\nexport function vectorMeshFromOutline(sp: VectorSubpath, columns = 4, rows = 4): VectorWarpMesh | null {\n\tif (!sp.closed || sp.anchors.length < 2) return null;\n\tlet ring = sampleSubpath(sp);\n\tconst xs = ring.map((p) => p.x);\n\tconst ys = ring.map((p) => p.y);\n\tconst box = { x0: Math.min(...xs), y0: Math.min(...ys), x1: Math.max(...xs), y1: Math.max(...ys) };\n\tif (!(box.x1 - box.x0 > 1e-9 && box.y1 - box.y0 > 1e-9)) return null;\n\tconst nearest = (c: Vec2) => {\n\t\tlet best = 0;\n\t\tfor (let i = 1; i < ring.length; i++) if (Math.hypot(ring[i].x - c.x, ring[i].y - c.y) < Math.hypot(ring[best].x - c.x, ring[best].y - c.y)) best = i;\n\t\treturn best;\n\t};\n\tconst cornersOf = () =>\n\t\t[\n\t\t\t{ x: box.x0, y: box.y0 },\n\t\t\t{ x: box.x1, y: box.y0 },\n\t\t\t{ x: box.x1, y: box.y1 },\n\t\t\t{ x: box.x0, y: box.y1 }\n\t\t].map(nearest);\n\tlet c = cornersOf();\n\tconst n = ring.length;\n\tconst fwd = (from: number, to: number) => (to - from + n) % n;\n\t// Clockwise on screen: top-left, top-right, bottom-right, bottom-left in walking order.\n\tif (!(fwd(c[0], c[1]) < fwd(c[0], c[2]) && fwd(c[0], c[2]) < fwd(c[0], c[3]))) {\n\t\tring = ring.slice().reverse();\n\t\tc = cornersOf();\n\t\tif (!(fwd(c[0], c[1]) < fwd(c[0], c[2]) && fwd(c[0], c[2]) < fwd(c[0], c[3]))) return null;\n\t}\n\tif (new Set(c).size < 4) return null;\n\tconst walk = (from: number, to: number) => {\n\t\tconst out: Vec2[] = [];\n\t\tfor (let i = from; ; i = (i + 1) % n) {\n\t\t\tout.push(ring[i]);\n\t\t\tif (i === to) break;\n\t\t}\n\t\treturn out;\n\t};\n\t// The ring runs clockwise, so the bottom (bottom-right → bottom-left) and left (bottom-left →\n\t// top-left) walks are reversed to run left to right and top to bottom.\n\tconst top = polylineAt(walk(c[0], c[1]));\n\tconst right = polylineAt(walk(c[1], c[2]));\n\tconst bottomLR = polylineAt(walk(c[2], c[3]).reverse());\n\tconst leftTB = polylineAt(walk(c[3], c[0]).reverse());\n\tconst p00 = top(0);\n\tconst p10 = top(1);\n\tconst p01 = bottomLR(0);\n\tconst p11 = bottomLR(1);\n\tconst coons = (s: number, t: number): Vec2 => {\n\t\tconst T = top(s);\n\t\tconst B = bottomLR(s);\n\t\tconst L = leftTB(t);\n\t\tconst R = right(t);\n\t\treturn {\n\t\t\tx: (1 - t) * T.x + t * B.x + (1 - s) * L.x + s * R.x - ((1 - s) * (1 - t) * p00.x + s * (1 - t) * p10.x + (1 - s) * t * p01.x + s * t * p11.x),\n\t\t\ty: (1 - t) * T.y + t * B.y + (1 - s) * L.y + s * R.y - ((1 - s) * (1 - t) * p00.y + s * (1 - t) * p10.y + (1 - s) * t * p01.y + s * t * p11.y)\n\t\t};\n\t};\n\treturn fitWarpMesh(coons, evenKnots(clampMeshCount(columns)), evenKnots(clampMeshCount(rows)));\n}\n\n/** The mesh's border as one closed subpath (clockwise from the top-left corner): what Release gives back as the envelope's shape. */\nexport function vectorMeshOutline(m: VectorWarpMesh): VectorSubpath {\n\tconst nx = warpMeshColumns(m);\n\tconst ny = warpMeshRows(m);\n\tconst pt = (i: number, j: number) => m.points[j * nx + i];\n\t// The border as a chain of cubics, each [p0, p1, p2, p3].\n\tconst runs: Vec2[][] = [];\n\tfor (let i = 0; i + 3 < nx; i += 3) runs.push([pt(i, 0), pt(i + 1, 0), pt(i + 2, 0), pt(i + 3, 0)]);\n\tfor (let j = 0; j + 3 < ny; j += 3) runs.push([pt(nx - 1, j), pt(nx - 1, j + 1), pt(nx - 1, j + 2), pt(nx - 1, j + 3)]);\n\tfor (let i = nx - 1; i - 3 >= 0; i -= 3) runs.push([pt(i, ny - 1), pt(i - 1, ny - 1), pt(i - 2, ny - 1), pt(i - 3, ny - 1)]);\n\tfor (let j = ny - 1; j - 3 >= 0; j -= 3) runs.push([pt(0, j), pt(0, j - 1), pt(0, j - 2), pt(0, j - 3)]);\n\tconst anchors = runs.map((r, k) => {\n\t\tconst prev = runs[(k + runs.length - 1) % runs.length];\n\t\treturn { x: r[0].x, y: r[0].y, in: { ...prev[2] }, out: { ...r[1] } };\n\t});\n\treturn { closed: true, anchors };\n}\n","/**\n * Live appearance: path effect stacks and live boolean groups, evaluated on demand while the\n * stored anchors and children stay editable.\n *\n * `expandVectorAppearance` is the one place the effected geometry is made (cached per node\n * object, so an edit recomputes only the nodes it replaced). Rendering, hit-testing, bounds,\n * snapping, booleans, the Pathfinder, the Shape Builder and SVG export all read it, the way they\n * read live corners through `subpathsToBezier`; Expand Appearance stores it.\n *\n * Stacking follows After Effects' shape layers (effectcraft `crates/render/src/shapes.rs`): an\n * effect acts on every path above it — the node's own outline, or for a group every path of its\n * children (nested groups included, as drawn by their own effects) — in the order of the stack,\n * and effects placed after a repeater act on its copies. The result paints with the style of the\n * path each shape came from; Merge Paths and live booleans paint with the bottom one's.\n *\n * Live booleans fold their operands bottom to top, each combined with the result below it by its\n * own operation or the group's, and every prefix of the fold is cached under a rolling hash of the\n * operands it covers, so editing one operand recombines only the operands from it up; the cache\n * drops its least recently used half when full. Live groups are hit by their result except while\n * they are being edited (`vectorEnteredGroups`).\n *\n * Ported from ArtCraft (MIT OR Apache-2.0, © ArtCraft Team and contributors; see\n * THIRD_PARTY_NOTICES.md): the stacking rule of effectcraft `crates/render/src/shapes.rs`\n * (`collect()`); figcraft `crates/render/src/boolean.rs` (`fold_cached`, `PathCache`) and\n * `crates/engine/src/booleans.rs` (`operand_op`, `result_outline`); and the live-object model of\n * vectorcraft `crates/doc/src/live.rs` (`expand_live`, `expanded_group`, `subtree_has_live`).\n */\nimport { bezierPathBounds, transformBezierPath, type AffineMatrix, type BezierPath } from '../canvas/pathops/bezier.js';\nimport { pathBoolean } from '../canvas/pathops/boolean.js';\nimport { bezierToSubpaths, isIdentityMatrix, subpathsToBezier } from './geometry.js';\nimport {\n\tmergePaths,\n\toffsetPaths,\n\tpathsCenter,\n\tpuckerBloatPaths,\n\trepeatPaths,\n\troundCornerPaths,\n\tsweepPath,\n\ttrimPaths,\n\ttrimPathsIndividually,\n\ttwistPaths,\n\twigglePaths,\n\tzigzagPaths\n} from './pathEffects.js';\nimport { mapBezierPath } from './pathMap.js';\nimport { isVectorMaskGroup, vectorMaskedShapes } from './mask.js';\nimport { vectorTextPaintSource, vectorTextPaths, vectorTextShaperGeneration } from './text.js';\nimport { vectorInstanceGroup } from './symbols.js';\nimport { isVectorFrame, vectorFrameDrawn } from './frames.js';\nimport { parseVectorColor } from './gradient.js';\nimport { isVectorSymmetryGroup, vectorSymmetryDrawn, type VectorSymmetryGroup } from './symmetry.js';\nimport { transformVectorNode } from './geometry.js';\nimport {\n\tVECTOR_WARP_STYLES,\n\tVECTOR_WARP_STYLE_LABELS,\n\tevalVectorMesh,\n\tisValidVectorMesh,\n\tmapVectorMeshPoints,\n\tresizeVectorMesh,\n\tvectorIdentityMesh,\n\tvectorWarpPresetMesh\n} from './warp.js';\nimport type { VectorPaint } from './types.js';\nimport type {\n\tVectorBounds,\n\tVec2,\n\tVectorBooleanOperation,\n\tVectorEffect,\n\tVectorEffectParamsMap,\n\tVectorEffectType,\n\tVectorFillRule,\n\tVectorGroupNode,\n\tVectorInstanceNode,\n\tVectorNode,\n\tVectorPathNode,\n\tVectorWarpMesh\n} from './types.js';\n\n/** One shape of a node's appearance: a path in the node's own space, painted in `source`'s style. */\nexport interface VectorAppearanceShape {\n\t/** The path whose style paints it. */\n\tsource: VectorPathNode;\n\tpath: BezierPath;\n\t/** Opacity factor relative to the node (its own opacity not included). */\n\topacity: number;\n\t/** Draw-order key (compared element by element). */\n\torder: number[];\n}\n\n// ---------------------------------------------------------------------------\n// Effect definitions\n// ---------------------------------------------------------------------------\n\n/** Default parameters of each effect type. */\nexport const VECTOR_EFFECT_DEFAULTS: { readonly [K in VectorEffectType]: VectorEffectParamsMap[K] } = {\n\ttrim: { start: 0, end: 50, offset: 0, mode: 'simultaneous' },\n\troundCorners: { radius: 10 },\n\tpuckerBloat: { amount: 30 },\n\ttwist: { angle: 45, center: { x: 0, y: 0 } },\n\tzigzag: { size: 5, ridges: 4, smooth: false },\n\twiggle: { size: 5, detail: 6, smooth: true, speed: 2, correlation: 50, phase: 0, seed: 1, time: 0 },\n\toffset: { amount: 5, join: 'miter', miterLimit: 4, copies: 1, copyOffset: 0 },\n\tmerge: { mode: 'add' },\n\trepeater: {\n\t\tcopies: 3,\n\t\toffset: 0,\n\t\tposition: { x: 100, y: 0 },\n\t\tanchor: { x: 0, y: 0 },\n\t\trotation: 0,\n\t\tscale: { x: 100, y: 100 },\n\t\tstartOpacity: 100,\n\t\tendOpacity: 100,\n\t\tcomposite: 'below'\n\t},\n\tenvelope: { style: 'arc', bend: 50, horizontal: 0, vertical: 0, orientation: 'horizontal', rows: 2, columns: 2, mesh: null },\n\tcontour: { direction: 'inside', steps: 4, offset: 6, join: 'round', miterLimit: 4, fillColor: '#ffffff', strokeColor: null, acceleration: 0 },\n\tblockShadow: { angle: 45, distance: 20, color: '#1e293b', opacity: 100, endOpacity: 100 }\n};\n\nexport const VECTOR_EFFECT_LABELS: Record<VectorEffectType, string> = {\n\ttrim: 'Trim Paths',\n\troundCorners: 'Round Corners',\n\tpuckerBloat: 'Pucker & Bloat',\n\ttwist: 'Twist',\n\tzigzag: 'Zig Zag',\n\twiggle: 'Wiggle Paths',\n\toffset: 'Offset Paths',\n\tmerge: 'Merge Paths',\n\trepeater: 'Repeater',\n\tenvelope: 'Envelope',\n\tcontour: 'Contour',\n\tblockShadow: 'Block Shadow'\n};\n\n/** How a panel edits one effect parameter. */\nexport type VectorEffectParamSpec =\n\t| { key: string; label: string; kind: 'number'; min?: number; max?: number; step: number; slider?: boolean }\n\t| { key: string; label: string; kind: 'vec2'; step: number }\n\t| { key: string; label: string; kind: 'boolean' }\n\t| { key: string; label: string; kind: 'select'; options: { value: string; label: string }[] }\n\t| { key: string; label: string; kind: 'color' };\n\n/** The editable parameters of each effect type, in panel order. */\nexport const VECTOR_EFFECT_PARAM_SPECS: Record<VectorEffectType, VectorEffectParamSpec[]> = {\n\ttrim: [\n\t\t{ key: 'start', label: 'Start %', kind: 'number', min: 0, max: 100, step: 1, slider: true },\n\t\t{ key: 'end', label: 'End %', kind: 'number', min: 0, max: 100, step: 1, slider: true },\n\t\t{ key: 'offset', label: 'Offset °', kind: 'number', min: -360, max: 360, step: 1, slider: true },\n\t\t{\n\t\t\tkey: 'mode',\n\t\t\tlabel: 'Paths',\n\t\t\tkind: 'select',\n\t\t\toptions: [\n\t\t\t\t{ value: 'simultaneous', label: 'Simultaneously' },\n\t\t\t\t{ value: 'individual', label: 'Individually' }\n\t\t\t]\n\t\t}\n\t],\n\troundCorners: [{ key: 'radius', label: 'Radius', kind: 'number', min: 0, max: 200, step: 1, slider: true }],\n\tpuckerBloat: [{ key: 'amount', label: 'Amount %', kind: 'number', min: -100, max: 100, step: 1, slider: true }],\n\ttwist: [\n\t\t{ key: 'angle', label: 'Angle °', kind: 'number', min: -720, max: 720, step: 1, slider: true },\n\t\t{ key: 'center', label: 'Centre', kind: 'vec2', step: 1 }\n\t],\n\tzigzag: [\n\t\t{ key: 'size', label: 'Size', kind: 'number', min: 0, max: 100, step: 0.5, slider: true },\n\t\t{ key: 'ridges', label: 'Ridges', kind: 'number', min: 0, max: 50, step: 1, slider: true },\n\t\t{ key: 'smooth', label: 'Smooth', kind: 'boolean' }\n\t],\n\twiggle: [\n\t\t{ key: 'size', label: 'Size', kind: 'number', min: 0, max: 100, step: 0.5, slider: true },\n\t\t{ key: 'detail', label: 'Detail', kind: 'number', min: 0, max: 50, step: 1, slider: true },\n\t\t{ key: 'smooth', label: 'Smooth', kind: 'boolean' },\n\t\t{ key: 'correlation', label: 'Correlation %', kind: 'number', min: 0, max: 100, step: 1, slider: true },\n\t\t{ key: 'speed', label: 'Speed', kind: 'number', min: 0, step: 0.1 },\n\t\t{ key: 'phase', label: 'Phase °', kind: 'number', step: 1 },\n\t\t{ key: 'time', label: 'Time (s)', kind: 'number', min: 0, max: 10, step: 0.05, slider: true },\n\t\t{ key: 'seed', label: 'Seed', kind: 'number', step: 1 }\n\t],\n\toffset: [\n\t\t{ key: 'amount', label: 'Amount', kind: 'number', min: -100, max: 100, step: 0.5, slider: true },\n\t\t{\n\t\t\tkey: 'join',\n\t\t\tlabel: 'Join',\n\t\t\tkind: 'select',\n\t\t\toptions: [\n\t\t\t\t{ value: 'miter', label: 'Miter' },\n\t\t\t\t{ value: 'round', label: 'Round' },\n\t\t\t\t{ value: 'bevel', label: 'Bevel' }\n\t\t\t]\n\t\t},\n\t\t{ key: 'miterLimit', label: 'Miter limit', kind: 'number', min: 1, step: 0.5 },\n\t\t{ key: 'copies', label: 'Copies', kind: 'number', min: 1, max: 20, step: 1 },\n\t\t{ key: 'copyOffset', label: 'Copy offset', kind: 'number', step: 0.5 }\n\t],\n\tmerge: [\n\t\t{\n\t\t\tkey: 'mode',\n\t\t\tlabel: 'Mode',\n\t\t\tkind: 'select',\n\t\t\toptions: [\n\t\t\t\t{ value: 'merge', label: 'Merge' },\n\t\t\t\t{ value: 'add', label: 'Add' },\n\t\t\t\t{ value: 'subtract', label: 'Subtract' },\n\t\t\t\t{ value: 'intersect', label: 'Intersect' },\n\t\t\t\t{ value: 'exclude', label: 'Exclude' }\n\t\t\t]\n\t\t}\n\t],\n\tcontour: [\n\t\t{\n\t\t\tkey: 'direction',\n\t\t\tlabel: 'Direction',\n\t\t\tkind: 'select',\n\t\t\toptions: [\n\t\t\t\t{ value: 'inside', label: 'Inside' },\n\t\t\t\t{ value: 'outside', label: 'Outside' },\n\t\t\t\t{ value: 'center', label: 'To centre' }\n\t\t\t]\n\t\t},\n\t\t{ key: 'steps', label: 'Steps', kind: 'number', min: 1, max: 200, step: 1, slider: true },\n\t\t{ key: 'offset', label: 'Offset', kind: 'number', min: 0.1, max: 200, step: 0.5, slider: true },\n\t\t{ key: 'fillColor', label: 'Fill to', kind: 'color' },\n\t\t{ key: 'strokeColor', label: 'Stroke to', kind: 'color' },\n\t\t{ key: 'acceleration', label: 'Acceleration', kind: 'number', min: -100, max: 100, step: 1, slider: true },\n\t\t{\n\t\t\tkey: 'join',\n\t\t\tlabel: 'Join',\n\t\t\tkind: 'select',\n\t\t\toptions: [\n\t\t\t\t{ value: 'miter', label: 'Miter' },\n\t\t\t\t{ value: 'round', label: 'Round' },\n\t\t\t\t{ value: 'bevel', label: 'Bevel' }\n\t\t\t]\n\t\t}\n\t],\n\tblockShadow: [\n\t\t{ key: 'angle', label: 'Angle °', kind: 'number', min: -360, max: 360, step: 1, slider: true },\n\t\t{ key: 'distance', label: 'Distance', kind: 'number', min: 0, max: 2000, step: 1, slider: true },\n\t\t{ key: 'color', label: 'Colour', kind: 'color' },\n\t\t{ key: 'opacity', label: 'Opacity %', kind: 'number', min: 0, max: 100, step: 1, slider: true },\n\t\t{ key: 'endOpacity', label: 'End opacity %', kind: 'number', min: 0, max: 100, step: 1, slider: true }\n\t],\n\trepeater: [\n\t\t{ key: 'copies', label: 'Copies', kind: 'number', min: 0, max: 50, step: 0.1, slider: true },\n\t\t{ key: 'offset', label: 'Offset', kind: 'number', min: -10, max: 10, step: 0.1, slider: true },\n\t\t{ key: 'position', label: 'Position', kind: 'vec2', step: 1 },\n\t\t{ key: 'anchor', label: 'Anchor', kind: 'vec2', step: 1 },\n\t\t{ key: 'rotation', label: 'Rotation °', kind: 'number', min: -360, max: 360, step: 1, slider: true },\n\t\t{ key: 'scale', label: 'Scale %', kind: 'vec2', step: 1 },\n\t\t{ key: 'startOpacity', label: 'Start opacity %', kind: 'number', min: 0, max: 100, step: 1, slider: true },\n\t\t{ key: 'endOpacity', label: 'End opacity %', kind: 'number', min: 0, max: 100, step: 1, slider: true },\n\t\t{\n\t\t\tkey: 'composite',\n\t\t\tlabel: 'Copies',\n\t\t\tkind: 'select',\n\t\t\toptions: [\n\t\t\t\t{ value: 'below', label: 'Below' },\n\t\t\t\t{ value: 'above', label: 'Above' }\n\t\t\t]\n\t\t}\n\t],\n\tenvelope: [\n\t\t{\n\t\t\tkey: 'style',\n\t\t\tlabel: 'Warp',\n\t\t\tkind: 'select',\n\t\t\toptions: [...VECTOR_WARP_STYLES.map((value) => ({ value, label: VECTOR_WARP_STYLE_LABELS[value] })), { value: 'mesh', label: 'Mesh' }]\n\t\t},\n\t\t{ key: 'bend', label: 'Bend %', kind: 'number', min: -100, max: 100, step: 1, slider: true },\n\t\t{ key: 'horizontal', label: 'Horizontal distortion %', kind: 'number', min: -100, max: 100, step: 1, slider: true },\n\t\t{ key: 'vertical', label: 'Vertical distortion %', kind: 'number', min: -100, max: 100, step: 1, slider: true },\n\t\t{\n\t\t\tkey: 'orientation',\n\t\t\tlabel: 'Orientation',\n\t\t\tkind: 'select',\n\t\t\toptions: [\n\t\t\t\t{ value: 'horizontal', label: 'Horizontal' },\n\t\t\t\t{ value: 'vertical', label: 'Vertical' }\n\t\t\t]\n\t\t},\n\t\t{ key: 'rows', label: 'Mesh rows', kind: 'number', min: 1, max: 16, step: 1 },\n\t\t{ key: 'columns', label: 'Mesh columns', kind: 'number', min: 1, max: 16, step: 1 }\n\t]\n};\n\n/** Envelope parameters. */\nexport type VectorEnvelopeParams = VectorEffectParamsMap['envelope'];\n\nconst cloneMesh = (m: VectorWarpMesh): VectorWarpMesh => ({ us: m.us.slice(), vs: m.vs.slice(), points: m.points.map((p) => ({ x: p.x, y: p.y })) });\n\n/**\n * The envelope's mesh over `bounds` (the paths' combined bounds), in the node's space: its own\n * mesh, the flat mesh of `columns × rows` patches, or a preset split exactly into that many patches.\n */\nexport function vectorEnvelopeMesh(params: VectorEnvelopeParams, bounds: VectorBounds): VectorWarpMesh {\n\tif (params.style === 'mesh') return params.mesh ?? vectorIdentityMesh(bounds, params.columns, params.rows);\n\tconst preset = vectorWarpPresetMesh({ style: params.style, bend: params.bend, horizontal: params.horizontal, vertical: params.vertical, orientation: params.orientation }, bounds);\n\treturn preset ? resizeVectorMesh(preset, params.columns, params.rows) : vectorIdentityMesh(bounds, params.columns, params.rows);\n}\n\n/** The envelope as a map of the node's space over `bounds`, or null when it changes nothing (or the box is empty). */\nexport function vectorEnvelopeMap(params: VectorEnvelopeParams, bounds: VectorBounds | null): ((p: { x: number; y: number }) => { x: number; y: number }) | null {\n\tif (!bounds || !(bounds.width > 0 && bounds.height > 0)) return null;\n\tconst mesh =\n\t\tparams.style === 'mesh'\n\t\t\t? params.mesh\n\t\t\t: vectorWarpPresetMesh({ style: params.style, bend: params.bend, horizontal: params.horizontal, vertical: params.vertical, orientation: params.orientation }, bounds);\n\tif (!mesh) return null;\n\tconst { x, y, width, height } = bounds;\n\treturn (p) => evalVectorMesh(mesh, (p.x - x) / width, (p.y - y) / height);\n}\n\n/** Combined bounds of paths. */\nfunction pathsBounds(paths: readonly BezierPath[]): VectorBounds | null {\n\tlet minX = Infinity;\n\tlet minY = Infinity;\n\tlet maxX = -Infinity;\n\tlet maxY = -Infinity;\n\tfor (const p of paths) {\n\t\tconst b = bezierPathBounds(p);\n\t\tif (!b) continue;\n\t\tminX = Math.min(minX, b.minX);\n\t\tminY = Math.min(minY, b.minY);\n\t\tmaxX = Math.max(maxX, b.maxX);\n\t\tmaxY = Math.max(maxY, b.maxY);\n\t}\n\treturn minX <= maxX ? { x: minX, y: minY, width: maxX - minX, height: maxY - minY } : null;\n}\n\n/** The paths through an envelope (each mapped adaptively, within a tolerance relative to their size). */\nfunction envelopePaths(paths: BezierPath[], params: VectorEnvelopeParams): BezierPath[] {\n\tconst bounds = pathsBounds(paths);\n\tconst f = vectorEnvelopeMap(params, bounds);\n\tif (!f || !bounds) return paths;\n\tconst tol = Math.min(0.25, Math.max(0.01, Math.hypot(bounds.width, bounds.height) / 2000));\n\treturn paths.map((p) => (p.length ? mapBezierPath(p, f, tol) : p));\n}\n\nconst isVec2 = (v: unknown): v is Vec2 => !!v && typeof v === 'object' && Number.isFinite((v as Vec2).x) && Number.isFinite((v as Vec2).y);\n\n/**\n * Effect parameters with defaults filled in and invalid values dropped (unknown keys go too).\n * Returns null for an unknown type.\n */\nexport function normalizeVectorEffectParams<K extends VectorEffectType>(type: K, params: Record<string, unknown> | null | undefined, base?: VectorEffectParamsMap[K]): VectorEffectParamsMap[K] | null {\n\tconst defaults = VECTOR_EFFECT_DEFAULTS[type] as Record<string, unknown> | undefined;\n\tif (!defaults) return null;\n\tconst out: Record<string, unknown> = { ...defaults, ...((base as Record<string, unknown> | undefined) ?? {}) };\n\tfor (const spec of VECTOR_EFFECT_PARAM_SPECS[type]) {\n\t\tconst v = params?.[spec.key];\n\t\tif (v === undefined) continue;\n\t\tif (spec.kind === 'number' && typeof v === 'number' && Number.isFinite(v)) out[spec.key] = Math.min(spec.max ?? Infinity, Math.max(spec.min ?? -Infinity, v));\n\t\telse if (spec.kind === 'boolean' && typeof v === 'boolean') out[spec.key] = v;\n\t\telse if (spec.kind === 'vec2' && isVec2(v)) out[spec.key] = { x: v.x, y: v.y };\n\t\telse if (spec.kind === 'select' && spec.options.some((o) => o.value === v)) out[spec.key] = v;\n\t\telse if (spec.kind === 'color' && (v === null || (typeof v === 'string' && parseVectorColor(v)))) out[spec.key] = v;\n\t}\n\tif (type === 'envelope') {\n\t\tconst o = out as unknown as VectorEnvelopeParams;\n\t\to.rows = Math.round(o.rows);\n\t\to.columns = Math.round(o.columns);\n\t\tconst given = params?.mesh;\n\t\tlet mesh: VectorWarpMesh | null = given !== undefined ? (isValidVectorMesh(given) ? cloneMesh(given) : null) : o.mesh;\n\t\tif (o.style !== 'mesh') mesh = null;\n\t\tif (mesh && given !== undefined) {\n\t\t\to.columns = mesh.us.length - 1;\n\t\t\to.rows = mesh.vs.length - 1;\n\t\t} else if (mesh) mesh = resizeVectorMesh(mesh, o.columns, o.rows);\n\t\to.mesh = mesh;\n\t}\n\treturn out as VectorEffectParamsMap[K];\n}\n\n/** A new effect of `type` (defaults merged with `params`), or null for an unknown type. */\nexport function createVectorEffect<K extends VectorEffectType>(type: K, id: string, params?: Partial<VectorEffectParamsMap[K]> | Record<string, unknown>): Extract<VectorEffect, { type: K }> | null {\n\tconst p = normalizeVectorEffectParams(type, params as Record<string, unknown>);\n\treturn p ? ({ id, type, params: p } as unknown as Extract<VectorEffect, { type: K }>) : null;\n}\n\nconst isEnabled = (e: VectorEffect) => e.enabled !== false && !!VECTOR_EFFECT_DEFAULTS[e.type];\n\n/** The node's effects that take part (enabled, of a known type). */\nexport function activeVectorEffects(node: VectorNode): VectorEffect[] {\n\treturn node.effects?.filter(isEnabled) ?? [];\n}\n\n/**\n * Whether the node itself draws differently from its stored geometry (effects or a live boolean).\n * Text always does: it draws as its glyphs.\n */\nexport function hasOwnVectorAppearance(node: VectorNode): boolean {\n\treturn node.type === 'text' || node.type === 'instance' || (node.type === 'group' && !!node.liveBoolean) || isVectorFrame(node) || isVectorSymmetryGroup(node) || !!node.effects?.some(isEnabled);\n}\n\nconst liveCache = new WeakMap<VectorNode, boolean>();\n\n/** Whether the node or anything inside it has a live appearance. */\nexport function hasVectorAppearance(node: VectorNode): boolean {\n\tlet v = liveCache.get(node);\n\tif (v === undefined) {\n\t\tv = hasOwnVectorAppearance(node) || (node.type === 'group' && node.children.some(hasVectorAppearance));\n\t\tliveCache.set(node, v);\n\t}\n\treturn v;\n}\n\n/** A live boolean group (its children are operands). */\nexport function isVectorLiveBoolean(node: VectorNode | null | undefined): node is VectorGroupNode & { liveBoolean: VectorBooleanOperation } {\n\treturn node?.type === 'group' && !!node.liveBoolean;\n}\n\n/** How operand `child` of a live boolean group combines with the operands below it. */\nexport function vectorOperandOperation(group: VectorGroupNode, child: VectorNode): VectorBooleanOperation {\n\treturn child.booleanOperation ?? group.liveBoolean ?? 'union';\n}\n\n// ---------------------------------------------------------------------------\n// Live boolean fold\n// ---------------------------------------------------------------------------\n\nconst PATH_OPS = { union: 'union', subtract: 'difference', intersect: 'intersection', exclude: 'xor' } as const;\n\n/** A bounded map of fold prefixes; the least recently used half goes when it is full. */\nclass FoldCache {\n\tprivate map = new Map<string, BezierPath>();\n\tconstructor(private readonly cap: number) {}\n\tget(key: string): BezierPath | undefined {\n\t\tconst hit = this.map.get(key);\n\t\tif (hit) {\n\t\t\tthis.map.delete(key);\n\t\t\tthis.map.set(key, hit);\n\t\t}\n\t\treturn hit;\n\t}\n\tset(key: string, path: BezierPath) {\n\t\tif (this.map.size >= this.cap) {\n\t\t\tlet drop = Math.floor(this.map.size / 2);\n\t\t\tfor (const k of this.map.keys()) {\n\t\t\t\tif (drop-- <= 0) break;\n\t\t\t\tthis.map.delete(k);\n\t\t\t}\n\t\t}\n\t\tthis.map.set(key, path);\n\t}\n\tclear() {\n\t\tthis.map.clear();\n\t}\n}\n\nconst foldCache = new FoldCache(4096);\nlet foldSteps = 0;\n\n/** How many boolean steps (one operand combined with the result below it) live booleans have computed: what a cache miss costs. */\nexport function vectorLiveBooleanSteps(): number {\n\treturn foldSteps;\n}\n\n/** Empties the live boolean prefix cache. */\nexport function clearVectorLiveBooleanCache(): void {\n\tfoldCache.clear();\n}\n\n/** A rolling hash of operands: two 32-bit FNV-1a lanes over every number's bits. */\nclass RollingHash {\n\tprivate a = 0x811c9dc5;\n\tprivate b = 0x01000193 ^ 0x5bd1e995;\n\tprivate static view = new DataView(new ArrayBuffer(8));\n\tbyte(v: number) {\n\t\tthis.a = Math.imul(this.a ^ (v & 0xff), 0x01000193);\n\t\tthis.b = Math.imul(this.b ^ (v & 0xff), 0x5bd1e995) ^ (this.b >>> 15);\n\t}\n\tnum(n: number) {\n\t\tRollingHash.view.setFloat64(0, n);\n\t\tfor (let i = 0; i < 8; i++) this.byte(RollingHash.view.getUint8(i));\n\t}\n\tpath(p: BezierPath) {\n\t\tfor (const c of p) {\n\t\t\tthis.byte(c.type.charCodeAt(0));\n\t\t\tif (c.type === 'Z') continue;\n\t\t\tif (c.type === 'C') {\n\t\t\t\tthis.num(c.x1);\n\t\t\t\tthis.num(c.y1);\n\t\t\t\tthis.num(c.x2);\n\t\t\t\tthis.num(c.y2);\n\t\t\t} else if (c.type === 'Q') {\n\t\t\t\tthis.num(c.x1);\n\t\t\t\tthis.num(c.y1);\n\t\t\t}\n\t\t\tthis.num(c.x);\n\t\t\tthis.num(c.y);\n\t\t}\n\t}\n\tkey(): string {\n\t\treturn `${(this.a >>> 0).toString(36)}.${(this.b >>> 0).toString(36)}`;\n\t}\n}\n\n/** One operand of a live boolean: its outline (group space), fill rule and operation (unused for the bottom one). */\nexport interface VectorBooleanOperand {\n\tpath: BezierPath;\n\tfillRule: VectorFillRule;\n\toperation: VectorBooleanOperation;\n}\n\n/**\n * The result of folding `operands` bottom to top, reusing the longest cached prefix: only the\n * operands above it are combined. Invalid geometry gives an empty path.\n */\nexport function foldVectorBooleanOperands(operands: readonly VectorBooleanOperand[]): BezierPath {\n\tif (!operands.length) return [];\n\tif (operands.length === 1) return operands[0].path;\n\tconst h = new RollingHash();\n\tconst keys = operands.map((o, i) => {\n\t\tif (i > 0) h.byte(o.operation.charCodeAt(0) + o.operation.length);\n\t\th.byte(o.fillRule === 'evenodd' ? 1 : 0);\n\t\th.path(o.path);\n\t\th.byte(9);\n\t\treturn h.key();\n\t});\n\tlet start = 0;\n\tlet acc: BezierPath = operands[0].path;\n\tfor (let i = keys.length - 1; i >= 1; i--) {\n\t\tconst hit = foldCache.get(keys[i]);\n\t\tif (hit) {\n\t\t\tif (i === keys.length - 1) return hit;\n\t\t\tstart = i;\n\t\t\tacc = hit;\n\t\t\tbreak;\n\t\t}\n\t}\n\tlet accRule: VectorFillRule = start === 0 ? operands[0].fillRule : 'nonzero';\n\tfor (let i = start + 1; i < operands.length; i++) {\n\t\tconst o = operands[i];\n\t\tfoldSteps++;\n\t\tconst r = pathBoolean(PATH_OPS[o.operation] ?? 'union', [\n\t\t\t{ path: acc, fillRule: accRule },\n\t\t\t{ path: o.path, fillRule: o.fillRule }\n\t\t]);\n\t\tif (r.error) return [];\n\t\tacc = r.path;\n\t\taccRule = 'nonzero';\n\t\tfoldCache.set(keys[i], acc);\n\t}\n\treturn acc;\n}\n\n// ---------------------------------------------------------------------------\n// The effect stack\n// ---------------------------------------------------------------------------\n\nconst compareOrder = (a: readonly number[], b: readonly number[]) => {\n\tconst n = Math.min(a.length, b.length);\n\tfor (let i = 0; i < n; i++) if (a[i] !== b[i]) return a[i] - b[i];\n\treturn a.length - b.length;\n};\n\nconst add = (a: Vec2, b: Vec2 | undefined): Vec2 => ({ x: a.x + (b?.x ?? 0), y: a.y + (b?.y ?? 0) });\n\n/** Every path operator maps the shapes' paths one to one. */\nconst mapPaths = (shapes: VectorAppearanceShape[], fn: (paths: BezierPath[]) => BezierPath[]): VectorAppearanceShape[] => {\n\tconst out = fn(shapes.map((s) => s.path));\n\treturn shapes.map((s, i) => ({ ...s, path: out[i] ?? [] }));\n};\n\n/** A paint blended toward `to` by `t` (only solid colours blend; gradients and null `to` keep it). */\nfunction blendPaint(from: VectorPaint | undefined, to: string | null, t: number): VectorPaint | undefined {\n\tif (to === null || typeof from !== 'string') return from;\n\tconst a = parseVectorColor(from);\n\tconst b = parseVectorColor(to);\n\tif (!a || !b) return from;\n\tconst h = (v: number) =>\n\t\tMath.round(Math.min(1, Math.max(0, v)) * 255)\n\t\t\t.toString(16)\n\t\t\t.padStart(2, '0');\n\tconst m = a.map((v, k) => v + (b[k] - v) * t);\n\treturn `#${h(m[0])}${h(m[1])}${h(m[2])}`;\n}\n\n/**\n * The contour steps of each shape (see `VectorEffectParamsMap.contour`): offset copies `offset`\n * apart, their colours blended toward the end colours, drawn over the shape inside and under it\n * outside. After CorelDRAW's Contour (concept); offsetting is our own `offsetPaths`.\n */\nfunction contourShapes(shapes: readonly VectorAppearanceShape[], c: VectorEffectParamsMap['contour']): VectorAppearanceShape[] {\n\tconst out: VectorAppearanceShape[] = [];\n\tconst step = Math.max(0.01, c.offset);\n\tconst outside = c.direction === 'outside';\n\tfor (const s of shapes) {\n\t\tlet n = Math.min(200, Math.max(1, Math.round(c.steps)));\n\t\tif (c.direction === 'center') {\n\t\t\tconst b = bezierPathBounds(s.path);\n\t\t\tn = b ? Math.min(200, Math.max(1, Math.ceil(Math.min(b.maxX - b.minX, b.maxY - b.minY) / 2 / step))) : 0;\n\t\t}\n\t\t// The original: on top outside, at the bottom inside.\n\t\tout.push({ ...s, order: [outside ? n : 0, ...s.order] });\n\t\t// Colour progress per step, bunched by the acceleration.\n\t\tconst power = 2 ** (Math.min(100, Math.max(-100, c.acceleration)) / 50);\n\t\tfor (let k = 1; k <= n; k++) {\n\t\t\tconst [path] = offsetPaths([s.path], (outside ? 1 : -1) * step * k, c.join, c.miterLimit, 1, 0);\n\t\t\tif (!path?.length) break;\n\t\t\tconst t = (k / n) ** power;\n\t\t\tconst source = { ...s.source, fill: blendPaint(s.source.fill, c.fillColor, t) ?? null, stroke: blendPaint(s.source.stroke, c.strokeColor, t) ?? null, fills: undefined, strokes: undefined };\n\t\t\tout.push({ source, path, opacity: s.opacity, order: [outside ? n - k : k, ...s.order] });\n\t\t}\n\t}\n\treturn out;\n}\n\n/**\n * The block shadow of each shape (see `VectorEffectParamsMap.blockShadow`): the shape swept\n * `distance` along `angle` (`sweepPath`), filled with the shadow colour (a gradient toward\n * `endOpacity` when it fades), drawn under every shape. After CorelDRAW's Block Shadow (concept).\n */\nfunction blockShadowShapes(shapes: readonly VectorAppearanceShape[], b: VectorEffectParamsMap['blockShadow']): VectorAppearanceShape[] {\n\tconst rad = (b.angle * Math.PI) / 180;\n\tconst u = { x: Math.cos(rad), y: Math.sin(rad) };\n\tconst distance = Math.max(0, b.distance);\n\tconst shadows: VectorAppearanceShape[] = [];\n\tfor (const s of shapes) {\n\t\tconst color = b.color ?? (typeof s.source.fill === 'string' && s.source.fill !== 'none' ? s.source.fill : '#000000');\n\t\tconst path = sweepPath(s.path, u.x * distance, u.y * distance, s.source.fillRule === 'evenodd' ? 'evenodd' : 'nonzero');\n\t\tconst box = bezierPathBounds(s.path);\n\t\tif (!path.length || !box) continue;\n\t\tlet fill: VectorPaint = color;\n\t\tconst near = Math.min(100, Math.max(0, b.opacity));\n\t\tconst far = Math.min(100, Math.max(0, b.endOpacity));\n\t\tconst top = Math.max(near, far);\n\t\tif (near !== far && distance > 0) {\n\t\t\t// From the near side of the shape to the far end of the shadow.\n\t\t\tconst along = [box.minX * u.x + box.minY * u.y, box.maxX * u.x + box.minY * u.y, box.minX * u.x + box.maxY * u.y, box.maxX * u.x + box.maxY * u.y];\n\t\t\tconst t0 = Math.min(...along);\n\t\t\tconst t1 = Math.max(...along) + distance;\n\t\t\tconst c = { x: (box.minX + box.maxX) / 2, y: (box.minY + box.maxY) / 2 };\n\t\t\tconst k = c.x * u.x + c.y * u.y;\n\t\t\tfill = {\n\t\t\t\ttype: 'linear',\n\t\t\t\tunits: 'userSpaceOnUse',\n\t\t\t\tstart: { x: c.x + u.x * (t0 - k), y: c.y + u.y * (t0 - k) },\n\t\t\t\tend: { x: c.x + u.x * (t1 - k), y: c.y + u.y * (t1 - k) },\n\t\t\t\tstops: [\n\t\t\t\t\t{ offset: 0, color, opacity: near / top },\n\t\t\t\t\t{ offset: 1, color, opacity: far / top }\n\t\t\t\t]\n\t\t\t};\n\t\t}\n\t\tconst source: VectorPathNode = { ...s.source, fill, stroke: null, fills: undefined, strokes: undefined, fillRule: 'nonzero' };\n\t\tshadows.push({ source, path, opacity: (s.opacity * top) / 100, order: [0, ...s.order] });\n\t}\n\treturn [...shadows, ...shapes.map((s) => ({ ...s, order: [1, ...s.order] }))];\n}\n\n/** Applies an effect stack to shapes, top to bottom (disabled effects skipped). */\nexport function applyVectorEffects(shapes: readonly VectorAppearanceShape[], effects: readonly VectorEffect[] | null | undefined): VectorAppearanceShape[] {\n\tlet list = shapes.slice();\n\tfor (const e of effects ?? []) {\n\t\tif (!isEnabled(e) || !list.length) continue;\n\t\tswitch (e.type) {\n\t\t\tcase 'trim': {\n\t\t\t\tconst { start, end, offset, mode } = e.params;\n\t\t\t\tlist = mapPaths(list, (p) => (mode === 'individual' ? trimPathsIndividually(p, start, end, offset) : trimPaths(p, start, end, offset)));\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase 'roundCorners':\n\t\t\t\tlist = mapPaths(list, (p) => roundCornerPaths(p, e.params.radius));\n\t\t\t\tbreak;\n\t\t\tcase 'puckerBloat':\n\t\t\t\tlist = mapPaths(list, (p) => puckerBloatPaths(p, e.params.amount));\n\t\t\t\tbreak;\n\t\t\tcase 'twist':\n\t\t\t\tlist = mapPaths(list, (p) => twistPaths(p, e.params.angle, add(pathsCenter(p), e.params.center)));\n\t\t\t\tbreak;\n\t\t\tcase 'zigzag':\n\t\t\t\tlist = mapPaths(list, (p) => zigzagPaths(p, e.params.size, e.params.ridges, e.params.smooth));\n\t\t\t\tbreak;\n\t\t\tcase 'wiggle':\n\t\t\t\tlist = mapPaths(list, (p) => wigglePaths(p, e.params));\n\t\t\t\tbreak;\n\t\t\tcase 'offset': {\n\t\t\t\tconst o = e.params;\n\t\t\t\tlist = mapPaths(list, (p) => offsetPaths(p, o.amount, o.join, o.miterLimit, o.copies, o.copyOffset));\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase 'merge': {\n\t\t\t\tconst first = list[0];\n\t\t\t\tlist = [{ ...first, path: mergePaths(list.map((s) => s.path), e.params.mode) }];\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase 'envelope': {\n\t\t\t\tconst params = e.params;\n\t\t\t\tlist = mapPaths(list, (p) => envelopePaths(p, params));\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase 'contour':\n\t\t\t\tlist = contourShapes(list, e.params);\n\t\t\t\tbreak;\n\t\t\tcase 'blockShadow':\n\t\t\t\tlist = blockShadowShapes(list, e.params);\n\t\t\t\tbreak;\n\t\t\tcase 'repeater': {\n\t\t\t\tconst r = e.params;\n\t\t\t\tconst copies = repeatPaths(\n\t\t\t\t\tlist.map((s) => s.path),\n\t\t\t\t\tr,\n\t\t\t\t\tadd(pathsCenter(list.map((s) => s.path)), r.anchor)\n\t\t\t\t);\n\t\t\t\tconst n = copies.length;\n\t\t\t\tconst next: VectorAppearanceShape[] = [];\n\t\t\t\tfor (const { copy, paths } of copies) {\n\t\t\t\t\t// Below: each copy draws under the one before it (the original on top).\n\t\t\t\t\tconst rank = r.composite === 'above' ? copy.index : n - 1 - copy.index;\n\t\t\t\t\tlist.forEach((s, i) => next.push({ source: s.source, path: paths[i], opacity: s.opacity * copy.opacity, order: [rank, ...s.order] }));\n\t\t\t\t}\n\t\t\t\tlist = next;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\treturn list;\n}\n\nconst instanceGroups = new WeakMap<VectorInstanceNode, VectorGroupNode>();\n\n/** What an instance draws as a plain group (cached per instance object; see `vectorInstanceGroup`). */\nexport function vectorInstanceDrawn(node: VectorInstanceNode): VectorGroupNode {\n\tlet g = instanceGroups.get(node);\n\tif (!g) {\n\t\tg = vectorInstanceGroup(node, (n, m) => transformVectorNode(n, m));\n\t\tinstanceGroups.set(node, g);\n\t}\n\treturn g;\n}\n\n/** The shapes of a child in its parent's space (hidden children have none), ordered by its index. */\nexport function vectorChildAppearanceShapes(child: VectorNode, index: number): VectorAppearanceShape[] {\n\tif (child.visible === false) return [];\n\t// An instance's transform may scale: its drawn group's is rigid.\n\tif (child.type === 'instance') child = vectorInstanceDrawn(child);\n\tconst m = child.transform;\n\tconst k = child.opacity ?? 1;\n\treturn vectorAppearanceShapes(child).map((s) => ({\n\t\tsource: s.source,\n\t\tpath: m && !isIdentityMatrix(m) ? transformBezierPath(s.path, m) : s.path,\n\t\topacity: s.opacity * k,\n\t\torder: [index, ...s.order]\n\t}));\n}\n\n/** A live boolean group's result: its operands folded, in the bottom operand's style. */\nfunction liveBooleanShapes(group: VectorGroupNode): VectorAppearanceShape[] {\n\tconst operands: VectorBooleanOperand[] = [];\n\tlet source: VectorPathNode | null = null;\n\tgroup.children.forEach((child, i) => {\n\t\tconst shapes = vectorChildAppearanceShapes(child, i);\n\t\tif (!shapes.length) return;\n\t\tsource ??= shapes[0].source;\n\t\tconst path =\n\t\t\tshapes.length === 1 ? shapes[0].path : pathBoolean('union', shapes.map((s) => ({ path: s.path, fillRule: s.source.fillRule ?? 'nonzero' }))).path;\n\t\tconst fillRule: VectorFillRule = shapes.length === 1 ? (shapes[0].source.fillRule ?? 'nonzero') : 'nonzero';\n\t\toperands.push({ path, fillRule, operation: vectorOperandOperation(group, child) });\n\t});\n\tif (!source) return [];\n\treturn [{ source, path: foldVectorBooleanOperands(operands), opacity: 1, order: [0] }];\n}\n\n/** Caches keyed by node, valid while the text shaper stays the same (text lays out by it). */\nconst shapeCache = new WeakMap<VectorNode, [number, VectorAppearanceShape[]]>();\nconst fresh = <T>(entry: [number, T] | undefined): T | undefined => (entry && entry[0] === vectorTextShaperGeneration() ? entry[1] : undefined);\n\n/** What a node's effect stack starts from: its own outline, its live boolean result or its children's shapes. */\nfunction baseShapes(node: VectorNode): VectorAppearanceShape[] {\n\tif (node.type === 'path') return [{ source: node, path: subpathsToBezier(node.subpaths), opacity: 1, order: [] }];\n\t// Text: its glyphs, one shape per fill (a run's own fill paints its characters).\n\tif (node.type === 'text') return vectorTextPaths(node).parts.map((p, k) => ({ source: vectorTextPaintSource(node, p.fill), path: p.path, opacity: 1, order: [k] }));\n\tif (node.type === 'instance') return baseShapes(vectorInstanceDrawn(node));\n\tif (node.liveBoolean) return liveBooleanShapes(node);\n\t// A mask group's effects act on its contents (the mask stays as it is).\n\tif (isVectorMaskGroup(node)) return node.children.flatMap((c, i) => (i === 0 ? [] : vectorChildAppearanceShapes(c, i)));\n\treturn node.children.flatMap((c, i) => vectorChildAppearanceShapes(c, i));\n}\n\n/** The paths entering effect `effectId` of the node's stack (those above it applied), in the node's own space. */\nexport function vectorEffectInputPaths(node: VectorNode, effectId: string): BezierPath[] | null {\n\tconst list = node.effects ?? [];\n\tconst i = list.findIndex((e) => e.id === effectId);\n\tif (i < 0) return null;\n\treturn applyVectorEffects(baseShapes(node), list.slice(0, i)).map((s) => s.path);\n}\n\n/** The box effect `effectId` (an envelope) bends: the combined bounds of the paths entering it, in the node's own space. */\nexport function vectorEffectInputBounds(node: VectorNode, effectId: string): VectorBounds | null {\n\tconst paths = vectorEffectInputPaths(node, effectId);\n\treturn paths ? pathsBounds(paths) : null;\n}\n\n/** The node's first enabled envelope effect, or null. */\nexport function vectorNodeEnvelope(node: VectorNode | null | undefined): Extract<VectorEffect, { type: 'envelope' }> | null {\n\treturn (node?.effects?.find((e) => e.type === 'envelope' && e.enabled !== false) as Extract<VectorEffect, { type: 'envelope' }> | undefined) ?? null;\n}\n\n/**\n * The editable mesh of a node's envelope (its own mesh, or the preset or flat mesh it stands for)\n * with the box it bends, in the node's own space; null without an envelope or contents.\n */\nexport function vectorEnvelopeFrame(node: VectorNode, effectId?: string): { effectId: string; bounds: VectorBounds; mesh: VectorWarpMesh } | null {\n\tconst e = effectId ? node.effects?.find((x) => x.id === effectId) : vectorNodeEnvelope(node);\n\tif (!e || e.type !== 'envelope') return null;\n\tconst bounds = vectorEffectInputBounds(node, e.id);\n\tif (!bounds || !(bounds.width > 0 && bounds.height > 0)) return null;\n\treturn { effectId: e.id, bounds, mesh: vectorEnvelopeMesh(e.params, bounds) };\n}\n\n/**\n * What a node draws as: shapes in its own space (its `transform` and opacity not applied),\n * bottom to top, with its effects and those of everything inside it applied. Cached per node\n * object.\n */\nexport function vectorAppearanceShapes(node: VectorNode): VectorAppearanceShape[] {\n\tconst hit = fresh(shapeCache.get(node));\n\tif (hit) return hit;\n\tif (node.type === 'instance') {\n\t\t// In the space of the drawn group (the instance's rotation and translation not applied).\n\t\tconst shapes = vectorAppearanceShapes(vectorInstanceDrawn(node));\n\t\tshapeCache.set(node, [vectorTextShaperGeneration(), shapes]);\n\t\treturn shapes;\n\t}\n\t// A frame draws as its clip group (its fill and children inside its rectangle), a symmetry\n\t// group as its children and their copies.\n\tif (isVectorFrame(node) || isVectorSymmetryGroup(node)) {\n\t\tconst shapes = vectorAppearanceShapes(isVectorFrame(node) ? vectorFrameDrawn(node) : vectorSymmetryDrawn(node as VectorSymmetryGroup));\n\t\tshapeCache.set(node, [vectorTextShaperGeneration(), shapes]);\n\t\treturn shapes;\n\t}\n\t// A mask group draws its contents (effects applied) clipped by its mask. Text without glyph\n\t// outlines has only glyph boxes, which effects would distort meaninglessly: they are skipped.\n\tconst effects = node.type === 'text' && !vectorTextPaths(node).outlines ? null : node.effects;\n\tconst out = (isVectorMaskGroup(node) ? vectorMaskedShapes(node) : applyVectorEffects(baseShapes(node), effects)).sort((a, b) => compareOrder(a.order, b.order));\n\tshapeCache.set(node, [vectorTextShaperGeneration(), out]);\n\treturn out;\n}\n\nconst outlineCache = new WeakMap<VectorNode, [number, BezierPath]>();\n\n/** Everything a node draws as one path in its own space (live corners cut, effects applied). */\nexport function vectorAppearanceOutline(node: VectorNode): BezierPath {\n\tlet hit = fresh(outlineCache.get(node));\n\tif (!hit) {\n\t\thit = node.type === 'path' && !hasOwnVectorAppearance(node) ? subpathsToBezier(node.subpaths) : vectorAppearanceShapes(node).flatMap((s) => s.path);\n\t\toutlineCache.set(node, [vectorTextShaperGeneration(), hit]);\n\t}\n\treturn hit;\n}\n\n// ---------------------------------------------------------------------------\n// Expanded nodes\n// ---------------------------------------------------------------------------\n\n/** A shape as a plain path node in `source`'s style. */\nfunction shapeNode(shape: VectorAppearanceShape, id: string): VectorPathNode {\n\tconst {\n\t\tid: _id,\n\t\ttype: _type,\n\t\tsubpaths: _s,\n\t\ttransform: _t,\n\t\teffects: _e,\n\t\tbooleanOperation: _b,\n\t\tblendStep: _bs,\n\t\tlocked: _l,\n\t\tvisible: _v,\n\t\topacity: _o,\n\t\t// The node's own blend mode and filters stay on the node, not on each shape it draws.\n\t\tblendMode: _bm,\n\t\tfilters: _fl,\n\t\t...style\n\t} = shape.source;\n\treturn { ...style, id, type: 'path', subpaths: bezierToSubpaths(shape.path), ...(shape.opacity < 1 ? { opacity: shape.opacity } : {}) };\n}\n\n/** The node's own placement and state, kept by its expanded form. */\nfunction placement(node: VectorNode) {\n\treturn {\n\t\t...(node.name !== undefined ? { name: node.name } : {}),\n\t\t...(node.transform ? { transform: node.transform } : {}),\n\t\t...(node.visible === false ? { visible: false } : {}),\n\t\t...(node.locked ? { locked: true } : {}),\n\t\t...(node.blendStep ? { blendStep: true } : {}),\n\t\t...(node.booleanOperation ? { booleanOperation: node.booleanOperation } : {}),\n\t\t...(node.blendMode ? { blendMode: node.blendMode } : {}),\n\t\t...(node.filters?.length ? { filters: node.filters } : {})\n\t};\n}\n\n/** What a node draws as, one plain path per shape (ids `<id>~fx<n>`, opacity relative to the node). */\nexport function vectorAppearanceNodes(node: VectorNode): VectorPathNode[] {\n\treturn vectorAppearanceShapes(node).map((s, k) => shapeNode(s, `${node.id}~fx${k}`));\n}\n\nconst expandCache = new WeakMap<VectorNode, [number, VectorPathNode | VectorGroupNode]>();\n\n/**\n * The node as plain geometry: path effects and live booleans evaluated into paths (the node\n * itself when nothing inside it is live). A path keeps its id when it draws as one shape;\n * otherwise, like any live group, it becomes a group with that id holding one path per shape\n * (ids `<id>~fx<n>`). Groups without effects of their own keep their structure. Cached per node.\n */\nexport function expandVectorAppearance(node: VectorNode): VectorPathNode | VectorGroupNode {\n\t// Text always has an appearance (its glyphs), so what is returned as is is a path or group.\n\tif (!hasVectorAppearance(node)) return node as VectorPathNode | VectorGroupNode;\n\tconst hit = fresh(expandCache.get(node));\n\tif (hit) return hit;\n\tif (node.type === 'instance') {\n\t\tconst drawn = expandVectorAppearance(vectorInstanceDrawn(node));\n\t\texpandCache.set(node, [vectorTextShaperGeneration(), drawn]);\n\t\treturn drawn;\n\t}\n\tif (isVectorFrame(node) || isVectorSymmetryGroup(node)) {\n\t\tconst drawn = isVectorFrame(node) ? vectorFrameDrawn(node) : vectorSymmetryDrawn(node as VectorSymmetryGroup);\n\t\tconst out = hasVectorAppearance(drawn) ? expandVectorAppearance(drawn) : drawn;\n\t\texpandCache.set(node, [vectorTextShaperGeneration(), out]);\n\t\treturn out;\n\t}\n\tlet out: VectorPathNode | VectorGroupNode;\n\tif (!hasOwnVectorAppearance(node)) {\n\t\tconst group = node as VectorGroupNode;\n\t\tout = { ...group, children: group.children.map(expandVectorAppearance) };\n\t} else if (isVectorMaskGroup(node)) {\n\t\t// A mask group keeps its mask; its effects act on the contents, wrapped in a group of their own.\n\t\tconst { effects, ...group } = node;\n\t\tconst [mask, ...contents] = node.children;\n\t\tconst wrapper: VectorGroupNode = { id: `${node.id}~content`, type: 'group', effects, children: contents };\n\t\tout = { ...group, children: [expandVectorAppearance(mask), ...(contents.length ? [expandVectorAppearance(wrapper)] : [])] };\n\t} else {\n\t\tconst shapes = vectorAppearanceShapes(node);\n\t\tif (node.type === 'path' && shapes.length === 1) {\n\t\t\tconst one = shapes[0];\n\t\t\tconst { effects: _e, opacity: _o, ...rest } = node;\n\t\t\tconst opacity = (node.opacity ?? 1) * one.opacity;\n\t\t\tout = { ...rest, subpaths: bezierToSubpaths(one.path), ...(opacity < 1 ? { opacity } : {}) };\n\t\t} else if (node.type === 'text' && shapes.length === 1) {\n\t\t\t// Text in one paint draws as one compound path with the text's id.\n\t\t\tconst one = shapes[0];\n\t\t\tconst opacity = (node.opacity ?? 1) * one.opacity;\n\t\t\tout = { ...shapeNode(one, node.id), ...placement(node), ...(opacity < 1 ? { opacity } : {}) };\n\t\t\tif (opacity >= 1) delete out.opacity;\n\t\t} else {\n\t\t\tout = {\n\t\t\t\tid: node.id,\n\t\t\t\ttype: 'group',\n\t\t\t\t...placement(node),\n\t\t\t\t...(node.opacity !== undefined ? { opacity: node.opacity } : {}),\n\t\t\t\tchildren: vectorAppearanceNodes(node)\n\t\t\t};\n\t\t}\n\t}\n\texpandCache.set(node, [vectorTextShaperGeneration(), out]);\n\treturn out;\n}\n\n/** Every node of a list expanded (the same array when nothing in it is live). */\nexport function expandVectorAppearances(nodes: readonly VectorNode[]): VectorNode[] {\n\tlet changed = false;\n\tconst out = nodes.map((n) => {\n\t\tconst e = expandVectorAppearance(n);\n\t\tif (e !== n) changed = true;\n\t\treturn e;\n\t});\n\treturn changed ? out : (nodes as VectorNode[]);\n}\n\n/**\n * Reads effects from untrusted data (JSON, agent input): unknown types and malformed entries are\n * dropped, parameters normalized, ids made unique.\n */\nexport function sanitizeVectorEffects(value: unknown): VectorEffect[] {\n\tif (!Array.isArray(value)) return [];\n\tconst out: VectorEffect[] = [];\n\tconst used = new Set<string>();\n\tfor (const raw of value) {\n\t\tif (!raw || typeof raw !== 'object') continue;\n\t\tconst r = raw as Record<string, unknown>;\n\t\tconst type = r.type as VectorEffectType;\n\t\tif (typeof type !== 'string' || !VECTOR_EFFECT_DEFAULTS[type]) continue;\n\t\tlet id = typeof r.id === 'string' && r.id && !used.has(r.id) ? r.id : '';\n\t\tfor (let k = out.length + 1; !id; k++) if (!used.has(`fx${k}`)) id = `fx${k}`;\n\t\tused.add(id);\n\t\tconst effect = createVectorEffect(type, id, (r.params as Record<string, unknown>) ?? {})!;\n\t\tout.push(r.enabled === false ? { ...effect, enabled: false } : effect);\n\t}\n\treturn out;\n}\n\n/**\n * Effect parameters carried through a linear map baked into a node's geometry (scaling or\n * flipping it): offsets and positions move with it, angles turn the other way when it mirrors.\n * Lengths such as sizes and radii are kept, like stroke widths.\n */\nexport function transformVectorEffects(effects: readonly VectorEffect[], m: AffineMatrix, node?: VectorNode): VectorEffect[] {\n\tconst lin = (v: Vec2): Vec2 => ({ x: m[0] * v.x + m[2] * v.y, y: m[1] * v.x + m[3] * v.y });\n\tconst full = (v: Vec2): Vec2 => ({ x: m[0] * v.x + m[2] * v.y + m[4], y: m[1] * v.x + m[3] * v.y + m[5] });\n\tconst mirror = m[0] * m[3] - m[1] * m[2] < 0 ? -1 : 1;\n\t// A preset is laid over the box of what it bends, so it follows a move or a scale by itself; a\n\t// skew or a mirror turns it into a mesh, which maps like the geometry.\n\tconst axisScale = Math.abs(m[1]) < 1e-12 && Math.abs(m[2]) < 1e-12 && m[0] > 0 && m[3] > 0;\n\treturn effects.map((e) => {\n\t\tif (e.type === 'envelope') {\n\t\t\tif (e.params.style === 'mesh') return e.params.mesh ? { ...e, params: { ...e.params, mesh: mapVectorMeshPoints(e.params.mesh, full) } } : e;\n\t\t\tif (axisScale || !node) return e;\n\t\t\tconst bounds = vectorEffectInputBounds(node, e.id);\n\t\t\tif (!bounds || !vectorEnvelopeMap(e.params, bounds)) return e;\n\t\t\treturn { ...e, params: { ...e.params, style: 'mesh', mesh: mapVectorMeshPoints(vectorEnvelopeMesh(e.params, bounds), full) } };\n\t\t}\n\t\tif (e.type === 'twist') return { ...e, params: { ...e.params, center: lin(e.params.center), angle: e.params.angle * mirror } };\n\t\tif (e.type === 'repeater')\n\t\t\treturn { ...e, params: { ...e.params, position: lin(e.params.position), anchor: lin(e.params.anchor), rotation: e.params.rotation * mirror } };\n\t\treturn e;\n\t});\n}\n\n/**\n * The live groups (live booleans and groups with effects) being edited: those in `ids` and those\n * holding a node in `ids`; mask groups only when they hold one. Their children are hit and outlined as stored instead of as drawn, so\n * each operand can be picked (figcraft `crates/engine/src/booleans.rs`, `result_outline`).\n */\nexport function vectorEnteredGroups(nodes: readonly VectorNode[], ids: readonly string[]): Set<string> {\n\tconst out = new Set<string>();\n\tif (!ids.length) return out;\n\tconst want = new Set(ids);\n\tconst visit = (list: readonly VectorNode[], live: readonly string[]) => {\n\t\tfor (const n of list) {\n\t\t\tconst own = n.type === 'group' && (hasOwnVectorAppearance(n) || isVectorMaskGroup(n));\n\t\t\tif (want.has(n.id)) {\n\t\t\t\tfor (const id of live) out.add(id);\n\t\t\t\t// A selected mask group stays clipped; selecting inside it opens it.\n\t\t\t\tif (own && hasOwnVectorAppearance(n)) out.add(n.id);\n\t\t\t}\n\t\t\tif (n.type === 'group') visit(n.children, own ? [...live, n.id] : live);\n\t\t}\n\t};\n\tvisit(nodes, []);\n\treturn out;\n}\n","/**\n * Connectors glued to objects: connection sites, routing and rerouting after every edit.\n *\n * After wordcraft's `crates/doc/src/connector.rs` (`sites`, `site_point`, `nearest_site`,\n * `connector_segs`, `reroute_group`) and deckcraft's `crates/engine/src/connect.rs` (`sites`,\n * `nearest_site`, `reroute`, `set_glue`) (MIT OR Apache-2.0, © ArtCraft Team and contributors; see\n * THIRD_PARTY_NOTICES.md): an end is glued to a site of another object (here a side's middle or the\n * centre of its own bounds, through its rotation); the connector is routed again whenever what it\n * is glued to changes, and glue to an object that no longer exists is dropped, the end staying where\n * it was. Straight, elbow and curved routes follow `connector_segs`; elbows leave and enter along the\n * sides' normals (a gap out first) and curves take their handles along them. `auto` sides (the one\n * facing the other end) are ours.\n */\n\nimport type { AffineMatrix } from '../geom/types.js';\nimport { applyMatrix, applyMatrixLinear, invertMatrix, isIdentityMatrix } from '../geom/affine.js';\nimport type {\n\tVectorAnchor,\n\tVectorConnector,\n\tVectorConnectorEnd,\n\tVectorConnectorRoute,\n\tVectorConnectorSide,\n\tVectorDocument,\n\tVectorNode,\n\tVectorPathNode,\n\tVectorSubpath\n} from './types.js';\nimport { VECTOR_CONNECTOR_ROUTES, VECTOR_CONNECTOR_SIDES } from './types.js';\nimport { findVectorNode, hitTestVectorNodes, vectorNodeBounds, vectorWorldMatrix } from './geometry.js';\n\ntype Vec = { x: number; y: number };\n\n/** A connection site in document space: where an end meets the object, and the side's outward normal. */\nexport interface VectorConnectionSite {\n\tside: Exclude<VectorConnectorSide, 'auto'>;\n\tx: number;\n\ty: number;\n\t/** Unit outward normal (zero for the centre). */\n\tnx: number;\n\tny: number;\n}\n\nconst SIDES = ['top', 'right', 'bottom', 'left', 'center'] as const;\n\n/** Whether the node is a connector path. */\nexport function isVectorConnector(node: VectorNode | null | undefined): node is VectorPathNode & { connector: VectorConnector } {\n\treturn node?.type === 'path' && !!node.connector;\n}\n\n/**\n * The connection sites of node `id` in document space, in the order top, right, bottom, left,\n * centre: the middles of its own (unrotated) bounds' sides, through its rotation and its ancestors'.\n * Empty for a connector, a hidden node or one without extent.\n */\nexport function vectorConnectionSites(nodes: readonly VectorNode[], id: string): VectorConnectionSite[] {\n\tconst node = findVectorNode(nodes, id);\n\tif (!node || isVectorConnector(node) || node.visible === false) return [];\n\tconst world = vectorWorldMatrix(nodes, id);\n\tif (!world) return [];\n\tconst { transform: _t, ...own } = node;\n\tconst b = vectorNodeBounds(own as VectorNode);\n\tif (!b) return [];\n\t// The node's own space → document (its transform included; `own` was measured without it).\n\tconst cx = b.x + b.width / 2;\n\tconst cy = b.y + b.height / 2;\n\tconst local: Record<(typeof SIDES)[number], [Vec, Vec]> = {\n\t\ttop: [{ x: cx, y: b.y }, { x: 0, y: -1 }],\n\t\tright: [{ x: b.x + b.width, y: cy }, { x: 1, y: 0 }],\n\t\tbottom: [{ x: cx, y: b.y + b.height }, { x: 0, y: 1 }],\n\t\tleft: [{ x: b.x, y: cy }, { x: -1, y: 0 }],\n\t\tcenter: [{ x: cx, y: cy }, { x: 0, y: 0 }]\n\t};\n\treturn SIDES.map((side) => {\n\t\tconst [p, n] = local[side];\n\t\tconst q = applyMatrix(world, p);\n\t\tconst m = applyMatrixLinear(world, n);\n\t\tconst len = Math.hypot(m.x, m.y);\n\t\treturn { side, x: q.x, y: q.y, nx: len > 1e-12 ? m.x / len : 0, ny: len > 1e-12 ? m.y / len : 0 };\n\t});\n}\n\n/** The site of `sites` nearest `p` (document space) within `radius`, or null. */\nexport function nearestVectorConnectionSite(sites: readonly VectorConnectionSite[], p: Vec, radius = Infinity): VectorConnectionSite | null {\n\tlet best: VectorConnectionSite | null = null;\n\tlet bestD = radius;\n\tfor (const s of sites) {\n\t\tconst d = Math.hypot(s.x - p.x, s.y - p.y);\n\t\tif (d <= bestD) {\n\t\t\tbest = s;\n\t\t\tbestD = d;\n\t\t}\n\t}\n\treturn best;\n}\n\n/** The site of an `auto` end: the side whose normal faces `toward` most (the nearer one on a tie). */\nfunction facingSite(sites: readonly VectorConnectionSite[], toward: Vec): VectorConnectionSite {\n\tlet best = sites[0];\n\tlet score = -Infinity;\n\tfor (const s of sites) {\n\t\tif (s.side === 'center') continue;\n\t\tconst dx = toward.x - s.x;\n\t\tconst dy = toward.y - s.y;\n\t\tconst len = Math.hypot(dx, dy) || 1;\n\t\tconst v = (s.nx * dx + s.ny * dy) / len - len * 1e-9;\n\t\tif (v > score) {\n\t\t\tscore = v;\n\t\t\tbest = s;\n\t\t}\n\t}\n\treturn best;\n}\n\n/** A routed end: its point and the direction the line leaves it (zero when it has none). */\ninterface RoutedEnd {\n\tx: number;\n\ty: number;\n\tnx: number;\n\tny: number;\n\tglued: boolean;\n}\n\n/** The connector's current end points in document space (its first and last anchors). */\nfunction storedEnds(node: VectorPathNode, world: AffineMatrix): [Vec, Vec] | null {\n\tconst sp = node.subpaths[0];\n\tif (!sp?.anchors.length) return null;\n\tconst a = sp.anchors[0];\n\tconst b = sp.anchors[sp.anchors.length - 1];\n\treturn [applyMatrix(world, a), applyMatrix(world, b)];\n}\n\n/** Where a glued end's object is (its centre), for choosing the other end's `auto` side. */\nfunction centreOf(sites: readonly VectorConnectionSite[]): Vec {\n\tconst c = sites[4];\n\treturn { x: c.x, y: c.y };\n}\n\n/** Unit vector along the dominant axis of `v` (right when zero). */\nfunction axis(v: Vec): Vec {\n\tif (Math.abs(v.x) >= Math.abs(v.y)) return { x: v.x < 0 ? -1 : 1, y: 0 };\n\treturn { x: 0, y: v.y < 0 ? -1 : 1 };\n}\n\n/** Removes repeated points and middle points of straight runs. */\nfunction tidy(points: Vec[]): Vec[] {\n\tconst out: Vec[] = [];\n\tfor (const p of points) {\n\t\tconst last = out[out.length - 1];\n\t\tif (last && Math.hypot(p.x - last.x, p.y - last.y) < 1e-9) continue;\n\t\tout.push(p);\n\t}\n\tfor (let i = out.length - 2; i >= 1; i--) {\n\t\tconst a = out[i - 1];\n\t\tconst b = out[i];\n\t\tconst c = out[i + 1];\n\t\tif (Math.abs((b.x - a.x) * (c.y - a.y) - (b.y - a.y) * (c.x - a.x)) < 1e-9) out.splice(i, 1);\n\t}\n\treturn out;\n}\n\n/** The elbow route's points between two ends (document space). */\nfunction elbowPoints(a: RoutedEnd, b: RoutedEnd, gap: number): Vec[] {\n\tconst na = a.glued && (a.nx || a.ny) ? axis({ x: a.nx, y: a.ny }) : axis({ x: b.x - a.x, y: b.y - a.y });\n\tconst nb = b.glued && (b.nx || b.ny) ? axis({ x: b.nx, y: b.ny }) : axis({ x: a.x - b.x, y: a.y - b.y });\n\tconst s = { x: a.x + na.x * (a.glued ? gap : 0), y: a.y + na.y * (a.glued ? gap : 0) };\n\tconst e = { x: b.x + nb.x * (b.glued ? gap : 0), y: b.y + nb.y * (b.glued ? gap : 0) };\n\tconst ha = na.x !== 0;\n\tconst hb = nb.x !== 0;\n\tlet mid: Vec[];\n\tif (ha && hb) {\n\t\t// Out and in sideways: across through the middle, or round the middle when that would turn back.\n\t\tconst mx = (s.x + e.x) / 2;\n\t\tmid = (mx - s.x) * na.x >= 0 && (mx - e.x) * nb.x >= 0 ? [{ x: mx, y: s.y }, { x: mx, y: e.y }] : [{ x: s.x, y: (s.y + e.y) / 2 }, { x: e.x, y: (s.y + e.y) / 2 }];\n\t} else if (!ha && !hb) {\n\t\tconst my = (s.y + e.y) / 2;\n\t\tmid = (my - s.y) * na.y >= 0 && (my - e.y) * nb.y >= 0 ? [{ x: s.x, y: my }, { x: e.x, y: my }] : [{ x: (s.x + e.x) / 2, y: s.y }, { x: (s.x + e.x) / 2, y: e.y }];\n\t} else if (ha) mid = [{ x: e.x, y: s.y }];\n\telse mid = [{ x: s.x, y: e.y }];\n\treturn tidy([{ x: a.x, y: a.y }, s, ...mid, e, { x: b.x, y: b.y }]);\n}\n\n/** The connector's path in document space, from routed ends. */\nexport function vectorConnectorWorldAnchors(a: RoutedEnd, b: RoutedEnd, route: VectorConnectorRoute, options: { radius?: number; gap?: number } = {}): VectorAnchor[] {\n\tconst gap = options.gap ?? 16;\n\tif (route === 'elbow') {\n\t\tconst pts = elbowPoints(a, b, gap);\n\t\tconst r = options.radius ?? 0;\n\t\treturn pts.map((p, i) => (r > 0 && i > 0 && i < pts.length - 1 ? { x: p.x, y: p.y, corner: { radius: r } } : { x: p.x, y: p.y }));\n\t}\n\tif (route === 'curved') {\n\t\tconst d = Math.hypot(b.x - a.x, b.y - a.y);\n\t\tconst k = Math.max(d * 0.4, gap);\n\t\tconst na = a.glued && (a.nx || a.ny) ? { x: a.nx, y: a.ny } : axis({ x: b.x - a.x, y: b.y - a.y });\n\t\tconst nb = b.glued && (b.nx || b.ny) ? { x: b.nx, y: b.ny } : axis({ x: a.x - b.x, y: a.y - b.y });\n\t\treturn [\n\t\t\t{ x: a.x, y: a.y, out: { x: a.x + na.x * k, y: a.y + na.y * k } },\n\t\t\t{ x: b.x, y: b.y, in: { x: b.x + nb.x * k, y: b.y + nb.y * k } }\n\t\t];\n\t}\n\treturn [\n\t\t{ x: a.x, y: a.y },\n\t\t{ x: b.x, y: b.y }\n\t];\n}\n\n/** Resolves one end: its site (an `auto` one facing `toward`), or null when its object is gone. */\nfunction resolveEnd(nodes: readonly VectorNode[], end: VectorConnectorEnd, toward: Vec): VectorConnectionSite | null {\n\tconst sites = vectorConnectionSites(nodes, end.nodeId);\n\tif (!sites.length) return null;\n\tconst side = end.side ?? 'auto';\n\treturn side === 'auto' ? facingSite(sites, toward) : (sites.find((s) => s.side === side) ?? null);\n}\n\n/** What routing a connector gives: its new subpaths (own space) and which ends lost their object. */\nexport interface VectorConnectorRouting {\n\tsubpaths: VectorSubpath[];\n\t/** The resolved sides of its glued ends (null when not glued). */\n\tstartSide: Exclude<VectorConnectorSide, 'auto'> | null;\n\tendSide: Exclude<VectorConnectorSide, 'auto'> | null;\n\t/** Ends glued to an object that no longer exists (or has no extent). */\n\tdropped: { start: boolean; end: boolean };\n}\n\n/** Routes connector `id` of `nodes` from where its ends are glued (or stored), or null when it is not a connector. */\nexport function routeVectorConnector(nodes: readonly VectorNode[], id: string): VectorConnectorRouting | null {\n\tconst node = findVectorNode(nodes, id);\n\tif (!isVectorConnector(node)) return null;\n\tconst world = vectorWorldMatrix(nodes, id);\n\tif (!world) return null;\n\tconst c = node.connector;\n\tconst stored = storedEnds(node, world) ?? [\n\t\t{ x: 0, y: 0 },\n\t\t{ x: 0, y: 0 }\n\t];\n\tconst glue = (e: VectorConnectorEnd | null | undefined) => (e && e.nodeId !== id ? e : null);\n\tconst startGlue = glue(c.start);\n\tconst endGlue = glue(c.end);\n\t// Reference points for `auto` sides: the other end's object centre, or its stored point.\n\tconst centre = (e: VectorConnectorEnd | null, fallback: Vec) => {\n\t\tif (!e) return fallback;\n\t\tconst sites = vectorConnectionSites(nodes, e.nodeId);\n\t\treturn sites.length ? centreOf(sites) : fallback;\n\t};\n\tconst s = startGlue ? resolveEnd(nodes, startGlue, centre(endGlue, stored[1])) : null;\n\tconst e = endGlue ? resolveEnd(nodes, endGlue, s ? { x: s.x, y: s.y } : centre(startGlue, stored[0])) : null;\n\tconst a: RoutedEnd = s ? { ...s, glued: true } : { ...stored[0], nx: 0, ny: 0, glued: false };\n\tconst b: RoutedEnd = e ? { ...e, glued: true } : { ...stored[1], nx: 0, ny: 0, glued: false };\n\tconst anchors = vectorConnectorWorldAnchors(a, b, c.route ?? 'straight', { radius: c.radius, gap: c.gap });\n\tconst back = invertMatrix(world);\n\tconst toLocal = (p: Vec) => (isIdentityMatrix(back) ? p : applyMatrix(back, p));\n\tconst local = anchors.map((an) => ({\n\t\t...an,\n\t\t...toLocal(an),\n\t\t...(an.in ? { in: toLocal(an.in) } : {}),\n\t\t...(an.out ? { out: toLocal(an.out) } : {})\n\t}));\n\treturn {\n\t\tsubpaths: [{ closed: false, anchors: local }],\n\t\tstartSide: s?.side ?? null,\n\t\tendSide: e?.side ?? null,\n\t\tdropped: { start: !!startGlue && !s, end: !!endGlue && !e }\n\t};\n}\n\nconst near = (a: number, b: number) => Math.abs(a - b) < 1e-9;\nconst samePoint = (a: Vec | null | undefined, b: Vec | null | undefined) => (!a && !b) || (!!a && !!b && near(a.x, b.x) && near(a.y, b.y));\nfunction sameSubpaths(a: readonly VectorSubpath[], b: readonly VectorSubpath[]): boolean {\n\tif (a.length !== b.length) return false;\n\treturn a.every((sp, i) => {\n\t\tconst o = b[i];\n\t\treturn (\n\t\t\tsp.closed === o.closed &&\n\t\t\tsp.anchors.length === o.anchors.length &&\n\t\t\tsp.anchors.every((p, k) => {\n\t\t\t\tconst q = o.anchors[k];\n\t\t\t\treturn samePoint(p, q) && samePoint(p.in, q.in) && samePoint(p.out, q.out) && (p.corner?.radius ?? 0) === (q.corner?.radius ?? 0);\n\t\t\t})\n\t\t);\n\t});\n}\n\n/**\n * The document with every connector routed again (glue to objects that no longer exist dropped);\n * the same object when nothing moved.\n */\nexport function rerouteVectorConnectors<D extends Pick<VectorDocument, 'nodes'>>(doc: D): D {\n\tconst ids: string[] = [];\n\tconst walk = (list: readonly VectorNode[]) => {\n\t\tfor (const n of list) {\n\t\t\tif (isVectorConnector(n) && (n.connector.start || n.connector.end)) ids.push(n.id);\n\t\t\tif (n.type === 'group') walk(n.children);\n\t\t}\n\t};\n\twalk(doc.nodes);\n\tif (!ids.length) return doc;\n\tconst next = new Map<string, VectorPathNode>();\n\tfor (const id of ids) {\n\t\tconst node = findVectorNode(doc.nodes, id) as VectorPathNode & { connector: VectorConnector };\n\t\tconst r = routeVectorConnector(doc.nodes, id);\n\t\tif (!r) continue;\n\t\tconst changed = !sameSubpaths(node.subpaths, r.subpaths);\n\t\tif (!changed && !r.dropped.start && !r.dropped.end) continue;\n\t\tconst connector: VectorConnector = { ...node.connector };\n\t\tif (r.dropped.start) delete connector.start;\n\t\tif (r.dropped.end) delete connector.end;\n\t\tnext.set(id, { ...node, subpaths: changed ? r.subpaths : node.subpaths, connector });\n\t}\n\tif (!next.size) return doc;\n\tconst map = (list: readonly VectorNode[]): VectorNode[] => {\n\t\tlet touched = false;\n\t\tconst out = list.map((n) => {\n\t\t\tconst hit = next.get(n.id);\n\t\t\tif (hit) {\n\t\t\t\ttouched = true;\n\t\t\t\treturn hit;\n\t\t\t}\n\t\t\tif (n.type === 'group') {\n\t\t\t\tconst children = map(n.children);\n\t\t\t\tif (children !== n.children) {\n\t\t\t\t\ttouched = true;\n\t\t\t\t\treturn { ...n, children };\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn n;\n\t\t});\n\t\treturn touched ? out : (list as VectorNode[]);\n\t};\n\treturn { ...doc, nodes: map(doc.nodes) };\n}\n\n/** Reads connector settings from untrusted data (JSON, SVG import), or null. */\nexport function sanitizeVectorConnector(value: unknown): VectorConnector | null {\n\tif (!value || typeof value !== 'object') return null;\n\tconst r = value as Record<string, unknown>;\n\tconst end = (v: unknown): VectorConnectorEnd | null => {\n\t\tif (!v || typeof v !== 'object') return null;\n\t\tconst e = v as Record<string, unknown>;\n\t\tif (typeof e.nodeId !== 'string' || !e.nodeId) return null;\n\t\treturn VECTOR_CONNECTOR_SIDES.includes(e.side as VectorConnectorSide) && e.side !== 'auto' ? { nodeId: e.nodeId, side: e.side as VectorConnectorSide } : { nodeId: e.nodeId };\n\t};\n\tconst out: VectorConnector = {};\n\tconst start = end(r.start);\n\tconst finish = end(r.end);\n\tif (start) out.start = start;\n\tif (finish) out.end = finish;\n\tif (VECTOR_CONNECTOR_ROUTES.includes(r.route as VectorConnectorRoute) && r.route !== 'straight') out.route = r.route as VectorConnectorRoute;\n\tif (typeof r.radius === 'number' && Number.isFinite(r.radius) && r.radius > 0) out.radius = r.radius;\n\tif (typeof r.gap === 'number' && Number.isFinite(r.gap) && r.gap >= 0) out.gap = r.gap;\n\treturn out;\n}\n\n/** Labels for the connector pickers. */\nexport const VECTOR_CONNECTOR_ROUTE_LABELS: Readonly<Record<VectorConnectorRoute, string>> = { straight: 'Straight', elbow: 'Elbow', curved: 'Curved' };\nexport const VECTOR_CONNECTOR_SIDE_LABELS: Readonly<Record<VectorConnectorSide, string>> = { auto: 'Auto', top: 'Top', right: 'Right', bottom: 'Bottom', left: 'Left', center: 'Centre' };\n\n/** What the connector panel shows: the first selected connector, or null. */\nexport interface VectorConnectorPanel {\n\tid: string;\n\troute: VectorConnectorRoute;\n\tradius: number;\n\tgap: number;\n\tstart: VectorConnectorEnd | null;\n\tend: VectorConnectorEnd | null;\n}\n\n/** The connector panel's data for a selection. */\nexport function getVectorConnectorPanel(state: { document: Pick<VectorDocument, 'nodes'>; selection: readonly string[] }): VectorConnectorPanel | null {\n\tfor (const id of state.selection) {\n\t\tconst n = findVectorNode(state.document.nodes, id);\n\t\tif (isVectorConnector(n)) {\n\t\t\tconst c = n.connector;\n\t\t\treturn { id: n.id, route: c.route ?? 'straight', radius: c.radius ?? 0, gap: c.gap ?? 16, start: c.start ?? null, end: c.end ?? null };\n\t\t}\n\t}\n\treturn null;\n}\n\n/**\n * What a connector end dragged to `p` (document space) glues to: the nearest connection site\n * within `radius` of a top-level object (that side), else the object under `p` (`auto`), else\n * null (a free end). Connectors, hidden and locked objects and `exclude` are skipped.\n */\nexport function vectorConnectorTargetAt(nodes: readonly VectorNode[], p: Vec, radius: number, exclude?: string): (VectorConnectorEnd & { site: VectorConnectionSite | null }) | null {\n\tlet best: { nodeId: string; site: VectorConnectionSite; d: number } | null = null;\n\tfor (const n of nodes) {\n\t\tif (n.id === exclude || n.visible === false || n.locked || isVectorConnector(n)) continue;\n\t\tconst site = nearestVectorConnectionSite(vectorConnectionSites(nodes, n.id), p, radius);\n\t\tif (site) {\n\t\t\tconst d = Math.hypot(site.x - p.x, site.y - p.y);\n\t\t\tif (!best || d < best.d) best = { nodeId: n.id, site, d };\n\t\t}\n\t}\n\tif (best) return { nodeId: best.nodeId, side: best.site.side, site: best.site };\n\tconst usable = nodes.filter((n) => n.id !== exclude && !isVectorConnector(n));\n\tconst hit = hitTestVectorNodes(usable, p, 0);\n\treturn hit ? { nodeId: hit.id, side: 'auto', site: null } : null;\n}\n","/**\n * Gradients laid along or across a stroke (`strokeMode: 'along' | 'across'`), as a `<pattern>`\n * paint server of slices, so the canvases and exported SVG draw them with plain SVG.\n *\n * Each subpath is flattened and cut into slices, one per flattened segment, reaching past\n * everything the stroke paints there (its joins, caps and arrowheads). Gentle turns share a rib on\n * the bisector, so neighbouring slices meet where both give the same colour; a sharp corner gets\n * square ribs and a patch under them in the corner's colour, and the open ends get a patch in the\n * end colour (caps and heads). Along: a slice's linear gradient runs from its start to its end\n * with the part of the gradient between their positions (by length, 0–1 per subpath), padded\n * beyond; across: from the stroke's left edge to its right edge (the visible band of an inside or\n * outside stroke; a width profile's sides at the slice's middle). The pattern paints only where the\n * stroke does, so no clipping is needed. Each slice overlaps the next a little to hide\n * anti-aliasing seams.\n *\n * After vectorcraft `crates/effects/src/stroke/gradient.rs` (ribs on the bisectors of gentle\n * turns, a fan round sharp corners: here one patch), ArtCraft, MIT OR Apache-2.0 — see\n * THIRD_PARTY_NOTICES.md.\n */\nimport type { SvgGradientDef } from '../canvas/gradient.js';\nimport { closeContour, flattenChain, pathToContours } from '../canvas/pathops/bezier.js';\nimport type { Point } from '../canvas/types.js';\nimport { subpathsToBezier } from './geometry.js';\nimport { strokeWidthProfileOf, vectorStrokeReach } from './stroke.js';\nimport { widthProfileAt } from './width.js';\nimport {\n\texpandVectorGradientStops,\n\tpatternAttrs,\n\tspanVectorGradientStops,\n\tvectorGradientArea,\n\ttype VectorPaintDef,\n\ttype VectorSvgPatternDef\n} from './gradient.js';\nimport type { Vec2, VectorBounds, VectorGradient, VectorGradientStop, VectorPathNode } from './types.js';\n\n/** Largest stretch of a rib on a turn's bisector (1 / cos of half the turn, about 74°) before the corner gets a patch. */\nconst SHARP = 1.25;\n/** Flattening tolerance (node units). */\nconst TOLERANCE = 0.2;\n/** How far each slice reaches into the next (node units). */\nconst OVERLAP = 0.5;\n\nconst fmt = (n: number, digits = 3) => {\n\tconst k = 10 ** digits;\n\tconst v = Math.round(n * k) / k;\n\treturn Object.is(v, -0) ? '0' : String(v);\n};\nconst toSvgStops = (stops: readonly VectorGradientStop[]) =>\n\tstops.map((s) => ({ offset: `${fmt(s.offset * 100)}%`, stopColor: s.color, ...(s.opacity !== undefined && s.opacity !== 1 ? { stopOpacity: Math.round(s.opacity * 1e4) / 1e4 } : {}) }));\nconst polygonD = (pts: readonly Vec2[], precision: number) => `M${pts.map((p) => `${fmt(p.x, precision)} ${fmt(p.y, precision)}`).join('L')}Z`;\nconst add = (a: Vec2, b: Vec2): Vec2 => ({ x: a.x + b.x, y: a.y + b.y });\nconst sub = (a: Vec2, b: Vec2): Vec2 => ({ x: a.x - b.x, y: a.y - b.y });\nconst scale = (a: Vec2, k: number): Vec2 => ({ x: a.x * k, y: a.y * k });\n/** Left of direction `d` looking along it on screen (y down). */\nconst left = (d: Vec2): Vec2 => ({ x: d.y, y: -d.x });\nconst unit = (v: Vec2): Vec2 => {\n\tconst l = Math.hypot(v.x, v.y);\n\treturn l > 1e-12 ? { x: v.x / l, y: v.y / l } : { x: 1, y: 0 };\n};\n\n/** A cross-section of the strip: from `l` (left of the path) through the path to `r`. */\ninterface Rib {\n\tl: Vec2;\n\tr: Vec2;\n}\n\n/** The flattened subpaths of a path (node space): points, whether closed, and their lengths. */\nfunction flattenedSubpaths(node: VectorPathNode): { pts: Vec2[]; closed: boolean }[] {\n\tconst out: { pts: Vec2[]; closed: boolean }[] = [];\n\tfor (const contour of pathToContours(subpathsToBezier(node.subpaths))) {\n\t\tconst segs = closeContour(contour);\n\t\tif (!segs.length) continue;\n\t\tconst ring: Point[] = flattenChain(segs, TOLERANCE);\n\t\tconst pts = ring.map(([x, y]) => ({ x, y })).filter((p, i, a) => i === 0 || Math.hypot(p.x - a[i - 1].x, p.y - a[i - 1].y) > 1e-9);\n\t\tif (contour.closed && pts.length > 2 && Math.hypot(pts[0].x - pts[pts.length - 1].x, pts[0].y - pts[pts.length - 1].y) < 1e-9) pts.pop();\n\t\tif (pts.length >= 2) out.push({ pts, closed: contour.closed && pts.length > 2 });\n\t}\n\treturn out;\n}\n\n/** Shoelace area (positive: clockwise on screen, y down). */\nconst signedArea = (pts: readonly Vec2[]) => {\n\tlet a = 0;\n\tfor (let i = 0; i < pts.length; i++) {\n\t\tconst p = pts[i];\n\t\tconst q = pts[(i + 1) % pts.length];\n\t\ta += p.x * q.y - q.x * p.y;\n\t}\n\treturn a / 2;\n};\n\n/**\n * The paint server of a gradient along or across the stroke of `node` (in its own space): a\n * pattern whose first def id is `id`. `area` defaults to the path's box padded by the stroke's\n * reach.\n */\nexport function vectorStrokeGradientDefs(g: VectorGradient, id: string, node: VectorPathNode, options: { bounds?: VectorBounds | null; area?: VectorBounds | null; precision?: number } = {}): VectorPaintDef[] {\n\tconst precision = options.precision ?? 3;\n\tconst mode = g.strokeMode === 'across' ? 'across' : 'along';\n\tconst expanded = expandVectorGradientStops(g);\n\tconst reach = vectorStrokeReach(node) + 1;\n\tconst area = options.area ?? vectorGradientArea(options.bounds && { x: options.bounds.x - reach, y: options.bounds.y - reach, width: options.bounds.width + 2 * reach, height: options.bounds.height + 2 * reach });\n\tconst width = node.strokeWidth ?? 1;\n\tconst align = node.strokeAlign ?? 'center';\n\tconst profile = strokeWidthProfileOf(node);\n\tconst gradients: SvgGradientDef[] = [];\n\tconst patches: { d: string; fill: string }[] = [];\n\tconst slices: { d: string; fill: string }[] = [];\n\tconst colourAt = (t: number) => {\n\t\tconst s = spanVectorGradientStops(g, t, t, expanded)[0];\n\t\treturn s;\n\t};\n\tlet counter = 0;\n\tconst solid = (pts: Vec2[], t: number) => {\n\t\tconst s = colourAt(t);\n\t\tconst gid = `${id}-p${counter++}`;\n\t\t// A one-stop gradient keeps the stop's opacity (a fill colour would need fill-opacity).\n\t\tgradients.push({ id: gid, type: 'linear', attrs: { gradientUnits: 'userSpaceOnUse', x1: 0, y1: 0, x2: 1, y2: 0 }, stops: toSvgStops([{ ...s, offset: 0 }]) });\n\t\tpatches.push({ d: polygonD(pts, precision), fill: `url(#${gid})` });\n\t};\n\tconst disc = (c: Vec2, r: number) => Array.from({ length: 16 }, (_, k) => add(c, scale({ x: Math.cos((k * Math.PI) / 8), y: Math.sin((k * Math.PI) / 8) }, r)));\n\n\tfor (const { pts, closed } of flattenedSubpaths(node)) {\n\t\tconst n = pts.length;\n\t\tconst segCount = closed ? n : n - 1;\n\t\tconst dirs: Vec2[] = [];\n\t\tconst lengths: number[] = [0];\n\t\tfor (let i = 0; i < segCount; i++) {\n\t\t\tconst a = pts[i];\n\t\t\tconst b = pts[(i + 1) % n];\n\t\t\tdirs.push(unit(sub(b, a)));\n\t\t\tlengths.push(lengths[i] + Math.hypot(b.x - a.x, b.y - a.y));\n\t\t}\n\t\tconst total = lengths[segCount];\n\t\tif (!(total > 1e-9)) continue;\n\t\tconst tAt = (i: number) => lengths[i] / total;\n\t\t// Inside / outside strokes show one side: the right of a clockwise outline is its inside.\n\t\tconst clockwise = closed && signedArea(pts) > 0;\n\t\tconst visibleLeft = align === 'center' || !closed ? null : align === 'inside' ? !clockwise : clockwise;\n\n\t\t// Ribs at each vertex: `before` ends the slice arriving, `after` starts the one leaving.\n\t\tconst ribs: { before: Rib; after: Rib }[] = [];\n\t\tfor (let i = 0; i < n; i++) {\n\t\t\tconst p = pts[i];\n\t\t\tconst din = i > 0 || closed ? dirs[(i - 1 + segCount) % segCount] : null;\n\t\t\tconst dout = i < segCount ? dirs[i] : null;\n\t\t\tconst square = (d: Vec2): Rib => ({ l: add(p, scale(left(d), reach)), r: sub(p, scale(left(d), reach)) });\n\t\t\tif (!din || !dout) {\n\t\t\t\tconst rib = square((din ?? dout)!);\n\t\t\t\tribs.push({ before: rib, after: rib });\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tconst nin = left(din);\n\t\t\tconst nout = left(dout);\n\t\t\tconst den = 1 + nin.x * nout.x + nin.y * nout.y;\n\t\t\tconst stretch = den > 1e-12 ? Math.sqrt(2 / den) : Infinity;\n\t\t\tif (stretch <= SHARP) {\n\t\t\t\tconst m = scale(add(nin, nout), reach / den);\n\t\t\t\tconst rib = { l: add(p, m), r: sub(p, m) };\n\t\t\t\tribs.push({ before: rib, after: rib });\n\t\t\t} else {\n\t\t\t\tribs.push({ before: square(din), after: square(dout) });\n\t\t\t\tsolid(disc(p, reach * 1.5), tAt(i));\n\t\t\t}\n\t\t}\n\t\tif (!closed) {\n\t\t\t// Caps and arrowheads beyond the ends paint the end colours.\n\t\t\tconst d0 = dirs[0];\n\t\t\tconst d1 = dirs[segCount - 1];\n\t\t\tconst a = pts[0];\n\t\t\tconst b = pts[n - 1];\n\t\t\tconst cap = (p: Vec2, d: Vec2) => [add(p, scale(left(d), reach)), add(add(p, scale(d, reach)), scale(left(d), reach)), sub(add(p, scale(d, reach)), scale(left(d), reach)), sub(p, scale(left(d), reach))];\n\t\t\tsolid(cap(a, scale(d0, -1)), 0);\n\t\t\tsolid(cap(b, d1), 1);\n\t\t}\n\t\tfor (let i = 0; i < segCount; i++) {\n\t\t\tconst j = (i + 1) % n;\n\t\t\tconst a = pts[i];\n\t\t\tconst b = pts[j];\n\t\t\tconst d = dirs[i];\n\t\t\tconst from = ribs[i].after;\n\t\t\tconst to = ribs[j].before;\n\t\t\tconst ext = scale(d, OVERLAP);\n\t\t\tconst quad = [from.l, add(to.l, ext), add(to.r, ext), from.r];\n\t\t\tconst gid = `${id}-s${counter++}`;\n\t\t\tconst t0 = tAt(i);\n\t\t\tconst t1 = closed && i === segCount - 1 ? 1 : tAt(i + 1);\n\t\t\tif (mode === 'along') {\n\t\t\t\tgradients.push({\n\t\t\t\t\tid: gid,\n\t\t\t\t\ttype: 'linear',\n\t\t\t\t\tattrs: { gradientUnits: 'userSpaceOnUse', x1: fmt(a.x, 4), y1: fmt(a.y, 4), x2: fmt(b.x, 4), y2: fmt(b.y, 4) },\n\t\t\t\t\tstops: toSvgStops(spanVectorGradientStops(g, t0, t1, expanded))\n\t\t\t\t});\n\t\t\t} else {\n\t\t\t\tconst mid = scale(add(a, b), 0.5);\n\t\t\t\tconst side = widthProfileAt(profile, (t0 + t1) / 2);\n\t\t\t\tconst nrm = left(d);\n\t\t\t\tconst reachL = visibleLeft === null ? (width / 2) * side.left : visibleLeft ? width * side.left : 0;\n\t\t\t\tconst reachR = visibleLeft === null ? (width / 2) * side.right : visibleLeft ? 0 : width * side.right;\n\t\t\t\tconst p0 = add(mid, scale(nrm, reachL));\n\t\t\t\tconst p1 = sub(mid, scale(nrm, reachR));\n\t\t\t\tgradients.push({\n\t\t\t\t\tid: gid,\n\t\t\t\t\ttype: 'linear',\n\t\t\t\t\tattrs: { gradientUnits: 'userSpaceOnUse', x1: fmt(p0.x, 4), y1: fmt(p0.y, 4), x2: fmt(p1.x, 4), y2: fmt(p1.y, 4) },\n\t\t\t\t\tstops: toSvgStops(expanded)\n\t\t\t\t});\n\t\t\t}\n\t\t\tslices.push({ d: polygonD(quad, precision), fill: `url(#${gid})` });\n\t\t}\n\t}\n\tconst def: VectorSvgPatternDef = {\n\t\tid,\n\t\ttype: 'pattern',\n\t\tattrs: patternAttrs(area),\n\t\tgradients,\n\t\ttiles: [...patches, ...slices]\n\t};\n\treturn [def];\n}\n","/**\n * SVG export and import for vector documents. Import is DOM-free (works in Node and\n * workers): it reads `<svg>`, `<g>`, `<path>`, `<rect>`, `<circle>`, `<ellipse>`, `<line>`,\n * `<polyline>`, `<polygon>`, linear / radial gradients, presentation attributes, `style`\n * declarations, `transform`s, `clip-path` and `mask` references (each becomes a mask group, the\n * clip or mask its first child). Text, images, foreign filters and `<use>` are skipped.\n *\n * Live corners export as their cut outline plus `data-vector-d` (the sharp path) and\n * `data-vector-corners` (the radii), so the editor's own SVG imports with editable corners.\n * Inside / outside strokes, which SVG cannot express, export (after vectorcraft\n * `crates/svg/src/lib.rs`, MIT OR Apache-2.0) as a `<g data-vector-path>` holding the fill, a\n * stroke of twice the width clipped to the shape (inside) or masked by it (outside), and the\n * arrowheads as filled outlines; import merges such a group back into one path. A variable-width\n * stroke exports as its filled outline (`data-vector-part=\"stroke-outline\"`) with the profile\n * and line style kept in `data-vector-width-profile` / `data-vector-stroke-*` attributes.\n *\n * A mask group exports as a `<g data-vector-mask>` (the settings as JSON) carrying the group's\n * transform, opacity, blend mode and filter, around a `<g data-vector-part=\"masked\">` with the\n * contents and `clip-path` / `mask`, so the group's appearance applies to the masked result. A\n * clip's `<clipPath>` holds the mask's outlines; for import, the mask itself is kept in a hidden\n * `<g data-vector-part=\"mask-source\">`. An opacity mask's `<mask>` holds the mask as drawn.\n */\nimport { bezierPathToSvg } from '../canvas/pathops/bezier.js';\nimport { bezierPathBounds, transformBezierPath } from '../canvas/pathops/bezier.js';\nimport { invertMatrix } from '../geom/affine.js';\nimport { isVectorFrame, sanitizeVectorFrame, sanitizeVectorResizing, vectorFrameRectPath, type VectorFrameGroup } from './frames.js';\nimport type { VectorConnector, VectorResizing } from './types.js';\nimport { sanitizeVectorConnector } from './connectors.js';\nimport { sanitizeVectorSymmetry, transformVectorSymmetry } from './symmetry.js';\nimport { isVectorShadedPaint, sanitizeVectorShadedPaint, vectorShadedSvgDefs } from './shading.js';\n\n/** `v` rounded to a whole number when within 1e-9 of one. */\nconst tidy = (v: number) => (Math.abs(v - Math.round(v)) < 1e-9 ? Math.round(v) + 0 : v);\n\n/** JSON from an attribute, or null when it does not parse. */\nconst parseJson = (text: string | undefined): unknown => {\n\tif (text === undefined) return null;\n\ttry {\n\t\treturn JSON.parse(text);\n\t} catch {\n\t\treturn null;\n\t}\n};\nimport { hasStrokeExtras, strokeWidthProfileOf, vectorStrokeLineArea, vectorStrokeOutlinePath, vectorStrokeParts, vectorStrokeReach } from './stroke.js';\nimport { sanitizeWidthProfile } from './width.js';\nimport { expandVectorAppearance, hasOwnVectorAppearance, sanitizeVectorEffects, transformVectorEffects, vectorAppearanceNodes, vectorInstanceDrawn } from './appearance.js';\nimport { resolveVectorSymbols } from './symbols.js';\nimport { isVectorMaskGroup, sanitizeVectorMask, vectorMaskRenderData } from './mask.js';\nimport { sanitizeVectorTextFields, vectorTextGeometryNode, vectorTextPaths, vectorTextSpans, vectorTextSpanSvg } from './text.js';\nimport { activeVectorFilters, sanitizeVectorFilters, vectorFilterMarkup, vectorFilterSvg, type VectorRenderFilter } from './filters.js';\nimport {\n\tneedsVectorPaintLayers,\n\tvectorFills,\n\tvectorStrokes,\n\tsanitizeVectorFills,\n\tsanitizeVectorStrokes,\n\tvectorBlendModeCss,\n\tvectorBlendModeFromCss,\n\tvectorPaintLayerNodes,\n\tvectorStrokeStackReach,\n\tnormalizeVectorPaintStacks,\n\twithVectorFills,\n\twithVectorStrokes,\n\thasVectorPaintStacks,\n\tvectorStrokeSettings\n} from './paintLayers.js';\nimport { angleToSvgLinearCoords, type SvgGradientDef } from '../canvas/gradient.js';\nimport { bezierPathBounds as pathBounds } from '../canvas/pathops/bezier.js';\nimport { isVectorGradient, sanitizeVectorGradient, vectorGradientSvgDefs, type VectorPaintDef } from './gradient.js';\nimport { vectorStrokeGradientDefs } from './gradientStroke.js';\nimport { formatNumber } from '../canvas/shapeGeometry.js';\nimport {\n\tbezierToSubpaths,\n\tdecomposeRigid,\n\tellipseSubpath,\n\thasPaint,\n\tIDENTITY_MATRIX,\n\tisIdentityMatrix,\n\tlineSubpath,\n\tmultiplyMatrices,\n\trectSubpath,\n\trotateMatrix,\n\tscaleMatrix,\n\tsubpathsToBezier,\n\ttransformVectorNode,\n\ttranslateMatrix,\n\tvectorPathData,\n\tunionBounds,\n\tvectorNodeBounds,\n\ttype AffineMatrix\n} from './geometry.js';\nimport {\n\tVECTOR_ARROWHEADS,\n\tVECTOR_CORNER_KINDS,\n\ttype VectorArrowhead,\n\ttype VectorBlend,\n\ttype VectorBooleanOperation,\n\ttype VectorCornerKind,\n\ttype VectorDocument,\n\ttype VectorFilter,\n\ttype VectorFillRule,\n\ttype VectorGradient,\n\ttype VectorGradientStop,\n\ttype VectorGroupNode,\n\ttype VectorEffect,\n\ttype VectorLineCap,\n\ttype VectorLineJoin,\n\ttype VectorWidthPoint,\n\ttype VectorNode,\n\ttype VectorPaint,\n\ttype VectorBounds,\n\ttype VectorPathNode,\n\ttype VectorPaintLayer,\n\ttype VectorStrokeAlign,\n\ttype VectorSubpath,\n\ttype VectorSymbol,\n\ttype VectorInstanceNode,\n\ttype VectorTextNode\n} from './types.js';\n\n// ---------------------------------------------------------------------------\n// Export\n// ---------------------------------------------------------------------------\n\nexport interface VectorSvgExportOptions {\n\t/** Decimal places for coordinates (default 3). */\n\tprecision?: number;\n\t/** Draw `document.background` as a full-size rect (default true). */\n\tbackground?: boolean;\n\t/** Include hidden nodes with `display=\"none\"` instead of leaving them out (default false). */\n\tincludeHidden?: boolean;\n\t/** Prefix for gradient ids (default `vg-`), to keep ids unique when several SVGs share a page. */\n\tidPrefix?: string;\n\t/** Indent nested elements (default true). */\n\tpretty?: boolean;\n\t/**\n\t * How strokes with an inside / outside alignment or arrowheads are written: `clip` (default)\n\t * as a double-width stroke clipped or masked by the shape plus filled heads, `outline` as\n\t * one filled path of the area the stroke paints.\n\t */\n\tstrokes?: 'clip' | 'outline';\n\t/**\n\t * Groups to write round nodes, by node id, outermost first: to move a node from outside it\n\t * or clip it (the animation editor's reveals and its Flair export use this).\n\t */\n\twrap?: Readonly<Record<string, readonly VectorSvgWrapper[]>>;\n\t/**\n\t * How text is written: `text` (default) as SVG `<text>` placed character by character, or\n\t * `outlines` as its glyph outlines (needs an outline shaper; otherwise text stays text). Text with\n\t * path effects is always written as outlines when it has them. Either way the text is kept for\n\t * import.\n\t */\n\ttext?: 'text' | 'outlines';\n}\n\n/** A group written round a node (see `VectorSvgExportOptions.wrap`). */\nexport interface VectorSvgWrapper {\n\tid?: string;\n\t/** An SVG `transform` attribute. */\n\ttransform?: string;\n\t/**\n\t * Clips the group through a rect (`x`, `y`, `width`, `height`) or circle (`cx`, `cy`, `r`) in\n\t * the units of the group's own box (`clipPathUnits=\"objectBoundingBox\"`: 0–1 across it).\n\t */\n\tclip?: { id: string; shape: 'rect' | 'circle'; shapeId?: string; attrs: Readonly<Record<string, number>> };\n}\n\n/** `data-vector-corners`: the live corners of subpaths as `subpath.index:radius[:kind]`, space separated. */\nexport function vectorCornersAttribute(subpaths: readonly VectorSubpath[], precision = 3): string {\n\tconst out: string[] = [];\n\tsubpaths.forEach((sp, s) =>\n\t\tsp.anchors.forEach((a, i) => {\n\t\t\tif (!a.corner || !(a.corner.radius > 0)) return;\n\t\t\tout.push(`${s}.${i}:${formatNumber(a.corner.radius, precision)}${a.corner.kind && a.corner.kind !== 'round' ? `:${a.corner.kind}` : ''}`);\n\t\t})\n\t);\n\treturn out.join(' ');\n}\n\n/** Puts `data-vector-corners` back on subpaths (malformed entries are ignored). */\nexport function applyVectorCornersAttribute(subpaths: VectorSubpath[], value: string): VectorSubpath[] {\n\tfor (const item of value.trim().split(/\\s+/)) {\n\t\tconst m = /^(\\d+)\\.(\\d+):([\\d.eE+-]+)(?::([a-z]+))?$/.exec(item);\n\t\tif (!m) continue;\n\t\tconst a = subpaths[+m[1]]?.anchors[+m[2]];\n\t\tconst radius = parseFloat(m[3]);\n\t\tif (!a || !(radius > 0)) continue;\n\t\tconst kind = VECTOR_CORNER_KINDS.includes(m[4] as VectorCornerKind) ? (m[4] as VectorCornerKind) : undefined;\n\t\ta.corner = { radius, ...(kind && kind !== 'round' ? { kind } : {}) };\n\t}\n\treturn subpaths;\n}\n\nconst escapeAttr = (value: string) => value.replace(/&/g, '&amp;').replace(/\"/g, '&quot;').replace(/</g, '&lt;').replace(/>/g, '&gt;');\nconst escapeText = (value: string) => value.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');\n\n/** Where a paint goes: what `vectorPaintToSvg` needs to place a gradient on a shape. */\nexport interface VectorPaintSvgOptions {\n\t/** The path painted (its box places `objectBoundingBox` gradients; strokes need its geometry). */\n\tnode?: VectorPathNode;\n\t/** `stroke` lays `along` / `across` gradients on the stroke and covers its reach (default `fill`). */\n\trole?: 'fill' | 'stroke';\n\tprecision?: number;\n}\n\n/** The box of a path's drawn outline in its own space (null when it has no points). */\nexport function vectorPathLocalBounds(node: VectorPathNode): VectorBounds | null {\n\tconst b = pathBounds(subpathsToBezier(node.subpaths));\n\treturn b ? { x: b.minX, y: b.minY, width: b.maxX - b.minX, height: b.maxY - b.minY } : null;\n}\n\n/** Paint defs are recomputed only when the node (or the id / role asked for) changes. */\nconst paintCache = new WeakMap<object, Map<string, VectorPaintDef[]>>();\n\n/**\n * A paint as an SVG attribute value plus the paint servers it needs (`url(#id)` refers to the\n * first). Gradients sit in the painted element's user space (the node's own space).\n */\nexport function vectorPaintToSvg(paint: VectorPaint | undefined, gradientId: string, options: VectorPaintSvgOptions = {}): { value: string; defs: VectorPaintDef[] } {\n\tif (!hasPaint(paint)) return { value: 'none', defs: [] };\n\tif (typeof paint === 'string') return { value: paint, defs: [] };\n\tif (isVectorShadedPaint(paint)) {\n\t\t// Meshes and freeform gradients: a pattern of flat tiles over the shape (cached per paint and box).\n\t\tconst node = options.node;\n\t\tconst bounds = node ? vectorPathLocalBounds(node) : null;\n\t\tconst reach = node && options.role === 'stroke' ? vectorStrokeReach(node) + 1 : 1;\n\t\tconst area = bounds ? { x: bounds.x - reach, y: bounds.y - reach, width: bounds.width + 2 * reach, height: bounds.height + 2 * reach } : null;\n\t\tconst key = `${gradientId}|${options.role ?? 'fill'}|${options.precision ?? 3}|${area ? [area.x, area.y, area.width, area.height].join(',') : ''}`;\n\t\tlet byKey = paintCache.get(paint);\n\t\tconst hit = byKey?.get(key);\n\t\tif (hit) return { value: `url(#${gradientId})`, defs: hit };\n\t\tconst defs = vectorShadedSvgDefs(paint, gradientId, { bounds, area, precision: options.precision ?? 3 });\n\t\tif (!byKey) paintCache.set(paint, (byKey = new Map()));\n\t\tbyKey.set(key, defs);\n\t\treturn { value: `url(#${gradientId})`, defs };\n\t}\n\tif (!isVectorGradient(paint)) return { value: 'none', defs: [] };\n\tconst role = options.role ?? 'fill';\n\tconst precision = options.precision ?? 3;\n\tconst key = `${gradientId}|${role}|${precision}`;\n\tconst owner: object = options.node ?? paint;\n\tconst cached = paintCache.get(owner)?.get(key);\n\tif (cached && (!options.node || (role === 'fill' ? options.node.fill : options.node.stroke) === paint)) return { value: `url(#${gradientId})`, defs: cached };\n\tconst node = options.node;\n\tconst bounds = node ? vectorPathLocalBounds(node) : null;\n\tconst reach = node && role === 'stroke' ? vectorStrokeReach(node) + 1 : 1;\n\tconst area = bounds ? { x: bounds.x - reach, y: bounds.y - reach, width: bounds.width + 2 * reach, height: bounds.height + 2 * reach } : null;\n\tconst defs =\n\t\tnode && role === 'stroke' && (paint.strokeMode === 'along' || paint.strokeMode === 'across')\n\t\t\t? vectorStrokeGradientDefs(paint, gradientId, node, { bounds, area, precision })\n\t\t\t: vectorGradientSvgDefs(paint, gradientId, { bounds, area, precision });\n\tlet byKey = paintCache.get(owner);\n\tif (!byKey) paintCache.set(owner, (byKey = new Map()));\n\tbyKey.set(key, defs);\n\treturn { value: `url(#${gradientId})`, defs };\n}\n\n/** The parts of an aligned or arrowed stroke (see `VectorRenderPath.strokeParts`). */\nexport interface VectorRenderStrokeParts {\n\talign: VectorStrokeAlign;\n\t/** The line the stroke follows (shortened under `tip`-aligned heads). */\n\td: string;\n\t/** Width to draw it with: twice the stroke width when aligned, half of it being clipped away. */\n\twidth: number;\n\t/**\n\t * A variable-width stroke: the area to fill with `stroke` (nonzero) instead of stroking `d`,\n\t * clipped or masked like the stroke would be.\n\t */\n\toutline?: string;\n\t/**\n\t * Inside: a `<clipPath id>` holding the shape (`d`, `clip-rule` = `fillRule`). Outside: a\n\t * `<mask id>` in user space over `bounds`, white with the shape (`d`) in black.\n\t */\n\tclip: { kind: 'clip' | 'mask'; id: string; bounds: VectorBounds } | null;\n\t/** Arrowhead outlines (fill with `stroke`, nonzero). */\n\theads: string[];\n}\n\n/** Stroke parts are recomputed only when the node (or the id / precision asked for) changes. */\nconst partsCache = new WeakMap<VectorPathNode, { clipId: string; precision: number; parts: VectorRenderStrokeParts | undefined }>();\n\n/** The stroke parts of a path whose stroke needs more than one element, in its own space (undefined otherwise). */\nexport function vectorStrokeSvgParts(node: VectorPathNode, clipId: string, precision = 3): VectorRenderStrokeParts | undefined {\n\tif (!hasPaint(node.stroke) || !hasStrokeExtras(node)) return undefined;\n\tconst hit = partsCache.get(node);\n\tif (hit && hit.clipId === clipId && hit.precision === precision) return hit.parts;\n\tconst parts = computeStrokeSvgParts(node, clipId, precision);\n\tpartsCache.set(node, { clipId, precision, parts });\n\treturn parts;\n}\n\nfunction computeStrokeSvgParts(node: VectorPathNode, clipId: string, precision: number): VectorRenderStrokeParts | undefined {\n\tconst path = subpathsToBezier(node.subpaths);\n\tconst parts = vectorStrokeParts(path, node);\n\tconst profiled = !!strokeWidthProfileOf(node);\n\tif (parts.align === 'center' && !parts.heads.length && !profiled) return undefined;\n\tlet clip: VectorRenderStrokeParts['clip'] = null;\n\tif (parts.align !== 'center') {\n\t\tconst b = bezierPathBounds(path);\n\t\tconst pad = vectorStrokeReach(node) + 1;\n\t\tconst bounds = b ? { x: round2(b.minX - pad), y: round2(b.minY - pad), width: round2(b.maxX - b.minX + 2 * pad), height: round2(b.maxY - b.minY + 2 * pad) } : { x: 0, y: 0, width: 0, height: 0 };\n\t\tclip = { kind: parts.align === 'inside' ? 'clip' : 'mask', id: clipId, bounds };\n\t}\n\treturn {\n\t\talign: parts.align,\n\t\td: bezierPathToSvg(parts.line, { precision }),\n\t\twidth: parts.drawWidth,\n\t\t...(profiled && (node.strokeWidth ?? 1) > 0 ? { outline: bezierPathToSvg(vectorStrokeLineArea(parts, node), { precision }) } : {}),\n\t\tclip,\n\t\theads: parts.heads.map((h) => bezierPathToSvg(h.path, { precision }))\n\t};\n}\n\n/**\n * The box a node draws over in its own space (its `transform` not applied): its geometry as drawn\n * (effects applied), padded by how far its strokes reach. Null when it draws nothing.\n */\nexport function vectorNodeLocalPaintBounds(node: VectorNode): VectorBounds | null {\n\tconst drawn = expandVectorAppearance(node);\n\tconst reach = (n: VectorNode): number => (n.type === 'path' ? vectorStrokeStackReach(n) : n.type === 'text' || n.type === 'instance' ? reach(expandVectorAppearance(n)) : Math.max(0, ...n.children.map(reach)));\n\tlet b: VectorBounds | null;\n\tif (drawn.type === 'path') b = vectorPathLocalBounds(drawn);\n\telse b = unionBounds(drawn.children.filter((c) => c.visible !== false).map((c) => vectorNodeBounds(c, IDENTITY_MATRIX)));\n\tif (!b) return null;\n\tconst pad = reach(drawn);\n\treturn { x: b.x - pad, y: b.y - pad, width: b.width + 2 * pad, height: b.height + 2 * pad };\n}\n\nconst filterCache = new WeakMap<VectorNode, { id: string; filter: VectorRenderFilter | null }>();\n\n/** A node's filter (`node.filters`) as render data with id `id`, or null when none draws. Cached per node. */\nexport function vectorNodeFilterSvg(node: VectorNode, id: string): VectorRenderFilter | null {\n\tif (!node.filters?.length) return null;\n\tconst hit = filterCache.get(node);\n\tif (hit && hit.id === id) return hit.filter;\n\tconst active = activeVectorFilters(node);\n\tconst filter = active.length ? vectorFilterSvg(active, id, vectorNodeLocalPaintBounds(node)) : null;\n\tfilterCache.set(node, { id, filter });\n\treturn filter;\n}\n\n/** A width profile as a data attribute: `t,left,right` points separated by `;`. */\nexport function widthProfileToAttribute(points: readonly VectorWidthPoint[], precision = 4): string {\n\treturn points.map((p) => [p.t, p.left, p.right].map((n) => formatNumber(n, precision)).join(',')).join(';');\n}\n\n/** Reads `widthProfileToAttribute` output (invalid points are dropped). */\nexport function widthProfileFromAttribute(value: string | undefined): VectorWidthPoint[] {\n\tif (!value) return [];\n\treturn sanitizeWidthProfile(\n\t\tvalue.split(';').map((part) => {\n\t\t\tconst [t, left, right] = part.split(',').map((n) => parseFloat(n));\n\t\t\treturn { t, left, right: Number.isFinite(right) ? right : left };\n\t\t})\n\t);\n}\n\nconst round2 = (n: number) => Math.round(n * 100) / 100;\n\nfunction gradientMarkup(def: SvgGradientDef, extra = ''): string {\n\tconst tag = def.type === 'radial' ? 'radialGradient' : 'linearGradient';\n\tconst attrs = Object.entries(def.attrs)\n\t\t.map(([k, v]) => ` ${k}=\"${escapeAttr(String(v))}\"`)\n\t\t.join('');\n\tconst stops = def.stops\n\t\t.map((s) => `<stop offset=\"${s.offset}\" stop-color=\"${escapeAttr(s.stopColor)}\"${s.stopOpacity !== undefined ? ` stop-opacity=\"${s.stopOpacity}\"` : ''}/>`)\n\t\t.join('');\n\treturn `<${tag} id=\"${escapeAttr(def.id)}\"${attrs}${extra}>${stops}</${tag}>`;\n}\n\n/**\n * A paint server's markup. The first def of a gradient carries `data-vector-gradient` (the\n * gradient as JSON, in the node's space) so import restores what SVG cannot say: midpoints,\n * interpolation, smoothness, conic / reflected / diamond styles and stroke modes.\n */\nfunction paintDefMarkup(def: VectorPaintDef, gradient?: VectorGradient): string {\n\tconst extra = gradient ? ` data-vector-gradient=\"${escapeAttr(JSON.stringify(gradient))}\"` : '';\n\tif (def.type !== 'pattern') return gradientMarkup(def, extra);\n\tconst attrs = Object.entries(def.attrs)\n\t\t.map(([k, v]) => ` ${k}=\"${escapeAttr(String(v))}\"`)\n\t\t.join('');\n\tconst inner = def.gradients.map((g) => gradientMarkup(g)).join('') + def.tiles.map((t) => `<path d=\"${t.d}\" fill=\"${escapeAttr(t.fill)}\"/>`).join('');\n\treturn `<pattern id=\"${escapeAttr(def.id)}\"${attrs}${extra}>${inner}</pattern>`;\n}\n\n/** Markup of a paint's defs (the gradient's data attribute on the first). */\nconst paintMarkup = (paint: VectorPaint | undefined, defs: readonly VectorPaintDef[]) => defs.map((d, i) => paintDefMarkup(d, i === 0 && isVectorGradient(paint) ? paint : undefined));\n\n/**\n * `data-vector-blend` (a blend group's options as JSON, its spine in the group's space) back to\n * a blend, the spine carried by `m` (import bakes group transforms into the children).\n */\nfunction blendFromAttribute(value: string | undefined, m: AffineMatrix): VectorBlend | null {\n\tif (!value) return null;\n\tlet raw: unknown;\n\ttry {\n\t\traw = JSON.parse(value);\n\t} catch {\n\t\treturn null;\n\t}\n\tif (!raw || typeof raw !== 'object') return null;\n\tconst r = raw as Record<string, unknown>;\n\tconst out: VectorBlend = {};\n\tif (r.spacing === 'steps' || r.spacing === 'distance' || r.spacing === 'smoothColor') out.spacing = r.spacing;\n\tif (typeof r.steps === 'number' && Number.isFinite(r.steps)) out.steps = Math.min(1000, Math.max(1, Math.round(r.steps)));\n\tif (typeof r.distance === 'number' && r.distance > 0) out.distance = r.distance;\n\tif (typeof r.orientToSpine === 'boolean') out.orientToSpine = r.orientToSpine;\n\tif (typeof r.linear === 'boolean') out.linear = r.linear;\n\tif (r.starts && typeof r.starts === 'object') {\n\t\tconst starts = Object.fromEntries(Object.entries(r.starts as Record<string, unknown>).filter((e): e is [string, number] => Number.isInteger(e[1]) && (e[1] as number) >= 0));\n\t\tif (Object.keys(starts).length) out.starts = starts;\n\t}\n\tconst spine = r.spine as VectorSubpath | null | undefined;\n\tif (spine && Array.isArray(spine.anchors) && spine.anchors.every((a) => a && Number.isFinite(a.x) && Number.isFinite(a.y))) {\n\t\tconst sp: VectorSubpath = { closed: !!spine.closed, anchors: spine.anchors.map((a) => ({ x: a.x, y: a.y, ...(a.in ? { in: { x: a.in.x, y: a.in.y } } : {}), ...(a.out ? { out: { x: a.out.x, y: a.out.y } } : {}) })) };\n\t\tout.spine = m === IDENTITY_MATRIX ? sp : transformVectorNode<VectorPathNode>({ id: '', type: 'path', subpaths: [sp] }, m).subpaths[0];\n\t}\n\treturn out;\n}\n\n/** Serializes a vector document as a standalone SVG string. */\nexport function vectorDocumentToSvg(doc: VectorDocument, options: VectorSvgExportOptions = {}): string {\n\t// Instances draw their symbol's art: resolve it when the caller's document has not.\n\tdoc = resolveVectorSymbols(doc);\n\tconst precision = options.precision ?? 3;\n\tconst prefix = options.idPrefix ?? 'vg-';\n\tconst pretty = options.pretty !== false;\n\tconst defs: string[] = [];\n\tconst lines: string[] = [];\n\tconst num = (n: number) => formatNumber(n, precision);\n\tconst indent = (depth: number) => (pretty ? ' '.repeat(depth) : '');\n\n\tconst common = (node: VectorNode) => {\n\t\tlet out = ` id=\"${escapeAttr(node.id)}\"`;\n\t\tif (node.transform) out += ` transform=\"matrix(${node.transform.map((n) => formatNumber(n, 6)).join(' ')})\"`;\n\t\tif (node.opacity !== undefined && node.opacity < 1) out += ` opacity=\"${num(node.opacity)}\"`;\n\t\tif (node.visible === false) out += ` display=\"none\"`;\n\t\tif (node.blendStep) out += ` data-vector-blend-step=\"\"`;\n\t\tif (node.type === 'group' && node.blend) out += ` data-vector-blend=\"${escapeAttr(JSON.stringify(node.blend))}\"`;\n\t\tif (node.booleanOperation) out += ` data-vector-boolean-operation=\"${node.booleanOperation}\"`;\n\t\tif (node.resizing) out += ` data-vector-resizing=\"${escapeAttr(JSON.stringify(node.resizing))}\"`;\n\t\tif (node.type === 'path' && isVectorShadedPaint(node.fill)) out += ` data-vector-shading=\"${escapeAttr(JSON.stringify(node.fill))}\"`;\n\t\tif (node.type === 'path' && node.connector) out += ` data-vector-connector=\"${escapeAttr(JSON.stringify(node.connector))}\"`;\n\t\tconst blend = vectorBlendModeCss(node.blendMode);\n\t\tif (blend) out += ` style=\"mix-blend-mode:${blend}\"`;\n\t\tif (node.filters?.length) {\n\t\t\t// The filter as drawn, carrying the filter stack (JSON) for import.\n\t\t\tconst filter = vectorNodeFilterSvg(node, `${prefix}filter-${node.id}`);\n\t\t\tconst data = ` data-vector-filters=\"${escapeAttr(JSON.stringify(node.filters))}\"`;\n\t\t\tif (filter) {\n\t\t\t\tdefs.push(vectorFilterMarkup(filter, data));\n\t\t\t\tout += ` filter=\"url(#${escapeAttr(filter.id)})\"`;\n\t\t\t} else out += data;\n\t\t}\n\t\treturn out;\n\t};\n\n\t/** Opacity and blend mode of one paint layer, as attributes. */\n\tconst layerAttrs = (layer: { opacity?: number; blendMode?: VectorPaintLayer['blendMode'] }) => {\n\t\tlet out = '';\n\t\tif (layer.opacity !== undefined && layer.opacity < 1) out += ` opacity=\"${num(layer.opacity)}\"`;\n\t\tconst blend = vectorBlendModeCss(layer.blendMode);\n\t\tif (blend) out += ` style=\"mix-blend-mode:${blend}\"`;\n\t\treturn out;\n\t};\n\n\t/**\n\t * The elements of a stroke drawn in parts (aligned, arrowed or profiled): the stroke (or its\n\t * outline) clipped or masked by the shape, then the heads. `d` is the shape's path data.\n\t */\n\tconst strokePartLines = (node: VectorPathNode, parts: VectorRenderStrokeParts, strokeValue: string, d: string, lineAttrs: (width: number) => string, depth: number): string[] => {\n\t\tconst out: string[] = [];\n\t\tif (options.strokes === 'outline') {\n\t\t\tconst area = bezierPathToSvg(vectorStrokeOutlinePath(subpathsToBezier(node.subpaths), node), { precision });\n\t\t\tout.push(`${indent(depth)}<path data-vector-part=\"stroke-outline\" d=\"${area}\" fill=\"${escapeAttr(strokeValue)}\"/>`);\n\t\t\treturn out;\n\t\t}\n\t\tlet clip = '';\n\t\tif (parts.clip) {\n\t\t\tconst rule = node.fillRule === 'evenodd' ? 'evenodd' : 'nonzero';\n\t\t\tconst id = escapeAttr(parts.clip.id);\n\t\t\tif (parts.clip.kind === 'clip') {\n\t\t\t\tdefs.push(`<clipPath id=\"${id}\"><path d=\"${d}\" clip-rule=\"${rule}\"/></clipPath>`);\n\t\t\t\tclip = ` clip-path=\"url(#${id})\"`;\n\t\t\t} else {\n\t\t\t\tconst b = parts.clip.bounds;\n\t\t\t\tconst box = `x=\"${num(b.x)}\" y=\"${num(b.y)}\" width=\"${num(b.width)}\" height=\"${num(b.height)}\"`;\n\t\t\t\tdefs.push(`<mask id=\"${id}\" maskUnits=\"userSpaceOnUse\" ${box}><rect ${box} fill=\"#fff\"/><path d=\"${d}\" fill=\"#000\" fill-rule=\"${rule}\"/></mask>`);\n\t\t\t\tclip = ` mask=\"url(#${id})\"`;\n\t\t\t}\n\t\t}\n\t\tif (parts.outline !== undefined) out.push(`${indent(depth)}<path data-vector-part=\"stroke-outline\" d=\"${parts.outline}\" fill=\"${escapeAttr(strokeValue)}\"${clip}/>`);\n\t\telse out.push(`${indent(depth)}<path data-vector-part=\"stroke\" d=\"${parts.d}\" fill=\"none\"${lineAttrs(parts.width)}${clip}/>`);\n\t\tfor (const h of parts.heads) out.push(`${indent(depth)}<path data-vector-part=\"head\" d=\"${h}\" fill=\"${escapeAttr(strokeValue)}\"/>`);\n\t\treturn out;\n\t};\n\n\t/** SVG line attributes of a (layer) node's stroke. */\n\tconst lineAttrsOf = (node: VectorPathNode, strokeValue: string) => (width: number) => {\n\t\tlet out = ` stroke=\"${escapeAttr(strokeValue)}\" stroke-width=\"${num(width)}\"`;\n\t\tif (node.strokeLinecap && node.strokeLinecap !== 'butt') out += ` stroke-linecap=\"${node.strokeLinecap}\"`;\n\t\tif (node.strokeLinejoin && node.strokeLinejoin !== 'miter') out += ` stroke-linejoin=\"${node.strokeLinejoin}\"`;\n\t\tif (node.strokeDasharray?.length) out += ` stroke-dasharray=\"${node.strokeDasharray.map(num).join(' ')}\"`;\n\t\treturn out;\n\t};\n\n\t/** `data-vector-d` / `data-vector-corners` of a path with live corners ('' without). */\n\tconst liveCorners = (node: VectorPathNode) => {\n\t\tconst corners = vectorCornersAttribute(node.subpaths, precision);\n\t\treturn corners ? ` data-vector-d=\"${bezierPathToSvg(subpathsToBezier(node.subpaths, { corners: false }), { precision })}\" data-vector-corners=\"${corners}\"` : '';\n\t};\n\n\t/**\n\t * A path painted through its stacks: a `<g data-vector-path>` carrying the stacks (JSON, for\n\t * import), holding each drawn layer bottom to top. The first part is a fill part with the\n\t * geometry (unpainted when no fill is drawn).\n\t */\n\tconst emitStacked = (node: VectorPathNode, depth: number) => {\n\t\tconst d = vectorPathData(node, precision);\n\t\tconst rule = node.fillRule === 'evenodd' ? ` fill-rule=\"evenodd\"` : '';\n\t\tlet data = ` data-vector-path=\"\" data-vector-fills=\"${escapeAttr(JSON.stringify(vectorFills(node)))}\" data-vector-strokes=\"${escapeAttr(JSON.stringify(vectorStrokes(node)))}\"`;\n\t\tif (node.fillRule === 'evenodd') data += ` data-vector-fill-rule=\"evenodd\"`;\n\t\tlines.push(`${indent(depth)}<g${common(node)}${data}>`);\n\t\tconst layers = vectorPaintLayerNodes(node).filter((l) => l.drawn);\n\t\tlet geometry = liveCorners(node);\n\t\tif (!layers.some((l) => l.kind === 'fill')) {\n\t\t\tlines.push(`${indent(depth + 1)}<path data-vector-part=\"fill\" d=\"${d}\" fill=\"none\"${rule}${geometry}/>`);\n\t\t\tgeometry = '';\n\t\t}\n\t\tfor (const l of layers) {\n\t\t\tconst id = `${prefix}${l.kind}-${node.id}-${l.index}`;\n\t\t\tconst paint = vectorPaintToSvg(l.layer.paint, id, { node: l.node, precision, ...(l.kind === 'stroke' ? { role: 'stroke' as const } : {}) });\n\t\t\tdefs.push(...paintMarkup(l.layer.paint, paint.defs));\n\t\t\tconst attrs = ` data-vector-layer=\"${l.index}\"${layerAttrs(l.layer)}`;\n\t\t\tif (l.kind === 'fill') {\n\t\t\t\tlines.push(`${indent(depth + 1)}<path data-vector-part=\"fill\"${attrs} d=\"${d}\" fill=\"${escapeAttr(paint.value)}\"${rule}${geometry}/>`);\n\t\t\t\tgeometry = '';\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tconst lineAttrs = lineAttrsOf(l.node, paint.value);\n\t\t\tconst parts = vectorStrokeSvgParts(l.node, `${prefix}clip-${node.id}-${l.index}`, precision);\n\t\t\tif (!parts) {\n\t\t\t\tlines.push(`${indent(depth + 1)}<path data-vector-part=\"stroke\"${attrs} d=\"${d}\" fill=\"none\"${lineAttrs(l.node.strokeWidth ?? 1)}/>`);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tlines.push(`${indent(depth + 1)}<g data-vector-part=\"stroke-layer\"${attrs}>`);\n\t\t\tlines.push(...strokePartLines(l.node, parts, paint.value, d, lineAttrs, depth + 2));\n\t\t\tlines.push(`${indent(depth + 1)}</g>`);\n\t\t}\n\t\tlines.push(`${indent(depth)}</g>`);\n\t};\n\n\tconst emit = (node: VectorNode, depth: number) => {\n\t\tif (node.visible === false && !options.includeHidden) return;\n\t\tconst wrappers = options.wrap?.[node.id] ?? [];\n\t\twrappers.forEach((w, i) => {\n\t\t\tlet attrs = w.id !== undefined ? ` id=\"${escapeAttr(w.id)}\"` : '';\n\t\t\tif (w.transform) attrs += ` transform=\"${escapeAttr(w.transform)}\"`;\n\t\t\tif (w.clip) {\n\t\t\t\tconst shape = Object.entries(w.clip.attrs).map(([k, v]) => ` ${k}=\"${formatNumber(v, 4)}\"`).join('');\n\t\t\t\tdefs.push(`<clipPath id=\"${escapeAttr(w.clip.id)}\" clipPathUnits=\"objectBoundingBox\"><${w.clip.shape}${w.clip.shapeId !== undefined ? ` id=\"${escapeAttr(w.clip.shapeId)}\"` : ''}${shape}/></clipPath>`);\n\t\t\t\tattrs += ` clip-path=\"url(#${escapeAttr(w.clip.id)})\"`;\n\t\t\t}\n\t\t\tlines.push(`${indent(depth + i)}<g${attrs}>`);\n\t\t});\n\t\temitNode(node, depth + wrappers.length);\n\t\tfor (let i = wrappers.length - 1; i >= 0; i--) lines.push(`${indent(depth + i)}</g>`);\n\t};\n\n\t/** The lines `fn` emits, taken out of the document (for markup that goes into `defs`). */\n\tconst capture = (fn: () => void): string => {\n\t\tconst at = lines.length;\n\t\tfn();\n\t\treturn lines.splice(at).map((l) => l.trim()).join('');\n\t};\n\n\t/**\n\t * A mask group: its appearance on the outer `<g data-vector-mask>`, the contents in an inner\n\t * `<g data-vector-part=\"masked\">` that references the `<clipPath>` or `<mask>`. Effects of the\n\t * group act on the contents, exported as a live group `<id>~content` around them.\n\t */\n\tconst emitMaskGroup = (node: VectorGroupNode & { mask: NonNullable<VectorGroupNode['mask']> }, depth: number) => {\n\t\tconst [source, ...contents] = node.children;\n\t\tconst body: VectorNode[] = node.effects?.length && contents.length ? [{ id: `${node.id}~content`, type: 'group', effects: node.effects, children: contents }] : contents;\n\t\tconst settings = { type: node.mask.type, ...(node.mask.invert ? { invert: true } : {}) };\n\t\tlines.push(`${indent(depth)}<g${common(node)} data-vector-mask=\"${escapeAttr(JSON.stringify(settings))}\">`);\n\t\tconst mask = vectorMaskRenderData(node, `${prefix}mask-${node.id}`, `${prefix}mask-filter-${node.id}`, precision);\n\t\tlet ref = '';\n\t\tif (mask && mask.type !== 'clip') {\n\t\t\tconst b = mask.bounds!;\n\t\t\tconst box = `x=\"${num(b.x)}\" y=\"${num(b.y)}\" width=\"${num(b.width)}\" height=\"${num(b.height)}\"`;\n\t\t\tif (mask.invertFilter) defs.push(vectorFilterMarkup(mask.invertFilter));\n\t\t\tconst inner = capture(() => emitNode(source, depth + 1));\n\t\t\tconst drawn = mask.filter ? `<g data-vector-part=\"mask-invert\" filter=\"${escapeAttr(mask.filter)}\">${inner}</g>` : inner;\n\t\t\tdefs.push(`<mask id=\"${escapeAttr(mask.id)}\" data-vector-part=\"mask-source\" maskUnits=\"userSpaceOnUse\" ${box}${mask.type === 'alpha' ? ' mask-type=\"alpha\"' : ''}>${drawn}</mask>`);\n\t\t\tref = ` mask=\"url(#${escapeAttr(mask.id)})\"`;\n\t\t} else {\n\t\t\t// The mask itself, hidden, for import (a clip's paint is not drawn; a mask turned off is hidden).\n\t\t\tlines.push(`${indent(depth + 1)}<g data-vector-part=\"mask-source\" display=\"none\">`);\n\t\t\temitNode(source, depth + 2);\n\t\t\tlines.push(`${indent(depth + 1)}</g>`);\n\t\t\tif (mask?.clip) {\n\t\t\t\tdefs.push(`<clipPath id=\"${escapeAttr(mask.id)}\">${mask.clip.map((c) => `<path d=\"${c.d}\" clip-rule=\"${c.clipRule}\"/>`).join('')}</clipPath>`);\n\t\t\t\tref = ` clip-path=\"url(#${escapeAttr(mask.id)})\"`;\n\t\t\t}\n\t\t}\n\t\tlines.push(`${indent(depth + 1)}<g data-vector-part=\"masked\"${ref}>`);\n\t\tfor (const child of body) emit(child, depth + 2);\n\t\tlines.push(`${indent(depth + 1)}</g>`);\n\t\tlines.push(`${indent(depth)}</g>`);\n\t};\n\n\t/**\n\t * A text node as SVG text: a `<g data-vector-text>` carrying the text and its stacks (JSON, for\n\t * import), holding one `<text>` per drawn paint layer with a `<tspan>` per styled fragment, every\n\t * character placed by our layout.\n\t */\n\tconst emitTextElement = (node: VectorTextNode, depth: number, attrs: string) => {\n\t\tconst geometry = vectorTextGeometryNode(node);\n\t\tconst fields = { text: node.text, font: node.font, ...(node.runs?.length ? { runs: node.runs } : {}), ...(node.paragraph ? { paragraph: node.paragraph } : {}), frame: node.frame, ...(node.effects?.length ? { effects: node.effects } : {}) };\n\t\tlet data = ` data-vector-text=\"${escapeAttr(JSON.stringify(fields))}\"`;\n\t\tif (hasVectorPaintStacks(node)) data += ` data-vector-fills=\"${escapeAttr(JSON.stringify(vectorFills(node)))}\" data-vector-strokes=\"${escapeAttr(JSON.stringify(vectorStrokes(node)))}\"`;\n\t\telse {\n\t\t\tdata += ` data-vector-fill=\"${escapeAttr(JSON.stringify(node.fill ?? null))}\" data-vector-stroke=\"${escapeAttr(JSON.stringify(node.stroke ?? null))}\"`;\n\t\t\tconst settings = vectorStrokeSettings(node);\n\t\t\tif (Object.keys(settings).length) data += ` data-vector-stroke-settings=\"${escapeAttr(JSON.stringify(settings))}\"`;\n\t\t}\n\t\tlines.push(`${indent(depth)}<g${attrs}${data}>`);\n\t\tconst nodes = vectorPaintLayerNodes(geometry).filter((l) => l.drawn);\n\t\tconst topFill = nodes.filter((l) => l.kind === 'fill').at(-1);\n\t\tconst spans = vectorTextSpans(node).map((sp, i) => {\n\t\t\tif (sp.fill === undefined) return vectorTextSpanSvg(sp);\n\t\t\tconst paint = vectorPaintToSvg(sp.fill, `${prefix}run-${node.id}-${i}`, { node: geometry, precision });\n\t\t\tdefs.push(...paintMarkup(sp.fill, paint.defs));\n\t\t\treturn vectorTextSpanSvg(sp, paint.value);\n\t\t});\n\t\tconst tspans = (runFills: boolean) =>\n\t\t\tspans\n\t\t\t\t.map((sp) => {\n\t\t\t\t\tlet a = ` x=\"${sp.x}\" y=\"${sp.y}\"`;\n\t\t\t\t\tif (sp.rotate) a += ` rotate=\"${sp.rotate}\"`;\n\t\t\t\t\ta += ` font-family=\"${escapeAttr(sp.fontFamily)}\" font-size=\"${num(sp.fontSize)}\"`;\n\t\t\t\t\tif (sp.fontWeight !== 400) a += ` font-weight=\"${sp.fontWeight}\"`;\n\t\t\t\t\tif (sp.fontStyle) a += ` font-style=\"italic\"`;\n\t\t\t\t\tif (sp.textDecoration) a += ` text-decoration=\"${sp.textDecoration}\"`;\n\t\t\t\t\tif (runFills && sp.fill) a += ` fill=\"${escapeAttr(sp.fill)}\"`;\n\t\t\t\t\treturn `<tspan${a}>${escapeText(sp.text)}</tspan>`;\n\t\t\t\t})\n\t\t\t\t.join('');\n\t\tconst layers = nodes.length ? nodes : [];\n\t\tif (!topFill && spans.some((sp) => sp.fill)) lines.push(`${indent(depth + 1)}<text data-vector-part=\"fill\" fill=\"none\" xml:space=\"preserve\">${tspans(true)}</text>`);\n\t\tfor (const l of layers) {\n\t\t\tconst id = `${prefix}${l.kind}-${node.id}-${l.index}`;\n\t\t\tconst paint = vectorPaintToSvg(l.layer.paint, id, { node: l.node, precision, ...(l.kind === 'stroke' ? { role: 'stroke' as const } : {}) });\n\t\t\tdefs.push(...paintMarkup(l.layer.paint, paint.defs));\n\t\t\tconst attrs = ` data-vector-part=\"${l.kind}\" data-vector-layer=\"${l.index}\"${layerAttrs(l.layer)}`;\n\t\t\tconst paintAttrs = l.kind === 'fill' ? ` fill=\"${escapeAttr(paint.value)}\"` : ` fill=\"none\"${lineAttrsOf(l.node, paint.value)(l.node.strokeWidth ?? 1)}`;\n\t\t\tlines.push(`${indent(depth + 1)}<text${attrs}${paintAttrs} xml:space=\"preserve\">${tspans(l === topFill)}</text>`);\n\t\t}\n\t\tif (!layers.length && !spans.some((sp) => sp.fill)) lines.push(`${indent(depth + 1)}<text data-vector-part=\"fill\" fill=\"none\" xml:space=\"preserve\">${tspans(false)}</text>`);\n\t\tlines.push(`${indent(depth)}</g>`);\n\t};\n\n\t/**\n\t * Text: as SVG text, or (with glyph outlines, when it has path effects or `text: 'outlines'`)\n\t * as its outlines with the text kept hidden for import, like other live art.\n\t */\n\tconst emitText = (node: VectorTextNode, depth: number) => {\n\t\tconst outlines = vectorTextPaths(node).outlines;\n\t\tconst effects = !!node.effects?.some((e) => e.enabled !== false);\n\t\tif (!outlines || (!effects && options.text !== 'outlines')) {\n\t\t\temitTextElement(node, depth, common(node));\n\t\t\treturn;\n\t\t}\n\t\tlines.push(`${indent(depth)}<g${common(node)} data-vector-live=\"${escapeAttr(JSON.stringify({ kind: 'text', ...(node.effects?.length ? { effects: node.effects } : {}) }))}\">`);\n\t\tlines.push(`${indent(depth + 1)}<g data-vector-part=\"appearance\">`);\n\t\tfor (const shape of vectorAppearanceNodes(node)) emit(shape, depth + 2);\n\t\tlines.push(`${indent(depth + 1)}</g>`);\n\t\tlines.push(`${indent(depth + 1)}<g data-vector-part=\"source\" display=\"none\">`);\n\t\tconst { effects: _e, transform: _t, opacity: _o, visible: _v, booleanOperation: _b, blendStep: _s, blendMode: _bm, filters: _f, ...source } = node;\n\t\temitTextElement({ ...source, id: `${node.id}~src` }, depth + 2, ` id=\"${escapeAttr(`${node.id}~src`)}\"`);\n\t\tlines.push(`${indent(depth + 1)}</g>`);\n\t\tlines.push(`${indent(depth)}</g>`);\n\t};\n\n\t/** Symbols referenced by `<use>`: written once into `defs` as `<symbol>`. */\n\tconst symbolIds = new Map<string, string>();\n\tconst symbolRef = (symbolId: string): string | null => {\n\t\tconst hit = symbolIds.get(symbolId);\n\t\tif (hit) return hit;\n\t\tconst sym = doc.symbols?.find((x) => x.id === symbolId);\n\t\tif (!sym) return null;\n\t\tconst id = `${prefix}symbol-${symbolId}`;\n\t\tsymbolIds.set(symbolId, id);\n\t\tconst inner = capture(() => sym.nodes.forEach((n) => emit(n, 2)));\n\t\tdefs.push(`<symbol id=\"${escapeAttr(id)}\" data-vector-symbol=\"${escapeAttr(JSON.stringify({ id: sym.id, name: sym.name }))}\" overflow=\"visible\">${inner}</symbol>`);\n\t\treturn id;\n\t};\n\n\t/**\n\t * An instance: a `<use>` of its symbol through its transform when that draws it exactly, else\n\t * its drawn art (overrides, unscaled strokes, effects or filters, which would be placed in the\n\t * symbol's space) in a `<g data-vector-instance>` that keeps what import needs.\n\t */\n\tconst emitInstance = (node: VectorInstanceNode, depth: number) => {\n\t\tconst data = { symbolId: node.symbolId, ...(node.scaleStrokes === false ? { scaleStrokes: false } : {}), ...(node.overrides ? { overrides: node.overrides } : {}) };\n\t\tconst exact = !node.overrides && node.scaleStrokes !== false && !node.effects?.length && !node.filters?.length;\n\t\tconst ref = symbolRef(node.symbolId);\n\t\tif (exact && ref) {\n\t\t\tlines.push(`${indent(depth)}<use${common(node)} href=\"#${escapeAttr(ref)}\" data-vector-instance=\"${escapeAttr(JSON.stringify(data))}\"/>`);\n\t\t\treturn;\n\t\t}\n\t\tconst full = { ...data, ...(node.transform ? { transform: node.transform } : {}), ...(node.effects?.length ? { effects: node.effects } : {}) };\n\t\tlines.push(`${indent(depth)}<g data-vector-instance=\"${escapeAttr(JSON.stringify(full))}\">`);\n\t\temitNode(vectorInstanceDrawn(node), depth + 1);\n\t\tlines.push(`${indent(depth)}</g>`);\n\t};\n\n\t/**\n\t * A frame: a `<g data-vector-frame>` (the frame as JSON, with the group's effects, which the\n\t * export does not draw) holding its fill (`data-vector-part=\"frame-fill\"`) and its children in a\n\t * `<g data-vector-part=\"frame-contents\">` clipped to the frame's rectangle.\n\t */\n\tconst emitFrame = (node: VectorFrameGroup, depth: number) => {\n\t\tconst f = node.frame;\n\t\tconst data = { ...f, ...(node.effects?.length ? { effects: node.effects } : {}) };\n\t\tlines.push(`${indent(depth)}<g${common(node)} data-vector-frame=\"${escapeAttr(JSON.stringify(data))}\">`);\n\t\tconst rect = vectorFrameRectPath(f);\n\t\tif (f.fill !== undefined && f.fill !== null && f.fill !== 'none') {\n\t\t\tlines.push(`${indent(depth + 1)}<g data-vector-part=\"frame-fill\">`);\n\t\t\temitNode({ id: `${node.id}~frame-fill`, type: 'path', fill: f.fill, stroke: null, subpaths: rect }, depth + 2);\n\t\t\tlines.push(`${indent(depth + 1)}</g>`);\n\t\t}\n\t\tlet ref = '';\n\t\tif (f.clip !== false) {\n\t\t\tconst id = `${prefix}frame-${node.id}`;\n\t\t\tdefs.push(`<clipPath id=\"${escapeAttr(id)}\"><rect x=\"${num(f.x)}\" y=\"${num(f.y)}\" width=\"${num(f.width)}\" height=\"${num(f.height)}\"/></clipPath>`);\n\t\t\tref = ` clip-path=\"url(#${escapeAttr(id)})\"`;\n\t\t}\n\t\tlines.push(`${indent(depth + 1)}<g data-vector-part=\"frame-contents\"${ref}>`);\n\t\tfor (const child of node.children) emit(child, depth + 2);\n\t\tlines.push(`${indent(depth + 1)}</g>`);\n\t\tlines.push(`${indent(depth)}</g>`);\n\t};\n\n\tconst emitNode = (node: VectorNode, depth: number) => {\n\t\tif (isVectorFrame(node)) {\n\t\t\temitFrame(node, depth);\n\t\t\treturn;\n\t\t}\n\t\tif (isVectorMaskGroup(node)) {\n\t\t\temitMaskGroup(node, depth);\n\t\t\treturn;\n\t\t}\n\t\tif (node.type === 'instance') {\n\t\t\temitInstance(node, depth);\n\t\t\treturn;\n\t\t}\n\t\tif (node.type === 'text') {\n\t\t\temitText(node, depth);\n\t\t\treturn;\n\t\t}\n\t\tif (hasOwnVectorAppearance(node)) {\n\t\t\t// Live: what it draws, then the editable source (hidden) for import.\n\t\t\tconst live = {\n\t\t\t\tkind: node.type,\n\t\t\t\t...(node.effects?.length ? { effects: node.effects } : {}),\n\t\t\t\t...(node.type === 'group' && node.liveBoolean ? { liveBoolean: node.liveBoolean } : {}),\n\t\t\t\t...(node.type === 'group' && node.symmetry ? { symmetry: node.symmetry } : {})\n\t\t\t};\n\t\t\tlines.push(`${indent(depth)}<g${common(node)} data-vector-live=\"${escapeAttr(JSON.stringify(live))}\">`);\n\t\t\tlines.push(`${indent(depth + 1)}<g data-vector-part=\"appearance\">`);\n\t\t\tfor (const shape of vectorAppearanceNodes(node)) emit(shape, depth + 2);\n\t\t\tlines.push(`${indent(depth + 1)}</g>`);\n\t\t\tlines.push(`${indent(depth + 1)}<g data-vector-part=\"source\" display=\"none\">`);\n\t\t\tif (node.type === 'path') {\n\t\t\t\tconst { effects: _e, transform: _t, opacity: _o, visible: _v, booleanOperation: _b, blendStep: _s, blendMode: _bm, filters: _f, ...source } = node;\n\t\t\t\temit({ ...source, id: `${node.id}~src` }, depth + 2);\n\t\t\t} else for (const child of node.children) emit(child, depth + 2);\n\t\t\tlines.push(`${indent(depth + 1)}</g>`);\n\t\t\tlines.push(`${indent(depth)}</g>`);\n\t\t\treturn;\n\t\t}\n\t\tif (node.type === 'group') {\n\t\t\tlines.push(`${indent(depth)}<g${common(node)}>`);\n\t\t\tfor (const child of node.children) emit(child, depth + 1);\n\t\t\tlines.push(`${indent(depth)}</g>`);\n\t\t\treturn;\n\t\t}\n\t\tif (needsVectorPaintLayers(node)) {\n\t\t\temitStacked(node, depth);\n\t\t\treturn;\n\t\t}\n\t\tconst fill = vectorPaintToSvg(node.fill, `${prefix}fill-${node.id}`, { node, precision });\n\t\tconst stroke = vectorPaintToSvg(node.stroke, `${prefix}stroke-${node.id}`, { node, role: 'stroke', precision });\n\t\tdefs.push(...paintMarkup(node.fill, fill.defs), ...paintMarkup(node.stroke, stroke.defs));\n\t\tconst d = vectorPathData(node, precision);\n\t\tconst live = liveCorners(node);\n\t\tconst fillAttrs = ` fill=\"${escapeAttr(fill.value)}\"${node.fillRule === 'evenodd' ? ` fill-rule=\"evenodd\"` : ''}`;\n\t\tconst lineAttrs = lineAttrsOf(node, stroke.value);\n\t\tconst parts = stroke.value !== 'none' ? vectorStrokeSvgParts(node, `${prefix}clip-${node.id}`, precision) : undefined;\n\t\tif (!parts) {\n\t\t\tlines.push(`${indent(depth)}<path${common(node)} d=\"${d}\"${fillAttrs}${stroke.value !== 'none' ? lineAttrs(node.strokeWidth ?? 1) : ''}${live}/>`);\n\t\t\treturn;\n\t\t}\n\t\t// The stroke options SVG has no attribute for, kept for import.\n\t\tlet data = ` data-vector-path=\"\" data-vector-stroke-width=\"${num(node.strokeWidth ?? 1)}\"`;\n\t\tif (parts.align !== 'center') data += ` data-vector-stroke-align=\"${parts.align}\"`;\n\t\tif (node.startArrow) data += ` data-vector-start-arrow=\"${node.startArrow}\"`;\n\t\tif (node.endArrow) data += ` data-vector-end-arrow=\"${node.endArrow}\"`;\n\t\tif (node.arrowAlign && node.arrowAlign !== 'extend') data += ` data-vector-arrow-align=\"${node.arrowAlign}\"`;\n\t\tif (node.startArrowScale !== undefined && node.startArrowScale !== 1) data += ` data-vector-start-arrow-scale=\"${num(node.startArrowScale)}\"`;\n\t\tif (node.endArrowScale !== undefined && node.endArrowScale !== 1) data += ` data-vector-end-arrow-scale=\"${num(node.endArrowScale)}\"`;\n\t\tconst profile = strokeWidthProfileOf(node);\n\t\tif (profile) {\n\t\t\t// Drawn as a filled outline: keep the line style the outline was built with.\n\t\t\tdata += ` data-vector-width-profile=\"${widthProfileToAttribute(profile)}\"`;\n\t\t\tif (node.strokeLinecap && node.strokeLinecap !== 'butt') data += ` data-vector-stroke-linecap=\"${node.strokeLinecap}\"`;\n\t\t\tif (node.strokeLinejoin && node.strokeLinejoin !== 'miter') data += ` data-vector-stroke-linejoin=\"${node.strokeLinejoin}\"`;\n\t\t\tif (node.strokeDasharray?.length) data += ` data-vector-stroke-dasharray=\"${node.strokeDasharray.map(num).join(' ')}\"`;\n\t\t}\n\t\tlines.push(`${indent(depth)}<g${common(node)}${data}>`);\n\t\tlines.push(`${indent(depth + 1)}<path data-vector-part=\"fill\" d=\"${d}\"${fillAttrs}${live}/>`);\n\t\tlines.push(...strokePartLines(node, parts, stroke.value, d, lineAttrs, depth + 1));\n\t\tlines.push(`${indent(depth)}</g>`);\n\t};\n\n\tfor (const node of doc.nodes) emit(node, 1);\n\t// Symbols no instance uses still go into `defs`, so they come back on import.\n\tfor (const sym of doc.symbols ?? []) symbolRef(sym.id);\n\tconst w = num(doc.width);\n\tconst h = num(doc.height);\n\tconst nl = pretty ? '\\n' : '';\n\tconst out = [`<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"${w}\" height=\"${h}\" viewBox=\"0 0 ${w} ${h}\">`];\n\tif (defs.length) out.push(`${indent(1)}<defs>${defs.join('')}</defs>`);\n\tif (doc.background && options.background !== false && hasPaint(doc.background)) {\n\t\tout.push(`${indent(1)}<rect width=\"${w}\" height=\"${h}\" fill=\"${escapeAttr(doc.background)}\"/>`);\n\t}\n\tout.push(...lines, '</svg>');\n\treturn out.join(nl);\n}\n\n// ---------------------------------------------------------------------------\n// Import\n// ---------------------------------------------------------------------------\n\nconst BOOLEAN_OPERATIONS: readonly VectorBooleanOperation[] = ['union', 'subtract', 'intersect', 'exclude'];\n\nexport interface VectorSvgImportOptions {\n\t/** Makes ids for elements without a usable `id` (default `node-1`, `node-2`, …). */\n\tcreateId?: () => string;\n\t/**\n\t * Merge neighbouring shapes with the same outline into one path with stacked fills and strokes,\n\t * as design tools export several paints on one layer (default false: an SVG may hold identical\n\t * shapes on purpose). Shapes merge only when the paint order stays the same (no stroke under a\n\t * later fill) and they share opacity, visibility, filters and blend mode.\n\t */\n\tmergeStackedShapes?: boolean;\n}\n\ninterface Element {\n\tname: string;\n\tattrs: Record<string, string>;\n\tchildren: Element[];\n\t/** Character data of text content elements (`text`, `tspan`, `textPath`), in order with their children. */\n\tcontent?: Array<string | Element>;\n}\n\nconst TEXT_CONTENT = new Set(['text', 'tspan', 'textPath']);\n\n/** A tiny non-validating XML reader: elements and attributes only. */\nfunction parseXml(source: string): Element | null {\n\tconst text = source\n\t\t.replace(/<!--[\\s\\S]*?-->/g, '')\n\t\t.replace(/<\\?[\\s\\S]*?\\?>/g, '')\n\t\t.replace(/<!\\[CDATA\\[[\\s\\S]*?\\]\\]>/g, '')\n\t\t.replace(/<!DOCTYPE[^>[]*(\\[[\\s\\S]*?\\])?\\s*>/gi, '');\n\tconst root: Element = { name: '#root', attrs: {}, children: [] };\n\tconst stack: Element[] = [root];\n\tconst tag = /<(\\/?)([A-Za-z_][\\w:.-]*)((?:\\s+[^\\s=/>]+(?:\\s*=\\s*(?:\"[^\"]*\"|'[^']*'|[^\\s>]+))?)*)\\s*(\\/?)>/g;\n\tconst attr = /([^\\s=/>]+)(?:\\s*=\\s*(?:\"([^\"]*)\"|'([^']*)'|([^\\s>]+)))?/g;\n\tlet m: RegExpExecArray | null;\n\tlet last = 0;\n\twhile ((m = tag.exec(text))) {\n\t\tconst [, closing, rawName, rawAttrs, selfClosing] = m;\n\t\t// Character data between tags belongs to the open text element, if any.\n\t\tconst top = stack[stack.length - 1];\n\t\tif (m.index > last && TEXT_CONTENT.has(top.name)) (top.content ??= []).push(decodeEntities(text.slice(last, m.index)));\n\t\tlast = tag.lastIndex;\n\t\tconst name = rawName.replace(/^svg:/, '');\n\t\tif (closing) {\n\t\t\tfor (let i = stack.length - 1; i > 0; i--) {\n\t\t\t\tif (stack[i].name === name) {\n\t\t\t\t\tstack.length = i;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\t\tconst attrs: Record<string, string> = {};\n\t\tlet a: RegExpExecArray | null;\n\t\tattr.lastIndex = 0;\n\t\twhile ((a = attr.exec(rawAttrs))) attrs[a[1]] = decodeEntities(a[2] ?? a[3] ?? a[4] ?? '');\n\t\tconst el: Element = { name, attrs, children: [] };\n\t\tstack[stack.length - 1].children.push(el);\n\t\tif (TEXT_CONTENT.has(top.name)) (top.content ??= []).push(el);\n\t\tif (!selfClosing) stack.push(el);\n\t}\n\tconst find = (el: Element): Element | null => {\n\t\tif (el.name === 'svg') return el;\n\t\tfor (const c of el.children) {\n\t\t\tconst f = find(c);\n\t\t\tif (f) return f;\n\t\t}\n\t\treturn null;\n\t};\n\treturn find(root);\n}\n\nfunction decodeEntities(s: string): string {\n\treturn s\n\t\t.replace(/&#x([0-9a-f]+);/gi, (_, h) => String.fromCodePoint(parseInt(h, 16)))\n\t\t.replace(/&#(\\d+);/g, (_, d) => String.fromCodePoint(parseInt(d, 10)))\n\t\t.replace(/&quot;/g, '\"')\n\t\t.replace(/&apos;/g, \"'\")\n\t\t.replace(/&lt;/g, '<')\n\t\t.replace(/&gt;/g, '>')\n\t\t.replace(/&amp;/g, '&');\n}\n\nconst numberList = (s: string | undefined): number[] =>\n\t(s ?? '')\n\t\t.trim()\n\t\t.split(/[\\s,]+|(?=-)(?<![eE])/)\n\t\t.filter(Boolean)\n\t\t.map(Number)\n\t\t.filter((n) => Number.isFinite(n));\n\nconst length = (s: string | undefined, fallback = 0): number => {\n\tif (s === undefined) return fallback;\n\tconst n = parseFloat(s);\n\treturn Number.isFinite(n) ? n : fallback;\n};\n\n/** Parses an SVG `transform` attribute into one matrix. */\nexport function parseSvgTransform(value: string | undefined): AffineMatrix {\n\tlet m: AffineMatrix = IDENTITY_MATRIX;\n\tif (!value) return m;\n\tconst re = /(matrix|translate|scale|rotate|skewX|skewY)\\s*\\(([^)]*)\\)/g;\n\tlet t: RegExpExecArray | null;\n\twhile ((t = re.exec(value))) {\n\t\tconst n = numberList(t[2]);\n\t\tlet step: AffineMatrix = IDENTITY_MATRIX;\n\t\tswitch (t[1]) {\n\t\t\tcase 'matrix':\n\t\t\t\tif (n.length >= 6) step = [n[0], n[1], n[2], n[3], n[4], n[5]];\n\t\t\t\tbreak;\n\t\t\tcase 'translate':\n\t\t\t\tstep = translateMatrix(n[0] ?? 0, n[1] ?? 0);\n\t\t\t\tbreak;\n\t\t\tcase 'scale':\n\t\t\t\tstep = scaleMatrix(n[0] ?? 1, n[1] ?? n[0] ?? 1);\n\t\t\t\tbreak;\n\t\t\tcase 'rotate':\n\t\t\t\tstep = rotateMatrix(n[0] ?? 0, { x: n[1] ?? 0, y: n[2] ?? 0 });\n\t\t\t\tbreak;\n\t\t\tcase 'skewX':\n\t\t\t\tstep = [1, 0, Math.tan(((n[0] ?? 0) * Math.PI) / 180), 1, 0, 0];\n\t\t\t\tbreak;\n\t\t\tcase 'skewY':\n\t\t\t\tstep = [1, Math.tan(((n[0] ?? 0) * Math.PI) / 180), 0, 1, 0, 0];\n\t\t\t\tbreak;\n\t\t}\n\t\t// SVG lists apply right to left: `translate(…) rotate(…)` rotates first.\n\t\tm = multiplyMatrices(step, m);\n\t}\n\treturn m;\n}\n\ninterface InheritedStyle {\n\tfill: string;\n\tstroke: string;\n\tstrokeWidth: string;\n\tstrokeLinecap?: string;\n\tstrokeLinejoin?: string;\n\tstrokeDasharray?: string;\n\tfillRule?: string;\n\tfillOpacity?: string;\n\tstrokeOpacity?: string;\n\t/** Not inherited: the element's own `mix-blend-mode` (reset for each element). */\n\tmixBlendMode?: string;\n\t/** Not inherited: the element's own `filter` (reset for each element). */\n\tfilter?: string;\n}\n\nconst STYLE_KEYS: Record<string, keyof InheritedStyle> = {\n\tfill: 'fill',\n\tstroke: 'stroke',\n\t'stroke-width': 'strokeWidth',\n\t'stroke-linecap': 'strokeLinecap',\n\t'stroke-linejoin': 'strokeLinejoin',\n\t'stroke-dasharray': 'strokeDasharray',\n\t'fill-rule': 'fillRule',\n\t'fill-opacity': 'fillOpacity',\n\t'stroke-opacity': 'strokeOpacity',\n\t'mix-blend-mode': 'mixBlendMode',\n\tfilter: 'filter'\n};\n\nfunction readStyle(el: Element, parent: InheritedStyle): InheritedStyle {\n\tconst { mixBlendMode: _m, filter: _f, ...inherited } = parent;\n\tconst out: InheritedStyle = { ...inherited };\n\tfor (const [attr, key] of Object.entries(STYLE_KEYS)) if (el.attrs[attr] !== undefined) out[key] = el.attrs[attr].trim();\n\tfor (const decl of (el.attrs.style ?? '').split(';')) {\n\t\tconst i = decl.indexOf(':');\n\t\tif (i < 0) continue;\n\t\tconst key = STYLE_KEYS[decl.slice(0, i).trim()];\n\t\tif (key) out[key] = decl.slice(i + 1).replace(/!important/, '').trim();\n\t}\n\treturn out;\n}\n\nfunction readStops(el: Element): VectorGradientStop[] {\n\treturn el.children\n\t\t.filter((c) => c.name === 'stop')\n\t\t.map((c) => {\n\t\t\tconst style = Object.fromEntries(\n\t\t\t\t(c.attrs.style ?? '')\n\t\t\t\t\t.split(';')\n\t\t\t\t\t.map((d) => d.split(':').map((s) => s.trim()))\n\t\t\t\t\t.filter((d) => d.length === 2)\n\t\t\t);\n\t\t\tconst raw = c.attrs.offset ?? '0';\n\t\t\tconst offset = raw.endsWith('%') ? parseFloat(raw) / 100 : parseFloat(raw);\n\t\t\tconst opacity = style['stop-opacity'] ?? c.attrs['stop-opacity'];\n\t\t\treturn {\n\t\t\t\toffset: Number.isFinite(offset) ? Math.max(0, Math.min(1, offset)) : 0,\n\t\t\t\tcolor: style['stop-color'] ?? c.attrs['stop-color'] ?? '#000',\n\t\t\t\t...(opacity !== undefined ? { opacity: parseFloat(opacity) } : {})\n\t\t\t};\n\t\t});\n}\n\nconst fraction = (s: string | undefined, fallback: number) => {\n\tif (s === undefined) return fallback;\n\tconst n = parseFloat(s);\n\tif (!Number.isFinite(n)) return fallback;\n\treturn s.trim().endsWith('%') ? n / 100 : n;\n};\n\nconst PAINT_SERVERS = new Set(['linearGradient', 'radialGradient', 'pattern']);\n\nfunction collectGradients(el: Element, raw: Map<string, Element>) {\n\tif (PAINT_SERVERS.has(el.name) && el.attrs.id) raw.set(el.attrs.id, el);\n\tfor (const c of el.children) collectGradients(c, raw);\n}\n\n/** Every `<clipPath>` and `<mask>` with an id. */\nfunction collectMasks(el: Element, raw: Map<string, Element>) {\n\tif ((el.name === 'clipPath' || el.name === 'mask') && el.attrs.id) raw.set(el.attrs.id, el);\n\tfor (const c of el.children) collectMasks(c, raw);\n}\n\n/** An attribute, or the same property in the element's `style`. */\nfunction attrOrStyle(el: Element, name: string): string | undefined {\n\tfor (const decl of (el.attrs.style ?? '').split(';')) {\n\t\tconst i = decl.indexOf(':');\n\t\tif (i >= 0 && decl.slice(0, i).trim() === name) return decl.slice(i + 1).replace(/!important/, '').trim();\n\t}\n\treturn el.attrs[name];\n}\n\n/** The id an `url(#id)` reference names, or null. */\nfunction urlId(value: string | undefined): string | null {\n\treturn /^url\\(\\s*['\"]?#([^'\")\\s]+)['\"]?\\s*\\)/.exec((value ?? '').trim())?.[1] ?? null;\n}\n\n/** A `<clipPath>`'s content with each `clip-rule` read as the `fill-rule` import knows. */\nfunction clipRulesAsFillRules(el: Element): Element {\n\tconst attrs = { ...el.attrs };\n\tconst rule = attrOrStyle(el, 'clip-rule');\n\tif (rule) attrs['fill-rule'] = rule;\n\treturn { ...el, attrs, children: el.children.map(clipRulesAsFillRules) };\n}\n\nfunction collectFilters(el: Element, raw: Map<string, Element>) {\n\tif (el.name === 'filter' && el.attrs.id) raw.set(el.attrs.id, el);\n\tfor (const c of el.children) collectFilters(c, raw);\n}\n\n/**\n * A `<filter>` as vector filters: our own export's `data-vector-filters`, or the simple filters\n * other tools write — `feDropShadow`, or a lone `feGaussianBlur` of the source (a layer blur).\n * Anything else is skipped (empty list).\n */\nfunction filtersFromElement(el: Element): VectorFilter[] {\n\tconst own = el.attrs['data-vector-filters'];\n\tif (own !== undefined) {\n\t\ttry {\n\t\t\treturn sanitizeVectorFilters(JSON.parse(own));\n\t\t} catch {\n\t\t\treturn [];\n\t\t}\n\t}\n\tconst prims = el.children.filter((c) => c.name.startsWith('fe'));\n\tconst out: unknown[] = [];\n\tfor (const p of prims) {\n\t\tconst std = numberList(p.attrs.stdDeviation)[0] ?? 0;\n\t\tif (p.name === 'feDropShadow') {\n\t\t\tconst style = Object.fromEntries(\n\t\t\t\t(p.attrs.style ?? '')\n\t\t\t\t\t.split(';')\n\t\t\t\t\t.map((d) => d.split(':').map((x) => x.trim()))\n\t\t\t\t\t.filter((d) => d.length === 2)\n\t\t\t);\n\t\t\tconst opacity = parseFloat(style['flood-opacity'] ?? p.attrs['flood-opacity'] ?? '1');\n\t\t\tout.push({\n\t\t\t\ttype: 'dropShadow',\n\t\t\t\tparams: {\n\t\t\t\t\tcolor: style['flood-color'] ?? p.attrs['flood-color'] ?? '#000000',\n\t\t\t\t\topacity: Number.isFinite(opacity) ? opacity : 1,\n\t\t\t\t\toffsetX: length(p.attrs.dx, 2),\n\t\t\t\t\toffsetY: length(p.attrs.dy, 2),\n\t\t\t\t\tblur: std * 2,\n\t\t\t\t\tspread: 0\n\t\t\t\t}\n\t\t\t});\n\t\t} else if (p.name === 'feGaussianBlur' && prims.length === 1 && (p.attrs.in === undefined || p.attrs.in === 'SourceGraphic')) {\n\t\t\tout.push({ type: 'layerBlur', params: { radius: std * 2 } });\n\t\t} else return [];\n\t}\n\treturn sanitizeVectorFilters(out);\n}\n\n/** The gradient a `data-vector-gradient` attribute (our own export) holds, or null. */\nfunction gradientFromAttribute(value: string | undefined): VectorGradient | null {\n\tif (!value) return null;\n\ttry {\n\t\treturn sanitizeVectorGradient(JSON.parse(value));\n\t} catch {\n\t\treturn null;\n\t}\n}\n\n/**\n * A `<linearGradient>` / `<radialGradient>` (attributes and stops inherited through `href`) as a\n * vector gradient: `gradientUnits`, `gradientTransform`, `spreadMethod`, `fx`, `fy` and `fr` read.\n * Box gradients that match the angle / centre shorthand keep it.\n */\nfunction resolveGradient(id: string, raw: Map<string, Element>): VectorGradient | null {\n\tconst first = raw.get(id);\n\tif (!first) return null;\n\tconst own = gradientFromAttribute(first.attrs['data-vector-gradient']);\n\tif (own) return own;\n\tif (first.name === 'pattern') return null;\n\t// The href chain: attributes and stops come from the nearest element that has them.\n\tconst chain: Element[] = [];\n\tfor (let el: Element | undefined = first; el && !chain.includes(el) && chain.length < 32; ) {\n\t\tchain.push(el);\n\t\tconst href: string | undefined = el.attrs.href ?? el.attrs['xlink:href'];\n\t\tel = href?.startsWith('#') ? raw.get(href.slice(1)) : undefined;\n\t}\n\tconst attr = (name: string) => chain.find((el) => el.attrs[name] !== undefined)?.attrs[name];\n\tconst stops = chain.map(readStops).find((s) => s.length) ?? [];\n\tif (!stops.length) return null;\n\tconst user = attr('gradientUnits') === 'userSpaceOnUse';\n\tconst t = parseSvgTransform(attr('gradientTransform'));\n\tconst plain = t === IDENTITY_MATRIX || (t[0] === 1 && t[1] === 0 && t[2] === 0 && t[3] === 1 && t[4] === 0 && t[5] === 0);\n\tconst at = (name: string, fallback: number) => (user ? length(attr(name), fallback) : fraction(attr(name), fallback));\n\tconst spreadAttr = attr('spreadMethod');\n\tconst spread = spreadAttr === 'reflect' || spreadAttr === 'repeat' ? { spread: spreadAttr as 'reflect' | 'repeat' } : {};\n\tconst map = (p: { x: number; y: number }) => applySvgMatrix(t, p);\n\tif (first.name === 'radialGradient') {\n\t\tconst cx = at('cx', user ? 0 : 0.5);\n\t\tconst cy = at('cy', user ? 0 : 0.5);\n\t\tconst r = at('r', user ? 0 : 0.5);\n\t\tconst fx = attr('fx') !== undefined ? at('fx', cx) : cx;\n\t\tconst fy = attr('fy') !== undefined ? at('fy', cy) : cy;\n\t\tconst fr = attr('fr') !== undefined ? at('fr', 0) : 0;\n\t\tconst focal = Math.abs(fx - cx) > 1e-9 || Math.abs(fy - cy) > 1e-9;\n\t\tif (!user && plain && !focal && !(fr > 0)) return { type: 'radial', cx, cy, r, stops, ...spread };\n\t\tconst g: VectorGradient = {\n\t\t\ttype: 'radial',\n\t\t\tstops,\n\t\t\tstart: map({ x: cx, y: cy }),\n\t\t\tend: map({ x: cx + r, y: cy }),\n\t\t\twidth: map({ x: cx, y: cy + r }),\n\t\t\tunits: user ? 'userSpaceOnUse' : 'objectBoundingBox',\n\t\t\t...spread\n\t\t};\n\t\tif (focal) g.focal = map({ x: fx, y: fy });\n\t\tif (fr > 0 && r > 0) g.focalRadius = Math.min(0.99, fr / r);\n\t\treturn g;\n\t}\n\tconst x1 = at('x1', 0);\n\tconst y1 = at('y1', 0);\n\tconst x2 = attr('x2') !== undefined ? at('x2', 1) : user ? 0 : 1;\n\tconst y2 = at('y2', 0);\n\tif (!user && plain) {\n\t\t// CSS angle: 0° points up, clockwise. Keep the shorthand when it paints the same.\n\t\tconst angle = Math.round(((Math.atan2(x2 - x1, -(y2 - y1)) * 180) / Math.PI + 360) % 360);\n\t\tconst c = angleToSvgLinearCoords(angle);\n\t\tconst len = Math.hypot(x2 - x1, y2 - y1);\n\t\tconst d = len > 0 ? { x: (x2 - x1) / len, y: (y2 - y1) / len } : { x: 0, y: 1 };\n\t\tconst along = (x: number, y: number) => x * d.x + y * d.y;\n\t\tconst same =\n\t\t\tlen > 0 &&\n\t\t\tMath.abs((c.x2 - c.x1) * d.y - (c.y2 - c.y1) * d.x) < 1e-3 &&\n\t\t\tMath.abs(along(c.x1, c.y1) - along(x1, y1)) < 1e-3 &&\n\t\t\tMath.abs(along(c.x2, c.y2) - along(x2, y2)) < 1e-3;\n\t\tif (same) return { type: 'linear', angle, stops, ...spread };\n\t}\n\tconst start = { x: x1, y: y1 };\n\tconst end = { x: x2, y: y2 };\n\treturn {\n\t\ttype: 'linear',\n\t\tstops,\n\t\tstart: map(start),\n\t\tend: map(end),\n\t\twidth: map({ x: x1 - (y2 - y1), y: y1 + (x2 - x1) }),\n\t\tunits: user ? 'userSpaceOnUse' : 'objectBoundingBox',\n\t\t...spread\n\t};\n}\n\nconst applySvgMatrix = (m: AffineMatrix, p: { x: number; y: number }) => ({ x: m[0] * p.x + m[2] * p.y + m[4], y: m[1] * p.x + m[3] * p.y + m[5] });\n\n/** Parses SVG markup into a vector document. Throws when there is no `<svg>` element. */\nexport function parseVectorSvg(svg: string, options: VectorSvgImportOptions = {}): VectorDocument {\n\tconst root = parseXml(svg);\n\tif (!root) throw new Error('The markup has no <svg> element.');\n\tlet counter = 0;\n\tconst usedIds = new Set<string>();\n\tconst createId = options.createId ?? (() => `node-${++counter}`);\n\tconst idFor = (el: Element) => {\n\t\tconst id = el.attrs.id;\n\t\tif (id && !usedIds.has(id)) {\n\t\t\tusedIds.add(id);\n\t\t\treturn id;\n\t\t}\n\t\tlet next = createId();\n\t\twhile (usedIds.has(next)) next = createId();\n\t\tusedIds.add(next);\n\t\treturn next;\n\t};\n\n\tconst rawGradients = new Map<string, Element>();\n\tcollectGradients(root, rawGradients);\n\tconst rawFilters = new Map<string, Element>();\n\tcollectFilters(root, rawFilters);\n\tconst rawMasks = new Map<string, Element>();\n\tcollectMasks(root, rawMasks);\n\t/** Masks being read (a mask that refers back to itself is ignored there). */\n\tconst resolving = new Set<string>();\n\tconst filtersOf = (value: string | undefined): VectorFilter[] => {\n\t\tconst url = /^url\\(\\s*['\"]?#([^'\")\\s]+)['\"]?\\s*\\)/.exec((value ?? '').trim());\n\t\tconst el = url ? rawFilters.get(url[1]) : undefined;\n\t\treturn el ? filtersFromElement(el) : [];\n\t};\n\tconst paint = (value: string): VectorPaint => {\n\t\tconst v = value.trim();\n\t\tconst url = /^url\\(\\s*['\"]?#([^'\")\\s]+)['\"]?\\s*\\)/.exec(v);\n\t\tif (url) return resolveGradient(url[1], rawGradients) ?? null;\n\t\tif (v === 'none' || v === '') return null;\n\t\treturn v;\n\t};\n\n\tconst viewBox = numberList(root.attrs.viewBox);\n\tconst width = viewBox.length === 4 ? viewBox[2] : length(root.attrs.width, 300);\n\tconst height = viewBox.length === 4 ? viewBox[3] : length(root.attrs.height, 150);\n\tconst rootMatrix: AffineMatrix = viewBox.length === 4 ? translateMatrix(-viewBox[0], -viewBox[1]) : IDENTITY_MATRIX;\n\n\tconst SKIP = new Set(['defs', 'clipPath', 'mask', 'symbol', 'style', 'title', 'desc', 'metadata', 'pattern', 'marker', 'filter', 'image', 'linearGradient', 'radialGradient', 'script', 'foreignObject']);\n\n\tconst shapeOf = (el: Element): VectorSubpath[] | null => {\n\t\tconst a = el.attrs;\n\t\tswitch (el.name) {\n\t\t\tcase 'path': {\n\t\t\t\t// Our own export: the sharp path and its live corners.\n\t\t\t\tif (a['data-vector-d'] && a['data-vector-corners']) {\n\t\t\t\t\tconst sharp = bezierToSubpaths(a['data-vector-d']);\n\t\t\t\t\tif (sharp.length) return applyVectorCornersAttribute(sharp, a['data-vector-corners']);\n\t\t\t\t}\n\t\t\t\treturn a.d ? bezierToSubpaths(a.d) : null;\n\t\t\t}\n\t\t\tcase 'rect': {\n\t\t\t\tconst w = length(a.width);\n\t\t\t\tconst h = length(a.height);\n\t\t\t\tif (w <= 0 || h <= 0) return null;\n\t\t\t\tconst r = length(a.rx ?? a.ry, 0);\n\t\t\t\treturn [rectSubpath({ x: length(a.x), y: length(a.y), width: w, height: h }, r)];\n\t\t\t}\n\t\t\tcase 'circle': {\n\t\t\t\tconst r = length(a.r);\n\t\t\t\tif (r <= 0) return null;\n\t\t\t\tconst cx = length(a.cx);\n\t\t\t\tconst cy = length(a.cy);\n\t\t\t\treturn [ellipseSubpath({ x: cx - r, y: cy - r, width: 2 * r, height: 2 * r })];\n\t\t\t}\n\t\t\tcase 'ellipse': {\n\t\t\t\tconst rx = length(a.rx);\n\t\t\t\tconst ry = length(a.ry);\n\t\t\t\tif (rx <= 0 || ry <= 0) return null;\n\t\t\t\treturn [ellipseSubpath({ x: length(a.cx) - rx, y: length(a.cy) - ry, width: 2 * rx, height: 2 * ry })];\n\t\t\t}\n\t\t\tcase 'line':\n\t\t\t\treturn [lineSubpath({ x: length(a.x1), y: length(a.y1) }, { x: length(a.x2), y: length(a.y2) })];\n\t\t\tcase 'polyline':\n\t\t\tcase 'polygon': {\n\t\t\t\tconst n = numberList(a.points);\n\t\t\t\tif (n.length < 4) return null;\n\t\t\t\tconst anchors = [];\n\t\t\t\tfor (let i = 0; i + 1 < n.length; i += 2) anchors.push({ x: n[i], y: n[i + 1] });\n\t\t\t\treturn [{ anchors, closed: el.name === 'polygon' }];\n\t\t\t}\n\t\t}\n\t\treturn null;\n\t};\n\n\tconst strokeStyle = (s: InheritedStyle): Partial<VectorPathNode> => ({\n\t\t...(s.strokeWidth ? { strokeWidth: length(s.strokeWidth, 1) } : {}),\n\t\t...(s.strokeLinecap ? { strokeLinecap: s.strokeLinecap as VectorLineCap } : {}),\n\t\t...(s.strokeLinejoin ? { strokeLinejoin: s.strokeLinejoin as VectorLineJoin } : {}),\n\t\t...(s.strokeDasharray && s.strokeDasharray !== 'none' ? { strokeDasharray: numberList(s.strokeDasharray) } : {}),\n\t\t...(s.fillRule === 'evenodd' ? { fillRule: 'evenodd' as VectorFillRule } : {})\n\t});\n\n\t/** A node mapped by `m` (scale and skew baked in, stroke width scaled). */\n\tconst placed = (node: VectorPathNode, m: AffineMatrix): VectorPathNode => {\n\t\tif (m === IDENTITY_MATRIX) return node;\n\t\tconst next = transformVectorNode(node, m);\n\t\tconst strokeScale = Math.sqrt(Math.abs(m[0] * m[3] - m[1] * m[2]));\n\t\tif (strokeScale > 0 && Math.abs(strokeScale - 1) > 1e-9) {\n\t\t\tif (hasPaint(next.stroke)) next.strokeWidth = (next.strokeWidth ?? 1) * strokeScale;\n\t\t\tif (Array.isArray(next.strokes)) next.strokes = next.strokes.map((l) => ((l.kind ?? 'paint') === 'paint' ? { ...l, strokeWidth: (l.strokeWidth ?? 1) * strokeScale } : l));\n\t\t}\n\t\treturn normalizeVectorPaintStacks(next, 'stack');\n\t};\n\n\t/** Paint with an element's `fill-opacity` / `stroke-opacity`: a one-layer stack when it is below 1. */\n\tconst withOpacities = (node: VectorPathNode, s: InheritedStyle): VectorPathNode => {\n\t\tlet out = node;\n\t\tconst fo = s.fillOpacity !== undefined ? fraction(s.fillOpacity, 1) : 1;\n\t\tconst so = s.strokeOpacity !== undefined ? fraction(s.strokeOpacity, 1) : 1;\n\t\tif (fo < 1 && hasPaint(out.fill)) out = withVectorFills(out, [{ paint: out.fill!, opacity: Math.max(0, fo) }]);\n\t\tif (so < 1 && hasPaint(out.stroke)) out = withVectorStrokes(out, vectorStrokes(out).map((l) => ({ ...l, opacity: Math.max(0, so) })));\n\t\treturn out;\n\t};\n\n\t/**\n\t * A `<g data-vector-path data-vector-fills>` from our own export (a path painted through its\n\t * stacks) as the path it came from: the geometry of its first fill part, the stacks from JSON.\n\t */\n\tconst stackedPath = (g: Element, _style: InheritedStyle, m: AffineMatrix, meta: Partial<VectorPathNode>): VectorPathNode | null => {\n\t\tconst fillEl = g.children.find((c) => c.name === 'path' && c.attrs['data-vector-part'] === 'fill');\n\t\tconst subpaths = fillEl ? shapeOf(fillEl) : null;\n\t\tif (!subpaths?.length) return null;\n\t\tconst parse = (v: string | undefined) => {\n\t\t\ttry {\n\t\t\t\treturn v ? JSON.parse(v) : [];\n\t\t\t} catch {\n\t\t\t\treturn [];\n\t\t\t}\n\t\t};\n\t\tlet node: VectorPathNode = { id: idFor(g), type: 'path', ...meta, subpaths, fill: null, stroke: null };\n\t\tif (g.attrs['data-vector-fill-rule'] === 'evenodd') node.fillRule = 'evenodd';\n\t\tnode = withVectorFills(node, sanitizeVectorFills(parse(g.attrs['data-vector-fills'])));\n\t\tnode = withVectorStrokes(node, sanitizeVectorStrokes(parse(g.attrs['data-vector-strokes'])));\n\t\treturn placed(node, m);\n\t};\n\n\t/**\n\t * Neighbouring paths with the same outline merged into one with stacked paints (see\n\t * `mergeStackedShapes`).\n\t */\n\tconst mergeStacked = (nodes: VectorNode[]): VectorNode[] => {\n\t\tconst out: VectorNode[] = [];\n\t\tconst key = (n: VectorPathNode) =>\n\t\t\tJSON.stringify([n.subpaths, n.transform ?? null, n.opacity ?? 1, n.visible !== false, n.filters ?? null, n.blendMode ?? 'normal', n.fillRule ?? 'nonzero', n.booleanOperation ?? null]);\n\t\tfor (const n of nodes) {\n\t\t\tconst prev = out[out.length - 1];\n\t\t\tif (prev?.type === 'path' && n.type === 'path' && key(prev) === key(n)) {\n\t\t\t\tconst fills = vectorFills(n);\n\t\t\t\tconst strokesBefore = vectorStrokes(prev);\n\t\t\t\t// A later fill would land under an earlier stroke: keep them apart.\n\t\t\t\tif (!(fills.length && strokesBefore.length)) {\n\t\t\t\t\tlet merged = withVectorFills(prev, [...vectorFills(prev), ...fills]);\n\t\t\t\t\tmerged = withVectorStrokes(merged, [...strokesBefore, ...vectorStrokes(n)]);\n\t\t\t\t\tout[out.length - 1] = merged;\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t}\n\t\t\tout.push(n);\n\t\t}\n\t\treturn out;\n\t};\n\n\t/**\n\t * A `<g data-vector-path>` from our own export (an aligned or arrowed stroke drawn in parts)\n\t * as the one path it came from: the fill part's outline and fill, the stroke part's paint and\n\t * line style, and the options the group's data attributes keep.\n\t */\n\tconst mergedPath = (g: Element, style: InheritedStyle, m: AffineMatrix, meta: Partial<VectorPathNode>): VectorPathNode | null => {\n\t\tconst part = (name: string) => g.children.find((c) => c.name === 'path' && c.attrs['data-vector-part'] === name);\n\t\tconst fillEl = part('fill');\n\t\tconst subpaths = fillEl ? shapeOf(fillEl) : null;\n\t\tif (!fillEl || !subpaths?.length) return null;\n\t\tconst a = g.attrs;\n\t\tconst fs = readStyle(fillEl, style);\n\t\tconst strokeEl = part('stroke');\n\t\tconst outlineEl = part('stroke-outline');\n\t\tconst ss = strokeEl ? readStyle(strokeEl, style) : null;\n\t\tconst width = length(a['data-vector-stroke-width'], ss ? length(ss.strokeWidth, 1) : 1);\n\t\tconst arrow = (v: string | undefined) => (VECTOR_ARROWHEADS.includes(v as VectorArrowhead) ? (v as VectorArrowhead) : undefined);\n\t\tconst scale = (v: string | undefined) => {\n\t\t\tconst n = v === undefined ? NaN : parseFloat(v);\n\t\t\treturn n > 0 ? n : undefined;\n\t\t};\n\t\tconst align = a['data-vector-stroke-align'];\n\t\tconst profile = widthProfileFromAttribute(a['data-vector-width-profile']);\n\t\tconst kept = (key: string, values: readonly string[]) => (values.includes(a[key]) ? a[key] : undefined);\n\t\tconst keptCap = kept('data-vector-stroke-linecap', ['round', 'square']) as VectorLineCap | undefined;\n\t\tconst keptJoin = kept('data-vector-stroke-linejoin', ['round', 'bevel']) as VectorLineJoin | undefined;\n\t\tconst keptDash = a['data-vector-stroke-dasharray'] ? numberList(a['data-vector-stroke-dasharray']) : undefined;\n\t\tconst node: VectorPathNode = {\n\t\t\tid: idFor(g),\n\t\t\ttype: 'path',\n\t\t\t...meta,\n\t\t\tsubpaths,\n\t\t\tfill: paint(fs.fill),\n\t\t\tstroke: ss ? paint(ss.stroke) : outlineEl ? paint(readStyle(outlineEl, style).fill) : null,\n\t\t\t...(ss ? strokeStyle(ss) : {}),\n\t\t\t...(fs.fillRule === 'evenodd' ? { fillRule: 'evenodd' as VectorFillRule } : {}),\n\t\t\tstrokeWidth: width,\n\t\t\t...(align === 'inside' || align === 'outside' ? { strokeAlign: align } : {}),\n\t\t\t...(arrow(a['data-vector-start-arrow']) ? { startArrow: arrow(a['data-vector-start-arrow']) } : {}),\n\t\t\t...(arrow(a['data-vector-end-arrow']) ? { endArrow: arrow(a['data-vector-end-arrow']) } : {}),\n\t\t\t...(a['data-vector-arrow-align'] === 'tip' ? { arrowAlign: 'tip' as const } : {}),\n\t\t\t...(scale(a['data-vector-start-arrow-scale']) ? { startArrowScale: scale(a['data-vector-start-arrow-scale']) } : {}),\n\t\t\t...(scale(a['data-vector-end-arrow-scale']) ? { endArrowScale: scale(a['data-vector-end-arrow-scale']) } : {}),\n\t\t\t...(profile.length ? { strokeWidthProfile: profile } : {}),\n\t\t\t...(keptCap ? { strokeLinecap: keptCap } : {}),\n\t\t\t...(keptJoin ? { strokeLinejoin: keptJoin } : {}),\n\t\t\t...(keptDash?.length ? { strokeDasharray: keptDash } : {})\n\t\t};\n\t\treturn placed(node, m);\n\t};\n\n\t/**\n\t * A `<g data-vector-live>` from our own export (path effects or a live boolean) as the node it\n\t * came from: its hidden source part with the effects put back (their offsets carried through\n\t * what import bakes into the geometry). The drawn appearance part is regenerated.\n\t */\n\tconst liveNode = (g: Element, style: InheritedStyle, m: AffineMatrix, meta: Pick<VectorNode, 'name' | 'opacity' | 'visible' | 'booleanOperation' | 'blendMode' | 'filters'>): VectorNode | null => {\n\t\tlet raw: Record<string, unknown> = {};\n\t\ttry {\n\t\t\traw = JSON.parse(g.attrs['data-vector-live']) ?? {};\n\t\t} catch {\n\t\t\traw = {};\n\t\t}\n\t\tconst sourceEl = g.children.find((c) => c.name === 'g' && c.attrs['data-vector-part'] === 'source');\n\t\tif (!sourceEl) return null;\n\t\tconst inner = visit(sourceEl, style, m);\n\t\tconst effects = sanitizeVectorEffects(raw.effects);\n\t\tconst liveBoolean = BOOLEAN_OPERATIONS.includes(raw.liveBoolean as VectorBooleanOperation) ? (raw.liveBoolean as VectorBooleanOperation) : null;\n\t\tconst id = idFor(g);\n\t\tif (raw.kind === 'text') {\n\t\t\tconst text = inner.find((n): n is VectorTextNode => n.type === 'text');\n\t\t\tif (!text) return null;\n\t\t\tconst { residual } = decomposeRigid(m);\n\t\t\tconst { visible: _v, ...rest } = text;\n\t\t\treturn { ...rest, id, ...meta, ...(effects.length ? { effects: transformVectorEffects(effects, residual) } : {}) };\n\t\t}\n\t\tif (raw.kind === 'path') {\n\t\t\tconst path = inner.find((n): n is VectorPathNode => n.type === 'path');\n\t\t\tif (!path) return null;\n\t\t\tconst { residual } = decomposeRigid(m);\n\t\t\tconst { visible: _v, ...rest } = path;\n\t\t\treturn { ...rest, id, ...meta, ...(effects.length ? { effects: transformVectorEffects(effects, residual) } : {}) };\n\t\t}\n\t\tif (!inner.length) return null;\n\t\tconst group: VectorGroupNode = { id, type: 'group', ...meta, children: inner };\n\t\tif (effects.length) group.effects = transformVectorEffects(effects, m);\n\t\tif (liveBoolean) group.liveBoolean = liveBoolean;\n\t\tconst symmetry = sanitizeVectorSymmetry(raw.symmetry);\n\t\tif (symmetry) group.symmetry = transformVectorSymmetry(symmetry, m);\n\t\tconst blend = blendFromAttribute(g.attrs['data-vector-blend'], m);\n\t\tif (blend) group.blend = blend;\n\t\treturn group;\n\t};\n\n\tconst json = (v: string | undefined): unknown => {\n\t\ttry {\n\t\t\treturn v === undefined ? undefined : JSON.parse(v);\n\t\t} catch {\n\t\t\treturn undefined;\n\t\t}\n\t};\n\n\t/** A `<g data-vector-text>` from our own export as the text node it came from. */\n\tconst ownText = (g: Element, m: AffineMatrix, meta: Partial<VectorTextNode>): VectorTextNode | null => {\n\t\tconst raw = json(g.attrs['data-vector-text']) as Record<string, unknown> | undefined;\n\t\tif (!raw || typeof raw !== 'object') return null;\n\t\tlet fields: ReturnType<typeof sanitizeVectorTextFields>;\n\t\ttry {\n\t\t\tfields = sanitizeVectorTextFields(raw);\n\t\t} catch {\n\t\t\treturn null;\n\t\t}\n\t\tconst effects = sanitizeVectorEffects(raw.effects);\n\t\tlet node: VectorTextNode = { id: idFor(g), type: 'text', ...meta, ...fields, ...(effects.length ? { effects } : {}) };\n\t\tif (g.attrs['data-vector-fills'] !== undefined) {\n\t\t\tnode = withVectorFills({ ...node, fill: null, stroke: null }, sanitizeVectorFills(json(g.attrs['data-vector-fills']) ?? []));\n\t\t\tnode = withVectorStrokes(node, sanitizeVectorStrokes(json(g.attrs['data-vector-strokes']) ?? []));\n\t\t} else {\n\t\t\tconst fill = json(g.attrs['data-vector-fill']);\n\t\t\tconst stroke = json(g.attrs['data-vector-stroke']);\n\t\t\tnode.fill = fill == null ? null : (sanitizeVectorFills([{ paint: fill }])[0]?.paint ?? null);\n\t\t\tnode.stroke = stroke == null ? null : (sanitizeVectorFills([{ paint: stroke }])[0]?.paint ?? null);\n\t\t\tconst settings = json(g.attrs['data-vector-stroke-settings']);\n\t\t\tif (settings && typeof settings === 'object') {\n\t\t\t\tconst strokes = sanitizeVectorStrokes([{ paint: node.stroke ?? '#000', ...(settings as object) }]);\n\t\t\t\tif (strokes[0]) {\n\t\t\t\t\tconst { paint: _p, ...rest } = strokes[0];\n\t\t\t\t\tnode = { ...node, ...rest };\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn m === IDENTITY_MATRIX ? node : normalizeVectorPaintStacks(transformVectorNode(node, m), 'stack');\n\t};\n\n\t/**\n\t * A foreign `<text>` as point text: its characters (tspans that start a new line at their own\n\t * `x` become line breaks), font, anchor and paint. Per-character positions, `textPath` and\n\t * `textLength` are not kept.\n\t */\n\tconst foreignText = (el: Element, style: InheritedStyle, m: AffineMatrix, meta: Partial<VectorTextNode>): VectorTextNode | null => {\n\t\tlet text = '';\n\t\tlet first = true;\n\t\tconst walk = (e: Element) => {\n\t\t\tfor (const part of e.content ?? []) {\n\t\t\t\tif (typeof part === 'string') text += part.replace(/\\s+/g, ' ');\n\t\t\t\telse if (part.name === 'tspan' || part.name === 'textPath') {\n\t\t\t\t\tif (!first && part.attrs.x !== undefined && (part.attrs.dy !== undefined || part.attrs.y !== undefined)) text += '\\n';\n\t\t\t\t\twalk(part);\n\t\t\t\t}\n\t\t\t\tfirst = false;\n\t\t\t}\n\t\t};\n\t\twalk(el);\n\t\ttext = text.replace(/^ +| +$/gm, '');\n\t\tif (!text.trim()) return null;\n\t\tconst font = (name: string) => attrOrStyle(el, name) ?? el.children.map((c) => attrOrStyle(c, name)).find((v) => v !== undefined);\n\t\tconst size = length(font('font-size'), 16);\n\t\tconst weightRaw = font('font-weight');\n\t\tconst weight = weightRaw === 'bold' ? 700 : weightRaw === 'normal' || !weightRaw ? 400 : Math.round(length(weightRaw, 400));\n\t\tconst family = (font('font-family') ?? 'sans-serif').split(',')[0].trim().replace(/^[\"']|[\"']$/g, '') || 'sans-serif';\n\t\tconst anchor = attrOrStyle(el, 'text-anchor');\n\t\tconst first0 = (v: string | undefined) => numberList(v)[0] ?? 0;\n\t\tconst tspan = el.children.find((c) => c.name === 'tspan');\n\t\tconst x = el.attrs.x !== undefined ? first0(el.attrs.x) : first0(tspan?.attrs.x);\n\t\tconst y = el.attrs.y !== undefined ? first0(el.attrs.y) : first0(tspan?.attrs.y);\n\t\tconst fillValue = attrOrStyle(el, 'fill') ?? style.fill;\n\t\tlet node: VectorTextNode = {\n\t\t\tid: idFor(el),\n\t\t\ttype: 'text',\n\t\t\t...meta,\n\t\t\ttext,\n\t\t\tfont: { fontFamily: family, fontWeight: Math.max(1, Math.min(1000, weight)), fontSize: size > 0 ? size : 16, ...(font('font-style') === 'italic' ? { italic: true } : {}) },\n\t\t\t...(anchor === 'middle' ? { paragraph: { align: 'center' as const } } : anchor === 'end' ? { paragraph: { align: 'right' as const } } : {}),\n\t\t\tframe: { kind: 'point', x, y },\n\t\t\tfill: paint(fillValue ?? '#000'),\n\t\t\tstroke: paint(s0(style.stroke)),\n\t\t\t...(style.strokeWidth ? { strokeWidth: length(style.strokeWidth, 1) } : {})\n\t\t};\n\t\tif (m !== IDENTITY_MATRIX) node = transformVectorNode(node, m);\n\t\treturn node;\n\t};\n\tconst s0 = (v: string | undefined) => v ?? 'none';\n\n\t// Symbols: our `<symbol data-vector-symbol>`, or any element a `<use>` refers to.\n\tconst byId = new Map<string, Element>();\n\tconst index = (el: Element) => {\n\t\tif (el.attrs.id && !byId.has(el.attrs.id)) byId.set(el.attrs.id, el);\n\t\tel.children.forEach(index);\n\t};\n\tindex(root);\n\tconst symbols: VectorSymbol[] = [];\n\tconst symbolOfElement = new Map<Element, string | null>();\n\tconst usedSymbolIds = new Set<string>();\n\tconst symbolFor = (el: Element): string | null => {\n\t\tif (symbolOfElement.has(el)) return symbolOfElement.get(el)!;\n\t\tsymbolOfElement.set(el, null); // a symbol that uses itself draws nothing\n\t\tconst own = json(el.attrs['data-vector-symbol']) as { id?: string; name?: string } | undefined;\n\t\tlet id = typeof own?.id === 'string' && own.id ? own.id : (el.attrs.id ?? createId());\n\t\twhile (usedSymbolIds.has(id)) id = `${id}-${usedSymbolIds.size}`;\n\t\tusedSymbolIds.add(id);\n\t\tconst style = readStyle(el, rootStyle);\n\t\t// A `<symbol>` holds its art; any other element referred to is the art itself.\n\t\tconst nodes = el.name === 'symbol' ? visit(el, style, IDENTITY_MATRIX) : visitOne({ ...el, attrs: { ...el.attrs, transform: '' } }, rootStyle, parseSvgTransform(el.attrs.transform));\n\t\tsymbols.push({ id, name: typeof own?.name === 'string' && own.name ? own.name : (el.attrs.id ?? 'Symbol'), nodes });\n\t\tsymbolOfElement.set(el, id);\n\t\treturn id;\n\t};\n\t/** A `<use>` as an instance of the symbol it refers to, placed by its transform and `x` / `y`. */\n\tconst useInstance = (el: Element, m: AffineMatrix, meta: Partial<VectorInstanceNode>): VectorInstanceNode | null => {\n\t\tconst href = (el.attrs.href ?? el.attrs['xlink:href'] ?? '').trim();\n\t\tconst target = href.startsWith('#') ? byId.get(href.slice(1)) : undefined;\n\t\tif (!target) return null;\n\t\tconst symbolId = symbolFor(target);\n\t\tif (!symbolId) return null;\n\t\tconst own = json(el.attrs['data-vector-instance']) as { scaleStrokes?: boolean; overrides?: VectorInstanceNode['overrides'] } | undefined;\n\t\tconst place = multiplyMatrices(translateMatrix(length(el.attrs.x), length(el.attrs.y)), m);\n\t\tconst node: VectorInstanceNode = { id: idFor(el), type: 'instance', ...meta, symbolId, ...(own?.scaleStrokes === false ? { scaleStrokes: false } : {}), ...(own?.overrides ? { overrides: own.overrides } : {}) };\n\t\treturn isIdentityMatrix(place) ? node : { ...node, transform: place };\n\t};\n\t/** A `<g data-vector-instance>` (an instance written as its drawn art) as the instance it came from. */\n\tconst ownInstance = (g: Element, m: AffineMatrix, meta: Partial<VectorInstanceNode>): VectorInstanceNode | null => {\n\t\tconst raw = json(g.attrs['data-vector-instance']) as { symbolId?: string; transform?: number[]; scaleStrokes?: boolean; overrides?: VectorInstanceNode['overrides']; effects?: unknown } | undefined;\n\t\tif (!raw || typeof raw.symbolId !== 'string') return null;\n\t\tconst sym = [...byId.values()].find((e) => e.name === 'symbol' && (json(e.attrs['data-vector-symbol']) as { id?: string } | undefined)?.id === raw.symbolId);\n\t\tconst symbolId = sym ? symbolFor(sym) : raw.symbolId;\n\t\tif (!symbolId) return null;\n\t\tconst t = Array.isArray(raw.transform) && raw.transform.length === 6 && raw.transform.every(Number.isFinite) ? (raw.transform as unknown as AffineMatrix) : IDENTITY_MATRIX;\n\t\tconst place = multiplyMatrices(t, m);\n\t\tconst drawn = g.children.find((c) => c.name === 'g');\n\t\tconst effects = sanitizeVectorEffects(raw.effects);\n\t\tconst node: VectorInstanceNode = {\n\t\t\tid: drawn?.attrs.id ?? idFor(g),\n\t\t\ttype: 'instance',\n\t\t\t...meta,\n\t\t\tsymbolId,\n\t\t\t...(raw.scaleStrokes === false ? { scaleStrokes: false } : {}),\n\t\t\t...(raw.overrides ? { overrides: raw.overrides } : {}),\n\t\t\t...(effects.length ? { effects } : {})\n\t\t};\n\t\tif (drawn) {\n\t\t\t// The drawn group carries the instance's own opacity, blend mode and filters.\n\t\t\tconst ds = readStyle(drawn, rootStyle);\n\t\t\tconst op = drawn.attrs.opacity !== undefined ? parseFloat(drawn.attrs.opacity) : undefined;\n\t\t\tif (op !== undefined && Number.isFinite(op) && op < 1) node.opacity = op;\n\t\t\tconst blend = vectorBlendModeFromCss(ds.mixBlendMode);\n\t\t\tif (blend && blend !== 'normal') node.blendMode = blend;\n\t\t\tconst filters = filtersOf(ds.filter);\n\t\t\tif (filters.length) node.filters = filters;\n\t\t\tif (drawn.attrs.display === 'none') node.visible = false;\n\t\t\tusedIds.add(node.id);\n\t\t}\n\t\treturn isIdentityMatrix(place) ? node : { ...node, transform: place };\n\t};\n\n\tconst visit = (el: Element, style: InheritedStyle, matrix: AffineMatrix): VectorNode[] => {\n\t\tconst out: VectorNode[] = [];\n\t\tfor (const child of el.children) {\n\t\t\tif (SKIP.has(child.name)) continue;\n\t\t\tconst nodes = visitOne(child, style, matrix);\n\t\t\tout.push(...(nodes.length ? masked(child, nodes, multiplyMatrices(parseSvgTransform(child.attrs.transform), matrix)) : nodes));\n\t\t}\n\t\treturn options.mergeStackedShapes ? mergeStacked(out) : out;\n\t};\n\n\t/** The base style mask and clip content inherits (the document's, not the referencing element's). */\n\tlet rootStyle: InheritedStyle = { fill: '#000', stroke: 'none', strokeWidth: '' };\n\n\t/** Maps a unit box onto the bounds of `nodes` (`objectBoundingBox` units), or null without bounds. */\n\tconst bboxMatrix = (nodes: readonly VectorNode[]): AffineMatrix | null => {\n\t\tconst b = unionBounds(nodes.map((n) => vectorNodeBounds(n)));\n\t\treturn b && b.width > 0 && b.height > 0 ? [b.width, 0, 0, b.height, b.x, b.y] : null;\n\t};\n\n\t/** The nodes a `<clipPath>` or `<mask>` holds as one mask node (several are grouped), or null. */\n\tconst maskNode = (el: Element, m: AffineMatrix, nodes: readonly VectorNode[], units: string | undefined): VectorNode | null => {\n\t\tconst id = el.attrs.id;\n\t\tif (!id || resolving.has(id)) return null;\n\t\tlet space = m;\n\t\tif (units === 'objectBoundingBox') {\n\t\t\tconst box = bboxMatrix(nodes);\n\t\t\tif (!box) return null;\n\t\t\tspace = box;\n\t\t}\n\t\tresolving.add(id);\n\t\tconst isClip = el.name === 'clipPath';\n\t\tconst content = isClip ? clipRulesAsFillRules(el) : el;\n\t\tconst inner = visit(content, readStyle(content, rootStyle), multiplyMatrices(parseSvgTransform(el.attrs.transform), space));\n\t\tresolving.delete(id);\n\t\t// A clip's paint is not drawn: imported clips are unpainted outlines.\n\t\tconst strip = (n: VectorNode): VectorNode => (n.type !== 'group' ? withVectorStrokes(withVectorFills({ ...n, fill: null, stroke: null }, []), []) : { ...n, children: n.children.map(strip) });\n\t\tconst list = isClip ? inner.map(strip) : inner;\n\t\tif (!list.length) return null;\n\t\treturn list.length === 1 ? list[0] : { id: idFor({ name: 'g', attrs: {}, children: [] }), type: 'group', name: isClip ? 'Clip' : 'Mask', children: list };\n\t};\n\n\t/**\n\t * Nodes made from an element that has `clip-path` and / or `mask`: wrapped in a mask group (the\n\t * clip or mask first), the clip inside the mask as SVG applies them. References to unknown or\n\t * unusable masks are dropped.\n\t */\n\tconst masked = (el: Element, nodes: VectorNode[], m: AffineMatrix): VectorNode[] => {\n\t\tlet out = nodes;\n\t\tconst clipEl = rawMasks.get(urlId(attrOrStyle(el, 'clip-path')) ?? '');\n\t\tif (clipEl?.name === 'clipPath') {\n\t\t\tconst source = maskNode(clipEl, m, out, clipEl.attrs.clipPathUnits);\n\t\t\tif (source) out = [{ id: idFor({ name: 'g', attrs: {}, children: [] }), type: 'group', name: 'Clip Group', mask: { type: 'clip' }, children: [source, ...out] }];\n\t\t}\n\t\tconst maskEl = rawMasks.get(urlId(attrOrStyle(el, 'mask')) ?? '');\n\t\tif (maskEl?.name === 'mask') {\n\t\t\tconst source = maskNode(maskEl, m, out, maskEl.attrs.maskContentUnits);\n\t\t\tconst type = attrOrStyle(maskEl, 'mask-type') === 'alpha' ? 'alpha' : 'luminance';\n\t\t\tif (source) out = [{ id: idFor({ name: 'g', attrs: {}, children: [] }), type: 'group', name: 'Opacity Mask', mask: { type }, children: [source, ...out] }];\n\t\t}\n\t\treturn out;\n\t};\n\n\t/**\n\t * A `<g data-vector-mask>` from our own export as the mask group it came from: the mask from its\n\t * hidden source part or its `<mask>`, the contents from the masked part (a `<id>~content` live\n\t * group there gives back the group's effects).\n\t */\n\tconst maskGroup = (g: Element, style: InheritedStyle, m: AffineMatrix, meta: Partial<VectorGroupNode>): VectorNode | null => {\n\t\tlet raw: unknown = null;\n\t\ttry {\n\t\t\traw = JSON.parse(g.attrs['data-vector-mask']);\n\t\t} catch {\n\t\t\traw = null;\n\t\t}\n\t\tconst mask = sanitizeVectorMask(raw);\n\t\tconst part = (name: string) => g.children.find((c) => c.name === 'g' && c.attrs['data-vector-part'] === name);\n\t\tconst maskedEl = part('masked');\n\t\tif (!mask || !maskedEl) return null;\n\t\tconst id = idFor(g);\n\t\tlet sourceEl = part('mask-source');\n\t\tif (!sourceEl) {\n\t\t\tconst el = rawMasks.get(urlId(maskedEl.attrs.mask) ?? '');\n\t\t\tconst invert = el?.children.find((c) => c.name === 'g' && c.attrs['data-vector-part'] === 'mask-invert');\n\t\t\tsourceEl = invert ?? el;\n\t\t}\n\t\tconst source = sourceEl ? visit(sourceEl, style, m)[0] : undefined;\n\t\tlet contents = visit(maskedEl, style, m);\n\t\tlet effects: VectorEffect[] | undefined;\n\t\tconst wrapper = contents.length === 1 && contents[0].type === 'group' && contents[0].id === `${id}~content` ? contents[0] : null;\n\t\tif (wrapper?.type === 'group') {\n\t\t\teffects = wrapper.effects ?? undefined;\n\t\t\tcontents = wrapper.children;\n\t\t}\n\t\tif (!source) return contents.length ? { id, type: 'group', ...meta, children: contents } : null;\n\t\treturn { id, type: 'group', ...meta, mask, ...(effects?.length ? { effects } : {}), children: [source, ...contents] };\n\t};\n\n\t/**\n\t * A `<g data-vector-frame>` from our own export as its frame: the contents from the\n\t * `frame-contents` part (the fill part is regenerated), the frame's rotation kept as the group's\n\t * transform and the rest of `m` mapped into its rectangle.\n\t */\n\tconst frameGroup = (g: Element, style: InheritedStyle, m: AffineMatrix, meta: Partial<VectorGroupNode>): VectorNode | null => {\n\t\tconst raw = parseJson(g.attrs['data-vector-frame']);\n\t\tconst frame = sanitizeVectorFrame(raw);\n\t\tconst contentsEl = g.children.find((c) => c.name === 'g' && c.attrs['data-vector-part'] === 'frame-contents');\n\t\tconst children = contentsEl ? visit(contentsEl, style, m) : [];\n\t\tconst id = idFor(g);\n\t\tif (!frame) return children.length ? { id, type: 'group', ...meta, children } : null;\n\t\tconst { rigid, residual } = decomposeRigid(m);\n\t\tconst r = bezierPathBounds(transformBezierPath(subpathsToBezier(vectorFrameRectPath(frame)), residual))!;\n\t\tconst back = invertMatrix(rigid);\n\t\tconst effects = sanitizeVectorEffects((raw as { effects?: unknown } | null)?.effects);\n\t\treturn {\n\t\t\tid,\n\t\t\ttype: 'group',\n\t\t\t...meta,\n\t\t\t...(isIdentityMatrix(rigid) ? {} : { transform: rigid }),\n\t\t\t// Whole numbers stay whole (the rotation split leaves float noise).\n\t\t\tframe: { ...frame, x: tidy(r.minX), y: tidy(r.minY), width: tidy(r.maxX - r.minX), height: tidy(r.maxY - r.minY) },\n\t\t\t...(effects.length ? { effects: transformVectorEffects(effects, residual) } : {}),\n\t\t\tchildren: isIdentityMatrix(rigid) ? children : children.map((c) => transformVectorNode(c, back))\n\t\t};\n\t};\n\n\tconst visitOne = (child: Element, style: InheritedStyle, matrix: AffineMatrix): VectorNode[] => {\n\t\tconst out: VectorNode[] = [];\n\t\tconst m = multiplyMatrices(parseSvgTransform(child.attrs.transform), matrix);\n\t\tconst s = readStyle(child, style);\n\t\tconst opacity = child.attrs.opacity !== undefined ? parseFloat(child.attrs.opacity) : undefined;\n\t\tconst hidden = child.attrs.display === 'none' || child.attrs.visibility === 'hidden';\n\t\tconst blendMode = vectorBlendModeFromCss(s.mixBlendMode);\n\t\tconst filters = filtersOf(s.filter);\n\t\tconst meta = {\n\t\t\t...(child.attrs['inkscape:label'] || child.attrs['data-name'] ? { name: child.attrs['inkscape:label'] ?? child.attrs['data-name'] } : {}),\n\t\t\t...(opacity !== undefined && Number.isFinite(opacity) && opacity < 1 ? { opacity } : {}),\n\t\t\t...(hidden ? { visible: false } : {}),\n\t\t\t...(blendMode && blendMode !== 'normal' ? { blendMode } : {}),\n\t\t\t...(filters.length ? { filters } : {})\n\t\t};\n\t\t// A blend's in-betweens are regenerated from its keys.\n\t\tif (child.attrs['data-vector-blend-step'] !== undefined) return out;\n\t\tconst operation = child.attrs['data-vector-boolean-operation'];\n\t\tif (BOOLEAN_OPERATIONS.includes(operation as VectorBooleanOperation)) (meta as { booleanOperation?: VectorBooleanOperation }).booleanOperation = operation as VectorBooleanOperation;\n\t\tconst resizing = child.attrs['data-vector-resizing'] !== undefined ? sanitizeVectorResizing(parseJson(child.attrs['data-vector-resizing'])) : null;\n\t\tif (resizing) (meta as { resizing?: VectorResizing }).resizing = resizing;\n\t\tconst connector = child.attrs['data-vector-connector'] !== undefined ? sanitizeVectorConnector(parseJson(child.attrs['data-vector-connector'])) : null;\n\t\tif (connector) (meta as { connector?: VectorConnector }).connector = connector;\n\t\tif (child.name === 'g' && child.attrs['data-vector-frame'] !== undefined) {\n\t\t\tconst node = frameGroup(child, s, m, meta);\n\t\t\tif (node) out.push(node);\n\t\t\treturn out;\n\t\t}\n\t\tif (child.name === 'g' && child.attrs['data-vector-mask'] !== undefined) {\n\t\t\tconst node = maskGroup(child, s, m, meta);\n\t\t\tif (node) out.push(node);\n\t\t\treturn out;\n\t\t}\n\t\tif (child.name === 'g' && child.attrs['data-vector-live'] !== undefined) {\n\t\t\tconst node = liveNode(child, s, m, meta);\n\t\t\tif (node) out.push(node);\n\t\t\treturn out;\n\t\t}\n\t\tif (child.name === 'use') {\n\t\t\tconst node = useInstance(child, m, meta);\n\t\t\tif (node) out.push(node);\n\t\t\treturn out;\n\t\t}\n\t\tif (child.name === 'g' && child.attrs['data-vector-instance'] !== undefined) {\n\t\t\tconst node = ownInstance(child, m, meta);\n\t\t\tif (node) out.push(node);\n\t\t\treturn out;\n\t\t}\n\t\tif (child.name === 'g' && child.attrs['data-vector-text'] !== undefined) {\n\t\t\tconst node = ownText(child, m, meta);\n\t\t\tif (node) out.push(node);\n\t\t\treturn out;\n\t\t}\n\t\tif (child.name === 'text') {\n\t\t\tconst node = foreignText(child, s, m, meta);\n\t\t\tif (node) out.push(node);\n\t\t\treturn out;\n\t\t}\n\t\tif (child.name === 'g' && child.attrs['data-vector-path'] !== undefined && child.attrs['data-vector-fills'] !== undefined) {\n\t\t\tconst node = stackedPath(child, s, m, meta);\n\t\t\tif (node) out.push(node);\n\t\t\treturn out;\n\t\t}\n\t\tif (child.name === 'g' && child.attrs['data-vector-path'] !== undefined) {\n\t\t\tconst node = mergedPath(child, s, m, meta);\n\t\t\tif (node) out.push(node);\n\t\t\treturn out;\n\t\t}\n\t\tif (child.name === 'g' || child.name === 'svg' || child.name === 'a' || child.name === 'switch') {\n\t\t\tconst children = visit(child, s, m);\n\t\t\tif (!children.length) return out;\n\t\t\tconst group: VectorGroupNode = { id: idFor(child), type: 'group', ...meta, children };\n\t\t\tconst blend = child.name === 'g' ? blendFromAttribute(child.attrs['data-vector-blend'], m) : null;\n\t\t\tif (blend) group.blend = blend;\n\t\t\tout.push(group);\n\t\t\treturn out;\n\t\t}\n\t\tconst subpaths = shapeOf(child);\n\t\tif (!subpaths || !subpaths.length) return out;\n\t\tconst node = placed(\n\t\t\twithOpacities(\n\t\t\t\t{\n\t\t\t\t\tid: idFor(child),\n\t\t\t\t\ttype: 'path',\n\t\t\t\t\t...meta,\n\t\t\t\t\tsubpaths,\n\t\t\t\t\tfill: child.name === 'line' ? null : (sanitizeVectorShadedPaint(parseJson(child.attrs['data-vector-shading'])) ?? paint(s.fill)),\n\t\t\t\t\tstroke: paint(s.stroke),\n\t\t\t\t\t...strokeStyle(s)\n\t\t\t\t},\n\t\t\t\ts\n\t\t\t),\n\t\t\tm\n\t\t);\n\t\tout.push(node);\n\t\treturn out;\n\t};\n\n\trootStyle = readStyle(root, rootStyle);\n\t// Our own symbols come back whether or not an instance uses them.\n\tconst walkAll = (el: Element) => {\n\t\tif (el.name === 'symbol' && el.attrs['data-vector-symbol'] !== undefined) symbolFor(el);\n\t\tel.children.forEach(walkAll);\n\t};\n\twalkAll(root);\n\tconst nodes = visit(root, rootStyle, rootMatrix);\n\treturn resolveVectorSymbols({ width, height, nodes, ...(symbols.length ? { symbols } : {}) });\n}\n","/**\n * A spatial index for hit-testing, marquee selection and snapping in large documents.\n *\n * After cadcraft's `crates/engine/src/spatial.rs` (MIT OR Apache-2.0, © ArtCraft Team and\n * contributors; see THIRD_PARTY_NOTICES.md): an R-tree over object bounds, built only above a\n * size where scanning costs more, reused while the content is the same (here: the same node array),\n * and rebuilt cheaply after an edit because each node's bounds are cached by node object, so only\n * the nodes an edit replaced are measured again (structural sharing). Queries return candidates in\n * draw order; callers then run exactly the same tests as a scan, so results are identical. The\n * tree itself is ours (sort-tile-recursive packing) since cadcraft uses the `rstar` crate.\n */\n\nimport type { VectorBounds, VectorNode } from './types.js';\nimport { vectorNodeLocalPaintBounds } from './svg.js';\nimport { applyMatrix } from '../geom/affine.js';\nimport type { AffineMatrix } from '../geom/types.js';\n\n/** Node lists shorter than this are scanned directly (building an index costs more). */\nexport const VECTOR_SPATIAL_MIN = 256;\nconst FANOUT = 16;\n\ninterface Box {\n\tminX: number;\n\tminY: number;\n\tmaxX: number;\n\tmaxY: number;\n}\n\ninterface TreeNode extends Box {\n\t/** Leaves hold item indices, inner nodes children. */\n\titems?: number[];\n\tchildren?: TreeNode[];\n}\n\nconst overlaps = (a: Box, b: Box) => a.minX <= b.maxX && b.minX <= a.maxX && a.minY <= b.maxY && b.minY <= a.maxY;\n\nfunction enclose(list: readonly Box[]): Box {\n\tlet minX = Infinity;\n\tlet minY = Infinity;\n\tlet maxX = -Infinity;\n\tlet maxY = -Infinity;\n\tfor (const b of list) {\n\t\tminX = Math.min(minX, b.minX);\n\t\tminY = Math.min(minY, b.minY);\n\t\tmaxX = Math.max(maxX, b.maxX);\n\t\tmaxY = Math.max(maxY, b.maxY);\n\t}\n\treturn { minX, minY, maxX, maxY };\n}\n\n/** A static R-tree over boxes, packed sort-tile-recursive (items with no box are always candidates). */\nexport class VectorRTree {\n\tprivate readonly root: TreeNode | null;\n\tprivate readonly always: number[];\n\tprivate readonly boxes: ReadonlyArray<Box | null>;\n\n\tconstructor(boxes: ReadonlyArray<Box | null>) {\n\t\tthis.boxes = boxes;\n\t\tconst items: Array<Box & { i: number }> = [];\n\t\tthis.always = [];\n\t\tboxes.forEach((b, i) => {\n\t\t\tif (!b) this.always.push(i);\n\t\t\telse items.push({ ...b, i });\n\t\t});\n\t\tthis.root = items.length ? VectorRTree.pack(items) : null;\n\t}\n\n\tprivate static pack(items: Array<Box & { i: number }>): TreeNode {\n\t\tlet level: TreeNode[] = [];\n\t\tconst leaves = Math.ceil(items.length / FANOUT);\n\t\tconst slices = Math.ceil(Math.sqrt(leaves));\n\t\titems.sort((a, b) => a.minX + a.maxX - (b.minX + b.maxX));\n\t\tconst perSlice = Math.ceil(items.length / slices);\n\t\tfor (let s = 0; s < items.length; s += perSlice) {\n\t\t\tconst slice = items.slice(s, s + perSlice).sort((a, b) => a.minY + a.maxY - (b.minY + b.maxY));\n\t\t\tfor (let k = 0; k < slice.length; k += FANOUT) {\n\t\t\t\tconst chunk = slice.slice(k, k + FANOUT);\n\t\t\t\tlevel.push({ ...enclose(chunk), items: chunk.map((c) => c.i) });\n\t\t\t}\n\t\t}\n\t\twhile (level.length > 1) {\n\t\t\tconst next: TreeNode[] = [];\n\t\t\tlevel.sort((a, b) => a.minX + a.maxX - (b.minX + b.maxX));\n\t\t\tconst n = Math.ceil(level.length / FANOUT);\n\t\t\tconst sl = Math.ceil(Math.sqrt(n));\n\t\t\tconst per = Math.ceil(level.length / sl);\n\t\t\tfor (let s = 0; s < level.length; s += per) {\n\t\t\t\tconst slice = level.slice(s, s + per).sort((a, b) => a.minY + a.maxY - (b.minY + b.maxY));\n\t\t\t\tfor (let k = 0; k < slice.length; k += FANOUT) {\n\t\t\t\t\tconst chunk = slice.slice(k, k + FANOUT);\n\t\t\t\t\tnext.push({ ...enclose(chunk), children: chunk });\n\t\t\t\t}\n\t\t\t}\n\t\t\tlevel = next;\n\t\t}\n\t\treturn level[0];\n\t}\n\n\t/** Indices of the items whose box meets `box` (and the unbounded ones), ascending. */\n\tsearch(box: Box): number[] {\n\t\tconst out = [...this.always];\n\t\tconst stack = this.root ? [this.root] : [];\n\t\twhile (stack.length) {\n\t\t\tconst n = stack.pop()!;\n\t\t\tif (!overlaps(n, box)) continue;\n\t\t\tif (n.items) {\n\t\t\t\tfor (const i of n.items) if (overlaps(this.boxes[i]!, box)) out.push(i);\n\t\t\t} else stack.push(...n.children!);\n\t\t}\n\t\treturn out.sort((a, b) => a - b);\n\t}\n}\n\nconst boundsCache = new WeakMap<VectorNode, Box | null>();\n\n/** A top-level node's paint box in its parent's space (strokes and filters' reach included), cached per node object. */\nexport function vectorNodePaintBox(node: VectorNode): Box | null {\n\tif (boundsCache.has(node)) return boundsCache.get(node)!;\n\tconst local = vectorNodeLocalPaintBounds(node);\n\tlet box: Box | null = null;\n\tif (local) {\n\t\tconst m = (node.transform ?? [1, 0, 0, 1, 0, 0]) as AffineMatrix;\n\t\tconst pts = [\n\t\t\t{ x: local.x, y: local.y },\n\t\t\t{ x: local.x + local.width, y: local.y },\n\t\t\t{ x: local.x, y: local.y + local.height },\n\t\t\t{ x: local.x + local.width, y: local.y + local.height }\n\t\t].map((p) => applyMatrix(m, p));\n\t\tbox = { minX: Math.min(...pts.map((p) => p.x)), minY: Math.min(...pts.map((p) => p.y)), maxX: Math.max(...pts.map((p) => p.x)), maxY: Math.max(...pts.map((p) => p.y)) };\n\t}\n\tboundsCache.set(node, box);\n\treturn box;\n}\n\nconst indexCache = new WeakMap<readonly VectorNode[], VectorRTree>();\n\n/**\n * The index over a node list (cached per array; null below `VECTOR_SPATIAL_MIN` nodes). Nodes\n * without bounds (empty groups, unresolved instances) are always candidates.\n */\nexport function vectorSpatialIndex(nodes: readonly VectorNode[]): VectorRTree | null {\n\tif (nodes.length < VECTOR_SPATIAL_MIN) return null;\n\tlet hit = indexCache.get(nodes);\n\tif (!hit) {\n\t\thit = new VectorRTree(nodes.map(vectorNodePaintBox));\n\t\tindexCache.set(nodes, hit);\n\t}\n\treturn hit;\n}\n\n/**\n * Indices (ascending, draw order) of the nodes of `nodes` that may meet `rect` padded by `pad`\n * (document units): every index when the list is small enough to scan.\n */\nexport function vectorNodesNear(nodes: readonly VectorNode[], rect: VectorBounds, pad = 0): number[] {\n\tconst index = vectorSpatialIndex(nodes);\n\tif (!index) return nodes.map((_, i) => i);\n\treturn index.search({ minX: rect.x - pad, minY: rect.y - pad, maxX: rect.x + rect.width + pad, maxY: rect.y + rect.height + pad });\n}\n","/**\n * Vector path geometry: anchors and handles to Bézier paths and back, bounds, hit-testing,\n * affine transforms, segment splitting, anchor-type conversion and shape factories.\n */\nimport { isVectorGradient, transformVectorPaint } from './gradient.js';\nimport { isVectorShadedPaint } from './shading.js';\nimport { transformVectorSymmetry } from './symmetry.js';\nimport type { Point } from '../canvas/types.js';\nimport {\n\tbezierPathBounds,\n\tbezierPathToSvg,\n\ttransformBezierPath,\n\tdistanceToBezierPath,\n\tpointInBezierPath,\n\tsegmentNearest,\n\tsegmentPoint,\n\tsplitSegment,\n\ttoBezierPath,\n\ttype AffineMatrix,\n\ttype BezierPath,\n\ttype BezierPathInput\n} from '../canvas/pathops/bezier.js';\nimport {\n\tIDENTITY_MATRIX,\n\tapplyMatrix,\n\tapplyMatrixLinear,\n\tdecomposeRigid,\n\tinvertMatrix,\n\tisIdentityMatrix,\n\tmatrixRotation,\n\tmultiplyMatrices,\n\trotateMatrix,\n\tscaleMatrix,\n\ttranslateMatrix\n} from '../geom/affine.js';\nimport { expandVectorCorners, setSubpathCorners } from './corners.js';\nimport { hitTestVectorStroke, vectorStrokeOutlinePath } from './stroke.js';\nimport { mirrorWidthProfile } from './width.js';\nimport { hitTestVectorPaintStack } from './paintLayers.js';\nimport { expandVectorAppearance, hasOwnVectorAppearance, transformVectorEffects, vectorAppearanceOutline, vectorAppearanceShapes } from './appearance.js';\nimport { isVectorMaskActive, isVectorMaskGroup, vectorMaskContains } from './mask.js';\nimport { bakeVectorTextGeometry } from './text.js';\nimport { vectorNodesNear } from './spatial.js';\nimport { isVectorFrame, vectorFrameChildMatrix, vectorFrameContains, vectorFrameRectPath, type VectorFrameGroup } from './frames.js';\nimport type {\n\tVectorAnchor,\n\tVectorAnchorType,\n\tVectorCornerKind,\n\tVectorBounds,\n\tVectorDocument,\n\tVectorGroupNode,\n\tVectorNode,\n\tVectorPaint,\n\tVectorPathNode,\n\tVectorSubpath,\n\tVectorWidthPoint,\n\tVec2,\n\tVectorTextNode\n} from './types.js';\n\nexport type { AffineMatrix };\n\nconst EPS = 1e-9;\n\n// ---------------------------------------------------------------------------\n// Small helpers\n// ---------------------------------------------------------------------------\n\nexport const cloneAnchor = (a: VectorAnchor): VectorAnchor => ({\n\tx: a.x,\n\ty: a.y,\n\t...(a.in ? { in: { x: a.in.x, y: a.in.y } } : {}),\n\t...(a.out ? { out: { x: a.out.x, y: a.out.y } } : {}),\n\t...(a.type && a.type !== 'corner' ? { type: a.type } : {}),\n\t...(a.corner ? { corner: { ...a.corner } } : {}),\n\t...(a.id ? { id: a.id } : {})\n});\n\nexport const cloneSubpath = (s: VectorSubpath): VectorSubpath => ({ anchors: s.anchors.map(cloneAnchor), closed: s.closed });\n\n/** A deep copy of a node (ids kept). */\nexport function cloneVectorNode<T extends VectorNode>(node: T): T {\n\treturn JSON.parse(JSON.stringify(node)) as T;\n}\n\nexport function cloneVectorDocument(doc: VectorDocument): VectorDocument {\n\treturn JSON.parse(JSON.stringify(doc)) as VectorDocument;\n}\n\n/** True when the paint draws something (not `null`, `'none'`, `'transparent'` or empty). */\nexport function hasPaint(paint: VectorPaint | undefined): boolean {\n\tif (paint === undefined || paint === null) return false;\n\tif (typeof paint === 'string') {\n\t\tconst p = paint.trim().toLowerCase();\n\t\treturn p !== '' && p !== 'none' && p !== 'transparent';\n\t}\n\treturn true;\n}\n\nconst handleOf = (a: VectorAnchor, side: 'in' | 'out'): Vec2 => a[side] ?? { x: a.x, y: a.y };\nconst isOnAnchor = (a: VectorAnchor, h: Vec2 | null | undefined) => !h || (Math.abs(h.x - a.x) < EPS && Math.abs(h.y - a.y) < EPS);\n\n// ---------------------------------------------------------------------------\n// Anchors ↔ Bézier\n// ---------------------------------------------------------------------------\n\n/** Number of segments of a subpath (a closed one has a segment from the last anchor back to the first). */\nexport function subpathSegmentCount(sp: VectorSubpath): number {\n\tconst n = sp.anchors.length;\n\tif (n < 2) return 0;\n\treturn sp.closed ? n : n - 1;\n}\n\n/** Control points of segment `i` of a subpath: 2 for a line, 4 for a cubic. */\nexport function subpathSegment(sp: VectorSubpath, i: number): Point[] {\n\tconst a = sp.anchors[i];\n\tconst b = sp.anchors[(i + 1) % sp.anchors.length];\n\tif (isOnAnchor(a, a.out) && isOnAnchor(b, b.in)) return [[a.x, a.y], [b.x, b.y]];\n\tconst c1 = handleOf(a, 'out');\n\tconst c2 = handleOf(b, 'in');\n\treturn [[a.x, a.y], [c1.x, c1.y], [c2.x, c2.y], [b.x, b.y]];\n}\n\n/**\n * Absolute `M` / `L` / `C` / `Z` commands of subpaths, with live corners cut\n * (`expandVectorCorners`). Pass `{ corners: false }` for the stored anchors as they are.\n */\nexport function subpathsToBezier(subpaths: readonly VectorSubpath[], options: { corners?: boolean } = {}): BezierPath {\n\tconst out: BezierPath = [];\n\tfor (const sp of options.corners === false ? subpaths : expandVectorCorners(subpaths)) {\n\t\tif (sp.anchors.length === 0) continue;\n\t\tconst first = sp.anchors[0];\n\t\tout.push({ type: 'M', x: first.x, y: first.y });\n\t\tconst count = subpathSegmentCount(sp);\n\t\tfor (let i = 0; i < count; i++) {\n\t\t\tconst seg = subpathSegment(sp, i);\n\t\t\tif (sp.closed && i === count - 1 && seg.length === 2) break; // `Z` draws the closing line.\n\t\t\tif (seg.length === 2) out.push({ type: 'L', x: seg[1][0], y: seg[1][1] });\n\t\t\telse out.push({ type: 'C', x1: seg[1][0], y1: seg[1][1], x2: seg[2][0], y2: seg[2][1], x: seg[3][0], y: seg[3][1] });\n\t\t}\n\t\tif (sp.closed) out.push({ type: 'Z' });\n\t}\n\treturn out;\n}\n\n/** The node's outline as Bézier commands, as drawn (path effects applied). Groups have none. */\nexport function vectorNodeToBezier(node: VectorNode): BezierPath {\n\treturn node.type === 'path' ? vectorAppearanceOutline(node) : [];\n}\n\n/** SVG path data (`d`) of a path node or subpaths. */\nexport function vectorPathData(input: VectorPathNode | readonly VectorSubpath[], precision = 3): string {\n\tconst subpaths = Array.isArray(input) ? (input as readonly VectorSubpath[]) : (input as VectorPathNode).subpaths;\n\treturn bezierPathToSvg(subpathsToBezier(subpaths), { precision });\n}\n\n/** Infers the anchor type from its handles. */\nexport function inferAnchorType(a: VectorAnchor): VectorAnchorType {\n\tif (isOnAnchor(a, a.in) || isOnAnchor(a, a.out)) return 'corner';\n\tconst ix = a.in!.x - a.x;\n\tconst iy = a.in!.y - a.y;\n\tconst ox = a.out!.x - a.x;\n\tconst oy = a.out!.y - a.y;\n\tconst li = Math.hypot(ix, iy);\n\tconst lo = Math.hypot(ox, oy);\n\tconst cross = (ix * oy - iy * ox) / (li * lo);\n\tconst dot = (ix * ox + iy * oy) / (li * lo);\n\tif (Math.abs(cross) > 1e-3 || dot > 0) return 'corner';\n\treturn Math.abs(li - lo) <= 1e-3 * Math.max(li, lo) ? 'symmetric' : 'smooth';\n}\n\n/**\n * Converts SVG path data or Bézier commands to editable subpaths. Quadratics become cubics,\n * arcs become cubics, a closing anchor that repeats the first one is merged into it, and\n * each anchor's type is inferred from its handles.\n */\nexport function bezierToSubpaths(input: BezierPathInput): VectorSubpath[] {\n\tconst path = toBezierPath(input);\n\tconst out: VectorSubpath[] = [];\n\tlet current: VectorSubpath | null = null;\n\tconst last = () => current!.anchors[current!.anchors.length - 1];\n\tfor (const cmd of path) {\n\t\tswitch (cmd.type) {\n\t\t\tcase 'M':\n\t\t\t\tcurrent = { anchors: [{ x: cmd.x, y: cmd.y }], closed: false };\n\t\t\t\tout.push(current);\n\t\t\t\tbreak;\n\t\t\tcase 'L':\n\t\t\t\tcurrent!.anchors.push({ x: cmd.x, y: cmd.y });\n\t\t\t\tbreak;\n\t\t\tcase 'Q': {\n\t\t\t\tconst p0 = last();\n\t\t\t\tp0.out = { x: p0.x + (2 / 3) * (cmd.x1 - p0.x), y: p0.y + (2 / 3) * (cmd.y1 - p0.y) };\n\t\t\t\tcurrent!.anchors.push({ x: cmd.x, y: cmd.y, in: { x: cmd.x + (2 / 3) * (cmd.x1 - cmd.x), y: cmd.y + (2 / 3) * (cmd.y1 - cmd.y) } });\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase 'C':\n\t\t\t\tlast().out = { x: cmd.x1, y: cmd.y1 };\n\t\t\t\tcurrent!.anchors.push({ x: cmd.x, y: cmd.y, in: { x: cmd.x2, y: cmd.y2 } });\n\t\t\t\tbreak;\n\t\t\tcase 'Z': {\n\t\t\t\tif (!current) break;\n\t\t\t\tcurrent.closed = true;\n\t\t\t\tconst anchors = current.anchors;\n\t\t\t\tif (anchors.length > 1) {\n\t\t\t\t\tconst first = anchors[0];\n\t\t\t\t\tconst end = anchors[anchors.length - 1];\n\t\t\t\t\tif (Math.abs(end.x - first.x) < 1e-7 && Math.abs(end.y - first.y) < 1e-7) {\n\t\t\t\t\t\tif (end.in) first.in = end.in;\n\t\t\t\t\t\tanchors.pop();\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tcurrent = null;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\tfor (const sp of out) {\n\t\tfor (const a of sp.anchors) {\n\t\t\tif (isOnAnchor(a, a.in)) delete a.in;\n\t\t\tif (isOnAnchor(a, a.out)) delete a.out;\n\t\t\tconst type = inferAnchorType(a);\n\t\t\tif (type !== 'corner') a.type = type;\n\t\t}\n\t}\n\treturn out.filter((sp) => sp.anchors.length > 0);\n}\n\n// ---------------------------------------------------------------------------\n// Tree helpers\n// ---------------------------------------------------------------------------\n\n/** Calls `fn` for every node, depth first, parents before children. */\nexport function walkVectorNodes(nodes: readonly VectorNode[], fn: (node: VectorNode, parent: VectorGroupNode | null, depth: number) => void): void {\n\tconst visit = (list: readonly VectorNode[], parent: VectorGroupNode | null, depth: number) => {\n\t\tfor (const node of list) {\n\t\t\tfn(node, parent, depth);\n\t\t\tif (node.type === 'group') visit(node.children, node, depth + 1);\n\t\t}\n\t};\n\tvisit(nodes, null, 0);\n}\n\n/** Finds a node by id anywhere in the tree. */\nexport function findVectorNode(nodes: readonly VectorNode[], id: string): VectorNode | undefined {\n\tfor (const node of nodes) {\n\t\tif (node.id === id) return node;\n\t\tif (node.type === 'group') {\n\t\t\tconst found = findVectorNode(node.children, id);\n\t\t\tif (found) return found;\n\t\t}\n\t}\n\treturn undefined;\n}\n\n/** The list that contains node `id` (the root list or a group's children) and its index there. */\nexport function locateVectorNode(nodes: VectorNode[], id: string): { list: VectorNode[]; index: number; parent: VectorGroupNode | null } | null {\n\tconst search = (list: VectorNode[], parent: VectorGroupNode | null): ReturnType<typeof locateVectorNode> => {\n\t\tfor (let i = 0; i < list.length; i++) {\n\t\t\tconst node = list[i];\n\t\t\tif (node.id === id) return { list, index: i, parent };\n\t\t\tif (node.type === 'group') {\n\t\t\t\tconst found = search(node.children, node);\n\t\t\t\tif (found) return found;\n\t\t\t}\n\t\t}\n\t\treturn null;\n\t};\n\treturn search(nodes, null);\n}\n\n/** Every node that paints with fills and strokes in the subtree: paths and text. */\nexport function collectPaintedNodes(node: VectorNode): Array<VectorPathNode | VectorTextNode> {\n\tconst out: Array<VectorPathNode | VectorTextNode> = [];\n\twalkVectorNodes([node], (n) => {\n\t\tif (n.type === 'path' || n.type === 'text') out.push(n);\n\t});\n\treturn out;\n}\n\n/** Every path node in the subtree (a path node itself, or a group's descendants). */\nexport function collectPathNodes(node: VectorNode): VectorPathNode[] {\n\tif (node.type === 'path') return [node];\n\tif (node.type === 'text' || node.type === 'instance') return [];\n\tconst out: VectorPathNode[] = [];\n\twalkVectorNodes(node.children, (n) => {\n\t\tif (n.type === 'path') out.push(n);\n\t});\n\treturn out;\n}\n\n// ---------------------------------------------------------------------------\n// Bounds\n// ---------------------------------------------------------------------------\n\n/** The node's local → parent matrix (identity when it has no `transform`). */\nexport function nodeMatrix(node: VectorNode): AffineMatrix {\n\treturn node.transform ?? IDENTITY_MATRIX;\n}\n\n/**\n * A path node's outline in the space `parent` maps to (default: its parent's space), as drawn:\n * live corners cut and path effects applied (`{ effects: false }`: the stored path only).\n */\nexport function vectorPathWorldBezier(node: VectorPathNode, parent: AffineMatrix = IDENTITY_MATRIX, options: { effects?: boolean } = {}): BezierPath {\n\tconst m = multiplyMatrices(nodeMatrix(node), parent);\n\tconst path = options.effects === false || !hasOwnVectorAppearance(node) ? subpathsToBezier(node.subpaths) : vectorAppearanceOutline(node);\n\treturn isIdentityMatrix(m) ? path : transformBezierPath(path, m);\n}\n\n/**\n * Geometric bounds of a node (stroke width not included) in the space `parent` maps to —\n * by default the node's parent space, which for top-level nodes is the document. Null when\n * the node has no points. A mask group is bounded by its masked result.\n */\nexport function vectorNodeBounds(node: VectorNode, parent: AffineMatrix = IDENTITY_MATRIX): VectorBounds | null {\n\t// A frame is bounded by its rectangle (and its children too when it does not clip them).\n\tif (isVectorFrame(node)) {\n\t\tconst m = multiplyMatrices(nodeMatrix(node), parent);\n\t\tconst rect = bezierPathBounds(transformBezierPath(subpathsToBezier(vectorFrameRectPath(node.frame)), m))!;\n\t\tconst box = { x: rect.minX, y: rect.minY, width: rect.maxX - rect.minX, height: rect.maxY - rect.minY };\n\t\treturn node.frame.clip === false ? unionBounds([box, ...node.children.map((c) => vectorNodeBounds(c, m))]) : box;\n\t}\n\tif (isVectorMaskActive(node)) {\n\t\tconst m = multiplyMatrices(nodeMatrix(node), parent);\n\t\tconst b = bezierPathBounds(vectorAppearanceShapes(node).flatMap((s) => (isIdentityMatrix(m) ? s.path : transformBezierPath(s.path, m))));\n\t\treturn b ? { x: b.minX, y: b.minY, width: b.maxX - b.minX, height: b.maxY - b.minY } : null;\n\t}\n\tnode = expandVectorAppearance(node);\n\tif (node.type === 'group') {\n\t\tconst m = multiplyMatrices(nodeMatrix(node), parent);\n\t\treturn unionBounds(node.children.map((c) => vectorNodeBounds(c, m)));\n\t}\n\tconst b = bezierPathBounds(vectorPathWorldBezier(node, parent));\n\tif (!b) return null;\n\treturn { x: b.minX, y: b.minY, width: b.maxX - b.minX, height: b.maxY - b.minY };\n}\n\n/** The smallest box around all non-null boxes, or null. */\nexport function unionBounds(list: readonly (VectorBounds | null | undefined)[]): VectorBounds | null {\n\tlet minX = Infinity;\n\tlet minY = Infinity;\n\tlet maxX = -Infinity;\n\tlet maxY = -Infinity;\n\tfor (const b of list) {\n\t\tif (!b) continue;\n\t\tminX = Math.min(minX, b.x);\n\t\tminY = Math.min(minY, b.y);\n\t\tmaxX = Math.max(maxX, b.x + b.width);\n\t\tmaxY = Math.max(maxY, b.y + b.height);\n\t}\n\tif (minX === Infinity) return null;\n\treturn { x: minX, y: minY, width: maxX - minX, height: maxY - minY };\n}\n\n/** True when two boxes overlap (touching counts). */\nexport function boundsIntersect(a: VectorBounds, b: VectorBounds): boolean {\n\treturn a.x <= b.x + b.width && b.x <= a.x + a.width && a.y <= b.y + b.height && b.y <= a.y + a.height;\n}\n\n/** A box from two corners in any order. */\nexport function boundsFromPoints(a: Vec2, b: Vec2): VectorBounds {\n\treturn { x: Math.min(a.x, b.x), y: Math.min(a.y, b.y), width: Math.abs(b.x - a.x), height: Math.abs(b.y - a.y) };\n}\n\n// ---------------------------------------------------------------------------\n// Hit-testing\n// ---------------------------------------------------------------------------\n\n/** Options of `hitTestVectorNode`. */\nexport interface VectorHitTestOptions {\n\t/**\n\t * Live groups (live booleans or groups with effects) hit by their children as stored rather\n\t * than by what they draw: the groups being edited.\n\t */\n\tentered?: ReadonlySet<string>;\n}\n\n/**\n * Whether `p` hits a node as drawn (path effects and live booleans applied): inside its fill\n * (when it has one), on its stroke (its alignment and arrowheads respected) or within\n * `tolerance` of either. A group is hit when any visible child is; a mask group when a child\n * above the mask is, where the mask lets it through. An entered mask group is hit by its children\n * as stored, the mask by its outline when it clips.\n */\nexport function hitTestVectorNode(node: VectorNode, p: Vec2, tolerance = 0, parent: AffineMatrix = IDENTITY_MATRIX, options: VectorHitTestOptions = {}): boolean {\n\tif (node.visible === false) return false;\n\t// A frame is hit anywhere in its rectangle (filled or not), and by children it lets show outside it.\n\tif (isVectorFrame(node)) {\n\t\tconst m = multiplyMatrices(nodeMatrix(node), parent);\n\t\tif (vectorFrameContains(node.frame, applyMatrix(invertMatrix(m), p), tolerance)) return true;\n\t\treturn node.frame.clip === false && node.children.some((c) => hitTestVectorNode(c, p, tolerance, m, options));\n\t}\n\tif (isVectorMaskGroup(node)) {\n\t\tconst m = multiplyMatrices(nodeMatrix(node), parent);\n\t\tconst entered = !!options.entered?.has(node.id);\n\t\tif (!entered && isVectorMaskActive(node) && !vectorMaskContains(node, applyMatrix(invertMatrix(m), p), tolerance)) return false;\n\t\t// With effects, the contents hit as drawn (unless entered).\n\t\tconst shown = !entered && hasOwnVectorAppearance(node) ? (expandVectorAppearance(node) as VectorGroupNode).children : node.children;\n\t\tfor (let i = shown.length - 1; i >= 1; i--) if (hitTestVectorNode(shown[i], p, tolerance, m, options)) return true;\n\t\treturn entered && hitTestVectorMaskSource(node, p, tolerance, m, options);\n\t}\n\t// Plain groups recurse as stored, so an entered live group deeper down still hits by its children.\n\tif (!(node.type === 'group' && (!hasOwnVectorAppearance(node) || options.entered?.has(node.id)))) node = expandVectorAppearance(node);\n\tif (node.type === 'group') {\n\t\tconst m = multiplyMatrices(nodeMatrix(node), parent);\n\t\treturn node.children.some((c) => hitTestVectorNode(c, p, tolerance, m, options));\n\t}\n\tconst path = vectorPathWorldBezier(node, parent);\n\tif (path.length === 0) return false;\n\t// Every drawn fill and stroke layer counts (hidden layers don't).\n\treturn hitTestVectorPaintStack(node, path, p, tolerance);\n}\n\n/** Whether `p` hits an entered mask group's mask: as drawn for an opacity mask, by its outline (any paint) for a clip. */\nfunction hitTestVectorMaskSource(group: VectorGroupNode, p: Vec2, tolerance: number, m: AffineMatrix, options: VectorHitTestOptions): boolean {\n\tconst source = group.children[0];\n\tif (source.visible === false) return false;\n\tif (group.mask?.type !== 'clip') return hitTestVectorNode(source, p, tolerance, m, options);\n\tconst paths = collectPathNodes(source).filter((n) => n.visible !== false);\n\tconst pt: [number, number] = [p.x, p.y];\n\treturn paths.some((n) => {\n\t\tconst world = vectorParentMatrix([source], n.id);\n\t\tconst path = vectorPathWorldBezier(n, multiplyMatrices(world ?? IDENTITY_MATRIX, m));\n\t\treturn pointInBezierPath(path, pt, n.fillRule ?? 'nonzero') || distanceToBezierPath(path, pt) <= tolerance;\n\t});\n}\n\n/**\n * The area a path node's stroke paints (alignment, caps, joins, dashes and arrowheads\n * included), as a filled path in the space `parent` maps to. Empty without a stroke.\n */\nexport function vectorStrokeOutline(node: VectorPathNode, parent: AffineMatrix = IDENTITY_MATRIX): BezierPath {\n\tif (!hasPaint(node.stroke) || !((node.strokeWidth ?? 1) > 0)) return [];\n\treturn vectorStrokeOutlinePath(vectorPathWorldBezier(node, parent), node);\n}\n\n/** The topmost node hit by `p` (skipping hidden and locked ones), or null. */\nexport function hitTestVectorNodes(nodes: readonly VectorNode[], p: Vec2, tolerance = 0, options: VectorHitTestOptions = {}): VectorNode | null {\n\t// Large documents: only the nodes whose paint box reaches the point (the same tests then run).\n\tconst candidates = vectorNodesNear(nodes, { x: p.x, y: p.y, width: 0, height: 0 }, tolerance);\n\tfor (let k = candidates.length - 1; k >= 0; k--) {\n\t\tconst node = nodes[candidates[k]];\n\t\tif (node.visible === false || node.locked) continue;\n\t\tif (hitTestVectorNode(node, p, tolerance, IDENTITY_MATRIX, options)) return node;\n\t}\n\treturn null;\n}\n\nexport interface NearestSegment {\n\tsubpath: number;\n\tsegment: number;\n\t/** Curve parameter 0–1 on the segment. */\n\tt: number;\n\tpoint: Vec2;\n\tdistance: number;\n}\n\n/** The closest point on any segment of a path node (`p` and the result are in the node's own space). */\nexport function nearestSegment(node: VectorPathNode, p: Vec2): NearestSegment | null {\n\tlet best: NearestSegment | null = null;\n\tnode.subpaths.forEach((sp, s) => {\n\t\tconst count = subpathSegmentCount(sp);\n\t\tfor (let i = 0; i < count; i++) {\n\t\t\tconst seg = subpathSegment(sp, i);\n\t\t\tconst hit = segmentNearest(seg, [p.x, p.y]);\n\t\t\tif (!best || hit.distance < best.distance) {\n\t\t\t\tconst pt = segmentPoint(seg, hit.t);\n\t\t\t\tbest = { subpath: s, segment: i, t: hit.t, point: { x: pt[0], y: pt[1] }, distance: hit.distance };\n\t\t\t}\n\t\t}\n\t});\n\treturn best;\n}\n\n// ---------------------------------------------------------------------------\n// Affine transforms\n// ---------------------------------------------------------------------------\n\n// The matrix maths is shared with the image editor (`src/geom/affine.ts`).\nexport {\n\tIDENTITY_MATRIX,\n\tmultiplyMatrices,\n\ttranslateMatrix,\n\tscaleMatrix,\n\trotateMatrix,\n\tapplyMatrix,\n\tisIdentityMatrix,\n\tinvertMatrix,\n\tapplyMatrixLinear,\n\tmatrixRotation,\n\tdecomposeRigid\n};\n\nfunction mapAnchor(a: VectorAnchor, m: AffineMatrix): VectorAnchor {\n\tconst p = applyMatrix(m, a);\n\tconst next: VectorAnchor = { x: p.x, y: p.y };\n\tif (a.in) next.in = applyMatrix(m, a.in);\n\tif (a.out) next.out = applyMatrix(m, a.out);\n\tif (a.type) next.type = a.type;\n\tif (a.corner) next.corner = { ...a.corner };\n\tif (a.id) next.id = a.id;\n\treturn next;\n}\n\n/** Every anchor and handle mapped through `m` (the node's own `transform` is untouched). */\nfunction bakeIntoGeometry<T extends VectorNode>(node: T, m: AffineMatrix): T {\n\tif (isIdentityMatrix(m)) return node;\n\tif (node.effects?.length) node = { ...node, effects: transformVectorEffects(node.effects, m, node) } as T;\n\tif (isVectorFrame(node)) return bakeFrame(node, m) as unknown as T;\n\tif (node.type === 'group') {\n\t\tconst group = node as VectorGroupNode;\n\t\tconst children = group.children.map((c) => transformVectorNode(c, m));\n\t\t// A symmetry's centre and axes live in the group's space too.\n\t\tconst sym = group.symmetry ? { symmetry: transformVectorSymmetry(group.symmetry, m) } : {};\n\t\t// A blend's replaced spine lives in the group's space too.\n\t\tconst spine = group.blend?.spine;\n\t\tif (!spine) return { ...group, ...sym, children } as T;\n\t\tconst moved = { closed: spine.closed, anchors: spine.anchors.map((a) => mapAnchor(a, m)) };\n\t\treturn { ...group, children, blend: { ...group.blend, spine: moved } } as T;\n\t}\n\t// Text: its frame maps and its font sizes scale (`bakeVectorTextGeometry`); paints as for paths.\n\tconst path = (node.type === 'text' ? bakeVectorTextGeometry(node as VectorTextNode, m) : node) as VectorPathNode;\n\t// A mirror swaps the sides of a variable-width stroke (the path still runs the same way).\n\tconst flips = m[0] * m[3] - m[1] * m[2] < 0;\n\tconst mirrored = flips && path.strokeWidthProfile?.length;\n\t// Each layer of a stack: its gradient moves with the geometry, its profile mirrors.\n\tconst layer = <L extends { paint: VectorPaint; strokeWidthProfile?: VectorWidthPoint[] | null }>(l: L): L => ({\n\t\t...l,\n\t\t...(isVectorGradient(l.paint) || isVectorShadedPaint(l.paint) ? { paint: transformVectorPaint(l.paint, m) } : {}),\n\t\t...(flips && l.strokeWidthProfile?.length ? { strokeWidthProfile: mirrorWidthProfile(l.strokeWidthProfile) } : {})\n\t});\n\treturn {\n\t\t...path,\n\t\t...(mirrored ? { strokeWidthProfile: mirrorWidthProfile(path.strokeWidthProfile!) } : {}),\n\t\t// Gradients in the node's own space move with its geometry.\n\t\t...(isVectorGradient(path.fill) || isVectorShadedPaint(path.fill) ? { fill: transformVectorPaint(path.fill, m) } : {}),\n\t\t...(isVectorGradient(path.stroke) || isVectorShadedPaint(path.stroke) ? { stroke: transformVectorPaint(path.stroke, m) } : {}),\n\t\t...(Array.isArray(path.fills) ? { fills: path.fills.map(layer) } : {}),\n\t\t...(Array.isArray(path.strokes) ? { strokes: path.strokes.map(layer) } : {}),\n\t\t...(path.type === 'path'\n\t\t\t? {\n\t\t\t\t\tsubpaths: path.subpaths.map((sp) => ({\n\t\t\t\t\t\tclosed: sp.closed,\n\t\t\t\t\t\tanchors: sp.anchors.map((a) => mapAnchor(a, m))\n\t\t\t\t\t}))\n\t\t\t\t}\n\t\t\t: {})\n\t} as T;\n}\n\n/**\n * A frame resized by `m` (in its own space): its rectangle maps through `m` and its children follow\n * their `resizing` constraints (`vectorFrameChildMatrix`). Text keeps its font size: area text\n * takes the new box, point and path text move with it. A skew, rotation or mirror scales every\n * child instead (constraints are per axis).\n */\nfunction bakeFrame(node: VectorFrameGroup, m: AffineMatrix): VectorFrameGroup {\n\tconst from = node.frame;\n\tconst r = bezierPathBounds(transformBezierPath(subpathsToBezier(vectorFrameRectPath(from)), m))!;\n\tconst to = { ...from, x: r.minX, y: r.minY, width: r.maxX - r.minX, height: r.maxY - r.minY };\n\tconst axisAligned = Math.abs(m[1]) < 1e-12 && Math.abs(m[2]) < 1e-12 && m[0] > 0 && m[3] > 0;\n\tif (!axisAligned) return { ...node, frame: to, children: node.children.map((c) => transformVectorNode(c, m)) };\n\tconst children = node.children.map((c): VectorNode => {\n\t\tif (c.type === 'text' && !c.transform && c.frame.kind === 'area') {\n\t\t\tconst f = c.frame;\n\t\t\tconst cm = vectorFrameChildMatrix(c.resizing, { x: f.x, y: f.y, width: f.width, height: f.height }, from, to);\n\t\t\treturn { ...c, frame: { ...f, x: cm[0] * f.x + cm[4], y: cm[3] * f.y + cm[5], width: f.width * cm[0], height: f.height * cm[3] } };\n\t\t}\n\t\tconst box = vectorNodeBounds(c);\n\t\tif (!box) return transformVectorNode(c, translateMatrix(to.x - from.x, to.y - from.y));\n\t\tconst cm = vectorFrameChildMatrix(c.resizing, box, from, to);\n\t\tif (c.type === 'text') {\n\t\t\t// Point and path text move with their box's centre; their size stays.\n\t\t\tconst cx = box.x + box.width / 2;\n\t\t\tconst cy = box.y + box.height / 2;\n\t\t\treturn transformVectorNode(c, translateMatrix(cm[0] * cx + cm[4] - cx, cm[3] * cy + cm[5] - cy));\n\t\t}\n\t\treturn transformVectorNode(c, cm);\n\t});\n\treturn { ...node, frame: to, children };\n}\n\n/**\n * A copy of the node moved by `m`, given in its parent's space. The node's rotation and\n * translation go to its rigid `transform`; scale and skew are baked into its anchors (or its\n * children), so the result draws exactly as `m` says. Stroke widths are kept.\n */\nexport function transformVectorNode<T extends VectorNode>(node: T, m: AffineMatrix): T {\n\tconst total = multiplyMatrices(nodeMatrix(node), m);\n\t// An instance keeps the whole matrix: its art is drawn through it.\n\tif (node.type === 'instance') {\n\t\tconst { transform: _t, ...rest } = node as VectorNode;\n\t\treturn (isIdentityMatrix(total) ? rest : { ...rest, transform: total }) as T;\n\t}\n\tconst { rigid, residual } = decomposeRigid(total);\n\tconst { transform: _old, ...rest } = node as VectorNode;\n\tconst baked = bakeIntoGeometry(rest as T, residual);\n\treturn isIdentityMatrix(rigid) ? baked : ({ ...baked, transform: rigid } as T);\n}\n\n/** The node's rotation in degrees (from its `transform` and its ancestors' when `parent` is given). */\nexport function vectorNodeRotation(node: VectorNode, parent: AffineMatrix = IDENTITY_MATRIX): number {\n\treturn matrixRotation(multiplyMatrices(nodeMatrix(node), parent));\n}\n\n/** The local → document matrix of node `id` (ancestors' transforms included), or null. */\nexport function vectorWorldMatrix(nodes: readonly VectorNode[], id: string): AffineMatrix | null {\n\tconst search = (list: readonly VectorNode[], parent: AffineMatrix): AffineMatrix | null => {\n\t\tfor (const n of list) {\n\t\t\tconst m = multiplyMatrices(nodeMatrix(n), parent);\n\t\t\tif (n.id === id) return m;\n\t\t\tif (n.type === 'group') {\n\t\t\t\tconst found = search(n.children, m);\n\t\t\t\tif (found) return found;\n\t\t\t}\n\t\t}\n\t\treturn null;\n\t};\n\treturn search(nodes, IDENTITY_MATRIX);\n}\n\n/** The parent space → document matrix of node `id` (identity for top-level nodes), or null. */\nexport function vectorParentMatrix(nodes: readonly VectorNode[], id: string): AffineMatrix | null {\n\tconst node = findVectorNode(nodes, id);\n\tconst world = vectorWorldMatrix(nodes, id);\n\tif (!node || !world) return null;\n\treturn multiplyMatrices(invertMatrix(nodeMatrix(node)), world);\n}\n\n// ---------------------------------------------------------------------------\n// Anchor editing\n// ---------------------------------------------------------------------------\n\n/** Moves an anchor and its handles by (dx, dy). */\nexport function translateAnchor(a: VectorAnchor, dx: number, dy: number): VectorAnchor {\n\tconst next = cloneAnchor(a);\n\tnext.x += dx;\n\tnext.y += dy;\n\tif (next.in) next.in = { x: next.in.x + dx, y: next.in.y + dy };\n\tif (next.out) next.out = { x: next.out.x + dx, y: next.out.y + dy };\n\treturn next;\n}\n\n/**\n * Moves one handle to `pos`, keeping the other in line for `smooth` anchors and mirrored for\n * `symmetric` ones. With `breakHandles` the anchor becomes a `corner` and only this handle moves.\n */\nexport function moveAnchorHandle(a: VectorAnchor, side: 'in' | 'out', pos: Vec2, breakHandles = false): VectorAnchor {\n\tconst next = cloneAnchor(a);\n\tnext[side] = { x: pos.x, y: pos.y };\n\tconst other = side === 'in' ? 'out' : 'in';\n\tconst type = breakHandles ? 'corner' : (a.type ?? 'corner');\n\tif (breakHandles) delete next.type;\n\tconst dx = pos.x - a.x;\n\tconst dy = pos.y - a.y;\n\tconst len = Math.hypot(dx, dy);\n\tif (type === 'symmetric') next[other] = { x: a.x - dx, y: a.y - dy };\n\telse if (type === 'smooth' && len > EPS) {\n\t\tconst o = a[other];\n\t\tconst olen = o ? Math.hypot(o.x - a.x, o.y - a.y) : len;\n\t\tnext[other] = { x: a.x - (dx / len) * olen, y: a.y - (dy / len) * olen };\n\t}\n\tif (isOnAnchor(next, next.in)) delete next.in;\n\tif (isOnAnchor(next, next.out)) delete next.out;\n\treturn next;\n}\n\n/**\n * Converts anchor `index` of a subpath. `corner` removes both handles; `smooth` and\n * `symmetric` keep existing handles in line, or add handles a third of the way to the\n * neighbours along the line between them.\n */\nexport function convertAnchor(sp: VectorSubpath, index: number, type: VectorAnchorType): VectorSubpath {\n\tconst anchors = sp.anchors.map(cloneAnchor);\n\tconst a = anchors[index];\n\tif (!a) return { anchors, closed: sp.closed };\n\tif (type === 'corner') {\n\t\tdelete a.in;\n\t\tdelete a.out;\n\t\tdelete a.type;\n\t\treturn { anchors, closed: sp.closed };\n\t}\n\tconst n = anchors.length;\n\tconst prev = index > 0 ? anchors[index - 1] : sp.closed ? anchors[n - 1] : null;\n\tconst next = index < n - 1 ? anchors[index + 1] : sp.closed ? anchors[0] : null;\n\tlet dir: Vec2 | null = null;\n\tlet lenIn = 0;\n\tlet lenOut = 0;\n\tif (!isOnAnchor(a, a.out)) dir = { x: a.out!.x - a.x, y: a.out!.y - a.y };\n\telse if (!isOnAnchor(a, a.in)) dir = { x: a.x - a.in!.x, y: a.y - a.in!.y };\n\telse if (prev && next) dir = { x: next.x - prev.x, y: next.y - prev.y };\n\telse if (next) dir = { x: next.x - a.x, y: next.y - a.y };\n\telse if (prev) dir = { x: a.x - prev.x, y: a.y - prev.y };\n\tif (!dir || Math.hypot(dir.x, dir.y) < EPS) return { anchors, closed: sp.closed };\n\tconst dl = Math.hypot(dir.x, dir.y);\n\tconst ux = dir.x / dl;\n\tconst uy = dir.y / dl;\n\tlenIn = a.in && !isOnAnchor(a, a.in) ? Math.hypot(a.in.x - a.x, a.in.y - a.y) : prev ? Math.hypot(prev.x - a.x, prev.y - a.y) / 3 : 0;\n\tlenOut = a.out && !isOnAnchor(a, a.out) ? Math.hypot(a.out.x - a.x, a.out.y - a.y) : next ? Math.hypot(next.x - a.x, next.y - a.y) / 3 : 0;\n\tif (type === 'symmetric') lenIn = lenOut = (lenIn + lenOut) / 2 || Math.max(lenIn, lenOut);\n\tif (lenIn > EPS) a.in = { x: a.x - ux * lenIn, y: a.y - uy * lenIn };\n\tif (lenOut > EPS) a.out = { x: a.x + ux * lenOut, y: a.y + uy * lenOut };\n\ta.type = type;\n\treturn { anchors, closed: sp.closed };\n}\n\n/**\n * Inserts an anchor on segment `segment` at parameter `t` without changing the curve's\n * shape (de Casteljau split). Returns the new subpath and the new anchor's index.\n */\nexport function insertAnchor(sp: VectorSubpath, segment: number, t: number): { subpath: VectorSubpath; index: number } {\n\tconst anchors = sp.anchors.map(cloneAnchor);\n\tconst n = anchors.length;\n\tconst ia = segment;\n\tconst ib = (segment + 1) % n;\n\tconst seg = subpathSegment(sp, segment);\n\tconst [left, right] = splitSegment(seg, t);\n\tconst mid = left[left.length - 1];\n\tconst anchor: VectorAnchor = { x: mid[0], y: mid[1] };\n\tif (seg.length === 4) {\n\t\tanchors[ia].out = { x: left[1][0], y: left[1][1] };\n\t\tanchor.in = { x: left[2][0], y: left[2][1] };\n\t\tanchor.out = { x: right[1][0], y: right[1][1] };\n\t\tanchor.type = 'smooth';\n\t\tanchors[ib].in = { x: right[2][0], y: right[2][1] };\n\t\tfor (const k of [ia, ib]) if (isOnAnchor(anchors[k], anchors[k].in)) delete anchors[k].in;\n\t\tfor (const k of [ia, ib]) if (isOnAnchor(anchors[k], anchors[k].out)) delete anchors[k].out;\n\t}\n\tconst index = segment + 1;\n\tanchors.splice(index, 0, anchor);\n\treturn { subpath: { anchors, closed: sp.closed }, index };\n}\n\n/**\n * Removes anchors from a subpath. An open subpath with fewer than 2 anchors left, or a\n * closed one with fewer than 2, is returned with whatever remains (callers drop empty ones).\n */\nexport function removeAnchors(sp: VectorSubpath, indices: readonly number[]): VectorSubpath {\n\tconst drop = new Set(indices);\n\treturn { anchors: sp.anchors.filter((_, i) => !drop.has(i)).map(cloneAnchor), closed: sp.closed };\n}\n\n/** Reverses a subpath's direction (handles swap sides). */\nexport function reverseSubpath(sp: VectorSubpath): VectorSubpath {\n\tconst anchors = sp.anchors\n\t\t.slice()\n\t\t.reverse()\n\t\t.map((a) => {\n\t\t\tconst next: VectorAnchor = { x: a.x, y: a.y };\n\t\t\tif (a.out) next.in = { ...a.out };\n\t\t\tif (a.in) next.out = { ...a.in };\n\t\t\tif (a.type) next.type = a.type;\n\t\t\tif (a.corner) next.corner = { ...a.corner };\n\t\t\tif (a.id) next.id = a.id;\n\t\t\treturn next;\n\t\t});\n\treturn { anchors, closed: sp.closed };\n}\n\n// ---------------------------------------------------------------------------\n// Shape factories\n// ---------------------------------------------------------------------------\n\n/** Handle length that makes a cubic approximate a quarter circle. */\nexport const KAPPA = 0.5522847498307936;\n\n/**\n * A rectangle. A `radius` becomes a live corner on each of its four anchors (drawn round, and\n * clamped to half the shorter side, when the path is turned into curves).\n */\nexport function rectSubpath(b: VectorBounds, radius = 0, kind?: VectorCornerKind): VectorSubpath {\n\tconst { x, y, width: w, height: h } = b;\n\tconst sp: VectorSubpath = { anchors: [{ x, y }, { x: x + w, y }, { x: x + w, y: y + h }, { x, y: y + h }], closed: true };\n\treturn radius > 0 ? setSubpathCorners(sp, radius, kind) : sp;\n}\n\n/** An ellipse inscribed in a box (four smooth anchors). */\nexport function ellipseSubpath(b: VectorBounds): VectorSubpath {\n\tconst rx = b.width / 2;\n\tconst ry = b.height / 2;\n\tconst cx = b.x + rx;\n\tconst cy = b.y + ry;\n\tconst kx = rx * KAPPA;\n\tconst ky = ry * KAPPA;\n\treturn {\n\t\tclosed: true,\n\t\tanchors: [\n\t\t\t{ x: cx, y: cy - ry, in: { x: cx - kx, y: cy - ry }, out: { x: cx + kx, y: cy - ry }, type: 'symmetric' },\n\t\t\t{ x: cx + rx, y: cy, in: { x: cx + rx, y: cy - ky }, out: { x: cx + rx, y: cy + ky }, type: 'symmetric' },\n\t\t\t{ x: cx, y: cy + ry, in: { x: cx + kx, y: cy + ry }, out: { x: cx - kx, y: cy + ry }, type: 'symmetric' },\n\t\t\t{ x: cx - rx, y: cy, in: { x: cx - rx, y: cy + ky }, out: { x: cx - rx, y: cy - ky }, type: 'symmetric' }\n\t\t]\n\t};\n}\n\n/** A regular polygon inscribed in a box, first vertex at the top. */\nexport function polygonSubpath(b: VectorBounds, sides = 6): VectorSubpath {\n\tconst n = Math.max(3, Math.round(sides));\n\tconst cx = b.x + b.width / 2;\n\tconst cy = b.y + b.height / 2;\n\tconst anchors: VectorAnchor[] = [];\n\tfor (let i = 0; i < n; i++) {\n\t\tconst t = -Math.PI / 2 + (i * 2 * Math.PI) / n;\n\t\tanchors.push({ x: cx + (Math.cos(t) * b.width) / 2, y: cy + (Math.sin(t) * b.height) / 2 });\n\t}\n\treturn { anchors, closed: true };\n}\n\n/** A star inscribed in a box, first point at the top. `innerRatio` is inner / outer radius. */\nexport function starSubpath(b: VectorBounds, points = 5, innerRatio = 0.5): VectorSubpath {\n\tconst n = Math.max(3, Math.round(points));\n\tconst cx = b.x + b.width / 2;\n\tconst cy = b.y + b.height / 2;\n\tconst anchors: VectorAnchor[] = [];\n\tfor (let i = 0; i < n * 2; i++) {\n\t\tconst t = -Math.PI / 2 + (i * Math.PI) / n;\n\t\tconst r = i % 2 === 0 ? 1 : innerRatio;\n\t\tanchors.push({ x: cx + (Math.cos(t) * r * b.width) / 2, y: cy + (Math.sin(t) * r * b.height) / 2 });\n\t}\n\treturn { anchors, closed: true };\n}\n\n/** A straight open line. */\nexport function lineSubpath(a: Vec2, b: Vec2): VectorSubpath {\n\treturn { anchors: [{ x: a.x, y: a.y }, { x: b.x, y: b.y }], closed: false };\n}\n\n/** Rounds every coordinate to `precision` decimals (stable JSON and SVG output). */\nexport function roundSubpaths(subpaths: readonly VectorSubpath[], precision = 3): VectorSubpath[] {\n\tconst f = 10 ** precision;\n\tconst r = (n: number) => Math.round(n * f) / f;\n\tconst rp = (p: Vec2) => ({ x: r(p.x), y: r(p.y) });\n\treturn subpaths.map((sp) => ({\n\t\tclosed: sp.closed,\n\t\tanchors: sp.anchors.map((a) => ({ ...cloneAnchor(a), x: r(a.x), y: r(a.y), ...(a.in ? { in: rp(a.in) } : {}), ...(a.out ? { out: rp(a.out) } : {}) }))\n\t}));\n}\n","/**\n * Live symmetry groups: children drawn with their mirrored or rotated copies.\n *\n * The mirror modes and axes follow photocraft's `crates/paint/src/symmetry.rs` (MIT OR Apache-2.0,\n * © ArtCraft Team and contributors; see THIRD_PARTY_NOTICES.md): `vertical`, `horizontal`,\n * `diagonal` and `dual` (both axes and the point reflection between them) about a centre, turned\n * by a rotation, and the axes clipped to a box for display (`segments`). Radial symmetry (turns,\n * optionally mirrored: the dihedral group) is ours. The copies are not stored: they are part of\n * the group's appearance, rebuilt whenever a child changes, like CorelDRAW's live symmetry.\n */\n\nimport type { AffineMatrix } from '../geom/types.js';\nimport { multiplyMatrices } from '../geom/affine.js';\nimport type { VectorBounds, VectorGroupNode, VectorNode, VectorSymmetry, VectorSymmetryMode, Vec2 } from './types.js';\nimport { VECTOR_SYMMETRY_MODES } from './types.js';\nimport { transformVectorNode } from './geometry.js';\n\n/** A symmetry group (with `symmetry` set, and not a blend, live boolean, mask group or frame). */\nexport type VectorSymmetryGroup = VectorGroupNode & { symmetry: VectorSymmetry };\n\n/** Whether the node is a live symmetry group. */\nexport function isVectorSymmetryGroup(node: VectorNode | null | undefined): node is VectorSymmetryGroup {\n\treturn node?.type === 'group' && !!node.symmetry && !node.blend && !node.liveBoolean && !node.mask && !node.frame;\n}\n\nconst rad = (deg: number) => (deg * Math.PI) / 180;\nconst exact = (v: number) => (Math.abs(v) < 1e-12 ? 0 : v);\nconst around = (c: Vec2, m: AffineMatrix): AffineMatrix => multiplyMatrices(multiplyMatrices([1, 0, 0, 1, -c.x, -c.y], m), [1, 0, 0, 1, c.x, c.y]);\n/** The reflection across the line through `c` at `deg` degrees (clockwise, y down). */\nconst reflect = (c: Vec2, deg: number): AffineMatrix => {\n\tconst a = 2 * rad(deg);\n\treturn around(c, [exact(Math.cos(a)), exact(Math.sin(a)), exact(Math.sin(a)), exact(-Math.cos(a)), 0, 0]);\n};\nconst turn = (c: Vec2, deg: number): AffineMatrix => around(c, [exact(Math.cos(rad(deg))), exact(Math.sin(rad(deg))), exact(-Math.sin(rad(deg))), exact(Math.cos(rad(deg))), 0, 0]);\n\n/** The directions (degrees) of the mirror axes of a mode before rotation (photocraft `directions`). */\nconst AXIS: Record<Exclude<VectorSymmetryMode, 'radial'>, number[]> = { horizontal: [0], vertical: [90], diagonal: [45], dual: [90, 0] };\n\n/** The copies a symmetry makes, as matrices in the group's space (the identity, the original, not included). */\nexport function vectorSymmetryMatrices(s: VectorSymmetry): AffineMatrix[] {\n\tconst c = s.center;\n\tconst r = s.rotation ?? 0;\n\tif (s.mode === 'radial') {\n\t\tconst n = Math.min(64, Math.max(2, Math.round(s.copies ?? 6)));\n\t\tconst out: AffineMatrix[] = [];\n\t\tfor (let k = 1; k < n; k++) out.push(turn(c, (360 * k) / n));\n\t\t// Kaleidoscope: the reflections across the n axes through the centre.\n\t\tif (s.mirror) for (let k = 0; k < n; k++) out.push(reflect(c, r + (180 * k) / n));\n\t\treturn out;\n\t}\n\tconst axes = AXIS[s.mode].map((a) => reflect(c, a + r));\n\t// Dual: both mirrors and the half turn between them.\n\treturn s.mode === 'dual' ? [...axes, turn(c, 180)] : axes;\n}\n\n/** A node with its ids (and its children's) made unique for copy `k`. */\nfunction renamed<T extends VectorNode>(node: T, k: number): T {\n\tconst id = `${node.id}~sym${k}`;\n\tif (node.type === 'group') return { ...node, id, children: node.children.map((c) => renamed(c, k)) } as T;\n\treturn { ...node, id } as T;\n}\n\nconst drawnCache = new WeakMap<VectorSymmetryGroup, VectorGroupNode>();\n\n/**\n * The symmetry group as a plain group: its children, then each copy of them (ids `<id>~sym<k>`),\n * the copies locked. Same id, transform and appearance. Cached per node.\n */\nexport function vectorSymmetryDrawn(node: VectorSymmetryGroup): VectorGroupNode {\n\tlet hit = drawnCache.get(node);\n\tif (hit) return hit;\n\tconst { symmetry, ...group } = node;\n\tconst copies = vectorSymmetryMatrices(symmetry).flatMap((m, k) => node.children.map((c) => ({ ...renamed(transformVectorNode(c, m), k + 1), locked: true })));\n\thit = { ...group, children: [...node.children, ...copies] };\n\tdrawnCache.set(node, hit);\n\treturn hit;\n}\n\n/**\n * The symmetry's axes for display: each mirror line (or each spoke of a radial symmetry) clipped\n * to `box` (photocraft `segments`), in the group's space.\n */\nexport function vectorSymmetryAxes(s: VectorSymmetry, box: VectorBounds): [Vec2, Vec2][] {\n\tconst r = s.rotation ?? 0;\n\tconst dirs = s.mode === 'radial' ? Array.from({ length: Math.min(64, Math.max(2, Math.round(s.copies ?? 6))) }, (_, k) => r - 90 + (360 * k) / Math.min(64, Math.max(2, Math.round(s.copies ?? 6)))) : AXIS[s.mode].map((a) => a + r);\n\tconst out: [Vec2, Vec2][] = [];\n\tfor (const deg of dirs) {\n\t\tconst d = { x: Math.cos(rad(deg)), y: Math.sin(rad(deg)) };\n\t\tlet lo = s.mode === 'radial' ? 0 : -Infinity;\n\t\tlet hi = Infinity;\n\t\tlet inside = true;\n\t\tfor (const [o, dv, min, max] of [\n\t\t\t[s.center.x, d.x, box.x, box.x + box.width],\n\t\t\t[s.center.y, d.y, box.y, box.y + box.height]\n\t\t] as const) {\n\t\t\tif (Math.abs(dv) < 1e-12) {\n\t\t\t\tif (o < min || o > max) inside = false;\n\t\t\t} else {\n\t\t\t\tconst a = (min - o) / dv;\n\t\t\t\tconst b = (max - o) / dv;\n\t\t\t\tlo = Math.max(lo, Math.min(a, b));\n\t\t\t\thi = Math.min(hi, Math.max(a, b));\n\t\t\t}\n\t\t}\n\t\tif (inside && Number.isFinite(lo) && Number.isFinite(hi) && hi > lo) out.push([{ x: s.center.x + lo * d.x, y: s.center.y + lo * d.y }, { x: s.center.x + hi * d.x, y: s.center.y + hi * d.y }]);\n\t}\n\treturn out;\n}\n\n/** Reads symmetry settings from untrusted data (JSON, agent input, SVG import), or null. */\nexport function sanitizeVectorSymmetry(value: unknown): VectorSymmetry | null {\n\tif (!value || typeof value !== 'object') return null;\n\tconst r = value as Record<string, unknown>;\n\tif (!VECTOR_SYMMETRY_MODES.includes(r.mode as VectorSymmetryMode)) return null;\n\tconst c = r.center as Vec2 | undefined;\n\tif (!c || !Number.isFinite(c.x) || !Number.isFinite(c.y)) return null;\n\tconst out: VectorSymmetry = { mode: r.mode as VectorSymmetryMode, center: { x: c.x, y: c.y } };\n\tif (typeof r.rotation === 'number' && Number.isFinite(r.rotation) && r.rotation % 360 !== 0) out.rotation = ((r.rotation % 360) + 360) % 360;\n\tif (out.mode === 'radial') {\n\t\tif (typeof r.copies === 'number' && Number.isFinite(r.copies)) out.copies = Math.min(64, Math.max(2, Math.round(r.copies)));\n\t\tif (r.mirror === true) out.mirror = true;\n\t}\n\treturn out;\n}\n\n/** Labels for the symmetry pickers. */\nexport const VECTOR_SYMMETRY_MODE_LABELS: Readonly<Record<VectorSymmetryMode, string>> = {\n\tvertical: 'Mirror left / right',\n\thorizontal: 'Mirror top / bottom',\n\tdual: 'Four quarters',\n\tdiagonal: 'Mirror diagonally',\n\tradial: 'Radial'\n};\n\n/** The symmetry settings carried through a map baked into the group (its centre moves; its axes turn with a rotation, flip with a mirror). */\nexport function transformVectorSymmetry(s: VectorSymmetry, m: AffineMatrix): VectorSymmetry {\n\tconst center = { x: m[0] * s.center.x + m[2] * s.center.y + m[4], y: m[1] * s.center.x + m[3] * s.center.y + m[5] };\n\tconst det = m[0] * m[3] - m[1] * m[2];\n\tconst angle = (Math.atan2(m[1], m[0]) * 180) / Math.PI;\n\tconst rotation = det < 0 ? -(s.rotation ?? 0) + 2 * angle : (s.rotation ?? 0) + angle;\n\tconst norm = ((rotation % 360) + 360) % 360;\n\treturn { ...s, center, ...(Math.abs(norm) > 1e-9 && Math.abs(norm - 360) > 1e-9 ? { rotation: norm } : { rotation: undefined }) };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA0BO,IAAM,sBAAmD,CAAC,SAAS,YAAY,SAAS;AAyDxF,IAAM,wBAAuD,CAAC,UAAU,UAAU,SAAS,aAAa,SAAS;AAIjH,IAAM,0BAA2D,CAAC,OAAO,WAAW,QAAQ;AAI5F,IAAM,iCAAyE,CAAC,QAAQ,UAAU,OAAO;AAczG,IAAM,+BAAoE,CAAC,UAAU,SAAS,QAAQ;AAoHtG,IAAM,oBAAgD,CAAC,YAAY,SAAS,QAAQ,UAAU,UAAU,KAAK;AA4C7G,IAAM,qBAAiD;AAAA,EAC7D;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAA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AS,UAAU;AAC1B,QAAI,OAAO,EAAE,WAAW,YAAY,OAAO,SAAS,EAAE,MAAM,EAAG,KAAI,SAAS,KAAK,IAAI,IAAI,KAAK,IAAI,GAAG,KAAK,MAAM,EAAE,MAAM,CAAC,CAAC;AAC1H,QAAI,EAAE,WAAW,KAAM,KAAI,SAAS;AAAA,EACrC;AACA,SAAO;AACR;AAGO,IAAM,8BAA4E;AAAA,EACxF,UAAU;AAAA,EACV,YAAY;AAAA,EACZ,MAAM;AAAA,EACN,UAAU;AAAA,EACV,QAAQ;AACT;AAGO,SAAS,wBAAwB,GAAmB,GAAiC;AAC3F,QAAM,SAAS,EAAE,GAAG,EAAE,CAAC,IAAI,EAAE,OAAO,IAAI,EAAE,CAAC,IAAI,EAAE,OAAO,IAAI,EAAE,CAAC,GAAG,GAAG,EAAE,CAAC,IAAI,EAAE,OAAO,IAAI,EAAE,CAAC,IAAI,EAAE,OAAO,IAAI,EAAE,CAAC,EAAE;AAClH,QAAM,MAAM,EAAE,CAAC,IAAI,EAAE,CAAC,IAAI,EAAE,CAAC,IAAI,EAAE,CAAC;AACpC,QAAM,QAAS,KAAK,MAAM,EAAE,CAAC,GAAG,EAAE,CAAC,CAAC,IAAI,MAAO,KAAK;AACpD,QAAM,WAAW,MAAM,IAAI,EAAE,EAAE,YAAY,KAAK,IAAI,SAAS,EAAE,YAAY,KAAK;AAChF,QAAM,QAAS,WAAW,MAAO,OAAO;AACxC,SAAO,EAAE,GAAG,GAAG,QAAQ,GAAI,KAAK,IAAI,IAAI,IAAI,QAAQ,KAAK,IAAI,OAAO,GAAG,IAAI,OAAO,EAAE,UAAU,KAAK,IAAI,EAAE,UAAU,OAAU,EAAG;AACjI;","names":["v","color","at","tangent","plain","s","start","turn","along","mirrored","capped","clean","color","v","at","left","c","scale","len","add","acc","n","fmt","apply","v","sub","add","mul","dot","t","v","turn","V","v","same","p","round","sub","v","lerp","len","w","cross","dot","left","polygon","near","pt","scale","at","s","t","dist","place","near","v","next","same","num","plain","EPS","unit","perp","v","turn","sub","len","pt","lerp","dist","toVec","out","finite","v","scale","pt","degenerate","face","fi","from","to","len","v","pt","invert","fe","length","left","at","k","l","exact","length","left","at","tangent","layoutCache","computeLayout","v","polygon","g","n","num","clean","next","runs","fmt","sym","nodes","strip","v","at","tangent","q","pt","c","pt","v","add","rad","color","near","along","out","visit","len","v","e","near","fmt","v","toSvgStops","polygonD","add","sub","scale","unit","tidy","v","escapeAttr","node","bounds","reach","area","key","byKey","defs","left","num","out","h","emit","w","at","attrs","sym","exact","live","plain","len","along","same","nodes","width","scale","visit","json","place","strip","invert","EPS","cross","dot","current","visit","b","pt","sym","cm","rest","len","EPS","left","KAPPA","v","drawnCache"]}