rxdb-server 15.7.0 → 15.13.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +4 -0
- package/dist/cjs/index.js.map +1 -1
- package/dist/cjs/plugins/adapter-express/index.js +122 -0
- package/dist/cjs/plugins/adapter-express/index.js.map +1 -0
- package/dist/cjs/plugins/client-rest/index.js.map +1 -1
- package/dist/cjs/plugins/client-rest/utils.js.map +1 -1
- package/dist/cjs/plugins/replication-server/helpers.js.map +1 -1
- package/dist/cjs/plugins/replication-server/index.js +1 -1
- package/dist/cjs/plugins/replication-server/index.js.map +1 -1
- package/dist/cjs/plugins/replication-server/types.js.map +1 -1
- package/dist/cjs/plugins/server/endpoint-replication.js +22 -20
- package/dist/cjs/plugins/server/endpoint-replication.js.map +1 -1
- package/dist/cjs/plugins/server/endpoint-rest.js +33 -31
- package/dist/cjs/plugins/server/endpoint-rest.js.map +1 -1
- package/dist/cjs/plugins/server/helper.js +6 -45
- package/dist/cjs/plugins/server/helper.js.map +1 -1
- package/dist/cjs/plugins/server/index.js +5 -15
- package/dist/cjs/plugins/server/index.js.map +1 -1
- package/dist/cjs/plugins/server/rx-server.js +25 -22
- package/dist/cjs/plugins/server/rx-server.js.map +1 -1
- package/dist/cjs/plugins/server/types.js.map +1 -1
- package/dist/esm/index.js.map +1 -1
- package/dist/esm/plugins/adapter-express/index.js +115 -0
- package/dist/esm/plugins/adapter-express/index.js.map +1 -0
- package/dist/esm/plugins/client-rest/index.js.map +1 -1
- package/dist/esm/plugins/client-rest/utils.js.map +1 -1
- package/dist/esm/plugins/replication-server/helpers.js.map +1 -1
- package/dist/esm/plugins/replication-server/index.js +1 -1
- package/dist/esm/plugins/replication-server/index.js.map +1 -1
- package/dist/esm/plugins/replication-server/types.js.map +1 -1
- package/dist/esm/plugins/server/endpoint-replication.js +23 -21
- package/dist/esm/plugins/server/endpoint-replication.js.map +1 -1
- package/dist/esm/plugins/server/endpoint-rest.js +34 -32
- package/dist/esm/plugins/server/endpoint-rest.js.map +1 -1
- package/dist/esm/plugins/server/helper.js +6 -42
- package/dist/esm/plugins/server/helper.js.map +1 -1
- package/dist/esm/plugins/server/index.js +3 -12
- package/dist/esm/plugins/server/index.js.map +1 -1
- package/dist/esm/plugins/server/rx-server.js +25 -22
- package/dist/esm/plugins/server/rx-server.js.map +1 -1
- package/dist/esm/plugins/server/types.js.map +1 -1
- package/dist/types/plugins/adapter-express/index.d.ts +7 -0
- package/dist/types/plugins/server/endpoint-replication.d.ts +3 -3
- package/dist/types/plugins/server/endpoint-rest.d.ts +3 -3
- package/dist/types/plugins/server/helper.d.ts +6 -8
- package/dist/types/plugins/server/index.d.ts +1 -1
- package/dist/types/plugins/server/rx-server.d.ts +12 -11
- package/dist/types/plugins/server/types.d.ts +26 -3
- package/package.json +33 -27
- package/plugins/adapter-express/index.cjs +2 -0
- package/plugins/adapter-express/index.d.cts +1 -0
- package/plugins/adapter-express/index.d.mts +1 -0
- package/plugins/adapter-express/index.mjs +1 -0
- package/plugins/adapter-express/index.ts +1 -0
- package/plugins/adapter-express/package.json +18 -0
package/README.md
CHANGED
|
@@ -5,3 +5,7 @@ This is the repository for the [RxDB Server plugins](https://rxdb.info/rx-server
|
|
|
5
5
|
The code of the server plugins is in a different repository because:
|
|
6
6
|
- It has too many dependencies that you do not want to install if you only use RxDB at the client side.
|
|
7
7
|
- It has a different license [(SSPL)](https://en.wikipedia.org/wiki/Server_Side_Public_License) to prevent large cloud vendors from "stealing" the revenue. [Similar to MongoDB](https://www.mongodb.com/legal/licensing/server-side-public-license/faq)
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
## Issues
|
|
11
|
+
The issue section of this repository is closed. Please make issues directly at the [RxDB Repo](https://github.com/pubkey/rxdb/issues).
|
package/dist/cjs/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":["wrongImport","Error"],"sources":["../../src/index.ts"],"sourcesContent":["export function wrongImport() {\n throw new Error('You should never import this file, only the server plugins');\n}\n"],"mappings":";;;;;;AAAO,SAASA,WAAWA,CAAA,EAAG;EAC1B,MAAM,IAAIC,KAAK,CAAC,4DAA4D,CAAC;AACjF"}
|
|
1
|
+
{"version":3,"file":"index.js","names":["wrongImport","Error"],"sources":["../../src/index.ts"],"sourcesContent":["export function wrongImport() {\n throw new Error('You should never import this file, only the server plugins');\n}\n"],"mappings":";;;;;;AAAO,SAASA,WAAWA,CAAA,EAAG;EAC1B,MAAM,IAAIC,KAAK,CAAC,4DAA4D,CAAC;AACjF","ignoreList":[]}
|
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
|
|
3
|
+
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
|
|
4
|
+
Object.defineProperty(exports, "__esModule", {
|
|
5
|
+
value: true
|
|
6
|
+
});
|
|
7
|
+
exports.RxServerAdapterExpress = exports.HTTP_SERVER_BY_EXPRESS = void 0;
|
|
8
|
+
var _express = _interopRequireDefault(require("express"));
|
|
9
|
+
var _cors = _interopRequireDefault(require("cors"));
|
|
10
|
+
var _core = require("rxdb/plugins/core");
|
|
11
|
+
var HTTP_SERVER_BY_EXPRESS = exports.HTTP_SERVER_BY_EXPRESS = new WeakMap();
|
|
12
|
+
var RxServerAdapterExpress = exports.RxServerAdapterExpress = {
|
|
13
|
+
async create() {
|
|
14
|
+
var app = (0, _express.default)();
|
|
15
|
+
app.use(_express.default.json());
|
|
16
|
+
return app;
|
|
17
|
+
},
|
|
18
|
+
setCors(serverApp, path, cors) {
|
|
19
|
+
serverApp.options('/' + path + '/*', (0, _cors.default)({
|
|
20
|
+
origin: cors,
|
|
21
|
+
// some legacy browsers (IE11, various SmartTVs) choke on 204
|
|
22
|
+
optionsSuccessStatus: 200
|
|
23
|
+
}));
|
|
24
|
+
},
|
|
25
|
+
getRequestBody(req) {
|
|
26
|
+
return req.body;
|
|
27
|
+
},
|
|
28
|
+
getRequestHeaders(req) {
|
|
29
|
+
return req.headers;
|
|
30
|
+
},
|
|
31
|
+
getRequestQuery(req) {
|
|
32
|
+
return req.query;
|
|
33
|
+
},
|
|
34
|
+
onRequestClose(req, fn) {
|
|
35
|
+
req.on('close', () => {
|
|
36
|
+
fn();
|
|
37
|
+
});
|
|
38
|
+
},
|
|
39
|
+
setResponseHeader(res, k, v) {
|
|
40
|
+
res.setHeader(k, v);
|
|
41
|
+
},
|
|
42
|
+
responseWrite(res, data) {
|
|
43
|
+
res.write(data);
|
|
44
|
+
},
|
|
45
|
+
endResponseJson(res, data) {
|
|
46
|
+
res.json(data);
|
|
47
|
+
},
|
|
48
|
+
endResponse(res) {
|
|
49
|
+
res.end();
|
|
50
|
+
},
|
|
51
|
+
async closeConnection(response, code, message) {
|
|
52
|
+
var responseWrite = {
|
|
53
|
+
code,
|
|
54
|
+
error: true,
|
|
55
|
+
message
|
|
56
|
+
};
|
|
57
|
+
response.statusCode = code;
|
|
58
|
+
response.set("Connection", "close");
|
|
59
|
+
await response.write(JSON.stringify(responseWrite));
|
|
60
|
+
response.end();
|
|
61
|
+
},
|
|
62
|
+
setSSEHeaders(res) {
|
|
63
|
+
res.writeHead(200, {
|
|
64
|
+
/**
|
|
65
|
+
* Use exact these headers to make is less likely
|
|
66
|
+
* for people to have problems.
|
|
67
|
+
* @link https://www.youtube.com/watch?v=0PcMuYGJPzM
|
|
68
|
+
*/
|
|
69
|
+
'Content-Type': 'text/event-stream; charset=utf-8',
|
|
70
|
+
'Connection': 'keep-alive',
|
|
71
|
+
'Cache-Control': 'no-cache',
|
|
72
|
+
/**
|
|
73
|
+
* Required for nginx
|
|
74
|
+
* @link https://stackoverflow.com/q/61029079/3443137
|
|
75
|
+
*/
|
|
76
|
+
'X-Accel-Buffering': 'no'
|
|
77
|
+
});
|
|
78
|
+
res.flushHeaders();
|
|
79
|
+
},
|
|
80
|
+
get(serverApp, path, handler) {
|
|
81
|
+
serverApp.get(path, handler);
|
|
82
|
+
},
|
|
83
|
+
post(serverApp, path, handler) {
|
|
84
|
+
serverApp.post(path, handler);
|
|
85
|
+
},
|
|
86
|
+
all(serverApp, path, handler) {
|
|
87
|
+
serverApp.all(path, handler);
|
|
88
|
+
},
|
|
89
|
+
async listen(serverApp, port, hostname) {
|
|
90
|
+
var httpServer = await new Promise((res, rej) => {
|
|
91
|
+
var ret = (0, _core.ensureNotFalsy)(serverApp).listen(port, hostname, () => {
|
|
92
|
+
res(ret);
|
|
93
|
+
});
|
|
94
|
+
});
|
|
95
|
+
HTTP_SERVER_BY_EXPRESS.set(serverApp, httpServer);
|
|
96
|
+
},
|
|
97
|
+
async close(serverApp) {
|
|
98
|
+
var httpServer = (0, _core.getFromMapOrThrow)(HTTP_SERVER_BY_EXPRESS, serverApp);
|
|
99
|
+
await new Promise((res, rej) => {
|
|
100
|
+
httpServer.close(err => {
|
|
101
|
+
if (err) {
|
|
102
|
+
rej(err);
|
|
103
|
+
} else {
|
|
104
|
+
res();
|
|
105
|
+
}
|
|
106
|
+
});
|
|
107
|
+
/**
|
|
108
|
+
* By default it will await all ongoing connections
|
|
109
|
+
* before it closes. So we have to close it directly.
|
|
110
|
+
* @link https://stackoverflow.com/a/36830072/3443137
|
|
111
|
+
*/
|
|
112
|
+
setImmediate(() => httpServer.emit('close'));
|
|
113
|
+
});
|
|
114
|
+
},
|
|
115
|
+
async closeAllConnections(serverApp) {
|
|
116
|
+
var httpServer = HTTP_SERVER_BY_EXPRESS.get(serverApp);
|
|
117
|
+
if (httpServer) {
|
|
118
|
+
await httpServer.closeAllConnections();
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
};
|
|
122
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","names":["_express","_interopRequireDefault","require","_cors","_core","HTTP_SERVER_BY_EXPRESS","exports","WeakMap","RxServerAdapterExpress","create","app","express","use","json","setCors","serverApp","path","cors","options","expressCors","origin","optionsSuccessStatus","getRequestBody","req","body","getRequestHeaders","headers","getRequestQuery","query","onRequestClose","fn","on","setResponseHeader","res","k","v","setHeader","responseWrite","data","write","endResponseJson","endResponse","end","closeConnection","response","code","message","error","statusCode","set","JSON","stringify","setSSEHeaders","writeHead","flushHeaders","get","handler","post","all","listen","port","hostname","httpServer","Promise","rej","ret","ensureNotFalsy","close","getFromMapOrThrow","err","setImmediate","emit","closeAllConnections"],"sources":["../../../../src/plugins/adapter-express/index.ts"],"sourcesContent":["import type { RxServerAdapter } from '../server/types';\nimport type { Express } from 'express';\nimport express, { Request, Response } from 'express';\nimport {\n Server as HttpServer\n} from 'http';\nimport expressCors from 'cors';\nimport { ensureNotFalsy, getFromMapOrThrow } from 'rxdb/plugins/core';\n\nexport const HTTP_SERVER_BY_EXPRESS = new WeakMap<Express, HttpServer>();\n\nexport const RxServerAdapterExpress: RxServerAdapter<Express, Request, Response> = {\n async create() {\n const app = express();\n app.use(express.json());\n return app;\n },\n setCors(serverApp, path, cors) {\n serverApp.options('/' + path + '/*', expressCors({\n origin: cors,\n // some legacy browsers (IE11, various SmartTVs) choke on 204\n optionsSuccessStatus: 200\n }));\n },\n\n getRequestBody(req: Request) {\n return req.body;\n },\n getRequestHeaders(req: Request) {\n return req.headers as any;\n },\n getRequestQuery(req: Request) {\n return req.query;\n },\n onRequestClose(req: Request, fn) {\n req.on('close', () => {\n fn();\n });\n },\n\n setResponseHeader(res: Response, k: string, v: string) {\n res.setHeader(k, v);\n },\n responseWrite(res: Response, data: string) {\n res.write(data);\n },\n endResponseJson(res: Response, data: any) {\n res.json(data);\n },\n endResponse(res: Response) {\n res.end();\n },\n async closeConnection(response: Response, code: number, message: string) {\n const responseWrite = {\n code,\n error: true,\n message\n };\n response.statusCode = code;\n response.set(\"Connection\", \"close\");\n await response.write(JSON.stringify(responseWrite));\n response.end();\n },\n setSSEHeaders(res: Response) {\n res.writeHead(200, {\n /**\n * Use exact these headers to make is less likely\n * for people to have problems.\n * @link https://www.youtube.com/watch?v=0PcMuYGJPzM\n */\n 'Content-Type': 'text/event-stream; charset=utf-8',\n 'Connection': 'keep-alive',\n 'Cache-Control': 'no-cache',\n /**\n * Required for nginx\n * @link https://stackoverflow.com/q/61029079/3443137\n */\n 'X-Accel-Buffering': 'no'\n });\n res.flushHeaders();\n },\n\n get(serverApp, path, handler) {\n serverApp.get(path, handler);\n },\n post(serverApp, path, handler) {\n serverApp.post(path, handler);\n },\n all(serverApp, path, handler) {\n serverApp.all(path, handler);\n },\n async listen(serverApp, port, hostname) {\n const httpServer: HttpServer = await new Promise((res, rej) => {\n const ret = ensureNotFalsy(serverApp).listen(port, hostname, () => {\n res(ret);\n });\n });\n HTTP_SERVER_BY_EXPRESS.set(serverApp, httpServer);\n },\n async close(serverApp) {\n const httpServer = getFromMapOrThrow(HTTP_SERVER_BY_EXPRESS, serverApp);\n await new Promise<void>((res, rej) => {\n httpServer.close((err) => {\n if (err) { rej(err); } else { res(); }\n });\n /**\n * By default it will await all ongoing connections\n * before it closes. So we have to close it directly.\n * @link https://stackoverflow.com/a/36830072/3443137\n */\n setImmediate(() => httpServer.emit('close'));\n });\n },\n async closeAllConnections(serverApp) {\n const httpServer = HTTP_SERVER_BY_EXPRESS.get(serverApp);\n if (httpServer) {\n await httpServer.closeAllConnections();\n }\n }\n};\n"],"mappings":";;;;;;;AAEA,IAAAA,QAAA,GAAAC,sBAAA,CAAAC,OAAA;AAIA,IAAAC,KAAA,GAAAF,sBAAA,CAAAC,OAAA;AACA,IAAAE,KAAA,GAAAF,OAAA;AAEO,IAAMG,sBAAsB,GAAAC,OAAA,CAAAD,sBAAA,GAAG,IAAIE,OAAO,CAAsB,CAAC;AAEjE,IAAMC,sBAAmE,GAAAF,OAAA,CAAAE,sBAAA,GAAG;EAC/E,MAAMC,MAAMA,CAAA,EAAG;IACX,IAAMC,GAAG,GAAG,IAAAC,gBAAO,EAAC,CAAC;IACrBD,GAAG,CAACE,GAAG,CAACD,gBAAO,CAACE,IAAI,CAAC,CAAC,CAAC;IACvB,OAAOH,GAA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AsB,CAAC4C,GAAG,CAAClC,SAAS,EAAE+C,UAAU,CAAC;EACrD,CAAC;EACD,MAAMK,KAAKA,CAACpD,SAAS,EAAE;IACnB,IAAM+C,UAAU,GAAG,IAAAM,uBAAiB,EAAC/D,sBAAsB,EAAEU,SAAS,CAAC;IACvE,MAAM,IAAIgD,OAAO,CAAO,CAAC9B,GAAG,EAAE+B,GAAG,KAAK;MAClCF,UAAU,CAACK,KAAK,CAAEE,GAAG,IAAK;QACtB,IAAIA,GAAG,EAAE;UAAEL,GAAG,CAACK,GAAG,CAAC;QAAE,CAAC,MAAM;UAAEpC,GAAG,CAAC,CAAC;QAAE;MACzC,CAAC,CAAC;MACF;AACZ;AACA;AACA;AACA;MACYqC,YAAY,CAAC,MAAMR,UAAU,CAACS,IAAI,CAAC,OAAO,CAAC,CAAC;IAChD,CAAC,CAAC;EACN,CAAC;EACD,MAAMC,mBAAmBA,CAACzD,SAAS,EAAE;IACjC,IAAM+C,UAAU,GAAGzD,sBAAsB,CAACkD,GAAG,CAACxC,SAAS,CAAC;IACxD,IAAI+C,UAAU,EAAE;MACZ,MAAMA,UAAU,CAACU,mBAAmB,CAAC,CAAC;IAC1C;EACJ;AACJ,CAAC","ignoreList":[]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":["_utils","require","Object","keys","forEach","key","prototype","hasOwnProperty","call","_exportNames","exports","defineProperty","enumerable","get","_rxjs","_eventsource","_interopRequireDefault","RxRestClient","endpointUrl","headers","eventSource","EventSource","_proto","setHeaders","handleError","response","error","Error","JSON","stringify","query","postRequest","observeQuery","result","Subject","queryAsBase64","btoa","withCredentials","onmessage","event","eventData","parse","data","next","asObservable","ids","set","docs","delete","_delete","createRestClient"],"sources":["../../../../src/plugins/client-rest/index.ts"],"sourcesContent":["import { ById, MangoQuery, newRxError } from 'rxdb/plugins/core';\nimport { postRequest } from './utils.ts';\nimport { Observable, Subject } from 'rxjs';\nimport EventSource from 'eventsource';\n\nexport class RxRestClient<RxDocType> {\n constructor(\n public readonly endpointUrl: string,\n public headers: ById<string> = {},\n public readonly eventSource: typeof EventSource | any = EventSource\n ) { }\n\n setHeaders(headers: ById<string>) {\n this.headers = headers;\n }\n\n handleError(response: any) {\n if (response.error) {\n throw new Error('Server returned an error ' + JSON.stringify(response));\n }\n }\n\n async query(query: MangoQuery<RxDocType>): Promise<{ documents: RxDocType[] }> {\n const response = await postRequest(\n this.endpointUrl + '/query',\n query,\n this.headers\n );\n this.handleError(response);\n return response;\n }\n\n observeQuery(query: MangoQuery<RxDocType>): Observable<RxDocType[]> {\n const result = new Subject<RxDocType[]>;\n const queryAsBase64 = btoa(JSON.stringify(query));\n const eventSource: EventSource = new this.eventSource(\n this.endpointUrl + '/query/observe?query=' + queryAsBase64,\n {\n withCredentials: true,\n /**\n * Sending headers is not supported by the Browser EventSource API,\n * only by the npm module we use. In react-native you might have\n * to set another EventSource implementation.\n * @link https://www.npmjs.com/package/eventsource\n */\n headers: this.headers\n });\n eventSource.onmessage = event => {\n const eventData = JSON.parse(event.data);\n result.next(eventData);\n };\n return result.asObservable();\n }\n\n get(ids: string[]): Promise<{ documents: RxDocType[] }> {\n const response = postRequest(\n this.endpointUrl + '/get',\n ids,\n this.headers\n );\n this.handleError(response);\n return response;\n }\n\n set(docs: RxDocType[]) {\n const response = postRequest(\n this.endpointUrl + '/set',\n docs,\n this.headers\n );\n this.handleError(response);\n return response;\n }\n\n delete(ids: string[]) {\n const response = postRequest(\n this.endpointUrl + '/delete',\n ids,\n this.headers\n );\n this.handleError(response);\n return response;\n }\n}\n\nexport function createRestClient<RxDocType>(\n endpointUrl: string,\n headers: ById<string>,\n eventSource: typeof EventSource | any = EventSource\n) {\n\n return new RxRestClient<RxDocType>(\n endpointUrl,\n headers,\n eventSource\n );\n}\n\n\nexport * from './utils.ts';\n"],"mappings":";;;;;;;;;;;;AACA,IAAAA,MAAA,GAAAC,OAAA;AAkGAC,MAAA,CAAAC,IAAA,CAAAH,MAAA,EAAAI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,CAAC;IAC1B,OAAOA,QAAQ;EACnB,CAAC;EAAAH,MAAA,CAED0B,MAAM,GAAN,SAAAC,QAAOJ,GAAa,EAAE;IAClB,IAAMpB,QAAQ,GAAG,IAAAM,kBAAW,EACxB,IAAI,CAACb,WAAW,GAAG,SAAS,EAC5B2B,GAAG,EACH,IAAI,CAAC1B,OACT,CAAC;IACD,IAAI,CAACK,WAAW,CAACC,QAAQ,CAAC;IAC1B,OAAOA,QAAQ;EACnB,CAAC;EAAA,OAAAR,YAAA;AAAA;AAGE,SAASiC,gBAAgBA,CAC5BhC,WAAmB,EACnBC,OAAqB,EACrBC,WAAqC,GAAGC,oBAAW,EACrD;EAEE,OAAO,IAAIJ,YAAY,CACnBC,WAAW,EACXC,OAAO,EACPC,WACJ,CAAC;AACL"}
|
|
1
|
+
{"version":3,"file":"index.js","names":["_utils","require","Object","keys","forEach","key","prototype","hasOwnProperty","call","_exportNames","exports","defineProperty","enumerable","get","_rxjs","_eventsource","_interopRequireDefault","RxRestClient","endpointUrl","headers","eventSource","EventSource","_proto","setHeaders","handleError","response","error","Error","JSON","stringify","query","postRequest","observeQuery","result","Subject","queryAsBase64","btoa","withCredentials","onmessage","event","eventData","parse","data","next","asObservable","ids","set","docs","delete","_delete","createRestClient"],"sources":["../../../../src/plugins/client-rest/index.ts"],"sourcesContent":["import { ById, MangoQuery, newRxError } from 'rxdb/plugins/core';\nimport { postRequest } from './utils.ts';\nimport { Observable, Subject } from 'rxjs';\nimport EventSource from 'eventsource';\n\nexport class RxRestClient<RxDocType> {\n constructor(\n public readonly endpointUrl: string,\n public headers: ById<string> = {},\n public readonly eventSource: typeof EventSource | any = EventSource\n ) { }\n\n setHeaders(headers: ById<string>) {\n this.headers = headers;\n }\n\n handleError(response: any) {\n if (response.error) {\n throw new Error('Server returned an error ' + JSON.stringify(response));\n }\n }\n\n async query(query: MangoQuery<RxDocType>): Promise<{ documents: RxDocType[] }> {\n const response = await postRequest(\n this.endpointUrl + '/query',\n query,\n this.headers\n );\n this.handleError(response);\n return response;\n }\n\n observeQuery(query: MangoQuery<RxDocType>): Observable<RxDocType[]> {\n const result = new Subject<RxDocType[]>;\n const queryAsBase64 = btoa(JSON.stringify(query));\n const eventSource: EventSource = new this.eventSource(\n this.endpointUrl + '/query/observe?query=' + queryAsBase64,\n {\n withCredentials: true,\n /**\n * Sending headers is not supported by the Browser EventSource API,\n * only by the npm module we use. In react-native you might have\n * to set another EventSource implementation.\n * @link https://www.npmjs.com/package/eventsource\n */\n headers: this.headers\n });\n eventSource.onmessage = event => {\n const eventData = JSON.parse(event.data);\n result.next(eventData);\n };\n return result.asObservable();\n }\n\n get(ids: string[]): Promise<{ documents: RxDocType[] }> {\n const response = postRequest(\n this.endpointUrl + '/get',\n ids,\n this.headers\n );\n this.handleError(response);\n return response;\n }\n\n set(docs: RxDocType[]) {\n const response = postRequest(\n this.endpointUrl + '/set',\n docs,\n this.headers\n );\n this.handleError(response);\n return response;\n }\n\n delete(ids: string[]) {\n const response = postRequest(\n this.endpointUrl + '/delete',\n ids,\n this.headers\n );\n this.handleError(response);\n return response;\n }\n}\n\nexport function createRestClient<RxDocType>(\n endpointUrl: string,\n headers: ById<string>,\n eventSource: typeof EventSource | any = EventSource\n) {\n\n return new RxRestClient<RxDocType>(\n endpointUrl,\n headers,\n eventSource\n );\n}\n\n\nexport * from './utils.ts';\n"],"mappings":";;;;;;;;;;;;AACA,IAAAA,MAAA,GAAAC,OAAA;AAkGAC,MAAA,CAAAC,IAAA,CAAAH,MAAA,EAAAI,OAAA,WAAAC,GAAA;EAAA,IAAAA,GAAA,kBAAAA,GAAA;EAAA,IAAAH,MAAA,CAAAI,SAAA,CAAAC,cAAA,CAAAC,IAAA,CAAAC,YAAA,EAAAJ,GAAA;EAAA,IAAAA,GAAA,IAAAK,OAAA,IAAAA,OAAA,CAAAL,GAAA,MAAAL,MAAA,CAAAK,GAAA;EAAAH,MAAA,CAAAS,cAAA,CAAAD,OAAA,EAAAL,GAAA;IAAAO,UAAA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nB,CAAC;EAAA,OAAAR,YAAA;AAAA;AAGE,SAASiC,gBAAgBA,CAC5BhC,WAAmB,EACnBC,OAAqB,EACrBC,WAAqC,GAAGC,oBAAW,EACrD;EAEE,OAAO,IAAIJ,YAAY,CACnBC,WAAW,EACXC,OAAO,EACPC,WACJ,CAAC;AACL","ignoreList":[]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"utils.js","names":["postRequest","url","body","headers","request","fetch","method","Object","assign","JSON","stringify","response","json"],"sources":["../../../../src/plugins/client-rest/utils.ts"],"sourcesContent":["import { ById } from 'rxdb/plugins/core';\n\nexport async function postRequest(\n url: string,\n body: any,\n headers: ById<string> = {},\n) {\n const request = await fetch(url, {\n method: 'POST',\n headers: Object.assign({\n 'Accept': 'application/json',\n 'Content-Type': 'application/json'\n }, headers),\n body: JSON.stringify(body)\n });\n const response = await request.json();\n return response;\n}\n"],"mappings":";;;;;;AAEO,eAAeA,WAAWA,CAC7BC,GAAW,EACXC,IAAS,EACTC,OAAqB,GAAG,CAAC,CAAC,EAC5B;EACE,IAAMC,OAAO,GAAG,MAAMC,KAAK,CAACJ,GAAG,EAAE;IAC7BK,MAAM,EAAE,MAAM;IACdH,OAAO,EAAEI,MAAM,CAACC,MAAM,CAAC;MACnB,QAAQ,EAAE,kBAAkB;MAC5B,cAAc,EAAE;IACpB,CAAC,EAAEL,OAAO,CAAC;IACXD,IAAI,EAAEO,IAAI,CAACC,SAAS,CAACR,IAAI;EAC7B,CAAC,CAAC;EACF,IAAMS,QAAQ,GAAG,MAAMP,OAAO,CAACQ,IAAI,CAAC,CAAC;EACrC,OAAOD,QAAQ;AACnB"}
|
|
1
|
+
{"version":3,"file":"utils.js","names":["postRequest","url","body","headers","request","fetch","method","Object","assign","JSON","stringify","response","json"],"sources":["../../../../src/plugins/client-rest/utils.ts"],"sourcesContent":["import { ById } from 'rxdb/plugins/core';\n\nexport async function postRequest(\n url: string,\n body: any,\n headers: ById<string> = {},\n) {\n const request = await fetch(url, {\n method: 'POST',\n headers: Object.assign({\n 'Accept': 'application/json',\n 'Content-Type': 'application/json'\n }, headers),\n body: JSON.stringify(body)\n });\n const response = await request.json();\n return response;\n}\n"],"mappings":";;;;;;AAEO,eAAeA,WAAWA,CAC7BC,GAAW,EACXC,IAAS,EACTC,OAAqB,GAAG,CAAC,CAAC,EAC5B;EACE,IAAMC,OAAO,GAAG,MAAMC,KAAK,CAACJ,GAAG,EAAE;IAC7BK,MAAM,EAAE,MAAM;IACdH,OAAO,EAAEI,MAAM,CAACC,MAAM,CAAC;MACnB,QAAQ,EAAE,kBAAkB;MAC5B,cAAc,EAAE;IACpB,CAAC,EAAEL,OAAO,CAAC;IACXD,IAAI,EAAEO,IAAI,CAACC,SAAS,CAACR,IAAI;EAC7B,CAAC,CAAC;EACF,IAAMS,QAAQ,GAAG,MAAMP,OAAO,CAACQ,IAAI,CAAC,CAAC;EACrC,OAAOD,QAAQ;AACnB","ignoreList":[]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"helpers.js","names":["_core","require","parseResponse","replicationState","fetchResponse","status","outdatedClient$","next","nextTick","then","cancel","newRxError","url","unauthorized$","forbidden$","data","json","error","console","log","dir"],"sources":["../../../../src/plugins/replication-server/helpers.ts"],"sourcesContent":["import { newRxError, nextTick } from 'rxdb/plugins/core';\nimport type { RxServerReplicationState } from './index.ts';\n\nexport async function parseResponse(\n replicationState: RxServerReplicationState<any>,\n fetchResponse: Response\n) {\n if (fetchResponse.status === 426) {\n replicationState.outdatedClient$.next();\n nextTick().then(() => replicationState.cancel());\n throw newRxError('RC_OUTDATED', {\n url: fetchResponse.url\n });\n }\n if (fetchResponse.status === 401) {\n replicationState.unauthorized$.next();\n throw newRxError('RC_UNAUTHORIZED', {\n url: fetchResponse.url\n });\n }\n if (fetchResponse.status === 403) {\n replicationState.forbidden$.next();\n nextTick().then(() => replicationState.cancel());\n throw newRxError('RC_FORBIDDEN', {\n url: fetchResponse.url\n });\n }\n const data = await fetchResponse.json();\n\n if (data.error) {\n // TODO\n console.log('TODO handle parseResponse error');\n console.dir(data);\n throw data;\n }\n\n return data;\n}\n"],"mappings":";;;;;;AAAA,IAAAA,KAAA,GAAAC,OAAA;AAGO,eAAeC,aAAaA,CAC/BC,gBAA+C,EAC/CC,aAAuB,EACzB;EACE,IAAIA,aAAa,CAACC,MAAM,KAAK,GAAG,EAAE;IAC9BF,gBAAgB,CAACG,eAAe,CAACC,IAAI,CAAC,CAAC;IACvC,IAAAC,cAAQ,EAAC,CAAC,CAACC,IAAI,CAAC,MAAMN,gBAAgB,CAACO,MAAM,CAAC,CAAC,CAAC;IAChD,MAAM,IAAAC,gBAAU,EAAC,aAAa,EAAE;MAC5BC,GAAG,EAAER,aAAa,CAACQ;IACvB,CAAC,CAAC;EACN;EACA,IAAIR,aAAa,CAACC,MAAM,KAAK,GAAG,EAAE;IAC9BF,gBAAgB,CAACU,aAAa,CAACN,IAAI,CAAC,CAAC;IACrC,MAAM,IAAAI,gBAAU,EAAC,iBAAiB,EAAE;MAChCC,GAAG,EAAER,aAAa,CAACQ;IACvB,CAAC,CAAC;EACN;EACA,IAAIR,aAAa,CAACC,MAAM,KAAK,GAAG,EAAE;IAC9BF,gBAAgB,CAACW,UAAU,CAACP,IAAI,CAAC,CAAC;IAClC,IAAAC,cAAQ,EAAC,CAAC,CAACC,IAAI,CAAC,MAAMN,gBAAgB,CAACO,MAAM,CAAC,CAAC,CAAC;IAChD,MAAM,IAAAC,gBAAU,EAAC,cAAc,EAAE;MAC7BC,GAAG,EAAER,aAAa,CAACQ;IACvB,CAAC,CAAC;EACN;EACA,IAAMG,IAAI,GAAG,MAAMX,aAAa,CAACY,IAAI,CAAC,CAAC;EAEvC,IAAID,IAAI,CAACE,KAAK,EAAE;IACZ;IACAC,OAAO,CAACC,GAAG,CAAC,iCAAiC,CAAC;IAC9CD,OAAO,CAACE,GAAG,CAACL,IAAI,CAAC;IACjB,MAAMA,IAAI;EACd;EAEA,OAAOA,IAAI;AACf"}
|
|
1
|
+
{"version":3,"file":"helpers.js","names":["_core","require","parseResponse","replicationState","fetchResponse","status","outdatedClient$","next","nextTick","then","cancel","newRxError","url","unauthorized$","forbidden$","data","json","error","console","log","dir"],"sources":["../../../../src/plugins/replication-server/helpers.ts"],"sourcesContent":["import { newRxError, nextTick } from 'rxdb/plugins/core';\nimport type { RxServerReplicationState } from './index.ts';\n\nexport async function parseResponse(\n replicationState: RxServerReplicationState<any>,\n fetchResponse: Response\n) {\n if (fetchResponse.status === 426) {\n replicationState.outdatedClient$.next();\n nextTick().then(() => replicationState.cancel());\n throw newRxError('RC_OUTDATED', {\n url: fetchResponse.url\n });\n }\n if (fetchResponse.status === 401) {\n replicationState.unauthorized$.next();\n throw newRxError('RC_UNAUTHORIZED', {\n url: fetchResponse.url\n });\n }\n if (fetchResponse.status === 403) {\n replicationState.forbidden$.next();\n nextTick().then(() => replicationState.cancel());\n throw newRxError('RC_FORBIDDEN', {\n url: fetchResponse.url\n });\n }\n const data = await fetchResponse.json();\n\n if (data.error) {\n // TODO\n console.log('TODO handle parseResponse error');\n console.dir(data);\n throw data;\n }\n\n return data;\n}\n"],"mappings":";;;;;;AAAA,IAAAA,KAAA,GAAAC,OAAA;AAGO,eAAeC,aAAaA,CAC/BC,gBAA+C,EAC/CC,aAAuB,EACzB;EACE,IAAIA,aAAa,CAACC,MAAM,KAAK,GAAG,EAAE;IAC9BF,gBAAgB,CAACG,eAAe,CAACC,IAAI,CAAC,CAAC;IACvC,IAAAC,cAAQ,EAAC,CAAC,CAACC,IAAI,CAAC,MAAMN,gBAAgB,CAACO,MAAM,CAAC,CAAC,CAAC;IAChD,MAAM,IAAAC,gBAAU,EAAC,aAAa,EAAE;MAC5BC,GAAG,EAAER,aAAa,CAACQ;IACvB,CAAC,CAAC;EACN;EACA,IAAIR,aAAa,CAACC,MAAM,KAAK,GAAG,EAAE;IAC9BF,gBAAgB,CAACU,aAAa,CAACN,IAAI,CAAC,CAAC;IACrC,MAAM,IAAAI,gBAAU,EAAC,iBAAiB,EAAE;MAChCC,GAAG,EAAER,aAAa,CAACQ;IACvB,CAAC,CAAC;EACN;EACA,IAAIR,aAAa,CAACC,MAAM,KAAK,GAAG,EAAE;IAC9BF,gBAAgB,CAACW,UAAU,CAACP,IAAI,CAAC,CAAC;IAClC,IAAAC,cAAQ,EAAC,CAAC,CAACC,IAAI,CAAC,MAAMN,gBAAgB,CAACO,MAAM,CAAC,CAAC,CAAC;IAChD,MAAM,IAAAC,gBAAU,EAAC,cAAc,EAAE;MAC7BC,GAAG,EAAER,aAAa,CAACQ;IACvB,CAAC,CAAC;EACN;EACA,IAAMG,IAAI,GAAG,MAAMX,aAAa,CAACY,IAAI,CAAC,CAAC;EAEvC,IAAID,IAAI,CAACE,KAAK,EAAE;IACZ;IACAC,OAAO,CAACC,GAAG,CAAC,iCAAiC,CAAC;IAC9CD,OAAO,CAACE,GAAG,CAACL,IAAI,CAAC;IACjB,MAAMA,IAAI;EACd;EAEA,OAAOA,IAAI;AACf","ignoreList":[]}
|
|
@@ -30,7 +30,6 @@ Object.keys(_types).forEach(function (key) {
|
|
|
30
30
|
});
|
|
31
31
|
});
|
|
32
32
|
var RxServerReplicationState = exports.RxServerReplicationState = /*#__PURE__*/function (_RxReplicationState) {
|
|
33
|
-
(0, _inheritsLoose2.default)(RxServerReplicationState, _RxReplicationState);
|
|
34
33
|
function RxServerReplicationState(replicationIdentifier, collection, pull, push, live = true, retryTime = 1000 * 5, autoStart = true, headers = {}) {
|
|
35
34
|
var _this;
|
|
36
35
|
_this = _RxReplicationState.call(this, replicationIdentifier, collection, '_deleted', pull, push, live, retryTime, autoStart) || this;
|
|
@@ -52,6 +51,7 @@ var RxServerReplicationState = exports.RxServerReplicationState = /*#__PURE__*/f
|
|
|
52
51
|
});
|
|
53
52
|
return _this;
|
|
54
53
|
}
|
|
54
|
+
(0, _inheritsLoose2.default)(RxServerReplicationState, _RxReplicationState);
|
|
55
55
|
var _proto = RxServerReplicationState.prototype;
|
|
56
56
|
_proto.setHeaders = function setHeaders(headers) {
|
|
57
57
|
this.headers = (0, _core.flatClone)(headers);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":["_core","require","_leaderElection","_replication","_rxjs","_helpers","_eventsource","_interopRequireDefault","_types","Object","keys","forEach","key","prototype","hasOwnProperty","call","_exportNames","exports","defineProperty","enumerable","get","RxServerReplicationState","_RxReplicationState","_inheritsLoose2","default","replicationIdentifier","collection","pull","push","live","retryTime","autoStart","headers","_this","outdatedClient$","Subject","unauthorized$","forbidden$","onCancel","complete","_proto","setHeaders","flatClone","RxReplicationState","replicateServer","options","newRxError","name","args","waitForLeadership","addRxPlugin","RxDBLeaderElectionPlugin","pullStream$","replicationPrimitivesPull","handler","checkpointOrNull","batchSize","lwt","id","url","response","fetch","method","assign","replicationState","data","parseResponse","documents","checkpoint","ensureNotFalsy","modifier","stream$","asObservable","replicationPrimitivesPush","changeRows","body","JSON","stringify","conflictsArray","startBefore","start","bind","useEventSource","eventSource","EventSource","refreshEventSource","withCredentials","onerror","err","status","next","close","promiseWait","then","onopen","x","onmessage","event","eventData","parse","startReplicationOnLeaderShip"],"sources":["../../../../src/plugins/replication-server/index.ts"],"sourcesContent":["import {\n ensureNotFalsy,\n flatClone,\n promiseWait,\n RxCollection,\n ReplicationPullOptions,\n ReplicationPushOptions,\n RxReplicationPullStreamItem,\n RxStorageDefaultCheckpoint,\n ById,\n addRxPlugin, \n newRxError\n} from 'rxdb/plugins/core';\nimport { RxDBLeaderElectionPlugin } from 'rxdb/plugins/leader-election';\nimport {\n RxReplicationState,\n startReplicationOnLeaderShip\n} from 'rxdb/plugins/replication';\n\nimport { Subject } from 'rxjs';\nimport { ServerSyncOptions } from './types.ts';\nimport { parseResponse } from './helpers.ts';\nimport EventSource from 'eventsource';\n\nexport * from './types.ts';\n\nexport class RxServerReplicationState<RxDocType> extends RxReplicationState<RxDocType, RxStorageDefaultCheckpoint> {\n public readonly outdatedClient$ = new Subject<void>();\n public readonly unauthorized$ = new Subject<void>();\n public readonly forbidden$ = new Subject<void>();\n\n constructor(\n public readonly replicationIdentifier: string,\n public readonly collection: RxCollection<RxDocType>,\n public readonly pull?: ReplicationPullOptions<RxDocType, RxStorageDefaultCheckpoint>,\n public readonly push?: ReplicationPushOptions<RxDocType>,\n public readonly live: boolean = true,\n public retryTime: number = 1000 * 5,\n public autoStart: boolean = true,\n public headers: ById<string> = {}\n ) {\n super(\n replicationIdentifier,\n collection,\n '_deleted',\n pull,\n push,\n live,\n retryTime,\n autoStart\n );\n\n this.onCancel.push(() => {\n this.outdatedClient$.complete();\n this.unauthorized$.complete();\n this.forbidden$.complete();\n });\n }\n\n setHeaders(headers: ById<string>): void {\n this.headers = flatClone(headers);\n }\n}\n\nexport function replicateServer<RxDocType>(\n options: ServerSyncOptions<RxDocType>\n): RxServerReplicationState<RxDocType> {\n\n if (!options.pull && !options.push) {\n throw newRxError('UT3', {\n collection: options.collection.name,\n args: {\n replicationIdentifier: options.replicationIdentifier\n }\n });\n }\n\n options.live = typeof options.live === 'undefined' ? true : options.live;\n options.waitForLeadership = typeof options.waitForLeadership === 'undefined' ? true : options.waitForLeadership;\n\n const collection = options.collection;\n addRxPlugin(RxDBLeaderElectionPlugin);\n\n const pullStream$: Subject<RxReplicationPullStreamItem<RxDocType, RxStorageDefaultCheckpoint>> = new Subject();\n\n let replicationPrimitivesPull: ReplicationPullOptions<RxDocType, RxStorageDefaultCheckpoint> | undefined;\n if (options.pull) {\n replicationPrimitivesPull = {\n async handler(checkpointOrNull, batchSize) {\n const lwt = checkpointOrNull && checkpointOrNull.lwt ? checkpointOrNull.lwt : 0;\n const id = checkpointOrNull && checkpointOrNull.id ? checkpointOrNull.id : '';\n const url = options.url + `/pull?lwt=${lwt}&id=${id}&limit=${batchSize}`;\n const response = await fetch(url, {\n method: 'GET',\n headers: Object.assign({\n 'Accept': 'application/json',\n 'Content-Type': 'application/json'\n }, replicationState.headers),\n });\n const data = await await parseResponse(replicationState, response);\n return {\n documents: data.documents,\n checkpoint: data.checkpoint\n };\n },\n batchSize: ensureNotFalsy(options.pull).batchSize,\n modifier: ensureNotFalsy(options.pull).modifier,\n stream$: pullStream$.asObservable()\n };\n }\n\n let replicationPrimitivesPush: ReplicationPushOptions<RxDocType> | undefined;\n if (options.push) {\n replicationPrimitivesPush = {\n async handler(changeRows) {\n const response = await fetch(options.url + '/push', {\n method: 'POST',\n headers: Object.assign({\n 'Accept': 'application/json',\n 'Content-Type': 'application/json'\n }, replicationState.headers),\n body: JSON.stringify(changeRows)\n });\n const conflictsArray = await parseResponse(replicationState, response);\n return conflictsArray;\n },\n batchSize: options.push.batchSize,\n modifier: options.push.modifier\n };\n }\n\n const replicationState = new RxServerReplicationState<RxDocType>(\n options.replicationIdentifier,\n collection,\n replicationPrimitivesPull,\n replicationPrimitivesPush,\n options.live,\n options.retryTime,\n options.autoStart,\n options.headers\n );\n\n /**\n * Use long polling to get live changes for the pull.stream$\n */\n if (options.live && options.pull) {\n const startBefore = replicationState.start.bind(replicationState);\n replicationState.start = async () => {\n const useEventSource: typeof EventSource = options.eventSource ? options.eventSource : EventSource;\n let eventSource: EventSource;\n const refreshEventSource = () => {\n eventSource = new useEventSource(options.url + '/pullStream', {\n withCredentials: true,\n /**\n * Sending headers is not supported by the Browser EventSource API,\n * only by the npm module we use. In react-native you might have\n * to set another EventSource implementation.\n * @link https://www.npmjs.com/package/eventsource\n */\n headers: replicationState.headers\n });\n // TODO check for 426 errors and handle them\n eventSource.onerror = (err) => {\n if (err.status === 401) {\n replicationState.unauthorized$.next();\n eventSource.close();\n promiseWait(replicationState.retryTime).then(() => refreshEventSource());\n } else {\n pullStream$.next('RESYNC');\n }\n };\n eventSource.onopen = (x) => {\n pullStream$.next('RESYNC');\n }\n eventSource.onmessage = event => {\n const eventData = JSON.parse(event.data);\n pullStream$.next({\n documents: eventData.documents,\n checkpoint: eventData.checkpoint\n });\n };\n }\n refreshEventSource();\n\n replicationState.onCancel.push(() => eventSource && eventSource.close());\n return startBefore();\n };\n }\n\n startReplicationOnLeaderShip(options.waitForLeadership, replicationState);\n\n return replicationState;\n}\n"],"mappings":";;;;;;;;;;;;;AAAA,IAAAA,KAAA,GAAAC,OAAA;AAaA,IAAAC,eAAA,GAAAD,OAAA;AACA,IAAAE,YAAA,GAAAF,OAAA;AAKA,IAAAG,KAAA,GAAAH,OAAA;AAEA,IAAAI,QAAA,GAAAJ,OAAA;AACA,IAAAK,YAAA,GAAAC,sBAAA,CAAAN,OAAA;AAEA,IAAAO,MAAA,GAAAP,OAAA;AAAAQ,MAAA,CAAAC,IAAA,CAAAF,MAAA,EAAAG,OAAA,WAAAC,GAAA;EAAA,IAAAA,GAAA,kBAAAA,GAAA;EAAA,IAAAH,MAAA,CAAAI,SAAA,CAAAC,cAAA,CAAAC,IAAA,CAAAC,YAAA,EAAAJ,GAAA;EAAA,IAAAA,GAAA,IAAAK,OAAA,IAAAA,OAAA,CAAAL,GAAA,MAAAJ,MAAA,CAAAI,GAAA;EAAAH,MAAA,CAAAS,cAAA,CAAAD,OAAA,EAAAL,GAAA;IAAAO,UAAA;IAAAC,GAAA,WAAAA,CAAA;MAAA,OAAAZ,MAAA,CAAAI,GAAA;IAAA;EAAA;AAAA;AAA2B,IAEdS,wBAAwB,GAAAJ,OAAA,CAAAI,wBAAA,0BAAAC,mBAAA;EAAA,IAAAC,eAAA,CAAAC,OAAA,EAAAH,wBAAA,EAAAC,mBAAA;EAKjC,SAAAD,yBACoBI,qBAA6B,EAC7BC,UAAmC,EACnCC,IAAoE,EACpEC,IAAwC,EACxCC,IAAa,GAAG,IAAI,EAC7BC,SAAiB,GAAG,IAAI,GAAG,CAAC,EAC5BC,SAAkB,GAAG,IAAI,EACzBC,OAAqB,GAAG,CAAC,CAAC,EACnC;IAAA,IAAAC,KAAA;IACEA,KAAA,GAAAX,mBAAA,CAAAP,IAAA,OACIU,qBAAqB,EACrBC,UAAU,EACV,UAAU,EACVC,IAAI,EACJC,IAAI,EACJC,IAAI,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SAAS,EAAE+B,SAAS,CAAC/B,SAAS;YAC9BC,UAAU,EAAE8B,SAAS,CAAC9B;UAC1B,CAAC,CAAC;QACN,CAAC;MACL,CAAC;MACDiB,kBAAkB,CAAC,CAAC;MAEpBrB,gBAAgB,CAAC1B,QAAQ,CAACV,IAAI,CAAC,MAAMuD,WAAW,IAAIA,WAAW,CAACQ,KAAK,CAAC,CAAC,CAAC;MACxE,OAAOZ,WAAW,CAAC,CAAC;IACxB,CAAC;EACL;EAEA,IAAAqB,yCAA4B,EAACvD,OAAO,CAACI,iBAAiB,EAAEe,gBAAgB,CAAC;EAEzE,OAAOA,gBAAgB;AAC3B"}
|
|
1
|
+
{"version":3,"file":"index.js","names":["_core","require","_leaderElection","_replication","_rxjs","_helpers","_eventsource","_interopRequireDefault","_types","Object","keys","forEach","key","prototype","hasOwnProperty","call","_exportNames","exports","defineProperty","enumerable","get","RxServerReplicationState","_RxReplicationState","replicationIdentifier","collection","pull","push","live","retryTime","autoStart","headers","_this","outdatedClient$","Subject","unauthorized$","forbidden$","onCancel","complete","_inheritsLoose2","default","_proto","setHeaders","flatClone","RxReplicationState","replicateServer","options","newRxError","name","args","waitForLeadership","addRxPlugin","RxDBLeaderElectionPlugin","pullStream$","replicationPrimitivesPull","handler","checkpointOrNull","batchSize","lwt","id","url","response","fetch","method","assign","replicationState","data","parseResponse","documents","checkpoint","ensureNotFalsy","modifier","stream$","asObservable","replicationPrimitivesPush","changeRows","body","JSON","stringify","conflictsArray","startBefore","start","bind","useEventSource","eventSource","EventSource","refreshEventSource","withCredentials","onerror","err","status","next","close","promiseWait","then","onopen","x","onmessage","event","eventData","parse","startReplicationOnLeaderShip"],"sources":["../../../../src/plugins/replication-server/index.ts"],"sourcesContent":["import {\n ensureNotFalsy,\n flatClone,\n promiseWait,\n RxCollection,\n ReplicationPullOptions,\n ReplicationPushOptions,\n RxReplicationPullStreamItem,\n RxStorageDefaultCheckpoint,\n ById,\n addRxPlugin, \n newRxError\n} from 'rxdb/plugins/core';\nimport { RxDBLeaderElectionPlugin } from 'rxdb/plugins/leader-election';\nimport {\n RxReplicationState,\n startReplicationOnLeaderShip\n} from 'rxdb/plugins/replication';\n\nimport { Subject } from 'rxjs';\nimport { ServerSyncOptions } from './types.ts';\nimport { parseResponse } from './helpers.ts';\nimport EventSource from 'eventsource';\n\nexport * from './types.ts';\n\nexport class RxServerReplicationState<RxDocType> extends RxReplicationState<RxDocType, RxStorageDefaultCheckpoint> {\n public readonly outdatedClient$ = new Subject<void>();\n public readonly unauthorized$ = new Subject<void>();\n public readonly forbidden$ = new Subject<void>();\n\n constructor(\n public readonly replicationIdentifier: string,\n public readonly collection: RxCollection<RxDocType>,\n public readonly pull?: ReplicationPullOptions<RxDocType, RxStorageDefaultCheckpoint>,\n public readonly push?: ReplicationPushOptions<RxDocType>,\n public readonly live: boolean = true,\n public retryTime: number = 1000 * 5,\n public autoStart: boolean = true,\n public headers: ById<string> = {}\n ) {\n super(\n replicationIdentifier,\n collection,\n '_deleted',\n pull,\n push,\n live,\n retryTime,\n autoStart\n );\n\n this.onCancel.push(() => {\n this.outdatedClient$.complete();\n this.unauthorized$.complete();\n this.forbidden$.complete();\n });\n }\n\n setHeaders(headers: ById<string>): void {\n this.headers = flatClone(headers);\n }\n}\n\nexport function replicateServer<RxDocType>(\n options: ServerSyncOptions<RxDocType>\n): RxServerReplicationState<RxDocType> {\n\n if (!options.pull && !options.push) {\n throw newRxError('UT3', {\n collection: options.collection.name,\n args: {\n replicationIdentifier: options.replicationIdentifier\n }\n });\n }\n\n options.live = typeof options.live === 'undefined' ? true : options.live;\n options.waitForLeadership = typeof options.waitForLeadership === 'undefined' ? true : options.waitForLeadership;\n\n const collection = options.collection;\n addRxPlugin(RxDBLeaderElectionPlugin);\n\n const pullStream$: Subject<RxReplicationPullStreamItem<RxDocType, RxStorageDefaultCheckpoint>> = new Subject();\n\n let replicationPrimitivesPull: ReplicationPullOptions<RxDocType, RxStorageDefaultCheckpoint> | undefined;\n if (options.pull) {\n replicationPrimitivesPull = {\n async handler(checkpointOrNull, batchSize) {\n const lwt = checkpointOrNull && checkpointOrNull.lwt ? checkpointOrNull.lwt : 0;\n const id = checkpointOrNull && checkpointOrNull.id ? checkpointOrNull.id : '';\n const url = options.url + `/pull?lwt=${lwt}&id=${id}&limit=${batchSize}`;\n const response = await fetch(url, {\n method: 'GET',\n headers: Object.assign({\n 'Accept': 'application/json',\n 'Content-Type': 'application/json'\n }, replicationState.headers),\n });\n const data = await await parseResponse(replicationState, response);\n return {\n documents: data.documents,\n checkpoint: data.checkpoint\n };\n },\n batchSize: ensureNotFalsy(options.pull).batchSize,\n modifier: ensureNotFalsy(options.pull).modifier,\n stream$: pullStream$.asObservable()\n };\n }\n\n let replicationPrimitivesPush: ReplicationPushOptions<RxDocType> | undefined;\n if (options.push) {\n replicationPrimitivesPush = {\n async handler(changeRows) {\n const response = await fetch(options.url + '/push', {\n method: 'POST',\n headers: Object.assign({\n 'Accept': 'application/json',\n 'Content-Type': 'application/json'\n }, replicationState.headers),\n body: JSON.stringify(changeRows)\n });\n const conflictsArray = await parseResponse(replicationState, response);\n return conflictsArray;\n },\n batchSize: options.push.batchSize,\n modifier: options.push.modifier\n };\n }\n\n const replicationState = new RxServerReplicationState<RxDocType>(\n options.replicationIdentifier,\n collection,\n replicationPrimitivesPull,\n replicationPrimitivesPush,\n options.live,\n options.retryTime,\n options.autoStart,\n options.headers\n );\n\n /**\n * Use long polling to get live changes for the pull.stream$\n */\n if (options.live && options.pull) {\n const startBefore = replicationState.start.bind(replicationState);\n replicationState.start = async () => {\n const useEventSource: typeof EventSource = options.eventSource ? options.eventSource : EventSource;\n let eventSource: EventSource;\n const refreshEventSource = () => {\n eventSource = new useEventSource(options.url + '/pullStream', {\n withCredentials: true,\n /**\n * Sending headers is not supported by the Browser EventSource API,\n * only by the npm module we use. In react-native you might have\n * to set another EventSource implementation.\n * @link https://www.npmjs.com/package/eventsource\n */\n headers: replicationState.headers\n });\n // TODO check for 426 errors and handle them\n eventSource.onerror = (err) => {\n if (err.status === 401) {\n replicationState.unauthorized$.next();\n eventSource.close();\n promiseWait(replicationState.retryTime).then(() => refreshEventSource());\n } else {\n pullStream$.next('RESYNC');\n }\n };\n eventSource.onopen = (x) => {\n pullStream$.next('RESYNC');\n }\n eventSource.onmessage = event => {\n const eventData = JSON.parse(event.data);\n pullStream$.next({\n documents: eventData.documents,\n checkpoint: eventData.checkpoint\n });\n };\n }\n refreshEventSource();\n\n replicationState.onCancel.push(() => eventSource && eventSource.close());\n return startBefore();\n };\n }\n\n startReplicationOnLeaderShip(options.waitForLeadership, replicationState);\n\n return replicationState;\n}\n"],"mappings":";;;;;;;;;;;;;AAAA,IAAAA,KAAA,GAAAC,OAAA;AAaA,IAAAC,eAAA,GAAAD,OAAA;AACA,IAAAE,YAAA,GAAAF,OAAA;AAKA,IAAAG,KAAA,GAAAH,OAAA;AAEA,IAAAI,QAAA,GAAAJ,OAAA;AACA,IAAAK,YAAA,GAAAC,sBAAA,CAAAN,OAAA;AAEA,IAAAO,MAAA,GAAAP,OAAA;AAAAQ,MAAA,CAAAC,IAAA,CAAAF,MAAA,EAAAG,OAAA,WAAAC,GAAA;EAAA,IAAAA,GAAA,kBAAAA,GAAA;EAAA,IAAAH,MAAA,CAAAI,SAAA,CAAAC,cAAA,CAAAC,IAAA,CAAAC,YAAA,EAAAJ,GAAA;EAAA,IAAAA,GAAA,IAAAK,OAAA,IAAAA,OAAA,CAAAL,GAAA,MAAAJ,MAAA,CAAAI,GAAA;EAAAH,MAAA,CAAAS,cAAA,CAAAD,OAAA,EAAAL,GAAA;IAAAO,UAAA;IAAAC,GAAA,WAAAA,CAAA;MAAA,OAAAZ,MAAA,CAAAI,GAAA;IAAA;EAAA;AAAA;AAA2B,IAEdS,wBAAwB,GAAAJ,OAAA,CAAAI,wBAAA,0BAAAC,mBAAA;EAKjC,SAAAD,yBACoBE,qBAA6B,EAC7BC,UAAmC,EACnCC,IAAoE,EACpEC,IAAwC,EACxCC,IAAa,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CAACsC,IAAI,CAAC,QAAQ,CAAC;UAC9B;QACJ,CAAC;QACDP,WAAW,CAACW,MAAM,GAAIC,CAAC,IAAK;UACxB3C,WAAW,CAACsC,IAAI,CAAC,QAAQ,CAAC;QAC9B,CAAC;QACDP,WAAW,CAACa,SAAS,GAAGC,KAAK,IAAI;UAC7B,IAAMC,SAAS,GAAGtB,IAAI,CAACuB,KAAK,CAACF,KAAK,CAAChC,IAAI,CAAC;UACxCb,WAAW,CAACsC,IAAI,CAAC;YACbvB,SAAS,EAAE+B,SAAS,CAAC/B,SAAS;YAC9BC,UAAU,EAAE8B,SAAS,CAAC9B;UAC1B,CAAC,CAAC;QACN,CAAC;MACL,CAAC;MACDiB,kBAAkB,CAAC,CAAC;MAEpBrB,gBAAgB,CAAC5B,QAAQ,CAACV,IAAI,CAAC,MAAMyD,WAAW,IAAIA,WAAW,CAACQ,KAAK,CAAC,CAAC,CAAC;MACxE,OAAOZ,WAAW,CAAC,CAAC;IACxB,CAAC;EACL;EAEA,IAAAqB,yCAA4B,EAACvD,OAAO,CAACI,iBAAiB,EAAEe,gBAAgB,CAAC;EAEzE,OAAOA,gBAAgB;AAC3B","ignoreList":[]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"types.js","names":[],"sources":["../../../../src/plugins/replication-server/types.ts"],"sourcesContent":["import type {\n MaybePromise,\n ReplicationOptions,\n ReplicationPullOptions,\n ReplicationPushOptions,\n RxStorageDefaultCheckpoint\n} from 'rxdb/plugins/core';\n\nexport type ServerSyncPullOptions<RxDocType> =\n Omit<ReplicationPullOptions<RxDocType, RxStorageDefaultCheckpoint>, 'handler' | 'stream$'>\n & {\n };\n\nexport type ServerSyncPushOptions<RxDocType> = Omit<ReplicationPushOptions<RxDocType>, 'handler'>\n & {\n};\n\nexport type ServerSyncOptions<RxDocType> = Omit<\n ReplicationOptions<RxDocType, any>,\n 'pull' | 'push'\n> & {\n url: string;\n headers?: { [k: string]: string };\n pull?: ServerSyncPullOptions<RxDocType>;\n push?: ServerSyncPushOptions<RxDocType>;\n\n /**\n * If the EventSource API is not available\n * on the runtime, pass an own implementation here.\n * Mostly used with the \"eventsource\" npm package on Node.js.\n */\n eventSource?: typeof EventSource | any\n};\n"],"mappings":""}
|
|
1
|
+
{"version":3,"file":"types.js","names":[],"sources":["../../../../src/plugins/replication-server/types.ts"],"sourcesContent":["import type {\n MaybePromise,\n ReplicationOptions,\n ReplicationPullOptions,\n ReplicationPushOptions,\n RxStorageDefaultCheckpoint\n} from 'rxdb/plugins/core';\n\nexport type ServerSyncPullOptions<RxDocType> =\n Omit<ReplicationPullOptions<RxDocType, RxStorageDefaultCheckpoint>, 'handler' | 'stream$'>\n & {\n };\n\nexport type ServerSyncPushOptions<RxDocType> = Omit<ReplicationPushOptions<RxDocType>, 'handler'>\n & {\n};\n\nexport type ServerSyncOptions<RxDocType> = Omit<\n ReplicationOptions<RxDocType, any>,\n 'pull' | 'push'\n> & {\n url: string;\n headers?: { [k: string]: string };\n pull?: ServerSyncPullOptions<RxDocType>;\n push?: ServerSyncPushOptions<RxDocType>;\n\n /**\n * If the EventSource API is not available\n * on the runtime, pass an own implementation here.\n * Mostly used with the \"eventsource\" npm package on Node.js.\n */\n eventSource?: typeof EventSource | any\n};\n"],"mappings":"","ignoreList":[]}
|
|
@@ -16,6 +16,7 @@ var RxServerReplicationEndpoint = exports.RxServerReplicationEndpoint = function
|
|
|
16
16
|
this.collection = collection;
|
|
17
17
|
this.serverOnlyFields = serverOnlyFields;
|
|
18
18
|
this.cors = cors;
|
|
19
|
+
var adapter = this.server.adapter;
|
|
19
20
|
(0, _helper.setCors)(this.server, [this.name].join('/'), cors);
|
|
20
21
|
(0, _helper.blockPreviousVersionPaths)(this.server, [this.name].join('/'), collection.schema.version);
|
|
21
22
|
this.urlPath = [this.name, collection.schema.version].join('/');
|
|
@@ -36,11 +37,12 @@ var RxServerReplicationEndpoint = exports.RxServerReplicationEndpoint = function
|
|
|
36
37
|
};
|
|
37
38
|
var removeServerOnlyFields = (0, _helper.removeServerOnlyFieldsMonad)(this.serverOnlyFields);
|
|
38
39
|
var mergeServerDocumentFields = (0, _helper.mergeServerDocumentFieldsMonad)(this.serverOnlyFields);
|
|
39
|
-
this.server.
|
|
40
|
+
this.server.adapter.get(this.server.serverApp, '/' + this.urlPath + '/pull', async (req, res) => {
|
|
40
41
|
var authData = (0, _utils.getFromMapOrThrow)(authDataByRequest, req);
|
|
41
|
-
var
|
|
42
|
-
var
|
|
43
|
-
var
|
|
42
|
+
var urlQuery = adapter.getRequestQuery(req);
|
|
43
|
+
var id = urlQuery.id ? urlQuery.id : '';
|
|
44
|
+
var lwt = urlQuery.lwt ? parseInt(urlQuery.lwt, 10) : 0;
|
|
45
|
+
var limit = urlQuery.limit ? parseInt(urlQuery.limit, 10) : 1;
|
|
44
46
|
var plainQuery = (0, _core.getChangedDocumentsSinceQuery)(this.collection.storageInstance, limit, {
|
|
45
47
|
id,
|
|
46
48
|
lwt
|
|
@@ -56,16 +58,16 @@ var RxServerReplicationEndpoint = exports.RxServerReplicationEndpoint = function
|
|
|
56
58
|
updatedAt: (0, _utils.ensureNotFalsy)((0, _utils.lastOfArray)(result.documents))._meta.lwt
|
|
57
59
|
};
|
|
58
60
|
var responseDocuments = result.documents.map(d => removeServerOnlyFields(d));
|
|
59
|
-
|
|
60
|
-
|
|
61
|
+
adapter.setResponseHeader(res, 'Content-Type', 'application/json');
|
|
62
|
+
adapter.endResponseJson(res, {
|
|
61
63
|
documents: responseDocuments,
|
|
62
64
|
checkpoint: newCheckpoint
|
|
63
65
|
});
|
|
64
66
|
});
|
|
65
|
-
this.server.
|
|
67
|
+
this.server.adapter.post(this.server.serverApp, '/' + this.urlPath + '/push', async (req, res) => {
|
|
66
68
|
var authData = (0, _utils.getFromMapOrThrow)(authDataByRequest, req);
|
|
67
69
|
var docDataMatcherWrite = (0, _helper.getDocAllowedMatcher)(this, (0, _utils.ensureNotFalsy)(authData));
|
|
68
|
-
var rows = req
|
|
70
|
+
var rows = adapter.getRequestBody(req);
|
|
69
71
|
var ids = [];
|
|
70
72
|
rows.forEach(row => ids.push(row.newDocumentState[primaryPath]));
|
|
71
73
|
for (var row of rows) {
|
|
@@ -82,7 +84,7 @@ var RxServerReplicationEndpoint = exports.RxServerReplicationEndpoint = function
|
|
|
82
84
|
}
|
|
83
85
|
});
|
|
84
86
|
if (nonAllowedRow) {
|
|
85
|
-
|
|
87
|
+
adapter.closeConnection(res, 403, 'Forbidden');
|
|
86
88
|
return;
|
|
87
89
|
}
|
|
88
90
|
var hasInvalidChange = false;
|
|
@@ -105,15 +107,15 @@ var RxServerReplicationEndpoint = exports.RxServerReplicationEndpoint = function
|
|
|
105
107
|
};
|
|
106
108
|
});
|
|
107
109
|
if (hasInvalidChange) {
|
|
108
|
-
|
|
110
|
+
adapter.closeConnection(res, 403, 'Forbidden');
|
|
109
111
|
return;
|
|
110
112
|
}
|
|
111
113
|
var conflicts = await replicationHandler.masterWrite(useRows);
|
|
112
|
-
|
|
113
|
-
|
|
114
|
+
adapter.setResponseHeader(res, 'Content-Type', 'application/json');
|
|
115
|
+
adapter.endResponseJson(res, conflicts);
|
|
114
116
|
});
|
|
115
|
-
this.server.
|
|
116
|
-
|
|
117
|
+
this.server.adapter.get(this.server.serverApp, '/' + this.urlPath + '/pullStream', async (req, res) => {
|
|
118
|
+
adapter.setSSEHeaders(res);
|
|
117
119
|
var authData = (0, _utils.getFromMapOrThrow)(authDataByRequest, req);
|
|
118
120
|
var docDataMatcherStream = (0, _helper.getDocAllowedMatcher)(this, (0, _utils.ensureNotFalsy)(authData));
|
|
119
121
|
var subscription = replicationHandler.masterChangeStream$.pipe((0, _rxjs.mergeMap)(async changes => {
|
|
@@ -124,9 +126,9 @@ var RxServerReplicationEndpoint = exports.RxServerReplicationEndpoint = function
|
|
|
124
126
|
*/
|
|
125
127
|
var authData;
|
|
126
128
|
try {
|
|
127
|
-
authData = await server.authHandler(req
|
|
129
|
+
authData = await server.authHandler(adapter.getRequestHeaders(req));
|
|
128
130
|
} catch (err) {
|
|
129
|
-
|
|
131
|
+
adapter.closeConnection(res, 401, 'Unauthorized');
|
|
130
132
|
return null;
|
|
131
133
|
}
|
|
132
134
|
if (changes === 'RESYNC') {
|
|
@@ -140,10 +142,10 @@ var RxServerReplicationEndpoint = exports.RxServerReplicationEndpoint = function
|
|
|
140
142
|
}
|
|
141
143
|
}), (0, _rxjs.filter)(f => f !== null && (f === 'RESYNC' || f.documents.length > 0))).subscribe(filteredAndModified => {
|
|
142
144
|
if (filteredAndModified === 'RESYNC') {
|
|
143
|
-
|
|
145
|
+
adapter.responseWrite(res, 'data: ' + JSON.stringify(filteredAndModified) + '\n\n');
|
|
144
146
|
} else {
|
|
145
147
|
var responseDocuments = (0, _utils.ensureNotFalsy)(filteredAndModified).documents.map(d => removeServerOnlyFields(d));
|
|
146
|
-
|
|
148
|
+
adapter.responseWrite(res, 'data: ' + JSON.stringify({
|
|
147
149
|
documents: responseDocuments,
|
|
148
150
|
checkpoint: (0, _utils.ensureNotFalsy)(filteredAndModified).checkpoint
|
|
149
151
|
}) + '\n\n');
|
|
@@ -153,9 +155,9 @@ var RxServerReplicationEndpoint = exports.RxServerReplicationEndpoint = function
|
|
|
153
155
|
/**
|
|
154
156
|
* @link https://youtu.be/0PcMuYGJPzM?si=AxkczxcMaUwhh8k9&t=363
|
|
155
157
|
*/
|
|
156
|
-
|
|
158
|
+
adapter.onRequestClose(req, () => {
|
|
157
159
|
subscription.unsubscribe();
|
|
158
|
-
|
|
160
|
+
adapter.endResponse(res);
|
|
159
161
|
});
|
|
160
162
|
});
|
|
161
163
|
};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"endpoint-replication.js","names":["_core","require","_replicationWebsocket","_rxjs","_utils","_helper","RxServerReplicationEndpoint","exports","server","name","collection","queryModifier","changeValidator","serverOnlyFields","cors","type","setCors","join","blockPreviousVersionPaths","schema","version","urlPath","primaryPath","replicationHandler","getReplicationHandlerByCollection","database","authDataByRequest","addAuthMiddleware","authData","query","doesContainRegexQuerySelector","selector","Error","change","assumedMasterState","docContainsServerOnlyFields","newDocumentState","removeServerOnlyFields","removeServerOnlyFieldsMonad","mergeServerDocumentFields","mergeServerDocumentFieldsMonad","expressApp","get","req","res","getFromMapOrThrow","id","lwt","parseInt","limit","plainQuery","getChangedDocumentsSinceQuery","storageInstance","useQueryChanges","ensureNotFalsy","prepared","prepareQuery","jsonSchema","result","newCheckpoint","documents","length","lastOfArray","updatedAt","_meta","responseDocuments","map","d","setHeader","json","checkpoint","post","docDataMatcherWrite","getDocAllowedMatcher","rows","body","ids","forEach","row","push","nonAllowedRow","find","closeConnection","hasInvalidChange","currentStateDocsArray","findDocumentsById","currentStateDocs","Map","set","useRows","isChangeValid","serverDoc","conflicts","masterWrite","writeSSEHeaders","docDataMatcherStream","subscription","masterChangeStream$","pipe","mergeMap","changes","authHandler","headers","err","useDocs","filter","f","subscribe","filteredAndModified","write","JSON","stringify","on","unsubscribe","end"],"sources":["../../../../src/plugins/server/endpoint-replication.ts"],"sourcesContent":["import {\n FilledMangoQuery,\n RxCollection,\n RxReplicationHandler,\n RxReplicationWriteToMasterRow,\n RxStorageDefaultCheckpoint,\n StringKeys,\n prepareQuery,\n getChangedDocumentsSinceQuery,\n RxDocumentData\n} from 'rxdb/plugins/core';\nimport { getReplicationHandlerByCollection } from 'rxdb/plugins/replication-websocket';\nimport type { RxServer } from './rx-server.ts';\nimport type {\n RxServerAuthData,\n RxServerChangeValidator,\n RxServerEndpoint,\n RxServerQueryModifier\n} from './types.ts';\nimport { filter, mergeMap } from 'rxjs';\nimport {\n ensureNotFalsy,\n getFromMapOrThrow,\n lastOfArray\n} from 'rxdb/plugins/utils';\n\nimport {\n addAuthMiddleware,\n blockPreviousVersionPaths,\n closeConnection,\n docContainsServerOnlyFields,\n doesContainRegexQuerySelector,\n getDocAllowedMatcher,\n mergeServerDocumentFieldsMonad,\n removeServerOnlyFieldsMonad,\n setCors,\n writeSSEHeaders\n} from './helper.ts';\n\nexport type RxReplicationEndpointMessageType = {\n id: string;\n method: StringKeys<RxReplicationHandler<any, any>> | 'auth';\n params: any[];\n};\n\nexport class RxServerReplicationEndpoint<AuthType, RxDocType> implements RxServerEndpoint<AuthType, RxDocType> {\n readonly type = 'replication';\n readonly urlPath: string;\n readonly changeValidator: RxServerChangeValidator<AuthType, RxDocType>;\n readonly queryModifier: RxServerQueryModifier<AuthType, RxDocType>;\n constructor(\n public readonly server: RxServer<AuthType>,\n public readonly name: string,\n public readonly collection: RxCollection<RxDocType>,\n queryModifier: RxServerQueryModifier<AuthType, RxDocType>,\n changeValidator: RxServerChangeValidator<AuthType, RxDocType>,\n public readonly serverOnlyFields: string[],\n public readonly cors?: string,\n ) {\n setCors(this.server, [this.name].join('/'), cors);\n blockPreviousVersionPaths(this.server, [this.name].join('/'), collection.schema.version);\n\n this.urlPath = [this.name, collection.schema.version].join('/');\n\n const primaryPath = this.collection.schema.primaryPath;\n const replicationHandler = getReplicationHandlerByCollection(this.server.database, collection.name);\n const authDataByRequest = addAuthMiddleware(\n this.server,\n this.urlPath\n );\n\n this.queryModifier = (authData, query) => {\n if (doesContainRegexQuerySelector(query.selector)) {\n throw new Error('$regex queries not allowed because of DOS-attacks');\n }\n return queryModifier(authData, query);\n }\n this.changeValidator = (authData, change) => {\n if (\n (change.assumedMasterState && docContainsServerOnlyFields(serverOnlyFields, change.assumedMasterState)) ||\n docContainsServerOnlyFields(serverOnlyFields, change.newDocumentState)\n ) {\n return false;\n }\n return changeValidator(authData, change);\n }\n const removeServerOnlyFields = removeServerOnlyFieldsMonad<RxDocType>(this.serverOnlyFields);\n const mergeServerDocumentFields = mergeServerDocumentFieldsMonad<RxDocType>(this.serverOnlyFields);\n\n this.server.expressApp.get('/' + this.urlPath + '/pull', async (req, res) => {\n const authData = getFromMapOrThrow(authDataByRequest, req);\n const id = req.query.id ? req.query.id as string : '';\n const lwt = req.query.lwt ? parseInt(req.query.lwt as any, 10) : 0;\n const limit = req.query.limit ? parseInt(req.query.limit as any, 10) : 1;\n const plainQuery = getChangedDocumentsSinceQuery<RxDocType, RxStorageDefaultCheckpoint>(\n this.collection.storageInstance,\n limit,\n { id, lwt }\n );\n const useQueryChanges: FilledMangoQuery<RxDocType> = this.queryModifier(\n ensureNotFalsy(authData),\n plainQuery\n );\n const prepared = prepareQuery<RxDocType>(\n this.collection.schema.jsonSchema,\n useQueryChanges\n );\n const result = await this.collection.storageInstance.query(prepared);\n\n const newCheckpoint = result.documents.length === 0 ? { id, lwt } : {\n id: ensureNotFalsy(lastOfArray(result.documents))[primaryPath],\n updatedAt: ensureNotFalsy(lastOfArray(result.documents))._meta.lwt\n };\n const responseDocuments = result.documents.map(d => removeServerOnlyFields(d));\n res.setHeader('Content-Type', 'application/json');\n res.json({\n documents: responseDocuments,\n checkpoint: newCheckpoint\n });\n });\n this.server.expressApp.post('/' + this.urlPath + '/push', async (req, res) => {\n const authData = getFromMapOrThrow(authDataByRequest, req);\n const docDataMatcherWrite = getDocAllowedMatcher(this, ensureNotFalsy(authData));\n const rows: RxReplicationWriteToMasterRow<RxDocType>[] = req.body;\n const ids: string[] = [];\n rows.forEach(row => ids.push((row.newDocumentState as any)[primaryPath]));\n\n for (const row of rows) {\n // TODO remove this check\n if (row.assumedMasterState && (row.assumedMasterState as any)._meta) {\n throw new Error('body document contains meta!');\n }\n }\n\n // ensure all writes are allowed\n const nonAllowedRow = rows.find(row => {\n if (\n !docDataMatcherWrite(row.newDocumentState as any) ||\n (row.assumedMasterState && !docDataMatcherWrite(row.assumedMasterState as any))\n ) {\n return true;\n }\n });\n if (nonAllowedRow) {\n closeConnection(res, 403, 'Forbidden');\n return;\n }\n let hasInvalidChange = false;\n\n const currentStateDocsArray = await this.collection.storageInstance.findDocumentsById(ids, true);\n const currentStateDocs = new Map<string, RxDocumentData<RxDocType>>();\n currentStateDocsArray.forEach(d => currentStateDocs.set((d as any)[primaryPath], d));\n\n const useRows: typeof rows = rows.map((row) => {\n const id = (row.newDocumentState as any)[primaryPath];\n const isChangeValid = this.changeValidator(ensureNotFalsy(authData), {\n newDocumentState: removeServerOnlyFields(row.newDocumentState),\n assumedMasterState: removeServerOnlyFields(row.assumedMasterState)\n });\n if (!isChangeValid) {\n hasInvalidChange = true;\n }\n\n const serverDoc = currentStateDocs.get(id);\n return {\n newDocumentState: mergeServerDocumentFields(row.newDocumentState, serverDoc),\n assumedMasterState: mergeServerDocumentFields(row.assumedMasterState as any, serverDoc)\n } as typeof row;\n });\n if (hasInvalidChange) {\n closeConnection(res, 403, 'Forbidden');\n return;\n }\n\n const conflicts = await replicationHandler.masterWrite(useRows);\n\n res.setHeader('Content-Type', 'application/json');\n res.json(conflicts);\n });\n this.server.expressApp.get('/' + this.urlPath + '/pullStream', async (req, res) => {\n writeSSEHeaders(res);\n\n const authData = getFromMapOrThrow(authDataByRequest, req);\n const docDataMatcherStream = getDocAllowedMatcher(this, ensureNotFalsy(authData));\n const subscription = replicationHandler.masterChangeStream$.pipe(\n mergeMap(async (changes) => {\n /**\n * The auth-data might be expired\n * so we re-run the auth parsing each time\n * before emitting an event.\n */\n let authData: RxServerAuthData<AuthType>;\n try {\n authData = await server.authHandler(req.headers);\n } catch (err) {\n closeConnection(res, 401, 'Unauthorized');\n return null;\n }\n\n if (changes === 'RESYNC') {\n return changes;\n } else {\n const useDocs = changes.documents.filter(d => docDataMatcherStream(d as any));\n return {\n documents: useDocs,\n checkpoint: changes.checkpoint\n };\n }\n }),\n filter(f => f !== null && (f === 'RESYNC' || f.documents.length > 0))\n ).subscribe(filteredAndModified => {\n if (filteredAndModified === 'RESYNC') {\n res.write('data: ' + JSON.stringify(filteredAndModified) + '\\n\\n');\n } else {\n const responseDocuments = ensureNotFalsy(filteredAndModified).documents.map(d => removeServerOnlyFields(d as any));\n res.write('data: ' + JSON.stringify({ documents: responseDocuments, checkpoint: ensureNotFalsy(filteredAndModified).checkpoint }) + '\\n\\n');\n }\n\n });\n\n /**\n * @link https://youtu.be/0PcMuYGJPzM?si=Axkczx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,SAAS,CAACC,MAAM,GAAG,CAAC,CAAC,CACxE,CAAC,CAAC8C,SAAS,CAACC,mBAAmB,IAAI;MAC/B,IAAIA,mBAAmB,KAAK,QAAQ,EAAE;QAClChE,GAAG,CAACiE,KAAK,CAAC,QAAQ,GAAGC,IAAI,CAACC,SAAS,CAACH,mBAAmB,CAAC,GAAG,MAAM,CAAC;MACtE,CAAC,MAAM;QACH,IAAM3C,iBAAiB,GAAG,IAAAX,qBAAc,EAACsD,mBAAmB,CAAC,CAAChD,SAAS,CAACM,GAAG,CAACC,CAAC,IAAI9B,sBAAsB,CAAC8B,CAAQ,CAAC,CAAC;QAClHvB,GAAG,CAACiE,KAAK,CAAC,QAAQ,GAAGC,IAAI,CAACC,SAAS,CAAC;UAAEnD,SAAS,EAAEK,iBAAiB;UAAEK,UAAU,EAAE,IAAAhB,qBAAc,EAACsD,mBAAmB,CAAC,CAACtC;QAAW,CAAC,CAAC,GAAG,MAAM,CAAC;MAC/I;IAEJ,CAAC,CAAC;;IAEF;AACZ;AACA;IACY3B,GAAG,CAACqE,EAAE,CAAC,OAAO,EAAE,MAAM;MAClBhB,YAAY,CAACiB,WAAW,CAAC,CAAC;MAC1BrE,GAAG,CAACsE,GAAG,CAAC,CAAC;IACb,CAAC,CAAC;EACN,CAAC,CAAC;AACN,CAAC"}
|
|
1
|
+
{"version":3,"file":"endpoint-replication.js","names":["_core","require","_replicationWebsocket","_rxjs","_utils","_helper","RxServerReplicationEndpoint","exports","server","name","collection","queryModifier","changeValidator","serverOnlyFields","cors","type","adapter","setCors","join","blockPreviousVersionPaths","schema","version","urlPath","primaryPath","replicationHandler","getReplicationHandlerByCollection","database","authDataByRequest","addAuthMiddleware","authData","query","doesContainRegexQuerySelector","selector","Error","change","assumedMasterState","docContainsServerOnlyFields","newDocumentState","removeServerOnlyFields","removeServerOnlyFieldsMonad","mergeServerDocumentFields","mergeServerDocumentFieldsMonad","get","serverApp","req","res","getFromMapOrThrow","urlQuery","getRequestQuery","id","lwt","parseInt","limit","plainQuery","getChangedDocumentsSinceQuery","storageInstance","useQueryChanges","ensureNotFalsy","prepared","prepareQuery","jsonSchema","result","newCheckpoint","documents","length","lastOfArray","updatedAt","_meta","responseDocuments","map","d","setResponseHeader","endResponseJson","checkpoint","post","docDataMatcherWrite","getDocAllowedMatcher","rows","getRequestBody","ids","forEach","row","push","nonAllowedRow","find","closeConnection","hasInvalidChange","currentStateDocsArray","findDocumentsById","currentStateDocs","Map","set","useRows","isChangeValid","serverDoc","conflicts","masterWrite","setSSEHeaders","docDataMatcherStream","subscription","masterChangeStream$","pipe","mergeMap","changes","authHandler","getRequestHeaders","err","useDocs","filter","f","subscribe","filteredAndModified","responseWrite","JSON","stringify","onRequestClose","unsubscribe","endResponse"],"sources":["../../../../src/plugins/server/endpoint-replication.ts"],"sourcesContent":["import {\n FilledMangoQuery,\n RxCollection,\n RxReplicationHandler,\n RxReplicationWriteToMasterRow,\n RxStorageDefaultCheckpoint,\n StringKeys,\n prepareQuery,\n getChangedDocumentsSinceQuery,\n RxDocumentData\n} from 'rxdb/plugins/core';\nimport { getReplicationHandlerByCollection } from 'rxdb/plugins/replication-websocket';\nimport type { RxServer } from './rx-server.ts';\nimport type {\n RxServerAuthData,\n RxServerChangeValidator,\n RxServerEndpoint,\n RxServerQueryModifier\n} from './types.ts';\nimport { filter, mergeMap } from 'rxjs';\nimport {\n ensureNotFalsy,\n getFromMapOrThrow,\n lastOfArray\n} from 'rxdb/plugins/utils';\n\nimport {\n addAuthMiddleware,\n blockPreviousVersionPaths,\n docContainsServerOnlyFields,\n doesContainRegexQuerySelector,\n getDocAllowedMatcher,\n mergeServerDocumentFieldsMonad,\n removeServerOnlyFieldsMonad,\n setCors\n} from './helper.ts';\n\nexport type RxReplicationEndpointMessageType = {\n id: string;\n method: StringKeys<RxReplicationHandler<any, any>> | 'auth';\n params: any[];\n};\n\nexport class RxServerReplicationEndpoint<ServerAppType, AuthType, RxDocType> implements RxServerEndpoint<AuthType, RxDocType> {\n readonly type = 'replication';\n readonly urlPath: string;\n readonly changeValidator: RxServerChangeValidator<AuthType, RxDocType>;\n readonly queryModifier: RxServerQueryModifier<AuthType, RxDocType>;\n constructor(\n public readonly server: RxServer<ServerAppType, AuthType>,\n public readonly name: string,\n public readonly collection: RxCollection<RxDocType>,\n queryModifier: RxServerQueryModifier<AuthType, RxDocType>,\n changeValidator: RxServerChangeValidator<AuthType, RxDocType>,\n public readonly serverOnlyFields: string[],\n public readonly cors?: string,\n ) {\n const adapter = this.server.adapter;\n\n setCors(this.server, [this.name].join('/'), cors);\n blockPreviousVersionPaths(this.server, [this.name].join('/'), collection.schema.version);\n\n this.urlPath = [this.name, collection.schema.version].join('/');\n\n const primaryPath = this.collection.schema.primaryPath;\n const replicationHandler = getReplicationHandlerByCollection(this.server.database, collection.name);\n const authDataByRequest = addAuthMiddleware(\n this.server,\n this.urlPath\n );\n\n this.queryModifier = (authData, query) => {\n if (doesContainRegexQuerySelector(query.selector)) {\n throw new Error('$regex queries not allowed because of DOS-attacks');\n }\n return queryModifier(authData, query);\n }\n this.changeValidator = (authData, change) => {\n if (\n (change.assumedMasterState && docContainsServerOnlyFields(serverOnlyFields, change.assumedMasterState)) ||\n docContainsServerOnlyFields(serverOnlyFields, change.newDocumentState)\n ) {\n return false;\n }\n return changeValidator(authData, change);\n }\n const removeServerOnlyFields = removeServerOnlyFieldsMonad<RxDocType>(this.serverOnlyFields);\n const mergeServerDocumentFields = mergeServerDocumentFieldsMonad<RxDocType>(this.serverOnlyFields);\n\n this.server.adapter.get(this.server.serverApp, '/' + this.urlPath + '/pull', async (req: any, res: any) => {\n const authData = getFromMapOrThrow(authDataByRequest, req);\n\n const urlQuery = adapter.getRequestQuery(req);\n const id = urlQuery.id ? urlQuery.id as string : '';\n const lwt = urlQuery.lwt ? parseInt(urlQuery.lwt as any, 10) : 0;\n const limit = urlQuery.limit ? parseInt(urlQuery.limit as any, 10) : 1;\n const plainQuery = getChangedDocumentsSinceQuery<RxDocType, RxStorageDefaultCheckpoint>(\n this.collection.storageInstance,\n limit,\n { id, lwt }\n );\n const useQueryChanges: FilledMangoQuery<RxDocType> = this.queryModifier(\n ensureNotFalsy(authData as any),\n plainQuery\n );\n const prepared = prepareQuery<RxDocType>(\n this.collection.schema.jsonSchema,\n useQueryChanges\n );\n const result = await this.collection.storageInstance.query(prepared);\n\n const newCheckpoint = result.documents.length === 0 ? { id, lwt } : {\n id: ensureNotFalsy(lastOfArray(result.documents))[primaryPath],\n updatedAt: ensureNotFalsy(lastOfArray(result.documents))._meta.lwt\n };\n const responseDocuments = result.documents.map(d => removeServerOnlyFields(d));\n adapter.setResponseHeader(res, 'Content-Type', 'application/json');\n adapter.endResponseJson(res, {\n documents: responseDocuments,\n checkpoint: newCheckpoint\n });\n });\n\n this.server.adapter.post(this.server.serverApp, '/' + this.urlPath + '/push', async (req: any, res: any) => {\n const authData = getFromMapOrThrow(authDataByRequest, req);\n const docDataMatcherWrite = getDocAllowedMatcher(this, ensureNotFalsy(authData as any));\n const rows: RxReplicationWriteToMasterRow<RxDocType>[] = adapter.getRequestBody(req);\n const ids: string[] = [];\n rows.forEach(row => ids.push((row.newDocumentState as any)[primaryPath]));\n\n for (const row of rows) {\n // TODO remove this check\n if (row.assumedMasterState && (row.assumedMasterState as any)._meta) {\n throw new Error('body document contains meta!');\n }\n }\n\n // ensure all writes are allowed\n const nonAllowedRow = rows.find(row => {\n if (\n !docDataMatcherWrite(row.newDocumentState as any) ||\n (row.assumedMasterState && !docDataMatcherWrite(row.assumedMasterState as any))\n ) {\n return true;\n }\n });\n if (nonAllowedRow) {\n adapter.closeConnection(res, 403, 'Forbidden');\n return;\n }\n let hasInvalidChange = false;\n\n const currentStateDocsArray = await this.collection.storageInstance.findDocumentsById(ids, true);\n const currentStateDocs = new Map<string, RxDocumentData<RxDocType>>();\n currentStateDocsArray.forEach(d => currentStateDocs.set((d as any)[primaryPath], d));\n\n const useRows: typeof rows = rows.map((row) => {\n const id = (row.newDocumentState as any)[primaryPath];\n const isChangeValid = this.changeValidator(ensureNotFalsy(authData as any), {\n newDocumentState: removeServerOnlyFields(row.newDocumentState),\n assumedMasterState: removeServerOnlyFields(row.assumedMasterState)\n });\n if (!isChangeValid) {\n hasInvalidChange = true;\n }\n\n const serverDoc = currentStateDocs.get(id);\n return {\n newDocumentState: mergeServerDocumentFields(row.newDocumentState, serverDoc),\n assumedMasterState: mergeServerDocumentFields(row.assumedMasterState as any, serverDoc)\n } as typeof row;\n });\n if (hasInvalidChange) {\n adapter.closeConnection(res, 403, 'Forbidden');\n return;\n }\n\n const conflicts = await replicationHandler.masterWrite(useRows);\n\n adapter.setResponseHeader(res, 'Content-Type', 'application/json');\n adapter.endResponseJson(res, conflicts);\n });\n this.server.adapter.get(this.server.serverApp, '/' + this.urlPath + '/pullStream', async (req, res) => {\n adapter.setSSEHeaders(res);\n\n const authData = getFromMapOrThrow(authDataByRequest, req);\n const docDataMatcherStream = getDocAllowedMatcher(this, ensureNotFalsy(authData));\n const subscription = replicationHandler.masterChangeStream$.pipe(\n mergeMap(async (changes) => {\n /**\n * The auth-data might be expired\n * so we re-run the auth parsing each time\n * before emitting an event.\n */\n let authData: RxServerAuthData<AuthType>;\n try {\n authData = await server.authHandler(adapter.getRequestHeaders(req));\n } catch (err) {\n adapter.closeConnection(res, 401, 'Unauthorized');\n return null;\n }\n\n if (changes === 'RESYNC') {\n return changes;\n } else {\n const useDocs = changes.documents.filter(d => docDataMatcherStream(d as any));\n return {\n documents: useDocs,\n checkpoint: changes.checkpoint\n };\n }\n }),\n filter(f => f !== null && (f === 'RESYNC' || f.documents.length > 0))\n ).subscribe(filteredAndModified => {\n if (filteredAndModified === 'RESYNC') {\n adapter.responseWrite(res, 'data: ' + JSON.stringify(filteredAndModified) + '\\n\\n');\n } else {\n const responseDocuments = ensureNotFalsy(filteredAndModified).documents.map(d => removeServerOnlyFields(d as any));\n adapter.responseWrite(res, 'data: ' + JSON.stringify({ documents: responseDocuments, checkpoint: ensureNotFalsy(filteredAndModified).checkpoint }) + '\\n\\n');\n }\n\n });\n\n /**\n * @link https://youtu.be/0PcMuYGJPzM?si=AxkczxcMaUwhh8k9&t=363\n */\n adapter.onRequestClose(req, () => {\n subscription.unsubscribe();\n adapter.endResponse(res);\n });\n });\n }\n}\n"],"mappings":";;;;;;AAAA,IAAAA,KAAA,GAAAC,OAAA;AAWA,IAAAC,qBAAA,GAAAD,OAAA;AAQA,IAAAE,KAAA,GAAAF,OAAA;AACA,IAAAG,MAAA,GAAAH,OAAA;AAMA,IAAAI,OAAA,GAAAJ,OAAA;AASqB,IAQRK,2BAA2B,GAAAC,OAAA,CAAAD,2BAAA,GAKpC,SAAAA,4BACoBE,MAAyC,EACzCC,IAAY,EACZC,UAAmC,EACnDC,aAAyD,EACzDC,eAA6D,EAC7CC,gBAA0B,EAC1BC,IAAa,EAC/B;EAAA,KAZOC,IAAI,GAAG,aAAa;EAAA,KAKTP,MAAyC,GAAzCA,MAAyC;EAAA,KACzCC,IAAY,GAAZA,IAAY;EAAA,KACZC,UAAmC,GAAnCA,UAAmC;EAAA,KAGnCG,gBAA0B,GAA1BA,gBAA0B;EAAA,KAC1BC,IAAa,GAAbA,IAAa;EAE7B,IAAME,OAAO,GAAG,IAAI,CAACR,MAAM,CAACQ,OAAO;EAEnC,IAAAC,eAAO,EAAC,IAAI,CAACT,MAAM,EAAE,CAAC,IAAI,CAACC,IAAI,CAAC,CAACS,IAAI,CAAC,GAAG,CAAC,EAAEJ,IAAI,CAAC;EACjD,IAAAK,iCAAyB,EAAC,IAAI,CAACX,MAAM,EAAE,CAAC,IAAI,CAACC,IAAI,CAAC,CAACS,IAAI,CAAC,GAAG,CAAC,EAAER,UAAU,CAACU,MAAM,CAACC,OAAO,CAAC;EAExF,IAAI,CAACC,OAAO,GAAG,CAAC,IAAI,CAACb,IAAI,EAAEC,UAAU,CAACU,MAAM,CAACC,OAAO,CAAC,CAACH,IAAI,CAAC,GAAG,CAAC;EAE/D,IAAMK,WAAW,GAAG,IAAI,CAAC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