@aventoapp/framework 0.1.0 → 0.2.1

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 (169) hide show
  1. package/README.md +260 -0
  2. package/dist/index.js.map +1 -1
  3. package/dist/native/index.js.map +1 -1
  4. package/dist/offline/index.js +399 -0
  5. package/dist/offline/index.js.map +7 -0
  6. package/dist/server/index.js +75 -0
  7. package/dist/server/index.js.map +3 -3
  8. package/dist/server/workflow/index.js.map +1 -1
  9. package/dist/shared/index.js.map +1 -1
  10. package/dist/web/index.js.map +1 -1
  11. package/package.json +10 -7
  12. package/schemas/Workflow.json +14 -14
  13. package/schemas/WorkflowHistory.json +22 -22
  14. package/schemas/WorkflowInstance.json +16 -16
  15. package/schemas/WorkflowState.json +18 -18
  16. package/schemas/WorkflowTransition.json +27 -27
  17. package/src/index.js +8 -8
  18. package/src/native/components/NativeAuthProvider.jsx +249 -249
  19. package/src/native/components/NativeDetail.jsx +270 -270
  20. package/src/native/components/NativeForm.jsx +543 -543
  21. package/src/native/components/NativeGrid.jsx +90 -90
  22. package/src/native/components/NativeJsonGrid.jsx +213 -213
  23. package/src/native/components/NativeJsonView.jsx +454 -454
  24. package/src/native/components/NativeJsonViewContext.js +17 -17
  25. package/src/native/components/NativeShell.jsx +68 -68
  26. package/src/native/components/NativeViewComponent.jsx +351 -351
  27. package/src/native/extensions/NativeExtensionRegistry.js +81 -81
  28. package/src/native/hooks/useNativeStore.js +72 -72
  29. package/src/native/index.js +15 -15
  30. package/src/native/layouts/NativeStackLayout.jsx +30 -30
  31. package/src/native/layouts/NativeTabLayout.jsx +96 -96
  32. package/src/native/storage.js +13 -13
  33. package/src/native/stores/NativeBaseStore.js +348 -348
  34. package/src/native/stores/NativeStoreContext.jsx +53 -53
  35. package/src/offline/clock.js +12 -0
  36. package/src/offline/coalesce.js +45 -0
  37. package/src/offline/diff.js +17 -0
  38. package/src/offline/idb.js +52 -0
  39. package/src/offline/index.js +13 -0
  40. package/src/offline/kit.js +121 -0
  41. package/src/offline/outbox.js +83 -0
  42. package/src/offline/store.js +26 -0
  43. package/src/offline/syncer.js +55 -0
  44. package/src/server/ai/capabilities-routes.js +106 -106
  45. package/src/server/ai/index.js +1 -1
  46. package/src/server/cache/MemoryCache.js +153 -153
  47. package/src/server/cache/index.js +2 -2
  48. package/src/server/cache/middleware.js +12 -12
  49. package/src/server/db/index.js +14 -14
  50. package/src/server/db/mongo.js +137 -137
  51. package/src/server/db/postgres.js +144 -144
  52. package/src/server/index.js +42 -38
  53. package/src/server/middleware/auth.js +682 -682
  54. package/src/server/middleware/can-flags.js +132 -132
  55. package/src/server/middleware/entityRoles.js +105 -105
  56. package/src/server/middleware/index.js +58 -58
  57. package/src/server/middleware/permissions.js +240 -240
  58. package/src/server/middleware/tenant.js +203 -203
  59. package/src/server/offline/field-lww.js +66 -0
  60. package/src/server/offline/index.js +1 -0
  61. package/src/server/realtime/EventBus.js +45 -45
  62. package/src/server/realtime/WebSocketServer.js +105 -105
  63. package/src/server/realtime/index.js +3 -3
  64. package/src/server/realtime/middleware.js +18 -18
  65. package/src/server/services/email-templates.js +157 -157
  66. package/src/server/services/email.js +78 -78
  67. package/src/server/services/index.js +15 -15
  68. package/src/server/services/storage.js +119 -119
  69. package/src/server/utils/index.js +16 -16
  70. package/src/server/utils/paginate.js +65 -65
  71. package/src/server/utils/query-builder.js +293 -293
  72. package/src/server/utils/route-loader.js +61 -61
  73. package/src/server/workflow/WorkflowEngine.js +494 -494
  74. package/src/server/workflow/index.js +2 -2
  75. package/src/server/workflow/workflow-routes.js +174 -174
  76. package/src/shared/index.js +10 -10
  77. package/src/shared/utils/field-accessor.js +108 -108
  78. package/src/shared/utils/index.js +7 -7
  79. package/src/shared/utils/validation-utils.js +83 -83
  80. package/src/web/components/AppRouter/AppRouter.jsx +130 -130
  81. package/src/web/components/AppRouter/index.js +1 -1
  82. package/src/web/components/AppShell/AppShell.jsx +101 -101
  83. package/src/web/components/AppShell/DefaultUserMenu.jsx +54 -54
  84. package/src/web/components/AppShell/ShellConfig.js +53 -53
  85. package/src/web/components/AppShell/index.js +3 -3
  86. package/src/web/components/AuthProvider.jsx +426 -426
  87. package/src/web/components/CardList/CardList.jsx +272 -272
  88. package/src/web/components/CardList/index.js +2 -2
  89. package/src/web/components/DetailView/DetailView.jsx +281 -281
  90. package/src/web/components/DetailView/index.js +2 -2
  91. package/src/web/components/Form/Form.jsx +300 -300
  92. package/src/web/components/Form/FormField.jsx +226 -226
  93. package/src/web/components/Form/index.js +3 -3
  94. package/src/web/components/Grid/Grid.jsx +304 -304
  95. package/src/web/components/Grid/index.js +2 -2
  96. package/src/web/components/IconRegistry/IconRegistry.jsx +127 -127
  97. package/src/web/components/IconRegistry/index.js +1 -1
  98. package/src/web/components/JsonView/JsonView.jsx +647 -647
  99. package/src/web/components/JsonView/ViewComponent.jsx +1045 -1045
  100. package/src/web/components/JsonView/ViewToolbar.jsx +141 -141
  101. package/src/web/components/JsonView/index.js +14 -14
  102. package/src/web/components/JsonView/layouts/SingleLayout.jsx +41 -41
  103. package/src/web/components/JsonView/layouts/SplitLayout.jsx +122 -122
  104. package/src/web/components/JsonView/layouts/TabLayout.jsx +112 -112
  105. package/src/web/components/JsonView/layouts/index.js +8 -8
  106. package/src/web/components/Layout.jsx +265 -265
  107. package/src/web/components/MobileLayout/MobileLayout.jsx +385 -385
  108. package/src/web/components/MobileLayout/index.js +1 -1
  109. package/src/web/components/Navigation/Navigation.jsx +248 -248
  110. package/src/web/components/Navigation/index.js +1 -1
  111. package/src/web/components/NotificationProvider.jsx +55 -55
  112. package/src/web/components/Pagination/InfiniteScroll.jsx +82 -82
  113. package/src/web/components/Pagination/Pagination.jsx +73 -73
  114. package/src/web/components/Pagination/index.js +8 -8
  115. package/src/web/components/SimpleList/SimpleList.jsx +177 -177
  116. package/src/web/components/SimpleList/index.js +2 -2
  117. package/src/web/components/TenantProvider.jsx +121 -121
  118. package/src/web/components/WorkflowActions/WorkflowActions.jsx +71 -71
  119. package/src/web/components/WorkflowActions/index.js +1 -1
  120. package/src/web/components/WorkflowField/WorkflowField.jsx +176 -176
  121. package/src/web/components/WorkflowField/index.js +2 -2
  122. package/src/web/components/WorkflowField/workflowColors.js +32 -32
  123. package/src/web/components/auth/DevTenantSelector.jsx +90 -90
  124. package/src/web/components/auth/ForgotPasswordForm.jsx +94 -94
  125. package/src/web/components/auth/RegisterForm.jsx +168 -168
  126. package/src/web/components/auth/ResetPasswordForm.jsx +121 -121
  127. package/src/web/components/auth/VerifyEmailView.jsx +85 -85
  128. package/src/web/components/auth/index.js +5 -5
  129. package/src/web/components/index.js +39 -39
  130. package/src/web/components/layouts/CardListLayout.jsx +68 -68
  131. package/src/web/components/layouts/FullscreenLayout.jsx +30 -30
  132. package/src/web/components/layouts/MobileStackLayout.jsx +28 -28
  133. package/src/web/components/layouts/WizardLayout.jsx +86 -86
  134. package/src/web/components/layouts/index.js +4 -4
  135. package/src/web/components/mobile/Badge.jsx +105 -105
  136. package/src/web/components/mobile/BadgeThemeEditor.jsx +104 -104
  137. package/src/web/components/mobile/EmptyState.jsx +30 -30
  138. package/src/web/components/mobile/QuickActionButton.jsx +77 -77
  139. package/src/web/components/mobile/ServerAutocomplete.jsx +123 -123
  140. package/src/web/components/mobile/StarRating.jsx +42 -42
  141. package/src/web/components/mobile/StatCard.jsx +65 -65
  142. package/src/web/components/mobile/index.js +7 -7
  143. package/src/web/extensions/ExtensionRegistry.js +79 -79
  144. package/src/web/extensions/index.js +7 -7
  145. package/src/web/hooks/index.js +15 -15
  146. package/src/web/hooks/useApi.js +76 -76
  147. package/src/web/hooks/useAuth.js +37 -37
  148. package/src/web/hooks/useDebouncedSave.js +158 -158
  149. package/src/web/hooks/useIsMobile.js +14 -14
  150. package/src/web/hooks/useOfflineQueue.js +99 -99
  151. package/src/web/hooks/useSelectionModel.js +143 -143
  152. package/src/web/hooks/useServerAutocomplete.js +146 -146
  153. package/src/web/hooks/useStore.js +107 -107
  154. package/src/web/hooks/useSubscription.js +130 -130
  155. package/src/web/hooks/useTenant.js +39 -39
  156. package/src/web/hooks/useTenantResolver.js +65 -65
  157. package/src/web/hooks/useUndoRedo.js +77 -77
  158. package/src/web/hooks/useViews.js +113 -113
  159. package/src/web/hooks/useWorkflow.js +190 -190
  160. package/src/web/index.js +117 -117
  161. package/src/web/stores/BaseStore.js +439 -439
  162. package/src/web/stores/StoreContext.jsx +93 -93
  163. package/src/web/stores/index.js +3 -3
  164. package/src/web/theme/index.js +3 -3
  165. package/src/web/theme/mui-theme.js +228 -228
  166. package/src/web/utils/formatTimeAgo.js +22 -22
  167. package/src/web/utils/index.js +1 -1
  168. package/src/web/views/ViewRegistry.js +235 -235
  169. package/src/web/views/index.js +2 -2
package/README.md ADDED
@@ -0,0 +1,260 @@
1
+ # @aventoapp/framework
2
+
3
+ Server and web modules for multi-tenant SaaS apps built on Avento.
4
+
5
+ ```bash
6
+ npm i @aventoapp/framework
7
+ ```
8
+
9
+ | Subpath | What it holds |
10
+ |---|---|
11
+ | `@aventoapp/framework/server` | Express middleware, database clients, workflow engine, services, and the server half of the offline kit (`applyFieldLWW`) |
12
+ | `@aventoapp/framework/web` | React web modules |
13
+ | `@aventoapp/framework/shared` | Code shared by server and web |
14
+ | `@aventoapp/framework/offline` | The offline sync kit: read cache, write outbox, sync engine. No React, no DOM required |
15
+ | `@aventoapp/framework/native` | React Native modules |
16
+
17
+ ## Offline sync kit
18
+
19
+ The kit lets a web or mobile client keep working with no signal. Reads come
20
+ from the network when online and from the last saved copy when not. Edits are
21
+ applied to the cached copy at once, queued, and sent when the device is back
22
+ online. The server settles conflicts per field: the newest edit of each field
23
+ wins, by client timestamp, so two people editing different fields of one record
24
+ never overwrite each other.
25
+
26
+ There are two halves:
27
+
28
+ - **Client** (`/offline`): `createOfflineKit` plus its parts (`createIdb`,
29
+ `createClock`).
30
+ - **Server** (`/server`): `applyFieldLWW`, which writes only the fields whose
31
+ incoming timestamp is at least as new as the stored one.
32
+
33
+ ### 1. Create the kit
34
+
35
+ ```js
36
+ import { createOfflineKit, createIdb, createClock } from '@aventoapp/framework/offline';
37
+
38
+ const idb = createIdb({ name: 'my-app-offline', indexedDB: window.indexedDB });
39
+ const clock = createClock();
40
+
41
+ const kit = createOfflineKit({
42
+ idb,
43
+ clock,
44
+ isOnline: navigator.onLine,
45
+ request, // your transport, below
46
+ });
47
+ ```
48
+
49
+ `createIdb({ name, indexedDB })` opens one IndexedDB database with three
50
+ object stores, `cache`, `outbox` and `meta`. `indexedDB` is injected, so tests
51
+ pass `fake-indexeddb` and the browser passes `window.indexedDB`. Nothing in the
52
+ kit reads a browser global on its own.
53
+
54
+ `createClock({ nowFn })` timestamps every edit. If you can read the server's
55
+ time (a `Date` response header, say), call
56
+ `clock.setOffsetFromServer(serverEpochMs)` so a device with a wrong clock does
57
+ not win or lose every conflict. `clock.getOffsetMs()` returns the current
58
+ offset.
59
+
60
+ #### The `request` transport
61
+
62
+ The kit never calls `fetch` itself. Every network call goes through the
63
+ `request` function you pass, which must resolve (never throw) to
64
+ `{ ok, body }`:
65
+
66
+ ```js
67
+ async function request({ url, method, body, headers, isBlob, idemKey, meta }) {
68
+ const res = await fetch(url, {
69
+ method,
70
+ headers: isBlob ? headers : { 'Content-Type': 'application/json', ...headers },
71
+ body: method === 'GET' ? undefined : (isBlob ? body : JSON.stringify(body)),
72
+ }).catch(() => null);
73
+ if (!res) return { ok: false }; // no network: retry later
74
+ if (res.ok) return { ok: true, body: await res.json().catch(() => null) };
75
+ if (res.status >= 500 || res.status === 408 || res.status === 429) return { ok: false };
76
+ // A permanent refusal (400, 403, 404, 409...). See "A refused write" below.
77
+ await keepForAPerson({ url, method, body, meta, status: res.status });
78
+ return { ok: true };
79
+ }
80
+ ```
81
+
82
+ **`ok: false` means "try again later".** The outbox is first in, first out:
83
+ a patch that fails stops the patch queue there, and a blob that fails stops the
84
+ blob queue there, until the next flush. Return `ok: false` only for a failure
85
+ that can succeed on retry.
86
+
87
+ ### 2. Declare a synced resource
88
+
89
+ ```js
90
+ kit.defineSyncedResource({
91
+ name: 'trip',
92
+ load: (id) => `/api/trips/${id}`, // a URL string
93
+ patch: (id) => ({ url: `/api/trips/${id}`, method: 'PATCH' }),
94
+ });
95
+ ```
96
+
97
+ ### 3. Read, edit, and queue files
98
+
99
+ ```js
100
+ const { data, fromCache, fetchedAt } = await kit.readSynced('trip', tripId);
101
+ ```
102
+
103
+ `readSynced(name, id)` fetches when online and saves the result. When offline,
104
+ or when the fetch fails, it returns the last saved copy with `fromCache: true`
105
+ (and `data: null` if there is none). `primeCache(name, id, data)` saves a copy
106
+ you already have, such as rows from a list response, so a later offline read
107
+ of that record finds it.
108
+
109
+ ```js
110
+ await kit.editSynced('trip', tripId, { status: 'completed', notes });
111
+ ```
112
+
113
+ `editSynced(name, id, fields)` compares `fields` with the cached copy and keeps
114
+ only the fields that changed (a shallow `===` compare). If nothing changed it
115
+ does nothing. Otherwise it writes the new values into the cache at once, so the
116
+ next read shows them, and queues one patch. Repeated edits to one record
117
+ coalesce into one queued patch, newest value per field. The patch is sent as
118
+
119
+ ```json
120
+ { "status": "completed", "notes": "…", "_fieldTimes": { "status": 1730300000000, "notes": 1730300000000 } }
121
+ ```
122
+
123
+ `queueBlob(name, { url, method, blob, headers, idemKey, meta })` queues a file
124
+ upload (a photo, a receipt). Blobs are sent after every queued patch, each with
125
+ its `idemKey`, so the server can drop a duplicate if an acknowledgment was lost.
126
+ `meta` is passed back to `request` untouched; use it to tell kinds of blob
127
+ apart, since `request` is not told the resource name.
128
+
129
+ Edits and blobs flush on their own when the kit is online. Call
130
+ `flushNow()` to flush at any other time; it resolves to
131
+ `{ sentPatches, sentBlobs, remaining }`.
132
+
133
+ ### 4. Wire online state
134
+
135
+ `isOnline` is read **once**, at construction. After that the kit only knows
136
+ what you tell it through `setOnline(bool)`:
137
+
138
+ ```js
139
+ window.addEventListener('online', () => { kit.setOnline(true); kit.flushNow(); });
140
+ window.addEventListener('offline', () => kit.setOnline(false));
141
+ ```
142
+
143
+ On React Native, feed `setOnline` from your connectivity listener the same way.
144
+
145
+ ### 5. Show sync status
146
+
147
+ ```js
148
+ const unsubscribe = kit.subscribe(({ online, pendingCount, lastSyncedAt, flushing }) => {
149
+ renderSyncChip({ online, pendingCount });
150
+ });
151
+ ```
152
+
153
+ `subscribe(fn)` calls `fn` at once and again on every change, and returns an
154
+ unsubscribe function. `getStatus()` returns the same object synchronously.
155
+ `pendingCount` counts queued patches plus queued blobs.
156
+
157
+ ### 6. Apply field-level last-write-wins on the server
158
+
159
+ The table needs a `field_ts` JSONB column that maps a column name to the client
160
+ timestamp of the write that last set it, plus a tenant column and an
161
+ `updated_at` column:
162
+
163
+ ```sql
164
+ ALTER TABLE trips ADD COLUMN IF NOT EXISTS field_ts jsonb NOT NULL DEFAULT '{}'::jsonb;
165
+ ```
166
+
167
+ In the PATCH route, take the `_fieldTimes` the kit sent and hand the fields to
168
+ `applyFieldLWW`:
169
+
170
+ ```js
171
+ import { applyFieldLWW } from '@aventoapp/framework/server';
172
+
173
+ const EDITABLE = ['status', 'notes', 'pax_count'];
174
+
175
+ router.patch('/api/trips/:id', async (req, res) => {
176
+ const { _fieldTimes, ...body } = req.body;
177
+ // Only columns you allow. applyFieldLWW refuses a name that is not a plain
178
+ // SQL identifier, but deciding which columns a client may write is yours.
179
+ const fields = Object.fromEntries(Object.entries(body).filter(([k]) => EDITABLE.includes(k)));
180
+
181
+ if (_fieldTimes && typeof _fieldTimes === 'object') {
182
+ const result = await applyFieldLWW(client, {
183
+ table: 'trips',
184
+ id: req.params.id,
185
+ tenantId: req.tenant.id,
186
+ fields,
187
+ fieldTimes: _fieldTimes,
188
+ });
189
+ if (result.notFound) return res.status(404).end();
190
+ // result.applied: columns written; result.skipped: columns a newer write already set
191
+ } else {
192
+ // An online client sent no timestamps: your normal update path.
193
+ }
194
+ res.json(await readTrip(req.params.id));
195
+ });
196
+ ```
197
+
198
+ `applyFieldLWW(db, { table, id, tenantId, fields, fieldTimes, idCol = 'id',
199
+ tenantCol = 'tenant_id', fieldTsCol = 'field_ts' })` reads the row's
200
+ `field_ts`, writes each field whose incoming timestamp is greater than or equal
201
+ to the stored one, stores the new timestamps, and sets `updated_at = now()`.
202
+ A field with no timestamp counts as `0`, so it loses to any timestamped write
203
+ and wins only where nothing was ever stamped. `db` is anything with
204
+ `query(sql, params)`: pass the client of the transaction you are in, so the
205
+ read and the write see the same row. It resolves to
206
+ `{ applied, skipped }`, or `{ applied: [], skipped, notFound: true }` when no
207
+ row matches the id and tenant.
208
+
209
+ `buildFieldLWWUpdate({ fields, fieldTimes, storedFieldTs })` is the same
210
+ decision with no database, for tests or for a store that is not Postgres.
211
+
212
+ ### Things to get right
213
+
214
+ - **A refused write must leave the queue.** Returning `ok: false` for a 403 or
215
+ a 409 retries identical bytes forever and stops every patch (or blob) queued
216
+ behind it. Save the payload somewhere a person can see it, then return
217
+ `ok: true` so the kit drops it. Write that copy first: a stuck queue can be
218
+ recovered, a dropped record cannot.
219
+ - **Shared devices need one queue per user.** IndexedDB belongs to the origin,
220
+ not to the signed-in user. On a tablet several people sign in to, wrap the
221
+ `idb` you pass the kit so the `outbox` and `cache` keys carry the user id;
222
+ otherwise the next person's flush sends the last person's edits under their
223
+ own login, and sees their unsent values as if the server held them.
224
+ - **One tab at a time.** The outbox serializes its own writes within a page,
225
+ not across tabs. Two tabs open on one origin can each flush the same queue.
226
+ - **`editSynced` diffs against the cache.** Read (or `primeCache`) a record
227
+ before editing it offline, or every field you pass counts as changed.
228
+
229
+ ### Reference
230
+
231
+ | Export | Subpath |
232
+ |---|---|
233
+ | `createOfflineKit({ idb, clock, isOnline, request })` | `/offline` |
234
+ | `createIdb({ name, indexedDB })` | `/offline` |
235
+ | `createClock({ nowFn })` | `/offline` |
236
+ | `diffFields(prev, next)` | `/offline` |
237
+ | `coalescePatch(queue, entry)` | `/offline` |
238
+ | `createStore`, `createOutbox`, `createSyncer` | `/offline` (the kit's parts, for a custom assembly) |
239
+ | `OFFLINE_KIT_VERSION` | `/offline` |
240
+ | `applyFieldLWW(db, opts)`, `buildFieldLWWUpdate(opts)` | `/server` |
241
+
242
+ Kit methods: `defineSyncedResource(def)`, `readSynced(name, id)`,
243
+ `primeCache(name, id, data)`, `editSynced(name, id, fields)`,
244
+ `queueBlob(name, opts)`, `flushNow()`, `setOnline(bool)`, `getStatus()`,
245
+ `subscribe(fn)`.
246
+
247
+ ## Releasing
248
+
249
+ Releases publish from GitHub Actions with npm Trusted Publishing
250
+ (`.github/workflows/publish-framework.yml`), so no token and no 2FA prompt.
251
+ Bump `version` in `package.json` (and the `packages/framework` entry in the
252
+ root `package-lock.json`), commit, then push a tag matching the version:
253
+
254
+ ```bash
255
+ git tag framework-v0.2.1
256
+ git push origin master framework-v0.2.1
257
+ ```
258
+
259
+ The workflow checks that the tag matches the version, runs the offline kit's
260
+ tests, and runs `npm publish`, whose `prepublishOnly` builds `dist/` first.
package/dist/index.js.map CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../src/index.js"],
4
- "sourcesContent": ["// @avento/framework - Main entry point\r\n// Re-exports server, web, and shared modules\r\n\r\nexport const version = '0.1.0';\r\n\r\n// Server exports will be added in Day 3\r\n// Web exports will be added in Day 4\r\n// Shared exports available from day 1\r\n"],
4
+ "sourcesContent": ["// @avento/framework - Main entry point\n// Re-exports server, web, and shared modules\n\nexport const version = '0.1.0';\n\n// Server exports will be added in Day 3\n// Web exports will be added in Day 4\n// Shared exports available from day 1\n"],
5
5
  "mappings": ";AAGO,IAAM,UAAU;",
6
6
  "names": []
7
7
  }