grimoire3d 0.0.0 → 0.1.0-dev.9361940

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 (153) hide show
  1. package/README.md +23 -123
  2. package/cli/cli.js +350 -0
  3. package/cli/content.js +403 -0
  4. package/cli/cover-options.d.ts +15 -0
  5. package/cli/cover-options.js +105 -0
  6. package/cli/head-file.js +133 -0
  7. package/cli/library-footer.d.ts +10 -0
  8. package/cli/library-footer.js +21 -0
  9. package/cli/markdown.js +139 -0
  10. package/cli/markup.d.ts +3 -0
  11. package/cli/markup.js +60 -0
  12. package/cli/routes.d.ts +6 -0
  13. package/cli/routes.js +19 -0
  14. package/cli/static-pages.js +481 -0
  15. package/cli/video-url.d.ts +5 -0
  16. package/cli/video-url.js +51 -0
  17. package/dist/BookViewer-GXuBR_bC.js +339 -0
  18. package/dist/components/BookModel.d.ts +20 -0
  19. package/dist/components/BookViewer.d.ts +17 -0
  20. package/dist/components/index.d.ts +2 -0
  21. package/dist/components/index.js +1 -0
  22. package/dist/grimoire3d.css +3 -0
  23. package/dist/index.d.ts +8 -0
  24. package/dist/index.js +1 -0
  25. package/dist/main.d.ts +1 -0
  26. package/dist/site/assets/BookReader-DudAXdp3.js +2 -0
  27. package/dist/site/assets/BookScene-DiAiTP9V.js +4294 -0
  28. package/dist/site/assets/MermaidDiagram-2mwgnVgM.js +44 -0
  29. package/dist/site/assets/PageMarkdown-ENP_TuEU.js +37 -0
  30. package/dist/site/assets/abnfDiagram-S7VZAUFO-CPn8kyCz.js +1 -0
  31. package/dist/site/assets/alcove-cyX4Tv3E.avif +0 -0
  32. package/dist/site/assets/architecture-WOLXFQ4H-Czsdswwl.js +1 -0
  33. package/dist/site/assets/architectureDiagram-YGSQEFNW-C_9i0B1c.js +36 -0
  34. package/dist/site/assets/blockDiagram-APKKGZFW-B4TEuCLK.js +140 -0
  35. package/dist/site/assets/bpmnIcons-APHXDYXF-C0jbCElo.js +1 -0
  36. package/dist/site/assets/c4Diagram-KJ2TOQU5-CH_Uv_Fz.js +38 -0
  37. package/dist/site/assets/catalog-07-UR91A.avif +0 -0
  38. package/dist/site/assets/chunk-2Q5K7J3B-C1jixKkw.js +1 -0
  39. package/dist/site/assets/chunk-5VM5RSS4-ZNzvKenW.js +15 -0
  40. package/dist/site/assets/chunk-6MUBBAK2-C4kh7Z3T.js +2 -0
  41. package/dist/site/assets/chunk-AXFCVDMN-B_taAhLl.js +62 -0
  42. package/dist/site/assets/chunk-BG4553SI-Cn6LMB1q.js +129 -0
  43. package/dist/site/assets/chunk-DQASFODM-BsDpj_0k.js +10 -0
  44. package/dist/site/assets/chunk-DUW6YSOI-Dgx8z5s3.js +1 -0
  45. package/dist/site/assets/chunk-HFQBQIA3-DLIuoeT3.js +1 -0
  46. package/dist/site/assets/chunk-J5ZVWO5B-oDCd-gWO.js +1 -0
  47. package/dist/site/assets/chunk-JWPE2WC7-DVXcaiue.js +1 -0
  48. package/dist/site/assets/chunk-KQLB2F66-AFzkv6d3.js +2 -0
  49. package/dist/site/assets/chunk-KS47KZWR-DjywFwRy.js +1 -0
  50. package/dist/site/assets/chunk-LEVMRMFU-BrDnuOnu.js +1 -0
  51. package/dist/site/assets/chunk-M57EVK23-BikTvdAr.js +1 -0
  52. package/dist/site/assets/chunk-NGNAAXSQ-DI_UYJZ4.js +136 -0
  53. package/dist/site/assets/chunk-OY52VR5R-Nk28J3qR.js +88 -0
  54. package/dist/site/assets/chunk-QB3YPZ4I-OgBmaa_y.js +213 -0
  55. package/dist/site/assets/chunk-R3KSYZAL-CdwBI4dZ.js +1 -0
  56. package/dist/site/assets/chunk-STOXU5M4-BZAF-H6I.js +72 -0
  57. package/dist/site/assets/chunk-TU62E6Q5-C6WlEf5k.js +1 -0
  58. package/dist/site/assets/chunk-X4PVCEUW-BYepnSMY.js +1 -0
  59. package/dist/site/assets/chunk-XXDRQBXY-DN9ONrwM.js +1 -0
  60. package/dist/site/assets/chunk-Y2CYZVJY-DsF7k-Jl.js +1 -0
  61. package/dist/site/assets/classDiagram-v2-L25IHNXF-ChtKa3P5.js +217 -0
  62. package/dist/site/assets/cose-bilkent-JH36ORCC-kNFKiV_g.js +1 -0
  63. package/dist/site/assets/cover-blue-Bh8Xp4T5.avif +0 -0
  64. package/dist/site/assets/cover-blue-mobile-YcuYIg0I.avif +0 -0
  65. package/dist/site/assets/cover-green-By13JjUx.avif +0 -0
  66. package/dist/site/assets/cover-green-mobile-BNTgNt7v.avif +0 -0
  67. package/dist/site/assets/cover-red-mobile-DHOCz3wI.avif +0 -0
  68. package/dist/site/assets/cover-red-qvZEk3PI.avif +0 -0
  69. package/dist/site/assets/cynefin-EF2NZ3EQ-lzZSPZ0f.js +1 -0
  70. package/dist/site/assets/cynefinDiagram-L36ESFBY-sq_xQVi7.js +62 -0
  71. package/dist/site/assets/cytoscape.esm-nTrd5EVq.js +321 -0
  72. package/dist/site/assets/d3-scale-CElPUUud.js +1 -0
  73. package/dist/site/assets/d3-selection-DIUqvUVB.js +1 -0
  74. package/dist/site/assets/dagre-SPEB5RXH-DqoO0sGc.js +4 -0
  75. package/dist/site/assets/diagram-3B7GL73J-M26Lh06i.js +200 -0
  76. package/dist/site/assets/diagram-DNEMPZML-ZZQRAEJq.js +24 -0
  77. package/dist/site/assets/diagram-L3MUGCDN-CjsMyH3f.js +41 -0
  78. package/dist/site/assets/diagram-LA4NIPWU-B1tD-62P.js +24 -0
  79. package/dist/site/assets/diagram-MHCOC4E2-B0jKQ9HQ.js +3 -0
  80. package/dist/site/assets/diagram-XPFHEONP-BelYHEVT.js +30 -0
  81. package/dist/site/assets/dist-ppXrr7du.js +1 -0
  82. package/dist/site/assets/ebnfDiagram-UZSYDL2S-BlM2_kcX.js +1 -0
  83. package/dist/site/assets/elk-XV6XMXQE-DGFBMQyB.js +27 -0
  84. package/dist/site/assets/erDiagram-EYBAPDEH-BYeh4LuC.js +99 -0
  85. package/dist/site/assets/es-YYQGP5MR.js +2 -0
  86. package/dist/site/assets/eventmodeling-K75KTNOO-CJHo0aIb.js +1 -0
  87. package/dist/site/assets/favicon-C9YRygge.png +0 -0
  88. package/dist/site/assets/flowDiagram-MALGAFMO-4xnU_Dv7.js +1 -0
  89. package/dist/site/assets/ganttDiagram-23REXITY-BlApGIuJ.js +292 -0
  90. package/dist/site/assets/gitGraph-VSP46ZUC-Dwcg1pSB.js +1 -0
  91. package/dist/site/assets/gitGraphDiagram-STJD7YCW-BJXE5oWq.js +106 -0
  92. package/dist/site/assets/graphlib-DS17s2tU.js +1 -0
  93. package/dist/site/assets/index-D4HJC4TW.js +2 -0
  94. package/dist/site/assets/index-fT8cj2JB.css +1 -0
  95. package/dist/site/assets/info-OHQRW6UA-BEW1vxOL.js +1 -0
  96. package/dist/site/assets/infoDiagram-KBXO4MBG-DseLOSIt.js +2 -0
  97. package/dist/site/assets/ishikawaDiagram-M35NCXHK-D3nXJVhq.js +70 -0
  98. package/dist/site/assets/journeyDiagram-OPLOXDXO-Dwmf_2yx.js +139 -0
  99. package/dist/site/assets/jsxRuntime-WpZ1bTm4.js +1 -0
  100. package/dist/site/assets/kanban-definition-BZKZHSQY-D8hRo5NB.js +89 -0
  101. package/dist/site/assets/katex-MEuSR36T.js +257 -0
  102. package/dist/site/assets/mermaid-parser.core-CRzqu-zz.js +7 -0
  103. package/dist/site/assets/mindmap-definition-I2QAS2VK-C_KsVBJE.js +98 -0
  104. package/dist/site/assets/mobile-cabinet-BUr9vtlo.avif +0 -0
  105. package/dist/site/assets/mobile-cabinet-sm-pauJUfRH.avif +0 -0
  106. package/dist/site/assets/mobile-paper-DF0CuLes.avif +0 -0
  107. package/dist/site/assets/mobile-paper-sm-77eJHX6h.avif +0 -0
  108. package/dist/site/assets/open-nWGD2hyb.glb +0 -0
  109. package/dist/site/assets/packet-JDAUHWVQ-vLUg6kma.js +1 -0
  110. package/dist/site/assets/pegDiagram-FD4XPPHP-CsAJzLE2.js +1 -0
  111. package/dist/site/assets/pie-XZMESJXO-C5OiZ5I_.js +1 -0
  112. package/dist/site/assets/pieDiagram-J4AKIIQI-C0Z-TuM1.js +39 -0
  113. package/dist/site/assets/quadrantDiagram-XTYBLID2-BfwNOGbp.js +7 -0
  114. package/dist/site/assets/radar-ABXABTNO-DlOAhNu8.js +1 -0
  115. package/dist/site/assets/railroad-I3PHUGI6-BUpxKd8T.js +1 -0
  116. package/dist/site/assets/railroad-abnf-LNEFI6M7-BsS9Vk34.js +1 -0
  117. package/dist/site/assets/railroad-ebnf-DWYD2UWJ-Cx8TyVDx.js +1 -0
  118. package/dist/site/assets/railroad-peg-JR7BVNR7-C2s9CJ5A.js +1 -0
  119. package/dist/site/assets/railroadDiagram-MRQ6NCDL-nXlyo8yi.js +1 -0
  120. package/dist/site/assets/requirementDiagram-Y7LWUY3S-C_jfLPMO.js +84 -0
  121. package/dist/site/assets/resting-amber-BSjsErIg.avif +0 -0
  122. package/dist/site/assets/resting-black-DDQ4XMJI.avif +0 -0
  123. package/dist/site/assets/resting-blue-DDOT8IQ8.avif +0 -0
  124. package/dist/site/assets/resting-green-DkRrV8eX.avif +0 -0
  125. package/dist/site/assets/resting-ivory-CEqoG5yI.avif +0 -0
  126. package/dist/site/assets/resting-plum-B-8tkSmP.avif +0 -0
  127. package/dist/site/assets/resting-red-D0hLpMpz.avif +0 -0
  128. package/dist/site/assets/resting-slate-CH8Z_Rky.avif +0 -0
  129. package/dist/site/assets/resting-teal-CGt6jFmT.avif +0 -0
  130. package/dist/site/assets/resting-walnut-t3WgHgUO.avif +0 -0
  131. package/dist/site/assets/rough.esm-Dy-Kn_BL.js +1 -0
  132. package/dist/site/assets/sankeyDiagram-WGJFYUXA-DiLclJAZ.js +40 -0
  133. package/dist/site/assets/search-stage-B8cH1AE_.avif +0 -0
  134. package/dist/site/assets/search-stage-mobile-BZ58ew4F.avif +0 -0
  135. package/dist/site/assets/sequenceDiagram-5NDRBG5M-B9sM-5ZJ.js +169 -0
  136. package/dist/site/assets/sizeCapture-INFHLROL-3uHXrFqA.js +1 -0
  137. package/dist/site/assets/stateDiagram-v2-FJ4FJNEA-Dkis5g_v.js +291 -0
  138. package/dist/site/assets/swimlanes-UMQ2AFYF-DB6kjOv7.js +1 -0
  139. package/dist/site/assets/swimlanesDiagram-OMPLPG4O-IMFdS7Zf.js +8 -0
  140. package/dist/site/assets/three-core-B1q6MRTI.js +5 -0
  141. package/dist/site/assets/timeline-definition-SEUHKTQE-2CMebGt0.js +120 -0
  142. package/dist/site/assets/treeView-D4JQ5SDB-BZ52mw7_.js +1 -0
  143. package/dist/site/assets/treemap-SAJKECNS-C-pobFuU.js +1 -0
  144. package/dist/site/assets/usecaseDiagram-AFA6YXN4-BACx6ppv.js +328 -0
  145. package/dist/site/assets/vennDiagram-NNMJR3RB-B8NLdumI.js +34 -0
  146. package/dist/site/assets/wardley-7MLQ67FV-BWJ-dzdI.js +1 -0
  147. package/dist/site/assets/wardleyDiagram-S7YFUSEH-WKBfzjEM.js +78 -0
  148. package/dist/site/assets/xychartDiagram-GGNKY7IX-BUciDj2U.js +7 -0
  149. package/dist/site/index.html +15 -0
  150. package/dist/types/index.d.ts +163 -0
  151. package/package.json +51 -28
  152. package/dist/grimoire3d.js +0 -504
  153. package/dist/grimoire3d.umd.cjs +0 -27
package/README.md CHANGED
@@ -1,149 +1,49 @@
1
- # grimoire3d
1
+ # Grimoire3D
2
2
 
3
- [![npm version](https://badge.fury.io/js/grimoire3d.svg)](https://badge.fury.io/js/grimoire3d)
4
- [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
3
+ Turn Markdown into 3D books you can open and flip through in a browser.
5
4
 
6
- A 3D magical book documentation generator. Transform your docs into an interactive grimoire with realistic page-flip animations.
5
+ [![npm version](https://img.shields.io/npm/v/grimoire3d)](https://www.npmjs.com/package/grimoire3d)
7
6
 
8
- ## What is this?
7
+ ![A Markdown chapter is added under docs, then opened and paged through from the Grimoire3D bookshelf](docs/book-experience/quick-start.gif)
9
8
 
10
- Grimoire3D transforms your Markdown documentation into an interactive 3D book. Perfect for:
9
+ [Read the documentation](https://kkm-horikawa.github.io/grimoire3d/)
11
10
 
12
- - Project documentation
13
- - Design specifications
14
- - Technical notes
15
- - Portfolios
16
- - Tutorials
11
+ ## Install
17
12
 
18
- ## Features
13
+ Use a maintained Node.js 22, 24, or 26 release. Install Grimoire3D from npm in the project where you want to write your books. If the project has no `package.json`, run `npm init -y` first.
19
14
 
20
- - Realistic 3D page-flip animation
21
- - Markdown rendering
22
- - HTML support
23
- - Mermaid diagram support (planned)
24
- - Multiple themes
25
- - Static site generation
26
- - Zero-config setup
27
-
28
- ## Installation
29
-
30
- ```bash
31
- npm install grimoire3d
32
- # or
33
- pnpm add grimoire3d
34
- # or
35
- yarn add grimoire3d
15
+ ```sh
16
+ npm install --save-dev grimoire3d
36
17
  ```
37
18
 
38
- ## Quick Start
39
-
40
- ### 1. Create your docs directory
41
-
42
- ```
43
- my-project/
44
- ├── grimoire.yml # Configuration (optional)
45
- └── docs/
46
- ├── index.md # Cover page
47
- ├── 01-overview.md
48
- ├── 02-features.md
49
- └── assets/
50
- └── diagram.png
51
- ```
19
+ ## Write and preview
52
20
 
53
- ### 2. Write your content
21
+ Create `docs/field-notes/index.md`.
54
22
 
55
23
  ```markdown
56
- <!-- docs/index.md -->
57
- # My Project
24
+ # Field Notes
58
25
 
59
- Welcome to the documentation.
60
-
61
- ## Overview
62
-
63
- This is an amazing project...
26
+ This is my first 3D book.
64
27
  ```
65
28
 
66
- ### 3. Start the dev server
29
+ Add Markdown files in the same folder for more chapters. Add folders directly under `docs/` for more books.
67
30
 
68
- ```bash
31
+ ```sh
69
32
  npx grimoire3d serve
70
33
  ```
71
34
 
72
- ### 4. Build for production
73
-
74
- ```bash
75
- npx grimoire3d build
76
- ```
35
+ Open the URL printed in the terminal. The preview updates when you save.
77
36
 
78
- ## Configuration
37
+ ![Workflow from Markdown files to a local bookshelf and a static site in dist](docs/book-experience/workflow.avif)
79
38
 
80
- Create a `grimoire.yml` file in your project root:
39
+ ## Build and publish
81
40
 
82
- ```yaml
83
- title: "My Project Documentation"
84
- theme: "vintage-red" # or "modern-dark", "paper-white"
85
- pages:
86
- - index.md
87
- - 01-overview.md
88
- - 02-features.md
89
- # Omit 'pages' to auto-detect all .md files
90
- ```
91
-
92
- ## Using as a React Component
93
-
94
- ```tsx
95
- import { BookViewer } from "grimoire3d/components";
96
-
97
- const pages = [
98
- {
99
- id: "cover",
100
- title: "Cover",
101
- front: <CoverPage />,
102
- back: <AboutPage />,
103
- tabColor: "#E57373",
104
- tabLabel: "Cover",
105
- },
106
- // ... more pages
107
- ];
108
-
109
- function App() {
110
- return <BookViewer pages={pages} />;
111
- }
41
+ ```sh
42
+ npx grimoire3d build
112
43
  ```
113
44
 
114
- ## Themes
115
-
116
- | Theme | Description |
117
- |-------|-------------|
118
- | `vintage-red` | Classic red leather book cover |
119
- | `modern-dark` | Sleek dark mode |
120
- | `paper-white` | Clean minimal design |
121
- | `forest-green` | Nature-inspired |
122
-
123
- ## Roadmap
124
-
125
- - [ ] v0.1.0 - MVP with basic page-flip and Markdown support
126
- - [ ] v0.2.0 - Mermaid diagrams and code highlighting
127
- - [ ] v0.3.0 - CLI for static site generation
128
- - [ ] v0.4.0 - Theme customization and plugins
129
-
130
- ## Documentation
131
-
132
- - [Architecture & Design Decisions](docs/ARCHITECTURE.md)
133
- - [Glossary of Terms](docs/GLOSSARY.md)
134
- - [Contributing Guide](CONTRIBUTING.md)
135
-
136
- ## Requirements
137
-
138
- - Node.js 22+
139
- - React 19+
140
-
141
- ## License
142
-
143
- MIT License. See [LICENSE](LICENSE) for details.
45
+ Deploy the contents of `dist/` to any static host, including Cloudflare Pages and GitHub Pages. Use `--out-dir site` to choose a different output directory.
144
46
 
145
- ## Inspiration
47
+ For chapter links, formatting, media, Mermaid, cover styles, locale, and SEO, see the [Grimoire3D documentation](https://kkm-horikawa.github.io/grimoire3d/).
146
48
 
147
- - Ancient grimoires and magical tomes
148
- - Vintage technical manuals
149
- - React component libraries
49
+ [Contributing](CONTRIBUTING.md) · [MIT License](LICENSE)
package/cli/cli.js ADDED
@@ -0,0 +1,350 @@
1
+ #!/usr/bin/env node
2
+
3
+ import { createReadStream, watch } from "node:fs";
4
+ import {
5
+ copyFile,
6
+ cp,
7
+ lstat,
8
+ mkdir,
9
+ mkdtemp,
10
+ readdir,
11
+ readFile,
12
+ rename,
13
+ rm,
14
+ stat,
15
+ writeFile,
16
+ } from "node:fs/promises";
17
+ import { createServer } from "node:http";
18
+ import {
19
+ basename,
20
+ dirname,
21
+ isAbsolute,
22
+ join,
23
+ relative,
24
+ resolve,
25
+ sep,
26
+ } from "node:path";
27
+ import { fileURLToPath } from "node:url";
28
+ import { parseArgs } from "node:util";
29
+ import { contentType, lookup } from "mime-types";
30
+ import { readLibrary, readSettings } from "./content.js";
31
+ import { readHeadFile } from "./head-file.js";
32
+ import { previewHead, writeStaticPages } from "./static-pages.js";
33
+
34
+ const template = fileURLToPath(new URL("../dist/site/", import.meta.url));
35
+ const marker = ".grimoire3d-output.json";
36
+
37
+ function json(value) {
38
+ return JSON.stringify(value);
39
+ }
40
+
41
+ async function listFiles(root, directory = "") {
42
+ const entries = await readdir(join(root, directory), { withFileTypes: true });
43
+ const results = [];
44
+ for (const entry of entries) {
45
+ const path = join(directory, entry.name);
46
+ if (entry.isDirectory()) results.push(...(await listFiles(root, path)));
47
+ else results.push(path.split(sep).join("/"));
48
+ }
49
+ return results.sort();
50
+ }
51
+
52
+ async function existingOutput(output, locale) {
53
+ const info = await lstat(output).catch((error) => {
54
+ if (error.code !== "ENOENT") throw error;
55
+ return undefined;
56
+ });
57
+ if (!info) return false;
58
+ const files = info.isDirectory() ? await listFiles(output) : ["unknown"];
59
+ if (!files.length) return true;
60
+ const previous = await readFile(join(output, marker), "utf8")
61
+ .then(JSON.parse, () => undefined)
62
+ .catch(() => undefined);
63
+ if (
64
+ Array.isArray(previous) &&
65
+ files
66
+ .filter((name) => name !== marker)
67
+ .every((file) => previous.includes(file))
68
+ )
69
+ return true;
70
+ throw new Error(
71
+ locale === "ja"
72
+ ? `${output} には既存のファイルがあります。--out-dir で空の出力先を指定してください。`
73
+ : `${output} contains existing files. Use --out-dir to select an empty directory.`
74
+ );
75
+ }
76
+
77
+ function serializedLibrary(library) {
78
+ return new Map([
79
+ ["library.json", json(library.manifest)],
80
+ ...library.books.map((book) => [`books/${book.id}.json`, json(book)]),
81
+ ]);
82
+ }
83
+
84
+ async function writeStaticSite(cwd, outDir, library, headMarkup) {
85
+ const output = resolve(cwd, outDir);
86
+ const { locale } = library.manifest;
87
+ const exists = await existingOutput(output, locale);
88
+ const parent = dirname(output);
89
+ await mkdir(parent, { recursive: true });
90
+ const temporary = await mkdtemp(join(parent, ".grimoire3d-"));
91
+ const staging = join(temporary, "site");
92
+ const backup = join(temporary, "previous");
93
+ let preserveBackup = false;
94
+ try {
95
+ await cp(template, staging, { recursive: true });
96
+ for (const [name, content] of serializedLibrary(library)) {
97
+ const path = join(staging, name);
98
+ await mkdir(dirname(path), { recursive: true });
99
+ await writeFile(path, content);
100
+ }
101
+ for (const [name, source] of library.assets) {
102
+ const path = join(staging, "content", name);
103
+ await mkdir(dirname(path), { recursive: true });
104
+ await copyFile(source, path);
105
+ }
106
+ await writeStaticPages(template, staging, library, headMarkup);
107
+ await writeFile(join(staging, marker), json(await listFiles(staging)));
108
+ if (exists) await rename(output, backup);
109
+ try {
110
+ await rename(staging, output);
111
+ } catch (error) {
112
+ if (exists) {
113
+ preserveBackup = true;
114
+ await rename(backup, output);
115
+ preserveBackup = false;
116
+ }
117
+ throw error;
118
+ }
119
+ } finally {
120
+ if (!preserveBackup) await rm(temporary, { recursive: true, force: true });
121
+ }
122
+ return output;
123
+ }
124
+
125
+ function showIssues(library) {
126
+ if (!library.issues.length) return;
127
+ const label =
128
+ library.manifest.locale === "ja"
129
+ ? "参照先が見つかりません"
130
+ : "Unresolved reference";
131
+ for (const issue of library.issues) console.error(`${label}: ${issue}`);
132
+ }
133
+
134
+ function snapshot(library) {
135
+ return {
136
+ files: serializedLibrary(library),
137
+ manifest: library.manifest,
138
+ assets: library.assets,
139
+ error: null,
140
+ };
141
+ }
142
+
143
+ function serve(cwd, port, initial) {
144
+ let current = snapshot(initial);
145
+ let timer;
146
+ let changes = 0;
147
+ const clients = new Set();
148
+ const notify = () => {
149
+ for (const client of clients) client.write("event: update\ndata: {}\n\n");
150
+ };
151
+ async function refresh() {
152
+ const revision = ++changes;
153
+ try {
154
+ const library = await readLibrary(cwd, await readSettings(cwd));
155
+ if (revision !== changes) return;
156
+ current = snapshot(library);
157
+ showIssues(library);
158
+ } catch (error) {
159
+ if (revision !== changes) return;
160
+ current = { ...current, error: error.message };
161
+ console.error(error.message);
162
+ }
163
+ notify();
164
+ }
165
+ function schedule() {
166
+ clearTimeout(timer);
167
+ timer = setTimeout(() => void refresh(), 140);
168
+ }
169
+ const watchers = [
170
+ watch(join(cwd, "docs"), { recursive: true }, schedule),
171
+ watch(cwd, (_event, name) => {
172
+ if (name === "grimoire.yml") schedule();
173
+ }),
174
+ ];
175
+
176
+ const server = createServer(async (request, response) => {
177
+ try {
178
+ const url = new URL(request.url, "http://localhost");
179
+ const name = decodeURIComponent(url.pathname.slice(1)) || "index.html";
180
+ if (name === "__grimoire_events") {
181
+ response.writeHead(200, {
182
+ "Content-Type": "text/event-stream",
183
+ "Cache-Control": "no-cache",
184
+ });
185
+ response.write(": connected\n\n");
186
+ clients.add(response);
187
+ response.on("close", () => clients.delete(response));
188
+ return;
189
+ }
190
+ if (current.error && name === "library.json") {
191
+ response
192
+ .writeHead(422, { "Content-Type": "application/json" })
193
+ .end(json({ error: current.error }));
194
+ return;
195
+ }
196
+ const content = current.files.get(name);
197
+ if (content !== undefined) {
198
+ response
199
+ .writeHead(200, {
200
+ "Content-Type": "application/json",
201
+ "Cache-Control": "no-store",
202
+ })
203
+ .end(content);
204
+ return;
205
+ }
206
+ const requested = resolve(template, name);
207
+ if (
208
+ name.startsWith("content/") &&
209
+ !current.assets.has(name.slice("content/".length))
210
+ ) {
211
+ response.writeHead(404).end();
212
+ return;
213
+ }
214
+ const asset = current.assets.get(name.slice("content/".length));
215
+ const diff = relative(template, requested);
216
+ if (diff === ".." || diff.startsWith(`..${sep}`) || isAbsolute(diff)) {
217
+ response.writeHead(404).end();
218
+ return;
219
+ }
220
+ const path = name.startsWith("content/") ? asset : requested;
221
+ const file = await stat(path);
222
+ if (!file.isFile()) {
223
+ response.writeHead(404).end();
224
+ return;
225
+ }
226
+ const mediaType = contentType(lookup(path) || "application/octet-stream");
227
+ if (name === "index.html") {
228
+ const html = await readFile(path, "utf8");
229
+ response.writeHead(200, {
230
+ "Content-Type": mediaType,
231
+ "Cache-Control": "no-store",
232
+ });
233
+ response.end(
234
+ html
235
+ .replace(
236
+ '<html lang="en">',
237
+ `<html lang="${current.manifest.locale}">`
238
+ )
239
+ .replace("</head>", () => `${previewHead(current.manifest)}</head>`)
240
+ );
241
+ return;
242
+ }
243
+ const headers = {
244
+ "Content-Type": mediaType,
245
+ "Cache-Control": "no-cache",
246
+ "Content-Length": file.size,
247
+ };
248
+ let status = 200;
249
+ let slice;
250
+ if (typeof mediaType === "string" && mediaType.startsWith("video/")) {
251
+ headers["Accept-Ranges"] = "bytes";
252
+ const range = /^bytes=(\d*)-(\d*)$/.exec(request.headers.range ?? "");
253
+ if (range) {
254
+ const [, from, to] = range;
255
+ const start = from
256
+ ? Number(from)
257
+ : Math.max(0, file.size - Number(to));
258
+ const end =
259
+ from && to ? Math.min(Number(to), file.size - 1) : file.size - 1;
260
+ if (!Number.isSafeInteger(start) || start > end) {
261
+ response
262
+ .writeHead(416, {
263
+ "Accept-Ranges": "bytes",
264
+ "Content-Range": `bytes */${file.size}`,
265
+ })
266
+ .end();
267
+ return;
268
+ }
269
+ status = 206;
270
+ slice = { start, end };
271
+ headers["Content-Length"] = end - start + 1;
272
+ headers["Content-Range"] = `bytes ${start}-${end}/${file.size}`;
273
+ }
274
+ }
275
+ response.writeHead(status, headers);
276
+ if (request.method === "HEAD") response.end();
277
+ else
278
+ createReadStream(path, slice)
279
+ .on("error", () => response.destroy())
280
+ .pipe(response);
281
+ } catch (error) {
282
+ if (response.headersSent) response.destroy();
283
+ else response.writeHead(error.code === "ENOENT" ? 404 : 400).end();
284
+ }
285
+ });
286
+ const stopWatchers = () => {
287
+ clearTimeout(timer);
288
+ for (const watcher of watchers) watcher.close();
289
+ };
290
+ server.on("error", (error) => {
291
+ stopWatchers();
292
+ console.error(error.message);
293
+ process.exitCode = 1;
294
+ });
295
+ server.listen(port, "127.0.0.1", () => {
296
+ const label = initial.manifest.locale === "ja" ? "プレビュー" : "Preview";
297
+ console.log(`${label}: http://127.0.0.1:${server.address().port}/`);
298
+ });
299
+ }
300
+
301
+ async function main() {
302
+ const {
303
+ positionals: [command],
304
+ values,
305
+ } = parseArgs({
306
+ allowPositionals: true,
307
+ options: {
308
+ help: { type: "boolean", short: "h" },
309
+ port: { type: "string" },
310
+ "out-dir": { type: "string" },
311
+ },
312
+ });
313
+ if (!command || values.help) {
314
+ console.log(
315
+ "grimoire3d serve [--port 3000]\ngrimoire3d build [--out-dir dist]"
316
+ );
317
+ return;
318
+ }
319
+ if (!["serve", "build"].includes(command))
320
+ throw new Error(`Unknown command: ${command}. See --help.`);
321
+ const cwd = process.cwd();
322
+ const settings = await readSettings(cwd);
323
+ const library = await readLibrary(cwd, settings);
324
+ showIssues(library);
325
+ if (command === "build") {
326
+ const output = await writeStaticSite(
327
+ cwd,
328
+ values["out-dir"] ?? settings.outDir ?? "dist",
329
+ library,
330
+ await readHeadFile(cwd, settings.headFile)
331
+ );
332
+ const label = settings.locale === "ja" ? "書き出し先" : "Built to";
333
+ console.log(`${label}: ${basename(output)}/ (${output})`);
334
+ return;
335
+ }
336
+ const port = Number(values.port ?? 3000);
337
+ if (!Number.isInteger(port) || port < 0 || port > 65535) {
338
+ throw new Error(
339
+ settings.locale === "ja"
340
+ ? "--port は 0 から 65535 の整数にしてください。"
341
+ : "--port must be an integer from 0 to 65535."
342
+ );
343
+ }
344
+ serve(cwd, port, library);
345
+ }
346
+
347
+ main().catch((error) => {
348
+ console.error(error.message);
349
+ process.exitCode = 1;
350
+ });