@zveltio/sdk 3.0.0-beta.1 → 3.0.0-beta.101

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 (151) hide show
  1. package/README.md +17 -4
  2. package/dist/client.d.ts +103 -7
  3. package/dist/client.d.ts.map +1 -1
  4. package/dist/client.js +117 -27
  5. package/dist/core.d.ts.map +1 -1
  6. package/dist/core.js +21 -3
  7. package/dist/crdt.d.ts.map +1 -1
  8. package/dist/crdt.js +11 -2
  9. package/dist/ddl/index.d.ts +20 -0
  10. package/dist/ddl/index.d.ts.map +1 -1
  11. package/dist/errors.d.ts +58 -0
  12. package/dist/errors.d.ts.map +1 -0
  13. package/dist/errors.js +124 -0
  14. package/dist/extension/action-refusal.d.ts +27 -0
  15. package/dist/extension/action-refusal.d.ts.map +1 -0
  16. package/dist/extension/action-refusal.js +29 -0
  17. package/dist/extension/capabilities.d.ts +71 -0
  18. package/dist/extension/capabilities.d.ts.map +1 -0
  19. package/dist/extension/capabilities.js +79 -0
  20. package/dist/extension/dates.d.ts +7 -0
  21. package/dist/extension/dates.d.ts.map +1 -0
  22. package/dist/extension/dates.js +14 -0
  23. package/dist/extension/index.d.ts +1086 -38
  24. package/dist/extension/index.d.ts.map +1 -1
  25. package/dist/extension/index.js +16 -0
  26. package/dist/extension/jsonb.d.ts +62 -0
  27. package/dist/extension/jsonb.d.ts.map +1 -0
  28. package/dist/extension/jsonb.js +64 -0
  29. package/dist/extension/multipart.d.ts +58 -0
  30. package/dist/extension/multipart.d.ts.map +1 -0
  31. package/dist/extension/multipart.js +61 -0
  32. package/dist/extension/numeric.d.ts +94 -0
  33. package/dist/extension/numeric.d.ts.map +1 -0
  34. package/dist/extension/numeric.js +162 -0
  35. package/dist/extension/permission-gate.d.ts +15 -0
  36. package/dist/extension/permission-gate.d.ts.map +1 -1
  37. package/dist/extension/permission-gate.js +33 -1
  38. package/dist/extension/reserved-paths.d.ts +10 -0
  39. package/dist/extension/reserved-paths.d.ts.map +1 -0
  40. package/dist/extension/reserved-paths.js +23 -0
  41. package/dist/index.d.ts +3 -1
  42. package/dist/index.d.ts.map +1 -1
  43. package/dist/index.js +1 -0
  44. package/dist/local-store.d.ts +14 -1
  45. package/dist/local-store.d.ts.map +1 -1
  46. package/dist/local-store.js +92 -13
  47. package/dist/offline/index.d.ts +25 -55
  48. package/dist/offline/index.d.ts.map +1 -1
  49. package/dist/offline/index.js +173 -157
  50. package/dist/publish/index.d.ts.map +1 -1
  51. package/dist/publish/index.js +6 -1
  52. package/dist/realtime.d.ts +25 -1
  53. package/dist/realtime.d.ts.map +1 -1
  54. package/dist/realtime.js +47 -3
  55. package/dist/rpc/index.d.ts.map +1 -1
  56. package/dist/rpc/index.js +2 -0
  57. package/dist/schema-codegen.d.ts +25 -1
  58. package/dist/schema-codegen.d.ts.map +1 -1
  59. package/dist/schema-codegen.js +141 -7
  60. package/dist/schema-watcher.d.ts +10 -2
  61. package/dist/schema-watcher.d.ts.map +1 -1
  62. package/dist/schema-watcher.js +25 -10
  63. package/dist/studio/index.d.ts +1 -0
  64. package/dist/studio/index.d.ts.map +1 -1
  65. package/dist/studio/index.js +3 -0
  66. package/dist/studio/slot-owner-registry.d.ts +13 -0
  67. package/dist/studio/slot-owner-registry.d.ts.map +1 -0
  68. package/dist/studio/slot-owner-registry.js +21 -0
  69. package/dist/svelte.d.ts +1 -1
  70. package/dist/svelte.d.ts.map +1 -1
  71. package/dist/svelte.js +4 -2
  72. package/dist/sync-manager.d.ts +49 -4
  73. package/dist/sync-manager.d.ts.map +1 -1
  74. package/dist/sync-manager.js +173 -15
  75. package/dist/testing/index.d.ts.map +1 -1
  76. package/dist/testing/index.js +23 -1
  77. package/dist/testing/with-test-db.d.ts +1 -1
  78. package/dist/testing/with-test-db.d.ts.map +1 -1
  79. package/dist/testing/with-test-db.js +22 -15
  80. package/dist/tests/action-refusal.test.d.ts +2 -0
  81. package/dist/tests/action-refusal.test.d.ts.map +1 -0
  82. package/dist/tests/action-refusal.test.js +13 -0
  83. package/dist/tests/client.test.d.ts +2 -0
  84. package/dist/tests/client.test.d.ts.map +1 -0
  85. package/dist/tests/client.test.js +164 -0
  86. package/dist/tests/crdt-orset.test.d.ts +2 -0
  87. package/dist/tests/crdt-orset.test.d.ts.map +1 -0
  88. package/dist/tests/crdt-orset.test.js +23 -0
  89. package/dist/tests/local-store.test.js +44 -0
  90. package/dist/tests/migration-parse.test.d.ts +2 -0
  91. package/dist/tests/migration-parse.test.d.ts.map +1 -0
  92. package/dist/tests/migration-parse.test.js +17 -0
  93. package/dist/tests/multipart.test.d.ts +2 -0
  94. package/dist/tests/multipart.test.d.ts.map +1 -0
  95. package/dist/tests/multipart.test.js +37 -0
  96. package/dist/tests/offline-provider-crdt.test.d.ts +2 -0
  97. package/dist/tests/offline-provider-crdt.test.d.ts.map +1 -0
  98. package/dist/tests/offline-provider-crdt.test.js +206 -0
  99. package/dist/tests/realtime.test.d.ts +2 -0
  100. package/dist/tests/realtime.test.d.ts.map +1 -0
  101. package/dist/tests/realtime.test.js +220 -0
  102. package/dist/tests/reserved-paths.test.d.ts +2 -0
  103. package/dist/tests/reserved-paths.test.d.ts.map +1 -0
  104. package/dist/tests/reserved-paths.test.js +21 -0
  105. package/dist/tests/sync-manager.test.d.ts +2 -0
  106. package/dist/tests/sync-manager.test.d.ts.map +1 -0
  107. package/dist/tests/sync-manager.test.js +123 -0
  108. package/dist/tests/today-in.test.d.ts +2 -0
  109. package/dist/tests/today-in.test.d.ts.map +1 -0
  110. package/dist/tests/today-in.test.js +14 -0
  111. package/dist/tests/validate-manifest-actions.test.d.ts +2 -0
  112. package/dist/tests/validate-manifest-actions.test.d.ts.map +1 -0
  113. package/dist/tests/validate-manifest-actions.test.js +82 -0
  114. package/dist/tests/validate-manifest-dependencies.test.d.ts +2 -0
  115. package/dist/tests/validate-manifest-dependencies.test.d.ts.map +1 -0
  116. package/dist/tests/validate-manifest-dependencies.test.js +27 -0
  117. package/dist/tests/validate-manifest-forward-credentials.test.d.ts +2 -0
  118. package/dist/tests/validate-manifest-forward-credentials.test.d.ts.map +1 -0
  119. package/dist/tests/validate-manifest-forward-credentials.test.js +35 -0
  120. package/dist/tests/validate-sdui-data-endpoints.test.d.ts +2 -0
  121. package/dist/tests/validate-sdui-data-endpoints.test.d.ts.map +1 -0
  122. package/dist/tests/validate-sdui-data-endpoints.test.js +41 -0
  123. package/dist/tests/with-test-db.test.d.ts +2 -0
  124. package/dist/tests/with-test-db.test.d.ts.map +1 -0
  125. package/dist/tests/with-test-db.test.js +57 -0
  126. package/dist/types/index.d.ts.map +1 -1
  127. package/dist/validate/index.d.ts +53 -0
  128. package/dist/validate/index.d.ts.map +1 -1
  129. package/dist/validate/index.js +693 -7
  130. package/dist/validate/migration-parse.d.ts +10 -5
  131. package/dist/validate/migration-parse.d.ts.map +1 -1
  132. package/dist/validate/migration-parse.js +1 -1
  133. package/dist/validate/shared-message-keys.d.ts +16 -0
  134. package/dist/validate/shared-message-keys.d.ts.map +1 -0
  135. package/dist/validate/shared-message-keys.js +227 -0
  136. package/package.json +8 -8
  137. package/dist/client/Auth.d.ts +0 -19
  138. package/dist/client/Auth.d.ts.map +0 -1
  139. package/dist/client/Auth.js +0 -45
  140. package/dist/client/QueryBuilder.d.ts +0 -17
  141. package/dist/client/QueryBuilder.d.ts.map +0 -1
  142. package/dist/client/QueryBuilder.js +0 -85
  143. package/dist/client/RealtimeClient.d.ts +0 -22
  144. package/dist/client/RealtimeClient.d.ts.map +0 -1
  145. package/dist/client/RealtimeClient.js +0 -98
  146. package/dist/client/ZveltioClient.d.ts +0 -20
  147. package/dist/client/ZveltioClient.d.ts.map +0 -1
  148. package/dist/client/ZveltioClient.js +0 -78
  149. package/dist/generate-types.d.ts +0 -37
  150. package/dist/generate-types.d.ts.map +0 -1
  151. package/dist/generate-types.js +0 -157
@@ -1,59 +1,39 @@
1
1
  /**
2
2
  * Offline-sync provider abstraction.
3
3
  *
4
- * The SDK ships TWO sync strategies for the Postgres ↔ client-SQLite
4
+ * The SDK ships TWO sync strategies for the Postgres ↔ client store
5
5
  * loop, picked at construction time:
6
6
  *
7
7
  * - **`crdt`** (default) — bespoke field-level Last-Write-Wins merge on
8
- * top of IndexedDB / SQLite via `LocalStore` + `SyncManager`. Works
9
- * offline, applies on reconnect, handles conflicts. No external
10
- * dependency beyond the SDK + engine.
8
+ * top of IndexedDB via `LocalStore` + `SyncManager`. Works offline,
9
+ * applies on reconnect, handles conflicts. No external dependency beyond
10
+ * the SDK + engine. Browser only: there is no store for React Native or
11
+ * Node (no SQLite backend).
11
12
  *
12
- * - **`electric`** — Electric SQL replication. Postgres logical-
13
- * replication slot → Electric service → client. Conflicts are
14
- * resolved server-side via CRDTs Electric implements internally.
15
- * Requires an Electric service running alongside Postgres + the
16
- * engine routes from `routes/electric.ts` that mint short-lived
17
- * JWTs the client uses to authenticate.
13
+ * - **`electric`** — Electric 1.x shapes, served THROUGH the engine:
14
+ * `GET {engineUrl}/api/electric/v1/shape?collection=…`. The engine decides
15
+ * the table, rows and columns from the caller's grants, tenant, row rules
16
+ * and column permissions, and proxies Electric's Shape protocol (initial
17
+ * snapshot, then long-poll `live=true`). Read-only: writes go through the
18
+ * data API, and Electric streams them back. Requires the engine's
19
+ * ELECTRIC_URL + ELECTRIC_SECRET; the client never talks to Electric.
18
20
  *
19
- * Auth flow for the electric provider
20
- * -----------------------------------
21
- * 1. Provider calls `POST {engineUrl}/api/electric/auth` (with
22
- * credentials; the engine reads the better-auth session).
23
- * 2. Engine returns `{ token, expiresAt, electricUrl }`.
24
- * 3. Provider opens a websocket to `${electricUrl}?token=<jwt>`.
25
- * 4. Before each token expires, the provider re-requests a fresh one
26
- * (no user interaction).
27
- *
28
- * Pull/push semantics
29
- * -------------------
30
- * Electric replicates continuously over the websocket — there's no
31
- * explicit "pull" call. The provider's `pull()` is a no-op that returns
32
- * once the initial sync handshake completes. `push()` is the same: local
33
- * writes go through Electric's normal replication path automatically.
34
- * Both shims exist so the OfflineProvider interface stays uniform across
35
- * crdt/electric.
36
- *
37
- * Subscriptions
38
- * -------------
39
- * `subscribe('zvd_contacts', cb)` registers a callback fired whenever
40
- * Electric pushes a change for that table. The implementation uses the
41
- * websocket's `message` event with a routing table; one socket, many
42
- * subscriptions.
21
+ * `subscribe('contacts', cb)` keeps one live shape per collection and calls
22
+ * `cb` with every current row after each change. `pull()` brings each of
23
+ * `tables` up to date once.
43
24
  */
44
25
  export class ElectricNotConfigured extends Error {
45
26
  constructor(reason) {
46
27
  super(`Electric SQL provider is not configured: ${reason}. ` +
47
- `Set provider: 'crdt' for the default sync path, or stand up an Electric ` +
48
- `service and pass electricUrl. See docs/OFFLINE-SYNC.md.`);
28
+ `Set provider: 'crdt' for the default sync path. See docs/engine/offline-sync.md.`);
49
29
  this.name = 'ElectricNotConfigured';
50
30
  }
51
31
  }
52
32
  export class ElectricUnavailable extends Error {
53
33
  constructor(reason) {
54
34
  super(`Electric SQL is unavailable: ${reason}. ` +
55
- `The engine reported ELECTRIC_URL / ELECTRIC_AUTH_TOKEN are unset, or the ` +
56
- `Electric service is down. Fall back to provider: 'crdt' or check the ops checklist.`);
35
+ `The engine refused the shape, reports ELECTRIC_URL / ELECTRIC_SECRET unset, or ` +
36
+ `the Electric service is down. Fall back to provider: 'crdt' or check the ops checklist.`);
57
37
  this.name = 'ElectricUnavailable';
58
38
  }
59
39
  }
@@ -62,11 +42,9 @@ export class ElectricUnavailable extends Error {
62
42
  *
63
43
  * For `crdt` (default): returns a thin adapter around `SyncManager`.
64
44
  *
65
- * For `electric`: returns the real Electric provider. Throws
66
- * `ElectricNotConfigured` synchronously when required config is missing
67
- * (no electricUrl AND no way to discover one), or `ElectricUnavailable`
68
- * lazily on the first network op when the engine reports Electric is
69
- * disabled.
45
+ * For `electric`: syncs `tables` once before resolving. Throws
46
+ * `ElectricNotConfigured` when there is no `fetch`, and `ElectricUnavailable`
47
+ * when the engine refuses a shape (401, 403, 409 with its reason, 503).
70
48
  */
71
49
  export async function createOfflineProvider(config) {
72
50
  const kind = config.provider ?? 'crdt';
@@ -76,27 +54,63 @@ export async function createOfflineProvider(config) {
76
54
  return makeCrdtAdapter(config);
77
55
  }
78
56
  // ── CRDT adapter (today's working path) ─────────────────────────────────────
79
- async function makeCrdtAdapter(_config) {
80
- // The existing SyncManager lives in `sync-manager.ts`. We don't import
81
- // it at the top of this file to keep the bundle tree-shakeable for
82
- // consumers who only want the type definitions. Lazy import here.
83
- const { SyncManager } = await import('../sync-manager.js');
84
- void SyncManager;
57
+ /**
58
+ * The CRDT provider, wrapping `SyncManager`.
59
+ *
60
+ * It did not wrap anything. `pull()` was an empty body, `subscribe()` returned
61
+ * an unsubscribe that unsubscribed from nothing, and `push()` returned `0` —
62
+ * which is the worst of the four, because `0` reads as "there was nothing to
63
+ * send" rather than "I did not look". `SyncManager` was imported and then
64
+ * discarded with `void SyncManager`, and the interface docs a few lines up said
65
+ * "Today the CRDT provider wraps SyncManager" while it did not.
66
+ *
67
+ * This is the DEFAULT provider (`config.provider ?? 'crdt'`), so an application
68
+ * that called `createOfflineProvider({ engineUrl })` and pushed on a timer got a
69
+ * clean run and an empty server, forever, with nothing in any log.
70
+ *
71
+ * The store is opened but background sync is NOT started: this interface is
72
+ * explicitly pull/push, and a timer firing `syncNow()` underneath would make the
73
+ * number `push()` returns meaningless.
74
+ */
75
+ async function makeCrdtAdapter(config) {
76
+ // Lazy imports keep the bundle tree-shakeable for consumers who only want the
77
+ // type definitions.
78
+ const [{ SyncManager }, { ZveltioClient }] = await Promise.all([
79
+ import('../sync-manager.js'),
80
+ import('../client.js'),
81
+ ]);
82
+ const client = new ZveltioClient({ baseUrl: config.engineUrl });
83
+ const sync = new SyncManager(client);
84
+ await sync.open();
85
+ const tables = config.tables ?? [];
85
86
  return {
86
87
  kind: 'crdt',
87
88
  async pull() {
88
- /* delegated to SyncManager in the full impl */
89
+ // Silence here is what the old implementation was. A provider asked to
90
+ // pull with nothing to pull from is a configuration mistake, and saying so
91
+ // costs one throw; not saying so costs an empty local database that looks
92
+ // like an empty server.
93
+ if (tables.length === 0) {
94
+ throw new Error('createOfflineProvider: `tables` is empty, so there is nothing to pull. ' +
95
+ 'List the collections to replicate, e.g. { tables: ["orders", "customers"] }.');
96
+ }
97
+ await sync.pull(tables);
89
98
  },
90
99
  async push() {
91
- return 0;
100
+ // The count is the drop in pending operations across the sync. Operations
101
+ // that failed stay pending and are therefore not counted, which is what
102
+ // "the number of ops sent" has to mean if the number is to be worth
103
+ // anything.
104
+ const before = await sync.getStatus();
105
+ await sync.syncNow();
106
+ const after = await sync.getStatus();
107
+ return Math.max(0, before.pending - after.pending);
92
108
  },
93
- subscribe(_table, _cb) {
94
- return () => {
95
- /* */
96
- };
109
+ subscribe(table, cb) {
110
+ return sync.collection(table).subscribe((rows) => cb(rows));
97
111
  },
98
112
  async close() {
99
- /* */
113
+ await sync.stop();
100
114
  },
101
115
  };
102
116
  }
@@ -105,131 +119,133 @@ async function makeElectricProvider(config) {
105
119
  if (typeof doFetch !== 'function') {
106
120
  throw new ElectricNotConfigured('no fetch implementation available — pass config.fetch');
107
121
  }
108
- const WSCandidate = config.websocket ?? globalThis.WebSocket;
109
- if (typeof WSCandidate !== 'function') {
110
- throw new ElectricNotConfigured('no WebSocket implementation available — pass config.websocket');
111
- }
112
- const WS = WSCandidate;
113
- // Mint the first token + figure out the Electric URL.
114
- async function mintToken() {
115
- const res = await doFetch(`${config.engineUrl}/api/electric/auth`, {
116
- method: 'POST',
122
+ const shapes = new Map();
123
+ const subscribers = new Map();
124
+ const loops = new Map();
125
+ // The engine names collections; `zvd_contacts` is accepted for the old table spelling.
126
+ const nameOf = (table) => table.replace(/^zvd_/, '');
127
+ const notify = (name) => {
128
+ const rows = [...(shapes.get(name)?.rows.values() ?? [])];
129
+ for (const cb of subscribers.get(name) ?? [])
130
+ cb(rows);
131
+ };
132
+ /** One Shape-protocol request. Resolves true once the shape is up to date. */
133
+ async function step(name, live, signal) {
134
+ const st = shapes.get(name) ?? { rows: new Map(), offset: '-1' };
135
+ shapes.set(name, st);
136
+ const qs = new URLSearchParams({ collection: name, offset: st.offset });
137
+ if (st.handle)
138
+ qs.set('handle', st.handle);
139
+ if (live)
140
+ qs.set('live', 'true');
141
+ if (live && st.cursor)
142
+ qs.set('cursor', st.cursor);
143
+ const res = await doFetch(`${config.engineUrl}/api/electric/v1/shape?${qs}`, {
117
144
  credentials: 'include',
118
- headers: { 'Content-Type': 'application/json' },
119
- body: JSON.stringify({ tables: config.tables ?? [] }),
145
+ headers: config.headers,
146
+ signal,
120
147
  });
121
- if (res.status === 401) {
122
- throw new ElectricUnavailable('engine returned 401 — sign in before requesting Electric sync');
123
- }
124
- if (res.status === 503) {
148
+ if (!res.ok) {
125
149
  const body = (await res.json().catch(() => ({})));
126
- throw new ElectricUnavailable(body.error ?? 'engine reports Electric is not configured');
150
+ if (res.status === 409 && body.code === 'electric.must_refetch') {
151
+ // The shape was rebuilt (a rule or grant changed): start over.
152
+ shapes.set(name, { rows: new Map(), offset: '-1' });
153
+ notify(name);
154
+ return false;
155
+ }
156
+ if (res.status === 403 && st.rows.size) {
157
+ // Read access was revoked: rows held from before must not outlive it.
158
+ shapes.set(name, { rows: new Map(), offset: '-1' });
159
+ notify(name);
160
+ }
161
+ throw new ElectricUnavailable(`engine returned ${res.status}${body.code ? ` ${body.code}` : ''}: ` +
162
+ (body.detail ?? body.error ?? 'no detail'));
127
163
  }
128
- if (!res.ok) {
129
- throw new ElectricUnavailable(`engine returned ${res.status}`);
164
+ const messages = (await res.json());
165
+ st.offset = res.headers.get('electric-offset') ?? st.offset;
166
+ st.handle = res.headers.get('electric-handle') ?? st.handle;
167
+ st.cursor = res.headers.get('electric-cursor') ?? st.cursor;
168
+ let changed = false;
169
+ let upToDate = false;
170
+ for (const m of messages) {
171
+ if (m.headers.control === 'up-to-date')
172
+ upToDate = true;
173
+ if (!m.key)
174
+ continue;
175
+ changed = true;
176
+ if (m.headers.operation === 'delete')
177
+ st.rows.delete(m.key);
178
+ // An update carries only the changed columns.
179
+ else
180
+ st.rows.set(m.key, { ...st.rows.get(m.key), ...m.value });
130
181
  }
131
- return (await res.json());
182
+ if (changed)
183
+ notify(name);
184
+ return upToDate;
132
185
  }
133
- let auth = await mintToken();
134
- let electricUrl = config.electricUrl ?? auth.electricUrl;
135
- // Per-table subscription registry.
136
- const subscribers = new Map();
137
- // Token refresh — fire-and-forget background timer that mints a fresh
138
- // token ~10s before the current one expires.
139
- let refreshTimer = null;
140
- function scheduleRefresh() {
141
- if (refreshTimer)
142
- clearTimeout(refreshTimer);
143
- const delay = Math.max(1_000, auth.expiresAt - Date.now() - 10_000);
144
- refreshTimer = setTimeout(async () => {
145
- try {
146
- auth = await mintToken();
147
- scheduleRefresh();
148
- // No need to reconnect — Electric accepts refreshed tokens via
149
- // its in-band auth-update message. The full Electric driver
150
- // would send `{ type: 'auth', token: auth.token }` over the
151
- // socket. We emit it here so the server-side TLS is kept warm.
152
- if (socket && socket.readyState === WS.OPEN) {
153
- socket.send(JSON.stringify({ type: 'auth', token: auth.token }));
186
+ async function syncOnce(name) {
187
+ for (let i = 0; i < 1000 && !(await step(name, false)); i++)
188
+ ;
189
+ }
190
+ function follow(name) {
191
+ if (loops.has(name))
192
+ return;
193
+ const ctl = new AbortController();
194
+ loops.set(name, ctl);
195
+ void (async () => {
196
+ let backoff = 1_000;
197
+ let upToDate = false;
198
+ while (!ctl.signal.aborted) {
199
+ try {
200
+ upToDate = await step(name, upToDate, ctl.signal);
201
+ backoff = 1_000;
202
+ }
203
+ catch (err) {
204
+ if (ctl.signal.aborted)
205
+ return;
206
+ // A refusal (403, 409) stays a refusal until something changes; retry slowly.
207
+ console.warn(`[offline:electric] ${name}:`, err.message);
208
+ await new Promise((r) => setTimeout(r, backoff));
209
+ backoff = Math.min(backoff * 2, 30_000);
154
210
  }
155
211
  }
156
- catch (err) {
157
- console.warn('[offline:electric] token refresh failed:', err.message);
158
- }
159
- }, delay);
212
+ })();
160
213
  }
161
- // Open the websocket. Electric's URL contract is
162
- // `${baseUrl}?token=<jwt>`; we forward the URL the engine gave us.
163
- let socket;
164
- const handshake = new Promise((resolve, reject) => {
165
- const url = `${electricUrl}${electricUrl.includes('?') ? '&' : '?'}token=${encodeURIComponent(auth.token)}`;
166
- socket = new WS(url);
167
- socket.addEventListener('open', () => {
168
- resolve();
169
- scheduleRefresh();
170
- });
171
- socket.addEventListener('error', (ev) => {
172
- // The first error fires before `open`; treat it as a connect failure.
173
- reject(new ElectricUnavailable(`websocket error: ${ev.message ?? 'unknown'}`));
174
- });
175
- socket.addEventListener('message', (ev) => {
176
- let msg;
177
- try {
178
- msg = JSON.parse(ev.data);
179
- }
180
- catch {
181
- return; // Electric sometimes sends binary heartbeats — skip parse errors.
182
- }
183
- if (msg.type === 'change' && msg.table && Array.isArray(msg.rows)) {
184
- const subs = subscribers.get(msg.table);
185
- if (subs)
186
- for (const cb of subs)
187
- cb(msg.rows);
188
- }
189
- });
190
- });
191
- await handshake;
192
- return {
214
+ const provider = {
193
215
  kind: 'electric',
194
216
  async pull() {
195
- // Electric is continuous-sync — `pull` is a no-op that exists for
196
- // API parity with the CRDT path.
217
+ // A followed collection is already kept current by its live loop.
218
+ for (const t of config.tables ?? [])
219
+ if (!loops.has(nameOf(t)))
220
+ await syncOnce(nameOf(t));
197
221
  },
198
222
  async push() {
199
- // Same shape — local writes flow through replication automatically.
200
- return 0;
223
+ throw new Error('The electric provider syncs reads only: write through the data API ' +
224
+ '(client.collection(name).create/update/delete); Electric streams the change back.');
201
225
  },
202
226
  subscribe(table, cb) {
203
- let set = subscribers.get(table);
204
- if (!set) {
205
- set = new Set();
206
- subscribers.set(table, set);
207
- // Tell Electric we're interested in this table — the protocol
208
- // is documented in Electric's docs as `{ type: 'subscribe', table }`.
209
- if (socket.readyState === WS.OPEN) {
210
- socket.send(JSON.stringify({ type: 'subscribe', table }));
211
- }
212
- }
227
+ const name = nameOf(table);
228
+ const set = subscribers.get(name) ?? new Set();
229
+ subscribers.set(name, set);
213
230
  set.add(cb);
231
+ follow(name);
214
232
  return () => {
215
233
  set.delete(cb);
216
234
  if (set.size === 0) {
217
- subscribers.delete(table);
218
- if (socket.readyState === WS.OPEN) {
219
- socket.send(JSON.stringify({ type: 'unsubscribe', table }));
220
- }
235
+ subscribers.delete(name);
236
+ loops.get(name)?.abort();
237
+ loops.delete(name);
221
238
  }
222
239
  };
223
240
  },
224
241
  async close() {
225
- if (refreshTimer) {
226
- clearTimeout(refreshTimer);
227
- refreshTimer = null;
228
- }
229
- if (socket.readyState === WS.OPEN || socket.readyState === WS.CONNECTING) {
230
- socket.close();
231
- }
242
+ for (const ctl of loops.values())
243
+ ctl.abort();
244
+ loops.clear();
232
245
  subscribers.clear();
233
246
  },
234
247
  };
248
+ // Fail at creation, as the token mint did, when the engine refuses.
249
+ await provider.pull();
250
+ return provider;
235
251
  }
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/publish/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAEH,+EAA+E;AAC/E,MAAM,WAAW,cAAc;IAC7B,+DAA+D;IAC/D,KAAK,EAAE,MAAM,CAAC;IACd,2CAA2C;IAC3C,SAAS,EAAE,MAAM,CAAC;IAClB,mCAAmC;IACnC,SAAS,EAAE,UAAU,CAAC;IACtB,oDAAoD;IACpD,UAAU,EAAE,UAAU,CAAC;CACxB;AAED,qFAAqF;AACrF,MAAM,WAAW,kBAAkB;IACjC,SAAS,EAAE,SAAS,CAAC;IACrB,+CAA+C;IAC/C,SAAS,EAAE,MAAM,CAAC;IAClB,oCAAoC;IACpC,YAAY,EAAE,MAAM,CAAC;IACrB,+BAA+B;IAC/B,QAAQ,EAAE,MAAM,CAAC;IACjB,sEAAsE;IACtE,KAAK,EAAE,MAAM,CAAC;CACf;AAED,iBAAS,UAAU,CAAC,KAAK,EAAE,WAAW,GAAG,UAAU,GAAG,MAAM,CAK3D;AAED,iBAAS,aAAa,CAAC,KAAK,EAAE,UAAU,GAAG,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EAAE,UAAU,GACpB,OAAO,CAAC;IAAE,EAAE,EAAE,IAAI,CAAA;CAAE,GAAG;IAAE,EAAE,EAAE,KAAK,CAAC;IAAC,MAAM,EAAE,MAAM,CAAA;CAAE,CAAC,CA+BvD;AAED;;;;;;;GAOG;AACH,wBAAsB,qBAAqB,CACzC,KAAK,EAAE,MAAM,EACb,SAAS,EAAE,UAAU,GACpB,OAAO,CAAC;IAAE,KAAK,EAAE,MAAM,CAAC;IAAC,YAAY,EAAE,MAAM,CAAA;CAAE,CAAC,CASlD;AAGD,eAAO,MAAM,MAAM;;;;CAA+C,CAAC"}
@@ -86,6 +86,7 @@ export async function signBundle(archive, keypair) {
86
86
  const bundleSha256 = await sha256Hex(archive);
87
87
  const key = await importPrivateKey(keypair.privateJwk);
88
88
  const dataBytes = new TextEncoder().encode(bundleSha256.toLowerCase());
89
+ // biome-ignore lint/suspicious/noExplicitAny: legacy any; tracked in hardening plan item H-01
89
90
  const sigBuf = await crypto.subtle.sign({ name: 'Ed25519' }, key, dataBytes);
90
91
  return {
91
92
  algorithm: 'ed25519',
@@ -123,7 +124,11 @@ export async function verifyBundle(archive, signature, publicJwk) {
123
124
  }
124
125
  const key = await importPublicKey(publicJwk);
125
126
  const dataBytes = new TextEncoder().encode(signature.bundleSha256.toLowerCase());
126
- const ok = await crypto.subtle.verify({ name: 'Ed25519' }, key, sigBytes, dataBytes);
127
+ const ok = await crypto.subtle.verify({ name: 'Ed25519' }, key,
128
+ // biome-ignore lint/suspicious/noExplicitAny: legacy any; tracked in hardening plan item H-01
129
+ sigBytes,
130
+ // biome-ignore lint/suspicious/noExplicitAny: legacy any; tracked in hardening plan item H-01
131
+ dataBytes);
127
132
  return ok ? { ok: true } : { ok: false, reason: 'Ed25519 verification failed' };
128
133
  }
129
134
  /**
@@ -1,3 +1,16 @@
1
+ /**
2
+ * The engine closes a socket with this code when the session or API key it
3
+ * opened with is no longer valid (signed out, revoked, expired, user
4
+ * deactivated). Reconnecting is refused with 401, so clients stop instead.
5
+ */
6
+ export declare const WS_UNAUTHORIZED = 4001;
7
+ /**
8
+ * A WebSocket that sends `headers` with the upgrade where the runtime can (the
9
+ * Bun/undici `{ headers }` second argument). A browser's constructor reads that
10
+ * argument as subprotocols and throws on an object, so there the socket opens
11
+ * without them and authenticates by the session cookie.
12
+ */
13
+ export declare function openWebSocket(url: string, headers?: Record<string, string>): WebSocket;
1
14
  export declare class ZveltioRealtime {
2
15
  private ws;
3
16
  private listeners;
@@ -5,10 +18,21 @@ export declare class ZveltioRealtime {
5
18
  private reconnectAttempts;
6
19
  private maxReconnectAttempts;
7
20
  private reconnectTimer;
8
- constructor(baseUrl: string);
21
+ private headers;
22
+ private unauthorizedCallbacks;
23
+ /**
24
+ * @param options.headers Sent with the upgrade — e.g. `{ 'X-API-Key': key }`
25
+ * for a server-side client. Bun and Node (undici) accept them; a browser
26
+ * cannot set headers on a WebSocket and authenticates by session cookie.
27
+ */
28
+ constructor(baseUrl: string, options?: {
29
+ headers?: Record<string, string>;
30
+ });
9
31
  connect(): void;
10
32
  private attemptReconnect;
11
33
  subscribe(collection: string, callback: (data: any) => void): () => void;
34
+ /** Called when the engine ends the socket because its credentials were revoked. */
35
+ onUnauthorized(callback: () => void): () => void;
12
36
  disconnect(): void;
13
37
  }
14
38
  //# sourceMappingURL=realtime.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"realtime.d.ts","sourceRoot":"","sources":["../src/realtime.ts"],"names":[],"mappings":"AAAA,qBAAa,eAAe;IAC1B,OAAO,CAAC,EAAE,CAA0B;IACpC,OAAO,CAAC,SAAS,CAAoD;IACrE,OAAO,CAAC,OAAO,CAAS;IACxB,OAAO,CAAC,iBAAiB,CAAK;IAC9B,OAAO,CAAC,oBAAoB,CAAM;IAClC,OAAO,CAAC,cAAc,CAA8C;gBAExD,OAAO,EAAE,MAAM;IAK3B,OAAO,IAAI,IAAI;IAyCf,OAAO,CAAC,gBAAgB;IAQxB,SAAS,CAAC,UAAU,EAAE,MAAM,EAAE,QAAQ,EAAE,CAAC,IAAI,EAAE,GAAG,KAAK,IAAI,GAAG,MAAM,IAAI;IAqBxE,UAAU,IAAI,IAAI;CAQnB"}
1
+ {"version":3,"file":"realtime.d.ts","sourceRoot":"","sources":["../src/realtime.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AACH,eAAO,MAAM,eAAe,OAAO,CAAC;AAEpC;;;;;GAKG;AACH,wBAAgB,aAAa,CAAC,GAAG,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,GAAG,SAAS,CAStF;AAED,qBAAa,eAAe;IAC1B,OAAO,CAAC,EAAE,CAA0B;IAEpC,OAAO,CAAC,SAAS,CAAoD;IACrE,OAAO,CAAC,OAAO,CAAS;IACxB,OAAO,CAAC,iBAAiB,CAAK;IAC9B,OAAO,CAAC,oBAAoB,CAAM;IAClC,OAAO,CAAC,cAAc,CAA8C;IACpE,OAAO,CAAC,OAAO,CAAqC;IACpD,OAAO,CAAC,qBAAqB,CAAyB;IAEtD;;;;OAIG;gBACS,OAAO,EAAE,MAAM,EAAE,OAAO,GAAE;QAAE,OAAO,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAA;KAAO;IAM/E,OAAO,IAAI,IAAI;IA+Cf,OAAO,CAAC,gBAAgB;IASxB,SAAS,CAAC,UAAU,EAAE,MAAM,EAAE,QAAQ,EAAE,CAAC,IAAI,EAAE,GAAG,KAAK,IAAI,GAAG,MAAM,IAAI;IAqBxE,mFAAmF;IACnF,cAAc,CAAC,QAAQ,EAAE,MAAM,IAAI,GAAG,MAAM,IAAI;IAKhD,UAAU,IAAI,IAAI;CAQnB"}
package/dist/realtime.js CHANGED
@@ -1,17 +1,49 @@
1
+ /**
2
+ * The engine closes a socket with this code when the session or API key it
3
+ * opened with is no longer valid (signed out, revoked, expired, user
4
+ * deactivated). Reconnecting is refused with 401, so clients stop instead.
5
+ */
6
+ export const WS_UNAUTHORIZED = 4001;
7
+ /**
8
+ * A WebSocket that sends `headers` with the upgrade where the runtime can (the
9
+ * Bun/undici `{ headers }` second argument). A browser's constructor reads that
10
+ * argument as subprotocols and throws on an object, so there the socket opens
11
+ * without them and authenticates by the session cookie.
12
+ */
13
+ export function openWebSocket(url, headers) {
14
+ if (headers && Object.keys(headers).length > 0) {
15
+ try {
16
+ return new WebSocket(url, { headers });
17
+ }
18
+ catch {
19
+ // A browser: no header can be set on a WebSocket.
20
+ }
21
+ }
22
+ return new WebSocket(url);
23
+ }
1
24
  export class ZveltioRealtime {
2
25
  ws = null;
26
+ // biome-ignore lint/suspicious/noExplicitAny: legacy any; tracked in hardening plan item H-01
3
27
  listeners = new Map();
4
28
  baseUrl;
5
29
  reconnectAttempts = 0;
6
30
  maxReconnectAttempts = 10;
7
31
  reconnectTimer = null;
8
- constructor(baseUrl) {
32
+ headers;
33
+ unauthorizedCallbacks = new Set();
34
+ /**
35
+ * @param options.headers Sent with the upgrade — e.g. `{ 'X-API-Key': key }`
36
+ * for a server-side client. Bun and Node (undici) accept them; a browser
37
+ * cannot set headers on a WebSocket and authenticates by session cookie.
38
+ */
39
+ constructor(baseUrl, options = {}) {
9
40
  // Convert http(s) to ws(s)
10
41
  this.baseUrl = baseUrl.replace(/^http/, 'ws');
42
+ this.headers = options.headers;
11
43
  }
12
44
  connect() {
13
45
  const wsUrl = `${this.baseUrl}/api/ws`;
14
- this.ws = new WebSocket(wsUrl);
46
+ this.ws = openWebSocket(wsUrl, this.headers);
15
47
  this.ws.onopen = () => {
16
48
  this.reconnectAttempts = 0;
17
49
  // Re-subscribe to all existing collections using the server's expected protocol
@@ -40,7 +72,13 @@ export class ZveltioRealtime {
40
72
  /* invalid JSON — ignore */
41
73
  }
42
74
  };
43
- this.ws.onclose = () => {
75
+ this.ws.onclose = (event) => {
76
+ if (event?.code === WS_UNAUTHORIZED) {
77
+ // No retry: every attempt would be refused. `connect()` again once the
78
+ // app holds a valid session or key.
79
+ this.unauthorizedCallbacks.forEach((cb) => cb());
80
+ return;
81
+ }
44
82
  this.attemptReconnect();
45
83
  };
46
84
  this.ws.onerror = () => {
@@ -55,6 +93,7 @@ export class ZveltioRealtime {
55
93
  this.reconnectAttempts++;
56
94
  this.reconnectTimer = setTimeout(() => this.connect(), delay);
57
95
  }
96
+ // biome-ignore lint/suspicious/noExplicitAny: legacy any; tracked in hardening plan item H-01
58
97
  subscribe(collection, callback) {
59
98
  if (!this.listeners.has(collection))
60
99
  this.listeners.set(collection, new Set());
@@ -74,6 +113,11 @@ export class ZveltioRealtime {
74
113
  }
75
114
  };
76
115
  }
116
+ /** Called when the engine ends the socket because its credentials were revoked. */
117
+ onUnauthorized(callback) {
118
+ this.unauthorizedCallbacks.add(callback);
119
+ return () => this.unauthorizedCallbacks.delete(callback);
120
+ }
77
121
  disconnect() {
78
122
  if (this.reconnectTimer)
79
123
  clearTimeout(this.reconnectTimer);
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/rpc/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA+BG;AAEH,OAAO,EAAE,EAAE,EAAE,MAAM,aAAa,CAAC;AACjC,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,MAAM,CAAC;AAEjC,MAAM,WAAW,gBAAgB;IAC/B,mFAAmF;IACnF,OAAO,EAAE,MAAM,CAAC;IAChB;;;OAGG;IACH,OAAO,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IACjC,kFAAkF;IAClF,UAAU,CAAC,EAAE,MAAM,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,GAAG,OAAO,CAAC,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC,CAAC;IAC5E;;;;;OAKG;IACH,kBAAkB,CAAC,EAAE,OAAO,CAAC;IAC7B;;;;OAIG;IACH,KAAK,CAAC,EAAE,OAAO,KAAK,CAAC;CACtB;AAED;;;;;;GAMG;AACH,wBAAgB,eAAe,CAAC,CAAC,SAAS,IAAI,CAAC,GAAG,EAAE,GAAG,EAAE,GAAG,CAAC,EAC3D,IAAI,EAAE,gBAAgB,GACrB,UAAU,CAAC,OAAO,EAAE,CAAC,CAAC,CAAC,CAAC,CAoB1B;AAID,YAAY,EAAE,gBAAgB,EAAE,iBAAiB,EAAE,MAAM,aAAa,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/rpc/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA+BG;AAEH,OAAO,EAAE,EAAE,EAAE,MAAM,aAAa,CAAC;AACjC,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,MAAM,CAAC;AAEjC,MAAM,WAAW,gBAAgB;IAC/B,mFAAmF;IACnF,OAAO,EAAE,MAAM,CAAC;IAChB;;;OAGG;IACH,OAAO,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IACjC,kFAAkF;IAClF,UAAU,CAAC,EAAE,MAAM,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,GAAG,OAAO,CAAC,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC,CAAC;IAC5E;;;;;OAKG;IACH,kBAAkB,CAAC,EAAE,OAAO,CAAC;IAC7B;;;;OAIG;IACH,KAAK,CAAC,EAAE,OAAO,KAAK,CAAC;CACtB;AAED;;;;;;GAMG;AAGH,wBAAgB,eAAe,CAAC,CAAC,SAAS,IAAI,CAAC,GAAG,EAAE,GAAG,EAAE,GAAG,CAAC,EAC3D,IAAI,EAAE,gBAAgB,GACrB,UAAU,CAAC,OAAO,EAAE,CAAC,CAAC,CAAC,CAAC,CAqB1B;AAID,YAAY,EAAE,gBAAgB,EAAE,iBAAiB,EAAE,MAAM,aAAa,CAAC"}
package/dist/rpc/index.js CHANGED
@@ -38,9 +38,11 @@ import { hc } from 'hono/client';
38
38
  * `ZveltioApi` from `@zveltio/engine/api-types`. For an
39
39
  * extension's own routes, pass `typeof yourApp`.
40
40
  */
41
+ // biome-ignore lint/suspicious/noExplicitAny: legacy any; tracked in hardening plan item H-01
41
42
  export function createRpcClient(opts) {
42
43
  const baseUrl = opts.baseUrl.replace(/\/$/, '');
43
44
  const includeCredentials = opts.includeCredentials !== false;
45
+ // biome-ignore lint/suspicious/noExplicitAny: legacy any; tracked in hardening plan item H-01
44
46
  const customFetch = (async (input, init) => {
45
47
  const dynHeaders = opts.getHeaders ? await opts.getHeaders() : {};
46
48
  const merged = new Headers(init?.headers ?? {});
@@ -8,7 +8,9 @@
8
8
  * column names in editors and `tsc` catches typos.
9
9
  *
10
10
  * Scope intentionally narrow:
11
- * - Handles `CREATE TABLE [IF NOT EXISTS]` and `ALTER TABLE … ADD COLUMN`.
11
+ * - Reads only the UP half of each file (everything before `-- DOWN`).
12
+ * - Handles `CREATE TABLE [IF NOT EXISTS]`, `ALTER TABLE … ADD COLUMN`
13
+ * and `ALTER TABLE … DROP COLUMN`.
12
14
  * - Maps the common Postgres types we see in extension migrations to TS.
13
15
  * - Ignores constraint-only ALTER TABLE statements (PRIMARY KEY, FK).
14
16
  * - Ignores CREATE INDEX, CREATE TYPE, CREATE FUNCTION, etc.
@@ -57,4 +59,26 @@ export interface CodegenOptions {
57
59
  * `<extension>/.zveltio/db.d.ts`).
58
60
  */
59
61
  export declare function emitTypeScript(schema: ParsedSchema, opts?: CodegenOptions): string;
62
+ /**
63
+ * TypeScript input type of each core field type. The engine registers the same
64
+ * types in `field-types/index.ts`; a unit test there keeps the two equal.
65
+ */
66
+ export declare const CORE_FIELD_TS_TYPES: Readonly<Record<string, string>>;
67
+ export interface CollectionShape {
68
+ name: string;
69
+ fields: {
70
+ name: string;
71
+ type: string;
72
+ required?: boolean;
73
+ }[];
74
+ }
75
+ /** A type `tsTypeOf` does not know is `any`. */
76
+ export declare function emitCollectionTypes(collection: CollectionShape, tsTypeOf?: (type: string) => string | undefined): string;
77
+ /** The whole `zveltio.d.ts`. */
78
+ export declare function emitCollectionTypesFile(collections: CollectionShape[], tsTypeOf?: (type: string) => string | undefined): string;
79
+ /**
80
+ * The collections of a schema directory, as `{ path: content }` (the shape
81
+ * `zveltio schema pull` writes), in name order.
82
+ */
83
+ export declare function collectionsFromSchemaFiles(files: Record<string, string>): CollectionShape[];
60
84
  //# sourceMappingURL=schema-codegen.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"schema-codegen.d.ts","sourceRoot":"","sources":["../src/schema-codegen.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;GAkBG;AAEH,MAAM,WAAW,MAAM;IACrB,IAAI,EAAE,MAAM,CAAC;IACb,mFAAmF;IACnF,MAAM,EAAE,MAAM,CAAC;IACf,qEAAqE;IACrE,MAAM,EAAE,MAAM,CAAC;IACf,QAAQ,EAAE,OAAO,CAAC;CACnB;AAED,MAAM,WAAW,KAAK;IACpB,IAAI,EAAE,MAAM,CAAC;IACb,OAAO,EAAE,MAAM,EAAE,CAAC;CACnB;AAED,MAAM,WAAW,YAAY;IAC3B,MAAM,EAAE,KAAK,EAAE,CAAC;CACjB;AAsMD;;;;GAIG;AACH,wBAAgB,eAAe,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,EAAE,CA+BtD;AA6BD;;;;;GAKG;AACH,wBAAgB,WAAW,CAAC,SAAS,EAAE,MAAM,EAAE,GAAG,YAAY,CA+C7D;AAID,MAAM,WAAW,cAAc;IAC7B,6DAA6D;IAC7D,aAAa,CAAC,EAAE,MAAM,CAAC;IACvB,0EAA0E;IAC1E,MAAM,CAAC,EAAE,MAAM,CAAC;CACjB;AAED;;;;GAIG;AACH,wBAAgB,cAAc,CAAC,MAAM,EAAE,YAAY,EAAE,IAAI,GAAE,cAAmB,GAAG,MAAM,CA0BtF"}
1
+ {"version":3,"file":"schema-codegen.d.ts","sourceRoot":"","sources":["../src/schema-codegen.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;GAoBG;AAEH,M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