@aventoapp/framework 0.2.0 → 0.2.2

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 (159) hide show
  1. package/README.md +281 -0
  2. package/dist/index.js.map +1 -1
  3. package/dist/native/index.js.map +1 -1
  4. package/dist/offline/index.js.map +1 -1
  5. package/dist/server/index.js +69 -6
  6. package/dist/server/index.js.map +2 -2
  7. package/dist/server/workflow/index.js.map +1 -1
  8. package/dist/shared/index.js.map +1 -1
  9. package/dist/web/index.js.map +1 -1
  10. package/package.json +84 -79
  11. package/schemas/Workflow.json +14 -14
  12. package/schemas/WorkflowHistory.json +22 -22
  13. package/schemas/WorkflowInstance.json +16 -16
  14. package/schemas/WorkflowState.json +18 -18
  15. package/schemas/WorkflowTransition.json +27 -27
  16. package/src/index.js +8 -8
  17. package/src/native/components/NativeAuthProvider.jsx +249 -249
  18. package/src/native/components/NativeDetail.jsx +270 -270
  19. package/src/native/components/NativeForm.jsx +543 -543
  20. package/src/native/components/NativeGrid.jsx +90 -90
  21. package/src/native/components/NativeJsonGrid.jsx +213 -213
  22. package/src/native/components/NativeJsonView.jsx +454 -454
  23. package/src/native/components/NativeJsonViewContext.js +17 -17
  24. package/src/native/components/NativeShell.jsx +68 -68
  25. package/src/native/components/NativeViewComponent.jsx +351 -351
  26. package/src/native/extensions/NativeExtensionRegistry.js +81 -81
  27. package/src/native/hooks/useNativeStore.js +72 -72
  28. package/src/native/index.js +15 -15
  29. package/src/native/layouts/NativeStackLayout.jsx +30 -30
  30. package/src/native/layouts/NativeTabLayout.jsx +96 -96
  31. package/src/native/storage.js +13 -13
  32. package/src/native/stores/NativeBaseStore.js +348 -348
  33. package/src/native/stores/NativeStoreContext.jsx +53 -53
  34. package/src/offline/index.js +1 -1
  35. package/src/server/ai/capabilities-routes.js +106 -106
  36. package/src/server/ai/index.js +1 -1
  37. package/src/server/cache/MemoryCache.js +153 -153
  38. package/src/server/cache/index.js +2 -2
  39. package/src/server/cache/middleware.js +12 -12
  40. package/src/server/db/index.js +14 -14
  41. package/src/server/db/mongo.js +137 -137
  42. package/src/server/db/postgres.js +144 -144
  43. package/src/server/index.js +42 -42
  44. package/src/server/middleware/auth.js +682 -682
  45. package/src/server/middleware/can-flags.js +132 -132
  46. package/src/server/middleware/entityRoles.js +105 -105
  47. package/src/server/middleware/index.js +58 -58
  48. package/src/server/middleware/permissions.js +240 -240
  49. package/src/server/middleware/tenant.js +203 -203
  50. package/src/server/offline/field-lww.js +98 -6
  51. package/src/server/realtime/EventBus.js +45 -45
  52. package/src/server/realtime/WebSocketServer.js +105 -105
  53. package/src/server/realtime/index.js +3 -3
  54. package/src/server/realtime/middleware.js +18 -18
  55. package/src/server/services/email-templates.js +157 -157
  56. package/src/server/services/email.js +78 -78
  57. package/src/server/services/index.js +15 -15
  58. package/src/server/services/storage.js +119 -119
  59. package/src/server/utils/index.js +16 -16
  60. package/src/server/utils/paginate.js +65 -65
  61. package/src/server/utils/query-builder.js +293 -293
  62. package/src/server/utils/route-loader.js +61 -61
  63. package/src/server/workflow/WorkflowEngine.js +494 -494
  64. package/src/server/workflow/index.js +2 -2
  65. package/src/server/workflow/workflow-routes.js +174 -174
  66. package/src/shared/index.js +10 -10
  67. package/src/shared/utils/field-accessor.js +108 -108
  68. package/src/shared/utils/index.js +7 -7
  69. package/src/shared/utils/validation-utils.js +83 -83
  70. package/src/web/components/AppRouter/AppRouter.jsx +130 -130
  71. package/src/web/components/AppRouter/index.js +1 -1
  72. package/src/web/components/AppShell/AppShell.jsx +101 -101
  73. package/src/web/components/AppShell/DefaultUserMenu.jsx +54 -54
  74. package/src/web/components/AppShell/ShellConfig.js +53 -53
  75. package/src/web/components/AppShell/index.js +3 -3
  76. package/src/web/components/AuthProvider.jsx +426 -426
  77. package/src/web/components/CardList/CardList.jsx +272 -272
  78. package/src/web/components/CardList/index.js +2 -2
  79. package/src/web/components/DetailView/DetailView.jsx +281 -281
  80. package/src/web/components/DetailView/index.js +2 -2
  81. package/src/web/components/Form/Form.jsx +300 -300
  82. package/src/web/components/Form/FormField.jsx +226 -226
  83. package/src/web/components/Form/index.js +3 -3
  84. package/src/web/components/Grid/Grid.jsx +304 -304
  85. package/src/web/components/Grid/index.js +2 -2
  86. package/src/web/components/IconRegistry/IconRegistry.jsx +127 -127
  87. package/src/web/components/IconRegistry/index.js +1 -1
  88. package/src/web/components/JsonView/JsonView.jsx +647 -647
  89. package/src/web/components/JsonView/ViewComponent.jsx +1045 -1045
  90. package/src/web/components/JsonView/ViewToolbar.jsx +141 -141
  91. package/src/web/components/JsonView/index.js +14 -14
  92. package/src/web/components/JsonView/layouts/SingleLayout.jsx +41 -41
  93. package/src/web/components/JsonView/layouts/SplitLayout.jsx +122 -122
  94. package/src/web/components/JsonView/layouts/TabLayout.jsx +112 -112
  95. package/src/web/components/JsonView/layouts/index.js +8 -8
  96. package/src/web/components/Layout.jsx +265 -265
  97. package/src/web/components/MobileLayout/MobileLayout.jsx +385 -385
  98. package/src/web/components/MobileLayout/index.js +1 -1
  99. package/src/web/components/Navigation/Navigation.jsx +248 -248
  100. package/src/web/components/Navigation/index.js +1 -1
  101. package/src/web/components/NotificationProvider.jsx +55 -55
  102. package/src/web/components/Pagination/InfiniteScroll.jsx +82 -82
  103. package/src/web/components/Pagination/Pagination.jsx +73 -73
  104. package/src/web/components/Pagination/index.js +8 -8
  105. package/src/web/components/SimpleList/SimpleList.jsx +177 -177
  106. package/src/web/components/SimpleList/index.js +2 -2
  107. package/src/web/components/TenantProvider.jsx +121 -121
  108. package/src/web/components/WorkflowActions/WorkflowActions.jsx +71 -71
  109. package/src/web/components/WorkflowActions/index.js +1 -1
  110. package/src/web/components/WorkflowField/WorkflowField.jsx +176 -176
  111. package/src/web/components/WorkflowField/index.js +2 -2
  112. package/src/web/components/WorkflowField/workflowColors.js +32 -32
  113. package/src/web/components/auth/DevTenantSelector.jsx +90 -90
  114. package/src/web/components/auth/ForgotPasswordForm.jsx +94 -94
  115. package/src/web/components/auth/RegisterForm.jsx +168 -168
  116. package/src/web/components/auth/ResetPasswordForm.jsx +121 -121
  117. package/src/web/components/auth/VerifyEmailView.jsx +85 -85
  118. package/src/web/components/auth/index.js +5 -5
  119. package/src/web/components/index.js +39 -39
  120. package/src/web/components/layouts/CardListLayout.jsx +68 -68
  121. package/src/web/components/layouts/FullscreenLayout.jsx +30 -30
  122. package/src/web/components/layouts/MobileStackLayout.jsx +28 -28
  123. package/src/web/components/layouts/WizardLayout.jsx +86 -86
  124. package/src/web/components/layouts/index.js +4 -4
  125. package/src/web/components/mobile/Badge.jsx +105 -105
  126. package/src/web/components/mobile/BadgeThemeEditor.jsx +104 -104
  127. package/src/web/components/mobile/EmptyState.jsx +30 -30
  128. package/src/web/components/mobile/QuickActionButton.jsx +77 -77
  129. package/src/web/components/mobile/ServerAutocomplete.jsx +123 -123
  130. package/src/web/components/mobile/StarRating.jsx +42 -42
  131. package/src/web/components/mobile/StatCard.jsx +65 -65
  132. package/src/web/components/mobile/index.js +7 -7
  133. package/src/web/extensions/ExtensionRegistry.js +79 -79
  134. package/src/web/extensions/index.js +7 -7
  135. package/src/web/hooks/index.js +15 -15
  136. package/src/web/hooks/useApi.js +76 -76
  137. package/src/web/hooks/useAuth.js +37 -37
  138. package/src/web/hooks/useDebouncedSave.js +158 -158
  139. package/src/web/hooks/useIsMobile.js +14 -14
  140. package/src/web/hooks/useOfflineQueue.js +99 -99
  141. package/src/web/hooks/useSelectionModel.js +143 -143
  142. package/src/web/hooks/useServerAutocomplete.js +146 -146
  143. package/src/web/hooks/useStore.js +107 -107
  144. package/src/web/hooks/useSubscription.js +130 -130
  145. package/src/web/hooks/useTenant.js +39 -39
  146. package/src/web/hooks/useTenantResolver.js +65 -65
  147. package/src/web/hooks/useUndoRedo.js +77 -77
  148. package/src/web/hooks/useViews.js +113 -113
  149. package/src/web/hooks/useWorkflow.js +190 -190
  150. package/src/web/index.js +117 -117
  151. package/src/web/stores/BaseStore.js +439 -439
  152. package/src/web/stores/StoreContext.jsx +93 -93
  153. package/src/web/stores/index.js +3 -3
  154. package/src/web/theme/index.js +3 -3
  155. package/src/web/theme/mui-theme.js +228 -228
  156. package/src/web/utils/formatTimeAgo.js +22 -22
  157. package/src/web/utils/index.js +1 -1
  158. package/src/web/views/ViewRegistry.js +235 -235
  159. package/src/web/views/index.js +2 -2
@@ -1,439 +1,439 @@
1
- /**
2
- * BaseStore
3
- *
4
- * Base class for entity stores with CRUD operations and reactive state.
5
- * Automatically integrates with auth and tenant contexts.
6
- */
7
-
8
- /**
9
- * Convert camelCase to snake_case
10
- */
11
- function toSnakeCase(str) {
12
- return str.replace(/[A-Z]/g, letter => `_${letter.toLowerCase()}`);
13
- }
14
-
15
- /**
16
- * Convert snake_case to camelCase
17
- */
18
- function toCamelCase(str) {
19
- return str.replace(/_([a-z])/g, (_, letter) => letter.toUpperCase());
20
- }
21
-
22
- /**
23
- * Transform object keys from camelCase to snake_case
24
- */
25
- function toSnakeCaseKeys(obj) {
26
- if (obj === null || typeof obj !== 'object') return obj;
27
- if (Array.isArray(obj)) return obj.map(toSnakeCaseKeys);
28
-
29
- return Object.keys(obj).reduce((acc, key) => {
30
- acc[toSnakeCase(key)] = toSnakeCaseKeys(obj[key]);
31
- return acc;
32
- }, {});
33
- }
34
-
35
- /**
36
- * Transform object keys from snake_case to camelCase
37
- */
38
- function toCamelCaseKeys(obj) {
39
- if (obj === null || typeof obj !== 'object') return obj;
40
- if (Array.isArray(obj)) return obj.map(toCamelCaseKeys);
41
-
42
- return Object.keys(obj).reduce((acc, key) => {
43
- acc[toCamelCase(key)] = toCamelCaseKeys(obj[key]);
44
- return acc;
45
- }, {});
46
- }
47
-
48
- export class BaseStore {
49
- /**
50
- * Create a new store
51
- * @param {string} entityName - Name of the entity (e.g., 'Task')
52
- * @param {string} endpoint - API endpoint (e.g., '/api/tasks')
53
- */
54
- constructor(entityName, endpoint) {
55
- this.entityName = entityName;
56
- this.endpoint = endpoint;
57
-
58
- // Auth and tenant context injectors (set by StoreProvider)
59
- this._getAuthHeader = null;
60
- this._getTenantHeader = null;
61
-
62
- // Reactive state
63
- this._state = {
64
- items: [],
65
- selectedItem: null,
66
- loading: false,
67
- error: null,
68
- pagination: {
69
- page: 1,
70
- pageSize: 25,
71
- total: 0,
72
- totalPages: 0,
73
- hasNext: false,
74
- hasPrev: false
75
- }
76
- };
77
-
78
- // Subscribers for React integration
79
- this._subscribers = new Set();
80
- }
81
-
82
- /**
83
- * Initialize store with auth/tenant context injectors
84
- * Called by StoreProvider
85
- */
86
- _initialize(getAuthHeader, getTenantHeader) {
87
- this._getAuthHeader = getAuthHeader;
88
- this._getTenantHeader = getTenantHeader;
89
- }
90
-
91
- /**
92
- * Get combined headers for API requests
93
- */
94
- _getHeaders() {
95
- const headers = {
96
- 'Content-Type': 'application/json'
97
- };
98
-
99
- if (this._getAuthHeader) {
100
- const authHeader = this._getAuthHeader();
101
- if (authHeader.Authorization) {
102
- headers.Authorization = authHeader.Authorization;
103
- }
104
- }
105
-
106
- if (this._getTenantHeader) {
107
- const tenantHeader = this._getTenantHeader();
108
- if (tenantHeader['X-Tenant-ID']) {
109
- headers['X-Tenant-ID'] = tenantHeader['X-Tenant-ID'];
110
- }
111
- }
112
-
113
- return headers;
114
- }
115
-
116
- /**
117
- * Get current state
118
- */
119
- getState() {
120
- return this._state;
121
- }
122
-
123
- /**
124
- * Update state and notify subscribers
125
- */
126
- _setState(updates) {
127
- this._state = { ...this._state, ...updates };
128
- this._notifySubscribers();
129
- }
130
-
131
- /**
132
- * Subscribe to state changes
133
- * Returns unsubscribe function
134
- */
135
- subscribe(callback) {
136
- this._subscribers.add(callback);
137
- return () => this._subscribers.delete(callback);
138
- }
139
-
140
- /**
141
- * Notify all subscribers of state change
142
- */
143
- _notifySubscribers() {
144
- this._subscribers.forEach(callback => callback(this._state));
145
- }
146
-
147
- /**
148
- * Handle API errors
149
- */
150
- async _handleResponse(response) {
151
- if (!response.ok) {
152
- const error = await response.json().catch(() => ({ message: 'Request failed' }));
153
- throw new Error(error.message || `HTTP ${response.status}`);
154
- }
155
- return response.json();
156
- }
157
-
158
- /**
159
- * List all items
160
- * @param {Object} options - Query options (page, pageSize, sort, filter, append, sliceId)
161
- * @param {boolean} options.append - If true, append items to existing list (for infinite scroll)
162
- * @param {string} options.sliceId - Slice ID for pre-generated JOIN queries
163
- */
164
- async list(options = {}) {
165
- this._setState({ loading: true, error: null });
166
-
167
- try {
168
- const queryParams = new URLSearchParams();
169
- if (options.page) queryParams.set('page', options.page);
170
- if (options.pageSize) queryParams.set('pageSize', options.pageSize);
171
- if (options.sort) queryParams.set('sort', options.sort);
172
- if (options.sortDirection) queryParams.set('sortDirection', options.sortDirection);
173
- if (options.sliceId) queryParams.set('slice', options.sliceId);
174
- if (options.filters) {
175
- for (const [key, value] of Object.entries(options.filters)) {
176
- queryParams.set(key, value);
177
- }
178
- }
179
-
180
- const url = queryParams.toString()
181
- ? `${this.endpoint}?${queryParams}`
182
- : this.endpoint;
183
-
184
- const response = await fetch(url, {
185
- method: 'GET',
186
- headers: this._getHeaders()
187
- });
188
-
189
- const data = await this._handleResponse(response);
190
-
191
- // Handle both array responses (legacy) and paginated responses
192
- let items, paginationInfo;
193
- if (Array.isArray(data)) {
194
- // Legacy array response - backward compatible
195
- items = data;
196
- paginationInfo = {
197
- page: options.page || 1,
198
- pageSize: options.pageSize || this._state.pagination.pageSize,
199
- total: items.length,
200
- totalPages: 1,
201
- hasNext: false,
202
- hasPrev: false
203
- };
204
- } else {
205
- // New paginated response format { data: [], pagination: {} }
206
- items = data.data || data.items || [];
207
- paginationInfo = data.pagination || {
208
- page: options.page || 1,
209
- pageSize: options.pageSize || this._state.pagination.pageSize,
210
- total: data.total || items.length,
211
- totalPages: Math.ceil((data.total || items.length) / (options.pageSize || this._state.pagination.pageSize)),
212
- hasNext: false,
213
- hasPrev: false
214
- };
215
- }
216
-
217
- const transformedItems = items.map(toCamelCaseKeys);
218
-
219
- // Append mode for infinite scroll
220
- const finalItems = options.append
221
- ? [...this._state.items, ...transformedItems]
222
- : transformedItems;
223
-
224
- this._setState({
225
- items: finalItems,
226
- loading: false,
227
- pagination: paginationInfo
228
- });
229
-
230
- return this._state.items;
231
- } catch (error) {
232
- this._setState({ loading: false, error: error.message });
233
- throw error;
234
- }
235
- }
236
-
237
- /**
238
- * Load more items for infinite scroll
239
- * Fetches the next page and appends to existing items
240
- */
241
- async loadMore() {
242
- const { pagination } = this._state;
243
-
244
- // Don't load if already loading or no more pages
245
- if (this._state.loading || !pagination.hasNext) {
246
- return this._state.items;
247
- }
248
-
249
- return this.list({
250
- page: pagination.page + 1,
251
- pageSize: pagination.pageSize,
252
- append: true
253
- });
254
- }
255
-
256
- /**
257
- * Get single item by ID
258
- * @param {string} id - Item ID
259
- * @param {Object} options - Query options
260
- * @param {string} options.sliceId - Slice ID for pre-generated JOIN queries
261
- */
262
- async get(id, options = {}) {
263
- this._setState({ loading: true, error: null });
264
-
265
- try {
266
- const queryParams = new URLSearchParams();
267
- if (options.sliceId) queryParams.set('slice', options.sliceId);
268
-
269
- const url = queryParams.toString()
270
- ? `${this.endpoint}/${id}?${queryParams}`
271
- : `${this.endpoint}/${id}`;
272
-
273
- const response = await fetch(url, {
274
- method: 'GET',
275
- headers: this._getHeaders()
276
- });
277
-
278
- const data = await this._handleResponse(response);
279
- const item = toCamelCaseKeys(data);
280
-
281
- this._setState({
282
- selectedItem: item,
283
- loading: false
284
- });
285
-
286
- return item;
287
- } catch (error) {
288
- this._setState({ loading: false, error: error.message });
289
- throw error;
290
- }
291
- }
292
-
293
- /**
294
- * Create new item
295
- * @param {Object} data - Item data
296
- */
297
- async create(data) {
298
- this._setState({ loading: true, error: null });
299
-
300
- try {
301
- const response = await fetch(this.endpoint, {
302
- method: 'POST',
303
- headers: this._getHeaders(),
304
- body: JSON.stringify(toSnakeCaseKeys(data))
305
- });
306
-
307
- const result = await this._handleResponse(response);
308
- const item = toCamelCaseKeys(result);
309
-
310
- this._setState({
311
- items: [item, ...this._state.items],
312
- loading: false
313
- });
314
-
315
- return item;
316
- } catch (error) {
317
- this._setState({ loading: false, error: error.message });
318
- throw error;
319
- }
320
- }
321
-
322
- /**
323
- * Update existing item
324
- * @param {string} id - Item ID
325
- * @param {Object} data - Updated data
326
- */
327
- async update(id, data) {
328
- this._setState({ loading: true, error: null });
329
-
330
- try {
331
- const response = await fetch(`${this.endpoint}/${id}`, {
332
- method: 'PUT',
333
- headers: this._getHeaders(),
334
- body: JSON.stringify(toSnakeCaseKeys(data))
335
- });
336
-
337
- const result = await this._handleResponse(response);
338
- const item = toCamelCaseKeys(result);
339
-
340
- this._setState({
341
- items: this._state.items.map(i => i.id === id ? item : i),
342
- selectedItem: this._state.selectedItem?.id === id ? item : this._state.selectedItem,
343
- loading: false
344
- });
345
-
346
- return item;
347
- } catch (error) {
348
- this._setState({ loading: false, error: error.message });
349
- throw error;
350
- }
351
- }
352
-
353
- /**
354
- * Delete item
355
- * @param {string} id - Item ID
356
- */
357
- async delete(id) {
358
- this._setState({ loading: true, error: null });
359
-
360
- try {
361
- const response = await fetch(`${this.endpoint}/${id}`, {
362
- method: 'DELETE',
363
- headers: this._getHeaders()
364
- });
365
-
366
- if (!response.ok && response.status !== 204) {
367
- await this._handleResponse(response);
368
- }
369
-
370
- this._setState({
371
- items: this._state.items.filter(i => i.id !== id),
372
- selectedItem: this._state.selectedItem?.id === id ? null : this._state.selectedItem,
373
- loading: false
374
- });
375
-
376
- return true;
377
- } catch (error) {
378
- this._setState({ loading: false, error: error.message });
379
- throw error;
380
- }
381
- }
382
-
383
- /**
384
- * Select an item
385
- * @param {Object|null} item - Item to select or null to clear
386
- */
387
- select(item) {
388
- this._setState({ selectedItem: item });
389
- }
390
-
391
- /**
392
- * Clear selection
393
- */
394
- clearSelection() {
395
- this._setState({ selectedItem: null });
396
- }
397
-
398
- /**
399
- * Clear error state
400
- */
401
- clearError() {
402
- this._setState({ error: null });
403
- }
404
-
405
- /**
406
- * Reset store to initial state
407
- */
408
- reset() {
409
- this._setState({
410
- items: [],
411
- selectedItem: null,
412
- loading: false,
413
- error: null,
414
- pagination: {
415
- page: 1,
416
- pageSize: 25,
417
- total: 0,
418
- totalPages: 0,
419
- hasNext: false,
420
- hasPrev: false
421
- }
422
- });
423
- }
424
-
425
- /**
426
- * Set page size
427
- * @param {number} pageSize - New page size
428
- */
429
- setPageSize(pageSize) {
430
- this._setState({
431
- pagination: {
432
- ...this._state.pagination,
433
- pageSize
434
- }
435
- });
436
- }
437
- }
438
-
439
- export default BaseStore;
1
+ /**
2
+ * BaseStore
3
+ *
4
+ * Base class for entity stores with CRUD operations and reactive state.
5
+ * Automatically integrates with auth and tenant contexts.
6
+ */
7
+
8
+ /**
9
+ * Convert camelCase to snake_case
10
+ */
11
+ function toSnakeCase(str) {
12
+ return str.replace(/[A-Z]/g, letter => `_${letter.toLowerCase()}`);
13
+ }
14
+
15
+ /**
16
+ * Convert snake_case to camelCase
17
+ */
18
+ function toCamelCase(str) {
19
+ return str.replace(/_([a-z])/g, (_, letter) => letter.toUpperCase());
20
+ }
21
+
22
+ /**
23
+ * Transform object keys from camelCase to snake_case
24
+ */
25
+ function toSnakeCaseKeys(obj) {
26
+ if (obj === null || typeof obj !== 'object') return obj;
27
+ if (Array.isArray(obj)) return obj.map(toSnakeCaseKeys);
28
+
29
+ return Object.keys(obj).reduce((acc, key) => {
30
+ acc[toSnakeCase(key)] = toSnakeCaseKeys(obj[key]);
31
+ return acc;
32
+ }, {});
33
+ }
34
+
35
+ /**
36
+ * Transform object keys from snake_case to camelCase
37
+ */
38
+ function toCamelCaseKeys(obj) {
39
+ if (obj === null || typeof obj !== 'object') return obj;
40
+ if (Array.isArray(obj)) return obj.map(toCamelCaseKeys);
41
+
42
+ return Object.keys(obj).reduce((acc, key) => {
43
+ acc[toCamelCase(key)] = toCamelCaseKeys(obj[key]);
44
+ return acc;
45
+ }, {});
46
+ }
47
+
48
+ export class BaseStore {
49
+ /**
50
+ * Create a new store
51
+ * @param {string} entityName - Name of the entity (e.g., 'Task')
52
+ * @param {string} endpoint - API endpoint (e.g., '/api/tasks')
53
+ */
54
+ constructor(entityName, endpoint) {
55
+ this.entityName = entityName;
56
+ this.endpoint = endpoint;
57
+
58
+ // Auth and tenant context injectors (set by StoreProvider)
59
+ this._getAuthHeader = null;
60
+ this._getTenantHeader = null;
61
+
62
+ // Reactive state
63
+ this._state = {
64
+ items: [],
65
+ selectedItem: null,
66
+ loading: false,
67
+ error: null,
68
+ pagination: {
69
+ page: 1,
70
+ pageSize: 25,
71
+ total: 0,
72
+ totalPages: 0,
73
+ hasNext: false,
74
+ hasPrev: false
75
+ }
76
+ };
77
+
78
+ // Subscribers for React integration
79
+ this._subscribers = new Set();
80
+ }
81
+
82
+ /**
83
+ * Initialize store with auth/tenant context injectors
84
+ * Called by StoreProvider
85
+ */
86
+ _initialize(getAuthHeader, getTenantHeader) {
87
+ this._getAuthHeader = getAuthHeader;
88
+ this._getTenantHeader = getTenantHeader;
89
+ }
90
+
91
+ /**
92
+ * Get combined headers for API requests
93
+ */
94
+ _getHeaders() {
95
+ const headers = {
96
+ 'Content-Type': 'application/json'
97
+ };
98
+
99
+ if (this._getAuthHeader) {
100
+ const authHeader = this._getAuthHeader();
101
+ if (authHeader.Authorization) {
102
+ headers.Authorization = authHeader.Authorization;
103
+ }
104
+ }
105
+
106
+ if (this._getTenantHeader) {
107
+ const tenantHeader = this._getTenantHeader();
108
+ if (tenantHeader['X-Tenant-ID']) {
109
+ headers['X-Tenant-ID'] = tenantHeader['X-Tenant-ID'];
110
+ }
111
+ }
112
+
113
+ return headers;
114
+ }
115
+
116
+ /**
117
+ * Get current state
118
+ */
119
+ getState() {
120
+ return this._state;
121
+ }
122
+
123
+ /**
124
+ * Update state and notify subscribers
125
+ */
126
+ _setState(updates) {
127
+ this._state = { ...this._state, ...updates };
128
+ this._notifySubscribers();
129
+ }
130
+
131
+ /**
132
+ * Subscribe to state changes
133
+ * Returns unsubscribe function
134
+ */
135
+ subscribe(callback) {
136
+ this._subscribers.add(callback);
137
+ return () => this._subscribers.delete(callback);
138
+ }
139
+
140
+ /**
141
+ * Notify all subscribers of state change
142
+ */
143
+ _notifySubscribers() {
144
+ this._subscribers.forEach(callback => callback(this._state));
145
+ }
146
+
147
+ /**
148
+ * Handle API errors
149
+ */
150
+ async _handleResponse(response) {
151
+ if (!response.ok) {
152
+ const error = await response.json().catch(() => ({ message: 'Request failed' }));
153
+ throw new Error(error.message || `HTTP ${response.status}`);
154
+ }
155
+ return response.json();
156
+ }
157
+
158
+ /**
159
+ * List all items
160
+ * @param {Object} options - Query options (page, pageSize, sort, filter, append, sliceId)
161
+ * @param {boolean} options.append - If true, append items to existing list (for infinite scroll)
162
+ * @param {string} options.sliceId - Slice ID for pre-generated JOIN queries
163
+ */
164
+ async list(options = {}) {
165
+ this._setState({ loading: true, error: null });
166
+
167
+ try {
168
+ const queryParams = new URLSearchParams();
169
+ if (options.page) queryParams.set('page', options.page);
170
+ if (options.pageSize) queryParams.set('pageSize', options.pageSize);
171
+ if (options.sort) queryParams.set('sort', options.sort);
172
+ if (options.sortDirection) queryParams.set('sortDirection', options.sortDirection);
173
+ if (options.sliceId) queryParams.set('slice', options.sliceId);
174
+ if (options.filters) {
175
+ for (const [key, value] of Object.entries(options.filters)) {
176
+ queryParams.set(key, value);
177
+ }
178
+ }
179
+
180
+ const url = queryParams.toString()
181
+ ? `${this.endpoint}?${queryParams}`
182
+ : this.endpoint;
183
+
184
+ const response = await fetch(url, {
185
+ method: 'GET',
186
+ headers: this._getHeaders()
187
+ });
188
+
189
+ const data = await this._handleResponse(response);
190
+
191
+ // Handle both array responses (legacy) and paginated responses
192
+ let items, paginationInfo;
193
+ if (Array.isArray(data)) {
194
+ // Legacy array response - backward compatible
195
+ items = data;
196
+ paginationInfo = {
197
+ page: options.page || 1,
198
+ pageSize: options.pageSize || this._state.pagination.pageSize,
199
+ total: items.length,
200
+ totalPages: 1,
201
+ hasNext: false,
202
+ hasPrev: false
203
+ };
204
+ } else {
205
+ // New paginated response format { data: [], pagination: {} }
206
+ items = data.data || data.items || [];
207
+ paginationInfo = data.pagination || {
208
+ page: options.page || 1,
209
+ pageSize: options.pageSize || this._state.pagination.pageSize,
210
+ total: data.total || items.length,
211
+ totalPages: Math.ceil((data.total || items.length) / (options.pageSize || this._state.pagination.pageSize)),
212
+ hasNext: false,
213
+ hasPrev: false
214
+ };
215
+ }
216
+
217
+ const transformedItems = items.map(toCamelCaseKeys);
218
+
219
+ // Append mode for infinite scroll
220
+ const finalItems = options.append
221
+ ? [...this._state.items, ...transformedItems]
222
+ : transformedItems;
223
+
224
+ this._setState({
225
+ items: finalItems,
226
+ loading: false,
227
+ pagination: paginationInfo
228
+ });
229
+
230
+ return this._state.items;
231
+ } catch (error) {
232
+ this._setState({ loading: false, error: error.message });
233
+ throw error;
234
+ }
235
+ }
236
+
237
+ /**
238
+ * Load more items for infinite scroll
239
+ * Fetches the next page and appends to existing items
240
+ */
241
+ async loadMore() {
242
+ const { pagination } = this._state;
243
+
244
+ // Don't load if already loading or no more pages
245
+ if (this._state.loading || !pagination.hasNext) {
246
+ return this._state.items;
247
+ }
248
+
249
+ return this.list({
250
+ page: pagination.page + 1,
251
+ pageSize: pagination.pageSize,
252
+ append: true
253
+ });
254
+ }
255
+
256
+ /**
257
+ * Get single item by ID
258
+ * @param {string} id - Item ID
259
+ * @param {Object} options - Query options
260
+ * @param {string} options.sliceId - Slice ID for pre-generated JOIN queries
261
+ */
262
+ async get(id, options = {}) {
263
+ this._setState({ loading: true, error: null });
264
+
265
+ try {
266
+ const queryParams = new URLSearchParams();
267
+ if (options.sliceId) queryParams.set('slice', options.sliceId);
268
+
269
+ const url = queryParams.toString()
270
+ ? `${this.endpoint}/${id}?${queryParams}`
271
+ : `${this.endpoint}/${id}`;
272
+
273
+ const response = await fetch(url, {
274
+ method: 'GET',
275
+ headers: this._getHeaders()
276
+ });
277
+
278
+ const data = await this._handleResponse(response);
279
+ const item = toCamelCaseKeys(data);
280
+
281
+ this._setState({
282
+ selectedItem: item,
283
+ loading: false
284
+ });
285
+
286
+ return item;
287
+ } catch (error) {
288
+ this._setState({ loading: false, error: error.message });
289
+ throw error;
290
+ }
291
+ }
292
+
293
+ /**
294
+ * Create new item
295
+ * @param {Object} data - Item data
296
+ */
297
+ async create(data) {
298
+ this._setState({ loading: true, error: null });
299
+
300
+ try {
301
+ const response = await fetch(this.endpoint, {
302
+ method: 'POST',
303
+ headers: this._getHeaders(),
304
+ body: JSON.stringify(toSnakeCaseKeys(data))
305
+ });
306
+
307
+ const result = await this._handleResponse(response);
308
+ const item = toCamelCaseKeys(result);
309
+
310
+ this._setState({
311
+ items: [item, ...this._state.items],
312
+ loading: false
313
+ });
314
+
315
+ return item;
316
+ } catch (error) {
317
+ this._setState({ loading: false, error: error.message });
318
+ throw error;
319
+ }
320
+ }
321
+
322
+ /**
323
+ * Update existing item
324
+ * @param {string} id - Item ID
325
+ * @param {Object} data - Updated data
326
+ */
327
+ async update(id, data) {
328
+ this._setState({ loading: true, error: null });
329
+
330
+ try {
331
+ const response = await fetch(`${this.endpoint}/${id}`, {
332
+ method: 'PUT',
333
+ headers: this._getHeaders(),
334
+ body: JSON.stringify(toSnakeCaseKeys(data))
335
+ });
336
+
337
+ const result = await this._handleResponse(response);
338
+ const item = toCamelCaseKeys(result);
339
+
340
+ this._setState({
341
+ items: this._state.items.map(i => i.id === id ? item : i),
342
+ selectedItem: this._state.selectedItem?.id === id ? item : this._state.selectedItem,
343
+ loading: false
344
+ });
345
+
346
+ return item;
347
+ } catch (error) {
348
+ this._setState({ loading: false, error: error.message });
349
+ throw error;
350
+ }
351
+ }
352
+
353
+ /**
354
+ * Delete item
355
+ * @param {string} id - Item ID
356
+ */
357
+ async delete(id) {
358
+ this._setState({ loading: true, error: null });
359
+
360
+ try {
361
+ const response = await fetch(`${this.endpoint}/${id}`, {
362
+ method: 'DELETE',
363
+ headers: this._getHeaders()
364
+ });
365
+
366
+ if (!response.ok && response.status !== 204) {
367
+ await this._handleResponse(response);
368
+ }
369
+
370
+ this._setState({
371
+ items: this._state.items.filter(i => i.id !== id),
372
+ selectedItem: this._state.selectedItem?.id === id ? null : this._state.selectedItem,
373
+ loading: false
374
+ });
375
+
376
+ return true;
377
+ } catch (error) {
378
+ this._setState({ loading: false, error: error.message });
379
+ throw error;
380
+ }
381
+ }
382
+
383
+ /**
384
+ * Select an item
385
+ * @param {Object|null} item - Item to select or null to clear
386
+ */
387
+ select(item) {
388
+ this._setState({ selectedItem: item });
389
+ }
390
+
391
+ /**
392
+ * Clear selection
393
+ */
394
+ clearSelection() {
395
+ this._setState({ selectedItem: null });
396
+ }
397
+
398
+ /**
399
+ * Clear error state
400
+ */
401
+ clearError() {
402
+ this._setState({ error: null });
403
+ }
404
+
405
+ /**
406
+ * Reset store to initial state
407
+ */
408
+ reset() {
409
+ this._setState({
410
+ items: [],
411
+ selectedItem: null,
412
+ loading: false,
413
+ error: null,
414
+ pagination: {
415
+ page: 1,
416
+ pageSize: 25,
417
+ total: 0,
418
+ totalPages: 0,
419
+ hasNext: false,
420
+ hasPrev: false
421
+ }
422
+ });
423
+ }
424
+
425
+ /**
426
+ * Set page size
427
+ * @param {number} pageSize - New page size
428
+ */
429
+ setPageSize(pageSize) {
430
+ this._setState({
431
+ pagination: {
432
+ ...this._state.pagination,
433
+ pageSize
434
+ }
435
+ });
436
+ }
437
+ }
438
+
439
+ export default BaseStore;