figdriver 0.0.0-stage → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,129 @@
1
+ import { SYNTHETIC_TAGS } from "./layout";
2
+ import { textOf, type El, type Run, type TextEl } from "./snapshot";
3
+
4
+ const SYNTHETIC_ROLES = new Map(Object.entries(SYNTHETIC_TAGS));
5
+
6
+ const TAG_ROLES = new Map(
7
+ Object.entries({
8
+ h1: "Heading",
9
+ h2: "Heading",
10
+ h3: "Heading",
11
+ h4: "Heading",
12
+ h5: "Heading",
13
+ h6: "Heading",
14
+ p: "Paragraph",
15
+ a: "Link",
16
+ button: "Button",
17
+ nav: "Navigation",
18
+ ul: "List",
19
+ ol: "List",
20
+ li: "Item",
21
+ img: "Image",
22
+ svg: "Icon",
23
+ header: "Header",
24
+ footer: "Footer",
25
+ section: "Section",
26
+ article: "Card",
27
+ main: "Main",
28
+ }),
29
+ );
30
+
31
+ export const titleCase = (s: string) =>
32
+ s
33
+ .split(/[-_\s]+/)
34
+ .filter(Boolean)
35
+ .map((w) => w[0].toUpperCase() + w.slice(1))
36
+ .join(" ");
37
+
38
+ export function nameOf(el: El): string {
39
+ const synthetic = SYNTHETIC_ROLES.get(el.tag);
40
+
41
+ if (synthetic) return synthetic;
42
+
43
+ if (el.tag.startsWith("::")) return "Decoration";
44
+ const element = el.cls.find((c) => c.includes("__"));
45
+
46
+ if (element) return titleCase(element.split("__")[1].split("--")[0]);
47
+ const block = el.cls.find((c) => !c.includes("--"));
48
+
49
+ if (block) return titleCase(block);
50
+
51
+ return TAG_ROLES.get(el.tag) ?? (el.kind === "text" ? "Label" : "Frame");
52
+ }
53
+
54
+ const hostOf = (el: El, parent: El | undefined) => (el.tag === "#text" && parent ? parent : el);
55
+
56
+ /** Components name text layers by role so their properties read well; elsewhere a short text names itself. */
57
+ export function textName(el: TextEl, parent: El | undefined, library: boolean) {
58
+ const host = hostOf(el, parent);
59
+
60
+ const role = host.cls.some((c) => c.includes("__"))
61
+ ? nameOf(host)
62
+ : /^h\d$/.test(host.tag)
63
+ ? "Heading"
64
+ : host.tag === "p"
65
+ ? "Paragraph"
66
+ : "Label";
67
+
68
+ if (library) return role;
69
+ const text = textOf(el).replace(/\n/g, " ");
70
+
71
+ return text.length <= 32 ? text : role;
72
+ }
73
+
74
+ export function textRole(el: El, parent: El | undefined, r: Run) {
75
+ const host = hostOf(el, parent);
76
+
77
+ if (/^h\d$/.test(host.tag)) return "Heading";
78
+
79
+ if (host.tag === "button" || host.cls.some((c) => c === "button" || c.startsWith("button--"))) return "Button";
80
+
81
+ if (host.tag === "p" || host.tag === "li") return "Body";
82
+
83
+ if (host.tag === "a") return "Link";
84
+
85
+ if (r.upper) return r.letterSpacing > 0 ? "Eyebrow" : "Label";
86
+
87
+ return "Text";
88
+ }
89
+
90
+ /** 32-bit FNV-1a hex hash. */
91
+ export function fnv1a(input: string) {
92
+ let hash = 0x811c9dc5;
93
+
94
+ for (let i = 0; i < input.length; i++) {
95
+ hash ^= input.charCodeAt(i);
96
+ hash = Math.imul(hash, 0x01000193);
97
+ }
98
+
99
+ return (hash >>> 0).toString(16);
100
+ }
101
+
102
+ /** Safe, bounded filename stem for a captured image URL, hashing inline data/blob URIs and overly long paths. */
103
+ export function assetSlug(url: string, taken: Set<string>): string {
104
+ const hash = fnv1a(url).padStart(8, "0");
105
+ let base: string;
106
+
107
+ if (/^(data|blob):/i.test(url)) {
108
+ base = `inline-${hash}`;
109
+ } else {
110
+ const pathname = url
111
+ .replace(/^[a-z][a-z0-9+.-]*:\/\/[^/?#]*/i, "")
112
+ .replace(/[?#].*$/, "")
113
+ .replace(/^\/(assets\/)?/, "")
114
+ .replace(/\.\w+$/, "");
115
+
116
+ const cleaned = pathname.replace(/[^\w]+/g, "-").replace(/^-+|-+$/g, "");
117
+ base = !cleaned
118
+ ? `asset-${hash}`
119
+ : cleaned.length > 64
120
+ ? `${cleaned.slice(0, 48).replace(/-+$/, "")}-${hash}`
121
+ : cleaned;
122
+ }
123
+
124
+ let name = base;
125
+
126
+ for (let n = 2; taken.has(name); n++) name = `${base}-${n}`;
127
+
128
+ return name;
129
+ }
@@ -0,0 +1,328 @@
1
+ export type Outcome = "replace" | "refuse-other-page" | "refuse-edited" | "refuse-in-use" | "keep-and-draft" | "failed";
2
+
3
+ export type HookKey = "check" | "migrate" | "place" | "links" | "flows" | "hide" | "moved" | "remove" | "removed";
4
+
5
+ export type Audit = {
6
+ frames: number;
7
+ texts: number;
8
+ instances: number;
9
+ problems: {
10
+ framesWithoutAutoLayout: string[];
11
+ textsWithoutStyle: string[];
12
+ detachedInstances: string[];
13
+ rawPaintsOnTokenColors: string[];
14
+ /** Auto layout frames with a negative gap. */
15
+ negativeSpacing: string[];
16
+ /** Auto layout children that cover a sibling by more than 2px. */
17
+ overlappingSiblings: string[];
18
+ /** Prototype links to layers that no longer exist. */
19
+ brokenLinks: string[];
20
+ };
21
+ rawPaints: { translucentTokenColors: number; offToken: number; offTokenColors: string[] };
22
+ };
23
+
24
+ export type OwnedAudit = Audit & { owners: string[] };
25
+
26
+ export type ImportSummary = {
27
+ variables: number;
28
+ textStyles: number;
29
+ effectStyles: number;
30
+ components: number;
31
+ componentSets: number;
32
+ instances: number;
33
+ fallbacks: number;
34
+ fallbackRules: string[];
35
+ fallbackReasons: string[];
36
+ unknownTextProperties: string[];
37
+ dropped: string[];
38
+ lost: string[];
39
+ warnings: string[];
40
+ };
41
+
42
+ export type RunPage = { name: string; id: string | null };
43
+
44
+ export type Imported = ImportSummary & {
45
+ design: string;
46
+ owner: string;
47
+ outcome: Outcome;
48
+ committed: string[];
49
+ draft: { name: string; id: string } | null;
50
+ message?: string;
51
+ audit: OwnedAudit;
52
+ page: RunPage;
53
+ output: string[];
54
+ };
55
+
56
+ /** An alias names its target and, when read from a file, carries its id, so two variables of one name never swap. */
57
+ export type Value = string | number | boolean | { alias: string; id?: string };
58
+
59
+ export type Collection = {
60
+ name: string;
61
+ id: string;
62
+ modes: string[];
63
+ variables: {
64
+ name: string;
65
+ id: string;
66
+ type: "BOOLEAN" | "COLOR" | "EASING" | "FLOAT" | "STRING" | "TIMING";
67
+ values: Record<string, Value>;
68
+ scopes?: string[];
69
+ codeSyntax?: { WEB?: string; ANDROID?: string; iOS?: string };
70
+ }[];
71
+ };
72
+
73
+ export type PaintSummary =
74
+ | { color: string; variable?: string; visible?: false }
75
+ | { type: string; visible?: false; opacity?: number; stops?: string[]; image?: string | null; video?: string | null };
76
+
77
+ export type EffectSummary = {
78
+ type: string;
79
+ visible?: false;
80
+ color?: string;
81
+ offset?: [number, number];
82
+ radius?: number;
83
+ spread?: number;
84
+ };
85
+
86
+ export type Inventory = {
87
+ file: string;
88
+ pages: {
89
+ name: string;
90
+ id: string;
91
+ children?: { name: string; id: string; type: string }[];
92
+ flows?: { name: string; nodeId: string }[];
93
+ }[];
94
+ collections: Collection[];
95
+ styles: {
96
+ text: {
97
+ name: string;
98
+ id: string;
99
+ family: string;
100
+ style: string;
101
+ size: number;
102
+ lineHeight?: string;
103
+ letterSpacing?: string;
104
+ paragraphSpacing?: number;
105
+ textCase?: string;
106
+ textDecoration?: string;
107
+ variables?: Record<string, string | undefined>;
108
+ }[];
109
+ paint: { name: string; id: string; paints?: string | PaintSummary[] }[];
110
+ effect: { name: string; id: string; effects: EffectSummary[] }[];
111
+ };
112
+ components: {
113
+ name: string;
114
+ id: string;
115
+ page: string;
116
+ description?: string;
117
+ properties?: Record<
118
+ string,
119
+ { type: string; default: string | boolean; options?: string[]; preferredValues?: { type: string; key: string }[] }
120
+ >;
121
+ variants?: { name: string; id: string }[];
122
+ }[];
123
+ };
124
+
125
+ export type Layer = {
126
+ id: string;
127
+ type: string;
128
+ name: string;
129
+ visible?: false;
130
+ size?: [number, number];
131
+ at?: [number, number];
132
+ sizing?: [string, string];
133
+ layout?: {
134
+ mode: string;
135
+ gap?: number | [number, number];
136
+ grid?: [number, number];
137
+ padding?: number[];
138
+ align?: [string, string];
139
+ wrap?: true;
140
+ };
141
+ fills?: string | PaintSummary[];
142
+ strokes?: string | PaintSummary[];
143
+ strokeWeight?: number | string | [number, number, number, number];
144
+ radius?: number | string | [number, number, number, number];
145
+ opacity?: number;
146
+ effects?: string | EffectSummary[];
147
+ variables?: Record<string, string | undefined>;
148
+ references?: Record<string, string>;
149
+ text?: string;
150
+ textStyle?: string | (readonly [number, number, string | null | undefined])[];
151
+ font?: [string, string, number | "MIXED"];
152
+ main?: { name: string; id: string; remote?: true };
153
+ properties?: Record<string, string | boolean>;
154
+ /** With --include prototype. */
155
+ reactions?: {
156
+ trigger: string;
157
+ actions: { type: string; destination?: string; navigation?: string; transition?: string }[];
158
+ }[];
159
+ overflow?: string;
160
+ /** With --include handoff. */
161
+ devStatus?: { type: string; description?: string };
162
+ annotations?: { label?: string; properties?: string[] }[];
163
+ devResources?: { name: string; url: string }[];
164
+ /** With --include variables: each collection's name mapped to the mode the layer sets for it. */
165
+ explicitModes?: Record<string, string>;
166
+ /** With --include text-runs. */
167
+ runs?: {
168
+ start: number;
169
+ end: number;
170
+ font?: [string, string, number];
171
+ style?: string;
172
+ fills?: PaintSummary[];
173
+ decoration?: string;
174
+ link?: string;
175
+ }[];
176
+ /** With --include grids. */
177
+ layoutGrids?: object[];
178
+ constraints?: { horizontal: string; vertical: string };
179
+ clipsContent?: boolean;
180
+ blendMode?: string;
181
+ rotation?: number;
182
+ bounds?: { minW?: number; maxW?: number; minH?: number; maxH?: number };
183
+ dashPattern?: number[];
184
+ strokeAlign?: string;
185
+ /** With --include vectors. */
186
+ vectorPaths?: string[];
187
+ /** FigJam and Slides nodes describe themselves without --include. */
188
+ sticky?: { text: string; authorVisible?: boolean; authorName?: string };
189
+ connector?: { text?: string; start?: string; end?: string };
190
+ /** A FigJam shape with text: `kind` is its shape type, such as ROUNDED_RECTANGLE. */
191
+ diagram?: { kind: string; text: string };
192
+ table?: { rows: number; cols: number; cells?: string[][] };
193
+ slide?: { skipped?: boolean; row?: number; col?: number };
194
+ children?: Layer[];
195
+ childCount?: number;
196
+ };
197
+
198
+ export type InspectInclude = "prototype" | "handoff" | "variables" | "text-runs" | "grids" | "vectors" | "all";
199
+
200
+ export type InspectOptions = { include?: InspectInclude[]; expandInstances?: boolean };
201
+
202
+ /** Filters are ANDed. `page` is a page's name or id, or "all"; without `page` or `node` the current page is searched. */
203
+ export type FindQuery = {
204
+ page?: string;
205
+ node?: string;
206
+ name?: string;
207
+ type?: string;
208
+ text?: string;
209
+ component?: string;
210
+ limit?: number;
211
+ };
212
+
213
+ /** `path` is the names of the layer's ancestors below its page and its own, joined with " / ". */
214
+ export type FindMatch = {
215
+ id: string;
216
+ type: string;
217
+ name: string;
218
+ page: string;
219
+ path: string;
220
+ size?: [number, number];
221
+ text?: string;
222
+ main?: string;
223
+ properties?: Record<string, string | boolean>;
224
+ };
225
+
226
+ export type FindResults = { matches: FindMatch[]; total: number; truncated: boolean };
227
+
228
+ export type EditorCapabilities = {
229
+ write: boolean;
230
+ variables: boolean;
231
+ components: boolean;
232
+ slides: boolean;
233
+ figjam: boolean;
234
+ devMode: boolean;
235
+ buzz: boolean;
236
+ };
237
+
238
+ /** A color is #rrggbb or #rrggbbaa; an alias names a variable of the plan or, failing that, any local variable of its type. */
239
+ export type TokenImportVariable = {
240
+ name: string;
241
+ type: "COLOR" | "FLOAT";
242
+ values: Record<string, string | number | { alias: string }>;
243
+ scopes?: string[];
244
+ codeSyntaxWeb?: string;
245
+ };
246
+
247
+ /** `modes[0]` fills the collection's default mode, whatever its name; other modes match existing ones by name or are added. */
248
+ export type TokenImportPlan = { collection: string; modes: string[]; variables: TokenImportVariable[] };
249
+
250
+ export type TokenImportSummary = {
251
+ collection: string;
252
+ created: number;
253
+ updated: number;
254
+ modes: string[];
255
+ warnings: string[];
256
+ };
257
+
258
+ export type ActiveUserRef = { id: string | null; name: string; sessionId: number };
259
+
260
+ export type TabStatus = {
261
+ file: string;
262
+ editor: string;
263
+ page: { name: string; id: string };
264
+ missing: string | null;
265
+ me: string | null;
266
+ users: string[] | null;
267
+ /** Empty unless asked for: listing owners loads every page. */
268
+ owners: string[];
269
+ pageCount: number;
270
+ capabilities: EditorCapabilities;
271
+ };
272
+
273
+ export type ExportFormat = "png" | "svg" | "pdf" | "jpg";
274
+
275
+ /** `render` includes what paints outside a node, such as a drop shadow; `layout` clips the export to the node's own box. */
276
+ export type ExportBounds = "render" | "layout";
277
+
278
+ export type ExportOptions = { scale?: number; format?: ExportFormat; bounds?: ExportBounds };
279
+
280
+ /** `data` is the exported file, base64-encoded, in `format`. */
281
+ export type ScreenShot = { name: string; id: string; data: string; format: ExportFormat };
282
+
283
+ export type PageFrames = { page: { name: string; id: string }; shots: ScreenShot[] };
284
+
285
+ export type PageLayers = { page: { name: string; id: string }; layers: Layer[] };
286
+
287
+ export type SectionShot = {
288
+ name: string;
289
+ id: string;
290
+ box: [number, number, number, number];
291
+ /** The color the section sat on in the page, as hex, so a section with transparent parts compares against it instead of white. */
292
+ bg?: string;
293
+ png: string;
294
+ };
295
+
296
+ /**
297
+ * `run` audits figdriver's own output. `authored` audits a person's file: no auto layout demands, library instances are fine, and every
298
+ * local color variable counts as a token.
299
+ */
300
+ export type AuditRules = "run" | "authored";
301
+
302
+ /** `layers` counts the page's top-level layers audited. */
303
+ export type PageAudit = OwnedAudit & { page: { name: string; id: string }; layers: number };
304
+
305
+ export type DesignTree = {
306
+ variables: readonly object[];
307
+ textStyles: object[];
308
+ paintStyles: object[];
309
+ effectStyles: object[];
310
+ flows: string[];
311
+ nodes: object[];
312
+ };
313
+
314
+ export type InspectApi = {
315
+ status(page?: string | null, missing?: boolean, includeOwners?: boolean): Promise<TabStatus>;
316
+ audit(design: string | null, rules?: AuditRules): Promise<OwnedAudit>;
317
+ auditPage(page: string, rules: AuditRules): Promise<PageAudit>;
318
+ screens(design: string | null, options: ExportOptions): Promise<ScreenShot[]>;
319
+ pageFrames(page: string | null, options: ExportOptions): Promise<PageFrames>;
320
+ nodes(ids: string[], options: ExportOptions, selection?: boolean): Promise<ScreenShot[]>;
321
+ sections(ids: string[]): Promise<SectionShot[]>;
322
+ tree(): Promise<DesignTree>;
323
+ inventory(): Promise<Inventory>;
324
+ layers(ids: string[], selection: boolean, depth: number, options?: InspectOptions): Promise<Layer[]>;
325
+ pageLayers(page: string, depth: number, options?: InspectOptions): Promise<PageLayers>;
326
+ find(query: FindQuery): Promise<FindResults>;
327
+ importTokens(plan: TokenImportPlan): Promise<TokenImportSummary>;
328
+ };
@@ -0,0 +1,130 @@
1
+ import type { HookKey, Outcome } from "./protocol";
2
+ import { truncateList } from "./snapshot";
3
+
4
+ export type { Outcome };
5
+
6
+ export type Observed = {
7
+ otherPage?: string;
8
+ edited: boolean;
9
+ /** Where the output was edited, such as "Pricing › Title", when the edits are to layers. */
10
+ edits?: string[];
11
+ inUse: string[];
12
+ ambiguous: string[];
13
+ clean: boolean;
14
+ force: boolean;
15
+ };
16
+
17
+ export function decide({ otherPage, edited, inUse, ambiguous, clean, force }: Observed): Exclude<Outcome, "failed"> {
18
+ if (otherPage && !force) return "refuse-other-page";
19
+
20
+ if (edited && !force) return "refuse-edited";
21
+
22
+ if (inUse.length && !force) return "refuse-in-use";
23
+
24
+ return clean && !ambiguous.length ? "replace" : "keep-and-draft";
25
+ }
26
+
27
+ export type Use = { what: string; where: string; key: string | null };
28
+
29
+ const KINDS = /^(component|variable|style|screen):/;
30
+
31
+ /**
32
+ * The key a part has after the spec's `renames`, such as `component:Button/Style=Main` for `component:Button/Style=Primary`. A rename
33
+ * names a part by its key or by its bare name. `back` maps a renamed key to its old one, to undo a migration.
34
+ */
35
+ export function renamer(renames: Record<string, string> = {}, back = false) {
36
+ const pairs = Object.entries(renames).map(([from, to]) => (back ? [to, from] : [from, to]));
37
+
38
+ return (key: string) => {
39
+ const kind = key.slice(0, key.indexOf(":"));
40
+ const keyed = (name: string) => (KINDS.test(name) ? name : `${kind}:${name}`);
41
+ const hit = pairs.find(([from]) => keyed(from) === key);
42
+
43
+ return hit ? keyed(hit[1]) : key;
44
+ };
45
+ }
46
+
47
+ export function blockers(
48
+ uses: Use[],
49
+ counterparts: string[],
50
+ previous: string[],
51
+ rename: (key: string) => string = (key) => key,
52
+ ) {
53
+ const count = (keys: string[]) => keys.reduce((n, k) => n.set(k, (n.get(k) ?? 0) + 1), new Map<string, number>());
54
+
55
+ const fresh = count(counterparts),
56
+ old = count(previous);
57
+
58
+ const lines = (list: Use[]) => [...new Set(list.map((u) => `${u.where} uses ${u.what}`))];
59
+ const movable = uses.filter((u) => u.key && fresh.has(rename(u.key)));
60
+
61
+ return {
62
+ inUse: lines(uses.filter((u) => !movable.includes(u))),
63
+ ambiguous: lines(movable.filter((u) => fresh.get(rename(u.key!))! > 1 || (old.get(u.key!) ?? 0) > 1)),
64
+ };
65
+ }
66
+
67
+ export const drafted = (name: string) => `${name} (figdriver draft)`;
68
+
69
+ export function why(
70
+ outcome: Exclude<Outcome, "replace" | "failed">,
71
+ name: string,
72
+ { otherPage, inUse, ambiguous, edits = [] }: Pick<Observed, "otherPage" | "inUse" | "ambiguous" | "edits">,
73
+ ) {
74
+ const list = (lines: string[]) => truncateList(lines, 5, "; ");
75
+
76
+ const kept = `The new build is on page "${drafted(name)}", and the next run of ${name} replaces it.`;
77
+
78
+ const reason = {
79
+ "refuse-other-page": `Page "${otherPage}" already holds ${name}'s output, and shares its variables and styles. Run on that page, or give the spec a new name. --force builds here anyway and replaces those variables and styles.`,
80
+ "refuse-edited": `${name}'s output on this page changed since figdriver built it${edits.length ? ` (edited: ${list(edits)})` : ""}. To keep those edits, give the spec a new name and run again. --force replaces it, edits included.`,
81
+ "refuse-in-use": `Layers outside ${name}'s output use parts of it that the new build has nothing of the same name for: ${list(inUse)}. Restore those names in the spec, map each old name to its new one in the spec's renames, or move the layers off them. --force replaces it anyway, and those layers keep pointing at the removed parts.`,
82
+ "keep-and-draft": ambiguous.length
83
+ ? `Layers outside ${name}'s output use parts that share their name with another part of the old output or the new build, so figdriver cannot tell which new part takes each one's place: ${list(ambiguous)}. ${name}'s previous output was left as it was. Give those parts names of their own, or move the layers off them, and run again.`
84
+ : `The build has the problems listed above, so ${name}'s previous output was left as it was. Fix the spec and run again.`,
85
+ }[outcome];
86
+
87
+ return `${reason} ${kept}`;
88
+ }
89
+
90
+ export function cleanup<P>(drafts: { page: P; unchanged: boolean }[], used: boolean) {
91
+ const remove = used ? [] : drafts.flatMap((d) => (d.unchanged ? [d.page] : []));
92
+ const letGo = drafts.flatMap((d) => (remove.includes(d.page) ? [] : [d.page]));
93
+
94
+ return { remove, letGo, removeParts: !letGo.length };
95
+ }
96
+
97
+ export type Step = { key: HookKey; done: string; run(): void | Promise<void>; undo(): void | Promise<void> };
98
+
99
+ export async function transact(
100
+ steps: Step[],
101
+ hook: (key: HookKey) => void | Promise<void>,
102
+ last: () => void | Promise<void>,
103
+ ) {
104
+ const taken: Step[] = [];
105
+
106
+ try {
107
+ for (const step of steps) {
108
+ await hook(step.key);
109
+ // Listed before it runs, so a step that throws part way, such as a migration after its first move, is undone too.
110
+ taken.push(step);
111
+ await step.run();
112
+ }
113
+
114
+ await last();
115
+
116
+ return { stayed: taken.map((s) => s.done) };
117
+ } catch (error) {
118
+ while (taken.length) {
119
+ try {
120
+ await taken[taken.length - 1].undo();
121
+ } catch {
122
+ break;
123
+ }
124
+
125
+ taken.pop();
126
+ }
127
+
128
+ return { stayed: taken.map((s) => s.done), error };
129
+ }
130
+ }