adula 2.1.0 → 2.2.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 (214) hide show
  1. package/README.md +149 -18
  2. package/build/agent/AGENTS.template.md +4 -4
  3. package/build/agent/capabilities.md +22 -11
  4. package/build/agent/skills/adula-frontend-design/SKILL.md +1 -1
  5. package/build/agent/skills/idea-review/SKILL.md +2 -2
  6. package/build/commands/adula_outbox.d.ts +10 -0
  7. package/build/commands/adula_outbox.js +11 -0
  8. package/build/commands/adula_restore_reconcile.d.ts +10 -0
  9. package/build/commands/adula_restore_reconcile.js +34 -0
  10. package/build/commands/adula_runtime_health.d.ts +10 -0
  11. package/build/commands/adula_runtime_health.js +27 -0
  12. package/build/commands/adula_uploads_prune.d.ts +10 -0
  13. package/build/commands/adula_uploads_prune.js +16 -0
  14. package/build/commands/app.d.ts +10 -0
  15. package/build/commands/app.js +64 -0
  16. package/build/commands/backup_create.d.ts +11 -0
  17. package/build/commands/backup_create.js +99 -0
  18. package/build/commands/backup_restore_files.d.ts +11 -0
  19. package/build/commands/backup_restore_files.js +44 -0
  20. package/build/commands/backup_restore_test.d.ts +12 -0
  21. package/build/commands/backup_restore_test.js +185 -0
  22. package/build/commands/backup_services.d.ts +31 -0
  23. package/build/commands/backup_services.js +6 -0
  24. package/build/commands/backup_verify.d.ts +9 -0
  25. package/build/commands/backup_verify.js +59 -0
  26. package/build/commands/backup_verify_snapshot.d.ts +10 -0
  27. package/build/commands/backup_verify_snapshot.js +37 -0
  28. package/build/commands/client.d.ts +16 -0
  29. package/build/commands/client.js +71 -0
  30. package/build/commands/doctor.js +4 -1
  31. package/build/commands/install.d.ts +8 -0
  32. package/build/commands/install.js +63 -45
  33. package/build/commands/main.d.ts +3 -2
  34. package/build/commands/main.js +26 -0
  35. package/build/commands/module_add.js +4 -20
  36. package/build/commands/resource.d.ts +2 -0
  37. package/build/commands/resource.js +12 -3
  38. package/build/commands/resource_migration.d.ts +15 -0
  39. package/build/commands/resource_migration.js +72 -0
  40. package/build/commands/resource_snapshot.d.ts +2 -0
  41. package/build/commands/resource_snapshot.js +3 -0
  42. package/build/commands/sla_evaluate.d.ts +14 -0
  43. package/build/commands/sla_evaluate.js +16 -0
  44. package/build/commands/ui.js +4 -2
  45. package/build/commands/ui_css.d.ts +9 -0
  46. package/build/commands/ui_css.js +19 -0
  47. package/build/commands/upgrade.d.ts +1 -1
  48. package/build/commands/upgrade.js +1 -1
  49. package/build/configure.js +1 -1
  50. package/build/database/migrations/1770000000020_two_factor.d.ts +5 -0
  51. package/build/database/migrations/1770000000020_two_factor.js +10 -0
  52. package/build/database/migrations/1770000000041_import_modes.d.ts +5 -0
  53. package/build/database/migrations/1770000000041_import_modes.js +10 -0
  54. package/build/database/migrations/1770000000042_sync_jobs.d.ts +5 -0
  55. package/build/database/migrations/1770000000042_sync_jobs.js +10 -0
  56. package/build/database/migrations/1770000000043_notification_channels.d.ts +5 -0
  57. package/build/database/migrations/1770000000043_notification_channels.js +10 -0
  58. package/build/database/migrations/1770000000044_channel_confirmations.d.ts +5 -0
  59. package/build/database/migrations/1770000000044_channel_confirmations.js +10 -0
  60. package/build/database/migrations/1770000000045_import_leases.d.ts +5 -0
  61. package/build/database/migrations/1770000000045_import_leases.js +10 -0
  62. package/build/database/migrations/1770000000046_workflow_delegation_sla.d.ts +5 -0
  63. package/build/database/migrations/1770000000046_workflow_delegation_sla.js +10 -0
  64. package/build/database/migrations/1770000000049_print_templates.d.ts +5 -0
  65. package/build/database/migrations/1770000000049_print_templates.js +10 -0
  66. package/build/index.d.ts +56 -10
  67. package/build/index.js +34 -6
  68. package/build/providers/adula_provider.d.ts +2 -0
  69. package/build/providers/adula_provider.js +7 -0
  70. package/build/src/admin/contracts.js +1 -1
  71. package/build/src/admin/controller.d.ts +14 -1
  72. package/build/src/admin/controller.js +77 -13
  73. package/build/src/admin/errors.d.ts +32 -0
  74. package/build/src/admin/errors.js +63 -1
  75. package/build/src/admin/presentation.d.ts +21 -2
  76. package/build/src/admin/resource/editor.d.ts +59 -0
  77. package/build/src/admin/resource/editor.js +323 -0
  78. package/build/src/admin/resource/export.d.ts +37 -0
  79. package/build/src/admin/resource/export.js +181 -0
  80. package/build/src/admin/resource/lifecycle.d.ts +21 -0
  81. package/build/src/admin/resource/lifecycle.js +91 -0
  82. package/build/src/admin/resource/query.d.ts +100 -0
  83. package/build/src/admin/resource/query.js +508 -0
  84. package/build/src/admin/resource/read.d.ts +106 -0
  85. package/build/src/admin/resource/read.js +327 -0
  86. package/build/src/admin/resource/shared.d.ts +77 -0
  87. package/build/src/admin/resource/shared.js +222 -0
  88. package/build/src/admin/resource/trash.d.ts +10 -0
  89. package/build/src/admin/resource/trash.js +56 -0
  90. package/build/src/admin/resource/write.d.ts +57 -0
  91. package/build/src/admin/resource/write.js +574 -0
  92. package/build/src/admin/resource_service.d.ts +66 -193
  93. package/build/src/admin/resource_service.js +69 -1345
  94. package/build/src/attachments/attachment_service.d.ts +46 -2
  95. package/build/src/attachments/attachment_service.js +96 -4
  96. package/build/src/auth/conditions.d.ts +5 -0
  97. package/build/src/auth/conditions.js +26 -3
  98. package/build/src/auth/sql.js +17 -5
  99. package/build/src/auth/two_factor.d.ts +96 -0
  100. package/build/src/auth/two_factor.js +259 -0
  101. package/build/src/collaboration/assignments.d.ts +36 -1
  102. package/build/src/collaboration/assignments.js +132 -66
  103. package/build/src/collaboration/record_collaboration.d.ts +2 -3
  104. package/build/src/collaboration/record_collaboration.js +19 -16
  105. package/build/src/collaboration/shared.d.ts +16 -0
  106. package/build/src/collaboration/shared.js +21 -0
  107. package/build/src/commands/app_scaffold.d.ts +72 -0
  108. package/build/src/commands/app_scaffold.js +285 -0
  109. package/build/src/commands/capabilities.js +34 -8
  110. package/build/src/commands/doctor.d.ts +14 -2
  111. package/build/src/commands/doctor.js +50 -5
  112. package/build/src/commands/gap_report.d.ts +1 -1
  113. package/build/src/commands/gap_report.js +2 -2
  114. package/build/src/commands/generator.d.ts +37 -1
  115. package/build/src/commands/generator.js +61 -18
  116. package/build/src/commands/snapshot.d.ts +10 -13
  117. package/build/src/commands/snapshot.js +31 -14
  118. package/build/src/commands/source_markers.d.ts +10 -0
  119. package/build/src/commands/source_markers.js +29 -0
  120. package/build/src/core/activity.d.ts +2 -0
  121. package/build/src/core/activity.js +7 -1
  122. package/build/src/core/administrators.d.ts +38 -0
  123. package/build/src/core/administrators.js +129 -0
  124. package/build/src/core/html_sanitizer.d.ts +20 -0
  125. package/build/src/core/html_sanitizer.js +261 -0
  126. package/build/src/core/like.d.ts +5 -0
  127. package/build/src/core/like.js +5 -0
  128. package/build/src/core/lookups.d.ts +80 -0
  129. package/build/src/core/lookups.js +319 -0
  130. package/build/src/core/message_templates.d.ts +7 -2
  131. package/build/src/core/message_templates.js +72 -11
  132. package/build/src/core/module_seed.js +2 -1
  133. package/build/src/core/notification_channels.d.ts +235 -0
  134. package/build/src/core/notification_channels.js +660 -0
  135. package/build/src/core/roles.js +2 -2
  136. package/build/src/core/saved_views.d.ts +8 -1
  137. package/build/src/core/saved_views.js +36 -2
  138. package/build/src/core/sequences.d.ts +32 -0
  139. package/build/src/core/sequences.js +97 -0
  140. package/build/src/core/settings.d.ts +5 -0
  141. package/build/src/core/settings.js +19 -2
  142. package/build/src/core/template_language.d.ts +61 -0
  143. package/build/src/core/template_language.js +141 -0
  144. package/build/src/core/ui_preferences.d.ts +4 -0
  145. package/build/src/core/ui_preferences.js +4 -1
  146. package/build/src/core/user_invitations.d.ts +5 -1
  147. package/build/src/core/user_invitations.js +7 -1
  148. package/build/src/core/users.js +1 -1
  149. package/build/src/database/calendar_days.d.ts +19 -0
  150. package/build/src/database/calendar_days.js +36 -0
  151. package/build/src/database/schema.d.ts +155 -2
  152. package/build/src/database/schema.js +531 -59
  153. package/build/src/database/schema_diff.d.ts +56 -0
  154. package/build/src/database/schema_diff.js +157 -0
  155. package/build/src/events/record_mutation.d.ts +2 -1
  156. package/build/src/events/record_mutation.js +1 -0
  157. package/build/src/integrations/api_client.d.ts +37 -0
  158. package/build/src/integrations/api_client.js +552 -0
  159. package/build/src/integrations/import_adapters.d.ts +37 -0
  160. package/build/src/integrations/import_adapters.js +35 -0
  161. package/build/src/integrations/imports.d.ts +118 -16
  162. package/build/src/integrations/imports.js +406 -73
  163. package/build/src/integrations/openapi.d.ts +3 -1
  164. package/build/src/integrations/openapi.js +454 -31
  165. package/build/src/integrations/outbound.d.ts +51 -0
  166. package/build/src/integrations/outbound.js +195 -0
  167. package/build/src/integrations/print.d.ts +21 -1
  168. package/build/src/integrations/print.js +63 -21
  169. package/build/src/integrations/print_templates.d.ts +216 -0
  170. package/build/src/integrations/print_templates.js +1015 -0
  171. package/build/src/integrations/sync_jobs.d.ts +139 -0
  172. package/build/src/integrations/sync_jobs.js +416 -0
  173. package/build/src/integrations/webhooks.d.ts +12 -12
  174. package/build/src/integrations/webhooks.js +34 -43
  175. package/build/src/languages/ar.d.ts +11 -0
  176. package/build/src/languages/ar.js +336 -0
  177. package/build/src/languages/ar_ui.d.ts +332 -0
  178. package/build/src/languages/ar_ui.js +333 -0
  179. package/build/src/languages/catalog.d.ts +66 -0
  180. package/build/src/languages/catalog.js +152 -0
  181. package/build/src/languages/en.d.ts +7 -0
  182. package/build/src/languages/en.js +330 -0
  183. package/build/src/languages/en_ui.d.ts +3 -0
  184. package/build/src/languages/en_ui.js +328 -0
  185. package/build/src/languages/validation.d.ts +26 -0
  186. package/build/src/languages/validation.js +60 -0
  187. package/build/src/lists/bulk_actions.d.ts +89 -0
  188. package/build/src/lists/bulk_actions.js +268 -0
  189. package/build/src/lists/dashboards.d.ts +96 -0
  190. package/build/src/lists/dashboards.js +241 -0
  191. package/build/src/mcp/tools.js +1 -1
  192. package/build/src/resource/define_resource.d.ts +18 -1
  193. package/build/src/resource/define_resource.js +205 -18
  194. package/build/src/resource/definition.d.ts +44 -0
  195. package/build/src/resource/definition.js +171 -0
  196. package/build/src/resource/registry.js +15 -4
  197. package/build/src/resource/types.d.ts +304 -16
  198. package/build/src/resource/values.d.ts +56 -1
  199. package/build/src/resource/values.js +237 -5
  200. package/build/src/services/settings.d.ts +2 -0
  201. package/build/src/services/settings.js +5 -1
  202. package/build/src/upgrade/legacy.js +2 -2
  203. package/build/src/workflows/calendar.d.ts +9 -0
  204. package/build/src/workflows/calendar.js +44 -0
  205. package/build/src/workflows/define_workflow.d.ts +48 -3
  206. package/build/src/workflows/define_workflow.js +57 -13
  207. package/build/src/workflows/delegations.d.ts +93 -0
  208. package/build/src/workflows/delegations.js +287 -0
  209. package/build/src/workflows/engine.d.ts +69 -4
  210. package/build/src/workflows/engine.js +441 -83
  211. package/build/src/workflows/sla.d.ts +15 -0
  212. package/build/src/workflows/sla.js +8 -0
  213. package/build/stubs/resource_contract.txt +12 -1
  214. package/package.json +5 -2
@@ -1,7 +1,12 @@
1
1
  import { assertTitle } from '../admin/record_title.js';
2
+ import { MULTIPLE_ATTACHMENT_MAX, decimalShape, fieldValue, isMultipleAttachment, } from './values.js';
3
+ import { assertPrintTemplates } from '../integrations/print_templates.js';
2
4
  export function identifier(value) {
3
5
  if (!/^[a-z][a-z0-9_]*$/.test(value))
4
6
  throw new Error(`Unsafe SQL identifier: ${value}`);
7
+ // PostgreSQL silently truncates longer names, so two distinct names could collide.
8
+ if (value.length > 63)
9
+ throw new Error(`SQL identifier longer than 63 bytes (PostgreSQL limit): ${value}`);
5
10
  return value;
6
11
  }
7
12
  const columns = new Map();
@@ -15,33 +20,194 @@ export function columnName(name) {
15
20
  columns.set(name, column);
16
21
  return column;
17
22
  }
23
+ /**
24
+ * The join table of a manyToMany field: `table`, or `<owner>_<key in snake_case>`. Its
25
+ * columns are `<owner>_id` and `<target>_id` (`related_id` when a resource links itself).
26
+ */
27
+ export function joinTable(owner, key, field) {
28
+ return {
29
+ table: identifier(field.table ?? `${owner}_${columnName(key)}`),
30
+ owner: identifier(`${owner}_id`),
31
+ target: field.resource === owner ? 'related_id' : identifier(`${field.resource}_id`),
32
+ };
33
+ }
34
+ /**
35
+ * Arabic is required; every other language is optional, but a language a label
36
+ * names must have text (an empty `en: ''` is a mistake, not an omission).
37
+ */
38
+ export function assertLabel(label, context) {
39
+ if (!label || typeof label.ar !== 'string' || !label.ar.trim())
40
+ throw new Error(`${context} needs Arabic text`);
41
+ for (const [language, text] of Object.entries(label))
42
+ if (typeof text !== 'string' || !text.trim())
43
+ throw new Error(`${context} needs Arabic text; ${language} is optional but cannot be empty`);
44
+ }
45
+ const RESERVED = [
46
+ 'id',
47
+ 'orgUnitId',
48
+ 'createdBy',
49
+ 'updatedBy',
50
+ 'createdAt',
51
+ 'updatedAt',
52
+ 'deletedAt',
53
+ 'version',
54
+ 'docStatus',
55
+ 'amendedFromId',
56
+ ];
57
+ /** Types whose value is not a single column: they cannot be sorted, searched or unique. */
58
+ const COLLECTIONS = ['hasMany', 'manyToMany', 'multiSelect'];
59
+ const TEXT_TYPES = ['string', 'text', 'email', 'url', 'phone'];
60
+ const NUMBER_TYPES = ['integer', 'money', 'decimal', 'percent'];
61
+ /** Types that cannot declare a default: ids differ between deployments, files are uploads. */
62
+ const NO_DEFAULT = ['hasMany', 'manyToMany', 'belongsTo', 'user', 'attachment', 'json'];
63
+ const isCount = (value) => Number.isSafeInteger(value) && Number(value) >= 0;
64
+ /** Constraint, option, default and visibility props of one field, checked at definition time. */
65
+ function assertFieldProps(name, key, field, fields) {
66
+ const context = `${name}.${key}`;
67
+ const raw = field;
68
+ if (TEXT_TYPES.includes(field.type)) {
69
+ for (const bound of ['min', 'max'])
70
+ if (raw[bound] !== undefined && !isCount(raw[bound]))
71
+ throw new Error(`${context}: ${bound} must be a non-negative integer length`);
72
+ if (raw.pattern !== undefined) {
73
+ if (typeof raw.pattern !== 'string')
74
+ throw new Error(`${context}: pattern must be a string`);
75
+ try {
76
+ new RegExp(raw.pattern);
77
+ }
78
+ catch {
79
+ throw new Error(`${context}: pattern is not a valid regular expression`);
80
+ }
81
+ }
82
+ if (raw.format !== undefined && !['email', 'url', 'phone'].includes(String(raw.format)))
83
+ throw new Error(`${context}: format must be email, url or phone`);
84
+ }
85
+ if (field.type === 'decimal' || field.type === 'percent') {
86
+ const { precision, scale } = decimalShape(field);
87
+ if (!Number.isSafeInteger(precision) || precision < 1 || precision > 1000)
88
+ throw new Error(`${context}: precision must be an integer from 1 to 1000`);
89
+ if (!Number.isSafeInteger(scale) || scale < 0 || scale > precision)
90
+ throw new Error(`${context}: scale must be an integer from 0 to precision`);
91
+ }
92
+ if (NUMBER_TYPES.includes(field.type))
93
+ for (const bound of ['min', 'max'])
94
+ if (raw[bound] !== undefined)
95
+ try {
96
+ fieldValue({ ...field, min: undefined, max: undefined }, raw[bound]);
97
+ }
98
+ catch {
99
+ throw new Error(`${context}: ${bound} must be a valid ${field.type} value`);
100
+ }
101
+ if (field.type === 'enum' || field.type === 'multiSelect') {
102
+ if (!Array.isArray(field.options) || !field.options.length)
103
+ throw new Error(`${context}: options must list at least one choice`);
104
+ const values = new Set();
105
+ for (const option of field.options) {
106
+ if (typeof option?.value !== 'string' || !option.value || option.value.length > 255)
107
+ throw new Error(`${context}: option values must be non-empty strings (255 at most)`);
108
+ if (values.has(option.value))
109
+ throw new Error(`${context}: duplicate option ${option.value}`);
110
+ values.add(option.value);
111
+ assertLabel(option.label, `${context}: option ${option.value}`);
112
+ }
113
+ if (field.type === 'multiSelect')
114
+ for (const bound of ['min', 'max'])
115
+ if (field[bound] !== undefined && !isCount(field[bound]))
116
+ throw new Error(`${context}: ${bound} must be a non-negative integer count`);
117
+ }
118
+ if (field.type === 'manyToMany') {
119
+ identifier(field.resource);
120
+ // Required means at least one linked record; persist() checks it.
121
+ joinTable(name, key, field);
122
+ }
123
+ if (field.type === 'attachment') {
124
+ if (raw.multiple !== undefined && typeof raw.multiple !== 'boolean')
125
+ throw new Error(`${context}: multiple must be true or false`);
126
+ if (raw.max !== undefined) {
127
+ if (!field.multiple)
128
+ throw new Error(`${context}: max needs multiple: true`);
129
+ if (!Number.isSafeInteger(raw.max) ||
130
+ Number(raw.max) < 1 ||
131
+ Number(raw.max) > MULTIPLE_ATTACHMENT_MAX)
132
+ throw new Error(`${context}: max must be an integer from 1 to ${MULTIPLE_ATTACHMENT_MAX} files`);
133
+ }
134
+ }
135
+ if (COLLECTIONS.includes(field.type) || isMultipleAttachment(field))
136
+ for (const flag of ['sortable', 'searchable', 'unique'])
137
+ if (field[flag])
138
+ throw new Error(`${context}: ${field.type} fields cannot be ${flag}`);
139
+ if (field.searchable &&
140
+ !['string', 'text', 'email', 'url', 'phone', 'enum', 'lookup'].includes(field.type))
141
+ throw new Error(`${context}: only text fields can be searchable`);
142
+ if (field.default !== undefined) {
143
+ if (NO_DEFAULT.includes(field.type) || field.sequence)
144
+ throw new Error(`${context}: ${field.type} fields cannot declare a default`);
145
+ if (Array.isArray(field.default) !== (field.type === 'multiSelect'))
146
+ throw new Error(`${context}: only multiSelect defaults are arrays`);
147
+ if (field.default !== null)
148
+ try {
149
+ const stored = fieldValue(field, field.default);
150
+ if (field.type !== 'multiSelect' && stored !== field.default)
151
+ throw new Error('not canonical');
152
+ }
153
+ catch {
154
+ throw new Error(`${context}: the default is not a valid canonical ${field.type} value`);
155
+ }
156
+ }
157
+ if (field.visibleWhen !== undefined) {
158
+ if (!field.visibleWhen ||
159
+ typeof field.visibleWhen !== 'object' ||
160
+ Array.isArray(field.visibleWhen))
161
+ throw new Error(`${context}: visibleWhen must map sibling fields to values`);
162
+ for (const [sibling, expected] of Object.entries(field.visibleWhen)) {
163
+ const controller = fields[sibling];
164
+ if (!controller || sibling === key)
165
+ throw new Error(`${context}: visibleWhen names unknown field ${sibling}`);
166
+ if (['hasMany', 'manyToMany', 'json', 'attachment'].includes(controller.type))
167
+ throw new Error(`${context}: visibleWhen cannot depend on ${controller.type} ${sibling}`);
168
+ for (const value of Array.isArray(expected) ? expected : [expected]) {
169
+ if (value === null)
170
+ continue;
171
+ if (!['string', 'number', 'boolean'].includes(typeof value))
172
+ throw new Error(`${context}: visibleWhen values must be scalars`);
173
+ // Each value is a canonical value of the controlling field (an option of an
174
+ // enum or multiSelect), so the rule compares stored values exactly.
175
+ let stored;
176
+ try {
177
+ stored =
178
+ controller.type === 'multiSelect'
179
+ ? fieldValue({ ...controller, min: undefined, max: undefined }, [
180
+ value,
181
+ ])[0]
182
+ : fieldValue({ ...controller, min: undefined, max: undefined }, value);
183
+ }
184
+ catch {
185
+ throw new Error(`${context}: visibleWhen ${sibling} = ${JSON.stringify(value)} is not a valid ${controller.type} value`);
186
+ }
187
+ if (stored !== value)
188
+ throw new Error(`${context}: visibleWhen ${sibling} must use the canonical value ${JSON.stringify(stored)}`);
189
+ }
190
+ }
191
+ }
192
+ }
18
193
  export function defineResource(input) {
19
194
  identifier(input.name);
195
+ if ('customFields' in input)
196
+ throw new Error(`${input.name}: the customFields option was removed (nothing read or wrote the column). ` +
197
+ 'Delete it from the definition; an existing custom_fields column is left untouched.');
20
198
  if (typeof input.scoped !== 'boolean')
21
199
  throw new Error(`${input.name}: scoped must be explicit`);
22
- if (!input.label.ar || !input.label.en)
23
- throw new Error('Bilingual labels are required');
200
+ assertLabel(input.label, `${input.name}: label`);
24
201
  for (const optional of [input.recordLabel, input.createLabel])
25
- if (optional && (!optional.ar || !optional.en))
26
- throw new Error(`${input.name}: recordLabel and createLabel need Arabic and English`);
202
+ if (optional)
203
+ assertLabel(optional, `${input.name}: recordLabel and createLabel`);
27
204
  for (const [key, field] of Object.entries(input.fields)) {
28
205
  columnName(key);
29
206
  identifier(field.column ?? columnName(key));
30
- if ([
31
- 'id',
32
- 'orgUnitId',
33
- 'createdBy',
34
- 'updatedBy',
35
- 'createdAt',
36
- 'updatedAt',
37
- 'deletedAt',
38
- 'version',
39
- 'docStatus',
40
- 'amendedFromId',
41
- ].includes(key))
207
+ if (RESERVED.includes(key))
42
208
  throw new Error(`Reserved field: ${key}`);
43
- if (!field.label.ar || !field.label.en)
44
- throw new Error(`${key}: bilingual labels are required`);
209
+ assertLabel(field.label, `${key}: label`);
210
+ assertFieldProps(input.name, key, field, input.fields);
45
211
  }
46
212
  for (const keys of [
47
213
  input.list,
@@ -54,6 +220,26 @@ export function defineResource(input) {
54
220
  if (!(key in input.fields))
55
221
  throw new Error(`Unknown field: ${key}`);
56
222
  }
223
+ for (const keys of input.unique ?? []) {
224
+ if (!Array.isArray(keys) || keys.length < 2 || new Set(keys).size !== keys.length)
225
+ throw new Error(`${input.name}: each unique combination needs two or more distinct fields`);
226
+ for (const key of keys) {
227
+ if (key === 'orgUnitId' && input.scoped)
228
+ continue;
229
+ const field = input.fields[key];
230
+ if (!field ||
231
+ COLLECTIONS.includes(field.type) ||
232
+ field.type === 'json' ||
233
+ isMultipleAttachment(field))
234
+ throw new Error(`${input.name}: unique combination names unknown or unstored field ${key}`);
235
+ }
236
+ const columnsOf = keys.map((key) => key === 'orgUnitId'
237
+ ? 'org_unit_id'
238
+ : (input.fields[key].column ?? columnName(key)));
239
+ const index = `${input.name}_${columnsOf.join('_')}_active_unique`;
240
+ if (index.length > 63)
241
+ throw new Error(`${input.name}: the unique index name ${index} is longer than 63 bytes (PostgreSQL limit); shorten the resource name or the field columns`);
242
+ }
57
243
  if (input.scope) {
58
244
  const parent = input.fields[input.scope.from];
59
245
  if (!input.scoped)
@@ -62,6 +248,7 @@ export function defineResource(input) {
62
248
  throw new Error(`${input.name}: scope.from must name a required belongsTo field`);
63
249
  }
64
250
  assertTitle(input);
251
+ assertPrintTemplates(input);
65
252
  if (!input.submittable && input.actions.some((a) => ['submit', 'cancel', 'amend'].includes(a)))
66
253
  throw new Error('Document actions require submittable');
67
254
  return Object.freeze({ ...input, version: input.version ?? input.submittable ?? false });
@@ -0,0 +1,44 @@
1
+ import type { SchemaTypes } from '@vinejs/vine/types';
2
+ import type { RecordData, Resource } from './types.js';
3
+ /**
4
+ * Runs fieldValue as a VineJS rule: the value becomes its stored representation and a
5
+ * constraint violation is reported under its catalog rule, so messages follow the
6
+ * application's messages provider (see installCatalogMessages).
7
+ */
8
+ /** Types whose blank string means "no value". */
9
+ export declare const TEXT_LIKE: string[];
10
+ /**
11
+ * The VineJS object properties derived from a resource's form fields (inline children
12
+ * and sequences excluded). Applications extend it instead of restating the fields:
13
+ * `vine.create(vine.object({ ...definitionSchema(resource), extra: vine.string() }))`.
14
+ * A required field is optional while it has a default or depends on `visibleWhen`:
15
+ * the server applies the default and enforces `required` once visibility is known.
16
+ */
17
+ export declare function definitionSchema(resource: Pick<Resource, 'fields' | 'form'>): Record<string, SchemaTypes>;
18
+ /**
19
+ * The validator persist() uses for a resource without its own `validator`, compiled
20
+ * once per definition. It picks up the VineJS messages provider installed when it is
21
+ * first used, so catalog messages apply.
22
+ */
23
+ export declare function definitionValidator(resource: Pick<Resource, 'fields' | 'form'>): {
24
+ validate(data: unknown): Promise<RecordData>;
25
+ };
26
+ /** The validator of a write: the resource's own, or the derived one. */
27
+ export declare function resourceValidator(resource: Resource): {
28
+ validate(data: unknown): Promise<RecordData>;
29
+ };
30
+ /** Whether a field applies to a (prospective) record; see Field.visibleWhen. */
31
+ export declare function isVisible(resource: Pick<Resource, 'fields'>, key: string, record: RecordData): boolean;
32
+ /**
33
+ * Clears every field that does not apply to the record (null, or an empty list for
34
+ * manyToMany), repeating until stable so a field depending on a hidden field is hidden
35
+ * too. Returns the hidden keys.
36
+ */
37
+ export declare function applyVisibility(resource: Pick<Resource, 'fields'>, record: RecordData, options?: {
38
+ /** The stored record of an update. */
39
+ existing?: RecordData;
40
+ /** Whether the writer may write a field; a hidden field it may not write keeps `existing`. */
41
+ writable?: (key: string) => boolean;
42
+ }): Set<string>;
43
+ /** Declared defaults for the stored fields a create input leaves out. */
44
+ export declare function missingDefaults(resource: Pick<Resource, 'fields'>, input: RecordData): RecordData;
@@ -0,0 +1,171 @@
1
+ import vine from '@vinejs/vine';
2
+ import { FieldValueError, fieldValue } from './values.js';
3
+ import { currentLanguage, translate } from '../languages/catalog.js';
4
+ /**
5
+ * Runs fieldValue as a VineJS rule: the value becomes its stored representation and a
6
+ * constraint violation is reported under its catalog rule, so messages follow the
7
+ * application's messages provider (see installCatalogMessages).
8
+ */
9
+ /** Types whose blank string means "no value". */
10
+ export const TEXT_LIKE = ['string', 'text', 'email', 'url', 'phone'];
11
+ const definitionRule = vine.createRule((value, { field: definition }, field) => {
12
+ if (!field.isValid)
13
+ return;
14
+ // A blank text-like value is no value: required fields refuse it, others store null.
15
+ if (TEXT_LIKE.includes(definition.type) && typeof value === 'string' && !value.trim()) {
16
+ if (definition.required && definition.visibleWhen === undefined)
17
+ field.report(translate('validation.required', currentLanguage()), 'required', field);
18
+ else
19
+ field.mutate(null, field);
20
+ return;
21
+ }
22
+ try {
23
+ field.mutate(fieldValue(definition, value), field);
24
+ }
25
+ catch (error) {
26
+ if (error instanceof FieldValueError)
27
+ field.report(error.message, error.rule, field, error.params);
28
+ else
29
+ field.report(translate('validation.invalid', currentLanguage()), 'invalid', field);
30
+ }
31
+ }, { name: 'adulaField' });
32
+ /** The base VineJS type of one stored field; constraints are applied by definitionRule. */
33
+ function baseSchema(field) {
34
+ switch (field.type) {
35
+ case 'string':
36
+ case 'email':
37
+ case 'url':
38
+ case 'phone':
39
+ // Length, pattern and format follow in definitionRule (TEXT_LIMITS included).
40
+ return vine.string().trim();
41
+ case 'text':
42
+ case 'lookup':
43
+ case 'enum':
44
+ case 'date':
45
+ return vine.string();
46
+ case 'attachment':
47
+ return field.multiple
48
+ ? vine.array(vine.number().withoutDecimals())
49
+ : vine.number().withoutDecimals();
50
+ case 'integer':
51
+ case 'belongsTo':
52
+ case 'user':
53
+ return vine.number().withoutDecimals();
54
+ case 'boolean':
55
+ return vine.boolean();
56
+ case 'multiSelect':
57
+ return vine.array(vine.string());
58
+ case 'manyToMany':
59
+ return vine.array(vine.number().withoutDecimals());
60
+ default:
61
+ // money, decimal, percent (numbers or numeric strings), datetime (string or Date), json.
62
+ return vine.any();
63
+ }
64
+ }
65
+ /**
66
+ * The VineJS object properties derived from a resource's form fields (inline children
67
+ * and sequences excluded). Applications extend it instead of restating the fields:
68
+ * `vine.create(vine.object({ ...definitionSchema(resource), extra: vine.string() }))`.
69
+ * A required field is optional while it has a default or depends on `visibleWhen`:
70
+ * the server applies the default and enforces `required` once visibility is known.
71
+ */
72
+ export function definitionSchema(resource) {
73
+ const properties = {};
74
+ for (const key of resource.form) {
75
+ const field = resource.fields[key];
76
+ if (!field || field.type === 'hasMany' || field.sequence)
77
+ continue;
78
+ const schema = baseSchema(field).use(definitionRule({ field }));
79
+ properties[key] =
80
+ field.required && field.visibleWhen === undefined && field.default === undefined
81
+ ? schema
82
+ : schema.nullable().optional();
83
+ }
84
+ return properties;
85
+ }
86
+ const validators = new WeakMap();
87
+ /**
88
+ * The validator persist() uses for a resource without its own `validator`, compiled
89
+ * once per definition. It picks up the VineJS messages provider installed when it is
90
+ * first used, so catalog messages apply.
91
+ */
92
+ export function definitionValidator(resource) {
93
+ let validator = validators.get(resource);
94
+ if (!validator) {
95
+ const compiled = vine.compile(vine.object(definitionSchema(resource)));
96
+ validator = { validate: (data) => compiled.validate(data) };
97
+ validators.set(resource, validator);
98
+ }
99
+ return validator;
100
+ }
101
+ /** The validator of a write: the resource's own, or the derived one. */
102
+ export function resourceValidator(resource) {
103
+ return resource.validator ?? definitionValidator(resource);
104
+ }
105
+ /**
106
+ * The canonical (stored) form of a controlling field's value, so a raw input such as
107
+ * 12.5 or ' 12.5' compares equal to the canonical rule value '12.50'. A value the field
108
+ * refuses stays as it is (and so matches no canonical rule value).
109
+ */
110
+ function canonical(field, value) {
111
+ if (!field || value === undefined || value === null)
112
+ return value ?? null;
113
+ try {
114
+ return fieldValue({ ...field, min: undefined, max: undefined }, value);
115
+ }
116
+ catch {
117
+ return value;
118
+ }
119
+ }
120
+ function matches(field, actual, expected) {
121
+ // A multiSelect controller contains the value; `null` matches no selection (null or []).
122
+ if (field?.type === 'multiSelect')
123
+ return expected === null
124
+ ? actual === null || actual === undefined || (Array.isArray(actual) && !actual.length)
125
+ : Array.isArray(actual) && actual.includes(expected);
126
+ // Rule values are canonical (checked by defineResource); the record value is made canonical.
127
+ return canonical(field, actual) === expected;
128
+ }
129
+ /** Whether a field applies to a (prospective) record; see Field.visibleWhen. */
130
+ export function isVisible(resource, key, record) {
131
+ const rule = resource.fields[key]?.visibleWhen;
132
+ if (!rule)
133
+ return true;
134
+ return Object.entries(rule).every(([sibling, expected]) => (Array.isArray(expected) ? expected : [expected]).some((value) => matches(resource.fields[sibling], record[sibling], value)));
135
+ }
136
+ /**
137
+ * Clears every field that does not apply to the record (null, or an empty list for
138
+ * manyToMany), repeating until stable so a field depending on a hidden field is hidden
139
+ * too. Returns the hidden keys.
140
+ */
141
+ export function applyVisibility(resource, record, options = {}) {
142
+ const hidden = new Set();
143
+ const cleared = (key) => options.existing && options.writable && !options.writable(key) && key in options.existing
144
+ ? options.existing[key]
145
+ : resource.fields[key].type === 'manyToMany'
146
+ ? []
147
+ : null;
148
+ for (let pass = 0; pass <= Object.keys(resource.fields).length; pass++) {
149
+ let changed = false;
150
+ for (const key of Object.keys(resource.fields)) {
151
+ if (hidden.has(key) || isVisible(resource, key, record))
152
+ continue;
153
+ hidden.add(key);
154
+ changed = true;
155
+ if (resource.fields[key].type === 'hasMany')
156
+ continue;
157
+ record[key] = cleared(key);
158
+ }
159
+ if (!changed)
160
+ break;
161
+ }
162
+ return hidden;
163
+ }
164
+ /** Declared defaults for the stored fields a create input leaves out. */
165
+ export function missingDefaults(resource, input) {
166
+ const defaults = {};
167
+ for (const [key, field] of Object.entries(resource.fields))
168
+ if (field.default !== undefined && !(key in input))
169
+ defaults[key] = Array.isArray(field.default) ? [...field.default] : field.default;
170
+ return defaults;
171
+ }
@@ -1,4 +1,5 @@
1
- import { identifier } from './define_resource.js';
1
+ import { assertLabel, identifier, joinTable } from './define_resource.js';
2
+ import { assertPrintTemplateColumns } from '../integrations/print_templates.js';
2
3
  export class ResourceRegistry {
3
4
  #resources = new Map();
4
5
  #owners = new Map();
@@ -28,8 +29,7 @@ export class ResourceRegistry {
28
29
  for (const row of rows) {
29
30
  if (typeof row.key !== 'string' || !row.key.trim() || row.key.length > 255)
30
31
  throw new Error(`Module ${module.name}: invalid lookup key in ${group}`);
31
- if (!row.label?.ar || !row.label?.en)
32
- throw new Error(`Module ${module.name}: lookup ${group}.${row.key} needs bilingual labels`);
32
+ assertLabel(row.label, `Module ${module.name}: lookup ${group}.${row.key}`);
33
33
  if (lookupKeys.has(`${group}\u0000${row.key}`))
34
34
  throw new Error(`Duplicate lookup: ${group}.${row.key}`);
35
35
  lookupKeys.add(`${group}\u0000${row.key}`);
@@ -45,6 +45,16 @@ export class ResourceRegistry {
45
45
  roleKeys.add(role.key);
46
46
  }
47
47
  }
48
+ const tables = new Set(next.all().map((resource) => resource.name));
49
+ for (const resource of next.all())
50
+ for (const [key, field] of Object.entries(resource.fields)) {
51
+ if (field.type !== 'manyToMany')
52
+ continue;
53
+ const { table } = joinTable(resource.name, key, field);
54
+ if (tables.has(table))
55
+ throw new Error(`Duplicate table name: ${table}`);
56
+ tables.add(table);
57
+ }
48
58
  for (const resource of next.all()) {
49
59
  if (resource.scope) {
50
60
  const field = resource.fields[resource.scope.from];
@@ -52,7 +62,7 @@ export class ResourceRegistry {
52
62
  throw new Error(`${resource.name}: scope.from must reference a scoped resource`);
53
63
  }
54
64
  for (const field of Object.values(resource.fields)) {
55
- if (field.type !== 'belongsTo' && field.type !== 'hasMany')
65
+ if (field.type !== 'belongsTo' && field.type !== 'hasMany' && field.type !== 'manyToMany')
56
66
  continue;
57
67
  const target = next.get(field.resource);
58
68
  const owner = next.owner(resource.name);
@@ -64,6 +74,7 @@ export class ResourceRegistry {
64
74
  if (field.type === 'hasMany' && !(field.foreignKey in target.fields))
65
75
  throw new Error(`Missing child foreign key: ${field.foreignKey}`);
66
76
  }
77
+ assertPrintTemplateColumns(resource, next);
67
78
  }
68
79
  this.#resources = next.#resources;
69
80
  this.#owners = next.#owners;