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,567 @@
1
+ /**
2
+ * A typed API client generated from the OpenAPI document of openApiDocument(): one
3
+ * self-contained TypeScript module (no imports, no DOM or Node types) holding the
4
+ * per-resource record and input types and a small fetch-based runtime. The document
5
+ * is usually actor-filtered, so the client describes exactly what one token may use.
6
+ */
7
+ const RESOURCE_OPERATIONS = [
8
+ 'list',
9
+ 'show',
10
+ 'create',
11
+ 'update',
12
+ 'delete',
13
+ 'submit',
14
+ 'cancel',
15
+ 'amend',
16
+ 'aggregate',
17
+ ];
18
+ const RUNTIME_NAMES = [
19
+ 'AdulaApiError',
20
+ 'AdulaClient',
21
+ 'AdulaClientOptions',
22
+ 'AdulaFetch',
23
+ 'AdulaFetchResponse',
24
+ 'AdulaListQuery',
25
+ 'AdulaPage',
26
+ 'AdulaAggregateQuery',
27
+ 'AdulaAggregate',
28
+ 'AdulaTransitionOptions',
29
+ 'AdulaResourceClients',
30
+ 'AdulaImportsClient',
31
+ 'AdulaImportBatch',
32
+ 'AdulaImportInput',
33
+ 'AdulaImportInputs',
34
+ 'AdulaImportModes',
35
+ 'AdulaImportStartInput',
36
+ 'AdulaImportableResource',
37
+ 'Resources',
38
+ ];
39
+ const isRecord = (value) => typeof value === 'object' && value !== null && !Array.isArray(value);
40
+ function pascal(name) {
41
+ return name
42
+ .split(/[^A-Za-z0-9]+/)
43
+ .filter(Boolean)
44
+ .map((part) => part[0].toUpperCase() + part.slice(1))
45
+ .join('');
46
+ }
47
+ const identifier = /^[A-Za-z_$][A-Za-z0-9_$]*$/;
48
+ const propertyKey = (key) => (identifier.test(key) ? key : JSON.stringify(key));
49
+ const comment = (text, indent) => typeof text === 'string' && text ? `${indent}/** ${text.replace(/\*\//g, '* /')} */\n` : '';
50
+ /** Reads the document once: component type names and each resource's operations. */
51
+ function plan(document) {
52
+ const schemas = document.components?.schemas ?? {};
53
+ const taken = new Set(RUNTIME_NAMES);
54
+ const names = new Map();
55
+ for (const key of Object.keys(schemas)) {
56
+ if (key === 'ImportBatch') {
57
+ names.set(key, 'AdulaImportBatch');
58
+ continue;
59
+ }
60
+ const input = key.endsWith('_input');
61
+ let base = pascal(input ? key.slice(0, -'_input'.length) : key) || 'Schema';
62
+ if (/^\d/.test(base))
63
+ base = `R${base}`;
64
+ let name = `${base}${input ? 'Input' : ''}`;
65
+ if (taken.has(name))
66
+ name = `${base}Record${input ? 'Input' : ''}`;
67
+ for (let suffix = 2; taken.has(name); suffix++)
68
+ name = `${base}${suffix}${input ? 'Input' : ''}`;
69
+ taken.add(name);
70
+ names.set(key, name);
71
+ }
72
+ const resources = new Map();
73
+ let basePath = '/api/v1';
74
+ let startInput;
75
+ let imports = false;
76
+ for (const [path, item] of Object.entries(document.paths)) {
77
+ const prefix = /^(.*?)\/(resources|imports)(\/|$)/.exec(path);
78
+ if (prefix)
79
+ basePath = prefix[1];
80
+ for (const [method, value] of Object.entries(item)) {
81
+ if (!isRecord(value))
82
+ continue;
83
+ const operation = value;
84
+ const id = operation.operationId;
85
+ if (typeof id !== 'string')
86
+ continue;
87
+ const match = /\/resources\/([^/{]+)(\/|$)/.exec(path);
88
+ if (!match) {
89
+ if (id.startsWith('imports.'))
90
+ imports = true;
91
+ if (id === 'imports.start')
92
+ startInput = operation.requestBody?.content?.['application/json']?.schema;
93
+ continue;
94
+ }
95
+ const name = match[1];
96
+ const entry = resources.get(name) ?? {
97
+ name,
98
+ type: names.get(name) ?? pascal(name),
99
+ operations: new Set(),
100
+ sort: ['id'],
101
+ importable: false,
102
+ };
103
+ resources.set(name, entry);
104
+ const kind = id.slice(id.lastIndexOf('.') + 1);
105
+ if (kind === 'import') {
106
+ entry.importable = true;
107
+ entry.importInput = operation.requestBody?.content?.['application/json']?.schema;
108
+ continue;
109
+ }
110
+ if (kind === 'importTemplate') {
111
+ const mode = operation.parameters?.find((parameter) => parameter.name === 'mode');
112
+ if (isRecord(mode?.schema))
113
+ entry.templateMode = mode.schema;
114
+ continue;
115
+ }
116
+ if (!RESOURCE_OPERATIONS.includes(kind) || method === 'parameters')
117
+ continue;
118
+ entry.operations.add(kind);
119
+ const parameters = operation.parameters ?? [];
120
+ const filters = parameters.find((parameter) => parameter.name === 'filters');
121
+ if (filters && isRecord(filters.schema) && kind === 'list')
122
+ entry.filters = filters.schema;
123
+ const sort = parameters.find((parameter) => parameter.name === 'sort');
124
+ const values = isRecord(sort?.schema) ? sort.schema.enum : undefined;
125
+ if (kind === 'list' && Array.isArray(values))
126
+ entry.sort = values.map(String);
127
+ }
128
+ }
129
+ // A stable method order, whatever the path order of the document.
130
+ for (const entry of resources.values())
131
+ entry.operations = new Set(RESOURCE_OPERATIONS.filter((operation) => entry.operations.has(operation)));
132
+ return { schemas, names, resources: [...resources.values()], basePath, imports, startInput };
133
+ }
134
+ /** A JSON Schema (the subset openApiDocument emits) as a TypeScript type expression. */
135
+ function tsType(schema, names, indent) {
136
+ if (!isRecord(schema))
137
+ return 'unknown';
138
+ if (typeof schema.$ref === 'string') {
139
+ const key = schema.$ref.replace('#/components/schemas/', '');
140
+ // A component the caller may not view is left out of its document.
141
+ return names.get(key) ?? 'Record<string, unknown>';
142
+ }
143
+ if (Array.isArray(schema.allOf)) {
144
+ // Inline child rows: the parent fills the inherited keys (x-adula-inherited).
145
+ const inherited = Array.isArray(schema['x-adula-inherited'])
146
+ ? schema['x-adula-inherited'].map(String)
147
+ : [];
148
+ const parts = schema.allOf.map((part) => {
149
+ const type = tsType(part, names, indent);
150
+ return inherited.length ? `Omit<${type}, ${literal(inherited)}>` : type;
151
+ });
152
+ if (isRecord(schema.properties))
153
+ parts.push(objectType(schema, names, indent));
154
+ return parts.join(' & ');
155
+ }
156
+ if (Array.isArray(schema.enum))
157
+ return schema.enum.map((value) => JSON.stringify(value)).join(' | ') || 'never';
158
+ const types = Array.isArray(schema.type)
159
+ ? schema.type.map(String)
160
+ : typeof schema.type === 'string'
161
+ ? [schema.type]
162
+ : isRecord(schema.properties)
163
+ ? ['object']
164
+ : [];
165
+ if (!types.length)
166
+ return 'unknown';
167
+ const parts = types.map((type) => {
168
+ switch (type) {
169
+ case 'string':
170
+ return 'string';
171
+ case 'integer':
172
+ case 'number':
173
+ return 'number';
174
+ case 'boolean':
175
+ return 'boolean';
176
+ case 'null':
177
+ return 'null';
178
+ case 'array':
179
+ return `Array<${tsType(schema.items, names, indent)}>`;
180
+ case 'object':
181
+ return objectType(schema, names, indent);
182
+ default:
183
+ return 'unknown';
184
+ }
185
+ });
186
+ return [...new Set(parts)].join(' | ');
187
+ }
188
+ function objectType(schema, names, indent) {
189
+ if (isRecord(schema.properties)) {
190
+ const body = members(schema, names, `${indent} `);
191
+ return body ? `{\n${body}${indent}}` : 'Record<string, never>';
192
+ }
193
+ if (isRecord(schema.additionalProperties))
194
+ return `Record<string, ${tsType(schema.additionalProperties, names, indent)}>`;
195
+ return 'Record<string, unknown>';
196
+ }
197
+ function members(schema, names, indent) {
198
+ const required = new Set(Array.isArray(schema.required) ? schema.required.map(String) : []);
199
+ return Object.entries(isRecord(schema.properties) ? schema.properties : {})
200
+ .map(([key, property]) => {
201
+ const optional = required.has(key) ? '' : '?';
202
+ return `${comment(isRecord(property) ? property.description : undefined, indent)}${indent}${propertyKey(key)}${optional}: ${tsType(property, names, indent)}\n`;
203
+ })
204
+ .join('');
205
+ }
206
+ function declaration(name, schema, names) {
207
+ const head = comment(schema.description, '');
208
+ if (isRecord(schema.properties)) {
209
+ const body = members(schema, names, ' ');
210
+ return body
211
+ ? `${head}export interface ${name} {\n${body}}\n`
212
+ : `${head}export type ${name} = Record<string, never>\n`;
213
+ }
214
+ return `${head}export type ${name} = ${tsType(schema, names, '')}\n`;
215
+ }
216
+ const literal = (values) => values.map((value) => JSON.stringify(value)).join(' | ');
217
+ /** The types shared by apiClientSource and apiClientDeclarations. */
218
+ function typesSection(document) {
219
+ const { schemas, names, resources, imports, startInput, basePath } = plan(document);
220
+ const lines = [
221
+ `/** The part of a fetch Response the client reads. */`,
222
+ `export interface AdulaFetchResponse {`,
223
+ ` ok: boolean`,
224
+ ` status: number`,
225
+ ` statusText: string`,
226
+ ` text(): Promise<string>`,
227
+ ` /** Needed only for binary downloads such as imports.xlsxTemplate(). */`,
228
+ ` arrayBuffer?(): Promise<ArrayBuffer>`,
229
+ `}`,
230
+ `/** The global fetch, or any compatible implementation (tests, proxies, retries). */`,
231
+ `export type AdulaFetch = (`,
232
+ ` url: string,`,
233
+ ` init: { method: string; headers: Record<string, string>; body?: string }`,
234
+ `) => Promise<AdulaFetchResponse>`,
235
+ `export interface AdulaClientOptions {`,
236
+ ` /** Server origin, for example https://erp.example.com. Defaults to the server this client was generated from. */`,
237
+ ` baseUrl?: string`,
238
+ ` /** API prefix. Defaults to ${JSON.stringify(basePath)}. */`,
239
+ ` basePath?: string`,
240
+ ` /** A personal API token (Account → API tokens), sent as a bearer token. */`,
241
+ ` token: string`,
242
+ ` fetch?: AdulaFetch`,
243
+ `}`,
244
+ `export interface AdulaListQuery<Filters, Sort extends string> {`,
245
+ ` limit?: number`,
246
+ ` /** meta.nextCursor of the previous page. */`,
247
+ ` cursor?: string | null`,
248
+ ` search?: string`,
249
+ ` sort?: Sort`,
250
+ ` direction?: 'asc' | 'desc'`,
251
+ ` tag?: string`,
252
+ ` /** false skips meta.estimatedTotal. */`,
253
+ ` estimate?: boolean`,
254
+ ` /** Equality filters on filterable fields (filters[field]=value). */`,
255
+ ` filters?: Filters`,
256
+ `}`,
257
+ `export interface AdulaPage<Row> {`,
258
+ ` data: Row[]`,
259
+ ` meta: { limit: number; nextCursor: string | null; estimatedTotal?: number }`,
260
+ `}`,
261
+ `export interface AdulaAggregateQuery<Filters> {`,
262
+ ` /** Up to three fields. */`,
263
+ ` groupBy?: string | readonly string[]`,
264
+ ` /** Integer or money fields to total. */`,
265
+ ` sum?: string | readonly string[]`,
266
+ ` /** Conditions ($eq, $ne, $in, $lt, $gt, $like) as an object or its JSON. */`,
267
+ ` where?: Record<string, unknown> | string`,
268
+ ` search?: string`,
269
+ ` count?: boolean`,
270
+ ` filters?: Filters`,
271
+ `}`,
272
+ `export interface AdulaAggregate {`,
273
+ ` truncated?: boolean`,
274
+ ` rows: Array<{ group: Record<string, unknown>; count?: number; sum?: Record<string, string | null> }>`,
275
+ `}`,
276
+ `export interface AdulaTransitionOptions {`,
277
+ ` /** The record version read last (optimistic locking). */`,
278
+ ` version?: number`,
279
+ `}`,
280
+ '',
281
+ ];
282
+ for (const [key, schema] of Object.entries(schemas))
283
+ lines.push(declaration(names.get(key), schema, names));
284
+ const clients = [];
285
+ for (const resource of resources) {
286
+ const record = names.get(resource.name) ?? 'Record<string, unknown>';
287
+ const input = names.get(`${resource.name}_input`) ?? 'Record<string, unknown>';
288
+ const type = resource.type;
289
+ lines.push(resource.filters
290
+ ? declaration(`${type}Filters`, resource.filters, names)
291
+ : `export type ${type}Filters = Record<string, never>\n`, `export type ${type}Sort = ${literal(resource.sort)}\n`);
292
+ const methods = [];
293
+ const has = (operation) => resource.operations.has(operation);
294
+ if (has('list'))
295
+ methods.push(` list(query?: AdulaListQuery<${type}Filters, ${type}Sort>): Promise<AdulaPage<${record}>>`);
296
+ if (has('show'))
297
+ methods.push(` show(id: number): Promise<${record}>`);
298
+ if (has('create'))
299
+ methods.push(` create(input: ${input}): Promise<${record}>`);
300
+ if (has('update'))
301
+ methods.push(` /** Only the given fields change; pass version on versioned resources. */`, ` update(id: number, input: Partial<${input}>): Promise<${record}>`);
302
+ if (has('delete'))
303
+ methods.push(` delete(id: number, options?: AdulaTransitionOptions): Promise<${record}>`);
304
+ if (has('submit'))
305
+ methods.push(` submit(id: number, options?: AdulaTransitionOptions): Promise<${record}>`);
306
+ if (has('cancel'))
307
+ methods.push(` cancel(id: number, options?: AdulaTransitionOptions): Promise<${record}>`);
308
+ if (has('amend'))
309
+ methods.push(` /** A new draft copied from the cancelled document. */`, ` amend(id: number): Promise<${record}>`);
310
+ if (has('aggregate'))
311
+ methods.push(` aggregate(query?: AdulaAggregateQuery<${type}Filters>): Promise<AdulaAggregate>`);
312
+ lines.push(`export interface ${type}Client {\n${methods.join('\n')}\n}\n`);
313
+ clients.push(` ${propertyKey(resource.name)}: ${type}Client`);
314
+ }
315
+ lines.push(`/** The resources this client may call, by name. */`, `export interface Resources {`, ...resources.map((resource) => ` ${propertyKey(resource.name)}: {\n record: ${names.get(resource.name) ?? 'Record<string, unknown>'}\n input: ${names.get(`${resource.name}_input`) ?? 'Record<string, unknown>'}\n filters: ${resource.type}Filters\n sort: ${resource.type}Sort\n operations: ${literal([...resource.operations]) || 'never'}\n }`), `}`, `export interface AdulaResourceClients {`, ...clients, `}`);
316
+ const importable = resources.filter((resource) => resource.importable);
317
+ if (imports) {
318
+ if (!names.has('ImportBatch'))
319
+ lines.push(`export type AdulaImportBatch = Record<string, unknown>`);
320
+ lines.push(`/** The upload body per importable resource: modes and match fields differ by resource. */`, `export interface AdulaImportInputs {`, ...importable.map((resource) => ` ${propertyKey(resource.name)}: ${tsType(resource.importInput ?? { type: 'object' }, names, ' ')}`), `}`, `export interface AdulaImportModes {`, ...importable.map((resource) => ` ${propertyKey(resource.name)}: ${resource.templateMode ? tsType(resource.templateMode, names, ' ') : '"create"'}`), `}`, `export type AdulaImportableResource = keyof AdulaImportInputs`, `export type AdulaImportInput = AdulaImportInputs[AdulaImportableResource]`, declaration('AdulaImportStartInput', startInput ?? {
321
+ type: 'object',
322
+ properties: { mapping: { type: 'object', additionalProperties: { type: 'string' } } },
323
+ required: ['mapping'],
324
+ }, names), `export interface AdulaImportsClient {`, ` /** The caller's latest batches. */`, ` list(): Promise<AdulaImportBatch[]>`, ` /** One batch; after a dry run, report holds each row's outcome. */`, ` show(id: number): Promise<AdulaImportBatch>`, ` /** Uploads a file; the batch then waits for start() with its column mapping. */`, ` create<R extends AdulaImportableResource>(resource: R, input: AdulaImportInputs[R]): Promise<AdulaImportBatch>`, ` /** Queues the batch: dryRun validates only (status validated); start again to import. */`, ` start(id: number, input: AdulaImportStartInput): Promise<AdulaImportBatch>`, ` /** The CSV header row (UTF-8 with BOM) of the fields the caller may import. */`, ` template<R extends AdulaImportableResource>(resource: R, options?: { mode?: AdulaImportModes[R] }): Promise<string>`, ` /** The same header row as an Excel workbook (.xlsx bytes). */`, ` xlsxTemplate<R extends AdulaImportableResource>(resource: R, options?: { mode?: AdulaImportModes[R] }): Promise<ArrayBuffer>`, `}`);
325
+ }
326
+ lines.push(`export interface AdulaClient {`, ` resources: AdulaResourceClients`, ...(imports ? [` imports: AdulaImportsClient`] : []), ` /** Any other API call: the path is relative to basePath; JSON in and out. */`, ` request<T = unknown>(method: string, path: string, body?: unknown): Promise<T>`, `}`);
327
+ return { text: lines.join('\n'), resources, basePath, imports };
328
+ }
329
+ function header(document) {
330
+ const title = [document.info?.title, document.info?.version].filter(Boolean).join(' ');
331
+ return [
332
+ `// Generated by AdulaJS from the OpenAPI document${title ? ` of ${title}` : ''}.`,
333
+ `// Do not edit: regenerate with \`node ace adula:client\` or download GET /api/v1/client.ts.`,
334
+ `/* eslint-disable */`,
335
+ '',
336
+ ].join('\n');
337
+ }
338
+ const RUNTIME = `
339
+ export class AdulaApiError extends Error {
340
+ readonly status: number
341
+ readonly code: string
342
+ readonly body: unknown
343
+ constructor(status: number, code: string, message: string, body?: unknown) {
344
+ super(message)
345
+ this.name = 'AdulaApiError'
346
+ this.status = status
347
+ this.code = code
348
+ this.body = body
349
+ }
350
+ }
351
+
352
+ function adulaQuery(query: Record<string, unknown> | undefined) {
353
+ const parts: string[] = []
354
+ const add = (key: string, value: unknown) => {
355
+ if (value === undefined || value === null || value === '') return
356
+ parts.push(key + '=' + encodeURIComponent(String(value)))
357
+ }
358
+ for (const key of Object.keys(query ?? {})) {
359
+ const value = (query as Record<string, unknown>)[key]
360
+ if (key === 'filters' && value && typeof value === 'object') {
361
+ const filters = value as Record<string, unknown>
362
+ for (const field of Object.keys(filters)) add('filters[' + encodeURIComponent(field) + ']', filters[field])
363
+ } else if ((key === 'groupBy' || key === 'sum') && Array.isArray(value)) add(key, value.join(','))
364
+ else if (key === 'where' && value && typeof value === 'object') add(key, JSON.stringify(value))
365
+ else add(encodeURIComponent(key), value)
366
+ }
367
+ return parts.length ? '?' + parts.join('&') : ''
368
+ }
369
+
370
+ export function createAdulaClient(options: AdulaClientOptions): AdulaClient {
371
+ const globalFetch = (globalThis as unknown as { fetch?: AdulaFetch }).fetch
372
+ const fetcher: AdulaFetch | undefined =
373
+ options.fetch ?? (globalFetch ? (url, init) => globalFetch(url, init) : undefined)
374
+ if (!fetcher) throw new Error('No fetch implementation: pass options.fetch')
375
+ if (!options.token) throw new Error('A personal API token is required')
376
+ const root =
377
+ (options.baseUrl ?? ADULA_API_SERVER).replace(/\\/+$/, '') +
378
+ (options.basePath ?? ADULA_API_BASE_PATH).replace(/\\/+$/, '')
379
+ async function call(
380
+ method: string,
381
+ path: string,
382
+ init: { query?: Record<string, unknown>; body?: unknown; text?: boolean; binary?: boolean } = {}
383
+ ): Promise<unknown> {
384
+ const headers: Record<string, string> = {
385
+ Authorization: 'Bearer ' + options.token,
386
+ Accept: init.binary
387
+ ? 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/json'
388
+ : init.text
389
+ ? 'text/csv, text/plain, */*'
390
+ : 'application/json',
391
+ }
392
+ if (init.body !== undefined) headers['Content-Type'] = 'application/json'
393
+ const response = await fetcher!(root + path + adulaQuery(init.query), {
394
+ method,
395
+ headers,
396
+ ...(init.body === undefined ? {} : { body: JSON.stringify(init.body) }),
397
+ })
398
+ if (init.binary && response.ok) {
399
+ if (!response.arrayBuffer) throw new Error('The fetch implementation cannot read binary responses')
400
+ return response.arrayBuffer()
401
+ }
402
+ const raw = await response.text()
403
+ if (!response.ok) {
404
+ let parsed: unknown
405
+ try {
406
+ parsed = raw ? JSON.parse(raw) : undefined
407
+ } catch {
408
+ parsed = undefined
409
+ }
410
+ const error = (parsed as { error?: { code?: unknown; message?: unknown } } | undefined)?.error
411
+ throw new AdulaApiError(
412
+ response.status,
413
+ typeof error?.code === 'string' ? error.code : 'E_HTTP',
414
+ typeof error?.message === 'string'
415
+ ? error.message
416
+ : response.statusText || 'HTTP ' + response.status,
417
+ parsed ?? raw
418
+ )
419
+ }
420
+ if (init.text) return raw
421
+ return raw ? JSON.parse(raw) : undefined
422
+ }
423
+ const data = async (promise: Promise<unknown>) => ((await promise) as { data: unknown }).data
424
+ const segment = (value: string | number) => encodeURIComponent(String(value))
425
+ const resources: Record<string, Record<string, unknown>> = {}
426
+ for (const [name, operations] of Object.entries(ADULA_OPERATIONS)) {
427
+ const path = '/resources/' + segment(name)
428
+ const item = (id: number) => path + '/' + segment(id)
429
+ const methods: Record<string, unknown> = {
430
+ list: (query?: Record<string, unknown>) => call('GET', path, { query }),
431
+ show: (id: number) => data(call('GET', item(id))),
432
+ create: (input: unknown) => data(call('POST', path, { body: input })),
433
+ update: (id: number, input: unknown) => data(call('PATCH', item(id), { body: input })),
434
+ delete: (id: number, transition?: AdulaTransitionOptions) =>
435
+ data(call('DELETE', item(id), { body: transition })),
436
+ submit: (id: number, transition?: AdulaTransitionOptions) =>
437
+ data(call('POST', item(id) + '/submit', { body: transition })),
438
+ cancel: (id: number, transition?: AdulaTransitionOptions) =>
439
+ data(call('POST', item(id) + '/cancel', { body: transition })),
440
+ amend: (id: number) => data(call('POST', item(id) + '/amend', { body: {} })),
441
+ aggregate: (query?: Record<string, unknown>) => data(call('GET', path + '/aggregate', { query })),
442
+ }
443
+ // Only the operations the document describes exist, at runtime as in the types.
444
+ resources[name] = Object.fromEntries(
445
+ operations.map((operation) => [operation, methods[operation]])
446
+ )
447
+ }
448
+ const client: Record<string, unknown> = {
449
+ resources,
450
+ request: (method: string, path: string, body?: unknown) =>
451
+ call(method.toUpperCase(), path.startsWith('/') ? path : '/' + path, { body }),
452
+ }
453
+ if (ADULA_IMPORTS)
454
+ client.imports = {
455
+ list: () => data(call('GET', '/imports')),
456
+ show: (id: number) => data(call('GET', '/imports/' + segment(id))),
457
+ create: (resource: string, input: unknown) =>
458
+ data(call('POST', '/resources/' + segment(resource) + '/imports', { body: input })),
459
+ start: (id: number, input: unknown) =>
460
+ data(call('POST', '/imports/' + segment(id) + '/start', { body: input })),
461
+ template: (resource: string, options?: { mode?: string }) =>
462
+ call('GET', '/resources/' + segment(resource) + '/imports/template', {
463
+ query: options,
464
+ text: true,
465
+ }),
466
+ xlsxTemplate: (resource: string, options?: { mode?: string }) =>
467
+ call('GET', '/resources/' + segment(resource) + '/imports/template', {
468
+ query: { ...options, format: 'xlsx' },
469
+ binary: true,
470
+ }),
471
+ }
472
+ return client as unknown as AdulaClient
473
+ }
474
+ `;
475
+ /**
476
+ * One self-contained TypeScript module for the API the document describes: record and
477
+ * input interfaces per resource, the Resources map and createAdulaClient().
478
+ */
479
+ export function apiClientSource(document, options = {}) {
480
+ const types = typesSection(document);
481
+ const server = options.baseUrl ?? document.servers?.[0]?.url ?? '';
482
+ const operations = types.resources
483
+ .filter((resource) => resource.operations.size)
484
+ .map((resource) => ` ${propertyKey(resource.name)}: [${[...resource.operations].map((operation) => `'${operation}'`).join(', ')}],`);
485
+ return [
486
+ header(document),
487
+ types.text,
488
+ '',
489
+ `export const ADULA_API_SERVER: string = ${JSON.stringify(server)}`,
490
+ `export const ADULA_API_BASE_PATH: string = ${JSON.stringify(types.basePath)}`,
491
+ `const ADULA_IMPORTS: boolean = ${types.imports}`,
492
+ `const ADULA_OPERATIONS: Record<string, readonly string[]> = {`,
493
+ ...operations,
494
+ `}`,
495
+ RUNTIME,
496
+ ].join('\n');
497
+ }
498
+ /** The same client as a declaration file: the types plus the runtime signatures. */
499
+ export function apiClientDeclarations(document) {
500
+ const types = typesSection(document);
501
+ return [
502
+ header(document),
503
+ types.text,
504
+ '',
505
+ `export declare const ADULA_API_SERVER: string`,
506
+ `export declare const ADULA_API_BASE_PATH: string`,
507
+ `export declare class AdulaApiError extends Error {`,
508
+ ` readonly status: number`,
509
+ ` readonly code: string`,
510
+ ` readonly body: unknown`,
511
+ ` constructor(status: number, code: string, message: string, body?: unknown)`,
512
+ `}`,
513
+ `export declare function createAdulaClient(options: AdulaClientOptions): AdulaClient`,
514
+ '',
515
+ ].join('\n');
516
+ }
517
+ /** The clients/<name> directory of a system: its package name without scope, in kebab-case. */
518
+ export function apiClientName(packageName) {
519
+ const name = String(packageName ?? '')
520
+ .replace(/^@[^/]+\//, '')
521
+ .toLowerCase()
522
+ .replace(/[^a-z0-9]+/g, '-')
523
+ .replace(/^-+|-+$/g, '');
524
+ return name || 'app';
525
+ }
526
+ /** README.md written next to a generated client by adula:client. */
527
+ export function apiClientReadme(name, document) {
528
+ const resources = Object.keys(document.paths)
529
+ .map((path) => /\/resources\/([^/{]+)$/.exec(path)?.[1])
530
+ .filter((resource) => Boolean(resource));
531
+ const example = resources[0] ?? '<resource>';
532
+ return `# ${name} API client
533
+
534
+ Generated by \`node ace adula:client\` from the resource registry. Do not edit
535
+ \`index.ts\`; run the command again after resources change. A running system also serves
536
+ the client for the calling token at \`GET /api/v1/client.ts\` (types only:
537
+ \`GET /api/v1/client.d.ts\`), limited to what that token's owner may use.
538
+
539
+ ## Token
540
+
541
+ Create a personal API token under **Account → API tokens** (read tokens may only call GET).
542
+ The client sends it as \`Authorization: Bearer <token>\`; every call is authorized with the
543
+ token owner's current roles, exactly as in the user interface. Keep the token in an
544
+ environment variable, never in source control.
545
+
546
+ ## Usage
547
+
548
+ \`\`\`ts
549
+ import { createAdulaClient, AdulaApiError } from './index.js'
550
+
551
+ const api = createAdulaClient({ baseUrl: 'https://erp.example.com', token: process.env.ADULA_TOKEN! })
552
+ const page = await api.resources.${example}.list({ limit: 50 })
553
+ for (const record of page.data) console.log(record.id)
554
+ // The next page: list({ cursor: page.meta.nextCursor })
555
+ try {
556
+ await api.resources.${example}.show(1)
557
+ } catch (error) {
558
+ if (error instanceof AdulaApiError) console.error(error.status, error.code, error.message)
559
+ }
560
+ \`\`\`
561
+
562
+ Money fields are decimal strings in minor units (\`"1050"\` is 10.50). Methods exist only
563
+ for the operations the API allows on each resource; filters, sort fields and input fields
564
+ are typed from the registry. The module has no dependencies and needs a global \`fetch\`
565
+ (Node.js 18+, browsers) or \`createAdulaClient({ fetch })\`.
566
+ `;
567
+ }
@@ -0,0 +1,37 @@
1
+ /** An uploaded import file as adapters see it: raw bytes, with the UTF-8 text decoded on demand. */
2
+ export type ImportFile = {
3
+ fileName: string;
4
+ mimeType?: string;
5
+ bytes: Uint8Array;
6
+ /** The bytes decoded as UTF-8 without a byte-order mark. */
7
+ readonly text: string;
8
+ };
9
+ /** A parsed sheet: one header row and the data rows as strings. */
10
+ export type ImportTable = {
11
+ headers: string[];
12
+ rows: string[][];
13
+ };
14
+ /**
15
+ * A file format the import batches can read. The CSV adapter is built in; other
16
+ * formats (for example XLSX) are registered through `ImportBatches` option `adapters`
17
+ * or `ImportBatches.registerAdapter()`. Limits (5 MB, 100 columns, 5000 rows) and
18
+ * the column mapping apply to every adapter's result.
19
+ */
20
+ export interface ImportAdapter {
21
+ /** Short format name used by the API's `format` field, for example 'csv' or 'xlsx'. */
22
+ name: string;
23
+ /** Lower-case file extensions without the dot, accepted by the upload. */
24
+ extensions: string[];
25
+ mimeTypes?: string[];
26
+ /** True for formats that are not UTF-8 text; JSON API uploads then send base64. */
27
+ binary?: boolean;
28
+ /** Whether this adapter reads the file (usually by extension, MIME type or signature). */
29
+ detect(file: ImportFile): boolean;
30
+ /** Parses the file; throw AdulaError(422, 'E_IMPORT_FILE', '…') with an Arabic message. */
31
+ parse(file: ImportFile): Promise<ImportTable>;
32
+ }
33
+ export declare function extensionOf(fileName: string): string;
34
+ /** Wraps raw upload bytes; the text is decoded once, only when an adapter reads it. */
35
+ export declare function importFile(fileName: string, bytes: Uint8Array, mimeType?: string): ImportFile;
36
+ /** The built-in CSV adapter (papaparse, delimiter detection, UTF-8 with or without BOM). */
37
+ export declare const csvImportAdapter: ImportAdapter;
@@ -0,0 +1,35 @@
1
+ import Papa from 'papaparse';
2
+ import { AdulaError } from '../admin/errors.js';
3
+ export function extensionOf(fileName) {
4
+ const dot = fileName.lastIndexOf('.');
5
+ return dot === -1 ? '' : fileName.slice(dot + 1).toLowerCase();
6
+ }
7
+ /** Wraps raw upload bytes; the text is decoded once, only when an adapter reads it. */
8
+ export function importFile(fileName, bytes, mimeType) {
9
+ let text;
10
+ return {
11
+ fileName,
12
+ mimeType,
13
+ bytes,
14
+ get text() {
15
+ text ??= Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength)
16
+ .toString('utf8')
17
+ .replace(/^\uFEFF/, '');
18
+ return text;
19
+ },
20
+ };
21
+ }
22
+ /** The built-in CSV adapter (papaparse, delimiter detection, UTF-8 with or without BOM). */
23
+ export const csvImportAdapter = {
24
+ name: 'csv',
25
+ extensions: ['csv', 'txt'],
26
+ mimeTypes: ['text/csv', 'text/plain', 'application/vnd.ms-excel'],
27
+ detect: (file) => ['csv', 'txt'].includes(extensionOf(file.fileName)),
28
+ async parse(file) {
29
+ const parsed = Papa.parse(file.text, { skipEmptyLines: 'greedy' });
30
+ if (parsed.errors.some((error) => error.type !== 'Delimiter'))
31
+ throw new AdulaError(422, 'E_IMPORT_FILE', `تعذر قراءة CSV: ${parsed.errors[0].message}`);
32
+ const [headers = [], ...rows] = parsed.data;
33
+ return { headers, rows };
34
+ },
35
+ };