sdtk-ops-kit 0.2.10 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,203 @@
1
+ #!/usr/bin/env node
2
+ // Put every non-layout material into the Framer project: pages, breakpoints,
3
+ // colour and text styles, and image assets.
4
+ //
5
+ // Dry run by default. Idempotent: reads what exists and skips it, so a re-run
6
+ // after a partial failure resumes instead of duplicating.
7
+ //
8
+ // Usage:
9
+ // node framer-scaffold.mjs # dry run
10
+ // node framer-scaffold.mjs --apply
11
+ // node framer-scaffold.mjs --apply --only=styles|pages|assets
12
+ // node framer-scaffold.mjs --apply --reupload
13
+
14
+ import fs from "node:fs";
15
+ import path from "node:path";
16
+ import { loadConfig, connectFramer } from "./lib/config.mjs";
17
+
18
+ const arg = (n, d = null) => (process.argv.find((a) => a.startsWith(`--${n}=`)) || "").split("=").slice(1).join("=") || d;
19
+ const APPLY = process.argv.includes("--apply");
20
+ const REUP = process.argv.includes("--reupload");
21
+ const ONLY = arg("only", "all");
22
+ const want = (phase) => ONLY === "all" || ONLY === phase;
23
+ const cfg = loadConfig(arg("config"));
24
+
25
+ /* ---------- colour styles, parsed from the project's own tokens ----------- */
26
+ // Parsed, never retyped. Hand-copying hex pairs into a second file is how the
27
+ // Framer project and the HTML edition silently diverge the first time either
28
+ // is touched.
29
+ function readColorTokens() {
30
+ if (!cfg.tokensFile) return [];
31
+ const css = fs.readFileSync(cfg.tokensFile, "utf8");
32
+ const block = (sel) => {
33
+ const i = css.indexOf(sel);
34
+ if (i < 0) throw new Error(`${cfg.tokensFile} has no ${sel} block`);
35
+ const open = css.indexOf("{", i), close = css.indexOf("}", open);
36
+ return css.slice(open + 1, close);
37
+ };
38
+ const vars = (text) =>
39
+ Object.fromEntries([...text.matchAll(/--([a-z-]+)\s*:\s*(#[0-9a-fA-F]{3,8})/g)].map((m) => [m[1], m[2]]));
40
+
41
+ /* Framer's model requires `light` and treats `dark` as optional. A project
42
+ whose CSS ships DARK as its default :root (common for this genre) must map
43
+ light <- its day-theme block, not the other way round: getting this
44
+ backwards yields a project whose light mode is near-black. */
45
+ const dark = vars(block(cfg.themes.dark + "{"));
46
+ const light = vars(block(cfg.themes.light));
47
+ const names = Object.keys(dark);
48
+ const missing = names.filter((n) => !light[n]);
49
+ if (missing.length) throw new Error(`light theme (${cfg.themes.light}) is missing: ${missing.join(", ")}`);
50
+ return names.map((n) => ({ name: n, light: light[n], dark: dark[n] }));
51
+ }
52
+
53
+ function listAssets() {
54
+ const out = [];
55
+ for (const d of cfg.assetDirs) {
56
+ if (!fs.existsSync(d)) continue;
57
+ for (const f of fs.readdirSync(d)) {
58
+ if (!f.endsWith(cfg.assetExtension)) continue;
59
+ const full = path.join(d, f);
60
+ out.push({ name: path.basename(f, cfg.assetExtension), file: full, bytes: fs.statSync(full).size });
61
+ }
62
+ }
63
+ return out.sort((a, b) => a.name.localeCompare(b.name));
64
+ }
65
+
66
+ const colors = readColorTokens();
67
+ const assets = listAssets();
68
+
69
+ console.log(`\nFramer scaffold — ${cfg.projectName}`);
70
+ console.log(APPLY ? "MODE: apply — this writes to the live project\n" : "MODE: dry run (pass --apply to write)\n");
71
+
72
+ const framer = await connectFramer();
73
+ console.log(`project: ${(await framer.getProjectInfo()).name}\n`);
74
+
75
+ const created = { colorStyles: 0, textStyles: 0, pages: 0, breakpoints: 0, assets: 0 };
76
+ const skipped = { colorStyles: 0, textStyles: 0, pages: 0, breakpoints: 0, assets: 0 };
77
+
78
+ if (want("styles")) {
79
+ console.log("colour styles");
80
+ const byName = new Map((await framer.getColorStyles()).map((s) => [s.name, s]));
81
+ for (const c of colors) {
82
+ if (byName.has(c.name)) { console.log(` skip ${c.name.padEnd(12)} already present`); skipped.colorStyles++; continue; }
83
+ console.log(` create ${c.name.padEnd(12)} light ${c.light} dark ${c.dark}`);
84
+ if (APPLY) await framer.createColorStyle({ name: c.name, light: c.light, dark: c.dark });
85
+ created.colorStyles++;
86
+ }
87
+
88
+ console.log("\ntext styles");
89
+ /* Match on `path`, not `name`: a style called "Display/Hero" is stored with
90
+ name "Hero" and path "/Display/Hero" -- Framer reads the slash as a group,
91
+ so comparing names lets every grouped style through the check twice. */
92
+ const havePath = new Set((await framer.getTextStyles()).map((s) => s.path).filter(Boolean));
93
+ for (const t of cfg.textStyles) {
94
+ if (havePath.has("/" + t.name)) { console.log(` skip ${t.name.padEnd(22)} already present`); skipped.textStyles++; continue; }
95
+ // A missing font is reported, not swallowed: a text style silently created
96
+ // in the wrong family looks finished on the canvas.
97
+ const font = await framer.getFont(t.family, { weight: t.weight }).catch(() => null);
98
+ if (!font) { console.log(` FAIL ${t.name.padEnd(22)} font not available: ${t.family} ${t.weight}`); continue; }
99
+ console.log(` create ${t.name.padEnd(22)} ${t.family} ${t.weight} ${t.size}px`);
100
+ if (APPLY) {
101
+ await framer.createTextStyle({
102
+ name: t.name, tag: t.tag || "p", font, fontSize: t.size,
103
+ ...(t.lineHeight ? { lineHeight: t.lineHeight } : {}),
104
+ ...(t.letterSpacing ? { letterSpacing: t.letterSpacing } : {}),
105
+ ...(t.transform ? { transform: t.transform } : {}),
106
+ });
107
+ }
108
+ created.textStyles++;
109
+ }
110
+ }
111
+
112
+ if (want("pages")) {
113
+ console.log("\npages");
114
+ const existingPages = await framer.getNodesWithType("WebPageNode");
115
+ /* WebPageNode exposes `path` as a plain property; reading it through
116
+ getAttributes() returns undefined, which made this set empty on a first
117
+ run and sent createWebPage("/") at a project that already had a home
118
+ page. A fresh Framer project always ships "/". */
119
+ const byPath = new Map(existingPages.map((n) => [n.path, n]).filter(([p]) => p));
120
+ for (const p of cfg.pages) {
121
+ let page = byPath.get(p.path);
122
+ if (page) { console.log(` skip ${p.path.padEnd(12)} page already present`); skipped.pages++; }
123
+ else {
124
+ console.log(` create ${p.path.padEnd(12)} (reference: ${p.file})`);
125
+ created.pages++;
126
+ if (!APPLY) { created.breakpoints += cfg.breakpoints.length; continue; }
127
+ page = await framer.createWebPage(p.path);
128
+ }
129
+ if (!APPLY) continue;
130
+
131
+ /* Breakpoints are reconciled SEPARATELY from the page: a page that already
132
+ exists can still be missing them. "Already exists" and "already correct"
133
+ are different questions. */
134
+ const kids = await page.getChildren();
135
+ // name and width are plain properties too -- same trap as path above.
136
+ const haveBp = new Set(kids.map((k) => k.name).filter(Boolean));
137
+ const base = kids[0];
138
+ if (!base) { console.log(` no base breakpoint on ${p.path} -- add the rest by hand`); continue; }
139
+ for (const bp of cfg.breakpoints) {
140
+ if (haveBp.has(bp.name)) { skipped.breakpoints++; continue; }
141
+ // addBreakpoint lives on WebPageNode, not on `framer`, and `basedOn`
142
+ // must be an EXISTING breakpoint node. Marked @alpha.
143
+ await page.addBreakpoint(base.id, bp);
144
+ console.log(` + ${bp.name} @${bp.width}px`);
145
+ created.breakpoints++;
146
+ }
147
+ }
148
+ }
149
+
150
+ if (want("assets")) {
151
+ console.log("\nimage assets");
152
+ const totalKB = (assets.reduce((s, a) => s + a.bytes, 0) / 1024).toFixed(0);
153
+ console.log(` ${assets.length} file(s) (${cfg.assetExtension}), ${totalKB} KB total`);
154
+
155
+ /* Framer's uploader REJECTS AVIF outright ("Failed to upload file
156
+ (image/avif, N bytes)") through every input shape the SDK accepts, while
157
+ the identical WebP uploads first try. Framer re-optimises on publish, so
158
+ uploading WebP loses nothing. */
159
+ if (cfg.assetExtension === ".avif") throw new Error("Framer's uploader rejects AVIF -- point assetExtension at .webp");
160
+
161
+ /* The ledger is one plugin-data key PER IMAGE, not one JSON blob for all of
162
+ them. The blob design was tried and failed for real: setPluginData rejects
163
+ any single value over 2 kB, and CDN URLs run 60-100+ characters each. It
164
+ is also the ONLY record of those URLs -- Framer has no endpoint to list
165
+ image assets and recover them afterwards. Plugin data is NODE-scoped over
166
+ a server connection: framer.getPluginData does not exist, only
167
+ node.getPluginData, so the home page anchors it. */
168
+ const anchor = (await framer.getNodesWithType("WebPageNode")).find((n) => n.path === "/");
169
+ if (!anchor) throw new Error("no home page to anchor the asset ledger on -- run --only=pages first");
170
+ const existingKeys = await anchor.getPluginDataKeys();
171
+ const haveNames = new Set(existingKeys.filter((k) => k.startsWith(cfg.ledgerPrefix)).map((k) => k.slice(cfg.ledgerPrefix.length)));
172
+ const todo = REUP ? assets : assets.filter((a) => !haveNames.has(a.name));
173
+ skipped.assets = assets.length - todo.length;
174
+ if (skipped.assets) console.log(` ${skipped.assets} already uploaded on a previous run (ledger)`);
175
+
176
+ if (!APPLY) {
177
+ for (const a of todo.slice(0, 4)) console.log(` would upload ${a.name}`);
178
+ if (todo.length > 4) console.log(` … and ${todo.length - 4} more`);
179
+ created.assets = todo.length;
180
+ } else {
181
+ for (const a of todo) {
182
+ // uploadImage, not addImage: addImage assigns to a selection or drops the
183
+ // image on the canvas, which is layout.
184
+ const asset = await framer.uploadImage({
185
+ name: a.name,
186
+ image: { type: "bytes", bytes: fs.readFileSync(a.file), mimeType: `image/${cfg.assetExtension.replace(".", "")}` },
187
+ });
188
+ // Written immediately, not batched: a run that dies at image 30 must not
189
+ // start again from image 1, and there is no size ceiling to batch around.
190
+ await anchor.setPluginData(cfg.ledgerPrefix + a.name, asset.url);
191
+ created.assets++;
192
+ if (created.assets % 8 === 0) console.log(` uploaded ${created.assets}/${todo.length}`);
193
+ }
194
+ if (todo.length) console.log(` uploaded ${created.assets}/${todo.length}`);
195
+ }
196
+ }
197
+
198
+ console.log("\n─────────────────────────────────────────────");
199
+ for (const k of Object.keys(created)) {
200
+ console.log(` ${k.padEnd(14)} ${APPLY ? "created" : "would create"} ${String(created[k]).padStart(3)} skipped ${skipped[k]}`);
201
+ }
202
+ console.log(APPLY ? "\nNext: framer-extract.mjs, then framer-install.mjs, then framer-place.mjs." : "\nDry run only. Re-run with --apply to write.");
203
+ process.exit(0);
@@ -0,0 +1,138 @@
1
+ #!/usr/bin/env node
2
+ // Does each generated component render what its page renders?
3
+ //
4
+ // THE RISK THIS EXISTS TO CATCH
5
+ //
6
+ // framer-extract.mjs decides which CSS rules belong to a section by testing
7
+ // selectors. A rule it misses does not throw -- it produces a component that
8
+ // looks structurally right and is quietly missing a colour, a grid, or a whole
9
+ // layout mode. Source review cannot see that. Pixels can. Every extractor bug
10
+ // this skill documents was found here, not by reading the output.
11
+ //
12
+ // METHOD
13
+ //
14
+ // Render each component's CSS + markup ALONE on a bare page carrying nothing
15
+ // the real page provides -- no reset, no tokens, no fonts beyond what the
16
+ // component itself pulls in -- and compare geometry against the same section
17
+ // in context. On a Framer canvas it gets exactly this much help.
18
+ //
19
+ // Asset markers resolve to the LOCAL build for this check: it is about
20
+ // geometry, not about whether a CDN is reachable, and a broken <img> reserves
21
+ // different space than a loaded one -- so an unresolved marker would corrupt
22
+ // every measurement around it rather than merely skipping the image.
23
+ //
24
+ // Usage:
25
+ // node framer-verify.mjs [--config=path] [--write-diffs]
26
+
27
+ import { chromium } from "playwright-core";
28
+ import fs from "node:fs";
29
+ import path from "node:path";
30
+ import { loadConfig, serveDir, resolveChrome } 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 WRITE = process.argv.includes("--write-diffs");
34
+ const cfg = loadConfig(arg("config"));
35
+ const COMPONENTS = path.resolve(arg("out", cfg.outDir));
36
+ const SHOTS = path.join(COMPONENTS, "..", "diff");
37
+ const PORT = Number(process.env.VERIFY_PORT || 8632);
38
+
39
+ /* Read CSS and markup back out of the generated .tsx. Reading the emitted file
40
+ rather than re-running the extractor is deliberate: this verifies THE
41
+ ARTEFACT THAT SHIPS, not the intent that produced it. */
42
+ function parseComponent(file, assetResolver) {
43
+ const src = fs.readFileSync(file, "utf8");
44
+ const css = src.match(/const CSS = `([\s\S]*?)`\n/);
45
+ const html = src.match(/const markup = `([\s\S]*?)`\n/);
46
+ if (!css || !html) throw new Error(`${path.basename(file)}: could not find CSS/markup literals`);
47
+ const unesc = (s) => s.replace(/\\`/g, "`").replace(/\\\$\{/g, "${").replace(/\\\\/g, "\\");
48
+ return { css: unesc(css[1]), html: unesc(html[1]).replace(/%%ASSET:([^%]+)%%/g, (m, n) => assetResolver(n)) };
49
+ }
50
+
51
+ /* Where an asset name lives in the LOCAL build. Searched across the configured
52
+ asset dirs so the check does not care how they are nested. */
53
+ const assetIndex = new Map();
54
+ for (const dir of cfg.assetDirs) {
55
+ if (!fs.existsSync(dir)) continue;
56
+ for (const f of fs.readdirSync(dir)) {
57
+ if (f.endsWith(cfg.assetExtension)) assetIndex.set(path.basename(f, cfg.assetExtension), path.join(dir, f));
58
+ }
59
+ }
60
+ const resolveAsset = (name) => {
61
+ const abs = assetIndex.get(name);
62
+ if (!abs) return `%%MISSING:${name}%%`;
63
+ return "/" + path.relative(cfg.serveRoot, abs).split(path.sep).join("/");
64
+ };
65
+
66
+ const server = await serveDir(cfg.serveRoot, PORT);
67
+ const browser = await chromium.launch({ executablePath: resolveChrome(cfg), args: ["--no-sandbox"] });
68
+ if (WRITE) fs.mkdirSync(SHOTS, { recursive: true });
69
+
70
+ const ref = await browser.newPage({ viewport: cfg.viewport });
71
+ let refPage = null;
72
+ async function loadRefPage(file) {
73
+ if (refPage === file) return;
74
+ const rel = path.relative(cfg.serveRoot, path.join(cfg.buildDir, file)).split(path.sep).join("/");
75
+ await ref.goto(`http://localhost:${PORT}/${rel}`, { waitUntil: "networkidle", timeout: 40000 });
76
+ await ref.evaluate(async () => {
77
+ for (let y = 0; y < document.body.scrollHeight; y += 400) { window.scrollTo(0, y); await new Promise((r) => setTimeout(r, 22)); }
78
+ window.scrollTo(0, 0); await new Promise((r) => setTimeout(r, 500));
79
+ });
80
+ refPage = file;
81
+ }
82
+
83
+ let failed = 0, checked = 0;
84
+ for (const p of cfg.pages) {
85
+ for (const s of p.sections || []) {
86
+ if (s.skipVerify) continue; // components carrying real JS behaviour verify separately
87
+ const file = path.join(COMPONENTS, `${s.component}.tsx`);
88
+ if (!fs.existsSync(file)) { console.log(` FAIL ${s.component.padEnd(22)} not generated`); failed++; continue; }
89
+ const { css, html } = parseComponent(file, resolveAsset);
90
+
91
+ await loadRefPage(p.file);
92
+ const refBox = await ref.locator(s.selector).boundingBox();
93
+ if (!refBox) { console.log(` FAIL ${s.component.padEnd(22)} selector ${s.selector} not found on ${p.file}`); failed++; continue; }
94
+
95
+ server.extra.set(`/bare-${s.component}.html`, `<!doctype html><html><head><meta charset="utf-8">
96
+ <style>html,body{margin:0;padding:0}</style>
97
+ <style>${css}</style></head>
98
+ <body><div class="${s.id}-scope">${html}</div></body></html>`);
99
+
100
+ const bare = await browser.newPage({ viewport: cfg.viewport });
101
+ const errs = [];
102
+ bare.on("pageerror", (e) => errs.push(String(e).slice(0, 90)));
103
+ // A 404 is a failure, not a warning: an image that does not load is a
104
+ // component that will render broken on someone else's canvas.
105
+ bare.on("response", (res) => { if (res.status() >= 400) errs.push(`${res.status()} ${res.url().split("/").pop()}`); });
106
+ await bare.goto(`http://localhost:${PORT}/bare-${s.component}.html`, { waitUntil: "networkidle", timeout: 30000 });
107
+ await bare.waitForTimeout(500);
108
+
109
+ const el = bare.locator(`.${s.id}-scope > *`).first();
110
+ const box = await el.boundingBox();
111
+ const dw = box ? Math.abs(box.width - refBox.width) : 9999;
112
+ const dh = box ? Math.abs(box.height - refBox.height) / refBox.height : 1;
113
+
114
+ /* Tolerance is per-component and declared, never loosened globally. The
115
+ legitimate reason it is ever needed: a page's own build may embed a
116
+ LOCAL variable font that Framer cannot serve, so components substitute
117
+ a hosted family whose letterforms are a different width -- real text
118
+ reflow, not a bug, and only some content is sensitive enough to show
119
+ it. Anything else exceeding 4% is a real defect. */
120
+ const limit = cfg.verifyTolerance[s.component] ?? 0.04;
121
+ const ok = dw <= 2 && dh <= limit && errs.length === 0;
122
+ if (!ok) failed++;
123
+ checked++;
124
+ console.log(` ${ok ? "PASS" : "FAIL"} ${s.component.padEnd(22)} ref ${String(Math.round(refBox.width)).padStart(4)}x${String(Math.round(refBox.height)).padStart(5)} bare ${String(Math.round(box?.width ?? 0)).padStart(4)}x${String(Math.round(box?.height ?? 0)).padStart(5)} Δh ${(dh * 100).toFixed(1)}%${limit !== 0.04 ? ` (limit ${(limit * 100).toFixed(0)}%)` : ""} ${errs.length} err`);
125
+ errs.slice(0, 2).forEach((e) => console.log(` ${e}`));
126
+
127
+ if (WRITE) {
128
+ fs.writeFileSync(path.join(SHOTS, `${s.component}.ref.png`), await ref.locator(s.selector).screenshot());
129
+ fs.writeFileSync(path.join(SHOTS, `${s.component}.bare.png`), await el.screenshot());
130
+ }
131
+ await bare.close();
132
+ }
133
+ }
134
+
135
+ await browser.close();
136
+ server.close();
137
+ console.log(failed ? `\n${failed} of ${checked} component(s) failed` : `\nall ${checked} components render standalone at their page's own geometry`);
138
+ process.exit(failed ? 1 : 0);
@@ -0,0 +1,163 @@
1
+ // Config + credential loading shared by every framer-*.mjs script.
2
+ //
3
+ // Everything project-specific lives in framer-deploy.config.json; the scripts
4
+ // themselves carry no template's page list, selectors, component names or
5
+ // asset paths. That split is the whole reason this skill is reusable: the
6
+ // first project it was extracted from had all of that hardcoded, and moving
7
+ // it into a declared config is what turned five bespoke scripts into five
8
+ // generic ones.
9
+
10
+ import fs from "node:fs";
11
+ import path from "node:path";
12
+ import os from "node:os";
13
+
14
+ export const DEFAULT_CONFIG_NAME = "framer-deploy.config.json";
15
+
16
+ /**
17
+ * Read framer-deploy.config.json, resolve its paths against its own location,
18
+ * and fail loudly on anything missing rather than half-running.
19
+ */
20
+ export function loadConfig(explicitPath) {
21
+ const file = path.resolve(explicitPath || findUpwards(process.cwd(), DEFAULT_CONFIG_NAME) || DEFAULT_CONFIG_NAME);
22
+ if (!fs.existsSync(file)) {
23
+ throw new Error(`no ${DEFAULT_CONFIG_NAME} found (looked up from ${process.cwd()}) -- copy framer-deploy.config.example.json and edit it`);
24
+ }
25
+ let cfg;
26
+ try { cfg = JSON.parse(fs.readFileSync(file, "utf8")); }
27
+ catch (e) { throw new Error(`${file} is not valid JSON: ${e.message}`); }
28
+
29
+ const root = path.dirname(file);
30
+ const req = (key) => {
31
+ if (cfg[key] === undefined || cfg[key] === null) throw new Error(`${file}: missing required key "${key}"`);
32
+ return cfg[key];
33
+ };
34
+
35
+ const resolved = {
36
+ file,
37
+ root,
38
+ projectName: cfg.projectName || path.basename(root),
39
+ /* Where the built HTML lives, and where the server that serves it should
40
+ be rooted. serveRoot matters when a page references assets by a path
41
+ relative to the repo rather than to the page. */
42
+ buildDir: path.resolve(root, req("buildDir")),
43
+ serveRoot: path.resolve(root, cfg.serveRoot || req("buildDir")),
44
+ outDir: path.resolve(root, cfg.outDir || "components"),
45
+ /* Prefix for the per-image plugin-data keys that record uploaded asset
46
+ URLs. MUST be unique per project inside one Framer project, and MUST
47
+ NOT be changed afterwards without re-uploading -- the ledger is the only
48
+ record of those URLs (Framer has no list-images endpoint). */
49
+ ledgerPrefix: cfg.ledgerPrefix || `${slug(cfg.projectName || path.basename(root))}.asset.`,
50
+ assetDirs: (cfg.assetDirs || []).map((d) => path.resolve(root, d)),
51
+ assetExtension: cfg.assetExtension || ".webp",
52
+ tokensFile: cfg.tokensFile ? path.resolve(root, cfg.tokensFile) : null,
53
+ themes: cfg.themes || { light: '[data-theme="day"]', dark: ":root" },
54
+ fontSubstitutions: cfg.fontSubstitutions || {},
55
+ fontImport: cfg.fontImport || null,
56
+ textStyles: cfg.textStyles || [],
57
+ breakpoints: cfg.breakpoints || [
58
+ { name: "Tablet", width: 810, viewportHeight: 1080 },
59
+ { name: "Phone", width: 390, viewportHeight: 844 },
60
+ ],
61
+ pages: req("pages"),
62
+ chrome: cfg.chrome || process.env.SDTK_CHROME || null,
63
+ viewport: cfg.viewport || { width: 1440, height: 900 },
64
+ verifyTolerance: cfg.verifyTolerance || {},
65
+ };
66
+
67
+ if (!Array.isArray(resolved.pages) || !resolved.pages.length)
68
+ throw new Error(`${file}: "pages" must be a non-empty array`);
69
+ for (const p of resolved.pages) {
70
+ if (!p.file) throw new Error(`${file}: every page needs "file" (e.g. "index.html")`);
71
+ if (!p.path) throw new Error(`${file}: page ${p.file} needs "path" (its Framer route, e.g. "/docs")`);
72
+ for (const s of p.sections || []) {
73
+ if (!s.id || !s.selector || !s.component)
74
+ throw new Error(`${file}: every section needs "id", "selector" and "component" (page ${p.file})`);
75
+ }
76
+ }
77
+ return resolved;
78
+ }
79
+
80
+ /** Page entry by its built filename, e.g. "docs.html". */
81
+ export function pageByFile(cfg, file) {
82
+ const p = cfg.pages.find((x) => x.file === file);
83
+ if (!p) throw new Error(`no page with file "${file}" in ${cfg.file} -- have: ${cfg.pages.map((x) => x.file).join(", ")}`);
84
+ return p;
85
+ }
86
+
87
+ /**
88
+ * Credentials, never from argv and never printed. ~/.sdtk/framer.env must be
89
+ * chmod 600 and define FRAMER_API_KEY and FRAMER_PROJECT_URL.
90
+ */
91
+ export function loadCredentials() {
92
+ const file = process.env.FRAMER_ENV_FILE || path.join(os.homedir(), ".sdtk/framer.env");
93
+ if (!fs.existsSync(file)) throw new Error(`missing ${file} -- see the skill's SKILL.md for the required contents`);
94
+ const mode = fs.statSync(file).mode & 0o777;
95
+ if (mode & 0o077) throw new Error(`${file} is mode ${mode.toString(8)}; expected 600 (chmod 600 it -- it holds an API key)`);
96
+ const env = Object.fromEntries(
97
+ fs.readFileSync(file, "utf8").split("\n").filter((l) => l.includes("=")).map((l) => {
98
+ const i = l.indexOf("=");
99
+ return [l.slice(0, i).trim(), l.slice(i + 1).trim()];
100
+ })
101
+ );
102
+ for (const k of ["FRAMER_API_KEY", "FRAMER_PROJECT_URL"]) {
103
+ if (!env[k]) throw new Error(`${file} must define ${k}`);
104
+ }
105
+ return env;
106
+ }
107
+
108
+ /** Connect, with the SDK imported lazily so --help style runs need no network. */
109
+ export async function connectFramer() {
110
+ const env = loadCredentials();
111
+ const { connect } = await import("framer-api");
112
+ return connect(env.FRAMER_PROJECT_URL, env.FRAMER_API_KEY);
113
+ }
114
+
115
+ /** A tiny static file server rooted at one directory; returns { port, close }. */
116
+ export async function serveDir(rootDir, port) {
117
+ const http = await import("node:http");
118
+ const MIME = {
119
+ ".html": "text/html", ".js": "text/javascript", ".css": "text/css", ".json": "application/json",
120
+ ".avif": "image/avif", ".webp": "image/webp", ".png": "image/png", ".jpg": "image/jpeg",
121
+ ".svg": "image/svg+xml", ".woff2": "font/woff2", ".woff": "font/woff",
122
+ };
123
+ const extra = new Map();
124
+ const srv = http.createServer((q, s) => {
125
+ const url = decodeURIComponent(q.url.split("?")[0]);
126
+ if (extra.has(url)) { s.writeHead(200, { "content-type": "text/html" }); return s.end(extra.get(url)); }
127
+ let f = path.join(rootDir, url);
128
+ try { if (fs.statSync(f).isDirectory()) f = path.join(f, "index.html"); } catch {}
129
+ if (!fs.existsSync(f)) { s.writeHead(404); return s.end("not found"); }
130
+ s.writeHead(200, { "content-type": MIME[path.extname(f)] || "application/octet-stream" });
131
+ s.end(fs.readFileSync(f));
132
+ });
133
+ await new Promise((r) => srv.listen(port, r));
134
+ return { port, extra, close: () => srv.close() };
135
+ }
136
+
137
+ /** Resolve a Chromium binary, preferring config, then env, then Playwright's. */
138
+ export function resolveChrome(cfg) {
139
+ if (cfg.chrome) return cfg.chrome;
140
+ const base = "/root/.cache/ms-playwright";
141
+ if (fs.existsSync(base)) {
142
+ const dir = fs.readdirSync(base).filter((d) => d.startsWith("chromium-")).sort().reverse()[0];
143
+ if (dir) {
144
+ const p = path.join(base, dir, "chrome-linux64", "chrome");
145
+ if (fs.existsSync(p)) return p;
146
+ }
147
+ }
148
+ throw new Error('no Chromium found -- set "chrome" in the config or SDTK_CHROME in the environment');
149
+ }
150
+
151
+ function slug(s) { return String(s).toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, ""); }
152
+
153
+ function findUpwards(from, name) {
154
+ let dir = from;
155
+ for (let i = 0; i < 8; i++) {
156
+ const candidate = path.join(dir, name);
157
+ if (fs.existsSync(candidate)) return candidate;
158
+ const parent = path.dirname(dir);
159
+ if (parent === dir) break;
160
+ dir = parent;
161
+ }
162
+ return null;
163
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "sdtk-ops-kit",
3
- "version": "0.2.10",
3
+ "version": "0.3.0",
4
4
  "description": "Skill-driven operations toolkit for deployment, verification, monitoring, incident response, backup, security, compliance, and cost discipline.",
5
5
  "bin": {
6
6
  "sdtk-ops": "bin/sdtk-ops.js"
package/src/lib/scope.js CHANGED
@@ -14,6 +14,7 @@ const MANAGED_CLAUDE_SKILLS = [
14
14
  "ops-debug",
15
15
  "ops-deploy",
16
16
  "ops-discover",
17
+ "ops-framer-deploy",
17
18
  "ops-incident",
18
19
  "ops-infra-plan",
19
20
  "ops-monitor",