@fabrika/app 0.9.0-dev.13 → 0.9.0-dev.15

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (89) hide show
  1. package/package.json +14 -9
  2. package/skill/SKILL.md +3 -2
  3. package/skill/references/app-setup.md +17 -9
  4. package/skill/references/endpoint.md +15 -2
  5. package/skill/references/errors.md +7 -6
  6. package/skill/references/jobs.md +10 -0
  7. package/skill/references/relations.md +145 -21
  8. package/skill/references/table-and-migration.md +4 -1
  9. package/skill/references/webhooks-links-connectors.md +2 -1
  10. package/src/build-contract-child.ts +16 -0
  11. package/src/build.ts +48 -2
  12. package/src/bun.ts +10 -0
  13. package/src/client/contract.ts +6 -4
  14. package/src/cloudflare/application.ts +3 -0
  15. package/src/contract/artifact-schema.ts +367 -299
  16. package/src/contract/attachment.ts +4 -3
  17. package/src/contract/build.ts +76 -18
  18. package/src/contract/compile.ts +3 -2
  19. package/src/contract/context.ts +2 -3
  20. package/src/contract/define.ts +19 -6
  21. package/src/contract/group.ts +18 -8
  22. package/src/contract/index.ts +1 -1
  23. package/src/contract/kit.ts +4 -3
  24. package/src/contract/problems.ts +4 -0
  25. package/src/contract/schema-shape.ts +14 -2
  26. package/src/contract/token.ts +4 -3
  27. package/src/disk-assets.ts +15 -3
  28. package/src/from-row.ts +12 -6
  29. package/src/implement/approved.ts +57 -0
  30. package/src/implement/attachment.ts +2 -1
  31. package/src/implement/boot.ts +118 -17
  32. package/src/implement/capability.ts +82 -12
  33. package/src/implement/dispatch.ts +265 -45
  34. package/src/implement/egress.ts +410 -9
  35. package/src/implement/faults.ts +1 -0
  36. package/src/implement/implement.ts +23 -3
  37. package/src/implement/invocation.ts +10 -9
  38. package/src/implement/project.ts +3 -1
  39. package/src/implement/tokens.ts +3 -2
  40. package/src/implement/types.ts +33 -10
  41. package/src/implement/webhook.ts +8 -0
  42. package/src/jobs/runner.ts +7 -2
  43. package/src/react/hooks.ts +12 -11
  44. package/src/react/provider.tsx +2 -1
  45. package/src/react/types.ts +2 -2
  46. package/src/schema/builder.ts +146 -0
  47. package/src/schema/data-schema.ts +365 -0
  48. package/src/schema/index.ts +18 -0
  49. package/src/schema/replay.ts +623 -0
  50. package/src/source-map-path.ts +21 -0
  51. package/src/testing/caller.ts +20 -9
  52. package/src/testing/kit.ts +3 -3
  53. package/src/testing/membership.ts +9 -5
  54. package/types/src/build-contract-child.d.ts +1 -0
  55. package/types/src/build.d.ts +16 -1
  56. package/types/src/client/contract.d.ts +3 -4
  57. package/types/src/cloudflare/application.d.ts +2 -0
  58. package/types/src/contract/artifact-schema.d.ts +8 -0
  59. package/types/src/contract/attachment.d.ts +3 -2
  60. package/types/src/contract/context.d.ts +2 -3
  61. package/types/src/contract/define.d.ts +16 -6
  62. package/types/src/contract/group.d.ts +14 -7
  63. package/types/src/contract/index.d.ts +1 -1
  64. package/types/src/contract/kit.d.ts +4 -5
  65. package/types/src/contract/problems.d.ts +1 -0
  66. package/types/src/contract/schema-shape.d.ts +3 -2
  67. package/types/src/contract/token.d.ts +3 -3
  68. package/types/src/from-row.d.ts +9 -5
  69. package/types/src/implement/approved.d.ts +11 -0
  70. package/types/src/implement/boot.d.ts +12 -0
  71. package/types/src/implement/capability.d.ts +14 -5
  72. package/types/src/implement/dispatch.d.ts +9 -1
  73. package/types/src/implement/egress.d.ts +36 -1
  74. package/types/src/implement/faults.d.ts +1 -0
  75. package/types/src/implement/implement.d.ts +19 -3
  76. package/types/src/implement/invocation.d.ts +3 -3
  77. package/types/src/implement/project.d.ts +2 -1
  78. package/types/src/implement/types.d.ts +17 -8
  79. package/types/src/jobs/runner.d.ts +3 -0
  80. package/types/src/react/hooks.d.ts +4 -5
  81. package/types/src/react/types.d.ts +2 -2
  82. package/types/src/schema/builder.d.ts +45 -0
  83. package/types/src/schema/data-schema.d.ts +124 -0
  84. package/types/src/schema/index.d.ts +3 -0
  85. package/types/src/schema/replay.d.ts +27 -0
  86. package/types/src/source-map-path.d.ts +4 -0
  87. package/types/src/testing/caller.d.ts +6 -1
  88. package/types/src/testing/kit.d.ts +2 -3
  89. package/types/src/testing/membership.d.ts +1 -1
@@ -17,6 +17,7 @@ import {
17
17
  fileKindsIn,
18
18
  isOwnWorkloadName,
19
19
  JOB_MAILERS,
20
+ JOB_SITE_PREFIX,
20
21
  LOCALES,
21
22
  mailTemplateProblems,
22
23
  MAX_CACHE_AGE_SECONDS,
@@ -24,9 +25,11 @@ import {
24
25
  type NumberShape,
25
26
  type OutputShape,
26
27
  parseEgressEntry,
28
+ PUBLIC_EGRESS,
27
29
  type RecordShape,
28
30
  type RowsTestArtifact,
29
31
  type SchemaShape,
32
+ SHARED_SHAPES_ENCODING,
30
33
  type StringShape,
31
34
  type TablePolicyArtifact,
32
35
  terminalIdentifyProblem,
@@ -63,77 +66,95 @@ const fileKindName = name.refine(
63
66
  /** IAM's own role keys win over an application role of the same key at resolution. */
64
67
  const roleKey = name.refine((key) => !BUILTIN_ROLE_KEYS.includes(key), 'a built-in IAM role key is not a contract role name')
65
68
 
66
- const stringShape: z.ZodType<StringShape> = z.strictObject({
67
- type: z.literal('string'),
68
- format: z.enum(['uuid', 'email', 'url', 'datetime', 'date', 'time', 'duration']).nullable(),
69
- minLength: z.int().nonnegative().nullable(),
70
- maxLength: z.int().nonnegative().nullable(),
71
- pattern: z.string().nullable(),
72
- startsWith: z.string().nullable(),
73
- endsWith: z.string().nullable(),
74
- includes: z.string().nullable(),
75
- })
69
+ /**
70
+ * The parser of a schema shape. Plain (`shared` null): every constraint present, null when unset, as `canonicalShape`
71
+ * writes it. Shared, as `encodeArtifact` writes it: a null constraint is absent, and `{ type: 'shared', index }` is the
72
+ * shape `shared[index]`, the same object wherever it is referenced. `shared` holds only the shapes parsed before, so a
73
+ * reference reaches back only, and no shape contains itself.
74
+ */
75
+ function shapeSchemaOf(shared: readonly SchemaShape[] | null): z.ZodType<SchemaShape> {
76
+ const absentIsNull = shared !== null
77
+ const nonNegative = orNull(z.int().nonnegative(), absentIsNull)
78
+ const text = orNull(z.string(), absentIsNull)
79
+ const bound = orNull(z.number(), absentIsNull)
80
+ const stringShape = z.strictObject({
81
+ type: z.literal('string'),
82
+ format: orNull(z.enum(['uuid', 'email', 'url', 'datetime', 'date', 'time', 'duration']), absentIsNull),
83
+ minLength: nonNegative,
84
+ maxLength: nonNegative,
85
+ pattern: text,
86
+ startsWith: text,
87
+ endsWith: text,
88
+ includes: text,
89
+ }) satisfies z.ZodType<StringShape>
90
+ const numberShape = z.strictObject({
91
+ type: z.literal('number'),
92
+ int: z.boolean(),
93
+ min: bound,
94
+ exclusiveMin: z.boolean(),
95
+ max: bound,
96
+ exclusiveMax: z.boolean(),
97
+ multipleOf: orNull(z.number().positive(), absentIsNull),
98
+ }) satisfies z.ZodType<NumberShape>
99
+ const forms = () =>
100
+ [
101
+ stringShape,
102
+ numberShape,
103
+ z.strictObject({ type: z.enum(['boolean', 'null']) }),
104
+ z.strictObject({ type: z.literal('literal'), value: z.union([z.string(), z.number(), z.boolean(), z.null()]) }),
105
+ z.strictObject({ type: z.literal('enum'), values: z.array(z.string()) }),
106
+ z.strictObject({ type: z.literal('array'), items: shape, minItems: nonNegative, maxItems: nonNegative }) satisfies z.ZodType<ArrayShape>,
107
+ z.strictObject({ type: z.literal('tuple'), items: z.array(shape), rest: orNull(shape, absentIsNull) }) satisfies z.ZodType<TupleShape>,
108
+ z.strictObject({ type: z.literal('record'), key: shape, value: shape }) satisfies z.ZodType<RecordShape>,
109
+ z.strictObject({ type: z.literal('object'), fields: z.record(z.string(), shape) }),
110
+ z.strictObject({ type: z.literal('optional'), inner: shape }),
111
+ z.strictObject({ type: z.literal('nullable'), inner: shape }),
112
+ z.strictObject({ type: z.literal('union'), options: z.array(shape) }),
113
+ z.strictObject({ type: z.literal('token'), purpose: name }),
114
+ z.strictObject({ type: z.literal('file'), kind: z.string().min(1) }),
115
+ ] as const
116
+ // Dispatched on `type`: one form per node, never a trial of each.
117
+ const shape: z.ZodType<SchemaShape> = shared === null
118
+ ? z.lazy(() => z.discriminatedUnion('type', forms()))
119
+ : z.lazy(() =>
120
+ z.discriminatedUnion('type', [...forms(), z.strictObject({ type: z.literal('shared'), index: z.int().nonnegative() })]).transform(
121
+ (written, context): SchemaShape => {
122
+ if (written.type !== 'shared') return written
123
+ const target = shared[written.index]
124
+ if (target === undefined) {
125
+ context.addIssue({ code: 'custom', message: `shape ${written.index} is not written before it is referenced` })
126
+ return z.NEVER
127
+ }
128
+ return target
129
+ },
130
+ )
131
+ )
132
+ return shape
133
+ }
76
134
 
77
- const numberShape: z.ZodType<NumberShape> = z.strictObject({
78
- type: z.literal('number'),
79
- int: z.boolean(),
80
- min: z.number().nullable(),
81
- exclusiveMin: z.boolean(),
82
- max: z.number().nullable(),
83
- exclusiveMax: z.boolean(),
84
- multipleOf: z.number().positive().nullable(),
85
- })
135
+ /** A constraint that is null when unset; absent stands for null where `absentIsNull`. */
136
+ function orNull<T extends z.ZodType>(schema: T, absentIsNull: boolean): z.ZodType<z.output<T> | null, z.input<T> | null | undefined> {
137
+ return absentIsNull ? schema.nullable().default(null) : schema.nullable()
138
+ }
86
139
 
87
140
  /** A `SchemaShape` read back as JSON. */
88
- export const schemaShapeSchema: z.ZodType<SchemaShape> = z.lazy(() =>
89
- z.union([
90
- stringShape,
91
- numberShape,
92
- z.strictObject({ type: z.enum(['boolean', 'null']) }),
93
- z.strictObject({ type: z.literal('literal'), value: z.union([z.string(), z.number(), z.boolean(), z.null()]) }),
94
- z.strictObject({ type: z.literal('enum'), values: z.array(z.string()) }),
95
- arrayShape,
96
- tupleShape,
97
- recordShape,
98
- z.strictObject({ type: z.literal('object'), fields: z.record(z.string(), schemaShapeSchema) }),
99
- z.strictObject({ type: z.literal('optional'), inner: schemaShapeSchema }),
100
- z.strictObject({ type: z.literal('nullable'), inner: schemaShapeSchema }),
101
- z.strictObject({ type: z.literal('union'), options: z.array(schemaShapeSchema) }),
102
- z.strictObject({ type: z.literal('token'), purpose: name }),
103
- z.strictObject({ type: z.literal('file'), kind: z.string().min(1) }),
104
- ])
105
- )
106
-
107
- const arrayShape: z.ZodType<ArrayShape> = z.lazy(() =>
108
- z.strictObject({
109
- type: z.literal('array'),
110
- items: schemaShapeSchema,
111
- minItems: z.int().nonnegative().nullable(),
112
- maxItems: z.int().nonnegative().nullable(),
113
- })
114
- )
115
-
116
- const tupleShape: z.ZodType<TupleShape> = z.lazy(() =>
117
- z.strictObject({ type: z.literal('tuple'), items: z.array(schemaShapeSchema), rest: schemaShapeSchema.nullable() })
118
- )
119
-
120
- const recordShape: z.ZodType<RecordShape> = z.lazy(() =>
121
- z.strictObject({ type: z.literal('record'), key: schemaShapeSchema, value: schemaShapeSchema })
122
- )
123
-
124
- const attachmentShape: z.ZodType<AttachmentShape> = z.strictObject({
125
- type: z.literal('attachment'),
126
- format: z.enum(['csv', 'xlsx']),
127
- filename: name,
128
- maxBytes: z.int().positive(),
129
- maxRows: z.int().positive(),
130
- columns: z.array(z.strictObject({ name: z.string(), shape: schemaShapeSchema })).min(1),
131
- })
141
+ export const schemaShapeSchema: z.ZodType<SchemaShape> = shapeSchemaOf(null)
132
142
 
133
143
  /** What a procedure answers: a schema shape, or an attachment's file. */
134
- const redirectShape = z.strictObject({ type: z.literal('redirect'), origins: z.array(z.string().startsWith('https://')) })
144
+ function outputShapeSchemaOf(shape: z.ZodType<SchemaShape>): z.ZodType<OutputShape> {
145
+ const attachmentShape: z.ZodType<AttachmentShape> = z.strictObject({
146
+ type: z.literal('attachment'),
147
+ format: z.enum(['csv', 'xlsx']),
148
+ filename: name,
149
+ maxBytes: z.int().positive(),
150
+ maxRows: z.int().positive(),
151
+ columns: z.array(z.strictObject({ name: z.string(), shape })).min(1),
152
+ })
153
+ const redirectShape = z.strictObject({ type: z.literal('redirect'), origins: z.array(z.string().startsWith('https://')) })
154
+ return z.union([shape, attachmentShape, redirectShape])
155
+ }
135
156
 
136
- export const outputShapeSchema: z.ZodType<OutputShape> = z.union([schemaShapeSchema, attachmentShape, redirectShape])
157
+ export const outputShapeSchema: z.ZodType<OutputShape> = outputShapeSchemaOf(schemaShapeSchema)
137
158
 
138
159
  const caller = z.union([z.enum(['human', 'machine', 'link']), z.templateLiteral(['app:', z.string().min(1)])])
139
160
  const rpcCaller = z.enum(['human', 'machine'])
@@ -169,79 +190,86 @@ const endpointCacheSchema = z.union([
169
190
  z.strictObject({ maxAgeSeconds: z.int().min(1).max(MAX_CACHE_AGE_SECONDS) }),
170
191
  ])
171
192
 
172
- const rowBase = {
173
- id: name,
174
- source: z.strictObject({ kind: z.enum(['mount', 'export', 'files']), name }),
175
- method: z.enum(['GET', 'POST']),
176
- path: z.string().startsWith('/'),
177
- admission: z.strictObject({ contentTypes: z.tuple([name], name), maxBytes: z.int().positive().nullable() }).nullable(),
178
- input: schemaShapeSchema.nullable(),
179
- output: outputShapeSchema.nullable(),
180
- response: z.enum(['file', 'inline-file']).optional(),
193
+ function rowBaseOf(shape: z.ZodType<SchemaShape>, output: z.ZodType<OutputShape>) {
194
+ return {
195
+ id: name,
196
+ source: z.strictObject({ kind: z.enum(['mount', 'export', 'files']), name }),
197
+ method: z.enum(['GET', 'POST']),
198
+ path: z.string().startsWith('/'),
199
+ admission: z.strictObject({ contentTypes: z.tuple([name], name), maxBytes: z.int().positive().nullable() }).nullable(),
200
+ input: shape.nullable(),
201
+ output: output.nullable(),
202
+ response: z.enum(['file', 'inline-file']).optional(),
203
+ }
181
204
  }
182
205
 
183
- const endpointRow: z.ZodType<EndpointRow> = z.union([
184
- z.strictObject({
185
- ...rowBase,
186
- kind: z.enum(['query', 'mutation', 'spa', 'upload', 'download']),
187
- callers: z.tuple([caller], caller),
188
- requirement,
189
- crossOrigin: z.literal('environment').optional(),
190
- }),
191
- z.strictObject({
192
- ...rowBase,
193
- kind: z.enum(['health', 'form', 'webhook', 'link-spa']),
194
- callers: z.tuple([]),
195
- requirement: z.null(),
196
- crossOrigin: z.enum(['environment', 'any']).optional(),
197
- authorization: z.literal('forward').optional(),
198
- }).refine((row) => row.authorization === undefined || row.kind === 'webhook', "only a webhook forwards the request's Authorization"),
199
- // A public procedure is a mount's procedure anyone calls: it admits a body and answers its output.
200
- z.strictObject({
201
- ...rowBase,
202
- kind: z.literal('public'),
203
- source: z.strictObject({ kind: z.literal('mount'), name }),
204
- output: outputShapeSchema,
205
- callers: z.tuple([]),
206
- requirement: z.null(),
207
- crossOrigin: z.enum(['environment', 'any']).optional(),
208
- cache: endpointCacheSchema.optional(),
209
- }).refine((row) => row.cache === undefined || row.method === 'GET', 'only a GET answer is cached'),
210
- // The framework's own GET that issues the ALTCHA challenge of the public procedure its source names: no body, no schemas.
211
- z.strictObject({
212
- ...rowBase,
213
- kind: z.literal('public'),
214
- source: z.strictObject({ kind: z.literal('challenge'), name }),
215
- method: z.literal('GET'),
216
- admission: z.null(),
217
- input: z.null(),
218
- output: z.null(),
219
- callers: z.tuple([]),
220
- requirement: z.null(),
221
- crossOrigin: z.enum(['environment', 'any']).optional(),
222
- }),
223
- // A public SPA is a fixed static row: GET only, no body, no schemas.
224
- z.strictObject({
225
- ...rowBase,
226
- kind: z.literal('public-spa'),
227
- method: z.literal('GET'),
228
- admission: z.null(),
229
- input: z.null(),
230
- output: z.null(),
231
- callers: z.tuple([]),
232
- requirement: z.null(),
233
- }),
234
- ]).refine(
235
- // Only a procedure answers a stored file, and exactly when its output is one.
236
- (row) => (row.response !== undefined) === (row.output?.type === 'file') && (row.response === undefined || FILE_RESPONSE_KINDS.includes(row.kind)),
237
- 'only a procedure whose output is a file answers a stored file',
238
- ).refine(
239
- // Only an RPC procedure, a public procedure and a form open to another origin, and only the anonymous two to any (ADR-0022).
240
- (row) =>
241
- !('crossOrigin' in row) || row.crossOrigin === undefined
242
- || (CROSS_ORIGIN_KINDS.includes(row.kind) && (row.crossOrigin !== 'any' || ANY_ORIGIN_KINDS.includes(row.kind))),
243
- 'this endpoint kind cannot be called cross-origin',
244
- )
206
+ /** An endpoint row whose schemas `shape` parses. */
207
+ function endpointRowOf(shape: z.ZodType<SchemaShape>): z.ZodType<EndpointRow> {
208
+ const output = outputShapeSchemaOf(shape)
209
+ const rowBase = rowBaseOf(shape, output)
210
+ return z.union([
211
+ z.strictObject({
212
+ ...rowBase,
213
+ kind: z.enum(['query', 'mutation', 'spa', 'upload', 'download']),
214
+ callers: z.tuple([caller], caller),
215
+ requirement,
216
+ crossOrigin: z.literal('environment').optional(),
217
+ }),
218
+ z.strictObject({
219
+ ...rowBase,
220
+ kind: z.enum(['health', 'form', 'webhook', 'link-spa']),
221
+ callers: z.tuple([]),
222
+ requirement: z.null(),
223
+ crossOrigin: z.enum(['environment', 'any']).optional(),
224
+ authorization: z.literal('forward').optional(),
225
+ }).refine((row) => row.authorization === undefined || row.kind === 'webhook', "only a webhook forwards the request's Authorization"),
226
+ // A public procedure is a mount's procedure anyone calls: it admits a body and answers its output.
227
+ z.strictObject({
228
+ ...rowBase,
229
+ kind: z.literal('public'),
230
+ source: z.strictObject({ kind: z.literal('mount'), name }),
231
+ output,
232
+ callers: z.tuple([]),
233
+ requirement: z.null(),
234
+ crossOrigin: z.enum(['environment', 'any']).optional(),
235
+ cache: endpointCacheSchema.optional(),
236
+ }).refine((row) => row.cache === undefined || row.method === 'GET', 'only a GET answer is cached'),
237
+ // The framework's own GET that issues the ALTCHA challenge of the public procedure its source names: no body, no schemas.
238
+ z.strictObject({
239
+ ...rowBase,
240
+ kind: z.literal('public'),
241
+ source: z.strictObject({ kind: z.literal('challenge'), name }),
242
+ method: z.literal('GET'),
243
+ admission: z.null(),
244
+ input: z.null(),
245
+ output: z.null(),
246
+ callers: z.tuple([]),
247
+ requirement: z.null(),
248
+ crossOrigin: z.enum(['environment', 'any']).optional(),
249
+ }),
250
+ // A public SPA is a fixed static row: GET only, no body, no schemas.
251
+ z.strictObject({
252
+ ...rowBase,
253
+ kind: z.literal('public-spa'),
254
+ method: z.literal('GET'),
255
+ admission: z.null(),
256
+ input: z.null(),
257
+ output: z.null(),
258
+ callers: z.tuple([]),
259
+ requirement: z.null(),
260
+ }),
261
+ ]).refine(
262
+ // Only a procedure answers a stored file, and exactly when its output is one.
263
+ (row) => (row.response !== undefined) === (row.output?.type === 'file') && (row.response === undefined || FILE_RESPONSE_KINDS.includes(row.kind)),
264
+ 'only a procedure whose output is a file answers a stored file',
265
+ ).refine(
266
+ // Only an RPC procedure, a public procedure and a form open to another origin, and only the anonymous two to any (ADR-0022).
267
+ (row) =>
268
+ !('crossOrigin' in row) || row.crossOrigin === undefined
269
+ || (CROSS_ORIGIN_KINDS.includes(row.kind) && (row.crossOrigin !== 'any' || ANY_ORIGIN_KINDS.includes(row.kind))),
270
+ 'this endpoint kind cannot be called cross-origin',
271
+ )
272
+ }
245
273
 
246
274
  const scopeBinding = z.discriminatedUnion('kind', [
247
275
  z.strictObject({ kind: z.literal('app') }),
@@ -381,6 +409,7 @@ const tablePolicy: z.ZodType<TablePolicyArtifact> = z.strictObject({
381
409
  assign: z.strictObject({ maxDays: z.int().positive().nullable(), self: z.boolean() }).nullable(),
382
410
  })).optional(),
383
411
  when: z.record(action, condition).optional(),
412
+ relationWhen: record(z.record(action, condition)).optional(),
384
413
  reveals: record(z.strictObject({
385
414
  to: name,
386
415
  actions: z.array(action).nonempty(),
@@ -388,186 +417,203 @@ const tablePolicy: z.ZodType<TablePolicyArtifact> = z.strictObject({
388
417
  assign: z.strictObject({ self: z.boolean() }).optional(),
389
418
  })).optional(),
390
419
  readThrough: z.record(name, name).optional(),
420
+ writeThrough: z.record(name, z.array(action).nonempty()).optional(),
391
421
  memberReveals: record(z.strictObject({
392
422
  to: name,
393
423
  actions: z.array(action).nonempty(),
394
424
  when: condition.optional(),
425
+ assign: z.strictObject({ self: z.boolean() }).optional(),
395
426
  })).optional(),
396
- })
397
-
398
- export const contractArtifactSchema: z.ZodType<ContractArtifact> = z.strictObject({
399
- format: z.literal(CONTRACT_FORMAT),
400
- app: name,
401
- dimensions: record(z.strictObject({
402
- in: nullableName,
403
- creator: nullableName,
404
- members: z.strictObject({ manage: action, list: action }).nullable(),
405
- directory: z.literal('labels').optional(),
406
- })),
407
- actions: z.record(action, z.string()),
408
- roles: z.record(
409
- roleKey,
410
- z.strictObject({
411
- grants: actions,
412
- member: z.strictObject({ scope: name, assignableBy: z.array(roleKey) }).nullable(),
413
- external: z.literal(true).optional(),
414
- via: record(actions.nonempty()).optional(),
415
- }).refine((role) => role.external !== true || role.member !== null, {
416
- path: ['external'],
417
- message: 'only a membership role admits external principals',
418
- }).refine((role) => role.via === undefined || (role.member === null && role.external !== true), {
419
- path: ['via'],
420
- message: 'a relation holds actions through an application-wide role only, never a membership or external one',
421
- }),
422
- ),
423
- relations: record(z.strictObject({ dimension: name })).optional(),
424
- mounts: record(mount),
425
- files: record(z.strictObject({
426
- owner: name,
427
- read: action,
428
- write: action,
429
- delete: action,
430
- maxBytes: z.int().positive(),
431
- types: names,
432
- maxPerOwner: z.int().positive().nullable(),
433
- link: z.union([z.boolean(), z.array(name).nonempty()]),
434
- scan: z.literal(true).optional(),
435
- })),
436
- fileKinds: z.record(
437
- fileKindName,
438
- z.strictObject({ types: names, maxBytes: z.int().positive(), scan: z.literal(true).optional(), inline: z.literal(true).optional() }).refine(
439
- (kind) => kind.inline === undefined || kind.types.every((type) => inlineFileTypes('inline-file').includes(type)),
440
- 'an inline kind admits only inert images and XML documents',
427
+ access: record(
428
+ z.strictObject({ view: name, row: name, principal: nullableName, member: nullableName }).refine(
429
+ (access) => access.principal !== null || access.member !== null,
430
+ 'an access view binds the principal, a member node or both (ADR-0076)',
441
431
  ),
442
432
  ).optional(),
443
- jobs: record(z.strictObject({
444
- schedule: name,
445
- actions,
446
- scope: scopeBinding,
447
- timeoutMs: z.int().positive().max(JOB_LIMITS.maxTimeoutMs),
448
- retries: z.int().nonnegative(),
449
- })),
450
- exports: record(z.strictObject({ version: z.int().positive(), consumers: names, audience: name })),
451
- imports: record(z.strictObject({
433
+ })
434
+
435
+ /** A contract artifact whose schemas `shape` parses. */
436
+ function artifactSchemaOf(shape: z.ZodType<SchemaShape>): z.ZodType<ContractArtifact> {
437
+ return z.strictObject({
438
+ format: z.literal(CONTRACT_FORMAT),
452
439
  app: name,
453
- export: name,
454
- version: z.int().positive(),
455
- digest: name,
456
- procedures: names,
457
- usedBy: names,
458
- timeoutMs: z.int().positive().nullable(),
459
- })),
460
- csp: z.strictObject({
461
- connectSrc: z.array(cspSource),
462
- imgSrc: z.array(cspSource),
463
- frameAncestors: z.array(cspSource),
464
- scriptSrc: z.array(cspSource).nonempty().optional(),
465
- frameSrc: z.array(cspSource).nonempty().optional(),
466
- styleSrc: z.array(cspSource).nonempty().optional(),
467
- fontSrc: z.array(cspSource).nonempty().optional(),
468
- workerSrc: z.tuple([z.strictObject({ origin: z.literal(WORKER_BLOB_SOURCE), purpose: z.string().min(1) })]).optional(),
469
- }),
470
- tables: record(tablePolicy),
471
- endpoints: z.array(endpointRow).superRefine((rows, context) => {
472
- for (const [index, row] of rows.entries()) {
473
- if (row.source.kind !== 'export' && row.callers.some((caller) => caller.startsWith('app:'))) {
474
- context.addIssue({ code: 'custom', path: [index, 'callers'], message: 'an app:<id> caller reaches only an export row' })
440
+ dimensions: record(z.strictObject({
441
+ in: nullableName,
442
+ creator: nullableName,
443
+ members: z.strictObject({ manage: action, list: action }).nullable(),
444
+ directory: z.literal('labels').optional(),
445
+ })),
446
+ actions: z.record(action, z.string()),
447
+ roles: z.record(
448
+ roleKey,
449
+ z.strictObject({
450
+ grants: actions,
451
+ member: z.strictObject({ scope: name, assignableBy: z.array(roleKey) }).nullable(),
452
+ external: z.literal(true).optional(),
453
+ via: record(actions.nonempty()).optional(),
454
+ }).refine((role) => role.external !== true || role.member !== null, {
455
+ path: ['external'],
456
+ message: 'only a membership role admits external principals',
457
+ }).refine((role) => role.via === undefined || role.external !== true, {
458
+ path: ['via'],
459
+ message: 'a relation holds actions through an internal role only, never an external one',
460
+ }),
461
+ ),
462
+ relations: record(z.strictObject({ dimension: name })).optional(),
463
+ mounts: record(mount),
464
+ files: record(z.strictObject({
465
+ owner: name,
466
+ read: action,
467
+ write: action,
468
+ delete: action,
469
+ maxBytes: z.int().positive(),
470
+ types: names,
471
+ maxPerOwner: z.int().positive().nullable(),
472
+ link: z.union([z.boolean(), z.array(name).nonempty()]),
473
+ scan: z.literal(true).optional(),
474
+ })),
475
+ fileKinds: z.record(
476
+ fileKindName,
477
+ z.strictObject({ types: names, maxBytes: z.int().positive(), scan: z.literal(true).optional(), inline: z.literal(true).optional() }).refine(
478
+ (kind) => kind.inline === undefined || kind.types.every((type) => inlineFileTypes('inline-file').includes(type)),
479
+ 'an inline kind admits only inert images and XML documents',
480
+ ),
481
+ ).optional(),
482
+ jobs: record(z.strictObject({
483
+ schedule: name,
484
+ actions,
485
+ scope: scopeBinding,
486
+ timeoutMs: z.int().positive().max(JOB_LIMITS.maxTimeoutMs),
487
+ retries: z.int().nonnegative(),
488
+ })),
489
+ exports: record(z.strictObject({ version: z.int().positive(), consumers: names, audience: name })),
490
+ imports: record(z.strictObject({
491
+ app: name,
492
+ export: name,
493
+ version: z.int().positive(),
494
+ digest: name,
495
+ procedures: names,
496
+ usedBy: names,
497
+ timeoutMs: z.int().positive().nullable(),
498
+ })),
499
+ csp: z.strictObject({
500
+ connectSrc: z.array(cspSource),
501
+ imgSrc: z.array(cspSource),
502
+ frameAncestors: z.array(cspSource),
503
+ scriptSrc: z.array(cspSource).nonempty().optional(),
504
+ frameSrc: z.array(cspSource).nonempty().optional(),
505
+ styleSrc: z.array(cspSource).nonempty().optional(),
506
+ fontSrc: z.array(cspSource).nonempty().optional(),
507
+ workerSrc: z.tuple([z.strictObject({ origin: z.literal(WORKER_BLOB_SOURCE), purpose: z.string().min(1) })]).optional(),
508
+ }),
509
+ tables: record(tablePolicy),
510
+ endpoints: z.array(endpointRowOf(shape)).superRefine((rows, context) => {
511
+ for (const [index, row] of rows.entries()) {
512
+ if (row.source.kind !== 'export' && row.callers.some((caller) => caller.startsWith('app:'))) {
513
+ context.addIssue({ code: 'custom', path: [index, 'callers'], message: 'an app:<id> caller reaches only an export row' })
514
+ }
515
+ if (row.source.kind === 'export' && row.requirement?.kind !== 'action') {
516
+ context.addIssue({ code: 'custom', path: [index, 'requirement'], message: 'an export row requires an action' })
517
+ }
518
+ if (row.source.kind === 'export' && row.requirement?.kind === 'action' && row.requirement.access.form === 'app') {
519
+ context.addIssue({ code: 'custom', path: [index, 'requirement'], message: 'an export row reads in one dimension, never app-wide' })
520
+ }
475
521
  }
476
- if (row.source.kind === 'export' && row.requirement?.kind !== 'action') {
477
- context.addIssue({ code: 'custom', path: [index, 'requirement'], message: 'an export row requires an action' })
522
+ }),
523
+ reservedPrefixes: names,
524
+ declared: record(z.strictObject({
525
+ sql: z.enum(['read', 'write']).nullable(),
526
+ unscoped: record(z.enum(['read', 'write'])),
527
+ connect: names,
528
+ issues: nullableName,
529
+ then: name.optional(),
530
+ mailer: z.enum(JOB_MAILERS).optional(),
531
+ actions: actions.nonempty().optional(),
532
+ kicks: z.array(name).nonempty().optional(),
533
+ binds: name.optional(),
534
+ signs: z.array(name).nonempty().optional(),
535
+ egress: z.union([z.array(z.string().refine((origin) => parseEgressEntry(origin).ok)).nonempty(), z.literal(PUBLIC_EGRESS)]).optional(),
536
+ })).superRefine((declared, context) => {
537
+ for (const [site, reach] of Object.entries(declared)) {
538
+ if (reach.egress === PUBLIC_EGRESS && !site.startsWith(JOB_SITE_PREFIX)) {
539
+ context.addIssue({ code: 'custom', path: [site, 'egress'], message: "egress: 'public' belongs to a cron job, keyed by job:<name>" })
540
+ }
541
+ if (reach.actions !== undefined && !isOwnWorkloadName('public', site)) {
542
+ context.addIssue({ code: 'custom', path: [site, 'actions'], message: 'workload actions belong to a public procedure, keyed by its endpoint id' })
543
+ }
478
544
  }
479
- if (row.source.kind === 'export' && row.requirement?.kind === 'action' && row.requirement.access.form === 'app') {
480
- context.addIssue({ code: 'custom', path: [index, 'requirement'], message: 'an export row reads in one dimension, never app-wide' })
545
+ }).optional(),
546
+ directories: record(z.strictObject({ dimension: name, lists: z.boolean() })).optional(),
547
+ locale: z.enum(LOCALES).optional(),
548
+ displayName: z.string().refine((value) => displayNameProblem(value) === null, 'not a display name').optional(),
549
+ mail: z.strictObject({ invitation: mailLocales('invitation'), enrollment: mailLocales('enrollment'), reset: mailLocales('reset') }).partial()
550
+ .optional(),
551
+ members: z.strictObject({ manage: action, list: action }).optional(),
552
+ directory: z.literal('labels').optional(),
553
+ terminal: z.strictObject({ identify: z.string().refine((path) => terminalIdentifyProblem(path) === null, 'not an identification path') })
554
+ .optional(),
555
+ procedures: record(z.strictObject({
556
+ rate: z.strictObject({
557
+ perClient: bucket,
558
+ perCaller: bucket,
559
+ perEndpoint: bucket,
560
+ bytesPerHour: z.int().positive().max(PROCEDURE_LIMITS.maxBytesPerHour).nullable(),
561
+ }),
562
+ challenge: procedureChallenge.nullable(),
563
+ timeoutMs: z.int().positive().max(PROCEDURE_LIMITS.maxTimeoutMs),
564
+ query: shape.optional(),
565
+ changesStateOnGet: z.literal(true).optional(),
566
+ })).optional(),
567
+ tokens: record(z.strictObject({ claims: shape, maxDays: z.int().positive().max(TOKEN_MAX_DAYS) })).optional(),
568
+ }).superRefine((artifact, context) => {
569
+ for (const row of artifact.endpoints) {
570
+ // A row answering a file of an inline kind shows it, every other row that answers a file downloads it.
571
+ if (row.output?.type === 'file' && (row.response === 'inline-file') !== (artifact.fileKinds?.[row.output.kind]?.inline === true)) {
572
+ context.addIssue({ code: 'custom', path: ['endpoints'], message: `'${row.id}' is inline-file exactly when its file kind is inline` })
481
573
  }
482
- }
483
- }),
484
- reservedPrefixes: names,
485
- declared: record(z.strictObject({
486
- sql: z.enum(['read', 'write']).nullable(),
487
- unscoped: record(z.enum(['read', 'write'])),
488
- connect: names,
489
- issues: nullableName,
490
- then: name.optional(),
491
- mailer: z.enum(JOB_MAILERS).optional(),
492
- actions: actions.nonempty().optional(),
493
- kicks: z.array(name).nonempty().optional(),
494
- binds: name.optional(),
495
- signs: z.array(name).nonempty().optional(),
496
- egress: z.array(z.string().refine((origin) => parseEgressEntry(origin).ok)).nonempty().optional(),
497
- })).superRefine((declared, context) => {
498
- for (const [site, reach] of Object.entries(declared)) {
499
- if (reach.actions !== undefined && !isOwnWorkloadName('public', site)) {
500
- context.addIssue({ code: 'custom', path: [site, 'actions'], message: 'workload actions belong to a public procedure, keyed by its endpoint id' })
574
+ // Only the application writes a file of an inline kind: an uploaded document could render as a page.
575
+ const inline = row.input === null ? undefined : fileKindsIn(row.input).find((kind) => artifact.fileKinds?.[kind]?.inline === true)
576
+ if (inline !== undefined) {
577
+ context.addIssue({
578
+ code: 'custom',
579
+ path: ['endpoints', artifact.endpoints.indexOf(row)],
580
+ message: `'${row.id}' takes a file of the inline kind '${inline}', which only the application writes`,
581
+ })
582
+ }
583
+ if (row.kind === 'public' && row.source.kind !== 'challenge' && artifact.declared?.[row.id]?.actions === undefined) {
584
+ context.addIssue({ code: 'custom', path: ['declared', row.id], message: 'a public procedure declares its workload actions' })
501
585
  }
502
586
  }
503
- }).optional(),
504
- directories: record(z.strictObject({ dimension: name, lists: z.boolean() })).optional(),
505
- locale: z.enum(LOCALES).optional(),
506
- displayName: z.string().refine((value) => displayNameProblem(value) === null, 'not a display name').optional(),
507
- mail: z.strictObject({ invitation: mailLocales('invitation'), enrollment: mailLocales('enrollment'), reset: mailLocales('reset') }).partial()
508
- .optional(),
509
- members: z.strictObject({ manage: action, list: action }).optional(),
510
- directory: z.literal('labels').optional(),
511
- terminal: z.strictObject({ identify: z.string().refine((path) => terminalIdentifyProblem(path) === null, 'not an identification path') }).optional(),
512
- procedures: record(z.strictObject({
513
- rate: z.strictObject({
514
- perClient: bucket,
515
- perCaller: bucket,
516
- perEndpoint: bucket,
517
- bytesPerHour: z.int().positive().max(PROCEDURE_LIMITS.maxBytesPerHour).nullable(),
518
- }),
519
- challenge: procedureChallenge.nullable(),
520
- timeoutMs: z.int().positive().max(PROCEDURE_LIMITS.maxTimeoutMs),
521
- query: schemaShapeSchema.optional(),
522
- changesStateOnGet: z.literal(true).optional(),
523
- })).optional(),
524
- tokens: record(z.strictObject({ claims: schemaShapeSchema, maxDays: z.int().positive().max(TOKEN_MAX_DAYS) })).optional(),
525
- }).superRefine((artifact, context) => {
526
- for (const row of artifact.endpoints) {
527
- // A row answering a file of an inline kind shows it, every other row that answers a file downloads it.
528
- if (row.output?.type === 'file' && (row.response === 'inline-file') !== (artifact.fileKinds?.[row.output.kind]?.inline === true)) {
529
- context.addIssue({ code: 'custom', path: ['endpoints'], message: `'${row.id}' is inline-file exactly when its file kind is inline` })
530
- }
531
- // Only the application writes a file of an inline kind: an uploaded document could render as a page.
532
- const inline = row.input === null ? undefined : fileKindsIn(row.input).find((kind) => artifact.fileKinds?.[kind]?.inline === true)
533
- if (inline !== undefined) {
534
- context.addIssue({
535
- code: 'custom',
536
- path: ['endpoints', artifact.endpoints.indexOf(row)],
537
- message: `'${row.id}' takes a file of the inline kind '${inline}', which only the application writes`,
538
- })
587
+ // Every ALTCHA challenge has exactly its own issuer, under its action, from the procedure's origins, with its own buckets.
588
+ const rows = new Map(artifact.endpoints.map((row) => [row.id, row]))
589
+ const issuers = artifact.endpoints.filter((row) => row.source.kind === 'challenge')
590
+ for (const [id, rules] of Object.entries(artifact.procedures ?? {})) {
591
+ if (rules.challenge?.provider !== 'altcha') continue
592
+ const issuer = rows.get(challengeRowId(id))
593
+ const procedure = rows.get(id)
594
+ if (
595
+ issuer === undefined || procedure === undefined || issuer.source.kind !== 'challenge' || issuer.source.name !== id
596
+ || issuer.path !== challengePath(rules.challenge.action) || issuer.crossOrigin !== procedure.crossOrigin
597
+ || artifact.procedures?.[issuer.id]?.challenge !== null
598
+ ) {
599
+ context.addIssue({ code: 'custom', path: ['procedures', id, 'challenge'], message: 'an ALTCHA challenge has its own issuer row' })
600
+ }
539
601
  }
540
- if (row.kind === 'public' && row.source.kind !== 'challenge' && artifact.declared?.[row.id]?.actions === undefined) {
541
- context.addIssue({ code: 'custom', path: ['declared', row.id], message: 'a public procedure declares its workload actions' })
602
+ for (const issuer of issuers) {
603
+ if (issuer.id !== challengeRowId(issuer.source.name) || artifact.procedures?.[issuer.source.name]?.challenge?.provider !== 'altcha') {
604
+ context.addIssue({ code: 'custom', path: ['endpoints'], message: `'${issuer.id}' issues the challenge of no ALTCHA procedure` })
605
+ }
542
606
  }
543
- }
544
- // Every ALTCHA challenge has exactly its own issuer, under its action, from the procedure's origins, with its own buckets.
545
- const rows = new Map(artifact.endpoints.map((row) => [row.id, row]))
546
- const issuers = artifact.endpoints.filter((row) => row.source.kind === 'challenge')
547
- for (const [id, rules] of Object.entries(artifact.procedures ?? {})) {
548
- if (rules.challenge?.provider !== 'altcha') continue
549
- const issuer = rows.get(challengeRowId(id))
550
- const procedure = rows.get(id)
551
- if (
552
- issuer === undefined || procedure === undefined || issuer.source.kind !== 'challenge' || issuer.source.name !== id
553
- || issuer.path !== challengePath(rules.challenge.action) || issuer.crossOrigin !== procedure.crossOrigin
554
- || artifact.procedures?.[issuer.id]?.challenge !== null
555
- ) {
556
- context.addIssue({ code: 'custom', path: ['procedures', id, 'challenge'], message: 'an ALTCHA challenge has its own issuer row' })
607
+ if (issuers.length > 0 && !artifact.reservedPrefixes.includes(CHALLENGE_PREFIX)) {
608
+ context.addIssue({ code: 'custom', path: ['reservedPrefixes'], message: `an issuer row reserves ${CHALLENGE_PREFIX}` })
557
609
  }
558
- }
559
- for (const issuer of issuers) {
560
- if (issuer.id !== challengeRowId(issuer.source.name) || artifact.procedures?.[issuer.source.name]?.challenge?.provider !== 'altcha') {
561
- context.addIssue({ code: 'custom', path: ['endpoints'], message: `'${issuer.id}' issues the challenge of no ALTCHA procedure` })
610
+ if ((artifact.csp.workerSrc !== undefined) !== issuers.length > 0) {
611
+ context.addIssue({ code: 'custom', path: ['csp', 'workerSrc'], message: 'workerSrc admits the workers of an ALTCHA challenge, and only those' })
562
612
  }
563
- }
564
- if (issuers.length > 0 && !artifact.reservedPrefixes.includes(CHALLENGE_PREFIX)) {
565
- context.addIssue({ code: 'custom', path: ['reservedPrefixes'], message: `an issuer row reserves ${CHALLENGE_PREFIX}` })
566
- }
567
- if ((artifact.csp.workerSrc !== undefined) !== issuers.length > 0) {
568
- context.addIssue({ code: 'custom', path: ['csp', 'workerSrc'], message: 'workerSrc admits the workers of an ALTCHA challenge, and only those' })
569
- }
570
- })
613
+ })
614
+ }
615
+
616
+ export const contractArtifactSchema: z.ZodType<ContractArtifact> = artifactSchemaOf(schemaShapeSchema)
571
617
 
572
618
  function mailLocales(kind: MessageKind) {
573
619
  const template = z.strictObject({ subject: z.string(), text: z.string(), html: z.string().optional() }).superRefine((value, context) => {
@@ -580,3 +626,25 @@ function mailLocales(kind: MessageKind) {
580
626
  export function parseContractArtifact(value: unknown): ContractArtifact {
581
627
  return contractArtifactSchema.parse(value)
582
628
  }
629
+
630
+ /** Whether a stored artifact is in the shared encoding, which `parseEncodedArtifact` reads, rather than plain. */
631
+ export function isEncodedArtifact(value: unknown): boolean {
632
+ return typeof value === 'object' && value !== null && 'encoding' in value
633
+ }
634
+
635
+ const encodedArtifactSchema = z.strictObject({ encoding: z.literal(SHARED_SHAPES_ENCODING), shapes: z.array(z.unknown()), artifact: z.unknown() })
636
+
637
+ /**
638
+ * Parses an artifact in the shared encoding (`encodeArtifact`): each shared shape over the shapes written before it,
639
+ * then the artifact over all of them. The result is the canonical artifact, its shared shapes one object each; throws a
640
+ * `ZodError` naming every mismatch.
641
+ */
642
+ export function parseEncodedArtifact(value: unknown): ContractArtifact {
643
+ const encoded = encodedArtifactSchema.parse(value)
644
+ const shapes: SchemaShape[] = []
645
+ const shape = shapeSchemaOf(shapes)
646
+ for (const written of encoded.shapes) {
647
+ shapes.push(shape.parse(written))
648
+ }
649
+ return artifactSchemaOf(shape).parse(encoded.artifact)
650
+ }