@notis_ai/cli 0.2.31 → 0.2.32

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@notis_ai/cli",
3
- "version": "0.2.31",
3
+ "version": "0.2.32",
4
4
  "description": "Agent-first Notis CLI for Spaces, Skills and generic tool execution",
5
5
  "type": "module",
6
6
  "bin": {
@@ -53,8 +53,8 @@
53
53
  "react-dom": "19.3.0"
54
54
  },
55
55
  "notisRelease": {
56
- "sourceSha": "b5902cc7f64ba2ed2615c903c6e88a58d588bf5f",
56
+ "sourceSha": "73f9e76d42341e84ac32ae1a25ee7f2a8e51052e",
57
57
  "channel": "stable"
58
58
  },
59
- "gitHead": "b5902cc7f64ba2ed2615c903c6e88a58d588bf5f"
59
+ "gitHead": "73f9e76d42341e84ac32ae1a25ee7f2a8e51052e"
60
60
  }
@@ -181,6 +181,20 @@ When to use: Find a link binding and its revision before removing it, including
181
181
  Examples:
182
182
  - `npx --package @notis_ai/cli@latest -- notis spaces links list <space-id>`
183
183
 
184
+ ### `npx --package @notis_ai/cli@latest -- notis spaces records <space-id> <binding>`
185
+
186
+ List the records of one database linked into a Space you edit: record key and title, oldest first, one page at a time.
187
+
188
+ When to use: Find the record keys and titles of a linked database, for example to write fixtures or link to one record. Editors only; anyone else reads through the Space's declared actions.
189
+
190
+ Options:
191
+ - `--limit <number>` — Records per page, 1 to 100; defaults to 20.
192
+ - `--offset <number>` — Zero-based start; pass next_offset from the previous page.
193
+ - `--record <record-key>` — Fixed record context, when this is a record-scoped Space.
194
+
195
+ Examples:
196
+ - `npx --package @notis_ai/cli@latest -- notis spaces records <space-id> tasks --limit 20`
197
+
184
198
  ### `npx --package @notis_ai/cli@latest -- notis spaces links remove <space-id> <binding-id>`
185
199
 
186
200
  Remove one database, Skill or automation link from a Space by its binding.
@@ -404,6 +404,60 @@ function refreshPulledSdk(projectDir) {
404
404
  warnings: messages.filter((message) => warning.test(message)).map((message) => message.replace(warning, '')) };
405
405
  }
406
406
 
407
+ function pageNumber(value, { flag, fallback, minimum, maximum }) {
408
+ if (value === undefined) return fallback;
409
+ const number = Number(value);
410
+ if (!Number.isSafeInteger(number) || number < minimum || number > maximum) {
411
+ throw usageError(`Pass ${flag} as a whole number from ${minimum} to ${maximum}.`);
412
+ }
413
+ return number;
414
+ }
415
+
416
+ /** One line per record: a tab or line break in a title would split the tab-separated output. */
417
+ const flatTitle = title => title.replace(/[\t\r\n]+/g, ' ');
418
+
419
+ /**
420
+ * The records of one database linked into a Space, through its link like any native read: the alias
421
+ * resolves among the links the caller can see, and the server's native query decides what they may open.
422
+ * A direct query on a link is an editor read; anyone else reads through the Space's declared actions.
423
+ */
424
+ async function listSpaceRecords(ctx) {
425
+ const limit = pageNumber(ctx.options.limit, { flag: '--limit', fallback: 20, minimum: 1, maximum: 100 });
426
+ const offset = pageNumber(ctx.options.offset, { flag: '--offset', fallback: 0, minimum: 0, maximum: 1_000_000 });
427
+ const spaceId = ctx.args.spaceId, wanted = ctx.args.binding;
428
+ const query = new URLSearchParams({ space_id: spaceId });
429
+ const links = (await httpRequest({ runtime: ctx.runtime, method: 'GET', path: `/portal_spaces/space-links?${query}`,
430
+ spacesProtocol: true })).payload?.links;
431
+ const link = (Array.isArray(links) ? links : []).find(entry => entry?.kind === 'database'
432
+ && (entry.binding_id === wanted || entry.alias === wanted));
433
+ if (!link) {
434
+ throw usageError(`This Space has no database link "${wanted}" you can open. List its links with notis spaces links list ${spaceId}.`);
435
+ }
436
+ const target = { space_id: spaceId, binding: link.binding_id, ...(ctx.options.record ? { document_id: ctx.options.record } : {}) };
437
+ // Oldest first, then by key, so --offset pages never skip or repeat a record.
438
+ const sorts = [{ field: { column: 'created_at' }, direction: 'asc' }, { field: { column: 'record_key' }, direction: 'asc' }];
439
+ let result;
440
+ try {
441
+ result = await httpRequest({ runtime: ctx.runtime, method: 'POST', path: '/portal_spaces/data', spacesProtocol: true,
442
+ body: { operation: 'query', target, input: { mode: 'rows', sorts, page_size: limit, offset, include_content: false } } });
443
+ } catch (error) {
444
+ if (error instanceof CliError && error.details?.error === 'action_required') {
445
+ throw new CliError({ code: error.code, message: 'Only an editor of this Space can list a linked database\'s records; anyone else reads them through the Space\'s declared actions.',
446
+ exitCode: error.exitCode, details: error.details });
447
+ }
448
+ throw error;
449
+ }
450
+ const answer = result.payload || {};
451
+ const records = (Array.isArray(answer.rows) ? answer.rows : []).map(row => ({ record_key: row.record_key,
452
+ title: typeof row.title === 'string' ? row.title : '' }));
453
+ const data = { space_id: spaceId, alias: link.alias, target, records, has_more: Boolean(answer.has_more),
454
+ next_offset: answer.next_offset ?? null, schema_revision: answer.schema_revision ?? null };
455
+ const lines = records.map(record => `${record.record_key}\t${flatTitle(record.title)}`);
456
+ if (data.has_more && data.next_offset !== null) lines.push(`More records: --offset ${data.next_offset}`);
457
+ return ctx.output.emitSuccess({ command: ctx.spec.command_path.join(' '), data,
458
+ humanSummary: lines.length ? lines.join('\n') : 'No records.', meta: { mutating: false, request_id: result.requestId } });
459
+ }
460
+
407
461
  const idArgument = { token: '<space-id>', key: 'spaceId', description: 'Exact existing Space ID.' };
408
462
  const recordOption = { flags: '--record <record-key>', description: 'Fixed record context, when this is a record-scoped Space.' };
409
463
  const requestOption = { flags: '--request-id <key>', description: 'Stable intent key. Reuse after timeouts or lost replies.' };
@@ -604,6 +658,19 @@ export const spacesCommandSpecs = [
604
658
  return remote(ctx, 'space-links', { method: 'GET', query: { space_id: ctx.args.spaceId } });
605
659
  },
606
660
  },
661
+ {
662
+ command_path: ['spaces', 'records'],
663
+ summary: 'List the records of one database linked into a Space you edit: record key and title, oldest first, one page at a time.',
664
+ when_to_use: 'Find the record keys and titles of a linked database, for example to write fixtures or link to one record. Editors only; anyone else reads through the Space\'s declared actions.',
665
+ args_schema: { arguments: [idArgument, { token: '<binding>', key: 'binding',
666
+ description: 'Database link alias or binding ID from spaces links list.' }], options: [
667
+ { flags: '--limit <number>', description: 'Records per page, 1 to 100; defaults to 20.' },
668
+ { flags: '--offset <number>', description: 'Zero-based start; pass next_offset from the previous page.' }, recordOption] },
669
+ examples: ['notis spaces records <space-id> tasks --limit 20'],
670
+ mutates: false, idempotent: true, require_auth: true,
671
+ backend_call: { type: 'http', path: '/portal_spaces/data' },
672
+ handler: listSpaceRecords,
673
+ },
607
674
  {
608
675
  command_path: ['spaces', 'links', 'remove'],
609
676
  summary: 'Remove one database, Skill or automation link from a Space by its binding.',
@@ -3,7 +3,7 @@ import { dirname, extname, join, resolve } from 'node:path';
3
3
  import { fileURLToPath } from 'node:url';
4
4
 
5
5
  import { usageError } from './errors.js';
6
- import { maskSerializedJsonData } from './app-data-literals.js';
6
+ import { maskSerializedJsonData, maskSerializedJsonDataOrNull } from './app-data-literals.js';
7
7
 
8
8
  const moduleDir = dirname(fileURLToPath(import.meta.url));
9
9
 
@@ -341,7 +341,7 @@ export function loadDesignRules({ rulesPath = resolveDesignRulesPath(), profile
341
341
  );
342
342
  }
343
343
  if (!payload) {
344
- return { profile, include: [], exclude: [], extensions: DEFAULT_DESIGN_EXTENSIONS, rules: [], allowDirective: 'notis-design-allow', allowReasonMinLength: 12 };
344
+ return { profile, include: [], exclude: [], extensions: DEFAULT_DESIGN_EXTENSIONS, rules: [], icons: null, allowDirective: 'notis-design-allow', allowReasonMinLength: 12 };
345
345
  }
346
346
  const profiles = payload.profiles && typeof payload.profiles === 'object' && !Array.isArray(payload.profiles) ? payload.profiles : {};
347
347
  const selected = profile !== 'app' && profiles[profile] && typeof profiles[profile] === 'object' ? profiles[profile] : null;
@@ -355,6 +355,7 @@ export function loadDesignRules({ rulesPath = resolveDesignRulesPath(), profile
355
355
  extensions: Array.isArray(payload.extensions) ? payload.extensions : DEFAULT_DESIGN_EXTENSIONS,
356
356
  allowDirective: typeof payload.allow_directive === 'string' ? payload.allow_directive : 'notis-design-allow',
357
357
  allowReasonMinLength: Number.isInteger(payload.allow_reason_min_length) ? payload.allow_reason_min_length : 12,
358
+ icons: loadIconCheck(payload.icons, profile),
358
359
  rules: (Array.isArray(payload.rules) ? payload.rules : [])
359
360
  .filter((rule) => !Array.isArray(rule.profiles) || rule.profiles.includes(profile))
360
361
  .map((rule) => ({
@@ -373,6 +374,243 @@ export function loadDesignRules({ rulesPath = resolveDesignRulesPath(), profile
373
374
  };
374
375
  }
375
376
 
377
+ // ---------------------------------------------------------------------------
378
+ // Icon names
379
+ //
380
+ // The toolkit's Icon draws a fixed set of names (`icons.names` in the rules
381
+ // file, kept equal to the SDK's ICON_NAMES by packages/sdk/src/ui/icons.test.tsx)
382
+ // and an unknown one draws nothing, so a guessed Phosphor name ships an empty
383
+ // button. Only toolkit inputs are checked, and only when the whole value is one
384
+ // kebab-case string literal:
385
+ // - `name` on the SDK's Icon and `icon` on any other SDK component, the tag
386
+ // resolved through the file's @notis/sdk imports (aliases and namespaces);
387
+ // - an `icon` field of an object that also has a `label` (reader actions,
388
+ // view menu items, tabs: the toolkit's labelled items).
389
+ // Text inside strings and comments is never read. Mirrored by
390
+ // _icon_candidates in server/lib/app_boundary_validator.py.
391
+ // ---------------------------------------------------------------------------
392
+
393
+ const ICON_NAME_SHAPE = /^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/;
394
+ const SDK_IMPORTS = /(?<![\w$.])import\s+([\w$\s{},*]+?)\s+from\s*(["'])@notis\/sdk(?:\/[^"'\s]*)?\2/g;
395
+ const JSX_TAG = /<([A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)?)(?=[\s/>])/g;
396
+ const JSX_ATTRIBUTE = /(?<![\w$.-])(icon|name)\s*=\s*/g;
397
+ const ICON_FIELD = /(?<![\w$.-])icon\s*:\s*/g;
398
+ const LABEL_KEY = /(?<![\w$.-])label\s*[:,}]/g;
399
+ // What a JSX opening tag holds at its own level besides strings and braced values.
400
+ const TAG_TEXT = /[\w$\-:.=\t\n\v\f\r /]/;
401
+
402
+ /** Local component names bound to @notis/sdk (local -> exported) and namespace names. Type-only imports bind nothing. */
403
+ function sdkBindings(text) {
404
+ const components = new Map(), namespaces = new Set();
405
+ for (const match of text.matchAll(SDK_IMPORTS)) {
406
+ const clause = match[1].trim();
407
+ if (/^type\s/.test(clause)) continue;
408
+ const namespace = clause.match(/\*\s*as\s+([\w$]+)/);
409
+ if (namespace) namespaces.add(namespace[1]);
410
+ const named = clause.match(/\{([^}]*)\}/);
411
+ for (const part of named ? named[1].split(',') : []) {
412
+ const item = part.trim();
413
+ if (!item || /^type\s/.test(item)) continue;
414
+ const [exported, local = exported] = item.split(/\s+as\s+/).map((value) => value.trim());
415
+ components.set(local, exported);
416
+ }
417
+ }
418
+ return { components, namespaces };
419
+ }
420
+
421
+ /**
422
+ * One pass over comment-masked source: which characters sit inside a string, the innermost open
423
+ * brace around each character, and where each brace closes. A quote left open at the end of its
424
+ * line is JSX text (an apostrophe), not a string.
425
+ */
426
+ function sourceShape(text) {
427
+ const length = text.length;
428
+ const inString = new Uint8Array(length), owner = new Int32Array(length).fill(-1), closes = new Map(), stack = [];
429
+ let index = 0;
430
+ while (index < length) {
431
+ const char = text[index];
432
+ const top = stack.length ? stack[stack.length - 1] : -1;
433
+ if (char === '"' || char === "'" || char === '`') {
434
+ let cursor = index + 1, closed = false;
435
+ while (cursor < length) {
436
+ const inner = text[cursor];
437
+ if (inner === '\\') { cursor += 2; continue; }
438
+ if (inner === char) { cursor += 1; closed = true; break; }
439
+ if (inner === '\n' && char !== '`') break;
440
+ cursor += 1;
441
+ }
442
+ if (closed) {
443
+ for (let at = index; at < cursor; at += 1) { inString[at] = 1; owner[at] = top; }
444
+ index = cursor;
445
+ continue;
446
+ }
447
+ }
448
+ owner[index] = top;
449
+ if (char === '{') stack.push(index);
450
+ else if (char === '}' && stack.length) closes.set(stack.pop(), index);
451
+ index += 1;
452
+ }
453
+ return { inString, owner, closes };
454
+ }
455
+
456
+ /** The literal at `at` when it is the whole value: 'x', "x", `x` (no ${}), or {'x'} in JSX. */
457
+ function literalAt(text, shape, at, { braced = false } = {}) {
458
+ let start = at;
459
+ if (braced && text[at] === '{' && shape.closes.has(at)) {
460
+ const inner = text.slice(at + 1, shape.closes.get(at));
461
+ const match = inner.match(/^\s*(["'`])([^"'`\n\\$]*)\1\s*$/);
462
+ if (!match) return null;
463
+ start = at + 1 + inner.indexOf(match[1]);
464
+ return { name: match[2], index: start + 1 };
465
+ }
466
+ const match = text.slice(start).match(/^(["'`])([^"'`\n\\$]*)\1/);
467
+ return match ? { name: match[2], index: start + 1, end: start + match[0].length } : null;
468
+ }
469
+
470
+ /**
471
+ * Where a JSX opening tag ends: its `>` at the tag's own brace level, outside strings, jumping over
472
+ * braced values. Any other character at that level means this is not a tag (`a <B && c`): stop there.
473
+ */
474
+ function tagEnd(text, shape, from) {
475
+ const level = shape.owner[from];
476
+ let index = from + 1;
477
+ while (index < text.length) {
478
+ const char = text[index];
479
+ if (shape.inString[index]) { index += 1; continue; }
480
+ if (char === '>') return index;
481
+ if (char === '{') {
482
+ if (!shape.closes.has(index)) return index;
483
+ index = shape.closes.get(index) + 1;
484
+ continue;
485
+ }
486
+ if (shape.owner[index] !== level || !TAG_TEXT.test(char)) return index;
487
+ index += 1;
488
+ }
489
+ return text.length;
490
+ }
491
+
492
+ /** True when the key at `at` sits where an object key does: right after `{` or `,`, outside strings. */
493
+ function keyPosition(text, shape, at) {
494
+ let index = at - 1;
495
+ while (index >= 0 && ' \t\n\v\f\r'.includes(text[index])) index -= 1;
496
+ return index >= 0 && !shape.inString[index] && (text[index] === '{' || text[index] === ',');
497
+ }
498
+
499
+ /** `{ index, name }` for every literal handed to a toolkit icon input in this comment-masked file. */
500
+ function iconCandidates(text) {
501
+ const { components, namespaces } = sdkBindings(text);
502
+ if (!components.size && !namespaces.size) return [];
503
+ const shape = sourceShape(text), found = [];
504
+ for (const match of text.matchAll(JSX_TAG)) {
505
+ if (shape.inString[match.index]) continue;
506
+ const [first, second] = match[1].split('.');
507
+ const exported = second === undefined ? components.get(first) : namespaces.has(first) ? second : undefined;
508
+ if (!exported) continue;
509
+ const wanted = exported === 'Icon' ? 'name' : 'icon';
510
+ const end = tagEnd(text, shape, match.index);
511
+ const level = shape.owner[match.index];
512
+ JSX_ATTRIBUTE.lastIndex = match.index + match[0].length;
513
+ let attribute;
514
+ while ((attribute = JSX_ATTRIBUTE.exec(text)) !== null && attribute.index < end) {
515
+ if (attribute[1] !== wanted || shape.inString[attribute.index] || shape.owner[attribute.index] !== level) continue;
516
+ const literal = literalAt(text, shape, attribute.index + attribute[0].length, { braced: true });
517
+ if (literal) found.push(literal);
518
+ }
519
+ }
520
+ for (const match of text.matchAll(ICON_FIELD)) {
521
+ if (shape.inString[match.index] || !keyPosition(text, shape, match.index)) continue;
522
+ const literal = literalAt(text, shape, match.index + match[0].length);
523
+ if (!literal || !/^\s*[,}]/.test(text.slice(literal.end))) continue;
524
+ const object = shape.owner[match.index];
525
+ if (object < 0 || !shape.closes.has(object)) continue;
526
+ const body = text.slice(object, shape.closes.get(object) + 1);
527
+ const labelled = [...body.matchAll(LABEL_KEY)].some((key) => !shape.inString[object + key.index]
528
+ && shape.owner[object + key.index] === object && keyPosition(text, shape, object + key.index));
529
+ if (labelled) found.push(literal);
530
+ }
531
+ return found;
532
+ }
533
+
534
+ function loadIconCheck(icons, profile) {
535
+ if (!icons || typeof icons !== 'object' || !Array.isArray(icons.names) || icons.names.length === 0) return null;
536
+ if (Array.isArray(icons.profiles) && !icons.profiles.includes(profile)) return null;
537
+ const names = icons.names.filter((name) => typeof name === 'string');
538
+ return {
539
+ id: typeof icons.id === 'string' ? icons.id : 'space-unknown-icon',
540
+ message: typeof icons.message === 'string' ? icons.message : 'Unknown icon "{name}". Closest names: {suggestions}.',
541
+ suggestions: Number.isInteger(icons.suggestions) && icons.suggestions > 0 ? icons.suggestions : 3,
542
+ exclude: Array.isArray(icons.exclude) ? icons.exclude : [],
543
+ names,
544
+ known: new Set(names),
545
+ };
546
+ }
547
+
548
+ function editDistance(a, b) {
549
+ let previous = Array.from({ length: b.length + 1 }, (_, index) => index);
550
+ for (let i = 1; i <= a.length; i += 1) {
551
+ const current = [i];
552
+ for (let j = 1; j <= b.length; j += 1) {
553
+ current[j] = Math.min(previous[j] + 1, current[j - 1] + 1, previous[j - 1] + (a[i - 1] === b[j - 1] ? 0 : 1));
554
+ }
555
+ previous = current;
556
+ }
557
+ return previous[b.length];
558
+ }
559
+
560
+ /**
561
+ * The names the refusal suggests: those sharing a word with the unknown name first ("funnel" finds
562
+ * funnel-simple), then by edit distance, ties by name.
563
+ */
564
+ export function closestIconNames(name, names, count = 3) {
565
+ const words = new Set(name.split('-'));
566
+ return names
567
+ .map((candidate) => ({
568
+ candidate,
569
+ shared: candidate.split('-').some((word) => words.has(word)) ? 0 : 1,
570
+ distance: editDistance(name, candidate),
571
+ }))
572
+ .sort((left, right) => left.shared - right.shared || left.distance - right.distance
573
+ || (left.candidate < right.candidate ? -1 : left.candidate > right.candidate ? 1 : 0))
574
+ .slice(0, count)
575
+ .map((entry) => entry.candidate);
576
+ }
577
+
578
+ function iconViolations(normalized, content, checked, lines, config) {
579
+ const icons = config.icons;
580
+ if (!icons || matchesAny(normalized, icons.exclude)) return [];
581
+ const found = new Map(), suggestions = new Map(), lineStarts = [0];
582
+ for (let cursor = 0; cursor < content.length; cursor += 1) if (content.charCodeAt(cursor) === 10) lineStarts.push(cursor + 1);
583
+ const lineAt = (index) => {
584
+ let low = 0, high = lineStarts.length - 1;
585
+ while (low < high) { const middle = (low + high + 1) >> 1; if (lineStarts[middle] <= index) low = middle; else high = middle - 1; }
586
+ return low + 1;
587
+ };
588
+ for (const { index, name } of iconCandidates(checked)) {
589
+ if (!ICON_NAME_SHAPE.test(name) || icons.known.has(name)) continue;
590
+ const line = lineAt(index);
591
+ const key = `${line}:${name}`;
592
+ if (!found.has(key)) found.set(key, { line, name });
593
+ }
594
+ return [...found.values()].sort((left, right) => left.line - right.line).map(({ line, name }) => {
595
+ const message = icons.message
596
+ .replace('{name}', name)
597
+ .replace('{suggestions}', suggestions.get(name) ?? suggestions.set(name, closestIconNames(name, icons.names, icons.suggestions).join(', ')).get(name));
598
+ const reason = findAllowDirective(lines, line, icons.id, config.allowDirective);
599
+ const allowed = reason !== null && reason.length >= config.allowReasonMinLength;
600
+ return {
601
+ file: normalized,
602
+ line,
603
+ ruleId: icons.id,
604
+ severity: allowed ? 'warn' : 'error',
605
+ message: reason !== null && !allowed
606
+ ? `${message} (a notis-design-allow directive needs a reason of at least ${config.allowReasonMinLength} characters)`
607
+ : message,
608
+ allowed,
609
+ reason: allowed ? reason : null,
610
+ };
611
+ });
612
+ }
613
+
376
614
  function getCompiledDesignRules(profile = 'app') {
377
615
  if (!compiledDesignRules.has(profile)) {
378
616
  compiledDesignRules.set(profile, loadDesignRules({ profile }));
@@ -411,7 +649,13 @@ export function collectDesignViolationsForFile(relPath, content, config = getCom
411
649
  // directive; comments are masked after, for matching only, so a real
412
650
  // directive comment is still read from `lines`.
413
651
  const unserialized = ['.js', '.jsx', '.ts', '.tsx'].includes(extension)
414
- ? maskSerializedJsonData(content, extension) : content;
652
+ ? maskSerializedJsonDataOrNull(content, extension) : content;
653
+ // Too deep to parse here: checked unmasked, data deep in it would read as code. The server checks it when the
654
+ // Space is released, at any depth, so this file is left to it.
655
+ if (unserialized === null) {
656
+ return [{ file: normalized, line: 1, ruleId: 'too-deep', severity: 'info', allowed: false, reason: null,
657
+ message: 'nested too deep to check here; the server checks this file when you deploy' }];
658
+ }
415
659
  const checked = maskComments(unserialized, extension);
416
660
  const lines = unserialized.split('\n');
417
661
  const violations = [];
@@ -452,6 +696,7 @@ export function collectDesignViolationsForFile(relPath, content, config = getCom
452
696
  });
453
697
  }
454
698
  }
699
+ if (extension !== '.css') violations.push(...iconViolations(normalized, content, checked, lines, config));
455
700
  return violations;
456
701
  }
457
702
 
@@ -10,22 +10,19 @@ function isJsonParse(node) {
10
10
  && callee.property?.type === 'Identifier' && callee.property.name === 'parse';
11
11
  }
12
12
 
13
- function dataContext(ancestors) {
14
- if (ancestors.some(node => node.type === 'JSXAttribute')) return false;
15
- for (let index = ancestors.length - 1; index >= 0; index -= 1) {
16
- const node = ancestors[index];
17
- if (node.type === 'JSXAttribute' || node.type === 'ImportDeclaration'
18
- || node.type === 'ImportExpression' || node.type === 'TSImportType'
19
- || node.type === 'ExportAllDeclaration' || node.type === 'ExportNamedDeclaration'
20
- || node.type === 'NewExpression' || node.type === 'TaggedTemplateExpression'
21
- || node.type === 'MemberExpression' || node.type === 'OptionalMemberExpression') return false;
22
- if (node.type === 'CallExpression' || node.type === 'OptionalCallExpression') {
23
- if (!isJsonParse(node)) return false;
24
- }
25
- if (['VariableDeclarator', 'ExportDefaultDeclaration', 'ReturnStatement'].includes(node.type)) return true;
26
- if (node.type === 'ExpressionStatement') return false;
27
- }
28
- return false;
13
+ const NOT_DATA = new Set(['JSXAttribute', 'ImportDeclaration', 'ImportExpression', 'TSImportType',
14
+ 'ExportAllDeclaration', 'ExportNamedDeclaration', 'NewExpression', 'TaggedTemplateExpression',
15
+ 'MemberExpression', 'OptionalMemberExpression']);
16
+ const DATA = new Set(['VariableDeclarator', 'ExportDefaultDeclaration', 'ReturnStatement']);
17
+
18
+ // What this ancestor says about a literal below it: true or false, or null to ask its parent.
19
+ // The nearest ancestor that answers decides, as climbing from the literal would.
20
+ function decides(node) {
21
+ if (NOT_DATA.has(node.type)) return false;
22
+ if ((node.type === 'CallExpression' || node.type === 'OptionalCallExpression') && !isJsonParse(node)) return false;
23
+ if (DATA.has(node.type)) return true;
24
+ if (node.type === 'ExpressionStatement') return false;
25
+ return null;
29
26
  }
30
27
 
31
28
  /**
@@ -37,6 +34,15 @@ function dataContext(ancestors) {
37
34
  * Source/archive bytes are never rewritten; offsets and line breaks survive.
38
35
  */
39
36
  export function maskSerializedJsonData(content, extension = '.js') {
37
+ return maskSerializedJsonDataOrNull(content, extension) ?? content;
38
+ }
39
+
40
+ /**
41
+ * The same mask, or null when the file nests too deep for the parser (Babel
42
+ * runs out of stack at about 200 levels): the caller then leaves the file to
43
+ * the server's check, which reads any depth.
44
+ */
45
+ export function maskSerializedJsonDataOrNull(content, extension = '.js') {
40
46
  let ast;
41
47
  try {
42
48
  babelParse ||= require('@babel/parser').parse;
@@ -46,15 +52,17 @@ export function maskSerializedJsonData(content, extension = '.js') {
46
52
  plugins: [...(['.ts', '.tsx'].includes(extension) ? ['typescript'] : []),
47
53
  ...(extension !== '.ts' ? ['jsx'] : [])],
48
54
  });
49
- } catch { return content; }
55
+ } catch (error) { return error instanceof RangeError ? null : content; }
50
56
  const ranges = [];
51
- const pending = [[ast, []]];
57
+ // Each node carries what its ancestors decided, so no literal looks back up the tree and no
58
+ // ancestor list is copied per node: deep data (objects nested a thousand levels) stays linear.
59
+ const pending = [[ast, false, null]];
52
60
  while (pending.length) {
53
- const [node, ancestors] = pending.pop();
61
+ const [node, underAttribute, decided] = pending.pop();
54
62
  if (!node || typeof node !== 'object') continue;
55
63
  const literal = node.type === 'StringLiteral' ? node.value
56
64
  : node.type === 'TemplateLiteral' && node.expressions.length === 0 ? node.quasis[0]?.value.cooked : null;
57
- if (typeof literal === 'string' && dataContext(ancestors)) {
65
+ if (typeof literal === 'string' && !underAttribute && decided === true) {
58
66
  try {
59
67
  const value = JSON.parse(literal);
60
68
  if (value !== null && typeof value === 'object') {
@@ -63,12 +71,13 @@ export function maskSerializedJsonData(content, extension = '.js') {
63
71
  }
64
72
  } catch { /* Ordinary/non-JSON strings keep their original checks. */ }
65
73
  }
66
- const parents = [...ancestors, node];
74
+ const own = node.type ? decides(node) : null;
75
+ const below = [underAttribute || node.type === 'JSXAttribute', own ?? decided];
67
76
  for (const [key, value] of Object.entries(node)) {
68
77
  if (['loc', 'extra', 'tokens', 'comments', 'errors'].includes(key)) continue;
69
78
  if (Array.isArray(value)) {
70
- for (const child of value) if (child?.type) pending.push([child, parents]);
71
- } else if (value?.type) pending.push([value, parents]);
79
+ for (const child of value) if (child?.type) pending.push([child, ...below]);
80
+ } else if (value?.type) pending.push([value, ...below]);
72
81
  }
73
82
  }
74
83
  let cursor = 0;
@@ -74,12 +74,31 @@ function checkContextFields(value,where) {
74
74
  /**
75
75
  * The states verify opens the view in: `contexts` (1 to 4 named ones, each with optional params, now and locale), or
76
76
  * the one `context`, named default. Each entry keeps the object the view receives as its runtime context.
77
+ * `context.views`, the further params the Spaces review deck draws (portal/scripts/spaces-boundary), are states too:
78
+ * the first 3 that open another link than the context (key order, text or number, and a declared default do not
79
+ * count) follow default, each named view-<place in the list>, with the context's now and locale. The deck draws them all.
77
80
  */
78
- function fixtureContexts(fixtures) {
81
+ function fixtureContexts(fixtures,declared={}) {
79
82
  if(fixtures.contexts===undefined) {
80
83
  const value=fixtures.context || {};
81
84
  checkContextFields(value,'The fixture context');
82
- return [{name:'default',context:value}];
85
+ if(value.views===undefined) return [{name:'default',context:value}];
86
+ if(!Array.isArray(value.views) || value.views.some(item=>!object(item))) {
87
+ throw usageError('The fixture context views must be a list of view params, such as [{"period": "week"}].');
88
+ }
89
+ const {views,...base}=value;
90
+ // One link is one view, as the deck reads it: a declared default is left out of the link and 10 is "10".
91
+ const link=params=>JSON.stringify(Object.entries(params || {})
92
+ .filter(([name,item])=>!(object(declared[name]) && Object.hasOwn(declared[name],'default') && String(declared[name].default)===String(item)))
93
+ .map(([name,item])=>[name,String(item)]).sort(([a],[b])=>a<b ? -1 : a>b ? 1 : 0));
94
+ const seen=new Set([link(base.params)]),extra=[];
95
+ views.forEach((params,index)=>{
96
+ checkContextFields({params},`The fixture context view ${index+1}`);
97
+ if(seen.has(link(params)) || extra.length>=FIXTURE_CONTEXTS_MAX-1) return;
98
+ seen.add(link(params));
99
+ extra.push({name:`view-${index+1}`,context:{...base,params}});
100
+ });
101
+ return [{name:'default',context:base},...extra];
83
102
  }
84
103
  if(fixtures.context!==undefined) throw usageError('Verification fixtures declare either context or contexts, not both. Move context into contexts as one named entry.');
85
104
  const list=fixtures.contexts;
@@ -164,7 +183,7 @@ export function createSpaceFixtureEngine(release) {
164
183
  }
165
184
  if(!object(fixtures) || Object.keys(fixtures).some(key=>!['actions','context','contexts','documentBodies','viewerReads','shown','recordViews','images'].includes(key)) || !object(fixtures.actions)
166
185
  || (fixtures.context!==undefined && !object(fixtures.context))) throw usageError('Verification fixtures declare actions and optional synthetic context.');
167
- const contexts=fixtureContexts(fixtures);
186
+ const contexts=fixtureContexts(fixtures,release.manifest.params || {});
168
187
  const images=new Map(fixtureImageEntries(fixtures,release.fixturePath).map(entry=>{
169
188
  const encoded=release.sourceFiles[entry.path];
170
189
  if(typeof encoded!=='string') throw usageError(`Fixture image ${entry.path} for ${entry.url} is missing from the Space folder.`);