@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,153 @@
1
+ // The names of a formaldef that lead to a citizen of the suite, as Elo's parser reads them. Pure.
2
+ //
3
+ // Elo's parser says where each expression stands (`parse(source, { locations: true })`), so a
4
+ // name is resolved from the tree: a free name, a member of `old`, of `seenBy.<actor>` or of `db`,
5
+ // a type a value is given to. What the expression binds (a lambda's parameters, a `let`'s names)
6
+ // is not the citizen of the same name, inside that scope only. A member and a record key are never
7
+ // a citizen. A type of a declaration has no position in the tree: it is found among the words of
8
+ // the code, outside texts and comments, and never where a key or a declared name stands.
9
+ import { parse, splitProgramHeader } from '@enspirit/elo';
10
+ import { RESERVED } from '../naming.js';
11
+ import { idOf } from './wiki.js';
12
+ /** The anchors of the citizens a formaldef may name, from what a suite says. */
13
+ export function refsOf(model) {
14
+ const by = (kind, names) => names.map((name) => [name, idOf(kind, name)]);
15
+ const definitions = model.definitions.map((one) => [one.name, idOf(one.kind, one.name)]);
16
+ return {
17
+ names: new Map([...by('state', model.state.map((one) => one.name)), ...definitions]),
18
+ types: new Map(by('type', model.types.map((one) => one.name))),
19
+ relations: new Map(by('relation', model.relations.map((one) => one.name))),
20
+ actors: new Map(by('actor', model.actors.map((one) => one.name))),
21
+ };
22
+ }
23
+ /** What is never a citizen, whatever the suite calls its own: the names of the moment, and `_`. */
24
+ const UNLINKED = new Set([...RESERVED, '_']);
25
+ const bind = (scope, names) => new Set([...scope, ...names]);
26
+ /** The tree of a text, a bare expression or type declarations, with positions; nothing when Elo cannot read it. */
27
+ function treeOf(text) {
28
+ try {
29
+ const header = splitProgramHeader(text);
30
+ const declarations = header.typeDefs.length > 0 && header.body.replace(/#[^\n]*/g, '').trim() === '';
31
+ return parse(declarations ? `${text}\nnull` : text, { locations: true });
32
+ }
33
+ catch {
34
+ return null;
35
+ }
36
+ }
37
+ /** The names of a text that lead to a citizen, in the order of the text: none when Elo cannot read it. */
38
+ export function refsIn(text, words, refs, about = {}) {
39
+ const tree = treeOf(text);
40
+ if (!tree)
41
+ return [];
42
+ const found = { refs, located: [], types: new Set(), declared: [] };
43
+ walk(tree, new Set(about.given ?? []), found);
44
+ const offset = offsetsOf(text);
45
+ const declared = new Set(found.declared.map(offset));
46
+ const located = found.located.map(({ loc, name, anchor, called }) => ({ at: offset(loc), length: name.length, anchor, name, called })).filter((one) => isWordAt(text, one.name, one.at));
47
+ const typed = words.filter((word) => found.types.has(word.text) && !declared.has(word.at) && !/^\s*:/.test(text.slice(word.at + word.text.length)));
48
+ const all = [...located, ...typed.map((word) => ({ at: word.at, length: word.text.length, anchor: refs.types.get(word.text) ?? '' }))];
49
+ const once = [...new Map(all.filter((one) => one.anchor !== about.self).map(({ at, length, anchor, called }) => [at, { at, length, anchor, ...(called ? { called } : {}) }])).values()];
50
+ return once.sort((a, b) => a.at - b.at);
51
+ }
52
+ /** A position of the tree as an offset in the text: lines and columns count from 1. */
53
+ function offsetsOf(text) {
54
+ const starts = [0];
55
+ for (let at = text.indexOf('\n'); at >= 0; at = text.indexOf('\n', at + 1))
56
+ starts.push(at + 1);
57
+ return (loc) => (starts[loc.line - 1] ?? text.length) + loc.column - 1;
58
+ }
59
+ /** Whether the name the tree places is the whole word written there: a position that says otherwise links nothing. */
60
+ const isWordAt = (text, name, at) => text.startsWith(name, at) && !/\w/.test(text.charAt(at - 1)) && !/\w/.test(text.charAt(at + name.length));
61
+ function note(found, loc, name, anchor, called = false) {
62
+ if (loc && anchor)
63
+ found.located.push({ loc, name, anchor, called });
64
+ }
65
+ function walk(node, scope, found) {
66
+ const { refs } = found;
67
+ if (node.type === 'variable' && !scope.has(node.name) && !UNLINKED.has(node.name))
68
+ note(found, node.loc, node.name, refs.names.get(node.name));
69
+ if (node.type === 'function_call' && !scope.has(node.name))
70
+ note(found, node.loc, node.name, refs.names.get(node.name) ?? refs.types.get(node.name), true);
71
+ if (node.type === 'member_access')
72
+ member(node.object, node.property, node.loc, scope, found);
73
+ if (node.type === 'lambda')
74
+ return walk(node.body, bind(scope, node.params), found);
75
+ if (node.type === 'let')
76
+ return walkLet(node.bindings, node.body, scope, found);
77
+ if (node.type === 'typedef')
78
+ return walkTypes(node.definitions, node.body, scope, found);
79
+ for (const child of childrenOf(node))
80
+ walk(child, scope, found);
81
+ }
82
+ /** A `let`: each name is bound for the ones after it, and in its body. */
83
+ function walkLet(bindings, body, scope, found) {
84
+ let inner = scope;
85
+ for (const one of bindings) {
86
+ walk(one.value, inner, found);
87
+ inner = bind(inner, [one.name]);
88
+ }
89
+ walk(body, inner, found);
90
+ }
91
+ /** Type declarations: their names are bound, where they are declared is no reference, and the types they name are found by name. */
92
+ function walkTypes(definitions, body, scope, found) {
93
+ const inner = bind(scope, definitions.map((one) => one.name));
94
+ for (const one of definitions) {
95
+ if (one.loc)
96
+ found.declared.push(one.loc);
97
+ walkType(one.typeExpr, inner, found);
98
+ }
99
+ walk(body, inner, found);
100
+ }
101
+ function walkType(type, scope, found) {
102
+ if (type.kind === 'type_ref' && !scope.has(type.name) && found.refs.types.has(type.name))
103
+ found.types.add(type.name);
104
+ if (type.kind === 'type_schema')
105
+ for (const one of type.properties)
106
+ walkType(one.typeExpr, scope, found);
107
+ if (type.kind === 'type_schema' && typeof type.extras === 'object')
108
+ walkType(type.extras, scope, found);
109
+ if (type.kind === 'array_type')
110
+ walkType(type.elementType, scope, found);
111
+ if (type.kind === 'union_type')
112
+ for (const one of type.types)
113
+ walkType(one, scope, found);
114
+ if (type.kind !== 'subtype_constraint')
115
+ return;
116
+ walkType(type.baseType, scope, found);
117
+ for (const one of type.constraints)
118
+ walk(one.condition, bind(scope, [type.variable]), found);
119
+ }
120
+ /** A member: a citizen after `old.`, `seenBy.<actor>.` and `db.`, an actor after `seenBy.`, and nothing else. */
121
+ function member(object, property, loc, scope, found) {
122
+ const root = rootOf(object, scope);
123
+ const { names, actors, relations } = found.refs;
124
+ const anchor = root === 'old' || root === 'view' ? names.get(property) : root === 'seenBy' ? actors.get(property) : root === 'db' ? relations.get(property) : undefined;
125
+ note(found, loc, property, anchor);
126
+ }
127
+ function rootOf(node, scope) {
128
+ if (node.type === 'variable')
129
+ return scope.has(node.name) ? null : node.name === 'old' || node.name === 'seenBy' || node.name === 'db' ? node.name : null;
130
+ if (node.type !== 'member_access')
131
+ return null;
132
+ const of = rootOf(node.object, scope);
133
+ if (of === 'seenBy')
134
+ return 'view';
135
+ if (of !== 'old' && of !== 'view')
136
+ return null;
137
+ return node.property === 'db' ? 'db' : node.property === 'seenBy' && of === 'old' ? 'seenBy' : null;
138
+ }
139
+ function childrenOf(node) {
140
+ switch (node.type) {
141
+ case 'binary': return [node.left, node.right];
142
+ case 'unary': return [node.operand];
143
+ case 'if': return [node.condition, node.then, node.else];
144
+ case 'function_call': return node.args;
145
+ case 'apply': return [node.fn, ...node.args];
146
+ case 'member_access': return [node.object];
147
+ case 'object': return node.properties.map((one) => one.value);
148
+ case 'array': return node.elements;
149
+ case 'alternative': return node.alternatives;
150
+ case 'guard': return [...node.constraints.map((one) => one.condition), node.body];
151
+ default: return [];
152
+ }
153
+ }
@@ -0,0 +1,95 @@
1
+ // Elo, highlighted. The grammar is Elo's own, for highlight.js (`@enspirit/highlightjs-elo`): which
2
+ // words are its keywords, its functions and its types is said there, and nowhere here. It is
3
+ // applied when the document is written, so the page carries no library and works offline.
4
+ // Pure: text in, tokens out, and the tokens say the whole text, every character once.
5
+ import grammar from '@enspirit/highlightjs-elo';
6
+ import hljs from 'highlight.js/lib/core';
7
+ import { refsIn } from './elo-refs.js';
8
+ import { esc } from './html.js';
9
+ export { refsOf } from './elo-refs.js';
10
+ hljs.registerLanguage('elo', grammar);
11
+ /** The kind of a token, by the scope the grammar gives it: a date and a duration are numbers there, a data path a variable. */
12
+ const SCOPES = [
13
+ ['comment', 'comment'],
14
+ ['string', 'string'],
15
+ ['number', 'number'],
16
+ ['keyword', 'keyword'],
17
+ ['literal', 'literal'],
18
+ ['built_in', 'builtin'],
19
+ ['type', 'type'],
20
+ ['title', 'fn'],
21
+ ['punctuation', 'op'],
22
+ ['operator', 'op'],
23
+ ['variable', 'member'],
24
+ ];
25
+ const kindOf = (classes) => SCOPES.find(([scope]) => classes.split(' ')[0] === `hljs-${scope}`)?.[1] ?? 'text';
26
+ /** What highlight.js writes instead of the characters that mean something in HTML. */
27
+ const WRITTEN = { '&amp;': '&', '&lt;': '<', '&gt;': '>', '&quot;': '"', '&#x27;': "'" };
28
+ const read = (html) => html.replace(/&(?:amp|lt|gt|quot|#x27);/g, (entity) => WRITTEN[entity] ?? entity);
29
+ /**
30
+ * The tokens of a text: concatenated, they are the text. highlight.js gives spans, one inside
31
+ * another where a text holds an escape: a token is the outermost, whole, and what is in no span
32
+ * is plain text.
33
+ */
34
+ export function tokensOf(text) {
35
+ const tokens = [];
36
+ let depth = 0;
37
+ for (const [, opened, closed, said] of hljs.highlight(text, { language: 'elo' }).value.matchAll(/<span class="([^"]*)">|(<\/span>)|([^<]+)/g)) {
38
+ if (opened !== undefined && depth++ === 0)
39
+ tokens.push({ kind: kindOf(opened), text: '' });
40
+ else if (closed)
41
+ depth--;
42
+ else if (said !== undefined)
43
+ append(tokens, depth, read(said));
44
+ }
45
+ return tokens;
46
+ }
47
+ /** Adds what is said to the token it is of: the span that is open, or the plain text that was being said. */
48
+ function append(tokens, depth, text) {
49
+ const last = tokens[tokens.length - 1];
50
+ if (last && (depth > 0 || last.kind === 'text'))
51
+ last.text += text;
52
+ else
53
+ tokens.push({ kind: 'text', text });
54
+ }
55
+ /** The words of the code, where they start: those of the plain tokens, never of a text, a comment or a member. */
56
+ function wordsOf(tokens) {
57
+ const words = [];
58
+ let at = 0;
59
+ for (const token of tokens) {
60
+ if (token.kind === 'text')
61
+ for (const found of token.text.matchAll(/[A-Za-z_]\w*/g))
62
+ words.push({ at: at + found.index, text: found[0] });
63
+ at += token.text.length;
64
+ }
65
+ return words;
66
+ }
67
+ /** What a token says, with the names in it that lead to a citizen as links. */
68
+ function linked(text, at, refs) {
69
+ let html = '';
70
+ let from = 0;
71
+ for (const ref of refs.filter((one) => one.at >= at && one.at + one.length <= at + text.length)) {
72
+ const start = ref.at - at;
73
+ html += `${esc(text.slice(from, start))}<a class="ref" href="${esc(`#${ref.anchor}`)}">${esc(text.slice(start, start + ref.length))}</a>`;
74
+ from = start + ref.length;
75
+ }
76
+ return html + esc(text.slice(from));
77
+ }
78
+ /**
79
+ * The text, highlighted: each kind of token is a span of its own class, the others are plain.
80
+ * Given what the suite names, a name that Elo's parser reads as a citizen leads to it (elo-refs.ts):
81
+ * about the citizen whose formaldef this is, which is not linked, and the parameters it is given.
82
+ */
83
+ export function eloHtml(text, refs, about = {}) {
84
+ const tokens = tokensOf(text);
85
+ const links = refs ? refsIn(text, wordsOf(tokens), refs, about) : [];
86
+ let at = 0;
87
+ return tokens
88
+ .map((token) => {
89
+ // A function of Elo's own, called, is that function: never the state or the word a suite gave the same name.
90
+ const html = linked(token.text, at, token.kind === 'fn' ? links.filter((one) => !one.called) : links);
91
+ at += token.text.length;
92
+ return token.kind === 'text' ? html : `<span class="e-${token.kind}">${html}</span>`;
93
+ })
94
+ .join('');
95
+ }
@@ -0,0 +1,93 @@
1
+ Copyright 2014 The DM Sans Project Authors (https://github.com/googlefonts/dm-fonts)
2
+
3
+ This Font Software is licensed under the SIL Open Font License, Version 1.1.
4
+ This license is copied below, and is also available with a FAQ at:
5
+ https://scripts.sil.org/OFL
6
+
7
+
8
+ -----------------------------------------------------------
9
+ SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
10
+ -----------------------------------------------------------
11
+
12
+ PREAMBLE
13
+ The goals of the Open Font License (OFL) are to stimulate worldwide
14
+ development of collaborative font projects, to support the font creation
15
+ efforts of academic and linguistic communities, and to provide a free and
16
+ open framework in which fonts may be shared and improved in partnership
17
+ with others.
18
+
19
+ The OFL allows the licensed fonts to be used, studied, modified and
20
+ redistributed freely as long as they are not sold by themselves. The
21
+ fonts, including any derivative works, can be bundled, embedded,
22
+ redistributed and/or sold with any software provided that any reserved
23
+ names are not used by derivative works. The fonts and derivatives,
24
+ however, cannot be released under any other type of license. The
25
+ requirement for fonts to remain under this license does not apply
26
+ to any document created using the fonts or their derivatives.
27
+
28
+ DEFINITIONS
29
+ "Font Software" refers to the set of files released by the Copyright
30
+ Holder(s) under this license and clearly marked as such. This may
31
+ include source files, build scripts and documentation.
32
+
33
+ "Reserved Font Name" refers to any names specified as such after the
34
+ copyright statement(s).
35
+
36
+ "Original Version" refers to the collection of Font Software components as
37
+ distributed by the Copyright Holder(s).
38
+
39
+ "Modified Version" refers to any derivative made by adding to, deleting,
40
+ or substituting -- in part or in whole -- any of the components of the
41
+ Original Version, by changing formats or by porting the Font Software to a
42
+ new environment.
43
+
44
+ "Author" refers to any designer, engineer, programmer, technical
45
+ writer or other person who contributed to the Font Software.
46
+
47
+ PERMISSION & CONDITIONS
48
+ Permission is hereby granted, free of charge, to any person obtaining
49
+ a copy of the Font Software, to use, study, copy, merge, embed, modify,
50
+ redistribute, and sell modified and unmodified copies of the Font
51
+ Software, subject to the following conditions:
52
+
53
+ 1) Neither the Font Software nor any of its individual components,
54
+ in Original or Modified Versions, may be sold by itself.
55
+
56
+ 2) Original or Modified Versions of the Font Software may be bundled,
57
+ redistributed and/or sold with any software, provided that each copy
58
+ contains the above copyright notice and this license. These can be
59
+ included either as stand-alone text files, human-readable headers or
60
+ in the appropriate machine-readable metadata fields within text or
61
+ binary files as long as those fields can be easily viewed by the user.
62
+
63
+ 3) No Modified Version of the Font Software may use the Reserved Font
64
+ Name(s) unless explicit written permission is granted by the corresponding
65
+ Copyright Holder. This restriction only applies to the primary font name as
66
+ presented to the users.
67
+
68
+ 4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
69
+ Software shall not be used to promote, endorse or advertise any
70
+ Modified Version, except to acknowledge the contribution(s) of the
71
+ Copyright Holder(s) and the Author(s) or with their explicit written
72
+ permission.
73
+
74
+ 5) The Font Software, modified or unmodified, in part or in whole,
75
+ must be distributed entirely under this license, and must not be
76
+ distributed under any other license. The requirement for fonts to
77
+ remain under this license does not apply to any document created
78
+ using the Font Software.
79
+
80
+ TERMINATION
81
+ This license becomes null and void if any of the above conditions are
82
+ not met.
83
+
84
+ DISCLAIMER
85
+ THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
86
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
87
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
88
+ OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
89
+ COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
90
+ INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
91
+ DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
92
+ FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
93
+ OTHER DEALINGS IN THE FONT SOFTWARE.
@@ -0,0 +1,104 @@
1
+ // Small pieces of HTML, and the one pattern every citizen is shown with: its name, its
2
+ // description, and its formaldef, folded. Pure: text in, markup out.
3
+ import { eloHtml } from './elo.js';
4
+ const ENTITIES = { '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' };
5
+ /** Any value, as text of a page: every name, sentence and value of the suite goes through here. */
6
+ export const esc = (value) => String(value).replace(/[&<>"']/g, (character) => ENTITIES[character] ?? character);
7
+ /** A value as a line of JSON, for what a case sends. */
8
+ export const compact = (value) => (value === undefined ? '' : JSON.stringify(value));
9
+ export const link = (href, text) => `<a href="${esc(href)}">${esc(text)}</a>`;
10
+ export const mono = (text) => `<span class="mono">${esc(text)}</span>`;
11
+ /** Elo code, highlighted, as a block: a name of the suite leads to its citizen, when what the suite names is given. */
12
+ export const elo = (text, refs, about) => `<pre class="elo">${eloHtml(text, refs, about)}</pre>`;
13
+ /** A description, as its file says it: what it sets between backticks is code. */
14
+ export const said = (description) => esc(description).replace(/`([^`]+)`/g, '<code>$1</code>');
15
+ /**
16
+ * What a file of the specification says of its section, as the page leads with it: its first
17
+ * paragraph as the lead, and the rest under it.
18
+ */
19
+ export function described(text) {
20
+ const [first = '', ...rest] = text.trim().split(/\n\s*\n/);
21
+ const lead = /^([-*] |#)/.test(first) ? markdown(first) : `<p class="lead">${inline(first.split('\n').map((line) => line.trim()).join(' '))}</p>`;
22
+ return `${lead}${rest.length ? `<div class="prose">${markdown(rest.join('\n\n'))}</div>` : ''}`;
23
+ }
24
+ /** A link of a text in Markdown leads to a page of the explorer, `#op-AddExpense`, or to the web: nothing else is a link. */
25
+ const LINKED = /^(#[\w-]+|https?:\/\/\S+)$/;
26
+ /** A line of Markdown: code between backticks, then, outside code, **strong**, *emphasis* and [links](#an-anchor). */
27
+ export function inline(text) {
28
+ // Code is set aside first, so that nothing in it is read as Markdown, then put back where it was.
29
+ const code = [];
30
+ const aside = text.replace(/\u0000/g, '').replace(/`([^`]+)`/g, (_, held) => `\u0000${code.push(held) - 1}\u0000`);
31
+ return esc(aside)
32
+ .replace(/\[([^\]]+)\]\(([^)\s]+)\)/g, (whole, label, href) => (LINKED.test(href) ? `<a href="${href}">${label}</a>` : whole))
33
+ .replace(/\*\*([^*]+)\*\*/g, '<strong>$1</strong>')
34
+ .replace(/\*([^*]+)\*/g, '<em>$1</em>')
35
+ .replace(/\u0000(\d+)\u0000/g, (_, at) => `<code>${esc(code[Number(at)])}</code>`);
36
+ }
37
+ /**
38
+ * A text of the suite in Markdown, as HTML: what a specification says of its system. Paragraphs,
39
+ * lists, headings (shown under the page's own), and what a line holds. Anything else is text:
40
+ * no HTML of the file reaches the page.
41
+ */
42
+ export function markdown(text) {
43
+ return text
44
+ .trim()
45
+ .split(/\n\s*\n/)
46
+ .map((block) => {
47
+ const lines = block.split('\n').map((line) => line.trim());
48
+ if (/^[-*] /.test(lines[0] ?? '')) {
49
+ // An item goes on until the next one begins: a long one is wrapped over several lines.
50
+ const items = lines.reduce((all, line) => (/^[-*] /.test(line) ? [...all, line.slice(2)] : [...all.slice(0, -1), `${all.at(-1)} ${line}`]), []);
51
+ return `<ul>${items.map((item) => `<li>${inline(item)}</li>`).join('')}</ul>`;
52
+ }
53
+ const heading = /^#{1,6} (.*)$/.exec(lines[0] ?? '');
54
+ if (heading && lines.length === 1)
55
+ return `<h3>${inline(heading[1] ?? '')}</h3>`;
56
+ return `<p>${inline(lines.join(' '))}</p>`;
57
+ })
58
+ .join('');
59
+ }
60
+ export const RESULT = {
61
+ passed: '<span class="res ok">✓ passed</span>',
62
+ failed: '<span class="res ko">✗ failed</span>',
63
+ notrun: '<span class="res nr">○ not run</span>',
64
+ };
65
+ const HOW = {
66
+ checked: { mark: '✔', words: 'Checked', short: 'checked' },
67
+ complete: { mark: '✚', words: 'Checked in the complete run only, by reading the database', short: 'checked in the complete run only' },
68
+ told: { mark: '○', words: 'Told, not checked: nothing decides it', short: 'told, not checked' },
69
+ };
70
+ /** How a clause is checked, as a mark with its words: by its formaldef, in the complete run only, or told. */
71
+ export function markOf(clause) {
72
+ const kind = !clause.formaldef ? 'told' : clause.mark === 'complete' ? 'complete' : 'checked';
73
+ const how = HOW[kind];
74
+ return `<span class="mk ${kind}" title="${esc(how.words)}" aria-label="${esc(how.words)}">${how.mark}</span>`;
75
+ }
76
+ /** What the marks mean: each as a clause shows it, a disc, beside its words. */
77
+ export const LEGEND = `<p class="legend">${Object.keys(HOW).map((kind) => `<span><span class="mk ${kind}" aria-hidden="true">${HOW[kind].mark}</span> ${HOW[kind].short}</span>`).join('')}</p>`;
78
+ /** A count, with the word for it, singular or plural. */
79
+ export const plural = (count, word) => `${count} ${count === 1 ? word : word.endsWith('y') ? `${word.slice(0, -1)}ies` : `${word}s`}`;
80
+ export const list = (items, cls = '') => (items.length ? `<ul class="list ${cls}">${items.map((item) => `<li>${item}</li>`).join('')}</ul>` : '');
81
+ const colgroup = (widths) => (widths ? `<colgroup>${widths.map((width) => `<col style="width:${width}">`).join('')}</colgroup>` : '');
82
+ const thead = (headers) => (headers.some(Boolean) ? `<thead><tr>${headers.map((header) => `<th>${esc(header)}</th>`).join('')}</tr></thead>` : '');
83
+ /** A table: its headers, then its rows, each a list of cells already written. Its columns may be given their widths, so that tables of one kind line up. */
84
+ export const table = (headers, rows, widths) => `<div class="scroll"><table class="t">${colgroup(widths)}${thead(headers)}<tbody>${rows.map((row) => `<tr>${row.map((cell) => `<td>${cell}</td>`).join('')}</tr>`).join('')}</tbody></table></div>`;
85
+ const TOGGLE = '<button type="button" class="fd-toggle" aria-expanded="false" title="Show or hide the formaldef of each one">formaldef</button>';
86
+ function citizenRows(one, span) {
87
+ const cells = [one.name, one.description, ...(one.more ?? [])].map((cell) => `<td>${cell}</td>`).join('');
88
+ const formal = one.formaldef ? `<tr class="formal-row"><td colspan="${span}"><div class="formaldef">${one.formaldef}</div></td></tr>` : '';
89
+ const told = [['id', one.id], ['class', 'citizen'], ['data-home', one.home], ['data-case', one.kase], ['data-source', one.source], ['data-request', one.request]].map(([name, value]) => (value ? ` ${name}="${esc(value)}"` : '')).join('');
90
+ return `<tr${told}>${cells}</tr>${formal}`;
91
+ }
92
+ /**
93
+ * The citizens of one kind, as every page shows them: a heading, then a row each with its name
94
+ * and its description, and its formaldef under it, folded until the heading's toggle, the
95
+ * sidebar's switch or its own address opens it.
96
+ */
97
+ export function citizens(title, all, { level = 'h2', columns = [], widths, note, intro = '' } = {}) {
98
+ if (!all.length)
99
+ return `<${level}>${esc(title)}</${level}>${intro}<p class="sub">None.</p>`;
100
+ const span = 2 + Math.max(0, ...all.map((one) => one.more?.length ?? 0));
101
+ const toggle = all.some((one) => one.formaldef) ? ` ${TOGGLE}` : '';
102
+ const heading = `<${level} class="group"><span>${esc(title)}${toggle}</span><span class="m s">${esc(note ?? plural(all.length, 'entry'))}</span></${level}>`;
103
+ return `<section class="citizens">${heading}${intro}<div class="scroll"><table class="t">${colgroup(widths)}${thead(columns)}<tbody>${all.map((one) => citizenRows(one, span)).join('')}</tbody></table></div></section>`;
104
+ }
@@ -0,0 +1,62 @@
1
+ // What the search of the explorer finds: one entry per page, and one per citizen at its own
2
+ // address, clauses and cases among them. Pure: the wiki and its pages are given.
3
+ //
4
+ // An entry is `{h, k, n, x, c, ctx}`: its anchor, its kind, its name or its sentence, what else
5
+ // it says, its formaldef as text, and the title of the page it is on. A row that only lists a
6
+ // citizen at home elsewhere is not one: a citizen is found once, where it is. What an example
7
+ // alone also shows is a clause, at an address in the row of its example.
8
+ //
9
+ // The search reads those six. A note taken on a citizen reads three more, where they apply, to
10
+ // say what it is about: `a`, its area; `w`, where it stands (`ReqPre 2`, `example 1`, the name of
11
+ // a condition); `q`, its description as written, when `n` is its name and not what it says.
12
+ import { PRE } from '../suite.js';
13
+ import { areaTitle } from './operation.js';
14
+ import { idOf, violating } from './wiki.js';
15
+ const WORLD = 'World';
16
+ const STATE = 'State';
17
+ const BACKGROUNDS = 'Backgrounds';
18
+ const answered = (then) => `${then.status}${then.code ? ` ${then.code}` : ''}`;
19
+ const told = (...parts) => parts.filter(Boolean).join(' · ');
20
+ const definition = (one, ctx) => ({ h: idOf(one.kind, one.name), k: one.kind === 'predicate' ? 'Predicate' : 'Function', n: one.name, x: one.description, c: one.formaldef, ctx, a: one.area, q: one.description });
21
+ /** A condition is found by its sentence; its name is where it stands. */
22
+ const condition = (one, ctx) => ({ h: idOf('condition', one.name), k: 'Condition', n: one.description, x: told(one.name, one.violated && `violated as ${one.violated.actor}: ${answered(one.violated.then)}`), c: one.formaldef, ctx, a: one.area, w: one.name });
23
+ const wordsOf = (area) => {
24
+ const ctx = areaTitle(area.name);
25
+ return [
26
+ ...[...area.predicates, ...area.functions].map((one) => definition(one, ctx)),
27
+ ...area.conditions.map((one) => condition(one, ctx)),
28
+ ...area.types.map((one) => ({ h: idOf('type', one.name), k: 'Type', n: one.name, x: one.description, c: `${one.name} = ${one.formaldef}`, ctx, a: one.area, q: one.description })),
29
+ ];
30
+ };
31
+ /** A clause is found by its sentence, and a precondition by the counterexamples that refuse it too. */
32
+ function clause(operation, one) {
33
+ const refused = PRE.includes(one.kind) ? violating(operation, one.description).map((kase) => kase.description) : [];
34
+ const at = operation.clauses.filter((other) => other.kind === one.kind).indexOf(one) + 1;
35
+ return { h: idOf('clause', one.name), k: 'Clause', n: one.description, x: told(one.kind, refused.length ? `refused when ${refused.join('; ')}` : ''), c: one.formaldef ?? '', ctx: operation.name, a: operation.area, w: `${one.kind} ${at}` };
36
+ }
37
+ /** A case is found by its `when`, by who calls and what is answered, and by what it alone also shows. */
38
+ function kase(operation, one) {
39
+ const sent = typeof one.input === 'string' ? one.input : one.input === null || one.input === undefined ? '' : JSON.stringify(one.input);
40
+ const x = told(one.kind, one.given.actor, one.given.seed, answered(one.then), one.for && `refuses ${one.for}`, ...one.and.map((also) => also.description), sent);
41
+ const w = one.generated ? 'counterexample, from a condition' : `${one.kind} ${operation.cases.filter((other) => other.kind === one.kind).indexOf(one) + 1}`;
42
+ return { h: idOf('case', one.name), k: 'Case', n: one.description, x, c: one.and.map((also) => also.formaldef ?? '').filter(Boolean).join('\n'), ctx: operation.name, a: operation.area, w };
43
+ }
44
+ /** What an example alone also shows is a clause too, found by its sentence: it stands in its example. */
45
+ function also(operation, one) {
46
+ const example = operation.cases.filter((other) => other.kind === one.kind).indexOf(one) + 1;
47
+ return one.and.map((clause, at) => ({ h: idOf('clause', clause.name), k: 'Clause', n: clause.description, x: told('and', `shown when ${one.description}`), c: clause.formaldef ?? '', ctx: operation.name, a: operation.area, w: `${one.kind} ${example}, and ${at + 1}` }));
48
+ }
49
+ /** A citizen that has no formaldef in Elo: found by its name, and by what it says. */
50
+ const plain = (kind, label, ctx, one, also = '') => ({ h: idOf(kind, one.name), k: label, n: one.name, x: told(one.description, also), c: '', ctx, q: one.description });
51
+ /** Every entry of the search: the pages, then the citizens, each at its address. */
52
+ export function indexOf(wiki, pages) {
53
+ return [
54
+ ...pages.map((page) => ({ h: page.id, k: page.kind, n: page.title, x: page.said ?? '', c: '', ctx: '', ...(page.area ? { a: page.area } : {}), ...(page.quote ? { q: page.quote } : {}) })),
55
+ ...wiki.areas.flatMap(wordsOf),
56
+ ...wiki.operations.flatMap((operation) => [...operation.clauses.map((one) => clause(operation, one)), ...operation.cases.flatMap((one) => [kase(operation, one), ...also(operation, one)])]),
57
+ ...wiki.state.map((one) => plain('state', 'State', STATE, one, `GET ${one.path}`)),
58
+ ...wiki.relations.map((one) => ({ h: idOf('relation', one.name), k: 'Relation', n: `db.${one.name}`, x: told(one.description, one.table, one.attributes.join(', ')), c: '', ctx: STATE, q: one.description })),
59
+ ...wiki.backgrounds.map((one) => plain('background', 'Background', BACKGROUNDS, one)),
60
+ ...wiki.actors.map((one) => plain('actor', 'Actor', WORLD, one, one.is)),
61
+ ];
62
+ }
@@ -0,0 +1,33 @@
1
+ // JSON, highlighted: the keys, strings, numbers, literals and punctuation of a JSON text, each
2
+ // in its class. Pure: text in, markup out; the tokens say the whole text, every character once.
3
+ import { esc } from './html.js';
4
+ const TOKENS = [
5
+ [/"(?:\\.|[^"\\])*"(?=\s*:)/y, 'key'],
6
+ [/"(?:\\.|[^"\\])*"/y, 'str'],
7
+ [/-?\d+(?:\.\d+)?(?:[eE][+-]?\d+)?/y, 'num'],
8
+ [/true|false|null/y, 'lit'],
9
+ [/[{}[\],:]/y, 'p'],
10
+ [/\s+/y, 'text'],
11
+ [/[\s\S]/y, 'text'],
12
+ ];
13
+ /** The JSON text, highlighted: each kind of token is a span of its own class. */
14
+ export function jsonHtml(text) {
15
+ let out = '';
16
+ let at = 0;
17
+ while (at < text.length) {
18
+ let matched = '';
19
+ let kind = 'text';
20
+ for (const [pattern, name] of TOKENS) {
21
+ pattern.lastIndex = at;
22
+ const found = pattern.exec(text);
23
+ if (found && found[0].length > 0) {
24
+ matched = found[0];
25
+ kind = name;
26
+ break;
27
+ }
28
+ }
29
+ out += kind === 'text' ? esc(matched) : `<span class="j-${kind}">${esc(matched)}</span>`;
30
+ at += matched.length;
31
+ }
32
+ return out;
33
+ }
@@ -0,0 +1,34 @@
1
+ // This machine, as a request or an option names it. Pure.
2
+ //
3
+ // The API of a served explorer runs cases and signs actors in, so it is offered on this machine
4
+ // and answers its own page: who asks is told by the host a request names and by the origin it
5
+ // comes from, which a browser says for a page and a page cannot change. What is not plainly this
6
+ // machine is not: a name that only resolves to it, a short form of its address.
7
+ /** The name in a host, without its port: `[::1]:8080` names `::1`, `LocalHost.:8080` names `localhost`. */
8
+ function named(host) {
9
+ const bracketed = /^\[([0-9a-f.]*:[0-9a-f:.]*)\](?::\d+)?$/i.exec(host);
10
+ if (bracketed)
11
+ return (bracketed[1] ?? '').toLowerCase();
12
+ // More than one colon is an address of IPv6 said bare, as `--host=::1` says it: it has no port.
13
+ const bare = (host.match(/:/g) ?? []).length > 1 ? host : host.replace(/:\d+$/, '');
14
+ return bare.toLowerCase().replace(/\.$/, '');
15
+ }
16
+ /** An address of IPv4 that never leaves the machine: 127.0.0.0/8, each part written plainly. */
17
+ const LOOPBACK = /^127(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}$/;
18
+ /** A host that is this machine: `localhost`, `::1`, an address under 127, whatever its port, its case, or the dot that ends its name. */
19
+ export function isLoopback(host) {
20
+ const name = named(host);
21
+ return name === 'localhost' || name === '::1' || LOOPBACK.test(name);
22
+ }
23
+ /**
24
+ * Whether a request is the page's own: it names this machine, and comes from nowhere else. A
25
+ * browser says the origin of whatever is more than a reading, so a request that says none is no
26
+ * page of another site.
27
+ */
28
+ export function ownPage(host, origin) {
29
+ if (host === undefined || !isLoopback(host))
30
+ return false;
31
+ return origin === undefined || origin.toLowerCase() === `http://${host.toLowerCase()}`;
32
+ }
33
+ /** Where a server is, as a reader types it: an address of IPv6 between brackets. */
34
+ export const urlOf = (host, port) => `http://${host.includes(':') ? `[${host}]` : host}:${port}/`;
@@ -0,0 +1,57 @@
1
+ // What is told of a run, without what the world keeps to itself. Pure.
2
+ //
3
+ // The world of a suite holds what its actors sign in with, and what the system told once: a
4
+ // token a seed planted. A case may send them (an input computed from `world`), a system may say
5
+ // them back, and a sign-in that fails may name them. The page of a run is told none of it: a
6
+ // text that is one of those values is said as `•••`, and so is the part of a longer text that is
7
+ // one of eight characters or more, which nobody says by chance. A shorter one is a name as often
8
+ // as a secret (`member`, `fr`): it is hidden where it stands alone, and left inside a sentence.
9
+ import { credentialsOf } from '../suite.js';
10
+ export const MASK = '•••';
11
+ const LONG = 8;
12
+ const textsIn = (value) => (typeof value === 'string' ? [value] : value && typeof value === 'object' ? Object.values(value).flatMap(textsIn) : []);
13
+ /** The texts of the world, at whatever depth: what each actor signs in with, and what else `world.yml` says. */
14
+ export function secretsOf(model) {
15
+ const all = new Set([...textsIn(credentialsOf(model)), ...textsIn(model.world)].filter(Boolean));
16
+ return { all, long: [...all].filter((one) => one.length >= LONG).sort((a, b) => b.length - a.length) };
17
+ }
18
+ /** A text, as it is told: the mask where it is a secret, or holds a long one. */
19
+ export const hidden = (text, { all, long }) => (all.has(text) ? MASK : long.reduce((told, secret) => told.split(secret).join(MASK), text));
20
+ /** Data, as it is told: each text of it hidden. The keys are left: they are names, not values. */
21
+ export function masked(value, secrets) {
22
+ if (typeof value === 'string')
23
+ return hidden(value, secrets);
24
+ if (Array.isArray(value))
25
+ return value.map((one) => masked(one, secrets));
26
+ if (!value || typeof value !== 'object')
27
+ return value;
28
+ return Object.fromEntries(Object.entries(value).map(([name, one]) => [name, masked(one, secrets)]));
29
+ }
30
+ /** A part of a path, as it is told: read as it was before it was made safe for a path, and left as it is written when nothing of it is hidden. */
31
+ function part(text, secrets) {
32
+ let written = text;
33
+ try {
34
+ written = decodeURIComponent(text);
35
+ }
36
+ catch {
37
+ // What is no part made safe is read as it stands.
38
+ }
39
+ const told = hidden(written, secrets);
40
+ return told === written ? text : told.split(MASK).map(encodeURIComponent).join(MASK);
41
+ }
42
+ /** A path, as it is told: each part of its route and each value of its query hidden. */
43
+ export function maskedPath(path, secrets) {
44
+ const [route = '', ...query] = path.split('?');
45
+ const pair = (one) => (one.includes('=') ? `${one.slice(0, one.indexOf('='))}=${part(one.slice(one.indexOf('=') + 1), secrets)}` : one);
46
+ const asked = query.length ? `?${query.join('?').split('&').map(pair).join('&')}` : '';
47
+ return `${route.split('/').map((one) => part(one, secrets)).join('/')}${asked}`;
48
+ }
49
+ /** What a case did, as it is told: of each call, where it went, what it sent and what it was answered. */
50
+ export function maskedWire(wire, secrets) {
51
+ return wire.map((one) => {
52
+ if (!('method' in one))
53
+ return one;
54
+ const sent = one.sent === undefined ? {} : { sent: masked(one.sent, secrets) };
55
+ return { ...one, path: maskedPath(one.path, secrets), ...sent, body: masked(one.body, secrets) };
56
+ });
57
+ }