@byearlybird/starling 0.11.1 → 0.13.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.
@@ -1,199 +0,0 @@
1
- import { a as AnyObject, s as JsonDocument } from "./index-D7bXWDg6.js";
2
-
3
- //#region src/database/standard-schema.d.ts
4
- /** The Standard Schema interface. */
5
- interface StandardSchemaV1<Input = unknown, Output = Input> {
6
- /** The Standard Schema properties. */
7
- readonly "~standard": StandardSchemaV1.Props<Input, Output>;
8
- }
9
- declare namespace StandardSchemaV1 {
10
- /** The Standard Schema properties interface. */
11
- interface Props<Input = unknown, Output = Input> {
12
- /** The version number of the standard. */
13
- readonly version: 1;
14
- /** The vendor name of the schema library. */
15
- readonly vendor: string;
16
- /** Validates unknown input values. */
17
- readonly validate: (value: unknown) => Result<Output> | Promise<Result<Output>>;
18
- /** Inferred types associated with the schema. */
19
- readonly types?: Types<Input, Output> | undefined;
20
- }
21
- /** The result interface of the validate function. */
22
- type Result<Output> = SuccessResult<Output> | FailureResult;
23
- /** The result interface if validation succeeds. */
24
- interface SuccessResult<Output> {
25
- /** The typed output value. */
26
- readonly value: Output;
27
- /** The non-existent issues. */
28
- readonly issues?: undefined;
29
- }
30
- /** The result interface if validation fails. */
31
- interface FailureResult {
32
- /** The issues of failed validation. */
33
- readonly issues: ReadonlyArray<Issue>;
34
- }
35
- /** The issue interface of the failure output. */
36
- interface Issue {
37
- /** The error message of the issue. */
38
- readonly message: string;
39
- /** The path of the issue, if any. */
40
- readonly path?: ReadonlyArray<PropertyKey | PathSegment> | undefined;
41
- }
42
- /** The path segment interface of the issue. */
43
- interface PathSegment {
44
- /** The key representing a path segment. */
45
- readonly key: PropertyKey;
46
- }
47
- /** The Standard Schema types interface. */
48
- interface Types<Input = unknown, Output = Input> {
49
- /** The input type of the schema. */
50
- readonly input: Input;
51
- /** The output type of the schema. */
52
- readonly output: Output;
53
- }
54
- /** Infers the input type of a Standard Schema. */
55
- type InferInput<Schema extends StandardSchemaV1> = NonNullable<Schema["~standard"]["types"]>["input"];
56
- /** Infers the output type of a Standard Schema. */
57
- type InferOutput<Schema extends StandardSchemaV1> = NonNullable<Schema["~standard"]["types"]>["output"];
58
- }
59
- //#endregion
60
- //#region src/database/types.d.ts
61
- type AnyObjectSchema<T extends AnyObject = AnyObject> = StandardSchemaV1<T>;
62
- type SchemasMap = Record<string, AnyObjectSchema>;
63
- //#endregion
64
- //#region src/database/collection.d.ts
65
- /**
66
- * Symbols for internal collection methods used by transactions.
67
- * These are not part of the public Collection type.
68
- */
69
- declare const CollectionInternals: {
70
- readonly getPendingMutations: symbol;
71
- readonly emitMutations: symbol;
72
- readonly replaceData: symbol;
73
- readonly data: symbol;
74
- };
75
- /** Shorthand for extracting the data type from a schema */
76
- type InferData<T extends AnyObjectSchema> = StandardSchemaV1.InferOutput<T>;
77
- type MutationBatch<T> = {
78
- added: Array<{
79
- id: string;
80
- item: T;
81
- }>;
82
- updated: Array<{
83
- id: string;
84
- before: T;
85
- after: T;
86
- }>;
87
- removed: Array<{
88
- id: string;
89
- item: T;
90
- }>;
91
- };
92
- type CollectionMutationEvent<T> = MutationBatch<T>;
93
- type Collection<T extends AnyObjectSchema> = {
94
- get(id: string, opts?: {
95
- includeDeleted?: boolean;
96
- }): InferData<T> | null;
97
- getAll(opts?: {
98
- includeDeleted?: boolean;
99
- }): InferData<T>[];
100
- find<U = InferData<T>>(filter: (item: InferData<T>) => boolean, opts?: {
101
- map?: (item: InferData<T>) => U;
102
- sort?: (a: U, b: U) => number;
103
- }): U[];
104
- add(item: StandardSchemaV1.InferInput<T>): InferData<T>;
105
- update(id: string, updates: Partial<StandardSchemaV1.InferInput<T>>): void;
106
- remove(id: string): void;
107
- merge(document: JsonDocument<InferData<T>>): void;
108
- toDocument(): JsonDocument<InferData<T>>;
109
- on(event: "mutation", handler: (payload: CollectionMutationEvent<InferData<T>>) => void): () => void;
110
- };
111
- declare class IdNotFoundError extends Error {
112
- constructor(id: string);
113
- }
114
- declare class DuplicateIdError extends Error {
115
- constructor(id: string);
116
- }
117
- //#endregion
118
- //#region src/database/query.d.ts
119
- /** Read-only collection handle for queries */
120
- type QueryCollectionHandle<T extends AnyObjectSchema> = Pick<Collection<T>, "get" | "getAll" | "find">;
121
- /** Query context with read-only collection handles */
122
- type QueryContext<Schemas extends SchemasMap> = { [K in keyof Schemas]: QueryCollectionHandle<Schemas[K]> };
123
- /** Handle returned by db.query() for managing the reactive query */
124
- type QueryHandle<R> = {
125
- /** Current query result */
126
- readonly result: R;
127
- /** Subscribe to result changes. Returns unsubscribe function. */
128
- subscribe(callback: (result: R) => void): () => void;
129
- /** Stop tracking and clean up subscriptions */
130
- dispose(): void;
131
- };
132
- //#endregion
133
- //#region src/database/transaction.d.ts
134
- /** Transaction-safe collection handle that excludes event subscription and serialization */
135
- type TransactionCollectionHandle<T extends AnyObjectSchema> = Omit<Collection<T>, "on" | "toDocument">;
136
- type TransactionCollectionHandles<Schemas extends SchemasMap> = { [K in keyof Schemas]: TransactionCollectionHandle<Schemas[K]> };
137
- type TransactionContext<Schemas extends SchemasMap> = TransactionCollectionHandles<Schemas> & {
138
- rollback(): void;
139
- };
140
- //#endregion
141
- //#region src/database/db.d.ts
142
- type Collections<Schemas extends SchemasMap> = { [K in keyof Schemas]: Collection<Schemas[K]> };
143
- type CollectionConfigMap<Schemas extends SchemasMap> = { [K in keyof Schemas]: CollectionConfig<Schemas[K]> };
144
- type MutationEnvelope<Schemas extends SchemasMap> = { [K in keyof Schemas]: {
145
- collection: K;
146
- } & MutationBatch<StandardSchemaV1.InferOutput<Schemas[K]>> }[keyof Schemas];
147
- type DatabaseMutationEvent<Schemas extends SchemasMap> = MutationEnvelope<Schemas>;
148
- type CollectionConfig<T extends AnyObjectSchema> = {
149
- schema: T;
150
- getId: (item: StandardSchemaV1.InferOutput<T>) => string;
151
- };
152
- type DatabasePlugin<Schemas extends SchemasMap> = {
153
- handlers: {
154
- init?: (db: Database<Schemas>) => Promise<unknown> | unknown;
155
- dispose?: (db: Database<Schemas>) => Promise<unknown> | unknown;
156
- };
157
- };
158
- type DbConfig<Schemas extends SchemasMap> = {
159
- name: string;
160
- schema: CollectionConfigMap<Schemas>;
161
- version?: number;
162
- };
163
- type Database<Schemas extends SchemasMap> = Collections<Schemas> & {
164
- name: string;
165
- version: number;
166
- begin<R>(callback: (tx: TransactionContext<Schemas>) => R): R;
167
- query<R>(callback: (ctx: QueryContext<Schemas>) => R): QueryHandle<R>;
168
- toDocuments(): { [K in keyof Schemas]: JsonDocument<StandardSchemaV1.InferOutput<Schemas[K]>> };
169
- on(event: "mutation", handler: (payload: DatabaseMutationEvent<Schemas>) => unknown): () => void;
170
- use(plugin: DatabasePlugin<Schemas>): Database<Schemas>;
171
- init(): Promise<Database<Schemas>>;
172
- dispose(): Promise<void>;
173
- collectionKeys(): (keyof Schemas)[];
174
- };
175
- /**
176
- * Create a typed database instance with collection access.
177
- * @param config - Database configuration
178
- * @param config.name - Database name used for persistence and routing
179
- * @param config.schema - Collection schema definitions
180
- * @param config.version - Optional database version, defaults to 1
181
- * @returns A database instance with typed collection properties
182
- *
183
- * @example
184
- * ```typescript
185
- * const db = await createDatabase({
186
- * name: "my-app",
187
- * schema: {
188
- * tasks: { schema: taskSchema, getId: (task) => task.id },
189
- * },
190
- * })
191
- * .use(idbPlugin())
192
- * .init();
193
- *
194
- * const task = db.tasks.add({ title: 'Learn Starling' });
195
- * ```
196
- */
197
- declare function createDatabase<Schemas extends SchemasMap>(config: DbConfig<Schemas>): Database<Schemas>;
198
- //#endregion
199
- export { StandardSchemaV1 as _, createDatabase as a, QueryCollectionHandle as c, Collection as d, CollectionInternals as f, SchemasMap as g, AnyObjectSchema as h, DbConfig as i, QueryContext as l, IdNotFoundError as m, Database as n, TransactionCollectionHandle as o, DuplicateIdError as p, DatabasePlugin as r, TransactionContext as s, CollectionConfig as t, QueryHandle as u };
@@ -1,270 +0,0 @@
1
- //#region src/core/clock/clock.d.ts
2
- /**
3
- * A Hybrid Logical Clock that generates monotonically increasing eventstamps.
4
- * Combines wall-clock time with a counter for handling clock stalls and a
5
- * random nonce for tie-breaking.
6
- *
7
- * The clock automatically increments the counter when the wall clock doesn't
8
- * advance, ensuring eventstamps are always unique and monotonic.
9
- *
10
- * @example
11
- * ```typescript
12
- * const clock = createClock();
13
- * const stamp1 = clock.now();
14
- * const stamp2 = clock.now();
15
- * ```
16
- */
17
- type Clock = ReturnType<typeof createClock>;
18
- /**
19
- * Create a new Clock instance.
20
- * @param initialState - Optional initial state for the clock
21
- */
22
- declare function createClock(initialState?: {
23
- counter: number;
24
- lastMs: number;
25
- lastNonce: string;
26
- }): {
27
- now: () => string;
28
- latest: () => string;
29
- forward: (eventstamp: string) => void;
30
- };
31
- /**
32
- * Create a Clock from an eventstamp string.
33
- * @param eventstamp - Eventstamp string to decode and initialize clock from
34
- * @throws Error if eventstamp is invalid
35
- */
36
- declare function createClockFromEventstamp(eventstamp: string): Clock;
37
- //#endregion
38
- //#region src/core/clock/errors.d.ts
39
- declare class InvalidEventstampError extends Error {
40
- constructor(eventstamp: string);
41
- }
42
- //#endregion
43
- //#region src/core/clock/eventstamp.d.ts
44
- /**
45
- * Validates whether a string is a properly formatted eventstamp.
46
- * Expected format: YYYY-MM-DDTHH:mm:ss.SSSZ|HHHH+|HHHH
47
- * where HHHH+ represents 4 or more hex characters for the counter,
48
- * and HHHH represents exactly 4 hex characters for the nonce.
49
- */
50
- declare function isValidEventstamp(stamp: string): boolean;
51
- declare const MIN_EVENTSTAMP: string;
52
- /**
53
- * Find the maximum eventstamp from an array of eventstamps.
54
- * Returns MIN_EVENTSTAMP if the array is empty.
55
- * @param eventstamps - Array of eventstamp strings
56
- * @returns The maximum eventstamp
57
- */
58
- declare function maxEventstamp(eventstamps: string[]): string;
59
- //#endregion
60
- //#region src/core/document/resource.d.ts
61
- /**
62
- * Resource object structure representing a single stored entity.
63
- * Resources are the primary unit of storage and synchronization in Starling.
64
- *
65
- * Each resource has a type, unique identifier, attributes containing the data,
66
- * and metadata for tracking deletion state and eventstamps.
67
- */
68
- type ResourceObject<T extends AnyObject> = {
69
- /** Resource type identifier */
70
- type: string;
71
- /** Unique identifier for this resource */
72
- id: string;
73
- /** The resource's data as a nested object structure */
74
- attributes: T;
75
- /** Metadata for tracking deletion and eventstamps */
76
- meta: {
77
- /** Flat map of dot-separated paths to eventstamps (e.g., "user.address.street": "2025-11-18...") */
78
- eventstamps: Record<string, string>;
79
- /** The greatest eventstamp in this resource (including deletedAt if applicable) */
80
- latest: string;
81
- /** Eventstamp when this resource was soft-deleted, or null if not deleted */
82
- deletedAt: string | null;
83
- };
84
- };
85
- declare function makeResource<T extends AnyObject>(type: string, id: string, obj: T, eventstamp: string, deletedAt?: string | null): ResourceObject<T>;
86
- declare function mergeResources<T extends AnyObject>(into: ResourceObject<T>, from: ResourceObject<T>): ResourceObject<T>;
87
- declare function deleteResource<T extends AnyObject>(resource: ResourceObject<T>, eventstamp: string): ResourceObject<T>;
88
- //#endregion
89
- //#region src/core/document/document.d.ts
90
- /**
91
- * Base constraint for all document data in Starling.
92
- * Documents must be plain JavaScript objects with string keys.
93
- */
94
- type AnyObject = Record<string, unknown>;
95
- /**
96
- * A JSON:API document represents the complete state of a store:
97
- * - API version information
98
- * - Metadata including the highest eventstamp observed across all operations
99
- * - A set of resource objects (including soft-deleted ones)
100
- *
101
- * Documents are the unit of synchronization between store replicas.
102
- */
103
- type JsonDocument<T extends AnyObject> = {
104
- /** API version information */
105
- jsonapi: {
106
- version: "1.1";
107
- };
108
- /** Document-level metadata */
109
- meta: {
110
- /** Latest eventstamp observed by this document for clock synchronization */
111
- latest: string;
112
- };
113
- /** Array of resource objects with eventstamps and metadata */
114
- data: ResourceObject<T>[];
115
- };
116
- /**
117
- * Change tracking information returned by mergeDocuments.
118
- * Categorizes resources by mutation type for hook notifications.
119
- */
120
- type DocumentChanges<T extends AnyObject> = {
121
- /** Resources that were newly added (didn't exist before or were previously deleted) */
122
- added: Map<string, ResourceObject<T>>;
123
- /** Resources that were modified (existed before and changed) */
124
- updated: Map<string, ResourceObject<T>>;
125
- /** Resources that were deleted (newly marked with deletedAt) */
126
- deleted: Set<string>;
127
- };
128
- /**
129
- * Result of merging two JSON:API documents.
130
- */
131
- type MergeDocumentsResult<T extends AnyObject> = {
132
- /** The merged document with updated resources and forwarded clock */
133
- document: JsonDocument<T>;
134
- /** Change tracking for plugin hook notifications */
135
- changes: DocumentChanges<T>;
136
- };
137
- /**
138
- * Merges two JSON:API documents using field-level Last-Write-Wins semantics.
139
- *
140
- * The merge operation:
141
- * 1. Forwards the clock to the newest eventstamp from either document
142
- * 2. Merges each resource pair using field-level LWW (via mergeResources)
143
- * 3. Tracks what changed for hook notifications (added/updated/deleted)
144
- *
145
- * Deletion is final: once a resource is deleted, updates to it are merged into
146
- * the resource's attributes but don't restore visibility. Only new resources or
147
- * transitions into the deleted state are tracked.
148
- *
149
- * @param into - The base document to merge into
150
- * @param from - The source document to merge from
151
- * @returns Merged document and categorized changes
152
- *
153
- * @example
154
- * ```typescript
155
- * const into = {
156
- * jsonapi: { version: "1.1" },
157
- * meta: { latest: "2025-01-01T00:00:00.000Z|0001|a1b2" },
158
- * data: [{ type: "items", id: "doc1", attributes: {...}, meta: { deletedAt: null, latest: "..." } }]
159
- * };
160
- *
161
- * const from = {
162
- * jsonapi: { version: "1.1" },
163
- * meta: { latest: "2025-01-01T00:05:00.000Z|0001|c3d4" },
164
- * data: [
165
- * { type: "items", id: "doc1", attributes: {...}, meta: { deletedAt: null, latest: "..." } }, // updated
166
- * { type: "items", id: "doc2", attributes: {...}, meta: { deletedAt: null, latest: "..." } } // new
167
- * ]
168
- * };
169
- *
170
- * const result = mergeDocuments(into, from);
171
- * // result.document.meta.latest === "2025-01-01T00:05:00.000Z|0001|c3d4"
172
- * // result.changes.added has "doc2"
173
- * // result.changes.updated has "doc1"
174
- * ```
175
- */
176
- declare function mergeDocuments<T extends AnyObject>(into: JsonDocument<T>, from: JsonDocument<T>): MergeDocumentsResult<T>;
177
- /**
178
- * Creates an empty JSON:API document with the given eventstamp.
179
- * Useful for initializing new stores or testing.
180
- *
181
- * @param eventstamp - Initial clock value for this document
182
- * @returns Empty document
183
- *
184
- * @example
185
- * ```typescript
186
- * const empty = makeDocument("2025-01-01T00:00:00.000Z|0000|0000");
187
- * ```
188
- */
189
- declare function makeDocument<T extends AnyObject>(eventstamp: string): JsonDocument<T>;
190
- //#endregion
191
- //#region src/core/document/utils.d.ts
192
- /**
193
- * Convert a JsonDocument's data array into a Map keyed by resource ID.
194
- * @param document - JsonDocument containing resource data
195
- * @returns Map of resource ID to ResourceObject
196
- */
197
- declare function documentToMap<T extends AnyObject>(document: JsonDocument<T>): Map<string, ResourceObject<T>>;
198
- /**
199
- * Convert a Map of resources into a JsonDocument.
200
- * @param resources - Map of resource ID to ResourceObject
201
- * @param fallbackEventstamp - Eventstamp to include when computing the max (optional)
202
- * @returns JsonDocument representation of the resources
203
- */
204
- declare function mapToDocument<T extends AnyObject>(resources: Map<string, ResourceObject<T>>, fallbackEventstamp?: string): JsonDocument<T>;
205
- //#endregion
206
- //#region src/core/resource-map/resource-map.d.ts
207
- /**
208
- * A ResourceMap container for storing and managing ResourceObjects.
209
- *
210
- * This factory function creates a ResourceMap with state-based replication
211
- * and automatic convergence via Last-Write-Wins conflict resolution.
212
- * It stores complete resource snapshots with encoded metadata, including deletion markers.
213
- *
214
- * ResourceMap does NOT filter based on deletion status—it stores and returns
215
- * all ResourceObjects including deleted ones. The Store class is responsible
216
- * for filtering what's visible to users.
217
- *
218
- * @example
219
- * ```typescript
220
- * const resourceMap = createMap("todos");
221
- * resourceMap.set("id1", { name: "Alice" });
222
- * const resource = resourceMap.get("id1"); // ResourceObject with metadata
223
- * ```
224
- */
225
- declare function createMap<T extends AnyObject>(resourceType: string, initialMap?: Map<string, ResourceObject<T>>, eventstamp?: string): {
226
- /**
227
- * Check if a resource exists by ID (regardless of deletion status).
228
- * @param id - Resource ID
229
- */
230
- has(id: string): boolean;
231
- /**
232
- * Get a resource by ID (regardless of deletion status).
233
- * @returns The raw resource with metadata (including deletedAt flag), or undefined if not found
234
- */
235
- get(id: string): ResourceObject<T> | undefined;
236
- /**
237
- * Iterate over all resources (including deleted) as [id, resource] tuples.
238
- */
239
- entries(): IterableIterator<readonly [string, ResourceObject<T>]>;
240
- /**
241
- * Set a resource using field-level Last-Write-Wins merge.
242
- * Creates a new resource if it doesn't exist, or merges with existing resource.
243
- * @param id - Resource ID (provided by caller, not generated)
244
- * @param object - Data to set (partial fields are merged, full objects replace)
245
- */
246
- set(id: string, object: Partial<T>): void;
247
- delete(id: string): void;
248
- /**
249
- * Clone the internal map of encoded resources.
250
- */
251
- cloneMap(): Map<string, ResourceObject<T>>;
252
- /**
253
- * Export the current state as a JsonDocument snapshot.
254
- */
255
- toDocument(): JsonDocument<T>;
256
- /**
257
- * Merge another document into this ResourceMap using field-level Last-Write-Wins.
258
- * @returns The merge result containing the merged document and tracked changes
259
- * @param document - JsonDocument from another replica or storage
260
- */
261
- merge(document: JsonDocument<T>): MergeDocumentsResult<T>;
262
- };
263
- /**
264
- * Create a ResourceMap from a JsonDocument snapshot.
265
- * @param type - Resource type identifier (defaults to "default")
266
- * @param document - JsonDocument containing resource data
267
- */
268
- declare function createMapFromDocument<U extends AnyObject>(type: string, document: JsonDocument<U>): ReturnType<typeof createMap<U>>;
269
- //#endregion
270
- export { maxEventstamp as _, AnyObject as a, createClock as b, MergeDocumentsResult as c, ResourceObject as d, deleteResource as f, isValidEventstamp as g, MIN_EVENTSTAMP as h, mapToDocument as i, makeDocument as l, mergeResources as m, createMapFromDocument as n, DocumentChanges as o, makeResource as p, documentToMap as r, JsonDocument as s, createMap as t, mergeDocuments as u, InvalidEventstampError as v, createClockFromEventstamp as x, Clock as y };
@@ -1,139 +0,0 @@
1
- import { a as AnyObject, s as JsonDocument } from "./index-D7bXWDg6.js";
2
- import { g as SchemasMap, r as DatabasePlugin } from "./db-DJ_6dO-K.js";
3
-
4
- //#region src/plugins/http/index.d.ts
5
-
6
- /**
7
- * Context provided to the onRequest hook
8
- */
9
- type RequestContext<T extends AnyObject = AnyObject> = {
10
- collection: string;
11
- operation: "GET" | "PATCH";
12
- url: string;
13
- document?: JsonDocument<T>;
14
- };
15
- /**
16
- * Result returned by the onRequest hook
17
- */
18
- type RequestHookResult<T extends AnyObject = AnyObject> = {
19
- skip: true;
20
- } | {
21
- headers?: Record<string, string>;
22
- document?: JsonDocument<T>;
23
- } | undefined;
24
- /**
25
- * Result returned by the onResponse hook
26
- */
27
- type ResponseHookResult<T extends AnyObject = AnyObject> = {
28
- document: JsonDocument<T>;
29
- } | {
30
- skip: true;
31
- } | undefined;
32
- /**
33
- * Configuration for the HTTP plugin
34
- */
35
- type HttpPluginConfig<_Schemas extends SchemasMap> = {
36
- /**
37
- * Base URL for the HTTP server (e.g., "https://api.example.com")
38
- */
39
- baseUrl: string;
40
- /**
41
- * Interval in milliseconds to poll for server updates
42
- * @default 5000
43
- */
44
- pollingInterval?: number;
45
- /**
46
- * Delay in milliseconds to debounce local mutations before pushing
47
- * @default 1000
48
- */
49
- debounceDelay?: number;
50
- /**
51
- * Hook called before each HTTP request
52
- * Return { skip: true } to abort the request
53
- * Return { headers } to add custom headers
54
- * Return { document } to transform the document (PATCH only)
55
- */
56
- onRequest?: <T extends AnyObject>(context: RequestContext<T>) => RequestHookResult<T>;
57
- /**
58
- * Hook called after each successful HTTP response
59
- * Return { skip: true } to skip merging the response
60
- * Return { document } to transform the document before merging
61
- */
62
- onResponse?: <T extends AnyObject>(context: {
63
- collection: string;
64
- document: JsonDocument<T>;
65
- }) => ResponseHookResult<T>;
66
- /**
67
- * Retry configuration for failed requests
68
- */
69
- retry?: {
70
- /**
71
- * Maximum number of retry attempts
72
- * @default 3
73
- */
74
- maxAttempts?: number;
75
- /**
76
- * Initial delay in milliseconds before first retry
77
- * @default 1000
78
- */
79
- initialDelay?: number;
80
- /**
81
- * Maximum delay in milliseconds between retries
82
- * @default 30000
83
- */
84
- maxDelay?: number;
85
- };
86
- };
87
- /**
88
- * Create an HTTP sync plugin for Starling databases.
89
- *
90
- * The plugin:
91
- * - Fetches all collections from the server on init (single attempt)
92
- * - Polls the server at regular intervals to fetch updates (with retry)
93
- * - Debounces local mutations and pushes them to the server (with retry)
94
- * - Supports request/response hooks for authentication, encryption, etc.
95
- *
96
- * @param config - HTTP plugin configuration
97
- * @returns A DatabasePlugin instance
98
- *
99
- * @example
100
- * ```typescript
101
- * const db = await createDatabase({
102
- * name: "my-app",
103
- * schema: {
104
- * tasks: { schema: taskSchema, getId: (task) => task.id },
105
- * },
106
- * })
107
- * .use(httpPlugin({
108
- * baseUrl: "https://api.example.com",
109
- * onRequest: () => ({
110
- * headers: { Authorization: `Bearer ${token}` }
111
- * })
112
- * }))
113
- * .init();
114
- * ```
115
- *
116
- * @example With encryption
117
- * ```typescript
118
- * const db = await createDatabase({
119
- * name: "my-app",
120
- * schema: {
121
- * tasks: { schema: taskSchema, getId: (task) => task.id },
122
- * },
123
- * })
124
- * .use(httpPlugin({
125
- * baseUrl: "https://api.example.com",
126
- * onRequest: ({ document }) => ({
127
- * headers: { Authorization: `Bearer ${token}` },
128
- * document: document ? encrypt(document) : undefined
129
- * }),
130
- * onResponse: ({ document }) => ({
131
- * document: decrypt(document)
132
- * })
133
- * }))
134
- * .init();
135
- * ```
136
- */
137
- declare function httpPlugin<Schemas extends SchemasMap>(config: HttpPluginConfig<Schemas>): DatabasePlugin<Schemas>;
138
- //#endregion
139
- export { HttpPluginConfig, RequestContext, RequestHookResult, ResponseHookResult, httpPlugin };