@enspirit/opspicy 0.0.0-stage → 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 (74) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +281 -2
  3. package/bin/entry.js +27 -0
  4. package/bin/opspicy +19 -0
  5. package/dist/addresses.js +27 -0
  6. package/dist/behind.js +64 -0
  7. package/dist/citizens.js +71 -0
  8. package/dist/configuration.d.ts +56 -0
  9. package/dist/configuration.js +66 -0
  10. package/dist/explorer/afresh.js +43 -0
  11. package/dist/explorer/api.js +101 -0
  12. package/dist/explorer/asking.js +59 -0
  13. package/dist/explorer/build.js +11 -0
  14. package/dist/explorer/calls.js +42 -0
  15. package/dist/explorer/document.js +109 -0
  16. package/dist/explorer/elo-refs.js +153 -0
  17. package/dist/explorer/elo.js +95 -0
  18. package/dist/explorer/fonts/OFL.txt +93 -0
  19. package/dist/explorer/fonts/dm-sans-latin.woff2 +0 -0
  20. package/dist/explorer/html.js +59 -0
  21. package/dist/explorer/index.js +61 -0
  22. package/dist/explorer/json.js +33 -0
  23. package/dist/explorer/machine.js +34 -0
  24. package/dist/explorer/masking.js +57 -0
  25. package/dist/explorer/operation.js +94 -0
  26. package/dist/explorer/pages.js +132 -0
  27. package/dist/explorer/script/base.js +103 -0
  28. package/dist/explorer/script/call.js +161 -0
  29. package/dist/explorer/script/calling.js +103 -0
  30. package/dist/explorer/script/connection.js +83 -0
  31. package/dist/explorer/script/copying.js +75 -0
  32. package/dist/explorer/script/filter.js +56 -0
  33. package/dist/explorer/script/formaldef.js +37 -0
  34. package/dist/explorer/script/main.js +82 -0
  35. package/dist/explorer/script/markdown.js +143 -0
  36. package/dist/explorer/script/notes.js +184 -0
  37. package/dist/explorer/script/noting.js +38 -0
  38. package/dist/explorer/script/peek.js +62 -0
  39. package/dist/explorer/script/peeking.js +19 -0
  40. package/dist/explorer/script/ranking.js +91 -0
  41. package/dist/explorer/script/review.js +126 -0
  42. package/dist/explorer/script/rows.js +58 -0
  43. package/dist/explorer/script/run.js +168 -0
  44. package/dist/explorer/script/running.js +66 -0
  45. package/dist/explorer/script/search.js +122 -0
  46. package/dist/explorer/script/sending.js +64 -0
  47. package/dist/explorer/script/served.js +51 -0
  48. package/dist/explorer/serve.js +41 -0
  49. package/dist/explorer/server.js +143 -0
  50. package/dist/explorer/site.js +77 -0
  51. package/dist/explorer/style.css +241 -0
  52. package/dist/explorer/telling.js +30 -0
  53. package/dist/explorer/tests.js +78 -0
  54. package/dist/explorer/wiki.js +76 -0
  55. package/dist/files.js +176 -0
  56. package/dist/finding.js +17 -0
  57. package/dist/judging.js +75 -0
  58. package/dist/lines.js +30 -0
  59. package/dist/main.js +128 -0
  60. package/dist/meaning.js +100 -0
  61. package/dist/modelling.js +115 -0
  62. package/dist/naming.js +84 -0
  63. package/dist/notation.js +119 -0
  64. package/dist/planning.js +32 -0
  65. package/dist/reading.js +120 -0
  66. package/dist/report-file.js +42 -0
  67. package/dist/report.js +62 -0
  68. package/dist/running.js +102 -0
  69. package/dist/selecting.js +71 -0
  70. package/dist/starting.js +41 -0
  71. package/dist/suite.js +29 -0
  72. package/dist/words.js +103 -0
  73. package/dist/world.js +128 -0
  74. package/package.json +57 -4
@@ -0,0 +1,75 @@
1
+ import { POST, isPre, sameSentence } from './suite.js';
2
+ const excerpt = (value) => (JSON.stringify(value) ?? 'nothing').slice(0, 300);
3
+ /** Whether a clause holds, or why nobody can tell. */
4
+ function holds(meaning, clause, context) {
5
+ const named = `${clause.kind} "${clause.description}"`;
6
+ try {
7
+ const value = meaning.value(clause.formaldef ?? 'true', context, isPre(clause) ? 'pre' : 'post');
8
+ return typeof value === 'boolean' ? value : { says: `${named} is neither true nor false`, saw: `it gives ${excerpt(value)}` };
9
+ }
10
+ catch (error) {
11
+ return { says: `${named} could not be decided`, saw: error instanceof Error ? error.message : String(error) };
12
+ }
13
+ }
14
+ /** What to say of a clause, given whether it should hold. */
15
+ function about(meaning, clause, context, expected, otherwise) {
16
+ if (!clause.formaldef)
17
+ return [];
18
+ const held = holds(meaning, clause, context);
19
+ if (typeof held !== 'boolean')
20
+ return [held];
21
+ return held === expected ? [] : [{ says: `${clause.kind} "${clause.description}" ${otherwise}` }];
22
+ }
23
+ function preconditions(operation, kase, observed, meaning) {
24
+ const context = { input: observed.input, before: observed.before, world: observed.world };
25
+ const violated = (clause) => kase.kind === 'counterexample' && sameSentence(clause.description, kase.for ?? '');
26
+ return operation.clauses.filter(isPre).flatMap((clause) => {
27
+ if (violated(clause))
28
+ return about(meaning, clause, context, false, 'holds before the call: the case does not violate what it is for');
29
+ if (kase.generated)
30
+ return [];
31
+ return about(meaning, clause, context, true, kase.kind === 'example' ? 'does not hold before the call' : 'does not hold before the call either: the case violates more than what it is for');
32
+ });
33
+ }
34
+ function answer(operation, kase, observed, meaning, refusal) {
35
+ if (observed.status !== kase.then.status)
36
+ return [{ says: `answered ${observed.status} where ${kase.then.status} is said`, saw: excerpt(observed.body) }];
37
+ const type = kase.kind === 'example' ? operation.output : refusal.type;
38
+ const misfit = type ? meaning.misfit(type, observed.body) : null;
39
+ const code = refusal.code(observed.body);
40
+ const typed = misfit ? [{ says: `what is answered is not a ${type}`, saw: `${misfit} — ${excerpt(observed.body)}` }] : [];
41
+ return [...typed, ...(kase.then.code && code !== kase.then.code ? [{ says: `it is not refused as ${kase.then.code}`, saw: `refused as ${excerpt(code)}` }] : [])];
42
+ }
43
+ /** The names of what is not as it was: of the state, of the relations, of what others see. */
44
+ export function changed(before, after, path = '') {
45
+ if (JSON.stringify(before) === JSON.stringify(after))
46
+ return [];
47
+ const nested = (value) => Boolean(value) && typeof value === 'object' && !Array.isArray(value);
48
+ const deeper = path === '' || path === 'db' || path.startsWith('seenBy');
49
+ if (!deeper || !nested(before) || !nested(after))
50
+ return [path];
51
+ return [...new Set([...Object.keys(before), ...Object.keys(after)])].flatMap((name) => changed(before[name], after[name], path ? `${path}.${name}` : name));
52
+ }
53
+ function unchanged(observed, why) {
54
+ const names = changed(observed.before, observed.after);
55
+ return names.length ? [{ says: `${why}, yet this is not as it was: ${names.join(', ')}` }] : [];
56
+ }
57
+ function postconditions(operation, kase, observed, meaning) {
58
+ const context = { ...observed, output: observed.body };
59
+ const clauses = [...operation.clauses.filter((clause) => POST.includes(clause.kind)), ...kase.and];
60
+ return [...clauses.flatMap((clause) => about(meaning, clause, context, true, 'does not hold after the call')), ...(operation.observes || operation.entry.method === 'GET' ? unchanged(observed, operation.observes ? 'an observation changes nothing' : 'a route that reads changes nothing') : [])];
61
+ }
62
+ /** What a case shows that the specification does not say: nothing, when it passes. */
63
+ export function judge(operation, kase, observed, meaning, refusal) {
64
+ const before = preconditions(operation, kase, observed, meaning);
65
+ const answered = answer(operation, kase, observed, meaning, refusal);
66
+ if (answered.length && observed.status !== kase.then.status)
67
+ return [...before, ...answered];
68
+ const after = kase.kind === 'example' ? postconditions(operation, kase, observed, meaning) : unchanged(observed, 'the call was refused');
69
+ return [...before, ...answered, ...after];
70
+ }
71
+ /** What keeps the input of an example from being of the type its operation says. */
72
+ export function inputMisfit(operation, kase, input, meaning) {
73
+ const misfit = kase.kind === 'example' && operation.input ? meaning.misfit(operation.input, input) : null;
74
+ return misfit ? [{ says: `the input is not a ${operation.input}`, saw: misfit }] : [];
75
+ }
package/dist/lines.js ADDED
@@ -0,0 +1,30 @@
1
+ // Where a citizen is written. Pure: from the text of a YAML file, the line of what is at a path
2
+ // in it. What does not parse, or leads nowhere, has none.
3
+ import { LineCounter, isNode, parseDocument } from 'yaml';
4
+ const NOWHERE = () => undefined;
5
+ /** The lookup of the lines of a YAML text. */
6
+ export function linesOf(text) {
7
+ const counter = new LineCounter();
8
+ try {
9
+ const document = parseDocument(text, { lineCounter: counter });
10
+ if (document.errors.length)
11
+ return NOWHERE;
12
+ return (...path) => {
13
+ try {
14
+ const node = path.length ? document.getIn(path, true) : document.contents;
15
+ return isNode(node) && node.range ? counter.linePos(node.range[0]).line : undefined;
16
+ }
17
+ catch {
18
+ return undefined;
19
+ }
20
+ };
21
+ }
22
+ catch {
23
+ return NOWHERE;
24
+ }
25
+ }
26
+ /** Where a file says things, given what is known of its lines. */
27
+ export const placeOf = (file, lines) => (...path) => {
28
+ const line = lines?.(...path);
29
+ return line === undefined ? file : `${file}:${line}`;
30
+ };
package/dist/main.js ADDED
@@ -0,0 +1,128 @@
1
+ // node src/main.ts <suite> runs the suite of that directory against the stack it is in
2
+ // node src/main.ts <suite> --check reads it and says what cannot be read: needs no stack
3
+ //
4
+ // What of it is run, and how much is told, is asked through the environment (selecting.ts):
5
+ // O, METHOD, CASE, ROBUST, FAILFAST, FAST (or --fast), LOG_LEVEL.
6
+ // --report=<file>: also writes what the run decided, as JSON, for the explorer (report-file.ts).
7
+ import { writeFileSync } from 'node:fs';
8
+ import { resolve } from 'node:path';
9
+ import { NotConfigured, configurationOf } from './configuration.js';
10
+ import { namesOf, readSuite } from './files.js';
11
+ import { meaningOf } from './meaning.js';
12
+ import { casesOf, gapsOf, mustOnly } from './planning.js';
13
+ import { reportOf } from './report-file.js';
14
+ import { failed, operationLines, summaryLines } from './report.js';
15
+ import { runCase } from './running.js';
16
+ import { askedOf, casesAsked, commandOf, narrowed, operationAsked, problemsAsked, toldWithNoCase } from './selecting.js';
17
+ import { NotStarted, answering, reachOf, why, writable } from './starting.js';
18
+ const { command, problems: misgiven } = commandOf(process.argv.slice(2));
19
+ const root = resolve(command.suite);
20
+ function stop(lines, code) {
21
+ for (const line of lines)
22
+ console.error(line);
23
+ process.exit(code);
24
+ }
25
+ const { asked, problems: misasked } = askedOf(process.env, process.argv);
26
+ if (misasked.length || misgiven.length)
27
+ stop(['What is asked of the run is not understood:', ...[...misgiven, ...misasked].map((problem) => ` ${problem}`)], 2);
28
+ /** Setting a Background empties the database: only a stack that says its database may be emptied is run against. Said as `true` and nothing else: a text, "no" among them, is not a yes. */
29
+ function mayEmptyOrStop(config) {
30
+ if (config.mayEmptyTheDatabase === true)
31
+ return;
32
+ stop(['This stack does not say that its database may be emptied, and every case sets a Background, which empties it.', 'Run the suite on a stack whose database is the suites\' own.'], 2);
33
+ }
34
+ /** What is run, decided before anything is called. */
35
+ const planOf = (suite) => suite.operations.filter((operation) => operationAsked(operation, asked)).map((written) => {
36
+ const operation = asked.fast ? mustOnly(written) : written;
37
+ const all = casesOf(operation, suite.model);
38
+ return { operation, all, cases: casesAsked(all, asked) };
39
+ });
40
+ /** Runs what was asked of the suite, telling each operation as it is done; stops at the first case that fails when asked to. */
41
+ async function run(suite, where, plan) {
42
+ const meaning = meaningOf(suite.types, namesOf(suite.model));
43
+ const listening = asked.log === 'debug' || asked.log === 'trace';
44
+ const stops = (outcomes) => asked.failfast && outcomes.some((outcome) => outcome.findings.length > 0);
45
+ const ran = [];
46
+ let n = 0;
47
+ for (const { operation, all, cases } of plan) {
48
+ const outcomes = [];
49
+ for (const kase of cases) {
50
+ outcomes.push(await runCase(where, suite.model, meaning, operation, kase, { run: process.pid, n: n++, listening }));
51
+ if (stops(outcomes))
52
+ break;
53
+ }
54
+ if (!outcomes.length && !toldWithNoCase(all, asked))
55
+ continue;
56
+ ran.push({ operation, outcomes, gaps: gapsOf(operation, all) });
57
+ for (const line of operationLines(ran[ran.length - 1], asked.log))
58
+ console.log(line);
59
+ if (stops(outcomes))
60
+ return { ran, stopped: true };
61
+ }
62
+ return { ran, stopped: false };
63
+ }
64
+ /** The suite, as it reads: what cannot be read of what is run is told, and nothing is run. Asked to check only, that is all. */
65
+ function read() {
66
+ const suite = readSuite(root);
67
+ const problems = problemsAsked(suite.problems, suite.operations, asked);
68
+ if (problems.length)
69
+ stop(['The specifications cannot be read:', ...problems.map((problem) => ` ${problem}`)], 2);
70
+ if (!command.check)
71
+ return suite;
72
+ console.log(`${suite.operations.length} specifications read, ${suite.model.conditions.length} conditions, ${suite.model.definitions.length} predicates and functions`);
73
+ process.exit(0);
74
+ }
75
+ /**
76
+ * What a run needs before its first case, in the order that calls nothing for nothing: a
77
+ * configuration, a database that may be emptied, a case to run, somewhere to write the report,
78
+ * the database to read, a system that answers.
79
+ */
80
+ async function start(suite) {
81
+ const config = await configurationOf(root);
82
+ mayEmptyOrStop(config);
83
+ const plan = planOf(suite);
84
+ if (!plan.some((one) => one.cases.length))
85
+ stop(['Nothing of the suite is what was asked for: no case was run.'], 2);
86
+ if (command.report)
87
+ writable(command.report);
88
+ const where = await reachOf(suite, config, asked.fast);
89
+ await answering(config);
90
+ return { where, plan };
91
+ }
92
+ /** The report, in its file. It could be written there when the run started: what keeps it from being so now is told, and the run did not do what was asked. */
93
+ function written(file, report) {
94
+ try {
95
+ writeFileSync(file, JSON.stringify(report, null, 2) + '\n');
96
+ }
97
+ catch (error) {
98
+ stop([`The report could not be written to ${file}: ${why(error)}`], 2);
99
+ }
100
+ }
101
+ /** The run in its last lines, its report when one was asked, and its answer: 0 when every case passes, 1 when one does not. */
102
+ function tell(ran, stopped) {
103
+ for (const line of summaryLines(ran))
104
+ console.log(line);
105
+ if (asked.fast)
106
+ console.log('The fast run: nothing was read behind the front door.');
107
+ if (narrowed(asked).length)
108
+ console.log(`Asked: ${narrowed(asked).join(' ')}. The rest of the suite was not run.`);
109
+ if (stopped)
110
+ console.log('Stopped at the first case that fails.');
111
+ if (command.report)
112
+ written(command.report, reportOf(ran, { when: new Date().toISOString(), narrowed: narrowed(asked), fast: asked.fast, stopped }));
113
+ process.exit(failed(ran).length ? 1 : 0);
114
+ }
115
+ try {
116
+ const suite = read();
117
+ const { where, plan } = await start(suite);
118
+ const { ran, stopped } = await run(suite, where, plan);
119
+ await where.database?.end();
120
+ tell(ran, stopped);
121
+ }
122
+ catch (error) {
123
+ // What keeps a run from starting is a sentence. Anything else was not foreseen: it is told whole, and is no failure of a case either.
124
+ if (error instanceof NotConfigured || error instanceof NotStarted)
125
+ stop([error.message], 2);
126
+ console.error(error);
127
+ process.exit(2);
128
+ }
@@ -0,0 +1,100 @@
1
+ // What a formaldef means: an expression in Elo (elo-lang.org), compiled once and applied to what
2
+ // was observed. It reads the names of its moment (naming.ts), over `_`: what was observed, whole.
3
+ // It can do nothing else: Elo has no input or output of its own.
4
+ import { compileToJavaScript, parse, typecheck, typecheckWithType } from '@enspirit/elo';
5
+ import { DateTime, Duration, Interval } from 'luxon';
6
+ import { NOTHING_NAMED, misnamed, relationsType, sourceOf, typedSourceOf } from './naming.js';
7
+ const firstLine = (error) => String(error instanceof Error ? error.message : error).split('\n')[0] ?? '';
8
+ function compiled(source) {
9
+ const javascript = compileToJavaScript(parse(source));
10
+ return new Function('DateTime', 'Duration', 'Interval', `return (${javascript})`)(DateTime, Duration, Interval);
11
+ }
12
+ /** The meaning of a suite: its expressions, under the names it gives, and its types as the areas declare them. */
13
+ export function meaningOf(types, names = NOTHING_NAMED) {
14
+ const known = new Map();
15
+ const expression = (source) => {
16
+ if (!known.has(source))
17
+ known.set(source, compiled(source));
18
+ return known.get(source);
19
+ };
20
+ const said = new Map();
21
+ const at = (source, moment) => {
22
+ const key = `${moment}\n${source}`;
23
+ if (!said.has(key))
24
+ said.set(key, sourceOf(source, moment, names));
25
+ return expression(said.get(key));
26
+ };
27
+ const value = (source, context, moment) => {
28
+ try {
29
+ return at(source, moment)(context);
30
+ }
31
+ catch (error) {
32
+ throw new Error(firstLine(error));
33
+ }
34
+ };
35
+ const prelude = `${types}\n${relationsType(names)}`;
36
+ const unreadable = (source, moment, exchanged) => moment ? misnamed(source, names) ?? unread(() => at(source, moment)) ?? mistyped(`${prelude}\n${typedSourceOf(source, moment, names, exchanged)}`) : unread(() => expression(source));
37
+ const decides = (name) => truthOf(`${prelude}\n${typedSourceOf(name, 'post', names)}`);
38
+ return { value, misfit: (type, given) => misfit(expression, types, type, given), unreadable, decides };
39
+ }
40
+ function misfit(expression, types, type, value) {
41
+ try {
42
+ return readFor(value, expression(`${types}\n_ |> ${type}`)(value));
43
+ }
44
+ catch (error) {
45
+ return firstLine(error);
46
+ }
47
+ }
48
+ const isData = (value) => Array.isArray(value) || (Boolean(value) && Object.getPrototypeOf(value) === Object.prototype);
49
+ /**
50
+ * The member where Elo read a text for what the type says, in a line as Elo says its own; nothing
51
+ * when it did not. Elo gives a value the type it is asked for where it can: right of a date,
52
+ * which JSON says as a text and no other way, and not of `"12"` where an Int is said, which is a
53
+ * text to whoever gets the answer. Where a type says a number or a text, in that order, a text
54
+ * that reads as a number is refused: `String|Int` says the same and takes both.
55
+ */
56
+ function readFor(given, dressed, at = '') {
57
+ if (typeof given === 'string')
58
+ return typeof dressed === 'number' || typeof dressed === 'boolean' ? `${at || '.'}: expected ${typeof dressed === 'number' ? 'a number' : 'true or false'}, got the text ${JSON.stringify(given)}` : null;
59
+ if (!isData(given) || !isData(dressed))
60
+ return null;
61
+ for (const [member, value] of Object.entries(given)) {
62
+ const found = readFor(value, dressed[member], `${at}.${member}`);
63
+ if (found)
64
+ return found;
65
+ }
66
+ return null;
67
+ }
68
+ /** A member that no type of the suite has: read, it would give `null` and say nothing. */
69
+ function mistyped(typed) {
70
+ try {
71
+ const found = typecheck(parse(typed)).find((one) => one.code === 'unknown-field');
72
+ const [, member, has] = found?.message.match(/^'(\w+)' is not a field of .*Declared: (.*?)\.?$/s) ?? [];
73
+ return found ? (member ? `"${member}" is not a member of what it is read of, which has: ${has}` : found.message) : null;
74
+ }
75
+ catch (error) {
76
+ return `its types cannot be checked: ${firstLine(error)}`;
77
+ }
78
+ }
79
+ /** Whether an expression, or what the function it names gives, is true or false; nothing where Elo does not know its type. */
80
+ function truthOf(typed) {
81
+ try {
82
+ const { type } = typecheckWithType(parse(typed));
83
+ const given = type.kind === 'fn' ? type.result : type;
84
+ return !given || given.kind === 'any' ? null : given.kind === 'bool';
85
+ }
86
+ catch {
87
+ return null;
88
+ }
89
+ }
90
+ function unread(read) {
91
+ try {
92
+ read();
93
+ return null;
94
+ }
95
+ catch (error) {
96
+ return firstLine(error);
97
+ }
98
+ }
99
+ /** The names of the types a file of Elo types declares. */
100
+ export const typesDeclared = (types) => [...types.matchAll(/^([A-Z]\w*)\s*=/gm)].map((match) => match[1] ?? '');
@@ -0,0 +1,115 @@
1
+ // What a suite says apart from its operations, as it is written (YAML, already parsed), becomes
2
+ // its model: the areas, the agents, the Backgrounds, the state, the world, and the words of each
3
+ // area. Pure: what cannot be read is told as a problem, and never guessed.
4
+ import { citizenOf, list, record, text } from './citizens.js';
5
+ import { placeOf } from './lines.js';
6
+ import { RESERVED } from './naming.js';
7
+ import { observedOf } from './notation.js';
8
+ import { named } from './suite.js';
9
+ import { conditionsOf, definitionsOf, typesOf } from './words.js';
10
+ const under = (where, problems) => problems.map((problem) => `${where}: ${problem}`);
11
+ /** The citizens of one kind a file lists, each said once. */
12
+ function listed(what, written, problems, place, says = {}) {
13
+ if (written !== undefined && written !== null && !Array.isArray(written))
14
+ problems.push(`expected a list, of each ${what} with its name and its description`);
15
+ const all = list(written).map((item, at) => ({ ...citizenOf(what, item, problems, says), source: place(at) })).filter((one) => one.name);
16
+ const names = all.map((one) => one.name);
17
+ for (const name of new Set(names.filter((one, at) => names.indexOf(one) !== at)))
18
+ problems.push(`${what} "${name}" is said twice`);
19
+ return all;
20
+ }
21
+ const plain = (written, what, problems, place) => listed(what, written, problems, place).map(({ name, description, source }) => ({ name, description, source }));
22
+ /** The agents, from `agents.yml`: one may be another, and none is itself in the end. */
23
+ function agentsOf(written, problems, place) {
24
+ const agents = listed('agent', written, problems, place, { also: ['is'] }).map(({ name, description, source, raw }) => ({ name, description, source, ...(text(raw.is) ? { is: text(raw.is) } : {}) }));
25
+ for (const one of agents) {
26
+ if (one.is && !named(agents, one.is))
27
+ problems.push(`agent "${one.name}" is a "${one.is}", which is not an agent`);
28
+ const chain = [one.name];
29
+ for (let next = one.is; next && named(agents, next); next = named(agents, next)?.is) {
30
+ if (chain.includes(next)) {
31
+ problems.push(`agent "${one.name}" is itself in the end: ${[...chain, next].join(' → ')}`);
32
+ break;
33
+ }
34
+ chain.push(next);
35
+ }
36
+ }
37
+ return agents;
38
+ }
39
+ function stateOf(item, problems) {
40
+ const { name, description, source, formaldef = '' } = item;
41
+ if (RESERVED.includes(name))
42
+ problems.push(`state "${name}": the name is taken by the suite`);
43
+ try {
44
+ return { name, description, source, formaldef, ...observedOf(formaldef) };
45
+ }
46
+ catch (error) {
47
+ if (formaldef)
48
+ problems.push(`state "${name}": ${error instanceof Error ? error.message : error}`);
49
+ return { name, description, source, formaldef, path: '' };
50
+ }
51
+ }
52
+ function relationOf({ name, description, source, raw }, problems) {
53
+ const names = (given) => list(given).map(text).filter(Boolean);
54
+ const relation = { name, description, source, table: text(raw.table), key: names(raw.key), attributes: names(raw.attributes) };
55
+ const identifiers = [relation.table, ...relation.key, ...relation.attributes].every((identifier) => /^[a-z_][a-z0-9_]*$/.test(identifier));
56
+ if (!relation.table || !relation.key.length || !identifiers)
57
+ problems.push(`relation "${name}": a table, its key and its attributes, each by its plain name`);
58
+ return relation;
59
+ }
60
+ /** What is observed, from `state.yml`: the routes that tell the state, and the relations behind them. */
61
+ function observedIn(written, problems, place) {
62
+ const raw = record(written);
63
+ for (const key of Object.keys(raw))
64
+ if (!['state', 'relations'].includes(key))
65
+ problems.push(`"${key}" is not something it says (state, relations)`);
66
+ return {
67
+ state: listed('state', raw.state, problems, (at) => place('state', at), { formaldef: true }).map((item) => stateOf(item, problems)),
68
+ relations: listed('relation', raw.relations, problems, (at) => place('relations', at), { also: ['table', 'key', 'attributes'] }).map((item) => relationOf(item, problems)),
69
+ };
70
+ }
71
+ function actorOf({ name, description, source, raw }, agents, problems) {
72
+ const held = raw.with === undefined || raw.with === null ? null : record(raw.with);
73
+ if (held && (typeof raw.with !== 'object' || Array.isArray(raw.with)))
74
+ problems.push(`actor "${name}": "with" is what they sign in with, or nothing for somebody who is not signed in`);
75
+ if (!text(raw.is))
76
+ problems.push(`actor "${name}" says the agent they are: "is"`);
77
+ else if (!named(agents, text(raw.is)))
78
+ problems.push(`actor "${name}" is a "${text(raw.is)}", which is not an agent of agents.yml`);
79
+ return { name, description, source, is: text(raw.is), with: held };
80
+ }
81
+ /** What the runner knows, from `world.yml`: who may call, its actors, and whatever else it says. */
82
+ function knownIn(written, agents, problems, place) {
83
+ const { actors, ...world } = record(written);
84
+ if ('requester' in world)
85
+ problems.push('"requester" is who calls, which a case says');
86
+ return { actors: listed('actor', actors, problems, (at) => place('actors', at), { also: ['is', 'with'] }).map((item) => actorOf(item, agents, problems)), world };
87
+ }
88
+ /** Every directory of the specification is an area that `areas.yml` describes, and nothing else is one. */
89
+ function unplaced(areas, words) {
90
+ const directories = words.map((said) => said.area);
91
+ return [
92
+ ...directories.filter((directory) => !named(areas, directory)).map((directory) => `${directory}/ is not an area it describes`),
93
+ ...areas.filter((area) => !directories.includes(area.name)).map((area) => `area "${area.name}" has no directory in the specification`),
94
+ ];
95
+ }
96
+ /** The model of a suite, from what it says. */
97
+ export function modelOf(said) {
98
+ const [inAreas, inAgents, inBackgrounds, inState, inWorld, inWords] = [[], [], [], [], [], []];
99
+ const words = said.words ?? [];
100
+ const at = (file) => placeOf(`${file}.yml`, said.lines?.[file]);
101
+ const areas = plain(said.areas, 'area', inAreas, at('areas'));
102
+ inAreas.push(...unplaced(areas, words));
103
+ const agents = agentsOf(said.agents, inAgents, at('agents'));
104
+ const backgrounds = plain(said.backgrounds, 'background', inBackgrounds, at('backgrounds'));
105
+ const observed = observedIn(said.state, inState, at('state'));
106
+ const known = knownIn(said.world, agents, inWorld, at('world'));
107
+ const conditions = conditionsOf(words, inWords);
108
+ const definitions = definitionsOf(words, observed.state.map((one) => one.name), inWords);
109
+ const types = words.flatMap((one) => typesOf(one.types ?? '', one.area, inWords));
110
+ for (const condition of conditions)
111
+ if (condition.violated && !named(known.actors, condition.violated.actor))
112
+ inWords.push(`condition "${condition.description}": nobody is called "${condition.violated.actor}" in the world`);
113
+ const problems = [...under('areas.yml', inAreas), ...under('agents.yml', inAgents), ...under('backgrounds.yml', inBackgrounds), ...under('state.yml', inState), ...under('world.yml', inWorld), ...inWords];
114
+ return { model: { areas, agents, backgrounds, ...known, ...observed, definitions, conditions, types }, problems };
115
+ }
package/dist/naming.js ADDED
@@ -0,0 +1,84 @@
1
+ /** The name the relations have as a type, for the checker. */
2
+ export const RELATIONS = 'TheRelations';
3
+ export const NOTHING_NAMED = { states: [], relations: [], actors: [], definitions: [] };
4
+ /** What neither a state, a predicate nor a function may be called: the suite's own names, and those of the `let`. */
5
+ export const RESERVED = ['input', 'output', 'world', 'old', 'seenBy', 'db', 'nothingChanged', 'the_state', 'the_view', 'the_moment', 'the_now'];
6
+ /** An expression without what its texts hold: a name in a text names nothing. */
7
+ export const bare = (source) => source.replace(/'(?:[^'\\]|\\.)*'/g, "''");
8
+ const wordsOf = (source) => new Set(bare(source).match(/[A-Za-z_]\w*/g) ?? []);
9
+ /** The predicates and the functions an expression names, and those these name in turn, each after what it uses. */
10
+ export function definitionsUsed(source, definitions) {
11
+ const ordered = [];
12
+ const visit = (text, path) => {
13
+ const words = wordsOf(text);
14
+ for (const one of definitions) {
15
+ if (!words.has(one.name) || ordered.includes(one))
16
+ continue;
17
+ if (path.includes(one.name))
18
+ throw new Error(`${one.kind} "${one.name}" is said in terms of itself: ${[...path, one.name].join(' → ')}`);
19
+ visit(one.formaldef, [...path, one.name]);
20
+ ordered.push(one);
21
+ }
22
+ };
23
+ visit(source, []);
24
+ return ordered;
25
+ }
26
+ /** Those through whose eyes an expression looks: `seenBy.admin.boards`. */
27
+ export const witnessesNamed = (source) => [...new Set([...bare(source).matchAll(/\bseenBy\.(\w+)/g)].map((match) => match[1] ?? ''))];
28
+ // The closing parenthesis is on a line of its own: a formaldef may end with a comment.
29
+ const bound = (one) => (one.parameters.length ? `fn(${one.parameters.join(', ')} ~> ${one.formaldef}\n)` : `(${one.formaldef}\n)`);
30
+ /** A moment as somebody sees it: the state, and the predicates and functions said of it. */
31
+ function view(names, used) {
32
+ const members = [...names.states, 'db', ...used.map((one) => one.name)];
33
+ const state = [...names.states, 'db'].map((name) => `${name} = the_state.${name}`).join(', ');
34
+ return [`fn(the_state ~> let ${state}`, ...used.map((one) => `, ${one.name} = ${bound(one)}`), `in { ${members.map((name) => `${name}: ${name}`).join(', ')} })`].join('\n');
35
+ }
36
+ /** The expression as Elo reads it: under the names of its moment. */
37
+ export function sourceOf(expression, moment, names) {
38
+ const used = definitionsUsed(expression, names.definitions);
39
+ const seen = witnessesNamed(expression).map((actor) => `${actor}: the_view(the_state.seenBy.${actor})`).join(', ');
40
+ const at = moment === 'post' ? 'old = the_moment(_.before), the_now = the_moment(_.after), input = _.input, output = _.output, nothingChanged = _.after == _.before' : `the_now = the_moment(_.before)${moment === 'pre' ? ', input = _.input' : ''}`;
41
+ const read = [...names.states, 'db', 'seenBy', ...used.map((one) => one.name)].map((name) => `${name} = the_now.${name}`).join(', ');
42
+ return `let world = _.world, the_view = ${view(names, used)}, the_moment = fn(the_state ~> merge(the_view(the_state), { seenBy: { ${seen} } })), ${at}, ${read} in\n${expression}`;
43
+ }
44
+ /** An expression changed outside what its texts hold. */
45
+ const rewritten = (source, change) => source.split(/('(?:[^'\\]|\\.)*')/).map((part, at) => (at % 2 ? part : change(part))).join('');
46
+ /** Without `old.` and `seenBy.<actor>.`: the same names, which have the same types. */
47
+ const here = (source) => rewritten(source, (code) => code.replace(/(?<![\w.])old\./g, '').replace(/(?<![\w.])seenBy\.\w+\./g, ''));
48
+ /** The relations as a type: each a list of rows, of the columns the suite reads. */
49
+ export const relationsType = (names) => `${RELATIONS} = { ${Object.entries(names.columns ?? {}).map(([name, columns]) => `${name}: [{ ${columns.map((column) => `${column}: .`).join(', ')} }]`).join(', ')} }`;
50
+ /**
51
+ * The expression as Elo's checker reads it, and as nothing runs it: each name of the moment
52
+ * with its type, where the suite says one. Flat: `old.boards` and `seenBy.admin.boards` are read
53
+ * as `boards`, which has the same type, so that a member misspelt is told through whatever eyes
54
+ * and at whatever moment.
55
+ */
56
+ export function typedSourceOf(expression, moment, names, exchanged = {}) {
57
+ const of = (value, type) => (type ? `${value} |> ${type}` : value);
58
+ const given = moment === 'given' ? [] : [`input = ${of('_.input', exchanged.input)}`];
59
+ const answered = moment === 'post' ? [`output = ${of('_.output', exchanged.output)}`, 'nothingChanged = _.after == _.before'] : [];
60
+ const states = names.states.map((name) => `${name} = ${of(`_.after.${name}`, names.types?.[name])}`);
61
+ const used = definitionsUsed(expression, names.definitions).map((one) => `${one.name} = ${here(bound(one))}`);
62
+ return `let ${['world = _.world', ...given, ...answered, ...states, `db = ${of('_.after.db', names.columns ? RELATIONS : undefined)}`, ...used].join(',\n')} in\n${here(expression)}`;
63
+ }
64
+ /**
65
+ * A name that names nothing, where Elo would give `null` and say nothing: a member of `old`,
66
+ * of somebody's view, of the database.
67
+ */
68
+ export function misnamed(expression, names) {
69
+ const text = bare(expression);
70
+ const told = [...names.states, ...names.definitions.map((one) => one.name)];
71
+ for (const [, name = ''] of text.matchAll(/(?<![\w.])old\.(\w+)/g))
72
+ if (![...told, 'db', 'seenBy'].includes(name))
73
+ return `"old.${name}" is neither a state, a predicate nor a function`;
74
+ for (const [, actor = '', name] of text.matchAll(/(?<![\w.])(?:old\.)?seenBy\.(\w+)(?:\.(\w+))?/g)) {
75
+ if (!names.actors.includes(actor))
76
+ return `"seenBy.${actor}": nobody is called "${actor}"`;
77
+ if (name && !told.includes(name))
78
+ return `"seenBy.${actor}.${name}" is neither a state, a predicate nor a function`;
79
+ }
80
+ for (const [, name = ''] of text.matchAll(/(?<![\w.])(?:old\.)?db\.(\w+)/g))
81
+ if (!names.relations.includes(name))
82
+ return `"db.${name}" is not a relation of the state`;
83
+ return null;
84
+ }
@@ -0,0 +1,119 @@
1
+ // The small notations of a specification file, each read from a text: an entry, a Background,
2
+ // an answer, a way of violating a condition, the mark of a sentence, what a predicate or a
3
+ // function is given, the route of a state. Pure: a text that cannot be read throws what is wrong
4
+ // with it. The forms a citizen is written in are in citizens.ts.
5
+ import { Unrunnable } from './finding.js';
6
+ import { MARKS } from './suite.js';
7
+ const METHODS = ['GET', 'POST', 'PUT', 'DELETE'];
8
+ /** `POST /api/boards/:id` */
9
+ export function entryOf(text) {
10
+ const [, method, path] = String(text ?? '').match(/^\s*([A-Z]+)\s+(\/\S*)\s*$/) ?? [];
11
+ if (!method || !path || !METHODS.includes(method))
12
+ throw new Error(`entry: expected a method and a path, as in "POST /api/boards", got ${told(text)}`);
13
+ return { method: method, path };
14
+ }
15
+ /** `test/base, as member` */
16
+ export function givenOf(text) {
17
+ const [, seed, actor] = String(text ?? '').match(/^\s*([\w/-]+)\s*,\s*as\s+(\w+)\s*$/) ?? [];
18
+ if (!seed || !actor)
19
+ throw new Error(`given: expected a seed and who calls, as in "test/base, as member", got ${told(text)}`);
20
+ return { seed, actor };
21
+ }
22
+ /** `201`, or `400 boards.nameRequired` */
23
+ export function thenOf(text) {
24
+ const [, status, code] = String(text ?? '').match(/^\s*(\d{3})(?:\s+([\w.-]+))?\s*$/) ?? [];
25
+ if (!status)
26
+ throw new Error(`then: expected a status, and the code of a refusal, as in "400 boards.nameRequired", got ${told(text)}`);
27
+ return code ? { status: Number(status), code } : { status: Number(status) };
28
+ }
29
+ /** Whether an answer is a refusal, as a specification says one: a status of 400 or more, and the code it is refused with. */
30
+ export const refuses = (then) => then.status >= 400 && Boolean(then.code);
31
+ /** What a counterexample, or a condition that is violated, says instead of a refusal. */
32
+ export const NO_REFUSAL = 'what is answered is a refusal: a status of 400 or more, and its code, as in "400 boards.nameRequired"';
33
+ /** `as visitor -> 401 auth.signedOut` */
34
+ export function violatedOf(text) {
35
+ const [, actor, then] = String(text ?? '').match(/^\s*as\s+(\w+)\s*->\s*(.+)$/) ?? [];
36
+ if (!actor || !then)
37
+ throw new Error(`violated: expected who calls and what is answered, as in "as visitor -> 401 auth.signedOut", got ${told(text)}`);
38
+ return { actor, then: thenOf(then) };
39
+ }
40
+ /**
41
+ * A sentence may say whether it is checked: `(x) the requester is signed in` is one a formaldef
42
+ * decides, `( ) the origin is not locked out` one that is told and that nothing decides, and
43
+ * `(+) only the hash of the token is kept` one a formaldef decides in the complete run only.
44
+ */
45
+ export function marked(sentence) {
46
+ const [, mark, said] = sentence.match(/^\s*\((x|\+| )\)\s+(.*)$/s) ?? [];
47
+ if (mark !== undefined && said)
48
+ return { description: said.trim(), mark: MARKS[mark] };
49
+ if (MARKLIKE.test(sentence))
50
+ throw new Error(`"${sentence.trim()}": a sentence is marked (x), (+) or ( ), then a space`);
51
+ return { description: sentence.trim() };
52
+ }
53
+ /**
54
+ * What looks like a mark and is none: `(X)`, `[x]`, `()`, or a mark with no space after it. Read
55
+ * as the start of the sentence, it would make another sentence of it, one no condition decides,
56
+ * and what was to be checked would be told.
57
+ */
58
+ const MARKLIKE = /^\s*[([][^)\]]?[)\]]/;
59
+ /** What a predicate or a function is called, and what it is given: `board(id)`, or `signedIn` with nothing. */
60
+ export function signatureOf(text) {
61
+ const [, name, parameters] = String(text ?? '').match(/^\s*([a-z]\w*)\s*(?:\(([\w\s,]*)\))?\s*$/) ?? [];
62
+ if (!name)
63
+ throw new Error(`expected a name, and what it is given, as in "board(id)", got ${told(text)}`);
64
+ return { name, parameters: (parameters ?? '').split(',').map((parameter) => parameter.trim()).filter(Boolean) };
65
+ }
66
+ /** `GET /api/boards -> Boards`: state is observed by reading, and by nothing else; the type of what is told may follow. */
67
+ export function observedOf(text) {
68
+ const [, way, type] = String(text ?? '').match(/^\s*(GET\s+\/\S*?)(?:\s*->\s*([A-Z]\w*))?\s*$/) ?? [];
69
+ const path = way ? entryOf(way).path : '';
70
+ if (!path || placeholders(path).length)
71
+ throw new Error(`observed by a GET route with nothing to fill in, then "-> Type" for the type of what it tells if any, got ${told(text)}`);
72
+ return type ? { path, type } : { path };
73
+ }
74
+ /**
75
+ * The lines where a case starts right under the one before: a file is read by people, and an
76
+ * empty line sets each case apart. A comment above a case is its own, and the first case of a
77
+ * list stands right under `examples:`.
78
+ */
79
+ export function crowded(text) {
80
+ const lines = text.split('\n');
81
+ const starts = lines.flatMap((line, at) => (/^\s*- when:/.test(line) ? [at] : []));
82
+ return starts.filter((at) => {
83
+ let above = at - 1;
84
+ while (above >= 0 && /^\s*#/.test(lines[above] ?? ''))
85
+ above--;
86
+ const before = lines[above] ?? '';
87
+ return before.trim() !== '' && !/^(examples|counterexamples):/.test(before);
88
+ }).map((at) => at + 1);
89
+ }
90
+ /** The parts of a path the input gives: `/api/boards/:id` names `id`. */
91
+ export const placeholders = (path) => [...path.matchAll(/:(\w+)/g)].map((match) => match[1] ?? '');
92
+ /** Data that has names: what a route takes its parts from, and what a query is made of. A list or a text has none. */
93
+ const isRecord = (value) => Boolean(value) && typeof value === 'object' && !Array.isArray(value);
94
+ /** A part that is no name: left as it is when the route is encoded, and followed when it is called, `/api/nothing/../boards` is `/api/boards`. */
95
+ const LEADS_ELSEWHERE = ['.', '..'];
96
+ /**
97
+ * The path with its parts filled from the input, and what is left of the input to send. An input
98
+ * that is no record (a list, a text, a number) fills no part and is left whole. A part is one the
99
+ * input itself gives: `:constructor` is not found in what every record is made from.
100
+ */
101
+ export function addressed(path, input) {
102
+ const given = isRecord(input) ? { ...input } : {};
103
+ const filled = path.replace(/:(\w+)/g, (_all, name) => {
104
+ if (!Object.hasOwn(given, name) || given[name] === undefined || given[name] === null)
105
+ throw new Unrunnable(`the input gives no "${name}" for ${path}`);
106
+ const part = String(given[name]);
107
+ if (LEADS_ELSEWHERE.includes(part))
108
+ throw new Unrunnable(`the input gives "${part}" as "${name}" for ${path}: it would lead to another route`);
109
+ delete given[name];
110
+ return encodeURIComponent(part);
111
+ });
112
+ return { path: filled, rest: isRecord(input) ? given : input ?? null };
113
+ }
114
+ /** What is left of the input as a query, for a route that is only read: its names, and nothing of an input that has none. */
115
+ export function queryOf(rest) {
116
+ const pairs = Object.entries(isRecord(rest) ? rest : {}).filter(([, value]) => value !== undefined && value !== null);
117
+ return pairs.length ? `?${pairs.map(([name, value]) => `${encodeURIComponent(name)}=${encodeURIComponent(String(value))}`).join('&')}` : '';
118
+ }
119
+ const told = (value) => (value === undefined ? 'nothing' : JSON.stringify(value));