@routier/pouchdb-plugin 0.5.2 → 0.5.3
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/explainQuery.d.ts +6 -0
- package/dist/index.cjs +65 -12
- package/dist/index.cjs.map +1 -1
- package/dist/index.js +66 -13
- package/dist/index.js.map +1 -1
- package/package.json +4 -4
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import type { DescribedFilters, ExecutedQuery } from '@routier/core/plugins';
|
|
2
|
+
export type ViewKeyOptions = Pick<PouchDB.Query.Options<{}, {}>, 'key' | 'keys'>;
|
|
3
|
+
export declare const fullReadQuery: () => ExecutedQuery;
|
|
4
|
+
export declare const indexedViewQuery: (view: string, options: ViewKeyOptions, described: DescribedFilters) => ExecutedQuery;
|
|
5
|
+
export declare const remoteScanQuery: (described: DescribedFilters) => ExecutedQuery;
|
|
6
|
+
export declare const temporaryViewQuery: (described: DescribedFilters) => ExecutedQuery;
|
package/dist/index.cjs
CHANGED
|
@@ -141,6 +141,65 @@ class PouchDbTranslator extends plugins_namespaceObject.JsonTranslator {
|
|
|
141
141
|
}
|
|
142
142
|
}
|
|
143
143
|
|
|
144
|
+
;// CONCATENATED MODULE: ./src/explainQuery.ts
|
|
145
|
+
const withParameters = (described, before = [])=>{
|
|
146
|
+
const parameters = [
|
|
147
|
+
...before,
|
|
148
|
+
...described.parameters
|
|
149
|
+
];
|
|
150
|
+
return parameters.length > 0 ? {
|
|
151
|
+
parameters
|
|
152
|
+
} : {};
|
|
153
|
+
};
|
|
154
|
+
const viewKey = (options)=>{
|
|
155
|
+
if (options.keys != null) {
|
|
156
|
+
return {
|
|
157
|
+
text: `keys: [${options.keys.map(()=>'?').join(', ')}], `,
|
|
158
|
+
parameters: options.keys
|
|
159
|
+
};
|
|
160
|
+
}
|
|
161
|
+
return 'key' in options ? {
|
|
162
|
+
text: 'key: ?, ',
|
|
163
|
+
parameters: [
|
|
164
|
+
options.key
|
|
165
|
+
]
|
|
166
|
+
} : {
|
|
167
|
+
text: '',
|
|
168
|
+
parameters: []
|
|
169
|
+
};
|
|
170
|
+
};
|
|
171
|
+
const filteredRows = (described)=>described.text === '' ? '' : `\n .then(({ rows }) => rows.map(row => row.doc).filter(doc => ${described.text}))`;
|
|
172
|
+
const noteWith = (note, described)=>[
|
|
173
|
+
note,
|
|
174
|
+
...described.notes
|
|
175
|
+
].join('; ');
|
|
176
|
+
const fullReadQuery = ()=>({
|
|
177
|
+
text: 'db.allDocs({ include_docs: true })',
|
|
178
|
+
language: 'pouchdb',
|
|
179
|
+
note: 'a full database read, no index'
|
|
180
|
+
});
|
|
181
|
+
const indexedViewQuery = (view, options, described)=>{
|
|
182
|
+
const key = viewKey(options);
|
|
183
|
+
return {
|
|
184
|
+
text: `db.query(${JSON.stringify(view)}, { ${key.text}include_docs: true })${filteredRows(described)}`,
|
|
185
|
+
...withParameters(described, key.parameters),
|
|
186
|
+
language: 'pouchdb',
|
|
187
|
+
note: noteWith('an indexed view query', described)
|
|
188
|
+
};
|
|
189
|
+
};
|
|
190
|
+
const remoteScanQuery = (described)=>({
|
|
191
|
+
text: `db.allDocs({ include_docs: true })${filteredRows(described)}`,
|
|
192
|
+
...withParameters(described),
|
|
193
|
+
language: 'pouchdb',
|
|
194
|
+
note: noteWith('a full read of a remote database, filtered in JavaScript', described)
|
|
195
|
+
});
|
|
196
|
+
const temporaryViewQuery = (described)=>({
|
|
197
|
+
text: `db.query((doc, emit) => {\n if (${described.text}) emit(doc._id, doc);\n})`,
|
|
198
|
+
...withParameters(described),
|
|
199
|
+
language: 'pouchdb',
|
|
200
|
+
note: noteWith('a temporary view: PouchDB runs the map function over every document', described)
|
|
201
|
+
});
|
|
202
|
+
|
|
144
203
|
;// CONCATENATED MODULE: external "@routier/core/pipeline"
|
|
145
204
|
const pipeline_namespaceObject = require("@routier/core/pipeline");
|
|
146
205
|
;// CONCATENATED MODULE: external "@routier/core/results"
|
|
@@ -155,7 +214,9 @@ const expressions_namespaceObject = require("@routier/core/expressions");
|
|
|
155
214
|
|
|
156
215
|
|
|
157
216
|
|
|
217
|
+
|
|
158
218
|
const INDEX_NAME = "routier_pdb_indexes";
|
|
219
|
+
const filtersOf = (event)=>(0,plugins_namespaceObject.describeFilters)(event.operation.options.get("filter").map((item)=>item.option.value), "doc");
|
|
159
220
|
class PouchDbPlugin {
|
|
160
221
|
_name;
|
|
161
222
|
_options;
|
|
@@ -944,9 +1005,7 @@ class PouchDbPlugin {
|
|
|
944
1005
|
return;
|
|
945
1006
|
}
|
|
946
1007
|
try {
|
|
947
|
-
event.executedQueries.push({
|
|
948
|
-
text: `${INDEX_NAME}/${matchingIndex.viewName}: indexed view query`
|
|
949
|
-
});
|
|
1008
|
+
event.executedQueries.push(indexedViewQuery(`${INDEX_NAME}/${matchingIndex.viewName}`, options, filtersOf(event)));
|
|
950
1009
|
const translated = translator.translate(response.rows.map((w)=>w.doc));
|
|
951
1010
|
d(results_namespaceObject.Result.success(translated));
|
|
952
1011
|
} catch (e) {
|
|
@@ -970,9 +1029,7 @@ class PouchDbPlugin {
|
|
|
970
1029
|
include_docs: true
|
|
971
1030
|
}).then((response)=>{
|
|
972
1031
|
try {
|
|
973
|
-
event.executedQueries.push(
|
|
974
|
-
text: "allDocs({ include_docs: true }): full database scan, no index"
|
|
975
|
-
});
|
|
1032
|
+
event.executedQueries.push(fullReadQuery());
|
|
976
1033
|
const data = response.rows.map((w)=>w.doc);
|
|
977
1034
|
const translated = translator.translate(data);
|
|
978
1035
|
d(results_namespaceObject.Result.success(translated));
|
|
@@ -995,9 +1052,7 @@ class PouchDbPlugin {
|
|
|
995
1052
|
}).then((response)=>{
|
|
996
1053
|
const data = response.rows.map((w)=>w.doc);
|
|
997
1054
|
try {
|
|
998
|
-
event.executedQueries.push(
|
|
999
|
-
text: "allDocs({ include_docs: true }): full database scan, no index"
|
|
1000
|
-
});
|
|
1055
|
+
event.executedQueries.push(remoteScanQuery(filtersOf(event)));
|
|
1001
1056
|
const translated = translator.translate(data);
|
|
1002
1057
|
d(results_namespaceObject.Result.success(translated));
|
|
1003
1058
|
} catch (e) {
|
|
@@ -1019,9 +1074,7 @@ class PouchDbPlugin {
|
|
|
1019
1074
|
}
|
|
1020
1075
|
const data = response.rows.map((w)=>w.value);
|
|
1021
1076
|
try {
|
|
1022
|
-
event.executedQueries.push(
|
|
1023
|
-
text: "view query"
|
|
1024
|
-
});
|
|
1077
|
+
event.executedQueries.push(temporaryViewQuery(filtersOf(event)));
|
|
1025
1078
|
const translated = translator.translate(data);
|
|
1026
1079
|
d(results_namespaceObject.Result.success(translated));
|
|
1027
1080
|
} catch (e) {
|
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/pouchRevision.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}","import type { EtagComparator } from '@routier/core/schema';\n\nexport const pouchRevision: EtagComparator<string> = (prev, next) => {\n const prevGeneration = Number(prev.slice(0, prev.indexOf('-')));\n const nextGeneration = Number(next.slice(0, next.indexOf('-')));\n\n if (prevGeneration !== nextGeneration) {\n return Math.sign(prevGeneration - nextGeneration);\n }\n\n return prev < next ? -1 : prev > next ? 1 : 0;\n};\n","export { PouchDbPlugin } from './PouchDbPlugin';\nexport { pouchRevision } from './pouchRevision';\n"],"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","pouchRevision","prev","next","prevGeneration","Number","nextGeneration","Math"],"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,OAAO,CAAC,GAAG,CAAC;QACvC,uFAAuF;QACvF,MAAMC,kBAAkBD,QAAQ,MAAM,CAAC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;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;;;ACzrCO,MAAMS,gBAAwC,CAACC,MAAMC;IACxD,MAAMC,iBAAiBC,OAAOH,KAAK,KAAK,CAAC,GAAGA,KAAK,OAAO,CAAC;IACzD,MAAMI,iBAAiBD,OAAOF,KAAK,KAAK,CAAC,GAAGA,KAAK,OAAO,CAAC;IAEzD,IAAIC,mBAAmBE,gBAAgB;QACnC,OAAOC,KAAK,IAAI,CAACH,iBAAiBE;IACtC;IAEA,OAAOJ,OAAOC,OAAO,CAAC,IAAID,OAAOC,OAAO,IAAI;AAChD,EAAE;;;ACX8C;AACA"}
|
|
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/explainQuery.ts","webpack://@routier/pouchdb-plugin/./src/PouchDbPlugin.ts","webpack://@routier/pouchdb-plugin/./src/pouchRevision.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 type { DescribedFilters, ExecutedQuery } from '@routier/core/plugins';\n\ntype Parameters = NonNullable<ExecutedQuery['parameters']>;\n\nexport type ViewKeyOptions = Pick<PouchDB.Query.Options<{}, {}>, 'key' | 'keys'>;\n\nconst withParameters = (described: DescribedFilters, before: Parameters = []) => {\n const parameters = [...before, ...described.parameters];\n\n return parameters.length > 0 ? { parameters } : {};\n};\n\nconst viewKey = (options: ViewKeyOptions): { text: string; parameters: Parameters } => {\n if (options.keys != null) {\n return { text: `keys: [${options.keys.map(() => '?').join(', ')}], `, parameters: options.keys };\n }\n\n return 'key' in options ? { text: 'key: ?, ', parameters: [options.key] } : { text: '', parameters: [] };\n};\n\nconst filteredRows = (described: DescribedFilters) =>\n described.text === '' ? '' : `\\n .then(({ rows }) => rows.map(row => row.doc).filter(doc => ${described.text}))`;\n\nconst noteWith = (note: string, described: DescribedFilters) => [note, ...described.notes].join('; ');\n\nexport const fullReadQuery = (): ExecutedQuery => ({\n text: 'db.allDocs({ include_docs: true })',\n language: 'pouchdb',\n note: 'a full database read, no index',\n});\n\nexport const indexedViewQuery = (view: string, options: ViewKeyOptions, described: DescribedFilters): ExecutedQuery => {\n const key = viewKey(options);\n\n return {\n text: `db.query(${JSON.stringify(view)}, { ${key.text}include_docs: true })${filteredRows(described)}`,\n ...withParameters(described, key.parameters),\n language: 'pouchdb',\n note: noteWith('an indexed view query', described),\n };\n};\n\nexport const remoteScanQuery = (described: DescribedFilters): ExecutedQuery => ({\n text: `db.allDocs({ include_docs: true })${filteredRows(described)}`,\n ...withParameters(described),\n language: 'pouchdb',\n note: noteWith('a full read of a remote database, filtered in JavaScript', described),\n});\n\nexport const temporaryViewQuery = (described: DescribedFilters): ExecutedQuery => ({\n text: `db.query((doc, emit) => {\\n if (${described.text}) emit(doc._id, doc);\\n})`,\n ...withParameters(described),\n language: 'pouchdb',\n note: noteWith('a temporary view: PouchDB runs the map function over every document', described),\n});\n","import PouchDB from 'pouchdb';\nimport { PouchDbTranslator } from './PouchDbTranslator';\nimport { fullReadQuery, indexedViewQuery, remoteScanQuery, temporaryViewQuery } from './explainQuery';\nimport { SyncronousQueue, SyncronousUnitOfWork, WorkPipeline } from '@routier/core/pipeline';\nimport { InferCreateType, InferType, PropertyInfo, SchemaId } from '@routier/core/schema';\nimport { DbPluginBulkPersistEvent, DbPluginEvent, DbPluginQueryEvent, describeFilters, type DescribedFilters, 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\n\nconst filtersOf = <TEntity extends {}, TShape>(event: DbPluginQueryEvent<TEntity, TShape>): DescribedFilters =>\n describeFilters(event.operation.options.get(\"filter\").map(item => item.option.value), \"doc\");\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(indexedViewQuery(`${INDEX_NAME}/${matchingIndex.viewName}`, options, filtersOf(event)));\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(fullReadQuery());\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(remoteScanQuery(filtersOf(event)));\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(temporaryViewQuery(filtersOf(event)));\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}","import type { EtagComparator } from '@routier/core/schema';\n\nexport const pouchRevision: EtagComparator<string> = (prev, next) => {\n const prevGeneration = Number(prev.slice(0, prev.indexOf('-')));\n const nextGeneration = Number(next.slice(0, next.indexOf('-')));\n\n if (prevGeneration !== nextGeneration) {\n return Math.sign(prevGeneration - nextGeneration);\n }\n\n return prev < next ? -1 : prev > next ? 1 : 0;\n};\n","export { PouchDbPlugin } from './PouchDbPlugin';\nexport { pouchRevision } from './pouchRevision';\n"],"names":["assertIsArray","JsonTranslator","getStorageDateReviver","PouchDbTranslator","query","item","filterChain","filters","databaseFilters","x","index","currentFilter","nextFilter","filter","selector","params","data","documents","i","length","document","withParameters","described","before","parameters","viewKey","options","filteredRows","noteWith","note","fullReadQuery","indexedViewQuery","view","key","JSON","remoteScanQuery","temporaryViewQuery","PouchDB","SyncronousQueue","WorkPipeline","describeFilters","joinInPlugin","reportRenamedProperties","PluginEventResult","Result","assertIsNotNull","combineExpressions","Expression","getProperties","INDEX_NAME","filtersOf","event","PouchDbPlugin","_sync","_queryType","rest","name","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","indexes","ddoc","path","matchingIndex","views","Object","schema","defaultSchemaIds","identityResult","defaultResult","work","shouldClose","_event","unitOfWork","settle","cb","_","__","expression","prop","left","right","queryProperties","property","value","translator","values","translated","emit","mapMatchingIndex","expressions","map","pouchRevision","prev","next","prevGeneration","Number","nextGeneration","Math"],"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,gDAAq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AAK,CAAC,GAAGA,KAAK,OAAO,CAAC;IAEzD,IAAIC,mBAAmBE,gBAAgB;QACnC,OAAOC,KAAK,IAAI,CAACH,iBAAiBE;IACtC;IAEA,OAAOJ,OAAOC,OAAO,CAAC,IAAID,OAAOC,OAAO,IAAI;AAChD,EAAE;;;ACX8C;AACA"}
|
package/dist/index.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import pouchdb from "pouchdb";
|
|
2
2
|
import { assertIsArray, assertIsNotNull } from "@routier/core/assertions";
|
|
3
|
-
import { JsonTranslator, joinInPlugin, reportRenamedProperties } from "@routier/core/plugins";
|
|
3
|
+
import { JsonTranslator, describeFilters, joinInPlugin, reportRenamedProperties } from "@routier/core/plugins";
|
|
4
4
|
import { getStorageDateReviver } from "@routier/core/schema";
|
|
5
5
|
import { SyncronousQueue, WorkPipeline } from "@routier/core/pipeline";
|
|
6
6
|
import { PluginEventResult, Result } from "@routier/core/results";
|
|
@@ -121,6 +121,65 @@ class PouchDbTranslator extends JsonTranslator {
|
|
|
121
121
|
}
|
|
122
122
|
}
|
|
123
123
|
|
|
124
|
+
;// CONCATENATED MODULE: ./src/explainQuery.ts
|
|
125
|
+
const withParameters = (described, before = [])=>{
|
|
126
|
+
const parameters = [
|
|
127
|
+
...before,
|
|
128
|
+
...described.parameters
|
|
129
|
+
];
|
|
130
|
+
return parameters.length > 0 ? {
|
|
131
|
+
parameters
|
|
132
|
+
} : {};
|
|
133
|
+
};
|
|
134
|
+
const viewKey = (options)=>{
|
|
135
|
+
if (options.keys != null) {
|
|
136
|
+
return {
|
|
137
|
+
text: `keys: [${options.keys.map(()=>'?').join(', ')}], `,
|
|
138
|
+
parameters: options.keys
|
|
139
|
+
};
|
|
140
|
+
}
|
|
141
|
+
return 'key' in options ? {
|
|
142
|
+
text: 'key: ?, ',
|
|
143
|
+
parameters: [
|
|
144
|
+
options.key
|
|
145
|
+
]
|
|
146
|
+
} : {
|
|
147
|
+
text: '',
|
|
148
|
+
parameters: []
|
|
149
|
+
};
|
|
150
|
+
};
|
|
151
|
+
const filteredRows = (described)=>described.text === '' ? '' : `\n .then(({ rows }) => rows.map(row => row.doc).filter(doc => ${described.text}))`;
|
|
152
|
+
const noteWith = (note, described)=>[
|
|
153
|
+
note,
|
|
154
|
+
...described.notes
|
|
155
|
+
].join('; ');
|
|
156
|
+
const fullReadQuery = ()=>({
|
|
157
|
+
text: 'db.allDocs({ include_docs: true })',
|
|
158
|
+
language: 'pouchdb',
|
|
159
|
+
note: 'a full database read, no index'
|
|
160
|
+
});
|
|
161
|
+
const indexedViewQuery = (view, options, described)=>{
|
|
162
|
+
const key = viewKey(options);
|
|
163
|
+
return {
|
|
164
|
+
text: `db.query(${JSON.stringify(view)}, { ${key.text}include_docs: true })${filteredRows(described)}`,
|
|
165
|
+
...withParameters(described, key.parameters),
|
|
166
|
+
language: 'pouchdb',
|
|
167
|
+
note: noteWith('an indexed view query', described)
|
|
168
|
+
};
|
|
169
|
+
};
|
|
170
|
+
const remoteScanQuery = (described)=>({
|
|
171
|
+
text: `db.allDocs({ include_docs: true })${filteredRows(described)}`,
|
|
172
|
+
...withParameters(described),
|
|
173
|
+
language: 'pouchdb',
|
|
174
|
+
note: noteWith('a full read of a remote database, filtered in JavaScript', described)
|
|
175
|
+
});
|
|
176
|
+
const temporaryViewQuery = (described)=>({
|
|
177
|
+
text: `db.query((doc, emit) => {\n if (${described.text}) emit(doc._id, doc);\n})`,
|
|
178
|
+
...withParameters(described),
|
|
179
|
+
language: 'pouchdb',
|
|
180
|
+
note: noteWith('a temporary view: PouchDB runs the map function over every document', described)
|
|
181
|
+
});
|
|
182
|
+
|
|
124
183
|
;// CONCATENATED MODULE: external "@routier/core/pipeline"
|
|
125
184
|
|
|
126
185
|
;// CONCATENATED MODULE: external "@routier/core/results"
|
|
@@ -135,7 +194,9 @@ class PouchDbTranslator extends JsonTranslator {
|
|
|
135
194
|
|
|
136
195
|
|
|
137
196
|
|
|
197
|
+
|
|
138
198
|
const INDEX_NAME = "routier_pdb_indexes";
|
|
199
|
+
const filtersOf = (event)=>describeFilters(event.operation.options.get("filter").map((item)=>item.option.value), "doc");
|
|
139
200
|
class PouchDbPlugin {
|
|
140
201
|
_name;
|
|
141
202
|
_options;
|
|
@@ -924,9 +985,7 @@ class PouchDbPlugin {
|
|
|
924
985
|
return;
|
|
925
986
|
}
|
|
926
987
|
try {
|
|
927
|
-
event.executedQueries.push({
|
|
928
|
-
text: `${INDEX_NAME}/${matchingIndex.viewName}: indexed view query`
|
|
929
|
-
});
|
|
988
|
+
event.executedQueries.push(indexedViewQuery(`${INDEX_NAME}/${matchingIndex.viewName}`, options, filtersOf(event)));
|
|
930
989
|
const translated = translator.translate(response.rows.map((w)=>w.doc));
|
|
931
990
|
d(Result.success(translated));
|
|
932
991
|
} catch (e) {
|
|
@@ -950,9 +1009,7 @@ class PouchDbPlugin {
|
|
|
950
1009
|
include_docs: true
|
|
951
1010
|
}).then((response)=>{
|
|
952
1011
|
try {
|
|
953
|
-
event.executedQueries.push(
|
|
954
|
-
text: "allDocs({ include_docs: true }): full database scan, no index"
|
|
955
|
-
});
|
|
1012
|
+
event.executedQueries.push(fullReadQuery());
|
|
956
1013
|
const data = response.rows.map((w)=>w.doc);
|
|
957
1014
|
const translated = translator.translate(data);
|
|
958
1015
|
d(Result.success(translated));
|
|
@@ -975,9 +1032,7 @@ class PouchDbPlugin {
|
|
|
975
1032
|
}).then((response)=>{
|
|
976
1033
|
const data = response.rows.map((w)=>w.doc);
|
|
977
1034
|
try {
|
|
978
|
-
event.executedQueries.push(
|
|
979
|
-
text: "allDocs({ include_docs: true }): full database scan, no index"
|
|
980
|
-
});
|
|
1035
|
+
event.executedQueries.push(remoteScanQuery(filtersOf(event)));
|
|
981
1036
|
const translated = translator.translate(data);
|
|
982
1037
|
d(Result.success(translated));
|
|
983
1038
|
} catch (e) {
|
|
@@ -999,9 +1054,7 @@ class PouchDbPlugin {
|
|
|
999
1054
|
}
|
|
1000
1055
|
const data = response.rows.map((w)=>w.value);
|
|
1001
1056
|
try {
|
|
1002
|
-
event.executedQueries.push(
|
|
1003
|
-
text: "view query"
|
|
1004
|
-
});
|
|
1057
|
+
event.executedQueries.push(temporaryViewQuery(filtersOf(event)));
|
|
1005
1058
|
const translated = translator.translate(data);
|
|
1006
1059
|
d(Result.success(translated));
|
|
1007
1060
|
} catch (e) {
|
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/pouchRevision.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}","import type { EtagComparator } from '@routier/core/schema';\n\nexport const pouchRevision: EtagComparator<string> = (prev, next) => {\n const prevGeneration = Number(prev.slice(0, prev.indexOf('-')));\n const nextGeneration = Number(next.slice(0, next.indexOf('-')));\n\n if (prevGeneration !== nextGeneration) {\n return Math.sign(prevGeneration - nextGeneration);\n }\n\n return prev < next ? -1 : prev > next ? 1 : 0;\n};\n","export { PouchDbPlugin } from './PouchDbPlugin';\nexport { pouchRevision } from './pouchRevision';\n"],"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","pouchRevision","prev","next","prevGeneration","Number","nextGeneration","Math"],"mappings":";;;;;;;;;;;;AAAA;AACA;AACA;AACA,kDAAkD,wCAAwC;AAC1F;AACA;AACA,E;;;;ACNA,wF;;;;;;;;;;;;;;;;;;;ACAyD;AAEwC;AAChB;AAE1E,MAAMG,0BAAgFF,cAAcA;IAEvG;;;;KAIC,GACgB,YAAu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,CAAC,GAAG,CAAC;QAE5C,4DAA4D;QAC5D,IAAInF,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,MAAMR,WAAWQ,IAAI,KAAK,CAAC,MAAM,CAAC,EAAE,CAAC,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;;;ACzrCO,MAAMS,gBAAwC,CAACC,MAAMC;IACxD,MAAMC,iBAAiBC,OAAOH,KAAK,KAAK,CAAC,GAAGA,KAAK,OAAO,CAAC;IACzD,MAAMI,iBAAiBD,OAAOF,KAAK,KAAK,CAAC,GAAGA,KAAK,OAAO,CAAC;IAEzD,IAAIC,mBAAmBE,gBAAgB;QACnC,OAAOC,KAAK,IAAI,CAACH,iBAAiBE;IACtC;IAEA,OAAOJ,OAAOC,OAAO,CAAC,IAAID,OAAOC,OAAO,IAAI;AAChD,EAAE;;;ACX8C;AACA"}
|
|
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/explainQuery.ts","webpack://@routier/pouchdb-plugin/./src/PouchDbPlugin.ts","webpack://@routier/pouchdb-plugin/./src/pouchRevision.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 type { DescribedFilters, ExecutedQuery } from '@routier/core/plugins';\n\ntype Parameters = NonNullable<ExecutedQuery['parameters']>;\n\nexport type ViewKeyOptions = Pick<PouchDB.Query.Options<{}, {}>, 'key' | 'keys'>;\n\nconst withParameters = (described: DescribedFilters, before: Parameters = []) => {\n const parameters = [...before, ...described.parameters];\n\n return parameters.length > 0 ? { parameters } : {};\n};\n\nconst viewKey = (options: ViewKeyOptions): { text: string; parameters: Parameters } => {\n if (options.keys != null) {\n return { text: `keys: [${options.keys.map(() => '?').join(', ')}], `, parameters: options.keys };\n }\n\n return 'key' in options ? { text: 'key: ?, ', parameters: [options.key] } : { text: '', parameters: [] };\n};\n\nconst filteredRows = (described: DescribedFilters) =>\n described.text === '' ? '' : `\\n .then(({ rows }) => rows.map(row => row.doc).filter(doc => ${described.text}))`;\n\nconst noteWith = (note: string, described: DescribedFilters) => [note, ...described.notes].join('; ');\n\nexport const fullReadQuery = (): ExecutedQuery => ({\n text: 'db.allDocs({ include_docs: true })',\n language: 'pouchdb',\n note: 'a full database read, no index',\n});\n\nexport const indexedViewQuery = (view: string, options: ViewKeyOptions, described: DescribedFilters): ExecutedQuery => {\n const key = viewKey(options);\n\n return {\n text: `db.query(${JSON.stringify(view)}, { ${key.text}include_docs: true })${filteredRows(described)}`,\n ...withParameters(described, key.parameters),\n language: 'pouchdb',\n note: noteWith('an indexed view query', described),\n };\n};\n\nexport const remoteScanQuery = (described: DescribedFilters): ExecutedQuery => ({\n text: `db.allDocs({ include_docs: true })${filteredRows(described)}`,\n ...withParameters(described),\n language: 'pouchdb',\n note: noteWith('a full read of a remote database, filtered in JavaScript', described),\n});\n\nexport const temporaryViewQuery = (described: DescribedFilters): ExecutedQuery => ({\n text: `db.query((doc, emit) => {\\n if (${described.text}) emit(doc._id, doc);\\n})`,\n ...withParameters(described),\n language: 'pouchdb',\n note: noteWith('a temporary view: PouchDB runs the map function over every document', described),\n});\n","import PouchDB from 'pouchdb';\nimport { PouchDbTranslator } from './PouchDbTranslator';\nimport { fullReadQuery, indexedViewQuery, remoteScanQuery, temporaryViewQuery } from './explainQuery';\nimport { SyncronousQueue, SyncronousUnitOfWork, WorkPipeline } from '@routier/core/pipeline';\nimport { InferCreateType, InferType, PropertyInfo, SchemaId } from '@routier/core/schema';\nimport { DbPluginBulkPersistEvent, DbPluginEvent, DbPluginQueryEvent, describeFilters, type DescribedFilters, 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\n\nconst filtersOf = <TEntity extends {}, TShape>(event: DbPluginQueryEvent<TEntity, TShape>): DescribedFilters =>\n describeFilters(event.operation.options.get(\"filter\").map(item => item.option.value), \"doc\");\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(indexedViewQuery(`${INDEX_NAME}/${matchingIndex.viewName}`, options, filtersOf(event)));\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(fullReadQuery());\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(remoteScanQuery(filtersOf(event)));\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(temporaryViewQuery(filtersOf(event)));\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}","import type { EtagComparator } from '@routier/core/schema';\n\nexport const pouchRevision: EtagComparator<string> = (prev, next) => {\n const prevGeneration = Number(prev.slice(0, prev.indexOf('-')));\n const nextGeneration = Number(next.slice(0, next.indexOf('-')));\n\n if (prevGeneration !== nextGeneration) {\n return Math.sign(prevGeneration - nextGeneration);\n }\n\n return prev < next ? -1 : prev > next ? 1 : 0;\n};\n","export { PouchDbPlugin } from './PouchDbPlugin';\nexport { pouchRevision } from './pouchRevision';\n"],"names":["assertIsArray","JsonTranslator","getStorageDateReviver","PouchDbTranslator","query","item","filterChain","filters","databaseFilters","x","index","currentFilter","nextFilter","filter","selector","params","data","documents","i","length","document","withParameters","described","before","parameters","viewKey","options","filteredRows","noteWith","note","fullReadQuery","indexedViewQuery","view","key","JSON","remoteScanQuery","temporaryViewQuery","PouchDB","SyncronousQueue","WorkPipeline","describeFilters","joinInPlugin","reportRenamedProperties","PluginEventResult","Result","assertIsNotNull","combineExpressions","Expression","getProperties","INDEX_NAME","filtersOf","event","PouchDbPlugin","_sync","_queryType","rest","name","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","indexes","ddoc","path","matchingIndex","views","Object","schema","defaultSchemaIds","identityResult","defaultResult","work","shouldClose","_event","unitOfWork","settle","cb","_","__","expression","prop","left","right","queryProperties","property","value","translator","values","translated","emit","mapMatchingIndex","expressions","map","pouchRevision","prev","next","prevGeneration","Number","nextGeneration","Math"],"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,IAA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AE;;;ACX8C;AACA"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@routier/pouchdb-plugin",
|
|
3
|
-
"version": "0.5.
|
|
3
|
+
"version": "0.5.3",
|
|
4
4
|
"main": "./dist/index.cjs",
|
|
5
5
|
"types": "./dist/index.d.ts",
|
|
6
6
|
"source": "./src/index.ts",
|
|
@@ -46,13 +46,13 @@
|
|
|
46
46
|
"events": "^3.3.0"
|
|
47
47
|
},
|
|
48
48
|
"peerDependencies": {
|
|
49
|
-
"@routier/core": ">=0.
|
|
49
|
+
"@routier/core": ">=0.10.0",
|
|
50
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.
|
|
54
|
+
"@routier/core": "^0.10.0",
|
|
55
|
+
"@routier/datastore": "^0.5.0",
|
|
56
56
|
"@routier/memory-plugin": "file:../memory",
|
|
57
57
|
"@routier/test-utils": "^0.3.0",
|
|
58
58
|
"@rspack/cli": "^1.1.8",
|