@brydio/manifest 0.1.0-alpha.5 → 0.1.0-alpha.50

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/src/schema.js CHANGED
@@ -2,6 +2,10 @@ import { z } from 'zod';
2
2
  import { MANIFEST_LIMITS, SEMVER_FORMAT, baseManifestSchema as manifestSchema } from "./base.js";
3
3
  import { COLLECTION_NAME, FIELD_LIMITS, FIELD_NAME, FieldTypeInvalid, isSearchable, isSortable, isStructured, parseFieldType, RESERVED_FIELDS, } from "./field-types.js";
4
4
  import { migrationsSchema } from "./migrations.js";
5
+ import { openSchemaProblems } from "./open-schema.js";
6
+ import { confirmEmailProblems, confirmEmailSchema } from "./confirm-email.js";
7
+ import { anonymousProblems, anonymousSchema, anonymousSpec } from "./anonymous.js";
8
+ import { editorsProblems, editorsSchema, READERS_LIMIT, readersProblems, readersSchema } from "./readers.js";
5
9
  export { COLOUR_TOKENS, FIELD_LIMITS, parseFieldType, RESERVED_FIELDS, structuredFields, } from "./field-types.js";
6
10
  /**
7
11
  * What an app adds to `.brydio/app.json` to be more than a bundle of servers
@@ -24,12 +28,84 @@ const placementSettingSchema = z.object({
24
28
  required: z.boolean().optional(),
25
29
  placeholder: z.string().max(200).optional(),
26
30
  });
31
+ /**
32
+ * How deep a folder's rows may nest, counting its own rows as the first
33
+ * level (ADR-A21): Issues → sprints → issues is two. Each level is listed
34
+ * only when a person opens its parent, so depth costs nothing while closed;
35
+ * the limit is for the sidebar's width and a person's patience.
36
+ */
37
+ export const MAX_FOLDER_DEPTH = 4;
38
+ /**
39
+ * "New sprint" on a folder's level (ADR-A21): one of the app's tools, run
40
+ * through the screen's door with the name the person typed in `titleField`
41
+ * and, below the first level, the row it is created under in `parentField`.
42
+ */
43
+ const folderCreateSchema = z.object({
44
+ tool: z.string().min(1).max(64),
45
+ /** "sprint", in "New sprint". */
46
+ noun: z.string().min(1).max(40).optional(),
47
+ titleField: z.string().regex(FIELD_NAME, 'A field name is letters, digits and _, starting with a lower-case letter.').optional(),
48
+ parentField: z.string().regex(FIELD_NAME, 'A field name is letters, digits and _, starting with a lower-case letter.').optional(),
49
+ });
50
+ /** A level below a folder's own rows: what they are called, and how one is made. */
51
+ const folderLevelSchema = z.object({
52
+ noun: z.string().min(1).max(60).optional(),
53
+ create: folderCreateSchema.optional(),
54
+ });
55
+ /** The sizes a Home card or a project widget can be drawn at (CC11-F10). */
56
+ export const HOME_CARD_SIZES = ['small', 'medium', 'large'];
57
+ /** The kinds drawn as a card, which say the sizes they draw well at. */
58
+ export const SIZED_PLACEMENT_KINDS = ['home', 'project-widget'];
59
+ /** A stable identity for one independently addable placement offering. */
60
+ export const PLACEMENT_KEY = /^[a-z][a-z0-9-]{0,39}$/;
61
+ export function effectivePlacementKey(one) {
62
+ return one.key ?? `${one.kind}:${one.screen}`;
63
+ }
27
64
  const placementSchema = z.object({
28
- kind: z.enum(['project-tab', 'project-sidebar', 'workspace-sidebar']),
65
+ key: z.string().regex(PLACEMENT_KEY).optional(),
66
+ /**
67
+ * `home`: a card on a person's Home, drawn by `screen` at one of `sizes`.
68
+ * `project-widget`: a card on a project's page, drawn at one of `sizes`.
69
+ * `project-tab` is retired (30 Sep 2026): still read from a published
70
+ * manifest, refused in a new one (`placement_tab_retired`).
71
+ * `public-page`: a screen people without a Brydio account open at the
72
+ * page's own address, once an admin turns it on (P3). It has no `sizes`,
73
+ * `children` or `settings` (`placement_public_shape`), and it reaches only
74
+ * collections marked `publicRead` or `publicSubmit` and tools marked
75
+ * `public`.
76
+ * `chat-card`: a screen drawn inside a chat message the app posted with
77
+ * a handler's `chat.post` (FO03). Nobody places it by hand, so it has no
78
+ * `sizes`, `children` or `settings` (`placement_chat_card_shape`); its
79
+ * screen sees `placement.kind === 'chat-card'` and the card's `route`.
80
+ */
81
+ kind: z.enum(['project-tab', 'project-widget', 'project-sidebar', 'workspace-sidebar', 'home', 'public-page', 'chat-card']),
29
82
  screen: z.string().min(1).max(FIELD_LIMITS.nameChars),
83
+ /** For `home` and `project-widget` only, and required there: the sizes the screen draws well at. */
84
+ sizes: z.array(z.enum(HOME_CARD_SIZES)).max(3).optional(),
30
85
  label: z.string().min(1).max(60).optional(),
31
86
  icon: z.string().max(60).optional(),
32
87
  settings: z.record(z.string().regex(FIELD_NAME), placementSettingSchema).optional(),
88
+ /**
89
+ * A folder (A2-F02-S02): a sidebar item whose rows one of the app's read
90
+ * tools lists live, only while it is open. It can nest, and offer "New …"
91
+ * at each level, when the app opts in (ADR-A21).
92
+ */
93
+ children: z
94
+ .object({
95
+ tool: z.string().min(1).max(64),
96
+ refreshSeconds: z.number().int().min(15).max(3600).optional(),
97
+ cap: z.number().int().min(1).max(50).optional(),
98
+ noun: z.string().min(1).max(60).optional(),
99
+ /** A "New …" row at the folder's first level (ADR-A21). */
100
+ create: folderCreateSchema.optional(),
101
+ /**
102
+ * The levels under the first, in order (ADR-A21). A row the tool marks
103
+ * `hasChildren` opens only when a level is declared for it; without
104
+ * `nested` the folder stays one flat list.
105
+ */
106
+ nested: z.array(folderLevelSchema).max(8).optional(),
107
+ })
108
+ .optional(),
33
109
  });
34
110
  const collectionSchema = z.object({
35
111
  /** Field name to type, in the manifest's spelling (`"member?"`, `["todo","done"]`). */
@@ -38,6 +114,49 @@ const collectionSchema = z.object({
38
114
  search: z.array(z.string()).optional(),
39
115
  /** The singular noun the tools are named with: `issue` gives `create_issue`. */
40
116
  label: z.string().optional(),
117
+ /**
118
+ * Fields defined at runtime as records of another collection (P5): `fields`
119
+ * names it, and `table`, when given, the `string` field on both naming
120
+ * which table a row or a definition belongs to.
121
+ */
122
+ openSchema: z
123
+ .object({
124
+ fields: z.string().min(1).max(FIELD_LIMITS.nameChars),
125
+ table: z.string().min(1).max(FIELD_LIMITS.nameChars).optional(),
126
+ })
127
+ .strict()
128
+ .optional(),
129
+ /**
130
+ * A visitor on one of the app's public pages may `get` and `list` every
131
+ * record of this collection in that instance (P3).
132
+ */
133
+ publicRead: z.boolean().optional(),
134
+ /**
135
+ * A visitor on one of the app's public pages may create records here, and
136
+ * nothing else: no update, remove or batch, and no get or list unless
137
+ * `publicRead` is set too (P3).
138
+ */
139
+ publicSubmit: z.boolean().optional(),
140
+ /**
141
+ * Brydio emails the visitor once after a public submission here (FO04):
142
+ * `field` names a `string` field holding their address; `subject` and
143
+ * `message` are short plain text; `link` adds a button back to the page.
144
+ * Needs `publicSubmit`. Brydio decides when, how often and from whom.
145
+ */
146
+ confirmEmail: confirmEmailSchema.optional(),
147
+ /**
148
+ * Answers nobody can tie to who gave them (P13): `group` names a
149
+ * structured field (a number, choice, date, boolean, token or project)
150
+ * the answers are read by, a whole group at a time and only once it holds
151
+ * `minimum` answers (at least 5, the default). Brydio keeps no writer,
152
+ * cuts times to the day, tells no live change, and refuses an update, a
153
+ * batch, a watch and a create naming its own writer.
154
+ */
155
+ anonymous: anonymousSchema.optional(),
156
+ /** One of its string[] fields: the user ids who alone may read a record, when it names any (P16). */
157
+ readers: readersSchema.optional(),
158
+ /** One of its string[] fields: the user ids who alone may change a record, when it names any (DW06). */
159
+ editors: editorsSchema.optional(),
41
160
  });
42
161
  const screenSchema = z.object({
43
162
  /**
@@ -74,23 +193,67 @@ const customToolSchema = z.object({
74
193
  write: z.boolean().optional(),
75
194
  /** The collection it works on, when it works on one: its grant then needs that collection too. */
76
195
  collection: z.string().optional(),
196
+ /**
197
+ * Callable from a public page (P3). Its handler then runs for a visitor,
198
+ * whose `data` is held to `publicRead` and `publicSubmit` and who can use
199
+ * nothing else of the workspace's.
200
+ */
201
+ public: z.boolean().optional(),
77
202
  });
78
203
  const toolsSchema = z.object({
79
204
  /** Off only when the app supplies every tool itself (A3-F08). */
80
- generated: z.boolean().optional(),
205
+ /**
206
+ * Off only when the app supplies every tool itself. `"read"` keeps the
207
+ * generated reads (get, list, search) and leaves every write to the app's
208
+ * own tools, where its rules about who may change what live (DW06).
209
+ */
210
+ generated: z.union([z.boolean(), z.literal('read')]).optional(),
81
211
  custom: z.array(customToolSchema).max(MAX_CUSTOM_TOOLS).optional(),
82
212
  });
213
+ /** Most secrets one app may declare (ADR-A24). */
214
+ export const MAX_APP_SECRETS = 20;
215
+ /** The longest value one secret may hold, in characters. */
216
+ export const MAX_SECRET_CHARS = 8 * 1024;
217
+ /** A secret's name, as a handler asks for it: `api_key`. */
218
+ export const SECRET_NAME = /^[a-z][a-z0-9_]{0,59}$/;
219
+ /**
220
+ * A secret the app needs (ADR-A24): named here, never valued here. The value
221
+ * is entered in the app's settings by an administrator, or stored by the
222
+ * app's own handler with `secrets.set`, and only that app's handlers can read
223
+ * it, with `secrets.get`. A screen never can.
224
+ *
225
+ * `install` (the default) is one value for the whole install; `instance` is
226
+ * one per instance.
227
+ */
228
+ const secretSchema = z.object({
229
+ name: z.string().regex(SECRET_NAME, 'A secret name is lower case letters, digits and underscores, starting with a letter.'),
230
+ label: z.string().min(1).max(60),
231
+ description: z.string().max(300).optional(),
232
+ required: z.boolean().optional(),
233
+ scope: z.enum(['install', 'instance']).optional(),
234
+ });
83
235
  const grantsSchema = z.object({
84
236
  tools: z.array(z.string().max(100)).max(200).optional(),
85
237
  collections: z.array(z.string().max(100)).max(FIELD_LIMITS.collections + 1).optional(),
86
238
  host: z.array(z.string().max(60)).max(20).optional(),
87
239
  });
240
+ /** The `instances` rules an app may declare (CA10). */
241
+ export const INSTANCE_RULES = ['one-per-workspace'];
88
242
  const extensionShape = {
89
243
  placements: z.array(placementSchema).max(20).optional(),
90
244
  data: z.record(z.string(), collectionSchema).optional(),
91
245
  tools: toolsSchema.optional(),
92
246
  screens: z.record(z.string(), screenSchema).optional(),
93
247
  grants: grantsSchema.optional(),
248
+ /** The secrets its handlers read (ADR-A24): names only, never values. */
249
+ secrets: z.array(secretSchema).max(MAX_APP_SECRETS).optional(),
250
+ /**
251
+ * How many instances a workspace may keep (CA10). `"one-per-workspace"`:
252
+ * a single workspace instance, shown in the sidebar and on any project as
253
+ * a view of that project's records; never a project's or a person's own.
254
+ * Left out, as many as people make.
255
+ */
256
+ instances: z.enum(INSTANCE_RULES).optional(),
94
257
  /**
95
258
  * How records move when the schema changes between versions (A3-F07).
96
259
  * Checked against the previous version when a version is published, and
@@ -104,13 +267,6 @@ const extensionShape = {
104
267
  */
105
268
  sdk: z.string().max(MANIFEST_LIMITS.versionChars).regex(SEMVER_FORMAT).optional(),
106
269
  };
107
- /**
108
- * Everything wrong with an app's additions that a type cannot say.
109
- *
110
- * Exported on its own so E5's validator can fold the codes into its import
111
- * report; the zod schemas below run it too, so a parse never accepts what
112
- * this refuses.
113
- */
114
270
  export function dataProblems(additions, options = {}) {
115
271
  const problems = [];
116
272
  const collections = Object.entries(additions.data ?? {});
@@ -225,6 +381,38 @@ export function dataProblems(additions, options = {}) {
225
381
  }
226
382
  }
227
383
  }
384
+ // Open-schema collections (P5): the companion is declared, shaped as the
385
+ // host reads it, and defines one collection's fields at most.
386
+ const companions = new Map();
387
+ for (const [collection, declared] of collections) {
388
+ if (!declared.openSchema)
389
+ continue;
390
+ for (const problem of openSchemaProblems(collection, declared.openSchema, additions.data ?? {})) {
391
+ problems.push({ ...problem, collection });
392
+ }
393
+ const other = companions.get(declared.openSchema.fields);
394
+ if (other) {
395
+ problems.push({
396
+ code: 'data_open_fields_unknown',
397
+ collection,
398
+ message: `${declared.openSchema.fields} already defines ${other}'s fields; give ${collection} its own.`,
399
+ });
400
+ }
401
+ companions.set(declared.openSchema.fields, collection);
402
+ }
403
+ // A confirmation email names a string field of a collection visitors submit to (FO04).
404
+ for (const [collection, declared] of collections) {
405
+ problems.push(...confirmEmailProblems(collection, declared));
406
+ }
407
+ // An anonymous collection groups its answers by one of its structured fields, names nobody (P13).
408
+ for (const [collection, declared] of collections) {
409
+ problems.push(...anonymousProblems(collection, declared));
410
+ }
411
+ // A collection whose records name their readers names a list of user ids to keep them in (P16).
412
+ for (const [collection, declared] of collections) {
413
+ problems.push(...readersProblems(collection, declared));
414
+ problems.push(...editorsProblems(collection, declared));
415
+ }
228
416
  // What the app keeps must be what it asks to keep (A3-F06-S01): a
229
417
  // collection the grants leave out would be data a workspace never agreed to
230
418
  // hold, found only when the first write is refused.
@@ -241,14 +429,134 @@ export function dataProblems(additions, options = {}) {
241
429
  }
242
430
  }
243
431
  problems.push(...customToolProblems(additions, options));
432
+ problems.push(...secretProblems(additions, options));
433
+ problems.push(...instanceRuleProblems(additions));
244
434
  const screens = new Set(Object.keys(additions.screens ?? {}));
435
+ const placementKeys = new Set();
245
436
  for (const placement of additions.placements ?? []) {
437
+ const key = effectivePlacementKey(placement);
438
+ if (placementKeys.has(key)) {
439
+ problems.push({
440
+ code: 'placement_key_taken',
441
+ message: `Two placements use the key "${key}"; each independently addable placement needs its own key.`,
442
+ });
443
+ }
444
+ else {
445
+ placementKeys.add(key);
446
+ }
246
447
  if (!screens.has(placement.screen)) {
247
448
  problems.push({
248
449
  code: 'placement_screen_unknown',
249
450
  message: `A ${placement.kind} placement opens "${placement.screen}", which is not one of the app's screens.`,
250
451
  });
251
452
  }
453
+ // A card must say how big it can be drawn (CC11-F10-S01).
454
+ if (placement.kind === 'home' && !placement.sizes?.length) {
455
+ problems.push({
456
+ code: 'placement_home_sizes',
457
+ message: `The Home card "${placement.screen}" must say which sizes it draws at: small, medium or large.`,
458
+ });
459
+ }
460
+ if (placement.kind === 'project-widget' && !placement.sizes?.length) {
461
+ problems.push({
462
+ code: 'placement_widget_sizes',
463
+ message: `The project widget "${placement.screen}" must say which sizes it draws at: small, medium or large.`,
464
+ });
465
+ }
466
+ if (!SIZED_PLACEMENT_KINDS.includes(placement.kind) && placement.sizes?.length) {
467
+ problems.push({
468
+ code: 'placement_sizes_not_home',
469
+ message: `Only a Home card or a project widget has sizes; the ${placement.kind} placement "${placement.screen}" cannot.`,
470
+ });
471
+ }
472
+ if (options.retired && placement.kind === 'project-tab') {
473
+ problems.push({
474
+ code: 'placement_tab_retired',
475
+ message: 'Project tabs are retired; declare a project-widget with sizes instead.',
476
+ });
477
+ }
478
+ // A public page is one screen at its own address: nothing to list in a
479
+ // sidebar, and nothing for an admin to fill in when it is placed.
480
+ if (placement.kind === 'public-page' && (placement.children || placement.settings)) {
481
+ problems.push({
482
+ code: 'placement_public_shape',
483
+ message: `The public page "${placement.screen}" can have no children or settings: it is one screen at its own address.`,
484
+ });
485
+ }
486
+ // A chat card is drawn at the message's own size, in a message nobody
487
+ // places by hand (FO03): nothing to size, configure or list.
488
+ if (placement.kind === 'chat-card' && (placement.sizes?.length || placement.children || placement.settings)) {
489
+ problems.push({
490
+ code: 'placement_chat_card_shape',
491
+ message: `The chat card "${placement.screen}" cannot have sizes, children or settings.`,
492
+ });
493
+ }
494
+ }
495
+ // A public page with nothing public could show a visitor nothing at all.
496
+ if ((additions.placements ?? []).some(placement => placement.kind === 'public-page')) {
497
+ const publicData = Object.values(additions.data ?? {}).some(declared => declared.publicRead || declared.publicSubmit);
498
+ const publicTool = (additions.tools?.custom ?? []).some(tool => tool.public);
499
+ if (!publicData && !publicTool) {
500
+ problems.push({
501
+ code: 'placement_public_nothing',
502
+ message: 'A public page needs something a visitor may use: mark a collection publicRead or publicSubmit, or a custom tool public.',
503
+ });
504
+ }
505
+ }
506
+ problems.push(...folderProblems(additions));
507
+ return problems;
508
+ }
509
+ /**
510
+ * A folder that nests or creates (ADR-A21) must stay within
511
+ * `MAX_FOLDER_DEPTH`, and each "New …" must name a tool the app has that
512
+ * changes records. Only the new keys are checked: a published manifest's
513
+ * existing folder still reads as it did.
514
+ */
515
+ function folderProblems(additions) {
516
+ const problems = [];
517
+ const custom = new Map((additions.tools?.custom ?? []).map(tool => [tool.name, tool]));
518
+ const generatedWrites = additions.tools?.generated === false || additions.tools?.generated === 'read'
519
+ ? new Set()
520
+ : new Set(Object.entries(additions.data ?? {}).flatMap(([name, declared]) => {
521
+ const label = labelOf(name, declared.label);
522
+ return [`create_${label}`, `update_${label}`, `delete_${label}`, `batch_${label}s`];
523
+ }));
524
+ const generatedReads = additions.tools?.generated === false
525
+ ? new Set()
526
+ : new Set(Object.entries(additions.data ?? {}).flatMap(([name, declared]) => {
527
+ const label = labelOf(name, declared.label);
528
+ return [`get_${label}`, `list_${label}s`, `search_${label}s`];
529
+ }));
530
+ for (const placement of additions.placements ?? []) {
531
+ const children = placement.children;
532
+ if (!children)
533
+ continue;
534
+ const depth = 1 + (children.nested?.length ?? 0);
535
+ if (depth > MAX_FOLDER_DEPTH) {
536
+ problems.push({
537
+ code: 'placement_children_too_deep',
538
+ message: `The "${placement.screen}" folder nests ${depth} levels deep; a sidebar folder may nest at most ${MAX_FOLDER_DEPTH}.`,
539
+ });
540
+ }
541
+ const creates = [children.create, ...(children.nested ?? []).map(level => level.create)];
542
+ for (const create of creates) {
543
+ if (!create)
544
+ continue;
545
+ const own = custom.get(create.tool);
546
+ const reads = own ? own.write !== true : generatedReads.has(create.tool);
547
+ if (!own && !reads && !generatedWrites.has(create.tool)) {
548
+ problems.push({
549
+ code: 'placement_create_tool_unknown',
550
+ message: `The "${placement.screen}" folder creates with ${create.tool}, which is not one of the app's tools.`,
551
+ });
552
+ }
553
+ else if (reads) {
554
+ problems.push({
555
+ code: 'placement_create_not_write',
556
+ message: `The "${placement.screen}" folder creates with ${create.tool}, which only reads: name a tool that makes records, or mark a custom one write: true.`,
557
+ });
558
+ }
559
+ }
252
560
  }
253
561
  return problems;
254
562
  }
@@ -268,18 +576,28 @@ function customToolProblems(additions, options) {
268
576
  : new Set(Object.entries(additions.data ?? {}).flatMap(([name, declared]) => {
269
577
  const label = labelOf(name, declared.label);
270
578
  const plural = `${label}s`;
271
- return [
272
- `create_${label}`,
273
- `update_${label}`,
274
- `get_${label}`,
275
- `delete_${label}`,
276
- `list_${plural}`,
277
- `search_${plural}`,
278
- `batch_${plural}`,
279
- ];
579
+ const reads = [`get_${label}`, `list_${plural}`, `search_${plural}`];
580
+ // With only reads generated, the write names are the app's to use.
581
+ return additions.tools?.generated === 'read'
582
+ ? reads
583
+ : [...reads, `create_${label}`, `update_${label}`, `delete_${label}`, `batch_${plural}`];
280
584
  }));
281
585
  const seen = new Set();
282
586
  const granted = additions.grants?.tools ?? [];
587
+ // Another app's tool, asked for by its assistant name `<slug>__<tool>`
588
+ // (FO07): never an unknown custom tool of this app, but naming the app
589
+ // itself would be a way round its own grants.
590
+ const name = additions.name;
591
+ const own = typeof name === 'string' ? appToolPrefix(name) : null;
592
+ for (const grant of granted) {
593
+ const qualified = crossAppTool(grant);
594
+ if (qualified && own !== null && qualified.app === own) {
595
+ problems.push({
596
+ code: 'grant_tool_cross_app_self',
597
+ message: `${grant} names this app's own tool: ask for ${qualified.tool} instead.`,
598
+ });
599
+ }
600
+ }
283
601
  for (const tool of custom) {
284
602
  if (generated.has(tool.name) || seen.has(tool.name)) {
285
603
  problems.push({
@@ -316,20 +634,86 @@ function customToolProblems(additions, options) {
316
634
  }
317
635
  return problems;
318
636
  }
637
+ /**
638
+ * Another installed app's tool, as `grants.tools` names it (FO07): the name
639
+ * the assistant knows it by, `<slug>__<tool>`. Null for anything else.
640
+ * A handler calls it with `tools.call('<slug>__<tool>', input)`.
641
+ */
642
+ export function crossAppTool(name) {
643
+ const at = name.indexOf('__');
644
+ if (at <= 0 || at + 2 >= name.length)
645
+ return null;
646
+ return { app: name.slice(0, at), tool: name.slice(at + 2) };
647
+ }
648
+ /** An app's name as the front of its tools' assistant names: `issue-tracker` → `issue_tracker`. */
649
+ export const appToolPrefix = (name) => name
650
+ .replace(/[^A-Za-z0-9_]+/g, '_')
651
+ .replace(/_+/g, '_')
652
+ .replace(/^_+|_+$/g, '');
653
+ /**
654
+ * Each secret declared once, and asked for (ADR-A24): an app that declares
655
+ * secrets without the `secrets` host grant could never read one.
656
+ */
657
+ /**
658
+ * One instance per workspace is added once, from the workspace sidebar
659
+ * (CA10): an app that says so and offers no sidebar item could never be
660
+ * added at all.
661
+ */
662
+ function instanceRuleProblems(additions) {
663
+ if (additions.instances !== 'one-per-workspace')
664
+ return [];
665
+ if ((additions.placements ?? []).some(one => one.kind === 'workspace-sidebar'))
666
+ return [];
667
+ return [
668
+ {
669
+ code: 'instances_needs_sidebar',
670
+ message: 'An app kept once per workspace is added from the workspace sidebar: add a "workspace-sidebar" placement.',
671
+ },
672
+ ];
673
+ }
674
+ function secretProblems(additions, options) {
675
+ const problems = [];
676
+ const secrets = additions.secrets ?? [];
677
+ const seen = new Set();
678
+ for (const secret of secrets) {
679
+ if (seen.has(secret.name)) {
680
+ problems.push({
681
+ code: 'secret_name_taken',
682
+ field: secret.name,
683
+ message: `The secret ${secret.name} is declared twice; keep one.`,
684
+ });
685
+ }
686
+ seen.add(secret.name);
687
+ }
688
+ const host = additions.grants?.host ?? [];
689
+ if (options.grants !== false && secrets.length && !host.includes('secrets') && !host.includes('*')) {
690
+ problems.push({
691
+ code: 'grant_secrets_missing',
692
+ message: 'The app declares secrets but does not ask to read them: add "secrets" to grants.host.',
693
+ });
694
+ }
695
+ return problems;
696
+ }
319
697
  const refuse = (additions, ctx, options = {}) => {
320
698
  for (const problem of dataProblems(additions, options)) {
321
699
  ctx.addIssue({
322
700
  code: 'custom',
323
701
  message: problem.message,
324
- path: problem.code === 'grant_tool_missing'
702
+ path: problem.code === 'grant_tool_missing' || problem.code === 'grant_tool_cross_app_self'
325
703
  ? ['grants', 'tools']
326
- : problem.code.startsWith('grant_')
327
- ? ['grants', 'collections']
328
- : problem.code.startsWith('custom_')
329
- ? ['tools', 'custom']
330
- : problem.collection
331
- ? ['data', problem.collection, ...(problem.field ? ['schema', problem.field] : [])]
332
- : [],
704
+ : problem.code === 'grant_secrets_missing'
705
+ ? ['grants', 'host']
706
+ : problem.code === 'secret_name_taken'
707
+ ? ['secrets']
708
+ : problem.code === 'instances_needs_sidebar'
709
+ ? ['instances']
710
+ : problem.code.startsWith('grant_')
711
+ ? ['grants', 'collections']
712
+ : problem.code.startsWith('custom_')
713
+ ? ['tools', 'custom']
714
+ : problem.collection
715
+ ? ['data', problem.collection, ...(problem.field ? ['schema', problem.field] : [])]
716
+ : [],
333
717
  params: { code: problem.code },
334
718
  });
335
719
  }
@@ -344,6 +728,14 @@ export const manifestExtensionsSchema = z.object(extensionShape).superRefine((ad
344
728
  export const storedExtensionsSchema = z.object(extensionShape).superRefine((additions, ctx) => refuse(additions, ctx, { grants: false }));
345
729
  /** E5's manifest with the additions: the whole `.brydio/app.json` of an app. */
346
730
  export const appManifestSchema = manifestSchema.extend(extensionShape).superRefine((additions, ctx) => refuse(additions, ctx));
731
+ /**
732
+ * A manifest being written now, as `brydio validate`, `build` and `dev` read
733
+ * it: the same, and nothing retired (`placement_tab_retired`) — which a
734
+ * published version may still hold.
735
+ */
736
+ export const newAppManifestSchema = manifestSchema
737
+ .extend(extensionShape)
738
+ .superRefine((additions, ctx) => refuse(additions, ctx, { retired: true }));
347
739
  /**
348
740
  * The singular a collection's tools are named with: the manifest's, else the
349
741
  * collection's name with a trailing "s" taken off (`issues` → `issue`).
@@ -360,8 +752,22 @@ export function labelOf(collection, label) {
360
752
  */
361
753
  export function collectionsOf(manifest) {
362
754
  const parsed = storedExtensionsSchema.parse({ data: manifest.data ?? {} });
755
+ const owners = new Map(Object.entries(parsed.data ?? {}).flatMap(([name, declared]) => declared.openSchema ? [[declared.openSchema.fields, { name, flag: declared.openSchema }]] : []));
363
756
  return Object.entries(parsed.data ?? {}).map(([name, declared]) => {
364
- const fields = Object.fromEntries(Object.entries(declared.schema).map(([field, raw]) => [field, parseFieldType(raw)]));
757
+ const owner = owners.get(name);
758
+ // The field naming a row's table is kept in plain on both sides, so a
759
+ // table is filtered and counted without decrypting a row (P5).
760
+ const tableField = declared.openSchema?.table ?? owner?.flag.table;
761
+ const fields = Object.fromEntries(Object.entries(declared.schema).map(([field, raw]) => {
762
+ const type = parseFieldType(raw);
763
+ if (field === tableField)
764
+ return [field, { ...type, plain: true }];
765
+ // A record's readers or editors may name a whole team (P16, DW06).
766
+ return [
767
+ field,
768
+ (field === declared.readers || field === declared.editors) && type.kind === 'string[]' ? { ...type, maxEntries: READERS_LIMIT } : type,
769
+ ];
770
+ }));
365
771
  const label = labelOf(name, declared.label);
366
772
  const names = Object.keys(fields);
367
773
  return {
@@ -373,6 +779,13 @@ export function collectionsOf(manifest) {
373
779
  sortable: names.filter(field => isSortable(fields[field])),
374
780
  search: declared.search ?? [],
375
781
  projectField: names.find(field => fields[field].kind === 'project') ?? null,
782
+ ...(declared.openSchema
783
+ ? { openSchema: { fields: declared.openSchema.fields, table: declared.openSchema.table ?? null } }
784
+ : {}),
785
+ ...(owner ? { definesFieldsOf: owner.name } : {}),
786
+ ...(declared.anonymous ? { anonymous: anonymousSpec(declared.anonymous) } : {}),
787
+ ...(declared.readers ? { readers: declared.readers } : {}),
788
+ ...(declared.editors ? { editors: declared.editors } : {}),
376
789
  };
377
790
  });
378
791
  }
package/src/secrets.d.ts CHANGED
@@ -30,3 +30,17 @@ export interface SecretFound {
30
30
  export declare function secretsInJson(document: unknown, at: string): SecretFound[];
31
31
  /** Every secret declared in a bundle's files, as the server finds them. */
32
32
  export declare function findSecrets(files: ReadonlyMap<string, Uint8Array>, root?: string): SecretFound[];
33
+ /**
34
+ * The server's sentence for `developer_key_in_bundle` (ADR-A22), word for
35
+ * word: `DEVELOPER_KEY_IN_BUNDLE` in Brydio's `app-publish.service.ts`.
36
+ */
37
+ export declare const DEVELOPER_KEY_MESSAGE = "That package contains a Brydio developer API key. A key belongs on your own server, never in an app: revoke it in Settings \u203A Developer, and call Brydio\u2019s model from a handler with the model grant instead.";
38
+ /** Whether a text holds a Brydio developer API key. */
39
+ export declare const holdsDeveloperKey: (text: string) => boolean;
40
+ /**
41
+ * The first file holding a developer API key, by path, as Brydio's publish
42
+ * route finds it (`developerKeyIn`). Unlike the declaration scan, every file
43
+ * is read, scripts included: the key's shape is exact enough that a match is
44
+ * a key, not a guess, and no part of an app may hold one (ADR-A24).
45
+ */
46
+ export declare function developerKeyIn(files: ReadonlyMap<string, Uint8Array>): string | null;