@enspirit/opspicy 0.0.0-stage → 0.3.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 (78) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +325 -2
  3. package/bin/entry.js +48 -0
  4. package/bin/help.js +115 -0
  5. package/bin/opspicy +27 -0
  6. package/dist/addresses.js +27 -0
  7. package/dist/behind.js +64 -0
  8. package/dist/citizens.js +71 -0
  9. package/dist/configuration.d.ts +56 -0
  10. package/dist/configuration.js +66 -0
  11. package/dist/explorer/afresh.js +43 -0
  12. package/dist/explorer/api.js +101 -0
  13. package/dist/explorer/asking.js +59 -0
  14. package/dist/explorer/build.js +11 -0
  15. package/dist/explorer/calls.js +42 -0
  16. package/dist/explorer/document.js +117 -0
  17. package/dist/explorer/elo-refs.js +153 -0
  18. package/dist/explorer/elo.js +95 -0
  19. package/dist/explorer/fonts/OFL.txt +93 -0
  20. package/dist/explorer/fonts/dm-sans-latin.woff2 +0 -0
  21. package/dist/explorer/html.js +104 -0
  22. package/dist/explorer/index.js +62 -0
  23. package/dist/explorer/json.js +33 -0
  24. package/dist/explorer/machine.js +34 -0
  25. package/dist/explorer/masking.js +57 -0
  26. package/dist/explorer/operation.js +97 -0
  27. package/dist/explorer/pages.js +159 -0
  28. package/dist/explorer/script/base.js +103 -0
  29. package/dist/explorer/script/call.js +161 -0
  30. package/dist/explorer/script/calling.js +103 -0
  31. package/dist/explorer/script/connection.js +83 -0
  32. package/dist/explorer/script/copying.js +75 -0
  33. package/dist/explorer/script/filter.js +56 -0
  34. package/dist/explorer/script/formaldef.js +37 -0
  35. package/dist/explorer/script/main.js +82 -0
  36. package/dist/explorer/script/markdown.js +143 -0
  37. package/dist/explorer/script/notes.js +184 -0
  38. package/dist/explorer/script/noting.js +38 -0
  39. package/dist/explorer/script/peek.js +62 -0
  40. package/dist/explorer/script/peeking.js +19 -0
  41. package/dist/explorer/script/ranking.js +91 -0
  42. package/dist/explorer/script/review.js +126 -0
  43. package/dist/explorer/script/rows.js +58 -0
  44. package/dist/explorer/script/run.js +168 -0
  45. package/dist/explorer/script/running.js +66 -0
  46. package/dist/explorer/script/search.js +122 -0
  47. package/dist/explorer/script/sending.js +64 -0
  48. package/dist/explorer/script/served.js +51 -0
  49. package/dist/explorer/serve.js +41 -0
  50. package/dist/explorer/server.js +143 -0
  51. package/dist/explorer/site.js +78 -0
  52. package/dist/explorer/style.css +247 -0
  53. package/dist/explorer/telling.js +30 -0
  54. package/dist/explorer/tests.js +78 -0
  55. package/dist/explorer/wiki.js +90 -0
  56. package/dist/files.js +178 -0
  57. package/dist/finding.js +17 -0
  58. package/dist/judging.js +99 -0
  59. package/dist/lines.js +30 -0
  60. package/dist/main.js +128 -0
  61. package/dist/meaning.js +100 -0
  62. package/dist/modelling.js +173 -0
  63. package/dist/naming.js +84 -0
  64. package/dist/notation.js +119 -0
  65. package/dist/planning.js +41 -0
  66. package/dist/reach.js +177 -0
  67. package/dist/reading.js +135 -0
  68. package/dist/report-file.js +42 -0
  69. package/dist/report.js +63 -0
  70. package/dist/running.js +105 -0
  71. package/dist/selecting.js +71 -0
  72. package/dist/starting.js +41 -0
  73. package/dist/suite.js +32 -0
  74. package/dist/upgrade.js +27 -0
  75. package/dist/upgrading.js +76 -0
  76. package/dist/words.js +103 -0
  77. package/dist/world.js +129 -0
  78. package/package.json +57 -4
@@ -0,0 +1,71 @@
1
+ // The forms a citizen is written in. Pure.
2
+ //
3
+ // Every citizen has a long form, the same for all: its `name`, its `description`, and its
4
+ // `formaldef` when it has one, then what else its kind says.
5
+ //
6
+ // - name: board(id)
7
+ // description: The board of this number.
8
+ // formaldef: find(boards, b ~> b.id == id)
9
+ //
10
+ // A sentence (a clause, a condition) is its own description, so it has shorter forms, which say
11
+ // the same and nothing more: the sentence alone, or `sentence: formaldef`.
12
+ //
13
+ // - the filter is kept reduced to the attributes we know
14
+ // - it has a name: "!isBlank(input.name | '')"
15
+ import { marked } from './notation.js';
16
+ const LONG = ['name', 'description', 'formaldef'];
17
+ const isRecord = (value) => Boolean(value) && typeof value === 'object' && !Array.isArray(value);
18
+ export const record = (value) => (isRecord(value) ? value : {});
19
+ export const list = (value) => (Array.isArray(value) ? value : []);
20
+ /**
21
+ * A list, as a file writes one under a key. A key that is absent or says nothing is an empty
22
+ * list. Anything else that is no list is told, and not read as an empty one: a dash forgotten
23
+ * would otherwise leave an operation with no clause, and nobody the wiser.
24
+ */
25
+ export function listOf(what, value, problems) {
26
+ if (value !== undefined && value !== null && !Array.isArray(value))
27
+ problems.push(`${what} says a list, got ${(JSON.stringify(value) ?? String(value)).slice(0, 80)}`);
28
+ return list(value);
29
+ }
30
+ export const text = (value) => (typeof value === 'string' ? value.trim() : '');
31
+ const told = (value) => (value === undefined ? 'nothing' : JSON.stringify(value));
32
+ /** A kind of citizen, as a sentence names one: `an agent`, `a predicate`. */
33
+ export const a = (what) => `${/^[aeiou]/i.test(what) ? 'an' : 'a'} ${what}`;
34
+ /** A citizen, from its long form. What it lacks is told, and it is read as far as it goes: a citizen with no description is still one others may name. */
35
+ export function citizenOf(what, item, problems, { formaldef = false, also = [] } = {}) {
36
+ const raw = record(item);
37
+ const name = text(raw.name);
38
+ const known = [...LONG.filter((key) => key !== 'formaldef' || formaldef), ...also];
39
+ if (!name)
40
+ problems.push(`${a(what)} says its "name", its "description"${formaldef ? ' and its "formaldef"' : ''}, got ${told(item)}`);
41
+ const called = `${what} "${name}"`;
42
+ for (const key of Object.keys(raw))
43
+ if (name && !known.includes(key))
44
+ problems.push(`${called}: "${key}" is not something ${a(what)} says (${known.join(', ')})`);
45
+ if (name && !text(raw.description))
46
+ problems.push(`${called} says its "description"`);
47
+ if (name && formaldef && !text(raw.formaldef))
48
+ problems.push(`${called} says its "formaldef"`);
49
+ return { name, description: text(raw.description), formaldef: text(raw.formaldef) || undefined, raw };
50
+ }
51
+ function longSentence(what, raw, also) {
52
+ const known = [...LONG, ...also];
53
+ const unknown = Object.keys(raw).filter((key) => !known.includes(key));
54
+ if (unknown.length)
55
+ throw new Error(`${what}: "${unknown[0]}" is not something it says in its long form (${known.join(', ')})`);
56
+ if (!text(raw.description) || (raw.formaldef !== undefined && !text(raw.formaldef)))
57
+ throw new Error(`${what}: its long form says its "description", a sentence, and its "formaldef" in Elo if any, got ${told(raw)}`);
58
+ return { name: text(raw.name) || undefined, description: text(raw.description), formaldef: text(raw.formaldef) || undefined, long: true, raw };
59
+ }
60
+ /** A sentence: alone, with its formaldef as `sentence: formaldef`, or in its long form. Throws what is wrong with it. */
61
+ export function sentenceOf(what, item, also = []) {
62
+ if (typeof item === 'string' && item.trim())
63
+ return { ...marked(item), long: false, raw: {} };
64
+ const raw = record(item);
65
+ if ('description' in raw)
66
+ return longSentence(what, raw, also);
67
+ const [[sentence, formaldef] = [], ...others] = Object.entries(raw);
68
+ if (others.length || !sentence || typeof formaldef !== 'string' || !formaldef.trim())
69
+ throw new Error(`${what}: expected a sentence, one sentence with its formaldef in Elo, or its long form (${LONG.join(', ')}), got ${told(item)}`);
70
+ return { ...marked(sentence), formaldef: formaldef.trim(), long: false, raw: {} };
71
+ }
@@ -0,0 +1,56 @@
1
+ export interface Answer {
2
+ status: number;
3
+ /** JSON as data, a text as it is, nothing otherwise. */
4
+ body: unknown;
5
+ }
6
+ /** Somebody's browser: it keeps the cookies it is given, and comes from one origin. */
7
+ export interface Browser {
8
+ call(method: string, path: string, body?: unknown): Promise<Answer>;
9
+ }
10
+ /** Asks the database, to read: one statement, its rows. */
11
+ export type Ask = (sql: string) => Promise<Record<string, unknown>[]>;
12
+ export interface Configuration {
13
+ /** The front door: an origin, with no path. */
14
+ api: string;
15
+ /**
16
+ * Whether the database of this stack may be emptied. Setting a Background empties it, so a
17
+ * suite runs only where this is true: never where the database is somebody's.
18
+ */
19
+ mayEmptyTheDatabase: boolean;
20
+ /** Sets the Background a case starts from: puts the database in a seed. */
21
+ background(seed: string): Promise<void>;
22
+ /** Signs an actor of the world in, on their browser; throws when they cannot. */
23
+ signIn(browser: Browser, actor: Record<string, unknown>, name: string): Promise<void>;
24
+ /** What a refusal is: the type of what is answered, and the code it carries. */
25
+ refusal: {
26
+ type: string;
27
+ code(body: unknown): unknown;
28
+ };
29
+ /** The database, for the relations of the state and to know the server is at rest. */
30
+ database?: string;
31
+ /** The header a proxy tells the origin of a call by. Given one, each case calls from an origin of its own. */
32
+ originHeader?: string;
33
+ /** Whether the server has nothing under way, for work that outlives the answer that started it. */
34
+ atRest?(ask: Ask): Promise<boolean>;
35
+ }
36
+ /** What a configuration is handed, so that it imports nothing. */
37
+ export interface Kit {
38
+ /** A variable of the environment. No default: a suite does not guess where the stack is. */
39
+ env(name: string): string;
40
+ /** Sets a Background by asking dbagent, over HTTP, to install the seed of that name. */
41
+ dbagent(url: string): Configuration['background'];
42
+ /** At rest when no key is held in the database: for a server that holds one while it works (PostgreSQL's advisory locks). */
43
+ noKeyHeld: NonNullable<Configuration['atRest']>;
44
+ }
45
+ export type Configure = (kit: Kit) => Configuration;
46
+ /** What keeps a suite from being configured: said in a line, and nothing is run. */
47
+ export declare class NotConfigured extends Error {
48
+ }
49
+ export declare const KIT: Kit;
50
+ /**
51
+ * The configuration of the suite under a directory. Whatever keeps it from being one is a
52
+ * `NotConfigured`, in a sentence: a file that is not there, that Node cannot read, that exports
53
+ * nothing, or that throws when asked. The file is named as a URL: a path is not one where it
54
+ * holds a `#` or a `%`.
55
+ */
56
+ export declare function configurationOf(root: string): Promise<Configuration>;
@@ -0,0 +1,66 @@
1
+ var __rewriteRelativeImportExtension = (this && this.__rewriteRelativeImportExtension) || function (path, preserveJsx) {
2
+ if (typeof path === "string" && /^\.\.?\//.test(path)) {
3
+ return path.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i, function (m, tsx, d, ext, cm) {
4
+ return tsx ? preserveJsx ? ".jsx" : ".js" : d && (!ext || !cm) ? m : (d + ext + "." + cm.toLowerCase() + "js");
5
+ });
6
+ }
7
+ return path;
8
+ };
9
+ // How a suite meets the system it specifies: its `config.ts`, beside its specification. Everything
10
+ // that is the system's own and not the notation's is said there: where its front door is, how
11
+ // somebody signs in, how a Background is set, what a refusal looks like.
12
+ //
13
+ // // config.ts
14
+ // import type { Configure } from '/opt/opspicy/src/configuration.ts'; // where the image has it
15
+ // import type { Configure } from '@enspirit/opspicy'; // or: the package, installed
16
+ // const configure: Configure = ({ env, dbagent }) => ({ api: env('API'), … });
17
+ // export default configure;
18
+ //
19
+ // The file imports the type only: what it needs at run time it is handed, as a kit. And this
20
+ // file imports nothing but what Node has, so a suite's `config.ts` is type-checked with Node's
21
+ // types and no other. It is what the package exports, and the one file it declares the types of
22
+ // (tsconfig.types.json).
23
+ import { existsSync } from 'node:fs';
24
+ import { join } from 'node:path';
25
+ import { pathToFileURL } from 'node:url';
26
+ /** What keeps a suite from being configured: said in a line, and nothing is run. */
27
+ export class NotConfigured extends Error {
28
+ }
29
+ const env = (name) => {
30
+ const value = process.env[name];
31
+ if (!value)
32
+ throw new NotConfigured(`${name} is not set: the suite does not guess where the stack is`);
33
+ return value;
34
+ };
35
+ const dbagent = (url) => async (seed) => {
36
+ const response = await fetch(`${url}/seeds/install?id=${encodeURIComponent(seed)}`, { method: 'POST' });
37
+ if (!response.ok)
38
+ throw new Error(`the seed "${seed}" was not installed: ${response.status} ${(await response.text()).slice(0, 300)}`);
39
+ };
40
+ const KEYS_HELD = `SELECT count(*)::int AS n FROM pg_locks WHERE locktype = 'advisory' AND database = (SELECT oid FROM pg_database WHERE datname = current_database())`;
41
+ const noKeyHeld = async (ask) => (await ask(KEYS_HELD))[0]?.n === 0;
42
+ export const KIT = { env, dbagent, noKeyHeld };
43
+ const lineOf = (error) => String(error instanceof Error ? error.message : error).split('\n')[0] ?? '';
44
+ /**
45
+ * The configuration of the suite under a directory. Whatever keeps it from being one is a
46
+ * `NotConfigured`, in a sentence: a file that is not there, that Node cannot read, that exports
47
+ * nothing, or that throws when asked. The file is named as a URL: a path is not one where it
48
+ * holds a `#` or a `%`.
49
+ */
50
+ export async function configurationOf(root) {
51
+ const file = join(root, 'config.ts');
52
+ if (!existsSync(file))
53
+ throw new NotConfigured(`${file} is not there: a suite says how it meets its system in its config.ts`);
54
+ const read = (error) => {
55
+ throw error instanceof NotConfigured ? error : new NotConfigured(`${file} cannot be read: ${lineOf(error)}`);
56
+ };
57
+ const { default: configure } = (await import(__rewriteRelativeImportExtension(pathToFileURL(file).href)).catch(read));
58
+ if (typeof configure !== 'function')
59
+ throw new NotConfigured(`${file} exports no configuration`);
60
+ try {
61
+ return configure(KIT);
62
+ }
63
+ catch (error) {
64
+ throw error instanceof NotConfigured ? error : new NotConfigured(`${file} gives no configuration: ${lineOf(error)}`);
65
+ }
66
+ }
@@ -0,0 +1,43 @@
1
+ // What was made of a suite on disk, kept for as long as the disk says the same.
2
+ //
3
+ // A served explorer reads its suite at each asking, so that what was just edited is what is shown
4
+ // and what is run. Reading a suite takes seconds once it has some size, and between most askings
5
+ // nothing changed. So what is asked of the disk each time is what its files are (their names,
6
+ // their times, their sizes), which takes a moment, and a suite is read again only when that is no
7
+ // longer what it was: an edited file still shows at the next request.
8
+ import { readdirSync, statSync } from 'node:fs';
9
+ import { join, resolve } from 'node:path';
10
+ import { SPECIFICATION, readSuite } from '../files.js';
11
+ /** What one path is now, without reading it: a file by its time and its size, a directory by everything under it, what is not there by its absence. */
12
+ function stamps(path) {
13
+ const told = statSync(path, { throwIfNoEntry: false });
14
+ if (!told)
15
+ return [`${path} ·`];
16
+ if (!told.isDirectory())
17
+ return [`${path} ${told.mtimeMs} ${told.size}`];
18
+ return [`${path}/`, ...readdirSync(path).sort().flatMap((name) => stamps(join(path, name)))];
19
+ }
20
+ /** What is at these paths now, as one text that differs once a file under them is edited, added or removed. A path that is not said is not looked at. */
21
+ export const stampOf = (...paths) => paths.flatMap((path) => (path === undefined ? [] : stamps(path))).join('\n');
22
+ /**
23
+ * What `make` gives, made again only when the stamp is no longer what it was when it was made.
24
+ * The stamp is taken first: what changes while it is being made is made again at the next asking.
25
+ * What could not be made is not kept, and is tried again.
26
+ */
27
+ export function kept(stamp, make) {
28
+ let last = null;
29
+ return () => {
30
+ const now = stamp();
31
+ if (last?.stamp !== now)
32
+ last = { stamp: now, made: make() };
33
+ return last.made;
34
+ };
35
+ }
36
+ const suites = new Map();
37
+ /** The suite of a directory, read again only when its specification is no longer what it was on disk. */
38
+ export function suiteAt(root) {
39
+ const at = resolve(root);
40
+ const read = suites.get(at) ?? kept(() => stampOf(join(at, SPECIFICATION)), () => readSuite(root));
41
+ suites.set(at, read);
42
+ return read();
43
+ }
@@ -0,0 +1,101 @@
1
+ // What the served explorer does when its page asks: says what it serves, runs one case, calls an
2
+ // operation as an actor of the world, and writes the review beside the specification. It is the
3
+ // runner, asked from a page: a case is run as main.ts runs it, through the front door, against
4
+ // the system the suite's configuration names.
5
+ //
6
+ // What the suite says is asked of the disk at each asking, so what was just edited is what is run:
7
+ // it is read again whenever its files are no longer what they were (afresh.ts). Nothing told
8
+ // here holds what an actor signs in with: a sign-in is neither logged nor answered, and what a
9
+ // run tells is told without what the world holds (telling.ts, masking.ts).
10
+ import { lstatSync, renameSync, rmSync, writeFileSync } from 'node:fs';
11
+ import { join } from 'node:path';
12
+ import { namesOf } from '../files.js';
13
+ import { meaningOf } from '../meaning.js';
14
+ import { addressed, queryOf } from '../notation.js';
15
+ import { runCase } from '../running.js';
16
+ import { NotStarted, reachOf } from '../starting.js';
17
+ import { browserOf } from '../world.js';
18
+ import { suiteAt } from './afresh.js';
19
+ import { callAsked, isTold, refused, runAsked } from './asking.js';
20
+ import { secretsOf } from './masking.js';
21
+ import { ranOf } from './telling.js';
22
+ const PROTECTED = 'This stack does not say that its database may be emptied';
23
+ /** Whether the database is somebody's: it is, unless the configuration says in so many words that it may be emptied. What only looks like yes (`'yes'`, `1`) is not. */
24
+ export const isProtected = (config) => config.mayEmptyTheDatabase !== true;
25
+ /** Whether the complete run can be made: it reads the relations, which takes a database. */
26
+ const completes = (suite, config) => suite.model.relations.length === 0 || Boolean(config.database);
27
+ /** What is served: the specification, the system it is run against, whether its database is somebody's, and the runs that can be made. */
28
+ export function health(bench) {
29
+ const suite = suiteAt(bench.root);
30
+ const modes = completes(suite, bench.config) ? ['fast', 'complete'] : ['fast'];
31
+ const mode = bench.lastMode() ?? 'fast';
32
+ return { status: 200, body: { name: bench.name, ...(bench.version ? { version: bench.version } : {}), target: bench.config.api, protected: isProtected(bench.config), modes, mode: modes.includes(mode) ? mode : 'fast' } };
33
+ }
34
+ let runs = 0;
35
+ /** Runs one case, by its anchor: its Background is set, which replaces what the database held, and the case is judged. */
36
+ export async function run(bench, asked) {
37
+ const suite = suiteAt(bench.root);
38
+ const found = runAsked(suite, asked, bench.lastMode());
39
+ if (isTold(found))
40
+ return found;
41
+ if (isProtected(bench.config))
42
+ return refused(403, `${PROTECTED}, and running a case sets its Background, which empties it.`);
43
+ if (found.mode === 'complete' && !completes(suite, bench.config))
44
+ return refused(400, 'The complete run reads the relations, and the configuration names no database to read them from.');
45
+ // What a run reads is reached as the runner reaches it, and a database that is not there is its sentence, not a failure of this server.
46
+ const reach = await reachOf(suite, bench.config, found.mode === 'fast').catch((error) => (error instanceof NotStarted ? refused(503, error.message) : Promise.reject(error)));
47
+ if (isTold(reach))
48
+ return reach;
49
+ try {
50
+ const outcome = await runCase(reach, suite.model, meaningOf(suite.types, namesOf(suite.model)), found.operation, found.kase, { run: process.pid, n: runs++, listening: true });
51
+ return { status: 200, body: ranOf(found.operation, outcome, found.mode, secretsOf(suite.model)) };
52
+ }
53
+ finally {
54
+ await reach.database?.end();
55
+ }
56
+ }
57
+ /** Calls an operation once, as an actor of the world, with an input: the route is filled from it, and the rest is sent. */
58
+ export async function call(bench, asked) {
59
+ const found = callAsked(suiteAt(bench.root), asked);
60
+ if (isTold(found))
61
+ return found;
62
+ const { operation, actor, held } = found;
63
+ if (isProtected(bench.config) && operation.entry.method !== 'GET')
64
+ return refused(403, `${PROTECTED}: only what is entered by GET is called on it.`);
65
+ let sent;
66
+ try {
67
+ sent = addressed(operation.entry.path, found.input);
68
+ }
69
+ catch (error) {
70
+ return refused(400, error instanceof Error ? error.message : String(error));
71
+ }
72
+ const started = Date.now();
73
+ const theirs = await browserOf(bench.config, `10.254.${(runs >> 8) % 256}.${runs++ % 256}`, actor, held).catch(() => null);
74
+ if (!theirs)
75
+ return refused(400, `"${actor}" could not be signed in.`);
76
+ const answer = operation.entry.method === 'GET' ? await theirs.call('GET', `${sent.path}${queryOf(sent.rest)}`) : await theirs.call(operation.entry.method, sent.path, sent.rest ?? {});
77
+ return { status: 200, body: { status: answer.status, seconds: (Date.now() - started) / 1000, body: answer.body, actor } };
78
+ }
79
+ /** The file the review is written to: beside the specification, which holds nothing it does not read. */
80
+ export const REVIEW = 'review.md';
81
+ /**
82
+ * Writes the review a reader made, as the page gives it. It is written beside and then put in
83
+ * its place, and not at all where the place is taken by what is no file of its own: nothing is
84
+ * written through a link, to a file that is elsewhere.
85
+ */
86
+ export function review(bench, markdown) {
87
+ if (!markdown.startsWith('# Specification review'))
88
+ return refused(400, 'What is written is the review file, as the Review page makes it.');
89
+ const path = join(bench.root, REVIEW);
90
+ if (lstatSync(path, { throwIfNoEntry: false })?.isFile() === false)
91
+ return refused(409, `${path} is not a file of its own (a link, a directory): the review is not written through it.`);
92
+ const beside = `${path}.${process.pid}.part`;
93
+ try {
94
+ writeFileSync(beside, markdown, { flag: 'wx' });
95
+ renameSync(beside, path);
96
+ }
97
+ finally {
98
+ rmSync(beside, { force: true });
99
+ }
100
+ return { status: 200, body: { path } };
101
+ }
@@ -0,0 +1,59 @@
1
+ // What a page asks of the served explorer, found in the suite: the case a run is asked of, the
2
+ // operation a call is asked of and who makes it, or why the suite has no answer to that. Pure: a
3
+ // suite is given, nothing is read and nothing is called.
4
+ import { casesOf, mustOnly } from '../planning.js';
5
+ import { askedOf, problemsAsked } from '../selecting.js';
6
+ import { credentialsOf, isA } from '../suite.js';
7
+ import { idOf } from './wiki.js';
8
+ export const refused = (status, why) => ({ status, body: { refused: why } });
9
+ /** Whether what was asked was refused, and not found. */
10
+ export const isTold = (found) => 'status' in found && 'body' in found;
11
+ const record = (value) => (value && typeof value === 'object' && !Array.isArray(value) ? value : {});
12
+ /**
13
+ * The case an anchor names, with its operation as the mode of a run checks it. A suite where two
14
+ * cases are at one address cannot be read (addresses.ts), and so is not run: the first is enough
15
+ * to say whose file it is.
16
+ */
17
+ function caseAt(suite, ref, mode) {
18
+ const checked = suite.operations.map((written) => (mode === 'fast' ? mustOnly(written) : written));
19
+ return checked.flatMap((operation) => casesOf(operation, suite.model).filter((kase) => idOf('case', kase.name) === ref).map((kase) => ({ operation, kase })))[0];
20
+ }
21
+ /**
22
+ * What keeps the cases of an operation from being run: what stops the runner when it is asked
23
+ * for that operation alone (`O=<its file>`). A suite that cannot be read is not run, and the
24
+ * file of another operation does not stop this one (selecting.ts).
25
+ */
26
+ export const stopping = (suite, operation) => problemsAsked(suite.problems, suite.operations, askedOf({ O: operation.file }).asked);
27
+ /** The run a page asks for, `{ case, mode }`, or why it is not made: the mode of the last run when none is asked, the fast one when there was none. */
28
+ export function runAsked(suite, asked, lastMode) {
29
+ const { case: ref, mode: wanted } = record(asked);
30
+ const mode = wanted ?? lastMode ?? 'fast';
31
+ if (typeof ref !== 'string' || (mode !== 'fast' && mode !== 'complete'))
32
+ return refused(400, 'A run is asked as { case, mode }: the anchor of a case, and "fast" or "complete".');
33
+ const found = caseAt(suite, ref, mode);
34
+ if (!found)
35
+ return refused(404, `The specification has no case at "${ref}".`);
36
+ const unread = stopping(suite, found.operation);
37
+ if (unread.length)
38
+ return refused(400, `The specification cannot be read, and nothing of it is run until it is: ${unread[0]}${unread.length > 1 ? ` (and ${unread.length - 1} more)` : ''}`);
39
+ return { ...found, mode };
40
+ }
41
+ /** The call a page asks for, `{ operation, input, actor }`, or why it is not made: called by the first of the world who is the agent of the operation, when the page names nobody. */
42
+ export function callAsked(suite, asked) {
43
+ const { operation: ref, input = null, actor: wanted } = record(asked);
44
+ const [operation, ...others] = suite.operations.filter((one) => idOf('op', one.name) === ref);
45
+ if (!operation)
46
+ return refused(404, `The specification has no operation at "${String(ref)}".`);
47
+ // Two operations may still be at one anchor: of one name, or of names that differ by what an
48
+ // anchor cannot hold. A call asks nothing of whether the suite reads, so it is refused here.
49
+ if (others.length)
50
+ return refused(409, `The specification has ${others.length + 1} operations at "${String(ref)}", in ${[operation, ...others].map((one) => one.file).join(' and ')}: name one otherwise.`);
51
+ const actor = typeof wanted === 'string' ? wanted : suite.model.actors.find((one) => isA(suite.model.agents, one.is, operation.agent))?.name;
52
+ if (actor === undefined)
53
+ return refused(400, `Nobody of the world is ${operation.agent}: say who calls.`);
54
+ const held = credentialsOf(suite.model);
55
+ // Theirs by name, and not what every record has: `constructor` is nobody of the world.
56
+ if (!Object.hasOwn(held, actor))
57
+ return refused(400, `Nobody is called "${actor}" in the world.`);
58
+ return { operation, actor, held: held[actor] ?? null, input };
59
+ }
@@ -0,0 +1,11 @@
1
+ // node src/explorer/build.ts <suite> [--report=<file>] [--out=<file>] [--name=<name>] [--version=<version>] [--runner=<command>]
2
+ //
3
+ // Writes the wiki of a suite, and of the report of its last run, as one standalone HTML file:
4
+ // open it in a browser, offline, and send it as it is.
5
+ import { writeFileSync } from 'node:fs';
6
+ import { documentAt, optionsOf } from './site.js';
7
+ const options = optionsOf(process.argv.slice(2));
8
+ const { suite, out = 'explorer.html' } = options;
9
+ const document = documentAt(options);
10
+ writeFileSync(out, document);
11
+ console.log(`The explorer of ${suite} is written to ${out}: ${(Buffer.byteLength(document) / 1e6).toFixed(2)} MB`);
@@ -0,0 +1,42 @@
1
+ // What the page needs to call an operation by hand, as data: how it is entered, which parts of
2
+ // its input fill the route, and the type of its input with every name it uses, in the form
3
+ // elo-form takes. Pure: the wiki is given.
4
+ //
5
+ // An entry is `{method, path, route, input, actors}`, by the anchor of the operation's page. `route`
6
+ // names the parts of the path the input gives: they are left out of what is sent, and the rest is
7
+ // the query of a GET, the body otherwise. `input` is `{type, source}`: the name of the type, and the
8
+ // declarations it needs, each before what uses it; none for an operation that is given nothing.
9
+ // `actors` names who of the world may perform it: those who are its agent, or one who is that too.
10
+ import { placeholders } from '../notation.js';
11
+ import { isA } from '../suite.js';
12
+ import { idOf } from './wiki.js';
13
+ /** The types a type names, itself among them, in the order the suite declares them: one is declared before it is used. */
14
+ function needed(name, types) {
15
+ const byName = new Map(types.map((one) => [one.name, one]));
16
+ const found = new Set();
17
+ const visit = (one) => {
18
+ const type = byName.get(one);
19
+ if (!type || found.has(one))
20
+ return;
21
+ found.add(one);
22
+ for (const word of type.formaldef.replace(/#[^\n]*/g, '').match(/[A-Z]\w*/g) ?? [])
23
+ visit(word);
24
+ };
25
+ visit(name);
26
+ return types.filter((one) => found.has(one.name));
27
+ }
28
+ function callOf(operation, types, { agents, actors }) {
29
+ const declared = operation.input ? needed(operation.input, types) : [];
30
+ const input = operation.input && declared.length ? { type: operation.input, source: declared.map((one) => `${one.name} = ${one.formaldef}`).join('\n') } : null;
31
+ const performing = actors.filter((actor) => isA(agents, actor.is, operation.agent)).map((actor) => actor.name);
32
+ return { method: operation.entry.method, path: operation.entry.path, route: placeholders(operation.entry.path), input, actors: performing };
33
+ }
34
+ /** How each operation is called, by the anchor of its page. The types are those of the suite as they are read, not as the areas are listed: what declares a type comes before what uses it. */
35
+ export function callsOf(wiki) {
36
+ return Object.fromEntries(wiki.operations.map((operation) => [idOf('op', operation.name), callOf(operation, wiki.types, wiki)]));
37
+ }
38
+ /** What a case sends, for the row of the case to say. */
39
+ export function requestOf(operation, kase) {
40
+ const sent = typeof kase.input === 'string' ? { elo: kase.input } : kase.input === null || kase.input === undefined ? {} : { input: kase.input };
41
+ return { actor: kase.given.actor, background: kase.given.seed, method: operation.entry.method, path: operation.entry.path, ...sent };
42
+ }
@@ -0,0 +1,117 @@
1
+ // The one HTML document of the explorer: its navigation, its bar of tools, its pages, and what
2
+ // its search finds. Pure: its style and its script are given, as texts. Offline and online, it is
3
+ // this same text: a file to open, or a page a server sends.
4
+ import { callsOf } from './calls.js';
5
+ import { LEGEND, esc, link, plural } from './html.js';
6
+ import { indexOf } from './index.js';
7
+ import { areaTitle } from './operation.js';
8
+ import { specPagesOf } from './pages.js';
9
+ import { testPagesOf } from './tests.js';
10
+ import { idOf } from './wiki.js';
11
+ /** What the page knows of itself: what it is the explorer of, and the last run, when there is one. */
12
+ function metaOf(wiki, about) {
13
+ const run = wiki.run && { when: wiki.run.when, mode: wiki.run.fast ? 'fast' : 'complete', narrowed: wiki.run.narrowed, ran: wiki.run.ran, passed: wiki.run.ran - wiki.run.failed, failed: wiki.run.failed, notRun: wiki.run.notRun };
14
+ return { name: about.name, ...(about.version ? { version: about.version } : {}), generated: about.generated, runner: about.runner, run };
15
+ }
16
+ const THEMES = '<select id="thm" aria-label="Theme"><option value="">System theme</option><option value="light">Light</option><option value="dark">Dark</option></select>';
17
+ /** The name the explorer goes by: that of the specified system, as its specification says it, or the name it was given. */
18
+ const nameOf = (wiki, about) => wiki.system.name ?? about.name;
19
+ const navOf = (wiki, about) => `<nav class="side" aria-label="Explorer">
20
+ <a class="brand" href="#home"><i aria-hidden="true"></i>${esc(nameOf(wiki, about))}</a>
21
+ <div class="searchbox"><input class="find" id="q" type="search" placeholder="Search everything" aria-label="Search every page, citizen and formaldef" aria-keyshortcuts="/" autocomplete="off"><kbd>/</kbd></div>
22
+ <p class="chap">The system</p>
23
+ <div class="nav">
24
+ ${link('#home', 'Overview')}
25
+ ${link('#agents', 'Agents')}
26
+ ${link('#state', 'State')}
27
+ </div>
28
+ <p class="chap">The specification</p>
29
+ <div class="nav">${wiki.areas
30
+ .map((area) => `<a href="#${esc(idOf('area', area.name))}">${esc(areaTitle(area.name))}<span>${area.operations.length}</span></a>`)
31
+ .join('')}</div>
32
+ <p class="chap">Index</p>
33
+ <div class="nav">
34
+ ${link('#definitions', 'Formal definitions')}
35
+ ${link('#types', 'Types')}
36
+ </div>
37
+ <p class="chap">Testing</p>
38
+ <div class="nav">
39
+ ${link('#world', 'World')}
40
+ ${link('#backgrounds', 'Backgrounds')}
41
+ <a href="#tests">Last run${wiki.run ? `<span>${wiki.run.failed ? '✗' : '✓'} ${esc(plural(wiki.run.ran, 'case'))}</span>` : ''}</a>
42
+ </div>
43
+ <p class="chap work">Your work</p>
44
+ <div class="nav work"><a href="#review">Review <span class="count" id="note-count"></span></a><button type="button" data-conf>Connection <span id="conf-state"></span></button></div>
45
+ <footer class="foot">${LEGEND}
46
+ ${THEMES}
47
+ <p class="by">A specification read by <a href="https://github.com/enspirit/opspicy">opspicy</a></p></footer>
48
+ </nav>`;
49
+ /** The bar that stays on top of every page, and under it where the search shows what it finds, in place of the page. */
50
+ const TOOLS = `<div class="tools" id="tools">
51
+ <input type="search" class="filter" id="filter" placeholder="Filter this page" aria-label="Filter this page" aria-keyshortcuts="f" autocomplete="off" hidden>
52
+ <span class="m s" id="fcount" aria-live="polite"></span>
53
+ <span class="sp"></span>
54
+ <button type="button" class="tb" id="formal" aria-pressed="false" aria-keyshortcuts="d" title="Show or hide every formaldef, on every page"><b>ƒ</b> Formaldefs <kbd>d</kbd></button>
55
+ <button type="button" class="tb" id="pnote" aria-keyshortcuts="n" title="Write a note on this page">✎ Note <kbd>n</kbd></button>
56
+ </div>
57
+ <section id="results" aria-live="polite"></section>`;
58
+ /** The page of the reader's notes, and of the review file made of them: the script fills it from what the browser keeps. */
59
+ const REVIEW = `<section class="page" id="review"><h1>Review</h1>
60
+ <p class="lead">Your notes, in the order of the specification. They stay in this browser until you delete them. The file below is written for a person and for an AI agent alike: each note names its item by its anchor, by the file and the line that declare it, and by its own words.</p>
61
+ <p class="empty" id="review-empty">No note yet. On any page, the ✎ at the end of a row writes a note on that row, and “Note” in the bar writes one on the page. Press <kbd>n</kbd> for the same.</p>
62
+ <div id="review-list"></div>
63
+ <div id="review-export" hidden>
64
+ <h2>The review file</h2>
65
+ <div class="review-bar"><button type="button" class="tb primary" id="copy-md">Copy as Markdown</button><button type="button" class="tb" id="save-md">Save review.md</button><span class="sp"></span><button type="button" class="tb" id="clear-notes">Delete every note</button></div>
66
+ <textarea class="export" id="review-md" readonly spellcheck="false" aria-label="The review, as Markdown"></textarea>
67
+ </div>
68
+ </section>`;
69
+ /** Before anything is painted: the page says its script runs, and takes the theme that was chosen. */
70
+ const EARLY = "document.documentElement.classList.add('js');try{const t=JSON.parse(localStorage.getItem('opspicy.theme'));if(t)document.documentElement.dataset.theme=t}catch{}";
71
+ /** Where calls made from the page go, and what they carry: asked from the sidebar. What it holds is the reader's, and never written here. */
72
+ const CONNECTION = `<dialog id="conf" aria-labelledby="conf-t"><form method="dialog">
73
+ <h2 id="conf-t">Connection</h2>
74
+ <p class="m s">Where a call made from this page goes, and what it carries. The target is kept in this browser; the token and the headers only until this tab closes.</p>
75
+ <label>Target of the calls<input type="url" id="c-target" placeholder="http://localhost:3000" autocomplete="off"></label>
76
+ <label>Token, sent as <span class="mono">Authorization: Bearer</span><input type="password" id="c-token" autocomplete="off"></label>
77
+ <label>Other headers, a line each, as <span class="mono">Name: value</span><textarea id="c-headers" rows="3" spellcheck="false" autocomplete="off"></textarea></label>
78
+ <p class="err s" id="c-problem" role="alert"></p>
79
+ <div class="bar"><button type="button" class="tb" value="cancel">Cancel</button><button class="tb primary" value="save">Save</button></div>
80
+ </form></dialog>`;
81
+ /** A JSON text that cannot close the script it sits in, nor break the line it is read from. */
82
+ const safeJson = (value) => JSON.stringify(value).replace(/</g, '\\u003c').replace(/\u2028/g, '\\u2028').replace(/\u2029/g, '\\u2029');
83
+ /** The whole explorer, as one HTML document, from the wiki of a suite and what it is dressed with. */
84
+ export function documentOf(wiki, { css, script, form }, about) {
85
+ const pages = [...specPagesOf(wiki), ...testPagesOf(wiki)];
86
+ const section = (page) => `<section class="page" id="${esc(page.id)}" data-kind="${esc(page.kind)}"${page.nav ? ` data-nav="${esc(page.nav)}"` : ''}${page.source ? ` data-source="${esc(page.source)}"` : ''}>${page.body}</section>`;
87
+ const sections = pages.map(section).join('\n');
88
+ return `<!doctype html>
89
+ <html lang="en">
90
+ <head>
91
+ <meta charset="utf-8">
92
+ <meta name="viewport" content="width=device-width, initial-scale=1">
93
+ <meta name="generator" content="opspicy explorer">
94
+ <title>${esc(nameOf(wiki, about))} · specification</title>
95
+ <style>
96
+ ${css}
97
+ </style>${form ? `\n<style id="elo-form-css">\n${form.css}\n</style>` : ''}
98
+ <script>${EARLY}</script>
99
+ </head>
100
+ <body>
101
+ <div class="layout">
102
+ ${navOf(wiki, about)}
103
+ <main id="main">
104
+ ${TOOLS}
105
+ ${sections}
106
+ ${REVIEW}
107
+ </main>
108
+ </div>
109
+ ${CONNECTION}
110
+ <script type="application/json" id="meta">${safeJson(metaOf(wiki, about))}</script>
111
+ <script type="application/json" id="index">${safeJson(indexOf(wiki, pages))}</script>
112
+ <script type="application/json" id="calls">${safeJson(callsOf(wiki))}</script>${form ? `\n<script type="text/plain" id="elo-form">${form.script.replace(/<\/(script)/gi, '<\\/$1')}</script>` : ''}
113
+ <script>${script}</script>
114
+ </body>
115
+ </html>
116
+ `;
117
+ }