@diagc/cli 1.1.4 → 1.1.6
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/assets/studio/assets/index-Cn03lgc3.js +110 -0
- package/assets/studio/index.html +1 -1
- package/dist/api/dispatch.js +14 -0
- package/dist/api/handlers.d.ts +3 -2
- package/dist/api/handlers.js +69 -18
- package/dist/api/routes.js +0 -2
- package/dist/cli.d.ts +1 -2
- package/dist/cli.js +36 -29
- package/dist/command-args.d.ts +9 -0
- package/dist/command-args.js +56 -0
- package/dist/compile.d.ts +3 -0
- package/dist/compile.js +6 -2
- package/dist/init.js +2 -2
- package/dist/lint.d.ts +2 -1
- package/dist/lint.js +8 -4
- package/dist/names.d.ts +3 -0
- package/dist/names.js +13 -0
- package/dist/publish/publish.js +37 -12
- package/package.json +2 -2
- package/assets/studio/assets/index-CMKGy0j8.js +0 -110
package/assets/studio/index.html
CHANGED
|
@@ -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-
|
|
7
|
+
<script type="module" crossorigin src="/assets/index-Cn03lgc3.js"></script>
|
|
8
8
|
<link rel="stylesheet" crossorigin href="/assets/index-Csx5rLJC.css">
|
|
9
9
|
</head>
|
|
10
10
|
<body>
|
package/dist/api/dispatch.js
CHANGED
|
@@ -12,6 +12,15 @@ function send(res, status, body) {
|
|
|
12
12
|
res.setHeader('content-type', 'application/json');
|
|
13
13
|
res.end(JSON.stringify(body));
|
|
14
14
|
}
|
|
15
|
+
function decodes(s) {
|
|
16
|
+
try {
|
|
17
|
+
decodeURIComponent(s);
|
|
18
|
+
return true;
|
|
19
|
+
}
|
|
20
|
+
catch {
|
|
21
|
+
return false;
|
|
22
|
+
}
|
|
23
|
+
}
|
|
15
24
|
/** Run the matching route with plain values — no HTTP anywhere. undefined means
|
|
16
25
|
* no route matched (the HTTP wrapper falls through to static serving; the
|
|
17
26
|
* Obsidian host answers 404). Errors become envelopes; this boundary never
|
|
@@ -23,6 +32,11 @@ export async function runRoute(request, ctx, handlers) {
|
|
|
23
32
|
try {
|
|
24
33
|
// matchRoute already proved the match; re-running exposes the captures.
|
|
25
34
|
const match = request.url.match(route.pattern);
|
|
35
|
+
// The routes decode their captures; one that cannot be decoded is the
|
|
36
|
+
// client's mistake, answered here rather than thrown as a server error.
|
|
37
|
+
if (!match.slice(1).every((c) => c === undefined || decodes(c))) {
|
|
38
|
+
return { status: 400, body: { issues: [{ message: 'Malformed name' }] } };
|
|
39
|
+
}
|
|
26
40
|
let body = undefined;
|
|
27
41
|
if (route.bodyMode === 'json') {
|
|
28
42
|
try {
|
package/dist/api/handlers.d.ts
CHANGED
|
@@ -1,9 +1,10 @@
|
|
|
1
1
|
import { type DiagramModel } from '@diagc/core/internal';
|
|
2
|
+
import { isSafeName } from '../names.js';
|
|
2
3
|
export interface HandlerResult {
|
|
3
4
|
status: number;
|
|
4
5
|
body: unknown;
|
|
5
6
|
}
|
|
6
|
-
export
|
|
7
|
+
export { isSafeName };
|
|
7
8
|
/** Recursively collect every file under `dir` whose name ends in `suffix`,
|
|
8
9
|
* posix-joined relative to `dir` with the suffix stripped. Missing dir → [].
|
|
9
10
|
* Shared by the diagram-source and layout-overlay walks. */
|
|
@@ -37,7 +38,7 @@ export declare function readDiagram(diagramsDir: string, name: string): Promise<
|
|
|
37
38
|
export declare function readComposedDiagram(diagramsDir: string, name: string): Promise<HandlerResult>;
|
|
38
39
|
export declare function saveDiagram(diagramsDir: string, name: string, payload: unknown): Promise<HandlerResult>;
|
|
39
40
|
/** Move a designer-owned diagram (and its sibling layout, if any) to a new name,
|
|
40
|
-
* rewriting the model's
|
|
41
|
+
* rewriting the model's id to match so the file stays self-consistent. */
|
|
41
42
|
export declare function renameDiagram(diagramsDir: string, from: string, to: string): Promise<HandlerResult>;
|
|
42
43
|
/** Promote a JSON-owned diagram to a generated `.diagram.ts`. See `ejectDiagram`
|
|
43
44
|
* for the round-trip guarantee; this just maps its failure codes to statuses. */
|
package/dist/api/handlers.js
CHANGED
|
@@ -5,10 +5,10 @@ import { IMAGE_REF, composeIncludes, errMessage, isDrawings, isLayoutOverlay, va
|
|
|
5
5
|
import { writeFileAtomic } from '../atomic-write.js';
|
|
6
6
|
import { EjectError, ejectDiagram } from '../eject.js';
|
|
7
7
|
import { resolveInclude } from '../includes.js';
|
|
8
|
+
import { isSafeName } from '../names.js';
|
|
8
9
|
import { snapshotSession } from '../snapshots.js';
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
}
|
|
10
|
+
// The name rule every route checks, for the hosts and tests that reach it here.
|
|
11
|
+
export { isSafeName };
|
|
12
12
|
// path.dirname(diagramsDir) is the .diagrams root when diagramsDir is
|
|
13
13
|
// .diagrams/src — the same rootDir a locked session uses elsewhere (eject.ts).
|
|
14
14
|
// 'locked' because the boot/refresh path must never fetch or vendor a remote
|
|
@@ -52,19 +52,26 @@ export async function listDiagramModels(diagramsDir, artifactsDir) {
|
|
|
52
52
|
const all = [...new Set([...sourceNames, ...artifactNames])].sort();
|
|
53
53
|
const diagrams = [];
|
|
54
54
|
for (const name of all) {
|
|
55
|
-
const
|
|
56
|
-
|
|
55
|
+
const isSource = sourceNames.has(name);
|
|
56
|
+
// Every read and save refuses a name isSafeName refuses, so such a source is shown but not offered for editing.
|
|
57
|
+
const editable = isSource && isSafeName(name);
|
|
58
|
+
const file = isSource
|
|
57
59
|
? path.join(diagramsDir, `${name}.diagram.json`)
|
|
58
60
|
: path.join(artifactsDir, `${name}.diagram.json`);
|
|
59
61
|
let model = null;
|
|
60
62
|
const issues = [];
|
|
63
|
+
if (isSource && !editable) {
|
|
64
|
+
issues.push({
|
|
65
|
+
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.`,
|
|
66
|
+
});
|
|
67
|
+
}
|
|
61
68
|
try {
|
|
62
69
|
model = JSON.parse(await readFile(file, 'utf8'));
|
|
63
70
|
}
|
|
64
71
|
catch {
|
|
65
72
|
issues.push({ message: `Could not read model for '${name}'` });
|
|
66
73
|
}
|
|
67
|
-
if (
|
|
74
|
+
if (isSource && hasIncludes(model)) {
|
|
68
75
|
try {
|
|
69
76
|
const { model: composed, warnings } = await composeIncludes(model, path.resolve(file), lockedResolver(diagramsDir));
|
|
70
77
|
// compileFile refuses an invalid composed result outright, because the
|
|
@@ -185,9 +192,24 @@ export async function readComposedDiagram(diagramsDir, name) {
|
|
|
185
192
|
return { status: 409, body: { issues: [{ message: errMessage(e) }] } };
|
|
186
193
|
}
|
|
187
194
|
}
|
|
195
|
+
/** A 409 when `<name>.diagram.ts` exists: that diagram is TypeScript's, and a JSON
|
|
196
|
+
* twin beside it would compile to the same artifact, the last compile winning. */
|
|
197
|
+
async function ownedByTs(diagramsDir, name) {
|
|
198
|
+
const tsPath = path.join(diagramsDir, `${name}.diagram.ts`);
|
|
199
|
+
try {
|
|
200
|
+
await access(tsPath);
|
|
201
|
+
}
|
|
202
|
+
catch {
|
|
203
|
+
return undefined;
|
|
204
|
+
}
|
|
205
|
+
return { status: 409, body: { issues: [{ message: `'${name}' is already TypeScript-owned (${tsPath})` }] } };
|
|
206
|
+
}
|
|
188
207
|
export async function saveDiagram(diagramsDir, name, payload) {
|
|
189
208
|
if (!isSafeName(name))
|
|
190
209
|
return { status: 400, body: { issues: [{ message: `Unsafe name '${name}'` }] } };
|
|
210
|
+
const owned = await ownedByTs(diagramsDir, name);
|
|
211
|
+
if (owned !== undefined)
|
|
212
|
+
return owned;
|
|
191
213
|
const p = payload;
|
|
192
214
|
const arraysOk = p !== null &&
|
|
193
215
|
p.version === 1 &&
|
|
@@ -208,7 +230,7 @@ export async function saveDiagram(diagramsDir, name, payload) {
|
|
|
208
230
|
return { status: 200, body: { ok: true } };
|
|
209
231
|
}
|
|
210
232
|
/** Move a designer-owned diagram (and its sibling layout, if any) to a new name,
|
|
211
|
-
* rewriting the model's
|
|
233
|
+
* rewriting the model's id to match so the file stays self-consistent. */
|
|
212
234
|
export async function renameDiagram(diagramsDir, from, to) {
|
|
213
235
|
if (!isSafeName(from) || !isSafeName(to)) {
|
|
214
236
|
return { status: 400, body: { issues: [{ message: `Unsafe name '${isSafeName(from) ? to : from}'` }] } };
|
|
@@ -231,6 +253,9 @@ export async function renameDiagram(diagramsDir, from, to) {
|
|
|
231
253
|
catch {
|
|
232
254
|
/* target free — proceed */
|
|
233
255
|
}
|
|
256
|
+
const owned = await ownedByTs(diagramsDir, to);
|
|
257
|
+
if (owned !== undefined)
|
|
258
|
+
return owned;
|
|
234
259
|
let model;
|
|
235
260
|
try {
|
|
236
261
|
model = JSON.parse(raw);
|
|
@@ -238,25 +263,51 @@ export async function renameDiagram(diagramsDir, from, to) {
|
|
|
238
263
|
catch {
|
|
239
264
|
return { status: 400, body: { issues: [{ message: `Corrupt diagram source '${from}'` }] } };
|
|
240
265
|
}
|
|
266
|
+
// The id follows the file. The name is the diagram's title, so it follows only
|
|
267
|
+
// when it was the id, a title nobody set.
|
|
268
|
+
if (model['name'] === model['id'])
|
|
269
|
+
model['name'] = to;
|
|
241
270
|
model['id'] = to;
|
|
242
|
-
model['name'] = to;
|
|
243
271
|
await mkdir(path.dirname(toDiagram), { recursive: true });
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
//
|
|
272
|
+
// Sidecars first, the source last, so the old name keeps its source until every
|
|
273
|
+
// other step has worked. A failure undoes the steps before it, in reverse, and
|
|
274
|
+
// the error answers 500.
|
|
275
|
+
const moved = [];
|
|
276
|
+
let written = false;
|
|
247
277
|
try {
|
|
248
|
-
|
|
278
|
+
for (const sidecar of ['layout', 'drawings']) {
|
|
279
|
+
const move = [
|
|
280
|
+
path.join(diagramsDir, `${from}.${sidecar}.json`),
|
|
281
|
+
path.join(diagramsDir, `${to}.${sidecar}.json`),
|
|
282
|
+
];
|
|
283
|
+
if (await moveIfPresent(...move))
|
|
284
|
+
moved.push(move);
|
|
285
|
+
}
|
|
286
|
+
await writeFileAtomic(toDiagram, `${JSON.stringify(model, null, 2)}\n`);
|
|
287
|
+
written = true;
|
|
288
|
+
await unlink(fromDiagram);
|
|
249
289
|
}
|
|
250
|
-
catch {
|
|
251
|
-
|
|
290
|
+
catch (e) {
|
|
291
|
+
if (written)
|
|
292
|
+
await unlink(toDiagram).catch(() => { });
|
|
293
|
+
for (const [src, dst] of moved.reverse())
|
|
294
|
+
await rename(dst, src).catch(() => { });
|
|
295
|
+
throw e;
|
|
252
296
|
}
|
|
297
|
+
return { status: 200, body: { ok: true } };
|
|
298
|
+
}
|
|
299
|
+
/** `rename(src, dst)`, false when there is no `src` to move: a diagram need not have
|
|
300
|
+
* a sidecar. Any other failure throws. */
|
|
301
|
+
async function moveIfPresent(src, dst) {
|
|
253
302
|
try {
|
|
254
|
-
await rename(
|
|
303
|
+
await rename(src, dst);
|
|
304
|
+
return true;
|
|
255
305
|
}
|
|
256
|
-
catch {
|
|
257
|
-
|
|
306
|
+
catch (e) {
|
|
307
|
+
if (e.code === 'ENOENT')
|
|
308
|
+
return false;
|
|
309
|
+
throw e;
|
|
258
310
|
}
|
|
259
|
-
return { status: 200, body: { ok: true } };
|
|
260
311
|
}
|
|
261
312
|
/** Promote a JSON-owned diagram to a generated `.diagram.ts`. See `ejectDiagram`
|
|
262
313
|
* for the round-trip guarantee; this just maps its failure codes to statuses. */
|
package/dist/api/routes.js
CHANGED
|
@@ -66,8 +66,6 @@ export const ROUTES = [
|
|
|
66
66
|
pattern: /^\/api\/(diagrams|layouts|drawings)\/(.+)$/,
|
|
67
67
|
bodyMode: 'json',
|
|
68
68
|
handler: (h, c) => {
|
|
69
|
-
// decodeURIComponent throws on malformed percent-encoding — kept
|
|
70
|
-
// inside the boundary so a bad name yields 500, never a crash.
|
|
71
69
|
const name = decodeURIComponent(c.match[2] ?? '');
|
|
72
70
|
return c.match[1] === 'diagrams'
|
|
73
71
|
? h.saveDiagram(c.diagramsDir, name, c.body)
|
package/dist/cli.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { type PublishOptions } from './publish/publish.js';
|
|
2
|
-
interface Args {
|
|
2
|
+
export interface Args {
|
|
3
3
|
command: string;
|
|
4
4
|
files: string[];
|
|
5
5
|
out: string;
|
|
@@ -50,4 +50,3 @@ export declare function parseRange(range: string): {
|
|
|
50
50
|
};
|
|
51
51
|
/** A ref as a directory name: `v1.0..feature/x` -> `v1.0..feature-x`. */
|
|
52
52
|
export declare function diffOutDir(from: string, to: string | undefined): string;
|
|
53
|
-
export {};
|
package/dist/cli.js
CHANGED
|
@@ -38,6 +38,7 @@ import { formatCompileEvent, startWatch } from './watch.js';
|
|
|
38
38
|
import { galleryLink } from './publish/gallery.js';
|
|
39
39
|
import { publishDiagrams } from './publish/publish.js';
|
|
40
40
|
import { runStudio } from './studio.js';
|
|
41
|
+
import { ArgNotTakenError, checkCommandArgs } from './command-args.js';
|
|
41
42
|
const USAGE = `Usage: diagc <init|compile|lint|watch|publish|studio|eject|diff|guide> [files...] [--out dir]
|
|
42
43
|
|
|
43
44
|
Commands:
|
|
@@ -224,20 +225,30 @@ export function publishDirs(args) {
|
|
|
224
225
|
assetsDir: path.join(srcDir, 'assets'),
|
|
225
226
|
};
|
|
226
227
|
}
|
|
228
|
+
/** End the process once stdout and stderr have taken everything written to them:
|
|
229
|
+
* `process.exit` straight after a write drops what a pipe has not accepted yet. A
|
|
230
|
+
* zero-length write's callback runs after everything queued before it. It ends with
|
|
231
|
+
* `process.exit`, not `exitCode`, so an open handle (a keep-alive socket from a remote
|
|
232
|
+
* include, a Chrome process) cannot keep the CLI running. */
|
|
233
|
+
async function exit(code) {
|
|
234
|
+
await Promise.all([process.stdout, process.stderr].map((s) => new Promise((done) => s.write('', done))));
|
|
235
|
+
process.exit(code);
|
|
236
|
+
}
|
|
227
237
|
async function main() {
|
|
228
238
|
let args;
|
|
229
239
|
try {
|
|
230
240
|
args = parseArgs(process.argv.slice(2));
|
|
241
|
+
checkCommandArgs(args);
|
|
231
242
|
}
|
|
232
243
|
catch (e) {
|
|
233
244
|
if (e instanceof HelpRequested) {
|
|
234
245
|
console.log(USAGE);
|
|
235
|
-
|
|
246
|
+
return exit(0);
|
|
236
247
|
}
|
|
237
|
-
if (e instanceof UnknownFlagError || e instanceof BadFlagValueError) {
|
|
248
|
+
if (e instanceof UnknownFlagError || e instanceof BadFlagValueError || e instanceof ArgNotTakenError) {
|
|
238
249
|
console.error(`diagc: ${e.message}\n`);
|
|
239
250
|
console.error(USAGE);
|
|
240
|
-
|
|
251
|
+
return exit(1);
|
|
241
252
|
}
|
|
242
253
|
throw e;
|
|
243
254
|
}
|
|
@@ -272,7 +283,7 @@ async function main() {
|
|
|
272
283
|
// the genuinely stale ones — skip the prune until every file compiles clean.
|
|
273
284
|
if (args.updateIncludes && args.files.length === 0 && !failed)
|
|
274
285
|
await snap.prune();
|
|
275
|
-
|
|
286
|
+
return exit(failed ? 1 : 0);
|
|
276
287
|
}
|
|
277
288
|
else if (args.command === 'lint') {
|
|
278
289
|
const files = args.files.length > 0 ? args.files : await fg(SOURCES);
|
|
@@ -287,19 +298,17 @@ async function main() {
|
|
|
287
298
|
else
|
|
288
299
|
for (const r of reports)
|
|
289
300
|
console.log(formatLintReport(r));
|
|
290
|
-
|
|
301
|
+
return exit(reports.length > 0 ? 1 : 0);
|
|
291
302
|
}
|
|
292
303
|
else if (args.command === 'watch') {
|
|
293
|
-
// Always locked,
|
|
304
|
+
// Always locked, and --update-includes is refused here: watch is a long-running
|
|
294
305
|
// live loop with no point at which "refetch and rewrite the lock" makes
|
|
295
|
-
// sense, so it
|
|
296
|
-
//
|
|
297
|
-
if (args.updateIncludes)
|
|
298
|
-
console.error('ignoring --update-includes: watch always runs locked');
|
|
306
|
+
// sense, so it has its own session rather than the shared one (mirrors
|
|
307
|
+
// studio.ts's own hardcoded 'locked' session).
|
|
299
308
|
const dir = args.files[0] ?? '.diagrams/src';
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
(await fg('**/*.diagram.{ts,json}', { cwd: dir })).length === 0)
|
|
309
|
+
// A directory that does not exist holds no diagrams either; a file is left alone.
|
|
310
|
+
if (!existsSync(dir) ||
|
|
311
|
+
(statSync(dir).isDirectory() && (await fg('**/*.diagram.{ts,json}', { cwd: dir })).length === 0))
|
|
303
312
|
warnNoSources(dir);
|
|
304
313
|
const watchSnap = snapshotSession(resolveInclude, '.diagrams', 'locked');
|
|
305
314
|
startWatch(dir, args.out, {
|
|
@@ -324,13 +333,14 @@ async function main() {
|
|
|
324
333
|
console.error(home.layout === 'monorepo'
|
|
325
334
|
? 'viewer shell not built — run `pnpm --filter @diagc/viewer build` in the monorepo.'
|
|
326
335
|
: `viewer shell missing from this install (${home.viewerShell}) — reinstall diagc.`);
|
|
327
|
-
|
|
336
|
+
return exit(1);
|
|
328
337
|
}
|
|
329
338
|
const dirs = publishDirs(args);
|
|
330
339
|
// Compile first so artifacts reflect current sources (TS + include expansion).
|
|
331
340
|
const sources = await fg('**/*.diagram.{ts,json}', { cwd: dirs.srcDir, absolute: true });
|
|
332
341
|
if (sources.length === 0)
|
|
333
342
|
warnNoSources(dirs.srcDir);
|
|
343
|
+
let failed = false;
|
|
334
344
|
for (const f of sources) {
|
|
335
345
|
try {
|
|
336
346
|
await compileFile(f, dirs.artifactsDir, {
|
|
@@ -340,13 +350,14 @@ async function main() {
|
|
|
340
350
|
});
|
|
341
351
|
}
|
|
342
352
|
catch (e) {
|
|
353
|
+
failed = true;
|
|
343
354
|
console.error(`✗ ${f}\n${errMessage(e)}`);
|
|
344
355
|
}
|
|
345
356
|
}
|
|
346
357
|
// publish's glob above ignores args.files (that only scopes which rendered
|
|
347
|
-
// pages come out below), so
|
|
348
|
-
//
|
|
349
|
-
if (args.updateIncludes)
|
|
358
|
+
// pages come out below), so an update run here is always full-tree; like
|
|
359
|
+
// compile's, its prune waits until every source compiles.
|
|
360
|
+
if (args.updateIncludes && !failed)
|
|
350
361
|
await snap.prune();
|
|
351
362
|
let images = args.images;
|
|
352
363
|
let renderPng;
|
|
@@ -373,39 +384,35 @@ async function main() {
|
|
|
373
384
|
if (res.images.length > 0)
|
|
374
385
|
console.log(`✓ ${res.images.length} image(s) -> ${dirs.staticDir}`);
|
|
375
386
|
console.log(`✓ gallery -> ${res.gallery}`);
|
|
376
|
-
|
|
387
|
+
return exit(0);
|
|
377
388
|
}
|
|
378
389
|
else if (args.command === 'studio') {
|
|
379
390
|
// Studio's own compile-watch loop always resolves includes locked (see
|
|
380
391
|
// studio.ts) — same reasoning as watch above.
|
|
381
|
-
if (args.updateIncludes)
|
|
382
|
-
console.error('ignoring --update-includes: studio always runs locked');
|
|
383
392
|
await runStudio(home, process.cwd());
|
|
384
393
|
return;
|
|
385
394
|
}
|
|
386
395
|
else if (args.command === 'eject') {
|
|
387
396
|
// ejectDiagram's post-swap recompile always resolves includes locked (see
|
|
388
397
|
// eject.ts) — same reasoning as watch above.
|
|
389
|
-
if (args.updateIncludes)
|
|
390
|
-
console.error('ignoring --update-includes: eject always runs locked');
|
|
391
398
|
const name = args.files[0] === undefined ? undefined : diagramName(args.files[0]);
|
|
392
399
|
if (name === undefined || name === '') {
|
|
393
400
|
console.error('diagc: eject needs a diagram name.');
|
|
394
401
|
console.error(USAGE);
|
|
395
|
-
|
|
402
|
+
return exit(1);
|
|
396
403
|
}
|
|
397
404
|
try {
|
|
398
405
|
const res = await ejectDiagram('.diagrams/src', args.out, name, { coreEntry: home.coreEntry });
|
|
399
406
|
console.log(`✓ ${res.tsPath}`);
|
|
400
|
-
|
|
407
|
+
return exit(0);
|
|
401
408
|
}
|
|
402
409
|
catch (e) {
|
|
403
410
|
console.error(errMessage(e));
|
|
404
|
-
|
|
411
|
+
return exit(1);
|
|
405
412
|
}
|
|
406
413
|
}
|
|
407
414
|
else if (args.command === 'diff') {
|
|
408
|
-
|
|
415
|
+
return exit(await runDiff(args, home));
|
|
409
416
|
}
|
|
410
417
|
else if (args.command === 'guide') {
|
|
411
418
|
// exitCode and a return, not process.exit: the guide is tens of kilobytes and
|
|
@@ -421,7 +428,7 @@ async function main() {
|
|
|
421
428
|
else if (args.command === 'init') {
|
|
422
429
|
if (args.files.length > 1) {
|
|
423
430
|
console.error(`diagc: init takes one name, got ${args.files.length} — e.g. diagc init shop --type c4`);
|
|
424
|
-
|
|
431
|
+
return exit(1);
|
|
425
432
|
}
|
|
426
433
|
process.exitCode = await runInit({
|
|
427
434
|
cwd: process.cwd(),
|
|
@@ -439,7 +446,7 @@ async function main() {
|
|
|
439
446
|
else {
|
|
440
447
|
console.error(`diagc: Unknown command '${args.command}'.`);
|
|
441
448
|
console.error(USAGE);
|
|
442
|
-
|
|
449
|
+
return exit(1);
|
|
443
450
|
}
|
|
444
451
|
}
|
|
445
452
|
/** `A..B` or `A` (against the working tree). */
|
|
@@ -528,5 +535,5 @@ async function runDiff(args, home) {
|
|
|
528
535
|
}
|
|
529
536
|
main().catch((e) => {
|
|
530
537
|
console.error(errMessage(e));
|
|
531
|
-
|
|
538
|
+
return exit(1);
|
|
532
539
|
});
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import type { Args } from './cli.js';
|
|
2
|
+
/** Thrown by {@link checkCommandArgs} for a flag or an argument the command does not
|
|
3
|
+
* take; `main` reports it the same way as an unknown flag. */
|
|
4
|
+
export declare class ArgNotTakenError extends Error {
|
|
5
|
+
constructor(message: string);
|
|
6
|
+
}
|
|
7
|
+
/** Refuse a flag or an argument `args.command` does not take. Ignored, it would be a
|
|
8
|
+
* wrong file set or an output the user never sees (`init --out build`). */
|
|
9
|
+
export declare function checkCommandArgs(args: Args): void;
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
/** Thrown by {@link checkCommandArgs} for a flag or an argument the command does not
|
|
2
|
+
* take; `main` reports it the same way as an unknown flag. */
|
|
3
|
+
export class ArgNotTakenError extends Error {
|
|
4
|
+
constructor(message) {
|
|
5
|
+
super(message);
|
|
6
|
+
this.name = 'ArgNotTakenError';
|
|
7
|
+
}
|
|
8
|
+
}
|
|
9
|
+
const LOCKED = { '--update-includes': 'it always resolves includes locked' };
|
|
10
|
+
/** What each command takes: the flags the reference's flag table lists for it, and a
|
|
11
|
+
* cap on positional arguments where the command has no message of its own for extra
|
|
12
|
+
* ones. `why` says why a flag another command takes means nothing here. */
|
|
13
|
+
const TAKES = {
|
|
14
|
+
compile: { flags: ['--out', '--update-includes'] },
|
|
15
|
+
lint: { flags: ['--json'] },
|
|
16
|
+
watch: { flags: ['--out'], max: [1, 'one directory'], why: LOCKED },
|
|
17
|
+
publish: { flags: ['--out', '--no-images', '--link', '--update-includes'] },
|
|
18
|
+
studio: { flags: [], max: [0, 'no arguments'], why: LOCKED },
|
|
19
|
+
eject: { flags: ['--out'], max: [1, 'one diagram name'], why: LOCKED },
|
|
20
|
+
diff: { flags: ['--out', '--no-images', '--json', '--labels', '--image-url'] },
|
|
21
|
+
guide: { flags: [] },
|
|
22
|
+
init: { flags: ['--type', '--agents'] },
|
|
23
|
+
};
|
|
24
|
+
/** The flags `args` says were passed. */
|
|
25
|
+
function flagsGiven(args) {
|
|
26
|
+
const given = [
|
|
27
|
+
[args.outGiven, '--out'],
|
|
28
|
+
[!args.images, '--no-images'],
|
|
29
|
+
[args.link !== undefined, '--link'],
|
|
30
|
+
[args.json, '--json'],
|
|
31
|
+
[args.labels !== undefined, '--labels'],
|
|
32
|
+
[args.imageUrl !== undefined, '--image-url'],
|
|
33
|
+
[args.updateIncludes, '--update-includes'],
|
|
34
|
+
[args.type !== undefined, '--type'],
|
|
35
|
+
[args.agents, '--agents'],
|
|
36
|
+
];
|
|
37
|
+
return given.filter(([on]) => on).map(([, flag]) => flag);
|
|
38
|
+
}
|
|
39
|
+
/** Refuse a flag or an argument `args.command` does not take. Ignored, it would be a
|
|
40
|
+
* wrong file set or an output the user never sees (`init --out build`). */
|
|
41
|
+
export function checkCommandArgs(args) {
|
|
42
|
+
const takes = TAKES[args.command];
|
|
43
|
+
if (takes === undefined)
|
|
44
|
+
return; // an unknown command has its own message
|
|
45
|
+
for (const flag of flagsGiven(args)) {
|
|
46
|
+
if (takes.flags.includes(flag))
|
|
47
|
+
continue;
|
|
48
|
+
const takers = Object.keys(TAKES).filter((c) => TAKES[c].flags.includes(flag));
|
|
49
|
+
const list = takers.length === 1 ? takers[0] : `${takers.slice(0, -1).join(', ')} and ${takers.at(-1)}`;
|
|
50
|
+
const why = takes.why?.[flag] === undefined ? '' : ` (${takes.why[flag]})`;
|
|
51
|
+
throw new ArgNotTakenError(`${args.command} does not take ${flag}${why}; ${list} ${takers.length === 1 ? 'does' : 'do'}.`);
|
|
52
|
+
}
|
|
53
|
+
const extra = takes.max === undefined ? undefined : args.files[takes.max[0]];
|
|
54
|
+
if (extra !== undefined)
|
|
55
|
+
throw new ArgNotTakenError(`${args.command} takes ${takes.max[1]}; '${extra}' is one too many.`);
|
|
56
|
+
}
|
package/dist/compile.d.ts
CHANGED
|
@@ -34,6 +34,9 @@ export interface LoadOptions {
|
|
|
34
34
|
rootDir?: string;
|
|
35
35
|
coreEntry?: string;
|
|
36
36
|
resolver?: IncludeResolver;
|
|
37
|
+
/** what composing the includes warns about, one warning at a time; by default each
|
|
38
|
+
* is printed on stderr as `<file>: <warning>` */
|
|
39
|
+
onWarning?: (warning: string) => void;
|
|
37
40
|
}
|
|
38
41
|
/**
|
|
39
42
|
* Read a source, validate it, expand its includes and validate the result: the
|
package/dist/compile.js
CHANGED
|
@@ -142,8 +142,12 @@ export async function loadModel(file, opts) {
|
|
|
142
142
|
? snapshotSession(resolveInclude, path.dirname(path.resolve(opts.rootDir)), 'locked').resolver
|
|
143
143
|
: resolveInclude);
|
|
144
144
|
const { model: composed, warnings } = await composeIncludes(model, path.resolve(file), resolver);
|
|
145
|
-
for (const w of warnings)
|
|
146
|
-
|
|
145
|
+
for (const w of warnings) {
|
|
146
|
+
if (opts?.onWarning !== undefined)
|
|
147
|
+
opts.onWarning(w);
|
|
148
|
+
else
|
|
149
|
+
console.warn(`${file}: ${w}`);
|
|
150
|
+
}
|
|
147
151
|
model = composed;
|
|
148
152
|
const issues = validate(model);
|
|
149
153
|
if (issues.length > 0)
|
package/dist/init.js
CHANGED
|
@@ -3,7 +3,7 @@ import { mkdir, readFile, writeFile } from 'node:fs/promises';
|
|
|
3
3
|
import path from 'node:path';
|
|
4
4
|
import fg from 'fast-glob';
|
|
5
5
|
import { errMessage } from '@diagc/core/internal';
|
|
6
|
-
import { isSafeName } from './
|
|
6
|
+
import { isSafeName } from './names.js';
|
|
7
7
|
import { compileFile } from './compile.js';
|
|
8
8
|
import { readStarter, UnknownStarterError } from './starters.js';
|
|
9
9
|
export const DEFAULT_NAME = 'example';
|
|
@@ -90,7 +90,7 @@ async function starterStep(opts, io) {
|
|
|
90
90
|
}
|
|
91
91
|
}
|
|
92
92
|
const name = diagramName(opts.name ?? DEFAULT_NAME);
|
|
93
|
-
if (!isSafeName(name)
|
|
93
|
+
if (!isSafeName(name)) {
|
|
94
94
|
throw new InitError(`'${name}' is not a diagram name — use lowercase letters, digits and '-', with '/' for a folder (shop, team/app).`);
|
|
95
95
|
}
|
|
96
96
|
// The type is checked before the name clash: a wrong `--type` is the more useful
|
package/dist/lint.d.ts
CHANGED
|
@@ -12,6 +12,7 @@ export interface LintReport {
|
|
|
12
12
|
column?: number;
|
|
13
13
|
}
|
|
14
14
|
/** Every finding for one source: its validation errors when it does not load,
|
|
15
|
-
* otherwise its warnings (core's lint included)
|
|
15
|
+
* otherwise its warnings (core's lint included), and in both cases what composing
|
|
16
|
+
* its includes warned about. */
|
|
16
17
|
export declare function lintFile(file: string, opts?: LoadOptions): Promise<LintReport[]>;
|
|
17
18
|
export declare function formatLintReport(r: LintReport): string;
|
package/dist/lint.js
CHANGED
|
@@ -8,18 +8,22 @@ const report = (file, severity, i) => ({
|
|
|
8
8
|
...(i.ref !== undefined ? { ref: i.ref } : {}),
|
|
9
9
|
});
|
|
10
10
|
/** Every finding for one source: its validation errors when it does not load,
|
|
11
|
-
* otherwise its warnings (core's lint included)
|
|
11
|
+
* otherwise its warnings (core's lint included), and in both cases what composing
|
|
12
|
+
* its includes warned about. */
|
|
12
13
|
export async function lintFile(file, opts) {
|
|
14
|
+
// Findings rather than lines on stderr, so `--json` carries them and they fail the lint.
|
|
15
|
+
const included = [];
|
|
16
|
+
const onWarning = (message) => included.push(report(file, 'warning', { code: 'include', message }));
|
|
13
17
|
try {
|
|
14
|
-
const model = await loadModel(file, opts);
|
|
15
|
-
return diagramWarnings(model).map((w) => report(file, 'warning', w));
|
|
18
|
+
const model = await loadModel(file, { ...opts, onWarning });
|
|
19
|
+
return [...included, ...diagramWarnings(model).map((w) => report(file, 'warning', w))];
|
|
16
20
|
}
|
|
17
21
|
catch (e) {
|
|
18
22
|
// By name, not instanceof: a builder diagram throws from jiti's own copy of core.
|
|
19
23
|
if (e instanceof Error &&
|
|
20
24
|
e.name === 'DiagramValidationError' &&
|
|
21
25
|
Array.isArray(e.issues)) {
|
|
22
|
-
return e.issues.map((i) => report(file, 'error', i));
|
|
26
|
+
return [...included, ...e.issues.map((i) => report(file, 'error', i))];
|
|
23
27
|
}
|
|
24
28
|
if (e instanceof LoadError) {
|
|
25
29
|
return [
|
package/dist/names.d.ts
ADDED
package/dist/names.js
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
/** Words the studio API's action routes put after a diagram's name
|
|
2
|
+
* (`/api/diagrams/<name>/rename`). A name ending in `/<word>` would be read as
|
|
3
|
+
* that action on its folder, so it could be created and never saved. Alone, the
|
|
4
|
+
* word is the plain route's name and is served like any other. */
|
|
5
|
+
const ACTION_SEGMENTS = ['rename', 'eject', 'composed'];
|
|
6
|
+
/** A diagram name the API, the CLI and the file tree all agree on: lowercase
|
|
7
|
+
* letters, digits and `-`, with `/` between folders, every segment non-empty. */
|
|
8
|
+
export function isSafeName(name) {
|
|
9
|
+
if (!/^[a-z0-9][a-z0-9/-]*$/.test(name) || name.includes('..') || name.includes('//') || name.endsWith('/'))
|
|
10
|
+
return false;
|
|
11
|
+
const slash = name.lastIndexOf('/');
|
|
12
|
+
return slash < 0 || !ACTION_SEGMENTS.includes(name.slice(slash + 1));
|
|
13
|
+
}
|