@pairdraw/core 0.20.0 → 0.21.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.
- package/dist/canvas/noise/render.js +1 -1
- package/dist/canvas/noise/render.js.map +1 -1
- package/dist/canvas/noise/shader.d.ts +6 -3
- package/dist/canvas/noise/shader.d.ts.map +1 -1
- package/dist/canvas/noise/shader.js +12 -7
- package/dist/canvas/noise/shader.js.map +1 -1
- package/dist/canvas/noise/tile.d.ts.map +1 -1
- package/dist/canvas/noise/tile.js +2 -1
- package/dist/canvas/noise/tile.js.map +1 -1
- package/dist/canvas/renderer/colors.d.ts +20 -5
- package/dist/canvas/renderer/colors.d.ts.map +1 -1
- package/dist/canvas/renderer/colors.js +48 -42
- package/dist/canvas/renderer/colors.js.map +1 -1
- package/dist/canvas/renderer/document-surface.d.ts +25 -0
- package/dist/canvas/renderer/document-surface.d.ts.map +1 -0
- package/dist/canvas/renderer/document-surface.js +46 -0
- package/dist/canvas/renderer/document-surface.js.map +1 -0
- package/dist/canvas/renderer/fonts.d.ts.map +1 -1
- package/dist/canvas/renderer/fonts.js +6 -4
- package/dist/canvas/renderer/fonts.js.map +1 -1
- package/dist/canvas/renderer/lifecycle.js +4 -3
- package/dist/canvas/renderer/lifecycle.js.map +1 -1
- package/dist/canvas/renderer/methods.d.ts.map +1 -1
- package/dist/canvas/renderer/methods.js +1 -0
- package/dist/canvas/renderer/methods.js.map +1 -1
- package/dist/canvas/renderer/pipeline.d.ts.map +1 -1
- package/dist/canvas/renderer/pipeline.js +23 -2
- package/dist/canvas/renderer/pipeline.js.map +1 -1
- package/dist/canvas/renderer/retained-backing.d.ts.map +1 -1
- package/dist/canvas/renderer/retained-backing.js +2 -1
- package/dist/canvas/renderer/retained-backing.js.map +1 -1
- package/dist/canvas/renderer/tiles/surface-pool.d.ts.map +1 -1
- package/dist/canvas/renderer/tiles/surface-pool.js +2 -7
- package/dist/canvas/renderer/tiles/surface-pool.js.map +1 -1
- package/dist/canvas/renderer.d.ts +20 -2
- package/dist/canvas/renderer.d.ts.map +1 -1
- package/dist/canvas/renderer.js +28 -4
- package/dist/canvas/renderer.js.map +1 -1
- package/dist/canvas/scene.d.ts.map +1 -1
- package/dist/canvas/scene.js +4 -3
- package/dist/canvas/scene.js.map +1 -1
- package/dist/canvas/shaders/effect.d.ts.map +1 -1
- package/dist/canvas/shaders/effect.js +2 -1
- package/dist/canvas/shaders/effect.js.map +1 -1
- package/dist/canvas/shadows/shape.d.ts.map +1 -1
- package/dist/canvas/shadows/shape.js +4 -2
- package/dist/canvas/shadows/shape.js.map +1 -1
- package/dist/canvas/shadows.d.ts.map +1 -1
- package/dist/canvas/shadows.js +4 -2
- package/dist/canvas/shadows.js.map +1 -1
- package/dist/canvas/text/decorations.d.ts +2 -2
- package/dist/canvas/text/decorations.d.ts.map +1 -1
- package/dist/canvas/text/decorations.js +5 -5
- package/dist/canvas/text/decorations.js.map +1 -1
- package/dist/canvas/text/index.js +1 -1
- package/dist/canvas/text/index.js.map +1 -1
- package/dist/canvas/text/paragraph/index.d.ts +2 -2
- package/dist/canvas/text/paragraph/index.d.ts.map +1 -1
- package/dist/canvas/text/paragraph/index.js +16 -5
- package/dist/canvas/text/paragraph/index.js.map +1 -1
- package/dist/canvas/text/renderer.d.ts +2 -1
- package/dist/canvas/text/renderer.d.ts.map +1 -1
- package/dist/canvas/text/shape.js +4 -4
- package/dist/canvas/text/shape.js.map +1 -1
- package/dist/canvas/texture.d.ts.map +1 -1
- package/dist/canvas/texture.js +2 -1
- package/dist/canvas/texture.js.map +1 -1
- package/dist/design-memory/rules.js +1 -1
- package/dist/editor/bridges/undo.d.ts +1 -1
- package/dist/editor/clipboard/assets.d.ts.map +1 -1
- package/dist/editor/clipboard/assets.js +2 -2
- package/dist/editor/clipboard/assets.js.map +1 -1
- package/dist/editor/clipboard/component-matches.d.ts +13 -0
- package/dist/editor/clipboard/component-matches.d.ts.map +1 -0
- package/dist/editor/clipboard/component-matches.js +50 -0
- package/dist/editor/clipboard/component-matches.js.map +1 -0
- package/dist/editor/clipboard/dependencies.d.ts +7 -0
- package/dist/editor/clipboard/dependencies.d.ts.map +1 -1
- package/dist/editor/clipboard/dependencies.js +5 -0
- package/dist/editor/clipboard/dependencies.js.map +1 -1
- package/dist/editor/clipboard.d.ts.map +1 -1
- package/dist/editor/clipboard.js +48 -19
- package/dist/editor/clipboard.js.map +1 -1
- package/dist/editor/components/properties.d.ts.map +1 -1
- package/dist/editor/components/properties.js +3 -3
- package/dist/editor/components/properties.js.map +1 -1
- package/dist/editor/create.d.ts +1 -1
- package/dist/editor/eyedropper.d.ts +1 -1
- package/dist/editor/eyedropper.d.ts.map +1 -1
- package/dist/editor/eyedropper.js +6 -3
- package/dist/editor/eyedropper.js.map +1 -1
- package/dist/editor/history/atomic-tool.d.ts.map +1 -1
- package/dist/editor/history/atomic-tool.js +3 -2
- package/dist/editor/history/atomic-tool.js.map +1 -1
- package/dist/editor/shapes/pencil.js +1 -1
- package/dist/editor/structure/state.d.ts.map +1 -1
- package/dist/editor/structure/state.js +2 -2
- package/dist/editor/structure/state.js.map +1 -1
- package/dist/editor/text.d.ts.map +1 -1
- package/dist/editor/text.js +2 -2
- package/dist/editor/text.js.map +1 -1
- package/dist/editor/variables.js +3 -3
- package/dist/editor/variables.js.map +1 -1
- package/dist/figma-api/fresh-read.d.ts +15 -0
- package/dist/figma-api/fresh-read.d.ts.map +1 -0
- package/dist/figma-api/fresh-read.js +54 -0
- package/dist/figma-api/fresh-read.js.map +1 -0
- package/dist/figma-api/graph-ref.d.ts +9 -0
- package/dist/figma-api/graph-ref.d.ts.map +1 -0
- package/dist/figma-api/graph-ref.js +14 -0
- package/dist/figma-api/graph-ref.js.map +1 -0
- package/dist/figma-api/index.d.ts +6 -1
- package/dist/figma-api/index.d.ts.map +1 -1
- package/dist/figma-api/index.js +12 -5
- package/dist/figma-api/index.js.map +1 -1
- package/dist/figma-api/pending-layout.d.ts +3 -3
- package/dist/figma-api/pending-layout.d.ts.map +1 -1
- package/dist/figma-api/pending-layout.js +7 -3
- package/dist/figma-api/pending-layout.js.map +1 -1
- package/dist/figma-api/pending-sync.d.ts +1 -1
- package/dist/figma-api/pending-sync.d.ts.map +1 -1
- package/dist/figma-api/pending-sync.js +3 -1
- package/dist/figma-api/pending-sync.js.map +1 -1
- package/dist/figma-api/proxy.d.ts.map +1 -1
- package/dist/figma-api/proxy.js +3 -2
- package/dist/figma-api/proxy.js.map +1 -1
- package/dist/figma-api/reactions.d.ts +20 -4
- package/dist/figma-api/reactions.d.ts.map +1 -1
- package/dist/figma-api/reactions.js +49 -3
- package/dist/figma-api/reactions.js.map +1 -1
- package/dist/figma-api/variables/index.d.ts.map +1 -1
- package/dist/figma-api/variables/index.js +2 -2
- package/dist/figma-api/variables/index.js.map +1 -1
- package/dist/io/formats/design-tokens/css/known.js +1 -1
- package/dist/io/formats/design-tokens/css/known.js.map +1 -1
- package/dist/io/formats/design-tokens/css/read.d.ts +3 -1
- package/dist/io/formats/design-tokens/css/read.d.ts.map +1 -1
- package/dist/io/formats/design-tokens/css/read.js +11 -5
- package/dist/io/formats/design-tokens/css/read.js.map +1 -1
- package/dist/io/formats/design-tokens/css/sync.d.ts.map +1 -1
- package/dist/io/formats/design-tokens/css/sync.js +17 -4
- package/dist/io/formats/design-tokens/css/sync.js.map +1 -1
- package/dist/io/formats/design-tokens/css/values.d.ts +6 -5
- package/dist/io/formats/design-tokens/css/values.d.ts.map +1 -1
- package/dist/io/formats/design-tokens/css/values.js +24 -8
- package/dist/io/formats/design-tokens/css/values.js.map +1 -1
- package/dist/io/formats/design-tokens/decode.d.ts +7 -6
- package/dist/io/formats/design-tokens/decode.d.ts.map +1 -1
- package/dist/io/formats/design-tokens/decode.js +13 -12
- package/dist/io/formats/design-tokens/decode.js.map +1 -1
- package/dist/io/formats/design-tokens/export.js +3 -3
- package/dist/io/formats/design-tokens/export.js.map +1 -1
- package/dist/io/formats/design-tokens/plan/index.d.ts.map +1 -1
- package/dist/io/formats/design-tokens/plan/index.js +4 -3
- package/dist/io/formats/design-tokens/plan/index.js.map +1 -1
- package/dist/io/formats/design-tokens/plan/styles.d.ts.map +1 -1
- package/dist/io/formats/design-tokens/plan/styles.js +9 -9
- package/dist/io/formats/design-tokens/plan/styles.js.map +1 -1
- package/dist/io/formats/design-tokens/styles.d.ts +4 -4
- package/dist/io/formats/design-tokens/styles.d.ts.map +1 -1
- package/dist/io/formats/design-tokens/styles.js +7 -7
- package/dist/io/formats/design-tokens/styles.js.map +1 -1
- package/dist/io/formats/design-tokens/sync/drift.js +2 -2
- package/dist/io/formats/design-tokens/sync/drift.js.map +1 -1
- package/dist/io/formats/design-tokens/values.d.ts +10 -5
- package/dist/io/formats/design-tokens/values.d.ts.map +1 -1
- package/dist/io/formats/design-tokens/values.js +13 -7
- package/dist/io/formats/design-tokens/values.js.map +1 -1
- package/dist/io/formats/drawio/label.js +1 -1
- package/dist/io/formats/drawio/paint.js +1 -1
- package/dist/io/formats/drawio/warnings.js +2 -2
- package/dist/io/formats/drawio/warnings.js.map +1 -1
- package/dist/io/formats/fig/export/index.d.ts.map +1 -1
- package/dist/io/formats/fig/export/index.js +15 -3
- package/dist/io/formats/fig/export/index.js.map +1 -1
- package/dist/io/formats/fig/export/patch/index.d.ts.map +1 -1
- package/dist/io/formats/fig/export/patch/index.js +2 -1
- package/dist/io/formats/fig/export/patch/index.js.map +1 -1
- package/dist/io/formats/fig/export/setup.d.ts +7 -2
- package/dist/io/formats/fig/export/setup.d.ts.map +1 -1
- package/dist/io/formats/fig/export/setup.js +12 -13
- package/dist/io/formats/fig/export/setup.js.map +1 -1
- package/dist/io/formats/fig/export/variables.d.ts.map +1 -1
- package/dist/io/formats/fig/export/variables.js +9 -7
- package/dist/io/formats/fig/export/variables.js.map +1 -1
- package/dist/io/formats/html/vectors.js +1 -0
- package/dist/io/formats/html/vectors.js.map +1 -1
- package/dist/io/formats/mermaid/layers.js +2 -2
- package/dist/io/formats/mermaid/layers.js.map +1 -1
- package/dist/io/formats/mermaid/styles.js +1 -1
- package/dist/io/formats/pdf/export.d.ts.map +1 -1
- package/dist/io/formats/pdf/export.js +1 -0
- package/dist/io/formats/pdf/export.js.map +1 -1
- package/dist/io/formats/pdf/prepare.d.ts +4 -4
- package/dist/io/formats/pdf/prepare.d.ts.map +1 -1
- package/dist/io/formats/pdf/prepare.js +2 -2
- package/dist/io/formats/pdf/prepare.js.map +1 -1
- package/dist/io/formats/pen/index.js +4 -2
- package/dist/io/formats/pen/index.js.map +1 -1
- package/dist/io/formats/pptx/style.js +1 -1
- package/dist/io/formats/raster/render.d.ts +1 -1
- package/dist/io/formats/raster/render.d.ts.map +1 -1
- package/dist/io/formats/raster/render.js +9 -4
- package/dist/io/formats/raster/render.js.map +1 -1
- package/dist/io/formats/svg/defs.d.ts +6 -3
- package/dist/io/formats/svg/defs.d.ts.map +1 -1
- package/dist/io/formats/svg/defs.js +12 -11
- package/dist/io/formats/svg/defs.js.map +1 -1
- package/dist/io/formats/svg/effects.js +2 -2
- package/dist/io/formats/svg/effects.js.map +1 -1
- package/dist/io/formats/svg/export.d.ts +5 -2
- package/dist/io/formats/svg/export.d.ts.map +1 -1
- package/dist/io/formats/svg/export.js +4 -2
- package/dist/io/formats/svg/export.js.map +1 -1
- package/dist/io/formats/svg/filter.d.ts +4 -1
- package/dist/io/formats/svg/filter.d.ts.map +1 -1
- package/dist/io/formats/svg/filter.js +6 -2
- package/dist/io/formats/svg/filter.js.map +1 -1
- package/dist/io/formats/svg/grain.js +1 -1
- package/dist/io/formats/svg/grain.js.map +1 -1
- package/dist/io/formats/svg/import.d.ts +4 -2
- package/dist/io/formats/svg/import.d.ts.map +1 -1
- package/dist/io/formats/svg/import.js +2 -1
- package/dist/io/formats/svg/import.js.map +1 -1
- package/dist/io/formats/svg/text/export.d.ts.map +1 -1
- package/dist/io/formats/svg/text/export.js +8 -8
- package/dist/io/formats/svg/text/export.js.map +1 -1
- package/dist/io/formats/svg/text/layout.js +2 -2
- package/dist/io/formats/svg/text/layout.js.map +1 -1
- package/dist/io/formats.d.ts.map +1 -1
- package/dist/io/formats.js +1 -0
- package/dist/io/formats.js.map +1 -1
- package/dist/io/subgraph.d.ts.map +1 -1
- package/dist/io/subgraph.js +1 -1
- package/dist/io/subgraph.js.map +1 -1
- package/dist/io/types.d.ts +1 -1
- package/dist/kiwi/fig/session/options.d.ts +3 -0
- package/dist/kiwi/fig/session/options.d.ts.map +1 -1
- package/dist/kiwi/fig/session/options.js +4 -0
- package/dist/kiwi/fig/session/options.js.map +1 -1
- package/dist/layout/yoga-helpers.d.ts +2 -1
- package/dist/layout/yoga-helpers.d.ts.map +1 -1
- package/dist/layout/yoga-helpers.js +7 -1
- package/dist/layout/yoga-helpers.js.map +1 -1
- package/dist/layout.js +24 -1
- package/dist/layout.js.map +1 -1
- package/dist/lint/fixes.js +1 -1
- package/dist/lint/linter.js +2 -2
- package/dist/lint/linter.js.map +1 -1
- package/dist/pairdraw-api/comments.d.ts +4 -1
- package/dist/pairdraw-api/comments.d.ts.map +1 -1
- package/dist/pairdraw-api/comments.js +5 -0
- package/dist/pairdraw-api/comments.js.map +1 -1
- package/dist/pairdraw-api/index.d.ts +3 -3
- package/dist/pairdraw-api/index.d.ts.map +1 -1
- package/dist/pairdraw-api/index.js +5 -5
- package/dist/pairdraw-api/index.js.map +1 -1
- package/dist/pairdraw-api/nodes.d.ts +1 -1
- package/dist/prototype/scene.js +1 -1
- package/dist/rpc/analyze-commands.js +1 -1
- package/dist/rpc/read-commands.d.ts +2 -2
- package/dist/rpc/read-commands.js +3 -3
- package/dist/rpc/read-commands.js.map +1 -1
- package/dist/rpc/variables-command.js +2 -2
- package/dist/rpc/variables-command.js.map +1 -1
- package/dist/text/font/provider.d.ts +15 -0
- package/dist/text/font/provider.d.ts.map +1 -0
- package/dist/text/font/provider.js +18 -0
- package/dist/text/font/provider.js.map +1 -0
- package/dist/text/font/readiness.d.ts +32 -0
- package/dist/text/font/readiness.d.ts.map +1 -0
- package/dist/text/font/{status.js → readiness.js} +8 -4
- package/dist/text/font/readiness.js.map +1 -0
- package/dist/text/index.d.ts +4 -3
- package/dist/text/index.js +4 -3
- package/dist/text/prepare.d.ts +9 -4
- package/dist/text/prepare.d.ts.map +1 -1
- package/dist/text/prepare.js +9 -4
- package/dist/text/prepare.js.map +1 -1
- package/dist/tools/analyze/colors.js +1 -1
- package/dist/tools/analyze/responsive/index.js +7 -18
- package/dist/tools/analyze/responsive/index.js.map +1 -1
- package/dist/tools/analyze/responsive/widths.d.ts +27 -0
- package/dist/tools/analyze/responsive/widths.d.ts.map +1 -0
- package/dist/tools/analyze/responsive/widths.js +49 -0
- package/dist/tools/analyze/responsive/widths.js.map +1 -0
- package/dist/tools/analyze.d.ts +2 -1
- package/dist/tools/analyze.js +2 -1
- package/dist/tools/codegen/tokens.d.ts.map +1 -1
- package/dist/tools/codegen/tokens.js +2 -2
- package/dist/tools/codegen/tokens.js.map +1 -1
- package/dist/tools/comments.d.ts.map +1 -1
- package/dist/tools/comments.js +2 -2
- package/dist/tools/comments.js.map +1 -1
- package/dist/tools/component-catalog.d.ts.map +1 -1
- package/dist/tools/component-catalog.js +5 -3
- package/dist/tools/component-catalog.js.map +1 -1
- package/dist/tools/create/basic.js +1 -1
- package/dist/tools/create/behaviours.js +1 -1
- package/dist/tools/create/html.d.ts.map +1 -1
- package/dist/tools/create/html.js +1 -3
- package/dist/tools/create/html.js.map +1 -1
- package/dist/tools/create/icons.js +2 -2
- package/dist/tools/create/icons.js.map +1 -1
- package/dist/tools/create/mermaid.js +1 -1
- package/dist/tools/create/render.js +1 -1
- package/dist/tools/create/svg.js +5 -2
- package/dist/tools/create/svg.js.map +1 -1
- package/dist/tools/create/vector.js +3 -3
- package/dist/tools/create/vector.js.map +1 -1
- package/dist/tools/css/shorthand.d.ts +20 -0
- package/dist/tools/css/shorthand.d.ts.map +1 -0
- package/dist/tools/css/shorthand.js +54 -0
- package/dist/tools/css/shorthand.js.map +1 -0
- package/dist/tools/describe/index.js +2 -2
- package/dist/tools/describe/index.js.map +1 -1
- package/dist/tools/describe/issues.js +1 -1
- package/dist/tools/html-host.d.ts.map +1 -1
- package/dist/tools/html-host.js +5 -3
- package/dist/tools/html-host.js.map +1 -1
- package/dist/tools/image-ai/apply.d.ts.map +1 -1
- package/dist/tools/image-ai/apply.js +1 -3
- package/dist/tools/image-ai/apply.js.map +1 -1
- package/dist/tools/image-ai/generate.js +1 -1
- package/dist/tools/image-ai/service.d.ts.map +1 -1
- package/dist/tools/image-ai/service.js +5 -3
- package/dist/tools/image-ai/service.js.map +1 -1
- package/dist/tools/index.d.ts +2 -1
- package/dist/tools/index.js +2 -1
- package/dist/tools/modify/effects.js +1 -1
- package/dist/tools/modify/effects.js.map +1 -1
- package/dist/tools/modify/geometry.d.ts.map +1 -1
- package/dist/tools/modify/geometry.js +14 -3
- package/dist/tools/modify/geometry.js.map +1 -1
- package/dist/tools/modify/layout.d.ts.map +1 -1
- package/dist/tools/modify/layout.js +35 -8
- package/dist/tools/modify/layout.js.map +1 -1
- package/dist/tools/modify/matching.d.ts.map +1 -1
- package/dist/tools/modify/matching.js +10 -10
- package/dist/tools/modify/matching.js.map +1 -1
- package/dist/tools/modify/paint.d.ts.map +1 -1
- package/dist/tools/modify/paint.js +57 -5
- package/dist/tools/modify/paint.js.map +1 -1
- package/dist/tools/modify/reactions.d.ts.map +1 -1
- package/dist/tools/modify/reactions.js +2 -2
- package/dist/tools/modify/reactions.js.map +1 -1
- package/dist/tools/modify/text.d.ts.map +1 -1
- package/dist/tools/modify/text.js +3 -3
- package/dist/tools/modify/text.js.map +1 -1
- package/dist/tools/prompts/codegen.js +1 -1
- package/dist/tools/prompts/codegen.js.map +1 -1
- package/dist/tools/read/css.d.ts +14 -0
- package/dist/tools/read/css.d.ts.map +1 -0
- package/dist/tools/read/css.js +306 -0
- package/dist/tools/read/css.js.map +1 -0
- package/dist/tools/read/libraries.js +1 -1
- package/dist/tools/read/reactions.js +1 -1
- package/dist/tools/read/reactions.js.map +1 -1
- package/dist/tools/read/space.d.ts.map +1 -1
- package/dist/tools/read/space.js +0 -2
- package/dist/tools/read/space.js.map +1 -1
- package/dist/tools/read.d.ts +2 -1
- package/dist/tools/read.js +2 -1
- package/dist/tools/registry/core.d.ts +1 -1
- package/dist/tools/registry/core.js +3 -1
- package/dist/tools/registry/core.js.map +1 -1
- package/dist/tools/schema.d.ts +6 -4
- package/dist/tools/schema.d.ts.map +1 -1
- package/dist/tools/schema.js +9 -5
- package/dist/tools/schema.js.map +1 -1
- package/dist/tools/script/host.d.ts.map +1 -1
- package/dist/tools/script/host.js +5 -3
- package/dist/tools/script/host.js.map +1 -1
- package/dist/tools/variables/collections.js +1 -1
- package/dist/tools/variables/collections.js.map +1 -1
- package/dist/tools/variables/values.d.ts.map +1 -1
- package/dist/tools/variables/values.js +4 -4
- package/dist/tools/variables/values.js.map +1 -1
- package/dist/tools/vector/vectorize.d.ts.map +1 -1
- package/dist/tools/vector/vectorize.js +6 -4
- package/dist/tools/vector/vectorize.js.map +1 -1
- package/dist/tools/video-host.d.ts.map +1 -1
- package/dist/tools/video-host.js +5 -3
- package/dist/tools/video-host.js.map +1 -1
- package/dist/vector/vectorize/svg/gradients.d.ts +2 -2
- package/dist/vector/vectorize/svg/gradients.d.ts.map +1 -1
- package/dist/vector/vectorize/svg/gradients.js +5 -5
- package/dist/vector/vectorize/svg/gradients.js.map +1 -1
- package/dist/vector/vectorize/svg/to-vectors.d.ts +3 -1
- package/dist/vector/vectorize/svg/to-vectors.d.ts.map +1 -1
- package/dist/vector/vectorize/svg/to-vectors.js +13 -12
- package/dist/vector/vectorize/svg/to-vectors.js.map +1 -1
- package/package.json +9 -9
- package/src/canvas/noise/render.ts +1 -1
- package/src/canvas/noise/shader.ts +13 -5
- package/src/canvas/noise/tile.ts +2 -1
- package/src/canvas/renderer/colors.ts +76 -50
- package/src/canvas/renderer/document-surface.ts +53 -0
- package/src/canvas/renderer/fonts.ts +6 -4
- package/src/canvas/renderer/lifecycle.ts +4 -4
- package/src/canvas/renderer/methods.ts +1 -0
- package/src/canvas/renderer/pipeline.ts +21 -3
- package/src/canvas/renderer/retained-backing.ts +2 -1
- package/src/canvas/renderer/tiles/surface-pool.ts +9 -7
- package/src/canvas/renderer.ts +36 -11
- package/src/canvas/scene.ts +4 -3
- package/src/canvas/shaders/effect.ts +2 -1
- package/src/canvas/shadows/shape.ts +4 -2
- package/src/canvas/shadows.ts +5 -2
- package/src/canvas/text/decorations.ts +15 -5
- package/src/canvas/text/index.ts +9 -1
- package/src/canvas/text/paragraph/index.ts +16 -6
- package/src/canvas/text/renderer.ts +2 -1
- package/src/canvas/text/shape.ts +4 -4
- package/src/canvas/texture.ts +2 -1
- package/src/editor/clipboard/assets.ts +6 -2
- package/src/editor/clipboard/component-matches.ts +65 -0
- package/src/editor/clipboard/dependencies.ts +22 -1
- package/src/editor/clipboard.ts +74 -20
- package/src/editor/components/properties.ts +3 -2
- package/src/editor/eyedropper.ts +14 -4
- package/src/editor/history/atomic-tool.ts +3 -2
- package/src/editor/structure/state.ts +2 -1
- package/src/editor/text.ts +2 -1
- package/src/editor/variables.ts +3 -3
- package/src/figma-api/fresh-read.ts +57 -0
- package/src/figma-api/graph-ref.ts +13 -0
- package/src/figma-api/index.ts +12 -4
- package/src/figma-api/pending-layout.ts +7 -3
- package/src/figma-api/pending-sync.ts +4 -1
- package/src/figma-api/proxy.ts +2 -1
- package/src/figma-api/reactions.ts +91 -10
- package/src/figma-api/variables/index.ts +5 -4
- package/src/io/formats/design-tokens/css/known.ts +1 -1
- package/src/io/formats/design-tokens/css/read.ts +20 -7
- package/src/io/formats/design-tokens/css/sync.ts +9 -4
- package/src/io/formats/design-tokens/css/values.ts +37 -9
- package/src/io/formats/design-tokens/decode.ts +17 -12
- package/src/io/formats/design-tokens/export.ts +3 -3
- package/src/io/formats/design-tokens/plan/index.ts +6 -5
- package/src/io/formats/design-tokens/plan/styles.ts +37 -10
- package/src/io/formats/design-tokens/styles.ts +10 -7
- package/src/io/formats/design-tokens/sync/drift.ts +6 -4
- package/src/io/formats/design-tokens/values.ts +15 -8
- package/src/io/formats/drawio/warnings.ts +2 -2
- package/src/io/formats/fig/export/index.ts +36 -3
- package/src/io/formats/fig/export/patch/index.ts +4 -1
- package/src/io/formats/fig/export/setup.ts +25 -15
- package/src/io/formats/fig/export/variables.ts +17 -6
- package/src/io/formats/html/vectors.ts +1 -0
- package/src/io/formats/mermaid/layers.ts +2 -2
- package/src/io/formats/pdf/export.ts +1 -0
- package/src/io/formats/pdf/prepare.ts +6 -6
- package/src/io/formats/pen/index.ts +5 -2
- package/src/io/formats/raster/render.ts +12 -4
- package/src/io/formats/svg/defs.ts +26 -14
- package/src/io/formats/svg/effects.ts +2 -2
- package/src/io/formats/svg/export.ts +17 -3
- package/src/io/formats/svg/filter.ts +12 -2
- package/src/io/formats/svg/grain.ts +1 -1
- package/src/io/formats/svg/import.ts +6 -3
- package/src/io/formats/svg/text/export.ts +10 -8
- package/src/io/formats/svg/text/layout.ts +2 -2
- package/src/io/formats.ts +8 -1
- package/src/io/subgraph.ts +4 -1
- package/src/kiwi/fig/session/options.ts +4 -1
- package/src/layout/yoga-helpers.ts +8 -0
- package/src/layout.ts +47 -1
- package/src/lint/linter.ts +1 -1
- package/src/pairdraw-api/comments.ts +6 -0
- package/src/pairdraw-api/index.ts +7 -9
- package/src/rpc/read-commands.ts +4 -4
- package/src/rpc/variables-command.ts +2 -2
- package/src/text/font/provider.ts +26 -0
- package/src/text/font/{status.ts → readiness.ts} +13 -9
- package/src/text/index.ts +2 -1
- package/src/text/prepare.ts +9 -4
- package/src/tools/analyze/responsive/index.ts +8 -15
- package/src/tools/analyze/responsive/widths.ts +63 -0
- package/src/tools/analyze.ts +2 -0
- package/src/tools/codegen/tokens.ts +4 -2
- package/src/tools/comments.ts +6 -4
- package/src/tools/component-catalog.ts +5 -3
- package/src/tools/create/html.ts +0 -3
- package/src/tools/create/icons.ts +1 -1
- package/src/tools/create/svg.ts +4 -1
- package/src/tools/create/vector.ts +2 -2
- package/src/tools/css/shorthand.ts +64 -0
- package/src/tools/describe/index.ts +2 -8
- package/src/tools/html-host.ts +5 -3
- package/src/tools/image-ai/apply.ts +0 -2
- package/src/tools/image-ai/service.ts +5 -3
- package/src/tools/index.ts +2 -0
- package/src/tools/modify/effects.ts +1 -1
- package/src/tools/modify/geometry.ts +16 -3
- package/src/tools/modify/layout.ts +47 -13
- package/src/tools/modify/matching.ts +14 -11
- package/src/tools/modify/paint.ts +85 -5
- package/src/tools/modify/reactions.ts +3 -2
- package/src/tools/modify/text.ts +15 -11
- package/src/tools/prompts/codegen.md +2 -1
- package/src/tools/read/css.ts +365 -0
- package/src/tools/read/reactions.ts +3 -2
- package/src/tools/read/space.ts +0 -2
- package/src/tools/read.ts +1 -0
- package/src/tools/registry/core.ts +3 -2
- package/src/tools/schema.ts +14 -5
- package/src/tools/script/host.ts +6 -3
- package/src/tools/variables/collections.ts +1 -1
- package/src/tools/variables/values.ts +16 -5
- package/src/tools/vector/vectorize.ts +10 -4
- package/src/tools/video-host.ts +5 -3
- package/src/vector/vectorize/svg/gradients.ts +8 -5
- package/src/vector/vectorize/svg/to-vectors.ts +48 -14
- package/dist/text/font/status.d.ts +0 -28
- package/dist/text/font/status.d.ts.map +0 -1
- package/dist/text/font/status.js.map +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"css.js","names":[],"sources":["../../../src/tools/read/css.ts"],"sourcesContent":["import * as v from 'valibot'\n\nimport type { ColorProfile, SceneGraph, SceneNode, ShadowEffect } from '@pairdraw/scene-graph'\nimport { colorToDocumentCSS } from '@pairdraw/scene-graph/color'\nimport type { Color } from '@pairdraw/scene-graph/primitives'\n\nimport { defineTool, nodeIdsField, toolNumber } from '#core/tools/schema'\n\n/**\n * A subtree as CSS-shaped lines: one line per node, lengths in px, colours in the document's\n * profile with the token that binds them in `var(--name, …)` form: hex in an sRGB document,\n * `color(display-p3 …)` in a Display P3 one. This is the read side of the CSS shorthand the\n * setters accept, so a value read here can be written back unchanged.\n */\nexport const DEFAULT_MAX_BYTES = 6000\nexport const HARD_MAX_BYTES = 20_000\n\nconst AXIS_JUSTIFY: Record<string, string> = {\n CENTER: 'center',\n MAX: 'end',\n SPACE_BETWEEN: 'space-between',\n SPACE_AROUND: 'space-around'\n}\n\nconst AXIS_ITEMS: Record<string, string> = {\n CENTER: 'center',\n MAX: 'end',\n STRETCH: 'stretch',\n BASELINE: 'baseline'\n}\n\n/** A length as CSS writes it: whole px where it is whole, up to two decimals otherwise. */\nfunction px(value: number): string {\n return `${Math.round(value * 100) / 100}px`\n}\n\n/**\n * The radius line, read the way `shape-details` reads corners: the per-corner fields while\n * `independentCorners` is set (the uniform field is stale then), four values in CSS order when\n * they differ, one otherwise. The four values write back through `set_radius`'s shorthand.\n */\nfunction radiusOf(node: SceneNode): string | null {\n if (node.independentCorners) {\n const corners = [\n node.topLeftRadius,\n node.topRightRadius,\n node.bottomRightRadius,\n node.bottomLeftRadius\n ]\n if (corners.every((value) => value === corners[0])) {\n return corners[0] > 0 ? px(corners[0]) : null\n }\n return corners.map((value) => (value === 0 ? '0' : px(value))).join(' ')\n }\n return node.cornerRadius > 0 ? px(node.cornerRadius) : null\n}\n\nfunction box(value: number): string {\n return String(Math.round(value))\n}\n\n/** UTF-8 bytes without a Node Buffer, so the tool runs in the app as well as headless. */\nfunction utf8Length(text: string): number {\n let bytes = 0\n for (let index = 0; index < text.length; index++) {\n const code = text.charCodeAt(index)\n if (code < 0x80) bytes += 1\n else if (code < 0x800) bytes += 2\n else if (code < 0xd800 || code >= 0xe000) bytes += 3\n else bytes += 4\n }\n return bytes\n}\n\nfunction boundName(graph: SceneGraph, node: SceneNode, field: string): string | null {\n const variableId = node.boundVariables[field]\n if (!variableId) return null\n return graph.variables.get(variableId)?.name ?? null\n}\n\n/**\n * A stored colour as the shorthand writes it: `#RRGGBB` in an sRGB document, `color(display-p3 …)`\n * in a Display P3 one, where hex would name a different colour. The shorthand carries no alpha, as\n * it never has, so the paint's opacity is left to `opacity`.\n */\nfunction cssColor(color: Color, profile: ColorProfile): string {\n return colorToDocumentCSS({ ...color, a: 1 }, profile)\n}\n\n/** A colour in the document's profile, or `var(--token, …)` when a variable paints it. */\nfunction paintOf(node: SceneNode, graph: SceneGraph, field: string, paint: string): string {\n const name = boundName(graph, node, field)\n return name ? `var(--${name}, ${paint})` : paint\n}\n\nfunction background(node: SceneNode, graph: SceneGraph): string | null {\n const index = node.fills.findIndex((candidate) => candidate.type === 'SOLID' && candidate.visible)\n const solid = index === -1 ? undefined : node.fills[index]\n if (solid) {\n const paint = cssColor(solid.color, graph.documentColorSpace)\n return paintOf(node, graph, `fills/${index}/color`, paint)\n }\n const otherIndex = node.fills.findIndex((candidate) => candidate.visible)\n const other = otherIndex === -1 ? undefined : node.fills[otherIndex]\n if (!other) return null\n return other.type.startsWith('GRADIENT') ? 'gradient' : 'image'\n}\n\nfunction border(node: SceneNode, graph: SceneGraph): string | null {\n const index = node.strokes.findIndex((candidate) => candidate.visible)\n const stroke = index === -1 ? undefined : node.strokes[index]\n if (!stroke) return null\n const paint = cssColor(stroke.color, graph.documentColorSpace)\n return `${px(stroke.weight)} ${paintOf(node, graph, `strokes/${index}/color`, paint)}`\n}\n\n/** Padding in CSS order, compressed to the fewest values that say the same thing. */\nfunction padding(node: SceneNode): string | null {\n const top = node.paddingTop\n const right = node.paddingRight\n const bottom = node.paddingBottom\n const left = node.paddingLeft\n if (top === 0 && right === 0 && bottom === 0 && left === 0) return null\n if (top === right && right === bottom && bottom === left) return px(top)\n if (top === bottom && right === left) return `${px(top)} ${px(right)}`\n return `${px(top)} ${px(right)} ${px(bottom)} ${px(left)}`\n}\n\nfunction shadowOf(prefix: string, effect: ShadowEffect, profile: ColorProfile): string {\n return `${prefix}:${px(effect.offset.x)} ${px(effect.offset.y)} ${px(effect.radius)} ${cssColor(effect.color, profile)}`\n}\n\nfunction effects(node: SceneNode, profile: ColorProfile): string[] {\n const out: string[] = []\n for (const effect of node.effects) {\n if (!effect.visible) continue\n if (effect.type === 'DROP_SHADOW') out.push(shadowOf('shadow', effect, profile))\n else if (effect.type === 'INNER_SHADOW') out.push(shadowOf('inner-shadow', effect, profile))\n else if (effect.type === 'LAYER_BLUR' || effect.type === 'FOREGROUND_BLUR')\n out.push(`blur:${px(effect.radius)}`)\n else out.push('backdrop-blur')\n }\n return out\n}\n\nfunction layoutDecls(node: SceneNode): string[] {\n if (node.layoutMode === 'NONE') return []\n const out = [node.layoutMode === 'HORIZONTAL' ? 'flex:row' : 'flex:column']\n if (node.itemSpacing > 0) {\n out.push(\n node.layoutWrap === 'WRAP' && node.counterAxisSpacing > 0\n ? `gap:${px(node.itemSpacing)} ${px(node.counterAxisSpacing)}`\n : `gap:${px(node.itemSpacing)}`\n )\n }\n const paddingValue = padding(node)\n if (paddingValue) out.push(`padding:${paddingValue}`)\n const justify = AXIS_JUSTIFY[node.primaryAxisAlign]\n if (justify) out.push(`justify:${justify}`)\n const items = AXIS_ITEMS[node.counterAxisAlign]\n if (items) out.push(`items:${items}`)\n if (node.layoutWrap === 'WRAP') out.push('wrap')\n if (node.primaryAxisSizing === 'HUG') out.push('hug:main')\n if (node.counterAxisSizing === 'HUG') out.push('hug:cross')\n return out\n}\n\nfunction boxDecls(node: SceneNode, graph: SceneGraph): string[] {\n const out: string[] = []\n if (node.layoutAlignSelf === 'STRETCH') out.push('stretch')\n if (node.layoutGrow > 0) out.push(`grow:${Math.round(node.layoutGrow * 100) / 100}`)\n const bg = background(node, graph)\n if (bg) out.push(`bg:${bg}`)\n const stroke = border(node, graph)\n if (stroke) out.push(`border:${stroke}`)\n const radius = radiusOf(node)\n if (radius) out.push(`radius:${radius}`)\n if (node.minWidth !== null) out.push(`min-w:${px(node.minWidth)}`)\n if (node.maxWidth !== null) out.push(`max-w:${px(node.maxWidth)}`)\n if (node.minHeight !== null) out.push(`min-h:${px(node.minHeight)}`)\n if (node.maxHeight !== null) out.push(`max-h:${px(node.maxHeight)}`)\n out.push(...effects(node, graph.documentColorSpace))\n if (node.opacity !== 1) out.push(`opacity:${Math.round(node.opacity * 100) / 100}`)\n if (node.clipsContent) out.push('clip')\n return out\n}\n\nfunction lineHeightOf(node: SceneNode): string {\n const lineHeight = node.lineHeight\n if (!lineHeight) return 'auto'\n return lineHeight.unit === 'PERCENT'\n ? `${Math.round(lineHeight.value * 100) / 100}%`\n : px(lineHeight.value)\n}\n\nfunction textDecls(node: SceneNode, graph: SceneGraph): string[] {\n const out = [\n `font:${node.fontWeight} ${px(node.fontSize)}/${lineHeightOf(node)} ${node.fontFamily}`\n ]\n const bg = background(node, graph)\n if (bg) out.push(`color:${bg}`)\n if (node.textAlignHorizontal !== 'LEFT') {\n out.push(`text-align:${node.textAlignHorizontal.toLowerCase()}`)\n }\n if (node.maxLines !== null && node.maxLines > 0) out.push(`max-lines:${node.maxLines}`)\n if (node.textAutoResize === 'NONE') out.push('fixed')\n return out\n}\n\nfunction lineOf(node: SceneNode, graph: SceneGraph): string {\n const decls =\n node.type === 'TEXT' ? textDecls(node, graph) : [...layoutDecls(node), ...boxDecls(node, graph)]\n const label =\n node.type === 'TEXT'\n ? `\"${node.text.slice(0, 40).replaceAll('\\\\', '\\\\\\\\').replaceAll('\"', '\\\\\"').replaceAll('\\n', '\\\\n')}\"`\n : node.name\n const body = decls.length > 0 ? ` {${decls.join(';')}}` : ''\n return `${label}#${node.id} ${box(node.width)}×${box(node.height)}${body}`\n}\n\ninterface Budget {\n bytes: number\n limit: number\n truncated: boolean\n}\n\n/** What a cut-off walk left out, counted through the same visible-node rule as the lines. */\nfunction countVisible(graph: SceneGraph, nodeId: string): number {\n const node = graph.getNode(nodeId)\n if (!node || !node.visible) return 0\n let count = 1\n for (const childId of node.childIds) count += countVisible(graph, childId)\n return count\n}\n\nfunction truncationTail(omitted: number): string {\n return `… +${omitted} node${omitted === 1 ? '' : 's'} (raise max_bytes or narrow with depth)`\n}\n\n/**\n * Depth-first lines until the budget is spent. A line that does not fit ends the walk; the kept\n * lines never exceed the limit on their own, so the reply can always stay within `max_bytes`.\n */\nfunction collect(\n graph: SceneGraph,\n nodeId: string,\n depth: number,\n indent: string,\n lines: string[],\n budget: Budget\n): void {\n const node = graph.getNode(nodeId)\n if (!node || !node.visible) return\n if (budget.truncated) return\n const line = `${indent}${lineOf(node, graph)}`\n const fits = budget.bytes + utf8Length(line) + 1 <= budget.limit\n if (!fits) {\n budget.truncated = true\n return\n }\n budget.bytes += utf8Length(line) + 1\n lines.push(line)\n if (depth > 0) {\n for (const childId of node.childIds) {\n collect(graph, childId, depth - 1, `${indent} `, lines, budget)\n }\n }\n}\n\n/**\n * A subtree within `maxBytes`. The truncation tail is charged to the same budget: trailing lines\n * give way first, then the tail is left out when only the kept lines fit. A block whose first line\n * does not fit returns no CSS at all; the reply's `truncated`/`omitted` fields report the cut.\n */\nfunction blockFor(\n graph: SceneGraph,\n nodeId: string,\n depth: number,\n maxBytes: number\n): { css: string; truncated?: true; omitted?: number } {\n const lines: string[] = []\n const budget: Budget = { bytes: 0, limit: maxBytes, truncated: false }\n collect(graph, nodeId, depth, '', lines, budget)\n if (!budget.truncated) return { css: lines.join('\\n') }\n // Every visible node either has a line or is left out, so the omitted count follows from the\n // node total. Each dropped line's byte count includes the newline collect charged for it.\n let omitted = countVisible(graph, nodeId) - lines.length\n while (\n lines.length > 1 &&\n budget.bytes + 1 + utf8Length(truncationTail(omitted)) > budget.limit\n ) {\n const last = lines.pop()\n if (last === undefined) break\n budget.bytes -= utf8Length(last) + 1\n omitted = countVisible(graph, nodeId) - lines.length\n }\n if (lines.length === 0) {\n return { css: '', truncated: true, omitted: countVisible(graph, nodeId) }\n }\n const head = lines.join('\\n')\n if (budget.bytes + 1 + utf8Length(truncationTail(omitted)) > budget.limit) {\n return { css: head, truncated: true, omitted }\n }\n return { css: `${head}\\n${truncationTail(omitted)}`, truncated: true, omitted }\n}\n\nexport const getCSS = defineTool({\n name: 'get_css',\n description:\n 'Read a node subtree as compact CSS-like lines: `Name#id W×H {flex:row;gap:12px;padding:16px 24px;bg:var(--color/brand, #4F46E5);radius:8px}`. ' +\n 'Lengths are px; short names: flex (implies display:flex), gap, padding, justify, items, wrap, hug, stretch, grow, bg, border, radius, min/max-w/h, shadow, blur, opacity, clip; text: `font:600 14px/20px Inter`, color, text-align, max-lines. ' +\n \"Colours follow the document's profile, as get_jsx writes them: `#RRGGBB` in an sRGB document, `color(display-p3 r g b)` in a Display P3 one, and either inside the `var()` fallback. \" +\n 'Use it for geometry and style; describe gives roles and design issues. The setters accept the same shorthand (padding/gap/radius strings, `var(--token)` colours).',\n execution: { kind: 'sync', mutation: 'none' },\n input: v.strictObject({\n id: v.optional(v.pipe(v.string(), v.description('Node ID (single node)'))),\n ids: nodeIdsField('Node IDs (several nodes in one call)'),\n depth: v.optional(\n toolNumber(\n v.pipe(\n v.number(),\n v.description('Child levels to include (default: as many as the budget holds)')\n )\n )\n ),\n max_bytes: v.optional(\n toolNumber(\n v.pipe(v.number(), v.description('Byte budget for the reply (default 6000, max 20000)'))\n )\n )\n }),\n execute: (figma, args) => {\n const maxBytes = Math.min(args.max_bytes ?? DEFAULT_MAX_BYTES, HARD_MAX_BYTES)\n const depth = args.depth ?? 100\n\n if (args.ids && Array.isArray(args.ids)) {\n const blocks: string[] = []\n let omitted = 0\n let truncated = false\n let used = 0\n for (const nodeId of args.ids) {\n if (!figma.graph.getNode(nodeId)) return { error: `Node \"${nodeId}\" not found` }\n const separator = blocks.length === 0 ? 0 : 1\n const block = blockFor(figma.graph, nodeId, depth, maxBytes - used - separator)\n if (block.css === '') {\n omitted += block.omitted ?? 0\n truncated = truncated || block.truncated === true\n continue\n }\n blocks.push(block.css)\n used += utf8Length(block.css) + separator\n omitted += block.omitted ?? 0\n truncated = truncated || block.truncated === true\n }\n const css = blocks.join('\\n')\n if (!truncated) return { ids: args.ids, css }\n return { ids: args.ids, css, truncated: true, omitted }\n }\n\n if (!args.id) return { error: 'Provide id (string) or ids (string[])' }\n if (!figma.graph.getNode(args.id)) return { error: `Node \"${args.id}\" not found` }\n const block = blockFor(figma.graph, args.id, depth, maxBytes)\n return { id: args.id, ...block }\n }\n})\n"],"mappings":";;;;;;;;;;AAcA,MAAa,oBAAoB;AACjC,MAAa,iBAAiB;AAE9B,MAAM,eAAuC;CAC3C,QAAQ;CACR,KAAK;CACL,eAAe;CACf,cAAc;AAChB;AAEA,MAAM,aAAqC;CACzC,QAAQ;CACR,KAAK;CACL,SAAS;CACT,UAAU;AACZ;;AAGA,SAAS,GAAG,OAAuB;CACjC,OAAO,GAAG,KAAK,MAAM,QAAQ,GAAG,IAAI,IAAI;AAC1C;;;;;;AAOA,SAAS,SAAS,MAAgC;CAChD,IAAI,KAAK,oBAAoB;EAC3B,MAAM,UAAU;GACd,KAAK;GACL,KAAK;GACL,KAAK;GACL,KAAK;EACP;EACA,IAAI,QAAQ,OAAO,UAAU,UAAU,QAAQ,EAAE,GAC/C,OAAO,QAAQ,KAAK,IAAI,GAAG,QAAQ,EAAE,IAAI;EAE3C,OAAO,QAAQ,KAAK,UAAW,UAAU,IAAI,MAAM,GAAG,KAAK,CAAE,CAAC,CAAC,KAAK,GAAG;CACzE;CACA,OAAO,KAAK,eAAe,IAAI,GAAG,KAAK,YAAY,IAAI;AACzD;AAEA,SAAS,IAAI,OAAuB;CAClC,OAAO,OAAO,KAAK,MAAM,KAAK,CAAC;AACjC;;AAGA,SAAS,WAAW,MAAsB;CACxC,IAAI,QAAQ;CACZ,KAAK,IAAI,QAAQ,GAAG,QAAQ,KAAK,QAAQ,SAAS;EAChD,MAAM,OAAO,KAAK,WAAW,KAAK;EAClC,IAAI,OAAO,KAAM,SAAS;OACrB,IAAI,OAAO,MAAO,SAAS;OAC3B,IAAI,OAAO,SAAU,QAAQ,OAAQ,SAAS;OAC9C,SAAS;CAChB;CACA,OAAO;AACT;AAEA,SAAS,UAAU,OAAmB,MAAiB,OAA8B;CACnF,MAAM,aAAa,KAAK,eAAe;CACvC,IAAI,CAAC,YAAY,OAAO;CACxB,OAAO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OAAO,EAAE,OAAO,SAAS,OAAO,aAAa;IAC/E,MAAM,YAAY,OAAO,WAAW,IAAI,IAAI;IAC5C,MAAM,QAAQ,SAAS,MAAM,OAAO,QAAQ,OAAO,WAAW,OAAO,SAAS;IAC9E,IAAI,MAAM,QAAQ,IAAI;KACpB,WAAW,MAAM,WAAW;KAC5B,YAAY,aAAa,MAAM,cAAc;KAC7C;IACF;IACA,OAAO,KAAK,MAAM,GAAG;IACrB,QAAQ,WAAW,MAAM,GAAG,IAAI;IAChC,WAAW,MAAM,WAAW;IAC5B,YAAY,aAAa,MAAM,cAAc;GAC/C;GACA,MAAM,MAAM,OAAO,KAAK,IAAI;GAC5B,IAAI,CAAC,WAAW,OAAO;IAAE,KAAK,KAAK;IAAK;GAAI;GAC5C,OAAO;IAAE,KAAK,KAAK;IAAK;IAAK,WAAW;IAAM;GAAQ;EACxD;EAEA,IAAI,CAAC,KAAK,IAAI,OAAO,EAAE,OAAO,wCAAwC;EACtE,IAAI,CAAC,MAAM,MAAM,QAAQ,KAAK,EAAE,GAAG,OAAO,EAAE,OAAO,SAAS,KAAK,GAAG,aAAa;EACjF,MAAM,QAAQ,SAAS,MAAM,OAAO,KAAK,IAAI,OAAO,QAAQ;EAC5D,OAAO;GAAE,IAAI,KAAK;GAAI,GAAG;EAAM;CACjC;AACF,CAAC"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { prepareSlotInsertion } from "../../figma-api/slots.js";
|
|
2
1
|
import { defineTool, toolNumber } from "../schema.js";
|
|
2
|
+
import { prepareSlotInsertion } from "../../figma-api/slots.js";
|
|
3
3
|
import { getComponentCatalog } from "../component-catalog.js";
|
|
4
4
|
import { groupBy, isPlainObject } from "es-toolkit";
|
|
5
5
|
import * as v from "valibot";
|
|
@@ -3,7 +3,7 @@ import * as v from "valibot";
|
|
|
3
3
|
//#region src/tools/read/reactions.ts
|
|
4
4
|
const getReactions = defineTool({
|
|
5
5
|
name: "get_reactions",
|
|
6
|
-
description: "Get the prototype connections on a layer, in Figma's plugin shape: each trigger and its actions, with a NODE action naming the destination frame. Empty when the layer connects to nothing.",
|
|
6
|
+
description: "Get the prototype connections on a layer, in Figma's plugin shape: each trigger and its actions, with a NODE action naming the destination frame or variant. A Change to authored by variant properties reads back as the destination variant id. Empty when the layer connects to nothing.",
|
|
7
7
|
execution: {
|
|
8
8
|
kind: "sync",
|
|
9
9
|
mutation: "none"
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"reactions.js","names":[],"sources":["../../../src/tools/read/reactions.ts"],"sourcesContent":["import * as v from 'valibot'\n\nimport { defineTool, nodeIdInputSchema, nodeNotFound } from '#core/tools/schema'\n\nexport const getReactions = defineTool({\n name: 'get_reactions',\n\n description:\n \"Get the prototype connections on a layer, in Figma's plugin shape: each trigger and its \" +\n 'actions, with a NODE action naming the destination frame. Empty when the layer
|
|
1
|
+
{"version":3,"file":"reactions.js","names":[],"sources":["../../../src/tools/read/reactions.ts"],"sourcesContent":["import * as v from 'valibot'\n\nimport { defineTool, nodeIdInputSchema, nodeNotFound } from '#core/tools/schema'\n\nexport const getReactions = defineTool({\n name: 'get_reactions',\n\n description:\n \"Get the prototype connections on a layer, in Figma's plugin shape: each trigger and its \" +\n 'actions, with a NODE action naming the destination frame or variant. A Change to authored ' +\n 'by variant properties reads back as the destination variant id. Empty when the layer ' +\n 'connects to nothing.',\n execution: { kind: 'sync', mutation: 'none' },\n input: v.strictObject({\n id: nodeIdInputSchema\n }),\n execute: (figma, { id }) => {\n const node = figma.getNodeById(id)\n if (!node) return nodeNotFound(id)\n return { id, reactions: node.reactions }\n }\n})\n"],"mappings":";;;AAIA,MAAa,eAAe,WAAW;CACrC,MAAM;CAEN,aACE;CAIF,WAAW;EAAE,MAAM;EAAQ,UAAU;CAAO;CAC5C,OAAO,EAAE,aAAa,EACpB,IAAI,kBACN,CAAC;CACD,UAAU,OAAO,EAAE,SAAS;EAC1B,MAAM,OAAO,MAAM,YAAY,EAAE;EACjC,IAAI,CAAC,MAAM,OAAO,aAAa,EAAE;EACjC,OAAO;GAAE;GAAI,WAAW,KAAK;EAAU;CACzC;AACF,CAAC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"space.d.ts","names":[],"sources":["../../../src/tools/read/space.ts"],"mappings":";;;;
|
|
1
|
+
{"version":3,"file":"space.d.ts","names":[],"sources":["../../../src/tools/read/space.ts"],"mappings":";;;;cAUM;KACD,yBAAyB;;cAGjB;UAEI;;EAEf,oBAAoB;EACpB;EACA;;EAEA,QAAQ;EACR;EACA,qBAAqB;;UAGN,mBAAmB;EAClC,WAAW;;;iBAIG,aAAa,MAAM,MAAM,UAAU,MAAM;;;;;iBAsDzC,eAAe,SAAS,oBAAoB;;iBAe5C,WAAW,OAAO,YAAY,mBAAmB;;iBAUjD,mBACd,OAAO,YACP,kBACA;EAAQ;EAAe;GACvB,eACC;cAcU,oBAAA"}
|
package/dist/tools/read/space.js
CHANGED
|
@@ -1,5 +1,4 @@
|
|
|
1
1
|
import { findPageId } from "../../io/subgraph.js";
|
|
2
|
-
import { flushPendingLayout } from "../../figma-api/pending-layout.js";
|
|
3
2
|
import { defineTool, toolNumber } from "../schema.js";
|
|
4
3
|
import { getAxisAlignedBoundsInParent } from "@pairdraw/scene-graph/coordinate";
|
|
5
4
|
import { computeBounds } from "@pairdraw/scene-graph/geometry";
|
|
@@ -137,7 +136,6 @@ const findEmptySpaceTool = defineTool({
|
|
|
137
136
|
if (!parent || parent.type !== "CANVAS" && !findPageId(graph, parentId)) return { error: `Parent "${parentId}" not found` };
|
|
138
137
|
if (parent.layoutMode !== "NONE" && parent.type !== "CANVAS") return { error: `${parent.name} places its children with auto layout; append to it instead` };
|
|
139
138
|
if (args.near_id && nearParentId !== parentId) return { error: `Node "${args.near_id}" is not a child of "${parentId}"` };
|
|
140
|
-
flushPendingLayout(graph);
|
|
141
139
|
const obstacles = childBoxes(graph, parentId);
|
|
142
140
|
const near = args.near_id ? graph.getNode(args.near_id) : void 0;
|
|
143
141
|
let anchor = obstacles.length > 0 ? computeBounds(obstacles) : null;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"space.js","names":[],"sources":["../../../src/tools/read/space.ts"],"sourcesContent":["import * as v from 'valibot'\n\nimport type { SceneGraph } from '@pairdraw/scene-graph'\nimport { getAxisAlignedBoundsInParent } from '@pairdraw/scene-graph/coordinate'\nimport { computeBounds } from '@pairdraw/scene-graph/geometry'\nimport type { Rect } from '@pairdraw/scene-graph/primitives'\n\nimport { flushPendingLayout } from '#core/figma-api'\nimport { findPageId } from '#core/io/subgraph'\nimport { defineTool, toolNumber } from '#core/tools/schema'\n\nconst SPACE_DIRECTIONS = ['right', 'below', 'left', 'above'] as const\ntype SpaceDirection = (typeof SPACE_DIRECTIONS)[number]\n\n/** Room kept between a found space and the layers around it, as `import_mermaid` keeps. */\nexport const DEFAULT_SPACE_GAP = 100\n\nexport interface EmptySpaceRequest {\n /** What is already there, in the parent's coordinates. */\n obstacles: readonly Rect[]\n width: number\n height: number\n /** The region to stay close to; null when the parent is empty. */\n anchor: Rect | null\n gap: number\n directions: readonly SpaceDirection[]\n}\n\nexport interface EmptySpace extends Rect {\n direction: SpaceDirection | null\n}\n\n/** Whether `rect` comes within `gap` of `obstacle`, or covers part of it when `gap` is 0. */\nexport function rectsOverlap(rect: Rect, obstacle: Rect, gap: number): boolean {\n return (\n rect.x < obstacle.x + obstacle.width + gap &&\n rect.x + rect.width + gap > obstacle.x &&\n rect.y < obstacle.y + obstacle.height + gap &&\n rect.y + rect.height + gap > obstacle.y\n )\n}\n\n/**\n * The first free position going one way from the anchor, keeping the anchor's row or column.\n * Each candidate sits just past an obstacle's far edge, so the last one clears them all.\n */\nfunction spaceToward(request: EmptySpaceRequest, anchor: Rect, direction: SpaceDirection): Rect {\n const { obstacles, width, height, gap } = request\n const horizontal = direction === 'right' || direction === 'left'\n const forward = direction === 'right' || direction === 'below'\n const start = {\n right: anchor.x + anchor.width + gap,\n left: anchor.x - gap - width,\n below: anchor.y + anchor.height + gap,\n above: anchor.y - gap - height\n }[direction]\n const edges = obstacles.map((obstacle) => {\n if (direction === 'right') return obstacle.x + obstacle.width + gap\n if (direction === 'left') return obstacle.x - gap - width\n if (direction === 'below') return obstacle.y + obstacle.height + gap\n return obstacle.y - gap - height\n })\n const candidates = [start, ...edges.filter((edge) => (forward ? edge > start : edge < start))]\n candidates.sort((a, b) => (forward ? a - b : b - a))\n const place = (offset: number): Rect =>\n horizontal\n ? { x: offset, y: anchor.y, width, height }\n : { x: anchor.x, y: offset, width, height }\n for (const offset of candidates) {\n const rect = place(offset)\n if (!obstacles.some((obstacle) => rectsOverlap(rect, obstacle, gap))) return rect\n }\n // Unreachable: the farthest candidate clears every obstacle along this axis.\n return place(candidates[candidates.length - 1] ?? start)\n}\n\nfunction distance(anchor: Rect, rect: Rect, direction: SpaceDirection, gap: number): number {\n if (direction === 'right') return rect.x - (anchor.x + anchor.width + gap)\n if (direction === 'left') return anchor.x - gap - (rect.x + rect.width)\n if (direction === 'below') return rect.y - (anchor.y + anchor.height + gap)\n return anchor.y - gap - (rect.y + rect.height)\n}\n\n/**\n * A free region of `width` × `height` that keeps `gap` from every obstacle, as close to the\n * anchor as the directions allow; the first direction wins a tie.\n */\nexport function findEmptySpace(request: EmptySpaceRequest): EmptySpace {\n const { anchor, width, height, gap } = request\n if (!anchor) return { x: 0, y: 0, width, height, direction: null }\n let best: { rect: Rect; direction: SpaceDirection; distance: number } | null = null\n for (const direction of request.directions) {\n const rect = spaceToward(request, anchor, direction)\n const away = distance(anchor, rect, direction, gap)\n if (!best || away < best.distance) best = { rect, direction, distance: away }\n }\n return best\n ? { ...best.rect, direction: best.direction }\n : { ...spaceToward(request, anchor, 'right'), direction: 'right' }\n}\n\n/** Each child of `parentId` as an axis-aligned box in the parent's coordinates. */\nexport function childBoxes(graph: SceneGraph, parentId: string): Rect[] {\n const parent = graph.getNode(parentId)\n if (!parent) return []\n return parent.childIds.flatMap((id) => {\n const node = graph.getNode(id)\n return node ? [getAxisAlignedBoundsInParent([node], parentId, graph)] : []\n })\n}\n\n/** Where content of a size goes beside what `parentId` already holds. */\nexport function spaceBesideContent(\n graph: SceneGraph,\n parentId: string,\n size: { width: number; height: number },\n gap = DEFAULT_SPACE_GAP\n): EmptySpace {\n const obstacles = childBoxes(graph, parentId)\n return findEmptySpace({\n obstacles,\n ...size,\n anchor: obstacles.length > 0 ? computeBounds(obstacles) : null,\n gap,\n directions: ['right']\n })\n}\n\nconst sizeInput = (description: string) =>\n toolNumber(v.pipe(v.number(), v.minValue(0), v.description(description)))\n\nexport const findEmptySpaceTool = defineTool({\n name: 'find_empty_space',\n description:\n 'Find a free region of the canvas for new content of a given size, so it overlaps nothing. Without near_id it looks beside everything the parent holds; with near_id it looks next to that layer. direction \"any\" (default) takes the nearest free spot to the right, below, left, or above. Returns x and y in the parent’s coordinates, ready for render or create tools.',\n execution: { kind: 'sync', mutation: 'none' },\n input: v.strictObject({\n width: sizeInput('Width of the content to place'),\n height: sizeInput('Height of the content to place'),\n near_id: v.optional(\n v.pipe(v.string(), v.description('Layer to place the content next to (default: all content)'))\n ),\n parent_id: v.optional(\n v.pipe(v.string(), v.description('Parent to search (default: the current page)'))\n ),\n direction: v.optional(\n v.pipe(\n v.picklist(['any', ...SPACE_DIRECTIONS]),\n v.description('Which side of the anchor to search (default: any)')\n ),\n 'any'\n ),\n gap: v.optional(\n toolNumber(\n v.pipe(\n v.number(),\n v.minValue(0),\n v.description(`Room to keep around other layers (default: ${DEFAULT_SPACE_GAP})`)\n )\n ),\n DEFAULT_SPACE_GAP\n )\n }),\n execute: (figma, args) => {\n const graph = figma.graph\n const nearParentId = args.near_id ? graph.getNode(args.near_id)?.parentId : undefined\n if (args.near_id && !nearParentId) return { error: `Node \"${args.near_id}\" not found` }\n const parentId = args.parent_id ?? nearParentId ?? figma.currentPage.id\n const parent = graph.getNode(parentId)\n if (!parent || (parent.type !== 'CANVAS' && !findPageId(graph, parentId))) {\n return { error: `Parent \"${parentId}\" not found` }\n }\n if (parent.layoutMode !== 'NONE' && parent.type !== 'CANVAS') {\n return { error: `${parent.name} places its children with auto layout; append to it instead` }\n }\n if (args.near_id && nearParentId !== parentId) {\n return { error: `Node \"${args.near_id}\" is not a child of \"${parentId}\"` }\n }\n flushPendingLayout(graph)\n const obstacles = childBoxes(graph, parentId)\n const near = args.near_id ? graph.getNode(args.near_id) : undefined\n let anchor = obstacles.length > 0 ? computeBounds(obstacles) : null\n if (near) anchor = getAxisAlignedBoundsInParent([near], parentId, graph)\n const space = findEmptySpace({\n obstacles,\n width: args.width,\n height: args.height,\n anchor,\n gap: args.gap,\n directions: args.direction === 'any' ? SPACE_DIRECTIONS : [args.direction]\n })\n // Whole pixels, rounded away from what the space was found beside.\n const round = (value: number, away: SpaceDirection) =>\n space.direction === away ? Math.floor(value) : Math.ceil(value)\n return {\n parent_id: parentId,\n x: round(space.x, 'left'),\n y: round(space.y, 'above'),\n width: args.width,\n height: args.height,\n ...(space.direction ? { direction: space.direction } : {})\n }\n }\n})\n"],"mappings":";;;;;;;AAWA,MAAM,mBAAmB;CAAC;CAAS;CAAS;CAAQ;AAAO;;AAI3D,MAAa,oBAAoB;;AAkBjC,SAAgB,aAAa,MAAY,UAAgB,KAAsB;CAC7E,OACE,KAAK,IAAI,SAAS,IAAI,SAAS,QAAQ,OACvC,KAAK,IAAI,KAAK,QAAQ,MAAM,SAAS,KACrC,KAAK,IAAI,SAAS,IAAI,SAAS,SAAS,OACxC,KAAK,IAAI,KAAK,SAAS,MAAM,SAAS;AAE1C;;;;;AAMA,SAAS,YAAY,SAA4B,QAAc,WAAiC;CAC9F,MAAM,EAAE,WAAW,OAAO,QAAQ,QAAQ;CAC1C,MAAM,aAAa,cAAc,WAAW,cAAc;CAC1D,MAAM,UAAU,cAAc,WAAW,cAAc;CACvD,MAAM,QAAQ;EACZ,OAAO,OAAO,IAAI,OAAO,QAAQ;EACjC,MAAM,OAAO,IAAI,MAAM;EACvB,OAAO,OAAO,I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AO,KAAK;GACZ,QAAQ,KAAK;GACb;GACA,KAAK,KAAK;GACV,YAAY,KAAK,cAAc,QAAQ,mBAAmB,CAAC,KAAK,SAAS;EAC3E,CAAC;EAED,MAAM,SAAS,OAAe,SAC5B,MAAM,cAAc,OAAO,KAAK,MAAM,KAAK,IAAI,KAAK,KAAK,KAAK;EAChE,OAAO;GACL,WAAW;GACX,GAAG,MAAM,MAAM,GAAG,MAAM;GACxB,GAAG,MAAM,MAAM,GAAG,OAAO;GACzB,OAAO,KAAK;GACZ,QAAQ,KAAK;GACb,GAAI,MAAM,YAAY,EAAE,WAAW,MAAM,UAAU,IAAI,CAAC;EAC1D;CACF;AACF,CAAC"}
|
|
1
|
+
{"version":3,"file":"space.js","names":[],"sources":["../../../src/tools/read/space.ts"],"sourcesContent":["import * as v from 'valibot'\n\nimport type { SceneGraph } from '@pairdraw/scene-graph'\nimport { getAxisAlignedBoundsInParent } from '@pairdraw/scene-graph/coordinate'\nimport { computeBounds } from '@pairdraw/scene-graph/geometry'\nimport type { Rect } from '@pairdraw/scene-graph/primitives'\n\nimport { findPageId } from '#core/io/subgraph'\nimport { defineTool, toolNumber } from '#core/tools/schema'\n\nconst SPACE_DIRECTIONS = ['right', 'below', 'left', 'above'] as const\ntype SpaceDirection = (typeof SPACE_DIRECTIONS)[number]\n\n/** Room kept between a found space and the layers around it, as `import_mermaid` keeps. */\nexport const DEFAULT_SPACE_GAP = 100\n\nexport interface EmptySpaceRequest {\n /** What is already there, in the parent's coordinates. */\n obstacles: readonly Rect[]\n width: number\n height: number\n /** The region to stay close to; null when the parent is empty. */\n anchor: Rect | null\n gap: number\n directions: readonly SpaceDirection[]\n}\n\nexport interface EmptySpace extends Rect {\n direction: SpaceDirection | null\n}\n\n/** Whether `rect` comes within `gap` of `obstacle`, or covers part of it when `gap` is 0. */\nexport function rectsOverlap(rect: Rect, obstacle: Rect, gap: number): boolean {\n return (\n rect.x < obstacle.x + obstacle.width + gap &&\n rect.x + rect.width + gap > obstacle.x &&\n rect.y < obstacle.y + obstacle.height + gap &&\n rect.y + rect.height + gap > obstacle.y\n )\n}\n\n/**\n * The first free position going one way from the anchor, keeping the anchor's row or column.\n * Each candidate sits just past an obstacle's far edge, so the last one clears them all.\n */\nfunction spaceToward(request: EmptySpaceRequest, anchor: Rect, direction: SpaceDirection): Rect {\n const { obstacles, width, height, gap } = request\n const horizontal = direction === 'right' || direction === 'left'\n const forward = direction === 'right' || direction === 'below'\n const start = {\n right: anchor.x + anchor.width + gap,\n left: anchor.x - gap - width,\n below: anchor.y + anchor.height + gap,\n above: anchor.y - gap - height\n }[direction]\n const edges = obstacles.map((obstacle) => {\n if (direction === 'right') return obstacle.x + obstacle.width + gap\n if (direction === 'left') return obstacle.x - gap - width\n if (direction === 'below') return obstacle.y + obstacle.height + gap\n return obstacle.y - gap - height\n })\n const candidates = [start, ...edges.filter((edge) => (forward ? edge > start : edge < start))]\n candidates.sort((a, b) => (forward ? a - b : b - a))\n const place = (offset: number): Rect =>\n horizontal\n ? { x: offset, y: anchor.y, width, height }\n : { x: anchor.x, y: offset, width, height }\n for (const offset of candidates) {\n const rect = place(offset)\n if (!obstacles.some((obstacle) => rectsOverlap(rect, obstacle, gap))) return rect\n }\n // Unreachable: the farthest candidate clears every obstacle along this axis.\n return place(candidates[candidates.length - 1] ?? start)\n}\n\nfunction distance(anchor: Rect, rect: Rect, direction: SpaceDirection, gap: number): number {\n if (direction === 'right') return rect.x - (anchor.x + anchor.width + gap)\n if (direction === 'left') return anchor.x - gap - (rect.x + rect.width)\n if (direction === 'below') return rect.y - (anchor.y + anchor.height + gap)\n return anchor.y - gap - (rect.y + rect.height)\n}\n\n/**\n * A free region of `width` × `height` that keeps `gap` from every obstacle, as close to the\n * anchor as the directions allow; the first direction wins a tie.\n */\nexport function findEmptySpace(request: EmptySpaceRequest): EmptySpace {\n const { anchor, width, height, gap } = request\n if (!anchor) return { x: 0, y: 0, width, height, direction: null }\n let best: { rect: Rect; direction: SpaceDirection; distance: number } | null = null\n for (const direction of request.directions) {\n const rect = spaceToward(request, anchor, direction)\n const away = distance(anchor, rect, direction, gap)\n if (!best || away < best.distance) best = { rect, direction, distance: away }\n }\n return best\n ? { ...best.rect, direction: best.direction }\n : { ...spaceToward(request, anchor, 'right'), direction: 'right' }\n}\n\n/** Each child of `parentId` as an axis-aligned box in the parent's coordinates. */\nexport function childBoxes(graph: SceneGraph, parentId: string): Rect[] {\n const parent = graph.getNode(parentId)\n if (!parent) return []\n return parent.childIds.flatMap((id) => {\n const node = graph.getNode(id)\n return node ? [getAxisAlignedBoundsInParent([node], parentId, graph)] : []\n })\n}\n\n/** Where content of a size goes beside what `parentId` already holds. */\nexport function spaceBesideContent(\n graph: SceneGraph,\n parentId: string,\n size: { width: number; height: number },\n gap = DEFAULT_SPACE_GAP\n): EmptySpace {\n const obstacles = childBoxes(graph, parentId)\n return findEmptySpace({\n obstacles,\n ...size,\n anchor: obstacles.length > 0 ? computeBounds(obstacles) : null,\n gap,\n directions: ['right']\n })\n}\n\nconst sizeInput = (description: string) =>\n toolNumber(v.pipe(v.number(), v.minValue(0), v.description(description)))\n\nexport const findEmptySpaceTool = defineTool({\n name: 'find_empty_space',\n description:\n 'Find a free region of the canvas for new content of a given size, so it overlaps nothing. Without near_id it looks beside everything the parent holds; with near_id it looks next to that layer. direction \"any\" (default) takes the nearest free spot to the right, below, left, or above. Returns x and y in the parent’s coordinates, ready for render or create tools.',\n execution: { kind: 'sync', mutation: 'none' },\n input: v.strictObject({\n width: sizeInput('Width of the content to place'),\n height: sizeInput('Height of the content to place'),\n near_id: v.optional(\n v.pipe(v.string(), v.description('Layer to place the content next to (default: all content)'))\n ),\n parent_id: v.optional(\n v.pipe(v.string(), v.description('Parent to search (default: the current page)'))\n ),\n direction: v.optional(\n v.pipe(\n v.picklist(['any', ...SPACE_DIRECTIONS]),\n v.description('Which side of the anchor to search (default: any)')\n ),\n 'any'\n ),\n gap: v.optional(\n toolNumber(\n v.pipe(\n v.number(),\n v.minValue(0),\n v.description(`Room to keep around other layers (default: ${DEFAULT_SPACE_GAP})`)\n )\n ),\n DEFAULT_SPACE_GAP\n )\n }),\n execute: (figma, args) => {\n const graph = figma.graph\n const nearParentId = args.near_id ? graph.getNode(args.near_id)?.parentId : undefined\n if (args.near_id && !nearParentId) return { error: `Node \"${args.near_id}\" not found` }\n const parentId = args.parent_id ?? nearParentId ?? figma.currentPage.id\n const parent = graph.getNode(parentId)\n if (!parent || (parent.type !== 'CANVAS' && !findPageId(graph, parentId))) {\n return { error: `Parent \"${parentId}\" not found` }\n }\n if (parent.layoutMode !== 'NONE' && parent.type !== 'CANVAS') {\n return { error: `${parent.name} places its children with auto layout; append to it instead` }\n }\n if (args.near_id && nearParentId !== parentId) {\n return { error: `Node \"${args.near_id}\" is not a child of \"${parentId}\"` }\n }\n const obstacles = childBoxes(graph, parentId)\n const near = args.near_id ? graph.getNode(args.near_id) : undefined\n let anchor = obstacles.length > 0 ? computeBounds(obstacles) : null\n if (near) anchor = getAxisAlignedBoundsInParent([near], parentId, graph)\n const space = findEmptySpace({\n obstacles,\n width: args.width,\n height: args.height,\n anchor,\n gap: args.gap,\n directions: args.direction === 'any' ? SPACE_DIRECTIONS : [args.direction]\n })\n // Whole pixels, rounded away from what the space was found beside.\n const round = (value: number, away: SpaceDirection) =>\n space.direction === away ? Math.floor(value) : Math.ceil(value)\n return {\n parent_id: parentId,\n x: round(space.x, 'left'),\n y: round(space.y, 'above'),\n width: args.width,\n height: args.height,\n ...(space.direction ? { direction: space.direction } : {})\n }\n }\n})\n"],"mappings":";;;;;;AAUA,MAAM,mBAAmB;CAAC;CAAS;CAAS;CAAQ;AAAO;;AAI3D,MAAa,oBAAoB;;AAkBjC,SAAgB,aAAa,MAAY,UAAgB,KAAsB;CAC7E,OACE,KAAK,IAAI,SAAS,IAAI,SAAS,QAAQ,OACvC,KAAK,IAAI,KAAK,QAAQ,MAAM,SAAS,KACrC,KAAK,IAAI,SAAS,IAAI,SAAS,SAAS,OACxC,KAAK,I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BAAuB,SAAS,GAAG;EAE3E,MAAM,YAAY,WAAW,OAAO,QAAQ;EAC5C,MAAM,OAAO,KAAK,UAAU,MAAM,QAAQ,KAAK,OAAO,IAAI,KAAA;EAC1D,IAAI,SAAS,UAAU,SAAS,IAAI,cAAc,SAAS,IAAI;EAC/D,IAAI,MAAM,SAAS,6BAA6B,CAAC,IAAI,GAAG,UAAU,KAAK;EACvE,MAAM,QAAQ,eAAe;GAC3B;GACA,OAAO,KAAK;GACZ,QAAQ,KAAK;GACb;GACA,KAAK,KAAK;GACV,YAAY,KAAK,cAAc,QAAQ,mBAAmB,CAAC,KAAK,SAAS;EAC3E,CAAC;EAED,MAAM,SAAS,OAAe,SAC5B,MAAM,cAAc,OAAO,KAAK,MAAM,KAAK,IAAI,KAAK,KAAK,KAAK;EAChE,OAAO;GACL,WAAW;GACX,GAAG,MAAM,MAAM,GAAG,MAAM;GACxB,GAAG,MAAM,MAAM,GAAG,OAAO;GACzB,OAAO,KAAK;GACZ,QAAQ,KAAK;GACb,GAAI,MAAM,YAAY,EAAE,WAAW,MAAM,UAAU,IAAI,CAAC;EAC1D;CACF;AACF,CAAC"}
|
package/dist/tools/read.d.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { getComponents } from "./read/components.js";
|
|
2
|
+
import { getCSS } from "./read/css.js";
|
|
2
3
|
import { insertLibraryComponent, listLibraries } from "./read/libraries.js";
|
|
3
4
|
import { getFontStatus, listAvailableFonts, listFonts } from "./read/fonts.js";
|
|
4
5
|
import { diffJSX, getJSX } from "./read/jsx.js";
|
|
@@ -8,4 +9,4 @@ import { queryNodes } from "./read/query.js";
|
|
|
8
9
|
import { getReactions } from "./read/reactions.js";
|
|
9
10
|
import { getSelection, selectNodes } from "./read/selection.js";
|
|
10
11
|
import { findEmptySpaceTool } from "./read/space.js";
|
|
11
|
-
export { diffJSX, findEmptySpaceTool, findNodes, getComponents, getCurrentPage, getFontStatus, getJSX, getNode, getPageTree, getReactions, getSelection, insertLibraryComponent, listAvailableFonts, listFonts, listLibraries, listPages, pageBounds, queryNodes, selectNodes, switchPage };
|
|
12
|
+
export { diffJSX, findEmptySpaceTool, findNodes, getCSS, getComponents, getCurrentPage, getFontStatus, getJSX, getNode, getPageTree, getReactions, getSelection, insertLibraryComponent, listAvailableFonts, listFonts, listLibraries, listPages, pageBounds, queryNodes, selectNodes, switchPage };
|
package/dist/tools/read.js
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { findEmptySpaceTool } from "./read/space.js";
|
|
2
2
|
import { getComponents } from "./read/components.js";
|
|
3
|
+
import { getCSS } from "./read/css.js";
|
|
3
4
|
import { insertLibraryComponent, listLibraries } from "./read/libraries.js";
|
|
4
5
|
import { getFontStatus, listAvailableFonts, listFonts } from "./read/fonts.js";
|
|
5
6
|
import { diffJSX, getJSX } from "./read/jsx.js";
|
|
@@ -8,4 +9,4 @@ import { getCurrentPage, listPages, pageBounds, switchPage } from "./read/pages.
|
|
|
8
9
|
import { queryNodes } from "./read/query.js";
|
|
9
10
|
import { getReactions } from "./read/reactions.js";
|
|
10
11
|
import { getSelection, selectNodes } from "./read/selection.js";
|
|
11
|
-
export { diffJSX, findEmptySpaceTool, findNodes, getComponents, getCurrentPage, getFontStatus, getJSX, getNode, getPageTree, getReactions, getSelection, insertLibraryComponent, listAvailableFonts, listFonts, listLibraries, listPages, pageBounds, queryNodes, selectNodes, switchPage };
|
|
12
|
+
export { diffJSX, findEmptySpaceTool, findNodes, getCSS, getComponents, getCurrentPage, getFontStatus, getJSX, getNode, getPageTree, getReactions, getSelection, insertLibraryComponent, listAvailableFonts, listFonts, listLibraries, listPages, pageBounds, queryNodes, selectNodes, switchPage };
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { ToolDef } from "../schema.js";
|
|
2
2
|
//#region src/tools/registry/core.d.ts
|
|
3
3
|
/**
|
|
4
|
-
* Core tools registered by default in AI chat (
|
|
4
|
+
* Core tools registered by default in AI chat (28 tools, ~5K schema tokens).
|
|
5
5
|
* Covers 90%+ of design sessions: render, describe, modify, structure, and diff checks.
|
|
6
6
|
*/
|
|
7
7
|
declare const CORE_TOOLS: ToolDef[];
|
|
@@ -11,6 +11,7 @@ import { setLayout, setLayoutChild } from "../modify/layout.js";
|
|
|
11
11
|
import { setText, setTextProperties } from "../modify/text.js";
|
|
12
12
|
import { setFill, setStroke } from "../modify/paint.js";
|
|
13
13
|
import { updateNode } from "../modify/update.js";
|
|
14
|
+
import { getCSS } from "../read/css.js";
|
|
14
15
|
import { diffJSX, getJSX } from "../read/jsx.js";
|
|
15
16
|
import { findNodes, getNode } from "../read/nodes.js";
|
|
16
17
|
import { getSelection } from "../read/selection.js";
|
|
@@ -21,7 +22,7 @@ import { batchUpdate } from "../structure/batch.js";
|
|
|
21
22
|
import { viewportZoomToFit } from "../vector/viewport.js";
|
|
22
23
|
//#region src/tools/registry/core.ts
|
|
23
24
|
/**
|
|
24
|
-
* Core tools registered by default in AI chat (
|
|
25
|
+
* Core tools registered by default in AI chat (28 tools, ~5K schema tokens).
|
|
25
26
|
* Covers 90%+ of design sessions: render, describe, modify, structure, and diff checks.
|
|
26
27
|
*/
|
|
27
28
|
const CORE_TOOLS = [
|
|
@@ -29,6 +30,7 @@ const CORE_TOOLS = [
|
|
|
29
30
|
getNode,
|
|
30
31
|
findNodes,
|
|
31
32
|
getJSX,
|
|
33
|
+
getCSS,
|
|
32
34
|
render,
|
|
33
35
|
updateNode,
|
|
34
36
|
setLayout,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"core.js","names":[],"sources":["../../../src/tools/registry/core.ts"],"sourcesContent":["import { diffChanges, diffCreate, diffVisual, evalCode } from '#core/tools/analyze'\nimport { checkResponsive } from '#core/tools/analyze/responsive'\nimport { calc } from '#core/tools/calc'\nimport { render } from '#core/tools/create'\nimport { describe } from '#core/tools/describe'\nimport {\n setFill,\n setLayout,\n setLayoutChild,\n setRadius,\n setStroke,\n setText,\n setTextProperties,\n updateNode\n} from '#core/tools/modify'\nimport { diffJSX, findNodes, getJSX, getNode, getSelection } from '#core/tools/read'\nimport type { ToolDef } from '#core/tools/schema'\nimport { stockPhoto } from '#core/tools/stock-photo'\nimport { batchUpdate, deleteNode, nodeResize, reparentNode } from '#core/tools/structure'\nimport { viewportZoomToFit } from '#core/tools/vector'\n\n/**\n * Core tools registered by default in AI chat (
|
|
1
|
+
{"version":3,"file":"core.js","names":[],"sources":["../../../src/tools/registry/core.ts"],"sourcesContent":["import { diffChanges, diffCreate, diffVisual, evalCode } from '#core/tools/analyze'\nimport { checkResponsive } from '#core/tools/analyze/responsive'\nimport { calc } from '#core/tools/calc'\nimport { render } from '#core/tools/create'\nimport { describe } from '#core/tools/describe'\nimport {\n setFill,\n setLayout,\n setLayoutChild,\n setRadius,\n setStroke,\n setText,\n setTextProperties,\n updateNode\n} from '#core/tools/modify'\nimport { diffJSX, findNodes, getCSS, getJSX, getNode, getSelection } from '#core/tools/read'\nimport type { ToolDef } from '#core/tools/schema'\nimport { stockPhoto } from '#core/tools/stock-photo'\nimport { batchUpdate, deleteNode, nodeResize, reparentNode } from '#core/tools/structure'\nimport { viewportZoomToFit } from '#core/tools/vector'\n\n/**\n * Core tools registered by default in AI chat (28 tools, ~5K schema tokens).\n * Covers 90%+ of design sessions: render, describe, modify, structure, and diff checks.\n */\nexport const CORE_TOOLS: ToolDef[] = [\n // Read\n getSelection,\n getNode,\n findNodes,\n getJSX,\n getCSS,\n // Create\n render,\n // Modify\n updateNode,\n setLayout,\n setLayoutChild,\n setRadius,\n setFill,\n setStroke,\n setText,\n setTextProperties,\n // Structure\n deleteNode,\n reparentNode,\n nodeResize,\n batchUpdate,\n // Stock photos\n stockPhoto,\n // Inspect & utility\n describe,\n diffChanges,\n diffCreate,\n diffJSX,\n diffVisual,\n checkResponsive,\n calc,\n evalCode,\n viewportZoomToFit\n]\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;AAyBA,MAAa,aAAwB;CAEnC;CACA;CACA;CACA;CACA;CAEA;CAEA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CAEA;CACA;CACA;CACA;CAEA;CAEA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF"}
|
package/dist/tools/schema.d.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { FigmaFontNameInput } from "../figma-api/fonts/names.js";
|
|
2
2
|
import { FigmaNodeProxy } from "../figma-api/proxy.js";
|
|
3
3
|
import { FigmaAPI } from "../figma-api/index.js";
|
|
4
|
-
import { SceneNode } from "@pairdraw/scene-graph";
|
|
4
|
+
import { DocumentColorSpace, SceneNode } from "@pairdraw/scene-graph";
|
|
5
5
|
import * as v from "valibot";
|
|
6
6
|
import { Color } from "@pairdraw/scene-graph/primitives";
|
|
7
7
|
//#region src/tools/schema.d.ts
|
|
@@ -107,14 +107,14 @@ declare function nodeSummary(node: FigmaNodeProxy): {
|
|
|
107
107
|
* used to paint black and report success. Read through `tryParseColor`, since a published schema
|
|
108
108
|
* cannot express what the parser accepts.
|
|
109
109
|
*/
|
|
110
|
-
declare function parseToolColor(value: string): Color | {
|
|
110
|
+
declare function parseToolColor(value: string, profile?: DocumentColorSpace): Color | {
|
|
111
111
|
error: string;
|
|
112
112
|
};
|
|
113
113
|
/**
|
|
114
114
|
* A colour the caller may leave out. Missing stays missing; text that is not a colour is the
|
|
115
115
|
* same refusal `parseToolColor` gives, so each tool does not repeat that check.
|
|
116
116
|
*/
|
|
117
|
-
declare function parseOptionalToolColor(value: string | undefined): {
|
|
117
|
+
declare function parseOptionalToolColor(value: string | undefined, profile?: DocumentColorSpace): {
|
|
118
118
|
color: Color | undefined;
|
|
119
119
|
} | {
|
|
120
120
|
error: string;
|
|
@@ -137,6 +137,8 @@ declare const positionInputs: {
|
|
|
137
137
|
};
|
|
138
138
|
/** Reuse a native number schema for both numeric and numeric-string agent inputs. */
|
|
139
139
|
declare function toolNumber(schema?: v.GenericSchema<number, number>): v.UnionSchema<[v.SchemaWithPipe<readonly [v.GenericSchema<number, number>, v.MinValueAction<number, number, undefined>, v.MaxValueAction<number, number, undefined>]>, v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.RegexAction<string, "Expected a nonblank numeric string">, v.DescriptionAction<string, string>, v.TransformAction<any, number>, v.SchemaWithPipe<readonly [v.GenericSchema<number, number>, v.MinValueAction<number, number, undefined>, v.MaxValueAction<number, number, undefined>]>]>], undefined>;
|
|
140
|
+
/** `ids`: several node IDs in one call; the description names what they point at. */
|
|
141
|
+
declare function nodeIdsField(description: string): v.OptionalSchema<v.SchemaWithPipe<readonly [v.ArraySchema<v.StringSchema<undefined>, undefined>, v.MinLengthAction<string[], 1, undefined>, v.DescriptionAction<string[], string>]>, undefined>;
|
|
140
142
|
//#endregion
|
|
141
|
-
export { NodeNotFoundError, ToolCapability, ToolDef, ToolExecution, ToolExposure, ToolInterface, defineTool, getRawNodeOrError, isAtomicTool, isToolExposed, nodeComparisonInputSchema, nodeIdInputSchema, nodeInputSchema, nodeNotFound, nodeSummary, nodeToResult, nodeTraversalInput, parseOptionalToolColor, parseToolArgs, parseToolColor, positionInputs, requireNode, requireNodes, toolChangesDocument, toolFailure, toolNumber };
|
|
143
|
+
export { NodeNotFoundError, ToolCapability, ToolDef, ToolExecution, ToolExposure, ToolInterface, defineTool, getRawNodeOrError, isAtomicTool, isToolExposed, nodeComparisonInputSchema, nodeIdInputSchema, nodeIdsField, nodeInputSchema, nodeNotFound, nodeSummary, nodeToResult, nodeTraversalInput, parseOptionalToolColor, parseToolArgs, parseToolColor, positionInputs, requireNode, requireNodes, toolChangesDocument, toolFailure, toolNumber };
|
|
142
144
|
//# sourceMappingURL=schema.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"schema.d.ts","names":[],"sources":["../../src/tools/schema.ts"],"mappings":";;;;;;;KAgBY;KAUA;EACN;EAAc;;EAEd;EACA;;;;;EAKA;;KAGM;KACA,eAAe,QAAQ,OAAO;UAEhC;EACR;EAC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;;;cAM9C;;;;;iBAMG,WAAW,SAAQ,EAAE,gCAA0C,EAAA,aAAA,EAAA,yBAAA,EAAA,+BAAA,EAAA,2CAAA,EAAA,6CAAA,EAAA,yBAAA,EAAA,yBAAA,EAAA,2DAAA,EAAA,mCAAA,EAAA,8BAAA,EAAA,yBAAA,EAAA,+BAAA,EAAA,2CAAA,EAAA;;iBAgB/D,aAAa,sBAAmB,EAAA,eAAA,EAAA,yBAAA,EAAA,YAAA,EAAA,qCAAA,EAAA,yCAAA,EAAA"}
|
package/dist/tools/schema.js
CHANGED
|
@@ -191,16 +191,16 @@ function nodeSummary(node) {
|
|
|
191
191
|
* used to paint black and report success. Read through `tryParseColor`, since a published schema
|
|
192
192
|
* cannot express what the parser accepts.
|
|
193
193
|
*/
|
|
194
|
-
function parseToolColor(value) {
|
|
195
|
-
return tryParseColor(value) ?? { error: `"${value}" is not a color; use a hex value, a color name, or a color function` };
|
|
194
|
+
function parseToolColor(value, profile = "srgb") {
|
|
195
|
+
return tryParseColor(value, profile) ?? { error: `"${value}" is not a color; use a hex value, a color name, or a color function` };
|
|
196
196
|
}
|
|
197
197
|
/**
|
|
198
198
|
* A colour the caller may leave out. Missing stays missing; text that is not a colour is the
|
|
199
199
|
* same refusal `parseToolColor` gives, so each tool does not repeat that check.
|
|
200
200
|
*/
|
|
201
|
-
function parseOptionalToolColor(value) {
|
|
201
|
+
function parseOptionalToolColor(value, profile = "srgb") {
|
|
202
202
|
if (value === void 0) return { color: void 0 };
|
|
203
|
-
const parsed = parseToolColor(value);
|
|
203
|
+
const parsed = parseToolColor(value, profile);
|
|
204
204
|
if ("error" in parsed) return parsed;
|
|
205
205
|
return { color: parsed };
|
|
206
206
|
}
|
|
@@ -225,7 +225,11 @@ function toolNumber(schema = v.number()) {
|
|
|
225
225
|
const finite = v.pipe(schema, v.minValue(-Number.MAX_VALUE), v.maxValue(Number.MAX_VALUE));
|
|
226
226
|
return v.union([finite, v.pipe(v.string(), v.regex(/\S/, "Expected a nonblank numeric string"), v.description(v.getDescription(schema) ?? "Numeric value"), v.transform(Number), finite)]);
|
|
227
227
|
}
|
|
228
|
+
/** `ids`: several node IDs in one call; the description names what they point at. */
|
|
229
|
+
function nodeIdsField(description) {
|
|
230
|
+
return v.optional(v.pipe(v.array(v.string()), v.minLength(1), v.description(description)));
|
|
231
|
+
}
|
|
228
232
|
//#endregion
|
|
229
|
-
export { NodeNotFoundError, defineTool, getRawNodeOrError, isAtomicTool, isToolExposed, nodeComparisonInputSchema, nodeIdInputSchema, nodeInputSchema, nodeNotFound, nodeSummary, nodeToResult, nodeTraversalInput, parseOptionalToolColor, parseToolArgs, parseToolColor, positionInputs, requireNode, requireNodes, toolChangesDocument, toolFailure, toolNumber };
|
|
233
|
+
export { NodeNotFoundError, defineTool, getRawNodeOrError, isAtomicTool, isToolExposed, nodeComparisonInputSchema, nodeIdInputSchema, nodeIdsField, nodeInputSchema, nodeNotFound, nodeSummary, nodeToResult, nodeTraversalInput, parseOptionalToolColor, parseToolArgs, parseToolColor, positionInputs, requireNode, requireNodes, toolChangesDocument, toolFailure, toolNumber };
|
|
230
234
|
|
|
231
235
|
//# sourceMappingURL=schema.js.map
|
package/dist/tools/schema.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"schema.js","names":[],"sources":["../../src/tools/schema.ts"],"sourcesContent":["/**\n * Tool definition schema.\n *\n * Native Valibot inputs and execution capabilities are owned by each tool.\n * Adapters consume these contracts rather than maintaining transport-specific schemas.\n */\n\nimport * as v from 'valibot'\n\nimport type { SceneNode } from '@pairdraw/scene-graph'\nimport { tryParseColor } from '@pairdraw/scene-graph/color'\nimport type { Color } from '@pairdraw/scene-graph/primitives'\n\nimport type { FigmaAPI, FigmaNodeProxy } from '#core/figma-api'\nimport type { FigmaFontNameInput } from '#core/figma-api/fonts/names'\n\nexport type ToolCapability =\n | 'document:read'\n | 'document:write'\n | 'filesystem:read'\n | 'filesystem:write'\n | 'network:access'\n | 'code:execute'\n | 'settings:read'\n | 'settings:write'\n\nexport type ToolExecution =\n | { kind: 'sync'; mutation: 'none' | 'view' | 'properties' | 'document' }\n | {\n kind: 'async'\n mutation: 'none' | 'view' | 'document'\n /**\n * The call can run for a long time even when it only reads, such as recording a video, so\n * bridges give it the deadline they give an edit.\n */\n long?: boolean\n }\n\nexport type ToolInterface = 'mcp' | 'ai' | 'webmcp'\nexport type ToolExposure = Partial<Record<ToolInterface, boolean>>\n\ninterface ToolMetadata {\n name: string\n description: string\n execution: ToolExecution\n /** Interface inclusion defaults to true; execution support and user permissions remain separate. */\n exposure: ToolExposure\n capabilities: readonly ToolCapability[]\n availability: 'default' | 'eval'\n /**\n * What a call's values come from, for the document's design memory:\n * - `imported`: outside content, such as a web page, an SVG, a photo or a library component,\n * whose colors and type are its own, so the memory warns about them rather than refusing;\n * - `copied`: the layers the call names, which it copies or converts with their values, such\n * as a clone, a group or a boolean, so values those layers already had are not new.\n * - `merged`: layers the call joins into one, which may take a paint from any of them, such as\n * flatten and boolean operations; a value is only theirs when every named layer had it.\n */\n content?: 'imported' | 'copied' | 'merged'\n}\n\nexport interface ToolDef extends ToolMetadata {\n input: v.StrictObjectSchema<v.ObjectEntries, undefined>\n /** Derived from execution metadata, never declared independently by a tool. */\n readonly mutates: boolean\n /**\n * Loads the fonts the call's text edits need, as a Figma plugin loads them before it edits\n * text; rejects when one cannot load. Every executor awaits it before `execute`, so a\n * synchronous tool still edits in one step.\n */\n loadFonts: (figma: FigmaAPI, args: Record<string, unknown>) => Promise<void>\n /** `signal` aborts a caller's cancelled request, which a long export checks while it runs. */\n execute: (figma: FigmaAPI, args: Record<string, unknown>, signal?: AbortSignal) => unknown\n /**\n * The synchronous answer of a read whose `execute` may load a page first, or `undefined`\n * when answering would load. Hosts that cannot wait refuse on `undefined` before any load.\n */\n executeSync?: (figma: FigmaAPI, args: Record<string, unknown>) => unknown\n}\n\ntype ToolDefinitionMetadata = Omit<ToolMetadata, 'exposure' | 'capabilities' | 'availability'> &\n Partial<Pick<ToolMetadata, 'exposure' | 'capabilities' | 'availability'>>\n\nexport function defineTool<P extends v.ObjectEntries, R>(\n def: ToolDefinitionMetadata & {\n input: v.StrictObjectSchema<P, undefined>\n execution: ToolExecution & (R extends PromiseLike<unknown> ? { kind: 'async' } : unknown)\n /** The fonts a call's text edits need loaded first; text edits refuse unloaded fonts. */\n fonts?: (\n figma: FigmaAPI,\n args: v.InferOutput<v.StrictObjectSchema<P, undefined>>\n ) => FigmaFontNameInput[]\n execute: (\n figma: FigmaAPI,\n args: v.InferOutput<v.StrictObjectSchema<P, undefined>>,\n signal?: AbortSignal\n ) => R\n executeSync?: (\n figma: FigmaAPI,\n args: v.InferOutput<v.StrictObjectSchema<P, undefined>>\n ) => unknown\n }\n): ToolDef {\n const { fonts } = def\n return {\n ...def,\n exposure: def.exposure ?? {},\n capabilities: def.capabilities ?? [\n toolChangesDocument(def) ? 'document:write' : 'document:read'\n ],\n availability: def.availability ?? 'default',\n get mutates() {\n return def.execution.mutation !== 'none'\n },\n async loadFonts(figma, args) {\n if (!fonts) return\n // Wrong arguments are for `execute` to report.\n const parsed = v.safeParse(def.input, args)\n if (!parsed.success) return\n for (const font of fonts(figma, parsed.output)) await figma.loadFontAsync(font)\n },\n execute: (figma, args, signal) =>\n def.execute(figma, parseToolArgs(def.name, def.input, args), signal),\n executeSync: def.executeSync\n ? (figma, args) => def.executeSync?.(figma, parseToolArgs(def.name, def.input, args))\n : undefined\n }\n}\n\n/**\n * Every tool run goes through here, so a wrong call from AI chat, the CLI, WebMCP, and MCP names\n * the tool and lists each problem with its argument. An unknown or missing argument names the\n * arguments the tool takes, and a picklist names the values it accepts, read from the schema, so\n * the caller does not have to guess. Inputs are strict objects, so a misspelled or mis-nested\n * argument fails here instead of being dropped.\n */\nexport function parseToolArgs<S extends v.GenericSchema>(\n name: string,\n schema: S,\n args: unknown\n): v.InferOutput<S> {\n const result = v.safeParse(schema, args)\n if (result.success) return result.output\n throw new Error(formatToolArgumentError(name, schema, result.issues))\n}\n\n/** One refusal for every surface: the tool, then each problem with where it is. */\nfunction formatToolArgumentError(\n name: string,\n schema: v.GenericSchema,\n issues: readonly v.BaseIssue<unknown>[]\n): string {\n const problems = issues\n .flatMap((issue) => branchIssues(schema, issue))\n .map(({ keys, issue }) => {\n const place = keys.length > 0 ? `\\n → at ${placeOf(keys)}` : ''\n return `× ${formatToolArgIssue(schema, keys, issue)}${place}`\n })\n return `Invalid arguments for ${name}:\\n${problems.join('\\n')}`\n}\n\n/** The parts of a Valibot schema this module reads to name what a call should have sent. */\ntype SchemaParts = {\n readonly entries?: v.ObjectEntries\n readonly item?: v.GenericSchema\n readonly wrapped?: v.GenericSchema\n readonly options?: readonly unknown[]\n}\n\nfunction schemaParts(schema: unknown): SchemaParts {\n return typeof schema === 'object' && schema !== null ? schema : {}\n}\n\n/** The schema a wrapper such as `optional` or `pipe` holds, down to the one with the rules. */\nfunction unwrappedSchema(schema: v.GenericSchema): v.GenericSchema {\n let current = schema\n for (;;) {\n const wrapped = schemaParts(current).wrapped\n if (!wrapped) return current\n current = wrapped\n }\n}\n\ntype ArgumentKey = string | number\n\nfunction issueKeys(issue: v.BaseIssue<unknown>): ArgumentKey[] {\n const keys: ArgumentKey[] = []\n for (const item of issue.path ?? []) {\n if (!('key' in item)) continue\n if (typeof item.key === 'string' || typeof item.key === 'number') keys.push(item.key)\n }\n return keys\n}\n\n/** `operations[0].props`: an index reads as part of its array, a name follows a dot. */\nfunction placeOf(keys: readonly ArgumentKey[]): string {\n return keys.reduce<string>((place, key) => {\n if (typeof key === 'number') return `${place}[${key}]`\n return place ? `${place}.${key}` : key\n }, '')\n}\n\n/**\n * `v.union` reports one issue for every branch, which reads as \"Expected Object but received\n * Object\". Re-check the value against each branch and keep the one that got furthest: the branch\n * whose own problems name the field the caller has to fix.\n */\nfunction branchIssues(\n schema: v.GenericSchema,\n issue: v.BaseIssue<unknown>\n): { keys: ArgumentKey[]; issue: v.BaseIssue<unknown> }[] {\n const keys = issueKeys(issue)\n if (issue.type !== 'union') return [{ keys, issue }]\n const union = schemaAtPath(schema, keys)\n const options = union ? schemaParts(union).options : undefined\n if (!options || options.length === 0) return [{ keys, issue }]\n let best: readonly v.BaseIssue<unknown>[] | null = null\n for (const option of options) {\n const parsed = v.safeParse(option as v.GenericSchema, issue.input)\n if (parsed.success) continue\n if (!best || parsed.issues.length < best.length) best = parsed.issues\n }\n if (!best || best.length === 0) return [{ keys, issue }]\n return best.map((nested) => ({ keys: [...keys, ...issueKeys(nested)], issue: nested }))\n}\n\nfunction schemaAtPath(root: v.GenericSchema, keys: readonly ArgumentKey[]): v.GenericSchema | null {\n let current = unwrappedSchema(root)\n for (const key of keys) {\n const parts = schemaParts(current)\n const name = String(key)\n const next = parts.entries && name in parts.entries ? parts.entries[name] : parts.item\n if (!next) return null\n current = unwrappedSchema(next)\n }\n return current\n}\n\nfunction formatToolArgIssue(\n schema: v.GenericSchema,\n keys: readonly ArgumentKey[],\n issue: v.BaseIssue<unknown>\n): string {\n const key = keys.at(-1)\n if (key !== undefined && (issue.type === 'object' || issue.type === 'strict_object')) {\n if (issue.expected === 'never') {\n const parent = schemaAtPath(schema, keys.slice(0, -1))\n const accepted = parent ? Object.keys(schemaParts(parent).entries ?? {}) : []\n return accepted.length > 0\n ? `Unknown argument \"${key}\". Accepted: ${accepted.join(', ')}`\n : `Unknown argument \"${key}\"`\n }\n if (issue.received === 'undefined') return `Missing required argument \"${key}\"`\n }\n if (issue.type === 'picklist' && key !== undefined) {\n const resolved = schemaAtPath(schema, keys)\n const options = resolved ? schemaParts(resolved).options : undefined\n if (options && options.length > 0) {\n const accepted = options.map((option) => JSON.stringify(option)).join(', ')\n return `Invalid value ${issue.received} for argument \"${key}\". Accepted: ${accepted}`\n }\n }\n return issue.message\n}\n\nexport function toolChangesDocument(def: Pick<ToolDef, 'execution'>): boolean {\n return def.execution.mutation === 'properties' || def.execution.mutation === 'document'\n}\n\nexport function isToolExposed(def: Pick<ToolDef, 'exposure'>, target: ToolInterface): boolean {\n return def.exposure[target] !== false\n}\n\nexport function isAtomicTool(def: ToolDef): boolean {\n return def.execution.kind === 'sync' && def.execution.mutation === 'properties'\n}\n\nexport class NodeNotFoundError extends Error {\n constructor(id: string) {\n super(`Node not found: ${id}`)\n this.name = 'NodeNotFoundError'\n }\n}\n\nexport function requireNode(figma: FigmaAPI, id: string): ReturnType<FigmaAPI['getNodeById']> {\n const node = figma.getNodeById(id)\n if (!node) throw new NodeNotFoundError(id)\n return node\n}\n\nexport function requireNodes(figma: FigmaAPI, ids: ReadonlyArray<string>): FigmaNodeProxy[] | null {\n const nodes: FigmaNodeProxy[] = []\n for (const id of ids) {\n const node = figma.getNodeById(id)\n if (!node) return null\n nodes.push(node)\n }\n return nodes\n}\n\n/** A tool's answer when the operation it wraps throws: the error's message for the caller. */\nexport function toolFailure(error: unknown): { error: string } {\n return { error: error instanceof Error ? error.message : String(error) }\n}\n\nexport function nodeNotFound(id: string): { error: string } {\n return { error: `Node \"${id}\" not found` }\n}\n\nexport function getRawNodeOrError(\n figma: FigmaAPI,\n id: string\n): { node: SceneNode } | { error: string } {\n const node = figma.graph.getNode(id)\n return node ? { node } : nodeNotFound(id)\n}\n\nexport function nodeToResult(node: FigmaNodeProxy, maxDepth?: number): Record<string, unknown> {\n return node.toJSON(maxDepth)\n}\n\nexport function nodeSummary(node: FigmaNodeProxy): { id: string; name: string; type: string } {\n return { id: node.id, name: node.name, type: node.type }\n}\n\n/**\n * A tool colour, refusing text that would otherwise land as black: `set_fill { color: \"#GGG\" }`\n * used to paint black and report success. Read through `tryParseColor`, since a published schema\n * cannot express what the parser accepts.\n */\nexport function parseToolColor(value: string): Color | { error: string } {\n return (\n tryParseColor(value) ?? {\n error: `\"${value}\" is not a color; use a hex value, a color name, or a color function`\n }\n )\n}\n\n/**\n * A colour the caller may leave out. Missing stays missing; text that is not a colour is the\n * same refusal `parseToolColor` gives, so each tool does not repeat that check.\n */\nexport function parseOptionalToolColor(\n value: string | undefined\n): { color: Color | undefined } | { error: string } {\n if (value === undefined) return { color: undefined }\n const parsed = parseToolColor(value)\n if ('error' in parsed) return parsed\n return { color: parsed }\n}\n\nexport const nodeIdInputSchema = v.pipe(v.string(), v.description('Node ID'))\nexport const nodeInputSchema = v.strictObject({ id: nodeIdInputSchema })\nexport const nodeComparisonInputSchema = v.strictObject({\n from: v.pipe(v.string(), v.description('Source node ID')),\n to: v.pipe(v.string(), v.description('Target node ID'))\n})\n\nexport function nodeTraversalInput(depthDescription: string) {\n return v.strictObject({\n id: nodeIdInputSchema,\n depth: v.optional(toolNumber(v.pipe(v.number(), v.description(depthDescription))))\n })\n}\nexport const positionInputs = {\n x: toolNumber(v.pipe(v.number(), v.description('X position in the parent, or on the page'))),\n y: toolNumber(v.pipe(v.number(), v.description('Y position in the parent, or on the page')))\n}\n\n/** Reuse a native number schema for both numeric and numeric-string agent inputs. */\nexport function toolNumber(schema: v.GenericSchema<number, number> = v.number()) {\n // JSON Schema numbers are finite. Express that with representable bounds as well as at runtime.\n const finite = v.pipe(schema, v.minValue(-Number.MAX_VALUE), v.maxValue(Number.MAX_VALUE))\n return v.union([\n finite,\n v.pipe(\n v.string(),\n v.regex(/\\S/, 'Expected a nonblank numeric string'),\n v.description(v.getDescription(schema) ?? 'Numeric value'),\n v.transform(Number),\n finite\n )\n ])\n}\n"],"mappings":";;;;;;;;;AAmFA,SAAgB,WACd,KAkBS;CACT,MAAM,EAAE,UAAU;CAClB,OAAO;EACL,GAAG;EACH,UAAU,IAAI,YAAY,CAAC;EAC3B,cAAc,IAAI,gBAAgB,CAChC,oBAAoB,GAAG,IAAI,mBAAmB,eAChD;EACA,cAAc,IAAI,gBAAgB;EAClC,IAAI,UAAU;GACZ,OAAO,IAAI,UAAU,aAAa;EACpC;EACA,MAAM,UAAU,OAAO,MAAM;GAC3B,IAAI,CAAC,OAAO;GAEZ,MAAM,SAAS,EAAE,UAAU,IAAI,OAAO,IAAI;GAC1C,IAAI,CAAC,OAAO,SAAS;GACrB,KAAK,MA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4BAA4B,EAAE,aAAa;CACtD,MAAM,EAAE,KAAK,EAAE,OAAO,GAAG,EAAE,YAAY,gBAAgB,CAAC;CACxD,IAAI,EAAE,KAAK,EAAE,OAAO,GAAG,EAAE,YAAY,gBAAgB,CAAC;AACxD,CAAC;AAED,SAAgB,mBAAmB,kBAA0B;CAC3D,OAAO,EAAE,aAAa;EACpB,IAAI;EACJ,OAAO,EAAE,SAAS,WAAW,EAAE,KAAK,EAAE,OAAO,GAAG,EAAE,YAAY,gBAAgB,CAAC,CAAC,CAAC;CACnF,CAAC;AACH;AACA,MAAa,iBAAiB;CAC5B,GAAG,WAAW,EAAE,KAAK,EAAE,OAAO,GAAG,EAAE,YAAY,0CAA0C,CAAC,CAAC;CAC3F,GAAG,WAAW,EAAE,KAAK,EAAE,OAAO,GAAG,EAAE,YAAY,0CAA0C,CAAC,CAAC;AAC7F;;AAGA,SAAgB,WAAW,SAA0C,EAAE,OAAO,GAAG;CAE/E,MAAM,SAAS,EAAE,KAAK,QAAQ,EAAE,SAAS,CAAC,OAAO,SAAS,GAAG,EAAE,SAAS,OAAO,SAAS,CAAC;CACzF,OAAO,EAAE,MAAM,CACb,QACA,EAAE,KACA,EAAE,OAAO,GACT,EAAE,MAAM,MAAM,oCAAoC,GAClD,EAAE,YAAY,EAAE,eAAe,MAAM,KAAK,eAAe,GACzD,EAAE,UAAU,MAAM,GAClB,MACF,CACF,CAAC;AACH"}
|
|
1
|
+
{"version":3,"file":"schema.js","names":[],"sources":["../../src/tools/schema.ts"],"sourcesContent":["/**\n * Tool definition schema.\n *\n * Native Valibot inputs and execution capabilities are owned by each tool.\n * Adapters consume these contracts rather than maintaining transport-specific schemas.\n */\n\nimport * as v from 'valibot'\n\nimport type { DocumentColorSpace, SceneNode } from '@pairdraw/scene-graph'\nimport { tryParseColor } from '@pairdraw/scene-graph/color'\nimport type { Color } from '@pairdraw/scene-graph/primitives'\n\nimport type { FigmaAPI, FigmaNodeProxy } from '#core/figma-api'\nimport type { FigmaFontNameInput } from '#core/figma-api/fonts/names'\n\nexport type ToolCapability =\n | 'document:read'\n | 'document:write'\n | 'filesystem:read'\n | 'filesystem:write'\n | 'network:access'\n | 'code:execute'\n | 'settings:read'\n | 'settings:write'\n\nexport type ToolExecution =\n | { kind: 'sync'; mutation: 'none' | 'view' | 'properties' | 'document' }\n | {\n kind: 'async'\n mutation: 'none' | 'view' | 'document'\n /**\n * The call can run for a long time even when it only reads, such as recording a video, so\n * bridges give it the deadline they give an edit.\n */\n long?: boolean\n }\n\nexport type ToolInterface = 'mcp' | 'ai' | 'webmcp'\nexport type ToolExposure = Partial<Record<ToolInterface, boolean>>\n\ninterface ToolMetadata {\n name: string\n description: string\n execution: ToolExecution\n /** Interface inclusion defaults to true; execution support and user permissions remain separate. */\n exposure: ToolExposure\n capabilities: readonly ToolCapability[]\n availability: 'default' | 'eval'\n /**\n * What a call's values come from, for the document's design memory:\n * - `imported`: outside content, such as a web page, an SVG, a photo or a library component,\n * whose colors and type are its own, so the memory warns about them rather than refusing;\n * - `copied`: the layers the call names, which it copies or converts with their values, such\n * as a clone, a group or a boolean, so values those layers already had are not new.\n * - `merged`: layers the call joins into one, which may take a paint from any of them, such as\n * flatten and boolean operations; a value is only theirs when every named layer had it.\n */\n content?: 'imported' | 'copied' | 'merged'\n}\n\nexport interface ToolDef extends ToolMetadata {\n input: v.StrictObjectSchema<v.ObjectEntries, undefined>\n /** Derived from execution metadata, never declared independently by a tool. */\n readonly mutates: boolean\n /**\n * Loads the fonts the call's text edits need, as a Figma plugin loads them before it edits\n * text; rejects when one cannot load. Every executor awaits it before `execute`, so a\n * synchronous tool still edits in one step.\n */\n loadFonts: (figma: FigmaAPI, args: Record<string, unknown>) => Promise<void>\n /** `signal` aborts a caller's cancelled request, which a long export checks while it runs. */\n execute: (figma: FigmaAPI, args: Record<string, unknown>, signal?: AbortSignal) => unknown\n /**\n * The synchronous answer of a read whose `execute` may load a page first, or `undefined`\n * when answering would load. Hosts that cannot wait refuse on `undefined` before any load.\n */\n executeSync?: (figma: FigmaAPI, args: Record<string, unknown>) => unknown\n}\n\ntype ToolDefinitionMetadata = Omit<ToolMetadata, 'exposure' | 'capabilities' | 'availability'> &\n Partial<Pick<ToolMetadata, 'exposure' | 'capabilities' | 'availability'>>\n\nexport function defineTool<P extends v.ObjectEntries, R>(\n def: ToolDefinitionMetadata & {\n input: v.StrictObjectSchema<P, undefined>\n execution: ToolExecution & (R extends PromiseLike<unknown> ? { kind: 'async' } : unknown)\n /** The fonts a call's text edits need loaded first; text edits refuse unloaded fonts. */\n fonts?: (\n figma: FigmaAPI,\n args: v.InferOutput<v.StrictObjectSchema<P, undefined>>\n ) => FigmaFontNameInput[]\n execute: (\n figma: FigmaAPI,\n args: v.InferOutput<v.StrictObjectSchema<P, undefined>>,\n signal?: AbortSignal\n ) => R\n executeSync?: (\n figma: FigmaAPI,\n args: v.InferOutput<v.StrictObjectSchema<P, undefined>>\n ) => unknown\n }\n): ToolDef {\n const { fonts } = def\n return {\n ...def,\n exposure: def.exposure ?? {},\n capabilities: def.capabilities ?? [\n toolChangesDocument(def) ? 'document:write' : 'document:read'\n ],\n availability: def.availability ?? 'default',\n get mutates() {\n return def.execution.mutation !== 'none'\n },\n async loadFonts(figma, args) {\n if (!fonts) return\n // Wrong arguments are for `execute` to report.\n const parsed = v.safeParse(def.input, args)\n if (!parsed.success) return\n for (const font of fonts(figma, parsed.output)) await figma.loadFontAsync(font)\n },\n execute: (figma, args, signal) =>\n def.execute(figma, parseToolArgs(def.name, def.input, args), signal),\n executeSync: def.executeSync\n ? (figma, args) => def.executeSync?.(figma, parseToolArgs(def.name, def.input, args))\n : undefined\n }\n}\n\n/**\n * Every tool run goes through here, so a wrong call from AI chat, the CLI, WebMCP, and MCP names\n * the tool and lists each problem with its argument. An unknown or missing argument names the\n * arguments the tool takes, and a picklist names the values it accepts, read from the schema, so\n * the caller does not have to guess. Inputs are strict objects, so a misspelled or mis-nested\n * argument fails here instead of being dropped.\n */\nexport function parseToolArgs<S extends v.GenericSchema>(\n name: string,\n schema: S,\n args: unknown\n): v.InferOutput<S> {\n const result = v.safeParse(schema, args)\n if (result.success) return result.output\n throw new Error(formatToolArgumentError(name, schema, result.issues))\n}\n\n/** One refusal for every surface: the tool, then each problem with where it is. */\nfunction formatToolArgumentError(\n name: string,\n schema: v.GenericSchema,\n issues: readonly v.BaseIssue<unknown>[]\n): string {\n const problems = issues\n .flatMap((issue) => branchIssues(schema, issue))\n .map(({ keys, issue }) => {\n const place = keys.length > 0 ? `\\n → at ${placeOf(keys)}` : ''\n return `× ${formatToolArgIssue(schema, keys, issue)}${place}`\n })\n return `Invalid arguments for ${name}:\\n${problems.join('\\n')}`\n}\n\n/** The parts of a Valibot schema this module reads to name what a call should have sent. */\ntype SchemaParts = {\n readonly entries?: v.ObjectEntries\n readonly item?: v.GenericSchema\n readonly wrapped?: v.GenericSchema\n readonly options?: readonly unknown[]\n}\n\nfunction schemaParts(schema: unknown): SchemaParts {\n return typeof schema === 'object' && schema !== null ? schema : {}\n}\n\n/** The schema a wrapper such as `optional` or `pipe` holds, down to the one with the rules. */\nfunction unwrappedSchema(schema: v.GenericSchema): v.GenericSchema {\n let current = schema\n for (;;) {\n const wrapped = schemaParts(current).wrapped\n if (!wrapped) return current\n current = wrapped\n }\n}\n\ntype ArgumentKey = string | number\n\nfunction issueKeys(issue: v.BaseIssue<unknown>): ArgumentKey[] {\n const keys: ArgumentKey[] = []\n for (const item of issue.path ?? []) {\n if (!('key' in item)) continue\n if (typeof item.key === 'string' || typeof item.key === 'number') keys.push(item.key)\n }\n return keys\n}\n\n/** `operations[0].props`: an index reads as part of its array, a name follows a dot. */\nfunction placeOf(keys: readonly ArgumentKey[]): string {\n return keys.reduce<string>((place, key) => {\n if (typeof key === 'number') return `${place}[${key}]`\n return place ? `${place}.${key}` : key\n }, '')\n}\n\n/**\n * `v.union` reports one issue for every branch, which reads as \"Expected Object but received\n * Object\". Re-check the value against each branch and keep the one that got furthest: the branch\n * whose own problems name the field the caller has to fix.\n */\nfunction branchIssues(\n schema: v.GenericSchema,\n issue: v.BaseIssue<unknown>\n): { keys: ArgumentKey[]; issue: v.BaseIssue<unknown> }[] {\n const keys = issueKeys(issue)\n if (issue.type !== 'union') return [{ keys, issue }]\n const union = schemaAtPath(schema, keys)\n const options = union ? schemaParts(union).options : undefined\n if (!options || options.length === 0) return [{ keys, issue }]\n let best: readonly v.BaseIssue<unknown>[] | null = null\n for (const option of options) {\n const parsed = v.safeParse(option as v.GenericSchema, issue.input)\n if (parsed.success) continue\n if (!best || parsed.issues.length < best.length) best = parsed.issues\n }\n if (!best || best.length === 0) return [{ keys, issue }]\n return best.map((nested) => ({ keys: [...keys, ...issueKeys(nested)], issue: nested }))\n}\n\nfunction schemaAtPath(root: v.GenericSchema, keys: readonly ArgumentKey[]): v.GenericSchema | null {\n let current = unwrappedSchema(root)\n for (const key of keys) {\n const parts = schemaParts(current)\n const name = String(key)\n const next = parts.entries && name in parts.entries ? parts.entries[name] : parts.item\n if (!next) return null\n current = unwrappedSchema(next)\n }\n return current\n}\n\nfunction formatToolArgIssue(\n schema: v.GenericSchema,\n keys: readonly ArgumentKey[],\n issue: v.BaseIssue<unknown>\n): string {\n const key = keys.at(-1)\n if (key !== undefined && (issue.type === 'object' || issue.type === 'strict_object')) {\n if (issue.expected === 'never') {\n const parent = schemaAtPath(schema, keys.slice(0, -1))\n const accepted = parent ? Object.keys(schemaParts(parent).entries ?? {}) : []\n return accepted.length > 0\n ? `Unknown argument \"${key}\". Accepted: ${accepted.join(', ')}`\n : `Unknown argument \"${key}\"`\n }\n if (issue.received === 'undefined') return `Missing required argument \"${key}\"`\n }\n if (issue.type === 'picklist' && key !== undefined) {\n const resolved = schemaAtPath(schema, keys)\n const options = resolved ? schemaParts(resolved).options : undefined\n if (options && options.length > 0) {\n const accepted = options.map((option) => JSON.stringify(option)).join(', ')\n return `Invalid value ${issue.received} for argument \"${key}\". Accepted: ${accepted}`\n }\n }\n return issue.message\n}\n\nexport function toolChangesDocument(def: Pick<ToolDef, 'execution'>): boolean {\n return def.execution.mutation === 'properties' || def.execution.mutation === 'document'\n}\n\nexport function isToolExposed(def: Pick<ToolDef, 'exposure'>, target: ToolInterface): boolean {\n return def.exposure[target] !== false\n}\n\nexport function isAtomicTool(def: ToolDef): boolean {\n return def.execution.kind === 'sync' && def.execution.mutation === 'properties'\n}\n\nexport class NodeNotFoundError extends Error {\n constructor(id: string) {\n super(`Node not found: ${id}`)\n this.name = 'NodeNotFoundError'\n }\n}\n\nexport function requireNode(figma: FigmaAPI, id: string): ReturnType<FigmaAPI['getNodeById']> {\n const node = figma.getNodeById(id)\n if (!node) throw new NodeNotFoundError(id)\n return node\n}\n\nexport function requireNodes(figma: FigmaAPI, ids: ReadonlyArray<string>): FigmaNodeProxy[] | null {\n const nodes: FigmaNodeProxy[] = []\n for (const id of ids) {\n const node = figma.getNodeById(id)\n if (!node) return null\n nodes.push(node)\n }\n return nodes\n}\n\n/** A tool's answer when the operation it wraps throws: the error's message for the caller. */\nexport function toolFailure(error: unknown): { error: string } {\n return { error: error instanceof Error ? error.message : String(error) }\n}\n\nexport function nodeNotFound(id: string): { error: string } {\n return { error: `Node \"${id}\" not found` }\n}\n\nexport function getRawNodeOrError(\n figma: FigmaAPI,\n id: string\n): { node: SceneNode } | { error: string } {\n const node = figma.graph.getNode(id)\n return node ? { node } : nodeNotFound(id)\n}\n\nexport function nodeToResult(node: FigmaNodeProxy, maxDepth?: number): Record<string, unknown> {\n return node.toJSON(maxDepth)\n}\n\nexport function nodeSummary(node: FigmaNodeProxy): { id: string; name: string; type: string } {\n return { id: node.id, name: node.name, type: node.type }\n}\n\n/**\n * A tool colour, refusing text that would otherwise land as black: `set_fill { color: \"#GGG\" }`\n * used to paint black and report success. Read through `tryParseColor`, since a published schema\n * cannot express what the parser accepts.\n */\nexport function parseToolColor(\n value: string,\n profile: DocumentColorSpace = 'srgb'\n): Color | { error: string } {\n return (\n tryParseColor(value, profile) ?? {\n error: `\"${value}\" is not a color; use a hex value, a color name, or a color function`\n }\n )\n}\n\n/**\n * A colour the caller may leave out. Missing stays missing; text that is not a colour is the\n * same refusal `parseToolColor` gives, so each tool does not repeat that check.\n */\nexport function parseOptionalToolColor(\n value: string | undefined,\n profile: DocumentColorSpace = 'srgb'\n): { color: Color | undefined } | { error: string } {\n if (value === undefined) return { color: undefined }\n const parsed = parseToolColor(value, profile)\n if ('error' in parsed) return parsed\n return { color: parsed }\n}\n\nexport const nodeIdInputSchema = v.pipe(v.string(), v.description('Node ID'))\nexport const nodeInputSchema = v.strictObject({ id: nodeIdInputSchema })\nexport const nodeComparisonInputSchema = v.strictObject({\n from: v.pipe(v.string(), v.description('Source node ID')),\n to: v.pipe(v.string(), v.description('Target node ID'))\n})\n\nexport function nodeTraversalInput(depthDescription: string) {\n return v.strictObject({\n id: nodeIdInputSchema,\n depth: v.optional(toolNumber(v.pipe(v.number(), v.description(depthDescription))))\n })\n}\nexport const positionInputs = {\n x: toolNumber(v.pipe(v.number(), v.description('X position in the parent, or on the page'))),\n y: toolNumber(v.pipe(v.number(), v.description('Y position in the parent, or on the page')))\n}\n\n/** Reuse a native number schema for both numeric and numeric-string agent inputs. */\nexport function toolNumber(schema: v.GenericSchema<number, number> = v.number()) {\n // JSON Schema numbers are finite. Express that with representable bounds as well as at runtime.\n const finite = v.pipe(schema, v.minValue(-Number.MAX_VALUE), v.maxValue(Number.MAX_VALUE))\n return v.union([\n finite,\n v.pipe(\n v.string(),\n v.regex(/\\S/, 'Expected a nonblank numeric string'),\n v.description(v.getDescription(schema) ?? 'Numeric value'),\n v.transform(Number),\n finite\n )\n ])\n}\n\n/** `ids`: several node IDs in one call; the description names what they point at. */\nexport function nodeIdsField(description: string) {\n return v.optional(v.pipe(v.array(v.string()), v.minLength(1), v.description(description)))\n}\n"],"mappings":";;;;;;;;;AAmFA,SAAgB,WACd,KAkBS;CACT,MAAM,EAAE,UAAU;CAClB,OAAO;EACL,GAAG;EACH,UAAU,IAAI,YAAY,CAAC;EAC3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B;CAChD,OAAO,EAAE,SAAS,EAAE,KAAK,EAAE,MAAM,EAAE,OAAO,CAAC,GAAG,EAAE,UAAU,CAAC,GAAG,EAAE,YAAY,WAAW,CAAC,CAAC;AAC3F"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"host.d.ts","names":[],"sources":["../../../src/tools/script/host.ts"],"mappings":";;;;;;
|
|
1
|
+
{"version":3,"file":"host.d.ts","names":[],"sources":["../../../src/tools/script/host.ts"],"mappings":";;;;;;UAOiB;;EAEf,OAAO;IACL;IACA;IACA;IACA;MACE;IAAU;IAAY;IAAa;;;EAEvC,UAAU,YAAY;;EAEtB,IAAI,aAAa;IAAU;IAAY;IAAa;IAAgB;;;;iBAMtD,uBAAuB,eAAe,MAAM;iBAQ5C,kBAAkB,gBAAgB"}
|
|
@@ -1,14 +1,16 @@
|
|
|
1
|
+
import { underlyingGraph } from "../../figma-api/graph-ref.js";
|
|
1
2
|
//#region src/tools/script/host.ts
|
|
2
3
|
const hosts = /* @__PURE__ */ new WeakMap();
|
|
3
4
|
/** Lets the `script` tool run for the documents of `owner`, a document's graph. */
|
|
4
5
|
function registerScriptToolHost(owner, host) {
|
|
5
|
-
|
|
6
|
+
const target = underlyingGraph(owner);
|
|
7
|
+
hosts.set(target, host);
|
|
6
8
|
return () => {
|
|
7
|
-
if (hosts.get(
|
|
9
|
+
if (hosts.get(target) === host) hosts.delete(target);
|
|
8
10
|
};
|
|
9
11
|
}
|
|
10
12
|
function getScriptToolHost(owner) {
|
|
11
|
-
return hosts.get(owner);
|
|
13
|
+
return hosts.get(underlyingGraph(owner));
|
|
12
14
|
}
|
|
13
15
|
//#endregion
|
|
14
16
|
export { getScriptToolHost, registerScriptToolHost };
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"host.js","names":[],"sources":["../../../src/tools/script/host.ts"],"sourcesContent":["/**\n * What the `script` tool needs from the host: the sandbox and the node that carries its program\n * live in the app, so the app registers the runner for the documents it shows. A headless host\n * without a sandbox registers nothing, and the tool reports that it is unavailable.\n */\nexport interface ScriptToolHost {\n /** Places a code layer, writes its program, and runs it once there. */\n create(placement: {\n source: string\n x?: number\n y?: number\n parentId?: string\n }): Promise<{ id: string; ok: boolean; error?: string }>\n /** Replaces the program of an existing code layer, as an undo step. */\n setSource(id: string, source: string): void\n /** Runs the code layer again without editing it. */\n run(id: string): Promise<{ id: string; ok: boolean; error?: string; layers?: number }>\n}\n\nconst hosts = new WeakMap<object, ScriptToolHost>()\n\n/** Lets the `script` tool run for the documents of `owner`, a document's graph. */\nexport function registerScriptToolHost(owner: object, host: ScriptToolHost): () => void {\n hosts.set(
|
|
1
|
+
{"version":3,"file":"host.js","names":[],"sources":["../../../src/tools/script/host.ts"],"sourcesContent":["import { underlyingGraph } from '#core/figma-api/graph-ref'\n\n/**\n * What the `script` tool needs from the host: the sandbox and the node that carries its program\n * live in the app, so the app registers the runner for the documents it shows. A headless host\n * without a sandbox registers nothing, and the tool reports that it is unavailable.\n */\nexport interface ScriptToolHost {\n /** Places a code layer, writes its program, and runs it once there. */\n create(placement: {\n source: string\n x?: number\n y?: number\n parentId?: string\n }): Promise<{ id: string; ok: boolean; error?: string }>\n /** Replaces the program of an existing code layer, as an undo step. */\n setSource(id: string, source: string): void\n /** Runs the code layer again without editing it. */\n run(id: string): Promise<{ id: string; ok: boolean; error?: string; layers?: number }>\n}\n\nconst hosts = new WeakMap<object, ScriptToolHost>()\n\n/** Lets the `script` tool run for the documents of `owner`, a document's graph. */\nexport function registerScriptToolHost(owner: object, host: ScriptToolHost): () => void {\n const target = underlyingGraph(owner)\n hosts.set(target, host)\n return () => {\n if (hosts.get(target) === host) hosts.delete(target)\n }\n}\n\nexport function getScriptToolHost(owner: object): ScriptToolHost | undefined {\n return hosts.get(underlyingGraph(owner))\n}\n"],"mappings":";;AAqBA,MAAM,wBAAQ,IAAI,QAAgC;;AAGlD,SAAgB,uBAAuB,OAAe,MAAkC;CACtF,MAAM,SAAS,gBAAgB,KAAK;CACpC,MAAM,IAAI,QAAQ,IAAI;CACtB,aAAa;EACX,IAAI,MAAM,IAAI,MAAM,MAAM,MAAM,MAAM,OAAO,MAAM;CACrD;AACF;AAEA,SAAgB,kBAAkB,OAA2C;CAC3E,OAAO,MAAM,IAAI,gBAAgB,KAAK,CAAC;AACzC"}
|
|
@@ -10,7 +10,7 @@ const listCollections = defineTool({
|
|
|
10
10
|
},
|
|
11
11
|
input: v.strictObject({}),
|
|
12
12
|
execute: (figma) => {
|
|
13
|
-
const collections =
|
|
13
|
+
const collections = figma.graph.getLiveCollections();
|
|
14
14
|
return {
|
|
15
15
|
count: collections.length,
|
|
16
16
|
collections
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"collections.js","names":[],"sources":["../../../src/tools/variables/collections.ts"],"sourcesContent":["import * as v from 'valibot'\n\nimport { defineTool } from '#core/tools/schema'\n\nexport const listCollections = defineTool({\n name: 'list_collections',\n description: 'List all variable collections.',\n execution: { kind: 'sync', mutation: 'none' },\n input: v.strictObject({}),\n execute: (figma) => {\n const collections =
|
|
1
|
+
{"version":3,"file":"collections.js","names":[],"sources":["../../../src/tools/variables/collections.ts"],"sourcesContent":["import * as v from 'valibot'\n\nimport { defineTool } from '#core/tools/schema'\n\nexport const listCollections = defineTool({\n name: 'list_collections',\n description: 'List all variable collections.',\n execution: { kind: 'sync', mutation: 'none' },\n input: v.strictObject({}),\n execute: (figma) => {\n const collections = figma.graph.getLiveCollections()\n return { count: collections.length, collections }\n }\n})\n\nexport const getCollection = defineTool({\n name: 'get_collection',\n description: 'Get a variable collection by ID.',\n execution: { kind: 'sync', mutation: 'none' },\n exposure: { webmcp: false },\n input: v.strictObject({\n id: v.pipe(v.string(), v.description('Collection ID'))\n }),\n execute: (figma, { id }) => {\n const collection = figma.graph.variableCollections.get(id)\n if (!collection) return { error: `Collection \"${id}\" not found` }\n return {\n ...collection,\n activeModeId: figma.graph.getActiveModeId(id)\n }\n }\n})\n\nexport const createCollection = defineTool({\n name: 'create_collection',\n\n description: 'Create a new variable collection.',\n execution: { kind: 'sync', mutation: 'document' },\n input: v.strictObject({\n name: v.pipe(v.string(), v.description('Collection name'))\n }),\n execute: (figma, { name }) => {\n return figma.graph.variableCollections.get(figma.variables.createVariableCollection(name).id)\n }\n})\n\nexport const deleteCollection = defineTool({\n name: 'delete_collection',\n\n description: 'Delete a variable collection and all its variables.',\n execution: { kind: 'sync', mutation: 'document' },\n input: v.strictObject({\n id: v.pipe(v.string(), v.description('Collection ID'))\n }),\n execute: (figma, { id }) => {\n const collection = figma.variables.getVariableCollectionById(id)\n if (!collection) return { error: `Collection \"${id}\" not found` }\n collection.remove()\n return { deleted: id }\n }\n})\n"],"mappings":";;;AAIA,MAAa,kBAAkB,WAAW;CACxC,MAAM;CACN,aAAa;CACb,WAAW;EAAE,MAAM;EAAQ,UAAU;CAAO;CAC5C,OAAO,EAAE,aAAa,CAAC,CAAC;CACxB,UAAU,UAAU;EAClB,MAAM,cAAc,MAAM,MAAM,mBAAmB;EACnD,OAAO;GAAE,OAAO,YAAY;GAAQ;EAAY;CAClD;AACF,CAAC;AAED,MAAa,gBAAgB,WAAW;CACtC,MAAM;CACN,aAAa;CACb,WAAW;EAAE,MAAM;EAAQ,UAAU;CAAO;CAC5C,UAAU,EAAE,QAAQ,MAAM;CAC1B,OAAO,EAAE,aAAa,EACpB,IAAI,EAAE,KAAK,EAAE,OAAO,GAAG,EAAE,YAAY,eAAe,CAAC,EACvD,CAAC;CACD,UAAU,OAAO,EAAE,SAAS;EAC1B,MAAM,aAAa,MAAM,MAAM,oBAAoB,IAAI,EAAE;EACzD,IAAI,CAAC,YAAY,OAAO,EAAE,OAAO,eAAe,GAAG,aAAa;EAChE,OAAO;GACL,GAAG;GACH,cAAc,MAAM,MAAM,gBAAgB,EAAE;EAC9C;CACF;AACF,CAAC;AAED,MAAa,mBAAmB,WAAW;CACzC,MAAM;CAEN,aAAa;CACb,WAAW;EAAE,MAAM;EAAQ,UAAU;CAAW;CAChD,OAAO,EAAE,aAAa,EACpB,MAAM,EAAE,KAAK,EAAE,OAAO,GAAG,EAAE,YAAY,iBAAiB,CAAC,EAC3D,CAAC;CACD,UAAU,OAAO,EAAE,WAAW;EAC5B,OAAO,MAAM,MAAM,oBAAoB,IAAI,MAAM,UAAU,yBAAyB,IAAI,CAAC,CAAC,EAAE;CAC9F;AACF,CAAC;AAED,MAAa,mBAAmB,WAAW;CACzC,MAAM;CAEN,aAAa;CACb,WAAW;EAAE,MAAM;EAAQ,UAAU;CAAW;CAChD,OAAO,EAAE,aAAa,EACpB,IAAI,EAAE,KAAK,EAAE,OAAO,GAAG,EAAE,YAAY,eAAe,CAAC,EACvD,CAAC;CACD,UAAU,OAAO,EAAE,SAAS;EAC1B,MAAM,aAAa,MAAM,UAAU,0BAA0B,EAAE;EAC/D,IAAI,CAAC,YAAY,OAAO,EAAE,OAAO,eAAe,GAAG,aAAa;EAChE,WAAW,OAAO;EAClB,OAAO,EAAE,SAAS,GAAG;CACvB;AACF,CAAC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"values.d.ts","names":[],"sources":["../../../src/tools/variables/values.ts"],"mappings":";;
|
|
1
|
+
{"version":3,"file":"values.d.ts","names":[],"sources":["../../../src/tools/variables/values.ts"],"mappings":";;cA2Ba,gBAAA;cAmCA,aAAA;cAyBA,gBAAA"}
|
|
@@ -6,8 +6,8 @@ import * as v from "valibot";
|
|
|
6
6
|
function figmaValue(value) {
|
|
7
7
|
return typeof value === "object" ? { ...value } : value;
|
|
8
8
|
}
|
|
9
|
-
function parseVariableValue(type, value) {
|
|
10
|
-
if (type === "COLOR") return tryParseColor(value);
|
|
9
|
+
function parseVariableValue(type, value, profile) {
|
|
10
|
+
if (type === "COLOR") return tryParseColor(value, profile);
|
|
11
11
|
if (type === "FLOAT") return Number(value);
|
|
12
12
|
if (type === "BOOLEAN") return value === "true";
|
|
13
13
|
return value;
|
|
@@ -32,7 +32,7 @@ const createVariable = defineTool({
|
|
|
32
32
|
}),
|
|
33
33
|
execute: (figma, args) => {
|
|
34
34
|
const type = args.type;
|
|
35
|
-
const value = args.value === void 0 ? void 0 : parseVariableValue(type, args.value);
|
|
35
|
+
const value = args.value === void 0 ? void 0 : parseVariableValue(type, args.value, figma.graph.documentColorSpace);
|
|
36
36
|
if (value === null) return { error: `"${args.value}" is not a ${type} value` };
|
|
37
37
|
if (typeof value === "number" && !Number.isFinite(value)) return { error: `"${args.value}" is not a number` };
|
|
38
38
|
const variable = figma.variables.createVariable(args.name, args.collection_id, type);
|
|
@@ -55,7 +55,7 @@ const setVariable = defineTool({
|
|
|
55
55
|
execute: (figma, args) => {
|
|
56
56
|
const variable = figma.variables.getVariableById(args.id);
|
|
57
57
|
if (!variable) return { error: `Variable "${args.id}" not found` };
|
|
58
|
-
const parsedValue = parseVariableValue(variable.resolvedType, args.value);
|
|
58
|
+
const parsedValue = parseVariableValue(variable.resolvedType, args.value, figma.graph.documentColorSpace);
|
|
59
59
|
if (parsedValue === null) return { error: `"${args.value}" is not a ${variable.resolvedType} value` };
|
|
60
60
|
variable.setValueForMode(args.mode, figmaValue(parsedValue));
|
|
61
61
|
return {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"values.js","names":[],"sources":["../../../src/tools/variables/values.ts"],"sourcesContent":["import * as v from 'valibot'\n\nimport type { VariableType } from '@pairdraw/scene-graph'\nimport { tryParseColor } from '@pairdraw/scene-graph/color'\nimport type { Color } from '@pairdraw/scene-graph/primitives'\n\nimport type { FigmaVariableValue } from '#core/figma-api'\nimport { defineTool } from '#core/tools/schema'\n\n/** A parsed value as `setValueForMode` takes it; a colour gets a copy of its own. */\nfunction figmaValue(value: ToolValue): FigmaVariableValue {\n return typeof value === 'object' ? { ...value } : value\n}\n\ntype ToolValue = Color | number | string | boolean\n\nfunction parseVariableValue(type: VariableType
|
|
1
|
+
{"version":3,"file":"values.js","names":[],"sources":["../../../src/tools/variables/values.ts"],"sourcesContent":["import * as v from 'valibot'\n\nimport type { DocumentColorSpace, VariableType } from '@pairdraw/scene-graph'\nimport { tryParseColor } from '@pairdraw/scene-graph/color'\nimport type { Color } from '@pairdraw/scene-graph/primitives'\n\nimport type { FigmaVariableValue } from '#core/figma-api'\nimport { defineTool } from '#core/tools/schema'\n\n/** A parsed value as `setValueForMode` takes it; a colour gets a copy of its own. */\nfunction figmaValue(value: ToolValue): FigmaVariableValue {\n return typeof value === 'object' ? { ...value } : value\n}\n\ntype ToolValue = Color | number | string | boolean\n\nfunction parseVariableValue(\n type: VariableType,\n value: string,\n profile: DocumentColorSpace\n): ToolValue | null {\n if (type === 'COLOR') return tryParseColor(value, profile)\n if (type === 'FLOAT') return Number(value)\n if (type === 'BOOLEAN') return value === 'true'\n return value\n}\n\nexport const createVariable = defineTool({\n name: 'create_variable',\n\n description: 'Create a new variable in a collection.',\n execution: { kind: 'sync', mutation: 'document' },\n input: v.strictObject({\n name: v.pipe(v.string(), v.description('Variable name')),\n type: v.pipe(\n v.picklist(['COLOR', 'FLOAT', 'STRING', 'BOOLEAN']),\n v.description('Variable type')\n ),\n collection_id: v.pipe(v.string(), v.description('Collection ID')),\n value: v.optional(\n v.pipe(v.string(), v.description('Initial value (hex for COLOR, number for FLOAT, etc.)'))\n )\n }),\n execute: (figma, args) => {\n const type = args.type\n // The value is checked first, so a value the variable cannot hold creates nothing.\n const value =\n args.value === undefined\n ? undefined\n : parseVariableValue(type, args.value, figma.graph.documentColorSpace)\n if (value === null) return { error: `\"${args.value}\" is not a ${type} value` }\n if (typeof value === 'number' && !Number.isFinite(value))\n return { error: `\"${args.value}\" is not a number` }\n const variable = figma.variables.createVariable(args.name, args.collection_id, type)\n if (value !== undefined) {\n for (const modeId of Object.keys(variable.valuesByMode))\n variable.setValueForMode(modeId, figmaValue(value))\n }\n return figma.graph.variables.get(variable.id)\n }\n})\n\nexport const setVariable = defineTool({\n name: 'set_variable',\n\n description: 'Set the value of a variable for a specific mode.',\n execution: { kind: 'sync', mutation: 'properties' },\n input: v.strictObject({\n id: v.pipe(v.string(), v.description('Variable ID')),\n mode: v.pipe(v.string(), v.description('Mode ID')),\n value: v.pipe(v.string(), v.description('Value (hex for COLOR, number for FLOAT, etc.)'))\n }),\n execute: (figma, args) => {\n const variable = figma.variables.getVariableById(args.id)\n if (!variable) return { error: `Variable \"${args.id}\" not found` }\n const parsedValue = parseVariableValue(\n variable.resolvedType,\n args.value,\n figma.graph.documentColorSpace\n )\n if (parsedValue === null)\n return { error: `\"${args.value}\" is not a ${variable.resolvedType} value` }\n variable.setValueForMode(args.mode, figmaValue(parsedValue))\n return { id: args.id, mode: args.mode, value: parsedValue }\n }\n})\n\nexport const deleteVariable = defineTool({\n name: 'delete_variable',\n\n description: 'Delete a variable.',\n execution: { kind: 'sync', mutation: 'document' },\n input: v.strictObject({\n id: v.pipe(v.string(), v.description('Variable ID'))\n }),\n execute: (figma, { id }) => {\n const variable = figma.variables.getVariableById(id)\n if (!variable) return { error: `Variable \"${id}\" not found` }\n variable.remove()\n return { deleted: id }\n }\n})\n"],"mappings":";;;;;AAUA,SAAS,WAAW,OAAsC;CACxD,OAAO,OAAO,UAAU,WAAW,EAAE,GAAG,MAAM,IAAI;AACpD;AAIA,SAAS,mBACP,MACA,OACA,SACkB;CAClB,IAAI,SAAS,SAAS,OAAO,cAAc,OAAO,OAAO;CACzD,IAAI,SAAS,SAAS,OAAO,OAAO,KAAK;CACzC,IAAI,SAAS,WAAW,OAAO,UAAU;CACzC,OAAO;AACT;AAEA,MAAa,iBAAiB,WAAW;CACvC,MAAM;CAEN,aAAa;CACb,WAAW;EAAE,MAAM;EAAQ,UAAU;CAAW;CAChD,OAAO,EAAE,aAAa;EACpB,MAAM,EAAE,KAAK,EAAE,OAAO,GAAG,EAAE,YAAY,eAAe,CAAC;EACvD,MAAM,EAAE,KACN,EAAE,SAAS;GAAC;GAAS;GAAS;GAAU;EAAS,CAAC,GAClD,EAAE,YAAY,eAAe,CAC/B;EACA,eAAe,EAAE,KAAK,EAAE,OAAO,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AM,kBACd;EACA,IAAI,gBAAgB,MAClB,OAAO,EAAE,OAAO,IAAI,KAAK,MAAM,aAAa,SAAS,aAAa,QAAQ;EAC5E,SAAS,gBAAgB,KAAK,MAAM,WAAW,WAAW,CAAC;EAC3D,OAAO;GAAE,IAAI,KAAK;GAAI,MAAM,KAAK;GAAM,OAAO;EAAY;CAC5D;AACF,CAAC;AAED,MAAa,iBAAiB,WAAW;CACvC,MAAM;CAEN,aAAa;CACb,WAAW;EAAE,MAAM;EAAQ,UAAU;CAAW;CAChD,OAAO,EAAE,aAAa,EACpB,IAAI,EAAE,KAAK,EAAE,OAAO,GAAG,EAAE,YAAY,aAAa,CAAC,EACrD,CAAC;CACD,UAAU,OAAO,EAAE,SAAS;EAC1B,MAAM,WAAW,MAAM,UAAU,gBAAgB,EAAE;EACnD,IAAI,CAAC,UAAU,OAAO,EAAE,OAAO,aAAa,GAAG,aAAa;EAC5D,SAAS,OAAO;EAChB,OAAO,EAAE,SAAS,GAAG;CACvB;AACF,CAAC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"vectorize.d.ts","names":[],"sources":["../../../src/tools/vector/vectorize.ts"],"mappings":";;;
|
|
1
|
+
{"version":3,"file":"vectorize.d.ts","names":[],"sources":["../../../src/tools/vector/vectorize.ts"],"mappings":";;;UAWiB;EACf;EACA,OAAO;;;;;;UAOQ;EACf,UAAU,SAAS,wBAAwB;;;iBAM7B,wBAAwB,eAAe,YAAY;iBAQnD,mBAAmB,gBAAgB;cAItC,gBAAA"}
|