@fabrika/check 0.6.0 → 0.7.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.
@@ -8,6 +8,7 @@ import {
8
8
  type AnyMount,
9
9
  attachmentOutput,
10
10
  type Builder,
11
+ type CapabilityDeclaration,
11
12
  type CronJob,
12
13
  type CspDeclaration,
13
14
  type DeclaredDeclaration,
@@ -15,7 +16,7 @@ import {
15
16
  type DimensionDef,
16
17
  type Export,
17
18
  type ExportAccessDeclaration,
18
- type FileCollection,
19
+ type FileKind,
19
20
  type ImportDeclaration,
20
21
  type KitImportDeclaration,
21
22
  kitImportsSection,
@@ -24,11 +25,14 @@ import {
24
25
  type ProcedureDeclaration,
25
26
  type ProcedureType,
26
27
  type QueryTree,
28
+ redirect,
27
29
  type RoleDef,
28
30
  type Schema,
29
31
  type SpaAccessDeclaration,
30
32
  type Surface,
31
33
  SURFACE_SECTIONS,
34
+ type TokenPurpose,
35
+ type TokenPurposes,
32
36
  unknownOptions,
33
37
  type Vocabulary,
34
38
  } from '@fabrika/app/contract'
@@ -67,14 +71,16 @@ class Refused {
67
71
  const MAIL_ALLOWED =
68
72
  "a one-line subject, a text with {{actionUrl}} and an optional HTML body of the e-mail subset, naming only the message's placeholders"
69
73
 
70
- const MOUNT_BUILDERS = ['rpc', 'link', 'spa', 'health', 'form', 'webhook'] as const
74
+ const MOUNT_BUILDERS = ['rpc', 'link', 'spa', 'health', 'webhook'] as const
71
75
  const MOUNT_ALLOWED = `one of c.${MOUNT_BUILDERS.join(', c.')}(…)`
72
- const KIT_MOUNT_ALLOWED = 'one of c.rpc, c.spa, c.health, c.form(…), or a const of app.link(…) or app.webhook(…)'
76
+ const KIT_MOUNT_ALLOWED = 'one of c.rpc, c.spa, c.health(…), or a const of app.link(…) or app.webhook(…)'
73
77
  const CONTRACT_ALLOWED = 'export const contract = app.contract((c) => ({ … })), or defineContract(vocabulary, (c) => ({ … }))'
74
78
 
75
79
  /** Which builders a surface is written with: `defineContract`'s `c`, or the staged kit's (`app.*` and its `c`). */
76
80
  type Form = 'surface' | 'kit'
77
- const ACCESS_ALLOWED = '{ member: true }, { action, over }, { action, in, from }, { action, on, from }, { action, creates } or { action, app: true }'
81
+ const ACCESS_ALLOWED =
82
+ '{ member: true }, { action, over }, { action, in, from }, { action, on, from }, { action, creates }, { action, app: true }, { capabilities: { <name>: … } } or { public: true }'
83
+ const CAPABILITY_ALLOWED = '{ action, over }, { action, in, from } or { action, on, from }'
78
84
 
79
85
  type Entries = ReadonlyMap<string, LiteralValue>
80
86
 
@@ -127,8 +133,10 @@ class SurfaceReader {
127
133
  }
128
134
  const vocabulary = this.#vocabulary(app.vocabulary)
129
135
  const imports = this.#attempt(() => kitImports(app.options)) ?? undefined
136
+ const tokens = this.#attempt(() => kitTokens(app.options)) ?? undefined
130
137
  const surface = this.#surface(callback.result, 'kit')
131
- return { vocabulary, surface: imports === undefined ? surface : { ...surface, imports: kitImportsSection(imports, surface) } }
138
+ const withImports = imports === undefined ? surface : { ...surface, imports: kitImportsSection(imports, surface) }
139
+ return { vocabulary, surface: tokens === undefined ? withImports : { ...withImports, tokens } }
132
140
  }
133
141
 
134
142
  /** Runs one entry's read; a refusal is recorded and the reader goes on, so one read reports every entry. */
@@ -160,6 +168,12 @@ class SurfaceReader {
160
168
 
161
169
  /** A procedure's output: a schema, or `attachment({ … })`, built as `@fabrika/app`'s `attachment` builds it. */
162
170
  #output(value: LiteralValue | undefined, owner: BuilderValue): Schema {
171
+ if (value?.kind === 'redirect') {
172
+ const [definition] = args(value, 'redirect', 0, 1)
173
+ const options = definition === undefined ? new Map<string, LiteralValue>() : builderOptions(definition, value, 'redirect')
174
+ const origins = options.get('origins')
175
+ return redirect(origins === undefined ? {} : { origins: texts(origins, value, 'origins') })
176
+ }
163
177
  if (value?.kind !== 'attachment') {
164
178
  return this.#schema(value, owner, 'output')
165
179
  }
@@ -364,7 +378,7 @@ class SurfaceReader {
364
378
  prefix: text(prefix, at, 'the prefix'),
365
379
  dir: text(options.get('dir'), at, 'dir'),
366
380
  access: spaAccessDeclaration(options.get('access'), at),
367
- public: options.has('public') ? texts(options.get('public'), at, 'public') : undefined,
381
+ browserConfig: options.has('browserConfig') ? texts(options.get('browserConfig'), at, 'browserConfig') : undefined,
368
382
  unknownOptions: optionKeys(options, 'spa'),
369
383
  }
370
384
  }
@@ -372,39 +386,21 @@ class SurfaceReader {
372
386
  const [path] = args(at, 'c.health', 1, 1)
373
387
  return { kind: 'health', path: text(path, at, 'the path') }
374
388
  }
375
- case 'form': {
376
- const [path, optionsValue] = args(at, 'c.form', 2, 2)
377
- const options = builderOptions(optionsValue, at, 'c.form')
378
- return {
379
- kind: 'form',
380
- path: text(path, at, 'the path'),
381
- input: this.#schema(options.get('input'), at, 'input'),
382
- appendTo: text(options.get('appendTo'), at, 'appendTo'),
383
- maxBytes: optionalNumber(options.get('maxBytes'), 'maxBytes'),
384
- rate: formRate(options.get('rate')),
385
- honeypot: optionalText(options.get('honeypot'), 'honeypot'),
386
- challenge: formChallenge(options.get('challenge')),
387
- then: optionalText(options.get('then'), 'then'),
388
- ...crossOriginOption(options.get('crossOrigin')),
389
- ...formFiles(options.get('files')),
390
- unknownOptions: optionKeys(options, 'form'),
391
- }
392
- }
393
389
  case 'webhook': {
394
390
  const [path, optionsValue] = args(at, 'c.webhook', 2, 2)
395
391
  const options = builderOptions(optionsValue, at, 'c.webhook')
396
392
  const scheme = options.get('scheme')
397
- if (scheme?.kind !== 'string' || scheme.value !== 'github-sha256') {
398
- throw new Refused(scheme?.at ?? at.at, 'c.webhook needs a known scheme', "scheme: 'github-sha256'")
393
+ if (scheme === undefined) {
394
+ throw new Refused(at.at, 'c.webhook needs a scheme', "scheme: 'github-sha256', a preset, or { hmac: { … } }")
399
395
  }
400
396
  return {
401
397
  kind: 'webhook',
402
398
  path: text(path, at, 'the path'),
403
- scheme: scheme.value,
399
+ scheme: plain(scheme),
404
400
  boundTo: text(options.get('boundTo'), at, 'boundTo'),
405
401
  actions: texts(options.get('actions'), at, 'actions'),
406
402
  input: this.#schema(options.get('input'), at, 'input'),
407
- maxBytes: optionalNumber(options.get('maxBytes'), 'maxBytes'),
403
+ ...limitsOption(options),
408
404
  unknownOptions: optionKeys(options, 'webhook'),
409
405
  }
410
406
  }
@@ -415,25 +411,42 @@ class SurfaceReader {
415
411
  #kitMount(value: LiteralValue): AnyMount {
416
412
  const builder = value.kind === 'builder' ? { name: value.name, kit: value.kit, args: value.args, at: value.at } : undefined
417
413
  if (builder?.kit === 'shell' && builder.name === 'rpc') {
418
- const [prefix, groupsValue] = args(builder, 'c.rpc', 2, 2)
414
+ const [prefix, groupsValue, optionsValue] = args(builder, 'c.rpc', 2, 3)
415
+ const options = optionsValue === undefined ? new Map<string, LiteralValue>() : builderOptions(optionsValue, builder, 'c.rpc')
416
+ const compatibility = options.get('compatibility')
417
+ const unknown = [...options.keys()].filter((key) => key !== 'compatibility')
418
+ if (unknown.length > 0) {
419
+ throw new Refused(
420
+ optionsValue?.at ?? builder.at,
421
+ `c.rpc('${text(prefix, builder, 'the prefix')}') takes no option '${unknown[0]}'`,
422
+ 'compatibility',
423
+ )
424
+ }
419
425
  const path = text(prefix, builder, 'the prefix')
420
426
  const read = this.#groups(groupsValue, builder)
421
427
  const [first] = read.groups
422
428
  if (first === undefined) {
423
429
  throw new Refused(groupsValue?.at ?? builder.at, `c.rpc('${path}') mounts no group`, `c.rpc('${path}', { <name>: <group> })`)
424
430
  }
425
- if (read.groups.some((group) => !sameCallers(group.callers, first.callers))) {
426
- throw new Refused(builder.at, 'every group of one RPC mount names the same callers, in the same order', "callers: ['human'] in each group")
431
+ const credentialed = read.groups.filter((group) => group.callers.length > 0)
432
+ const callers = credentialed[0]?.callers ?? []
433
+ if (credentialed.some((group) => !sameCallers(group.callers, callers))) {
434
+ throw new Refused(
435
+ builder.at,
436
+ 'every group of one RPC mount that names callers names the same ones, in the same order',
437
+ "callers: ['human'] in each group",
438
+ )
427
439
  }
428
440
  return {
429
441
  kind: 'rpc',
430
442
  prefix: path,
431
- callers: first.callers,
443
+ callers,
432
444
  procedures: read.procedures,
445
+ ...(compatibility === undefined ? {} : { compatibility: plain(compatibility) }),
433
446
  unknownOptions: [...new Set(read.groups.flatMap((group) => group.unknownOptions))],
434
447
  }
435
448
  }
436
- if (builder?.kit === 'shell' && (builder.name === 'spa' || builder.name === 'health' || builder.name === 'form')) {
449
+ if (builder?.kit === 'shell' && (builder.name === 'spa' || builder.name === 'health')) {
437
450
  return this.#mount(asSurface(builder))
438
451
  }
439
452
  if (builder?.kit === 'app' && builder.name === 'link') {
@@ -486,8 +499,19 @@ class SurfaceReader {
486
499
  'app.group({ callers }, (r) => ({ <name>: r.query({ … }) }))',
487
500
  )
488
501
  }
489
- const procedures = this.#tree(callback.result, at, 'endpoints', (leaf) => this.#procedure(leaf, 'endpoints', accessDeclaration))
490
- return { groups: [{ callers: rpcCallers(options.get('callers'), at), unknownOptions: optionKeys(options, 'rpc') }], procedures }
502
+ const callers = options.has('callers') ? rpcCallers(options.get('callers'), at) : []
503
+ const procedures = this.#tree(callback.result, at, 'endpoints', (leaf) => {
504
+ const procedure = this.#procedure(leaf, 'endpoints', accessDeclaration)
505
+ if (callers.length === 0 && !('public' in procedure.access)) {
506
+ throw new Refused(
507
+ leaf.at,
508
+ 'a group without callers holds public procedures only',
509
+ "app.group({ callers: ['human'] }, …), or access: { public: true }",
510
+ )
511
+ }
512
+ return procedure
513
+ })
514
+ return { groups: [{ callers, unknownOptions: optionKeys(options, 'rpc') }], procedures }
491
515
  }
492
516
  if (value?.kind !== 'object') {
493
517
  throw new Refused(
@@ -527,6 +551,17 @@ class SurfaceReader {
527
551
  return tree
528
552
  }
529
553
 
554
+ /** `http` as the kit holds it: its `query` a schema, every other field a plain value; `buildArtifact` checks them. */
555
+ #http(value: LiteralValue | undefined, owner: BuilderValue): { readonly http?: unknown } {
556
+ if (value === undefined) return {}
557
+ if (value.kind !== 'object') return { http: plain(value) }
558
+ const http: Record<string, unknown> = {}
559
+ for (const [key, entry] of value.entries) {
560
+ http[key] = key === 'query' ? this.#schema(entry, owner, 'http.query') : plain(entry)
561
+ }
562
+ return { http }
563
+ }
564
+
530
565
  #procedure<Access>(
531
566
  builder: BuilderValue,
532
567
  kit: Kit,
@@ -546,7 +581,8 @@ class SurfaceReader {
546
581
  input: input === undefined || input.kind === 'null' ? null : this.#schema(input, builder, 'input'),
547
582
  output: this.#output(options.get('output'), builder),
548
583
  access: access(options.get('access'), builder),
549
- ...crossOriginOption(options.get('crossOrigin')),
584
+ ...plainOptions(options, ['actions', 'admission', 'limits']),
585
+ ...this.#http(options.get('http'), builder),
550
586
  ...(kit === 'endpoints'
551
587
  ? { declared: declared(options), unknownOptions: kitOptionKeys(options, 'procedure') }
552
588
  : { unknownOptions: optionKeys(options, 'procedure') }),
@@ -555,29 +591,26 @@ class SurfaceReader {
555
591
 
556
592
  // ── Sections ────────────────────────────────────────────────────────────────────────────────
557
593
 
558
- #files(value: LiteralValue, form: Form): FileCollection<string> {
594
+ /**
595
+ * `c.files({ … })`: a kind of stored file. Every option but `types`, `maxBytes` and `scan` is unknown, as the kit
596
+ * records it, so `buildArtifact` refuses a file collection's `owner` in its own words.
597
+ */
598
+ #files(value: LiteralValue, form: Form): FileKind {
559
599
  const at =
560
600
  surfaceBuilder(form === 'kit' && value.kind === 'builder' && value.kit === 'shell' ? asSurface(value) : value, ['files'], 'c.files({ … })').value
561
- const [collection] = args(at, 'c.files', 1, 1)
562
- const options = builderOptions(collection, at, 'c.files')
563
- const link = options.get('link')
601
+ const [kind] = args(at, 'c.files', 1, 1)
602
+ const options = builderOptions(kind, at, 'c.files')
564
603
  const scan = options.get('scan')
565
604
  return {
566
- kind: 'files',
567
- owner: text(options.get('owner'), at, 'owner'),
568
- read: text(options.get('read'), at, 'read'),
569
- write: text(options.get('write'), at, 'write'),
570
- delete: text(options.get('delete'), at, 'delete'),
571
- maxBytes: numeric(options.get('maxBytes'), at, 'maxBytes'),
605
+ kind: 'file-kind',
572
606
  types: texts(options.get('types'), at, 'types'),
573
- maxPerOwner: optionalNumber(options.get('maxPerOwner'), 'maxPerOwner'),
574
- link: link === undefined ? undefined : fileLink(link, at),
607
+ maxBytes: numeric(options.get('maxBytes'), at, 'maxBytes'),
575
608
  scan: scan === undefined ? undefined : boolean(scan, 'scan'),
576
- unknownOptions: optionKeys(options, 'files'),
609
+ unknownOptions: optionKeys(options, 'fileKind'),
577
610
  }
578
611
  }
579
612
 
580
- #cron(value: LiteralValue): CronJob<string, string> {
613
+ #cron(value: LiteralValue): CronJob<string> {
581
614
  const at = surfaceBuilder(value, ['cron'], "c.cron('<schedule>', { … })").value
582
615
  const [schedule, optionsValue] = args(at, 'c.cron', 2, 2)
583
616
  const options = builderOptions(optionsValue, at, 'c.cron')
@@ -585,15 +618,14 @@ class SurfaceReader {
585
618
  kind: 'cron',
586
619
  schedule: text(schedule, at, 'the schedule'),
587
620
  actions: texts(options.get('actions'), at, 'actions'),
588
- scope: text(options.get('scope'), at, 'scope'),
589
- timeout: optionalText(options.get('timeout'), 'timeout'),
621
+ ...limitsOption(options),
590
622
  retries: optionalNumber(options.get('retries'), 'retries'),
591
623
  unknownOptions: optionKeys(options, 'cron'),
592
624
  }
593
625
  }
594
626
 
595
627
  /** A job of the kit: a const of `app.cron(schedule, { … })`, whose `.handle(…)` the slice removed. */
596
- #kitCron(value: LiteralValue): CronJob<string, string> {
628
+ #kitCron(value: LiteralValue): CronJob<string> {
597
629
  if (value.kind !== 'builder' || value.kit !== 'app' || value.name !== 'cron') {
598
630
  throw new Refused(value.at, `a ${describeKind(value)} where a job stands`, "a const of app.cron('<schedule>', { … })")
599
631
  }
@@ -673,7 +705,7 @@ function surfaceBuilder<const Name extends string>(
673
705
  }
674
706
 
675
707
  function args(
676
- builder: BuilderValue | Extract<LiteralValue, { kind: 'contract' | 'kit-contract' | 'attachment' }>,
708
+ builder: BuilderValue | Extract<LiteralValue, { kind: 'contract' | 'kit-contract' | 'attachment' | 'redirect' }>,
677
709
  call: string,
678
710
  min: number,
679
711
  max: number,
@@ -711,11 +743,35 @@ function declared(options: Entries): DeclaredDeclaration {
711
743
  unscoped: plain(options.get('unscoped')),
712
744
  connect: plain(options.get('connect')),
713
745
  issues: plain(options.get('issues')),
714
- then: plain(options.get('then')),
715
746
  mailer: plain(options.get('mailer')),
747
+ kicks: plain(options.get('kicks')),
748
+ binds: plain(options.get('binds')),
749
+ signs: plain(options.get('signs')),
750
+ egress: plain(options.get('egress')),
716
751
  })
717
752
  }
718
753
 
754
+ /** A webhook's or a job's `limits` as the plain value the builder copies, only when written. */
755
+ function limitsOption(options: Entries): { readonly limits?: unknown } {
756
+ const limits = options.get('limits')
757
+ return limits === undefined ? {} : { limits: plain(limits) }
758
+ }
759
+
760
+ /** The procedure options that hold plain values, each only when written, as the kit copies them. */
761
+ function plainOptions(
762
+ options: Entries,
763
+ keys: readonly ('actions' | 'admission' | 'limits' | 'http')[],
764
+ ): Partial<Record<(typeof keys)[number], unknown>> {
765
+ const read: Partial<Record<(typeof keys)[number], unknown>> = {}
766
+ for (const key of keys) {
767
+ const value = options.get(key)
768
+ if (value !== undefined) {
769
+ read[key] = plain(value)
770
+ }
771
+ }
772
+ return read
773
+ }
774
+
719
775
  /** A literal as the plain value the evaluated module holds; a declared field holds no schema or builder. */
720
776
  function plain(value: LiteralValue | undefined): unknown {
721
777
  if (value === undefined) {
@@ -738,7 +794,7 @@ function plain(value: LiteralValue | undefined): unknown {
738
794
  }
739
795
 
740
796
  const DECLARED_ALLOWED =
741
- "sql: 'read' | 'write', unscoped: { <table>: 'read' | 'write' }, connect: ['<import>'], issues: '<link mount>', then: '<cron job>', mailer: 'installation' | 'own'"
797
+ "sql: 'read' | 'write', unscoped: { <table>: 'read' | 'write' }, connect: ['<import>'], issues: '<link mount>', mailer: 'installation' | 'own', kicks: ['<cron job>'], binds: '<webhook>', signs: ['<token purpose>'], egress: ['https://<host>']"
742
798
 
743
799
  /** A builder of the kit read as the `defineContract` builder of the same name, which builds the same declaration. */
744
800
  const asSurface = (builder: BuilderValue): LiteralValue => ({
@@ -750,7 +806,8 @@ const asSurface = (builder: BuilderValue): LiteralValue => ({
750
806
  })
751
807
 
752
808
  interface ReadGroup {
753
- readonly callers: readonly [RpcCaller, ...RpcCaller[]]
809
+ /** None for a group of public procedures only. */
810
+ readonly callers: readonly RpcCaller[]
754
811
  readonly unknownOptions: readonly string[]
755
812
  }
756
813
 
@@ -765,7 +822,10 @@ function kitImports(options: LiteralValue | undefined): Record<string, KitImport
765
822
  if (options === undefined) {
766
823
  return undefined
767
824
  }
768
- const imports = strictFields(options, "defineApp's options", ['imports'], []).get('imports')
825
+ const imports = strictFields(options, "defineApp's options", [], ['imports', 'tokens']).get('imports')
826
+ if (imports === undefined) {
827
+ return undefined
828
+ }
769
829
  return Object.fromEntries([...entries(imports, options, 'imports')].map(([name, value]) => {
770
830
  const where = `import '${name}'`
771
831
  const declaration = strictFields(value, where, ['snapshot', 'procedures'], ['timeoutMs'])
@@ -784,6 +844,25 @@ function kitImports(options: LiteralValue | undefined): Record<string, KitImport
784
844
  }))
785
845
  }
786
846
 
847
+ /** The token purposes of `defineApp`'s options, each `token(Claims, { maxDays })`; `undefined` without any. */
848
+ function kitTokens(options: LiteralValue | undefined): TokenPurposes | undefined {
849
+ const tokens = options === undefined ? undefined : strictFields(options, "defineApp's options", [], ['imports', 'tokens']).get('tokens')
850
+ if (options === undefined || tokens === undefined) {
851
+ return undefined
852
+ }
853
+ return Object.fromEntries([...entries(tokens, options, 'tokens')].map(([purpose, value]): [string, TokenPurpose] => {
854
+ if (value.kind !== 'token') {
855
+ throw new Refused(value.at, `token purpose '${purpose}' is not built with token`, `${purpose}: token(Claims, { maxDays: 400 })`)
856
+ }
857
+ const [claims, definition] = value.args
858
+ if (claims?.kind !== 'schema' || definition === undefined || value.args.length !== 2) {
859
+ throw new Refused(value.at, `token purpose '${purpose}' takes its claims schema and its options`, `${purpose}: token(Claims, { maxDays: 400 })`)
860
+ }
861
+ const maxDays = numeric(strictFields(definition, `token '${purpose}'`, ['maxDays'], []).get('maxDays'), definition, 'maxDays')
862
+ return [purpose, { '~kind': 'token', claims: claims.schema, maxDays }]
863
+ }))
864
+ }
865
+
787
866
  const SECTIONS: ReadonlySet<string> = new Set(SURFACE_SECTIONS)
788
867
 
789
868
  function isSection(name: string): boolean {
@@ -857,13 +936,6 @@ function directoryOf(value: LiteralValue, owner: Owner): 'labels' {
857
936
  return directory
858
937
  }
859
938
 
860
- /** `crossOrigin` as written, `true` or a string; the build decides which a builder admits. Absent stays absent. */
861
- function crossOriginOption(value: LiteralValue | undefined): { readonly crossOrigin?: boolean | string } {
862
- if (value === undefined) return {}
863
- if (value.kind === 'boolean' || value.kind === 'string') return { crossOrigin: value.value }
864
- throw new Refused(value.at, `crossOrigin is a ${describeKind(value)}`, "crossOrigin: true, or crossOrigin: '*' on a form")
865
- }
866
-
867
939
  function optionalText(value: LiteralValue | undefined, field: string): string | undefined {
868
940
  return value === undefined ? undefined : text(value, value, field)
869
941
  }
@@ -897,13 +969,6 @@ function boolean(value: LiteralValue, field: string): boolean {
897
969
  return value.value
898
970
  }
899
971
 
900
- /** A collection's `link`: `true` or `false`, or the link mounts it names; the build refuses an empty list. */
901
- function fileLink(value: LiteralValue, owner: Owner): boolean | string[] {
902
- if (value.kind === 'boolean') return value.value
903
- if (value.kind !== 'array') throw new Refused(value.at, `link is a ${describeKind(value)}`, "link: true, or link: ['<link mount>']")
904
- return texts(value, owner, 'link')
905
- }
906
-
907
972
  function schema(value: LiteralValue | undefined, owner: Owner, field: string): Schema {
908
973
  if (value?.kind !== 'schema') {
909
974
  throw new Refused(
@@ -963,6 +1028,12 @@ function isApp(fields: Entries): boolean {
963
1028
  return hasKeys(fields, ['action', 'app']) && app?.kind === 'boolean' && app.value
964
1029
  }
965
1030
 
1031
+ /** `{ public: true }`: `public` is the literal `true`. */
1032
+ function isPublic(fields: Entries): boolean {
1033
+ const open = fields.get('public')
1034
+ return hasKeys(fields, ['public']) && open?.kind === 'boolean' && open.value
1035
+ }
1036
+
966
1037
  /** The one access form the object spells, with exactly its keys, as `buildArtifact` reads it. */
967
1038
  function accessDeclaration(value: LiteralValue | undefined, at: BuilderValue): AccessDeclaration {
968
1039
  const fields = accessFields(value, at, ACCESS_ALLOWED)
@@ -985,9 +1056,34 @@ function accessDeclaration(value: LiteralValue | undefined, at: BuilderValue): A
985
1056
  if (isApp(fields)) {
986
1057
  return { action: field('action'), app: true }
987
1058
  }
1059
+ if (isPublic(fields)) {
1060
+ return { public: true }
1061
+ }
1062
+ if (hasKeys(fields, ['capabilities'])) {
1063
+ return { capabilities: capabilityDeclarations(fields.get('capabilities'), value ?? at) }
1064
+ }
988
1065
  throw new Refused(value?.at ?? at.at, 'access is not one access form', ACCESS_ALLOWED)
989
1066
  }
990
1067
 
1068
+ /** `capabilities: { <name>: <form>, … }`: each one capability's form, by its name; `buildArtifact` checks the rest. */
1069
+ function capabilityDeclarations(value: LiteralValue | undefined, owner: Owner): Readonly<Record<string, CapabilityDeclaration>> {
1070
+ const declared: Record<string, CapabilityDeclaration> = {}
1071
+ for (const [name, form] of entries(value, owner, 'access.capabilities')) {
1072
+ const fields = entries(form, owner, `access.capabilities.${name}`)
1073
+ const field = (key: string): string => text(fields.get(key), form, `access.capabilities.${name}.${key}`)
1074
+ if (hasKeys(fields, ['action', 'over'])) {
1075
+ declared[name] = { action: field('action'), over: field('over') }
1076
+ } else if (hasKeys(fields, ['action', 'in', 'from'])) {
1077
+ declared[name] = { action: field('action'), in: field('in'), from: field('from') }
1078
+ } else if (hasKeys(fields, ['action', 'on', 'from'])) {
1079
+ declared[name] = { action: field('action'), on: field('on'), from: field('from') }
1080
+ } else {
1081
+ throw new Refused(form.at, `capability '${name}' is not one capability`, CAPABILITY_ALLOWED)
1082
+ }
1083
+ }
1084
+ return declared
1085
+ }
1086
+
991
1087
  /**
992
1088
  * An export procedure names its action in a dimension: the consumer's key holds exactly the actions, so `member` would
993
1089
  * hold none, and a v1 export declares one dimension, which `app` names none of.
@@ -1000,6 +1096,9 @@ function exportAccessDeclaration(value: LiteralValue | undefined, at: BuilderVal
1000
1096
  if ('app' in access) {
1001
1097
  throw new Refused(value?.at ?? at.at, 'an export procedure reads in one dimension', '{ action, over } (or in, on)')
1002
1098
  }
1099
+ if ('capabilities' in access || 'public' in access) {
1100
+ throw new Refused(value?.at ?? at.at, 'an export procedure names one action', '{ action, over } (or in, on)')
1101
+ }
1003
1102
  return access
1004
1103
  }
1005
1104
 
@@ -1047,57 +1146,6 @@ function importDeclaration(name: string, value: LiteralValue): ImportDeclaration
1047
1146
  }
1048
1147
  }
1049
1148
 
1050
- /** A form's `rate`, as `buildArtifact` reads it: per-minute counts, each optional. */
1051
- function formRate(value: LiteralValue | undefined): { perClient?: number; perForm?: number; bytesPerHour?: number } | undefined {
1052
- if (value === undefined) {
1053
- return undefined
1054
- }
1055
- const fields = strictFields(value, 'rate', [], ['perClient', 'perForm', 'bytesPerHour'])
1056
- const perClient = optionalNumber(fields.get('perClient'), 'perClient')
1057
- const perForm = optionalNumber(fields.get('perForm'), 'perForm')
1058
- const bytesPerHour = optionalNumber(fields.get('bytesPerHour'), 'bytesPerHour')
1059
- return {
1060
- ...(perClient === undefined ? {} : { perClient }),
1061
- ...(perForm === undefined ? {} : { perForm }),
1062
- ...(bytesPerHour === undefined ? {} : { bytesPerHour }),
1063
- }
1064
- }
1065
-
1066
- /** A form's `files`: each file field's collection and whether a submission must carry it; `buildArtifact` checks them. */
1067
- function formFiles(value: LiteralValue | undefined): { readonly files?: Record<string, { collection: string; required?: boolean }> } {
1068
- if (value === undefined) {
1069
- return {}
1070
- }
1071
- if (value.kind !== 'object') {
1072
- throw new Refused(value.at, `files is a ${describeKind(value)}`, "files: { photo: { collection: '<collection>' } }")
1073
- }
1074
- const files: Record<string, { collection: string; required?: boolean }> = {}
1075
- for (const [field, entry] of value.entries) {
1076
- const fields = strictFields(entry, `file '${field}'`, ['collection'], ['required'])
1077
- const required = fields.get('required')
1078
- files[field] = {
1079
- collection: text(fields.get('collection'), entry, 'collection'),
1080
- ...(required === undefined ? {} : { required: boolean(required, 'required') }),
1081
- }
1082
- }
1083
- return { files }
1084
- }
1085
-
1086
- /** A form's `challenge`: a provider of the closed list and the names of the application variables with its secret and site key. */
1087
- function formChallenge(value: LiteralValue | undefined): { provider: 'turnstile'; secret: string; siteKey?: string } | undefined {
1088
- if (value === undefined) {
1089
- return undefined
1090
- }
1091
- const fields = strictFields(value, 'challenge', ['provider', 'secret'], ['siteKey'])
1092
- const provider = fields.get('provider')
1093
- if (provider?.kind !== 'string' || provider.value !== 'turnstile') {
1094
- throw new Refused(provider?.at ?? value.at, 'challenge needs a known provider', "provider: 'turnstile'")
1095
- }
1096
- const secret = text(fields.get('secret'), value, 'secret')
1097
- const siteKey = fields.get('siteKey')
1098
- return siteKey === undefined ? { provider: provider.value, secret } : { provider: provider.value, secret, siteKey: text(siteKey, value, 'siteKey') }
1099
- }
1100
-
1101
1149
  function cspDeclaration(value: LiteralValue): CspDeclaration {
1102
1150
  const fields = strictFields(value, 'csp', [], ['connectSrc', 'imgSrc', 'frameAncestors', 'scriptSrc', 'frameSrc', 'styleSrc', 'fontSrc'])
1103
1151
  const sources = (key: string): CspSource[] | undefined => {
@@ -1,6 +1,7 @@
1
1
  // Reads the literal subset of `rules/literal.ts` into values, without executing the application: names resolve through
2
2
  // `ModuleGraph`, `z` chains build real zod schemas, `c.*` calls stay unapplied for `surface.ts`.
3
3
 
4
+ import { file, signedToken, WebhookSecret } from '@fabrika/app/contract'
4
5
  import type { z } from 'zod/v4'
5
6
  import { type AstNode, child, children, identifierName, isConstAssertion, type ParsedModule, staticKey } from '../ast'
6
7
  import type { Located, ModuleGraph } from '../graph'
@@ -56,6 +57,10 @@ export type LiteralValue =
56
57
  | { readonly kind: 'kit-contract'; readonly app: AppValue; readonly args: readonly LiteralValue[]; readonly at: Located }
57
58
  /** `attachment({ … })`, with its argument read; `surface.ts` builds the output schema the evaluated module holds. */
58
59
  | { readonly kind: 'attachment'; readonly args: readonly LiteralValue[]; readonly at: Located }
60
+ /** `redirect({ … })`, with its argument read; `surface.ts` builds the output schema the evaluated module holds. */
61
+ | { readonly kind: 'redirect'; readonly args: readonly LiteralValue[]; readonly at: Located }
62
+ /** `token(Claims, { maxDays })` of `defineApp`'s options, with its arguments read; `surface.ts` reads the purpose. */
63
+ | { readonly kind: 'token'; readonly args: readonly LiteralValue[]; readonly at: Located }
59
64
  /** A builder callback: its parameter is only ever a kit, so its body is read once, as a value. */
60
65
  | { readonly kind: 'callback'; readonly result: LiteralValue; readonly at: Located }
61
66
 
@@ -263,6 +268,11 @@ export class ValueReader {
263
268
  #identifier(located: Located, scope: Scope): LiteralValue | null {
264
269
  const name = identifierName(located.node) ?? ''
265
270
  const builder = this.#builderOf(located.module, name)
271
+ const imported = builder === 'value' ? this.#graph.index(located.module).imports.get(name)?.imported : undefined
272
+ const exported = imported === undefined || !Object.hasOwn(PACKAGE_SCHEMAS, imported) ? undefined : PACKAGE_SCHEMAS[imported]
273
+ if (exported !== undefined) {
274
+ return { kind: 'schema', schema: exported, nodes: 4, depth: 2, steps: [name], at: located }
275
+ }
266
276
  if (scope.has(name) || builder !== undefined || isKitName(this.#graph, located.module, name)) {
267
277
  this.#problems.add(located, `'${name}' used as a value`, `${name}.<builder>(…) calls only`)
268
278
  return null
@@ -326,6 +336,17 @@ export class ValueReader {
326
336
  return null
327
337
  case 'attachment':
328
338
  return this.#attachmentCall(located, links, scope)
339
+ case 'redirect':
340
+ return this.#redirectCall(located, links, scope)
341
+ case 'file':
342
+ return this.#fileCall(located, links, scope)
343
+ case 'value':
344
+ this.#problems.add(located, `${rootName} used other than as it is`, 'output: WebhookSecret')
345
+ return null
346
+ case 'token':
347
+ return this.#tokenCall(located, links, scope)
348
+ case 'signedToken':
349
+ return this.#signedTokenCall(located, links, scope)
329
350
  default:
330
351
  if (this.#isConstName(located.module, rootName) && links[0]?.kind === 'member') {
331
352
  return this.#schemaMethods(located, root, links, scope)
@@ -466,6 +487,50 @@ export class ValueReader {
466
487
  return args === null ? null : { kind: 'attachment', args, at: located }
467
488
  }
468
489
 
490
+ #redirectCall(located: Located, links: readonly Link[], scope: Scope): LiteralValue | null {
491
+ const [call] = links
492
+ if (call?.kind !== 'call' || links.length !== 1) {
493
+ this.#problems.add(located, 'redirect used other than as one call', "redirect() or redirect({ origins: ['https://…'] })")
494
+ return null
495
+ }
496
+ const args = this.#arguments(located.module, call.node, scope, () => null)
497
+ return args === null ? null : { kind: 'redirect', args, at: located }
498
+ }
499
+
500
+ #tokenCall(located: Located, links: readonly Link[], scope: Scope): LiteralValue | null {
501
+ const [call] = links
502
+ if (call?.kind !== 'call' || links.length !== 1) {
503
+ this.#problems.add(located, 'token used other than as one call', 'token(Claims, { maxDays: 400 })')
504
+ return null
505
+ }
506
+ const args = this.#arguments(located.module, call.node, scope, () => null)
507
+ return args === null ? null : { kind: 'token', args, at: located }
508
+ }
509
+
510
+ /** `signedToken('<purpose>')`: the schema `@fabrika/app`'s `signedToken` builds, so the artifact reads it as the runtime does. */
511
+ #signedTokenCall(located: Located, links: readonly Link[], scope: Scope): LiteralValue | null {
512
+ const [call] = links
513
+ const args = call?.kind === 'call' && links.length === 1 ? this.#arguments(located.module, call.node, scope, () => null) : null
514
+ const [purpose] = args ?? []
515
+ if (args === null || args.length !== 1 || purpose?.kind !== 'string') {
516
+ this.#problems.add(located, 'signedToken used other than as one call with the purpose', "signedToken('<purpose>')")
517
+ return null
518
+ }
519
+ return { kind: 'schema', schema: signedToken(purpose.value), nodes: 1, depth: 1, steps: ['signedToken'], at: located }
520
+ }
521
+
522
+ /** `file('<kind>')`: the schema `@fabrika/app`'s `file` builds, so the artifact reads the file field as the runtime does. */
523
+ #fileCall(located: Located, links: readonly Link[], scope: Scope): LiteralValue | null {
524
+ const [call] = links
525
+ const args = call?.kind === 'call' && links.length === 1 ? this.#arguments(located.module, call.node, scope, () => null) : null
526
+ const [kind] = args ?? []
527
+ if (args === null || args.length !== 1 || kind?.kind !== 'string') {
528
+ this.#problems.add(located, 'file used other than as one call with the kind', "file('<kind>')")
529
+ return null
530
+ }
531
+ return { kind: 'schema', schema: file(kind.value), nodes: 1, depth: 1, steps: ['file'], at: located }
532
+ }
533
+
469
534
  #contractCall(located: Located, links: readonly Link[], scope: Scope): LiteralValue | null {
470
535
  const [call] = links
471
536
  if (call?.kind !== 'call' || links.length !== 1) {
@@ -568,6 +633,9 @@ export class ValueReader {
568
633
  }
569
634
  }
570
635
 
636
+ /** The schemas `@fabrika/app/contract` exports for an output, by their exported name. */
637
+ const PACKAGE_SCHEMAS: Readonly<Record<string, z.ZodType>> = { WebhookSecret }
638
+
571
639
  interface SchemaStep {
572
640
  readonly name: string
573
641
  readonly call: AstNode
@@ -641,4 +709,8 @@ export const describeKind = (
641
709
  ? 'app.contract(…)'
642
710
  : value.kind === 'attachment'
643
711
  ? 'attachment(…)'
712
+ : value.kind === 'redirect'
713
+ ? 'redirect(…)'
714
+ : value.kind === 'token'
715
+ ? 'token(…)'
644
716
  : value.kind
@@ -15,7 +15,7 @@ const IDENTITY_FIELDS = new Set([
15
15
  'workspace_id',
16
16
  ])
17
17
  /** The contract builders whose options carry an `input`. */
18
- const ENDPOINT_BUILDERS = new Set(['query', 'mutation', 'form', 'webhook'])
18
+ const ENDPOINT_BUILDERS = new Set(['query', 'mutation', 'webhook'])
19
19
  const SHAPE_METHODS = new Set(['object', 'strictObject', 'looseObject', 'extend', 'safeExtend'])
20
20
  const MERGE_METHODS = new Set(['merge', 'and'])
21
21