@routier/pouchdb-plugin 0.4.0 → 0.5.1
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.
- package/dist/PouchDbTranslator.d.ts +6 -1
- package/dist/index.cjs +51 -21
- package/dist/index.cjs.map +1 -1
- package/dist/index.js +53 -22
- package/dist/index.js.map +1 -1
- package/package.json +6 -6
|
@@ -1,6 +1,11 @@
|
|
|
1
1
|
import { IQuery, JsonTranslator } from "@routier/core/plugins";
|
|
2
2
|
export declare class PouchDbTranslator<TEntity extends {}, TShape extends unknown = TEntity> extends JsonTranslator<TEntity, TShape> {
|
|
3
|
-
|
|
3
|
+
/**
|
|
4
|
+
* PouchDB stores JSON, so a date comes back as the ISO string the datastore serialized it to.
|
|
5
|
+
* The caller's lambdas compare and call Dates, so every document is revived before one runs.
|
|
6
|
+
* Only the dates: keys stay under their `from` names. `null` for a schema with no dates.
|
|
7
|
+
*/
|
|
8
|
+
private readonly reviveDates;
|
|
4
9
|
private cachedMatches;
|
|
5
10
|
constructor(query: IQuery<TEntity, TShape>);
|
|
6
11
|
matches(item: unknown): boolean;
|
package/dist/index.cjs
CHANGED
|
@@ -55,19 +55,27 @@ var external_pouchdb_default = /*#__PURE__*/__webpack_require__.n(external_pouch
|
|
|
55
55
|
const assertions_namespaceObject = require("@routier/core/assertions");
|
|
56
56
|
;// CONCATENATED MODULE: external "@routier/core/plugins"
|
|
57
57
|
const plugins_namespaceObject = require("@routier/core/plugins");
|
|
58
|
+
;// CONCATENATED MODULE: external "@routier/core/schema"
|
|
59
|
+
const schema_namespaceObject = require("@routier/core/schema");
|
|
58
60
|
;// CONCATENATED MODULE: ./src/PouchDbTranslator.ts
|
|
59
61
|
|
|
60
62
|
|
|
63
|
+
|
|
61
64
|
class PouchDbTranslator extends plugins_namespaceObject.JsonTranslator {
|
|
62
|
-
|
|
65
|
+
/**
|
|
66
|
+
* PouchDB stores JSON, so a date comes back as the ISO string the datastore serialized it to.
|
|
67
|
+
* The caller's lambdas compare and call Dates, so every document is revived before one runs.
|
|
68
|
+
* Only the dates: keys stay under their `from` names. `null` for a schema with no dates.
|
|
69
|
+
*/ reviveDates;
|
|
63
70
|
cachedMatches = null;
|
|
64
71
|
constructor(query){
|
|
65
72
|
super(query);
|
|
66
|
-
this.
|
|
73
|
+
this.reviveDates = (0,schema_namespaceObject.getStorageDateReviver)(query.schema);
|
|
67
74
|
}
|
|
68
75
|
matches(item) {
|
|
69
76
|
// Get or build cached filter chain
|
|
70
77
|
const filterChain = this.resolveFilterChain();
|
|
78
|
+
this.reviveDates?.(item);
|
|
71
79
|
// Execute the chain (no loops, just recursive function calls)
|
|
72
80
|
return filterChain(item);
|
|
73
81
|
}
|
|
@@ -78,7 +86,8 @@ class PouchDbTranslator extends plugins_namespaceObject.JsonTranslator {
|
|
|
78
86
|
}
|
|
79
87
|
// Build and cache the filter chain
|
|
80
88
|
const filters = this.query.options.get("filter");
|
|
81
|
-
|
|
89
|
+
// Not a filter the plugin reported: the datastore runs that one, after deserialization
|
|
90
|
+
const databaseFilters = filters.filter((x)=>x.option.target === "database" && x.option.reason === "executed");
|
|
82
91
|
this.cachedMatches = this.buildFilterChain(databaseFilters, 0);
|
|
83
92
|
return this.cachedMatches;
|
|
84
93
|
}
|
|
@@ -113,22 +122,21 @@ class PouchDbTranslator extends plugins_namespaceObject.JsonTranslator {
|
|
|
113
122
|
}
|
|
114
123
|
translate(data) {
|
|
115
124
|
(0,assertions_namespaceObject.assertIsArray)(data);
|
|
116
|
-
const
|
|
125
|
+
const documents = [];
|
|
117
126
|
for(let i = 0, length = data.length; i < length; i++){
|
|
118
|
-
const
|
|
127
|
+
const document = data[i];
|
|
119
128
|
// design docs can be included in the result, ignore them
|
|
120
|
-
if (
|
|
129
|
+
if (typeof document._id === "string" && document._id.startsWith("_design")) {
|
|
121
130
|
continue;
|
|
122
131
|
}
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
} catch (e) {
|
|
128
|
-
throw new Error(`Error deserializing entity from db. Message: ${e.message}, Entity: ${JSON.stringify(entity, null, 2)}`);
|
|
129
|
-
}
|
|
132
|
+
// Again, whether or not the view predicate revived it: a view may hand back a copy of
|
|
133
|
+
// what it emitted, and a document read without a view was never revived
|
|
134
|
+
this.reviveDates?.(document);
|
|
135
|
+
documents.push(document);
|
|
130
136
|
}
|
|
131
|
-
|
|
137
|
+
// Documents stay in storage shape. The datastore deserializes the rows this returns, by
|
|
138
|
+
// their `from` names, and a join does the same per side.
|
|
139
|
+
return super.translate(documents);
|
|
132
140
|
}
|
|
133
141
|
}
|
|
134
142
|
|
|
@@ -608,8 +616,13 @@ class PouchDbPlugin {
|
|
|
608
616
|
properties.sort((a, b)=>a.name.localeCompare(b.name, undefined, {
|
|
609
617
|
sensitivity: 'base'
|
|
610
618
|
}));
|
|
619
|
+
// A view reads documents as they are stored, where a renamed segment is under its `from`
|
|
620
|
+
// name. The view name is built from the same paths, so a design document saved when views
|
|
621
|
+
// read the in-memory name, and so emitted nothing for a renamed property, is missing the new
|
|
622
|
+
// view and gets replaced.
|
|
611
623
|
const paths = properties.map((w)=>w.getAssignmentPath({
|
|
612
|
-
parent: "doc"
|
|
624
|
+
parent: "doc",
|
|
625
|
+
useFromPropertyName: true
|
|
613
626
|
}));
|
|
614
627
|
const viewName = `by_${paths.join("_")}`;
|
|
615
628
|
return {
|
|
@@ -636,10 +649,7 @@ class PouchDbPlugin {
|
|
|
636
649
|
const index = indexes[i];
|
|
637
650
|
const { viewName, paths } = this._prepareProperties(...index.properties);
|
|
638
651
|
if (index.properties.length === 1) {
|
|
639
|
-
const
|
|
640
|
-
const path = property.getAssignmentPath({
|
|
641
|
-
parent: "doc"
|
|
642
|
-
});
|
|
652
|
+
const path = paths[0];
|
|
643
653
|
ddoc.views[viewName] = {
|
|
644
654
|
map: `function(doc) {
|
|
645
655
|
if (${path}) {
|
|
@@ -741,10 +751,26 @@ class PouchDbPlugin {
|
|
|
741
751
|
}, done);
|
|
742
752
|
}
|
|
743
753
|
_validateSchemas(event) {
|
|
744
|
-
for (const [, schema] of event.schemas){
|
|
754
|
+
for (const [schemaId, schema] of event.schemas){
|
|
755
|
+
// Only schemas this persist actually writes: a store may declare other collections,
|
|
756
|
+
// and an unused bad one should not block saves to the good ones.
|
|
757
|
+
if (event.operation.get(schemaId)?.hasItems !== true) {
|
|
758
|
+
continue;
|
|
759
|
+
}
|
|
745
760
|
if (schema.idProperties.length > 1) {
|
|
746
761
|
throw new Error("PouchDB cannot have more than one key per document. Only '_id' is allowed to be the key");
|
|
747
762
|
}
|
|
763
|
+
// An identity key is generated by PouchDB as '_id' and echoed back as '_id', so an
|
|
764
|
+
// identity key under any other name is never filled in: every entity reads back with
|
|
765
|
+
// an undefined key and the change tracker merges them all into one. Corruption, not
|
|
766
|
+
// an error — so refuse the schema up front. A caller-supplied key (default/computed)
|
|
767
|
+
// is stored as an ordinary field and round-trips fine under any name. A `.from()` on the
|
|
768
|
+
// identity key is refused for the same reason: it is stored under its `from` name, and
|
|
769
|
+
// PouchDB fills in `_id`.
|
|
770
|
+
const key = schema.idProperties[0];
|
|
771
|
+
if (key != null && key.isIdentity && (key.name !== "_id" || key.getResolvedName() !== "_id")) {
|
|
772
|
+
throw new Error(`PouchDB generates identity keys as '_id'. The schema for collection '${schema.collectionName}' uses ` + `'${key.name}' as its identity key, which PouchDB cannot fill in. ` + `Declare the key as: _id: s.string().key().identity()`);
|
|
773
|
+
}
|
|
748
774
|
}
|
|
749
775
|
}
|
|
750
776
|
_bulkPersist(event, done) {
|
|
@@ -1004,6 +1030,10 @@ class PouchDbPlugin {
|
|
|
1004
1030
|
}, done);
|
|
1005
1031
|
}
|
|
1006
1032
|
_query(event, done) {
|
|
1033
|
+
// Documents are matched and sorted by the caller's lambdas, over documents as they are
|
|
1034
|
+
// stored, where a `from` property has a different key. Handed back before any index is
|
|
1035
|
+
// chosen, so neither the index nor the view sees an option this plugin cannot run.
|
|
1036
|
+
(0,plugins_namespaceObject.reportRenamedProperties)(event.operation.options);
|
|
1007
1037
|
this.resolveIndexes(event, (r)=>{
|
|
1008
1038
|
if (r.ok !== results_namespaceObject.Result.SUCCESS) {
|
|
1009
1039
|
done(results_namespaceObject.PluginEventResult.error(event.id, r.error));
|
|
@@ -1034,7 +1064,7 @@ class PouchDbPlugin {
|
|
|
1034
1064
|
}
|
|
1035
1065
|
_getExpressionFromQuery(event) {
|
|
1036
1066
|
const filters = event.operation.options.get("filter");
|
|
1037
|
-
const databaseFilters = filters.filter((x)=>x.option.target === "database");
|
|
1067
|
+
const databaseFilters = filters.filter((x)=>x.option.target === "database" && x.option.reason === "executed");
|
|
1038
1068
|
if (databaseFilters.length === 0) {
|
|
1039
1069
|
return expressions_namespaceObject.Expression.EMPTY;
|
|
1040
1070
|
}
|
package/dist/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.cjs","sources":["webpack://@routier/pouchdb-plugin/webpack/runtime/compat_get_default_export","webpack://@routier/pouchdb-plugin/webpack/runtime/define_property_getters","webpack://@routier/pouchdb-plugin/webpack/runtime/has_own_property","webpack://@routier/pouchdb-plugin/webpack/runtime/make_namespace_object","webpack://@routier/pouchdb-plugin/./src/PouchDbTranslator.ts","webpack://@routier/pouchdb-plugin/./src/PouchDbPlugin.ts","webpack://@routier/pouchdb-plugin/./src/index.ts"],"sourcesContent":["// getDefaultExport function for compatibility with non-ESM modules\n__webpack_require__.n = (module) => {\n\tvar getter = module && module.__esModule ?\n\t\t() => (module['default']) :\n\t\t() => (module);\n\t__webpack_require__.d(getter, { a: getter });\n\treturn getter;\n};\n","__webpack_require__.d = (exports, definition) => {\n\tfor(var key in definition) {\n if(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {\n Object.defineProperty(exports, key, { enumerable: true, get: definition[key] });\n }\n }\n};","__webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))","// define __esModule on exports\n__webpack_require__.r = (exports) => {\n\tif(typeof Symbol !== 'undefined' && Symbol.toStringTag) {\n\t\tObject.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });\n\t}\n\tObject.defineProperty(exports, '__esModule', { value: true });\n};","import { assertIsArray } from \"@routier/core/assertions\";\nimport { Filter, ParamsFilter } from \"@routier/core/expressions\";\nimport { IQuery, JsonTranslator, QueryCollectionItem, QueryOption } from \"@routier/core/plugins\";\nimport { CompiledSchema, InferType } from \"@routier/core/schema\";\n\nexport class PouchDbTranslator<TEntity extends {}, TShape extends unknown = TEntity> extends JsonTranslator<TEntity, TShape> {\n\n private schema: CompiledSchema<TEntity>;\n private cachedMatches: ((item: unknown) => boolean) | null = null;\n\n constructor(query: IQuery<TEntity, TShape>) {\n super(query);\n this.schema = query.schema;\n }\n\n matches(item: unknown) {\n // Get or build cached filter chain\n const filterChain = this.resolveFilterChain();\n\n // Execute the chain (no loops, just recursive function calls)\n return filterChain(item);\n }\n\n private resolveFilterChain(): (item: unknown) => boolean {\n // Return cached chain if available\n if (this.cachedMatches !== null) {\n return this.cachedMatches;\n }\n\n // Build and cache the filter chain\n const filters = this.query.options.get(\"filter\");\n const databaseFilters = filters.filter(x => x.option.target === \"database\");\n\n this.cachedMatches = this.buildFilterChain(databaseFilters, 0);\n\n return this.cachedMatches;\n }\n\n private buildFilterChain(filters: QueryCollectionItem<TShape, \"filter\">[], index: number): (item: unknown) => boolean {\n // Base case: no more filters, return true\n if (index >= filters.length) {\n return () => true;\n }\n\n // Get current filter function\n const currentFilter = this.evaluateFilter(filters[index].option);\n\n // Build the rest of the chain\n const nextFilter = this.buildFilterChain(filters, index + 1);\n\n // Return a function that checks current filter and calls next\n return (item: unknown) => {\n if (!currentFilter(item)) {\n return false; // Early termination\n }\n return nextFilter(item); // Recursive call to next filter\n };\n }\n\n private evaluateFilter(filter: QueryOption<TShape, \"filter\">): (item: unknown) => boolean {\n if (filter.value.params == null) {\n const selector = filter.value.filter as Filter<unknown>;\n return (item: unknown) => selector(item) !== false;\n }\n\n const selector = filter.value.filter as ParamsFilter<unknown, {}>;\n const params = filter.value.params;\n return (item: unknown) => selector([item, params]) !== false;\n }\n\n override translate(data: unknown) {\n assertIsArray(data);\n\n const result: unknown[] = [];\n\n for (let i = 0, length = data.length; i < length; i++) {\n const entity: any = data[i];\n\n // design docs can be included in the result, ignore them\n if (\"_id\" in entity && typeof entity._id === \"string\" && entity._id.startsWith(\"_design\")) {\n continue;\n }\n\n try {\n // PouchDB converts a Date to a string when it is saved, we need to convert it back when it's selected\n result.push(this.schema.deserialize(entity as InferType<TEntity>));\n data[i] = null;\n } catch (e) {\n throw new Error(`Error deserializing entity from db. Message: ${e.message}, Entity: ${JSON.stringify(entity, null, 2)}`)\n }\n }\n\n return super.translate(result);\n }\n\n}","import PouchDB from 'pouchdb';\nimport { PouchDbTranslator } from './PouchDbTranslator';\nimport { SyncronousQueue, SyncronousUnitOfWork, WorkPipeline } from '@routier/core/pipeline';\nimport { InferCreateType, InferType, PropertyInfo, SchemaId } from '@routier/core/schema';\nimport { DbPluginBulkPersistEvent, DbPluginEvent, DbPluginQueryEvent, EntityUpdateInfo, IDbPlugin, IQuery, ITranslatedValue, joinInPlugin } from '@routier/core/plugins';\nimport { CallbackResult, PluginEventCallbackPartialResult, PluginEventCallbackResult, PluginEventResult, Result } from '@routier/core/results';\nimport { assertIsNotNull } from '@routier/core/assertions';\nimport { combineExpressions, ComparatorExpression, Expression, getProperties } from '@routier/core/expressions';\nimport { BulkPersistChanges, BulkPersistResult, ReadonlySchemaCollection, UnknownRecord } from '@routier/core';\n\nconst INDEX_NAME = \"routier_pdb_indexes\"\n\ntype PouchDBPluginOptions = PouchDB.Configuration.DatabaseConfiguration & {\n queryType?: \"default\" | \"memory-optimized\" | \"experimental\";\n sync?: PouchDB.Replication.SyncOptions & {\n remoteDb: string;\n onChange?: (schemas: ReadonlySchemaCollection, event: PouchDB.Replication.SyncResult<{}>) => void;\n onError?: (schemas: ReadonlySchemaCollection, error?: any) => void;\n onComplete?: (schemas: ReadonlySchemaCollection, event: PouchDB.Replication.SyncResultComplete<{}>) => void;\n onPaused?: (schemas: ReadonlySchemaCollection, event?: any) => void;\n onActive?: (schemas: ReadonlySchemaCollection) => void;\n onDenied?: (schemas: ReadonlySchemaCollection, event?: any) => void;\n auth?: {\n username: string;\n password: string;\n };\n headers?: { [key: string]: string };\n };\n}\n\nexport type PouchDbDesignDoc = {\n _id: string;\n language?: string;\n views?: {\n [viewName: string]: {\n map: string | Function;\n reduce?: string | Function;\n };\n };\n filters?: {\n [filterName: string]: string | Function;\n };\n validate_doc_update?: string | Function;\n options?: Record<string, any>;\n [key: string]: any; // allow other CouchDB features\n}\n\ntype MatchingIndex = {\n viewName: string,\n properties: {\n property: PropertyInfo<any>,\n value: unknown\n }[]\n}\n\nexport class PouchDbPlugin implements IDbPlugin {\n\n private readonly _name: string;\n private readonly _options?: PouchDBPluginOptions;\n\n /**\n * Per INSTANCE, all three of these. They used to be module-level, which made every\n * PouchDbPlugin in the process share one database's state regardless of its name:\n *\n * - the **queue** serialized work across unrelated databases, so a slow save against one\n * database blocked a read against another;\n * - the **index cache** was keyed by nothing at all, so the first database's design\n * document was reported as every database's;\n * - the **sync handle** lived under the literal key `\"sync\"`, so only the FIRST plugin in\n * a process could establish replication — every later one got back the first one's\n * handle, pointed at a different remote.\n *\n * A plugin instance is the natural scope: it owns exactly one database name.\n */\n private readonly queue = new SyncronousQueue();\n private indexCache: PouchDbDesignDoc | null = null;\n private syncHandle: PouchDB.Replication.Sync<{}> | null = null;\n\n /**\n * ONE local database handle for this plugin, shared by every operation and by `sync()`.\n *\n * This used to be a fresh `new PouchDB(name)` per operation, with `sync()` constructing\n * yet another one of its own. Two PouchDB objects over the same name only behave as one\n * database when the ADAPTER broadcasts changes between them: IndexedDB does, so this\n * works in a browser, and the in-memory adapter does not, so under it a live replication\n * never observes the plugin's own writes and the plugin never observes what replication\n * pulls in. Replication and data access were effectively wired to two different databases\n * on any adapter without that broadcast.\n *\n * One handle removes the question, and removes the per-operation construction churn with\n * it. It is closed and cleared by `destroy()`.\n */\n private localDb: PouchDB.Database<any> | null = null;\n\n private database<TEntity>(): PouchDB.Database<TEntity> {\n if (this.localDb == null) {\n const { sync: _sync, queryType: _queryType, ...rest } = this._options ?? {};\n this.localDb = new PouchDB(this._name, rest);\n }\n\n return this.localDb as PouchDB.Database<TEntity>;\n }\n\n constructor(name: string, options?: PouchDBPluginOptions) {\n this._name = name;\n this._options = options;\n }\n\n /**\n * See `IDbPlugin.databaseName`. The local database name — the same value two contexts\n * opening one PouchDB database supply, so they share subscription channels. Remote sync\n * targets are deliberately not part of it: two local databases replicating to one remote\n * are still two databases.\n */\n get databaseName(): string {\n return this._name;\n }\n\n sync(schemas: ReadonlySchemaCollection) {\n\n assertIsNotNull(this._options?.sync, \"Cannot start sync process without sync options. Provide sync options in PouchDbPlugin constructor\");\n\n if (this.syncHandle == null) {\n // No placeholder write before the work. The previous shape assigned `{}` first\n // and only replaced it after `sync()` returned, so if constructing either\n // database threw, the cache kept the placeholder forever and every later call\n // returned an empty object cast as a Sync — no replication, no error, no way back\n // without restarting the process.\n // The plugin's own handle, not a second one over the same name: replication has\n // to observe the writes this plugin makes, and on an adapter that does not\n // broadcast changes between instances (the in-memory one, for example) a\n // separate object is a separate database in every way that matters here.\n const localDb = this.database();\n const remoteDb = new PouchDB(this._options.sync.remoteDb);\n\n // Set up sync\n const sync = localDb.sync(remoteDb, {\n ...this._options.sync\n });\n\n if (this._options.sync.onChange) {\n sync.on('change', (e) => this._options.sync.onChange(schemas, e));\n }\n\n if (this._options.sync.onActive) {\n sync.on('active', () => this._options.sync.onActive(schemas));\n }\n\n if (this._options.sync.onComplete) {\n sync.on('complete', (e) => this._options.sync.onComplete(schemas, e));\n }\n\n if (this._options.sync.onDenied) {\n sync.on('denied', (e) => this._options.sync.onDenied(schemas, e));\n }\n\n if (this._options.sync.onError) {\n sync.on('error', (e) => this._options.sync.onError(schemas, e));\n }\n\n if (this._options.sync.onPaused) {\n sync.on('paused', (e) => this._options.sync.onPaused(schemas, e));\n }\n\n // Retained so destroy() can cancel it. An uncancelled sync keeps polling a\n // remote that the caller believes it has finished with, and holds both databases\n // open with it.\n this.syncHandle = sync;\n }\n\n return this.syncHandle;\n }\n\n /**\n * Fills in the `_rev` of any document about to be updated or removed that arrives without\n * one, in a single lookup.\n *\n * PouchDB is the only backend in this repository that needs a revision to change a row, and\n * it used to make that the CALLER's problem: a schema had to declare `_rev` and every\n * entity had to carry the current value. That is this plugin's write protocol leaking into\n * every schema written for it, and it made whole features unusable here — a generated\n * search-index row is built from the document being saved, so it has an id and never a\n * revision, and every edit to an indexed document failed with a conflict whose only\n * detail was `true`.\n *\n * A revision is a fact this database owns, so this is the layer that should look it up.\n * One `allDocs` for every id that needs one, only when at least one does, and never on the\n * path where every entity already carries its own. Nothing above has to know.\n *\n * A missing row resolves to no revision and is left alone: an update to a document that is\n * not there must still fail, and it fails the way it always did.\n */\n private _withRevisions(\n db: PouchDB.Database,\n documents: UnknownRecord[],\n done: (error: unknown | null) => void\n ) {\n const missing = documents\n .filter(document => document._rev == null && document._id != null)\n .map(document => String(document._id));\n\n if (missing.length === 0) {\n done(null);\n return;\n }\n\n db.allDocs({ keys: missing }).then(response => {\n const revisions = new Map<string, string>();\n\n for (const row of response?.rows ?? []) {\n const revision = (row as { value?: { rev?: string, deleted?: boolean } }).value;\n\n if (revision?.rev != null && revision.deleted !== true) {\n revisions.set(String(row.key), revision.rev);\n }\n }\n\n for (const document of documents) {\n\n if (document._rev == null) {\n const revision = revisions.get(String(document._id));\n\n if (revision != null) {\n document._rev = revision;\n }\n }\n }\n\n done(null);\n }).catch(error => done(error));\n }\n\n private _identityBulkOperations(identitySchemaIds: SchemaId[], changes: BulkPersistChanges, result: BulkPersistResult, done: CallbackResult<never>): void {\n\n if (changes.aggregate.size === 0) {\n done(Result.success())\n return;\n }\n\n // Link each entity to a schema id below so we can easily look up the schema id for an entity\n const updates: { change: EntityUpdateInfo<UnknownRecord>, schemaId: SchemaId }[] = [];\n const adds: { entity: InferCreateType<UnknownRecord>, schemaId: SchemaId }[] = [];\n const removes: { entity: InferType<UnknownRecord>, schemaId: SchemaId }[] = [];\n\n for (const [schemaId, schemaChanges] of changes) {\n\n if (identitySchemaIds.includes(schemaId) === false || schemaChanges.hasItems === false) {\n continue;\n }\n\n updates.push(...schemaChanges.updates.map(x => ({ change: x, schemaId })));\n adds.push(...schemaChanges.adds.map(x => ({ entity: x, schemaId })));\n removes.push(...schemaChanges.removes.map(x => ({ entity: x, schemaId })));\n }\n\n // Do adds separate. Updates/Removes already have an id that we can reference\n // Default can do the same as updates/removes below since it has an id\n // Check again now to see if we have any identity schema changes\n if (updates.length === 0 && removes.length === 0 && adds.length === 0) {\n done(Result.success())\n return;\n }\n\n this._doWork((db, d) => {\n try {\n\n const updatedDocuments = [...updates].map(w => w.change.entity);\n const errors: any[] = [];\n\n // Tombstones are built here rather than inline so a missing revision can be\n // resolved into them before the write.\n const tombstones = removes.map(w => ({ _id: w.entity._id, _rev: w.entity._rev, _deleted: true } as UnknownRecord));\n\n this._withRevisions(db, [...tombstones, ...updatedDocuments] as UnknownRecord[], (revisionError) => {\n\n if (revisionError != null) {\n d(Result.error(revisionError));\n return;\n }\n\n db.bulkDocs([...tombstones, ...updatedDocuments], null, (error, response) => {\n\n if (error) {\n d(Result.error(error));\n return;\n }\n\n for (let i = 0, length = response.length; i < length; i++) {\n const doc = response[i];\n\n if (\"error\" in doc && doc.error === true) {\n errors.push(doc); // send back the entire error\n continue;\n }\n\n if (\"id\" in doc && \"ok\" in doc) {\n const updatesIndex = updates.findIndex(x => x.change.entity._id === doc.id);\n\n if (updatesIndex !== -1) {\n // Optimistically assume that the update worked as expected\n const update = updates[updatesIndex];\n\n const changesResult = result.resolve(update.schemaId);\n\n // Set the new rev\n (update.change.entity as UnknownRecord)._rev = doc.rev;\n\n changesResult.updates.push(update.change.entity);\n continue;\n }\n\n const removesIndex = removes.findIndex(x => x.entity._id === doc.id);\n\n if (removesIndex !== -1) {\n\n const remove = removes[removesIndex];\n\n const changesResult = result.resolve(remove.schemaId);\n\n changesResult.removes.push(remove.entity);\n }\n }\n }\n\n if (errors.length > 0) {\n d(Result.error(errors));\n return;\n }\n\n const pipeline = new WorkPipeline();\n\n for (let i = 0, length = identitySchemaIds.length; i < length; i++) {\n const schemaId = identitySchemaIds[i];\n const schemaAdds = adds.filter(x => x.schemaId === schemaId).map(x => x.entity);\n\n // Skip schemas with no adds\n if (schemaAdds.length === 0) {\n continue;\n }\n\n pipeline.pipe((d) => {\n const schemaResult = result.resolve(schemaId);\n\n assertIsNotNull(schemaResult);\n assertIsNotNull(schemaAdds);\n\n db.bulkDocs([...schemaAdds], null, (error, response) => {\n\n if (error) {\n d(Result.error(error));\n return;\n }\n\n // Starts EMPTY and is filled from the ok entries below.\n // Seeding it from every response entry and then pushing each\n // ok id again put every id in twice, so `_bulkGetAdditions`\n // asked for each document twice and the echo carried\n // duplicates into the change tracker.\n const ids: string[] = [];\n\n for (let i = 0, length = response.length; i < length; i++) {\n\n const doc = response[i];\n\n if (\"error\" in doc) {\n\n const reason = doc.reason ?? doc.error;\n\n d(Result.error(reason));\n return;\n }\n\n if (\"id\" in doc && \"ok\" in doc) {\n ids.push(doc.id);\n } else {\n d(Result.error(doc.error));\n return;\n }\n }\n\n this._bulkGetAdditions(ids, (bulkGetResponse) => {\n\n if (bulkGetResponse.ok !== Result.SUCCESS) {\n d(Result.error(bulkGetResponse));\n return;\n }\n\n for (let i = 0, length = bulkGetResponse.data.results.length; i < length; i++) {\n const docs = bulkGetResponse.data.results[i].docs;\n\n if (docs.length === 1) {\n const doc = docs[0];\n\n if (\"ok\" in doc) {\n schemaResult.adds.push(doc.ok as any);\n }\n }\n }\n\n d(Result.success());\n });\n });\n\n });\n }\n\n pipeline.filter((r) => {\n if (r.ok !== Result.SUCCESS) {\n d(r);\n return;\n }\n\n d(Result.success());\n });\n });\n });\n } catch (e) {\n d(Result.error(e));\n }\n }, done);\n }\n\n private _defaultBulkOperations(nonIdentitySchemaIds: SchemaId[], changes: BulkPersistChanges, result: BulkPersistResult, done: CallbackResult<never>): void {\n\n if (changes.aggregate.size === 0) {\n done(Result.success())\n return;\n }\n\n // Link each entity to a schema id below so we can easily look up the schema id for an entity\n const updates: { change: EntityUpdateInfo<UnknownRecord>, schemaId: SchemaId }[] = [];\n const adds: { entity: InferCreateType<UnknownRecord>, schemaId: SchemaId }[] = [];\n const removes: { entity: InferType<UnknownRecord>, schemaId: SchemaId }[] = [];\n\n for (const [schemaId, schemaChanges] of changes) {\n\n if (nonIdentitySchemaIds.includes(schemaId) === false || schemaChanges.hasItems === false) {\n continue;\n }\n\n updates.push(...schemaChanges.updates.map(x => ({ change: x, schemaId })));\n adds.push(...schemaChanges.adds.map(x => ({ entity: x, schemaId })));\n removes.push(...schemaChanges.removes.map(x => ({ entity: x, schemaId })));\n }\n\n if (updates.length === 0 && removes.length === 0 && adds.length === 0) {\n done(Result.success())\n return;\n }\n\n this._doWork((db, d) => {\n try {\n\n const tombstones = removes.map(x => ({ _id: x.entity._id, _rev: x.entity._rev, _deleted: true } as UnknownRecord));\n const updatedDocuments = updates.map(x => x.change.entity) as UnknownRecord[];\n\n this._withRevisions(db, [...tombstones, ...updatedDocuments], (revisionError) => {\n\n if (revisionError != null) {\n d(Result.error(revisionError));\n return;\n }\n\n db.bulkDocs([...tombstones, ...updatedDocuments], null, (error, response) => {\n\n if (error != null) {\n d(Result.error(error));\n return;\n }\n\n for (let i = 0, length = response.length; i < length; i++) {\n const doc = response[i];\n\n if (\"error\" in doc) {\n\n const reason = doc.reason ?? doc.error;\n\n d(Result.error(reason));\n return;\n }\n\n const removesIndex = removes.findIndex(x => x.entity._id === doc.id);\n\n if (removesIndex !== -1) {\n const { schemaId } = removes[removesIndex]\n const schemaResult = result.resolve(schemaId);\n\n assertIsNotNull(schemaResult);\n\n schemaResult.removes.push(doc as any);\n continue;\n }\n\n const updatesIndex = updates.findIndex(x => x.change.entity._id === doc.id);\n\n if (updatesIndex !== -1) {\n // Optimistically assume that the update worked as expected\n const update = updates[updatesIndex];\n\n const changesResult = result.resolve(update.schemaId);\n\n // Set the new rev\n (update.change.entity as UnknownRecord)._rev = doc.rev;\n\n changesResult.updates.push(update.change.entity);\n continue;\n }\n\n d(Result.error(new Error(\"Cannot classify resulting doc\")));\n return;\n }\n\n const pipeline = new WorkPipeline();\n\n for (let i = 0, length = nonIdentitySchemaIds.length; i < length; i++) {\n const schemaId = nonIdentitySchemaIds[i];\n const schemaAdds = adds.filter(x => x.schemaId === schemaId).map(x => x.entity);\n\n // Skip schemas with no adds\n if (schemaAdds.length === 0) {\n continue;\n }\n\n pipeline.pipe((d) => {\n const schemaResult = result.resolve(schemaId);\n\n assertIsNotNull(schemaResult);\n assertIsNotNull(schemaAdds);\n\n db.bulkDocs([...schemaAdds], null, (error, response) => {\n\n if (error) {\n d(Result.error(error));\n return;\n }\n\n // Starts EMPTY and is filled from the ok entries below.\n // Seeding it from every response entry and then pushing each\n // ok id again put every id in twice, so `_bulkGetAdditions`\n // asked for each document twice and the echo carried\n // duplicates into the change tracker.\n const ids: string[] = [];\n\n for (let i = 0, length = response.length; i < length; i++) {\n\n const doc = response[i];\n\n if (\"error\" in doc) {\n\n const reason = doc.reason ?? doc.error;\n\n d(Result.error(reason));\n return;\n }\n\n if (\"id\" in doc && \"ok\" in doc) {\n ids.push(doc.id);\n } else {\n d(Result.error(doc.error));\n return;\n }\n }\n\n this._bulkGetAdditions(ids, (bulkGetResponse) => {\n\n if (bulkGetResponse.ok !== Result.SUCCESS) {\n d(Result.error(bulkGetResponse));\n return;\n }\n\n for (let i = 0, length = bulkGetResponse.data.results.length; i < length; i++) {\n const docs = bulkGetResponse.data.results[i].docs;\n\n if (docs.length === 1) {\n const doc = docs[0];\n\n if (\"ok\" in doc) {\n schemaResult.adds.push(doc.ok as any);\n }\n }\n }\n\n d(Result.success());\n });\n });\n\n });\n }\n\n pipeline.filter((r) => {\n if (r.ok !== Result.SUCCESS) {\n d(r);\n return;\n }\n\n d(Result.success());\n });\n });\n });\n } catch (e) {\n d(Result.error(e));\n }\n }, done);\n }\n\n private _prepareProperties(...properties: PropertyInfo<any>[]) {\n\n properties.sort((a, b) => a.name.localeCompare(b.name, undefined, { sensitivity: 'base' }));\n const paths = properties.map(w => w.getAssignmentPath({ parent: \"doc\" }));\n const viewName = `by_${paths.join(\"_\")}`;\n\n return {\n properties,\n paths,\n viewName\n }\n }\n\n private resolveIndexes<TEntity extends {}, TShape extends unknown = TEntity>(event: DbPluginQueryEvent<TEntity, TShape>, done: CallbackResult<PouchDbDesignDoc | null>) {\n\n const indexes = event.operation.schema.getIndexes();\n\n if (indexes.length === 0) {\n done(Result.success(null));\n return;\n }\n\n if (this.indexCache != null) {\n done(Result.success(this.indexCache));\n return; // Already built\n }\n\n const ddoc: PouchDbDesignDoc = {\n _id: `_design/${INDEX_NAME}`,\n views: {}\n }\n\n for (let i = 0, length = indexes.length; i < length; i++) {\n const index = indexes[i];\n const { viewName, paths } = this._prepareProperties(...index.properties);\n\n if (index.properties.length === 1) {\n const property = index.properties[0];\n const path = property.getAssignmentPath({ parent: \"doc\" });\n ddoc.views[viewName] = {\n map: `function(doc) {\n if (${path}) {\n emit(${path});\n }\n }`\n }\n continue;\n }\n\n ddoc.views[viewName] = {\n map: `function(doc) {\n if (${paths.join(\" && \")}) {\n emit([${paths.join(\",\")}]);\n }\n }`\n }\n }\n\n this._doWork((db, d) => {\n // change this out in the future? or make a new index, this does not return the rev which makes us need to call get again below\n db.allDocs({\n startkey: '_design/',\n endkey: '_design0',\n include_docs: true\n }).then(response => {\n\n // if we have no indexes, let's create it\n if (response.rows.length === 0) {\n db.put(ddoc as UnknownRecord, {}, (e) => {\n if (e) {\n d(Result.error(e));\n return;\n }\n\n this.indexCache = ddoc;\n\n d(Result.success(ddoc));\n });\n return;\n }\n\n const matchingIndex = response.rows.find(x => x.id === `_design/${INDEX_NAME}`);\n\n // make sure we have the correct index created\n if (matchingIndex == null) {\n db.put(ddoc as UnknownRecord, {}, (e) => {\n if (e) {\n d(Result.error(e));\n return;\n }\n\n this.indexCache = ddoc;\n\n d(Result.success(ddoc));\n });\n return;\n }\n\n assertIsNotNull(ddoc.views);\n assertIsNotNull(matchingIndex.doc);\n\n const views = Object.keys(ddoc.views)\n\n // make sure all of the views are in the document, if not update it\n if (views.some(x => (matchingIndex.doc as any).views[x] == null)) {\n\n // need to get the rev\n db.get(ddoc._id, {}, (e, result) => {\n\n if (e != null) {\n d(Result.error(e));\n return;\n }\n\n (result as any).views = ddoc.views\n\n db.put(result as any, {}, (e) => {\n\n if (e) {\n d(Result.error(e));\n return;\n }\n\n this.indexCache = ddoc;\n\n d(Result.success(ddoc));\n });\n })\n return;\n }\n\n d(Result.success(ddoc));\n }).catch(e => {\n d(Result.error(e));\n });\n }, done)\n }\n\n // id should be a string here because this is only run on identity inserts\n private _bulkGetAdditions<TEntity extends {}>(ids: string[], done: CallbackResult<PouchDB.Core.BulkGetResponse<TEntity>>) {\n\n if (ids.length === 0) {\n done(Result.success({ results: [] }));\n return;\n }\n\n this._doWork((db, d) => {\n db.bulkGet<TEntity>({\n docs: ids.map(w => ({ id: w as string }))\n }, (error, response) => {\n\n if (error) {\n d(Result.error(error));\n return\n }\n\n d(Result.success(response));\n });\n }, done);\n }\n\n private _validateSchemas(event: DbPluginBulkPersistEvent) {\n for (const [, schema] of event.schemas) {\n if (schema.idProperties.length > 1) {\n throw new Error(\"PouchDB cannot have more than one key per document. Only '_id' is allowed to be the key\")\n }\n }\n }\n\n private _bulkPersist(\n event: DbPluginBulkPersistEvent,\n done: PluginEventCallbackPartialResult<BulkPersistResult>) {\n\n this._validateSchemas(event);\n\n const result = event.operation.toResult();\n const identitySchemaIds: SchemaId[] = [];\n const defaultSchemaIds: SchemaId[] = [];\n\n for (const [schemaId, schema] of event.schemas) {\n\n if (schema.hasIdentityKeys) {\n identitySchemaIds.push(schemaId);\n continue;\n }\n\n defaultSchemaIds.push(schemaId);\n }\n\n this._identityBulkOperations(identitySchemaIds, event.operation, result, (identityResult) => {\n\n if (identityResult.ok !== Result.SUCCESS) {\n done(PluginEventResult.error(event.id, identityResult.error))\n return;\n }\n\n this._defaultBulkOperations(defaultSchemaIds, event.operation, result, (defaultResult) => {\n\n if (defaultResult.ok !== Result.SUCCESS) {\n done(PluginEventResult.error(event.id, defaultResult.error))\n return;\n }\n\n done(PluginEventResult.success(event.id, result))\n });\n\n });\n }\n\n private _doWork<TResult, TEntity>(work: (db: PouchDB.Database<TEntity>, done: CallbackResult<TResult>) => void, done: CallbackResult<TResult>, shouldClose: boolean = false) {\n const db = this.database<TEntity>();\n\n work(db, (result) => {\n\n // The `return` is the fix. Without it, `shouldClose` ran BOTH branches: `done`\n // fired synchronously here and again from the close callback. A doubled callback\n // resolves a settled promise silently, but it also drives every pipeline stage\n // downstream twice — see known-defects #3's \"calls done exactly once\".\n if (shouldClose) {\n // The handle is shared, so closing it has to clear the cache too — the next\n // operation must open a fresh one rather than reuse a closed database.\n this.localDb = null;\n db.close(() => done(result));\n return;\n }\n\n done(result);\n })\n }\n\n destroy(_event: DbPluginEvent, done: (error?: any) => void): void {\n // Replication first. A live sync holds both the local and the remote database open\n // and keeps polling; destroying the local one underneath it leaves a replication\n // running against a database that no longer exists, which surfaces later as errors\n // from a plugin the caller believes it has finished with.\n if (this.syncHandle != null) {\n try {\n this.syncHandle.cancel();\n } catch {\n // An already-finished sync throws on cancel. Destroy's goal is that no\n // replication is running, and that is satisfied either way.\n }\n\n this.syncHandle = null;\n }\n\n // A destroyed database must not keep serving its cached design document to a plugin\n // that outlives it.\n this.indexCache = null;\n\n // `shouldClose: true`, so the handle this work opened is closed rather than left to\n // the garbage collector. It was false, which is what left destroy leaking the very\n // resource it was called to release.\n this._doWork((w, d) => {\n w.destroy(null, (e) => {\n if (e) {\n d(Result.error(e))\n return;\n }\n\n d(Result.success());\n });\n }, done, true);\n }\n\n\n bulkPersist(\n event: DbPluginBulkPersistEvent,\n done: PluginEventCallbackPartialResult<BulkPersistResult>) {\n\n const unitOfWork: SyncronousUnitOfWork = (d) => this._bulkPersist(event, (r) => {\n d();\n done(r)\n })\n\n this.queue.enqueue(unitOfWork.bind(this));\n }\n\n query<TRoot extends {}, TShape extends any = TRoot>(event: DbPluginQueryEvent<TRoot, TShape>, done: PluginEventCallbackResult<ITranslatedValue<TShape>>): void {\n\n const unitOfWork: SyncronousUnitOfWork = (d) => {\n const settle = (r: Parameters<typeof done>[0]) => {\n d();\n done(r);\n };\n\n // A join is two reads through `_query` — the UN-QUEUED path — on purpose: this unit of\n // work already holds the queue, so routing them through `query` would make them wait on\n // itself and the plugin would never answer. They are still serialized against every\n // other query, because this slot is held for both.\n if (event.operation.options.has(\"join\")) {\n joinInPlugin(event, (e, cb) => this._query(e, cb), settle as never);\n return;\n }\n\n this._query<TRoot, TShape>(event, settle);\n };\n\n this.queue.enqueue(unitOfWork.bind(this));\n }\n\n protected onGetIndex<TEntity extends {}, TShape extends unknown = TEntity>(_: IQuery<TEntity, TShape>, __: PouchDB.Find.FindRequest<unknown>, done: (result: null | string | [string, string]) => void) {\n done(null);\n }\n\n extractEqualityValueForProperty(expression: Expression, prop: PropertyInfo<any>): any | undefined {\n // Recursively search for a comparator expression that matches the property\n if (expression.type === \"comparator\" && (expression as ComparatorExpression).comparator === \"equals\") {\n // Check left side is property, right side is value\n if (expression.left && expression.left.type === \"property\" && (expression.left as any).property.name === prop.name && expression.right && expression.right.type === \"value\") {\n return (expression.right as any).value;\n }\n // Or right side is property, left side is value\n if (expression.right && expression.right.type === \"property\" && (expression.right as any).property.name === prop.name && expression.left && expression.left.type === \"value\") {\n return (expression.left as any).value;\n }\n }\n // Recursively check left and right\n if (expression.left) {\n const left = this.extractEqualityValueForProperty(expression.left, prop);\n if (left !== undefined) return left;\n }\n if (expression.right) {\n const right = this.extractEqualityValueForProperty(expression.right, prop);\n if (right !== undefined) return right;\n }\n return undefined;\n }\n\n private _findMatchingIndex(ddoc: PouchDbDesignDoc, expression: Expression): MatchingIndex {\n const queryProperties = getProperties(expression);\n\n const { viewName } = this._prepareProperties(...queryProperties);\n\n if (ddoc.views == null) {\n return null;\n }\n\n const index = ddoc.views[viewName];\n\n if (index == null) {\n return null;\n }\n\n const properties: MatchingIndex[\"properties\"] = [];\n\n for (const property of queryProperties) {\n const value = this.extractEqualityValueForProperty(expression, property);\n\n if (value === undefined) {\n return null\n }\n\n properties.push({\n property,\n value\n });\n }\n\n return {\n viewName,\n properties\n };\n }\n\n private _queryIndex<TEntity extends {}, TShape extends unknown = TEntity>(event: DbPluginQueryEvent<TEntity, TShape>, matchingIndex: MatchingIndex, done: CallbackResult<ITranslatedValue<TShape>>) {\n const translator = new PouchDbTranslator<TEntity, TShape>(event.operation);\n this._doWork((w, d) => {\n\n const options: PouchDB.Query.Options<any, any> = {\n include_docs: true,\n };\n\n const values = matchingIndex.properties.map(x => x.value);\n\n if (values.some(x => x == null) == false) {\n\n if (values.length === 1) {\n options.key = values[0];\n } else {\n options.keys = values;\n }\n }\n\n w.query(`${INDEX_NAME}/${matchingIndex.viewName}`, options, (error, response) => {\n\n if (error != null) {\n d(Result.error(error));\n return;\n }\n\n try {\n event.executedQueries.push({ text: `${INDEX_NAME}/${matchingIndex.viewName}: indexed view query` });\n\n const translated = translator.translate(response.rows.map(w => w.doc));\n d(Result.success(translated));\n } catch (e) {\n d(Result.error(e));\n }\n });\n }, done);\n }\n\n private _queryNoIndex<TEntity extends {}, TShape extends unknown = TEntity>(event: DbPluginQueryEvent<TEntity, TShape>, done: CallbackResult<ITranslatedValue<TShape>>) {\n const filters = event.operation.options.get(\"filter\")\n if (filters.length === 0) {\n this._queryWithNoFilters(event, done);\n return;\n }\n\n this._queryWithFilters(event, done);\n }\n\n private _queryWithNoFilters<TEntity extends {}, TShape extends unknown = TEntity>(event: DbPluginQueryEvent<TEntity, TShape>, done: CallbackResult<ITranslatedValue<TShape>>) {\n const translator = new PouchDbTranslator<TEntity, TShape>(event.operation);\n this._doWork((w, d) => {\n w.allDocs({\n include_docs: true\n }).then(response => {\n\n try {\n event.executedQueries.push({ text: \"allDocs({ include_docs: true }): full database scan, no index\" });\n\n const data = response.rows.map(w => w.doc);\n const translated = translator.translate(data);\n d(Result.success(translated));\n } catch (e) {\n d(Result.error(e));\n }\n }).catch(error => {\n d(Result.error(error));\n });\n }, done);\n }\n\n private _queryWithFilters<TEntity extends {}, TShape extends unknown = TEntity>(event: DbPluginQueryEvent<TEntity, TShape>, done: CallbackResult<ITranslatedValue<TShape>>) {\n const translator = new PouchDbTranslator<TEntity, TShape>(event.operation);\n this._doWork((w, d) => {\n\n if (this._name.startsWith(\"http\")) {\n // Cannot query remote databases using translator.matches, fallback to alldocs\n // Does not throw, will fail on the remote server\n w.allDocs({\n include_docs: true\n }).then(response => {\n const data = response.rows.map(w => w.doc);\n try {\n event.executedQueries.push({ text: \"allDocs({ include_docs: true }): full database scan, no index\" });\n\n const translated = translator.translate(data);\n d(Result.success(translated));\n } catch (e) {\n d(Result.error(e));\n }\n }).catch(error => {\n d(Result.error(error));\n });\n return;\n }\n\n w.query<{}, any>((doc, emit) => {\n if (typeof doc === \"object\" && \"_id\" in doc && translator.matches(doc)) {\n emit(doc._id, doc);\n }\n }, (error, response) => {\n\n if (error != null) {\n d(Result.error(error));\n return;\n }\n\n const data = response.rows.map(w => w.value);\n\n try {\n event.executedQueries.push({ text: \"view query\" });\n\n const translated = translator.translate(data);\n d(Result.success(translated));\n } catch (e) {\n d(Result.error(e));\n }\n });\n\n }, done);\n }\n\n private _query<TEntity extends {}, TShape extends unknown = TEntity>(event: DbPluginQueryEvent<TEntity, TShape>, done: PluginEventCallbackResult<ITranslatedValue<TShape>>): void {\n this.resolveIndexes(event, (r) => {\n if (r.ok !== Result.SUCCESS) {\n done(PluginEventResult.error(event.id, r.error))\n return;\n }\n\n const ddoc = r.data;\n\n if (ddoc == null) {\n this._queryNoIndex(event, done);\n return;\n }\n\n const mapMatchingIndex = this.findMatchingIndexForMap(ddoc, event);\n\n if (mapMatchingIndex != null) {\n this._queryIndex(event, mapMatchingIndex, done);\n return;\n }\n\n const expression = this._getExpressionFromQuery(event);\n\n if (Expression.isEmpty(expression)) {\n this._queryNoIndex(event, done);\n return;\n }\n\n const matchingIndex = this._findMatchingIndex(ddoc, expression);\n\n if (matchingIndex == null) {\n this._queryNoIndex(event, done);\n return;\n }\n\n this._queryIndex(event, matchingIndex, done);\n });\n }\n\n private _getExpressionFromQuery<TEntity extends {}, TShape>(event: DbPluginQueryEvent<TEntity, TShape>) {\n const filters = event.operation.options.get(\"filter\");\n\n const databaseFilters = filters.filter(x => x.option.target === \"database\");\n\n if (databaseFilters.length === 0) {\n return Expression.EMPTY;\n }\n\n const expressions = databaseFilters.map(x => x.option.value.expression);\n\n return combineExpressions(...expressions);\n }\n\n private findMatchingIndexForMap<TEntity extends {}, TShape>(ddoc: PouchDbDesignDoc, event: DbPluginQueryEvent<TEntity, TShape>): MatchingIndex | null {\n const map = event.operation.options.getLast(\"map\");\n const filters = event.operation.options.get(\"filter\");\n\n // we only want to look at the index if there are no filters\n if (filters.length > 0) {\n return null;\n }\n\n if (map == null || map.target !== \"database\") {\n return null;\n }\n\n if (map.value.fields.length !== 1 || map.value.fields[0].property == null) {\n return null;\n }\n\n const property = map.value.fields[0].property;\n\n const { viewName } = this._prepareProperties(property);\n\n if (ddoc.views == null) {\n return null;\n }\n\n const index = ddoc.views[viewName];\n\n if (index == null) {\n return null;\n }\n\n return {\n viewName,\n properties: [{ property, value: null }]\n }\n }\n}","export { PouchDbPlugin } from './PouchDbPlugin';"],"names":["assertIsArray","JsonTranslator","PouchDbTranslator","query","item","filterChain","filters","databaseFilters","x","index","currentFilter","nextFilter","filter","selector","params","data","result","i","length","entity","e","Error","JSON","PouchDB","SyncronousQueue","WorkPipeline","joinInPlugin","PluginEventResult","Result","assertIsNotNull","combineExpressions","Expression","getProperties","INDEX_NAME","PouchDbPlugin","_sync","_queryType","rest","name","options","schemas","localDb","remoteDb","sync","db","documents","done","missing","document","String","response","revisions","Map","row","revision","error","identitySchemaIds","changes","updates","adds","removes","schemaId","schemaChanges","d","updatedDocuments","w","errors","tombstones","revisionError","doc","updatesIndex","update","changesResult","removesIndex","remove","pipeline","schemaAdds","schemaResult","ids","reason","bulkGetResponse","docs","r","nonIdentitySchemaIds","properties","a","b","undefined","paths","viewName","event","indexes","ddoc","property","path","matchingIndex","views","Object","schema","defaultSchemaIds","identityResult","defaultResult","work","shouldClose","_event","unitOfWork","settle","cb","_","__","expression","prop","left","right","queryProperties","value","translator","values","translated","emit","mapMatchingIndex","expressions","map"],"mappings":";;;;;;;AAAA;AACA;AACA;AACA;AACA;AACA,iCAAiC,WAAW;AAC5C;AACA;;;;;ACPA;AACA;AACA;AACA,kDAAkD,wCAAwC;AAC1F;AACA;AACA,E;;;;ACNA,wF;;;;ACAA;AACA;AACA;AACA,uDAAuD,iBAAiB;AACxE;AACA,gDAAgD,aAAa;AAC7D,E;;;;;;;;;;;;;;;;;;;ACNyD;AAEwC;AAG1F,MAAME,0BAAgFD,sCAAcA;IAE/F,OAAgC;IAChC,gBAAqD,KAAK;IAElE,YAAYE,KAA8B,CAAE;QACxC,KAAK,CAACA;QACN,IAAI,CAAC,MAAM,GAAGA,MAAM,MAAM;IAC9B;IAEA,QAAQC,IAAa,EAAE;QACnB,mCAAmC;QACnC,MAAMC,cAAc,IAAI,CAAC,kBAAkB;QAE3C,8DAA8D;QAC9D,OAAOA,YAAYD;IACvB;IAEQ,qBAAiD;QACrD,mCAAmC;QACnC,IAAI,IAAI,CAAC,aAAa,KAAK,MAAM;YAC7B,OAAO,IAAI,CAAC,aAAa;QAC7B;QAEA,mCAAmC;QACnC,MAAME,UAAU,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,GAAG,CAAC;QACvC,MAAMC,kBAAkBD,QAAQ,MAAM,CAACE,CAAAA,IAAKA,EAAE,MAAM,CAAC,MAAM,KAAK;QAEhE,IAAI,CAAC,aAAa,GAAG,IAAI,CAAC,gBAAgB,CAACD,iBAAiB;QAE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ACjC;IAEQ,wBAAoD7B,IAAsB,EAAEF,KAA0C,EAAwB;QAClJ,MAAMgC,MAAMhC,MAAM,SAAS,CAAC,OAAO,CAAC,OAAO,CAAC;QAC5C,MAAMpF,UAAUoF,MAAM,SAAS,CAAC,OAAO,CAAC,GAAG,CAAC;QAE5C,4DAA4D;QAC5D,IAAIpF,QAAQ,MAAM,GAAG,GAAG;YACpB,OAAO;QACX;QAEA,IAAIoH,OAAO,QAAQA,IAAI,MAAM,KAAK,YAAY;YAC1C,OAAO;QACX;QAEA,IAAIA,IAAI,KAAK,CAAC,MAAM,CAAC,MAAM,KAAK,KAAKA,IAAI,KAAK,CAAC,MAAM,CAAC,EAAE,CAAC,QAAQ,IAAI,MAAM;YACvE,OAAO;QACX;QAEA,MAAM7B,WAAW6B,IAAI,KAAK,CAAC,MAAM,CAAC,EAAE,CAAC,QAAQ;QAE7C,MAAM,EAAEjC,QAAQ,EAAE,GAAG,IAAI,CAAC,kBAAkB,CAACI;QAE7C,IAAID,KAAK,KAAK,IAAI,MAAM;YACpB,OAAO;QACX;QAEA,MAAMnF,QAAQmF,KAAK,KAAK,CAACH,SAAS;QAElC,IAAIhF,SAAS,MAAM;YACf,OAAO;QACX;QAEA,OAAO;YACHgF;YACA,YAAY;gBAAC;oBAAEI;oBAAU,OAAO;gBAAK;aAAE;QAC3C;IACJ;AACJ;;;AC5pCgD"}
|
|
1
|
+
{"version":3,"file":"index.cjs","sources":["webpack://@routier/pouchdb-plugin/webpack/runtime/compat_get_default_export","webpack://@routier/pouchdb-plugin/webpack/runtime/define_property_getters","webpack://@routier/pouchdb-plugin/webpack/runtime/has_own_property","webpack://@routier/pouchdb-plugin/webpack/runtime/make_namespace_object","webpack://@routier/pouchdb-plugin/./src/PouchDbTranslator.ts","webpack://@routier/pouchdb-plugin/./src/PouchDbPlugin.ts","webpack://@routier/pouchdb-plugin/./src/index.ts"],"sourcesContent":["// getDefaultExport function for compatibility with non-ESM modules\n__webpack_require__.n = (module) => {\n\tvar getter = module && module.__esModule ?\n\t\t() => (module['default']) :\n\t\t() => (module);\n\t__webpack_require__.d(getter, { a: getter });\n\treturn getter;\n};\n","__webpack_require__.d = (exports, definition) => {\n\tfor(var key in definition) {\n if(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {\n Object.defineProperty(exports, key, { enumerable: true, get: definition[key] });\n }\n }\n};","__webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))","// define __esModule on exports\n__webpack_require__.r = (exports) => {\n\tif(typeof Symbol !== 'undefined' && Symbol.toStringTag) {\n\t\tObject.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });\n\t}\n\tObject.defineProperty(exports, '__esModule', { value: true });\n};","import { assertIsArray } from \"@routier/core/assertions\";\nimport { Filter, ParamsFilter } from \"@routier/core/expressions\";\nimport { IQuery, JsonTranslator, QueryCollectionItem, QueryOption } from \"@routier/core/plugins\";\nimport { getStorageDateReviver, StorageDateReviver } from \"@routier/core/schema\";\n\nexport class PouchDbTranslator<TEntity extends {}, TShape extends unknown = TEntity> extends JsonTranslator<TEntity, TShape> {\n\n /**\n * PouchDB stores JSON, so a date comes back as the ISO string the datastore serialized it to.\n * The caller's lambdas compare and call Dates, so every document is revived before one runs.\n * Only the dates: keys stay under their `from` names. `null` for a schema with no dates.\n */\n private readonly reviveDates: StorageDateReviver | null;\n private cachedMatches: ((item: unknown) => boolean) | null = null;\n\n constructor(query: IQuery<TEntity, TShape>) {\n super(query);\n this.reviveDates = getStorageDateReviver(query.schema);\n }\n\n matches(item: unknown) {\n // Get or build cached filter chain\n const filterChain = this.resolveFilterChain();\n\n this.reviveDates?.(item as Record<string, unknown>);\n\n // Execute the chain (no loops, just recursive function calls)\n return filterChain(item);\n }\n\n private resolveFilterChain(): (item: unknown) => boolean {\n // Return cached chain if available\n if (this.cachedMatches !== null) {\n return this.cachedMatches;\n }\n\n // Build and cache the filter chain\n const filters = this.query.options.get(\"filter\");\n // Not a filter the plugin reported: the datastore runs that one, after deserialization\n const databaseFilters = filters.filter(x => x.option.target === \"database\" && x.option.reason === \"executed\");\n\n this.cachedMatches = this.buildFilterChain(databaseFilters, 0);\n\n return this.cachedMatches;\n }\n\n private buildFilterChain(filters: QueryCollectionItem<TShape, \"filter\">[], index: number): (item: unknown) => boolean {\n // Base case: no more filters, return true\n if (index >= filters.length) {\n return () => true;\n }\n\n // Get current filter function\n const currentFilter = this.evaluateFilter(filters[index].option);\n\n // Build the rest of the chain\n const nextFilter = this.buildFilterChain(filters, index + 1);\n\n // Return a function that checks current filter and calls next\n return (item: unknown) => {\n if (!currentFilter(item)) {\n return false; // Early termination\n }\n return nextFilter(item); // Recursive call to next filter\n };\n }\n\n private evaluateFilter(filter: QueryOption<TShape, \"filter\">): (item: unknown) => boolean {\n if (filter.value.params == null) {\n const selector = filter.value.filter as Filter<unknown>;\n return (item: unknown) => selector(item) !== false;\n }\n\n const selector = filter.value.filter as ParamsFilter<unknown, {}>;\n const params = filter.value.params;\n return (item: unknown) => selector([item, params]) !== false;\n }\n\n override translate(data: unknown) {\n assertIsArray(data);\n\n const documents: Record<string, unknown>[] = [];\n\n for (let i = 0, length = data.length; i < length; i++) {\n const document = data[i] as Record<string, unknown>;\n\n // design docs can be included in the result, ignore them\n if (typeof document._id === \"string\" && document._id.startsWith(\"_design\")) {\n continue;\n }\n\n // Again, whether or not the view predicate revived it: a view may hand back a copy of\n // what it emitted, and a document read without a view was never revived\n this.reviveDates?.(document);\n documents.push(document);\n }\n\n // Documents stay in storage shape. The datastore deserializes the rows this returns, by\n // their `from` names, and a join does the same per side.\n return super.translate(documents);\n }\n\n}","import PouchDB from 'pouchdb';\nimport { PouchDbTranslator } from './PouchDbTranslator';\nimport { SyncronousQueue, SyncronousUnitOfWork, WorkPipeline } from '@routier/core/pipeline';\nimport { InferCreateType, InferType, PropertyInfo, SchemaId } from '@routier/core/schema';\nimport { DbPluginBulkPersistEvent, DbPluginEvent, DbPluginQueryEvent, EntityUpdateInfo, IDbPlugin, IQuery, ITranslatedValue, joinInPlugin, reportRenamedProperties } from '@routier/core/plugins';\nimport { CallbackResult, PluginEventCallbackPartialResult, PluginEventCallbackResult, PluginEventResult, Result } from '@routier/core/results';\nimport { assertIsNotNull } from '@routier/core/assertions';\nimport { combineExpressions, ComparatorExpression, Expression, getProperties } from '@routier/core/expressions';\nimport { BulkPersistChanges, BulkPersistResult, ReadonlySchemaCollection, UnknownRecord } from '@routier/core';\n\nconst INDEX_NAME = \"routier_pdb_indexes\"\n\ntype PouchDBPluginOptions = PouchDB.Configuration.DatabaseConfiguration & {\n queryType?: \"default\" | \"memory-optimized\" | \"experimental\";\n sync?: PouchDB.Replication.SyncOptions & {\n remoteDb: string;\n onChange?: (schemas: ReadonlySchemaCollection, event: PouchDB.Replication.SyncResult<{}>) => void;\n onError?: (schemas: ReadonlySchemaCollection, error?: any) => void;\n onComplete?: (schemas: ReadonlySchemaCollection, event: PouchDB.Replication.SyncResultComplete<{}>) => void;\n onPaused?: (schemas: ReadonlySchemaCollection, event?: any) => void;\n onActive?: (schemas: ReadonlySchemaCollection) => void;\n onDenied?: (schemas: ReadonlySchemaCollection, event?: any) => void;\n auth?: {\n username: string;\n password: string;\n };\n headers?: { [key: string]: string };\n };\n}\n\nexport type PouchDbDesignDoc = {\n _id: string;\n language?: string;\n views?: {\n [viewName: string]: {\n map: string | Function;\n reduce?: string | Function;\n };\n };\n filters?: {\n [filterName: string]: string | Function;\n };\n validate_doc_update?: string | Function;\n options?: Record<string, any>;\n [key: string]: any; // allow other CouchDB features\n}\n\ntype MatchingIndex = {\n viewName: string,\n properties: {\n property: PropertyInfo<any>,\n value: unknown\n }[]\n}\n\nexport class PouchDbPlugin implements IDbPlugin {\n\n private readonly _name: string;\n private readonly _options?: PouchDBPluginOptions;\n\n /**\n * Per INSTANCE, all three of these. They used to be module-level, which made every\n * PouchDbPlugin in the process share one database's state regardless of its name:\n *\n * - the **queue** serialized work across unrelated databases, so a slow save against one\n * database blocked a read against another;\n * - the **index cache** was keyed by nothing at all, so the first database's design\n * document was reported as every database's;\n * - the **sync handle** lived under the literal key `\"sync\"`, so only the FIRST plugin in\n * a process could establish replication — every later one got back the first one's\n * handle, pointed at a different remote.\n *\n * A plugin instance is the natural scope: it owns exactly one database name.\n */\n private readonly queue = new SyncronousQueue();\n private indexCache: PouchDbDesignDoc | null = null;\n private syncHandle: PouchDB.Replication.Sync<{}> | null = null;\n\n /**\n * ONE local database handle for this plugin, shared by every operation and by `sync()`.\n *\n * This used to be a fresh `new PouchDB(name)` per operation, with `sync()` constructing\n * yet another one of its own. Two PouchDB objects over the same name only behave as one\n * database when the ADAPTER broadcasts changes between them: IndexedDB does, so this\n * works in a browser, and the in-memory adapter does not, so under it a live replication\n * never observes the plugin's own writes and the plugin never observes what replication\n * pulls in. Replication and data access were effectively wired to two different databases\n * on any adapter without that broadcast.\n *\n * One handle removes the question, and removes the per-operation construction churn with\n * it. It is closed and cleared by `destroy()`.\n */\n private localDb: PouchDB.Database<any> | null = null;\n\n private database<TEntity>(): PouchDB.Database<TEntity> {\n if (this.localDb == null) {\n const { sync: _sync, queryType: _queryType, ...rest } = this._options ?? {};\n this.localDb = new PouchDB(this._name, rest);\n }\n\n return this.localDb as PouchDB.Database<TEntity>;\n }\n\n constructor(name: string, options?: PouchDBPluginOptions) {\n this._name = name;\n this._options = options;\n }\n\n /**\n * See `IDbPlugin.databaseName`. The local database name — the same value two contexts\n * opening one PouchDB database supply, so they share subscription channels. Remote sync\n * targets are deliberately not part of it: two local databases replicating to one remote\n * are still two databases.\n */\n get databaseName(): string {\n return this._name;\n }\n\n sync(schemas: ReadonlySchemaCollection) {\n\n assertIsNotNull(this._options?.sync, \"Cannot start sync process without sync options. Provide sync options in PouchDbPlugin constructor\");\n\n if (this.syncHandle == null) {\n // No placeholder write before the work. The previous shape assigned `{}` first\n // and only replaced it after `sync()` returned, so if constructing either\n // database threw, the cache kept the placeholder forever and every later call\n // returned an empty object cast as a Sync — no replication, no error, no way back\n // without restarting the process.\n // The plugin's own handle, not a second one over the same name: replication has\n // to observe the writes this plugin makes, and on an adapter that does not\n // broadcast changes between instances (the in-memory one, for example) a\n // separate object is a separate database in every way that matters here.\n const localDb = this.database();\n const remoteDb = new PouchDB(this._options.sync.remoteDb);\n\n // Set up sync\n const sync = localDb.sync(remoteDb, {\n ...this._options.sync\n });\n\n if (this._options.sync.onChange) {\n sync.on('change', (e) => this._options.sync.onChange(schemas, e));\n }\n\n if (this._options.sync.onActive) {\n sync.on('active', () => this._options.sync.onActive(schemas));\n }\n\n if (this._options.sync.onComplete) {\n sync.on('complete', (e) => this._options.sync.onComplete(schemas, e));\n }\n\n if (this._options.sync.onDenied) {\n sync.on('denied', (e) => this._options.sync.onDenied(schemas, e));\n }\n\n if (this._options.sync.onError) {\n sync.on('error', (e) => this._options.sync.onError(schemas, e));\n }\n\n if (this._options.sync.onPaused) {\n sync.on('paused', (e) => this._options.sync.onPaused(schemas, e));\n }\n\n // Retained so destroy() can cancel it. An uncancelled sync keeps polling a\n // remote that the caller believes it has finished with, and holds both databases\n // open with it.\n this.syncHandle = sync;\n }\n\n return this.syncHandle;\n }\n\n /**\n * Fills in the `_rev` of any document about to be updated or removed that arrives without\n * one, in a single lookup.\n *\n * PouchDB is the only backend in this repository that needs a revision to change a row, and\n * it used to make that the CALLER's problem: a schema had to declare `_rev` and every\n * entity had to carry the current value. That is this plugin's write protocol leaking into\n * every schema written for it, and it made whole features unusable here — a generated\n * search-index row is built from the document being saved, so it has an id and never a\n * revision, and every edit to an indexed document failed with a conflict whose only\n * detail was `true`.\n *\n * A revision is a fact this database owns, so this is the layer that should look it up.\n * One `allDocs` for every id that needs one, only when at least one does, and never on the\n * path where every entity already carries its own. Nothing above has to know.\n *\n * A missing row resolves to no revision and is left alone: an update to a document that is\n * not there must still fail, and it fails the way it always did.\n */\n private _withRevisions(\n db: PouchDB.Database,\n documents: UnknownRecord[],\n done: (error: unknown | null) => void\n ) {\n const missing = documents\n .filter(document => document._rev == null && document._id != null)\n .map(document => String(document._id));\n\n if (missing.length === 0) {\n done(null);\n return;\n }\n\n db.allDocs({ keys: missing }).then(response => {\n const revisions = new Map<string, string>();\n\n for (const row of response?.rows ?? []) {\n const revision = (row as { value?: { rev?: string, deleted?: boolean } }).value;\n\n if (revision?.rev != null && revision.deleted !== true) {\n revisions.set(String(row.key), revision.rev);\n }\n }\n\n for (const document of documents) {\n\n if (document._rev == null) {\n const revision = revisions.get(String(document._id));\n\n if (revision != null) {\n document._rev = revision;\n }\n }\n }\n\n done(null);\n }).catch(error => done(error));\n }\n\n private _identityBulkOperations(identitySchemaIds: SchemaId[], changes: BulkPersistChanges, result: BulkPersistResult, done: CallbackResult<never>): void {\n\n if (changes.aggregate.size === 0) {\n done(Result.success())\n return;\n }\n\n // Link each entity to a schema id below so we can easily look up the schema id for an entity\n const updates: { change: EntityUpdateInfo<UnknownRecord>, schemaId: SchemaId }[] = [];\n const adds: { entity: InferCreateType<UnknownRecord>, schemaId: SchemaId }[] = [];\n const removes: { entity: InferType<UnknownRecord>, schemaId: SchemaId }[] = [];\n\n for (const [schemaId, schemaChanges] of changes) {\n\n if (identitySchemaIds.includes(schemaId) === false || schemaChanges.hasItems === false) {\n continue;\n }\n\n updates.push(...schemaChanges.updates.map(x => ({ change: x, schemaId })));\n adds.push(...schemaChanges.adds.map(x => ({ entity: x, schemaId })));\n removes.push(...schemaChanges.removes.map(x => ({ entity: x, schemaId })));\n }\n\n // Do adds separate. Updates/Removes already have an id that we can reference\n // Default can do the same as updates/removes below since it has an id\n // Check again now to see if we have any identity schema changes\n if (updates.length === 0 && removes.length === 0 && adds.length === 0) {\n done(Result.success())\n return;\n }\n\n this._doWork((db, d) => {\n try {\n\n const updatedDocuments = [...updates].map(w => w.change.entity);\n const errors: any[] = [];\n\n // Tombstones are built here rather than inline so a missing revision can be\n // resolved into them before the write.\n const tombstones = removes.map(w => ({ _id: w.entity._id, _rev: w.entity._rev, _deleted: true } as UnknownRecord));\n\n this._withRevisions(db, [...tombstones, ...updatedDocuments] as UnknownRecord[], (revisionError) => {\n\n if (revisionError != null) {\n d(Result.error(revisionError));\n return;\n }\n\n db.bulkDocs([...tombstones, ...updatedDocuments], null, (error, response) => {\n\n if (error) {\n d(Result.error(error));\n return;\n }\n\n for (let i = 0, length = response.length; i < length; i++) {\n const doc = response[i];\n\n if (\"error\" in doc && doc.error === true) {\n errors.push(doc); // send back the entire error\n continue;\n }\n\n if (\"id\" in doc && \"ok\" in doc) {\n const updatesIndex = updates.findIndex(x => x.change.entity._id === doc.id);\n\n if (updatesIndex !== -1) {\n // Optimistically assume that the update worked as expected\n const update = updates[updatesIndex];\n\n const changesResult = result.resolve(update.schemaId);\n\n // Set the new rev\n (update.change.entity as UnknownRecord)._rev = doc.rev;\n\n changesResult.updates.push(update.change.entity);\n continue;\n }\n\n const removesIndex = removes.findIndex(x => x.entity._id === doc.id);\n\n if (removesIndex !== -1) {\n\n const remove = removes[removesIndex];\n\n const changesResult = result.resolve(remove.schemaId);\n\n changesResult.removes.push(remove.entity);\n }\n }\n }\n\n if (errors.length > 0) {\n d(Result.error(errors));\n return;\n }\n\n const pipeline = new WorkPipeline();\n\n for (let i = 0, length = identitySchemaIds.length; i < length; i++) {\n const schemaId = identitySchemaIds[i];\n const schemaAdds = adds.filter(x => x.schemaId === schemaId).map(x => x.entity);\n\n // Skip schemas with no adds\n if (schemaAdds.length === 0) {\n continue;\n }\n\n pipeline.pipe((d) => {\n const schemaResult = result.resolve(schemaId);\n\n assertIsNotNull(schemaResult);\n assertIsNotNull(schemaAdds);\n\n db.bulkDocs([...schemaAdds], null, (error, response) => {\n\n if (error) {\n d(Result.error(error));\n return;\n }\n\n // Starts EMPTY and is filled from the ok entries below.\n // Seeding it from every response entry and then pushing each\n // ok id again put every id in twice, so `_bulkGetAdditions`\n // asked for each document twice and the echo carried\n // duplicates into the change tracker.\n const ids: string[] = [];\n\n for (let i = 0, length = response.length; i < length; i++) {\n\n const doc = response[i];\n\n if (\"error\" in doc) {\n\n const reason = doc.reason ?? doc.error;\n\n d(Result.error(reason));\n return;\n }\n\n if (\"id\" in doc && \"ok\" in doc) {\n ids.push(doc.id);\n } else {\n d(Result.error(doc.error));\n return;\n }\n }\n\n this._bulkGetAdditions(ids, (bulkGetResponse) => {\n\n if (bulkGetResponse.ok !== Result.SUCCESS) {\n d(Result.error(bulkGetResponse));\n return;\n }\n\n for (let i = 0, length = bulkGetResponse.data.results.length; i < length; i++) {\n const docs = bulkGetResponse.data.results[i].docs;\n\n if (docs.length === 1) {\n const doc = docs[0];\n\n if (\"ok\" in doc) {\n schemaResult.adds.push(doc.ok as any);\n }\n }\n }\n\n d(Result.success());\n });\n });\n\n });\n }\n\n pipeline.filter((r) => {\n if (r.ok !== Result.SUCCESS) {\n d(r);\n return;\n }\n\n d(Result.success());\n });\n });\n });\n } catch (e) {\n d(Result.error(e));\n }\n }, done);\n }\n\n private _defaultBulkOperations(nonIdentitySchemaIds: SchemaId[], changes: BulkPersistChanges, result: BulkPersistResult, done: CallbackResult<never>): void {\n\n if (changes.aggregate.size === 0) {\n done(Result.success())\n return;\n }\n\n // Link each entity to a schema id below so we can easily look up the schema id for an entity\n const updates: { change: EntityUpdateInfo<UnknownRecord>, schemaId: SchemaId }[] = [];\n const adds: { entity: InferCreateType<UnknownRecord>, schemaId: SchemaId }[] = [];\n const removes: { entity: InferType<UnknownRecord>, schemaId: SchemaId }[] = [];\n\n for (const [schemaId, schemaChanges] of changes) {\n\n if (nonIdentitySchemaIds.includes(schemaId) === false || schemaChanges.hasItems === false) {\n continue;\n }\n\n updates.push(...schemaChanges.updates.map(x => ({ change: x, schemaId })));\n adds.push(...schemaChanges.adds.map(x => ({ entity: x, schemaId })));\n removes.push(...schemaChanges.removes.map(x => ({ entity: x, schemaId })));\n }\n\n if (updates.length === 0 && removes.length === 0 && adds.length === 0) {\n done(Result.success())\n return;\n }\n\n this._doWork((db, d) => {\n try {\n\n const tombstones = removes.map(x => ({ _id: x.entity._id, _rev: x.entity._rev, _deleted: true } as UnknownRecord));\n const updatedDocuments = updates.map(x => x.change.entity) as UnknownRecord[];\n\n this._withRevisions(db, [...tombstones, ...updatedDocuments], (revisionError) => {\n\n if (revisionError != null) {\n d(Result.error(revisionError));\n return;\n }\n\n db.bulkDocs([...tombstones, ...updatedDocuments], null, (error, response) => {\n\n if (error != null) {\n d(Result.error(error));\n return;\n }\n\n for (let i = 0, length = response.length; i < length; i++) {\n const doc = response[i];\n\n if (\"error\" in doc) {\n\n const reason = doc.reason ?? doc.error;\n\n d(Result.error(reason));\n return;\n }\n\n const removesIndex = removes.findIndex(x => x.entity._id === doc.id);\n\n if (removesIndex !== -1) {\n const { schemaId } = removes[removesIndex]\n const schemaResult = result.resolve(schemaId);\n\n assertIsNotNull(schemaResult);\n\n schemaResult.removes.push(doc as any);\n continue;\n }\n\n const updatesIndex = updates.findIndex(x => x.change.entity._id === doc.id);\n\n if (updatesIndex !== -1) {\n // Optimistically assume that the update worked as expected\n const update = updates[updatesIndex];\n\n const changesResult = result.resolve(update.schemaId);\n\n // Set the new rev\n (update.change.entity as UnknownRecord)._rev = doc.rev;\n\n changesResult.updates.push(update.change.entity);\n continue;\n }\n\n d(Result.error(new Error(\"Cannot classify resulting doc\")));\n return;\n }\n\n const pipeline = new WorkPipeline();\n\n for (let i = 0, length = nonIdentitySchemaIds.length; i < length; i++) {\n const schemaId = nonIdentitySchemaIds[i];\n const schemaAdds = adds.filter(x => x.schemaId === schemaId).map(x => x.entity);\n\n // Skip schemas with no adds\n if (schemaAdds.length === 0) {\n continue;\n }\n\n pipeline.pipe((d) => {\n const schemaResult = result.resolve(schemaId);\n\n assertIsNotNull(schemaResult);\n assertIsNotNull(schemaAdds);\n\n db.bulkDocs([...schemaAdds], null, (error, response) => {\n\n if (error) {\n d(Result.error(error));\n return;\n }\n\n // Starts EMPTY and is filled from the ok entries below.\n // Seeding it from every response entry and then pushing each\n // ok id again put every id in twice, so `_bulkGetAdditions`\n // asked for each document twice and the echo carried\n // duplicates into the change tracker.\n const ids: string[] = [];\n\n for (let i = 0, length = response.length; i < length; i++) {\n\n const doc = response[i];\n\n if (\"error\" in doc) {\n\n const reason = doc.reason ?? doc.error;\n\n d(Result.error(reason));\n return;\n }\n\n if (\"id\" in doc && \"ok\" in doc) {\n ids.push(doc.id);\n } else {\n d(Result.error(doc.error));\n return;\n }\n }\n\n this._bulkGetAdditions(ids, (bulkGetResponse) => {\n\n if (bulkGetResponse.ok !== Result.SUCCESS) {\n d(Result.error(bulkGetResponse));\n return;\n }\n\n for (let i = 0, length = bulkGetResponse.data.results.length; i < length; i++) {\n const docs = bulkGetResponse.data.results[i].docs;\n\n if (docs.length === 1) {\n const doc = docs[0];\n\n if (\"ok\" in doc) {\n schemaResult.adds.push(doc.ok as any);\n }\n }\n }\n\n d(Result.success());\n });\n });\n\n });\n }\n\n pipeline.filter((r) => {\n if (r.ok !== Result.SUCCESS) {\n d(r);\n return;\n }\n\n d(Result.success());\n });\n });\n });\n } catch (e) {\n d(Result.error(e));\n }\n }, done);\n }\n\n private _prepareProperties(...properties: PropertyInfo<any>[]) {\n\n properties.sort((a, b) => a.name.localeCompare(b.name, undefined, { sensitivity: 'base' }));\n // A view reads documents as they are stored, where a renamed segment is under its `from`\n // name. The view name is built from the same paths, so a design document saved when views\n // read the in-memory name, and so emitted nothing for a renamed property, is missing the new\n // view and gets replaced.\n const paths = properties.map(w => w.getAssignmentPath({ parent: \"doc\", useFromPropertyName: true }));\n const viewName = `by_${paths.join(\"_\")}`;\n\n return {\n properties,\n paths,\n viewName\n }\n }\n\n private resolveIndexes<TEntity extends {}, TShape extends unknown = TEntity>(event: DbPluginQueryEvent<TEntity, TShape>, done: CallbackResult<PouchDbDesignDoc | null>) {\n\n const indexes = event.operation.schema.getIndexes();\n\n if (indexes.length === 0) {\n done(Result.success(null));\n return;\n }\n\n if (this.indexCache != null) {\n done(Result.success(this.indexCache));\n return; // Already built\n }\n\n const ddoc: PouchDbDesignDoc = {\n _id: `_design/${INDEX_NAME}`,\n views: {}\n }\n\n for (let i = 0, length = indexes.length; i < length; i++) {\n const index = indexes[i];\n const { viewName, paths } = this._prepareProperties(...index.properties);\n\n if (index.properties.length === 1) {\n const path = paths[0];\n ddoc.views[viewName] = {\n map: `function(doc) {\n if (${path}) {\n emit(${path});\n }\n }`\n }\n continue;\n }\n\n ddoc.views[viewName] = {\n map: `function(doc) {\n if (${paths.join(\" && \")}) {\n emit([${paths.join(\",\")}]);\n }\n }`\n }\n }\n\n this._doWork((db, d) => {\n // change this out in the future? or make a new index, this does not return the rev which makes us need to call get again below\n db.allDocs({\n startkey: '_design/',\n endkey: '_design0',\n include_docs: true\n }).then(response => {\n\n // if we have no indexes, let's create it\n if (response.rows.length === 0) {\n db.put(ddoc as UnknownRecord, {}, (e) => {\n if (e) {\n d(Result.error(e));\n return;\n }\n\n this.indexCache = ddoc;\n\n d(Result.success(ddoc));\n });\n return;\n }\n\n const matchingIndex = response.rows.find(x => x.id === `_design/${INDEX_NAME}`);\n\n // make sure we have the correct index created\n if (matchingIndex == null) {\n db.put(ddoc as UnknownRecord, {}, (e) => {\n if (e) {\n d(Result.error(e));\n return;\n }\n\n this.indexCache = ddoc;\n\n d(Result.success(ddoc));\n });\n return;\n }\n\n assertIsNotNull(ddoc.views);\n assertIsNotNull(matchingIndex.doc);\n\n const views = Object.keys(ddoc.views)\n\n // make sure all of the views are in the document, if not update it\n if (views.some(x => (matchingIndex.doc as any).views[x] == null)) {\n\n // need to get the rev\n db.get(ddoc._id, {}, (e, result) => {\n\n if (e != null) {\n d(Result.error(e));\n return;\n }\n\n (result as any).views = ddoc.views\n\n db.put(result as any, {}, (e) => {\n\n if (e) {\n d(Result.error(e));\n return;\n }\n\n this.indexCache = ddoc;\n\n d(Result.success(ddoc));\n });\n })\n return;\n }\n\n d(Result.success(ddoc));\n }).catch(e => {\n d(Result.error(e));\n });\n }, done)\n }\n\n // id should be a string here because this is only run on identity inserts\n private _bulkGetAdditions<TEntity extends {}>(ids: string[], done: CallbackResult<PouchDB.Core.BulkGetResponse<TEntity>>) {\n\n if (ids.length === 0) {\n done(Result.success({ results: [] }));\n return;\n }\n\n this._doWork((db, d) => {\n db.bulkGet<TEntity>({\n docs: ids.map(w => ({ id: w as string }))\n }, (error, response) => {\n\n if (error) {\n d(Result.error(error));\n return\n }\n\n d(Result.success(response));\n });\n }, done);\n }\n\n private _validateSchemas(event: DbPluginBulkPersistEvent) {\n for (const [schemaId, schema] of event.schemas) {\n\n // Only schemas this persist actually writes: a store may declare other collections,\n // and an unused bad one should not block saves to the good ones.\n if (event.operation.get(schemaId)?.hasItems !== true) {\n continue;\n }\n\n if (schema.idProperties.length > 1) {\n throw new Error(\"PouchDB cannot have more than one key per document. Only '_id' is allowed to be the key\")\n }\n\n // An identity key is generated by PouchDB as '_id' and echoed back as '_id', so an\n // identity key under any other name is never filled in: every entity reads back with\n // an undefined key and the change tracker merges them all into one. Corruption, not\n // an error — so refuse the schema up front. A caller-supplied key (default/computed)\n // is stored as an ordinary field and round-trips fine under any name. A `.from()` on the\n // identity key is refused for the same reason: it is stored under its `from` name, and\n // PouchDB fills in `_id`.\n const key = schema.idProperties[0];\n if (key != null && key.isIdentity && (key.name !== \"_id\" || key.getResolvedName() !== \"_id\")) {\n throw new Error(\n `PouchDB generates identity keys as '_id'. The schema for collection '${schema.collectionName}' uses ` +\n `'${key.name}' as its identity key, which PouchDB cannot fill in. ` +\n `Declare the key as: _id: s.string().key().identity()`\n );\n }\n }\n }\n\n private _bulkPersist(\n event: DbPluginBulkPersistEvent,\n done: PluginEventCallbackPartialResult<BulkPersistResult>) {\n\n this._validateSchemas(event);\n\n const result = event.operation.toResult();\n const identitySchemaIds: SchemaId[] = [];\n const defaultSchemaIds: SchemaId[] = [];\n\n for (const [schemaId, schema] of event.schemas) {\n\n if (schema.hasIdentityKeys) {\n identitySchemaIds.push(schemaId);\n continue;\n }\n\n defaultSchemaIds.push(schemaId);\n }\n\n this._identityBulkOperations(identitySchemaIds, event.operation, result, (identityResult) => {\n\n if (identityResult.ok !== Result.SUCCESS) {\n done(PluginEventResult.error(event.id, identityResult.error))\n return;\n }\n\n this._defaultBulkOperations(defaultSchemaIds, event.operation, result, (defaultResult) => {\n\n if (defaultResult.ok !== Result.SUCCESS) {\n done(PluginEventResult.error(event.id, defaultResult.error))\n return;\n }\n\n done(PluginEventResult.success(event.id, result))\n });\n\n });\n }\n\n private _doWork<TResult, TEntity>(work: (db: PouchDB.Database<TEntity>, done: CallbackResult<TResult>) => void, done: CallbackResult<TResult>, shouldClose: boolean = false) {\n const db = this.database<TEntity>();\n\n work(db, (result) => {\n\n // The `return` is the fix. Without it, `shouldClose` ran BOTH branches: `done`\n // fired synchronously here and again from the close callback. A doubled callback\n // resolves a settled promise silently, but it also drives every pipeline stage\n // downstream twice — see known-defects #3's \"calls done exactly once\".\n if (shouldClose) {\n // The handle is shared, so closing it has to clear the cache too — the next\n // operation must open a fresh one rather than reuse a closed database.\n this.localDb = null;\n db.close(() => done(result));\n return;\n }\n\n done(result);\n })\n }\n\n destroy(_event: DbPluginEvent, done: (error?: any) => void): void {\n // Replication first. A live sync holds both the local and the remote database open\n // and keeps polling; destroying the local one underneath it leaves a replication\n // running against a database that no longer exists, which surfaces later as errors\n // from a plugin the caller believes it has finished with.\n if (this.syncHandle != null) {\n try {\n this.syncHandle.cancel();\n } catch {\n // An already-finished sync throws on cancel. Destroy's goal is that no\n // replication is running, and that is satisfied either way.\n }\n\n this.syncHandle = null;\n }\n\n // A destroyed database must not keep serving its cached design document to a plugin\n // that outlives it.\n this.indexCache = null;\n\n // `shouldClose: true`, so the handle this work opened is closed rather than left to\n // the garbage collector. It was false, which is what left destroy leaking the very\n // resource it was called to release.\n this._doWork((w, d) => {\n w.destroy(null, (e) => {\n if (e) {\n d(Result.error(e))\n return;\n }\n\n d(Result.success());\n });\n }, done, true);\n }\n\n\n bulkPersist(\n event: DbPluginBulkPersistEvent,\n done: PluginEventCallbackPartialResult<BulkPersistResult>) {\n\n const unitOfWork: SyncronousUnitOfWork = (d) => this._bulkPersist(event, (r) => {\n d();\n done(r)\n })\n\n this.queue.enqueue(unitOfWork.bind(this));\n }\n\n query<TRoot extends {}, TShape extends any = TRoot>(event: DbPluginQueryEvent<TRoot, TShape>, done: PluginEventCallbackResult<ITranslatedValue<TShape>>): void {\n\n const unitOfWork: SyncronousUnitOfWork = (d) => {\n const settle = (r: Parameters<typeof done>[0]) => {\n d();\n done(r);\n };\n\n // A join is two reads through `_query` — the UN-QUEUED path — on purpose: this unit of\n // work already holds the queue, so routing them through `query` would make them wait on\n // itself and the plugin would never answer. They are still serialized against every\n // other query, because this slot is held for both.\n if (event.operation.options.has(\"join\")) {\n joinInPlugin(event, (e, cb) => this._query(e, cb), settle as never);\n return;\n }\n\n this._query<TRoot, TShape>(event, settle);\n };\n\n this.queue.enqueue(unitOfWork.bind(this));\n }\n\n protected onGetIndex<TEntity extends {}, TShape extends unknown = TEntity>(_: IQuery<TEntity, TShape>, __: PouchDB.Find.FindRequest<unknown>, done: (result: null | string | [string, string]) => void) {\n done(null);\n }\n\n extractEqualityValueForProperty(expression: Expression, prop: PropertyInfo<any>): any | undefined {\n // Recursively search for a comparator expression that matches the property\n if (expression.type === \"comparator\" && (expression as ComparatorExpression).comparator === \"equals\") {\n // Check left side is property, right side is value\n if (expression.left && expression.left.type === \"property\" && (expression.left as any).property.name === prop.name && expression.right && expression.right.type === \"value\") {\n return (expression.right as any).value;\n }\n // Or right side is property, left side is value\n if (expression.right && expression.right.type === \"property\" && (expression.right as any).property.name === prop.name && expression.left && expression.left.type === \"value\") {\n return (expression.left as any).value;\n }\n }\n // Recursively check left and right\n if (expression.left) {\n const left = this.extractEqualityValueForProperty(expression.left, prop);\n if (left !== undefined) return left;\n }\n if (expression.right) {\n const right = this.extractEqualityValueForProperty(expression.right, prop);\n if (right !== undefined) return right;\n }\n return undefined;\n }\n\n private _findMatchingIndex(ddoc: PouchDbDesignDoc, expression: Expression): MatchingIndex {\n const queryProperties = getProperties(expression);\n\n const { viewName } = this._prepareProperties(...queryProperties);\n\n if (ddoc.views == null) {\n return null;\n }\n\n const index = ddoc.views[viewName];\n\n if (index == null) {\n return null;\n }\n\n const properties: MatchingIndex[\"properties\"] = [];\n\n for (const property of queryProperties) {\n const value = this.extractEqualityValueForProperty(expression, property);\n\n if (value === undefined) {\n return null\n }\n\n properties.push({\n property,\n value\n });\n }\n\n return {\n viewName,\n properties\n };\n }\n\n private _queryIndex<TEntity extends {}, TShape extends unknown = TEntity>(event: DbPluginQueryEvent<TEntity, TShape>, matchingIndex: MatchingIndex, done: CallbackResult<ITranslatedValue<TShape>>) {\n const translator = new PouchDbTranslator<TEntity, TShape>(event.operation);\n this._doWork((w, d) => {\n\n const options: PouchDB.Query.Options<any, any> = {\n include_docs: true,\n };\n\n const values = matchingIndex.properties.map(x => x.value);\n\n if (values.some(x => x == null) == false) {\n\n if (values.length === 1) {\n options.key = values[0];\n } else {\n options.keys = values;\n }\n }\n\n w.query(`${INDEX_NAME}/${matchingIndex.viewName}`, options, (error, response) => {\n\n if (error != null) {\n d(Result.error(error));\n return;\n }\n\n try {\n event.executedQueries.push({ text: `${INDEX_NAME}/${matchingIndex.viewName}: indexed view query` });\n\n const translated = translator.translate(response.rows.map(w => w.doc));\n d(Result.success(translated));\n } catch (e) {\n d(Result.error(e));\n }\n });\n }, done);\n }\n\n private _queryNoIndex<TEntity extends {}, TShape extends unknown = TEntity>(event: DbPluginQueryEvent<TEntity, TShape>, done: CallbackResult<ITranslatedValue<TShape>>) {\n const filters = event.operation.options.get(\"filter\")\n if (filters.length === 0) {\n this._queryWithNoFilters(event, done);\n return;\n }\n\n this._queryWithFilters(event, done);\n }\n\n private _queryWithNoFilters<TEntity extends {}, TShape extends unknown = TEntity>(event: DbPluginQueryEvent<TEntity, TShape>, done: CallbackResult<ITranslatedValue<TShape>>) {\n const translator = new PouchDbTranslator<TEntity, TShape>(event.operation);\n this._doWork((w, d) => {\n w.allDocs({\n include_docs: true\n }).then(response => {\n\n try {\n event.executedQueries.push({ text: \"allDocs({ include_docs: true }): full database scan, no index\" });\n\n const data = response.rows.map(w => w.doc);\n const translated = translator.translate(data);\n d(Result.success(translated));\n } catch (e) {\n d(Result.error(e));\n }\n }).catch(error => {\n d(Result.error(error));\n });\n }, done);\n }\n\n private _queryWithFilters<TEntity extends {}, TShape extends unknown = TEntity>(event: DbPluginQueryEvent<TEntity, TShape>, done: CallbackResult<ITranslatedValue<TShape>>) {\n const translator = new PouchDbTranslator<TEntity, TShape>(event.operation);\n this._doWork((w, d) => {\n\n if (this._name.startsWith(\"http\")) {\n // Cannot query remote databases using translator.matches, fallback to alldocs\n // Does not throw, will fail on the remote server\n w.allDocs({\n include_docs: true\n }).then(response => {\n const data = response.rows.map(w => w.doc);\n try {\n event.executedQueries.push({ text: \"allDocs({ include_docs: true }): full database scan, no index\" });\n\n const translated = translator.translate(data);\n d(Result.success(translated));\n } catch (e) {\n d(Result.error(e));\n }\n }).catch(error => {\n d(Result.error(error));\n });\n return;\n }\n\n w.query<{}, any>((doc, emit) => {\n if (typeof doc === \"object\" && \"_id\" in doc && translator.matches(doc)) {\n emit(doc._id, doc);\n }\n }, (error, response) => {\n\n if (error != null) {\n d(Result.error(error));\n return;\n }\n\n const data = response.rows.map(w => w.value);\n\n try {\n event.executedQueries.push({ text: \"view query\" });\n\n const translated = translator.translate(data);\n d(Result.success(translated));\n } catch (e) {\n d(Result.error(e));\n }\n });\n\n }, done);\n }\n\n private _query<TEntity extends {}, TShape extends unknown = TEntity>(event: DbPluginQueryEvent<TEntity, TShape>, done: PluginEventCallbackResult<ITranslatedValue<TShape>>): void {\n // Documents are matched and sorted by the caller's lambdas, over documents as they are\n // stored, where a `from` property has a different key. Handed back before any index is\n // chosen, so neither the index nor the view sees an option this plugin cannot run.\n reportRenamedProperties(event.operation.options);\n\n this.resolveIndexes(event, (r) => {\n if (r.ok !== Result.SUCCESS) {\n done(PluginEventResult.error(event.id, r.error))\n return;\n }\n\n const ddoc = r.data;\n\n if (ddoc == null) {\n this._queryNoIndex(event, done);\n return;\n }\n\n const mapMatchingIndex = this.findMatchingIndexForMap(ddoc, event);\n\n if (mapMatchingIndex != null) {\n this._queryIndex(event, mapMatchingIndex, done);\n return;\n }\n\n const expression = this._getExpressionFromQuery(event);\n\n if (Expression.isEmpty(expression)) {\n this._queryNoIndex(event, done);\n return;\n }\n\n const matchingIndex = this._findMatchingIndex(ddoc, expression);\n\n if (matchingIndex == null) {\n this._queryNoIndex(event, done);\n return;\n }\n\n this._queryIndex(event, matchingIndex, done);\n });\n }\n\n private _getExpressionFromQuery<TEntity extends {}, TShape>(event: DbPluginQueryEvent<TEntity, TShape>) {\n const filters = event.operation.options.get(\"filter\");\n\n const databaseFilters = filters.filter(x => x.option.target === \"database\" && x.option.reason === \"executed\");\n\n if (databaseFilters.length === 0) {\n return Expression.EMPTY;\n }\n\n const expressions = databaseFilters.map(x => x.option.value.expression);\n\n return combineExpressions(...expressions);\n }\n\n private findMatchingIndexForMap<TEntity extends {}, TShape>(ddoc: PouchDbDesignDoc, event: DbPluginQueryEvent<TEntity, TShape>): MatchingIndex | null {\n const map = event.operation.options.getLast(\"map\");\n const filters = event.operation.options.get(\"filter\");\n\n // we only want to look at the index if there are no filters\n if (filters.length > 0) {\n return null;\n }\n\n if (map == null || map.target !== \"database\") {\n return null;\n }\n\n if (map.value.fields.length !== 1 || map.value.fields[0].property == null) {\n return null;\n }\n\n const property = map.value.fields[0].property;\n\n const { viewName } = this._prepareProperties(property);\n\n if (ddoc.views == null) {\n return null;\n }\n\n const index = ddoc.views[viewName];\n\n if (index == null) {\n return null;\n }\n\n return {\n viewName,\n properties: [{ property, value: null }]\n }\n }\n}","export { PouchDbPlugin } from './PouchDbPlugin';"],"names":["assertIsArray","JsonTranslator","getStorageDateReviver","PouchDbTranslator","query","item","filterChain","filters","databaseFilters","x","index","currentFilter","nextFilter","filter","selector","params","data","documents","i","length","document","PouchDB","SyncronousQueue","WorkPipeline","joinInPlugin","reportRenamedProperties","PluginEventResult","Result","assertIsNotNull","combineExpressions","Expression","getProperties","INDEX_NAME","PouchDbPlugin","_sync","_queryType","rest","name","options","schemas","localDb","remoteDb","sync","e","db","done","missing","String","response","revisions","Map","row","revision","error","identitySchemaIds","changes","result","updates","adds","removes","schemaId","schemaChanges","d","updatedDocuments","w","errors","tombstones","revisionError","doc","updatesIndex","update","changesResult","removesIndex","remove","pipeline","schemaAdds","schemaResult","ids","reason","bulkGetResponse","docs","r","nonIdentitySchemaIds","Error","properties","a","b","undefined","paths","viewName","event","indexes","ddoc","path","matchingIndex","views","Object","schema","key","defaultSchemaIds","identityResult","defaultResult","work","shouldClose","_event","unitOfWork","settle","cb","_","__","expression","prop","left","right","queryProperties","property","value","translator","values","translated","emit","mapMatchingIndex","expressions","map"],"mappings":";;;;;;;AAAA;AACA;AACA;AACA;AACA;AACA,iCAAiC,WAAW;AAC5C;AACA;;;;;ACPA;AACA;AACA;AACA,kDAAkD,wCAAwC;AAC1F;AACA;AACA,E;;;;ACNA,wF;;;;ACAA;AACA;AACA;AACA,uDAAuD,iBAAiB;AACxE;AACA,gDAAgD,aAAa;AAC7D,E;;;;;;;;;;;;;;;;;;;;;ACNyD;AAEwC;AAChB;AAE1E,MAAMG,0BAAgFF,sCAAcA;IAEvG;;;;KAIC,GACgB,YAAuC;IAChD,gBAAqD,KAAK;IAElE,YAAYG,KAA8B,CAAE;QACxC,KAAK,CAACA;QACN,IAAI,CAAC,WAAW,GAAGF,gDAAqBA,CAACE,MAAM,MAAM;IACzD;IAEA,QAAQC,IAAa,EAAE;QACnB,mCAAmC;QACnC,MAAMC,cAAc,IAAI,CAAC,kBAAkB;QAE3C,IAAI,CAAC,WAAW,GAAGD;QAEnB,8DAA8D;QAC9D,OAAOC,YAAYD;IACvB;IAEQ,qBAAiD;QACrD,mCAAmC;QACnC,IAAI,IAAI,CAAC,aAAa,KAAK,MAAM;YAC7B,OAAO,IAAI,CAAC,aAAa;QAC7B;QAEA,mCAAmC;QACnC,MAAME,UAAU,IAAI,CAAC,KAAK,CAAC,OAA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QAAQ;QAE7C,MAAM,EAAElC,QAAQ,EAAE,GAAG,IAAI,CAAC,kBAAkB,CAAC0B;QAE7C,IAAIvB,KAAK,KAAK,IAAI,MAAM;YACpB,OAAO;QACX;QAEA,MAAMlF,QAAQkF,KAAK,KAAK,CAACH,SAAS;QAElC,IAAI/E,SAAS,MAAM;YACf,OAAO;QACX;QAEA,OAAO;YACH+E;YACA,YAAY;gBAAC;oBAAE0B;oBAAU,OAAO;gBAAK;aAAE;QAC3C;IACJ;AACJ;;;AC3rCgD"}
|
package/dist/index.js
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import pouchdb from "pouchdb";
|
|
2
2
|
import { assertIsArray, assertIsNotNull } from "@routier/core/assertions";
|
|
3
|
-
import { JsonTranslator, joinInPlugin } from "@routier/core/plugins";
|
|
3
|
+
import { JsonTranslator, joinInPlugin, reportRenamedProperties } from "@routier/core/plugins";
|
|
4
|
+
import { getStorageDateReviver } from "@routier/core/schema";
|
|
4
5
|
import { SyncronousQueue, WorkPipeline } from "@routier/core/pipeline";
|
|
5
6
|
import { PluginEventResult, Result } from "@routier/core/results";
|
|
6
7
|
import { Expression, combineExpressions, getProperties } from "@routier/core/expressions";
|
|
@@ -34,19 +35,27 @@ __webpack_require__.d(__webpack_exports__, {
|
|
|
34
35
|
|
|
35
36
|
;// CONCATENATED MODULE: external "@routier/core/plugins"
|
|
36
37
|
|
|
38
|
+
;// CONCATENATED MODULE: external "@routier/core/schema"
|
|
39
|
+
|
|
37
40
|
;// CONCATENATED MODULE: ./src/PouchDbTranslator.ts
|
|
38
41
|
|
|
39
42
|
|
|
43
|
+
|
|
40
44
|
class PouchDbTranslator extends JsonTranslator {
|
|
41
|
-
|
|
45
|
+
/**
|
|
46
|
+
* PouchDB stores JSON, so a date comes back as the ISO string the datastore serialized it to.
|
|
47
|
+
* The caller's lambdas compare and call Dates, so every document is revived before one runs.
|
|
48
|
+
* Only the dates: keys stay under their `from` names. `null` for a schema with no dates.
|
|
49
|
+
*/ reviveDates;
|
|
42
50
|
cachedMatches = null;
|
|
43
51
|
constructor(query){
|
|
44
52
|
super(query);
|
|
45
|
-
this.
|
|
53
|
+
this.reviveDates = getStorageDateReviver(query.schema);
|
|
46
54
|
}
|
|
47
55
|
matches(item) {
|
|
48
56
|
// Get or build cached filter chain
|
|
49
57
|
const filterChain = this.resolveFilterChain();
|
|
58
|
+
this.reviveDates?.(item);
|
|
50
59
|
// Execute the chain (no loops, just recursive function calls)
|
|
51
60
|
return filterChain(item);
|
|
52
61
|
}
|
|
@@ -57,7 +66,8 @@ class PouchDbTranslator extends JsonTranslator {
|
|
|
57
66
|
}
|
|
58
67
|
// Build and cache the filter chain
|
|
59
68
|
const filters = this.query.options.get("filter");
|
|
60
|
-
|
|
69
|
+
// Not a filter the plugin reported: the datastore runs that one, after deserialization
|
|
70
|
+
const databaseFilters = filters.filter((x)=>x.option.target === "database" && x.option.reason === "executed");
|
|
61
71
|
this.cachedMatches = this.buildFilterChain(databaseFilters, 0);
|
|
62
72
|
return this.cachedMatches;
|
|
63
73
|
}
|
|
@@ -92,22 +102,21 @@ class PouchDbTranslator extends JsonTranslator {
|
|
|
92
102
|
}
|
|
93
103
|
translate(data) {
|
|
94
104
|
assertIsArray(data);
|
|
95
|
-
const
|
|
105
|
+
const documents = [];
|
|
96
106
|
for(let i = 0, length = data.length; i < length; i++){
|
|
97
|
-
const
|
|
107
|
+
const document = data[i];
|
|
98
108
|
// design docs can be included in the result, ignore them
|
|
99
|
-
if (
|
|
109
|
+
if (typeof document._id === "string" && document._id.startsWith("_design")) {
|
|
100
110
|
continue;
|
|
101
111
|
}
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
} catch (e) {
|
|
107
|
-
throw new Error(`Error deserializing entity from db. Message: ${e.message}, Entity: ${JSON.stringify(entity, null, 2)}`);
|
|
108
|
-
}
|
|
112
|
+
// Again, whether or not the view predicate revived it: a view may hand back a copy of
|
|
113
|
+
// what it emitted, and a document read without a view was never revived
|
|
114
|
+
this.reviveDates?.(document);
|
|
115
|
+
documents.push(document);
|
|
109
116
|
}
|
|
110
|
-
|
|
117
|
+
// Documents stay in storage shape. The datastore deserializes the rows this returns, by
|
|
118
|
+
// their `from` names, and a join does the same per side.
|
|
119
|
+
return super.translate(documents);
|
|
111
120
|
}
|
|
112
121
|
}
|
|
113
122
|
|
|
@@ -587,8 +596,13 @@ class PouchDbPlugin {
|
|
|
587
596
|
properties.sort((a, b)=>a.name.localeCompare(b.name, undefined, {
|
|
588
597
|
sensitivity: 'base'
|
|
589
598
|
}));
|
|
599
|
+
// A view reads documents as they are stored, where a renamed segment is under its `from`
|
|
600
|
+
// name. The view name is built from the same paths, so a design document saved when views
|
|
601
|
+
// read the in-memory name, and so emitted nothing for a renamed property, is missing the new
|
|
602
|
+
// view and gets replaced.
|
|
590
603
|
const paths = properties.map((w)=>w.getAssignmentPath({
|
|
591
|
-
parent: "doc"
|
|
604
|
+
parent: "doc",
|
|
605
|
+
useFromPropertyName: true
|
|
592
606
|
}));
|
|
593
607
|
const viewName = `by_${paths.join("_")}`;
|
|
594
608
|
return {
|
|
@@ -615,10 +629,7 @@ class PouchDbPlugin {
|
|
|
615
629
|
const index = indexes[i];
|
|
616
630
|
const { viewName, paths } = this._prepareProperties(...index.properties);
|
|
617
631
|
if (index.properties.length === 1) {
|
|
618
|
-
const
|
|
619
|
-
const path = property.getAssignmentPath({
|
|
620
|
-
parent: "doc"
|
|
621
|
-
});
|
|
632
|
+
const path = paths[0];
|
|
622
633
|
ddoc.views[viewName] = {
|
|
623
634
|
map: `function(doc) {
|
|
624
635
|
if (${path}) {
|
|
@@ -720,10 +731,26 @@ class PouchDbPlugin {
|
|
|
720
731
|
}, done);
|
|
721
732
|
}
|
|
722
733
|
_validateSchemas(event) {
|
|
723
|
-
for (const [, schema] of event.schemas){
|
|
734
|
+
for (const [schemaId, schema] of event.schemas){
|
|
735
|
+
// Only schemas this persist actually writes: a store may declare other collections,
|
|
736
|
+
// and an unused bad one should not block saves to the good ones.
|
|
737
|
+
if (event.operation.get(schemaId)?.hasItems !== true) {
|
|
738
|
+
continue;
|
|
739
|
+
}
|
|
724
740
|
if (schema.idProperties.length > 1) {
|
|
725
741
|
throw new Error("PouchDB cannot have more than one key per document. Only '_id' is allowed to be the key");
|
|
726
742
|
}
|
|
743
|
+
// An identity key is generated by PouchDB as '_id' and echoed back as '_id', so an
|
|
744
|
+
// identity key under any other name is never filled in: every entity reads back with
|
|
745
|
+
// an undefined key and the change tracker merges them all into one. Corruption, not
|
|
746
|
+
// an error — so refuse the schema up front. A caller-supplied key (default/computed)
|
|
747
|
+
// is stored as an ordinary field and round-trips fine under any name. A `.from()` on the
|
|
748
|
+
// identity key is refused for the same reason: it is stored under its `from` name, and
|
|
749
|
+
// PouchDB fills in `_id`.
|
|
750
|
+
const key = schema.idProperties[0];
|
|
751
|
+
if (key != null && key.isIdentity && (key.name !== "_id" || key.getResolvedName() !== "_id")) {
|
|
752
|
+
throw new Error(`PouchDB generates identity keys as '_id'. The schema for collection '${schema.collectionName}' uses ` + `'${key.name}' as its identity key, which PouchDB cannot fill in. ` + `Declare the key as: _id: s.string().key().identity()`);
|
|
753
|
+
}
|
|
727
754
|
}
|
|
728
755
|
}
|
|
729
756
|
_bulkPersist(event, done) {
|
|
@@ -983,6 +1010,10 @@ class PouchDbPlugin {
|
|
|
983
1010
|
}, done);
|
|
984
1011
|
}
|
|
985
1012
|
_query(event, done) {
|
|
1013
|
+
// Documents are matched and sorted by the caller's lambdas, over documents as they are
|
|
1014
|
+
// stored, where a `from` property has a different key. Handed back before any index is
|
|
1015
|
+
// chosen, so neither the index nor the view sees an option this plugin cannot run.
|
|
1016
|
+
reportRenamedProperties(event.operation.options);
|
|
986
1017
|
this.resolveIndexes(event, (r)=>{
|
|
987
1018
|
if (r.ok !== Result.SUCCESS) {
|
|
988
1019
|
done(PluginEventResult.error(event.id, r.error));
|
|
@@ -1013,7 +1044,7 @@ class PouchDbPlugin {
|
|
|
1013
1044
|
}
|
|
1014
1045
|
_getExpressionFromQuery(event) {
|
|
1015
1046
|
const filters = event.operation.options.get("filter");
|
|
1016
|
-
const databaseFilters = filters.filter((x)=>x.option.target === "database");
|
|
1047
|
+
const databaseFilters = filters.filter((x)=>x.option.target === "database" && x.option.reason === "executed");
|
|
1017
1048
|
if (databaseFilters.length === 0) {
|
|
1018
1049
|
return Expression.EMPTY;
|
|
1019
1050
|
}
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sources":["webpack://@routier/pouchdb-plugin/webpack/runtime/define_property_getters","webpack://@routier/pouchdb-plugin/webpack/runtime/has_own_property","webpack://@routier/pouchdb-plugin/./src/PouchDbTranslator.ts","webpack://@routier/pouchdb-plugin/./src/PouchDbPlugin.ts","webpack://@routier/pouchdb-plugin/./src/index.ts"],"sourcesContent":["__webpack_require__.d = (exports, definition) => {\n\tfor(var key in definition) {\n if(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {\n Object.defineProperty(exports, key, { enumerable: true, get: definition[key] });\n }\n }\n};","__webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))","import { assertIsArray } from \"@routier/core/assertions\";\nimport { Filter, ParamsFilter } from \"@routier/core/expressions\";\nimport { IQuery, JsonTranslator, QueryCollectionItem, QueryOption } from \"@routier/core/plugins\";\nimport { CompiledSchema, InferType } from \"@routier/core/schema\";\n\nexport class PouchDbTranslator<TEntity extends {}, TShape extends unknown = TEntity> extends JsonTranslator<TEntity, TShape> {\n\n private schema: CompiledSchema<TEntity>;\n private cachedMatches: ((item: unknown) => boolean) | null = null;\n\n constructor(query: IQuery<TEntity, TShape>) {\n super(query);\n this.schema = query.schema;\n }\n\n matches(item: unknown) {\n // Get or build cached filter chain\n const filterChain = this.resolveFilterChain();\n\n // Execute the chain (no loops, just recursive function calls)\n return filterChain(item);\n }\n\n private resolveFilterChain(): (item: unknown) => boolean {\n // Return cached chain if available\n if (this.cachedMatches !== null) {\n return this.cachedMatches;\n }\n\n // Build and cache the filter chain\n const filters = this.query.options.get(\"filter\");\n const databaseFilters = filters.filter(x => x.option.target === \"database\");\n\n this.cachedMatches = this.buildFilterChain(databaseFilters, 0);\n\n return this.cachedMatches;\n }\n\n private buildFilterChain(filters: QueryCollectionItem<TShape, \"filter\">[], index: number): (item: unknown) => boolean {\n // Base case: no more filters, return true\n if (index >= filters.length) {\n return () => true;\n }\n\n // Get current filter function\n const currentFilter = this.evaluateFilter(filters[index].option);\n\n // Build the rest of the chain\n const nextFilter = this.buildFilterChain(filters, index + 1);\n\n // Return a function that checks current filter and calls next\n return (item: unknown) => {\n if (!currentFilter(item)) {\n return false; // Early termination\n }\n return nextFilter(item); // Recursive call to next filter\n };\n }\n\n private evaluateFilter(filter: QueryOption<TShape, \"filter\">): (item: unknown) => boolean {\n if (filter.value.params == null) {\n const selector = filter.value.filter as Filter<unknown>;\n return (item: unknown) => selector(item) !== false;\n }\n\n const selector = filter.value.filter as ParamsFilter<unknown, {}>;\n const params = filter.value.params;\n return (item: unknown) => selector([item, params]) !== false;\n }\n\n override translate(data: unknown) {\n assertIsArray(data);\n\n const result: unknown[] = [];\n\n for (let i = 0, length = data.length; i < length; i++) {\n const entity: any = data[i];\n\n // design docs can be included in the result, ignore them\n if (\"_id\" in entity && typeof entity._id === \"string\" && entity._id.startsWith(\"_design\")) {\n continue;\n }\n\n try {\n // PouchDB converts a Date to a string when it is saved, we need to convert it back when it's selected\n result.push(this.schema.deserialize(entity as InferType<TEntity>));\n data[i] = null;\n } catch (e) {\n throw new Error(`Error deserializing entity from db. Message: ${e.message}, Entity: ${JSON.stringify(entity, null, 2)}`)\n }\n }\n\n return super.translate(result);\n }\n\n}","import PouchDB from 'pouchdb';\nimport { PouchDbTranslator } from './PouchDbTranslator';\nimport { SyncronousQueue, SyncronousUnitOfWork, WorkPipeline } from '@routier/core/pipeline';\nimport { InferCreateType, InferType, PropertyInfo, SchemaId } from '@routier/core/schema';\nimport { DbPluginBulkPersistEvent, DbPluginEvent, DbPluginQueryEvent, EntityUpdateInfo, IDbPlugin, IQuery, ITranslatedValue, joinInPlugin } from '@routier/core/plugins';\nimport { CallbackResult, PluginEventCallbackPartialResult, PluginEventCallbackResult, PluginEventResult, Result } from '@routier/core/results';\nimport { assertIsNotNull } from '@routier/core/assertions';\nimport { combineExpressions, ComparatorExpression, Expression, getProperties } from '@routier/core/expressions';\nimport { BulkPersistChanges, BulkPersistResult, ReadonlySchemaCollection, UnknownRecord } from '@routier/core';\n\nconst INDEX_NAME = \"routier_pdb_indexes\"\n\ntype PouchDBPluginOptions = PouchDB.Configuration.DatabaseConfiguration & {\n queryType?: \"default\" | \"memory-optimized\" | \"experimental\";\n sync?: PouchDB.Replication.SyncOptions & {\n remoteDb: string;\n onChange?: (schemas: ReadonlySchemaCollection, event: PouchDB.Replication.SyncResult<{}>) => void;\n onError?: (schemas: ReadonlySchemaCollection, error?: any) => void;\n onComplete?: (schemas: ReadonlySchemaCollection, event: PouchDB.Replication.SyncResultComplete<{}>) => void;\n onPaused?: (schemas: ReadonlySchemaCollection, event?: any) => void;\n onActive?: (schemas: ReadonlySchemaCollection) => void;\n onDenied?: (schemas: ReadonlySchemaCollection, event?: any) => void;\n auth?: {\n username: string;\n password: string;\n };\n headers?: { [key: string]: string };\n };\n}\n\nexport type PouchDbDesignDoc = {\n _id: string;\n language?: string;\n views?: {\n [viewName: string]: {\n map: string | Function;\n reduce?: string | Function;\n };\n };\n filters?: {\n [filterName: string]: string | Function;\n };\n validate_doc_update?: string | Function;\n options?: Record<string, any>;\n [key: string]: any; // allow other CouchDB features\n}\n\ntype MatchingIndex = {\n viewName: string,\n properties: {\n property: PropertyInfo<any>,\n value: unknown\n }[]\n}\n\nexport class PouchDbPlugin implements IDbPlugin {\n\n private readonly _name: string;\n private readonly _options?: PouchDBPluginOptions;\n\n /**\n * Per INSTANCE, all three of these. They used to be module-level, which made every\n * PouchDbPlugin in the process share one database's state regardless of its name:\n *\n * - the **queue** serialized work across unrelated databases, so a slow save against one\n * database blocked a read against another;\n * - the **index cache** was keyed by nothing at all, so the first database's design\n * document was reported as every database's;\n * - the **sync handle** lived under the literal key `\"sync\"`, so only the FIRST plugin in\n * a process could establish replication — every later one got back the first one's\n * handle, pointed at a different remote.\n *\n * A plugin instance is the natural scope: it owns exactly one database name.\n */\n private readonly queue = new SyncronousQueue();\n private indexCache: PouchDbDesignDoc | null = null;\n private syncHandle: PouchDB.Replication.Sync<{}> | null = null;\n\n /**\n * ONE local database handle for this plugin, shared by every operation and by `sync()`.\n *\n * This used to be a fresh `new PouchDB(name)` per operation, with `sync()` constructing\n * yet another one of its own. Two PouchDB objects over the same name only behave as one\n * database when the ADAPTER broadcasts changes between them: IndexedDB does, so this\n * works in a browser, and the in-memory adapter does not, so under it a live replication\n * never observes the plugin's own writes and the plugin never observes what replication\n * pulls in. Replication and data access were effectively wired to two different databases\n * on any adapter without that broadcast.\n *\n * One handle removes the question, and removes the per-operation construction churn with\n * it. It is closed and cleared by `destroy()`.\n */\n private localDb: PouchDB.Database<any> | null = null;\n\n private database<TEntity>(): PouchDB.Database<TEntity> {\n if (this.localDb == null) {\n const { sync: _sync, queryType: _queryType, ...rest } = this._options ?? {};\n this.localDb = new PouchDB(this._name, rest);\n }\n\n return this.localDb as PouchDB.Database<TEntity>;\n }\n\n constructor(name: string, options?: PouchDBPluginOptions) {\n this._name = name;\n this._options = options;\n }\n\n /**\n * See `IDbPlugin.databaseName`. The local database name — the same value two contexts\n * opening one PouchDB database supply, so they share subscription channels. Remote sync\n * targets are deliberately not part of it: two local databases replicating to one remote\n * are still two databases.\n */\n get databaseName(): string {\n return this._name;\n }\n\n sync(schemas: ReadonlySchemaCollection) {\n\n assertIsNotNull(this._options?.sync, \"Cannot start sync process without sync options. Provide sync options in PouchDbPlugin constructor\");\n\n if (this.syncHandle == null) {\n // No placeholder write before the work. The previous shape assigned `{}` first\n // and only replaced it after `sync()` returned, so if constructing either\n // database threw, the cache kept the placeholder forever and every later call\n // returned an empty object cast as a Sync — no replication, no error, no way back\n // without restarting the process.\n // The plugin's own handle, not a second one over the same name: replication has\n // to observe the writes this plugin makes, and on an adapter that does not\n // broadcast changes between instances (the in-memory one, for example) a\n // separate object is a separate database in every way that matters here.\n const localDb = this.database();\n const remoteDb = new PouchDB(this._options.sync.remoteDb);\n\n // Set up sync\n const sync = localDb.sync(remoteDb, {\n ...this._options.sync\n });\n\n if (this._options.sync.onChange) {\n sync.on('change', (e) => this._options.sync.onChange(schemas, e));\n }\n\n if (this._options.sync.onActive) {\n sync.on('active', () => this._options.sync.onActive(schemas));\n }\n\n if (this._options.sync.onComplete) {\n sync.on('complete', (e) => this._options.sync.onComplete(schemas, e));\n }\n\n if (this._options.sync.onDenied) {\n sync.on('denied', (e) => this._options.sync.onDenied(schemas, e));\n }\n\n if (this._options.sync.onError) {\n sync.on('error', (e) => this._options.sync.onError(schemas, e));\n }\n\n if (this._options.sync.onPaused) {\n sync.on('paused', (e) => this._options.sync.onPaused(schemas, e));\n }\n\n // Retained so destroy() can cancel it. An uncancelled sync keeps polling a\n // remote that the caller believes it has finished with, and holds both databases\n // open with it.\n this.syncHandle = sync;\n }\n\n return this.syncHandle;\n }\n\n /**\n * Fills in the `_rev` of any document about to be updated or removed that arrives without\n * one, in a single lookup.\n *\n * PouchDB is the only backend in this repository that needs a revision to change a row, and\n * it used to make that the CALLER's problem: a schema had to declare `_rev` and every\n * entity had to carry the current value. That is this plugin's write protocol leaking into\n * every schema written for it, and it made whole features unusable here — a generated\n * search-index row is built from the document being saved, so it has an id and never a\n * revision, and every edit to an indexed document failed with a conflict whose only\n * detail was `true`.\n *\n * A revision is a fact this database owns, so this is the layer that should look it up.\n * One `allDocs` for every id that needs one, only when at least one does, and never on the\n * path where every entity already carries its own. Nothing above has to know.\n *\n * A missing row resolves to no revision and is left alone: an update to a document that is\n * not there must still fail, and it fails the way it always did.\n */\n private _withRevisions(\n db: PouchDB.Database,\n documents: UnknownRecord[],\n done: (error: unknown | null) => void\n ) {\n const missing = documents\n .filter(document => document._rev == null && document._id != null)\n .map(document => String(document._id));\n\n if (missing.length === 0) {\n done(null);\n return;\n }\n\n db.allDocs({ keys: missing }).then(response => {\n const revisions = new Map<string, string>();\n\n for (const row of response?.rows ?? []) {\n const revision = (row as { value?: { rev?: string, deleted?: boolean } }).value;\n\n if (revision?.rev != null && revision.deleted !== true) {\n revisions.set(String(row.key), revision.rev);\n }\n }\n\n for (const document of documents) {\n\n if (document._rev == null) {\n const revision = revisions.get(String(document._id));\n\n if (revision != null) {\n document._rev = revision;\n }\n }\n }\n\n done(null);\n }).catch(error => done(error));\n }\n\n private _identityBulkOperations(identitySchemaIds: SchemaId[], changes: BulkPersistChanges, result: BulkPersistResult, done: CallbackResult<never>): void {\n\n if (changes.aggregate.size === 0) {\n done(Result.success())\n return;\n }\n\n // Link each entity to a schema id below so we can easily look up the schema id for an entity\n const updates: { change: EntityUpdateInfo<UnknownRecord>, schemaId: SchemaId }[] = [];\n const adds: { entity: InferCreateType<UnknownRecord>, schemaId: SchemaId }[] = [];\n const removes: { entity: InferType<UnknownRecord>, schemaId: SchemaId }[] = [];\n\n for (const [schemaId, schemaChanges] of changes) {\n\n if (identitySchemaIds.includes(schemaId) === false || schemaChanges.hasItems === false) {\n continue;\n }\n\n updates.push(...schemaChanges.updates.map(x => ({ change: x, schemaId })));\n adds.push(...schemaChanges.adds.map(x => ({ entity: x, schemaId })));\n removes.push(...schemaChanges.removes.map(x => ({ entity: x, schemaId })));\n }\n\n // Do adds separate. Updates/Removes already have an id that we can reference\n // Default can do the same as updates/removes below since it has an id\n // Check again now to see if we have any identity schema changes\n if (updates.length === 0 && removes.length === 0 && adds.length === 0) {\n done(Result.success())\n return;\n }\n\n this._doWork((db, d) => {\n try {\n\n const updatedDocuments = [...updates].map(w => w.change.entity);\n const errors: any[] = [];\n\n // Tombstones are built here rather than inline so a missing revision can be\n // resolved into them before the write.\n const tombstones = removes.map(w => ({ _id: w.entity._id, _rev: w.entity._rev, _deleted: true } as UnknownRecord));\n\n this._withRevisions(db, [...tombstones, ...updatedDocuments] as UnknownRecord[], (revisionError) => {\n\n if (revisionError != null) {\n d(Result.error(revisionError));\n return;\n }\n\n db.bulkDocs([...tombstones, ...updatedDocuments], null, (error, response) => {\n\n if (error) {\n d(Result.error(error));\n return;\n }\n\n for (let i = 0, length = response.length; i < length; i++) {\n const doc = response[i];\n\n if (\"error\" in doc && doc.error === true) {\n errors.push(doc); // send back the entire error\n continue;\n }\n\n if (\"id\" in doc && \"ok\" in doc) {\n const updatesIndex = updates.findIndex(x => x.change.entity._id === doc.id);\n\n if (updatesIndex !== -1) {\n // Optimistically assume that the update worked as expected\n const update = updates[updatesIndex];\n\n const changesResult = result.resolve(update.schemaId);\n\n // Set the new rev\n (update.change.entity as UnknownRecord)._rev = doc.rev;\n\n changesResult.updates.push(update.change.entity);\n continue;\n }\n\n const removesIndex = removes.findIndex(x => x.entity._id === doc.id);\n\n if (removesIndex !== -1) {\n\n const remove = removes[removesIndex];\n\n const changesResult = result.resolve(remove.schemaId);\n\n changesResult.removes.push(remove.entity);\n }\n }\n }\n\n if (errors.length > 0) {\n d(Result.error(errors));\n return;\n }\n\n const pipeline = new WorkPipeline();\n\n for (let i = 0, length = identitySchemaIds.length; i < length; i++) {\n const schemaId = identitySchemaIds[i];\n const schemaAdds = adds.filter(x => x.schemaId === schemaId).map(x => x.entity);\n\n // Skip schemas with no adds\n if (schemaAdds.length === 0) {\n continue;\n }\n\n pipeline.pipe((d) => {\n const schemaResult = result.resolve(schemaId);\n\n assertIsNotNull(schemaResult);\n assertIsNotNull(schemaAdds);\n\n db.bulkDocs([...schemaAdds], null, (error, response) => {\n\n if (error) {\n d(Result.error(error));\n return;\n }\n\n // Starts EMPTY and is filled from the ok entries below.\n // Seeding it from every response entry and then pushing each\n // ok id again put every id in twice, so `_bulkGetAdditions`\n // asked for each document twice and the echo carried\n // duplicates into the change tracker.\n const ids: string[] = [];\n\n for (let i = 0, length = response.length; i < length; i++) {\n\n const doc = response[i];\n\n if (\"error\" in doc) {\n\n const reason = doc.reason ?? doc.error;\n\n d(Result.error(reason));\n return;\n }\n\n if (\"id\" in doc && \"ok\" in doc) {\n ids.push(doc.id);\n } else {\n d(Result.error(doc.error));\n return;\n }\n }\n\n this._bulkGetAdditions(ids, (bulkGetResponse) => {\n\n if (bulkGetResponse.ok !== Result.SUCCESS) {\n d(Result.error(bulkGetResponse));\n return;\n }\n\n for (let i = 0, length = bulkGetResponse.data.results.length; i < length; i++) {\n const docs = bulkGetResponse.data.results[i].docs;\n\n if (docs.length === 1) {\n const doc = docs[0];\n\n if (\"ok\" in doc) {\n schemaResult.adds.push(doc.ok as any);\n }\n }\n }\n\n d(Result.success());\n });\n });\n\n });\n }\n\n pipeline.filter((r) => {\n if (r.ok !== Result.SUCCESS) {\n d(r);\n return;\n }\n\n d(Result.success());\n });\n });\n });\n } catch (e) {\n d(Result.error(e));\n }\n }, done);\n }\n\n private _defaultBulkOperations(nonIdentitySchemaIds: SchemaId[], changes: BulkPersistChanges, result: BulkPersistResult, done: CallbackResult<never>): void {\n\n if (changes.aggregate.size === 0) {\n done(Result.success())\n return;\n }\n\n // Link each entity to a schema id below so we can easily look up the schema id for an entity\n const updates: { change: EntityUpdateInfo<UnknownRecord>, schemaId: SchemaId }[] = [];\n const adds: { entity: InferCreateType<UnknownRecord>, schemaId: SchemaId }[] = [];\n const removes: { entity: InferType<UnknownRecord>, schemaId: SchemaId }[] = [];\n\n for (const [schemaId, schemaChanges] of changes) {\n\n if (nonIdentitySchemaIds.includes(schemaId) === false || schemaChanges.hasItems === false) {\n continue;\n }\n\n updates.push(...schemaChanges.updates.map(x => ({ change: x, schemaId })));\n adds.push(...schemaChanges.adds.map(x => ({ entity: x, schemaId })));\n removes.push(...schemaChanges.removes.map(x => ({ entity: x, schemaId })));\n }\n\n if (updates.length === 0 && removes.length === 0 && adds.length === 0) {\n done(Result.success())\n return;\n }\n\n this._doWork((db, d) => {\n try {\n\n const tombstones = removes.map(x => ({ _id: x.entity._id, _rev: x.entity._rev, _deleted: true } as UnknownRecord));\n const updatedDocuments = updates.map(x => x.change.entity) as UnknownRecord[];\n\n this._withRevisions(db, [...tombstones, ...updatedDocuments], (revisionError) => {\n\n if (revisionError != null) {\n d(Result.error(revisionError));\n return;\n }\n\n db.bulkDocs([...tombstones, ...updatedDocuments], null, (error, response) => {\n\n if (error != null) {\n d(Result.error(error));\n return;\n }\n\n for (let i = 0, length = response.length; i < length; i++) {\n const doc = response[i];\n\n if (\"error\" in doc) {\n\n const reason = doc.reason ?? doc.error;\n\n d(Result.error(reason));\n return;\n }\n\n const removesIndex = removes.findIndex(x => x.entity._id === doc.id);\n\n if (removesIndex !== -1) {\n const { schemaId } = removes[removesIndex]\n const schemaResult = result.resolve(schemaId);\n\n assertIsNotNull(schemaResult);\n\n schemaResult.removes.push(doc as any);\n continue;\n }\n\n const updatesIndex = updates.findIndex(x => x.change.entity._id === doc.id);\n\n if (updatesIndex !== -1) {\n // Optimistically assume that the update worked as expected\n const update = updates[updatesIndex];\n\n const changesResult = result.resolve(update.schemaId);\n\n // Set the new rev\n (update.change.entity as UnknownRecord)._rev = doc.rev;\n\n changesResult.updates.push(update.change.entity);\n continue;\n }\n\n d(Result.error(new Error(\"Cannot classify resulting doc\")));\n return;\n }\n\n const pipeline = new WorkPipeline();\n\n for (let i = 0, length = nonIdentitySchemaIds.length; i < length; i++) {\n const schemaId = nonIdentitySchemaIds[i];\n const schemaAdds = adds.filter(x => x.schemaId === schemaId).map(x => x.entity);\n\n // Skip schemas with no adds\n if (schemaAdds.length === 0) {\n continue;\n }\n\n pipeline.pipe((d) => {\n const schemaResult = result.resolve(schemaId);\n\n assertIsNotNull(schemaResult);\n assertIsNotNull(schemaAdds);\n\n db.bulkDocs([...schemaAdds], null, (error, response) => {\n\n if (error) {\n d(Result.error(error));\n return;\n }\n\n // Starts EMPTY and is filled from the ok entries below.\n // Seeding it from every response entry and then pushing each\n // ok id again put every id in twice, so `_bulkGetAdditions`\n // asked for each document twice and the echo carried\n // duplicates into the change tracker.\n const ids: string[] = [];\n\n for (let i = 0, length = response.length; i < length; i++) {\n\n const doc = response[i];\n\n if (\"error\" in doc) {\n\n const reason = doc.reason ?? doc.error;\n\n d(Result.error(reason));\n return;\n }\n\n if (\"id\" in doc && \"ok\" in doc) {\n ids.push(doc.id);\n } else {\n d(Result.error(doc.error));\n return;\n }\n }\n\n this._bulkGetAdditions(ids, (bulkGetResponse) => {\n\n if (bulkGetResponse.ok !== Result.SUCCESS) {\n d(Result.error(bulkGetResponse));\n return;\n }\n\n for (let i = 0, length = bulkGetResponse.data.results.length; i < length; i++) {\n const docs = bulkGetResponse.data.results[i].docs;\n\n if (docs.length === 1) {\n const doc = docs[0];\n\n if (\"ok\" in doc) {\n schemaResult.adds.push(doc.ok as any);\n }\n }\n }\n\n d(Result.success());\n });\n });\n\n });\n }\n\n pipeline.filter((r) => {\n if (r.ok !== Result.SUCCESS) {\n d(r);\n return;\n }\n\n d(Result.success());\n });\n });\n });\n } catch (e) {\n d(Result.error(e));\n }\n }, done);\n }\n\n private _prepareProperties(...properties: PropertyInfo<any>[]) {\n\n properties.sort((a, b) => a.name.localeCompare(b.name, undefined, { sensitivity: 'base' }));\n const paths = properties.map(w => w.getAssignmentPath({ parent: \"doc\" }));\n const viewName = `by_${paths.join(\"_\")}`;\n\n return {\n properties,\n paths,\n viewName\n }\n }\n\n private resolveIndexes<TEntity extends {}, TShape extends unknown = TEntity>(event: DbPluginQueryEvent<TEntity, TShape>, done: CallbackResult<PouchDbDesignDoc | null>) {\n\n const indexes = event.operation.schema.getIndexes();\n\n if (indexes.length === 0) {\n done(Result.success(null));\n return;\n }\n\n if (this.indexCache != null) {\n done(Result.success(this.indexCache));\n return; // Already built\n }\n\n const ddoc: PouchDbDesignDoc = {\n _id: `_design/${INDEX_NAME}`,\n views: {}\n }\n\n for (let i = 0, length = indexes.length; i < length; i++) {\n const index = indexes[i];\n const { viewName, paths } = this._prepareProperties(...index.properties);\n\n if (index.properties.length === 1) {\n const property = index.properties[0];\n const path = property.getAssignmentPath({ parent: \"doc\" });\n ddoc.views[viewName] = {\n map: `function(doc) {\n if (${path}) {\n emit(${path});\n }\n }`\n }\n continue;\n }\n\n ddoc.views[viewName] = {\n map: `function(doc) {\n if (${paths.join(\" && \")}) {\n emit([${paths.join(\",\")}]);\n }\n }`\n }\n }\n\n this._doWork((db, d) => {\n // change this out in the future? or make a new index, this does not return the rev which makes us need to call get again below\n db.allDocs({\n startkey: '_design/',\n endkey: '_design0',\n include_docs: true\n }).then(response => {\n\n // if we have no indexes, let's create it\n if (response.rows.length === 0) {\n db.put(ddoc as UnknownRecord, {}, (e) => {\n if (e) {\n d(Result.error(e));\n return;\n }\n\n this.indexCache = ddoc;\n\n d(Result.success(ddoc));\n });\n return;\n }\n\n const matchingIndex = response.rows.find(x => x.id === `_design/${INDEX_NAME}`);\n\n // make sure we have the correct index created\n if (matchingIndex == null) {\n db.put(ddoc as UnknownRecord, {}, (e) => {\n if (e) {\n d(Result.error(e));\n return;\n }\n\n this.indexCache = ddoc;\n\n d(Result.success(ddoc));\n });\n return;\n }\n\n assertIsNotNull(ddoc.views);\n assertIsNotNull(matchingIndex.doc);\n\n const views = Object.keys(ddoc.views)\n\n // make sure all of the views are in the document, if not update it\n if (views.some(x => (matchingIndex.doc as any).views[x] == null)) {\n\n // need to get the rev\n db.get(ddoc._id, {}, (e, result) => {\n\n if (e != null) {\n d(Result.error(e));\n return;\n }\n\n (result as any).views = ddoc.views\n\n db.put(result as any, {}, (e) => {\n\n if (e) {\n d(Result.error(e));\n return;\n }\n\n this.indexCache = ddoc;\n\n d(Result.success(ddoc));\n });\n })\n return;\n }\n\n d(Result.success(ddoc));\n }).catch(e => {\n d(Result.error(e));\n });\n }, done)\n }\n\n // id should be a string here because this is only run on identity inserts\n private _bulkGetAdditions<TEntity extends {}>(ids: string[], done: CallbackResult<PouchDB.Core.BulkGetResponse<TEntity>>) {\n\n if (ids.length === 0) {\n done(Result.success({ results: [] }));\n return;\n }\n\n this._doWork((db, d) => {\n db.bulkGet<TEntity>({\n docs: ids.map(w => ({ id: w as string }))\n }, (error, response) => {\n\n if (error) {\n d(Result.error(error));\n return\n }\n\n d(Result.success(response));\n });\n }, done);\n }\n\n private _validateSchemas(event: DbPluginBulkPersistEvent) {\n for (const [, schema] of event.schemas) {\n if (schema.idProperties.length > 1) {\n throw new Error(\"PouchDB cannot have more than one key per document. Only '_id' is allowed to be the key\")\n }\n }\n }\n\n private _bulkPersist(\n event: DbPluginBulkPersistEvent,\n done: PluginEventCallbackPartialResult<BulkPersistResult>) {\n\n this._validateSchemas(event);\n\n const result = event.operation.toResult();\n const identitySchemaIds: SchemaId[] = [];\n const defaultSchemaIds: SchemaId[] = [];\n\n for (const [schemaId, schema] of event.schemas) {\n\n if (schema.hasIdentityKeys) {\n identitySchemaIds.push(schemaId);\n continue;\n }\n\n defaultSchemaIds.push(schemaId);\n }\n\n this._identityBulkOperations(identitySchemaIds, event.operation, result, (identityResult) => {\n\n if (identityResult.ok !== Result.SUCCESS) {\n done(PluginEventResult.error(event.id, identityResult.error))\n return;\n }\n\n this._defaultBulkOperations(defaultSchemaIds, event.operation, result, (defaultResult) => {\n\n if (defaultResult.ok !== Result.SUCCESS) {\n done(PluginEventResult.error(event.id, defaultResult.error))\n return;\n }\n\n done(PluginEventResult.success(event.id, result))\n });\n\n });\n }\n\n private _doWork<TResult, TEntity>(work: (db: PouchDB.Database<TEntity>, done: CallbackResult<TResult>) => void, done: CallbackResult<TResult>, shouldClose: boolean = false) {\n const db = this.database<TEntity>();\n\n work(db, (result) => {\n\n // The `return` is the fix. Without it, `shouldClose` ran BOTH branches: `done`\n // fired synchronously here and again from the close callback. A doubled callback\n // resolves a settled promise silently, but it also drives every pipeline stage\n // downstream twice — see known-defects #3's \"calls done exactly once\".\n if (shouldClose) {\n // The handle is shared, so closing it has to clear the cache too — the next\n // operation must open a fresh one rather than reuse a closed database.\n this.localDb = null;\n db.close(() => done(result));\n return;\n }\n\n done(result);\n })\n }\n\n destroy(_event: DbPluginEvent, done: (error?: any) => void): void {\n // Replication first. A live sync holds both the local and the remote database open\n // and keeps polling; destroying the local one underneath it leaves a replication\n // running against a database that no longer exists, which surfaces later as errors\n // from a plugin the caller believes it has finished with.\n if (this.syncHandle != null) {\n try {\n this.syncHandle.cancel();\n } catch {\n // An already-finished sync throws on cancel. Destroy's goal is that no\n // replication is running, and that is satisfied either way.\n }\n\n this.syncHandle = null;\n }\n\n // A destroyed database must not keep serving its cached design document to a plugin\n // that outlives it.\n this.indexCache = null;\n\n // `shouldClose: true`, so the handle this work opened is closed rather than left to\n // the garbage collector. It was false, which is what left destroy leaking the very\n // resource it was called to release.\n this._doWork((w, d) => {\n w.destroy(null, (e) => {\n if (e) {\n d(Result.error(e))\n return;\n }\n\n d(Result.success());\n });\n }, done, true);\n }\n\n\n bulkPersist(\n event: DbPluginBulkPersistEvent,\n done: PluginEventCallbackPartialResult<BulkPersistResult>) {\n\n const unitOfWork: SyncronousUnitOfWork = (d) => this._bulkPersist(event, (r) => {\n d();\n done(r)\n })\n\n this.queue.enqueue(unitOfWork.bind(this));\n }\n\n query<TRoot extends {}, TShape extends any = TRoot>(event: DbPluginQueryEvent<TRoot, TShape>, done: PluginEventCallbackResult<ITranslatedValue<TShape>>): void {\n\n const unitOfWork: SyncronousUnitOfWork = (d) => {\n const settle = (r: Parameters<typeof done>[0]) => {\n d();\n done(r);\n };\n\n // A join is two reads through `_query` — the UN-QUEUED path — on purpose: this unit of\n // work already holds the queue, so routing them through `query` would make them wait on\n // itself and the plugin would never answer. They are still serialized against every\n // other query, because this slot is held for both.\n if (event.operation.options.has(\"join\")) {\n joinInPlugin(event, (e, cb) => this._query(e, cb), settle as never);\n return;\n }\n\n this._query<TRoot, TShape>(event, settle);\n };\n\n this.queue.enqueue(unitOfWork.bind(this));\n }\n\n protected onGetIndex<TEntity extends {}, TShape extends unknown = TEntity>(_: IQuery<TEntity, TShape>, __: PouchDB.Find.FindRequest<unknown>, done: (result: null | string | [string, string]) => void) {\n done(null);\n }\n\n extractEqualityValueForProperty(expression: Expression, prop: PropertyInfo<any>): any | undefined {\n // Recursively search for a comparator expression that matches the property\n if (expression.type === \"comparator\" && (expression as ComparatorExpression).comparator === \"equals\") {\n // Check left side is property, right side is value\n if (expression.left && expression.left.type === \"property\" && (expression.left as any).property.name === prop.name && expression.right && expression.right.type === \"value\") {\n return (expression.right as any).value;\n }\n // Or right side is property, left side is value\n if (expression.right && expression.right.type === \"property\" && (expression.right as any).property.name === prop.name && expression.left && expression.left.type === \"value\") {\n return (expression.left as any).value;\n }\n }\n // Recursively check left and right\n if (expression.left) {\n const left = this.extractEqualityValueForProperty(expression.left, prop);\n if (left !== undefined) return left;\n }\n if (expression.right) {\n const right = this.extractEqualityValueForProperty(expression.right, prop);\n if (right !== undefined) return right;\n }\n return undefined;\n }\n\n private _findMatchingIndex(ddoc: PouchDbDesignDoc, expression: Expression): MatchingIndex {\n const queryProperties = getProperties(expression);\n\n const { viewName } = this._prepareProperties(...queryProperties);\n\n if (ddoc.views == null) {\n return null;\n }\n\n const index = ddoc.views[viewName];\n\n if (index == null) {\n return null;\n }\n\n const properties: MatchingIndex[\"properties\"] = [];\n\n for (const property of queryProperties) {\n const value = this.extractEqualityValueForProperty(expression, property);\n\n if (value === undefined) {\n return null\n }\n\n properties.push({\n property,\n value\n });\n }\n\n return {\n viewName,\n properties\n };\n }\n\n private _queryIndex<TEntity extends {}, TShape extends unknown = TEntity>(event: DbPluginQueryEvent<TEntity, TShape>, matchingIndex: MatchingIndex, done: CallbackResult<ITranslatedValue<TShape>>) {\n const translator = new PouchDbTranslator<TEntity, TShape>(event.operation);\n this._doWork((w, d) => {\n\n const options: PouchDB.Query.Options<any, any> = {\n include_docs: true,\n };\n\n const values = matchingIndex.properties.map(x => x.value);\n\n if (values.some(x => x == null) == false) {\n\n if (values.length === 1) {\n options.key = values[0];\n } else {\n options.keys = values;\n }\n }\n\n w.query(`${INDEX_NAME}/${matchingIndex.viewName}`, options, (error, response) => {\n\n if (error != null) {\n d(Result.error(error));\n return;\n }\n\n try {\n event.executedQueries.push({ text: `${INDEX_NAME}/${matchingIndex.viewName}: indexed view query` });\n\n const translated = translator.translate(response.rows.map(w => w.doc));\n d(Result.success(translated));\n } catch (e) {\n d(Result.error(e));\n }\n });\n }, done);\n }\n\n private _queryNoIndex<TEntity extends {}, TShape extends unknown = TEntity>(event: DbPluginQueryEvent<TEntity, TShape>, done: CallbackResult<ITranslatedValue<TShape>>) {\n const filters = event.operation.options.get(\"filter\")\n if (filters.length === 0) {\n this._queryWithNoFilters(event, done);\n return;\n }\n\n this._queryWithFilters(event, done);\n }\n\n private _queryWithNoFilters<TEntity extends {}, TShape extends unknown = TEntity>(event: DbPluginQueryEvent<TEntity, TShape>, done: CallbackResult<ITranslatedValue<TShape>>) {\n const translator = new PouchDbTranslator<TEntity, TShape>(event.operation);\n this._doWork((w, d) => {\n w.allDocs({\n include_docs: true\n }).then(response => {\n\n try {\n event.executedQueries.push({ text: \"allDocs({ include_docs: true }): full database scan, no index\" });\n\n const data = response.rows.map(w => w.doc);\n const translated = translator.translate(data);\n d(Result.success(translated));\n } catch (e) {\n d(Result.error(e));\n }\n }).catch(error => {\n d(Result.error(error));\n });\n }, done);\n }\n\n private _queryWithFilters<TEntity extends {}, TShape extends unknown = TEntity>(event: DbPluginQueryEvent<TEntity, TShape>, done: CallbackResult<ITranslatedValue<TShape>>) {\n const translator = new PouchDbTranslator<TEntity, TShape>(event.operation);\n this._doWork((w, d) => {\n\n if (this._name.startsWith(\"http\")) {\n // Cannot query remote databases using translator.matches, fallback to alldocs\n // Does not throw, will fail on the remote server\n w.allDocs({\n include_docs: true\n }).then(response => {\n const data = response.rows.map(w => w.doc);\n try {\n event.executedQueries.push({ text: \"allDocs({ include_docs: true }): full database scan, no index\" });\n\n const translated = translator.translate(data);\n d(Result.success(translated));\n } catch (e) {\n d(Result.error(e));\n }\n }).catch(error => {\n d(Result.error(error));\n });\n return;\n }\n\n w.query<{}, any>((doc, emit) => {\n if (typeof doc === \"object\" && \"_id\" in doc && translator.matches(doc)) {\n emit(doc._id, doc);\n }\n }, (error, response) => {\n\n if (error != null) {\n d(Result.error(error));\n return;\n }\n\n const data = response.rows.map(w => w.value);\n\n try {\n event.executedQueries.push({ text: \"view query\" });\n\n const translated = translator.translate(data);\n d(Result.success(translated));\n } catch (e) {\n d(Result.error(e));\n }\n });\n\n }, done);\n }\n\n private _query<TEntity extends {}, TShape extends unknown = TEntity>(event: DbPluginQueryEvent<TEntity, TShape>, done: PluginEventCallbackResult<ITranslatedValue<TShape>>): void {\n this.resolveIndexes(event, (r) => {\n if (r.ok !== Result.SUCCESS) {\n done(PluginEventResult.error(event.id, r.error))\n return;\n }\n\n const ddoc = r.data;\n\n if (ddoc == null) {\n this._queryNoIndex(event, done);\n return;\n }\n\n const mapMatchingIndex = this.findMatchingIndexForMap(ddoc, event);\n\n if (mapMatchingIndex != null) {\n this._queryIndex(event, mapMatchingIndex, done);\n return;\n }\n\n const expression = this._getExpressionFromQuery(event);\n\n if (Expression.isEmpty(expression)) {\n this._queryNoIndex(event, done);\n return;\n }\n\n const matchingIndex = this._findMatchingIndex(ddoc, expression);\n\n if (matchingIndex == null) {\n this._queryNoIndex(event, done);\n return;\n }\n\n this._queryIndex(event, matchingIndex, done);\n });\n }\n\n private _getExpressionFromQuery<TEntity extends {}, TShape>(event: DbPluginQueryEvent<TEntity, TShape>) {\n const filters = event.operation.options.get(\"filter\");\n\n const databaseFilters = filters.filter(x => x.option.target === \"database\");\n\n if (databaseFilters.length === 0) {\n return Expression.EMPTY;\n }\n\n const expressions = databaseFilters.map(x => x.option.value.expression);\n\n return combineExpressions(...expressions);\n }\n\n private findMatchingIndexForMap<TEntity extends {}, TShape>(ddoc: PouchDbDesignDoc, event: DbPluginQueryEvent<TEntity, TShape>): MatchingIndex | null {\n const map = event.operation.options.getLast(\"map\");\n const filters = event.operation.options.get(\"filter\");\n\n // we only want to look at the index if there are no filters\n if (filters.length > 0) {\n return null;\n }\n\n if (map == null || map.target !== \"database\") {\n return null;\n }\n\n if (map.value.fields.length !== 1 || map.value.fields[0].property == null) {\n return null;\n }\n\n const property = map.value.fields[0].property;\n\n const { viewName } = this._prepareProperties(property);\n\n if (ddoc.views == null) {\n return null;\n }\n\n const index = ddoc.views[viewName];\n\n if (index == null) {\n return null;\n }\n\n return {\n viewName,\n properties: [{ property, value: null }]\n }\n }\n}","export { PouchDbPlugin } from './PouchDbPlugin';"],"names":["assertIsArray","JsonTranslator","PouchDbTranslator","query","item","filterChain","filters","databaseFilters","x","index","currentFilter","nextFilter","filter","selector","params","data","result","i","length","entity","e","Error","JSON","PouchDB","SyncronousQueue","WorkPipeline","joinInPlugin","PluginEventResult","Result","assertIsNotNull","combineExpressions","Expression","getProperties","INDEX_NAME","PouchDbPlugin","_sync","_queryType","rest","name","options","schemas","localDb","remoteDb","sync","db","documents","done","missing","document","String","response","revisions","Map","row","revision","error","identitySchemaIds","changes","updates","adds","removes","schemaId","schemaChanges","d","updatedDocuments","w","errors","tombstones","revisionError","doc","updatesIndex","update","changesResult","removesIndex","remove","pipeline","schemaAdds","schemaResult","ids","reason","bulkGetResponse","docs","r","nonIdentitySchemaIds","properties","a","b","undefined","paths","viewName","event","indexes","ddoc","property","path","matchingIndex","views","Object","schema","defaultSchemaIds","identityResult","defaultResult","work","shouldClose","_event","unitOfWork","settle","cb","_","__","expression","prop","left","right","queryProperties","value","translator","values","translated","emit","mapMatchingIndex","expressions","map"],"mappings":";;;;;;;;;;;AAAA;AACA;AACA;AACA,kDAAkD,wCAAwC;AAC1F;AACA;AACA,E;;;;ACNA,wF;;;;;;;;;;;;;;;;ACAyD;AAEwC;AAG1F,MAAME,0BAAgFD,cAAcA;IAE/F,OAAgC;IAChC,gBAAqD,KAAK;IAElE,YAAYE,KAA8B,CAAE;QACxC,KAAK,CAACA;QACN,IAAI,CAAC,MAAM,GAAGA,MAAM,MAAM;IA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pCgD"}
|
|
1
|
+
{"version":3,"file":"index.js","sources":["webpack://@routier/pouchdb-plugin/webpack/runtime/define_property_getters","webpack://@routier/pouchdb-plugin/webpack/runtime/has_own_property","webpack://@routier/pouchdb-plugin/./src/PouchDbTranslator.ts","webpack://@routier/pouchdb-plugin/./src/PouchDbPlugin.ts","webpack://@routier/pouchdb-plugin/./src/index.ts"],"sourcesContent":["__webpack_require__.d = (exports, definition) => {\n\tfor(var key in definition) {\n if(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {\n Object.defineProperty(exports, key, { enumerable: true, get: definition[key] });\n }\n }\n};","__webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))","import { assertIsArray } from \"@routier/core/assertions\";\nimport { Filter, ParamsFilter } from \"@routier/core/expressions\";\nimport { IQuery, JsonTranslator, QueryCollectionItem, QueryOption } from \"@routier/core/plugins\";\nimport { getStorageDateReviver, StorageDateReviver } from \"@routier/core/schema\";\n\nexport class PouchDbTranslator<TEntity extends {}, TShape extends unknown = TEntity> extends JsonTranslator<TEntity, TShape> {\n\n /**\n * PouchDB stores JSON, so a date comes back as the ISO string the datastore serialized it to.\n * The caller's lambdas compare and call Dates, so every document is revived before one runs.\n * Only the dates: keys stay under their `from` names. `null` for a schema with no dates.\n */\n private readonly reviveDates: StorageDateReviver | null;\n private cachedMatches: ((item: unknown) => boolean) | null = null;\n\n constructor(query: IQuery<TEntity, TShape>) {\n super(query);\n this.reviveDates = getStorageDateReviver(query.schema);\n }\n\n matches(item: unknown) {\n // Get or build cached filter chain\n const filterChain = this.resolveFilterChain();\n\n this.reviveDates?.(item as Record<string, unknown>);\n\n // Execute the chain (no loops, just recursive function calls)\n return filterChain(item);\n }\n\n private resolveFilterChain(): (item: unknown) => boolean {\n // Return cached chain if available\n if (this.cachedMatches !== null) {\n return this.cachedMatches;\n }\n\n // Build and cache the filter chain\n const filters = this.query.options.get(\"filter\");\n // Not a filter the plugin reported: the datastore runs that one, after deserialization\n const databaseFilters = filters.filter(x => x.option.target === \"database\" && x.option.reason === \"executed\");\n\n this.cachedMatches = this.buildFilterChain(databaseFilters, 0);\n\n return this.cachedMatches;\n }\n\n private buildFilterChain(filters: QueryCollectionItem<TShape, \"filter\">[], index: number): (item: unknown) => boolean {\n // Base case: no more filters, return true\n if (index >= filters.length) {\n return () => true;\n }\n\n // Get current filter function\n const currentFilter = this.evaluateFilter(filters[index].option);\n\n // Build the rest of the chain\n const nextFilter = this.buildFilterChain(filters, index + 1);\n\n // Return a function that checks current filter and calls next\n return (item: unknown) => {\n if (!currentFilter(item)) {\n return false; // Early termination\n }\n return nextFilter(item); // Recursive call to next filter\n };\n }\n\n private evaluateFilter(filter: QueryOption<TShape, \"filter\">): (item: unknown) => boolean {\n if (filter.value.params == null) {\n const selector = filter.value.filter as Filter<unknown>;\n return (item: unknown) => selector(item) !== false;\n }\n\n const selector = filter.value.filter as ParamsFilter<unknown, {}>;\n const params = filter.value.params;\n return (item: unknown) => selector([item, params]) !== false;\n }\n\n override translate(data: unknown) {\n assertIsArray(data);\n\n const documents: Record<string, unknown>[] = [];\n\n for (let i = 0, length = data.length; i < length; i++) {\n const document = data[i] as Record<string, unknown>;\n\n // design docs can be included in the result, ignore them\n if (typeof document._id === \"string\" && document._id.startsWith(\"_design\")) {\n continue;\n }\n\n // Again, whether or not the view predicate revived it: a view may hand back a copy of\n // what it emitted, and a document read without a view was never revived\n this.reviveDates?.(document);\n documents.push(document);\n }\n\n // Documents stay in storage shape. The datastore deserializes the rows this returns, by\n // their `from` names, and a join does the same per side.\n return super.translate(documents);\n }\n\n}","import PouchDB from 'pouchdb';\nimport { PouchDbTranslator } from './PouchDbTranslator';\nimport { SyncronousQueue, SyncronousUnitOfWork, WorkPipeline } from '@routier/core/pipeline';\nimport { InferCreateType, InferType, PropertyInfo, SchemaId } from '@routier/core/schema';\nimport { DbPluginBulkPersistEvent, DbPluginEvent, DbPluginQueryEvent, EntityUpdateInfo, IDbPlugin, IQuery, ITranslatedValue, joinInPlugin, reportRenamedProperties } from '@routier/core/plugins';\nimport { CallbackResult, PluginEventCallbackPartialResult, PluginEventCallbackResult, PluginEventResult, Result } from '@routier/core/results';\nimport { assertIsNotNull } from '@routier/core/assertions';\nimport { combineExpressions, ComparatorExpression, Expression, getProperties } from '@routier/core/expressions';\nimport { BulkPersistChanges, BulkPersistResult, ReadonlySchemaCollection, UnknownRecord } from '@routier/core';\n\nconst INDEX_NAME = \"routier_pdb_indexes\"\n\ntype PouchDBPluginOptions = PouchDB.Configuration.DatabaseConfiguration & {\n queryType?: \"default\" | \"memory-optimized\" | \"experimental\";\n sync?: PouchDB.Replication.SyncOptions & {\n remoteDb: string;\n onChange?: (schemas: ReadonlySchemaCollection, event: PouchDB.Replication.SyncResult<{}>) => void;\n onError?: (schemas: ReadonlySchemaCollection, error?: any) => void;\n onComplete?: (schemas: ReadonlySchemaCollection, event: PouchDB.Replication.SyncResultComplete<{}>) => void;\n onPaused?: (schemas: ReadonlySchemaCollection, event?: any) => void;\n onActive?: (schemas: ReadonlySchemaCollection) => void;\n onDenied?: (schemas: ReadonlySchemaCollection, event?: any) => void;\n auth?: {\n username: string;\n password: string;\n };\n headers?: { [key: string]: string };\n };\n}\n\nexport type PouchDbDesignDoc = {\n _id: string;\n language?: string;\n views?: {\n [viewName: string]: {\n map: string | Function;\n reduce?: string | Function;\n };\n };\n filters?: {\n [filterName: string]: string | Function;\n };\n validate_doc_update?: string | Function;\n options?: Record<string, any>;\n [key: string]: any; // allow other CouchDB features\n}\n\ntype MatchingIndex = {\n viewName: string,\n properties: {\n property: PropertyInfo<any>,\n value: unknown\n }[]\n}\n\nexport class PouchDbPlugin implements IDbPlugin {\n\n private readonly _name: string;\n private readonly _options?: PouchDBPluginOptions;\n\n /**\n * Per INSTANCE, all three of these. They used to be module-level, which made every\n * PouchDbPlugin in the process share one database's state regardless of its name:\n *\n * - the **queue** serialized work across unrelated databases, so a slow save against one\n * database blocked a read against another;\n * - the **index cache** was keyed by nothing at all, so the first database's design\n * document was reported as every database's;\n * - the **sync handle** lived under the literal key `\"sync\"`, so only the FIRST plugin in\n * a process could establish replication — every later one got back the first one's\n * handle, pointed at a different remote.\n *\n * A plugin instance is the natural scope: it owns exactly one database name.\n */\n private readonly queue = new SyncronousQueue();\n private indexCache: PouchDbDesignDoc | null = null;\n private syncHandle: PouchDB.Replication.Sync<{}> | null = null;\n\n /**\n * ONE local database handle for this plugin, shared by every operation and by `sync()`.\n *\n * This used to be a fresh `new PouchDB(name)` per operation, with `sync()` constructing\n * yet another one of its own. Two PouchDB objects over the same name only behave as one\n * database when the ADAPTER broadcasts changes between them: IndexedDB does, so this\n * works in a browser, and the in-memory adapter does not, so under it a live replication\n * never observes the plugin's own writes and the plugin never observes what replication\n * pulls in. Replication and data access were effectively wired to two different databases\n * on any adapter without that broadcast.\n *\n * One handle removes the question, and removes the per-operation construction churn with\n * it. It is closed and cleared by `destroy()`.\n */\n private localDb: PouchDB.Database<any> | null = null;\n\n private database<TEntity>(): PouchDB.Database<TEntity> {\n if (this.localDb == null) {\n const { sync: _sync, queryType: _queryType, ...rest } = this._options ?? {};\n this.localDb = new PouchDB(this._name, rest);\n }\n\n return this.localDb as PouchDB.Database<TEntity>;\n }\n\n constructor(name: string, options?: PouchDBPluginOptions) {\n this._name = name;\n this._options = options;\n }\n\n /**\n * See `IDbPlugin.databaseName`. The local database name — the same value two contexts\n * opening one PouchDB database supply, so they share subscription channels. Remote sync\n * targets are deliberately not part of it: two local databases replicating to one remote\n * are still two databases.\n */\n get databaseName(): string {\n return this._name;\n }\n\n sync(schemas: ReadonlySchemaCollection) {\n\n assertIsNotNull(this._options?.sync, \"Cannot start sync process without sync options. Provide sync options in PouchDbPlugin constructor\");\n\n if (this.syncHandle == null) {\n // No placeholder write before the work. The previous shape assigned `{}` first\n // and only replaced it after `sync()` returned, so if constructing either\n // database threw, the cache kept the placeholder forever and every later call\n // returned an empty object cast as a Sync — no replication, no error, no way back\n // without restarting the process.\n // The plugin's own handle, not a second one over the same name: replication has\n // to observe the writes this plugin makes, and on an adapter that does not\n // broadcast changes between instances (the in-memory one, for example) a\n // separate object is a separate database in every way that matters here.\n const localDb = this.database();\n const remoteDb = new PouchDB(this._options.sync.remoteDb);\n\n // Set up sync\n const sync = localDb.sync(remoteDb, {\n ...this._options.sync\n });\n\n if (this._options.sync.onChange) {\n sync.on('change', (e) => this._options.sync.onChange(schemas, e));\n }\n\n if (this._options.sync.onActive) {\n sync.on('active', () => this._options.sync.onActive(schemas));\n }\n\n if (this._options.sync.onComplete) {\n sync.on('complete', (e) => this._options.sync.onComplete(schemas, e));\n }\n\n if (this._options.sync.onDenied) {\n sync.on('denied', (e) => this._options.sync.onDenied(schemas, e));\n }\n\n if (this._options.sync.onError) {\n sync.on('error', (e) => this._options.sync.onError(schemas, e));\n }\n\n if (this._options.sync.onPaused) {\n sync.on('paused', (e) => this._options.sync.onPaused(schemas, e));\n }\n\n // Retained so destroy() can cancel it. An uncancelled sync keeps polling a\n // remote that the caller believes it has finished with, and holds both databases\n // open with it.\n this.syncHandle = sync;\n }\n\n return this.syncHandle;\n }\n\n /**\n * Fills in the `_rev` of any document about to be updated or removed that arrives without\n * one, in a single lookup.\n *\n * PouchDB is the only backend in this repository that needs a revision to change a row, and\n * it used to make that the CALLER's problem: a schema had to declare `_rev` and every\n * entity had to carry the current value. That is this plugin's write protocol leaking into\n * every schema written for it, and it made whole features unusable here — a generated\n * search-index row is built from the document being saved, so it has an id and never a\n * revision, and every edit to an indexed document failed with a conflict whose only\n * detail was `true`.\n *\n * A revision is a fact this database owns, so this is the layer that should look it up.\n * One `allDocs` for every id that needs one, only when at least one does, and never on the\n * path where every entity already carries its own. Nothing above has to know.\n *\n * A missing row resolves to no revision and is left alone: an update to a document that is\n * not there must still fail, and it fails the way it always did.\n */\n private _withRevisions(\n db: PouchDB.Database,\n documents: UnknownRecord[],\n done: (error: unknown | null) => void\n ) {\n const missing = documents\n .filter(document => document._rev == null && document._id != null)\n .map(document => String(document._id));\n\n if (missing.length === 0) {\n done(null);\n return;\n }\n\n db.allDocs({ keys: missing }).then(response => {\n const revisions = new Map<string, string>();\n\n for (const row of response?.rows ?? []) {\n const revision = (row as { value?: { rev?: string, deleted?: boolean } }).value;\n\n if (revision?.rev != null && revision.deleted !== true) {\n revisions.set(String(row.key), revision.rev);\n }\n }\n\n for (const document of documents) {\n\n if (document._rev == null) {\n const revision = revisions.get(String(document._id));\n\n if (revision != null) {\n document._rev = revision;\n }\n }\n }\n\n done(null);\n }).catch(error => done(error));\n }\n\n private _identityBulkOperations(identitySchemaIds: SchemaId[], changes: BulkPersistChanges, result: BulkPersistResult, done: CallbackResult<never>): void {\n\n if (changes.aggregate.size === 0) {\n done(Result.success())\n return;\n }\n\n // Link each entity to a schema id below so we can easily look up the schema id for an entity\n const updates: { change: EntityUpdateInfo<UnknownRecord>, schemaId: SchemaId }[] = [];\n const adds: { entity: InferCreateType<UnknownRecord>, schemaId: SchemaId }[] = [];\n const removes: { entity: InferType<UnknownRecord>, schemaId: SchemaId }[] = [];\n\n for (const [schemaId, schemaChanges] of changes) {\n\n if (identitySchemaIds.includes(schemaId) === false || schemaChanges.hasItems === false) {\n continue;\n }\n\n updates.push(...schemaChanges.updates.map(x => ({ change: x, schemaId })));\n adds.push(...schemaChanges.adds.map(x => ({ entity: x, schemaId })));\n removes.push(...schemaChanges.removes.map(x => ({ entity: x, schemaId })));\n }\n\n // Do adds separate. Updates/Removes already have an id that we can reference\n // Default can do the same as updates/removes below since it has an id\n // Check again now to see if we have any identity schema changes\n if (updates.length === 0 && removes.length === 0 && adds.length === 0) {\n done(Result.success())\n return;\n }\n\n this._doWork((db, d) => {\n try {\n\n const updatedDocuments = [...updates].map(w => w.change.entity);\n const errors: any[] = [];\n\n // Tombstones are built here rather than inline so a missing revision can be\n // resolved into them before the write.\n const tombstones = removes.map(w => ({ _id: w.entity._id, _rev: w.entity._rev, _deleted: true } as UnknownRecord));\n\n this._withRevisions(db, [...tombstones, ...updatedDocuments] as UnknownRecord[], (revisionError) => {\n\n if (revisionError != null) {\n d(Result.error(revisionError));\n return;\n }\n\n db.bulkDocs([...tombstones, ...updatedDocuments], null, (error, response) => {\n\n if (error) {\n d(Result.error(error));\n return;\n }\n\n for (let i = 0, length = response.length; i < length; i++) {\n const doc = response[i];\n\n if (\"error\" in doc && doc.error === true) {\n errors.push(doc); // send back the entire error\n continue;\n }\n\n if (\"id\" in doc && \"ok\" in doc) {\n const updatesIndex = updates.findIndex(x => x.change.entity._id === doc.id);\n\n if (updatesIndex !== -1) {\n // Optimistically assume that the update worked as expected\n const update = updates[updatesIndex];\n\n const changesResult = result.resolve(update.schemaId);\n\n // Set the new rev\n (update.change.entity as UnknownRecord)._rev = doc.rev;\n\n changesResult.updates.push(update.change.entity);\n continue;\n }\n\n const removesIndex = removes.findIndex(x => x.entity._id === doc.id);\n\n if (removesIndex !== -1) {\n\n const remove = removes[removesIndex];\n\n const changesResult = result.resolve(remove.schemaId);\n\n changesResult.removes.push(remove.entity);\n }\n }\n }\n\n if (errors.length > 0) {\n d(Result.error(errors));\n return;\n }\n\n const pipeline = new WorkPipeline();\n\n for (let i = 0, length = identitySchemaIds.length; i < length; i++) {\n const schemaId = identitySchemaIds[i];\n const schemaAdds = adds.filter(x => x.schemaId === schemaId).map(x => x.entity);\n\n // Skip schemas with no adds\n if (schemaAdds.length === 0) {\n continue;\n }\n\n pipeline.pipe((d) => {\n const schemaResult = result.resolve(schemaId);\n\n assertIsNotNull(schemaResult);\n assertIsNotNull(schemaAdds);\n\n db.bulkDocs([...schemaAdds], null, (error, response) => {\n\n if (error) {\n d(Result.error(error));\n return;\n }\n\n // Starts EMPTY and is filled from the ok entries below.\n // Seeding it from every response entry and then pushing each\n // ok id again put every id in twice, so `_bulkGetAdditions`\n // asked for each document twice and the echo carried\n // duplicates into the change tracker.\n const ids: string[] = [];\n\n for (let i = 0, length = response.length; i < length; i++) {\n\n const doc = response[i];\n\n if (\"error\" in doc) {\n\n const reason = doc.reason ?? doc.error;\n\n d(Result.error(reason));\n return;\n }\n\n if (\"id\" in doc && \"ok\" in doc) {\n ids.push(doc.id);\n } else {\n d(Result.error(doc.error));\n return;\n }\n }\n\n this._bulkGetAdditions(ids, (bulkGetResponse) => {\n\n if (bulkGetResponse.ok !== Result.SUCCESS) {\n d(Result.error(bulkGetResponse));\n return;\n }\n\n for (let i = 0, length = bulkGetResponse.data.results.length; i < length; i++) {\n const docs = bulkGetResponse.data.results[i].docs;\n\n if (docs.length === 1) {\n const doc = docs[0];\n\n if (\"ok\" in doc) {\n schemaResult.adds.push(doc.ok as any);\n }\n }\n }\n\n d(Result.success());\n });\n });\n\n });\n }\n\n pipeline.filter((r) => {\n if (r.ok !== Result.SUCCESS) {\n d(r);\n return;\n }\n\n d(Result.success());\n });\n });\n });\n } catch (e) {\n d(Result.error(e));\n }\n }, done);\n }\n\n private _defaultBulkOperations(nonIdentitySchemaIds: SchemaId[], changes: BulkPersistChanges, result: BulkPersistResult, done: CallbackResult<never>): void {\n\n if (changes.aggregate.size === 0) {\n done(Result.success())\n return;\n }\n\n // Link each entity to a schema id below so we can easily look up the schema id for an entity\n const updates: { change: EntityUpdateInfo<UnknownRecord>, schemaId: SchemaId }[] = [];\n const adds: { entity: InferCreateType<UnknownRecord>, schemaId: SchemaId }[] = [];\n const removes: { entity: InferType<UnknownRecord>, schemaId: SchemaId }[] = [];\n\n for (const [schemaId, schemaChanges] of changes) {\n\n if (nonIdentitySchemaIds.includes(schemaId) === false || schemaChanges.hasItems === false) {\n continue;\n }\n\n updates.push(...schemaChanges.updates.map(x => ({ change: x, schemaId })));\n adds.push(...schemaChanges.adds.map(x => ({ entity: x, schemaId })));\n removes.push(...schemaChanges.removes.map(x => ({ entity: x, schemaId })));\n }\n\n if (updates.length === 0 && removes.length === 0 && adds.length === 0) {\n done(Result.success())\n return;\n }\n\n this._doWork((db, d) => {\n try {\n\n const tombstones = removes.map(x => ({ _id: x.entity._id, _rev: x.entity._rev, _deleted: true } as UnknownRecord));\n const updatedDocuments = updates.map(x => x.change.entity) as UnknownRecord[];\n\n this._withRevisions(db, [...tombstones, ...updatedDocuments], (revisionError) => {\n\n if (revisionError != null) {\n d(Result.error(revisionError));\n return;\n }\n\n db.bulkDocs([...tombstones, ...updatedDocuments], null, (error, response) => {\n\n if (error != null) {\n d(Result.error(error));\n return;\n }\n\n for (let i = 0, length = response.length; i < length; i++) {\n const doc = response[i];\n\n if (\"error\" in doc) {\n\n const reason = doc.reason ?? doc.error;\n\n d(Result.error(reason));\n return;\n }\n\n const removesIndex = removes.findIndex(x => x.entity._id === doc.id);\n\n if (removesIndex !== -1) {\n const { schemaId } = removes[removesIndex]\n const schemaResult = result.resolve(schemaId);\n\n assertIsNotNull(schemaResult);\n\n schemaResult.removes.push(doc as any);\n continue;\n }\n\n const updatesIndex = updates.findIndex(x => x.change.entity._id === doc.id);\n\n if (updatesIndex !== -1) {\n // Optimistically assume that the update worked as expected\n const update = updates[updatesIndex];\n\n const changesResult = result.resolve(update.schemaId);\n\n // Set the new rev\n (update.change.entity as UnknownRecord)._rev = doc.rev;\n\n changesResult.updates.push(update.change.entity);\n continue;\n }\n\n d(Result.error(new Error(\"Cannot classify resulting doc\")));\n return;\n }\n\n const pipeline = new WorkPipeline();\n\n for (let i = 0, length = nonIdentitySchemaIds.length; i < length; i++) {\n const schemaId = nonIdentitySchemaIds[i];\n const schemaAdds = adds.filter(x => x.schemaId === schemaId).map(x => x.entity);\n\n // Skip schemas with no adds\n if (schemaAdds.length === 0) {\n continue;\n }\n\n pipeline.pipe((d) => {\n const schemaResult = result.resolve(schemaId);\n\n assertIsNotNull(schemaResult);\n assertIsNotNull(schemaAdds);\n\n db.bulkDocs([...schemaAdds], null, (error, response) => {\n\n if (error) {\n d(Result.error(error));\n return;\n }\n\n // Starts EMPTY and is filled from the ok entries below.\n // Seeding it from every response entry and then pushing each\n // ok id again put every id in twice, so `_bulkGetAdditions`\n // asked for each document twice and the echo carried\n // duplicates into the change tracker.\n const ids: string[] = [];\n\n for (let i = 0, length = response.length; i < length; i++) {\n\n const doc = response[i];\n\n if (\"error\" in doc) {\n\n const reason = doc.reason ?? doc.error;\n\n d(Result.error(reason));\n return;\n }\n\n if (\"id\" in doc && \"ok\" in doc) {\n ids.push(doc.id);\n } else {\n d(Result.error(doc.error));\n return;\n }\n }\n\n this._bulkGetAdditions(ids, (bulkGetResponse) => {\n\n if (bulkGetResponse.ok !== Result.SUCCESS) {\n d(Result.error(bulkGetResponse));\n return;\n }\n\n for (let i = 0, length = bulkGetResponse.data.results.length; i < length; i++) {\n const docs = bulkGetResponse.data.results[i].docs;\n\n if (docs.length === 1) {\n const doc = docs[0];\n\n if (\"ok\" in doc) {\n schemaResult.adds.push(doc.ok as any);\n }\n }\n }\n\n d(Result.success());\n });\n });\n\n });\n }\n\n pipeline.filter((r) => {\n if (r.ok !== Result.SUCCESS) {\n d(r);\n return;\n }\n\n d(Result.success());\n });\n });\n });\n } catch (e) {\n d(Result.error(e));\n }\n }, done);\n }\n\n private _prepareProperties(...properties: PropertyInfo<any>[]) {\n\n properties.sort((a, b) => a.name.localeCompare(b.name, undefined, { sensitivity: 'base' }));\n // A view reads documents as they are stored, where a renamed segment is under its `from`\n // name. The view name is built from the same paths, so a design document saved when views\n // read the in-memory name, and so emitted nothing for a renamed property, is missing the new\n // view and gets replaced.\n const paths = properties.map(w => w.getAssignmentPath({ parent: \"doc\", useFromPropertyName: true }));\n const viewName = `by_${paths.join(\"_\")}`;\n\n return {\n properties,\n paths,\n viewName\n }\n }\n\n private resolveIndexes<TEntity extends {}, TShape extends unknown = TEntity>(event: DbPluginQueryEvent<TEntity, TShape>, done: CallbackResult<PouchDbDesignDoc | null>) {\n\n const indexes = event.operation.schema.getIndexes();\n\n if (indexes.length === 0) {\n done(Result.success(null));\n return;\n }\n\n if (this.indexCache != null) {\n done(Result.success(this.indexCache));\n return; // Already built\n }\n\n const ddoc: PouchDbDesignDoc = {\n _id: `_design/${INDEX_NAME}`,\n views: {}\n }\n\n for (let i = 0, length = indexes.length; i < length; i++) {\n const index = indexes[i];\n const { viewName, paths } = this._prepareProperties(...index.properties);\n\n if (index.properties.length === 1) {\n const path = paths[0];\n ddoc.views[viewName] = {\n map: `function(doc) {\n if (${path}) {\n emit(${path});\n }\n }`\n }\n continue;\n }\n\n ddoc.views[viewName] = {\n map: `function(doc) {\n if (${paths.join(\" && \")}) {\n emit([${paths.join(\",\")}]);\n }\n }`\n }\n }\n\n this._doWork((db, d) => {\n // change this out in the future? or make a new index, this does not return the rev which makes us need to call get again below\n db.allDocs({\n startkey: '_design/',\n endkey: '_design0',\n include_docs: true\n }).then(response => {\n\n // if we have no indexes, let's create it\n if (response.rows.length === 0) {\n db.put(ddoc as UnknownRecord, {}, (e) => {\n if (e) {\n d(Result.error(e));\n return;\n }\n\n this.indexCache = ddoc;\n\n d(Result.success(ddoc));\n });\n return;\n }\n\n const matchingIndex = response.rows.find(x => x.id === `_design/${INDEX_NAME}`);\n\n // make sure we have the correct index created\n if (matchingIndex == null) {\n db.put(ddoc as UnknownRecord, {}, (e) => {\n if (e) {\n d(Result.error(e));\n return;\n }\n\n this.indexCache = ddoc;\n\n d(Result.success(ddoc));\n });\n return;\n }\n\n assertIsNotNull(ddoc.views);\n assertIsNotNull(matchingIndex.doc);\n\n const views = Object.keys(ddoc.views)\n\n // make sure all of the views are in the document, if not update it\n if (views.some(x => (matchingIndex.doc as any).views[x] == null)) {\n\n // need to get the rev\n db.get(ddoc._id, {}, (e, result) => {\n\n if (e != null) {\n d(Result.error(e));\n return;\n }\n\n (result as any).views = ddoc.views\n\n db.put(result as any, {}, (e) => {\n\n if (e) {\n d(Result.error(e));\n return;\n }\n\n this.indexCache = ddoc;\n\n d(Result.success(ddoc));\n });\n })\n return;\n }\n\n d(Result.success(ddoc));\n }).catch(e => {\n d(Result.error(e));\n });\n }, done)\n }\n\n // id should be a string here because this is only run on identity inserts\n private _bulkGetAdditions<TEntity extends {}>(ids: string[], done: CallbackResult<PouchDB.Core.BulkGetResponse<TEntity>>) {\n\n if (ids.length === 0) {\n done(Result.success({ results: [] }));\n return;\n }\n\n this._doWork((db, d) => {\n db.bulkGet<TEntity>({\n docs: ids.map(w => ({ id: w as string }))\n }, (error, response) => {\n\n if (error) {\n d(Result.error(error));\n return\n }\n\n d(Result.success(response));\n });\n }, done);\n }\n\n private _validateSchemas(event: DbPluginBulkPersistEvent) {\n for (const [schemaId, schema] of event.schemas) {\n\n // Only schemas this persist actually writes: a store may declare other collections,\n // and an unused bad one should not block saves to the good ones.\n if (event.operation.get(schemaId)?.hasItems !== true) {\n continue;\n }\n\n if (schema.idProperties.length > 1) {\n throw new Error(\"PouchDB cannot have more than one key per document. Only '_id' is allowed to be the key\")\n }\n\n // An identity key is generated by PouchDB as '_id' and echoed back as '_id', so an\n // identity key under any other name is never filled in: every entity reads back with\n // an undefined key and the change tracker merges them all into one. Corruption, not\n // an error — so refuse the schema up front. A caller-supplied key (default/computed)\n // is stored as an ordinary field and round-trips fine under any name. A `.from()` on the\n // identity key is refused for the same reason: it is stored under its `from` name, and\n // PouchDB fills in `_id`.\n const key = schema.idProperties[0];\n if (key != null && key.isIdentity && (key.name !== \"_id\" || key.getResolvedName() !== \"_id\")) {\n throw new Error(\n `PouchDB generates identity keys as '_id'. The schema for collection '${schema.collectionName}' uses ` +\n `'${key.name}' as its identity key, which PouchDB cannot fill in. ` +\n `Declare the key as: _id: s.string().key().identity()`\n );\n }\n }\n }\n\n private _bulkPersist(\n event: DbPluginBulkPersistEvent,\n done: PluginEventCallbackPartialResult<BulkPersistResult>) {\n\n this._validateSchemas(event);\n\n const result = event.operation.toResult();\n const identitySchemaIds: SchemaId[] = [];\n const defaultSchemaIds: SchemaId[] = [];\n\n for (const [schemaId, schema] of event.schemas) {\n\n if (schema.hasIdentityKeys) {\n identitySchemaIds.push(schemaId);\n continue;\n }\n\n defaultSchemaIds.push(schemaId);\n }\n\n this._identityBulkOperations(identitySchemaIds, event.operation, result, (identityResult) => {\n\n if (identityResult.ok !== Result.SUCCESS) {\n done(PluginEventResult.error(event.id, identityResult.error))\n return;\n }\n\n this._defaultBulkOperations(defaultSchemaIds, event.operation, result, (defaultResult) => {\n\n if (defaultResult.ok !== Result.SUCCESS) {\n done(PluginEventResult.error(event.id, defaultResult.error))\n return;\n }\n\n done(PluginEventResult.success(event.id, result))\n });\n\n });\n }\n\n private _doWork<TResult, TEntity>(work: (db: PouchDB.Database<TEntity>, done: CallbackResult<TResult>) => void, done: CallbackResult<TResult>, shouldClose: boolean = false) {\n const db = this.database<TEntity>();\n\n work(db, (result) => {\n\n // The `return` is the fix. Without it, `shouldClose` ran BOTH branches: `done`\n // fired synchronously here and again from the close callback. A doubled callback\n // resolves a settled promise silently, but it also drives every pipeline stage\n // downstream twice — see known-defects #3's \"calls done exactly once\".\n if (shouldClose) {\n // The handle is shared, so closing it has to clear the cache too — the next\n // operation must open a fresh one rather than reuse a closed database.\n this.localDb = null;\n db.close(() => done(result));\n return;\n }\n\n done(result);\n })\n }\n\n destroy(_event: DbPluginEvent, done: (error?: any) => void): void {\n // Replication first. A live sync holds both the local and the remote database open\n // and keeps polling; destroying the local one underneath it leaves a replication\n // running against a database that no longer exists, which surfaces later as errors\n // from a plugin the caller believes it has finished with.\n if (this.syncHandle != null) {\n try {\n this.syncHandle.cancel();\n } catch {\n // An already-finished sync throws on cancel. Destroy's goal is that no\n // replication is running, and that is satisfied either way.\n }\n\n this.syncHandle = null;\n }\n\n // A destroyed database must not keep serving its cached design document to a plugin\n // that outlives it.\n this.indexCache = null;\n\n // `shouldClose: true`, so the handle this work opened is closed rather than left to\n // the garbage collector. It was false, which is what left destroy leaking the very\n // resource it was called to release.\n this._doWork((w, d) => {\n w.destroy(null, (e) => {\n if (e) {\n d(Result.error(e))\n return;\n }\n\n d(Result.success());\n });\n }, done, true);\n }\n\n\n bulkPersist(\n event: DbPluginBulkPersistEvent,\n done: PluginEventCallbackPartialResult<BulkPersistResult>) {\n\n const unitOfWork: SyncronousUnitOfWork = (d) => this._bulkPersist(event, (r) => {\n d();\n done(r)\n })\n\n this.queue.enqueue(unitOfWork.bind(this));\n }\n\n query<TRoot extends {}, TShape extends any = TRoot>(event: DbPluginQueryEvent<TRoot, TShape>, done: PluginEventCallbackResult<ITranslatedValue<TShape>>): void {\n\n const unitOfWork: SyncronousUnitOfWork = (d) => {\n const settle = (r: Parameters<typeof done>[0]) => {\n d();\n done(r);\n };\n\n // A join is two reads through `_query` — the UN-QUEUED path — on purpose: this unit of\n // work already holds the queue, so routing them through `query` would make them wait on\n // itself and the plugin would never answer. They are still serialized against every\n // other query, because this slot is held for both.\n if (event.operation.options.has(\"join\")) {\n joinInPlugin(event, (e, cb) => this._query(e, cb), settle as never);\n return;\n }\n\n this._query<TRoot, TShape>(event, settle);\n };\n\n this.queue.enqueue(unitOfWork.bind(this));\n }\n\n protected onGetIndex<TEntity extends {}, TShape extends unknown = TEntity>(_: IQuery<TEntity, TShape>, __: PouchDB.Find.FindRequest<unknown>, done: (result: null | string | [string, string]) => void) {\n done(null);\n }\n\n extractEqualityValueForProperty(expression: Expression, prop: PropertyInfo<any>): any | undefined {\n // Recursively search for a comparator expression that matches the property\n if (expression.type === \"comparator\" && (expression as ComparatorExpression).comparator === \"equals\") {\n // Check left side is property, right side is value\n if (expression.left && expression.left.type === \"property\" && (expression.left as any).property.name === prop.name && expression.right && expression.right.type === \"value\") {\n return (expression.right as any).value;\n }\n // Or right side is property, left side is value\n if (expression.right && expression.right.type === \"property\" && (expression.right as any).property.name === prop.name && expression.left && expression.left.type === \"value\") {\n return (expression.left as any).value;\n }\n }\n // Recursively check left and right\n if (expression.left) {\n const left = this.extractEqualityValueForProperty(expression.left, prop);\n if (left !== undefined) return left;\n }\n if (expression.right) {\n const right = this.extractEqualityValueForProperty(expression.right, prop);\n if (right !== undefined) return right;\n }\n return undefined;\n }\n\n private _findMatchingIndex(ddoc: PouchDbDesignDoc, expression: Expression): MatchingIndex {\n const queryProperties = getProperties(expression);\n\n const { viewName } = this._prepareProperties(...queryProperties);\n\n if (ddoc.views == null) {\n return null;\n }\n\n const index = ddoc.views[viewName];\n\n if (index == null) {\n return null;\n }\n\n const properties: MatchingIndex[\"properties\"] = [];\n\n for (const property of queryProperties) {\n const value = this.extractEqualityValueForProperty(expression, property);\n\n if (value === undefined) {\n return null\n }\n\n properties.push({\n property,\n value\n });\n }\n\n return {\n viewName,\n properties\n };\n }\n\n private _queryIndex<TEntity extends {}, TShape extends unknown = TEntity>(event: DbPluginQueryEvent<TEntity, TShape>, matchingIndex: MatchingIndex, done: CallbackResult<ITranslatedValue<TShape>>) {\n const translator = new PouchDbTranslator<TEntity, TShape>(event.operation);\n this._doWork((w, d) => {\n\n const options: PouchDB.Query.Options<any, any> = {\n include_docs: true,\n };\n\n const values = matchingIndex.properties.map(x => x.value);\n\n if (values.some(x => x == null) == false) {\n\n if (values.length === 1) {\n options.key = values[0];\n } else {\n options.keys = values;\n }\n }\n\n w.query(`${INDEX_NAME}/${matchingIndex.viewName}`, options, (error, response) => {\n\n if (error != null) {\n d(Result.error(error));\n return;\n }\n\n try {\n event.executedQueries.push({ text: `${INDEX_NAME}/${matchingIndex.viewName}: indexed view query` });\n\n const translated = translator.translate(response.rows.map(w => w.doc));\n d(Result.success(translated));\n } catch (e) {\n d(Result.error(e));\n }\n });\n }, done);\n }\n\n private _queryNoIndex<TEntity extends {}, TShape extends unknown = TEntity>(event: DbPluginQueryEvent<TEntity, TShape>, done: CallbackResult<ITranslatedValue<TShape>>) {\n const filters = event.operation.options.get(\"filter\")\n if (filters.length === 0) {\n this._queryWithNoFilters(event, done);\n return;\n }\n\n this._queryWithFilters(event, done);\n }\n\n private _queryWithNoFilters<TEntity extends {}, TShape extends unknown = TEntity>(event: DbPluginQueryEvent<TEntity, TShape>, done: CallbackResult<ITranslatedValue<TShape>>) {\n const translator = new PouchDbTranslator<TEntity, TShape>(event.operation);\n this._doWork((w, d) => {\n w.allDocs({\n include_docs: true\n }).then(response => {\n\n try {\n event.executedQueries.push({ text: \"allDocs({ include_docs: true }): full database scan, no index\" });\n\n const data = response.rows.map(w => w.doc);\n const translated = translator.translate(data);\n d(Result.success(translated));\n } catch (e) {\n d(Result.error(e));\n }\n }).catch(error => {\n d(Result.error(error));\n });\n }, done);\n }\n\n private _queryWithFilters<TEntity extends {}, TShape extends unknown = TEntity>(event: DbPluginQueryEvent<TEntity, TShape>, done: CallbackResult<ITranslatedValue<TShape>>) {\n const translator = new PouchDbTranslator<TEntity, TShape>(event.operation);\n this._doWork((w, d) => {\n\n if (this._name.startsWith(\"http\")) {\n // Cannot query remote databases using translator.matches, fallback to alldocs\n // Does not throw, will fail on the remote server\n w.allDocs({\n include_docs: true\n }).then(response => {\n const data = response.rows.map(w => w.doc);\n try {\n event.executedQueries.push({ text: \"allDocs({ include_docs: true }): full database scan, no index\" });\n\n const translated = translator.translate(data);\n d(Result.success(translated));\n } catch (e) {\n d(Result.error(e));\n }\n }).catch(error => {\n d(Result.error(error));\n });\n return;\n }\n\n w.query<{}, any>((doc, emit) => {\n if (typeof doc === \"object\" && \"_id\" in doc && translator.matches(doc)) {\n emit(doc._id, doc);\n }\n }, (error, response) => {\n\n if (error != null) {\n d(Result.error(error));\n return;\n }\n\n const data = response.rows.map(w => w.value);\n\n try {\n event.executedQueries.push({ text: \"view query\" });\n\n const translated = translator.translate(data);\n d(Result.success(translated));\n } catch (e) {\n d(Result.error(e));\n }\n });\n\n }, done);\n }\n\n private _query<TEntity extends {}, TShape extends unknown = TEntity>(event: DbPluginQueryEvent<TEntity, TShape>, done: PluginEventCallbackResult<ITranslatedValue<TShape>>): void {\n // Documents are matched and sorted by the caller's lambdas, over documents as they are\n // stored, where a `from` property has a different key. Handed back before any index is\n // chosen, so neither the index nor the view sees an option this plugin cannot run.\n reportRenamedProperties(event.operation.options);\n\n this.resolveIndexes(event, (r) => {\n if (r.ok !== Result.SUCCESS) {\n done(PluginEventResult.error(event.id, r.error))\n return;\n }\n\n const ddoc = r.data;\n\n if (ddoc == null) {\n this._queryNoIndex(event, done);\n return;\n }\n\n const mapMatchingIndex = this.findMatchingIndexForMap(ddoc, event);\n\n if (mapMatchingIndex != null) {\n this._queryIndex(event, mapMatchingIndex, done);\n return;\n }\n\n const expression = this._getExpressionFromQuery(event);\n\n if (Expression.isEmpty(expression)) {\n this._queryNoIndex(event, done);\n return;\n }\n\n const matchingIndex = this._findMatchingIndex(ddoc, expression);\n\n if (matchingIndex == null) {\n this._queryNoIndex(event, done);\n return;\n }\n\n this._queryIndex(event, matchingIndex, done);\n });\n }\n\n private _getExpressionFromQuery<TEntity extends {}, TShape>(event: DbPluginQueryEvent<TEntity, TShape>) {\n const filters = event.operation.options.get(\"filter\");\n\n const databaseFilters = filters.filter(x => x.option.target === \"database\" && x.option.reason === \"executed\");\n\n if (databaseFilters.length === 0) {\n return Expression.EMPTY;\n }\n\n const expressions = databaseFilters.map(x => x.option.value.expression);\n\n return combineExpressions(...expressions);\n }\n\n private findMatchingIndexForMap<TEntity extends {}, TShape>(ddoc: PouchDbDesignDoc, event: DbPluginQueryEvent<TEntity, TShape>): MatchingIndex | null {\n const map = event.operation.options.getLast(\"map\");\n const filters = event.operation.options.get(\"filter\");\n\n // we only want to look at the index if there are no filters\n if (filters.length > 0) {\n return null;\n }\n\n if (map == null || map.target !== \"database\") {\n return null;\n }\n\n if (map.value.fields.length !== 1 || map.value.fields[0].property == null) {\n return null;\n }\n\n const property = map.value.fields[0].property;\n\n const { viewName } = this._prepareProperties(property);\n\n if (ddoc.views == null) {\n return null;\n }\n\n const index = ddoc.views[viewName];\n\n if (index == null) {\n return null;\n }\n\n return {\n viewName,\n properties: [{ property, value: null }]\n }\n }\n}","export { PouchDbPlugin } from './PouchDbPlugin';"],"names":["assertIsArray","JsonTranslator","getStorageDateReviver","PouchDbTranslator","query","item","filterChain","filters","databaseFilters","x","index","currentFilter","nextFilter","filter","selector","params","data","documents","i","length","document","PouchDB","SyncronousQueue","WorkPipeline","joinInPlugin","reportRenamedProperties","PluginEventResult","Result","assertIsNotNull","combineExpressions","Expression","getProperties","INDEX_NAME","PouchDbPlugin","_sync","_queryType","rest","name","options","schemas","localDb","remoteDb","sync","e","db","done","missing","String","response","revisions","Map","row","revision","error","identitySchemaIds","changes","result","updates","adds","removes","schemaId","schemaChanges","d","updatedDocuments","w","errors","tombstones","revisionError","doc","updatesIndex","update","changesResult","removesIndex","remove","pipeline","schemaAdds","schemaResult","ids","reason","bulkGetResponse","docs","r","nonIdentitySchemaIds","Error","properties","a","b","undefined","paths","viewName","event","indexes","ddoc","path","matchingIndex","views","Object","schema","key","defaultSchemaIds","identityResult","defaultResult","work","shouldClose","_event","unitOfWork","settle","cb","_","__","expression","prop","left","right","queryProperties","property","value","translator","values","translated","emit","mapMatchingIndex","expressions","map"],"mappings":";;;;;;;;;;;;AAAA;AACA;AACA;AACA,kDAAkD,wCAAwC;AAC1F;AACA;AACA,E;;;;ACNA,wF;;;;;;;;;;;;;;;;;;ACAyD;AAEwC;AAChB;AAE1E,MAAMG,0BAAgFF,cAAcA;IAEvG;;;;KAIC,GACgB,YAAuC;IAChD,gBAAqD,KAAK;IAElE,YAAYG,KAA8B,CAAE;QACxC,KAAK,CAACA;QACN,IAAI,CAAC,WAAW,GAAGF,qBAAqBA,CAACE,MAAM,MAAM;IACzD;IAEA,QAAQC,IAAa,EAAE;QACnB,mCAAmC;QACnC,MAAMC,cAAc,IAAI,CAAC,kBAAkB;QAE3C,IAAI,CAAC,WAAW,GAAGD;QAEnB,8DAA8D;QAC9D,OAAOC,YAAYD;IACvB;IAEQ,qBAAiD;QACrD,mCAAmC;QACnC,IAAI,IAAI,CAAC,aAAa,KAAK,MAAM;YAC7B,OAAO,IAAI,CAAC,aAAa;QAC7B;QAEA,mCAAmC;QACnC,MAAME,UAAU,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,GAAG,CAAC;QACvC,uFAAuF;QACvF,MAAMC,kBAAkBD,QAAQ,MAAM,CAACE,CAAAA,IAAKA,EAAE,MAAM,CAAC,MAAM,KAAK,cAAcA,EAAE,MAAM,CAAC,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E;YACA,YAAY;gBAAC;oBAAE0B;oBAAU,OAAO;gBAAK;aAAE;QAC3C;IACJ;AACJ;;;AC3rCgD"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@routier/pouchdb-plugin",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.5.1",
|
|
4
4
|
"main": "./dist/index.cjs",
|
|
5
5
|
"types": "./dist/index.d.ts",
|
|
6
6
|
"source": "./src/index.ts",
|
|
@@ -43,16 +43,16 @@
|
|
|
43
43
|
],
|
|
44
44
|
"description": "PouchDB plugin for routier",
|
|
45
45
|
"dependencies": {
|
|
46
|
-
"events": "^3.3.0"
|
|
47
|
-
"pouchdb": "^9.0.0"
|
|
46
|
+
"events": "^3.3.0"
|
|
48
47
|
},
|
|
49
48
|
"peerDependencies": {
|
|
50
|
-
"@routier/core": ">=0.
|
|
49
|
+
"@routier/core": ">=0.8.0",
|
|
50
|
+
"pouchdb": ">=9.0.0"
|
|
51
51
|
},
|
|
52
52
|
"devDependencies": {
|
|
53
53
|
"@faker-js/faker": "^10.0.0",
|
|
54
|
-
"@routier/core": "^0.
|
|
55
|
-
"@routier/datastore": "^0.4.
|
|
54
|
+
"@routier/core": "^0.8.0",
|
|
55
|
+
"@routier/datastore": "^0.4.2",
|
|
56
56
|
"@routier/memory-plugin": "file://../memory",
|
|
57
57
|
"@routier/test-utils": "^0.3.0",
|
|
58
58
|
"@rspack/cli": "^1.1.8",
|