@descix/frqtl-web 0.6.0-p4.1 → 0.6.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 (69) hide show
  1. package/CLAUDE.md +15 -11
  2. package/README.md +26 -6
  3. package/dist/artifact/double-slit.html +2 -2
  4. package/dist/dist-manifest.json +61 -60
  5. package/dist/experiments/empty/index.html +22 -7
  6. package/dist/frqtl/compat/providers/wasm-engine.js +3 -4
  7. package/dist/frqtl/compat/renderer/providers/p5-provider.js +1 -1
  8. package/dist/frqtl/objects/FrqtlApp.js +5 -5
  9. package/dist/frqtl/objects/RecipeContext.js +106 -1
  10. package/dist/frqtl/objects/constants/WallBehaviors.js +1 -1
  11. package/dist/frqtl/objects/instruments/capture.js +1 -24
  12. package/dist/frqtl/objects/instruments/hosted-eyes.js +17 -1
  13. package/dist/frqtl/objects/objects/makeControlsForObject.js +5 -5
  14. package/dist/frqtl/objects/record/Record.js +25 -5
  15. package/dist/frqtl/objects/schema/engine-scopes.js +2 -2
  16. package/dist/frqtl/objects/schema/scopes.js +2 -2
  17. package/dist/frqtl/objects/setup/_worldInit.js +1 -2
  18. package/dist/frqtl/objects/setup/setupBlackbodySubstrate.js +1 -2
  19. package/dist/frqtl/parts/CameraControls.js +8 -0
  20. package/dist/frqtl/parts/DetectorWall.js +1 -1
  21. package/dist/frqtl/parts/GraphingDetectorWall.js +7 -7
  22. package/dist/frqtl/parts/LargeObject.js +2 -2
  23. package/dist/frqtl/parts/LiveChart.js +2 -2
  24. package/dist/frqtl/parts/LogicGate.js +3 -3
  25. package/dist/frqtl/parts/OvenBox.js +1 -1
  26. package/dist/frqtl/parts/PointSource.js +1 -1
  27. package/dist/frqtl/parts/SlitLightSource.js +1 -1
  28. package/dist/frqtl/parts/SlitScreen.js +1 -1
  29. package/dist/frqtl/parts/SphereEmitter.js +12 -12
  30. package/dist/frqtl/parts/Trace.js +1 -1
  31. package/dist/frqtl/parts/Tunnel.js +11 -11
  32. package/dist/frqtl/parts/Wall.js +20 -10
  33. package/dist/frqtl/scenes/circuit-sat.js +1 -0
  34. package/dist/frqtl/scenes/dse-one-emitter.js +32 -34
  35. package/dist/frqtl/scenes/dse-two-emitters.js +33 -34
  36. package/dist/frqtl/scenes/mirror-route.js +96 -79
  37. package/dist/frqtl-web.min.js +54 -54
  38. package/dist/sdk.html +2 -2
  39. package/dist/shim/bundle/index.js +6 -0
  40. package/dist/shim/controls/index.js +1 -1
  41. package/dist/shim/engine/artifact-shell.js +1 -1
  42. package/dist/shim/engine/router.js +3 -3
  43. package/dist/shim/host/host-view.js +228 -0
  44. package/dist/shim/host/index.js +18 -0
  45. package/dist/shim/index.js +2 -4
  46. package/dist/shim/notebook/kernel.js +1 -1
  47. package/dist/shim/notebook/setup-builder.js +2 -2
  48. package/dist/shim/package.json +1 -0
  49. package/dist/shim/page-params/index.js +2 -30
  50. package/dist/shim/project/fork.js +293 -0
  51. package/dist/shim/project/identity.js +3 -1
  52. package/dist/shim/project/link.js +43 -3
  53. package/dist/shim/project/parts-writer.js +62 -5
  54. package/dist/shim/project/read-text.js +43 -0
  55. package/dist/shim/project/specifiers.js +104 -15
  56. package/dist/shim/registry/exhibits.js +15 -34
  57. package/dist/shim/registry/index.js +2 -2
  58. package/dist/shim/registry/scene-roster.js +35 -0
  59. package/dist/shim/registry/scene-source.js +6 -36
  60. package/dist/shim/registry/walkthrough.js +2 -3
  61. package/dist/shim/render-state/apply.js +66 -31
  62. package/dist/shim/render-state/index.js +6 -2
  63. package/dist/shim/runtime/index.js +4 -4
  64. package/llms.txt +9 -7
  65. package/package.json +20 -2
  66. package/dist/frqtl/experiments/_shared/fx-experiment.js +0 -449
  67. package/dist/js/models/flamingo-draco.glb +0 -0
  68. package/dist/js/models/flamingo.glb +0 -0
  69. package/dist/shim/registry/experiments.js +0 -215
@@ -0,0 +1,293 @@
1
+ /* Copyright 2023-2026 by Essam Abadir */
2
+
3
+ /**
4
+ * fork.js — THE fork transform: a part file's text becomes the text of its renamed copy, `parts/<To>.js`.
5
+ *
6
+ * forkPartText(text, { from, to, libPath, files }) → { text, imports }
7
+ * text the source part file's exact bytes, as text
8
+ * from the class name the file registers (its kind name)
9
+ * to the new class name (the fork's kind name)
10
+ * libPath where the source lives: a package lib-identity path ('frqtl/parts/Wall.js') or, for a fork of a
11
+ * fork, the project path of the held file ('parts/MyWall.js')
12
+ * files the project's files by path ({} when none) — a fork never overwrites one
13
+ * imports [{ from, to }] — each import specifier of the source and the specifier the copy writes
14
+ *
15
+ * The text is parsed once (parts-writer.js parseModule: the vendored acorn's one importer). The copy differs from the source
16
+ * in exactly three kinds of range, and every other byte (comments, docstrings, the schema, every string) is the
17
+ * source's byte:
18
+ * 1. THE CLASS BINDING. `to` replaces the module-scope binding `from`: its declaration's id and every reference
19
+ * that resolves to it (`registerKind(Wall, …)`, `Wall.prototype…`, `instanceof Wall`, `export { Wall }`). A
20
+ * same-named binding in an inner scope, a property key and a string are untouched.
21
+ * 2. THE PALETTE NAME. The registerKind row's `palette.displayName` string becomes `to`, so a palette lists the
22
+ * fork by its own name. Every other property of the row is the source's byte.
23
+ * 3. THE IMPORTS. A package part's relative import is rewritten to the package specifier naming the SAME file
24
+ * (specifiers.js specifierOfLibPath — a part file under frqtl/parts/ → the parts prefix row; frqtl/objects/
25
+ * kinds.js → @descix/frqtl-web/kinds when every imported name is in KINDS_EXPORTS; anything else its own
26
+ * row). A fork of a fork keeps its relative imports (they name project files beside it) and its package
27
+ * specifiers as they are. A fork never copies a non-part module: a second copy of a registry or a schema
28
+ * would split one fact.
29
+ *
30
+ * REFUSED (throws, naming the part): `to` is not an identifier or is a reserved word; `to` equals `from`; `to` is
31
+ * already a registered kind, or `parts/<to>.js` is already a project file; `from` is a kind FORK_REFUSED names
32
+ * (with its reason); the file declares no module-scope `from`; a relative import with no row (naming the import).
33
+ *
34
+ * FORK_REFUSED { <kind>: reason } — the kinds no fork copies, each with the census reason (fork.test.mjs
35
+ * G-CENSUS derives the set from the part files and holds it equal to this table)
36
+ */
37
+
38
+ import { kindOf } from '../../frqtl/objects/kinds.js';
39
+ import { KINDS_EXPORTS } from '../../frqtl/objects/kinds-entry.js';
40
+ import { specifierOfLibPath } from './specifiers.js';
41
+ import { isIdentifierName, parseModule } from './parts-writer.js';
42
+
43
+ /** The kinds a fork refuses, each with why (the census: a scope row, or the class name used as a string). */
44
+ export const FORK_REFUSED = Object.freeze({
45
+ LargeObject: 'LargeObject is a scope row (schema/scopes.js SCOPE_DESCRIPTORS) and passes \'LargeObject\' as the engine ' +
46
+ 'scope name to universe.updateObjectProperty — a copy would be a second scope row',
47
+ PointSource: 'PointSource numbers its default name with declaredCount(ctx.runner, \'PointSource\') — a copy would ' +
48
+ 'number itself in its parent\'s sequence (the class name used as a string)'
49
+ });
50
+
51
+ /** The lib-identity path of the parts directory, and the kinds registry a part imports. */
52
+ const PARTS_DIR = 'frqtl/parts/';
53
+ const KINDS_LIB = 'frqtl/objects/kinds.js';
54
+
55
+ function _fail(msg) {
56
+ throw new Error('[fork] ' + msg + ' (FAIL-LOUD.)');
57
+ }
58
+
59
+ /** The children of an AST node (every key holding a node or an array of nodes). */
60
+ function _children(n) {
61
+ const out = [];
62
+ for (const k of Object.keys(n)) {
63
+ if (k === 'type' || k === 'start' || k === 'end' || k === 'loc' || k === 'range') { continue; }
64
+ const v = n[k];
65
+ if (Array.isArray(v)) { for (const c of v) { if (c && typeof c.type === 'string') { out.push(c); } } }
66
+ else if (v && typeof v.type === 'string') { out.push(v); }
67
+ }
68
+ return out;
69
+ }
70
+
71
+ function _patternNames(p, out) {
72
+ if (!p) { return out; }
73
+ if (p.type === 'Identifier') { out.push(p.name); }
74
+ else if (p.type === 'ObjectPattern') { for (const q of p.properties) { _patternNames(q.type === 'RestElement' ? q.argument : q.value, out); } }
75
+ else if (p.type === 'ArrayPattern') { for (const e of p.elements) { _patternNames(e, out); } }
76
+ else if (p.type === 'RestElement') { _patternNames(p.argument, out); }
77
+ else if (p.type === 'AssignmentPattern') { _patternNames(p.left, out); }
78
+ return out;
79
+ }
80
+
81
+ const _FUNCTION = { FunctionDeclaration: 1, FunctionExpression: 1, ArrowFunctionExpression: 1 };
82
+
83
+ /** `var` names declared in a function body (not crossing a nested function). */
84
+ function _varNames(n, out) {
85
+ for (const c of _children(n)) {
86
+ if (_FUNCTION[c.type]) { continue; }
87
+ if (c.type === 'VariableDeclaration' && c.kind === 'var') {
88
+ for (const d of c.declarations) { _patternNames(d.id, out); }
89
+ }
90
+ _varNames(c, out);
91
+ }
92
+ return out;
93
+ }
94
+
95
+ /** Block-scoped names declared directly in a statement list (let/const/class/function). */
96
+ function _lexicalNames(body, out) {
97
+ for (const s of body) {
98
+ const d = (s.type === 'ExportNamedDeclaration' || s.type === 'ExportDefaultDeclaration') ? s.declaration : s;
99
+ if (!d) { continue; }
100
+ if (d.type === 'VariableDeclaration' && d.kind !== 'var') { for (const x of d.declarations) { _patternNames(x.id, out); } }
101
+ else if ((d.type === 'ClassDeclaration' || d.type === 'FunctionDeclaration') && d.id) { out.push(d.id.name); }
102
+ }
103
+ return out;
104
+ }
105
+
106
+ /** The names a node introduces into the scope it opens (null when it opens none). */
107
+ function _scopeNames(n, isModule) {
108
+ if (_FUNCTION[n.type]) {
109
+ const names = [];
110
+ for (const p of n.params) { _patternNames(p, names); }
111
+ if (n.type === 'FunctionExpression' && n.id) { names.push(n.id.name); }
112
+ if (n.body.type === 'BlockStatement') { _varNames(n.body, names); _lexicalNames(n.body.body, names); }
113
+ return names;
114
+ }
115
+ if (n.type === 'BlockStatement' || n.type === 'StaticBlock') { return isModule ? null : _lexicalNames(n.body, []); }
116
+ if (n.type === 'SwitchStatement') { return _lexicalNames(n.cases.flatMap(function (c) { return c.consequent; }), []); }
117
+ if (n.type === 'ForStatement' || n.type === 'ForInStatement' || n.type === 'ForOfStatement') {
118
+ const init = n.type === 'ForStatement' ? n.init : n.left;
119
+ if (!init || init.type !== 'VariableDeclaration' || init.kind === 'var') { return []; }
120
+ return init.declarations.reduce(function (acc, d) { return _patternNames(d.id, acc); }, []);
121
+ }
122
+ if (n.type === 'CatchClause') { return n.param ? _patternNames(n.param, []) : []; }
123
+ if (n.type === 'ClassExpression' && n.id) { return [n.id.name]; }
124
+ return null;
125
+ }
126
+
127
+ /**
128
+ * Every Identifier node that resolves to the MODULE-scope binding `name` (declarations and references).
129
+ * Positions that are not references (non-computed property keys and member properties, labels, an import's
130
+ * imported name, an export's exported name when it differs from the local) are skipped.
131
+ */
132
+ function _moduleBindingIds(ast, name) {
133
+ const hits = [];
134
+ function visit(n, shadowed, parent, key) {
135
+ if (n.type === 'Identifier') {
136
+ if (n.name !== name || shadowed) { return; }
137
+ if (parent) {
138
+ if (parent.type === 'MemberExpression' && key === 'property' && !parent.computed) { return; }
139
+ if ((parent.type === 'Property' || parent.type === 'MethodDefinition' || parent.type === 'PropertyDefinition') &&
140
+ key === 'key' && !parent.computed && !parent.shorthand) { return; }
141
+ if ((parent.type === 'LabeledStatement' || parent.type === 'BreakStatement' || parent.type === 'ContinueStatement') && key === 'label') { return; }
142
+ // An import's imported name and an export's exported name are names, not references: the local
143
+ // is the binding (acorn hands the SAME node to both keys of a shorthand specifier).
144
+ if (parent.type === 'ImportSpecifier' && key === 'imported') { return; }
145
+ if (parent.type === 'ExportSpecifier' && key === 'exported') { return; }
146
+ }
147
+ hits.push(n);
148
+ return;
149
+ }
150
+ const names = n === ast ? null : _scopeNames(n, false);
151
+ const sh = shadowed || !!(names && names.indexOf(name) !== -1);
152
+ for (const k of Object.keys(n)) {
153
+ if (k === 'type' || k === 'start' || k === 'end' || k === 'loc') { continue; }
154
+ const v = n[k];
155
+ if (Array.isArray(v)) { for (const c of v) { if (c && typeof c.type === 'string') { visit(c, _childShadow(n, k, c, sh, shadowed), n, k); } } }
156
+ else if (v && typeof v.type === 'string') { visit(v, _childShadow(n, k, v, sh, shadowed), n, k); }
157
+ }
158
+ }
159
+ // A function DECLARATION's id belongs to the enclosing scope, not the one the function opens.
160
+ function _childShadow(n, k, c, sh, outer) {
161
+ if (n.type === 'FunctionDeclaration' && k === 'id') { return outer; }
162
+ return sh;
163
+ }
164
+ visit(ast, false, null, null);
165
+ return hits;
166
+ }
167
+
168
+ /** The module-top binding of `name`: its declaration node, or null. */
169
+ function _topDeclaration(ast, name) {
170
+ for (const s of ast.body) {
171
+ const d = (s.type === 'ExportNamedDeclaration' || s.type === 'ExportDefaultDeclaration') ? s.declaration : s;
172
+ if (!d) { continue; }
173
+ if ((d.type === 'ClassDeclaration' || d.type === 'FunctionDeclaration') && d.id && d.id.name === name) { return d; }
174
+ if (d.type === 'VariableDeclaration' && d.declarations.some(function (x) { return _patternNames(x.id, []).indexOf(name) !== -1; })) { return d; }
175
+ }
176
+ return null;
177
+ }
178
+
179
+ /** The `palette.displayName` string Literal of the module's `registerKind(<from>, { … })` row, or null. */
180
+ function _paletteName(ast, from) {
181
+ let found = null;
182
+ (function visit(n) {
183
+ if (found) { return; }
184
+ if (n.type === 'CallExpression' && n.callee.type === 'Identifier' && n.callee.name === 'registerKind' &&
185
+ n.arguments[0] && n.arguments[0].type === 'Identifier' && n.arguments[0].name === from &&
186
+ n.arguments[1] && n.arguments[1].type === 'ObjectExpression') {
187
+ const pal = n.arguments[1].properties.find(function (p) { return p.type === 'Property' && !p.computed && p.key.name === 'palette'; });
188
+ if (pal && pal.value.type === 'ObjectExpression') {
189
+ const dn = pal.value.properties.find(function (p) { return p.type === 'Property' && !p.computed && p.key.name === 'displayName'; });
190
+ if (dn && dn.value.type === 'Literal' && typeof dn.value.value === 'string') { found = dn.value; }
191
+ }
192
+ return;
193
+ }
194
+ for (const c of _children(n)) { visit(c); }
195
+ })(ast);
196
+ return found;
197
+ }
198
+
199
+ /** The lib-identity (or project) path a relative specifier names from `fromPath`. */
200
+ function _resolve(fromPath, spec) {
201
+ const segs = fromPath.split('/');
202
+ segs.pop();
203
+ for (const s of spec.split('/')) {
204
+ if (s === '.' || s === '') { continue; }
205
+ if (s === '..') { segs.pop(); } else { segs.push(s); }
206
+ }
207
+ return segs.join('/');
208
+ }
209
+
210
+ function _quoteLike(original, value) {
211
+ const q = original[0] === '"' ? '"' : '\'';
212
+ return q + value.replace(/\\/g, '\\\\').split(q).join('\\' + q) + q;
213
+ }
214
+
215
+ /**
216
+ * @param {string} text — the source part file
217
+ * @param {{from: string, to: string, libPath: string, files: Object<string, string>}} opts
218
+ * @returns {{text: string, imports: Array<{from: string, to: string}>}}
219
+ */
220
+ export function forkPartText(text, opts) {
221
+ if (typeof text !== 'string' || !text) { _fail('forkPartText(text, opts): text is the part file (got ' + typeof text + ').'); }
222
+ const o = opts || {};
223
+ const from = o.from, to = o.to, libPath = o.libPath, files = o.files;
224
+ if (typeof from !== 'string' || !from) { _fail('forkPartText: `from` is the class name the part registers.'); }
225
+ if (typeof libPath !== 'string' || !libPath) { _fail('forkPartText(' + from + '): `libPath` names the source file.'); }
226
+ if (!files || typeof files !== 'object') { _fail('forkPartText(' + from + '): `files` is the project\'s file map ({} when none).'); }
227
+ if (typeof to !== 'string' || !isIdentifierName(to)) {
228
+ _fail('forkPartText(' + from + '): the new class name ' + JSON.stringify(to) + ' is not an identifier (or is a reserved word) ' +
229
+ '— the class name IS the kind name.');
230
+ }
231
+ if (to === from) { _fail('forkPartText(' + from + '): the new class name equals the part\'s own — a fork is a NEW kind; name it.'); }
232
+ if (kindOf(to)) {
233
+ _fail('forkPartText(' + from + '): "' + to + '" is already a registered kind (' + kindOf(to).from + ') — one name has one owner; ' +
234
+ 'choose another name.');
235
+ }
236
+ const target = 'parts/' + to + '.js';
237
+ if (Object.prototype.hasOwnProperty.call(files, target)) {
238
+ _fail('forkPartText(' + from + '): ' + target + ' is already a project file — a fork never overwrites one.');
239
+ }
240
+ if (Object.prototype.hasOwnProperty.call(FORK_REFUSED, from)) {
241
+ _fail('forkPartText(' + from + '): ' + from + ' is not forkable — ' + FORK_REFUSED[from] + '.');
242
+ }
243
+ const pkg = libPath.indexOf(PARTS_DIR) === 0;
244
+ let ast;
245
+ try { ast = parseModule(text); }
246
+ catch (err) { _fail('forkPartText(' + from + '): ' + libPath + ' does not parse (' + err.message + ').'); }
247
+ if (!_topDeclaration(ast, from)) {
248
+ _fail('forkPartText(' + from + '): ' + libPath + ' declares no module-scope ' + from + ' — the file a kind\'s `from` names declares its class.');
249
+ }
250
+
251
+ const patches = [];
252
+ const imports = [];
253
+ for (const s of ast.body) {
254
+ const src = (s.type === 'ImportDeclaration' || ((s.type === 'ExportNamedDeclaration' || s.type === 'ExportAllDeclaration') && s.source))
255
+ ? s.source : null;
256
+ if (!src) { continue; }
257
+ const spec = src.value;
258
+ if (!(spec.startsWith('./') || spec.startsWith('../'))) { imports.push({ from: spec, to: spec }); continue; }
259
+ if (!pkg) { imports.push({ from: spec, to: spec }); continue; } // a fork of a fork: project files beside it
260
+ const lp = _resolve(libPath, spec);
261
+ let out;
262
+ if (lp === KINDS_LIB) {
263
+ const names = (s.specifiers || []).map(function (x) {
264
+ return x.type === 'ImportSpecifier' ? (x.imported.name || x.imported.value) : '*';
265
+ });
266
+ const outside = names.filter(function (n) { return KINDS_EXPORTS.indexOf(n) === -1; });
267
+ if (outside.length) {
268
+ _fail('forkPartText(' + from + '): ' + libPath + ' imports ' + outside.join(', ') + ' from "' + spec + '" — the kinds ' +
269
+ 'door (@descix/frqtl-web/kinds) publishes ' + KINDS_EXPORTS.join(', ') + ' only.');
270
+ }
271
+ out = specifierOfLibPath('frqtl/objects/kinds-entry.js');
272
+ } else {
273
+ out = specifierOfLibPath(lp);
274
+ }
275
+ if (!out) {
276
+ _fail('forkPartText(' + from + '): ' + libPath + ' imports "' + spec + '" (' + lp + '), which no specifier row names — a ' +
277
+ 'fork imports every non-part module from the package (lib/shim/project/specifiers.js); it never copies one.');
278
+ }
279
+ patches.push({ start: src.start, end: src.end, text: _quoteLike(text.slice(src.start, src.end), out) });
280
+ imports.push({ from: spec, to: out });
281
+ }
282
+ for (const id of _moduleBindingIds(ast, from)) { patches.push({ start: id.start, end: id.end, text: to }); }
283
+ const dn = _paletteName(ast, from);
284
+ if (dn) { patches.push({ start: dn.start, end: dn.end, text: _quoteLike(text.slice(dn.start, dn.end), to) }); }
285
+
286
+ patches.sort(function (a, b) { return b.start - a.start; });
287
+ for (let i = 1; i < patches.length; i++) {
288
+ if (patches[i].end > patches[i - 1].start) { _fail('forkPartText(' + from + '): overlapping rewrites — a bug in the transform.'); }
289
+ }
290
+ let out = text;
291
+ for (const p of patches) { out = out.slice(0, p.start) + p.text + out.slice(p.end); }
292
+ return { text: out, imports: imports };
293
+ }
@@ -103,7 +103,9 @@ export async function projectIdentity(project) {
103
103
  for (const c of chunks) { stream.set(c, at); at += c.length; }
104
104
  const subtle = (typeof crypto !== 'undefined') ? crypto.subtle : null;
105
105
  if (!subtle || typeof subtle.digest !== 'function') {
106
- _fail('crypto.subtle.digest is unavailable — the project identity is a content hash with no second hashing path.');
106
+ _fail('crypto.subtle is unavailable — this page is not a secure context (isSecureContext ' + String(typeof isSecureContext === 'undefined' ? undefined : isSecureContext) +
107
+ '): serve the folder from https or from localhost (e.g. npx serve). The project identity is a content hash with no second ' +
108
+ 'hashing path.');
107
109
  }
108
110
  const view = new Uint8Array(await subtle.digest('SHA-256', stream));
109
111
  let hex = '';
@@ -47,11 +47,15 @@
47
47
  * is minted, each naming the file, the specifier and the reason: a relative specifier that climbs out of
48
48
  * the root (package internals have no public specifier), one that names a non-module path (not ".js" /
49
49
  * ".mjs": a data file, an extensionless name, frqtl.json), one that names no project file (never an HTTP
50
- * sibling), a @descix/frqtl-web specifier that is not a row of FRQTL_WEB_SPECIFIERS, any other specifier;
50
+ * sibling), a @descix/frqtl-web specifier that is not a row of FRQTL_WEB_SPECIFIERS, a part-internal row imported
51
+ * by any file but a part file (parts/*.js), any other specifier;
51
52
  * an import cycle among project files; a module file the entry never reaches; an invalid frqtl.json; a
52
53
  * served file that is not UTF-8; a missing or non-function default export of the entry, a missing entry,
53
54
  * an empty project. Every argument error REJECTS.
54
55
  *
56
+ * An error raised while the project EVALUATES (a duplicate kind, a throw at module top) is rethrown with every minted
57
+ * URL in its message named by its project path and every package file URL by its specifier (_namePaths).
58
+ *
55
59
  * blobMint(text) → { url, release() } a `blob:` module URL (a page), one per byte-identical text
56
60
  * dataMint(text) → { url, release() } a `data:` module URL (node)
57
61
  *
@@ -59,7 +63,7 @@
59
63
  * sketchProject(text) is that shape's one writer inside the tree (SKETCH_ENTRY its entry path).
60
64
  */
61
65
 
62
- import { libPathOf, FRQTL_WEB_PACKAGE, FRQTL_WEB_SPECIFIERS } from './specifiers.js';
66
+ import { libPathOf, tierOf, specifierOfLibPath, FRQTL_WEB_PACKAGE, FRQTL_WEB_SPECIFIERS } from './specifiers.js';
63
67
  import { checkProjectPath, projectBytes } from './identity.js';
64
68
  import { MANIFEST_FILE, parseManifest } from './manifest.js';
65
69
  import { packageRoot } from '../../frqtl/compat/package-root.js';
@@ -134,6 +138,14 @@ function _publishedList() {
134
138
  return FRQTL_WEB_SPECIFIERS.map(function (r) { return r.specifier + (r.specifier.endsWith('/') ? '<file>' : ''); }).join(', ');
135
139
  }
136
140
 
141
+ /** The tier a forked part's internals carry (specifiers.js SPECIFIER_TIERS). */
142
+ const PART_INTERNAL = 'part-internal';
143
+
144
+ /** A project file under parts/ (a part file: the only importer of a part-internal module). */
145
+ function _isPartFile(p) {
146
+ return /^parts\/[^/]+\.m?js$/.test(p);
147
+ }
148
+
137
149
  function _isPackage(spec) {
138
150
  return spec === FRQTL_WEB_PACKAGE || spec.startsWith(FRQTL_WEB_PACKAGE + '/');
139
151
  }
@@ -198,6 +210,10 @@ async function _walk(entry, sourceOf) {
198
210
  _fail('"' + p + '" imports "' + imp.spec + '" — not a published specifier; the table ' +
199
211
  '(lib/shim/project/specifiers.js FRQTL_WEB_SPECIFIERS) offers: ' + _publishedList() + '.');
200
212
  }
213
+ if (tierOf(imp.spec) === PART_INTERNAL && !_isPartFile(p)) {
214
+ _fail('"' + p + '" imports "' + imp.spec + '" — a part-internal module is imported by a part file ' +
215
+ '(parts/*.js), never by a sketch — a sketch imports parts by @descix/frqtl-web/parts.');
216
+ }
201
217
  list.push(Object.assign({ kind: 'package' }, imp));
202
218
  } else {
203
219
  _fail('"' + p + '" imports "' + imp.spec + '" — a project file imports another project file by a ' +
@@ -463,7 +479,9 @@ export async function linkProject(project) {
463
479
  minted.push(m);
464
480
  urls[p] = m.url;
465
481
  }
466
- const ns = await import(urls[entry]);
482
+ let ns;
483
+ try { ns = await import(urls[entry]); }
484
+ catch (err) { throw _namePaths(err, urls); }
467
485
  const held = { files: heldFiles, entry: entry, mint: mint };
468
486
  if (project.bare !== undefined) { held.bare = project.bare; }
469
487
  return { buildExperiment: _entryFunction(ns, entry), module: ns, manifest: manifest, files: bytes,
@@ -473,6 +491,28 @@ export async function linkProject(project) {
473
491
  }
474
492
  }
475
493
 
494
+ /**
495
+ * An error raised while the project evaluates, with every minted URL in its message replaced by the project path
496
+ * it names (byte-identical files share one minted URL: all their paths), and every package file URL by its
497
+ * specifier — so a duplicate kind reads "kind "Wall" is already registered by @descix/frqtl-web/parts/Wall.js;
498
+ * parts/Wall2.js registers it again". The SAME error is rethrown (its stack kept): enrichment, never a catch.
499
+ */
500
+ function _namePaths(err, urls) {
501
+ if (!err || typeof err.message !== 'string') { return err; }
502
+ const byUrl = new Map();
503
+ for (const p of Object.keys(urls)) { byUrl.set(urls[p], (byUrl.get(urls[p]) || []).concat(p)); }
504
+ let msg = err.message;
505
+ for (const [url, paths] of [...byUrl.entries()].sort(function (a, b) { return b[0].length - a[0].length; })) {
506
+ msg = msg.split(url).join(paths.join(' (= ') + (paths.length > 1 ? ', byte-identical)' : ''));
507
+ }
508
+ const root = packageRoot();
509
+ msg = msg.replace(new RegExp(root.replace(/[.*+?^${}()|[\]\\]/g, '\\$&') + '([^\\s;,)\'"]+)', 'g'), function (m, lp) {
510
+ return specifierOfLibPath(lp) || m;
511
+ });
512
+ try { err.message = msg; } catch (_) { /* a frozen error keeps its own text */ }
513
+ return err;
514
+ }
515
+
476
516
  /** The entry path of a one-string sketch held as a project. */
477
517
  export const SKETCH_ENTRY = 'sketch.js';
478
518
 
@@ -16,6 +16,10 @@
16
16
  * import line for Kind (after the last import statement;
17
17
  * `module` from parts-module.js moduleOfKind)
18
18
  * | { op: 'remove', name } the entry's property node, its comma included
19
+ * | { op: 'kind', name, Kind, module } within entry `name`, replace ONLY its Kind identifier's text, plus
20
+ * at most one import line for Kind (the add's line, after the last
21
+ * import); the entry's old import line is the author's and stays,
22
+ * even when nothing uses it now (a fork: exp.fork)
19
23
  *
20
24
  * changes[i] = { op, name, key?, from?, to, literalized? } from/to are source TEXT; `literalized: true`
21
25
  * when the old value was an expression (its text is `from`), now its literal value
@@ -29,7 +33,8 @@
29
33
  *
30
34
  * entryKeys(text, name) → string[] the plain prop keys entry `name` spells (how an entry spells a value)
31
35
  * entryLiteral(text, name, key) → { literal, value?, length? } what a key declares when it is a literal
32
- * (read-back); an array expression's element count otherwise
36
+ * (read-back); an array expression's element count otherwise (none when
37
+ * an element is a spread)
33
38
  *
34
39
  * serializeValue(value, key) → text THE one value serializer: numbers, strings (single-quoted),
35
40
  * booleans, null, arrays inline, plain objects. Anything else THROWS
@@ -39,6 +44,14 @@
39
44
  import { parse } from '../../frqtl/assets/vendor/acorn.mjs';
40
45
  import { importSpecifierOf } from './parts-module.js';
41
46
 
47
+ /**
48
+ * parseModule(text) → the acorn syntax tree of an ES module (latest syntax, source ranges) — the vendored parser's
49
+ * ONE entry point in the tree; every other reader of a project file's syntax (fork.js) parses through it.
50
+ */
51
+ export function parseModule(text) {
52
+ return parse(text, { ecmaVersion: 'latest', sourceType: 'module' });
53
+ }
54
+
42
55
  /** The export the writer patches. */
43
56
  export const PARTS_EXPORT = 'parts';
44
57
 
@@ -47,6 +60,14 @@ const _RESERVED = new Set(('break case catch class const continue debugger defau
47
60
  'false finally for function if import in instanceof new null return super switch this throw true try typeof ' +
48
61
  'var void while with yield let static enum await implements package protected interface private public').split(' '));
49
62
 
63
+ /**
64
+ * isIdentifierName(s) → true when `s` can name a binding (an identifier that is not a reserved word) — the one
65
+ * test the writer and the fork transform share.
66
+ */
67
+ export function isIdentifierName(s) {
68
+ return typeof s === 'string' && _IDENT.test(s) && !_RESERVED.has(s);
69
+ }
70
+
50
71
  function _keyText(k) {
51
72
  return (_IDENT.test(k) && !_RESERVED.has(k)) ? k : _quote(k);
52
73
  }
@@ -230,7 +251,7 @@ export function patchParts(text, edits, opts) {
230
251
  throw new TypeError('[parts-writer] patchParts(text, edits): text is the sketch file (got ' + typeof text + '). (FAIL-LOUD.)');
231
252
  }
232
253
  if (!Array.isArray(edits)) {
233
- throw new TypeError('[parts-writer] patchParts(text, edits): edits is an array of { op: set | add | remove }. (FAIL-LOUD.)');
254
+ throw new TypeError('[parts-writer] patchParts(text, edits): edits is an array of { op: set | add | remove | kind }. (FAIL-LOUD.)');
234
255
  }
235
256
  const changes = [];
236
257
  const refused = [];
@@ -317,6 +338,37 @@ export function patchParts(text, edits, opts) {
317
338
  const ins = _appendProperty(text, obj, appended.join(_multiline(text, obj) ? ',\n' + _indentAt(text, (obj.properties[obj.properties.length - 1] || obj).start) : ', '));
318
339
  patches.push(ins);
319
340
  }
341
+ } else if (e.op === 'kind') {
342
+ const p = entryOf(e);
343
+ if (!p) { continue; }
344
+ const v = p.value;
345
+ if (v.type !== 'ArrayExpression' || v.elements.length !== 2 || !v.elements[0] || v.elements[0].type !== 'Identifier') {
346
+ refuse(e, 'the entry "' + e.name + '" is not written as [Kind, { …props }] — the writer patches only that form.');
347
+ continue;
348
+ }
349
+ if (typeof e.Kind !== 'string' || !_IDENT.test(e.Kind)) {
350
+ throw new TypeError('[parts-writer] kind: Kind is the new kind\'s class name (got ' + JSON.stringify(e.Kind) + '). (FAIL-LOUD.)');
351
+ }
352
+ if (e.module === null || e.module === undefined) {
353
+ refuse(e, 'the kind ' + e.Kind + ' has no importable module, so a sketch cannot import it.');
354
+ continue;
355
+ }
356
+ const spec = importSpecifierOf(e.module, entry);
357
+ const b = bindings.get(e.Kind);
358
+ if (b && !(b.kind === 'import' && b.source === spec && b.imported === e.Kind)) {
359
+ refuse(e, 'the identifier ' + e.Kind + ' is already bound in this sketch to ' +
360
+ (b.kind === 'import' ? '"' + (b.imported || '*') + '" from \'' + b.source + '\'' : 'its own declaration') +
361
+ ' — the writer cannot import the kind ' + e.Kind + ' under that name.');
362
+ continue;
363
+ }
364
+ const id = v.elements[0];
365
+ if (id.name === e.Kind) { continue; }
366
+ patches.push({ start: id.start, end: id.end, text: e.Kind });
367
+ const line = 'import { ' + e.Kind + ' } from ' + _quote(spec) + ';';
368
+ if (!b && !importLines.some(function (l) { return l.Kind === e.Kind; })) {
369
+ importLines.push({ Kind: e.Kind, line: line });
370
+ }
371
+ changes.push({ op: 'kind', name: e.name, from: id.name, to: e.Kind, import: (!b ? line : null) });
320
372
  } else if (e.op === 'remove') {
321
373
  const p = entryOf(e);
322
374
  if (!p) { continue; }
@@ -353,7 +405,7 @@ export function patchParts(text, edits, opts) {
353
405
  changes.push({ op: 'add', name: e.name, from: null, to: _keyText(e.name) + ': [' + e.Kind + ', ' + lit + ']',
354
406
  import: (!b ? 'import { ' + e.Kind + ' } from ' + _quote(spec) + ';' : null) });
355
407
  } else {
356
- throw new TypeError('[parts-writer] unknown edit op ' + JSON.stringify(e.op) + ' — set | add | remove. (FAIL-LOUD.)');
408
+ throw new TypeError('[parts-writer] unknown edit op ' + JSON.stringify(e.op) + ' — set | add | remove | kind. (FAIL-LOUD.)');
357
409
  }
358
410
  }
359
411
  if (adds.length) {
@@ -450,8 +502,13 @@ export function entryLiteral(text, name, key) {
450
502
  for (const q of _entryProps(text, name, 'entryLiteral').properties) {
451
503
  if (_plainKey(q) !== key) { continue; }
452
504
  if (_isLiteral(q.value)) { return { literal: true, value: _literalValue(q.value) }; }
453
- // An array expression still spells its arity (`center: [srcX, cy]` is two numbers).
454
- return q.value.type === 'ArrayExpression' ? { literal: false, length: q.value.elements.length } : { literal: false };
505
+ // An array expression still spells its arity (`center: [srcX, cy]` is two numbers) — unless an element is a
506
+ // spread (`center: [...c]`), which spells no arity: the caller applies the live one.
507
+ const arr = q.value.type === 'ArrayExpression';
508
+ if (arr && !q.value.elements.some(function (x) { return x && x.type === 'SpreadElement'; })) {
509
+ return { literal: false, length: q.value.elements.length };
510
+ }
511
+ return { literal: false };
455
512
  }
456
513
  throw new Error('[parts-writer] entryLiteral: the entry "' + name + '" spells no key "' + key + '". (FAIL-LOUD.)');
457
514
  }
@@ -0,0 +1,43 @@
1
+ /* Copyright 2023-2026 by Essam Abadir */
2
+
3
+ /**
4
+ * read-text.js — THE reader of a text file by URL, for every host: a `file:` URL is read through node's fs
5
+ * (`process.getBuiltinModule`, Node 20.16+ / 22.3+); any other URL is fetched. The split is a CAPABILITY of the
6
+ * resolved URL, never a host sniff.
7
+ *
8
+ * readText(url[, { fetch }]) → Promise<string> REJECTS naming the URL: a file it cannot read ("reading <url>
9
+ * failed: …"), a non-200 ("GET <url> answered <status>"), no
10
+ * fs for a file: URL, no fetch. `fetch` is injectable (tests).
11
+ *
12
+ * Callers prefix their own subject: lib/shim/registry/scene-source.js (a registry scene's sketch) and
13
+ * RecipeContext.fork (a package part's exact bytes).
14
+ */
15
+
16
+ /**
17
+ * @param {string} url
18
+ * @param {{fetch?: function}} [opts]
19
+ * @returns {Promise<string>}
20
+ */
21
+ export function readText(url, opts) {
22
+ return Promise.resolve().then(function () {
23
+ if (typeof url !== 'string' || !url) { throw new TypeError('readText(url): a URL string (got ' + JSON.stringify(url) + ')'); }
24
+ if (url.indexOf('file:') === 0) {
25
+ var getBuiltin = (typeof process !== 'undefined' && process.getBuiltinModule) ? process.getBuiltinModule : null;
26
+ if (typeof getBuiltin !== 'function') {
27
+ throw new Error(url + ' is a file: URL; reading one needs node\'s process.getBuiltinModule (Node 20.16+ / ' +
28
+ '22.3+). In a page, serve the package over http');
29
+ }
30
+ var fs = getBuiltin('node:fs');
31
+ var fileURLToPath = getBuiltin('node:url').fileURLToPath;
32
+ return fs.promises.readFile(fileURLToPath(url), 'utf8').catch(function (e) {
33
+ throw new Error('reading ' + url + ' failed: ' + (e && e.message));
34
+ });
35
+ }
36
+ var f = (opts && opts.fetch) || (typeof fetch === 'function' ? fetch : null);
37
+ if (!f) { throw new Error('no fetch available to load ' + url); }
38
+ return Promise.resolve(f(url)).then(function (res) {
39
+ if (!res || !res.ok) { throw new Error('GET ' + url + ' answered ' + (res ? res.status : 'nothing')); }
40
+ return res.text();
41
+ });
42
+ });
43
+ }