Skip to content

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

feat(figma-api): add figma.util, closePlugin, loadAllPagesAsync, and createImageAsync (#1478)

Danila Poyarkova5ab68d54411
diff --git a/changes/1478/added.md b/changes/1478/added.md
new file mode 100644
index 000000000..6ab1b5d75
--- /dev/null
+++ b/changes/1478/added.md
@@ -0,0 +1 @@
+- Scripts can call `figma.util.rgb`, `figma.util.rgba`, `figma.util.solidPaint`, `figma.closePlugin()`, `figma.loadAllPagesAsync()`, `figma.getImageByHash()`, and `figma.createImageAsync(url)` as in Figma, and `figma.createImage` returns Figma's `Image` with `getBytesAsync()` and `getSizeAsync()`. `createImage` takes PNG, JPEG, and GIF up to 4096 pixels a side, as Figma does, and the desktop app loads `createImageAsync` URLs through its native proxy, so hosts without CORS headers work.
diff --git a/packages/core/src/figma-api/compatibility.ts b/packages/core/src/figma-api/compatibility.ts
index 4f4d6503b..bc9816f96 100644
--- a/packages/core/src/figma-api/compatibility.ts
+++ b/packages/core/src/figma-api/compatibility.ts
@@ -25,13 +25,19 @@ export type SupportedPluginAPI = Pick<
PluginAPI,
| 'base64Decode'
| 'base64Encode'
+ | 'closePlugin'
+ | 'getImageByHash'
+ | 'loadAllPagesAsync'
| 'loadFontAsync'
| 'notify'
+ | 'util'
| 'setCurrentPageAsync'
| 'createComponent'
| 'createConnector'
| 'createEllipse'
| 'createFrame'
+ | 'createImage'
+ | 'createImageAsync'
| 'createLine'
| 'createNodeFromSvg'
| 'createPolygon'
diff --git a/packages/core/src/figma-api/images.ts b/packages/core/src/figma-api/images.ts
new file mode 100644
index 000000000..779b77c92
--- /dev/null
+++ b/packages/core/src/figma-api/images.ts
@@ -0,0 +1,177 @@
+/// <reference types="@figma/plugin-typings" />
+
+import type { SceneGraph } from '@open-pencil/scene-graph'
+import {
+ computeImageHash,
+ imageMimeType,
+ imageSize,
+ type ImageMimeType
+} from '@open-pencil/scene-graph/images'
+
+import { invalid, received } from './accessors/text/messages'
+
+/** How a host fetches the URLs `figma.createImageAsync` loads. */
+export type ImageFetch = (input: string, init?: RequestInit) => Promise<Response>
+
+/** The largest width or height Figma takes an image at. */
+const MAX_IMAGE_SIDE = 4096
+
+/** The most bytes `createImageAsync` reads from a response, well above any 4096 × 4096 image. */
+export const MAX_IMAGE_FETCH_BYTES = 64 * 1024 * 1024
+
+/**
+ * The bytes Figma needs before it takes an image: a PNG's header through its bit depth and color
+ * type, and a GIF's logical screen size. A JPEG needs its start-of-frame, which `imageSize` reads.
+ */
+const MIN_HEADER_BYTES: Partial<Record<ImageMimeType, number>> = {
+ 'image/png': 26,
+ 'image/gif': 10
+}
+
+/** A PNG's signature and the type of its first chunk, which Figma requires byte for byte. */
+const PNG_HEADER = [
+ 0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0, 0, 0, 13, 0x49, 0x48, 0x44, 0x52
+]
+
+/** Figma's complaint about `data` as an image, or null when it takes it. */
+function imageProblem(data: Uint8Array): string | null {
+ const type = imageMimeType(data)
+ const size = type === 'image/webp' ? null : imageSize(data)
+ if (!size || size.width === 0 || size.height === 0) return 'Image type is unsupported'
+ if (type === 'image/png' && PNG_HEADER.some((byte, index) => data[index] !== byte)) {
+ return 'Image type is unsupported'
+ }
+ if (data.length < (MIN_HEADER_BYTES[type] ?? 0)) return 'Image type is unsupported'
+ if (size.width > MAX_IMAGE_SIDE || size.height > MAX_IMAGE_SIDE) return 'Image is too large'
+ return null
+}
+
+/** The document's image under `hash`, as Figma's `Image` gives it to a script. */
+function figmaImage(graph: SceneGraph, hash: string): Image {
+ const bytes = (method: string) => {
+ const data = graph.images.get(hash)
+ if (!data) throw new Error(`in ${method}: The document has no image ${hash}`)
+ return data
+ }
+ return {
+ hash,
+ getBytesAsync: async () => bytes('getBytesAsync').slice(),
+ getSizeAsync: async () => {
+ const size = imageSize(bytes('getSizeAsync'))
+ if (!size) throw new Error('in getSizeAsync: Image type is unsupported')
+ return size
+ }
+ }
+}
+
+/**
+ * Stores a copy of encoded image bytes under their hash and returns the hash, so a caller that
+ * reuses its array afterwards cannot change the stored image. Tools store formats Figma's API
+ * refuses, such as WebP, through this; scripts go through `createImage`.
+ */
+export function storeImage(graph: SceneGraph, data: Uint8Array): string {
+ const stored = data.slice()
+ const hash = computeImageHash(stored)
+ graph.images.set(hash, stored)
+ return hash
+}
+
+/**
+ * The PNG, JPEG, or GIF in `data`, stored as `figma.createImage` stores it. Throws Figma's
+ * messages for anything else and for an image wider or taller than 4096 pixels.
+ */
+export function createImage(graph: SceneGraph, data: unknown): Image {
+ if (!(data instanceof Uint8Array)) {
+ const problem =
+ data === undefined
+ ? 'Required value missing'
+ : `Expected Uint8Array, received ${received(data)}`
+ throw invalid('createImage', problem, 'createImage')
+ }
+ const problem = imageProblem(data)
+ if (problem) throw new Error(`in createImage: ${problem}`)
+ return figmaImage(graph, storeImage(graph, data))
+}
+
+/** 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
+}
+
+/** The protocol of `src` when it is an absolute URL, or null. */
+function protocol(src: string): string | null {
+ try {
+ return new URL(src).protocol
+ } catch {
+ return null
+ }
+}
+
+/**
+ * The body of `response`, refused as too large once it passes `MAX_IMAGE_FETCH_BYTES`. It reads
+ * chunk by chunk and cancels there, so a body that declares no length, or a smaller one, cannot
+ * fill memory first.
+ */
+async function readBounded(response: Response): Promise<Uint8Array> {
+ if (Number(response.headers.get('content-length') ?? 0) > MAX_IMAGE_FETCH_BYTES) {
+ throw new Error('Image is too large')
+ }
+ const reader = response.body?.getReader()
+ if (!reader) return new Uint8Array()
+ const chunks: Uint8Array[] = []
+ let length = 0
+ for (;;) {
+ const { done, value } = await reader.read()
+ if (done) break
+ length += value.byteLength
+ if (length > MAX_IMAGE_FETCH_BYTES) {
+ await reader.cancel()
+ throw new Error('Image is too large')
+ }
+ chunks.push(value)
+ }
+ const data = new Uint8Array(length)
+ let offset = 0
+ for (const chunk of chunks) {
+ data.set(chunk, offset)
+ offset += chunk.byteLength
+ }
+ return data
+}
+
+/**
+ * The image at `src`, fetched and stored as `figma.createImageAsync` does. HTTP(S) URLs go
+ * through the host's `fetch`; data URIs hold their bytes and are read here, since a desktop
+ * proxy takes only HTTP(S). Figma's own server fetches the rest, so its messages name only the
+ * status.
+ */
+export async function fetchImage(
+ graph: SceneGraph,
+ src: 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 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')
+ }
+ const load = scheme === 'data:' ? globalThis.fetch : fetch
+ const response = await load(src).catch((error: unknown) => {
+ const reason = error instanceof Error ? error.message : String(error)
+ throw new Error(`Unable to fetch image: ${reason}`)
+ })
+ if (!response.ok) throw new Error(`Unable to fetch image. Response status: ${response.status}`)
+ const data = await readBounded(response)
+ const problem = imageProblem(data)
+ if (problem) throw new Error(problem)
+ return figmaImage(graph, storeImage(graph, data))
+}
diff --git a/packages/core/src/figma-api/index.ts b/packages/core/src/figma-api/index.ts
index 2b86ff2e3..d8d908b31 100644
--- a/packages/core/src/figma-api/index.ts
+++ b/packages/core/src/figma-api/index.ts
@@ -4,7 +4,6 @@ import type { SceneGraph, SceneNode as CoreSceneNode, NodeType } from '@open-pen
import { createConnector, freeEndpoint } from '@open-pencil/scene-graph/connectors'
import { computeBounds } from '@open-pencil/scene-graph/geometry'
import type { GroupFitOptions } from '@open-pencil/scene-graph/group-bounds'
-import { computeImageHash } from '@open-pencil/scene-graph/images'
import type { Rect, Vector } from '@open-pencil/scene-graph/primitives'
import type { SkiaRenderer } from '#core/canvas'
@@ -23,6 +22,7 @@ import { fontManager } from '#core/text/fonts'
import { componentFromNode } from './components'
import { flattenSceneNodes } from './flatten'
+import * as images from './images'
import type {
FigmaBooleanOperationNode,
FigmaComponentNode,
@@ -51,16 +51,24 @@ import {
} from './proxy'
import { newShapeWithText } from './shape-with-text'
import type { ExportImageOptions } from './types'
+import { figmaUtil } from './util'
import { FigmaVariablesAPI } from './variables'
import { combineComponentsAsVariants } from './variants'
const noop = () => undefined
+/** What a host passes to `FigmaAPI` beyond the document. */
+export interface FigmaAPIOptions {
+ /** Fetches the HTTP(S) URLs `figma.createImageAsync` loads; the global `fetch` by default. */
+ fetch?: images.ImageFetch
+}
+
export { FigmaNodeProxy } from './proxy'
export { getPageBackgrounds, setPageBackgrounds } from './page-backgrounds'
export { flushPendingLayout } from './pending-layout'
export type { FigmaEffect } from './effects'
export type { ExportImageOptions } from './types'
+export { MAX_IMAGE_FETCH_BYTES, type ImageFetch } from './images'
export {
FigmaVariable,
FigmaVariableCollection,
@@ -103,11 +111,17 @@ export class FigmaAPI implements NodeProxyHost {
theme: InterfaceTheme = 'light'
readonly mixed = MIXED
+ /** Figma's color and Markdown helpers, as `figma.util`. */
+ readonly util: UtilAPI = figmaUtil
/** The document's variables and collections, as Figma's `figma.variables`. */
readonly variables: FigmaVariablesAPI
- constructor(graph: SceneGraph) {
+ /** How `createImageAsync` fetches HTTP(S) URLs; a host passes one that gets past CORS. */
+ readonly #fetch: images.ImageFetch
+
+ constructor(graph: SceneGraph, options: FigmaAPIOptions = {}) {
this.graph = graph
+ this.#fetch = options.fetch ?? ((input, init) => fetch(input, init))
this.variables = new FigmaVariablesAPI(graph)
startPendingLayout(graph)
const pages = graph.getPages()
@@ -507,10 +521,17 @@ export class FigmaAPI implements NodeProxyHost {
this._viewport = { x: v.center.x, y: v.center.y, zoom: v.zoom }
}
- createImage(data: Uint8Array): { hash: string } {
- const hash = computeImageHash(data)
- this.graph.images.set(hash, data)
- return { hash }
+ createImage(data: Uint8Array): Image {
+ return images.createImage(this.graph, data)
+ }
+
+ getImageByHash(hash: string): Image | null {
+ return images.imageByHash(this.graph, hash)
+ }
+
+ /** Fetches the image at `src` through the host's `fetch` and stores it as `createImage` does. */
+ createImageAsync(src: string): Promise<Image> {
+ return images.fetchImage(this.graph, src, this.#fetch)
}
// --- Stubs ---
@@ -543,6 +564,19 @@ export class FigmaAPI implements NodeProxyHost {
return { cancel: noop }
}
+ /**
+ * A script is one call rather than a plugin with a lifetime, so nothing closes; the message is
+ * shown as Figma shows it, through `notify`.
+ */
+ closePlugin(message?: string): void {
+ if (message) this.notify(message)
+ }
+
+ /** Every page is already in memory. */
+ async loadAllPagesAsync(): Promise<void> {
+ return undefined
+ }
+
commitUndo(): void {
return undefined
}
diff --git a/packages/core/src/figma-api/surface.ts b/packages/core/src/figma-api/surface.ts
index 85519a972..dfa186539 100644
--- a/packages/core/src/figma-api/surface.ts
+++ b/packages/core/src/figma-api/surface.ts
@@ -24,7 +24,6 @@ export const FIGMA_API_HOST_MEMBERS = [
*/
export const FIGMA_API_INCOMPLETE_MEMBERS = [
'createComponentFromNode',
- 'createImage',
'createPage',
'currentPage',
'getNodeById',
diff --git a/packages/core/src/figma-api/util.ts b/packages/core/src/figma-api/util.ts
new file mode 100644
index 000000000..1c0be8abb
--- /dev/null
+++ b/packages/core/src/figma-api/util.ts
@@ -0,0 +1,165 @@
+/// <reference types="@figma/plugin-typings" />
+
+import { clampRgb as clampRGB, converter, parse, type Color as CuloriColor } from 'culori'
+
+import { invalid, received } from './accessors/text/messages'
+
+const toRGB = converter('rgb')
+
+/** The CSS color spaces Figma's `figma.util` reads; it refuses `lch()`, `hwb()`, and the rest. */
+const READABLE_MODES = new Set(['rgb', 'hsl', 'lab', 'oklab', 'oklch', 'p3'])
+
+/** The order Figma lists blend modes in when it refuses one. */
+const BLEND_MODES = [
+ 'PASS_THROUGH',
+ 'NORMAL',
+ 'DARKEN',
+ 'MULTIPLY',
+ 'LINEAR_BURN',
+ 'COLOR_BURN',
+ 'LIGHTEN',
+ 'SCREEN',
+ 'LINEAR_DODGE',
+ 'COLOR_DODGE',
+ 'OVERLAY',
+ 'SOFT_LIGHT',
+ 'HARD_LIGHT',
+ 'DIFFERENCE',
+ 'EXCLUSION',
+ 'HUE',
+ 'SATURATION',
+ 'COLOR',
+ 'LUMINOSITY'
+] as const satisfies readonly BlendMode[]
+
+const SOLID_PAINT_KEYS = new Set([
+ 'type',
+ 'color',
+ 'visible',
+ 'opacity',
+ 'blendMode',
+ 'boundVariables'
+])
+
+/** What Figma's messages call a value of the wrong type; unlike text styles, it says `NaN`. */
+function kind(value: unknown): string {
+ return typeof value === 'number' && Number.isNaN(value) ? 'NaN' : received(value)
+}
+
+/** Figma's complaint about a channel from 0 to 1, or null when `value` is one. */
+function channelProblem(value: unknown, at = ''): string | null {
+ if (value === undefined) return `Required value missing${at}`
+ if (typeof value !== 'number' || Number.isNaN(value)) {
+ return `Expected number, received ${kind(value)}${at}`
+ }
+ if (value > 1) return `Too big: expected number to be <=1${at}`
+ if (value < 0) return `Too small: expected number to be >=0${at}`
+ return null
+}
+
+function unrecognizedKeys(value: object, known: ReadonlySet<string>): 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: ${names}` : `Unrecognized keys: ${names}`
+}
+
+/**
+ * A CSS color string as Figma reads it: clipped to sRGB channel by channel, and `lab()` taken
+ * with a D65 white rather than CSS's D50.
+ */
+function readColorString(method: string, input: string): RGBA {
+ const parsed = parse(input.trim())
+ // Figma refuses CSS `none` channels, which culori reads by leaving the channel out.
+ if (!parsed || !READABLE_MODES.has(parsed.mode) || /\bnone\b/i.test(input)) {
+ throw new Error(`in ${method}: failed to parse color: ${input}`)
+ }
+ const color: CuloriColor = parsed.mode === 'lab' ? { ...parsed, mode: 'lab65' } : parsed
+ const { r, g, b } = clampRGB(toRGB(color))
+ return { r, g, b, a: Math.min(Math.max(parsed.alpha ?? 1, 0), 1) }
+}
+
+const RGBA_KEYS = new Set(['r', 'g', 'b', 'a'])
+
+/** `color` as `figma.util` takes it: a CSS color string, or an RGB or RGBA object. */
+function readColor(method: string, color: unknown): RGBA {
+ if (typeof color === 'string') return readColorString(method, color)
+ const fail = (problem: string) => invalid(method, problem, 'color')
+ if (color === undefined) {
+ throw fail('Expected one of the following, but none matched:\n Required value missing')
+ }
+ if (typeof color !== 'object' || color === null || Array.isArray(color)) {
+ const type = kind(color)
+ throw fail(
+ 'Expected one of the following, but none matched:\n' +
+ ` Expected string, received ${type}\n Expected object, received ${type}`
+ )
+ }
+ const unknown = unrecognizedKeys(color, RGBA_KEYS)
+ if (unknown) throw fail(unknown)
+ const channels: Record<string, unknown> = { ...color }
+ const problems = (['r', 'g', 'b', 'a'] as const).flatMap((key) => {
+ if (key === 'a' && channels.a === undefined) return []
+ return channelProblem(channels[key], ` at .${key}`) ?? []
+ })
+ if (problems.length > 0) throw fail(problems.join('\n'))
+ // Every channel is a number from 0 to 1 now.
+ const channel = (key: keyof RGBA) => Number(channels[key] ?? 1)
+ return { r: channel('r'), g: channel('g'), b: channel('b'), a: channel('a') }
+}
+
+function rgb(color: string | RGB | RGBA): RGB {
+ const { r, g, b } = readColor('rgb', color)
+ return { r, g, b }
+}
+
+function rgba(color: string | RGB | RGBA, alphaOverride?: number): RGBA {
+ const parsed = readColor('rgba', color)
+ if (alphaOverride === undefined) return parsed
+ const problem = channelProblem(alphaOverride)
+ if (problem) throw invalid('rgba', problem, 'alphaOverride')
+ return { ...parsed, a: alphaOverride }
+}
+
+/** Figma's complaint about `overrides` for a solid paint, or null when it takes them. */
+function overridesProblem(overrides: unknown): string | null {
+ if (typeof overrides !== 'object' || overrides === null || Array.isArray(overrides)) {
+ return `Expected object, received ${kind(overrides)}`
+ }
+ const unknown = unrecognizedKeys(overrides, SOLID_PAINT_KEYS)
+ if (unknown) return unknown
+ const type = 'type' in overrides ? overrides.type : undefined
+ const visible = 'visible' in overrides ? overrides.visible : undefined
+ const blendMode = 'blendMode' in overrides ? overrides.blendMode : undefined
+ if (type !== undefined && type !== 'SOLID') return 'Invalid input: expected "SOLID" at .type'
+ if (visible !== undefined && typeof visible !== 'boolean') {
+ return `Expected boolean, received ${kind(visible)} at .visible`
+ }
+ if (blendMode !== undefined && !(BLEND_MODES as readonly unknown[]).includes(blendMode)) {
+ const expected = BLEND_MODES.map((mode) => `"${mode}"`).join('|')
+ return `Invalid option: expected one of ${expected} at .blendMode`
+ }
+ return null
+}
+
+/**
+ * A solid paint of `color` with its alpha as the opacity, keeping the other properties of
+ * `overrides`. The color and its alpha win over `overrides`, as in Figma, so an existing paint
+ * takes the new color and opacity.
+ */
+function solidPaint(color: string | RGB | RGBA, overrides?: Partial<SolidPaint>): SolidPaint {
+ const { r, g, b, a } = readColor('solidPaint', color)
+ if (overrides !== undefined) {
+ const problem = overridesProblem(overrides)
+ if (problem) throw invalid('solidPaint', problem, 'SolidPaint')
+ }
+ return { ...overrides, type: 'SOLID', color: { r, g, b }, opacity: a }
+}
+
+/** Figma normalizes for its rich-text editors, which OpenPencil does not have. */
+function normalizeMarkdown(): string {
+ throw new Error('in normalizeMarkdown: OpenPencil does not support rich-text Markdown')
+}
+
+/** Figma's `figma.util`, whose functions a script may call detached (`const rgb = figma.util.rgb`). */
+export const figmaUtil: UtilAPI = Object.freeze({ rgb, rgba, solidPaint, normalizeMarkdown })
diff --git a/packages/core/src/tools/modify/paint.ts b/packages/core/src/tools/modify/paint.ts
index be966cea7..0cd1da589 100644
--- a/packages/core/src/tools/modify/paint.ts
+++ b/packages/core/src/tools/modify/paint.ts
@@ -6,6 +6,7 @@ import { gradientTransformRows, linearGradientTransform } from '@open-pencil/sce
import type { Vector } from '@open-pencil/scene-graph/primitives'
import { BLACK } from '#core/constants'
+import { storeImage } from '#core/figma-api/images'
import { defineTool, nodeIdInputSchema, toolNumber } from '#core/tools/schema'
export const setFill = defineTool({
@@ -133,7 +134,7 @@ export const setImageFill = defineTool({
if (!node) return { error: `Node "${id}" not found` }
if (!isValid(image_data)) return { error: 'image_data is not valid Base64' }
const bytes = toUint8Array(image_data)
- const image = figma.createImage(bytes)
+ const imageHash = storeImage(figma.graph, bytes)
const mode = scale_mode
node.fills = [
{
@@ -141,10 +142,10 @@ export const setImageFill = defineTool({
color: BLACK,
opacity: 1,
visible: true,
- imageHash: image.hash,
+ imageHash,
imageScaleMode: mode
}
]
- return { id, imageHash: image.hash, scaleMode: mode }
+ return { id, imageHash, scaleMode: mode }
}
})
diff --git a/packages/core/src/tools/stock-photo/apply.ts b/packages/core/src/tools/stock-photo/apply.ts
index c78c33bad..93eca4227 100644
--- a/packages/core/src/tools/stock-photo/apply.ts
+++ b/packages/core/src/tools/stock-photo/apply.ts
@@ -1,4 +1,5 @@
import type { FigmaAPI } from '#core/figma-api'
+import { storeImage } from '#core/figma-api/images'
import type { FigmaNodeProxy } from '#core/figma-api/proxy'
import type { StockPhotoProvider, StockPhotoResult } from './providers'
@@ -85,12 +86,12 @@ export async function applyPhoto(
return { id: req.id, error: `Download: ${err instanceof Error ? err.message : String(err)}` }
}
- const image = figma.createImage(imageBytes)
+ const imageHash = storeImage(figma.graph, imageBytes)
node.fills = [
{
type: 'IMAGE',
color: { r: 1, g: 1, b: 1, a: 1 },
- imageHash: image.hash,
+ imageHash,
imageScaleMode: 'FILL',
visible: true,
opacity: 1
diff --git a/packages/core/tests/figma-api/images.test.ts b/packages/core/tests/figma-api/images.test.ts
index f8342db5f..62f44e344 100644
--- a/packages/core/tests/figma-api/images.test.ts
+++ b/packages/core/tests/figma-api/images.test.ts
@@ -1,49 +1,248 @@
import { describe, expect, test } from 'bun:test'
-import { FigmaAPI } from '@open-pencil/core/figma-api'
+import { scriptResult } from '#core-tests/helpers/script'
+import { toUint8Array } from 'js-base64'
+
+import { FigmaAPI, MAX_IMAGE_FETCH_BYTES } from '@open-pencil/core/figma-api'
import { SceneGraph } from '@open-pencil/scene-graph'
-const PNG_MAGIC = new Uint8Array([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a])
-const JPEG_MAGIC = new Uint8Array([0xff, 0xd8, 0xff, 0xe0])
+// Expected values were recorded by running the same scripts in Figma, except where noted.
+
+/** A 1 × 1 PNG, which Figma stores under the hash below. */
+const PNG_1X1 =
+ 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg=='
+const PNG_1X1_HASH = 'b2bbe763c7e1828c750d53f78550709a6fea19be'
+const PNG_3X2 =
+ 'iVBORw0KGgoAAAANSUhEUgAAAAMAAAACCAIAAAASFvFNAAAAEElEQVR4nGP4z8AAQQxwFgBB0gX7h/C5SAAAAABJRU5ErkJggg=='
+/** A 3 × 2 JPEG, which Figma stores under the hash below. */
+const JPEG_3X2 =
+ '/9j/4AAQSkZJRgABAQAASABIAAD/4QBMRXhpZgAATU0AKgAAAAgAAYdpAAQAAAABAAAAGgAAAAAAA6ABAAMAAAABAAEAAKACAAQAAAABAAAAA6ADAAQAAAABAAAAAgAAAAD/7QA4UGhvdG9zaG9wIDMuMAA4QklNBAQAAAAAAAA4QklNBCUAAAAAABDUHYzZjwCyBOmACZjs+EJ+/8AAEQgAAgADAwEiAAIRAQMRAf/EAB8AAAEFAQEBAQEBAAAAAAAAAAABAgMEBQYHCAkKC//EALUQAAIBAwMCBAMFBQQEAAABfQECAwAEEQUSITFBBhNRYQcicRQygZGhCCNCscEVUtHwJDNicoIJChYXGBkaJSYnKCkqNDU2Nzg5OkNERUZHSElKU1RVVldYWVpjZGVmZ2hpanN0dXZ3eHl6g4SFhoeIiYqSk5SVlpeYmZqio6Slpqeoqaqys7S1tre4ubrCw8TFxsfIycrS09TV1tfY2drh4uPk5ebn6Onq8fLz9PX29/j5+v/EAB8BAAMBAQEBAQEBAQEAAAAAAAABAgMEBQYHCAkKC//EALURAAIBAgQEAwQHBQQEAAECdwABAgMRBAUhMQYSQVEHYXETIjKBCBRCkaGxwQkjM1LwFWJy0QoWJDThJfEXGBkaJicoKSo1Njc4OTpDREVGR0hJSlNUVVZXWFlaY2RlZmdoaWpzdHV2d3h5eoKDhIWGh4iJipKTlJWWl5iZmqKjpKWmp6ipqrKztLW2t7i5usLDxMXGx8jJytLT1NXW19jZ2uLj5OXm5+jp6vLz9PX29/j5+v/bAEMAAQEBAQEBAgEBAgMCAgIDBAMDAwMEBQQEBAQEBQYFBQUFBQUGBgYGBgYGBgcHBwcHBwgICAgICQkJCQkJCQkJCf/bAEMBAQEBAgICBAICBAkGBQYJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCf/dAAQAAf/aAAwDAQACEQMRAD8A/F+iiiv8pz/v4P/Z'
+const JPEG_3X2_HASH = '7a28914c98c0ec831e892346a126c7ec9677ac7c'
+const GIF_1X1 = 'R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7'
+const WEBP_1X1 = 'UklGRiQAAABXRUJQVlA4IBgAAAAwAQCdASoBAAEAAwA0JaQAA3AA/vuUAAA='
+
+/** A PNG header declaring a `width` × `height` image, through its bit depth and color type. */
+function pngHeader(width: number, height: number): number[] {
+ const header = new Uint8Array(26)
+ const view = new DataView(header.buffer)
+ header.set([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0, 0, 0, 13, 0x49, 0x48, 0x44, 0x52])
+ view.setUint32(16, width)
+ view.setUint32(20, height)
+ header.set([8, 0], 24)
+ return Array.from(header)
+}
-function setup() {
- const graph = new SceneGraph()
- const figma = new FigmaAPI(graph)
- return { graph, figma }
+/** A script that runs each case's call and gives what it resolved to or the message it threw. */
+function attempts(cases: Record<string, string>): string {
+ const entries = Object.entries(cases).map(
+ ([name, call]) =>
+ `[${JSON.stringify(name)}, await (async () => ${call})().then((value) => value, (error) => error.message)]`
+ )
+ return `
+ const bytes = (base64) => figma.base64Decode(base64)
+ return Object.fromEntries([${entries.join(',\n')}])
+ `
}
-describe('FigmaAPI.createImage', () => {
- test('returns deterministic hash for same bytes', () => {
- const { figma } = setup()
- const a = figma.createImage(PNG_MAGIC)
- const b = figma.createImage(PNG_MAGIC)
- expect(a.hash).toBe(b.hash)
+describe('figma.createImage', () => {
+ test("gives Figma's Image: its hash, copies of its bytes, and its size", async () => {
+ expect(
+ await scriptResult(`
+ const image = figma.createImage(figma.base64Decode('${PNG_1X1}'))
+ const edited = await image.getBytesAsync()
+ edited[0] = 0
+ return {
+ hash: image.hash,
+ again: figma.createImage(figma.base64Decode('${PNG_1X1}')).hash,
+ byHash: figma.getImageByHash(image.hash)?.hash,
+ first: (await image.getBytesAsync())[0],
+ size: await image.getSizeAsync(),
+ png: await figma.createImage(figma.base64Decode('${PNG_3X2}')).getSizeAsync(),
+ gif: await figma.createImage(figma.base64Decode('${GIF_1X1}')).getSizeAsync(),
+ jpeg: await (async () => {
+ const jpeg = figma.createImage(figma.base64Decode('${JPEG_3X2}'))
+ return [jpeg.hash, await jpeg.getSizeAsync()]
+ })()
+ }
+ `)
+ ).toEqual({
+ hash: PNG_1X1_HASH,
+ again: PNG_1X1_HASH,
+ byHash: PNG_1X1_HASH,
+ first: 0x89,
+ size: { width: 1, height: 1 },
+ png: { width: 3, height: 2 },
+ gif: { width: 1, height: 1 },
+ jpeg: [JPEG_3X2_HASH, { width: 3, height: 2 }]
+ })
})
- test('different bytes produce different hashes', () => {
- const { figma } = setup()
- const a = figma.createImage(PNG_MAGIC)
- const b = figma.createImage(JPEG_MAGIC)
- expect(a.hash).not.toBe(b.hash)
+ test('keeps the bytes it was given when the script changes its array afterwards', async () => {
+ expect(
+ await scriptResult(`
+ const data = figma.base64Decode('${PNG_1X1}')
+ const image = figma.createImage(data)
+ data[0] = 0
+ return (await image.getBytesAsync())[0]
+ `)
+ ).toBe(0x89)
})
- test('stores bytes in graph.images', () => {
- const { graph, figma } = setup()
- const { hash } = figma.createImage(PNG_MAGIC)
- expect(graph.images.get(hash)).toEqual(PNG_MAGIC)
+ test('takes a PNG, JPEG, or GIF up to 4096 pixels a side, and finds only images it stored', async () => {
+ const png = (width: number, height: number, length = 26) =>
+ `new Uint8Array(${JSON.stringify(pngHeader(width, height).slice(0, length))})`
+ /** A 1 × 1 PNG header with `value` at `index`, breaking its signature or chunk type. */
+ const brokenPNG = (index: number, value: number) =>
+ `(() => { const bytes = ${png(1, 1)}; bytes[${index}] = ${value}; return figma.createImage(bytes).hash })()`
+ expect(
+ await scriptResult(
+ attempts({
+ side4096: `(await figma.createImage(${png(4096, 1)}).getSizeAsync()).width`,
+ wide: `figma.createImage(${png(4097, 1)}).hash`,
+ tall: `figma.createImage(${png(1, 4097)}).hash`,
+ empty: `figma.createImage(${png(0, 0)}).hash`,
+ noColorType: `figma.createImage(${png(1, 1, 25)}).hash`,
+ signature: brokenPNG(0, 0),
+ lineEnding: brokenPNG(4, 0),
+ chunkType: brokenPNG(12, 0x58),
+ webp: `figma.createImage(bytes('${WEBP_1X1}')).hash`,
+ junk: 'figma.createImage(new Uint8Array([1, 2, 3])).hash',
+ array: 'figma.createImage([1, 2, 3]).hash',
+ missing: 'figma.createImage().hash',
+ unknownHash: `figma.getImageByHash('${'a'.repeat(40)}')`,
+ numberHash: 'figma.getImageByHash(5)'
+ })
+ )
+ ).toEqual({
+ side4096: 4096,
+ wide: 'in createImage: Image is too large',
+ tall: 'in createImage: Image is too large',
+ empty: 'in createImage: Image type is unsupported',
+ noColorType: 'in createImage: Image type is unsupported',
+ signature: 'in createImage: Image type is unsupported',
+ lineEnding: 'in createImage: Image type is unsupported',
+ chunkType: 'in createImage: Image type is unsupported',
+ webp: 'in createImage: Image type is unsupported',
+ junk: 'in createImage: Image type is unsupported',
+ array:
+ 'in createImage: Property "createImage" failed validation: Expected Uint8Array, received array',
+ missing: 'in createImage: Property "createImage" failed validation: Required value missing',
+ unknownHash: null,
+ numberHash:
+ 'in getImageByHash: Property "getImageByHash" failed validation: Expected string, received number'
+ })
})
+})
+
+describe('figma.createImageAsync', () => {
+ /** A FigmaAPI whose host answers `fetch` with `respond`, and the URLs the host was asked for. */
+ function withHostFetch(respond: (url: string) => Promise<Response>) {
+ const requested: string[] = []
+ const figma = new FigmaAPI(new SceneGraph(), {
+ fetch: (url) => {
+ requested.push(url)
+ return respond(url)
+ }
+ })
+ return { figma, requested }
+ }
- test('hash is a 40-char hex string', () => {
- const { figma } = setup()
- const { hash } = figma.createImage(PNG_MAGIC)
- expect(hash).toHaveLength(40)
- expect(hash).toMatch(/^[0-9a-f]{40}$/)
+ test("loads an HTTP(S) URL through the host's fetch and reads a data URI itself", async () => {
+ const { figma, requested } = withHostFetch(
+ async () => new Response(new Uint8Array(toUint8Array(PNG_3X2)))
+ )
+ const result = await scriptResult(
+ `
+ const image = await figma.createImageAsync('https://example.com/photo.png')
+ const node = figma.createRectangle()
+ const { width, height } = await image.getSizeAsync()
+ node.resize(width, height)
+ node.fills = [{ type: 'IMAGE', imageHash: image.hash, scaleMode: 'FILL' }]
+ const data = await figma.createImageAsync('data:image/png;base64,${PNG_1X1}')
+ return {
+ size: [node.width, node.height],
+ fillIsImage: node.fills[0].imageHash === image.hash,
+ sameAsCreateImage: image.hash === figma.createImage(figma.base64Decode('${PNG_3X2}')).hash,
+ data: [data.hash, await data.getSizeAsync()]
+ }
+ `,
+ figma
+ )
+
+ expect(result).toEqual({
+ size: [3, 2],
+ fillIsImage: true,
+ sameAsCreateImage: true,
+ data: [PNG_1X1_HASH, { width: 1, height: 1 }]
+ })
+ expect(requested).toEqual(['https://example.com/photo.png'])
})
- test('empty data produces a valid hash', () => {
- const { figma } = setup()
- const { hash } = figma.createImage(new Uint8Array([]))
- expect(hash).toHaveLength(40)
- expect(hash).toMatch(/^[0-9a-f]{40}$/)
+ test('refuses what Figma refuses and stores nothing', async () => {
+ const { figma, requested } = withHostFetch(async (url) => {
+ if (url.endsWith('/offline.png')) throw new TypeError('Load failed')
+ if (url.endsWith('/page')) return new Response('<html></html>')
+ return new Response('Not found', { status: 404 })
+ })
+ const result = await scriptResult(
+ attempts({
+ missing: `figma.createImageAsync('https://example.com/missing.png')`,
+ offline: `figma.createImageAsync('https://example.com/offline.png')`,
+ page: `figma.createImageAsync('https://example.com/page')`,
+ relative: `figma.createImageAsync('/photo.png')`,
+ file: `figma.createImageAsync('file:///etc/hosts')`,
+ ftp: `figma.createImageAsync('ftp://example.com/photo.png')`,
+ text: `figma.createImageAsync('data:text/plain,hello')`,
+ webp: `figma.createImageAsync('data:image/webp;base64,${WEBP_1X1}')`,
+ number: 'figma.createImageAsync(5)'
+ }),
+ figma
+ )
+
+ const absolute = 'createImageAsync requires an absolute URL (http:// or https://) or a data URI'
+ expect(result).toEqual({
+ // Figma fetches through its own server, which answers 403 for a missing or non-image
+ // resource and for a host it cannot reach; a host fetch reports what actually happened.
+ missing: 'Unable to fetch image. Response status: 404',
+ offline: 'Unable to fetch image: Load failed',
+ page: 'Image type is unsupported',
+ relative: absolute,
+ file: absolute,
+ ftp: absolute,
+ text: 'Image type is unsupported',
+ webp: 'Image type is unsupported',
+ number:
+ 'in createImageAsync: Property "createImageAsync" failed validation: Expected string, received number'
+ })
+ expect(requested).toEqual([
+ 'https://example.com/missing.png',
+ 'https://example.com/offline.png',
+ 'https://example.com/page'
+ ])
+ expect(figma.graph.images.size).toBe(0)
+ })
+
+ test('stops reading a body that runs past the limit, whatever length it declares', async () => {
+ const chunk = new Uint8Array(1024 * 1024)
+ let sent = 0
+ let cancelled = false
+ const endless = new ReadableStream<Uint8Array>({
+ pull(controller) {
+ sent += chunk.byteLength
+ controller.enqueue(chunk)
+ },
+ cancel() {
+ cancelled = true
+ }
+ })
+ const { figma } = withHostFetch(async () => new Response(endless))
+ const result = await scriptResult(
+ attempts({ endless: `figma.createImageAsync('https://example.com/endless')` }),
+ figma
+ )
+
+ expect(result).toEqual({ endless: 'Image is too large' })
+ expect(cancelled).toBe(true)
+ expect(sent).toBeLessThanOrEqual(MAX_IMAGE_FETCH_BYTES + 2 * chunk.byteLength)
})
})
diff --git a/packages/core/tests/figma-api/plugin-lifecycle.test.ts b/packages/core/tests/figma-api/plugin-lifecycle.test.ts
new file mode 100644
index 000000000..136a263fa
--- /dev/null
+++ b/packages/core/tests/figma-api/plugin-lifecycle.test.ts
@@ -0,0 +1,36 @@
+import { expect, spyOn, test } from 'bun:test'
+
+import { scriptResult } from '#core-tests/helpers/script'
+
+import { FigmaAPI } from '@open-pencil/core/figma-api'
+import { SceneGraph } from '@open-pencil/scene-graph'
+
+// Figma refuses every API call after closePlugin, so Figma's docs end a plugin with
+// `figma.closePlugin(); return`. A script here is one call with nothing to close, and code after
+// closePlugin still runs, so this follows the documented shape instead.
+test('a script written as a Figma plugin keeps its edits through loadAllPagesAsync and closePlugin', async () => {
+ const figma = new FigmaAPI(new SceneGraph())
+ const notify = spyOn(figma, 'notify').mockImplementation(() => ({ cancel: () => undefined }))
+ try {
+ const result = await scriptResult(
+ `
+ async function main() {
+ await figma.loadAllPagesAsync()
+ const rect = figma.createRectangle()
+ rect.name = 'Card'
+ figma.closePlugin('Done')
+ return
+ }
+ await main()
+ return figma.currentPage.children.map((node) => node.name)
+ `,
+ figma
+ )
+
+ expect(result).toEqual(['Card'])
+ // Figma shows closePlugin's message as it shows figma.notify's.
+ expect(notify.mock.calls).toEqual([['Done']])
+ } finally {
+ notify.mockRestore()
+ }
+})
diff --git a/packages/core/tests/figma-api/util.test.ts b/packages/core/tests/figma-api/util.test.ts
new file mode 100644
index 000000000..45b5a49b9
--- /dev/null
+++ b/packages/core/tests/figma-api/util.test.ts
@@ -0,0 +1,182 @@
+import { describe, expect, test } from 'bun:test'
+
+import { scriptResult } from '#core-tests/helpers/script'
+
+// Expected values were recorded by running the same scripts in Figma.
+
+/** Runs `script` with `colors` and the util functions detached, as Figma's docs alias them. */
+function withColors(colors: unknown[], script: string) {
+ return scriptResult(`
+ const { rgb: toRGB, rgba: toRGBA, solidPaint } = figma.util
+ const colors = ${JSON.stringify(colors)}
+ const attempt = (call) => { try { call(); return null } catch (error) { return error.message } }
+ ${script}
+ `)
+}
+
+/** `colors` read by `figma.util.rgba`, each channel rounded to the precision Figma's agree to. */
+async function rgbaOf(colors: string[]) {
+ const result = await withColors(colors, 'return colors.map((color) => toRGBA(color))')
+ if (!Array.isArray(result)) return result
+ return result.map((color: Record<string, number>) =>
+ Object.fromEntries(Object.entries(color).map(([key, value]) => [key, Number(value.toFixed(3))]))
+ )
+}
+
+describe('figma.util', () => {
+ test('rgb reads hex and CSS colors and drops their alpha', async () => {
+ const colors = ['#FF00FF', '#f0f8', 'rgb(0 128 255 / 50%)', 'hsl(120 100% 25%)', ' red ']
+ expect(
+ await withColors(
+ [...colors, { r: 1, g: 0.5, b: 0, a: 0.2 }],
+ 'return colors.map((color) => toRGB(color))'
+ )
+ ).toEqual([
+ { r: 1, g: 0, b: 1 },
+ { r: 1, g: 0, b: 1 },
+ { r: 0, g: 128 / 255, b: 1 },
+ { r: 0, g: 0.5, b: 0 },
+ { r: 1, g: 0, b: 0 },
+ { r: 1, g: 0.5, b: 0 }
+ ])
+ })
+
+ test('rgba keeps the alpha, defaults it to 1, and takes an alpha that overrides it', async () => {
+ expect(
+ await withColors(
+ ['rgb(25% 25% 25% / 0.5)', '#00ff00', { r: 0, g: 0, b: 1 }, 'transparent'],
+ "return [...colors.map((color) => toRGBA(color)), toRGBA('#ff000080', 0.25)]"
+ )
+ ).toEqual([
+ { r: 0.25, g: 0.25, b: 0.25, a: 0.5 },
+ { r: 0, g: 1, b: 0, a: 1 },
+ { r: 0, g: 0, b: 1, a: 1 },
+ { r: 0, g: 0, b: 0, a: 0 },
+ { r: 1, g: 0, b: 0, a: 0.25 }
+ ])
+ })
+
+ test('clips colors outside sRGB channel by channel and reads lab() with a D65 white', async () => {
+ expect(
+ await rgbaOf([
+ 'color(display-p3 1 0 0)',
+ 'oklch(70% 0.2 30)',
+ 'oklab(0.7 0.3 0.1)',
+ 'lab(50% 40 59 / 0.5)',
+ 'rgb(300 0 0)',
+ 'rgb(0 0 0 / 150%)'
+ ])
+ ).toEqual([
+ { r: 1, g: 0, b: 0, a: 1 },
+ { r: 1, g: 0.38, b: 0.301, a: 1 },
+ { r: 1, g: 0, b: 0.29, a: 1 },
+ { r: 0.766, g: 0.34, b: 0.007, a: 0.5 },
+ { r: 1, g: 0, b: 0, a: 1 },
+ { r: 0, g: 0, b: 0, a: 1 }
+ ])
+ })
+
+ test('solidPaint makes a paint a layer takes, its opacity from the alpha', async () => {
+ expect(
+ await withColors(
+ [],
+ `const rect = figma.createRectangle()
+ rect.fills = [solidPaint('#FF0000')]
+ const [{ type, color: { r, g, b }, opacity }] = rect.fills
+ return { paint: solidPaint('#0000ff80'), fill: { type, color: { r, g, b }, opacity } }`
+ )
+ ).toEqual({
+ paint: { type: 'SOLID', color: { r: 0, g: 0, b: 1 }, opacity: 128 / 255 },
+ fill: { type: 'SOLID', color: { r: 1, g: 0, b: 0 }, opacity: 1 }
+ })
+ })
+
+ test("solidPaint keeps an existing paint's other properties and takes the new color and opacity", async () => {
+ expect(
+ await withColors(
+ [],
+ `const existing = { type: 'SOLID', color: { r: 0, g: 0, b: 0 }, opacity: 0.2, visible: false, blendMode: 'MULTIPLY' }
+ return [
+ solidPaint('#FF00FF88', existing),
+ solidPaint('#FF00FF', { opacity: 0.2, color: { r: 0, g: 1, b: 0 }, boundVariables: {} })
+ ]`
+ )
+ ).toEqual([
+ {
+ type: 'SOLID',
+ color: { r: 1, g: 0, b: 1 },
+ opacity: 0x88 / 255,
+ visible: false,
+ blendMode: 'MULTIPLY'
+ },
+ { type: 'SOLID', color: { r: 1, g: 0, b: 1 }, opacity: 1, boundVariables: {} }
+ ])
+ })
+
+ test('a color, alpha, or override it cannot take is refused with Figma’s message', async () => {
+ expect(
+ await withColors(
+ [
+ 'not a color',
+ 'lch(50% 70 50)',
+ 'rgb(none 0 0)',
+ 'rgb(255 0 0 / none)',
+ { r: 255, g: 0, b: 0 },
+ { r: 2, g: -1, b: 0 }
+ ],
+ `return [
+ attempt(() => toRGB(colors[0])),
+ attempt(() => toRGBA(colors[1])),
+ attempt(() => toRGB(colors[2])),
+ attempt(() => toRGBA(colors[3])),
+ attempt(() => solidPaint(colors[4])),
+ attempt(() => toRGB(colors[5])),
+ attempt(() => toRGB({ r: 1, g: 0, b: 0, x: 1 })),
+ attempt(() => toRGB(5)),
+ attempt(() => toRGB(null)),
+ attempt(() => toRGB()),
+ attempt(() => toRGBA('#fff', 2)),
+ attempt(() => toRGBA('#fff', -1)),
+ attempt(() => toRGBA('#fff', '0.5')),
+ attempt(() => solidPaint('#fff', { type: 'GRADIENT_LINEAR' })),
+ attempt(() => solidPaint('#fff', { foo: 1 })),
+ attempt(() => solidPaint('#fff', { visible: 'yes' })),
+ attempt(() => solidPaint('#fff', { blendMode: 'NOPE' })),
+ attempt(() => solidPaint('#fff', null))
+ ]`
+ )
+ ).toEqual([
+ 'in rgb: failed to parse color: not a color',
+ 'in rgba: failed to parse color: lch(50% 70 50)',
+ 'in rgb: failed to parse color: rgb(none 0 0)',
+ 'in rgba: failed to parse color: rgb(255 0 0 / none)',
+ 'in solidPaint: Property "color" failed validation: Too big: expected number to be <=1 at .r',
+ 'in rgb: Property "color" failed validation: Too big: expected number to be <=1 at .r\n' +
+ 'Too small: expected number to be >=0 at .g',
+ 'in rgb: Property "color" failed validation: Unrecognized key: "x"',
+ 'in rgb: Property "color" failed validation: Expected one of the following, but none matched:\n' +
+ ' Expected string, received number\n Expected object, received number',
+ 'in rgb: Property "color" failed validation: Expected one of the following, but none matched:\n' +
+ ' Expected string, received null\n Expected object, received null',
+ 'in rgb: Property "color" failed validation: Expected one of the following, but none matched:\n' +
+ ' Required value missing',
+ 'in rgba: Property "alphaOverride" failed validation: Too big: expected number to be <=1',
+ 'in rgba: Property "alphaOverride" failed validation: Too small: expected number to be >=0',
+ 'in rgba: Property "alphaOverride" failed validation: Expected number, received string',
+ 'in solidPaint: Property "SolidPaint" failed validation: Invalid input: expected "SOLID" at .type',
+ 'in solidPaint: Property "SolidPaint" failed validation: Unrecognized key: "foo"',
+ 'in solidPaint: Property "SolidPaint" failed validation: Expected boolean, received string at .visible',
+ 'in solidPaint: Property "SolidPaint" failed validation: Invalid option: expected one of ' +
+ '"PASS_THROUGH"|"NORMAL"|"DARKEN"|"MULTIPLY"|"LINEAR_BURN"|"COLOR_BURN"|"LIGHTEN"|"SCREEN"|' +
+ '"LINEAR_DODGE"|"COLOR_DODGE"|"OVERLAY"|"SOFT_LIGHT"|"HARD_LIGHT"|"DIFFERENCE"|"EXCLUSION"|' +
+ '"HUE"|"SATURATION"|"COLOR"|"LUMINOSITY" at .blendMode',
+ 'in solidPaint: Property "SolidPaint" failed validation: Expected object, received null'
+ ])
+ })
+
+ test('normalizeMarkdown, which has no rich-text editor to normalize for, is refused by name', async () => {
+ expect(
+ await withColors([], "return attempt(() => figma.util.normalizeMarkdown('# Title'))")
+ ).toEqual(expect.stringContaining('in normalizeMarkdown: OpenPencil does not support'))
+ })
+})
diff --git a/packages/core/tests/helpers/script.ts b/packages/core/tests/helpers/script.ts
new file mode 100644
index 000000000..9b395e5d1
--- /dev/null
+++ b/packages/core/tests/helpers/script.ts
@@ -0,0 +1,10 @@
+import { FigmaAPI } from '@open-pencil/core/figma-api'
+import { compileScript } from '@open-pencil/core/tools'
+import { SceneGraph } from '@open-pencil/scene-graph'
+
+/** What `code` gives back when run as a script: its result, or the message it stopped with. */
+export function scriptResult(code: string, figma = new FigmaAPI(new SceneGraph())): Promise<unknown> {
+ return compileScript(code)(figma).catch((error: unknown) =>
+ error instanceof Error ? error.message : error
+ )
+}
diff --git a/packages/docs/programmable/cli/scripting.md b/packages/docs/programmable/cli/scripting.md
index 79142390a..3f73de3c0 100644
--- a/packages/docs/programmable/cli/scripting.md
+++ b/packages/docs/programmable/cli/scripting.md
@@ -243,12 +243,15 @@ Common node properties are readable/writable through the proxy, including:
### Utilities
- `figma.mixed`
-- `figma.createImage(data)`
+- `figma.util.rgb(color)`, `figma.util.rgba(color, alphaOverride?)`, and `figma.util.solidPaint(color, overrides?)` read a hex or CSS color string (`rgb()`, `hsl()`, `lab()`, `oklab()`, `oklch()`, `color(display-p3 …)`, or a name), clipped to sRGB, or an `{ r, g, b, a? }` object with channels from 0 to 1; `solidPaint` takes its color and opacity from `color` and its other properties from `overrides`, such as an existing paint
+- `figma.createImage(data)` takes a PNG, JPEG, or GIF up to 4096 pixels a side and gives Figma's `Image`: its `hash`, `getBytesAsync()`, and `getSizeAsync()`; `figma.getImageByHash(hash)` gives a stored image back
+- `figma.createImageAsync(url)` loads an `http(s)://` URL or a data URI. The desktop app fetches through its native proxy, as Figma fetches through its servers; in the browser, the image's host must allow cross-origin requests
- `figma.loadFontAsync(fontName)` no-ops because OpenPencil does not gate text edits on plugin font loading
- `figma.listAvailableFontsAsync()` returns host-provided fonts when available
- `figma.getNodeByIdAsync(id)` and `instance.getMainComponentAsync()` resolve to the same nodes as `figma.getNodeById(id)` and `instance.mainComponent`, for scripts written for Figma's dynamic-page mode
- `figma.setCurrentPageAsync(page)` switches pages as setting `figma.currentPage` does, and `page.loadAsync()` resolves at once because every page is already loaded, for scripts written for Figma's dynamic-page mode
- `figma.notify(message)` logs a warning in headless mode
+- `figma.closePlugin(message?)` and `figma.loadAllPagesAsync()` let a script written as a Figma plugin run: nothing needs closing or loading, and `closePlugin` passes its message to `figma.notify`. Figma refuses every call after `closePlugin` while a script here keeps running, so follow it with `return` as Figma's docs do
- `instance.swapComponent(component)` points an instance at another component
- A layer inside an instance refuses `x`, `y`, `rotation`, `relativeTransform`, `constraints`, `isMask`, and `maskType` with Figma's error, such as `in set_x: This property cannot be overridden in an instance: relative-transform`; those always follow the component. Slot content keeps them, and setting one on a slot's default content makes the instance own the slot
- `component.createSlot()` adds a slot frame and its `SLOT` property; slot frames read `type: 'SLOT'`, `resetSlot()` brings back an instance slot's component content, and `limitViolations` lists the limits an instance slot breaks. `addComponentProperty` and `editComponentProperty` take a `description` and, for slots, `slotSettings`
@@ -259,6 +262,7 @@ Common node properties are readable/writable through the proxy, including:
These Figma APIs are not exposed as compatible helpers yet:
- `node.exportAsync()`
+- `figma.util.normalizeMarkdown()`, which fails because OpenPencil has no rich-text descriptions or annotations to normalize for
- Library variables, extended collections, and variable bindings on effects and layout grids
- Figma style APIs such as `figma.createPaintStyle()` / `figma.createTextStyle()`
- Full vector boolean operation parity
diff --git a/src/app/automation/bridge/figma-factory.ts b/src/app/automation/bridge/figma-factory.ts
index ae1173f75..6581c9a29 100644
--- a/src/app/automation/bridge/figma-factory.ts
+++ b/src/app/automation/bridge/figma-factory.ts
@@ -1,15 +1,23 @@
-import { FigmaAPI } from '@open-pencil/core/figma-api'
+import { FigmaAPI, MAX_IMAGE_FETCH_BYTES } from '@open-pencil/core/figma-api'
import { createCanvasKitRasterCodec } from '@open-pencil/core/io/formats/raster'
import { renderAutomationImage } from '@/app/automation/bridge/export-handlers'
import type { EditorStore } from '@/app/editor/active-store'
import { listFamilies, listFonts, loadFont } from '@/app/editor/fonts'
+import { createTauriFetch } from '@/app/tauri/http'
+import { IS_TAURI } from '@/constants'
+
+// Figma loads `createImageAsync` URLs through its own server; on desktop the native proxy does
+// the same, past CORS, which a browser cannot.
+const imageFetch = IS_TAURI
+ ? createTauriFetch({ maxResponseBytes: MAX_IMAGE_FETCH_BYTES })
+ : undefined
export function makeFigmaFromStore(
store: EditorStore,
pageId = store.state.currentPageId
): FigmaAPI {
- const api = new FigmaAPI(store.graph)
+ const api = new FigmaAPI(store.graph, { fetch: imageFetch })
api.setRenderer(store.renderer ?? null)
api.icons = store.iconProvider
api.theme = store.state.theme ?? 'light'
diff --git a/tests/engine/clipboard/figma/images.test.ts b/tests/engine/clipboard/figma/images.test.ts
index bd3b8e0b4..e5ecf8740 100644
--- a/tests/engine/clipboard/figma/images.test.ts
+++ b/tests/engine/clipboard/figma/images.test.ts
@@ -48,5 +48,5 @@ test('Figma clipboard embeds shared image bytes once with SHA-1 references', asy
expect(parsed.blobs[paint.image?.dataBlob ?? -1]).toEqual(bytes)
}
expect(nodes[0].fills[0].imageHash).toBe(hash)
- expect(graph.images.get(hash)).toBe(bytes)
+ expect(graph.images.get(hash)).toEqual(bytes)
})
diff --git a/tests/engine/clipboard/openpencil/images.test.ts b/tests/engine/clipboard/openpencil/images.test.ts
index 5192851ec..643708a40 100644
--- a/tests/engine/clipboard/openpencil/images.test.ts
+++ b/tests/engine/clipboard/openpencil/images.test.ts
@@ -4,7 +4,6 @@ import { deflateSync } from 'fflate'
import { fromUint8Array } from 'js-base64'
import { buildOpenPencilClipboardHTML, parseOpenPencilClipboard } from '@open-pencil/core/clipboard'
-import { FigmaAPI } from '@open-pencil/core/figma-api'
import { SceneGraph, type SceneNode } from '@open-pencil/scene-graph'
import {
getInstanceOverride,
@@ -12,6 +11,7 @@ import {
} from '@open-pencil/scene-graph/instances/overrides'
import { expectDefined } from '#tests/helpers/assert'
+import { storeImageBytes } from '#tests/helpers/scene'
describe('clipboard roundtrip with images', () => {
function graphWithImageNode(): {
@@ -23,8 +23,7 @@ describe('clipboard roundtrip with images', () => {
const graph = new SceneGraph()
const page = graph.getPages()[0]
const imageBytes = new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8])
- const figma = new FigmaAPI(graph)
- const { hash } = figma.createImage(imageBytes)
+ const hash = storeImageBytes(graph, imageBytes)
const node = graph.createNode('RECTANGLE', page.id, {
name: 'ImageRect',
@@ -120,12 +119,11 @@ describe('clipboard roundtrip with images', () => {
test('multiple image hashes in different nodes are all included', () => {
const graph = new SceneGraph()
const page = graph.getPages()[0]
- const figma = new FigmaAPI(graph)
const bytes1 = new Uint8Array([10, 20, 30])
const bytes2 = new Uint8Array([40, 50, 60])
- const { hash: hash1 } = figma.createImage(bytes1)
- const { hash: hash2 } = figma.createImage(bytes2)
+ const hash1 = storeImageBytes(graph, bytes1)
+ const hash2 = storeImageBytes(graph, bytes2)
const node1 = graph.createNode('RECTANGLE', page.id, {
name: 'Img1',
@@ -186,10 +184,9 @@ describe('clipboard roundtrip with images', () => {
test('child node image hashes are collected', () => {
const graph = new SceneGraph()
const page = graph.getPages()[0]
- const figma = new FigmaAPI(graph)
const bytes = new Uint8Array([99, 88, 77])
- const { hash } = figma.createImage(bytes)
+ const hash = storeImageBytes(graph, bytes)
const frame = graph.createNode('FRAME', page.id, { name: 'Parent', width: 200, height: 200 })
graph.createNode('RECTANGLE', frame.id, {
diff --git a/tests/engine/io/fig/export/images.test.ts b/tests/engine/io/fig/export/images.test.ts
index 21fd17fa0..24e46b28b 100644
--- a/tests/engine/io/fig/export/images.test.ts
+++ b/tests/engine/io/fig/export/images.test.ts
@@ -2,12 +2,12 @@ import { beforeAll, describe, expect, test } from 'bun:test'
import { unzipSync } from 'fflate'
-import { FigmaAPI } from '@open-pencil/core/figma-api'
import { exportFigFile, parseFigFile } from '@open-pencil/core/io/formats/fig'
import { initCodec } from '@open-pencil/kiwi/fig/codec'
import { SceneGraph } from '@open-pencil/scene-graph'
import { expectDefined } from '#tests/helpers/assert'
+import { storeImageBytes } from '#tests/helpers/scene'
describe('fig export/import with images', () => {
beforeAll(async () => {
@@ -17,10 +17,9 @@ describe('fig export/import with images', () => {
test('exported zip contains images entries', async () => {
const graph = new SceneGraph()
const page = graph.getPages()[0]
- const figma = new FigmaAPI(graph)
const bytes = new Uint8Array([0x89, 0x50, 0x4e, 0x47, 0x00, 0x01, 0x02, 0x03])
- const { hash } = figma.createImage(bytes)
+ const hash = storeImageBytes(graph, bytes)
graph.createNode('RECTANGLE', page.id, {
name: 'ImageNode',
@@ -63,12 +62,11 @@ describe('fig export/import with images', () => {
test('round-trip preserves images', async () => {
const graph = new SceneGraph()
const page = graph.getPages()[0]
- const figma = new FigmaAPI(graph)
const bytes1 = new Uint8Array([11, 22, 33, 44, 55])
const bytes2 = new Uint8Array([66, 77, 88, 99])
- const { hash: hash1 } = figma.createImage(bytes1)
- const { hash: hash2 } = figma.createImage(bytes2)
+ const hash1 = storeImageBytes(graph, bytes1)
+ const hash2 = storeImageBytes(graph, bytes2)
graph.createNode('RECTANGLE', page.id, {
name: 'Img1',
diff --git a/tests/helpers/scene.ts b/tests/helpers/scene.ts
index eb43c9aad..8c6c3d7f5 100644
--- a/tests/helpers/scene.ts
+++ b/tests/helpers/scene.ts
@@ -1,4 +1,5 @@
import { SceneGraph, type SceneNode } from '@open-pencil/scene-graph'
+import { computeImageHash } from '@open-pencil/scene-graph/images'
import type { Color } from '@open-pencil/scene-graph/primitives'
export function makeSceneGraph(pageName = 'Test'): SceneGraph {
@@ -11,6 +12,13 @@ export function firstPageId(graph: SceneGraph): string {
return graph.getPages()[0].id
}
+/** Stores `bytes` as an image under their hash, whatever they encode, and returns the hash. */
+export function storeImageBytes(graph: SceneGraph, bytes: Uint8Array): string {
+ const hash = computeImageHash(bytes)
+ graph.images.set(hash, bytes)
+ return hash
+}
+
export function addTestColorVariable(
graph: SceneGraph,
id: string,