adula 2.0.0 → 2.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (214) hide show
  1. package/README.md +149 -18
  2. package/build/agent/AGENTS.template.md +4 -4
  3. package/build/agent/capabilities.md +22 -11
  4. package/build/agent/skills/adula-frontend-design/SKILL.md +1 -1
  5. package/build/agent/skills/idea-review/SKILL.md +2 -2
  6. package/build/commands/adula_outbox.d.ts +10 -0
  7. package/build/commands/adula_outbox.js +11 -0
  8. package/build/commands/adula_restore_reconcile.d.ts +10 -0
  9. package/build/commands/adula_restore_reconcile.js +34 -0
  10. package/build/commands/adula_runtime_health.d.ts +10 -0
  11. package/build/commands/adula_runtime_health.js +27 -0
  12. package/build/commands/adula_uploads_prune.d.ts +10 -0
  13. package/build/commands/adula_uploads_prune.js +16 -0
  14. package/build/commands/app.d.ts +10 -0
  15. package/build/commands/app.js +64 -0
  16. package/build/commands/backup_create.d.ts +11 -0
  17. package/build/commands/backup_create.js +99 -0
  18. package/build/commands/backup_restore_files.d.ts +11 -0
  19. package/build/commands/backup_restore_files.js +44 -0
  20. package/build/commands/backup_restore_test.d.ts +12 -0
  21. package/build/commands/backup_restore_test.js +185 -0
  22. package/build/commands/backup_services.d.ts +31 -0
  23. package/build/commands/backup_services.js +6 -0
  24. package/build/commands/backup_verify.d.ts +9 -0
  25. package/build/commands/backup_verify.js +59 -0
  26. package/build/commands/backup_verify_snapshot.d.ts +10 -0
  27. package/build/commands/backup_verify_snapshot.js +37 -0
  28. package/build/commands/client.d.ts +16 -0
  29. package/build/commands/client.js +71 -0
  30. package/build/commands/doctor.js +4 -1
  31. package/build/commands/install.d.ts +8 -0
  32. package/build/commands/install.js +63 -45
  33. package/build/commands/main.d.ts +3 -2
  34. package/build/commands/main.js +26 -0
  35. package/build/commands/module_add.js +4 -20
  36. package/build/commands/resource.d.ts +2 -0
  37. package/build/commands/resource.js +12 -3
  38. package/build/commands/resource_migration.d.ts +15 -0
  39. package/build/commands/resource_migration.js +72 -0
  40. package/build/commands/resource_snapshot.d.ts +2 -0
  41. package/build/commands/resource_snapshot.js +3 -0
  42. package/build/commands/sla_evaluate.d.ts +14 -0
  43. package/build/commands/sla_evaluate.js +16 -0
  44. package/build/commands/ui.js +5 -3
  45. package/build/commands/ui_css.d.ts +9 -0
  46. package/build/commands/ui_css.js +19 -0
  47. package/build/commands/upgrade.d.ts +1 -1
  48. package/build/commands/upgrade.js +1 -1
  49. package/build/configure.js +1 -1
  50. package/build/database/migrations/1770000000020_two_factor.d.ts +5 -0
  51. package/build/database/migrations/1770000000020_two_factor.js +10 -0
  52. package/build/database/migrations/1770000000041_import_modes.d.ts +5 -0
  53. package/build/database/migrations/1770000000041_import_modes.js +10 -0
  54. package/build/database/migrations/1770000000042_sync_jobs.d.ts +5 -0
  55. package/build/database/migrations/1770000000042_sync_jobs.js +10 -0
  56. package/build/database/migrations/1770000000043_notification_channels.d.ts +5 -0
  57. package/build/database/migrations/1770000000043_notification_channels.js +10 -0
  58. package/build/database/migrations/1770000000044_channel_confirmations.d.ts +5 -0
  59. package/build/database/migrations/1770000000044_channel_confirmations.js +10 -0
  60. package/build/database/migrations/1770000000045_import_leases.d.ts +5 -0
  61. package/build/database/migrations/1770000000045_import_leases.js +10 -0
  62. package/build/database/migrations/1770000000046_workflow_delegation_sla.d.ts +5 -0
  63. package/build/database/migrations/1770000000046_workflow_delegation_sla.js +10 -0
  64. package/build/database/migrations/1770000000049_print_templates.d.ts +5 -0
  65. package/build/database/migrations/1770000000049_print_templates.js +10 -0
  66. package/build/index.d.ts +56 -10
  67. package/build/index.js +34 -6
  68. package/build/providers/adula_provider.d.ts +2 -0
  69. package/build/providers/adula_provider.js +7 -0
  70. package/build/src/admin/contracts.js +1 -1
  71. package/build/src/admin/controller.d.ts +14 -1
  72. package/build/src/admin/controller.js +77 -13
  73. package/build/src/admin/errors.d.ts +32 -0
  74. package/build/src/admin/errors.js +63 -1
  75. package/build/src/admin/presentation.d.ts +21 -2
  76. package/build/src/admin/resource/editor.d.ts +59 -0
  77. package/build/src/admin/resource/editor.js +323 -0
  78. package/build/src/admin/resource/export.d.ts +37 -0
  79. package/build/src/admin/resource/export.js +181 -0
  80. package/build/src/admin/resource/lifecycle.d.ts +21 -0
  81. package/build/src/admin/resource/lifecycle.js +91 -0
  82. package/build/src/admin/resource/query.d.ts +100 -0
  83. package/build/src/admin/resource/query.js +508 -0
  84. package/build/src/admin/resource/read.d.ts +106 -0
  85. package/build/src/admin/resource/read.js +327 -0
  86. package/build/src/admin/resource/shared.d.ts +77 -0
  87. package/build/src/admin/resource/shared.js +222 -0
  88. package/build/src/admin/resource/trash.d.ts +10 -0
  89. package/build/src/admin/resource/trash.js +56 -0
  90. package/build/src/admin/resource/write.d.ts +57 -0
  91. package/build/src/admin/resource/write.js +574 -0
  92. package/build/src/admin/resource_service.d.ts +66 -193
  93. package/build/src/admin/resource_service.js +69 -1345
  94. package/build/src/attachments/attachment_service.d.ts +46 -2
  95. package/build/src/attachments/attachment_service.js +96 -4
  96. package/build/src/auth/conditions.d.ts +5 -0
  97. package/build/src/auth/conditions.js +26 -3
  98. package/build/src/auth/sql.js +17 -5
  99. package/build/src/auth/two_factor.d.ts +96 -0
  100. package/build/src/auth/two_factor.js +259 -0
  101. package/build/src/collaboration/assignments.d.ts +36 -1
  102. package/build/src/collaboration/assignments.js +132 -66
  103. package/build/src/collaboration/record_collaboration.d.ts +2 -3
  104. package/build/src/collaboration/record_collaboration.js +19 -16
  105. package/build/src/collaboration/shared.d.ts +16 -0
  106. package/build/src/collaboration/shared.js +21 -0
  107. package/build/src/commands/app_scaffold.d.ts +72 -0
  108. package/build/src/commands/app_scaffold.js +285 -0
  109. package/build/src/commands/capabilities.js +34 -8
  110. package/build/src/commands/doctor.d.ts +14 -2
  111. package/build/src/commands/doctor.js +50 -5
  112. package/build/src/commands/gap_report.d.ts +1 -1
  113. package/build/src/commands/gap_report.js +2 -2
  114. package/build/src/commands/generator.d.ts +37 -1
  115. package/build/src/commands/generator.js +61 -18
  116. package/build/src/commands/snapshot.d.ts +10 -13
  117. package/build/src/commands/snapshot.js +31 -14
  118. package/build/src/commands/source_markers.d.ts +10 -0
  119. package/build/src/commands/source_markers.js +29 -0
  120. package/build/src/core/activity.d.ts +2 -0
  121. package/build/src/core/activity.js +7 -1
  122. package/build/src/core/administrators.d.ts +38 -0
  123. package/build/src/core/administrators.js +129 -0
  124. package/build/src/core/html_sanitizer.d.ts +20 -0
  125. package/build/src/core/html_sanitizer.js +261 -0
  126. package/build/src/core/like.d.ts +5 -0
  127. package/build/src/core/like.js +5 -0
  128. package/build/src/core/lookups.d.ts +80 -0
  129. package/build/src/core/lookups.js +319 -0
  130. package/build/src/core/message_templates.d.ts +7 -2
  131. package/build/src/core/message_templates.js +72 -11
  132. package/build/src/core/module_seed.js +2 -1
  133. package/build/src/core/notification_channels.d.ts +235 -0
  134. package/build/src/core/notification_channels.js +660 -0
  135. package/build/src/core/roles.js +2 -2
  136. package/build/src/core/saved_views.d.ts +8 -1
  137. package/build/src/core/saved_views.js +36 -2
  138. package/build/src/core/sequences.d.ts +32 -0
  139. package/build/src/core/sequences.js +97 -0
  140. package/build/src/core/settings.d.ts +5 -0
  141. package/build/src/core/settings.js +19 -2
  142. package/build/src/core/template_language.d.ts +61 -0
  143. package/build/src/core/template_language.js +141 -0
  144. package/build/src/core/ui_preferences.d.ts +4 -0
  145. package/build/src/core/ui_preferences.js +4 -1
  146. package/build/src/core/user_invitations.d.ts +5 -1
  147. package/build/src/core/user_invitations.js +7 -1
  148. package/build/src/core/users.js +1 -1
  149. package/build/src/database/calendar_days.d.ts +19 -0
  150. package/build/src/database/calendar_days.js +36 -0
  151. package/build/src/database/schema.d.ts +155 -2
  152. package/build/src/database/schema.js +531 -59
  153. package/build/src/database/schema_diff.d.ts +56 -0
  154. package/build/src/database/schema_diff.js +157 -0
  155. package/build/src/events/record_mutation.d.ts +2 -1
  156. package/build/src/events/record_mutation.js +1 -0
  157. package/build/src/integrations/api_client.d.ts +37 -0
  158. package/build/src/integrations/api_client.js +552 -0
  159. package/build/src/integrations/import_adapters.d.ts +37 -0
  160. package/build/src/integrations/import_adapters.js +35 -0
  161. package/build/src/integrations/imports.d.ts +118 -16
  162. package/build/src/integrations/imports.js +406 -73
  163. package/build/src/integrations/openapi.d.ts +3 -1
  164. package/build/src/integrations/openapi.js +454 -31
  165. package/build/src/integrations/outbound.d.ts +51 -0
  166. package/build/src/integrations/outbound.js +195 -0
  167. package/build/src/integrations/print.d.ts +21 -1
  168. package/build/src/integrations/print.js +63 -21
  169. package/build/src/integrations/print_templates.d.ts +216 -0
  170. package/build/src/integrations/print_templates.js +1015 -0
  171. package/build/src/integrations/sync_jobs.d.ts +139 -0
  172. package/build/src/integrations/sync_jobs.js +416 -0
  173. package/build/src/integrations/webhooks.d.ts +12 -12
  174. package/build/src/integrations/webhooks.js +34 -43
  175. package/build/src/languages/ar.d.ts +11 -0
  176. package/build/src/languages/ar.js +336 -0
  177. package/build/src/languages/ar_ui.d.ts +332 -0
  178. package/build/src/languages/ar_ui.js +333 -0
  179. package/build/src/languages/catalog.d.ts +66 -0
  180. package/build/src/languages/catalog.js +152 -0
  181. package/build/src/languages/en.d.ts +7 -0
  182. package/build/src/languages/en.js +330 -0
  183. package/build/src/languages/en_ui.d.ts +3 -0
  184. package/build/src/languages/en_ui.js +328 -0
  185. package/build/src/languages/validation.d.ts +26 -0
  186. package/build/src/languages/validation.js +60 -0
  187. package/build/src/lists/bulk_actions.d.ts +89 -0
  188. package/build/src/lists/bulk_actions.js +268 -0
  189. package/build/src/lists/dashboards.d.ts +96 -0
  190. package/build/src/lists/dashboards.js +241 -0
  191. package/build/src/mcp/tools.js +1 -1
  192. package/build/src/resource/define_resource.d.ts +18 -1
  193. package/build/src/resource/define_resource.js +205 -18
  194. package/build/src/resource/definition.d.ts +44 -0
  195. package/build/src/resource/definition.js +171 -0
  196. package/build/src/resource/registry.js +15 -4
  197. package/build/src/resource/types.d.ts +304 -16
  198. package/build/src/resource/values.d.ts +56 -1
  199. package/build/src/resource/values.js +237 -5
  200. package/build/src/services/settings.d.ts +2 -0
  201. package/build/src/services/settings.js +5 -1
  202. package/build/src/upgrade/legacy.js +2 -2
  203. package/build/src/workflows/calendar.d.ts +9 -0
  204. package/build/src/workflows/calendar.js +44 -0
  205. package/build/src/workflows/define_workflow.d.ts +48 -3
  206. package/build/src/workflows/define_workflow.js +57 -13
  207. package/build/src/workflows/delegations.d.ts +93 -0
  208. package/build/src/workflows/delegations.js +287 -0
  209. package/build/src/workflows/engine.d.ts +69 -4
  210. package/build/src/workflows/engine.js +441 -83
  211. package/build/src/workflows/sla.d.ts +15 -0
  212. package/build/src/workflows/sla.js +8 -0
  213. package/build/stubs/resource_contract.txt +12 -1
  214. package/package.json +5 -2
@@ -0,0 +1,552 @@
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
+ `}`,
228
+ `/** The global fetch, or any compatible implementation (tests, proxies, retries). */`,
229
+ `export type AdulaFetch = (`,
230
+ ` url: string,`,
231
+ ` init: { method: string; headers: Record<string, string>; body?: string }`,
232
+ `) => Promise<AdulaFetchResponse>`,
233
+ `export interface AdulaClientOptions {`,
234
+ ` /** Server origin, for example https://erp.example.com. Defaults to the server this client was generated from. */`,
235
+ ` baseUrl?: string`,
236
+ ` /** API prefix. Defaults to ${JSON.stringify(basePath)}. */`,
237
+ ` basePath?: string`,
238
+ ` /** A personal API token (Account → API tokens), sent as a bearer token. */`,
239
+ ` token: string`,
240
+ ` fetch?: AdulaFetch`,
241
+ `}`,
242
+ `export interface AdulaListQuery<Filters, Sort extends string> {`,
243
+ ` limit?: number`,
244
+ ` /** meta.nextCursor of the previous page. */`,
245
+ ` cursor?: string | null`,
246
+ ` search?: string`,
247
+ ` sort?: Sort`,
248
+ ` direction?: 'asc' | 'desc'`,
249
+ ` tag?: string`,
250
+ ` /** false skips meta.estimatedTotal. */`,
251
+ ` estimate?: boolean`,
252
+ ` /** Equality filters on filterable fields (filters[field]=value). */`,
253
+ ` filters?: Filters`,
254
+ `}`,
255
+ `export interface AdulaPage<Row> {`,
256
+ ` data: Row[]`,
257
+ ` meta: { limit: number; nextCursor: string | null; estimatedTotal?: number }`,
258
+ `}`,
259
+ `export interface AdulaAggregateQuery<Filters> {`,
260
+ ` /** Up to three fields. */`,
261
+ ` groupBy?: string | readonly string[]`,
262
+ ` /** Integer or money fields to total. */`,
263
+ ` sum?: string | readonly string[]`,
264
+ ` /** Conditions ($eq, $ne, $in, $lt, $gt, $like) as an object or its JSON. */`,
265
+ ` where?: Record<string, unknown> | string`,
266
+ ` search?: string`,
267
+ ` count?: boolean`,
268
+ ` filters?: Filters`,
269
+ `}`,
270
+ `export interface AdulaAggregate {`,
271
+ ` truncated?: boolean`,
272
+ ` rows: Array<{ group: Record<string, unknown>; count?: number; sum?: Record<string, string | null> }>`,
273
+ `}`,
274
+ `export interface AdulaTransitionOptions {`,
275
+ ` /** The record version read last (optimistic locking). */`,
276
+ ` version?: number`,
277
+ `}`,
278
+ '',
279
+ ];
280
+ for (const [key, schema] of Object.entries(schemas))
281
+ lines.push(declaration(names.get(key), schema, names));
282
+ const clients = [];
283
+ for (const resource of resources) {
284
+ const record = names.get(resource.name) ?? 'Record<string, unknown>';
285
+ const input = names.get(`${resource.name}_input`) ?? 'Record<string, unknown>';
286
+ const type = resource.type;
287
+ lines.push(resource.filters
288
+ ? declaration(`${type}Filters`, resource.filters, names)
289
+ : `export type ${type}Filters = Record<string, never>\n`, `export type ${type}Sort = ${literal(resource.sort)}\n`);
290
+ const methods = [];
291
+ const has = (operation) => resource.operations.has(operation);
292
+ if (has('list'))
293
+ methods.push(` list(query?: AdulaListQuery<${type}Filters, ${type}Sort>): Promise<AdulaPage<${record}>>`);
294
+ if (has('show'))
295
+ methods.push(` show(id: number): Promise<${record}>`);
296
+ if (has('create'))
297
+ methods.push(` create(input: ${input}): Promise<${record}>`);
298
+ if (has('update'))
299
+ methods.push(` /** Only the given fields change; pass version on versioned resources. */`, ` update(id: number, input: Partial<${input}>): Promise<${record}>`);
300
+ if (has('delete'))
301
+ methods.push(` delete(id: number, options?: AdulaTransitionOptions): Promise<${record}>`);
302
+ if (has('submit'))
303
+ methods.push(` submit(id: number, options?: AdulaTransitionOptions): Promise<${record}>`);
304
+ if (has('cancel'))
305
+ methods.push(` cancel(id: number, options?: AdulaTransitionOptions): Promise<${record}>`);
306
+ if (has('amend'))
307
+ methods.push(` /** A new draft copied from the cancelled document. */`, ` amend(id: number): Promise<${record}>`);
308
+ if (has('aggregate'))
309
+ methods.push(` aggregate(query?: AdulaAggregateQuery<${type}Filters>): Promise<AdulaAggregate>`);
310
+ lines.push(`export interface ${type}Client {\n${methods.join('\n')}\n}\n`);
311
+ clients.push(` ${propertyKey(resource.name)}: ${type}Client`);
312
+ }
313
+ 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, `}`);
314
+ const importable = resources.filter((resource) => resource.importable);
315
+ if (imports) {
316
+ if (!names.has('ImportBatch'))
317
+ lines.push(`export type AdulaImportBatch = Record<string, unknown>`);
318
+ 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 ?? {
319
+ type: 'object',
320
+ properties: { mapping: { type: 'object', additionalProperties: { type: 'string' } } },
321
+ required: ['mapping'],
322
+ }, 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>`, `}`);
323
+ }
324
+ 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>`, `}`);
325
+ return { text: lines.join('\n'), resources, basePath, imports };
326
+ }
327
+ function header(document) {
328
+ const title = [document.info?.title, document.info?.version].filter(Boolean).join(' ');
329
+ return [
330
+ `// Generated by AdulaJS from the OpenAPI document${title ? ` of ${title}` : ''}.`,
331
+ `// Do not edit: regenerate with \`node ace adula:client\` or download GET /api/v1/client.ts.`,
332
+ `/* eslint-disable */`,
333
+ '',
334
+ ].join('\n');
335
+ }
336
+ const RUNTIME = `
337
+ export class AdulaApiError extends Error {
338
+ readonly status: number
339
+ readonly code: string
340
+ readonly body: unknown
341
+ constructor(status: number, code: string, message: string, body?: unknown) {
342
+ super(message)
343
+ this.name = 'AdulaApiError'
344
+ this.status = status
345
+ this.code = code
346
+ this.body = body
347
+ }
348
+ }
349
+
350
+ function adulaQuery(query: Record<string, unknown> | undefined) {
351
+ const parts: string[] = []
352
+ const add = (key: string, value: unknown) => {
353
+ if (value === undefined || value === null || value === '') return
354
+ parts.push(key + '=' + encodeURIComponent(String(value)))
355
+ }
356
+ for (const key of Object.keys(query ?? {})) {
357
+ const value = (query as Record<string, unknown>)[key]
358
+ if (key === 'filters' && value && typeof value === 'object') {
359
+ const filters = value as Record<string, unknown>
360
+ for (const field of Object.keys(filters)) add('filters[' + encodeURIComponent(field) + ']', filters[field])
361
+ } else if ((key === 'groupBy' || key === 'sum') && Array.isArray(value)) add(key, value.join(','))
362
+ else if (key === 'where' && value && typeof value === 'object') add(key, JSON.stringify(value))
363
+ else add(encodeURIComponent(key), value)
364
+ }
365
+ return parts.length ? '?' + parts.join('&') : ''
366
+ }
367
+
368
+ export function createAdulaClient(options: AdulaClientOptions): AdulaClient {
369
+ const globalFetch = (globalThis as unknown as { fetch?: AdulaFetch }).fetch
370
+ const fetcher: AdulaFetch | undefined =
371
+ options.fetch ?? (globalFetch ? (url, init) => globalFetch(url, init) : undefined)
372
+ if (!fetcher) throw new Error('No fetch implementation: pass options.fetch')
373
+ if (!options.token) throw new Error('A personal API token is required')
374
+ const root =
375
+ (options.baseUrl ?? ADULA_API_SERVER).replace(/\\/+$/, '') +
376
+ (options.basePath ?? ADULA_API_BASE_PATH).replace(/\\/+$/, '')
377
+ async function call(
378
+ method: string,
379
+ path: string,
380
+ init: { query?: Record<string, unknown>; body?: unknown; text?: boolean } = {}
381
+ ): Promise<unknown> {
382
+ const headers: Record<string, string> = {
383
+ Authorization: 'Bearer ' + options.token,
384
+ Accept: init.text ? 'text/csv, text/plain, */*' : 'application/json',
385
+ }
386
+ if (init.body !== undefined) headers['Content-Type'] = 'application/json'
387
+ const response = await fetcher!(root + path + adulaQuery(init.query), {
388
+ method,
389
+ headers,
390
+ ...(init.body === undefined ? {} : { body: JSON.stringify(init.body) }),
391
+ })
392
+ const raw = await response.text()
393
+ if (!response.ok) {
394
+ let parsed: unknown
395
+ try {
396
+ parsed = raw ? JSON.parse(raw) : undefined
397
+ } catch {
398
+ parsed = undefined
399
+ }
400
+ const error = (parsed as { error?: { code?: unknown; message?: unknown } } | undefined)?.error
401
+ throw new AdulaApiError(
402
+ response.status,
403
+ typeof error?.code === 'string' ? error.code : 'E_HTTP',
404
+ typeof error?.message === 'string'
405
+ ? error.message
406
+ : response.statusText || 'HTTP ' + response.status,
407
+ parsed ?? raw
408
+ )
409
+ }
410
+ if (init.text) return raw
411
+ return raw ? JSON.parse(raw) : undefined
412
+ }
413
+ const data = async (promise: Promise<unknown>) => ((await promise) as { data: unknown }).data
414
+ const segment = (value: string | number) => encodeURIComponent(String(value))
415
+ const resources: Record<string, Record<string, unknown>> = {}
416
+ for (const [name, operations] of Object.entries(ADULA_OPERATIONS)) {
417
+ const path = '/resources/' + segment(name)
418
+ const item = (id: number) => path + '/' + segment(id)
419
+ const methods: Record<string, unknown> = {
420
+ list: (query?: Record<string, unknown>) => call('GET', path, { query }),
421
+ show: (id: number) => data(call('GET', item(id))),
422
+ create: (input: unknown) => data(call('POST', path, { body: input })),
423
+ update: (id: number, input: unknown) => data(call('PATCH', item(id), { body: input })),
424
+ delete: (id: number, transition?: AdulaTransitionOptions) =>
425
+ data(call('DELETE', item(id), { body: transition })),
426
+ submit: (id: number, transition?: AdulaTransitionOptions) =>
427
+ data(call('POST', item(id) + '/submit', { body: transition })),
428
+ cancel: (id: number, transition?: AdulaTransitionOptions) =>
429
+ data(call('POST', item(id) + '/cancel', { body: transition })),
430
+ amend: (id: number) => data(call('POST', item(id) + '/amend', { body: {} })),
431
+ aggregate: (query?: Record<string, unknown>) => data(call('GET', path + '/aggregate', { query })),
432
+ }
433
+ // Only the operations the document describes exist, at runtime as in the types.
434
+ resources[name] = Object.fromEntries(
435
+ operations.map((operation) => [operation, methods[operation]])
436
+ )
437
+ }
438
+ const client: Record<string, unknown> = {
439
+ resources,
440
+ request: (method: string, path: string, body?: unknown) =>
441
+ call(method.toUpperCase(), path.startsWith('/') ? path : '/' + path, { body }),
442
+ }
443
+ if (ADULA_IMPORTS)
444
+ client.imports = {
445
+ list: () => data(call('GET', '/imports')),
446
+ show: (id: number) => data(call('GET', '/imports/' + segment(id))),
447
+ create: (resource: string, input: unknown) =>
448
+ data(call('POST', '/resources/' + segment(resource) + '/imports', { body: input })),
449
+ start: (id: number, input: unknown) =>
450
+ data(call('POST', '/imports/' + segment(id) + '/start', { body: input })),
451
+ template: (resource: string, options?: { mode?: string }) =>
452
+ call('GET', '/resources/' + segment(resource) + '/imports/template', {
453
+ query: options,
454
+ text: true,
455
+ }),
456
+ }
457
+ return client as unknown as AdulaClient
458
+ }
459
+ `;
460
+ /**
461
+ * One self-contained TypeScript module for the API the document describes: record and
462
+ * input interfaces per resource, the Resources map and createAdulaClient().
463
+ */
464
+ export function apiClientSource(document, options = {}) {
465
+ const types = typesSection(document);
466
+ const server = options.baseUrl ?? document.servers?.[0]?.url ?? '';
467
+ const operations = types.resources
468
+ .filter((resource) => resource.operations.size)
469
+ .map((resource) => ` ${propertyKey(resource.name)}: [${[...resource.operations].map((operation) => `'${operation}'`).join(', ')}],`);
470
+ return [
471
+ header(document),
472
+ types.text,
473
+ '',
474
+ `export const ADULA_API_SERVER: string = ${JSON.stringify(server)}`,
475
+ `export const ADULA_API_BASE_PATH: string = ${JSON.stringify(types.basePath)}`,
476
+ `const ADULA_IMPORTS: boolean = ${types.imports}`,
477
+ `const ADULA_OPERATIONS: Record<string, readonly string[]> = {`,
478
+ ...operations,
479
+ `}`,
480
+ RUNTIME,
481
+ ].join('\n');
482
+ }
483
+ /** The same client as a declaration file: the types plus the runtime signatures. */
484
+ export function apiClientDeclarations(document) {
485
+ const types = typesSection(document);
486
+ return [
487
+ header(document),
488
+ types.text,
489
+ '',
490
+ `export declare const ADULA_API_SERVER: string`,
491
+ `export declare const ADULA_API_BASE_PATH: string`,
492
+ `export declare class AdulaApiError extends Error {`,
493
+ ` readonly status: number`,
494
+ ` readonly code: string`,
495
+ ` readonly body: unknown`,
496
+ ` constructor(status: number, code: string, message: string, body?: unknown)`,
497
+ `}`,
498
+ `export declare function createAdulaClient(options: AdulaClientOptions): AdulaClient`,
499
+ '',
500
+ ].join('\n');
501
+ }
502
+ /** The clients/<name> directory of a system: its package name without scope, in kebab-case. */
503
+ export function apiClientName(packageName) {
504
+ const name = String(packageName ?? '')
505
+ .replace(/^@[^/]+\//, '')
506
+ .toLowerCase()
507
+ .replace(/[^a-z0-9]+/g, '-')
508
+ .replace(/^-+|-+$/g, '');
509
+ return name || 'app';
510
+ }
511
+ /** README.md written next to a generated client by adula:client. */
512
+ export function apiClientReadme(name, document) {
513
+ const resources = Object.keys(document.paths)
514
+ .map((path) => /\/resources\/([^/{]+)$/.exec(path)?.[1])
515
+ .filter((resource) => Boolean(resource));
516
+ const example = resources[0] ?? '<resource>';
517
+ return `# ${name} API client
518
+
519
+ Generated by \`node ace adula:client\` from the resource registry. Do not edit
520
+ \`index.ts\`; run the command again after resources change. A running system also serves
521
+ the client for the calling token at \`GET /api/v1/client.ts\` (types only:
522
+ \`GET /api/v1/client.d.ts\`), limited to what that token's owner may use.
523
+
524
+ ## Token
525
+
526
+ Create a personal API token under **Account → API tokens** (read tokens may only call GET).
527
+ The client sends it as \`Authorization: Bearer <token>\`; every call is authorized with the
528
+ token owner's current roles, exactly as in the user interface. Keep the token in an
529
+ environment variable, never in source control.
530
+
531
+ ## Usage
532
+
533
+ \`\`\`ts
534
+ import { createAdulaClient, AdulaApiError } from './index.js'
535
+
536
+ const api = createAdulaClient({ baseUrl: 'https://erp.example.com', token: process.env.ADULA_TOKEN! })
537
+ const page = await api.resources.${example}.list({ limit: 50 })
538
+ for (const record of page.data) console.log(record.id)
539
+ // The next page: list({ cursor: page.meta.nextCursor })
540
+ try {
541
+ await api.resources.${example}.show(1)
542
+ } catch (error) {
543
+ if (error instanceof AdulaApiError) console.error(error.status, error.code, error.message)
544
+ }
545
+ \`\`\`
546
+
547
+ Money fields are decimal strings in minor units (\`"1050"\` is 10.50). Methods exist only
548
+ for the operations the API allows on each resource; filters, sort fields and input fields
549
+ are typed from the registry. The module has no dependencies and needs a global \`fetch\`
550
+ (Node.js 18+, browsers) or \`createAdulaClient({ fetch })\`.
551
+ `;
552
+ }
@@ -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
+ };