astro-loupe 0.0.0-stage → 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.
Files changed (80) hide show
  1. package/Board.astro +54 -0
  2. package/LICENSE +21 -0
  3. package/LICENSE-ecad-viewer.md +22 -0
  4. package/LoupeHead.astro +26 -0
  5. package/NOTICE +28 -0
  6. package/PartLink.astro +16 -0
  7. package/README.md +59 -2
  8. package/builder/browser-modules.json +1 -0
  9. package/builder/build.mjs +98 -0
  10. package/builder/bundle.mjs +24 -0
  11. package/builder/export-bundle.mjs +98 -0
  12. package/builder/groups.mjs +119 -0
  13. package/builder/index-board.mjs +130 -0
  14. package/builder/outline.mjs +106 -0
  15. package/builder/package.mjs +217 -0
  16. package/builder/preflight.mjs +55 -0
  17. package/builder/preview.mjs +62 -0
  18. package/builder/project.mjs +82 -0
  19. package/builder/sexpr.mjs +48 -0
  20. package/builder/source-node.mjs +15 -0
  21. package/builder/source.mjs +72 -0
  22. package/builder/tools.mjs +146 -0
  23. package/builder/validate.mjs +91 -0
  24. package/builder/zip.mjs +85 -0
  25. package/integration.mjs +116 -0
  26. package/package.json +53 -4
  27. package/runtime/THIRD_PARTY_NOTICES.txt +53 -0
  28. package/runtime/builder/astro/Board.astro +54 -0
  29. package/runtime/builder/astro/LoupeHead.astro +26 -0
  30. package/runtime/builder/astro/PartLink.astro +16 -0
  31. package/runtime/builder/builder-web.css +96 -0
  32. package/runtime/builder/builder-web.js +269 -0
  33. package/runtime/builder/index.html +119 -0
  34. package/runtime/builder/lib/bundle.mjs +24 -0
  35. package/runtime/builder/lib/export-bundle.mjs +98 -0
  36. package/runtime/builder/lib/groups.mjs +119 -0
  37. package/runtime/builder/lib/index-board.mjs +130 -0
  38. package/runtime/builder/lib/outline.mjs +106 -0
  39. package/runtime/builder/lib/package.mjs +217 -0
  40. package/runtime/builder/lib/preflight.mjs +55 -0
  41. package/runtime/builder/lib/project.mjs +82 -0
  42. package/runtime/builder/lib/sexpr.mjs +48 -0
  43. package/runtime/builder/lib/source.mjs +72 -0
  44. package/runtime/builder/lib/validate.mjs +91 -0
  45. package/runtime/builder/lib/zip.mjs +85 -0
  46. package/runtime/builder/web-export.kicad_jobset +63 -0
  47. package/runtime/ecad_viewer/3d-viewer.js +20 -0
  48. package/runtime/ecad_viewer/ecad-viewer.js +3960 -0
  49. package/runtime/ecad_viewer/glyph-full.js +1 -0
  50. package/runtime/ecad_viewer/parser.worker.js +269 -0
  51. package/runtime/loupe/loupe-board.css +427 -0
  52. package/runtime/loupe/loupe-board.js +968 -0
  53. package/runtime/loupe/view-3d.js +135 -0
  54. package/runtime/loupe/view-bom.js +106 -0
  55. package/runtime/loupe/view-canvas.js +130 -0
  56. package/runtime/runtime.json +32 -0
  57. package/runtime/three/addons/controls/TrackballControls.js +828 -0
  58. package/runtime/three/addons/environments/RoomEnvironment.js +148 -0
  59. package/runtime/three/addons/libs/fflate.module.js +2474 -0
  60. package/runtime/three/addons/libs/ktx-parse.module.js +1 -0
  61. package/runtime/three/addons/libs/meshopt_decoder.module.js +178 -0
  62. package/runtime/three/addons/libs/zstddec.module.js +1 -0
  63. package/runtime/three/addons/loaders/DRACOLoader.js +613 -0
  64. package/runtime/three/addons/loaders/EXRLoader.js +2309 -0
  65. package/runtime/three/addons/loaders/GLTFLoader.js +4663 -0
  66. package/runtime/three/addons/loaders/KTX2Loader.js +932 -0
  67. package/runtime/three/addons/utils/BufferGeometryUtils.js +1371 -0
  68. package/runtime/three/addons/utils/WorkerPool.js +102 -0
  69. package/runtime/three/three.module.js +53316 -0
  70. package/starlight/BoardPage.astro +50 -0
  71. package/starlight/GroupPage.astro +67 -0
  72. package/starlight/Head.astro +11 -0
  73. package/starlight/TwoColumnContent.astro +171 -0
  74. package/starlight/data.mjs +42 -0
  75. package/starlight/index.mjs +91 -0
  76. package/starlight/notes.mjs +14 -0
  77. package/starlight/setup/index.html +105 -0
  78. package/starlight/setup/setup.css +73 -0
  79. package/starlight/setup/setup.js +191 -0
  80. package/starlight/setup.mjs +317 -0
package/Board.astro ADDED
@@ -0,0 +1,54 @@
1
+ ---
2
+ // Loupe board for Astro sites: renders <loupe-board>. Needs <LoupeHead /> once in the page's <head>.
3
+ // Board packages live in public/boards/<slug>/ (loupe build ... -o <site>/public/boards).
4
+ //
5
+ // <Board slug="hackrf-one" chrome="compact" view="pcb" select="U19" />
6
+ // <a data-loupe-select="U19" data-loupe-board="#board-hackrf-one">U19</a> (text link; data-loupe-board is
7
+ // needed only with several boards)
8
+ //
9
+ // Reading the manifest here makes a missing or broken package fail the site build, not a reader's page.
10
+ import fs from "node:fs";
11
+ import path from "node:path";
12
+
13
+ interface Props {
14
+ slug: string;
15
+ view?: "pcb" | "3d" | "sch" | "bom";
16
+ select?: string;
17
+ chrome?: "full" | "compact" | "minimal" | "none";
18
+ theme?: "auto" | "workbench" | "paper" | "night" | "contrast" | "kicad";
19
+ height?: number;
20
+ title?: string;
21
+ base?: string; // URL prefix where packages live, default /boards/
22
+ loading?: "lazy" | "eager";
23
+ }
24
+ // URLs respect the site's base path (astro.config `base`); the package itself is read from public/ at build time.
25
+ const siteBase = import.meta.env.BASE_URL.replace(/\/?$/, "/");
26
+ const { slug, view, select, chrome = "compact", theme = "auto", height = 560, title, base = `${siteBase}boards/`, loading = "lazy" } = Astro.props;
27
+ const pkgDir = path.join(process.cwd(), "public", base.startsWith(siteBase) ? base.slice(siteBase.length) : base, slug);
28
+ const mfPath = path.join(pkgDir, "manifest.json");
29
+ if (!fs.existsSync(mfPath)) throw new Error(`Board "${slug}": no package at ${pkgDir}. Build it with loupe build ... -o public${base}`);
30
+ const manifest = JSON.parse(fs.readFileSync(mfPath, "utf8"));
31
+ if (manifest.formatVersion !== 1) throw new Error(`Board ${slug}: unsupported formatVersion ${manifest.formatVersion}`);
32
+ const pkg = `${base}${slug}/`;
33
+ const thumb = manifest.files.thumbnail ? `${pkg}${manifest.files.thumbnail}` : null;
34
+ const name = title ?? manifest.title;
35
+ ---
36
+ <figure class="loupe-figure">
37
+ <loupe-board id={`board-${slug}`} src={`${pkg}manifest.json`} view={view} select={select} chrome={chrome} theme={theme}
38
+ loading={loading} style={`height:${height}px`} aria-label={`${name}: interactive board viewer`}>
39
+ {/* The same cover the viewer shows while it loads, so a reader sees one change: this, then the board. The thumbnail
40
+ (a 3D render) is for readers without JavaScript only; shown first, it flashed a 3D board before the 2D one. */}
41
+ <div class="loupe-loading" role="status">Loading {manifest.title}…</div>
42
+ {thumb && <noscript><img class="loupe-placeholder" src={thumb} alt={`${name}: board preview`} /></noscript>}
43
+ </loupe-board>
44
+ <figcaption>{name}{manifest.revision && ` · rev ${manifest.revision}`}{manifest.license && ` · ${manifest.license}`}</figcaption>
45
+ </figure>
46
+
47
+ <style>
48
+ .loupe-figure { margin: 28px 0; }
49
+ loupe-board { border: 1px solid #d9d6cf; border-radius: 10px; overflow: hidden; }
50
+ .loupe-placeholder { width: 100%; height: 100%; object-fit: contain; background: #121212; display: block; }
51
+ /* Before the viewer's script runs, the shell's tokens aren't there yet: workbench values as fallbacks. */
52
+ loupe-board:not(.loupe) .loupe-loading { position: absolute; inset: 0; display: grid; place-items: center; background: #121212; color: #77736b; font: 13px ui-monospace, Consolas, sans-serif; }
53
+ figcaption { font-size: 13px; color: #6d6a63; margin-top: 8px; }
54
+ </style>
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Nerd-Sniped
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,22 @@
1
+ Copyright (c) 2024 深圳华秋电子有限公司
2
+
3
+ Permission is hereby granted, free of charge, to any person
4
+ obtaining a copy of this software and associated documentation
5
+ files (the "Software"), to deal in the Software without
6
+ restriction, including without limitation the rights to use,
7
+ copy, modify, merge, publish, distribute, sublicense, and/or sell
8
+ copies of the Software, and to permit persons to whom the
9
+ Software is furnished to do so, subject to the following
10
+ conditions:
11
+
12
+ The above copyright notice and this permission notice shall be
13
+ included in all copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
17
+ OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18
+ NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
19
+ HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
20
+ WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
21
+ FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
22
+ OTHER DEALINGS IN THE SOFTWARE.
@@ -0,0 +1,26 @@
1
+ ---
2
+ // Loupe runtime for Astro sites. Put it ONCE in <head> (a layout), before any <Board>.
3
+ // It loads the shell CSS, the import map ecad-viewer's 3D view needs, the viewer, and <loupe-board>.
4
+ // An import map must precede every module script and may appear only once on older browsers,
5
+ // which is why this is separate from Board.astro.
6
+ //
7
+ // <LoupeHead /> runtime at /loupe/ (node scripts/build-runtime.mjs --out <site>/public/loupe)
8
+ // <LoupeHead runtime="/assets/loupe/" />
9
+ interface Props {
10
+ runtime?: string; // URL prefix of the runtime folder, with trailing slash
11
+ }
12
+ // Default: loupe/ under the site's base path (astro.config `base`), where the integration installs it.
13
+ const { runtime = `${import.meta.env.BASE_URL.replace(/\/?$/, "/")}loupe/` } = Astro.props;
14
+ const importmap = JSON.stringify({
15
+ imports: {
16
+ three: `${runtime}three/three.module.js`,
17
+ "three/addons/": `${runtime}three/addons/`,
18
+ "3d-viewer": `${runtime}ecad_viewer/3d-viewer.js`,
19
+ "glyph-full": `${runtime}ecad_viewer/glyph-full.js`,
20
+ },
21
+ });
22
+ ---
23
+ <link rel="stylesheet" href={`${runtime}loupe/loupe-board.css`} />
24
+ <script type="importmap" is:inline set:html={importmap} />
25
+ <script type="module" is:inline src={`${runtime}ecad_viewer/ecad-viewer.js`}></script>
26
+ <script type="module" is:inline src={`${runtime}loupe/loupe-board.js`}></script>
package/NOTICE ADDED
@@ -0,0 +1,28 @@
1
+ Loupe
2
+ A fork of ecad-viewer with a static board-package builder, embed and site components.
3
+
4
+ Loupe's own code (loupe/, scripts/, docs/loupe/ and the `// LOUPE: #n` patches in packages/) is
5
+ Copyright (c) 2026 Nerd-Sniped. MIT License (see loupe/LICENSE).
6
+
7
+ This repository contains code from:
8
+
9
+ - ecad-viewer — Copyright (c) Huaqiu Electronics and contributors. MIT License.
10
+ https://github.com/Huaqiu-Electronics/ecad-viewer (see LICENSE.md)
11
+ - KiCanvas — Copyright (c) Alethea Katherine Flowers and contributors. MIT License.
12
+ Included in ecad-viewer; notices are kept in the source headers.
13
+ - three.js — Copyright (c) 2010-2026 three.js authors. MIT License. (packages/ecad-viewer-app/static/three)
14
+
15
+ Code ported from KiCAD-Prism (Apache License 2.0, https://github.com/krishna-swaroop/KiCAD-Prism),
16
+ if any, is listed here with the files it went into, and those files say so in their headers:
17
+
18
+ - (none yet)
19
+
20
+ Test fixture loupe/fixtures/hackrf-one: Copyright 2012-2023 Great Scott Gadgets,
21
+ CERN Open Hardware Licence Version 2 - Permissive (see loupe/fixtures/hackrf-one/LICENSE).
22
+
23
+ Test fixture loupe/fixtures/royalblue54l-feather: the RoyalBlue54L Feather by Lord's Boards, from KiCad's demo
24
+ projects, CERN Open Hardware Licence Version 2 - Permissive (see loupe/fixtures/royalblue54l-feather/LICENSE). Its 3D
25
+ model (web/RoyalBlue54L-Feather.glb) also contains models from the KiCad library (CC-BY-SA 4.0 with an exception for
26
+ designs and the files generated from them).
27
+
28
+ Nothing in this repository is taken from PCBView.io, whose software is proprietary.
package/PartLink.astro ADDED
@@ -0,0 +1,16 @@
1
+ ---
2
+ // A link in text that selects a part, pin or net in a board (spec: viewer.md, "Text links"). For MDX posts:
3
+ //
4
+ // The clock generator <PartLink to="U19" /> drives <PartLink to="GCK1">the GCK1 net</PartLink>.
5
+ // With several boards on the page, name one: <PartLink to="R2" board="mini-k10" view="sch" />
6
+ //
7
+ // No script: the first <loupe-board> on the page handles these clicks.
8
+ interface Props {
9
+ to: string; // a reference, a pin ("U19.3") or a net ("/baseband/CLK0")
10
+ board?: string; // the board's slug; default: the first board on the page
11
+ view?: "pcb" | "3d" | "sch" | "bom";
12
+ }
13
+ const { to, board, view } = Astro.props;
14
+ ---
15
+ <a class="loupe-partlink" href={`#${board ? `board-${board}` : ""}`} data-loupe-select={to}
16
+ data-loupe-board={board ? `#board-${board}` : undefined} data-loupe-view={view}><slot>{to}</slot></a>
package/README.md CHANGED
@@ -1,3 +1,60 @@
1
- # Temporary Holding Version
1
+ # astro-loupe
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Show a KiCad board on an Astro site as linked schematic, PCB, 3D and BOM views. The integration builds your
4
+ `.kicad_pro` projects into static board packages when the site builds; nothing runs on a server and nothing is fetched
5
+ from the network.
6
+
7
+ ```bash
8
+ npm install astro-loupe
9
+ ```
10
+
11
+ ## A Starlight site with the board beside every page
12
+
13
+ ```js
14
+ // astro.config.mjs
15
+ import { defineConfig } from "astro/config";
16
+ import starlight from "@astrojs/starlight";
17
+ import loupe from "astro-loupe/starlight";
18
+
19
+ export default defineConfig({
20
+ integrations: [starlight({
21
+ title: "My board",
22
+ plugins: [loupe({ boards: [{ project: "./kicad/my-board/my-board.kicad_pro", slug: "my-board" }] })],
23
+ })],
24
+ });
25
+ ```
26
+
27
+ The board stays on screen while readers move between pages, and each part of the design (a titled box in the
28
+ schematic, or a sheet) gets its own page. The quickest start is the Loupe template:
29
+ `npm create astro@latest -- --template nerd-sniped/astro-loupe`.
30
+
31
+ ## Any Astro site
32
+
33
+ ```js
34
+ // astro.config.mjs
35
+ import mdx from "@astrojs/mdx";
36
+ import loupe from "astro-loupe/integration";
37
+ export default defineConfig({ integrations: [mdx(), loupe({ boards: [{ project: "./kicad/my-board/my-board.kicad_pro" }] })] });
38
+ ```
39
+
40
+ ```astro
41
+ ---
42
+ import LoupeHead from "astro-loupe/LoupeHead.astro";
43
+ import Board from "astro-loupe/Board.astro";
44
+ import PartLink from "astro-loupe/PartLink.astro";
45
+ ---
46
+ <LoupeHead /> <!-- once per page, in <head> -->
47
+ <Board slug="my-board" />
48
+ The regulator <PartLink to="U2" board="my-board" /> feeds the radio.
49
+ ```
50
+
51
+ ## 3D and thumbnails
52
+
53
+ The builder reads `web/<project>.glb` and `web/<project>-top.png` next to the project when they're there (KiCad's
54
+ web-export jobset writes them), so a site builds with full 3D on hosts without KiCad, such as Netlify. Without them it
55
+ runs `kicad-cli` (8+ for 3D, 9+ for the thumbnail) if it can find it, and otherwise builds the board without them.
56
+
57
+ ## Licence
58
+
59
+ MIT, Copyright (c) 2026 Nerd-Sniped (`LICENSE`). The viewer runtime includes ecad-viewer (Huaqiu Electronics,
60
+ `LICENSE-ecad-viewer.md`), KiCanvas and three.js, all MIT; see `NOTICE` and `runtime/THIRD_PARTY_NOTICES.txt`.
@@ -0,0 +1 @@
1
+ ["sexpr", "index-board", "preflight", "project", "package", "validate", "bundle", "source", "zip", "export-bundle", "outline", "groups"]
@@ -0,0 +1,98 @@
1
+ // loupe build: KiCad project -> board package (see docs/loupe/spec/builder.md).
2
+ // The Node shell around package.mjs: it finds the project on disk, supplies the machine's tools (kicad-cli,
3
+ // gltfpack, git) as capabilities, and moves the validated package into place atomically.
4
+ import fs from "node:fs";
5
+ import os from "node:os";
6
+ import path from "node:path";
7
+ import { execFileSync } from "node:child_process";
8
+ import { buildPackage, slugOf, PROFILES_BUILT } from "./package.mjs";
9
+ import { nodeSource } from "./source-node.mjs";
10
+ import { findKicadCli, findGltfpack, findModelDir, resolveModelPaths, exportGlb, compressGlb, renderThumb } from "./tools.mjs";
11
+
12
+ export { BUILDER_VERSION, FORMAT_VERSION } from "./package.mjs";
13
+
14
+ // A project folder, or a .kicad_pro file in it.
15
+ function locate(input) {
16
+ const abs = path.resolve(input);
17
+ if (fs.statSync(abs).isDirectory()) return { dir: abs, pro: null };
18
+ if (!abs.endsWith(".kicad_pro")) throw new Error(`Not a .kicad_pro file: ${abs}`);
19
+ return { dir: path.dirname(abs), pro: path.basename(abs) };
20
+ }
21
+
22
+ export async function build(input, opts = {}) {
23
+ const log = opts.log || ((...a) => console.log(...a));
24
+ if (opts.profile && !PROFILES_BUILT.includes(opts.profile)) throw new Error(`--profile ${opts.profile} is not built yet (source, packed)`);
25
+ const { dir, pro } = locate(input);
26
+ const stem = (pro || fs.readdirSync(dir).find((f) => f.endsWith(".kicad_pro")) || path.basename(dir)).replace(/\.kicad_pro$/, "");
27
+ const slug = opts.slug || slugOf(stem);
28
+ const outDir = path.resolve(opts.out || "boards", slug);
29
+ const tmp = fs.mkdtempSync(path.join(os.tmpdir(), `loupe-${slug}-`));
30
+ // Always remove the temp folder: it holds the full design, and a failed build must not leave it behind.
31
+ try {
32
+ const r = await buildPackage(nodeSource(dir), { ...opts, slug, project: pro, log }, nodeCaps(dir, tmp, opts));
33
+ if (opts.preflightOnly) return r;
34
+ const stage = path.join(tmp, "package");
35
+ for (const [f, bytes] of r.files) {
36
+ fs.mkdirSync(path.dirname(path.join(stage, f)), { recursive: true });
37
+ fs.writeFileSync(path.join(stage, f), bytes);
38
+ }
39
+ fs.mkdirSync(path.dirname(outDir), { recursive: true });
40
+ fs.rmSync(outDir, { recursive: true, force: true });
41
+ fs.cpSync(stage, outDir, { recursive: true });
42
+ return { outDir, manifest: r.manifest, warnings: r.warnings, preflight: r.preflight };
43
+ } finally {
44
+ fs.rmSync(tmp, { recursive: true, force: true });
45
+ }
46
+ }
47
+
48
+ // The machine's tools, for package.mjs. kicad-cli works on files, so each call writes into the temp folder.
49
+ function nodeCaps(dir, tmp, opts) {
50
+ const cli = opts.noKicad ? null : findKicadCli(opts.kicadCli);
51
+ let gp; const gltfpack = () => (gp === undefined ? (gp = findGltfpack()) : gp);
52
+ const work = path.join(tmp, "work");
53
+ const writePcb = (name, text) => {
54
+ const p = path.join(work, "design", name);
55
+ fs.mkdirSync(path.dirname(p), { recursive: true });
56
+ fs.writeFileSync(p, text);
57
+ return p;
58
+ };
59
+ const caps = {
60
+ cli: cli ? { version: cli.version, major: cli.major } : null,
61
+ git: gitInfo(dir),
62
+ canCompress: () => Boolean(gltfpack()),
63
+ compressGlb: async (bytes) => {
64
+ fs.mkdirSync(work, { recursive: true });
65
+ const i = path.join(work, "in.glb"), o = path.join(work, "out.glb");
66
+ fs.writeFileSync(i, bytes);
67
+ return gltfpack() && compressGlb(gltfpack(), i, o) ? new Uint8Array(fs.readFileSync(o)) : null;
68
+ },
69
+ };
70
+ if (cli) {
71
+ // The copy kicad-cli reads gets model paths it can resolve (tools.mjs, resolveModelPaths): older projects name
72
+ // their models in ways a newer KiCad doesn't, and ${KIPRJMOD} would point at this temp folder.
73
+ const modelDir = findModelDir(cli);
74
+ const withModels = (text) => resolveModelPaths(text, { projectDir: dir, modelDir });
75
+ caps.exportGlb = async (name, text) => {
76
+ const raw = path.join(work, "model.raw.glb");
77
+ const m = withModels(text);
78
+ const r = exportGlb(cli, writePcb(name, m.text), raw);
79
+ const warnings = [...r.warnings];
80
+ if (m.missing.length) {
81
+ const uniq = [...new Set(m.missing)];
82
+ warnings.push(`${m.missing.length} footprint 3D model${m.missing.length === 1 ? "" : "s"} not found (${uniq.length} file${uniq.length === 1 ? "" : "s"}, e.g. ${uniq[0]}): those parts have no body in 3D${modelDir ? "" : ". No KiCad 3D model library found: set KICAD" + cli.major + "_3DMODEL_DIR"}`);
83
+ }
84
+ return { bytes: r.ok ? new Uint8Array(fs.readFileSync(raw)) : null, warnings };
85
+ };
86
+ caps.renderThumb = async (name, text) => {
87
+ const png = path.join(work, "thumb.png");
88
+ return renderThumb(cli, writePcb(name, withModels(text).text), png) ? new Uint8Array(fs.readFileSync(png)) : null;
89
+ };
90
+ }
91
+ return caps;
92
+ }
93
+
94
+ function gitInfo(dir) {
95
+ const run = (...a) => { try { return execFileSync("git", ["-C", dir, ...a], { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] }).trim(); } catch { return null; } };
96
+ const commit = run("rev-parse", "--short", "HEAD");
97
+ return { repo: run("remote", "get-url", "origin"), commit, dirty: commit ? Boolean(run("status", "--porcelain", "--", ".")) : false };
98
+ }
@@ -0,0 +1,24 @@
1
+ // The packed profile's design.bundle (docs/loupe/spec/package-format.md, "Package profiles").
2
+ //
3
+ // design.bundle = base64( gzip( UTF-8 JSON ) ), with the JSON:
4
+ // { "bundleVersion": 1, "pcb": "x.kicad_pcb" | null, "schematicRoot": "x.kicad_sch" | null,
5
+ // "schematics": ["x.kicad_sch", ...], "files": { "<file name>": "<file text>", ... } }
6
+ //
7
+ // Base64 keeps it a text file, which hosts that serve only web file types accept. The point is that no
8
+ // .kicad_* URL exists to "save as"; it's not protection: the viewer unpacks it in the reader's browser.
9
+ // The viewer side (DecompressionStream) is unpackBundle() in loupe/embed/loupe-board.js; keep the two in step.
10
+ // Browser-safe (CompressionStream), so the drop-in page packs with the same code as the CLI.
11
+ import { bytesOf, utf8, gzip, gunzip, toBase64, fromBase64 } from "./source.mjs";
12
+
13
+ export const BUNDLE_VERSION = 1;
14
+
15
+ export async function packBundle({ pcb = null, schematicRoot = null, schematics = [], files }) {
16
+ const json = JSON.stringify({ bundleVersion: BUNDLE_VERSION, pcb, schematicRoot, schematics, files });
17
+ return toBase64(await gzip(bytesOf(json)));
18
+ }
19
+
20
+ export async function unpackBundle(text) {
21
+ const b = JSON.parse(utf8(await gunzip(fromBase64(text))));
22
+ if (b.bundleVersion !== BUNDLE_VERSION) throw new Error(`bundleVersion ${b.bundleVersion} is not ${BUNDLE_VERSION}`);
23
+ return b;
24
+ }
@@ -0,0 +1,98 @@
1
+ // Export bundle (docs/loupe/spec/builder.md, "Builder site and its exits"): one board package plus everything a site
2
+ // needs to show it, laid out like a site root. Browser-safe: the builder page calls it with the runtime files it
3
+ // fetched from its own origin; Node tests call it with files read from loupe/dist/runtime.
4
+ //
5
+ // public/loupe/ the viewer runtime (renamed with the project, decisions D2)
6
+ // public/boards/<slug>/ the package
7
+ // public/<slug>.html a plain HTML page with the board, for any static host
8
+ // src/components/loupe/ LoupeHead.astro, Board.astro, PartLink.astro
9
+ // README.md
10
+ import { bytesOf } from "./source.mjs";
11
+
12
+ export const RUNTIME_DIR = "loupe"; // under public/; the same folder name the Astro integration installs to
13
+
14
+ const esc = (s) => String(s ?? "").replace(/[&<>"]/g, (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;" })[c]);
15
+
16
+ // The page's own CSP, as loupe view sends it: nothing outside the page's origin.
17
+ export const PAGE_CSP = "default-src 'self'; script-src 'self' 'unsafe-inline' 'wasm-unsafe-eval'; style-src 'self' 'unsafe-inline'; img-src 'self' data: blob:; worker-src 'self' blob:; connect-src 'self' blob: data:; font-src 'self' data:; base-uri 'none'; form-action 'none'";
18
+
19
+ // Relative paths only, so the page works from any folder of any host (public/ served at / or at /some/base/).
20
+ export function embedPage({ slug, title }) {
21
+ const rt = `${RUNTIME_DIR}/`;
22
+ const importmap = JSON.stringify({ imports: {
23
+ three: `./${rt}three/three.module.js`, "three/addons/": `./${rt}three/addons/`,
24
+ "3d-viewer": `./${rt}ecad_viewer/3d-viewer.js`, "glyph-full": `./${rt}ecad_viewer/glyph-full.js`,
25
+ } });
26
+ return `<!doctype html>
27
+ <html lang="en">
28
+ <head>
29
+ <meta charset="utf-8">
30
+ <meta name="viewport" content="width=device-width, initial-scale=1">
31
+ <meta http-equiv="Content-Security-Policy" content="${PAGE_CSP}">
32
+ <title>${esc(title)}</title>
33
+ <link rel="stylesheet" href="${rt}loupe/loupe-board.css">
34
+ <style>html, body { margin: 0; height: 100%; } loupe-board { display: block; height: 100%; }</style>
35
+ <script type="importmap">${importmap}</script>
36
+ <script type="module" src="${rt}ecad_viewer/ecad-viewer.js"></script>
37
+ <script type="module" src="${rt}loupe/loupe-board.js"></script>
38
+ </head>
39
+ <body>
40
+ <loupe-board id="board-${esc(slug)}" src="boards/${esc(slug)}/manifest.json" chrome="full" loading="eager" hash global-keys aria-label="${esc(title)}: interactive board viewer"></loupe-board>
41
+ </body>
42
+ </html>
43
+ `;
44
+ }
45
+
46
+ export function bundleReadme({ slug, title, profile, runtime }) {
47
+ return `# ${title}: board bundle
48
+
49
+ A board package for \`${slug}\` (profile \`${profile}\`) with the viewer that shows it. Everything here is static files:
50
+ no server, no account, nothing loaded from anywhere else.
51
+
52
+ ## Astro site
53
+
54
+ 1. Copy \`public/\` and \`src/\` into your site's root (they merge with yours).
55
+ 2. In your layout's \`<head>\`, once per page:
56
+
57
+ \`\`\`astro
58
+ import LoupeHead from "../components/loupe/LoupeHead.astro";
59
+ <LoupeHead />
60
+ \`\`\`
61
+
62
+ 3. Where the board goes, in a page or an MDX post:
63
+
64
+ \`\`\`astro
65
+ import Board from "../components/loupe/Board.astro";
66
+ <Board slug="${slug}" />
67
+ \`\`\`
68
+
69
+ Links in text that select a part: \`import PartLink from "../components/loupe/PartLink.astro"\`, then
70
+ \`<PartLink to="U1" />\`. Adjust the \`../\` in the imports to where your file sits.
71
+
72
+ ## Any other static host
73
+
74
+ Copy what's in \`public/\` to your site, and open \`${slug}.html\`. To put the board in a page of your own, copy the
75
+ \`<link>\`, the import map and the two \`<script>\` tags from that file into its \`<head>\`, and the \`<loupe-board>\` tag
76
+ where the board goes. Pages must be served over http(s): browsers don't run the viewer from \`file://\`.
77
+
78
+ ## What's inside
79
+
80
+ - \`public/${RUNTIME_DIR}/\`: the viewer runtime${runtime?.fork ? ` (built from ${runtime.fork})` : ""}. Several boards on one site share it.
81
+ Its licenses are in \`THIRD_PARTY_NOTICES.txt\`.
82
+ - \`public/boards/${slug}/\`: the board package. \`manifest.json\` lists a SHA-256 for every file.
83
+ - \`public/${slug}.html\`: the board on a page of its own.
84
+ - \`src/components/loupe/\`: the Astro components.
85
+ `;
86
+ }
87
+
88
+ // pkg: Map path→bytes (the package); runtime: Map path→bytes (runtime-relative paths); astro: Map name→text|bytes.
89
+ export function bundleFiles({ pkg, manifest, runtime, runtimeInfo, astro }) {
90
+ const out = new Map();
91
+ const slug = manifest.slug;
92
+ for (const [p, b] of runtime) out.set(`public/${RUNTIME_DIR}/${p}`, b);
93
+ for (const [p, b] of pkg) out.set(`public/boards/${slug}/${p}`, b);
94
+ out.set(`public/${slug}.html`, bytesOf(embedPage({ slug, title: manifest.title })));
95
+ for (const [n, t] of astro) out.set(`src/components/loupe/${n}`, typeof t === "string" ? bytesOf(t) : t);
96
+ out.set("README.md", bytesOf(bundleReadme({ slug, title: manifest.title, profile: manifest.profile || "source", runtime: runtimeInfo })));
97
+ return out;
98
+ }
@@ -0,0 +1,119 @@
1
+ // Functional groups (decisions D20, package-format.md "groups"): what a board is made of, by design intent ("Battery",
2
+ // "Power", "Debugger"), read from the schematic. Browser-safe.
3
+ //
4
+ // 1. A titled box on a sheet is a group: a rectangle with a one-line text in its top-left corner (or just above it), or a
5
+ // KiCad text box, whose first line is the name. Every part whose symbol sits inside the box belongs to it. Boxes
6
+ // without a title are drawings and are ignored. Boxes may nest; a part's own group is the smallest box holding it.
7
+ // 2. Parts in no box belong to their sheet's group, named after the sheet. Parts on the root sheet (and parts with no
8
+ // symbol) form "Other parts".
9
+ // KiCad 6 has no schematic rectangles, so its boards get sheet groups only.
10
+ import { parse, kids, kid, num } from "./sexpr.mjs";
11
+
12
+ const MAX_NAME = 60;
13
+ const ABOVE = 6; // mm: a title this far above a box's top edge still names it
14
+
15
+ // sheets: [{ file, name, page, path }] (walkSheets, root first); texts: Map file -> schematic text; parts and nets as in
16
+ // index.json. Returns the groups, and sets part.group to each part's own group id.
17
+ export function findGroups(sheets, texts, parts, nets) {
18
+ const rootFile = sheets[0]?.file ?? null;
19
+ const known = new Set(parts.map((p) => p.ref));
20
+ const boxGroups = [];
21
+ const inBox = new Map(); // ref -> [{ group, area }]
22
+ for (const sheet of sheets) {
23
+ const text = texts.get(sheet.file);
24
+ if (!text) continue;
25
+ const doc = parse(text, sheet.file);
26
+ const symbols = placedSymbols(doc).filter((s) => known.has(s.ref));
27
+ for (const b of titledBoxes(doc)) {
28
+ const refs = [...new Set(symbols.filter((s) => inside(s, b)).map((s) => s.ref))];
29
+ if (!refs.length) continue;
30
+ const g = { name: b.name, source: "box", sheet: sheet.file, box: b.rect.map((v) => round(v)), parts: refs, page: sheet.page, y: b.rect[1], x: b.rect[0] };
31
+ boxGroups.push(g);
32
+ for (const r of refs) (inBox.get(r) ?? inBox.set(r, []).get(r)).push({ g, area: b.rect[2] * b.rect[3] });
33
+ }
34
+ }
35
+
36
+ // Sheet groups take every part no box holds.
37
+ const sheetGroups = new Map(); // file -> group
38
+ for (const p of parts) {
39
+ if (inBox.has(p.ref)) continue;
40
+ const file = p.sheetfile && sheets.some((s) => s.file === p.sheetfile) ? p.sheetfile : rootFile;
41
+ if (!sheetGroups.has(file)) {
42
+ const sheet = sheets.find((s) => s.file === file);
43
+ const root = !sheet || file === rootFile;
44
+ sheetGroups.set(file, { name: root ? "Other parts" : sheet.name, source: "sheet", sheet: sheet?.file ?? null, box: null, parts: [], page: root ? null : sheet.page, y: Infinity, x: 0, root });
45
+ }
46
+ sheetGroups.get(file).parts.push(p.ref);
47
+ }
48
+
49
+ // Order: by sheet page (the reader's order through the schematic), boxes top to bottom then left to right, each sheet's
50
+ // own group after its boxes, "Other parts" last.
51
+ const pageNo = (g) => (g.root ? Infinity : Number.parseFloat(g.page) || 0);
52
+ const all = [...boxGroups, ...sheetGroups.values()].sort((a, b) => pageNo(a) - pageNo(b) || String(a.sheet).localeCompare(String(b.sheet)) || a.y - b.y || a.x - b.x);
53
+
54
+ const used = new Set(["overview"]); // reserved: a board site keeps the board's own notes under that name
55
+ const netsByRef = new Map();
56
+ for (const n of nets) for (const pin of n.pins) { const r = pin.split(".")[0]; (netsByRef.get(r) ?? netsByRef.set(r, new Set()).get(r)).add(n.name); }
57
+ const groups = all.map((g) => {
58
+ let id = slug(g.name), i = 2;
59
+ while (used.has(id)) id = `${slug(g.name)}-${i++}`;
60
+ used.add(id);
61
+ g.id = id;
62
+ const refs = g.parts.sort(natural);
63
+ return { id, name: g.name, source: g.source, sheet: g.sheet, box: g.box, parts: refs, nets: [...new Set(refs.flatMap((r) => [...(netsByRef.get(r) ?? [])]))].sort(natural) };
64
+ });
65
+ for (const p of parts) {
66
+ const boxes = inBox.get(p.ref);
67
+ p.group = boxes ? boxes.sort((a, b) => a.area - b.area)[0].g.id : [...sheetGroups.values()].find((g) => g.parts.includes(p.ref)).id;
68
+ }
69
+ return groups;
70
+ }
71
+
72
+ // Placed symbols: { ref, x, y }. The reference is the symbol's own property; a sheet used several times also lists
73
+ // each use's reference in (instances), and all of them count.
74
+ function placedSymbols(doc) {
75
+ const out = [];
76
+ for (const s of kids(doc, "symbol")) {
77
+ const at = kid(s, "at");
78
+ if (!at) continue;
79
+ const refs = new Set(kids(kid(s, "instances"), "project").flatMap((pr) => kids(pr, "path")).map((p) => kid(p, "reference")?.[1]).filter(Boolean));
80
+ const own = kids(s, "property").find((p) => p[1] === "Reference")?.[2];
81
+ if (own) refs.add(own);
82
+ for (const ref of refs) out.push({ ref, x: num(at[1]) ?? 0, y: num(at[2]) ?? 0 });
83
+ }
84
+ return out;
85
+ }
86
+
87
+ // Boxes with a name: { name, rect: [x, y, w, h] } in sheet millimetres.
88
+ export function titledBoxes(doc) {
89
+ const titles = kids(doc, "text").map((t) => ({ text: String(t[1] ?? "").trim(), at: kid(t, "at") })).filter((t) => t.at && oneLine(t.text))
90
+ .map((t) => ({ text: t.text, x: num(t.at[1]) ?? 0, y: num(t.at[2]) ?? 0 }));
91
+ const boxes = [];
92
+ for (const r of kids(doc, "rectangle")) {
93
+ const a = kid(r, "start"), b = kid(r, "end");
94
+ if (!a || !b) continue;
95
+ const rect = norm(num(a[1]), num(a[2]), num(b[1]), num(b[2]));
96
+ // The title: a text in the box's top band or just above it, the one nearest the top-left corner.
97
+ const band = Math.min(10, rect[3] / 3);
98
+ const t = titles.filter((t) => t.x >= rect[0] - 1 && t.x <= rect[0] + rect[2] && t.y >= rect[1] - ABOVE && t.y <= rect[1] + band)
99
+ .sort((p, q) => Math.hypot(p.x - rect[0], p.y - rect[1]) - Math.hypot(q.x - rect[0], q.y - rect[1]))[0];
100
+ if (t) boxes.push({ name: t.text, rect });
101
+ }
102
+ for (const tb of kids(doc, "text_box")) {
103
+ const name = String(tb[1] ?? "").split("\n")[0].trim();
104
+ if (!oneLine(name)) continue;
105
+ const at = kid(tb, "at"), size = kid(tb, "size"), a = kid(tb, "start"), b = kid(tb, "end");
106
+ const rect = at && size ? norm(num(at[1]), num(at[2]), num(at[1]) + num(size[1]), num(at[2]) + num(size[2]))
107
+ : a && b ? norm(num(a[1]), num(a[2]), num(b[1]), num(b[2])) : null;
108
+ if (rect) boxes.push({ name, rect });
109
+ }
110
+ return boxes;
111
+ }
112
+
113
+ const oneLine = (s) => s && s.length <= MAX_NAME && !s.includes("\n");
114
+ const norm = (x0, y0, x1, y1) => [Math.min(x0, x1), Math.min(y0, y1), Math.abs(x1 - x0), Math.abs(y1 - y0)];
115
+ const inside = (s, b) => s.x >= b.rect[0] && s.x <= b.rect[0] + b.rect[2] && s.y >= b.rect[1] && s.y <= b.rect[1] + b.rect[3];
116
+ export const slug = (s) => String(s).toLowerCase().normalize("NFKD").replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "") || "group";
117
+ const collator = new Intl.Collator("en", { numeric: true, sensitivity: "base" });
118
+ const natural = (a, b) => collator.compare(a, b);
119
+ const round = (v) => Math.round(v * 1000) / 1000;