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
@@ -2,7 +2,9 @@ import { lstat, readFile, readdir, realpath } from 'node:fs/promises';
2
2
  import { isAbsolute, join, relative } from 'node:path';
3
3
  import { ADULA_VERSION } from '../version.js';
4
4
  import { agentAssets, managedRules, digest } from './agent_assets.js';
5
- import { columnName } from '../resource/define_resource.js';
5
+ import { columnName, joinTable } from '../resource/define_resource.js';
6
+ import { decimalShape } from '../resource/values.js';
7
+ import { describeDrift, inSync, migratable, schemaDrift } from '../database/schema_diff.js';
6
8
  // The deployment volume and backup scripts share this application-relative path.
7
9
  const UPLOADS_PATH = 'storage/uploads';
8
10
  const UPLOADS_WARNING_BYTES = 5_000_000_000;
@@ -265,21 +267,36 @@ export async function diagnose(root, settings, production, env, now = Date.now()
265
267
  /** The columns and indexes createResourceTable derives from a definition, one entry each. */
266
268
  function tableShape(resource) {
267
269
  const shape = new Map();
268
- for (const flag of ['scoped', 'version', 'submittable', 'customFields'])
270
+ for (const flag of ['scoped', 'version', 'submittable'])
269
271
  if (resource[flag])
270
272
  shape.set(flag, flag);
271
273
  for (const [key, field] of Object.entries(resource.fields)) {
272
274
  if (field.type === 'hasMany')
273
275
  continue;
274
- const column = field.column ?? columnName(key);
276
+ const column = field.type === 'manyToMany'
277
+ ? joinTable(resource.name, key, { resource: String(field.resource), table: field.table })
278
+ .table
279
+ : (field.column ?? columnName(key));
275
280
  const traits = [
276
- field.type === 'belongsTo' ? `belongsTo ${field.resource}` : field.type,
277
- ...(field.required || field.sequence ? ['required'] : []),
281
+ field.type === 'belongsTo' || field.type === 'manyToMany'
282
+ ? `${field.type} ${field.resource}`
283
+ : field.type === 'decimal' || field.type === 'percent'
284
+ ? `${field.type}(${Object.values(decimalShape(field)).join(',')})`
285
+ : field.type,
286
+ // The same NOT NULL rule as createResourceTable: visibleWhen may hide (and clear) it.
287
+ ...(field.sequence || (field.required && field.visibleWhen === undefined)
288
+ ? ['required']
289
+ : []),
278
290
  ...(field.unique ? ['unique'] : []),
279
291
  ...(field.searchable ? ['searchable'] : []),
292
+ ...(field.default !== undefined && !Array.isArray(field.default)
293
+ ? [`default ${JSON.stringify(field.default)}`]
294
+ : []),
280
295
  ];
281
296
  shape.set(column, `${column} (${traits.join(', ')})`);
282
297
  }
298
+ for (const keys of resource.unique ?? [])
299
+ shape.set(`unique ${keys.join(',')}`, `unique (${keys.join(', ')})`);
283
300
  return shape;
284
301
  }
285
302
  /**
@@ -373,3 +390,31 @@ export function diagnoseOutbox(health) {
373
390
  : `No outbox event is older than ${OUTBOX_STALE_MS / 1000} s; the worker is ${worker}`,
374
391
  };
375
392
  }
393
+ /**
394
+ * Compares every registered resource with its live table (see schemaDrift): missing
395
+ * columns, different types, NOT NULL columns the definition lets be empty, missing unique
396
+ * indexes, unique indexes still counting cancelled documents and missing join tables. Run
397
+ * `node ace adula:resource:migration <name>` to add what is missing and apply the
398
+ * relaxing changes.
399
+ */
400
+ export async function diagnoseResourceSchemas(db, resources) {
401
+ const problems = [];
402
+ const missing = new Set();
403
+ for (const resource of resources) {
404
+ const drift = await schemaDrift(db, resource);
405
+ if (inSync(drift))
406
+ continue;
407
+ if (migratable(drift))
408
+ missing.add(resource.name);
409
+ problems.push(...describeDrift(drift));
410
+ }
411
+ return {
412
+ check: 'resources.schema',
413
+ status: problems.length ? 'warn' : 'pass',
414
+ message: problems.length
415
+ ? `The database differs from the resource definitions: ${problems.join('; ')}${missing.size
416
+ ? `. Add what is missing with ${[...missing].map((name) => `node ace adula:resource:migration ${name}`).join(', ')}, then migration:run`
417
+ : ''}`
418
+ : 'Every resource table matches its definition',
419
+ };
420
+ }
@@ -36,7 +36,7 @@ export declare const GAP_FIELDS: readonly [{
36
36
  readonly id: "workaround";
37
37
  readonly required: false;
38
38
  }];
39
- export declare const GAPS_TEMPLATE = "# AdulaJS gaps\n\nRecord each limitation of AdulaJS as one entry. Describe AdulaJS capability, not this\nproject: reproduce it on a new application from create-app. Run `node ace adula:gaps report`\nto open AdulaJS's gap form prefilled, then write the issue number in `Issue:`.\n\n<!--\n## GAP-001 \u2014 Short title naming AdulaJS capability\nPackage: adula 1.0.0\nNeeded by: AdulaJS capability that is missing, stated without project details\nTried: AdulaJS extension points tried\nBlocked because: why none of them works\nProposed AdulaJS change: the API, option or fix AdulaJS should offer\nReproduction: steps on a new application from create-app\nAcceptance: the test that proves the gap is closed\nWorkaround: none, or what the project does meanwhile\nIssue:\n-->\n";
39
+ export declare const GAPS_TEMPLATE = "# AdulaJS gaps\n\nRecord each limitation of AdulaJS as one entry. Describe AdulaJS capability, not this\nproject: reproduce it on a new system from create-adulajs. Run `node ace adula:gaps report`\nto open AdulaJS's gap form prefilled, then write the issue number in `Issue:`.\n\n<!--\n## GAP-001 \u2014 Short title naming AdulaJS capability\nPackage: adula 1.0.0\nNeeded by: AdulaJS capability that is missing, stated without project details\nTried: AdulaJS extension points tried\nBlocked because: why none of them works\nProposed AdulaJS change: the API, option or fix AdulaJS should offer\nReproduction: steps on a new system from create-adulajs\nAcceptance: the test that proves the gap is closed\nWorkaround: none, or what the project does meanwhile\nIssue:\n-->\n";
40
40
  export interface GapEntry {
41
41
  title: string;
42
42
  fields: Record<string, string>;
@@ -16,7 +16,7 @@ export const GAP_FIELDS = [
16
16
  export const GAPS_TEMPLATE = `# AdulaJS gaps
17
17
 
18
18
  Record each limitation of AdulaJS as one entry. Describe AdulaJS capability, not this
19
- project: reproduce it on a new application from create-app. Run \`node ace adula:gaps report\`
19
+ project: reproduce it on a new system from create-adulajs. Run \`node ace adula:gaps report\`
20
20
  to open AdulaJS's gap form prefilled, then write the issue number in \`Issue:\`.
21
21
 
22
22
  <!--
@@ -26,7 +26,7 @@ Needed by: AdulaJS capability that is missing, stated without project details
26
26
  Tried: AdulaJS extension points tried
27
27
  Blocked because: why none of them works
28
28
  Proposed AdulaJS change: the API, option or fix AdulaJS should offer
29
- Reproduction: steps on a new application from create-app
29
+ Reproduction: steps on a new system from create-adulajs
30
30
  Acceptance: the test that proves the gap is closed
31
31
  Workaround: none, or what the project does meanwhile
32
32
  Issue:
@@ -1 +1,37 @@
1
- export declare function generateResource(root: string, name: string, module: string): Promise<string[]>;
1
+ import type { Label } from '../resource/types.js';
2
+ /** Every file a resource generation writes, computed without touching the disk. */
3
+ export type ResourcePlan = {
4
+ /** New files relative to the application root; none may exist yet. */
5
+ files: Record<string, string>;
6
+ /** The module definition after registering the resource (created when missing). */
7
+ module: {
8
+ path: string;
9
+ source: string;
10
+ };
11
+ /** start/modules.ts after registering the module, or null when it is already registered. */
12
+ modules: {
13
+ path: string;
14
+ source: string;
15
+ } | null;
16
+ };
17
+ /** A single-quoted TypeScript string literal. */
18
+ export declare function quoted(value: string): string;
19
+ /**
20
+ * Plans a scoped resource with its migration, model, validator, factory and security
21
+ * contract, without writing. `moduleSource` replaces the module definition read from disk
22
+ * (adula:app passes the module it is about to create); `label` sets the resource labels.
23
+ */
24
+ export declare function planResource(root: string, name: string, module: string, options?: {
25
+ moduleSource?: string;
26
+ label?: Label;
27
+ /** Also write a VineJS validator file; by default the fields are the validator (ADR 045). */
28
+ validator?: boolean;
29
+ /** Also write a Lucid model and its factory; AdulaJS itself never reads a model. */
30
+ model?: boolean;
31
+ }): Promise<ResourcePlan>;
32
+ /** Writes a plan: new files first (never overwriting), then the module and the index. */
33
+ export declare function writeResourcePlan(root: string, plan: ResourcePlan): Promise<void>;
34
+ export declare function generateResource(root: string, name: string, module: string, options?: {
35
+ validator?: boolean;
36
+ model?: boolean;
37
+ }): Promise<string[]>;
@@ -1,16 +1,33 @@
1
1
  import { mkdir, readFile, writeFile, access, glob } from 'node:fs/promises';
2
2
  import { dirname, join, resolve } from 'node:path';
3
3
  import { identifier } from '../resource/define_resource.js';
4
- import { appendMarkedItem, moduleSource } from './source_markers.js';
5
- export async function generateResource(root, name, module) {
4
+ import { appendMarkedItem, moduleRegistered, moduleSource, registerModuleSource, } from './source_markers.js';
5
+ /** A single-quoted TypeScript string literal. */
6
+ export function quoted(value) {
7
+ return `'${value.replaceAll('\\', '\\\\').replaceAll("'", "\\'")}'`;
8
+ }
9
+ /**
10
+ * Plans a scoped resource with its migration, model, validator, factory and security
11
+ * contract, without writing. `moduleSource` replaces the module definition read from disk
12
+ * (adula:app passes the module it is about to create); `label` sets the resource labels.
13
+ */
14
+ export async function planResource(root, name, module, options = {}) {
6
15
  identifier(name);
7
16
  identifier(module);
8
17
  for await (const existing of glob(`app/modules/*/resources/${name}.ts`, { cwd: root }))
9
18
  throw new Error(`Refusing to overwrite resource registered at ${existing}`);
10
19
  const base = resolve(root, 'app/modules', module);
11
20
  const title = name.replace(/_/g, ' ');
21
+ const ar = quoted(options.label?.ar ?? title);
22
+ const en = quoted(options.label?.en ?? title);
12
23
  const relative = `app/modules/${module}`;
13
- const resourceSource = `import { defineResource } from 'adula'\nimport Model from '#modules/${module}/models/${name}'\nimport { validator } from '#modules/${module}/validators/${name}'\n\nexport default defineResource({\n name: '${name}', label: { ar: '${title}', en: '${title}' },\n recordLabel: { ar: '${title}', en: '${title}' }, model: Model, scoped: true,\n fields: { title: { type: 'string', label: { ar: 'العنوان', en: 'Title' }, required: true, searchable: true } },\n list: ['title'], form: ['title'], show: ['title'],\n actions: ['view', 'create', 'update', 'delete'], validator,\n})\n`;
24
+ const imports = [
25
+ ...(options.model ? [`import Model from '#modules/${module}/models/${name}'`] : []),
26
+ ...(options.validator
27
+ ? [`import { validator } from '#modules/${module}/validators/${name}'`]
28
+ : []),
29
+ ];
30
+ const resourceSource = `import { defineResource } from 'adula'\n${imports.map((line) => `${line}\n`).join('')}\n// The fields are the source of truth: validation, columns and forms derive from them.\nexport default defineResource({\n name: '${name}', label: { ar: ${ar}, en: ${en} },\n recordLabel: { ar: ${ar}, en: ${en} },${options.model ? ' model: Model,' : ''} scoped: true,\n fields: { title: { type: 'string', label: { ar: 'العنوان', en: 'Title' }, required: true, searchable: true } },\n list: ['title'], form: ['title'], show: ['title'],\n actions: ['view', 'create', 'update', 'delete'],${options.validator ? ' validator,' : ''}\n})\n`;
14
31
  const migration = {
15
32
  name,
16
33
  scoped: true,
@@ -31,16 +48,24 @@ export async function generateResource(root, name, module) {
31
48
  [`${relative}/factories/${name}.ts`]: `import factory from '@adonisjs/lucid/factories'\nimport Model from '#modules/${module}/models/${name}'\nexport default factory.define(Model, ({ faker }) => ({ title: faker.lorem.words(3) })).build()\n`,
32
49
  [`tests/functional/${name}.spec.ts`]: `import { resourceContract } from '#tests/helpers/resource_contract'\n\n// Extend this fixture whenever the resource form or its validator changes.\nresourceContract('${name}', ({ unique }) => ({\n input: { title: 'سجل ' + unique },\n expected: { title: 'سجل ' + unique },\n update: { title: 'سجل محدث ' + unique },\n updated: { title: 'سجل محدث ' + unique },\n}))\n`,
33
50
  };
34
- const modulePath = join(base, 'module.ts');
35
- let current;
36
- try {
37
- current = await readFile(modulePath, 'utf8');
38
- }
39
- catch (error) {
40
- if (error.code !== 'ENOENT')
41
- throw error;
42
- current = moduleSource(module);
51
+ // Opt-in only: the definition derives the validator, and persistence never reads a model.
52
+ if (!options.model) {
53
+ delete files[`${relative}/models/${name}.ts`];
54
+ delete files[`${relative}/factories/${name}.ts`];
43
55
  }
56
+ if (!options.validator)
57
+ delete files[`${relative}/validators/${name}.ts`];
58
+ const modulePath = join(base, 'module.ts');
59
+ let current = options.moduleSource;
60
+ if (current === undefined)
61
+ try {
62
+ current = await readFile(modulePath, 'utf8');
63
+ }
64
+ catch (error) {
65
+ if (error.code !== 'ENOENT')
66
+ throw error;
67
+ current = moduleSource(module);
68
+ }
44
69
  if (!current.includes('// adula:imports') || !current.includes('/* adula:resources */'))
45
70
  throw new Error('Module registration markers are missing; no files were changed');
46
71
  const modulesPath = join(root, 'start/modules.ts');
@@ -57,14 +82,32 @@ export async function generateResource(root, name, module) {
57
82
  throw error;
58
83
  }
59
84
  }
60
- for (const [file, content] of Object.entries(files)) {
85
+ return {
86
+ files,
87
+ module: {
88
+ path: modulePath,
89
+ source: appendMarkedItem(current.replace('// adula:imports', `import resource_${name} from './resources/${name}.js'
90
+ // adula:imports`), '/* adula:resources */', `resource_${name}`),
91
+ },
92
+ modules: moduleRegistered(modules, module)
93
+ ? null
94
+ : { path: modulesPath, source: registerModuleSource(modules, module) },
95
+ };
96
+ }
97
+ /** Writes a plan: new files first (never overwriting), then the module and the index. */
98
+ export async function writeResourcePlan(root, plan) {
99
+ for (const [file, content] of Object.entries(plan.files)) {
61
100
  const path = join(root, file);
62
101
  await mkdir(dirname(path), { recursive: true });
63
102
  await writeFile(path, content, { flag: 'wx' });
64
103
  }
65
- await mkdir(base, { recursive: true });
66
- await writeFile(modulePath, appendMarkedItem(current.replace('// adula:imports', `import resource_${name} from './resources/${name}.js'\n// adula:imports`), '/* adula:resources */', `resource_${name}`));
67
- if (!modules.includes(`'#modules/${module}/module'`))
68
- await writeFile(modulesPath, appendMarkedItem(modules.replace('// adula:imports', `import module_${module} from '#modules/${module}/module'\n// adula:imports`), '/* adula:modules */', `module_${module}`));
69
- return Object.keys(files);
104
+ await mkdir(dirname(plan.module.path), { recursive: true });
105
+ await writeFile(plan.module.path, plan.module.source);
106
+ if (plan.modules)
107
+ await writeFile(plan.modules.path, plan.modules.source);
108
+ }
109
+ export async function generateResource(root, name, module, options = {}) {
110
+ const plan = await planResource(root, name, module, options);
111
+ await writeResourcePlan(root, plan);
112
+ return Object.keys(plan.files);
70
113
  }
@@ -1,22 +1,19 @@
1
- import type { Resource } from '../resource/types.js';
1
+ import type { Field, Resource } from '../resource/types.js';
2
+ /**
3
+ * The parts of one field that decide its table shape (and keep the snapshot a valid
4
+ * Field): type and label, relation target and join table, column, constraints that
5
+ * become indexes or NOT NULL, numeric shape, the column default and enum options.
6
+ */
7
+ export declare function fieldSnapshot(field: Field): Field;
2
8
  /**
3
9
  * The part of a resource definition createResourceTable reads, as a generated
4
10
  * create-migration embeds it. Labels are kept so the migration stays readable.
5
11
  */
6
- export declare function resourceSnapshot(resource: Pick<Resource, 'name' | 'scoped' | 'version' | 'submittable' | 'customFields' | 'fields'>): {
12
+ export declare function resourceSnapshot(resource: Pick<Resource, 'name' | 'scoped' | 'version' | 'submittable' | 'fields' | 'unique'>): {
7
13
  fields: {
8
- [k: string]: {
9
- sequence?: string | undefined;
10
- searchable?: boolean | undefined;
11
- unique?: boolean | undefined;
12
- required?: boolean | undefined;
13
- column?: string | undefined;
14
- resource?: string | undefined;
15
- type: "string" | "boolean" | "text" | "integer" | "money" | "date" | "datetime" | "json" | "attachment" | "belongsTo" | "user" | "hasMany" | "lookup";
16
- label: import("../resource/types.js").Label;
17
- };
14
+ [k: string]: Field;
18
15
  };
19
- customFields?: boolean | undefined;
16
+ unique?: string[][] | undefined;
20
17
  submittable?: boolean | undefined;
21
18
  version?: boolean | undefined;
22
19
  name: string;
@@ -1,4 +1,33 @@
1
+ import { decimalShape } from '../resource/values.js';
1
2
  const EMBEDDED = /(createResourceTable\([^,]+,\s*)(\{[\s\S]*\})(\s*\)\s*\})/;
3
+ /**
4
+ * The parts of one field that decide its table shape (and keep the snapshot a valid
5
+ * Field): type and label, relation target and join table, column, constraints that
6
+ * become indexes or NOT NULL, numeric shape, the column default and enum options.
7
+ */
8
+ export function fieldSnapshot(field) {
9
+ return {
10
+ type: field.type,
11
+ label: field.label,
12
+ ...('resource' in field && field.type !== 'hasMany' ? { resource: field.resource } : {}),
13
+ ...(field.type === 'manyToMany' && field.table ? { table: field.table } : {}),
14
+ ...(field.column ? { column: field.column } : {}),
15
+ ...(field.required ? { required: true } : {}),
16
+ ...(field.unique ? { unique: true } : {}),
17
+ ...(field.searchable ? { searchable: true } : {}),
18
+ ...(field.sequence ? { sequence: field.sequence } : {}),
19
+ // The resolved numeric shape: replay never depends on the package's defaults.
20
+ ...(field.type === 'decimal' || field.type === 'percent' ? decimalShape(field) : {}),
21
+ // Decides nullability: a required field that visibleWhen may hide is a nullable column.
22
+ ...(field.visibleWhen !== undefined ? { visibleWhen: field.visibleWhen } : {}),
23
+ ...(field.default !== undefined && !Array.isArray(field.default)
24
+ ? { default: field.default }
25
+ : {}),
26
+ ...('options' in field ? { options: field.options } : {}),
27
+ // A multiple attachment field is a jsonb column instead of a foreign key.
28
+ ...(field.type === 'attachment' && field.multiple ? { multiple: true } : {}),
29
+ };
30
+ }
2
31
  /**
3
32
  * The part of a resource definition createResourceTable reads, as a generated
4
33
  * create-migration embeds it. Labels are kept so the migration stays readable.
@@ -9,22 +38,10 @@ export function resourceSnapshot(resource) {
9
38
  scoped: resource.scoped,
10
39
  ...(resource.version ? { version: true } : {}),
11
40
  ...(resource.submittable ? { submittable: true } : {}),
12
- ...(resource.customFields ? { customFields: true } : {}),
41
+ ...(resource.unique?.length ? { unique: resource.unique.map((keys) => [...keys]) } : {}),
13
42
  fields: Object.fromEntries(Object.entries(resource.fields)
14
43
  .filter(([, field]) => field.type !== 'hasMany')
15
- .map(([key, field]) => [
16
- key,
17
- {
18
- type: field.type,
19
- label: field.label,
20
- ...(field.type === 'belongsTo' ? { resource: field.resource } : {}),
21
- ...(field.column ? { column: field.column } : {}),
22
- ...(field.required ? { required: true } : {}),
23
- ...(field.unique ? { unique: true } : {}),
24
- ...(field.searchable ? { searchable: true } : {}),
25
- ...(field.sequence ? { sequence: field.sequence } : {}),
26
- },
27
- ])),
44
+ .map(([key, field]) => [key, fieldSnapshot(field)])),
28
45
  };
29
46
  }
30
47
  /** The resource name embedded in a generated create-migration, if the source is one. */
@@ -9,3 +9,13 @@ export declare function moduleSource(name: string, options?: {
9
9
  reference?: boolean;
10
10
  typed?: boolean;
11
11
  }): string;
12
+ /**
13
+ * Registers a module in the application's start/modules.ts source: one import before
14
+ * `// adula:imports` and one item in the `/* adula:modules *\/` list. Shared by
15
+ * adula:module:add, adula:resource and adula:app so the three stay identical.
16
+ */
17
+ export declare function registerModuleSource(source: string, name: string): string;
18
+ /** True when start/modules.ts already imports the module. */
19
+ export declare function moduleRegistered(source: string, name: string): boolean;
20
+ /** The folders every application-owned module starts with. */
21
+ export declare const MODULE_DIRECTORIES: readonly ["models", "resources", "validators", "migrations", "factories", "listeners", "jobs", "workflows", "reports", "pages", "tests"];
@@ -39,3 +39,32 @@ export function moduleSource(name, options = {}) {
39
39
  '',
40
40
  ].join('\n');
41
41
  }
42
+ /**
43
+ * Registers a module in the application's start/modules.ts source: one import before
44
+ * `// adula:imports` and one item in the `/* adula:modules *\/` list. Shared by
45
+ * adula:module:add, adula:resource and adula:app so the three stay identical.
46
+ */
47
+ export function registerModuleSource(source, name) {
48
+ if (!source.includes('// adula:imports') || !source.includes('/* adula:modules */'))
49
+ throw new Error('Module index registration markers are missing');
50
+ const alias = `module_${name}`;
51
+ return appendMarkedItem(source.replace('// adula:imports', `import ${alias} from '#modules/${name}/module'\n// adula:imports`), '/* adula:modules */', alias);
52
+ }
53
+ /** True when start/modules.ts already imports the module. */
54
+ export function moduleRegistered(source, name) {
55
+ return source.includes(`'#modules/${name}/module'`);
56
+ }
57
+ /** The folders every application-owned module starts with. */
58
+ export const MODULE_DIRECTORIES = [
59
+ 'models',
60
+ 'resources',
61
+ 'validators',
62
+ 'migrations',
63
+ 'factories',
64
+ 'listeners',
65
+ 'jobs',
66
+ 'workflows',
67
+ 'reports',
68
+ 'pages',
69
+ 'tests',
70
+ ];
@@ -6,6 +6,8 @@ export type ActivityEntry = {
6
6
  actorId: number;
7
7
  action: string;
8
8
  changes?: Record<string, unknown>;
9
+ /** The administrator acting as actorId through impersonation; stored as impersonatedBy. */
10
+ impersonatorId?: number | null;
9
11
  };
10
12
  export type ActivityFilters = {
11
13
  resource?: string;
@@ -6,12 +6,18 @@ export function pageLimit(limit, fallback = 50) {
6
6
  return Math.min(value, 100);
7
7
  }
8
8
  export async function logActivity(db, entry) {
9
+ // Only the trusted impersonatorId may mark an entry as impersonated.
10
+ const changes = { ...entry.changes };
11
+ delete changes.impersonatedBy;
9
12
  await db('activities').insert({
10
13
  resource: entry.resource,
11
14
  record_id: entry.recordId,
12
15
  actor_id: entry.actorId,
13
16
  action: entry.action,
14
- changes: JSON.stringify(entry.changes ?? {}),
17
+ changes: JSON.stringify({
18
+ ...changes,
19
+ ...(entry.impersonatorId ? { impersonatedBy: entry.impersonatorId } : {}),
20
+ }),
15
21
  });
16
22
  }
17
23
  function boundary(value, end) {
@@ -0,0 +1,38 @@
1
+ import type { Knex } from 'knex';
2
+ /**
3
+ * Whether any user holds an unconditional `manage all` grant, which is what the
4
+ * administration area requires. Disabled holders still count: disabling the last
5
+ * administrator must not reopen bootstrap paths such as self-signup.
6
+ */
7
+ export declare function administratorExists(knex: Knex | Knex.Transaction): Promise<boolean>;
8
+ /** What installation did to secure a pre-existing account before promoting it. */
9
+ export type InstallAccountRotation = {
10
+ sessions: number;
11
+ tokens: number;
12
+ resetTokens: number;
13
+ invitations: number;
14
+ };
15
+ /**
16
+ * Resolves the installation administrator by e-mail. A missing account is created
17
+ * through `create` only while the application has no administrator yet, so a
18
+ * mistyped address on an existing installation never mints a new privileged user.
19
+ *
20
+ * An account that already exists while no administrator does may have been
21
+ * self-registered by anyone who guessed the address (pre-registration takeover).
22
+ * When `rotatePassword` is given it replaces the password, every session and API
23
+ * token of that account ends, and the event is recorded before it is promoted.
24
+ * Callers that just created the account themselves omit it (`--keep-password`).
25
+ */
26
+ export declare function resolveInstallAdministrator(knex: Knex, email: string, create: () => Promise<number>, options?: {
27
+ rotatePassword?: (userId: number) => Promise<void>;
28
+ }): Promise<{
29
+ id: number;
30
+ created: boolean;
31
+ rotated?: InstallAccountRotation;
32
+ }>;
33
+ /**
34
+ * Idempotently installs the root unit, the bootstrap `administrator` role with its
35
+ * `manage all` grant, and assigns it to the user. A transaction-scoped advisory
36
+ * lock makes repeated and concurrent installation safe.
37
+ */
38
+ export declare function grantInstallAdministrator(knex: Knex, userId: number, version: string): Promise<void>;
@@ -0,0 +1,129 @@
1
+ import { Settings } from '../services/settings.js';
2
+ import { logActivity } from './activity.js';
3
+ /**
4
+ * Whether any user holds an unconditional `manage all` grant, which is what the
5
+ * administration area requires. Disabled holders still count: disabling the last
6
+ * administrator must not reopen bootstrap paths such as self-signup.
7
+ */
8
+ export async function administratorExists(knex) {
9
+ const row = await knex('user_roles')
10
+ .join('role_rules', 'role_rules.role_id', 'user_roles.role_id')
11
+ .where({ 'role_rules.subject': 'all', 'role_rules.action': 'manage' })
12
+ .where('role_rules.inverted', false)
13
+ .whereNull('role_rules.conditions')
14
+ .whereNull('role_rules.fields')
15
+ .first('user_roles.user_id');
16
+ return Boolean(row);
17
+ }
18
+ /**
19
+ * Ends every way into an account: browser sessions (the `user_sessions` index and
20
+ * the database session store), personal API tokens, outstanding recovery links and
21
+ * pending invitations for the address. Tables are application-owned, so each is used
22
+ * only when it exists.
23
+ */
24
+ async function endAccountAccess(knex, userId, email) {
25
+ let sessions = 0;
26
+ let tokens = 0;
27
+ let resetTokens = 0;
28
+ let invitations = 0;
29
+ if (await knex.schema.hasTable('user_sessions')) {
30
+ const rows = await knex('user_sessions')
31
+ .where({ user_id: userId })
32
+ .select('id');
33
+ if (rows.length && (await knex.schema.hasTable('sessions')))
34
+ await knex('sessions')
35
+ .whereIn('id', rows.map((row) => row.id))
36
+ .delete();
37
+ sessions = Number(await knex('user_sessions').where({ user_id: userId }).delete());
38
+ }
39
+ if (await knex.schema.hasTable('auth_access_tokens'))
40
+ tokens = Number(await knex('auth_access_tokens').where({ tokenable_id: userId }).delete());
41
+ // A recovery link requested while signup was open would otherwise outlive the rotation.
42
+ if (await knex.schema.hasTable('password_reset_tokens'))
43
+ resetTokens = Number(await knex('password_reset_tokens').where({ user_id: userId }).whereNull('used_at').delete());
44
+ if (await knex.schema.hasTable('user_invitations'))
45
+ invitations = Number(await knex('user_invitations')
46
+ .whereRaw('lower(email) = lower(?)', [email])
47
+ .whereNull('accepted_at')
48
+ .delete());
49
+ return { sessions, tokens, resetTokens, invitations };
50
+ }
51
+ /**
52
+ * Resolves the installation administrator by e-mail. A missing account is created
53
+ * through `create` only while the application has no administrator yet, so a
54
+ * mistyped address on an existing installation never mints a new privileged user.
55
+ *
56
+ * An account that already exists while no administrator does may have been
57
+ * self-registered by anyone who guessed the address (pre-registration takeover).
58
+ * When `rotatePassword` is given it replaces the password, every session and API
59
+ * token of that account ends, and the event is recorded before it is promoted.
60
+ * Callers that just created the account themselves omit it (`--keep-password`).
61
+ */
62
+ export async function resolveInstallAdministrator(knex, email, create, options = {}) {
63
+ const existing = await knex('users').whereRaw('lower(email) = lower(?)', [email]).first('id');
64
+ const bootstrap = !(await administratorExists(knex));
65
+ if (existing) {
66
+ const id = Number(existing.id);
67
+ if (!bootstrap || !options.rotatePassword)
68
+ return { id, created: false };
69
+ await options.rotatePassword(id);
70
+ const rotated = await endAccountAccess(knex, id, email);
71
+ await logActivity(knex, {
72
+ resource: 'core.users',
73
+ recordId: id,
74
+ actorId: id,
75
+ action: 'install_rotate_credentials',
76
+ changes: rotated,
77
+ });
78
+ return { id, created: false, rotated };
79
+ }
80
+ if (!bootstrap)
81
+ throw new Error('Administrator user does not exist. An administrator already exists, so adula:install only creates the first one; check the e-mail address.');
82
+ return { id: await create(), created: true };
83
+ }
84
+ /**
85
+ * Idempotently installs the root unit, the bootstrap `administrator` role with its
86
+ * `manage all` grant, and assigns it to the user. A transaction-scoped advisory
87
+ * lock makes repeated and concurrent installation safe.
88
+ */
89
+ export async function grantInstallAdministrator(knex, userId, version) {
90
+ await knex.transaction(async (trx) => {
91
+ await trx.raw('SELECT pg_advisory_xact_lock(717011)');
92
+ let root = await trx('org_units').whereNull('parent_id').first();
93
+ if (!root) {
94
+ const [created] = await trx('org_units')
95
+ .insert({ name: 'الجهة', type: 'root', path: 'root' })
96
+ .returning('*');
97
+ await trx('org_units')
98
+ .where('id', created.id)
99
+ .update({ path: String(created.id) });
100
+ root = created;
101
+ }
102
+ let role = await trx('roles').where('name', 'administrator').first();
103
+ if (!role) {
104
+ const [created] = await trx('roles')
105
+ .insert({ name: 'administrator', key: 'administrator', permission_level: 1 })
106
+ .returning('*');
107
+ role = created;
108
+ }
109
+ else if (!role.key && !(await trx('roles').where('key', 'administrator').first()))
110
+ await trx('roles').where('id', role.id).update({ key: 'administrator' });
111
+ // Repair a missing bootstrap grant even when the role already exists.
112
+ if (!(await trx('role_rules')
113
+ .where({ role_id: role.id, subject: 'all', action: 'manage', inverted: false })
114
+ .whereNull('conditions')
115
+ .whereNull('fields')
116
+ .first()))
117
+ await trx('role_rules').insert({ role_id: role.id, subject: 'all', action: 'manage' });
118
+ if (!(await trx('user_roles')
119
+ .where({ user_id: userId, role_id: role.id })
120
+ .whereNull('org_unit_id')
121
+ .first()))
122
+ await trx('user_roles').insert({ user_id: userId, role_id: role.id });
123
+ await trx('user_org_units')
124
+ .insert({ user_id: userId, org_unit_id: root.id })
125
+ .onConflict(['user_id', 'org_unit_id'])
126
+ .ignore();
127
+ await new Settings(trx).set('adula.version', version);
128
+ });
129
+ }
@@ -0,0 +1,20 @@
1
+ /**
2
+ * In-house allowlist sanitizer for administrator-written print markup (ADR 048). It is
3
+ * not a general HTML parser: it keeps a fixed set of structural tags and four attributes
4
+ * and drops everything else, so the output can only lay out escaped text.
5
+ *
6
+ * - Allowed tags: ALLOWED_TAGS. Any other tag is removed; the contents of DROPPED_WITH_CONTENT
7
+ * (script, style, iframe, svg, form, …) are removed with it.
8
+ * - Allowed attributes: class (word characters and dashes), colspan/rowspan (1–99),
9
+ * dir (rtl/ltr/auto) and style restricted by sanitizeStyle. Every other attribute,
10
+ * including on* handlers, href and src, is removed.
11
+ * - An attribute value with `&`, `\`, `{{` or `}}` is removed: entities and CSS escapes
12
+ * could hide a URL, and template values may not flow into attributes.
13
+ * - Comments, doctype and processing instructions are removed; a stray `<` becomes `&lt;`.
14
+ * - Closing tags are balanced against the open allowed tags; unclosed ones are closed.
15
+ */
16
+ export declare const ALLOWED_TAGS: Set<string>;
17
+ /** A style attribute reduced to allowlisted properties with plain values; '' when none survive. */
18
+ export declare function sanitizeStyle(style: string): string;
19
+ /** Sanitizes administrator print markup; see the module comment for the rules. */
20
+ export declare function sanitizePrintHtml(input: string): string;