@appling/cli 0.1.1 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/README.md +48 -4
  2. package/out/main.js +198 -36
  3. package/package.json +6 -4
package/README.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # @appling/cli
2
2
 
3
- Command line tool to check and format Appling models (`.appling` files).
3
+ Command line tool to check, format and inspect Appling models (`.appling` files).
4
4
 
5
5
  Appling is a declarative language that describes a business or web application in five layers: domain, behavior, application, interfaces and experience. The language itself lives in [`@appling/lang`](https://www.npmjs.com/package/@appling/lang).
6
6
 
@@ -21,6 +21,12 @@ npx @appling/cli check models
21
21
  ```sh
22
22
  appling check [files or folders...]
23
23
  appling fmt [files or folders...]
24
+ appling graph [files or folders...]
25
+ appling release <version> [files or folders...]
26
+ appling generate [--plan | --migrate] [files or folders...]
27
+ appling simulate reach <machine> <state> [files or folders...]
28
+ appling simulate actors <action> [files or folders...]
29
+ appling simulate risks <action> [files or folders...]
24
30
  ```
25
31
 
26
32
  Folders are searched recursively for `.appling` files. Hidden folders and `node_modules` are skipped. Without a path, the current folder is used.
@@ -40,19 +46,57 @@ models/sales.appling:13:23 error A machine must govern an entity field marked "s
40
46
 
41
47
  Rewrites every file into its canonical form:
42
48
 
43
- - Gives every element without a stable id a new one, such as `entity Order #1kzox`.
44
49
  - Normalizes whitespace, indentation and line breaks. Comments are kept.
45
50
  - Running it twice changes nothing.
46
51
 
47
52
  Files with syntax errors are left untouched and reported.
48
53
 
54
+ ### graph
55
+
56
+ Prints the semantic graph of the model as JSON: every element as a node with its qualified name, kind, layer, zoom level, module and properties, every reference as an edge, and the module to module dependencies. Unnamed elements such as policies or transitions get a key derived from their content, for example `sales.Order.policy[read fields total]`.
57
+
58
+ ```json
59
+ {
60
+ "nodes": [{ "qn": "sales.Order.status", "kind": "Field", "layer": "domain", "level": "in", "module": "sales", "props": { "type": "OrderStatus", "modifiers": ["state"], "default": "draft" } }],
61
+ "edges": [{ "from": "sales.Order.status", "to": "sales.OrderStatus", "kind": "type" }],
62
+ "dependencies": [{ "from": "sales", "to": "crm", "count": 1 }]
63
+ }
64
+ ```
65
+
66
+ When the model has errors, they are printed to stderr instead and nothing is written to stdout.
67
+
68
+ ### release
69
+
70
+ Writes a snapshot of the semantic graph to `.appling/releases/<version>.json` in the current folder. The version looks like `1.2.3`. A model with errors is not released, and an existing version is never overwritten.
71
+
72
+ Once a release exists, tools that edit the model (the IDE, the AI) record renames, type changes and removals of released domain elements as migration steps, in one block per module named after the release, such as `migration since_v1_0_0`.
73
+
74
+ ### generate
75
+
76
+ Generates a draft project for every target in `appling.config.json` through its code generation extension, and writes the task registry `.appling/tasks.json` into it. See [`@appling/codegen`](https://www.npmjs.com/package/@appling/codegen) for the configuration. With `--plan`, it prints the steps without running them.
77
+
78
+ Generation checks the tools the extension needs first and refuses to write into a folder that is not empty.
79
+
80
+ With `--migrate`, it carries the model's migration steps that a generated project has not applied yet into it: renames, type changes and removals become framework migrations that keep the data (a rename stays a rename, not a drop and an add), the generated model code changes with them, and updating the rest of the code becomes registry tasks. Applied steps are recorded in the project's `.appling/migrations.json`.
81
+
82
+ ### simulate
83
+
84
+ Asks the simulator about behavior: whether a state of a machine is reachable and by which transitions, which actors may trigger an action (yes, no, or depending on the data), and which invariants an action puts at risk through the fields it changes.
85
+
86
+ ```
87
+ $ appling simulate reach sales.OrderFlow paid models
88
+ paid is reachable from draft:
89
+ PlaceOrder -> placed
90
+ PaymentReceived -> paid
91
+ ```
92
+
49
93
  ## Exit codes
50
94
 
51
95
  | Code | Meaning |
52
96
  |---|---|
53
97
  | 0 | No errors |
54
- | 1 | `check` found errors, or `fmt` skipped a file with syntax errors |
55
- | 2 | Unknown command |
98
+ | 1 | `check`, `graph`, `release` or `generate` found errors, `release` found an invalid or existing version, `generate` failed, or `fmt` skipped a file with syntax errors |
99
+ | 2 | Unknown command, or `release` without a version |
56
100
 
57
101
  ## License
58
102
 
package/out/main.js CHANGED
@@ -1,48 +1,217 @@
1
1
  #!/usr/bin/env node
2
- import { randomBytes } from 'node:crypto';
3
- import { readdirSync, statSync, writeFileSync } from 'node:fs';
4
- import { join, relative, resolve } from 'node:path';
5
- import { AstUtils, URI } from 'langium';
2
+ import { existsSync, mkdtempSync, readdirSync, rmSync, writeFileSync } from 'node:fs';
3
+ import { tmpdir } from 'node:os';
4
+ import { basename, join, relative, resolve } from 'node:path';
5
+ import { URI } from 'langium';
6
6
  import { NodeFileSystem } from 'langium/node';
7
- import { createApplingServices, hasStableId, print } from '@appling/lang';
8
- const USAGE = 'Usage: appling <check|fmt> [files or folders...]';
9
- async function main([command, ...paths]) {
10
- if (command !== 'check' && command !== 'fmt') {
7
+ import { createApplingServices, print } from '@appling/lang';
8
+ import { BASELINE, checkPrerequisites, describe, loadExtension, mergeGeneration, pendingChanges, plan, planMigrations, readApplied, readConfig, readRegistry, runMigrations, runPlan } from '@appling/codegen';
9
+ import { buildGraph, dependencies, findApplingFiles, Simulator, writeRelease } from '@appling/model';
10
+ const USAGE = [
11
+ 'Usage: appling <check|fmt|graph> [files or folders...]',
12
+ ' appling release <version> [files or folders...]',
13
+ ' appling generate [--plan | --migrate | --sync] [files or folders...]',
14
+ ' appling simulate <reach <machine> <state> | actors <action> | risks <action>> [files or folders...]'
15
+ ].join('\n');
16
+ async function main([command, ...args]) {
17
+ const question = command === 'simulate' ? args.slice(0, args[0] === 'reach' ? 3 : 2) : [];
18
+ if (!['check', 'fmt', 'graph', 'release', 'generate', 'simulate'].includes(command) || (command === 'release' && !args[0])
19
+ || (command === 'simulate' && (!['reach', 'actors', 'risks'].includes(question[0]) || question.some(a => !a)))) {
11
20
  console.error(USAGE);
12
21
  return 2;
13
22
  }
14
- const files = (paths.length ? paths : ['.']).flatMap(p => applingFiles(resolve(p)));
15
- const { shared } = createApplingServices(NodeFileSystem);
23
+ const mode = command === 'generate' && ['--plan', '--migrate', '--sync'].includes(args[0]) ? args[0] : undefined;
24
+ const [version, paths] = command === 'release' ? [args[0], args.slice(1)] : ['', args.slice(mode ? 1 : question.length)];
25
+ const files = (paths.length ? paths : ['.']).flatMap(p => findApplingFiles(resolve(p)));
26
+ const { shared, Appling } = createApplingServices(NodeFileSystem);
16
27
  const documents = await Promise.all(files.map(f => shared.workspace.LangiumDocuments.getOrCreateDocument(URI.file(f))));
17
- await shared.workspace.DocumentBuilder.build(documents, { validation: command === 'check' });
18
- return command === 'check' ? check(documents) : format(documents);
28
+ await shared.workspace.DocumentBuilder.build(documents, { validation: command !== 'fmt' });
29
+ if (command === 'fmt')
30
+ return format(documents);
31
+ if (command === 'graph')
32
+ return graph(documents, Appling);
33
+ if (command === 'release')
34
+ return release(documents, Appling, version);
35
+ if (command === 'generate')
36
+ return generate(documents, Appling, mode);
37
+ if (command === 'simulate')
38
+ return simulate(documents, Appling, question);
39
+ const errors = report(documents, console.log);
40
+ console.log(`${documents.length} file(s), ${errors} error(s)`);
41
+ return errors ? 1 : 0;
42
+ }
43
+ function simulate(documents, services, [question, target, state]) {
44
+ if (report(documents, console.error))
45
+ return 1;
46
+ const simulator = new Simulator(buildGraph(documents.map(doc => doc.parseResult.value), services));
47
+ try {
48
+ if (question === 'reach') {
49
+ const reach = simulator.reach(target, state);
50
+ console.log(reach
51
+ ? [`${state} is reachable from ${reach.from}:`, ...reach.path.map(p => ` ${p.trigger} -> ${p.to}${p.guarded ? ' (guarded)' : ''}`)].join('\n')
52
+ : `${state} is not reachable`);
53
+ }
54
+ else if (question === 'actors') {
55
+ for (const { actor, verdict } of simulator.actors(target))
56
+ console.log(`${actor}: ${verdict === 'depends' ? 'depends on the data' : verdict}`);
57
+ }
58
+ else {
59
+ const risks = simulator.risks(target);
60
+ console.log(risks.length ? risks.map(r => `${r.invariant} (reads ${r.fields.join(', ')})`).join('\n') : 'no invariant reads a field this action changes');
61
+ }
62
+ return 0;
63
+ }
64
+ catch (error) {
65
+ console.error(error.message);
66
+ return 1;
67
+ }
68
+ }
69
+ async function generate(documents, services, mode) {
70
+ if (report(documents, console.error))
71
+ return 1;
72
+ const targets = readConfig('.').generate ?? [];
73
+ if (!targets.length) {
74
+ console.error('No targets: add "generate": [{ "extension": "...", "out": "..." }] to appling.config.json.');
75
+ return 1;
76
+ }
77
+ const graph = buildGraph(documents.map(doc => doc.parseResult.value), services);
78
+ for (const target of targets) {
79
+ const failed = mode === '--migrate' ? await migrateTarget(graph, target.extension, target.out, target.options ?? {})
80
+ : mode === '--sync' ? await syncTarget(graph, target.extension, target.out, target.options ?? {})
81
+ : await generateTarget(graph, target.extension, target.out, target.options ?? {}, mode === '--plan');
82
+ if (failed)
83
+ return 1;
84
+ }
85
+ return 0;
86
+ }
87
+ /**
88
+ * Brings a generated project up to the current model: applies pending migration steps, generates the model
89
+ * afresh in a temporary folder and merges it three ways with the project. Returns true when it failed.
90
+ */
91
+ async function syncTarget(graph, name, out, options) {
92
+ if (!readRegistry(out) || !existsSync(join(out, BASELINE))) {
93
+ console.error(`${out} has no generation baseline. Generate it with this version of appling first.`);
94
+ return true;
95
+ }
96
+ const extension = await loadExtension(name, '.');
97
+ if (extension.migrate && await migrateTarget(graph, name, out, options))
98
+ return true;
99
+ const missing = checkPrerequisites(extension.prerequisites ?? [], graph);
100
+ if (missing.length) {
101
+ missing.forEach(m => console.error(m));
102
+ return true;
103
+ }
104
+ const temp = mkdtempSync(join(tmpdir(), 'appling-sync-'));
105
+ try {
106
+ const next = join(temp, basename(resolve(out)));
107
+ runPlan(plan(graph, extension, String(options.name ?? basename(resolve(out))), options), next, line => console.log(` ${line}`));
108
+ const report = mergeGeneration(out, next, extension.syncExclude ?? []);
109
+ for (const [label, files] of Object.entries(report))
110
+ if (files.length)
111
+ console.log(`${label}: ${files.join(', ')}`);
112
+ console.log(`${out}: synced${report.conflicts.length ? `, ${report.conflicts.length} file(s) with conflict markers (registry tasks)` : ''}`);
113
+ return false;
114
+ }
115
+ catch (error) {
116
+ console.error(error.message);
117
+ return true;
118
+ }
119
+ finally {
120
+ rmSync(temp, { recursive: true, force: true });
121
+ }
122
+ }
123
+ /** Carries the model's migration steps that a generated project has not applied yet into it. Returns true when it failed. */
124
+ async function migrateTarget(graph, name, out, options) {
125
+ if (!readRegistry(out)) {
126
+ console.error(`${out} was not generated yet. Run "appling generate" first.`);
127
+ return true;
128
+ }
129
+ const extension = await loadExtension(name, '.');
130
+ const stamp = new Date().toISOString().replace(/\D/g, '').slice(0, 14);
131
+ const changes = pendingChanges(graph, readApplied(out), stamp);
132
+ if (!changes.length) {
133
+ console.log(`${out}: no pending migration steps`);
134
+ return false;
135
+ }
136
+ try {
137
+ const plan = planMigrations(graph, extension, String(options.name ?? basename(resolve(out))), options, out, changes);
138
+ runMigrations(out, plan, changes, line => console.log(line));
139
+ console.log(`${out}: ${changes.length} migration step(s) applied, ${plan.tasks.length} task(s) added to the registry`);
140
+ return false;
141
+ }
142
+ catch (error) {
143
+ console.error(error.message);
144
+ return true;
145
+ }
146
+ }
147
+ /** Returns true when the target failed. */
148
+ async function generateTarget(graph, name, out, options, onlyPlan) {
149
+ const extension = await loadExtension(name, '.');
150
+ const result = plan(graph, extension, String(options.name ?? basename(resolve(out))), options);
151
+ if (onlyPlan) {
152
+ console.log(`${name} -> ${out}`);
153
+ for (const { node, step } of result.steps)
154
+ console.log(` ${node}: ${describe(step)}`);
155
+ console.log(summary(result));
156
+ return false;
157
+ }
158
+ const missing = checkPrerequisites(extension.prerequisites ?? [], graph);
159
+ if (missing.length) {
160
+ missing.forEach(m => console.error(m));
161
+ return true;
162
+ }
163
+ if (existsSync(out) && readdirSync(out).length) {
164
+ console.error(`${out} is not empty. Generation creates a new draft project once.`);
165
+ return true;
166
+ }
167
+ try {
168
+ runPlan(result, out, line => console.log(line));
169
+ }
170
+ catch (error) {
171
+ console.error(error.message);
172
+ return true;
173
+ }
174
+ console.log(summary(result));
175
+ return false;
176
+ }
177
+ function summary(result) {
178
+ const count = (status) => result.entries.filter(e => e.status === status).length;
179
+ return `${result.entries.length} element(s): ${count('generated')} generated, ${count('partial')} partial, ${count('todo')} todo`;
180
+ }
181
+ function release(documents, services, version) {
182
+ if (report(documents, console.error))
183
+ return 1;
184
+ try {
185
+ const file = writeRelease('.', version, buildGraph(documents.map(doc => doc.parseResult.value), services));
186
+ console.log(`released ${version} to ${relative('.', file)}`);
187
+ return 0;
188
+ }
189
+ catch (error) {
190
+ console.error(error.message);
191
+ return 1;
192
+ }
19
193
  }
20
- function check(documents) {
194
+ /** Prints every diagnostic and returns the number of errors. */
195
+ function report(documents, log) {
21
196
  let errors = 0;
22
197
  for (const doc of documents) {
23
198
  for (const d of doc.diagnostics ?? []) {
24
199
  const severity = d.severity === 1 ? 'error' : 'warning';
25
200
  if (severity === 'error')
26
201
  errors++;
27
- console.log(`${relative('.', doc.uri.fsPath)}:${d.range.start.line + 1}:${d.range.start.character + 1} ${severity} ${d.message}`);
202
+ log(`${relative('.', doc.uri.fsPath)}:${d.range.start.line + 1}:${d.range.start.character + 1} ${severity} ${d.message}`);
28
203
  }
29
204
  }
30
- console.log(`${documents.length} file(s), ${errors} error(s)`);
31
- return errors ? 1 : 0;
205
+ return errors;
206
+ }
207
+ function graph(documents, services) {
208
+ if (report(documents, console.error))
209
+ return 1;
210
+ const result = buildGraph(documents.map(doc => doc.parseResult.value), services);
211
+ console.log(JSON.stringify({ ...result, dependencies: dependencies(result) }, null, 2));
212
+ return 0;
32
213
  }
33
214
  function format(documents) {
34
- const used = new Set(documents.flatMap(doc => AstUtils.streamAst(doc.parseResult.value)
35
- .filter(hasStableId)
36
- .map(n => n.id)
37
- .toArray()));
38
- const newId = () => {
39
- let id;
40
- do
41
- id = '#' + randomBytes(4).readUInt32BE().toString(36).padStart(7, '0').slice(-5);
42
- while (used.has(id));
43
- used.add(id);
44
- return id;
45
- };
46
215
  let failed = 0;
47
216
  for (const doc of documents) {
48
217
  const { lexerErrors, parserErrors } = doc.parseResult;
@@ -51,7 +220,7 @@ function format(documents) {
51
220
  console.error(`${relative('.', doc.uri.fsPath)}: not formatted, fix syntax errors first (run "appling check")`);
52
221
  continue;
53
222
  }
54
- const text = print(doc.parseResult.value, newId);
223
+ const text = print(doc.parseResult.value);
55
224
  if (text !== doc.textDocument.getText()) {
56
225
  writeFileSync(doc.uri.fsPath, text);
57
226
  console.log(`formatted ${relative('.', doc.uri.fsPath)}`);
@@ -59,11 +228,4 @@ function format(documents) {
59
228
  }
60
229
  return failed ? 1 : 0;
61
230
  }
62
- function applingFiles(path) {
63
- if (!statSync(path).isDirectory())
64
- return [path];
65
- return readdirSync(path, { withFileTypes: true })
66
- .filter(e => !e.name.startsWith('.') && e.name !== 'node_modules')
67
- .flatMap(e => e.isDirectory() ? applingFiles(join(path, e.name)) : e.name.endsWith('.appling') ? [join(path, e.name)] : []);
68
- }
69
231
  main(process.argv.slice(2)).then(code => process.exit(code));
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@appling/cli",
3
- "version": "0.1.1",
4
- "description": "Command line tool to check and format Appling models",
3
+ "version": "0.2.0",
4
+ "description": "Command line tool to check, format, inspect, release and generate Appling models",
5
5
  "type": "module",
6
6
  "bin": {
7
7
  "appling": "./out/main.js"
@@ -10,8 +10,10 @@
10
10
  "out"
11
11
  ],
12
12
  "dependencies": {
13
- "@appling/lang": "0.1.1",
14
- "langium": "4.4.0"
13
+ "langium": "4.4.0",
14
+ "@appling/codegen": "0.1.0",
15
+ "@appling/lang": "0.2.0",
16
+ "@appling/model": "0.1.0"
15
17
  },
16
18
  "devDependencies": {
17
19
  "@types/node": "^24.19.2",