fastify-auto-sqlapi 0.5.0 → 1.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 (212) hide show
  1. package/AGENTS.md +5 -5
  2. package/AGENTS_BACKEND.md +166 -130
  3. package/AGENTS_FRONTEND.md +60 -38
  4. package/BREAKING_CHANGES.md +9 -893
  5. package/CHANGELOG.md +258 -15
  6. package/README.md +71 -45
  7. package/dist/bin/generate-schema.js +12 -12
  8. package/dist/bin/generate-tables.js +1 -2
  9. package/dist/bin/utils.d.ts +2 -6
  10. package/dist/bin/utils.d.ts.map +1 -1
  11. package/dist/bin/utils.js +13 -33
  12. package/dist/index.d.ts +13 -33
  13. package/dist/index.d.ts.map +1 -1
  14. package/dist/index.js +6 -37
  15. package/dist/lib/adapters/mysql-adapter.d.ts +5 -2
  16. package/dist/lib/adapters/mysql-adapter.d.ts.map +1 -1
  17. package/dist/lib/adapters/pg-adapter.d.ts +5 -2
  18. package/dist/lib/adapters/pg-adapter.d.ts.map +1 -1
  19. package/dist/lib/agent/manifest.d.ts +27 -10
  20. package/dist/lib/agent/manifest.d.ts.map +1 -1
  21. package/dist/lib/agent/manifest.js +43 -26
  22. package/dist/lib/agent/tool-schemas.d.ts +5 -4
  23. package/dist/lib/agent/tool-schemas.d.ts.map +1 -1
  24. package/dist/lib/agent/tool-schemas.js +5 -5
  25. package/dist/lib/cli/config.d.ts +37 -2
  26. package/dist/lib/cli/config.d.ts.map +1 -1
  27. package/dist/lib/cli/config.js +106 -16
  28. package/dist/lib/cli/mysql-introspect.d.ts +6 -1
  29. package/dist/lib/cli/mysql-introspect.d.ts.map +1 -1
  30. package/dist/lib/cli/mysql-introspect.js +15 -15
  31. package/dist/lib/cli/pg-introspect.d.ts +0 -1
  32. package/dist/lib/cli/pg-introspect.d.ts.map +1 -1
  33. package/dist/lib/cli/pg-introspect.js +2 -13
  34. package/dist/lib/cli/tables-codegen.d.ts +0 -4
  35. package/dist/lib/cli/tables-codegen.d.ts.map +1 -1
  36. package/dist/lib/cli/tables-codegen.js +24 -87
  37. package/dist/lib/db.d.ts +42 -17
  38. package/dist/lib/db.d.ts.map +1 -1
  39. package/dist/lib/db.js +114 -40
  40. package/dist/lib/dialect.d.ts +5 -0
  41. package/dist/lib/dialect.d.ts.map +1 -1
  42. package/dist/lib/dialect.js +3 -0
  43. package/dist/lib/engine/bulk/bulk-delete.d.ts +5 -0
  44. package/dist/lib/engine/bulk/bulk-delete.d.ts.map +1 -1
  45. package/dist/lib/engine/bulk/bulk-delete.js +66 -30
  46. package/dist/lib/engine/bulk/bulk-upsert.d.ts.map +1 -1
  47. package/dist/lib/engine/bulk/bulk-upsert.js +45 -26
  48. package/dist/lib/engine/read-hooks.d.ts +3 -3
  49. package/dist/lib/engine/read-hooks.d.ts.map +1 -1
  50. package/dist/lib/engine/read-hooks.js +3 -3
  51. package/dist/lib/engine/rest/delete.d.ts.map +1 -1
  52. package/dist/lib/engine/rest/delete.js +12 -18
  53. package/dist/lib/engine/rest/get.js +8 -8
  54. package/dist/lib/engine/rest/insert.d.ts.map +1 -1
  55. package/dist/lib/engine/rest/insert.js +31 -18
  56. package/dist/lib/engine/rest/update.d.ts.map +1 -1
  57. package/dist/lib/engine/rest/update.js +34 -17
  58. package/dist/lib/engine/search/aggregations.d.ts +3 -3
  59. package/dist/lib/engine/search/aggregations.d.ts.map +1 -1
  60. package/dist/lib/engine/search/aggregations.js +20 -16
  61. package/dist/lib/engine/search/conditions.d.ts +9 -5
  62. package/dist/lib/engine/search/conditions.d.ts.map +1 -1
  63. package/dist/lib/engine/search/conditions.js +31 -20
  64. package/dist/lib/engine/search/fields.d.ts +44 -11
  65. package/dist/lib/engine/search/fields.d.ts.map +1 -1
  66. package/dist/lib/engine/search/fields.js +94 -28
  67. package/dist/lib/engine/search/join-families.d.ts +7 -7
  68. package/dist/lib/engine/search/join-families.d.ts.map +1 -1
  69. package/dist/lib/engine/search/join-families.js +84 -75
  70. package/dist/lib/engine/search/joins.d.ts +15 -7
  71. package/dist/lib/engine/search/joins.d.ts.map +1 -1
  72. package/dist/lib/engine/search/joins.js +23 -13
  73. package/dist/lib/engine/search/order-by.d.ts +11 -12
  74. package/dist/lib/engine/search/order-by.d.ts.map +1 -1
  75. package/dist/lib/engine/search/order-by.js +24 -28
  76. package/dist/lib/engine/search/search.d.ts.map +1 -1
  77. package/dist/lib/engine/search/search.js +111 -62
  78. package/dist/lib/engine/validate.d.ts +21 -3
  79. package/dist/lib/engine/validate.d.ts.map +1 -1
  80. package/dist/lib/engine/validate.js +106 -16
  81. package/dist/lib/engine/write-helpers.d.ts +69 -16
  82. package/dist/lib/engine/write-helpers.d.ts.map +1 -1
  83. package/dist/lib/engine/write-helpers.js +257 -105
  84. package/dist/lib/errors.d.ts +42 -10
  85. package/dist/lib/errors.d.ts.map +1 -1
  86. package/dist/lib/errors.js +69 -15
  87. package/dist/lib/nullable.d.ts +3 -2
  88. package/dist/lib/nullable.d.ts.map +1 -1
  89. package/dist/lib/nullable.js +14 -5
  90. package/dist/lib/read-access.d.ts +33 -21
  91. package/dist/lib/read-access.d.ts.map +1 -1
  92. package/dist/lib/read-access.js +42 -23
  93. package/dist/lib/schema/bulk-delete.d.ts +13 -7
  94. package/dist/lib/schema/bulk-delete.d.ts.map +1 -1
  95. package/dist/lib/schema/bulk-delete.js +18 -8
  96. package/dist/lib/schema/bulk-upsert.d.ts +3 -3
  97. package/dist/lib/schema/bulk-upsert.d.ts.map +1 -1
  98. package/dist/lib/schema/bulk-upsert.js +9 -14
  99. package/dist/lib/schema/get.d.ts +1 -1
  100. package/dist/lib/schema/get.d.ts.map +1 -1
  101. package/dist/lib/schema/get.js +2 -2
  102. package/dist/lib/schema/helpers.d.ts +41 -23
  103. package/dist/lib/schema/helpers.d.ts.map +1 -1
  104. package/dist/lib/schema/helpers.js +80 -33
  105. package/dist/lib/schema/insert.d.ts +1 -1
  106. package/dist/lib/schema/insert.d.ts.map +1 -1
  107. package/dist/lib/schema/insert.js +12 -20
  108. package/dist/lib/schema/search.d.ts +2 -13
  109. package/dist/lib/schema/search.d.ts.map +1 -1
  110. package/dist/lib/schema/search.js +64 -61
  111. package/dist/lib/schema/update.d.ts +1 -1
  112. package/dist/lib/schema/update.d.ts.map +1 -1
  113. package/dist/lib/schema/update.js +6 -13
  114. package/dist/lib/sql-api.d.ts +47 -25
  115. package/dist/lib/sql-api.d.ts.map +1 -1
  116. package/dist/lib/sql-api.js +70 -27
  117. package/dist/lib/table-helpers.d.ts +92 -14
  118. package/dist/lib/table-helpers.d.ts.map +1 -1
  119. package/dist/lib/table-helpers.js +367 -128
  120. package/dist/lib/tenant.d.ts +16 -22
  121. package/dist/lib/tenant.d.ts.map +1 -1
  122. package/dist/lib/tenant.js +38 -54
  123. package/dist/lib/write-access.d.ts +15 -9
  124. package/dist/lib/write-access.d.ts.map +1 -1
  125. package/dist/lib/write-access.js +12 -4
  126. package/dist/routes/auto/agent-manifest.routes.d.ts +1 -1
  127. package/dist/routes/auto/agent-manifest.routes.js +2 -2
  128. package/dist/routes/auto/bulk-delete.routes.d.ts +2 -2
  129. package/dist/routes/auto/bulk-delete.routes.d.ts.map +1 -1
  130. package/dist/routes/auto/bulk-delete.routes.js +1 -7
  131. package/dist/routes/auto/bulk-upsert.routes.d.ts +2 -2
  132. package/dist/routes/auto/bulk-upsert.routes.d.ts.map +1 -1
  133. package/dist/routes/auto/bulk-upsert.routes.js +2 -2
  134. package/dist/routes/auto/delete.routes.d.ts +2 -2
  135. package/dist/routes/auto/delete.routes.d.ts.map +1 -1
  136. package/dist/routes/auto/delete.routes.js +8 -10
  137. package/dist/routes/auto/get.routes.d.ts +2 -2
  138. package/dist/routes/auto/get.routes.d.ts.map +1 -1
  139. package/dist/routes/auto/get.routes.js +5 -5
  140. package/dist/routes/auto/insert.routes.d.ts +2 -2
  141. package/dist/routes/auto/insert.routes.d.ts.map +1 -1
  142. package/dist/routes/auto/insert.routes.js +1 -7
  143. package/dist/routes/auto/plugin.d.ts +6 -0
  144. package/dist/routes/auto/plugin.d.ts.map +1 -1
  145. package/dist/routes/auto/plugin.js +60 -36
  146. package/dist/routes/auto/route-helpers.d.ts +26 -12
  147. package/dist/routes/auto/route-helpers.d.ts.map +1 -1
  148. package/dist/routes/auto/route-helpers.js +50 -19
  149. package/dist/routes/auto/search.routes.d.ts +2 -2
  150. package/dist/routes/auto/search.routes.d.ts.map +1 -1
  151. package/dist/routes/auto/search.routes.js +36 -24
  152. package/dist/routes/auto/update.routes.d.ts +2 -2
  153. package/dist/routes/auto/update.routes.d.ts.map +1 -1
  154. package/dist/routes/auto/update.routes.js +1 -8
  155. package/dist/routes/sql-api-decorator.d.ts +30 -12
  156. package/dist/routes/sql-api-decorator.d.ts.map +1 -1
  157. package/dist/routes/sql-api-decorator.js +44 -27
  158. package/dist/types/cli.d.ts +17 -6
  159. package/dist/types/cli.d.ts.map +1 -1
  160. package/dist/types/computed.d.ts +1 -1
  161. package/dist/types/computed.d.ts.map +1 -1
  162. package/dist/types/conditions.d.ts +3 -1
  163. package/dist/types/conditions.d.ts.map +1 -1
  164. package/dist/types/db.d.ts +44 -4
  165. package/dist/types/db.d.ts.map +1 -1
  166. package/dist/types/dml.d.ts +26 -17
  167. package/dist/types/dml.d.ts.map +1 -1
  168. package/dist/types/hooks.d.ts +62 -0
  169. package/dist/types/hooks.d.ts.map +1 -0
  170. package/dist/types/hooks.js +1 -0
  171. package/dist/types/join.d.ts +25 -8
  172. package/dist/types/join.d.ts.map +1 -1
  173. package/dist/types/plugin.d.ts +58 -19
  174. package/dist/types/plugin.d.ts.map +1 -1
  175. package/dist/types/plugin.js +2 -0
  176. package/dist/types/request.d.ts +2 -2
  177. package/dist/types/schema.d.ts +3 -3
  178. package/dist/types/schema.d.ts.map +1 -1
  179. package/dist/types/search.d.ts +28 -13
  180. package/dist/types/search.d.ts.map +1 -1
  181. package/dist/types/search.js +2 -1
  182. package/dist/types/table.d.ts +109 -94
  183. package/dist/types/table.d.ts.map +1 -1
  184. package/dist/types/table.js +7 -2
  185. package/dist/types/tenant.d.ts +28 -2
  186. package/dist/types/tenant.d.ts.map +1 -1
  187. package/dist/types/tenant.js +7 -1
  188. package/dist/types/validation.d.ts +69 -13
  189. package/dist/types/validation.d.ts.map +1 -1
  190. package/dist/types.d.ts +1 -0
  191. package/dist/types.d.ts.map +1 -1
  192. package/dist/types.js +1 -0
  193. package/docs/GLOSSARY.md +11 -5
  194. package/docs/adr/0003-bulk-not-transactional.md +2 -1
  195. package/docs/adr/0006-raw-db-errors.md +2 -1
  196. package/docs/adr/0013-sanitized-db-errors.md +2 -1
  197. package/docs/adr/0014-what-follows-a-write-join.md +1 -1
  198. package/docs/adr/0022-stay-on-0x-while-every-consumer-is-first-party.md +88 -0
  199. package/docs/adr/0023-a-write-runs-in-a-transaction-or-not-at-all.md +60 -0
  200. package/docs/adr/0024-the-consumer-maps-driver-codes-through-dberrors.md +78 -0
  201. package/docs/adr/0025-validatebulk-replaces-validate-in-a-bulk-upsert.md +46 -0
  202. package/docs/adr/0026-update-carries-its-primary-key-in-main.md +43 -0
  203. package/docs/adr/0027-the-1-0-contract.md +74 -0
  204. package/docs/adr/0028-select-star-is-the-default-projection.md +64 -0
  205. package/docs/adr/0029-a-write-names-its-child-rows-by-action.md +96 -0
  206. package/docs/adr/0030-a-child-row-is-validated-by-its-own-table.md +117 -0
  207. package/docs/adr/0031-an-insert-excluded-upsert-key-addresses-an-existing-row.md +58 -0
  208. package/docs/adr/0032-tenant-scope-names-schema-fields.md +56 -0
  209. package/docs/adr/README.md +12 -1
  210. package/docs/upgrading/0.x.md +906 -0
  211. package/docs/upgrading/1.0.md +628 -0
  212. package/package.json +4 -5
@@ -1,8 +1,12 @@
1
1
  import { camelcaseObject, snakecaseRecord } from '../naming.js';
2
- import { runValidation } from './validate.js';
3
- import { removeWriteExcluded } from '../write-access.js';
2
+ import { buildKeyMatch } from '../db.js';
3
+ import { ConditionBuilder } from 'node-condition-builder';
4
+ import { runValidation, runChildValidation, throwValidationError } from './validate.js';
5
+ import { removeWriteExcluded, insertExcludedFields } from '../write-access.js';
6
+ import { resolveJoinTableConf } from '../table-helpers.js';
4
7
  import { httpError } from '../errors.js';
5
8
  import { tenantForTable, buildTenantRowGuard, enforceTenantOnWrites, assertTenantOwnsConflicts, tenantImmutableColumns, } from '../tenant.js';
9
+ import { rejectRetiredKey } from './search/fields.js';
6
10
  /**
7
11
  * Every upserted record must carry its key (ADR 0021), checked on the record as it reaches the
8
12
  * database — after hooks, tenant injection and the FK auto-fill of secondaries:
@@ -24,50 +28,135 @@ export function assertUpsertKeys(schema, conflictCols, pkCols, records) {
24
28
  if (isPrimaryKey && conflictCols.every((c) => record[c] === undefined))
25
29
  return;
26
30
  const missing = conflictCols.filter((c) => record[c] == null);
31
+ // Not attributable to one request path here: the rows may be a bulk's mains or one
32
+ // write's secondaries, and the message carries the index either way.
27
33
  if (missing.length) {
28
34
  throw httpError(400, `${rule}: the row at index ${i} has no value for ${missing.map(fieldOf).join(', ')} — ` +
29
- `an upserted row must carry its whole key`);
35
+ `an upserted row must carry its whole key`, { code: 'missing_key' });
30
36
  }
31
37
  const key = JSON.stringify(conflictCols.map((c) => record[c]));
32
38
  const first = seen.get(key);
33
39
  if (first !== undefined) {
34
- throw httpError(400, `${rule}: the rows at index ${first} and ${i} have the same key`);
40
+ throw httpError(400, `${rule}: the rows at index ${first} and ${i} have the same key`, { code: 'duplicate_key' });
35
41
  }
36
42
  seen.set(key, i);
37
43
  });
38
44
  }
45
+ /**
46
+ * The fields of an upsert key the client may not set on insert (`insertExclude`). Such a key
47
+ * is kept on the rows that carry it — it names the row to update — but it may not name a new
48
+ * row: the client never picks a value `insertExclude` reserves to the server.
49
+ */
50
+ export function insertExcludedKeyFields(tableConf, upsertKey) {
51
+ const excluded = insertExcludedFields(tableConf);
52
+ return upsertKey.filter((f) => excluded.includes(f));
53
+ }
54
+ /**
55
+ * Every row carrying an upsert key that `insertExclude` reserves to the server must name an
56
+ * existing row: such a key addresses a row, it cannot create one (see
57
+ * `insertExcludedKeyFields`). One SELECT for the rows whose key the client sent (`sent`, the
58
+ * rows as the request carried them, camelCase); each one no row matches is a 400 `not_found`
59
+ * at `pathOf(i)`, before the upsert runs. Rows without the key are plain inserts and are not
60
+ * probed, nor is a key a `beforeInsert` assigned. `records` and `conflictCols` are DB column
61
+ * names.
62
+ */
63
+ export async function assertExcludedKeysExist(db, schema, conflictCols, excludedKeyFields, records, sent, pathOf) {
64
+ if (!excludedKeyFields.length)
65
+ return;
66
+ // Only the rows whose key the CLIENT sent: a key a `beforeInsert` assigned names a new row.
67
+ const carrying = records
68
+ .map((record, i) => ({ i, key: conflictCols.map((c) => record[c]) }))
69
+ .filter(({ i, key }) => excludedKeyFields.every((f) => sent[i]?.[f] != null) && key.every((v) => v != null));
70
+ if (!carrying.length)
71
+ return;
72
+ const match = buildKeyMatch(db, conflictCols.map((c) => db.qi(c)), carrying.map(({ key }) => key));
73
+ const found = await db.select({
74
+ tableName: schema.tableName,
75
+ columns: conflictCols.map((c) => db.qi(c)).join(', '),
76
+ where: match.build(1, db.ph),
77
+ values: match.getValues(),
78
+ });
79
+ // Compared as strings: the driver may hand a bigint or numeric key back as a string.
80
+ const tupleOf = (key) => JSON.stringify(key.map((v) => String(v)));
81
+ const existing = new Set(found.map((row) => tupleOf(conflictCols.map((c) => row[c]))));
82
+ const field = excludedKeyFields[0];
83
+ const missing = carrying.filter(({ key }) => !existing.has(tupleOf(key)));
84
+ if (missing.length) {
85
+ throwValidationError(missing.map(({ i, key }) => ({
86
+ path: pathOf(i, field),
87
+ code: 'not_found',
88
+ message: `No "${schema.tableName}" row has the key (${key.join(', ')}): ` +
89
+ `${field} is set by the server on insert, so it can only name an existing row`,
90
+ })));
91
+ }
92
+ }
39
93
  /**
40
94
  * Resolve the write join an alias names, or undefined when the table does not declare it.
41
- *
42
- * An undeclared alias is skipped rather than rejected: a table with no `allowedWriteJoins`
43
- * ignores any secondaries sent to it, which is the tested contract (see the "ignores
44
- * secondaries/deletions not in allowedWriteJoins" specs). The HTTP boundary is what fails
45
- * closed — the generated body schema declares `additionalProperties:false` on the alias
46
- * container, so a request naming an undeclared alias is a 400 before it reaches here.
95
+ * An undeclared alias never gets this far: `assertWriteJoinAliases` refuses it first.
47
96
  */
48
97
  function findWriteJoin(tableConf, alias) {
49
- return tableConf.allowedWriteJoins?.find((j) => j.alias === alias);
98
+ return tableConf.writeJoins?.find((j) => j.alias === alias);
99
+ }
100
+ /** True when any of `sections` names at least one alias — an empty list included. */
101
+ export function hasAliases(...sections) {
102
+ return sections.some((s) => s !== undefined && Object.keys(s).length > 0);
103
+ }
104
+ /** The sections of a write request, in the order their aliases are checked. */
105
+ const SECTIONS = ['upsert', 'delete', 'replace'];
106
+ /**
107
+ * Refuse the pre-1.0 child-row keys of a write request: `secondaries` became `upsert` and
108
+ * `deletions` became `delete` (ADR 0029). A 400 `retired_key` at `<at>.<key>`, never ignored:
109
+ * dropped, the child rows would go unwritten or undeleted with the write answering success.
110
+ * `at` is the bulk item's index, empty for a single write.
111
+ */
112
+ export function rejectRetiredWriteKeys(input, at = '') {
113
+ const path = (key) => [at, key].filter(Boolean).join('.');
114
+ rejectRetiredKey(input, 'secondaries', path('secondaries'), `child rows to write go under 'upsert', a complete set under 'replace'`);
115
+ rejectRetiredKey(input, 'deletions', path('deletions'), `child rows to delete go under 'delete'`);
50
116
  }
51
117
  /**
52
- * Drop `excludeFromCreation` fields from a camelCase record, in place.
118
+ * Check the aliases of a write request's `upsert`, `delete` and `replace` sections, before
119
+ * anything is validated or written; a 400 at `<at>.<section>.<alias>`:
120
+ * - `unknown_field` for an alias the table does not declare in `writeJoins`. Dropped in
121
+ * silence, a typo'd alias would answer success with the child rows unwritten, or the rows to
122
+ * delete still there;
123
+ * - `unknown_field` for a `replace` alias whose relation has no `upsertKey`: the key is what
124
+ * tells a child row the request sends from one to delete;
125
+ * - `conflicting_alias` for an alias in `replace` and in `upsert` or `delete` too: the set
126
+ * `replace` names already says what stays and what goes.
127
+ * `at` is the bulk item's index, empty for a single write.
128
+ */
129
+ export function assertWriteJoinAliases(tableConf, sections, at = '') {
130
+ for (const section of SECTIONS) {
131
+ for (const alias of Object.keys(sections[section] ?? {})) {
132
+ const join = findWriteJoin(tableConf, alias);
133
+ const path = [at, section, alias].filter(Boolean).join('.');
134
+ if (!join) {
135
+ throw httpError(400, `Unknown write join alias: ${alias}`, { code: 'unknown_field', path });
136
+ }
137
+ if (section === 'replace' && !join.upsertKey) {
138
+ throw httpError(400, `'${alias}' cannot be replaced: its relation declares no upsertKey to tell the rows apart`, { code: 'unknown_field', path });
139
+ }
140
+ if (section === 'replace' && (Object.hasOwn(sections.upsert ?? {}, alias) || Object.hasOwn(sections.delete ?? {}, alias))) {
141
+ throw httpError(400, `'${alias}' is under replace and under upsert or delete: replace already names the complete set`, { code: 'conflicting_alias', path });
142
+ }
143
+ }
144
+ }
145
+ }
146
+ /**
147
+ * Drop `insertExclude` fields from a camelCase record, in place.
53
148
  *
54
149
  * Exclusion is a whitelist on CLIENT input: call this on the client payload only, BEFORE any
55
150
  * server-side value is assigned (beforeInsert mutations, FK auto-fill), so engine- and
56
- * hook-generated values on those fields reach the SQL (ADR 0005).
151
+ * hook-generated values on those fields reach the SQL (ADR 0005). The fields of the row's
152
+ * `upsertKey` stay: there they name the row to update, and `assertExcludedKeysExist` refuses
153
+ * one that would name a new row.
57
154
  */
58
- function removeExcludedFieldsCamel(record, tableConf) {
59
- if (!tableConf.excludeFromCreation?.length)
60
- return;
61
- for (const field of tableConf.excludeFromCreation) {
62
- delete record[field];
63
- }
64
- }
65
- export function findSecondaryTableConf(dbTables, joinTableName) {
66
- for (const [, conf] of Object.entries(dbTables)) {
67
- if (conf.Schema.tableName === joinTableName)
68
- return conf;
155
+ function removeInsertExcluded(record, tableConf, upsertKey = []) {
156
+ for (const field of insertExcludedFields(tableConf)) {
157
+ if (!upsertKey.includes(field))
158
+ delete record[field];
69
159
  }
70
- return undefined;
71
160
  }
72
161
  /**
73
162
  * Resolve one write-join alias: where the child's FK lives, what value it takes, and which
@@ -75,7 +164,7 @@ export function findSecondaryTableConf(dbTables, joinTableName) {
75
164
  */
76
165
  function resolveWriteJoinTarget(joinDef, dbTables, mainRecord, tenant) {
77
166
  const { joinSchema, joinField, mainField } = joinDef;
78
- const childConf = findSecondaryTableConf(dbTables, joinSchema.tableName);
167
+ const childConf = resolveJoinTableConf(dbTables, joinDef);
79
168
  return {
80
169
  joinSchema,
81
170
  joinCol: joinSchema.col(joinField),
@@ -87,9 +176,11 @@ function resolveWriteJoinTarget(joinDef, dbTables, mainRecord, tenant) {
87
176
  /**
88
177
  * Prepare a single record for INSERT/UPSERT:
89
178
  * 1. shallow camelCase copy of `input`
90
- * 2. runValidation (camelCase — sees the client payload as sent)
91
- * 3. drop excludeFromCreation fields (client-input whitelist; applied BEFORE the
92
- * hook so values it assigns — e.g. a server-generated id — reach the INSERT)
179
+ * 2. runValidation (camelCase — sees the client payload as sent), then the child tables'
180
+ * own `validate` on the child rows (ADR 0030) — both before the hook and any SQL
181
+ * 3. drop insertExclude fields (client-input whitelist; applied BEFORE the
182
+ * hook so values it assigns — e.g. a server-generated id — reach the INSERT), except
183
+ * those of the table's upsertKey, which name the row to update
93
184
  * 4. beforeInsert hook (caller can mutate the camelCase copy)
94
185
  * 5. drop non-writable fields (generated columns, writeExclude) — AFTER the hook, because
95
186
  * the database refuses those values whoever assigned them
@@ -98,97 +189,153 @@ function resolveWriteJoinTarget(joinDef, dbTables, mainRecord, tenant) {
98
189
  * Returns both `camel` (input + hook mutations, used for FK auto-fill / afterInsert) and
99
190
  * `snake` (DB-ready record). The original `input` is left intact.
100
191
  *
101
- * Pass `secondaries` so the validate hook receives them; pass undefined to skip
102
- * secondaries-aware validation (e.g. when a bulk-level validator already ran).
192
+ * Pass the request's `upsert`/`replace` sections so the validate hooks receive them; set
193
+ * `skipValidate` when a bulk-level validator already ran for the host (the child tables still
194
+ * validate their rows), and `at` to the bulk item's index for the error paths.
103
195
  */
104
- export async function prepareInsertRecord(ctx, input, secondaries, options) {
196
+ export async function prepareInsertRecord(ctx, input, children = {}, options) {
105
197
  const camel = { ...input };
106
198
  if (!options?.skipValidate) {
107
- await runValidation(ctx.db, ctx.request, ctx.tableConf, camel, secondaries);
199
+ await runValidation(ctx.db, ctx.request, ctx.tableConf, camel, children);
108
200
  }
109
- removeExcludedFieldsCamel(camel, ctx.tableConf);
201
+ await runChildValidation(ctx, input, children, options?.at);
202
+ removeInsertExcluded(camel, ctx.tableConf, ctx.tableConf.upsertKey);
110
203
  if (ctx.tableConf.beforeInsert) {
111
- await ctx.tableConf.beforeInsert(ctx.db, ctx.request, camel);
204
+ await ctx.tableConf.beforeInsert({ db: ctx.db, req: ctx.request, record: camel });
112
205
  }
113
- removeWriteExcluded(camel, ctx.tableConf, ctx.tableConf.Schema);
114
- const snake = snakecaseRecord(camel, ctx.tableConf.Schema);
206
+ removeWriteExcluded(camel, ctx.tableConf, ctx.tableConf.schema);
207
+ const snake = snakecaseRecord(camel, ctx.tableConf.schema);
115
208
  return { camel, snake };
116
209
  }
117
210
  /**
118
- * Run `writeAlias` once per alias of a write-join payload, handing it the resolved target for
119
- * that alias and collecting the rows it reports back.
211
+ * Write the child rows of a request's `upsert` and `replace` sections, one bulk statement per
212
+ * alias; for a `replace` alias, then delete every other child row of the main row (ADR 0029).
213
+ *
214
+ * A secondary is a write like any other: the child table's own `tenantScope` is enforced on it
215
+ * (`tenantForTable` re-targets the caller's tenant onto that table's scope). Without this the
216
+ * client picks the child's tenant value, which lets it plant rows inside another tenant — and,
217
+ * where the child is upserted, hijack one of that tenant's existing rows via the conflict key.
120
218
  *
121
- * Empty lists are a no-op, and an alias the table does not declare as a write join is skipped:
122
- * rejecting it is the request schema's job (`additionalProperties:false` on the alias
123
- * container), because a table declaring no write joins must keep ignoring what it is sent.
219
+ * An empty list writes nothing; under `replace` it still removes every child row. An alias the
220
+ * table does not declare is skipped: `assertWriteJoinAliases` refuses it first.
124
221
  */
125
- async function forEachWriteJoin(pass, payload, writeAlias) {
126
- const results = {};
127
- for (const [alias, records] of Object.entries(payload)) {
128
- if (!records?.length)
129
- continue;
222
+ export async function processSecondaries(pass, sections) {
223
+ const outcome = { written: {}, removed: {} };
224
+ const aliases = [
225
+ ...Object.entries(sections.upsert ?? {}).map(([a, r]) => [a, r, false]),
226
+ ...Object.entries(sections.replace ?? {}).map(([a, r]) => [a, r, true]),
227
+ ];
228
+ for (const [alias, records, replace] of aliases) {
130
229
  const joinDef = findWriteJoin(pass.tableConf, alias);
131
- if (!joinDef)
230
+ if (!joinDef || (!records?.length && !replace))
132
231
  continue;
133
232
  const target = resolveWriteJoinTarget(joinDef, pass.dbTables, pass.mainRecord, pass.tenant);
134
- results[alias] = await writeAlias(records, target, joinDef);
233
+ const section = replace ? 'replace' : 'upsert';
234
+ const sent = records?.length ? await writeSecondaryRows(pass, records, target, joinDef, section) : [];
235
+ if (records?.length)
236
+ outcome.written[alias] = sent.map((r) => camelcaseObject(r.pk, target.joinSchema));
237
+ if (replace) {
238
+ const removed = await removeUnsentChildren(pass.db, target, joinDef, sent.map((r) => r.record));
239
+ if (removed.length)
240
+ outcome.removed[alias] = removed;
241
+ }
135
242
  }
136
- return results;
243
+ return outcome;
244
+ }
245
+ /** The child table's primary key fields: its config's, else the Schema's, else the join field. */
246
+ function childPrimaryKey(target, joinDef) {
247
+ return target.childConf?.primary ?? target.joinSchema.primaryKey ?? joinDef.joinField;
137
248
  }
138
249
  /**
139
- * Write the child rows a request sent alongside the main record, one bulk statement per alias.
140
- *
141
- * A secondary is a write like any other: the child table's own `tenantScope` is enforced on it
142
- * (`tenantForTable` re-targets the caller's tenant onto that table's scope). Without this the
143
- * client picks the child's tenant value, which lets it plant rows inside another tenant — and,
144
- * where the child is upserted, hijack one of that tenant's existing rows via the conflict key.
250
+ * Insert, or upsert on the relation's `upsertKey`, one alias' rows: each row's PK (DB columns)
251
+ * and the record as written, FK and tenant included — the key a `replace` keeps.
145
252
  */
146
- export function processSecondaries(pass, secondaries) {
147
- const { db, tableConf, request } = pass;
148
- return forEachWriteJoin(pass, secondaries, async (records, target, joinDef) => {
149
- const { joinSchema, joinCol, mainValue, childConf, childTenant } = target;
150
- const childPk = childConf?.primary || joinDef.joinField;
151
- const childPkCol = Array.isArray(childPk)
152
- ? childPk.map((f) => joinSchema.col(f))
153
- : joinSchema.col(childPk);
154
- // Same order as `prepareInsertRecord` (ADR 0005): the client whitelist runs first, then
155
- // the child's own `beforeInsert`, then the DB format — so a value the hook assigns to an
156
- // excluded field still reaches the INSERT. A secondary is a write like any other, and its
157
- // table's transform has to run here too or a column that table encodes on the way in is
158
- // stored raw whenever its rows arrive as another table's children.
159
- const preparedRecords = [];
160
- for (const rec of records) {
161
- const camel = { ...rec };
162
- if (childConf) {
163
- removeExcludedFieldsCamel(camel, childConf);
164
- if (childConf.beforeInsert) {
165
- await childConf.beforeInsert(db, request, camel);
166
- }
253
+ async function writeSecondaryRows(pass, records, target, joinDef, section) {
254
+ const { db, request } = pass;
255
+ const { joinSchema, joinCol, mainValue, childConf, childTenant } = target;
256
+ const childPk = childPrimaryKey(target, joinDef);
257
+ const childPkCol = Array.isArray(childPk)
258
+ ? childPk.map((f) => joinSchema.col(f))
259
+ : joinSchema.col(childPk);
260
+ // Same order as `prepareInsertRecord` (ADR 0005): the client whitelist runs first, then
261
+ // the FK to the main row, then the child's own `beforeInsert`, then the DB format — so a
262
+ // value the hook assigns to an excluded field still reaches the INSERT. A secondary is a write like any other, and its
263
+ // table's transform has to run here too or a column that table encodes on the way in is
264
+ // stored raw whenever its rows arrive as another table's children.
265
+ const preparedRecords = [];
266
+ for (const rec of records) {
267
+ const camel = { ...rec };
268
+ if (childConf) {
269
+ removeInsertExcluded(camel, childConf, joinDef.upsertKey);
270
+ // The hook sees the row as it will be written: the FK to the main row already filled in,
271
+ // over whatever the client sent. It is filled again below, so the hook cannot move it.
272
+ camel[joinDef.joinField] = mainValue;
273
+ if (childConf.beforeInsert) {
274
+ await childConf.beforeInsert({ db, req: request, record: camel });
167
275
  }
168
- removeWriteExcluded(camel, childConf, joinSchema);
169
- const prepared = snakecaseRecord(camel, joinSchema);
170
- // FK auto-fill last: the engine's own value, not the client's and not the hook's.
171
- prepared[joinCol] = mainValue;
172
- preparedRecords.push(prepared);
173
276
  }
174
- // Tenant enforcement runs after the FK auto-fill: for an indirect scope the through-FK
175
- // the engine just injected is the value being validated.
176
- await enforceTenantOnWrites(db, childTenant, preparedRecords);
177
- const upsertKeys = tableConf.upsertMap?.get(joinSchema);
178
- let pkRows;
179
- if (upsertKeys) {
180
- const conflictCols = upsertKeys.map((k) => joinSchema.col(k));
181
- assertUpsertKeys(joinSchema, conflictCols, (joinSchema.primaryKey ?? [childPk].flat()).map((f) => joinSchema.col(f)), preparedRecords);
182
- // A conflicting upsert must not overwrite — or re-parent — a child row owned by
183
- // another tenant, which the ON CONFLICT key alone would happily match.
184
- await assertTenantOwnsConflicts(db, childTenant, joinSchema.tableName, conflictCols, preparedRecords);
185
- pkRows = await db.bulkInsertOrUpdate(joinSchema.tableName, preparedRecords, conflictCols, childPkCol, undefined, tenantImmutableColumns(childTenant));
186
- }
187
- else {
188
- pkRows = await db.bulkInsert(joinSchema.tableName, preparedRecords, childPkCol);
189
- }
190
- return pkRows.map((r) => camelcaseObject(r, joinSchema));
191
- });
277
+ removeWriteExcluded(camel, childConf, joinSchema);
278
+ const prepared = snakecaseRecord(camel, joinSchema);
279
+ // FK auto-fill last: the engine's own value, not the client's and not the hook's.
280
+ prepared[joinCol] = mainValue;
281
+ preparedRecords.push(prepared);
282
+ }
283
+ // Tenant enforcement runs after the FK auto-fill: for an indirect scope the through-FK
284
+ // the engine just injected is the value being validated.
285
+ await enforceTenantOnWrites(db, childTenant, preparedRecords);
286
+ const upsertKeys = joinDef.upsertKey;
287
+ let pkRows;
288
+ if (upsertKeys) {
289
+ const conflictCols = upsertKeys.map((k) => joinSchema.col(k));
290
+ assertUpsertKeys(joinSchema, conflictCols, (joinSchema.primaryKey ?? [childPk].flat()).map((f) => joinSchema.col(f)), preparedRecords);
291
+ const prefix = [pass.at, section, joinDef.alias].filter(Boolean).join('.');
292
+ await assertExcludedKeysExist(db, joinSchema, conflictCols, insertExcludedKeyFields(childConf, upsertKeys), preparedRecords, records, (i, field) => `${prefix}.${i}.${field}`);
293
+ // A conflicting upsert must not overwrite — or re-parent — a child row owned by
294
+ // another tenant, which the ON CONFLICT key alone would happily match.
295
+ await assertTenantOwnsConflicts(db, childTenant, joinSchema.tableName, conflictCols, preparedRecords);
296
+ pkRows = (await db.bulkUpsert(joinSchema.tableName, preparedRecords, conflictCols, childPkCol, { immutableCols: tenantImmutableColumns(childTenant) })).map((r) => r.pk);
297
+ }
298
+ else {
299
+ pkRows = await db.bulkInsert(joinSchema.tableName, preparedRecords, childPkCol);
300
+ }
301
+ return pkRows.map((pk, i) => ({ pk, record: preparedRecords[i] }));
302
+ }
303
+ /**
304
+ * Delete the child rows of the main row that a `replace` section left out: every
305
+ * row with the main row's FK whose `upsertKey` matches none of the rows just written. The
306
+ * child table's tenant guard joins the statement, so a row of another tenant pointing at this
307
+ * main row is never touched. A row with a NULL key matches nothing sent and is removed too
308
+ * (`NOT COALESCE(…, FALSE)`). Returns the removed rows' keys — primary key and `upsertKey`
309
+ * fields — as `deletions` reports them.
310
+ */
311
+ async function removeUnsentChildren(db, target, joinDef, kept) {
312
+ const { joinSchema, joinCol, mainValue, childTenant } = target;
313
+ const table = db.qi(joinSchema.tableName);
314
+ const keyCols = (joinDef.upsertKey ?? []).map((f) => joinSchema.col(f));
315
+ const pkCols = [childPrimaryKey(target, joinDef)].flat().map((f) => joinSchema.col(f));
316
+ const reported = [...new Set([...pkCols, ...keyCols])].map((c) => db.qi(c)).join(', ');
317
+ const cb = new ConditionBuilder('AND', db.cbDialect);
318
+ cb.isEqual(db.qi(joinCol), mainValue);
319
+ if (kept.length) {
320
+ const match = buildKeyMatch(db, keyCols.map((c) => db.qi(c)), kept.map((r) => keyCols.map((c) => r[c]))).toExpression();
321
+ cb.raw(`NOT COALESCE(${match.value}, FALSE)`, [...match.values]);
322
+ }
323
+ const guard = buildTenantRowGuard(db, childTenant, joinSchema.tableName);
324
+ if (guard)
325
+ cb.append(guard);
326
+ const where = cb.build(1, db.ph);
327
+ const values = cb.getValues();
328
+ let rows;
329
+ if (db.supportsReturning) {
330
+ rows = (await db.query(`DELETE FROM ${table} WHERE ${where}${db.returningPk(reported)}`, values)).rows;
331
+ }
332
+ else {
333
+ // No RETURNING (mysql): read the rows through the same WHERE, then delete them.
334
+ rows = (await db.query(`SELECT ${reported} FROM ${table} WHERE ${where}`, values)).rows;
335
+ if (rows.length)
336
+ await db.query(`DELETE FROM ${table} WHERE ${where}`, values);
337
+ }
338
+ return rows.map((r) => camelcaseObject(r, joinSchema));
192
339
  }
193
340
  /**
194
341
  * Process per-alias deletion requests for a write join.
@@ -203,10 +350,14 @@ export function processSecondaries(pass, secondaries) {
203
350
  * The FK alone is not isolation: a child row owned by another tenant may still point at a main
204
351
  * row the caller owns, so the child table's own `tenantScope` is added to the DELETE.
205
352
  */
206
- export function processDeletions(pass, deletions) {
353
+ export async function processDeletions(pass, deletions) {
207
354
  const { db } = pass;
208
- return forEachWriteJoin(pass, deletions, async (records, target) => {
209
- const { joinSchema, joinCol, mainValue, childTenant } = target;
355
+ const results = {};
356
+ for (const [alias, records] of Object.entries(deletions)) {
357
+ const joinDef = findWriteJoin(pass.tableConf, alias);
358
+ if (!joinDef || !records?.length)
359
+ continue;
360
+ const { joinSchema, joinCol, mainValue, childTenant } = resolveWriteJoinTarget(joinDef, pass.dbTables, pass.mainRecord, pass.tenant);
210
361
  const tenantGuard = buildTenantRowGuard(db, childTenant, joinSchema.tableName);
211
362
  const deletedRows = [];
212
363
  for (const rec of records) {
@@ -218,6 +369,7 @@ export function processDeletions(pass, deletions) {
218
369
  deletedRows.push(camelcaseObject(snaked, joinSchema));
219
370
  }
220
371
  }
221
- return deletedRows;
222
- });
372
+ results[alias] = deletedRows;
373
+ }
374
+ return results;
223
375
  }
@@ -1,29 +1,55 @@
1
+ import type { DbErrorMapping } from '../types.js';
2
+ /** What a 400 the engine raises says about the input it rejects, see `ValidationField`. */
3
+ export interface HttpErrorField {
4
+ /** Stable machine-readable code (`unknown_field`, `invalid_params`, …). */
5
+ code: string;
6
+ /** Dot path of the offending value in the request; omitted or '' when not attributable. */
7
+ path?: string;
8
+ }
1
9
  /**
2
- * Build a plain Error decorated with `statusCode` (and optionally `validationErrors`),
3
- * which Fastify reads to emit the corresponding HTTP response.
10
+ * Build a plain Error decorated with `statusCode`, which the plugin's error handler reads to
11
+ * emit the corresponding HTTP response.
12
+ *
13
+ * A 400 should also say what was wrong with the input: `field` is rendered as the single
14
+ * entry of the response's `fields` array, so an engine rejection reaches the client in the
15
+ * same shape as a schema or `validate` error. Another status takes a `field` only where the
16
+ * client must read a code, e.g. a 409 a hook raises. `message` is copied into the field: a
17
+ * caller with nothing to say beyond the code sets `validationErrors` itself (`dbErrors`).
4
18
  *
5
19
  * Using a function instead of a custom class keeps the throw sites lightweight
6
20
  * and matches the existing convention across the codebase.
7
21
  */
8
- export declare function httpError(statusCode: number, message: string): Error & {
22
+ export declare function httpError(statusCode: number, message: string, field?: HttpErrorField): Error & {
9
23
  statusCode: number;
10
24
  };
25
+ /** Whether `err` is the safe replacement `sanitizeRouteError` built for another error. */
26
+ export declare function isSanitized(err: unknown): boolean;
27
+ /** How a route answers an error it did not raise itself: the plugin options that decide it. */
28
+ export interface RouteErrorPolicy {
29
+ /** The request's id, rendered as `requestId` so the client can name the log line. */
30
+ requestId?: string;
31
+ /** Attach the driver error as an additive `debugInfo` payload (ADR 0013). */
32
+ exposeDebugInfo?: boolean;
33
+ /** Driver error codes the consumer answers with a status instead of `500`. */
34
+ dbErrors?: Record<string, DbErrorMapping>;
35
+ }
11
36
  /**
12
37
  * Replace an error escaping a route handler with one that carries no database detail.
13
38
  *
14
39
  * Driver messages name tables, columns and constraints, and the route error handler sends
15
40
  * `error.message` verbatim — so a unique violation describes the schema to whoever
16
41
  * triggered it. Errors the plugin raises itself are deliberate `4xx` with messages written
17
- * for clients (`httpError`, `validationErrors`) and pass through untouched; everything
18
- * else becomes a bare `500`.
42
+ * for clients (`httpError`, `validationErrors`) and pass through untouched; a driver error
43
+ * whose `code` the consumer listed in `dbErrors` gets that status and the consumer's code, as
44
+ * the single entry of `fields`; everything else becomes a bare `500`. The plugin maps no code of
45
+ * its own: which ones deserve a status depends on the database, its version and the product
46
+ * (ADR 0006).
19
47
  *
20
- * The original is attached as `cause`, so a consumer `setErrorHandler` can still apply its
21
- * own policy — mapping SQLSTATE to a status code stays the consumer's decision (ADR 0006).
22
- * No status code is remapped here: a `500` stays a `500`.
48
+ * The original is attached as `cause`, and logged by the route under the same `reqId`.
23
49
  *
24
50
  * `requestId` is carried on the sanitized error and rendered in the response body: it is the
25
51
  * same value Fastify logs as `reqId` on every line, so the log entry holding the real error
26
- * is one grep away from the client's `500`.
52
+ * is one grep away from the client's response.
27
53
  *
28
54
  * With `exposeDebugInfo`, the original is also described in a `debugInfo` payload rendered
29
55
  * beside those fields — additive, so the response a client codes against is the same one it
@@ -31,5 +57,11 @@ export declare function httpError(statusCode: number, message: string): Error &
31
57
  * consumer, who may wire it to an environment variable, and no option may open an external
32
58
  * channel as a side effect of meaning something internal. See ADR 0013.
33
59
  */
34
- export declare function sanitizeRouteError(err: unknown, requestId?: string, exposeDebugInfo?: boolean): unknown;
60
+ export declare function sanitizeRouteError(err: unknown, policy?: RouteErrorPolicy): unknown;
61
+ /**
62
+ * Refuse a `dbErrors` option a route could not honour, at registration rather than on the
63
+ * first failing request: every entry is `{ status, code }`, the status an integer in 400–599,
64
+ * the code a non-empty string.
65
+ */
66
+ export declare function assertDbErrors(dbErrors: unknown): void;
35
67
  //# sourceMappingURL=errors.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"errors.d.ts","sourceRoot":"","sources":["../../src/lib/errors.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AACH,wBAAgB,SAAS,CAAC,UAAU,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,GAAG,KAAK,GAAG;IAAE,UAAU,EAAE,MAAM,CAAA;CAAE,CAI7F;AAED;;;;;;;;;;;;;;;;;;;;;;GAsBG;AACH,wBAAgB,kBAAkB,CAChC,GAAG,EAAE,OAAO,EACZ,SAAS,CAAC,EAAE,MAAM,EAClB,eAAe,UAAQ,GACtB,OAAO,CAcT"}
1
+ {"version":3,"file":"errors.d.ts","sourceRoot":"","sources":["../../src/lib/errors.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAmB,cAAc,EAAE,MAAM,aAAa,CAAC;AAEnE,2FAA2F;AAC3F,MAAM,WAAW,cAAc;IAC7B,2EAA2E;IAC3E,IAAI,EAAE,MAAM,CAAC;IACb,2FAA2F;IAC3F,IAAI,CAAC,EAAE,MAAM,CAAC;CACf;AAED;;;;;;;;;;;;GAYG;AACH,wBAAgB,SAAS,CACvB,UAAU,EAAE,MAAM,EAClB,OAAO,EAAE,MAAM,EACf,KAAK,CAAC,EAAE,cAAc,GACrB,KAAK,GAAG;IAAE,UAAU,EAAE,MAAM,CAAA;CAAE,CAKhC;AAKD,0FAA0F;AAC1F,wBAAgB,WAAW,CAAC,GAAG,EAAE,OAAO,GAAG,OAAO,CAEjD;AAED,+FAA+F;AAC/F,MAAM,WAAW,gBAAgB;IAC/B,qFAAqF;IACrF,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,6EAA6E;IAC7E,eAAe,CAAC,EAAE,OAAO,CAAC;IAC1B,8EAA8E;IAC9E,QAAQ,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,cAAc,CAAC,CAAC;CAC3C;AAED;;;;;;;;;;;;;;;;;;;;;;;GAuBG;AACH,wBAAgB,kBAAkB,CAAC,GAAG,EAAE,OAAO,EAAE,MAAM,GAAE,gBAAqB,GAAG,OAAO,CAqBvF;AAYD;;;;GAIG;AACH,wBAAgB,cAAc,CAAC,QAAQ,EAAE,OAAO,GAAG,IAAI,CAiBtD"}