@fabrika/auth-core 0.9.0-dev.2 → 0.9.0-dev.20

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 (47) hide show
  1. package/package.json +2 -2
  2. package/src/canonical-path.ts +18 -0
  3. package/src/client-address.ts +74 -0
  4. package/src/contract-canonical.ts +152 -1
  5. package/src/contract-encoding.ts +181 -0
  6. package/src/contract.ts +201 -9
  7. package/src/dev-environment.ts +6 -0
  8. package/src/egress.ts +97 -0
  9. package/src/endpoint-digest.ts +22 -2
  10. package/src/framework-release.ts +2 -0
  11. package/src/framework-variables.ts +15 -0
  12. package/src/index.ts +8 -0
  13. package/src/locale.ts +1 -1
  14. package/src/managed-environment.ts +140 -0
  15. package/src/membership.ts +12 -4
  16. package/src/ops.ts +1933 -0
  17. package/src/public-egress.ts +168 -0
  18. package/src/requirement.ts +5 -2
  19. package/src/rpc.ts +8 -8
  20. package/src/sha256.ts +52 -14
  21. package/src/terminal.ts +105 -0
  22. package/src/token.ts +73 -13
  23. package/src/types.ts +63 -2
  24. package/src/wire.ts +7 -0
  25. package/types/src/canonical-path.d.ts +6 -0
  26. package/types/src/client-address.d.ts +7 -0
  27. package/types/src/contract-canonical.d.ts +11 -1
  28. package/types/src/contract-encoding.d.ts +18 -0
  29. package/types/src/contract.d.ts +186 -8
  30. package/types/src/dev-environment.d.ts +5 -0
  31. package/types/src/egress.d.ts +27 -0
  32. package/types/src/endpoint-digest.d.ts +5 -0
  33. package/types/src/framework-release.d.ts +2 -0
  34. package/types/src/framework-variables.d.ts +12 -1
  35. package/types/src/index.d.ts +8 -0
  36. package/types/src/locale.d.ts +1 -1
  37. package/types/src/managed-environment.d.ts +32 -0
  38. package/types/src/membership.d.ts +8 -3
  39. package/types/src/ops.d.ts +657 -0
  40. package/types/src/public-egress.d.ts +31 -0
  41. package/types/src/requirement.d.ts +2 -2
  42. package/types/src/rpc.d.ts +5 -5
  43. package/types/src/sha256.d.ts +10 -0
  44. package/types/src/terminal.d.ts +72 -0
  45. package/types/src/token.d.ts +36 -11
  46. package/types/src/types.d.ts +42 -2
  47. package/types/src/wire.d.ts +6 -0
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@fabrika/auth-core",
3
- "version": "0.9.0-dev.2",
3
+ "version": "0.9.0-dev.20",
4
4
  "type": "module",
5
5
  "repository": {
6
6
  "type": "git",
@@ -23,7 +23,7 @@
23
23
  }
24
24
  },
25
25
  "scripts": {
26
- "typecheck": "tsc --noEmit",
26
+ "typecheck": "tsrs --build tsconfig.test.json",
27
27
  "test": "bun test"
28
28
  }
29
29
  }
@@ -50,6 +50,24 @@ export function rawRequestTarget(url: string): RequestTarget {
50
50
  return target.pathname === '' ? { pathname: '/', search: target.search } : target
51
51
  }
52
52
 
53
+ /**
54
+ * The absolute URL of `path` on `origin`, or `null` when `path` is not a path of that origin: the one rule for a
55
+ * redirect or return target that must stay on its own origin. A leading `//` or any `\` would make a browser read a
56
+ * host from it, and a browser strips a tab or newline before parsing, so no control character is admitted.
57
+ */
58
+ export function sameOriginTarget(origin: string, path: string): string | null {
59
+ if (!path.startsWith('/') || path.startsWith('//') || path.includes('\\') || [...path].some(isControl)) {
60
+ return null
61
+ }
62
+ const target = new URL(path, origin)
63
+ return target.origin === origin ? target.toString() : null
64
+ }
65
+
66
+ function isControl(character: string): boolean {
67
+ const code = character.charCodeAt(0)
68
+ return code < 0x20 || code === 0x7f
69
+ }
70
+
53
71
  /** A segment one reader decodes and another refuses would route differently, so a malformed escape is refused. */
54
72
  function isDecodable(segment: string): boolean {
55
73
  try {
@@ -0,0 +1,74 @@
1
+ // The client a per-client abuse bucket counts, derived from the address an ingress wrote. IAM and the application
2
+ // runtime both key on it, so one client is one bucket on either side.
3
+
4
+ /** Longest header value read; an IPv6 address with a zone id fits with room to spare. */
5
+ const MAX_ADDRESS_LENGTH = 64
6
+
7
+ const IPV4 = /^(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}$/
8
+ const HEXTET = /^[0-9a-f]{1,4}$/
9
+
10
+ /**
11
+ * The eight groups of an IPv6 address, or `null`. An embedded IPv4 tail (`::ffff:192.0.2.1`) counts as two groups,
12
+ * and a zone id (`%eth0`) is dropped.
13
+ */
14
+ function ipv6Groups(text: string): number[] | null {
15
+ const address = text.split('%')[0] ?? ''
16
+ const halves = address.split('::')
17
+ if (halves.length > 2) {
18
+ return null
19
+ }
20
+ const groupsOf = (half: string): number[] | null => {
21
+ if (half === '') {
22
+ return []
23
+ }
24
+ const groups: number[] = []
25
+ const parts = half.split(':')
26
+ for (const [index, part] of parts.entries()) {
27
+ if (index === parts.length - 1 && IPV4.test(part)) {
28
+ const [a = 0, b = 0, c = 0, d = 0] = part.split('.').map(Number)
29
+ groups.push(a * 256 + b, c * 256 + d)
30
+ } else if (HEXTET.test(part)) {
31
+ groups.push(Number.parseInt(part, 16))
32
+ } else {
33
+ return null
34
+ }
35
+ }
36
+ return groups
37
+ }
38
+ const head = groupsOf(halves[0] ?? '')
39
+ const tail = halves.length === 2 ? groupsOf(halves[1] ?? '') : []
40
+ if (head === null || tail === null) {
41
+ return null
42
+ }
43
+ if (halves.length === 1) {
44
+ return head.length === 8 ? head : null
45
+ }
46
+ const missing = 8 - head.length - tail.length
47
+ return missing < 1 ? null : [...head, ...Array.from({ length: missing }, () => 0), ...tail]
48
+ }
49
+
50
+ /**
51
+ * The client a client-address header value counts as: an IPv4 address, or an IPv6 address's /64 (one subscriber's
52
+ * prefix, of which it may hold every address); an IPv4-mapped IPv6 address counts as its IPv4 address. Only the first
53
+ * value counts, so a caller that appends a second copy cannot change the key. `null` when the value is absent or no
54
+ * IP address.
55
+ */
56
+ export function clientAddressKey(header: string | null): string | null {
57
+ const value = (header ?? '').split(',')[0]?.trim().toLowerCase() ?? ''
58
+ if (value === '' || value.length > MAX_ADDRESS_LENGTH) {
59
+ return null
60
+ }
61
+ if (IPV4.test(value)) {
62
+ return value
63
+ }
64
+ const groups = ipv6Groups(value.startsWith('[') && value.endsWith(']') ? value.slice(1, -1) : value)
65
+ if (groups === null) {
66
+ return null
67
+ }
68
+ const mapped = groups.slice(0, 5).every((group) => group === 0) && groups[5] === 0xffff
69
+ if (mapped) {
70
+ const [high = 0, low = 0] = groups.slice(6)
71
+ return [high >> 8, high & 0xff, low >> 8, low & 0xff].join('.')
72
+ }
73
+ return `${groups.slice(0, 4).map((group) => group.toString(16)).join(':')}::/64`
74
+ }
@@ -4,12 +4,19 @@
4
4
  import type {
5
5
  BodyAdmission,
6
6
  Caller,
7
+ ColumnTestArtifact,
8
+ ConditionArtifact,
9
+ ConditionLiteralArtifact,
10
+ ConfersArtifact,
7
11
  ContractArtifact,
8
12
  CspSource,
9
13
  EndpointRow,
14
+ MemberRevealsArtifact,
10
15
  MountArtifact,
11
16
  OutputShape,
17
+ RevealsArtifact,
12
18
  RoleArtifact,
19
+ RowsTestArtifact,
13
20
  SchemaShape,
14
21
  TableActionArtifact,
15
22
  TablePolicyArtifact,
@@ -27,6 +34,7 @@ export function canonicalizeArtifact(artifact: ContractArtifact): ContractArtifa
27
34
  dimensions: artifact.dimensions,
28
35
  actions: artifact.actions,
29
36
  roles: mapValues(artifact.roles, canonicalRole),
37
+ ...(artifact.relations === undefined ? {} : { relations: artifact.relations }),
30
38
  mounts: mapValues(artifact.mounts, canonicalMount),
31
39
  files: mapValues(artifact.files, (collection) => ({
32
40
  ...collection,
@@ -65,7 +73,7 @@ export function canonicalizeArtifact(artifact: ContractArtifact): ContractArtifa
65
73
  ...(reach.actions === undefined ? {} : { actions: sorted(reach.actions) }),
66
74
  ...(reach.kicks === undefined ? {} : { kicks: sorted(reach.kicks) }),
67
75
  ...(reach.signs === undefined ? {} : { signs: sorted(reach.signs) }),
68
- ...(reach.egress === undefined ? {} : { egress: sorted(reach.egress) }),
76
+ ...(reach.egress === undefined ? {} : { egress: typeof reach.egress === 'string' ? reach.egress : sorted(reach.egress) }),
69
77
  })),
70
78
  }),
71
79
  ...(artifact.directories === undefined ? {} : { directories: artifact.directories }),
@@ -74,6 +82,7 @@ export function canonicalizeArtifact(artifact: ContractArtifact): ContractArtifa
74
82
  ...(artifact.mail === undefined ? {} : { mail: artifact.mail }),
75
83
  ...(artifact.members === undefined ? {} : { members: artifact.members }),
76
84
  ...(artifact.directory === undefined ? {} : { directory: artifact.directory }),
85
+ ...(artifact.terminal === undefined ? {} : { terminal: { identify: artifact.terminal.identify } }),
77
86
  ...(artifact.procedures === undefined
78
87
  ? {}
79
88
  : {
@@ -100,6 +109,7 @@ function canonicalRole(role: RoleArtifact): RoleArtifact {
100
109
  grants: sorted(role.grants),
101
110
  member: role.member === null ? null : { scope: role.member.scope, assignableBy: sorted(role.member.assignableBy) },
102
111
  ...(role.external === true ? { external: true } : {}),
112
+ ...(role.via === undefined ? {} : { via: mapValues(role.via, sorted) }),
103
113
  }
104
114
  }
105
115
 
@@ -150,9 +160,112 @@ function canonicalTable(table: TablePolicyArtifact): TablePolicyArtifact {
150
160
  scope: table.scope.mode === 'child' ? { ...table.scope, inherit: sorted(table.scope.inherit) } : table.scope,
151
161
  insert: sorted(table.insert),
152
162
  update: sorted(table.update),
163
+ ...(table.when === undefined ? {} : { when: mapValues(table.when, canonicalCondition) }),
164
+ ...(table.relationWhen === undefined
165
+ ? {}
166
+ : { relationWhen: mapValues(table.relationWhen, (conditions) => mapValues(conditions, canonicalCondition)) }),
167
+ ...(table.confers === undefined ? {} : { confers: mapValues(table.confers, canonicalConfers) }),
168
+ ...(table.reveals === undefined ? {} : { reveals: mapValues(table.reveals, canonicalReveals) }),
169
+ ...(table.memberReveals === undefined ? {} : { memberReveals: mapValues(table.memberReveals, canonicalMemberReveals) }),
170
+ }
171
+ }
172
+
173
+ function canonicalConfers(confers: ConfersArtifact): ConfersArtifact {
174
+ return confers.when === undefined ? confers : { ...confers, when: canonicalCondition(confers.when) }
175
+ }
176
+
177
+ function canonicalReveals(reveals: RevealsArtifact): RevealsArtifact {
178
+ return {
179
+ ...reveals,
180
+ actions: sorted(reveals.actions),
181
+ ...(reveals.when === undefined ? {} : { when: canonicalCondition(reveals.when) }),
182
+ }
183
+ }
184
+
185
+ function canonicalMemberReveals(reveals: MemberRevealsArtifact): MemberRevealsArtifact {
186
+ return {
187
+ ...reveals,
188
+ actions: sorted(reveals.actions),
189
+ ...(reveals.when === undefined ? {} : { when: canonicalCondition(reveals.when) }),
190
+ }
191
+ }
192
+
193
+ /**
194
+ * A condition with its connectives' operands and its `in` / `notIn` lists sorted by their canonical JSON: AND and OR
195
+ * commute and a list is a set, so neither order changes which rows it admits.
196
+ */
197
+ export function canonicalCondition(condition: ConditionArtifact): ConditionArtifact {
198
+ if ('allOf' in condition && isConditionList(condition.allOf)) {
199
+ return { allOf: sortedConditions(condition.allOf) }
200
+ }
201
+ if ('anyOf' in condition && isConditionList(condition.anyOf)) {
202
+ return { anyOf: sortedConditions(condition.anyOf) }
203
+ }
204
+ if ('not' in condition && isCondition(condition.not)) {
205
+ return { not: canonicalCondition(condition.not) }
206
+ }
207
+ const rows = canonicalRows(condition)
208
+ if (rows !== undefined) return rows
209
+ const tests: Record<string, ColumnTestArtifact | RowsTestArtifact> = {}
210
+ for (const [path, test] of Object.entries(condition)) {
211
+ const after = isCondition(test) ? canonicalRows(test) : undefined
212
+ if (after !== undefined) {
213
+ tests[path] = after
214
+ continue
215
+ }
216
+ // A parsed artifact holds nothing else here; dropping an unknown test would widen what the condition admits.
217
+ if (!isColumnTest(test)) throw new Error(`the condition test of ${path} is not a column test`)
218
+ tests[path] = canonicalTest(test)
219
+ }
220
+ return tests
221
+ }
222
+
223
+ /** `some` or `none` with its condition canonical, or `undefined` for any other form: one beside another key is no rows test. */
224
+ function canonicalRows(condition: object): RowsTestArtifact | undefined {
225
+ if (Object.keys(condition).length !== 1) return undefined
226
+ if ('some' in condition && isConditionRecord(condition.some)) {
227
+ return { some: mapValues(condition.some, canonicalCondition) }
228
+ }
229
+ if ('none' in condition && isConditionRecord(condition.none)) {
230
+ return { none: mapValues(condition.none, canonicalCondition) }
231
+ }
232
+ return undefined
233
+ }
234
+
235
+ function canonicalTest(test: ColumnTestArtifact): ColumnTestArtifact {
236
+ return {
237
+ ...test,
238
+ ...(test.in === undefined ? {} : { in: sortedLiterals(test.in) }),
239
+ ...(test.notIn === undefined ? {} : { notIn: sortedLiterals(test.notIn) }),
153
240
  }
154
241
  }
155
242
 
243
+ function sortedConditions(conditions: readonly ConditionArtifact[]): ConditionArtifact[] {
244
+ return conditions.map(canonicalCondition).sort((a, b) => compare(canonicalJson(a), canonicalJson(b)))
245
+ }
246
+
247
+ function sortedLiterals(values: readonly ConditionLiteralArtifact[]): ConditionLiteralArtifact[] {
248
+ return [...values].sort((a, b) => compare(JSON.stringify(a), JSON.stringify(b)))
249
+ }
250
+
251
+ function isCondition(value: unknown): value is ConditionArtifact {
252
+ return typeof value === 'object' && value !== null && !Array.isArray(value)
253
+ }
254
+
255
+ function isConditionRecord(value: unknown): value is Readonly<Record<string, ConditionArtifact>> {
256
+ return isCondition(value) && Object.values(value).every(isCondition)
257
+ }
258
+
259
+ function isConditionList(value: unknown): value is readonly ConditionArtifact[] {
260
+ return Array.isArray(value) && value.every(isCondition)
261
+ }
262
+
263
+ const COLUMN_TEST_OPERATORS: ReadonlySet<string> = new Set(['eq', 'notEq', 'in', 'notIn', 'isNull', 'lt', 'lte', 'gt', 'gte'])
264
+
265
+ function isColumnTest(value: unknown): value is ColumnTestArtifact {
266
+ return isCondition(value) && Object.keys(value).every((operator) => COLUMN_TEST_OPERATORS.has(operator))
267
+ }
268
+
156
269
  function canonicalizeEndpoint(row: EndpointRow): EndpointRow {
157
270
  const shared = {
158
271
  admission: row.admission === null ? null : canonicalAdmission(row.admission),
@@ -233,3 +346,41 @@ function sortKeys(_key: string, value: unknown): unknown {
233
346
  }
234
347
  return Object.fromEntries(Object.entries(value).sort(([a], [b]) => compare(a, b)))
235
348
  }
349
+
350
+ /**
351
+ * `canonicalJson(value)` written in pieces to `write`, so a digest of a large value never holds its whole text. Each
352
+ * object is rebuilt as `sortKeys` rebuilds it, so integer-like keys come first exactly as `JSON.stringify` orders them.
353
+ */
354
+ export function writeCanonicalJson(value: unknown, write: (piece: string) => void): void {
355
+ if (Array.isArray(value)) {
356
+ write('[')
357
+ for (const [index, item] of value.entries()) {
358
+ if (index > 0) write(',')
359
+ if (isOmitted(item)) write('null')
360
+ else writeCanonicalJson(item, write)
361
+ }
362
+ write(']')
363
+ return
364
+ }
365
+ if (typeof value === 'object' && value !== null) {
366
+ write('{')
367
+ let first = true
368
+ const rebuilt = Object.fromEntries(Object.entries(value).sort(([a], [b]) => compare(a, b)))
369
+ for (const [key, item] of Object.entries(rebuilt)) {
370
+ if (isOmitted(item)) continue
371
+ if (!first) write(',')
372
+ first = false
373
+ write(JSON.stringify(key))
374
+ write(':')
375
+ writeCanonicalJson(item, write)
376
+ }
377
+ write('}')
378
+ return
379
+ }
380
+ write(JSON.stringify(value) ?? 'null')
381
+ }
382
+
383
+ /** What `JSON.stringify` leaves out of an object and writes as `null` in an array. */
384
+ function isOmitted(value: unknown): boolean {
385
+ return value === undefined || typeof value === 'function' || typeof value === 'symbol'
386
+ }
@@ -0,0 +1,181 @@
1
+ // The shared encoding of a contract artifact: how a build bundles it and how Control stores a large one. Each composite
2
+ // schema shape that occurs more than once is written once, in `shapes`, and referenced by its index; a shape's null
3
+ // constraints are left out. Decoding (`@fabrika/app/contract`) restores the canonical artifact exactly, so its digest
4
+ // is the one `contractDigest` takes: the encoding is a storage form, never what a digest is taken over.
5
+
6
+ import type { ContractArtifact, OutputShape, SchemaShape } from './contract'
7
+ import { canonicalizeArtifact, canonicalJson } from './contract-canonical'
8
+
9
+ /** The `encoding` of an encoded artifact; a plain artifact has no such key. */
10
+ export const SHARED_SHAPES_ENCODING = 'shared-shapes'
11
+
12
+ /** In place of a shape: `shapes[index]` of the encoded artifact, which is always written before it is referenced. */
13
+ export interface SharedShapeReference {
14
+ readonly type: 'shared'
15
+ readonly index: number
16
+ }
17
+
18
+ /** An artifact in the shared encoding, as JSON. */
19
+ export interface EncodedArtifact {
20
+ readonly encoding: typeof SHARED_SHAPES_ENCODING
21
+ readonly shapes: readonly object[]
22
+ readonly artifact: object
23
+ }
24
+
25
+ /** The canonical artifact in the shared encoding. */
26
+ export function encodeArtifact(artifact: ContractArtifact): EncodedArtifact {
27
+ const canonical = canonicalizeArtifact(artifact)
28
+ const interner = new ShapeInterner()
29
+ mapShapes(canonical, (shape) => {
30
+ interner.node(shape).uses++
31
+ return null
32
+ })
33
+ for (const node of interner.nodes) {
34
+ for (const child of node.children) child.uses++
35
+ }
36
+ const writer = new SharedWriter(interner)
37
+ const encoded = mapShapes(canonical, (shape) => writer.write(shape))
38
+ return { encoding: SHARED_SHAPES_ENCODING, shapes: writer.shapes, artifact: encoded }
39
+ }
40
+
41
+ /** The encoded artifact as text, keys sorted: what a build bundles. */
42
+ export function encodedArtifactJson(artifact: ContractArtifact): string {
43
+ return canonicalJson(encodeArtifact(artifact))
44
+ }
45
+
46
+ /** One distinct shape: equal shapes, wherever they occur, are one node. */
47
+ interface ShapeNode {
48
+ readonly id: number
49
+ readonly shape: SchemaShape
50
+ readonly children: readonly ShapeNode[]
51
+ uses: number
52
+ }
53
+
54
+ class ShapeInterner {
55
+ readonly nodes: ShapeNode[] = []
56
+ readonly #byForm = new Map<string, ShapeNode>()
57
+ readonly #byObject = new WeakMap<SchemaShape, ShapeNode>()
58
+
59
+ node(shape: SchemaShape): ShapeNode {
60
+ const known = this.#byObject.get(shape)
61
+ if (known !== undefined) return known
62
+ const children: ShapeNode[] = []
63
+ // A node's identity is its own fields and its children's identities, so equal subtrees are found bottom up.
64
+ const form = canonicalJson(compactShape(shape, (child) => {
65
+ const node = this.node(child)
66
+ children.push(node)
67
+ return node.id
68
+ }))
69
+ let node = this.#byForm.get(form)
70
+ if (node === undefined) {
71
+ node = { id: this.nodes.length, shape, children, uses: 0 }
72
+ this.nodes.push(node)
73
+ this.#byForm.set(form, node)
74
+ }
75
+ this.#byObject.set(shape, node)
76
+ return node
77
+ }
78
+ }
79
+
80
+ class SharedWriter {
81
+ readonly shapes: object[] = []
82
+ readonly #indexes = new Map<ShapeNode, number>()
83
+ readonly #interner: ShapeInterner
84
+
85
+ constructor(interner: ShapeInterner) {
86
+ this.#interner = interner
87
+ }
88
+
89
+ write(shape: SchemaShape): object {
90
+ const node = this.#interner.node(shape)
91
+ if (node.children.length === 0 || node.uses < 2) {
92
+ return compactShape(shape, (child) => this.write(child))
93
+ }
94
+ let index = this.#indexes.get(node)
95
+ if (index === undefined) {
96
+ // Children first, so every reference points to a shape written before it.
97
+ const written = compactShape(shape, (child) => this.write(child))
98
+ index = this.shapes.length
99
+ this.shapes.push(written)
100
+ this.#indexes.set(node, index)
101
+ }
102
+ const reference: SharedShapeReference = { type: 'shared', index }
103
+ return reference
104
+ }
105
+ }
106
+
107
+ /** The shape without its null constraints, each child replaced by `child`'s answer; an object's fields in key order. */
108
+ function compactShape(shape: SchemaShape, child: (shape: SchemaShape) => unknown): object {
109
+ switch (shape.type) {
110
+ case 'string':
111
+ return {
112
+ type: 'string',
113
+ ...present('format', shape.format),
114
+ ...present('minLength', shape.minLength),
115
+ ...present('maxLength', shape.maxLength),
116
+ ...present('pattern', shape.pattern),
117
+ ...present('startsWith', shape.startsWith),
118
+ ...present('endsWith', shape.endsWith),
119
+ ...present('includes', shape.includes),
120
+ }
121
+ case 'number':
122
+ return {
123
+ type: 'number',
124
+ int: shape.int,
125
+ ...present('min', shape.min),
126
+ exclusiveMin: shape.exclusiveMin,
127
+ ...present('max', shape.max),
128
+ exclusiveMax: shape.exclusiveMax,
129
+ ...present('multipleOf', shape.multipleOf),
130
+ }
131
+ case 'array':
132
+ return { type: 'array', items: child(shape.items), ...present('minItems', shape.minItems), ...present('maxItems', shape.maxItems) }
133
+ case 'tuple':
134
+ return { type: 'tuple', items: shape.items.map(child), ...(shape.rest === null ? {} : { rest: child(shape.rest) }) }
135
+ case 'record':
136
+ return { type: 'record', key: child(shape.key), value: child(shape.value) }
137
+ case 'object':
138
+ return { type: 'object', fields: Object.fromEntries(sortedEntries(shape.fields).map(([name, field]) => [name, child(field)])) }
139
+ case 'optional':
140
+ case 'nullable':
141
+ return { type: shape.type, inner: child(shape.inner) }
142
+ case 'union':
143
+ return { type: 'union', options: shape.options.map(child) }
144
+ default:
145
+ return shape
146
+ }
147
+ }
148
+
149
+ function present(key: string, value: string | number | null): object {
150
+ return value === null ? {} : { [key]: value }
151
+ }
152
+
153
+ /** The artifact with each schema shape replaced by `map`'s answer; records are visited in key order. */
154
+ function mapShapes(artifact: ContractArtifact, map: (shape: SchemaShape) => unknown): object {
155
+ const output = (shape: OutputShape): unknown => {
156
+ if (shape.type === 'redirect') return shape
157
+ if (shape.type === 'attachment') return { ...shape, columns: shape.columns.map((column) => ({ name: column.name, shape: map(column.shape) })) }
158
+ return map(shape)
159
+ }
160
+ const endpoints = artifact.endpoints.map((row) => ({
161
+ ...row,
162
+ input: row.input === null ? null : map(row.input),
163
+ output: row.output === null ? null : output(row.output),
164
+ }))
165
+ const procedures = artifact.procedures === undefined ? undefined : Object.fromEntries(
166
+ sortedEntries(artifact.procedures).map(([id, rules]) => [id, rules.query === undefined ? rules : { ...rules, query: map(rules.query) }]),
167
+ )
168
+ const tokens = artifact.tokens === undefined ? undefined : Object.fromEntries(
169
+ sortedEntries(artifact.tokens).map(([purpose, token]) => [purpose, { ...token, claims: map(token.claims) }]),
170
+ )
171
+ return {
172
+ ...artifact,
173
+ endpoints,
174
+ ...(procedures === undefined ? {} : { procedures }),
175
+ ...(tokens === undefined ? {} : { tokens }),
176
+ }
177
+ }
178
+
179
+ function sortedEntries<T>(record: Readonly<Record<string, T>>): [string, T][] {
180
+ return Object.entries(record).sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))
181
+ }