Skip to content

AI-native design editor. Open-source Figma alternative.

refactor(figma-api): validate plugin API values with Valibot schemas (#1690)

Danila Poyarkovad0903faacf3
diff --git a/changes/1690/fixed.md b/changes/1690/fixed.md
new file mode 100644
index 000000000..4bbdf0d38
--- /dev/null
+++ b/changes/1690/fixed.md
@@ -0,0 +1 @@
+- Plugin API effect errors read in Figma's words, and a value with several problems lists each one, as Figma does.
diff --git a/packages/core/src/figma-api/accessors/basic.ts b/packages/core/src/figma-api/accessors/basic.ts
index ef7d383e3..f4f4addb3 100644
--- a/packages/core/src/figma-api/accessors/basic.ts
+++ b/packages/core/src/figma-api/accessors/basic.ts
@@ -27,10 +27,10 @@ import {
type NodeProxyInternals,
type ProxyThis
} from '#core/figma-api/accessor-utils'
-import { invalid, numberProblem } from '#core/figma-api/accessors/text/messages'
import { flushPendingLayout } from '#core/figma-api/pending-layout'
import type { FigmaNodeProxy, NodeProxyHost } from '#core/figma-api/proxy'
import { computeAbsoluteRenderBounds } from '#core/figma-api/render-bounds'
+import { atLeast } from '#core/figma-api/schema'
import {
containerTransform,
setContainerTransform,
@@ -38,6 +38,7 @@ import {
withOrigin
} from '#core/figma-api/transform'
import type { FigmaTransform } from '#core/figma-api/types'
+import { parseFigma } from '#core/figma-api/validation'
import { syncVariantName } from '#core/figma-api/variants'
import { figmaRotation } from '#core/geometry/figma'
import { computeAccurateBounds } from '#core/vector/curve-math'
@@ -328,9 +329,7 @@ function resizedSize(
['width', width],
['height', height]
] as const) {
- const problem =
- numberProblem(value) ?? (value < 0 ? 'Too small: expected number to be >=0' : null)
- if (problem) throw invalid(method, problem, property)
+ parseFigma(atLeast(0), value, method, property)
}
if (node.type === 'VECTOR' && width === 0 && height === 0)
throw new Error('Cannot set width and height of vector node to zero')
diff --git a/packages/core/src/figma-api/accessors/component.ts b/packages/core/src/figma-api/accessors/component.ts
index de643c37a..dd319dd1f 100644
--- a/packages/core/src/figma-api/accessors/component.ts
+++ b/packages/core/src/figma-api/accessors/component.ts
@@ -1,5 +1,6 @@
import type { ComponentSetNode } from '@figma/plugin-typings/plugin-api-standalone'
import { compact, uniq } from 'es-toolkit/array'
+import * as v from 'valibot'
import type { SceneNode } from '@open-pencil/scene-graph'
import { defaultVariant } from '@open-pencil/scene-graph/components'
@@ -11,8 +12,8 @@ import {
type NodeProxyInternals,
type ProxyThis
} from '#core/figma-api/accessor-utils'
-import { invalid, received } from '#core/figma-api/accessors/text/messages'
import type { FigmaNodeProxy, NodeProxyHost } from '#core/figma-api/proxy'
+import { parseFigma } from '#core/figma-api/validation'
function wrap(target: ProxyThis, internals: NodeProxyInternals, id: string): FigmaNodeProxy {
return (target[internals.api] as NodeProxyHost).wrapNode(id)
@@ -41,14 +42,8 @@ export function installComponentNodeAccessors(
return raw(this, internals).symbolDescription
},
set(this: ProxyThis, value: unknown) {
- if (typeof value !== 'string') {
- throw invalid(
- 'set_description',
- `Expected string, received ${received(value)}`,
- 'description'
- )
- }
- updateNode(this, internals, { symbolDescription: value })
+ const description = parseFigma(v.string(), value, 'set_description', 'description')
+ updateNode(this, internals, { symbolDescription: description })
}
})
if (type === 'COMPONENT') {
diff --git a/packages/core/src/figma-api/accessors/guides.ts b/packages/core/src/figma-api/accessors/guides.ts
index 5d1811664..884e4b81a 100644
--- a/packages/core/src/figma-api/accessors/guides.ts
+++ b/packages/core/src/figma-api/accessors/guides.ts
@@ -1,4 +1,5 @@
import type { Guide } from '@figma/plugin-typings/plugin-api-standalone'
+import * as v from 'valibot'
import type { SceneNode } from '@open-pencil/scene-graph'
import { newGuideId, type CanvasGuide } from '@open-pencil/scene-graph/guides'
@@ -9,9 +10,8 @@ import {
type NodeProxyInternals,
type ProxyThis
} from '#core/figma-api/accessor-utils'
-import { invalid, numberProblem, received } from '#core/figma-api/accessors/text/messages'
-
-const METHOD = 'set_guides'
+import { finiteNumberSchema } from '#core/figma-api/schema'
+import { parseFigma } from '#core/figma-api/validation'
/** The layers Figma keeps guides for; installed on their proxies alone, as Figma has them. */
const GUIDE_OWNER_TYPES: ReadonlySet<SceneNode['type']> = new Set([
@@ -22,22 +22,10 @@ const GUIDE_OWNER_TYPES: ReadonlySet<SceneNode['type']> = new Set([
'INSTANCE'
])
-function parseGuide(value: unknown, index: number): Guide {
- if (!value || typeof value !== 'object' || Array.isArray(value)) {
- throw invalid(
- METHOD,
- `Expected object, received ${received(value)} at index ${index}`,
- 'guides'
- )
- }
- const { axis, offset } = value as { axis?: unknown; offset?: unknown }
- if (axis !== 'X' && axis !== 'Y') {
- throw invalid(METHOD, `Invalid option: expected one of "X"|"Y" at [${index}].axis`, 'guides')
- }
- const problem = numberProblem(offset, ` at [${index}].offset`)
- if (problem) throw invalid(METHOD, problem, 'guides')
- return { axis, offset: offset as number }
-}
+/** Figma's `Guide`: an axis and an offset along it. */
+const guidesSchema = v.array(
+ v.strictObject({ axis: v.picklist(['X', 'Y']), offset: finiteNumberSchema })
+)
/**
* `guides` on pages and frames, as Figma keeps them for each (Figma desktop 126). A guide set at
@@ -58,10 +46,7 @@ export function installGuideAccessors(
)
},
set(this: ProxyThis, value: unknown) {
- if (!Array.isArray(value)) {
- throw invalid(METHOD, `Expected array, received ${received(value)}`, 'guides')
- }
- const parsed = value.map(parseGuide)
+ const parsed = parseFigma(guidesSchema, value, 'set_guides', 'guides')
const current = raw(this, internals).guides
const guides = parsed.map(({ axis, offset }, index): CanvasGuide => {
const { id, figGuid } = current.at(index) ?? { id: newGuideId() }
diff --git a/packages/core/src/figma-api/accessors/layout.ts b/packages/core/src/figma-api/accessors/layout.ts
index 38137afdd..c83848d56 100644
--- a/packages/core/src/figma-api/accessors/layout.ts
+++ b/packages/core/src/figma-api/accessors/layout.ts
@@ -1,3 +1,5 @@
+import * as v from 'valibot'
+
import type { LayoutGrid, LayoutMode, LayoutSizing, SceneNode } from '@open-pencil/scene-graph'
import {
aspectRatioLockEditable,
@@ -21,7 +23,8 @@ import {
type NodeProxyInternals,
type ProxyThis
} from '#core/figma-api/accessor-utils'
-import { invalid, numberProblem, received } from '#core/figma-api/accessors/text/messages'
+import { atLeast } from '#core/figma-api/schema'
+import { parseFigma } from '#core/figma-api/validation'
/** A guide in Figma's plugin shape, whether it was set that way or read from a file. */
function figmaLayoutGrid(grid: LayoutGrid): Readonly<LayoutGrid> {
@@ -75,10 +78,7 @@ export function installLayoutNodeProxyAccessors(
return Object.freeze(raw(this, internals).layoutGrids.map(figmaLayoutGrid))
},
set(this: ProxyThis, value: readonly LayoutGrid[]) {
- if (!Array.isArray(value)) {
- const problem = `Expected array, received ${received(value)}`
- throw invalid('set_layoutGrids', problem, 'layoutGrids')
- }
+ parseFigma(v.array(v.unknown()), value, 'set_layoutGrids', 'layoutGrids')
// An Auto count is stored as the archive stores it, so it survives copies and saves.
const grids = structuredClone([...value]).map((grid) =>
isAutoGridCount(grid.count) ? { ...grid, count: AUTO_LAYOUT_GRID_COUNT } : grid
@@ -245,11 +245,8 @@ function padding(
return raw(this, internals)[sides[0]]
},
set(this: ProxyThis, value: unknown) {
- const problem =
- numberProblem(value) ??
- ((value as number) < 0 ? 'Too small: expected number to be >=0' : null)
- if (problem) throw invalid(`set_${property}`, problem, property)
- updateNode(this, internals, Object.fromEntries(sides.map((side) => [side, value])))
+ const amount = parseFigma(atLeast(0), value, `set_${property}`, property)
+ updateNode(this, internals, Object.fromEntries(sides.map((side) => [side, amount])))
}
}
}
diff --git a/packages/core/src/figma-api/accessors/shape.ts b/packages/core/src/figma-api/accessors/shape.ts
index 2f74467e0..dd7edca58 100644
--- a/packages/core/src/figma-api/accessors/shape.ts
+++ b/packages/core/src/figma-api/accessors/shape.ts
@@ -1,3 +1,5 @@
+import * as v from 'valibot'
+
import type { ArcData, SceneNode } from '@open-pencil/scene-graph'
import { fitEnclosingGroups } from '@open-pencil/scene-graph/group-bounds'
@@ -10,57 +12,41 @@ import {
type NodeProxyInternals,
type ProxyThis
} from '#core/figma-api/accessor-utils'
-import { invalid, numberProblem, received } from '#core/figma-api/accessors/text/messages'
+import { finiteNumberSchema, unitIntervalSchema } from '#core/figma-api/schema'
+import { parseFigma } from '#core/figma-api/validation'
/** Figma caps a polygon or star at this many points, past which it keeps the cap. */
const MAX_POINT_COUNT = 60
type BooleanOperation = NonNullable<SceneNode['booleanOperation']>
-const BOOLEAN_OPERATIONS = new Set<BooleanOperation>(['UNION', 'INTERSECT', 'SUBTRACT', 'EXCLUDE'])
-
-const ARC_FIELDS = ['startingAngle', 'endingAngle', 'innerRadius'] as const
+const BOOLEAN_OPERATIONS = [
+ 'UNION',
+ 'INTERSECT',
+ 'SUBTRACT',
+ 'EXCLUDE'
+] as const satisfies readonly BooleanOperation[]
-/** Figma's complaint about a ratio outside 0 to 1, or null. */
-function ratioProblem(value: number, at = ''): string | null {
- if (value < 0) return `Too small: expected number to be >=0${at}`
- if (value > 1) return `Too big: expected number to be <=1${at}`
- return null
-}
+/** Figma checks the minimum before whole numbers, and reports both. */
+const pointCountSchema = v.pipe(finiteNumberSchema, v.minValue(3), v.integer())
+/** Figma's `ArcData`; it checks every field and lists each problem on its own line. */
+const arcDataSchema = v.strictObject({
+ startingAngle: finiteNumberSchema,
+ endingAngle: finiteNumberSchema,
+ innerRadius: unitIntervalSchema
+})
function parsePointCount(value: unknown): number {
- const problem =
- numberProblem(value) ??
- (Number.isInteger(value) ? null : 'Expected int, received number') ??
- ((value as number) < 3 ? 'Too small: expected number to be >=3' : null)
- if (problem) throw invalid('set_pointCount', problem, 'pointCount')
- return Math.min(value as number, MAX_POINT_COUNT)
+ const count = parseFigma(pointCountSchema, value, 'set_pointCount', 'pointCount')
+ return Math.min(count, MAX_POINT_COUNT)
}
function parseInnerRadius(value: unknown): number {
- const problem = numberProblem(value) ?? ratioProblem(value as number)
- if (problem) throw invalid('set_innerRadius', problem, 'innerRadius')
- return value as number
+ return parseFigma(unitIntervalSchema, value, 'set_innerRadius', 'innerRadius')
}
-/** Figma checks every field and lists each problem on its own line. */
function parseArcData(value: unknown): ArcData {
- if (typeof value !== 'object' || value === null || Array.isArray(value)) {
- throw invalid('set_arcData', `Expected object, received ${received(value)}`, 'arcData')
- }
- const fields = value as Partial<Record<(typeof ARC_FIELDS)[number], unknown>>
- // Each field read once, so a getter cannot pass the checks and then store something else.
- const values = ARC_FIELDS.map((field) => fields[field])
- const problems = values.map((value, index) => numberProblem(value, ` at .${ARC_FIELDS[index]}`))
- const [startingAngle, endingAngle, innerRadius] = values
- if (!problems[2]) problems[2] = ratioProblem(innerRadius as number, ' at .innerRadius')
- const listed = problems.filter((problem) => problem !== null)
- if (listed.length > 0) throw invalid('set_arcData', listed.join('\n'), 'arcData')
- return {
- startingAngle: startingAngle as number,
- endingAngle: endingAngle as number,
- innerRadius: innerRadius as number
- }
+ return parseFigma(arcDataSchema, value, 'set_arcData', 'arcData')
}
/** An ellipse without arc data is a whole one, which Figma reports as a full turn. */
@@ -102,14 +88,13 @@ export function installShapeNodeProxyAccessors(
return raw(this, internals).booleanOperation ?? 'UNION'
},
set(this: ProxyThis, value: unknown) {
- if (!BOOLEAN_OPERATIONS.has(value as BooleanOperation)) {
- throw invalid(
- 'set_booleanOperation',
- 'Invalid option: expected one of "UNION"|"INTERSECT"|"SUBTRACT"|"EXCLUDE"',
- 'booleanOperation'
- )
- }
- updateNode(this, internals, { booleanOperation: value as BooleanOperation })
+ const booleanOperation = parseFigma(
+ v.picklist(BOOLEAN_OPERATIONS),
+ value,
+ 'set_booleanOperation',
+ 'booleanOperation'
+ )
+ updateNode(this, internals, { booleanOperation })
// The result's bounds change with the operation, and the groups around it follow.
fitEnclosingGroups(
graph(this, internals),
diff --git a/packages/core/src/figma-api/accessors/styles.ts b/packages/core/src/figma-api/accessors/styles.ts
index 5585843f3..d06cfcabb 100644
--- a/packages/core/src/figma-api/accessors/styles.ts
+++ b/packages/core/src/figma-api/accessors/styles.ts
@@ -1,4 +1,5 @@
import { upperFirst } from 'es-toolkit/string'
+import * as v from 'valibot'
import type { SceneNode, SharedStyleKind } from '@open-pencil/scene-graph'
import { sharedStyleRefKey } from '@open-pencil/scene-graph/shared-styles'
@@ -11,9 +12,9 @@ import {
type NodeProxyInternals,
type ProxyThis
} from '#core/figma-api/accessor-utils'
-import { invalid, received } from '#core/figma-api/accessors/text/messages'
import { bindStylePaints, STYLE_NOT_FOUND, styleChanges } from '#core/figma-api/styles/apply'
import { getTextStyle } from '#core/figma-api/text/style'
+import { parseFigma } from '#core/figma-api/validation'
/** Layers with frames' layout guides, which a grid style gives. */
const GRID_STYLE_TYPES = new Set<SceneNode['type']>([
@@ -69,10 +70,8 @@ function styleMembers(internals: NodeProxyInternals, kind: SharedStyleKind, mixe
},
set(this: ProxyThis, value: unknown) {
const method = `set_${field}`
- if (typeof value !== 'string') {
- throw invalid(method, `Expected string, received ${received(value)}`, field)
- }
- applyStyle(this, internals, kind, value, `in ${method}: ${STYLE_NOT_FOUND}`)
+ const styleId = parseFigma(v.string(), value, method, field)
+ applyStyle(this, internals, kind, styleId, `in ${method}: ${STYLE_NOT_FOUND}`)
}
},
// Figma takes anything but a string without a word, and rejects a style it cannot find.
@@ -107,10 +106,8 @@ export function installStyleReferenceAccessors(
},
set(this: ProxyThis, value: unknown) {
const method = 'set_backgroundStyleId'
- if (typeof value !== 'string') {
- throw invalid(method, `Expected string, received ${received(value)}`, 'backgroundStyleId')
- }
- applyStyle(this, internals, 'fill', value, `in ${method}: ${STYLE_NOT_FOUND}`)
+ const styleId = parseFigma(v.string(), value, method, 'backgroundStyleId')
+ applyStyle(this, internals, 'fill', styleId, `in ${method}: ${STYLE_NOT_FOUND}`)
}
})
}
diff --git a/packages/core/src/figma-api/accessors/text/decoration.ts b/packages/core/src/figma-api/accessors/text/decoration.ts
index a37170e8d..94969b6a5 100644
--- a/packages/core/src/figma-api/accessors/text/decoration.ts
+++ b/packages/core/src/figma-api/accessors/text/decoration.ts
@@ -1,3 +1,5 @@
+import * as v from 'valibot'
+
import type { SceneNode } from '@open-pencil/scene-graph'
import {
@@ -8,9 +10,9 @@ import {
} from '#core/figma-api/accessor-utils'
import { assertTextFontsLoaded } from '#core/figma-api/fonts/loaded'
import { getTextStyle, rangeHasUnderline } from '#core/figma-api/text/style'
+import { parseFigma } from '#core/figma-api/validation'
import { textStyleChanges, type TextStylePatch } from '#core/text/character-style'
-import { invalid, received } from './messages'
import { DECORATION_STYLES, decorationColorFills, enumValue, lengthOrAuto, sized } from './values'
/** The text properties that style an underline, as Figma names them. */
@@ -51,9 +53,7 @@ const PATCHES: Record<
textDecorationFills: decorationColorFills(method, value)
}),
textDecorationSkipInk: (method, value, property) => {
- if (typeof value !== 'boolean')
- throw invalid(method, `Expected boolean, received ${received(value)}`, property)
- return { textDecorationSkipInk: value }
+ return { textDecorationSkipInk: parseFigma(v.boolean(), value, method, property) }
}
}
diff --git a/packages/core/src/figma-api/accessors/text/hyperlink.ts b/packages/core/src/figma-api/accessors/text/hyperlink.ts
index 791f32332..1bb8f26f2 100644
--- a/packages/core/src/figma-api/accessors/text/hyperlink.ts
+++ b/packages/core/src/figma-api/accessors/text/hyperlink.ts
@@ -1,8 +1,14 @@
+import * as v from 'valibot'
+
import type { HyperlinkTarget, NodeType, SceneGraph } from '@open-pencil/scene-graph'
-import { invalid, invalidOption, noneMatched, received } from './messages'
+import { parseFigma } from '#core/figma-api/validation'
-const HYPERLINK_TYPES = new Set(['URL', 'NODE'])
+/** Figma's `HyperlinkTarget`, or null to remove a link; Figma checks a value against both. */
+const hyperlinkSchema = v.union([
+ v.strictObject({ type: v.picklist(['URL', 'NODE']), value: v.string() }),
+ v.null()
+])
/**
* URLs Figma links to: web addresses with a host, in lower case and without surrounding space,
@@ -32,23 +38,8 @@ export function hyperlinkTarget(
graph: SceneGraph,
property: string
): HyperlinkTarget | null {
- if (value === null) return null
- // Figma checks a link against a target and against null, and reports both.
- const refuse: (problem: string) => never = (problem) => {
- throw invalid(
- method,
- noneMatched([problem, `Expected null, received ${received(value)}`]),
- property
- )
- }
- if (typeof value !== 'object' || Array.isArray(value))
- refuse(`Expected object, received ${received(value)}`)
- const target = value as Partial<Record<keyof HyperlinkTarget, unknown>>
- if (!HYPERLINK_TYPES.has(target.type as string))
- refuse(invalidOption(HYPERLINK_TYPES, ' at .type'))
- if (typeof target.value !== 'string') {
- refuse(`Expected string, received ${received(target.value)} at .value`)
- }
+ const target = parseFigma(hyperlinkSchema, value, method, property)
+ if (target === null) return null
if (target.type === 'URL') {
if (target.value === '') return null
if (!LINK_URL.test(target.value)) {
diff --git a/packages/core/src/figma-api/accessors/text/index.ts b/packages/core/src/figma-api/accessors/text/index.ts
index 3e5bfadc1..e361b965b 100644
--- a/packages/core/src/figma-api/accessors/text/index.ts
+++ b/packages/core/src/figma-api/accessors/text/index.ts
@@ -15,17 +15,18 @@ import {
} from '#core/figma-api/accessor-utils'
import { assertFontLoaded, assertTextFontsLoaded } from '#core/figma-api/fonts/loaded'
import type { FigmaFontNameInput } from '#core/figma-api/fonts/names'
+import { atLeast } from '#core/figma-api/schema'
import {
getParagraphSpacing,
letterSpacingValue,
lineHeightValue,
paragraphStylesForCharacters,
styleRunsForCharacters,
- spacingProblem,
type FigmaLetterSpacing,
type FigmaLineHeight
} from '#core/figma-api/text'
import { getTextStyle, type TextSegmentField } from '#core/figma-api/text/style'
+import { parseFigma } from '#core/figma-api/validation'
import { styleRunsWithPatch, textStyleChanges } from '#core/text/character-style'
import { installTextDecorationAccessors } from './decoration'
@@ -45,10 +46,7 @@ function spacing(internals: NodeProxyInternals, name: TextParagraphSpacingField,
return getParagraphSpacing(raw(this, internals), name, mixed)
},
set(this: ProxyThis, value: number) {
- const invalid = spacingProblem(value)
- if (invalid) {
- throw new Error(`in set_${name}: Property "${name}" failed validation: ${invalid}`)
- }
+ parseFigma(atLeast(0), value, `set_${name}`, name)
assertTextFontsLoaded(`set_${name}`, raw(this, internals))
updateNode(this, internals, { [name]: value })
}
diff --git a/packages/core/src/figma-api/accessors/text/messages.ts b/packages/core/src/figma-api/accessors/text/messages.ts
deleted file mode 100644
index 4fd8d4d81..000000000
--- a/packages/core/src/figma-api/accessors/text/messages.ts
+++ /dev/null
@@ -1,55 +0,0 @@
-// Figma's validation messages, worded as its plugin API words them (Figma desktop 126).
-
-/** Figma's message for a value its schema rejects. */
-export function invalid(method: string, problem: string, property = 'value'): Error {
- return new Error(`in ${method}: Property "${property}" failed validation: ${problem}`)
-}
-
-export function received(value: unknown): string {
- // Figma names NaN and the infinities rather than calling them numbers.
- if (typeof value === 'number' && !Number.isFinite(value)) return String(value)
- if (Array.isArray(value)) return 'array'
- return value === null ? 'null' : typeof value
-}
-
-/** Figma's complaint about `value` as a finite number at `at`, or null when it is one. */
-export function numberProblem(value: unknown, at = ''): string | null {
- if (typeof value === 'number' && Number.isFinite(value)) return null
- if (value === undefined) return `Required value missing${at}`
- return `Expected number, received ${received(value)}${at}`
-}
-
-/** A value outside a fixed list of options. */
-export function invalidOption(options: Iterable<string>, at = ''): string {
- return `Invalid option: expected one of ${[...options].map((option) => `"${option}"`).join('|')}${at}`
-}
-
-export function tooSmall(minimum: number, at = ''): string {
- return `Too small: expected number to be >=${minimum}${at}`
-}
-
-export function tooBig(maximum: number, at = ''): string {
- return `Too big: expected number to be <=${maximum}${at}`
-}
-
-/** A literal value, such as a paint type, that the input does not match. */
-export function invalidLiteral(expected: string, at = ''): string {
- return `Invalid input: expected "${expected}"${at}`
-}
-
-/** Keys an object Figma checks strictly does not know, or null when there are none. */
-export function unrecognizedKeys(
- value: object,
- known: ReadonlySet<string>,
- at = ''
-): string | null {
- const unknown = Object.keys(value).filter((key) => !known.has(key))
- if (unknown.length === 0) return null
- const names = unknown.map((key) => `"${key}"`).join(', ')
- return `${unknown.length === 1 ? 'Unrecognized key' : 'Unrecognized keys'}: ${names}${at}`
-}
-
-/** A choice between shapes that none of them matches, each listing its own problem. */
-export function noneMatched(problems: readonly string[]): string {
- return `Expected one of the following, but none matched:\n${problems.map((problem) => ` ${problem}`).join('\n')}`
-}
diff --git a/packages/core/src/figma-api/accessors/text/ranges.ts b/packages/core/src/figma-api/accessors/text/ranges.ts
index 7871221e2..46c77b9ef 100644
--- a/packages/core/src/figma-api/accessors/text/ranges.ts
+++ b/packages/core/src/figma-api/accessors/text/ranges.ts
@@ -27,11 +27,9 @@ import {
type FigmaFontName,
type FigmaFontNameInput
} from '#core/figma-api/fonts/names'
-import {
- readVariationSettings,
- type FigmaVariationSettings
-} from '#core/figma-api/fonts/variations'
+import { readVariationSettings } from '#core/figma-api/fonts/variations'
import type { FigmaPaint } from '#core/figma-api/paints'
+import { fontNameSchema } from '#core/figma-api/schema'
import {
getRangeIndentation,
getRangeListOptions,
@@ -50,6 +48,7 @@ import {
type StyledTextSegment,
type TextSegmentField
} from '#core/figma-api/text/style'
+import { parseFigma } from '#core/figma-api/validation'
import type { FigmaVariableAlias } from '#core/figma-api/variables/values'
import {
characterStyles,
@@ -61,7 +60,6 @@ import { textStyleName } from '#core/text/font/names'
import { rangeDecorationPatch, type DecorationField } from './decoration'
import { hyperlinkTarget } from './hyperlink'
-import { invalid, received, unrecognizedKeys } from './messages'
import { installTextReferenceMethods } from './references'
import {
DECORATIONS,
@@ -70,9 +68,7 @@ import {
fontSizeValue,
lengthOrAuto,
letterSpacingLength,
- stringProblem,
- textCaseValue,
- variationSettingsProblem
+ textCaseValue
} from './values'
/** The font Figma reads for the character at `index`, as a font name left out reads from. */
@@ -97,8 +93,6 @@ function currentFont(node: SceneNode, index: number): CurrentFont {
* A font name Figma takes: a family, and a style and variation settings that may be left out, as
* in `FontNameInput`. What is left out reads from the font of the character at `start`.
*/
-const FONT_NAME_KEYS = new Set(['family', 'style', 'variationSettings'])
-
export function fontNameStyle(
method: string,
node: SceneNode,
@@ -106,25 +100,8 @@ export function fontNameStyle(
value: unknown,
property = 'value'
): CharacterStyleOverride {
- if (!value || typeof value !== 'object') {
- throw invalid(method, `Expected object, received ${received(value)}`, property)
- }
- const fontName = value as Partial<Record<keyof FigmaFontName, unknown>>
- const problem =
- stringProblem(fontName.family, '.family') ??
- (fontName.style === undefined ? null : stringProblem(fontName.style, '.style')) ??
- variationSettingsProblem(fontName.variationSettings) ??
- unrecognizedKeys(value, FONT_NAME_KEYS)
- if (problem) throw invalid(method, problem, property)
- return fontNameInputStyle(
- method,
- {
- family: fontName.family as string,
- style: fontName.style as string | undefined,
- variationSettings: fontName.variationSettings as FigmaVariationSettings | undefined
- },
- currentFont(node, start)
- )
+ const fontName = parseFigma(fontNameSchema, value, method, property)
+ return fontNameInputStyle(method, fontName, currentFont(node, start))
}
type RangeSetter = (
diff --git a/packages/core/src/figma-api/accessors/text/references.ts b/packages/core/src/figma-api/accessors/text/references.ts
index 810ef132f..aaa367a7a 100644
--- a/packages/core/src/figma-api/accessors/text/references.ts
+++ b/packages/core/src/figma-api/accessors/text/references.ts
@@ -1,3 +1,5 @@
+import * as v from 'valibot'
+
import {
graph,
raw,
@@ -14,10 +16,9 @@ import {
rangeSharedStylePatch
} from '#core/figma-api/text/bindings'
import { assertTextRange } from '#core/figma-api/text/style'
+import { parseFigma } from '#core/figma-api/validation'
import { styleRunsWithPatch } from '#core/text/character-style'
-import { invalid, received } from './messages'
-
/** Methods that give characters a text or fill style, deprecated and async alike. */
const SHARED_STYLE_SETTERS = {
setRangeTextStyleId: 'text',
@@ -45,11 +46,9 @@ export function installTextReferenceMethods(
async = false
) {
const node = raw(this, internals)
- if (typeof styleId !== 'string') {
- throw invalid(method, `Expected string, received ${received(styleId)}`, 'styleId')
- }
+ const id = parseFigma(v.string(), styleId, method, 'styleId')
assertTextRange(method, node, start, end)
- const patch = rangeSharedStylePatch(graph(this, internals), kind, styleId)
+ const patch = rangeSharedStylePatch(graph(this, internals), kind, id)
if (!patch) throw new Error(async ? STYLE_NOT_FOUND : `in ${method}: ${STYLE_NOT_FOUND}`)
updateNode(this, internals, { styleRuns: styleRunsWithPatch(node, start, end, patch) })
}
diff --git a/packages/core/src/figma-api/accessors/text/values.ts b/packages/core/src/figma-api/accessors/text/values.ts
index 404d23481..e0599e9cc 100644
--- a/packages/core/src/figma-api/accessors/text/values.ts
+++ b/packages/core/src/figma-api/accessors/text/values.ts
@@ -1,3 +1,5 @@
+import * as v from 'valibot'
+
import type {
CharacterStyleOverride,
Fill,
@@ -9,40 +11,17 @@ import type {
import { textLengthPixels } from '@open-pencil/scene-graph/text'
import { parseFigmaPaints } from '#core/figma-api/paints'
+import { atLeast, finiteNumberSchema, unitIntervalSchema } from '#core/figma-api/schema'
+import { parseFigma } from '#core/figma-api/validation'
-import {
- invalid,
- invalidLiteral,
- invalidOption,
- noneMatched,
- numberProblem,
- received,
- tooBig,
- tooSmall,
- unrecognizedKeys
-} from './messages'
-
-// The values text setters take, checked as Figma checks them, with its messages.
+// The values text setters take, as Figma's schemas check them (Figma desktop 126).
export const DECORATIONS = new Set<TextDecoration>(['NONE', 'UNDERLINE', 'STRIKETHROUGH'])
export const DECORATION_STYLES = new Set<TextDecorationStyle>(['SOLID', 'DOTTED', 'WAVY'])
-const LENGTH_UNITS = new Set(['PIXELS', 'PERCENT'])
-const LENGTH_KEYS = new Set(['unit', 'value'])
-const TEXT_CASES = new Set<TextCase>(['ORIGINAL', 'UPPER', 'LOWER', 'TITLE'])
+const LENGTH_UNITS = ['PIXELS', 'PERCENT'] as const
+const TEXT_CASES = ['ORIGINAL', 'UPPER', 'LOWER', 'TITLE'] as const
/** Text cases Figma takes that OpenPencil cannot draw yet. */
-const SMALL_CAPS = new Set(['SMALL_CAPS', 'SMALL_CAPS_FORCED'])
-const SOLID_PAINT_KEYS = new Set([
- 'type',
- 'color',
- 'opacity',
- 'visible',
- 'blendMode',
- 'boundVariables'
-])
-
-function isLengthUnit(unit: unknown): unit is 'PIXELS' | 'PERCENT' {
- return typeof unit === 'string' && LENGTH_UNITS.has(unit)
-}
+const SMALL_CAPS = ['SMALL_CAPS', 'SMALL_CAPS_FORCED'] as const
/** A length in pixels for a font size: a percent is of the size of the characters it styles. */
export type SizedLength<T> = (fontSize: number) => T
@@ -52,28 +31,39 @@ export function sized(length: TextLength | null): SizedLength<number | null> {
return (fontSize) => length && textLengthPixels(length, fontSize)
}
+/** A size in pixels or a percent of the font size, as Figma's `LetterSpacing` and others are. */
+const lengthSchema = v.strictObject({ value: finiteNumberSchema, unit: v.picklist(LENGTH_UNITS) })
+
+/** A length that may also be automatic, as Figma's `LineHeight` and decoration sizes are. */
+const lengthOrAutoSchema = v.variant('unit', [
+ lengthSchema,
+ v.strictObject({ unit: v.literal('AUTO') })
+])
+
+/** A solid paint, the one paint a decoration colour takes; a colour's alpha may be left out. */
+const solidPaintSchema = v.strictObject({
+ type: v.literal('SOLID'),
+ color: v.strictObject({
+ r: unitIntervalSchema,
+ g: unitIntervalSchema,
+ b: unitIntervalSchema,
+ a: v.optional(unitIntervalSchema)
+ }),
+ opacity: v.optional(unitIntervalSchema),
+ visible: v.optional(v.boolean()),
+ blendMode: v.optional(v.string()),
+ boundVariables: v.optional(v.unknown())
+})
+
+/** Figma's `TextDecorationColor`: automatic, following the text, or a solid paint. */
+const decorationColorSchema = v.union([
+ v.strictObject({ value: solidPaintSchema }),
+ v.strictObject({ value: v.literal('AUTO') })
+])
+
/** A font size Figma takes: a number of at least 1. */
export function fontSizeValue(method: string, value: unknown, property = 'value'): number {
- const problem = numberProblem(value) ?? ((value as number) < 1 ? tooSmall(1) : null)
- if (problem) throw invalid(method, problem, property)
- return value as number
-}
-
-/** A `{ unit, value }` length, its unit one of `units`; Figma knows no other keys. */
-function length(
- method: string,
- value: unknown,
- property: string,
- unitProblem: (unit: unknown) => string | null
-): TextLength {
- if (!value || typeof value !== 'object' || Array.isArray(value)) {
- throw invalid(method, `Expected object, received ${received(value)}`, property)
- }
- const { unit, value: amount } = value as { unit?: unknown; value?: unknown }
- const problem =
- unitProblem(unit) ?? numberProblem(amount, ' at .value') ?? unrecognizedKeys(value, LENGTH_KEYS)
- if (problem) throw invalid(method, problem, property)
- return { unit: unit as TextLength['unit'], value: amount as number }
+ return parseFigma(atLeast(1), value, method, property)
}
/** A letter spacing Figma takes: pixels or percent, never automatic. */
@@ -82,63 +72,17 @@ export function letterSpacingLength(
value: unknown,
property = 'value'
): TextLength {
- return length(method, value, property, (unit) =>
- isLengthUnit(unit) ? null : invalidOption(LENGTH_UNITS, ' at .unit')
- )
+ return parseFigma(lengthSchema, value, method, property)
}
-/** A length that may also be automatic, as line heights and decoration sizes are. */
+/** A length that may also be automatic, read as null, as line heights and decoration sizes are. */
export function lengthOrAuto(
method: string,
value: unknown,
property = 'value'
): TextLength | null {
- if (value && typeof value === 'object' && (value as { unit?: unknown }).unit === 'AUTO') {
- const problem = unrecognizedKeys(value, new Set(['unit']))
- if (problem) throw invalid(method, problem, property)
- return null
- }
- return length(method, value, property, (unit) =>
- isLengthUnit(unit) ? null : 'Expected .unit to be one of the following: PIXELS, PERCENT, AUTO'
- )
-}
-
-export function stringProblem(value: unknown, at: string): string | null {
- return typeof value === 'string' ? null : `Expected string, received ${received(value)} at ${at}`
-}
-
-/** Variation settings Figma takes: numbers by axis tag. */
-export function variationSettingsProblem(value: unknown): string | null {
- if (value === undefined) return null
- if (!value || typeof value !== 'object' || Array.isArray(value)) {
- return `Expected record, received ${received(value)} at .variationSettings`
- }
- for (const [tag, setting] of Object.entries(value)) {
- const problem = numberProblem(setting, ` at .variationSettings.${tag}`)
- if (problem) return problem
- }
- return null
-}
-
-/** A number from 0 to 1, as Figma takes colour channels and opacity. */
-function unitProblem(value: unknown, at: string): string | null {
- const problem = numberProblem(value, ` at ${at}`)
- if (problem) return problem
- if ((value as number) < 0) return tooSmall(0, ` at ${at}`)
- if ((value as number) > 1) return tooBig(1, ` at ${at}`)
- return null
-}
-
-/** A solid paint's colour and opacity as Figma checks them; a colour's alpha may be left out. */
-function solidPaintProblem(paint: { color?: unknown; opacity?: unknown }, at: string) {
- const { color, opacity } = paint
- const channels = color as Partial<Record<'r' | 'g' | 'b' | 'a', unknown>>
- for (const channel of ['r', 'g', 'b', 'a'] as const) {
- if (channel === 'a' && channels.a === undefined) continue
- const problem = unitProblem(channels[channel], `${at}.color.${channel}`)
- if (problem) return problem
- }
- return opacity === undefined ? null : unitProblem(opacity, `${at}.opacity`)
+ const length = parseFigma(lengthOrAutoSchema, value, method, property)
+ return length.unit === 'AUTO' ? null : length
}
/** A range's fills, checked as `fills` checks them. */
@@ -146,52 +90,19 @@ export function fillsFromPaints(method: string, value: unknown): CharacterStyleO
return parseFigmaPaints(value, method, 'value')
}
-/**
- * A decoration colour Figma takes: `AUTO`, or a solid paint. A solid paint wrong only in its
- * values or its keys reports just that; any other input is reported against both choices.
- */
+/** The fills a decoration colour gives: none for automatic, else its solid paint. */
export function decorationColorFills(method: string, value: unknown): Fill[] {
- const color = (value as { value?: unknown } | null)?.value
- if (color === 'AUTO') return []
- const issues: string[] = []
- if (!color || typeof color !== 'object') {
- issues.push(`Expected object, received ${received(color)} at .value`)
- } else {
- const paint = color as Partial<Record<'type' | 'color', unknown>>
- if (paint.type !== 'SOLID') issues.push(invalidLiteral('SOLID', ' at .value.type'))
- if (paint.color === undefined) issues.push('Required value missing at .value.color')
- else if (!paint.color || typeof paint.color !== 'object') {
- issues.push(`Expected object, received ${received(paint.color)} at .value.color`)
- }
- const unknown = unrecognizedKeys(paint, SOLID_PAINT_KEYS, ' at .value')
- if (unknown && issues.length === 0) throw invalid(method, unknown, 'textDecorationColor')
- if (unknown) issues.push(unknown)
- }
- if (issues.length === 0) {
- const problem = solidPaintProblem(color as { color?: unknown; opacity?: unknown }, '.value')
- if (problem) throw invalid(method, problem, 'textDecorationColor')
- return parseFigmaPaints([color], method, 'textDecorationColor')
- }
- const paintProblem =
- issues.length === 1
- ? issues[0]
- : `Multiple issues:\n${issues.map((issue) => ` ${issue}`).join('\n')}`
- throw invalid(
- method,
- noneMatched([paintProblem, invalidLiteral('AUTO', ' at .value')]),
- 'textDecorationColor'
- )
+ const color = parseFigma(decorationColorSchema, value, method, 'textDecorationColor').value
+ return color === 'AUTO' ? [] : parseFigmaPaints([color], method, 'textDecorationColor')
}
/** A text case Figma takes; it takes small caps too, which OpenPencil cannot draw yet. */
export function textCaseValue(method: string, value: unknown, property = 'value'): TextCase {
- if (SMALL_CAPS.has(value as string)) {
- throw new Error(`in ${method}: OpenPencil does not support the ${String(value)} text case`)
+ const textCase = parseFigma(v.picklist([...TEXT_CASES, ...SMALL_CAPS]), value, method, property)
+ if (textCase === 'SMALL_CAPS' || textCase === 'SMALL_CAPS_FORCED') {
+ throw new Error(`in ${method}: OpenPencil does not support the ${textCase} text case`)
}
- if (!TEXT_CASES.has(value as TextCase)) {
- throw invalid(method, invalidOption([...TEXT_CASES, ...SMALL_CAPS]), property)
- }
- return value as TextCase
+ return textCase
}
export function enumValue<T extends string>(
@@ -200,8 +111,5 @@ export function enumValue<T extends string>(
allowed: ReadonlySet<T>,
property = 'value'
): T {
- if (!(allowed as ReadonlySet<unknown>).has(value)) {
- throw invalid(method, invalidOption(allowed), property)
- }
- return value as T
+ return parseFigma(v.picklist([...allowed]), value, method, property)
}
diff --git a/packages/core/src/figma-api/effects.ts b/packages/core/src/figma-api/effects.ts
index 88cd07a19..8cc5ab5a7 100644
--- a/packages/core/src/figma-api/effects.ts
+++ b/packages/core/src/figma-api/effects.ts
@@ -3,7 +3,7 @@ import * as v from 'valibot'
import type { BlendMode, Effect } from '@open-pencil/scene-graph'
import { TRANSPARENT } from '#core/constants'
-import { invalid, received } from '#core/figma-api/accessors/text/messages'
+import { invalid, parseFigma } from '#core/figma-api/validation'
/** Blend modes in the order Figma lists them in its messages. */
const BLEND_MODE_KEYS = {
@@ -74,13 +74,6 @@ const effectsSchema = v.array(effectSchema)
/** An effect as Figma's plugin API reads and writes it (`Effect` in `@figma/plugin-typings`). */
export type FigmaEffect = v.InferOutput<typeof effectSchema>
-/** Figma's spelling of a path into a value: `[0].color.r`. */
-export function issuePath(path: readonly v.IssuePathItem[] | undefined): string {
- return (path ?? [])
- .map((item) => (typeof item.key === 'number' ? `[${item.key}]` : `.${String(item.key)}`))
- .join('')
-}
-
function unsupportedEffect(value: unknown): string | null {
if (!Array.isArray(value)) return null
for (const [index, effect] of value.entries()) {
@@ -95,24 +88,12 @@ function unsupportedEffect(value: unknown): string | null {
return null
}
-/**
- * Check `value` against Figma's effect shapes and convert it to scene effects.
- * Throws with the first problem, as Figma's `effects` setter does.
- */
+/** Check `value` against Figma's effect shapes and convert it to scene effects. */
export function parseFigmaEffects(value: unknown): Effect[] {
const method = 'set_effects'
- if (!Array.isArray(value)) {
- throw invalid(method, `Expected array, received ${received(value)}`, 'effects')
- }
const unsupported = unsupportedEffect(value)
if (unsupported) throw invalid(method, unsupported, 'effects')
- const result = v.safeParse(effectsSchema, value)
- if (!result.success) {
- const [issue] = result.issues
- const at = issuePath(issue.path) || 'effects'
- throw invalid(method, `${issue.message} at ${at}`, 'effects')
- }
- return result.output.map(toSceneEffect)
+ return parseFigma(effectsSchema, value, method, 'effects').map(toSceneEffect)
}
/** `value` as scene effects when it holds valid Figma effects, or null. */
diff --git a/packages/core/src/figma-api/images.ts b/packages/core/src/figma-api/images.ts
index 64d5a86ca..0561cf595 100644
--- a/packages/core/src/figma-api/images.ts
+++ b/packages/core/src/figma-api/images.ts
@@ -1,4 +1,5 @@
import type { Image } from '@figma/plugin-typings/plugin-api-standalone'
+import * as v from 'valibot'
import type { SceneGraph } from '@open-pencil/scene-graph'
import {
@@ -8,7 +9,7 @@ import {
type ImageMimeType
} from '@open-pencil/scene-graph/images'
-import { invalid, received } from './accessors/text/messages'
+import { invalid, parseFigma, received } from '#core/figma-api/validation'
/** How a host fetches the URLs `figma.createImageAsync` loads. */
export type ImageFetch = (input: string, init?: RequestInit) => Promise<Response>
@@ -84,12 +85,8 @@ export function createImage(graph: SceneGraph, data: unknown): Image {
/** The document's image under `hash`, as `figma.getImageByHash` gives it, or null. */
export function imageByHash(graph: SceneGraph, hash: unknown): Image | null {
- if (typeof hash !== 'string') {
- const problem =
- hash === undefined ? 'Required value missing' : `Expected string, received ${received(hash)}`
- throw invalid('getImageByHash', problem, 'getImageByHash')
- }
- return graph.images.has(hash) ? figmaImage(graph, hash) : null
+ const key = parseFigma(v.string(), hash, 'getImageByHash', 'getImageByHash')
+ return graph.images.has(key) ? figmaImage(graph, key) : null
}
/** The protocol of `src` when it is an absolute URL, or null. */
@@ -141,14 +138,10 @@ async function readBounded(response: Response): Promise<Uint8Array> {
*/
export async function fetchImage(
graph: SceneGraph,
- src: unknown,
+ value: unknown,
fetch: ImageFetch
): Promise<Image> {
- if (typeof src !== 'string') {
- const problem =
- src === undefined ? 'Required value missing' : `Expected string, received ${received(src)}`
- throw invalid('createImageAsync', problem, 'createImageAsync')
- }
+ const src = parseFigma(v.string(), value, 'createImageAsync', 'createImageAsync')
const scheme = protocol(src)
if (scheme !== 'http:' && scheme !== 'https:' && scheme !== 'data:') {
throw new Error('createImageAsync requires an absolute URL (http:// or https://) or a data URI')
diff --git a/packages/core/src/figma-api/paints.ts b/packages/core/src/figma-api/paints.ts
index 6cc67a10c..a10f98c10 100644
--- a/packages/core/src/figma-api/paints.ts
+++ b/packages/core/src/figma-api/paints.ts
@@ -8,8 +8,9 @@ import {
} from '@open-pencil/scene-graph/gradient'
import type { Color, Vector } from '@open-pencil/scene-graph/primitives'
-import { invalid, invalidOption, received } from './accessors/text/messages'
-import { BLEND_MODES, issuePath } from './effects'
+import { invalid, parseFigma } from '#core/figma-api/validation'
+
+import { BLEND_MODES } from './effects'
import type { FigmaTransform } from './types'
import { variableAlias, type FigmaVariableAlias } from './variables/values'
@@ -64,7 +65,7 @@ const colorBindingSchema = v.optional(v.strictObject({ color: v.optional(aliasSc
const paintEntries = {
visible: v.optional(v.boolean()),
opacity: v.optional(unitSchema),
- blendMode: v.optional(v.picklist(BLEND_MODES, invalidOption(BLEND_MODES)))
+ blendMode: v.optional(v.picklist(BLEND_MODES))
}
// Figma checks a transform's rows itself, after the paint's other fields.
@@ -74,7 +75,7 @@ const transformSchema = v.optional(v.unknown())
const filterSchema = v.optional(v.pipe(v.number(), v.minValue(-1), v.maxValue(1)))
const mediaEntries = {
- scaleMode: v.picklist(SCALE_MODES, invalidOption(SCALE_MODES)),
+ scaleMode: v.picklist(SCALE_MODES),
scalingFactor: v.optional(v.number()),
rotation: v.optional(v.number()),
filters: v.optional(
@@ -195,49 +196,6 @@ export type FigmaPaint =
type ReadBase = Required<PaintBase>
-/** What Figma calls the value each Valibot schema expects. */
-const EXPECTED: Partial<Record<string, string>> = {
- strict_object: 'object',
- object: 'object',
- variant: 'object',
- array: 'array',
- number: 'number',
- string: 'string',
- boolean: 'boolean'
-}
-
-/** Where Figma reports an issue: a paint itself by its index, a field by its path. */
-function where(path: readonly v.IssuePathItem[]): string {
- if (path.length === 0) return ''
- const [first] = path
- if (path.length === 1 && typeof first.key === 'number') return ` at index ${first.key}`
- return ` at ${issuePath(path)}`
-}
-
-/** One of Figma's lines for a Valibot issue, as its paint validation words it. */
-function issueProblem(issue: v.BaseIssue<unknown>): string {
- const path = issue.path ?? []
- const last = path.at(-1)
- if (last?.origin === 'key') {
- if (issue.expected === 'never') {
- return `Unrecognized key: "${String(last.key)}"${where(path.slice(0, -1))}`
- }
- // Figma checks a missing field as undefined, which a choice refuses as an option.
- const problem = last.key === 'scaleMode' ? invalidOption(SCALE_MODES) : 'Required value missing'
- return `${problem}${where(path)}`
- }
- if (issue.type === 'picklist') return `${issue.message}${where(path)}`
- if (issue.type === 'max_value') {
- return `Too big: expected number to be <=${String(issue.requirement)}${where(path)}`
- }
- if (issue.type === 'min_value') {
- return `Too small: expected number to be >=${String(issue.requirement)}${where(path)}`
- }
- if (issue.input === undefined) return `Required value missing${where(path)}`
- const expected = EXPECTED[issue.type] ?? issue.expected ?? issue.type
- return `Expected ${expected}, received ${received(issue.input)}${where(path)}`
-}
-
/** Figma's complaint about a paint type it does not take, or OpenPencil does not model. */
function typeProblem(value: readonly unknown[]): string | null {
for (const [index, paint] of value.entries()) {
@@ -345,19 +303,15 @@ function sceneFill(paint: ParsedPaint, site: PaintSite): Fill {
* message for `method` setting `property`, listing every problem on its own line.
*/
export function parseFigmaPaints(value: unknown, method = 'set_fills', property = 'fills'): Fill[] {
- if (!Array.isArray(value)) {
- throw invalid(method, `Expected array, received ${received(value)}`, property)
- }
- const unsupported = typeProblem(value)
+ const unsupported = Array.isArray(value) ? typeProblem(value) : null
if (unsupported) throw invalid(method, unsupported, property)
- const result = v.safeParse(v.array(paintSchema), value)
- if (!result.success) throw invalid(method, result.issues.map(issueProblem).join('\n'), property)
- for (const paint of result.output) {
+ const paints = parseFigma(v.array(paintSchema), value, method, property)
+ for (const paint of paints) {
if (paint.type === 'VIDEO' && paint.videoHash !== null && !SHA1_HASH.test(paint.videoHash)) {
throw new Error(`in ${method}: Invalid SHA1 hash`)
}
}
- return result.output.map((paint, index) => sceneFill(paint, { index, method, property }))
+ return paints.map((paint, index) => sceneFill(paint, { index, method, property }))
}
function rows(transform: GradientTransform | undefined): FigmaTransform {
diff --git a/packages/core/src/figma-api/schema.ts b/packages/core/src/figma-api/schema.ts
new file mode 100644
index 000000000..7b63115b9
--- /dev/null
+++ b/packages/core/src/figma-api/schema.ts
@@ -0,0 +1,21 @@
+import * as v from 'valibot'
+
+// Values Figma's plugin API takes in several places, as its schemas check them.
+
+/** A finite number, as Figma takes every number. */
+export const finiteNumberSchema = v.pipe(v.number(), v.finite())
+
+/** A finite number from `minimum` up. */
+export function atLeast(minimum: number) {
+ return v.pipe(v.number(), v.finite(), v.minValue(minimum))
+}
+
+/** A number from 0 to 1, as Figma takes colour channels, opacity, and ratios. */
+export const unitIntervalSchema = v.pipe(finiteNumberSchema, v.minValue(0), v.maxValue(1))
+
+/** Figma's `FontNameInput`: a family, and a style and axes that may be left out. */
+export const fontNameSchema = v.strictObject({
+ family: v.string(),
+ style: v.optional(v.string()),
+ variationSettings: v.optional(v.record(v.string(), finiteNumberSchema))
+})
diff --git a/packages/core/src/figma-api/styles/handles.ts b/packages/core/src/figma-api/styles/handles.ts
index 5a570eea7..62997af86 100644
--- a/packages/core/src/figma-api/styles/handles.ts
+++ b/packages/core/src/figma-api/styles/handles.ts
@@ -3,13 +3,14 @@ import type {
StyleType,
TextStyle
} from '@figma/plugin-typings/plugin-api-standalone'
+import * as v from 'valibot'
import type { SceneGraph, SceneNode, SharedStyleType } from '@open-pencil/scene-graph'
-import { invalid, received } from '#core/figma-api/accessors/text/messages'
import { figmaFills } from '#core/figma-api/accessors/visual'
import { parseFigmaPaints, type FigmaPaint } from '#core/figma-api/paints'
import type { FigmaNodeProxy } from '#core/figma-api/proxy'
+import { parseFigma } from '#core/figma-api/validation'
import { setPaintBindings } from '#core/figma-api/variables/bindings'
import { releaseUsers, restyleUsers, styleConsumers, type LayerUpdate } from './apply'
@@ -86,10 +87,8 @@ export abstract class FigmaBaseStyle {
set name(value: string) {
const node = this[NODE]('set_name')
- if (typeof value !== 'string') {
- throw invalid('set_name', `Expected string, received ${received(value)}`, 'name')
- }
- this[HOST].graph.updateNode(node.id, { name: value })
+ const name = parseFigma(v.string(), value, 'set_name', 'name')
+ this[HOST].graph.updateNode(node.id, { name })
}
get description(): string {
diff --git a/packages/core/src/figma-api/text/bindings.ts b/packages/core/src/figma-api/text/bindings.ts
index aa2de402d..c6a38b4ed 100644
--- a/packages/core/src/figma-api/text/bindings.ts
+++ b/packages/core/src/figma-api/text/bindings.ts
@@ -1,4 +1,5 @@
import { mapValues, omit, pick } from 'es-toolkit/object'
+import * as v from 'valibot'
import {
TEXT_BINDABLE_FIELDS,
@@ -12,7 +13,7 @@ import {
import { copyFills } from '@open-pencil/scene-graph/copy'
import { findSharedStyle, SHARED_TEXT_STYLE_FIELDS } from '@open-pencil/scene-graph/shared-styles'
-import { invalidOption } from '#core/figma-api/accessors/text/messages'
+import { parseFigma } from '#core/figma-api/validation'
import { variableAlias, type FigmaVariableAlias } from '#core/figma-api/variables/values'
import { styleRunsWithPatch } from '#core/text/character-style'
import { faceForStyle } from '#core/text/font/names'
@@ -49,12 +50,7 @@ export function rangeSharedStylePatch(
/** Figma's message for a text field it cannot bind. */
export function assertTextBindableField(method: string, field: unknown): TextBindableField {
- if (!(TEXT_BINDABLE_FIELDS as readonly unknown[]).includes(field)) {
- throw new Error(
- `in ${method}: Property "field" failed validation: ${invalidOption(TEXT_BINDABLE_FIELDS)}`
- )
- }
- return field as TextBindableField
+ return parseFigma(v.picklist(TEXT_BINDABLE_FIELDS), field, method, 'field')
}
/** The variable a binding takes: one the document holds, of the type the field takes. */
diff --git a/packages/core/src/figma-api/text/index.ts b/packages/core/src/figma-api/text/index.ts
index f7940b834..0f754411c 100644
--- a/packages/core/src/figma-api/text/index.ts
+++ b/packages/core/src/figma-api/text/index.ts
@@ -3,8 +3,8 @@ import type {
LineHeight,
TextListOptions
} from '@figma/plugin-typings/plugin-api-standalone'
-import { compact } from 'es-toolkit/array'
import { upperFirst } from 'es-toolkit/string'
+import * as v from 'valibot'
import type {
SceneGraph,
@@ -30,15 +30,10 @@ import {
withParagraphSpacing
} from '@open-pencil/scene-graph/text'
-import {
- invalid,
- invalidOption,
- numberProblem,
- received,
- tooBig,
- tooSmall
-} from '#core/figma-api/accessors/text/messages'
+import { lengthOrAuto, letterSpacingLength } from '#core/figma-api/accessors/text/values'
import { assertTextFontsLoaded } from '#core/figma-api/fonts/loaded'
+import { atLeast, finiteNumberSchema } from '#core/figma-api/schema'
+import { parseFigma } from '#core/figma-api/validation'
import { adjustRunsForDelete, getStyleAt, insertRunsWithStyle } from '#core/text/style-runs'
import { assertTextRange } from './style'
@@ -48,23 +43,6 @@ export type FigmaLineHeight = LineHeight
/** Figma's `LetterSpacing`, in pixels or percent of the font size. */
export type FigmaLetterSpacing = LetterSpacing
-/** Figma's complaint about a length's `.value`, or null when it is a number. */
-function amountProblem(amount: unknown): string | null {
- if (amount === undefined) return 'Required value missing at .value'
- // NaN is a number to typeof, but not to Figma's check.
- return typeof amount === 'number' && !Number.isNaN(amount)
- ? null
- : `Expected number, received ${received(amount)} at .value`
-}
-
-/** A length object a script passes to `method`, checked as Figma checks it. */
-function lengthObject(method: string, property: string, value: unknown) {
- if (typeof value !== 'object' || value === null) {
- throw invalid(method, `Expected object, received ${received(value)}`, property)
- }
- return value as { unit?: unknown; value?: unknown }
-}
-
/**
* Accepts Figma's object, kept in its unit so a percent follows the font size as in Figma, or a
* bare number of pixels or `null` for automatic, as earlier OpenPencil scripts wrote it.
@@ -72,40 +50,19 @@ function lengthObject(method: string, property: string, value: unknown) {
export function lineHeightValue(value: unknown): TextLength | null {
if (value === null) return null
if (typeof value === 'number') return pixelLength(value)
- const length = lengthObject('set_lineHeight', 'lineHeight', value)
- if (length.unit === 'AUTO') return null
- if (length.unit !== 'PIXELS' && length.unit !== 'PERCENT') {
- throw invalid(
- 'set_lineHeight',
- 'Expected .unit to be one of the following: PIXELS, PERCENT, AUTO',
- 'lineHeight'
- )
- }
- const problem = amountProblem(length.value)
- if (problem) throw invalid('set_lineHeight', problem, 'lineHeight')
- return { unit: length.unit, value: length.value as number }
+ return lengthOrAuto('set_lineHeight', value, 'lineHeight')
}
/** Accepts Figma's object, in its unit, or a bare number of pixels as earlier scripts wrote it. */
export function letterSpacingValue(value: unknown): TextLength {
if (typeof value === 'number') return pixelLength(value)
- const length = lengthObject('set_letterSpacing', 'letterSpacing', value)
- const unitKnown = length.unit === 'PIXELS' || length.unit === 'PERCENT'
- // Figma lists every problem, the value's before the unit's.
- const problems = compact([
- amountProblem(length.value),
- unitKnown ? null : 'Invalid option: expected one of "PIXELS"|"PERCENT" at .unit'
- ])
- if (problems.length > 0) {
- throw invalid('set_letterSpacing', problems.join('\n'), 'letterSpacing')
- }
- return { unit: length.unit as TextLength['unit'], value: length.value as number }
+ return letterSpacingLength('set_letterSpacing', value, 'letterSpacing')
}
/** Which neighbour inserted characters copy their style from, as Figma's `insertCharacters` takes it. */
export type InsertStyleSource = 'BEFORE' | 'AFTER'
-const INSERT_STYLE_SOURCES: ReadonlySet<string> = new Set(['BEFORE', 'AFTER'])
+const INSERT_STYLE_SOURCES = ['BEFORE', 'AFTER'] as const satisfies readonly InsertStyleSource[]
/**
* The style inserted characters take, as Figma gives it: the preceding character's for `BEFORE`
@@ -136,13 +93,7 @@ export function insertCharacters(
useStyle: InsertStyleSource = 'BEFORE'
): void {
// Scripts are not type-checked, so the value is checked as Figma checks it.
- if (!INSERT_STYLE_SOURCES.has(useStyle)) {
- throw invalid(
- 'insertCharacters',
- 'Invalid option: expected one of "BEFORE"|"AFTER"',
- 'useStyle'
- )
- }
+ parseFigma(v.picklist(INSERT_STYLE_SOURCES), useStyle, 'insertCharacters', 'useStyle')
assertEditPosition('insertCharacters', node, 'start', start)
assertTextFontsLoaded('insertCharacters', node)
const text = node.text.slice(0, start) + characters + node.text.slice(start)
@@ -163,6 +114,8 @@ export function insertCharacters(
recordInstanceOverride(graph, node.id, ['text', 'textParagraphs', 'styleRuns'])
}
+const editPositionSchema = v.pipe(finiteNumberSchema, v.integer(), v.minValue(0))
+
/**
* A position an edit can use: an integer from 0 through the text length, the end included,
* refused with Figma's messages.
@@ -173,8 +126,7 @@ function assertEditPosition(
name: string,
value: number
) {
- if (!Number.isInteger(value)) throw invalid(method, 'Expected int, received number', name)
- if (value < 0) throw invalid(method, 'Too small: expected number to be >=0', name)
+ parseFigma(editPositionSchema, value, method, name)
if (value > node.text.length) {
const verb = method === 'insertCharacters' ? 'insert' : 'delete'
throw new Error(
@@ -203,7 +155,9 @@ export function deleteCharacters(
}
type ListType = TextListOptions['type']
-const LIST_TYPES: ReadonlySet<string> = new Set<ListType>(['NONE', 'ORDERED', 'UNORDERED'])
+const listOptionsSchema = v.strictObject({
+ type: v.picklist(['NONE', 'ORDERED', 'UNORDERED'] as const satisfies readonly ListType[])
+})
/** The styles of the paragraphs a range touches: a newline belongs to the paragraph it ends. */
function rangeParagraphStyles(node: SceneNode, start: number, end: number): TextParagraphStyle[] {
@@ -238,10 +192,6 @@ export function getRangeListOptions(
return types.size === 1 ? { type } : mixed
}
-function isListType(value: unknown): value is TextListOptions['type'] {
- return (LIST_TYPES as ReadonlySet<unknown>).has(value)
-}
-
export function setRangeListOptions(
graph: SceneGraph,
node: SceneNode,
@@ -249,19 +199,7 @@ export function setRangeListOptions(
end: number,
value: TextListOptions
): void {
- // Scripts pass anything, whatever the types say.
- const options: unknown = value
- if (!options || typeof options !== 'object') {
- throw invalid(
- 'setRangeListOptions',
- `Expected object, received ${received(options)}`,
- 'options'
- )
- }
- const type: unknown = Reflect.get(options, 'type')
- if (!isListType(type)) {
- throw invalid('setRangeListOptions', invalidOption(LIST_TYPES, ' at .type'), 'options')
- }
+ const { type } = parseFigma(listOptionsSchema, value, 'setRangeListOptions', 'options')
assertTextRange('setRangeListOptions', node, start, end)
assertTextFontsLoaded('setRangeListOptions', node)
updateParagraphs(graph, node, start, end, (style) => withListType(style, type))
@@ -279,15 +217,11 @@ export function getRangeIndentation(
return levels.size === 1 ? level : mixed
}
-/** What Figma reports about an indentation it rejects, or `null`. */
-function indentationProblem(level: unknown): string | null {
- const problem = numberProblem(level)
- if (problem) return problem
- if (!Number.isInteger(level)) return 'Expected int, received number'
- if ((level as number) < 0) return tooSmall(0)
- if ((level as number) > MAX_LIST_INDENTATION) return tooBig(MAX_LIST_INDENTATION)
- return null
-}
+/** A whole level of nesting; Figma stops at a fraction before checking the bounds. */
+const indentationSchema = v.config(
+ v.pipe(finiteNumberSchema, v.integer(), v.minValue(0), v.maxValue(MAX_LIST_INDENTATION)),
+ { abortPipeEarly: true }
+)
export function setRangeIndentation(
graph: SceneGraph,
@@ -296,8 +230,7 @@ export function setRangeIndentation(
end: number,
level: number
): void {
- const problem = indentationProblem(level)
- if (problem) throw invalid('setRangeIndentation', problem, 'indentation')
+ parseFigma(indentationSchema, level, 'setRangeIndentation', 'indentation')
assertTextRange('setRangeIndentation', node, start, end)
assertTextFontsLoaded('setRangeIndentation', node)
updateParagraphs(graph, node, start, end, (style) => withIndentation(style, level))
@@ -311,11 +244,6 @@ function spacingParagraphs(node: SceneNode, start: number, end: number): [number
return [paragraphIndexAt(node.text, start), paragraphIndexAt(node.text, end)]
}
-/** What Figma reports about a spacing it rejects, a finite number of 0 or more, or `null`. */
-export function spacingProblem(value: unknown): string | null {
- return numberProblem(value) ?? ((value as number) >= 0 ? null : tooSmall(0))
-}
-
export function getRangeParagraphSpacing(
node: SceneNode,
field: TextParagraphSpacingField,
@@ -336,8 +264,7 @@ export function setRangeParagraphSpacing(
value: number
): void {
const method = `setRange${upperFirst(field)}`
- const invalid = spacingProblem(value)
- if (invalid) throw new Error(`in ${method}: Property "value" failed validation: ${invalid}`)
+ parseFigma(atLeast(0), value, method)
assertTextRange(method, node, start, end)
assertTextFontsLoaded(method, node)
// Ranges change the paragraphs of their characters; one more reaches the end position's.
diff --git a/packages/core/src/figma-api/text/style.ts b/packages/core/src/figma-api/text/style.ts
index 854cd1b84..b00a8abcb 100644
--- a/packages/core/src/figma-api/text/style.ts
+++ b/packages/core/src/figma-api/text/style.ts
@@ -1,6 +1,7 @@
import type { TextDecorationOffset } from '@figma/plugin-typings/plugin-api-standalone'
import { mapValues, pickBy } from 'es-toolkit/object'
import { isEqual } from 'es-toolkit/predicate'
+import * as v from 'valibot'
import type { SceneNode } from '@open-pencil/scene-graph'
import {
@@ -9,9 +10,9 @@ import {
paragraphStyleAt
} from '@open-pencil/scene-graph/text'
-import { invalidOption, tooSmall } from '#core/figma-api/accessors/text/messages'
import { readVariationSettings } from '#core/figma-api/fonts/variations'
import { toFigmaPaint, type FigmaPaint } from '#core/figma-api/paints'
+import { parseFigma, tooSmall } from '#core/figma-api/validation'
import { variableAlias } from '#core/figma-api/variables/values'
import { characterStyles, nodeStyle, type CharacterStyle } from '#core/text/character-style'
import { textStyleName } from '#core/text/font/names'
@@ -244,14 +245,7 @@ export function getStyledTextSegments(
end?: number
): StyledTextSegment[] {
const method = 'getStyledTextSegments'
- for (const [index, field] of fields.entries()) {
- if (!(TEXT_SEGMENT_FIELDS as readonly string[]).includes(field)) {
- throw new Error(
- `in ${method}: Property "${method}" failed validation: ` +
- invalidOption(TEXT_SEGMENT_FIELDS, ` at index ${index}`)
- )
- }
- }
+ parseFigma(v.array(v.picklist(TEXT_SEGMENT_FIELDS)), fields, method, method)
if ((start === undefined) !== (end === undefined)) {
throw new Error(`in ${method}: Invalid range. Must provide both 'start' and 'end'`)
}
diff --git a/packages/core/src/figma-api/util.ts b/packages/core/src/figma-api/util.ts
index 2b2dd4ea7..a2383cbdc 100644
--- a/packages/core/src/figma-api/util.ts
+++ b/packages/core/src/figma-api/util.ts
@@ -7,7 +7,7 @@ import type {
} from '@figma/plugin-typings/plugin-api-standalone'
import { clampRgb as clampRGB, converter, parse, type Color as CuloriColor } from 'culori'
-import { invalid, received } from './accessors/text/messages'
+import { invalid, received } from '#core/figma-api/validation'
const toRGB = converter('rgb')
diff --git a/packages/core/src/figma-api/validation.ts b/packages/core/src/figma-api/validation.ts
new file mode 100644
index 000000000..d70f56122
--- /dev/null
+++ b/packages/core/src/figma-api/validation.ts
@@ -0,0 +1,324 @@
+import { uniq } from 'es-toolkit/array'
+import * as v from 'valibot'
+
+// Figma's plugin API validates arguments with Zod 4 and words what it refuses in its own way
+// (Figma desktop 126). OpenPencil checks them with Valibot; this module words the issues as Figma
+// does, so a script sees the message it would see in Figma.
+
+/** Figma's message for a value its schema rejects. */
+export function invalid(method: string, problem: string, property = 'value'): Error {
+ return new Error(`in ${method}: Property "${property}" failed validation: ${problem}`)
+}
+
+export function received(value: unknown): string {
+ // Figma names NaN and the infinities rather than calling them numbers.
+ if (typeof value === 'number' && !Number.isFinite(value)) return String(value)
+ if (Array.isArray(value)) return 'array'
+ return value === null ? 'null' : typeof value
+}
+
+/**
+ * The values in one of Valibot's `expected` texts, such as `("A" | "B")` for a picklist or `"A"`
+ * for a literal, which Figma lists without Valibot's grouping.
+ */
+function expectedValues(expected: string | null | undefined): string[] {
+ return [...(expected ?? '').matchAll(/"([^"]*)"/g)].map((match) => match[1])
+}
+
+/** A value outside a fixed list of options. */
+function invalidOption(expected: string | null | undefined, at = ''): string {
+ const options = expectedValues(expected).map((option) => `"${option}"`)
+ return `Invalid option: expected one of ${options.join('|')}${at}`
+}
+
+export function tooSmall(minimum: number, at = ''): string {
+ return `Too small: expected number to be >=${minimum}${at}`
+}
+
+function tooBig(maximum: number, at = ''): string {
+ return `Too big: expected number to be <=${maximum}${at}`
+}
+
+/** A choice between shapes that none of them matches, each listing its own problem. */
+function noneMatched(problems: readonly string[], at = ''): string {
+ const expected = at
+ ? `Expected ${at} to be one of the following`
+ : 'Expected one of the following'
+ return `${expected}, but none matched:\n${problems.map((problem) => indent(problem)).join('\n')}`
+}
+
+/** `text` two spaces in, every line of it, so a choice inside a choice keeps its depth. */
+function indent(text: string): string {
+ return text.replaceAll(/^/gm, ' ')
+}
+
+// --- Reading a schema at an issue's path ---
+
+type Schema = v.GenericSchema
+type PathItem = v.IssuePathItem
+
+function property(target: unknown, key: string): unknown {
+ return target && typeof target === 'object' ? Reflect.get(target, key) : undefined
+}
+
+function isSchema(value: unknown): value is Schema {
+ return !!value && typeof value === 'object' && 'kind' in value && '~run' in value
+}
+
+function schemaProperty(target: unknown, key: string): Schema | undefined {
+ const value = property(target, key)
+ return isSchema(value) ? value : undefined
+}
+
+/** A picklist's options, or a union's or variant's: the values or schemas it chooses from. */
+function listProperty(target: unknown, key: string): readonly unknown[] {
+ const value = property(target, key)
+ return Array.isArray(value) ? value : []
+}
+
+/** The schema under a pipe or an optional wrapper, which decides what a value must be. */
+function base(schema: Schema): Schema {
+ const [first] = listProperty(schema, 'pipe')
+ if (isSchema(first) && first !== schema) return base(first)
+ const wrapped = schemaProperty(schema, 'wrapped')
+ return wrapped ? base(wrapped) : schema
+}
+
+function entries(schema: Schema): Partial<Record<string, Schema>> {
+ const value = property(base(schema), 'entries')
+ if (!value || typeof value !== 'object') return {}
+ return Object.fromEntries(Object.entries(value).filter(([, entry]) => isSchema(entry)))
+}
+
+function options(schema: Schema): readonly Schema[] {
+ return listProperty(base(schema), 'options').filter(isSchema)
+}
+
+/** The option of a variant that `input`'s discriminator picks. */
+function variantOption(schema: Schema, input: unknown): Schema | undefined {
+ const key = property(base(schema), 'key')
+ if (typeof key !== 'string') return undefined
+ const value = property(input, key)
+ return options(schema).find((option) => v.is(entries(option)[key] ?? v.never(), value))
+}
+
+/** The schema a step down `item` leads to from `schema`. */
+function child(schema: Schema, item: PathItem): Schema | undefined {
+ const own = base(schema)
+ if (own.type === 'variant') {
+ const option = variantOption(own, item.input)
+ return option && child(option, item)
+ }
+ if (own.type === 'array') return schemaProperty(own, 'item')
+ if (own.type === 'record') return schemaProperty(own, 'value')
+ return entries(own)[String(item.key)]
+}
+
+function schemaAt(root: Schema, path: readonly PathItem[]): Schema | undefined {
+ let schema: Schema | undefined = root
+ for (const item of path) schema = schema && child(schema, item)
+ return schema
+}
+
+// --- Wording ---
+
+/** Where Figma reports an issue: an array item by its index, a field by its path. */
+function where(path: readonly PathItem[]): string {
+ if (path.length === 0) return ''
+ const [first] = path
+ if (path.length === 1 && typeof first.key === 'number') return ` at index ${first.key}`
+ return ` at ${pathText(path)}`
+}
+
+function pathText(path: readonly PathItem[]): string {
+ return path
+ .map((item) => (typeof item.key === 'number' ? `[${item.key}]` : `.${String(item.key)}`))
+ .join('')
+}
+
+/** What Figma calls the value each schema expects. */
+const EXPECTED: Partial<Record<string, string>> = {
+ strict_object: 'object',
+ loose_object: 'object',
+ object: 'object',
+ variant: 'object',
+ array: 'array',
+ record: 'record',
+ number: 'number',
+ string: 'string',
+ boolean: 'boolean',
+ null: 'null'
+}
+
+/**
+ * A field left out. Zod checks it as undefined, so an option or literal is refused as such and
+ * anything else as missing; Valibot reports it against the key, so its schema says which.
+ */
+function missing(schema: Schema | undefined, path: readonly PathItem[]): string {
+ const own = schema && base(schema)
+ if (own?.type === 'picklist') return invalidOption(own.expects, where(path))
+ if (own?.type === 'literal') return `Invalid input: expected ${own.expects}${where(path)}`
+ return `Required value missing${where(path)}`
+}
+
+/**
+ * Every key of `input` the object schema does not know, in one line as Figma lists them. Valibot
+ * stops at the first; without the schema, only that one is named.
+ */
+function unrecognized(
+ schema: Schema | undefined,
+ input: unknown,
+ first: unknown,
+ at: string
+): string {
+ // A variant's keys are those of the option the input's discriminator picks.
+ const object = schema && base(schema).type === 'variant' ? variantOption(schema, input) : schema
+ const known = object ? entries(object) : {}
+ // Valibot reads keys with `for...in`, inherited ones too; any it reports is named.
+ const own = Object.keys(input && typeof input === 'object' ? input : {})
+ const keys = uniq([...own, String(first)]).filter((key) => !Object.hasOwn(known, key))
+ const names = keys.map((key) => `"${key}"`).join(', ')
+ return `${keys.length === 1 ? 'Unrecognized key' : 'Unrecognized keys'}: ${names}${at}`
+}
+
+/** Figma's line for a number outside its bounds, or a check's own message; null for others. */
+function refinementLine(issue: v.BaseIssue<unknown>, at: string): string | null {
+ switch (issue.type) {
+ case 'min_value':
+ return tooSmall(Number(issue.requirement), at)
+ case 'max_value':
+ return tooBig(Number(issue.requirement), at)
+ case 'integer':
+ return `Expected int, received number${at}`
+ case 'finite':
+ return `Expected number, received ${received(issue.input)}${at}`
+ case 'check':
+ case 'raw_check':
+ return `${issue.message}${at}`
+ default:
+ return null
+ }
+}
+
+/**
+ * One of Figma's lines for an issue. Its path, relative to `root`, finds the schemas involved;
+ * `prefix` places `root` in the value the script passed, for where the line says it is.
+ */
+function line(issue: v.BaseIssue<unknown>, root: Schema, prefix: readonly PathItem[]): string {
+ const relative = issue.path ?? []
+ const path = [...prefix, ...relative]
+ const last = relative.at(-1)
+ if (last?.origin === 'key') {
+ if (issue.expected === 'never') {
+ const parent = relative.slice(0, -1)
+ return unrecognized(schemaAt(root, parent), last.input, last.key, where(path.slice(0, -1)))
+ }
+ return missing(schemaAt(root, relative), path)
+ }
+ switch (issue.type) {
+ // A variant refuses an object by its discriminator, anything else as not an object.
+ case 'variant': {
+ const variant = schemaAt(root, relative.slice(0, -1))
+ if (!last || !variant || property(base(variant), 'key') !== last.key) break
+ const values = expectedValues(issue.expected).join(', ')
+ return `Expected ${pathText(path.slice(0, -1))}.${String(last.key)} to be one of the following: ${values}`
+ }
+ case 'picklist':
+ return invalidOption(issue.expected, where(path))
+ // Valibot quotes the string a literal expects, as Figma does.
+ case 'literal':
+ return `Invalid input: expected ${issue.expected}${where(path)}`
+ }
+ const refinement = refinementLine(issue, where(path))
+ if (refinement) return refinement
+ if (issue.input === undefined) return `Required value missing${where(path)}`
+ return `Expected ${EXPECTED[issue.type] ?? issue.type}, received ${received(issue.input)}${where(path)}`
+}
+
+/**
+ * Whether a shape matched but for checks on its values, such as a bound, an integer, or a key it
+ * does not know, so a choice settles on it. Valibot counts a key left out and a number that is not
+ * finite as matching too; Zod, and so Figma, refuses those as the wrong type.
+ */
+function matchedButForChecks(issues: readonly v.BaseIssue<unknown>[]): boolean {
+ return issues.every((issue) =>
+ issue.kind === 'validation'
+ ? issue.type !== 'finite'
+ : issue.path?.at(-1)?.origin === 'key' && issue.expected === 'never'
+ )
+}
+
+/**
+ * Figma's lines for `value` against `schema`, empty when it passes. A choice between shapes that
+ * fails is worded as Zod words it: the one shape that matched but for checks on its values reports
+ * alone; otherwise every shape reports, several problems of one shape grouped.
+ */
+function figmaProblems(schema: Schema, value: unknown, prefix: readonly PathItem[] = []): string[] {
+ const own = base(schema)
+ if (own.type !== 'union') {
+ const result = v.safeParse(schema, value)
+ return result.success ? [] : wordIssues(schema, result.issues, prefix)
+ }
+ const branches = options(own).map((option) => ({ option, result: v.safeParse(option, value) }))
+ const failed = branches.flatMap(({ option, result }) =>
+ result.success ? [] : [{ option, issues: result.issues }]
+ )
+ if (failed.length < branches.length) return []
+ const settled = failed.filter(({ issues }) => matchedButForChecks(issues))
+ if (settled.length === 1) return wordIssues(settled[0].option, settled[0].issues, prefix)
+ // Shapes that fail alike, as every shape fails a missing value, read once.
+ const lines = failed.map(({ option, issues }) => {
+ const problems = wordIssues(option, issues, prefix)
+ return problems.length === 1
+ ? (problems[0] ?? '')
+ : `Multiple issues${where(prefix)}:\n${problems.map((text) => indent(text)).join('\n')}`
+ })
+ return [noneMatched(uniq(lines), pathText(prefix))]
+}
+
+/** Figma's lines for the issues `schema` found; a choice nested in it is worded from where it sits. */
+function wordIssues(
+ schema: Schema,
+ issues: readonly v.BaseIssue<unknown>[],
+ prefix: readonly PathItem[]
+): string[] {
+ return issues.map((issue) => {
+ const nested = issue.type === 'union' ? schemaAt(schema, issue.path ?? []) : undefined
+ if (!nested) return line(issue, schema, prefix)
+ return figmaProblems(nested, issue.input, [...prefix, ...(issue.path ?? [])]).join('\n')
+ })
+}
+
+/** A line from an issue alone, a choice listing what each of its shapes found. */
+function fallback(issue: v.BaseIssue<unknown>, root: Schema): string {
+ if (issue.type !== 'union' || !issue.issues) return line(issue, root, [])
+ return noneMatched(uniq(issue.issues.map((nested) => line(nested, root, []))))
+}
+
+function rereadProblems(schema: Schema, value: unknown): string[] {
+ try {
+ return figmaProblems(schema, value)
+ } catch {
+ return []
+ }
+}
+
+/**
+ * `value` as `schema` reads it, each field read once, or Figma's refusal of it from `method` for
+ * `property`.
+ */
+export function parseFigma<const S extends Schema>(
+ schema: S,
+ value: unknown,
+ method: string,
+ property = 'value'
+): v.InferOutput<S> {
+ const result = v.safeParse(schema, value)
+ if (result.success) return result.output
+ // Wording a choice reads the value again; a value that reads differently the second time, or
+ // throws, still reports what the first read found.
+ const problems = rereadProblems(schema, value)
+ const lines =
+ problems.length > 0 ? problems : result.issues.map((issue) => fallback(issue, schema))
+ throw invalid(method, lines.join('\n'), property)
+}
diff --git a/packages/core/tests/figma-api/accessors/layout/guides.test.ts b/packages/core/tests/figma-api/accessors/layout/guides.test.ts
index f18151f51..ea88ab477 100644
--- a/packages/core/tests/figma-api/accessors/layout/guides.test.ts
+++ b/packages/core/tests/figma-api/accessors/layout/guides.test.ts
@@ -56,6 +56,9 @@ describe('guides', () => {
expect(() => (frame.guides = [{ axis: 'X', offset: Infinity }])).toThrow(
message('Expected number, received Infinity at [0].offset')
)
+ expect(() => (frame.guides = [{ axis: 'X', offset: 1, foo: 1 }] as never)).toThrow(
+ message('Unrecognized key: "foo" at index 0')
+ )
expect(() => (frame.guides = [5] as never)).toThrow(
message('Expected object, received number at index 0')
)
diff --git a/packages/core/tests/figma-api/accessors/shape.test.ts b/packages/core/tests/figma-api/accessors/shape.test.ts
index a3c175e39..43eeb9f9b 100644
--- a/packages/core/tests/figma-api/accessors/shape.test.ts
+++ b/packages/core/tests/figma-api/accessors/shape.test.ts
@@ -128,3 +128,18 @@ describe('a boolean operation', () => {
expect('booleanOperation' in api().figma.createRectangle()).toBe(false)
})
})
+
+describe('shape values Figma refuses', () => {
+ test('a point count reports its minimum before whole numbers, and arc data takes no other keys', () => {
+ const { figma } = api()
+ const polygon = figma.createPolygon()
+ expect(() => (polygon.pointCount = 2.5)).toThrow(
+ 'in set_pointCount: Property "pointCount" failed validation: Too small: expected number to be >=3\nExpected int, received number'
+ )
+ const ellipse = figma.createEllipse()
+ expect(
+ () =>
+ (ellipse.arcData = { startingAngle: 0, endingAngle: 1, innerRadius: 0, foo: 1 } as never)
+ ).toThrow('in set_arcData: Property "arcData" failed validation: Unrecognized key: "foo"')
+ })
+})
diff --git a/packages/core/tests/figma-api/accessors/text/properties.test.ts b/packages/core/tests/figma-api/accessors/text/properties.test.ts
index a24855706..49e21af0b 100644
--- a/packages/core/tests/figma-api/accessors/text/properties.test.ts
+++ b/packages/core/tests/figma-api/accessors/text/properties.test.ts
@@ -151,6 +151,33 @@ describe('text setters check their values as Figma does', () => {
)
})
+ test('links and list options take no keys Figma does not know, and a level is whole first', async () => {
+ const api = createAPI()
+ await api.loadFontAsync({ family: 'Inter', style: 'Regular' })
+ const text = api.createText()
+ text.characters = 'Hello'
+ expect(() =>
+ text.setRangeHyperlink(0, 3, { type: 'URL', value: 'https://a.com', foo: 1 } as never)
+ ).toThrow(
+ 'in setRangeHyperlink: Property "hyperlink" failed validation: Unrecognized key: "foo"'
+ )
+ expect(() => text.setRangeHyperlink(0, 3, undefined as never)).toThrow(
+ 'failed validation: Expected one of the following, but none matched:\n Required value missing'
+ )
+ expect(() => text.setRangeListOptions(0, 3, { type: 'NONE', foo: 1 } as never)).toThrow(
+ 'in setRangeListOptions: Property "options" failed validation: Unrecognized key: "foo"'
+ )
+ let refusal = ''
+ try {
+ text.setRangeIndentation(0, 3, -1.5)
+ } catch (error) {
+ refusal = error instanceof Error ? error.message : ''
+ }
+ expect(refusal).toBe(
+ 'in setRangeIndentation: Property "indentation" failed validation: Expected int, received number'
+ )
+ })
+
test('font names and lengths take no keys Figma does not know', async () => {
const api = createAPI()
await api.loadFontAsync({ family: 'Inter', style: 'Regular' })
diff --git a/packages/core/tests/figma-api/effects.test.ts b/packages/core/tests/figma-api/effects.test.ts
index 6af4ca687..bada95050 100644
--- a/packages/core/tests/figma-api/effects.test.ts
+++ b/packages/core/tests/figma-api/effects.test.ts
@@ -132,8 +132,14 @@ describe('node.effects', () => {
})
test('names the invalid field', () => {
- expect(() => assign([{ ...shadow, radius: -5 }])).toThrow('at [0].radius')
- expect(() => assign([shadow, { ...shadow, foo: 1 }])).toThrow('[1]')
+ const message = (problem: string) =>
+ `in set_effects: Property "effects" failed validation: ${problem}`
+ expect(() => assign([{ ...shadow, radius: -5 }])).toThrow(
+ message('Too small: expected number to be >=0 at [0].radius')
+ )
+ expect(() => assign([shadow, { ...shadow, foo: 1 }])).toThrow(
+ message('Unrecognized key: "foo" at index 1')
+ )
})
test('reports Figma effects OpenPencil does not model yet', () => {
diff --git a/packages/core/tests/figma-api/validation.test.ts b/packages/core/tests/figma-api/validation.test.ts
new file mode 100644
index 000000000..e76295f53
--- /dev/null
+++ b/packages/core/tests/figma-api/validation.test.ts
@@ -0,0 +1,203 @@
+import { describe, expect, test } from 'bun:test'
+
+import * as v from 'valibot'
+
+import { atLeast, finiteNumberSchema } from '#core/figma-api/schema'
+import { parseFigma } from '#core/figma-api/validation'
+
+// The rules come from messages measured in Figma desktop 126, which validates with Zod 4.
+
+const refusal = (schema: v.GenericSchema, value: unknown) => {
+ try {
+ parseFigma(schema, value, 'set_example', 'example')
+ } catch (error) {
+ return error instanceof Error
+ ? error.message.replace('in set_example: Property "example" failed validation: ', '')
+ : String(error)
+ }
+ return null
+}
+
+describe('Figma’s validation messages', () => {
+ test('numbers are finite, and bounds and integers are worded as Figma words them', () => {
+ expect(refusal(finiteNumberSchema, 'a')).toBe('Expected number, received string')
+ expect(refusal(finiteNumberSchema, Number.NaN)).toBe('Expected number, received NaN')
+ expect(refusal(finiteNumberSchema, Infinity)).toBe('Expected number, received Infinity')
+ expect(refusal(atLeast(1), 0)).toBe('Too small: expected number to be >=1')
+ expect(refusal(v.pipe(finiteNumberSchema, v.maxValue(1)), 2)).toBe(
+ 'Too big: expected number to be <=1'
+ )
+ expect(refusal(v.pipe(finiteNumberSchema, v.integer()), 1.5)).toBe(
+ 'Expected int, received number'
+ )
+ })
+
+ test('a field left out reads by what it must be', () => {
+ const schema = v.object({
+ unit: v.picklist(['PIXELS', 'PERCENT']),
+ type: v.literal('SOLID'),
+ value: finiteNumberSchema
+ })
+ expect(refusal(schema, {})).toBe(
+ [
+ 'Invalid option: expected one of "PIXELS"|"PERCENT" at .unit',
+ 'Invalid input: expected "SOLID" at .type',
+ 'Required value missing at .value'
+ ].join('\n')
+ )
+ })
+
+ test('unknown keys are listed together, an array item by its index', () => {
+ const item = v.strictObject({ axis: v.picklist(['X', 'Y']) })
+ expect(refusal(item, { axis: 'X', r: 1, g: 2 })).toBe('Unrecognized keys: "r", "g"')
+ expect(refusal(v.array(item), [{ axis: 'X' }, { axis: 'Y', foo: 1 }])).toBe(
+ 'Unrecognized key: "foo" at index 1'
+ )
+ expect(refusal(item, { axis: 'X', toString: 1, constructor: 2 })).toBe(
+ 'Unrecognized keys: "toString", "constructor"'
+ )
+ expect(refusal(v.array(item), [{ axis: 'Z' }])).toBe(
+ 'Invalid option: expected one of "X"|"Y" at [0].axis'
+ )
+ })
+
+ test('a variant names its discriminator’s options, and refuses anything else as an object', () => {
+ const length = v.variant('unit', [
+ v.strictObject({ unit: v.picklist(['PIXELS', 'PERCENT']), value: finiteNumberSchema }),
+ v.strictObject({ unit: v.literal('AUTO') })
+ ])
+ expect(refusal(length, { unit: 'EM' })).toBe(
+ 'Expected .unit to be one of the following: PIXELS, PERCENT, AUTO'
+ )
+ expect(refusal(v.array(length), [null])).toBe('Expected object, received null at index 0')
+ })
+
+ test('a choice settles on the one shape that matched but for its refinements', () => {
+ const color = v.union([
+ v.strictObject({
+ value: v.strictObject({
+ type: v.literal('SOLID'),
+ color: v.strictObject({ r: v.pipe(finiteNumberSchema, v.maxValue(1)) })
+ })
+ }),
+ v.strictObject({ value: v.literal('AUTO') })
+ ])
+ expect(refusal(color, { value: { type: 'SOLID', color: { r: 2 } } })).toBe(
+ 'Too big: expected number to be <=1 at .value.color.r'
+ )
+ expect(refusal(color, { value: 'RED' })).toBe(
+ 'Expected one of the following, but none matched:\n' +
+ ' Expected object, received string at .value\n' +
+ ' Invalid input: expected "AUTO" at .value'
+ )
+ expect(refusal(color, { value: { type: 'X' } })).toBe(
+ 'Expected one of the following, but none matched:\n' +
+ ' Multiple issues:\n' +
+ ' Invalid input: expected "SOLID" at .value.type\n' +
+ ' Required value missing at .value.color\n' +
+ ' Invalid input: expected "AUTO" at .value'
+ )
+ // Shapes that fail alike read once, as every shape fails a missing value.
+ expect(refusal(color, undefined)).toBe(
+ 'Expected one of the following, but none matched:\n Required value missing'
+ )
+ expect(parseFigma(color, { value: 'AUTO' }, 'set_example')).toEqual({ value: 'AUTO' })
+ })
+
+ test('a value that reads differently the second time reports what the first read found', () => {
+ const choice = v.union([v.strictObject({ size: finiteNumberSchema }), v.literal('AUTO')])
+ let reads = 0
+ const value = {
+ get size() {
+ reads += 1
+ return reads === 1 ? 'big' : 1
+ }
+ }
+ expect(refusal(choice, value)).toBe(
+ 'Expected one of the following, but none matched:\n' +
+ ' Expected number, received string at .size\n' +
+ ' Invalid input: expected "AUTO"'
+ )
+ })
+
+ test('a choice inside the value names where it sits', () => {
+ const constraint = v.union([
+ v.strictObject({ type: v.literal('SCALE'), value: finiteNumberSchema }),
+ v.strictObject({ type: v.picklist(['WIDTH', 'HEIGHT']), value: finiteNumberSchema })
+ ])
+ const settings = v.array(v.object({ constraint: v.optional(constraint) }))
+ expect(refusal(settings, [{ constraint: { type: 'SCALE' } }])).toBe(
+ 'Expected [0].constraint to be one of the following, but none matched:\n' +
+ ' Required value missing at [0].constraint.value\n' +
+ ' Multiple issues at [0].constraint:\n' +
+ ' Invalid option: expected one of "WIDTH"|"HEIGHT" at [0].constraint.type\n' +
+ ' Required value missing at [0].constraint.value'
+ )
+ })
+
+ test('a choice inside a shape of a choice keeps its depth', () => {
+ const inner = v.union([v.literal('A'), v.literal('B')])
+ const choice = v.union([v.strictObject({ mode: inner }), v.literal('NONE')])
+ expect(refusal(choice, { mode: 'C' })).toBe(
+ 'Expected one of the following, but none matched:\n' +
+ ' Expected .mode to be one of the following, but none matched:\n' +
+ ' Invalid input: expected "A" at .mode\n' +
+ ' Invalid input: expected "B" at .mode\n' +
+ ' Invalid input: expected "NONE"'
+ )
+ })
+
+ test('a shape refused on a second, different read names its options', () => {
+ const choice = v.union([v.strictObject({ axis: v.picklist(['X', 'Y']) }), v.literal('NONE')])
+ let reads = 0
+ const value = {
+ get axis() {
+ reads += 1
+ return reads === 1 ? 'Z' : 'X'
+ }
+ }
+ expect(refusal(choice, value)).toBe(
+ 'Expected one of the following, but none matched:\n' +
+ ' Invalid option: expected one of "X"|"Y" at .axis\n' +
+ ' Invalid input: expected "NONE"'
+ )
+ })
+
+ test('a literal left out on the first read names what it must be', () => {
+ const choice = v.union([v.strictObject({ type: v.literal('SOLID') }), v.literal('NONE')])
+ let reads = 0
+ const value = {
+ get type() {
+ reads += 1
+ return reads === 1 ? undefined : 'SOLID'
+ }
+ }
+ expect(refusal(choice, value)).toBe(
+ 'Expected one of the following, but none matched:\n' +
+ ' Invalid input: expected "SOLID" at .type\n' +
+ ' Invalid input: expected "NONE"'
+ )
+ })
+
+ test('an unknown key inherited by the value is named', () => {
+ const value: object = Object.create({ inherited: 1 })
+ expect(refusal(v.strictObject({}), value)).toBe('Unrecognized key: "inherited"')
+ })
+
+ test('a value that throws on a second read reports what the first read found', () => {
+ const choice = v.union([v.strictObject({ axis: v.picklist(['X', 'Y']) }), v.literal('NONE')])
+ let reads = 0
+ const value = {
+ get axis() {
+ reads += 1
+ if (reads > 1) throw new Error('second read')
+ return 'Z'
+ }
+ }
+ expect(refusal(choice, value)).toBe(
+ 'Expected one of the following, but none matched:\n' +
+ ' Invalid option: expected one of "X"|"Y" at .axis\n' +
+ ' Invalid input: expected "NONE"'
+ )
+ })
+})