@event-driven-io/pongo 0.17.0-beta.33 → 0.17.0-beta.35

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 (46) hide show
  1. package/dist/chunk-EQ3T4XHT.cjs +1583 -0
  2. package/dist/chunk-EQ3T4XHT.cjs.map +1 -0
  3. package/dist/{chunk-TTZGGAZV.js → chunk-H6YIW5C5.js} +69 -2
  4. package/dist/chunk-H6YIW5C5.js.map +1 -0
  5. package/dist/{chunk-A4DCNQJR.cjs → chunk-NTHMSHNG.cjs} +79 -12
  6. package/dist/chunk-NTHMSHNG.cjs.map +1 -0
  7. package/dist/{chunk-H637RRXS.js → chunk-NWYI26VT.js} +1310 -632
  8. package/dist/chunk-NWYI26VT.js.map +1 -0
  9. package/dist/cli.cjs +13 -13
  10. package/dist/cli.cjs.map +1 -1
  11. package/dist/cli.js +2 -2
  12. package/dist/cli.js.map +1 -1
  13. package/dist/cloudflare.cjs +10 -10
  14. package/dist/cloudflare.d.cts +3 -2
  15. package/dist/cloudflare.d.ts +3 -2
  16. package/dist/cloudflare.js +2 -2
  17. package/dist/{index-gHRYr05w.d.ts → index-BfBszcG4.d.ts} +1 -1
  18. package/dist/{index-DxHXL62G.d.cts → index-a-fxODW1.d.cts} +1 -1
  19. package/dist/index.cjs +26 -2
  20. package/dist/index.cjs.map +1 -1
  21. package/dist/index.d.cts +38 -16
  22. package/dist/index.d.ts +38 -16
  23. package/dist/index.js +25 -1
  24. package/dist/index.js.map +1 -1
  25. package/dist/pg.cjs +102 -16
  26. package/dist/pg.cjs.map +1 -1
  27. package/dist/pg.d.cts +2 -1
  28. package/dist/pg.d.ts +2 -1
  29. package/dist/pg.js +87 -1
  30. package/dist/pg.js.map +1 -1
  31. package/dist/{pongoCollectionSchemaComponent-B5Oatwu0.d.cts → pongoTransactionCache-CRuPGag3.d.cts} +155 -35
  32. package/dist/{pongoCollectionSchemaComponent-B5Oatwu0.d.ts → pongoTransactionCache-CRuPGag3.d.ts} +155 -35
  33. package/dist/shim.cjs +5 -5
  34. package/dist/shim.d.cts +2 -1
  35. package/dist/shim.d.ts +2 -1
  36. package/dist/shim.js +1 -1
  37. package/dist/sqlite3.cjs +10 -10
  38. package/dist/sqlite3.d.cts +3 -2
  39. package/dist/sqlite3.d.ts +3 -2
  40. package/dist/sqlite3.js +2 -2
  41. package/package.json +20 -18
  42. package/dist/chunk-A4DCNQJR.cjs.map +0 -1
  43. package/dist/chunk-BZRKCNRY.cjs +0 -905
  44. package/dist/chunk-BZRKCNRY.cjs.map +0 -1
  45. package/dist/chunk-H637RRXS.js.map +0 -1
  46. package/dist/chunk-TTZGGAZV.js.map +0 -1
@@ -0,0 +1,1583 @@
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }// src/core/cache/pongoCacheWrapper.ts
2
+ var pongoCacheWrapper = (options) => {
3
+ const { provider, hooks } = options;
4
+ const onError = (error, operation) => {
5
+ _optionalChain([hooks, 'optionalAccess', _2 => _2.onError, 'optionalCall', _3 => _3(error, operation)]);
6
+ };
7
+ let isClosed = false;
8
+ return {
9
+ cacheType: provider.cacheType,
10
+ async get(key) {
11
+ try {
12
+ const result = await provider.get(key);
13
+ if (result !== void 0) {
14
+ _optionalChain([hooks, 'optionalAccess', _4 => _4.onHit, 'optionalCall', _5 => _5(key)]);
15
+ } else {
16
+ _optionalChain([hooks, 'optionalAccess', _6 => _6.onMiss, 'optionalCall', _7 => _7(key)]);
17
+ }
18
+ return result;
19
+ } catch (error) {
20
+ onError(error, "get");
21
+ _optionalChain([hooks, 'optionalAccess', _8 => _8.onMiss, 'optionalCall', _9 => _9(key)]);
22
+ return void 0;
23
+ }
24
+ },
25
+ async getMany(keys) {
26
+ try {
27
+ return await provider.getMany(keys);
28
+ } catch (error) {
29
+ onError(error, "getMany");
30
+ return [];
31
+ }
32
+ },
33
+ async set(key, value) {
34
+ try {
35
+ await provider.set(key, value);
36
+ } catch (error) {
37
+ onError(error, "set");
38
+ }
39
+ },
40
+ async setMany(entries) {
41
+ try {
42
+ await provider.setMany(entries);
43
+ } catch (error) {
44
+ onError(error, "setMany");
45
+ }
46
+ },
47
+ async update(key, updater) {
48
+ try {
49
+ await provider.update(key, updater);
50
+ } catch (error) {
51
+ onError(error, "update");
52
+ }
53
+ },
54
+ async updateMany(keys, updater) {
55
+ try {
56
+ await provider.updateMany(keys, updater);
57
+ } catch (error) {
58
+ onError(error, "updateMany");
59
+ }
60
+ },
61
+ async delete(key) {
62
+ try {
63
+ await provider.delete(key);
64
+ _optionalChain([hooks, 'optionalAccess', _10 => _10.onEvict, 'optionalCall', _11 => _11(key)]);
65
+ } catch (error) {
66
+ onError(error, "delete");
67
+ }
68
+ },
69
+ async deleteMany(keys) {
70
+ try {
71
+ await provider.deleteMany(keys);
72
+ for (const key of keys) _optionalChain([hooks, 'optionalAccess', _12 => _12.onEvict, 'optionalCall', _13 => _13(key)]);
73
+ } catch (error) {
74
+ onError(error, "deleteMany");
75
+ }
76
+ },
77
+ clear() {
78
+ return provider.clear();
79
+ },
80
+ close() {
81
+ if (isClosed) return;
82
+ isClosed = true;
83
+ return provider.close();
84
+ }
85
+ };
86
+ };
87
+
88
+ // src/core/cache/providers/identityMapCache.ts
89
+ var identityMapCache = () => {
90
+ const store = /* @__PURE__ */ new Map();
91
+ return {
92
+ cacheType: "pongo:cache:identity-map",
93
+ get: (key) => Promise.resolve(
94
+ store.has(key) ? store.get(key) : void 0
95
+ ),
96
+ getMany: (keys) => keys.map(
97
+ (k) => store.has(k) ? store.get(k) : void 0
98
+ ),
99
+ set: (key, value) => {
100
+ store.set(key, value);
101
+ },
102
+ setMany: (entries) => {
103
+ for (const { key, value } of entries) store.set(key, value);
104
+ },
105
+ update: (key, _updater) => {
106
+ store.delete(key);
107
+ },
108
+ updateMany: (keys, _updater) => {
109
+ for (const key of keys) store.delete(key);
110
+ },
111
+ delete: (key) => {
112
+ store.delete(key);
113
+ },
114
+ deleteMany: (keys) => {
115
+ for (const key of keys) store.delete(key);
116
+ },
117
+ clear: () => {
118
+ store.clear();
119
+ },
120
+ close: () => {
121
+ store.clear();
122
+ }
123
+ };
124
+ };
125
+
126
+ // src/core/cache/providers/lruCache.ts
127
+ var _lrucache = require('lru-cache');
128
+ var defaultLRUCacheOptions = {
129
+ max: 1e3
130
+ };
131
+ var lruCache = (options) => {
132
+ const cache = new (0, _lrucache.LRUCache)({
133
+ ...defaultLRUCacheOptions,
134
+ ...options
135
+ });
136
+ return {
137
+ cacheType: "pongo:cache:lru",
138
+ get: (key) => {
139
+ const entry = cache.get(key);
140
+ if (entry === void 0) return void 0;
141
+ return entry.doc;
142
+ },
143
+ getMany: (keys) => keys.map((k) => {
144
+ const entry = cache.get(k);
145
+ if (entry === void 0) return void 0;
146
+ return entry.doc;
147
+ }),
148
+ set: (key, value) => {
149
+ cache.set(key, { doc: value });
150
+ },
151
+ setMany: (entries) => {
152
+ for (const { key, value } of entries) {
153
+ cache.set(key, { doc: value });
154
+ }
155
+ },
156
+ update: (key, _updater) => {
157
+ cache.delete(key);
158
+ },
159
+ updateMany(keys, _updater) {
160
+ for (const key of keys) {
161
+ cache.delete(key);
162
+ }
163
+ },
164
+ delete: (key) => {
165
+ cache.delete(key);
166
+ },
167
+ deleteMany: (keys) => {
168
+ for (const key of keys) cache.delete(key);
169
+ },
170
+ clear: () => {
171
+ cache.clear();
172
+ },
173
+ close: () => {
174
+ cache.clear();
175
+ }
176
+ };
177
+ };
178
+
179
+ // src/core/cache/providers/noopCache.ts
180
+ var noopCacheProvider = {
181
+ cacheType: "pongo:cache:no-op",
182
+ get: () => void 0,
183
+ set: () => {
184
+ },
185
+ update: () => {
186
+ },
187
+ delete: () => {
188
+ },
189
+ getMany: (keys) => keys.map(() => void 0),
190
+ setMany: () => {
191
+ },
192
+ updateMany: () => {
193
+ },
194
+ deleteMany: () => {
195
+ },
196
+ clear: () => {
197
+ },
198
+ close: () => {
199
+ }
200
+ };
201
+
202
+ // src/core/cache/pongoCache.ts
203
+ var DEFAULT_CONFIG = { type: "in-memory" };
204
+ var pongoCache = (options) => {
205
+ if (options === void 0 || options === "disabled") return noopCacheProvider;
206
+ if ("cacheType" in options) return options;
207
+ const config = _nullishCoalesce(options, () => ( DEFAULT_CONFIG));
208
+ if (config.type === "identity-map") return identityMapCache();
209
+ const raw = lruCache(config);
210
+ return pongoCacheWrapper({ provider: raw });
211
+ };
212
+
213
+ // src/core/cache/transactions/pongoTransactionCache.ts
214
+ var pongoTransactionCache = (options) => {
215
+ const innerCache = _nullishCoalesce(_optionalChain([options, 'optionalAccess', _14 => _14.cache]), () => ( identityMapCache()));
216
+ const operations = [];
217
+ const cache = {
218
+ type: "pongo:cache:transaction-buffer",
219
+ get(key) {
220
+ return innerCache.get(key);
221
+ },
222
+ set(key, value, options2) {
223
+ const { mainCache } = options2;
224
+ innerCache.set(key, value);
225
+ operations.push({
226
+ type: "set",
227
+ key,
228
+ value,
229
+ mainCache
230
+ });
231
+ },
232
+ update(key, updater, options2) {
233
+ const { mainCache } = options2;
234
+ innerCache.update(key, updater);
235
+ operations.push({
236
+ type: "update",
237
+ key,
238
+ updater,
239
+ mainCache
240
+ });
241
+ },
242
+ delete(key, options2) {
243
+ innerCache.delete(key);
244
+ operations.push({ type: "delete", key, mainCache: options2.mainCache });
245
+ },
246
+ getMany(keys) {
247
+ return innerCache.getMany(keys);
248
+ },
249
+ setMany(entries, options2) {
250
+ innerCache.setMany(entries);
251
+ operations.push({
252
+ type: "setMany",
253
+ entries,
254
+ mainCache: options2.mainCache
255
+ });
256
+ },
257
+ updateMany(keys, updater, options2) {
258
+ const { mainCache } = options2;
259
+ innerCache.updateMany(keys, updater);
260
+ operations.push({
261
+ type: "updateMany",
262
+ keys,
263
+ updater,
264
+ mainCache
265
+ });
266
+ },
267
+ deleteMany(keys, options2) {
268
+ innerCache.deleteMany(keys);
269
+ operations.push({
270
+ type: "deleteMany",
271
+ keys,
272
+ mainCache: options2.mainCache
273
+ });
274
+ },
275
+ clear() {
276
+ innerCache.clear();
277
+ operations.length = 0;
278
+ },
279
+ async commit() {
280
+ for (const op of operations) {
281
+ switch (op.type) {
282
+ case "set":
283
+ await op.mainCache.set(op.key, op.value);
284
+ break;
285
+ case "setMany":
286
+ await op.mainCache.setMany(op.entries);
287
+ break;
288
+ case "update":
289
+ await op.mainCache.update(
290
+ op.key,
291
+ op.updater
292
+ );
293
+ break;
294
+ case "updateMany":
295
+ await op.mainCache.updateMany(
296
+ op.keys,
297
+ op.updater
298
+ );
299
+ break;
300
+ case "delete":
301
+ await op.mainCache.delete(op.key);
302
+ break;
303
+ case "deleteMany":
304
+ await op.mainCache.deleteMany(op.keys);
305
+ break;
306
+ }
307
+ }
308
+ innerCache.clear();
309
+ operations.length = 0;
310
+ }
311
+ };
312
+ return cache;
313
+ };
314
+
315
+ // src/core/collection/filters/filters.ts
316
+ var asPlainObjectWithSingleKey = (filter, key) => filter && typeof filter === "object" && !Array.isArray(filter) && Object.keys(filter).length === 1 && key in filter ? filter : void 0;
317
+ var idFromFilter = (filter) => {
318
+ const idFilter = asPlainObjectWithSingleKey(filter, "_id");
319
+ return typeof _optionalChain([idFilter, 'optionalAccess', _15 => _15["_id"]]) === "string" ? idFilter["_id"] : void 0;
320
+ };
321
+ var getIdsFromIdOnlyFilter = (filter) => {
322
+ const idFilter = asPlainObjectWithSingleKey(filter, "_id");
323
+ if (!idFilter) return void 0;
324
+ const idValue = idFilter["_id"];
325
+ if (typeof idValue === "string") return [idValue];
326
+ const $in = idValue && typeof idValue === "object" && "$in" in idValue ? idValue["$in"] : void 0;
327
+ return Array.isArray($in) && $in.every((i) => typeof i === "string") ? $in : void 0;
328
+ };
329
+
330
+ // src/core/collection/pongoCollection.ts
331
+
332
+
333
+
334
+
335
+
336
+ var _dumbo = require('@event-driven-io/dumbo');
337
+ var _uuid = require('uuid');
338
+ var enlistIntoTransactionIfActive = async (db, options) => {
339
+ const transaction = _optionalChain([options, 'optionalAccess', _16 => _16.session, 'optionalAccess', _17 => _17.transaction]);
340
+ if (!transaction || !transaction.isActive) return null;
341
+ return await transaction.enlistDatabase(db);
342
+ };
343
+ var transactionExecutorOrDefault = async (db, options, defaultSqlExecutor) => {
344
+ const existingTransaction = await enlistIntoTransactionIfActive(db, options);
345
+ return _nullishCoalesce(_optionalChain([existingTransaction, 'optionalAccess', _18 => _18.execute]), () => ( defaultSqlExecutor));
346
+ };
347
+ var pongoCollection = ({
348
+ db,
349
+ collectionName,
350
+ pool,
351
+ schemaComponent: schemaComponent3,
352
+ schema,
353
+ errors,
354
+ serializer,
355
+ cache: cacheOptions
356
+ }) => {
357
+ const SqlFor = schemaComponent3.sqlBuilder;
358
+ const sqlExecutor = pool.execute;
359
+ const cache = pongoCache(cacheOptions);
360
+ const columnMapping = {
361
+ mapping: {
362
+ ..._dumbo.mapColumnToJSON.call(void 0, "data", serializer),
363
+ ..._dumbo.mapColumnToBigint.call(void 0, "_version")
364
+ }
365
+ };
366
+ const command = async (sql, options) => (await transactionExecutorOrDefault(db, options, sqlExecutor)).command(sql, columnMapping);
367
+ const query = async (sql, options) => (await transactionExecutorOrDefault(db, options, sqlExecutor)).query(
368
+ sql,
369
+ columnMapping
370
+ );
371
+ let shouldMigrate = _optionalChain([schema, 'optionalAccess', _19 => _19.autoMigration]) !== "None";
372
+ const createCollection = (options) => {
373
+ shouldMigrate = false;
374
+ if (_optionalChain([options, 'optionalAccess', _20 => _20.session])) return command(SqlFor.createCollection(), options);
375
+ else return command(SqlFor.createCollection());
376
+ };
377
+ const ensureCollectionCreated = (options) => {
378
+ if (!shouldMigrate) {
379
+ return Promise.resolve();
380
+ }
381
+ return createCollection(options);
382
+ };
383
+ const upcast = _nullishCoalesce(_optionalChain([schema, 'optionalAccess', _21 => _21.versioning, 'optionalAccess', _22 => _22.upcast]), () => ( ((doc) => doc)));
384
+ const downcast = _nullishCoalesce(_optionalChain([schema, 'optionalAccess', _23 => _23.versioning, 'optionalAccess', _24 => _24.downcast]), () => ( ((doc) => doc)));
385
+ const rowToDoc = (row) => upcast({
386
+ ...row.data,
387
+ _version: row._version
388
+ });
389
+ const findOneFromDb = async (filter, options) => {
390
+ const result = await query(
391
+ SqlFor.findOne(filter),
392
+ options
393
+ );
394
+ const row = result.rows[0];
395
+ return row ? rowToDoc(row) : null;
396
+ };
397
+ const cacheKey = (id) => `${db.databaseName}:${collectionName}:${id}`;
398
+ const txCacheFor = (options) => _nullishCoalesce(_optionalChain([options, 'optionalAccess', _25 => _25.session, 'optionalAccess', _26 => _26.transaction, 'optionalAccess', _27 => _27.cache]), () => ( null));
399
+ const resolveFromCache = async (key, options) => {
400
+ const txCache = txCacheFor(options);
401
+ if (txCache) {
402
+ const cached = await txCache.get(key);
403
+ if (cached !== void 0) return cached;
404
+ }
405
+ return cache.get(key);
406
+ };
407
+ const findManyFromCache = async (keys, options) => {
408
+ const txCache = txCacheFor(options);
409
+ if (!txCache) {
410
+ return cache.getMany(keys);
411
+ }
412
+ const txResults = await txCache.getMany(keys);
413
+ const mainResults = await cache.getMany(keys);
414
+ return keys.map(
415
+ (_, i) => txResults[i] !== void 0 ? txResults[i] : mainResults[i]
416
+ );
417
+ };
418
+ const fetchByIds = async (ids, options) => {
419
+ const cachedResults = await findManyFromCache(ids.map(cacheKey), options);
420
+ const missIds = ids.filter((_, i) => cachedResults[i] === void 0);
421
+ let dbDocsById = /* @__PURE__ */ new Map();
422
+ if (missIds.length > 0) {
423
+ const dbResult = await query(
424
+ SqlFor.find(
425
+ { _id: { $in: missIds } },
426
+ options
427
+ )
428
+ );
429
+ const dbDocs = dbResult.rows.map(rowToDoc);
430
+ dbDocsById = new Map(
431
+ dbDocs.map((d) => [d["_id"], d])
432
+ );
433
+ const leftovers = missIds.map(
434
+ (id) => [id, _nullishCoalesce(dbDocsById.get(id), () => ( null))]
435
+ );
436
+ await cacheSetMany(
437
+ leftovers.map((d) => d[1]).filter((d) => d !== null),
438
+ options
439
+ );
440
+ await cacheDeleteMany(
441
+ leftovers.filter(([, doc]) => doc === null).map(([id]) => id),
442
+ options
443
+ );
444
+ }
445
+ return ids.map((id, i) => {
446
+ const cached = cachedResults[i];
447
+ if (cached !== void 0) {
448
+ return cached !== null ? upcast({ ...cached }) : null;
449
+ }
450
+ return _nullishCoalesce(dbDocsById.get(id), () => ( null));
451
+ });
452
+ };
453
+ const findManyByIds = async (ids, options) => {
454
+ const results = await fetchByIds(ids, options);
455
+ return results.filter((doc) => doc !== null);
456
+ };
457
+ const cacheSet = (value, options) => {
458
+ const key = cacheKey(value._id);
459
+ const txCache = txCacheFor(options);
460
+ if (txCache) return txCache.set(key, value, { mainCache: cache });
461
+ return cache.set(key, value);
462
+ };
463
+ const cacheSetMany = (documents, options) => {
464
+ const txCache = txCacheFor(options);
465
+ const entries = documents.map((d) => ({ key: cacheKey(d._id), value: d }));
466
+ if (txCache) return txCache.setMany(entries, { mainCache: cache });
467
+ return cache.setMany(entries);
468
+ };
469
+ const cacheDelete = (id, options) => {
470
+ const txCache = txCacheFor(options);
471
+ const key = cacheKey(id);
472
+ if (txCache) return txCache.delete(key, { mainCache: cache });
473
+ return cache.delete(key);
474
+ };
475
+ const cacheDeleteMany = (ids, options) => {
476
+ const txCache = txCacheFor(options);
477
+ const keys = ids.map(cacheKey);
478
+ if (txCache) return txCache.deleteMany(keys, { mainCache: cache });
479
+ return cache.deleteMany(keys);
480
+ };
481
+ const deleteManyByIds = async (ids, options) => {
482
+ await ensureCollectionCreated(options);
483
+ const result = await command(
484
+ SqlFor.deleteManyByIds(ids),
485
+ options
486
+ );
487
+ const deletedIds = new Set(
488
+ result.rows.filter((row) => (_nullishCoalesce(row.deleted, () => ( 1))) > 0).map((row) => row._id)
489
+ );
490
+ if (!_optionalChain([options, 'optionalAccess', _28 => _28.skipCache])) {
491
+ await cacheDeleteMany([...deletedIds], options);
492
+ }
493
+ return operationResult(
494
+ {
495
+ successful: deletedIds.size > 0,
496
+ deletedCount: deletedIds.size,
497
+ matchedCount: ids.length,
498
+ deletedIds
499
+ },
500
+ {
501
+ operationName: "deleteManyByIds",
502
+ collectionName,
503
+ serializer,
504
+ errors
505
+ }
506
+ );
507
+ };
508
+ const collection = {
509
+ dbName: db.databaseName,
510
+ collectionName,
511
+ createCollection: async (options) => {
512
+ await createCollection(options);
513
+ },
514
+ insertOne: async (document, options) => {
515
+ await ensureCollectionCreated(options);
516
+ const _id = _nullishCoalesce(document._id, () => ( _uuid.v7.call(void 0, )));
517
+ const _version = _nullishCoalesce(document._version, () => ( 1n));
518
+ const downcasted = downcast(document);
519
+ const result = await command(
520
+ SqlFor.insertOne({
521
+ ...downcasted,
522
+ _id,
523
+ _version
524
+ }),
525
+ options
526
+ );
527
+ const successful = (_nullishCoalesce(result.rowCount, () => ( 0))) > 0;
528
+ if (successful && !_optionalChain([options, 'optionalAccess', _29 => _29.skipCache])) {
529
+ const doc = { ...document, _id, _version };
530
+ await cacheSet(doc, options);
531
+ }
532
+ return operationResult(
533
+ {
534
+ successful,
535
+ insertedId: successful ? _id : null,
536
+ nextExpectedVersion: _version
537
+ },
538
+ { operationName: "insertOne", collectionName, serializer, errors }
539
+ );
540
+ },
541
+ insertMany: async (documents, options) => {
542
+ await ensureCollectionCreated(options);
543
+ const documentsWithMetadata = documents.map(
544
+ (doc) => doc._id && doc._version ? doc : {
545
+ ...doc,
546
+ _id: _nullishCoalesce(doc._id, () => ( _uuid.v7.call(void 0, ))),
547
+ _version: _nullishCoalesce(doc._version, () => ( 1n))
548
+ }
549
+ );
550
+ const rows = documentsWithMetadata.map((d) => ({
551
+ ...downcast(d),
552
+ _id: d._id,
553
+ _version: d._version
554
+ }));
555
+ const result = await command(
556
+ SqlFor.insertMany(
557
+ rows
558
+ ),
559
+ options
560
+ );
561
+ if (!_optionalChain([options, 'optionalAccess', _30 => _30.skipCache])) {
562
+ const insertedIdSet = new Set(result.rows.map((d) => d._id));
563
+ await cacheSetMany(
564
+ documentsWithMetadata.filter((d) => insertedIdSet.has(d._id)),
565
+ options
566
+ );
567
+ }
568
+ return operationResult(
569
+ {
570
+ successful: result.rowCount === rows.length,
571
+ insertedCount: _nullishCoalesce(result.rowCount, () => ( 0)),
572
+ insertedIds: result.rows.map((d) => d._id)
573
+ },
574
+ { operationName: "insertMany", collectionName, serializer, errors }
575
+ );
576
+ },
577
+ updateOne: async (filter, update, options) => {
578
+ await ensureCollectionCreated(options);
579
+ const result = await command(
580
+ SqlFor.updateOne(filter, update, options),
581
+ options
582
+ );
583
+ const opResult = operationResult(
584
+ {
585
+ successful: result.rows.length > 0 && result.rows[0].modified === result.rows[0].matched,
586
+ modifiedCount: Number(_nullishCoalesce(_optionalChain([result, 'access', _31 => _31.rows, 'access', _32 => _32[0], 'optionalAccess', _33 => _33.modified]), () => ( 0))),
587
+ matchedCount: Number(_nullishCoalesce(_optionalChain([result, 'access', _34 => _34.rows, 'access', _35 => _35[0], 'optionalAccess', _36 => _36.matched]), () => ( 0))),
588
+ nextExpectedVersion: BigInt(_nullishCoalesce(_optionalChain([result, 'access', _37 => _37.rows, 'access', _38 => _38[0], 'optionalAccess', _39 => _39.version]), () => ( 0n)))
589
+ },
590
+ { operationName: "updateOne", collectionName, serializer, errors }
591
+ );
592
+ if (opResult.successful && !_optionalChain([options, 'optionalAccess', _40 => _40.skipCache])) {
593
+ const id = idFromFilter(filter);
594
+ if (id) await cacheDelete(id, options);
595
+ }
596
+ return opResult;
597
+ },
598
+ replaceOne: async (filter, document, options) => {
599
+ await ensureCollectionCreated(options);
600
+ const downcasted = downcast(document);
601
+ const result = await command(
602
+ SqlFor.replaceOne(filter, downcasted, options),
603
+ options
604
+ );
605
+ const opResult = operationResult(
606
+ {
607
+ successful: result.rows.length > 0 && result.rows[0].modified > 0,
608
+ modifiedCount: Number(_nullishCoalesce(_optionalChain([result, 'access', _41 => _41.rows, 'access', _42 => _42[0], 'optionalAccess', _43 => _43.modified]), () => ( 0))),
609
+ matchedCount: Number(_nullishCoalesce(_optionalChain([result, 'access', _44 => _44.rows, 'access', _45 => _45[0], 'optionalAccess', _46 => _46.matched]), () => ( 0))),
610
+ nextExpectedVersion: BigInt(_nullishCoalesce(_optionalChain([result, 'access', _47 => _47.rows, 'access', _48 => _48[0], 'optionalAccess', _49 => _49.version]), () => ( 0n)))
611
+ },
612
+ { operationName: "replaceOne", collectionName, serializer, errors }
613
+ );
614
+ if (opResult.successful && !_optionalChain([options, 'optionalAccess', _50 => _50.skipCache])) {
615
+ const _id = idFromFilter(filter);
616
+ if (_id) {
617
+ await cacheSet(
618
+ {
619
+ ...document,
620
+ _id,
621
+ _version: opResult.nextExpectedVersion
622
+ },
623
+ options
624
+ );
625
+ }
626
+ }
627
+ return opResult;
628
+ },
629
+ updateMany: async (filter, update, options) => {
630
+ await ensureCollectionCreated(options);
631
+ const result = await command(SqlFor.updateMany(filter, update), options);
632
+ return operationResult(
633
+ {
634
+ successful: true,
635
+ modifiedCount: _nullishCoalesce(result.rowCount, () => ( 0)),
636
+ matchedCount: _nullishCoalesce(result.rowCount, () => ( 0))
637
+ },
638
+ { operationName: "updateMany", collectionName, serializer, errors }
639
+ );
640
+ },
641
+ deleteOne: async (filter, options) => {
642
+ await ensureCollectionCreated(options);
643
+ const result = await command(
644
+ SqlFor.deleteOne(_nullishCoalesce(filter, () => ( {})), options),
645
+ options
646
+ );
647
+ const opResult = operationResult(
648
+ {
649
+ successful: result.rows.length > 0 && result.rows[0].deleted > 0,
650
+ deletedCount: Number(_nullishCoalesce(_optionalChain([result, 'access', _51 => _51.rows, 'access', _52 => _52[0], 'optionalAccess', _53 => _53.deleted]), () => ( 0))),
651
+ matchedCount: Number(_nullishCoalesce(_optionalChain([result, 'access', _54 => _54.rows, 'access', _55 => _55[0], 'optionalAccess', _56 => _56.matched]), () => ( 0)))
652
+ },
653
+ { operationName: "deleteOne", collectionName, serializer, errors }
654
+ );
655
+ if (opResult.successful && !_optionalChain([options, 'optionalAccess', _57 => _57.skipCache]) && filter) {
656
+ const id = idFromFilter(filter);
657
+ if (id) await cacheDelete(id, options);
658
+ }
659
+ return opResult;
660
+ },
661
+ deleteMany: async (filter, options) => {
662
+ const ids = filter ? getIdsFromIdOnlyFilter(filter) : null;
663
+ if (ids)
664
+ return deleteManyByIds(
665
+ ids.map((id) => ({ _id: id })),
666
+ options
667
+ );
668
+ await ensureCollectionCreated(options);
669
+ const result = await command(SqlFor.deleteMany(_nullishCoalesce(filter, () => ( {}))), options);
670
+ return operationResult(
671
+ {
672
+ successful: (_nullishCoalesce(result.rowCount, () => ( 0))) > 0,
673
+ deletedCount: _nullishCoalesce(result.rowCount, () => ( 0)),
674
+ matchedCount: _nullishCoalesce(result.rowCount, () => ( 0))
675
+ },
676
+ { operationName: "deleteMany", collectionName, serializer, errors }
677
+ );
678
+ },
679
+ findOne: async (filter, options) => {
680
+ await ensureCollectionCreated(options);
681
+ const id = filter && !_optionalChain([options, 'optionalAccess', _58 => _58.skipCache]) ? idFromFilter(filter) : null;
682
+ if (id) {
683
+ const cached = await resolveFromCache(cacheKey(id), options);
684
+ if (cached !== void 0)
685
+ return cached !== null ? upcast({
686
+ ...cached
687
+ }) : null;
688
+ const doc = await findOneFromDb(filter, options);
689
+ if (doc) await cacheSet(doc, options);
690
+ else await cacheDelete(id, options);
691
+ return doc;
692
+ }
693
+ return findOneFromDb(_nullishCoalesce(filter, () => ( {})), options);
694
+ },
695
+ findOneAndDelete: async (filter, options) => {
696
+ await ensureCollectionCreated(options);
697
+ const existingDoc = await collection.findOne(filter, options);
698
+ if (existingDoc === null) return null;
699
+ await collection.deleteOne(filter, options);
700
+ return existingDoc;
701
+ },
702
+ findOneAndReplace: async (filter, replacement, options) => {
703
+ await ensureCollectionCreated(options);
704
+ const existingDoc = await collection.findOne(filter, options);
705
+ if (existingDoc === null) return null;
706
+ await collection.replaceOne(filter, replacement, options);
707
+ return existingDoc;
708
+ },
709
+ findOneAndUpdate: async (filter, update, options) => {
710
+ await ensureCollectionCreated(options);
711
+ const existingDoc = await collection.findOne(filter, options);
712
+ if (existingDoc === null) return null;
713
+ await collection.updateOne(filter, update, options);
714
+ return existingDoc;
715
+ },
716
+ replaceMany: async (documents, options) => {
717
+ await ensureCollectionCreated(options);
718
+ const downcasted = documents.map(
719
+ (d) => downcast(d)
720
+ );
721
+ const result = await command(SqlFor.replaceMany(downcasted), options);
722
+ const modifiedIds = result.rows.map((row) => row._id);
723
+ const conflictIds = documents.map((d) => d._id).filter((id) => !modifiedIds.includes(id));
724
+ const versions = new Map(
725
+ result.rows.map((row) => [row._id, BigInt(_nullishCoalesce(row.version, () => ( 1n)))])
726
+ );
727
+ if (!_optionalChain([options, 'optionalAccess', _59 => _59.skipCache])) {
728
+ const cacheEntries = documents.filter((d) => modifiedIds.includes(d._id)).map(
729
+ (doc) => doc._version ? doc : {
730
+ ...doc,
731
+ _version: _nullishCoalesce(versions.get(doc._id), () => ( 1n))
732
+ }
733
+ );
734
+ if (cacheEntries.length > 0) await cacheSetMany(cacheEntries, options);
735
+ if (conflictIds.length > 0)
736
+ await cacheDeleteMany([...conflictIds], options);
737
+ }
738
+ return operationResult(
739
+ {
740
+ successful: modifiedIds.length > 0 && conflictIds.length === 0,
741
+ modifiedCount: modifiedIds.length,
742
+ matchedCount: documents.length,
743
+ modifiedIds: [...modifiedIds],
744
+ conflictIds: [...conflictIds],
745
+ nextExpectedVersions: versions
746
+ },
747
+ { operationName: "replaceMany", collectionName, serializer, errors }
748
+ );
749
+ },
750
+ handle: DocumentCommandHandler({
751
+ collectionName,
752
+ serializer,
753
+ errors,
754
+ storage: {
755
+ ensureCollectionCreated,
756
+ fetchByIds,
757
+ insertMany: (docs, options) => collection.insertMany(docs, options),
758
+ replaceMany: (docs, options) => collection.replaceMany(docs, options),
759
+ deleteManyByIds
760
+ }
761
+ }),
762
+ find: async (filter, options) => {
763
+ await ensureCollectionCreated(options);
764
+ if (!_optionalChain([options, 'optionalAccess', _60 => _60.skipCache]) && filter) {
765
+ const ids = getIdsFromIdOnlyFilter(filter);
766
+ if (ids && ids.length > 0) return findManyByIds(ids, options);
767
+ }
768
+ const result = await query(
769
+ SqlFor.find(_nullishCoalesce(filter, () => ( {})), options)
770
+ );
771
+ return result.rows.map(rowToDoc);
772
+ },
773
+ countDocuments: async (filter, options) => {
774
+ await ensureCollectionCreated(options);
775
+ const { count } = await _dumbo.single.call(void 0,
776
+ query(SqlFor.countDocuments(_nullishCoalesce(filter, () => ( {}))))
777
+ );
778
+ return count;
779
+ },
780
+ drop: async (options) => {
781
+ await ensureCollectionCreated(options);
782
+ const result = await command(SqlFor.drop());
783
+ return (_nullishCoalesce(_optionalChain([result, 'optionalAccess', _61 => _61.rowCount]), () => ( 0))) > 0;
784
+ },
785
+ rename: async (newName, options) => {
786
+ await ensureCollectionCreated(options);
787
+ await command(SqlFor.rename(newName));
788
+ collectionName = newName;
789
+ return collection;
790
+ },
791
+ close: () => cache.close(),
792
+ sql: {
793
+ async query(sql, options) {
794
+ await ensureCollectionCreated(options);
795
+ const result = await query(sql, options);
796
+ return result.rows;
797
+ },
798
+ async command(sql, options) {
799
+ await ensureCollectionCreated(options);
800
+ return command(sql, options);
801
+ }
802
+ },
803
+ schema: {
804
+ component: schemaComponent3,
805
+ migrate: (options) => _dumbo.runSQLMigrations.call(void 0, pool, schemaComponent3.migrations, options)
806
+ }
807
+ };
808
+ return collection;
809
+ };
810
+
811
+ // src/core/collection/pongoCollectionSchemaComponent.ts
812
+
813
+
814
+
815
+ var PongoCollectionSchemaComponent = ({
816
+ definition,
817
+ migrationsOrSchemaComponents,
818
+ sqlBuilder
819
+ }) => ({
820
+ ..._dumbo.schemaComponent.call(void 0,
821
+ `sc:pongo:collection:${definition.name}`,
822
+ migrationsOrSchemaComponents
823
+ ),
824
+ sqlBuilder,
825
+ definition,
826
+ collectionName: definition.name
827
+ });
828
+
829
+ // src/core/collection/query.ts
830
+ var QueryOperators = {
831
+ $eq: "$eq",
832
+ $gt: "$gt",
833
+ $gte: "$gte",
834
+ $lt: "$lt",
835
+ $lte: "$lte",
836
+ $ne: "$ne",
837
+ $in: "$in",
838
+ $nin: "$nin",
839
+ $elemMatch: "$elemMatch",
840
+ $all: "$all",
841
+ $size: "$size"
842
+ };
843
+ var OperatorMap = {
844
+ $gt: ">",
845
+ $gte: ">=",
846
+ $lt: "<",
847
+ $lte: "<=",
848
+ $ne: "!="
849
+ };
850
+ var isOperator = (key) => key.startsWith("$");
851
+ var hasOperators = (value) => Object.keys(value).some(isOperator);
852
+
853
+ // src/core/database/pongoDatabaseCache.ts
854
+
855
+
856
+
857
+ var PongoDatabaseCache = ({
858
+ driver,
859
+ typedSchema
860
+ }) => {
861
+ const dbClients = /* @__PURE__ */ new Map();
862
+ const getDatabaseDefinition = (dbName) => Object.values(_nullishCoalesce(_optionalChain([typedSchema, 'optionalAccess', _62 => _62.dbs]), () => ( {}))).find((d) => d.name === dbName);
863
+ return {
864
+ getOrCreate: (createOptions) => {
865
+ const metadata = _dumbo.getDatabaseMetadata.call(void 0, driver.driverType);
866
+ const dbName = _nullishCoalesce(_nullishCoalesce(createOptions.databaseName, () => ( _optionalChain([metadata, 'optionalAccess', _63 => _63.parseDatabaseName, 'optionalCall', _64 => _64(
867
+ "connectionString" in createOptions ? createOptions.connectionString : void 0
868
+ )]))), () => ( "db:default"));
869
+ const existing = dbClients.get(dbName);
870
+ if (existing) return existing;
871
+ const definition = getDatabaseDefinition(createOptions.databaseName);
872
+ const newDb = driver.databaseFactory({
873
+ ...createOptions,
874
+ databaseName: dbName,
875
+ schema: {
876
+ ...createOptions.schema,
877
+ ...definition ? { definition } : {}
878
+ }
879
+ });
880
+ dbClients.set(dbName, newDb);
881
+ return newDb;
882
+ },
883
+ all: () => Array.from(dbClients.values()),
884
+ forAll: (func) => {
885
+ return Promise.all(
886
+ Array.from(dbClients.values()).map((v) => v).map(func)
887
+ );
888
+ }
889
+ };
890
+ };
891
+
892
+ // src/core/database/pongoDatabaseSchemaComponent.ts
893
+
894
+
895
+
896
+
897
+ // src/core/typing/entries.ts
898
+ var objectEntries = (obj) => Object.entries(obj).map(([key, value]) => [key, value]);
899
+
900
+ // src/core/typing/operations.ts
901
+
902
+
903
+ // src/core/errors/index.ts
904
+ var isNumber = (val) => typeof val === "number" && val === val;
905
+ var isString = (val) => typeof val === "string";
906
+ var PongoError = class _PongoError extends Error {
907
+
908
+ constructor(options) {
909
+ const errorCode = options && typeof options === "object" && "errorCode" in options ? options.errorCode : isNumber(options) ? options : 500;
910
+ const message = options && typeof options === "object" && "message" in options ? options.message : isString(options) ? options : `Error with status code '${errorCode}' ocurred during Pongo processing`;
911
+ super(message);
912
+ this.errorCode = errorCode;
913
+ Object.setPrototypeOf(this, _PongoError.prototype);
914
+ }
915
+ };
916
+ var ConcurrencyError = class _ConcurrencyError extends PongoError {
917
+ constructor(message) {
918
+ super({
919
+ errorCode: 412,
920
+ message: _nullishCoalesce(message, () => ( `Expected document state does not match current one!`))
921
+ });
922
+ Object.setPrototypeOf(this, _ConcurrencyError.prototype);
923
+ }
924
+ };
925
+
926
+ // src/core/typing/operations.ts
927
+ var ObjectId = (value) => _nullishCoalesce(value, () => ( _uuid.v7.call(void 0, )));
928
+ var DOCUMENT_EXISTS = "DOCUMENT_EXISTS";
929
+ var DOCUMENT_DOES_NOT_EXIST = "DOCUMENT_DOES_NOT_EXIST";
930
+ var NO_CONCURRENCY_CHECK = "NO_CONCURRENCY_CHECK";
931
+ var isGeneralExpectedDocumentVersion = (version) => version === "DOCUMENT_DOES_NOT_EXIST" || version === "DOCUMENT_EXISTS" || version === "NO_CONCURRENCY_CHECK";
932
+ var expectedVersionValue = (version) => version === void 0 || isGeneralExpectedDocumentVersion(version) ? null : version;
933
+ var expectedVersion = (version) => {
934
+ return version ? BigInt(version) : NO_CONCURRENCY_CHECK;
935
+ };
936
+ var operationResult = (result, options) => {
937
+ const operationResult2 = {
938
+ ...result,
939
+ acknowledged: true,
940
+ successful: result.successful,
941
+ assertSuccessful: (errorMessage) => {
942
+ const { successful } = result;
943
+ const { operationName, collectionName } = options;
944
+ if (!successful)
945
+ throw new ConcurrencyError(
946
+ _nullishCoalesce(errorMessage, () => ( `${operationName} on ${collectionName} failed. Expected document state does not match current one! Result: ${options.serializer.serialize(result)}!`))
947
+ );
948
+ }
949
+ };
950
+ if (_optionalChain([options, 'access', _65 => _65.errors, 'optionalAccess', _66 => _66.throwOnOperationFailures]))
951
+ operationResult2.assertSuccessful();
952
+ return operationResult2;
953
+ };
954
+
955
+ // src/core/schema/index.ts
956
+ var pongoCollectionSchema = (name) => ({
957
+ name
958
+ });
959
+ pongoCollectionSchema.from = (collectionNames) => collectionNames.reduce(
960
+ (acc, collectionName) => (acc[collectionName] = pongoSchema.collection(collectionName), acc),
961
+ {}
962
+ );
963
+ function pongoDbSchema(nameOrCollections, collections) {
964
+ if (collections === void 0) {
965
+ if (typeof nameOrCollections === "string") {
966
+ throw new Error("You need to provide colleciton definition");
967
+ }
968
+ return {
969
+ collections: nameOrCollections
970
+ };
971
+ }
972
+ return nameOrCollections && typeof nameOrCollections === "string" ? {
973
+ name: nameOrCollections,
974
+ collections
975
+ } : { collections };
976
+ }
977
+ pongoDbSchema.from = (databaseName, collectionNames) => databaseName ? pongoDbSchema(databaseName, pongoCollectionSchema.from(collectionNames)) : pongoDbSchema(pongoCollectionSchema.from(collectionNames));
978
+ var pongoClientSchema = (dbs) => ({
979
+ dbs
980
+ });
981
+ var pongoSchema = {
982
+ client: pongoClientSchema,
983
+ db: pongoDbSchema,
984
+ collection: pongoCollectionSchema
985
+ };
986
+ var proxyPongoDbWithSchema = (pongoDb, dbSchema, collections) => {
987
+ const collectionNames = Object.keys(dbSchema.collections);
988
+ for (const collectionName of collectionNames) {
989
+ collections.set(collectionName, pongoDb.collection(collectionName));
990
+ }
991
+ return new Proxy(
992
+ pongoDb,
993
+ {
994
+ get(target, prop) {
995
+ return _nullishCoalesce(collections.get(prop), () => ( target[prop]));
996
+ }
997
+ }
998
+ );
999
+ };
1000
+ var proxyClientWithSchema = (client, schema) => {
1001
+ if (!schema)
1002
+ return client;
1003
+ const dbNames = Object.keys(schema.dbs);
1004
+ return new Proxy(
1005
+ client,
1006
+ {
1007
+ get(target, prop) {
1008
+ if (dbNames.includes(prop)) return client.db(_optionalChain([schema, 'access', _67 => _67.dbs, 'access', _68 => _68[prop], 'optionalAccess', _69 => _69.name]));
1009
+ return target[prop];
1010
+ }
1011
+ }
1012
+ );
1013
+ };
1014
+ var toDbSchemaMetadata = (schema) => ({
1015
+ name: schema.name,
1016
+ collections: objectEntries(schema.collections).map((c) => ({
1017
+ name: c[1].name
1018
+ }))
1019
+ });
1020
+ var toClientSchemaMetadata = (schema) => {
1021
+ const databases = objectEntries(schema.dbs).map(
1022
+ (e) => toDbSchemaMetadata(e[1])
1023
+ );
1024
+ return {
1025
+ databases,
1026
+ database: (name) => databases.find((db) => db.name === name)
1027
+ };
1028
+ };
1029
+
1030
+ // src/core/database/pongoDatabaseSchemaComponent.ts
1031
+ var PongoDatabaseSchemaComponent = ({
1032
+ definition,
1033
+ collectionFactory
1034
+ }) => {
1035
+ const collections = _nullishCoalesce(Object.values(definition.collections).map(collectionFactory), () => ( []));
1036
+ return {
1037
+ ..._dumbo.schemaComponent.call(void 0, `sc:dumbo:database:${definition.name}`, {
1038
+ components: collections
1039
+ }),
1040
+ definition,
1041
+ collections,
1042
+ collection: (schema) => {
1043
+ const existing = collections.find(
1044
+ (c) => c.collectionName === schema.name
1045
+ );
1046
+ if (existing) return existing;
1047
+ const newCollection = collectionFactory(
1048
+ pongoSchema.collection(schema.name)
1049
+ );
1050
+ collections.push(newCollection);
1051
+ definition.collections[schema.name] = schema;
1052
+ return newCollection;
1053
+ }
1054
+ };
1055
+ };
1056
+
1057
+ // src/core/database/pongoDb.ts
1058
+
1059
+
1060
+
1061
+ var PongoDatabase = (options) => {
1062
+ const {
1063
+ databaseName,
1064
+ schemaComponent: schemaComponent3,
1065
+ pool,
1066
+ cache: cacheOptions,
1067
+ serializer
1068
+ } = options;
1069
+ const cache = cacheOptions === "disabled" || cacheOptions === void 0 ? "disabled" : pongoCache(cacheOptions);
1070
+ const collections = /* @__PURE__ */ new Map();
1071
+ const command = async (sql, options2) => (await transactionExecutorOrDefault(db, options2, pool.execute)).command(sql, options2);
1072
+ const query = async (sql, options2) => (await transactionExecutorOrDefault(db, options2, pool.execute)).query(
1073
+ sql,
1074
+ options2
1075
+ );
1076
+ const driverType = pool.driverType;
1077
+ const db = {
1078
+ driverType,
1079
+ databaseName,
1080
+ connect: () => Promise.resolve(),
1081
+ close: async () => {
1082
+ await Promise.allSettled([
1083
+ pool.close(),
1084
+ cache !== "disabled" ? cache.close() : Promise.resolve(),
1085
+ ...collections.values().map((collection) => collection.close())
1086
+ ]);
1087
+ },
1088
+ collections: () => [...collections.values()],
1089
+ collection: (collectionName, collectionOptions) => _nullishCoalesce(collections.get(collectionName), () => ( pongoCollection({
1090
+ collectionName,
1091
+ db,
1092
+ pool,
1093
+ schemaComponent: schemaComponent3.collection(
1094
+ pongoSchema.collection(collectionName)
1095
+ ),
1096
+ schema: { ...options.schema, ..._optionalChain([collectionOptions, 'optionalAccess', _70 => _70.schema]) },
1097
+ serializer,
1098
+ errors: { ...options.errors, ..._optionalChain([collectionOptions, 'optionalAccess', _71 => _71.errors]) },
1099
+ cache: _optionalChain([collectionOptions, 'optionalAccess', _72 => _72.cache]) !== void 0 ? collectionOptions.cache : cache
1100
+ }))),
1101
+ transaction: () => pool.transaction(),
1102
+ withTransaction: (handle) => pool.withTransaction(handle),
1103
+ schema: {
1104
+ component: schemaComponent3,
1105
+ migrate: (options2) => _dumbo.runSQLMigrations.call(void 0, pool, schemaComponent3.migrations, options2)
1106
+ },
1107
+ sql: {
1108
+ async query(sql, options2) {
1109
+ const result = await query(sql, options2);
1110
+ return result.rows;
1111
+ },
1112
+ async command(sql, options2) {
1113
+ return command(sql, options2);
1114
+ }
1115
+ }
1116
+ };
1117
+ const dbSchema = _optionalChain([options, 'optionalAccess', _73 => _73.schema, 'optionalAccess', _74 => _74.definition]);
1118
+ if (dbSchema) {
1119
+ return proxyPongoDbWithSchema(db, dbSchema, collections);
1120
+ }
1121
+ return db;
1122
+ };
1123
+
1124
+ // src/core/drivers/databaseDriver.ts
1125
+ var PongoDriverRegistry = () => {
1126
+ const drivers = /* @__PURE__ */ new Map();
1127
+ const register = (driverType, driver) => {
1128
+ const entry = drivers.get(driverType);
1129
+ if (entry && (typeof entry !== "function" || typeof driver === "function")) {
1130
+ return;
1131
+ }
1132
+ drivers.set(driverType, driver);
1133
+ };
1134
+ const tryResolve = async (driverType) => {
1135
+ const entry = drivers.get(driverType);
1136
+ if (!entry) return null;
1137
+ if (typeof entry !== "function") return entry;
1138
+ const driver = await entry();
1139
+ register(driverType, driver);
1140
+ return driver;
1141
+ };
1142
+ const tryGet = (driverType) => {
1143
+ const entry = drivers.get(driverType);
1144
+ return entry && typeof entry !== "function" ? entry : null;
1145
+ };
1146
+ const has = (driverType) => drivers.has(driverType);
1147
+ return {
1148
+ register,
1149
+ tryResolve,
1150
+ tryGet,
1151
+ has,
1152
+ get databaseDriverTypes() {
1153
+ return Array.from(drivers.keys());
1154
+ }
1155
+ };
1156
+ };
1157
+ var pongoDriverRegistry = globalThis.pongoDriverRegistry = _nullishCoalesce(globalThis.pongoDriverRegistry, () => ( PongoDriverRegistry()));
1158
+
1159
+ // src/core/pongoClient.ts
1160
+
1161
+
1162
+ // src/core/pongoTransaction.ts
1163
+ var pongoTransaction = (options) => {
1164
+ let isCommitted = false;
1165
+ let isRolledBack = false;
1166
+ let databaseName = null;
1167
+ let transaction = null;
1168
+ const cache = pongoTransactionCache();
1169
+ return {
1170
+ cache,
1171
+ enlistDatabase: async (db) => {
1172
+ if (transaction && databaseName !== db.databaseName)
1173
+ throw new Error(
1174
+ "There's already other database assigned to transaction"
1175
+ );
1176
+ if (transaction && databaseName === db.databaseName) return transaction;
1177
+ databaseName = db.databaseName;
1178
+ transaction = db.transaction();
1179
+ await transaction.begin();
1180
+ return transaction;
1181
+ },
1182
+ commit: async () => {
1183
+ if (isCommitted) return;
1184
+ if (isRolledBack) throw new Error("Transaction is not active!");
1185
+ isCommitted = true;
1186
+ if (transaction) {
1187
+ await transaction.commit();
1188
+ transaction = null;
1189
+ }
1190
+ await cache.commit();
1191
+ },
1192
+ rollback: async (error) => {
1193
+ if (isCommitted) throw new Error("Cannot rollback commited transaction!");
1194
+ if (isRolledBack) return;
1195
+ isRolledBack = true;
1196
+ if (transaction) {
1197
+ await transaction.rollback(error);
1198
+ transaction = null;
1199
+ }
1200
+ cache.clear();
1201
+ },
1202
+ databaseName,
1203
+ isStarting: false,
1204
+ isCommitted,
1205
+ get isActive() {
1206
+ return !isCommitted && !isRolledBack;
1207
+ },
1208
+ get sqlExecutor() {
1209
+ if (transaction === null)
1210
+ throw new Error("No database transaction was started");
1211
+ return transaction.execute;
1212
+ },
1213
+ options
1214
+ };
1215
+ };
1216
+
1217
+ // src/core/pongoSession.ts
1218
+ var isActive = (transaction) => _optionalChain([transaction, 'optionalAccess', _75 => _75.isActive]) === true;
1219
+ function assertInActiveTransaction(transaction) {
1220
+ if (!isActive(transaction)) throw new Error("No active transaction exists!");
1221
+ }
1222
+ function assertNotInActiveTransaction(transaction) {
1223
+ if (isActive(transaction))
1224
+ throw new Error("Active transaction already exists!");
1225
+ }
1226
+ var pongoSession = (options) => {
1227
+ const explicit = _optionalChain([options, 'optionalAccess', _76 => _76.explicit]) === true;
1228
+ const defaultTransactionOptions = _nullishCoalesce(_optionalChain([options, 'optionalAccess', _77 => _77.defaultTransactionOptions]), () => ( {
1229
+ get snapshotEnabled() {
1230
+ return false;
1231
+ }
1232
+ }));
1233
+ let transaction = null;
1234
+ let hasEnded = false;
1235
+ const startTransaction = (options2) => {
1236
+ assertNotInActiveTransaction(transaction);
1237
+ transaction = pongoTransaction(_nullishCoalesce(options2, () => ( defaultTransactionOptions)));
1238
+ };
1239
+ const commitTransaction = async () => {
1240
+ assertInActiveTransaction(transaction);
1241
+ await transaction.commit();
1242
+ };
1243
+ const abortTransaction = async () => {
1244
+ assertInActiveTransaction(transaction);
1245
+ await transaction.rollback();
1246
+ };
1247
+ const endSession = async () => {
1248
+ if (hasEnded) return;
1249
+ hasEnded = true;
1250
+ if (isActive(transaction)) await transaction.rollback();
1251
+ };
1252
+ const session = {
1253
+ get hasEnded() {
1254
+ return hasEnded;
1255
+ },
1256
+ explicit,
1257
+ defaultTransactionOptions: _nullishCoalesce(defaultTransactionOptions, () => ( {
1258
+ get snapshotEnabled() {
1259
+ return false;
1260
+ }
1261
+ })),
1262
+ get transaction() {
1263
+ return transaction;
1264
+ },
1265
+ get snapshotEnabled() {
1266
+ return defaultTransactionOptions.snapshotEnabled;
1267
+ },
1268
+ endSession,
1269
+ incrementTransactionNumber: () => {
1270
+ },
1271
+ inTransaction: () => isActive(transaction),
1272
+ startTransaction,
1273
+ commitTransaction,
1274
+ abortTransaction,
1275
+ withTransaction: async (fn, options2) => {
1276
+ startTransaction(options2);
1277
+ try {
1278
+ const result = await fn(session);
1279
+ await commitTransaction();
1280
+ return result;
1281
+ } catch (error) {
1282
+ await abortTransaction();
1283
+ throw error;
1284
+ }
1285
+ }
1286
+ };
1287
+ return session;
1288
+ };
1289
+
1290
+ // src/core/pongoClient.ts
1291
+ var pongoClient = (options) => {
1292
+ const {
1293
+ driver,
1294
+ schema,
1295
+ errors,
1296
+ cache: cacheOptions,
1297
+ serialization,
1298
+ ...connectionOptions
1299
+ } = options;
1300
+ const dbClients = PongoDatabaseCache({
1301
+ driver,
1302
+ typedSchema: _optionalChain([schema, 'optionalAccess', _78 => _78.definition])
1303
+ });
1304
+ const serializer = _dumbo.JSONSerializer.from(options);
1305
+ const cache = cacheOptions === "disabled" || cacheOptions === void 0 ? "disabled" : pongoCache(cacheOptions);
1306
+ const pongoClient2 = {
1307
+ driverType: driver.driverType,
1308
+ connect: async () => {
1309
+ await dbClients.forAll((db) => db.connect());
1310
+ return pongoClient2;
1311
+ },
1312
+ close: async () => {
1313
+ await dbClients.forAll((db) => db.close());
1314
+ },
1315
+ db: (dbName, options2) => {
1316
+ const db = dbClients.getOrCreate({
1317
+ ...connectionOptions,
1318
+ databaseName: dbName,
1319
+ serializer,
1320
+ errors,
1321
+ cache: _nullishCoalesce(_optionalChain([options2, 'optionalAccess', _79 => _79.cache]), () => ( cache)),
1322
+ serialization
1323
+ });
1324
+ return db;
1325
+ },
1326
+ startSession: pongoSession,
1327
+ withSession: async (callback) => {
1328
+ const session = pongoSession();
1329
+ try {
1330
+ return await callback(session);
1331
+ } finally {
1332
+ await session.endSession();
1333
+ }
1334
+ }
1335
+ };
1336
+ return proxyClientWithSchema(pongoClient2, _optionalChain([schema, 'optionalAccess', _80 => _80.definition]));
1337
+ };
1338
+
1339
+ // src/core/utils/deepEquals.ts
1340
+ var deepEquals = (left, right) => {
1341
+ if (isEquatable(left)) {
1342
+ return left.equals(right);
1343
+ }
1344
+ if (Array.isArray(left)) {
1345
+ return Array.isArray(right) && left.length === right.length && left.every((val, index) => deepEquals(val, right[index]));
1346
+ }
1347
+ if (typeof left !== "object" || typeof right !== "object" || left === null || right === null) {
1348
+ return left === right;
1349
+ }
1350
+ if (Array.isArray(right)) return false;
1351
+ const keys1 = Object.keys(left);
1352
+ const keys2 = Object.keys(right);
1353
+ if (keys1.length !== keys2.length || !keys1.every((key) => keys2.includes(key)))
1354
+ return false;
1355
+ for (const key in left) {
1356
+ if (left[key] instanceof Function && right[key] instanceof Function)
1357
+ continue;
1358
+ const isEqual = deepEquals(left[key], right[key]);
1359
+ if (!isEqual) {
1360
+ return false;
1361
+ }
1362
+ }
1363
+ return true;
1364
+ };
1365
+ var isEquatable = (left) => {
1366
+ return left && typeof left === "object" && "equals" in left && typeof left["equals"] === "function";
1367
+ };
1368
+
1369
+ // src/core/utils/mapAsync.ts
1370
+ async function mapSequential(items, fn) {
1371
+ const results = [];
1372
+ for (let i = 0; i < items.length; i++) {
1373
+ results.push(await fn(items[i], i));
1374
+ }
1375
+ return results;
1376
+ }
1377
+ var mapParallel = (items, fn) => Promise.all(items.map(fn));
1378
+ var mapAsync = (items, fn, options = { parallel: false }) => _optionalChain([options, 'optionalAccess', _81 => _81.parallel]) ? mapParallel(items, fn) : mapSequential(items, fn);
1379
+
1380
+ // src/core/collection/handle.ts
1381
+ function DocumentCommandHandler(deps) {
1382
+ const fn = async (input, handler, options) => {
1383
+ const changes = await handleDocuments(
1384
+ deps.storage,
1385
+ normalizeInput(input),
1386
+ handler,
1387
+ options
1388
+ );
1389
+ const results = changes.map(
1390
+ ({ change, result: outcome }) => toHandleResult(deps, change, outcome)
1391
+ );
1392
+ return Array.isArray(input) ? results : results[0];
1393
+ };
1394
+ return fn;
1395
+ }
1396
+ async function handleDocuments(storage, inputs, handler, options) {
1397
+ if (inputs.length === 0) return [];
1398
+ const { parallel, ...operationOptions } = _nullishCoalesce(options, () => ( {}));
1399
+ await storage.ensureCollectionCreated(operationOptions);
1400
+ const docs = await storage.fetchByIds(
1401
+ inputs.map((i) => i._id),
1402
+ operationOptions
1403
+ );
1404
+ const changes = await mapAsync(
1405
+ inputs,
1406
+ (item, i) => handleDocument(
1407
+ {
1408
+ ...item,
1409
+ existing: _nullishCoalesce(docs[i], () => ( null))
1410
+ },
1411
+ handler
1412
+ ),
1413
+ { parallel }
1414
+ );
1415
+ return await executeStorageChanges(storage, changes, operationOptions);
1416
+ }
1417
+ async function handleDocument(item, handler) {
1418
+ const { _id: id, existing, expectedVersion: expectedVersion2 } = item;
1419
+ if (hasVersionMismatch(existing, expectedVersion2))
1420
+ return { type: "noop", existing, versionMismatch: true };
1421
+ const result = await handler(existing ? { ...existing } : null, id);
1422
+ return toDocumentChange(id, existing, result);
1423
+ }
1424
+ async function executeStorageChanges(storage, changes, operationOptions) {
1425
+ const toInsert = changes.flatMap(
1426
+ (c) => c.type === "insert" ? [c.doc] : []
1427
+ );
1428
+ const toReplace = changes.flatMap((c) => {
1429
+ if (c.type !== "replace") return [];
1430
+ const { _version: _, ...cleanResult } = c.result;
1431
+ return [
1432
+ c._version !== void 0 ? { ...cleanResult, _version: c._version } : cleanResult
1433
+ ];
1434
+ });
1435
+ const toDelete = changes.flatMap(
1436
+ (c) => c.type === "delete" ? [
1437
+ c._version !== void 0 ? { _id: c.docId, _version: c._version } : { _id: c.docId }
1438
+ ] : []
1439
+ );
1440
+ const insertedIds = toInsert.length > 0 ? new Set(
1441
+ (await storage.insertMany(toInsert, operationOptions)).insertedIds
1442
+ ) : /* @__PURE__ */ new Set();
1443
+ const replaceResult = toReplace.length > 0 ? await storage.replaceMany(toReplace, operationOptions) : null;
1444
+ const deletedIds = toDelete.length > 0 ? (await storage.deleteManyByIds(toDelete, operationOptions)).deletedIds : /* @__PURE__ */ new Set();
1445
+ const toDocumentHandlerResult = (change) => {
1446
+ if (change.type === "noop") return { succeeded: !change.versionMismatch };
1447
+ if (change.type === "insert")
1448
+ return { succeeded: insertedIds.has(change.doc._id), newVersion: 1n };
1449
+ if (change.type === "delete")
1450
+ return { succeeded: deletedIds.has(change.docId) };
1451
+ const id = change.result._id;
1452
+ return {
1453
+ succeeded: _nullishCoalesce(_optionalChain([replaceResult, 'optionalAccess', _82 => _82.modifiedIds, 'access', _83 => _83.includes, 'call', _84 => _84(id)]), () => ( false)),
1454
+ newVersion: _nullishCoalesce(_optionalChain([replaceResult, 'optionalAccess', _85 => _85.nextExpectedVersions, 'access', _86 => _86.get, 'call', _87 => _87(id)]), () => ( 0n))
1455
+ };
1456
+ };
1457
+ return changes.map((change) => ({
1458
+ change,
1459
+ result: toDocumentHandlerResult(change)
1460
+ }));
1461
+ }
1462
+ function normalizeInput(input) {
1463
+ if (typeof input === "string") return [{ _id: input }];
1464
+ if (!Array.isArray(input)) return [input];
1465
+ return input.map((item) => typeof item === "string" ? { _id: item } : item);
1466
+ }
1467
+ function hasVersionMismatch(existing, version) {
1468
+ const expected = expectedVersionValue(version);
1469
+ return existing == null && version === "DOCUMENT_EXISTS" || existing == null && expected != null || existing != null && version === "DOCUMENT_DOES_NOT_EXIST" || existing != null && expected !== null && existing._version !== expected;
1470
+ }
1471
+ function toDocumentChange(docId, existing, result) {
1472
+ if (deepEquals(existing, result))
1473
+ return { type: "noop", existing };
1474
+ if (!existing && result)
1475
+ return {
1476
+ type: "insert",
1477
+ doc: { ...result, _id: docId }
1478
+ };
1479
+ if (existing && !result)
1480
+ return {
1481
+ type: "delete",
1482
+ docId,
1483
+ _version: existing._version
1484
+ };
1485
+ return {
1486
+ type: "replace",
1487
+ existing,
1488
+ result: { ...result, _id: docId },
1489
+ _version: existing._version
1490
+ };
1491
+ }
1492
+ function toHandleResult(deps, change, { succeeded, newVersion }) {
1493
+ const opMeta = {
1494
+ operationName: "handle",
1495
+ collectionName: deps.collectionName,
1496
+ serializer: deps.serializer,
1497
+ errors: deps.errors
1498
+ };
1499
+ const toResult = (op, document) => ({
1500
+ ...operationResult(op, opMeta),
1501
+ document
1502
+ });
1503
+ if (change.type === "noop")
1504
+ return toResult({ successful: succeeded }, change.existing);
1505
+ if (change.type === "insert")
1506
+ return toResult(
1507
+ {
1508
+ successful: succeeded,
1509
+ insertedId: succeeded ? change.doc._id : null,
1510
+ nextExpectedVersion: 1n
1511
+ },
1512
+ succeeded ? { ...change.doc, _version: 1n } : null
1513
+ );
1514
+ if (change.type === "delete")
1515
+ return toResult(
1516
+ {
1517
+ successful: succeeded,
1518
+ deletedCount: succeeded ? 1 : 0,
1519
+ matchedCount: 1
1520
+ },
1521
+ null
1522
+ );
1523
+ return toResult(
1524
+ {
1525
+ successful: succeeded,
1526
+ modifiedCount: succeeded ? 1 : 0,
1527
+ matchedCount: 1,
1528
+ nextExpectedVersion: _nullishCoalesce(newVersion, () => ( 0n))
1529
+ },
1530
+ succeeded ? { ...change.result, _version: newVersion } : change.existing
1531
+ );
1532
+ }
1533
+
1534
+
1535
+
1536
+
1537
+
1538
+
1539
+
1540
+
1541
+
1542
+
1543
+
1544
+
1545
+
1546
+
1547
+
1548
+
1549
+
1550
+
1551
+
1552
+
1553
+
1554
+
1555
+
1556
+
1557
+
1558
+
1559
+
1560
+
1561
+
1562
+
1563
+
1564
+
1565
+
1566
+
1567
+
1568
+
1569
+
1570
+
1571
+
1572
+
1573
+
1574
+
1575
+
1576
+
1577
+
1578
+
1579
+
1580
+
1581
+
1582
+ exports.pongoCacheWrapper = pongoCacheWrapper; exports.identityMapCache = identityMapCache; exports.lruCache = lruCache; exports.noopCacheProvider = noopCacheProvider; exports.pongoCache = pongoCache; exports.pongoTransactionCache = pongoTransactionCache; exports.idFromFilter = idFromFilter; exports.getIdsFromIdOnlyFilter = getIdsFromIdOnlyFilter; exports.DocumentCommandHandler = DocumentCommandHandler; exports.transactionExecutorOrDefault = transactionExecutorOrDefault; exports.pongoCollection = pongoCollection; exports.PongoCollectionSchemaComponent = PongoCollectionSchemaComponent; exports.QueryOperators = QueryOperators; exports.OperatorMap = OperatorMap; exports.isOperator = isOperator; exports.hasOperators = hasOperators; exports.PongoDatabaseCache = PongoDatabaseCache; exports.objectEntries = objectEntries; exports.isNumber = isNumber; exports.isString = isString; exports.PongoError = PongoError; exports.ConcurrencyError = ConcurrencyError; exports.ObjectId = ObjectId; exports.DOCUMENT_EXISTS = DOCUMENT_EXISTS; exports.DOCUMENT_DOES_NOT_EXIST = DOCUMENT_DOES_NOT_EXIST; exports.NO_CONCURRENCY_CHECK = NO_CONCURRENCY_CHECK; exports.isGeneralExpectedDocumentVersion = isGeneralExpectedDocumentVersion; exports.expectedVersionValue = expectedVersionValue; exports.expectedVersion = expectedVersion; exports.operationResult = operationResult; exports.pongoSchema = pongoSchema; exports.proxyPongoDbWithSchema = proxyPongoDbWithSchema; exports.proxyClientWithSchema = proxyClientWithSchema; exports.toDbSchemaMetadata = toDbSchemaMetadata; exports.toClientSchemaMetadata = toClientSchemaMetadata; exports.PongoDatabaseSchemaComponent = PongoDatabaseSchemaComponent; exports.PongoDatabase = PongoDatabase; exports.PongoDriverRegistry = PongoDriverRegistry; exports.pongoDriverRegistry = pongoDriverRegistry; exports.pongoTransaction = pongoTransaction; exports.pongoSession = pongoSession; exports.pongoClient = pongoClient; exports.deepEquals = deepEquals; exports.isEquatable = isEquatable; exports.mapSequential = mapSequential; exports.mapParallel = mapParallel; exports.mapAsync = mapAsync;
1583
+ //# sourceMappingURL=chunk-EQ3T4XHT.cjs.map