@sigrix-io/gatehouse 0.1.1 → 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.
@@ -0,0 +1,329 @@
1
+ /* What is inside a playbook: its files, in the order a person works through
2
+ * them, with what each one is for, and the placeholders a buyer fills in.
3
+ *
4
+ * A playbook is a process a business runs by hand, sold as the files a person
5
+ * works through, and described by a `playbook.json` in the Muster format. The
6
+ * host hands that document in, parsed, and the block draws it. There is
7
+ * nothing to run and nothing to fetch: the block never reads a file and never
8
+ * draws a file's text, only what the document says the files are, so a page
9
+ * may show a playbook's contents to someone who has not bought it.
10
+ *
11
+ * It reads format 0.x. A minor version only adds members an earlier reader can
12
+ * ignore, so any 0.x is read and a member this file does not name is ignored;
13
+ * a major version it does not know is refused, whole, saying why.
14
+ *
15
+ * **Nothing here uses `innerHTML`.** A path, a placeholder's label and a
16
+ * host's note are someone's typing, and all of it reaches the page through
17
+ * `textContent`. No attribute is written from the document.
18
+ */
19
+ (function (global) {
20
+ const root = global || (typeof window !== 'undefined' ? window : {});
21
+
22
+ /* The major version of the format this file reads. */
23
+ const FORMAT_MAJOR = 0;
24
+
25
+ /* What each role the format names is called here. A role this client has
26
+ * not heard of is shown as the document spells it, rather than guessed into
27
+ * one of these. */
28
+ const ROLES = {
29
+ guide: 'Guide',
30
+ steps: 'Steps',
31
+ checklist: 'Checklist',
32
+ copy: 'Copy',
33
+ reference: 'Reference',
34
+ tool: 'Tool',
35
+ license: 'License',
36
+ changelog: 'Changelog',
37
+ };
38
+
39
+ /* The kinds of placeholder the format names, by when a buyer fills them in,
40
+ * in the format's order. A kind a later minor adds is ignored, as the
41
+ * format lets a reader ignore what it does not know. */
42
+ const SLOT_KINDS = [
43
+ ['setup', 'Once, for your business'],
44
+ ['message', 'Each time you use it'],
45
+ ];
46
+
47
+ function el(tag, className, textContent) {
48
+ const node = document.createElement(tag);
49
+ if (className) node.className = className;
50
+ if (textContent !== undefined && textContent !== null) node.textContent = String(textContent);
51
+ return node;
52
+ }
53
+
54
+ function clear(node) {
55
+ while (node.firstChild) node.removeChild(node.firstChild);
56
+ }
57
+
58
+ function isObject(value) {
59
+ return Boolean(value) && typeof value === 'object' && !Array.isArray(value);
60
+ }
61
+
62
+ function has(table, key) {
63
+ return Object.prototype.hasOwnProperty.call(table, key);
64
+ }
65
+
66
+ /* ---------- reading the document ----------
67
+ *
68
+ * The reader answers `{ value }` or `{ refusal }`, never both. A refusal is
69
+ * one sentence naming what was wrong, for whoever built the host's data. The
70
+ * block checks only what drawing needs: that the members it reads are what
71
+ * the format says they are, and that `order` and `same_as` name the files
72
+ * `files` lists, matched exactly, as the format matches them. Whether the
73
+ * files really say what the document claims is a checker's question, asked
74
+ * of the files, which this block never has. */
75
+
76
+ class Fault extends Error {}
77
+
78
+ function formatOf(doc) {
79
+ const value = doc.format_version;
80
+ if (value === undefined || value === null) {
81
+ throw new Fault('It carries no "format_version", and this client reads format ' + FORMAT_MAJOR + '.x.');
82
+ }
83
+ if (typeof value !== 'string' || !/^\d+\.\d+$/.test(value)) {
84
+ throw new Fault('"format_version" is not a version such as 0.1.');
85
+ }
86
+ if (Number(value.split('.')[0]) !== FORMAT_MAJOR) {
87
+ throw new Fault('It is in format ' + value + ', and this client reads format ' + FORMAT_MAJOR + '.x.');
88
+ }
89
+ return value;
90
+ }
91
+
92
+ function textMember(doc, key, required) {
93
+ const value = doc[key];
94
+ if (value === undefined || value === null) {
95
+ if (required) throw new Fault('"' + key + '" is missing.');
96
+ return '';
97
+ }
98
+ if (typeof value !== 'string') throw new Fault('"' + key + '" is not text.');
99
+ if (required && !value.trim()) throw new Fault('"' + key + '" is empty.');
100
+ return value;
101
+ }
102
+
103
+ function listMember(doc, key, where) {
104
+ const value = doc[key];
105
+ const name = where ? where + '.' + key : key;
106
+ if (value === undefined || value === null) throw new Fault('"' + name + '" is missing.');
107
+ if (!Array.isArray(value)) throw new Fault('"' + name + '" is not a list.');
108
+ return value;
109
+ }
110
+
111
+ function readFiles(doc) {
112
+ const entries = listMember(doc, 'files');
113
+ if (!entries.length) throw new Fault('"files" lists no file.');
114
+ const byPath = new Map();
115
+ entries.forEach(function (entry) {
116
+ if (!isObject(entry)) throw new Fault('"files" holds something other than a file.');
117
+ const path = textMember(entry, 'path', true);
118
+ if (byPath.has(path)) throw new Fault('"files" lists ' + path + ' twice.');
119
+ byPath.set(path, {
120
+ path,
121
+ role: textMember(entry, 'role', true),
122
+ sameAs: textMember(entry, 'same_as', false),
123
+ selfContained: entry.self_contained === true,
124
+ });
125
+ });
126
+ byPath.forEach(function (file) {
127
+ if (file.sameAs && (file.sameAs === file.path || !byPath.has(file.sameAs))) {
128
+ throw new Fault(file.path + ' is the same as ' + file.sameAs + ', which is not another file in "files".');
129
+ }
130
+ });
131
+
132
+ /* Drawn in `order`, which names every file once: the order a person works
133
+ * through them is part of what the playbook is. */
134
+ const seen = new Set();
135
+ const ordered = listMember(doc, 'order').map(function (path) {
136
+ if (typeof path !== 'string') throw new Fault('"order" holds something other than a path.');
137
+ if (!byPath.has(path)) throw new Fault('"order" names ' + path + ', which "files" does not.');
138
+ if (seen.has(path)) throw new Fault('"order" names ' + path + ' twice.');
139
+ seen.add(path);
140
+ return byPath.get(path);
141
+ });
142
+ byPath.forEach(function (file) {
143
+ if (!seen.has(file.path)) throw new Fault('"order" leaves out ' + file.path + '.');
144
+ });
145
+ return ordered;
146
+ }
147
+
148
+ function readSlots(doc) {
149
+ if (!isObject(doc.slots)) throw new Fault('"slots" is missing.');
150
+ return SLOT_KINDS.map(function (kind) {
151
+ const entries = listMember(doc.slots, kind[0], 'slots');
152
+ return {
153
+ kind: kind[0],
154
+ heading: kind[1],
155
+ slots: entries.map(function (entry) {
156
+ if (!isObject(entry)) throw new Fault('"slots.' + kind[0] + '" holds something other than a placeholder.');
157
+ return { placeholder: textMember(entry, 'placeholder', true), label: textMember(entry, 'label', true) };
158
+ }),
159
+ };
160
+ });
161
+ }
162
+
163
+ function readPlaybook(doc) {
164
+ try {
165
+ if (!isObject(doc)) throw new Fault('The document is not an object.');
166
+ const formatVersion = formatOf(doc);
167
+ return { value: { formatVersion, files: readFiles(doc), slotGroups: readSlots(doc) } };
168
+ } catch (err) {
169
+ if (err instanceof Fault) return { refusal: err.message };
170
+ throw err;
171
+ }
172
+ }
173
+
174
+ /* ---------- writing it down ---------- */
175
+
176
+ function headingLevel(options) {
177
+ const level = Number(options && options.headingLevel);
178
+ return Number.isInteger(level) && level >= 2 && level <= 6 ? level : 3;
179
+ }
180
+
181
+ function plural(count, one, many) {
182
+ return count + ' ' + (count === 1 ? one : many);
183
+ }
184
+
185
+ /* `a`, `a and b`, `a, b and c`. */
186
+ function and(items) {
187
+ return items.length === 1 ? items[0] : items.slice(0, -1).join(', ') + ' and ' + items[items.length - 1];
188
+ }
189
+
190
+ /* What a file adds to its role: the file it is another form of, and, for a
191
+ * page, that it opens in a browser and loads nothing. Only an `.html` file
192
+ * the document calls self-contained is said to work offline. */
193
+ function about(file) {
194
+ const parts = [];
195
+ if (file.sameAs) parts.push('Another form of ' + file.sameAs + '.');
196
+ if (/\.html$/i.test(file.path)) {
197
+ parts.push(file.selfContained ? 'Opens in a browser, and works offline.' : 'Opens in a browser.');
198
+ }
199
+ return parts.join(' ');
200
+ }
201
+
202
+ /* A sentence the host adds to one file, keyed by its path: something the
203
+ * host knows that the document does not say, such as what it found when it
204
+ * read the file. Drawn as text, beside the file it names; a note for a path
205
+ * the playbook does not hold is not drawn. */
206
+ function hostNote(options, path) {
207
+ const notes = options && options.fileNotes;
208
+ if (!isObject(notes) || !has(notes, path)) return '';
209
+ const note = notes[path];
210
+ return typeof note === 'string' ? note.trim() : '';
211
+ }
212
+
213
+ /* Two placeholders one case apart are two placeholders, which a reader
214
+ * replacing them by eye could take for one, so the block says so. */
215
+ function caseNote(groups) {
216
+ const folded = new Map();
217
+ groups.forEach(function (group) {
218
+ group.slots.forEach(function (slot) {
219
+ const key = slot.placeholder.toLowerCase();
220
+ if (!folded.has(key)) folded.set(key, []);
221
+ if (folded.get(key).indexOf(slot.placeholder) === -1) folded.get(key).push(slot.placeholder);
222
+ });
223
+ });
224
+ const pairs = [];
225
+ folded.forEach(function (spellings) {
226
+ if (spellings.length > 1) pairs.push(and(spellings) + ' are different placeholders');
227
+ });
228
+ return pairs.length ? 'Case matters: ' + pairs.join('; ') + '.' : '';
229
+ }
230
+
231
+ function filesPart(files, level, options) {
232
+ const part = el('div', 'gh-playbook-part');
233
+ part.appendChild(el('h' + level, 'gh-playbook-heading', 'The files'));
234
+ part.appendChild(el('p', 'gh-playbook-lead', plural(files.length, 'file', 'files') + ', in the order you work through them.'));
235
+ const list = el('ol', 'gh-playbook-files');
236
+ files.forEach(function (file) {
237
+ /* The row's parts sit in a box of their own, so the item stays a list
238
+ * item and keeps the number the browser gives it: an item laid out as
239
+ * a flex row is drawn with none. */
240
+ const item = el('li', 'gh-playbook-file');
241
+ const body = el('div', 'gh-playbook-file-body');
242
+ body.appendChild(el('code', 'gh-playbook-path', file.path));
243
+ body.appendChild(el('span', 'gh-playbook-role', has(ROLES, file.role) ? ROLES[file.role] : file.role));
244
+ const sentence = about(file);
245
+ if (sentence) body.appendChild(el('span', 'gh-playbook-about', sentence));
246
+ const note = hostNote(options, file.path);
247
+ if (note) body.appendChild(el('span', 'gh-playbook-note', note));
248
+ item.appendChild(body);
249
+ list.appendChild(item);
250
+ });
251
+ part.appendChild(list);
252
+ return part;
253
+ }
254
+
255
+ function placeholdersPart(groups, level) {
256
+ const part = el('div', 'gh-playbook-part');
257
+ part.appendChild(el('h' + level, 'gh-playbook-heading', 'The placeholders'));
258
+ const total = groups.reduce((sum, group) => sum + group.slots.length, 0);
259
+ if (!total) {
260
+ part.appendChild(el('p', 'gh-playbook-lead', 'None. Every file is used as it is.'));
261
+ return part;
262
+ }
263
+ part.appendChild(el('p', 'gh-playbook-lead', total === 1
264
+ ? 'One placeholder, in square brackets. Replace it with your own words wherever it appears.'
265
+ : total + ' placeholders, each in square brackets. Replace each with your own words wherever it appears.'));
266
+ const note = caseNote(groups);
267
+ if (note) part.appendChild(el('p', 'gh-playbook-lead', note));
268
+ /* Hoisted rather than written in the call, so the stylesheet's test, which
269
+ * reads the class beside the first comma, sees this one too. */
270
+ const subheading = 'h' + Math.min(level + 1, 6);
271
+ groups.forEach(function (group) {
272
+ if (!group.slots.length) return;
273
+ const section = el('div', 'gh-playbook-slot-group');
274
+ section.dataset.slotKind = group.kind;
275
+ section.appendChild(el(subheading, 'gh-playbook-subheading', group.heading));
276
+ const list = el('dl', 'gh-playbook-slots');
277
+ group.slots.forEach(function (slot) {
278
+ const row = el('div', 'gh-playbook-slot');
279
+ const name = el('dt', 'gh-playbook-slot-name');
280
+ name.appendChild(el('code', 'gh-playbook-token', slot.placeholder));
281
+ row.appendChild(name);
282
+ row.appendChild(el('dd', 'gh-playbook-slot-label', slot.label));
283
+ list.appendChild(row);
284
+ });
285
+ section.appendChild(list);
286
+ part.appendChild(section);
287
+ });
288
+ return part;
289
+ }
290
+
291
+ class PlaybookContents {
292
+ /* `playbook` is a playbook's `playbook.json`, parsed. `options.headingLevel`
293
+ * (2 to 6, default 3) is the level of the block's two headings, and the
294
+ * placeholders' kinds take the level below. `options.fileNotes` maps a
295
+ * file's path to a sentence of the host's own, drawn beside that file. */
296
+ constructor(container, playbook, options) {
297
+ this.container = container;
298
+ this.playbook = playbook;
299
+ this.options = options || {};
300
+ }
301
+
302
+ render() {
303
+ clear(this.container);
304
+ const block = el('section', 'gh-block gh-playbook');
305
+ this.container.appendChild(block);
306
+ const read = readPlaybook(this.playbook);
307
+ if (read.refusal) {
308
+ block.appendChild(el('p', 'gh-refuse', 'This playbook could not be shown. ' + read.refusal));
309
+ return;
310
+ }
311
+ const level = headingLevel(this.options);
312
+ block.appendChild(filesPart(read.value.files, level, this.options));
313
+ block.appendChild(placeholdersPart(read.value.slotGroups, level));
314
+ }
315
+
316
+ update(playbook) {
317
+ this.playbook = playbook;
318
+ this.render();
319
+ }
320
+ }
321
+
322
+ root.Gatehouse = Object.assign({}, root.Gatehouse, {
323
+ PlaybookContents,
324
+ playbookData: { FORMAT_MAJOR, ROLES: Object.keys(ROLES), readPlaybook },
325
+ });
326
+
327
+ /* The deprecated alias the other scripts keep; see `host_blocks.js`. */
328
+ root.SigrixRun = root.Gatehouse;
329
+ })(typeof window !== 'undefined' ? window : globalThis);
@@ -31,6 +31,13 @@
31
31
  return 'k-' + Date.now() + '-' + Math.random().toString(16).slice(2);
32
32
  }
33
33
 
34
+ /* How many renderers this copy of the file has made. An id is unique to the
35
+ * document, not to the container it is drawn in, so two renderers on one
36
+ * page that both wrote `run-field-prompt` would bind each `<label>` to the
37
+ * first page's field. Each renderer writes its ids under a scope of its own
38
+ * instead, numbered in the order they were made. */
39
+ let renderersMade = 0;
40
+
34
41
  class RunRenderer {
35
42
  /* `container` is where the page is drawn; `client` is any object with the
36
43
  * four verbs, so a caller may pass its own. `options.composition` is the
@@ -64,6 +71,15 @@
64
71
  this.idempotencyKey = '';
65
72
  this.onRunStateChange = settings.onRunStateChange || function () {};
66
73
  this.nodes = {};
74
+ renderersMade += 1;
75
+ this.idScope = 'run-' + renderersMade;
76
+ }
77
+
78
+ /* An id inside this renderer's scope. A host looking for a field finds it
79
+ * by its `name`, which is the input's key, inside the container it handed
80
+ * in; the id is this renderer's own business. */
81
+ scopedId(part) {
82
+ return this.idScope + '-' + part;
67
83
  }
68
84
 
69
85
  async load() {
@@ -197,7 +213,7 @@
197
213
  this.nodes.choiceAbout = null;
198
214
  vm.fields.forEach(function (field) {
199
215
  const wrap = el('div', 'run-field');
200
- const id = 'run-field-' + field.key;
216
+ const id = self.scopedId('field-' + field.key);
201
217
  const label = el('label', 'run-field-label', field.label + (field.required ? ' *' : ''));
202
218
  label.htmlFor = id;
203
219
  wrap.appendChild(label);
@@ -316,11 +332,11 @@
316
332
  const gate = el('div', 'run-write-gate');
317
333
  const box = el('input', 'run-write-check');
318
334
  box.type = 'checkbox';
319
- box.id = 'run-write-confirm';
335
+ box.id = this.scopedId('write-confirm');
320
336
  const label = el('label', 'run-write-label',
321
337
  'This agent can ' + vm.capabilities.writeTools.join(', ') +
322
338
  '. Runs cost money and write outside this page; stopping a run or closing the tab cancels it but does not undo it.');
323
- label.htmlFor = 'run-write-confirm';
339
+ label.htmlFor = box.id;
324
340
  box.addEventListener('change', function () {
325
341
  self.writeToolsAccepted = box.checked;
326
342
  self.syncRunEnabled();
@@ -82,6 +82,24 @@
82
82
  return value === null || value === undefined ? '' : String(value);
83
83
  }
84
84
 
85
+ /* A link the page may draw: an absolute `http:` or `https:` address, and
86
+ * nothing else. `signup_url` is a runner author's prose, and the schema's
87
+ * `"format": "uri"` is satisfied by a `javascript:` URI as readily as by a
88
+ * web page; an anchor is the one element through which a string becomes
89
+ * something a click runs. Anything else draws no link. `host_blocks.js`
90
+ * applies the same rule to the same member, and one case table holds both. */
91
+ function webLink(value) {
92
+ const candidate = text(value).trim();
93
+ if (!candidate) return '';
94
+ let parsed;
95
+ try {
96
+ parsed = new URL(candidate);
97
+ } catch (err) {
98
+ return '';
99
+ }
100
+ return parsed.protocol === 'http:' || parsed.protocol === 'https:' ? parsed.href : '';
101
+ }
102
+
85
103
  /* SPEC 4.1.3 and 7: a `describe` carrying a credential *value* is
86
104
  * nonconformant, and a client meeting one SHOULD refuse to proceed. This one
87
105
  * refuses — returning the reason rather than throwing, so the page can say
@@ -432,7 +450,7 @@
432
450
  return {
433
451
  env,
434
452
  purpose: text(entry.purpose),
435
- signupUrl: text(entry.signup_url),
453
+ signupUrl: webLink(entry.signup_url),
436
454
  satisfied: missing.indexOf(env) === -1,
437
455
  };
438
456
  });
@@ -612,6 +630,7 @@
612
630
  limitsView,
613
631
  updateNotice,
614
632
  credentialLeak,
633
+ webLink,
615
634
  },
616
635
  });
617
636