adula 2.0.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 +5 -3
  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,3 +1,166 @@
1
+ import { currentLanguage, translate } from '../languages/catalog.js';
2
+ /**
3
+ * A value the field definition forbids. `rule` names the catalog message
4
+ * (`validation.<rule>`), so the derived VineJS validator reports it like its own rules.
5
+ */
6
+ export class FieldValueError extends Error {
7
+ rule;
8
+ params;
9
+ constructor(rule, params = {}) {
10
+ super(translate(`validation.${rule}`, currentLanguage(), params));
11
+ this.rule = rule;
12
+ this.params = params;
13
+ this.name = 'FieldValueError';
14
+ }
15
+ }
16
+ /** Column length of each text-like type (string and enum are varchar(255)). */
17
+ export const TEXT_LIMITS = {
18
+ string: 255,
19
+ enum: 255,
20
+ email: 254,
21
+ phone: 32,
22
+ url: 2048,
23
+ };
24
+ /** The most ids one manyToMany write may link. */
25
+ export const MANY_TO_MANY_LIMIT = 500;
26
+ /** Files a multiple attachment field accepts when it declares no `max` (ADR 047). */
27
+ export const MULTIPLE_ATTACHMENT_LIMIT = 10;
28
+ /** The largest `max` a multiple attachment field may declare. */
29
+ export const MULTIPLE_ATTACHMENT_MAX = 100;
30
+ /** An attachment field holding several files: a JSON array of attachment ids, in order. */
31
+ export function isMultipleAttachment(field) {
32
+ return field?.type === 'attachment' && field.multiple === true;
33
+ }
34
+ /** The most files an attachment field accepts: one, or the `max` of a multiple field. */
35
+ export function attachmentLimit(field) {
36
+ return field.type === 'attachment' && field.multiple
37
+ ? (field.max ?? MULTIPLE_ATTACHMENT_LIMIT)
38
+ : 1;
39
+ }
40
+ /** numeric(precision, scale) of a decimal or percent field, with the documented defaults. */
41
+ export function decimalShape(field) {
42
+ return {
43
+ precision: field.precision ?? (field.type === 'percent' ? 7 : 18),
44
+ scale: field.scale ?? 2,
45
+ };
46
+ }
47
+ /**
48
+ * Refuses a JSON number that cannot carry a decimal exactly: its magnitude reaches
49
+ * Number.MAX_SAFE_INTEGER or it has more than 15 significant digits, so String(value)
50
+ * may already be a rounded neighbour of what the client meant (12345678901234567 arrives
51
+ * as 12345678901234568). Such values must be sent as strings.
52
+ */
53
+ function unsafeNumber(value) {
54
+ const significant = String(Math.abs(value)).replace('.', '').replace(/^0+/, '').replace(/0+$/, '');
55
+ if (Math.abs(value) >= Number.MAX_SAFE_INTEGER || significant.length > 15)
56
+ throw new FieldValueError('unsafeNumber');
57
+ }
58
+ /**
59
+ * The canonical decimal string of a number or numeric string: an optional minus, the
60
+ * integer digits without leading zeros and exactly `scale` fractional digits ("12.50").
61
+ * Rejects more fractional digits than `scale` (trailing zeros excepted), more than
62
+ * `precision - scale` integer digits and JSON numbers beyond exact precision (see
63
+ * unsafeNumber); strings keep every digit.
64
+ */
65
+ export function canonicalDecimal(value, precision, scale) {
66
+ if (typeof value === 'number' && Number.isFinite(value))
67
+ unsafeNumber(value);
68
+ const text = typeof value === 'number' && Number.isFinite(value)
69
+ ? String(value)
70
+ : typeof value === 'string'
71
+ ? value.trim()
72
+ : undefined;
73
+ const match = text === undefined ? null : /^([+-])?(\d+)(?:\.(\d+))?$/.exec(text);
74
+ if (!match)
75
+ throw new FieldValueError('number');
76
+ const [, sign, whole, fraction = ''] = match;
77
+ if (/[^0]/.test(fraction.slice(scale)))
78
+ throw new FieldValueError('decimalScale', { scale });
79
+ const integer = whole.replace(/^0+(?=\d)/, '');
80
+ if (integer.replace(/^0$/, '').length > precision - scale)
81
+ throw new FieldValueError('decimalPrecision', { digits: precision - scale });
82
+ const digits = fraction.slice(0, scale).padEnd(scale, '0');
83
+ const body = scale ? `${integer}.${digits}` : integer;
84
+ return sign === '-' && /[1-9]/.test(body) ? `-${body}` : body;
85
+ }
86
+ /** A canonical decimal string as an integer count of 10^-scale units, for comparisons. */
87
+ function scaled(value) {
88
+ return BigInt(value.replace('.', ''));
89
+ }
90
+ /** Arabic-Indic and Extended Arabic-Indic digits as ASCII digits. */
91
+ export function latinDigits(value) {
92
+ return value
93
+ .replace(/[٠-٩]/g, (digit) => String(digit.charCodeAt(0) - 0x0660))
94
+ .replace(/[۰-۹]/g, (digit) => String(digit.charCodeAt(0) - 0x06f0));
95
+ }
96
+ /** `+?digits` (7 to 15 digits) from input with spaces, dashes, dots, parentheses or Arabic digits. */
97
+ export function normalizePhone(value) {
98
+ const phone = latinDigits(value.trim()).replace(/[\s\-().]/g, '');
99
+ if (!/^\+?\d{7,15}$/.test(phone))
100
+ throw new FieldValueError('phone');
101
+ return phone;
102
+ }
103
+ const EMAIL = /^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)+$/;
104
+ /** A trimmed, lower-cased e-mail address. */
105
+ export function normalizeEmail(value) {
106
+ const email = value.trim().toLowerCase();
107
+ if (email.length > 254 || !EMAIL.test(email))
108
+ throw new FieldValueError('email');
109
+ return email;
110
+ }
111
+ /** A trimmed absolute http(s) URL; javascript:, data: and relative URLs are refused. */
112
+ export function normalizeUrl(value) {
113
+ const url = value.trim();
114
+ let parsed;
115
+ try {
116
+ parsed = new URL(url);
117
+ }
118
+ catch { }
119
+ if (!parsed ||
120
+ !/^https?:\/\/[^\s/?#]/i.test(url) ||
121
+ /\s/.test(url) ||
122
+ !['http:', 'https:'].includes(parsed.protocol) ||
123
+ !parsed.hostname)
124
+ throw new FieldValueError('url');
125
+ return url;
126
+ }
127
+ function normalizeFormat(format, value) {
128
+ return format === 'email'
129
+ ? normalizeEmail(value)
130
+ : format === 'url'
131
+ ? normalizeUrl(value)
132
+ : normalizePhone(value);
133
+ }
134
+ const patterns = new Map();
135
+ /** The anchored RegExp of a field pattern (`^(?:source)$`), compiled once. */
136
+ export function fieldPattern(source) {
137
+ let pattern = patterns.get(source);
138
+ if (!pattern) {
139
+ pattern = new RegExp(`^(?:${source})$`);
140
+ if (patterns.size < 1000)
141
+ patterns.set(source, pattern);
142
+ }
143
+ return pattern;
144
+ }
145
+ function checkText(field, value) {
146
+ const max = Math.min(Number(field.max ?? Infinity), TEXT_LIMITS[field.type] ?? Infinity);
147
+ if (field.min !== undefined && value.length < Number(field.min))
148
+ throw new FieldValueError('minLength', { min: Number(field.min) });
149
+ if (value.length > max)
150
+ throw new FieldValueError('maxLength', { max });
151
+ if (field.pattern !== undefined && !fieldPattern(field.pattern).test(value))
152
+ throw new FieldValueError('regex');
153
+ return value;
154
+ }
155
+ /** Checks numeric limits; `compare` returns a negative, zero or positive number. */
156
+ function checkRange(field, value, limit, compare) {
157
+ if (field.min !== undefined && compare(value, limit(field.min)) < 0)
158
+ throw new FieldValueError('min', { min: String(field.min) });
159
+ if (field.max !== undefined && compare(value, limit(field.max)) > 0)
160
+ throw new FieldValueError('max', { max: String(field.max) });
161
+ return value;
162
+ }
163
+ const bigCompare = (a, b) => (a < b ? -1 : a > b ? 1 : 0);
1
164
  export function canonicalDate(value, type) {
2
165
  if (typeof value !== 'string')
3
166
  return false;
@@ -35,7 +198,13 @@ function isJson(value, ancestors = new Set()) {
35
198
  ancestors.delete(value);
36
199
  return valid;
37
200
  }
38
- /** Normalize before CASL evaluates a prospective record, using its stored representation. */
201
+ /**
202
+ * Normalize before CASL evaluates a prospective record, using its stored representation.
203
+ * It is also the hard guarantee of the definition: every stored value passes here, so
204
+ * hooks, custom validators and system writes cannot store what a field forbids (length,
205
+ * pattern, format, options, numeric limits, decimal scale). Constraint violations of
206
+ * the field types and options added in 2.2 throw FieldValueError with a catalog message.
207
+ */
39
208
  export function fieldValue(field, value) {
40
209
  if (value === undefined || value === null)
41
210
  return value;
@@ -44,8 +213,14 @@ export function fieldValue(field, value) {
44
213
  const amount = typeof value === 'number' && Number.isSafeInteger(value) ? String(value) : value;
45
214
  if (!canonicalMoney(amount))
46
215
  throw new Error('Money requires canonical integer minor units within PostgreSQL bigint range');
216
+ checkRange(field, BigInt(amount), (bound) => BigInt(bound), bigCompare);
47
217
  return amount;
48
218
  }
219
+ case 'decimal':
220
+ case 'percent': {
221
+ const { precision, scale } = decimalShape(field);
222
+ return checkRange(field, canonicalDecimal(value, precision, scale), (bound) => canonicalDecimal(bound, precision, scale), (a, b) => bigCompare(scaled(a), scaled(b)));
223
+ }
49
224
  case 'integer':
50
225
  case 'belongsTo':
51
226
  case 'user':
@@ -53,6 +228,8 @@ export function fieldValue(field, value) {
53
228
  Number(value) < (field.type === 'integer' ? -2147483648 : 1) ||
54
229
  Number(value) > 2147483647)
55
230
  throw new Error('Expected a PostgreSQL integer');
231
+ if (field.type === 'integer')
232
+ checkRange(field, Number(value), Number, (a, b) => a - b);
56
233
  return value;
57
234
  case 'boolean':
58
235
  if (typeof value !== 'boolean')
@@ -63,7 +240,46 @@ export function fieldValue(field, value) {
63
240
  case 'lookup':
64
241
  if (typeof value !== 'string')
65
242
  throw new Error('Expected a string');
243
+ if (field.type === 'lookup')
244
+ return value;
245
+ if (field.type === 'string' && field.format)
246
+ return checkText(field, normalizeFormat(field.format, value));
247
+ return checkText(field, value);
248
+ case 'email':
249
+ case 'phone':
250
+ case 'url':
251
+ if (typeof value !== 'string')
252
+ throw new FieldValueError('string');
253
+ return checkText(field, normalizeFormat(field.type, value));
254
+ case 'enum':
255
+ if (typeof value !== 'string' || !field.options.some((option) => option.value === value))
256
+ throw new FieldValueError('in');
66
257
  return value;
258
+ case 'multiSelect': {
259
+ if (!Array.isArray(value) || value.some((entry) => typeof entry !== 'string'))
260
+ throw new FieldValueError('array');
261
+ const chosen = new Set(value);
262
+ const known = field.options.map((option) => option.value);
263
+ if ([...chosen].some((entry) => !known.includes(entry)))
264
+ throw new FieldValueError('in');
265
+ const ordered = known.filter((entry) => chosen.has(entry));
266
+ if (field.min !== undefined && ordered.length < field.min)
267
+ throw new FieldValueError('array.minLength', { min: field.min });
268
+ if (field.max !== undefined && ordered.length > field.max)
269
+ throw new FieldValueError('array.maxLength', { max: field.max });
270
+ return ordered;
271
+ }
272
+ case 'manyToMany': {
273
+ // Form posts send ids as strings: decimal digit strings are accepted as ids.
274
+ const ids = Array.isArray(value)
275
+ ? value.map((id) => (typeof id === 'string' && /^\d{1,10}$/.test(id) ? Number(id) : id))
276
+ : null;
277
+ if (!ids ||
278
+ ids.length > MANY_TO_MANY_LIMIT ||
279
+ ids.some((id) => !Number.isSafeInteger(id) || id < 1 || id > 2147483647))
280
+ throw new FieldValueError('relation');
281
+ return [...new Set(ids)].sort((a, b) => a - b);
282
+ }
67
283
  case 'date':
68
284
  case 'datetime': {
69
285
  const normalized = field.type === 'datetime' && value instanceof Date && Number.isFinite(value.getTime())
@@ -77,11 +293,27 @@ export function fieldValue(field, value) {
77
293
  if (!isJson(value))
78
294
  throw new Error('Expected a JSON value without cycles or non-JSON values');
79
295
  return value;
80
- case 'attachment':
296
+ case 'attachment': {
81
297
  // Writes carry the id of an owned upload; reads are hydrated into summaries later.
82
- if (!Number.isSafeInteger(value) || Number(value) < 1 || Number(value) > 2147483647)
83
- throw new Error('Expected the identifier of an uploaded attachment');
84
- return value;
298
+ const isId = (id) => Number.isSafeInteger(id) && Number(id) >= 1 && Number(id) <= 2147483647;
299
+ if (!field.multiple) {
300
+ if (!isId(value))
301
+ throw new Error('Expected the identifier of an uploaded attachment');
302
+ return value;
303
+ }
304
+ // Several files keep the order the user gave them; form posts may send digit strings.
305
+ const ids = Array.isArray(value)
306
+ ? value.map((id) => (typeof id === 'string' && /^\d{1,10}$/.test(id) ? Number(id) : id))
307
+ : null;
308
+ if (!ids || ids.length > MULTIPLE_ATTACHMENT_MAX || !ids.every(isId))
309
+ throw new FieldValueError('attachments');
310
+ if (new Set(ids).size !== ids.length)
311
+ throw new FieldValueError('attachments.distinct');
312
+ const max = attachmentLimit(field);
313
+ if (ids.length > max)
314
+ throw new FieldValueError('attachments.max', { max });
315
+ return ids;
316
+ }
85
317
  default:
86
318
  return value;
87
319
  }
@@ -5,6 +5,8 @@ export declare class Settings {
5
5
  get<T>(key: string, scope?: string, scopeId?: string): Promise<T | undefined>;
6
6
  set(key: string, value: unknown, scope?: string, scopeId?: string): Promise<void>;
7
7
  }
8
+ /** The number a sequence value is issued as: `ORD-000042`. */
9
+ export declare function formatSequence(key: string, value: string | number | bigint): string;
8
10
  export declare function sequence(trx: Knex.Transaction, key: string): Promise<string>;
9
11
  /** The record a notification is about; opening the notification opens the record. */
10
12
  export type NotificationTarget = {
@@ -14,9 +14,13 @@ export class Settings {
14
14
  .merge(['value']);
15
15
  }
16
16
  }
17
+ /** The number a sequence value is issued as: `ORD-000042`. */
18
+ export function formatSequence(key, value) {
19
+ return `${key}-${String(value).padStart(6, '0')}`;
20
+ }
17
21
  export async function sequence(trx, key) {
18
22
  const result = await trx.raw('INSERT INTO sequences (key,value) VALUES (?,1) ON CONFLICT (key) DO UPDATE SET value=sequences.value+1 RETURNING value', [key]);
19
- return `${key}-${String(result.rows[0].value).padStart(6, '0')}`;
23
+ return formatSequence(key, result.rows[0].value);
20
24
  }
21
25
  export function targetColumns(target) {
22
26
  if (!target)
@@ -1,8 +1,8 @@
1
1
  /**
2
2
  * Names used by 1.x releases, published as `@adula/kit`. They exist only so that
3
3
  * `adula:upgrade` and migration 016 can find and rename what 1.x installed; nothing
4
- * else may read or write them. This file is the single allow-listed place for the
5
- * retired name in the core package (`pnpm check:naming`).
4
+ * else may read or write them. This file is the only place for the retired name in
5
+ * the core package; review is the only guard now (ADR 040).
6
6
  */
7
7
  const RETIRED = 'kit';
8
8
  /** Directory Lucid recorded for each 1.x core migration. */
@@ -0,0 +1,9 @@
1
+ /**
2
+ * Refuses a time zone the runtime does not know, at construction rather than per call.
3
+ * Services are built per request, so each zone is checked with Intl only once.
4
+ */
5
+ export declare function assertTimeZone(timeZone: string): string;
6
+ /** The calendar date (YYYY-MM-DD) of an instant in a time zone. */
7
+ export declare function calendarDate(instant: Date, timeZone?: string): string;
8
+ /** A calendar date moved by whole days. */
9
+ export declare function addDays(date: string, days: number): string;
@@ -0,0 +1,44 @@
1
+ /**
2
+ * Calendar days of the system (ADR 044). Due dates and delegation ranges are whole days
3
+ * in the system's time zone (an IANA name such as Asia/Riyadh; UTC by default), so a
4
+ * day starts at local midnight rather than at 00:00 UTC.
5
+ */
6
+ const formats = new Map();
7
+ const knownZones = new Set();
8
+ /**
9
+ * Refuses a time zone the runtime does not know, at construction rather than per call.
10
+ * Services are built per request, so each zone is checked with Intl only once.
11
+ */
12
+ export function assertTimeZone(timeZone) {
13
+ if (knownZones.has(timeZone))
14
+ return timeZone;
15
+ try {
16
+ new Intl.DateTimeFormat('en-CA', { timeZone });
17
+ }
18
+ catch {
19
+ throw new Error(`Unknown time zone "${timeZone}"; use an IANA name such as Asia/Riyadh`);
20
+ }
21
+ knownZones.add(timeZone);
22
+ return timeZone;
23
+ }
24
+ /** The calendar date (YYYY-MM-DD) of an instant in a time zone. */
25
+ export function calendarDate(instant, timeZone = 'UTC') {
26
+ let format = formats.get(timeZone);
27
+ if (!format) {
28
+ format = new Intl.DateTimeFormat('en-CA', {
29
+ timeZone,
30
+ year: 'numeric',
31
+ month: '2-digit',
32
+ day: '2-digit',
33
+ });
34
+ formats.set(timeZone, format);
35
+ }
36
+ const parts = Object.fromEntries(format.formatToParts(instant).map((p) => [p.type, p.value]));
37
+ return `${parts.year}-${parts.month}-${parts.day}`;
38
+ }
39
+ /** A calendar date moved by whole days. */
40
+ export function addDays(date, days) {
41
+ const moved = new Date(`${date}T00:00:00Z`);
42
+ moved.setUTCDate(moved.getUTCDate() + days);
43
+ return moved.toISOString().slice(0, 10);
44
+ }
@@ -22,6 +22,38 @@ export type Recipients = 'creator' | 'submitter'
22
22
  } | {
23
23
  users: number[];
24
24
  } | ((context: StepContext) => number[] | Promise<number[]>);
25
+ /**
26
+ * Who receives an SLA escalation: any step recipient, or `{ manager: roleKey }` — the
27
+ * holders of that role in the approver's organizational unit or, failing that, the
28
+ * nearest ancestor unit (the approver's line manager in the org tree).
29
+ */
30
+ export type EscalationTarget = Recipients | {
31
+ manager: string;
32
+ };
33
+ /** What happens when an approval passes its deadline. */
34
+ export type SlaEscalation =
35
+ /** Mark the approval overdue and tell its approvers (the default). */
36
+ {
37
+ action: 'overdue';
38
+ }
39
+ /** Also tell the target, for example the approver's manager. */
40
+ | {
41
+ action: 'notify';
42
+ to: EscalationTarget;
43
+ }
44
+ /** Move the approval to the target; the late approvers' tasks are cancelled. */
45
+ | {
46
+ action: 'reassign';
47
+ to: EscalationTarget;
48
+ };
49
+ /** A service-level deadline on an approval or decision step (ADR 044). */
50
+ export type StepSla = {
51
+ /** Hours the approvers have from the moment the step opens. */
52
+ hours: number;
53
+ /** Remind the approvers this many hours before the deadline; default a quarter of `hours`, 0 for none. */
54
+ dueSoonHours?: number;
55
+ escalate?: SlaEscalation;
56
+ };
25
57
  /** One decision an approver can take at a decision step (#42). */
26
58
  export type DecisionOutcome = {
27
59
  label: string;
@@ -53,6 +85,7 @@ export type WorkflowStep = {
53
85
  label: string;
54
86
  assignees: Recipients;
55
87
  dueInDays?: number;
88
+ sla?: StepSla;
56
89
  approve: string;
57
90
  reject: string;
58
91
  } | {
@@ -65,6 +98,7 @@ export type WorkflowStep = {
65
98
  label: string;
66
99
  assignees: Recipients;
67
100
  dueInDays?: number;
101
+ sla?: StepSla;
68
102
  outcomes: Record<string, DecisionOutcome>;
69
103
  } | {
70
104
  type: 'delay';
@@ -97,6 +131,11 @@ export type WorkflowInput = {
97
131
  maxAttempts?: number;
98
132
  };
99
133
  export type WorkflowDefinition = WorkflowInput & {
134
+ /**
135
+ * The compiled XState machine.
136
+ * @deprecated Transitions are resolved by AdulaJS itself (ADR 044); `machine` and the
137
+ * xstate dependency are removed in the next major version.
138
+ */
100
139
  machine: AnyStateMachine;
101
140
  };
102
141
  export type WorkflowEvent = {
@@ -114,11 +153,17 @@ export type WorkflowEvent = {
114
153
  };
115
154
  export declare const WORKFLOW_NAME_RULE = "use lower-case letters, digits and underscores, starting with a letter";
116
155
  /**
117
- * Declares a versioned workflow. Steps compile to an XState machine; the engine
118
- * performs each step's effect and asks the machine for the next step. Runs keep
156
+ * Declares a versioned workflow. The engine performs each step's effect and resolves
157
+ * the next step from the step table (nextStep); the deprecated XState machine is still
158
+ * compiled for compatibility until the next major version (ADR 044). Runs keep
119
159
  * the version they started with, so publishing a new version never changes a
120
160
  * running workflow (migrate explicitly with WorkflowEngine.migrateRuns).
121
161
  */
122
162
  export declare function defineWorkflow(input: WorkflowInput): WorkflowDefinition;
123
- /** The step reached from `current` by `event`, or an error if the step does not accept it. */
163
+ /**
164
+ * The step reached from `current` by `event`, or an error if the step does not accept
165
+ * it. Resolved from the step table itself (ADR 044). Unlike the former XState lookup, an
166
+ * approval or decision step may name itself (for example "ask again"), which reopens it;
167
+ * defineWorkflow refuses a self-target on any other step.
168
+ */
124
169
  export declare function nextStep(definition: WorkflowDefinition, current: string, event: WorkflowEvent): string;
@@ -1,4 +1,4 @@
1
- import { createMachine, getNextSnapshot } from 'xstate';
1
+ import { createMachine } from 'xstate';
2
2
  const IDENTIFIER = /^[a-z][a-z0-9_]*$/;
3
3
  export const WORKFLOW_NAME_RULE = 'use lower-case letters, digits and underscores, starting with a letter';
4
4
  /** Names the rule and a valid spelling, since dotted event-style names are a natural first try. */
@@ -17,6 +17,18 @@ function assertIdentifier(kind, value) {
17
17
  : 'notify_approved';
18
18
  throw new Error(`Invalid ${kind} name "${value}": ${WORKFLOW_NAME_RULE} (for example ${example}).`);
19
19
  }
20
+ function assertSla(key, sla) {
21
+ if (typeof sla.hours !== 'number' || !Number.isFinite(sla.hours) || sla.hours <= 0)
22
+ throw new Error(`Step ${key} needs a positive SLA duration in hours`);
23
+ if (sla.dueSoonHours !== undefined &&
24
+ (typeof sla.dueSoonHours !== 'number' || sla.dueSoonHours < 0 || sla.dueSoonHours >= sla.hours))
25
+ throw new Error(`Step ${key} needs dueSoonHours between 0 and its SLA duration`);
26
+ const action = sla.escalate?.action ?? 'overdue';
27
+ if (!['overdue', 'notify', 'reassign'].includes(action))
28
+ throw new Error(`Step ${key} has an unknown SLA escalation "${action}"`);
29
+ if (action !== 'overdue' && !sla.escalate.to)
30
+ throw new Error(`Step ${key} needs an escalation target for ${action}`);
31
+ }
20
32
  function targets(step) {
21
33
  switch (step.type) {
22
34
  case 'condition':
@@ -32,8 +44,9 @@ function targets(step) {
32
44
  }
33
45
  }
34
46
  /**
35
- * Declares a versioned workflow. Steps compile to an XState machine; the engine
36
- * performs each step's effect and asks the machine for the next step. Runs keep
47
+ * Declares a versioned workflow. The engine performs each step's effect and resolves
48
+ * the next step from the step table (nextStep); the deprecated XState machine is still
49
+ * compiled for compatibility until the next major version (ADR 044). Runs keep
37
50
  * the version they started with, so publishing a new version never changes a
38
51
  * running workflow (migrate explicitly with WorkflowEngine.migrateRuns).
39
52
  */
@@ -46,12 +59,19 @@ export function defineWorkflow(input) {
46
59
  const keys = Object.keys(input.steps);
47
60
  for (const key of keys) {
48
61
  assertIdentifier('step', key);
49
- for (const target of targets(input.steps[key]))
62
+ const step = input.steps[key];
63
+ for (const target of targets(step)) {
50
64
  if (!(target in input.steps))
51
65
  throw new Error(`Step ${key} points to unknown step ${target}`);
52
- const step = input.steps[key];
66
+ // Only a step that waits for a person may reopen itself; any other step naming
67
+ // itself would repeat its effect (notifications, HTTP calls) without end.
68
+ if (target === key && step.type !== 'approval' && step.type !== 'decision')
69
+ throw new Error(`Step ${key} cannot name itself as its next step`);
70
+ }
53
71
  if (step.type === 'delay' && (!Number.isInteger(step.ms) || step.ms < 0))
54
72
  throw new Error(`Step ${key} needs a non-negative integer delay`);
73
+ if ((step.type === 'approval' || step.type === 'decision') && step.sla)
74
+ assertSla(key, step.sla);
55
75
  if (step.type === 'decision') {
56
76
  const outcomes = Object.entries(step.outcomes ?? {});
57
77
  if (outcomes.length < 2)
@@ -110,14 +130,38 @@ export function defineWorkflow(input) {
110
130
  });
111
131
  return { ...input, machine };
112
132
  }
113
- /** The step reached from `current` by `event`, or an error if the step does not accept it. */
133
+ /**
134
+ * The step reached from `current` by `event`, or an error if the step does not accept
135
+ * it. Resolved from the step table itself (ADR 044). Unlike the former XState lookup, an
136
+ * approval or decision step may name itself (for example "ask again"), which reopens it;
137
+ * defineWorkflow refuses a self-target on any other step.
138
+ */
114
139
  export function nextStep(definition, current, event) {
115
- if (!(current in definition.steps))
140
+ const step = Object.hasOwn(definition.steps, current) ? definition.steps[current] : undefined;
141
+ if (!step)
116
142
  throw new Error(`Step ${current} is not part of ${definition.name}@${definition.version}`);
117
- const snapshot = definition.machine.resolveState({ value: current, context: {} });
118
- const next = getNextSnapshot(definition.machine, snapshot, event);
119
- const value = String(next.value);
120
- if (value === current)
121
- throw new Error(`Step ${current} does not accept ${event.type}`);
122
- return value;
143
+ const refuse = () => new Error(`Step ${current} does not accept ${event.type}`);
144
+ switch (step.type) {
145
+ case 'condition':
146
+ if (event.type !== 'EVALUATE')
147
+ throw refuse();
148
+ return step.when(event.record) ? step.then : step.else;
149
+ case 'approval':
150
+ if (event.type === 'APPROVE')
151
+ return step.approve;
152
+ if (event.type === 'REJECT')
153
+ return step.reject;
154
+ throw refuse();
155
+ case 'decision': {
156
+ if (event.type !== 'DECIDE' || !Object.hasOwn(step.outcomes, event.outcome))
157
+ throw refuse();
158
+ return step.outcomes[event.outcome].next;
159
+ }
160
+ case 'end':
161
+ throw refuse();
162
+ default:
163
+ if (event.type !== 'DONE')
164
+ throw refuse();
165
+ return step.next;
166
+ }
123
167
  }
@@ -0,0 +1,93 @@
1
+ import type { Knex } from 'knex';
2
+ /** A user's approvals routed to a delegate for an inclusive date range (ADR 044). */
3
+ export type WorkflowDelegation = {
4
+ id: number;
5
+ delegatorId: number;
6
+ delegatorName: string | null;
7
+ delegateId: number;
8
+ delegateName: string | null;
9
+ /** Inclusive dates (YYYY-MM-DD), days in the system time zone (UTC by default). */
10
+ startsOn: string;
11
+ endsOn: string;
12
+ note: string | null;
13
+ status: 'scheduled' | 'active' | 'ended' | 'revoked';
14
+ createdBy: number | null;
15
+ createdAt: string;
16
+ revokedAt: string | null;
17
+ };
18
+ export type WorkflowDelegationInput = {
19
+ delegatorId: number;
20
+ delegateId: unknown;
21
+ startsOn: unknown;
22
+ endsOn: unknown;
23
+ note?: unknown;
24
+ };
25
+ export type WorkflowDelegationOptions = {
26
+ now?: () => Date;
27
+ /** The system time zone whose calendar days delegation ranges use (default UTC). */
28
+ timeZone?: string;
29
+ };
30
+ /** The activity log subject for delegation changes. */
31
+ export declare const DELEGATION_ACTIVITY = "core.workflow_delegations";
32
+ /**
33
+ * Narrows an assignments query (aliased `a`) to the rows a user may act on today:
34
+ * - their own rows, and rows routed to them through a delegation still in force;
35
+ * - rows routed away from them (on_behalf_of): the approver always keeps them;
36
+ * - as a delegate, the open approvals of users who delegated to them for today,
37
+ * including rows routed earlier through a delegation that has since ended.
38
+ * A delegate never holds an approval of a run they started themselves, so delegation
39
+ * cannot let anyone approve their own request. Delegation never widens record access:
40
+ * every caller still checks the record with the acting user's own rights.
41
+ */
42
+ export declare function actionableBy(db: Knex, actorId: number, today: string): (query: Knex.QueryBuilder) => Knex.QueryBuilder<any, any>;
43
+ /** The SQL flag `delegation_active` for an assignments query aliased `a`. */
44
+ export declare function delegationActive(db: Knex, today: string): Knex.Raw<any>;
45
+ /**
46
+ * Out-of-office delegation of workflow approvals. A user delegates to one person per
47
+ * date range (overlapping ranges are refused); administrators manage delegations for
48
+ * others. Creation and revocation are written to the activity log and the delegate is
49
+ * notified. Manual tasks are never delegated, only workflow approvals.
50
+ */
51
+ export declare class WorkflowDelegations {
52
+ private db;
53
+ private options;
54
+ constructor(db: Knex, options?: WorkflowDelegationOptions);
55
+ /** A user's own delegations (given and received), newest first. */
56
+ forUser(userId: number): Promise<{
57
+ given: WorkflowDelegation[];
58
+ received: WorkflowDelegation[];
59
+ }>;
60
+ /**
61
+ * Active users a delegate can be chosen from (id and display name only), at most 20.
62
+ * The search needs two characters and matches names, or an e-mail address exactly, so
63
+ * the picker cannot list the whole user directory or probe e-mail fragments.
64
+ */
65
+ candidates(search: unknown, exceptId: number): Promise<{
66
+ id: number;
67
+ name: string;
68
+ }[]>;
69
+ /** Every delegation that has not ended, for administrators. */
70
+ current(): Promise<WorkflowDelegation[]>;
71
+ /** The delegation in force today for a user, if any. */
72
+ active(delegatorId: number, db?: Knex): Promise<{
73
+ id: number;
74
+ delegateId: number;
75
+ } | null>;
76
+ /** Creates a delegation; the caller decides whether `createdBy` may act for the delegator. */
77
+ create(input: WorkflowDelegationInput, createdBy: number): Promise<WorkflowDelegation>;
78
+ /**
79
+ * Ends a delegation now. `ownerId` must be the delegator unless `any` (administrators);
80
+ * unknown or foreign ids read as not found. `actorId` (default `ownerId`) is recorded,
81
+ * for example the administrator behind an impersonation. Open approvals routed through
82
+ * the delegation return to their approver.
83
+ */
84
+ revoke(id: unknown, ownerId: number, options?: {
85
+ any?: boolean;
86
+ actorId?: number;
87
+ }): Promise<void>;
88
+ private date;
89
+ private query;
90
+ private present;
91
+ private now;
92
+ private today;
93
+ }