sdtk-ops-kit 0.2.10 → 0.3.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,309 @@
1
+ #!/usr/bin/env node
2
+ // Turn sections of a built HTML page into Framer code components.
3
+ //
4
+ // WHAT THIS IS FOR
5
+ //
6
+ // Framer's node model has no <table>, no :nth-child, no color-mix() and no
7
+ // radio-driven tabs. Any section leaning on those cannot be rebuilt as Framer
8
+ // nodes without becoming a worse version of itself. Extracting it as a code
9
+ // component keeps exactly what was designed and measured.
10
+ //
11
+ // HOW THE CSS IS CHOSEN -- and the two bugs that shaped it
12
+ //
13
+ // Not by judging which rules "look related". The page is loaded in a real
14
+ // browser and every rule in every stylesheet is tested with matches().
15
+ //
16
+ // 1. ANCESTOR RULES COUNT TOO. body{color:...} and its font-family live on
17
+ // <body>, outside the section's subtree. Testing only descendants drops
18
+ // every inherited property: measured, on the first version of this,
19
+ // color rgb(0,0,0) against the page's rgb(244,240,233), and "Times New
20
+ // Roman" against the real body face. Nothing errored -- it rendered
21
+ // wrong. Ancestor rules are re-aimed at the wrapper.
22
+ //
23
+ // 2. SELECTOR SPLITTING MUST RESPECT PARENTHESES. Splitting selectorText on
24
+ // every comma shreds :is(a, b, c), :not(), :where() and
25
+ // :nth-child(n of .x) into fragments meaning something else.
26
+ //
27
+ // Both are the same category: no error, plausible output, wrong result.
28
+ // framer-verify.mjs exists because of them.
29
+ //
30
+ // Usage:
31
+ // node framer-extract.mjs --page=index.html [--config=path] [--out=dir]
32
+
33
+ import { chromium } from "playwright-core";
34
+ import fs from "node:fs";
35
+ import path from "node:path";
36
+ import { loadConfig, pageByFile, serveDir, resolveChrome } from "./lib/config.mjs";
37
+
38
+ const arg = (n, d = null) => (process.argv.find((a) => a.startsWith(`--${n}=`)) || "").split("=").slice(1).join("=") || d;
39
+ const cfg = loadConfig(arg("config"));
40
+ const pageFile = arg("page", cfg.pages[0].file);
41
+ const spec = pageByFile(cfg, pageFile);
42
+ const OUT = path.resolve(arg("out", cfg.outDir));
43
+ const PORT = Number(process.env.EXTRACT_PORT || 8631);
44
+
45
+ if (!(spec.sections || []).length) { console.log(`page ${pageFile} declares no sections -- nothing to extract`); process.exit(0); }
46
+ const built = path.join(cfg.buildDir, pageFile);
47
+ if (!fs.existsSync(built)) throw new Error(`no build at ${built} -- build the HTML first`);
48
+ fs.mkdirSync(OUT, { recursive: true });
49
+
50
+ const server = await serveDir(cfg.serveRoot, PORT);
51
+ const rel = path.relative(cfg.serveRoot, built).split(path.sep).join("/");
52
+ const browser = await chromium.launch({ executablePath: resolveChrome(cfg), args: ["--no-sandbox"] });
53
+ const page = await browser.newPage({ viewport: cfg.viewport });
54
+ await page.goto(`http://localhost:${PORT}/${rel}`, { waitUntil: "networkidle", timeout: 40000 });
55
+ // Walk the page so appear-on-scroll sections are in their resting state before
56
+ // anything is read: a section still parked at opacity 0 would export with the
57
+ // pre-reveal styles baked in.
58
+ await page.evaluate(async () => {
59
+ for (let y = 0; y < document.body.scrollHeight; y += 400) { window.scrollTo(0, y); await new Promise((r) => setTimeout(r, 22)); }
60
+ window.scrollTo(0, 0); await new Promise((r) => setTimeout(r, 500));
61
+ });
62
+
63
+ const results = await page.evaluate(({ sections, assetExt }) => {
64
+ const out = [];
65
+ const rootStyle = getComputedStyle(document.documentElement);
66
+ const tokenNames = [];
67
+ for (const sheet of document.styleSheets) {
68
+ let rules; try { rules = sheet.cssRules; } catch { continue; }
69
+ for (const r of rules) {
70
+ if (r.type !== CSSRule.STYLE_RULE) continue;
71
+ if (!/^:root\b/.test(r.selectorText || "")) continue;
72
+ for (const p of r.style) if (p.startsWith("--")) tokenNames.push(p);
73
+ }
74
+ }
75
+ const tokens = {};
76
+ for (const n of [...new Set(tokenNames)]) tokens[n] = rootStyle.getPropertyValue(n).trim();
77
+
78
+ for (const S of sections) {
79
+ const root = document.querySelector(S.selector);
80
+ if (!root) { out.push({ ...S, error: `selector ${S.selector} matched nothing` }); continue; }
81
+ const nodes = [root, ...root.querySelectorAll("*")];
82
+ const ancestors = [];
83
+ for (let n = root.parentElement; n; n = n.parentElement) ancestors.push(n);
84
+ ancestors.push(document.documentElement);
85
+
86
+ const splitTop = (sel) => {
87
+ const parts = []; let depth = 0, cur = "";
88
+ for (const ch of sel) {
89
+ if (ch === "(" || ch === "[") depth++;
90
+ else if (ch === ")" || ch === "]") depth--;
91
+ if (ch === "," && depth === 0) { parts.push(cur); cur = ""; continue; }
92
+ cur += ch;
93
+ }
94
+ if (cur.trim()) parts.push(cur);
95
+ return parts;
96
+ };
97
+ const scopeSel = (selText) =>
98
+ splitTop(selText).map((s) => {
99
+ const t = s.trim();
100
+ if (/^(:root|html|body)\b/.test(t)) return t.replace(/^(:root|html|body)/, "&");
101
+ return `& ${t}`;
102
+ }).join(", ");
103
+
104
+ const matched = [];
105
+ const lossy = [];
106
+ let tested = 0, kept = 0;
107
+ const walk = (rules, into) => {
108
+ for (const r of rules) {
109
+ if (r.type === CSSRule.STYLE_RULE) {
110
+ tested++;
111
+ let hit = false, viaAncestor = false;
112
+ try { hit = nodes.some((n) => n.matches(r.selectorText)); } catch { hit = false; }
113
+ if (!hit) {
114
+ try { viaAncestor = ancestors.some((n) => n.matches(r.selectorText)); } catch { viaAncestor = false; }
115
+ hit = viaAncestor;
116
+ }
117
+ if (!hit) {
118
+ const cls = (r.selectorText || "").match(/\.[A-Za-z_][-\w]*/g) || [];
119
+ hit = cls.length > 0 && cls.every((c) => nodes.some((n) => n.classList && n.classList.contains(c.slice(1))));
120
+ }
121
+ if (hit) {
122
+ kept++;
123
+ /* `r.style.cssText` is CSSOM's serialization, and it is LOSSY for one
124
+ shape: a shorthand whose value contains var() and whose longhands
125
+ are then partly overridden inside the same rule. The override makes
126
+ the shorthand unserializable, and the var()-bearing longhands are
127
+ pending-substitution values, which serialize as the EMPTY STRING:
128
+
129
+ .grad{ background: linear-gradient(..., var(--ink), ...);
130
+ background-clip: text; color: transparent; }
131
+
132
+ becomes `background-image: ; background-position-x: ; ...
133
+ background-clip: text; color: transparent;` -- eight declarations
134
+ the parser drops on the way back in, leaving transparent text with
135
+ nothing painted behind it. The SOURCE page renders fine (it uses
136
+ the parsed rule), so this is invisible until you look at what
137
+ shipped. It cost four live pages a missing word in the headline.
138
+
139
+ CSSOM will not hand the value back -- getPropertyValue() on the
140
+ shorthand returns "" too -- but the AUTHOR's text is still there:
141
+ these are inline <style> nodes, so ownerNode.textContent is the
142
+ source CSS verbatim, var() references intact and still
143
+ theme-switchable. So recover the rule body from that, and keep
144
+ failing the run only for the cases recovery cannot reach (a
145
+ cross-origin or constructed sheet, a selector the matcher cannot
146
+ find). Recovery is the fix; the failure is the net under it. */
147
+ const declBody = () => {
148
+ const decls = r.style.cssText;
149
+ if (!/([-\w]+):\s*(;|$)/.test(decls)) return decls;
150
+ const raw = r.parentStyleSheet?.ownerNode?.textContent;
151
+ if (raw) {
152
+ const sel = (r.selectorText || "").split(",").map((x) =>
153
+ x.trim().replace(/[.*+?^${}()|[\]\\]/g, "\\$&").replace(/\s+/g, "\\s+")).join("\\s*,\\s*");
154
+ const m = raw.match(new RegExp("(?:^|[^-\\w.#%])" + sel + "\\s*\\{([^}]*)\\}"));
155
+ if (m) return m[1].trim();
156
+ }
157
+ lossy.push({ sel: r.selectorText, props: (decls.match(/[-\w]+(?=:\s*(?:;|$))/g) || []) });
158
+ return decls;
159
+ };
160
+ into.push((viaAncestor ? "&" : scopeSel(r.selectorText)) + "{" + declBody() + "}");
161
+ }
162
+ } else if (r.type === CSSRule.MEDIA_RULE) {
163
+ const inner = []; walk(r.cssRules, inner);
164
+ if (inner.length) into.push("@media " + r.conditionText + "{" + inner.join("") + "}");
165
+ } else if (r.type === CSSRule.SUPPORTS_RULE) {
166
+ const inner = []; walk(r.cssRules, inner);
167
+ if (inner.length) into.push("@supports " + r.conditionText + "{" + inner.join("") + "}");
168
+ } else if (r.type === CSSRule.KEYFRAMES_RULE) {
169
+ into.push(r.cssText);
170
+ }
171
+ }
172
+ };
173
+ for (const sheet of document.styleSheets) {
174
+ let rules; try { rules = sheet.cssRules; } catch { continue; }
175
+ walk(rules, matched);
176
+ }
177
+
178
+ /* Drop <source> variants in formats that will not be uploaded. Framer's
179
+ uploader rejects AVIF, so an AVIF <source> points at an asset that does
180
+ not exist there -- and a <picture> does NOT fall back to <img> just
181
+ because the source it already chose 404s, so this is a broken image for
182
+ exactly the browsers modern enough to prefer AVIF. Cloned so the live
183
+ page, read again by the next section in this pass, is untouched. */
184
+ const clone = root.cloneNode(true);
185
+ const keep = assetExt.replace(".", "");
186
+ clone.querySelectorAll("picture > source").forEach((el) => {
187
+ const type = el.getAttribute("type") || "";
188
+ if (!type.includes(keep)) el.remove();
189
+ });
190
+
191
+ out.push({
192
+ ...S,
193
+ html: clone.outerHTML,
194
+ css: matched.join("\n"),
195
+ tokens,
196
+ lossy,
197
+ stats: { elements: nodes.length, rulesTested: tested, rulesKept: kept,
198
+ imgs: root.querySelectorAll("img").length, svgs: root.querySelectorAll("svg").length },
199
+ });
200
+ }
201
+ return out;
202
+ }, { sections: spec.sections, assetExt: cfg.assetExtension });
203
+
204
+ await browser.close();
205
+ server.close();
206
+
207
+ const esc = (s) => s.replace(/\\/g, "\\\\").replace(/`/g, "\\`").replace(/\$\{/g, "\\${");
208
+ const assetRe = new RegExp('src="(?:\\./)?[^"]*?([^"/]+)\\' + cfg.assetExtension + '"', "g");
209
+
210
+ let failed = 0;
211
+ for (const r of results) {
212
+ if (r.error) { console.log(` FAIL ${r.id.padEnd(12)} ${r.error}`); failed++; continue; }
213
+
214
+ /* Every image src becomes a marker rather than a path. Framer hosts uploaded
215
+ images at a random per-asset CDN URL with no folder structure a prefix
216
+ could reconstruct -- there is no "base URL" that turns "assets/foo.webp"
217
+ into the right address. framer-install.mjs resolves each marker to the
218
+ exact URL uploadImage() returned for that name. */
219
+ const html = r.html.replace(assetRe, (m, name) => 'src="%%ASSET:' + name + '%%"');
220
+
221
+ /* Font substitution carries !important for a reason that cost a live bug:
222
+ the ancestor :root rule kept above ALSO defines these custom properties,
223
+ is emitted later in this same stylesheet, and at equal specificity
224
+ silently overwrote the substitution back to the page's local @font-face
225
+ names -- which Framer cannot serve. Symptom on the live site: computed
226
+ font-family still read the local name and document.fonts was EMPTY, so
227
+ every component had been rendering in the browser's bare ui-serif /
228
+ ui-sans-serif fallback. Nothing looked broken, which is why it survived
229
+ several rounds of review. */
230
+ const tokenCss = Object.entries(r.tokens)
231
+ .map(([k, v]) => (cfg.fontSubstitutions[k] ? ` ${k}: ${cfg.fontSubstitutions[k]} !important;` : ` ${k}: ${v};`))
232
+ .join("\n");
233
+
234
+ const tsx = `// ${r.title || r.component} — generated Framer code component.
235
+ //
236
+ // GENERATED FILE — do not edit by hand.
237
+ // Source: ${pageFile} ${r.selector}
238
+ // Regenerate: node framer-extract.mjs --page=${pageFile}
239
+ //
240
+ // Markup and CSS are lifted from the built page rather than rewritten, so what
241
+ // renders here is what that page's own checks measured: ${r.stats.elements} elements,
242
+ // ${r.stats.rulesKept} CSS rules kept of ${r.stats.rulesTested} tested.
243
+
244
+ const CSS = \`${cfg.fontImport ? cfg.fontImport + "\n" : ""}
245
+ .${r.id}-scope {
246
+ ${tokenCss}
247
+ display: block;
248
+ width: 100%;
249
+ /* Framer writes BOTH of these onto this same element through props.style,
250
+ and both break content the page's CSS never expected to be constrained:
251
+ overflow -- the instance's Overflow setting (Visible/Hidden/Scroll),
252
+ which resizing a frame is an ordinary way to switch on. It
253
+ clips any position:absolute dropdown AND adds a scrollbar.
254
+ isolation -- makes this div its own stacking context regardless of
255
+ z-index, so nothing inside can ever paint above a LATER
256
+ placed instance. Measured live: elementFromPoint() inside
257
+ an open dropdown returned the NEXT section's element.
258
+ A plain inline style beats any stylesheet rule except an !important one,
259
+ which is why both are forced back here. */
260
+ overflow: visible !important;
261
+ isolation: auto !important;
262
+ }
263
+ ${esc(r.css).replace(/&/g, "." + r.id + "-scope")}
264
+ \`
265
+
266
+ /**
267
+ * @framerIntrinsicWidth ${cfg.viewport.width}
268
+ * @framerIntrinsicHeight ${Math.max(200, r.stats.elements * 6)}
269
+ * @framerSupportedLayoutWidth any-prefer-fixed
270
+ * @framerSupportedLayoutHeight auto
271
+ */
272
+ export default function ${r.component}(props) {
273
+ // Image URLs are resolved at install time, not here: by the time this code
274
+ // reaches Framer every asset marker below has been replaced with a real
275
+ // absolute CDN URL. Committed copies still show the raw markers.
276
+ const markup = \`${esc(html)}\`
277
+ return (
278
+ <div className="${r.id}-scope" style={props.style}>
279
+ <style>{CSS}</style>
280
+ <div dangerouslySetInnerHTML={{ __html: markup }} />
281
+ </div>
282
+ )
283
+ }
284
+ `;
285
+ const file = path.join(OUT, `${r.component}.tsx`);
286
+ fs.writeFileSync(file, tsx);
287
+ const kb = (fs.statSync(file).size / 1024).toFixed(0);
288
+ console.log(` ${r.component.padEnd(22)} ${String(r.stats.elements).padStart(4)} el ${String(r.stats.rulesKept).padStart(3)}/${String(r.stats.rulesTested).padEnd(4)} rules ${String(r.stats.imgs).padStart(2)} img ${String(r.stats.svgs).padStart(2)} svg ${kb.padStart(4)} KB`);
289
+ }
290
+
291
+ /* Fail-closed, not a warning: a rule whose serialization lost its values ships
292
+ a component that looks almost right, which is the shape that survives review. */
293
+ const lossyRules = new Map();
294
+ for (const r of results) for (const l of r.lossy || []) {
295
+ if (!lossyRules.has(l.sel)) lossyRules.set(l.sel, new Set());
296
+ for (const prop of l.props) lossyRules.get(l.sel).add(prop);
297
+ }
298
+ if (lossyRules.size) {
299
+ console.log("\nFAIL CSSOM dropped declaration values while serializing these rules:");
300
+ for (const [sel, props] of lossyRules)
301
+ console.log(` ${sel} -> ${[...props].join(", ")} (emitted with empty values)`);
302
+ console.log(" Cause: a shorthand containing var() whose longhands are partly");
303
+ console.log(" overridden in the same rule. Rewrite it in the source CSS as longhands.");
304
+ failed++;
305
+ }
306
+
307
+ console.log(`\n${results.length - failed} component(s) from ${pageFile} -> ${OUT}`);
308
+ if (spec.wire?.length) console.log(`NEXT: this page declares wiring (${spec.wire.join(", ")}) -- run those now, or the behaviour they add is silently missing.`);
309
+ process.exit(failed ? 1 : 0);
@@ -0,0 +1,96 @@
1
+ #!/usr/bin/env node
2
+ // Install generated components into the Framer project, resolving asset
3
+ // markers to real URLs on the way in, then make Framer itself check them.
4
+ //
5
+ // WHY MARKERS AND NOT A BASE URL
6
+ //
7
+ // An earlier design shipped a runtime "assetBase" property control and left
8
+ // "${BASE}assets/foo.webp" in the markup. It never worked: nothing ever
9
+ // substituted the value, so every <img src> rendered those literal characters
10
+ // as a URL, and the control sat in the panel looking configurable while doing
11
+ // nothing. Even had it substituted, there is no base URL that could work --
12
+ // Framer hosts each image at a random per-asset hash with no relationship to
13
+ // the original filename.
14
+ //
15
+ // So markers are resolved HERE, against the ledger framer-scaffold.mjs wrote,
16
+ // and what ships is a real absolute URL baked into the component. A marker
17
+ // with no ledger entry STOPS that component's install rather than uploading
18
+ // something whose <img src> is the literal text of an unresolved marker.
19
+ //
20
+ // Re-install replaces file content in place, so component instances already
21
+ // placed on a page keep pointing at the same file. Remove-and-recreate would
22
+ // break every instance a layout step had positioned.
23
+ //
24
+ // Usage:
25
+ // node framer-install.mjs # dry run
26
+ // node framer-install.mjs --apply
27
+
28
+ import fs from "node:fs";
29
+ import path from "node:path";
30
+ import { loadConfig, connectFramer } from "./lib/config.mjs";
31
+
32
+ const arg = (n, d = null) => (process.argv.find((a) => a.startsWith(`--${n}=`)) || "").split("=").slice(1).join("=") || d;
33
+ const APPLY = process.argv.includes("--apply");
34
+ const cfg = loadConfig(arg("config"));
35
+ const COMPONENTS = path.resolve(arg("out", cfg.outDir));
36
+
37
+ if (!fs.existsSync(COMPONENTS)) throw new Error(`no components at ${COMPONENTS} -- run framer-extract.mjs first`);
38
+ const files = fs.readdirSync(COMPONENTS).filter((f) => f.endsWith(".tsx")).sort();
39
+ if (!files.length) throw new Error(`no .tsx files in ${COMPONENTS}`);
40
+
41
+ console.log(`\nFramer components — ${cfg.projectName}`);
42
+ console.log(APPLY ? "MODE: apply\n" : "MODE: dry run (pass --apply to write)\n");
43
+
44
+ const framer = await connectFramer();
45
+ console.log(`project: ${(await framer.getProjectInfo()).name}\n`);
46
+
47
+ const anchor = (await framer.getNodesWithType("WebPageNode")).find((n) => n.path === "/");
48
+ if (!anchor) throw new Error("no home page to read the asset ledger from -- run framer-scaffold.mjs --apply first");
49
+ const ledgerKeys = (await anchor.getPluginDataKeys()).filter((k) => k.startsWith(cfg.ledgerPrefix));
50
+ const assetUrls = Object.fromEntries(
51
+ await Promise.all(ledgerKeys.map(async (k) => [k.slice(cfg.ledgerPrefix.length), await anchor.getPluginData(k)]))
52
+ );
53
+ console.log(`asset ledger: ${Object.keys(assetUrls).length} image(s) with a known URL\n`);
54
+
55
+ const existing = new Map((await framer.getCodeFiles()).map((f) => [f.name, f]));
56
+ let failed = 0;
57
+
58
+ for (const f of files) {
59
+ let code = fs.readFileSync(path.join(COMPONENTS, f), "utf8");
60
+
61
+ const missing = new Set();
62
+ code = code.replace(/%%ASSET:([^%]+)%%/g, (m, name) => {
63
+ if (!assetUrls[name]) { missing.add(name); return m; }
64
+ return assetUrls[name];
65
+ });
66
+ if (missing.size) {
67
+ failed++;
68
+ console.log(` SKIP ${f.padEnd(24)} ${missing.size} unresolved marker(s): ${[...missing].slice(0, 3).join(", ")}${missing.size > 3 ? "…" : ""}`);
69
+ console.log(` run: node framer-scaffold.mjs --apply --only=assets`);
70
+ continue;
71
+ }
72
+
73
+ const kb = (Buffer.byteLength(code) / 1024).toFixed(0);
74
+ const already = existing.get(f);
75
+ if (!APPLY) { console.log(` ${already ? "would replace" : "would create "} ${f.padEnd(24)} ${kb.padStart(3)} KB`); continue; }
76
+
77
+ if (already) { await already.setFileContent(code); console.log(` replaced ${f.padEnd(24)} ${kb.padStart(3)} KB`); }
78
+ else { await framer.createCodeFile(f, code); console.log(` created ${f.padEnd(24)} ${kb.padStart(3)} KB`); }
79
+
80
+ // Framer's own lint and typecheck, not a local tsc: what matters is whether
81
+ // the project accepts it.
82
+ const lint = await framer.lintCode?.(code).catch((e) => ({ error: String(e).slice(0, 90) }));
83
+ const tc = await framer.typecheckCode?.(code).catch((e) => ({ error: String(e).slice(0, 90) }));
84
+ const diags = [...(lint?.diagnostics ?? []), ...(tc?.diagnostics ?? [])];
85
+ const errors = diags.filter((d) => (d.severity ?? "error") === "error");
86
+ if (errors.length) {
87
+ failed++;
88
+ console.log(` ${errors.length} error(s):`);
89
+ for (const d of errors.slice(0, 3)) console.log(` ${(d.message || JSON.stringify(d)).slice(0, 110)}`);
90
+ } else {
91
+ console.log(` lint + typecheck clean${diags.length ? ` (${diags.length} warning(s))` : ""}`);
92
+ }
93
+ }
94
+
95
+ console.log(failed ? `\n${failed} component(s) reported errors` : `\n${files.length} component(s) installed and clean`);
96
+ process.exit(failed ? 1 : 0);
@@ -0,0 +1,134 @@
1
+ #!/usr/bin/env node
2
+ // Place every component instance onto its page, in document order.
3
+ //
4
+ // THIS STEP IS NOT MANUAL, DESPITE HOW IT LOOKS
5
+ //
6
+ // Framer's Agent API (startAgentConversation and siblings) is NOT reachable
7
+ // over a `connect(projectUrl, apiKey)` session -- probed, all of it. That
8
+ // means there is no way to hand Framer a prose brief and have it DESIGN a
9
+ // page. It does NOT mean instances cannot be placed: that has a documented
10
+ // API, and it is the whole of this script.
11
+ //
12
+ // CodeFile.exports[].insertURL "URL that can be used with
13
+ // addComponentInstance to insert this
14
+ // export onto the canvas"
15
+ // framer.addComponentInstance({ url, parentId, attributes })
16
+ //
17
+ // The order placed is the page's own document order, declared in the config --
18
+ // no design decision is being made here.
19
+ //
20
+ // BREAKPOINTS: PLACE ONCE, NOT ONCE PER BREAKPOINT
21
+ //
22
+ // Verified, not assumed: a single addComponentInstance into the base (widest)
23
+ // frame leaves every smaller breakpoint reporting the same child, because they
24
+ // inherit from the base. Placing per breakpoint produces N copies of
25
+ // everything.
26
+ //
27
+ // THE API LIMITATION THIS WORKS AROUND
28
+ //
29
+ // `parentId` is @alpha and only resolves nodes created in the SAME session. A
30
+ // breakpoint frame read back from a page that already existed is rejected with
31
+ // "Assertion Error: Parent node not found: <id>" -- even though that id
32
+ // appears in getNodesWithType("FrameNode"); framer.getNode() on it returns
33
+ // undefined, and enumerating every frame first to "load" them does not help
34
+ // (all three checked). So a page whose layout is EMPTY is deleted and
35
+ // re-created in-session before placing, breakpoints re-added.
36
+ //
37
+ // That is safe only because of the guard in front of it: content is counted
38
+ // across every breakpoint, and a page with anything arranged on it is SKIPPED.
39
+ // Running this cannot throw away a hand-built layout.
40
+ //
41
+ // Usage:
42
+ // node framer-place.mjs # dry run
43
+ // node framer-place.mjs --apply
44
+ // node framer-place.mjs --apply --page=/docs
45
+ // node framer-place.mjs --apply --replace # rebuild pages that have content
46
+
47
+ import path from "node:path";
48
+ import { loadConfig, connectFramer } from "./lib/config.mjs";
49
+
50
+ const arg = (n, d = null) => (process.argv.find((a) => a.startsWith(`--${n}=`)) || "").split("=").slice(1).join("=") || d;
51
+ const APPLY = process.argv.includes("--apply");
52
+ const REPLACE = process.argv.includes("--replace");
53
+ const ONLY = arg("page");
54
+ const cfg = loadConfig(arg("config"));
55
+
56
+ console.log(`\nFramer instance placement — ${cfg.projectName}`);
57
+ console.log(APPLY ? `MODE: apply${REPLACE ? " (--replace: rebuilding pages that already have content)" : ""}\n` : "MODE: dry run (pass --apply to write)\n");
58
+
59
+ const framer = await connectFramer();
60
+ console.log(`project: ${(await framer.getProjectInfo()).name}\n`);
61
+
62
+ /* insertURL per component, read from the project rather than stored: these
63
+ URLs carry a version hash that changes every time a code file is replaced,
64
+ so a cached copy goes stale silently. */
65
+ const urlByName = new Map();
66
+ for (const f of await framer.getCodeFiles()) {
67
+ const exp = (f.exports || []).find((e) => e.type === "component");
68
+ if (exp) urlByName.set(path.basename(f.name, ".tsx"), exp.insertURL);
69
+ }
70
+ console.log(`${urlByName.size} component(s) available to place\n`);
71
+
72
+ const pageByPath = new Map((await framer.getNodesWithType("WebPageNode")).map((p) => [p.path, p]));
73
+ let placed = 0, skipped = 0, failed = 0;
74
+
75
+ for (const spec of cfg.pages) {
76
+ const order = spec.place || (spec.sections || []).map((s) => s.component);
77
+ if (!order.length) continue;
78
+ if (ONLY && spec.path !== ONLY) continue;
79
+
80
+ const page = pageByPath.get(spec.path);
81
+ if (!page) { console.log(` FAIL ${spec.path.padEnd(12)} page does not exist -- run framer-scaffold.mjs --apply first`); failed++; continue; }
82
+
83
+ const frames = await page.getChildren();
84
+ if (!frames.length) { console.log(` FAIL ${spec.path.padEnd(12)} page has no breakpoint frame`); failed++; continue; }
85
+
86
+ /* Count content across EVERY breakpoint: a page is only safe to re-create if
87
+ nothing has been arranged on any of them. */
88
+ const contentCount = (await Promise.all(frames.map(async (f) => (await f.getChildren()).length))).reduce((a, b) => a + b, 0);
89
+ if (contentCount && !REPLACE) {
90
+ console.log(` skip ${spec.path.padEnd(12)} already has ${contentCount} node(s) placed -- pass --replace to rebuild`);
91
+ skipped++;
92
+ continue;
93
+ }
94
+
95
+ const missing = order.filter((n) => !urlByName.has(n));
96
+ if (missing.length) { console.log(` FAIL ${spec.path.padEnd(12)} not installed: ${missing.join(", ")} -- run framer-install.mjs --apply`); failed++; continue; }
97
+
98
+ console.log(` ${spec.path.padEnd(12)} ${order.length} component(s)${contentCount ? `, replacing ${contentCount} existing` : ""}`);
99
+ if (!APPLY) { order.forEach((n, i) => console.log(` ${String(i + 1).padStart(2)}. ${n}`)); placed += order.length; continue; }
100
+
101
+ // Re-create in-session so the frames are addressable as parentId.
102
+ await framer.removeNode(page.id);
103
+ const fresh = await framer.createWebPage(spec.path);
104
+ const base = (await fresh.getChildren())[0];
105
+ for (const bp of cfg.breakpoints) await fresh.addBreakpoint(base.id, bp);
106
+
107
+ /* Vertical stack, so sections flow top to bottom the way the source page
108
+ does instead of piling at one absolute origin. Set BEFORE the children go
109
+ in -- a frame switched to stack afterwards has to relayout everything
110
+ already inside it. */
111
+ await base.setAttributes({ layout: "stack", stackDirection: "vertical", stackDistribution: "start", stackAlignment: "center" })
112
+ .catch((e) => console.log(` note: could not set stack layout (${String(e?.message || e).slice(0, 70)})`));
113
+
114
+ for (const name of order) {
115
+ const attributes = { width: "100%" };
116
+ const controls = spec.controls?.[name];
117
+ if (controls) attributes.controls = controls;
118
+ try {
119
+ await framer.addComponentInstance({ url: urlByName.get(name), parentId: base.id, attributes });
120
+ console.log(` + ${name}${controls ? ` (${Object.entries(controls).map(([k, v]) => `${k}=${v}`).join(", ")})` : ""}`);
121
+ placed++;
122
+ } catch (e) {
123
+ console.log(` FAIL ${name}: ${String(e?.message || e).split("\n")[0].slice(0, 140)}`);
124
+ failed++;
125
+ }
126
+ }
127
+ }
128
+
129
+ console.log("\n─────────────────────────────────────────────");
130
+ console.log(` ${APPLY ? "placed" : "would place"} ${placed} skipped pages ${skipped} failed ${failed}`);
131
+ console.log(APPLY
132
+ ? "\nPublish from the Framer editor to put this on the live URL -- placing\ninstances through the API does not deploy them."
133
+ : "\nDry run only. Re-run with --apply to write.");
134
+ process.exit(failed ? 1 : 0);