astro-loupe 0.1.0 → 0.2.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/integration.mjs CHANGED
@@ -23,6 +23,14 @@ const packed = fs.existsSync(path.join(here, "builder", "build.mjs"));
23
23
  const BUILDER = packed ? path.join(here, "builder") : path.resolve(here, "../builder/src");
24
24
  const DEFAULT_RUNTIME = packed ? path.join(here, "runtime") : path.resolve(here, "../dist/runtime");
25
25
 
26
+ // The builder (build, slugOf, findKicadCli), loaded on first use. The setup page (starlight/setup.mjs) uses it too.
27
+ export const loadBuilder = async () => {
28
+ const load = (f) => import(pathToFileURL(path.join(BUILDER, f)).href);
29
+ const [{ build }, { slugOf }, { findKicadCli }] = await Promise.all([load("build.mjs"), load("package.mjs"), load("tools.mjs")]);
30
+ return { build, slugOf, findKicadCli };
31
+ };
32
+ export const RUNTIME_DIR = DEFAULT_RUNTIME;
33
+
26
34
  export default function loupe({ boards = [], runtime = DEFAULT_RUNTIME, boardsDir = "boards", runtimeDir = "loupe" } = {}) {
27
35
  return {
28
36
  name: "loupe",
@@ -83,7 +91,7 @@ function inputHash(projectDir, opts) {
83
91
  }
84
92
 
85
93
  async function buildBoards(boards, { root, out, cache, logger }) {
86
- const { build } = await import(pathToFileURL(path.join(BUILDER, "build.mjs")).href);
94
+ const { build } = await loadBuilder();
87
95
  let seen = {};
88
96
  try { seen = JSON.parse(fs.readFileSync(cache, "utf8")); } catch {}
89
97
  const next = {}, slugs = [];
@@ -92,6 +100,7 @@ async function buildBoards(boards, { root, out, cache, logger }) {
92
100
  const dir = fs.statSync(project).isDirectory() ? project : path.dirname(project);
93
101
  const opts = { ...b };
94
102
  delete opts.project;
103
+ delete opts.example; // loupe.json marks the template's example board (the setup page offers to remove it)
95
104
  const hash = inputHash(dir, opts);
96
105
  const slug = b.slug ?? path.basename(project, ".kicad_pro").toLowerCase().replace(/[^a-z0-9]+/g, "-");
97
106
  if (seen[slug] === hash && fs.existsSync(path.join(out, slug, "manifest.json"))) { next[slug] = hash; slugs.push(slug); continue; }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "astro-loupe",
3
- "version": "0.1.0",
3
+ "version": "0.2.0",
4
4
  "description": "Show a KiCad board on an Astro site as linked schematic, PCB, 3D and BOM views: an integration that builds your KiCad projects into static board packages, <Board>/<PartLink> components and a Starlight plugin. Offline.",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -1,8 +1,8 @@
1
1
  {
2
2
  "upstream": "c37404bcd756ce67712981a715d904b1efc9f69e",
3
- "fork": "874211f",
3
+ "fork": "de39342",
4
4
  "dirty": false,
5
- "builtAt": "2026-11-29T16:50:43Z",
5
+ "builtAt": "2026-11-29T17:57:31Z",
6
6
  "files": [
7
7
  "THIRD_PARTY_NOTICES.txt",
8
8
  "ecad_viewer/3d-viewer.js",
@@ -37,7 +37,12 @@ if (board) {
37
37
  }
38
38
  ---
39
39
  <div class="loupe-sl-cols" data-board={board ?? undefined}>
40
- <div class="main-pane"><slot /></div>
40
+ <div class="main-pane">
41
+ {cfg.example && (
42
+ <p class="loupe-sl-setup">This site still shows the example board. <a href={cfg.setupUrl}>Set up your own board →</a> <span>(only while <code>npm run dev</code> runs; the published site never shows this)</span></p>
43
+ )}
44
+ <slot />
45
+ </div>
41
46
  {board && (
42
47
  <aside class="loupe-sl-board-col" transition:persist={`loupe-sl-board-${board}`} data-click={cfg.partClick} aria-label="Board">
43
48
  <button type="button" class="loupe-sl-toggle" aria-expanded="true">Board</button>
@@ -154,6 +159,13 @@ if (board) {
154
159
  .loupe-sl-toggle { display: none; }
155
160
  }
156
161
 
162
+ /* Dev only, while the example board is there (the setup page, setup.mjs). */
163
+ .loupe-sl-setup {
164
+ margin: 1rem var(--sl-content-pad-x, 1rem) 0; padding: 0.6rem 0.9rem; border-radius: 0.5rem; font-size: var(--sl-text-sm);
165
+ background: var(--sl-color-accent-low); border: 1px solid var(--sl-color-accent); color: var(--sl-color-white);
166
+ }
167
+ .loupe-sl-setup a { font-weight: 600; }
168
+ .loupe-sl-setup span { color: var(--sl-color-gray-3); }
157
169
  :global(.loupe-sl-summary) { margin: 0 0 0.5rem; }
158
170
  :global(.loupe-sl-more) { font-weight: 600; }
159
171
  </style>
@@ -19,11 +19,14 @@
19
19
  import { fileURLToPath } from "node:url";
20
20
  import { install } from "../integration.mjs";
21
21
  import { loadBoard, sidebarGroup } from "./data.mjs";
22
+ import path from "node:path";
22
23
 
23
24
  const VIRTUAL = "virtual:loupe/config";
24
25
  const CLICKS = ["group", "stay"];
25
26
 
26
- export default function loupe({ boards = [], partClick = "group", runtime, boardsDir = "boards", runtimeDir = "loupe" } = {}) {
27
+ // setup: the site's settings file (the Loupe template's "loupe.json"). With it, `astro dev` serves the setup page at
28
+ // <base>setup/ (setup.mjs) and restarts when the file changes; builds never include the page.
29
+ export default function loupe({ boards = [], partClick = "group", runtime, boardsDir = "boards", runtimeDir = "loupe", setup = null } = {}) {
27
30
  if (!CLICKS.includes(partClick)) {
28
31
  throw new Error(`loupe: partClick must be "group" or "stay", not ${JSON.stringify(partClick)}` +
29
32
  (["inspector", "page"].includes(partClick) ? " (part pages were replaced by group pages: decisions D20)" : ""));
@@ -31,7 +34,7 @@ export default function loupe({ boards = [], partClick = "group", runtime, board
31
34
  return {
32
35
  name: "loupe",
33
36
  hooks: {
34
- "config:setup": async ({ config, updateConfig, addIntegration, astroConfig, logger }) => {
37
+ "config:setup": async ({ config, updateConfig, addIntegration, astroConfig, logger, command }) => {
35
38
  const slugs = await install(astroConfig, { boards, runtime, boardsDir, runtimeDir }, logger);
36
39
  const publicDir = fileURLToPath(astroConfig.publicDir);
37
40
  const root = fileURLToPath(astroConfig.root);
@@ -47,11 +50,14 @@ export default function loupe({ boards = [], partClick = "group", runtime, board
47
50
  // base: the site's base path with a trailing slash ("/" or "/demo/loupe/"). Page links get it here; sidebar links
48
51
  // don't need it (Starlight adds it).
49
52
  const base = (astroConfig.base || "/").replace(/\/?$/, "/");
50
- const settings = { boards: slugs, defaultBoard: slugs[0] ?? null, boardsDir, runtimeDir, partClick, publicDir, base };
53
+ const setupUrl = setup && command === "dev" ? `${base}setup/` : null;
54
+ const settings = { boards: slugs, defaultBoard: slugs[0] ?? null, boardsDir, runtimeDir, partClick, publicDir, base,
55
+ setupUrl, example: setupUrl && boards.some((b) => b.example) };
51
56
  addIntegration({
52
57
  name: "loupe-routes",
53
58
  hooks: {
54
- "astro:config:setup": ({ injectRoute, updateConfig: updateAstro }) => {
59
+ "astro:config:setup": ({ injectRoute, updateConfig: updateAstro, addWatchFile }) => {
60
+ if (setupUrl) addWatchFile(path.resolve(root, setup));
55
61
  injectRoute({ pattern: "/[board]/", entrypoint: "astro-loupe/starlight/BoardPage.astro" });
56
62
  injectRoute({ pattern: "/[board]/[group]/", entrypoint: "astro-loupe/starlight/GroupPage.astro" });
57
63
  updateAstro({
@@ -67,6 +73,15 @@ export default function loupe({ boards = [], partClick = "group", runtime, board
67
73
  },
68
74
  });
69
75
  },
76
+ // Dev only (Astro runs this hook for `astro dev` alone): the setup page and its local endpoints.
77
+ "astro:server:setup": async ({ server }) => {
78
+ if (!setupUrl) return;
79
+ const { setupMiddleware } = await import("./setup.mjs");
80
+ server.middlewares.use(setupMiddleware({ root, configFile: setup, base, logger }));
81
+ },
82
+ "astro:server:start": ({ address }) => {
83
+ if (setupUrl) logger.info(`setup page: http://${address.family === "IPv6" ? `[${address.address}]` : address.address}:${address.port}${setupUrl}`);
84
+ },
70
85
  },
71
86
  });
72
87
  logger.info(`loupe: ${data.map((d) => `${d.slug} (${d.groups.length} group pages)`).join(", ") || "no boards"}`);
@@ -0,0 +1,105 @@
1
+ <!doctype html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="utf-8">
5
+ <meta name="viewport" content="width=device-width, initial-scale=1">
6
+ <meta http-equiv="Content-Security-Policy" content="default-src 'self'; style-src 'self'; script-src 'self'; img-src 'self' data: blob:; connect-src 'self'">
7
+ <title>Set up your board · Loupe</title>
8
+ <link rel="stylesheet" href="%BASE%setup/setup.css">
9
+ <script type="module" src="%BASE%setup/setup.js" data-base="%BASE%"></script>
10
+ </head>
11
+ <body>
12
+ <main>
13
+ <header>
14
+ <h1>Set up your board</h1>
15
+ <p class="muted">This page runs only on your computer, while <code>npm run dev</code> is running. It copies your
16
+ KiCad project into this site's folder and writes the site's settings; it never appears on the published site,
17
+ and nothing you drop leaves your computer.</p>
18
+ </header>
19
+
20
+ <section id="add" aria-labelledby="add-h">
21
+ <h2 id="add-h"><span class="step">1</span> Add your board</h2>
22
+ <p>Save your work in KiCad, then drop your project's folder here: the one with the <code>.kicad_pro</code> file.</p>
23
+ <div id="drop" class="drop" tabindex="0">
24
+ <p><strong>Drop the project folder here</strong></p>
25
+ <p class="muted">or</p>
26
+ <p>
27
+ <label class="btn">Choose folder…<input type="file" id="folder" webkitdirectory multiple></label>
28
+ <label class="btn quiet">Choose files…<input type="file" id="files" multiple accept=".kicad_pro,.kicad_sch,.kicad_pcb"></label>
29
+ </p>
30
+ <p class="muted small">Only KiCad files, 3D models, the licence and <code>web/</code> are copied. Backups and lock
31
+ files are left out.</p>
32
+ </div>
33
+ <p id="status" class="status" role="status" aria-live="polite"></p>
34
+ <p id="error" class="error" role="alert" hidden></p>
35
+
36
+ <form id="review" hidden>
37
+ <div class="card">
38
+ <h3 id="r-title"></h3>
39
+ <p id="r-stats" class="muted"></p>
40
+ <h4>Its pages</h4>
41
+ <p class="muted small">One page per titled box in your schematic (a rectangle with a text in its top-left corner,
42
+ or a text box), otherwise one per sheet. Not what you meant? Draw or rename boxes in KiCad, save, and drop the
43
+ folder again.</p>
44
+ <ul id="r-groups" class="groups"></ul>
45
+ <div id="r-warn" hidden><h4>Worth a look</h4><ul id="r-warnings" class="warnings"></ul></div>
46
+ </div>
47
+
48
+ <label class="field">Site title <input id="f-title" required></label>
49
+ <label class="field">One line about it <input id="f-desc" placeholder="What the board is, for search results and link previews"></label>
50
+ <label class="field">URL name <input id="f-slug" required pattern="[a-z0-9][a-z0-9\-]*" spellcheck="false">
51
+ <span class="muted small">The board's pages live at <code>/<span id="f-slug-echo"></span>/</code>.</span></label>
52
+ <label class="check" id="c-example-row"><input type="checkbox" id="c-example" checked>
53
+ <span>Remove the example board (<span id="c-example-name"></span>), its notes, and the example home page</span></label>
54
+ <label class="check" id="c-3d-row"><input type="checkbox" id="c-3d" checked>
55
+ <span id="c-3d-text"></span></label>
56
+ <p><button type="submit" class="btn primary" id="apply">Add to my site</button></p>
57
+ </form>
58
+
59
+ <div id="done" class="card ok" hidden>
60
+ <h3>Added</h3>
61
+ <ul id="d-list"></ul>
62
+ <p id="d-wait" class="muted">The site is restarting with your board…</p>
63
+ <p id="d-open" hidden><a class="btn primary" href="%BASE%">Open your site</a></p>
64
+ </div>
65
+ </section>
66
+
67
+ <section id="three" aria-labelledby="three-h">
68
+ <h2 id="three-h"><span class="step">2</span> 3D on any host</h2>
69
+ <p>The site builds the 3D view from <code>web/&lt;project&gt;.glb</code> next to each project (KiCad's 3D export),
70
+ plus <code>web/&lt;project&gt;-top.png</code> for the thumbnail. With those files committed, hosts that have no
71
+ KiCad, like Netlify or Cloudflare Pages building from your repo, still show the board in 3D.</p>
72
+ <table class="boards">
73
+ <thead><tr><th>Board</th><th>3D model</th><th>Thumbnail</th><th></th></tr></thead>
74
+ <tbody id="b-rows"></tbody>
75
+ </table>
76
+ <p id="kicad-line" class="muted small"></p>
77
+
78
+ <details>
79
+ <summary>Or export them in KiCad yourself, with the web-export jobset</summary>
80
+ <ol>
81
+ <li><a id="jobset" download="web-export.kicad_jobset">Download <code>web-export.kicad_jobset</code></a> and save
82
+ it next to your <code>.kicad_pro</code> (in <code id="jobset-dir">kicad/&lt;board&gt;/</code>).</li>
83
+ <li>In KiCad's project window, open the jobset from the project's file list and press <strong>Generate</strong>.
84
+ It writes the 3D model, the thumbnail and a PDF of the schematic into <code>web/</code>. This needs KiCad 10:
85
+ KiCad 9 may write STEP instead of GLB. With KiCad 9, use the Export button above.</li>
86
+ <li>Or from a terminal: <code>kicad-cli jobset run -f web-export.kicad_jobset &lt;project&gt;.kicad_pro</code></li>
87
+ <li>Reload this page: the table above shows what's there. Commit the <code>web/</code> folder with your site.</li>
88
+ </ol>
89
+ </details>
90
+ </section>
91
+
92
+ <section aria-labelledby="next-h">
93
+ <h2 id="next-h"><span class="step">3</span> Write, then publish</h2>
94
+ <ul>
95
+ <li>Your home page is <code>src/content/docs/index.mdx</code>. Add more pages next to it.</li>
96
+ <li>Each part of the design has a note in <code>src/content/groups/&lt;board&gt;/</code>: give it a
97
+ <code>summary:</code> and write below the <code>---</code>. The note tops that part's page.</li>
98
+ <li>When it reads well: <code>npm run build</code>, then drag the <code>dist/</code> folder onto
99
+ <a href="https://app.netlify.com/drop" rel="noreferrer" target="_blank">app.netlify.com/drop</a> (or any
100
+ static host).</li>
101
+ </ul>
102
+ </section>
103
+ </main>
104
+ </body>
105
+ </html>
@@ -0,0 +1,73 @@
1
+ /* The setup page (dev only). Its own small token set; it follows the system's light/dark setting. */
2
+ :root {
3
+ --loupe-setup-bg: #ffffff;
4
+ --loupe-setup-fg: #1d2129;
5
+ --loupe-setup-muted: #5d6472;
6
+ --loupe-setup-line: #d9dce3;
7
+ --loupe-setup-card: #f5f6f8;
8
+ --loupe-setup-accent: #2f5fd0;
9
+ --loupe-setup-accent-fg: #ffffff;
10
+ --loupe-setup-ok: #1f7a4a;
11
+ --loupe-setup-warn: #8a5a00;
12
+ --loupe-setup-error: #b42318;
13
+ --loupe-setup-font: system-ui, -apple-system, "Segoe UI", Roboto, sans-serif;
14
+ --loupe-setup-mono: ui-monospace, "Cascadia Mono", Menlo, Consolas, monospace;
15
+ --loupe-setup-radius: 8px;
16
+ color-scheme: light dark;
17
+ }
18
+ @media (prefers-color-scheme: dark) {
19
+ :root {
20
+ --loupe-setup-bg: #16181d;
21
+ --loupe-setup-fg: #e6e8ec;
22
+ --loupe-setup-muted: #9aa1ad;
23
+ --loupe-setup-line: #2e323b;
24
+ --loupe-setup-card: #1e2128;
25
+ --loupe-setup-accent: #7c9cff;
26
+ --loupe-setup-accent-fg: #0d1020;
27
+ --loupe-setup-ok: #5cc48d;
28
+ --loupe-setup-warn: #e0b050;
29
+ --loupe-setup-error: #ff8a80;
30
+ }
31
+ }
32
+ * { box-sizing: border-box; }
33
+ [hidden] { display: none !important; } /* .check and .btn set display, which would beat the attribute */
34
+ body { margin: 0; background: var(--loupe-setup-bg); color: var(--loupe-setup-fg); font: 16px/1.55 var(--loupe-setup-font); }
35
+ main { max-width: 46rem; margin: 0 auto; padding: 2rem 1.25rem 4rem; }
36
+ h1 { font-size: 1.8rem; margin: 0 0 0.5rem; }
37
+ h2 { font-size: 1.25rem; margin: 2.5rem 0 0.75rem; display: flex; align-items: center; gap: 0.6rem; }
38
+ h3 { margin: 0 0 0.25rem; font-size: 1.15rem; }
39
+ h4 { margin: 1rem 0 0.25rem; font-size: 1rem; }
40
+ code { font-family: var(--loupe-setup-mono); font-size: 0.9em; }
41
+ a { color: var(--loupe-setup-accent); }
42
+ .muted { color: var(--loupe-setup-muted); }
43
+ .small { font-size: 0.875rem; }
44
+ .step { display: inline-grid; place-items: center; width: 1.7rem; height: 1.7rem; border-radius: 50%; font-size: 0.95rem;
45
+ background: var(--loupe-setup-accent); color: var(--loupe-setup-accent-fg); }
46
+ .drop { border: 2px dashed var(--loupe-setup-line); border-radius: var(--loupe-setup-radius); padding: 1.5rem; text-align: center; }
47
+ .drop p { margin: 0.35rem 0; }
48
+ .drop[data-over] { border-color: var(--loupe-setup-accent); background: var(--loupe-setup-card); }
49
+ .btn { display: inline-block; padding: 0.45rem 0.9rem; border: 1px solid var(--loupe-setup-line); border-radius: var(--loupe-setup-radius);
50
+ background: var(--loupe-setup-card); color: var(--loupe-setup-fg); font: inherit; cursor: pointer; text-decoration: none; }
51
+ .btn.primary { background: var(--loupe-setup-accent); border-color: var(--loupe-setup-accent); color: var(--loupe-setup-accent-fg); }
52
+ .btn.quiet { background: transparent; }
53
+ .btn:disabled { opacity: 0.55; cursor: progress; }
54
+ .btn input[type="file"] { display: none; }
55
+ .status { min-height: 1.5em; color: var(--loupe-setup-muted); }
56
+ .error { color: var(--loupe-setup-error); white-space: pre-wrap; }
57
+ .card { background: var(--loupe-setup-card); border: 1px solid var(--loupe-setup-line); border-radius: var(--loupe-setup-radius); padding: 1rem 1.25rem; margin: 1rem 0; }
58
+ .card.ok h3 { color: var(--loupe-setup-ok); }
59
+ .groups { columns: 2; margin: 0.25rem 0; padding-left: 1.2rem; }
60
+ .warnings li { color: var(--loupe-setup-warn); }
61
+ .field { display: block; margin: 0.9rem 0; font-weight: 600; }
62
+ .field input { display: block; width: 100%; margin-top: 0.25rem; padding: 0.45rem 0.6rem; font: inherit; font-weight: 400;
63
+ color: var(--loupe-setup-fg); background: var(--loupe-setup-bg); border: 1px solid var(--loupe-setup-line); border-radius: var(--loupe-setup-radius); }
64
+ .field .small { font-weight: 400; }
65
+ .check { display: flex; gap: 0.6rem; align-items: flex-start; margin: 0.7rem 0; }
66
+ .check input { margin-top: 0.35rem; }
67
+ table.boards { width: 100%; border-collapse: collapse; margin: 0.5rem 0; }
68
+ .boards th, .boards td { text-align: left; padding: 0.45rem 0.4rem; border-bottom: 1px solid var(--loupe-setup-line); }
69
+ .boards .yes { color: var(--loupe-setup-ok); }
70
+ .boards .no { color: var(--loupe-setup-warn); }
71
+ details { margin-top: 1rem; }
72
+ summary { cursor: pointer; font-weight: 600; }
73
+ @media (max-width: 34rem) { .groups { columns: 1; } }
@@ -0,0 +1,191 @@
1
+ // The setup page's client (see ../setup.mjs for the server half). Reads a dropped folder, sends the project's files to
2
+ // the dev server on this computer, shows what the board will look like as a site, and applies it.
3
+ const BASE = document.currentScript?.dataset.base ?? document.querySelector("script[data-base]").dataset.base;
4
+ const API = `${BASE}_loupe/setup/`;
5
+ const $ = (id) => document.getElementById(id);
6
+ const esc = (s) => String(s ?? "").replace(/[&<>"]/g, (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;" })[c]);
7
+ // The server's filter (setup.mjs, KEEP and SKIP_DIR), so only what it would keep is sent.
8
+ const KEEP = /(\.(kicad_pro|kicad_sch|kicad_pcb|kicad_dru|kicad_sym|kicad_mod|kicad_wks|kicad_jobset|step|stp|wrl)|(^|\/)(fp|sym)-lib-table|(^|\/)(LICEN[CS]E|COPYING)[^/]*|(^|\/)web\/[^/]+\.(glb|png))$/i;
9
+ const SKIP_DIR = /^(\.git|\.svn|node_modules|\.history|.*-backups)$/;
10
+ const keep = (p) => KEEP.test(p) && !/(^|\/)(~|_autosave-)|\.lck$/.test(p) && !p.split("/").slice(0, -1).some((s) => SKIP_DIR.test(s));
11
+
12
+ const state = { site: null, session: null, review: null };
13
+ window.loupeSetup = state; // for tests
14
+
15
+ async function call(method, route, data, query = "") {
16
+ const opts = { method, headers: { "x-loupe-setup": "1" } };
17
+ if (data instanceof Blob) opts.body = data;
18
+ else if (data !== undefined) { opts.body = JSON.stringify(data); opts.headers["content-type"] = "application/json"; }
19
+ const r = await fetch(API + route + query, opts);
20
+ const json = await r.json().catch(() => ({ error: `${r.status} ${r.statusText}` }));
21
+ if (!r.ok) throw new Error(json.error || `${r.status}`);
22
+ return json;
23
+ }
24
+
25
+ const status = (t) => { $("status").textContent = t || ""; };
26
+ const error = (e) => { $("error").hidden = !e; $("error").textContent = e ? e.message || String(e) : ""; if (e) status(""); };
27
+
28
+ // ---------- the site as it is ----------
29
+
30
+ async function loadState() {
31
+ state.site = await call("GET", "state");
32
+ const { boards, kicad } = state.site;
33
+ $("b-rows").innerHTML = boards.map((b) => `<tr data-slug="${esc(b.slug)}">
34
+ <td><strong>${esc(b.slug)}</strong>${b.example ? ' <span class="muted small">(example)</span>' : ""}<br><code class="small">${esc(b.web)}/</code></td>
35
+ <td class="${b.model ? "yes" : "no"}">${b.model ? "✓ there" : "missing"}</td>
36
+ <td class="${b.thumb ? "yes" : "no"}">${b.thumb ? "✓ there" : "missing"}</td>
37
+ <td>${kicad ? `<button type="button" class="btn quiet" data-export="${esc(b.slug)}">${b.model ? "Export again" : "Export now"}</button>` : ""}</td>
38
+ </tr>`).join("") || `<tr><td colspan="4" class="muted">No boards yet: add one above.</td></tr>`;
39
+ $("kicad-line").textContent = kicad
40
+ ? `Export uses KiCad ${kicad.version} on this computer (3D needs KiCad 8 or later, the thumbnail 9 or later).`
41
+ : "No KiCad found on this computer, so this page can't export; use the KiCad steps below on a computer that has it.";
42
+ $("jobset").href = state.site.jobset;
43
+ if (boards[0]) $("jobset-dir").textContent = `${boards[0].jobsetDir}/`;
44
+ }
45
+
46
+ $("b-rows").addEventListener("click", async (e) => {
47
+ const slug = e.target.closest("[data-export]")?.dataset.export;
48
+ if (!slug) return;
49
+ e.target.disabled = true;
50
+ error(null);
51
+ status(`Exporting ${slug}'s 3D model with KiCad: this can take a minute…`);
52
+ try {
53
+ const r = await call("POST", "export", { slug });
54
+ status(r.ok ? `Exported ${slug}'s 3D model into web/. The site restarts to use it.` : "");
55
+ if (r.warnings.length) error(new Error(r.warnings.join("\n")));
56
+ await waitForRestart();
57
+ await loadState();
58
+ } catch (err) { error(err); e.target.disabled = false; }
59
+ });
60
+
61
+ // ---------- getting the files ----------
62
+
63
+ const drop = $("drop");
64
+ drop.addEventListener("dragover", (e) => { e.preventDefault(); drop.dataset.over = ""; });
65
+ drop.addEventListener("dragleave", () => delete drop.dataset.over);
66
+ drop.addEventListener("drop", async (e) => {
67
+ e.preventDefault();
68
+ delete drop.dataset.over;
69
+ const entries = [...e.dataTransfer.items].map((i) => i.webkitGetAsEntry?.()).filter(Boolean);
70
+ status("Reading the folder…");
71
+ try { await send((await Promise.all(entries.map((en) => walkEntry(en, "")))).flat()); } catch (err) { error(err); }
72
+ });
73
+ $("folder").addEventListener("change", (e) => send([...e.target.files].map((f) => [f.webkitRelativePath || f.name, f])).catch(error));
74
+ $("files").addEventListener("change", (e) => send([...e.target.files].map((f) => [f.name, f])).catch(error));
75
+
76
+ // FileSystemEntry tree → [path, File]. readEntries returns at most 100 entries per call, so read until empty.
77
+ async function walkEntry(entry, base) {
78
+ const p = base + entry.name;
79
+ if (entry.isFile) return [[p, await new Promise((res, rej) => entry.file(res, rej))]];
80
+ if (SKIP_DIR.test(entry.name)) return [];
81
+ const reader = entry.createReader(), all = [];
82
+ for (;;) {
83
+ const batch = await new Promise((res, rej) => reader.readEntries(res, rej));
84
+ if (!batch.length) break;
85
+ all.push(...batch);
86
+ }
87
+ return (await Promise.all(all.map((c) => walkEntry(c, p + "/")))).flat();
88
+ }
89
+
90
+ // Paths relative to the dropped folder: a single top folder (the one picked) is stripped.
91
+ function relative(pairs) {
92
+ pairs = pairs.map(([p, f]) => [p.replace(/\\/g, "/").replace(/^\/+/, ""), f]);
93
+ const tops = new Set(pairs.map(([p]) => (p.includes("/") ? p.split("/")[0] : "")));
94
+ if (tops.size === 1 && !tops.has("")) pairs = pairs.map(([p, f]) => [p.slice(p.indexOf("/") + 1), f]);
95
+ return pairs.filter(([p]) => keep(p));
96
+ }
97
+
98
+ async function send(pairs) {
99
+ error(null);
100
+ $("review").hidden = true;
101
+ $("done").hidden = true;
102
+ const files = relative(pairs);
103
+ if (!files.some(([p]) => p.endsWith(".kicad_pro"))) throw new Error("No .kicad_pro in what you dropped. Drop the folder that holds your KiCad project.");
104
+ const total = files.reduce((n, [, f]) => n + f.size, 0);
105
+ const { id } = await call("POST", "start");
106
+ state.session = id;
107
+ let sent = 0, done = 0;
108
+ // A few at a time: big boards have hundreds of 3D model files.
109
+ const queue = [...files];
110
+ await Promise.all(Array.from({ length: 4 }, async () => {
111
+ for (let item; (item = queue.shift());) {
112
+ const [p, f] = item;
113
+ await call("PUT", "file", f, `?id=${id}&path=${encodeURIComponent(p)}`);
114
+ sent += f.size; done++;
115
+ status(`Copying ${done} of ${files.length} files (${(sent / 1e6).toFixed(1)} of ${(total / 1e6).toFixed(1)} MB)…`);
116
+ }
117
+ }));
118
+ status("Reading the design…");
119
+ state.review = await call("POST", "analyze", { id });
120
+ review(state.review);
121
+ status("");
122
+ }
123
+
124
+ // ---------- review, then apply ----------
125
+
126
+ function review(r) {
127
+ const example = state.site.boards.find((b) => b.example);
128
+ $("r-title").textContent = r.title || r.stem;
129
+ $("r-stats").textContent = [`${r.parts} parts`, `${r.nets} nets`, r.sheets && `${r.sheets} sheet${r.sheets === 1 ? "" : "s"}`, `from ${r.project}`].filter(Boolean).join(" · ");
130
+ $("r-groups").innerHTML = r.groups.map((g) => `<li>${esc(g.name)} <span class="muted small">(${g.parts})</span></li>`).join("") || '<li class="muted">No groups: the board has a single overview page.</li>';
131
+ $("r-warn").hidden = !r.warnings.length;
132
+ $("r-warnings").innerHTML = r.warnings.map((w) => `<li>${esc(w)}</li>`).join("");
133
+ $("f-title").value = example && state.site.title === "Loupe" ? r.title || r.stem : state.site.title || r.title || r.stem;
134
+ $("f-desc").value = example ? "" : state.site.description;
135
+ let slug = r.slug;
136
+ for (let i = 2; r.taken.includes(slug) && !(example && slug === example.slug); i++) slug = `${r.slug}-${i}`;
137
+ $("f-slug").value = slug;
138
+ $("f-slug-echo").textContent = slug;
139
+ $("c-example-row").hidden = !example;
140
+ $("c-example").checked = !!example;
141
+ if (example) $("c-example-name").textContent = example.slug;
142
+ const k = state.site.kicad;
143
+ $("c-3d-row").hidden = r.model;
144
+ $("c-3d").disabled = !k;
145
+ $("c-3d").checked = !!k && !r.model;
146
+ $("c-3d-text").innerHTML = k
147
+ ? `Export the 3D model and thumbnail with KiCad ${esc(k.version)} now, into <code>kicad/&lt;URL name&gt;/web/</code> (takes a minute; then hosts without KiCad show 3D too)`
148
+ : "No KiCad found on this computer: the site builds without 3D until a <code>web/</code> folder is added (step 2)";
149
+ $("review").hidden = false;
150
+ }
151
+
152
+ $("f-slug").addEventListener("input", (e) => { $("f-slug-echo").textContent = e.target.value; });
153
+
154
+ $("review").addEventListener("submit", async (e) => {
155
+ e.preventDefault();
156
+ error(null);
157
+ $("apply").disabled = true;
158
+ status($("c-3d").checked ? "Adding the board and exporting its 3D model with KiCad: this can take a minute…" : "Adding the board…");
159
+ try {
160
+ const r = await call("POST", "apply", {
161
+ id: state.session, slug: $("f-slug").value.trim(), title: $("f-title").value, description: $("f-desc").value,
162
+ removeExample: !$("c-example-row").hidden && $("c-example").checked, export3d: $("c-3d").checked,
163
+ });
164
+ $("review").hidden = true;
165
+ $("d-list").innerHTML = [
166
+ `Your project is in <code>${esc(r.project.replace(/^\.\//, "").replace(/\/[^/]+$/, "/"))}</code>`,
167
+ r.model ? "Its 3D model and thumbnail are in its <code>web/</code> folder: commit them with the site" : null,
168
+ r.notes.length ? `${r.notes.length} notes to fill in, in <code>src/content/groups/${esc(r.slug)}/</code>` : null,
169
+ r.removed.length ? `Removed the example (${esc(r.removed.join(", "))}) and wrote a new home page, <code>src/content/docs/index.mdx</code>` : null,
170
+ ...r.warnings.map((w) => `<span class="muted">${esc(w)}</span>`),
171
+ ].filter(Boolean).map((l) => `<li>${l}</li>`).join("");
172
+ $("done").hidden = false;
173
+ status("");
174
+ await waitForRestart();
175
+ $("d-wait").hidden = true;
176
+ $("d-open").hidden = false;
177
+ await loadState();
178
+ } catch (err) { error(err); }
179
+ $("apply").disabled = false;
180
+ });
181
+
182
+ // The dev server restarts when loupe.json changes, then builds the boards. Wait until it answers again.
183
+ async function waitForRestart() {
184
+ await new Promise((r) => setTimeout(r, 1500));
185
+ for (let i = 0; i < 240; i++) {
186
+ try { if ((await fetch(BASE, { cache: "no-store" })).ok) return; } catch {}
187
+ await new Promise((r) => setTimeout(r, 1000));
188
+ }
189
+ }
190
+
191
+ loadState().catch(error);
@@ -0,0 +1,317 @@
1
+ // The setup page (spec/publish.md, "The setup page"): only on `astro dev`, never in a build. A person drops their KiCad
2
+ // project on <base>setup/ and the dev server, on their own machine, does the template's manual steps:
3
+ // copy the project into kicad/<slug>/, export its 3D model and thumbnail into kicad/<slug>/web/ (what the web-export
4
+ // jobset would write, so hosts without KiCad still show 3D), add a stub note per group, optionally remove the
5
+ // example board, and write loupe.json (the site's title, description and boards), which restarts the dev server.
6
+ //
7
+ // It writes only under kicad/, src/content/ and loupe.json, answers only loopback clients on a loopback Host (no DNS
8
+ // rebinding), and wants its own header on every write (a page on another origin can't send it without a CORS
9
+ // preflight, which this never grants). Nothing goes over the network.
10
+ import fs from "node:fs";
11
+ import os from "node:os";
12
+ import path from "node:path";
13
+ import crypto from "node:crypto";
14
+ import { fileURLToPath } from "node:url";
15
+ import { loadBuilder } from "../integration.mjs";
16
+
17
+ const PAGE_DIR = path.join(path.dirname(fileURLToPath(import.meta.url)), "setup");
18
+ const ASSETS = { "": ["index.html", "text/html"], "setup.js": ["setup.js", "text/javascript"], "setup.css": ["setup.css", "text/css"] };
19
+ const MAX_FILE = 200e6;
20
+ // What a site needs from a KiCad project. The page filters the same way, so junk never leaves the browser.
21
+ export const KEEP = /(\.(kicad_pro|kicad_sch|kicad_pcb|kicad_dru|kicad_sym|kicad_mod|kicad_wks|kicad_jobset|step|stp|wrl)|(^|\/)(fp|sym)-lib-table|(^|\/)(LICEN[CS]E|COPYING)[^/]*|(^|\/)web\/[^/]+\.(glb|png))$/i;
22
+ export const SKIP_DIR = /^(\.git|\.svn|node_modules|\.history|.*-backups)$/;
23
+ const SLUG = /^[a-z0-9][a-z0-9-]{0,62}$/;
24
+
25
+ // A path from the browser, relative to the dropped folder: plain segments only.
26
+ export function safeRel(p) {
27
+ const parts = String(p).replace(/\\/g, "/").split("/");
28
+ if (!parts.length || parts.some((s) => !s || s === "." || s === ".." || /[:\0]/.test(s) || SKIP_DIR.test(s))) return null;
29
+ const rel = parts.join("/");
30
+ return KEEP.test(rel) && !/(^|\/)(~|_autosave-)|\.lck$/.test(rel) ? rel : null;
31
+ }
32
+
33
+ const loopback = (a) => /^(127\.|::1$|::ffff:127\.)/.test(a || "");
34
+ const loopHost = (h) => /^(127\.0\.0\.1|localhost|\[::1\])(:\d+)?$/.test(h || "");
35
+
36
+ export function setupMiddleware({ root, configFile, base, logger }) {
37
+ const cfgPath = path.resolve(root, configFile);
38
+ const stageRoot = path.join(root, ".astro", "loupe-setup");
39
+ fs.rmSync(stageRoot, { recursive: true, force: true }); // stages left by an earlier run hold full designs
40
+ const sessions = new Map(); // id -> { dir, project }
41
+ const pagePrefix = `${base}setup/`, api = `${base}_loupe/setup/`;
42
+ let kicad; // found once, on first use
43
+ const findKicad = async () => (kicad === undefined ? (kicad = (await loadBuilder()).findKicadCli() || null) : kicad);
44
+
45
+ const readCfg = () => JSON.parse(fs.readFileSync(cfgPath, "utf8"));
46
+ const projectDir = (b) => path.dirname(path.resolve(root, b.project));
47
+ const stemOf = (b) => path.basename(b.project, ".kicad_pro");
48
+ const inside = (dir, p) => { const r = path.relative(dir, p); return r && !r.startsWith("..") && !path.isAbsolute(r); };
49
+
50
+ async function state() {
51
+ const c = readCfg(), k = await findKicad();
52
+ return {
53
+ title: c.title ?? "", description: c.description ?? "",
54
+ boards: (c.boards || []).map((b) => ({
55
+ slug: b.slug, project: b.project, example: !!b.example,
56
+ model: fs.existsSync(path.join(projectDir(b), "web", `${stemOf(b)}.glb`)),
57
+ thumb: fs.existsSync(path.join(projectDir(b), "web", `${stemOf(b)}-top.png`)),
58
+ web: path.relative(root, path.join(projectDir(b), "web")).replace(/\\/g, "/"),
59
+ jobsetDir: path.relative(root, projectDir(b)).replace(/\\/g, "/"),
60
+ })),
61
+ kicad: k ? { version: k.version, major: k.major } : null,
62
+ jobset: `${base}loupe/builder/web-export.kicad_jobset`,
63
+ };
64
+ }
65
+
66
+ // The dropped project's .kicad_pro, relative to the stage. One project per drop.
67
+ function findProject(dir) {
68
+ const found = [];
69
+ const walk = (d, rel) => {
70
+ for (const e of fs.readdirSync(d, { withFileTypes: true })) {
71
+ const r = rel ? `${rel}/${e.name}` : e.name;
72
+ if (e.isDirectory()) walk(path.join(d, e.name), r);
73
+ else if (e.name.endsWith(".kicad_pro")) found.push(r);
74
+ }
75
+ };
76
+ walk(dir, "");
77
+ if (!found.length) throw httpError(422, "No .kicad_pro in what you dropped. Drop the folder that holds your KiCad project.");
78
+ if (found.length > 1) throw httpError(422, `Several KiCad projects (${found.join(", ")}). Drop one project's folder.`);
79
+ return found[0];
80
+ }
81
+
82
+ // A build into a temp folder, read back: the board's title, counts and groups. no3d for the quick look.
83
+ async function inspect(pro, { slug, no3d }) {
84
+ const { build } = await loadBuilder();
85
+ const out = fs.mkdtempSync(path.join(os.tmpdir(), "loupe-setup-"));
86
+ try {
87
+ const r = await build(pro, { out, slug, no3d, noThumb: no3d, log: () => {} });
88
+ const index = JSON.parse(fs.readFileSync(path.join(r.outDir, "index.json"), "utf8"));
89
+ const files = {};
90
+ for (const f of ["model.glb", "thumb.png"]) if (fs.existsSync(path.join(r.outDir, f))) files[f] = fs.readFileSync(path.join(r.outDir, f));
91
+ const count = (id) => index.parts.filter((p) => p.group === id).length;
92
+ return {
93
+ title: r.manifest.title, parts: r.manifest.stats.parts, nets: r.manifest.stats.nets, sheets: (index.sheets || []).length || null,
94
+ groups: (index.groups || []).map((g) => ({ id: g.id, name: g.name, parts: count(g.id) })),
95
+ warnings: r.warnings, files,
96
+ };
97
+ } catch (e) {
98
+ throw httpError(422, e.message);
99
+ } finally {
100
+ fs.rmSync(out, { recursive: true, force: true });
101
+ }
102
+ }
103
+
104
+ function session(id) {
105
+ const s = sessions.get(String(id));
106
+ if (!s) throw httpError(404, "That upload has expired. Drop the folder again.");
107
+ return s;
108
+ }
109
+
110
+ // Into <project>/web/, as the web-export jobset names them: what the builder reads on a host without KiCad.
111
+ function writeWeb(dir, stem, files) {
112
+ if (!files["model.glb"]) return false;
113
+ fs.mkdirSync(path.join(dir, "web"), { recursive: true });
114
+ fs.writeFileSync(path.join(dir, "web", `${stem}.glb`), files["model.glb"]);
115
+ if (files["thumb.png"]) fs.writeFileSync(path.join(dir, "web", `${stem}-top.png`), files["thumb.png"]);
116
+ return true;
117
+ }
118
+
119
+ // loupe.json is watched (addWatchFile): writing it restarts the dev server, which then builds the boards. Written after
120
+ // the response has gone, or the restart could cut it off.
121
+ const writeCfgLater = (c) => setTimeout(() => fs.writeFileSync(cfgPath, JSON.stringify(c, null, 2) + "\n"), 300);
122
+
123
+ const routes = {
124
+ "GET state": () => state(),
125
+
126
+ "POST start": () => {
127
+ const id = crypto.randomBytes(8).toString("hex");
128
+ const dir = path.join(stageRoot, id);
129
+ fs.mkdirSync(dir, { recursive: true });
130
+ sessions.set(id, { dir });
131
+ return { id };
132
+ },
133
+
134
+ "PUT file": async (req, url) => {
135
+ const s = session(url.searchParams.get("id"));
136
+ const rel = safeRel(url.searchParams.get("path"));
137
+ if (!rel) throw httpError(400, `Not a project file: ${url.searchParams.get("path")}`);
138
+ const dest = path.join(s.dir, ...rel.split("/"));
139
+ fs.mkdirSync(path.dirname(dest), { recursive: true });
140
+ await new Promise((resolve, reject) => {
141
+ let n = 0;
142
+ const w = fs.createWriteStream(dest);
143
+ req.on("data", (c) => { n += c.length; if (n > MAX_FILE) { req.destroy(); w.destroy(); reject(httpError(413, `${rel} is over 200 MB`)); } });
144
+ req.pipe(w);
145
+ w.on("finish", resolve);
146
+ w.on("error", reject);
147
+ });
148
+ return { ok: true };
149
+ },
150
+
151
+ "POST analyze": async (req) => {
152
+ const { id } = await body(req);
153
+ const s = session(id);
154
+ s.project = findProject(s.dir);
155
+ const stem = path.basename(s.project, ".kicad_pro");
156
+ const { slugOf } = await loadBuilder();
157
+ const slug = slugOf(stem).replace(/^-+|-+$/g, "") || "board";
158
+ const info = await inspect(path.join(s.dir, ...s.project.split("/")), { slug, no3d: true });
159
+ s.groups = info.groups;
160
+ const c = readCfg();
161
+ const taken = (c.boards || []).map((b) => b.slug);
162
+ return {
163
+ stem, slug, project: s.project, ...info, files: undefined,
164
+ model: fs.existsSync(path.join(s.dir, path.dirname(s.project), "web", `${stem}.glb`)),
165
+ taken, kicad: (await findKicad())?.version ?? null,
166
+ };
167
+ },
168
+
169
+ "POST apply": async (req) => {
170
+ const opt = await body(req);
171
+ const s = session(opt.id);
172
+ if (!s.project) throw httpError(400, "Analyze the project first");
173
+ const slug = String(opt.slug || "");
174
+ if (!SLUG.test(slug)) throw httpError(400, "The URL name may use a-z, 0-9 and -, starting with a letter or digit");
175
+ const c = readCfg();
176
+ const removed = opt.removeExample ? (c.boards || []).filter((b) => b.example) : [];
177
+ const kept = (c.boards || []).filter((b) => !removed.includes(b));
178
+ if (kept.some((b) => b.slug === slug)) throw httpError(409, `The site already has a board named ${slug}. Pick another URL name.`);
179
+ const stem = path.basename(s.project, ".kicad_pro");
180
+ const dest = path.join(root, "kicad", slug);
181
+ if (fs.existsSync(dest) && !removed.some((b) => path.resolve(projectDir(b)) === path.resolve(dest))) {
182
+ throw httpError(409, `kicad/${slug}/ already exists. Pick another URL name, or delete that folder first.`);
183
+ }
184
+ const notes = [];
185
+
186
+ // The example goes first: its folder may be the one this board moves into.
187
+ for (const b of removed) {
188
+ const dir = projectDir(b);
189
+ if (inside(path.join(root, "kicad"), dir)) fs.rmSync(dir, { recursive: true, force: true });
190
+ fs.rmSync(path.join(root, "src", "content", "groups", b.slug), { recursive: true, force: true });
191
+ }
192
+
193
+ fs.cpSync(path.join(s.dir, path.dirname(s.project)), dest, { recursive: true });
194
+ const pro = path.join(dest, `${stem}.kicad_pro`);
195
+ let model = fs.existsSync(path.join(dest, "web", `${stem}.glb`));
196
+ const warnings = [];
197
+ if (opt.export3d && !model) {
198
+ if (!(await findKicad())) warnings.push("No KiCad found on this computer, so no 3D model was exported. See the KiCad steps below.");
199
+ else {
200
+ const info = await inspect(pro, { slug, no3d: false });
201
+ warnings.push(...info.warnings);
202
+ model = writeWeb(dest, stem, info.files);
203
+ if (!model) warnings.push("KiCad exported no 3D model for this board.");
204
+ }
205
+ }
206
+
207
+ // A stub note per group, and the overview: never over a note that's there.
208
+ const groupsDir = path.join(root, "src", "content", "groups", slug);
209
+ fs.mkdirSync(groupsDir, { recursive: true });
210
+ for (const g of [{ id: "overview", name: null }, ...(s.groups || [])]) {
211
+ const f = path.join(groupsDir, `${g.id}.mdx`);
212
+ if (fs.existsSync(f)) continue;
213
+ fs.writeFileSync(f, noteStub(g));
214
+ notes.push(path.relative(root, f).replace(/\\/g, "/"));
215
+ }
216
+
217
+ const title = String(opt.title || "").trim() || c.title;
218
+ const description = String(opt.description ?? c.description ?? "").trim();
219
+ if (removed.length) {
220
+ // The example's home page talks about the example board; start this one from the new board.
221
+ fs.writeFileSync(path.join(root, "src", "content", "docs", "index.mdx"), homePage({ title, description, slug, groups: s.groups || [] }));
222
+ }
223
+ const project = "./" + path.relative(root, pro).replace(/\\/g, "/");
224
+ writeCfgLater({ ...c, title, description, boards: [{ project, slug }, ...kept] });
225
+ fs.rmSync(s.dir, { recursive: true, force: true });
226
+ sessions.delete(String(opt.id));
227
+ logger.info(`setup: added ${slug} (${project})${removed.length ? `, removed ${removed.map((b) => b.slug).join(", ")}` : ""}`);
228
+ return { ok: true, slug, project, model, notes, warnings, removed: removed.map((b) => b.slug) };
229
+ },
230
+
231
+ // The 3D model and thumbnail for a board already on the site: what the web-export jobset does, through the builder.
232
+ "POST export": async (req) => {
233
+ const { slug } = await body(req);
234
+ const c = readCfg(), b = (c.boards || []).find((x) => x.slug === slug);
235
+ if (!b) throw httpError(404, `No board ${slug} in ${configFile}`);
236
+ if (!(await findKicad())) throw httpError(422, "No KiCad found on this computer. Use the KiCad steps instead.");
237
+ const dir = projectDir(b), stem = stemOf(b);
238
+ // The builder reuses a model already in web/, so move it aside for the export, and back if KiCad makes none.
239
+ const old = path.join(dir, "web", `${stem}.glb`), aside = `${old}.loupe-old`;
240
+ if (fs.existsSync(old)) fs.renameSync(old, aside);
241
+ let info;
242
+ try { info = await inspect(path.resolve(root, b.project), { slug, no3d: false }); }
243
+ finally { if (fs.existsSync(aside) && !info?.files["model.glb"]) fs.renameSync(aside, old); }
244
+ const model = writeWeb(dir, stem, info.files);
245
+ fs.rmSync(aside, { force: true });
246
+ writeCfgLater(c); // the same content: restarts the dev server, which rebuilds the board with its new model
247
+ return { ok: model, warnings: model ? info.warnings : [...info.warnings, "KiCad exported no 3D model for this board."] };
248
+ },
249
+ };
250
+
251
+ return async (req, res, next) => {
252
+ const url = new URL(req.url, "http://localhost");
253
+ const isPage = url.pathname === pagePrefix.slice(0, -1) || url.pathname.startsWith(pagePrefix);
254
+ if (!isPage && !url.pathname.startsWith(api)) return next();
255
+ try {
256
+ if (!loopback(req.socket.remoteAddress) || !loopHost(req.headers.host)) throw httpError(403, "The setup page only answers this computer");
257
+ if (isPage) {
258
+ if (url.pathname === pagePrefix.slice(0, -1)) { res.writeHead(301, { location: pagePrefix }); return res.end(); }
259
+ const asset = ASSETS[url.pathname.slice(pagePrefix.length)];
260
+ if (!asset || req.method !== "GET") throw httpError(404, "Not found");
261
+ let text = fs.readFileSync(path.join(PAGE_DIR, asset[0]), "utf8");
262
+ if (asset[0] === "index.html") text = text.replaceAll("%BASE%", base);
263
+ res.writeHead(200, { "content-type": `${asset[1]}; charset=utf-8`, "cache-control": "no-store" });
264
+ return res.end(text);
265
+ }
266
+ if (req.method !== "GET") {
267
+ if (req.headers["x-loupe-setup"] !== "1") throw httpError(403, "Missing the setup page's header");
268
+ const origin = req.headers.origin;
269
+ if (origin && origin !== `http://${req.headers.host}`) throw httpError(403, "Requests from other sites are refused");
270
+ }
271
+ const route = routes[`${req.method} ${url.pathname.slice(api.length)}`];
272
+ if (!route) throw httpError(404, "Not found");
273
+ const result = await route(req, url);
274
+ res.writeHead(200, { "content-type": "application/json", "cache-control": "no-store" });
275
+ res.end(JSON.stringify(result));
276
+ } catch (e) {
277
+ if (!e.status) logger.error(`setup: ${e.stack || e.message}`);
278
+ res.writeHead(e.status || 500, { "content-type": "application/json" });
279
+ res.end(JSON.stringify({ error: e.message }));
280
+ }
281
+ };
282
+ }
283
+
284
+ function httpError(status, message) { return Object.assign(new Error(message), { status }); }
285
+
286
+ async function body(req) {
287
+ let s = "";
288
+ for await (const c of req) { s += c; if (s.length > 1e5) throw httpError(413, "Too large"); }
289
+ try { return JSON.parse(s || "{}"); } catch { throw httpError(400, "Bad JSON"); }
290
+ }
291
+
292
+ const yaml = (s) => JSON.stringify(String(s)); // a JSON string is a valid YAML scalar
293
+
294
+ function noteStub(g) {
295
+ return g.name == null
296
+ ? `---\n# summary: One line about the board, shown on its overview.\n---\n{/* Notes on the whole board go here: what it is, what it's for. They top the board's overview page. */}\n`
297
+ : `---\ntitle: ${yaml(g.name)}\n# summary: One line about this part of the design, shown in the board's card when it's selected.\n---\n{/* Notes on ${g.name.replace(/\*\//g, "")} go here. They top its page, above its parts and nets. */}\n`;
298
+ }
299
+
300
+ function homePage({ title, description, slug, groups }) {
301
+ const list = groups.map((g) => `- [${g.name.replace(/[[\]]/g, "")}](${slug}/${g.id}/)`).join("\n");
302
+ return `---
303
+ title: ${yaml(title)}
304
+ description: ${yaml(description || "A KiCad board, explorable beside its notes.")}
305
+ ---
306
+ import PartLink from "astro-loupe/PartLink.astro";
307
+
308
+ The board on the right stays put while you move through these pages. Open a part of the design from the sidebar and the
309
+ board highlights everything in it; click a part on the board to see where it belongs.
310
+
311
+ Write about your board here. A link like \`<PartLink to="U1" board="${slug}" />\` selects a part from the text.
312
+
313
+ ## The parts of the design
314
+
315
+ ${list || `- [Overview](${slug}/)`}
316
+ `;
317
+ }