@diagc/cli 1.4.0 → 1.5.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.
@@ -4,7 +4,7 @@
4
4
  <meta charset="UTF-8" />
5
5
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
6
6
  <title>diagc studio</title>
7
- <script type="module" crossorigin src="/assets/index-B4EbTBLO.js"></script>
7
+ <script type="module" crossorigin src="/assets/index-DRsUukzt.js"></script>
8
8
  <link rel="stylesheet" crossorigin href="/assets/index-DzVDK5uD.css">
9
9
  </head>
10
10
  <body>
@@ -12,6 +12,11 @@ export interface DiagramEntry {
12
12
  * `diagramsDir`, compiled TS artifacts from `artifactsDir`. A source shadows its
13
13
  * artifact so unsaved-compile staleness never shows. */
14
14
  export declare function listDiagramModels(diagramsDir: string, artifactsDir: string): Promise<HandlerResult>;
15
+ /** The diagram `name` as the studio's list shows it, or undefined when the list has
16
+ * no such name. Looking the name up in the listing, rather than checking its
17
+ * spelling, is what keeps it inside the two directories: a compiled diagram's name
18
+ * comes from its `.diagram.ts` file and need not pass `isSafeName`. */
19
+ export declare function diagramAsShown(diagramsDir: string, artifactsDir: string, name: string): Promise<DiagramEntry | undefined>;
15
20
  /** the JSON source (+ sibling layout and drawings) of a designer-owned diagram — the studio
16
21
  * reads these directly so it never depends on a compile watcher for its own files */
17
22
  export declare function readDiagram(diagramsDir: string, name: string): Promise<HandlerResult>;
@@ -16,32 +16,45 @@ export async function listDiagramModels(diagramsDir, artifactsDir) {
16
16
  const artifactNames = await walkDiagramJson(artifactsDir);
17
17
  const all = [...new Set([...sourceNames, ...artifactNames])].sort();
18
18
  const diagrams = [];
19
- for (const name of all) {
20
- const isSource = sourceNames.has(name);
21
- // Every read and save refuses a name isSafeName refuses, so such a source is shown but not offered for editing.
22
- const editable = isSource && isSafeName(name);
23
- const file = isSource
24
- ? path.join(diagramsDir, `${name}.diagram.json`)
25
- : path.join(artifactsDir, `${name}.diagram.json`);
26
- let model = null;
27
- const issues = [];
28
- if (isSource && !editable) {
29
- issues.push({
30
- message: `'${name}' is read-only here: the studio saves names of lowercase letters, digits, '-' and '/', none ending in /rename, /eject or /composed. Rename the file to edit it.`,
31
- });
32
- }
33
- try {
34
- model = JSON.parse(await readFile(file, 'utf8'));
35
- }
36
- catch {
37
- issues.push({ message: `Could not read model for '${name}'` });
38
- }
39
- if (isSource && hasIncludes(model))
40
- model = await composedForList(model, file, diagramsDir, issues);
41
- diagrams.push({ name, model, issues, editable });
42
- }
19
+ for (const name of all)
20
+ diagrams.push(await loadEntry(diagramsDir, artifactsDir, name, sourceNames.has(name)));
43
21
  return { status: 200, body: { diagrams } };
44
22
  }
23
+ /** The diagram `name` as the studio's list shows it, or undefined when the list has
24
+ * no such name. Looking the name up in the listing, rather than checking its
25
+ * spelling, is what keeps it inside the two directories: a compiled diagram's name
26
+ * comes from its `.diagram.ts` file and need not pass `isSafeName`. */
27
+ export async function diagramAsShown(diagramsDir, artifactsDir, name) {
28
+ if ((await walkDiagramJson(diagramsDir)).includes(name))
29
+ return loadEntry(diagramsDir, artifactsDir, name, true);
30
+ if ((await walkDiagramJson(artifactsDir)).includes(name))
31
+ return loadEntry(diagramsDir, artifactsDir, name, false);
32
+ return undefined;
33
+ }
34
+ /** One listed diagram: its JSON source with includes expanded, or else its artifact. */
35
+ async function loadEntry(diagramsDir, artifactsDir, name, isSource) {
36
+ // Every read and save refuses a name isSafeName refuses, so such a source is shown but not offered for editing.
37
+ const editable = isSource && isSafeName(name);
38
+ const file = isSource
39
+ ? path.join(diagramsDir, `${name}.diagram.json`)
40
+ : path.join(artifactsDir, `${name}.diagram.json`);
41
+ let model = null;
42
+ const issues = [];
43
+ if (isSource && !editable) {
44
+ issues.push({
45
+ message: `'${name}' is read-only here: the studio saves names of lowercase letters, digits, '-' and '/', none ending in /rename, /eject or /composed. Rename the file to edit it.`,
46
+ });
47
+ }
48
+ try {
49
+ model = JSON.parse(await readFile(file, 'utf8'));
50
+ }
51
+ catch {
52
+ issues.push({ message: `Could not read model for '${name}'` });
53
+ }
54
+ if (isSource && hasIncludes(model))
55
+ model = await composedForList(model, file, diagramsDir, issues);
56
+ return { name, model, issues, editable };
57
+ }
45
58
  /** `model` with its includes expanded for the list, or `model` itself when they
46
59
  * cannot be, with what went wrong added to `issues`. */
47
60
  async function composedForList(model, file, diagramsDir, issues) {
@@ -1,4 +1,5 @@
1
1
  import type { IncomingMessage, ServerResponse } from 'node:http';
2
+ import type { PageSources } from './pages.js';
2
3
  /** The handler module, passed in rather than imported: the Vite adapter loads it
3
4
  * through the dev pipeline, the packaged server imports it directly. */
4
5
  export type Handlers = typeof import('./handlers.js');
@@ -6,6 +7,8 @@ export type Handlers = typeof import('./handlers.js');
6
7
  export interface ApiContext {
7
8
  diagramsDir: string;
8
9
  artifactsDir: string;
10
+ /** what the page route builds from; a host without it answers that route 501 */
11
+ pages?: PageSources;
9
12
  }
10
13
  /** A request in transport-neutral terms: no `IncomingMessage`, so a host with
11
14
  * no HTTP objects at all (the Obsidian in-process bridge) can still drive a
@@ -2,6 +2,7 @@ export { MAX_ASSET_BYTES, readAsset, saveAsset } from './assets.js';
2
2
  export { ejectDiagramSource, listDiagramModels, readComposedDiagram, readDiagram, renameDiagram, saveDiagram, type DiagramEntry, } from './diagrams.js';
3
3
  export { walkDiagramJson, walkFiles } from './files.js';
4
4
  export { readLibrary, saveLibrary } from './library.js';
5
+ export { exportPage } from './pages.js';
5
6
  export type { HandlerResult } from './result.js';
6
7
  export { listDrawings, listLayouts, saveDrawings, saveLayout } from './sidecars.js';
7
8
  export { isSafeName } from '../names.js';
@@ -6,6 +6,7 @@ export { MAX_ASSET_BYTES, readAsset, saveAsset } from './assets.js';
6
6
  export { ejectDiagramSource, listDiagramModels, readComposedDiagram, readDiagram, renameDiagram, saveDiagram, } from './diagrams.js';
7
7
  export { walkDiagramJson, walkFiles } from './files.js';
8
8
  export { readLibrary, saveLibrary } from './library.js';
9
+ export { exportPage } from './pages.js';
9
10
  export { listDrawings, listLayouts, saveDrawings, saveLayout } from './sidecars.js';
10
11
  // The name rule every route checks, for the hosts and tests that reach it here.
11
12
  export { isSafeName } from '../names.js';
@@ -0,0 +1,21 @@
1
+ import { type HandlerResult } from './result.js';
2
+ /** What a host builds a diagram's web page from: the viewer page `publish` stamps
3
+ * models into, and the icon library its `/library/…` pictures are read from. Each
4
+ * host has its own copies (a checkout's build output, a package's `assets/`, the
5
+ * Obsidian plugin's folder), so each says where they are. */
6
+ export interface PageSources {
7
+ shellPath: string;
8
+ libraryDir: string;
9
+ }
10
+ /**
11
+ * The diagram `name` as one self-contained web page: the page `publish` writes for
12
+ * it, built here so the studio can hand it over as a download. The model is the one
13
+ * the studio shows (the saved source, includes expanded, or else the compiled
14
+ * artifact), so the page cannot lag a compile the way an artifact can.
15
+ *
16
+ * Answered as JSON, `{ html, warnings }`, not as raw bytes: what could not be
17
+ * packed in (a missing picture, a malformed drawings sidecar) still leaves a page
18
+ * worth saving, and the studio should say so rather than hand over a quietly
19
+ * broken one.
20
+ */
21
+ export declare function exportPage(diagramsDir: string, artifactsDir: string, sources: PageSources | undefined, name: string): Promise<HandlerResult>;
@@ -0,0 +1,50 @@
1
+ import { access, readFile } from 'node:fs/promises';
2
+ import path from 'node:path';
3
+ import { stampHtml } from '../publish/html.js';
4
+ import { inlineAssets, readSidecars } from '../publish/publish.js';
5
+ import { diagramAsShown } from './diagrams.js';
6
+ import { refuse } from './result.js';
7
+ const existing = async (p) => {
8
+ try {
9
+ await access(p);
10
+ return p;
11
+ }
12
+ catch {
13
+ return undefined;
14
+ }
15
+ };
16
+ /**
17
+ * The diagram `name` as one self-contained web page: the page `publish` writes for
18
+ * it, built here so the studio can hand it over as a download. The model is the one
19
+ * the studio shows (the saved source, includes expanded, or else the compiled
20
+ * artifact), so the page cannot lag a compile the way an artifact can.
21
+ *
22
+ * Answered as JSON, `{ html, warnings }`, not as raw bytes: what could not be
23
+ * packed in (a missing picture, a malformed drawings sidecar) still leaves a page
24
+ * worth saving, and the studio should say so rather than hand over a quietly
25
+ * broken one.
26
+ */
27
+ export async function exportPage(diagramsDir, artifactsDir, sources, name) {
28
+ if (sources === undefined)
29
+ return refuse(501, 'This studio cannot build web pages: its host has no viewer page to build them from.');
30
+ const entry = await diagramAsShown(diagramsDir, artifactsDir, name);
31
+ if (entry === undefined)
32
+ return refuse(404, `No diagram '${name}'`);
33
+ if (entry.model === null)
34
+ return { status: 500, body: { issues: entry.issues } };
35
+ let shell;
36
+ try {
37
+ shell = await readFile(sources.shellPath, 'utf8');
38
+ }
39
+ catch {
40
+ return refuse(500, `No viewer page at ${sources.shellPath} — in a checkout, build it with \`pnpm build:cli\`.`);
41
+ }
42
+ const warnings = [];
43
+ const warn = (line) => void warnings.push(line);
44
+ const sidecar = (suffix) => existing(path.join(diagramsDir, `${name}.${suffix}.json`));
45
+ const [layoutPath, drawingsPath] = await Promise.all([sidecar('layout'), sidecar('drawings')]);
46
+ const sidecars = await readSidecars({ name, layoutPath, drawingsPath }, warn);
47
+ const assets = { libraryDir: sources.libraryDir, assetsDir: path.join(diagramsDir, 'assets'), warn };
48
+ const model = await inlineAssets(entry.model, assets, new Map(), `diagram "${name}"`);
49
+ return { status: 200, body: { html: stampHtml(shell, { model, ...sidecars }), warnings } };
50
+ }
@@ -1,3 +1,4 @@
1
+ import type { PageSources } from './pages.js';
1
2
  type Handlers = typeof import('./handlers.js');
2
3
  /** One route handler's result: handlers' JSON envelope plus readAsset's
3
4
  * optional `bytes`/`contentType`, which the wrapper streams raw. */
@@ -10,6 +11,7 @@ export interface RouteCtx {
10
11
  contentType?: string;
11
12
  diagramsDir: string;
12
13
  artifactsDir: string;
14
+ pages?: PageSources;
13
15
  }
14
16
  export type BodyMode = 'none' | 'json' | 'raw';
15
17
  export interface Route {
@@ -74,6 +74,12 @@ export const ROUTES = [
74
74
  : h.saveDrawings(c.diagramsDir, name, c.body);
75
75
  },
76
76
  },
77
+ // --- pages: a diagram as one self-contained web page, for the studio to download ---
78
+ {
79
+ method: 'GET',
80
+ pattern: /^\/api\/pages\/(.+)$/,
81
+ handler: (h, c) => h.exportPage(c.diagramsDir, c.artifactsDir, c.pages, decodeURIComponent(c.match[1] ?? '')),
82
+ },
77
83
  ];
78
84
  /** The route matching `method` + `url`, or undefined. First match wins. */
79
85
  export function matchRoute(method, url) {
@@ -1,4 +1,5 @@
1
- import type { DiagramModel } from '@diagc/core/internal';
1
+ import type { DiagramModel, LayoutOverlay, Drawings } from '@diagc/core/internal';
2
+ import { type DiscoveredDiagram } from './discover.js';
2
3
  import type { PictureLook } from './snapshot.js';
3
4
  export interface PublishOptions {
4
5
  srcDir: string;
@@ -34,6 +35,19 @@ export interface PublishResult {
34
35
  * diagram in the warnings for refs it has to leave as they are.
35
36
  */
36
37
  export declare function inlineAssets(model: DiagramModel, opts: Pick<PublishOptions, 'libraryDir' | 'assetsDir' | 'warn'>, cache: Map<string, Buffer>, label: string): Promise<DiagramModel>;
38
+ /** What a page carries beside its model. */
39
+ export interface PageSidecars {
40
+ layout?: LayoutOverlay;
41
+ drawings?: Drawings;
42
+ }
43
+ /**
44
+ * A diagram's layout and drawings as its page carries them; a path left out is a
45
+ * sidecar the diagram does not have. A hand-edited drawings sidecar can be valid
46
+ * JSON and still not be a drawings overlay. Stamping it would put shapeless data
47
+ * into a page that has no validator of its own, so it is warned about and dropped
48
+ * — the page still ships, just without ink. Unparseable JSON throws.
49
+ */
50
+ export declare function readSidecars(d: Pick<DiscoveredDiagram, 'name' | 'layoutPath' | 'drawingsPath'>, warn: (line: string) => void): Promise<PageSidecars>;
37
51
  /** One picture of a diagram: its plane (absent = the first) and what goes between
38
52
  * the diagram's name and `.png`. */
39
53
  export interface PlanePicture {
@@ -60,6 +60,26 @@ export async function inlineAssets(model, opts, cache, label) {
60
60
  }
61
61
  return rewriteAssetRefs(model, (ref) => cache.get(ref));
62
62
  }
63
+ /**
64
+ * A diagram's layout and drawings as its page carries them; a path left out is a
65
+ * sidecar the diagram does not have. A hand-edited drawings sidecar can be valid
66
+ * JSON and still not be a drawings overlay. Stamping it would put shapeless data
67
+ * into a page that has no validator of its own, so it is warned about and dropped
68
+ * — the page still ships, just without ink. Unparseable JSON throws.
69
+ */
70
+ export async function readSidecars(d, warn) {
71
+ const out = {};
72
+ if (d.layoutPath !== undefined)
73
+ out.layout = JSON.parse(await readFile(d.layoutPath, 'utf8'));
74
+ if (d.drawingsPath !== undefined) {
75
+ const parsed = JSON.parse(await readFile(d.drawingsPath, 'utf8'));
76
+ if (isDrawings(parsed))
77
+ out.drawings = parsed;
78
+ else
79
+ warn(`publish: ignoring malformed drawings sidecar for diagram "${d.name}" (${d.drawingsPath}); the page ships without ink.`);
80
+ }
81
+ return out;
82
+ }
63
83
  /**
64
84
  * The pictures publish takes of a model, one per plane. The first plane's is
65
85
  * `<name>.png`, the picture docs and READMEs already link; each further plane's
@@ -117,24 +137,11 @@ export async function publishDiagrams(opts) {
117
137
  try {
118
138
  const modelRaw = JSON.parse(await readFile(d.modelPath, 'utf8'));
119
139
  titles.set(d.name, modelRaw.name);
120
- const layout = d.layoutPath !== undefined ? JSON.parse(await readFile(d.layoutPath, 'utf8')) : undefined;
121
- // A hand-edited sidecar can be valid JSON and still not be a drawings
122
- // overlay. Publishing it would stamp shapeless data into a page that has
123
- // no validator of its own, so it is warned about and dropped — the page
124
- // still ships, just without ink. (Unparseable JSON keeps its old
125
- // behaviour: it throws, and the diagram is skipped below.)
126
- let drawings;
127
- if (d.drawingsPath !== undefined) {
128
- const parsed = JSON.parse(await readFile(d.drawingsPath, 'utf8'));
129
- if (isDrawings(parsed))
130
- drawings = parsed;
131
- else
132
- warn(`publish: ignoring malformed drawings sidecar for diagram "${d.name}" (${d.drawingsPath}); the page ships without ink.`);
133
- }
140
+ const sidecars = await readSidecars(d, warn);
134
141
  const inlined = await inlineAssets(modelRaw, opts, cache, `diagram "${d.name}"`);
135
142
  const pagePath = path.join(opts.htmlDir, `${d.name}.html`);
136
143
  await mkdir(path.dirname(pagePath), { recursive: true });
137
- await writeFile(pagePath, stampHtml(shell, { model: inlined, layout, drawings }));
144
+ await writeFile(pagePath, stampHtml(shell, { model: inlined, ...sidecars }));
138
145
  pages.push(pagePath);
139
146
  if (opts.images && opts.renderPng !== undefined) {
140
147
  const run = {
package/dist/serve.d.ts CHANGED
@@ -1,9 +1,12 @@
1
+ import type { PageSources } from './api/pages.js';
1
2
  export declare const contentTypeFor: (file: string) => string;
2
3
  export interface ServeOptions {
3
4
  /** prebuilt studio bundle (index.html + assets + library) */
4
5
  studioDir: string;
5
6
  diagramsDir: string;
6
7
  artifactsDir: string;
8
+ /** what the page route builds from (see `PageSources`) */
9
+ pages?: PageSources;
7
10
  /** first port to try; the server walks upward when one is taken */
8
11
  port?: number;
9
12
  host?: string;
package/dist/serve.js CHANGED
@@ -110,13 +110,13 @@ function listen(server, port, host, attempts = 20) {
110
110
  * itself is an ordinary SPA that only ever talks to `/api/*`, which is what
111
111
  * makes a static bundle behave identically here. */
112
112
  export async function startStudioServer(opts) {
113
- const { studioDir, diagramsDir, artifactsDir } = opts;
113
+ const { studioDir, diagramsDir, artifactsDir, pages } = opts;
114
114
  const host = opts.host ?? '127.0.0.1';
115
115
  const index = path.join(studioDir, 'index.html');
116
116
  const server = createServer((req, res) => {
117
117
  void (async () => {
118
118
  try {
119
- if (await handleApiRequest(req, res, { diagramsDir, artifactsDir }, handlers))
119
+ if (await handleApiRequest(req, res, { diagramsDir, artifactsDir, pages }, handlers))
120
120
  return;
121
121
  const file = resolveStatic(studioDir, req.url ?? '/');
122
122
  if (file === undefined) {
package/dist/studio.js CHANGED
@@ -84,6 +84,7 @@ async function servePackaged(home, env) {
84
84
  studioDir: home.studioDir,
85
85
  diagramsDir: env.DIAGRAMS_DIR,
86
86
  artifactsDir: env.ARTIFACTS_DIR,
87
+ pages: { shellPath: home.viewerShell, libraryDir: home.libraryDir },
87
88
  });
88
89
  console.log(`Studio ready on ${server.url}`);
89
90
  if (env.DIAGRAMS_OPEN === '1')
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@diagc/cli",
3
- "version": "1.4.0",
3
+ "version": "1.5.0",
4
4
  "description": "Author software-architecture diagrams as code, compile them to a validated model, edit them in a local studio, and publish pages and images.",
5
5
  "license": "AGPL-3.0-only",
6
6
  "author": "Bogdan Frankovskyi",
@@ -44,7 +44,7 @@
44
44
  "fast-glob": "^3.3.0",
45
45
  "jiti": "^2.0.0",
46
46
  "playwright-core": "^1.62.0",
47
- "@diagc/core": "1.4.0"
47
+ "@diagc/core": "1.5.0"
48
48
  },
49
49
  "publishConfig": {
50
50
  "access": "public"