okforest 0.12.0 → 0.14.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.mjs CHANGED
@@ -1,10 +1,10 @@
1
1
  #!/usr/bin/env node
2
2
  import { createRequire } from "node:module";
3
- import { mkdir, readFile, readdir, stat, writeFile } from "node:fs/promises";
4
- import { basename, join, resolve } from "node:path";
3
+ import { access, mkdir, readFile, readdir, stat, writeFile } from "node:fs/promises";
4
+ import { basename, dirname, join, posix, resolve } from "node:path";
5
5
  import { fileURLToPath } from "node:url";
6
6
  import { parseArgs, styleText } from "node:util";
7
- import { TYPES_FOLDER, buildInventory } from "@okforest/okf";
7
+ import { TYPES_FOLDER, buildInventory, startPage } from "@okforest/okf";
8
8
  import { readTree } from "@okforest/okf/node";
9
9
  import { defaultRules, draftTypeSchema, okfRules, ruleDocs, ruleUrl, toReport, validate } from "@okforest/validate";
10
10
  // src/io.ts
@@ -49,7 +49,7 @@ function formatOption(value) {
49
49
  throw new UsageError(`--format must be \`text\` or \`json\` (got \`${String(value)}\`).`);
50
50
  }
51
51
  // src/commands/init.ts
52
- const HELP$5 = `Usage: okforest init [path] --template <name> [--name <name>]
52
+ const HELP$6 = `Usage: okforest init [path] --template <name> [--name <name>]
53
53
 
54
54
  Create a new OKF v0.2 tree at path (default: the current directory, which must
55
55
  be empty apart from .git) from a starter template. Starter concepts are drafts
@@ -66,7 +66,7 @@ async function initCommand(args, io) {
66
66
  name: { type: "string" }
67
67
  });
68
68
  if (values.help) {
69
- io.stdout(HELP$5);
69
+ io.stdout(HELP$6);
70
70
  return EXIT.ok;
71
71
  }
72
72
  const templates = await listTemplates();
@@ -137,7 +137,7 @@ async function loadTree(path, io) {
137
137
  }
138
138
  }
139
139
  // src/commands/inventory.ts
140
- const HELP$4 = `Usage: okforest inventory [path] [--format text|json]
140
+ const HELP$5 = `Usage: okforest inventory [path] [--format text|json]
141
141
 
142
142
  List every type, tag, and frontmatter key in use in the tree at path (default:
143
143
  the current directory), with counts, lifecycle and trust totals, and likely
@@ -149,7 +149,7 @@ Options
149
149
  async function inventoryCommand(args, io) {
150
150
  const { values, path } = parseCommand(args, { format: { type: "string" } });
151
151
  if (values.help) {
152
- io.stdout(HELP$4);
152
+ io.stdout(HELP$5);
153
153
  return EXIT.ok;
154
154
  }
155
155
  const format = formatOption(values.format);
@@ -193,8 +193,169 @@ function inventoryText(inventory, io) {
193
193
  }
194
194
  return `${out.join("\n")}\n`;
195
195
  }
196
+ // src/commands/validate.ts
197
+ const HELP$4 = `Usage: okforest validate [path] [--format text|json]
198
+
199
+ Check the OKF v0.2 tree at path (default: the current directory) against the
200
+ OKF specification and OKForest conventions. Exits 1 when there are errors;
201
+ warnings and info are reported but never fail.
202
+
203
+ Options
204
+ --format text|json Output format (default: text). JSON is for CI and tools.
205
+ `;
206
+ async function validateCommand(args, io) {
207
+ const { values, path } = parseCommand(args, { format: { type: "string" } });
208
+ if (values.help) {
209
+ io.stdout(HELP$4);
210
+ return EXIT.ok;
211
+ }
212
+ const format = formatOption(values.format);
213
+ const result = await validate(await loadTree(path, io));
214
+ io.stdout(format === "json" ? toJson(path, result) : toText(result, io));
215
+ return result.ok ? EXIT.ok : EXIT.failed;
216
+ }
217
+ /** The shared validation report (`@okforest/validate`'s `toReport`), as JSON. */
218
+ function toJson(path, result) {
219
+ return `${JSON.stringify(toReport(result, {
220
+ tool: {
221
+ name: "okforest",
222
+ version: VERSION
223
+ },
224
+ path
225
+ }), null, 2)}\n`;
226
+ }
227
+ const LABEL = {
228
+ error: "error",
229
+ warning: "warning",
230
+ info: "info"
231
+ };
232
+ const COLOR$1 = {
233
+ error: "red",
234
+ warning: "yellow",
235
+ info: "cyan"
236
+ };
237
+ function toText(result, io) {
238
+ const out = [];
239
+ const byFile = /* @__PURE__ */ new Map();
240
+ for (const finding of result.findings) byFile.set(finding.file, [...byFile.get(finding.file) ?? [], finding]);
241
+ for (const [file, findings] of byFile) {
242
+ out.push(paint(io, "underline", file));
243
+ const positions = findings.map((f) => f.line === void 0 ? "" : `${f.line}:${f.column ?? 1}`);
244
+ const width = Math.max(...positions.map((p) => p.length));
245
+ findings.forEach((f, i) => {
246
+ out.push(` ${paint(io, "dim", positions[i].padEnd(width))} ${paint(io, COLOR$1[f.severity], LABEL[f.severity].padEnd(7))} ${f.message} ${paint(io, "dim", f.ruleId)}`);
247
+ });
248
+ out.push("");
249
+ }
250
+ out.push(...ruleDocs$1(result.findings, io));
251
+ out.push(summary(result, io));
252
+ return `${out.join("\n")}\n`;
253
+ }
254
+ /** Each rule that reported something, with its documentation page. */
255
+ function ruleDocs$1(findings, io) {
256
+ const ids = [...new Set(findings.map((f) => f.ruleId))];
257
+ if (ids.length === 0) return [];
258
+ const width = Math.max(...ids.map((id) => id.length));
259
+ return [
260
+ paint(io, "underline", "Rule docs"),
261
+ ...ids.map((id) => ` ${id.padEnd(width)} ${paint(io, "dim", ruleUrl(id))}`),
262
+ ` ${paint(io, "dim", "Run `okforest rule <rule>` for why and how to fix.")}`,
263
+ ""
264
+ ];
265
+ }
266
+ function summary(result, io) {
267
+ const plural = (n, word) => `${n} ${word}${n === 1 ? "" : "s"}`;
268
+ const scope = `${plural(result.concepts, "concept")} in ${plural(result.files, "file")}`;
269
+ if (result.findings.length === 0) return `${paint(io, "green", "✔")} No problems · ${scope}`;
270
+ const counts = `${plural(result.errors, "error")}, ${plural(result.warnings, "warning")}, ${result.infos} info`;
271
+ return result.ok ? `${paint(io, "green", "✔")} ${counts} · ${scope}` : `${paint(io, "red", "✖")} ${counts} · ${scope}`;
272
+ }
273
+ // src/commands/new.ts
274
+ const HELP$3 = `Usage: okforest new <type> <file> [--title <title>] [--description <text>] [--root <path>]
275
+
276
+ Create a concept of type <type> at <file> (a path in the tree, ending in .md)
277
+ from the type's template, ${TYPES_FOLDER}<type>.template.md, as written: its
278
+ front matter in its order, its body, and its guidance. The title and
279
+ description given replace the template's. A type without a template starts
280
+ with just its type, title, and description. When the file's folder has an
281
+ index.md, the new concept is listed in it. Then the new page is checked, so
282
+ what's left to fill in shows at once.
283
+
284
+ Options
285
+ --title <title> The concept's title.
286
+ --description <text> Its one-sentence description.
287
+ --root <path> The tree's root folder (default: the current directory).
288
+ `;
289
+ async function newCommand(args, io) {
290
+ const { values, positionals } = parseArgs({
291
+ args: [...args],
292
+ options: {
293
+ title: { type: "string" },
294
+ description: { type: "string" },
295
+ root: { type: "string" },
296
+ help: {
297
+ type: "boolean",
298
+ short: "h"
299
+ }
300
+ },
301
+ allowPositionals: true,
302
+ strict: true
303
+ });
304
+ if (values.help) {
305
+ io.stdout(HELP$3);
306
+ return EXIT.ok;
307
+ }
308
+ const [type, file, ...extra] = positionals;
309
+ if (type === void 0 || file === void 0 || extra.length > 0) throw new UsageError("Give a type and a file: `okforest new <type> <file>`, e.g. `okforest new Metric metrics/churn.md`.");
310
+ if (type.trim() === "") throw new UsageError("The type can't be blank.");
311
+ const root = values.root ?? ".";
312
+ const path = posix.normalize(file.replaceAll("\\", "/")).replace(/^\.\//, "");
313
+ if (!path.endsWith(".md") || path.startsWith("../") || posix.isAbsolute(path)) throw new UsageError(`${file} isn't a markdown file in the tree: give a path ending in .md.`);
314
+ const name = posix.basename(path);
315
+ if (name === "index.md" || name === "log.md") throw new UsageError(`${name} is OKF's, not a concept: give another name.`);
316
+ if (path.split("/").some((segment) => segment === ".okforest" || segment === ".git")) throw new UsageError(`${file} is in a folder OKF leaves out of the tree.`);
317
+ const tree = await loadTree(root, io);
318
+ const target = resolve(io.cwd, root, path);
319
+ if (await exists(target)) throw new UsageError(`${path} exists already.`);
320
+ const template = tree.templates.find((t) => t.name === type && t.frontmatter);
321
+ const text = startPage({
322
+ type,
323
+ ...values.title !== void 0 && { title: values.title },
324
+ ...values.description !== void 0 && { description: values.description }
325
+ }, template);
326
+ await mkdir(dirname(target), { recursive: true });
327
+ await writeFile(target, text, { flag: "wx" });
328
+ const folder = posix.dirname(path);
329
+ const index = folder === "." ? "index.md" : `${folder}/index.md`;
330
+ const listed = tree.files.includes(index);
331
+ if (listed) {
332
+ const indexFile = resolve(io.cwd, root, index);
333
+ const before = await readFile(indexFile, "utf8");
334
+ const entry = `* [${(values.title ?? name.slice(0, -3)).replace(/[[\]]/g, "\\$&")}](${name})${values.description ? ` - ${values.description}` : ""}`;
335
+ await writeFile(indexFile, `${before}${before === "" || before.endsWith("\n") ? "" : "\n"}${entry}\n`);
336
+ }
337
+ io.stdout(`Created ${path} ${template ? `from ${template.path}` : `(${type} has no template in ${TYPES_FOLDER})`}${listed ? `, listed in ${index}` : ""}.\n\n`);
338
+ const mine = (await validate(await loadTree(root, io))).findings.filter((f) => f.file === path || listed && f.file === index);
339
+ if (mine.length > 0) io.stdout(toText(onlyThese(mine, listed ? 2 : 1), io));
340
+ return EXIT.ok;
341
+ }
342
+ /** A result narrowed to the new page (and its index), counted again. */
343
+ function onlyThese(findings, files) {
344
+ const count = (severity) => findings.filter((f) => f.severity === severity).length;
345
+ const errors = count("error");
346
+ return {
347
+ findings,
348
+ errors,
349
+ warnings: count("warning"),
350
+ infos: count("info"),
351
+ concepts: 1,
352
+ files,
353
+ ok: errors === 0
354
+ };
355
+ }
356
+ const exists = (path) => access(path).then(() => true, () => false);
196
357
  // src/commands/rule.ts
197
- const HELP$3 = `Usage: okforest rule [rule] [--format text|json]
358
+ const HELP$2 = `Usage: okforest rule [rule] [--format text|json]
198
359
 
199
360
  Explain a rule: why it exists, an example that breaks it, what
200
361
  \`okforest validate\` reports for it, and the fix. Without a rule, list every
@@ -207,7 +368,7 @@ Examples
207
368
  okforest rule okf/type
208
369
  okforest rule --format json okforest/slug
209
370
  `;
210
- const COLOR$1 = {
371
+ const COLOR = {
211
372
  error: "red",
212
373
  warning: "yellow",
213
374
  info: "cyan"
@@ -228,7 +389,7 @@ async function ruleCommand(args, io) {
228
389
  strict: true
229
390
  });
230
391
  if (values.help) {
231
- io.stdout(HELP$3);
392
+ io.stdout(HELP$2);
232
393
  return EXIT.ok;
233
394
  }
234
395
  if (positionals.length > 1) throw new UsageError(`Expected one rule, got ${positionals.length}: ${positionals.join(" ")}`);
@@ -272,7 +433,7 @@ function list(io) {
272
433
  for (const name of ["OKF specification", "OKForest conventions"]) {
273
434
  out.push(paint(io, "underline", name));
274
435
  const rules = defaultRules.filter((found) => set(found) === name).sort((a, b) => a.id.localeCompare(b.id));
275
- for (const rule of rules) out.push(` ${rule.id.padEnd(width)} ${paint(io, COLOR$1[rule.severity], rule.severity.padEnd(7))} ${rule.description}`);
436
+ for (const rule of rules) out.push(` ${rule.id.padEnd(width)} ${paint(io, COLOR[rule.severity], rule.severity.padEnd(7))} ${rule.description}`);
276
437
  out.push("");
277
438
  }
278
439
  out.push("Run `okforest rule <rule>` for why a rule exists and how to fix it.");
@@ -283,7 +444,7 @@ function explain(rule, io) {
283
444
  const docs = ruleDocs[rule.id];
284
445
  const heading = (text) => paint(io, "underline", text);
285
446
  const out = [
286
- `${paint(io, "bold", rule.id)} ${paint(io, COLOR$1[rule.severity], rule.severity)} ${paint(io, "dim", set(rule))}`,
447
+ `${paint(io, "bold", rule.id)} ${paint(io, COLOR[rule.severity], rule.severity)} ${paint(io, "dim", set(rule))}`,
287
448
  "",
288
449
  ...wrap(rule.description, ""),
289
450
  ""
@@ -296,7 +457,7 @@ function explain(rule, io) {
296
457
  out.push(heading("okforest validate reports"), ` ${file}`);
297
458
  for (const finding of findings) {
298
459
  const [at = "", ...message] = finding.split(" ");
299
- out.push(` ${at === "-:-" ? "" : at} ${paint(io, COLOR$1[rule.severity], rule.severity.padEnd(7))} ${message.join(" ")}`);
460
+ out.push(` ${at === "-:-" ? "" : at} ${paint(io, COLOR[rule.severity], rule.severity.padEnd(7))} ${message.join(" ")}`);
300
461
  }
301
462
  out.push("");
302
463
  if (fixed === void 0) out.push(heading("Nothing to fix"), "");
@@ -357,7 +518,7 @@ function edits(a, b) {
357
518
  return previous[b.length];
358
519
  }
359
520
  // src/commands/types.ts
360
- const HELP$2 = `Usage: okforest types <command> [path]
521
+ const HELP$1 = `Usage: okforest types <command> [path]
361
522
 
362
523
  Work with the tree's type schemas: a JSON Schema for each type's frontmatter
363
524
  in ${TYPES_FOLDER}, which \`okforest validate\` checks concepts against.
@@ -384,7 +545,7 @@ const COMMANDS$1 = { init: typesInit };
384
545
  async function typesCommand(args, io) {
385
546
  const [command, ...rest] = args;
386
547
  if (command === void 0 || command === "-h" || command === "--help") {
387
- io.stdout(HELP$2);
548
+ io.stdout(HELP$1);
388
549
  return command === void 0 ? EXIT.usage : EXIT.ok;
389
550
  }
390
551
  if (!Object.hasOwn(COMMANDS$1, command)) throw new UsageError(`Unknown command \`types ${command}\`. Run \`okforest types --help\` for usage.`);
@@ -452,83 +613,6 @@ async function typesInit(args, io) {
452
613
  function slug(type) {
453
614
  return type.toLowerCase().replace(/[^\p{L}\p{N}]+/gu, "-").replace(/^-+|-+$/g, "") || "type";
454
615
  }
455
- // src/commands/validate.ts
456
- const HELP$1 = `Usage: okforest validate [path] [--format text|json]
457
-
458
- Check the OKF v0.2 tree at path (default: the current directory) against the
459
- OKF specification and OKForest conventions. Exits 1 when there are errors;
460
- warnings and info are reported but never fail.
461
-
462
- Options
463
- --format text|json Output format (default: text). JSON is for CI and tools.
464
- `;
465
- async function validateCommand(args, io) {
466
- const { values, path } = parseCommand(args, { format: { type: "string" } });
467
- if (values.help) {
468
- io.stdout(HELP$1);
469
- return EXIT.ok;
470
- }
471
- const format = formatOption(values.format);
472
- const result = await validate(await loadTree(path, io));
473
- io.stdout(format === "json" ? toJson(path, result) : toText(result, io));
474
- return result.ok ? EXIT.ok : EXIT.failed;
475
- }
476
- /** The shared validation report (`@okforest/validate`'s `toReport`), as JSON. */
477
- function toJson(path, result) {
478
- return `${JSON.stringify(toReport(result, {
479
- tool: {
480
- name: "okforest",
481
- version: VERSION
482
- },
483
- path
484
- }), null, 2)}\n`;
485
- }
486
- const LABEL = {
487
- error: "error",
488
- warning: "warning",
489
- info: "info"
490
- };
491
- const COLOR = {
492
- error: "red",
493
- warning: "yellow",
494
- info: "cyan"
495
- };
496
- function toText(result, io) {
497
- const out = [];
498
- const byFile = /* @__PURE__ */ new Map();
499
- for (const finding of result.findings) byFile.set(finding.file, [...byFile.get(finding.file) ?? [], finding]);
500
- for (const [file, findings] of byFile) {
501
- out.push(paint(io, "underline", file));
502
- const positions = findings.map((f) => f.line === void 0 ? "" : `${f.line}:${f.column ?? 1}`);
503
- const width = Math.max(...positions.map((p) => p.length));
504
- findings.forEach((f, i) => {
505
- out.push(` ${paint(io, "dim", positions[i].padEnd(width))} ${paint(io, COLOR[f.severity], LABEL[f.severity].padEnd(7))} ${f.message} ${paint(io, "dim", f.ruleId)}`);
506
- });
507
- out.push("");
508
- }
509
- out.push(...ruleDocs$1(result.findings, io));
510
- out.push(summary(result, io));
511
- return `${out.join("\n")}\n`;
512
- }
513
- /** Each rule that reported something, with its documentation page. */
514
- function ruleDocs$1(findings, io) {
515
- const ids = [...new Set(findings.map((f) => f.ruleId))];
516
- if (ids.length === 0) return [];
517
- const width = Math.max(...ids.map((id) => id.length));
518
- return [
519
- paint(io, "underline", "Rule docs"),
520
- ...ids.map((id) => ` ${id.padEnd(width)} ${paint(io, "dim", ruleUrl(id))}`),
521
- ` ${paint(io, "dim", "Run `okforest rule <rule>` for why and how to fix.")}`,
522
- ""
523
- ];
524
- }
525
- function summary(result, io) {
526
- const plural = (n, word) => `${n} ${word}${n === 1 ? "" : "s"}`;
527
- const scope = `${plural(result.concepts, "concept")} in ${plural(result.files, "file")}`;
528
- if (result.findings.length === 0) return `${paint(io, "green", "✔")} No problems · ${scope}`;
529
- const counts = `${plural(result.errors, "error")}, ${plural(result.warnings, "warning")}, ${result.infos} info`;
530
- return result.ok ? `${paint(io, "green", "✔")} ${counts} · ${scope}` : `${paint(io, "red", "✖")} ${counts} · ${scope}`;
531
- }
532
616
  // src/main.ts
533
617
  const HELP = `okforest ${VERSION}: validate, inventory, and scaffold Open Knowledge Format (OKF) v0.2 trees
534
618
 
@@ -536,6 +620,7 @@ Usage
536
620
  okforest validate [path] [--format text|json]
537
621
  okforest inventory [path] [--format text|json]
538
622
  okforest init [path] --template company [--name <name>]
623
+ okforest new <type> <file> [--title <title>] [--description <text>]
539
624
  okforest rule [rule] [--format text|json]
540
625
  okforest types init [path] [--type <type>]... [--dry-run]
541
626
 
@@ -545,6 +630,8 @@ Commands
545
630
  inventory List every type, tag, and frontmatter key in use, with counts
546
631
  and likely near-duplicates.
547
632
  init Create a new tree from a starter template (templates: company).
633
+ new Create a concept of a type, from the type's template
634
+ (.okforest/types/<type>.template.md) when it has one.
548
635
  rule Explain a rule: why it exists, an example, and the fix.
549
636
  Without a rule, list every rule.
550
637
  types Work with the tree's type schemas (.okforest/types/):
@@ -564,6 +651,7 @@ const COMMANDS = {
564
651
  validate: validateCommand,
565
652
  inventory: inventoryCommand,
566
653
  init: initCommand,
654
+ new: newCommand,
567
655
  rule: ruleCommand,
568
656
  types: typesCommand
569
657
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "okforest",
3
- "version": "0.12.0",
3
+ "version": "0.14.0",
4
4
  "description": "The OKForest CLI: validate Open Knowledge Format (OKF) v0.2 trees, inventory their metadata, and scaffold new trees from templates.",
5
5
  "keywords": [
6
6
  "okf",
@@ -32,8 +32,8 @@
32
32
  "node": ">=22"
33
33
  },
34
34
  "dependencies": {
35
- "@okforest/okf": "0.12.0",
36
- "@okforest/validate": "0.12.0"
35
+ "@okforest/okf": "0.14.0",
36
+ "@okforest/validate": "0.14.0"
37
37
  },
38
38
  "devDependencies": {
39
39
  "@types/node": "^26.6.6",
@@ -0,0 +1,26 @@
1
+ {
2
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
3
+ "title": "Customer Profile",
4
+ "description": "A kind of customer the company serves well, and how to recognize one.",
5
+ "type": "object",
6
+ "properties": {
7
+ "industries": {
8
+ "type": "array",
9
+ "items": { "type": "string" },
10
+ "description": "The industries they work in."
11
+ },
12
+ "company_size": {
13
+ "type": "string",
14
+ "description": "How big they are, like 50 to 500 employees."
15
+ },
16
+ "regions": {
17
+ "type": "array",
18
+ "items": { "type": "string" },
19
+ "description": "Where they are."
20
+ },
21
+ "buyer": {
22
+ "type": "string",
23
+ "description": "The role of the person who buys, like Head of Operations."
24
+ }
25
+ }
26
+ }
@@ -0,0 +1,21 @@
1
+ {
2
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
3
+ "title": "Organization",
4
+ "description": "A company or other organization: what it does, and where and when it began. Named after schema.org's Organization.",
5
+ "type": "object",
6
+ "properties": {
7
+ "website": {
8
+ "type": "string",
9
+ "format": "uri",
10
+ "description": "Its website's address."
11
+ },
12
+ "founded": {
13
+ "type": "integer",
14
+ "description": "The year it was founded."
15
+ },
16
+ "headquarters": {
17
+ "type": "string",
18
+ "description": "Where it's based: a city and country."
19
+ }
20
+ }
21
+ }
@@ -4,6 +4,9 @@ title: Company overview
4
4
  description: What the company does, why it exists, and who it serves.
5
5
  tags: [company]
6
6
  status: draft
7
+ # website: https://www.acme.example
8
+ # founded: 2019
9
+ # headquarters: Austin, United States
7
10
  generated: { by: okforest/{{version}}, at: {{now}} }
8
11
  ---
9
12
 
@@ -4,6 +4,10 @@ title: Ideal customer profile
4
4
  description: The customers the company serves best, and how to recognize them.
5
5
  tags: [customers, sales]
6
6
  status: draft
7
+ # industries: [logistics, retail]
8
+ # company_size: 50 to 500 employees
9
+ # regions: [North America]
10
+ # buyer: Head of Operations
7
11
  generated: { by: okforest/{{version}}, at: {{now}} }
8
12
  ---
9
13