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.
- package/CHANGELOG.md +86 -0
- package/LICENSE +21 -0
- package/README.md +87 -2
- package/cli/result.ts +231 -0
- package/dist/cli.js +4125 -0
- package/index.d.ts +12 -0
- package/index.js +8 -0
- package/package.json +78 -4
- package/src/core/color.ts +435 -0
- package/src/core/css.ts +668 -0
- package/src/core/foundations.ts +389 -0
- package/src/core/json.d.ts +4 -0
- package/src/core/layout.ts +684 -0
- package/src/core/naming.ts +129 -0
- package/src/core/protocol.ts +328 -0
- package/src/core/rerun.ts +130 -0
- package/src/core/reuse.ts +149 -0
- package/src/core/snapshot.ts +88 -0
- package/src/core/spec.ts +167 -0
- package/src/core/text.ts +37 -0
- package/src/core/tokens.ts +77 -0
- package/src/core/types.ts +181 -0
- package/src/core/users.ts +17 -0
- package/src/figma/helpers.ts +238 -0
- package/src/figma/import.ts +962 -0
- package/src/figma/inspect.ts +254 -0
- package/src/figma/kit.ts +562 -0
- package/src/figma/migrate.ts +301 -0
- package/src/figma/owned.ts +56 -0
- package/src/figma/read.ts +618 -0
- package/src/figma/rerun.ts +387 -0
- package/src/figma/review.ts +481 -0
- package/src/figma/tokens.ts +97 -0
- package/src/page/capture.ts +999 -0
package/dist/cli.js
ADDED
|
@@ -0,0 +1,4125 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
|
|
3
|
+
// cli/main.ts
|
|
4
|
+
import { readFileSync as readFileSync8, realpathSync as realpathSync3 } from "node:fs";
|
|
5
|
+
import { resolve as resolve6 } from "node:path";
|
|
6
|
+
import { fileURLToPath } from "node:url";
|
|
7
|
+
import { parseArgs } from "node:util";
|
|
8
|
+
|
|
9
|
+
// src/core/color.ts
|
|
10
|
+
function times(m, v) {
|
|
11
|
+
const dot = (row) => row[0] * v[0] + row[1] * v[1] + row[2] * v[2];
|
|
12
|
+
return [dot(m[0]), dot(m[1]), dot(m[2])];
|
|
13
|
+
}
|
|
14
|
+
var product = (a, b) => {
|
|
15
|
+
const column = (j) => [b[0][j], b[1][j], b[2][j]];
|
|
16
|
+
const [c0, c1, c2] = [times(a, column(0)), times(a, column(1)), times(a, column(2))];
|
|
17
|
+
return [
|
|
18
|
+
[c0[0], c1[0], c2[0]],
|
|
19
|
+
[c0[1], c1[1], c2[1]],
|
|
20
|
+
[c0[2], c1[2], c2[2]]
|
|
21
|
+
];
|
|
22
|
+
};
|
|
23
|
+
function inverse([[a, b, c], [d, e, f], [g, h, i]]) {
|
|
24
|
+
const det = a * (e * i - f * h) - b * (d * i - f * g) + c * (d * h - e * g);
|
|
25
|
+
return [
|
|
26
|
+
[(e * i - f * h) / det, (c * h - b * i) / det, (b * f - c * e) / det],
|
|
27
|
+
[(f * g - d * i) / det, (a * i - c * g) / det, (c * d - a * f) / det],
|
|
28
|
+
[(d * h - e * g) / det, (b * g - a * h) / det, (a * e - b * d) / det]
|
|
29
|
+
];
|
|
30
|
+
}
|
|
31
|
+
var map = (v, f) => [f(v[0]), f(v[1]), f(v[2])];
|
|
32
|
+
var mirrored = (f) => (c) => Math.sign(c) * f(Math.abs(c));
|
|
33
|
+
var srgbLinear = mirrored((c) => c <= 0.04045 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4);
|
|
34
|
+
var srgbGamma = mirrored((c) => c <= 31308e-7 ? 12.92 * c : 1.055 * c ** (1 / 2.4) - 0.055);
|
|
35
|
+
var same = (c) => c;
|
|
36
|
+
var XYZ_FROM_SRGB = [
|
|
37
|
+
[0.41239079926595934, 0.357584339383878, 0.1804807884018343],
|
|
38
|
+
[0.21263900587151027, 0.715168678767756, 0.07219231536073371],
|
|
39
|
+
[0.01933081871559182, 0.11919477979462598, 0.9505321522496607]
|
|
40
|
+
];
|
|
41
|
+
var SRGB_FROM_XYZ = inverse(XYZ_FROM_SRGB);
|
|
42
|
+
var D65_FROM_D50 = [
|
|
43
|
+
[0.955473421488075, -0.02309845494876471, 0.06325924320057072],
|
|
44
|
+
[-0.0283697093338637, 1.0099953980813041, 0.021041441191917323],
|
|
45
|
+
[0.012314014864481998, -0.020507649298898964, 1.330365926242124]
|
|
46
|
+
];
|
|
47
|
+
var D50_FROM_D65 = inverse(D65_FROM_D50);
|
|
48
|
+
var IDENTITY = [
|
|
49
|
+
[1, 0, 0],
|
|
50
|
+
[0, 1, 0],
|
|
51
|
+
[0, 0, 1]
|
|
52
|
+
];
|
|
53
|
+
var clean = ([x, y, z]) => [x || 0, y || 0, z || 0];
|
|
54
|
+
function inSpace(c, space) {
|
|
55
|
+
if (c.space === space) return c.coords;
|
|
56
|
+
const out = space.to(c.space.from(clean(c.coords)));
|
|
57
|
+
if (space.hue && space.hue.powerless(out)) out[space.hue.at] = NaN;
|
|
58
|
+
return out;
|
|
59
|
+
}
|
|
60
|
+
function rgbSpace(toXyz, linear, gamma) {
|
|
61
|
+
const toSrgb = product(SRGB_FROM_XYZ, toXyz);
|
|
62
|
+
const fromSrgb = inverse(toSrgb);
|
|
63
|
+
return { from: (v) => times(toSrgb, map(v, linear)), to: (v) => map(times(fromSrgb, v), gamma) };
|
|
64
|
+
}
|
|
65
|
+
var REC2020 = { alpha: 1.09929682680944, beta: 0.018053968510807 };
|
|
66
|
+
var D50_WHITE = [0.3457 / 0.3585, 1, (1 - 0.3457 - 0.3585) / 0.3585];
|
|
67
|
+
var LAB = { k: 24389 / 27, e: 216 / 24389 };
|
|
68
|
+
var lab = {
|
|
69
|
+
from([L, a, b]) {
|
|
70
|
+
const fy = (L + 16) / 116;
|
|
71
|
+
const cube = (f) => f ** 3 > LAB.e ? f ** 3 : (116 * f - 16) / LAB.k;
|
|
72
|
+
const xyz = [cube(a / 500 + fy), L > LAB.k * LAB.e ? fy ** 3 : L / LAB.k, cube(fy - b / 200)];
|
|
73
|
+
return times(SRGB_FROM_XYZ, times(D65_FROM_D50, [xyz[0] * D50_WHITE[0], xyz[1], xyz[2] * D50_WHITE[2]]));
|
|
74
|
+
},
|
|
75
|
+
to(v) {
|
|
76
|
+
const xyz = times(D50_FROM_D65, times(XYZ_FROM_SRGB, v));
|
|
77
|
+
const f = (c) => c > LAB.e ? Math.cbrt(c) : (LAB.k * c + 16) / 116;
|
|
78
|
+
const [fx, fy, fz] = [f(xyz[0] / D50_WHITE[0]), f(xyz[1]), f(xyz[2] / D50_WHITE[2])];
|
|
79
|
+
return [116 * fy - 16, 500 * (fx - fy), 200 * (fy - fz)];
|
|
80
|
+
}
|
|
81
|
+
};
|
|
82
|
+
var LMS_FROM_OKLAB = [
|
|
83
|
+
[1, 0.3963377774, 0.2158037573],
|
|
84
|
+
[1, -0.1055613458, -0.0638541728],
|
|
85
|
+
[1, -0.0894841775, -1.291485548]
|
|
86
|
+
];
|
|
87
|
+
var OKLAB_FROM_LMS = inverse(LMS_FROM_OKLAB);
|
|
88
|
+
var SRGB_FROM_LMS = [
|
|
89
|
+
[4.0767416621, -3.3077115913, 0.2309699292],
|
|
90
|
+
[-1.2684380046, 2.6097574011, -0.3413193965],
|
|
91
|
+
[-0.0041960863, -0.7034186147, 1.707614701]
|
|
92
|
+
];
|
|
93
|
+
var LMS_FROM_SRGB = inverse(SRGB_FROM_LMS);
|
|
94
|
+
var oklab = {
|
|
95
|
+
from: (v) => times(
|
|
96
|
+
SRGB_FROM_LMS,
|
|
97
|
+
map(times(LMS_FROM_OKLAB, v), (c) => c ** 3)
|
|
98
|
+
),
|
|
99
|
+
to: (v) => times(OKLAB_FROM_LMS, map(times(LMS_FROM_SRGB, v), Math.cbrt))
|
|
100
|
+
};
|
|
101
|
+
var radians = (deg) => deg * Math.PI / 180;
|
|
102
|
+
var turn = (h) => (h % 360 + 360) % 360;
|
|
103
|
+
function polar(base, gray) {
|
|
104
|
+
return {
|
|
105
|
+
from: ([L, C, H]) => base.from([L, C * Math.cos(radians(H)), C * Math.sin(radians(H))]),
|
|
106
|
+
to(v) {
|
|
107
|
+
const [L, a, b] = base.to(v);
|
|
108
|
+
return [L, Math.hypot(a, b), (Math.atan2(b, a) * 180 / Math.PI + 360) % 360];
|
|
109
|
+
},
|
|
110
|
+
hue: { at: 2, powerless: ([, C]) => C < gray }
|
|
111
|
+
};
|
|
112
|
+
}
|
|
113
|
+
function fromHsl([h, s, l]) {
|
|
114
|
+
const hue = turn(h);
|
|
115
|
+
const k = (n) => (n + hue / 30) % 12;
|
|
116
|
+
const f = (n) => l - s * Math.min(l, 1 - l) * Math.max(-1, Math.min(k(n) - 3, 9 - k(n), 1));
|
|
117
|
+
return [f(0), f(8), f(4)];
|
|
118
|
+
}
|
|
119
|
+
function toHsl([r, g, b]) {
|
|
120
|
+
const max = Math.max(r, g, b), min = Math.min(r, g, b), d = max - min, l = (max + min) / 2;
|
|
121
|
+
const s = d === 0 || l === 0 || l === 1 ? 0 : (max - l) / Math.min(l, 1 - l);
|
|
122
|
+
const h = d === 0 ? 0 : max === r ? ((g - b) / d + 6) % 6 : max === g ? (b - r) / d + 2 : (r - g) / d + 4;
|
|
123
|
+
return [h * 60, s, l];
|
|
124
|
+
}
|
|
125
|
+
var hsl = {
|
|
126
|
+
from: (v) => map(fromHsl(v), srgbLinear),
|
|
127
|
+
to: (v) => toHsl(map(v, srgbGamma)),
|
|
128
|
+
hue: { at: 0, powerless: ([, s]) => s < 1e-6 }
|
|
129
|
+
};
|
|
130
|
+
var hwb = {
|
|
131
|
+
from([h, w, b]) {
|
|
132
|
+
if (w + b >= 1) return map([w / (w + b), w / (w + b), w / (w + b)], srgbLinear);
|
|
133
|
+
return map(
|
|
134
|
+
map(fromHsl([h, 1, 0.5]), (c) => c * (1 - w - b) + w),
|
|
135
|
+
srgbLinear
|
|
136
|
+
);
|
|
137
|
+
},
|
|
138
|
+
to(v) {
|
|
139
|
+
const rgb2 = map(v, srgbGamma);
|
|
140
|
+
return [toHsl(rgb2)[0], Math.min(...rgb2), 1 - Math.max(...rgb2)];
|
|
141
|
+
},
|
|
142
|
+
hue: { at: 0, powerless: ([, w, b]) => w + b >= 1 - 1e-6 }
|
|
143
|
+
};
|
|
144
|
+
var SRGB = { from: (v) => map(v, srgbLinear), to: (v) => map(v, srgbGamma) };
|
|
145
|
+
var SPACES = /* @__PURE__ */ new Map([
|
|
146
|
+
["srgb", SRGB],
|
|
147
|
+
["srgb-linear", { from: (v) => v, to: (v) => v }],
|
|
148
|
+
[
|
|
149
|
+
"display-p3",
|
|
150
|
+
rgbSpace(
|
|
151
|
+
[
|
|
152
|
+
[0.4865709486482162, 0.26566769316909306, 0.1982172852343625],
|
|
153
|
+
[0.2289745640697488, 0.6917385218365064, 0.079286914093745],
|
|
154
|
+
[0, 0.04511338185890264, 1.043944368900976]
|
|
155
|
+
],
|
|
156
|
+
srgbLinear,
|
|
157
|
+
srgbGamma
|
|
158
|
+
)
|
|
159
|
+
],
|
|
160
|
+
[
|
|
161
|
+
"a98-rgb",
|
|
162
|
+
rgbSpace(
|
|
163
|
+
[
|
|
164
|
+
[0.5766690429101305, 0.1855582379065463, 0.1882286462349947],
|
|
165
|
+
[0.29734497525053605, 0.6273635662554661, 0.0752914584939979],
|
|
166
|
+
[0.02703136138641234, 0.07068885253582723, 0.9913375368376388]
|
|
167
|
+
],
|
|
168
|
+
mirrored((c) => c ** (563 / 256)),
|
|
169
|
+
mirrored((c) => c ** (256 / 563))
|
|
170
|
+
)
|
|
171
|
+
],
|
|
172
|
+
[
|
|
173
|
+
"prophoto-rgb",
|
|
174
|
+
rgbSpace(
|
|
175
|
+
product(D65_FROM_D50, [
|
|
176
|
+
[0.7977604896723027, 0.13518583717574031, 0.0313493495815248],
|
|
177
|
+
[0.2880711282292934, 0.7118432178101014, 8565396060525902e-20],
|
|
178
|
+
[0, 0, 0.8251046025104602]
|
|
179
|
+
]),
|
|
180
|
+
mirrored((c) => c <= 16 / 512 ? c / 16 : c ** 1.8),
|
|
181
|
+
mirrored((c) => c < 1 / 512 ? 16 * c : c ** (1 / 1.8))
|
|
182
|
+
)
|
|
183
|
+
],
|
|
184
|
+
[
|
|
185
|
+
"rec2020",
|
|
186
|
+
rgbSpace(
|
|
187
|
+
[
|
|
188
|
+
[0.6369580483012914, 0.14461690358620832, 0.1688809751641721],
|
|
189
|
+
[0.2627002120112671, 0.6779980715188708, 0.05930171646986196],
|
|
190
|
+
[0, 0.028072693049087428, 1.060985057710791]
|
|
191
|
+
],
|
|
192
|
+
mirrored((c) => c < REC2020.beta * 4.5 ? c / 4.5 : ((c + REC2020.alpha - 1) / REC2020.alpha) ** (1 / 0.45)),
|
|
193
|
+
mirrored((c) => c < REC2020.beta ? 4.5 * c : REC2020.alpha * c ** 0.45 - (REC2020.alpha - 1))
|
|
194
|
+
)
|
|
195
|
+
],
|
|
196
|
+
["xyz", rgbSpace(IDENTITY, same, same)],
|
|
197
|
+
["xyz-d65", rgbSpace(IDENTITY, same, same)],
|
|
198
|
+
["xyz-d50", rgbSpace(D65_FROM_D50, same, same)],
|
|
199
|
+
["lab", lab],
|
|
200
|
+
["lch", polar(lab, 15e-4)],
|
|
201
|
+
["oklab", oklab],
|
|
202
|
+
["oklch", polar(oklab, 4e-6)],
|
|
203
|
+
["hsl", hsl],
|
|
204
|
+
["hwb", hwb]
|
|
205
|
+
]);
|
|
206
|
+
var CHANNEL = /^([+-]?(?:\d+\.?\d*|\.\d+)(?:e[+-]?\d+)?)(%|deg|turn|grad|rad)?$/i;
|
|
207
|
+
function channel(v, percent = 1) {
|
|
208
|
+
if (v.toLowerCase() === "none") return NaN;
|
|
209
|
+
const m = v.match(CHANNEL);
|
|
210
|
+
if (!m) return;
|
|
211
|
+
const n = parseFloat(m[1]);
|
|
212
|
+
const unit = m[2]?.toLowerCase();
|
|
213
|
+
return unit === "%" ? n / 100 * percent : unit === "turn" ? n * 360 : unit === "grad" ? n * 0.9 : unit === "rad" ? n * 180 / Math.PI : n;
|
|
214
|
+
}
|
|
215
|
+
var vec = (x, y, z, scale = [1, 1, 1]) => x === void 0 || y === void 0 || z === void 0 ? void 0 : [x / scale[0], y / scale[1], z / scale[2]];
|
|
216
|
+
var rgbChannels = (x, y, z) => vec(channel(x, 255), channel(y, 255), channel(z, 255), [255, 255, 255]);
|
|
217
|
+
var hslChannels = (x, y, z) => vec(channel(x), channel(y, 100), channel(z, 100), [1, 100, 100]);
|
|
218
|
+
var FUNCTIONS = /* @__PURE__ */ new Map([
|
|
219
|
+
["rgb", ["srgb", rgbChannels]],
|
|
220
|
+
["rgba", ["srgb", rgbChannels]],
|
|
221
|
+
["hsl", ["hsl", hslChannels]],
|
|
222
|
+
["hsla", ["hsl", hslChannels]],
|
|
223
|
+
["hwb", ["hwb", hslChannels]],
|
|
224
|
+
["lab", ["lab", (x, y, z) => vec(channel(x, 100), channel(y, 125), channel(z, 125))]],
|
|
225
|
+
["lch", ["lch", (x, y, z) => vec(channel(x, 100), channel(y, 150), channel(z))]],
|
|
226
|
+
["oklab", ["oklab", (x, y, z) => vec(channel(x), channel(y, 0.4), channel(z, 0.4))]],
|
|
227
|
+
["oklch", ["oklch", (x, y, z) => vec(channel(x), channel(y, 0.4), channel(z))]]
|
|
228
|
+
]);
|
|
229
|
+
var hex = (h) => {
|
|
230
|
+
const byte = (i) => parseInt(h.slice(i, i + 2), 16) / 255;
|
|
231
|
+
return [byte(0), byte(2), byte(4)];
|
|
232
|
+
};
|
|
233
|
+
function colorOf(css) {
|
|
234
|
+
const fn = css.match(/^([a-z]+)\(([^)]+)\)$/i);
|
|
235
|
+
if (fn) {
|
|
236
|
+
const args = fn[2].split(/[\s,/]+/).filter(Boolean);
|
|
237
|
+
const kind = fn[1].toLowerCase();
|
|
238
|
+
const [name, read] = kind === "color" ? [
|
|
239
|
+
args.shift()?.toLowerCase() ?? "",
|
|
240
|
+
(x2, y2, z2) => vec(channel(x2), channel(y2), channel(z2))
|
|
241
|
+
] : FUNCTIONS.get(kind) ?? [];
|
|
242
|
+
const space = name && SPACES.get(name);
|
|
243
|
+
if (!space || !read || args.length < 3 || args.length > 4) return;
|
|
244
|
+
const [x, y, z, rawAlpha = "1"] = args;
|
|
245
|
+
const coords = read(x, y, z);
|
|
246
|
+
const alpha = channel(rawAlpha);
|
|
247
|
+
if (!coords || alpha === void 0) return;
|
|
248
|
+
return { space, coords, alpha };
|
|
249
|
+
}
|
|
250
|
+
const short = css.match(/^#([0-9a-f]{3}|[0-9a-f]{6})$/i)?.[1];
|
|
251
|
+
if (short)
|
|
252
|
+
return { space: SRGB, coords: hex(short.length === 3 ? [...short].map((c) => c + c).join("") : short), alpha: 1 };
|
|
253
|
+
if (css.toLowerCase() === "transparent") return { space: SRGB, coords: [0, 0, 0], alpha: 0 };
|
|
254
|
+
}
|
|
255
|
+
function srgbOf(c) {
|
|
256
|
+
const [r, g, b] = map(inSpace(c, SRGB), (v) => Math.min(1, Math.max(0, v || 0)));
|
|
257
|
+
return { r, g, b, a: Math.min(1, Math.max(0, c.alpha || 0)) };
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
// src/core/css.ts
|
|
261
|
+
var hexOf = (c) => `#${[c.r, c.g, c.b].map(
|
|
262
|
+
(v) => Math.round(v * 255).toString(16).padStart(2, "0")
|
|
263
|
+
).join("")}`;
|
|
264
|
+
function parseColor(css) {
|
|
265
|
+
const c = colorOf(css);
|
|
266
|
+
return c && srgbOf(c);
|
|
267
|
+
}
|
|
268
|
+
function splitTop(s) {
|
|
269
|
+
const out = [];
|
|
270
|
+
let depth = 0, from = 0;
|
|
271
|
+
for (let i = 0; i < s.length; i++) {
|
|
272
|
+
if (s[i] === "(") depth++;
|
|
273
|
+
else if (s[i] === ")") depth--;
|
|
274
|
+
else if (s[i] === "," && depth === 0) {
|
|
275
|
+
out.push(s.slice(from, i).trim());
|
|
276
|
+
from = i + 1;
|
|
277
|
+
}
|
|
278
|
+
}
|
|
279
|
+
out.push(s.slice(from).trim());
|
|
280
|
+
return out;
|
|
281
|
+
}
|
|
282
|
+
var SIDES = new Map(Object.entries({ top: 0, right: 90, bottom: 180, left: 270 }));
|
|
283
|
+
var UNITS = new Map(Object.entries({ deg: 1, grad: 0.9, rad: 180 / Math.PI, turn: 360 }));
|
|
284
|
+
var NUMBER = "-?(?:\\d+\\.?\\d*|\\.\\d+)";
|
|
285
|
+
var ANGLE_RE = new RegExp(`^(${NUMBER})([a-z]+)$`);
|
|
286
|
+
var LENGTH_RE = new RegExp(`^(${NUMBER})(%|px)$`);
|
|
287
|
+
var CONIC_POS_RE = new RegExp(`^(${NUMBER})(%|deg|turn|grad|rad)$`);
|
|
288
|
+
var SHADOW_LEN_RE = new RegExp(`^${NUMBER}(px)?$`);
|
|
289
|
+
var TOLERANCE = 1 / 255;
|
|
290
|
+
var PROBES = [1 / 32, 1 / 8, 0.25, 0.5, 0.75, 7 / 8, 31 / 32];
|
|
291
|
+
var KEYWORD_AT = new Map(Object.entries({ left: 0, top: 0, center: 0.5, right: 1, bottom: 1 }));
|
|
292
|
+
function shadowsOf(css) {
|
|
293
|
+
if (!css || css === "none") return [];
|
|
294
|
+
const out = [];
|
|
295
|
+
for (const layer of splitTop(css)) {
|
|
296
|
+
const words = layer.match(/[\w-]+\([^)]*\)|\S+/g) ?? [];
|
|
297
|
+
const inset = words.includes("inset");
|
|
298
|
+
const rest = words.filter((v) => v !== "inset");
|
|
299
|
+
const colors = rest.filter((v) => !SHADOW_LEN_RE.test(v));
|
|
300
|
+
const lengths = rest.flatMap((v) => SHADOW_LEN_RE.test(v) ? [parseFloat(v)] : []);
|
|
301
|
+
const color = colors.length === 1 ? parseColor(colors[0]) : void 0;
|
|
302
|
+
if (!color || lengths.length < 2 || lengths.length > 4 || (lengths[2] ?? 0) < 0) return [];
|
|
303
|
+
const [x, y, radius = 0, spread = 0] = lengths;
|
|
304
|
+
out.push({ type: inset ? "INNER_SHADOW" : "DROP_SHADOW", color, x, y, radius, spread });
|
|
305
|
+
}
|
|
306
|
+
return out;
|
|
307
|
+
}
|
|
308
|
+
var BLEND_MODES = new Map(
|
|
309
|
+
Object.entries({
|
|
310
|
+
multiply: "MULTIPLY",
|
|
311
|
+
screen: "SCREEN",
|
|
312
|
+
overlay: "OVERLAY",
|
|
313
|
+
darken: "DARKEN",
|
|
314
|
+
lighten: "LIGHTEN",
|
|
315
|
+
"color-dodge": "COLOR_DODGE",
|
|
316
|
+
"color-burn": "COLOR_BURN",
|
|
317
|
+
"hard-light": "HARD_LIGHT",
|
|
318
|
+
"soft-light": "SOFT_LIGHT",
|
|
319
|
+
difference: "DIFFERENCE",
|
|
320
|
+
exclusion: "EXCLUSION",
|
|
321
|
+
hue: "HUE",
|
|
322
|
+
saturation: "SATURATION",
|
|
323
|
+
color: "COLOR",
|
|
324
|
+
luminosity: "LUMINOSITY",
|
|
325
|
+
"plus-lighter": "LINEAR_DODGE",
|
|
326
|
+
"plus-darker": "LINEAR_BURN"
|
|
327
|
+
})
|
|
328
|
+
);
|
|
329
|
+
|
|
330
|
+
// src/core/snapshot.ts
|
|
331
|
+
var selectorOf = (el) => el.tag + el.cls.map((c) => `.${c}`).join("");
|
|
332
|
+
var textOf = (el) => el.runs.map((r) => r.text).join("");
|
|
333
|
+
var messageOf = (cause) => cause instanceof Error ? cause.message : String(cause);
|
|
334
|
+
var truncateList = (items, max, sep2 = ", ") => `${items.slice(0, max).join(sep2)}${items.length > max ? `${sep2}and ${items.length - max} more` : ""}`;
|
|
335
|
+
function walk(el, visit, parent, context = "") {
|
|
336
|
+
visit(el, parent, context);
|
|
337
|
+
if (el.kind !== "frame") return;
|
|
338
|
+
const own = el.cls.find((c) => c.includes("__")) ?? el.cls[0];
|
|
339
|
+
for (const c of el.children) walk(c, visit, el, own ?? context);
|
|
340
|
+
}
|
|
341
|
+
function withoutImages(e, missing) {
|
|
342
|
+
if (e.kind === "image") {
|
|
343
|
+
if (!missing(e.image)) return e.video && missing(e.video) ? { ...e, video: void 0 } : e;
|
|
344
|
+
return {
|
|
345
|
+
tag: e.tag,
|
|
346
|
+
cls: e.cls,
|
|
347
|
+
box: e.box,
|
|
348
|
+
style: e.style,
|
|
349
|
+
label: e.label,
|
|
350
|
+
vars: e.vars,
|
|
351
|
+
kind: "frame",
|
|
352
|
+
children: [],
|
|
353
|
+
pseudos: [],
|
|
354
|
+
bgImages: []
|
|
355
|
+
};
|
|
356
|
+
}
|
|
357
|
+
if (e.kind !== "frame") return e;
|
|
358
|
+
const children = e.children.map((c) => withoutImages(c, missing));
|
|
359
|
+
if (!e.bgImages.some(missing)) return { ...e, children };
|
|
360
|
+
let url = 0;
|
|
361
|
+
const keep = splitTop(e.style.bgImage).map((layer) => !layer.startsWith("url(") || !missing(e.bgImages[url++]));
|
|
362
|
+
const pick2 = (list, fallback) => {
|
|
363
|
+
const items = splitTop(list);
|
|
364
|
+
return keep.flatMap((ok, i) => ok ? [items[i % items.length]] : []).join(", ") || fallback;
|
|
365
|
+
};
|
|
366
|
+
const style = {
|
|
367
|
+
...e.style,
|
|
368
|
+
bgImage: pick2(e.style.bgImage, "none"),
|
|
369
|
+
bgSize: pick2(e.style.bgSize, "auto"),
|
|
370
|
+
bgPos: pick2(e.style.bgPos, "0% 0%")
|
|
371
|
+
};
|
|
372
|
+
return { ...e, children, style, bgImages: e.bgImages.filter((n) => !missing(n)) };
|
|
373
|
+
}
|
|
374
|
+
|
|
375
|
+
// cli/browser.ts
|
|
376
|
+
import { spawn } from "node:child_process";
|
|
377
|
+
import { existsSync, mkdtempSync, readdirSync, readFileSync, rmSync } from "node:fs";
|
|
378
|
+
import { homedir, tmpdir } from "node:os";
|
|
379
|
+
import { delimiter, isAbsolute, join, resolve } from "node:path";
|
|
380
|
+
import { setTimeout as sleep2 } from "node:timers/promises";
|
|
381
|
+
|
|
382
|
+
// cli/cdp.ts
|
|
383
|
+
import { setTimeout as sleep } from "node:timers/promises";
|
|
384
|
+
|
|
385
|
+
// cli/shared.ts
|
|
386
|
+
var Problem = class extends Error {
|
|
387
|
+
};
|
|
388
|
+
var chosen = (...on) => on.filter(Boolean).length;
|
|
389
|
+
var maxMismatchOf = (flags) => flags["max-mismatch"] === void 0 ? void 0 : Number(flags["max-mismatch"]);
|
|
390
|
+
function auditReport(audit, design, found = audit.owners.length > 0) {
|
|
391
|
+
if (design && !audit.owners.length)
|
|
392
|
+
throw new Problem(
|
|
393
|
+
`The open file holds no output of the design "${design}", so there is nothing to audit. Build it first: figdriver import run <dir>`
|
|
394
|
+
);
|
|
395
|
+
return {
|
|
396
|
+
...audit,
|
|
397
|
+
found,
|
|
398
|
+
clean: Object.values(audit.problems).every((paths) => !paths.length)
|
|
399
|
+
};
|
|
400
|
+
}
|
|
401
|
+
var slug = (name) => name.replace(/[^\w]+/g, "-").replace(/^-|-$/g, "").toLowerCase();
|
|
402
|
+
function screenFiles(dir, screens, ext = "png") {
|
|
403
|
+
const bases = screens.map((s) => slug(s.name) || "screen");
|
|
404
|
+
const taken = /* @__PURE__ */ new Set();
|
|
405
|
+
return screens.map((s, i) => {
|
|
406
|
+
const raw = bases[i] ?? "screen";
|
|
407
|
+
const base = bases.indexOf(raw) !== bases.lastIndexOf(raw) ? `${raw}-${slug(s.id)}` : raw;
|
|
408
|
+
let name = base;
|
|
409
|
+
for (let n = 2; taken.has(name); n++) name = `${base}-${n}`;
|
|
410
|
+
taken.add(name);
|
|
411
|
+
return `${dir}/${name}.${ext}`;
|
|
412
|
+
});
|
|
413
|
+
}
|
|
414
|
+
|
|
415
|
+
// cli/target.ts
|
|
416
|
+
var FIGMA_HOSTS = /* @__PURE__ */ new Set(["www.figma.com", "figma.com"]);
|
|
417
|
+
var FIGMA_FILE_PATH = /^\/(design|file|board|slides|make|buzz|site)\//;
|
|
418
|
+
var NODE_ID = /^I?\d+:\d+(?:;I?\d+:\d+)*$/;
|
|
419
|
+
function isFigmaFile(url) {
|
|
420
|
+
const u = URL.parse(url);
|
|
421
|
+
return u?.protocol === "https:" && FIGMA_HOSTS.has(u.host) && FIGMA_FILE_PATH.test(u.pathname);
|
|
422
|
+
}
|
|
423
|
+
function isMakePreview(url) {
|
|
424
|
+
const u = URL.parse(url);
|
|
425
|
+
return u?.protocol === "https:" && u.host.endsWith(".figma.site");
|
|
426
|
+
}
|
|
427
|
+
function fileKeyOf(url) {
|
|
428
|
+
if (!isFigmaFile(url)) return void 0;
|
|
429
|
+
const parts = new URL(url).pathname.split("/");
|
|
430
|
+
return parts[3] === "branch" && parts[4] ? parts[4] : parts[2];
|
|
431
|
+
}
|
|
432
|
+
var keyOf = (typed) => /^[A-Za-z0-9]+$/.test(typed) ? typed : fileKeyOf(typed);
|
|
433
|
+
function parseFile(typed) {
|
|
434
|
+
const key = keyOf(typed);
|
|
435
|
+
if (!key)
|
|
436
|
+
throw new Problem(
|
|
437
|
+
`"${typed}" is neither a Figma file URL nor a file key. Pass the file's link, such as https://www.figma.com/design/<key>/<name>.`
|
|
438
|
+
);
|
|
439
|
+
return key;
|
|
440
|
+
}
|
|
441
|
+
function parseNodeId(input) {
|
|
442
|
+
const trimmed = input.trim();
|
|
443
|
+
let raw = trimmed;
|
|
444
|
+
if (isFigmaFile(trimmed)) {
|
|
445
|
+
const param = URL.parse(trimmed)?.searchParams.get("node-id")?.trim();
|
|
446
|
+
if (!param)
|
|
447
|
+
throw new Problem(
|
|
448
|
+
`Figma URL "${trimmed}" has no node-id query parameter. Copy a layer link or pass a node id such as 1:23.`
|
|
449
|
+
);
|
|
450
|
+
raw = param;
|
|
451
|
+
} else if (/^https?:\/\//i.test(trimmed)) {
|
|
452
|
+
throw new Problem(`"${trimmed}" is not a Figma file URL. Pass a Figma layer link or a node id such as 1:23.`);
|
|
453
|
+
}
|
|
454
|
+
const normalized = raw.replace(/(\d+)-(\d+)/g, "$1:$2");
|
|
455
|
+
if (!NODE_ID.test(normalized))
|
|
456
|
+
throw new Problem(
|
|
457
|
+
`"${trimmed}" is not a valid Figma node id or layer URL. Pass an id like 1:23, 1-23, or a Figma URL with ?node-id=...`
|
|
458
|
+
);
|
|
459
|
+
return normalized;
|
|
460
|
+
}
|
|
461
|
+
function pickFile(tabs, key, command, writes) {
|
|
462
|
+
const files = tabs.filter((t) => isFigmaFile(t.url));
|
|
463
|
+
const listing = files.map((t) => ` --file ${fileKeyOf(t.url)} ${t.title.replace(/ – Figma$/, "")}`).join("\n");
|
|
464
|
+
const open = files.length ? `Open files:
|
|
465
|
+
${listing}` : "No Figma file is open in the debugging browser. Open the file to work on there.";
|
|
466
|
+
if (key) {
|
|
467
|
+
const matches = files.filter((t) => fileKeyOf(t.url) === key);
|
|
468
|
+
if (writes && matches.length > 1) {
|
|
469
|
+
throw new Problem(
|
|
470
|
+
`The file ${key} is open in ${matches.length} tabs, and ${command} writes through one tab only, so a write through another would not see it. Close all but one of these tabs, then retry:
|
|
471
|
+
${matches.map((t) => ` ${t.title} ${t.url}`).join("\n")}`
|
|
472
|
+
);
|
|
473
|
+
}
|
|
474
|
+
if (matches.length) return matches[0];
|
|
475
|
+
throw new Problem(`No open Figma file has the key ${key}. ${open}`);
|
|
476
|
+
}
|
|
477
|
+
if (writes)
|
|
478
|
+
throw new Problem(
|
|
479
|
+
`${command} writes to a Figma file, so name it with --file <URL or key>, or set FIGDRIVER_FILE. ${open}`
|
|
480
|
+
);
|
|
481
|
+
if (files.length === 1) return files[0];
|
|
482
|
+
throw new Problem(
|
|
483
|
+
files.length ? `Several Figma files are open. Name one with --file <URL or key>, or set FIGDRIVER_FILE. ${open}` : open
|
|
484
|
+
);
|
|
485
|
+
}
|
|
486
|
+
function pickCloseTargets(tabs, wanted, duplicates) {
|
|
487
|
+
if (duplicates) {
|
|
488
|
+
const filterKey = wanted ? parseFile(wanted) : void 0;
|
|
489
|
+
const seen = /* @__PURE__ */ new Set();
|
|
490
|
+
const extras = [];
|
|
491
|
+
for (const tab of tabs) {
|
|
492
|
+
const key2 = fileKeyOf(tab.url);
|
|
493
|
+
if (!key2 || filterKey && key2 !== filterKey) continue;
|
|
494
|
+
if (seen.has(key2)) extras.push(tab);
|
|
495
|
+
else seen.add(key2);
|
|
496
|
+
}
|
|
497
|
+
return extras;
|
|
498
|
+
}
|
|
499
|
+
if (!wanted) throw new Problem("Name a tab id, Figma URL, or file key to close, or pass --duplicates.");
|
|
500
|
+
const byId = tabs.filter((t) => t.id === wanted);
|
|
501
|
+
if (byId.length) return byId;
|
|
502
|
+
const byUrl = tabs.filter((t) => t.url === wanted);
|
|
503
|
+
if (byUrl.length) return byUrl;
|
|
504
|
+
const key = keyOf(wanted);
|
|
505
|
+
const byKey = key ? tabs.filter((t) => fileKeyOf(t.url) === key) : [];
|
|
506
|
+
if (byKey.length) return byKey;
|
|
507
|
+
const open = tabs.length ? `Open tabs:
|
|
508
|
+
${tabs.map((t) => ` ${t.id} ${fileKeyOf(t.url) ?? "-"} ${t.title}`).join("\n")}` : "No tabs are open in the debugging browser.";
|
|
509
|
+
throw new Problem(`No open tab matches "${wanted}". ${open}`);
|
|
510
|
+
}
|
|
511
|
+
|
|
512
|
+
// cli/cdp.ts
|
|
513
|
+
var Timeout = class extends Problem {
|
|
514
|
+
};
|
|
515
|
+
var LEASE_SECONDS = 900;
|
|
516
|
+
var CONNECT_TIMEOUT_MS = 15e3;
|
|
517
|
+
var WAIT_POLL_MS = 500;
|
|
518
|
+
var WAIT_LOG_MS = 15e3;
|
|
519
|
+
var MAX_RESPONSIVE_MISSES = 40;
|
|
520
|
+
var inProgress = (w, now = Date.now()) => `figdriver ${w.command}, started ${Math.max(0, Math.round((now - w.started) / 1e3))}s ago`;
|
|
521
|
+
var stillRunning = (command, seconds) => new Problem(
|
|
522
|
+
`${command} did not finish within ${seconds}s and may still be writing to the file. Run figdriver doctor before you retry: it shows a write still in progress.`
|
|
523
|
+
);
|
|
524
|
+
function formatConsole(event) {
|
|
525
|
+
const args = event.args ?? [];
|
|
526
|
+
if (!args.length) return null;
|
|
527
|
+
const text = args.map((a) => a.value !== void 0 ? String(a.value) : a.description ?? a.type).join(" ");
|
|
528
|
+
const tag = event.type === "warning" || event.type === "error" ? `figma:${event.type}` : "figma";
|
|
529
|
+
return `[${tag}] ${text}`;
|
|
530
|
+
}
|
|
531
|
+
async function pollUntil(seconds, onWait, attempt) {
|
|
532
|
+
const deadline = Date.now() + seconds * 1e3;
|
|
533
|
+
let lastNotice = 0;
|
|
534
|
+
const notify = (line) => {
|
|
535
|
+
const now = Date.now();
|
|
536
|
+
if (now - lastNotice >= WAIT_LOG_MS) {
|
|
537
|
+
onWait?.(line);
|
|
538
|
+
lastNotice = now;
|
|
539
|
+
}
|
|
540
|
+
};
|
|
541
|
+
for (; ; ) {
|
|
542
|
+
const remainingMs = Math.max(0, deadline - Date.now());
|
|
543
|
+
const sliceSeconds = Math.max(0.1, Math.min(15, remainingMs / 1e3 || 0.1));
|
|
544
|
+
let step;
|
|
545
|
+
try {
|
|
546
|
+
step = await attempt(sliceSeconds);
|
|
547
|
+
} catch (e) {
|
|
548
|
+
if (!(e instanceof Timeout)) throw e;
|
|
549
|
+
if (Date.now() >= deadline)
|
|
550
|
+
throw new Timeout(
|
|
551
|
+
`The tab did not respond within ${Math.round(seconds)}s. Keep the browser window visible or run figdriver doctor to check it.`
|
|
552
|
+
);
|
|
553
|
+
notify("Waiting for the Figma tab to respond...");
|
|
554
|
+
await sleep(Math.min(WAIT_POLL_MS, Math.max(0, deadline - Date.now())));
|
|
555
|
+
continue;
|
|
556
|
+
}
|
|
557
|
+
if (step.done) return step.value;
|
|
558
|
+
notify(step.notice);
|
|
559
|
+
const left = deadline - Date.now();
|
|
560
|
+
if (left <= 0) throw new Timeout(step.notice);
|
|
561
|
+
await sleep(Math.min(WAIT_POLL_MS, left));
|
|
562
|
+
}
|
|
563
|
+
}
|
|
564
|
+
async function connect(t) {
|
|
565
|
+
const ws = new WebSocket(t.webSocketDebuggerUrl);
|
|
566
|
+
await new Promise((resolve7, reject) => {
|
|
567
|
+
const timer = setTimeout(() => {
|
|
568
|
+
ws.close();
|
|
569
|
+
reject(new Problem(`Timed out attaching to the tab at ${t.url}`));
|
|
570
|
+
}, CONNECT_TIMEOUT_MS);
|
|
571
|
+
ws.addEventListener(
|
|
572
|
+
"open",
|
|
573
|
+
() => {
|
|
574
|
+
clearTimeout(timer);
|
|
575
|
+
resolve7();
|
|
576
|
+
},
|
|
577
|
+
{ once: true }
|
|
578
|
+
);
|
|
579
|
+
ws.addEventListener(
|
|
580
|
+
"error",
|
|
581
|
+
() => {
|
|
582
|
+
clearTimeout(timer);
|
|
583
|
+
reject(new Problem(`Could not attach to the tab at ${t.url}`));
|
|
584
|
+
},
|
|
585
|
+
{ once: true }
|
|
586
|
+
);
|
|
587
|
+
});
|
|
588
|
+
let seq = 0;
|
|
589
|
+
const pending = /* @__PURE__ */ new Map();
|
|
590
|
+
const consoleListeners = /* @__PURE__ */ new Set();
|
|
591
|
+
ws.addEventListener("message", (e) => {
|
|
592
|
+
const msg = JSON.parse(String(e.data));
|
|
593
|
+
if (msg.id !== void 0) {
|
|
594
|
+
pending.get(msg.id)?.(msg);
|
|
595
|
+
return;
|
|
596
|
+
}
|
|
597
|
+
if (msg.method === "Runtime.consoleAPICalled" && consoleListeners.size && msg.params) {
|
|
598
|
+
const line = formatConsole(msg.params);
|
|
599
|
+
if (line !== null) {
|
|
600
|
+
for (const onLine of consoleListeners) onLine(line);
|
|
601
|
+
}
|
|
602
|
+
}
|
|
603
|
+
});
|
|
604
|
+
ws.addEventListener("close", () => {
|
|
605
|
+
for (const settle of pending.values())
|
|
606
|
+
settle({ error: { message: `The tab at ${t.url} closed or navigated away before it answered.` } });
|
|
607
|
+
});
|
|
608
|
+
function send(method, params = {}, seconds = 30) {
|
|
609
|
+
if (ws.readyState !== WebSocket.OPEN) {
|
|
610
|
+
return Promise.reject(new Problem(`The tab at ${t.url} is no longer connected.`));
|
|
611
|
+
}
|
|
612
|
+
const id = ++seq;
|
|
613
|
+
ws.send(JSON.stringify({ id, method, params }));
|
|
614
|
+
return new Promise((resolve7, reject) => {
|
|
615
|
+
const timer = setTimeout(() => {
|
|
616
|
+
pending.delete(id);
|
|
617
|
+
reject(
|
|
618
|
+
new Timeout(
|
|
619
|
+
`The tab did not answer ${method} within ${seconds}s. Another figdriver command may be busy on this tab (pass --wait to wait for it), or the browser window is hidden and throttled: keep it visible and rerun.`
|
|
620
|
+
)
|
|
621
|
+
);
|
|
622
|
+
}, seconds * 1e3);
|
|
623
|
+
pending.set(id, (m) => {
|
|
624
|
+
clearTimeout(timer);
|
|
625
|
+
pending.delete(id);
|
|
626
|
+
if (m.error) {
|
|
627
|
+
reject(new Problem(m.error.message));
|
|
628
|
+
return;
|
|
629
|
+
}
|
|
630
|
+
resolve7(m.result);
|
|
631
|
+
});
|
|
632
|
+
});
|
|
633
|
+
}
|
|
634
|
+
const thrown = (r) => r.exceptionDetails && new Problem(r.exceptionDetails.exception?.description ?? r.exceptionDetails.text);
|
|
635
|
+
async function valueOf(r, seconds) {
|
|
636
|
+
const error = thrown(r);
|
|
637
|
+
if (error) throw error;
|
|
638
|
+
if (!r.result.objectId) {
|
|
639
|
+
return r.result.value;
|
|
640
|
+
}
|
|
641
|
+
const json = await send(
|
|
642
|
+
"Runtime.callFunctionOn",
|
|
643
|
+
{
|
|
644
|
+
objectId: r.result.objectId,
|
|
645
|
+
returnByValue: true,
|
|
646
|
+
functionDeclaration: `function () { "use strict"; return JSON.stringify(this, (key, value) => (typeof value === "symbol" ? "MIXED" : value)); }`
|
|
647
|
+
},
|
|
648
|
+
seconds
|
|
649
|
+
);
|
|
650
|
+
const failed = thrown(json);
|
|
651
|
+
if (failed) throw failed;
|
|
652
|
+
return json.result.value === void 0 ? void 0 : JSON.parse(json.result.value);
|
|
653
|
+
}
|
|
654
|
+
async function evaluate(expression, seconds = 120) {
|
|
655
|
+
return valueOf(
|
|
656
|
+
await send("Runtime.evaluate", { expression, awaitPromise: true, userGesture: true }, seconds),
|
|
657
|
+
seconds
|
|
658
|
+
);
|
|
659
|
+
}
|
|
660
|
+
async function waitIdle(seconds = 600, onWait) {
|
|
661
|
+
let lastHeld;
|
|
662
|
+
try {
|
|
663
|
+
await pollUntil(seconds, onWait, async (slice) => {
|
|
664
|
+
const held = await evaluate("globalThis.figdriverWrite ?? null", slice);
|
|
665
|
+
if (!held) return { done: true, value: void 0 };
|
|
666
|
+
lastHeld = held;
|
|
667
|
+
return { done: false, notice: `Waiting for ${inProgress(held)} to finish...` };
|
|
668
|
+
});
|
|
669
|
+
} catch (e) {
|
|
670
|
+
if (lastHeld && e instanceof Timeout)
|
|
671
|
+
throw new Problem(
|
|
672
|
+
`${inProgress(lastHeld)}, is still writing to this file after waiting ${seconds}s. Run figdriver doctor to check it, or reload the Figma tab if no figdriver command is running.`
|
|
673
|
+
);
|
|
674
|
+
throw e;
|
|
675
|
+
}
|
|
676
|
+
}
|
|
677
|
+
async function write2(command, before, expression, seconds, wait = false, onWait) {
|
|
678
|
+
const id = JSON.stringify(crypto.randomUUID());
|
|
679
|
+
const release = `if (globalThis.figdriverWrite?.id === ${id}) { clearTimeout(globalThis.figdriverWrite.lease); delete globalThis.figdriverWrite; }`;
|
|
680
|
+
const leaseSeconds = Math.max(LEASE_SECONDS, seconds);
|
|
681
|
+
const acquireExpr = `(() => {
|
|
682
|
+
if (globalThis.figdriverWrite && globalThis.figdriverWrite.id !== ${id}) return { held: globalThis.figdriverWrite };
|
|
683
|
+
if (globalThis.figdriverWrite?.id === ${id}) clearTimeout(globalThis.figdriverWrite.lease);
|
|
684
|
+
globalThis.figdriverWrite = { id: ${id}, command: ${JSON.stringify(command)}, started: Date.now(), lease: setTimeout(() => { ${release} }, ${leaseSeconds * 1e3}) };
|
|
685
|
+
return { href: location.href };
|
|
686
|
+
})()`;
|
|
687
|
+
const releaseNow = () => evaluate(release, 10).catch(() => {
|
|
688
|
+
});
|
|
689
|
+
const lockBusy = (held) => new Problem(
|
|
690
|
+
`${inProgress(held)}, is still writing to this file. Pass --wait to wait for it, or retry once figdriver doctor no longer lists it. Two writes at once can undo each other. If no figdriver command is running, reload the Figma tab to clear it.`
|
|
691
|
+
);
|
|
692
|
+
let taken;
|
|
693
|
+
if (!wait) {
|
|
694
|
+
try {
|
|
695
|
+
taken = await evaluate(acquireExpr, 120);
|
|
696
|
+
} catch (e) {
|
|
697
|
+
if (e instanceof Timeout) await releaseNow();
|
|
698
|
+
throw e;
|
|
699
|
+
}
|
|
700
|
+
if (taken.held) throw lockBusy(taken.held);
|
|
701
|
+
} else {
|
|
702
|
+
let lastHeld;
|
|
703
|
+
try {
|
|
704
|
+
taken = await pollUntil(seconds, onWait, async (slice) => {
|
|
705
|
+
const res = await evaluate(acquireExpr, slice);
|
|
706
|
+
if (!res.held) return { done: true, value: res };
|
|
707
|
+
lastHeld = res.held;
|
|
708
|
+
return { done: false, notice: `Waiting for ${inProgress(res.held)} to finish...` };
|
|
709
|
+
});
|
|
710
|
+
} catch (e) {
|
|
711
|
+
await releaseNow();
|
|
712
|
+
if (lastHeld && e instanceof Timeout) throw lockBusy(lastHeld);
|
|
713
|
+
throw e;
|
|
714
|
+
}
|
|
715
|
+
}
|
|
716
|
+
if (fileKeyOf(taken.href) !== fileKeyOf(t.url)) {
|
|
717
|
+
await releaseNow();
|
|
718
|
+
throw new Problem(
|
|
719
|
+
`The tab figdriver matched to ${t.url} now shows ${taken.href}, so nothing was written. Open the file there again, then retry.`
|
|
720
|
+
);
|
|
721
|
+
}
|
|
722
|
+
try {
|
|
723
|
+
await before();
|
|
724
|
+
} catch (e) {
|
|
725
|
+
await releaseNow();
|
|
726
|
+
throw e;
|
|
727
|
+
}
|
|
728
|
+
const guard = `if (globalThis.figdriverWrite?.id !== ${id}) throw new Error("The Figma tab navigated or reloaded while figdriver prepared the ${command}, so nothing was written. Retry.");`;
|
|
729
|
+
let r;
|
|
730
|
+
try {
|
|
731
|
+
r = await send(
|
|
732
|
+
"Runtime.evaluate",
|
|
733
|
+
{ expression: `${guard} ${expression}`, userGesture: true },
|
|
734
|
+
seconds
|
|
735
|
+
);
|
|
736
|
+
} catch (e) {
|
|
737
|
+
if (!(e instanceof Timeout)) await releaseNow();
|
|
738
|
+
throw e instanceof Timeout ? stillRunning(command, seconds) : e;
|
|
739
|
+
}
|
|
740
|
+
if (r.result.subtype !== "promise") {
|
|
741
|
+
await releaseNow();
|
|
742
|
+
return valueOf(r, seconds);
|
|
743
|
+
}
|
|
744
|
+
try {
|
|
745
|
+
const settled = await send(
|
|
746
|
+
"Runtime.callFunctionOn",
|
|
747
|
+
{
|
|
748
|
+
objectId: r.result.objectId,
|
|
749
|
+
awaitPromise: true,
|
|
750
|
+
functionDeclaration: `function () { if (globalThis.figdriverWrite?.id === ${id}) clearTimeout(globalThis.figdriverWrite.lease); return this.finally(() => { ${release} }); }`
|
|
751
|
+
},
|
|
752
|
+
seconds
|
|
753
|
+
);
|
|
754
|
+
return await valueOf(settled, seconds);
|
|
755
|
+
} catch (e) {
|
|
756
|
+
throw e instanceof Timeout ? stillRunning(command, seconds) : e;
|
|
757
|
+
}
|
|
758
|
+
}
|
|
759
|
+
async function front(seconds = 10) {
|
|
760
|
+
if (await evaluate("document.visibilityState", seconds) !== "visible")
|
|
761
|
+
await send("Page.bringToFront", {}, seconds);
|
|
762
|
+
}
|
|
763
|
+
async function streamConsole(onLine) {
|
|
764
|
+
await send("Runtime.enable");
|
|
765
|
+
await send("Runtime.discardConsoleEntries").catch(() => {
|
|
766
|
+
});
|
|
767
|
+
consoleListeners.add(onLine);
|
|
768
|
+
return () => {
|
|
769
|
+
consoleListeners.delete(onLine);
|
|
770
|
+
};
|
|
771
|
+
}
|
|
772
|
+
return { target: t, send, evaluate, write: write2, waitIdle, front, console: streamConsole, close: () => ws.close() };
|
|
773
|
+
}
|
|
774
|
+
var FIGMA_PROBE = `(() => {
|
|
775
|
+
if (typeof figma === "object") return "ready";
|
|
776
|
+
if (document.readyState !== "complete" || !document.querySelector("canvas")) return "loading";
|
|
777
|
+
const badge = document.querySelector('[data-testid="view-only-badge"]');
|
|
778
|
+
if (badge) return "view-only";
|
|
779
|
+
for (const el of document.querySelectorAll('button, [role="button"], [role="status"]')) {
|
|
780
|
+
const r = el.getBoundingClientRect();
|
|
781
|
+
if (!r.width || !r.height) continue;
|
|
782
|
+
if (/^(view only|ask to edit|request edit access)$/i.test((el.textContent || "").trim())) return "view-only";
|
|
783
|
+
}
|
|
784
|
+
return "waiting";
|
|
785
|
+
})()`;
|
|
786
|
+
var NO_FIGMA_API = "The Figma tab has no plugin API: `figma` is undefined. Either the file is still loading, or this account only has view access. If it is view-only, duplicate the file to your drafts (or request edit access) and pass the copy's URL. `figdriver browser screenshot out/tab.png` shows the tab state.";
|
|
787
|
+
var VIEW_ONLY_ERROR = "This Figma file is view-only, so the plugin API (`figma`) is unavailable. Duplicate the file to your drafts (or request edit access) and pass the copy's URL. `figdriver browser screenshot out/tab.png` can still screenshot the tab.";
|
|
788
|
+
async function figma(target2, wait = false, waitSeconds = 600, onWait) {
|
|
789
|
+
const session = await connect(target2);
|
|
790
|
+
const deadline = Date.now() + waitSeconds * 1e3;
|
|
791
|
+
try {
|
|
792
|
+
if (wait) {
|
|
793
|
+
await pollUntil(waitSeconds, onWait, async (slice) => {
|
|
794
|
+
await session.front(slice);
|
|
795
|
+
return { done: true, value: void 0 };
|
|
796
|
+
});
|
|
797
|
+
} else {
|
|
798
|
+
await session.front();
|
|
799
|
+
}
|
|
800
|
+
let viewOnlyHits = 0;
|
|
801
|
+
let responsiveMisses = 0;
|
|
802
|
+
if (!wait) {
|
|
803
|
+
for (let i = 0; i < MAX_RESPONSIVE_MISSES; i++) {
|
|
804
|
+
const state = await session.evaluate(FIGMA_PROBE, 120);
|
|
805
|
+
if (state === "ready") return session;
|
|
806
|
+
if (state === "view-only") {
|
|
807
|
+
if (++viewOnlyHits >= 2) throw new Problem(VIEW_ONLY_ERROR);
|
|
808
|
+
} else viewOnlyHits = 0;
|
|
809
|
+
await sleep(WAIT_POLL_MS);
|
|
810
|
+
}
|
|
811
|
+
throw new Problem(NO_FIGMA_API);
|
|
812
|
+
}
|
|
813
|
+
const remaining = Math.max(0.1, (deadline - Date.now()) / 1e3);
|
|
814
|
+
return await pollUntil(remaining, onWait, async (slice) => {
|
|
815
|
+
const state = await session.evaluate(FIGMA_PROBE, slice);
|
|
816
|
+
if (state === "ready") return { done: true, value: session };
|
|
817
|
+
if (state === "view-only") {
|
|
818
|
+
if (++viewOnlyHits >= 2) throw new Problem(VIEW_ONLY_ERROR);
|
|
819
|
+
} else viewOnlyHits = 0;
|
|
820
|
+
if (++responsiveMisses >= MAX_RESPONSIVE_MISSES) throw new Problem(NO_FIGMA_API);
|
|
821
|
+
return { done: false, notice: "Waiting for Figma to load..." };
|
|
822
|
+
});
|
|
823
|
+
} catch (e) {
|
|
824
|
+
session.close();
|
|
825
|
+
throw e;
|
|
826
|
+
}
|
|
827
|
+
}
|
|
828
|
+
|
|
829
|
+
// cli/browser.ts
|
|
830
|
+
var PROFILE = join(homedir(), ".cache", "figdriver-profile");
|
|
831
|
+
var cdpPort = () => process.env.CDP_PORT ?? "9333";
|
|
832
|
+
var cdpBase = () => `http://127.0.0.1:${cdpPort()}`;
|
|
833
|
+
var SYSTEM_BROWSERS = [
|
|
834
|
+
"helium-browser",
|
|
835
|
+
"google-chrome-stable",
|
|
836
|
+
"google-chrome",
|
|
837
|
+
"chromium",
|
|
838
|
+
"chromium-browser",
|
|
839
|
+
"brave-browser",
|
|
840
|
+
"microsoft-edge",
|
|
841
|
+
...["Google Chrome", "Chromium", "Microsoft Edge", "Brave Browser"].map(
|
|
842
|
+
(app) => `/Applications/${app}.app/Contents/MacOS/${app}`
|
|
843
|
+
),
|
|
844
|
+
...[process.env.PROGRAMFILES, process.env["PROGRAMFILES(X86)"], process.env.LOCALAPPDATA].flatMap(
|
|
845
|
+
(root) => root ? [
|
|
846
|
+
"Google/Chrome/Application/chrome.exe",
|
|
847
|
+
"Chromium/Application/chrome.exe",
|
|
848
|
+
"Microsoft/Edge/Application/msedge.exe",
|
|
849
|
+
"BraveSoftware/Brave-Browser/Application/brave.exe"
|
|
850
|
+
].map((path) => join(root, path)) : []
|
|
851
|
+
)
|
|
852
|
+
];
|
|
853
|
+
var PLAYWRIGHT_CANDIDATES = [
|
|
854
|
+
"chrome-linux64/chrome",
|
|
855
|
+
"chrome-linux/chrome",
|
|
856
|
+
"chrome-mac-arm64/Google Chrome for Testing.app/Contents/MacOS/Google Chrome for Testing",
|
|
857
|
+
"chrome-mac/Google Chrome for Testing.app/Contents/MacOS/Google Chrome for Testing",
|
|
858
|
+
"chrome-mac/Chromium.app/Contents/MacOS/Chromium",
|
|
859
|
+
"chrome-win64/chrome.exe",
|
|
860
|
+
"chrome-win/chrome.exe"
|
|
861
|
+
];
|
|
862
|
+
var HEADLESS_ARGS = [
|
|
863
|
+
"--headless=new",
|
|
864
|
+
"--no-first-run",
|
|
865
|
+
"--no-default-browser-check",
|
|
866
|
+
"--use-gl=angle",
|
|
867
|
+
"--use-angle=swiftshader",
|
|
868
|
+
"--enable-webgl"
|
|
869
|
+
];
|
|
870
|
+
var onPath = (name) => (process.env.PATH ?? "").split(delimiter).some((dir) => dir && existsSync(join(dir, name)));
|
|
871
|
+
function findPlaywrightChromium(cacheRoots) {
|
|
872
|
+
const roots = cacheRoots ?? [
|
|
873
|
+
process.env.PLAYWRIGHT_BROWSERS_PATH,
|
|
874
|
+
process.platform === "darwin" ? join(homedir(), "Library", "Caches", "ms-playwright") : process.platform === "win32" ? process.env.LOCALAPPDATA && join(process.env.LOCALAPPDATA, "ms-playwright") : join(homedir(), ".cache", "ms-playwright")
|
|
875
|
+
].filter((r) => Boolean(r));
|
|
876
|
+
for (const root of roots) {
|
|
877
|
+
if (!existsSync(root)) continue;
|
|
878
|
+
const dirs = readdirSync(root).filter((d) => /^chromium-\d+$/.test(d)).sort((a, b) => Number(b.slice(9)) - Number(a.slice(9)));
|
|
879
|
+
for (const dir of dirs) {
|
|
880
|
+
for (const rel of PLAYWRIGHT_CANDIDATES) {
|
|
881
|
+
const bin = join(root, dir, rel);
|
|
882
|
+
if (existsSync(bin)) return bin;
|
|
883
|
+
}
|
|
884
|
+
}
|
|
885
|
+
}
|
|
886
|
+
}
|
|
887
|
+
function findBrowser(preferPlaywright = false) {
|
|
888
|
+
const env = process.env.FIGDRIVER_BROWSER;
|
|
889
|
+
if (env === "playwright") {
|
|
890
|
+
const pw = findPlaywrightChromium();
|
|
891
|
+
if (!pw)
|
|
892
|
+
throw new Problem(
|
|
893
|
+
"FIGDRIVER_BROWSER=playwright was set, but no Playwright Chromium was found. Run `npx playwright install chromium` or unset FIGDRIVER_BROWSER."
|
|
894
|
+
);
|
|
895
|
+
return pw;
|
|
896
|
+
}
|
|
897
|
+
if (env) return env;
|
|
898
|
+
const system = () => SYSTEM_BROWSERS.find((b) => isAbsolute(b) ? existsSync(b) : onPath(b));
|
|
899
|
+
const found = preferPlaywright ? findPlaywrightChromium() ?? system() : system() ?? findPlaywrightChromium();
|
|
900
|
+
if (!found)
|
|
901
|
+
throw new Problem(
|
|
902
|
+
"No Chromium-based browser found on PATH, in standard install folders, or in Playwright's cache. Set FIGDRIVER_BROWSER to a Chromium binary, or run `npx playwright install chromium`."
|
|
903
|
+
);
|
|
904
|
+
return found;
|
|
905
|
+
}
|
|
906
|
+
function spawnEnv() {
|
|
907
|
+
return process.platform !== "win32" && (process.env.TMPDIR ?? "").length > 60 ? { ...process.env, TMPDIR: "/tmp" } : process.env;
|
|
908
|
+
}
|
|
909
|
+
function isFigdriverProfile(profilePath, profile = PROFILE) {
|
|
910
|
+
if (!profilePath) return false;
|
|
911
|
+
const same2 = (a, b) => process.platform === "win32" ? a.toLowerCase() === b.toLowerCase() : a === b;
|
|
912
|
+
return same2(resolve(profilePath, ".."), resolve(profile));
|
|
913
|
+
}
|
|
914
|
+
async function running() {
|
|
915
|
+
try {
|
|
916
|
+
await fetch(`${cdpBase()}/json/version`);
|
|
917
|
+
return true;
|
|
918
|
+
} catch {
|
|
919
|
+
return false;
|
|
920
|
+
}
|
|
921
|
+
}
|
|
922
|
+
async function launch(url) {
|
|
923
|
+
const port = cdpPort();
|
|
924
|
+
const browser = findBrowser();
|
|
925
|
+
const fix = "Set FIGDRIVER_BROWSER to the path of a Chromium-based browser, such as Chrome, Edge, Brave, Chromium, or `playwright`.";
|
|
926
|
+
const child = spawn(
|
|
927
|
+
browser,
|
|
928
|
+
[
|
|
929
|
+
`--user-data-dir=${PROFILE}`,
|
|
930
|
+
// Its own window class, so a window manager can keep it from taking focus without touching the person's browser.
|
|
931
|
+
"--class=figdriver",
|
|
932
|
+
"--remote-debugging-address=127.0.0.1",
|
|
933
|
+
`--remote-debugging-port=${port}`,
|
|
934
|
+
url
|
|
935
|
+
],
|
|
936
|
+
{ detached: true, stdio: "ignore", env: spawnEnv() }
|
|
937
|
+
);
|
|
938
|
+
let failed;
|
|
939
|
+
child.once("error", (e) => failed = e.message);
|
|
940
|
+
child.once(
|
|
941
|
+
"exit",
|
|
942
|
+
(code, signal) => failed = `it exited with ${signal ?? `code ${code}`} before opening the debugging port`
|
|
943
|
+
);
|
|
944
|
+
child.unref();
|
|
945
|
+
for (let i = 0; i < 60 && !failed; i++) {
|
|
946
|
+
if (await running()) return browser;
|
|
947
|
+
await sleep2(500);
|
|
948
|
+
}
|
|
949
|
+
if (failed) {
|
|
950
|
+
throw new Problem(
|
|
951
|
+
`Could not start ${browser}: ${failed}. If that browser is already open with the profile at ${PROFILE}, close it and retry. Otherwise: ${fix}`
|
|
952
|
+
);
|
|
953
|
+
}
|
|
954
|
+
throw new Problem(`${browser} started, but nothing answers on port ${port}. ${fix}`);
|
|
955
|
+
}
|
|
956
|
+
async function verify(port) {
|
|
957
|
+
const fix = `Close that program, or set CDP_PORT to a free port and run figdriver browser open.`;
|
|
958
|
+
const answer = await (await fetch(`http://127.0.0.1:${port}/json/version`)).text();
|
|
959
|
+
let version = {};
|
|
960
|
+
try {
|
|
961
|
+
version = JSON.parse(answer);
|
|
962
|
+
} catch {
|
|
963
|
+
}
|
|
964
|
+
if (!version.webSocketDebuggerUrl?.startsWith(`ws://127.0.0.1:${port}/devtools/browser/`)) {
|
|
965
|
+
throw new Problem(
|
|
966
|
+
`Port ${port} answers, but not as a Chromium debugging port, so it is not the figdriver browser. It answered: ${answer.slice(0, 120).trim() || "nothing"}. ${fix}`
|
|
967
|
+
);
|
|
968
|
+
}
|
|
969
|
+
const browser = await connect({ url: "the browser", webSocketDebuggerUrl: version.webSocketDebuggerUrl });
|
|
970
|
+
let profile;
|
|
971
|
+
try {
|
|
972
|
+
const { targetId } = await browser.send("Target.createTarget", {
|
|
973
|
+
url: "chrome://version",
|
|
974
|
+
background: true
|
|
975
|
+
});
|
|
976
|
+
const page = await connect({
|
|
977
|
+
url: "chrome://version",
|
|
978
|
+
webSocketDebuggerUrl: `ws://127.0.0.1:${port}/devtools/page/${targetId}`
|
|
979
|
+
});
|
|
980
|
+
try {
|
|
981
|
+
for (let i = 0; i < 50 && !profile; i++) {
|
|
982
|
+
profile = await page.evaluate(
|
|
983
|
+
`document.getElementById("profile_path")?.textContent?.trim()`
|
|
984
|
+
);
|
|
985
|
+
if (!profile) await sleep2(100);
|
|
986
|
+
}
|
|
987
|
+
} finally {
|
|
988
|
+
page.close();
|
|
989
|
+
await browser.send("Target.closeTarget", { targetId }).catch(() => {
|
|
990
|
+
});
|
|
991
|
+
}
|
|
992
|
+
} finally {
|
|
993
|
+
browser.close();
|
|
994
|
+
}
|
|
995
|
+
if (!isFigdriverProfile(profile)) {
|
|
996
|
+
throw new Problem(
|
|
997
|
+
`The browser on port ${port}, ${version.Browser ?? "of unknown make"}, runs with ${profile ? `the profile ${profile}` : "a profile it does not name"}, so it is not the figdriver browser, whose profile is ${PROFILE}. ${fix}`
|
|
998
|
+
);
|
|
999
|
+
}
|
|
1000
|
+
return version.webSocketDebuggerUrl;
|
|
1001
|
+
}
|
|
1002
|
+
var verified;
|
|
1003
|
+
async function verifiedBrowserUrl() {
|
|
1004
|
+
const port = cdpPort();
|
|
1005
|
+
if (!await running()) {
|
|
1006
|
+
if (verified?.port === port) verified = void 0;
|
|
1007
|
+
throw new Problem(`No debugging browser on port ${port}. Start it with: figdriver browser open`);
|
|
1008
|
+
}
|
|
1009
|
+
if (verified?.port !== port) {
|
|
1010
|
+
const promise = verify(port).catch((e) => {
|
|
1011
|
+
if (verified?.port === port) verified = void 0;
|
|
1012
|
+
throw e;
|
|
1013
|
+
});
|
|
1014
|
+
verified = { port, promise };
|
|
1015
|
+
}
|
|
1016
|
+
return verified.promise;
|
|
1017
|
+
}
|
|
1018
|
+
async function targets() {
|
|
1019
|
+
await verifiedBrowserUrl();
|
|
1020
|
+
return (await fetch(`${cdpBase()}/json`)).json();
|
|
1021
|
+
}
|
|
1022
|
+
async function figmaTarget(wanted, command, writes) {
|
|
1023
|
+
const key = wanted ? parseFile(wanted) : void 0;
|
|
1024
|
+
return pickFile(
|
|
1025
|
+
(await targets()).filter((t) => t.type === "page"),
|
|
1026
|
+
key,
|
|
1027
|
+
command,
|
|
1028
|
+
writes
|
|
1029
|
+
);
|
|
1030
|
+
}
|
|
1031
|
+
async function isolatedTab() {
|
|
1032
|
+
const webSocketDebuggerUrl = await verifiedBrowserUrl();
|
|
1033
|
+
const browser = await connect({ url: "the browser", webSocketDebuggerUrl });
|
|
1034
|
+
let browserContextId;
|
|
1035
|
+
try {
|
|
1036
|
+
({ browserContextId } = await browser.send("Target.createBrowserContext", {
|
|
1037
|
+
disposeOnDetach: true
|
|
1038
|
+
}));
|
|
1039
|
+
const { targetId } = await browser.send("Target.createTarget", {
|
|
1040
|
+
url: "about:blank",
|
|
1041
|
+
browserContextId
|
|
1042
|
+
});
|
|
1043
|
+
const page = await connect({
|
|
1044
|
+
url: "the capture tab",
|
|
1045
|
+
webSocketDebuggerUrl: `ws://127.0.0.1:${cdpPort()}/devtools/page/${targetId}`
|
|
1046
|
+
});
|
|
1047
|
+
return {
|
|
1048
|
+
page,
|
|
1049
|
+
async close() {
|
|
1050
|
+
page.close();
|
|
1051
|
+
await browser.send("Target.disposeBrowserContext", { browserContextId }).catch(() => {
|
|
1052
|
+
});
|
|
1053
|
+
browser.close();
|
|
1054
|
+
}
|
|
1055
|
+
};
|
|
1056
|
+
} catch (e) {
|
|
1057
|
+
if (browserContextId) await browser.send("Target.disposeBrowserContext", { browserContextId }).catch(() => {
|
|
1058
|
+
});
|
|
1059
|
+
browser.close();
|
|
1060
|
+
throw e;
|
|
1061
|
+
}
|
|
1062
|
+
}
|
|
1063
|
+
async function ephemeralTab() {
|
|
1064
|
+
const browser = findBrowser(true);
|
|
1065
|
+
const baseTmp = process.platform !== "win32" && tmpdir().length > 60 ? "/tmp" : tmpdir();
|
|
1066
|
+
const profile = mkdtempSync(join(baseTmp, "figdriver-cap-"));
|
|
1067
|
+
const child = spawn(
|
|
1068
|
+
browser,
|
|
1069
|
+
[
|
|
1070
|
+
...HEADLESS_ARGS,
|
|
1071
|
+
`--user-data-dir=${profile}`,
|
|
1072
|
+
"--remote-debugging-address=127.0.0.1",
|
|
1073
|
+
"--remote-debugging-port=0",
|
|
1074
|
+
"about:blank"
|
|
1075
|
+
],
|
|
1076
|
+
{ stdio: ["ignore", "ignore", "pipe"], env: spawnEnv() }
|
|
1077
|
+
);
|
|
1078
|
+
let failed;
|
|
1079
|
+
let stderr = "";
|
|
1080
|
+
let port;
|
|
1081
|
+
child.stderr.on("data", (chunk) => {
|
|
1082
|
+
const text = chunk.toString("utf8");
|
|
1083
|
+
stderr = (stderr + text).slice(-1e3);
|
|
1084
|
+
const listening = stderr.match(/DevTools listening on ws:\/\/127\.0\.0\.1:(\d+)\//);
|
|
1085
|
+
if (listening) port ??= listening[1];
|
|
1086
|
+
});
|
|
1087
|
+
child.once("error", (e) => failed = e.message);
|
|
1088
|
+
child.once("exit", (code, signal) => failed = `exited with ${signal ?? `code ${code}`}`);
|
|
1089
|
+
const cleanup = async () => {
|
|
1090
|
+
child.kill();
|
|
1091
|
+
await Promise.race([new Promise((done) => child.once("exit", done)), sleep2(2e3)]);
|
|
1092
|
+
if (child.exitCode === null && child.signalCode === null) {
|
|
1093
|
+
child.kill("SIGKILL");
|
|
1094
|
+
await Promise.race([new Promise((done) => child.once("exit", done)), sleep2(500)]);
|
|
1095
|
+
}
|
|
1096
|
+
try {
|
|
1097
|
+
rmSync(profile, { recursive: true, force: true, maxRetries: 10, retryDelay: 100 });
|
|
1098
|
+
} catch {
|
|
1099
|
+
}
|
|
1100
|
+
};
|
|
1101
|
+
try {
|
|
1102
|
+
const portFile = join(profile, "DevToolsActivePort");
|
|
1103
|
+
for (let i = 0; i < 300 && !failed && !port; i++) {
|
|
1104
|
+
if (existsSync(portFile)) port = readFileSync(portFile, "utf8").split("\n")[0]?.trim();
|
|
1105
|
+
if (!port) await sleep2(100);
|
|
1106
|
+
}
|
|
1107
|
+
const detail2 = [failed, stderr.trim().split("\n").slice(-3).join(" | ")].filter(Boolean).join(" \u2014 ");
|
|
1108
|
+
if (!port) throw new Problem(`Could not start headless ${browser}${detail2 ? `: ${detail2}` : ""}`);
|
|
1109
|
+
let target2;
|
|
1110
|
+
for (let i = 0; i < 50 && !target2; i++) {
|
|
1111
|
+
try {
|
|
1112
|
+
const list = await (await fetch(`http://127.0.0.1:${port}/json`)).json();
|
|
1113
|
+
target2 = list.find((t) => t.type === "page");
|
|
1114
|
+
} catch {
|
|
1115
|
+
}
|
|
1116
|
+
if (!target2) await sleep2(100);
|
|
1117
|
+
}
|
|
1118
|
+
if (!target2) throw new Problem(`Headless ${browser} opened no page target.`);
|
|
1119
|
+
const page = await connect(target2);
|
|
1120
|
+
return {
|
|
1121
|
+
page,
|
|
1122
|
+
async close() {
|
|
1123
|
+
page.close();
|
|
1124
|
+
await cleanup();
|
|
1125
|
+
}
|
|
1126
|
+
};
|
|
1127
|
+
} catch (e) {
|
|
1128
|
+
await cleanup();
|
|
1129
|
+
throw e;
|
|
1130
|
+
}
|
|
1131
|
+
}
|
|
1132
|
+
async function stopBrowser() {
|
|
1133
|
+
if (!await running()) return false;
|
|
1134
|
+
const webSocketDebuggerUrl = await verifiedBrowserUrl();
|
|
1135
|
+
const browser = await connect({ url: "the browser", webSocketDebuggerUrl });
|
|
1136
|
+
try {
|
|
1137
|
+
await browser.send("Browser.close");
|
|
1138
|
+
} catch {
|
|
1139
|
+
} finally {
|
|
1140
|
+
browser.close();
|
|
1141
|
+
}
|
|
1142
|
+
verified = void 0;
|
|
1143
|
+
return true;
|
|
1144
|
+
}
|
|
1145
|
+
async function openTab(url, newWindow = false) {
|
|
1146
|
+
const webSocketDebuggerUrl = await verifiedBrowserUrl();
|
|
1147
|
+
const pages = (await targets()).filter((t) => t.type === "page");
|
|
1148
|
+
const key = fileKeyOf(url);
|
|
1149
|
+
const existing = key ? pages.find((t) => fileKeyOf(t.url) === key) : newWindow ? void 0 : pages.find((t) => t.url === url);
|
|
1150
|
+
if (existing) {
|
|
1151
|
+
const s = await connect(existing);
|
|
1152
|
+
try {
|
|
1153
|
+
await s.front();
|
|
1154
|
+
} finally {
|
|
1155
|
+
s.close();
|
|
1156
|
+
}
|
|
1157
|
+
return { target: existing, reused: true };
|
|
1158
|
+
}
|
|
1159
|
+
const browser = await connect({ url: "the browser", webSocketDebuggerUrl });
|
|
1160
|
+
try {
|
|
1161
|
+
const { targetId } = await browser.send("Target.createTarget", { url, newWindow });
|
|
1162
|
+
const created = {
|
|
1163
|
+
id: targetId,
|
|
1164
|
+
type: "page",
|
|
1165
|
+
title: "",
|
|
1166
|
+
url,
|
|
1167
|
+
webSocketDebuggerUrl: `ws://127.0.0.1:${cdpPort()}/devtools/page/${targetId}`
|
|
1168
|
+
};
|
|
1169
|
+
return { target: created, reused: false };
|
|
1170
|
+
} finally {
|
|
1171
|
+
browser.close();
|
|
1172
|
+
}
|
|
1173
|
+
}
|
|
1174
|
+
async function closeTabs(wanted, duplicates) {
|
|
1175
|
+
const webSocketDebuggerUrl = await verifiedBrowserUrl();
|
|
1176
|
+
const pages = (await targets()).filter((t) => t.type === "page");
|
|
1177
|
+
const matched = pickCloseTargets(pages, wanted, duplicates);
|
|
1178
|
+
if (!matched.length) return [];
|
|
1179
|
+
const browser = await connect({ url: "the browser", webSocketDebuggerUrl });
|
|
1180
|
+
try {
|
|
1181
|
+
for (const tab of matched) await browser.send("Target.closeTarget", { targetId: tab.id });
|
|
1182
|
+
} finally {
|
|
1183
|
+
browser.close();
|
|
1184
|
+
}
|
|
1185
|
+
return matched.map((t) => ({ id: t.id, title: t.title, url: t.url, fileKey: fileKeyOf(t.url) ?? null }));
|
|
1186
|
+
}
|
|
1187
|
+
|
|
1188
|
+
// cli/fs.ts
|
|
1189
|
+
import { existsSync as existsSync2, mkdirSync, mkdtempSync as mkdtempSync2, renameSync, rmSync as rmSync2, statSync, writeFileSync } from "node:fs";
|
|
1190
|
+
import { dirname, join as join2, resolve as resolve2 } from "node:path";
|
|
1191
|
+
var isFile = (path) => statSync(path, { throwIfNoEntry: false })?.isFile();
|
|
1192
|
+
function write(file, data) {
|
|
1193
|
+
mkdirSync(dirname(file), { recursive: true });
|
|
1194
|
+
writeFileSync(file, data);
|
|
1195
|
+
}
|
|
1196
|
+
function swapIn(moves) {
|
|
1197
|
+
if (!moves.length) return;
|
|
1198
|
+
const base = dirname(resolve2(moves[0][1]));
|
|
1199
|
+
mkdirSync(base, { recursive: true });
|
|
1200
|
+
const backup = mkdtempSync2(join2(base, ".figdriver-old-"));
|
|
1201
|
+
const done = [];
|
|
1202
|
+
try {
|
|
1203
|
+
for (const [i, [from, to]] of moves.entries()) {
|
|
1204
|
+
const old = join2(backup, String(i));
|
|
1205
|
+
const had = existsSync2(to);
|
|
1206
|
+
mkdirSync(dirname(to), { recursive: true });
|
|
1207
|
+
if (had) renameSync(to, old);
|
|
1208
|
+
done.push({ to, old, had });
|
|
1209
|
+
renameSync(from, to);
|
|
1210
|
+
}
|
|
1211
|
+
} catch (e) {
|
|
1212
|
+
for (const { to, old, had } of done.reverse()) {
|
|
1213
|
+
rmSync2(to, { recursive: true, force: true });
|
|
1214
|
+
if (had) renameSync(old, to);
|
|
1215
|
+
}
|
|
1216
|
+
rmSync2(backup, { recursive: true, force: true });
|
|
1217
|
+
throw e;
|
|
1218
|
+
}
|
|
1219
|
+
rmSync2(backup, { recursive: true, force: true });
|
|
1220
|
+
}
|
|
1221
|
+
|
|
1222
|
+
// cli/session.ts
|
|
1223
|
+
import { mkdirSync as mkdirSync2, mkdtempSync as mkdtempSync3, rmSync as rmSync3 } from "node:fs";
|
|
1224
|
+
import { basename as basename2, dirname as dirname3, join as join4, resolve as resolve4 } from "node:path";
|
|
1225
|
+
|
|
1226
|
+
// cli/bundle.ts
|
|
1227
|
+
import esbuild from "esbuild-wasm/lib/browser.js";
|
|
1228
|
+
import { existsSync as existsSync3, readdirSync as readdirSync2, readFileSync as readFileSync2, realpathSync, writeFileSync as writeFileSync2 } from "node:fs";
|
|
1229
|
+
import { createRequire } from "node:module";
|
|
1230
|
+
import { basename, dirname as dirname2, extname, isAbsolute as isAbsolute2, join as join3, relative, resolve as resolve3, sep } from "node:path";
|
|
1231
|
+
|
|
1232
|
+
// cli/sourcemap.ts
|
|
1233
|
+
var BASE64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
|
|
1234
|
+
function vlq(segment2) {
|
|
1235
|
+
const values = [];
|
|
1236
|
+
let value = 0;
|
|
1237
|
+
let shift = 0;
|
|
1238
|
+
for (const ch of segment2) {
|
|
1239
|
+
const digit = BASE64.indexOf(ch);
|
|
1240
|
+
if (digit < 0) throw new Error(`Bad base64 VLQ digit "${ch}" in a source map.`);
|
|
1241
|
+
value += (digit & 31) << shift;
|
|
1242
|
+
if (digit & 32) shift += 5;
|
|
1243
|
+
else {
|
|
1244
|
+
values.push(value & 1 ? -(value >>> 1) : value >>> 1);
|
|
1245
|
+
value = shift = 0;
|
|
1246
|
+
}
|
|
1247
|
+
}
|
|
1248
|
+
return values;
|
|
1249
|
+
}
|
|
1250
|
+
function decode(mappings) {
|
|
1251
|
+
let [source, line, column] = [0, 0, 0];
|
|
1252
|
+
return mappings.split(";").map((text) => {
|
|
1253
|
+
let generated = 0;
|
|
1254
|
+
return text.split(",").flatMap((segment2) => {
|
|
1255
|
+
if (!segment2) return [];
|
|
1256
|
+
const v = vlq(segment2);
|
|
1257
|
+
generated += v[0];
|
|
1258
|
+
if (v.length < 4) return [];
|
|
1259
|
+
source += v[1];
|
|
1260
|
+
line += v[2];
|
|
1261
|
+
column += v[3];
|
|
1262
|
+
return [[generated, source, line, column]];
|
|
1263
|
+
});
|
|
1264
|
+
});
|
|
1265
|
+
}
|
|
1266
|
+
function mapStack(text, map2, name) {
|
|
1267
|
+
const lines = decode(map2.mappings);
|
|
1268
|
+
const escaped = name.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
1269
|
+
return text.replace(new RegExp(`${escaped}:(\\d+):(\\d+)`, "g"), (frame, line, column) => {
|
|
1270
|
+
const segments = lines[Number(line) - 1];
|
|
1271
|
+
if (!segments?.length) return frame;
|
|
1272
|
+
const at = Number(column) - 1;
|
|
1273
|
+
const hit = segments.findLast(([generated]) => generated <= at) ?? segments[0];
|
|
1274
|
+
const source = map2.sources[hit[1]];
|
|
1275
|
+
return source === void 0 ? frame : `${source}:${hit[2] + 1}:${hit[3] + 1}`;
|
|
1276
|
+
});
|
|
1277
|
+
}
|
|
1278
|
+
|
|
1279
|
+
// cli/bundle.ts
|
|
1280
|
+
var SRC = resolve3(import.meta.dirname, "../src");
|
|
1281
|
+
var EXTENSIONS = [".tsx", ".ts", ".mts", ".cts", ".jsx", ".js", ".mjs", ".cjs", ".css", ".json"];
|
|
1282
|
+
var BUNDLE_SECONDS = 60;
|
|
1283
|
+
var require2 = createRequire(import.meta.url);
|
|
1284
|
+
var LOADERS = new Map(
|
|
1285
|
+
Object.entries({
|
|
1286
|
+
".ts": "ts",
|
|
1287
|
+
".mts": "ts",
|
|
1288
|
+
".cts": "ts",
|
|
1289
|
+
".tsx": "tsx",
|
|
1290
|
+
".jsx": "jsx",
|
|
1291
|
+
".json": "json",
|
|
1292
|
+
".css": "css",
|
|
1293
|
+
".txt": "text"
|
|
1294
|
+
})
|
|
1295
|
+
);
|
|
1296
|
+
function readManifest(root, cache) {
|
|
1297
|
+
const cached = cache?.get(root);
|
|
1298
|
+
if (cached) return cached;
|
|
1299
|
+
const parsed = JSON.parse(readFileSync2(join3(root, "package.json"), "utf8"));
|
|
1300
|
+
cache?.set(root, parsed);
|
|
1301
|
+
return parsed;
|
|
1302
|
+
}
|
|
1303
|
+
var probe = (base) => [
|
|
1304
|
+
base,
|
|
1305
|
+
base.replace(/\.([mc]?)js(x?)$/, ".$1ts$2"),
|
|
1306
|
+
...EXTENSIONS.map((ext) => base + ext),
|
|
1307
|
+
...EXTENSIONS.map((ext) => join3(base, `index${ext}`))
|
|
1308
|
+
].find(isFile);
|
|
1309
|
+
function packageOf(dir) {
|
|
1310
|
+
for (; ; dir = dirname2(dir)) {
|
|
1311
|
+
if (isFile(join3(dir, "package.json"))) return dir;
|
|
1312
|
+
if (dirname2(dir) === dir) return void 0;
|
|
1313
|
+
}
|
|
1314
|
+
}
|
|
1315
|
+
function browserAlias(root, keys, cache) {
|
|
1316
|
+
const map2 = root && readManifest(root, cache).browser;
|
|
1317
|
+
if (!(map2 instanceof Object)) return void 0;
|
|
1318
|
+
const key = keys.find((k) => Object.hasOwn(map2, k));
|
|
1319
|
+
return key === void 0 ? void 0 : map2[key];
|
|
1320
|
+
}
|
|
1321
|
+
function conditional(target2, conditions) {
|
|
1322
|
+
if (target2 === null) return void 0;
|
|
1323
|
+
if (Array.isArray(target2)) return target2.map((t) => conditional(t, conditions)).find((t) => t !== void 0);
|
|
1324
|
+
if (!(target2 instanceof Object)) return target2;
|
|
1325
|
+
for (const [condition, value] of Object.entries(target2)) {
|
|
1326
|
+
const found = conditions.includes(condition) ? conditional(value, conditions) : void 0;
|
|
1327
|
+
if (found !== void 0) return found;
|
|
1328
|
+
}
|
|
1329
|
+
}
|
|
1330
|
+
function exported(exports, subpath, conditions) {
|
|
1331
|
+
const map2 = new Map(
|
|
1332
|
+
Object.entries(
|
|
1333
|
+
exports instanceof Object && !Array.isArray(exports) && Object.keys(exports).some((k) => k.startsWith(".")) ? exports : { ".": exports }
|
|
1334
|
+
)
|
|
1335
|
+
);
|
|
1336
|
+
const exact = map2.get(subpath);
|
|
1337
|
+
if (exact !== void 0) return conditional(exact, conditions);
|
|
1338
|
+
const patterns = [...map2].filter(([k]) => k.includes("*")).sort(([a], [b]) => b.indexOf("*") - a.indexOf("*"));
|
|
1339
|
+
for (const [key, target2] of patterns) {
|
|
1340
|
+
const [pre, post] = key.split("*");
|
|
1341
|
+
if (subpath.startsWith(pre) && subpath.endsWith(post) && subpath.length >= pre.length + post.length) {
|
|
1342
|
+
return conditional(target2, conditions)?.replaceAll("*", subpath.slice(pre.length, subpath.length - post.length));
|
|
1343
|
+
}
|
|
1344
|
+
}
|
|
1345
|
+
}
|
|
1346
|
+
function packagePath(specifier, from, kind, cache) {
|
|
1347
|
+
const [, name, sub = ""] = specifier.match(/^((?:@[^/]+\/)?[^/]+)(\/.*)?$/) ?? [];
|
|
1348
|
+
if (!name) return void 0;
|
|
1349
|
+
for (let dir = from; ; dir = dirname2(dir)) {
|
|
1350
|
+
const root = join3(dir, "node_modules", name);
|
|
1351
|
+
if (isFile(join3(root, "package.json"))) {
|
|
1352
|
+
const pkg = readManifest(root, cache);
|
|
1353
|
+
if (pkg.exports !== void 0) {
|
|
1354
|
+
const target2 = exported(pkg.exports, `.${sub}`, ["browser", "module", kind, "default"]);
|
|
1355
|
+
return target2 && join3(root, target2);
|
|
1356
|
+
}
|
|
1357
|
+
const browser = pkg.browser instanceof Object || pkg.browser === false ? void 0 : pkg.browser;
|
|
1358
|
+
return join3(root, sub || (browser ?? pkg.module ?? pkg.main ?? "index"));
|
|
1359
|
+
}
|
|
1360
|
+
if (dirname2(dir) === dir) return void 0;
|
|
1361
|
+
}
|
|
1362
|
+
}
|
|
1363
|
+
function resolveImport(specifier, from, kind, bare, cache) {
|
|
1364
|
+
if (bare) {
|
|
1365
|
+
const root2 = packageOf(from);
|
|
1366
|
+
const alias2 = browserAlias(root2, [specifier], cache);
|
|
1367
|
+
if (alias2 === false) return false;
|
|
1368
|
+
if (alias2 && alias2 !== specifier)
|
|
1369
|
+
return alias2.startsWith(".") ? probe(join3(root2, alias2)) : resolveImport(alias2, from, kind, true, cache);
|
|
1370
|
+
}
|
|
1371
|
+
const base = bare ? packagePath(specifier, from, kind, cache) : resolve3(from, specifier);
|
|
1372
|
+
const found = base && probe(base);
|
|
1373
|
+
if (!found) return void 0;
|
|
1374
|
+
const file = realpathSync(found);
|
|
1375
|
+
const root = packageOf(dirname2(file));
|
|
1376
|
+
if (!root) return file;
|
|
1377
|
+
const own = `./${relative(root, file).split(sep).join("/")}`;
|
|
1378
|
+
const plain = own.replace(/\.[^./]+$/, "");
|
|
1379
|
+
const alias = browserAlias(root, [own, own.slice(2), plain, plain.slice(2)], cache);
|
|
1380
|
+
return alias === void 0 || alias === own ? file : alias && probe(join3(root, alias));
|
|
1381
|
+
}
|
|
1382
|
+
var toEsbuildPath = (path) => {
|
|
1383
|
+
const posix = path.replaceAll("\\", "/");
|
|
1384
|
+
return posix.startsWith("/") ? posix : `/${posix}`;
|
|
1385
|
+
};
|
|
1386
|
+
var fromEsbuildPath = (path) => /^\/[A-Za-z]:(?:\/|$)/.test(path) ? path.slice(1) : path;
|
|
1387
|
+
function filesPlugin() {
|
|
1388
|
+
const manifests = /* @__PURE__ */ new Map();
|
|
1389
|
+
return {
|
|
1390
|
+
name: "files",
|
|
1391
|
+
setup(b) {
|
|
1392
|
+
b.onResolve({ filter: /^figdriver$/ }, () => ({ path: toEsbuildPath(join3(SRC, "figma/import.ts")) }));
|
|
1393
|
+
b.onResolve({ filter: /.*/ }, ({ path, resolveDir, kind }) => {
|
|
1394
|
+
const bare = kind !== "entry-point" && !path.startsWith(".") && !isAbsolute2(path);
|
|
1395
|
+
const found = resolveImport(
|
|
1396
|
+
path,
|
|
1397
|
+
fromEsbuildPath(resolveDir),
|
|
1398
|
+
kind === "require-call" ? "require" : "import",
|
|
1399
|
+
bare,
|
|
1400
|
+
manifests
|
|
1401
|
+
);
|
|
1402
|
+
if (found === false) return { path, namespace: "empty" };
|
|
1403
|
+
return found ? { path: toEsbuildPath(found) } : { errors: [{ text: `Could not resolve "${path}"` }] };
|
|
1404
|
+
});
|
|
1405
|
+
b.onLoad({ filter: /.*/, namespace: "empty" }, () => ({ contents: "" }));
|
|
1406
|
+
b.onLoad({ filter: /.*/, namespace: "file" }, ({ path }) => {
|
|
1407
|
+
const file = fromEsbuildPath(path);
|
|
1408
|
+
return {
|
|
1409
|
+
contents: readFileSync2(file),
|
|
1410
|
+
loader: LOADERS.get(extname(file)) ?? "js",
|
|
1411
|
+
resolveDir: toEsbuildPath(dirname2(file))
|
|
1412
|
+
};
|
|
1413
|
+
});
|
|
1414
|
+
}
|
|
1415
|
+
};
|
|
1416
|
+
}
|
|
1417
|
+
var started;
|
|
1418
|
+
async function start() {
|
|
1419
|
+
if (!("self" in globalThis)) Object.assign(globalThis, { self: globalThis });
|
|
1420
|
+
const wasmModule = await WebAssembly.compile(readFileSync2(require2.resolve("esbuild-wasm/esbuild.wasm")));
|
|
1421
|
+
await esbuild.initialize({ wasmModule, worker: false });
|
|
1422
|
+
}
|
|
1423
|
+
async function bundle(entry, define = {}, globalName, sourcemap = false) {
|
|
1424
|
+
let timer;
|
|
1425
|
+
const stalled = new Promise((_, fail2) => {
|
|
1426
|
+
timer = setTimeout(
|
|
1427
|
+
() => fail2(
|
|
1428
|
+
new Problem(
|
|
1429
|
+
`Bundling ${entry} did not finish in ${BUNDLE_SECONDS}s: esbuild-wasm did not answer. Reinstall figdriver so node_modules/esbuild-wasm/esbuild.wasm is whole, or run figdriver with another Node release (22 or later).`
|
|
1430
|
+
)
|
|
1431
|
+
),
|
|
1432
|
+
BUNDLE_SECONDS * 1e3
|
|
1433
|
+
);
|
|
1434
|
+
});
|
|
1435
|
+
const run = async () => {
|
|
1436
|
+
await (started ??= start());
|
|
1437
|
+
return esbuild.build({
|
|
1438
|
+
entryPoints: [entry],
|
|
1439
|
+
absWorkingDir: toEsbuildPath(process.cwd()),
|
|
1440
|
+
bundle: true,
|
|
1441
|
+
write: false,
|
|
1442
|
+
format: "iife",
|
|
1443
|
+
globalName,
|
|
1444
|
+
platform: "browser",
|
|
1445
|
+
define,
|
|
1446
|
+
plugins: [filesPlugin()],
|
|
1447
|
+
tsconfigRaw: {},
|
|
1448
|
+
sourcemap: sourcemap && "inline",
|
|
1449
|
+
sourcesContent: false,
|
|
1450
|
+
logLevel: "silent"
|
|
1451
|
+
});
|
|
1452
|
+
};
|
|
1453
|
+
const result = await Promise.race([run(), stalled]).finally(() => clearTimeout(timer));
|
|
1454
|
+
return result.outputFiles[0].text;
|
|
1455
|
+
}
|
|
1456
|
+
var EVAL_URL = "figdriver-eval.js";
|
|
1457
|
+
var INLINE_MAP = "//# sourceMappingURL=data:application/json;base64,";
|
|
1458
|
+
async function bundleEval(entry) {
|
|
1459
|
+
const text = await bundle(entry, {}, "__figdriverEval", true);
|
|
1460
|
+
const at = text.lastIndexOf(INLINE_MAP);
|
|
1461
|
+
const map2 = JSON.parse(Buffer.from(text.slice(at + INLINE_MAP.length).trim(), "base64").toString("utf8"));
|
|
1462
|
+
return {
|
|
1463
|
+
code: `(() => { ${text.slice(0, at)}
|
|
1464
|
+
const mod = __figdriverEval; const out = mod && "default" in mod ? mod.default : mod; return typeof out === "function" ? out() : out; })()
|
|
1465
|
+
//# sourceURL=${EVAL_URL}`,
|
|
1466
|
+
mapStack: (stack) => mapStack(stack, map2, EVAL_URL)
|
|
1467
|
+
};
|
|
1468
|
+
}
|
|
1469
|
+
function stripComments(svg) {
|
|
1470
|
+
let out = svg;
|
|
1471
|
+
for (let prev = ""; out !== prev; ) {
|
|
1472
|
+
prev = out;
|
|
1473
|
+
out = out.replace(/<!--[\s\S]*?-->/g, "");
|
|
1474
|
+
}
|
|
1475
|
+
return out;
|
|
1476
|
+
}
|
|
1477
|
+
function writeAssets(root, out = `${root}/assets.gen.ts`, assets = `${root}/assets`) {
|
|
1478
|
+
const read = (dir, ext, encode) => existsSync3(dir) ? Object.fromEntries(
|
|
1479
|
+
readdirSync2(dir).filter((f) => ext.test(f)).sort().map((f) => [f.replace(ext, ""), encode(`${dir}/${f}`)])
|
|
1480
|
+
) : {};
|
|
1481
|
+
const base64 = (f) => readFileSync2(f).toString("base64");
|
|
1482
|
+
const encoded = read(`${assets}/img`, /\.(png|jpe?g)$/, base64);
|
|
1483
|
+
const videos = read(`${assets}/video`, /\.(mp4|webm|mov)$/, base64);
|
|
1484
|
+
const icons = read(
|
|
1485
|
+
`${root}/assets/icons`,
|
|
1486
|
+
/\.svg$/,
|
|
1487
|
+
(f) => stripComments(readFileSync2(f, "utf8")).replace(/\s+/g, " ").trim()
|
|
1488
|
+
);
|
|
1489
|
+
writeFileSync2(
|
|
1490
|
+
out,
|
|
1491
|
+
`// Generated by \`figdriver import plugin\`. Do not edit.
|
|
1492
|
+
export const images = ${JSON.stringify(encoded)} as const;
|
|
1493
|
+
export const videos = ${JSON.stringify(videos)} as const;
|
|
1494
|
+
export const icons = ${JSON.stringify(icons, null, 1)} as const;
|
|
1495
|
+
export type ImageName = keyof typeof images;
|
|
1496
|
+
export type VideoName = keyof typeof videos;
|
|
1497
|
+
export type IconSvgName = keyof typeof icons;
|
|
1498
|
+
`
|
|
1499
|
+
);
|
|
1500
|
+
}
|
|
1501
|
+
var manifestOf = (spec) => ({
|
|
1502
|
+
name: "figdriver",
|
|
1503
|
+
id: "figdriver-local",
|
|
1504
|
+
api: "1.0.0",
|
|
1505
|
+
main: "code.js",
|
|
1506
|
+
editorType: /\bslides\s*:\s*true\b/.test(spec) ? ["figma", "slides"] : ["figma"],
|
|
1507
|
+
documentAccess: "dynamic-page"
|
|
1508
|
+
});
|
|
1509
|
+
async function buildDesign(dir) {
|
|
1510
|
+
const entry = `${dir}/index.ts`;
|
|
1511
|
+
if (!existsSync3(entry))
|
|
1512
|
+
throw new Problem(
|
|
1513
|
+
`No ${entry}. A design needs an index.ts entry (run \`figdriver --help\` or see https://github.com/MahmoudOmiesh/figdriver/blob/main/skills/figdriver/references/import.md).`
|
|
1514
|
+
);
|
|
1515
|
+
writeAssets(dir);
|
|
1516
|
+
const out = `${dir}/out/${basename(resolve3(dir))}.js`;
|
|
1517
|
+
const list = [`${dir}/assets.gen.ts`, out, `${dir}/out/plugin/code.js`, `${dir}/out/plugin/manifest.json`];
|
|
1518
|
+
write(out, await bundle(entry, { IS_PLUGIN: "false" }));
|
|
1519
|
+
write(list[2], await bundle(entry, { IS_PLUGIN: "true" }));
|
|
1520
|
+
write(list[3], `${JSON.stringify(manifestOf(readFileSync2(entry, "utf8")), null, 2)}
|
|
1521
|
+
`);
|
|
1522
|
+
return { dir, out, files: list };
|
|
1523
|
+
}
|
|
1524
|
+
|
|
1525
|
+
// cli/session.ts
|
|
1526
|
+
var DEFAULT_WAIT_SECONDS = 600;
|
|
1527
|
+
var inspectBundle;
|
|
1528
|
+
var injected = /* @__PURE__ */ new WeakSet();
|
|
1529
|
+
async function ensureInspect(s) {
|
|
1530
|
+
const code = await (inspectBundle ??= bundle(`${SRC}/figma/inspect.ts`).catch((e) => {
|
|
1531
|
+
inspectBundle = void 0;
|
|
1532
|
+
throw e;
|
|
1533
|
+
}));
|
|
1534
|
+
await s.evaluate(code);
|
|
1535
|
+
injected.add(s);
|
|
1536
|
+
}
|
|
1537
|
+
async function inspect(s, name, ...args) {
|
|
1538
|
+
const call = `figdriver.${name}(${args.map((a) => JSON.stringify(a)).join(", ")})`;
|
|
1539
|
+
if (!injected.has(s)) {
|
|
1540
|
+
await ensureInspect(s);
|
|
1541
|
+
return s.evaluate(call, 300);
|
|
1542
|
+
}
|
|
1543
|
+
try {
|
|
1544
|
+
return await s.evaluate(call, 300);
|
|
1545
|
+
} catch (e) {
|
|
1546
|
+
if (!(e instanceof Problem) || !/figdriver is not defined/.test(e.message)) throw e;
|
|
1547
|
+
await ensureInspect(s);
|
|
1548
|
+
return s.evaluate(call, 300);
|
|
1549
|
+
}
|
|
1550
|
+
}
|
|
1551
|
+
var fileOf = (s, name) => ({
|
|
1552
|
+
name,
|
|
1553
|
+
key: fileKeyOf(s.target.url) ?? "",
|
|
1554
|
+
url: s.target.url
|
|
1555
|
+
});
|
|
1556
|
+
var target = (flags, command, writes) => figmaTarget(flags.file ?? process.env.FIGDRIVER_FILE, command, writes);
|
|
1557
|
+
var waitLog = (line) => console.error(line);
|
|
1558
|
+
async function withFigma(flags, command, use) {
|
|
1559
|
+
const wait = flags.wait === true;
|
|
1560
|
+
const s = await figma(await target(flags, command, false), wait, DEFAULT_WAIT_SECONDS, waitLog);
|
|
1561
|
+
try {
|
|
1562
|
+
if (wait) await s.waitIdle(DEFAULT_WAIT_SECONDS, waitLog);
|
|
1563
|
+
const status = await inspect(s, "status", null, false, false);
|
|
1564
|
+
return await use(s, fileOf(s, status.file), status.page);
|
|
1565
|
+
} finally {
|
|
1566
|
+
s.close();
|
|
1567
|
+
}
|
|
1568
|
+
}
|
|
1569
|
+
async function withWrite(flags, command, timeout, opts, code, use) {
|
|
1570
|
+
const wait = flags.wait === true;
|
|
1571
|
+
const s = await figma(opts.tab ?? await target(flags, command, !opts.readOnly), wait, timeout, waitLog);
|
|
1572
|
+
try {
|
|
1573
|
+
let status;
|
|
1574
|
+
const prepare = async () => {
|
|
1575
|
+
status = await inspect(s, "status", opts.page ?? null, opts.creates === true, false);
|
|
1576
|
+
await opts.prepare?.(s, status);
|
|
1577
|
+
};
|
|
1578
|
+
const run = async () => {
|
|
1579
|
+
if (!opts.readOnly) return s.write(command, prepare, code, timeout, wait, waitLog);
|
|
1580
|
+
if (wait) await s.waitIdle(timeout, waitLog);
|
|
1581
|
+
await prepare();
|
|
1582
|
+
return s.evaluate(code, timeout);
|
|
1583
|
+
};
|
|
1584
|
+
const stopConsole = opts.console ? await s.console((line) => console.error(line)) : void 0;
|
|
1585
|
+
const result = await run().finally(stopConsole);
|
|
1586
|
+
return await use(s, fileOf(s, status.file), status.page, result);
|
|
1587
|
+
} finally {
|
|
1588
|
+
s.close();
|
|
1589
|
+
}
|
|
1590
|
+
}
|
|
1591
|
+
var pageSourceOf = (page) => page === void 0 ? "current" : "flag";
|
|
1592
|
+
var pageSourceLabel = (page) => page === void 0 ? "the file's current page" : "--page";
|
|
1593
|
+
var usersAre = (users) => `${users.join(", ")} ${users.length === 1 ? "is" : "are"}`;
|
|
1594
|
+
function reportAudit(a, say, page) {
|
|
1595
|
+
const where = page && `page "${page.name}" (${page.id})`;
|
|
1596
|
+
if (!a.found) return say(where ? `audit: ${where} holds no layers` : "audit: found nothing built by figdriver");
|
|
1597
|
+
say(
|
|
1598
|
+
`audit: ${a.frames} frames, ${a.texts} texts, ${a.instances} instances, ${where ? `on ${where}` : `built by ${a.owners.join(", ")}`}`
|
|
1599
|
+
);
|
|
1600
|
+
for (const [name, paths] of Object.entries(a.problems).filter(([, paths2]) => paths2.length)) {
|
|
1601
|
+
say(` \u2717 ${name} (${paths.length})`);
|
|
1602
|
+
for (const p of paths.slice(0, 10)) say(` ${p}`);
|
|
1603
|
+
if (paths.length > 10) say(` and ${paths.length - 10} more`);
|
|
1604
|
+
}
|
|
1605
|
+
if (a.clean)
|
|
1606
|
+
say(
|
|
1607
|
+
where ? " \u2713 no problems found" : " \u2713 every frame has auto layout, every text a text style, every instance its main, and no token color is painted raw"
|
|
1608
|
+
);
|
|
1609
|
+
const { offToken, offTokenColors, translucentTokenColors } = a.rawPaints;
|
|
1610
|
+
if (offToken)
|
|
1611
|
+
say(
|
|
1612
|
+
` \xB7 ${offToken} paints use ${offTokenColors.length} colors the theme never named: ${offTokenColors.slice(0, 12).join(" ")}`
|
|
1613
|
+
);
|
|
1614
|
+
if (translucentTokenColors) say(` \xB7 ${translucentTokenColors} translucent token colors stay raw, by design`);
|
|
1615
|
+
}
|
|
1616
|
+
async function writeShotDir(shots, dir, replace, say) {
|
|
1617
|
+
const files = screenFiles(dir, shots, shots[0]?.format);
|
|
1618
|
+
mkdirSync2(dirname3(resolve4(dir)), { recursive: true });
|
|
1619
|
+
const stage = mkdtempSync3(join4(dirname3(resolve4(dir)), ".screens-"));
|
|
1620
|
+
const out = join4(stage, "out");
|
|
1621
|
+
mkdirSync2(out, { recursive: true });
|
|
1622
|
+
try {
|
|
1623
|
+
shots.forEach(({ data }, i) => write(join4(out, basename2(files[i])), Buffer.from(data, "base64")));
|
|
1624
|
+
swapIn(replace ? [[out, dir]] : files.map((f) => [join4(out, basename2(f)), f]));
|
|
1625
|
+
} finally {
|
|
1626
|
+
rmSync3(stage, { recursive: true, force: true });
|
|
1627
|
+
}
|
|
1628
|
+
for (const f of files) say(` ${f}`);
|
|
1629
|
+
return shots.map(({ name, id }, i) => ({ name, id, file: files[i] }));
|
|
1630
|
+
}
|
|
1631
|
+
async function exportScreens(s, dir, design, options, replace, say) {
|
|
1632
|
+
return writeShotDir(await inspect(s, "screens", design, options), dir, replace, say);
|
|
1633
|
+
}
|
|
1634
|
+
|
|
1635
|
+
// cli/commands/browser.ts
|
|
1636
|
+
async function pageTabs() {
|
|
1637
|
+
const list = [];
|
|
1638
|
+
for (const t of await targets()) {
|
|
1639
|
+
if (t.type !== "page") continue;
|
|
1640
|
+
list.push({ id: t.id, title: t.title, url: t.url, fileKey: fileKeyOf(t.url) ?? null });
|
|
1641
|
+
}
|
|
1642
|
+
return list;
|
|
1643
|
+
}
|
|
1644
|
+
function reportOpened(url, reused, newWindow, say) {
|
|
1645
|
+
const fileKey = fileKeyOf(url) ?? null;
|
|
1646
|
+
say(
|
|
1647
|
+
`${reused ? "Focused existing tab" : `Opened${newWindow ? " in a new window" : ""}`} ${url}${fileKey ? ` (${fileKey})` : ""}`
|
|
1648
|
+
);
|
|
1649
|
+
const warnings = reused && newWindow && fileKey ? [
|
|
1650
|
+
`${fileKey} is already open in a tab, so it stays there: write commands refuse a file open in two tabs. Close that tab first to give the file a window of its own.`
|
|
1651
|
+
] : [];
|
|
1652
|
+
for (const w of warnings) say(`! ${w}`);
|
|
1653
|
+
return { fileKey, warnings };
|
|
1654
|
+
}
|
|
1655
|
+
async function runBrowserOpen(arg, newWindow, say) {
|
|
1656
|
+
if (newWindow && !arg) throw new Problem("--new-window opens a URL. Pass the one to open.");
|
|
1657
|
+
if (await running()) {
|
|
1658
|
+
if (arg) {
|
|
1659
|
+
const { target: tab, reused } = await openTab(arg, newWindow);
|
|
1660
|
+
if (isFigmaFile(arg)) {
|
|
1661
|
+
const s = await figma(tab);
|
|
1662
|
+
s.close();
|
|
1663
|
+
}
|
|
1664
|
+
const tabs2 = await pageTabs();
|
|
1665
|
+
const { fileKey, warnings } = reportOpened(arg, reused, newWindow, say);
|
|
1666
|
+
return {
|
|
1667
|
+
command: "browser open",
|
|
1668
|
+
ok: true,
|
|
1669
|
+
action: reused ? "focused" : "opened",
|
|
1670
|
+
browser: null,
|
|
1671
|
+
url: arg,
|
|
1672
|
+
fileKey,
|
|
1673
|
+
reused,
|
|
1674
|
+
tabs: tabs2,
|
|
1675
|
+
warnings,
|
|
1676
|
+
files: []
|
|
1677
|
+
};
|
|
1678
|
+
}
|
|
1679
|
+
const tabs = await pageTabs();
|
|
1680
|
+
say("The debugging browser is already running. Its tabs:");
|
|
1681
|
+
for (const t of tabs) say(` ${t.title} ${t.url}`);
|
|
1682
|
+
return {
|
|
1683
|
+
command: "browser open",
|
|
1684
|
+
ok: true,
|
|
1685
|
+
action: "running",
|
|
1686
|
+
browser: null,
|
|
1687
|
+
url: null,
|
|
1688
|
+
fileKey: null,
|
|
1689
|
+
reused: false,
|
|
1690
|
+
tabs,
|
|
1691
|
+
warnings: [],
|
|
1692
|
+
files: []
|
|
1693
|
+
};
|
|
1694
|
+
}
|
|
1695
|
+
const url = arg ?? "https://www.figma.com/files";
|
|
1696
|
+
const browser = await launch(url);
|
|
1697
|
+
say(
|
|
1698
|
+
`Started ${browser}. Log in to Figma there if it asks, open the design file, then run: figdriver doctor --file <its URL>`
|
|
1699
|
+
);
|
|
1700
|
+
return {
|
|
1701
|
+
command: "browser open",
|
|
1702
|
+
ok: true,
|
|
1703
|
+
action: "started",
|
|
1704
|
+
browser,
|
|
1705
|
+
url,
|
|
1706
|
+
fileKey: fileKeyOf(url) ?? null,
|
|
1707
|
+
reused: false,
|
|
1708
|
+
tabs: [],
|
|
1709
|
+
warnings: [],
|
|
1710
|
+
files: []
|
|
1711
|
+
};
|
|
1712
|
+
}
|
|
1713
|
+
async function runBrowserStop(say) {
|
|
1714
|
+
const stopped = await stopBrowser();
|
|
1715
|
+
say(stopped ? "Stopped the debugging browser." : "The debugging browser is not running.");
|
|
1716
|
+
return {
|
|
1717
|
+
command: "browser stop",
|
|
1718
|
+
ok: true,
|
|
1719
|
+
action: stopped ? "stopped" : "not-running",
|
|
1720
|
+
warnings: [],
|
|
1721
|
+
files: []
|
|
1722
|
+
};
|
|
1723
|
+
}
|
|
1724
|
+
async function runBrowserTabs(say) {
|
|
1725
|
+
const list = await pageTabs();
|
|
1726
|
+
const counts = /* @__PURE__ */ new Map();
|
|
1727
|
+
for (const tab of list) if (tab.fileKey) counts.set(tab.fileKey, (counts.get(tab.fileKey) ?? 0) + 1);
|
|
1728
|
+
const duplicates = [...counts].flatMap(([k, n]) => n > 1 ? [k] : []);
|
|
1729
|
+
const warnings = duplicates.map(
|
|
1730
|
+
(k) => `File ${k} is open in ${counts.get(k)} tabs. Run \`figdriver browser close --duplicates\` before write commands.`
|
|
1731
|
+
);
|
|
1732
|
+
for (const tab of list) say(` ${tab.fileKey ? `${tab.fileKey} ` : ""}${tab.title} ${tab.url}`);
|
|
1733
|
+
for (const w of warnings) say(`! ${w}`);
|
|
1734
|
+
return { command: "browser tabs", ok: true, tabs: list, duplicates, warnings, files: [] };
|
|
1735
|
+
}
|
|
1736
|
+
async function runBrowserClose(wanted, duplicates, say) {
|
|
1737
|
+
const closed = await closeTabs(wanted, duplicates);
|
|
1738
|
+
if (!closed.length) say("No duplicate tabs to close.");
|
|
1739
|
+
else for (const tab of closed) say(`Closed ${tab.fileKey ? `${tab.fileKey} ` : ""}${tab.title} ${tab.url}`);
|
|
1740
|
+
return { command: "browser close", ok: true, closed, warnings: [], files: [] };
|
|
1741
|
+
}
|
|
1742
|
+
async function runBrowserScreenshot(out, flags, say) {
|
|
1743
|
+
if (!out) throw new Problem("Name the PNG file to write, such as out/tab.png.");
|
|
1744
|
+
const wait = flags.wait === true;
|
|
1745
|
+
const tab = await target(flags, "browser screenshot", false);
|
|
1746
|
+
const s = await connect(tab);
|
|
1747
|
+
try {
|
|
1748
|
+
if (wait) await s.waitIdle(DEFAULT_WAIT_SECONDS, waitLog);
|
|
1749
|
+
await s.front();
|
|
1750
|
+
const { data } = await s.send("Page.captureScreenshot", { format: "png" });
|
|
1751
|
+
const status = await s.evaluate("typeof figma") === "object" ? await inspect(s, "status", null, false, false) : null;
|
|
1752
|
+
const file = fileOf(s, status?.file ?? s.target.title.replace(/ – Figma$/, ""));
|
|
1753
|
+
write(out, Buffer.from(data, "base64"));
|
|
1754
|
+
say(out);
|
|
1755
|
+
return { command: "browser screenshot", ok: true, file, page: status?.page ?? null, warnings: [], files: [out] };
|
|
1756
|
+
} finally {
|
|
1757
|
+
s.close();
|
|
1758
|
+
}
|
|
1759
|
+
}
|
|
1760
|
+
async function runDoctor(version, flags, say) {
|
|
1761
|
+
const wait = flags.wait === true;
|
|
1762
|
+
const s = await figma(await target(flags, "doctor", false), wait, DEFAULT_WAIT_SECONDS, waitLog);
|
|
1763
|
+
const [status, currentWrite] = await Promise.all([
|
|
1764
|
+
inspect(s, "status"),
|
|
1765
|
+
s.evaluate("globalThis.figdriverWrite ?? null")
|
|
1766
|
+
]).finally(s.close);
|
|
1767
|
+
const file = fileOf(s, status.file);
|
|
1768
|
+
say(`\u2713 figdriver ${version}`);
|
|
1769
|
+
say(`\u2713 browser attached to ${s.target.url}`);
|
|
1770
|
+
say(
|
|
1771
|
+
`\u2713 file "${status.file}" (${status.editor}), key ${file.key}, ${status.pageCount} page${status.pageCount === 1 ? "" : "s"}, current page "${status.page.name}"`
|
|
1772
|
+
);
|
|
1773
|
+
say(
|
|
1774
|
+
status.capabilities.write ? "\u2713 access the plugin API is up, so this account can edit the file" : "\xB7 access the plugin API is up read-only: Dev Mode cannot edit the file"
|
|
1775
|
+
);
|
|
1776
|
+
const can = Object.entries(status.capabilities).flatMap(([name, on]) => on ? [name] : []);
|
|
1777
|
+
say(`\xB7 can ${can.join(", ") || "nothing beyond reading"}`);
|
|
1778
|
+
if (status.me) say(`\xB7 account ${status.me}`);
|
|
1779
|
+
const warnings = status.users?.length ? [`${usersAre(status.users)} in the file. Their edits can collide with a run.`] : [];
|
|
1780
|
+
if (warnings.length) say(`! people ${warnings[0]}`);
|
|
1781
|
+
else if (!status.users) say("\xB7 people this editor does not say who else is in the file");
|
|
1782
|
+
if (status.editor === "figma" && status.pageCount >= 3) {
|
|
1783
|
+
say(`\xB7 pages ${status.pageCount} (Figma Starter allows 3; import run needs one spare page to stage its build)`);
|
|
1784
|
+
}
|
|
1785
|
+
const { owners } = status;
|
|
1786
|
+
say(
|
|
1787
|
+
owners.length ? `\xB7 built ${owners.join(", ")}. An import run of the same name replaces that output only when it is unedited.` : "\xB7 built nothing from figdriver yet"
|
|
1788
|
+
);
|
|
1789
|
+
const writing = currentWrite && {
|
|
1790
|
+
command: currentWrite.command,
|
|
1791
|
+
seconds: Math.max(0, Math.round((Date.now() - currentWrite.started) / 1e3))
|
|
1792
|
+
};
|
|
1793
|
+
if (currentWrite) {
|
|
1794
|
+
warnings.push(
|
|
1795
|
+
`${inProgress(currentWrite)}, is still writing to this file. Wait for it to finish before the next write.`
|
|
1796
|
+
);
|
|
1797
|
+
say(`! writing ${warnings[warnings.length - 1]}`);
|
|
1798
|
+
} else say("\xB7 writing no figdriver write is in progress in this tab");
|
|
1799
|
+
return {
|
|
1800
|
+
command: "doctor",
|
|
1801
|
+
ok: true,
|
|
1802
|
+
version,
|
|
1803
|
+
browser: s.target.url,
|
|
1804
|
+
file,
|
|
1805
|
+
page: status.page,
|
|
1806
|
+
editor: status.editor,
|
|
1807
|
+
me: status.me,
|
|
1808
|
+
users: status.users,
|
|
1809
|
+
built: owners,
|
|
1810
|
+
writing,
|
|
1811
|
+
pageCount: status.pageCount,
|
|
1812
|
+
capabilities: status.capabilities,
|
|
1813
|
+
warnings,
|
|
1814
|
+
files: []
|
|
1815
|
+
};
|
|
1816
|
+
}
|
|
1817
|
+
|
|
1818
|
+
// cli/commands/edit.ts
|
|
1819
|
+
import { existsSync as existsSync4, readFileSync as readFileSync3 } from "node:fs";
|
|
1820
|
+
|
|
1821
|
+
// cli/eval.ts
|
|
1822
|
+
import * as acorn from "acorn";
|
|
1823
|
+
var PARSE = {
|
|
1824
|
+
ecmaVersion: "latest",
|
|
1825
|
+
allowReturnOutsideFunction: true,
|
|
1826
|
+
allowAwaitOutsideFunction: true
|
|
1827
|
+
};
|
|
1828
|
+
function bareObjectExpression(code) {
|
|
1829
|
+
try {
|
|
1830
|
+
const first = acorn.tokenizer(code, PARSE).getToken();
|
|
1831
|
+
if (first.type.label !== "{") return;
|
|
1832
|
+
const expr = acorn.parseExpressionAt(code, first.start, PARSE);
|
|
1833
|
+
const tail = acorn.parse(code.slice(expr.end), PARSE);
|
|
1834
|
+
if (tail.body.every((s) => s.type === "EmptyStatement")) return code.slice(expr.start, expr.end);
|
|
1835
|
+
} catch {
|
|
1836
|
+
return;
|
|
1837
|
+
}
|
|
1838
|
+
}
|
|
1839
|
+
function wrapEval(code) {
|
|
1840
|
+
const bareObject = bareObjectExpression(code);
|
|
1841
|
+
if (bareObject !== void 0) return `(async () => (
|
|
1842
|
+
${bareObject}
|
|
1843
|
+
))()`;
|
|
1844
|
+
let program;
|
|
1845
|
+
try {
|
|
1846
|
+
program = acorn.parse(code, PARSE);
|
|
1847
|
+
} catch {
|
|
1848
|
+
return `(async () => {
|
|
1849
|
+
${code}
|
|
1850
|
+
})()`;
|
|
1851
|
+
}
|
|
1852
|
+
const last = [...program.body].reverse().find((s) => s.type !== "EmptyStatement");
|
|
1853
|
+
if (last?.type !== "ExpressionStatement") return `(async () => {
|
|
1854
|
+
${code}
|
|
1855
|
+
})()`;
|
|
1856
|
+
const expr = code.slice(last.expression.start, last.expression.end);
|
|
1857
|
+
return `(async () => {
|
|
1858
|
+
${code.slice(0, last.start)}return (
|
|
1859
|
+
${expr}
|
|
1860
|
+
);${code.slice(last.end)}
|
|
1861
|
+
})()`;
|
|
1862
|
+
}
|
|
1863
|
+
|
|
1864
|
+
// cli/commands/edit.ts
|
|
1865
|
+
var DEFAULT_EVAL_TIMEOUT = 600;
|
|
1866
|
+
function sourceOf(path, flags) {
|
|
1867
|
+
if (flags.expression !== void 0 && path !== void 0)
|
|
1868
|
+
throw new Problem("Pass either a script file (or - for stdin) or -e, not both.");
|
|
1869
|
+
if (path === "-" && flags.bundle)
|
|
1870
|
+
throw new Problem("--bundle requires a script file path and cannot be used with - (stdin).");
|
|
1871
|
+
if (flags.bundle && !path) throw new Problem("--bundle requires a script file path.");
|
|
1872
|
+
if (path && path !== "-") {
|
|
1873
|
+
if (!existsSync4(path)) throw new Problem(`No script file at ${path}.`);
|
|
1874
|
+
if (flags.bundle || /\.(?:ts|mts|cts|tsx)$/.test(path)) return { bundle: path };
|
|
1875
|
+
}
|
|
1876
|
+
const code = flags.expression ?? (path ? readFileSync3(path === "-" ? 0 : path, "utf8") : "");
|
|
1877
|
+
if (!code.trim()) throw new Problem("Pass a script file, - to read stdin, or code with -e.");
|
|
1878
|
+
return { code };
|
|
1879
|
+
}
|
|
1880
|
+
async function runEval(path, flags) {
|
|
1881
|
+
const source = sourceOf(path, flags);
|
|
1882
|
+
const pageSource = pageSourceOf(flags.page);
|
|
1883
|
+
const { code, mapStack: mapStack2 = (stack) => stack } = "bundle" in source ? await bundleEval(source.bundle) : { code: wrapEval(source.code) };
|
|
1884
|
+
const prepare = (s, status) => {
|
|
1885
|
+
if (!flags.json)
|
|
1886
|
+
console.error(
|
|
1887
|
+
`eval in "${status.file}" (${fileKeyOf(s.target.url)}), page "${status.page.name}" (${pageSourceLabel(flags.page)})`
|
|
1888
|
+
);
|
|
1889
|
+
};
|
|
1890
|
+
return withWrite(
|
|
1891
|
+
flags,
|
|
1892
|
+
"eval",
|
|
1893
|
+
Number(flags.timeout ?? DEFAULT_EVAL_TIMEOUT),
|
|
1894
|
+
{ page: flags.page, readOnly: flags["read-only"] === true, console: true, prepare },
|
|
1895
|
+
code,
|
|
1896
|
+
(_s, file, page, result) => {
|
|
1897
|
+
if (!flags.json) return console.log(JSON.stringify(result, null, 2));
|
|
1898
|
+
return { command: "eval", ok: true, file, page, pageSource, result, warnings: [], files: [] };
|
|
1899
|
+
}
|
|
1900
|
+
).catch((e) => {
|
|
1901
|
+
const mapped = e instanceof Problem ? mapStack2(e.message) : e.message;
|
|
1902
|
+
throw mapped === e.message ? e : new Problem(mapped);
|
|
1903
|
+
});
|
|
1904
|
+
}
|
|
1905
|
+
|
|
1906
|
+
// cli/commands/import.ts
|
|
1907
|
+
import { existsSync as existsSync7, readFileSync as readFileSync6 } from "node:fs";
|
|
1908
|
+
|
|
1909
|
+
// cli/capture.ts
|
|
1910
|
+
import { existsSync as existsSync5, mkdirSync as mkdirSync3, mkdtempSync as mkdtempSync4, readFileSync as readFileSync4, realpathSync as realpathSync2, rmSync as rmSync4, statSync as statSync2 } from "node:fs";
|
|
1911
|
+
import { createServer } from "node:http";
|
|
1912
|
+
import { basename as basename3, dirname as dirname4, extname as extname2, isAbsolute as isAbsolute4, join as join5, relative as relative2, resolve as resolve5 } from "node:path";
|
|
1913
|
+
import { setTimeout as sleep3 } from "node:timers/promises";
|
|
1914
|
+
import { PNG } from "pngjs";
|
|
1915
|
+
|
|
1916
|
+
// src/core/layout.ts
|
|
1917
|
+
var TOL = 1.5;
|
|
1918
|
+
var near = (a, b, tol = TOL) => Math.abs(a - b) <= tol;
|
|
1919
|
+
var isAbsolute3 = (el) => el.style.position === "absolute" || el.style.position === "fixed";
|
|
1920
|
+
var flowOf = (el) => el.children.filter((c) => !isAbsolute3(c));
|
|
1921
|
+
var start2 = (b, a) => a === "x" ? b[0] : b[1];
|
|
1922
|
+
var size = (b, a) => a === "x" ? b[2] : b[3];
|
|
1923
|
+
var end = (b, a) => start2(b, a) + size(b, a);
|
|
1924
|
+
function contentBox(el) {
|
|
1925
|
+
const [x, y, w, h] = el.box;
|
|
1926
|
+
const { pad, border } = el.style;
|
|
1927
|
+
return [
|
|
1928
|
+
x + border[3] + pad[3],
|
|
1929
|
+
y + border[0] + pad[0],
|
|
1930
|
+
w - border[1] - border[3] - pad[1] - pad[3],
|
|
1931
|
+
h - border[0] - border[2] - pad[0] - pad[2]
|
|
1932
|
+
];
|
|
1933
|
+
}
|
|
1934
|
+
function alignIn(b, within, a) {
|
|
1935
|
+
const lead = start2(b, a) - start2(within, a);
|
|
1936
|
+
const trail = end(within, a) - end(b, a);
|
|
1937
|
+
if (near(lead, 0)) return "MIN";
|
|
1938
|
+
if (near(lead, trail)) return "CENTER";
|
|
1939
|
+
if (near(trail, 0)) return "MAX";
|
|
1940
|
+
return lead < trail ? "MIN" : "MAX";
|
|
1941
|
+
}
|
|
1942
|
+
var tracksOf = (v) => v === "none" ? [] : v.split(" ").map((t) => parseFloat(t)).filter((n) => !Number.isNaN(n));
|
|
1943
|
+
function directionOf(el) {
|
|
1944
|
+
const s = el.style;
|
|
1945
|
+
if (s.display.endsWith("grid") && tracksOf(s.gridCols).length && tracksOf(s.gridRows).length) return "GRID";
|
|
1946
|
+
if (s.display.endsWith("flex")) return s.flexDirection.startsWith("column") ? "VERTICAL" : "HORIZONTAL";
|
|
1947
|
+
const flow = flowOf(el);
|
|
1948
|
+
const [first] = flow;
|
|
1949
|
+
const oneLine = flow.length > 1 && flow.every((c) => c.box[1] < first.box[1] + first.box[3] - 1 && c.box[1] + c.box[3] > first.box[1] + 1);
|
|
1950
|
+
return oneLine ? "HORIZONTAL" : "VERTICAL";
|
|
1951
|
+
}
|
|
1952
|
+
var JUSTIFY = new Map(
|
|
1953
|
+
Object.entries({
|
|
1954
|
+
"flex-start": "MIN",
|
|
1955
|
+
start: "MIN",
|
|
1956
|
+
left: "MIN",
|
|
1957
|
+
normal: "MIN",
|
|
1958
|
+
center: "CENTER",
|
|
1959
|
+
"flex-end": "MAX",
|
|
1960
|
+
end: "MAX",
|
|
1961
|
+
right: "MAX",
|
|
1962
|
+
"space-between": "SPACE_BETWEEN",
|
|
1963
|
+
"space-around": "SPACE_BETWEEN",
|
|
1964
|
+
"space-evenly": "SPACE_BETWEEN"
|
|
1965
|
+
})
|
|
1966
|
+
);
|
|
1967
|
+
var ALIGN = new Map(
|
|
1968
|
+
Object.entries({
|
|
1969
|
+
normal: "MIN",
|
|
1970
|
+
stretch: "MIN",
|
|
1971
|
+
"flex-start": "MIN",
|
|
1972
|
+
start: "MIN",
|
|
1973
|
+
"self-start": "MIN",
|
|
1974
|
+
center: "CENTER",
|
|
1975
|
+
"flex-end": "MAX",
|
|
1976
|
+
end: "MAX",
|
|
1977
|
+
"self-end": "MAX",
|
|
1978
|
+
baseline: "BASELINE"
|
|
1979
|
+
})
|
|
1980
|
+
);
|
|
1981
|
+
var TEXT_ALIGN = new Map(
|
|
1982
|
+
Object.entries({
|
|
1983
|
+
start: "MIN",
|
|
1984
|
+
left: "MIN",
|
|
1985
|
+
center: "CENTER",
|
|
1986
|
+
end: "MAX",
|
|
1987
|
+
right: "MAX",
|
|
1988
|
+
justify: "MIN"
|
|
1989
|
+
})
|
|
1990
|
+
);
|
|
1991
|
+
function trackSpans(sizes, gap, from) {
|
|
1992
|
+
let at = from;
|
|
1993
|
+
return sizes.map((s) => {
|
|
1994
|
+
const span = [at, at + s];
|
|
1995
|
+
at += s + gap;
|
|
1996
|
+
return span;
|
|
1997
|
+
});
|
|
1998
|
+
}
|
|
1999
|
+
var gridCache = /* @__PURE__ */ new WeakMap();
|
|
2000
|
+
function spanIndex(spans, at) {
|
|
2001
|
+
const i = spans.findIndex(([, e]) => at < e);
|
|
2002
|
+
return i < 0 ? spans.length - 1 : i;
|
|
2003
|
+
}
|
|
2004
|
+
function measureCell(c, cols, rows) {
|
|
2005
|
+
const [x, y, w, h] = c.box;
|
|
2006
|
+
const col = spanIndex(cols, x + 1), colEnd = Math.max(col, spanIndex(cols, x + w - 1));
|
|
2007
|
+
const row = spanIndex(rows, y + 1), rowEnd = Math.max(row, spanIndex(rows, y + h - 1));
|
|
2008
|
+
const box = [cols[col][0], rows[row][0], cols[colEnd][1] - cols[col][0], rows[rowEnd][1] - rows[row][0]];
|
|
2009
|
+
return {
|
|
2010
|
+
box,
|
|
2011
|
+
cell: {
|
|
2012
|
+
row,
|
|
2013
|
+
col,
|
|
2014
|
+
rowSpan: rowEnd - row + 1,
|
|
2015
|
+
colSpan: colEnd - col + 1,
|
|
2016
|
+
h: alignIn(c.box, box, "x"),
|
|
2017
|
+
v: alignIn(c.box, box, "y")
|
|
2018
|
+
}
|
|
2019
|
+
};
|
|
2020
|
+
}
|
|
2021
|
+
function gridInfoOf(grid) {
|
|
2022
|
+
const cached = gridCache.get(grid);
|
|
2023
|
+
if (cached) return cached;
|
|
2024
|
+
const cb = contentBox(grid);
|
|
2025
|
+
const cols = trackSpans(tracksOf(grid.style.gridCols), grid.style.gap[1], cb[0]);
|
|
2026
|
+
const rows = trackSpans(tracksOf(grid.style.gridRows), grid.style.gap[0], cb[1]);
|
|
2027
|
+
const cells = /* @__PURE__ */ new Map();
|
|
2028
|
+
const collisions = /* @__PURE__ */ new Set();
|
|
2029
|
+
const occupied = /* @__PURE__ */ new Set();
|
|
2030
|
+
if (cols.length && rows.length) {
|
|
2031
|
+
for (const child of flowOf(grid)) {
|
|
2032
|
+
const measured = measureCell(child, cols, rows);
|
|
2033
|
+
cells.set(child, measured);
|
|
2034
|
+
const { row, col, rowSpan, colSpan } = measured.cell;
|
|
2035
|
+
let clash = false;
|
|
2036
|
+
for (let r = row; r < row + rowSpan && !clash; r++) {
|
|
2037
|
+
for (let k = col; k < col + colSpan; k++) {
|
|
2038
|
+
if (occupied.has(`${r},${k}`)) {
|
|
2039
|
+
clash = true;
|
|
2040
|
+
break;
|
|
2041
|
+
}
|
|
2042
|
+
}
|
|
2043
|
+
}
|
|
2044
|
+
if (clash) {
|
|
2045
|
+
collisions.add(child);
|
|
2046
|
+
continue;
|
|
2047
|
+
}
|
|
2048
|
+
for (let r = row; r < row + rowSpan; r++) {
|
|
2049
|
+
for (let k = col; k < col + colSpan; k++) occupied.add(`${r},${k}`);
|
|
2050
|
+
}
|
|
2051
|
+
}
|
|
2052
|
+
}
|
|
2053
|
+
const info = { cols, rows, cells, collisions };
|
|
2054
|
+
gridCache.set(grid, info);
|
|
2055
|
+
return info;
|
|
2056
|
+
}
|
|
2057
|
+
function gridCellCollisions(grid) {
|
|
2058
|
+
return directionOf(grid) === "GRID" ? gridInfoOf(grid).collisions : /* @__PURE__ */ new Set();
|
|
2059
|
+
}
|
|
2060
|
+
var SYNTHETIC_TAGS = { stack: "Stack", offset: "Offset", align: "Wrapper" };
|
|
2061
|
+
|
|
2062
|
+
// src/core/naming.ts
|
|
2063
|
+
var SYNTHETIC_ROLES = new Map(Object.entries(SYNTHETIC_TAGS));
|
|
2064
|
+
var TAG_ROLES = new Map(
|
|
2065
|
+
Object.entries({
|
|
2066
|
+
h1: "Heading",
|
|
2067
|
+
h2: "Heading",
|
|
2068
|
+
h3: "Heading",
|
|
2069
|
+
h4: "Heading",
|
|
2070
|
+
h5: "Heading",
|
|
2071
|
+
h6: "Heading",
|
|
2072
|
+
p: "Paragraph",
|
|
2073
|
+
a: "Link",
|
|
2074
|
+
button: "Button",
|
|
2075
|
+
nav: "Navigation",
|
|
2076
|
+
ul: "List",
|
|
2077
|
+
ol: "List",
|
|
2078
|
+
li: "Item",
|
|
2079
|
+
img: "Image",
|
|
2080
|
+
svg: "Icon",
|
|
2081
|
+
header: "Header",
|
|
2082
|
+
footer: "Footer",
|
|
2083
|
+
section: "Section",
|
|
2084
|
+
article: "Card",
|
|
2085
|
+
main: "Main"
|
|
2086
|
+
})
|
|
2087
|
+
);
|
|
2088
|
+
var titleCase = (s) => s.split(/[-_\s]+/).filter(Boolean).map((w) => w[0].toUpperCase() + w.slice(1)).join(" ");
|
|
2089
|
+
function nameOf(el) {
|
|
2090
|
+
const synthetic = SYNTHETIC_ROLES.get(el.tag);
|
|
2091
|
+
if (synthetic) return synthetic;
|
|
2092
|
+
if (el.tag.startsWith("::")) return "Decoration";
|
|
2093
|
+
const element = el.cls.find((c) => c.includes("__"));
|
|
2094
|
+
if (element) return titleCase(element.split("__")[1].split("--")[0]);
|
|
2095
|
+
const block = el.cls.find((c) => !c.includes("--"));
|
|
2096
|
+
if (block) return titleCase(block);
|
|
2097
|
+
return TAG_ROLES.get(el.tag) ?? (el.kind === "text" ? "Label" : "Frame");
|
|
2098
|
+
}
|
|
2099
|
+
|
|
2100
|
+
// src/core/foundations.ts
|
|
2101
|
+
var svgInner = (svg) => svg.replace(/^<svg[^>]*>|<\/svg>$/g, "");
|
|
2102
|
+
var iconKey = (el) => svgInner(el.svg).replace(/ (stroke|fill|style|color)="[^"]*"/g, "");
|
|
2103
|
+
var PAINT = / (?:fill|stroke)="([^"]*)"/g;
|
|
2104
|
+
function isSimpleIcon(el) {
|
|
2105
|
+
if (el.box[2] > 64 || el.box[3] > 64 || /<(defs|linearGradient|radialGradient|text|image|filter)\b/.test(el.svg))
|
|
2106
|
+
return false;
|
|
2107
|
+
const paints = /* @__PURE__ */ new Set();
|
|
2108
|
+
for (const [, value] of el.svg.matchAll(PAINT)) {
|
|
2109
|
+
if (value === "none" || value === "transparent") continue;
|
|
2110
|
+
const c = parseColor(value);
|
|
2111
|
+
if (!c) return false;
|
|
2112
|
+
if (c.a > 0) paints.add(`${hexOf(c)} ${c.a}`);
|
|
2113
|
+
}
|
|
2114
|
+
return paints.size <= 1;
|
|
2115
|
+
}
|
|
2116
|
+
|
|
2117
|
+
// cli/capture.ts
|
|
2118
|
+
var MIME = new Map(
|
|
2119
|
+
Object.entries({
|
|
2120
|
+
".html": "text/html",
|
|
2121
|
+
".css": "text/css",
|
|
2122
|
+
".js": "text/javascript",
|
|
2123
|
+
".mjs": "text/javascript",
|
|
2124
|
+
".json": "application/json",
|
|
2125
|
+
".svg": "image/svg+xml",
|
|
2126
|
+
".png": "image/png",
|
|
2127
|
+
".jpg": "image/jpeg",
|
|
2128
|
+
".jpeg": "image/jpeg",
|
|
2129
|
+
".gif": "image/gif",
|
|
2130
|
+
".webp": "image/webp",
|
|
2131
|
+
".avif": "image/avif",
|
|
2132
|
+
".mp4": "video/mp4",
|
|
2133
|
+
".webm": "video/webm",
|
|
2134
|
+
".mov": "video/quicktime",
|
|
2135
|
+
".ico": "image/x-icon",
|
|
2136
|
+
".woff": "font/woff",
|
|
2137
|
+
".woff2": "font/woff2",
|
|
2138
|
+
".ttf": "font/ttf",
|
|
2139
|
+
".otf": "font/otf"
|
|
2140
|
+
})
|
|
2141
|
+
);
|
|
2142
|
+
var STABLE_ORIGIN = "http://localhost:4873";
|
|
2143
|
+
function servedFile(root, path) {
|
|
2144
|
+
const file = resolve5(root, `.${path}`);
|
|
2145
|
+
const inside = relative2(root, file);
|
|
2146
|
+
if (inside.startsWith("..") || isAbsolute4(inside) || !existsSync5(file)) return void 0;
|
|
2147
|
+
return realpathSync2(file) === file && statSync2(file).isFile() ? file : void 0;
|
|
2148
|
+
}
|
|
2149
|
+
async function serve(source) {
|
|
2150
|
+
const [typed, hash] = source.split("#");
|
|
2151
|
+
const path = resolve5(typed);
|
|
2152
|
+
if (!existsSync5(path)) throw new Problem(`No file or folder at ${path}`);
|
|
2153
|
+
const isDir = statSync2(path).isDirectory();
|
|
2154
|
+
const root = realpathSync2(isDir ? path : dirname4(path));
|
|
2155
|
+
const index = isDir ? "index.html" : basename3(path);
|
|
2156
|
+
const server = createServer((req, res) => {
|
|
2157
|
+
let file;
|
|
2158
|
+
try {
|
|
2159
|
+
file = servedFile(
|
|
2160
|
+
root,
|
|
2161
|
+
decodeURIComponent(new URL(req.url ?? "/", "http://localhost").pathname).replace(/\/$/, `/${index}`)
|
|
2162
|
+
);
|
|
2163
|
+
} catch {
|
|
2164
|
+
}
|
|
2165
|
+
if (!file) return res.writeHead(404).end("Not found");
|
|
2166
|
+
res.writeHead(200, { "content-type": MIME.get(extname2(file).toLowerCase()) ?? "application/octet-stream" }).end(readFileSync4(file));
|
|
2167
|
+
});
|
|
2168
|
+
await new Promise((done, fail2) => server.once("error", fail2).listen(0, "127.0.0.1", done));
|
|
2169
|
+
const origin = `http://127.0.0.1:${server.address().port}`;
|
|
2170
|
+
return {
|
|
2171
|
+
url: `${origin}/${index === "index.html" ? "" : index}${hash ? `#${hash}` : ""}`,
|
|
2172
|
+
stable: (text) => text.replaceAll(origin, STABLE_ORIGIN),
|
|
2173
|
+
stop() {
|
|
2174
|
+
server.closeAllConnections();
|
|
2175
|
+
server.close();
|
|
2176
|
+
}
|
|
2177
|
+
};
|
|
2178
|
+
}
|
|
2179
|
+
function lint(snapshot) {
|
|
2180
|
+
const found = /* @__PURE__ */ new Map();
|
|
2181
|
+
const note = (issue, el, where = selectorOf(el)) => found.set(issue, (found.get(issue) ?? /* @__PURE__ */ new Set()).add(where));
|
|
2182
|
+
walk(snapshot.root, (el) => {
|
|
2183
|
+
if (el.style.margin.some((m) => m < 0))
|
|
2184
|
+
note(
|
|
2185
|
+
"Negative margin. Auto layout rejects negative padding, so the run can fail. Use padding or absolute positioning in the page",
|
|
2186
|
+
el
|
|
2187
|
+
);
|
|
2188
|
+
for (const color of [el.style.bg, el.style.borderColor, ...el.kind === "text" ? el.runs.map((r) => r.color) : []])
|
|
2189
|
+
if (color && !parseColor(color))
|
|
2190
|
+
note(
|
|
2191
|
+
`Color ${color.split("(")[0]}(). The importer cannot read it, so it is dropped. Use a CSS Color 4 color such as rgb, hex, hsl, hwb, lab, lch, oklab, oklch, or color()`,
|
|
2192
|
+
el
|
|
2193
|
+
);
|
|
2194
|
+
if (el.style.shadow !== "none" && !shadowsOf(el.style.shadow).length)
|
|
2195
|
+
note(
|
|
2196
|
+
"Shadow the importer cannot read, so it is dropped. Give each layer a color and px offsets, blur and spread",
|
|
2197
|
+
el
|
|
2198
|
+
);
|
|
2199
|
+
if (el.kind === "svg" && !isSimpleIcon(el))
|
|
2200
|
+
note(
|
|
2201
|
+
"SVG with several colors, gradients or text, or larger than 64px. It is imported as a vector frame in its own colors, not as a recolorable icon component",
|
|
2202
|
+
el
|
|
2203
|
+
);
|
|
2204
|
+
if (el.kind === "svg" && /<(text|filter)\b/.test(el.svg))
|
|
2205
|
+
note("SVG text or filter. Figma turns SVG text into outlines and can drop SVG filters", el);
|
|
2206
|
+
if (el.kind === "frame") {
|
|
2207
|
+
for (const p of el.pseudos)
|
|
2208
|
+
if (p.style.margin.some((m) => m < 0))
|
|
2209
|
+
note(
|
|
2210
|
+
"Negative margin on a pseudo-element. It is placed where the browser drew it, but auto layout cannot hold the overlap. Position it absolutely in the page",
|
|
2211
|
+
el,
|
|
2212
|
+
`${selectorOf(el)}::${p.which}`
|
|
2213
|
+
);
|
|
2214
|
+
}
|
|
2215
|
+
if (el.kind === "frame" && gridCellCollisions(el).size > 0)
|
|
2216
|
+
note(
|
|
2217
|
+
"CSS Grid has overlapping items in the same cell. Figma Grid forbids shared cells, so overlapping items fall back to absolute positioning",
|
|
2218
|
+
el
|
|
2219
|
+
);
|
|
2220
|
+
if (el.kind === "frame" && el.children.some((c) => c.tag === "#text") && el.children.some((c) => c.kind === "frame" && c.style.display === "inline"))
|
|
2221
|
+
note(
|
|
2222
|
+
"Painted inline element inside text. Figma text runs cannot carry background or border fills, so inline highlights split into separate frames",
|
|
2223
|
+
el
|
|
2224
|
+
);
|
|
2225
|
+
});
|
|
2226
|
+
const warnings = [...found].map(([issue, where]) => `${issue}: ${truncateList([...where], 8)}`);
|
|
2227
|
+
if (!Object.keys(snapshot.tokens).length)
|
|
2228
|
+
warnings.push(
|
|
2229
|
+
"No :root custom properties. Colors become variables only when the page declares them as tokens, such as --primary"
|
|
2230
|
+
);
|
|
2231
|
+
return warnings;
|
|
2232
|
+
}
|
|
2233
|
+
function starter(name, snapshot) {
|
|
2234
|
+
const all = snapshot.root.kind === "frame" && snapshot.root.children.length ? snapshot.root.children : [snapshot.root];
|
|
2235
|
+
const keyOf2 = (el) => el.cls.find((c) => all.every((o) => o === el || !o.cls.includes(c))) ?? el.cls[0];
|
|
2236
|
+
const top = all.filter((el, i) => !el.cls.length || all.findIndex((o) => keyOf2(o) === keyOf2(el)) === i);
|
|
2237
|
+
const names = top.map((el) => {
|
|
2238
|
+
const key = keyOf2(el);
|
|
2239
|
+
return key?.includes("--") && !key.includes("__") ? titleCase(key.split("--").pop()) : nameOf(el);
|
|
2240
|
+
});
|
|
2241
|
+
const unique = names.map(
|
|
2242
|
+
(n, i) => names.indexOf(n) === i ? n : `${n} ${names.slice(0, i + 1).filter((m) => m === n).length}`
|
|
2243
|
+
);
|
|
2244
|
+
const rule = (el) => el.cls.length ? `has(${JSON.stringify(keyOf2(el))})` : `at(${JSON.stringify(el.tag)}, ${JSON.stringify(el.box)})`;
|
|
2245
|
+
const helpers = [
|
|
2246
|
+
top.some((el) => el.cls.length) && "const has = (cls: string): Match => (el) => el.cls.includes(cls);\n",
|
|
2247
|
+
top.some((el) => !el.cls.length) && "const at = (tag: string, box: number[]): Match => (el) => el.tag === tag && el.box.every((v, i) => v === box[i]);\n"
|
|
2248
|
+
];
|
|
2249
|
+
return `import { importDesign, type Match } from "figdriver";
|
|
2250
|
+
import { images, videos } from "./assets.gen";
|
|
2251
|
+
import snapshot from "./snapshot.json";
|
|
2252
|
+
|
|
2253
|
+
${helpers.filter(Boolean).join("")}
|
|
2254
|
+
importDesign({
|
|
2255
|
+
name: ${JSON.stringify(titleCase(name))},
|
|
2256
|
+
snapshot,
|
|
2257
|
+
images,
|
|
2258
|
+
videos,
|
|
2259
|
+
sections: [
|
|
2260
|
+
${top.map((el, i) => ` { name: ${JSON.stringify(unique[i])}, match: ${rule(el)} },
|
|
2261
|
+
`).join("")} ],
|
|
2262
|
+
components: [],
|
|
2263
|
+
});
|
|
2264
|
+
`;
|
|
2265
|
+
}
|
|
2266
|
+
var KEEP_WEBGL_PIXELS = `{
|
|
2267
|
+
const getContext = HTMLCanvasElement.prototype.getContext;
|
|
2268
|
+
HTMLCanvasElement.prototype.getContext = function (type, options) {
|
|
2269
|
+
return getContext.call(this, type, /webgl/.test(type) ? { ...options, preserveDrawingBuffer: true } : options);
|
|
2270
|
+
};
|
|
2271
|
+
}`;
|
|
2272
|
+
var EXTENSIONS2 = /* @__PURE__ */ new Map([
|
|
2273
|
+
["image/jpeg", "img/{}.jpg"],
|
|
2274
|
+
["video/mp4", "video/{}.mp4"],
|
|
2275
|
+
["video/webm", "video/{}.webm"],
|
|
2276
|
+
["video/quicktime", "video/{}.mov"]
|
|
2277
|
+
]);
|
|
2278
|
+
async function navigate(page, url) {
|
|
2279
|
+
const { errorText } = await page.send("Page.navigate", { url });
|
|
2280
|
+
if (errorText) throw new Problem(`Could not open ${url}: ${errorText}`);
|
|
2281
|
+
for (let i = 0; i < 60; i++) {
|
|
2282
|
+
if (await page.evaluate(`document.readyState === "complete" && location.href !== "about:blank"`)) return;
|
|
2283
|
+
await sleep3(500);
|
|
2284
|
+
}
|
|
2285
|
+
throw new Problem(`${url} did not finish loading in 30s.`);
|
|
2286
|
+
}
|
|
2287
|
+
var SCREENSHOT_TILE = 8192;
|
|
2288
|
+
async function captureScreenshot(shoot, width, height, tileSize = SCREENSHOT_TILE) {
|
|
2289
|
+
const w = Math.max(1, Math.round(width));
|
|
2290
|
+
const h = Math.max(1, Math.round(height));
|
|
2291
|
+
if (w <= tileSize && h <= tileSize) return shoot(0, 0, w, h);
|
|
2292
|
+
const out = new PNG({ width: w, height: h });
|
|
2293
|
+
for (let y = 0; y < h; y += tileSize) {
|
|
2294
|
+
const th = Math.min(tileSize, h - y);
|
|
2295
|
+
for (let x = 0; x < w; x += tileSize) {
|
|
2296
|
+
const tw = Math.min(tileSize, w - x);
|
|
2297
|
+
const tile = PNG.sync.read(await shoot(x, y, tw, th));
|
|
2298
|
+
PNG.bitblt(tile, out, 0, 0, Math.min(tw, tile.width), Math.min(th, tile.height), x, y);
|
|
2299
|
+
}
|
|
2300
|
+
}
|
|
2301
|
+
return PNG.sync.write(out);
|
|
2302
|
+
}
|
|
2303
|
+
function viewportsOf(typed) {
|
|
2304
|
+
const sizes = typed.split(",");
|
|
2305
|
+
const twice = sizes.find((v, i) => sizes.indexOf(v) !== i);
|
|
2306
|
+
if (twice) throw new Problem(`--viewport lists ${twice} twice.`);
|
|
2307
|
+
return sizes.map((v) => {
|
|
2308
|
+
const [width, height] = v.split("x").map(Number);
|
|
2309
|
+
return [width, height];
|
|
2310
|
+
});
|
|
2311
|
+
}
|
|
2312
|
+
function bestOverlap(rect, frames) {
|
|
2313
|
+
const score = (f) => {
|
|
2314
|
+
const w = Math.min(rect.x + rect.w, f.x + f.w) - Math.max(rect.x, f.x);
|
|
2315
|
+
const h = Math.min(rect.y + rect.h, f.y + f.h) - Math.max(rect.y, f.y);
|
|
2316
|
+
const shared = Math.max(0, w) * Math.max(0, h);
|
|
2317
|
+
return shared && shared / (rect.w * rect.h + f.w * f.h - shared);
|
|
2318
|
+
};
|
|
2319
|
+
const scores = frames.map(score);
|
|
2320
|
+
const best = Math.max(0, ...scores);
|
|
2321
|
+
return best > 0 ? scores.indexOf(best) : -1;
|
|
2322
|
+
}
|
|
2323
|
+
var EMBED_RECT = (id) => `(async () => {
|
|
2324
|
+
const n = await figma.getNodeByIdAsync(${JSON.stringify(id)});
|
|
2325
|
+
figma.viewport.scrollAndZoomIntoView([n]);
|
|
2326
|
+
const v = figma.viewport.bounds, b = n.absoluteBoundingBox;
|
|
2327
|
+
return { x: (b.x - v.x) / v.width, y: (b.y - v.y) / v.height, w: b.width / v.width, h: b.height / v.height };
|
|
2328
|
+
})()`;
|
|
2329
|
+
var FRAME_RECTS = `(() => {
|
|
2330
|
+
const c = document.querySelector("canvas")?.getBoundingClientRect();
|
|
2331
|
+
if (!c) return [];
|
|
2332
|
+
return [...document.querySelectorAll("iframe")].map((f) => {
|
|
2333
|
+
const r = f.getBoundingClientRect();
|
|
2334
|
+
return { src: f.src, x: (r.x - c.x) / c.width, y: (r.y - c.y) / c.height, w: r.width / c.width, h: r.height / c.height };
|
|
2335
|
+
});
|
|
2336
|
+
})()`;
|
|
2337
|
+
var originOf = (url) => URL.parse(url)?.origin;
|
|
2338
|
+
async function makeEmbed(getTarget, wanted) {
|
|
2339
|
+
const file = await figma(await getTarget());
|
|
2340
|
+
try {
|
|
2341
|
+
const embeds = await file.evaluate(
|
|
2342
|
+
`figma.currentPage.findAll((n) => n.type === "CODE_INSTANCE").map((n) => n.id)`
|
|
2343
|
+
);
|
|
2344
|
+
if (wanted !== void 0 && !embeds.includes(wanted))
|
|
2345
|
+
throw new Problem(
|
|
2346
|
+
`The current page holds no Figma Make embed ${wanted}. Its embeds: ${embeds.join(", ") || "none"}.`
|
|
2347
|
+
);
|
|
2348
|
+
const previews = (await targets()).filter(
|
|
2349
|
+
(t) => t.type === "iframe" && isMakePreview(t.url) && (!t.parentId || t.parentId === file.target.id)
|
|
2350
|
+
);
|
|
2351
|
+
if (!previews.length)
|
|
2352
|
+
throw new Problem(
|
|
2353
|
+
"No Figma Make preview is running in the open file. Open the file that holds the Make embed, or pass a URL or an HTML file to capture."
|
|
2354
|
+
);
|
|
2355
|
+
let preview = previews[0];
|
|
2356
|
+
if (wanted !== void 0 && previews.length > 1) {
|
|
2357
|
+
const rect = await file.evaluate(EMBED_RECT(wanted));
|
|
2358
|
+
await sleep3(500);
|
|
2359
|
+
const frames = await file.evaluate(FRAME_RECTS);
|
|
2360
|
+
const drawn = frames[bestOverlap(rect, frames)];
|
|
2361
|
+
const found = drawn && previews.find((t) => originOf(t.url) === originOf(drawn.src));
|
|
2362
|
+
if (!found)
|
|
2363
|
+
throw new Problem(
|
|
2364
|
+
`${previews.length} Figma Make previews are running, and figdriver could not tell which one draws ${wanted}. Keep only that embed's preview running, then capture again.`
|
|
2365
|
+
);
|
|
2366
|
+
preview = found;
|
|
2367
|
+
}
|
|
2368
|
+
const warning = wanted === void 0 && embeds.length !== 1 ? `The file's current page holds ${embeds.length} Figma Make embeds, so the capture cannot tell which one it is. A rebuild lands beside them and hides none. Pass --embed <node-id> to name one.` : void 0;
|
|
2369
|
+
return { page: await connect(preview), embed: wanted ?? (embeds.length === 1 ? embeds[0] : void 0), warning };
|
|
2370
|
+
} finally {
|
|
2371
|
+
file.close();
|
|
2372
|
+
}
|
|
2373
|
+
}
|
|
2374
|
+
async function screenshotOf(page) {
|
|
2375
|
+
const [w, h] = await page.evaluate(
|
|
2376
|
+
"[document.documentElement.scrollWidth, document.documentElement.scrollHeight]"
|
|
2377
|
+
);
|
|
2378
|
+
return captureScreenshot(
|
|
2379
|
+
async (x, y, width, height) => {
|
|
2380
|
+
const { data } = await page.send(
|
|
2381
|
+
"Page.captureScreenshot",
|
|
2382
|
+
{ format: "png", captureBeyondViewport: true, clip: { x, y, width, height, scale: 1 } },
|
|
2383
|
+
60
|
|
2384
|
+
);
|
|
2385
|
+
return Buffer.from(data, "base64");
|
|
2386
|
+
},
|
|
2387
|
+
w,
|
|
2388
|
+
h
|
|
2389
|
+
);
|
|
2390
|
+
}
|
|
2391
|
+
async function captureInto(dir, page, screenshot, stable, embed, say) {
|
|
2392
|
+
mkdirSync3(dir, { recursive: true });
|
|
2393
|
+
const stage = mkdtempSync4(join5(dir, ".capture-"));
|
|
2394
|
+
try {
|
|
2395
|
+
await page.evaluate(await bundle(`${SRC}/page/capture.ts`));
|
|
2396
|
+
const { snapshot, bytes, skipped, notes, hasClips } = await page.evaluate("designCapture", 180);
|
|
2397
|
+
let shot = screenshot ? await screenshotOf(page) : void 0;
|
|
2398
|
+
if (hasClips) {
|
|
2399
|
+
await page.send("Emulation.setEmulatedMedia", {
|
|
2400
|
+
features: [{ name: "prefers-reduced-motion", value: "no-preference" }]
|
|
2401
|
+
});
|
|
2402
|
+
await sleep3(1e3);
|
|
2403
|
+
const clips = await page.evaluate("designClips()", 120);
|
|
2404
|
+
if (screenshot && Object.values(clips.assets).some((a) => !a.mime.startsWith("video/")))
|
|
2405
|
+
shot = await screenshotOf(page);
|
|
2406
|
+
await page.send("Emulation.setEmulatedMedia", {
|
|
2407
|
+
features: screenshot ? [{ name: "prefers-reduced-motion", value: "reduce" }] : []
|
|
2408
|
+
});
|
|
2409
|
+
Object.assign(snapshot.assets, clips.assets);
|
|
2410
|
+
Object.assign(bytes, clips.bytes);
|
|
2411
|
+
skipped.push(...clips.skipped);
|
|
2412
|
+
}
|
|
2413
|
+
snapshot.root = withoutImages(snapshot.root, (name) => !snapshot.assets[name]);
|
|
2414
|
+
const used = /* @__PURE__ */ new Set();
|
|
2415
|
+
walk(snapshot.root, (el) => {
|
|
2416
|
+
if (el.kind === "image") {
|
|
2417
|
+
used.add(el.image);
|
|
2418
|
+
if (el.video) used.add(el.video);
|
|
2419
|
+
} else if (el.kind === "frame") for (const name of el.bgImages) used.add(name);
|
|
2420
|
+
});
|
|
2421
|
+
for (const name of Object.keys(snapshot.assets)) if (!used.has(name)) delete snapshot.assets[name];
|
|
2422
|
+
if (embed !== void 0) snapshot.embed = embed;
|
|
2423
|
+
const moved = ["assets/img", "assets/video", "snapshot.json", "assets.gen.ts"];
|
|
2424
|
+
mkdirSync3(`${stage}/assets/img`, { recursive: true });
|
|
2425
|
+
mkdirSync3(`${stage}/assets/video`, { recursive: true });
|
|
2426
|
+
const images = [];
|
|
2427
|
+
const videos = [];
|
|
2428
|
+
for (const [name, asset] of Object.entries(snapshot.assets)) {
|
|
2429
|
+
const file = `assets/${EXTENSIONS2.get(asset.mime) ?? "img/{}.png"}`.replace("{}", name);
|
|
2430
|
+
write(`${stage}/${file}`, Buffer.from(bytes[name], "base64"));
|
|
2431
|
+
if (asset.mime.startsWith("video/")) videos.push(`${dir}/${file}`);
|
|
2432
|
+
else images.push(`${dir}/${file}`);
|
|
2433
|
+
}
|
|
2434
|
+
write(`${stage}/snapshot.json`, stable(JSON.stringify(snapshot)));
|
|
2435
|
+
writeAssets(dir, `${stage}/assets.gen.ts`, `${stage}/assets`);
|
|
2436
|
+
if (shot) {
|
|
2437
|
+
write(`${stage}/ref/page.png`, shot);
|
|
2438
|
+
moved.push("ref/page.png");
|
|
2439
|
+
}
|
|
2440
|
+
const spec = existsSync5(`${dir}/index.ts`) ? null : `${dir}/index.ts`;
|
|
2441
|
+
if (spec) {
|
|
2442
|
+
write(`${stage}/index.ts`, starter(basename3(resolve5(dir)), snapshot));
|
|
2443
|
+
moved.push("index.ts");
|
|
2444
|
+
}
|
|
2445
|
+
swapIn(moved.map((path) => [`${stage}/${path}`, `${dir}/${path}`]));
|
|
2446
|
+
const files = [...images, ...videos, `${dir}/snapshot.json`, `${dir}/assets.gen.ts`];
|
|
2447
|
+
const media = `${images.length} images${videos.length ? `, ${videos.length} video${videos.length > 1 ? "s" : ""}` : ""}`;
|
|
2448
|
+
say(
|
|
2449
|
+
`${dir}/snapshot.json ${snapshot.viewport.join("\xD7")}, ${media}, ${Object.keys(snapshot.tokens).length} tokens`
|
|
2450
|
+
);
|
|
2451
|
+
const reference = screenshot ? `${dir}/ref/page.png` : null;
|
|
2452
|
+
if (reference) {
|
|
2453
|
+
files.push(reference);
|
|
2454
|
+
say(`${reference} the page as the browser drew it, for \`figdriver import parity ${dir}\``);
|
|
2455
|
+
}
|
|
2456
|
+
const skippedImages = skipped.map(({ url, reason }) => ({ url: stable(url), reason }));
|
|
2457
|
+
const warnings = [
|
|
2458
|
+
...skippedImages.map(({ url, reason }) => `${url} was left out: ${reason}.`),
|
|
2459
|
+
...notes ?? [],
|
|
2460
|
+
...lint(snapshot)
|
|
2461
|
+
];
|
|
2462
|
+
for (const warning of warnings) say(`! ${warning}`);
|
|
2463
|
+
if (spec) {
|
|
2464
|
+
files.push(spec);
|
|
2465
|
+
say(`${spec} a starter spec. Next: figdriver import outline ${dir}, then fill in its sections and components`);
|
|
2466
|
+
}
|
|
2467
|
+
return {
|
|
2468
|
+
dir,
|
|
2469
|
+
viewport: snapshot.viewport,
|
|
2470
|
+
snapshot: `${dir}/snapshot.json`,
|
|
2471
|
+
tokens: Object.keys(snapshot.tokens).length,
|
|
2472
|
+
images,
|
|
2473
|
+
videos,
|
|
2474
|
+
skippedImages,
|
|
2475
|
+
reference,
|
|
2476
|
+
starter: spec,
|
|
2477
|
+
warnings,
|
|
2478
|
+
files
|
|
2479
|
+
};
|
|
2480
|
+
} finally {
|
|
2481
|
+
rmSync4(stage, { recursive: true, force: true });
|
|
2482
|
+
}
|
|
2483
|
+
}
|
|
2484
|
+
async function runCapture(dir, source, viewport, embed, getTarget, say) {
|
|
2485
|
+
const viewports = viewportsOf(viewport);
|
|
2486
|
+
if (!source && viewports.length > 1)
|
|
2487
|
+
throw new Problem(
|
|
2488
|
+
"Several --viewport sizes need a URL or an HTML file to capture: a Figma Make embed renders at its own size."
|
|
2489
|
+
);
|
|
2490
|
+
if (source && embed !== void 0)
|
|
2491
|
+
throw new Problem("--embed names a Figma Make embed in the open file. Leave out the URL or file to capture it.");
|
|
2492
|
+
let server;
|
|
2493
|
+
let tab;
|
|
2494
|
+
let page;
|
|
2495
|
+
try {
|
|
2496
|
+
const captured = [];
|
|
2497
|
+
const notes = [];
|
|
2498
|
+
if (source) {
|
|
2499
|
+
server = /^https?:/.test(source) ? void 0 : await serve(source);
|
|
2500
|
+
tab = await running() ? await isolatedTab() : await ephemeralTab();
|
|
2501
|
+
page = tab.page;
|
|
2502
|
+
await page.front();
|
|
2503
|
+
await page.send("Page.enable");
|
|
2504
|
+
await page.send("Page.addScriptToEvaluateOnNewDocument", { source: KEEP_WEBGL_PIXELS });
|
|
2505
|
+
for (const [i, [width, height]] of viewports.entries()) {
|
|
2506
|
+
await page.send("Emulation.setDeviceMetricsOverride", { width, height, deviceScaleFactor: 1, mobile: false });
|
|
2507
|
+
await page.send("Emulation.setEmulatedMedia", {
|
|
2508
|
+
features: [{ name: "prefers-reduced-motion", value: "reduce" }]
|
|
2509
|
+
});
|
|
2510
|
+
await navigate(page, server?.url ?? source);
|
|
2511
|
+
const into = i === 0 ? dir : `${dir}/${width}x${height}`;
|
|
2512
|
+
captured.push(await captureInto(into, page, true, server?.stable ?? ((text) => text), void 0, say));
|
|
2513
|
+
}
|
|
2514
|
+
} else {
|
|
2515
|
+
const make = await makeEmbed(getTarget, embed);
|
|
2516
|
+
page = make.page;
|
|
2517
|
+
captured.push(await captureInto(dir, page, false, (text) => text, make.embed, say));
|
|
2518
|
+
if (make.warning) {
|
|
2519
|
+
notes.push(make.warning);
|
|
2520
|
+
say(`! ${make.warning}`);
|
|
2521
|
+
}
|
|
2522
|
+
}
|
|
2523
|
+
const [first] = captured;
|
|
2524
|
+
return {
|
|
2525
|
+
command: "import capture",
|
|
2526
|
+
ok: true,
|
|
2527
|
+
dir,
|
|
2528
|
+
source: source ?? "Figma Make embed",
|
|
2529
|
+
snapshot: first.snapshot,
|
|
2530
|
+
viewport: first.viewport,
|
|
2531
|
+
tokens: first.tokens,
|
|
2532
|
+
images: first.images,
|
|
2533
|
+
videos: first.videos,
|
|
2534
|
+
skippedImages: first.skippedImages,
|
|
2535
|
+
reference: first.reference,
|
|
2536
|
+
starter: first.starter,
|
|
2537
|
+
...captured.length > 1 && {
|
|
2538
|
+
viewports: captured.map(({ dir: dir2, viewport: viewport2, snapshot, reference, starter: starter2 }) => ({
|
|
2539
|
+
dir: dir2,
|
|
2540
|
+
viewport: viewport2,
|
|
2541
|
+
snapshot,
|
|
2542
|
+
reference,
|
|
2543
|
+
starter: starter2
|
|
2544
|
+
}))
|
|
2545
|
+
},
|
|
2546
|
+
warnings: [
|
|
2547
|
+
...captured.flatMap(
|
|
2548
|
+
(c) => captured.length > 1 ? c.warnings.map((w) => `${c.viewport.join("x")}: ${w}`) : c.warnings
|
|
2549
|
+
),
|
|
2550
|
+
...notes
|
|
2551
|
+
],
|
|
2552
|
+
files: captured.flatMap((c) => c.files)
|
|
2553
|
+
};
|
|
2554
|
+
} finally {
|
|
2555
|
+
if (tab) await tab.close();
|
|
2556
|
+
else page?.close();
|
|
2557
|
+
server?.stop();
|
|
2558
|
+
}
|
|
2559
|
+
}
|
|
2560
|
+
|
|
2561
|
+
// cli/outline.ts
|
|
2562
|
+
var clip = (s, max) => s.length > max ? `${s.slice(0, max)}\u2026` : s;
|
|
2563
|
+
var signature = (el) => el.kind === "frame" ? `${selectorOf(el)}(${el.children.map(signature).join(",")})` : el.kind === "text" ? `text:${selectorOf(el)}` : el.kind === "svg" ? iconKey(el) : selectorOf(el);
|
|
2564
|
+
var iconFragment = (el) => clip(iconKey(el).match(/ d="([^"]*)"/)?.[1] ?? iconKey(el), 28);
|
|
2565
|
+
function detail(el) {
|
|
2566
|
+
if (el.kind === "text")
|
|
2567
|
+
return `"${clip(textOf(el).replace(/\n/g, " "), 48)}" ${el.runs[0].size}px/${el.runs[0].weight}`;
|
|
2568
|
+
if (el.kind === "image") return `image=${el.image}`;
|
|
2569
|
+
if (el.kind === "svg")
|
|
2570
|
+
return isSimpleIcon(el) ? `icon=${JSON.stringify(iconFragment(el))}` : "vector, imported in its own colors";
|
|
2571
|
+
return "";
|
|
2572
|
+
}
|
|
2573
|
+
var descendants = (el) => el.kind === "frame" ? el.children.reduce((n, c) => n + 1 + descendants(c), 0) : 0;
|
|
2574
|
+
function outline(snapshot, maxDepth = Infinity) {
|
|
2575
|
+
const lines = [];
|
|
2576
|
+
const visit = (el, depth) => {
|
|
2577
|
+
const pad = " ".repeat(depth);
|
|
2578
|
+
lines.push(
|
|
2579
|
+
`${pad}${el.kind === "text" && el.tag === "#text" ? "" : `${selectorOf(el)} `}${Math.round(el.box[2])}\xD7${Math.round(el.box[3])} ${detail(el)}`.trimEnd()
|
|
2580
|
+
);
|
|
2581
|
+
if (el.kind !== "frame" || !el.children.length) return;
|
|
2582
|
+
if (depth >= maxDepth) {
|
|
2583
|
+
lines.push(`${pad} \u2026 ${descendants(el)} more inside`);
|
|
2584
|
+
return;
|
|
2585
|
+
}
|
|
2586
|
+
for (let i = 0; i < el.children.length; ) {
|
|
2587
|
+
let same2 = 1;
|
|
2588
|
+
while (i + same2 < el.children.length && signature(el.children[i + same2]) === signature(el.children[i])) same2++;
|
|
2589
|
+
visit(el.children[i], depth + 1);
|
|
2590
|
+
if (same2 > 1) lines.push(`${pad} \xD7 ${same2 - 1} more like it`);
|
|
2591
|
+
i += same2;
|
|
2592
|
+
}
|
|
2593
|
+
};
|
|
2594
|
+
visit(snapshot.root, 0);
|
|
2595
|
+
const tokens = Object.entries(snapshot.tokens).map(([name, value]) => ` --${name}: ${value}`);
|
|
2596
|
+
const icons = /* @__PURE__ */ new Map();
|
|
2597
|
+
walk(snapshot.root, (el) => {
|
|
2598
|
+
if (el.kind !== "svg" || !isSimpleIcon(el)) return;
|
|
2599
|
+
const seen = icons.get(iconKey(el)) ?? { fragment: iconFragment(el), count: 0 };
|
|
2600
|
+
seen.count++;
|
|
2601
|
+
icons.set(iconKey(el), seen);
|
|
2602
|
+
});
|
|
2603
|
+
return [
|
|
2604
|
+
`${snapshot.url} ${snapshot.viewport.join("\xD7")}`,
|
|
2605
|
+
"",
|
|
2606
|
+
...lines,
|
|
2607
|
+
"",
|
|
2608
|
+
`tokens (${tokens.length})`,
|
|
2609
|
+
...tokens,
|
|
2610
|
+
...icons.size ? [
|
|
2611
|
+
"",
|
|
2612
|
+
`icons (${icons.size})`,
|
|
2613
|
+
...[...icons.values()].map(({ fragment, count }) => ` icon=${JSON.stringify(fragment)} \xD7 ${count}`)
|
|
2614
|
+
] : []
|
|
2615
|
+
].join("\n");
|
|
2616
|
+
}
|
|
2617
|
+
|
|
2618
|
+
// cli/parity.ts
|
|
2619
|
+
import { existsSync as existsSync6, mkdirSync as mkdirSync4, readFileSync as readFileSync5, rmSync as rmSync5, writeFileSync as writeFileSync3 } from "node:fs";
|
|
2620
|
+
import { PNG as PNG2 } from "pngjs";
|
|
2621
|
+
var FUZZ = 0.1 * 255;
|
|
2622
|
+
var HIGHLIGHT = [241, 0, 30];
|
|
2623
|
+
var LOWLIGHT = [255, 255, 255];
|
|
2624
|
+
function region(png, [x, y, w, h], [canvasW, canvasH], under = LOWLIGHT) {
|
|
2625
|
+
const out = new PNG2({ width: canvasW, height: canvasH });
|
|
2626
|
+
out.data.fill(255);
|
|
2627
|
+
const maxJ = Math.min(h, canvasH, png.height - y);
|
|
2628
|
+
const maxI = Math.min(w, canvasW, png.width - x);
|
|
2629
|
+
for (let j = Math.max(0, -y); j < maxJ; j++) {
|
|
2630
|
+
for (let i = Math.max(0, -x); i < maxI; i++) {
|
|
2631
|
+
const [p, o] = [4 * ((y + j) * png.width + x + i), 4 * (j * canvasW + i)];
|
|
2632
|
+
const alpha = png.data[p + 3] / 255;
|
|
2633
|
+
for (let c = 0; c < 3; c++) out.data[o + c] = Math.round(alpha * png.data[p + c] + (1 - alpha) * under[c]);
|
|
2634
|
+
}
|
|
2635
|
+
}
|
|
2636
|
+
return out;
|
|
2637
|
+
}
|
|
2638
|
+
function compareSection(page, [x, y, w, h], rebuilt, bg) {
|
|
2639
|
+
const c = bg ? parseColor(bg) : void 0;
|
|
2640
|
+
const under = c ? [c.r, c.g, c.b].map((v) => Math.round(v * 255)) : LOWLIGHT;
|
|
2641
|
+
const [cw, ch] = [Math.max(w, rebuilt.width), Math.max(h, rebuilt.height)];
|
|
2642
|
+
if (cw === 0 || ch === 0) {
|
|
2643
|
+
return {
|
|
2644
|
+
sheet: PNG2.sync.write(new PNG2({ width: 1, height: 1 })),
|
|
2645
|
+
mismatch: 0,
|
|
2646
|
+
compared: [cw, ch]
|
|
2647
|
+
};
|
|
2648
|
+
}
|
|
2649
|
+
const [a, b] = [
|
|
2650
|
+
region(page, [x, y, w, h], [cw, ch]),
|
|
2651
|
+
region(rebuilt, [0, 0, rebuilt.width, rebuilt.height], [cw, ch], under)
|
|
2652
|
+
];
|
|
2653
|
+
const diff = new PNG2({ width: cw, height: ch });
|
|
2654
|
+
let differing = 0;
|
|
2655
|
+
for (let o = 0; o < a.data.length; o += 4) {
|
|
2656
|
+
const [i, j] = [o / 4 % cw, Math.floor(o / 4 / cw)];
|
|
2657
|
+
const outside = i >= w || j >= h || i >= rebuilt.width || j >= rebuilt.height;
|
|
2658
|
+
const differs = outside || [0, 1, 2].some((c2) => Math.abs(a.data[o + c2] - b.data[o + c2]) > FUZZ);
|
|
2659
|
+
if (differs) differing++;
|
|
2660
|
+
const tint = differs ? HIGHLIGHT : LOWLIGHT;
|
|
2661
|
+
for (let c2 = 0; c2 < 3; c2++) diff.data[o + c2] = Math.round(0.2 * a.data[o + c2] + 0.8 * tint[c2]);
|
|
2662
|
+
diff.data[o + 3] = 255;
|
|
2663
|
+
}
|
|
2664
|
+
const sheet = new PNG2({ width: 3 * cw, height: ch });
|
|
2665
|
+
for (const [k, img] of [a, b, diff].entries()) PNG2.bitblt(img, sheet, 0, 0, cw, ch, k * cw, 0);
|
|
2666
|
+
return {
|
|
2667
|
+
sheet: PNG2.sync.write(sheet),
|
|
2668
|
+
mismatch: differing / (cw * ch),
|
|
2669
|
+
compared: [cw, ch]
|
|
2670
|
+
};
|
|
2671
|
+
}
|
|
2672
|
+
function readPng(path) {
|
|
2673
|
+
if (!existsSync6(path)) throw new Problem(`No reference image at ${path}.`);
|
|
2674
|
+
try {
|
|
2675
|
+
return PNG2.sync.read(readFileSync5(path));
|
|
2676
|
+
} catch (e) {
|
|
2677
|
+
throw new Problem(`${path} is not a PNG: ${messageOf(e)}`);
|
|
2678
|
+
}
|
|
2679
|
+
}
|
|
2680
|
+
function compareInto(out, source, found, maxMismatch, say) {
|
|
2681
|
+
rmSync5(out, { recursive: true, force: true });
|
|
2682
|
+
mkdirSync4(out, { recursive: true });
|
|
2683
|
+
const sections = found.map((section, i) => {
|
|
2684
|
+
const box = section.box.map(Math.round);
|
|
2685
|
+
const rebuilt = PNG2.sync.read(Buffer.from(section.png, "base64"));
|
|
2686
|
+
const { sheet, mismatch, compared } = compareSection(source, box, rebuilt, section.bg);
|
|
2687
|
+
const path = `${out}/${i + 1}-${slug(section.name.replace(/^Section\//, "")) || "node"}.png`;
|
|
2688
|
+
writeFileSync3(path, sheet);
|
|
2689
|
+
return {
|
|
2690
|
+
name: section.name,
|
|
2691
|
+
id: section.id,
|
|
2692
|
+
source: [box[2], box[3]],
|
|
2693
|
+
rebuilt: [rebuilt.width, rebuilt.height],
|
|
2694
|
+
compared,
|
|
2695
|
+
mismatch,
|
|
2696
|
+
file: path
|
|
2697
|
+
};
|
|
2698
|
+
});
|
|
2699
|
+
for (const p of sections)
|
|
2700
|
+
say(
|
|
2701
|
+
`${p.name} source ${p.source.join("\xD7")}, rebuilt ${p.rebuilt.join("\xD7")}, ${(100 * p.mismatch).toFixed(2)}% differs ${p.file}`
|
|
2702
|
+
);
|
|
2703
|
+
say(
|
|
2704
|
+
"Each file shows source | rebuilt | diff over the larger of the two sizes. Read the images: a low percentage can still hide a shifted block."
|
|
2705
|
+
);
|
|
2706
|
+
const warnings = sections.flatMap(
|
|
2707
|
+
(p) => p.source[0] === p.rebuilt[0] && p.source[1] === p.rebuilt[1] ? [] : [
|
|
2708
|
+
`${p.name} (${p.id}) is ${p.rebuilt.join("\xD7")} in Figma but ${p.source.join("\xD7")} in the reference, so the area only one covers counts as differing.`
|
|
2709
|
+
]
|
|
2710
|
+
);
|
|
2711
|
+
const over = maxMismatch === void 0 ? [] : sections.filter((p) => 100 * p.mismatch > maxMismatch);
|
|
2712
|
+
if (over.length)
|
|
2713
|
+
warnings.push(
|
|
2714
|
+
`${over.length} of ${sections.length} sections differ by more than --max-mismatch ${maxMismatch}%: ${over.map((p) => `${p.name} ${(100 * p.mismatch).toFixed(2)}%`).join(", ")}.`
|
|
2715
|
+
);
|
|
2716
|
+
for (const w of warnings) say(`! ${w}`);
|
|
2717
|
+
return { sections, warnings, ok: !over.length };
|
|
2718
|
+
}
|
|
2719
|
+
async function runParity(dir, build, loadSections, maxMismatch, say) {
|
|
2720
|
+
const reference = `${dir}/ref/page.png`;
|
|
2721
|
+
if (!existsSync6(reference))
|
|
2722
|
+
throw new Problem(
|
|
2723
|
+
`No ${reference}. \`figdriver import capture\` saves one from a URL or file. For a Figma Make embed, export the CODE_INSTANCE node with \`figdriver export ${reference} <id>\`.`
|
|
2724
|
+
);
|
|
2725
|
+
const [file, page, found] = await loadSections(build.nodes);
|
|
2726
|
+
if (!found.length)
|
|
2727
|
+
throw new Problem(
|
|
2728
|
+
`The build of "${build.name}" on page "${build.page.name}" holds no sections. Build it again: figdriver import run ${dir} --file ${file.key}`
|
|
2729
|
+
);
|
|
2730
|
+
say(
|
|
2731
|
+
`Comparing the build of ${build.name} that the last run left on page "${build.page.name}"${build.owner === build.name ? "" : ", its draft"}.`
|
|
2732
|
+
);
|
|
2733
|
+
const { sections, warnings, ok } = compareInto(`${dir}/out/parity`, readPng(reference), found, maxMismatch, say);
|
|
2734
|
+
return {
|
|
2735
|
+
command: "import parity",
|
|
2736
|
+
ok,
|
|
2737
|
+
design: build.name,
|
|
2738
|
+
build,
|
|
2739
|
+
node: null,
|
|
2740
|
+
reference,
|
|
2741
|
+
maxMismatch: maxMismatch ?? null,
|
|
2742
|
+
file,
|
|
2743
|
+
page,
|
|
2744
|
+
sections,
|
|
2745
|
+
warnings,
|
|
2746
|
+
files: sections.map((p) => p.file)
|
|
2747
|
+
};
|
|
2748
|
+
}
|
|
2749
|
+
async function runNodeParity(node, reference, out, maxMismatch, loadNode, say) {
|
|
2750
|
+
const source = readPng(reference);
|
|
2751
|
+
const [file, page, shot] = await loadNode();
|
|
2752
|
+
say(`Comparing "${shot.name}" (${shot.id}) with ${reference}.`);
|
|
2753
|
+
const { sections, warnings, ok } = compareInto(
|
|
2754
|
+
out,
|
|
2755
|
+
source,
|
|
2756
|
+
[{ name: shot.name, id: shot.id, box: [0, 0, source.width, source.height], png: shot.data }],
|
|
2757
|
+
maxMismatch,
|
|
2758
|
+
say
|
|
2759
|
+
);
|
|
2760
|
+
return {
|
|
2761
|
+
command: "parity",
|
|
2762
|
+
ok,
|
|
2763
|
+
design: null,
|
|
2764
|
+
build: null,
|
|
2765
|
+
node,
|
|
2766
|
+
reference,
|
|
2767
|
+
maxMismatch: maxMismatch ?? null,
|
|
2768
|
+
file,
|
|
2769
|
+
page,
|
|
2770
|
+
sections,
|
|
2771
|
+
warnings,
|
|
2772
|
+
files: sections.map((p) => p.file)
|
|
2773
|
+
};
|
|
2774
|
+
}
|
|
2775
|
+
|
|
2776
|
+
// cli/commands/import.ts
|
|
2777
|
+
var DEFAULT_RUN_TIMEOUT = 900;
|
|
2778
|
+
var START = `(() => {
|
|
2779
|
+
const slot = globalThis.figdriverImport;
|
|
2780
|
+
delete globalThis.figdriverImport;
|
|
2781
|
+
const calls = slot ? slot.calls.length : 0;
|
|
2782
|
+
if (calls !== 1) throw new Error(calls ? "index.ts calls importDesign " + calls + " times, so nothing was built. Call it once, at the top level of index.ts." : "index.ts never called importDesign, so nothing was built. Call it once, at the top level of index.ts.");
|
|
2783
|
+
return slot.calls[0]();
|
|
2784
|
+
})()`;
|
|
2785
|
+
function folderOf(dir) {
|
|
2786
|
+
if (!dir) throw new Problem("Name the design's folder, such as ./landing");
|
|
2787
|
+
return dir;
|
|
2788
|
+
}
|
|
2789
|
+
function builtDesign(dir) {
|
|
2790
|
+
const manifest = `${dir}/out/design.json`;
|
|
2791
|
+
if (!existsSync7(manifest))
|
|
2792
|
+
throw new Problem(
|
|
2793
|
+
`No ${manifest}, which names the design. Run it first: figdriver import run ${dir} --file <Figma URL or key>`
|
|
2794
|
+
);
|
|
2795
|
+
return JSON.parse(readFileSync6(manifest, "utf8"));
|
|
2796
|
+
}
|
|
2797
|
+
var explain = (message) => /padding\w* .*expected number to be >= ?0/i.test(message) ? `${message}
|
|
2798
|
+
A negative margin in the source page became negative padding. Replace it with padding or absolute positioning, then capture again.` : message;
|
|
2799
|
+
function runImportCapture(dir, source, flags, say) {
|
|
2800
|
+
return runCapture(
|
|
2801
|
+
folderOf(dir),
|
|
2802
|
+
source,
|
|
2803
|
+
flags.viewport ?? "1440x900",
|
|
2804
|
+
flags.embed === void 0 ? void 0 : parseNodeId(flags.embed),
|
|
2805
|
+
() => target(flags, "import capture", false),
|
|
2806
|
+
say
|
|
2807
|
+
);
|
|
2808
|
+
}
|
|
2809
|
+
function runImportOutline(dir, flags) {
|
|
2810
|
+
const file = `${folderOf(dir)}/snapshot.json`;
|
|
2811
|
+
if (!existsSync7(file)) throw new Problem(`No ${file}. Capture the page first: figdriver import capture ${dir} <url>`);
|
|
2812
|
+
const snapshot = JSON.parse(readFileSync6(file, "utf8"));
|
|
2813
|
+
console.log(outline(snapshot, flags.depth ? Number(flags.depth) : void 0));
|
|
2814
|
+
}
|
|
2815
|
+
async function runImportPlugin(typed) {
|
|
2816
|
+
const { dir, files } = await buildDesign(folderOf(typed));
|
|
2817
|
+
return { command: "import plugin", ok: true, dir, warnings: [], files };
|
|
2818
|
+
}
|
|
2819
|
+
async function runDesign(typed, flags, say) {
|
|
2820
|
+
const dir = folderOf(typed);
|
|
2821
|
+
const tab = await target(flags, "import run", true);
|
|
2822
|
+
const { out, files } = await buildDesign(dir);
|
|
2823
|
+
const pageSource = pageSourceOf(flags.page);
|
|
2824
|
+
const warnings = [];
|
|
2825
|
+
const prepare = async (s, status) => {
|
|
2826
|
+
const where = status.missing === null ? `page "${status.page.name}"` : `page "${status.missing}", which the run makes from its build page`;
|
|
2827
|
+
say(`Building ${dir} in "${status.file}" (${fileKeyOf(s.target.url)}), ${where} (${pageSourceLabel(flags.page)})`);
|
|
2828
|
+
if (status.users?.length)
|
|
2829
|
+
warnings.push(`${usersAre(status.users)} in this file. Edits made during the run can collide with it.`);
|
|
2830
|
+
for (const warning of warnings) say(`! ${warning}`);
|
|
2831
|
+
await s.evaluate(
|
|
2832
|
+
`globalThis.figdriverImport = ${JSON.stringify({ force: flags.force === true, page: status.missing ?? void 0, calls: [] })}`
|
|
2833
|
+
);
|
|
2834
|
+
await s.evaluate(readFileSync6(out, "utf8"));
|
|
2835
|
+
};
|
|
2836
|
+
return withWrite(
|
|
2837
|
+
flags,
|
|
2838
|
+
"import run",
|
|
2839
|
+
Number(flags.timeout ?? DEFAULT_RUN_TIMEOUT),
|
|
2840
|
+
{ tab, page: flags.page, creates: true, console: true, prepare },
|
|
2841
|
+
START,
|
|
2842
|
+
async (s, file, _page, imported) => {
|
|
2843
|
+
const {
|
|
2844
|
+
design: name,
|
|
2845
|
+
owner,
|
|
2846
|
+
outcome,
|
|
2847
|
+
committed,
|
|
2848
|
+
draft,
|
|
2849
|
+
message,
|
|
2850
|
+
audit: checked,
|
|
2851
|
+
page,
|
|
2852
|
+
output,
|
|
2853
|
+
...built
|
|
2854
|
+
} = imported;
|
|
2855
|
+
const at = draft ?? (page.id === null ? null : { name: page.name, id: page.id });
|
|
2856
|
+
if (output.length && at) {
|
|
2857
|
+
const manifest = `${dir}/out/design.json`;
|
|
2858
|
+
write(
|
|
2859
|
+
manifest,
|
|
2860
|
+
`${JSON.stringify({ name, file: file.key, page: at, owner, nodes: output })}
|
|
2861
|
+
`
|
|
2862
|
+
);
|
|
2863
|
+
files.push(manifest);
|
|
2864
|
+
}
|
|
2865
|
+
say(JSON.stringify(built));
|
|
2866
|
+
if (built.fallbacks) {
|
|
2867
|
+
say(
|
|
2868
|
+
` \u2717 ${built.fallbacks} fallbacks in ${built.fallbackRules.join(", ")}: these elements match a component rule but are built differently from its main, so they became plain frames. Give them their own variant, or narrow the rule's match.`
|
|
2869
|
+
);
|
|
2870
|
+
}
|
|
2871
|
+
for (const reason2 of built.fallbackReasons) say(` ${reason2}`);
|
|
2872
|
+
for (const unknown of built.unknownTextProperties) say(` \u2717 text placeholder: ${unknown}`);
|
|
2873
|
+
for (const warning of built.warnings) say(` ! ${warning}`);
|
|
2874
|
+
const audit = auditReport(checked, null);
|
|
2875
|
+
reportAudit(audit, say);
|
|
2876
|
+
say(draft ? `screens of the draft on page "${draft.name}":` : "screens:");
|
|
2877
|
+
const screens = !output.length ? [] : await exportScreens(s, `${dir}/out/screens`, owner, {}, true, say).catch((e) => {
|
|
2878
|
+
warnings.push(
|
|
2879
|
+
`The screens could not be exported: ${e.message}. The file holds the build as this result says. Retry with figdriver export ${dir}/out/screens --screens --file ${file.key}`
|
|
2880
|
+
);
|
|
2881
|
+
return null;
|
|
2882
|
+
});
|
|
2883
|
+
const reason = message === void 0 ? null : explain(message);
|
|
2884
|
+
if (reason) say(`\u2717 ${reason}`);
|
|
2885
|
+
if (!screens) say(`\u2717 ${warnings[warnings.length - 1]}`);
|
|
2886
|
+
return {
|
|
2887
|
+
command: "import run",
|
|
2888
|
+
ok: outcome === "replace" && !!screens,
|
|
2889
|
+
design: name,
|
|
2890
|
+
file,
|
|
2891
|
+
page,
|
|
2892
|
+
pageSource,
|
|
2893
|
+
outcome,
|
|
2894
|
+
committed,
|
|
2895
|
+
draft,
|
|
2896
|
+
reason,
|
|
2897
|
+
output,
|
|
2898
|
+
built,
|
|
2899
|
+
audit,
|
|
2900
|
+
screens: screens ?? [],
|
|
2901
|
+
warnings: [...warnings, ...built.warnings],
|
|
2902
|
+
files: [...files, ...(screens ?? []).map((x) => x.file)]
|
|
2903
|
+
};
|
|
2904
|
+
}
|
|
2905
|
+
).catch((e) => {
|
|
2906
|
+
throw e instanceof Problem ? new Problem(explain(e.message)) : e;
|
|
2907
|
+
});
|
|
2908
|
+
}
|
|
2909
|
+
async function runImportAudit(dir, flags, say) {
|
|
2910
|
+
const ruleset = flags.ruleset === "authored" ? "authored" : "run";
|
|
2911
|
+
const build = dir === void 0 ? null : builtDesign(folderOf(dir));
|
|
2912
|
+
const owner = build?.owner ?? null;
|
|
2913
|
+
const [file, page, raw] = await withFigma(
|
|
2914
|
+
flags,
|
|
2915
|
+
"import audit",
|
|
2916
|
+
async (s, file2, page2) => [file2, page2, await inspect(s, "audit", owner, ruleset)]
|
|
2917
|
+
);
|
|
2918
|
+
const audit = auditReport(raw, owner);
|
|
2919
|
+
reportAudit(audit, say);
|
|
2920
|
+
return {
|
|
2921
|
+
command: "import audit",
|
|
2922
|
+
ok: audit.clean,
|
|
2923
|
+
design: build?.name ?? null,
|
|
2924
|
+
ruleset,
|
|
2925
|
+
file,
|
|
2926
|
+
page,
|
|
2927
|
+
audit,
|
|
2928
|
+
warnings: [],
|
|
2929
|
+
files: []
|
|
2930
|
+
};
|
|
2931
|
+
}
|
|
2932
|
+
async function runImportParityCommand(typed, flags, say) {
|
|
2933
|
+
const max = maxMismatchOf(flags);
|
|
2934
|
+
const dir = folderOf(typed);
|
|
2935
|
+
const build = builtDesign(dir);
|
|
2936
|
+
return runParity(
|
|
2937
|
+
dir,
|
|
2938
|
+
build,
|
|
2939
|
+
(nodes) => withFigma(flags, "import parity", async (s, file, page) => {
|
|
2940
|
+
if (file.key !== build.file) {
|
|
2941
|
+
throw new Problem(
|
|
2942
|
+
`${dir}/out/design.json records a build in the Figma file ${build.file}, but the open file is ${file.name} (${file.key}). Name that file with --file, or run \`figdriver import run ${dir}\` here first.`
|
|
2943
|
+
);
|
|
2944
|
+
}
|
|
2945
|
+
return [file, page, await inspect(s, "sections", nodes)];
|
|
2946
|
+
}),
|
|
2947
|
+
max,
|
|
2948
|
+
say
|
|
2949
|
+
);
|
|
2950
|
+
}
|
|
2951
|
+
|
|
2952
|
+
// cli/commands/read.ts
|
|
2953
|
+
var INSPECT_OVERFLOW_CHARS = 16e3;
|
|
2954
|
+
var INCLUDES = ["prototype", "handoff", "variables", "text-runs", "grids", "vectors", "all"];
|
|
2955
|
+
function includesOf(typed) {
|
|
2956
|
+
const parts = typed.split(",").map((x) => x.trim());
|
|
2957
|
+
const bad = parts.filter((x) => !INCLUDES.some((i) => i === x));
|
|
2958
|
+
if (bad.length)
|
|
2959
|
+
throw new Problem(
|
|
2960
|
+
`--include takes a comma-separated list of ${INCLUDES.join(", ")}, not ${bad.map((x) => `"${x}"`).join(", ")}.`
|
|
2961
|
+
);
|
|
2962
|
+
return INCLUDES.filter((i) => parts.includes(i));
|
|
2963
|
+
}
|
|
2964
|
+
function summarizeOverflow(layers, size2, pageName, nodeId) {
|
|
2965
|
+
const kb = (size2 / 1024).toFixed(1);
|
|
2966
|
+
const top = layers.slice(0, 12).map((l) => ` ${l.id} ${l.type} ${l.name}`);
|
|
2967
|
+
const more = layers.length > 12 ? [` \u2026 and ${layers.length - 12} more top-level nodes`] : [];
|
|
2968
|
+
const narrow = nodeId ? `figdriver find --under ${nodeId} --type TEXT,INSTANCE` : pageName ? `figdriver find --page ${JSON.stringify(pageName)} --type TEXT,INSTANCE` : `figdriver find --type TEXT,INSTANCE`;
|
|
2969
|
+
return [
|
|
2970
|
+
`inspect output is ${kb} KB (over 16 KB limit for terminal display). Top-level layers:`,
|
|
2971
|
+
...top,
|
|
2972
|
+
...more,
|
|
2973
|
+
`Narrow targets with \`${narrow}\`, lower \`--depth 1\`, or pass \`--json\` for the full tree.`
|
|
2974
|
+
].join("\n");
|
|
2975
|
+
}
|
|
2976
|
+
async function runInspect(flags) {
|
|
2977
|
+
const targets2 = chosen(!!flags.node?.length, !!flags.selection, flags.page !== void 0);
|
|
2978
|
+
const layered = targets2 > 0;
|
|
2979
|
+
if ((flags.depth !== void 0 || flags.include !== void 0 || flags["expand-instances"]) && !layered)
|
|
2980
|
+
throw new Problem(
|
|
2981
|
+
"--depth, --include, and --expand-instances describe layers. Pass them with --node, --page, or --selection."
|
|
2982
|
+
);
|
|
2983
|
+
if (targets2 > 1) throw new Problem("Pass at most one of --node, --page, or --selection.");
|
|
2984
|
+
const nodeIds = flags.node?.map(parseNodeId) ?? [];
|
|
2985
|
+
const depth = Number(flags.depth ?? 3);
|
|
2986
|
+
const options = {
|
|
2987
|
+
include: flags.include === void 0 ? void 0 : includesOf(flags.include),
|
|
2988
|
+
expandInstances: flags["expand-instances"] || void 0
|
|
2989
|
+
};
|
|
2990
|
+
const [file, page, result] = await withFigma(flags, "inspect", async (s, file2, current) => {
|
|
2991
|
+
if (flags.page !== void 0) {
|
|
2992
|
+
const resolved = await inspect(s, "pageLayers", flags.page, depth, options);
|
|
2993
|
+
return [file2, resolved.page, resolved.layers];
|
|
2994
|
+
}
|
|
2995
|
+
return [
|
|
2996
|
+
file2,
|
|
2997
|
+
current,
|
|
2998
|
+
nodeIds.length || flags.selection ? await inspect(s, "layers", nodeIds, !!flags.selection, depth, options) : await inspect(s, "inventory")
|
|
2999
|
+
];
|
|
3000
|
+
});
|
|
3001
|
+
if (!flags.json) {
|
|
3002
|
+
const text = JSON.stringify(result, null, 1);
|
|
3003
|
+
if (layered && Array.isArray(result) && text.length > INSPECT_OVERFLOW_CHARS) {
|
|
3004
|
+
const roots = flags.page !== void 0 && result.length === 1 && result[0].children ? result[0].children : result;
|
|
3005
|
+
return console.log(
|
|
3006
|
+
summarizeOverflow(roots, text.length, flags.page !== void 0 ? page.name : void 0, nodeIds[0])
|
|
3007
|
+
);
|
|
3008
|
+
}
|
|
3009
|
+
return console.log(text);
|
|
3010
|
+
}
|
|
3011
|
+
return { command: "inspect", ok: true, file, page, result, warnings: [], files: [] };
|
|
3012
|
+
}
|
|
3013
|
+
async function runFind(flags, say) {
|
|
3014
|
+
if ([flags.name, flags.type, flags.text, flags.component].every((x) => x === void 0))
|
|
3015
|
+
throw new Problem("Pass at least one of --name, --type, --text, or --component to find layers by.");
|
|
3016
|
+
if (chosen(flags.under !== void 0, flags.page !== void 0, !!flags["all-pages"]) > 1)
|
|
3017
|
+
throw new Problem("Pass at most one scope: --page, --all-pages, or --under.");
|
|
3018
|
+
const query = {
|
|
3019
|
+
page: flags["all-pages"] ? "all" : flags.page,
|
|
3020
|
+
node: flags.under === void 0 ? void 0 : parseNodeId(flags.under),
|
|
3021
|
+
name: flags.name,
|
|
3022
|
+
type: flags.type,
|
|
3023
|
+
text: flags.text,
|
|
3024
|
+
component: flags.component,
|
|
3025
|
+
limit: flags.limit === void 0 ? void 0 : Number(flags.limit)
|
|
3026
|
+
};
|
|
3027
|
+
const [file, page, found] = await withFigma(
|
|
3028
|
+
flags,
|
|
3029
|
+
"find",
|
|
3030
|
+
async (s, file2, page2) => [file2, page2, await inspect(s, "find", query)]
|
|
3031
|
+
);
|
|
3032
|
+
for (const m of found.matches) {
|
|
3033
|
+
const where = query.page === "all" ? `${m.page} / ` : "";
|
|
3034
|
+
const main2 = m.main ? ` \u27F6 ${m.main}` : "";
|
|
3035
|
+
const props = m.properties ? ` ${JSON.stringify(m.properties)}` : "";
|
|
3036
|
+
const text = m.text === void 0 ? "" : ` ${JSON.stringify(m.text.length > 60 ? `${m.text.slice(0, 60)}\u2026` : m.text)}`;
|
|
3037
|
+
say(`${m.id} ${m.type} ${where}${m.path}${main2}${props}${text}`);
|
|
3038
|
+
}
|
|
3039
|
+
say(
|
|
3040
|
+
found.truncated ? `${found.matches.length} of ${found.total} matches. Raise --limit or narrow the filters to see the rest.` : `${found.total} match${found.total === 1 ? "" : "es"}`
|
|
3041
|
+
);
|
|
3042
|
+
return { command: "find", ok: true, file, page, query, ...found, warnings: [], files: [] };
|
|
3043
|
+
}
|
|
3044
|
+
async function runTree(flags) {
|
|
3045
|
+
await withFigma(flags, "tree", async (s) => console.log(JSON.stringify(await inspect(s, "tree"), null, 1)));
|
|
3046
|
+
}
|
|
3047
|
+
|
|
3048
|
+
// cli/commands/tokens.ts
|
|
3049
|
+
import { existsSync as existsSync8, readFileSync as readFileSync7 } from "node:fs";
|
|
3050
|
+
|
|
3051
|
+
// src/core/tokens.ts
|
|
3052
|
+
var cssSlug = (name) => name.toLowerCase().replace(/[^a-z0-9_-]+/g, "-").replace(/^-+|-+$/g, "");
|
|
3053
|
+
var CSS_NAME = /^(?:var\(\s*(--[\w-]+)\s*\)|(--[\w-]+))$/;
|
|
3054
|
+
function cssProperty(name, web) {
|
|
3055
|
+
const named = web?.trim().match(CSS_NAME);
|
|
3056
|
+
return named ? named[1] ?? named[2] : `--${cssSlug(name)}`;
|
|
3057
|
+
}
|
|
3058
|
+
var modeKey = (name) => name.toLowerCase().replace(/[^a-z0-9]+/g, "");
|
|
3059
|
+
function matchVariable(planned, existing) {
|
|
3060
|
+
const byName = existing.find((v) => v.name === planned.name);
|
|
3061
|
+
if (byName || planned.codeSyntaxWeb === void 0) return byName;
|
|
3062
|
+
const property = cssProperty(planned.name, planned.codeSyntaxWeb);
|
|
3063
|
+
return existing.find((v) => cssProperty(v.name, v.web) === property);
|
|
3064
|
+
}
|
|
3065
|
+
function upsertsOf(plan, own) {
|
|
3066
|
+
const upserts = [];
|
|
3067
|
+
const warnings = [];
|
|
3068
|
+
for (const planned of plan.variables) {
|
|
3069
|
+
const match = matchVariable(planned, own);
|
|
3070
|
+
if (match && match.type !== planned.type)
|
|
3071
|
+
warnings.push(`${planned.name} is left out: ${plan.collection}/${match.name} is a ${match.type} variable.`);
|
|
3072
|
+
else upserts.push({ planned, match });
|
|
3073
|
+
}
|
|
3074
|
+
return { upserts, warnings };
|
|
3075
|
+
}
|
|
3076
|
+
function aliasTarget(alias, type, upserted, local) {
|
|
3077
|
+
const own = upserted.get(alias);
|
|
3078
|
+
return own?.type === type ? own : local.find((v) => v.name === alias && v.type === type);
|
|
3079
|
+
}
|
|
3080
|
+
var unboundAlias = (name, mode, alias) => `${name} keeps its ${mode} value: it aliases ${alias}, which neither the tokens file nor this Figma file holds.`;
|
|
3081
|
+
|
|
3082
|
+
// cli/tokens.ts
|
|
3083
|
+
var UNITLESS = /* @__PURE__ */ new Set(["FONT_WEIGHT", "OPACITY"]);
|
|
3084
|
+
var unitless = (v) => !!v.scopes?.length && v.scopes.every((s) => UNITLESS.has(s));
|
|
3085
|
+
var exportable = (v) => v.type === "COLOR" || v.type === "FLOAT";
|
|
3086
|
+
function pick(collections, wanted) {
|
|
3087
|
+
if (wanted === void 0) return collections;
|
|
3088
|
+
const found = collections.filter((c) => c.name === wanted || c.id === wanted);
|
|
3089
|
+
if (!found.length)
|
|
3090
|
+
throw new Problem(
|
|
3091
|
+
`The file has no variable collection named "${wanted}" or with that id. Its collections: ${collections.map((c) => `"${c.name}" (${c.id})`).join(", ") || "none"}.`
|
|
3092
|
+
);
|
|
3093
|
+
return found;
|
|
3094
|
+
}
|
|
3095
|
+
function resolver(collections) {
|
|
3096
|
+
const byId = new Map(collections.flatMap((c) => c.variables.map((v) => [v.id, { v, collection: c }])));
|
|
3097
|
+
const all = [...byId.values()];
|
|
3098
|
+
const valueIn = (e, mode) => e.v.values[mode] ?? e.v.values[e.collection.modes[0]];
|
|
3099
|
+
const targetOf = (alias, from) => {
|
|
3100
|
+
if (alias.id !== void 0) return byId.get(alias.id);
|
|
3101
|
+
const named = all.filter((e) => e.v.name === alias.alias && e.v.type === from.v.type);
|
|
3102
|
+
return named.find((e) => e.collection === from.collection) ?? named[0];
|
|
3103
|
+
};
|
|
3104
|
+
function resolve7(e, mode, ref, literal, seen = /* @__PURE__ */ new Set()) {
|
|
3105
|
+
const value = valueIn(e, mode);
|
|
3106
|
+
if (!(value instanceof Object)) return value === void 0 ? void 0 : literal(e.v, value);
|
|
3107
|
+
const target2 = targetOf(value, e);
|
|
3108
|
+
if (!target2 || target2.v.type !== e.v.type || seen.has(target2.v.id)) return;
|
|
3109
|
+
return ref(target2) ?? resolve7(
|
|
3110
|
+
target2,
|
|
3111
|
+
target2.collection === e.collection ? mode : target2.collection.modes[0],
|
|
3112
|
+
ref,
|
|
3113
|
+
literal,
|
|
3114
|
+
seen.add(e.v.id)
|
|
3115
|
+
);
|
|
3116
|
+
}
|
|
3117
|
+
function why(e, mode) {
|
|
3118
|
+
const value = valueIn(e, mode);
|
|
3119
|
+
if (!(value instanceof Object)) return "it has no value in this mode";
|
|
3120
|
+
const target2 = targetOf(value, e);
|
|
3121
|
+
if (!target2) return `it aliases ${value.alias}, which this file does not hold, such as a library's variable`;
|
|
3122
|
+
return target2.v.type === e.v.type ? `its alias ${value.alias} never ends at a value this file holds` : `it aliases ${value.alias}, a ${target2.v.type} variable`;
|
|
3123
|
+
}
|
|
3124
|
+
return { byId, resolve: resolve7, why };
|
|
3125
|
+
}
|
|
3126
|
+
var SCOPE_NAMESPACES = /* @__PURE__ */ new Map([
|
|
3127
|
+
["CORNER_RADIUS", "radius"],
|
|
3128
|
+
["GAP", "spacing"],
|
|
3129
|
+
["WIDTH_HEIGHT", "spacing"],
|
|
3130
|
+
["FONT_SIZE", "text"],
|
|
3131
|
+
["FONT_WEIGHT", "font-weight"],
|
|
3132
|
+
["LINE_HEIGHT", "leading"],
|
|
3133
|
+
["LETTER_SPACING", "tracking"]
|
|
3134
|
+
]);
|
|
3135
|
+
function tailwindProperty(v, property) {
|
|
3136
|
+
const spaces = new Set(v.scopes?.map((s) => SCOPE_NAMESPACES.get(s)));
|
|
3137
|
+
const [only] = spaces;
|
|
3138
|
+
const namespace = v.type === "COLOR" ? "color" : spaces.size === 1 ? only : void 0;
|
|
3139
|
+
return !namespace || property.startsWith(`--${namespace}-`) ? property : `--${namespace}-${property.slice(2)}`;
|
|
3140
|
+
}
|
|
3141
|
+
var selectorOf2 = (mode, root = ":root") => mode === null ? root : `[data-theme="${mode}"]`;
|
|
3142
|
+
function declarations(collections, options, tailwind) {
|
|
3143
|
+
const selected = pick(collections, options.collection);
|
|
3144
|
+
const { byId, resolve: resolve7, why } = resolver(collections);
|
|
3145
|
+
const property = (v) => tailwind ? tailwindProperty(v, cssProperty(v.name, v.codeSyntax?.WEB)) : cssProperty(v.name, v.codeSyntax?.WEB);
|
|
3146
|
+
const owners = /* @__PURE__ */ new Map();
|
|
3147
|
+
const warnings = [];
|
|
3148
|
+
const keyOf2 = (c, i) => i === 0 ? null : cssSlug(c.modes[i]);
|
|
3149
|
+
for (const c of selected) {
|
|
3150
|
+
for (const v of c.variables) {
|
|
3151
|
+
if (!exportable(v)) continue;
|
|
3152
|
+
const p = property(v);
|
|
3153
|
+
if (!owners.has(p)) owners.set(p, v.id);
|
|
3154
|
+
else
|
|
3155
|
+
warnings.push(
|
|
3156
|
+
`${c.name}/${v.name} is left out of ${c.modes.map((_, i) => selectorOf2(keyOf2(c, i))).join(", ")}: ${p} already holds another variable.`
|
|
3157
|
+
);
|
|
3158
|
+
}
|
|
3159
|
+
}
|
|
3160
|
+
const exported2 = (e) => exportable(e.v) && owners.get(property(e.v)) === e.v.id;
|
|
3161
|
+
const literal = (v, value) => v.type === "FLOAT" && !unitless(v) ? `${value}px` : String(value);
|
|
3162
|
+
const blocks = /* @__PURE__ */ new Map();
|
|
3163
|
+
for (const c of selected) {
|
|
3164
|
+
c.modes.forEach((mode, i) => {
|
|
3165
|
+
const key = keyOf2(c, i);
|
|
3166
|
+
const block = blocks.get(key) ?? blocks.set(key, /* @__PURE__ */ new Map()).get(key);
|
|
3167
|
+
for (const v of c.variables) {
|
|
3168
|
+
const e = byId.get(v.id);
|
|
3169
|
+
if (!exported2(e)) continue;
|
|
3170
|
+
const value = resolve7(e, mode, (t) => exported2(t) ? `var(${property(t.v)})` : void 0, literal);
|
|
3171
|
+
if (value === void 0)
|
|
3172
|
+
warnings.push(`${c.name}/${v.name} is left out of ${selectorOf2(key)}: ${why(e, mode)}.`);
|
|
3173
|
+
else block.set(property(v), String(value));
|
|
3174
|
+
}
|
|
3175
|
+
});
|
|
3176
|
+
}
|
|
3177
|
+
if (options.strict && warnings.length) throw new Problem(`--strict: ${warnings.join(" ")}`);
|
|
3178
|
+
return { blocks, warnings, count: new Set([...blocks.values()].flatMap((b) => [...b.keys()])).size };
|
|
3179
|
+
}
|
|
3180
|
+
var ruleOf = (selector, block) => `${selector} {
|
|
3181
|
+
${[...block].map(([p, v]) => ` ${p}: ${v};`).join("\n")}
|
|
3182
|
+
}
|
|
3183
|
+
`;
|
|
3184
|
+
function render(blocks, root) {
|
|
3185
|
+
return [...blocks].flatMap(([mode, block]) => block.size ? [ruleOf(selectorOf2(mode, root), block)] : []).join("\n");
|
|
3186
|
+
}
|
|
3187
|
+
var isGroup = (x) => x instanceof Object && !Array.isArray(x);
|
|
3188
|
+
var textOf2 = (x) => x === String(x) ? x : void 0;
|
|
3189
|
+
var numberOf = (x) => x === Number(x) ? x : void 0;
|
|
3190
|
+
var dtcgType = (v) => v.type === "COLOR" ? "color" : unitless(v) ? "number" : "dimension";
|
|
3191
|
+
var segment = (name) => name.replace(/[.{}]/g, "_").replace(/^\$/, "_");
|
|
3192
|
+
function groupAt(root, path) {
|
|
3193
|
+
let at = root;
|
|
3194
|
+
for (const part of path) {
|
|
3195
|
+
const next = at[part];
|
|
3196
|
+
at = isGroup(next) ? next : at[part] = {};
|
|
3197
|
+
}
|
|
3198
|
+
return at;
|
|
3199
|
+
}
|
|
3200
|
+
var pathOf = (e) => [e.collection.name, ...e.v.name.split("/")].map(segment);
|
|
3201
|
+
function dtcgOf(collections, options) {
|
|
3202
|
+
const selected = pick(collections, options.collection);
|
|
3203
|
+
const { byId, resolve: resolve7, why } = resolver(collections);
|
|
3204
|
+
const chosen2 = new Set(selected);
|
|
3205
|
+
const warnings = [];
|
|
3206
|
+
const root = {};
|
|
3207
|
+
let count = 0;
|
|
3208
|
+
const literal = (v, value) => v.type === "COLOR" ? String(value) : dtcgType(v) === "number" ? Number(value) : `${value}px`;
|
|
3209
|
+
const ref = (t) => chosen2.has(t.collection) && exportable(t.v) ? `{${pathOf(t).join(".")}}` : void 0;
|
|
3210
|
+
for (const c of selected) {
|
|
3211
|
+
const group = { $extensions: { "com.figdriver": { id: c.id, modes: c.modes } } };
|
|
3212
|
+
root[segment(c.name)] = group;
|
|
3213
|
+
for (const v of c.variables) {
|
|
3214
|
+
if (!exportable(v)) continue;
|
|
3215
|
+
const e = byId.get(v.id);
|
|
3216
|
+
const modes = {};
|
|
3217
|
+
for (const mode of c.modes) {
|
|
3218
|
+
const value = resolve7(e, mode, ref, literal);
|
|
3219
|
+
if (value === void 0) warnings.push(`${c.name}/${v.name} is left out of mode ${mode}: ${why(e, mode)}.`);
|
|
3220
|
+
else modes[mode] = value;
|
|
3221
|
+
}
|
|
3222
|
+
if (modes[c.modes[0]] === void 0) continue;
|
|
3223
|
+
const [, ...path] = pathOf(e);
|
|
3224
|
+
const name = path.pop();
|
|
3225
|
+
const parent = groupAt(group, path);
|
|
3226
|
+
if (isGroup(parent[name]) || "$value" in parent) {
|
|
3227
|
+
warnings.push(`${c.name}/${v.name} is left out: a DTCG token cannot also be a group.`);
|
|
3228
|
+
continue;
|
|
3229
|
+
}
|
|
3230
|
+
parent[name] = {
|
|
3231
|
+
$type: dtcgType(v),
|
|
3232
|
+
$value: modes[c.modes[0]],
|
|
3233
|
+
$extensions: { "com.figdriver": { id: v.id, modes, scopes: v.scopes, web: v.codeSyntax?.WEB } }
|
|
3234
|
+
};
|
|
3235
|
+
count++;
|
|
3236
|
+
}
|
|
3237
|
+
}
|
|
3238
|
+
if (options.strict && warnings.length) throw new Problem(`--strict: ${warnings.join(" ")}`);
|
|
3239
|
+
return { text: `${JSON.stringify(root, null, 2)}
|
|
3240
|
+
`, warnings, count };
|
|
3241
|
+
}
|
|
3242
|
+
function exportTokens(collections, format, options = {}) {
|
|
3243
|
+
if (format === "dtcg") return dtcgOf(collections, options);
|
|
3244
|
+
const { blocks, warnings, count } = declarations(collections, options, format === "tailwind");
|
|
3245
|
+
return { text: render(blocks, format === "tailwind" ? "@theme" : ":root"), warnings, count };
|
|
3246
|
+
}
|
|
3247
|
+
function withAlpha(hex2, alpha) {
|
|
3248
|
+
const byte = Math.round(alpha * 255);
|
|
3249
|
+
return byte < 255 ? hex2 + byte.toString(16).padStart(2, "0") : hex2;
|
|
3250
|
+
}
|
|
3251
|
+
function colorHex(css) {
|
|
3252
|
+
if (/^#[0-9a-f]{8}$/i.test(css)) return css.toLowerCase();
|
|
3253
|
+
const c = parseColor(css.toLowerCase());
|
|
3254
|
+
return c && withAlpha(hexOf(c), c.a);
|
|
3255
|
+
}
|
|
3256
|
+
function pixels(css) {
|
|
3257
|
+
const m = css.trim().match(/^(-?(?:\d+\.?\d*|\.\d+))(px|r?em)?$/);
|
|
3258
|
+
return m ? Number(m[1]) * (m[2]?.endsWith("em") ? 16 : 1) : void 0;
|
|
3259
|
+
}
|
|
3260
|
+
function planOf(collection, modes, drafts, warnings) {
|
|
3261
|
+
const typeOf = (name, seen = /* @__PURE__ */ new Set()) => {
|
|
3262
|
+
const d = drafts.get(name);
|
|
3263
|
+
if (!d || seen.has(name)) return;
|
|
3264
|
+
if (d.type) return d.type;
|
|
3265
|
+
for (const value of d.values.values()) {
|
|
3266
|
+
if (value instanceof Object) {
|
|
3267
|
+
const t = typeOf(value.alias, seen.add(name));
|
|
3268
|
+
if (t) return t;
|
|
3269
|
+
} else return Number(value) === value ? "FLOAT" : "COLOR";
|
|
3270
|
+
}
|
|
3271
|
+
};
|
|
3272
|
+
const variables = [];
|
|
3273
|
+
for (const [name, d] of drafts) {
|
|
3274
|
+
const type = typeOf(name);
|
|
3275
|
+
if (!type) {
|
|
3276
|
+
warnings.push(
|
|
3277
|
+
`${name} is left out: it only aliases variables the file does not define, so its type is unknown. Give it a $type, or define its target.`
|
|
3278
|
+
);
|
|
3279
|
+
continue;
|
|
3280
|
+
}
|
|
3281
|
+
const values = {};
|
|
3282
|
+
for (const [mode, value] of d.values) {
|
|
3283
|
+
if (value instanceof Object || type === "FLOAT" === (Number(value) === value)) values[mode] = value;
|
|
3284
|
+
else warnings.push(`${name} keeps no ${mode} value: ${value} is not a ${type === "FLOAT" ? "number" : "color"}.`);
|
|
3285
|
+
}
|
|
3286
|
+
const [first] = Object.values(values);
|
|
3287
|
+
if (first === void 0) continue;
|
|
3288
|
+
values[modes[0]] ??= first;
|
|
3289
|
+
variables.push({ name, type, values, scopes: d.scopes, codeSyntaxWeb: d.web });
|
|
3290
|
+
}
|
|
3291
|
+
return { collection, modes, variables };
|
|
3292
|
+
}
|
|
3293
|
+
var BLOCK = /(?::root|@theme(?:\s+inline)?|\[data-theme=(["']?)([^"'\]]+)\1\])\s*\{([^{}]*)\}/g;
|
|
3294
|
+
var DECLARATION = /(--[\w-]+)\s*:\s*([^;]+)/g;
|
|
3295
|
+
function parseCssValue(css) {
|
|
3296
|
+
const alias = css.match(/^var\(\s*--([\w-]+)\s*(?:,[^)]*)?\)$/);
|
|
3297
|
+
return alias ? { alias: alias[1] } : pixels(css) ?? colorHex(css);
|
|
3298
|
+
}
|
|
3299
|
+
function parseCss(content, collection) {
|
|
3300
|
+
const modes = ["Default"];
|
|
3301
|
+
const drafts = /* @__PURE__ */ new Map();
|
|
3302
|
+
const warnings = [];
|
|
3303
|
+
for (const [, , theme, body] of content.replace(/\/\*[\s\S]*?\*\//g, "").matchAll(BLOCK)) {
|
|
3304
|
+
const mode = theme ?? modes[0];
|
|
3305
|
+
if (!modes.includes(mode)) modes.push(mode);
|
|
3306
|
+
for (const [, property, raw] of body.matchAll(DECLARATION)) {
|
|
3307
|
+
const value = parseCssValue(raw.trim());
|
|
3308
|
+
if (value === void 0) {
|
|
3309
|
+
warnings.push(
|
|
3310
|
+
`${property} is left out of ${mode}: figdriver imports colors, lengths, numbers, and var() aliases, not ${raw.trim()}.`
|
|
3311
|
+
);
|
|
3312
|
+
continue;
|
|
3313
|
+
}
|
|
3314
|
+
const name = property.slice(2);
|
|
3315
|
+
const d = drafts.get(name) ?? drafts.set(name, { values: /* @__PURE__ */ new Map(), web: `var(${property})` }).get(name);
|
|
3316
|
+
d.values.set(mode, value);
|
|
3317
|
+
}
|
|
3318
|
+
}
|
|
3319
|
+
return { plan: planOf(collection, modes, drafts, warnings), warnings };
|
|
3320
|
+
}
|
|
3321
|
+
var extensionOf = (x) => {
|
|
3322
|
+
const ext = isGroup(x) && isGroup(x.$extensions) ? x.$extensions["com.figdriver"] : void 0;
|
|
3323
|
+
return isGroup(ext) ? ext : void 0;
|
|
3324
|
+
};
|
|
3325
|
+
var textsOf = (x) => Array.isArray(x) ? x.flatMap((s) => textOf2(s) ?? []) : void 0;
|
|
3326
|
+
function parseDtcg(content, collection) {
|
|
3327
|
+
let root;
|
|
3328
|
+
try {
|
|
3329
|
+
root = JSON.parse(content);
|
|
3330
|
+
} catch (e) {
|
|
3331
|
+
throw new Problem(`The tokens file is not JSON: ${messageOf(e)}`);
|
|
3332
|
+
}
|
|
3333
|
+
if (!isGroup(root)) throw new Problem("The tokens file holds no DTCG group at its top level.");
|
|
3334
|
+
const collections = Object.entries(root).flatMap(
|
|
3335
|
+
([name2, g]) => isGroup(g) && textsOf(extensionOf(g)?.modes) ? [name2] : []
|
|
3336
|
+
);
|
|
3337
|
+
if (collection === void 0 && collections.length > 1)
|
|
3338
|
+
throw new Problem(
|
|
3339
|
+
`The tokens file holds several collections. Name one with --collection: ${collections.join(", ")}.`
|
|
3340
|
+
);
|
|
3341
|
+
if (collections.length && collection !== void 0 && !collections.includes(collection))
|
|
3342
|
+
throw new Problem(
|
|
3343
|
+
`The tokens file holds no collection "${collection}". Its collections: ${collections.join(", ")}.`
|
|
3344
|
+
);
|
|
3345
|
+
const name = collection ?? collections[0] ?? "Tokens";
|
|
3346
|
+
const tokens = collections.length ? root[name] : root;
|
|
3347
|
+
const found = [];
|
|
3348
|
+
const walk2 = (group, path, inherited) => {
|
|
3349
|
+
const type = textOf2(group.$type) ?? inherited;
|
|
3350
|
+
for (const [key, child] of Object.entries(group)) {
|
|
3351
|
+
if (key.startsWith("$") || !isGroup(child)) continue;
|
|
3352
|
+
if ("$value" in child) found.push({ path: [...path, key], token: child, type: textOf2(child.$type) ?? type });
|
|
3353
|
+
else walk2(child, [...path, key], type);
|
|
3354
|
+
}
|
|
3355
|
+
};
|
|
3356
|
+
if (isGroup(tokens)) walk2(tokens, []);
|
|
3357
|
+
const declared = textsOf(extensionOf(tokens)?.modes);
|
|
3358
|
+
const modes = declared ?? [...new Set(found.flatMap(({ token }) => Object.keys(modesOf(token))))];
|
|
3359
|
+
if (!modes.length) modes.push("Default");
|
|
3360
|
+
const drafts = /* @__PURE__ */ new Map();
|
|
3361
|
+
const warnings = [];
|
|
3362
|
+
for (const { path, token, type } of found) {
|
|
3363
|
+
const tokenName = path.join("/");
|
|
3364
|
+
const kind = type === "color" ? "COLOR" : type === "dimension" || type === "number" ? "FLOAT" : void 0;
|
|
3365
|
+
if (type !== void 0 && !kind) {
|
|
3366
|
+
warnings.push(`${tokenName} is left out: figdriver imports color, dimension, and number tokens, not ${type}.`);
|
|
3367
|
+
continue;
|
|
3368
|
+
}
|
|
3369
|
+
const ext = extensionOf(token);
|
|
3370
|
+
const values = /* @__PURE__ */ new Map();
|
|
3371
|
+
const byMode = modesOf(token);
|
|
3372
|
+
for (const mode of modes) {
|
|
3373
|
+
const raw = byMode[mode] ?? (mode === modes[0] ? token.$value : void 0);
|
|
3374
|
+
const value = raw === void 0 ? void 0 : dtcgValue(raw, kind, collections);
|
|
3375
|
+
if (value !== void 0) values.set(mode, value);
|
|
3376
|
+
else if (raw !== void 0)
|
|
3377
|
+
warnings.push(`${tokenName} keeps no ${mode} value: figdriver cannot read ${JSON.stringify(raw)}.`);
|
|
3378
|
+
}
|
|
3379
|
+
drafts.set(tokenName, { values, type: kind, scopes: textsOf(ext?.scopes), web: textOf2(ext?.web) });
|
|
3380
|
+
}
|
|
3381
|
+
return { plan: planOf(name, modes, drafts, warnings), warnings };
|
|
3382
|
+
}
|
|
3383
|
+
function modesOf(token) {
|
|
3384
|
+
const modes = extensionOf(token)?.modes;
|
|
3385
|
+
return isGroup(modes) ? modes : {};
|
|
3386
|
+
}
|
|
3387
|
+
function dtcgValue(raw, kind, collections) {
|
|
3388
|
+
const text = textOf2(raw);
|
|
3389
|
+
const ref = text?.match(/^\{([^{}]+)\}$/)?.[1].split(".");
|
|
3390
|
+
if (ref) return { alias: (collections.includes(ref[0]) && ref.length > 1 ? ref.slice(1) : ref).join("/") };
|
|
3391
|
+
if (kind === "COLOR") {
|
|
3392
|
+
const hex2 = isGroup(raw) ? textOf2(raw.hex) : text;
|
|
3393
|
+
const alpha = isGroup(raw) ? numberOf(raw.alpha) : void 0;
|
|
3394
|
+
const color = hex2 === void 0 ? void 0 : colorHex(hex2);
|
|
3395
|
+
return color && alpha !== void 0 && alpha < 1 ? withAlpha(color.slice(0, 7), alpha) : color;
|
|
3396
|
+
}
|
|
3397
|
+
if (isGroup(raw)) {
|
|
3398
|
+
const value = numberOf(raw.value);
|
|
3399
|
+
const unit = textOf2(raw.unit) ?? "px";
|
|
3400
|
+
return value === void 0 ? void 0 : pixels(`${value}${unit}`);
|
|
3401
|
+
}
|
|
3402
|
+
return numberOf(raw) ?? (text === void 0 ? void 0 : pixels(text));
|
|
3403
|
+
}
|
|
3404
|
+
function parseTokensFile(content, format, collection) {
|
|
3405
|
+
return format === "css" ? parseCss(content, collection ?? "Tokens") : parseDtcg(content, collection);
|
|
3406
|
+
}
|
|
3407
|
+
function previewImport(plan, inventory) {
|
|
3408
|
+
const existing = inventory.collections.find((c) => c.name === plan.collection);
|
|
3409
|
+
const modes = [...existing?.modes ?? plan.modes.slice(0, 1)];
|
|
3410
|
+
for (const mode of plan.modes.slice(1)) if (!modes.some((m) => modeKey(m) === modeKey(mode))) modes.push(mode);
|
|
3411
|
+
const own = (existing?.variables ?? []).map((v) => ({ ...v, web: v.codeSyntax?.WEB }));
|
|
3412
|
+
const local = inventory.collections.flatMap((c) => c.variables);
|
|
3413
|
+
const { upserts, warnings } = upsertsOf(plan, own);
|
|
3414
|
+
const upserted = new Map(upserts.map(({ planned }) => [planned.name, planned]));
|
|
3415
|
+
for (const { planned } of upserts) {
|
|
3416
|
+
for (const mode of plan.modes) {
|
|
3417
|
+
const value = planned.values[mode] ?? planned.values[plan.modes[0]];
|
|
3418
|
+
if (value instanceof Object && !aliasTarget(value.alias, planned.type, upserted, local))
|
|
3419
|
+
warnings.push(unboundAlias(planned.name, mode, value.alias));
|
|
3420
|
+
}
|
|
3421
|
+
}
|
|
3422
|
+
const updated = upserts.filter((u) => u.match).length;
|
|
3423
|
+
return { collection: plan.collection, created: upserts.length - updated, updated, modes, warnings };
|
|
3424
|
+
}
|
|
3425
|
+
|
|
3426
|
+
// cli/commands/tokens.ts
|
|
3427
|
+
var EXPORT_FORMATS = ["css", "tailwind", "dtcg"];
|
|
3428
|
+
var IMPORT_FORMATS = ["css", "dtcg"];
|
|
3429
|
+
function formatOf(formats, path, typed) {
|
|
3430
|
+
const format = formats.find((f) => f === (typed ?? (/\.json$/i.test(path) ? "dtcg" : "css")));
|
|
3431
|
+
if (!format) throw new Problem(`--format takes ${formats.join(", ")}, not "${typed}".`);
|
|
3432
|
+
return format;
|
|
3433
|
+
}
|
|
3434
|
+
async function runTokensExport(path, flags, say) {
|
|
3435
|
+
if (!path) throw new Problem("Name the tokens file to write, such as tokens.css or tokens.json.");
|
|
3436
|
+
const format = formatOf(EXPORT_FORMATS, path, flags.format);
|
|
3437
|
+
const [file, page, inventory] = await withFigma(
|
|
3438
|
+
flags,
|
|
3439
|
+
"tokens export",
|
|
3440
|
+
async (s, file2, page2) => [file2, page2, await inspect(s, "inventory")]
|
|
3441
|
+
);
|
|
3442
|
+
const { text, warnings, count } = exportTokens(inventory.collections, format, {
|
|
3443
|
+
collection: flags.collection,
|
|
3444
|
+
strict: flags.strict
|
|
3445
|
+
});
|
|
3446
|
+
write(path, text);
|
|
3447
|
+
say(`${path} ${count} variables as ${format}`);
|
|
3448
|
+
for (const warning of warnings) say(`! ${warning}`);
|
|
3449
|
+
return { command: "tokens export", ok: true, action: "export", format, count, file, page, warnings, files: [path] };
|
|
3450
|
+
}
|
|
3451
|
+
async function runTokensImport(path, flags, say) {
|
|
3452
|
+
if (!path) throw new Problem("Name the tokens file to read, such as tokens.css or tokens.json.");
|
|
3453
|
+
const format = formatOf(IMPORT_FORMATS, path, flags.format);
|
|
3454
|
+
if (!existsSync8(path)) throw new Problem(`No tokens file at ${path}.`);
|
|
3455
|
+
const { plan, warnings } = parseTokensFile(readFileSync7(path, "utf8"), format, flags.collection);
|
|
3456
|
+
if (!plan.variables.length)
|
|
3457
|
+
throw new Problem(
|
|
3458
|
+
`${path} holds no color, dimension, or number tokens to import.${warnings.length ? ` ${warnings.join(" ")}` : ""}`
|
|
3459
|
+
);
|
|
3460
|
+
for (const warning of warnings) say(`! ${warning}`);
|
|
3461
|
+
const count = plan.variables.length;
|
|
3462
|
+
const done = (imported, file, page, dryRun) => {
|
|
3463
|
+
say(
|
|
3464
|
+
`${dryRun ? "Would import" : "Imported"} into "${imported.collection}": ${imported.created} created, ${imported.updated} updated; modes ${imported.modes.join(", ")}`
|
|
3465
|
+
);
|
|
3466
|
+
for (const warning of imported.warnings) say(`! ${warning}`);
|
|
3467
|
+
return {
|
|
3468
|
+
command: "tokens import",
|
|
3469
|
+
ok: true,
|
|
3470
|
+
action: "import",
|
|
3471
|
+
format,
|
|
3472
|
+
dryRun,
|
|
3473
|
+
count,
|
|
3474
|
+
imported,
|
|
3475
|
+
file,
|
|
3476
|
+
page,
|
|
3477
|
+
warnings: [...warnings, ...imported.warnings],
|
|
3478
|
+
files: []
|
|
3479
|
+
};
|
|
3480
|
+
};
|
|
3481
|
+
if (flags["dry-run"])
|
|
3482
|
+
return withFigma(
|
|
3483
|
+
flags,
|
|
3484
|
+
"tokens import",
|
|
3485
|
+
async (s, file, page) => done(previewImport(plan, await inspect(s, "inventory")), file, page, true)
|
|
3486
|
+
);
|
|
3487
|
+
return withWrite(
|
|
3488
|
+
flags,
|
|
3489
|
+
"tokens import",
|
|
3490
|
+
DEFAULT_WAIT_SECONDS,
|
|
3491
|
+
{
|
|
3492
|
+
prepare: (_s, status) => {
|
|
3493
|
+
if (!status.capabilities.write || !status.capabilities.variables)
|
|
3494
|
+
throw new Problem(`The ${status.editor} editor cannot write variables, so nothing was imported.`);
|
|
3495
|
+
}
|
|
3496
|
+
},
|
|
3497
|
+
`figdriver.importTokens(${JSON.stringify(plan)})`,
|
|
3498
|
+
(_s, file, page, imported) => done(imported, file, page)
|
|
3499
|
+
);
|
|
3500
|
+
}
|
|
3501
|
+
|
|
3502
|
+
// cli/commands/verify.ts
|
|
3503
|
+
import { extname as extname3 } from "node:path";
|
|
3504
|
+
var FORMATS = ["png", "svg", "pdf", "jpg"];
|
|
3505
|
+
var EXTENSIONS3 = /* @__PURE__ */ new Map([
|
|
3506
|
+
[".png", "png"],
|
|
3507
|
+
[".svg", "svg"],
|
|
3508
|
+
[".pdf", "pdf"],
|
|
3509
|
+
[".jpg", "jpg"],
|
|
3510
|
+
[".jpeg", "jpg"]
|
|
3511
|
+
]);
|
|
3512
|
+
function exportOptions(flags, file) {
|
|
3513
|
+
const typed = flags.format;
|
|
3514
|
+
const format = FORMATS.find((f) => f === typed);
|
|
3515
|
+
if (typed !== void 0 && !format) throw new Problem(`--format takes ${FORMATS.join(", ")}, not "${typed}".`);
|
|
3516
|
+
const ext = extname3(file ?? "");
|
|
3517
|
+
const implied = EXTENSIONS3.get(ext.toLowerCase());
|
|
3518
|
+
if (format && implied && format !== implied)
|
|
3519
|
+
throw new Problem(`${file} ends in ${ext}, but --format is ${format}. Make them agree.`);
|
|
3520
|
+
const chosen2 = format ?? implied ?? "png";
|
|
3521
|
+
if (flags.scale !== void 0 && (chosen2 === "svg" || chosen2 === "pdf"))
|
|
3522
|
+
throw new Problem(`--scale sizes png and jpg exports. ${chosen2} is a vector format, so leave it out.`);
|
|
3523
|
+
return {
|
|
3524
|
+
format: chosen2,
|
|
3525
|
+
// main validates --bounds as one of its two values.
|
|
3526
|
+
bounds: flags.bounds === "layout" ? "layout" : "render",
|
|
3527
|
+
scale: Number(flags.scale ?? 1)
|
|
3528
|
+
};
|
|
3529
|
+
}
|
|
3530
|
+
async function runExport(out, id, flags, say) {
|
|
3531
|
+
if (!out)
|
|
3532
|
+
throw new Problem(
|
|
3533
|
+
"Name the output file (with a node id) or output folder (with --node, --selection, --page, or --screens)."
|
|
3534
|
+
);
|
|
3535
|
+
const targets2 = chosen(!!id || !!flags.node?.length, !!flags.selection, flags.page !== void 0, !!flags.screens);
|
|
3536
|
+
if (targets2 === 0)
|
|
3537
|
+
throw new Problem(
|
|
3538
|
+
"Name what to export: pass a node id, --node <id>..., --selection, --page <name|id>, or --screens."
|
|
3539
|
+
);
|
|
3540
|
+
if (targets2 > 1) throw new Problem("Pass one of a node id, --node, --selection, --page, or --screens.");
|
|
3541
|
+
if (flags.node?.length && id)
|
|
3542
|
+
throw new Problem("Pass either a positional node id or repeatable --node flags, not both.");
|
|
3543
|
+
const hasExportExt = EXTENSIONS3.has(extname3(out).toLowerCase());
|
|
3544
|
+
const singleNodeId = id ? parseNodeId(id) : flags.node?.length === 1 && hasExportExt ? parseNodeId(flags.node[0]) : null;
|
|
3545
|
+
if (singleNodeId) {
|
|
3546
|
+
const options2 = exportOptions(flags, out);
|
|
3547
|
+
const [file2, page2, shot] = await withFigma(flags, "export", async (s, file3, current) => {
|
|
3548
|
+
const [item] = await inspect(s, "nodes", [singleNodeId], options2, false);
|
|
3549
|
+
if (!item) throw new Problem(`No exportable node with id ${singleNodeId}`);
|
|
3550
|
+
return [file3, current, item];
|
|
3551
|
+
});
|
|
3552
|
+
write(out, Buffer.from(shot.data, "base64"));
|
|
3553
|
+
say(out);
|
|
3554
|
+
return {
|
|
3555
|
+
command: "export",
|
|
3556
|
+
ok: true,
|
|
3557
|
+
file: file2,
|
|
3558
|
+
page: page2,
|
|
3559
|
+
node: singleNodeId,
|
|
3560
|
+
format: options2.format,
|
|
3561
|
+
bounds: options2.bounds,
|
|
3562
|
+
screens: [{ name: shot.name, id: shot.id, file: out }],
|
|
3563
|
+
warnings: [],
|
|
3564
|
+
files: [out]
|
|
3565
|
+
};
|
|
3566
|
+
}
|
|
3567
|
+
if (hasExportExt)
|
|
3568
|
+
throw new Problem(
|
|
3569
|
+
`"${out}" looks like a single file path, but this export writes a folder. Pass an output folder instead.`
|
|
3570
|
+
);
|
|
3571
|
+
const options = exportOptions(flags);
|
|
3572
|
+
const ids = (flags.node ?? []).map(parseNodeId);
|
|
3573
|
+
const [file, page, screens] = await withFigma(flags, "export", async (s, file2, current) => {
|
|
3574
|
+
if (flags.screens) {
|
|
3575
|
+
const built = await exportScreens(s, out, null, options, false, say);
|
|
3576
|
+
if (!built.length)
|
|
3577
|
+
throw new Problem(
|
|
3578
|
+
`${file2.name} holds no screens built by figdriver. Pass --page <name> to export any page's frames, or build first with \`figdriver import run <dir> --file ${file2.key}\`.`
|
|
3579
|
+
);
|
|
3580
|
+
return [file2, current, built];
|
|
3581
|
+
}
|
|
3582
|
+
if (flags.page !== void 0) {
|
|
3583
|
+
const { page: resolved, shots } = await inspect(s, "pageFrames", flags.page, options);
|
|
3584
|
+
if (!shots.length)
|
|
3585
|
+
throw new Problem(
|
|
3586
|
+
`Page "${resolved.name}" (${resolved.id}) in ${file2.name} holds no top-level or section frames to export.`
|
|
3587
|
+
);
|
|
3588
|
+
return [file2, resolved, await writeShotDir(shots, out, false, say)];
|
|
3589
|
+
}
|
|
3590
|
+
return [
|
|
3591
|
+
file2,
|
|
3592
|
+
current,
|
|
3593
|
+
await writeShotDir(await inspect(s, "nodes", ids, options, flags.selection === true), out, false, say)
|
|
3594
|
+
];
|
|
3595
|
+
});
|
|
3596
|
+
return {
|
|
3597
|
+
command: "export",
|
|
3598
|
+
ok: true,
|
|
3599
|
+
file,
|
|
3600
|
+
page,
|
|
3601
|
+
node: !flags.selection && !flags.screens && flags.page === void 0 && ids.length === 1 ? ids[0] : null,
|
|
3602
|
+
format: options.format,
|
|
3603
|
+
bounds: options.bounds,
|
|
3604
|
+
screens,
|
|
3605
|
+
warnings: [],
|
|
3606
|
+
files: screens.map((x) => x.file)
|
|
3607
|
+
};
|
|
3608
|
+
}
|
|
3609
|
+
async function runNodeParityCommand(nodeId, reference, flags, say) {
|
|
3610
|
+
if (!nodeId || !reference)
|
|
3611
|
+
throw new Problem("Pass both a node id and a reference PNG: figdriver parity <node-id> <reference.png>");
|
|
3612
|
+
const id = parseNodeId(nodeId);
|
|
3613
|
+
const options = { bounds: flags.bounds === "render" ? "render" : "layout" };
|
|
3614
|
+
return runNodeParity(
|
|
3615
|
+
id,
|
|
3616
|
+
reference,
|
|
3617
|
+
flags.out ?? "out/parity",
|
|
3618
|
+
maxMismatchOf(flags),
|
|
3619
|
+
() => withFigma(flags, "parity", async (s, file, page) => {
|
|
3620
|
+
const [shot] = await inspect(s, "nodes", [id], options, false);
|
|
3621
|
+
return [file, page, shot];
|
|
3622
|
+
}),
|
|
3623
|
+
say
|
|
3624
|
+
);
|
|
3625
|
+
}
|
|
3626
|
+
async function runAuditPage(flags, say) {
|
|
3627
|
+
const ruleset = flags.ruleset === "run" ? "run" : "authored";
|
|
3628
|
+
const [file, raw] = await withFigma(
|
|
3629
|
+
flags,
|
|
3630
|
+
"audit",
|
|
3631
|
+
async (s, file2, current) => [file2, await inspect(s, "auditPage", flags.page ?? current.id, ruleset)]
|
|
3632
|
+
);
|
|
3633
|
+
const { page, layers, ...rest } = raw;
|
|
3634
|
+
const audit = auditReport(rest, null, layers > 0);
|
|
3635
|
+
reportAudit(audit, say, page);
|
|
3636
|
+
return { command: "audit", ok: audit.clean, design: null, ruleset, file, page, audit, warnings: [], files: [] };
|
|
3637
|
+
}
|
|
3638
|
+
|
|
3639
|
+
// cli/main.ts
|
|
3640
|
+
var VERSION = JSON.parse(readFileSync8(resolve6(import.meta.dirname, "../package.json"), "utf8")).version;
|
|
3641
|
+
var OPTIONS = {
|
|
3642
|
+
viewport: { type: "string" },
|
|
3643
|
+
scale: { type: "string" },
|
|
3644
|
+
depth: { type: "string" },
|
|
3645
|
+
timeout: { type: "string" },
|
|
3646
|
+
expression: { type: "string", short: "e" },
|
|
3647
|
+
page: { type: "string" },
|
|
3648
|
+
"all-pages": { type: "boolean" },
|
|
3649
|
+
under: { type: "string" },
|
|
3650
|
+
json: { type: "boolean" },
|
|
3651
|
+
force: { type: "boolean" },
|
|
3652
|
+
wait: { type: "boolean" },
|
|
3653
|
+
duplicates: { type: "boolean" },
|
|
3654
|
+
bundle: { type: "boolean" },
|
|
3655
|
+
"read-only": { type: "boolean", short: "r" },
|
|
3656
|
+
node: { type: "string", multiple: true },
|
|
3657
|
+
selection: { type: "boolean" },
|
|
3658
|
+
screens: { type: "boolean" },
|
|
3659
|
+
include: { type: "string" },
|
|
3660
|
+
"expand-instances": { type: "boolean" },
|
|
3661
|
+
collection: { type: "string" },
|
|
3662
|
+
strict: { type: "boolean" },
|
|
3663
|
+
format: { type: "string" },
|
|
3664
|
+
"dry-run": { type: "boolean" },
|
|
3665
|
+
name: { type: "string" },
|
|
3666
|
+
type: { type: "string" },
|
|
3667
|
+
text: { type: "string" },
|
|
3668
|
+
component: { type: "string" },
|
|
3669
|
+
limit: { type: "string" },
|
|
3670
|
+
file: { type: "string" },
|
|
3671
|
+
bounds: { type: "string" },
|
|
3672
|
+
ruleset: { type: "string" },
|
|
3673
|
+
out: { type: "string" },
|
|
3674
|
+
"max-mismatch": { type: "string" },
|
|
3675
|
+
embed: { type: "string" },
|
|
3676
|
+
"new-window": { type: "boolean" },
|
|
3677
|
+
help: { type: "boolean", short: "h" },
|
|
3678
|
+
version: { type: "boolean", short: "v" }
|
|
3679
|
+
};
|
|
3680
|
+
var VIEWPORT = "[1-9]\\d*x[1-9]\\d*";
|
|
3681
|
+
var VALUES = /* @__PURE__ */ new Map([
|
|
3682
|
+
["depth", ["a whole number, such as 3", (v) => /^\d+$/.test(v)]],
|
|
3683
|
+
["limit", ["a whole number above 0, such as 50", (v) => /^[1-9]\d*$/.test(v)]],
|
|
3684
|
+
["scale", ["a number above 0, such as 2", (v) => Number(v) > 0 && Number.isFinite(Number(v))]],
|
|
3685
|
+
["timeout", ["a number above 0, such as 120", (v) => Number(v) > 0 && Number.isFinite(Number(v))]],
|
|
3686
|
+
[
|
|
3687
|
+
"viewport",
|
|
3688
|
+
[
|
|
3689
|
+
"WIDTHxHEIGHT or a comma-separated list of them, such as 1440x900 or 1440x900,390x844",
|
|
3690
|
+
(v) => new RegExp(`^${VIEWPORT}(,${VIEWPORT})*$`).test(v)
|
|
3691
|
+
]
|
|
3692
|
+
],
|
|
3693
|
+
["max-mismatch", ["a percentage from 0 to 100, such as 1.5", (v) => /^\d+(\.\d+)?$/.test(v) && Number(v) <= 100]],
|
|
3694
|
+
["bounds", ["render or layout", (v) => v === "render" || v === "layout"]],
|
|
3695
|
+
["ruleset", ["run or authored", (v) => v === "run" || v === "authored"]]
|
|
3696
|
+
]);
|
|
3697
|
+
var FILE = "[--file <url|key>]";
|
|
3698
|
+
var COMMANDS = {
|
|
3699
|
+
browser: {
|
|
3700
|
+
kind: "group",
|
|
3701
|
+
summary: "Manage the debugging Chromium browser, tabs, and window screenshots",
|
|
3702
|
+
details: "Start or stop the isolated Chromium profile, manage open Figma tabs, or screenshot a tab window.",
|
|
3703
|
+
subcommands: {
|
|
3704
|
+
open: {
|
|
3705
|
+
kind: "leaf",
|
|
3706
|
+
args: "[url] [--new-window] [--json]",
|
|
3707
|
+
most: 1,
|
|
3708
|
+
flags: ["new-window", "json"],
|
|
3709
|
+
summary: "Start the debugging browser if needed, or open/focus a URL",
|
|
3710
|
+
details: "Starts the isolated debugging Chromium if it is not running, or opens/focuses the given URL if it is. Reuses an existing tab for the same Figma file key. --new-window opens the URL in its own window so parallel agents working on different files never throttle each other's tabs.",
|
|
3711
|
+
examples: [
|
|
3712
|
+
'figdriver browser open "https://www.figma.com/design/<key>/<name>"',
|
|
3713
|
+
'figdriver browser open "https://www.figma.com/design/<key>/<name>" --new-window'
|
|
3714
|
+
],
|
|
3715
|
+
run: ([url], { flags, say }) => runBrowserOpen(url, flags["new-window"] === true, say)
|
|
3716
|
+
},
|
|
3717
|
+
tabs: {
|
|
3718
|
+
kind: "leaf",
|
|
3719
|
+
args: "[--json]",
|
|
3720
|
+
most: 0,
|
|
3721
|
+
flags: ["json"],
|
|
3722
|
+
summary: "List open tabs with Figma file keys and duplicate-tab warnings",
|
|
3723
|
+
details: "Lists every open page tab in the debugging browser, its Figma file key, and warnings for any file open in multiple tabs.",
|
|
3724
|
+
examples: ["figdriver browser tabs --json"],
|
|
3725
|
+
run: (_, { say }) => runBrowserTabs(say)
|
|
3726
|
+
},
|
|
3727
|
+
close: {
|
|
3728
|
+
kind: "leaf",
|
|
3729
|
+
args: "[url | key | tab-id] [--duplicates] [--json]",
|
|
3730
|
+
most: 1,
|
|
3731
|
+
flags: ["duplicates", "json"],
|
|
3732
|
+
summary: "Close matching tab(s) or extra duplicate tabs of a file",
|
|
3733
|
+
details: "Closes tabs matching a tab id, URL, or Figma file key. Pass --duplicates to close only extra copies of any file open in more than one tab (write commands refuse duplicate tabs).",
|
|
3734
|
+
examples: ["figdriver browser close --duplicates", "figdriver browser close <file-key>"],
|
|
3735
|
+
run: ([wanted], { flags, say }) => runBrowserClose(wanted, flags.duplicates === true, say)
|
|
3736
|
+
},
|
|
3737
|
+
stop: {
|
|
3738
|
+
kind: "leaf",
|
|
3739
|
+
args: "[--json]",
|
|
3740
|
+
most: 0,
|
|
3741
|
+
flags: ["json"],
|
|
3742
|
+
summary: "Close the debugging browser",
|
|
3743
|
+
details: "Stops the running figdriver debugging browser process cleanly.",
|
|
3744
|
+
examples: ["figdriver browser stop"],
|
|
3745
|
+
run: (_, { say }) => runBrowserStop(say)
|
|
3746
|
+
},
|
|
3747
|
+
screenshot: {
|
|
3748
|
+
kind: "leaf",
|
|
3749
|
+
args: `<out.png> ${FILE} [--wait] [--json]`,
|
|
3750
|
+
most: 1,
|
|
3751
|
+
flags: ["file", "wait", "json"],
|
|
3752
|
+
summary: "Capture the visible Figma browser tab window as a PNG",
|
|
3753
|
+
details: "Brings the matched Figma tab to the front and captures a PNG screenshot of the browser window (works even on view-only files where the Plugin API is unavailable). To export Figma layers, use `figdriver export`.",
|
|
3754
|
+
examples: ["figdriver browser screenshot out/tab.png"],
|
|
3755
|
+
run: ([out], { flags, say }) => runBrowserScreenshot(out, flags, say)
|
|
3756
|
+
}
|
|
3757
|
+
}
|
|
3758
|
+
},
|
|
3759
|
+
doctor: {
|
|
3760
|
+
kind: "leaf",
|
|
3761
|
+
args: `${FILE} [--wait] [--json]`,
|
|
3762
|
+
most: 0,
|
|
3763
|
+
flags: ["file", "wait", "json"],
|
|
3764
|
+
summary: "Check browser connection, file edit access, capabilities, and active users",
|
|
3765
|
+
details: "Verifies the debugging browser, matched Figma file, editor capabilities (Design, FigJam, Slides, Dev Mode), page count, other active users in the file, and whether a figdriver write is currently running.",
|
|
3766
|
+
examples: ["figdriver doctor --json"],
|
|
3767
|
+
run: (_, { flags, say }) => runDoctor(VERSION, flags, say)
|
|
3768
|
+
},
|
|
3769
|
+
find: {
|
|
3770
|
+
kind: "leaf",
|
|
3771
|
+
args: `(--name <text> | --type <TYPE[,TYPE]> | --text <text> | --component <name>)... [--page <name|id> | --all-pages | --under <node-id>] [--limit 50] ${FILE} [--wait] [--json]`,
|
|
3772
|
+
most: 0,
|
|
3773
|
+
flags: ["name", "type", "text", "component", "page", "all-pages", "under", "limit", "file", "wait", "json"],
|
|
3774
|
+
summary: "Search layers compactly by name, type, text, or component",
|
|
3775
|
+
details: "Lists matching layers one per line with id, type, path, main component, instance property keys (such as Label#1:23), and text content. --name, --text (text, sticky, and shape content), and --component match case-insensitively by substring; --type matches exact Figma node types (comma-separated). --component matches INSTANCE nodes by their main component or set name, never COMPONENT or COMPONENT_SET definitions (find those with --type COMPONENT,COMPONENT_SET --name). Searches the current page by default, or scope with --page, --all-pages, or --under <node-id>. Prefer `find` over `inspect --page` on large pages.",
|
|
3776
|
+
examples: [
|
|
3777
|
+
"figdriver find --type INSTANCE --component Button --all-pages",
|
|
3778
|
+
'figdriver find --page "Pricing" --type TEXT,INSTANCE',
|
|
3779
|
+
"figdriver find --under 1:23 --name Summary"
|
|
3780
|
+
],
|
|
3781
|
+
run: (_, { flags, say }) => runFind(flags, say)
|
|
3782
|
+
},
|
|
3783
|
+
inspect: {
|
|
3784
|
+
kind: "leaf",
|
|
3785
|
+
args: `[(--node <id>... | --page <name|id> | --selection) [--depth 3] [--include <sections>] [--expand-instances]] ${FILE} [--wait] [--json]`,
|
|
3786
|
+
most: 0,
|
|
3787
|
+
flags: ["node", "page", "selection", "depth", "include", "expand-instances", "file", "wait", "json"],
|
|
3788
|
+
summary: "Read file inventory or narrow layer subtree details",
|
|
3789
|
+
details: "With no target flags: prints the file inventory (pages, prototype flows, variable collections with modes and codeSyntax, styles, and components with property definitions). With --node (repeatable), --page, or --selection: prints layer trees up to --depth levels deep. --expand-instances descends into instances, and --include adds prototype, handoff, variables, text-runs, grids, vectors, or all (comma-separated). Use `find` first to locate specific node ids on large pages; terminal tree dumps above 16 KB print a compact summary unless --json is passed. To export variables as CSS/Tailwind/DTCG, use `figdriver tokens export`.",
|
|
3790
|
+
examples: [
|
|
3791
|
+
"figdriver inspect --json",
|
|
3792
|
+
"figdriver inspect --node 1:23 --include prototype,handoff --expand-instances"
|
|
3793
|
+
],
|
|
3794
|
+
run: (_, { flags }) => runInspect(flags)
|
|
3795
|
+
},
|
|
3796
|
+
tokens: {
|
|
3797
|
+
kind: "group",
|
|
3798
|
+
summary: "Export or import Figma variables as CSS, Tailwind @theme, or W3C DTCG JSON",
|
|
3799
|
+
details: "Sync Figma variable collections to and from CSS custom properties, Tailwind v4 @theme, or W3C DTCG JSON.",
|
|
3800
|
+
subcommands: {
|
|
3801
|
+
export: {
|
|
3802
|
+
kind: "leaf",
|
|
3803
|
+
args: `<out-file> [--format css|tailwind|dtcg] [--collection <name|id>] [--strict] ${FILE} [--wait] [--json]`,
|
|
3804
|
+
most: 1,
|
|
3805
|
+
flags: ["format", "collection", "strict", "file", "wait", "json"],
|
|
3806
|
+
summary: "Write color and number variables to CSS, Tailwind @theme, or DTCG JSON",
|
|
3807
|
+
details: "Exports variable collections as CSS custom properties (:root / [data-theme]), Tailwind v4 @theme, or W3C DTCG JSON (default for .json files). Resolves aliases by variable id and honors WEB codeSyntax. --collection limits to one collection; --strict fails if any variable is skipped or collides.",
|
|
3808
|
+
examples: [
|
|
3809
|
+
"figdriver tokens export tokens.css --collection Brand --strict",
|
|
3810
|
+
"figdriver tokens export tokens.json --format dtcg --collection Brand"
|
|
3811
|
+
],
|
|
3812
|
+
run: ([path], { flags, say }) => runTokensExport(path, flags, say)
|
|
3813
|
+
},
|
|
3814
|
+
import: {
|
|
3815
|
+
kind: "leaf",
|
|
3816
|
+
args: `<in-file> [--format css|dtcg] [--collection <name>] [--dry-run] ${FILE} [--wait] [--json]`,
|
|
3817
|
+
most: 1,
|
|
3818
|
+
flags: ["format", "collection", "dry-run", "file", "wait", "json"],
|
|
3819
|
+
summary: "Upsert CSS or W3C DTCG tokens into a Figma variable collection",
|
|
3820
|
+
details: "Reads CSS (:root/@theme/[data-theme]) or W3C DTCG JSON and upserts variables, modes, and aliases into --collection (default: the file's sole collection, or Tokens). Pass --dry-run to preview creates/updates without writing.",
|
|
3821
|
+
writes: "Writes to Figma unless --dry-run is set (requires --file or FIGDRIVER_FILE).",
|
|
3822
|
+
examples: [
|
|
3823
|
+
"figdriver tokens import tokens.css --collection Brand --dry-run",
|
|
3824
|
+
"figdriver tokens import tokens.json --collection Brand --file <key>"
|
|
3825
|
+
],
|
|
3826
|
+
run: ([path], { flags, say }) => runTokensImport(path, flags, say)
|
|
3827
|
+
}
|
|
3828
|
+
}
|
|
3829
|
+
},
|
|
3830
|
+
eval: {
|
|
3831
|
+
kind: "leaf",
|
|
3832
|
+
args: `(<file.js|ts | -> | -e '<code>') [--bundle] [--read-only] [--page <name|id>] [--timeout 600] ${FILE} [--wait] [--json]`,
|
|
3833
|
+
most: 1,
|
|
3834
|
+
flags: ["expression", "bundle", "read-only", "wait", "timeout", "file", "page", "json"],
|
|
3835
|
+
summary: "Run Plugin API JS/TS scripts with global `fd` helpers",
|
|
3836
|
+
details: [
|
|
3837
|
+
"Runs Plugin API code in the matched Figma file (file path, `-` for stdin, or `-e '<code>'`).",
|
|
3838
|
+
"Plain JS runs in an isolated async scope (top-level await, return, and trailing expressions work). .ts files and --bundle modules bundle local imports, call `export default` if it is a function, and map errors back to .ts lines.",
|
|
3839
|
+
"--read-only (-r) skips the write lock and --file requirement for read-only queries (it does not sandbox mutations).",
|
|
3840
|
+
"",
|
|
3841
|
+
"Global `fd` helpers. Every node or variable argument accepts a live object or its id string:",
|
|
3842
|
+
" fd.page Target PageNode (--page or current page)",
|
|
3843
|
+
" await fd.find(root | null, pred) Safe recursive search (skips leaves; null = fd.page)",
|
|
3844
|
+
" await fd.mainOf(inst) Async main component lookup (no deprecation warning)",
|
|
3845
|
+
" await fd.replaceText(text, next, opts?) Loads range fonts; { replace: 'old' | /re/ } or { range: [s, e] } preserves mixed spans",
|
|
3846
|
+
" await fd.setProps(inst, props) Calls setProperties(props) using exact #id keys from `find`",
|
|
3847
|
+
" await fd.setSlot(inst, slotName, fn | null) Clears and populates a SLOT child (null resets)",
|
|
3848
|
+
" await fd.placeInstance(comp, parent, opts?) Appends instance before applying { index, fillX, fillY, props }",
|
|
3849
|
+
" await fd.bindColor(node, varId, opts?) Binds opaque solid fill/stroke variable ({ field, index, force })"
|
|
3850
|
+
].join("\n"),
|
|
3851
|
+
writes: "Writes to Figma unless --read-only (-r) is set (requires --file or FIGDRIVER_FILE).",
|
|
3852
|
+
examples: [
|
|
3853
|
+
`figdriver eval -e 'await fd.replaceText("1:23", "Annual", { replace: "Monthly" })'`,
|
|
3854
|
+
`figdriver eval -e 'await fd.setProps("1:40", { "Price#1:3": "$49", "Popular Badge#1:4": true })'`,
|
|
3855
|
+
"figdriver eval ./script.ts --page Pricing"
|
|
3856
|
+
],
|
|
3857
|
+
run: ([path], { flags }) => runEval(path, flags)
|
|
3858
|
+
},
|
|
3859
|
+
export: {
|
|
3860
|
+
kind: "leaf",
|
|
3861
|
+
args: `<out-file> <node-id> | <out-dir> (--node <id>... | --selection | --page <name|id> | --screens) [--format png|svg|pdf|jpg] [--bounds render|layout] [--scale 1] ${FILE} [--wait] [--json]`,
|
|
3862
|
+
most: 2,
|
|
3863
|
+
flags: ["node", "selection", "page", "screens", "format", "bounds", "scale", "file", "wait", "json"],
|
|
3864
|
+
summary: "Export node(s), selection, a page's frames, or built screens as PNG/SVG/PDF/JPG",
|
|
3865
|
+
details: "Exports one node to <out-file>, or exports multiple --node ids, the current --selection, every top-level/section frame of --page (or slides of a Slides file), or figdriver-built --screens into <out-dir>. --format (or <out-file>'s extension) selects png, svg, pdf, or jpg. --bounds layout clips to the node's layout box, excluding shadows that paint past it; default is render. --scale applies to png and jpg only.",
|
|
3866
|
+
examples: [
|
|
3867
|
+
"figdriver export out/card.svg 1:23 --bounds layout",
|
|
3868
|
+
'figdriver export out/screens --page "Cover" --format png --scale 2',
|
|
3869
|
+
"figdriver export out/selected --selection"
|
|
3870
|
+
],
|
|
3871
|
+
run: ([out, id], { flags, say }) => runExport(out, id, flags, say)
|
|
3872
|
+
},
|
|
3873
|
+
parity: {
|
|
3874
|
+
kind: "leaf",
|
|
3875
|
+
args: `<node-id> <reference.png> [--out out/parity] [--bounds layout|render] [--max-mismatch <pct>] ${FILE} [--wait] [--json]`,
|
|
3876
|
+
most: 2,
|
|
3877
|
+
flags: ["out", "bounds", "max-mismatch", "file", "wait", "json"],
|
|
3878
|
+
summary: "Visually diff one Figma node against a reference PNG",
|
|
3879
|
+
details: "Exports <node-id> (at layout bounds by default) and diffs it against <reference.png>, writing a side-by-side triptych into --out. Exits 1 when mismatch exceeds --max-mismatch percent. To diff a web-to-Figma rebuild directory, use `figdriver import parity <dir>`.",
|
|
3880
|
+
examples: ["figdriver parity 1:23 ref/expected.png --out out/parity --max-mismatch 2"],
|
|
3881
|
+
run: ([nodeId, reference], { flags, say }) => runNodeParityCommand(nodeId, reference, flags, say)
|
|
3882
|
+
},
|
|
3883
|
+
audit: {
|
|
3884
|
+
kind: "leaf",
|
|
3885
|
+
args: `[--page <name|id>] [--ruleset authored|run] ${FILE} [--wait] [--json]`,
|
|
3886
|
+
most: 0,
|
|
3887
|
+
flags: ["page", "ruleset", "file", "wait", "json"],
|
|
3888
|
+
summary: "Audit a page's layers for text styles, variable-bound colors, and layout issues",
|
|
3889
|
+
details: "Audits every layer on --page (or the file's current page) using the `authored` ruleset by default (no auto-layout demands, library instances allowed, any local color variable counts as a token). Pass --ruleset run for strict figdriver build rules, or use `figdriver import audit` to audit web-to-Figma builds.",
|
|
3890
|
+
examples: ['figdriver audit --page "Cover"'],
|
|
3891
|
+
run: (_, { flags, say }) => runAuditPage(flags, say)
|
|
3892
|
+
},
|
|
3893
|
+
import: {
|
|
3894
|
+
kind: "group",
|
|
3895
|
+
summary: "Web-to-Figma rebuild pipeline (capture, outline, run, audit, parity, plugin)",
|
|
3896
|
+
details: "Capture a web page or Figma Make embed, inspect its DOM outline, rebuild it into Figma, and verify parity.",
|
|
3897
|
+
subcommands: {
|
|
3898
|
+
capture: {
|
|
3899
|
+
kind: "leaf",
|
|
3900
|
+
args: `<dir> [url | file.html[#hash]] [--viewport 1440x900[,390x844...]] [--embed <node-id>] ${FILE} [--json]`,
|
|
3901
|
+
most: 2,
|
|
3902
|
+
flags: ["viewport", "embed", "file", "json"],
|
|
3903
|
+
summary: "Capture a URL, HTML file, or Figma Make embed into <dir>/snapshot.json",
|
|
3904
|
+
details: "Renders a URL or local HTML file into <dir>/snapshot.json, assets, <dir>/ref/page.png, and a starter <dir>/index.ts. Runs headless when no debugging browser is up. Comma-separated --viewport sizes write the first to <dir> and extras to <dir>/<w>x<h>/. Omit the source to capture a Figma Make embed (--embed selects one CODE_INSTANCE).",
|
|
3905
|
+
examples: [
|
|
3906
|
+
"figdriver import capture ./landing https://example.com",
|
|
3907
|
+
"figdriver import capture ./landing ./page.html --viewport 1440x900,390x844"
|
|
3908
|
+
],
|
|
3909
|
+
run: ([dir, source], { flags, say }) => runImportCapture(dir, source, flags, say)
|
|
3910
|
+
},
|
|
3911
|
+
outline: {
|
|
3912
|
+
kind: "leaf",
|
|
3913
|
+
args: "<dir> [--depth n]",
|
|
3914
|
+
most: 1,
|
|
3915
|
+
flags: ["depth"],
|
|
3916
|
+
summary: "Print a captured page's tag/class tree, tokens, and icons footer",
|
|
3917
|
+
details: "Prints the captured snapshot in <dir>/snapshot.json as a compact tree of tags, classes, tokens, and distinct icon SVG fragments to write spec match rules against.",
|
|
3918
|
+
examples: ["figdriver import outline ./landing --depth 4"],
|
|
3919
|
+
run: async ([dir], { flags }) => runImportOutline(dir, flags)
|
|
3920
|
+
},
|
|
3921
|
+
run: {
|
|
3922
|
+
kind: "leaf",
|
|
3923
|
+
args: `<dir> --file <url|key> [--page <name|id>] [--force] [--wait] [--timeout 900] [--json]`,
|
|
3924
|
+
most: 1,
|
|
3925
|
+
flags: ["file", "page", "force", "wait", "timeout", "json"],
|
|
3926
|
+
summary: "Build a design spec in Figma, audit it, and export its screens",
|
|
3927
|
+
details: "Stages and builds <dir>/index.ts on --page (created if missing) or the current page, audits the output, and exports screens to <dir>/out/screens/. Replaces prior output of the same spec name only when clean, unedited, and every external reference migrates unambiguously; otherwise keeps the build on a draft page and exits 1. --force replaces edited or in-use output, never builds with audit/fallback problems.",
|
|
3928
|
+
writes: "Writes to Figma (requires --file or FIGDRIVER_FILE).",
|
|
3929
|
+
examples: ['figdriver import run ./landing --page "Landing"'],
|
|
3930
|
+
run: ([typed], { flags, say }) => runDesign(typed, flags, say)
|
|
3931
|
+
},
|
|
3932
|
+
audit: {
|
|
3933
|
+
kind: "leaf",
|
|
3934
|
+
args: `[dir] [--ruleset run|authored] ${FILE} [--wait] [--json]`,
|
|
3935
|
+
most: 1,
|
|
3936
|
+
flags: ["ruleset", "file", "wait", "json"],
|
|
3937
|
+
summary: "Audit figdriver-built output (every page, or one design folder/draft)",
|
|
3938
|
+
details: "Checks what figdriver built on every page of the file, or the named design folder (including its draft page when the last run kept one): auto layout, text styles, instances, and variable-bound colors.",
|
|
3939
|
+
examples: ["figdriver import audit ./landing"],
|
|
3940
|
+
run: ([dir], { flags, say }) => runImportAudit(dir, flags, say)
|
|
3941
|
+
},
|
|
3942
|
+
parity: {
|
|
3943
|
+
kind: "leaf",
|
|
3944
|
+
args: `<dir> [--max-mismatch <pct>] ${FILE} [--wait] [--json]`,
|
|
3945
|
+
most: 1,
|
|
3946
|
+
flags: ["max-mismatch", "file", "wait", "json"],
|
|
3947
|
+
summary: "Diff every rebuilt section of <dir> against <dir>/ref/page.png",
|
|
3948
|
+
details: "Exports each rebuilt section at layout bounds, composites transparent areas over its ancestor backdrop, writes triptychs to <dir>/out/parity/, and exits 1 if any section exceeds --max-mismatch.",
|
|
3949
|
+
examples: ["figdriver import parity ./landing --max-mismatch 2"],
|
|
3950
|
+
run: ([dir], { flags, say }) => runImportParityCommand(dir, flags, say)
|
|
3951
|
+
},
|
|
3952
|
+
plugin: {
|
|
3953
|
+
kind: "leaf",
|
|
3954
|
+
args: "<dir> [--json]",
|
|
3955
|
+
most: 1,
|
|
3956
|
+
flags: ["json"],
|
|
3957
|
+
summary: "Bundle <dir> to an offline script and Figma development plugin",
|
|
3958
|
+
details: "Bundles <dir>/index.ts to <dir>/out/<folder>.js and <dir>/out/plugin/ without executing it locally.",
|
|
3959
|
+
examples: ["figdriver import plugin ./landing"],
|
|
3960
|
+
run: ([typed]) => runImportPlugin(typed)
|
|
3961
|
+
}
|
|
3962
|
+
}
|
|
3963
|
+
}
|
|
3964
|
+
};
|
|
3965
|
+
var HIDDEN = {
|
|
3966
|
+
tree: {
|
|
3967
|
+
kind: "leaf",
|
|
3968
|
+
args: `${FILE} [--wait]`,
|
|
3969
|
+
most: 0,
|
|
3970
|
+
flags: ["file", "wait"],
|
|
3971
|
+
summary: "Print figdriver-built output as stable JSON for engine diffing",
|
|
3972
|
+
details: "Internal engine-pinning helper used by scripts/pin.ts.",
|
|
3973
|
+
run: (_, { flags }) => runTree(flags)
|
|
3974
|
+
}
|
|
3975
|
+
};
|
|
3976
|
+
var ENTRIES = new Map([...Object.entries(COMMANDS), ...Object.entries(HIDDEN)]);
|
|
3977
|
+
function resolveCommand([top = "", sub = ""]) {
|
|
3978
|
+
const entry = ENTRIES.get(top);
|
|
3979
|
+
if (entry?.kind !== "group") return { name: top, leaf: entry };
|
|
3980
|
+
const leaf = new Map(Object.entries(entry.subcommands)).get(sub);
|
|
3981
|
+
return { name: leaf ? `${top} ${sub}` : top, group: entry, leaf };
|
|
3982
|
+
}
|
|
3983
|
+
var ROOT_SECTIONS = [
|
|
3984
|
+
["Connect", ["browser", "doctor"]],
|
|
3985
|
+
["Read & Tokens", ["find", "inspect", "tokens"]],
|
|
3986
|
+
["Edit & Verify", ["eval", "export", "parity", "audit"]],
|
|
3987
|
+
["Web-to-Figma", ["import"]]
|
|
3988
|
+
];
|
|
3989
|
+
function formatLeaf(fullName, leaf) {
|
|
3990
|
+
const lines = [`Usage: figdriver ${fullName}${leaf.args ? ` ${leaf.args}` : ""}`, "", leaf.details];
|
|
3991
|
+
if (leaf.writes) lines.push("", leaf.writes);
|
|
3992
|
+
if (leaf.examples?.length) {
|
|
3993
|
+
lines.push("", "Examples:", ...leaf.examples.map((ex) => ` ${ex}`));
|
|
3994
|
+
}
|
|
3995
|
+
return lines.join("\n");
|
|
3996
|
+
}
|
|
3997
|
+
function formatGroup(name, group) {
|
|
3998
|
+
const subs = Object.entries(group.subcommands);
|
|
3999
|
+
const pad = Math.max(...subs.map(([k]) => k.length)) + 2;
|
|
4000
|
+
return [
|
|
4001
|
+
`Usage: figdriver ${name} <subcommand> [options]`,
|
|
4002
|
+
"",
|
|
4003
|
+
group.details,
|
|
4004
|
+
"",
|
|
4005
|
+
"Subcommands:",
|
|
4006
|
+
...subs.map(([sub, leaf]) => ` ${sub.padEnd(pad)}${leaf.summary}`),
|
|
4007
|
+
"",
|
|
4008
|
+
`Run \`figdriver ${name} <subcommand> --help\` for flags and examples.`
|
|
4009
|
+
].join("\n");
|
|
4010
|
+
}
|
|
4011
|
+
function usage(path = []) {
|
|
4012
|
+
const { name, group, leaf } = resolveCommand(path);
|
|
4013
|
+
if (leaf) return formatLeaf(name, leaf);
|
|
4014
|
+
if (group) return formatGroup(name, group);
|
|
4015
|
+
const pad = Math.max(...Object.keys(COMMANDS).map((k) => k.length)) + 2;
|
|
4016
|
+
const sections = ROOT_SECTIONS.flatMap(([title, names]) => [
|
|
4017
|
+
title,
|
|
4018
|
+
...names.map((n) => ` ${n.padEnd(pad)}${COMMANDS[n].summary}`),
|
|
4019
|
+
""
|
|
4020
|
+
]);
|
|
4021
|
+
return [
|
|
4022
|
+
`figdriver ${VERSION}. Usage: figdriver <command> [options] | --version (-v) | --help (-h)`,
|
|
4023
|
+
"Run `figdriver <command> --help` for flags, defaults, and examples.",
|
|
4024
|
+
"",
|
|
4025
|
+
...sections,
|
|
4026
|
+
"Global flags (where supported): --file <url|key> (or FIGDRIVER_FILE), --wait, --json.",
|
|
4027
|
+
"Write commands (`eval` without --read-only, `tokens import` without --dry-run, `import run`) require --file or FIGDRIVER_FILE.",
|
|
4028
|
+
"Node ids accept 1:23, 1-23, or a Figma layer URL with ?node-id=... .",
|
|
4029
|
+
"Environment: FIGDRIVER_FILE, CDP_PORT (default 9333), FIGDRIVER_BROWSER (Chromium path or 'playwright').",
|
|
4030
|
+
`--json prints one JSON object on stdout (typed in ${resolve6(import.meta.dirname, "../cli/result.ts")}) and sends logs to stderr. Exit 0 means ok: true.`
|
|
4031
|
+
].join("\n");
|
|
4032
|
+
}
|
|
4033
|
+
var emit = process.stdout.write.bind(process.stdout);
|
|
4034
|
+
function fail(command, message) {
|
|
4035
|
+
if (process.argv.includes("--json"))
|
|
4036
|
+
emit(`${JSON.stringify({ command, ok: false, error: message })}
|
|
4037
|
+
`);
|
|
4038
|
+
else console.error(`error: ${message}`);
|
|
4039
|
+
process.exit(1);
|
|
4040
|
+
}
|
|
4041
|
+
function parse2() {
|
|
4042
|
+
try {
|
|
4043
|
+
return parseArgs({
|
|
4044
|
+
args: process.argv.slice(2),
|
|
4045
|
+
allowPositionals: true,
|
|
4046
|
+
options: OPTIONS
|
|
4047
|
+
});
|
|
4048
|
+
} catch (e) {
|
|
4049
|
+
const { name } = resolveCommand(process.argv.slice(2).filter((a) => !a.startsWith("-")));
|
|
4050
|
+
fail(name, `${messageOf(e)}. Run \`figdriver ${name ? `${name} ` : ""}--help\`.`);
|
|
4051
|
+
}
|
|
4052
|
+
}
|
|
4053
|
+
async function main() {
|
|
4054
|
+
const { values, positionals } = parse2();
|
|
4055
|
+
const [name, ...rest] = positionals;
|
|
4056
|
+
if (values.json) {
|
|
4057
|
+
console.log = console.info = console.debug = console.error;
|
|
4058
|
+
process.stdout.write = process.stderr.write.bind(process.stderr);
|
|
4059
|
+
process.on("uncaughtException", (e) => fail(name ?? "", e.message));
|
|
4060
|
+
}
|
|
4061
|
+
if (values.help && values.json) fail(name ?? "", "--help prints text for people. Run it without --json.");
|
|
4062
|
+
if (values.version && !name) {
|
|
4063
|
+
if (values.json)
|
|
4064
|
+
emit(
|
|
4065
|
+
`${JSON.stringify({ command: "version", ok: true, version: VERSION, warnings: [], files: [] })}
|
|
4066
|
+
`
|
|
4067
|
+
);
|
|
4068
|
+
else console.log(VERSION);
|
|
4069
|
+
process.exit(0);
|
|
4070
|
+
}
|
|
4071
|
+
if (!name) {
|
|
4072
|
+
if (values.json) fail("", "Name a command. Run `figdriver --help`.");
|
|
4073
|
+
console.log(usage());
|
|
4074
|
+
process.exit(0);
|
|
4075
|
+
}
|
|
4076
|
+
const { name: fullName, group, leaf } = resolveCommand(positionals);
|
|
4077
|
+
const [sub] = rest;
|
|
4078
|
+
if (values.help || group && !sub && !values.json) {
|
|
4079
|
+
console.log(usage(positionals));
|
|
4080
|
+
process.exit(0);
|
|
4081
|
+
}
|
|
4082
|
+
if (!leaf) {
|
|
4083
|
+
if (!group) fail(name, `Unknown command "${name}". Commands: ${Object.keys(COMMANDS).join(", ")}.`);
|
|
4084
|
+
const subs = Object.keys(group.subcommands).join(", ");
|
|
4085
|
+
fail(
|
|
4086
|
+
name,
|
|
4087
|
+
sub ? `Unknown subcommand "${name} ${sub}". Subcommands: ${subs}.` : `Choose a ${name} subcommand: ${subs}.`
|
|
4088
|
+
);
|
|
4089
|
+
}
|
|
4090
|
+
const args = group ? rest.slice(1) : rest;
|
|
4091
|
+
const stray = Object.keys(values).find((flag) => !leaf.flags.some((f) => f === flag));
|
|
4092
|
+
if (stray) fail(fullName, `${fullName} takes no --${stray}. Run \`figdriver ${fullName} --help\`.`);
|
|
4093
|
+
if (args.length > leaf.most) {
|
|
4094
|
+
fail(
|
|
4095
|
+
fullName,
|
|
4096
|
+
`${fullName} takes ${leaf.most ? `at most ${leaf.most} argument${leaf.most > 1 ? "s" : ""}` : "no arguments"}, and got ${args.length}: ${args.map((a) => JSON.stringify(a)).join(" ")}. Run \`figdriver ${fullName} --help\`.`
|
|
4097
|
+
);
|
|
4098
|
+
}
|
|
4099
|
+
for (const [flag, [form, valid]] of VALUES) {
|
|
4100
|
+
const value = values[flag];
|
|
4101
|
+
if (value !== void 0 && !valid(value)) fail(fullName, `--${flag} takes ${form}, not "${value}".`);
|
|
4102
|
+
}
|
|
4103
|
+
const say = (line) => (values.json ? console.error : console.log)(line);
|
|
4104
|
+
try {
|
|
4105
|
+
const result = await leaf.run(args, { flags: values, say });
|
|
4106
|
+
if (result && values.json) emit(`${JSON.stringify(result, null, 2)}
|
|
4107
|
+
`);
|
|
4108
|
+
if (result && !result.ok) process.exitCode = 1;
|
|
4109
|
+
} catch (e) {
|
|
4110
|
+
if (!(e instanceof Problem) && !values.json) throw e;
|
|
4111
|
+
fail(fullName, messageOf(e));
|
|
4112
|
+
}
|
|
4113
|
+
}
|
|
4114
|
+
function isMain() {
|
|
4115
|
+
try {
|
|
4116
|
+
return !!process.argv[1] && realpathSync3(process.argv[1]) === realpathSync3(fileURLToPath(import.meta.url));
|
|
4117
|
+
} catch {
|
|
4118
|
+
return false;
|
|
4119
|
+
}
|
|
4120
|
+
}
|
|
4121
|
+
if (isMain()) await main();
|
|
4122
|
+
export {
|
|
4123
|
+
COMMANDS,
|
|
4124
|
+
usage
|
|
4125
|
+
};
|