@kosuke-ai/kosuke 1.0.155 → 1.0.156

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,9 @@
1
1
  # Changelog
2
2
 
3
+ ## 1.0.156
4
+
5
+ - `kosuke prototypes create` now runs each state's `view`, including the first draw inside `definePrototype` as the page does, and refuses a prototype whose `view` throws or draws no element, naming the state, Variant and error.
6
+
3
7
  ## 1.0.155
4
8
 
5
9
  - Setting a workspace's AWS Bedrock credentials now refuses a region that is not an AWS region name, such as `us-east-1`, before any key check runs.
@@ -4,10 +4,13 @@ import { extname } from 'node:path';
4
4
  /**
5
5
  * The step check `kosuke prototypes create` runs before it uploads: it runs the prototype's own
6
6
  * content.js here, in the sandbox, and never on the platform. For each declared state, in each
7
- * Variant it shows, it seeds the model as the page does, applies the state's `show` entry and asks
8
- * `state()` which state is on screen; a state that cannot be shown, or shows another, is an issue.
9
- * The context below mirrors the shell's `ctx` in src/lib/prototypes/template.html, with scheduled
10
- * work held as the shell holds it while it shows a state. `view` is not run: there is no page.
7
+ * Variant it shows, it seeds the model as the page does, applies the state's `show` entry, asks
8
+ * `state()` which state is on screen and runs `view`; a state that cannot be shown, shows another,
9
+ * or draws nothing (`view` throws, or returns no element) is an issue. As the page does, it also
10
+ * draws once inside `definePrototype`, so content whose `view` reaches a const declared below the
11
+ * call fails here as it fails in the browser. The context below mirrors the shell's `ctx` in
12
+ * src/lib/prototypes/template.html, with scheduled work held as the shell holds it while it shows
13
+ * a state. There is no DOM: "an element" means the markup holds at least one tag.
11
14
  *
12
15
  * The script runs in a child Node process, never in the CLI's own: under the permission model
13
16
  * (no file system, no child processes, no workers or addons), with an empty environment, so no
@@ -46,29 +49,23 @@ function checksOf(config) {
46
49
  }
47
50
  return checks;
48
51
  }
49
- // The page's globals the content may call, made inside the context.
50
- const PRELUDE = `globalThis.__definitions = [];
51
- globalThis.definePrototype = (definition) => { __definitions.push(definition); };
52
- globalThis.console = { log() {}, info() {}, warn() {}, error() {}, debug() {} };
53
- globalThis.window = globalThis;
54
- globalThis.self = globalThis;`;
55
- // Runs inside the context, so the time limit covers the content's own calls too.
56
- const HARNESS = `(() => {
57
- const checks = JSON.parse(__checks);
58
- const definition = __definitions[0];
59
- if (__definitions.length === 0) return JSON.stringify({ load: 'content.js never calls definePrototype' });
60
- if (__definitions.length > 1) return JSON.stringify({ load: 'content.js calls definePrototype more than once' });
52
+ // The page's globals the content may call, made inside the context before content.js runs. As the
53
+ // shell does, definePrototype seeds and draws at once, in the scenario the page opens on, and a
54
+ // throw there leaves definePrototype and stops content.js: a const declared below the call stays
55
+ // uninitialised for good, so every later draw throws too, as it does in the browser. The harness
56
+ // keeps its state on one configurable global, so content may declare any name of its own.
57
+ const PRELUDE = `(() => {
61
58
  const escape = (value) => String(value).replace(/[&<>"']/g, (char) => ({'&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;'})[char]);
62
59
  const RAW = Symbol('pt-raw');
63
60
  const raw = (value) => value != null && value[RAW] !== undefined ? value : Object.defineProperty({[RAW]: String(value)}, 'toString', {value() { return this[RAW]; }});
64
61
  const interpolate = (value) => value == null || value === false ? '' : Array.isArray(value) ? value.map(interpolate).join('') : value[RAW] !== undefined ? value[RAW] : escape(value);
65
62
  const html = (strings, ...values) => raw(strings.reduce((out, part, index) => out + part + (index < values.length ? interpolate(values[index]) : ''), ''));
66
63
  const message = (error) => error && error.message ? String(error.message) : String(error);
67
- return JSON.stringify({ results: checks.map((check) => {
64
+ const context = (scenario) => {
68
65
  let overlay = null, pending = 0;
69
- const ctx = {
66
+ return {
70
67
  html, raw, escape,
71
- flow: check.flow, variant: check.variant, condition: check.condition,
68
+ flow: scenario.flow, variant: scenario.variant, condition: scenario.condition,
72
69
  get overlay() { return overlay; },
73
70
  get pending() { return pending > 0; },
74
71
  open(id) { overlay = String(id); },
@@ -79,41 +76,123 @@ const HARNESS = `(() => {
79
76
  cancelWork() { pending = 0; },
80
77
  focus() {},
81
78
  };
79
+ };
80
+ // The page's DOM, which a view may read there and this check does not have: while view runs,
81
+ // reading one throws this marker, and that draw goes unjudged rather than refused.
82
+ const DOM = Object.freeze({ dom: true });
83
+ const DOM_NAMES = ['document', 'matchMedia', 'getComputedStyle', 'innerWidth', 'innerHeight', 'navigator', 'location'];
84
+ const view = (definition, model, ctx) => {
85
+ const own = DOM_NAMES.filter((name) => !Object.prototype.hasOwnProperty.call(globalThis, name));
86
+ for (const name of own) Object.defineProperty(globalThis, name, { configurable: true, get() { throw DOM; } });
87
+ try {
88
+ const drawn = definition.view(model, ctx);
89
+ // Read as render() reads it, so a throw while it turns into markup is the view's too.
90
+ return { markup: drawn && drawn[RAW] !== undefined ? String(drawn[RAW]) : String(drawn ?? '') };
91
+ } catch (error) {
92
+ if (error === DOM) return { dom: true };
93
+ throw error;
94
+ } finally {
95
+ for (const name of own) delete globalThis[name];
96
+ }
97
+ };
98
+ // Elements a template's innerHTML keeps: a whole tag, html, head and body dropped as a fragment drops them.
99
+ const blank = (drawn) => {
100
+ if (drawn.dom) return null;
101
+ const markup = drawn.markup.replace(/<!--[\\s\\S]*?(-->|$)/g, '');
102
+ if (!drawn.markup.trim()) return 'view returned no markup';
103
+ for (const tag of markup.matchAll(/<([a-zA-Z][^\\s/>]*)(?:[\\s/][^>]*)?>/g))
104
+ if (!['html', 'head', 'body'].includes(tag[1].toLowerCase())) return null;
105
+ return 'view returned markup with no element in it';
106
+ };
107
+ const definitions = [];
108
+ const first = JSON.parse(globalThis.__kosukeStepFirst);
109
+ const drawn = {};
110
+ Object.defineProperty(globalThis, '__kosukeStepCheck', { configurable: true, value: Object.freeze({ definitions, context, message, view, blank, drawn }) });
111
+ globalThis.definePrototype = (definition) => {
112
+ definitions.push(definition);
113
+ if (definitions.length > 1) return;
114
+ drawn.started = true;
115
+ const ctx = context(first);
116
+ drawn.blank = blank(view(definition, definition.seed(ctx), ctx));
117
+ drawn.done = true;
118
+ };
119
+ globalThis.console = { log() {}, info() {}, warn() {}, error() {}, debug() {} };
120
+ globalThis.window = globalThis;
121
+ globalThis.self = globalThis;
122
+ })();`;
123
+ // Runs inside the context, so the time limit covers the content's own calls too. Each state is
124
+ // shown as showState shows it: a fresh seed drawn by reset(), its show entry, then a draw.
125
+ const HARNESS = `(() => {
126
+ const checks = JSON.parse(globalThis.__kosukeStepChecks);
127
+ const { definitions, context, message, view, blank } = globalThis.__kosukeStepCheck;
128
+ const definition = definitions[0];
129
+ if (definitions.length === 0) return JSON.stringify({ load: 'content.js never calls definePrototype' });
130
+ if (definitions.length > 1) return JSON.stringify({ load: 'content.js calls definePrototype more than once' });
131
+ return JSON.stringify({ results: checks.map((check) => {
132
+ const ctx = context(check);
82
133
  let model;
83
134
  try { model = definition.seed(ctx); } catch (error) { return { error: 'seed threw: ' + message(error) }; }
84
135
  const show = definition.show && definition.show[check.id];
85
136
  if (typeof show === 'function') {
137
+ try { view(definition, model, ctx); }
138
+ catch (error) { return { show: true, error: 'view threw on its fresh seed, before its show entry ran: ' + message(error) }; }
86
139
  try { const next = show(model, ctx); if (next && typeof next === 'object') model = next; }
87
140
  catch (error) { return { show: true, error: 'its show threw: ' + message(error) }; }
88
141
  }
89
- try { return { show: typeof show === 'function', reported: String(definition.state(model, ctx)) }; }
90
- catch (error) { return { show: typeof show === 'function', error: 'state() threw: ' + message(error) }; }
142
+ const result = { show: typeof show === 'function' };
143
+ try { result.reported = String(definition.state(model, ctx)); }
144
+ catch (error) { result.error = 'state() threw: ' + message(error); }
145
+ try { result.view = blank(view(definition, model, ctx)); }
146
+ catch (error) { result.view = 'view threw: ' + message(error); }
147
+ return result;
91
148
  }) });
92
149
  })()`;
93
- // The child: reads the checks and the script on stdin, answers JSON on stdout. Browser globals a
94
- // page has come from the child's realm, which holds nothing worth reaching.
150
+ // The child: reads the pages and the script on stdin, answers JSON on stdout. Each page is a fresh
151
+ // context that loads content.js anew, as each saved page does. Browser globals a page has come
152
+ // from the child's realm, which holds nothing worth reaching.
95
153
  const CHILD = `'use strict';
96
154
  const vm = require('node:vm');
97
- const { checks, script } = JSON.parse(require('node:fs').readFileSync(0, 'utf8'));
155
+ const { pages, script } = JSON.parse(require('node:fs').readFileSync(0, 'utf8'));
98
156
  const browser = ['URL', 'URLSearchParams', 'TextEncoder', 'TextDecoder', 'atob', 'btoa', 'structuredClone', 'crypto', 'performance', 'queueMicrotask', 'AbortController', 'Event', 'EventTarget'];
99
- const context = vm.createContext(Object.fromEntries(browser.filter((name) => name in globalThis).map((name) => [name, globalThis[name]])));
100
- context.__checks = JSON.stringify(checks);
101
- let output;
102
- try {
103
- vm.runInContext(${JSON.stringify(PRELUDE)}, context, { timeout: ${TIME_LIMIT_MS}, filename: 'step-check' });
104
- vm.runInContext(script, context, { timeout: ${TIME_LIMIT_MS}, filename: 'content.js' });
105
- output = vm.runInContext(${JSON.stringify(HARNESS)}, context, { timeout: ${TIME_LIMIT_MS}, filename: 'step-check' });
106
- } catch (error) {
107
- let text;
108
- try { text = String(error && error.message !== undefined ? error.message : error); } catch { text = 'it threw'; }
109
- output = JSON.stringify({ load: 'content.js could not run for the step check: ' + text.slice(0, 300) });
157
+ const text = (error) => {
158
+ try { return String(error && error.message !== undefined ? error.message : error).slice(0, 300); } catch { return 'it threw'; }
159
+ };
160
+ const timedOut = (error) => error && error.code === 'ERR_SCRIPT_EXECUTION_TIMEOUT';
161
+ const run = (code, context, filename) => vm.runInContext(code, context, { timeout: ${TIME_LIMIT_MS}, filename });
162
+ function check({ first, checks }) {
163
+ const context = vm.createContext(Object.fromEntries(browser.filter((name) => name in globalThis).map((name) => [name, globalThis[name]])));
164
+ context.__kosukeStepChecks = JSON.stringify(checks);
165
+ context.__kosukeStepFirst = JSON.stringify(first);
166
+ try {
167
+ run(${JSON.stringify(PRELUDE)}, context, 'step-check');
168
+ const step = context.__kosukeStepCheck;
169
+ let thrown = null;
170
+ try {
171
+ run(script, context, 'content.js');
172
+ } catch (error) {
173
+ if (timedOut(error)) throw error;
174
+ const at = 'flow "' + first.label + '"' + (first.variant ? ', Variant ' + first.variant : '');
175
+ let uninitialised = false;
176
+ try { uninitialised = Boolean(error) && error.name === 'ReferenceError'; } catch {}
177
+ thrown = step.drawn.started && !step.drawn.done
178
+ ? 'content.js stopped in definePrototype, whose first draw (' + at + ') threw: ' + text(error) +
179
+ (uninitialised ? '; definePrototype draws at once, so declare every const or let its view reaches above the call' : '')
180
+ : 'content.js threw while it loaded: ' + text(error);
181
+ }
182
+ if (thrown && step.definitions.length === 0) return { load: thrown };
183
+ const checked = JSON.parse(run(${JSON.stringify(HARNESS)}, context, 'step-check'));
184
+ return { ...checked, thrown, firstBlank: step.drawn.blank || null };
185
+ } catch (error) {
186
+ return { load: 'content.js could not run for the step check: ' + text(error) };
187
+ }
110
188
  }
111
- process.stdout.write(String(output));`;
189
+ process.stdout.write(JSON.stringify(pages.map(check)));`;
112
190
  /**
113
- * The issues of one prototype's script, empty when every state shows as declared.
191
+ * The issues of one prototype's script, empty when every state shows and draws as declared.
192
+ * `per-variant` saves a page per Variant, each loading the script in its own Variant.
114
193
  * @internal
115
194
  */
116
- export function prototypeStepIssues(configText, script) {
195
+ export function prototypeStepIssues(configText, script, mode = 'one') {
117
196
  let config;
118
197
  try {
119
198
  config = record(JSON.parse(configText));
@@ -124,8 +203,15 @@ export function prototypeStepIssues(configText, script) {
124
203
  const checks = checksOf(config);
125
204
  if (checks.length === 0)
126
205
  return [];
206
+ const pages = pagesOf(config, checks, mode);
127
207
  const child = spawnSync(process.execPath, ['--permission', '--max-old-space-size=256', '-e', CHILD], {
128
- input: JSON.stringify({ checks, script }),
208
+ input: JSON.stringify({
209
+ pages: pages.map((page) => ({
210
+ first: page.first,
211
+ checks: page.checks.map((index) => checks[index]),
212
+ })),
213
+ script,
214
+ }),
129
215
  env: {},
130
216
  encoding: 'utf8',
131
217
  timeout: DEADLINE_MS,
@@ -150,39 +236,105 @@ export function prototypeStepIssues(configText, script) {
150
236
  .find((line) => /Error|error/.test(line));
151
237
  return [`content.js crashed the step check${reason ? `: ${reason.trim().slice(0, 300)}` : ''}`];
152
238
  }
153
- if (output.load)
154
- return [output.load];
155
- const issues = [];
156
- (output.results ?? []).forEach((result, index) => {
157
- const check = checks[index];
158
- if (!check)
239
+ const issues = new Set();
240
+ output.forEach((page, at) => {
241
+ const own = pages[at];
242
+ if (!own)
159
243
  return;
160
- const where = (check.step ? `step "${check.id}"` : `condition state "${check.id}" (${check.condition})`) +
161
- ` of flow "${check.flowLabel}"` +
162
- (declaredVariants(config) > 1 ? `, Variant ${check.variant}` : '');
163
- if (result.error)
164
- issues.push(`${where}: ${result.error}`);
165
- else if (result.reported !== check.id)
166
- issues.push(result.show
167
- ? `${where}: after its show entry, state() reports "${result.reported}"`
168
- : `${where}: it has no show entry, and from a fresh seed state() reports "${result.reported}"; add show["${check.id}"]`);
244
+ if (page.load)
245
+ return issues.add(page.load);
246
+ if (page.thrown)
247
+ issues.add(page.thrown);
248
+ const blankStart = (page.results ?? []).some((result, index) => {
249
+ const check = checks[own.checks[index] ?? -1];
250
+ return result.view && !result.show && check && sameScenario(check, own.first);
251
+ });
252
+ if (page.firstBlank && !blankStart)
253
+ issues.add(`the page opens blank: the first draw, inside definePrototype (flow "${own.first.label}", Variant ${own.first.variant}), ${page.firstBlank}`);
254
+ (page.results ?? []).forEach((result, index) => {
255
+ const check = checks[own.checks[index] ?? -1];
256
+ if (check)
257
+ for (const issue of checkIssues(config, check, result))
258
+ issues.add(issue);
259
+ });
169
260
  });
261
+ return [...issues];
262
+ }
263
+ /** What one state's result says is wrong, named by its step or condition and Variant. */
264
+ function checkIssues(config, check, result) {
265
+ const issues = [];
266
+ const where = (check.step ? `step "${check.id}"` : `condition state "${check.id}" (${check.condition})`) +
267
+ ` of flow "${check.flowLabel}"` +
268
+ (declaredVariants(config) > 1 ? `, Variant ${check.variant}` : '');
269
+ if (result.error)
270
+ issues.push(`${where}: ${result.error}`);
271
+ else if (result.reported !== check.id)
272
+ issues.push(result.show
273
+ ? `${where}: after its show entry, state() reports "${result.reported}"`
274
+ : `${where}: it has no show entry, and from a fresh seed state() reports "${result.reported}"; add show["${check.id}"]`);
275
+ // A blank canvas is named by its Variant even when the file declares one.
276
+ if (result.view)
277
+ issues.push(`${where}${declaredVariants(config) > 1 ? '' : `, Variant ${check.variant}`}: ${result.view}`);
170
278
  return issues;
171
279
  }
280
+ const sameScenario = (check, first) => check.flow === first.flow &&
281
+ check.variant === first.variant &&
282
+ check.condition === first.condition;
283
+ const variantIds = (config) => Array.isArray(config.variants)
284
+ ? config.variants
285
+ .map((variant) => record(variant).id)
286
+ .filter((id) => typeof id === 'string')
287
+ : ['a'];
288
+ const flowVariants = (config, flow) => flow.variants === undefined ? variantIds(config) : strings(flow.variants);
289
+ /**
290
+ * The pages a save makes: one with every state, or, per Variant, one whose flows each show that
291
+ * Variant (else their first), as the shell's `variantsOf` picks with `fileVariant` set.
292
+ */
293
+ function pagesOf(config, checks, mode) {
294
+ const all = checks.map((_, index) => index);
295
+ if (mode !== 'per-variant')
296
+ return [{ first: openingScenario(config), checks: all }];
297
+ const flows = Array.isArray(config.flows) ? config.flows.map(record) : [];
298
+ return variantIds(config).map((fileVariant) => {
299
+ const shown = (flow) => {
300
+ const own = flow ? flowVariants(config, flow) : [];
301
+ return own.includes(fileVariant) ? fileVariant : own[0];
302
+ };
303
+ return {
304
+ first: openingScenario(config, fileVariant),
305
+ checks: all.filter((index) => {
306
+ const check = checks[index];
307
+ return check && check.variant === shown(flows.find((flow) => flow.id === check.flow));
308
+ }),
309
+ };
310
+ });
311
+ }
312
+ /** The flow, Variant and condition a page opens on, where definePrototype draws first. */
313
+ function openingScenario(config, fileVariant) {
314
+ const flow = Array.isArray(config.flows) ? record(config.flows[0]) : {};
315
+ const variants = flowVariants(config, flow);
316
+ const variant = fileVariant && variants.includes(fileVariant) ? fileVariant : variants[0];
317
+ return {
318
+ flow: typeof flow.id === 'string' ? flow.id : '',
319
+ label: typeof flow.label === 'string' ? flow.label : String(flow.id ?? ''),
320
+ variant: variant ?? '',
321
+ condition: strings(flow.conditions)[0] ?? '',
322
+ };
323
+ }
172
324
  const declaredVariants = (config) => Array.isArray(config.variants) ? config.variants.length : 1;
173
325
  /**
174
326
  * The check on the files a `prototypes create` call attaches, told apart by extension as the
175
327
  * platform tells them; null when they are not one .json and one .js the CLI can read, which the
176
328
  * platform then refuses on its own terms.
177
329
  */
178
- function attachedPrototypeIssues(paths) {
330
+ function attachedPrototypeIssues(paths, mode) {
179
331
  const json = paths.filter((path) => extname(path).toLowerCase() === '.json');
180
332
  const js = paths.filter((path) => extname(path).toLowerCase() === '.js');
181
333
  const [config, script] = [json[0], js[0]];
182
334
  if (json.length !== 1 || js.length !== 1 || !config || !script)
183
335
  return null;
184
336
  try {
185
- return prototypeStepIssues(readFileSync(config, 'utf8'), readFileSync(script, 'utf8'));
337
+ return prototypeStepIssues(readFileSync(config, 'utf8'), readFileSync(script, 'utf8'), mode);
186
338
  }
187
339
  catch {
188
340
  return null;
@@ -193,7 +345,7 @@ function attachedPrototypeIssues(paths) {
193
345
  * so a caller reads either the same way; null when the step check finds nothing.
194
346
  */
195
347
  function prototypeRefusal(input) {
196
- const issues = attachedPrototypeIssues(input.attachments);
348
+ const issues = attachedPrototypeIssues(input.attachments, input.fields.variants === 'per-variant' ? 'per-variant' : 'one');
197
349
  if (!issues?.length)
198
350
  return null;
199
351
  return {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kosuke-ai/kosuke",
3
- "version": "1.0.155",
3
+ "version": "1.0.156",
4
4
  "description": "Sensei platform CLI. The client customers install to drive app.kosuke.ai from their own machine.",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -43,10 +43,10 @@
43
43
  "minimatch": "^11.0.1"
44
44
  },
45
45
  "kosukeRelease": {
46
- "sourceCommit": "349a40b676f4e30172da5f6e12ee8eb6f4fa24cf",
47
- "sourceIdentity": "a995a8de1824ecad26526fda865872c1ee11ff76b9d77b9bc70eccbdf1b0df6b",
46
+ "sourceCommit": "d8c15a3efd50c7a130803c6aac1ae9765fe5a894",
47
+ "sourceIdentity": "b073e8e911c1e6c3915c70a4d0cd13b3d5155d46183d8684fab92727cd219334",
48
48
  "fragments": [
49
- "bedrock-region-check-s0994w.json"
49
+ "prototype-view-check-71yv0g.json"
50
50
  ]
51
51
  }
52
52
  }