@cosmicdrift/kumiko-framework 0.406.0 → 0.409.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 (209) hide show
  1. package/agents/api/framework-db.md +1 -0
  2. package/agents/api/framework-engine.md +15 -2
  3. package/agents/api/framework-ui-types.md +15 -0
  4. package/agents/api/renderer-web.md +156 -2
  5. package/agents/api/types.md +113 -71
  6. package/agents/api.md +4 -4
  7. package/agents/boot-rules.md +743 -0
  8. package/agents/examples/contact.md +167 -0
  9. package/agents/examples/delivery-notifications.md +34 -1
  10. package/agents/examples/record-detail-layout.md +13 -2
  11. package/agents/examples/search.md +65 -3
  12. package/agents/examples/secrets-demo.md +96 -2
  13. package/agents/examples/tenant-inactivity.md +138 -0
  14. package/agents/examples.md +2 -0
  15. package/agents/features-index.md +4 -0
  16. package/agents/features.md +24 -1
  17. package/agents/widgets.md +12 -1
  18. package/dist/api/export/export-rows.js +1 -0
  19. package/dist/compliance/index.d.ts +1 -1
  20. package/dist/db/event-store-executor-read-where.js +15 -5
  21. package/dist/db/index.d.ts +1 -1
  22. package/dist/db/index.js +1 -1
  23. package/dist/db/migrate-generator.js +3 -1
  24. package/dist/db/queries/event-consumer.js +11 -7
  25. package/dist/db/queries/event-store.d.ts +2 -1
  26. package/dist/db/queries/event-store.js +25 -6
  27. package/dist/db/queries/rls-boot-catalog.js +3 -1
  28. package/dist/db/queries/session-advisory-lock.d.ts +7 -0
  29. package/dist/db/queries/session-advisory-lock.js +23 -0
  30. package/dist/db/query.js +7 -10
  31. package/dist/db/row-level-security-connection.js +4 -2
  32. package/dist/engine/active-membership.js +1 -0
  33. package/dist/engine/boot-validator/access-declarations.js +57 -33
  34. package/dist/engine/boot-validator/action-wiring.js +8 -6
  35. package/dist/engine/boot-validator/agent-effect-rules.d.ts +12 -0
  36. package/dist/engine/boot-validator/agent-effect-rules.js +12 -0
  37. package/dist/engine/boot-validator/agent-effect.d.ts +2 -0
  38. package/dist/engine/boot-validator/agent-effect.js +20 -0
  39. package/dist/engine/boot-validator/boot-context.js +5 -1
  40. package/dist/engine/boot-validator/boot-environment-rules.d.ts +12 -0
  41. package/dist/engine/boot-validator/boot-environment-rules.js +12 -0
  42. package/dist/engine/boot-validator/boot-phases-app.js +5 -1
  43. package/dist/engine/boot-validator/boot-phases.js +3 -1
  44. package/dist/engine/boot-validator/boot-rules.d.ts +2619 -0
  45. package/dist/engine/boot-validator/boot-rules.js +58 -0
  46. package/dist/engine/boot-validator/bundled-lists-table.js +23 -9
  47. package/dist/engine/boot-validator/config-deps.js +71 -23
  48. package/dist/engine/boot-validator/config-edit-action-rules.d.ts +17 -0
  49. package/dist/engine/boot-validator/config-edit-action-rules.js +17 -0
  50. package/dist/engine/boot-validator/config-key-rules.d.ts +117 -0
  51. package/dist/engine/boot-validator/config-key-rules.js +117 -0
  52. package/dist/engine/boot-validator/custom-screen-write-qns.js +6 -2
  53. package/dist/engine/boot-validator/derived-sql-fields-rules.d.ts +77 -0
  54. package/dist/engine/boot-validator/derived-sql-fields-rules.js +77 -0
  55. package/dist/engine/boot-validator/derived-sql-fields.js +53 -17
  56. package/dist/engine/boot-validator/detail-screens.js +10 -4
  57. package/dist/engine/boot-validator/entity-declaration-rules.d.ts +92 -0
  58. package/dist/engine/boot-validator/entity-declaration-rules.js +92 -0
  59. package/dist/engine/boot-validator/entity-handler-access-rules.d.ts +102 -0
  60. package/dist/engine/boot-validator/entity-handler-access-rules.js +102 -0
  61. package/dist/engine/boot-validator/entity-handler.d.ts +0 -7
  62. package/dist/engine/boot-validator/entity-handler.js +259 -355
  63. package/dist/engine/boot-validator/entity-image-variants.d.ts +2 -0
  64. package/dist/engine/boot-validator/entity-image-variants.js +91 -0
  65. package/dist/engine/boot-validator/entity-list-aggregate-options.js +8 -2
  66. package/dist/engine/boot-validator/entity-reference-embedded-rules.d.ts +117 -0
  67. package/dist/engine/boot-validator/entity-reference-embedded-rules.js +117 -0
  68. package/dist/engine/boot-validator/entity-select-image-rules.d.ts +122 -0
  69. package/dist/engine/boot-validator/entity-select-image-rules.js +122 -0
  70. package/dist/engine/boot-validator/entity-select.d.ts +8 -0
  71. package/dist/engine/boot-validator/entity-select.js +197 -0
  72. package/dist/engine/boot-validator/entity-structure-rules.d.ts +107 -0
  73. package/dist/engine/boot-validator/entity-structure-rules.js +107 -0
  74. package/dist/engine/boot-validator/field-conditions-rules.d.ts +92 -0
  75. package/dist/engine/boot-validator/field-conditions-rules.js +92 -0
  76. package/dist/engine/boot-validator/field-conditions.js +67 -22
  77. package/dist/engine/boot-validator/form-derivations-rules.d.ts +77 -0
  78. package/dist/engine/boot-validator/form-derivations-rules.js +77 -0
  79. package/dist/engine/boot-validator/form-derivations.js +52 -18
  80. package/dist/engine/boot-validator/global-tenancy.js +13 -7
  81. package/dist/engine/boot-validator/handler-declaration-rules.d.ts +72 -0
  82. package/dist/engine/boot-validator/handler-declaration-rules.js +72 -0
  83. package/dist/engine/boot-validator/handler-field-references-rules.d.ts +22 -0
  84. package/dist/engine/boot-validator/handler-field-references-rules.js +22 -0
  85. package/dist/engine/boot-validator/handler-field-references.js +14 -6
  86. package/dist/engine/boot-validator/list-bulk-actions-rules.d.ts +42 -0
  87. package/dist/engine/boot-validator/list-bulk-actions-rules.js +42 -0
  88. package/dist/engine/boot-validator/list-bulk-actions.js +29 -11
  89. package/dist/engine/boot-validator/list-column-layout.js +22 -10
  90. package/dist/engine/boot-validator/list-query-rules.d.ts +107 -0
  91. package/dist/engine/boot-validator/list-query-rules.js +107 -0
  92. package/dist/engine/boot-validator/list-table-aggregate-options.js +43 -15
  93. package/dist/engine/boot-validator/list-table-aggregate-query.js +7 -3
  94. package/dist/engine/boot-validator/list-table-aggregate-rules.d.ts +82 -0
  95. package/dist/engine/boot-validator/list-table-aggregate-rules.js +82 -0
  96. package/dist/engine/boot-validator/list-table-export-options.js +19 -7
  97. package/dist/engine/boot-validator/list-table-options.js +33 -13
  98. package/dist/engine/boot-validator/list-table-reject-unknown-keys.js +6 -2
  99. package/dist/engine/boot-validator/list-table-rules.d.ts +132 -0
  100. package/dist/engine/boot-validator/list-table-rules.js +132 -0
  101. package/dist/engine/boot-validator/nav-rules.d.ts +42 -0
  102. package/dist/engine/boot-validator/nav-rules.js +42 -0
  103. package/dist/engine/boot-validator/nav.js +29 -15
  104. package/dist/engine/boot-validator/ownership-rules.d.ts +27 -0
  105. package/dist/engine/boot-validator/ownership-rules.js +27 -0
  106. package/dist/engine/boot-validator/ownership.js +28 -12
  107. package/dist/engine/boot-validator/parent-ref.js +32 -20
  108. package/dist/engine/boot-validator/projection-list-screens.js +76 -35
  109. package/dist/engine/boot-validator/query-output-columns.js +9 -3
  110. package/dist/engine/boot-validator/query-refs.js +20 -10
  111. package/dist/engine/boot-validator/query-rules.d.ts +37 -0
  112. package/dist/engine/boot-validator/query-rules.js +37 -0
  113. package/dist/engine/boot-validator/read-gate.js +14 -10
  114. package/dist/engine/boot-validator/record-owned.js +5 -1
  115. package/dist/engine/boot-validator/related-list-table-rules.js +17 -7
  116. package/dist/engine/boot-validator/screens-actions-rules.d.ts +185 -0
  117. package/dist/engine/boot-validator/screens-actions-rules.js +185 -0
  118. package/dist/engine/boot-validator/screens-actions.js +169 -93
  119. package/dist/engine/boot-validator/screens-dashboard-chart-rules.d.ts +87 -0
  120. package/dist/engine/boot-validator/screens-dashboard-chart-rules.js +87 -0
  121. package/dist/engine/boot-validator/screens-dashboard-rules.d.ts +227 -0
  122. package/dist/engine/boot-validator/screens-dashboard-rules.js +227 -0
  123. package/dist/engine/boot-validator/screens-dashboard.js +222 -85
  124. package/dist/engine/boot-validator/screens-forms-layout-rules.d.ts +122 -0
  125. package/dist/engine/boot-validator/screens-forms-layout-rules.js +122 -0
  126. package/dist/engine/boot-validator/screens-forms-rules.d.ts +152 -0
  127. package/dist/engine/boot-validator/screens-forms-rules.js +152 -0
  128. package/dist/engine/boot-validator/screens-forms.js +240 -112
  129. package/dist/engine/boot-validator/screens-kind-config-edit.js +72 -16
  130. package/dist/engine/boot-validator/screens-kind-entity-edit.js +15 -7
  131. package/dist/engine/boot-validator/screens-kind-entity-list.js +57 -32
  132. package/dist/engine/boot-validator/screens-kind-projection-detail-rules.d.ts +92 -0
  133. package/dist/engine/boot-validator/screens-kind-projection-detail-rules.js +92 -0
  134. package/dist/engine/boot-validator/screens-kind-projection-detail.js +85 -47
  135. package/dist/engine/boot-validator/screens-kind-rules.d.ts +137 -0
  136. package/dist/engine/boot-validator/screens-kind-rules.js +137 -0
  137. package/dist/engine/boot-validator/screens-kind-secret-mint.js +18 -8
  138. package/dist/engine/boot-validator/screens-kind-shared.js +40 -22
  139. package/dist/engine/boot-validator/screens-lists-rules.d.ts +82 -0
  140. package/dist/engine/boot-validator/screens-lists-rules.js +82 -0
  141. package/dist/engine/boot-validator/screens-lists.js +90 -45
  142. package/dist/engine/boot-validator/screens-rules.d.ts +57 -0
  143. package/dist/engine/boot-validator/screens-rules.js +57 -0
  144. package/dist/engine/boot-validator/screens.js +17 -12
  145. package/dist/engine/boot-validator/transaction-phases.js +12 -4
  146. package/dist/engine/boot-validator/transfer-graph.js +17 -11
  147. package/dist/engine/boot-validator/url-prefill-fields.js +9 -5
  148. package/dist/engine/boot-validator/workspaces.js +11 -5
  149. package/dist/engine/boot-validator/zod-shape.js +6 -2
  150. package/dist/engine/entity-handlers.d.ts +1 -0
  151. package/dist/engine/entity-handlers.js +3 -0
  152. package/dist/engine/entity-list-runtime-options.js +23 -29
  153. package/dist/engine/extensions/tenant-data.d.ts +3 -0
  154. package/dist/engine/factories.d.ts +1 -1
  155. package/dist/engine/factories.js +4 -3
  156. package/dist/engine/index.d.ts +4 -2
  157. package/dist/engine/index.js +2 -0
  158. package/dist/engine/project-app-schema-for-roles.js +29 -14
  159. package/dist/engine/registry-facade.js +7 -8
  160. package/dist/engine/registry-validate.js +5 -1
  161. package/dist/engine/soft-delete-cleanup.d.ts +1 -0
  162. package/dist/engine/soft-delete-cleanup.js +5 -0
  163. package/dist/engine/steps/describe-workflow-step-error.js +1 -0
  164. package/dist/es-ops/operations-schema.d.ts +1 -1
  165. package/dist/event-store/ensure-dead-letter-table.d.ts +2 -0
  166. package/dist/event-store/ensure-dead-letter-table.js +10 -0
  167. package/dist/event-store/rebuild-dead-letter.js +2 -8
  168. package/dist/event-store/upcaster-dead-letter.js +2 -8
  169. package/dist/files/copy-pending-file-refs-to-tenant.d.ts +28 -0
  170. package/dist/files/copy-pending-file-refs-to-tenant.js +87 -0
  171. package/dist/files/file-routes.d.ts +1 -1
  172. package/dist/files/file-routes.js +21 -6
  173. package/dist/files/index.d.ts +2 -0
  174. package/dist/files/index.js +1 -0
  175. package/dist/i18n/required-surface-keys.js +1 -0
  176. package/dist/jobs/job-runner-helpers.js +1 -0
  177. package/dist/jobs/job-runner.js +7 -12
  178. package/dist/logging/utils.js +30 -60
  179. package/dist/observability/metrics-handle.js +10 -21
  180. package/dist/pipeline/cascade-handler.js +7 -6
  181. package/dist/pipeline/dispatch-query.js +18 -5
  182. package/dist/pipeline/dispatch-shared.d.ts +1 -0
  183. package/dist/pipeline/dispatch-shared.js +3 -1
  184. package/dist/pipeline/dispatch-write.js +10 -12
  185. package/dist/pipeline/dispatcher.js +12 -14
  186. package/dist/pipeline/event-dispatcher-admin.js +9 -8
  187. package/dist/pipeline/event-dispatcher-delivery.d.ts +19 -1
  188. package/dist/pipeline/event-dispatcher-delivery.js +121 -29
  189. package/dist/pipeline/event-dispatcher.d.ts +5 -1
  190. package/dist/pipeline/event-dispatcher.js +28 -21
  191. package/dist/pipeline/handler-context-phase-denials.js +2 -0
  192. package/dist/pipeline/multi-stream-apply-context.js +12 -20
  193. package/dist/pipeline/system-hooks.d.ts +4 -1
  194. package/dist/pipeline/system-hooks.js +79 -6
  195. package/dist/pipeline/system-identity-switch.js +10 -7
  196. package/dist/search/build-search-snippet.d.ts +9 -0
  197. package/dist/search/build-search-snippet.js +40 -0
  198. package/dist/search/index.d.ts +1 -0
  199. package/dist/search/index.js +1 -0
  200. package/dist/search/meilisearch-adapter.d.ts +32 -0
  201. package/dist/search/meilisearch-adapter.js +153 -56
  202. package/dist/search/meilisearch-chunking.d.ts +21 -0
  203. package/dist/search/meilisearch-chunking.js +96 -0
  204. package/dist/search/reindex-entity.d.ts +1 -0
  205. package/dist/search/reindex-entity.js +97 -52
  206. package/dist/ui-types/index.d.ts +1 -1
  207. package/dist/upgrade-cli.js +3 -14
  208. package/package.json +3 -3
  209. package/src/changes.json +73 -0
@@ -1,11 +1,14 @@
1
- import { SELECT_OPTION_TONES } from "@cosmicdrift/kumiko-types/fields";
2
1
  import { declaredRateLimitOptions, isRateLimitDisabled } from "@cosmicdrift/kumiko-types/handlers";
3
2
  import { ZodObject } from "zod";
4
- import { VARIANT_NAME_PATTERN } from "../../derivatives/variant-key.js";
5
3
  import { holdsFileRefs } from "../../files/file-field-slots.js";
6
4
  import { access as accessPresets } from "../config-helpers.js";
7
5
  import { parseRefTarget } from "../parse-ref-target.js";
8
- import { isSelectOptionTone } from "./select-option-tone.js";
6
+ import { validateAgentProposalEffect } from "./agent-effect.js";
7
+ import { bootRuleError } from "./boot-rule.js";
8
+ import { HANDLER_ACCESS_RULES } from "./entity-handler-access-rules.js";
9
+ import { ENTITY_REFERENCE_EMBEDDED_RULES } from "./entity-reference-embedded-rules.js";
10
+ import { ENTITY_STRUCTURE_RULES } from "./entity-structure-rules.js";
11
+ import { FIELD_CONDITION_RULES } from "./field-conditions-rules.js";
9
12
  import { validateBeforeTransactionWhenNested, validatePerCommandTransaction, } from "./transaction-phases.js";
10
13
  export const FILE_FIELD_TYPES = new Set(["file", "image", "files", "images"]);
11
14
  // Field names that typically contain PII. Without a `pii: true` /
@@ -104,9 +107,11 @@ export function validateExtensionPreSaveWiring(features) {
104
107
  if (!extensionsWithPreSave.has(usage.extensionName))
105
108
  continue;
106
109
  if (!entitiesWithMappedWrites.has(usage.entityName)) {
107
- throw new Error(`Feature "${f.name}" uses extension "${usage.extensionName}" with preSave on entity "${usage.entityName}" ` +
108
- `but no write handler is entity-mapped to "${usage.entityName}". ` +
109
- `Use create/update/delete on a matching entity or name the handler "entity:verb".`);
110
+ throw bootRuleError(HANDLER_ACCESS_RULES.presaveWithoutMappedWrite, {
111
+ message: `Feature "${f.name}" uses extension "${usage.extensionName}" with preSave on entity "${usage.entityName}" ` +
112
+ `but no write handler is entity-mapped to "${usage.entityName}". ` +
113
+ `Use create/update/delete on a matching entity or name the handler "entity:verb".`,
114
+ });
110
115
  }
111
116
  }
112
117
  }
@@ -129,8 +134,10 @@ export function validateHandlerAccess(feature) {
129
134
  for (const { kind, label, handlers } of kinds) {
130
135
  for (const [name, handler] of Object.entries(handlers)) {
131
136
  if (!handler.access) {
132
- throw new Error(`${label} handler "${feature.name}:${kind}:${name}" is missing an access rule. ` +
133
- `Set { roles: [...] } for role-based access, or { openToAll: { reason: "..." } } for any authenticated user.`);
137
+ throw bootRuleError(HANDLER_ACCESS_RULES.accessMissing, {
138
+ message: `${label} handler "${feature.name}:${kind}:${name}" is missing an access rule. ` +
139
+ `Set { roles: [...] } for role-based access, or { openToAll: { reason: "..." } } for any authenticated user.`,
140
+ });
134
141
  }
135
142
  validateNoAllRoleInHandlerAccess(feature.name, kind, name, handler.access);
136
143
  validateRateLimitBucketList(feature.name, kind, name, handler.rateLimit);
@@ -144,6 +151,10 @@ export function validateHandlerAccess(feature) {
144
151
  validateRateLimitCost(feature.name, name, handler);
145
152
  validatePerCommandTransaction(feature.name, name, handler);
146
153
  validateBeforeTransactionWhenNested(feature.name, name, handler);
154
+ validateAgentProposalEffect(feature.name, "write", name, handler.agent);
155
+ }
156
+ for (const [name, handler] of Object.entries(feature.queryHandlers)) {
157
+ validateAgentProposalEffect(feature.name, "query", name, handler.agent);
147
158
  }
148
159
  }
149
160
  const IP_BUCKETED_RATE_LIMIT_PER = new Set(["ip", "ip+handler"]);
@@ -157,7 +168,9 @@ export function validateAdditionalRateLimits(featureName, handlerName, handler)
157
168
  return;
158
169
  const where = `write handler "${featureName}:write:${handlerName}" declares additionalRateLimits`;
159
170
  if (additionalRateLimits.length === 0) {
160
- throw new Error(`${where} as an empty array — declare at least one bucket or drop the option.`);
171
+ throw bootRuleError(HANDLER_ACCESS_RULES.additionalBucketsEmpty, {
172
+ message: `${where} as an empty array — declare at least one bucket or drop the option.`,
173
+ });
161
174
  }
162
175
  validateAnonymousHasIpBucket(where, handler);
163
176
  const shape = handler.schema instanceof ZodObject ? handler.schema.shape : undefined;
@@ -168,8 +181,10 @@ export function validateAdditionalRateLimits(featureName, handlerName, handler)
168
181
  // Two entries on one field hash the same value into the same Redis key, so enforceAll
169
182
  // would deduct only one of the costs.
170
183
  if (seenFields.has(field)) {
171
- throw new Error(`${where} with payloadField "${field}" more than once — both entries would share one ` +
172
- `Redis bucket per value. Keep one entry per payloadField.`);
184
+ throw bootRuleError(HANDLER_ACCESS_RULES.additionalPayloadFieldDuplicate, {
185
+ message: `${where} with payloadField "${field}" more than once — both entries would share one ` +
186
+ `Redis bucket per value. Keep one entry per payloadField.`,
187
+ });
173
188
  }
174
189
  seenFields.add(field);
175
190
  }
@@ -182,21 +197,29 @@ function validateAnonymousHasIpBucket(where, handler) {
182
197
  return;
183
198
  const hasIpBucket = declaredRateLimitOptions(rateLimit).some((option) => IP_BUCKETED_RATE_LIMIT_PER.has(option.per));
184
199
  if (!hasIpBucket) {
185
- throw new Error(`${where} and allows anonymous callers, but has no ip-keyed rateLimit ` +
186
- `(per: "ip" or "ip+handler", not disabled). Payload buckets only complement the IP bucket. Set rateLimit: { per: "ip", ... } on the handler.`);
200
+ throw bootRuleError(HANDLER_ACCESS_RULES.additionalWithoutIpBucket, {
201
+ message: `${where} and allows anonymous callers, but has no ip-keyed rateLimit ` +
202
+ `(per: "ip" or "ip+handler", not disabled). Payload buckets only complement the IP bucket. Set rateLimit: { per: "ip", ... } on the handler.`,
203
+ });
187
204
  }
188
205
  }
189
206
  function validatePayloadBucket(where, shape, entry) {
190
207
  const field = entry.per.payloadField;
191
208
  if (shape === undefined || !Object.hasOwn(shape, field)) {
192
- throw new Error(`${where} with payloadField "${field}", which is not a field of the handler's schema ` +
193
- `(the schema must be a Zod object containing it).`);
209
+ throw bootRuleError(HANDLER_ACCESS_RULES.payloadFieldUnknown, {
210
+ message: `${where} with payloadField "${field}", which is not a field of the handler's schema ` +
211
+ `(the schema must be a Zod object containing it).`,
212
+ });
194
213
  }
195
214
  if (!Number.isInteger(entry.limit) || entry.limit <= 0) {
196
- throw new Error(`${where} for "${field}" with limit ${entry.limit} — must be a positive integer.`);
215
+ throw bootRuleError(HANDLER_ACCESS_RULES.payloadLimitInvalid, {
216
+ message: `${where} for "${field}" with limit ${entry.limit} — must be a positive integer.`,
217
+ });
197
218
  }
198
219
  if (!Number.isInteger(entry.windowSeconds) || entry.windowSeconds <= 0) {
199
- throw new Error(`${where} for "${field}" with windowSeconds ${entry.windowSeconds} — must be a positive integer.`);
220
+ throw bootRuleError(HANDLER_ACCESS_RULES.payloadWindowInvalid, {
221
+ message: `${where} for "${field}" with windowSeconds ${entry.windowSeconds} — must be a positive integer.`,
222
+ });
200
223
  }
201
224
  }
202
225
  const IP_SCOPED_RATE_LIMIT_PER = ["ip", "ip+handler"];
@@ -208,19 +231,25 @@ export function validateTenantlessAnonymous(featureName, handlerName, handler) {
208
231
  const { access } = handler;
209
232
  const isAnonymousOnly = "roles" in access && access.roles.length === 1 && access.roles[0] === "anonymous";
210
233
  if (!isAnonymousOnly) {
211
- throw new Error(`${where} but its access is not exactly { roles: ["anonymous"] } — a tenantless request ` +
212
- `carries no principal beyond the anonymous visitor. Set access to { roles: ["anonymous"] } or remove tenantlessAnonymous.`);
234
+ throw bootRuleError(HANDLER_ACCESS_RULES.tenantlessAnonymousAccess, {
235
+ message: `${where} but its access is not exactly { roles: ["anonymous"] } — a tenantless request ` +
236
+ `carries no principal beyond the anonymous visitor. Set access to { roles: ["anonymous"] } or remove tenantlessAnonymous.`,
237
+ });
213
238
  }
214
239
  const options = declaredRateLimitOptions(handler.rateLimit);
215
240
  if (options.length === 0) {
216
- throw new Error(`${where} without a rateLimit — a handler reachable on hosts that resolve no tenant ` +
217
- `needs a real upper bound (rateLimit: { per: "ip", ... }); { disabled: true } does not count.`);
241
+ throw bootRuleError(HANDLER_ACCESS_RULES.tenantlessAnonymousWithoutRateLimit, {
242
+ message: `${where} without a rateLimit — a handler reachable on hosts that resolve no tenant ` +
243
+ `needs a real upper bound (rateLimit: { per: "ip", ... }); { disabled: true } does not count.`,
244
+ });
218
245
  }
219
246
  for (const { per } of options) {
220
247
  if (IP_SCOPED_RATE_LIMIT_PER.includes(per))
221
248
  continue;
222
- throw new Error(`${where} with rateLimit.per "${per}" — every anonymous visitor shares the same ` +
223
- `tenant/user bucket, so one caller could exhaust it for all. Use ${IP_SCOPED_RATE_LIMIT_PER.map((allowed) => `"${allowed}"`).join(" or ")}.`);
249
+ throw bootRuleError(HANDLER_ACCESS_RULES.tenantlessAnonymousRateLimitPer, {
250
+ message: `${where} with rateLimit.per "${per}" — every anonymous visitor shares the same ` +
251
+ `tenant/user bucket, so one caller could exhaust it for all. Use ${IP_SCOPED_RATE_LIMIT_PER.map((allowed) => `"${allowed}"`).join(" or ")}.`,
252
+ });
224
253
  }
225
254
  }
226
255
  export function validateRateLimitCost(featureName, handlerName, handler) {
@@ -228,15 +257,19 @@ export function validateRateLimitCost(featureName, handlerName, handler) {
228
257
  if (!handler.rateLimitCost)
229
258
  return;
230
259
  if (handler.rateLimit === undefined || isRateLimitDisabled(handler.rateLimit)) {
231
- throw new Error(`write handler "${featureName}:write:${handlerName}" declares rateLimitCost without an active rateLimit — ` +
232
- `the cost is booked on the rateLimit buckets, so declare rateLimit or drop rateLimitCost.`);
260
+ throw bootRuleError(HANDLER_ACCESS_RULES.costWithoutRateLimit, {
261
+ message: `write handler "${featureName}:write:${handlerName}" declares rateLimitCost without an active rateLimit — ` +
262
+ `the cost is booked on the rateLimit buckets, so declare rateLimit or drop rateLimitCost.`,
263
+ });
233
264
  }
234
265
  const isAnonymous = "roles" in handler.access && handler.access.roles.includes("anonymous");
235
266
  const hasIpBucket = declaredRateLimitOptions(handler.rateLimit).some(({ per }) => IP_SCOPED_RATE_LIMIT_PER.includes(per));
236
267
  if (isAnonymous || hasIpBucket) {
237
- throw new Error(`write handler "${featureName}:write:${handlerName}" declares rateLimitCost on an anonymous or ip-limited handler — ` +
238
- `rateLimitCost books after the parse, so such a handler would lose its pre-parse protection against junk floods. ` +
239
- `Bulk handlers are authenticated: use a user/tenant bucket and drop "anonymous", or drop rateLimitCost.`);
268
+ throw bootRuleError(HANDLER_ACCESS_RULES.costOnAnonymousHandler, {
269
+ message: `write handler "${featureName}:write:${handlerName}" declares rateLimitCost on an anonymous or ip-limited handler — ` +
270
+ `rateLimitCost books after the parse, so such a handler would lose its pre-parse protection against junk floods. ` +
271
+ `Bulk handlers are authenticated: use a user/tenant bucket and drop "anonymous", or drop rateLimitCost.`,
272
+ });
240
273
  }
241
274
  }
242
275
  export function validateRateLimitDisabledReason(featureName, kind, handlerName, rateLimit) {
@@ -244,9 +277,11 @@ export function validateRateLimitDisabledReason(featureName, kind, handlerName,
244
277
  if (!isRateLimitDisabled(rateLimit))
245
278
  return;
246
279
  if (rateLimit.reason.trim().length === 0) {
247
- throw new Error(`${kind} handler "${featureName}:${kind}:${handlerName}" declares rateLimit: { disabled: true } ` +
248
- `without a reason. Provide { disabled: true, reason: "..." } explaining why this handler must not ` +
249
- `be rate-limited.`);
280
+ throw bootRuleError(HANDLER_ACCESS_RULES.disabledWithoutReason, {
281
+ message: `${kind} handler "${featureName}:${kind}:${handlerName}" declares rateLimit: { disabled: true } ` +
282
+ `without a reason. Provide { disabled: true, reason: "..." } explaining why this handler must not ` +
283
+ `be rate-limited.`,
284
+ });
250
285
  }
251
286
  }
252
287
  export function validateRateLimitBucketList(featureName, kind, handlerName, rateLimit) {
@@ -255,13 +290,17 @@ export function validateRateLimitBucketList(featureName, kind, handlerName, rate
255
290
  return;
256
291
  const where = `${kind} handler "${featureName}:${kind}:${handlerName}"`;
257
292
  if (rateLimit.length === 0) {
258
- throw new Error(`${where} declares rateLimit as an empty array — declare at least one bucket or drop the option.`);
293
+ throw bootRuleError(HANDLER_ACCESS_RULES.bucketListEmpty, {
294
+ message: `${where} declares rateLimit as an empty array — declare at least one bucket or drop the option.`,
295
+ });
259
296
  }
260
297
  const seen = new Set();
261
298
  for (const { per } of rateLimit) {
262
299
  if (seen.has(per)) {
263
- throw new Error(`${where} declares rateLimit with per "${per}" more than once — both entries would share one ` +
264
- `Redis bucket with conflicting limits. Keep one entry per "per".`);
300
+ throw bootRuleError(HANDLER_ACCESS_RULES.bucketPerDuplicate, {
301
+ message: `${where} declares rateLimit with per "${per}" more than once — both entries would share one ` +
302
+ `Redis bucket with conflicting limits. Keep one entry per "per".`,
303
+ });
265
304
  }
266
305
  seen.add(per);
267
306
  }
@@ -274,10 +313,12 @@ export function validateNoAllRoleInHandlerAccess(featureName, kind, handlerName,
274
313
  // skip: no "all" in the roles list, nothing unreachable to report
275
314
  if (!accessPresets.all.some((role) => access.roles.includes(role)))
276
315
  return;
277
- throw new Error(`${kind} handler "${featureName}:${kind}:${handlerName}" declares access: { roles: ["all"] } — ` +
278
- `no session ever carries the role "all", so this handler is unreachable by any caller. ` +
279
- `Use access: { roles: ["anonymous"] } plus rateLimit: { per: "ip", ... } (or "ip+handler") ` +
280
- `for unauthenticated callers, or access: { openToAll: { reason: "..." } } for any signed-in user.`);
316
+ throw bootRuleError(HANDLER_ACCESS_RULES.accessAllRole, {
317
+ message: `${kind} handler "${featureName}:${kind}:${handlerName}" declares access: { roles: ["all"] } — ` +
318
+ `no session ever carries the role "all", so this handler is unreachable by any caller. ` +
319
+ `Use access: { roles: ["anonymous"] } plus rateLimit: { per: "ip", ... } (or "ip+handler") ` +
320
+ `for unauthenticated callers, or access: { openToAll: { reason: "..." } } for any signed-in user.`,
321
+ });
281
322
  }
282
323
  export function validateAnonymousRateLimit(featureName, kind, handlerName, access, rateLimit) {
283
324
  // skip: openToAll handlers don't allow anonymous (hasAccess rejects), so
@@ -292,19 +333,23 @@ export function validateAnonymousRateLimit(featureName, kind, handlerName, acces
292
333
  return;
293
334
  const options = declaredRateLimitOptions(rateLimit);
294
335
  if (options.length === 0) {
295
- throw new Error(`${kind} handler "${featureName}:${kind}:${handlerName}" allows anonymous callers but declares no ` +
296
- `rateLimit — an anonymous, internet-facing endpoint needs an upper bound. Set rateLimit: ` +
297
- `{ per: "ip", limit: ..., windowSeconds: ... }, or the documented exception ` +
298
- `rateLimit: { disabled: true, reason: "..." }.`);
336
+ throw bootRuleError(HANDLER_ACCESS_RULES.anonymousWithoutRateLimit, {
337
+ message: `${kind} handler "${featureName}:${kind}:${handlerName}" allows anonymous callers but declares no ` +
338
+ `rateLimit — an anonymous, internet-facing endpoint needs an upper bound. Set rateLimit: ` +
339
+ `{ per: "ip", limit: ..., windowSeconds: ... }, or the documented exception ` +
340
+ `rateLimit: { disabled: true, reason: "..." }.`,
341
+ });
299
342
  }
300
343
  for (const { per } of options) {
301
344
  // skip: this bucket is keyed on something safe (ip / tenant)
302
345
  if (!USER_BUCKETED_RATE_LIMIT_PER.has(per))
303
346
  continue;
304
- throw new Error(`${kind} handler "${featureName}:${kind}:${handlerName}" allows anonymous callers but uses ` +
305
- `rateLimit.per="${per}" — every anonymous request shares user.id="anonymous", ` +
306
- `so this bucket would be a single global tap any caller could drain. ` +
307
- `Use rateLimit.per="ip" or "ip+handler" for anonymous endpoints.`);
347
+ throw bootRuleError(HANDLER_ACCESS_RULES.anonymousUserBucket, {
348
+ message: `${kind} handler "${featureName}:${kind}:${handlerName}" allows anonymous callers but uses ` +
349
+ `rateLimit.per="${per}" — every anonymous request shares user.id="anonymous", ` +
350
+ `so this bucket would be a single global tap any caller could drain. ` +
351
+ `Use rateLimit.per="ip" or "ip+handler" for anonymous endpoints.`,
352
+ });
308
353
  }
309
354
  }
310
355
  // --- MultiStreamProjection delivery invariant ---
@@ -322,9 +367,11 @@ export function validateAnonymousRateLimit(featureName, kind, handlerName, acces
322
367
  export function validateMultiStreamProjections(feature) {
323
368
  for (const [name, msp] of Object.entries(feature.multiStreamProjections)) {
324
369
  if (msp.delivery === "per-instance" && msp.table !== undefined) {
325
- throw new Error(`[Feature ${feature.name}] MultiStreamProjection "${name}" has delivery="per-instance" AND a backing table — ` +
326
- `that combination would make every dispatcher-instance write the same rows (duplicate INSERTs), and rebuild would reset only the shared cursor while live cursors live per-instance (cursor divergence). ` +
327
- `Use delivery="shared" (default) for table-materializing projections, or drop the table for side-effect-only consumers (SSE, in-memory caches).`);
370
+ throw bootRuleError(HANDLER_ACCESS_RULES.perInstanceWithTable, {
371
+ message: `[Feature ${feature.name}] MultiStreamProjection "${name}" has delivery="per-instance" AND a backing table — ` +
372
+ `that combination would make every dispatcher-instance write the same rows (duplicate INSERTs), and rebuild would reset only the shared cursor while live cursors live per-instance (cursor divergence). ` +
373
+ `Use delivery="shared" (default) for table-materializing projections, or drop the table for side-effect-only consumers (SSE, in-memory caches).`,
374
+ });
328
375
  }
329
376
  }
330
377
  }
@@ -349,15 +396,19 @@ export function validateLocatedTimestamps(feature) {
349
396
  continue;
350
397
  const referenced = fields[field.locatedBy];
351
398
  if (!referenced) {
352
- throw new Error(`Feature "${feature.name}", entity "${entityName}": field "${fieldName}" has ` +
353
- `locatedBy: "${field.locatedBy}" but no field with that name exists in the entity. ` +
354
- `Either declare the tz-field, or use createLocatedTimestampField() ` +
355
- `to create a single located-timestamp field instead.`);
399
+ throw bootRuleError(ENTITY_STRUCTURE_RULES.locatedByMissingField, {
400
+ message: `Feature "${feature.name}", entity "${entityName}": field "${fieldName}" has ` +
401
+ `locatedBy: "${field.locatedBy}" but no field with that name exists in the entity. ` +
402
+ `Either declare the tz-field, or use createLocatedTimestampField() ` +
403
+ `to create a single located-timestamp field instead.`,
404
+ });
356
405
  }
357
406
  if (referenced.type !== "tz") {
358
- throw new Error(`Feature "${feature.name}", entity "${entityName}": field "${fieldName}" has ` +
359
- `locatedBy: "${field.locatedBy}" but that field is type "${referenced.type}", ` +
360
- `expected "tz". The locatedBy marker must point to a tz-field (IANA-zone slot).`);
407
+ throw bootRuleError(ENTITY_STRUCTURE_RULES.locatedByNotTz, {
408
+ message: `Feature "${feature.name}", entity "${entityName}": field "${fieldName}" has ` +
409
+ `locatedBy: "${field.locatedBy}" but that field is type "${referenced.type}", ` +
410
+ `expected "tz". The locatedBy marker must point to a tz-field (IANA-zone slot).`,
411
+ });
361
412
  }
362
413
  }
363
414
  }
@@ -382,22 +433,28 @@ export function validateEntityIndexes(feature) {
382
433
  for (const [idx, def] of entity.indexes.entries()) {
383
434
  const where = `Feature "${feature.name}", entity "${entityName}", indexes[${idx}]`;
384
435
  if (def.columns.length === 0) {
385
- throw new Error(`${where}: empty columns list. An index needs at least one column.`);
436
+ throw bootRuleError(ENTITY_STRUCTURE_RULES.indexColumnsEmpty, {
437
+ message: `${where}: empty columns list. An index needs at least one column.`,
438
+ });
386
439
  }
387
440
  for (const col of def.columns) {
388
441
  if (col === "tenantId" || col === "id" || col === "version")
389
442
  continue; // base columns
390
443
  if (!fieldNames.has(col)) {
391
- throw new Error(`${where}: column "${col}" does not match any field in the entity. ` +
392
- `Available fields: ${[...fieldNames].join(", ")}.`);
444
+ throw bootRuleError(ENTITY_STRUCTURE_RULES.indexUnknownColumn, {
445
+ message: `${where}: column "${col}" does not match any field in the entity. ` +
446
+ `Available fields: ${[...fieldNames].join(", ")}.`,
447
+ });
393
448
  }
394
449
  const field = entity.fields[col];
395
450
  if (field &&
396
451
  (field.type === "files" ||
397
452
  field.type === "images" ||
398
453
  (field.type === "reference" && field.multiple === true))) {
399
- throw new Error(`${where}: column "${col}" is a multi-value field (${field.type}) — ` +
400
- `a jsonb array cannot be indexed as a column. Use a single-value field or remove from the index.`);
454
+ throw bootRuleError(ENTITY_STRUCTURE_RULES.indexMultiValueColumn, {
455
+ message: `${where}: column "${col}" is a multi-value field (${field.type}) — ` +
456
+ `a jsonb array cannot be indexed as a column. Use a single-value field or remove from the index.`,
457
+ });
401
458
  }
402
459
  if (field && field.type === "longText") {
403
460
  // longText semantically means "potentially-megabytes content" — a
@@ -407,8 +464,10 @@ export function validateEntityIndexes(feature) {
407
464
  // that longText has no sortable/searchable/filterable flags. Anyone
408
465
  // who truly needs indexing should use `text` with the
409
466
  // corresponding scaling trade-offs.
410
- throw new Error(`${where}: column "${col}" is a longText field — these cannot be indexed. ` +
411
- `Use \`text\` if you need indexing, or rely on the SearchAdapter (Meilisearch) for full-text search on long content.`);
467
+ throw bootRuleError(ENTITY_STRUCTURE_RULES.indexLongTextColumn, {
468
+ message: `${where}: column "${col}" is a longText field — these cannot be indexed. ` +
469
+ `Use \`text\` if you need indexing, or rely on the SearchAdapter (Meilisearch) for full-text search on long content.`,
470
+ });
412
471
  }
413
472
  }
414
473
  // A UNIQUE constraint on tenantId is semantically meaningful (1:1 tenant→entity)
@@ -416,8 +475,10 @@ export function validateEntityIndexes(feature) {
416
475
  // performance hint, not a constraint. Only the tenantId-only,
417
476
  // single-column, non-unique form is rejected.
418
477
  if (def.columns.length === 1 && def.columns[0] === "tenantId" && !def.unique) {
419
- throw new Error(`${where}: single-column index on "tenantId" is redundant — ` +
420
- `buildEntityTable always creates one automatically. Remove this entry.`);
478
+ throw bootRuleError(ENTITY_STRUCTURE_RULES.indexTenantIdOnly, {
479
+ message: `${where}: single-column index on "tenantId" is redundant — ` +
480
+ `buildEntityTable always creates one automatically. Remove this entry.`,
481
+ });
421
482
  }
422
483
  // AES-GCM's random-IV ciphertext is never equal to itself across two
423
484
  // writes of the same plaintext, so a unique index on an encrypted
@@ -426,8 +487,10 @@ export function validateEntityIndexes(feature) {
426
487
  for (const col of def.columns) {
427
488
  const field = entity.fields[col];
428
489
  if (field && (field.type === "text" || field.type === "longText") && field.encrypted) {
429
- throw new Error(`${where}: column "${col}" is encrypted — a unique index on it can never detect ` +
430
- `duplicates (non-deterministic ciphertext). Remove \`unique\` or \`encrypted\`.`);
490
+ throw bootRuleError(ENTITY_STRUCTURE_RULES.indexUniqueEncryptedColumn, {
491
+ message: `${where}: column "${col}" is encrypted — a unique index on it can never detect ` +
492
+ `duplicates (non-deterministic ciphertext). Remove \`unique\` or \`encrypted\`.`,
493
+ });
431
494
  }
432
495
  }
433
496
  }
@@ -449,17 +512,23 @@ export function validateEncryptedFields(feature) {
449
512
  found = true;
450
513
  if (field.type === "text") {
451
514
  if (field.searchable) {
452
- throw new Error(`Field "${fieldName}" on entity "${entityName}" cannot be both encrypted and searchable. Drop searchable: true or remove the encryption.`);
515
+ throw bootRuleError(ENTITY_STRUCTURE_RULES.encryptedSearchable, {
516
+ message: `Field "${fieldName}" on entity "${entityName}" cannot be both encrypted and searchable. Drop searchable: true or remove the encryption.`,
517
+ });
453
518
  }
454
519
  if (field.sortable) {
455
- throw new Error(`Field "${fieldName}" on entity "${entityName}" cannot be both encrypted and sortable. Drop sortable: true or remove the encryption.`);
520
+ throw bootRuleError(ENTITY_STRUCTURE_RULES.encryptedSortable, {
521
+ message: `Field "${fieldName}" on entity "${entityName}" cannot be both encrypted and sortable. Drop sortable: true or remove the encryption.`,
522
+ });
456
523
  }
457
524
  // AES-GCM draws a fresh random IV per call, so the ciphertext is
458
525
  // non-deterministic — an equality filter on it never matches, even
459
526
  // against the identical plaintext.
460
527
  if (field.filterable) {
461
- throw new Error(`Field "${fieldName}" on entity "${entityName}" cannot be both encrypted and filterable ` +
462
- `— non-deterministic ciphertext never matches an equality filter. Drop filterable: true or remove the encryption.`);
528
+ throw bootRuleError(ENTITY_STRUCTURE_RULES.encryptedFilterable, {
529
+ message: `Field "${fieldName}" on entity "${entityName}" cannot be both encrypted and filterable ` +
530
+ `— non-deterministic ciphertext never matches an equality filter. Drop filterable: true or remove the encryption.`,
531
+ });
463
532
  }
464
533
  }
465
534
  }
@@ -513,9 +582,11 @@ function validateReferenceTarget(entityName, fieldPath, refString, labelField, o
513
582
  const targetFeature = featureMap.get(target.featureName);
514
583
  if (!targetFeature) {
515
584
  const knownFeatures = [...featureMap.keys()].sort().join(", ");
516
- throw new Error(`[Feature ${feature.name}] Reference field "${fieldPath}" on entity "${entityName}" ` +
517
- `targets unknown feature "${target.featureName}" via "${refString}". ` +
518
- `Known features: ${knownFeatures}.`);
585
+ throw bootRuleError(ENTITY_REFERENCE_EMBEDDED_RULES.referenceUnknownFeature, {
586
+ message: `[Feature ${feature.name}] Reference field "${fieldPath}" on entity "${entityName}" ` +
587
+ `targets unknown feature "${target.featureName}" via "${refString}". ` +
588
+ `Known features: ${knownFeatures}.`,
589
+ });
519
590
  }
520
591
  const targetEntity = targetFeature.entities?.[target.entityName];
521
592
  if (!targetEntity) {
@@ -525,17 +596,21 @@ function validateReferenceTarget(entityName, fieldPath, refString, labelField, o
525
596
  const where = target.featureName === feature.name
526
597
  ? `in this feature`
527
598
  : `in feature "${target.featureName}"`;
528
- throw new Error(`[Feature ${feature.name}] Reference field "${fieldPath}" on entity "${entityName}" ` +
529
- `targets unknown entity "${target.entityName}" ${where}. ` +
530
- `Known entities: ${known}.`);
599
+ throw bootRuleError(ENTITY_REFERENCE_EMBEDDED_RULES.referenceUnknownEntity, {
600
+ message: `[Feature ${feature.name}] Reference field "${fieldPath}" on entity "${entityName}" ` +
601
+ `targets unknown entity "${target.entityName}" ${where}. ` +
602
+ `Known entities: ${known}.`,
603
+ });
531
604
  }
532
605
  if (labelField !== undefined) {
533
606
  const knownFields = Object.keys(targetEntity.fields);
534
607
  // "id" always exists, even without an explicit field definition (PK).
535
608
  if (labelField !== "id" && !knownFields.includes(labelField)) {
536
- throw new Error(`[Feature ${feature.name}] Reference field "${fieldPath}" on entity "${entityName}" ` +
537
- `references labelField "${labelField}" which does not exist on entity ` +
538
- `"${target.entityName}". Known fields: ${[...knownFields, "id"].sort().join(", ")}.`);
609
+ throw bootRuleError(ENTITY_REFERENCE_EMBEDDED_RULES.referenceUnknownLabelField, {
610
+ message: `[Feature ${feature.name}] Reference field "${fieldPath}" on entity "${entityName}" ` +
611
+ `references labelField "${labelField}" which does not exist on entity ` +
612
+ `"${target.entityName}". Known fields: ${[...knownFields, "id"].sort().join(", ")}.`,
613
+ });
539
614
  }
540
615
  }
541
616
  // Pins query-handler existence. The renderer fires
@@ -545,11 +620,13 @@ function validateReferenceTarget(entityName, fieldPath, refString, labelField, o
545
620
  // "<entity>:list" in feature.queryHandlers.
546
621
  const expectedHandlerShortName = `${target.entityName}:list`;
547
622
  if (targetFeature.queryHandlers[expectedHandlerShortName] === undefined) {
548
- throw new Error(`[Feature ${feature.name}] Reference field "${fieldPath}" on entity "${entityName}" ` +
549
- `targets entity "${target.entityName}" but no list-query-handler is registered ` +
550
- `there. Add r.queryHandler(defineEntityListHandler("${target.entityName}", ` +
551
- `${target.entityName}Entity)) to feature "${target.featureName}", or pick a ` +
552
- `different label/entity.`);
623
+ throw bootRuleError(ENTITY_REFERENCE_EMBEDDED_RULES.referenceTargetWithoutListHandler, {
624
+ message: `[Feature ${feature.name}] Reference field "${fieldPath}" on entity "${entityName}" ` +
625
+ `targets entity "${target.entityName}" but no list-query-handler is registered ` +
626
+ `there. Add r.queryHandler(defineEntityListHandler("${target.entityName}", ` +
627
+ `${target.entityName}Entity)) to feature "${target.featureName}", or pick a ` +
628
+ `different label/entity.`,
629
+ });
553
630
  }
554
631
  // The check above still applies when optionsQuery is set: optionsQuery only
555
632
  // replaces the picker's option list, while list cells keep resolving the
@@ -566,14 +643,18 @@ function validateReferenceOptionsQuery(entityName, fieldPath, optionsQuery, feat
566
643
  if (optionsQuery === undefined)
567
644
  return;
568
645
  if (optionsQuery.length === 0) {
569
- throw new Error(`[Feature ${feature.name}] Reference field "${fieldPath}" on entity "${entityName}" ` +
570
- `has an empty optionsQuery. Drop the property or name a query handler.`);
646
+ throw bootRuleError(ENTITY_REFERENCE_EMBEDDED_RULES.referenceOptionsQueryEmpty, {
647
+ message: `[Feature ${feature.name}] Reference field "${fieldPath}" on entity "${entityName}" ` +
648
+ `has an empty optionsQuery. Drop the property or name a query handler.`,
649
+ });
571
650
  }
572
651
  if (!queryHandlers.has(optionsQuery)) {
573
- throw new Error(`[Feature ${feature.name}] Reference field "${fieldPath}" on entity "${entityName}" ` +
574
- `declares optionsQuery "${optionsQuery}" which is not a registered query-handler. ` +
575
- `Check the QN spelling (expected "<feature>:query:<short>") and that the handler ` +
576
- `is declared via r.queryHandler(...).`);
652
+ throw bootRuleError(ENTITY_REFERENCE_EMBEDDED_RULES.referenceOptionsQueryUnregistered, {
653
+ message: `[Feature ${feature.name}] Reference field "${fieldPath}" on entity "${entityName}" ` +
654
+ `declares optionsQuery "${optionsQuery}" which is not a registered query-handler. ` +
655
+ `Check the QN spelling (expected "<feature>:query:<short>") and that the handler ` +
656
+ `is declared via r.queryHandler(...).`,
657
+ });
577
658
  }
578
659
  }
579
660
  // ReferenceFieldDef validation for top-level
@@ -595,17 +676,25 @@ export function validateEmbeddedFields(feature, featureMap, queryHandlers) {
595
676
  if (field.type !== "embedded")
596
677
  continue;
597
678
  if (!field.schema || Object.keys(field.schema).length === 0) {
598
- throw new Error(`Embedded field "${fieldName}" on entity "${entityName}" in feature "${feature.name}" has an empty schema. Declare at least one sub-field in the embedded schema.`);
679
+ throw bootRuleError(ENTITY_REFERENCE_EMBEDDED_RULES.embeddedSchemaEmpty, {
680
+ message: `Embedded field "${fieldName}" on entity "${entityName}" in feature "${feature.name}" has an empty schema. Declare at least one sub-field in the embedded schema.`,
681
+ });
599
682
  }
600
683
  for (const [subName, subField] of Object.entries(field.schema)) {
601
684
  if (!VALID_EMBEDDED_SUB_TYPES.has(subField.type)) {
602
- throw new Error(`Embedded field "${fieldName}.${subName}" on entity "${entityName}" has invalid type "${subField.type}". Allowed: ${[...VALID_EMBEDDED_SUB_TYPES].join(", ")}`);
685
+ throw bootRuleError(ENTITY_REFERENCE_EMBEDDED_RULES.embeddedSubFieldTypeInvalid, {
686
+ message: `Embedded field "${fieldName}.${subName}" on entity "${entityName}" has invalid type "${subField.type}". Allowed: ${[...VALID_EMBEDDED_SUB_TYPES].join(", ")}`,
687
+ });
603
688
  }
604
689
  if (subField.type === "decimal" && !isValidEmbeddedDecimalScale(subField.scale)) {
605
- throw new Error(`Embedded field "${fieldName}.${subName}" on entity "${entityName}" has invalid scale ${subField.scale}. Must be an integer between 0 and 15.`);
690
+ throw bootRuleError(ENTITY_REFERENCE_EMBEDDED_RULES.embeddedDecimalScaleInvalid, {
691
+ message: `Embedded field "${fieldName}.${subName}" on entity "${entityName}" has invalid scale ${subField.scale}. Must be an integer between 0 and 15.`,
692
+ });
606
693
  }
607
694
  if (subField.type === "select" && subField.options.length === 0) {
608
- throw new Error(`Embedded field "${fieldName}.${subName}" on entity "${entityName}" has empty options. Add at least one option.`);
695
+ throw bootRuleError(ENTITY_REFERENCE_EMBEDDED_RULES.embeddedSelectOptionsEmpty, {
696
+ message: `Embedded field "${fieldName}.${subName}" on entity "${entityName}" has empty options. Add at least one option.`,
697
+ });
609
698
  }
610
699
  // Reference sub-fields get the same target/labelField/query-handler
611
700
  // checks as a top-level reference field — same failure mode
@@ -621,22 +710,30 @@ export function validateEmbeddedFields(feature, featureMap, queryHandlers) {
621
710
  }
622
711
  function validateEmbeddedListBounds(fieldName, entityName, field) {
623
712
  if (field.minItems !== undefined && field.minItems < 0) {
624
- throw new Error(`Embedded-list field "${fieldName}" on entity "${entityName}" has invalid minItems ${field.minItems}. Must be >= 0.`);
713
+ throw bootRuleError(ENTITY_REFERENCE_EMBEDDED_RULES.embeddedMinItemsNegative, {
714
+ message: `Embedded-list field "${fieldName}" on entity "${entityName}" has invalid minItems ${field.minItems}. Must be >= 0.`,
715
+ });
625
716
  }
626
717
  if (field.maxItems !== undefined && field.maxItems < 1) {
627
- throw new Error(`Embedded-list field "${fieldName}" on entity "${entityName}" has invalid maxItems ${field.maxItems}. Must be >= 1.`);
718
+ throw bootRuleError(ENTITY_REFERENCE_EMBEDDED_RULES.embeddedMaxItemsTooSmall, {
719
+ message: `Embedded-list field "${fieldName}" on entity "${entityName}" has invalid maxItems ${field.maxItems}. Must be >= 1.`,
720
+ });
628
721
  }
629
722
  if (field.minItems !== undefined &&
630
723
  field.maxItems !== undefined &&
631
724
  field.minItems > field.maxItems) {
632
- throw new Error(`Embedded-list field "${fieldName}" on entity "${entityName}" has minItems ${field.minItems} greater than maxItems ${field.maxItems}. Set minItems at or below maxItems.`);
725
+ throw bootRuleError(ENTITY_REFERENCE_EMBEDDED_RULES.embeddedMinItemsAboveMax, {
726
+ message: `Embedded-list field "${fieldName}" on entity "${entityName}" has minItems ${field.minItems} greater than maxItems ${field.maxItems}. Set minItems at or below maxItems.`,
727
+ });
633
728
  }
634
729
  // required:true means "at least one row" (schema-builder.ts falls back to
635
730
  // minItems:1 for that); an explicit minItems:0 would silently win over
636
731
  // that and let a required list submit empty — reject the contradiction
637
732
  // instead of picking one side of it for the caller.
638
733
  if (field.required === true && field.minItems === 0) {
639
- throw new Error(`Embedded-list field "${fieldName}" on entity "${entityName}" sets required:true and minItems:0 — these contradict each other. Drop minItems (defaults to 1) or set required:false.`);
734
+ throw bootRuleError(ENTITY_REFERENCE_EMBEDDED_RULES.embeddedRequiredMinItemsZero, {
735
+ message: `Embedded-list field "${fieldName}" on entity "${entityName}" sets required:true and minItems:0 — these contradict each other. Drop minItems (defaults to 1) or set required:false.`,
736
+ });
640
737
  }
641
738
  }
642
739
  function validateEmbeddedDerivedCells(fieldName, entityName, field) {
@@ -645,17 +742,25 @@ function validateEmbeddedDerivedCells(fieldName, entityName, field) {
645
742
  return;
646
743
  for (const [derivedName, derivedDef] of Object.entries(field.derived)) {
647
744
  if (!(derivedName in field.schema)) {
648
- throw new Error(`Embedded-list field "${fieldName}" on entity "${entityName}" has a derived cell "${derivedName}" that is not a sub-field in its schema. Add the sub-field to the schema or remove the derived cell.`);
745
+ throw bootRuleError(ENTITY_REFERENCE_EMBEDDED_RULES.embeddedDerivedCellNotInSchema, {
746
+ message: `Embedded-list field "${fieldName}" on entity "${entityName}" has a derived cell "${derivedName}" that is not a sub-field in its schema. Add the sub-field to the schema or remove the derived cell.`,
747
+ });
649
748
  }
650
749
  if (derivedDef.op === "percent" && derivedDef.from.length !== 2) {
651
- throw new Error(`Embedded-list field "${fieldName}" on entity "${entityName}" has a derived cell "${derivedName}" with op "percent", which needs exactly two sources (base, rate).`);
750
+ throw bootRuleError(ENTITY_REFERENCE_EMBEDDED_RULES.embeddedPercentNeedsTwoSources, {
751
+ message: `Embedded-list field "${fieldName}" on entity "${entityName}" has a derived cell "${derivedName}" with op "percent", which needs exactly two sources (base, rate).`,
752
+ });
652
753
  }
653
754
  for (const sourceName of derivedDef.from) {
654
755
  if (!(sourceName in field.schema)) {
655
- throw new Error(`Embedded-list field "${fieldName}" on entity "${entityName}" has a derived cell "${derivedName}" reading unknown sub-field "${sourceName}". Read only sub-fields that exist in the schema.`);
756
+ throw bootRuleError(ENTITY_REFERENCE_EMBEDDED_RULES.embeddedDerivedSourceUnknown, {
757
+ message: `Embedded-list field "${fieldName}" on entity "${entityName}" has a derived cell "${derivedName}" reading unknown sub-field "${sourceName}". Read only sub-fields that exist in the schema.`,
758
+ });
656
759
  }
657
760
  if (sourceName in field.derived) {
658
- throw new Error(`Embedded-list field "${fieldName}" on entity "${entityName}" has a derived cell "${derivedName}" reading derived sub-field "${sourceName}". Read only stored sub-fields, not other derived cells.`);
761
+ throw bootRuleError(ENTITY_REFERENCE_EMBEDDED_RULES.embeddedDerivedSourceIsDerived, {
762
+ message: `Embedded-list field "${fieldName}" on entity "${entityName}" has a derived cell "${derivedName}" reading derived sub-field "${sourceName}". Read only stored sub-fields, not other derived cells.`,
763
+ });
659
764
  }
660
765
  }
661
766
  }
@@ -666,12 +771,16 @@ function validateEmbeddedTotalsColumns(fieldName, entityName, field) {
666
771
  return;
667
772
  for (const total of field.totals) {
668
773
  if (typeof total !== "string" && total.from.length === 0) {
669
- throw new Error(`Embedded-list field "${fieldName}" on entity "${entityName}" has a totals entry "${total.label}" with an empty "from". List at least one number, money or decimal sub-field.`);
774
+ throw bootRuleError(ENTITY_REFERENCE_EMBEDDED_RULES.embeddedTotalsFromEmpty, {
775
+ message: `Embedded-list field "${fieldName}" on entity "${entityName}" has a totals entry "${total.label}" with an empty "from". List at least one number, money or decimal sub-field.`,
776
+ });
670
777
  }
671
778
  for (const totalName of typeof total === "string" ? [total] : total.from) {
672
779
  const totalSubField = field.schema[totalName];
673
780
  if (!totalSubField || !NUMERIC_EMBEDDED_SUB_TYPES.has(totalSubField.type)) {
674
- throw new Error(`Embedded-list field "${fieldName}" on entity "${entityName}" lists "${totalName}" in totals, but it is not a number/money/decimal sub-field. List only number, money or decimal sub-fields in totals.`);
781
+ throw bootRuleError(ENTITY_REFERENCE_EMBEDDED_RULES.embeddedTotalsNotNumeric, {
782
+ message: `Embedded-list field "${fieldName}" on entity "${entityName}" lists "${totalName}" in totals, but it is not a number/money/decimal sub-field. List only number, money or decimal sub-fields in totals.`,
783
+ });
675
784
  }
676
785
  }
677
786
  }
@@ -683,11 +792,15 @@ function validateEmbeddedTotalsMatch(fieldName, entityName, field, entity) {
683
792
  for (const [subFieldName, siblingFieldName] of Object.entries(field.totalsMatch)) {
684
793
  const subField = field.schema[subFieldName];
685
794
  if (subField?.type !== "money") {
686
- throw new Error(`Embedded-list field "${fieldName}" on entity "${entityName}" has a totalsMatch entry for "${subFieldName}", which is not a money sub-field in its schema. Use a money sub-field as the totalsMatch key.`);
795
+ throw bootRuleError(ENTITY_REFERENCE_EMBEDDED_RULES.embeddedTotalsMatchKeyNotMoney, {
796
+ message: `Embedded-list field "${fieldName}" on entity "${entityName}" has a totalsMatch entry for "${subFieldName}", which is not a money sub-field in its schema. Use a money sub-field as the totalsMatch key.`,
797
+ });
687
798
  }
688
799
  const siblingField = entity.fields[siblingFieldName];
689
800
  if (siblingField?.type !== "money") {
690
- throw new Error(`Embedded-list field "${fieldName}" on entity "${entityName}" has a totalsMatch entry mapping "${subFieldName}" to sibling field "${siblingFieldName}", which is not a money field on entity "${entityName}". Map it to a money field of the entity.`);
801
+ throw bootRuleError(ENTITY_REFERENCE_EMBEDDED_RULES.embeddedTotalsMatchSiblingNotMoney, {
802
+ message: `Embedded-list field "${fieldName}" on entity "${entityName}" has a totalsMatch entry mapping "${subFieldName}" to sibling field "${siblingFieldName}", which is not a money field on entity "${entityName}". Map it to a money field of the entity.`,
803
+ });
691
804
  }
692
805
  }
693
806
  }
@@ -704,243 +817,12 @@ function validateEmbeddedListMetadata(fieldName, entityName, field, entity) {
704
817
  field.derived !== undefined ||
705
818
  field.totals !== undefined ||
706
819
  field.totalsMatch !== undefined)) {
707
- throw new Error(`Embedded field "${fieldName}" on entity "${entityName}" sets minItems/maxItems/derived/totals/totalsMatch, which is only valid on an embedded LIST field (multiple: true).`);
820
+ throw bootRuleError(ENTITY_REFERENCE_EMBEDDED_RULES.embeddedListOptionsOnNonList, {
821
+ message: `Embedded field "${fieldName}" on entity "${entityName}" sets minItems/maxItems/derived/totals/totalsMatch, which is only valid on an embedded LIST field (multiple: true).`,
822
+ });
708
823
  }
709
824
  validateEmbeddedDerivedAndTotals(fieldName, entityName, field, entity);
710
825
  }
711
- // --- MultiSelect field validation ---
712
- //
713
- // options must be non-empty (otherwise the field cannot be used), and
714
- // default — when set — must be a subset of options. Both conditions would
715
- // also fail at runtime in the Zod schema; boot validation only provides
716
- // the earliest clear error messages.
717
- // Exhaustive over MultiSelectFieldDef["columns"] (the compiler flags a union
718
- // change); the TS union is gone at runtime for JS/JSON-sourced definitions.
719
- const CHECKBOX_COLUMN_COUNTS = {
720
- 1: true,
721
- 2: true,
722
- 3: true,
723
- 4: true,
724
- };
725
- function validateCheckboxDisplayOptions(field, fieldName, entityName) {
726
- if (field.display === "checkboxes") {
727
- if (field.columns !== undefined && !(field.columns in CHECKBOX_COLUMN_COUNTS)) {
728
- throw new Error(`MultiSelect field "${fieldName}" on entity "${entityName}" has invalid columns "${field.columns}" — must be ${Object.keys(CHECKBOX_COLUMN_COUNTS).join(", ")}.`);
729
- }
730
- if (field.maxRows !== undefined && (!Number.isInteger(field.maxRows) || field.maxRows < 1)) {
731
- throw new Error(`MultiSelect field "${fieldName}" on entity "${entityName}" has invalid maxRows "${field.maxRows}" — must be a positive integer.`);
732
- }
733
- // skip: checkboxes is the valid display for these options — the checks below only apply to other displays
734
- return;
735
- }
736
- if (field.columns !== undefined) {
737
- throw new Error(`MultiSelect field "${fieldName}" on entity "${entityName}" sets columns, which is only valid with display: "checkboxes".`);
738
- }
739
- if (field.maxRows !== undefined) {
740
- throw new Error(`MultiSelect field "${fieldName}" on entity "${entityName}" sets maxRows, which is only valid with display: "checkboxes".`);
741
- }
742
- }
743
- function assertSelectOptionTones(field, path, featureName) {
744
- const tones = field.type === "select" ? Object.entries(field.optionTones ?? {}) : [];
745
- for (const [optionValue, tone] of tones) {
746
- if (!isSelectOptionTone(tone)) {
747
- throw new Error(`[Feature ${featureName}] Entity select field "${path}" optionTones["${optionValue}"] is ` +
748
- `"${String(tone)}" — expected one of ${SELECT_OPTION_TONES.join(", ")}.`);
749
- }
750
- }
751
- }
752
- export function validateEntitySelectOptionsQuery(feature) {
753
- for (const [entityName, entity] of Object.entries(feature.entities ?? {})) {
754
- for (const [fieldName, field] of Object.entries(entity.fields)) {
755
- assertNoSelectOptionsQuery(field, `${entityName}.${fieldName}`, feature.name);
756
- assertSelectOptionTones(field, `${entityName}.${fieldName}`, feature.name);
757
- if (field.type !== "embedded")
758
- continue;
759
- for (const [subName, subField] of Object.entries(field.schema ?? {})) {
760
- assertNoSelectOptionsQuery(subField, `${entityName}.${fieldName}.${subName}`, feature.name);
761
- assertSelectOptionTones(subField, `${entityName}.${fieldName}.${subName}`, feature.name);
762
- }
763
- }
764
- }
765
- }
766
- function assertNoSelectOptionsQuery(field, path, featureName) {
767
- // @cast-boundary schema-walk — embedded sub-field types don't declare optionsQuery, an untyped author may still set it
768
- const { optionsQuery, optionsQueryPayload } = field;
769
- const declaresOptionsQuery = optionsQuery !== undefined || optionsQueryPayload !== undefined;
770
- if (field.type === "select" && declaresOptionsQuery) {
771
- throw new Error(`[Feature ${featureName}] Entity select field "${path}" declares optionsQuery — not supported on entity fields because the stored value would not be validated against the query result. Use static options, or a reference field.`);
772
- }
773
- }
774
- // A typo'd availability QN would only surface as a failed query when the form
775
- // mounts, so it is pinned at boot like the other option queries.
776
- export function validateEntitySelectAvailabilityQuery(feature, queryHandlers) {
777
- for (const [entityName, entity] of Object.entries(feature.entities ?? {})) {
778
- for (const [fieldName, field] of Object.entries(entity.fields)) {
779
- if ((field.type !== "select" && field.type !== "multiSelect") ||
780
- field.optionsAvailabilityQuery === undefined)
781
- continue;
782
- const query = field.optionsAvailabilityQuery;
783
- if (query.length === 0 || !queryHandlers.has(query)) {
784
- throw new Error(`[Feature ${feature.name}] ${field.type === "select" ? "Select" : "MultiSelect"} field "${fieldName}" on entity "${entityName}" ` +
785
- `declares optionsAvailabilityQuery "${query}" which is not a registered query-handler. ` +
786
- `Check the QN spelling (expected "<feature>:query:<short>") and that the handler ` +
787
- `is declared via r.queryHandler(...).`);
788
- }
789
- }
790
- }
791
- }
792
- export function conditionComparisonValues(when) {
793
- if ("eq" in when)
794
- return [when.eq];
795
- if ("ne" in when)
796
- return [when.ne];
797
- if ("in" in when)
798
- return when.in;
799
- return when.notIn;
800
- }
801
- export function validateEntitySelectConditionalOptions(feature) {
802
- for (const [entityName, entity] of Object.entries(feature.entities ?? {})) {
803
- for (const [fieldName, field] of Object.entries(entity.fields)) {
804
- if (field.type !== "select" || field.conditionalOptions === undefined)
805
- continue;
806
- const where = `[Feature ${feature.name}] Select field "${fieldName}" on entity "${entityName}"`;
807
- if (field.optionsQuery !== undefined) {
808
- throw new Error(`${where} combines conditionalOptions with optionsQuery — conditionalOptions filters the static options only. Remove either conditionalOptions or optionsQuery.`);
809
- }
810
- const knownOptions = new Set(field.options);
811
- const ruleOfOption = new Map();
812
- field.conditionalOptions.forEach((rule, ruleIndex) => {
813
- const ruleLabel = `conditionalOptions[${ruleIndex}]`;
814
- if (rule.options.length === 0) {
815
- throw new Error(`${where} has an empty ${ruleLabel}.options — drop the rule.`);
816
- }
817
- for (const option of rule.options) {
818
- if (!knownOptions.has(option)) {
819
- throw new Error(`${where} lists "${option}" in ${ruleLabel} which is not in options (${field.options.join(", ")}).`);
820
- }
821
- const otherRule = ruleOfOption.get(option);
822
- if (otherRule !== undefined) {
823
- throw new Error(`${where} lists "${option}" in conditionalOptions[${otherRule}] and ${ruleLabel} — an option may belong to one rule only. Remove the option from one of the rules.`);
824
- }
825
- ruleOfOption.set(option, ruleIndex);
826
- if (option === field.default) {
827
- throw new Error(`${where} has default "${option}" inside ${ruleLabel} — the default must be available unconditionally.`);
828
- }
829
- }
830
- const conditionField = rule.when.field;
831
- if (conditionField === fieldName) {
832
- throw new Error(`${where} has ${ruleLabel}.when on its own field. Make the condition depend on a different field.`);
833
- }
834
- if (!(conditionField in entity.fields)) {
835
- throw new Error(`${where} has ${ruleLabel}.when.field "${conditionField}" which is not a field of the entity. Use an existing field of the entity in when.field.`);
836
- }
837
- const conditionFieldDef = entity.fields[conditionField];
838
- if (conditionFieldDef?.type === "select" || conditionFieldDef?.type === "multiSelect") {
839
- const conditionOptions = conditionFieldDef.options;
840
- for (const value of conditionComparisonValues(rule.when)) {
841
- if (typeof value !== "string" || !conditionOptions.includes(value)) {
842
- throw new Error(`${where} has ${ruleLabel}.when value "${String(value)}" which is not an option of "${conditionField}" (${conditionOptions.join(", ")}).`);
843
- }
844
- }
845
- }
846
- });
847
- }
848
- }
849
- }
850
- export function validateMultiSelectFields(feature) {
851
- for (const [entityName, entity] of Object.entries(feature.entities ?? {})) {
852
- for (const [fieldName, field] of Object.entries(entity.fields)) {
853
- if (field.type !== "multiSelect")
854
- continue;
855
- if (field.options.length === 0) {
856
- throw new Error(`MultiSelect field "${fieldName}" on entity "${entityName}" in feature "${feature.name}" has empty options. Add at least one option.`);
857
- }
858
- if (field.default !== undefined) {
859
- const validOptions = new Set(field.options);
860
- for (const value of field.default) {
861
- if (!validOptions.has(value)) {
862
- throw new Error(`MultiSelect default "${value}" on "${entityName}.${fieldName}" is not a valid option. Valid: ${field.options.join(", ")}`);
863
- }
864
- }
865
- }
866
- validateCheckboxDisplayOptions(field, fieldName, entityName);
867
- }
868
- }
869
- }
870
- // --- Image variant validation ---
871
- function isPositiveInt(value) {
872
- return Number.isInteger(value) && value > 0;
873
- }
874
- // Renderers cap dimensions in practice (sharp refuses output above 0x1000000
875
- // pixels); 8192 per edge is generously above any real thumbnail/preview use
876
- // and keeps a boot-declared spec from becoming a memory-exhaustion vector.
877
- const MAX_VARIANT_EDGE_PX = 8192;
878
- // sharp's blur() accepts a sigma of 0.3..1000; anything above that throws at
879
- // render time, months after boot, on the first request for that variant.
880
- const MAX_BLUR_SIGMA = 1000;
881
- function isValidBlurRegion(region) {
882
- const { x, y, width, height } = region;
883
- return (Number.isFinite(x) &&
884
- Number.isFinite(y) &&
885
- Number.isFinite(width) &&
886
- Number.isFinite(height) &&
887
- x >= 0 &&
888
- y >= 0 &&
889
- width >= 0 &&
890
- height >= 0 &&
891
- x + width <= 1 &&
892
- y + height <= 1);
893
- }
894
- // kumiko-lint-ignore complexity-budget blur/size bounds added for boot-time DoS guard
895
- function assertValidVariantSpec(name, spec, where) {
896
- if (!VARIANT_NAME_PATTERN.test(name)) {
897
- throw new Error(`Image variant "${name}" ${where} must match ${VARIANT_NAME_PATTERN.source} — the name becomes part of a storage key and a URL segment.`);
898
- }
899
- if (spec.size !== undefined && spec.maxEdge !== undefined) {
900
- throw new Error(`Image variant "${name}" ${where} sets both "size" and "maxEdge" — pick one.`);
901
- }
902
- if (spec.size !== undefined &&
903
- !(isPositiveInt(spec.size.width) &&
904
- isPositiveInt(spec.size.height) &&
905
- spec.size.width <= MAX_VARIANT_EDGE_PX &&
906
- spec.size.height <= MAX_VARIANT_EDGE_PX)) {
907
- throw new Error(`Image variant "${name}" ${where} has an invalid "size" (${spec.size.width}x${spec.size.height}) — must be a positive integer up to ${MAX_VARIANT_EDGE_PX}px per edge.`);
908
- }
909
- if (spec.maxEdge !== undefined &&
910
- !(isPositiveInt(spec.maxEdge) && spec.maxEdge <= MAX_VARIANT_EDGE_PX)) {
911
- throw new Error(`Image variant "${name}" ${where} has an invalid "maxEdge" (${spec.maxEdge}) — must be a positive integer up to ${MAX_VARIANT_EDGE_PX}px.`);
912
- }
913
- if (spec.quality !== undefined && !(isPositiveInt(spec.quality) && spec.quality <= 100)) {
914
- throw new Error(`Image variant "${name}" ${where} has "quality" ${spec.quality} — must be an integer in 1..100.`);
915
- }
916
- if (spec.blur !== undefined &&
917
- !(Number.isFinite(spec.blur) && spec.blur > 0 && spec.blur <= MAX_BLUR_SIGMA)) {
918
- throw new Error(`Image variant "${name}" ${where} has "blur" ${spec.blur} — must be a finite number in (0, ${MAX_BLUR_SIGMA}].`);
919
- }
920
- if (spec.blurRegions !== undefined) {
921
- for (const region of spec.blurRegions) {
922
- if (!isValidBlurRegion(region)) {
923
- throw new Error(`Image variant "${name}" ${where} has an invalid "blurRegions" entry ${JSON.stringify(region)} — x/y/width/height must be within 0..1 and x+width/y+height must not exceed 1.`);
924
- }
925
- }
926
- }
927
- }
928
- // A bad spec is only visible when someone finally requests that variant —
929
- // possibly months later, in production. Catch it at boot instead.
930
- export function validateImageVariants(feature) {
931
- for (const [entityName, entity] of Object.entries(feature.entities ?? {})) {
932
- for (const [fieldName, field] of Object.entries(entity.fields)) {
933
- if (field.type !== "image" && field.type !== "images")
934
- continue;
935
- if (field.variants === undefined)
936
- continue;
937
- const where = `on "${entityName}.${fieldName}" in feature "${feature.name}"`;
938
- for (const [name, spec] of Object.entries(field.variants)) {
939
- assertValidVariantSpec(name, spec, where);
940
- }
941
- }
942
- }
943
- }
944
826
  // --- lockedWhen validation ---
945
827
  function isCiphertextAtRest(field) {
946
828
  return (("pii" in field && field.pii === true) ||
@@ -968,16 +850,24 @@ export function validateLockedWhen(feature) {
968
850
  const where = `Entity "${entityName}" in feature "${feature.name}": lockedWhen field "${lockedWhen.field}"`;
969
851
  const field = entity.fields[lockedWhen.field];
970
852
  if (!field) {
971
- throw new Error(`${where} is not a field of the entity (known: ${Object.keys(entity.fields).sort().join(", ")}).`);
853
+ throw bootRuleError(ENTITY_STRUCTURE_RULES.lockedWhenUnknownField, {
854
+ message: `${where} is not a field of the entity (known: ${Object.keys(entity.fields).sort().join(", ")}).`,
855
+ });
972
856
  }
973
857
  if (isCiphertextAtRest(field)) {
974
- throw new Error(`${where} is personal or encrypted — the lock condition is evaluated on the stored value, which is ciphertext. Use a plaintext field.`);
858
+ throw bootRuleError(ENTITY_STRUCTURE_RULES.lockedWhenCiphertextField, {
859
+ message: `${where} is personal or encrypted — the lock condition is evaluated on the stored value, which is ciphertext. Use a plaintext field.`,
860
+ });
975
861
  }
976
862
  if (field.access?.read !== undefined) {
977
- throw new Error(`${where} has a read restriction — roles that cannot read it get records without it, and the client would show every record as locked. Drop field access.read or use another field.`);
863
+ throw bootRuleError(ENTITY_STRUCTURE_RULES.lockedWhenReadRestricted, {
864
+ message: `${where} has a read restriction — roles that cannot read it get records without it, and the client would show every record as locked. Drop field access.read or use another field.`,
865
+ });
978
866
  }
979
867
  if (!LOCKABLE_FIELD_TYPES.has(field.type)) {
980
- throw new Error(`${where} has type "${field.type}", which does not store a plain scalar the condition can compare. Use a text, select, boolean, number or reference field.`);
868
+ throw bootRuleError(FIELD_CONDITION_RULES.conditionFieldTypeNotComparable, {
869
+ message: `${where} has type "${field.type}", which does not store a plain scalar the condition can compare. Use a text, select, boolean, number or reference field.`,
870
+ });
981
871
  }
982
872
  }
983
873
  }
@@ -989,20 +879,28 @@ export function validateTransitions(feature) {
989
879
  for (const [fieldName, transitionMap] of Object.entries(entity.transitions)) {
990
880
  const field = entity.fields[fieldName];
991
881
  if (!field) {
992
- throw new Error(`Transitions defined for unknown field "${fieldName}" on entity "${entityName}" in feature "${feature.name}"`);
882
+ throw bootRuleError(ENTITY_STRUCTURE_RULES.transitionUnknownField, {
883
+ message: `Transitions defined for unknown field "${fieldName}" on entity "${entityName}" in feature "${feature.name}"`,
884
+ });
993
885
  }
994
886
  if (field.type !== "select") {
995
- throw new Error(`Transitions defined for field "${fieldName}" on entity "${entityName}" but field type is "${field.type}" (must be "select")`);
887
+ throw bootRuleError(ENTITY_STRUCTURE_RULES.transitionFieldNotSelect, {
888
+ message: `Transitions defined for field "${fieldName}" on entity "${entityName}" but field type is "${field.type}" (must be "select")`,
889
+ });
996
890
  }
997
891
  const validOptions = new Set(field.options);
998
892
  // Check all states in the transition map
999
893
  for (const [from, targets] of Object.entries(transitionMap)) {
1000
894
  if (!validOptions.has(from)) {
1001
- throw new Error(`Transition state "${from}" on "${entityName}.${fieldName}" is not a valid option. Valid: ${[...validOptions].join(", ")}`);
895
+ throw bootRuleError(ENTITY_STRUCTURE_RULES.transitionStateNotOption, {
896
+ message: `Transition state "${from}" on "${entityName}.${fieldName}" is not a valid option. Valid: ${[...validOptions].join(", ")}`,
897
+ });
1002
898
  }
1003
899
  for (const to of targets) {
1004
900
  if (!validOptions.has(to)) {
1005
- throw new Error(`Transition target "${to}" (from "${from}") on "${entityName}.${fieldName}" is not a valid option. Valid: ${[...validOptions].join(", ")}`);
901
+ throw bootRuleError(ENTITY_STRUCTURE_RULES.transitionTargetNotOption, {
902
+ message: `Transition target "${to}" (from "${from}") on "${entityName}.${fieldName}" is not a valid option. Valid: ${[...validOptions].join(", ")}`,
903
+ });
1006
904
  }
1007
905
  }
1008
906
  }
@@ -1020,7 +918,9 @@ export function validateExtendSchemaCollisions(feature) {
1020
918
  const extraFields = ext.extendSchema(entityName);
1021
919
  for (const fieldName of Object.keys(extraFields)) {
1022
920
  if (existingFields.has(fieldName)) {
1023
- throw new Error(`extendSchema column "${fieldName}" conflicts with existing field on entity "${entityName}". Rename the extension column or the entity field.`);
921
+ throw bootRuleError(ENTITY_STRUCTURE_RULES.extendSchemaCollision, {
922
+ message: `extendSchema column "${fieldName}" conflicts with existing field on entity "${entityName}". Rename the extension column or the entity field.`,
923
+ });
1024
924
  }
1025
925
  }
1026
926
  }
@@ -1040,8 +940,10 @@ export function validateDerivedFieldCollisions(feature) {
1040
940
  const fieldNames = new Set(Object.keys(entity.fields));
1041
941
  for (const derivedName of Object.keys(entity.derivedFields)) {
1042
942
  if (fieldNames.has(derivedName)) {
1043
- throw new Error(`Entity "${entityName}": derivedFields key "${derivedName}" conflicts with a stored ` +
1044
- `field of the same name — the derived value would silently overwrite the real one on every read. Rename the derivedFields key or the stored field.`);
943
+ throw bootRuleError(ENTITY_STRUCTURE_RULES.derivedFieldCollision, {
944
+ message: `Entity "${entityName}": derivedFields key "${derivedName}" conflicts with a stored ` +
945
+ `field of the same name — the derived value would silently overwrite the real one on every read. Rename the derivedFields key or the stored field.`,
946
+ });
1045
947
  }
1046
948
  }
1047
949
  }
@@ -1058,9 +960,11 @@ function isUnrestrictedReadAccess(access) {
1058
960
  return Array.isArray(readAccess) ? readAccess.length === 0 : Object.keys(readAccess).length === 0;
1059
961
  }
1060
962
  function throwSearchableRestricted(subject, entityName) {
1061
- throw new Error(`${subject} on entity "${entityName}" cannot be searchable with a restricted ` +
1062
- "access.read — the search index is not filtered per role, so search matches would leak " +
1063
- 'the value to roles that cannot read it. Drop `searchable`/`find: "fuzzy"` or `access.read`.');
963
+ throw bootRuleError(ENTITY_STRUCTURE_RULES.searchableRestrictedRead, {
964
+ message: `${subject} on entity "${entityName}" cannot be searchable with a restricted ` +
965
+ "access.read — the search index is not filtered per role, so search matches would leak " +
966
+ 'the value to roles that cannot read it. Drop `searchable`/`find: "fuzzy"` or `access.read`.',
967
+ });
1064
968
  }
1065
969
  export function validateSearchableFieldReadAccess(feature) {
1066
970
  for (const [entityName, entity] of Object.entries(feature.entities ?? {})) {