js-bao 0.2.10 → 0.2.12

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 (67) hide show
  1. package/README.md +174 -0
  2. package/dist/BaseModel-5YQCROYE.js +17 -0
  3. package/dist/BaseModel-5YQCROYE.js.map +1 -0
  4. package/dist/BaseModel-FCNWDJBH.js +17 -0
  5. package/dist/BaseModel-FCNWDJBH.js.map +1 -0
  6. package/dist/BrowserDatabaseFactory-PXOTK2DQ.js +119 -0
  7. package/dist/BrowserDatabaseFactory-PXOTK2DQ.js.map +1 -0
  8. package/dist/BrowserDatabaseFactory-WD4VX2VZ.js +119 -0
  9. package/dist/BrowserDatabaseFactory-WD4VX2VZ.js.map +1 -0
  10. package/dist/IncludeResolver-RCKQGNPZ.js +385 -0
  11. package/dist/IncludeResolver-RCKQGNPZ.js.map +1 -0
  12. package/dist/IncludeResolver-WGSQDMS7.js +385 -0
  13. package/dist/IncludeResolver-WGSQDMS7.js.map +1 -0
  14. package/dist/NodeDatabaseFactory-J4Z36UF3.js +165 -0
  15. package/dist/NodeDatabaseFactory-J4Z36UF3.js.map +1 -0
  16. package/dist/NodeDatabaseFactory-QIEKAXBM.js +10 -0
  17. package/dist/NodeDatabaseFactory-QIEKAXBM.js.map +1 -0
  18. package/dist/NodeSqliteEngine-HJSAYE4E.js +383 -0
  19. package/dist/NodeSqliteEngine-HJSAYE4E.js.map +1 -0
  20. package/dist/NodeSqliteEngine-I5SLWLME.js +383 -0
  21. package/dist/NodeSqliteEngine-I5SLWLME.js.map +1 -0
  22. package/dist/browser.cjs +3779 -3370
  23. package/dist/browser.d.cts +18 -1
  24. package/dist/browser.d.ts +18 -1
  25. package/dist/browser.js +3750 -3341
  26. package/dist/chunk-3PZWHUZO.js +4153 -0
  27. package/dist/chunk-3PZWHUZO.js.map +1 -0
  28. package/dist/chunk-53MS4MN7.js +373 -0
  29. package/dist/chunk-53MS4MN7.js.map +1 -0
  30. package/dist/chunk-65G2P4GL.js +709 -0
  31. package/dist/chunk-65G2P4GL.js.map +1 -0
  32. package/dist/chunk-6UX3YSCW.js +4151 -0
  33. package/dist/chunk-6UX3YSCW.js.map +1 -0
  34. package/dist/chunk-DANSD6BE.js +709 -0
  35. package/dist/chunk-DANSD6BE.js.map +1 -0
  36. package/dist/chunk-DF3JEQXA.js +373 -0
  37. package/dist/chunk-DF3JEQXA.js.map +1 -0
  38. package/dist/chunk-GO3APTPX.js +61 -0
  39. package/dist/chunk-GO3APTPX.js.map +1 -0
  40. package/dist/chunk-ID4U6IQC.js +53 -0
  41. package/dist/chunk-ID4U6IQC.js.map +1 -0
  42. package/dist/chunk-RQVS3LVL.js +165 -0
  43. package/dist/chunk-RQVS3LVL.js.map +1 -0
  44. package/dist/client.cjs +837 -0
  45. package/dist/client.d.cts +1101 -0
  46. package/dist/client.d.ts +1101 -0
  47. package/dist/client.js +806 -0
  48. package/dist/cloudflare-do.cjs +3637 -0
  49. package/dist/cloudflare-do.d.cts +1366 -0
  50. package/dist/cloudflare-do.d.ts +1366 -0
  51. package/dist/cloudflare-do.js +3614 -0
  52. package/dist/cloudflare.cjs +1048 -0
  53. package/dist/cloudflare.d.cts +1381 -0
  54. package/dist/cloudflare.d.ts +1381 -0
  55. package/dist/cloudflare.js +1017 -0
  56. package/dist/codegen.cjs +259 -18
  57. package/dist/environment-TOTQICSE.js +17 -0
  58. package/dist/environment-TOTQICSE.js.map +1 -0
  59. package/dist/index.cjs +1906 -1493
  60. package/dist/index.d.cts +19 -2
  61. package/dist/index.d.ts +19 -2
  62. package/dist/index.js +1871 -1458
  63. package/dist/node.cjs +4779 -4366
  64. package/dist/node.d.cts +18 -1
  65. package/dist/node.d.ts +18 -1
  66. package/dist/node.js +4602 -4189
  67. package/package.json +41 -12
@@ -0,0 +1,1381 @@
1
+ import * as Y from 'yjs';
2
+
3
+ interface RefersToRelationshipConfig {
4
+ type: "refersTo";
5
+ model: string;
6
+ relatedIdField: string;
7
+ }
8
+ interface HasManyRelationshipConfig {
9
+ type: "hasMany";
10
+ model: string;
11
+ relatedIdField: string;
12
+ orderByField?: string;
13
+ orderDirection?: "ASC" | "DESC";
14
+ }
15
+ interface HasManyThroughRelationshipConfig {
16
+ type: "hasManyThrough";
17
+ model: string;
18
+ joinModel: string;
19
+ joinModelLocalField: string;
20
+ joinModelRelatedField: string;
21
+ joinModelOrderByField?: string;
22
+ joinModelOrderDirection?: "ASC" | "DESC";
23
+ }
24
+ type RelationshipConfig = RefersToRelationshipConfig | HasManyRelationshipConfig | HasManyThroughRelationshipConfig;
25
+
26
+ type FieldType = "string" | "number" | "boolean" | "date" | "id" | "stringset";
27
+ interface FieldOptions {
28
+ type: FieldType;
29
+ indexed?: boolean;
30
+ required?: boolean;
31
+ unique?: boolean;
32
+ default?: any | (() => any);
33
+ autoAssign?: boolean;
34
+ maxLength?: number;
35
+ maxCount?: number;
36
+ }
37
+ interface UniqueConstraintConfig {
38
+ name: string;
39
+ fields: string[];
40
+ }
41
+ interface ModelOptions {
42
+ name: string;
43
+ uniqueConstraints?: UniqueConstraintConfig[];
44
+ relationships?: Record<string, RelationshipConfig>;
45
+ }
46
+
47
+ interface ITransactionalDatabaseOperations {
48
+ insert(modelName: string, data: any): Promise<void>;
49
+ delete(modelName: string, id: string): Promise<void>;
50
+ query<T extends Record<string, any>>(sql: string, params?: any[]): Promise<T[]>;
51
+ }
52
+ /**
53
+ * Abstract class defining the interface for database engines.
54
+ * This allows for different database implementations (e.g., SQL.js, DuckDB) to be used interchangeably.
55
+ */
56
+ declare abstract class DatabaseEngine {
57
+ /**
58
+ * Ensures that the database engine is fully initialized and ready for use.
59
+ * For WASM-based engines, this might involve loading the WASM module.
60
+ */
61
+ abstract ensureReady(): Promise<void>;
62
+ /**
63
+ * Executes a SQL query against the database.
64
+ * @param sql The SQL query string.
65
+ * @param params Optional array of parameters for prepared statements.
66
+ * @returns A promise that resolves to an array of query results.
67
+ */
68
+ abstract query(sql: string, params?: any[]): Promise<any[]>;
69
+ /**
70
+ * Retrieves the last error message from the database engine, if any.
71
+ * @returns The last error message as a string, or undefined if no error occurred.
72
+ */
73
+ abstract getLastErrorMessage(): string | undefined;
74
+ /**
75
+ * Retrieves the schema for a given table.
76
+ * This is useful for understanding table structure, field types, etc.
77
+ * The exact return type might vary based on the database engine.
78
+ * @param tableName The name of the table.
79
+ * @returns A promise that resolves to the table schema information.
80
+ */
81
+ abstract getTableSchema(tableName: string): Promise<any>;
82
+ /**
83
+ * Destroys the database engine instance and releases any associated resources.
84
+ * This is crucial for cleanup, especially in testing environments or when the application is shutting down.
85
+ */
86
+ abstract destroy(): Promise<void>;
87
+ createTable(_modelName: string, _schema: Map<string, any>, // Assuming 'any' for field options for now, can be refined
88
+ _options: ModelOptions): Promise<void>;
89
+ createStringSetJunctionTable(_modelName: string, _fieldName: string): Promise<void>;
90
+ insertStringSetValues(_modelName: string, _fieldName: string, _recordId: string, _values: string[]): Promise<void>;
91
+ removeStringSetValues(_modelName: string, _fieldName: string, _recordId: string, _values: string[]): Promise<void>;
92
+ insert(_modelName: string, _data: any): Promise<void>;
93
+ delete(_modelName: string, _id: string): Promise<void>;
94
+ /**
95
+ * Deletes all records for a specific document from the given model table.
96
+ * This is used when disconnecting a document to remove all its data.
97
+ * @param modelName The name of the model/table
98
+ * @param docId The document ID to filter by
99
+ */
100
+ deleteByDocumentId(_modelName: string, _docId: string): Promise<void>;
101
+ getTableName(_modelName: string): string;
102
+ withTransaction<T>(_callback: (operations: ITransactionalDatabaseOperations) => Promise<T>): Promise<T>;
103
+ }
104
+
105
+ interface StringSetChangeTracker {
106
+ markStringSetChange(fieldName: string, operation: "add" | "remove" | "clear", value?: string): void;
107
+ }
108
+
109
+ type DocumentPermissionHint = "read" | "read-write";
110
+ interface SaveOptions$1 {
111
+ targetDocument?: string;
112
+ forceWrite?: boolean;
113
+ }
114
+
115
+ interface ComparisonOperators<T = any> {
116
+ $eq?: T;
117
+ $ne?: T;
118
+ $gt?: T;
119
+ $gte?: T;
120
+ $lt?: T;
121
+ $lte?: T;
122
+ $in?: T[];
123
+ $nin?: T[];
124
+ }
125
+ interface StringSetOperators {
126
+ /**
127
+ * Exact membership: StringSet contains this specific string
128
+ */
129
+ $contains?: string;
130
+ $all?: string[];
131
+ $size?: number | ComparisonOperators<number>;
132
+ }
133
+ interface SubstringOperators {
134
+ /** Prefix match */
135
+ $startsWith?: string;
136
+ /** Suffix match */
137
+ $endsWith?: string;
138
+ /** Substring anywhere */
139
+ $containsText?: string;
140
+ }
141
+ interface ExistenceOperators {
142
+ $exists?: boolean;
143
+ }
144
+ type FieldOperators<T = any> = ComparisonOperators<T> & ExistenceOperators & StringSetOperators & SubstringOperators;
145
+ interface LogicalOperators {
146
+ $and?: DocumentFilter[];
147
+ $or?: DocumentFilter[];
148
+ }
149
+ type DocumentFilter = {
150
+ [field: string]: any | FieldOperators<any>;
151
+ } & LogicalOperators;
152
+ type SortDirection = 1 | -1;
153
+ type SortSpec = {
154
+ [field: string]: SortDirection;
155
+ };
156
+ type ProjectionSpec = {
157
+ [field: string]: 1 | 0;
158
+ };
159
+ interface IncludeSpec {
160
+ model: string;
161
+ type: "refersTo" | "hasMany" | "refersToMany";
162
+ sourceField?: string;
163
+ foreignKey?: string;
164
+ localField?: string;
165
+ as?: string;
166
+ projection?: ProjectionSpec;
167
+ limit?: number;
168
+ sort?: SortSpec;
169
+ filter?: DocumentFilter;
170
+ include?: IncludeSpec[];
171
+ }
172
+ interface QueryOptions {
173
+ sort?: SortSpec;
174
+ projection?: ProjectionSpec;
175
+ documents?: string | string[];
176
+ limit?: number;
177
+ uniqueStartKey?: string;
178
+ direction?: 1 | -1;
179
+ include?: IncludeSpec[];
180
+ }
181
+ interface PaginatedResult<T> {
182
+ data: T[];
183
+ nextCursor?: string;
184
+ prevCursor?: string;
185
+ hasMore: boolean;
186
+ }
187
+ interface TranslatedQuery {
188
+ sql: string;
189
+ params: any[];
190
+ sortFields: string[];
191
+ sortDirections?: (1 | -1)[];
192
+ }
193
+ type ProjectedResult<T, P extends ProjectionSpec> = {
194
+ [K in keyof P]: K extends keyof T ? T[K] : never;
195
+ };
196
+ type QueryResult<T, P extends ProjectionSpec | undefined> = P extends ProjectionSpec ? ProjectedResult<T, P> : T;
197
+
198
+ declare class DocumentQueryTranslator {
199
+ private modelName;
200
+ private schema;
201
+ private tableName;
202
+ private quotedTableName;
203
+ private fieldSqlCache;
204
+ constructor(modelName: string, schema: Map<string, FieldOptions>);
205
+ private getQuotedField;
206
+ /**
207
+ * Translate document filter and options to SQL for find operations
208
+ */
209
+ translateFind(filter: DocumentFilter, options?: QueryOptions): TranslatedQuery;
210
+ /**
211
+ * Translate document filter to SQL for count operations
212
+ */
213
+ translateCount(filter: DocumentFilter, options?: Pick<QueryOptions, "documents">): {
214
+ sql: string;
215
+ params: any[];
216
+ };
217
+ /**
218
+ * Translate document filter to SQL WHERE clause
219
+ */
220
+ translateFilter(filter: DocumentFilter): {
221
+ sql: string;
222
+ params: any[];
223
+ };
224
+ /**
225
+ * Translate logical operators ($and, $or)
226
+ */
227
+ private translateLogicalOperator;
228
+ /**
229
+ * Translate field condition to SQL
230
+ */
231
+ private translateFieldCondition;
232
+ /**
233
+ * Translate field operators to SQL
234
+ */
235
+ private translateFieldOperators;
236
+ /**
237
+ * Translate individual operator to SQL
238
+ */
239
+ private translateOperator;
240
+ /**
241
+ * Build SELECT clause based on projection
242
+ */
243
+ private buildSelectClause;
244
+ /**
245
+ * Build LIMIT clause
246
+ */
247
+ private buildLimitClause;
248
+ /**
249
+ * Build pagination WHERE clause from cursor
250
+ */
251
+ private buildPaginationClause;
252
+ /**
253
+ * Validate that field exists in schema
254
+ */
255
+ private validateField;
256
+ /**
257
+ * Validate projection fields
258
+ */
259
+ private validateProjection;
260
+ /**
261
+ * Validate operator is supported for field type
262
+ */
263
+ private validateOperatorForType;
264
+ /**
265
+ * Validate field value matches expected type
266
+ */
267
+ private validateFieldValue;
268
+ /**
269
+ * Validate array values for $in/$nin operators
270
+ */
271
+ private validateArrayValues;
272
+ /**
273
+ * Check if value is a primitive (not an object with operators)
274
+ */
275
+ private isPrimitiveValue;
276
+ /**
277
+ * Get the type of a value for validation
278
+ */
279
+ private getValueType;
280
+ /**
281
+ * Check if value type is compatible with field type
282
+ */
283
+ private isTypeCompatible;
284
+ /**
285
+ * Convert value for SQLite compatibility
286
+ */
287
+ private convertValueForSQLite;
288
+ private normalizeDocumentIds;
289
+ private buildDocumentClause;
290
+ }
291
+
292
+ interface StringSetMembership$1 {
293
+ field: string;
294
+ contains: string;
295
+ }
296
+ type GroupByField$1 = string | StringSetMembership$1;
297
+ interface AggregationOperation$1 {
298
+ type: "count" | "sum" | "avg" | "min" | "max";
299
+ field?: string;
300
+ }
301
+ interface AggregationOptions$1 {
302
+ groupBy: GroupByField$1[];
303
+ operations: AggregationOperation$1[];
304
+ filter?: DocumentFilter;
305
+ limit?: number;
306
+ sort?: {
307
+ field: string;
308
+ direction: 1 | -1;
309
+ };
310
+ }
311
+ type AggregationResult$1 = Record<string, any> | Record<string, any>[];
312
+ interface AggregationAliasDebugInfo {
313
+ field: string;
314
+ contains: string;
315
+ originalAlias: string;
316
+ }
317
+ interface AggregationAliasDetail extends AggregationAliasDebugInfo {
318
+ alias: string;
319
+ membershipKey: string;
320
+ }
321
+ interface AggregationQueryPlan {
322
+ sql: string;
323
+ params: any[];
324
+ aliasMetadata?: AggregationAliasDetail[];
325
+ }
326
+ declare enum LogLevel {
327
+ SILENT = 0,
328
+ ERROR = 1,
329
+ WARN = 2,
330
+ INFO = 3,
331
+ DEBUG = 4,
332
+ VERBOSE = 5
333
+ }
334
+ declare class BaseModel implements StringSetChangeTracker {
335
+ static modelName?: string;
336
+ private static listenersMap;
337
+ private static modelNameToDefaultDocId;
338
+ private static globalDefaultDocId;
339
+ private static defaultDocChangedListeners;
340
+ private static modelDocMappingChangedListeners;
341
+ private static readonly DEFAULT_LEGACY_DOC_ID;
342
+ protected static dbInstance: DatabaseEngine | null;
343
+ protected static connectedDocuments: Map<string, {
344
+ yDoc: Y.Doc;
345
+ permissionHint: DocumentPermissionHint;
346
+ }>;
347
+ protected static documentYMaps: Map<string, Y.Map<any>>;
348
+ private _localChanges;
349
+ private _isDirty;
350
+ private _isLoadingFromYjs;
351
+ private _stringSetFields;
352
+ private _metaDocId;
353
+ private _metaPermissionHint;
354
+ /**
355
+ * Returns the document id this instance is associated with, or null if not resolved yet.
356
+ */
357
+ getDocumentId(): string | null;
358
+ id: string;
359
+ type: string;
360
+ static setLogLevel(level: LogLevel): void;
361
+ static getLogLevel(): LogLevel;
362
+ static setModelDefaultDocumentId(modelName: string, docId: string): void;
363
+ static removeModelDefaultDocumentId(modelName: string): void;
364
+ static clearModelDefaultDocumentIds(): void;
365
+ static setGlobalDefaultDocumentId(docId: string): void;
366
+ static clearGlobalDefaultDocumentId(): void;
367
+ static getModelDefaultDocumentMapping(): Record<string, string>;
368
+ static getDocumentIdForModel(modelName: string): string | undefined;
369
+ static getGlobalDefaultDocumentId(): string | undefined;
370
+ static onDefaultDocChanged(listener: (payload: {
371
+ previous?: string;
372
+ current?: string;
373
+ }) => void): () => void;
374
+ static onModelDocMappingChanged(listener: (payload: {
375
+ modelName: string;
376
+ previous?: string;
377
+ current?: string;
378
+ }) => void): () => void;
379
+ static _clearMappingsForDocId(docId: string): void;
380
+ private static attachFieldAccessorsSet;
381
+ static attachFieldAccessors(modelClass: typeof BaseModel, fields: Map<string, FieldOptions>): void;
382
+ constructor(data?: Partial<any>);
383
+ private ensureLocalChanges;
384
+ private hasLocalChange;
385
+ private getFromYjs;
386
+ private getValue;
387
+ private setValue;
388
+ get isDirty(): boolean;
389
+ get hasUnsavedChanges(): boolean;
390
+ private clearLocalChanges;
391
+ discardChanges(): void;
392
+ protected validateFieldValue(fieldKey: string, value: any): void;
393
+ protected validateBeforeSave(): void;
394
+ getChangedFields(): string[];
395
+ getOriginalValue(fieldKey: string): any;
396
+ getCurrentValue(fieldKey: string): any;
397
+ hasFieldChanged(fieldKey: string): boolean;
398
+ markStringSetChange(fieldName: string, operation: "add" | "remove" | "clear", value?: string): void;
399
+ private getStringSetCurrentValues;
400
+ private getStringSetFromYjs;
401
+ private getOrCreateStringSet;
402
+ static initialize(_yDoc: Y.Doc, _db: DatabaseEngine): Promise<void>;
403
+ static initializeForDocument(yDoc: Y.Doc, db: DatabaseEngine, docId: string, permissionHint: DocumentPermissionHint): Promise<void>;
404
+ static cleanupDocumentData(docId: string): Promise<void>;
405
+ static subscribe(callback: () => void): () => void;
406
+ protected static notifyListeners(): void;
407
+ /**
408
+ * Legacy migration method - no longer needed in the new multidoc architecture.
409
+ * Data migration is now handled during document initialization.
410
+ */
411
+ static migrateToNestedYMaps(): Promise<void>;
412
+ /**
413
+ * Utility to diff current instance data against YJS nested map data
414
+ * Returns object with added, modified, and removed fields
415
+ */
416
+ protected _diffWithYjsData(): {
417
+ added: Record<string, any>;
418
+ modified: Record<string, any>;
419
+ removed: string[];
420
+ };
421
+ /**
422
+ * Deep equality check for comparing field values
423
+ */
424
+ protected _deepEqual(a: any, b: any): boolean;
425
+ protected static _buildKeyFromValues(fields: string[], keyValues: any[], modelName: string, constraintName: string): string | null;
426
+ protected _buildUniqueKey(fields: string[], data: Record<string, any>, modelName: string, constraintName: string): string | null;
427
+ save(options?: SaveOptions$1): Promise<void>;
428
+ delete(): Promise<void>;
429
+ protected getCurrentJSState(): Record<string, any>;
430
+ protected toJSON(): Record<string, any>;
431
+ static find<T extends BaseModel>(this: new (...args: any[]) => T, id: string): Promise<T | null>;
432
+ /**
433
+ * Document-style query API - returns paginated results
434
+ */
435
+ static query<T extends BaseModel, P extends ProjectionSpec | undefined = undefined>(this: new (...args: any[]) => T, filter?: DocumentFilter, options?: QueryOptions & {
436
+ projection?: P;
437
+ }): Promise<PaginatedResult<QueryResult<T, P>>>;
438
+ /**
439
+ * Main aggregation API - performs grouping, faceting, and statistical operations
440
+ * @param options Aggregation configuration with groupBy, operations, filter, limit, and sort
441
+ * @returns Nested object structure with aggregation results
442
+ *
443
+ * @example
444
+ * // Simple facet count
445
+ * const tagCounts = await Model.aggregate({
446
+ * groupBy: ['tags'],
447
+ * operations: [{ type: 'count' }]
448
+ * });
449
+ * // Result: { red: 15, blue: 8, green: 12 }
450
+ *
451
+ * @example
452
+ * // Multi-dimensional grouping with multiple operations
453
+ * const categoryStats = await Model.aggregate({
454
+ * groupBy: ['category', 'status'],
455
+ * operations: [
456
+ * { type: 'count' },
457
+ * { type: 'sum', field: 'amount' },
458
+ * { type: 'avg', field: 'score' }
459
+ * ],
460
+ * filter: { active: true },
461
+ * sort: { field: 'count', direction: 'desc' },
462
+ * limit: 10
463
+ * });
464
+ *
465
+ * @example
466
+ * // StringSet membership grouping
467
+ * const urgentCounts = await Model.aggregate({
468
+ * groupBy: [{ field: 'tags', contains: 'urgent' }],
469
+ * operations: [{ type: 'count' }]
470
+ * });
471
+ * // Result: { true: 5, false: 23 }
472
+ */
473
+ static aggregate<T extends BaseModel>(this: new (...args: any[]) => T, options: AggregationOptions$1): Promise<AggregationResult$1>;
474
+ /**
475
+ * Build SQL query for structured aggregation
476
+ */
477
+ protected static buildAggregationQuery(options: AggregationOptions$1, schema: any, modelName: string): AggregationQueryPlan;
478
+ /**
479
+ * Get the proper database table name (should match database engine naming)
480
+ */
481
+ protected static getDatabaseTableName(modelName: string): string;
482
+ /**
483
+ * Get the proper database junction table name for StringSet fields
484
+ */
485
+ protected static getDatabaseJunctionTableName(modelName: string, fieldName: string): string;
486
+ private static buildMembershipKey;
487
+ /**
488
+ * Build query for StringSet facet counts
489
+ */
490
+ protected static buildStringSetFacetQuery(stringSetFields: string[], options: AggregationOptions$1, translator: DocumentQueryTranslator, modelName: string): AggregationQueryPlan;
491
+ /**
492
+ * Build query for regular field aggregation
493
+ */
494
+ protected static buildRegularAggregationQuery(regularGroupBy: string[], stringSetMemberships: StringSetMembership$1[], options: AggregationOptions$1, translator: DocumentQueryTranslator, modelName: string): AggregationQueryPlan;
495
+ /**
496
+ * Process aggregation results into nested structure
497
+ */
498
+ protected static processAggregationResults(results: any[], options: AggregationOptions$1, aliasMetadata?: AggregationAliasDetail[]): AggregationResult$1;
499
+ /**
500
+ * Document-style query API - returns single result or null
501
+ */
502
+ static queryOne<T extends BaseModel, P extends ProjectionSpec | undefined = undefined>(this: new (...args: any[]) => T, filter?: DocumentFilter, options?: Omit<QueryOptions, "limit" | "uniqueStartKey" | "direction"> & {
503
+ projection?: P;
504
+ }): Promise<QueryResult<T, P> | null>;
505
+ /**
506
+ * Document-style count API
507
+ */
508
+ static count(this: new (...args: any[]) => any, filter?: DocumentFilter, options?: Pick<QueryOptions, "documents">): Promise<number>;
509
+ static findAll<T extends BaseModel>(this: new (...args: any[]) => T): Promise<T[]>;
510
+ static findByUnique<T extends BaseModel>(this: typeof BaseModel & (new (...args: any[]) => T), constraintName: string, value: any | any[]): Promise<T | null>;
511
+ static upsertByUnique<T extends BaseModel>(this: typeof BaseModel & (new (...args: any[]) => T), constraintName: string, uniqueLookupValue: any | any[], dataToUpsert: Partial<Omit<InstanceType<new (...args: any[]) => T>, keyof BaseModel | "toJSON">> & {
512
+ id?: string;
513
+ }, options?: {
514
+ objectMustExist?: boolean;
515
+ objectMustNotExist?: boolean;
516
+ targetDocument?: string;
517
+ }): Promise<T>;
518
+ /**
519
+ * Execute a callback with automatic transaction handling for all modified models
520
+ */
521
+ static withTransaction<T>(callback: () => Promise<T> | T): Promise<T>;
522
+ /**
523
+ * Sets up deep observation on a nested YMap to sync field-level changes to the database
524
+ */
525
+ protected static setupNestedYMapObserver(recordId: string, recordYMap: Y.Map<any>): void;
526
+ /**
527
+ * Sets up deep observation on a nested YMap for a specific document to sync field-level changes to the database
528
+ */
529
+ protected static setupNestedYMapObserverForDocument(recordId: string, recordYMap: Y.Map<any>, docId: string, permissionHint: DocumentPermissionHint): void;
530
+ }
531
+
532
+ /**
533
+ * Durable Object Engine
534
+ *
535
+ * Database engine implementation that runs inside a Cloudflare Durable Object.
536
+ * Uses the DO's embedded SQLite database via ctx.storage.sql.
537
+ *
538
+ * Key characteristics:
539
+ * - Synchronous SQL execution (DO SQLite is sync)
540
+ * - No doc ID column needed (one DO = one document)
541
+ * - Uses JSON schema (records + stringset_index tables)
542
+ * - Schemaless: any model/field can be saved and queried without registration
543
+ * - Indexes are additive: register/drop individual field indexes independently
544
+ */
545
+
546
+ /** Row shape from the _indexes table */
547
+ interface IndexEntry {
548
+ model_name: string;
549
+ field_name: string;
550
+ field_type: string;
551
+ is_unique: number;
552
+ created_at: string;
553
+ }
554
+ /** Row shape from the _unique_constraints table */
555
+ interface UniqueConstraintEntry {
556
+ model_name: string;
557
+ constraint_name: string;
558
+ fields: string[];
559
+ created_at: string;
560
+ }
561
+ /** Row shape from the _model_fields table */
562
+ interface ModelFieldInfo {
563
+ model_name: string;
564
+ field_name: string;
565
+ inferred_type: string;
566
+ first_seen_at: string;
567
+ }
568
+
569
+ /**
570
+ * Aggregation types shared between Yjs and DO backends.
571
+ */
572
+
573
+ /**
574
+ * Describes a StringSet membership check in a groupBy clause.
575
+ * Groups records by whether they have a specific value in a StringSet field.
576
+ */
577
+ interface StringSetMembership {
578
+ field: string;
579
+ contains: string;
580
+ }
581
+ /**
582
+ * A groupBy field can be a plain field name or a StringSet membership check.
583
+ */
584
+ type GroupByField = string | StringSetMembership;
585
+ /**
586
+ * An aggregation operation (count, sum, avg, min, max).
587
+ */
588
+ interface AggregationOperation {
589
+ type: "count" | "sum" | "avg" | "min" | "max";
590
+ /** Required for sum, avg, min, max; not used for count */
591
+ field?: string;
592
+ }
593
+ /**
594
+ * Options for an aggregation query.
595
+ */
596
+ interface AggregationOptions {
597
+ groupBy: GroupByField[];
598
+ operations: AggregationOperation[];
599
+ filter?: DocumentFilter;
600
+ limit?: number;
601
+ sort?: {
602
+ /** Can be operation result field like 'count', 'sum_fieldName', etc. */
603
+ field: string;
604
+ /** 1 for ascending, -1 for descending */
605
+ direction: 1 | -1;
606
+ };
607
+ }
608
+ /**
609
+ * Result of an aggregation query — nested object keyed by group values.
610
+ */
611
+ type AggregationResult = Record<string, any> | Record<string, any>[];
612
+
613
+ /**
614
+ * Hook type definitions for Durable Object access control.
615
+ *
616
+ * Hooks run server-side inside the DO before CRUD operations.
617
+ * They can allow/deny operations and inject query filters.
618
+ */
619
+
620
+ /** Context passed to all hooks */
621
+ interface HookContext {
622
+ /** The model (type discriminator) being operated on */
623
+ modelName: string;
624
+ /** The document ID (derived from the DO instance) */
625
+ docId: string;
626
+ /** The raw request (for reading headers, auth tokens, etc.) */
627
+ request: Request;
628
+ /** The DO's SQLite engine (for direct queries, e.g. lookup functions) */
629
+ engine: any;
630
+ }
631
+ /** Context for beforeSave hooks */
632
+ interface BeforeSaveContext extends HookContext {
633
+ /** Record ID being saved */
634
+ id: string;
635
+ /** Data being saved */
636
+ data: Record<string, any>;
637
+ /** StringSet values being saved (if any) */
638
+ stringSets?: Record<string, string[]>;
639
+ /** Whether this is a new record (true) or an update (false) */
640
+ isNew: boolean;
641
+ }
642
+ /** Context for beforeDelete hooks */
643
+ interface BeforeDeleteContext extends HookContext {
644
+ /** Record ID being deleted */
645
+ id: string;
646
+ /** The existing record being deleted (parsed from data_json) */
647
+ record: Record<string, any> | null;
648
+ }
649
+ /** Context for beforeQuery hooks */
650
+ interface BeforeQueryContext extends HookContext {
651
+ /** The filter being applied */
652
+ filter: DocumentFilter;
653
+ /** Query options (sort, limit, etc.) */
654
+ options?: QueryOptions;
655
+ }
656
+ /** Context for afterQuery hooks */
657
+ interface AfterQueryContext extends HookContext {
658
+ /** The query results to filter */
659
+ results: Record<string, any>[];
660
+ }
661
+ /** Result from beforeSave/beforeDelete hooks */
662
+ interface HookResult {
663
+ allow: boolean;
664
+ /** Reason for denial (returned to client as error message) */
665
+ reason?: string;
666
+ }
667
+ /** Result from beforeQuery hooks — can inject additional filters */
668
+ interface BeforeQueryResult extends HookResult {
669
+ /** Additional filter merged into the query via $and */
670
+ injectFilter?: DocumentFilter;
671
+ }
672
+ /** Result from afterQuery hooks — returns filtered results */
673
+ interface AfterQueryResult {
674
+ /** The filtered results to return */
675
+ results: Record<string, any>[];
676
+ }
677
+ /** Hook definitions for createDatabaseDO */
678
+ interface DatabaseDOHooks {
679
+ beforeSave?: (ctx: BeforeSaveContext) => Promise<HookResult>;
680
+ beforeDelete?: (ctx: BeforeDeleteContext) => Promise<HookResult>;
681
+ beforeQuery?: (ctx: BeforeQueryContext) => Promise<BeforeQueryResult>;
682
+ afterQuery?: (ctx: AfterQueryContext) => Promise<AfterQueryResult>;
683
+ }
684
+
685
+ /**
686
+ * Database Durable Object Factory
687
+ *
688
+ * Creates a Durable Object class that serves as a schemaless database store.
689
+ * Each DO instance has its own SQLite database.
690
+ *
691
+ * Usage:
692
+ * ```typescript
693
+ * import { createDatabaseDO } from 'js-bao/cloudflare/do';
694
+ *
695
+ * export const MyDatabaseDO = createDatabaseDO({
696
+ * hooks: {
697
+ * beforeSave: async (ctx) => {
698
+ * // Access control logic
699
+ * return { allow: true };
700
+ * },
701
+ * },
702
+ * });
703
+ * ```
704
+ */
705
+
706
+ /**
707
+ * Request body types for RPC endpoints
708
+ */
709
+ interface QueryRequest {
710
+ modelName: string;
711
+ filter: DocumentFilter;
712
+ options?: QueryOptions;
713
+ }
714
+ interface SaveRequest {
715
+ modelName: string;
716
+ id: string;
717
+ data: Record<string, any>;
718
+ stringSets?: Record<string, string[]>;
719
+ ifNotExists?: boolean;
720
+ condition?: DocumentFilter;
721
+ }
722
+ interface DeleteRequest {
723
+ modelName: string;
724
+ id: string;
725
+ condition?: DocumentFilter;
726
+ }
727
+ interface CountRequest {
728
+ modelName: string;
729
+ filter: DocumentFilter;
730
+ }
731
+ interface RegisterIndexRequest {
732
+ modelName: string;
733
+ fieldName: string;
734
+ fieldType: string;
735
+ unique?: boolean;
736
+ }
737
+ interface DropIndexRequest {
738
+ modelName: string;
739
+ fieldName: string;
740
+ }
741
+ interface RegisterUniqueConstraintRequest {
742
+ modelName: string;
743
+ constraintName: string;
744
+ fields: string[];
745
+ }
746
+ interface DropUniqueConstraintRequest {
747
+ modelName: string;
748
+ constraintName: string;
749
+ }
750
+ /**
751
+ * Response types
752
+ */
753
+ interface QueryResponse {
754
+ data: Record<string, any>[];
755
+ hasMore?: boolean;
756
+ nextCursor?: string;
757
+ prevCursor?: string;
758
+ }
759
+ interface SaveResponse {
760
+ success: boolean;
761
+ id: string;
762
+ }
763
+ interface DeleteResponse {
764
+ success: boolean;
765
+ }
766
+ interface CountResponse {
767
+ count: number;
768
+ }
769
+ interface ErrorResponse {
770
+ error: string;
771
+ code?: string;
772
+ }
773
+ interface RegisterIndexResponse {
774
+ success: boolean;
775
+ modelName: string;
776
+ fieldName: string;
777
+ }
778
+ interface DropIndexResponse {
779
+ success: boolean;
780
+ modelName: string;
781
+ fieldName: string;
782
+ }
783
+ interface IndexListResponse {
784
+ indexes: IndexEntry[];
785
+ }
786
+ interface RegisterUniqueConstraintResponse {
787
+ success: boolean;
788
+ modelName: string;
789
+ constraintName: string;
790
+ }
791
+ interface DropUniqueConstraintResponse {
792
+ success: boolean;
793
+ modelName: string;
794
+ constraintName: string;
795
+ }
796
+ interface UniqueConstraintListResponse {
797
+ constraints: UniqueConstraintEntry[];
798
+ }
799
+ interface AggregateRequest {
800
+ modelName: string;
801
+ options: AggregationOptions;
802
+ }
803
+ interface AggregateResponse {
804
+ result: AggregationResult;
805
+ }
806
+ interface SyncIndexesRequest {
807
+ models: Array<{
808
+ modelName: string;
809
+ indexes: Array<{
810
+ fieldName: string;
811
+ fieldType: string;
812
+ unique: boolean;
813
+ }>;
814
+ uniqueConstraints: Array<{
815
+ name: string;
816
+ fields: string[];
817
+ }>;
818
+ }>;
819
+ }
820
+ interface SyncIndexesResponse {
821
+ registered: number;
822
+ }
823
+ interface PatchRequest {
824
+ modelName: string;
825
+ id: string;
826
+ data: Record<string, any>;
827
+ stringSets?: Record<string, string[]>;
828
+ condition?: DocumentFilter;
829
+ }
830
+ interface PatchResponse {
831
+ success: boolean;
832
+ id: string;
833
+ }
834
+ interface BatchOperation {
835
+ op: "save" | "patch" | "delete" | "increment" | "addToSet" | "removeFromSet";
836
+ modelName: string;
837
+ id: string;
838
+ data?: Record<string, any>;
839
+ stringSets?: Record<string, string[]>;
840
+ fields?: Record<string, number>;
841
+ ifNotExists?: boolean;
842
+ condition?: DocumentFilter;
843
+ }
844
+ interface BatchRequest {
845
+ operations: BatchOperation[];
846
+ }
847
+ interface BatchOperationResult {
848
+ success: boolean;
849
+ id: string;
850
+ error?: string;
851
+ values?: Record<string, number>;
852
+ }
853
+ interface BatchResponse {
854
+ results: BatchOperationResult[];
855
+ }
856
+ interface IncrementRequest {
857
+ modelName: string;
858
+ id: string;
859
+ fields: Record<string, number>;
860
+ condition?: DocumentFilter;
861
+ }
862
+ interface IncrementResponse {
863
+ success: boolean;
864
+ id: string;
865
+ values: Record<string, number>;
866
+ }
867
+ interface StringSetUpdateRequest {
868
+ modelName: string;
869
+ id: string;
870
+ sets: Record<string, string[]>;
871
+ condition?: DocumentFilter;
872
+ }
873
+ interface StringSetUpdateResponse {
874
+ success: boolean;
875
+ }
876
+
877
+ /**
878
+ * Durable Object Client Engine
879
+ *
880
+ * Client-side engine that proxies database operations to a Cloudflare
881
+ * Durable Object via HTTP fetch calls.
882
+ *
883
+ * This engine runs in the browser or Node.js and communicates with
884
+ * the DO-based backend.
885
+ */
886
+
887
+ interface DOClientEngineConfig {
888
+ /**
889
+ * Base URL of the Cloudflare Worker
890
+ * e.g., "https://my-worker.my-subdomain.workers.dev"
891
+ */
892
+ endpoint: string;
893
+ /**
894
+ * Optional custom fetch function (useful for testing)
895
+ */
896
+ fetch?: typeof fetch;
897
+ /**
898
+ * Optional authorization header value
899
+ */
900
+ authorization?: string;
901
+ /**
902
+ * Request timeout in milliseconds (default: 30000)
903
+ */
904
+ timeout?: number;
905
+ }
906
+ declare class DOClientEngine extends DatabaseEngine {
907
+ private endpoint;
908
+ private customFetch;
909
+ private authorization?;
910
+ private timeout;
911
+ private currentDocId;
912
+ constructor(config: DOClientEngineConfig);
913
+ /**
914
+ * Set the current document ID for subsequent operations.
915
+ */
916
+ setCurrentDocument(docId: string): void;
917
+ /**
918
+ * Get the current document ID.
919
+ */
920
+ getCurrentDocument(): string | null;
921
+ /**
922
+ * Build the URL for a DO endpoint.
923
+ */
924
+ private buildUrl;
925
+ /**
926
+ * Make a fetch request to the DO.
927
+ */
928
+ private doFetch;
929
+ /**
930
+ * Query records from the DO.
931
+ */
932
+ queryModel(modelName: string, filter?: DocumentFilter, options?: QueryOptions): Promise<PaginatedResult<Record<string, any>>>;
933
+ /**
934
+ * Save a record to the DO.
935
+ */
936
+ saveModel(modelName: string, id: string, data: Record<string, any>, stringSets?: Record<string, string[]>, options?: {
937
+ ifNotExists?: boolean;
938
+ condition?: DocumentFilter;
939
+ }): Promise<string>;
940
+ /**
941
+ * Patch (partial update) a record in the DO.
942
+ * Only the provided fields are updated; existing fields are preserved.
943
+ */
944
+ patchModel(modelName: string, id: string, data: Record<string, any>, stringSets?: Record<string, string[]>, options?: {
945
+ condition?: DocumentFilter;
946
+ }): Promise<string>;
947
+ /**
948
+ * Delete a record from the DO.
949
+ */
950
+ deleteModel(modelName: string, id: string, options?: {
951
+ condition?: DocumentFilter;
952
+ }): Promise<boolean>;
953
+ /**
954
+ * Count records matching a filter.
955
+ */
956
+ countModel(modelName: string, filter?: DocumentFilter): Promise<number>;
957
+ /**
958
+ * Aggregate records with groupBy and operations (count, sum, avg, min, max).
959
+ */
960
+ aggregateModel(modelName: string, options: AggregationOptions): Promise<AggregationResult>;
961
+ /**
962
+ * Atomically add values to StringSet fields on a record.
963
+ */
964
+ addToStringSet(modelName: string, id: string, sets: Record<string, string[]>, options?: {
965
+ condition?: DocumentFilter;
966
+ }): Promise<void>;
967
+ /**
968
+ * Atomically remove values from StringSet fields on a record.
969
+ */
970
+ removeFromStringSet(modelName: string, id: string, sets: Record<string, string[]>, options?: {
971
+ condition?: DocumentFilter;
972
+ }): Promise<void>;
973
+ /**
974
+ * Atomically increment/decrement numeric fields on a record.
975
+ * Returns the new values after the increment.
976
+ */
977
+ incrementFields(modelName: string, id: string, fields: Record<string, number>, options?: {
978
+ condition?: DocumentFilter;
979
+ }): Promise<Record<string, number>>;
980
+ /**
981
+ * Execute multiple save/patch/delete operations in a single request.
982
+ * All operations run in a single transaction on the server.
983
+ */
984
+ batchWrite(operations: BatchOperation[]): Promise<BatchOperationResult[]>;
985
+ /**
986
+ * Check if the DO is healthy.
987
+ */
988
+ healthCheck(): Promise<{
989
+ status: string;
990
+ }>;
991
+ /**
992
+ * Batch sync indexes: send all desired indexes in one request.
993
+ * The DO compares against its _indexes table and registers only what's missing.
994
+ * Returns the number of indexes/constraints newly registered.
995
+ */
996
+ syncIndexesBatch(request: SyncIndexesRequest): Promise<number>;
997
+ /**
998
+ * Register an index on a model field.
999
+ * Creates a SQLite index on json_extract(data_json, '$.fieldName').
1000
+ * Set unique=true to enforce uniqueness on this field.
1001
+ */
1002
+ registerIndex(modelName: string, fieldName: string, fieldType?: string, unique?: boolean): Promise<void>;
1003
+ /**
1004
+ * Drop an index from a model field.
1005
+ */
1006
+ dropIndex(modelName: string, fieldName: string): Promise<void>;
1007
+ /**
1008
+ * List indexes, optionally filtered by model name.
1009
+ */
1010
+ listIndexes(modelName?: string): Promise<IndexEntry[]>;
1011
+ /**
1012
+ * Describe tracked fields for a model.
1013
+ */
1014
+ describe(modelName: string): Promise<ModelFieldInfo[]>;
1015
+ /**
1016
+ * Register a composite unique constraint across multiple fields.
1017
+ */
1018
+ registerUniqueConstraint(modelName: string, constraintName: string, fields: string[]): Promise<void>;
1019
+ /**
1020
+ * Drop a composite unique constraint.
1021
+ */
1022
+ dropUniqueConstraint(modelName: string, constraintName: string): Promise<void>;
1023
+ /**
1024
+ * List composite unique constraints, optionally filtered by model name.
1025
+ */
1026
+ listUniqueConstraints(modelName?: string): Promise<UniqueConstraintEntry[]>;
1027
+ /**
1028
+ * Ensure the engine is ready.
1029
+ * For DOClient, this verifies connectivity.
1030
+ */
1031
+ ensureReady(): Promise<void>;
1032
+ /**
1033
+ * Execute raw SQL.
1034
+ * Not supported in DO client mode - use queryModel instead.
1035
+ */
1036
+ query(_sql: string, _params?: any[]): Promise<any[]>;
1037
+ /**
1038
+ * Get last error message.
1039
+ */
1040
+ getLastErrorMessage(): string | undefined;
1041
+ /**
1042
+ * Get table schema.
1043
+ * Not directly supported - schema is managed by the DO.
1044
+ */
1045
+ getTableSchema(_tableName: string): Promise<any>;
1046
+ /**
1047
+ * Destroy the engine.
1048
+ * Nothing to clean up for the client.
1049
+ */
1050
+ destroy(): Promise<void>;
1051
+ /**
1052
+ * Create table.
1053
+ * No-op in DO client mode - schema is managed by the DO.
1054
+ */
1055
+ createTable(_modelName: string, _schema: Map<string, FieldOptions>, _options: ModelOptions): Promise<void>;
1056
+ /**
1057
+ * Create StringSet junction table.
1058
+ * No-op in DO client mode.
1059
+ */
1060
+ createStringSetJunctionTable(_modelName: string, _fieldName: string): Promise<void>;
1061
+ /**
1062
+ * Insert a record.
1063
+ * Delegates to saveModel.
1064
+ */
1065
+ insert(modelName: string, data: any): Promise<void>;
1066
+ /**
1067
+ * Delete a record.
1068
+ * Delegates to deleteModel.
1069
+ */
1070
+ delete(modelName: string, id: string): Promise<void>;
1071
+ /**
1072
+ * Get table name.
1073
+ * All models use 'records' in JSON schema.
1074
+ */
1075
+ getTableName(_modelName: string): string;
1076
+ /**
1077
+ * Transaction support.
1078
+ * DO client doesn't support client-side transactions.
1079
+ * Operations are atomic on the DO side.
1080
+ */
1081
+ withTransaction<T>(callback: (operations: ITransactionalDatabaseOperations) => Promise<T>): Promise<T>;
1082
+ }
1083
+
1084
+ /**
1085
+ * Durable Object Mode Initialization
1086
+ *
1087
+ * Alternative initialization for js-bao that uses Cloudflare Durable Objects
1088
+ * instead of yjs for document storage.
1089
+ *
1090
+ * Key differences from yjs mode:
1091
+ * - No yjs dependency
1092
+ * - Server-authoritative (DO is source of truth)
1093
+ * - HTTP-based communication with DO backend
1094
+ * - One DO per document
1095
+ * - Schemaless: any field can be saved/queried without registration
1096
+ * - Only indexes need explicit registration for performance
1097
+ */
1098
+
1099
+ /**
1100
+ * A model can be identified by either a BaseModel subclass or a plain string name.
1101
+ * Use a string when you don't have a model class (e.g., schemaless / CSV import).
1102
+ */
1103
+ type ModelIdentifier = typeof BaseModel | string;
1104
+ /**
1105
+ * Configuration for DO mode initialization
1106
+ */
1107
+ interface InitJsBaoDOOptions {
1108
+ /**
1109
+ * Base URL of the Cloudflare Worker
1110
+ * e.g., "https://my-worker.my-subdomain.workers.dev"
1111
+ */
1112
+ endpoint: string;
1113
+ /**
1114
+ * Optional authorization header value
1115
+ */
1116
+ authorization?: string;
1117
+ /**
1118
+ * Optional custom fetch function (for testing)
1119
+ */
1120
+ fetch?: typeof fetch;
1121
+ /**
1122
+ * Request timeout in milliseconds (default: 30000)
1123
+ */
1124
+ timeout?: number;
1125
+ }
1126
+ /**
1127
+ * Result of DO mode initialization
1128
+ */
1129
+ interface InitJsBaoDOResult {
1130
+ /**
1131
+ * The DO client engine
1132
+ */
1133
+ engine: DOClientEngine;
1134
+ /**
1135
+ * Connect to a document (sets the current document for operations)
1136
+ */
1137
+ connectDocument: (docId: string) => Promise<void>;
1138
+ /**
1139
+ * Disconnect from the current document
1140
+ */
1141
+ disconnectDocument: () => Promise<void>;
1142
+ /**
1143
+ * Get the current document ID
1144
+ */
1145
+ getCurrentDocument: () => string | null;
1146
+ /**
1147
+ * Check if connected to a document
1148
+ */
1149
+ isConnected: () => boolean;
1150
+ /**
1151
+ * Query records from the current document
1152
+ */
1153
+ query: <T extends Record<string, any>>(model: ModelIdentifier, filter?: DocumentFilter, options?: QueryOptions) => Promise<PaginatedResult<T>>;
1154
+ /**
1155
+ * Find a single record by ID
1156
+ */
1157
+ find: <T extends Record<string, any>>(model: ModelIdentifier, id: string) => Promise<T | null>;
1158
+ /**
1159
+ * Save a record to the current document
1160
+ */
1161
+ save: (model: ModelIdentifier, data: Record<string, any>, options?: SaveOptions | Record<string, string[]>) => Promise<string>;
1162
+ /**
1163
+ * Patch (partial update) a record — only the provided fields are changed
1164
+ */
1165
+ patch: (model: ModelIdentifier, id: string, data: Record<string, any>, options?: PatchOptions | Record<string, string[]>) => Promise<string>;
1166
+ /**
1167
+ * Delete a record from the current document
1168
+ */
1169
+ delete: (model: ModelIdentifier, id: string, options?: WriteCondition) => Promise<boolean>;
1170
+ /**
1171
+ * Count records matching a filter
1172
+ */
1173
+ count: (model: ModelIdentifier, filter?: DocumentFilter) => Promise<number>;
1174
+ /**
1175
+ * Aggregate records with groupBy and operations (count, sum, avg, min, max)
1176
+ */
1177
+ aggregate: (model: ModelIdentifier, options: AggregationOptions) => Promise<AggregationResult>;
1178
+ /**
1179
+ * Atomically add values to StringSet fields on a record
1180
+ */
1181
+ addToSet: (model: ModelIdentifier, id: string, sets: Record<string, string[]>, options?: WriteCondition) => Promise<void>;
1182
+ /**
1183
+ * Atomically remove values from StringSet fields on a record
1184
+ */
1185
+ removeFromSet: (model: ModelIdentifier, id: string, sets: Record<string, string[]>, options?: WriteCondition) => Promise<void>;
1186
+ /**
1187
+ * Atomically increment/decrement numeric fields on a record.
1188
+ * Returns the new values after the increment.
1189
+ */
1190
+ increment: (model: ModelIdentifier, id: string, fields: Record<string, number>, options?: WriteCondition) => Promise<Record<string, number>>;
1191
+ /**
1192
+ * Execute multiple save/patch/delete operations in a single request
1193
+ */
1194
+ batch: (operations: BatchOperation[]) => Promise<BatchOperationResult[]>;
1195
+ /**
1196
+ * Describe tracked fields for a model (names and inferred types).
1197
+ */
1198
+ describe: (modelName: string) => Promise<ModelFieldInfo[]>;
1199
+ /**
1200
+ * Register an index on a model field for query performance.
1201
+ * Set unique=true to enforce uniqueness on this field.
1202
+ */
1203
+ registerIndex: (modelName: string, fieldName: string, fieldType?: string, unique?: boolean) => Promise<void>;
1204
+ /**
1205
+ * Drop an index from a model field.
1206
+ */
1207
+ dropIndex: (modelName: string, fieldName: string) => Promise<void>;
1208
+ /**
1209
+ * List all registered indexes, optionally filtered by model name.
1210
+ */
1211
+ listIndexes: (modelName?: string) => Promise<IndexEntry[]>;
1212
+ /**
1213
+ * Register a composite unique constraint across multiple fields.
1214
+ */
1215
+ registerUniqueConstraint: (modelName: string, constraintName: string, fields: string[]) => Promise<void>;
1216
+ /**
1217
+ * Drop a composite unique constraint.
1218
+ */
1219
+ dropUniqueConstraint: (modelName: string, constraintName: string) => Promise<void>;
1220
+ /**
1221
+ * List composite unique constraints, optionally filtered by model name.
1222
+ */
1223
+ listUniqueConstraints: (modelName?: string) => Promise<UniqueConstraintEntry[]>;
1224
+ /**
1225
+ * Sync indexes from a model's schema definition.
1226
+ *
1227
+ * Reads the model's field definitions and registers indexes for any field
1228
+ * with `indexed: true` or `unique: true`. Also registers composite unique
1229
+ * constraints from the model's `uniqueConstraints` option.
1230
+ *
1231
+ * **Additive only** — never drops existing indexes, since other developers
1232
+ * may have registered indexes that aren't in this model's schema.
1233
+ *
1234
+ * @returns The number of indexes/constraints that were newly registered.
1235
+ */
1236
+ syncIndexes: (modelClass: typeof BaseModel) => Promise<number>;
1237
+ }
1238
+ /**
1239
+ * Initialize js-bao in Durable Object mode.
1240
+ *
1241
+ * Usage:
1242
+ * ```typescript
1243
+ * import { initJsBaoDO } from 'js-bao/cloudflare';
1244
+ * import { Statement } from './models';
1245
+ *
1246
+ * const jsbao = await initJsBaoDO({
1247
+ * endpoint: 'https://my-worker.workers.dev',
1248
+ * });
1249
+ *
1250
+ * await jsbao.connectDocument('my-doc-id');
1251
+ *
1252
+ * // Save any data — no schema registration required
1253
+ * await jsbao.save(Statement, { id: 'stmt-1', amount: 100, label: 'rent' });
1254
+ *
1255
+ * // Query on any field
1256
+ * const results = await jsbao.query(Statement, { amount: { $gt: 50 } });
1257
+ *
1258
+ * // Optionally register indexes for performance
1259
+ * await jsbao.registerIndex('Statement', 'amount', 'number');
1260
+ * ```
1261
+ */
1262
+ declare function initJsBaoDO(options: InitJsBaoDOOptions): Promise<InitJsBaoDOResult>;
1263
+ /**
1264
+ * Reset DO mode state (for testing)
1265
+ */
1266
+ declare function resetJsBaoDO(): Promise<void>;
1267
+ /**
1268
+ * Get the active DO engine (if any)
1269
+ */
1270
+ declare function getActiveDOEngine(): DOClientEngine | null;
1271
+ /**
1272
+ * Configuration for connectDoDb
1273
+ */
1274
+ interface ConnectDoDbOptions {
1275
+ /** Base URL of the Cloudflare Worker */
1276
+ endpoint: string;
1277
+ /** Document ID to connect to */
1278
+ id: string;
1279
+ /** Model classes to create pre-bound accessors for */
1280
+ models?: (typeof BaseModel)[];
1281
+ /** Optional authorization header value */
1282
+ authorization?: string;
1283
+ /** Optional custom fetch function (for testing) */
1284
+ fetch?: typeof fetch;
1285
+ /** Request timeout in milliseconds (default: 30000) */
1286
+ timeout?: number;
1287
+ }
1288
+ /**
1289
+ * Pre-bound model accessor — all methods are scoped to a specific model.
1290
+ */
1291
+ interface SaveOptions {
1292
+ stringSets?: Record<string, string[]>;
1293
+ ifNotExists?: boolean;
1294
+ condition?: DocumentFilter;
1295
+ }
1296
+ interface PatchOptions {
1297
+ stringSets?: Record<string, string[]>;
1298
+ condition?: DocumentFilter;
1299
+ }
1300
+ interface WriteCondition {
1301
+ condition?: DocumentFilter;
1302
+ }
1303
+ interface ModelAccessor {
1304
+ query<T extends Record<string, any> = Record<string, any>>(filter?: DocumentFilter, options?: QueryOptions): Promise<PaginatedResult<T>>;
1305
+ find<T extends Record<string, any> = Record<string, any>>(id: string): Promise<T | null>;
1306
+ save(data: Record<string, any>, options?: SaveOptions | Record<string, string[]>): Promise<string>;
1307
+ patch(id: string, data: Record<string, any>, options?: PatchOptions | Record<string, string[]>): Promise<string>;
1308
+ delete(id: string, options?: WriteCondition): Promise<boolean>;
1309
+ count(filter?: DocumentFilter): Promise<number>;
1310
+ aggregate(options: AggregationOptions): Promise<AggregationResult>;
1311
+ increment(id: string, fields: Record<string, number>, options?: WriteCondition): Promise<Record<string, number>>;
1312
+ addToSet(id: string, sets: Record<string, string[]>, options?: WriteCondition): Promise<void>;
1313
+ removeFromSet(id: string, sets: Record<string, string[]>, options?: WriteCondition): Promise<void>;
1314
+ }
1315
+ /**
1316
+ * Result of connectDoDb — provides both ad-hoc and pre-bound model access.
1317
+ *
1318
+ * Ad-hoc: `db.query(User, filter)` — works with any model class.
1319
+ * Pre-bound: `db.User.query(filter)` — only for models passed in `models` array.
1320
+ */
1321
+ interface DoDb {
1322
+ /** The underlying DO client engine */
1323
+ readonly engine: DOClientEngine;
1324
+ /** The connected document ID */
1325
+ readonly docId: string;
1326
+ query<T extends Record<string, any> = Record<string, any>>(model: ModelIdentifier, filter?: DocumentFilter, options?: QueryOptions): Promise<PaginatedResult<T>>;
1327
+ find<T extends Record<string, any> = Record<string, any>>(model: ModelIdentifier, id: string): Promise<T | null>;
1328
+ save(model: ModelIdentifier, data: Record<string, any>, options?: SaveOptions | Record<string, string[]>): Promise<string>;
1329
+ patch(model: ModelIdentifier, id: string, data: Record<string, any>, options?: PatchOptions | Record<string, string[]>): Promise<string>;
1330
+ delete(model: ModelIdentifier, id: string, options?: WriteCondition): Promise<boolean>;
1331
+ count(model: ModelIdentifier, filter?: DocumentFilter): Promise<number>;
1332
+ aggregate(model: ModelIdentifier, options: AggregationOptions): Promise<AggregationResult>;
1333
+ increment(model: ModelIdentifier, id: string, fields: Record<string, number>, options?: WriteCondition): Promise<Record<string, number>>;
1334
+ addToSet(model: ModelIdentifier, id: string, sets: Record<string, string[]>, options?: WriteCondition): Promise<void>;
1335
+ removeFromSet(model: ModelIdentifier, id: string, sets: Record<string, string[]>, options?: WriteCondition): Promise<void>;
1336
+ batch(operations: BatchOperation[]): Promise<BatchOperationResult[]>;
1337
+ describe(modelName: string): Promise<ModelFieldInfo[]>;
1338
+ registerIndex(modelName: string, fieldName: string, fieldType?: string, unique?: boolean): Promise<void>;
1339
+ dropIndex(modelName: string, fieldName: string): Promise<void>;
1340
+ listIndexes(modelName?: string): Promise<IndexEntry[]>;
1341
+ registerUniqueConstraint(modelName: string, constraintName: string, fields: string[]): Promise<void>;
1342
+ dropUniqueConstraint(modelName: string, constraintName: string): Promise<void>;
1343
+ listUniqueConstraints(modelName?: string): Promise<UniqueConstraintEntry[]>;
1344
+ syncIndexes(modelClass: typeof BaseModel): Promise<number>;
1345
+ /**
1346
+ * Sync indexes for all models passed in the `models` array at init.
1347
+ * Returns total number of indexes/constraints newly registered.
1348
+ */
1349
+ syncAllIndexes(): Promise<number>;
1350
+ [modelName: string]: any;
1351
+ }
1352
+ /**
1353
+ * Connect to a Durable Object document database.
1354
+ *
1355
+ * Combines initialization and document connection into a single call.
1356
+ * Returns an object with both ad-hoc and pre-bound model access.
1357
+ *
1358
+ * Usage:
1359
+ * ```typescript
1360
+ * import { connectDoDb } from 'js-bao/cloudflare';
1361
+ * import { User, Post } from './models';
1362
+ *
1363
+ * const db = connectDoDb({
1364
+ * endpoint: 'https://my-worker.workers.dev',
1365
+ * id: 'my-document',
1366
+ * models: [User, Post],
1367
+ * });
1368
+ *
1369
+ * // Pre-bound model access (models registered at init)
1370
+ * await db.User.save({ id: 'u-1', name: 'Alice' });
1371
+ * const users = await db.User.query({ name: 'Alice' });
1372
+ * const user = await db.User.find('u-1');
1373
+ *
1374
+ * // Ad-hoc model access (any model class)
1375
+ * await db.save(User, { id: 'u-2', name: 'Bob' });
1376
+ * const results = await db.query(User, { name: 'Bob' });
1377
+ * ```
1378
+ */
1379
+ declare function connectDoDb(options: ConnectDoDbOptions): DoDb;
1380
+
1381
+ export { type AfterQueryContext, type AfterQueryResult, type AggregateRequest, type AggregateResponse, type AggregationOperation, type AggregationOptions, type AggregationResult, type BatchOperation, type BatchOperationResult, type BatchRequest, type BatchResponse, type BeforeDeleteContext, type BeforeQueryContext, type BeforeQueryResult, type BeforeSaveContext, type ConnectDoDbOptions, type CountRequest, type CountResponse, DOClientEngine, type DOClientEngineConfig, type DatabaseDOHooks, type DeleteRequest, type DeleteResponse, type DoDb, type DocumentFilter, type DropIndexRequest, type DropIndexResponse, type DropUniqueConstraintRequest, type DropUniqueConstraintResponse, type ErrorResponse, type GroupByField, type HookContext, type HookResult, type IncrementRequest, type IncrementResponse, type IndexEntry, type IndexListResponse, type InitJsBaoDOOptions, type InitJsBaoDOResult, type ModelAccessor, type PaginatedResult, type PatchOptions, type PatchRequest, type PatchResponse, type ProjectionSpec, type QueryOptions, type QueryRequest, type QueryResponse, type RegisterIndexRequest, type RegisterIndexResponse, type RegisterUniqueConstraintRequest, type RegisterUniqueConstraintResponse, type SaveOptions, type SaveRequest, type SaveResponse, type SortSpec, type StringSetMembership, type StringSetUpdateRequest, type StringSetUpdateResponse, type SyncIndexesRequest, type SyncIndexesResponse, type UniqueConstraintEntry, type UniqueConstraintListResponse, type WriteCondition, connectDoDb, getActiveDOEngine, initJsBaoDO, resetJsBaoDO };