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
@@ -2,6 +2,8 @@ import { subject } from '@casl/ability';
2
2
  import { jsonValue } from '../admin/contracts.js';
3
3
  import { AdulaError } from '../admin/errors.js';
4
4
  import { notifyWithTemplate } from '../core/message_templates.js';
5
+ import { escapeLike } from '../core/like.js';
6
+ import { canView, resourceLabel } from './shared.js';
5
7
  const BODY_LIMIT = 5000;
6
8
  const MENTION_LIMIT = 20;
7
9
  const TAG_LIMIT = 20;
@@ -254,8 +256,12 @@ export class RecordCollaboration {
254
256
  .offset(offset)
255
257
  .limit(page)
256
258
  .select('id', 'full_name');
259
+ // Names match by substring; e-mail only by exact (case-insensitive) equality so
260
+ // the picker cannot be used to enumerate addresses prefix by prefix.
257
261
  if (term)
258
- query.where((where) => where.whereILike('full_name', `%${term}%`).orWhereILike('email', `${term}%`));
262
+ query.where((where) => where
263
+ .whereILike('full_name', `%${escapeLike(term)}%`)
264
+ .orWhereRaw('lower(email) = lower(?)', [term]));
259
265
  const users = await query;
260
266
  for (const user of users) {
261
267
  if (result.length >= 10)
@@ -274,8 +280,7 @@ export class RecordCollaboration {
274
280
  */
275
281
  followerListener(module, resource, event) {
276
282
  return {
277
- name: `adula.followers.${module}.${resource}.${event}`,
278
- event: `${module}.${resource}.${event}`,
283
+ ...followerKey(module, resource, event),
279
284
  handle: async (domainEvent, trx) => {
280
285
  const id = Number(domainEvent.payload.id);
281
286
  const actorId = Number(domainEvent.payload.actorId);
@@ -300,18 +305,10 @@ export class RecordCollaboration {
300
305
  };
301
306
  }
302
307
  label(name) {
303
- try {
304
- return this.resources.label(name);
305
- }
306
- catch {
307
- return name;
308
- }
308
+ return resourceLabel(this.resources, name);
309
309
  }
310
- async canView(name, id, userId) {
311
- const disabled = await this.db('users').where('id', userId).first('disabled_at');
312
- if (!disabled || disabled.disabled_at)
313
- return false;
314
- return this.resources.permits(name, id, await this.actors.load(userId));
310
+ canView(name, id, userId) {
311
+ return canView(this.db, this.resources, this.actors, name, id, userId);
315
312
  }
316
313
  /** Parsed after the record is authorized, so malformed ids never bypass the 403. */
317
314
  commentId(value) {
@@ -335,13 +332,19 @@ export class RecordCollaboration {
335
332
  ];
336
333
  }
337
334
  }
335
+ /** The listener name and domain event of a follower notification. */
336
+ function followerKey(module, resource, event) {
337
+ return {
338
+ name: `adula.followers.${module}.${resource}.${event}`,
339
+ event: `${module}.${resource}.${event}`,
340
+ };
341
+ }
338
342
  /** Follower notifications for every registered resource's update and document events. */
339
343
  export function followerListeners(registry, collaboration) {
340
344
  return registry.all().flatMap((resource) => ['updated', 'submitted', 'cancelled', 'deleted'].map((event) => {
341
345
  const module = registry.owner(resource.name);
342
346
  return {
343
- name: `adula.followers.${module}.${resource.name}.${event}`,
344
- event: `${module}.${resource.name}.${event}`,
347
+ ...followerKey(module, resource.name, event),
345
348
  handle: (domainEvent, trx) => collaboration().followerListener(module, resource.name, event).handle(domainEvent, trx),
346
349
  };
347
350
  }));
@@ -0,0 +1,16 @@
1
+ import type { Knex } from 'knex';
2
+ import type { Actor } from '../auth/ability.js';
3
+ import type { ResourceService } from '../admin/resource_service.js';
4
+ /** Loads the full actor (roles, permission level) of a user by id. */
5
+ export type ActorLoader = {
6
+ load(id: number): Promise<Actor>;
7
+ };
8
+ /**
9
+ * Whether a user may view a record: the account must exist and be active, and the
10
+ * record must pass the same ResourceService authorization that the user's own read
11
+ * would. Used before notifying, mentioning or assigning someone, so these features
12
+ * never reveal a record to a user who cannot open it.
13
+ */
14
+ export declare function canView(db: Knex, resources: Pick<ResourceService, 'permits'>, actors: ActorLoader, resource: string, id: number, userId: number): Promise<boolean>;
15
+ /** The resource's display label, or its name when the resource is no longer registered. */
16
+ export declare function resourceLabel(resources: Pick<ResourceService, 'label'>, name: string): string;
@@ -0,0 +1,21 @@
1
+ /**
2
+ * Whether a user may view a record: the account must exist and be active, and the
3
+ * record must pass the same ResourceService authorization that the user's own read
4
+ * would. Used before notifying, mentioning or assigning someone, so these features
5
+ * never reveal a record to a user who cannot open it.
6
+ */
7
+ export async function canView(db, resources, actors, resource, id, userId) {
8
+ const user = await db('users').where('id', userId).first('disabled_at');
9
+ if (!user || user.disabled_at)
10
+ return false;
11
+ return resources.permits(resource, Number(id), await actors.load(userId));
12
+ }
13
+ /** The resource's display label, or its name when the resource is no longer registered. */
14
+ export function resourceLabel(resources, name) {
15
+ try {
16
+ return resources.label(name);
17
+ }
18
+ catch {
19
+ return String(name);
20
+ }
21
+ }
@@ -0,0 +1,72 @@
1
+ import type { Label } from '../resource/types.js';
2
+ /**
3
+ * Names an application (module) may not take: AdulaJS framework areas, URL segments of
4
+ * the generated application, and tables the core and the host application own. An
5
+ * application's example resource and table share its name, so a collision would shadow
6
+ * a framework table or route.
7
+ */
8
+ export declare const RESERVED_APP_NAMES: readonly string[];
9
+ /** Longest application name: its table, indexes and role keys must fit PostgreSQL limits. */
10
+ export declare const APP_NAME_MAX_LENGTH = 40;
11
+ export type AppOptions = {
12
+ name: string;
13
+ labelAr?: string;
14
+ labelEn?: string;
15
+ };
16
+ export type AppPlan = {
17
+ name: string;
18
+ label: Label;
19
+ /** New files relative to the application root, module definition included. */
20
+ files: Record<string, string>;
21
+ /** Empty module folders created next to the files. */
22
+ directories: string[];
23
+ /** start/modules.ts after registering the application. */
24
+ modules: {
25
+ path: string;
26
+ source: string;
27
+ };
28
+ };
29
+ /** Validates an application name: an SQL-safe slug that is neither reserved nor too long. */
30
+ export declare function appName(value: string): string;
31
+ /** leave_requests → Leave requests */
32
+ export declare function defaultEnglishLabel(name: string): string;
33
+ /** The default roles an application ships, in the shape module definitions declare. */
34
+ export declare function appDefaultRoles(name: string, labelAr: string): ({
35
+ key: string;
36
+ name: string;
37
+ permissionLevel: number;
38
+ rules: {
39
+ subject: string;
40
+ action: "update" | "view" | "create" | "delete";
41
+ }[];
42
+ } | {
43
+ key: string;
44
+ name: string;
45
+ rules: ({
46
+ subject: string;
47
+ action: string;
48
+ conditions?: undefined;
49
+ } | {
50
+ subject: string;
51
+ action: string;
52
+ conditions: {
53
+ createdBy: string;
54
+ };
55
+ })[];
56
+ permissionLevel?: undefined;
57
+ })[];
58
+ /** The module definition of a new application, in the project's Prettier layout. */
59
+ export declare function appModuleSource(name: string, label: Label): string;
60
+ /**
61
+ * A functional smoke test: an administrator opens the example resource list and the
62
+ * navigation carries the application's menu group.
63
+ */
64
+ export declare function appSmokeTestSource(name: string, label: Label): string;
65
+ /**
66
+ * Plans a new application (module) without writing: its module definition with bilingual
67
+ * labels and default roles, one example resource from the resource generator, the empty
68
+ * module folders, a smoke test and its registration in start/modules.ts.
69
+ */
70
+ export declare function planApp(root: string, options: AppOptions): Promise<AppPlan>;
71
+ /** Writes a plan; files are created exclusively, start/modules.ts is changed last. */
72
+ export declare function writeAppPlan(root: string, plan: AppPlan): Promise<void>;
@@ -0,0 +1,285 @@
1
+ import { access, mkdir, readFile, writeFile } from 'node:fs/promises';
2
+ import { dirname, join } from 'node:path';
3
+ import { identifier } from '../resource/define_resource.js';
4
+ import { planResource, quoted } from './generator.js';
5
+ import { MODULE_DIRECTORIES, moduleRegistered } from './source_markers.js';
6
+ /**
7
+ * Names an application (module) may not take: AdulaJS framework areas, URL segments of
8
+ * the generated application, and tables the core and the host application own. An
9
+ * application's example resource and table share its name, so a collision would shadow
10
+ * a framework table or route.
11
+ */
12
+ export const RESERVED_APP_NAMES = [
13
+ // Framework and application areas
14
+ 'adula',
15
+ 'adulajs',
16
+ 'core',
17
+ 'app',
18
+ 'apps',
19
+ 'module',
20
+ 'modules',
21
+ 'system',
22
+ 'admin',
23
+ 'auth',
24
+ 'api',
25
+ 'account',
26
+ 'profile',
27
+ 'work',
28
+ 'resources',
29
+ 'settings',
30
+ 'lookups',
31
+ 'sequences',
32
+ 'notifications',
33
+ 'workflows',
34
+ 'approvals',
35
+ 'my_tasks',
36
+ 'imports',
37
+ 'attachments',
38
+ 'webhooks',
39
+ 'health',
40
+ 'login',
41
+ 'logout',
42
+ 'invitations',
43
+ 'permissions',
44
+ 'reports',
45
+ 'jobs',
46
+ 'mcp',
47
+ // Core and host-application tables
48
+ 'users',
49
+ 'roles',
50
+ 'role_rules',
51
+ 'user_roles',
52
+ 'user_org_units',
53
+ 'org_units',
54
+ 'activities',
55
+ 'assignments',
56
+ 'auth_access_tokens',
57
+ 'authorization_revision',
58
+ 'comment_mentions',
59
+ 'comments',
60
+ 'field_changes',
61
+ 'followers',
62
+ 'import_batches',
63
+ 'inbound_deliveries',
64
+ 'inbound_sources',
65
+ 'message_templates',
66
+ 'outbox',
67
+ 'processed_events',
68
+ 'saved_views',
69
+ 'sessions',
70
+ 'taggables',
71
+ 'tags',
72
+ 'upload_grants',
73
+ 'user_invitations',
74
+ 'user_sessions',
75
+ 'webhook_deliveries',
76
+ 'workflow_events',
77
+ 'workflow_runs',
78
+ 'password_reset_tokens',
79
+ 'social_accounts',
80
+ 'adonis_schema',
81
+ 'adonis_schema_versions',
82
+ ];
83
+ /** Longest application name: its table, indexes and role keys must fit PostgreSQL limits. */
84
+ export const APP_NAME_MAX_LENGTH = 40;
85
+ /** Validates an application name: an SQL-safe slug that is neither reserved nor too long. */
86
+ export function appName(value) {
87
+ if (typeof value !== 'string' || !/^[a-z][a-z0-9_]*$/.test(value))
88
+ throw new Error(`Invalid application name "${value}": use lower-case letters, digits and underscores, starting with a letter`);
89
+ identifier(value);
90
+ if (value.length > APP_NAME_MAX_LENGTH)
91
+ throw new Error(`Application name is longer than ${APP_NAME_MAX_LENGTH} characters`);
92
+ if (RESERVED_APP_NAMES.includes(value))
93
+ throw new Error(`"${value}" is reserved by AdulaJS; choose another application name`);
94
+ return value;
95
+ }
96
+ /** leave_requests → Leave requests */
97
+ export function defaultEnglishLabel(name) {
98
+ const words = name.replaceAll('_', ' ').trim();
99
+ return words.charAt(0).toUpperCase() + words.slice(1);
100
+ }
101
+ /** The default roles an application ships, in the shape module definitions declare. */
102
+ export function appDefaultRoles(name, labelAr) {
103
+ return [
104
+ {
105
+ key: `${name}_manager`,
106
+ name: `مدير ${labelAr}`,
107
+ permissionLevel: 1,
108
+ rules: ['view', 'create', 'update', 'delete'].map((action) => ({
109
+ subject: name,
110
+ action,
111
+ })),
112
+ },
113
+ {
114
+ key: `${name}_user`,
115
+ name: `مستخدم ${labelAr}`,
116
+ rules: [
117
+ { subject: name, action: 'view' },
118
+ { subject: name, action: 'create' },
119
+ { subject: name, action: 'update', conditions: { createdBy: '$actor.id' } },
120
+ ],
121
+ },
122
+ ];
123
+ }
124
+ /** The module definition of a new application, in the project's Prettier layout. */
125
+ export function appModuleSource(name, label) {
126
+ const [manager, user] = appDefaultRoles(name, label.ar);
127
+ const rule = (action) => ` { subject: '${name}', action: '${action}' },`;
128
+ return [
129
+ "import { ACTOR_ID, type Module } from 'adula'",
130
+ '// adula:imports',
131
+ 'export default {',
132
+ ` name: '${name}',`,
133
+ ' label: {',
134
+ ` ar: ${quoted(label.ar)},`,
135
+ ` en: ${quoted(label.en ?? defaultEnglishLabel(name))},`,
136
+ ' },',
137
+ ' dependsOn: [],',
138
+ ' resources: [/* adula:resources */],',
139
+ ' // Created by `node ace adula:install` when missing; administrators own them afterwards.',
140
+ ' defaultRoles: [',
141
+ ' {',
142
+ ` key: '${manager.key}',`,
143
+ ` name: ${quoted(manager.name)},`,
144
+ ' permissionLevel: 1,',
145
+ ' rules: [',
146
+ ...['view', 'create', 'update', 'delete'].map((action) => rule(action)),
147
+ ' ],',
148
+ ' },',
149
+ ' {',
150
+ ` key: '${user.key}',`,
151
+ ` name: ${quoted(user.name)},`,
152
+ ' rules: [',
153
+ rule('view'),
154
+ rule('create'),
155
+ ' // Each user edits only the records they created.',
156
+ ' {',
157
+ ` subject: '${name}',`,
158
+ " action: 'update',",
159
+ ' conditions: { createdBy: ACTOR_ID },',
160
+ ' },',
161
+ ' ],',
162
+ ' },',
163
+ ' ],',
164
+ '} satisfies Module',
165
+ '',
166
+ ].join('\n');
167
+ }
168
+ /**
169
+ * A functional smoke test: an administrator opens the example resource list and the
170
+ * navigation carries the application's menu group.
171
+ */
172
+ export function appSmokeTestSource(name, label) {
173
+ return `import { test } from '@japa/runner'
174
+ import { randomUUID } from 'node:crypto'
175
+ import db from '@adonisjs/lucid/services/db'
176
+ import User from '#models/user'
177
+
178
+ const application = '${name}'
179
+ const label = ${quoted(label.ar)}
180
+
181
+ test.group('${name} application smoke test', () => {
182
+ test('an administrator opens the list and sees the application menu group', async ({
183
+ client,
184
+ assert,
185
+ }) => {
186
+ const knex = db.connection().getWriteClient()
187
+ const unique = randomUUID()
188
+ const admin = await User.create({
189
+ email: \`\${application}-admin-\${unique}@example.test\`,
190
+ password: 'smoke-test-password-123',
191
+ })
192
+ const [role] = await knex('roles')
193
+ .insert({ name: \`\${application}-admin-\${unique}\`, permission_level: 1 })
194
+ .returning('id')
195
+ await knex('role_rules').insert({ role_id: role.id, subject: 'all', action: 'manage' })
196
+ await knex('user_roles').insert({ user_id: admin.id, role_id: role.id })
197
+ const [unit] = await knex('org_units')
198
+ .insert({
199
+ name: 'وحدة الاختبار',
200
+ type: 'root',
201
+ path: \`\${application}_\${unique.replaceAll('-', '_')}\`,
202
+ })
203
+ .returning('id')
204
+ await knex('user_org_units').insert({ user_id: admin.id, org_unit_id: unit.id })
205
+ const page = await client
206
+ .get(\`/resources/\${application}\`)
207
+ .loginAs(admin)
208
+ .header('Accept', 'text/html')
209
+ .withInertia()
210
+ page.assertStatus(200)
211
+ const group = page
212
+ .body()
213
+ .props.navigation.filter((entry: { module: string }) => entry.module === application)
214
+ assert.deepEqual(
215
+ group.map((entry: { name: string }) => entry.name),
216
+ [application]
217
+ )
218
+ assert.equal(group[0].moduleLabel, label)
219
+ })
220
+ })
221
+ `;
222
+ }
223
+ async function exists(path) {
224
+ try {
225
+ await access(path);
226
+ return true;
227
+ }
228
+ catch (error) {
229
+ if (error.code !== 'ENOENT')
230
+ throw error;
231
+ return false;
232
+ }
233
+ }
234
+ /**
235
+ * Plans a new application (module) without writing: its module definition with bilingual
236
+ * labels and default roles, one example resource from the resource generator, the empty
237
+ * module folders, a smoke test and its registration in start/modules.ts.
238
+ */
239
+ export async function planApp(root, options) {
240
+ const name = appName(options.name);
241
+ const ar = options.labelAr?.trim();
242
+ if (!ar)
243
+ throw new Error('--label-ar is required: the Arabic label shown in the menu');
244
+ const label = { ar, en: options.labelEn?.trim() || defaultEnglishLabel(name) };
245
+ // eslint-disable-next-line no-control-regex
246
+ if (/[\u0000-\u001f\u007f]/.test(label.ar + label.en))
247
+ throw new Error('Labels must be a single line without control characters');
248
+ if (await exists(join(root, 'app/modules', name)))
249
+ throw new Error(`Application already exists: app/modules/${name}`);
250
+ const modulesPath = join(root, 'start/modules.ts');
251
+ if (moduleRegistered(await readFile(modulesPath, 'utf8'), name))
252
+ throw new Error(`Application ${name} is already registered in start/modules.ts`);
253
+ const resource = await planResource(root, name, name, {
254
+ moduleSource: appModuleSource(name, label),
255
+ label,
256
+ });
257
+ if (!resource.modules)
258
+ throw new Error(`Application ${name} is already registered`);
259
+ const files = {
260
+ [`app/modules/${name}/module.ts`]: resource.module.source,
261
+ ...resource.files,
262
+ [`tests/functional/${name}/smoke.spec.ts`]: appSmokeTestSource(name, label),
263
+ };
264
+ for (const file of Object.keys(files))
265
+ if (await exists(join(root, file)))
266
+ throw new Error(`Refusing to overwrite ${file}`);
267
+ return {
268
+ name,
269
+ label,
270
+ files,
271
+ directories: MODULE_DIRECTORIES.map((directory) => `app/modules/${name}/${directory}`),
272
+ modules: resource.modules,
273
+ };
274
+ }
275
+ /** Writes a plan; files are created exclusively, start/modules.ts is changed last. */
276
+ export async function writeAppPlan(root, plan) {
277
+ for (const directory of plan.directories)
278
+ await mkdir(join(root, directory), { recursive: true });
279
+ for (const [file, content] of Object.entries(plan.files)) {
280
+ const path = join(root, file);
281
+ await mkdir(dirname(path), { recursive: true });
282
+ await writeFile(path, content, { flag: 'wx' });
283
+ }
284
+ await writeFile(plan.modules.path, plan.modules.source);
285
+ }
@@ -3,15 +3,23 @@ import { WORKFLOW_NAME_RULE } from '../workflows/define_workflow.js';
3
3
  import { ACTOR_ID } from '../auth/conditions.js';
4
4
  /** Field kinds accepted by defineResource, with their storage. */
5
5
  export const FIELD_TYPES = {
6
- string: 'varchar',
7
- text: 'text',
8
- integer: 'integer',
9
- money: 'bigint minor units, decimal string in JSON',
6
+ string: 'varchar(255); min/max length, pattern, format email/url/phone',
7
+ text: 'text; min/max length, pattern',
8
+ integer: 'integer; min/max',
9
+ money: 'bigint minor units, decimal string in JSON; min/max in minor units',
10
+ decimal: 'numeric(precision 18, scale 2 by default); canonical decimal string ("12.50"); min/max',
11
+ percent: 'numeric(precision 7, scale 2 by default); 12.5 means 12.5 %; min/max',
12
+ email: 'varchar(254), trimmed and lower-cased',
13
+ phone: 'varchar(32), stored as +?digits (7 to 15 digits)',
14
+ url: 'varchar(2048), absolute http(s) URLs only',
15
+ enum: 'varchar; one of options [{ value, label }]',
16
+ multiSelect: 'jsonb array of option values in options order; min/max count; filter contains',
17
+ manyToMany: 'join table <owner>_<key> (or table), array of target ids; targets must be viewable',
10
18
  boolean: 'boolean',
11
19
  date: 'date (YYYY-MM-DD)',
12
20
  datetime: 'timestamptz',
13
21
  json: 'jsonb',
14
- attachment: 'attachments row id; per-field accept/maxSize',
22
+ attachment: 'attachments row id; per-file accept/maxSize; multiple: true (max, default 10) stores an ordered jsonb array of ids; images, PDF and text preview inline',
15
23
  belongsTo: 'foreign key, preloaded, restrict on delete',
16
24
  user: 'users foreign key, restrict on delete; choices are active members of the record unit or its ancestors; related as { id, fullName }',
17
25
  hasMany: 'child resource; inline rows saved with the parent',
@@ -26,6 +34,14 @@ export const FIELD_OPTIONS = [
26
34
  'permissionLevel',
27
35
  'sequence',
28
36
  'column',
37
+ 'default (create prefill, server default and column default)',
38
+ 'visibleWhen ({ sibling: value | values }; hidden fields are stored empty and not required)',
39
+ 'min / max (length, numeric limit or count)',
40
+ 'pattern (anchored RegExp source)',
41
+ 'format (string: email, url or phone)',
42
+ 'precision / scale (decimal, percent)',
43
+ 'options (enum, multiSelect)',
44
+ 'resource / table (manyToMany)',
29
45
  ];
30
46
  export const RESOURCE_OPTIONS = [
31
47
  'scoped (required)',
@@ -33,10 +49,11 @@ export const RESOURCE_OPTIONS = [
33
49
  'title (fields that name the record in relations, pickers, tasks and approvals)',
34
50
  'submittable (docStatus, submit/cancel/amend-by-copy)',
35
51
  'version (optimistic locking, default with submittable)',
36
- 'customFields',
52
+ 'unique (composite combinations of fields, partial over active rows)',
37
53
  'list / form / show / serialize / hidden',
38
54
  'actions',
39
55
  'hooks.beforeSave / hooks.afterSave',
56
+ 'validator / model (optional: without validator a VineJS validator is derived from the fields)',
40
57
  ];
41
58
  export const CONDITION_OPERATORS = ['$eq', '$ne', '$in', '$lt', '$gt', '$like'];
42
59
  export const WORKFLOW_STEPS = [
@@ -71,7 +88,12 @@ export const SERVICES = {
71
88
  'SavedViews',
72
89
  'logActivity',
73
90
  ],
74
- 'Documents and workflows': ['defineWorkflow', 'WorkflowEngine', 'workflowListeners'],
91
+ 'Documents and workflows': [
92
+ 'defineWorkflow',
93
+ 'WorkflowEngine',
94
+ 'workflowListeners',
95
+ 'WorkflowDelegations',
96
+ ],
75
97
  'Notifications and messages': [
76
98
  'notify',
77
99
  'notifyWithTemplate',
@@ -85,6 +107,7 @@ export const SERVICES = {
85
107
  'signWebhook',
86
108
  'InboundWebhooks',
87
109
  'openApiDocument',
110
+ 'apiClientSource',
88
111
  'ImportBatches',
89
112
  'renderPrintHtml',
90
113
  'htmlToPdf',
@@ -111,8 +134,11 @@ export const EXTENSION_POINTS = [
111
134
  'Create links with defaults: /resources/<resource>/create?defaults[field]=value',
112
135
  'Domain events <module>.<resource>.{created,updated,deleted,submitted,cancelled,amended} with idempotent listeners',
113
136
  'Module workflows (Module.workflows) with versioned definitions',
137
+ 'Approval delegation while out of office (WorkflowDelegations; never widens record access)',
138
+ 'Step SLA deadlines (sla: hours, dueSoonHours, escalate overdue | notify | reassign, to a recipient or { manager: roleKey }) evaluated by the sla:evaluate job',
114
139
  'Message templates edited per deployment',
115
140
  'Outgoing webhooks and the bearer-token /api/v1 API',
141
+ 'Typed API client of the bearer-token API: GET /api/v1/client.ts per token, or node ace adula:client into clients/<system>/',
116
142
  'Signed inbound webhooks raising inbound.<source>.<event> through the outbox',
117
143
  ];
118
144
  export const OUTSIDE_ADULAJS = [
@@ -127,7 +153,7 @@ export function capabilityCatalog(options = {}) {
127
153
  const lines = [
128
154
  `# AdulaJS capabilities (${ADULA_VERSION})`,
129
155
  '',
130
- 'Generated by `node ace adula:capabilities`. Read this before proposing a module; anything not listed here is not provided by AdulaJS.',
156
+ 'Generated by `node ace adula:capabilities`. Read this before proposing an application (a module under app/modules); anything not listed here is not provided by AdulaJS.',
131
157
  '',
132
158
  '## Resource definition',
133
159
  '',
@@ -1,4 +1,5 @@
1
1
  import type { Settings } from '../services/settings.js';
2
+ import type { Knex } from 'knex';
2
3
  import type { Field, Resource } from '../resource/types.js';
3
4
  import type { WorkflowDefinition } from '../workflows/define_workflow.js';
4
5
  import type { RuntimeHealth } from '../core/health.js';
@@ -12,10 +13,13 @@ export declare function diagnoseUploads(root: string): Promise<Finding>;
12
13
  export declare function diagnoseUi(root: string): Promise<Finding[]>;
13
14
  export declare function diagnoseAgentSkills(root: string): Promise<Finding>;
14
15
  export declare function diagnose(root: string, settings: Settings, production: boolean, env: Record<string, string | undefined>, now?: number): Promise<Finding[]>;
15
- type TableShape = Pick<Resource, 'name' | 'scoped' | 'version' | 'submittable' | 'customFields'> & {
16
- fields: Record<string, Pick<Field, 'column' | 'required' | 'sequence' | 'unique' | 'searchable'> & {
16
+ type TableShape = Pick<Resource, 'name' | 'scoped' | 'version' | 'submittable' | 'unique'> & {
17
+ fields: Record<string, Pick<Field, 'column' | 'required' | 'sequence' | 'unique' | 'searchable' | 'default' | 'visibleWhen'> & {
17
18
  type: string;
18
19
  resource?: string;
20
+ table?: string;
21
+ precision?: number;
22
+ scale?: number;
19
23
  }>;
20
24
  };
21
25
  /**
@@ -39,4 +43,12 @@ export declare function diagnoseWorkflowRoles(workflows: readonly Pick<WorkflowD
39
43
  export declare function diagnoseOutbox(health: Pick<RuntimeHealth, 'outbox'> & {
40
44
  heartbeats: Pick<RuntimeHealth['heartbeats'], 'worker'>;
41
45
  }): Finding;
46
+ /**
47
+ * Compares every registered resource with its live table (see schemaDrift): missing
48
+ * columns, different types, NOT NULL columns the definition lets be empty, missing unique
49
+ * indexes, unique indexes still counting cancelled documents and missing join tables. Run
50
+ * `node ace adula:resource:migration <name>` to add what is missing and apply the
51
+ * relaxing changes.
52
+ */
53
+ export declare function diagnoseResourceSchemas(db: Knex, resources: readonly Resource[]): Promise<Finding>;
42
54
  export {};