adula 2.1.0 → 2.3.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 (269) hide show
  1. package/README.md +149 -18
  2. package/build/agent/AGENTS.template.md +4 -4
  3. package/build/agent/capabilities.md +22 -12
  4. package/build/agent/skills/adula-frontend-design/SKILL.md +6 -4
  5. package/build/agent/skills/idea-review/SKILL.md +2 -2
  6. package/build/commands/adula_assistant_prune.d.ts +10 -0
  7. package/build/commands/adula_assistant_prune.js +12 -0
  8. package/build/commands/adula_outbox.d.ts +10 -0
  9. package/build/commands/adula_outbox.js +11 -0
  10. package/build/commands/adula_restore_reconcile.d.ts +10 -0
  11. package/build/commands/adula_restore_reconcile.js +34 -0
  12. package/build/commands/adula_runtime_health.d.ts +10 -0
  13. package/build/commands/adula_runtime_health.js +27 -0
  14. package/build/commands/adula_uploads_prune.d.ts +10 -0
  15. package/build/commands/adula_uploads_prune.js +16 -0
  16. package/build/commands/app.d.ts +10 -0
  17. package/build/commands/app.js +64 -0
  18. package/build/commands/backup_create.d.ts +11 -0
  19. package/build/commands/backup_create.js +99 -0
  20. package/build/commands/backup_open.d.ts +16 -0
  21. package/build/commands/backup_open.js +48 -0
  22. package/build/commands/backup_restore_files.d.ts +11 -0
  23. package/build/commands/backup_restore_files.js +44 -0
  24. package/build/commands/backup_restore_test.d.ts +12 -0
  25. package/build/commands/backup_restore_test.js +188 -0
  26. package/build/commands/backup_seal.d.ts +12 -0
  27. package/build/commands/backup_seal.js +36 -0
  28. package/build/commands/backup_services.d.ts +33 -0
  29. package/build/commands/backup_services.js +6 -0
  30. package/build/commands/backup_verify.d.ts +9 -0
  31. package/build/commands/backup_verify.js +59 -0
  32. package/build/commands/backup_verify_snapshot.d.ts +10 -0
  33. package/build/commands/backup_verify_snapshot.js +37 -0
  34. package/build/commands/client.d.ts +16 -0
  35. package/build/commands/client.js +71 -0
  36. package/build/commands/doctor.js +21 -1
  37. package/build/commands/install.d.ts +8 -0
  38. package/build/commands/install.js +69 -45
  39. package/build/commands/main.d.ts +3 -2
  40. package/build/commands/main.js +32 -0
  41. package/build/commands/module_add.js +4 -20
  42. package/build/commands/resource.d.ts +2 -0
  43. package/build/commands/resource.js +12 -3
  44. package/build/commands/resource_migration.d.ts +15 -0
  45. package/build/commands/resource_migration.js +81 -0
  46. package/build/commands/resource_snapshot.d.ts +2 -0
  47. package/build/commands/resource_snapshot.js +21 -4
  48. package/build/commands/sla_evaluate.d.ts +14 -0
  49. package/build/commands/sla_evaluate.js +16 -0
  50. package/build/commands/ui.js +4 -2
  51. package/build/commands/ui_css.d.ts +9 -0
  52. package/build/commands/ui_css.js +19 -0
  53. package/build/commands/upgrade.d.ts +1 -1
  54. package/build/commands/upgrade.js +1 -1
  55. package/build/configure.js +1 -1
  56. package/build/database/migrations/1770000000020_two_factor.d.ts +5 -0
  57. package/build/database/migrations/1770000000020_two_factor.js +10 -0
  58. package/build/database/migrations/1770000000041_import_modes.d.ts +5 -0
  59. package/build/database/migrations/1770000000041_import_modes.js +10 -0
  60. package/build/database/migrations/1770000000042_sync_jobs.d.ts +5 -0
  61. package/build/database/migrations/1770000000042_sync_jobs.js +10 -0
  62. package/build/database/migrations/1770000000043_notification_channels.d.ts +5 -0
  63. package/build/database/migrations/1770000000043_notification_channels.js +10 -0
  64. package/build/database/migrations/1770000000044_channel_confirmations.d.ts +5 -0
  65. package/build/database/migrations/1770000000044_channel_confirmations.js +10 -0
  66. package/build/database/migrations/1770000000045_import_leases.d.ts +5 -0
  67. package/build/database/migrations/1770000000045_import_leases.js +10 -0
  68. package/build/database/migrations/1770000000046_workflow_delegation_sla.d.ts +5 -0
  69. package/build/database/migrations/1770000000046_workflow_delegation_sla.js +10 -0
  70. package/build/database/migrations/1770000000049_print_templates.d.ts +5 -0
  71. package/build/database/migrations/1770000000049_print_templates.js +10 -0
  72. package/build/database/migrations/1770000000051_comment_notifications.d.ts +5 -0
  73. package/build/database/migrations/1770000000051_comment_notifications.js +10 -0
  74. package/build/database/migrations/1770000000054_cloud_backups.d.ts +5 -0
  75. package/build/database/migrations/1770000000054_cloud_backups.js +10 -0
  76. package/build/database/migrations/1770000000055_ai_assistant.d.ts +5 -0
  77. package/build/database/migrations/1770000000055_ai_assistant.js +10 -0
  78. package/build/database/migrations/1770000000056_appearance.d.ts +5 -0
  79. package/build/database/migrations/1770000000056_appearance.js +10 -0
  80. package/build/index.d.ts +87 -11
  81. package/build/index.js +50 -7
  82. package/build/providers/adula_provider.d.ts +2 -0
  83. package/build/providers/adula_provider.js +7 -0
  84. package/build/src/admin/contracts.js +1 -1
  85. package/build/src/admin/controller.d.ts +14 -1
  86. package/build/src/admin/controller.js +91 -13
  87. package/build/src/admin/errors.d.ts +32 -0
  88. package/build/src/admin/errors.js +63 -1
  89. package/build/src/admin/presentation.d.ts +21 -2
  90. package/build/src/admin/resource/editor.d.ts +60 -0
  91. package/build/src/admin/resource/editor.js +345 -0
  92. package/build/src/admin/resource/export.d.ts +54 -0
  93. package/build/src/admin/resource/export.js +262 -0
  94. package/build/src/admin/resource/lifecycle.d.ts +23 -0
  95. package/build/src/admin/resource/lifecycle.js +91 -0
  96. package/build/src/admin/resource/query.d.ts +111 -0
  97. package/build/src/admin/resource/query.js +595 -0
  98. package/build/src/admin/resource/read.d.ts +109 -0
  99. package/build/src/admin/resource/read.js +388 -0
  100. package/build/src/admin/resource/shared.d.ts +93 -0
  101. package/build/src/admin/resource/shared.js +265 -0
  102. package/build/src/admin/resource/trash.d.ts +10 -0
  103. package/build/src/admin/resource/trash.js +56 -0
  104. package/build/src/admin/resource/write.d.ts +57 -0
  105. package/build/src/admin/resource/write.js +603 -0
  106. package/build/src/admin/resource_service.d.ts +80 -193
  107. package/build/src/admin/resource_service.js +81 -1343
  108. package/build/src/admin/resource_tools.d.ts +111 -0
  109. package/build/src/admin/resource_tools.js +139 -0
  110. package/build/src/ai/assistant.d.ts +100 -0
  111. package/build/src/ai/assistant.js +487 -0
  112. package/build/src/ai/client.d.ts +49 -0
  113. package/build/src/ai/client.js +85 -0
  114. package/build/src/ai/prompt.d.ts +23 -0
  115. package/build/src/ai/prompt.js +83 -0
  116. package/build/src/ai/settings.d.ts +56 -0
  117. package/build/src/ai/settings.js +214 -0
  118. package/build/src/ai/usage.d.ts +16 -0
  119. package/build/src/ai/usage.js +33 -0
  120. package/build/src/appearance/appearance.d.ts +134 -0
  121. package/build/src/appearance/appearance.js +461 -0
  122. package/build/src/appearance/colors.d.ts +43 -0
  123. package/build/src/appearance/colors.js +99 -0
  124. package/build/src/appearance/logo.d.ts +32 -0
  125. package/build/src/appearance/logo.js +112 -0
  126. package/build/src/attachments/attachment_service.d.ts +46 -2
  127. package/build/src/attachments/attachment_service.js +96 -4
  128. package/build/src/auth/actor_store.d.ts +5 -1
  129. package/build/src/auth/actor_store.js +8 -4
  130. package/build/src/auth/conditions.d.ts +5 -0
  131. package/build/src/auth/conditions.js +26 -3
  132. package/build/src/auth/sql.js +17 -5
  133. package/build/src/auth/two_factor.d.ts +96 -0
  134. package/build/src/auth/two_factor.js +259 -0
  135. package/build/src/backups/archive.d.ts +52 -0
  136. package/build/src/backups/archive.js +362 -0
  137. package/build/src/backups/cloud_backups.d.ts +133 -0
  138. package/build/src/backups/cloud_backups.js +650 -0
  139. package/build/src/backups/doctor.d.ts +7 -0
  140. package/build/src/backups/doctor.js +55 -0
  141. package/build/src/backups/providers.d.ts +81 -0
  142. package/build/src/backups/providers.js +470 -0
  143. package/build/src/collaboration/assignments.d.ts +59 -2
  144. package/build/src/collaboration/assignments.js +196 -74
  145. package/build/src/collaboration/record_collaboration.d.ts +21 -4
  146. package/build/src/collaboration/record_collaboration.js +126 -51
  147. package/build/src/collaboration/shared.d.ts +24 -0
  148. package/build/src/collaboration/shared.js +34 -0
  149. package/build/src/commands/app_scaffold.d.ts +72 -0
  150. package/build/src/commands/app_scaffold.js +285 -0
  151. package/build/src/commands/capabilities.js +35 -9
  152. package/build/src/commands/doctor.d.ts +24 -2
  153. package/build/src/commands/doctor.js +81 -6
  154. package/build/src/commands/gap_report.d.ts +1 -1
  155. package/build/src/commands/gap_report.js +2 -2
  156. package/build/src/commands/generator.d.ts +37 -1
  157. package/build/src/commands/generator.js +61 -18
  158. package/build/src/commands/snapshot.d.ts +24 -13
  159. package/build/src/commands/snapshot.js +54 -14
  160. package/build/src/commands/source_markers.d.ts +10 -0
  161. package/build/src/commands/source_markers.js +29 -0
  162. package/build/src/core/activity.d.ts +2 -0
  163. package/build/src/core/activity.js +7 -1
  164. package/build/src/core/administrators.d.ts +38 -0
  165. package/build/src/core/administrators.js +145 -0
  166. package/build/src/core/avatar_image.d.ts +33 -0
  167. package/build/src/core/avatar_image.js +278 -0
  168. package/build/src/core/html_sanitizer.d.ts +20 -0
  169. package/build/src/core/html_sanitizer.js +261 -0
  170. package/build/src/core/like.d.ts +5 -0
  171. package/build/src/core/like.js +5 -0
  172. package/build/src/core/lookups.d.ts +80 -0
  173. package/build/src/core/lookups.js +319 -0
  174. package/build/src/core/mail_settings.d.ts +83 -0
  175. package/build/src/core/mail_settings.js +274 -0
  176. package/build/src/core/mail_test.d.ts +16 -0
  177. package/build/src/core/mail_test.js +81 -6
  178. package/build/src/core/message_templates.d.ts +15 -2
  179. package/build/src/core/message_templates.js +81 -11
  180. package/build/src/core/module_seed.js +2 -1
  181. package/build/src/core/notification_channels.d.ts +235 -0
  182. package/build/src/core/notification_channels.js +660 -0
  183. package/build/src/core/roles.js +26 -9
  184. package/build/src/core/saved_views.d.ts +8 -1
  185. package/build/src/core/saved_views.js +91 -26
  186. package/build/src/core/sequences.d.ts +32 -0
  187. package/build/src/core/sequences.js +97 -0
  188. package/build/src/core/settings.d.ts +5 -0
  189. package/build/src/core/settings.js +31 -3
  190. package/build/src/core/template_language.d.ts +61 -0
  191. package/build/src/core/template_language.js +141 -0
  192. package/build/src/core/ui_preferences.d.ts +10 -0
  193. package/build/src/core/ui_preferences.js +15 -1
  194. package/build/src/core/user_avatars.d.ts +79 -0
  195. package/build/src/core/user_avatars.js +186 -0
  196. package/build/src/core/user_invitations.d.ts +5 -1
  197. package/build/src/core/user_invitations.js +7 -1
  198. package/build/src/core/user_preferences.d.ts +36 -0
  199. package/build/src/core/user_preferences.js +125 -0
  200. package/build/src/core/users.d.ts +2 -0
  201. package/build/src/core/users.js +5 -3
  202. package/build/src/database/calendar_days.d.ts +19 -0
  203. package/build/src/database/calendar_days.js +36 -0
  204. package/build/src/database/schema.d.ts +201 -2
  205. package/build/src/database/schema.js +713 -59
  206. package/build/src/database/schema_diff.d.ts +70 -0
  207. package/build/src/database/schema_diff.js +190 -0
  208. package/build/src/events/record_mutation.d.ts +2 -1
  209. package/build/src/events/record_mutation.js +1 -0
  210. package/build/src/integrations/api_client.d.ts +37 -0
  211. package/build/src/integrations/api_client.js +567 -0
  212. package/build/src/integrations/import_adapters.d.ts +37 -0
  213. package/build/src/integrations/import_adapters.js +35 -0
  214. package/build/src/integrations/imports.d.ts +130 -16
  215. package/build/src/integrations/imports.js +434 -73
  216. package/build/src/integrations/openapi.d.ts +3 -1
  217. package/build/src/integrations/openapi.js +465 -31
  218. package/build/src/integrations/outbound.d.ts +94 -0
  219. package/build/src/integrations/outbound.js +276 -0
  220. package/build/src/integrations/print.d.ts +22 -1
  221. package/build/src/integrations/print.js +68 -22
  222. package/build/src/integrations/print_templates.d.ts +216 -0
  223. package/build/src/integrations/print_templates.js +1017 -0
  224. package/build/src/integrations/sync_jobs.d.ts +139 -0
  225. package/build/src/integrations/sync_jobs.js +416 -0
  226. package/build/src/integrations/webhooks.d.ts +12 -12
  227. package/build/src/integrations/webhooks.js +34 -43
  228. package/build/src/integrations/xlsx.d.ts +41 -0
  229. package/build/src/integrations/xlsx.js +519 -0
  230. package/build/src/languages/ar.d.ts +11 -0
  231. package/build/src/languages/ar.js +358 -0
  232. package/build/src/languages/ar_ui.d.ts +461 -0
  233. package/build/src/languages/ar_ui.js +464 -0
  234. package/build/src/languages/catalog.d.ts +66 -0
  235. package/build/src/languages/catalog.js +152 -0
  236. package/build/src/languages/en.d.ts +7 -0
  237. package/build/src/languages/en.js +352 -0
  238. package/build/src/languages/en_ui.d.ts +3 -0
  239. package/build/src/languages/en_ui.js +458 -0
  240. package/build/src/languages/validation.d.ts +26 -0
  241. package/build/src/languages/validation.js +60 -0
  242. package/build/src/lists/bulk_actions.d.ts +89 -0
  243. package/build/src/lists/bulk_actions.js +268 -0
  244. package/build/src/lists/dashboards.d.ts +138 -0
  245. package/build/src/lists/dashboards.js +290 -0
  246. package/build/src/mcp/tools.js +9 -104
  247. package/build/src/resource/define_resource.d.ts +18 -1
  248. package/build/src/resource/define_resource.js +212 -18
  249. package/build/src/resource/definition.d.ts +44 -0
  250. package/build/src/resource/definition.js +171 -0
  251. package/build/src/resource/registry.js +15 -4
  252. package/build/src/resource/types.d.ts +313 -16
  253. package/build/src/resource/values.d.ts +56 -1
  254. package/build/src/resource/values.js +237 -5
  255. package/build/src/services/settings.d.ts +2 -0
  256. package/build/src/services/settings.js +5 -1
  257. package/build/src/upgrade/legacy.js +2 -2
  258. package/build/src/workflows/calendar.d.ts +9 -0
  259. package/build/src/workflows/calendar.js +44 -0
  260. package/build/src/workflows/define_workflow.d.ts +48 -3
  261. package/build/src/workflows/define_workflow.js +57 -13
  262. package/build/src/workflows/delegations.d.ts +107 -0
  263. package/build/src/workflows/delegations.js +326 -0
  264. package/build/src/workflows/engine.d.ts +80 -4
  265. package/build/src/workflows/engine.js +466 -86
  266. package/build/src/workflows/sla.d.ts +15 -0
  267. package/build/src/workflows/sla.js +8 -0
  268. package/build/stubs/resource_contract.txt +12 -1
  269. package/package.json +9 -2
@@ -0,0 +1,109 @@
1
+ import type { Knex } from 'knex';
2
+ import type { Action, RecordData, Resource, SerializedRecord } from '../../resource/types.js';
3
+ import { type Actor, type AdulaAbility } from '../../auth/ability.js';
4
+ import type { ResourceDescription, ResourceNavigation } from '../presentation.js';
5
+ import { type ResourceContext } from './shared.js';
6
+ /** Project navigation is derived from registered resources and the current actor. */
7
+ export declare function navigation(ctx: ResourceContext, actor: Actor): ResourceNavigation;
8
+ export declare function describe(ctx: ResourceContext, name: string, actor: Actor): ResourceDescription;
9
+ /** Authorizes one record for collaboration features; see ResourceService.access. */
10
+ export declare function access(ctx: ResourceContext, name: string, id: number, actor: Actor, action: Action, db: Knex): Promise<{
11
+ resource: Resource;
12
+ record: RecordData;
13
+ ability: AdulaAbility;
14
+ }>;
15
+ /** Whether a (possibly other) actor may perform an action on a record; never throws for denial. */
16
+ export declare function permits(ctx: ResourceContext, name: string, id: number, actor: Actor, action: Action): Promise<boolean>;
17
+ /** Display rows of the users and related records referenced by the given records. */
18
+ export declare function preload(ctx: ResourceContext, resource: Resource, records: RecordData[], actor: Actor): Promise<Record<string, SerializedRecord[]>>;
19
+ /** Formats record titles of one resource, loading the labels of its title lookups once. */
20
+ export declare function titler(ctx: ResourceContext, resource: Resource): Promise<(record: SerializedRecord) => string | null>;
21
+ /** Titles of records the actor may view; see ResourceService.titles. */
22
+ export declare function titles(ctx: ResourceContext, name: string, ids: readonly number[], actor: Actor): Promise<Map<number, string>>;
23
+ export declare function show(ctx: ResourceContext, name: string, id: number, actor: Actor): Promise<{
24
+ data: SerializedRecord;
25
+ permissions: Partial<Record<Action | "restore", boolean>>;
26
+ related: Record<string, SerializedRecord[]>;
27
+ }>;
28
+ /** Deferred relation reads re-authorize the parent and each child on every request. */
29
+ export declare function recordChildren(ctx: ResourceContext, name: string, id: number, actor: Actor): Promise<Record<string, {
30
+ rows: SerializedRecord[];
31
+ hasMore: boolean;
32
+ related?: Record<string, SerializedRecord[]>;
33
+ }>>;
34
+ /**
35
+ * The lines of a printed document (ADR 048): the named hasMany fields, up to `limit` rows
36
+ * each, with the display rows of the lines' own relations. See ResourceService.documentLines.
37
+ */
38
+ export declare function documentLines(ctx: ResourceContext, name: string, id: number, actor: Actor, keys: readonly string[], limit: number): Promise<Record<string, {
39
+ rows: SerializedRecord[];
40
+ hasMore: boolean;
41
+ related?: Record<string, SerializedRecord[]>;
42
+ }>>;
43
+ /** Active lookup labels for the lookup fields the actor may read on this resource. */
44
+ export declare function lookups(ctx: ResourceContext, name: string, actor: Actor): Promise<Record<string, {
45
+ value: string;
46
+ label: string;
47
+ }[]>>;
48
+ /** The last 50 recorded mutations of one record, after authorizing the record itself. */
49
+ export declare function activity(ctx: ResourceContext, name: string, id: number, actor: Actor): Promise<{
50
+ id: number;
51
+ action: Action;
52
+ fields: string[];
53
+ actorId: number;
54
+ actorName: string | null;
55
+ actorAvatarUrl: string | null;
56
+ /**
57
+ * @deprecated Always null. Kept so project-owned copies of resource-show from
58
+ * earlier releases still compile; they fall back to the actor id.
59
+ */
60
+ actorEmail: string | null;
61
+ createdAt: string;
62
+ }[]>;
63
+ /** Inline children and recent activity of one record from a single record read. */
64
+ export declare function details(ctx: ResourceContext, name: string, id: number, actor: Actor): Promise<{
65
+ children: Record<string, {
66
+ rows: SerializedRecord[];
67
+ hasMore: boolean;
68
+ related?: Record<string, SerializedRecord[]>;
69
+ }>;
70
+ activity: {
71
+ id: number;
72
+ action: Action;
73
+ fields: string[];
74
+ actorId: number;
75
+ actorName: string | null;
76
+ actorAvatarUrl: string | null;
77
+ /**
78
+ * @deprecated Always null. Kept so project-owned copies of resource-show from
79
+ * earlier releases still compile; they fall back to the actor id.
80
+ */
81
+ actorEmail: string | null;
82
+ createdAt: string;
83
+ }[];
84
+ }>;
85
+ /** show(), children() and activity() of one record from a single record read. */
86
+ export declare function recordPage(ctx: ResourceContext, name: string, id: number, actor: Actor): Promise<{
87
+ children: Record<string, {
88
+ rows: SerializedRecord[];
89
+ hasMore: boolean;
90
+ related?: Record<string, SerializedRecord[]>;
91
+ }>;
92
+ activity: {
93
+ id: number;
94
+ action: Action;
95
+ fields: string[];
96
+ actorId: number;
97
+ actorName: string | null;
98
+ actorAvatarUrl: string | null;
99
+ /**
100
+ * @deprecated Always null. Kept so project-owned copies of resource-show from
101
+ * earlier releases still compile; they fall back to the actor id.
102
+ */
103
+ actorEmail: string | null;
104
+ createdAt: string;
105
+ }[];
106
+ data: SerializedRecord;
107
+ permissions: Partial<Record<Action | "restore", boolean>>;
108
+ related: Record<string, SerializedRecord[]>;
109
+ }>;
@@ -0,0 +1,388 @@
1
+ import { subject } from '@casl/ability';
2
+ import { columnName } from '../../resource/define_resource.js';
3
+ import { buildAbility, canRecord } from '../../auth/ability.js';
4
+ import { accessibleBy } from '../../auth/sql.js';
5
+ import { fromRow, serialize } from '../contracts.js';
6
+ import { AdulaError, notFound } from '../errors.js';
7
+ import { avatarUrlFor, avatarVersionColumn } from '../../core/user_avatars.js';
8
+ import { formatTitle, titleFields } from '../record_title.js';
9
+ import { authorizeAction, canQueryField, columns, fieldLevel, find, hydrate, permissions, readableField, requireRecord, } from './shared.js';
10
+ /** Project navigation is derived from registered resources and the current actor. */
11
+ export function navigation(ctx, actor) {
12
+ const { registry } = ctx;
13
+ const ability = buildAbility(actor.rules, registry.all());
14
+ const children = new Set(registry
15
+ .all()
16
+ .flatMap((resource) => Object.values(resource.fields).flatMap((field) => field.type === 'hasMany' ? [field.resource] : [])));
17
+ return registry
18
+ .all()
19
+ .filter((resource) => !children.has(resource.name) &&
20
+ resource.actions.includes('view') &&
21
+ (!resource.scoped || actor.orgPaths.length > 0) &&
22
+ ability.can('view', resource.name) &&
23
+ // A role that may add records keeps the entry: creating and importing start there.
24
+ (ability.can('create', resource.name) || !referenceOnly(resource, actor)))
25
+ .map((resource) => ({
26
+ name: resource.name,
27
+ label: resource.label.ar,
28
+ href: `/resources/${resource.name}`,
29
+ module: registry.owner(resource.name),
30
+ moduleLabel: registry.modules().find((module) => module.name === registry.owner(resource.name))?.label
31
+ .ar ?? registry.owner(resource.name),
32
+ }));
33
+ }
34
+ /**
35
+ * Whether the actor reads the resource only to name its records: every rule that grants
36
+ * `view` on it is limited to its title fields (#141). Such a role reads the resource for
37
+ * titles, pickers and inherited scope checks, so navigation does not present it. A rule
38
+ * meant only for references must therefore name title fields (the resource's `title`).
39
+ */
40
+ function referenceOnly(resource, actor) {
41
+ const title = new Set(titleFields(resource));
42
+ const grants = actor.rules.filter((rule) => {
43
+ const actions = Array.isArray(rule.action) ? rule.action : [rule.action];
44
+ return (!rule.inverted &&
45
+ (rule.subject === resource.name || rule.subject === 'all') &&
46
+ (actions.includes('view') || actions.includes('manage')));
47
+ });
48
+ return (grants.length > 0 &&
49
+ grants.every((rule) => rule.fields?.length && rule.fields.every((key) => title.has(key))));
50
+ }
51
+ export function describe(ctx, name, actor) {
52
+ const resource = ctx.registry.get(name);
53
+ const ability = authorizeAction(ctx, resource, actor, 'view');
54
+ const serialized = new Set(resource.serialize ?? [...resource.list, ...resource.show]);
55
+ const fields = Object.entries(resource.fields)
56
+ .filter(([key]) => serialized.has(key) &&
57
+ actor.permissionLevel >= fieldLevel(resource, key) &&
58
+ ability.can('view', name, key))
59
+ .map(([key, field]) => ({
60
+ ...field,
61
+ key,
62
+ sortable: Boolean(field.sortable && canQueryField(resource, actor, ability, key)),
63
+ filterable: Boolean(field.filterable && canQueryField(resource, actor, ability, key)),
64
+ }));
65
+ const visible = new Set(fields.map((field) => field.key));
66
+ const searchable = Object.entries(resource.fields).filter(([, field]) => field.searchable);
67
+ return {
68
+ name,
69
+ label: resource.label.ar,
70
+ recordLabel: resource.recordLabel?.ar ?? null,
71
+ createLabel: resource.createLabel?.ar ?? null,
72
+ fields,
73
+ list: resource.list.filter((key) => visible.has(key)),
74
+ show: resource.show.filter((key) => visible.has(key)),
75
+ searchable: searchable.length > 0 &&
76
+ searchable.every(([key]) => canQueryField(resource, actor, ability, key)),
77
+ canCreate: resource.actions.includes('create') && ability.can('create', name),
78
+ scoped: resource.scoped,
79
+ submittable: Boolean(resource.submittable),
80
+ trash: resource.actions.includes('delete') && ability.can('delete', name),
81
+ exportable: true,
82
+ bulk: ['delete', 'submit', 'cancel', 'update'].some((action) => resource.actions.includes(action) && ability.can(action, name)),
83
+ ...(resource.printTemplates?.length
84
+ ? {
85
+ printTemplates: resource.printTemplates.map((template) => ({
86
+ key: template.key,
87
+ label: template.label,
88
+ })),
89
+ }
90
+ : {}),
91
+ };
92
+ }
93
+ /** Authorizes one record for collaboration features; see ResourceService.access. */
94
+ export async function access(ctx, name, id, actor, action, db) {
95
+ let resource;
96
+ try {
97
+ resource = ctx.registry.get(name);
98
+ }
99
+ catch {
100
+ throw notFound('الكيان غير موجود');
101
+ }
102
+ if (!Number.isSafeInteger(id) || id <= 0)
103
+ throw notFound();
104
+ const ability = authorizeAction(ctx, resource, actor, action);
105
+ const record = await find(db, resource, actor, ability, id);
106
+ requireRecord(ability, actor, resource, action, record);
107
+ return { resource, record, ability };
108
+ }
109
+ /** Whether a (possibly other) actor may perform an action on a record; never throws for denial. */
110
+ export async function permits(ctx, name, id, actor, action) {
111
+ try {
112
+ await access(ctx, name, id, actor, action, ctx.db);
113
+ return true;
114
+ }
115
+ catch (error) {
116
+ if (error instanceof AdulaError && [403, 404].includes(error.status))
117
+ return false;
118
+ throw error;
119
+ }
120
+ }
121
+ /** Display rows of the users and related records referenced by the given records. */
122
+ export async function preload(ctx, resource, records, actor) {
123
+ const { db, registry } = ctx;
124
+ const related = {};
125
+ const ability = buildAbility(actor.rules, registry.all());
126
+ for (const [key, field] of Object.entries(resource.fields)) {
127
+ if (field.type === 'user' && records.length) {
128
+ const ids = records
129
+ .filter((record) => key in serialize(resource, record, ability, actor))
130
+ .map((record) => record[key])
131
+ .filter((v) => v !== null && v !== undefined);
132
+ // A display name only: readers of the record need not read account e-mails.
133
+ if (ids.length) {
134
+ const users = await db('users as u')
135
+ .whereIn('u.id', [...new Set(ids)])
136
+ .select('u.id', 'u.full_name', avatarVersionColumn(db, 'u.id'));
137
+ related[key] = users.map((row) => ({
138
+ id: Number(row.id),
139
+ fullName: String(row.full_name ?? ''),
140
+ // The versioned picture, or null so the page shows initials and requests nothing.
141
+ avatarUrl: avatarUrlFor(row.id, row.avatar_version),
142
+ }));
143
+ }
144
+ continue;
145
+ }
146
+ if ((field.type !== 'belongsTo' && field.type !== 'manyToMany') || !records.length)
147
+ continue;
148
+ const target = registry.get(field.resource);
149
+ if (!ability.can('view', target.name))
150
+ continue;
151
+ const ids = records
152
+ .filter((record) => key in serialize(resource, record, ability, actor))
153
+ // A manyToMany value is an array of ids; its related rows title every link.
154
+ .flatMap((record) => record[key])
155
+ .filter((v) => v !== null && v !== undefined);
156
+ if (!ids.length)
157
+ continue;
158
+ const query = accessibleBy(db(`${target.name} as r`).whereIn('r.id', ids).whereNull('r.deleted_at'), ability, actor, 'view', target).select(columns(target, ability));
159
+ if (target.scoped)
160
+ query.select('ou.path as org_path');
161
+ const rows = await query;
162
+ const targets = await hydrate(db, target, rows.map((r) => fromRow(r, target)), ctx.attachments);
163
+ const title = await titler(ctx, target);
164
+ related[key] = targets.map((r) => {
165
+ const row = serialize(target, r, ability, actor);
166
+ // `_title` cannot collide with a field key; clients label the relation with it.
167
+ return { ...row, _title: title(row) };
168
+ });
169
+ }
170
+ return related;
171
+ }
172
+ /** Formats record titles of one resource, loading the labels of its title lookups once. */
173
+ export async function titler(ctx, resource) {
174
+ const groups = titleFields(resource).flatMap((key) => {
175
+ const field = resource.fields[key];
176
+ return field.type === 'lookup' ? [field.group] : [];
177
+ });
178
+ const labels = new Map();
179
+ if (groups.length)
180
+ for (const row of await ctx
181
+ .db('lookups')
182
+ .whereIn('group', groups)
183
+ .select('group', 'key', 'label_ar'))
184
+ labels.set(`${row.group}\u0000${row.key}`, String(row.label_ar));
185
+ return (record) => formatTitle(resource, record, (group, key) => labels.get(`${group}\u0000${key}`));
186
+ }
187
+ /** Titles of records the actor may view; see ResourceService.titles. */
188
+ export async function titles(ctx, name, ids, actor) {
189
+ const result = new Map();
190
+ let resource;
191
+ try {
192
+ resource = ctx.registry.get(name);
193
+ }
194
+ catch {
195
+ return result;
196
+ }
197
+ const wanted = [...new Set(ids.filter((id) => Number.isSafeInteger(id) && id > 0))];
198
+ const ability = buildAbility(actor.rules, ctx.registry.all());
199
+ if (!wanted.length || !resource.actions.includes('view') || !ability.can('view', name))
200
+ return result;
201
+ const query = accessibleBy(ctx.db(`${resource.name} as r`).whereIn('r.id', wanted).whereNull('r.deleted_at'), ability, actor, 'view', resource).select(columns(resource, ability));
202
+ if (resource.scoped)
203
+ query.select('ou.path as org_path');
204
+ const rows = await query;
205
+ const records = rows.map((row) => fromRow(row, resource));
206
+ const title = await titler(ctx, resource);
207
+ for (const record of records) {
208
+ if (!canRecord(ability, actor, resource, 'view', record))
209
+ continue;
210
+ const text = title(serialize(resource, record, ability, actor));
211
+ if (text)
212
+ result.set(Number(record.id), text);
213
+ }
214
+ return result;
215
+ }
216
+ /** One viewable record, authorized for the actor. */
217
+ async function viewable(ctx, name, id, actor) {
218
+ const resource = ctx.registry.get(name);
219
+ const ability = authorizeAction(ctx, resource, actor, 'view');
220
+ const record = await find(ctx.db, resource, actor, ability, id);
221
+ requireRecord(ability, actor, resource, 'view', record);
222
+ return { resource, ability, record };
223
+ }
224
+ /** The serialized record with its permissions and related rows. */
225
+ async function presented(ctx, resource, record, actor, ability) {
226
+ const [hydrated] = await hydrate(ctx.db, resource, [record], ctx.attachments);
227
+ const related = await preload(ctx, resource, [record], actor);
228
+ // A reader of the record may read the name of its unit; clients show it instead of an id.
229
+ if (resource.scoped && record.orgUnitId !== null && record.orgUnitId !== undefined) {
230
+ const unit = await ctx.db('org_units').where('id', Number(record.orgUnitId)).first('id', 'name');
231
+ if (unit)
232
+ related.orgUnitId = [
233
+ { id: Number(unit.id), name: String(unit.name), _title: String(unit.name) },
234
+ ];
235
+ }
236
+ return {
237
+ data: serialize(resource, hydrated, ability, actor),
238
+ permissions: permissions(resource, record, actor, ability),
239
+ related,
240
+ };
241
+ }
242
+ export async function show(ctx, name, id, actor) {
243
+ const { resource, ability, record } = await viewable(ctx, name, id, actor);
244
+ return presented(ctx, resource, record, actor, ability);
245
+ }
246
+ /** Deferred relation reads re-authorize the parent and each child on every request. */
247
+ export async function recordChildren(ctx, name, id, actor) {
248
+ const { resource, ability, record } = await viewable(ctx, name, id, actor);
249
+ return childrenOf(ctx, resource, record, actor, ability);
250
+ }
251
+ /**
252
+ * The lines of a printed document (ADR 048): the named hasMany fields, up to `limit` rows
253
+ * each, with the display rows of the lines' own relations. See ResourceService.documentLines.
254
+ */
255
+ export async function documentLines(ctx, name, id, actor, keys, limit) {
256
+ const { resource, ability, record } = await viewable(ctx, name, id, actor);
257
+ return childrenOf(ctx, resource, record, actor, ability, keys, { limit, related: true });
258
+ }
259
+ /** Inline children of an already authorized parent record. */
260
+ async function childrenOf(ctx, resource, parent, actor, ability, keys = resource.show, options = {}) {
261
+ const name = resource.name;
262
+ const id = Number(parent.id);
263
+ const limit = options.limit ?? 100;
264
+ // A line group is readable where the record exposes it (serialize, or list and show),
265
+ // or where the resource's own code print templates declare it (ADR 048). Declaring a
266
+ // group in a code print template is the resource author exposing it like a detail field:
267
+ // children() returns it to any caller that names it, not only to printing (the record
268
+ // page itself names `show`).
269
+ const exposed = new Set([
270
+ ...(resource.serialize ?? [...resource.list, ...resource.show]),
271
+ ...(resource.printTemplates ?? []).flatMap((template) => Object.keys(template.lines ?? {})),
272
+ ]);
273
+ const result = {};
274
+ for (const key of keys) {
275
+ const field = resource.fields[key];
276
+ if (field?.type !== 'hasMany' ||
277
+ !ability.can('view', subject(name, parent), key) ||
278
+ actor.permissionLevel < fieldLevel(resource, key))
279
+ continue;
280
+ if (!exposed.has(key))
281
+ continue;
282
+ const child = ctx.registry.get(field.resource);
283
+ if (!ability.can('view', child.name) || !child.actions.includes('view'))
284
+ continue;
285
+ const rows = await accessibleBy(ctx.db(`${child.name} as r`).whereNull('r.deleted_at'), ability, actor, 'view', child)
286
+ .where(`r.${child.fields[field.foreignKey].column ?? columnName(field.foreignKey)}`, id)
287
+ .select([...columns(child, ability), ...(child.scoped ? ['ou.path as org_path'] : [])])
288
+ .orderBy('r.id')
289
+ .limit(limit + 1);
290
+ const hydrated = await hydrate(ctx.db, child, rows.slice(0, limit).map((row) => fromRow(row, child)), ctx.attachments);
291
+ result[key] = {
292
+ rows: hydrated.map((row) => serialize(child, row, ability, actor)),
293
+ hasMore: rows.length > limit,
294
+ ...(options.related ? { related: await preload(ctx, child, hydrated, actor) } : {}),
295
+ };
296
+ }
297
+ return result;
298
+ }
299
+ /** Active lookup labels for the lookup fields the actor may read on this resource. */
300
+ export async function lookups(ctx, name, actor) {
301
+ const options = {};
302
+ for (const field of describe(ctx, name, actor).fields) {
303
+ if (field.type !== 'lookup')
304
+ continue;
305
+ const rows = await ctx
306
+ .db('lookups')
307
+ .where({ group: field.group, active: true })
308
+ .orderBy(['sort', 'id'])
309
+ .select('key', 'label_ar');
310
+ options[field.key] = rows.map((row) => ({ value: row.key, label: row.label_ar }));
311
+ }
312
+ return options;
313
+ }
314
+ /** The last 50 recorded mutations of one record, after authorizing the record itself. */
315
+ export async function activity(ctx, name, id, actor) {
316
+ const { resource, ability, record } = await viewable(ctx, name, id, actor);
317
+ return activityOf(ctx, resource, record, ability, actor);
318
+ }
319
+ /** Inline children and recent activity of one record from a single record read. */
320
+ export async function details(ctx, name, id, actor) {
321
+ const { resource, ability, record } = await viewable(ctx, name, id, actor);
322
+ return {
323
+ children: await childrenOf(ctx, resource, record, actor, ability),
324
+ activity: await activityOf(ctx, resource, record, ability, actor),
325
+ };
326
+ }
327
+ /** show(), children() and activity() of one record from a single record read. */
328
+ export async function recordPage(ctx, name, id, actor) {
329
+ const { resource, ability, record: found } = await viewable(ctx, name, id, actor);
330
+ return {
331
+ ...(await presented(ctx, resource, found, actor, ability)),
332
+ children: await childrenOf(ctx, resource, found, actor, ability),
333
+ activity: await activityOf(ctx, resource, found, ability, actor),
334
+ };
335
+ }
336
+ /**
337
+ * The record's recent activity. Each entry names only fields the viewer may read
338
+ * (readableField, as the field history); an update names the fields its field history
339
+ * recorded, plus the inline line groups it wrote, so entries stored with every submitted
340
+ * key are narrowed too.
341
+ */
342
+ async function activityOf(ctx, resource, record, ability, actor) {
343
+ const rows = await ctx
344
+ .db('activities as a')
345
+ .leftJoin('users as u', 'u.id', 'a.actor_id')
346
+ .where({ 'a.resource': resource.name, 'a.record_id': Number(record.id) })
347
+ .orderBy('a.id', 'desc')
348
+ .limit(50)
349
+ .select('a.id', 'a.action', 'a.changes', 'a.actor_id', 'a.created_at', 'u.full_name as actor_name', avatarVersionColumn(ctx.db, 'a.actor_id'));
350
+ const updates = rows.filter((row) => row.action === 'update').map((row) => Number(row.id));
351
+ const changed = new Map();
352
+ if (updates.length)
353
+ for (const change of await ctx
354
+ .db('field_changes')
355
+ .whereIn('activity_id', updates)
356
+ .orderBy('id')
357
+ .select('activity_id', 'field')) {
358
+ const keys = changed.get(Number(change.activity_id)) ?? [];
359
+ if (!keys.includes(String(change.field)))
360
+ keys.push(String(change.field));
361
+ changed.set(Number(change.activity_id), keys);
362
+ }
363
+ const named = (row) => {
364
+ const stored = Array.isArray(row.changes?.fields) ? row.changes.fields.map(String) : [];
365
+ if (row.action !== 'update')
366
+ return stored;
367
+ const keys = [...(changed.get(Number(row.id)) ?? [])];
368
+ for (const key of stored)
369
+ if (resource.fields[key]?.type === 'hasMany' && !keys.includes(key))
370
+ keys.push(key);
371
+ return keys;
372
+ };
373
+ return rows.map((row) => ({
374
+ id: Number(row.id),
375
+ action: String(row.action),
376
+ fields: named(row).filter((key) => readableField(resource, record, ability, actor, key)),
377
+ actorId: Number(row.actor_id),
378
+ // A display name only: record viewers need not be able to read account e-mails.
379
+ actorName: row.actor_name ? String(row.actor_name) : null,
380
+ actorAvatarUrl: avatarUrlFor(row.actor_id, row.avatar_version),
381
+ /**
382
+ * @deprecated Always null. Kept so project-owned copies of resource-show from
383
+ * earlier releases still compile; they fall back to the actor id.
384
+ */
385
+ actorEmail: null,
386
+ createdAt: new Date(row.created_at).toISOString(),
387
+ }));
388
+ }
@@ -0,0 +1,93 @@
1
+ import type { Knex } from 'knex';
2
+ import type { ResourceRegistry } from '../../resource/registry.js';
3
+ import type { Action, RecordData, Resource } from '../../resource/types.js';
4
+ import { type Actor, type AdulaAbility } from '../../auth/ability.js';
5
+ import { type AttachmentPreviewOptions } from '../../attachments/attachment_service.js';
6
+ import type { RecordPermissions } from '../presentation.js';
7
+ /**
8
+ * What every resource operation needs: the database and the registered resources, plus
9
+ * the deployment's attachment preview settings for the summaries readers receive.
10
+ */
11
+ export type ResourceContext = {
12
+ db: Knex;
13
+ registry: ResourceRegistry;
14
+ attachments?: AttachmentPreviewOptions;
15
+ };
16
+ /**
17
+ * The permission level an actor needs to see or write a field: its own permissionLevel,
18
+ * and at least 1 when the resource lists it as hidden.
19
+ */
20
+ export declare function fieldLevel(resource: Resource, key: string): number;
21
+ /**
22
+ * Whether a viewer may read a field of a record: exposed by the resource (serialize, or
23
+ * list and show), at the field's permission level, and allowed by the role rules on this
24
+ * record. The per-field change history and the activity entries apply this rule.
25
+ */
26
+ export declare function readableField(resource: Resource, record: RecordData, ability: AdulaAbility, actor: Actor, key: string): boolean;
27
+ /**
28
+ * Whether an actor may sort, filter or search by a field. Querying reveals values
29
+ * indirectly, so it needs unconditional view access at the field's level.
30
+ */
31
+ export declare function canQueryField(resource: Resource, actor: Actor, ability: AdulaAbility, key: string): boolean;
32
+ /** The actor's ability, after checking the resource offers the action and the actor holds it. */
33
+ export declare function authorizeAction(ctx: ResourceContext, resource: Resource, actor: Actor, action: Action): AdulaAbility;
34
+ /** Live rows of a resource inside the actor's organization scope. */
35
+ export declare function scopedQuery(db: Knex, resource: Resource, actor: Actor): Knex.QueryBuilder<any, {
36
+ _base: any;
37
+ _hasSelection: false;
38
+ _keys: never;
39
+ _aliases: {};
40
+ _single: false;
41
+ _intersectProps: {};
42
+ _unionProps: never;
43
+ }[]>;
44
+ /** The qualified columns the ability may read (or write). */
45
+ export declare function columns(resource: Resource, ability: AdulaAbility, write?: boolean, extra?: string[]): string[];
46
+ /** One live record within the actor's scope; 404 otherwise. */
47
+ export declare function find(db: Knex, resource: Resource, actor: Actor, ability: AdulaAbility, id: number, lock?: boolean): Promise<RecordData>;
48
+ /**
49
+ * Adds the linked ids of every manyToMany field (ascending arrays) to records read
50
+ * from the resource's table, so policies, serialization and audits see them like
51
+ * column values. Mutates and returns the records.
52
+ *
53
+ * Only live targets are linked: a soft-deleted target's id is never shown, and because
54
+ * writes diff against these ids too, its join row survives an edit and the link returns
55
+ * when the target is restored.
56
+ */
57
+ export declare function withLinks(db: Knex, resource: Resource, records: RecordData[]): Promise<RecordData[]>;
58
+ /**
59
+ * Applies a filter on a field without a plain column comparison: a multiSelect contains
60
+ * the value, a manyToMany links the id. Returns false for other fields.
61
+ */
62
+ export declare function collectionFilter(query: Knex.QueryBuilder, resource: Resource, key: string, value: unknown): boolean;
63
+ /** A live record regardless of any actor's scope, for system writes. */
64
+ export declare function findAny(db: Knex, resource: Resource, id: number, lock?: boolean): Promise<RecordData>;
65
+ /** Scope (404) and conditional rules (403) of one loaded record. */
66
+ export declare function requireRecord(ability: AdulaAbility, actor: Actor, resource: Resource, action: Action, record: RecordData): void;
67
+ /**
68
+ * A child that inherits its unit (`scope.from`, ADR 029) is written only by readers of its
69
+ * parent. The refusal names the missing rule, since the same role may read and delete
70
+ * the child (#140); a parent outside the actor's scope stays 404.
71
+ */
72
+ export declare function requireParentView(ability: AdulaAbility, actor: Actor, child: Resource, parent: Resource, record: RecordData): void;
73
+ /** Which of the resource's actions the actor may take on one record now. */
74
+ export declare function permissions(resource: Resource, record: RecordData, actor: Actor, ability: AdulaAbility): RecordPermissions;
75
+ /** Coerces every present field value to its stored representation (422 E_FIELD_VALUE). */
76
+ export declare function normalizeValues(resource: Resource, record: RecordData): void;
77
+ /** Stored attachment ids become summaries for readers; copies keep policy checks on raw rows. */
78
+ export declare function hydrate(db: Knex, resource: Resource, records: RecordData[], options?: AttachmentPreviewOptions): Promise<RecordData[]>;
79
+ export declare function hydrateOne(db: Knex, resource: Resource, record: RecordData, options?: AttachmentPreviewOptions): Promise<RecordData>;
80
+ /**
81
+ * Active users eligible for a user field: members of the unit at `path` or of one of
82
+ * its ancestors, or (without a path) users sharing organization scope with the actor.
83
+ * A system write on an unscoped resource passes no actor: any active member qualifies.
84
+ */
85
+ export declare function eligibleUsers(db: Knex, path: string | null, actor: Actor | null): Knex.QueryBuilder<any, {
86
+ _base: any;
87
+ _hasSelection: true;
88
+ _keys: string;
89
+ _aliases: {};
90
+ _single: false;
91
+ _intersectProps: {};
92
+ _unionProps: never;
93
+ }[]>;