@fleetless/contracts 14.0.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 (119) hide show
  1. package/CHANGELOG.md +163 -0
  2. package/artifacts/openapi.json +19842 -11398
  3. package/artifacts/routes.json +1160 -39
  4. package/artifacts/schema/addon-catalogue-entry.schema.json +3 -1
  5. package/artifacts/schema/admin-plan-change-request.schema.json +26 -0
  6. package/artifacts/schema/app-deletion-summary.schema.json +15 -1
  7. package/artifacts/schema/asset-plan-limit-details.schema.json +3 -1
  8. package/artifacts/schema/cloud-config.schema.json +5 -5
  9. package/artifacts/schema/collection-actor.schema.json +35 -0
  10. package/artifacts/schema/collection-definitions-response.schema.json +612 -0
  11. package/artifacts/schema/collection-event.schema.json +216 -0
  12. package/artifacts/schema/collection-export-query.schema.json +56 -0
  13. package/artifacts/schema/collection-filter.schema.json +9 -0
  14. package/artifacts/schema/collection-import-preview.schema.json +143 -0
  15. package/artifacts/schema/collection-import-request.schema.json +105 -0
  16. package/artifacts/schema/collection-import-result.schema.json +38 -0
  17. package/artifacts/schema/collection-list-response.schema.json +119 -0
  18. package/artifacts/schema/collection-record-get-query.schema.json +12 -0
  19. package/artifacts/schema/collection-record-history-query.schema.json +35 -0
  20. package/artifacts/schema/collection-record-history-response.schema.json +389 -0
  21. package/artifacts/schema/collection-record-list-query.schema.json +67 -0
  22. package/artifacts/schema/collection-record-list-response.schema.json +212 -0
  23. package/artifacts/schema/collection-record-restore-request.schema.json +14 -0
  24. package/artifacts/schema/collection-record-write.schema.json +31 -0
  25. package/artifacts/schema/collection-record.schema.json +180 -0
  26. package/artifacts/schema/collection-revision.schema.json +295 -0
  27. package/artifacts/schema/collection-subscribe-error.schema.json +31 -0
  28. package/artifacts/schema/collection-subscribe.schema.json +48 -0
  29. package/artifacts/schema/collection-subscribed.schema.json +22 -0
  30. package/artifacts/schema/collection-summary.schema.json +92 -0
  31. package/artifacts/schema/collection-unsubscribe.schema.json +22 -0
  32. package/artifacts/schema/collections-access-change.schema.json +34 -0
  33. package/artifacts/schema/collections-document.schema.json +732 -0
  34. package/artifacts/schema/collections-draft-response.schema.json +845 -0
  35. package/artifacts/schema/collections-effect.schema.json +384 -0
  36. package/artifacts/schema/collections-issue.schema.json +36 -0
  37. package/artifacts/schema/collections-publish-request.schema.json +18 -0
  38. package/artifacts/schema/collections-publish-response.schema.json +450 -0
  39. package/artifacts/schema/collections-purge-preview.schema.json +60 -0
  40. package/artifacts/schema/collections-purge-request.schema.json +27 -0
  41. package/artifacts/schema/collections-purge-response.schema.json +30 -0
  42. package/artifacts/schema/collections-restore-preview-query.schema.json +20 -0
  43. package/artifacts/schema/collections-restore-preview.schema.json +581 -0
  44. package/artifacts/schema/collections-restore-request.schema.json +27 -0
  45. package/artifacts/schema/collections-restore-response.schema.json +455 -0
  46. package/artifacts/schema/collections-schema-preview.schema.json +519 -0
  47. package/artifacts/schema/collections-schema-published.schema.json +22 -0
  48. package/artifacts/schema/collections-version-response.schema.json +869 -0
  49. package/artifacts/schema/collections-version-summary.schema.json +139 -0
  50. package/artifacts/schema/collections-versions-response.schema.json +167 -0
  51. package/artifacts/schema/config-draft-response.schema.json +5 -5
  52. package/artifacts/schema/config-version-response.schema.json +5 -5
  53. package/artifacts/schema/confirmation-required-details.schema.json +13 -0
  54. package/artifacts/schema/dangling-reference.schema.json +7 -6
  55. package/artifacts/schema/datapoint-list-response.schema.json +2 -2
  56. package/artifacts/schema/effective-rights-response.schema.json +87 -1
  57. package/artifacts/schema/org-plan.schema.json +29 -1
  58. package/artifacts/schema/org-quota-usage-counts.schema.json +18 -0
  59. package/artifacts/schema/org-quota-usage.schema.json +47 -1
  60. package/artifacts/schema/org-quotas.schema.json +29 -1
  61. package/artifacts/schema/org-role-list-response.schema.json +8 -7
  62. package/artifacts/schema/org-role.schema.json +1 -1
  63. package/artifacts/schema/plan-catalogue-entry.schema.json +29 -1
  64. package/artifacts/schema/plan-change-decision-status-response.schema.json +29 -1
  65. package/artifacts/schema/plan-limit-details.schema.json +3 -1
  66. package/artifacts/schema/plan-limits.schema.json +29 -1
  67. package/artifacts/schema/plan-overrides.schema.json +26 -0
  68. package/artifacts/schema/put-collections-draft-request.schema.json +16 -0
  69. package/artifacts/schema/record-changed-details.schema.json +16 -0
  70. package/artifacts/schema/record-referenced-details.schema.json +35 -0
  71. package/artifacts/schema/reference-invalid-details.schema.json +25 -0
  72. package/artifacts/schema/reference-place.schema.json +7 -6
  73. package/artifacts/schema/required-missing-details.schema.json +19 -0
  74. package/artifacts/schema/robot-config-doc.schema.json +5 -5
  75. package/artifacts/schema/robot-deletion-summary.schema.json +33 -1
  76. package/artifacts/schema/role-collection-rights.schema.json +82 -0
  77. package/artifacts/schema/role-rename-preview.schema.json +7 -6
  78. package/dist/apps.d.ts +18 -2
  79. package/dist/apps.js +12 -2
  80. package/dist/audit.d.ts +32 -2
  81. package/dist/audit.js +40 -2
  82. package/dist/collections-issues.d.ts +67 -0
  83. package/dist/collections-issues.js +340 -0
  84. package/dist/collections-records.d.ts +562 -0
  85. package/dist/collections-records.js +525 -0
  86. package/dist/collections-rights.d.ts +17 -0
  87. package/dist/collections-rights.js +41 -0
  88. package/dist/collections-schema.d.ts +1064 -0
  89. package/dist/collections-schema.js +386 -0
  90. package/dist/collections-templates.d.ts +55 -0
  91. package/dist/collections-templates.js +137 -0
  92. package/dist/collections-transfer.d.ts +101 -0
  93. package/dist/collections-transfer.js +206 -0
  94. package/dist/collections-values.d.ts +67 -0
  95. package/dist/collections-values.js +284 -0
  96. package/dist/collections.d.ts +568 -0
  97. package/dist/collections.js +332 -0
  98. package/dist/config.d.ts +8 -8
  99. package/dist/config.js +13 -13
  100. package/dist/errors.d.ts +50 -1
  101. package/dist/errors.js +115 -0
  102. package/dist/index.d.ts +24 -8
  103. package/dist/index.js +13 -3
  104. package/dist/org-roles.d.ts +4 -0
  105. package/dist/org-roles.js +10 -9
  106. package/dist/plans.d.ts +19 -1
  107. package/dist/plans.js +21 -1
  108. package/dist/realtime.d.ts +166 -0
  109. package/dist/realtime.js +163 -0
  110. package/dist/rest.d.ts +28 -28
  111. package/dist/rest.js +39 -27
  112. package/dist/rights.d.ts +2 -2
  113. package/dist/rights.js +1 -1
  114. package/dist/routes.d.ts +1 -1
  115. package/dist/routes.js +495 -21
  116. package/package.json +1 -1
  117. package/artifacts/schema/put-robot-details-request.schema.json +0 -41
  118. package/artifacts/schema/put-robot-details-response.schema.json +0 -43
  119. package/artifacts/schema/robot-details-doc.schema.json +0 -33
@@ -0,0 +1,101 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+ import { z } from 'zod';
3
+ /**
4
+ * An import, as a preview request and as the confirming request: the same body,
5
+ * with `confirm` added the second time.
6
+ *
7
+ * `mode: 'mirror'` needs `key`, because records are matched to the file by it.
8
+ * That is a rule across two fields, which JSON Schema cannot express, so the
9
+ * published artifact describes both as independent and the cloud is the only
10
+ * place that refuses the combination with a `400 validation_error`. It
11
+ * refuses, in the same way, `key` and `mirror` on a `one_per_robot`
12
+ * collection (rule `one_per_robot_is_automatic`) and a `robot_id` sent together
13
+ * with a `robot` column in the file (rule `robot_column_present`).
14
+ */
15
+ export declare const collectionImportRequest: z.ZodObject<{
16
+ format: z.ZodEnum<{
17
+ json: "json";
18
+ csv: "csv";
19
+ }>;
20
+ content: z.ZodString;
21
+ mapping: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnion<[z.ZodString, z.ZodLiteral<"">]>>>;
22
+ references: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodString>>;
23
+ key: z.ZodOptional<z.ZodString>;
24
+ mode: z.ZodOptional<z.ZodEnum<{
25
+ upsert: "upsert";
26
+ mirror: "mirror";
27
+ }>>;
28
+ scope: z.ZodOptional<z.ZodObject<{
29
+ filter: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
30
+ robot_id: z.ZodOptional<z.ZodUUID>;
31
+ }, z.core.$strict>>;
32
+ robot_id: z.ZodOptional<z.ZodUUID>;
33
+ confirm: z.ZodOptional<z.ZodString>;
34
+ }, z.core.$strict>;
35
+ export type CollectionImportRequest = z.infer<typeof collectionImportRequest>;
36
+ /**
37
+ * What an import would do. `token` is present exactly when the file has no
38
+ * errors, since a file with errors cannot be imported and so needs no
39
+ * confirmation.
40
+ */
41
+ export declare const collectionImportPreview: z.ZodObject<{
42
+ counts: z.ZodObject<{
43
+ unchanged: z.ZodNumber;
44
+ new: z.ZodNumber;
45
+ updated: z.ZodNumber;
46
+ deleted: z.ZodNumber;
47
+ errors: z.ZodNumber;
48
+ }, z.core.$strip>;
49
+ errors: z.ZodArray<z.ZodObject<{
50
+ row: z.ZodNumber;
51
+ column: z.ZodString;
52
+ value: z.ZodString;
53
+ reason: z.ZodString;
54
+ }, z.core.$strip>>;
55
+ errors_total: z.ZodNumber;
56
+ mirror_scope: z.ZodNullable<z.ZodEnum<{
57
+ filter: "filter";
58
+ robot: "robot";
59
+ collection: "collection";
60
+ }>>;
61
+ warnings: z.ZodArray<z.ZodEnum<{
62
+ plan_limit: "plan_limit";
63
+ }>>;
64
+ token: z.ZodNullable<z.ZodString>;
65
+ }, z.core.$strip>;
66
+ export type CollectionImportPreview = z.infer<typeof collectionImportPreview>;
67
+ export declare const collectionImportResult: z.ZodObject<{
68
+ created: z.ZodNumber;
69
+ updated: z.ZodNumber;
70
+ deleted: z.ZodNumber;
71
+ unchanged: z.ZodNumber;
72
+ }, z.core.$strip>;
73
+ export type CollectionImportResult = z.infer<typeof collectionImportResult>;
74
+ /**
75
+ * The query string of an export. The filter, search and sort are those of the
76
+ * record list, so a file contains what the list showed.
77
+ *
78
+ * The columns, in order: `robot` (the robot's name) first in a collection that
79
+ * belongs to robots, then the fields, then with `system=true` the system
80
+ * fields. A CSV cell, or a robot name, whose text starts with apostrophes and
81
+ * then `=`, `+`, `-` or `@` (white space before one counts) gets one more
82
+ * apostrophe, so that a spreadsheet does not read it as a formula; an import
83
+ * takes exactly one off again, so an exported file imports to the same values.
84
+ */
85
+ export declare const collectionExportQuery: z.ZodObject<{
86
+ fields: z.ZodOptional<z.ZodString>;
87
+ references: z.ZodOptional<z.ZodString>;
88
+ system: z.ZodOptional<z.ZodEnum<{
89
+ true: "true";
90
+ false: "false";
91
+ }>>;
92
+ search: z.ZodOptional<z.ZodString>;
93
+ filter: z.ZodOptional<z.ZodString>;
94
+ sort: z.ZodOptional<z.ZodString>;
95
+ robot: z.ZodOptional<z.ZodUUID>;
96
+ format: z.ZodEnum<{
97
+ json: "json";
98
+ csv: "csv";
99
+ }>;
100
+ }, z.core.$strict>;
101
+ export type CollectionExportQuery = z.infer<typeof collectionExportQuery>;
@@ -0,0 +1,206 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+ import { z } from 'zod';
3
+ import { COLLECTION_LIMITS, collectionKey } from './collections.js';
4
+ import { collectionFilter, collectionRecordListQuery } from './collections-records.js';
5
+ /**
6
+ * Getting records into and out of a collection in bulk: a CSV or JSON file in,
7
+ * a CSV or JSON file out.
8
+ *
9
+ * **An import is all or nothing.** One invalid row, a reference that cannot be
10
+ * resolved, a plan limit that would be exceeded or a deletion that a `prevent`
11
+ * reference blocks fails the whole file, and nothing is written. The same
12
+ * request is made twice: the first time (or the `…/import/preview` route)
13
+ * answers a preview, the second carries the preview's `token` as `confirm`
14
+ * and imports. Without `confirm`, the import route answers `200` with the
15
+ * preview, as the preview route does, and imports nothing. With a `confirm`
16
+ * that is not the token of the preview of exactly this import, because the
17
+ * data changed in between so that the counts differ, or the token belongs to
18
+ * another import, the answer is `409 confirmation_required` with the current
19
+ * preview in `details.preview`. A file with errors answers its preview, with
20
+ * `token: null`, whatever `confirm` says.
21
+ *
22
+ * The token stands for the file, the mapping, the references, the key, the
23
+ * mode, the scope, `robot_id` and the counts, and for the records the import
24
+ * would match, with their revisions, and the ones a mirror would delete. It is
25
+ * not single-use: sending the confirmation of a keyless import again creates
26
+ * its rows again, so a client that did not hear the answer to a first attempt
27
+ * looks at the collection before it repeats one.
28
+ *
29
+ * **Every import goes through the same checks as single writes** (field
30
+ * values, uniqueness, required fields, references, plan limits), and its
31
+ * rows are written as revisions with the reason `import`.
32
+ */
33
+ /** The most errors a preview lists; `errors_total` stays exact. */
34
+ const IMPORT_ERRORS_LISTED = 1000;
35
+ const count = z.number().int().min(0);
36
+ const confirm = z
37
+ .string()
38
+ .min(1)
39
+ .meta({
40
+ description: 'The `token` of the preview of exactly this import. Without it the import route answers the preview and imports nothing. A token that is not the one of the current preview, because the data moved on or it belongs to another import, is answered `409 confirmation_required` with the current preview in `details.preview`. A file with errors is never imported: its preview comes back with `token: null`, whatever `confirm` says.',
41
+ });
42
+ /** What a mapping can send a column to: a field, the robot of the record, or nowhere. */
43
+ const mappingTarget = collectionKey.or(z.literal('')).meta({
44
+ description: 'The key of the field the column is imported into, the literal `robot`, or an empty string to leave the column out.',
45
+ });
46
+ /**
47
+ * The scope of a `mirror` import: the part of the collection in which records
48
+ * that are missing from the file are deleted. A mirror without a scope covers
49
+ * the whole collection.
50
+ *
51
+ * `{}` is not a scope: the cloud refuses it (`400 validation_error`, field
52
+ * `scope`, rule `empty`), and so a scope on an import that is not a `mirror`
53
+ * (rule `needs_mirror`). JSON Schema cannot express either rule, so the
54
+ * artifact describes `scope` as an object with two optional keys.
55
+ */
56
+ const importScope = z
57
+ .object({
58
+ filter: collectionFilter
59
+ .meta({ description: 'Only records matching this filter can be deleted. The same filter object that record lists take as JSON text.' })
60
+ .optional(),
61
+ robot_id: z.uuid().meta({ description: 'Only records of this robot can be deleted.' }).optional(),
62
+ })
63
+ .strict()
64
+ .refine((scope) => !(scope.filter !== undefined && scope.robot_id !== undefined), {
65
+ message: 'A scope is a filter or a robot, not both',
66
+ path: ['robot_id'],
67
+ })
68
+ .meta({
69
+ description: 'Limits which records `mirror` may delete: those matching a filter, or those of one robot. Name exactly one of them: an empty `scope` is `400 validation_error` (rule `empty`), and so is a `scope` on an import that is not a `mirror` (rule `needs_mirror`). Without a scope the whole collection is mirrored, every robot\'s records included. `robot_id` of the request does not narrow a mirror; use `scope.robot_id`.',
70
+ });
71
+ /**
72
+ * An import, as a preview request and as the confirming request: the same body,
73
+ * with `confirm` added the second time.
74
+ *
75
+ * `mode: 'mirror'` needs `key`, because records are matched to the file by it.
76
+ * That is a rule across two fields, which JSON Schema cannot express, so the
77
+ * published artifact describes both as independent and the cloud is the only
78
+ * place that refuses the combination with a `400 validation_error`. It
79
+ * refuses, in the same way, `key` and `mirror` on a `one_per_robot`
80
+ * collection (rule `one_per_robot_is_automatic`) and a `robot_id` sent together
81
+ * with a `robot` column in the file (rule `robot_column_present`).
82
+ */
83
+ export const collectionImportRequest = z
84
+ .object({
85
+ format: z.enum(['csv', 'json']).meta({
86
+ description: '`csv`: UTF-8 text with a header row, as in RFC 4180; a `json` field is written as JSON text in its cell. `json`: an array of objects, one per record.',
87
+ }),
88
+ content: z.string().max(COLLECTION_LIMITS.importBytes).meta({
89
+ description: `The file as text, at most ${COLLECTION_LIMITS.importBytes.toLocaleString('en-US')} characters and as many bytes of UTF-8, and ${COLLECTION_LIMITS.importRows.toLocaleString('en-US')} rows (\`400 validation_error\`, rule \`too_large\` or \`too_many_rows\`; the latter is raised as soon as the 50,001st row is read, so it does not say how many there are). A byte order mark at the start of a JSON file is ignored.`,
90
+ }),
91
+ mapping: z.record(z.string(), mappingTarget).meta({
92
+ description: 'Where each column of the file goes, by the column name in the header (for JSON, the property name). A column that is not listed is imported into the field with the same key. A column named after a system field (`id`, `created_at`, `created_by`, `updated_at`, `updated_by`, `revision`, `robot_id`) is left out unless it is mapped.',
93
+ }).optional(),
94
+ references: z.record(collectionKey, collectionKey).meta({
95
+ description: 'For each reference field, by its key: the unique field of the target collection that the values in its column identify, for example `name`. A reference field that is not listed takes record ids.',
96
+ }).optional(),
97
+ key: collectionKey.meta({
98
+ description: 'A unique field that matches rows to existing records: a row whose value is found updates that record, the rest create records. Without a key every row creates a record. A collection with one record per robot is only updated, matched by robot, takes no key and no mirror, and two rows for one robot are an error.',
99
+ }).optional(),
100
+ mode: z.enum(['upsert', 'mirror']).meta({
101
+ description: '`upsert` (the default) creates and updates records. `mirror` also deletes the records of `scope` that are not in the file, and needs `key`. A mirror deletes at most 50,000 records, a file without rows is refused, and a deletion that a `prevent` reference blocks fails the whole import. A collection with one record per robot takes neither a `key` nor a `mirror` (`400 validation_error`, rule `one_per_robot_is_automatic`).',
102
+ }).optional(),
103
+ scope: importScope.optional(),
104
+ robot_id: z.uuid().meta({
105
+ description: 'The robot every row belongs to, in a collection that belongs to robots, when the file has no `robot` column; sent together with a `robot` column it is refused (rule `robot_column_present`). It says which robot the rows are for and does not narrow a `mirror`: that is `scope.robot_id`.',
106
+ }).optional(),
107
+ confirm: confirm.optional(),
108
+ })
109
+ .strict()
110
+ .refine((request) => request.mode !== 'mirror' || request.key !== undefined, {
111
+ message: 'Mode "mirror" needs a key: records are matched to the file by it',
112
+ path: ['key'],
113
+ })
114
+ .meta({ description: 'Imports a file of records into a collection, all or nothing.' });
115
+ /** One thing wrong with the file. */
116
+ const importError = z
117
+ .object({
118
+ row: count.meta({
119
+ description: 'The row the problem is in, counted from 1 over the records of the file, so the header of a CSV is not counted. 0 marks a problem with the file as a whole, and a deletion of a `mirror` that a `prevent` reference blocks (the column is then the key column and the value the key of the record).',
120
+ }),
121
+ column: z
122
+ .string()
123
+ .max(COLLECTION_LIMITS.importErrorText)
124
+ .meta({ description: 'The column as named in the file. Empty when the problem is not about one column. Cut to 200 characters, an ellipsis included.' }),
125
+ value: z
126
+ .string()
127
+ .max(COLLECTION_LIMITS.importErrorText)
128
+ .meta({ description: 'The value as found in the file, cut to 200 characters with an ellipsis (`…`) at the end when it was longer.' }),
129
+ reason: z.string().min(1).meta({ description: 'What is wrong with it, in words.' }),
130
+ })
131
+ .meta({ description: 'A row, column and value that stop the import, with the reason.' });
132
+ /**
133
+ * What an import would do. `token` is present exactly when the file has no
134
+ * errors, since a file with errors cannot be imported and so needs no
135
+ * confirmation.
136
+ */
137
+ export const collectionImportPreview = z
138
+ .object({
139
+ counts: z
140
+ .object({
141
+ unchanged: count.meta({ description: 'Rows that match a record that already has these values.' }),
142
+ new: count.meta({ description: 'Records that would be created.' }),
143
+ updated: count.meta({ description: 'Records that would change.' }),
144
+ deleted: count.meta({ description: 'Records that `mirror` would delete.' }),
145
+ errors: count.meta({ description: 'Problems found in the file. The same number as `errors_total`.' }),
146
+ })
147
+ .meta({ description: 'What the import would do, counted.' }),
148
+ errors: z.array(importError).max(IMPORT_ERRORS_LISTED).meta({
149
+ description: `The problems found, in file order, at most ${IMPORT_ERRORS_LISTED.toLocaleString('en-US')}; \`errors_total\` is the exact number.`,
150
+ }),
151
+ errors_total: count.meta({ description: 'The exact number of problems found.' }),
152
+ mirror_scope: z.enum(['collection', 'filter', 'robot']).nullable().meta({
153
+ description: 'Where `mirror` would delete records: `collection` is every record of the collection, which the preview should say prominently; `filter` and `robot` are the scope that was sent. Null when the mode is not `mirror`.',
154
+ }),
155
+ warnings: z.array(z.enum(['plan_limit'])).meta({
156
+ description: '`plan_limit`: importing the file would take the organization over a limit of its plan, so the import itself would be refused.',
157
+ }),
158
+ token: z.string().min(1).nullable().meta({
159
+ description: 'Stands for exactly this import: send it as `confirm` to carry it out. Null while the file has errors. It is not single-use; see the note on the import routes.',
160
+ }),
161
+ })
162
+ .meta({ description: 'The preview of an import: what it would do, the problems that stop it and the token that confirms it.' });
163
+ export const collectionImportResult = z
164
+ .object({
165
+ created: count.meta({ description: 'Records created.' }),
166
+ updated: count.meta({ description: 'Records changed.' }),
167
+ deleted: count.meta({ description: 'Records deleted by `mirror`.' }),
168
+ unchanged: count.meta({ description: 'Rows that matched a record that already had these values.' }),
169
+ })
170
+ .meta({ description: 'What an import did.' });
171
+ /**
172
+ * The query string of an export. The filter, search and sort are those of the
173
+ * record list, so a file contains what the list showed.
174
+ *
175
+ * The columns, in order: `robot` (the robot's name) first in a collection that
176
+ * belongs to robots, then the fields, then with `system=true` the system
177
+ * fields. A CSV cell, or a robot name, whose text starts with apostrophes and
178
+ * then `=`, `+`, `-` or `@` (white space before one counts) gets one more
179
+ * apostrophe, so that a spreadsheet does not read it as a formula; an import
180
+ * takes exactly one off again, so an exported file imports to the same values.
181
+ */
182
+ export const collectionExportQuery = z
183
+ .object({
184
+ format: z.enum(['csv', 'json']).meta({ description: '`csv`: UTF-8 text with a header row. `json`: an array of objects.' }),
185
+ // The same four parameters, in the same words, as the record list they narrow down.
186
+ ...collectionRecordListQuery.pick({ filter: true, search: true, sort: true, robot: true }).shape,
187
+ fields: z
188
+ .string()
189
+ .min(1)
190
+ .meta({ description: 'The fields to export by key, separated by commas, in the order given. Default: all fields, in the order of the schema.' })
191
+ .optional(),
192
+ references: z
193
+ .string()
194
+ .min(1)
195
+ .meta({
196
+ description: 'How reference fields are written: `id` (the default) or the key of a unique field of the target collection, such as `name`, so that the file can be imported again. A reference field in the file whose target collection has no such unique field is `400 validation_error` (field `references`, rule `not_unique`); with no reference field among the columns the value is ignored.',
197
+ })
198
+ .optional(),
199
+ system: z
200
+ .enum(['true', 'false'])
201
+ .meta({
202
+ description: '`true` adds the system fields after the fields: `robot_id` in a collection that belongs to robots, then `id`, `created_at`, `created_by`, `updated_at`, `updated_by` and `revision`. `created_by` and `updated_by` are the actors\' labels. Default `false`.',
203
+ })
204
+ .optional(),
205
+ })
206
+ .strict();
@@ -0,0 +1,67 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+ import { type CollectionField } from './collections.js';
3
+ /**
4
+ * Whether a value fits a field, written once for everyone who has to ask.
5
+ *
6
+ * The cloud asks it for every record write and import row, and the document
7
+ * asks it of a field's `default` (`collectionsDocumentIssues`). One function
8
+ * answers both, so a default the document accepts is a value a write accepts.
9
+ *
10
+ * It judges **a value**, and `null` is not one: in a write `null` clears a
11
+ * field, so a caller handles it before asking. Whether an empty value is
12
+ * allowed (`required`) and whether it repeats (`unique`) are record questions,
13
+ * not value questions, and are decided by the caller.
14
+ */
15
+ /** What is wrong with a value: a stable code to branch on, and a sentence for a person. */
16
+ export type CollectionValueProblem = {
17
+ code: string;
18
+ message: string;
19
+ };
20
+ export type CollectionValueOptions = {
21
+ /**
22
+ * Checks a JSON value against a JSON Schema and returns what is wrong with
23
+ * it, or `null`. Contracts has no JSON Schema validator of its own, so the
24
+ * caller supplies one; without it a `json` value is accepted as it is. It is
25
+ * handed the schema itself: for a template name, the template's schema.
26
+ */
27
+ validateJsonValue?: (schema: unknown, value: unknown) => string | null;
28
+ /**
29
+ * Whether `value` matches the regular expression `pattern` of a `text`
30
+ * field. Patterns are written in the RE2 subset and the server matches them
31
+ * with an RE2 engine, whose time grows with the text and not with the
32
+ * pattern. Contracts has no such engine, and the JavaScript one can take
33
+ * exponential time for a pattern such as `(a+)+$`, so the server passes its
34
+ * own. Without one the JavaScript engine is used, which suits feedback on an
35
+ * author's own pattern in a browser and not matching what other people send.
36
+ * It throws for a pattern it cannot compile; that is reported like a pattern
37
+ * the JavaScript engine cannot compile.
38
+ *
39
+ * **A partial match, not a full one**: the pattern may match anywhere in the
40
+ * value, as `RegExp.prototype.test` does and as RE2's `PartialMatch` does. A
41
+ * pattern that must match the whole value anchors itself with `^` and `$`, as
42
+ * the field's description says. An engine wrapper that matched the whole value
43
+ * would silently change what every unanchored pattern means.
44
+ */
45
+ matchPattern?: (pattern: string, value: string) => boolean;
46
+ };
47
+ /**
48
+ * Checks `value` against `field`. Returns `null` when it fits and the first
49
+ * problem when it does not.
50
+ *
51
+ * The codes are `type` (the wrong kind of value, or a line break in `text`),
52
+ * `max_length`, `pattern`, `min`, `max`, `integer`, `option`, `multiple`,
53
+ * `date`, `datetime`, `json_schema` and `reference_format`. A `json` value that
54
+ * cannot be stored, because a string in it holds a NUL or half of a surrogate
55
+ * pair or because it nests arrays and objects more than 32 levels deep, is a
56
+ * `type` problem too.
57
+ */
58
+ export declare function checkCollectionValue(field: CollectionField, value: unknown, options?: CollectionValueOptions): CollectionValueProblem | null;
59
+ /**
60
+ * The one spelling a value is stored and compared in. A datetime always has
61
+ * three fractional digits, so `…:00Z`, `…:00.5Z` and `…:00.500Z` are one value
62
+ * for `unique`, filters and sorting; a reference is always a lowercase UUID, so
63
+ * `3F25…` and `3f25…` are one record for `unique`, filters and joins. Every
64
+ * other value is returned unchanged, and so is anything that is not a datetime
65
+ * or an id this module understands.
66
+ */
67
+ export declare function normalizeCollectionValue(field: CollectionField, value: unknown): unknown;
@@ -0,0 +1,284 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+ import { COLLECTION_LIMITS } from './collections.js';
3
+ import { COLLECTION_JSON_TEMPLATES } from './collections-templates.js';
4
+ const problem = (code, message) => ({ code, message });
5
+ /** A value for a message: long text is cut, so a refusal never repeats a megabyte back. */
6
+ const quote = (value) => (value.length > 40 ? `"${value.slice(0, 40)}..."` : `"${value}"`);
7
+ /** The length of a string in characters rather than UTF-16 units, so an emoji counts as one. */
8
+ function characters(value) {
9
+ let count = 0;
10
+ for (const _ of value)
11
+ count += 1;
12
+ return count;
13
+ }
14
+ const LINE_BREAK = /[\r\n\u2028\u2029]/;
15
+ const DATE = /^(\d{4})-(\d{2})-(\d{2})$/;
16
+ const DATETIME = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.(\d{1,3}))?Z$/;
17
+ /**
18
+ * A record id in either letter case. RFC 4122 treats the two as one id and
19
+ * clients differ in what they print (Swift writes uppercase), so both are
20
+ * accepted; `normalizeCollectionValue` then stores the one lowercase spelling.
21
+ */
22
+ const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
23
+ function isCalendarDay(year, month, day) {
24
+ if (year < 1 || month < 1 || month > 12 || day < 1)
25
+ return false;
26
+ const leap = (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0;
27
+ const days = [31, leap ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
28
+ return day <= days[month - 1];
29
+ }
30
+ /**
31
+ * Patterns are compiled once and reused: an import checks the same pattern for
32
+ * every row. A `u` regular expression without the `g` or `y` flag keeps no state
33
+ * between calls, so sharing one is safe. The cache is cleared when it grows, so
34
+ * it cannot hold on to the patterns of a long-running process forever.
35
+ */
36
+ const patterns = new Map();
37
+ function compile(pattern) {
38
+ const known = patterns.get(pattern);
39
+ if (known !== undefined)
40
+ return known;
41
+ let compiled;
42
+ try {
43
+ compiled = new RegExp(pattern, 'u');
44
+ }
45
+ catch {
46
+ compiled = null;
47
+ }
48
+ if (patterns.size >= 256)
49
+ patterns.clear();
50
+ patterns.set(pattern, compiled);
51
+ return compiled;
52
+ }
53
+ /**
54
+ * Does `text` hold a character that cannot be stored? A database that keeps
55
+ * records as JSON refuses a NUL character (U+0000) and half of a surrogate pair
56
+ * (a code unit from U+D800 to U+DFFF that does not belong to a pair: what is
57
+ * left of an emoji cut in the middle). Such a string is refused here and not
58
+ * left to fail at the write.
59
+ *
60
+ * Read by code unit with a loop, as the check for a pair needs the neighbour and
61
+ * a regular expression for it needs lookbehind, which older browsers lack.
62
+ */
63
+ function hasUnstorableCharacter(text) {
64
+ for (let i = 0; i < text.length; i += 1) {
65
+ const unit = text.charCodeAt(i);
66
+ if (unit === 0)
67
+ return true;
68
+ if (unit >= 0xd800 && unit <= 0xdbff) {
69
+ const next = text.charCodeAt(i + 1);
70
+ if (next >= 0xdc00 && next <= 0xdfff)
71
+ i += 1;
72
+ else
73
+ return true;
74
+ }
75
+ else if (unit >= 0xdc00 && unit <= 0xdfff) {
76
+ return true;
77
+ }
78
+ }
79
+ return false;
80
+ }
81
+ /**
82
+ * What stops a JSON value from being stored: a string or a key of an object
83
+ * anywhere in it that holds a character that cannot be stored, or arrays and
84
+ * objects nested deeper than `COLLECTION_LIMITS.jsonDepth`. Walked with a list
85
+ * of what is left to look at and not by recursion, because a value nested a
86
+ * hundred thousand levels deep must be refused, not crash the stack. The depth
87
+ * is counted while walking, so such a value is refused after a few dozen steps
88
+ * (and so is a structure that contains itself).
89
+ */
90
+ function jsonProblem(value) {
91
+ const pending = [{ item: value, depth: 0 }];
92
+ while (pending.length > 0) {
93
+ const { item, depth } = pending.pop();
94
+ if (typeof item === 'string') {
95
+ if (hasUnstorableCharacter(item))
96
+ return 'unstorable';
97
+ }
98
+ else if (typeof item === 'object' && item !== null) {
99
+ if (depth >= COLLECTION_LIMITS.jsonDepth)
100
+ return 'too_deep';
101
+ if (Array.isArray(item)) {
102
+ for (const child of item)
103
+ pending.push({ item: child, depth: depth + 1 });
104
+ }
105
+ else {
106
+ for (const [key, child] of Object.entries(item)) {
107
+ if (hasUnstorableCharacter(key))
108
+ return 'unstorable';
109
+ pending.push({ item: child, depth: depth + 1 });
110
+ }
111
+ }
112
+ }
113
+ }
114
+ return null;
115
+ }
116
+ const UNSTORABLE_TEXT = 'The text contains a character that cannot be stored: NUL (U+0000) or half of a surrogate pair.';
117
+ const UNSTORABLE_JSON = 'The value contains a character in a string or a key that cannot be stored: NUL (U+0000) or half of a surrogate pair.';
118
+ const TOO_DEEP_JSON = `The value nests arrays and objects more than ${COLLECTION_LIMITS.jsonDepth} levels deep.`;
119
+ /**
120
+ * Whether `value` matches `pattern`, by the injected matcher or else by the
121
+ * JavaScript engine. `null` means the pattern cannot be compiled.
122
+ */
123
+ function matchesPattern(pattern, value, options) {
124
+ if (options.matchPattern !== undefined) {
125
+ try {
126
+ return options.matchPattern(pattern, value);
127
+ }
128
+ catch {
129
+ return null;
130
+ }
131
+ }
132
+ const expression = compile(pattern);
133
+ return expression === null ? null : expression.test(value);
134
+ }
135
+ /**
136
+ * Checks `value` against `field`. Returns `null` when it fits and the first
137
+ * problem when it does not.
138
+ *
139
+ * The codes are `type` (the wrong kind of value, or a line break in `text`),
140
+ * `max_length`, `pattern`, `min`, `max`, `integer`, `option`, `multiple`,
141
+ * `date`, `datetime`, `json_schema` and `reference_format`. A `json` value that
142
+ * cannot be stored, because a string in it holds a NUL or half of a surrogate
143
+ * pair or because it nests arrays and objects more than 32 levels deep, is a
144
+ * `type` problem too.
145
+ */
146
+ export function checkCollectionValue(field, value, options = {}) {
147
+ if (value === null || value === undefined) {
148
+ return problem('type', 'Expected a value. null clears a field and is not itself a value.');
149
+ }
150
+ switch (field.type) {
151
+ case 'text': {
152
+ if (typeof value !== 'string')
153
+ return problem('type', 'Expected text.');
154
+ if (hasUnstorableCharacter(value))
155
+ return problem('type', UNSTORABLE_TEXT);
156
+ if (LINE_BREAK.test(value))
157
+ return problem('type', 'Expected one line of text. Line breaks belong in long_text fields.');
158
+ const max = Math.min(field.max_length ?? COLLECTION_LIMITS.textDefault, COLLECTION_LIMITS.textMax);
159
+ if (value.length > max && characters(value) > max) {
160
+ return problem('max_length', `Too long: the text has ${characters(value)} characters and the field allows ${max}.`);
161
+ }
162
+ if (field.pattern !== undefined) {
163
+ const matched = matchesPattern(field.pattern, value, options);
164
+ if (matched === null)
165
+ return problem('pattern', 'The pattern of this field is not a valid regular expression, so no text can match it.');
166
+ if (!matched)
167
+ return problem('pattern', `The text does not match the pattern ${quote(field.pattern)}.`);
168
+ }
169
+ return null;
170
+ }
171
+ case 'long_text': {
172
+ if (typeof value !== 'string')
173
+ return problem('type', 'Expected text.');
174
+ if (hasUnstorableCharacter(value))
175
+ return problem('type', UNSTORABLE_TEXT);
176
+ const max = Math.min(field.max_length ?? COLLECTION_LIMITS.longTextDefault, COLLECTION_LIMITS.longTextMax);
177
+ if (value.length > max && characters(value) > max) {
178
+ return problem('max_length', `Too long: the text has ${characters(value)} characters and the field allows ${max}.`);
179
+ }
180
+ return null;
181
+ }
182
+ case 'number': {
183
+ if (typeof value !== 'number' || !Number.isFinite(value))
184
+ return problem('type', 'Expected a number.');
185
+ if (field.integer === true && !Number.isInteger(value))
186
+ return problem('integer', `Expected a whole number, got ${value}.`);
187
+ if (field.min !== undefined && value < field.min)
188
+ return problem('min', `${value} is below the smallest allowed value, ${field.min}.`);
189
+ if (field.max !== undefined && value > field.max)
190
+ return problem('max', `${value} is above the largest allowed value, ${field.max}.`);
191
+ return null;
192
+ }
193
+ case 'boolean':
194
+ return typeof value === 'boolean' ? null : problem('type', 'Expected true or false.');
195
+ case 'select': {
196
+ const allowed = new Set(field.options.map((option) => option.value));
197
+ if (field.multiple !== true) {
198
+ if (typeof value !== 'string')
199
+ return problem('type', 'Expected the value of one option, as text.');
200
+ return allowed.has(value) ? null : problem('option', `${quote(value)} is not one of the options.`);
201
+ }
202
+ if (!Array.isArray(value))
203
+ return problem('multiple', 'Expected a list of option values.');
204
+ const seen = new Set();
205
+ for (const item of value) {
206
+ if (typeof item !== 'string')
207
+ return problem('type', 'Expected every option in the list as text.');
208
+ if (seen.has(item))
209
+ return problem('multiple', `${quote(item)} is in the list twice.`);
210
+ if (!allowed.has(item))
211
+ return problem('option', `${quote(item)} is not one of the options.`);
212
+ seen.add(item);
213
+ }
214
+ return null;
215
+ }
216
+ case 'date': {
217
+ if (typeof value !== 'string')
218
+ return problem('type', 'Expected a date as text.');
219
+ const match = DATE.exec(value);
220
+ if (match === null || !isCalendarDay(Number(match[1]), Number(match[2]), Number(match[3]))) {
221
+ return problem('date', `${quote(value)} is not a calendar date written as YYYY-MM-DD.`);
222
+ }
223
+ return null;
224
+ }
225
+ case 'datetime': {
226
+ if (typeof value !== 'string')
227
+ return problem('type', 'Expected a date and time as text.');
228
+ const match = DATETIME.exec(value);
229
+ const [, year, month, day, hour, minute, second] = match ?? [];
230
+ if (match === null ||
231
+ !isCalendarDay(Number(year), Number(month), Number(day)) ||
232
+ Number(hour) > 23 ||
233
+ Number(minute) > 59 ||
234
+ Number(second) > 59) {
235
+ return problem('datetime', `${quote(value)} is not a UTC time written as YYYY-MM-DDTHH:MM:SS.sssZ, with up to three fractional digits.`);
236
+ }
237
+ return null;
238
+ }
239
+ case 'json': {
240
+ if (typeof value === 'function' || typeof value === 'symbol' || typeof value === 'bigint') {
241
+ return problem('type', 'Expected a JSON value.');
242
+ }
243
+ const unstorable = jsonProblem(value);
244
+ if (unstorable !== null)
245
+ return problem('type', unstorable === 'too_deep' ? TOO_DEEP_JSON : UNSTORABLE_JSON);
246
+ if (field.schema === undefined)
247
+ return null;
248
+ let schema = field.schema;
249
+ if (typeof field.schema === 'string') {
250
+ if (!Object.hasOwn(COLLECTION_JSON_TEMPLATES, field.schema)) {
251
+ return problem('json_schema', `${quote(field.schema)} is not the name of a JSON template.`);
252
+ }
253
+ schema = COLLECTION_JSON_TEMPLATES[field.schema];
254
+ }
255
+ const refusal = options.validateJsonValue?.(schema, value) ?? null;
256
+ return refusal === null ? null : problem('json_schema', refusal);
257
+ }
258
+ case 'reference': {
259
+ if (typeof value !== 'string')
260
+ return problem('type', 'Expected the id of a record, as text.');
261
+ return UUID.test(value) ? null : problem('reference_format', `${quote(value)} is not a record id. An id is a UUID.`);
262
+ }
263
+ }
264
+ }
265
+ /**
266
+ * The one spelling a value is stored and compared in. A datetime always has
267
+ * three fractional digits, so `…:00Z`, `…:00.5Z` and `…:00.500Z` are one value
268
+ * for `unique`, filters and sorting; a reference is always a lowercase UUID, so
269
+ * `3F25…` and `3f25…` are one record for `unique`, filters and joins. Every
270
+ * other value is returned unchanged, and so is anything that is not a datetime
271
+ * or an id this module understands.
272
+ */
273
+ export function normalizeCollectionValue(field, value) {
274
+ if (typeof value !== 'string')
275
+ return value;
276
+ if (field.type === 'reference')
277
+ return UUID.test(value) ? value.toLowerCase() : value;
278
+ if (field.type !== 'datetime')
279
+ return value;
280
+ const match = DATETIME.exec(value);
281
+ if (match === null)
282
+ return value;
283
+ return `${value.slice(0, 19)}.${(match[7] ?? '').padEnd(3, '0')}Z`;
284
+ }