@basementuniverse/jsonpad-cli 1.4.0 → 1.6.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/build/flows.js ADDED
@@ -0,0 +1,153 @@
1
+ import path from 'node:path';
2
+ import { compile, runTests, version as engineVersion, } from '@basementuniverse/jsonpad-flows';
3
+ import { CliError, EXIT_TESTS_FAILED } from './errors.js';
4
+ import { readJsonFile } from './rules.js';
5
+ export { engineVersion };
6
+ /**
7
+ * Where `flows test` looks for a flow's tests when it isn't told
8
+ */
9
+ export function defaultFlowTestsFile(flowFile) {
10
+ return flowFile.replace(/(\.flow)?(\.json)?$/, '.tests.json');
11
+ }
12
+ /**
13
+ * Print a flow's diagnostics as file: path, with the line and column of the
14
+ * problem inside an expression when there is one
15
+ */
16
+ export function printFlowDiagnostics(context, diagnostics, file) {
17
+ const { red, yellow, dim } = context.colours;
18
+ let errors = 0;
19
+ let warnings = 0;
20
+ for (const diagnostic of diagnostics) {
21
+ const isError = diagnostic.severity === 'error';
22
+ if (isError) {
23
+ errors++;
24
+ }
25
+ else {
26
+ warnings++;
27
+ }
28
+ const where = `${file}:${diagnostic.path || '/'}${diagnostic.span
29
+ ? `:${diagnostic.span.line}:${diagnostic.span.column}`
30
+ : ''}`;
31
+ context.log(`${dim(where)} ${isError ? red('error') : yellow('warning')} ${diagnostic.message} ${dim(`[${diagnostic.code}]`)}`);
32
+ }
33
+ return { errors, warnings };
34
+ }
35
+ /**
36
+ * Compile a flow document, printing its diagnostics. Throws when it doesn't
37
+ * compile
38
+ */
39
+ export function compileFlow(context, document, file, options = {}) {
40
+ const { flow, diagnostics } = compile(document);
41
+ const { errors, warnings } = options.quiet
42
+ ? {
43
+ errors: diagnostics.filter(d => d.severity === 'error').length,
44
+ warnings: 0,
45
+ }
46
+ : printFlowDiagnostics(context, diagnostics, file);
47
+ if (!flow) {
48
+ throw new CliError(`${file} has ${errors} ${errors === 1 ? 'error' : 'errors'}`);
49
+ }
50
+ if (options.strict && warnings > 0) {
51
+ throw new CliError(`${file} has ${warnings} ${warnings === 1 ? 'warning' : 'warnings'} (--strict)`);
52
+ }
53
+ return flow;
54
+ }
55
+ function printFlowTestResult(context, result, options) {
56
+ const { green, red, dim } = context.colours;
57
+ if (result.passed) {
58
+ context.log(`${green('✓')} ${result.name}`);
59
+ return;
60
+ }
61
+ context.log(`${red('✗')} ${result.name}`);
62
+ for (const failure of result.failures) {
63
+ context.log(` ${failure}`);
64
+ }
65
+ if (options.trace && result.run?.trace) {
66
+ for (const entry of result.run.trace) {
67
+ const status = entry.status === 'ran'
68
+ ? green('ran')
69
+ : entry.status === 'failed'
70
+ ? red('failed')
71
+ : dim('skipped');
72
+ context.log(` ${dim(entry.id)} ${entry.type}: ${status}${entry.port ? dim(` → ${entry.port}`) : ''}${entry.error ? ` ${red(entry.error)}` : ''}`);
73
+ }
74
+ }
75
+ }
76
+ /**
77
+ * Run a flow's tests, printing each one, and throw if any of them fail
78
+ */
79
+ export async function runFlowTests(context, flow, document, file, options = {}) {
80
+ const run = await runTests(flow, document, {
81
+ filter: options.filter,
82
+ trace: options.trace ? 'values' : 'off',
83
+ });
84
+ if (run.errors.length > 0) {
85
+ throw new CliError([
86
+ `${file} isn't a valid flow test document:`,
87
+ ...run.errors.map(error => error.path
88
+ ? ` ${error.path}: ${error.message}`
89
+ : ` ${error.message}`),
90
+ ].join('\n'));
91
+ }
92
+ if (options.json) {
93
+ context.log(JSON.stringify({
94
+ passed: run.passed,
95
+ failed: run.failed,
96
+ results: run.results.map(result => ({
97
+ name: result.name,
98
+ passed: result.passed,
99
+ failures: result.failures,
100
+ })),
101
+ }, null, 2));
102
+ }
103
+ else {
104
+ for (const result of run.results) {
105
+ printFlowTestResult(context, result, options);
106
+ }
107
+ const { green, red } = context.colours;
108
+ context.log(`\n${run.passed} passed, ${run.failed > 0 ? red(`${run.failed} failed`) : green('0 failed')}`);
109
+ }
110
+ if (run.failed > 0) {
111
+ throw new CliError(`${run.failed} of ${run.results.length} ${run.results.length === 1 ? 'test' : 'tests'} failed`, EXIT_TESTS_FAILED);
112
+ }
113
+ }
114
+ /**
115
+ * Resolve the CLI-only flowFile and flowTestsFile fields in a schema sync
116
+ * document, relative to the document, into the document and tests the API
117
+ * takes
118
+ */
119
+ export function resolveFlowFiles(context, document, documentFile) {
120
+ const directory = path.dirname(path.resolve(context.cwd, documentFile));
121
+ for (const [name, flow] of Object.entries(document.flows ?? {})) {
122
+ for (const [field, target] of [
123
+ ['flowFile', 'document'],
124
+ ['flowTestsFile', 'tests'],
125
+ ]) {
126
+ const file = flow[field];
127
+ if (file === undefined) {
128
+ continue;
129
+ }
130
+ if (flow[target] !== undefined) {
131
+ throw new CliError(`Flow "${name}" has both ${field} and ${target}: use one or the other`);
132
+ }
133
+ const resolved = path.relative(context.cwd, path.resolve(directory, file));
134
+ flow[target] = readJsonFile(context, resolved, `${field} for flow "${name}"`);
135
+ delete flow[field];
136
+ }
137
+ }
138
+ }
139
+ /**
140
+ * Compile and test the flows in a schema sync document, before it's sent
141
+ */
142
+ export async function checkDocumentFlows(context, document) {
143
+ for (const [name, flow] of Object.entries(document.flows ?? {})) {
144
+ if (!flow.document || typeof flow.document !== 'object') {
145
+ continue;
146
+ }
147
+ const where = `flow "${name}"`;
148
+ const compiled = compileFlow(context, { name, ...flow.document }, where);
149
+ if (flow.tests) {
150
+ await runFlowTests(context, compiled, flow.tests, `the tests for ${where}`);
151
+ }
152
+ }
153
+ }
package/build/program.js CHANGED
@@ -9,6 +9,8 @@ import { defineItems } from './commands/items.js';
9
9
  import { defineListen } from './commands/listen.js';
10
10
  import { defineLists } from './commands/lists.js';
11
11
  import { defineRebuildIndex } from './commands/rebuild-index.js';
12
+ import { defineFlows } from './commands/flows.js';
13
+ import { defineRules } from './commands/rules.js';
12
14
  import { defineExportSchema } from './commands/schema/export.js';
13
15
  import { defineMoveLists } from './commands/schema/move.js';
14
16
  import { defineSyncSchema } from './commands/schema/sync.js';
@@ -45,6 +47,8 @@ export const EXIT_CODES_HELP = `Exit codes:
45
47
  7 The token isn't allowed to do this, or isn't valid
46
48
  8 Rate limited (after retrying), or a plan limit or the monthly quota was
47
49
  reached
50
+ 9 Write rule or flow tests failed, or a rules check refused a write
51
+ 10 A flow failed (flows run)
48
52
 
49
53
  The schema commands and rebuild-index (and indexes rebuild) exit with 1 for
50
54
  every API error, as they did in @basementuniverse/jsonpad-sdk.`;
@@ -100,6 +104,8 @@ export function createProgram(context) {
100
104
  defineIndexes(program.command('indexes'), context);
101
105
  defineItems(program.command('items'), context);
102
106
  defineIdentities(program.command('identities'), context);
107
+ defineRules(program.command('rules'), context);
108
+ defineFlows(program.command('flows'), context);
103
109
  defineWhoami(program.command('whoami'), context);
104
110
  defineConfig(program.command('config'), context);
105
111
  defineListen(program.command('listen'), context);
package/build/rules.js ADDED
@@ -0,0 +1,241 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import { compile, runTests, version as engineVersion, } from '@basementuniverse/jsonpad-rules';
4
+ import { CliError, EXIT_RULE_TESTS_FAILED } from './errors.js';
5
+ export { engineVersion };
6
+ /**
7
+ * Where `rules test` looks for a rule set's tests when it isn't told
8
+ */
9
+ export function defaultTestsFile(rulesFile) {
10
+ return rulesFile.replace(/(\.[^./\\]+)?$/, '.tests.json');
11
+ }
12
+ export function readTextFile(context, file, what) {
13
+ try {
14
+ return fs.readFileSync(path.resolve(context.cwd, file), 'utf8');
15
+ }
16
+ catch (error) {
17
+ throw new CliError(error.code === 'ENOENT'
18
+ ? `Can't find ${file} (${what})`
19
+ : `Can't read ${file} (${what}): ${error.message}`);
20
+ }
21
+ }
22
+ export function readJsonFile(context, file, what) {
23
+ const text = readTextFile(context, file, what);
24
+ try {
25
+ return JSON.parse(text);
26
+ }
27
+ catch (error) {
28
+ throw new CliError(`${file} isn't valid JSON: ${error.message}`);
29
+ }
30
+ }
31
+ /**
32
+ * Print diagnostics as file:line:column, the way compilers do, so an editor
33
+ * can jump to them
34
+ */
35
+ export function printDiagnostics(context, diagnostics, file) {
36
+ const { red, yellow, dim } = context.colours;
37
+ let errors = 0;
38
+ let warnings = 0;
39
+ for (const diagnostic of diagnostics) {
40
+ const isError = diagnostic.severity === 'error';
41
+ if (isError) {
42
+ errors++;
43
+ }
44
+ else {
45
+ warnings++;
46
+ }
47
+ context.log(`${dim(`${file}:${diagnostic.span.line}:${diagnostic.span.column}`)} ${isError ? red('error') : yellow('warning')} ${diagnostic.message} ${dim(`[${diagnostic.code}]`)}`);
48
+ }
49
+ return { errors, warnings };
50
+ }
51
+ /**
52
+ * Compile rule text, printing its diagnostics. Throws when it doesn't compile
53
+ */
54
+ export function compileRules(context, text, file, options = {}) {
55
+ const { ruleSet, diagnostics } = compile(text);
56
+ const { errors, warnings } = options.quiet
57
+ ? {
58
+ errors: diagnostics.filter(d => d.severity === 'error').length,
59
+ warnings: 0,
60
+ }
61
+ : printDiagnostics(context, diagnostics, file);
62
+ if (!ruleSet) {
63
+ throw new CliError(`${file} has ${errors} ${errors === 1 ? 'error' : 'errors'}`);
64
+ }
65
+ if (options.strict && warnings > 0) {
66
+ throw new CliError(`${file} has ${warnings} ${warnings === 1 ? 'warning' : 'warnings'} (--strict)`);
67
+ }
68
+ return ruleSet;
69
+ }
70
+ /**
71
+ * Print the result of one test, and its trace if asked for
72
+ */
73
+ export function printTestResult(context, result, options = {}) {
74
+ const { green, red, dim } = context.colours;
75
+ const describe = (outcome, expectation) => {
76
+ if (typeof expectation === 'object') {
77
+ return `${outcome} (expected the write to fail with "${expectation.fail}")`;
78
+ }
79
+ return `${outcome} (expected ${expectation})`;
80
+ };
81
+ if (result.passed) {
82
+ context.log(`${green('✓')} ${result.name}`);
83
+ return;
84
+ }
85
+ context.log(`${red('✗')} ${result.name} ${dim(describe(result.actual, result.expected))}`);
86
+ if (result.message) {
87
+ context.log(` ${result.message}`);
88
+ }
89
+ if (options.trace && result.decision) {
90
+ for (const statement of result.decision.statements) {
91
+ const outcome = statement.error
92
+ ? red(`error: ${statement.error}`)
93
+ : statement.result
94
+ ? green('true')
95
+ : dim('false');
96
+ context.log(` ${dim(`line ${statement.span.line}`)} ${statement.kind}${statement.label ? ` "${statement.label}"` : ''}: ${outcome}`);
97
+ }
98
+ }
99
+ }
100
+ /**
101
+ * Run a test document against a rule set, printing each test, and throw if
102
+ * any of them fail
103
+ */
104
+ export function runRuleTests(context, ruleSet, document, file, options = {}) {
105
+ const run = runTests(ruleSet, document, { filter: options.filter });
106
+ if (run.errors.length > 0) {
107
+ throw new CliError([
108
+ `${file} isn't a valid test document:`,
109
+ ...run.errors.map(error => error.path
110
+ ? ` ${error.path}: ${error.message}`
111
+ : ` ${error.message}`),
112
+ ].join('\n'));
113
+ }
114
+ if (options.json) {
115
+ context.log(JSON.stringify({
116
+ passed: run.passed,
117
+ failed: run.failed,
118
+ results: run.results.map(result => ({
119
+ name: result.name,
120
+ passed: result.passed,
121
+ expected: result.expected,
122
+ actual: result.actual,
123
+ message: result.message,
124
+ })),
125
+ }, null, 2));
126
+ }
127
+ else {
128
+ for (const result of run.results) {
129
+ printTestResult(context, result, options);
130
+ }
131
+ const { green, red } = context.colours;
132
+ context.log(`\n${run.passed} passed, ${run.failed > 0 ? red(`${run.failed} failed`) : green('0 failed')}`);
133
+ }
134
+ if (run.failed > 0) {
135
+ throw new CliError(`${run.failed} of ${run.results.length} ${run.results.length === 1 ? 'test' : 'tests'} failed`, EXIT_RULE_TESTS_FAILED);
136
+ }
137
+ }
138
+ /**
139
+ * Warn when the server's rules engine isn't the one built into this CLI: a
140
+ * rule set that passes here could still be refused there
141
+ */
142
+ export function checkEngineVersion(context, serverVersion) {
143
+ if (!serverVersion) {
144
+ return;
145
+ }
146
+ const [major, minor] = engineVersion.split('.');
147
+ const [serverMajor, serverMinor] = serverVersion.split('.');
148
+ if (major !== serverMajor || minor !== serverMinor) {
149
+ context.error(`${context.colours.yellow('warning')}: this CLI has rules engine ${engineVersion}, and the API has ${serverVersion}. The API decides: check your rules with --list if they disagree`);
150
+ }
151
+ }
152
+ /**
153
+ * Resolve the CLI-only rulesFile and rulesTestsFile fields in a schema sync
154
+ * document, relative to the document, into the rules and rulesTests the API
155
+ * takes
156
+ */
157
+ export function resolveRuleFiles(context, document, documentFile) {
158
+ const directory = path.dirname(path.resolve(context.cwd, documentFile));
159
+ for (const [pathName, list] of Object.entries(document.lists ?? {})) {
160
+ for (const [field, target] of [
161
+ ['rulesFile', 'rules'],
162
+ ['rulesTestsFile', 'rulesTests'],
163
+ ]) {
164
+ const file = list[field];
165
+ if (file === undefined) {
166
+ continue;
167
+ }
168
+ if (list[target] !== undefined) {
169
+ throw new CliError(`List "${pathName}" has both ${field} and ${target}: use one or the other`);
170
+ }
171
+ const resolved = path.relative(context.cwd, path.resolve(directory, file));
172
+ list[target] =
173
+ target === 'rules'
174
+ ? readTextFile(context, resolved, `${field} for list "${pathName}"`)
175
+ : readJsonFile(context, resolved, `${field} for list "${pathName}"`);
176
+ delete list[field];
177
+ }
178
+ }
179
+ }
180
+ /**
181
+ * Compile and test the write rules in a schema sync document, before it's
182
+ * sent
183
+ */
184
+ export function checkDocumentRules(context, document) {
185
+ for (const [pathName, list] of Object.entries(document.lists ?? {})) {
186
+ const rules = Array.isArray(list.rules)
187
+ ? list.rules.join('\n')
188
+ : list.rules;
189
+ if (typeof rules !== 'string' || rules.trim() === '') {
190
+ continue;
191
+ }
192
+ const where = `the rules for list "${pathName}"`;
193
+ const { ruleSet, diagnostics } = compile(rules);
194
+ printDiagnostics(context, diagnostics, where);
195
+ if (!ruleSet) {
196
+ throw new CliError(`${where} don't compile`);
197
+ }
198
+ if (list.rulesTests) {
199
+ runRuleTests(context, ruleSet, list.rulesTests, `the rule tests for list "${pathName}"`);
200
+ }
201
+ }
202
+ }
203
+ /**
204
+ * Show a rule change as a line diff, since rule text is usually many lines
205
+ */
206
+ export function printRuleDiff(context, from, to) {
207
+ const { green, red, dim } = context.colours;
208
+ // A file's trailing newline isn't a line of rules
209
+ const lines = (text) => text ? text.replace(/\n$/, '').split('\n') : [];
210
+ const before = lines(from);
211
+ const after = lines(to);
212
+ if (before.length === 0 && after.length === 0) {
213
+ context.log(` ${dim('(no rules)')}`);
214
+ return;
215
+ }
216
+ // The common start and end are usually most of the text
217
+ let start = 0;
218
+ while (start < before.length &&
219
+ start < after.length &&
220
+ before[start] === after[start]) {
221
+ start++;
222
+ }
223
+ let end = 0;
224
+ while (end < before.length - start &&
225
+ end < after.length - start &&
226
+ before[before.length - 1 - end] === after[after.length - 1 - end]) {
227
+ end++;
228
+ }
229
+ if (start > 0) {
230
+ context.log(dim(` … ${start} unchanged ${start === 1 ? 'line' : 'lines'}`));
231
+ }
232
+ for (const line of before.slice(start, before.length - end)) {
233
+ context.log(red(` - ${line}`));
234
+ }
235
+ for (const line of after.slice(start, after.length - end)) {
236
+ context.log(green(` + ${line}`));
237
+ }
238
+ if (end > 0) {
239
+ context.log(dim(` … ${end} unchanged ${end === 1 ? 'line' : 'lines'}`));
240
+ }
241
+ }
package/build/sdk.js CHANGED
@@ -2,4 +2,4 @@ import sdk from '@basementuniverse/jsonpad-sdk';
2
2
  // The SDK is a UMD build, which Node loads as CommonJS, so an ES module only
3
3
  // sees its exports object as the default import
4
4
  export const JSONPad = sdk.default;
5
- export const { IndexBuildError, JSONPadError } = sdk;
5
+ export const { FlowError, IndexBuildError, JSONPadError, WriteRuleError } = sdk;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@basementuniverse/jsonpad-cli",
3
- "version": "1.4.0",
3
+ "version": "1.6.0",
4
4
  "description": "Command line tool for JSONPad",
5
5
  "author": "Gordon Larrigan <gordonlarrigan@gmail.com> (https://gordonlarrigan.com)",
6
6
  "license": "MIT",
@@ -38,8 +38,10 @@
38
38
  "reference": "node scripts/generate-reference.ts"
39
39
  },
40
40
  "dependencies": {
41
+ "@basementuniverse/jsonpad-flows": "1.0.0",
41
42
  "@basementuniverse/jsonpad-realtime-sdk": "^1.6.0",
42
- "@basementuniverse/jsonpad-sdk": "^2.1.0",
43
+ "@basementuniverse/jsonpad-rules": "^1.2.0",
44
+ "@basementuniverse/jsonpad-sdk": "^2.3.0",
43
45
  "commander": "^15.0.0"
44
46
  },
45
47
  "devDependencies": {