@fleetless/contracts 13.3.0 → 15.0.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.
Files changed (182) hide show
  1. package/CHANGELOG.md +304 -0
  2. package/artifacts/openapi.json +20156 -10513
  3. package/artifacts/routes.json +1429 -292
  4. package/artifacts/schema/access-warning.schema.json +51 -0
  5. package/artifacts/schema/action-config.schema.json +35 -0
  6. package/artifacts/schema/addon-catalogue-entry.schema.json +3 -1
  7. package/artifacts/schema/admin-plan-change-request.schema.json +26 -0
  8. package/artifacts/schema/app-access-response.schema.json +136 -0
  9. package/artifacts/schema/app-access.schema.json +80 -0
  10. package/artifacts/schema/app-deletion-summary.schema.json +15 -8
  11. package/artifacts/schema/app-invitation-list-response.schema.json +13 -6
  12. package/artifacts/schema/app-invitation.schema.json +5 -5
  13. package/artifacts/schema/app-list-response.schema.json +6 -6
  14. package/artifacts/schema/app-lock.schema.json +30 -0
  15. package/artifacts/schema/app-user-list-response.schema.json +13 -6
  16. package/artifacts/schema/app-user.schema.json +13 -6
  17. package/artifacts/schema/app.schema.json +6 -6
  18. package/artifacts/schema/asset-plan-limit-details.schema.json +3 -1
  19. package/artifacts/schema/auth-ok.schema.json +20 -6
  20. package/artifacts/schema/camera-list-response.schema.json +1 -1
  21. package/artifacts/schema/client-identity.schema.json +21 -6
  22. package/artifacts/schema/cloud-config.schema.json +359 -5
  23. package/artifacts/schema/collection-actor.schema.json +35 -0
  24. package/artifacts/schema/collection-definitions-response.schema.json +612 -0
  25. package/artifacts/schema/collection-event.schema.json +216 -0
  26. package/artifacts/schema/collection-export-query.schema.json +56 -0
  27. package/artifacts/schema/collection-filter.schema.json +9 -0
  28. package/artifacts/schema/collection-import-preview.schema.json +143 -0
  29. package/artifacts/schema/collection-import-request.schema.json +105 -0
  30. package/artifacts/schema/collection-import-result.schema.json +38 -0
  31. package/artifacts/schema/collection-list-response.schema.json +119 -0
  32. package/artifacts/schema/collection-record-get-query.schema.json +12 -0
  33. package/artifacts/schema/collection-record-history-query.schema.json +35 -0
  34. package/artifacts/schema/collection-record-history-response.schema.json +389 -0
  35. package/artifacts/schema/collection-record-list-query.schema.json +67 -0
  36. package/artifacts/schema/collection-record-list-response.schema.json +212 -0
  37. package/artifacts/schema/collection-record-restore-request.schema.json +14 -0
  38. package/artifacts/schema/collection-record-write.schema.json +31 -0
  39. package/artifacts/schema/collection-record.schema.json +180 -0
  40. package/artifacts/schema/collection-revision.schema.json +295 -0
  41. package/artifacts/schema/collection-subscribe-error.schema.json +31 -0
  42. package/artifacts/schema/collection-subscribe.schema.json +48 -0
  43. package/artifacts/schema/collection-subscribed.schema.json +22 -0
  44. package/artifacts/schema/collection-summary.schema.json +92 -0
  45. package/artifacts/schema/collection-unsubscribe.schema.json +22 -0
  46. package/artifacts/schema/collections-access-change.schema.json +34 -0
  47. package/artifacts/schema/collections-document.schema.json +732 -0
  48. package/artifacts/schema/collections-draft-response.schema.json +845 -0
  49. package/artifacts/schema/collections-effect.schema.json +384 -0
  50. package/artifacts/schema/collections-issue.schema.json +36 -0
  51. package/artifacts/schema/collections-publish-request.schema.json +18 -0
  52. package/artifacts/schema/collections-publish-response.schema.json +450 -0
  53. package/artifacts/schema/collections-purge-preview.schema.json +60 -0
  54. package/artifacts/schema/collections-purge-request.schema.json +27 -0
  55. package/artifacts/schema/collections-purge-response.schema.json +30 -0
  56. package/artifacts/schema/collections-restore-preview-query.schema.json +20 -0
  57. package/artifacts/schema/collections-restore-preview.schema.json +581 -0
  58. package/artifacts/schema/collections-restore-request.schema.json +27 -0
  59. package/artifacts/schema/collections-restore-response.schema.json +455 -0
  60. package/artifacts/schema/collections-schema-preview.schema.json +519 -0
  61. package/artifacts/schema/collections-schema-published.schema.json +22 -0
  62. package/artifacts/schema/collections-version-response.schema.json +869 -0
  63. package/artifacts/schema/collections-version-summary.schema.json +139 -0
  64. package/artifacts/schema/collections-versions-response.schema.json +167 -0
  65. package/artifacts/schema/config-draft-response.schema.json +359 -5
  66. package/artifacts/schema/config-version-response.schema.json +359 -5
  67. package/artifacts/schema/confirmation-required-details.schema.json +13 -0
  68. package/artifacts/schema/create-app-invitation-request.schema.json +4 -4
  69. package/artifacts/schema/create-app-user-request.schema.json +4 -4
  70. package/artifacts/schema/create-org-role-request.schema.json +33 -0
  71. package/artifacts/schema/dangling-reference.schema.json +130 -0
  72. package/artifacts/schema/datapoint-config.schema.json +35 -0
  73. package/artifacts/schema/datapoint-list-response.schema.json +2 -2
  74. package/artifacts/schema/effective-capability.schema.json +104 -0
  75. package/artifacts/schema/effective-rights-query.schema.json +19 -0
  76. package/artifacts/schema/effective-rights-response.schema.json +396 -0
  77. package/artifacts/schema/effective-robot-rights.schema.json +266 -0
  78. package/artifacts/schema/invoke-or-service-response.schema.json +1 -1
  79. package/artifacts/schema/invoke-response.schema.json +1 -1
  80. package/artifacts/schema/journal-intent-v2-body.schema.json +74 -0
  81. package/artifacts/schema/journal-intent-v2.schema.json +84 -0
  82. package/artifacts/schema/journal-replay-receipt-body.schema.json +1 -0
  83. package/artifacts/schema/journal-replay-receipt.schema.json +1 -0
  84. package/artifacts/schema/mcp-robot-datasheet.schema.json +2 -2
  85. package/artifacts/schema/org-plan.schema.json +29 -1
  86. package/artifacts/schema/org-quota-usage-counts.schema.json +18 -0
  87. package/artifacts/schema/org-quota-usage.schema.json +47 -1
  88. package/artifacts/schema/org-quotas.schema.json +29 -1
  89. package/artifacts/schema/org-role-list-response.schema.json +206 -0
  90. package/artifacts/schema/org-role.schema.json +59 -0
  91. package/artifacts/schema/patch-app-user-request.schema.json +4 -4
  92. package/artifacts/schema/patch-org-role-request.schema.json +38 -0
  93. package/artifacts/schema/plan-catalogue-entry.schema.json +29 -1
  94. package/artifacts/schema/plan-change-decision-status-response.schema.json +29 -1
  95. package/artifacts/schema/plan-limit-details.schema.json +3 -1
  96. package/artifacts/schema/plan-limits.schema.json +29 -1
  97. package/artifacts/schema/plan-overrides.schema.json +26 -0
  98. package/artifacts/schema/publish-config-response.schema.json +48 -1
  99. package/artifacts/schema/publisher-config.schema.json +35 -0
  100. package/artifacts/schema/put-collections-draft-request.schema.json +16 -0
  101. package/artifacts/schema/put-role-defaults-request.schema.json +127 -0
  102. package/artifacts/schema/record-changed-details.schema.json +16 -0
  103. package/artifacts/schema/record-referenced-details.schema.json +35 -0
  104. package/artifacts/schema/reference-invalid-details.schema.json +25 -0
  105. package/artifacts/schema/reference-place.schema.json +112 -0
  106. package/artifacts/schema/rename-slug-response.schema.json +4 -3
  107. package/artifacts/schema/required-missing-details.schema.json +19 -0
  108. package/artifacts/schema/robot-config-doc.schema.json +359 -5
  109. package/artifacts/schema/robot-deletion-summary.schema.json +33 -1
  110. package/artifacts/schema/role-collection-rights.schema.json +82 -0
  111. package/artifacts/schema/role-cycle-details.schema.json +18 -0
  112. package/artifacts/schema/role-defaults-response.schema.json +59 -0
  113. package/artifacts/schema/role-rename-preview.schema.json +147 -0
  114. package/artifacts/schema/service-config.schema.json +35 -0
  115. package/artifacts/schema/slug-usage-response.schema.json +4 -3
  116. package/artifacts/schema/update-app-request.schema.json +0 -12
  117. package/dist/app-users.d.ts +11 -8
  118. package/dist/app-users.js +18 -10
  119. package/dist/apps.d.ts +258 -71
  120. package/dist/apps.js +215 -151
  121. package/dist/audit.d.ts +35 -5
  122. package/dist/audit.js +40 -2
  123. package/dist/billing.d.ts +10 -10
  124. package/dist/client-auth.d.ts +5 -2
  125. package/dist/client-auth.js +11 -3
  126. package/dist/client-robots.d.ts +1 -1
  127. package/dist/client-robots.js +1 -1
  128. package/dist/collections-issues.d.ts +67 -0
  129. package/dist/collections-issues.js +340 -0
  130. package/dist/collections-records.d.ts +562 -0
  131. package/dist/collections-records.js +525 -0
  132. package/dist/collections-rights.d.ts +17 -0
  133. package/dist/collections-rights.js +41 -0
  134. package/dist/collections-schema.d.ts +1064 -0
  135. package/dist/collections-schema.js +386 -0
  136. package/dist/collections-templates.d.ts +55 -0
  137. package/dist/collections-templates.js +137 -0
  138. package/dist/collections-transfer.d.ts +101 -0
  139. package/dist/collections-transfer.js +206 -0
  140. package/dist/collections-values.d.ts +67 -0
  141. package/dist/collections-values.js +284 -0
  142. package/dist/collections.d.ts +568 -0
  143. package/dist/collections.js +332 -0
  144. package/dist/common.d.ts +1 -1
  145. package/dist/common.js +1 -1
  146. package/dist/config-issues.d.ts +1 -1
  147. package/dist/config-issues.js +1 -1
  148. package/dist/config.d.ts +78 -12
  149. package/dist/config.js +109 -15
  150. package/dist/errors.d.ts +63 -5
  151. package/dist/errors.js +152 -24
  152. package/dist/index.d.ts +40 -14
  153. package/dist/index.js +27 -7
  154. package/dist/journal-intents.d.ts +30 -0
  155. package/dist/journal-intents.js +3 -0
  156. package/dist/legal-acceptances.d.ts +2 -2
  157. package/dist/mcp.d.ts +5 -37
  158. package/dist/mcp.js +4 -14
  159. package/dist/org-roles.d.ts +186 -0
  160. package/dist/org-roles.js +199 -0
  161. package/dist/plans.d.ts +25 -7
  162. package/dist/plans.js +21 -1
  163. package/dist/protocol.d.ts +19 -1
  164. package/dist/realtime.d.ts +172 -3
  165. package/dist/realtime.js +164 -1
  166. package/dist/rest.d.ts +104 -53
  167. package/dist/rest.js +79 -55
  168. package/dist/rights.d.ts +197 -0
  169. package/dist/rights.js +396 -0
  170. package/dist/routes.d.ts +1 -1
  171. package/dist/routes.js +675 -150
  172. package/package.json +1 -1
  173. package/artifacts/schema/mcp-role-preview-response.schema.json +0 -134
  174. package/artifacts/schema/put-robot-details-request.schema.json +0 -41
  175. package/artifacts/schema/put-robot-details-response.schema.json +0 -43
  176. package/artifacts/schema/robot-details-doc.schema.json +0 -33
  177. package/artifacts/schema/role-delete-query.schema.json +0 -13
  178. package/artifacts/schema/role-in-use-details.schema.json +0 -28
  179. package/artifacts/schema/role-list-response.schema.json +0 -48
  180. package/artifacts/schema/role-permissions.schema.json +0 -61
  181. package/artifacts/schema/role-rename-request.schema.json +0 -16
  182. package/artifacts/schema/role.schema.json +0 -35
@@ -0,0 +1,525 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+ import { z } from 'zod';
3
+ import { wireSeqCursor } from './common.js';
4
+ import { COLLECTION_LIMITS, COLLECTION_RESERVED_KEYS, collectionBinding, collectionField, collectionKey, } from './collections.js';
5
+ /**
6
+ * The records of a collection as they travel: what a read returns, what a
7
+ * write sends, and the two small languages a list query is written in, the
8
+ * filter and the sort.
9
+ *
10
+ * **A record is an envelope, not a flat object.** The record's own values sit
11
+ * under `values`, next to the system fields that describe the record (`id`,
12
+ * who created it, its revision) and the answers the cloud works out for the
13
+ * reader (`display`, `missing_required`). A flat object would have to share one
14
+ * namespace between a developer's field keys and ours, and every system field
15
+ * added later would be a chance to collide with a field somebody already has.
16
+ *
17
+ * **The filter is parsed, not described.** Its grammar (nesting, a count of
18
+ * conditions, one operator per condition) cannot be written as a zod schema
19
+ * without losing the one thing a person typing a filter needs, which is to be
20
+ * told where it is wrong. `parseCollectionFilter` returns every problem with
21
+ * the path of the object that has it. It judges the *shape* of a filter; whether
22
+ * a field exists and whether a value suits its type needs the document, and is
23
+ * the cloud's to answer.
24
+ */
25
+ /** The cap on problems reported for one filter: enough to fix a filter in one go, few enough to read. */
26
+ const MAX_FILTER_ISSUES = 20;
27
+ const timestamp = z.iso.datetime();
28
+ const count = z.number().int().min(0);
29
+ const schemaVersion = z.number().int().min(1);
30
+ /**
31
+ * Who made a change. `fleetless` is the platform itself (a schema change, an
32
+ * automatic record) and always carries the nil id. `label` is worked out when
33
+ * the record is read, from the person's display name, so a user who has since
34
+ * been deleted reads `Deleted user` instead of leaving the record with a
35
+ * dangling id. An email address is the fallback only for a reader who may see
36
+ * it: a developer or a server key reading a person without a name, and an app
37
+ * user reading their own label.
38
+ */
39
+ export const collectionActor = z
40
+ .object({
41
+ kind: z.enum(['developer', 'app_user', 'server_key', 'fleetless']).meta({
42
+ description: 'What made the change: a developer, a user of the app, a server key of the app, or the platform itself.',
43
+ }),
44
+ id: z.uuid().meta({ description: 'The id of the developer, app user or server key. The nil id for the platform.' }),
45
+ label: z.string().min(1).max(200).meta({
46
+ description: 'A name to show: the person\'s display name, the name of a server key, `Fleetless`, `Deleted user` when the user no longer exists, or `Deleted key` when the key does. A person without a display name reads as their email address to a developer or a server key and to themselves, and to an app user reading someone else as `Team member` (a developer) or `User` (an app user): an app user never learns another person\'s address.',
47
+ }),
48
+ })
49
+ .meta({ description: 'Who or what made a change to a record.' });
50
+ /**
51
+ * One record. `display` is the collection's display template rendered for this
52
+ * record, so a list can name its rows without knowing the template.
53
+ */
54
+ export const collectionRecord = z
55
+ .object({
56
+ id: z.uuid(),
57
+ robot_id: z.uuid().nullable().meta({
58
+ description: 'The robot a record of a `per_robot` or `one_per_robot` collection belongs to; null in a `global` collection.',
59
+ }),
60
+ created_at: timestamp,
61
+ created_by: collectionActor,
62
+ updated_at: timestamp,
63
+ updated_by: collectionActor,
64
+ revision: z.number().int().min(1).meta({ description: 'Starts at 1 and grows by one with every change. Send it as `expected_revision` to refuse a write that would overwrite a newer one.' }),
65
+ display: z.string().meta({ description: 'The collection\'s display template filled in for this record.' }),
66
+ missing_required: z
67
+ .array(z.string())
68
+ .meta({
69
+ description: 'Required fields that are empty because the schema changed after the record was written. The record can still be updated in its other fields. Absent when nothing is missing.',
70
+ })
71
+ .optional(),
72
+ values: z.record(z.string(), z.unknown()).meta({
73
+ description: 'The record\'s fields by key. A field without a value is absent. With `expand`, a reference field holds the referenced record in this same shape instead of its id, when the caller may read that collection.',
74
+ }),
75
+ deleted_at: timestamp
76
+ .meta({ description: 'When the record was deleted. Present only in the list of deleted records (`deleted=true`); absent on a live record.' })
77
+ .optional(),
78
+ deleted_by: collectionActor
79
+ .meta({ description: 'Who deleted the record. Present only in the list of deleted records (`deleted=true`); absent on a live record.' })
80
+ .optional(),
81
+ })
82
+ .meta({ description: 'A record of a collection: its system fields and its values.' });
83
+ // ---------------------------------------------------------------------------
84
+ // The filter and the sort
85
+ // ---------------------------------------------------------------------------
86
+ /** The operators a filter condition can use. */
87
+ export const COLLECTION_FILTER_OPS = ['eq', 'ne', 'lt', 'lte', 'gt', 'gte', 'contains', 'in', 'empty'];
88
+ /**
89
+ * The system fields a filter or sort may name. The other system values
90
+ * (`revision`, `updated_by`, `robot`) are not filterable; a robot is chosen
91
+ * with the `robot` parameter of a list.
92
+ */
93
+ export const COLLECTION_FILTER_SYSTEM_KEYS = ['id', 'robot_id', 'created_at', 'updated_at', 'created_by'];
94
+ /** A filter on the wire: a JSON object. Its grammar is checked by `parseCollectionFilter`. */
95
+ export const collectionFilter = z.record(z.string(), z.unknown()).meta({
96
+ description: 'A filter is a JSON object. A condition names a field and one operator: `{ "location.name": { "eq": "XTD1" } }`. The operators are `eq`, `ne`, `lt`, `lte`, `gt`, `gte`, `contains` (case-insensitive text search), `in` (a list of at most 100 values) and `empty` (`true` or `false`). Conditions are combined with `{ "and": [ ... ] }` and `{ "or": [ ... ] }`, nested at most 3 levels deep, 50 conditions in all. A field is a field key, `reference.field` to go one hop through a reference field, or one of the system fields `id`, `robot_id`, `created_at`, `updated_at` and `created_by`.',
97
+ });
98
+ /** A value for a message: long text is cut, so a refusal never repeats a megabyte back. */
99
+ const quote = (value) => (value.length > 40 ? `"${value.slice(0, 40)}..."` : `"${value}"`);
100
+ const isObject = (value) => typeof value === 'object' && value !== null && !Array.isArray(value);
101
+ /** The text, number and true/false values that conditions compare with. A `null` is not one: `empty` asks for "no value". */
102
+ const isPlainValue = (value) => typeof value === 'string' || typeof value === 'boolean' || (typeof value === 'number' && Number.isFinite(value));
103
+ const kindOf = (value) => value === null ? 'null' : Array.isArray(value) ? 'a list' : typeof value === 'object' ? 'an object' : `a ${typeof value}`;
104
+ const RESERVED = COLLECTION_RESERVED_KEYS;
105
+ const SYSTEM_FILTER_KEYS = COLLECTION_FILTER_SYSTEM_KEYS;
106
+ const isFilterOp = (op) => COLLECTION_FILTER_OPS.includes(op);
107
+ /** A segment of a JSON Pointer, with the two characters the syntax reserves escaped. */
108
+ const pointerSegment = (segment) => segment.replaceAll('~', '~0').replaceAll('/', '~1');
109
+ /**
110
+ * Why `field` cannot be filtered or sorted by, or `null`.
111
+ *
112
+ * A field is a key, or `reference.field`: one hop through a reference field,
113
+ * never two. A key that is reserved for a system value is allowed only where
114
+ * that value can be filtered. A reference field is a developer's field, so a
115
+ * reserved key cannot start a hop; its target's system fields can end one.
116
+ */
117
+ function fieldProblem(field) {
118
+ const parts = field.split('.');
119
+ if (parts.length > 2) {
120
+ return `${quote(field)} goes through more than one reference. A field can go through one: "location.name".`;
121
+ }
122
+ if (!parts.every((part) => collectionKey.safeParse(part).success)) {
123
+ return `${quote(field)} is not a field key. A key is lowercase letters, digits and underscores, starting with a letter, up to 63 characters.`;
124
+ }
125
+ const [first, second] = parts;
126
+ const unusable = (key) => `${quote(key)} is a system value that cannot be filtered or sorted by. The system fields that can be: ${COLLECTION_FILTER_SYSTEM_KEYS.join(', ')}.`;
127
+ if (second === undefined)
128
+ return RESERVED.includes(first) && !SYSTEM_FILTER_KEYS.includes(first) ? unusable(first) : null;
129
+ if (RESERVED.includes(first))
130
+ return `${quote(first)} is not a reference field, so ${quote(field)} cannot go through it.`;
131
+ return RESERVED.includes(second) && !SYSTEM_FILTER_KEYS.includes(second) ? unusable(second) : null;
132
+ }
133
+ /**
134
+ * Checks the shape of a filter and turns it into a tree.
135
+ *
136
+ * **What is checked.** An object is either a combination, `{ "and": [...] }`
137
+ * or `{ "or": [...] }`, which has no other keys, or a condition, `{ "<field>":
138
+ * { "<operator>": value } }`, which names one field and holds one operator.
139
+ * Nesting goes at most 3 levels deep and the filter has at most 50 conditions.
140
+ * Every operator checks its value: `eq` and `ne` take text, a number or
141
+ * `true`/`false`, the four order operators take a number or text (dates are
142
+ * text), `contains` takes text, `in` takes 1 to 100 of those values and `empty`
143
+ * takes `true` or `false`. Values keep their type; nothing is coerced.
144
+ *
145
+ * **What is not checked.** Whether the fields exist, and whether a value suits
146
+ * the type of its field, need the document. The tree keeps the field and the
147
+ * value exactly as written for the cloud to judge.
148
+ *
149
+ * `and`/`or` are always combinations, so a field called `and` or `or` cannot
150
+ * be filtered by. An empty object and an empty `and`/`or` list are refused
151
+ * rather than given a meaning; leave the filter out to list everything.
152
+ */
153
+ export function parseCollectionFilter(input) {
154
+ const issues = [];
155
+ let conditions = 0;
156
+ const report = (path, message) => {
157
+ if (issues.length < MAX_FILTER_ISSUES)
158
+ issues.push({ path: path.map((s) => `/${pointerSegment(s)}`).join(''), message });
159
+ };
160
+ /** The value of one condition, checked for its operator. Reports and returns false when it is wrong. */
161
+ const operandIsValid = (op, operand, path) => {
162
+ switch (op) {
163
+ case 'eq':
164
+ case 'ne':
165
+ if (isPlainValue(operand))
166
+ return true;
167
+ report(path, `"${op}" compares with text, a number or true/false, not ${kindOf(operand)}.${operand === null ? ' To find records without a value, use { "empty": true }.' : ''}`);
168
+ return false;
169
+ case 'lt':
170
+ case 'lte':
171
+ case 'gt':
172
+ case 'gte':
173
+ if (typeof operand === 'string' || (typeof operand === 'number' && Number.isFinite(operand)))
174
+ return true;
175
+ report(path, `"${op}" compares with a number or text, not ${kindOf(operand)}.`);
176
+ return false;
177
+ case 'contains':
178
+ if (typeof operand === 'string')
179
+ return true;
180
+ report(path, `"contains" searches for text, not ${kindOf(operand)}.`);
181
+ return false;
182
+ case 'empty':
183
+ if (typeof operand === 'boolean')
184
+ return true;
185
+ report(path, '"empty" takes true or false.');
186
+ return false;
187
+ case 'in': {
188
+ if (!Array.isArray(operand)) {
189
+ report(path, `"in" takes a list of values, not ${kindOf(operand)}.`);
190
+ return false;
191
+ }
192
+ if (operand.length === 0) {
193
+ report(path, '"in" needs at least one value.');
194
+ return false;
195
+ }
196
+ if (operand.length > COLLECTION_LIMITS.inValues) {
197
+ report(path, `"in" takes at most ${COLLECTION_LIMITS.inValues} values; this list has ${operand.length}.`);
198
+ return false;
199
+ }
200
+ let valid = true;
201
+ operand.forEach((item, index) => {
202
+ if (isPlainValue(item))
203
+ return;
204
+ report([...path, String(index)], `A value in the list is ${kindOf(item)}. Lists hold text, numbers and true/false.`);
205
+ valid = false;
206
+ });
207
+ return valid;
208
+ }
209
+ }
210
+ };
211
+ const walk = (value, path, depth) => {
212
+ if (!isObject(value)) {
213
+ report(path, 'A filter is a JSON object, for example { "name": { "eq": "XTD1" } }.');
214
+ return null;
215
+ }
216
+ const keys = Object.keys(value);
217
+ if (keys.length === 0) {
218
+ report(path, 'An empty object is not a filter. Leave the filter out to list everything.');
219
+ return null;
220
+ }
221
+ const combinator = keys.includes('and') ? 'and' : keys.includes('or') ? 'or' : null;
222
+ if (combinator !== null) {
223
+ if (keys.length > 1) {
224
+ report(path, 'An object with "and" or "or" has no other keys. Put the other conditions in its list.');
225
+ return null;
226
+ }
227
+ const here = [...path, combinator];
228
+ if (depth >= COLLECTION_LIMITS.filterDepth) {
229
+ report(here, `Nested more than ${COLLECTION_LIMITS.filterDepth} levels of "and" and "or".`);
230
+ return null;
231
+ }
232
+ const list = value[combinator];
233
+ if (!Array.isArray(list)) {
234
+ report(here, `"${combinator}" takes a list of filters, not ${kindOf(list)}.`);
235
+ return null;
236
+ }
237
+ if (list.length === 0) {
238
+ report(here, `"${combinator}" needs at least one filter in its list.`);
239
+ return null;
240
+ }
241
+ const children = [];
242
+ let valid = true;
243
+ list.forEach((entry, index) => {
244
+ const child = walk(entry, [...here, String(index)], depth + 1);
245
+ if (child === null)
246
+ valid = false;
247
+ else
248
+ children.push(child);
249
+ });
250
+ return valid ? { kind: combinator, children } : null;
251
+ }
252
+ if (keys.length > 1) {
253
+ report(path, 'An object names one field. Combine several conditions with "and" or "or".');
254
+ return null;
255
+ }
256
+ const field = keys[0];
257
+ const here = [...path, field];
258
+ conditions += 1;
259
+ const problem = fieldProblem(field);
260
+ if (problem !== null)
261
+ report(here, problem);
262
+ const condition = value[field];
263
+ if (!isObject(condition)) {
264
+ report(here, 'A condition is an object with one operator, for example { "eq": value }.');
265
+ return null;
266
+ }
267
+ const ops = Object.keys(condition);
268
+ if (ops.length !== 1) {
269
+ report(here, `A condition has exactly one operator; this one has ${ops.length === 0 ? 'none' : `${ops.length}: ${ops.map(quote).join(', ')}`}.`);
270
+ return null;
271
+ }
272
+ const op = ops[0];
273
+ if (!isFilterOp(op)) {
274
+ report([...here, op], `Unknown operator ${quote(op)}. Use one of: ${COLLECTION_FILTER_OPS.join(', ')}.`);
275
+ return null;
276
+ }
277
+ const operand = condition[op];
278
+ if (!operandIsValid(op, operand, [...here, op]) || problem !== null)
279
+ return null;
280
+ return { kind: 'condition', field, op, value: operand };
281
+ };
282
+ const node = walk(input, [], 0);
283
+ if (conditions > COLLECTION_LIMITS.filterConditions) {
284
+ report([], `The filter has ${conditions} conditions; at most ${COLLECTION_LIMITS.filterConditions} are allowed.`);
285
+ }
286
+ return issues.length === 0 && node !== null ? { ok: true, node } : { ok: false, issues };
287
+ }
288
+ /**
289
+ * Checks the entries of a `sort` and reads them: `name` ascending, `-name`
290
+ * descending. A sort names at most 3 fields, each once, and each follows the
291
+ * rule a filter's field does (a key, `reference.field`, or a system field).
292
+ *
293
+ * The final tie-break on `id` that makes a page boundary exact is the cloud's;
294
+ * a sort need not and does not have to name it.
295
+ */
296
+ export function parseCollectionSort(specs) {
297
+ if (specs.length > COLLECTION_LIMITS.sortFields) {
298
+ return { ok: false, message: `A sort names at most ${COLLECTION_LIMITS.sortFields} fields; this one names ${specs.length}.` };
299
+ }
300
+ const sort = [];
301
+ const seen = new Set();
302
+ for (const entry of specs) {
303
+ const descending = entry.startsWith('-');
304
+ const field = descending ? entry.slice(1) : entry;
305
+ const problem = fieldProblem(field);
306
+ if (problem !== null)
307
+ return { ok: false, message: `Sort entry ${quote(entry)} cannot be used. ${problem}` };
308
+ if (seen.has(field))
309
+ return { ok: false, message: `${quote(field)} is in the sort twice.` };
310
+ seen.add(field);
311
+ sort.push({ field, descending });
312
+ }
313
+ return { ok: true, sort };
314
+ }
315
+ // ---------------------------------------------------------------------------
316
+ // Reading records
317
+ // ---------------------------------------------------------------------------
318
+ /**
319
+ * A page size as a **query string** carries it: the same shape as
320
+ * `auditQuery.limit`, a union whose input branch is the wire, because a
321
+ * `z.coerce` cannot be published (the artifact would describe a shape a query
322
+ * string can never carry). The runtime is the authority for the bounds.
323
+ */
324
+ const pageLimit = z
325
+ .union([z.string().regex(/^\d{1,4}$/), z.number().int()])
326
+ .transform((v) => Number(v))
327
+ .pipe(z.number().int().positive().max(COLLECTION_LIMITS.pageMax));
328
+ const wireBoolean = z.enum(['true', 'false']);
329
+ const expandParam = z
330
+ .string()
331
+ .min(1)
332
+ .meta({
333
+ description: 'Reference fields to embed as records, separated by commas. Only one hop is followed. The embedded records are not counted in the size of a page.',
334
+ });
335
+ /**
336
+ * The query string of a record list. `filter` is the JSON text of a filter,
337
+ * `sort` and `expand` are comma-separated lists; the cloud parses all three
338
+ * (`parseCollectionFilter`, `parseCollectionSort`) and answers a problem with
339
+ * the path of what is wrong.
340
+ */
341
+ export const collectionRecordListQuery = z
342
+ .object({
343
+ filter: z
344
+ .string()
345
+ .min(1)
346
+ .meta({
347
+ description: 'A filter as JSON text, for example `{"location.name":{"eq":"XTD1"}}`. A condition names a field of the collection, one of the system fields `id`, `robot_id`, `created_at`, `updated_at` and `created_by`, or a field of a referenced record written `reference.field`. `created_by` is compared with the id of the developer, user or key that created the record.',
348
+ })
349
+ .optional(),
350
+ search: z
351
+ .string()
352
+ .meta({
353
+ description: 'Words that must all occur, in any letter case, in at least one searchable field of the record. At most 10 words, separated by whitespace.',
354
+ })
355
+ .optional(),
356
+ sort: z
357
+ .string()
358
+ .min(1)
359
+ .meta({
360
+ description: 'Up to 3 fields separated by commas; a leading `-` sorts descending, for example `-position_m,name`. A field is named as in `filter`: a field of the collection, one of the system fields `id`, `robot_id`, `created_at`, `updated_at` and `created_by`, or `reference.field`. Ties are broken by `id`.',
361
+ })
362
+ .optional(),
363
+ expand: expandParam.optional(),
364
+ limit: pageLimit
365
+ .meta({
366
+ description: `The most records to return, 1 to ${COLLECTION_LIMITS.pageMax}. Default ${COLLECTION_LIMITS.pageDefault}. A page can hold fewer: see \`next_cursor\`.`,
367
+ })
368
+ .optional(),
369
+ cursor: z.string().min(1).meta({ description: 'The `next_cursor` of the previous page.' }).optional(),
370
+ count: wireBoolean.meta({ description: '`true` adds `total`, the number of records that match.' }).optional(),
371
+ deleted: wireBoolean
372
+ .meta({ description: '`true` lists deleted records instead, newest deletion first. Needs the right to create records.' })
373
+ .optional(),
374
+ robot: z.uuid().meta({ description: 'Only the records of this robot, in a collection that belongs to robots.' }).optional(),
375
+ })
376
+ .strict();
377
+ /**
378
+ * The query string of a single record read. `expand` means what it does on the
379
+ * list, so a record read one by one and the same record in a page look alike.
380
+ */
381
+ export const collectionRecordGetQuery = z.object({ expand: expandParam.optional() }).strict();
382
+ export const collectionRecordListResponse = z
383
+ .object({
384
+ records: z.array(collectionRecord).meta({
385
+ description: 'The records of the page. A page is cut short at 4 MiB of stored record values (for the list of deleted records, of the revisions that deleted them), so it can hold fewer than `limit` records while more follow. It always holds at least one record when there is one, and a list of ordinary size is never cut.',
386
+ }),
387
+ next_cursor: z.string().nullable().meta({
388
+ description: 'Send it as `cursor` to read the next page; it continues after the last record this page holds. Null when this is the last page, which a short page does not say on its own: only `null` says the list is at its end.',
389
+ }),
390
+ total: count.meta({ description: 'The number of records that match, sent only when `count=true` was asked for. A page cut short does not change it.' }).optional(),
391
+ })
392
+ .meta({ description: 'One page of records.' });
393
+ // ---------------------------------------------------------------------------
394
+ // Writing records
395
+ // ---------------------------------------------------------------------------
396
+ /**
397
+ * A create or an update. Updates have `PATCH` semantics: only the fields sent
398
+ * change, and `null` clears one. `robot_id` is read on create only, because a
399
+ * record never changes its robot.
400
+ */
401
+ export const collectionRecordWrite = z
402
+ .object({
403
+ values: z.record(z.string(), z.unknown()).meta({
404
+ description: `The fields to set by key. A \`null\` clears a field. On an update, fields that are left out keep their value. A record may hold ${COLLECTION_LIMITS.recordBytes.toLocaleString('en-US')} bytes of values as JSON; more is \`400 validation_error\`, field \`values\`, rule \`record_too_large\`, and so is a request body of more than 2 MiB.`,
405
+ }),
406
+ robot_id: z.uuid().meta({ description: 'The robot of a new record in a collection that belongs to robots. Fixed once the record exists.' }).optional(),
407
+ expected_revision: z
408
+ .number()
409
+ .int()
410
+ .min(1)
411
+ .meta({ description: 'The revision you last read. The write is refused with `record_changed` if the record has moved on.' })
412
+ .optional(),
413
+ })
414
+ .strict()
415
+ .meta({ description: 'The body of a record create or update.' });
416
+ // ---------------------------------------------------------------------------
417
+ // History
418
+ // ---------------------------------------------------------------------------
419
+ /**
420
+ * One entry of a record's history. `changes` holds each changed field with its
421
+ * old and new value, `null` standing for no value. A `delete` revision carries
422
+ * the whole record so that a deleted record can be seen and brought back.
423
+ */
424
+ export const collectionRevision = z
425
+ .object({
426
+ seq: z.number().int().positive().meta({ description: 'The position of this revision in the history. Use it to page (`before_seq`) and to restore (`seq`).' }),
427
+ op: z.enum(['create', 'update', 'delete', 'restore']),
428
+ at: timestamp,
429
+ actor: collectionActor,
430
+ reason: z.string().nullable().meta({ description: 'Why a change was made when it was not an ordinary write: `schema v5`, `import`, `restore v4`. Null otherwise.' }),
431
+ revision: z.number().int().min(1).meta({ description: 'The record\'s revision number after this change.' }),
432
+ changes: z.record(z.string(), z.object({ old: z.unknown(), new: z.unknown() })).meta({
433
+ description: 'The fields this change touched by key, each with its value before and after. `null` means no value.',
434
+ }),
435
+ record: collectionRecord.nullable().meta({ description: 'The whole record, on a `delete` revision. Null on every other operation.' }),
436
+ })
437
+ .meta({ description: 'One change in the history of a record.' });
438
+ export const collectionRecordHistoryQuery = z
439
+ .object({
440
+ limit: pageLimit
441
+ .meta({ description: `The most revisions to return, 1 to ${COLLECTION_LIMITS.pageMax}. A page can hold fewer: see \`next_before_seq\`.` })
442
+ .optional(),
443
+ before_seq: wireSeqCursor.meta({ description: 'Only revisions older than this `seq`: the next page, since the history is read newest first.' }).optional(),
444
+ })
445
+ .strict();
446
+ export const collectionRecordHistoryResponse = z
447
+ .object({
448
+ revisions: z.array(collectionRevision).meta({
449
+ description: 'The revisions of the page, newest first. A page is cut short at 4 MiB of stored revisions, since the changes of a revision keep the old and the new value and a `delete` the whole record. It always holds at least one revision, and a history of ordinary size is never cut.',
450
+ }),
451
+ next_before_seq: z.number().int().positive().nullable().meta({
452
+ description: 'Send it as `before_seq` to read older revisions; it names the last revision this page holds, also when the page was cut short. Null when there are none.',
453
+ }),
454
+ purged: z
455
+ .object({
456
+ before: timestamp.meta({ description: 'Revisions older than this were removed.' }),
457
+ by: collectionActor,
458
+ at: timestamp.meta({ description: 'When they were removed.' }),
459
+ })
460
+ .nullable()
461
+ .meta({ description: 'Set when an organization owner removed the older part of this history: the history then starts with that note.' }),
462
+ })
463
+ .meta({ description: 'A page of a record\'s history, newest first.' });
464
+ /**
465
+ * Restores a record. With `seq` the record gets the values it had after that
466
+ * revision; without it, a deleted record comes back as it was deleted.
467
+ */
468
+ export const collectionRecordRestoreRequest = z
469
+ .object({
470
+ seq: z.number().int().positive().meta({ description: 'Put the record back to its state after this revision. Leave it out to restore a deleted record.' }).optional(),
471
+ })
472
+ .strict()
473
+ .meta({ description: 'The body of a record restore.' });
474
+ // ---------------------------------------------------------------------------
475
+ // Listing the collections
476
+ // ---------------------------------------------------------------------------
477
+ /** One collection in the developer's overview, with what it holds and what needs a look. */
478
+ export const collectionSummary = z
479
+ .object({
480
+ key: collectionKey,
481
+ label: z.string(),
482
+ binding: collectionBinding,
483
+ records: count.meta({ description: 'Records the collection holds now.' }),
484
+ fields: count,
485
+ read_roles: z.array(z.string()).meta({ description: 'The roles that may read the records.' }),
486
+ warnings: z
487
+ .array(z.enum(['no_role_access', 'history_growing', 'unknown_role']))
488
+ .meta({
489
+ description: '`no_role_access`: no role may read these records. `unknown_role`: `access` names a role the organization does not have. `history_growing`: the history is far larger than the records, which often means a client writing in a loop.',
490
+ }),
491
+ revisions: count.meta({ description: 'Entries in the history of all the collection\'s records.' }),
492
+ history_bytes: count.meta({ description: 'The size of that history in bytes.' }),
493
+ updated_at: timestamp.nullable().meta({ description: 'When a record of the collection last changed. Null if it never held one.' }),
494
+ })
495
+ .meta({ description: 'A collection as the developer\'s overview shows it.' });
496
+ export const collectionListResponse = z
497
+ .object({
498
+ version: schemaVersion.nullable().meta({ description: 'The published schema version. Null before anything was published.' }),
499
+ collections: z.array(collectionSummary),
500
+ })
501
+ .meta({ description: 'The collections of an app.' });
502
+ /** What one collection allows the caller to do with its records. */
503
+ const collectionCan = z
504
+ .object({
505
+ read: z.boolean(),
506
+ create: z.boolean(),
507
+ update: z.union([z.enum(['all', 'own']), z.literal(false)]).meta({ description: '`all`: any record. `own`: only records the caller created. `false`: none.' }),
508
+ delete: z.union([z.enum(['all', 'own']), z.literal(false)]).meta({ description: '`all`: any record. `own`: only records the caller created. `false`: none.' }),
509
+ })
510
+ .meta({ description: 'What the caller may do with the records of this collection.' });
511
+ /** The collections the caller can read, with their fields: what a client needs to build a form. */
512
+ export const collectionDefinitionsResponse = z
513
+ .object({
514
+ version: schemaVersion.nullable().meta({ description: 'The published schema version. Null before anything was published.' }),
515
+ collections: z.array(z.object({
516
+ key: collectionKey,
517
+ label: z.string(),
518
+ description: z.string(),
519
+ binding: collectionBinding,
520
+ display: z.string().meta({ description: 'The template that names a record of this collection.' }),
521
+ fields: z.record(collectionKey, collectionField),
522
+ can: collectionCan,
523
+ })),
524
+ })
525
+ .meta({ description: 'The collections the caller may read, with their field definitions and the caller\'s rights.' });
@@ -0,0 +1,17 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+ import { z } from 'zod';
3
+ export declare const roleCollectionRights: z.ZodObject<{
4
+ collection: z.ZodString;
5
+ label: z.ZodString;
6
+ binding: z.ZodEnum<{
7
+ global: "global";
8
+ per_robot: "per_robot";
9
+ one_per_robot: "one_per_robot";
10
+ }>;
11
+ read: z.ZodBoolean;
12
+ create: z.ZodBoolean;
13
+ update: z.ZodUnion<readonly [z.ZodLiteral<"all">, z.ZodLiteral<"own">, z.ZodLiteral<false>]>;
14
+ delete: z.ZodUnion<readonly [z.ZodLiteral<"all">, z.ZodLiteral<"own">, z.ZodLiteral<false>]>;
15
+ robot_filter: z.ZodBoolean;
16
+ }, z.core.$strip>;
17
+ export type RoleCollectionRights = z.infer<typeof roleCollectionRights>;
@@ -0,0 +1,41 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+ import { z } from 'zod';
3
+ import { collectionBinding, collectionKey } from './collections.js';
4
+ /**
5
+ * What a role may do with the records of one collection, as the published
6
+ * schema's `access` rules resolve for it (inheritance between roles applied,
7
+ * a key that names no role granting nothing). One row per collection of the
8
+ * latest published version; it rides on the effective-rights answer
9
+ * (`GET /api/apps/:id/effective-rights` and the console tool's
10
+ * `effective_rights`) so the "view as role" page can show it beside the
11
+ * robots, and nothing here can be edited.
12
+ *
13
+ * **`update` and `delete` say which records, not just whether.** A bare `true`
14
+ * would hide the one distinction `access` exists to draw: `all` is every
15
+ * record, `own` only those the app user created, `false` none. `read` and
16
+ * `create` have no such scope. `create` is `false` on a `one_per_robot`
17
+ * collection, whose records Fleetless creates itself, and so is `delete`,
18
+ * which the API never does there.
19
+ *
20
+ * Developers and server keys always may do everything; this row is about an
21
+ * app user holding the role, so it says nothing about them.
22
+ */
23
+ const records = z.union([z.literal('all'), z.literal('own'), z.literal(false)]);
24
+ export const roleCollectionRights = z
25
+ .object({
26
+ collection: collectionKey.meta({ description: 'The collection\'s key.' }),
27
+ label: z.string().meta({ description: 'The collection\'s label for people to read; its key when the schema gives none.' }),
28
+ binding: collectionBinding,
29
+ read: z.boolean().meta({ description: 'Whether the role may read the records.' }),
30
+ create: z.boolean().meta({ description: 'Whether the role may create records.' }),
31
+ update: records.meta({
32
+ description: '`all`: the role may change every record. `own`: only records its user created. `false`: none.',
33
+ }),
34
+ delete: records.meta({
35
+ description: '`all`: the role may delete every record. `own`: only records its user created. `false`: none.',
36
+ }),
37
+ robot_filter: z.boolean().meta({
38
+ description: '`true` on a collection that belongs to robots (`per_robot`, `one_per_robot`): the role sees and writes only the records of robots a session of the role reaches, whatever the rights above say. `false` on a `global` collection.',
39
+ }),
40
+ })
41
+ .meta({ description: 'What one role may do with the records of one collection.' });