@abloatai/ablo 0.35.0 → 0.36.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (215) hide show
  1. package/CHANGELOG.md +713 -629
  2. package/README.md +56 -519
  3. package/bin/ablo.cjs +39 -0
  4. package/dist/BaseSyncedStore.d.ts +24 -4
  5. package/dist/BaseSyncedStore.js +53 -37
  6. package/dist/Database.d.ts +8 -20
  7. package/dist/Database.js +61 -59
  8. package/dist/InstanceCache.d.ts +6 -2
  9. package/dist/InstanceCache.js +18 -16
  10. package/dist/Model.d.ts +17 -7
  11. package/dist/Model.js +17 -7
  12. package/dist/ModelRegistry.d.ts +4 -0
  13. package/dist/ModelRegistry.js +17 -15
  14. package/dist/NetworkMonitor.d.ts +3 -1
  15. package/dist/NetworkMonitor.js +7 -5
  16. package/dist/SyncClient.d.ts +5 -15
  17. package/dist/SyncClient.js +60 -57
  18. package/dist/client/Ablo.js +30 -19
  19. package/dist/client/createInternalComponents.d.ts +4 -0
  20. package/dist/client/createInternalComponents.js +8 -2
  21. package/dist/client/createModelProxy.d.ts +21 -1
  22. package/dist/client/createModelProxy.js +123 -57
  23. package/dist/client/humans.d.ts +30 -9
  24. package/dist/client/humans.js +45 -19
  25. package/dist/client/reactiveEngine.d.ts +16 -11
  26. package/dist/client/reactiveEngine.js +113 -335
  27. package/dist/client/storeCluster.d.ts +47 -0
  28. package/dist/client/storeCluster.js +118 -0
  29. package/dist/client/storeLifecycle.d.ts +61 -0
  30. package/dist/client/storeLifecycle.js +231 -0
  31. package/dist/context.d.ts +13 -0
  32. package/dist/context.js +23 -0
  33. package/dist/core/index.d.ts +1 -1
  34. package/dist/docs/catalog.js +6 -3
  35. package/dist/index.d.ts +4 -2
  36. package/dist/index.js +4 -2
  37. package/dist/query/client.d.ts +3 -0
  38. package/dist/query/client.js +6 -5
  39. package/dist/react/AbloProvider.d.ts +13 -1
  40. package/dist/react/AbloProvider.js +5 -2
  41. package/dist/react/context.d.ts +2 -2
  42. package/dist/react/createAbloReact.d.ts +56 -0
  43. package/dist/react/createAbloReact.js +51 -0
  44. package/dist/react/index.d.ts +1 -0
  45. package/dist/react/index.js +3 -0
  46. package/dist/react/useAblo.d.ts +9 -2
  47. package/dist/react/useAblo.js +25 -7
  48. package/dist/schema/coordination.js +5 -1
  49. package/dist/schema/index.d.ts +1 -0
  50. package/dist/schema/index.js +4 -0
  51. package/dist/schema/select.js +3 -0
  52. package/dist/schema/serialize.js +3 -0
  53. package/dist/source/adapter.d.ts +7 -5
  54. package/dist/source/adapter.js +7 -5
  55. package/dist/source/index.d.ts +1 -1
  56. package/dist/source/index.js +1 -1
  57. package/dist/{core/storeContract.d.ts → storeContract.d.ts} +5 -5
  58. package/dist/{core → stores}/DatabaseManager.d.ts +3 -1
  59. package/dist/{core → stores}/DatabaseManager.js +13 -12
  60. package/dist/{core → stores}/StoreManager.d.ts +5 -3
  61. package/dist/{core → stores}/StoreManager.js +24 -22
  62. package/dist/stores/SyncActionStore.d.ts +3 -1
  63. package/dist/stores/SyncActionStore.js +9 -7
  64. package/dist/sync/BootstrapFetcher.d.ts +4 -0
  65. package/dist/sync/BootstrapFetcher.js +28 -26
  66. package/dist/sync/OnDemandLoader.d.ts +3 -0
  67. package/dist/sync/OnDemandLoader.js +1 -0
  68. package/dist/sync/bootstrapApply.d.ts +3 -0
  69. package/dist/sync/bootstrapApply.js +2 -2
  70. package/dist/sync/deltaPipeline.d.ts +13 -12
  71. package/dist/sync/deltaPipeline.js +21 -4
  72. package/dist/sync/groupChange.d.ts +3 -0
  73. package/dist/sync/groupChange.js +16 -14
  74. package/dist/sync/participants.d.ts +19 -2
  75. package/dist/sync/participants.js +3 -1
  76. package/dist/sync/schemas.d.ts +2 -1
  77. package/dist/sync/schemas.js +3 -3
  78. package/dist/syncLog/contract.d.ts +20 -0
  79. package/dist/syncLog/contract.js +19 -0
  80. package/dist/syncLog/index.d.ts +1 -0
  81. package/dist/syncLog/index.js +1 -0
  82. package/dist/transaction/auth/capability.d.ts +35 -0
  83. package/dist/transaction/auth/capability.js +25 -0
  84. package/dist/transaction/coordination/awaitClaimGrant.d.ts +7 -0
  85. package/dist/transaction/coordination/awaitClaimGrant.js +12 -0
  86. package/dist/transaction/coordination/claimHeartbeatLoop.d.ts +34 -0
  87. package/dist/transaction/coordination/claimHeartbeatLoop.js +20 -0
  88. package/dist/transaction/coordination/index.d.ts +4 -4
  89. package/dist/transaction/coordination/index.js +4 -3
  90. package/dist/transaction/coordination/locator.d.ts +23 -2
  91. package/dist/transaction/coordination/locator.js +22 -2
  92. package/dist/transaction/coordination/schema.d.ts +125 -62
  93. package/dist/transaction/coordination/schema.js +228 -64
  94. package/dist/transaction/coordination/targetConflict.js +32 -28
  95. package/dist/transaction/errorCodes.d.ts +2 -2
  96. package/dist/transaction/errorCodes.js +13 -9
  97. package/dist/transaction/plugin.d.ts +95 -2
  98. package/dist/transaction/plugin.js +21 -2
  99. package/dist/transaction/resources/httpResources.d.ts +57 -2
  100. package/dist/transaction/resources/modelOperations.d.ts +148 -40
  101. package/dist/transaction/resources/where.d.ts +16 -0
  102. package/dist/transaction/resources/where.js +45 -0
  103. package/dist/transaction/schema/field.d.ts +12 -18
  104. package/dist/transaction/schema/fieldRef.d.ts +38 -0
  105. package/dist/transaction/schema/fieldRef.js +11 -0
  106. package/dist/transaction/schema/openapi.d.ts +16 -15
  107. package/dist/transaction/schema/openapi.js +186 -25
  108. package/dist/transaction/schema/relation.d.ts +7 -2
  109. package/dist/transaction/schema/schema.d.ts +27 -0
  110. package/dist/transaction/schema/schema.js +20 -0
  111. package/dist/transaction/transactions/settlement/commitEnvelope.d.ts +1 -1
  112. package/dist/transaction/transactions/settlement/pendingWrite.d.ts +1 -1
  113. package/dist/transaction/transport/httpClient.d.ts +9 -1
  114. package/dist/transaction/transport/httpClient.js +1 -0
  115. package/dist/transaction/transport/httpTransport.js +156 -44
  116. package/dist/transaction/transport/wsTransport.d.ts +2 -4
  117. package/dist/transaction/transport/wsTransport.js +16 -10
  118. package/dist/transaction/types/streams.d.ts +10 -0
  119. package/dist/transaction/utils/duration.d.ts +25 -0
  120. package/dist/transaction/utils/duration.js +32 -0
  121. package/dist/transaction/wire/accountResponses.d.ts +69 -0
  122. package/dist/transaction/wire/accountResponses.js +36 -1
  123. package/dist/transaction/wire/auth.d.ts +9 -2
  124. package/dist/transaction/wire/auth.js +7 -1
  125. package/dist/transaction/wire/claims.d.ts +164 -97
  126. package/dist/transaction/wire/claims.js +126 -28
  127. package/dist/transaction/wire/commit.d.ts +1 -1
  128. package/dist/transaction/wire/feedEvent.d.ts +27 -0
  129. package/dist/transaction/wire/feedEvent.js +27 -1
  130. package/dist/transaction/wire/frames.d.ts +2 -2
  131. package/dist/transaction/wire/inboundFrames.d.ts +12 -2
  132. package/dist/transaction/wire/index.d.ts +10 -6
  133. package/dist/transaction/wire/index.js +12 -3
  134. package/dist/transaction/wire/modelMutations.d.ts +31 -0
  135. package/dist/transaction/wire/modelMutations.js +52 -0
  136. package/dist/transaction/wire/modelShape.d.ts +78 -0
  137. package/dist/transaction/wire/modelShape.js +74 -0
  138. package/dist/transactions/mutations/MutationQueue.d.ts +6 -0
  139. package/dist/transactions/mutations/MutationQueue.js +55 -45
  140. package/dist/transactions/mutations/commitPayload.d.ts +3 -2
  141. package/dist/transactions/mutations/commitPayload.js +5 -5
  142. package/dist/transactions/mutations/deltaConfirmation.d.ts +4 -0
  143. package/dist/transactions/mutations/deltaConfirmation.js +10 -8
  144. package/dist/transactions/mutations/replayValidation.d.ts +2 -1
  145. package/dist/transactions/mutations/replayValidation.js +3 -2
  146. package/dist/{core → views}/QueryView.d.ts +1 -1
  147. package/dist/{core → views}/QueryView.js +1 -1
  148. package/dist/{core → views}/ViewRegistry.d.ts +1 -1
  149. package/dist/{core/queryUtils.d.ts → views/incrementalView.d.ts} +6 -6
  150. package/dist/{core/queryUtils.js → views/incrementalView.js} +6 -6
  151. package/docs/agents.md +1 -1
  152. package/docs/api-keys.md +6 -6
  153. package/docs/api.md +5 -43
  154. package/docs/audit.md +4 -3
  155. package/docs/cli.md +11 -11
  156. package/docs/client-behavior.md +4 -4
  157. package/docs/concurrency-convention.md +28 -42
  158. package/docs/coordination.md +235 -83
  159. package/docs/data-sources.md +4 -4
  160. package/docs/debugging.md +34 -12
  161. package/docs/deployment.md +8 -8
  162. package/docs/examples/scoped-agent.md +3 -3
  163. package/docs/groups.md +57 -3
  164. package/docs/guarantees.md +37 -10
  165. package/docs/how-it-works.md +29 -5
  166. package/docs/idempotency.md +6 -6
  167. package/docs/identity.md +22 -23
  168. package/docs/index.md +8 -8
  169. package/docs/integration-guide.md +14 -3
  170. package/docs/mcp.md +7 -7
  171. package/docs/migration.md +34 -15
  172. package/docs/projects.md +1 -1
  173. package/docs/react.md +19 -8
  174. package/docs/sessions.md +1 -1
  175. package/docs/webhooks.md +9 -9
  176. package/llms.txt +4 -4
  177. package/package.json +13 -20
  178. package/dist/cli.cjs +0 -288600
  179. package/dist/testing/fixtures/bootstrap.d.ts +0 -49
  180. package/dist/testing/fixtures/bootstrap.js +0 -59
  181. package/dist/testing/fixtures/deltas.d.ts +0 -83
  182. package/dist/testing/fixtures/deltas.js +0 -136
  183. package/dist/testing/fixtures/httpResponses.d.ts +0 -70
  184. package/dist/testing/fixtures/httpResponses.js +0 -90
  185. package/dist/testing/fixtures/models.d.ts +0 -83
  186. package/dist/testing/fixtures/models.js +0 -272
  187. package/dist/testing/helpers/reactWrapper.d.ts +0 -69
  188. package/dist/testing/helpers/reactWrapper.js +0 -67
  189. package/dist/testing/helpers/syncEngineHarness.d.ts +0 -54
  190. package/dist/testing/helpers/syncEngineHarness.js +0 -73
  191. package/dist/testing/helpers/wait.d.ts +0 -30
  192. package/dist/testing/helpers/wait.js +0 -49
  193. package/dist/testing/index.d.ts +0 -23
  194. package/dist/testing/index.js +0 -33
  195. package/dist/testing/mocks/FakeDatabase.d.ts +0 -18
  196. package/dist/testing/mocks/FakeDatabase.js +0 -10
  197. package/dist/testing/mocks/MockMutationExecutor.d.ts +0 -87
  198. package/dist/testing/mocks/MockMutationExecutor.js +0 -186
  199. package/dist/testing/mocks/MockNetworkMonitor.d.ts +0 -20
  200. package/dist/testing/mocks/MockNetworkMonitor.js +0 -46
  201. package/dist/testing/mocks/MockSyncContext.d.ts +0 -51
  202. package/dist/testing/mocks/MockSyncContext.js +0 -72
  203. package/dist/testing/mocks/MockSyncStore.d.ts +0 -88
  204. package/dist/testing/mocks/MockSyncStore.js +0 -171
  205. package/dist/testing/mocks/MockWebSocket.d.ts +0 -71
  206. package/dist/testing/mocks/MockWebSocket.js +0 -118
  207. package/docs/interaction-model.md +0 -99
  208. /package/dist/{core → query}/QueryProcessor.d.ts +0 -0
  209. /package/dist/{core → query}/QueryProcessor.js +0 -0
  210. /package/dist/{core/storeContract.js → storeContract.js} +0 -0
  211. /package/dist/{core → stores}/openIDBWithTimeout.d.ts +0 -0
  212. /package/dist/{core → stores}/openIDBWithTimeout.js +0 -0
  213. /package/dist/{source → transaction}/footprint.d.ts +0 -0
  214. /package/dist/{source → transaction}/footprint.js +0 -0
  215. /package/dist/{core → views}/ViewRegistry.js +0 -0
@@ -1,18 +0,0 @@
1
- import type { Database } from '../../Database.js';
2
- /**
3
- * Overrides for {@link fakeDatabase}. Everything is typechecked against
4
- * Database's public surface except `getPersistedTransactions`, which widens to
5
- * `unknown[]`: persisted rows are untrusted input (the DurableWriteStore port
6
- * documents this), and restore-path tests feed deliberately corrupt rows.
7
- */
8
- export type FakeDatabaseOverrides = Omit<Partial<Database>, 'getPersistedTransactions'> & {
9
- getPersistedTransactions?: () => Promise<unknown[]>;
10
- };
11
- /**
12
- * A Database double that implements ONLY the given members — no real
13
- * prototype behind it, so a code path reaching for anything else fails
14
- * loudly instead of silently running real IndexedDB logic. The bare `as`
15
- * is a single narrowing assert (Database is assignable to the overrides
16
- * type), so every override stays typechecked against the real surface.
17
- */
18
- export declare function fakeDatabase(overrides: FakeDatabaseOverrides): Database;
@@ -1,10 +0,0 @@
1
- /**
2
- * A Database double that implements ONLY the given members — no real
3
- * prototype behind it, so a code path reaching for anything else fails
4
- * loudly instead of silently running real IndexedDB logic. The bare `as`
5
- * is a single narrowing assert (Database is assignable to the overrides
6
- * type), so every override stays typechecked against the real surface.
7
- */
8
- export function fakeDatabase(overrides) {
9
- return overrides;
10
- }
@@ -1,87 +0,0 @@
1
- /**
2
- * A test double for {@link MutationExecutor} that records every call instead
3
- * of writing to a database. Use it to assert what a component tried to commit
4
- * and to script the response — success, failure, or added latency — without a
5
- * live backend. Each successful commit hands back an incrementing `lastSyncId`,
6
- * so tests can drive the delta-confirmation flow that depends on those ids.
7
- */
8
- import type { MutationExecutor, MutationOperation, MutationOptions, CommitResult } from '../../interfaces/index.js';
9
- import type { StaleNotification } from '../../transaction/coordination/schema.js';
10
- export interface CapturedMutation {
11
- method: string;
12
- modelName?: string;
13
- modelId?: string;
14
- input?: Record<string, unknown>;
15
- operations?: MutationOperation[];
16
- options?: MutationOptions;
17
- clientMutationId?: string;
18
- timestamp: number;
19
- }
20
- export interface MockMutationExecutorOptions {
21
- /** The first `lastSyncId` to return. It increments by one after each commit. */
22
- initialSyncId?: number;
23
- /** Whether mutations succeed by default. Set this false to make every call reject. */
24
- shouldSucceed?: boolean;
25
- /** A delay applied before each call resolves, in milliseconds, to simulate a slow network. */
26
- latencyMs?: number;
27
- /** The settlement status each commit reports. Defaults to `'confirmed'`. */
28
- status?: CommitResult['status'];
29
- /** Optional server-issued source/WAL correlation returned with queued receipts. */
30
- correlationId?: string;
31
- /** Optional stale-context notifications returned with each commit. */
32
- notifications?: StaleNotification[];
33
- /** Optional zero-row target ids returned with each commit. */
34
- missingIds?: string[];
35
- }
36
- export declare class MockMutationExecutor implements MutationExecutor {
37
- /** Every captured call, in the order it was made. Assertions read from this list. */
38
- readonly calls: CapturedMutation[];
39
- /** Current sync ID — incremented on each successful commit */
40
- private _syncId;
41
- private _shouldSucceed;
42
- private _latencyMs;
43
- private _status;
44
- private _correlationId;
45
- private _notifications;
46
- private _missingIds;
47
- /** Per-method failure overrides: method name → error */
48
- private _failureOverrides;
49
- /** Per-method response overrides */
50
- private _responseOverrides;
51
- constructor(options?: MockMutationExecutorOptions);
52
- /** Returns the current sync id without advancing it. */
53
- get currentSyncId(): number;
54
- /** Sets the next sync id the executor will return. */
55
- setSyncId(id: number): void;
56
- /** Sets the settlement status returned by subsequent commit calls. */
57
- setStatus(status: CommitResult['status']): void;
58
- /** Sets the opaque source/WAL correlation returned by subsequent commits. */
59
- setCorrelationId(correlationId: string | undefined): void;
60
- /** Sets stale-context notifications returned by subsequent commit calls. */
61
- setNotifications(notifications: StaleNotification[] | undefined): void;
62
- /** Sets zero-row target ids returned by subsequent commit calls. */
63
- setMissingIds(missingIds: string[] | undefined): void;
64
- /** Makes every mutation reject. Pass an error to control what is thrown. */
65
- failAll(error?: Error): void;
66
- /** Restores the default where mutations succeed, clearing any failure overrides. */
67
- succeedAll(): void;
68
- /** Makes a single named method reject. Pass an error to control what is thrown. */
69
- failMethod(method: string, error?: Error): void;
70
- /** Removes the failure override for one method. */
71
- clearFailure(method: string): void;
72
- /** Returns the captured calls for one method, in order. */
73
- getCallsByMethod(method: string): CapturedMutation[];
74
- /** The most recent captured call, or undefined if none have been made. */
75
- get lastCall(): CapturedMutation | undefined;
76
- /** Clears captured calls and restores the initial options. */
77
- reset(options?: MockMutationExecutorOptions): void;
78
- commit(operations: MutationOperation[], options?: MutationOptions): Promise<CommitResult>;
79
- executeCreate(modelName: string, id: string, input: Record<string, unknown>, clientMutationId?: string): Promise<void>;
80
- executeUpdate(modelName: string, modelId: string, data: Record<string, unknown>, clientMutationId?: string): Promise<CommitResult | null>;
81
- executeDelete(modelName: string, modelId: string, clientMutationId?: string): Promise<void>;
82
- executeArchive(modelName: string, modelId: string, clientMutationId?: string): Promise<void>;
83
- executeUnarchive(modelName: string, modelId: string, clientMutationId?: string): Promise<void>;
84
- private _capture;
85
- private _maybeDelay;
86
- private _maybeThrow;
87
- }
@@ -1,186 +0,0 @@
1
- /**
2
- * A test double for {@link MutationExecutor} that records every call instead
3
- * of writing to a database. Use it to assert what a component tried to commit
4
- * and to script the response — success, failure, or added latency — without a
5
- * live backend. Each successful commit hands back an incrementing `lastSyncId`,
6
- * so tests can drive the delta-confirmation flow that depends on those ids.
7
- */
8
- import { AbloError } from '../../transaction/errors.js';
9
- export class MockMutationExecutor {
10
- /** Every captured call, in the order it was made. Assertions read from this list. */
11
- calls = [];
12
- /** Current sync ID — incremented on each successful commit */
13
- _syncId;
14
- _shouldSucceed;
15
- _latencyMs;
16
- _status;
17
- _correlationId;
18
- _notifications;
19
- _missingIds;
20
- /** Per-method failure overrides: method name → error */
21
- _failureOverrides = new Map();
22
- /** Per-method response overrides */
23
- _responseOverrides = new Map();
24
- constructor(options = {}) {
25
- this._syncId = options.initialSyncId ?? 1;
26
- this._shouldSucceed = options.shouldSucceed ?? true;
27
- this._latencyMs = options.latencyMs ?? 0;
28
- this._status = options.status ?? 'confirmed';
29
- this._correlationId = options.correlationId;
30
- this._notifications = options.notifications;
31
- this._missingIds = options.missingIds;
32
- }
33
- // ─────────────────────────────────────────────
34
- // Test control API
35
- // ─────────────────────────────────────────────
36
- /** Returns the current sync id without advancing it. */
37
- get currentSyncId() {
38
- return this._syncId;
39
- }
40
- /** Sets the next sync id the executor will return. */
41
- setSyncId(id) {
42
- this._syncId = id;
43
- }
44
- /** Sets the settlement status returned by subsequent commit calls. */
45
- setStatus(status) {
46
- this._status = status;
47
- }
48
- /** Sets the opaque source/WAL correlation returned by subsequent commits. */
49
- setCorrelationId(correlationId) {
50
- this._correlationId = correlationId;
51
- }
52
- /** Sets stale-context notifications returned by subsequent commit calls. */
53
- setNotifications(notifications) {
54
- this._notifications = notifications;
55
- }
56
- /** Sets zero-row target ids returned by subsequent commit calls. */
57
- setMissingIds(missingIds) {
58
- this._missingIds = missingIds;
59
- }
60
- /** Makes every mutation reject. Pass an error to control what is thrown. */
61
- failAll(error) {
62
- this._shouldSucceed = false;
63
- if (error) {
64
- this._failureOverrides.set('*', error);
65
- }
66
- }
67
- /** Restores the default where mutations succeed, clearing any failure overrides. */
68
- succeedAll() {
69
- this._shouldSucceed = true;
70
- this._failureOverrides.clear();
71
- }
72
- /** Makes a single named method reject. Pass an error to control what is thrown. */
73
- failMethod(method, error) {
74
- this._failureOverrides.set(method, error ?? new Error(`Mock ${method} failed`));
75
- }
76
- /** Removes the failure override for one method. */
77
- clearFailure(method) {
78
- this._failureOverrides.delete(method);
79
- }
80
- /** Returns the captured calls for one method, in order. */
81
- getCallsByMethod(method) {
82
- return this.calls.filter((c) => c.method === method);
83
- }
84
- /** The most recent captured call, or undefined if none have been made. */
85
- get lastCall() {
86
- return this.calls[this.calls.length - 1];
87
- }
88
- /** Clears captured calls and restores the initial options. */
89
- reset(options) {
90
- this.calls.length = 0;
91
- this._syncId = options?.initialSyncId ?? 1;
92
- this._shouldSucceed = options?.shouldSucceed ?? true;
93
- this._latencyMs = options?.latencyMs ?? 0;
94
- this._status = options?.status ?? 'confirmed';
95
- this._correlationId = options?.correlationId;
96
- this._notifications = options?.notifications;
97
- this._missingIds = options?.missingIds;
98
- this._failureOverrides.clear();
99
- this._responseOverrides.clear();
100
- }
101
- // ─────────────────────────────────────────────
102
- // MutationExecutor interface implementation
103
- // ─────────────────────────────────────────────
104
- async commit(operations, options) {
105
- this._capture('commit', { operations, options });
106
- await this._maybeDelay();
107
- this._maybeThrow('commit');
108
- const syncId = this._syncId++;
109
- if (this._status === 'queued') {
110
- if (!this._correlationId) {
111
- throw new Error('Mock queued commits require a correlationId');
112
- }
113
- return {
114
- lastSyncId: 0,
115
- status: 'queued',
116
- correlationId: this._correlationId,
117
- ...(this._notifications ? { notifications: this._notifications } : {}),
118
- ...(this._missingIds ? { missingIds: this._missingIds } : {}),
119
- };
120
- }
121
- return {
122
- lastSyncId: syncId,
123
- status: 'confirmed',
124
- ...(this._correlationId ? { correlationId: this._correlationId } : {}),
125
- ...(this._notifications ? { notifications: this._notifications } : {}),
126
- ...(this._missingIds ? { missingIds: this._missingIds } : {}),
127
- };
128
- }
129
- async executeCreate(modelName, id, input, clientMutationId) {
130
- this._capture('executeCreate', { modelName, modelId: id, input, clientMutationId });
131
- await this._maybeDelay();
132
- this._maybeThrow('executeCreate');
133
- }
134
- async executeUpdate(modelName, modelId, data, clientMutationId) {
135
- this._capture('executeUpdate', { modelName, modelId, input: data, clientMutationId });
136
- await this._maybeDelay();
137
- this._maybeThrow('executeUpdate');
138
- return { lastSyncId: this._syncId++, status: 'confirmed' };
139
- }
140
- async executeDelete(modelName, modelId, clientMutationId) {
141
- this._capture('executeDelete', { modelName, modelId, clientMutationId });
142
- await this._maybeDelay();
143
- this._maybeThrow('executeDelete');
144
- }
145
- async executeArchive(modelName, modelId, clientMutationId) {
146
- this._capture('executeArchive', { modelName, modelId, clientMutationId });
147
- await this._maybeDelay();
148
- this._maybeThrow('executeArchive');
149
- }
150
- async executeUnarchive(modelName, modelId, clientMutationId) {
151
- this._capture('executeUnarchive', { modelName, modelId, clientMutationId });
152
- await this._maybeDelay();
153
- this._maybeThrow('executeUnarchive');
154
- }
155
- // ─────────────────────────────────────────────
156
- // Internal helpers
157
- // ─────────────────────────────────────────────
158
- _capture(method, data) {
159
- this.calls.push({
160
- method,
161
- timestamp: Date.now(),
162
- ...data,
163
- });
164
- }
165
- async _maybeDelay() {
166
- if (this._latencyMs > 0) {
167
- await new Promise((r) => setTimeout(r, this._latencyMs));
168
- }
169
- }
170
- _maybeThrow(method) {
171
- // Check specific method override first
172
- const methodError = this._failureOverrides.get(method);
173
- if (methodError)
174
- throw methodError;
175
- // Check global override
176
- const globalError = this._failureOverrides.get('*');
177
- if (globalError)
178
- throw globalError;
179
- // Check global flag
180
- if (!this._shouldSucceed) {
181
- throw new AbloError(`Mock mutation failed: ${method}`, {
182
- code: 'mock_mutation_failed',
183
- });
184
- }
185
- }
186
- }
@@ -1,20 +0,0 @@
1
- /**
2
- * A test double for {@link OnlineStatusProvider} that lets tests flip the
3
- * connection between online and offline on demand. Alongside its own state, it
4
- * updates the global `navigator.onLine` flag so code that reads the browser
5
- * value directly sees the same status.
6
- */
7
- import type { OnlineStatusProvider } from '../../interfaces/index.js';
8
- export declare class MockNetworkMonitor implements OnlineStatusProvider {
9
- private _online;
10
- constructor(initialOnline?: boolean);
11
- isOnline(): boolean;
12
- /** Marks the connection online and sets `navigator.onLine` to true. */
13
- goOnline(): void;
14
- /** Marks the connection offline and sets `navigator.onLine` to false. */
15
- goOffline(): void;
16
- /** Flips between online and offline, returning the new online state. */
17
- toggle(): boolean;
18
- /** Returns the monitor to its online starting state. */
19
- reset(): void;
20
- }
@@ -1,46 +0,0 @@
1
- /**
2
- * A test double for {@link OnlineStatusProvider} that lets tests flip the
3
- * connection between online and offline on demand. Alongside its own state, it
4
- * updates the global `navigator.onLine` flag so code that reads the browser
5
- * value directly sees the same status.
6
- */
7
- export class MockNetworkMonitor {
8
- _online;
9
- constructor(initialOnline = true) {
10
- this._online = initialOnline;
11
- }
12
- isOnline() {
13
- return this._online;
14
- }
15
- /** Marks the connection online and sets `navigator.onLine` to true. */
16
- goOnline() {
17
- this._online = true;
18
- // Also update navigator.onLine for code that reads it directly
19
- Object.defineProperty(navigator, 'onLine', {
20
- writable: true,
21
- value: true,
22
- });
23
- }
24
- /** Marks the connection offline and sets `navigator.onLine` to false. */
25
- goOffline() {
26
- this._online = false;
27
- Object.defineProperty(navigator, 'onLine', {
28
- writable: true,
29
- value: false,
30
- });
31
- }
32
- /** Flips between online and offline, returning the new online state. */
33
- toggle() {
34
- if (this._online) {
35
- this.goOffline();
36
- }
37
- else {
38
- this.goOnline();
39
- }
40
- return this._online;
41
- }
42
- /** Returns the monitor to its online starting state. */
43
- reset() {
44
- this.goOnline();
45
- }
46
- }
@@ -1,51 +0,0 @@
1
- /**
2
- * Assembles a ready-to-use {@link RuntimeContext} for tests. The context
3
- * bundles every dependency the engine needs — logger, network monitor,
4
- * mutation executor, and configuration — so a test can start the engine
5
- * without a real backend. {@link createTestContext} is the entry point: it
6
- * wires the mocks, installs the context globally through {@link initRuntime},
7
- * and returns handles to each mock for assertions.
8
- */
9
- import type { RuntimeContext } from '../../RuntimeContext.js';
10
- import type { Logger, ObservabilityProvider, SessionErrorDetector, RuntimeConfig } from '../../interfaces/index.js';
11
- import { MockMutationExecutor } from './MockMutationExecutor.js';
12
- import { MockNetworkMonitor } from './MockNetworkMonitor.js';
13
- export interface TestContextOptions {
14
- /** Replaces the default no-op logger. */
15
- logger?: Logger;
16
- /** Replaces the default no-op observability provider. */
17
- observability?: ObservabilityProvider;
18
- /** Replaces the detector that decides whether an error means the session has expired. */
19
- sessionErrorDetector?: SessionErrorDetector;
20
- /** Options forwarded to the {@link MockMutationExecutor} that the context creates. */
21
- mutationExecutorOptions?: ConstructorParameters<typeof MockMutationExecutor>[0];
22
- /** A partial {@link RuntimeConfig} merged over the defaults. */
23
- config?: Partial<RuntimeConfig>;
24
- /** Starts the network monitor offline. Defaults to online. */
25
- startOffline?: boolean;
26
- }
27
- export interface TestContextResult {
28
- /** The assembled context that {@link createTestContext} installed globally. */
29
- context: RuntimeContext;
30
- /** Handles to the underlying mocks, so tests can drive them and assert on them. */
31
- mocks: {
32
- mutationExecutor: MockMutationExecutor;
33
- networkMonitor: MockNetworkMonitor;
34
- };
35
- /** Tears the test down by resetting the engine and the mocks. Call it when the test finishes. */
36
- cleanup: () => void;
37
- }
38
- /**
39
- * Builds a {@link RuntimeContext} with every mock pre-wired and installs it
40
- * globally through {@link initRuntime}, so code under test reaches the engine
41
- * the same way it would in production. Returns the context, the mock handles,
42
- * and a cleanup function to call when the test finishes.
43
- *
44
- * @example
45
- * ```ts
46
- * const { context, mocks, cleanup } = createTestContext();
47
- * // ... run tests using mocks.mutationExecutor, mocks.networkMonitor
48
- * cleanup();
49
- * ```
50
- */
51
- export declare function createTestContext(options?: TestContextOptions): TestContextResult;
@@ -1,72 +0,0 @@
1
- /**
2
- * Assembles a ready-to-use {@link RuntimeContext} for tests. The context
3
- * bundles every dependency the engine needs — logger, network monitor,
4
- * mutation executor, and configuration — so a test can start the engine
5
- * without a real backend. {@link createTestContext} is the entry point: it
6
- * wires the mocks, installs the context globally through {@link initRuntime},
7
- * and returns handles to each mock for assertions.
8
- */
9
- import { noopLogger, noopObservability, noopAnalytics, defaultSessionErrorDetector, emptyConfig, } from '../../RuntimeContext.js';
10
- import { initRuntime, resetRuntime } from '../../context.js';
11
- import { ModelRegistry, getActiveRegistry, setActiveRegistry, hasActiveRegistry, clearActiveRegistry, } from '../../ModelRegistry.js';
12
- import { registerTestModels } from '../fixtures/models.js';
13
- import { MockMutationExecutor } from './MockMutationExecutor.js';
14
- import { MockNetworkMonitor } from './MockNetworkMonitor.js';
15
- /**
16
- * Builds a {@link RuntimeContext} with every mock pre-wired and installs it
17
- * globally through {@link initRuntime}, so code under test reaches the engine
18
- * the same way it would in production. Returns the context, the mock handles,
19
- * and a cleanup function to call when the test finishes.
20
- *
21
- * @example
22
- * ```ts
23
- * const { context, mocks, cleanup } = createTestContext();
24
- * // ... run tests using mocks.mutationExecutor, mocks.networkMonitor
25
- * cleanup();
26
- * ```
27
- */
28
- export function createTestContext(options = {}) {
29
- const mutationExecutor = new MockMutationExecutor(options.mutationExecutorOptions);
30
- const networkMonitor = new MockNetworkMonitor(!options.startOffline);
31
- const config = {
32
- ...emptyConfig,
33
- ...options.config,
34
- // Merge maps/sets properly if overrides provided
35
- modelCreatePriority: options.config?.modelCreatePriority ?? emptyConfig.modelCreatePriority,
36
- };
37
- const context = {
38
- getModelMetadata: (name) => (hasActiveRegistry() ? getActiveRegistry().getMetadata(name) : undefined),
39
- logger: options.logger ?? noopLogger,
40
- observability: options.observability ?? noopObservability,
41
- analytics: noopAnalytics,
42
- sessionErrorDetector: options.sessionErrorDetector ?? defaultSessionErrorDetector,
43
- onlineStatus: networkMonitor,
44
- mutationExecutor,
45
- config,
46
- };
47
- initRuntime(context);
48
- // Bootstrap a default ModelRegistry with test models if none is active.
49
- // Tests that manage their own registry call setActiveRegistry before this.
50
- const bootstrappedRegistry = !hasActiveRegistry();
51
- if (bootstrappedRegistry) {
52
- const defaultRegistry = new ModelRegistry();
53
- setActiveRegistry(defaultRegistry);
54
- registerTestModels(defaultRegistry);
55
- }
56
- return {
57
- context,
58
- mocks: {
59
- mutationExecutor,
60
- networkMonitor,
61
- },
62
- cleanup: () => {
63
- resetRuntime();
64
- // Leave the active ModelRegistry in place on purpose. Async callbacks
65
- // from in-flight transactions can call Model.toJSON() after a test's
66
- // teardown has run; keeping the default registry available keeps those
67
- // late calls valid, and the next createTestContext simply reuses it.
68
- mutationExecutor.reset();
69
- networkMonitor.reset();
70
- },
71
- };
72
- }
@@ -1,88 +0,0 @@
1
- /**
2
- * An in-memory {@link SyncStoreContract} for tests. It lets you seed rows,
3
- * read and write them synchronously, and inspect every call the code under
4
- * test made — all without a real sync backend.
5
- */
6
- import type { Model } from '../../Model.js';
7
- import type { ModelScope } from '../../InstanceCache.js';
8
- import type { SyncStoreContract } from '../../react/context.js';
9
- interface QueryOptions<T extends Model> {
10
- predicate?: (model: T) => boolean;
11
- scope?: ModelScope;
12
- orderBy?: keyof T;
13
- order?: 'asc' | 'desc';
14
- limit?: number;
15
- offset?: number;
16
- }
17
- interface QueryResult<T extends Model> {
18
- data: T[];
19
- }
20
- type ModelCtor<T extends Model> = abstract new (...args: never[]) => T;
21
- /**
22
- * An in-memory implementation of {@link SyncStoreContract}. Seed rows with
23
- * {@link MockSyncStore.setModels}, then read and write through the contract
24
- * methods; every call is recorded on {@link MockSyncStore.calls} so tests can
25
- * assert on what happened.
26
- */
27
- export declare class MockSyncStore implements SyncStoreContract {
28
- private byClass;
29
- calls: {
30
- retrieve: {
31
- modelClass: ModelCtor<Model>;
32
- id: string;
33
- }[];
34
- query: {
35
- modelClass: ModelCtor<Model>;
36
- options?: QueryOptions<Model>;
37
- }[];
38
- save: Model[];
39
- delete: Model[];
40
- archive: Model[];
41
- unarchive: Model[];
42
- };
43
- /**
44
- * Seed the store with models of a specific class.
45
- *
46
- * @example
47
- * mockStore.setModels(Task, [task1, task2]);
48
- */
49
- setModels<T extends Model>(modelClass: ModelCtor<T>, models: T[]): void;
50
- /**
51
- * Adds or replaces a single model, keyed by its id.
52
- */
53
- addModel<T extends Model>(modelClass: ModelCtor<T>, model: T): void;
54
- /**
55
- * Remove a model by ID.
56
- */
57
- removeModel<T extends Model>(modelClass: ModelCtor<T>, id: string): void;
58
- /**
59
- * Clear all seeded data and call history.
60
- */
61
- reset(): void;
62
- retrieve<T extends Model>(modelClass: ModelCtor<T>, id: string): T | undefined;
63
- queryByClass<T extends Model>(modelClass: ModelCtor<T>, options?: QueryOptions<T>): QueryResult<T>;
64
- save(model: Model): Promise<void>;
65
- delete(model: Model): Promise<void>;
66
- archive(model: Model): Promise<void>;
67
- unarchive(model: Model): Promise<void>;
68
- isReady: boolean;
69
- isSyncing: boolean;
70
- isOffline: boolean;
71
- isReconnecting: boolean;
72
- isError: boolean;
73
- hasUnsyncedChanges: boolean;
74
- syncStatus: {
75
- state: "idle";
76
- progress: number;
77
- pendingChanges: number;
78
- isSessionError: boolean;
79
- };
80
- /** A minimal object pool backing the useEntity and useEntities hooks in tests. */
81
- pool: SyncStoreContract['pool'];
82
- }
83
- /**
84
- * Create a new MockSyncStore.
85
- * Shorthand for `new MockSyncStore()`.
86
- */
87
- export declare function createMockSyncStore(): MockSyncStore;
88
- export {};