@arkitektio/bsx 6.6.2 → 6.8.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 (91) hide show
  1. package/dist/bsx/analyze.d.ts.map +1 -1
  2. package/dist/bsx/analyze.js +2 -2
  3. package/dist/bsx/analyze.js.map +1 -1
  4. package/dist/bsx/declared.d.ts +25 -1
  5. package/dist/bsx/declared.d.ts.map +1 -1
  6. package/dist/bsx/declared.js +34 -2
  7. package/dist/bsx/declared.js.map +1 -1
  8. package/dist/bsx/expr.d.ts +18 -4
  9. package/dist/bsx/expr.d.ts.map +1 -1
  10. package/dist/bsx/expr.js +46 -9
  11. package/dist/bsx/expr.js.map +1 -1
  12. package/dist/bsx/language.d.ts.map +1 -1
  13. package/dist/bsx/language.js +4 -2
  14. package/dist/bsx/language.js.map +1 -1
  15. package/dist/bsx/parse.d.ts +2 -0
  16. package/dist/bsx/parse.d.ts.map +1 -1
  17. package/dist/bsx/parse.js +63 -6
  18. package/dist/bsx/parse.js.map +1 -1
  19. package/dist/bsx/print.d.ts.map +1 -1
  20. package/dist/bsx/print.js +53 -10
  21. package/dist/bsx/print.js.map +1 -1
  22. package/dist/bsx/references.d.ts +23 -1
  23. package/dist/bsx/references.d.ts.map +1 -1
  24. package/dist/bsx/references.js +266 -14
  25. package/dist/bsx/references.js.map +1 -1
  26. package/dist/ports/rekuest.d.ts +1 -0
  27. package/dist/ports/rekuest.d.ts.map +1 -1
  28. package/dist/renderer/BlokRenderer.d.ts +4 -2
  29. package/dist/renderer/BlokRenderer.d.ts.map +1 -1
  30. package/dist/renderer/BlokRenderer.js +5 -1
  31. package/dist/renderer/BlokRenderer.js.map +1 -1
  32. package/dist/renderer/bloks/control.d.ts +5 -1
  33. package/dist/renderer/bloks/control.d.ts.map +1 -1
  34. package/dist/renderer/bloks/control.js +25 -3
  35. package/dist/renderer/bloks/control.js.map +1 -1
  36. package/dist/renderer/bloks/run/host.d.ts +5 -0
  37. package/dist/renderer/bloks/run/host.d.ts.map +1 -1
  38. package/dist/renderer/bloks/run/host.js.map +1 -1
  39. package/dist/renderer/runtime/context.d.ts +2 -1
  40. package/dist/renderer/runtime/context.d.ts.map +1 -1
  41. package/dist/renderer/runtime/context.js +4 -0
  42. package/dist/renderer/runtime/context.js.map +1 -1
  43. package/dist/renderer/runtime/hooks.d.ts +2 -0
  44. package/dist/renderer/runtime/hooks.d.ts.map +1 -1
  45. package/dist/renderer/runtime/hooks.js +12 -0
  46. package/dist/renderer/runtime/hooks.js.map +1 -1
  47. package/dist/renderer/runtime/resolution.d.ts +1 -0
  48. package/dist/renderer/runtime/resolution.d.ts.map +1 -1
  49. package/dist/renderer/runtime/resolution.js +11 -0
  50. package/dist/renderer/runtime/resolution.js.map +1 -1
  51. package/dist/renderer/runtime/schemas.d.ts.map +1 -1
  52. package/dist/renderer/runtime/schemas.js +1 -0
  53. package/dist/renderer/runtime/schemas.js.map +1 -1
  54. package/dist/renderer/runtime/types.d.ts +13 -0
  55. package/dist/renderer/runtime/types.d.ts.map +1 -1
  56. package/dist/renderer/runtime/types.js.map +1 -1
  57. package/dist/spec/bsx_v2.json +4804 -440
  58. package/dist/spec/catalogs/base@4.json +57 -1
  59. package/dist/spec/catalogs/base@4.json.js +57 -1
  60. package/dist/spec/vocabulary.d.ts +2 -0
  61. package/dist/spec/vocabulary.d.ts.map +1 -1
  62. package/dist/spec/vocabulary.js +2 -0
  63. package/dist/spec/vocabulary.js.map +1 -1
  64. package/dist/spec/vocabulary.json +19 -10
  65. package/dist/spec/vocabulary.json.js +19 -10
  66. package/package.json +1 -1
  67. package/src/bsx/analyze.ts +2 -2
  68. package/src/bsx/declared.ts +48 -2
  69. package/src/bsx/expr.ts +55 -11
  70. package/src/bsx/infer.test.ts +1 -1
  71. package/src/bsx/language.test.ts +17 -16
  72. package/src/bsx/language.ts +4 -2
  73. package/src/bsx/parse.ts +61 -5
  74. package/src/bsx/print.ts +50 -8
  75. package/src/bsx/references.test.ts +12 -11
  76. package/src/bsx/references.ts +277 -12
  77. package/src/ports/rekuest.ts +1 -1
  78. package/src/renderer/BlokRenderer.tsx +9 -0
  79. package/src/renderer/bloks/control.tsx +36 -4
  80. package/src/renderer/bloks/run/host.tsx +5 -0
  81. package/src/renderer/runtime/context.tsx +6 -0
  82. package/src/renderer/runtime/hooks.ts +13 -0
  83. package/src/renderer/runtime/resolution.ts +11 -1
  84. package/src/renderer/runtime/schemas.ts +1 -0
  85. package/src/renderer/runtime/types.ts +14 -0
  86. package/src/renderer/unbound.test.tsx +34 -1
  87. package/src/spec/bsx_v2.json +4804 -440
  88. package/src/spec/catalogs/base@4.json +57 -1
  89. package/src/spec/spec.test.ts +2 -2
  90. package/src/spec/vocabulary.json +19 -10
  91. package/src/spec/vocabulary.ts +4 -0
@@ -13,7 +13,8 @@ import {portIsValid} from './infer';
13
13
  * - its declarations, each a node of its own that draws nothing: `<local>`
14
14
  * anywhere (first among its parent's children, in scope in its parent's
15
15
  * subtree), `<query>` and `<subscription>` as children of the `<Blok>`, each
16
- * with `<var>` children for its variables.
16
+ * with `<var>` children for its variables, and an agent blok's
17
+ * `<dependencies>` children of the `<Blok>`.
17
18
  *
18
19
  * Nothing here checks a rule beyond what makes a declaration readable at all;
19
20
  * the checker (`references.ts`) says the rest.
@@ -24,8 +25,15 @@ export const LOCAL_COMPONENT = 'local';
24
25
  export const QUERY_COMPONENT = 'query';
25
26
  export const SUBSCRIPTION_COMPONENT = 'subscription';
26
27
  export const VAR_COMPONENT = 'var';
28
+ export const DEPENDENCIES_COMPONENT = 'dependencies';
27
29
  /** The components that declare what a blok owns and draw nothing. */
28
- export const DECLARATION_COMPONENTS: ReadonlySet<string> = new Set([LOCAL_COMPONENT, QUERY_COMPONENT, SUBSCRIPTION_COMPONENT, VAR_COMPONENT]);
30
+ export const DECLARATION_COMPONENTS: ReadonlySet<string> = new Set([
31
+ LOCAL_COMPONENT,
32
+ QUERY_COMPONENT,
33
+ SUBSCRIPTION_COMPONENT,
34
+ VAR_COMPONENT,
35
+ DEPENDENCIES_COMPONENT,
36
+ ]);
29
37
  /** The name a local, a query or a subscription is read by. */
30
38
  export const NAME_PROP = 'name';
31
39
  /** A local's borrowed port: `self.<action>.<arg>` or `deps.<key>.<action>.<arg>`. */
@@ -323,6 +331,44 @@ const declaredRead = (node: BlokComponentNode): Record<string, unknown> => {
323
331
 
324
332
  const rootChildren = (tree: BlokComponentNode | null | undefined): BlokComponentNode[] => tree?.children ?? [];
325
333
 
334
+ /**
335
+ * A `<dependencies key="cells" like="self.<action>" />` (custom blok: `agents.<name>.<action>`):
336
+ * the dependencies of one action, each read and called as `deps.<key>__<dependency>` and
337
+ * handed to a run of that action with `with <key>`.
338
+ */
339
+ export type DeclaredDependencies = {
340
+ key: string;
341
+ node: string;
342
+ /** As written; null when it is missing or no literal. */
343
+ like: string | null;
344
+ };
345
+
346
+ /**
347
+ * Whose action it names: `['self', action]` for `self.<action>`, `[key, action]` for a custom
348
+ * blok's `agents.<key>.<action>` (stored `deps.<key>.<action>`); else null.
349
+ */
350
+ export const dependenciesTarget = (declared: DeclaredDependencies): readonly [string, string] | null => {
351
+ const parts = declared.like ? declared.like.split('.') : [];
352
+ if (parts.length === 2 && parts[0] === 'self' && parts[1]) return ['self', parts[1]];
353
+ if (parts.length === 3 && parts[0] === 'deps' && parts[1] && parts[1] !== 'self' && parts[2]) return [parts[1], parts[2]];
354
+ return null;
355
+ };
356
+
357
+ /** The dependency whose action it names: `self`, or a custom blok's bound agent. */
358
+ export const dependenciesOwner = (declared: DeclaredDependencies): string | null => dependenciesTarget(declared)?.[0] ?? null;
359
+
360
+ /** The action `like` names, else null. */
361
+ export const dependenciesAction = (declared: DeclaredDependencies): string | null => dependenciesTarget(declared)?.[1] ?? null;
362
+
363
+ /** The keyed `<dependencies>` children of a blok's `<Blok>`, in order. */
364
+ export const declaredDependencies = (tree: BlokComponentNode | null | undefined): DeclaredDependencies[] =>
365
+ rootChildren(tree).flatMap(child => {
366
+ if (child.component !== DEPENDENCIES_COMPONENT) return [];
367
+ const key = staticProp(child, KEY_PROP)?.static_value;
368
+ const like = staticProp(child, LIKE_PROP)?.static_value;
369
+ return typeof key === 'string' && key ? [{key, node: child.id, like: typeof like === 'string' ? like : null}] : [];
370
+ });
371
+
326
372
  /** The readable `<query>` children of a blok's `<Blok>`, in order. */
327
373
  export const declaredQueries = (tree: BlokComponentNode | null | undefined): DeclaredQuery[] =>
328
374
  rootChildren(tree)
package/src/bsx/expr.ts CHANGED
@@ -6,7 +6,7 @@ import {BsxSyntaxError} from './source';
6
6
  * (takt) and Python parsers implement the same grammar and all three are held
7
7
  * to one corpus (`core/blok/spec/bsx_v2.json`):
8
8
  *
9
- * callback := expression ('into' name)?
9
+ * callback := expression ('with' name)? ('into' name)?
10
10
  * expression := ternary
11
11
  * ternary := coalesce ('?' expression ':' expression)?
12
12
  * coalesce := or ('??' or)*
@@ -34,7 +34,14 @@ export type ListExpr = {type: 'list'; items: Expr[]; offset: number};
34
34
  export type ObjectExpr = {type: 'object'; entries: Array<[string, Expr]>; offset: number};
35
35
  export type PathExpr = {type: 'path'; segments: string[]; offset: number};
36
36
  export type Argument = {name: string | null; value: Expr; offset: number};
37
- export type CallExpr = {type: 'call'; callee: string[]; arguments: Argument[]; offset: number};
37
+ export type CallExpr = {
38
+ type: 'call';
39
+ callee: string[];
40
+ arguments: Argument[];
41
+ offset: number;
42
+ /** `with cells` on a task call: the dependencies the blok declares under that key (`<dependencies key="cells" />`), whose agents the run gets. */
43
+ given?: string;
44
+ };
38
45
  export type NotExpr = {type: 'not'; operand: Expr; offset: number};
39
46
  export type CompareExpr = {type: 'compare'; operator: string; left: Expr; right: Expr; offset: number};
40
47
  /** `a && b && c`, `a || b` or `a ?? b`: one operator over every operand (a parenthesized group stays one operand). */
@@ -241,12 +248,29 @@ class Lexer {
241
248
  /* Parser */
242
249
  /* -------------------------------------------------------------------------- */
243
250
 
251
+ /**
252
+ * How a read through a declared `<dependencies key="cells" />` is stored: `cells.microscope`
253
+ * is the dependency `cells__microscope` of the blok (`deps.cells__microscope`), one segment.
254
+ */
255
+ export const REFERENCE_SEPARATOR = '__';
256
+ /** How a custom blok writes an agent it is bound to: `agents.<key>`, stored `deps.<key>`. */
257
+ export const AGENTS_ROOT = 'agents';
258
+ /** `cells.pick(microscope: id)`: the one call a reference itself takes. */
259
+ export const PICK_VERB = 'pick';
260
+
261
+ const NO_REFERENCES: ReadonlySet<string> = new Set();
262
+
244
263
  class Parser {
245
264
  private readonly lexer: Lexer;
246
265
  private readonly tokens: Token[];
266
+ private readonly references: ReadonlySet<string>;
267
+ /** In a custom blok: its bound agents are written `agents.<key>` (stored `deps.<key>`). */
268
+ private readonly custom: boolean;
247
269
  private index = 0;
248
270
 
249
- constructor(text: string, base: number, locator: Locator) {
271
+ constructor(text: string, base: number, locator: Locator, references: ReadonlySet<string> = NO_REFERENCES, custom = false) {
272
+ this.references = references;
273
+ this.custom = custom;
250
274
  this.lexer = new Lexer(text, base, locator);
251
275
  this.tokens = this.lexer.tokens();
252
276
  }
@@ -308,7 +332,14 @@ class Parser {
308
332
 
309
333
  callback(): Expr {
310
334
  if (this.token.kind === 'name' && this.token.value === 'await') throw this.fail('callback.await');
311
- const expression = this.expression();
335
+ let expression = this.expression();
336
+ if (this.token.kind === 'name' && this.token.value === 'with') {
337
+ const withToken = this.advance();
338
+ const name = this.token;
339
+ if (expression.type !== 'call' || name.kind !== 'name' || name.value === 'into') throw this.fail('callback.with', withToken.offset);
340
+ this.advance();
341
+ expression = {...expression, given: name.value};
342
+ }
312
343
  if (this.token.kind === 'name' && this.token.value === 'into') {
313
344
  const into = this.advance();
314
345
  if (expression.type !== 'call') throw this.fail('callback.into', into.offset);
@@ -428,13 +459,22 @@ class Parser {
428
459
 
429
460
  private pathOrCall(): Expr {
430
461
  const first = this.advance();
431
- const segments = [first.value];
462
+ let segments = [first.value];
432
463
  while (this.isOp('.')) {
433
464
  this.advance();
434
465
  if (this.token.kind !== 'name') throw this.unexpected("expected a name after '.'");
435
466
  segments.push(this.advance().value);
436
467
  }
437
468
  if (this.isOp('=>')) throw this.fail('expr.lambda');
469
+ // A read or a call through declared dependencies (`cells.microscope.stage`) is one of
470
+ // the blok's dependencies, `deps.cells__microscope`; `cells.pick(...)` stays as written.
471
+ if (this.references.has(segments[0]) && segments.length > 1 && !(this.isOp('(') && segments.length === 2 && segments[1] === PICK_VERB)) {
472
+ segments = ['deps', `${segments[0]}${REFERENCE_SEPARATOR}${segments[1]}`, ...segments.slice(2)];
473
+ } else if (this.custom && segments[0] === AGENTS_ROOT) {
474
+ segments[0] = 'deps';
475
+ } else if (this.custom && segments[0] === 'deps') {
476
+ throw this.fail('roots.custom_deps', first.offset, {path: segments.join('.')});
477
+ }
438
478
  if (!this.isOp('(')) return {type: 'path', segments, offset: first.offset};
439
479
  this.advance();
440
480
  const args: Argument[] = [];
@@ -496,22 +536,26 @@ class Parser {
496
536
  }
497
537
  }
498
538
 
499
- const parser = (text: string, base: number, locator: Locator | undefined): Parser => {
500
- const parsing = new Parser(text, base, locator ?? new Locator(text));
539
+ const parser = (text: string, base: number, locator: Locator | undefined, references?: ReadonlySet<string>, custom = false): Parser => {
540
+ const parsing = new Parser(text, base, locator ?? new Locator(text), references, custom);
501
541
  if (parsing.isEmpty()) throw parsing.fail('expr.syntax', undefined, {detail: 'the expression is empty'});
502
542
  return parsing;
503
543
  };
504
544
 
505
- /** A value expression (no `into`). `base` is where `text` starts in the source `locator` reads. */
506
- export const parseExpression = (text: string, base = 0, locator?: Locator): Expr => {
507
- const parsing = parser(text, base, locator);
545
+ /**
546
+ * A value expression (no `into`). `base` is where `text` starts in the source `locator` reads;
547
+ * `references` are the keys of the `<dependencies>` it may read through; `custom` says it is a custom blok's.
548
+ */
549
+ export const parseExpression = (text: string, base = 0, locator?: Locator, references?: ReadonlySet<string>, custom = false): Expr => {
550
+ const parsing = parser(text, base, locator, references, custom);
508
551
  const expression = parsing.expression();
509
552
  parsing.finish();
510
553
  return expression;
511
554
  };
512
555
 
513
556
  /** An attribute's expression: a value, or a callback (`<call> into <name>`). */
514
- export const parseAttribute = (text: string, base = 0, locator?: Locator): Expr => parser(text, base, locator).callback();
557
+ export const parseAttribute = (text: string, base = 0, locator?: Locator, references?: ReadonlySet<string>, custom = false): Expr =>
558
+ parser(text, base, locator, references, custom).callback();
515
559
 
516
560
  /** The expressions directly inside `expression`. */
517
561
  export const childrenOf = (expression: Expr): Expr[] => {
@@ -81,7 +81,7 @@ describe('local kind inference', () => {
81
81
  });
82
82
 
83
83
  it('never infers a dependency: a custom blok reading an undeclared one is refused', () => {
84
- const tree = parseBsx(blok('custom', '<Card><Text text={deps.zeta.x} /><Button onClick={deps.alpha.go()} /><Text text={deps.mid.y} /></Card>')).tree;
84
+ const tree = parseBsx(blok('custom', '<Card><Text text={agents.zeta.x} /><Button onClick={agents.alpha.go()} /><Text text={agents.mid.y} /></Card>')).tree;
85
85
  const found = checkBlokTree(tree, mountedBlokScope([], [{key: 'mid', state_dependencies: []}]), null);
86
86
  expect(found.map(finding => finding.code)).toEqual(['deps.unknown', 'deps.unknown', 'deps.unknown_state']);
87
87
  expect(found[0].message).toContain('Fix: dependencies=[AgentDependencyInput(key="zeta")].');
@@ -108,7 +108,8 @@ describe('completeBsx: components and props', () => {
108
108
  describe('completeBsx: expressions', () => {
109
109
  it('offers the roots of the kind, locals, records and namespaces', () => {
110
110
  const items = labels('<Text text={|');
111
- expect(items).toEqual(expect.arrayContaining(['deps', 'args', 'queries', 'viewer', 'speed', 'str', 'true']));
111
+ expect(items).toEqual(expect.arrayContaining(['agents', 'args', 'queries', 'viewer', 'speed', 'str', 'true']));
112
+ expect(items).not.toContain('deps');
112
113
  expect(items).not.toContain('self');
113
114
  expect(items).not.toContain('task');
114
115
  expect(items).not.toContain('event');
@@ -116,14 +117,14 @@ describe('completeBsx: expressions', () => {
116
117
  });
117
118
 
118
119
  it('walks agents: states, tasks, assets, fields, and actions only in callbacks', () => {
119
- expect(labels('<Text text={deps.|')).toEqual(['stage']);
120
- expect(labels('<Text text={deps.stage.|')).toEqual(['position', 'tasks', 'assets', 'id', 'name', 'connected']);
121
- expect(labels('<Button onClick={deps.stage.|')).toContain('move');
122
- expect(at('<Button onClick={deps.stage.|').find(item => item.label === 'move')?.insertText).toBe('move(x: ${1}, y: ${2})');
123
- expect(labels('<Text text={deps.stage.position.|')).toEqual(['x', 'y']);
124
- expect(labels('<Text text={deps.stage.tasks.|')).toEqual(['move']);
125
- expect(labels('<Text text={deps.stage.tasks.move.|')).toEqual(expect.arrayContaining(['status', 'running', 'returns', 'args']));
126
- expect(labels('<Text text={deps.stage.tasks.move.returns.|')).toEqual(['arrived']);
120
+ expect(labels('<Text text={agents.|')).toEqual(['stage']);
121
+ expect(labels('<Text text={agents.stage.|')).toEqual(['position', 'tasks', 'assets', 'id', 'name', 'connected']);
122
+ expect(labels('<Button onClick={agents.stage.|')).toContain('move');
123
+ expect(at('<Button onClick={agents.stage.|').find(item => item.label === 'move')?.insertText).toBe('move(x: ${1}, y: ${2})');
124
+ expect(labels('<Text text={agents.stage.position.|')).toEqual(['x', 'y']);
125
+ expect(labels('<Text text={agents.stage.tasks.|')).toEqual(['move']);
126
+ expect(labels('<Text text={agents.stage.tasks.move.|')).toEqual(expect.arrayContaining(['status', 'running', 'returns', 'args']));
127
+ expect(labels('<Text text={agents.stage.tasks.move.returns.|')).toEqual(['arrived']);
127
128
  });
128
129
 
129
130
  it('offers query records and refetch in a callback', () => {
@@ -145,11 +146,11 @@ describe('completeBsx: expressions', () => {
145
146
  });
146
147
 
147
148
  it('offers into names, lets and event fields where they are bound', () => {
148
- expect(labels('<Card><Button onClick={deps.stage.move(x: 1, y: 2) into run} /><Text>{run.|')).toContain('progress');
149
- expect(labels('<Card><Button onClick={deps.stage.move(x: 1, y: 2) into run} /><Text>{|')).toContain('run');
149
+ expect(labels('<Card><Button onClick={agents.stage.move(x: 1, y: 2) into run} /><Text>{run.|')).toContain('progress');
150
+ expect(labels('<Card><Button onClick={agents.stage.move(x: 1, y: 2) into run} /><Text>{|')).toContain('run');
150
151
  expect(labels('<foreach items={args.image} let="p" key={p}><Text text={|')).toContain('p');
151
- expect(labels('<Slider onChange={deps.stage.move(x: |')).toContain('event');
152
- expect(labels('<Slider onChange={deps.stage.move(x: event.|')).toEqual(['value']);
152
+ expect(labels('<Slider onChange={agents.stage.move(x: |')).toContain('event');
153
+ expect(labels('<Slider onChange={agents.stage.move(x: event.|')).toEqual(['value']);
153
154
  expect(labels('<suspense><error><Text text={|')).toContain('error');
154
155
  });
155
156
 
@@ -161,7 +162,7 @@ describe('completeBsx: expressions', () => {
161
162
  });
162
163
 
163
164
  it('offers into after a task call', () => {
164
- expect(labels('<Button onClick={deps.stage.move(x: 1, y: 2) |')).toEqual(['into']);
165
+ expect(labels('<Button onClick={agents.stage.move(x: 1, y: 2) |')).toEqual(['into']);
165
166
  expect(labels("<Text text={str.upper('|")).toEqual([]);
166
167
  });
167
168
  });
@@ -192,11 +193,11 @@ describe('analyzeBsx', () => {
192
193
  const analyze = (source: string, overrides: Partial<BlokCheckScope> = {}) => analyzeBsx(source, {scope: {...scope, ...overrides}});
193
194
 
194
195
  it('marks a finding at its prop, with its code', () => {
195
- const source = '<Blok kind="custom" context="panel"><Text text={deps.stage.speed} /></Blok>';
196
+ const source = '<Blok kind="custom" context="panel"><Text text={agents.stage.speed} /></Blok>';
196
197
  const {markers} = analyze(source);
197
198
  expect(markers).toHaveLength(1);
198
199
  expect(markers[0]).toMatchObject({code: 'deps.unknown_state', severity: 'error'});
199
- expect(source.slice(markers[0].range.start, markers[0].range.end)).toBe('deps.stage.speed');
200
+ expect(source.slice(markers[0].range.start, markers[0].range.end)).toBe('agents.stage.speed');
200
201
  });
201
202
 
202
203
  it('marks warnings as warnings', () => {
@@ -615,7 +615,8 @@ const completeExpression = (env: BsxEnvironment, text: string, expression: strin
615
615
  }
616
616
  if (lets.includes(first)) return [];
617
617
  if (into.includes(first)) {
618
- const call = new RegExp(`(?:self|deps\\.(\\w+))\\.(\\w+)\\([^)]*\\)\\s+${INTO_KEYWORD}\\s+${first}\\b`).exec(text);
618
+ // `self.go() with cells into run`: the `with` clause sits between the call and its name.
619
+ const call = new RegExp(`(?:self|(?:deps|agents)\\.(\\w+))\\.(\\w+)\\([^)]*\\)(?:\\s+with\\s+\\w+)?\\s+${INTO_KEYWORD}\\s+${first}\\b`).exec(text);
619
620
  const dependency = call ? dependencyOf(env, call[1] ?? 'self') : undefined;
620
621
  const action = dependency?.action_dependencies?.find(candidate => candidate.key === call?.[2]);
621
622
  return taskRecord(rest, action?.demand?.return_matches);
@@ -642,6 +643,7 @@ const completeExpression = (env: BsxEnvironment, text: string, expression: strin
642
643
  case 'self':
643
644
  return agent(dependencyOf(env, 'self'), rest);
644
645
  case 'deps':
646
+ case 'agents': // a custom blok's spelling of its bound agents
645
647
  if (rest.length === 0) return dependenciesOf(env).filter(dependency => dependency.key !== 'self').map(dependency => item(dependency.key, 'dependency', 'dependency'));
646
648
  return agent(dependencyOf(env, rest[0]), rest.slice(1));
647
649
  case 'args':
@@ -783,7 +785,7 @@ export const signatureBsx = (text: string, offset: number, env: BsxEnvironment):
783
785
  };
784
786
  }
785
787
  const parts = call.callee.split('.');
786
- const target = parts[0] === 'self' && parts.length === 2 ? ['self', parts[1]] : parts[0] === 'deps' && parts.length === 3 ? [parts[1], parts[2]] : null;
788
+ const target = parts[0] === 'self' && parts.length === 2 ? ['self', parts[1]] : (parts[0] === 'deps' || parts[0] === 'agents') && parts.length === 3 ? [parts[1], parts[2]] : null;
787
789
  if (!target) return null;
788
790
  const action = dependencyOf(env, target[0])?.action_dependencies?.find(candidate => candidate.key === target[1]);
789
791
  if (!action) return null;
package/src/bsx/parse.ts CHANGED
@@ -14,8 +14,10 @@ import {
14
14
  dotted,
15
15
  isLocalName,
16
16
  Locator,
17
+ AGENTS_ROOT,
17
18
  parseAttribute,
18
19
  parseExpression,
20
+ PICK_VERB,
19
21
  type CallExpr,
20
22
  type Expr,
21
23
  } from './expr';
@@ -71,6 +73,11 @@ export const EVENT_ROOT = 'event';
71
73
  export const REFETCH_FUNCTION = 'query.refetch';
72
74
  export const FETCH_MORE_FUNCTION = 'query.fetch_more';
73
75
  /** The read intents written as methods of a query: `queries.<name>.refetch()`. */
76
+ /** What `<key>.pick(<dependency>: <agent id>)` is stored as. */
77
+ export const PICK_FUNCTION = 'deps.pick';
78
+ const DEPENDENCIES_COMPONENT = 'dependencies';
79
+ const BLOK_COMPONENT = 'Blok';
80
+ const LIKE_PROP = 'like';
74
81
  export const QUERY_SUGAR: Readonly<Record<string, string>> = {refetch: REFETCH_FUNCTION, fetch_more: FETCH_MORE_FUNCTION};
75
82
 
76
83
  const isQuerySugar = (call: CallExpr): boolean =>
@@ -181,6 +188,21 @@ class Markup {
181
188
  return match[0];
182
189
  }
183
190
 
191
+ /** The keys of the `<dependencies>` read so far: what a later expression may read through. */
192
+ readonly references = new Set<string>();
193
+ /** Whether the root is a custom blok: its bound agents are written `agents.<key>`. */
194
+ custom = false;
195
+
196
+ /** A `<dependencies key="cells" />` is read through from here on (`cells.microscope`). */
197
+ private declares(element: MarkupElement): void {
198
+ if (element.name === BLOK_COMPONENT) {
199
+ this.custom = element.attributes.some(attribute => attribute.name === 'kind' && attribute.value === 'custom');
200
+ }
201
+ if (element.name !== DEPENDENCIES_COMPONENT) return;
202
+ const key = element.attributes.find(attribute => attribute.name === 'key')?.value;
203
+ if (typeof key === 'string' && isLocalName(key)) this.references.add(key);
204
+ }
205
+
184
206
  element(): MarkupElement {
185
207
  const offset = this.index;
186
208
  this.index += 1;
@@ -202,11 +224,13 @@ class Markup {
202
224
  this.index += 2;
203
225
  element.tagEnd = this.index;
204
226
  element.end = this.index;
227
+ this.declares(element);
205
228
  return element;
206
229
  }
207
230
  if (this.at('>')) {
208
231
  this.index += 1;
209
232
  element.tagEnd = this.index;
233
+ this.declares(element);
210
234
  this.content(element);
211
235
  element.end = this.index;
212
236
  return element;
@@ -248,7 +272,7 @@ class Markup {
248
272
  const inner = this.source.slice(start, end);
249
273
  this.index = end + 1;
250
274
  if (!inner.trim()) throw this.fail('expr.syntax', start, {detail: `the value of ${name} is empty`});
251
- const expression = parseAttribute(inner, start, this.locator);
275
+ const expression = parseAttribute(inner, start, this.locator, new Set(this.references), this.custom);
252
276
  return {name, value: expression, offset, nameEnd, valueStart: start, end};
253
277
  }
254
278
  throw this.fail('bsx.syntax', undefined, {detail: `${name}= takes "a string" or {an expression}`});
@@ -308,7 +332,7 @@ class Markup {
308
332
  this.index = end + 1;
309
333
  const stripped = inner.trim();
310
334
  if (!stripped || (stripped.startsWith('/*') && stripped.endsWith('*/'))) continue;
311
- element.children.push({kind: 'container', expression: parseExpression(inner, start, this.locator), offset});
335
+ element.children.push({kind: 'container', expression: parseExpression(inner, start, this.locator, new Set(this.references), this.custom), offset});
312
336
  continue;
313
337
  }
314
338
  if (this.at('}')) throw this.fail('bsx.syntax', undefined, {detail: "unexpected '}' in text; write {'}'}"});
@@ -559,6 +583,9 @@ class Lowering {
559
583
  }
560
584
  if (value === true) return {key: attribute.name, static_value: true};
561
585
  if (typeof value === 'string') {
586
+ if (attribute.name === LIKE_PROP && (component === LOCAL_COMPONENT || component === DEPENDENCIES_COMPONENT) && this.markup.custom) {
587
+ return {key: attribute.name, static_value: this.customLike(value, attribute.offset)};
588
+ }
562
589
  if ((attribute.name === FOREACH_LET_PROP || attribute.name === FOREACH_INDEX_PROP) && component === FOREACH_COMPONENT) {
563
590
  return {key: attribute.name, static_value: value, declares_value: value};
564
591
  }
@@ -569,6 +596,15 @@ class Lowering {
569
596
  return this.value(attribute.name, value, attribute.offset);
570
597
  }
571
598
 
599
+ /** A custom blok's `like="agents.<key>..."` as it is stored: `deps.<key>...`. */
600
+ private customLike(like: string, offset: number): string {
601
+ const dot = like.indexOf('.');
602
+ const root = dot < 0 ? like : like.slice(0, dot);
603
+ const rest = dot < 0 ? '' : like.slice(dot + 1);
604
+ if (root === 'deps') throw this.fail('roots.custom_deps', offset, {path: like});
605
+ return root === AGENTS_ROOT && rest ? `deps.${rest}` : like;
606
+ }
607
+
572
608
  private value(key: string, expression: Expr, offset: number): BlokComponentProp {
573
609
  switch (expression.type) {
574
610
  case 'into': {
@@ -592,7 +628,7 @@ class Lowering {
592
628
  case 'call': {
593
629
  const agent = this.agentCall(expression);
594
630
  if (agent) return {key, agent_call: agent};
595
- const effect = this.queryEffect(expression);
631
+ const effect = this.pickEffect(expression) ?? this.queryEffect(expression);
596
632
  if (effect) return {key, util_call: effect};
597
633
  return {key, util_call: this.utilCall(expression, true)};
598
634
  }
@@ -626,7 +662,7 @@ class Lowering {
626
662
  return null;
627
663
  }
628
664
 
629
- /** A task call (`self.<action>(...)`, `deps.<key>.<action>(...)`), or null. */
665
+ /** A task call (`self.<action>(...)`, `deps.<key>.<action>(...)`; a custom blok's `agents.<key>` was read as the latter), or null. */
630
666
  private agentCall(call: CallExpr): BlokAgentCall | null {
631
667
  const {callee} = call;
632
668
  let dependency: string;
@@ -638,6 +674,7 @@ class Lowering {
638
674
  dependency = callee[1];
639
675
  operation = callee[2];
640
676
  } else {
677
+ if (call.given !== undefined) throw this.fail('callback.with', call.offset);
641
678
  return null;
642
679
  }
643
680
  const args: BlokActionArgument[] = [];
@@ -648,7 +685,26 @@ class Lowering {
648
685
  seen.add(argument.name);
649
686
  args.push(this.argument(argument.name, argument.value));
650
687
  }
651
- return {dependency, operation, ...(args.length ? {arguments: args} : {})};
688
+ // Left out, so a call without `with` is stored as it always was.
689
+ return {dependency, operation, ...(args.length ? {arguments: args} : {}), ...(call.given !== undefined ? {given: call.given} : {})};
690
+ }
691
+
692
+ /** `cells.pick(microscope: id, ...)` as its effect (`deps.pick`), or null. */
693
+ private pickEffect(call: CallExpr): BlokUtilCall | null {
694
+ const {callee} = call;
695
+ if (callee.length !== 2 || callee[1] !== PICK_VERB || !this.markup.references.has(callee[0])) return null;
696
+ const picks: BlokActionArgument[] = [];
697
+ const seen = new Set<string>();
698
+ for (const argument of call.arguments) {
699
+ if (argument.name === null) throw this.fail('callback.positional', argument.offset, {call: calleeName(call)});
700
+ if (seen.has(argument.name)) throw this.fail('expr.duplicate_key', argument.offset, {key: argument.name});
701
+ seen.add(argument.name);
702
+ picks.push(this.argument(argument.name, argument.value));
703
+ }
704
+ if (!picks.length) {
705
+ throw this.fail('expr.arguments', call.offset, {function: calleeName(call), detail: 'pick names the dependency to bind: pick(<dependency>: <agent id>)'});
706
+ }
707
+ return {operation: PICK_FUNCTION, arguments: [{key: 'key', value_literal: callee[0]}, {key: 'picks', value_dict: picks}]};
652
708
  }
653
709
 
654
710
  /** `queries.<name>.refetch()` / `.fetch_more(k: v, ...)` as its effect, or null. */
package/src/bsx/print.ts CHANGED
@@ -15,11 +15,14 @@ import {
15
15
  FOREACH_INDEX_PROP,
16
16
  FOREACH_LET_PROP,
17
17
  LEGACY_IMPLICIT_TEXTS,
18
+ PICK_FUNCTION,
18
19
  TEXT_NODE,
19
20
  TEXT_VALUE,
20
21
  REFETCH_FUNCTION,
21
22
  TEMPLATE_FUNCTION,
22
23
  } from './parse';
24
+ import {declaredDependencies} from './declared';
25
+ import {AGENTS_ROOT, PICK_VERB, REFERENCE_SEPARATOR} from './expr';
23
26
 
24
27
  /**
25
28
  * Print a stored v2 tree as BSX: the inverse of `parseBsx`, the port of
@@ -229,7 +232,7 @@ class Printer {
229
232
  if (typeof prop.static_value === 'string') return textLiteral(prop.static_value, !inline);
230
233
  if (prop.dynamic_value) {
231
234
  if (prop.dynamic_value.literal != null || prop.dynamic_value.path == null || prop.static_value != null) return null;
232
- return `{${prop.dynamic_value.path}}`;
235
+ return `{${this.path(prop.dynamic_value.path)}}`;
233
236
  }
234
237
  const call = prop.util_call;
235
238
  if (call && call.operation === TEMPLATE_FUNCTION) {
@@ -264,7 +267,7 @@ class Printer {
264
267
  }
265
268
  if (prop.util_call) {
266
269
  const call = prop.util_call;
267
- const sugar = this.querySugar(call);
270
+ const sugar = this.pickSugar(call) ?? this.querySugar(call);
268
271
  if (sugar !== null) return `${key}={${sugar}}`;
269
272
  if (key === CLASS_NAME && call.operation === CLASSES_FUNCTION && call.arguments?.length === 1) {
270
273
  const values = call.arguments[0];
@@ -276,11 +279,14 @@ class Printer {
276
279
  if (prop.dynamic_value.literal != null || prop.dynamic_value.path == null) {
277
280
  return refuse(`<${node.component}> (${node.id}): ${key} has a fallback literal, which BSX cannot spell`);
278
281
  }
279
- return `${key}={${prop.dynamic_value.path}}`;
282
+ return `${key}={${this.path(prop.dynamic_value.path)}}`;
280
283
  }
281
284
  const value = prop.static_value;
282
285
  if (value === true) return key;
283
- if (typeof value === 'string') return `${key}=${quoted(value)}`;
286
+ if (typeof value === 'string') {
287
+ const agents = this.custom && key === 'like' && (node.component === 'local' || node.component === 'dependencies') && value.startsWith('deps.');
288
+ return `${key}=${quoted(agents ? `${AGENTS_ROOT}.${value.slice('deps.'.length)}` : value)}`;
289
+ }
284
290
  if (value !== null && typeof value === 'object' && key === CLASS_NAME) {
285
291
  return refuse(`<${node.component}> (${node.id}): a static className list reads back as str.classes`);
286
292
  }
@@ -314,15 +320,48 @@ class Printer {
314
320
  return `queries.${named.value_literal}.fetch_more(${variables.join(', ')})`;
315
321
  }
316
322
 
323
+ /** The keys of the `<dependencies>` the tree declares: what it reads through, bare. */
324
+ references: ReadonlySet<string> = new Set();
325
+ /** Whether the tree is a custom blok: its bound agents (stored `deps.<key>`) are written `agents.<key>`. */
326
+ custom = false;
327
+
328
+ /** `path` as BSX writes it: one through declared dependencies (stored `deps.cells__microscope.stage`) reads `cells.microscope.stage`. */
329
+ private path(path: string): string {
330
+ const parts = path.split('.');
331
+ if (parts.length > 1 && parts[0] === 'deps') {
332
+ const at = parts[1].indexOf(REFERENCE_SEPARATOR);
333
+ const key = at < 0 ? '' : parts[1].slice(0, at);
334
+ if (at >= 0 && this.references.has(key)) return [key, parts[1].slice(at + REFERENCE_SEPARATOR.length), ...parts.slice(2)].join('.');
335
+ if (this.custom) return [AGENTS_ROOT, ...parts.slice(1)].join('.');
336
+ }
337
+ return path;
338
+ }
339
+
340
+ /** `deps.pick` as BSX writes it (`cells.pick(microscope: id)`), or null when the call is not one the sugar spells. */
341
+ private pickSugar(call: BlokUtilCall): string | null {
342
+ if (call.operation !== PICK_FUNCTION) return null;
343
+ const args = call.arguments ?? [];
344
+ if (args.length !== 2 || args[0].key !== 'key' || args[1].key !== 'picks') return null;
345
+ const key = args[0].value_literal;
346
+ const picks = args[1].value_dict;
347
+ if (typeof key !== 'string' || !this.references.has(key) || !picks?.length) return null;
348
+ const written: string[] = [];
349
+ for (const pick of picks) {
350
+ if (pick.key == null || !IDENTIFIER.test(pick.key)) return null;
351
+ written.push(`${pick.key}: ${this.argument(pick, 0)}`);
352
+ }
353
+ return `${key}.${PICK_VERB}(${written.join(', ')})`;
354
+ }
355
+
317
356
  private agentCall(call: BlokAgentCall): string {
318
- const callee = call.dependency === 'self' ? `self.${call.operation}` : `deps.${call.dependency}.${call.operation}`;
357
+ const callee = call.dependency === 'self' ? `self.${call.operation}` : this.path(`deps.${call.dependency}.${call.operation}`);
319
358
  const args = (call.arguments ?? []).map(argument => {
320
359
  if (argument.key == null || !IDENTIFIER.test(argument.key)) {
321
360
  return refuse(`${callee}: a task call names its arguments, not '${argument.key ?? 'None'}'`);
322
361
  }
323
362
  return `${argument.key}: ${this.argument(argument, 0)}`;
324
363
  });
325
- return `${callee}(${args.join(', ')})`;
364
+ return `${callee}(${args.join(', ')})${call.given ? ` with ${call.given}` : ''}`;
326
365
  }
327
366
 
328
367
  private expressionOfCall(call: BlokUtilCall, needed: number): string {
@@ -383,7 +422,7 @@ class Printer {
383
422
 
384
423
  argument(argument: BlokActionArgument, needed: number): string {
385
424
  if (argument.agent_call) return refuse("a task call is a callback's one thing, never an argument");
386
- if (argument.value_path != null) return argument.value_path;
425
+ if (argument.value_path != null) return this.path(argument.value_path);
387
426
  if (argument.util_call) return this.expressionOfCall(argument.util_call, needed);
388
427
  if (argument.value_list != null) return `[${argument.value_list.map(item => this.argument(item, 0)).join(', ')}]`;
389
428
  if (argument.value_dict != null) {
@@ -400,7 +439,10 @@ class Printer {
400
439
  /** Print `node` as v2 BSX that `parseBsx` (with the same view) reads back into it. Throws a `BsxPrintError`. */
401
440
  export const printBsx = (node: BlokComponentNode, options: {view?: BlokView; indent?: number} = {}): string => {
402
441
  const lines: string[] = [];
403
- new Printer(options.view ?? defaultBlokView(), options.indent ?? 2).node(node, `${node.component}[0]`, 0, lines);
442
+ const printer = new Printer(options.view ?? defaultBlokView(), options.indent ?? 2);
443
+ printer.references = new Set(declaredDependencies(node).map(declared => declared.key));
444
+ printer.custom = node.component === 'Blok' && (node.props ?? []).some(prop => prop.key === 'kind' && prop.static_value === 'custom');
445
+ printer.node(node, `${node.component}[0]`, 0, lines);
404
446
  return lines.join('\n');
405
447
  };
406
448