dexie-cloud-addon 1.0.0-beta.10 → 1.0.0-beta.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (34) hide show
  1. package/dist/modern/dexie-cloud-addon.js +189 -158
  2. package/dist/modern/dexie-cloud-addon.js.map +1 -1
  3. package/dist/modern/dexie-cloud-addon.min.js +1 -1
  4. package/dist/modern/dexie-cloud-addon.min.js.map +1 -1
  5. package/dist/modern/service-worker.js +1208 -1176
  6. package/dist/modern/service-worker.js.map +1 -1
  7. package/dist/modern/service-worker.min.js +1 -1
  8. package/dist/modern/service-worker.min.js.map +1 -1
  9. package/dist/module-es5/dexie-cloud-addon.js +259 -207
  10. package/dist/module-es5/dexie-cloud-addon.js.map +1 -1
  11. package/dist/module-es5/dexie-cloud-addon.min.js +1 -1
  12. package/dist/module-es5/dexie-cloud-addon.min.js.map +1 -1
  13. package/dist/types/WSObservable.d.ts +11 -6
  14. package/dist/types/WebSocketStatus.d.ts +1 -0
  15. package/dist/types/helpers/BroadcastedLocalEvent.d.ts +8 -0
  16. package/dist/types/helpers/visibleState.d.ts +1 -0
  17. package/dist/types/sync/syncServerToClientOnly.d.ts +3 -0
  18. package/dist/types/types/CloudConnectionStatus.d.ts +0 -0
  19. package/dist/types/types/ConnectionStatus.d.ts +0 -0
  20. package/dist/types/types/LoginState.d.ts +41 -0
  21. package/dist/types/types/SyncConnectionStatus.d.ts +1 -0
  22. package/dist/types/types/SyncFlowStatus.d.ts +6 -0
  23. package/dist/types/types/SyncStatus.d.ts +6 -0
  24. package/dist/umd/dexie-cloud-addon.js +259 -207
  25. package/dist/umd/dexie-cloud-addon.js.map +1 -1
  26. package/dist/umd/dexie-cloud-addon.min.js +1 -1
  27. package/dist/umd/dexie-cloud-addon.min.js.map +1 -1
  28. package/dist/umd/service-worker.js +1208 -1176
  29. package/dist/umd/service-worker.js.map +1 -1
  30. package/dist/umd/service-worker.min.js +1 -1
  31. package/dist/umd/service-worker.min.js.map +1 -1
  32. package/dist/umd-modern/dexie-cloud-addon.js +188 -157
  33. package/dist/umd-modern/dexie-cloud-addon.js.map +1 -1
  34. package/package.json +2 -2
@@ -1 +1 @@
1
- {"version":3,"file":"service-worker.js","sources":["../../src/authentication/UNAUTHORIZED_USER.ts","../../src/helpers/SWBroadcastChannel.ts","../../src/helpers/BroadcastedAndLocalEvent.ts","../../node_modules/rxjs/node_modules/tslib/tslib.es6.js","../../node_modules/rxjs/src/internal/util/isFunction.ts","../../node_modules/rxjs/src/internal/config.ts","../../node_modules/rxjs/src/internal/util/hostReportError.ts","../../node_modules/rxjs/src/internal/Observer.ts","../../node_modules/rxjs/src/internal/util/isArray.ts","../../node_modules/rxjs/src/internal/util/isObject.ts","../../node_modules/rxjs/src/internal/util/UnsubscriptionError.ts","../../node_modules/rxjs/src/internal/Subscription.ts","../../node_modules/rxjs/src/internal/symbol/rxSubscriber.ts","../../node_modules/rxjs/src/internal/Subscriber.ts","../../node_modules/rxjs/src/internal/util/canReportError.ts","../../node_modules/rxjs/src/internal/util/toSubscriber.ts","../../node_modules/rxjs/src/internal/symbol/observable.ts","../../node_modules/rxjs/src/internal/util/identity.ts","../../node_modules/rxjs/src/internal/util/pipe.ts","../../node_modules/rxjs/src/internal/Observable.ts","../../node_modules/rxjs/src/internal/util/subscribeToArray.ts","../../node_modules/rxjs/src/internal/util/subscribeToPromise.ts","../../node_modules/rxjs/src/internal/symbol/iterator.ts","../../node_modules/rxjs/src/internal/util/subscribeToIterable.ts","../../node_modules/rxjs/src/internal/util/subscribeToObservable.ts","../../node_modules/rxjs/src/internal/util/isArrayLike.ts","../../node_modules/rxjs/src/internal/util/isPromise.ts","../../node_modules/rxjs/src/internal/util/subscribeTo.ts","../../node_modules/rxjs/src/internal/innerSubscribe.ts","../../node_modules/rxjs/src/internal/scheduler/Action.ts","../../node_modules/rxjs/src/internal/scheduler/AsyncAction.ts","../../node_modules/rxjs/src/internal/Scheduler.ts","../../node_modules/rxjs/src/internal/scheduler/AsyncScheduler.ts","../../node_modules/rxjs/src/internal/scheduler/async.ts","../../node_modules/rxjs/src/internal/util/isScheduler.ts","../../node_modules/rxjs/src/internal/operators/catchError.ts","../../node_modules/rxjs/src/internal/scheduled/scheduleArray.ts","../../node_modules/rxjs/src/internal/observable/fromArray.ts","../../node_modules/rxjs/src/internal/scheduled/scheduleObservable.ts","../../node_modules/rxjs/src/internal/scheduled/schedulePromise.ts","../../node_modules/rxjs/src/internal/scheduled/scheduleIterable.ts","../../node_modules/rxjs/src/internal/util/isInteropObservable.ts","../../node_modules/rxjs/src/internal/util/isIterable.ts","../../node_modules/rxjs/src/internal/scheduled/scheduled.ts","../../node_modules/rxjs/src/internal/observable/from.ts","../../node_modules/rxjs/src/internal/observable/of.ts","../../node_modules/rxjs/src/internal/operators/map.ts","../../node_modules/rxjs/src/internal/operators/mergeMap.ts","../../node_modules/rxjs/src/internal/operators/mergeAll.ts","../../node_modules/rxjs/src/internal/operators/concatAll.ts","../../node_modules/rxjs/src/internal/observable/concat.ts","../../node_modules/rxjs/src/internal/operators/debounceTime.ts","../../node_modules/rxjs/src/internal/util/isDate.ts","../../node_modules/rxjs/src/internal/observable/empty.ts","../../node_modules/rxjs/src/internal/observable/throwError.ts","../../node_modules/rxjs/src/internal/Notification.ts","../../node_modules/rxjs/src/internal/operators/delay.ts","../../node_modules/rxjs/src/internal/operators/distinctUntilChanged.ts","../../node_modules/rxjs/src/internal/util/ArgumentOutOfRangeError.ts","../../node_modules/rxjs/src/internal/operators/filter.ts","../../node_modules/rxjs/src/internal/operators/take.ts","../../node_modules/rxjs/src/internal/operators/skip.ts","../../node_modules/rxjs/src/internal/operators/startWith.ts","../../node_modules/rxjs/src/internal/operators/switchMap.ts","../../node_modules/rxjs/src/internal/util/noop.ts","../../node_modules/rxjs/src/internal/operators/tap.ts","../../node_modules/rxjs/src/internal/util/TimeoutError.ts","../../node_modules/rxjs/src/internal/operators/timeoutWith.ts","../../node_modules/rxjs/src/internal/operators/timeout.ts","../../node_modules/dreambase-library/dist/typeson-simplified/TypesonSimplified.js","../../node_modules/dreambase-library/dist/typeson-simplified/BisonBinaryTypes.js","../../node_modules/dreambase-library/dist/typeson-simplified/types/number.js","../../node_modules/dreambase-library/dist/typeson-simplified/types/bigint.js","../../node_modules/dreambase-library/dist/typeson-simplified/types/Date.js","../../node_modules/dreambase-library/dist/typeson-simplified/types/Set.js","../../node_modules/dreambase-library/dist/typeson-simplified/types/Map.js","../../node_modules/dreambase-library/dist/common/_global.js","../../node_modules/dreambase-library/dist/typeson-simplified/types/TypedArray.js","../../node_modules/dreambase-library/dist/common/base64.js","../../node_modules/dreambase-library/dist/common/b64lex.js","../../node_modules/dreambase-library/dist/typeson-simplified/types/ArrayBuffer.js","../../node_modules/dreambase-library/dist/typeson-simplified/FakeBlob.js","../../node_modules/dreambase-library/dist/typeson-simplified/readBlobSync.js","../../node_modules/dreambase-library/dist/typeson-simplified/string2arraybuffer.js","../../node_modules/dreambase-library/dist/typeson-simplified/types/Blob.js","../../node_modules/dreambase-library/dist/typeson-simplified/presets/builtin.js","../../node_modules/dreambase-library/dist/typeson-simplified/Bison.js","../../node_modules/dreambase-library/dist/typeson-simplified/types/undefined.js","../../src/TSON.ts","../../src/sync/registerSyncEvent.ts","../../src/sync/triggerSync.ts","../../src/helpers/computeRealmSetHash.ts","../../src/helpers/getSyncableTables.ts","../../src/helpers/getMutationTable.ts","../../src/helpers/getTableFromMutationTable.ts","../../src/sync/listClientChanges.ts","../../node_modules/universal-imports/index-browser.mjs","../../node_modules/dexie-cloud-common/dist/utils.js","../../node_modules/dexie-cloud-common/dist/validation/isValidSyncableID.js","../../node_modules/dexie-cloud-common/dist/change-processing/applyOperation.js","../../node_modules/dexie-cloud-common/dist/change-processing/applyOperations.js","../../node_modules/dexie-cloud-common/dist/change-processing/subtractChanges.js","../../node_modules/dexie-cloud-common/dist/change-processing/toDBOperationSet.js","../../node_modules/dexie-cloud-common/dist/getDbNameFromDbUrl.js","../../src/sync/listSyncifiedChanges.ts","../../src/sync/getTablesToSyncify.ts","../../src/authentication/interactWithUser.ts","../../src/authentication/authenticate.ts","../../src/errors/HttpError.ts","../../src/sync/syncWithServer.ts","../../src/sync/modifyLocalObjectsWithNewUserId.ts","../../src/helpers/bulkUpdate.ts","../../src/helpers/CancelToken.ts","../../src/sync/isOnline.ts","../../src/sync/updateBaseRevs.ts","../../src/sync/getLatestRevisionsPerTable.ts","../../src/sync/sync.ts","../../src/sync/messagesFromServerQueue.ts","../../src/db/DexieCloudDB.ts","../../src/authentication/AuthPersistedContext.ts","../../src/authentication/otpFetchTokenCallback.ts","../../src/authentication/setCurrentUser.ts","../../src/authentication/login.ts","../../src/isFirefox.ts","../../src/isSafari.ts","../../src/DISABLE_SERVICEWORKER_STRATEGY.ts","../../src/helpers/dbOnClosed.ts","../../src/helpers/IS_SERVICE_WORKER.ts","../../src/helpers/throwVersionIncrementNeeded.ts","../../src/middlewares/createIdGenerationMiddleware.ts","../../src/middlewares/createImplicitPropSetterMiddleware.ts","../../src/helpers/randomString.ts","../../src/helpers/allSettled.ts","../../src/middleware-helpers/guardedTable.ts","../../src/middlewares/outstandingTransaction.ts","../../src/middlewares/createMutationTrackingMiddleware.ts","../../src/overrideParseStoresSpec.ts","../../src/helpers/date-constants.ts","../../src/sync/myId.ts","../../src/sync/performGuardedJob.ts","../../src/performInitialSync.ts","../../src/userIsActive.ts","../../src/authentication/TokenExpiredError.ts","../../src/WSObservable.ts","../../src/sync/connectWebSocket.ts","../../src/sync/isSyncNeeded.ts","../../src/sync/syncIfPossible.ts","../../src/sync/LocalSyncWorker.ts","../../src/updateSchemaFromOptions.ts","../../src/verifySchema.ts","../../node_modules/preact/src/options.js","../../node_modules/preact/src/component.js","../../node_modules/preact/src/constants.js","../../node_modules/preact/src/util.js","../../node_modules/preact/src/create-element.js","../../node_modules/preact/src/diff/children.js","../../node_modules/preact/src/diff/props.js","../../node_modules/preact/src/diff/index.js","../../node_modules/preact/src/render.js","../../node_modules/preact/src/diff/catch-error.js","../../node_modules/preact/src/create-context.js","../../src/default-ui/Styles.ts","../../src/default-ui/Dialog.tsx","../../node_modules/preact/hooks/src/index.js","../../src/helpers/resolveText.ts","../../src/default-ui/LoginDialog.tsx","../../src/default-ui/index.tsx","../../src/computeSyncState.ts","../../src/dexie-cloud-client.ts","../../src/service-worker.ts"],"sourcesContent":["import { UserLogin } from '../db/entities/UserLogin';\n\nexport const UNAUTHORIZED_USER: UserLogin = {\n userId: \"unauthorized\",\n name: \"Unauthorized\",\n claims: {\n sub: \"unauthorized\",\n },\n lastLogin: new Date(0)\n}\n\ntry {\n Object.freeze(UNAUTHORIZED_USER);\n Object.freeze(UNAUTHORIZED_USER.claims);\n} catch {}\n","const swHolder: { registration?: ServiceWorkerRegistration } = {};\nconst swContainer = self.document && navigator.serviceWorker; // self.document is to verify we're not the SW ourself\nif (swContainer)\n swContainer.ready.then(\n (registration) => (swHolder.registration = registration)\n );\n\nif (typeof self !== 'undefined' && 'clients' in self && !self.document) {\n // We are the service worker. Propagate messages to all our clients.\n addEventListener('message', (ev: any) => {\n if (ev.data?.type?.startsWith('sw-broadcast-')) {\n [...self['clients'].matchAll({ includeUncontrolled: true })].forEach(\n (client) => client.id !== ev.source?.id && client.postMessage(ev.data)\n );\n }\n });\n}\n\nexport class SWBroadcastChannel {\n name: string;\n constructor(name: string) {\n this.name = name;\n }\n subscribe(listener: (message: any) => void) {\n if (!swContainer) return ()=>{};\n const forwarder = (ev: MessageEvent) => {\n if (ev.data?.type === `sw-broadcast-${this.name}`) {\n listener(ev.data.message);\n }\n };\n swContainer.addEventListener('message', forwarder);\n return () =>\n swContainer.removeEventListener('message', forwarder);\n }\n postMessage(message: any) {\n if (typeof self['clients'] === 'object') {\n // We're a service worker. Propagate to our browser clients.\n [...self['clients'].matchAll({ includeUncontrolled: true })].forEach(\n (client) =>\n client.postMessage({\n type: `sw-broadcast-${this.name}`,\n message\n })\n );\n } else if (swHolder.registration) {\n // We're a client (browser window or other worker)\n // Post to SW so it can repost to all its clients and to itself\n swHolder.registration.active?.postMessage({\n type: `sw-broadcast-${this.name}`,\n message\n });\n }\n }\n}\n","import { Observable } from \"rxjs\";\nimport { SWBroadcastChannel } from \"./SWBroadcastChannel\";\n\nexport class BroadcastedAndLocalEvent<T> extends Observable<T>{\n name: string;\n bc: BroadcastChannel | SWBroadcastChannel\n\n constructor(name: string) {\n const bc = typeof BroadcastChannel === \"undefined\"\n ? new SWBroadcastChannel(name) : new BroadcastChannel(name);\n super(subscriber => {\n function onCustomEvent(ev: CustomEvent) {\n subscriber.next(ev.detail);\n }\n function onMessageEvent(ev: MessageEvent) {\n console.debug(\"BroadcastedAndLocalEvent: onMessageEvent\", ev);\n subscriber.next(ev.data);\n }\n let unsubscribe: ()=>void;\n self.addEventListener(`lbc-${name}`, onCustomEvent); \n if (bc instanceof SWBroadcastChannel) {\n unsubscribe = bc.subscribe(message => subscriber.next(message));\n } else {\n console.debug(\"BroadcastedAndLocalEvent: bc.addEventListener()\", name, \"bc is a\", bc);\n bc.addEventListener(\"message\", onMessageEvent);\n }\n return () => {\n self.removeEventListener(`lbc-${name}`, onCustomEvent);\n if (bc instanceof SWBroadcastChannel) {\n unsubscribe!();\n } else {\n bc.removeEventListener(\"message\", onMessageEvent);\n }\n }\n });\n this.name = name;\n this.bc = bc;\n }\n\n next(message: T) {\n console.debug(\"BroadcastedAndLocalEvent: bc.postMessage()\", {...message}, \"bc is a\", this.bc);\n this.bc.postMessage(message);\n const ev = new CustomEvent(`lbc-${this.name}`, { detail: message });\n self.dispatchEvent(ev);\n }\n}\n","/*! *****************************************************************************\r\nCopyright (c) Microsoft Corporation.\r\n\r\nPermission to use, copy, modify, and/or distribute this software for any\r\npurpose with or without fee is hereby granted.\r\n\r\nTHE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH\r\nREGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY\r\nAND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,\r\nINDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM\r\nLOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR\r\nOTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR\r\nPERFORMANCE OF THIS SOFTWARE.\r\n***************************************************************************** */\r\n/* global Reflect, Promise */\r\n\r\nvar extendStatics = function(d, b) {\r\n extendStatics = Object.setPrototypeOf ||\r\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\r\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\r\n return extendStatics(d, b);\r\n};\r\n\r\nexport function __extends(d, b) {\r\n extendStatics(d, b);\r\n function __() { this.constructor = d; }\r\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\r\n}\r\n\r\nexport var __assign = function() {\r\n __assign = Object.assign || function __assign(t) {\r\n for (var s, i = 1, n = arguments.length; i < n; i++) {\r\n s = arguments[i];\r\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];\r\n }\r\n return t;\r\n }\r\n return __assign.apply(this, arguments);\r\n}\r\n\r\nexport function __rest(s, e) {\r\n var t = {};\r\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\r\n t[p] = s[p];\r\n if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\r\n for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {\r\n if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))\r\n t[p[i]] = s[p[i]];\r\n }\r\n return t;\r\n}\r\n\r\nexport function __decorate(decorators, target, key, desc) {\r\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\r\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\r\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\r\n return c > 3 && r && Object.defineProperty(target, key, r), r;\r\n}\r\n\r\nexport function __param(paramIndex, decorator) {\r\n return function (target, key) { decorator(target, key, paramIndex); }\r\n}\r\n\r\nexport function __metadata(metadataKey, metadataValue) {\r\n if (typeof Reflect === \"object\" && typeof Reflect.metadata === \"function\") return Reflect.metadata(metadataKey, metadataValue);\r\n}\r\n\r\nexport function __awaiter(thisArg, _arguments, P, generator) {\r\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\r\n return new (P || (P = Promise))(function (resolve, reject) {\r\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\r\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\r\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\r\n step((generator = generator.apply(thisArg, _arguments || [])).next());\r\n });\r\n}\r\n\r\nexport function __generator(thisArg, body) {\r\n var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;\r\n return g = { next: verb(0), \"throw\": verb(1), \"return\": verb(2) }, typeof Symbol === \"function\" && (g[Symbol.iterator] = function() { return this; }), g;\r\n function verb(n) { return function (v) { return step([n, v]); }; }\r\n function step(op) {\r\n if (f) throw new TypeError(\"Generator is already executing.\");\r\n while (_) try {\r\n if (f = 1, y && (t = op[0] & 2 ? y[\"return\"] : op[0] ? y[\"throw\"] || ((t = y[\"return\"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;\r\n if (y = 0, t) op = [op[0] & 2, t.value];\r\n switch (op[0]) {\r\n case 0: case 1: t = op; break;\r\n case 4: _.label++; return { value: op[1], done: false };\r\n case 5: _.label++; y = op[1]; op = [0]; continue;\r\n case 7: op = _.ops.pop(); _.trys.pop(); continue;\r\n default:\r\n if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\r\n if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\r\n if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\r\n if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\r\n if (t[2]) _.ops.pop();\r\n _.trys.pop(); continue;\r\n }\r\n op = body.call(thisArg, _);\r\n } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\r\n if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\r\n }\r\n}\r\n\r\nexport function __createBinding(o, m, k, k2) {\r\n if (k2 === undefined) k2 = k;\r\n o[k2] = m[k];\r\n}\r\n\r\nexport function __exportStar(m, exports) {\r\n for (var p in m) if (p !== \"default\" && !exports.hasOwnProperty(p)) exports[p] = m[p];\r\n}\r\n\r\nexport function __values(o) {\r\n var s = typeof Symbol === \"function\" && Symbol.iterator, m = s && o[s], i = 0;\r\n if (m) return m.call(o);\r\n if (o && typeof o.length === \"number\") return {\r\n next: function () {\r\n if (o && i >= o.length) o = void 0;\r\n return { value: o && o[i++], done: !o };\r\n }\r\n };\r\n throw new TypeError(s ? \"Object is not iterable.\" : \"Symbol.iterator is not defined.\");\r\n}\r\n\r\nexport function __read(o, n) {\r\n var m = typeof Symbol === \"function\" && o[Symbol.iterator];\r\n if (!m) return o;\r\n var i = m.call(o), r, ar = [], e;\r\n try {\r\n while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);\r\n }\r\n catch (error) { e = { error: error }; }\r\n finally {\r\n try {\r\n if (r && !r.done && (m = i[\"return\"])) m.call(i);\r\n }\r\n finally { if (e) throw e.error; }\r\n }\r\n return ar;\r\n}\r\n\r\nexport function __spread() {\r\n for (var ar = [], i = 0; i < arguments.length; i++)\r\n ar = ar.concat(__read(arguments[i]));\r\n return ar;\r\n}\r\n\r\nexport function __spreadArrays() {\r\n for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;\r\n for (var r = Array(s), k = 0, i = 0; i < il; i++)\r\n for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)\r\n r[k] = a[j];\r\n return r;\r\n};\r\n\r\nexport function __await(v) {\r\n return this instanceof __await ? (this.v = v, this) : new __await(v);\r\n}\r\n\r\nexport function __asyncGenerator(thisArg, _arguments, generator) {\r\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\r\n var g = generator.apply(thisArg, _arguments || []), i, q = [];\r\n return i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i;\r\n function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }\r\n function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }\r\n function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }\r\n function fulfill(value) { resume(\"next\", value); }\r\n function reject(value) { resume(\"throw\", value); }\r\n function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }\r\n}\r\n\r\nexport function __asyncDelegator(o) {\r\n var i, p;\r\n return i = {}, verb(\"next\"), verb(\"throw\", function (e) { throw e; }), verb(\"return\"), i[Symbol.iterator] = function () { return this; }, i;\r\n function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === \"return\" } : f ? f(v) : v; } : f; }\r\n}\r\n\r\nexport function __asyncValues(o) {\r\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\r\n var m = o[Symbol.asyncIterator], i;\r\n return m ? m.call(o) : (o = typeof __values === \"function\" ? __values(o) : o[Symbol.iterator](), i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i);\r\n function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }\r\n function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }\r\n}\r\n\r\nexport function __makeTemplateObject(cooked, raw) {\r\n if (Object.defineProperty) { Object.defineProperty(cooked, \"raw\", { value: raw }); } else { cooked.raw = raw; }\r\n return cooked;\r\n};\r\n\r\nexport function __importStar(mod) {\r\n if (mod && mod.__esModule) return mod;\r\n var result = {};\r\n if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];\r\n result.default = mod;\r\n return result;\r\n}\r\n\r\nexport function __importDefault(mod) {\r\n return (mod && mod.__esModule) ? mod : { default: mod };\r\n}\r\n\r\nexport function __classPrivateFieldGet(receiver, privateMap) {\r\n if (!privateMap.has(receiver)) {\r\n throw new TypeError(\"attempted to get private field on non-instance\");\r\n }\r\n return privateMap.get(receiver);\r\n}\r\n\r\nexport function __classPrivateFieldSet(receiver, privateMap, value) {\r\n if (!privateMap.has(receiver)) {\r\n throw new TypeError(\"attempted to set private field on non-instance\");\r\n }\r\n privateMap.set(receiver, value);\r\n return value;\r\n}\r\n","export function isFunction(x: any): x is Function {\n return typeof x === 'function';\n}\n","let _enable_super_gross_mode_that_will_cause_bad_things = false;\n\n/**\n * The global configuration object for RxJS, used to configure things\n * like what Promise contructor should used to create Promises\n */\nexport const config = {\n /**\n * The promise constructor used by default for methods such as\n * {@link toPromise} and {@link forEach}\n */\n Promise: undefined as PromiseConstructorLike,\n\n /**\n * If true, turns on synchronous error rethrowing, which is a deprecated behavior\n * in v6 and higher. This behavior enables bad patterns like wrapping a subscribe\n * call in a try/catch block. It also enables producer interference, a nasty bug\n * where a multicast can be broken for all observers by a downstream consumer with\n * an unhandled error. DO NOT USE THIS FLAG UNLESS IT'S NEEDED TO BY TIME\n * FOR MIGRATION REASONS.\n */\n set useDeprecatedSynchronousErrorHandling(value: boolean) {\n if (value) {\n const error = new Error();\n console.warn('DEPRECATED! RxJS was set to use deprecated synchronous error handling behavior by code at: \\n' + error.stack);\n } else if (_enable_super_gross_mode_that_will_cause_bad_things) {\n console.log('RxJS: Back to a better error behavior. Thank you. <3');\n }\n _enable_super_gross_mode_that_will_cause_bad_things = value;\n },\n\n get useDeprecatedSynchronousErrorHandling() {\n return _enable_super_gross_mode_that_will_cause_bad_things;\n },\n};\n","/**\n * Throws an error on another job so that it's picked up by the runtime's\n * uncaught error handling mechanism.\n * @param err the error to throw\n */\nexport function hostReportError(err: any) {\n setTimeout(() => { throw err; }, 0);\n}","import { Observer } from './types';\nimport { config } from './config';\nimport { hostReportError } from './util/hostReportError';\n\nexport const empty: Observer<any> = {\n closed: true,\n next(value: any): void { /* noop */},\n error(err: any): void {\n if (config.useDeprecatedSynchronousErrorHandling) {\n throw err;\n } else {\n hostReportError(err);\n }\n },\n complete(): void { /*noop*/ }\n};\n","export const isArray = (() => Array.isArray || (<T>(x: any): x is T[] => x && typeof x.length === 'number'))();\n","export function isObject(x: any): x is Object {\n return x !== null && typeof x === 'object';\n}\n","export interface UnsubscriptionError extends Error {\n readonly errors: any[];\n}\n\nexport interface UnsubscriptionErrorCtor {\n new(errors: any[]): UnsubscriptionError;\n}\n\nconst UnsubscriptionErrorImpl = (() => {\n function UnsubscriptionErrorImpl(this: any, errors: any[]) {\n Error.call(this);\n this.message = errors ?\n `${errors.length} errors occurred during unsubscription:\n${errors.map((err, i) => `${i + 1}) ${err.toString()}`).join('\\n ')}` : '';\n this.name = 'UnsubscriptionError';\n this.errors = errors;\n return this;\n }\n\n UnsubscriptionErrorImpl.prototype = Object.create(Error.prototype);\n\n return UnsubscriptionErrorImpl;\n})();\n\n/**\n * An error thrown when one or more errors have occurred during the\n * `unsubscribe` of a {@link Subscription}.\n */\nexport const UnsubscriptionError: UnsubscriptionErrorCtor = UnsubscriptionErrorImpl as any;","import { isArray } from './util/isArray';\nimport { isObject } from './util/isObject';\nimport { isFunction } from './util/isFunction';\nimport { UnsubscriptionError } from './util/UnsubscriptionError';\nimport { SubscriptionLike, TeardownLogic } from './types';\n\n/**\n * Represents a disposable resource, such as the execution of an Observable. A\n * Subscription has one important method, `unsubscribe`, that takes no argument\n * and just disposes the resource held by the subscription.\n *\n * Additionally, subscriptions may be grouped together through the `add()`\n * method, which will attach a child Subscription to the current Subscription.\n * When a Subscription is unsubscribed, all its children (and its grandchildren)\n * will be unsubscribed as well.\n *\n * @class Subscription\n */\nexport class Subscription implements SubscriptionLike {\n /** @nocollapse */\n public static EMPTY: Subscription = (function(empty: any) {\n empty.closed = true;\n return empty;\n }(new Subscription()));\n\n /**\n * A flag to indicate whether this Subscription has already been unsubscribed.\n * @type {boolean}\n */\n public closed: boolean = false;\n\n /** @internal */\n protected _parentOrParents: Subscription | Subscription[] = null;\n /** @internal */\n private _subscriptions: SubscriptionLike[] = null;\n\n /**\n * @param {function(): void} [unsubscribe] A function describing how to\n * perform the disposal of resources when the `unsubscribe` method is called.\n */\n constructor(unsubscribe?: () => void) {\n if (unsubscribe) {\n (this as any)._ctorUnsubscribe = true;\n (this as any)._unsubscribe = unsubscribe;\n }\n }\n\n /**\n * Disposes the resources held by the subscription. May, for instance, cancel\n * an ongoing Observable execution or cancel any other type of work that\n * started when the Subscription was created.\n * @return {void}\n */\n unsubscribe(): void {\n let errors: any[];\n\n if (this.closed) {\n return;\n }\n\n let { _parentOrParents, _ctorUnsubscribe, _unsubscribe, _subscriptions } = (this as any);\n\n this.closed = true;\n this._parentOrParents = null;\n // null out _subscriptions first so any child subscriptions that attempt\n // to remove themselves from this subscription will noop\n this._subscriptions = null;\n\n if (_parentOrParents instanceof Subscription) {\n _parentOrParents.remove(this);\n } else if (_parentOrParents !== null) {\n for (let index = 0; index < _parentOrParents.length; ++index) {\n const parent = _parentOrParents[index];\n parent.remove(this);\n }\n }\n\n if (isFunction(_unsubscribe)) {\n // It's only possible to null _unsubscribe - to release the reference to\n // any teardown function passed in the constructor - if the property was\n // actually assigned in the constructor, as there are some classes that\n // are derived from Subscriber (which derives from Subscription) that\n // implement an _unsubscribe method as a mechanism for obtaining\n // unsubscription notifications and some of those subscribers are\n // recycled. Also, in some of those subscribers, _unsubscribe switches\n // from a prototype method to an instance property - see notifyNext in\n // RetryWhenSubscriber.\n if (_ctorUnsubscribe) {\n (this as any)._unsubscribe = undefined;\n }\n try {\n _unsubscribe.call(this);\n } catch (e) {\n errors = e instanceof UnsubscriptionError ? flattenUnsubscriptionErrors(e.errors) : [e];\n }\n }\n\n if (isArray(_subscriptions)) {\n let index = -1;\n let len = _subscriptions.length;\n\n while (++index < len) {\n const sub = _subscriptions[index];\n if (isObject(sub)) {\n try {\n sub.unsubscribe();\n } catch (e) {\n errors = errors || [];\n if (e instanceof UnsubscriptionError) {\n errors = errors.concat(flattenUnsubscriptionErrors(e.errors));\n } else {\n errors.push(e);\n }\n }\n }\n }\n }\n\n if (errors) {\n throw new UnsubscriptionError(errors);\n }\n }\n\n /**\n * Adds a tear down to be called during the unsubscribe() of this\n * Subscription. Can also be used to add a child subscription.\n *\n * If the tear down being added is a subscription that is already\n * unsubscribed, is the same reference `add` is being called on, or is\n * `Subscription.EMPTY`, it will not be added.\n *\n * If this subscription is already in an `closed` state, the passed\n * tear down logic will be executed immediately.\n *\n * When a parent subscription is unsubscribed, any child subscriptions that were added to it are also unsubscribed.\n *\n * @param {TeardownLogic} teardown The additional logic to execute on\n * teardown.\n * @return {Subscription} Returns the Subscription used or created to be\n * added to the inner subscriptions list. This Subscription can be used with\n * `remove()` to remove the passed teardown logic from the inner subscriptions\n * list.\n */\n add(teardown: TeardownLogic): Subscription {\n let subscription = (<Subscription>teardown);\n\n if (!teardown) {\n return Subscription.EMPTY;\n }\n\n switch (typeof teardown) {\n case 'function':\n subscription = new Subscription(<(() => void)>teardown);\n case 'object':\n if (subscription === this || subscription.closed || typeof subscription.unsubscribe !== 'function') {\n // This also covers the case where `subscription` is `Subscription.EMPTY`, which is always in `closed` state.\n return subscription;\n } else if (this.closed) {\n subscription.unsubscribe();\n return subscription;\n } else if (!(subscription instanceof Subscription)) {\n const tmp = subscription;\n subscription = new Subscription();\n subscription._subscriptions = [tmp];\n }\n break;\n default: {\n throw new Error('unrecognized teardown ' + teardown + ' added to Subscription.');\n }\n }\n\n // Add `this` as parent of `subscription` if that's not already the case.\n let { _parentOrParents } = subscription;\n if (_parentOrParents === null) {\n // If we don't have a parent, then set `subscription._parents` to\n // the `this`, which is the common case that we optimize for.\n subscription._parentOrParents = this;\n } else if (_parentOrParents instanceof Subscription) {\n if (_parentOrParents === this) {\n // The `subscription` already has `this` as a parent.\n return subscription;\n }\n // If there's already one parent, but not multiple, allocate an\n // Array to store the rest of the parent Subscriptions.\n subscription._parentOrParents = [_parentOrParents, this];\n } else if (_parentOrParents.indexOf(this) === -1) {\n // Only add `this` to the _parentOrParents list if it's not already there.\n _parentOrParents.push(this);\n } else {\n // The `subscription` already has `this` as a parent.\n return subscription;\n }\n\n // Optimize for the common case when adding the first subscription.\n const subscriptions = this._subscriptions;\n if (subscriptions === null) {\n this._subscriptions = [subscription];\n } else {\n subscriptions.push(subscription);\n }\n\n return subscription;\n }\n\n /**\n * Removes a Subscription from the internal list of subscriptions that will\n * unsubscribe during the unsubscribe process of this Subscription.\n * @param {Subscription} subscription The subscription to remove.\n * @return {void}\n */\n remove(subscription: Subscription): void {\n const subscriptions = this._subscriptions;\n if (subscriptions) {\n const subscriptionIndex = subscriptions.indexOf(subscription);\n if (subscriptionIndex !== -1) {\n subscriptions.splice(subscriptionIndex, 1);\n }\n }\n }\n}\n\nfunction flattenUnsubscriptionErrors(errors: any[]) {\n return errors.reduce((errs, err) => errs.concat((err instanceof UnsubscriptionError) ? err.errors : err), []);\n}\n","/** @deprecated do not use, this is no longer checked by RxJS internals */\nexport const rxSubscriber = (() =>\n typeof Symbol === 'function'\n ? Symbol('rxSubscriber')\n : '@@rxSubscriber_' + Math.random())();\n\n/**\n * @deprecated use rxSubscriber instead\n */\nexport const $$rxSubscriber = rxSubscriber;\n","import { isFunction } from './util/isFunction';\nimport { empty as emptyObserver } from './Observer';\nimport { Observer, PartialObserver, TeardownLogic } from './types';\nimport { Subscription } from './Subscription';\nimport { rxSubscriber as rxSubscriberSymbol } from '../internal/symbol/rxSubscriber';\nimport { config } from './config';\nimport { hostReportError } from './util/hostReportError';\n\n/**\n * Implements the {@link Observer} interface and extends the\n * {@link Subscription} class. While the {@link Observer} is the public API for\n * consuming the values of an {@link Observable}, all Observers get converted to\n * a Subscriber, in order to provide Subscription-like capabilities such as\n * `unsubscribe`. Subscriber is a common type in RxJS, and crucial for\n * implementing operators, but it is rarely used as a public API.\n *\n * @class Subscriber<T>\n */\nexport class Subscriber<T> extends Subscription implements Observer<T> {\n\n [rxSubscriberSymbol]() { return this; }\n\n /**\n * A static factory for a Subscriber, given a (potentially partial) definition\n * of an Observer.\n * @param {function(x: ?T): void} [next] The `next` callback of an Observer.\n * @param {function(e: ?any): void} [error] The `error` callback of an\n * Observer.\n * @param {function(): void} [complete] The `complete` callback of an\n * Observer.\n * @return {Subscriber<T>} A Subscriber wrapping the (partially defined)\n * Observer represented by the given arguments.\n * @nocollapse\n */\n static create<T>(next?: (x?: T) => void,\n error?: (e?: any) => void,\n complete?: () => void): Subscriber<T> {\n const subscriber = new Subscriber(next, error, complete);\n subscriber.syncErrorThrowable = false;\n return subscriber;\n }\n\n /** @internal */ syncErrorValue: any = null;\n /** @internal */ syncErrorThrown: boolean = false;\n /** @internal */ syncErrorThrowable: boolean = false;\n\n protected isStopped: boolean = false;\n protected destination: PartialObserver<any> | Subscriber<any>; // this `any` is the escape hatch to erase extra type param (e.g. R)\n\n /**\n * @param {Observer|function(value: T): void} [destinationOrNext] A partially\n * defined Observer or a `next` callback function.\n * @param {function(e: ?any): void} [error] The `error` callback of an\n * Observer.\n * @param {function(): void} [complete] The `complete` callback of an\n * Observer.\n */\n constructor(destinationOrNext?: PartialObserver<any> | ((value: T) => void),\n error?: (e?: any) => void,\n complete?: () => void) {\n super();\n\n switch (arguments.length) {\n case 0:\n this.destination = emptyObserver;\n break;\n case 1:\n if (!destinationOrNext) {\n this.destination = emptyObserver;\n break;\n }\n if (typeof destinationOrNext === 'object') {\n if (destinationOrNext instanceof Subscriber) {\n this.syncErrorThrowable = destinationOrNext.syncErrorThrowable;\n this.destination = destinationOrNext;\n destinationOrNext.add(this);\n } else {\n this.syncErrorThrowable = true;\n this.destination = new SafeSubscriber<T>(this, <PartialObserver<any>> destinationOrNext);\n }\n break;\n }\n default:\n this.syncErrorThrowable = true;\n this.destination = new SafeSubscriber<T>(this, <((value: T) => void)> destinationOrNext, error, complete);\n break;\n }\n }\n\n /**\n * The {@link Observer} callback to receive notifications of type `next` from\n * the Observable, with a value. The Observable may call this method 0 or more\n * times.\n * @param {T} [value] The `next` value.\n * @return {void}\n */\n next(value?: T): void {\n if (!this.isStopped) {\n this._next(value);\n }\n }\n\n /**\n * The {@link Observer} callback to receive notifications of type `error` from\n * the Observable, with an attached `Error`. Notifies the Observer that\n * the Observable has experienced an error condition.\n * @param {any} [err] The `error` exception.\n * @return {void}\n */\n error(err?: any): void {\n if (!this.isStopped) {\n this.isStopped = true;\n this._error(err);\n }\n }\n\n /**\n * The {@link Observer} callback to receive a valueless notification of type\n * `complete` from the Observable. Notifies the Observer that the Observable\n * has finished sending push-based notifications.\n * @return {void}\n */\n complete(): void {\n if (!this.isStopped) {\n this.isStopped = true;\n this._complete();\n }\n }\n\n unsubscribe(): void {\n if (this.closed) {\n return;\n }\n this.isStopped = true;\n super.unsubscribe();\n }\n\n protected _next(value: T): void {\n this.destination.next(value);\n }\n\n protected _error(err: any): void {\n this.destination.error(err);\n this.unsubscribe();\n }\n\n protected _complete(): void {\n this.destination.complete();\n this.unsubscribe();\n }\n\n /** @deprecated This is an internal implementation detail, do not use. */\n _unsubscribeAndRecycle(): Subscriber<T> {\n const { _parentOrParents } = this;\n this._parentOrParents = null;\n this.unsubscribe();\n this.closed = false;\n this.isStopped = false;\n this._parentOrParents = _parentOrParents;\n return this;\n }\n}\n\n/**\n * We need this JSDoc comment for affecting ESDoc.\n * @ignore\n * @extends {Ignored}\n */\nexport class SafeSubscriber<T> extends Subscriber<T> {\n\n private _context: any;\n\n constructor(private _parentSubscriber: Subscriber<T>,\n observerOrNext?: PartialObserver<T> | ((value: T) => void),\n error?: (e?: any) => void,\n complete?: () => void) {\n super();\n\n let next: ((value: T) => void);\n let context: any = this;\n\n if (isFunction(observerOrNext)) {\n next = (<((value: T) => void)> observerOrNext);\n } else if (observerOrNext) {\n next = (<PartialObserver<T>> observerOrNext).next;\n error = (<PartialObserver<T>> observerOrNext).error;\n complete = (<PartialObserver<T>> observerOrNext).complete;\n if (observerOrNext !== emptyObserver) {\n context = Object.create(observerOrNext);\n if (isFunction(context.unsubscribe)) {\n this.add(<() => void> context.unsubscribe.bind(context));\n }\n context.unsubscribe = this.unsubscribe.bind(this);\n }\n }\n\n this._context = context;\n this._next = next;\n this._error = error;\n this._complete = complete;\n }\n\n next(value?: T): void {\n if (!this.isStopped && this._next) {\n const { _parentSubscriber } = this;\n if (!config.useDeprecatedSynchronousErrorHandling || !_parentSubscriber.syncErrorThrowable) {\n this.__tryOrUnsub(this._next, value);\n } else if (this.__tryOrSetError(_parentSubscriber, this._next, value)) {\n this.unsubscribe();\n }\n }\n }\n\n error(err?: any): void {\n if (!this.isStopped) {\n const { _parentSubscriber } = this;\n const { useDeprecatedSynchronousErrorHandling } = config;\n if (this._error) {\n if (!useDeprecatedSynchronousErrorHandling || !_parentSubscriber.syncErrorThrowable) {\n this.__tryOrUnsub(this._error, err);\n this.unsubscribe();\n } else {\n this.__tryOrSetError(_parentSubscriber, this._error, err);\n this.unsubscribe();\n }\n } else if (!_parentSubscriber.syncErrorThrowable) {\n this.unsubscribe();\n if (useDeprecatedSynchronousErrorHandling) {\n throw err;\n }\n hostReportError(err);\n } else {\n if (useDeprecatedSynchronousErrorHandling) {\n _parentSubscriber.syncErrorValue = err;\n _parentSubscriber.syncErrorThrown = true;\n } else {\n hostReportError(err);\n }\n this.unsubscribe();\n }\n }\n }\n\n complete(): void {\n if (!this.isStopped) {\n const { _parentSubscriber } = this;\n if (this._complete) {\n const wrappedComplete = () => this._complete.call(this._context);\n\n if (!config.useDeprecatedSynchronousErrorHandling || !_parentSubscriber.syncErrorThrowable) {\n this.__tryOrUnsub(wrappedComplete);\n this.unsubscribe();\n } else {\n this.__tryOrSetError(_parentSubscriber, wrappedComplete);\n this.unsubscribe();\n }\n } else {\n this.unsubscribe();\n }\n }\n }\n\n private __tryOrUnsub(fn: Function, value?: any): void {\n try {\n fn.call(this._context, value);\n } catch (err) {\n this.unsubscribe();\n if (config.useDeprecatedSynchronousErrorHandling) {\n throw err;\n } else {\n hostReportError(err);\n }\n }\n }\n\n private __tryOrSetError(parent: Subscriber<T>, fn: Function, value?: any): boolean {\n if (!config.useDeprecatedSynchronousErrorHandling) {\n throw new Error('bad call');\n }\n try {\n fn.call(this._context, value);\n } catch (err) {\n if (config.useDeprecatedSynchronousErrorHandling) {\n parent.syncErrorValue = err;\n parent.syncErrorThrown = true;\n return true;\n } else {\n hostReportError(err);\n return true;\n }\n }\n return false;\n }\n\n /** @internal This is an internal implementation detail, do not use. */\n _unsubscribe(): void {\n const { _parentSubscriber } = this;\n this._context = null;\n this._parentSubscriber = null;\n _parentSubscriber.unsubscribe();\n }\n}\n","import { Subscriber } from '../Subscriber';\nimport { Subject } from '../Subject';\n\n/**\n * Determines whether the ErrorObserver is closed or stopped or has a\n * destination that is closed or stopped - in which case errors will\n * need to be reported via a different mechanism.\n * @param observer the observer\n */\nexport function canReportError(observer: Subscriber<any> | Subject<any>): boolean {\n while (observer) {\n const { closed, destination, isStopped } = observer as any;\n if (closed || isStopped) {\n return false;\n } else if (destination && destination instanceof Subscriber) {\n observer = destination;\n } else {\n observer = null;\n }\n }\n return true;\n}\n","import { Subscriber } from '../Subscriber';\nimport { rxSubscriber as rxSubscriberSymbol } from '../symbol/rxSubscriber';\nimport { empty as emptyObserver } from '../Observer';\nimport { PartialObserver } from '../types';\n\nexport function toSubscriber<T>(\n nextOrObserver?: PartialObserver<T> | ((value: T) => void),\n error?: (error: any) => void,\n complete?: () => void): Subscriber<T> {\n\n if (nextOrObserver) {\n if (nextOrObserver instanceof Subscriber) {\n return (<Subscriber<T>> nextOrObserver);\n }\n\n if (nextOrObserver[rxSubscriberSymbol]) {\n return nextOrObserver[rxSubscriberSymbol]();\n }\n }\n\n if (!nextOrObserver && !error && !complete) {\n return new Subscriber(emptyObserver);\n }\n\n return new Subscriber(nextOrObserver, error, complete);\n}\n","/** Symbol.observable or a string \"@@observable\". Used for interop */\nexport const observable = (() => typeof Symbol === 'function' && Symbol.observable || '@@observable')();\n","export function identity<T>(x: T): T {\n return x;\n}\n","import { noop } from './noop';\nimport { identity } from './identity';\nimport { UnaryFunction } from '../types';\n\n/* tslint:disable:max-line-length */\nexport function pipe<T>(): UnaryFunction<T, T>;\nexport function pipe<T, A>(fn1: UnaryFunction<T, A>): UnaryFunction<T, A>;\nexport function pipe<T, A, B>(fn1: UnaryFunction<T, A>, fn2: UnaryFunction<A, B>): UnaryFunction<T, B>;\nexport function pipe<T, A, B, C>(fn1: UnaryFunction<T, A>, fn2: UnaryFunction<A, B>, fn3: UnaryFunction<B, C>): UnaryFunction<T, C>;\nexport function pipe<T, A, B, C, D>(fn1: UnaryFunction<T, A>, fn2: UnaryFunction<A, B>, fn3: UnaryFunction<B, C>, fn4: UnaryFunction<C, D>): UnaryFunction<T, D>;\nexport function pipe<T, A, B, C, D, E>(fn1: UnaryFunction<T, A>, fn2: UnaryFunction<A, B>, fn3: UnaryFunction<B, C>, fn4: UnaryFunction<C, D>, fn5: UnaryFunction<D, E>): UnaryFunction<T, E>;\nexport function pipe<T, A, B, C, D, E, F>(fn1: UnaryFunction<T, A>, fn2: UnaryFunction<A, B>, fn3: UnaryFunction<B, C>, fn4: UnaryFunction<C, D>, fn5: UnaryFunction<D, E>, fn6: UnaryFunction<E, F>): UnaryFunction<T, F>;\nexport function pipe<T, A, B, C, D, E, F, G>(fn1: UnaryFunction<T, A>, fn2: UnaryFunction<A, B>, fn3: UnaryFunction<B, C>, fn4: UnaryFunction<C, D>, fn5: UnaryFunction<D, E>, fn6: UnaryFunction<E, F>, fn7: UnaryFunction<F, G>): UnaryFunction<T, G>;\nexport function pipe<T, A, B, C, D, E, F, G, H>(fn1: UnaryFunction<T, A>, fn2: UnaryFunction<A, B>, fn3: UnaryFunction<B, C>, fn4: UnaryFunction<C, D>, fn5: UnaryFunction<D, E>, fn6: UnaryFunction<E, F>, fn7: UnaryFunction<F, G>, fn8: UnaryFunction<G, H>): UnaryFunction<T, H>;\nexport function pipe<T, A, B, C, D, E, F, G, H, I>(fn1: UnaryFunction<T, A>, fn2: UnaryFunction<A, B>, fn3: UnaryFunction<B, C>, fn4: UnaryFunction<C, D>, fn5: UnaryFunction<D, E>, fn6: UnaryFunction<E, F>, fn7: UnaryFunction<F, G>, fn8: UnaryFunction<G, H>, fn9: UnaryFunction<H, I>): UnaryFunction<T, I>;\nexport function pipe<T, A, B, C, D, E, F, G, H, I>(fn1: UnaryFunction<T, A>, fn2: UnaryFunction<A, B>, fn3: UnaryFunction<B, C>, fn4: UnaryFunction<C, D>, fn5: UnaryFunction<D, E>, fn6: UnaryFunction<E, F>, fn7: UnaryFunction<F, G>, fn8: UnaryFunction<G, H>, fn9: UnaryFunction<H, I>, ...fns: UnaryFunction<any, any>[]): UnaryFunction<T, {}>;\n/* tslint:enable:max-line-length */\n\nexport function pipe(...fns: Array<UnaryFunction<any, any>>): UnaryFunction<any, any> {\n return pipeFromArray(fns);\n}\n\n/** @internal */\nexport function pipeFromArray<T, R>(fns: Array<UnaryFunction<T, R>>): UnaryFunction<T, R> {\n if (fns.length === 0) {\n return identity as UnaryFunction<any, any>;\n }\n\n if (fns.length === 1) {\n return fns[0];\n }\n\n return function piped(input: T): R {\n return fns.reduce((prev: any, fn: UnaryFunction<T, R>) => fn(prev), input as any);\n };\n}\n","import { Operator } from './Operator';\nimport { Subscriber } from './Subscriber';\nimport { Subscription } from './Subscription';\nimport { TeardownLogic, OperatorFunction, PartialObserver, Subscribable } from './types';\nimport { canReportError } from './util/canReportError';\nimport { toSubscriber } from './util/toSubscriber';\nimport { iif } from './observable/iif';\nimport { throwError } from './observable/throwError';\nimport { observable as Symbol_observable } from './symbol/observable';\nimport { pipeFromArray } from './util/pipe';\nimport { config } from './config';\n\n/**\n * A representation of any set of values over any amount of time. This is the most basic building block\n * of RxJS.\n *\n * @class Observable<T>\n */\nexport class Observable<T> implements Subscribable<T> {\n\n /** Internal implementation detail, do not use directly. */\n public _isScalar: boolean = false;\n\n /** @deprecated This is an internal implementation detail, do not use. */\n source: Observable<any>;\n\n /** @deprecated This is an internal implementation detail, do not use. */\n operator: Operator<any, T>;\n\n /**\n * @constructor\n * @param {Function} subscribe the function that is called when the Observable is\n * initially subscribed to. This function is given a Subscriber, to which new values\n * can be `next`ed, or an `error` method can be called to raise an error, or\n * `complete` can be called to notify of a successful completion.\n */\n constructor(subscribe?: (this: Observable<T>, subscriber: Subscriber<T>) => TeardownLogic) {\n if (subscribe) {\n this._subscribe = subscribe;\n }\n }\n\n // HACK: Since TypeScript inherits static properties too, we have to\n // fight against TypeScript here so Subject can have a different static create signature\n /**\n * Creates a new cold Observable by calling the Observable constructor\n * @static true\n * @owner Observable\n * @method create\n * @param {Function} subscribe? the subscriber function to be passed to the Observable constructor\n * @return {Observable} a new cold observable\n * @nocollapse\n * @deprecated use new Observable() instead\n */\n static create: Function = <T>(subscribe?: (subscriber: Subscriber<T>) => TeardownLogic) => {\n return new Observable<T>(subscribe);\n }\n\n /**\n * Creates a new Observable, with this Observable as the source, and the passed\n * operator defined as the new observable's operator.\n * @method lift\n * @param {Operator} operator the operator defining the operation to take on the observable\n * @return {Observable} a new observable with the Operator applied\n */\n lift<R>(operator: Operator<T, R>): Observable<R> {\n const observable = new Observable<R>();\n observable.source = this;\n observable.operator = operator;\n return observable;\n }\n\n subscribe(observer?: PartialObserver<T>): Subscription;\n /** @deprecated Use an observer instead of a complete callback */\n subscribe(next: null | undefined, error: null | undefined, complete: () => void): Subscription;\n /** @deprecated Use an observer instead of an error callback */\n subscribe(next: null | undefined, error: (error: any) => void, complete?: () => void): Subscription;\n /** @deprecated Use an observer instead of a complete callback */\n subscribe(next: (value: T) => void, error: null | undefined, complete: () => void): Subscription;\n subscribe(next?: (value: T) => void, error?: (error: any) => void, complete?: () => void): Subscription;\n /**\n * Invokes an execution of an Observable and registers Observer handlers for notifications it will emit.\n *\n * <span class=\"informal\">Use it when you have all these Observables, but still nothing is happening.</span>\n *\n * `subscribe` is not a regular operator, but a method that calls Observable's internal `subscribe` function. It\n * might be for example a function that you passed to Observable's constructor, but most of the time it is\n * a library implementation, which defines what will be emitted by an Observable, and when it be will emitted. This means\n * that calling `subscribe` is actually the moment when Observable starts its work, not when it is created, as it is often\n * the thought.\n *\n * Apart from starting the execution of an Observable, this method allows you to listen for values\n * that an Observable emits, as well as for when it completes or errors. You can achieve this in two\n * of the following ways.\n *\n * The first way is creating an object that implements {@link Observer} interface. It should have methods\n * defined by that interface, but note that it should be just a regular JavaScript object, which you can create\n * yourself in any way you want (ES6 class, classic function constructor, object literal etc.). In particular do\n * not attempt to use any RxJS implementation details to create Observers - you don't need them. Remember also\n * that your object does not have to implement all methods. If you find yourself creating a method that doesn't\n * do anything, you can simply omit it. Note however, if the `error` method is not provided, all errors will\n * be left uncaught.\n *\n * The second way is to give up on Observer object altogether and simply provide callback functions in place of its methods.\n * This means you can provide three functions as arguments to `subscribe`, where the first function is equivalent\n * of a `next` method, the second of an `error` method and the third of a `complete` method. Just as in case of Observer,\n * if you do not need to listen for something, you can omit a function, preferably by passing `undefined` or `null`,\n * since `subscribe` recognizes these functions by where they were placed in function call. When it comes\n * to `error` function, just as before, if not provided, errors emitted by an Observable will be thrown.\n *\n * Whichever style of calling `subscribe` you use, in both cases it returns a Subscription object.\n * This object allows you to call `unsubscribe` on it, which in turn will stop the work that an Observable does and will clean\n * up all resources that an Observable used. Note that cancelling a subscription will not call `complete` callback\n * provided to `subscribe` function, which is reserved for a regular completion signal that comes from an Observable.\n *\n * Remember that callbacks provided to `subscribe` are not guaranteed to be called asynchronously.\n * It is an Observable itself that decides when these functions will be called. For example {@link of}\n * by default emits all its values synchronously. Always check documentation for how given Observable\n * will behave when subscribed and if its default behavior can be modified with a `scheduler`.\n *\n * ## Example\n * ### Subscribe with an Observer\n * ```ts\n * import { of } from 'rxjs';\n *\n * const sumObserver = {\n * sum: 0,\n * next(value) {\n * console.log('Adding: ' + value);\n * this.sum = this.sum + value;\n * },\n * error() {\n * // We actually could just remove this method,\n * // since we do not really care about errors right now.\n * },\n * complete() {\n * console.log('Sum equals: ' + this.sum);\n * }\n * };\n *\n * of(1, 2, 3) // Synchronously emits 1, 2, 3 and then completes.\n * .subscribe(sumObserver);\n *\n * // Logs:\n * // \"Adding: 1\"\n * // \"Adding: 2\"\n * // \"Adding: 3\"\n * // \"Sum equals: 6\"\n * ```\n *\n * ### Subscribe with functions\n * ```ts\n * import { of } from 'rxjs'\n *\n * let sum = 0;\n *\n * of(1, 2, 3).subscribe(\n * value => {\n * console.log('Adding: ' + value);\n * sum = sum + value;\n * },\n * undefined,\n * () => console.log('Sum equals: ' + sum)\n * );\n *\n * // Logs:\n * // \"Adding: 1\"\n * // \"Adding: 2\"\n * // \"Adding: 3\"\n * // \"Sum equals: 6\"\n * ```\n *\n * ### Cancel a subscription\n * ```ts\n * import { interval } from 'rxjs';\n *\n * const subscription = interval(1000).subscribe(\n * num => console.log(num),\n * undefined,\n * () => {\n * // Will not be called, even when cancelling subscription.\n * console.log('completed!');\n * }\n * );\n *\n * setTimeout(() => {\n * subscription.unsubscribe();\n * console.log('unsubscribed!');\n * }, 2500);\n *\n * // Logs:\n * // 0 after 1s\n * // 1 after 2s\n * // \"unsubscribed!\" after 2.5s\n * ```\n *\n * @param {Observer|Function} observerOrNext (optional) Either an observer with methods to be called,\n * or the first of three possible handlers, which is the handler for each value emitted from the subscribed\n * Observable.\n * @param {Function} error (optional) A handler for a terminal event resulting from an error. If no error handler is provided,\n * the error will be thrown as unhandled.\n * @param {Function} complete (optional) A handler for a terminal event resulting from successful completion.\n * @return {ISubscription} a subscription reference to the registered handlers\n * @method subscribe\n */\n subscribe(observerOrNext?: PartialObserver<T> | ((value: T) => void),\n error?: (error: any) => void,\n complete?: () => void): Subscription {\n\n const { operator } = this;\n const sink = toSubscriber(observerOrNext, error, complete);\n\n if (operator) {\n sink.add(operator.call(sink, this.source));\n } else {\n sink.add(\n this.source || (config.useDeprecatedSynchronousErrorHandling && !sink.syncErrorThrowable) ?\n this._subscribe(sink) :\n this._trySubscribe(sink)\n );\n }\n\n if (config.useDeprecatedSynchronousErrorHandling) {\n if (sink.syncErrorThrowable) {\n sink.syncErrorThrowable = false;\n if (sink.syncErrorThrown) {\n throw sink.syncErrorValue;\n }\n }\n }\n\n return sink;\n }\n\n /** @deprecated This is an internal implementation detail, do not use. */\n _trySubscribe(sink: Subscriber<T>): TeardownLogic {\n try {\n return this._subscribe(sink);\n } catch (err) {\n if (config.useDeprecatedSynchronousErrorHandling) {\n sink.syncErrorThrown = true;\n sink.syncErrorValue = err;\n }\n if (canReportError(sink)) {\n sink.error(err);\n } else {\n console.warn(err);\n }\n }\n }\n\n /**\n * @method forEach\n * @param {Function} next a handler for each value emitted by the observable\n * @param {PromiseConstructor} [promiseCtor] a constructor function used to instantiate the Promise\n * @return {Promise} a promise that either resolves on observable completion or\n * rejects with the handled error\n */\n forEach(next: (value: T) => void, promiseCtor?: PromiseConstructorLike): Promise<void> {\n promiseCtor = getPromiseCtor(promiseCtor);\n\n return new promiseCtor<void>((resolve, reject) => {\n // Must be declared in a separate statement to avoid a ReferenceError when\n // accessing subscription below in the closure due to Temporal Dead Zone.\n let subscription: Subscription;\n subscription = this.subscribe((value) => {\n try {\n next(value);\n } catch (err) {\n reject(err);\n if (subscription) {\n subscription.unsubscribe();\n }\n }\n }, reject, resolve);\n }) as Promise<void>;\n }\n\n /** @internal This is an internal implementation detail, do not use. */\n _subscribe(subscriber: Subscriber<any>): TeardownLogic {\n const { source } = this;\n return source && source.subscribe(subscriber);\n }\n\n // `if` and `throw` are special snow flakes, the compiler sees them as reserved words. Deprecated in\n // favor of iif and throwError functions.\n /**\n * @nocollapse\n * @deprecated In favor of iif creation function: import { iif } from 'rxjs';\n */\n static if: typeof iif;\n /**\n * @nocollapse\n * @deprecated In favor of throwError creation function: import { throwError } from 'rxjs';\n */\n static throw: typeof throwError;\n\n /**\n * An interop point defined by the es7-observable spec https://github.com/zenparsing/es-observable\n * @method Symbol.observable\n * @return {Observable} this instance of the observable\n */\n [Symbol_observable]() {\n return this;\n }\n\n /* tslint:disable:max-line-length */\n pipe(): Observable<T>;\n pipe<A>(op1: OperatorFunction<T, A>): Observable<A>;\n pipe<A, B>(op1: OperatorFunction<T, A>, op2: OperatorFunction<A, B>): Observable<B>;\n pipe<A, B, C>(op1: OperatorFunction<T, A>, op2: OperatorFunction<A, B>, op3: OperatorFunction<B, C>): Observable<C>;\n pipe<A, B, C, D>(op1: OperatorFunction<T, A>, op2: OperatorFunction<A, B>, op3: OperatorFunction<B, C>, op4: OperatorFunction<C, D>): Observable<D>;\n pipe<A, B, C, D, E>(op1: OperatorFunction<T, A>, op2: OperatorFunction<A, B>, op3: OperatorFunction<B, C>, op4: OperatorFunction<C, D>, op5: OperatorFunction<D, E>): Observable<E>;\n pipe<A, B, C, D, E, F>(op1: OperatorFunction<T, A>, op2: OperatorFunction<A, B>, op3: OperatorFunction<B, C>, op4: OperatorFunction<C, D>, op5: OperatorFunction<D, E>, op6: OperatorFunction<E, F>): Observable<F>;\n pipe<A, B, C, D, E, F, G>(op1: OperatorFunction<T, A>, op2: OperatorFunction<A, B>, op3: OperatorFunction<B, C>, op4: OperatorFunction<C, D>, op5: OperatorFunction<D, E>, op6: OperatorFunction<E, F>, op7: OperatorFunction<F, G>): Observable<G>;\n pipe<A, B, C, D, E, F, G, H>(op1: OperatorFunction<T, A>, op2: OperatorFunction<A, B>, op3: OperatorFunction<B, C>, op4: OperatorFunction<C, D>, op5: OperatorFunction<D, E>, op6: OperatorFunction<E, F>, op7: OperatorFunction<F, G>, op8: OperatorFunction<G, H>): Observable<H>;\n pipe<A, B, C, D, E, F, G, H, I>(op1: OperatorFunction<T, A>, op2: OperatorFunction<A, B>, op3: OperatorFunction<B, C>, op4: OperatorFunction<C, D>, op5: OperatorFunction<D, E>, op6: OperatorFunction<E, F>, op7: OperatorFunction<F, G>, op8: OperatorFunction<G, H>, op9: OperatorFunction<H, I>): Observable<I>;\n pipe<A, B, C, D, E, F, G, H, I>(op1: OperatorFunction<T, A>, op2: OperatorFunction<A, B>, op3: OperatorFunction<B, C>, op4: OperatorFunction<C, D>, op5: OperatorFunction<D, E>, op6: OperatorFunction<E, F>, op7: OperatorFunction<F, G>, op8: OperatorFunction<G, H>, op9: OperatorFunction<H, I>, ...operations: OperatorFunction<any, any>[]): Observable<{}>;\n /* tslint:enable:max-line-length */\n\n /**\n * Used to stitch together functional operators into a chain.\n * @method pipe\n * @return {Observable} the Observable result of all of the operators having\n * been called in the order they were passed in.\n *\n * ### Example\n * ```ts\n * import { interval } from 'rxjs';\n * import { map, filter, scan } from 'rxjs/operators';\n *\n * interval(1000)\n * .pipe(\n * filter(x => x % 2 === 0),\n * map(x => x + x),\n * scan((acc, x) => acc + x)\n * )\n * .subscribe(x => console.log(x))\n * ```\n */\n pipe(...operations: OperatorFunction<any, any>[]): Observable<any> {\n if (operations.length === 0) {\n return this as any;\n }\n\n return pipeFromArray(operations)(this);\n }\n\n /* tslint:disable:max-line-length */\n toPromise<T>(this: Observable<T>): Promise<T>;\n toPromise<T>(this: Observable<T>, PromiseCtor: typeof Promise): Promise<T>;\n toPromise<T>(this: Observable<T>, PromiseCtor: PromiseConstructorLike): Promise<T>;\n /* tslint:enable:max-line-length */\n\n toPromise(promiseCtor?: PromiseConstructorLike): Promise<T> {\n promiseCtor = getPromiseCtor(promiseCtor);\n\n return new promiseCtor((resolve, reject) => {\n let value: any;\n this.subscribe((x: T) => value = x, (err: any) => reject(err), () => resolve(value));\n }) as Promise<T>;\n }\n}\n\n/**\n * Decides between a passed promise constructor from consuming code,\n * A default configured promise constructor, and the native promise\n * constructor and returns it. If nothing can be found, it will throw\n * an error.\n * @param promiseCtor The optional promise constructor to passed by consuming code\n */\nfunction getPromiseCtor(promiseCtor: PromiseConstructorLike | undefined) {\n if (!promiseCtor) {\n promiseCtor = config.Promise || Promise;\n }\n\n if (!promiseCtor) {\n throw new Error('no Promise impl found');\n }\n\n return promiseCtor;\n}\n","import { Subscriber } from '../Subscriber';\n\n/**\n * Subscribes to an ArrayLike with a subscriber\n * @param array The array or array-like to subscribe to\n */\nexport const subscribeToArray = <T>(array: ArrayLike<T>) => (subscriber: Subscriber<T>) => {\n for (let i = 0, len = array.length; i < len && !subscriber.closed; i++) {\n subscriber.next(array[i]);\n }\n subscriber.complete();\n};\n","import { Subscriber } from '../Subscriber';\nimport { hostReportError } from './hostReportError';\n\nexport const subscribeToPromise = <T>(promise: PromiseLike<T>) => (subscriber: Subscriber<T>) => {\n promise.then(\n (value) => {\n if (!subscriber.closed) {\n subscriber.next(value);\n subscriber.complete();\n }\n },\n (err: any) => subscriber.error(err)\n )\n .then(null, hostReportError);\n return subscriber;\n};\n","export function getSymbolIterator(): symbol {\n if (typeof Symbol !== 'function' || !Symbol.iterator) {\n return '@@iterator' as any;\n }\n\n return Symbol.iterator;\n}\n\nexport const iterator = getSymbolIterator();\n\n/**\n * @deprecated use {@link iterator} instead\n */\nexport const $$iterator = iterator;\n","import { Subscriber } from '../Subscriber';\nimport { iterator as Symbol_iterator } from '../symbol/iterator';\n\nexport const subscribeToIterable = <T>(iterable: Iterable<T>) => (subscriber: Subscriber<T>) => {\n const iterator = (iterable as any)[Symbol_iterator]();\n\n do {\n let item: IteratorResult<T>;\n try {\n item = iterator.next();\n } catch (err) {\n subscriber.error(err);\n return subscriber;\n }\n if (item.done) {\n subscriber.complete();\n break;\n }\n subscriber.next(item.value);\n if (subscriber.closed) {\n break;\n }\n } while (true);\n\n // Finalize the iterator if it happens to be a Generator\n if (typeof iterator.return === 'function') {\n subscriber.add(() => {\n if (iterator.return) {\n iterator.return();\n }\n });\n }\n\n return subscriber;\n};\n","import { Subscriber } from '../Subscriber';\nimport { observable as Symbol_observable } from '../symbol/observable';\n\n/**\n * Subscribes to an object that implements Symbol.observable with the given\n * Subscriber.\n * @param obj An object that implements Symbol.observable\n */\nexport const subscribeToObservable = <T>(obj: any) => (subscriber: Subscriber<T>) => {\n const obs = obj[Symbol_observable]();\n if (typeof obs.subscribe !== 'function') {\n // Should be caught by observable subscribe function error handling.\n throw new TypeError('Provided object does not correctly implement Symbol.observable');\n } else {\n return obs.subscribe(subscriber);\n }\n};\n","export const isArrayLike = (<T>(x: any): x is ArrayLike<T> => x && typeof x.length === 'number' && typeof x !== 'function');","/**\n * Tests to see if the object is an ES2015 (ES6) Promise\n * @see {@link https://www.ecma-international.org/ecma-262/6.0/#sec-promise-objects}\n * @param value the object to test\n */\nexport function isPromise(value: any): value is PromiseLike<any> {\n return !!value && typeof (<any>value).subscribe !== 'function' && typeof (value as any).then === 'function';\n}\n","import { ObservableInput } from '../types';\nimport { subscribeToArray } from './subscribeToArray';\nimport { subscribeToPromise } from './subscribeToPromise';\nimport { subscribeToIterable } from './subscribeToIterable';\nimport { subscribeToObservable } from './subscribeToObservable';\nimport { isArrayLike } from './isArrayLike';\nimport { isPromise } from './isPromise';\nimport { isObject } from './isObject';\nimport { iterator as Symbol_iterator } from '../symbol/iterator';\nimport { observable as Symbol_observable } from '../symbol/observable';\nimport { Subscription } from '../Subscription';\nimport { Subscriber } from '../Subscriber';\n\nexport const subscribeTo = <T>(result: ObservableInput<T>): (subscriber: Subscriber<T>) => Subscription | void => {\n if (!!result && typeof result[Symbol_observable] === 'function') {\n return subscribeToObservable(result as any);\n } else if (isArrayLike(result)) {\n return subscribeToArray(result);\n } else if (isPromise(result)) {\n return subscribeToPromise(result as Promise<any>);\n } else if (!!result && typeof result[Symbol_iterator] === 'function') {\n return subscribeToIterable(result as any);\n } else {\n const value = isObject(result) ? 'an invalid object' : `'${result}'`;\n const msg = `You provided ${value} where a stream was expected.`\n + ' You can provide an Observable, Promise, Array, or Iterable.';\n throw new TypeError(msg);\n }\n};\n","/** @prettier */\nimport { Subscription } from './Subscription';\nimport { Subscriber } from './Subscriber';\nimport { Observable } from './Observable';\nimport { subscribeTo } from './util/subscribeTo';\n\ninterface SimpleOuterSubscriberLike<T> {\n /**\n * A handler for inner next notifications from the inner subscription\n * @param innerValue the value nexted by the inner producer\n */\n notifyNext(innerValue: T): void;\n /**\n * A handler for inner error notifications from the inner subscription\n * @param err the error from the inner producer\n */\n notifyError(err: any): void;\n /**\n * A handler for inner complete notifications from the inner subscription.\n */\n notifyComplete(): void;\n}\n\nexport class SimpleInnerSubscriber<T> extends Subscriber<T> {\n constructor(private parent: SimpleOuterSubscriberLike<any>) {\n super();\n }\n\n protected _next(value: T): void {\n this.parent.notifyNext(value);\n }\n\n protected _error(error: any): void {\n this.parent.notifyError(error);\n this.unsubscribe();\n }\n\n protected _complete(): void {\n this.parent.notifyComplete();\n this.unsubscribe();\n }\n}\n\nexport class ComplexInnerSubscriber<T, R> extends Subscriber<R> {\n constructor(private parent: ComplexOuterSubscriber<T, R>, public outerValue: T, public outerIndex: number) {\n super();\n }\n\n protected _next(value: R): void {\n this.parent.notifyNext(this.outerValue, value, this.outerIndex, this);\n }\n\n protected _error(error: any): void {\n this.parent.notifyError(error);\n this.unsubscribe();\n }\n\n protected _complete(): void {\n this.parent.notifyComplete(this);\n this.unsubscribe();\n }\n}\n\nexport class SimpleOuterSubscriber<T, R> extends Subscriber<T> implements SimpleOuterSubscriberLike<R> {\n notifyNext(innerValue: R): void {\n this.destination.next(innerValue);\n }\n\n notifyError(err: any): void {\n this.destination.error(err);\n }\n\n notifyComplete(): void {\n this.destination.complete();\n }\n}\n\n/**\n * DO NOT USE (formerly \"OuterSubscriber\")\n * TODO: We want to refactor this and remove it. It is retaining values it shouldn't for long\n * periods of time.\n */\nexport class ComplexOuterSubscriber<T, R> extends Subscriber<T> {\n /**\n * @param _outerValue Used by: bufferToggle, delayWhen, windowToggle\n * @param innerValue Used by: subclass default, combineLatest, race, bufferToggle, windowToggle, withLatestFrom\n * @param _outerIndex Used by: combineLatest, race, withLatestFrom\n * @param _innerSub Used by: delayWhen\n */\n notifyNext(_outerValue: T, innerValue: R, _outerIndex: number, _innerSub: ComplexInnerSubscriber<T, R>): void {\n this.destination.next(innerValue);\n }\n\n notifyError(error: any): void {\n this.destination.error(error);\n }\n\n /**\n * @param _innerSub Used by: race, bufferToggle, delayWhen, windowToggle, windowWhen\n */\n notifyComplete(_innerSub: ComplexInnerSubscriber<T, R>): void {\n this.destination.complete();\n }\n}\n\nexport function innerSubscribe(result: any, innerSubscriber: Subscriber<any>): Subscription | undefined {\n if (innerSubscriber.closed) {\n return undefined;\n }\n if (result instanceof Observable) {\n return result.subscribe(innerSubscriber);\n }\n let subscription: Subscription;\n try {\n subscription = subscribeTo(result)(innerSubscriber) as Subscription;\n } catch (error) {\n innerSubscriber.error(error);\n }\n return subscription;\n}\n","import { Scheduler } from '../Scheduler';\nimport { Subscription } from '../Subscription';\nimport { SchedulerAction } from '../types';\n\n/**\n * A unit of work to be executed in a `scheduler`. An action is typically\n * created from within a {@link SchedulerLike} and an RxJS user does not need to concern\n * themselves about creating and manipulating an Action.\n *\n * ```ts\n * class Action<T> extends Subscription {\n * new (scheduler: Scheduler, work: (state?: T) => void);\n * schedule(state?: T, delay: number = 0): Subscription;\n * }\n * ```\n *\n * @class Action<T>\n */\nexport class Action<T> extends Subscription {\n constructor(scheduler: Scheduler, work: (this: SchedulerAction<T>, state?: T) => void) {\n super();\n }\n /**\n * Schedules this action on its parent {@link SchedulerLike} for execution. May be passed\n * some context object, `state`. May happen at some point in the future,\n * according to the `delay` parameter, if specified.\n * @param {T} [state] Some contextual data that the `work` function uses when\n * called by the Scheduler.\n * @param {number} [delay] Time to wait before executing the work, where the\n * time unit is implicit and defined by the Scheduler.\n * @return {void}\n */\n public schedule(state?: T, delay: number = 0): Subscription {\n return this;\n }\n}\n","import { Action } from './Action';\nimport { SchedulerAction } from '../types';\nimport { Subscription } from '../Subscription';\nimport { AsyncScheduler } from './AsyncScheduler';\n\n/**\n * We need this JSDoc comment for affecting ESDoc.\n * @ignore\n * @extends {Ignored}\n */\nexport class AsyncAction<T> extends Action<T> {\n\n public id: any;\n public state: T;\n public delay: number;\n protected pending: boolean = false;\n\n constructor(protected scheduler: AsyncScheduler,\n protected work: (this: SchedulerAction<T>, state?: T) => void) {\n super(scheduler, work);\n }\n\n public schedule(state?: T, delay: number = 0): Subscription {\n\n if (this.closed) {\n return this;\n }\n\n // Always replace the current state with the new state.\n this.state = state;\n\n const id = this.id;\n const scheduler = this.scheduler;\n\n //\n // Important implementation note:\n //\n // Actions only execute once by default, unless rescheduled from within the\n // scheduled callback. This allows us to implement single and repeat\n // actions via the same code path, without adding API surface area, as well\n // as mimic traditional recursion but across asynchronous boundaries.\n //\n // However, JS runtimes and timers distinguish between intervals achieved by\n // serial `setTimeout` calls vs. a single `setInterval` call. An interval of\n // serial `setTimeout` calls can be individually delayed, which delays\n // scheduling the next `setTimeout`, and so on. `setInterval` attempts to\n // guarantee the interval callback will be invoked more precisely to the\n // interval period, regardless of load.\n //\n // Therefore, we use `setInterval` to schedule single and repeat actions.\n // If the action reschedules itself with the same delay, the interval is not\n // canceled. If the action doesn't reschedule, or reschedules with a\n // different delay, the interval will be canceled after scheduled callback\n // execution.\n //\n if (id != null) {\n this.id = this.recycleAsyncId(scheduler, id, delay);\n }\n\n // Set the pending flag indicating that this action has been scheduled, or\n // has recursively rescheduled itself.\n this.pending = true;\n\n this.delay = delay;\n // If this action has already an async Id, don't request a new one.\n this.id = this.id || this.requestAsyncId(scheduler, this.id, delay);\n\n return this;\n }\n\n protected requestAsyncId(scheduler: AsyncScheduler, id?: any, delay: number = 0): any {\n return setInterval(scheduler.flush.bind(scheduler, this), delay);\n }\n\n protected recycleAsyncId(scheduler: AsyncScheduler, id: any, delay: number = 0): any {\n // If this action is rescheduled with the same delay time, don't clear the interval id.\n if (delay !== null && this.delay === delay && this.pending === false) {\n return id;\n }\n // Otherwise, if the action's delay time is different from the current delay,\n // or the action has been rescheduled before it's executed, clear the interval id\n clearInterval(id);\n return undefined;\n }\n\n /**\n * Immediately executes this action and the `work` it contains.\n * @return {any}\n */\n public execute(state: T, delay: number): any {\n\n if (this.closed) {\n return new Error('executing a cancelled action');\n }\n\n this.pending = false;\n const error = this._execute(state, delay);\n if (error) {\n return error;\n } else if (this.pending === false && this.id != null) {\n // Dequeue if the action didn't reschedule itself. Don't call\n // unsubscribe(), because the action could reschedule later.\n // For example:\n // ```\n // scheduler.schedule(function doWork(counter) {\n // /* ... I'm a busy worker bee ... */\n // var originalAction = this;\n // /* wait 100ms before rescheduling the action */\n // setTimeout(function () {\n // originalAction.schedule(counter + 1);\n // }, 100);\n // }, 1000);\n // ```\n this.id = this.recycleAsyncId(this.scheduler, this.id, null);\n }\n }\n\n protected _execute(state: T, delay: number): any {\n let errored: boolean = false;\n let errorValue: any = undefined;\n try {\n this.work(state);\n } catch (e) {\n errored = true;\n errorValue = !!e && e || new Error(e);\n }\n if (errored) {\n this.unsubscribe();\n return errorValue;\n }\n }\n\n /** @deprecated This is an internal implementation detail, do not use. */\n _unsubscribe() {\n\n const id = this.id;\n const scheduler = this.scheduler;\n const actions = scheduler.actions;\n const index = actions.indexOf(this);\n\n this.work = null;\n this.state = null;\n this.pending = false;\n this.scheduler = null;\n\n if (index !== -1) {\n actions.splice(index, 1);\n }\n\n if (id != null) {\n this.id = this.recycleAsyncId(scheduler, id, null);\n }\n\n this.delay = null;\n }\n}\n","import { Action } from './scheduler/Action';\nimport { Subscription } from './Subscription';\nimport { SchedulerLike, SchedulerAction } from './types';\n\n/**\n * An execution context and a data structure to order tasks and schedule their\n * execution. Provides a notion of (potentially virtual) time, through the\n * `now()` getter method.\n *\n * Each unit of work in a Scheduler is called an `Action`.\n *\n * ```ts\n * class Scheduler {\n * now(): number;\n * schedule(work, delay?, state?): Subscription;\n * }\n * ```\n *\n * @class Scheduler\n * @deprecated Scheduler is an internal implementation detail of RxJS, and\n * should not be used directly. Rather, create your own class and implement\n * {@link SchedulerLike}\n */\nexport class Scheduler implements SchedulerLike {\n\n /**\n * Note: the extra arrow function wrapper is to make testing by overriding\n * Date.now easier.\n * @nocollapse\n */\n public static now: () => number = () => Date.now();\n\n constructor(private SchedulerAction: typeof Action,\n now: () => number = Scheduler.now) {\n this.now = now;\n }\n\n /**\n * A getter method that returns a number representing the current time\n * (at the time this function was called) according to the scheduler's own\n * internal clock.\n * @return {number} A number that represents the current time. May or may not\n * have a relation to wall-clock time. May or may not refer to a time unit\n * (e.g. milliseconds).\n */\n public now: () => number;\n\n /**\n * Schedules a function, `work`, for execution. May happen at some point in\n * the future, according to the `delay` parameter, if specified. May be passed\n * some context object, `state`, which will be passed to the `work` function.\n *\n * The given arguments will be processed an stored as an Action object in a\n * queue of actions.\n *\n * @param {function(state: ?T): ?Subscription} work A function representing a\n * task, or some unit of work to be executed by the Scheduler.\n * @param {number} [delay] Time to wait before executing the work, where the\n * time unit is implicit and defined by the Scheduler itself.\n * @param {T} [state] Some contextual data that the `work` function uses when\n * called by the Scheduler.\n * @return {Subscription} A subscription in order to be able to unsubscribe\n * the scheduled work.\n */\n public schedule<T>(work: (this: SchedulerAction<T>, state?: T) => void, delay: number = 0, state?: T): Subscription {\n return new this.SchedulerAction<T>(this, work).schedule(state, delay);\n }\n}\n","import { Scheduler } from '../Scheduler';\nimport { Action } from './Action';\nimport { AsyncAction } from './AsyncAction';\nimport { SchedulerAction } from '../types';\nimport { Subscription } from '../Subscription';\n\nexport class AsyncScheduler extends Scheduler {\n public static delegate?: Scheduler;\n public actions: Array<AsyncAction<any>> = [];\n /**\n * A flag to indicate whether the Scheduler is currently executing a batch of\n * queued actions.\n * @type {boolean}\n * @deprecated internal use only\n */\n public active: boolean = false;\n /**\n * An internal ID used to track the latest asynchronous task such as those\n * coming from `setTimeout`, `setInterval`, `requestAnimationFrame`, and\n * others.\n * @type {any}\n * @deprecated internal use only\n */\n public scheduled: any = undefined;\n\n constructor(SchedulerAction: typeof Action,\n now: () => number = Scheduler.now) {\n super(SchedulerAction, () => {\n if (AsyncScheduler.delegate && AsyncScheduler.delegate !== this) {\n return AsyncScheduler.delegate.now();\n } else {\n return now();\n }\n });\n }\n\n public schedule<T>(work: (this: SchedulerAction<T>, state?: T) => void, delay: number = 0, state?: T): Subscription {\n if (AsyncScheduler.delegate && AsyncScheduler.delegate !== this) {\n return AsyncScheduler.delegate.schedule(work, delay, state);\n } else {\n return super.schedule(work, delay, state);\n }\n }\n\n public flush(action: AsyncAction<any>): void {\n\n const {actions} = this;\n\n if (this.active) {\n actions.push(action);\n return;\n }\n\n let error: any;\n this.active = true;\n\n do {\n if (error = action.execute(action.state, action.delay)) {\n break;\n }\n } while (action = actions.shift()); // exhaust the scheduler queue\n\n this.active = false;\n\n if (error) {\n while (action = actions.shift()) {\n action.unsubscribe();\n }\n throw error;\n }\n }\n}\n","import { AsyncAction } from './AsyncAction';\nimport { AsyncScheduler } from './AsyncScheduler';\n\n/**\n *\n * Async Scheduler\n *\n * <span class=\"informal\">Schedule task as if you used setTimeout(task, duration)</span>\n *\n * `async` scheduler schedules tasks asynchronously, by putting them on the JavaScript\n * event loop queue. It is best used to delay tasks in time or to schedule tasks repeating\n * in intervals.\n *\n * If you just want to \"defer\" task, that is to perform it right after currently\n * executing synchronous code ends (commonly achieved by `setTimeout(deferredTask, 0)`),\n * better choice will be the {@link asapScheduler} scheduler.\n *\n * ## Examples\n * Use async scheduler to delay task\n * ```ts\n * import { asyncScheduler } from 'rxjs';\n *\n * const task = () => console.log('it works!');\n *\n * asyncScheduler.schedule(task, 2000);\n *\n * // After 2 seconds logs:\n * // \"it works!\"\n * ```\n *\n * Use async scheduler to repeat task in intervals\n * ```ts\n * import { asyncScheduler } from 'rxjs';\n *\n * function task(state) {\n * console.log(state);\n * this.schedule(state + 1, 1000); // `this` references currently executing Action,\n * // which we reschedule with new state and delay\n * }\n *\n * asyncScheduler.schedule(task, 3000, 0);\n *\n * // Logs:\n * // 0 after 3s\n * // 1 after 4s\n * // 2 after 5s\n * // 3 after 6s\n * ```\n */\nexport const asyncScheduler = new AsyncScheduler(AsyncAction);\n\n/**\n * @deprecated renamed. Use {@link asyncScheduler}\n */\nexport const async = asyncScheduler;","import { SchedulerLike } from '../types';\n\nexport function isScheduler(value: any): value is SchedulerLike {\n return value && typeof (<any>value).schedule === 'function';\n}\n","import { Operator } from '../Operator';\nimport { Subscriber } from '../Subscriber';\nimport { Observable } from '../Observable';\n\nimport { ObservableInput, OperatorFunction, ObservedValueOf } from '../types';\nimport { SimpleOuterSubscriber, SimpleInnerSubscriber, innerSubscribe } from '../innerSubscribe';\n\n/* tslint:disable:max-line-length */\nexport function catchError<T, O extends ObservableInput<any>>(selector: (err: any, caught: Observable<T>) => O): OperatorFunction<T, T | ObservedValueOf<O>>;\n/* tslint:enable:max-line-length */\n\n/**\n * Catches errors on the observable to be handled by returning a new observable or throwing an error.\n *\n * ![](catch.png)\n *\n * ## Examples\n * Continues with a different Observable when there's an error\n *\n * ```ts\n * import { of } from 'rxjs';\n * import { map, catchError } from 'rxjs/operators';\n *\n * of(1, 2, 3, 4, 5).pipe(\n * map(n => {\n * \t if (n === 4) {\n * \t throw 'four!';\n * }\n *\t return n;\n * }),\n * catchError(err => of('I', 'II', 'III', 'IV', 'V')),\n * )\n * .subscribe(x => console.log(x));\n * // 1, 2, 3, I, II, III, IV, V\n * ```\n *\n * Retries the caught source Observable again in case of error, similar to retry() operator\n *\n * ```ts\n * import { of } from 'rxjs';\n * import { map, catchError, take } from 'rxjs/operators';\n *\n * of(1, 2, 3, 4, 5).pipe(\n * map(n => {\n * \t if (n === 4) {\n * \t throw 'four!';\n * }\n * \t return n;\n * }),\n * catchError((err, caught) => caught),\n * take(30),\n * )\n * .subscribe(x => console.log(x));\n * // 1, 2, 3, 1, 2, 3, ...\n * ```\n *\n * Throws a new error when the source Observable throws an error\n *\n * ```ts\n * import { of } from 'rxjs';\n * import { map, catchError } from 'rxjs/operators';\n *\n * of(1, 2, 3, 4, 5).pipe(\n * map(n => {\n * if (n === 4) {\n * throw 'four!';\n * }\n * return n;\n * }),\n * catchError(err => {\n * throw 'error in source. Details: ' + err;\n * }),\n * )\n * .subscribe(\n * x => console.log(x),\n * err => console.log(err)\n * );\n * // 1, 2, 3, error in source. Details: four!\n * ```\n *\n * @param {function} selector a function that takes as arguments `err`, which is the error, and `caught`, which\n * is the source observable, in case you'd like to \"retry\" that observable by returning it again. Whatever observable\n * is returned by the `selector` will be used to continue the observable chain.\n * @return {Observable} An observable that originates from either the source or the observable returned by the\n * catch `selector` function.\n * @name catchError\n */\nexport function catchError<T, O extends ObservableInput<any>>(\n selector: (err: any, caught: Observable<T>) => O\n): OperatorFunction<T, T | ObservedValueOf<O>> {\n return function catchErrorOperatorFunction(source: Observable<T>): Observable<T | ObservedValueOf<O>> {\n const operator = new CatchOperator(selector);\n const caught = source.lift(operator);\n return (operator.caught = caught as Observable<T>);\n };\n}\n\nclass CatchOperator<T, R> implements Operator<T, T | R> {\n caught: Observable<T>;\n\n constructor(private selector: (err: any, caught: Observable<T>) => ObservableInput<T | R>) {\n }\n\n call(subscriber: Subscriber<R>, source: any): any {\n return source.subscribe(new CatchSubscriber(subscriber, this.selector, this.caught));\n }\n}\n\n/**\n * We need this JSDoc comment for affecting ESDoc.\n * @ignore\n * @extends {Ignored}\n */\nclass CatchSubscriber<T, R> extends SimpleOuterSubscriber<T, T | R> {\n constructor(destination: Subscriber<any>,\n private selector: (err: any, caught: Observable<T>) => ObservableInput<T | R>,\n private caught: Observable<T>) {\n super(destination);\n }\n\n // NOTE: overriding `error` instead of `_error` because we don't want\n // to have this flag this subscriber as `isStopped`. We can mimic the\n // behavior of the RetrySubscriber (from the `retry` operator), where\n // we unsubscribe from our source chain, reset our Subscriber flags,\n // then subscribe to the selector result.\n error(err: any) {\n if (!this.isStopped) {\n let result: any;\n try {\n result = this.selector(err, this.caught);\n } catch (err2) {\n super.error(err2);\n return;\n }\n this._unsubscribeAndRecycle();\n const innerSubscriber = new SimpleInnerSubscriber(this);\n this.add(innerSubscriber);\n const innerSubscription = innerSubscribe(result, innerSubscriber);\n // The returned subscription will usually be the subscriber that was\n // passed. However, interop subscribers will be wrapped and for\n // unsubscriptions to chain correctly, the wrapper needs to be added, too.\n if (innerSubscription !== innerSubscriber) {\n this.add(innerSubscription);\n }\n }\n }\n}\n","import { Observable } from '../Observable';\nimport { SchedulerLike } from '../types';\nimport { Subscription } from '../Subscription';\n\nexport function scheduleArray<T>(input: ArrayLike<T>, scheduler: SchedulerLike) {\n return new Observable<T>(subscriber => {\n const sub = new Subscription();\n let i = 0;\n sub.add(scheduler.schedule(function () {\n if (i === input.length) {\n subscriber.complete();\n return;\n }\n subscriber.next(input[i++]);\n if (!subscriber.closed) {\n sub.add(this.schedule());\n }\n }));\n return sub;\n });\n}\n","import { Observable } from '../Observable';\nimport { SchedulerLike } from '../types';\nimport { subscribeToArray } from '../util/subscribeToArray';\nimport { scheduleArray } from '../scheduled/scheduleArray';\n\nexport function fromArray<T>(input: ArrayLike<T>, scheduler?: SchedulerLike) {\n if (!scheduler) {\n return new Observable<T>(subscribeToArray(input));\n } else {\n return scheduleArray(input, scheduler);\n }\n}\n","import { Observable } from '../Observable';\nimport { Subscription } from '../Subscription';\nimport { observable as Symbol_observable } from '../symbol/observable';\nimport { InteropObservable, SchedulerLike, Subscribable } from '../types';\n\nexport function scheduleObservable<T>(input: InteropObservable<T>, scheduler: SchedulerLike) {\n return new Observable<T>(subscriber => {\n const sub = new Subscription();\n sub.add(scheduler.schedule(() => {\n const observable: Subscribable<T> = input[Symbol_observable]();\n sub.add(observable.subscribe({\n next(value) { sub.add(scheduler.schedule(() => subscriber.next(value))); },\n error(err) { sub.add(scheduler.schedule(() => subscriber.error(err))); },\n complete() { sub.add(scheduler.schedule(() => subscriber.complete())); },\n }));\n }));\n return sub;\n });\n}\n","import { Observable } from '../Observable';\nimport { SchedulerLike } from '../types';\nimport { Subscription } from '../Subscription';\n\nexport function schedulePromise<T>(input: PromiseLike<T>, scheduler: SchedulerLike) {\n return new Observable<T>(subscriber => {\n const sub = new Subscription();\n sub.add(scheduler.schedule(() => input.then(\n value => {\n sub.add(scheduler.schedule(() => {\n subscriber.next(value);\n sub.add(scheduler.schedule(() => subscriber.complete()));\n }));\n },\n err => {\n sub.add(scheduler.schedule(() => subscriber.error(err)));\n }\n )));\n return sub;\n });\n}\n","import { Observable } from '../Observable';\nimport { SchedulerLike } from '../types';\nimport { Subscription } from '../Subscription';\nimport { iterator as Symbol_iterator } from '../symbol/iterator';\n\nexport function scheduleIterable<T>(input: Iterable<T>, scheduler: SchedulerLike) {\n if (!input) {\n throw new Error('Iterable cannot be null');\n }\n return new Observable<T>(subscriber => {\n const sub = new Subscription();\n let iterator: Iterator<T>;\n sub.add(() => {\n // Finalize generators\n if (iterator && typeof iterator.return === 'function') {\n iterator.return();\n }\n });\n sub.add(scheduler.schedule(() => {\n iterator = input[Symbol_iterator]();\n sub.add(scheduler.schedule(function () {\n if (subscriber.closed) {\n return;\n }\n let value: T;\n let done: boolean;\n try {\n const result = iterator.next();\n value = result.value;\n done = result.done;\n } catch (err) {\n subscriber.error(err);\n return;\n }\n if (done) {\n subscriber.complete();\n } else {\n subscriber.next(value);\n this.schedule();\n }\n }));\n }));\n return sub;\n });\n}\n","import { InteropObservable } from '../types';\nimport { observable as Symbol_observable } from '../symbol/observable';\n\n/** Identifies an input as being Observable (but not necessary an Rx Observable) */\nexport function isInteropObservable(input: any): input is InteropObservable<any> {\n return input && typeof input[Symbol_observable] === 'function';\n}\n","import { iterator as Symbol_iterator } from '../symbol/iterator';\n\n/** Identifies an input as being an Iterable */\nexport function isIterable(input: any): input is Iterable<any> {\n return input && typeof input[Symbol_iterator] === 'function';\n}\n","import { scheduleObservable } from './scheduleObservable';\nimport { schedulePromise } from './schedulePromise';\nimport { scheduleArray } from './scheduleArray';\nimport { scheduleIterable } from './scheduleIterable';\nimport { ObservableInput, SchedulerLike, Observable } from 'rxjs';\nimport { isInteropObservable } from '../util/isInteropObservable';\nimport { isPromise } from '../util/isPromise';\nimport { isArrayLike } from '../util/isArrayLike';\nimport { isIterable } from '../util/isIterable';\n\n/**\n * Converts from a common {@link ObservableInput} type to an observable where subscription and emissions\n * are scheduled on the provided scheduler.\n *\n * @see from\n * @see of\n *\n * @param input The observable, array, promise, iterable, etc you would like to schedule\n * @param scheduler The scheduler to use to schedule the subscription and emissions from\n * the returned observable.\n */\nexport function scheduled<T>(input: ObservableInput<T>, scheduler: SchedulerLike): Observable<T> {\n if (input != null) {\n if (isInteropObservable(input)) {\n return scheduleObservable(input, scheduler);\n } else if (isPromise(input)) {\n return schedulePromise(input, scheduler);\n } else if (isArrayLike(input)) {\n return scheduleArray(input, scheduler);\n } else if (isIterable(input) || typeof input === 'string') {\n return scheduleIterable(input, scheduler);\n }\n }\n\n throw new TypeError((input !== null && typeof input || input) + ' is not observable');\n}\n","import { Observable } from '../Observable';\nimport { subscribeTo } from '../util/subscribeTo';\nimport { ObservableInput, SchedulerLike, ObservedValueOf } from '../types';\nimport { scheduled } from '../scheduled/scheduled';\n\nexport function from<O extends ObservableInput<any>>(input: O): Observable<ObservedValueOf<O>>;\n/** @deprecated use {@link scheduled} instead. */\nexport function from<O extends ObservableInput<any>>(input: O, scheduler: SchedulerLike): Observable<ObservedValueOf<O>>;\n\n/**\n * Creates an Observable from an Array, an array-like object, a Promise, an iterable object, or an Observable-like object.\n *\n * <span class=\"informal\">Converts almost anything to an Observable.</span>\n *\n * ![](from.png)\n *\n * `from` converts various other objects and data types into Observables. It also converts a Promise, an array-like, or an\n * <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#iterable\" target=\"_blank\">iterable</a>\n * object into an Observable that emits the items in that promise, array, or iterable. A String, in this context, is treated\n * as an array of characters. Observable-like objects (contains a function named with the ES2015 Symbol for Observable) can also be\n * converted through this operator.\n *\n * ## Examples\n *\n * ### Converts an array to an Observable\n *\n * ```ts\n * import { from } from 'rxjs';\n *\n * const array = [10, 20, 30];\n * const result = from(array);\n *\n * result.subscribe(x => console.log(x));\n *\n * // Logs:\n * // 10\n * // 20\n * // 30\n * ```\n *\n * ---\n *\n * ### Convert an infinite iterable (from a generator) to an Observable\n *\n * ```ts\n * import { from } from 'rxjs';\n * import { take } from 'rxjs/operators';\n *\n * function* generateDoubles(seed) {\n * let i = seed;\n * while (true) {\n * yield i;\n * i = 2 * i; // double it\n * }\n * }\n *\n * const iterator = generateDoubles(3);\n * const result = from(iterator).pipe(take(10));\n *\n * result.subscribe(x => console.log(x));\n *\n * // Logs:\n * // 3\n * // 6\n * // 12\n * // 24\n * // 48\n * // 96\n * // 192\n * // 384\n * // 768\n * // 1536\n * ```\n *\n * ---\n *\n * ### With async scheduler\n *\n * ```ts\n * import { from, asyncScheduler } from 'rxjs';\n *\n * console.log('start');\n *\n * const array = [10, 20, 30];\n * const result = from(array, asyncScheduler);\n *\n * result.subscribe(x => console.log(x));\n *\n * console.log('end');\n *\n * // Logs:\n * // start\n * // end\n * // 10\n * // 20\n * // 30\n * ```\n *\n * @see {@link fromEvent}\n * @see {@link fromEventPattern}\n *\n * @param {ObservableInput<T>} A subscription object, a Promise, an Observable-like,\n * an Array, an iterable, or an array-like object to be converted.\n * @param {SchedulerLike} An optional {@link SchedulerLike} on which to schedule the emission of values.\n * @return {Observable<T>}\n * @name from\n * @owner Observable\n */\nexport function from<T>(input: ObservableInput<T>, scheduler?: SchedulerLike): Observable<T> {\n if (!scheduler) {\n if (input instanceof Observable) {\n return input;\n }\n return new Observable<T>(subscribeTo(input));\n } else {\n return scheduled(input, scheduler);\n }\n}\n","import { SchedulerLike } from '../types';\nimport { isScheduler } from '../util/isScheduler';\nimport { fromArray } from './fromArray';\nimport { Observable } from '../Observable';\nimport { scheduleArray } from '../scheduled/scheduleArray';\n\n/* tslint:disable:max-line-length */\n/** @deprecated use {@link scheduled} instead `scheduled([a, b, c], scheduler)` */\nexport function of<T>(a: T, scheduler: SchedulerLike): Observable<T>;\n/** @deprecated use {@link scheduled} instead `scheduled([a, b, c], scheduler)` */\nexport function of<T, T2>(a: T, b: T2, scheduler: SchedulerLike): Observable<T | T2>;\n/** @deprecated use {@link scheduled} instead `scheduled([a, b, c], scheduler)` */\nexport function of<T, T2, T3>(a: T, b: T2, c: T3, scheduler: SchedulerLike): Observable<T | T2 | T3>;\n/** @deprecated use {@link scheduled} instead `scheduled([a, b, c], scheduler)` */\nexport function of<T, T2, T3, T4>(a: T, b: T2, c: T3, d: T4, scheduler: SchedulerLike): Observable<T | T2 | T3 | T4>;\n/** @deprecated use {@link scheduled} instead `scheduled([a, b, c], scheduler)` */\nexport function of<T, T2, T3, T4, T5>(a: T, b: T2, c: T3, d: T4, e: T5, scheduler: SchedulerLike): Observable<T | T2 | T3 | T4 | T5>;\n/** @deprecated use {@link scheduled} instead `scheduled([a, b, c], scheduler)` */\nexport function of<T, T2, T3, T4, T5, T6>(a: T, b: T2, c: T3, d: T4, e: T5, f: T6, scheduler: SchedulerLike): Observable<T | T2 | T3 | T4 | T5 | T6>;\n/** @deprecated use {@link scheduled} instead `scheduled([a, b, c], scheduler)` */\nexport function of<T, T2, T3, T4, T5, T6, T7>(a: T, b: T2, c: T3, d: T4, e: T5, f: T6, g: T7, scheduler: SchedulerLike):\n Observable<T | T2 | T3 | T4 | T5 | T6 | T7>;\n/** @deprecated use {@link scheduled} instead `scheduled([a, b, c], scheduler)` */\nexport function of<T, T2, T3, T4, T5, T6, T7, T8>(a: T, b: T2, c: T3, d: T4, e: T5, f: T6, g: T7, h: T8, scheduler: SchedulerLike):\n Observable<T | T2 | T3 | T4 | T5 | T6 | T7 | T8>;\n/** @deprecated use {@link scheduled} instead `scheduled([a, b, c], scheduler)` */\nexport function of<T, T2, T3, T4, T5, T6, T7, T8, T9>(a: T, b: T2, c: T3, d: T4, e: T5, f: T6, g: T7, h: T8, i: T9, scheduler: SchedulerLike):\n Observable<T | T2 | T3 | T4 | T5 | T6 | T7 | T8 | T9>;\nexport function of<T>(...args: (T | SchedulerLike)[]): Observable<T>;\n\n// TODO(benlesh): Update the typings for this when we can switch to TS 3.x\nexport function of<T>(a: T): Observable<T>;\nexport function of<T, T2>(a: T, b: T2): Observable<T | T2>;\nexport function of<T, T2, T3>(a: T, b: T2, c: T3): Observable<T | T2 | T3>;\nexport function of<T, T2, T3, T4>(a: T, b: T2, c: T3, d: T4): Observable<T | T2 | T3 | T4>;\nexport function of<T, T2, T3, T4, T5>(a: T, b: T2, c: T3, d: T4, e: T5): Observable<T | T2 | T3 | T4 | T5>;\nexport function of<T, T2, T3, T4, T5, T6>(a: T, b: T2, c: T3, d: T4, e: T5, f: T6): Observable<T | T2 | T3 | T4 | T5 | T6>;\nexport function of<T, T2, T3, T4, T5, T6, T7>(a: T, b: T2, c: T3, d: T4, e: T5, f: T6, g: T7):\n Observable<T | T2 | T3 | T4 | T5 | T6 | T7>;\nexport function of<T, T2, T3, T4, T5, T6, T7, T8>(a: T, b: T2, c: T3, d: T4, e: T5, f: T6, g: T7, h: T8):\n Observable<T | T2 | T3 | T4 | T5 | T6 | T7 | T8>;\nexport function of<T, T2, T3, T4, T5, T6, T7, T8, T9>(a: T, b: T2, c: T3, d: T4, e: T5, f: T6, g: T7, h: T8, i: T9):\n Observable<T | T2 | T3 | T4 | T5 | T6 | T7 | T8 | T9>;\nexport function of<T>(...args: T[]): Observable<T>;\n/* tslint:enable:max-line-length */\n\n/**\n * Converts the arguments to an observable sequence.\n *\n * <span class=\"informal\">Each argument becomes a `next` notification.</span>\n *\n * ![](of.png)\n *\n * Unlike {@link from}, it does not do any flattening and emits each argument in whole\n * as a separate `next` notification.\n *\n * ## Examples\n *\n * Emit the values `10, 20, 30`\n *\n * ```ts\n * import { of } from 'rxjs';\n *\n * of(10, 20, 30)\n * .subscribe(\n * next => console.log('next:', next),\n * err => console.log('error:', err),\n * () => console.log('the end'),\n * );\n * // result:\n * // 'next: 10'\n * // 'next: 20'\n * // 'next: 30'\n *\n * ```\n *\n * Emit the array `[1,2,3]`\n *\n * ```ts\n * import { of } from 'rxjs';\n *\n * of([1,2,3])\n * .subscribe(\n * next => console.log('next:', next),\n * err => console.log('error:', err),\n * () => console.log('the end'),\n * );\n * // result:\n * // 'next: [1,2,3]'\n * ```\n *\n * @see {@link from}\n * @see {@link range}\n *\n * @param {...T} values A comma separated list of arguments you want to be emitted\n * @return {Observable} An Observable that emits the arguments\n * described above and then completes.\n * @method of\n * @owner Observable\n */\n\nexport function of<T>(...args: Array<T | SchedulerLike>): Observable<T> {\n let scheduler = args[args.length - 1] as SchedulerLike;\n if (isScheduler(scheduler)) {\n args.pop();\n return scheduleArray(args as T[], scheduler);\n } else {\n return fromArray(args as T[]);\n }\n}\n","import { Operator } from '../Operator';\nimport { Subscriber } from '../Subscriber';\nimport { Observable } from '../Observable';\nimport { OperatorFunction } from '../types';\n\n/**\n * Applies a given `project` function to each value emitted by the source\n * Observable, and emits the resulting values as an Observable.\n *\n * <span class=\"informal\">Like [Array.prototype.map()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map),\n * it passes each source value through a transformation function to get\n * corresponding output values.</span>\n *\n * ![](map.png)\n *\n * Similar to the well known `Array.prototype.map` function, this operator\n * applies a projection to each value and emits that projection in the output\n * Observable.\n *\n * ## Example\n * Map every click to the clientX position of that click\n * ```ts\n * import { fromEvent } from 'rxjs';\n * import { map } from 'rxjs/operators';\n *\n * const clicks = fromEvent(document, 'click');\n * const positions = clicks.pipe(map(ev => ev.clientX));\n * positions.subscribe(x => console.log(x));\n * ```\n *\n * @see {@link mapTo}\n * @see {@link pluck}\n *\n * @param {function(value: T, index: number): R} project The function to apply\n * to each `value` emitted by the source Observable. The `index` parameter is\n * the number `i` for the i-th emission that has happened since the\n * subscription, starting from the number `0`.\n * @param {any} [thisArg] An optional argument to define what `this` is in the\n * `project` function.\n * @return {Observable<R>} An Observable that emits the values from the source\n * Observable transformed by the given `project` function.\n * @method map\n * @owner Observable\n */\nexport function map<T, R>(project: (value: T, index: number) => R, thisArg?: any): OperatorFunction<T, R> {\n return function mapOperation(source: Observable<T>): Observable<R> {\n if (typeof project !== 'function') {\n throw new TypeError('argument is not a function. Are you looking for `mapTo()`?');\n }\n return source.lift(new MapOperator(project, thisArg));\n };\n}\n\nexport class MapOperator<T, R> implements Operator<T, R> {\n constructor(private project: (value: T, index: number) => R, private thisArg: any) {\n }\n\n call(subscriber: Subscriber<R>, source: any): any {\n return source.subscribe(new MapSubscriber(subscriber, this.project, this.thisArg));\n }\n}\n\n/**\n * We need this JSDoc comment for affecting ESDoc.\n * @ignore\n * @extends {Ignored}\n */\nclass MapSubscriber<T, R> extends Subscriber<T> {\n count: number = 0;\n private thisArg: any;\n\n constructor(destination: Subscriber<R>,\n private project: (value: T, index: number) => R,\n thisArg: any) {\n super(destination);\n this.thisArg = thisArg || this;\n }\n\n // NOTE: This looks unoptimized, but it's actually purposefully NOT\n // using try/catch optimizations.\n protected _next(value: T) {\n let result: R;\n try {\n result = this.project.call(this.thisArg, value, this.count++);\n } catch (err) {\n this.destination.error(err);\n return;\n }\n this.destination.next(result);\n }\n}\n","import { Observable } from '../Observable';\nimport { Operator } from '../Operator';\nimport { Subscriber } from '../Subscriber';\nimport { Subscription } from '../Subscription';\nimport { ObservableInput, OperatorFunction, ObservedValueOf } from '../types';\nimport { map } from './map';\nimport { from } from '../observable/from';\nimport { SimpleOuterSubscriber, SimpleInnerSubscriber, innerSubscribe } from '../innerSubscribe';\n\n/* tslint:disable:max-line-length */\nexport function mergeMap<T, O extends ObservableInput<any>>(project: (value: T, index: number) => O, concurrent?: number): OperatorFunction<T, ObservedValueOf<O>>;\n/** @deprecated resultSelector no longer supported, use inner map instead */\nexport function mergeMap<T, O extends ObservableInput<any>>(project: (value: T, index: number) => O, resultSelector: undefined, concurrent?: number): OperatorFunction<T, ObservedValueOf<O>>;\n/** @deprecated resultSelector no longer supported, use inner map instead */\nexport function mergeMap<T, R, O extends ObservableInput<any>>(project: (value: T, index: number) => O, resultSelector: (outerValue: T, innerValue: ObservedValueOf<O>, outerIndex: number, innerIndex: number) => R, concurrent?: number): OperatorFunction<T, R>;\n/* tslint:enable:max-line-length */\n\n/**\n * Projects each source value to an Observable which is merged in the output\n * Observable.\n *\n * <span class=\"informal\">Maps each value to an Observable, then flattens all of\n * these inner Observables using {@link mergeAll}.</span>\n *\n * ![](mergeMap.png)\n *\n * Returns an Observable that emits items based on applying a function that you\n * supply to each item emitted by the source Observable, where that function\n * returns an Observable, and then merging those resulting Observables and\n * emitting the results of this merger.\n *\n * ## Example\n * Map and flatten each letter to an Observable ticking every 1 second\n * ```ts\n * import { of, interval } from 'rxjs';\n * import { mergeMap, map } from 'rxjs/operators';\n *\n * const letters = of('a', 'b', 'c');\n * const result = letters.pipe(\n * mergeMap(x => interval(1000).pipe(map(i => x+i))),\n * );\n * result.subscribe(x => console.log(x));\n *\n * // Results in the following:\n * // a0\n * // b0\n * // c0\n * // a1\n * // b1\n * // c1\n * // continues to list a,b,c with respective ascending integers\n * ```\n *\n * @see {@link concatMap}\n * @see {@link exhaustMap}\n * @see {@link merge}\n * @see {@link mergeAll}\n * @see {@link mergeMapTo}\n * @see {@link mergeScan}\n * @see {@link switchMap}\n *\n * @param {function(value: T, ?index: number): ObservableInput} project A function\n * that, when applied to an item emitted by the source Observable, returns an\n * Observable.\n * @param {number} [concurrent=Number.POSITIVE_INFINITY] Maximum number of input\n * Observables being subscribed to concurrently.\n * @return {Observable} An Observable that emits the result of applying the\n * projection function (and the optional deprecated `resultSelector`) to each item\n * emitted by the source Observable and merging the results of the Observables\n * obtained from this transformation.\n */\nexport function mergeMap<T, R, O extends ObservableInput<any>>(\n project: (value: T, index: number) => O,\n resultSelector?: ((outerValue: T, innerValue: ObservedValueOf<O>, outerIndex: number, innerIndex: number) => R) | number,\n concurrent: number = Number.POSITIVE_INFINITY\n): OperatorFunction<T, ObservedValueOf<O>|R> {\n if (typeof resultSelector === 'function') {\n // DEPRECATED PATH\n return (source: Observable<T>) => source.pipe(\n mergeMap((a, i) => from(project(a, i)).pipe(\n map((b: any, ii: number) => resultSelector(a, b, i, ii)),\n ), concurrent)\n );\n } else if (typeof resultSelector === 'number') {\n concurrent = resultSelector;\n }\n return (source: Observable<T>) => source.lift(new MergeMapOperator(project, concurrent));\n}\n\nexport class MergeMapOperator<T, R> implements Operator<T, R> {\n constructor(private project: (value: T, index: number) => ObservableInput<R>,\n private concurrent: number = Number.POSITIVE_INFINITY) {\n }\n\n call(observer: Subscriber<R>, source: any): any {\n return source.subscribe(new MergeMapSubscriber(\n observer, this.project, this.concurrent\n ));\n }\n}\n\n/**\n * We need this JSDoc comment for affecting ESDoc.\n * @ignore\n * @extends {Ignored}\n */\nexport class MergeMapSubscriber<T, R> extends SimpleOuterSubscriber<T, R> {\n private hasCompleted: boolean = false;\n private buffer: T[] = [];\n private active: number = 0;\n protected index: number = 0;\n\n constructor(destination: Subscriber<R>,\n private project: (value: T, index: number) => ObservableInput<R>,\n private concurrent: number = Number.POSITIVE_INFINITY) {\n super(destination);\n }\n\n protected _next(value: T): void {\n if (this.active < this.concurrent) {\n this._tryNext(value);\n } else {\n this.buffer.push(value);\n }\n }\n\n protected _tryNext(value: T) {\n let result: ObservableInput<R>;\n const index = this.index++;\n try {\n result = this.project(value, index);\n } catch (err) {\n this.destination.error!(err);\n return;\n }\n this.active++;\n this._innerSub(result);\n }\n\n private _innerSub(ish: ObservableInput<R>): void {\n const innerSubscriber = new SimpleInnerSubscriber(this);\n const destination = this.destination as Subscription;\n destination.add(innerSubscriber);\n const innerSubscription = innerSubscribe(ish, innerSubscriber);\n // The returned subscription will usually be the subscriber that was\n // passed. However, interop subscribers will be wrapped and for\n // unsubscriptions to chain correctly, the wrapper needs to be added, too.\n if (innerSubscription !== innerSubscriber) {\n destination.add(innerSubscription);\n }\n }\n\n protected _complete(): void {\n this.hasCompleted = true;\n if (this.active === 0 && this.buffer.length === 0) {\n this.destination.complete!();\n }\n this.unsubscribe();\n }\n\n notifyNext(innerValue: R): void {\n this.destination.next!(innerValue);\n }\n\n notifyComplete(): void {\n const buffer = this.buffer;\n this.active--;\n if (buffer.length > 0) {\n this._next(buffer.shift()!);\n } else if (this.active === 0 && this.hasCompleted) {\n this.destination.complete!();\n }\n }\n}\n\n/**\n * @deprecated renamed. Use {@link mergeMap}\n */\nexport const flatMap = mergeMap;","\nimport { mergeMap } from './mergeMap';\nimport { identity } from '../util/identity';\nimport { OperatorFunction, ObservableInput } from '../types';\n\n/**\n * Converts a higher-order Observable into a first-order Observable which\n * concurrently delivers all values that are emitted on the inner Observables.\n *\n * <span class=\"informal\">Flattens an Observable-of-Observables.</span>\n *\n * ![](mergeAll.png)\n *\n * `mergeAll` subscribes to an Observable that emits Observables, also known as\n * a higher-order Observable. Each time it observes one of these emitted inner\n * Observables, it subscribes to that and delivers all the values from the\n * inner Observable on the output Observable. The output Observable only\n * completes once all inner Observables have completed. Any error delivered by\n * a inner Observable will be immediately emitted on the output Observable.\n *\n * ## Examples\n * Spawn a new interval Observable for each click event, and blend their outputs as one Observable\n * ```ts\n * import { fromEvent, interval } from 'rxjs';\n * import { map, mergeAll } from 'rxjs/operators';\n *\n * const clicks = fromEvent(document, 'click');\n * const higherOrder = clicks.pipe(map((ev) => interval(1000)));\n * const firstOrder = higherOrder.pipe(mergeAll());\n * firstOrder.subscribe(x => console.log(x));\n * ```\n *\n * Count from 0 to 9 every second for each click, but only allow 2 concurrent timers\n * ```ts\n * import { fromEvent, interval } from 'rxjs';\n * import { take, map, mergeAll } from 'rxjs/operators';\n *\n * const clicks = fromEvent(document, 'click');\n * const higherOrder = clicks.pipe(\n * map((ev) => interval(1000).pipe(take(10))),\n * );\n * const firstOrder = higherOrder.pipe(mergeAll(2));\n * firstOrder.subscribe(x => console.log(x));\n * ```\n *\n * @see {@link combineAll}\n * @see {@link concatAll}\n * @see {@link exhaust}\n * @see {@link merge}\n * @see {@link mergeMap}\n * @see {@link mergeMapTo}\n * @see {@link mergeScan}\n * @see {@link switchAll}\n * @see {@link switchMap}\n * @see {@link zipAll}\n *\n * @param {number} [concurrent=Number.POSITIVE_INFINITY] Maximum number of inner\n * Observables being subscribed to concurrently.\n * @return {Observable} An Observable that emits values coming from all the\n * inner Observables emitted by the source Observable.\n * @method mergeAll\n * @owner Observable\n */\nexport function mergeAll<T>(concurrent: number = Number.POSITIVE_INFINITY): OperatorFunction<ObservableInput<T>, T> {\n return mergeMap(identity, concurrent);\n}\n","\nimport { mergeAll } from './mergeAll';\nimport { OperatorFunction, ObservableInput } from '../types';\n\nexport function concatAll<T>(): OperatorFunction<ObservableInput<T>, T>;\nexport function concatAll<R>(): OperatorFunction<any, R>;\n\n/**\n * Converts a higher-order Observable into a first-order Observable by\n * concatenating the inner Observables in order.\n *\n * <span class=\"informal\">Flattens an Observable-of-Observables by putting one\n * inner Observable after the other.</span>\n *\n * ![](concatAll.png)\n *\n * Joins every Observable emitted by the source (a higher-order Observable), in\n * a serial fashion. It subscribes to each inner Observable only after the\n * previous inner Observable has completed, and merges all of their values into\n * the returned observable.\n *\n * __Warning:__ If the source Observable emits Observables quickly and\n * endlessly, and the inner Observables it emits generally complete slower than\n * the source emits, you can run into memory issues as the incoming Observables\n * collect in an unbounded buffer.\n *\n * Note: `concatAll` is equivalent to `mergeAll` with concurrency parameter set\n * to `1`.\n *\n * ## Example\n *\n * For each click event, tick every second from 0 to 3, with no concurrency\n * ```ts\n * import { fromEvent, interval } from 'rxjs';\n * import { map, take, concatAll } from 'rxjs/operators';\n *\n * const clicks = fromEvent(document, 'click');\n * const higherOrder = clicks.pipe(\n * map(ev => interval(1000).pipe(take(4))),\n * );\n * const firstOrder = higherOrder.pipe(concatAll());\n * firstOrder.subscribe(x => console.log(x));\n *\n * // Results in the following:\n * // (results are not concurrent)\n * // For every click on the \"document\" it will emit values 0 to 3 spaced\n * // on a 1000ms interval\n * // one click = 1000ms-> 0 -1000ms-> 1 -1000ms-> 2 -1000ms-> 3\n * ```\n *\n * @see {@link combineAll}\n * @see {@link concat}\n * @see {@link concatMap}\n * @see {@link concatMapTo}\n * @see {@link exhaust}\n * @see {@link mergeAll}\n * @see {@link switchAll}\n * @see {@link switchMap}\n * @see {@link zipAll}\n *\n * @return {Observable} An Observable emitting values from all the inner\n * Observables concatenated.\n * @method concatAll\n * @owner Observable\n */\nexport function concatAll<T>(): OperatorFunction<ObservableInput<T>, T> {\n return mergeAll<T>(1);\n}\n","import { Observable } from '../Observable';\nimport { ObservableInput, SchedulerLike, ObservedValueOf } from '../types';\nimport { isScheduler } from '../util/isScheduler';\nimport { of } from './of';\nimport { from } from './from';\nimport { concatAll } from '../operators/concatAll';\n\n/* tslint:disable:max-line-length */\n/** @deprecated Use {@link scheduled} and {@link concatAll} (e.g. `scheduled([o1, o2, o3], scheduler).pipe(concatAll())`) */\nexport function concat<O1 extends ObservableInput<any>>(v1: O1, scheduler: SchedulerLike): Observable<ObservedValueOf<O1>>;\n/** @deprecated Use {@link scheduled} and {@link concatAll} (e.g. `scheduled([o1, o2, o3], scheduler).pipe(concatAll())`) */\nexport function concat<O1 extends ObservableInput<any>, O2 extends ObservableInput<any>>(v1: O1, v2: O2, scheduler: SchedulerLike): Observable<ObservedValueOf<O1> | ObservedValueOf<O2>>;\n/** @deprecated Use {@link scheduled} and {@link concatAll} (e.g. `scheduled([o1, o2, o3], scheduler).pipe(concatAll())`) */\nexport function concat<O1 extends ObservableInput<any>, O2 extends ObservableInput<any>, O3 extends ObservableInput<any>>(v1: O1, v2: O2, v3: O3, scheduler: SchedulerLike): Observable<ObservedValueOf<O1> | ObservedValueOf<O2> | ObservedValueOf<O3>>;\n/** @deprecated Use {@link scheduled} and {@link concatAll} (e.g. `scheduled([o1, o2, o3], scheduler).pipe(concatAll())`) */\nexport function concat<O1 extends ObservableInput<any>, O2 extends ObservableInput<any>, O3 extends ObservableInput<any>, O4 extends ObservableInput<any>>(v1: O1, v2: O2, v3: O3, v4: O4, scheduler: SchedulerLike): Observable<ObservedValueOf<O1> | ObservedValueOf<O2> | ObservedValueOf<O3> | ObservedValueOf<O4>>;\n/** @deprecated Use {@link scheduled} and {@link concatAll} (e.g. `scheduled([o1, o2, o3], scheduler).pipe(concatAll())`) */\nexport function concat<O1 extends ObservableInput<any>, O2 extends ObservableInput<any>, O3 extends ObservableInput<any>, O4 extends ObservableInput<any>, O5 extends ObservableInput<any>>(v1: O1, v2: O2, v3: O3, v4: O4, v5: O5, scheduler: SchedulerLike): Observable<ObservedValueOf<O1> | ObservedValueOf<O2> | ObservedValueOf<O3> | ObservedValueOf<O4> | ObservedValueOf<O5>>;\n/** @deprecated Use {@link scheduled} and {@link concatAll} (e.g. `scheduled([o1, o2, o3], scheduler).pipe(concatAll())`) */\nexport function concat<O1 extends ObservableInput<any>, O2 extends ObservableInput<any>, O3 extends ObservableInput<any>, O4 extends ObservableInput<any>, O5 extends ObservableInput<any>, O6 extends ObservableInput<any>>(v1: O1, v2: O2, v3: O3, v4: O4, v5: O5, v6: O6, scheduler: SchedulerLike): Observable<ObservedValueOf<O1> | ObservedValueOf<O2> | ObservedValueOf<O3> | ObservedValueOf<O4> | ObservedValueOf<O5> | ObservedValueOf<O6>>;\n\nexport function concat<O1 extends ObservableInput<any>>(v1: O1): Observable<ObservedValueOf<O1>>;\nexport function concat<O1 extends ObservableInput<any>, O2 extends ObservableInput<any>>(v1: O1, v2: O2): Observable<ObservedValueOf<O1> | ObservedValueOf<O2>>;\nexport function concat<O1 extends ObservableInput<any>, O2 extends ObservableInput<any>, O3 extends ObservableInput<any>>(v1: O1, v2: O2, v3: O3): Observable<ObservedValueOf<O1> | ObservedValueOf<O2> | ObservedValueOf<O3>>;\nexport function concat<O1 extends ObservableInput<any>, O2 extends ObservableInput<any>, O3 extends ObservableInput<any>, O4 extends ObservableInput<any>>(v1: O1, v2: O2, v3: O3, v4: O4): Observable<ObservedValueOf<O1> | ObservedValueOf<O2> | ObservedValueOf<O3> | ObservedValueOf<O4>>;\nexport function concat<O1 extends ObservableInput<any>, O2 extends ObservableInput<any>, O3 extends ObservableInput<any>, O4 extends ObservableInput<any>, O5 extends ObservableInput<any>>(v1: O1, v2: O2, v3: O3, v4: O4, v5: O5): Observable<ObservedValueOf<O1> | ObservedValueOf<O2> | ObservedValueOf<O3> | ObservedValueOf<O4> | ObservedValueOf<O5>>;\nexport function concat<O1 extends ObservableInput<any>, O2 extends ObservableInput<any>, O3 extends ObservableInput<any>, O4 extends ObservableInput<any>, O5 extends ObservableInput<any>, O6 extends ObservableInput<any>>(v1: O1, v2: O2, v3: O3, v4: O4, v5: O5, v6: O6): Observable<ObservedValueOf<O1> | ObservedValueOf<O2> | ObservedValueOf<O3> | ObservedValueOf<O4> | ObservedValueOf<O5> | ObservedValueOf<O6>>;\nexport function concat<O extends ObservableInput<any>>(...observables: O[]): Observable<ObservedValueOf<O>>;\n/** @deprecated Use {@link scheduled} and {@link concatAll} (e.g. `scheduled([o1, o2, o3], scheduler).pipe(concatAll())`) */\nexport function concat<O extends ObservableInput<any>>(...observables: (O | SchedulerLike)[]): Observable<ObservedValueOf<O>>;\nexport function concat<R>(...observables: ObservableInput<any>[]): Observable<R>;\n/** @deprecated Use {@link scheduled} and {@link concatAll} (e.g. `scheduled([o1, o2, o3], scheduler).pipe(concatAll())`) */\nexport function concat<R>(...observables: (ObservableInput<any> | SchedulerLike)[]): Observable<R>;\n/* tslint:enable:max-line-length */\n/**\n * Creates an output Observable which sequentially emits all values from given\n * Observable and then moves on to the next.\n *\n * <span class=\"informal\">Concatenates multiple Observables together by\n * sequentially emitting their values, one Observable after the other.</span>\n *\n * ![](concat.png)\n *\n * `concat` joins multiple Observables together, by subscribing to them one at a time and\n * merging their results into the output Observable. You can pass either an array of\n * Observables, or put them directly as arguments. Passing an empty array will result\n * in Observable that completes immediately.\n *\n * `concat` will subscribe to first input Observable and emit all its values, without\n * changing or affecting them in any way. When that Observable completes, it will\n * subscribe to then next Observable passed and, again, emit its values. This will be\n * repeated, until the operator runs out of Observables. When last input Observable completes,\n * `concat` will complete as well. At any given moment only one Observable passed to operator\n * emits values. If you would like to emit values from passed Observables concurrently, check out\n * {@link merge} instead, especially with optional `concurrent` parameter. As a matter of fact,\n * `concat` is an equivalent of `merge` operator with `concurrent` parameter set to `1`.\n *\n * Note that if some input Observable never completes, `concat` will also never complete\n * and Observables following the one that did not complete will never be subscribed. On the other\n * hand, if some Observable simply completes immediately after it is subscribed, it will be\n * invisible for `concat`, which will just move on to the next Observable.\n *\n * If any Observable in chain errors, instead of passing control to the next Observable,\n * `concat` will error immediately as well. Observables that would be subscribed after\n * the one that emitted error, never will.\n *\n * If you pass to `concat` the same Observable many times, its stream of values\n * will be \"replayed\" on every subscription, which means you can repeat given Observable\n * as many times as you like. If passing the same Observable to `concat` 1000 times becomes tedious,\n * you can always use {@link repeat}.\n *\n * ## Examples\n * ### Concatenate a timer counting from 0 to 3 with a synchronous sequence from 1 to 10\n * ```ts\n * import { concat, interval, range } from 'rxjs';\n * import { take } from 'rxjs/operators';\n *\n * const timer = interval(1000).pipe(take(4));\n * const sequence = range(1, 10);\n * const result = concat(timer, sequence);\n * result.subscribe(x => console.log(x));\n *\n * // results in:\n * // 0 -1000ms-> 1 -1000ms-> 2 -1000ms-> 3 -immediate-> 1 ... 10\n * ```\n *\n * ### Concatenate 3 Observables\n * ```ts\n * import { concat, interval } from 'rxjs';\n * import { take } from 'rxjs/operators';\n *\n * const timer1 = interval(1000).pipe(take(10));\n * const timer2 = interval(2000).pipe(take(6));\n * const timer3 = interval(500).pipe(take(10));\n *\n * const result = concat(timer1, timer2, timer3);\n * result.subscribe(x => console.log(x));\n *\n * // results in the following:\n * // (Prints to console sequentially)\n * // -1000ms-> 0 -1000ms-> 1 -1000ms-> ... 9\n * // -2000ms-> 0 -2000ms-> 1 -2000ms-> ... 5\n * // -500ms-> 0 -500ms-> 1 -500ms-> ... 9\n * ```\n *\n * ### Concatenate the same Observable to repeat it\n * ```ts\n * import { concat, interval } from 'rxjs';\n * import { take } from 'rxjs/operators';\n *\n * const timer = interval(1000).pipe(take(2));\n *\n * concat(timer, timer) // concatenating the same Observable!\n * .subscribe(\n * value => console.log(value),\n * err => {},\n * () => console.log('...and it is done!')\n * );\n *\n * // Logs:\n * // 0 after 1s\n * // 1 after 2s\n * // 0 after 3s\n * // 1 after 4s\n * // \"...and it is done!\" also after 4s\n * ```\n *\n * @see {@link concatAll}\n * @see {@link concatMap}\n * @see {@link concatMapTo}\n * @see {@link startWith}\n * @see {@link endWith}\n *\n * @param {ObservableInput} input1 An input Observable to concatenate with others.\n * @param {ObservableInput} input2 An input Observable to concatenate with others.\n * More than one input Observables may be given as argument.\n * @param {SchedulerLike} [scheduler=null] An optional {@link SchedulerLike} to schedule each\n * Observable subscription on.\n * @return {Observable} All values of each passed Observable merged into a\n * single Observable, in order, in serial fashion.\n * @static true\n * @name concat\n * @owner Observable\n */\nexport function concat<O extends ObservableInput<any>, R>(...observables: Array<O | SchedulerLike>): Observable<ObservedValueOf<O> | R> {\n return concatAll<R>()(of(...observables));\n}\n","import { Operator } from '../Operator';\nimport { Observable } from '../Observable';\nimport { Subscriber } from '../Subscriber';\nimport { Subscription } from '../Subscription';\nimport { async } from '../scheduler/async';\nimport { MonoTypeOperatorFunction, SchedulerLike, TeardownLogic } from '../types';\n\n/**\n * Emits a value from the source Observable only after a particular time span\n * has passed without another source emission.\n *\n * <span class=\"informal\">It's like {@link delay}, but passes only the most\n * recent value from each burst of emissions.</span>\n *\n * ![](debounceTime.png)\n *\n * `debounceTime` delays values emitted by the source Observable, but drops\n * previous pending delayed emissions if a new value arrives on the source\n * Observable. This operator keeps track of the most recent value from the\n * source Observable, and emits that only when `dueTime` enough time has passed\n * without any other value appearing on the source Observable. If a new value\n * appears before `dueTime` silence occurs, the previous value will be dropped\n * and will not be emitted on the output Observable.\n *\n * This is a rate-limiting operator, because it is impossible for more than one\n * value to be emitted in any time window of duration `dueTime`, but it is also\n * a delay-like operator since output emissions do not occur at the same time as\n * they did on the source Observable. Optionally takes a {@link SchedulerLike} for\n * managing timers.\n *\n * ## Example\n * Emit the most recent click after a burst of clicks\n * ```ts\n * import { fromEvent } from 'rxjs';\n * import { debounceTime } from 'rxjs/operators';\n *\n * const clicks = fromEvent(document, 'click');\n * const result = clicks.pipe(debounceTime(1000));\n * result.subscribe(x => console.log(x));\n * ```\n *\n * @see {@link auditTime}\n * @see {@link debounce}\n * @see {@link delay}\n * @see {@link sampleTime}\n * @see {@link throttleTime}\n *\n * @param {number} dueTime The timeout duration in milliseconds (or the time\n * unit determined internally by the optional `scheduler`) for the window of\n * time required to wait for emission silence before emitting the most recent\n * source value.\n * @param {SchedulerLike} [scheduler=async] The {@link SchedulerLike} to use for\n * managing the timers that handle the timeout for each value.\n * @return {Observable} An Observable that delays the emissions of the source\n * Observable by the specified `dueTime`, and may drop some values if they occur\n * too frequently.\n * @method debounceTime\n * @owner Observable\n */\nexport function debounceTime<T>(dueTime: number, scheduler: SchedulerLike = async): MonoTypeOperatorFunction<T> {\n return (source: Observable<T>) => source.lift(new DebounceTimeOperator(dueTime, scheduler));\n}\n\nclass DebounceTimeOperator<T> implements Operator<T, T> {\n constructor(private dueTime: number, private scheduler: SchedulerLike) {\n }\n\n call(subscriber: Subscriber<T>, source: any): TeardownLogic {\n return source.subscribe(new DebounceTimeSubscriber(subscriber, this.dueTime, this.scheduler));\n }\n}\n\n/**\n * We need this JSDoc comment for affecting ESDoc.\n * @ignore\n * @extends {Ignored}\n */\nclass DebounceTimeSubscriber<T> extends Subscriber<T> {\n private debouncedSubscription: Subscription = null;\n private lastValue: T = null;\n private hasValue: boolean = false;\n\n constructor(destination: Subscriber<T>,\n private dueTime: number,\n private scheduler: SchedulerLike) {\n super(destination);\n }\n\n protected _next(value: T) {\n this.clearDebounce();\n this.lastValue = value;\n this.hasValue = true;\n this.add(this.debouncedSubscription = this.scheduler.schedule(dispatchNext, this.dueTime, this));\n }\n\n protected _complete() {\n this.debouncedNext();\n this.destination.complete();\n }\n\n debouncedNext(): void {\n this.clearDebounce();\n\n if (this.hasValue) {\n const { lastValue } = this;\n // This must be done *before* passing the value\n // along to the destination because it's possible for\n // the value to synchronously re-enter this operator\n // recursively when scheduled with things like\n // VirtualScheduler/TestScheduler.\n this.lastValue = null;\n this.hasValue = false;\n this.destination.next(lastValue);\n }\n }\n\n private clearDebounce(): void {\n const debouncedSubscription = this.debouncedSubscription;\n\n if (debouncedSubscription !== null) {\n this.remove(debouncedSubscription);\n debouncedSubscription.unsubscribe();\n this.debouncedSubscription = null;\n }\n }\n}\n\nfunction dispatchNext(subscriber: DebounceTimeSubscriber<any>) {\n subscriber.debouncedNext();\n}\n","export function isDate(value: any): value is Date {\n return value instanceof Date && !isNaN(+value);\n}\n","import { Observable } from '../Observable';\nimport { SchedulerLike } from '../types';\n\n/**\n * The same Observable instance returned by any call to {@link empty} without a\n * `scheduler`. It is preferrable to use this over `empty()`.\n */\nexport const EMPTY = new Observable<never>(subscriber => subscriber.complete());\n\n/**\n * Creates an Observable that emits no items to the Observer and immediately\n * emits a complete notification.\n *\n * <span class=\"informal\">Just emits 'complete', and nothing else.\n * </span>\n *\n * ![](empty.png)\n *\n * This static operator is useful for creating a simple Observable that only\n * emits the complete notification. It can be used for composing with other\n * Observables, such as in a {@link mergeMap}.\n *\n * ## Examples\n * ### Emit the number 7, then complete\n * ```ts\n * import { empty } from 'rxjs';\n * import { startWith } from 'rxjs/operators';\n *\n * const result = empty().pipe(startWith(7));\n * result.subscribe(x => console.log(x));\n * ```\n *\n * ### Map and flatten only odd numbers to the sequence 'a', 'b', 'c'\n * ```ts\n * import { empty, interval, of } from 'rxjs';\n * import { mergeMap } from 'rxjs/operators';\n *\n * const interval$ = interval(1000);\n * const result = interval$.pipe(\n * mergeMap(x => x % 2 === 1 ? of('a', 'b', 'c') : empty()),\n * );\n * result.subscribe(x => console.log(x));\n *\n * // Results in the following to the console:\n * // x is equal to the count on the interval eg(0,1,2,3,...)\n * // x will occur every 1000ms\n * // if x % 2 is equal to 1 print abc\n * // if x % 2 is not equal to 1 nothing will be output\n * ```\n *\n * @see {@link Observable}\n * @see {@link never}\n * @see {@link of}\n * @see {@link throwError}\n *\n * @param scheduler A {@link SchedulerLike} to use for scheduling\n * the emission of the complete notification.\n * @return An \"empty\" Observable: emits only the complete\n * notification.\n * @deprecated Deprecated in favor of using {@link EMPTY} constant, or {@link scheduled} (e.g. `scheduled([], scheduler)`)\n */\nexport function empty(scheduler?: SchedulerLike) {\n return scheduler ? emptyScheduled(scheduler) : EMPTY;\n}\n\nfunction emptyScheduled(scheduler: SchedulerLike) {\n return new Observable<never>(subscriber => scheduler.schedule(() => subscriber.complete()));\n}\n","import { Observable } from '../Observable';\nimport { SchedulerLike } from '../types';\nimport { Subscriber } from '../Subscriber';\n\n/**\n * Creates an Observable that emits no items to the Observer and immediately\n * emits an error notification.\n *\n * <span class=\"informal\">Just emits 'error', and nothing else.\n * </span>\n *\n * ![](throw.png)\n *\n * This static operator is useful for creating a simple Observable that only\n * emits the error notification. It can be used for composing with other\n * Observables, such as in a {@link mergeMap}.\n *\n * ## Examples\n * ### Emit the number 7, then emit an error\n * ```ts\n * import { throwError, concat, of } from 'rxjs';\n *\n * const result = concat(of(7), throwError(new Error('oops!')));\n * result.subscribe(x => console.log(x), e => console.error(e));\n *\n * // Logs:\n * // 7\n * // Error: oops!\n * ```\n *\n * ---\n *\n * ### Map and flatten numbers to the sequence 'a', 'b', 'c', but throw an error for 2\n * ```ts\n * import { throwError, interval, of } from 'rxjs';\n * import { mergeMap } from 'rxjs/operators';\n *\n * interval(1000).pipe(\n * mergeMap(x => x === 2\n * ? throwError('Twos are bad')\n * : of('a', 'b', 'c')\n * ),\n * ).subscribe(x => console.log(x), e => console.error(e));\n *\n * // Logs:\n * // a\n * // b\n * // c\n * // a\n * // b\n * // c\n * // Twos are bad\n * ```\n *\n * @see {@link Observable}\n * @see {@link empty}\n * @see {@link never}\n * @see {@link of}\n *\n * @param {any} error The particular Error to pass to the error notification.\n * @param {SchedulerLike} [scheduler] A {@link SchedulerLike} to use for scheduling\n * the emission of the error notification.\n * @return {Observable} An error Observable: emits only the error notification\n * using the given error argument.\n * @static true\n * @name throwError\n * @owner Observable\n */\nexport function throwError(error: any, scheduler?: SchedulerLike): Observable<never> {\n if (!scheduler) {\n return new Observable(subscriber => subscriber.error(error));\n } else {\n return new Observable(subscriber => scheduler.schedule(dispatch, 0, { error, subscriber }));\n }\n}\n\ninterface DispatchArg {\n error: any;\n subscriber: Subscriber<any>;\n}\n\nfunction dispatch({ error, subscriber }: DispatchArg) {\n subscriber.error(error);\n}\n","import { PartialObserver } from './types';\nimport { Observable } from './Observable';\nimport { empty } from './observable/empty';\nimport { of } from './observable/of';\nimport { throwError } from './observable/throwError';\nimport { deprecate } from 'util';\n\n// TODO: When this enum is removed, replace it with a type alias. See #4556.\n/**\n * @deprecated NotificationKind is deprecated as const enums are not compatible with isolated modules. Use a string literal instead.\n */\nexport enum NotificationKind {\n NEXT = 'N',\n ERROR = 'E',\n COMPLETE = 'C',\n}\n\n/**\n * Represents a push-based event or value that an {@link Observable} can emit.\n * This class is particularly useful for operators that manage notifications,\n * like {@link materialize}, {@link dematerialize}, {@link observeOn}, and\n * others. Besides wrapping the actual delivered value, it also annotates it\n * with metadata of, for instance, what type of push message it is (`next`,\n * `error`, or `complete`).\n *\n * @see {@link materialize}\n * @see {@link dematerialize}\n * @see {@link observeOn}\n *\n * @class Notification<T>\n */\nexport class Notification<T> {\n hasValue: boolean;\n\n constructor(public kind: 'N' | 'E' | 'C', public value?: T, public error?: any) {\n this.hasValue = kind === 'N';\n }\n\n /**\n * Delivers to the given `observer` the value wrapped by this Notification.\n * @param {Observer} observer\n * @return\n */\n observe(observer: PartialObserver<T>): any {\n switch (this.kind) {\n case 'N':\n return observer.next && observer.next(this.value);\n case 'E':\n return observer.error && observer.error(this.error);\n case 'C':\n return observer.complete && observer.complete();\n }\n }\n\n /**\n * Given some {@link Observer} callbacks, deliver the value represented by the\n * current Notification to the correctly corresponding callback.\n * @param {function(value: T): void} next An Observer `next` callback.\n * @param {function(err: any): void} [error] An Observer `error` callback.\n * @param {function(): void} [complete] An Observer `complete` callback.\n * @return {any}\n */\n do(next: (value: T) => void, error?: (err: any) => void, complete?: () => void): any {\n const kind = this.kind;\n switch (kind) {\n case 'N':\n return next && next(this.value);\n case 'E':\n return error && error(this.error);\n case 'C':\n return complete && complete();\n }\n }\n\n /**\n * Takes an Observer or its individual callback functions, and calls `observe`\n * or `do` methods accordingly.\n * @param {Observer|function(value: T): void} nextOrObserver An Observer or\n * the `next` callback.\n * @param {function(err: any): void} [error] An Observer `error` callback.\n * @param {function(): void} [complete] An Observer `complete` callback.\n * @return {any}\n */\n accept(nextOrObserver: PartialObserver<T> | ((value: T) => void), error?: (err: any) => void, complete?: () => void) {\n if (nextOrObserver && typeof (<PartialObserver<T>>nextOrObserver).next === 'function') {\n return this.observe(<PartialObserver<T>>nextOrObserver);\n } else {\n return this.do(<(value: T) => void>nextOrObserver, error, complete);\n }\n }\n\n /**\n * Returns a simple Observable that just delivers the notification represented\n * by this Notification instance.\n * @return {any}\n */\n toObservable(): Observable<T> {\n const kind = this.kind;\n switch (kind) {\n case 'N':\n return of(this.value);\n case 'E':\n return throwError(this.error);\n case 'C':\n return empty();\n }\n throw new Error('unexpected notification kind value');\n }\n\n private static completeNotification: Notification<any> = new Notification('C');\n private static undefinedValueNotification: Notification<any> = new Notification('N', undefined);\n\n /**\n * A shortcut to create a Notification instance of the type `next` from a\n * given value.\n * @param {T} value The `next` value.\n * @return {Notification<T>} The \"next\" Notification representing the\n * argument.\n * @nocollapse\n */\n static createNext<T>(value: T): Notification<T> {\n if (typeof value !== 'undefined') {\n return new Notification('N', value);\n }\n return Notification.undefinedValueNotification;\n }\n\n /**\n * A shortcut to create a Notification instance of the type `error` from a\n * given error.\n * @param {any} [err] The `error` error.\n * @return {Notification<T>} The \"error\" Notification representing the\n * argument.\n * @nocollapse\n */\n static createError<T>(err?: any): Notification<T> {\n return new Notification('E', undefined, err);\n }\n\n /**\n * A shortcut to create a Notification instance of the type `complete`.\n * @return {Notification<any>} The valueless \"complete\" Notification.\n * @nocollapse\n */\n static createComplete(): Notification<any> {\n return Notification.completeNotification;\n }\n}\n","import { async } from '../scheduler/async';\nimport { isDate } from '../util/isDate';\nimport { Operator } from '../Operator';\nimport { Subscriber } from '../Subscriber';\nimport { Subscription } from '../Subscription';\nimport { Notification } from '../Notification';\nimport { Observable } from '../Observable';\nimport { MonoTypeOperatorFunction, PartialObserver, SchedulerAction, SchedulerLike, TeardownLogic } from '../types';\n\n/**\n * Delays the emission of items from the source Observable by a given timeout or\n * until a given Date.\n *\n * <span class=\"informal\">Time shifts each item by some specified amount of\n * milliseconds.</span>\n *\n * ![](delay.png)\n *\n * If the delay argument is a Number, this operator time shifts the source\n * Observable by that amount of time expressed in milliseconds. The relative\n * time intervals between the values are preserved.\n *\n * If the delay argument is a Date, this operator time shifts the start of the\n * Observable execution until the given date occurs.\n *\n * ## Examples\n * Delay each click by one second\n * ```ts\n * import { fromEvent } from 'rxjs';\n * import { delay } from 'rxjs/operators';\n *\n * const clicks = fromEvent(document, 'click');\n * const delayedClicks = clicks.pipe(delay(1000)); // each click emitted after 1 second\n * delayedClicks.subscribe(x => console.log(x));\n * ```\n *\n * Delay all clicks until a future date happens\n * ```ts\n * import { fromEvent } from 'rxjs';\n * import { delay } from 'rxjs/operators';\n *\n * const clicks = fromEvent(document, 'click');\n * const date = new Date('March 15, 2050 12:00:00'); // in the future\n * const delayedClicks = clicks.pipe(delay(date)); // click emitted only after that date\n * delayedClicks.subscribe(x => console.log(x));\n * ```\n *\n * @see {@link debounceTime}\n * @see {@link delayWhen}\n *\n * @param {number|Date} delay The delay duration in milliseconds (a `number`) or\n * a `Date` until which the emission of the source items is delayed.\n * @param {SchedulerLike} [scheduler=async] The {@link SchedulerLike} to use for\n * managing the timers that handle the time-shift for each item.\n * @return {Observable} An Observable that delays the emissions of the source\n * Observable by the specified timeout or Date.\n * @method delay\n * @owner Observable\n */\nexport function delay<T>(delay: number|Date,\n scheduler: SchedulerLike = async): MonoTypeOperatorFunction<T> {\n const absoluteDelay = isDate(delay);\n const delayFor = absoluteDelay ? (+delay - scheduler.now()) : Math.abs(<number>delay);\n return (source: Observable<T>) => source.lift(new DelayOperator(delayFor, scheduler));\n}\n\nclass DelayOperator<T> implements Operator<T, T> {\n constructor(private delay: number,\n private scheduler: SchedulerLike) {\n }\n\n call(subscriber: Subscriber<T>, source: any): TeardownLogic {\n return source.subscribe(new DelaySubscriber(subscriber, this.delay, this.scheduler));\n }\n}\n\ninterface DelayState<T> {\n source: DelaySubscriber<T>;\n destination: PartialObserver<T>;\n scheduler: SchedulerLike;\n}\n\n/**\n * We need this JSDoc comment for affecting ESDoc.\n * @ignore\n * @extends {Ignored}\n */\nclass DelaySubscriber<T> extends Subscriber<T> {\n private queue: Array<DelayMessage<T>> = [];\n private active: boolean = false;\n private errored: boolean = false;\n\n private static dispatch<T>(this: SchedulerAction<DelayState<T>>, state: DelayState<T>): void {\n const source = state.source;\n const queue = source.queue;\n const scheduler = state.scheduler;\n const destination = state.destination;\n\n while (queue.length > 0 && (queue[0].time - scheduler.now()) <= 0) {\n queue.shift().notification.observe(destination);\n }\n\n if (queue.length > 0) {\n const delay = Math.max(0, queue[0].time - scheduler.now());\n this.schedule(state, delay);\n } else {\n this.unsubscribe();\n source.active = false;\n }\n }\n\n constructor(destination: Subscriber<T>,\n private delay: number,\n private scheduler: SchedulerLike) {\n super(destination);\n }\n\n private _schedule(scheduler: SchedulerLike): void {\n this.active = true;\n const destination = this.destination as Subscription;\n destination.add(scheduler.schedule<DelayState<T>>(DelaySubscriber.dispatch, this.delay, {\n source: this, destination: this.destination, scheduler: scheduler\n }));\n }\n\n private scheduleNotification(notification: Notification<T>): void {\n if (this.errored === true) {\n return;\n }\n\n const scheduler = this.scheduler;\n const message = new DelayMessage(scheduler.now() + this.delay, notification);\n this.queue.push(message);\n\n if (this.active === false) {\n this._schedule(scheduler);\n }\n }\n\n protected _next(value: T) {\n this.scheduleNotification(Notification.createNext(value));\n }\n\n protected _error(err: any) {\n this.errored = true;\n this.queue = [];\n this.destination.error(err);\n this.unsubscribe();\n }\n\n protected _complete() {\n this.scheduleNotification(Notification.createComplete());\n this.unsubscribe();\n }\n}\n\nclass DelayMessage<T> {\n constructor(public readonly time: number,\n public readonly notification: Notification<T>) {\n }\n}\n","import { Operator } from '../Operator';\nimport { Subscriber } from '../Subscriber';\nimport { Observable } from '../Observable';\nimport { MonoTypeOperatorFunction, TeardownLogic } from '../types';\n\n/* tslint:disable:max-line-length */\nexport function distinctUntilChanged<T>(compare?: (x: T, y: T) => boolean): MonoTypeOperatorFunction<T>;\nexport function distinctUntilChanged<T, K>(compare: (x: K, y: K) => boolean, keySelector: (x: T) => K): MonoTypeOperatorFunction<T>;\n/* tslint:enable:max-line-length */\n\n/**\n * Returns an Observable that emits all items emitted by the source Observable that are distinct by comparison from the previous item.\n *\n * If a comparator function is provided, then it will be called for each item to test for whether or not that value should be emitted.\n *\n * If a comparator function is not provided, an equality check is used by default.\n *\n * ## Example\n * A simple example with numbers\n * ```ts\n * import { of } from 'rxjs';\n * import { distinctUntilChanged } from 'rxjs/operators';\n *\n * of(1, 1, 2, 2, 2, 1, 1, 2, 3, 3, 4).pipe(\n * distinctUntilChanged(),\n * )\n * .subscribe(x => console.log(x)); // 1, 2, 1, 2, 3, 4\n * ```\n *\n * An example using a compare function\n * ```typescript\n * import { of } from 'rxjs';\n * import { distinctUntilChanged } from 'rxjs/operators';\n *\n * interface Person {\n * age: number,\n * name: string\n * }\n *\n * of<Person>(\n * { age: 4, name: 'Foo'},\n * { age: 7, name: 'Bar'},\n * { age: 5, name: 'Foo'},\n * { age: 6, name: 'Foo'},\n * ).pipe(\n * distinctUntilChanged((p: Person, q: Person) => p.name === q.name),\n * )\n * .subscribe(x => console.log(x));\n *\n * // displays:\n * // { age: 4, name: 'Foo' }\n * // { age: 7, name: 'Bar' }\n * // { age: 5, name: 'Foo' }\n * ```\n *\n * @see {@link distinct}\n * @see {@link distinctUntilKeyChanged}\n *\n * @param {function} [compare] Optional comparison function called to test if an item is distinct from the previous item in the source.\n * @return {Observable} An Observable that emits items from the source Observable with distinct values.\n * @method distinctUntilChanged\n * @owner Observable\n */\nexport function distinctUntilChanged<T, K>(compare?: (x: K, y: K) => boolean, keySelector?: (x: T) => K): MonoTypeOperatorFunction<T> {\n return (source: Observable<T>) => source.lift(new DistinctUntilChangedOperator<T, K>(compare, keySelector));\n}\n\nclass DistinctUntilChangedOperator<T, K> implements Operator<T, T> {\n constructor(private compare: (x: K, y: K) => boolean,\n private keySelector: (x: T) => K) {\n }\n\n call(subscriber: Subscriber<T>, source: any): TeardownLogic {\n return source.subscribe(new DistinctUntilChangedSubscriber(subscriber, this.compare, this.keySelector));\n }\n}\n\n/**\n * We need this JSDoc comment for affecting ESDoc.\n * @ignore\n * @extends {Ignored}\n */\nclass DistinctUntilChangedSubscriber<T, K> extends Subscriber<T> {\n private key: K;\n private hasKey: boolean = false;\n\n constructor(destination: Subscriber<T>,\n compare: (x: K, y: K) => boolean,\n private keySelector: (x: T) => K) {\n super(destination);\n if (typeof compare === 'function') {\n this.compare = compare;\n }\n }\n\n private compare(x: any, y: any): boolean {\n return x === y;\n }\n\n protected _next(value: T): void {\n let key: any;\n try {\n const { keySelector } = this;\n key = keySelector ? keySelector(value) : value;\n } catch (err) {\n return this.destination.error(err);\n }\n let result = false;\n if (this.hasKey) {\n try {\n const { compare } = this;\n result = compare(this.key, key);\n } catch (err) {\n return this.destination.error(err);\n }\n } else {\n this.hasKey = true;\n }\n if (!result) {\n this.key = key;\n this.destination.next(value);\n }\n }\n}\n","export interface ArgumentOutOfRangeError extends Error {\n}\n\nexport interface ArgumentOutOfRangeErrorCtor {\n new(): ArgumentOutOfRangeError;\n}\n\nconst ArgumentOutOfRangeErrorImpl = (() => {\n function ArgumentOutOfRangeErrorImpl(this: any) {\n Error.call(this);\n this.message = 'argument out of range';\n this.name = 'ArgumentOutOfRangeError';\n return this;\n }\n\n ArgumentOutOfRangeErrorImpl.prototype = Object.create(Error.prototype);\n\n return ArgumentOutOfRangeErrorImpl;\n})();\n\n/**\n * An error thrown when an element was queried at a certain index of an\n * Observable, but no such index or position exists in that sequence.\n *\n * @see {@link elementAt}\n * @see {@link take}\n * @see {@link takeLast}\n *\n * @class ArgumentOutOfRangeError\n */\nexport const ArgumentOutOfRangeError: ArgumentOutOfRangeErrorCtor = ArgumentOutOfRangeErrorImpl as any;","import { Operator } from '../Operator';\nimport { Subscriber } from '../Subscriber';\nimport { Observable } from '../Observable';\nimport { OperatorFunction, MonoTypeOperatorFunction, TeardownLogic } from '../types';\n\n/* tslint:disable:max-line-length */\nexport function filter<T, S extends T>(predicate: (value: T, index: number) => value is S,\n thisArg?: any): OperatorFunction<T, S>;\nexport function filter<T>(predicate: (value: T, index: number) => boolean,\n thisArg?: any): MonoTypeOperatorFunction<T>;\n/* tslint:enable:max-line-length */\n\n/**\n * Filter items emitted by the source Observable by only emitting those that\n * satisfy a specified predicate.\n *\n * <span class=\"informal\">Like\n * [Array.prototype.filter()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter),\n * it only emits a value from the source if it passes a criterion function.</span>\n *\n * ![](filter.png)\n *\n * Similar to the well-known `Array.prototype.filter` method, this operator\n * takes values from the source Observable, passes them through a `predicate`\n * function and only emits those values that yielded `true`.\n *\n * ## Example\n * Emit only click events whose target was a DIV element\n * ```ts\n * import { fromEvent } from 'rxjs';\n * import { filter } from 'rxjs/operators';\n *\n * const clicks = fromEvent(document, 'click');\n * const clicksOnDivs = clicks.pipe(filter(ev => ev.target.tagName === 'DIV'));\n * clicksOnDivs.subscribe(x => console.log(x));\n * ```\n *\n * @see {@link distinct}\n * @see {@link distinctUntilChanged}\n * @see {@link distinctUntilKeyChanged}\n * @see {@link ignoreElements}\n * @see {@link partition}\n * @see {@link skip}\n *\n * @param {function(value: T, index: number): boolean} predicate A function that\n * evaluates each value emitted by the source Observable. If it returns `true`,\n * the value is emitted, if `false` the value is not passed to the output\n * Observable. The `index` parameter is the number `i` for the i-th source\n * emission that has happened since the subscription, starting from the number\n * `0`.\n * @param {any} [thisArg] An optional argument to determine the value of `this`\n * in the `predicate` function.\n * @return {Observable} An Observable of values from the source that were\n * allowed by the `predicate` function.\n * @method filter\n * @owner Observable\n */\nexport function filter<T>(predicate: (value: T, index: number) => boolean,\n thisArg?: any): MonoTypeOperatorFunction<T> {\n return function filterOperatorFunction(source: Observable<T>): Observable<T> {\n return source.lift(new FilterOperator(predicate, thisArg));\n };\n}\n\nclass FilterOperator<T> implements Operator<T, T> {\n constructor(private predicate: (value: T, index: number) => boolean,\n private thisArg?: any) {\n }\n\n call(subscriber: Subscriber<T>, source: any): TeardownLogic {\n return source.subscribe(new FilterSubscriber(subscriber, this.predicate, this.thisArg));\n }\n}\n\n/**\n * We need this JSDoc comment for affecting ESDoc.\n * @ignore\n * @extends {Ignored}\n */\nclass FilterSubscriber<T> extends Subscriber<T> {\n\n count: number = 0;\n\n constructor(destination: Subscriber<T>,\n private predicate: (value: T, index: number) => boolean,\n private thisArg: any) {\n super(destination);\n }\n\n // the try catch block below is left specifically for\n // optimization and perf reasons. a tryCatcher is not necessary here.\n protected _next(value: T) {\n let result: any;\n try {\n result = this.predicate.call(this.thisArg, value, this.count++);\n } catch (err) {\n this.destination.error(err);\n return;\n }\n if (result) {\n this.destination.next(value);\n }\n }\n}\n","import { Operator } from '../Operator';\nimport { Subscriber } from '../Subscriber';\nimport { ArgumentOutOfRangeError } from '../util/ArgumentOutOfRangeError';\nimport { empty } from '../observable/empty';\nimport { Observable } from '../Observable';\nimport { MonoTypeOperatorFunction, TeardownLogic } from '../types';\n\n/**\n * Emits only the first `count` values emitted by the source Observable.\n *\n * <span class=\"informal\">Takes the first `count` values from the source, then\n * completes.</span>\n *\n * ![](take.png)\n *\n * `take` returns an Observable that emits only the first `count` values emitted\n * by the source Observable. If the source emits fewer than `count` values then\n * all of its values are emitted. After that, it completes, regardless if the\n * source completes.\n *\n * ## Example\n * Take the first 5 seconds of an infinite 1-second interval Observable\n * ```ts\n * import { interval } from 'rxjs';\n * import { take } from 'rxjs/operators';\n *\n * const intervalCount = interval(1000);\n * const takeFive = intervalCount.pipe(take(5));\n * takeFive.subscribe(x => console.log(x));\n *\n * // Logs:\n * // 0\n * // 1\n * // 2\n * // 3\n * // 4\n * ```\n *\n * @see {@link takeLast}\n * @see {@link takeUntil}\n * @see {@link takeWhile}\n * @see {@link skip}\n *\n * @throws {ArgumentOutOfRangeError} When using `take(i)`, it delivers an\n * ArgumentOutOrRangeError to the Observer's `error` callback if `i < 0`.\n *\n * @param {number} count The maximum number of `next` values to emit.\n * @return {Observable<T>} An Observable that emits only the first `count`\n * values emitted by the source Observable, or all of the values from the source\n * if the source emits fewer than `count` values.\n * @method take\n * @owner Observable\n */\nexport function take<T>(count: number): MonoTypeOperatorFunction<T> {\n return (source: Observable<T>) => {\n if (count === 0) {\n return empty();\n } else {\n return source.lift(new TakeOperator(count));\n }\n };\n}\n\nclass TakeOperator<T> implements Operator<T, T> {\n constructor(private total: number) {\n if (this.total < 0) {\n throw new ArgumentOutOfRangeError;\n }\n }\n\n call(subscriber: Subscriber<T>, source: any): TeardownLogic {\n return source.subscribe(new TakeSubscriber(subscriber, this.total));\n }\n}\n\n/**\n * We need this JSDoc comment for affecting ESDoc.\n * @ignore\n * @extends {Ignored}\n */\nclass TakeSubscriber<T> extends Subscriber<T> {\n private count: number = 0;\n\n constructor(destination: Subscriber<T>, private total: number) {\n super(destination);\n }\n\n protected _next(value: T): void {\n const total = this.total;\n const count = ++this.count;\n if (count <= total) {\n this.destination.next(value);\n if (count === total) {\n this.destination.complete();\n this.unsubscribe();\n }\n }\n }\n}\n","import { Operator } from '../Operator';\nimport { Subscriber } from '../Subscriber';\nimport { Observable } from '../Observable';\nimport { MonoTypeOperatorFunction, TeardownLogic } from '../types';\n\n/**\n * Returns an Observable that skips the first `count` items emitted by the source Observable.\n *\n * ![](skip.png)\n *\n * @param {Number} count - The number of times, items emitted by source Observable should be skipped.\n * @return {Observable} An Observable that skips values emitted by the source Observable.\n *\n * @method skip\n * @owner Observable\n */\nexport function skip<T>(count: number): MonoTypeOperatorFunction<T> {\n return (source: Observable<T>) => source.lift(new SkipOperator(count));\n}\n\nclass SkipOperator<T> implements Operator<T, T> {\n constructor(private total: number) {\n }\n\n call(subscriber: Subscriber<T>, source: any): TeardownLogic {\n return source.subscribe(new SkipSubscriber(subscriber, this.total));\n }\n}\n\n/**\n * We need this JSDoc comment for affecting ESDoc.\n * @ignore\n * @extends {Ignored}\n */\nclass SkipSubscriber<T> extends Subscriber<T> {\n count: number = 0;\n\n constructor(destination: Subscriber<T>, private total: number) {\n super(destination);\n }\n\n protected _next(x: T) {\n if (++this.count > this.total) {\n this.destination.next(x);\n }\n }\n}\n","import { Observable } from '../Observable';\nimport { concat } from '../observable/concat';\nimport { isScheduler } from '../util/isScheduler';\nimport { MonoTypeOperatorFunction, OperatorFunction, SchedulerLike } from '../types';\n\n/* tslint:disable:max-line-length */\n/** @deprecated use {@link scheduled} and {@link concatAll} (e.g. `scheduled([[a, b, c], source], scheduler).pipe(concatAll())`) */\nexport function startWith<T>(scheduler: SchedulerLike): MonoTypeOperatorFunction<T>;\n/** @deprecated use {@link scheduled} and {@link concatAll} (e.g. `scheduled([[a, b, c], source], scheduler).pipe(concatAll())`) */\nexport function startWith<T, D>(v1: D, scheduler: SchedulerLike): OperatorFunction<T, T | D>;\n/** @deprecated use {@link scheduled} and {@link concatAll} (e.g. `scheduled([[a, b, c], source], scheduler).pipe(concatAll())`) */\nexport function startWith<T, D, E>(v1: D, v2: E, scheduler: SchedulerLike): OperatorFunction<T, T | D | E>;\n/** @deprecated use {@link scheduled} and {@link concatAll} (e.g. `scheduled([[a, b, c], source], scheduler).pipe(concatAll())`) */\nexport function startWith<T, D, E, F>(v1: D, v2: E, v3: F, scheduler: SchedulerLike): OperatorFunction<T, T | D | E | F>;\n/** @deprecated use {@link scheduled} and {@link concatAll} (e.g. `scheduled([[a, b, c], source], scheduler).pipe(concatAll())`) */\nexport function startWith<T, D, E, F, G>(v1: D, v2: E, v3: F, v4: G, scheduler: SchedulerLike): OperatorFunction<T, T | D | E | F | G>;\n/** @deprecated use {@link scheduled} and {@link concatAll} (e.g. `scheduled([[a, b, c], source], scheduler).pipe(concatAll())`) */\nexport function startWith<T, D, E, F, G, H>(v1: D, v2: E, v3: F, v4: G, v5: H, scheduler: SchedulerLike): OperatorFunction<T, T | D | E | F | G | H>;\n/** @deprecated use {@link scheduled} and {@link concatAll} (e.g. `scheduled([[a, b, c], source], scheduler).pipe(concatAll())`) */\nexport function startWith<T, D, E, F, G, H, I>(v1: D, v2: E, v3: F, v4: G, v5: H, v6: I, scheduler: SchedulerLike): OperatorFunction<T, T | D | E | F | G | H | I>;\n\nexport function startWith<T, D>(v1: D): OperatorFunction<T, T | D>;\nexport function startWith<T, D, E>(v1: D, v2: E): OperatorFunction<T, T | D | E>;\nexport function startWith<T, D, E, F>(v1: D, v2: E, v3: F): OperatorFunction<T, T | D | E | F>;\nexport function startWith<T, D, E, F, G>(v1: D, v2: E, v3: F, v4: G): OperatorFunction<T, T | D | E | F | G>;\nexport function startWith<T, D, E, F, G, H>(v1: D, v2: E, v3: F, v4: G, v5: H): OperatorFunction<T, T | D | E | F | G | H>;\nexport function startWith<T, D, E, F, G, H, I>(v1: D, v2: E, v3: F, v4: G, v5: H, v6: I): OperatorFunction<T, T | D | E | F | G | H | I>;\nexport function startWith<T, D = T>(...array: D[]): OperatorFunction<T, T | D>;\n/** @deprecated use {@link scheduled} and {@link concatAll} (e.g. `scheduled([[a, b, c], source], scheduler).pipe(concatAll())`) */\nexport function startWith<T, D = T>(...array: Array<D | SchedulerLike>): OperatorFunction<T, T | D>;\n/* tslint:enable:max-line-length */\n\n/**\n * Returns an Observable that emits the items you specify as arguments before it begins to emit\n * items emitted by the source Observable.\n *\n * <span class=\"informal\">First emits its arguments in order, and then any\n * emissions from the source.</span>\n *\n * ![](startWith.png)\n *\n * ## Examples\n *\n * Start the chain of emissions with `\"first\"`, `\"second\"`\n *\n * ```ts\n * import { of } from 'rxjs';\n * import { startWith } from 'rxjs/operators';\n *\n * of(\"from source\")\n * .pipe(startWith(\"first\", \"second\"))\n * .subscribe(x => console.log(x));\n *\n * // results:\n * // \"first\"\n * // \"second\"\n * // \"from source\"\n * ```\n *\n * @param {...T} values - Items you want the modified Observable to emit first.\n * @param {SchedulerLike} [scheduler] - A {@link SchedulerLike} to use for scheduling\n * the emissions of the `next` notifications.\n * @return {Observable} An Observable that emits the items in the specified Iterable and then emits the items\n * emitted by the source Observable.\n * @method startWith\n * @owner Observable\n */\nexport function startWith<T, D>(...array: Array<T | SchedulerLike>): OperatorFunction<T, T | D> {\n const scheduler = array[array.length - 1] as SchedulerLike;\n if (isScheduler(scheduler)) {\n // deprecated path\n array.pop();\n return (source: Observable<T>) => concat(array as T[], source, scheduler);\n } else {\n return (source: Observable<T>) => concat(array as T[], source);\n }\n}\n","import { Operator } from '../Operator';\nimport { Observable } from '../Observable';\nimport { Subscriber } from '../Subscriber';\nimport { Subscription } from '../Subscription';\nimport { ObservableInput, OperatorFunction, ObservedValueOf } from '../types';\nimport { map } from './map';\nimport { from } from '../observable/from';\nimport { SimpleOuterSubscriber, SimpleInnerSubscriber, innerSubscribe } from '../innerSubscribe';\n\n/* tslint:disable:max-line-length */\nexport function switchMap<T, O extends ObservableInput<any>>(project: (value: T, index: number) => O): OperatorFunction<T, ObservedValueOf<O>>;\n/** @deprecated resultSelector is no longer supported, use inner map instead */\nexport function switchMap<T, O extends ObservableInput<any>>(project: (value: T, index: number) => O, resultSelector: undefined): OperatorFunction<T, ObservedValueOf<O>>;\n/** @deprecated resultSelector is no longer supported, use inner map instead */\nexport function switchMap<T, R, O extends ObservableInput<any>>(project: (value: T, index: number) => O, resultSelector: (outerValue: T, innerValue: ObservedValueOf<O>, outerIndex: number, innerIndex: number) => R): OperatorFunction<T, R>;\n/* tslint:enable:max-line-length */\n\n/**\n * Projects each source value to an Observable which is merged in the output\n * Observable, emitting values only from the most recently projected Observable.\n *\n * <span class=\"informal\">Maps each value to an Observable, then flattens all of\n * these inner Observables.</span>\n *\n * ![](switchMap.png)\n *\n * Returns an Observable that emits items based on applying a function that you\n * supply to each item emitted by the source Observable, where that function\n * returns an (so-called \"inner\") Observable. Each time it observes one of these\n * inner Observables, the output Observable begins emitting the items emitted by\n * that inner Observable. When a new inner Observable is emitted, `switchMap`\n * stops emitting items from the earlier-emitted inner Observable and begins\n * emitting items from the new one. It continues to behave like this for\n * subsequent inner Observables.\n *\n * ## Example\n * Generate new Observable according to source Observable values\n * ```typescript\n * import { of } from 'rxjs';\n * import { switchMap } from 'rxjs/operators';\n *\n * const switched = of(1, 2, 3).pipe(switchMap((x: number) => of(x, x ** 2, x ** 3)));\n * switched.subscribe(x => console.log(x));\n * // outputs\n * // 1\n * // 1\n * // 1\n * // 2\n * // 4\n * // 8\n * // ... and so on\n * ```\n *\n * Rerun an interval Observable on every click event\n * ```ts\n * import { fromEvent, interval } from 'rxjs';\n * import { switchMap } from 'rxjs/operators';\n *\n * const clicks = fromEvent(document, 'click');\n * const result = clicks.pipe(switchMap((ev) => interval(1000)));\n * result.subscribe(x => console.log(x));\n * ```\n *\n * @see {@link concatMap}\n * @see {@link exhaustMap}\n * @see {@link mergeMap}\n * @see {@link switchAll}\n * @see {@link switchMapTo}\n *\n * @param {function(value: T, ?index: number): ObservableInput} project A function\n * that, when applied to an item emitted by the source Observable, returns an\n * Observable.\n * @return {Observable} An Observable that emits the result of applying the\n * projection function (and the optional deprecated `resultSelector`) to each item\n * emitted by the source Observable and taking only the values from the most recently\n * projected inner Observable.\n * @method switchMap\n * @owner Observable\n */\nexport function switchMap<T, R, O extends ObservableInput<any>>(\n project: (value: T, index: number) => O,\n resultSelector?: (outerValue: T, innerValue: ObservedValueOf<O>, outerIndex: number, innerIndex: number) => R,\n): OperatorFunction<T, ObservedValueOf<O>|R> {\n if (typeof resultSelector === 'function') {\n return (source: Observable<T>) => source.pipe(\n switchMap((a, i) => from(project(a, i)).pipe(\n map((b, ii) => resultSelector(a, b, i, ii))\n ))\n );\n }\n return (source: Observable<T>) => source.lift(new SwitchMapOperator(project));\n}\n\nclass SwitchMapOperator<T, R> implements Operator<T, R> {\n constructor(private project: (value: T, index: number) => ObservableInput<R>) {\n }\n\n call(subscriber: Subscriber<R>, source: any): any {\n return source.subscribe(new SwitchMapSubscriber(subscriber, this.project));\n }\n}\n\n/**\n * We need this JSDoc comment for affecting ESDoc.\n * @ignore\n * @extends {Ignored}\n */\nclass SwitchMapSubscriber<T, R> extends SimpleOuterSubscriber<T, R> {\n private index = 0;\n private innerSubscription?: Subscription;\n\n constructor(destination: Subscriber<R>,\n private project: (value: T, index: number) => ObservableInput<R>) {\n super(destination);\n }\n\n protected _next(value: T) {\n let result: ObservableInput<R>;\n const index = this.index++;\n try {\n result = this.project(value, index);\n } catch (error) {\n this.destination.error!(error);\n return;\n }\n this._innerSub(result);\n }\n\n private _innerSub(result: ObservableInput<R>) {\n const innerSubscription = this.innerSubscription;\n if (innerSubscription) {\n innerSubscription.unsubscribe();\n }\n const innerSubscriber = new SimpleInnerSubscriber(this);\n const destination = this.destination as Subscription;\n destination.add(innerSubscriber);\n this.innerSubscription = innerSubscribe(result, innerSubscriber);\n // The returned subscription will usually be the subscriber that was\n // passed. However, interop subscribers will be wrapped and for\n // unsubscriptions to chain correctly, the wrapper needs to be added, too.\n if (this.innerSubscription !== innerSubscriber) {\n destination.add(this.innerSubscription);\n }\n }\n\n protected _complete(): void {\n const {innerSubscription} = this;\n if (!innerSubscription || innerSubscription.closed) {\n super._complete();\n }\n this.unsubscribe();\n }\n\n protected _unsubscribe() {\n this.innerSubscription = undefined;\n }\n\n notifyComplete(): void {\n this.innerSubscription = undefined;\n if (this.isStopped) {\n super._complete();\n }\n }\n\n notifyNext(innerValue: R): void {\n this.destination.next!(innerValue);\n }\n}\n","/* tslint:disable:no-empty */\nexport function noop() { }\n","import { Operator } from '../Operator';\nimport { Subscriber } from '../Subscriber';\nimport { Observable } from '../Observable';\nimport { MonoTypeOperatorFunction, PartialObserver, TeardownLogic } from '../types';\nimport { noop } from '../util/noop';\nimport { isFunction } from '../util/isFunction';\n\n/* tslint:disable:max-line-length */\n/** @deprecated Use an observer instead of a complete callback */\nexport function tap<T>(next: null | undefined, error: null | undefined, complete: () => void): MonoTypeOperatorFunction<T>;\n/** @deprecated Use an observer instead of an error callback */\nexport function tap<T>(next: null | undefined, error: (error: any) => void, complete?: () => void): MonoTypeOperatorFunction<T>;\n/** @deprecated Use an observer instead of a complete callback */\nexport function tap<T>(next: (value: T) => void, error: null | undefined, complete: () => void): MonoTypeOperatorFunction<T>;\nexport function tap<T>(next?: (x: T) => void, error?: (e: any) => void, complete?: () => void): MonoTypeOperatorFunction<T>;\nexport function tap<T>(observer: PartialObserver<T>): MonoTypeOperatorFunction<T>;\n/* tslint:enable:max-line-length */\n\n/**\n * Perform a side effect for every emission on the source Observable, but return\n * an Observable that is identical to the source.\n *\n * <span class=\"informal\">Intercepts each emission on the source and runs a\n * function, but returns an output which is identical to the source as long as errors don't occur.</span>\n *\n * ![](do.png)\n *\n * Returns a mirrored Observable of the source Observable, but modified so that\n * the provided Observer is called to perform a side effect for every value,\n * error, and completion emitted by the source. Any errors that are thrown in\n * the aforementioned Observer or handlers are safely sent down the error path\n * of the output Observable.\n *\n * This operator is useful for debugging your Observables for the correct values\n * or performing other side effects.\n *\n * Note: this is different to a `subscribe` on the Observable. If the Observable\n * returned by `tap` is not subscribed, the side effects specified by the\n * Observer will never happen. `tap` therefore simply spies on existing\n * execution, it does not trigger an execution to happen like `subscribe` does.\n *\n * ## Example\n * Map every click to the clientX position of that click, while also logging the click event\n * ```ts\n * import { fromEvent } from 'rxjs';\n * import { tap, map } from 'rxjs/operators';\n *\n * const clicks = fromEvent(document, 'click');\n * const positions = clicks.pipe(\n * tap(ev => console.log(ev)),\n * map(ev => ev.clientX),\n * );\n * positions.subscribe(x => console.log(x));\n * ```\n *\n * @see {@link map}\n * @see {@link Observable#subscribe}\n *\n * @param {Observer|function} [nextOrObserver] A normal Observer object or a\n * callback for `next`.\n * @param {function} [error] Callback for errors in the source.\n * @param {function} [complete] Callback for the completion of the source.\n * @return {Observable} An Observable identical to the source, but runs the\n * specified Observer or callback(s) for each item.\n * @name tap\n */\nexport function tap<T>(nextOrObserver?: PartialObserver<T> | ((x: T) => void),\n error?: (e: any) => void,\n complete?: () => void): MonoTypeOperatorFunction<T> {\n return function tapOperatorFunction(source: Observable<T>): Observable<T> {\n return source.lift(new DoOperator(nextOrObserver, error, complete));\n };\n}\n\nclass DoOperator<T> implements Operator<T, T> {\n constructor(private nextOrObserver?: PartialObserver<T> | ((x: T) => void),\n private error?: (e: any) => void,\n private complete?: () => void) {\n }\n call(subscriber: Subscriber<T>, source: any): TeardownLogic {\n return source.subscribe(new TapSubscriber(subscriber, this.nextOrObserver, this.error, this.complete));\n }\n}\n\n/**\n * We need this JSDoc comment for affecting ESDoc.\n * @ignore\n * @extends {Ignored}\n */\n\nclass TapSubscriber<T> extends Subscriber<T> {\n private _context: any;\n\n private _tapNext: ((value: T) => void) = noop;\n\n private _tapError: ((err: any) => void) = noop;\n\n private _tapComplete: (() => void) = noop;\n\n constructor(destination: Subscriber<T>,\n observerOrNext?: PartialObserver<T> | ((value: T) => void),\n error?: (e?: any) => void,\n complete?: () => void) {\n super(destination);\n this._tapError = error || noop;\n this._tapComplete = complete || noop;\n if (isFunction(observerOrNext)) {\n this._context = this;\n this._tapNext = observerOrNext;\n } else if (observerOrNext) {\n this._context = observerOrNext;\n this._tapNext = observerOrNext.next || noop;\n this._tapError = observerOrNext.error || noop;\n this._tapComplete = observerOrNext.complete || noop;\n }\n }\n\n _next(value: T) {\n try {\n this._tapNext.call(this._context, value);\n } catch (err) {\n this.destination.error(err);\n return;\n }\n this.destination.next(value);\n }\n\n _error(err: any) {\n try {\n this._tapError.call(this._context, err);\n } catch (err) {\n this.destination.error(err);\n return;\n }\n this.destination.error(err);\n }\n\n _complete() {\n try {\n this._tapComplete.call(this._context, );\n } catch (err) {\n this.destination.error(err);\n return;\n }\n return this.destination.complete();\n }\n}\n","export interface TimeoutError extends Error {\n}\n\nexport interface TimeoutErrorCtor {\n new(): TimeoutError;\n}\n\nconst TimeoutErrorImpl = (() => {\n function TimeoutErrorImpl(this: any) {\n Error.call(this);\n this.message = 'Timeout has occurred';\n this.name = 'TimeoutError';\n return this;\n }\n\n TimeoutErrorImpl.prototype = Object.create(Error.prototype);\n\n return TimeoutErrorImpl;\n})();\n\n/**\n * An error thrown when duetime elapses.\n *\n * @see {@link operators/timeout}\n *\n * @class TimeoutError\n */\nexport const TimeoutError: TimeoutErrorCtor = TimeoutErrorImpl as any;\n","import { Operator } from '../Operator';\nimport { Subscriber } from '../Subscriber';\nimport { async } from '../scheduler/async';\nimport { Observable } from '../Observable';\nimport { isDate } from '../util/isDate';\nimport { ObservableInput, OperatorFunction, SchedulerAction, SchedulerLike, TeardownLogic } from '../types';\nimport { SimpleOuterSubscriber, innerSubscribe, SimpleInnerSubscriber } from '../innerSubscribe';\n\n/* tslint:disable:max-line-length */\nexport function timeoutWith<T, R>(due: number | Date, withObservable: ObservableInput<R>, scheduler?: SchedulerLike): OperatorFunction<T, T | R>;\n/* tslint:enable:max-line-length */\n\n/**\n *\n * Errors if Observable does not emit a value in given time span, in case of which\n * subscribes to the second Observable.\n *\n * <span class=\"informal\">It's a version of `timeout` operator that let's you specify fallback Observable.</span>\n *\n * ![](timeoutWith.png)\n *\n * `timeoutWith` is a variation of `timeout` operator. It behaves exactly the same,\n * still accepting as a first argument either a number or a Date, which control - respectively -\n * when values of source Observable should be emitted or when it should complete.\n *\n * The only difference is that it accepts a second, required parameter. This parameter\n * should be an Observable which will be subscribed when source Observable fails any timeout check.\n * So whenever regular `timeout` would emit an error, `timeoutWith` will instead start re-emitting\n * values from second Observable. Note that this fallback Observable is not checked for timeouts\n * itself, so it can emit values and complete at arbitrary points in time. From the moment of a second\n * subscription, Observable returned from `timeoutWith` simply mirrors fallback stream. When that\n * stream completes, it completes as well.\n *\n * Scheduler, which in case of `timeout` is provided as as second argument, can be still provided\n * here - as a third, optional parameter. It still is used to schedule timeout checks and -\n * as a consequence - when second Observable will be subscribed, since subscription happens\n * immediately after failing check.\n *\n * ## Example\n * Add fallback observable\n * ```ts\n * import { interval } from 'rxjs';\n * import { timeoutWith } from 'rxjs/operators';\n *\n * const seconds = interval(1000);\n * const minutes = interval(60 * 1000);\n *\n * seconds.pipe(timeoutWith(900, minutes))\n * .subscribe(\n * value => console.log(value), // After 900ms, will start emitting `minutes`,\n * // since first value of `seconds` will not arrive fast enough.\n * err => console.log(err), // Would be called after 900ms in case of `timeout`,\n * // but here will never be called.\n * );\n * ```\n *\n * @param {number|Date} due Number specifying period within which Observable must emit values\n * or Date specifying before when Observable should complete\n * @param {Observable<T>} withObservable Observable which will be subscribed if source fails timeout check.\n * @param {SchedulerLike} [scheduler] Scheduler controlling when timeout checks occur.\n * @return {Observable<T>} Observable that mirrors behaviour of source or, when timeout check fails, of an Observable\n * passed as a second parameter.\n * @method timeoutWith\n * @owner Observable\n */\nexport function timeoutWith<T, R>(due: number | Date,\n withObservable: ObservableInput<R>,\n scheduler: SchedulerLike = async): OperatorFunction<T, T | R> {\n return (source: Observable<T>) => {\n let absoluteTimeout = isDate(due);\n let waitFor = absoluteTimeout ? (+due - scheduler.now()) : Math.abs(<number>due);\n return source.lift(new TimeoutWithOperator(waitFor, absoluteTimeout, withObservable, scheduler));\n };\n}\n\nclass TimeoutWithOperator<T> implements Operator<T, T> {\n constructor(private waitFor: number,\n private absoluteTimeout: boolean,\n private withObservable: ObservableInput<any>,\n private scheduler: SchedulerLike) {\n }\n\n call(subscriber: Subscriber<T>, source: any): TeardownLogic {\n return source.subscribe(new TimeoutWithSubscriber(\n subscriber, this.absoluteTimeout, this.waitFor, this.withObservable, this.scheduler\n ));\n }\n}\n\n/**\n * We need this JSDoc comment for affecting ESDoc.\n * @ignore\n * @extends {Ignored}\n */\nclass TimeoutWithSubscriber<T, R> extends SimpleOuterSubscriber<T, R> {\n\n private action?: SchedulerAction<TimeoutWithSubscriber<T, R>>;\n\n constructor(destination: Subscriber<T>,\n private absoluteTimeout: boolean,\n private waitFor: number,\n private withObservable: ObservableInput<any>,\n private scheduler: SchedulerLike) {\n super(destination);\n this.scheduleTimeout();\n }\n\n private static dispatchTimeout<T, R>(subscriber: TimeoutWithSubscriber<T, R>): void {\n const { withObservable } = subscriber;\n subscriber._unsubscribeAndRecycle();\n subscriber.add(innerSubscribe(withObservable, new SimpleInnerSubscriber(subscriber)));\n }\n\n private scheduleTimeout(): void {\n const { action } = this;\n if (action) {\n // Recycle the action if we've already scheduled one. All the production\n // Scheduler Actions mutate their state/delay time and return themeselves.\n // VirtualActions are immutable, so they create and return a clone. In this\n // case, we need to set the action reference to the most recent VirtualAction,\n // to ensure that's the one we clone from next time.\n this.action = (<SchedulerAction<TimeoutWithSubscriber<T, R>>> action.schedule(this, this.waitFor));\n } else {\n this.add(this.action = (<SchedulerAction<TimeoutWithSubscriber<T, R>>> this.scheduler.schedule<TimeoutWithSubscriber<T, R>>(\n TimeoutWithSubscriber.dispatchTimeout as any, this.waitFor, this\n )));\n }\n }\n\n protected _next(value: T): void {\n if (!this.absoluteTimeout) {\n this.scheduleTimeout();\n }\n super._next(value);\n }\n\n /** @deprecated This is an internal implementation detail, do not use. */\n _unsubscribe() {\n this.action = undefined;\n this.scheduler = null!;\n this.withObservable = null!;\n }\n}\n","import { async } from '../scheduler/async';\nimport { isDate } from '../util/isDate';\nimport { Operator } from '../Operator';\nimport { Subscriber } from '../Subscriber';\nimport { Observable } from '../Observable';\nimport { TimeoutError } from '../util/TimeoutError';\nimport { MonoTypeOperatorFunction, SchedulerAction, SchedulerLike, TeardownLogic } from '../types';\nimport { timeoutWith } from './timeoutWith';\nimport { throwError } from '../observable/throwError';\n\n/**\n *\n * Errors if Observable does not emit a value in given time span.\n *\n * <span class=\"informal\">Timeouts on Observable that doesn't emit values fast enough.</span>\n *\n * ![](timeout.png)\n *\n * `timeout` operator accepts as an argument either a number or a Date.\n *\n * If number was provided, it returns an Observable that behaves like a source\n * Observable, unless there is a period of time where there is no value emitted.\n * So if you provide `100` as argument and first value comes after 50ms from\n * the moment of subscription, this value will be simply re-emitted by the resulting\n * Observable. If however after that 100ms passes without a second value being emitted,\n * stream will end with an error and source Observable will be unsubscribed.\n * These checks are performed throughout whole lifecycle of Observable - from the moment\n * it was subscribed to, until it completes or errors itself. Thus every value must be\n * emitted within specified period since previous value.\n *\n * If provided argument was Date, returned Observable behaves differently. It throws\n * if Observable did not complete before provided Date. This means that periods between\n * emission of particular values do not matter in this case. If Observable did not complete\n * before provided Date, source Observable will be unsubscribed. Other than that, resulting\n * stream behaves just as source Observable.\n *\n * `timeout` accepts also a Scheduler as a second parameter. It is used to schedule moment (or moments)\n * when returned Observable will check if source stream emitted value or completed.\n *\n * ## Examples\n * Check if ticks are emitted within certain timespan\n * ```ts\n * import { interval } from 'rxjs';\n * import { timeout } from 'rxjs/operators';\n *\n * const seconds = interval(1000);\n *\n * seconds.pipe(timeout(1100)) // Let's use bigger timespan to be safe,\n * // since `interval` might fire a bit later then scheduled.\n * .subscribe(\n * value => console.log(value), // Will emit numbers just as regular `interval` would.\n * err => console.log(err), // Will never be called.\n * );\n *\n * seconds.pipe(timeout(900))\n * .subscribe(\n * value => console.log(value), // Will never be called.\n * err => console.log(err), // Will emit error before even first value is emitted,\n * // since it did not arrive within 900ms period.\n * );\n * ```\n *\n * Use Date to check if Observable completed\n * ```ts\n * import { interval } from 'rxjs';\n * import { timeout } from 'rxjs/operators';\n *\n * const seconds = interval(1000);\n *\n * seconds.pipe(\n * timeout(new Date(\"December 17, 2020 03:24:00\")),\n * )\n * .subscribe(\n * value => console.log(value), // Will emit values as regular `interval` would\n * // until December 17, 2020 at 03:24:00.\n * err => console.log(err) // On December 17, 2020 at 03:24:00 it will emit an error,\n * // since Observable did not complete by then.\n * );\n * ```\n * @see {@link timeoutWith}\n *\n * @param {number|Date} due Number specifying period within which Observable must emit values\n * or Date specifying before when Observable should complete\n * @param {SchedulerLike} [scheduler] Scheduler controlling when timeout checks occur.\n * @return {Observable<T>} Observable that mirrors behaviour of source, unless timeout checks fail.\n * @method timeout\n * @owner Observable\n */\nexport function timeout<T>(due: number | Date,\n scheduler: SchedulerLike = async): MonoTypeOperatorFunction<T> {\n return timeoutWith(due, throwError(new TimeoutError()), scheduler);\n}\n","const { toString: toStr } = {};\nfunction getToStringTag(val) {\n return toStr.call(val).slice(8, -1);\n}\nexport function escapeDollarProps(value) {\n const keys = Object.keys(value);\n let dollarKeys = null;\n for (let i = 0, l = keys.length; i < l; ++i) {\n if (keys[i][0] === \"$\") {\n dollarKeys = dollarKeys || [];\n dollarKeys.push(keys[i]);\n }\n }\n if (!dollarKeys)\n return value;\n const clone = { ...value };\n for (const k of dollarKeys) {\n delete clone[k];\n clone[\"$\" + k] = value[k];\n }\n return clone;\n}\nconst ObjectDef = {\n replace: escapeDollarProps,\n};\nexport function TypesonSimplified(...typeDefsInputs) {\n const typeDefs = typeDefsInputs.reduce((p, c) => ({ ...p, ...c }), typeDefsInputs.reduce((p, c) => ({ ...c, ...p }), {}));\n const protoMap = new WeakMap();\n return {\n stringify(value, alternateChannel, space) {\n const json = JSON.stringify(value, function (key) {\n const realVal = this[key];\n const typeDef = getTypeDef(realVal);\n return typeDef\n ? typeDef.replace(realVal, alternateChannel, typeDefs)\n : realVal;\n }, space);\n return json;\n },\n parse(tson, alternateChannel) {\n let parent = null;\n let unescapeParentKeys = [];\n return JSON.parse(tson, function (key, value) {\n //\n // Parent Part\n //\n const type = value === null || value === void 0 ? void 0 : value.$t;\n if (type) {\n const typeDef = typeDefs[type];\n value = typeDef\n ? typeDef.revive(value, alternateChannel, typeDefs)\n : value;\n }\n if (value === parent) {\n // Do what the kid told us to\n if (unescapeParentKeys.length > 0) {\n // Unescape dollar props\n value = { ...value };\n for (const k of unescapeParentKeys) {\n value[k.substr(1)] = value[k];\n delete value[k];\n }\n }\n unescapeParentKeys = [];\n return value;\n }\n //\n // Child part\n //\n if (key[0] === \"$\" && key !== \"$t\") {\n parent = this;\n unescapeParentKeys.push(key);\n }\n return value;\n });\n },\n };\n function getTypeDef(realVal) {\n const type = typeof realVal;\n switch (typeof realVal) {\n case \"object\":\n case \"function\": {\n // \"object\", \"function\", null\n if (realVal === null)\n return null;\n const proto = Object.getPrototypeOf(realVal);\n if (!proto)\n return ObjectDef;\n let typeDef = protoMap.get(proto);\n if (typeDef !== undefined)\n return typeDef; // Null counts to! So the caching of Array.prototype also counts.\n const toStringTag = getToStringTag(realVal);\n const entry = Object.entries(typeDefs).find(([typeName, typeDef]) => { var _a, _b; return (_b = (_a = typeDef === null || typeDef === void 0 ? void 0 : typeDef.test) === null || _a === void 0 ? void 0 : _a.call(typeDef, realVal, toStringTag)) !== null && _b !== void 0 ? _b : typeName === toStringTag; });\n typeDef = entry === null || entry === void 0 ? void 0 : entry[1];\n if (!typeDef) {\n typeDef = Array.isArray(realVal)\n ? null\n : typeof realVal === \"function\"\n ? typeDefs.function || null\n : ObjectDef;\n }\n protoMap.set(proto, typeDef);\n return typeDef;\n }\n default:\n return typeDefs[type];\n }\n }\n}\n","export const BisonBinaryTypes = {\n Blob: {\n test: (blob, toStringTag) => toStringTag === \"Blob\",\n replace: (blob, altChannel) => {\n const i = altChannel.length;\n altChannel.push(blob);\n return {\n $t: \"Blob\",\n mimeType: blob.type,\n i,\n };\n },\n revive: ({ i, mimeType }, altChannel) => new Blob([altChannel[i]], { type: mimeType }),\n },\n};\n","export default {\n number: {\n replace: (num) => {\n switch (true) {\n case isNaN(num):\n return { $t: \"number\", v: \"NaN\" };\n case num === Infinity:\n return { $t: \"number\", v: \"Infinity\" };\n case num === -Infinity:\n return { $t: \"number\", v: \"-Infinity\" };\n default:\n return num;\n }\n },\n revive: ({ v }) => Number(v),\n },\n};\n","const bigIntDef = {\n bigint: {\n replace: (realVal) => {\n return { $t: \"bigint\", v: \"\" + realVal };\n },\n revive: (obj) => BigInt(obj.v),\n },\n};\nexport default bigIntDef;\n","export default {\n Date: {\n replace: (date) => ({\n $t: \"Date\",\n v: isNaN(date.getTime()) ? \"NaN\" : date.toISOString(),\n }),\n revive: ({ v }) => new Date(v === \"NaN\" ? NaN : Date.parse(v)),\n },\n};\n","export default {\n Set: {\n replace: (set) => ({\n $t: \"Set\",\n v: Array.from(set.entries()),\n }),\n revive: ({ v }) => new Set(v),\n },\n};\n","export default {\n Map: {\n replace: (map) => ({\n $t: \"Map\",\n v: Array.from(map.entries()),\n }),\n revive: ({ v }) => new Map(v),\n },\n};\n","export const _global = typeof globalThis !== \"undefined\"\n ? globalThis\n : typeof self !== \"undefined\"\n ? self\n : typeof global === \"undefined\"\n ? global\n : this;\n","import { _global } from \"../../common/_global.js\";\nexport default [\n \"Int8Array\",\n \"Uint8Array\",\n \"Uint8ClampedArray\",\n \"Int16Array\",\n \"Uint16Array\",\n \"Int32Array\",\n \"Uint32Array\",\n \"Float32Array\",\n \"Float64Array\",\n \"DataView\",\n \"BigInt64Array\",\n \"BigUint64Array\",\n].reduce((specs, typeName) => ({\n ...specs,\n [typeName]: {\n // Replace passes the the typed array into $t, buffer so that\n // the ArrayBuffer typedef takes care of further handling of the buffer:\n // {$t:\"Uint8Array\",buffer:{$t:\"ArrayBuffer\",idx:0}}\n // CHANGED ABOVE! Now shortcutting that for more sparse format of the typed arrays\n // to contain the b64 property directly.\n replace: (a, _, typeDefs) => {\n const result = {\n $t: typeName,\n v: typeDefs.ArrayBuffer.replace(a.byteOffset === 0 && a.byteLength === a.buffer.byteLength\n ? a.buffer\n : a.buffer.slice(a.byteOffset, a.byteOffset + a.byteLength), _, typeDefs).v,\n };\n return result;\n },\n revive: ({ v }, _, typeDefs) => {\n const TypedArray = _global[typeName];\n return (TypedArray &&\n new TypedArray(typeDefs.ArrayBuffer.revive({ v }, _, typeDefs)));\n },\n },\n}), {});\n","export const b64decode = typeof Buffer !== \"undefined\"\n ? (base64) => Buffer.from(base64, \"base64\")\n : (base64) => {\n const binary_string = atob(base64);\n const len = binary_string.length;\n const bytes = new Uint8Array(len);\n for (var i = 0; i < len; i++) {\n bytes[i] = binary_string.charCodeAt(i);\n }\n return bytes;\n };\nexport const b64encode = typeof Buffer !== \"undefined\"\n ? (b) => ArrayBuffer.isView(b)\n ? Buffer.from(b.buffer, b.byteOffset, b.byteLength).toString(\"base64\")\n : Buffer.from(b).toString(\"base64\")\n : (b) => btoa(String.fromCharCode.apply(null, b));\n","import { b64decode, b64encode } from \"./base64.js\";\nexport function b64LexEncode(b) {\n return b64ToLex(b64encode(b));\n}\nexport function b64LexDecode(b64Lex) {\n return b64decode(lexToB64(b64Lex));\n}\nexport function b64ToLex(base64) {\n var encoded = \"\";\n for (var i = 0, length = base64.length; i < length; i++) {\n encoded += ENCODE_TABLE[base64[i]];\n }\n return encoded;\n}\nexport function lexToB64(base64lex) {\n // only accept string input\n if (typeof base64lex !== \"string\") {\n throw new Error(\"invalid decoder input: \" + base64lex);\n }\n var base64 = \"\";\n for (var i = 0, length = base64lex.length; i < length; i++) {\n base64 += DECODE_TABLE[base64lex[i]];\n }\n return base64;\n}\nconst DECODE_TABLE = {\n \"-\": \"=\",\n \"0\": \"A\",\n \"1\": \"B\",\n \"2\": \"C\",\n \"3\": \"D\",\n \"4\": \"E\",\n \"5\": \"F\",\n \"6\": \"G\",\n \"7\": \"H\",\n \"8\": \"I\",\n \"9\": \"J\",\n A: \"K\",\n B: \"L\",\n C: \"M\",\n D: \"N\",\n E: \"O\",\n F: \"P\",\n G: \"Q\",\n H: \"R\",\n I: \"S\",\n J: \"T\",\n K: \"U\",\n L: \"V\",\n M: \"W\",\n N: \"X\",\n O: \"Y\",\n P: \"Z\",\n Q: \"a\",\n R: \"b\",\n S: \"c\",\n T: \"d\",\n U: \"e\",\n V: \"f\",\n W: \"g\",\n X: \"h\",\n Y: \"i\",\n Z: \"j\",\n _: \"k\",\n a: \"l\",\n b: \"m\",\n c: \"n\",\n d: \"o\",\n e: \"p\",\n f: \"q\",\n g: \"r\",\n h: \"s\",\n i: \"t\",\n j: \"u\",\n k: \"v\",\n l: \"w\",\n m: \"x\",\n n: \"y\",\n o: \"z\",\n p: \"0\",\n q: \"1\",\n r: \"2\",\n s: \"3\",\n t: \"4\",\n u: \"5\",\n v: \"6\",\n w: \"7\",\n x: \"8\",\n y: \"9\",\n z: \"+\",\n \"|\": \"/\",\n};\nconst ENCODE_TABLE = {};\nfor (const c of Object.keys(DECODE_TABLE)) {\n ENCODE_TABLE[DECODE_TABLE[c]] = c;\n}\n","import { b64LexDecode, b64LexEncode } from \"../../common/b64lex.js\";\nexport default {\n ArrayBuffer: {\n replace: (ab) => ({\n $t: \"ArrayBuffer\",\n v: b64LexEncode(ab),\n }),\n revive: ({ v }) => {\n const ba = b64LexDecode(v);\n return ba.buffer.byteLength === ba.byteLength\n ? ba.buffer\n : ba.buffer.slice(ba.byteOffset, ba.byteOffset + ba.byteLength);\n },\n },\n};\n","export class FakeBlob {\n constructor(buf, type) {\n this.buf = buf;\n this.type = type;\n }\n}\n","export function readBlobSync(b) {\n const req = new XMLHttpRequest();\n req.overrideMimeType(\"text/plain; charset=x-user-defined\");\n req.open(\"GET\", URL.createObjectURL(b), false); // Sync\n req.send();\n if (req.status !== 200 && req.status !== 0) {\n throw new Error(\"Bad Blob access: \" + req.status);\n }\n return req.responseText;\n}\n","export function string2ArrayBuffer(str) {\n const array = new Uint8Array(str.length);\n for (let i = 0; i < str.length; ++i) {\n array[i] = str.charCodeAt(i); // & 0xff;\n }\n return array.buffer;\n}\nexport function arrayBuffer2String(buf) {\n // TODO: Optimize\n return new Uint8Array(buf).reduce((s, byte) => s + String.fromCharCode(byte), \"\");\n}\n","import { b64decode, b64encode } from \"../../common/base64.js\";\nimport { FakeBlob } from \"../FakeBlob.js\";\nimport { readBlobSync } from \"../readBlobSync.js\";\nimport { string2ArrayBuffer } from \"../string2arraybuffer.js\";\nexport default {\n Blob: {\n test: (blob, toStringTag) => toStringTag === \"Blob\" || blob instanceof FakeBlob,\n replace: (blob) => ({\n $t: \"Blob\",\n v: blob instanceof FakeBlob\n ? b64encode(blob.buf)\n : b64encode(string2ArrayBuffer(readBlobSync(blob))),\n type: blob.type,\n }),\n revive: ({ type, v }) => {\n const ab = b64decode(v);\n return typeof Blob !== undefined\n ? new Blob([ab])\n : new FakeBlob(ab.buffer, type);\n },\n },\n};\n","import numberDef from \"../types/number.js\";\nimport bigintDef from \"../types/bigint.js\";\nimport DateDef from \"../types/Date.js\";\nimport SetDef from \"../types/Set.js\";\nimport MapDef from \"../types/Map.js\";\nimport TypedArraysDefs from \"../types/TypedArray.js\";\nimport ArrayBufferDef from \"../types/ArrayBuffer.js\";\nimport BlobDef from \"../types/Blob.js\";\nconst builtin = {\n ...numberDef,\n ...bigintDef,\n ...DateDef,\n ...SetDef,\n ...MapDef,\n ...TypedArraysDefs,\n ...ArrayBufferDef,\n ...BlobDef,\n};\nexport default builtin;\n","import { BisonBinaryTypes } from \"./BisonBinaryTypes.js\";\nimport builtin from \"./presets/builtin.js\";\nimport { TypesonSimplified } from \"./TypesonSimplified.js\";\nexport function Bison(...typeDefsInputs) {\n const tson = TypesonSimplified(builtin, BisonBinaryTypes, ...typeDefsInputs);\n return {\n toBinary(value) {\n const [blob, json] = this.stringify(value);\n const lenBuf = new ArrayBuffer(4);\n new DataView(lenBuf).setUint32(0, blob.size);\n return new Blob([lenBuf, blob, json]);\n },\n stringify(value) {\n const binaries = [];\n const json = tson.stringify(value, binaries);\n const blob = new Blob(binaries.map((b) => {\n const lenBuf = new ArrayBuffer(4);\n new DataView(lenBuf).setUint32(0, \"byteLength\" in b ? b.byteLength : b.size);\n return new Blob([lenBuf, b]);\n }));\n return [blob, json];\n },\n async parse(json, binData) {\n let pos = 0;\n const arrayBuffers = [];\n const buf = await readBlobBinary(binData);\n const view = new DataView(buf);\n while (pos < buf.byteLength) {\n const len = view.getUint32(pos);\n pos += 4;\n const ab = buf.slice(pos, pos + len);\n pos += len;\n arrayBuffers.push(ab);\n }\n return tson.parse(json, arrayBuffers);\n },\n async fromBinary(blob) {\n const len = new DataView(await readBlobBinary(blob.slice(0, 4))).getUint32(0);\n const binData = blob.slice(4, len + 4);\n const json = await readBlob(blob.slice(len + 4));\n return await this.parse(json, binData);\n },\n };\n}\nexport function readBlob(blob) {\n return new Promise((resolve, reject) => {\n const reader = new FileReader();\n reader.onabort = (ev) => reject(new Error(\"file read aborted\"));\n reader.onerror = (ev) => reject(ev.target.error);\n reader.onload = (ev) => resolve(ev.target.result);\n reader.readAsText(blob);\n });\n}\nexport function readBlobBinary(blob) {\n return new Promise((resolve, reject) => {\n const reader = new FileReader();\n reader.onabort = (ev) => reject(new Error(\"file read aborted\"));\n reader.onerror = (ev) => reject(ev.target.error);\n reader.onload = (ev) => resolve(ev.target.result);\n reader.readAsArrayBuffer(blob);\n });\n}\n","/** The undefined type is not part of builtin but can be manually added.\n * The reason for supporting undefined is if the following object should be revived correctly:\n *\n * {foo: undefined}\n *\n * Without including this typedef, the revived object would just be {}.\n * If including this typedef, the revived object would be {foo: undefined}.\n */\nexport default {\n undefined: {\n replace: () => {\n $t: \"undefined\";\n },\n revive: () => undefined,\n },\n};\n","import { TypesonSimplified } from 'dreambase-library/dist/typeson-simplified/TypesonSimplified';\nimport { Bison } from \"dreambase-library/dist/typeson-simplified/Bison\";\nimport undefinedDef from 'dreambase-library/dist/typeson-simplified/types/undefined.js';\nimport tsonBuiltinDefs from 'dreambase-library/dist/typeson-simplified/presets/builtin.js';\nimport { TypeDefSet } from 'dreambase-library/dist/typeson-simplified/TypeDefSet';\n\n// Since server revisions are stored in bigints, we need to handle clients without\n// bigint support to not fail when serverRevision is passed over to client.\n// We need to not fail when reviving it and we need to somehow store the information.\n// Since the revived version will later on be put into indexedDB we have another\n// issue: When reading it back from indexedDB we will get a poco object that we\n// cannot replace correctly when sending it to server. So we will also need\n// to do an explicit workaround in the protocol where a bigint is supported.\n// The workaround should be there regardless if browser supports BigInt or not, because\n// the serverRev might have been stored in IDB before the browser was upgraded to support bigint.\n//\n// if (typeof serverRev.rev !== \"bigint\")\n// if (hasBigIntSupport)\n// serverRev.rev = bigIntDef.bigint.revive(server.rev)\n// else\n// serverRev.rev = new FakeBigInt(server.rev)\nexport const hasBigIntSupport = typeof BigInt(0) === 'bigint';\n\nfunction getValueOfBigInt(x: bigint | FakeBigInt | string) {\n if (typeof x === 'bigint') {\n return x;\n }\n if (hasBigIntSupport) {\n return typeof x === 'string' ? BigInt(x) : BigInt(x.v);\n } else {\n return typeof x === 'string' ? Number(x) : Number(x.v);\n }\n}\n\nexport function compareBigInts(a: bigint | FakeBigInt | string, b:bigint | FakeBigInt | string) {\n const valA = getValueOfBigInt(a);\n const valB = getValueOfBigInt(b);\n return valA < valB ? -1 : valA > valB ? 1 : 0;\n}\nexport class FakeBigInt {\n v: string;\n toString() {\n return this.v;\n }\n constructor(value: string) {\n this.v = value;\n }\n}\n\nconst defs: TypeDefSet = {\n ...undefinedDef,\n ...(hasBigIntSupport\n ? {}\n : {\n bigint: {\n test: (val: any) => val instanceof FakeBigInt,\n replace: (fakeBigInt: any) => {\n return {\n $t: 'bigint',\n ...fakeBigInt\n };\n },\n revive: ({\n v,\n }: {\n $t: 'bigint';\n v: string;\n }) => new FakeBigInt(v) as any as bigint\n }\n })\n};\n\nexport const TSON = TypesonSimplified(tsonBuiltinDefs, defs);\n\nexport const BISON = Bison(defs);\n","import Dexie from 'dexie';\nimport { DexieCloudDB } from '../db/DexieCloudDB';\n\n//const hasSW = 'serviceWorker' in navigator;\nlet hasComplainedAboutSyncEvent = false;\n\nexport async function registerSyncEvent(db: DexieCloudDB, purpose: \"push\" | \"pull\") {\n try {\n // Send sync event to SW:\n const sw = await navigator.serviceWorker.ready;\n if (purpose === \"push\" && sw.sync) {\n await sw.sync.register(`dexie-cloud:${db.name}`);\n }\n if (sw.active) {\n // Use postMessage for pull syncs and for browsers not supporting sync event (Firefox, Safari).\n // Also chromium based browsers with sw.sync as a fallback for sleepy sync events not taking action for a while.\n sw.active.postMessage({\n type: 'dexie-cloud-sync',\n dbName: db.name,\n purpose\n });\n } else {\n console.error(`Dexie Cloud: There's no active service worker. Can this ever happen??`);\n }\n return;\n } catch (e) {\n if (!hasComplainedAboutSyncEvent) {\n console.debug(`Dexie Cloud: Could not register sync event`, e);\n hasComplainedAboutSyncEvent = true;\n }\n }\n}\n\nexport async function registerPeriodicSyncEvent(db: DexieCloudDB) {\n try {\n // Register periodicSync event to SW:\n // @ts-ignore\n const { periodicSync } = await navigator.serviceWorker.ready;\n if (periodicSync) {\n try {\n await periodicSync.register(\n `dexie-cloud:${db.name}`,\n db.cloud.options?.periodicSync\n );\n console.debug(\n `Dexie Cloud: Successfully registered periodicsync event for ${db.name}`\n );\n } catch (e) {\n console.debug(`Dexie Cloud: Failed to register periodic sync. Your PWA must be installed to allow background sync.`, e);\n }\n } else {\n console.debug(`Dexie Cloud: periodicSync not supported.`);\n }\n } catch (e) {\n console.debug(\n `Dexie Cloud: Could not register periodicSync for ${db.name}`,\n e\n );\n }\n}\n","import { DexieCloudDB } from \"../db/DexieCloudDB\";\nimport { registerSyncEvent } from \"./registerSyncEvent\";\n\nexport function triggerSync(db: DexieCloudDB, purpose: \"push\" | \"pull\") {\n if (db.cloud.usingServiceWorker) {\n registerSyncEvent(db, purpose);\n } else {\n db.localSyncEvent.next({purpose});\n }\n}","import { PersistedSyncState } from '../db/entities/PersistedSyncState';\nimport { b64encode } from 'dreambase-library/dist/common/base64';\n\nexport async function computeRealmSetHash({\n realms,\n inviteRealms,\n}: PersistedSyncState) {\n const data = JSON.stringify(\n [\n ...realms.map((realmId) => ({ realmId, accepted: true })),\n ...inviteRealms.map((realmId) => ({ realmId, accepted: false })),\n ].sort((a, b) =>\n a.realmId < b.realmId ? -1 : a.realmId > b.realmId ? 1 : 0\n )\n );\n const byteArray = new TextEncoder().encode(data);\n const digestBytes = await crypto.subtle.digest('SHA-1', byteArray);\n const base64 = b64encode(digestBytes);\n return base64;\n}\n","import { IndexableType, Table } from \"dexie\";\nimport { DexieCloudDB } from \"../db/DexieCloudDB\";\nimport { EntityCommon } from \"../db/entities/EntityCommon\";\n\nexport function getSyncableTables(db: DexieCloudDB): Table<EntityCommon>[] {\n return Object.entries(db.cloud.schema || {})\n .filter(([, { markedForSync }]) => markedForSync)\n .map(([tbl]) => db.table(tbl));\n}\n","\n\nexport function getMutationTable(tableName: string) {\n return `$${tableName}_mutations`;\n}\n","\n\nexport function getTableFromMutationTable(mutationTable: string) {\n const tableName = /^\\$(.*)_mutations$/.exec(mutationTable)?.[1];\n if (!tableName) throw new Error(`Given mutationTable ${mutationTable} is not correct`);\n return tableName;\n}\n","import { Table } from \"dexie\";\nimport { getTableFromMutationTable } from \"../helpers/getTableFromMutationTable\";\nimport { DexieCloudDB } from \"../db/DexieCloudDB\";\nimport { DBOperation, DBOperationsSet } from \"dexie-cloud-common\";\n\nexport async function listClientChanges(\n mutationTables: Table[],\n db: DexieCloudDB,\n { since = {} as {[table: string]: number}, limit = Infinity } = {}): Promise<DBOperationsSet> {\n const allMutsOnTables = await Promise.all(\n mutationTables.map(async (mutationTable) => {\n const tableName = getTableFromMutationTable(mutationTable.name);\n const lastRevision = since[tableName];\n\n let query = lastRevision\n ? mutationTable.where(\"rev\").above(lastRevision)\n : mutationTable;\n\n if (limit < Infinity) query = query.limit(limit);\n \n const muts: DBOperation[] = await query.toArray();\n\n //const objTable = db.table(tableName);\n /*for (const mut of muts) {\n if (mut.type === \"insert\" || mut.type === \"upsert\") {\n mut.values = await objTable.bulkGet(mut.keys);\n }\n }*/\n return {\n table: tableName,\n muts,\n };\n })\n );\n\n // Filter out those tables that doesn't have any mutations:\n return allMutsOnTables.filter(({ muts }) => muts.length > 0);\n}\n","//@ts-check\nconst _fetch = fetch;\nexport { _fetch as fetch };\nexport const randomFillSync = crypto.getRandomValues;\n","import { randomFillSync } from \"universal-imports\";\nexport function assert(b) {\n if (!b)\n throw new Error('Assertion Failed');\n}\nexport function setByKeyPath(obj, keyPath, value) {\n if (!obj || keyPath === undefined)\n return;\n if ('isFrozen' in Object && Object.isFrozen(obj))\n return;\n if (typeof keyPath !== 'string' && 'length' in keyPath) {\n assert(typeof value !== 'string' && 'length' in value);\n for (var i = 0, l = keyPath.length; i < l; ++i) {\n setByKeyPath(obj, keyPath[i], value[i]);\n }\n }\n else {\n var period = keyPath.indexOf('.');\n if (period !== -1) {\n var currentKeyPath = keyPath.substr(0, period);\n var remainingKeyPath = keyPath.substr(period + 1);\n if (remainingKeyPath === '')\n if (value === undefined) {\n if (Array.isArray(obj)) {\n if (!isNaN(parseInt(currentKeyPath)))\n obj.splice(parseInt(currentKeyPath), 1);\n }\n else\n delete obj[currentKeyPath];\n // @ts-ignore: even if currentKeyPath would be numeric string and obj would be array - it works.\n }\n else\n obj[currentKeyPath] = value;\n else {\n //@ts-ignore: even if currentKeyPath would be numeric string and obj would be array - it works.\n var innerObj = obj[currentKeyPath];\n //@ts-ignore: even if currentKeyPath would be numeric string and obj would be array - it works.\n if (!innerObj)\n innerObj = obj[currentKeyPath] = {};\n setByKeyPath(innerObj, remainingKeyPath, value);\n }\n }\n else {\n if (value === undefined) {\n if (Array.isArray(obj) && !isNaN(parseInt(keyPath)))\n // @ts-ignore: even if currentKeyPath would be numeric string and obj would be array - it works.\n obj.splice(keyPath, 1);\n //@ts-ignore: even if currentKeyPath would be numeric string and obj would be array - it works.\n else\n delete obj[keyPath];\n //@ts-ignore: even if currentKeyPath would be numeric string and obj would be array - it works.\n }\n else\n obj[keyPath] = value;\n }\n }\n}\nexport const randomString = typeof self === 'undefined' ? (bytes) => {\n // Node\n const buf = Buffer.alloc(bytes);\n randomFillSync(buf);\n return buf.toString(\"base64\");\n} : (bytes) => {\n // Web\n const buf = new Uint8Array(bytes);\n crypto.getRandomValues(buf);\n return btoa(String.fromCharCode.apply(null, buf));\n};\n","const validIDTypes = {\n Uint8Array,\n};\n/** Verifies that given primary key is valid.\n * The reason we narrow validity for valid keys are twofold:\n * 1: Make sure to only support types that can be used as an object index in DBKeyMutationSet.\n * For example, ArrayBuffer cannot be used (gives \"object ArrayBuffer\") but Uint8Array can be\n * used (gives comma-delimited list of included bytes).\n * 2: Avoid using plain numbers and Dates as keys when they are synced, as they are not globally unique.\n * 3: Since we store the key as a VARCHAR server side in current version, try not promote types that stringifies to become very long server side.\n *\n * @param id\n * @returns\n */\nexport function isValidSyncableID(id) {\n if (typeof id === \"string\")\n return true;\n //if (validIDTypes[toStringTag(id)]) return true;\n //if (Array.isArray(id)) return id.every((part) => isValidSyncableID(part));\n if (Array.isArray(id) && id.some(key => isValidSyncableID(key)) && id.every(isValidSyncableIDPart))\n return true;\n return false;\n}\n/** Verifies that given key part is valid.\n * 1: Make sure that arrays of this types are stringified correclty and works with DBKeyMutationSet.\n * For example, ArrayBuffer cannot be used (gives \"object ArrayBuffer\") but Uint8Array can be\n * used (gives comma-delimited list of included bytes).\n * 2: Since we store the key as a VARCHAR server side in current version, try not promote types that stringifies to become very long server side.\n*/\nfunction isValidSyncableIDPart(part) {\n return typeof part === \"string\" || typeof part === \"number\" || Array.isArray(part) && part.every(isValidSyncableIDPart);\n}\nexport function isValidAtID(id, idPrefix) {\n return !idPrefix || (typeof id === \"string\" && id.startsWith(idPrefix));\n}\n","import { setByKeyPath } from \"../utils.js\";\nexport function applyOperation(target, table, op) {\n const tbl = target[table] || (target[table] = {});\n switch (op.type) {\n case \"insert\":\n // TODO: Don't treat insert and upsert the same?\n case \"upsert\":\n op.keys.forEach((key, idx) => {\n tbl[key] = {\n type: \"ups\",\n val: op.values[idx],\n };\n });\n break;\n case \"update\":\n case \"modify\": {\n op.keys.forEach((key, idx) => {\n const changeSpec = op.type === \"update\"\n ? op.changeSpecs[idx]\n : op.changeSpec;\n const entry = tbl[key];\n if (!entry) {\n tbl[key] = {\n type: \"upd\",\n mod: changeSpec,\n };\n }\n else {\n switch (entry.type) {\n case \"ups\":\n // Adjust the existing upsert with additional updates\n for (const [propPath, value] of Object.entries(changeSpec)) {\n setByKeyPath(entry.val, propPath, value);\n }\n break;\n case \"del\":\n // No action.\n break;\n case \"upd\":\n // Adjust existing update with additional updates\n Object.assign(entry.mod, changeSpec); // May work for deep props as well - new keys is added later, right? Does the prop order persist along TSON and all? But it will not be 100% when combined with some server code (seach for \"address.city\": \"Stockholm\" comment)\n break;\n }\n }\n });\n break;\n }\n case \"delete\":\n op.keys.forEach((key) => {\n tbl[key] = {\n type: \"del\",\n };\n });\n break;\n }\n return target;\n}\n","import { applyOperation } from \"./applyOperation.js\";\nexport function applyOperations(target, ops) {\n for (const { table, muts } of ops) {\n for (const mut of muts) {\n applyOperation(target, table, mut);\n }\n }\n}\n","import { setByKeyPath } from '../utils.js';\nexport function subtractChanges(target, // Server change set\nchangesToSubtract // additional mutations on client during syncWithServer()\n) {\n var _a, _b, _c;\n for (const [table, mutationSet] of Object.entries(changesToSubtract)) {\n for (const [key, mut] of Object.entries(mutationSet)) {\n switch (mut.type) {\n case 'ups':\n {\n const targetMut = (_a = target[table]) === null || _a === void 0 ? void 0 : _a[key];\n if (targetMut) {\n switch (targetMut.type) {\n case 'ups':\n delete target[table][key];\n break;\n case 'del':\n // Leave delete operation.\n // (Don't resurrect objects unintenionally (using tx(get, put) pattern locally))\n break;\n case 'upd':\n delete target[table][key];\n break;\n }\n }\n }\n break;\n case 'del':\n (_b = target[table]) === null || _b === void 0 ? true : delete _b[key];\n break;\n case 'upd': {\n const targetMut = (_c = target[table]) === null || _c === void 0 ? void 0 : _c[key];\n if (targetMut) {\n switch (targetMut.type) {\n case 'ups':\n // Adjust the server upsert with locally updated values.\n for (const [propPath, value] of Object.entries(mut.mod)) {\n setByKeyPath(targetMut.val, propPath, value);\n }\n break;\n case 'del':\n // Leave delete.\n break;\n case 'upd':\n // Remove the local update props from the server update mutation.\n for (const propPath of Object.keys(mut.mod)) {\n delete targetMut.mod[propPath];\n }\n break;\n }\n }\n break;\n }\n }\n }\n }\n}\n","import { randomString } from \"../utils.js\";\n/** Convert a DBKeyMutationSet (which is an internal format capable of looking up changes per ID)\n * ...into a DBOperationsSet (which is more optimal for performing DB operations into DB (bulkAdd() etc))\n *\n * @param inSet\n * @returns DBOperationsSet representing inSet\n */\nexport function toDBOperationSet(inSet) {\n // Fictive transaction:\n const txid = randomString(16);\n // Convert data into a temporary map to collect mutations of same table and type\n const map = {};\n for (const [table, ops] of Object.entries(inSet)) {\n for (const [key, op] of Object.entries(ops)) {\n const mapEntry = map[table] || (map[table] = {});\n const ops = mapEntry[op.type] || (mapEntry[op.type] = []);\n ops.push(Object.assign({ key }, op)); // DBKeyMutation doesn't contain key, so we need to bring it in.\n }\n }\n // Start computing the resulting format:\n const result = [];\n for (const [table, ops] of Object.entries(map)) {\n const resultEntry = {\n table,\n muts: [],\n };\n for (const [optype, muts] of Object.entries(ops)) {\n switch (optype) {\n case \"ups\": {\n const op = {\n type: \"upsert\",\n keys: muts.map(mut => mut.key),\n values: muts.map(mut => mut.val),\n txid\n };\n resultEntry.muts.push(op);\n break;\n }\n case \"upd\": {\n const op = {\n type: \"update\",\n keys: muts.map(mut => mut.key),\n changeSpecs: muts.map(mut => mut.mod),\n txid\n };\n resultEntry.muts.push(op);\n break;\n }\n case \"del\": {\n const op = {\n type: \"delete\",\n keys: muts.map(mut => mut.key),\n txid,\n };\n resultEntry.muts.push(op);\n break;\n }\n }\n }\n result.push(resultEntry);\n }\n return result;\n}\n","export function getDbNameFromDbUrl(dbUrl) {\n const url = new URL(dbUrl);\n return url.pathname === \"/\"\n ? url.hostname.split('.')[0]\n : url.pathname.split('/')[1];\n}\n","import { DexieCloudDB } from \"../db/DexieCloudDB\";\nimport { PersistedSyncState } from \"../db/entities/PersistedSyncState\";\nimport { UserLogin } from \"../db/entities/UserLogin\";\nimport { randomString } from \"../helpers/randomString\";\nimport { EntityCommon } from \"../db/entities/EntityCommon\";\nimport { Table } from \"dexie\";\nimport { DBInsertOperation, DBOperationsSet, DexieCloudSchema, isValidAtID, isValidSyncableID } from \"dexie-cloud-common\";\n\nexport async function listSyncifiedChanges(\n tablesToSyncify: Table<EntityCommon>[],\n currentUser: UserLogin,\n schema: DexieCloudSchema,\n alreadySyncedRealms?: string[]\n): Promise<DBOperationsSet> {\n if (currentUser.isLoggedIn) {\n if (tablesToSyncify.length > 0) {\n const ignoredRealms = new Set(alreadySyncedRealms || []);\n const inserts = await Promise.all(\n tablesToSyncify.map(async (table) => {\n const { extractKey } = table.core.schema.primaryKey;\n if (!extractKey) return { table: table.name, muts: [] }; // Outbound tables are not synced.\n\n const dexieCloudTableSchema = schema[table.name];\n const query = dexieCloudTableSchema?.generatedGlobalId\n ? table.filter(\n (item) => !ignoredRealms.has(item.realmId || \"\") && isValidSyncableID(extractKey(item))\n )\n : table.filter(\n (item) => !ignoredRealms.has(item.realmId || \"\") && isValidAtID(extractKey(item), dexieCloudTableSchema?.idPrefix)\n );\n const unsyncedObjects = await query.toArray();\n if (unsyncedObjects.length > 0) {\n const mut: DBInsertOperation = {\n type: \"insert\",\n values: unsyncedObjects,\n keys: unsyncedObjects.map(extractKey),\n userId: currentUser.userId,\n };\n return {\n table: table.name,\n muts: [mut],\n };\n } else {\n return {\n table: table.name,\n muts: []\n }\n }\n })\n );\n return inserts.filter(op => op.muts.length > 0);\n }\n }\n return [];\n}\n","import { getSyncableTables } from \"../helpers/getSyncableTables\";\nimport { DexieCloudDB } from \"../db/DexieCloudDB\";\nimport { PersistedSyncState } from \"../db/entities/PersistedSyncState\";\n\nexport function getTablesToSyncify(db: DexieCloudDB, syncState: PersistedSyncState | undefined) {\n const syncedTables = syncState?.syncedTables || [];\n const syncableTables = getSyncableTables(db);\n const tablesToSyncify = syncableTables.filter(\n (tbl) => !syncedTables.includes(tbl.name)\n );\n return tablesToSyncify;\n}\n","import Dexie from 'dexie';\nimport { BehaviorSubject } from 'rxjs';\nimport { take } from 'rxjs/operators';\nimport { DexieCloudDB } from '../db/DexieCloudDB';\nimport { DXCAlert } from '../types/DXCAlert';\nimport { DXCInputField } from '../types/DXCInputField';\nimport { DXCUserInteraction } from '../types/DXCUserInteraction';\n\nexport interface DXCUserInteractionRequest {\n type: DXCUserInteraction['type'];\n title: string;\n alerts: DXCAlert[];\n fields: { [name: string]: DXCInputField };\n}\n\nexport function interactWithUser<T extends DXCUserInteractionRequest>(\n userInteraction: BehaviorSubject<DXCUserInteraction | undefined>,\n req: T\n): Promise<\n {\n [P in keyof T['fields']]: string;\n }\n> {\n let done = false;\n return new Promise<\n {\n [P in keyof T['fields']]: string;\n }\n >((resolve, reject) => {\n const interactionProps = {\n ...req,\n onSubmit: (\n res: {\n [P in keyof T['fields']]: string;\n }\n ) => {\n userInteraction.next(undefined);\n done = true;\n resolve(res);\n },\n onCancel: () => {\n userInteraction.next(undefined);\n done = true;\n reject(new Dexie.AbortError(\"User cancelled\"));\n },\n } as DXCUserInteraction;\n userInteraction.next(interactionProps);\n // Start subscribing for external updates to db.cloud.userInteraction, and if so, cancel this request.\n /*const subscription = userInteraction.subscribe((currentInteractionProps) => {\n if (currentInteractionProps !== interactionProps) {\n if (subscription) subscription.unsubscribe();\n if (!done) {\n reject(new Dexie.AbortError(\"User cancelled\"));\n }\n }\n });*/\n });\n}\n\nexport function alertUser(\n userInteraction: BehaviorSubject<DXCUserInteraction | undefined>,\n title: string,\n ...alerts: DXCAlert[]\n) {\n return interactWithUser(userInteraction, {\n type: 'message-alert',\n title,\n alerts,\n fields: {}\n });\n}\n\nexport async function promptForEmail(\n userInteraction: BehaviorSubject<DXCUserInteraction | undefined>,\n title: string,\n emailHint?: string\n) {\n let email = emailHint || '';\n while (!email || !/^[\\w-\\.]+@([\\w-]+\\.)+[\\w-]{2,10}$/.test(email)) {\n email = (\n await interactWithUser(userInteraction, {\n type: 'email',\n title,\n alerts: email\n ? [\n {\n type: 'error',\n messageCode: 'INVALID_EMAIL',\n message: 'Please enter a valid email address',\n messageParams: {},\n },\n ]\n : [],\n fields: {\n email: {\n type: 'email',\n placeholder: 'you@somedomain.com',\n },\n },\n })\n ).email;\n }\n return email;\n}\n\nexport async function promptForOTP(\n userInteraction: BehaviorSubject<DXCUserInteraction | undefined>,\n email: string,\n alert?: DXCAlert\n) {\n const alerts: DXCAlert[] = [\n {\n type: 'info',\n messageCode: 'OTP_SENT',\n message: `A One-Time password has been sent to {email}`,\n messageParams: { email },\n },\n ];\n if (alert) {\n alerts.push(alert);\n }\n const { otp } = await interactWithUser(userInteraction, {\n type: 'otp',\n title: 'Enter OTP',\n alerts,\n fields: {\n otp: {\n type: 'otp',\n label: 'OTP',\n placeholder: 'Paste OTP here',\n },\n },\n });\n return otp;\n}\n","import type {\n RefreshTokenRequest,\n TokenFinalResponse,\n} from 'dexie-cloud-common';\nimport { b64encode } from 'dreambase-library/dist/common/base64';\nimport { BehaviorSubject } from 'rxjs';\nimport { DexieCloudDB } from '../db/DexieCloudDB';\nimport { UserLogin } from '../db/entities/UserLogin';\nimport { DXCAlert } from '../types/DXCAlert';\nimport {\n DXCMessageAlert,\n DXCUserInteraction,\n} from '../types/DXCUserInteraction';\nimport { alertUser, interactWithUser } from './interactWithUser';\n\nexport type FetchTokenCallback = (tokenParams: {\n public_key: string;\n hints?: { userId?: string; email?: string; grant_type?: string };\n}) => Promise<TokenFinalResponse>;\n\nexport async function loadAccessToken(\n db: DexieCloudDB\n): Promise<string | undefined> {\n const currentUser = await db.getCurrentUser();\n const {\n accessToken,\n accessTokenExpiration,\n refreshToken,\n refreshTokenExpiration,\n claims,\n } = currentUser;\n if (!accessToken) return;\n const expTime = accessTokenExpiration?.getTime() ?? Infinity;\n if (expTime > Date.now()) {\n return accessToken;\n }\n if (!refreshToken) {\n throw new Error(`Refresh token missing`);\n }\n const refreshExpTime = refreshTokenExpiration?.getTime() ?? Infinity;\n if (refreshExpTime <= Date.now()) {\n throw new Error(`Refresh token has expired`);\n }\n const refreshedLogin = await refreshAccessToken(\n db.cloud.options!.databaseUrl,\n currentUser\n );\n await db.table('$logins').update(claims.sub, {\n accessToken: refreshedLogin.accessToken,\n accessTokenExpiration: refreshedLogin.accessTokenExpiration,\n });\n return refreshedLogin.accessToken;\n}\n\nexport async function authenticate(\n url: string,\n context: UserLogin,\n fetchToken: FetchTokenCallback,\n userInteraction: BehaviorSubject<DXCUserInteraction | undefined>,\n hints?: { userId?: string; email?: string; grant_type?: string }\n): Promise<UserLogin> {\n if (\n context.accessToken &&\n context.accessTokenExpiration!.getTime() > Date.now()\n ) {\n return context;\n } else if (\n context.refreshToken &&\n (!context.refreshTokenExpiration ||\n context.refreshTokenExpiration.getTime() > Date.now())\n ) {\n return await refreshAccessToken(url, context);\n } else {\n return await userAuthenticate(context, fetchToken, userInteraction, hints);\n }\n}\n\nexport async function refreshAccessToken(\n url: string,\n login: UserLogin\n): Promise<UserLogin> {\n if (!login.refreshToken)\n throw new Error(`Cannot refresh token - refresh token is missing.`);\n if (!login.nonExportablePrivateKey)\n throw new Error(\n `login.nonExportablePrivateKey is missing - cannot sign refresh token without a private key.`\n );\n\n const time_stamp = Date.now();\n const signing_algorithm = 'RSASSA-PKCS1-v1_5';\n const textEncoder = new TextEncoder();\n const data = textEncoder.encode(login.refreshToken + time_stamp);\n const binarySignature = await crypto.subtle.sign(\n signing_algorithm,\n login.nonExportablePrivateKey,\n data\n );\n const signature = b64encode(binarySignature);\n\n const tokenRequest: RefreshTokenRequest = {\n grant_type: 'refresh_token',\n refresh_token: login.refreshToken,\n scopes: ['ACCESS_DB'],\n signature,\n signing_algorithm,\n time_stamp,\n };\n const res = await fetch(`${url}/token`, {\n body: JSON.stringify(tokenRequest),\n method: 'post',\n headers: { 'Content-Type': 'application/json' },\n mode: 'cors',\n });\n if (res.status !== 200)\n throw new Error(`RefreshToken: Status ${res.status} from ${url}/token`);\n const response: TokenFinalResponse = await res.json();\n login.accessToken = response.accessToken;\n login.accessTokenExpiration = response.accessTokenExpiration\n ? new Date(response.accessTokenExpiration)\n : undefined;\n return login;\n}\n\nasync function userAuthenticate(\n context: UserLogin,\n fetchToken: FetchTokenCallback,\n userInteraction: BehaviorSubject<DXCUserInteraction | undefined>,\n hints?: { userId?: string; email?: string; grant_type?: string }\n) {\n const { privateKey, publicKey } = await crypto.subtle.generateKey(\n {\n name: 'RSASSA-PKCS1-v1_5',\n modulusLength: 2048,\n publicExponent: new Uint8Array([0x01, 0x00, 0x01]),\n hash: { name: 'SHA-256' },\n },\n false, // Non-exportable...\n ['sign', 'verify']\n );\n context.nonExportablePrivateKey = privateKey; //...but storable!\n const publicKeySPKI = await crypto.subtle.exportKey('spki', publicKey);\n const publicKeyPEM = spkiToPEM(publicKeySPKI);\n context.publicKey = publicKey;\n\n try {\n const response2 = await fetchToken({\n public_key: publicKeyPEM,\n hints,\n });\n\n if (response2.type !== 'tokens')\n throw new Error(\n `Unexpected response type from token endpoint: ${response2.type}`\n );\n\n context.accessToken = response2.accessToken;\n context.accessTokenExpiration = new Date(response2.accessTokenExpiration);\n context.refreshToken = response2.refreshToken;\n if (response2.refreshTokenExpiration) {\n context.refreshTokenExpiration = new Date(\n response2.refreshTokenExpiration\n );\n }\n context.userId = response2.claims.sub;\n context.email = response2.claims.email;\n context.name = response2.claims.name;\n context.claims = response2.claims;\n\n if (response2.alerts && response2.alerts.length > 0) {\n await interactWithUser(userInteraction, {\n type: 'message-alert',\n title: 'Authentication Alert',\n fields: {},\n alerts: response2.alerts as DXCAlert[],\n });\n }\n return context;\n } catch (error) {\n await alertUser(userInteraction, 'Authentication Failed', {\n type: 'error',\n messageCode: 'GENERIC_ERROR',\n message: `We're having a problem to authenticate rigth now.`,\n messageParams: {}\n }).catch(()=>{});\n throw error;\n }\n}\n\nfunction spkiToPEM(keydata: ArrayBuffer) {\n const keydataB64 = b64encode(keydata);\n const keydataB64Pem = formatAsPem(keydataB64);\n return keydataB64Pem;\n}\n\nfunction formatAsPem(str: string) {\n let finalString = '-----BEGIN PUBLIC KEY-----\\n';\n\n while (str.length > 0) {\n finalString += str.substring(0, 64) + '\\n';\n str = str.substring(64);\n }\n\n finalString = finalString + '-----END PUBLIC KEY-----';\n\n return finalString;\n}\n","export class HttpError extends Error {\n httpStatus: number;\n constructor(\n res: Response,\n message?: string)\n {\n super(message || `${res.status} ${res.statusText}`);\n this.httpStatus = res.status;\n }\n\n get name() {\n return \"HttpError\";\n }\n}\n","import { DexieCloudDB } from '../db/DexieCloudDB';\nimport { PersistedSyncState } from '../db/entities/PersistedSyncState';\nimport { loadAccessToken } from '../authentication/authenticate';\nimport { BISON, TSON } from '../TSON';\nimport { getSyncableTables } from '../helpers/getSyncableTables';\nimport { BaseRevisionMapEntry } from '../db/entities/BaseRevisionMapEntry';\nimport { HttpError } from '../errors/HttpError';\nimport {\n DBOperationsSet,\n DexieCloudSchema,\n SyncRequest,\n SyncResponse\n} from 'dexie-cloud-common';\n//import {BisonWebStreamReader} from \"dreambase-library/dist/typeson-simplified/BisonWebStreamReader\";\n\nexport async function syncWithServer(\n changes: DBOperationsSet,\n syncState: PersistedSyncState | undefined,\n baseRevs: BaseRevisionMapEntry[],\n db: DexieCloudDB,\n databaseUrl: string,\n schema: DexieCloudSchema | null,\n clientIdentity: string\n): Promise<SyncResponse> {\n //\n // Push changes to server using fetch\n //\n const headers: HeadersInit = {\n Accept: 'application/json, application/x-bison, application/x-bison-stream',\n 'Content-Type': 'application/tson'\n };\n const accessToken = await loadAccessToken(db);\n if (accessToken) {\n headers.Authorization = `Bearer ${accessToken}`;\n }\n\n const syncRequest: SyncRequest = {\n dbID: syncState?.remoteDbId,\n clientIdentity,\n schema: schema || {},\n lastPull: syncState ? {\n serverRevision: syncState.serverRevision!,\n realms: syncState.realms,\n inviteRealms: syncState.inviteRealms\n } : undefined,\n baseRevs,\n //baseRevisions: syncState?.baseRevisions || [],\n changes\n };\n console.debug(\"Sync request\", syncRequest);\n db.syncStateChangedEvent.next({\n phase: 'pushing',\n });\n const res = await fetch(`${databaseUrl}/sync`, {\n method: 'post',\n headers,\n body: TSON.stringify(syncRequest)\n });\n //const contentLength = Number(res.headers.get('content-length'));\n db.syncStateChangedEvent.next({\n phase: 'pulling'\n });\n\n if (!res.ok) {\n throw new HttpError(res);\n }\n\n switch (res.headers.get('content-type')) {\n case 'application/x-bison':\n return BISON.fromBinary(await res.blob());\n case 'application/x-bison-stream': //return BisonWebStreamReader(BISON, res);\n default:\n case 'application/json': {\n const text = await res.text();\n const syncRes = TSON.parse(text);\n return syncRes;\n }\n }\n}\n","import { Table } from \"dexie\";\nimport { EntityCommon } from \"../db/entities/EntityCommon\";\nimport { UserLogin } from \"../db/entities/UserLogin\";\nimport { Member } from \"../db/entities/Member\";\nimport { UNAUTHORIZED_USER } from \"../authentication/UNAUTHORIZED_USER\";\nimport { Realm } from \"../db/entities/Realm\";\n\nexport async function modifyLocalObjectsWithNewUserId(\n syncifiedTables: Table<EntityCommon>[],\n currentUser: UserLogin,\n alreadySyncedRealms?: string[]) {\n const ignoredRealms = new Set(alreadySyncedRealms || []);\n for (const table of syncifiedTables) {\n if (table.name === \"members\") {\n // members\n await table.toCollection().modify((member: Member) => {\n if (!ignoredRealms.has(member.realmId) && member.userId === UNAUTHORIZED_USER.userId) {\n member.userId = currentUser.userId;\n }\n });\n } else if (table.name === \"roles\") {\n // roles\n // No changes needed.\n } else if (table.name === \"realms\") {\n // realms\n await table.toCollection().modify((realm: Realm) => {\n if (!ignoredRealms.has(realm.realmId) && !realm.owner || realm.owner === UNAUTHORIZED_USER.userId) {\n realm.owner = currentUser.userId;\n }\n });\n } else {\n // application entities\n await table.toCollection().modify((obj) => {\n if (!obj.realmId || !ignoredRealms.has(obj.realmId)) {\n if (!obj.owner || obj.owner === UNAUTHORIZED_USER.userId)\n obj.owner = currentUser.userId;\n if (!obj.realmId || obj.realmId === UNAUTHORIZED_USER.userId) {\n obj.realmId = currentUser.userId;\n }\n }\n });\n }\n }\n}\n","import Dexie, { Table } from 'dexie';\n\nexport async function bulkUpdate(\n table: Table,\n keys: any[],\n changeSpecs: { [keyPath: string]: any }[]\n) {\n const objs = await table.bulkGet(keys);\n const resultKeys: any[] = [];\n const resultObjs: any[] = [];\n keys.forEach((key, idx) => {\n const obj = objs[idx];\n if (obj) {\n for (const [keyPath, value] of Object.entries(changeSpecs[idx])) {\n if (keyPath === table.schema.primKey.keyPath) {\n throw new Error(`Cannot change primary key`);\n }\n Dexie.setByKeyPath(obj, keyPath, value);\n }\n resultKeys.push(key);\n resultObjs.push(obj);\n }\n });\n await (table.schema.primKey.keyPath == null\n ? table.bulkPut(resultObjs, resultKeys)\n : table.bulkPut(resultObjs));\n}\n","import Dexie from \"dexie\";\n\nexport interface CancelToken {\n cancelled: boolean;\n}\n\nexport function throwIfCancelled(cancelToken?: CancelToken) {\n if (cancelToken?.cancelled) throw new Dexie.AbortError(`Operation was cancelled`);\n}\n","/* Need this because navigator.onLine seems to say \"false\" when it is actually online.\n This function relies initially on navigator.onLine but then uses online and offline events\n which seem to be more reliable.\n*/\nexport let isOnline = navigator.onLine;\nself.addEventListener('online', ()=>isOnline = true);\nself.addEventListener('offline', ()=>isOnline = false);\n","import { DexieCloudDB } from '../db/DexieCloudDB';\nimport { DexieCloudSchema, SyncResponse } from 'dexie-cloud-common';\n\nexport async function updateBaseRevs(db: DexieCloudDB, schema: DexieCloudSchema, latestRevisions: { [table: string]: number; }, serverRev: any) {\n await db.$baseRevs.bulkPut(\n Object.keys(schema)\n .filter((table) => schema[table].markedForSync)\n .map((tableName) => {\n const lastClientRevOnPreviousServerRev = latestRevisions[tableName] || 0;\n return {\n tableName,\n clientRev: lastClientRevOnPreviousServerRev + 1,\n serverRev,\n };\n })\n );\n}\n","import { DBOperationsSet } from 'dexie-cloud-common';\n\nexport function getLatestRevisionsPerTable(\n clientChangeSet: DBOperationsSet,\n lastRevisions = {} as { [table: string]: number; }) {\n for (const { table, muts } of clientChangeSet) {\n const lastRev = muts.length > 0 ? muts[muts.length - 1].rev || 0 : 0;\n lastRevisions[table] = lastRev;\n }\n return lastRevisions;\n}\n","import { getMutationTable } from '../helpers/getMutationTable';\nimport { getSyncableTables } from '../helpers/getSyncableTables';\nimport { DexieCloudDB } from '../db/DexieCloudDB';\nimport { listSyncifiedChanges } from './listSyncifiedChanges';\nimport { getTablesToSyncify } from './getTablesToSyncify';\nimport { listClientChanges } from './listClientChanges';\nimport { syncWithServer } from './syncWithServer';\nimport Dexie from 'dexie';\nimport { modifyLocalObjectsWithNewUserId } from './modifyLocalObjectsWithNewUserId';\nimport { bulkUpdate } from '../helpers/bulkUpdate';\nimport { throwIfCancelled } from '../helpers/CancelToken';\nimport { DexieCloudOptions } from '../DexieCloudOptions';\nimport { BaseRevisionMapEntry } from '../db/entities/BaseRevisionMapEntry';\nimport { getTableFromMutationTable } from '../helpers/getTableFromMutationTable';\nimport {\n applyOperations,\n DBKeyMutationSet,\n DBOperationsSet,\n DexieCloudSchema,\n randomString,\n subtractChanges,\n SyncResponse,\n toDBOperationSet,\n} from 'dexie-cloud-common';\nimport { PersistedSyncState } from '../db/entities/PersistedSyncState';\nimport { isOnline } from './isOnline';\nimport { updateBaseRevs } from './updateBaseRevs';\nimport { getLatestRevisionsPerTable } from './getLatestRevisionsPerTable';\n\nexport const CURRENT_SYNC_WORKER = 'currentSyncWorker';\n\nexport let numberOfSyncRequests = 0;\n\n/*\n TODO:\n 1. V: Rätta flödet och gör det persistent mellan transaktioner\n 2. Sync-requestet ska autenticera sig med nuvarande användare.\n MEN:\n Vissa medskickade operationer kan vara gjorda av annan användare.\n Därför: Om några av client-changes är andra användare, så måste de användarnas\n tokens följa med som extra parameter till fetch-requestet.\n Servern skall då validera och genomföra dessa operationer baserat på alternativt token.\n Kanske kan vi skita i det flödet just nu och hindra att det uppstår istället.\n Hur? Jo, genom:\n 1. Användare är ANONYMOUS\n 2. Data laddas ned.\n 3. Data modifieras.\n 4. Användare loggar in.\n 5. Sync: Några inledande requests är ANONYMOUS men autenticeras som användaren.\n\n X: Se till att vi förhandlar initialt sync state eller uppdaterat sync state (tabell aliases etc)\n\n Y: Använd Bison hjälpare för streamad BISON?\n\n*/\n\nexport interface SyncOptions {\n isInitialSync?: boolean;\n cancelToken?: { cancelled: boolean };\n justCheckIfNeeded?: boolean;\n retryImmediatelyOnFetchError?: boolean;\n purpose?: 'pull' | 'push';\n}\n\nexport function sync(\n db: DexieCloudDB,\n options: DexieCloudOptions,\n schema: DexieCloudSchema,\n syncOptions?: SyncOptions\n): Promise<boolean> {\n return _sync\n .apply(this, arguments)\n .then(() => {\n if (!syncOptions?.justCheckIfNeeded) {\n db.syncStateChangedEvent.next({\n phase: 'in-sync',\n });\n }\n })\n .catch(async (error: any) => {\n if (syncOptions?.justCheckIfNeeded) return Promise.reject(error); // Just rethrow.\n console.debug('Error from _sync', {\n isOnline,\n syncOptions,\n error,\n });\n if (\n isOnline &&\n syncOptions?.retryImmediatelyOnFetchError &&\n error?.name === 'TypeError' &&\n /fetch/.test(error?.message)\n ) {\n db.syncStateChangedEvent.next({\n phase: 'error',\n error,\n });\n // Retry again in 500 ms but if it fails again, don't retry.\n await new Promise((resolve) => setTimeout(resolve, 500));\n return await sync(db, options, schema, {\n ...syncOptions,\n retryImmediatelyOnFetchError: false,\n });\n }\n // Make sure that no matter whether sync() explodes or not,\n // always update the timestamp. Also store the error.\n await db.$syncState.update('syncState', {\n timestamp: new Date(),\n error: '' + error,\n });\n db.syncStateChangedEvent.next({\n phase: isOnline ? 'error' : 'offline',\n error,\n });\n return Promise.reject(error);\n });\n}\n\nasync function _sync(\n db: DexieCloudDB,\n options: DexieCloudOptions,\n schema: DexieCloudSchema,\n { isInitialSync, cancelToken, justCheckIfNeeded, purpose }: SyncOptions = {\n isInitialSync: false,\n }\n): Promise<boolean> {\n if (!justCheckIfNeeded) {\n console.debug('SYNC STARTED', { isInitialSync, purpose });\n }\n if (!db.cloud.options?.databaseUrl)\n throw new Error(\n `Internal error: sync must not be called when no databaseUrl is configured`\n );\n const { databaseUrl } = options;\n const currentUser = await db.getCurrentUser(); // Keep same value across entire sync flow:\n const tablesToSync = currentUser.isLoggedIn ? getSyncableTables(db) : [];\n\n const mutationTables = tablesToSync.map((tbl) =>\n db.table(getMutationTable(tbl.name))\n );\n\n // If this is not the initial sync,\n // go through tables that were previously not synced but should now be according to\n // logged in state and the sync table whitelist in db.cloud.options.\n //\n // Prepare for syncification by modifying locally unauthorized objects:\n //\n const persistedSyncState = await db.getPersistedSyncState();\n const tablesToSyncify =\n !isInitialSync && currentUser.isLoggedIn\n ? getTablesToSyncify(db, persistedSyncState)\n : [];\n throwIfCancelled(cancelToken);\n const doSyncify = tablesToSyncify.length > 0;\n\n if (doSyncify) {\n if (justCheckIfNeeded) return true;\n console.debug('sync doSyncify is true');\n await db.transaction('rw', tablesToSyncify, async (tx) => {\n // @ts-ignore\n tx.idbtrans.disableChangeTracking = true;\n // @ts-ignore\n tx.idbtrans.disableAccessControl = true; // TODO: Take care of this flag in access control middleware!\n await modifyLocalObjectsWithNewUserId(\n tablesToSyncify,\n currentUser,\n persistedSyncState?.realms\n );\n });\n throwIfCancelled(cancelToken);\n }\n //\n // List changes to sync\n //\n const [clientChangeSet, syncState, baseRevs] = await db.transaction(\n 'r',\n db.tables,\n async () => {\n const syncState = await db.getPersistedSyncState();\n const baseRevs = await db.$baseRevs.toArray();\n let clientChanges = await listClientChanges(mutationTables, db);\n throwIfCancelled(cancelToken);\n if (doSyncify) {\n const syncificationInserts = await listSyncifiedChanges(\n tablesToSyncify,\n currentUser,\n schema!,\n persistedSyncState?.realms\n );\n throwIfCancelled(cancelToken);\n clientChanges = clientChanges.concat(syncificationInserts);\n return [clientChanges, syncState, baseRevs];\n }\n return [clientChanges, syncState, baseRevs];\n }\n );\n\n const syncIsNeeded = clientChangeSet.some((set) =>\n set.muts.some((mut) => mut.keys.length > 0)\n );\n if (justCheckIfNeeded) {\n console.debug('Sync is needed:', syncIsNeeded);\n return syncIsNeeded;\n }\n if (purpose === \"push\" && !syncIsNeeded) {\n // The purpose of this request was to push changes\n return false;\n }\n\n const latestRevisions = getLatestRevisionsPerTable(\n clientChangeSet,\n syncState?.latestRevisions\n );\n\n const clientIdentity = syncState?.clientIdentity || randomString(16);\n\n //\n // Push changes to server\n //\n throwIfCancelled(cancelToken);\n const res = await syncWithServer(\n clientChangeSet,\n syncState,\n baseRevs,\n db,\n databaseUrl,\n schema,\n clientIdentity\n );\n console.debug('Sync response', res);\n\n //\n // Apply changes locally and clear old change entries:\n //\n const done = await db.transaction('rw', db.tables, async (tx) => {\n // @ts-ignore\n tx.idbtrans.disableChangeTracking = true;\n // @ts-ignore\n tx.idbtrans.disableAccessControl = true; // TODO: Take care of this flag in access control middleware!\n\n // Update db.cloud.schema from server response.\n // Local schema MAY include a subset of tables, so do not force all tables into local schema.\n for (const tableName of Object.keys(schema)) {\n if (res.schema[tableName]) {\n // Write directly into configured schema. This code can only be executed alone.\n schema[tableName] = res.schema[tableName];\n }\n }\n await db.$syncState.put(schema, 'schema');\n\n // List mutations that happened during our exchange with the server:\n const addedClientChanges = await listClientChanges(mutationTables, db, {\n since: latestRevisions,\n });\n\n //\n // Delete changes now as server has return success\n // (but keep changes that haven't reached server yet)\n //\n for (const mutTable of mutationTables) {\n const tableName = getTableFromMutationTable(mutTable.name);\n if (\n !addedClientChanges.some(\n (ch) => ch.table === tableName && ch.muts.length > 0\n )\n ) {\n // No added mutations for this table during the time we sent changes\n // to the server.\n // It is therefore safe to clear all changes (which is faster than\n // deleting a range)\n await Promise.all([\n mutTable.clear(),\n db.$baseRevs.where({ tableName }).delete(),\n ]);\n } else if (latestRevisions[mutTable.name]) {\n const latestRev = latestRevisions[mutTable.name] || 0;\n //await mutTable.where('rev').belowOrEqual(latestRev).reverse().offset(1).delete();\n await Promise.all([\n mutTable.where('rev').belowOrEqual(latestRev).delete(),\n db.$baseRevs\n .where(':id')\n .between(\n [tableName, -Infinity],\n [tableName, latestRev + 1],\n true,\n true\n )\n .reverse()\n .offset(1) // Keep one entry (the one mapping muts that came during fetch --> previous server revision)\n .delete(),\n ]);\n } else {\n // In this case, the mutation table only contains added items after sending empty changeset to server.\n // We should not clear out anything now.\n }\n }\n\n // Update latestRevisions object according to additional changes:\n getLatestRevisionsPerTable(addedClientChanges, latestRevisions);\n\n // Update/add new entries into baseRevs map.\n // * On tables without mutations since last serverRevision,\n // this will update existing entry.\n // * On tables where mutations have been recorded since last\n // serverRevision, this will create a new entry.\n // The purpose of this operation is to mark a start revision (per table)\n // so that all client-mutations that come after this, will be mapped to current\n // server revision.\n await updateBaseRevs(db, schema, latestRevisions, res.serverRevision);\n\n const syncState = await db.getPersistedSyncState();\n\n //\n // Delete objects from removed realms\n //\n await deleteObjectsFromRemovedRealms(db, res, syncState);\n\n //\n // Update syncState\n //\n const newSyncState: PersistedSyncState = syncState || {\n syncedTables: [],\n latestRevisions: {},\n realms: [],\n inviteRealms: [],\n clientIdentity\n };\n newSyncState.syncedTables = tablesToSync\n .map((tbl) => tbl.name)\n .concat(tablesToSyncify.map((tbl) => tbl.name));\n newSyncState.latestRevisions = latestRevisions;\n newSyncState.remoteDbId = res.dbId;\n newSyncState.initiallySynced = true;\n newSyncState.realms = res.realms;\n newSyncState.inviteRealms = res.inviteRealms;\n newSyncState.serverRevision = res.serverRevision;\n newSyncState.timestamp = new Date();\n delete newSyncState.error;\n\n const filteredChanges = filterServerChangesThroughAddedClientChanges(\n res.changes,\n addedClientChanges\n );\n\n //\n // apply server changes\n //\n await applyServerChanges(filteredChanges, db);\n\n //\n // Update syncState\n //\n db.$syncState.put(newSyncState, 'syncState');\n\n return addedClientChanges.length === 0;\n });\n if (!done) {\n console.debug('MORE SYNC NEEDED. Go for it again!');\n return await _sync(db, options, schema, { isInitialSync, cancelToken });\n }\n console.debug('SYNC DONE', { isInitialSync });\n return false; // Not needed anymore\n}\n\nasync function deleteObjectsFromRemovedRealms(\n db: DexieCloudDB,\n res: SyncResponse,\n prevState: PersistedSyncState | undefined\n) {\n const deletedRealms: string[] = [];\n const previousRealmSet = prevState\n ? prevState.realms.concat(prevState.inviteRealms)\n : [];\n const updatedRealmSet = new Set([...res.realms, ...res.inviteRealms]);\n for (const realmId of previousRealmSet) {\n if (!updatedRealmSet.has(realmId)) deletedRealms.push(realmId);\n }\n if (deletedRealms.length > 0) {\n const deletedRealmSet = new Set(deletedRealms);\n const tables = getSyncableTables(db);\n for (const table of tables) {\n if (\n table.schema.indexes.some(\n (idx) =>\n idx.keyPath === 'realmId' ||\n (Array.isArray(idx.keyPath) && idx.keyPath[0] === 'realmId')\n )\n ) {\n // There's an index to use:\n await table.where('realmId').anyOf(deletedRealms).delete();\n } else {\n // No index to use:\n await table\n .filter((obj) => !!obj?.realmId && deletedRealmSet.has(obj.realmId))\n .delete();\n }\n }\n }\n}\n\nexport async function applyServerChanges(\n changes: DBOperationsSet,\n db: DexieCloudDB\n) {\n console.debug('Applying server changes', changes, Dexie.currentTransaction);\n for (const { table: tableName, muts } of changes) {\n const table = db.table(tableName);\n if (!table) continue; // If server sends changes on a table we don't have, ignore it.\n const { primaryKey } = table.core.schema;\n for (const mut of muts) {\n switch (mut.type) {\n case 'insert':\n if (primaryKey.outbound) {\n await table.bulkAdd(mut.values, mut.keys);\n } else {\n mut.keys.forEach((key, i) => {\n Dexie.setByKeyPath(mut.values[i], primaryKey.keyPath as any, key);\n });\n await table.bulkAdd(mut.values);\n }\n break;\n case 'upsert':\n if (primaryKey.outbound) {\n await table.bulkPut(mut.values, mut.keys);\n } else {\n mut.keys.forEach((key, i) => {\n Dexie.setByKeyPath(mut.values[i], primaryKey.keyPath as any, key);\n });\n await table.bulkPut(mut.values);\n }\n break;\n case 'modify':\n if (mut.keys.length === 1) {\n await table.update(mut.keys[0], mut.changeSpec);\n } else {\n await table.where(':id').anyOf(mut.keys).modify(mut.changeSpec);\n }\n break;\n case 'update':\n await bulkUpdate(table, mut.keys, mut.changeSpecs);\n break;\n case 'delete':\n await table.bulkDelete(mut.keys);\n break;\n }\n }\n }\n}\n\nexport function filterServerChangesThroughAddedClientChanges(\n serverChanges: DBOperationsSet,\n addedClientChanges: DBOperationsSet\n): DBOperationsSet {\n const changes: DBKeyMutationSet = {};\n applyOperations(changes, serverChanges);\n const localPostChanges: DBKeyMutationSet = {};\n applyOperations(localPostChanges, addedClientChanges);\n subtractChanges(changes, localPostChanges);\n return toDBOperationSet(changes);\n}\n","import { BehaviorSubject } from 'rxjs';\nimport { filter, take } from 'rxjs/operators';\nimport { DexieCloudDB } from '../db/DexieCloudDB';\nimport { compareBigInts, FakeBigInt } from '../TSON';\nimport { WSConnectionMsg } from '../WSObservable';\nimport { triggerSync } from './triggerSync';\nimport Dexie from 'dexie';\nimport { computeRealmSetHash } from '../helpers/computeRealmSetHash';\nimport { DBOperationsSet } from 'dexie-cloud-common';\nimport { getSyncableTables } from '../helpers/getSyncableTables';\nimport { getMutationTable } from '../helpers/getMutationTable';\nimport { listClientChanges } from './listClientChanges';\nimport {\n applyServerChanges,\n filterServerChangesThroughAddedClientChanges,\n} from './sync';\nimport { updateBaseRevs } from './updateBaseRevs';\nimport { getLatestRevisionsPerTable } from './getLatestRevisionsPerTable';\nimport { refreshAccessToken } from '../authentication/authenticate';\n\nexport type MessagesFromServerConsumer = ReturnType<\n typeof MessagesFromServerConsumer\n>;\n\nexport function MessagesFromServerConsumer(db: DexieCloudDB) {\n const queue: WSConnectionMsg[] = [];\n const readyToServe = new BehaviorSubject(true);\n const event = new BehaviorSubject(null);\n let isWorking = false;\n\n event.subscribe(async () => {\n if (isWorking) return;\n if (queue.length > 0) {\n isWorking = true;\n readyToServe.next(false);\n try {\n await consumeQueue();\n } finally {\n isWorking = false;\n readyToServe.next(true);\n }\n }\n });\n\n function enqueue(msg: WSConnectionMsg) {\n queue.push(msg);\n event.next(null);\n }\n\n async function consumeQueue() {\n while (queue.length > 0) {\n const msg = queue.shift();\n try {\n console.debug('processing msg', msg);\n await db.cloud.syncState\n .pipe(\n filter(({ phase }) => phase === 'in-sync' || phase === 'error'),\n take(1)\n )\n .toPromise();\n console.debug('processing msg', msg);\n const persistedSyncState = db.cloud.persistedSyncState.value;\n //syncState.\n if (!msg) continue;\n switch (msg.type) {\n case 'token-expired':\n console.debug(\n 'WebSocket observable: Token expired. Refreshing token...'\n );\n const user = db.cloud.currentUser.value;\n // Refresh access token\n const refreshedLogin = await refreshAccessToken(\n db.cloud.options!.databaseUrl,\n user\n );\n // Persist updated access token\n await db.table('$logins').update(user.userId, {\n accessToken: refreshedLogin.accessToken,\n accessTokenExpiration: refreshedLogin.accessTokenExpiration,\n });\n // Updating $logins will trigger emission of db.cloud.currentUser observable, which\n // in turn will lead to that connectWebSocket.ts will reconnect the socket with the\n // new token. So we don't need to do anything more here.\n break;\n case 'rev':\n if (\n !persistedSyncState?.serverRevision ||\n compareBigInts(persistedSyncState.serverRevision, msg.rev) < 0\n ) {\n triggerSync(db, \"pull\");\n }\n break;\n case 'realm-added':\n if (!persistedSyncState?.realms?.includes(msg.realm)) {\n triggerSync(db, \"pull\");\n }\n break;\n case 'realm-removed':\n if (persistedSyncState?.realms?.includes(msg.realm)) {\n triggerSync(db, \"pull\");\n }\n break;\n case 'changes':\n console.debug('changes');\n if (db.cloud.syncState.value?.phase === 'error') {\n triggerSync(db, \"pull\");\n break;\n }\n await db.transaction('rw', db.dx.tables, async (tx) => {\n // @ts-ignore\n tx.idbtrans.disableChangeTracking = true;\n // @ts-ignore\n tx.idbtrans.disableAccessControl = true;\n const [schema, syncState, currentUser] = await Promise.all([\n db.getSchema(),\n db.getPersistedSyncState(),\n db.getCurrentUser(),\n ]);\n console.debug('ws message queue: in transaction');\n if (!syncState || !schema || !currentUser) {\n console.debug('required vars not present', {\n syncState,\n schema,\n currentUser,\n });\n return; // Initial sync must have taken place - otherwise, ignore this.\n }\n // Verify again in ACID tx that we're on same server revision.\n if (compareBigInts(msg.baseRev, syncState.serverRevision) !== 0) {\n console.debug(\n `baseRev (${msg.baseRev}) differs from our serverRevision in syncState (${syncState.serverRevision})`\n );\n return; // Ignore message\n }\n // Verify also that the message is based on the exact same set of realms\n const ourRealmSetHash = await Dexie.waitFor(\n computeRealmSetHash(syncState)\n );\n console.debug('ourRealmSetHash', ourRealmSetHash);\n if (ourRealmSetHash !== msg.realmSetHash) {\n console.debug('not same realmSetHash', msg.realmSetHash);\n triggerSync(db, \"pull\");\n // The message isn't based on the same realms.\n // Trigger a sync instead to resolve all things up.\n return;\n }\n // Get clientChanges\n let clientChanges: DBOperationsSet = [];\n if (currentUser.isLoggedIn) {\n const mutationTables = getSyncableTables(db).map((tbl) =>\n db.table(getMutationTable(tbl.name))\n );\n clientChanges = await listClientChanges(mutationTables, db);\n console.debug('msg queue: client changes', clientChanges);\n }\n const filteredChanges =\n filterServerChangesThroughAddedClientChanges(\n msg.changes,\n clientChanges\n );\n\n //\n // apply server changes\n //\n console.debug(\n 'applying filtered server changes',\n filteredChanges\n );\n await applyServerChanges(filteredChanges, db);\n\n // Update latest revisions per table in case there are unsynced changes\n // This can be a real case in future when we allow non-eagery sync.\n // And it can actually be realistic now also, but very rare.\n syncState.latestRevisions = getLatestRevisionsPerTable(\n clientChanges,\n syncState.latestRevisions\n );\n syncState.serverRevision = msg.newRev;\n\n // Update base revs\n console.debug('Updating baseRefs', syncState.latestRevisions);\n await updateBaseRevs(\n db,\n schema!,\n syncState.latestRevisions,\n msg.newRev\n );\n\n //\n // Update syncState\n //\n console.debug('Updating syncState', syncState);\n await db.$syncState.put(syncState, 'syncState');\n });\n console.debug('msg queue: done with rw transaction');\n break;\n }\n } catch (error) {\n console.error(`Error in msg queue`, error);\n }\n }\n }\n\n return {\n enqueue,\n readyToServe,\n };\n}\n","import Dexie, { Table } from 'dexie';\nimport { GuardedJob } from './entities/GuardedJob';\nimport { UserLogin } from './entities/UserLogin';\nimport { PersistedSyncState } from './entities/PersistedSyncState';\nimport { Realm } from './entities/Realm';\nimport { Member } from './entities/Member';\nimport { Role } from './entities/Role';\nimport { UNAUTHORIZED_USER } from '../authentication/UNAUTHORIZED_USER';\nimport { DexieCloudOptions } from '../DexieCloudOptions';\nimport { BehaviorSubject, Subject } from 'rxjs';\nimport { BaseRevisionMapEntry } from './entities/BaseRevisionMapEntry';\nimport {\n DBRealm,\n DBRealmMember,\n DBRealmRole,\n DexieCloudSchema,\n} from 'dexie-cloud-common';\nimport { BroadcastedAndLocalEvent } from '../helpers/BroadcastedAndLocalEvent';\nimport { SyncState, SyncStatePhase } from '../types/SyncState';\nimport { MessagesFromServerConsumer } from '../sync/messagesFromServerQueue';\n\n/*export interface DexieCloudDB extends Dexie {\n table(name: string): Table<any, any>;\n table(name: \"$jobs\"): Table<GuardedJob, string>;\n table(name: \"$logins\"): Table<UserLogin, string>;\n table(name: \"$syncState\"): Table<SyncState, \"syncState\">;\n //table(name: \"$pendingChangesFromServer\"): Table<DBOperationsSet, number>;\n}\n*/\n\nexport interface SyncStateChangedEventData {\n phase: SyncStatePhase;\n error?: Error;\n progress?: number;\n}\n\ntype SyncStateTable = Table<\n PersistedSyncState | DexieCloudSchema | DexieCloudOptions,\n 'syncState' | 'options' | 'schema'\n>;\nexport interface DexieCloudDBBase {\n readonly name: Dexie['name'];\n readonly close: Dexie['close'];\n transaction: Dexie['transaction'];\n table: Dexie['table'];\n readonly tables: Dexie['tables'];\n readonly cloud: Dexie['cloud'];\n readonly $jobs: Table<GuardedJob, string>;\n readonly $logins: Table<UserLogin, string>;\n readonly $syncState: SyncStateTable;\n readonly $baseRevs: Table<BaseRevisionMapEntry, [string, number]>;\n\n readonly realms: Table<DBRealm, string>;\n readonly members: Table<DBRealmMember, string>;\n readonly roles: Table<DBRealmRole, [string, string]>;\n\n readonly localSyncEvent: BehaviorSubject<{ purpose?: 'pull' | 'push' }>;\n readonly syncStateChangedEvent: BroadcastedAndLocalEvent<SyncStateChangedEventData>;\n readonly dx: Dexie;\n readonly initiallySynced: boolean;\n}\n\nexport interface DexieCloudDB extends DexieCloudDBBase {\n getCurrentUser(): Promise<UserLogin>;\n getSchema(): Promise<DexieCloudSchema | undefined>;\n getOptions(): Promise<DexieCloudOptions | undefined>;\n getPersistedSyncState(): Promise<PersistedSyncState | undefined>;\n setInitiallySynced(initiallySynced: boolean): void;\n reconfigure(): void;\n messageConsumer: MessagesFromServerConsumer;\n}\n\nconst wm = new WeakMap<object, DexieCloudDB>();\n\nexport const DEXIE_CLOUD_SCHEMA = {\n realms: '@realmId',\n members: '@id',\n roles: '[realmId+name]',\n $jobs: '',\n $syncState: '',\n $baseRevs: '[tableName+clientRev]',\n $logins: 'claims.sub, lastLogin',\n};\n\nlet static_counter = 0;\nexport function DexieCloudDB(dx: Dexie): DexieCloudDB {\n if ('vip' in dx) dx = dx['vip']; // Avoid race condition. Always map to a vipped dexie that don't block during db.on.ready().\n let db = wm.get(dx.cloud);\n if (!db) {\n const localSyncEvent = new Subject<{ purpose: 'push' | 'pull' }>();\n let syncStateChangedEvent =\n new BroadcastedAndLocalEvent<SyncStateChangedEventData>(\n `syncstatechanged-${dx.name}`\n );\n localSyncEvent['id'] = ++static_counter;\n let initiallySynced = false;\n db = {\n get name() {\n return dx.name;\n },\n close() {\n return dx.close();\n },\n transaction: dx.transaction.bind(dx),\n table: dx.table.bind(dx),\n get tables() {\n return dx.tables;\n },\n cloud: dx.cloud,\n get $jobs() {\n return dx.table('$jobs') as Table<GuardedJob, string>;\n },\n get $syncState() {\n return dx.table('$syncState') as SyncStateTable;\n },\n get $baseRevs() {\n return dx.table('$baseRevs') as Table<\n BaseRevisionMapEntry,\n [string, number]\n >;\n },\n get $logins() {\n return dx.table('$logins') as Table<UserLogin, string>;\n },\n\n get realms() {\n return dx.realms;\n },\n get members() {\n return dx.members;\n },\n get roles() {\n return dx.roles;\n },\n get initiallySynced() {\n return initiallySynced;\n },\n localSyncEvent,\n get syncStateChangedEvent() {\n return syncStateChangedEvent;\n },\n dx,\n } as DexieCloudDB;\n\n const helperMethods: Partial<DexieCloudDB> = {\n getCurrentUser() {\n return db!.$logins\n .toArray()\n .then(\n (logins) => logins.find((l) => l.isLoggedIn) || UNAUTHORIZED_USER\n );\n },\n getPersistedSyncState() {\n return db!.$syncState.get('syncState') as Promise<\n PersistedSyncState | undefined\n >;\n },\n getSchema() {\n return db!.$syncState.get('schema') as Promise<\n DexieCloudSchema | undefined\n >;\n },\n getOptions() {\n return db!.$syncState.get('options') as Promise<\n DexieCloudOptions | undefined\n >;\n },\n setInitiallySynced(value) {\n initiallySynced = value;\n },\n reconfigure() {\n syncStateChangedEvent = new BroadcastedAndLocalEvent<SyncState>(\n `syncstatechanged-${dx.name}`\n );\n },\n };\n\n Object.assign(db, helperMethods);\n db.messageConsumer = MessagesFromServerConsumer(db);\n wm.set(dx.cloud, db);\n }\n return db;\n}\n","import { DexieCloudDB } from \"../db/DexieCloudDB\";\nimport { UserLogin } from \"../db/entities/UserLogin\";\n\nexport interface AuthPersistedContext extends UserLogin {\n save(): Promise<void>;\n}\n\n// Emulate true-private property db. Why? So it's not stored in DB.\nconst wm = new WeakMap<AuthPersistedContext, DexieCloudDB>();\n\nexport class AuthPersistedContext {\n constructor(db: DexieCloudDB, userLogin: UserLogin) {\n wm.set(this, db);\n Object.assign(this, userLogin);\n }\n\n static load(db: DexieCloudDB, userId: string) {\n return db\n .table(\"$logins\")\n .get(userId)\n .then(\n (userLogin) => new AuthPersistedContext(db, userLogin || {\n userId,\n claims: {\n sub: userId\n },\n lastLogin: new Date(0)\n })\n );\n }\n\n async save() {\n const db = wm.get(this)!;\n db.table(\"$logins\").put(this);\n }\n}\n","import {\n TokenFinalResponse,\n TokenRequest,\n TokenResponse,\n} from 'dexie-cloud-common';\nimport { DexieCloudDB } from '../db/DexieCloudDB';\nimport { HttpError } from '../errors/HttpError';\nimport { FetchTokenCallback } from './authenticate';\nimport { alertUser, promptForEmail, promptForOTP } from './interactWithUser';\n\nexport function otpFetchTokenCallback(db: DexieCloudDB): FetchTokenCallback {\n const { userInteraction } = db.cloud;\n return async function otpAuthenticate({ public_key, hints }) {\n let tokenRequest: TokenRequest;\n const url = db.cloud.options?.databaseUrl;\n if (!url) throw new Error(`No database URL given.`);\n if (hints?.grant_type === 'demo') {\n const demo_user = await promptForEmail(\n userInteraction,\n 'Enter a demo user email',\n hints?.email || hints?.userId\n );\n tokenRequest = {\n demo_user,\n grant_type: 'demo',\n scopes: ['ACCESS_DB'],\n public_key,\n };\n } else {\n const email = await promptForEmail(\n userInteraction,\n 'Enter email address',\n hints?.email\n );\n tokenRequest = {\n email,\n grant_type: 'otp',\n scopes: ['ACCESS_DB'],\n public_key,\n };\n }\n const res1 = await fetch(`${url}/token`, {\n body: JSON.stringify(tokenRequest),\n method: 'post',\n headers: { 'Content-Type': 'application/json', mode: 'cors' },\n });\n if (res1.status !== 200) {\n const errMsg = await res1.text();\n await alertUser(userInteraction, \"Token request failed\", {\n type: 'error',\n messageCode: 'GENERIC_ERROR',\n message: errMsg,\n messageParams: {}\n }).catch(()=>{});\n throw new HttpError(res1, errMsg);\n }\n const response: TokenResponse = await res1.json();\n if (response.type === 'tokens') {\n // Demo user request can get a \"tokens\" response right away\n return response;\n } else if (tokenRequest.grant_type === 'otp') {\n if (response.type !== 'otp-sent')\n throw new Error(`Unexpected response from ${url}/token`);\n const otp = await promptForOTP(userInteraction, tokenRequest.email);\n tokenRequest.otp = otp || '';\n tokenRequest.otp_id = response.otp_id;\n\n let res2 = await fetch(`${url}/token`, {\n body: JSON.stringify(tokenRequest),\n method: 'post',\n headers: { 'Content-Type': 'application/json' },\n mode: 'cors',\n });\n while (res2.status === 401) {\n const errorText = await res2.text();\n tokenRequest.otp = await promptForOTP(userInteraction, tokenRequest.email, {\n type: 'error',\n messageCode: 'INVALID_OTP',\n message: errorText,\n messageParams: {}\n });\n res2 = await fetch(`${url}/token`, {\n body: JSON.stringify(tokenRequest),\n method: 'post',\n headers: { 'Content-Type': 'application/json' },\n mode: 'cors',\n });\n }\n if (res2.status !== 200) {\n const errMsg = await res2.text();\n await alertUser(userInteraction, \"OTP Authentication Failed\", {\n type: 'error',\n messageCode: 'GENERIC_ERROR',\n message: errMsg,\n messageParams: {}\n }).catch(()=>{});\n throw new HttpError(res2, errMsg);\n }\n const response2: TokenFinalResponse = await res2.json();\n return response2;\n } else {\n throw new Error(`Unexpected response from ${url}/token`);\n }\n };\n}\n","import { DexieCloudDB } from \"../db/DexieCloudDB\";\nimport { AuthPersistedContext } from \"./AuthPersistedContext\";\n\n/** This function changes or sets the current user as requested.\n * \n * Use cases:\n * * Initially on db.ready after reading the current user from db.$logins.\n * This will make sure that any unsynced operations from the previous user is synced before\n * changing the user.\n * * Upon user request\n * \n * @param db \n * @param newUser \n */\nexport async function setCurrentUser(db: DexieCloudDB, user: AuthPersistedContext) {\n if (user.userId === db.cloud.currentUserId) return; // Already this user.\n\n const $logins = db.table('$logins');\n await db.transaction('rw', $logins, async tx => {\n const existingLogins = await $logins.toArray();\n await Promise.all(existingLogins.filter(login => login.userId !== user.userId && login.isLoggedIn).map(login => {\n login.isLoggedIn = false;\n return $logins.put(login);\n }));\n user.isLoggedIn = true;\n user.lastLogin = new Date();\n await user.save();\n console.debug(\"Saved new user\", user.email);\n });\n await new Promise(resolve=>{\n if (db.cloud.currentUserId === user.userId) {\n resolve(null);\n } else {\n const subscription = db.cloud.currentUser.subscribe(currentUser=>{\n if (currentUser.userId === user.userId) {\n subscription.unsubscribe();\n resolve(null);\n }\n });\n }\n });\n\n // TANKAR!!!!\n // V: Service workern kommer inte ha tillgång till currentUserObservable om den inte istället härrör från ett liveQuery.\n // V: Samma med andra windows.\n // V: Så kanske göra om den till att häröra från liveQuery som läser $logins.orderBy('lastLogin').last().\n // V: Då bara vara medveten om:\n // V: En sån observable börjar hämta data vid första subscribe\n // V: Vi har inget \"inital value\" men kan emulera det till att vara ANONYMOUS_USER\n // V: Om requireAuth är true, så borde db.on(ready) hålla databasen stängd för alla utom denna observable.\n // V: Om inte så behöver den inte blocka.\n\n // Andra tankar:\n // * Man kan inte byta användare när man är offline. Skulle gå att flytta realms till undanstuff-tabell vid user-change.\n // men troligen inte värt det.\n // * Istället: sälj inte inte switch-user funktionalitet utan tala enbart om inloggat vs icke inloggat läge.\n // * populate $logins med ANONYMOUS så att en påbörjad inloggning inte räknas, alternativt ha en boolean prop!\n // Kanske bäst ha en boolean prop!\n // * Alternativ switch-user funktionalitet:\n // * DBCore gömmer data från realms man inte har tillgång till.\n // * Cursor impl behövs också då.\n // * Då blir det snabba user switch.\n // * claims-settet som skickas till servern blir summan av alla claims. Då måste servern stödja multipla tokens eller\n // att ens token är ett samlad.\n}\n","import { DexieCloudDB } from '../db/DexieCloudDB';\nimport { triggerSync } from '../sync/triggerSync';\nimport { authenticate } from './authenticate';\nimport { AuthPersistedContext } from './AuthPersistedContext';\nimport { otpFetchTokenCallback } from './otpFetchTokenCallback';\nimport { setCurrentUser } from './setCurrentUser';\n\nexport async function login(\n db: DexieCloudDB,\n hints?: { email?: string; userId?: string; grant_type?: string }\n) {\n const currentUser = await db.getCurrentUser();\n if (currentUser.isLoggedIn) {\n if (hints) {\n if (hints.email && db.cloud.currentUser.value.email !== hints.email) {\n throw new Error(`Must logout before changing user`);\n }\n if (hints.userId && db.cloud.currentUserId !== hints.userId) {\n throw new Error(`Must logout before changing user`);\n }\n }\n // Already authenticated according to given hints.\n return;\n }\n const context = new AuthPersistedContext(db, {\n claims: {},\n lastLogin: new Date(0),\n });\n await authenticate(\n db.cloud.options!.databaseUrl,\n context,\n db.cloud.options!.fetchTokens || otpFetchTokenCallback(db),\n db.cloud.userInteraction,\n hints\n );\n await context.save();\n await setCurrentUser(db, context);\n // Make sure to resync as the new login will be authorized\n // for new realms.\n triggerSync(db, \"pull\");\n}\n","// @ts-ignore\nexport const isFirefox = typeof InstallTrigger !== 'undefined';\n","export const isSafari =\n typeof navigator !== 'undefined' &&\n /Safari\\//.test(navigator.userAgent) &&\n !/Chrom(e|ium)\\/|Edge\\//.test(navigator.userAgent);\n\nexport const safariVersion = isSafari\n ? // @ts-ignore\n [].concat(navigator.userAgent.match(/Safari\\/(\\d*)/))[1]\n : NaN;\n","import { isFirefox } from './isFirefox';\nimport { isSafari, safariVersion } from './isSafari';\n\n// What we know: Safari 14.1 (version 605) crashes when using dexie-cloud's service worker.\n// We don't know what exact call is causing this. Have tried safari-14-idb-fix with no luck.\n// Something we do in the service worker is triggering the crash.\n// When next Safari version (606) is out we will start enabling SW again, hoping that the bug is solved.\n// If not, we might increment 605 to 606.\nexport const DISABLE_SERVICEWORKER_STRATEGY =\n (isSafari && safariVersion <= 605) || // Disable for Safari for now.\n isFirefox; // Disable for Firefox for now. Seems to have a bug in reading CryptoKeys from IDB from service workers\n","import Dexie from \"dexie\";\n\n/* Helper function to subscribe to database close no matter if it was unexpectedly closed or manually using db.close()\n */\nexport function dbOnClosed(db: Dexie, handler: () => void) {\n db.on.close.subscribe(handler);\n const origClose = db.close;\n db.close = function () {\n origClose.call(this);\n handler();\n };\n return () => {\n db.on.close.unsubscribe(handler);\n db.close = origClose;\n };\n}\n","export const IS_SERVICE_WORKER =\n typeof self !== \"undefined\" && \"clients\" in self && !self.document;\n","import Dexie from \"dexie\";\n\nexport function throwVersionIncrementNeeded() {\n throw new Dexie.SchemaError(\n `Version increment needed to allow dexie-cloud change tracking`\n );\n}\n","import Dexie, {\n DBCore,\n DBCoreAddRequest,\n DBCoreDeleteRequest,\n DBCoreIndex,\n DBCoreMutateRequest,\n DBCorePutRequest,\n Middleware\n} from 'dexie';\nimport { isValidSyncableID } from 'dexie-cloud-common';\nimport { b64LexEncode } from 'dreambase-library/dist/common/b64lex';\nimport { DexieCloudDB } from '../db/DexieCloudDB';\n\nconst { toString } = {};\nexport function toStringTag(o: Object) {\n return toString.call(o).slice(8, -1);\n}\n\nexport function getEffectiveKeys(\n primaryKey: DBCoreIndex,\n req:\n | (Pick<DBCoreAddRequest | DBCorePutRequest, 'type' | 'values'> & {\n keys?: any[];\n })\n | Pick<DBCoreDeleteRequest, 'keys' | 'type'>\n) {\n if (req.type === 'delete') return req.keys;\n return req.keys?.slice() || req.values.map(primaryKey.extractKey!);\n}\n\nfunction applyToUpperBitFix(orig: string, bits: number) {\n return (\n (bits & 1 ? orig[0].toUpperCase() : orig[0].toLowerCase()) +\n (bits & 2 ? orig[1].toUpperCase() : orig[1].toLowerCase()) +\n (bits & 4 ? orig[2].toUpperCase() : orig[2].toLowerCase())\n );\n}\n\nconst consonants = /b|c|d|f|g|h|j|k|l|m|n|p|q|r|s|t|v|x|y|z/i;\n\nfunction isUpperCase(ch: string) {\n return ch >= 'A' && ch <= 'Z';\n}\n\nexport function generateTablePrefix(\n tableName: string,\n allPrefixes: Set<string>\n) {\n let rv = tableName[0].toLocaleLowerCase(); // \"users\" = \"usr\", \"friends\" = \"frn\", \"realms\" = \"rlm\", etc.\n for (let i = 1, l = tableName.length; i < l && rv.length < 3; ++i) {\n if (consonants.test(tableName[i]) || isUpperCase(tableName[i]))\n rv += tableName[i].toLowerCase();\n }\n while (allPrefixes.has(rv)) {\n if (/\\d/g.test(rv)) {\n rv = rv.substr(0, rv.length - 1) + (rv[rv.length - 1] + 1);\n if (rv.length > 3) rv = rv.substr(0, 3);\n else continue;\n } else if (rv.length < 3) {\n rv = rv + '2';\n continue;\n }\n let bitFix = 1;\n let upperFixed = rv;\n while (allPrefixes.has(upperFixed) && bitFix < 8) {\n upperFixed = applyToUpperBitFix(rv, bitFix);\n ++bitFix;\n }\n if (bitFix < 8) rv = upperFixed;\n else {\n let nextChar = (rv.charCodeAt(2) + 1) & 127;\n rv = rv.substr(0, 2) + String.fromCharCode(nextChar);\n // Here, in theory we could get an infinite loop if having 127*8 table names with identical 3 first consonants.\n }\n }\n return rv;\n}\n\nlet time = 0;\n/**\n *\n * @param prefix A unique 3-letter short-name of the table.\n * @param shardKey 3 last letters from another ID if colocation is requested. Verified on server on inserts - guarantees unique IDs across shards.\n * The shardKey part of the key represent the shardId where it was first created. An object with this\n * primary key can later on be moved to another shard without being altered. The reason for having\n * the origin shardKey as part of the key, is that the server will not need to check uniqueness constraint\n * across all shards on every insert. Updates / moves across shards are already controlled by the server\n * in the sense that the objects needs to be there already - we only need this part for inserts.\n * @returns\n */\nfunction generateKey(prefix: string, shardKey?: string) {\n const a = new Uint8Array(18);\n const timePart = new Uint8Array(a.buffer, 0, 6);\n const now = Date.now(); // Will fit into 6 bytes until year 10 895.\n if (time >= now) {\n // User is bulk-creating objects the same millisecond.\n // Increment the time part by one millisecond for each item.\n // If bulk-creating 1,000,000 rows client-side in 10 seconds,\n // the last time-stamp will be 990 seconds in future, which is no biggie at all.\n // The point is to create a nice order of the generated IDs instead of\n // using random ids.\n ++time;\n } else {\n time = now;\n }\n timePart[0] = time / 0x1_00_00_00_00_00; // Normal division (no bitwise operator) --> works with >= 32 bits.\n timePart[1] = time / 0x1_00_00_00_00;\n timePart[2] = time / 0x1_00_00_00;\n timePart[3] = time / 0x1_00_00;\n timePart[4] = time / 0x1_00;\n timePart[5] = time;\n const randomPart = new Uint8Array(a.buffer, 6);\n crypto.getRandomValues(randomPart);\n const id = new Uint8Array(a.buffer);\n return prefix + b64LexEncode(id) + (shardKey || '');\n}\n\nexport function createIdGenerationMiddleware(\n db: DexieCloudDB\n): Middleware<DBCore> {\n return {\n stack: 'dbcore',\n name: 'idGenerationMiddleware',\n level: 1,\n create: (core) => {\n return {\n ...core,\n table: (tableName) => {\n const table = core.table(tableName);\n\n function generateOrVerifyAtKeys(req: DBCoreAddRequest | DBCorePutRequest, idPrefix: string) {\n let valueClones: null | object[] = null;\n const keys = getEffectiveKeys(table.schema.primaryKey, req);\n keys.forEach((key, idx) => {\n if (key === undefined) {\n // Generate the key\n const colocatedId =\n req.values[idx].realmId || db.cloud.currentUserId;\n const shardKey = colocatedId.substr(colocatedId.length - 3);\n keys[idx] = generateKey(idPrefix, shardKey);\n if (!table.schema.primaryKey.outbound) {\n if (!valueClones) valueClones = req.values.slice();\n valueClones[idx] = Dexie.deepClone(valueClones[idx]);\n Dexie.setByKeyPath(\n valueClones[idx],\n table.schema.primaryKey.keyPath as any, // TODO: fix typings in dexie-constructor.d.ts!\n keys[idx]\n );\n }\n } else if (\n typeof key !== 'string' ||\n !key.startsWith(idPrefix)\n ) {\n // Key was specified by caller. Verify it complies with id prefix.\n throw new Dexie.ConstraintError(\n `The ID \"${key}\" is not valid for table \"${tableName}\". ` +\n `Primary '@' keys requires the key to be prefixed with \"${idPrefix}.\\n\"` +\n `If you want to generate IDs programmatically, remove '@' from the schema to get rid of this constraint. Dexie Cloud supports custom IDs as long as they are random and globally unique.`\n );\n }\n });\n return table.mutate({\n ...req,\n keys,\n values: valueClones || req.values\n });\n }\n\n return {\n ...table,\n mutate: (req) => {\n // @ts-ignore\n if (req.trans.disableChangeTracking) {\n // Disable ID policy checks and ID generation\n return table.mutate(req);\n }\n if (req.type === 'add' || req.type === 'put') {\n const cloudTableSchema = db.cloud.schema?.[tableName];\n if (!cloudTableSchema?.generatedGlobalId) {\n if (cloudTableSchema?.markedForSync) {\n // Just make sure primary key is of a supported type:\n const keys = getEffectiveKeys(table.schema.primaryKey, req);\n keys.forEach((key, idx) => {\n if (!isValidSyncableID(key)) {\n const type = Array.isArray(key) ? key.map(toStringTag).join(',') : toStringTag(key);\n throw new Dexie.ConstraintError(\n `Invalid primary key type ${type} for table ${tableName}. Tables marked for sync has primary keys of type string or Array of string (and optional numbers)`\n );\n }\n });\n }\n } else {\n if (db.cloud.options?.databaseUrl && !db.initiallySynced) {\n // A database URL is configured but no initial sync has been performed.\n const keys = getEffectiveKeys(table.schema.primaryKey, req);\n // Check if the operation would yield any INSERT. If so, complain! We never want wrong ID prefixes stored.\n return table.getMany({keys, trans: req.trans, cache: \"immutable\"}).then(results => {\n if (results.length < keys.length) {\n // At least one of the given objects would be created. Complain since\n // the generated ID would be based on a locally computed ID prefix only - we wouldn't\n // know if the server would give the same ID prefix until an initial sync has been\n // performed.\n throw new Error(`Unable to create new objects without an initial sync having been performed.`);\n }\n return table.mutate(req);\n });\n }\n return generateOrVerifyAtKeys(req, cloudTableSchema.idPrefix!);\n }\n }\n return table.mutate(req);\n }\n };\n }\n };\n }\n };\n}\n","import { DBCore, DBCoreTransaction, Middleware } from 'dexie';\nimport { DexieCloudDB } from '../db/DexieCloudDB';\nimport { TXExpandos } from '../types/TXExpandos';\n\nexport function createImplicitPropSetterMiddleware(\n db: DexieCloudDB\n): Middleware<DBCore> {\n return {\n stack: 'dbcore',\n name: 'implicitPropSetterMiddleware',\n level: 1,\n create: (core) => {\n return {\n ...core,\n table: (tableName) => {\n const table = core.table(tableName);\n return {\n ...table,\n mutate: (req) => {\n const trans = req.trans as DBCoreTransaction & TXExpandos;\n if (\n db.cloud.schema?.[tableName]?.markedForSync &&\n trans.currentUser?.isLoggedIn\n ) {\n if (req.type === 'add' || req.type === 'put') {\n // If user is logged in, make sure \"owner\" and \"realmId\" props are set properly.\n // If not logged in, this will be set upon syncification of the tables (next sync after login)\n for (const obj of req.values) {\n if (!('owner' in obj)) {\n obj.owner = trans.currentUser.userId;\n }\n if (!('realmId' in obj)) {\n obj.realmId = trans.currentUser.userId;\n }\n }\n }\n }\n return table.mutate(req);\n }\n };\n }\n };\n }\n };\n}\n","export function randomString(bytes: number) {\n const buf = new Uint8Array(bytes);\n crypto.getRandomValues(buf);\n return btoa(String.fromCharCode.apply(null, buf));\n}","\nexport function allSettled(possiblePromises: any[]) {\n return new Promise(resolve => {\n if (possiblePromises.length === 0) resolve([]);\n let remaining = possiblePromises.length;\n const results = new Array(remaining);\n possiblePromises.forEach((p, i) => Promise.resolve(p).then(\n value => results[i] = {status: \"fulfilled\", value},\n reason => results[i] = {status: \"rejected\", reason})\n .then(()=>--remaining || resolve(results)));\n });\n}\n","import { DBCoreTable, DBCoreTransaction } from \"dexie\";\nimport { allSettled } from \"../helpers/allSettled\";\n\nlet counter = 0;\n\nexport function guardedTable(table: DBCoreTable) {\n const prop = \"$lock\"+ (++counter);\n return {\n ...table,\n count: readLock(table.count, prop),\n get: readLock(table.get, prop),\n getMany: readLock(table.getMany, prop),\n openCursor: readLock(table.openCursor, prop),\n query: readLock(table.query, prop),\n mutate: writeLock(table.mutate, prop),\n };\n}\n\nfunction readLock<TReq extends { trans: DBCoreTransaction }, TRes>(\n fn: (req: TReq) => Promise<TRes>,\n prop: string\n): (req: TReq) => Promise<TRes> {\n return function readLocker(req): Promise<TRes> {\n const {\n readers,\n writers,\n }: { writers: Promise<any>[]; readers: Promise<any>[] } =\n req.trans[prop] || (req.trans[prop] = { writers: [], readers: [] });\n const numWriters = writers.length;\n const promise = (numWriters > 0\n ? writers[numWriters - 1].then(() => fn(req), () => fn(req))\n : fn(req)\n ).finally(() => readers.splice(readers.indexOf(promise)));\n readers.push(promise);\n return promise;\n };\n}\n\nfunction writeLock<TReq extends { trans: DBCoreTransaction }, TRes>(\n fn: (req: TReq) => Promise<TRes>,\n prop: string\n): (req: TReq) => Promise<TRes> {\n return function writeLocker(req): Promise<TRes> {\n const {\n readers,\n writers,\n }: { writers: Promise<any>[]; readers: Promise<any>[] } =\n req.trans[prop] || (req.trans[prop] = { writers: [], readers: [] });\n let promise = (writers.length > 0\n ? writers[writers.length - 1].then(() => fn(req), () => fn(req))\n : readers.length > 0\n ? allSettled(readers).then(() => fn(req))\n : fn(req)\n ).finally(() => writers.shift());\n writers.push(promise);\n return promise;\n };\n}\n","import { DBCoreTransaction } from 'dexie';\nimport { BehaviorSubject } from 'rxjs';\nimport { TXExpandos } from '../types/TXExpandos';\n\nexport const outstandingTransactions = new BehaviorSubject<Set<DBCoreTransaction & IDBTransaction & TXExpandos>>(new Set());\n","import {\n DBCore,\n DBCoreAddRequest,\n DBCoreDeleteRequest,\n DBCoreMutateResponse,\n DBCorePutRequest,\n DBCoreTable,\n DBCoreTransaction,\n Middleware\n} from 'dexie';\nimport { DBOperation } from 'dexie-cloud-common';\nimport { BehaviorSubject } from 'rxjs';\nimport { DexieCloudDB } from '../db/DexieCloudDB';\nimport { UserLogin } from '../db/entities/UserLogin';\nimport { getMutationTable } from '../helpers/getMutationTable';\nimport { randomString } from '../helpers/randomString';\nimport { throwVersionIncrementNeeded } from '../helpers/throwVersionIncrementNeeded';\nimport { guardedTable } from '../middleware-helpers/guardedTable';\nimport { registerSyncEvent } from '../sync/registerSyncEvent';\nimport { TXExpandos } from '../types/TXExpandos';\nimport { outstandingTransactions } from './outstandingTransaction';\n\nexport interface MutationTrackingMiddlewareArgs {\n currentUserObservable: BehaviorSubject<UserLogin>;\n db: DexieCloudDB;\n}\n\n/** Tracks all mutations in the same transaction as the mutations -\n * so it is guaranteed that no mutation goes untracked - and if transaction\n * aborts, the mutations won't be tracked.\n *\n * The sync job will use the tracked mutations as the source of truth when pushing\n * changes to server and cleanup the tracked mutations once the server has\n * ackowledged that it got them.\n */\nexport function createMutationTrackingMiddleware({\n currentUserObservable,\n db\n}: MutationTrackingMiddlewareArgs): Middleware<DBCore> {\n return {\n stack: 'dbcore',\n name: 'MutationTrackingMiddleware',\n level: 1,\n create: (core) => {\n const ordinaryTables = core.schema.tables.filter(\n (t) => !/^\\$/.test(t.name)\n );\n let mutTableMap: Map<string, DBCoreTable>;\n try {\n mutTableMap = new Map(\n ordinaryTables.map((tbl) => [\n tbl.name,\n core.table(`$${tbl.name}_mutations`)\n ])\n );\n } catch {\n throwVersionIncrementNeeded();\n }\n\n return {\n ...core,\n transaction: (tables, mode) => {\n let tx: DBCoreTransaction & IDBTransaction & TXExpandos;\n if (mode === 'readwrite') {\n const mutationTables = tables\n .filter((tbl) => db.cloud.schema?.[tbl]?.markedForSync)\n .map((tbl) => getMutationTable(tbl));\n tx = core.transaction(\n [...tables, ...mutationTables],\n mode\n ) as DBCoreTransaction & IDBTransaction & TXExpandos;\n } else {\n tx = core.transaction(tables, mode) as DBCoreTransaction &\n IDBTransaction &\n TXExpandos;\n }\n\n if (mode === 'readwrite') {\n // Give each transaction a globally unique id.\n tx.txid = randomString(16);\n // Introduce the concept of current user that lasts through the entire transaction.\n // This is important because the tracked mutations must be connected to the user.\n tx.currentUser = currentUserObservable.value;\n outstandingTransactions.value.add(tx);\n outstandingTransactions.next(outstandingTransactions.value);\n const removeTransaction = () => {\n tx.removeEventListener('complete', txComplete);\n tx.removeEventListener('error', removeTransaction);\n tx.removeEventListener('abort', removeTransaction);\n outstandingTransactions.value.delete(tx);\n outstandingTransactions.next(outstandingTransactions.value);\n };\n const txComplete = () => {\n if (tx.mutationsAdded && db.cloud.options?.databaseUrl) {\n if (db.cloud.usingServiceWorker) {\n console.debug('registering sync event');\n registerSyncEvent(db, \"push\");\n } else {\n db.localSyncEvent.next({purpose: \"push\"});\n }\n }\n removeTransaction();\n };\n tx.addEventListener('complete', txComplete);\n tx.addEventListener('error', removeTransaction);\n tx.addEventListener('abort', removeTransaction);\n }\n return tx;\n },\n table: (tableName) => {\n const table = core.table(tableName);\n if (/^\\$/.test(tableName)) {\n if (tableName.endsWith('_mutations')) {\n // In case application code adds items to ..._mutations tables,\n // make sure to set the mutationsAdded flag on transaction.\n // This is also done in mutateAndLog() as that function talks to a\n // lower level DBCore and wouldn't be catched by this code.\n return {\n ...table,\n mutate: (req) => {\n if (req.type === 'add' || req.type === 'put') {\n (\n req.trans as DBCoreTransaction & TXExpandos\n ).mutationsAdded = true;\n }\n return table.mutate(req);\n }\n };\n } else if (tableName === '$logins') {\n return {\n ...table,\n mutate: (req) => {\n console.debug('Mutating $logins table', req);\n return table\n .mutate(req)\n .then((res) => {\n console.debug('Mutating $logins');\n (\n req.trans as DBCoreTransaction & TXExpandos\n ).mutationsAdded = true;\n console.debug('$logins mutated');\n return res;\n })\n .catch((err) => {\n console.debug('Failed mutation $logins', err);\n return Promise.reject(err);\n });\n }\n };\n } else {\n return table;\n }\n }\n const { schema } = table;\n const mutsTable = mutTableMap.get(tableName)!;\n return guardedTable({\n ...table,\n mutate: (req) => {\n const trans = req.trans as DBCoreTransaction & TXExpandos;\n if (!trans.txid) return table.mutate(req); // Upgrade transactions not guarded by us.\n if (trans.disableChangeTracking) return table.mutate(req);\n if (!trans.currentUser?.isLoggedIn) {\n // Unauthorized user should not log mutations.\n // Instead, after login all local data should be logged at once.\n return table.mutate(req);\n }\n\n return req.type === 'deleteRange'\n ? table\n // Query the actual keys (needed for server sending correct rollback to us)\n .query({\n query: { range: req.range, index: schema.primaryKey },\n trans: req.trans,\n values: false\n })\n // Do a delete request instead, but keep the criteria info for the server to execute\n .then((res) => {\n return mutateAndLog({\n type: 'delete',\n keys: res.result,\n trans: req.trans,\n criteria: { index: null, range: req.range }\n });\n })\n : mutateAndLog(req);\n }\n });\n\n function mutateAndLog(\n req: DBCoreDeleteRequest | DBCoreAddRequest | DBCorePutRequest\n ): Promise<DBCoreMutateResponse> {\n const trans = req.trans as DBCoreTransaction & TXExpandos;\n trans.mutationsAdded = true;\n const {\n txid,\n currentUser: { userId }\n } = trans;\n const { type } = req;\n\n return table.mutate(req).then((res) => {\n const { numFailures: hasFailures, failures } = res;\n let keys = type === 'delete' ? req.keys! : res.results!;\n let values = 'values' in req ? req.values : [];\n let changeSpecs = 'changeSpecs' in req ? req.changeSpecs! : [];\n if (hasFailures) {\n keys = keys.filter((_, idx) => !failures[idx]);\n values = values.filter((_, idx) => !failures[idx]);\n changeSpecs = changeSpecs.filter((_, idx) => !failures[idx]);\n }\n const ts = Date.now();\n\n const mut: DBOperation =\n req.type === 'delete'\n ? {\n type: 'delete',\n ts,\n keys,\n criteria: req.criteria,\n txid,\n userId\n }\n : req.type === 'add'\n ? {\n type: 'insert',\n ts,\n keys,\n txid,\n userId,\n values\n }\n : req.criteria && req.changeSpec\n ? {\n // Common changeSpec for all keys\n type: 'modify',\n ts,\n keys,\n criteria: req.criteria,\n changeSpec: req.changeSpec,\n txid,\n userId\n }\n : req.changeSpecs\n ? {\n // One changeSpec per key\n type: 'update',\n ts,\n keys,\n changeSpecs,\n txid,\n userId\n }\n : {\n type: 'upsert',\n ts,\n keys,\n values,\n txid,\n userId\n };\n return keys.length > 0 || ('criteria' in req && req.criteria)\n ? mutsTable\n .mutate({ type: 'add', trans, values: [mut] }) // Log entry\n .then(() => res) // Return original response\n : res;\n });\n }\n }\n };\n }\n };\n}\n","import Dexie, { DbSchema } from 'dexie';\nimport { DEXIE_CLOUD_SCHEMA } from './db/DexieCloudDB';\nimport { generateTablePrefix } from './middlewares/createIdGenerationMiddleware';\n\nexport function overrideParseStoresSpec(origFunc: Function, dexie: Dexie) {\n return function(stores: {[tableName: string]: string}, dbSchema: DbSchema) {\n const storesClone = {\n ...DEXIE_CLOUD_SCHEMA,\n ...stores,\n };\n const cloudSchema = dexie.cloud.schema || (dexie.cloud.schema = {});\n const allPrefixes = new Set<string>();\n Object.keys(storesClone).forEach(tableName => {\n const schemaSrc = storesClone[tableName];\n const cloudTableSchema = cloudSchema[tableName] || (cloudSchema[tableName] = {});\n if (schemaSrc != null) {\n if (/^\\@/.test(schemaSrc)) {\n storesClone[tableName] = storesClone[tableName].substr(1);\n cloudTableSchema.generatedGlobalId = true;\n cloudTableSchema.idPrefix = generateTablePrefix(tableName, allPrefixes);\n allPrefixes.add(cloudTableSchema.idPrefix);\n }\n if (!/^\\$/.test(tableName)) {\n storesClone[`$${tableName}_mutations`] = '++rev';\n cloudTableSchema.markedForSync = true;\n }\n if (cloudTableSchema.deleted) {\n cloudTableSchema.deleted = false;\n }\n } else {\n cloudTableSchema.deleted = true;\n cloudTableSchema.markedForSync = false;\n storesClone[`$${tableName}_mutations`] = null;\n }\n });\n const rv = origFunc.call(this, storesClone, dbSchema);\n return rv;\n }\n}\n","export const SECONDS = 1000;\nexport const MINUTES = 60 * SECONDS;\nexport const HOURS = 60 * MINUTES;\nexport const DAYS = 24 * HOURS;\nexport const WEEKS = 7 * DAYS;\n","import { randomString } from \"../helpers/randomString\";\n\nexport const myId = randomString(16);\n","import { liveQuery, Table } from 'dexie';\nimport { MINUTES, SECONDS } from '../helpers/date-constants';\nimport { DexieCloudDB } from '../db/DexieCloudDB';\nimport { GuardedJob } from '../db/entities/GuardedJob';\nimport { myId } from './myId';\nimport { from } from 'rxjs';\nimport { filter, timeout } from 'rxjs/operators';\n\nconst GUARDED_JOB_HEARTBEAT = 1 * SECONDS;\nconst GUARDED_JOB_TIMEOUT = 1 * MINUTES;\n\nexport async function performGuardedJob(\n db: DexieCloudDB,\n jobName: string,\n jobsTableName: string,\n job: () => Promise<any>,\n { awaitRemoteJob }: { awaitRemoteJob?: boolean } = {}\n): Promise<void> {\n // Start working.\n //\n // Check if someone else is working on this already.\n //\n const jobsTable = db.table(jobsTableName) as Table<GuardedJob, string>;\n\n async function aquireLock() {\n const gotTheLock = await db.transaction('rw!', jobsTableName, async () => {\n const currentWork = await jobsTable.get(jobName);\n if (!currentWork) {\n // No one else is working. Let's record that we are.\n await jobsTable.add(\n {\n nodeId: myId,\n started: new Date(),\n heartbeat: new Date()\n },\n jobName\n );\n return true;\n } else if (\n currentWork.heartbeat.getTime() <\n Date.now() - GUARDED_JOB_TIMEOUT\n ) {\n console.warn(\n `Latest ${jobName} worker seem to have died.\\n`,\n `The dead job started:`,\n currentWork.started,\n `\\n`,\n `Last heart beat was:`,\n currentWork.heartbeat,\n '\\n',\n `We're now taking over!`\n );\n // Now, take over!\n await jobsTable.put(\n {\n nodeId: myId,\n started: new Date(),\n heartbeat: new Date()\n },\n jobName\n );\n return true;\n }\n return false;\n });\n\n if (gotTheLock) return true;\n\n // Someone else took the job.\n if (awaitRemoteJob) {\n try {\n const jobDoneObservable = from(\n liveQuery(() => jobsTable.get(jobName))\n ).pipe(\n timeout(GUARDED_JOB_TIMEOUT),\n filter((job) => !job)\n ); // Wait til job is not there anymore.\n await jobDoneObservable.toPromise();\n return false;\n } catch (err) {\n if (err.name !== 'TimeoutError') {\n throw err;\n }\n // Timeout stopped us! Try aquire the lock now.\n // It will likely succeed this time unless\n // another client took it.\n return await aquireLock();\n }\n }\n return false;\n }\n\n if (await aquireLock()) {\n // We own the lock entry and can do our job undisturbed.\n // We're not within a transaction, but these type of locks\n // spans over transactions.\n\n // Start our heart beat during the job.\n // Use setInterval to make sure we are updating heartbeat even during long-lived fetch calls.\n const heartbeat = setInterval(() => {\n jobsTable.update(\n jobName,\n (job: GuardedJob) => job.nodeId === myId && (job.heartbeat = new Date())\n );\n }, GUARDED_JOB_HEARTBEAT);\n\n try {\n return await job();\n } finally {\n // Stop heartbeat\n clearInterval(heartbeat);\n // Remove the persisted job state:\n await db.transaction('rw!', jobsTableName, async () => {\n const currentWork = await jobsTable.get(jobName);\n if (currentWork && currentWork.nodeId === myId) {\n jobsTable.delete(jobName);\n }\n });\n }\n }\n}\n","import { DexieCloudSchema } from 'dexie-cloud-common';\nimport { DexieCloudDB } from './db/DexieCloudDB';\nimport { DexieCloudOptions } from './DexieCloudOptions';\nimport { performGuardedJob } from './sync/performGuardedJob';\nimport { sync } from './sync/sync';\n\nexport async function performInitialSync(\n db: DexieCloudDB,\n cloudOptions: DexieCloudOptions,\n cloudSchema: DexieCloudSchema\n) {\n console.debug(\"Performing initial sync\");\n await performGuardedJob(\n db,\n 'initialSync',\n '$jobs',\n async () => {\n // Even though caller has already checked it,\n // Do check again (now within a transaction) that we really do not have a sync state:\n const syncState = await db.getPersistedSyncState();\n if (!syncState?.initiallySynced) {\n await sync(db, cloudOptions, cloudSchema, {isInitialSync: true});\n }\n },\n { awaitRemoteJob: true } // Don't return until the job is done!\n );\n console.debug(\"Done initial sync\");\n}\n","import { BehaviorSubject, fromEvent, merge, of } from 'rxjs';\nimport {\n debounceTime,\n delay,\n distinctUntilChanged,\n filter,\n map,\n skip,\n startWith,\n switchMap,\n tap,\n} from 'rxjs/operators';\n\nconst USER_INACTIVITY_TIMEOUT = 300_000; // 300_000;\nconst ACTIVE_WAIT_TIME = 0; // For now, it's nicer to react instantly on user activity\nconst INACTIVE_WAIT_TIME = 20_000;\n\n// This observable will be emitted to later down....\nexport const userIsActive = new BehaviorSubject<boolean>(true);\n\n// A refined version that waits before changing state:\n// * Wait another INACTIVE_WAIT_TIME before accepting that the user is inactive.\n// Reason 1: Spare resources - no need to setup the entire websocket flow when\n// switching tabs back and forth.\n// Reason 2: Less flickering for the end user when switching tabs back and forth.\n// * Wait another ACTIVE_WAIT_TIME before accepting that the user is active.\n// Possible reason to have a value here: Sparing resources if users often temporary click the tab\n// for just a short time.\nexport const userIsReallyActive = new BehaviorSubject<boolean>(true);\nuserIsActive\n .pipe(\n switchMap((isActive) =>\n isActive\n ? ACTIVE_WAIT_TIME\n ? of(true).pipe(delay(ACTIVE_WAIT_TIME))\n : of(true)\n : of(false).pipe(delay(INACTIVE_WAIT_TIME))\n ),\n distinctUntilChanged()\n )\n .subscribe(userIsReallyActive);\n\n//\n// First create some corner-stone observables to build the flow on\n//\n\n// document.onvisibilitychange:\nexport const visibilityStateIsChanged =\n typeof document !== 'undefined'\n ? fromEvent(document, 'visibilitychange')\n : of({});\n\n// document.onvisibilitychange makes document hidden:\nexport const documentBecomesHidden = visibilityStateIsChanged.pipe(\n filter(() => document.visibilityState === 'hidden')\n);\n\n// document.onvisibilitychange makes document visible\nexport const documentBecomesVisible = visibilityStateIsChanged.pipe(\n filter(() => document.visibilityState === 'visible')\n);\n\n// Any of various user-activity-related events happen:\nexport const userDoesSomething =\n typeof window !== 'undefined'\n ? merge(\n documentBecomesVisible,\n fromEvent(window, 'mousemove'),\n fromEvent(window, 'keydown'),\n fromEvent(window, 'wheel'),\n fromEvent(window, 'touchmove')\n )\n : of({});\n\nif (typeof document !== 'undefined') {\n //\n // Now, create a final observable and start subscribing to it in order\n // to make it emit values to userIsActive BehaviourSubject (which is the\n // most important global hot observable we have here)\n //\n // Live test: https://jsitor.com/LboCDHgbn\n //\n merge(\n of(true), // Make sure something is always emitted from start\n documentBecomesHidden, // so that we can eagerly emit false!\n userDoesSomething\n )\n .pipe(\n // No matter event source, compute whether user is visible using visibilityState:\n map(() => document.visibilityState === 'visible'),\n // Make sure to emit it\n tap((isActive) => {\n if (userIsActive.value !== isActive) {\n // Emit new value unless it already has that value\n userIsActive.next(isActive);\n }\n }),\n // Now, if true was emitted, make sure to set a timeout to emit false\n // unless new user activity things happen (in that case, the timeout will be cancelled!)\n switchMap((isActive) =>\n isActive\n ? of(0).pipe(\n delay(USER_INACTIVITY_TIMEOUT - INACTIVE_WAIT_TIME),\n tap(() => userIsActive.next(false))\n )\n : of(0)\n )\n )\n .subscribe(() => {}); // Unless we subscribe nothing will be propagated to userIsActive observable\n}\n","export class TokenExpiredError extends Error {\n name = \"TokenExpiredError\";\n}\n","import { DBOperationsSet } from 'dexie-cloud-common';\nimport { BehaviorSubject, Observable, Subscriber, Subscription } from 'rxjs';\nimport { TokenExpiredError } from './authentication/TokenExpiredError';\nimport { DXCWebSocketStatus } from './DXCWebSocketStatus';\nimport { TSON } from './TSON';\n\nconst SERVER_PING_TIMEOUT = 20000;\nconst CLIENT_PING_INTERVAL = 30000;\nconst FAIL_RETRY_WAIT_TIME = 60000;\n\nexport type WSClientToServerMsg = ReadyForChangesMessage;\nexport interface ReadyForChangesMessage {\n type: 'ready';\n rev: bigint;\n}\n\nexport type WSConnectionMsg =\n | RevisionChangedMessage\n | RealmAddedMessage\n | RealmRemovedMessage\n | ChangesFromServerMessage\n | TokenExpiredMessage;\ninterface PingMessage {\n type: 'ping';\n}\n\ninterface PongMessage {\n type: 'pong';\n}\n\ninterface ErrorMessage {\n type: 'error';\n error: string;\n}\n\nexport interface ChangesFromServerMessage {\n type: 'changes';\n baseRev: bigint;\n realmSetHash: string;\n newRev: bigint;\n changes: DBOperationsSet;\n}\nexport interface RevisionChangedMessage {\n type: 'rev';\n rev: string;\n}\n\nexport interface RealmAddedMessage {\n type: 'realm-added';\n realm: string;\n}\n\nexport interface RealmRemovedMessage {\n type: 'realm-removed';\n realm: string;\n}\nexport interface TokenExpiredMessage {\n type: 'token-expired';\n}\n\nexport class WSObservable extends Observable<WSConnectionMsg> {\n constructor(\n databaseUrl: string,\n rev: string,\n clientIdentity: string,\n messageProducer: Observable<WSClientToServerMsg>,\n webSocketStatus: BehaviorSubject<DXCWebSocketStatus>,\n token?: string,\n tokenExpiration?: Date,\n ) {\n super(\n (subscriber) =>\n new WSConnection(\n databaseUrl,\n rev,\n clientIdentity,\n token,\n tokenExpiration,\n subscriber,\n messageProducer,\n webSocketStatus\n )\n );\n }\n}\n\nlet counter = 0;\n\nexport class WSConnection extends Subscription {\n ws: WebSocket | null;\n lastServerActivity: Date;\n lastUserActivity: Date;\n lastPing: Date;\n databaseUrl: string;\n rev: string;\n clientIdentity: string;\n token: string | undefined;\n tokenExpiration: Date | undefined;\n subscriber: Subscriber<WSConnectionMsg>;\n pauseUntil?: Date;\n messageProducer: Observable<WSClientToServerMsg>;\n webSocketStatus: BehaviorSubject<DXCWebSocketStatus>;\n id = ++counter;\n\n private pinger: any;\n private messageProducerSubscription: null | Subscription;\n\n constructor(\n databaseUrl: string,\n rev: string,\n clientIdentity: string,\n token: string | undefined,\n tokenExpiration: Date | undefined,\n subscriber: Subscriber<WSConnectionMsg>,\n messageProducer: Observable<WSClientToServerMsg>,\n webSocketStatus: BehaviorSubject<DXCWebSocketStatus>\n ) {\n super(() => this.teardown());\n console.debug(\n 'New WebSocket Connection',\n this.id,\n token ? 'authorized' : 'unauthorized'\n );\n this.databaseUrl = databaseUrl;\n this.rev = rev;\n this.clientIdentity = clientIdentity;\n this.token = token;\n this.tokenExpiration = tokenExpiration;\n this.subscriber = subscriber;\n this.lastUserActivity = new Date();\n this.messageProducer = messageProducer;\n this.messageProducerSubscription = null;\n this.webSocketStatus = webSocketStatus;\n this.connect();\n }\n\n private teardown() {\n console.debug('Teardown WebSocket Connection', this.id);\n this.disconnect();\n }\n\n private disconnect() {\n this.webSocketStatus.next(\"disconnected\");\n if (this.pinger) {\n clearInterval(this.pinger);\n this.pinger = null;\n }\n if (this.ws) {\n try {\n this.ws.close();\n } catch {}\n }\n this.ws = null;\n if (this.messageProducerSubscription) {\n this.messageProducerSubscription.unsubscribe();\n this.messageProducerSubscription = null;\n }\n }\n\n reconnect() {\n this.disconnect();\n this.connect();\n }\n\n async connect() {\n this.webSocketStatus.next(\"connecting\");\n this.lastServerActivity = new Date();\n if (this.pauseUntil && this.pauseUntil > new Date()) {\n console.debug('WS not reconnecting just yet', {\n id: this.id,\n pauseUntil: this.pauseUntil,\n });\n return;\n }\n if (this.ws) {\n throw new Error(`Called connect() when a connection is already open`);\n }\n if (!this.databaseUrl)\n throw new Error(`Cannot connect without a database URL`);\n if (this.closed) {\n return;\n }\n if (this.tokenExpiration && this.tokenExpiration < new Date()) {\n this.subscriber.error(new TokenExpiredError()); // Will be handled in connectWebSocket.ts.\n return;\n }\n this.pinger = setInterval(async () => {\n if (this.closed) {\n console.debug('pinger check', this.id, 'CLOSED.');\n this.teardown();\n return;\n }\n if (this.ws) {\n try {\n this.ws.send(JSON.stringify({ type: 'ping' } as PingMessage));\n setTimeout(() => {\n console.debug(\n 'pinger setTimeout',\n this.id,\n this.pinger ? `alive` : 'dead'\n );\n if (!this.pinger) return;\n if (this.closed) {\n console.debug(\n 'pinger setTimeout',\n this.id,\n 'subscription is closed'\n );\n this.teardown();\n return;\n }\n if (\n this.lastServerActivity <\n new Date(Date.now() - SERVER_PING_TIMEOUT)\n ) {\n // Server inactive. Reconnect if user is active.\n console.debug('pinger: server is inactive');\n console.debug('pinger reconnecting');\n this.reconnect();\n } else {\n console.debug('pinger: server still active');\n }\n }, SERVER_PING_TIMEOUT);\n } catch {\n console.debug('pinger catch error', this.id, 'reconnecting');\n this.reconnect();\n }\n } else {\n console.debug('pinger', this.id, 'reconnecting');\n this.reconnect();\n }\n }, CLIENT_PING_INTERVAL);\n\n // The following vars are needed because we must know which callback to ack when server sends it's ack to us.\n const wsUrl = new URL(this.databaseUrl);\n wsUrl.protocol = wsUrl.protocol === 'http:' ? 'ws' : 'wss';\n const searchParams = new URLSearchParams();\n if (this.subscriber.closed) return;\n searchParams.set('rev', this.rev);\n searchParams.set('clientId', this.clientIdentity);\n if (this.token) {\n searchParams.set('token', this.token);\n }\n\n // Connect the WebSocket to given url:\n console.debug('dexie-cloud WebSocket create');\n const ws = (this.ws = new WebSocket(`${wsUrl}/changes?${searchParams}`));\n //ws.binaryType = \"arraybuffer\"; // For future when subscribing to actual changes.\n\n ws.onclose = (event: Event) => {\n if (!this.pinger) return;\n console.debug('dexie-cloud WebSocket onclosed', this.id);\n this.reconnect();\n };\n\n ws.onmessage = (event: MessageEvent) => {\n if (!this.pinger) return;\n console.debug('dexie-cloud WebSocket onmessage', event.data);\n\n this.lastServerActivity = new Date();\n try {\n const msg = TSON.parse(event.data) as\n | WSConnectionMsg\n | PongMessage\n | ErrorMessage;\n if (msg.type === 'error') {\n throw new Error(`Error message from dexie-cloud: ${msg.error}`);\n }\n if (msg.type === 'rev') {\n this.rev = msg.rev; // No meaning but seems reasonable.\n }\n if (msg.type !== 'pong') {\n this.subscriber.next(msg);\n }\n } catch (e) {\n this.subscriber.error(e);\n }\n };\n\n try {\n await new Promise((resolve, reject) => {\n ws.onopen = (event) => {\n console.debug('dexie-cloud WebSocket onopen');\n resolve(null);\n };\n ws.onerror = (event: ErrorEvent) => {\n const error = event.error || new Error('WebSocket Error');\n this.disconnect();\n this.subscriber.error(error);\n this.webSocketStatus.next(\"error\");\n reject(error);\n };\n });\n this.messageProducerSubscription = this.messageProducer.subscribe(msg => {\n if (!this.closed) {\n if (msg.type === 'ready' && this.webSocketStatus.value !== 'connected') {\n this.webSocketStatus.next(\"connected\");\n }\n this.ws?.send(TSON.stringify(msg));\n }\n });\n } catch (error) {\n this.pauseUntil = new Date(Date.now() + FAIL_RETRY_WAIT_TIME);\n }\n }\n}\n","import { BehaviorSubject, from, Observable, of, throwError } from 'rxjs';\nimport {\n catchError,\n debounceTime,\n delay,\n distinctUntilChanged,\n filter,\n map,\n switchMap,\n take,\n tap,\n} from 'rxjs/operators';\nimport { refreshAccessToken } from '../authentication/authenticate';\nimport { DexieCloudDB } from '../db/DexieCloudDB';\nimport { PersistedSyncState } from '../db/entities/PersistedSyncState';\nimport {\n userDoesSomething,\n userIsActive,\n userIsReallyActive,\n} from '../userIsActive';\nimport {\n ReadyForChangesMessage,\n WSConnectionMsg,\n WSObservable,\n} from '../WSObservable';\n\nfunction sleep(ms: number) {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n\nasync function waitAndReconnectWhenUserDoesSomething(error: Error) {\n console.error(\n `WebSocket observable: error but revive when user does some active thing...`,\n error\n );\n // Sleep some seconds...\n await sleep(3000);\n // Wait til user does something (move mouse, tap, scroll, click etc)\n console.debug('waiting for someone to do something');\n await userDoesSomething.pipe(take(1)).toPromise();\n console.debug('someone did something!');\n}\n\nexport function connectWebSocket(db: DexieCloudDB) {\n if (!db.cloud.options?.databaseUrl) {\n throw new Error(`No database URL to connect WebSocket to`);\n }\n\n const messageProducer = db.messageConsumer.readyToServe.pipe(\n filter((isReady) => isReady), // When consumer is ready for new messages, produce such a message to inform server about it\n switchMap(() => db.getPersistedSyncState()), // We need the info on which server revision we are at:\n filter((syncState) => syncState && syncState.serverRevision), // We wont send anything to server before inital sync has taken place\n map<PersistedSyncState, ReadyForChangesMessage>((syncState) => ({\n // Produce the message to trigger server to send us new messages to consume:\n type: 'ready',\n rev: syncState.serverRevision,\n }))\n );\n\n function createObservable(): Observable<WSConnectionMsg | null> {\n return db.cloud.persistedSyncState.pipe(\n filter(syncState => syncState?.serverRevision),// Don't connect before there's no initial sync performed.\n take(1), // Don't continue waking up whenever syncState change\n switchMap(()=> db.cloud.currentUser),\n switchMap((userLogin) =>\n userIsReallyActive.pipe(\n map((isActive) => (isActive ? userLogin : null))\n )\n ),\n switchMap((userLogin) =>\n // Let server end query changes from last entry of same client-ID and forward.\n // If no new entries, server won't bother the client. If new entries, server sends only those\n // and the baseRev of the last from same client-ID.\n userLogin\n ? new WSObservable(\n db.cloud.options!.databaseUrl,\n db.cloud.persistedSyncState!.value!.serverRevision,\n db.cloud.persistedSyncState!.value!.clientIdentity,\n messageProducer,\n db.cloud.webSocketStatus,\n userLogin.accessToken,\n userLogin.accessTokenExpiration\n )\n : from([] as WSConnectionMsg[])\n ),\n catchError((error) => {\n if (error?.name === 'TokenExpiredError') {\n console.debug(\n 'WebSocket observable: Token expired. Refreshing token...'\n );\n return of(true).pipe(\n switchMap(async () => {\n // Refresh access token\n const user = await db.getCurrentUser();\n const refreshedLogin = await refreshAccessToken(\n db.cloud.options!.databaseUrl,\n user\n );\n // Persist updated access token\n await db.table('$logins').update(user.userId, {\n accessToken: refreshedLogin.accessToken,\n accessTokenExpiration: refreshedLogin.accessTokenExpiration,\n });\n }),\n switchMap(() => createObservable())\n );\n } else {\n return throwError(error);\n }\n }),\n catchError((error) =>\n from(waitAndReconnectWhenUserDoesSomething(error)).pipe(\n switchMap(() => createObservable())\n )\n )\n );\n }\n\n return createObservable().subscribe(\n (msg) => {\n if (msg) {\n console.debug('WS got message', msg);\n db.messageConsumer.enqueue(msg);\n }\n },\n (error) => {\n console.error('Oops! The main observable errored!', error);\n },\n () => {\n console.error('Oops! The main observable completed!');\n }\n );\n}\n","import { DexieCloudDB } from \"../db/DexieCloudDB\";\nimport { sync } from \"./sync\";\n\nexport async function isSyncNeeded(db: DexieCloudDB) {\n return db.cloud.options?.databaseUrl && db.cloud.schema\n ? await sync(db, db.cloud.options, db.cloud.schema, {justCheckIfNeeded: true})\n : false;\n}\n","import { IS_SERVICE_WORKER } from '../helpers/IS_SERVICE_WORKER';\nimport { performGuardedJob } from './performGuardedJob';\nimport { DexieCloudDB } from '../db/DexieCloudDB';\nimport { sync, CURRENT_SYNC_WORKER, SyncOptions } from './sync';\nimport { DexieCloudOptions } from '../DexieCloudOptions';\nimport { DexieCloudSchema } from 'dexie-cloud-common';\nimport { compareBigInts } from '../TSON';\n\nconst ongoingSyncs = new WeakMap<\n DexieCloudDB,\n { promise: Promise<void>; pull: boolean }\n>();\n\nexport function syncIfPossible(\n db: DexieCloudDB,\n cloudOptions: DexieCloudOptions,\n cloudSchema: DexieCloudSchema,\n options?: SyncOptions\n) {\n const ongoing = ongoingSyncs.get(db);\n if (ongoing) {\n if (ongoing.pull || options?.purpose === 'push') {\n console.debug('syncIfPossible(): returning the ongoing sync promise.');\n return ongoing.promise;\n } else {\n // Ongoing sync may never do anything in case there are no outstanding changes\n // to sync (because its purpose was \"push\" not \"pull\")\n // Now, however, we are asked to do a sync with the purpose of \"pull\"\n // We want to optimize here. We must wait for the ongoing to complete\n // and then, if the ongoing sync never resulted in a sync request,\n // we must redo the sync.\n\n // To inspect what is happening in the ongoing request, let's subscribe\n // to db.cloud.syncState and look for if it is doing any \"pulling\" phase:\n let hasPullTakenPlace = false;\n const subscription = db.cloud.syncState.subscribe((syncState) => {\n if (syncState.phase === 'pulling') {\n hasPullTakenPlace = true;\n }\n });\n // Ok, so now we are watching. At the same time, wait for the ongoing to complete\n // and when it has completed, check if we're all set or if we need to redo\n // the call:\n return (\n ongoing.promise\n // This is a finally block but we are still running tests on\n // browsers that don't support it, so need to do it like this:\n .then(() => {\n subscription.unsubscribe();\n })\n .catch((error) => {\n subscription.unsubscribe();\n return Promise.reject(error);\n })\n .then(() => {\n if (!hasPullTakenPlace) {\n // No pull took place in the ongoing sync but the caller had \"pull\" as\n // an explicit purpose of this call - so we need to redo the call!\n return syncIfPossible(db, cloudOptions, cloudSchema, options);\n }\n })\n );\n }\n }\n const promise = _syncIfPossible();\n ongoingSyncs.set(db, { promise, pull: options?.purpose !== 'push' });\n return promise;\n\n async function _syncIfPossible() {\n try {\n if (db.cloud.usingServiceWorker) {\n if (IS_SERVICE_WORKER) {\n await sync(db, cloudOptions, cloudSchema, options);\n }\n } else {\n // We use a flow that is better suited for the case when multiple workers want to\n // do the same thing.\n await performGuardedJob(db, CURRENT_SYNC_WORKER, '$jobs', () =>\n sync(db, cloudOptions, cloudSchema, options)\n );\n }\n ongoingSyncs.delete(db);\n console.debug('Done sync');\n } catch (error) {\n ongoingSyncs.delete(db);\n console.error(`Failed to sync client changes`, error);\n throw error; // Make sure we rethrow error so that sync event is retried.\n // I don't think we should setTimout or so here.\n // Unless server tells us to in some response.\n // Then we could follow that advice but not by waiting here but by registering\n // Something that triggers an event listened to in startPushWorker()\n }\n }\n}\n","import { Subscription } from 'rxjs';\nimport { syncIfPossible } from './syncIfPossible';\nimport { DexieCloudDB } from '../db/DexieCloudDB';\nimport { MINUTES } from '../helpers/date-constants';\nimport { DexieCloudOptions } from '../DexieCloudOptions';\nimport { DexieCloudSchema } from 'dexie-cloud-common';\n\nexport function LocalSyncWorker(\n db: DexieCloudDB,\n cloudOptions: DexieCloudOptions,\n cloudSchema: DexieCloudSchema\n) {\n let localSyncEventSubscription: Subscription | null = null;\n //let syncHandler: ((event: Event) => void) | null = null;\n //let periodicSyncHandler: ((event: Event) => void) | null = null;\n let cancelToken = { cancelled: false };\n\n function syncAndRetry(purpose: \"pull\" | \"push\", retryNum = 1) {\n syncIfPossible(db, cloudOptions, cloudSchema, {\n cancelToken,\n retryImmediatelyOnFetchError: true, // workaround for \"net::ERR_NETWORK_CHANGED\" in chrome.\n purpose\n }).catch((e) => {\n console.error('error in syncIfPossible()', e);\n if (cancelToken.cancelled) {\n stop();\n } else if (retryNum < 3) {\n // Mimic service worker sync event: retry 3 times\n // * first retry after 5 minutes\n // * second retry 15 minutes later\n setTimeout(\n () => syncAndRetry(purpose, retryNum + 1),\n [0, 5, 15][retryNum] * MINUTES\n );\n }\n });\n }\n\n const start = () => {\n // Sync eagerly whenever a change has happened (+ initially when there's no syncState yet)\n // This initial subscribe will also trigger an sync also now.\n console.debug('Starting LocalSyncWorker', db.localSyncEvent['id']);\n localSyncEventSubscription = db.localSyncEvent.subscribe(({purpose}) => {\n try {\n syncAndRetry(purpose || \"pull\");\n } catch (err) {\n console.error('What-the....', err);\n }\n });\n //setTimeout(()=>db.localSyncEvent.next({}), 5000);\n };\n\n const stop = () => {\n console.debug('Stopping LocalSyncWorker');\n cancelToken.cancelled = true;\n if (localSyncEventSubscription) localSyncEventSubscription.unsubscribe();\n };\n\n return {\n start,\n stop,\n };\n}\n","import { DexieCloudSchema } from \"dexie-cloud-common\";\nimport { DexieCloudOptions } from \"./DexieCloudOptions\";\n\nexport function updateSchemaFromOptions(schema?: DexieCloudSchema | null, options?: DexieCloudOptions | null) {\n if (schema && options) {\n if (options.unsyncedTables) {\n for (const tableName of options.unsyncedTables) {\n if (schema[tableName]) {\n schema[tableName].markedForSync = false;\n }\n }\n }\n }\n}","import Dexie from \"dexie\";\nimport { DexieCloudDB } from \"./db/DexieCloudDB\";\n\nexport function verifySchema(db: DexieCloudDB) {\n for (const table of db.tables) {\n if (db.cloud.schema?.[table.name]?.markedForSync) {\n if (table.schema.primKey.auto) {\n throw new Dexie.SchemaError(\n `Table ${table.name} is both autoIncremented and synced. ` +\n `Use db.cloud.configure({unsyncedTables: [${JSON.stringify(\n table.name\n )}]}) to blacklist it from sync`\n );\n }\n if (!table.schema.primKey.keyPath) {\n throw new Dexie.SchemaError(\n `Table ${table.name} cannot be both synced and outbound. ` +\n `Use db.cloud.configure({unsyncedTables: [${JSON.stringify(\n table.name\n )}]}) to blacklist it from sync`\n );\n }\n }\n }\n}\n","import { _catchError } from './diff/catch-error';\n\n/**\n * The `option` object can potentially contain callback functions\n * that are called during various stages of our renderer. This is the\n * foundation on which all our addons like `preact/debug`, `preact/compat`,\n * and `preact/hooks` are based on. See the `Options` type in `internal.d.ts`\n * for a full list of available option hooks (most editors/IDEs allow you to\n * ctrl+click or cmd+click on mac the type definition below).\n * @type {import('./internal').Options}\n */\nconst options = {\n\t_catchError,\n\t_vnodeId: 0\n};\n\nexport default options;\n","import { assign } from './util';\nimport { diff, commitRoot } from './diff/index';\nimport options from './options';\nimport { Fragment } from './create-element';\n\n/**\n * Base Component class. Provides `setState()` and `forceUpdate()`, which\n * trigger rendering\n * @param {object} props The initial component props\n * @param {object} context The initial context from parent components'\n * getChildContext\n */\nexport function Component(props, context) {\n\tthis.props = props;\n\tthis.context = context;\n}\n\n/**\n * Update component state and schedule a re-render.\n * @this {import('./internal').Component}\n * @param {object | ((s: object, p: object) => object)} update A hash of state\n * properties to update with new values or a function that given the current\n * state and props returns a new partial state\n * @param {() => void} [callback] A function to be called once component state is\n * updated\n */\nComponent.prototype.setState = function(update, callback) {\n\t// only clone state when copying to nextState the first time.\n\tlet s;\n\tif (this._nextState != null && this._nextState !== this.state) {\n\t\ts = this._nextState;\n\t} else {\n\t\ts = this._nextState = assign({}, this.state);\n\t}\n\n\tif (typeof update == 'function') {\n\t\t// Some libraries like `immer` mark the current state as readonly,\n\t\t// preventing us from mutating it, so we need to clone it. See #2716\n\t\tupdate = update(assign({}, s), this.props);\n\t}\n\n\tif (update) {\n\t\tassign(s, update);\n\t}\n\n\t// Skip update if updater function returned null\n\tif (update == null) return;\n\n\tif (this._vnode) {\n\t\tif (callback) this._renderCallbacks.push(callback);\n\t\tenqueueRender(this);\n\t}\n};\n\n/**\n * Immediately perform a synchronous re-render of the component\n * @this {import('./internal').Component}\n * @param {() => void} [callback] A function to be called after component is\n * re-rendered\n */\nComponent.prototype.forceUpdate = function(callback) {\n\tif (this._vnode) {\n\t\t// Set render mode so that we can differentiate where the render request\n\t\t// is coming from. We need this because forceUpdate should never call\n\t\t// shouldComponentUpdate\n\t\tthis._force = true;\n\t\tif (callback) this._renderCallbacks.push(callback);\n\t\tenqueueRender(this);\n\t}\n};\n\n/**\n * Accepts `props` and `state`, and returns a new Virtual DOM tree to build.\n * Virtual DOM is generally constructed via [JSX](http://jasonformat.com/wtf-is-jsx).\n * @param {object} props Props (eg: JSX attributes) received from parent\n * element/component\n * @param {object} state The component's current state\n * @param {object} context Context object, as returned by the nearest\n * ancestor's `getChildContext()`\n * @returns {import('./index').ComponentChildren | void}\n */\nComponent.prototype.render = Fragment;\n\n/**\n * @param {import('./internal').VNode} vnode\n * @param {number | null} [childIndex]\n */\nexport function getDomSibling(vnode, childIndex) {\n\tif (childIndex == null) {\n\t\t// Use childIndex==null as a signal to resume the search from the vnode's sibling\n\t\treturn vnode._parent\n\t\t\t? getDomSibling(vnode._parent, vnode._parent._children.indexOf(vnode) + 1)\n\t\t\t: null;\n\t}\n\n\tlet sibling;\n\tfor (; childIndex < vnode._children.length; childIndex++) {\n\t\tsibling = vnode._children[childIndex];\n\n\t\tif (sibling != null && sibling._dom != null) {\n\t\t\t// Since updateParentDomPointers keeps _dom pointer correct,\n\t\t\t// we can rely on _dom to tell us if this subtree contains a\n\t\t\t// rendered DOM node, and what the first rendered DOM node is\n\t\t\treturn sibling._dom;\n\t\t}\n\t}\n\n\t// If we get here, we have not found a DOM node in this vnode's children.\n\t// We must resume from this vnode's sibling (in it's parent _children array)\n\t// Only climb up and search the parent if we aren't searching through a DOM\n\t// VNode (meaning we reached the DOM parent of the original vnode that began\n\t// the search)\n\treturn typeof vnode.type == 'function' ? getDomSibling(vnode) : null;\n}\n\n/**\n * Trigger in-place re-rendering of a component.\n * @param {import('./internal').Component} component The component to rerender\n */\nfunction renderComponent(component) {\n\tlet vnode = component._vnode,\n\t\toldDom = vnode._dom,\n\t\tparentDom = component._parentDom;\n\n\tif (parentDom) {\n\t\tlet commitQueue = [];\n\t\tconst oldVNode = assign({}, vnode);\n\t\toldVNode._original = vnode._original + 1;\n\n\t\tdiff(\n\t\t\tparentDom,\n\t\t\tvnode,\n\t\t\toldVNode,\n\t\t\tcomponent._globalContext,\n\t\t\tparentDom.ownerSVGElement !== undefined,\n\t\t\tvnode._hydrating != null ? [oldDom] : null,\n\t\t\tcommitQueue,\n\t\t\toldDom == null ? getDomSibling(vnode) : oldDom,\n\t\t\tvnode._hydrating\n\t\t);\n\t\tcommitRoot(commitQueue, vnode);\n\n\t\tif (vnode._dom != oldDom) {\n\t\t\tupdateParentDomPointers(vnode);\n\t\t}\n\t}\n}\n\n/**\n * @param {import('./internal').VNode} vnode\n */\nfunction updateParentDomPointers(vnode) {\n\tif ((vnode = vnode._parent) != null && vnode._component != null) {\n\t\tvnode._dom = vnode._component.base = null;\n\t\tfor (let i = 0; i < vnode._children.length; i++) {\n\t\t\tlet child = vnode._children[i];\n\t\t\tif (child != null && child._dom != null) {\n\t\t\t\tvnode._dom = vnode._component.base = child._dom;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\t\treturn updateParentDomPointers(vnode);\n\t}\n}\n\n/**\n * The render queue\n * @type {Array<import('./internal').Component>}\n */\nlet rerenderQueue = [];\n\n/**\n * Asynchronously schedule a callback\n * @type {(cb: () => void) => void}\n */\n/* istanbul ignore next */\n// Note the following line isn't tree-shaken by rollup cuz of rollup/rollup#2566\nconst defer =\n\ttypeof Promise == 'function'\n\t\t? Promise.prototype.then.bind(Promise.resolve())\n\t\t: setTimeout;\n\n/*\n * The value of `Component.debounce` must asynchronously invoke the passed in callback. It is\n * important that contributors to Preact can consistently reason about what calls to `setState`, etc.\n * do, and when their effects will be applied. See the links below for some further reading on designing\n * asynchronous APIs.\n * * [Designing APIs for Asynchrony](https://blog.izs.me/2013/08/designing-apis-for-asynchrony)\n * * [Callbacks synchronous and asynchronous](https://blog.ometer.com/2011/07/24/callbacks-synchronous-and-asynchronous/)\n */\n\nlet prevDebounce;\n\n/**\n * Enqueue a rerender of a component\n * @param {import('./internal').Component} c The component to rerender\n */\nexport function enqueueRender(c) {\n\tif (\n\t\t(!c._dirty &&\n\t\t\t(c._dirty = true) &&\n\t\t\trerenderQueue.push(c) &&\n\t\t\t!process._rerenderCount++) ||\n\t\tprevDebounce !== options.debounceRendering\n\t) {\n\t\tprevDebounce = options.debounceRendering;\n\t\t(prevDebounce || defer)(process);\n\t}\n}\n\n/** Flush the render queue by rerendering all queued components */\nfunction process() {\n\tlet queue;\n\twhile ((process._rerenderCount = rerenderQueue.length)) {\n\t\tqueue = rerenderQueue.sort((a, b) => a._vnode._depth - b._vnode._depth);\n\t\trerenderQueue = [];\n\t\t// Don't update `renderCount` yet. Keep its value non-zero to prevent unnecessary\n\t\t// process() calls from getting scheduled while `queue` is still being consumed.\n\t\tqueue.some(c => {\n\t\t\tif (c._dirty) renderComponent(c);\n\t\t});\n\t}\n}\nprocess._rerenderCount = 0;\n","export const EMPTY_OBJ = {};\nexport const EMPTY_ARR = [];\nexport const IS_NON_DIMENSIONAL = /acit|ex(?:s|g|n|p|$)|rph|grid|ows|mnc|ntw|ine[ch]|zoo|^ord|itera/i;\n","/**\n * Assign properties from `props` to `obj`\n * @template O, P The obj and props types\n * @param {O} obj The object to copy properties to\n * @param {P} props The object to copy properties from\n * @returns {O & P}\n */\nexport function assign(obj, props) {\n\t// @ts-ignore We change the type of `obj` to be `O & P`\n\tfor (let i in props) obj[i] = props[i];\n\treturn /** @type {O & P} */ (obj);\n}\n\n/**\n * Remove a child node from its parent if attached. This is a workaround for\n * IE11 which doesn't support `Element.prototype.remove()`. Using this function\n * is smaller than including a dedicated polyfill.\n * @param {Node} node The node to remove\n */\nexport function removeNode(node) {\n\tlet parentNode = node.parentNode;\n\tif (parentNode) parentNode.removeChild(node);\n}\n","import options from './options';\n\n/**\n * Create an virtual node (used for JSX)\n * @param {import('./internal').VNode[\"type\"]} type The node name or Component\n * constructor for this virtual node\n * @param {object | null | undefined} [props] The properties of the virtual node\n * @param {Array<import('.').ComponentChildren>} [children] The children of the virtual node\n * @returns {import('./internal').VNode}\n */\nexport function createElement(type, props, children) {\n\tlet normalizedProps = {},\n\t\tkey,\n\t\tref,\n\t\ti;\n\tfor (i in props) {\n\t\tif (i == 'key') key = props[i];\n\t\telse if (i == 'ref') ref = props[i];\n\t\telse normalizedProps[i] = props[i];\n\t}\n\n\tif (arguments.length > 3) {\n\t\tchildren = [children];\n\t\t// https://github.com/preactjs/preact/issues/1916\n\t\tfor (i = 3; i < arguments.length; i++) {\n\t\t\tchildren.push(arguments[i]);\n\t\t}\n\t}\n\tif (children != null) {\n\t\tnormalizedProps.children = children;\n\t}\n\n\t// If a Component VNode, check for and apply defaultProps\n\t// Note: type may be undefined in development, must never error here.\n\tif (typeof type == 'function' && type.defaultProps != null) {\n\t\tfor (i in type.defaultProps) {\n\t\t\tif (normalizedProps[i] === undefined) {\n\t\t\t\tnormalizedProps[i] = type.defaultProps[i];\n\t\t\t}\n\t\t}\n\t}\n\n\treturn createVNode(type, normalizedProps, key, ref, null);\n}\n\n/**\n * Create a VNode (used internally by Preact)\n * @param {import('./internal').VNode[\"type\"]} type The node name or Component\n * Constructor for this virtual node\n * @param {object | string | number | null} props The properties of this virtual node.\n * If this virtual node represents a text node, this is the text of the node (string or number).\n * @param {string | number | null} key The key for this virtual node, used when\n * diffing it against its children\n * @param {import('./internal').VNode[\"ref\"]} ref The ref property that will\n * receive a reference to its created child\n * @returns {import('./internal').VNode}\n */\nexport function createVNode(type, props, key, ref, original) {\n\t// V8 seems to be better at detecting type shapes if the object is allocated from the same call site\n\t// Do not inline into createElement and coerceToVNode!\n\tconst vnode = {\n\t\ttype,\n\t\tprops,\n\t\tkey,\n\t\tref,\n\t\t_children: null,\n\t\t_parent: null,\n\t\t_depth: 0,\n\t\t_dom: null,\n\t\t// _nextDom must be initialized to undefined b/c it will eventually\n\t\t// be set to dom.nextSibling which can return `null` and it is important\n\t\t// to be able to distinguish between an uninitialized _nextDom and\n\t\t// a _nextDom that has been set to `null`\n\t\t_nextDom: undefined,\n\t\t_component: null,\n\t\t_hydrating: null,\n\t\tconstructor: undefined,\n\t\t_original: original == null ? ++options._vnodeId : original\n\t};\n\n\tif (options.vnode != null) options.vnode(vnode);\n\n\treturn vnode;\n}\n\nexport function createRef() {\n\treturn { current: null };\n}\n\nexport function Fragment(props) {\n\treturn props.children;\n}\n\n/**\n * Check if a the argument is a valid Preact VNode.\n * @param {*} vnode\n * @returns {vnode is import('./internal').VNode}\n */\nexport const isValidElement = vnode =>\n\tvnode != null && vnode.constructor === undefined;\n","import { diff, unmount, applyRef } from './index';\nimport { createVNode, Fragment } from '../create-element';\nimport { EMPTY_OBJ, EMPTY_ARR } from '../constants';\nimport { getDomSibling } from '../component';\n\n/**\n * Diff the children of a virtual node\n * @param {import('../internal').PreactElement} parentDom The DOM element whose\n * children are being diffed\n * @param {import('../internal').ComponentChildren[]} renderResult\n * @param {import('../internal').VNode} newParentVNode The new virtual\n * node whose children should be diff'ed against oldParentVNode\n * @param {import('../internal').VNode} oldParentVNode The old virtual\n * node whose children should be diff'ed against newParentVNode\n * @param {object} globalContext The current context object - modified by getChildContext\n * @param {boolean} isSvg Whether or not this DOM node is an SVG node\n * @param {Array<import('../internal').PreactElement>} excessDomChildren\n * @param {Array<import('../internal').Component>} commitQueue List of components\n * which have callbacks to invoke in commitRoot\n * @param {import('../internal').PreactElement} oldDom The current attached DOM\n * element any new dom elements should be placed around. Likely `null` on first\n * render (except when hydrating). Can be a sibling DOM element when diffing\n * Fragments that have siblings. In most cases, it starts out as `oldChildren[0]._dom`.\n * @param {boolean} isHydrating Whether or not we are in hydration\n */\nexport function diffChildren(\n\tparentDom,\n\trenderResult,\n\tnewParentVNode,\n\toldParentVNode,\n\tglobalContext,\n\tisSvg,\n\texcessDomChildren,\n\tcommitQueue,\n\toldDom,\n\tisHydrating\n) {\n\tlet i, j, oldVNode, childVNode, newDom, firstChildDom, refs;\n\n\t// This is a compression of oldParentVNode!=null && oldParentVNode != EMPTY_OBJ && oldParentVNode._children || EMPTY_ARR\n\t// as EMPTY_OBJ._children should be `undefined`.\n\tlet oldChildren = (oldParentVNode && oldParentVNode._children) || EMPTY_ARR;\n\n\tlet oldChildrenLength = oldChildren.length;\n\n\tnewParentVNode._children = [];\n\tfor (i = 0; i < renderResult.length; i++) {\n\t\tchildVNode = renderResult[i];\n\n\t\tif (childVNode == null || typeof childVNode == 'boolean') {\n\t\t\tchildVNode = newParentVNode._children[i] = null;\n\t\t}\n\t\t// If this newVNode is being reused (e.g. <div>{reuse}{reuse}</div>) in the same diff,\n\t\t// or we are rendering a component (e.g. setState) copy the oldVNodes so it can have\n\t\t// it's own DOM & etc. pointers\n\t\telse if (\n\t\t\ttypeof childVNode == 'string' ||\n\t\t\ttypeof childVNode == 'number' ||\n\t\t\t// eslint-disable-next-line valid-typeof\n\t\t\ttypeof childVNode == 'bigint'\n\t\t) {\n\t\t\tchildVNode = newParentVNode._children[i] = createVNode(\n\t\t\t\tnull,\n\t\t\t\tchildVNode,\n\t\t\t\tnull,\n\t\t\t\tnull,\n\t\t\t\tchildVNode\n\t\t\t);\n\t\t} else if (Array.isArray(childVNode)) {\n\t\t\tchildVNode = newParentVNode._children[i] = createVNode(\n\t\t\t\tFragment,\n\t\t\t\t{ children: childVNode },\n\t\t\t\tnull,\n\t\t\t\tnull,\n\t\t\t\tnull\n\t\t\t);\n\t\t} else if (childVNode._depth > 0) {\n\t\t\t// VNode is already in use, clone it. This can happen in the following\n\t\t\t// scenario:\n\t\t\t// const reuse = <div />\n\t\t\t// <div>{reuse}<span />{reuse}</div>\n\t\t\tchildVNode = newParentVNode._children[i] = createVNode(\n\t\t\t\tchildVNode.type,\n\t\t\t\tchildVNode.props,\n\t\t\t\tchildVNode.key,\n\t\t\t\tnull,\n\t\t\t\tchildVNode._original\n\t\t\t);\n\t\t} else {\n\t\t\tchildVNode = newParentVNode._children[i] = childVNode;\n\t\t}\n\n\t\t// Terser removes the `continue` here and wraps the loop body\n\t\t// in a `if (childVNode) { ... } condition\n\t\tif (childVNode == null) {\n\t\t\tcontinue;\n\t\t}\n\n\t\tchildVNode._parent = newParentVNode;\n\t\tchildVNode._depth = newParentVNode._depth + 1;\n\n\t\t// Check if we find a corresponding element in oldChildren.\n\t\t// If found, delete the array item by setting to `undefined`.\n\t\t// We use `undefined`, as `null` is reserved for empty placeholders\n\t\t// (holes).\n\t\toldVNode = oldChildren[i];\n\n\t\tif (\n\t\t\toldVNode === null ||\n\t\t\t(oldVNode &&\n\t\t\t\tchildVNode.key == oldVNode.key &&\n\t\t\t\tchildVNode.type === oldVNode.type)\n\t\t) {\n\t\t\toldChildren[i] = undefined;\n\t\t} else {\n\t\t\t// Either oldVNode === undefined or oldChildrenLength > 0,\n\t\t\t// so after this loop oldVNode == null or oldVNode is a valid value.\n\t\t\tfor (j = 0; j < oldChildrenLength; j++) {\n\t\t\t\toldVNode = oldChildren[j];\n\t\t\t\t// If childVNode is unkeyed, we only match similarly unkeyed nodes, otherwise we match by key.\n\t\t\t\t// We always match by type (in either case).\n\t\t\t\tif (\n\t\t\t\t\toldVNode &&\n\t\t\t\t\tchildVNode.key == oldVNode.key &&\n\t\t\t\t\tchildVNode.type === oldVNode.type\n\t\t\t\t) {\n\t\t\t\t\toldChildren[j] = undefined;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\toldVNode = null;\n\t\t\t}\n\t\t}\n\n\t\toldVNode = oldVNode || EMPTY_OBJ;\n\n\t\t// Morph the old element into the new one, but don't append it to the dom yet\n\t\tdiff(\n\t\t\tparentDom,\n\t\t\tchildVNode,\n\t\t\toldVNode,\n\t\t\tglobalContext,\n\t\t\tisSvg,\n\t\t\texcessDomChildren,\n\t\t\tcommitQueue,\n\t\t\toldDom,\n\t\t\tisHydrating\n\t\t);\n\n\t\tnewDom = childVNode._dom;\n\n\t\tif ((j = childVNode.ref) && oldVNode.ref != j) {\n\t\t\tif (!refs) refs = [];\n\t\t\tif (oldVNode.ref) refs.push(oldVNode.ref, null, childVNode);\n\t\t\trefs.push(j, childVNode._component || newDom, childVNode);\n\t\t}\n\n\t\tif (newDom != null) {\n\t\t\tif (firstChildDom == null) {\n\t\t\t\tfirstChildDom = newDom;\n\t\t\t}\n\n\t\t\tif (\n\t\t\t\ttypeof childVNode.type == 'function' &&\n\t\t\t\tchildVNode._children != null && // Can be null if childVNode suspended\n\t\t\t\tchildVNode._children === oldVNode._children\n\t\t\t) {\n\t\t\t\tchildVNode._nextDom = oldDom = reorderChildren(\n\t\t\t\t\tchildVNode,\n\t\t\t\t\toldDom,\n\t\t\t\t\tparentDom\n\t\t\t\t);\n\t\t\t} else {\n\t\t\t\toldDom = placeChild(\n\t\t\t\t\tparentDom,\n\t\t\t\t\tchildVNode,\n\t\t\t\t\toldVNode,\n\t\t\t\t\toldChildren,\n\t\t\t\t\tnewDom,\n\t\t\t\t\toldDom\n\t\t\t\t);\n\t\t\t}\n\n\t\t\t// Browsers will infer an option's `value` from `textContent` when\n\t\t\t// no value is present. This essentially bypasses our code to set it\n\t\t\t// later in `diff()`. It works fine in all browsers except for IE11\n\t\t\t// where it breaks setting `select.value`. There it will be always set\n\t\t\t// to an empty string. Re-applying an options value will fix that, so\n\t\t\t// there are probably some internal data structures that aren't\n\t\t\t// updated properly.\n\t\t\t//\n\t\t\t// To fix it we make sure to reset the inferred value, so that our own\n\t\t\t// value check in `diff()` won't be skipped.\n\t\t\tif (!isHydrating && newParentVNode.type === 'option') {\n\t\t\t\t// @ts-ignore We have validated that the type of parentDOM is 'option'\n\t\t\t\t// in the above check\n\t\t\t\tparentDom.value = '';\n\t\t\t} else if (typeof newParentVNode.type == 'function') {\n\t\t\t\t// Because the newParentVNode is Fragment-like, we need to set it's\n\t\t\t\t// _nextDom property to the nextSibling of its last child DOM node.\n\t\t\t\t//\n\t\t\t\t// `oldDom` contains the correct value here because if the last child\n\t\t\t\t// is a Fragment-like, then oldDom has already been set to that child's _nextDom.\n\t\t\t\t// If the last child is a DOM VNode, then oldDom will be set to that DOM\n\t\t\t\t// node's nextSibling.\n\t\t\t\tnewParentVNode._nextDom = oldDom;\n\t\t\t}\n\t\t} else if (\n\t\t\toldDom &&\n\t\t\toldVNode._dom == oldDom &&\n\t\t\toldDom.parentNode != parentDom\n\t\t) {\n\t\t\t// The above condition is to handle null placeholders. See test in placeholder.test.js:\n\t\t\t// `efficiently replace null placeholders in parent rerenders`\n\t\t\toldDom = getDomSibling(oldVNode);\n\t\t}\n\t}\n\n\tnewParentVNode._dom = firstChildDom;\n\n\t// Remove remaining oldChildren if there are any.\n\tfor (i = oldChildrenLength; i--; ) {\n\t\tif (oldChildren[i] != null) {\n\t\t\tif (\n\t\t\t\ttypeof newParentVNode.type == 'function' &&\n\t\t\t\toldChildren[i]._dom != null &&\n\t\t\t\toldChildren[i]._dom == newParentVNode._nextDom\n\t\t\t) {\n\t\t\t\t// If the newParentVNode.__nextDom points to a dom node that is about to\n\t\t\t\t// be unmounted, then get the next sibling of that vnode and set\n\t\t\t\t// _nextDom to it\n\t\t\t\tnewParentVNode._nextDom = getDomSibling(oldParentVNode, i + 1);\n\t\t\t}\n\n\t\t\tunmount(oldChildren[i], oldChildren[i]);\n\t\t}\n\t}\n\n\t// Set refs only after unmount\n\tif (refs) {\n\t\tfor (i = 0; i < refs.length; i++) {\n\t\t\tapplyRef(refs[i], refs[++i], refs[++i]);\n\t\t}\n\t}\n}\n\nfunction reorderChildren(childVNode, oldDom, parentDom) {\n\tfor (let tmp = 0; tmp < childVNode._children.length; tmp++) {\n\t\tlet vnode = childVNode._children[tmp];\n\t\tif (vnode) {\n\t\t\t// We typically enter this code path on sCU bailout, where we copy\n\t\t\t// oldVNode._children to newVNode._children. If that is the case, we need\n\t\t\t// to update the old children's _parent pointer to point to the newVNode\n\t\t\t// (childVNode here).\n\t\t\tvnode._parent = childVNode;\n\n\t\t\tif (typeof vnode.type == 'function') {\n\t\t\t\toldDom = reorderChildren(vnode, oldDom, parentDom);\n\t\t\t} else {\n\t\t\t\toldDom = placeChild(\n\t\t\t\t\tparentDom,\n\t\t\t\t\tvnode,\n\t\t\t\t\tvnode,\n\t\t\t\t\tchildVNode._children,\n\t\t\t\t\tvnode._dom,\n\t\t\t\t\toldDom\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t}\n\n\treturn oldDom;\n}\n\n/**\n * Flatten and loop through the children of a virtual node\n * @param {import('../index').ComponentChildren} children The unflattened\n * children of a virtual node\n * @returns {import('../internal').VNode[]}\n */\nexport function toChildArray(children, out) {\n\tout = out || [];\n\tif (children == null || typeof children == 'boolean') {\n\t} else if (Array.isArray(children)) {\n\t\tchildren.some(child => {\n\t\t\ttoChildArray(child, out);\n\t\t});\n\t} else {\n\t\tout.push(children);\n\t}\n\treturn out;\n}\n\nfunction placeChild(\n\tparentDom,\n\tchildVNode,\n\toldVNode,\n\toldChildren,\n\tnewDom,\n\toldDom\n) {\n\tlet nextDom;\n\tif (childVNode._nextDom !== undefined) {\n\t\t// Only Fragments or components that return Fragment like VNodes will\n\t\t// have a non-undefined _nextDom. Continue the diff from the sibling\n\t\t// of last DOM child of this child VNode\n\t\tnextDom = childVNode._nextDom;\n\n\t\t// Eagerly cleanup _nextDom. We don't need to persist the value because\n\t\t// it is only used by `diffChildren` to determine where to resume the diff after\n\t\t// diffing Components and Fragments. Once we store it the nextDOM local var, we\n\t\t// can clean up the property\n\t\tchildVNode._nextDom = undefined;\n\t} else if (\n\t\toldVNode == null ||\n\t\tnewDom != oldDom ||\n\t\tnewDom.parentNode == null\n\t) {\n\t\touter: if (oldDom == null || oldDom.parentNode !== parentDom) {\n\t\t\tparentDom.appendChild(newDom);\n\t\t\tnextDom = null;\n\t\t} else {\n\t\t\t// `j<oldChildrenLength; j+=2` is an alternative to `j++<oldChildrenLength/2`\n\t\t\tfor (\n\t\t\t\tlet sibDom = oldDom, j = 0;\n\t\t\t\t(sibDom = sibDom.nextSibling) && j < oldChildren.length;\n\t\t\t\tj += 2\n\t\t\t) {\n\t\t\t\tif (sibDom == newDom) {\n\t\t\t\t\tbreak outer;\n\t\t\t\t}\n\t\t\t}\n\t\t\tparentDom.insertBefore(newDom, oldDom);\n\t\t\tnextDom = oldDom;\n\t\t}\n\t}\n\n\t// If we have pre-calculated the nextDOM node, use it. Else calculate it now\n\t// Strictly check for `undefined` here cuz `null` is a valid value of `nextDom`.\n\t// See more detail in create-element.js:createVNode\n\tif (nextDom !== undefined) {\n\t\toldDom = nextDom;\n\t} else {\n\t\toldDom = newDom.nextSibling;\n\t}\n\n\treturn oldDom;\n}\n","import { IS_NON_DIMENSIONAL } from '../constants';\nimport options from '../options';\n\n/**\n * Diff the old and new properties of a VNode and apply changes to the DOM node\n * @param {import('../internal').PreactElement} dom The DOM node to apply\n * changes to\n * @param {object} newProps The new props\n * @param {object} oldProps The old props\n * @param {boolean} isSvg Whether or not this node is an SVG node\n * @param {boolean} hydrate Whether or not we are in hydration mode\n */\nexport function diffProps(dom, newProps, oldProps, isSvg, hydrate) {\n\tlet i;\n\n\tfor (i in oldProps) {\n\t\tif (i !== 'children' && i !== 'key' && !(i in newProps)) {\n\t\t\tsetProperty(dom, i, null, oldProps[i], isSvg);\n\t\t}\n\t}\n\n\tfor (i in newProps) {\n\t\tif (\n\t\t\t(!hydrate || typeof newProps[i] == 'function') &&\n\t\t\ti !== 'children' &&\n\t\t\ti !== 'key' &&\n\t\t\ti !== 'value' &&\n\t\t\ti !== 'checked' &&\n\t\t\toldProps[i] !== newProps[i]\n\t\t) {\n\t\t\tsetProperty(dom, i, newProps[i], oldProps[i], isSvg);\n\t\t}\n\t}\n}\n\nfunction setStyle(style, key, value) {\n\tif (key[0] === '-') {\n\t\tstyle.setProperty(key, value);\n\t} else if (value == null) {\n\t\tstyle[key] = '';\n\t} else if (typeof value != 'number' || IS_NON_DIMENSIONAL.test(key)) {\n\t\tstyle[key] = value;\n\t} else {\n\t\tstyle[key] = value + 'px';\n\t}\n}\n\n/**\n * Set a property value on a DOM node\n * @param {import('../internal').PreactElement} dom The DOM node to modify\n * @param {string} name The name of the property to set\n * @param {*} value The value to set the property to\n * @param {*} oldValue The old value the property had\n * @param {boolean} isSvg Whether or not this DOM node is an SVG node or not\n */\nexport function setProperty(dom, name, value, oldValue, isSvg) {\n\tlet useCapture;\n\n\to: if (name === 'style') {\n\t\tif (typeof value == 'string') {\n\t\t\tdom.style.cssText = value;\n\t\t} else {\n\t\t\tif (typeof oldValue == 'string') {\n\t\t\t\tdom.style.cssText = oldValue = '';\n\t\t\t}\n\n\t\t\tif (oldValue) {\n\t\t\t\tfor (name in oldValue) {\n\t\t\t\t\tif (!(value && name in value)) {\n\t\t\t\t\t\tsetStyle(dom.style, name, '');\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (value) {\n\t\t\t\tfor (name in value) {\n\t\t\t\t\tif (!oldValue || value[name] !== oldValue[name]) {\n\t\t\t\t\t\tsetStyle(dom.style, name, value[name]);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\t// Benchmark for comparison: https://esbench.com/bench/574c954bdb965b9a00965ac6\n\telse if (name[0] === 'o' && name[1] === 'n') {\n\t\tuseCapture = name !== (name = name.replace(/Capture$/, ''));\n\n\t\t// Infer correct casing for DOM built-in events:\n\t\tif (name.toLowerCase() in dom) name = name.toLowerCase().slice(2);\n\t\telse name = name.slice(2);\n\n\t\tif (!dom._listeners) dom._listeners = {};\n\t\tdom._listeners[name + useCapture] = value;\n\n\t\tif (value) {\n\t\t\tif (!oldValue) {\n\t\t\t\tconst handler = useCapture ? eventProxyCapture : eventProxy;\n\t\t\t\tdom.addEventListener(name, handler, useCapture);\n\t\t\t}\n\t\t} else {\n\t\t\tconst handler = useCapture ? eventProxyCapture : eventProxy;\n\t\t\tdom.removeEventListener(name, handler, useCapture);\n\t\t}\n\t} else if (name !== 'dangerouslySetInnerHTML') {\n\t\tif (isSvg) {\n\t\t\t// Normalize incorrect prop usage for SVG:\n\t\t\t// - xlink:href / xlinkHref --> href (xlink:href was removed from SVG and isn't needed)\n\t\t\t// - className --> class\n\t\t\tname = name.replace(/xlink[H:h]/, 'h').replace(/sName$/, 's');\n\t\t} else if (\n\t\t\tname !== 'href' &&\n\t\t\tname !== 'list' &&\n\t\t\tname !== 'form' &&\n\t\t\t// Default value in browsers is `-1` and an empty string is\n\t\t\t// cast to `0` instead\n\t\t\tname !== 'tabIndex' &&\n\t\t\tname !== 'download' &&\n\t\t\tname in dom\n\t\t) {\n\t\t\ttry {\n\t\t\t\tdom[name] = value == null ? '' : value;\n\t\t\t\t// labelled break is 1b smaller here than a return statement (sorry)\n\t\t\t\tbreak o;\n\t\t\t} catch (e) {}\n\t\t}\n\n\t\t// ARIA-attributes have a different notion of boolean values.\n\t\t// The value `false` is different from the attribute not\n\t\t// existing on the DOM, so we can't remove it. For non-boolean\n\t\t// ARIA-attributes we could treat false as a removal, but the\n\t\t// amount of exceptions would cost us too many bytes. On top of\n\t\t// that other VDOM frameworks also always stringify `false`.\n\n\t\tif (typeof value === 'function') {\n\t\t\t// never serialize functions as attribute values\n\t\t} else if (\n\t\t\tvalue != null &&\n\t\t\t(value !== false || (name[0] === 'a' && name[1] === 'r'))\n\t\t) {\n\t\t\tdom.setAttribute(name, value);\n\t\t} else {\n\t\t\tdom.removeAttribute(name);\n\t\t}\n\t}\n}\n\n/**\n * Proxy an event to hooked event handlers\n * @param {Event} e The event object from the browser\n * @private\n */\nfunction eventProxy(e) {\n\tthis._listeners[e.type + false](options.event ? options.event(e) : e);\n}\n\nfunction eventProxyCapture(e) {\n\tthis._listeners[e.type + true](options.event ? options.event(e) : e);\n}\n","import { EMPTY_OBJ, EMPTY_ARR } from '../constants';\nimport { Component } from '../component';\nimport { Fragment } from '../create-element';\nimport { diffChildren } from './children';\nimport { diffProps, setProperty } from './props';\nimport { assign, removeNode } from '../util';\nimport options from '../options';\n\n/**\n * Diff two virtual nodes and apply proper changes to the DOM\n * @param {import('../internal').PreactElement} parentDom The parent of the DOM element\n * @param {import('../internal').VNode} newVNode The new virtual node\n * @param {import('../internal').VNode} oldVNode The old virtual node\n * @param {object} globalContext The current context object. Modified by getChildContext\n * @param {boolean} isSvg Whether or not this element is an SVG node\n * @param {Array<import('../internal').PreactElement>} excessDomChildren\n * @param {Array<import('../internal').Component>} commitQueue List of components\n * which have callbacks to invoke in commitRoot\n * @param {import('../internal').PreactElement} oldDom The current attached DOM\n * element any new dom elements should be placed around. Likely `null` on first\n * render (except when hydrating). Can be a sibling DOM element when diffing\n * Fragments that have siblings. In most cases, it starts out as `oldChildren[0]._dom`.\n * @param {boolean} [isHydrating] Whether or not we are in hydration\n */\nexport function diff(\n\tparentDom,\n\tnewVNode,\n\toldVNode,\n\tglobalContext,\n\tisSvg,\n\texcessDomChildren,\n\tcommitQueue,\n\toldDom,\n\tisHydrating\n) {\n\tlet tmp,\n\t\tnewType = newVNode.type;\n\n\t// When passing through createElement it assigns the object\n\t// constructor as undefined. This to prevent JSON-injection.\n\tif (newVNode.constructor !== undefined) return null;\n\n\t// If the previous diff bailed out, resume creating/hydrating.\n\tif (oldVNode._hydrating != null) {\n\t\tisHydrating = oldVNode._hydrating;\n\t\toldDom = newVNode._dom = oldVNode._dom;\n\t\t// if we resume, we want the tree to be \"unlocked\"\n\t\tnewVNode._hydrating = null;\n\t\texcessDomChildren = [oldDom];\n\t}\n\n\tif ((tmp = options._diff)) tmp(newVNode);\n\n\ttry {\n\t\touter: if (typeof newType == 'function') {\n\t\t\tlet c, isNew, oldProps, oldState, snapshot, clearProcessingException;\n\t\t\tlet newProps = newVNode.props;\n\n\t\t\t// Necessary for createContext api. Setting this property will pass\n\t\t\t// the context value as `this.context` just for this component.\n\t\t\ttmp = newType.contextType;\n\t\t\tlet provider = tmp && globalContext[tmp._id];\n\t\t\tlet componentContext = tmp\n\t\t\t\t? provider\n\t\t\t\t\t? provider.props.value\n\t\t\t\t\t: tmp._defaultValue\n\t\t\t\t: globalContext;\n\n\t\t\t// Get component and set it to `c`\n\t\t\tif (oldVNode._component) {\n\t\t\t\tc = newVNode._component = oldVNode._component;\n\t\t\t\tclearProcessingException = c._processingException = c._pendingError;\n\t\t\t} else {\n\t\t\t\t// Instantiate the new component\n\t\t\t\tif ('prototype' in newType && newType.prototype.render) {\n\t\t\t\t\t// @ts-ignore The check above verifies that newType is suppose to be constructed\n\t\t\t\t\tnewVNode._component = c = new newType(newProps, componentContext); // eslint-disable-line new-cap\n\t\t\t\t} else {\n\t\t\t\t\t// @ts-ignore Trust me, Component implements the interface we want\n\t\t\t\t\tnewVNode._component = c = new Component(newProps, componentContext);\n\t\t\t\t\tc.constructor = newType;\n\t\t\t\t\tc.render = doRender;\n\t\t\t\t}\n\t\t\t\tif (provider) provider.sub(c);\n\n\t\t\t\tc.props = newProps;\n\t\t\t\tif (!c.state) c.state = {};\n\t\t\t\tc.context = componentContext;\n\t\t\t\tc._globalContext = globalContext;\n\t\t\t\tisNew = c._dirty = true;\n\t\t\t\tc._renderCallbacks = [];\n\t\t\t}\n\n\t\t\t// Invoke getDerivedStateFromProps\n\t\t\tif (c._nextState == null) {\n\t\t\t\tc._nextState = c.state;\n\t\t\t}\n\t\t\tif (newType.getDerivedStateFromProps != null) {\n\t\t\t\tif (c._nextState == c.state) {\n\t\t\t\t\tc._nextState = assign({}, c._nextState);\n\t\t\t\t}\n\n\t\t\t\tassign(\n\t\t\t\t\tc._nextState,\n\t\t\t\t\tnewType.getDerivedStateFromProps(newProps, c._nextState)\n\t\t\t\t);\n\t\t\t}\n\n\t\t\toldProps = c.props;\n\t\t\toldState = c.state;\n\n\t\t\t// Invoke pre-render lifecycle methods\n\t\t\tif (isNew) {\n\t\t\t\tif (\n\t\t\t\t\tnewType.getDerivedStateFromProps == null &&\n\t\t\t\t\tc.componentWillMount != null\n\t\t\t\t) {\n\t\t\t\t\tc.componentWillMount();\n\t\t\t\t}\n\n\t\t\t\tif (c.componentDidMount != null) {\n\t\t\t\t\tc._renderCallbacks.push(c.componentDidMount);\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tif (\n\t\t\t\t\tnewType.getDerivedStateFromProps == null &&\n\t\t\t\t\tnewProps !== oldProps &&\n\t\t\t\t\tc.componentWillReceiveProps != null\n\t\t\t\t) {\n\t\t\t\t\tc.componentWillReceiveProps(newProps, componentContext);\n\t\t\t\t}\n\n\t\t\t\tif (\n\t\t\t\t\t(!c._force &&\n\t\t\t\t\t\tc.shouldComponentUpdate != null &&\n\t\t\t\t\t\tc.shouldComponentUpdate(\n\t\t\t\t\t\t\tnewProps,\n\t\t\t\t\t\t\tc._nextState,\n\t\t\t\t\t\t\tcomponentContext\n\t\t\t\t\t\t) === false) ||\n\t\t\t\t\tnewVNode._original === oldVNode._original\n\t\t\t\t) {\n\t\t\t\t\tc.props = newProps;\n\t\t\t\t\tc.state = c._nextState;\n\t\t\t\t\t// More info about this here: https://gist.github.com/JoviDeCroock/bec5f2ce93544d2e6070ef8e0036e4e8\n\t\t\t\t\tif (newVNode._original !== oldVNode._original) c._dirty = false;\n\t\t\t\t\tc._vnode = newVNode;\n\t\t\t\t\tnewVNode._dom = oldVNode._dom;\n\t\t\t\t\tnewVNode._children = oldVNode._children;\n\t\t\t\t\tnewVNode._children.forEach(vnode => {\n\t\t\t\t\t\tif (vnode) vnode._parent = newVNode;\n\t\t\t\t\t});\n\t\t\t\t\tif (c._renderCallbacks.length) {\n\t\t\t\t\t\tcommitQueue.push(c);\n\t\t\t\t\t}\n\n\t\t\t\t\tbreak outer;\n\t\t\t\t}\n\n\t\t\t\tif (c.componentWillUpdate != null) {\n\t\t\t\t\tc.componentWillUpdate(newProps, c._nextState, componentContext);\n\t\t\t\t}\n\n\t\t\t\tif (c.componentDidUpdate != null) {\n\t\t\t\t\tc._renderCallbacks.push(() => {\n\t\t\t\t\t\tc.componentDidUpdate(oldProps, oldState, snapshot);\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tc.context = componentContext;\n\t\t\tc.props = newProps;\n\t\t\tc.state = c._nextState;\n\n\t\t\tif ((tmp = options._render)) tmp(newVNode);\n\n\t\t\tc._dirty = false;\n\t\t\tc._vnode = newVNode;\n\t\t\tc._parentDom = parentDom;\n\n\t\t\ttmp = c.render(c.props, c.state, c.context);\n\n\t\t\t// Handle setState called in render, see #2553\n\t\t\tc.state = c._nextState;\n\n\t\t\tif (c.getChildContext != null) {\n\t\t\t\tglobalContext = assign(assign({}, globalContext), c.getChildContext());\n\t\t\t}\n\n\t\t\tif (!isNew && c.getSnapshotBeforeUpdate != null) {\n\t\t\t\tsnapshot = c.getSnapshotBeforeUpdate(oldProps, oldState);\n\t\t\t}\n\n\t\t\tlet isTopLevelFragment =\n\t\t\t\ttmp != null && tmp.type === Fragment && tmp.key == null;\n\t\t\tlet renderResult = isTopLevelFragment ? tmp.props.children : tmp;\n\n\t\t\tdiffChildren(\n\t\t\t\tparentDom,\n\t\t\t\tArray.isArray(renderResult) ? renderResult : [renderResult],\n\t\t\t\tnewVNode,\n\t\t\t\toldVNode,\n\t\t\t\tglobalContext,\n\t\t\t\tisSvg,\n\t\t\t\texcessDomChildren,\n\t\t\t\tcommitQueue,\n\t\t\t\toldDom,\n\t\t\t\tisHydrating\n\t\t\t);\n\n\t\t\tc.base = newVNode._dom;\n\n\t\t\t// We successfully rendered this VNode, unset any stored hydration/bailout state:\n\t\t\tnewVNode._hydrating = null;\n\n\t\t\tif (c._renderCallbacks.length) {\n\t\t\t\tcommitQueue.push(c);\n\t\t\t}\n\n\t\t\tif (clearProcessingException) {\n\t\t\t\tc._pendingError = c._processingException = null;\n\t\t\t}\n\n\t\t\tc._force = false;\n\t\t} else if (\n\t\t\texcessDomChildren == null &&\n\t\t\tnewVNode._original === oldVNode._original\n\t\t) {\n\t\t\tnewVNode._children = oldVNode._children;\n\t\t\tnewVNode._dom = oldVNode._dom;\n\t\t} else {\n\t\t\tnewVNode._dom = diffElementNodes(\n\t\t\t\toldVNode._dom,\n\t\t\t\tnewVNode,\n\t\t\t\toldVNode,\n\t\t\t\tglobalContext,\n\t\t\t\tisSvg,\n\t\t\t\texcessDomChildren,\n\t\t\t\tcommitQueue,\n\t\t\t\tisHydrating\n\t\t\t);\n\t\t}\n\n\t\tif ((tmp = options.diffed)) tmp(newVNode);\n\t} catch (e) {\n\t\tnewVNode._original = null;\n\t\t// if hydrating or creating initial tree, bailout preserves DOM:\n\t\tif (isHydrating || excessDomChildren != null) {\n\t\t\tnewVNode._dom = oldDom;\n\t\t\tnewVNode._hydrating = !!isHydrating;\n\t\t\texcessDomChildren[excessDomChildren.indexOf(oldDom)] = null;\n\t\t\t// ^ could possibly be simplified to:\n\t\t\t// excessDomChildren.length = 0;\n\t\t}\n\t\toptions._catchError(e, newVNode, oldVNode);\n\t}\n}\n\n/**\n * @param {Array<import('../internal').Component>} commitQueue List of components\n * which have callbacks to invoke in commitRoot\n * @param {import('../internal').VNode} root\n */\nexport function commitRoot(commitQueue, root) {\n\tif (options._commit) options._commit(root, commitQueue);\n\n\tcommitQueue.some(c => {\n\t\ttry {\n\t\t\t// @ts-ignore Reuse the commitQueue variable here so the type changes\n\t\t\tcommitQueue = c._renderCallbacks;\n\t\t\tc._renderCallbacks = [];\n\t\t\tcommitQueue.some(cb => {\n\t\t\t\t// @ts-ignore See above ts-ignore on commitQueue\n\t\t\t\tcb.call(c);\n\t\t\t});\n\t\t} catch (e) {\n\t\t\toptions._catchError(e, c._vnode);\n\t\t}\n\t});\n}\n\n/**\n * Diff two virtual nodes representing DOM element\n * @param {import('../internal').PreactElement} dom The DOM element representing\n * the virtual nodes being diffed\n * @param {import('../internal').VNode} newVNode The new virtual node\n * @param {import('../internal').VNode} oldVNode The old virtual node\n * @param {object} globalContext The current context object\n * @param {boolean} isSvg Whether or not this DOM node is an SVG node\n * @param {*} excessDomChildren\n * @param {Array<import('../internal').Component>} commitQueue List of components\n * which have callbacks to invoke in commitRoot\n * @param {boolean} isHydrating Whether or not we are in hydration\n * @returns {import('../internal').PreactElement}\n */\nfunction diffElementNodes(\n\tdom,\n\tnewVNode,\n\toldVNode,\n\tglobalContext,\n\tisSvg,\n\texcessDomChildren,\n\tcommitQueue,\n\tisHydrating\n) {\n\tlet oldProps = oldVNode.props;\n\tlet newProps = newVNode.props;\n\tlet nodeType = newVNode.type;\n\tlet i = 0;\n\n\t// Tracks entering and exiting SVG namespace when descending through the tree.\n\tif (nodeType === 'svg') isSvg = true;\n\n\tif (excessDomChildren != null) {\n\t\tfor (; i < excessDomChildren.length; i++) {\n\t\t\tconst child = excessDomChildren[i];\n\n\t\t\t// if newVNode matches an element in excessDomChildren or the `dom`\n\t\t\t// argument matches an element in excessDomChildren, remove it from\n\t\t\t// excessDomChildren so it isn't later removed in diffChildren\n\t\t\tif (\n\t\t\t\tchild &&\n\t\t\t\t(child === dom ||\n\t\t\t\t\t(nodeType ? child.localName == nodeType : child.nodeType == 3))\n\t\t\t) {\n\t\t\t\tdom = child;\n\t\t\t\texcessDomChildren[i] = null;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\n\tif (dom == null) {\n\t\tif (nodeType === null) {\n\t\t\t// @ts-ignore createTextNode returns Text, we expect PreactElement\n\t\t\treturn document.createTextNode(newProps);\n\t\t}\n\n\t\tif (isSvg) {\n\t\t\tdom = document.createElementNS(\n\t\t\t\t'http://www.w3.org/2000/svg',\n\t\t\t\t// @ts-ignore We know `newVNode.type` is a string\n\t\t\t\tnodeType\n\t\t\t);\n\t\t} else {\n\t\t\tdom = document.createElement(\n\t\t\t\t// @ts-ignore We know `newVNode.type` is a string\n\t\t\t\tnodeType,\n\t\t\t\tnewProps.is && newProps\n\t\t\t);\n\t\t}\n\n\t\t// we created a new parent, so none of the previously attached children can be reused:\n\t\texcessDomChildren = null;\n\t\t// we are creating a new node, so we can assume this is a new subtree (in case we are hydrating), this deopts the hydrate\n\t\tisHydrating = false;\n\t}\n\n\tif (nodeType === null) {\n\t\t// During hydration, we still have to split merged text from SSR'd HTML.\n\t\tif (oldProps !== newProps && (!isHydrating || dom.data !== newProps)) {\n\t\t\tdom.data = newProps;\n\t\t}\n\t} else {\n\t\t// If excessDomChildren was not null, repopulate it with the current element's children:\n\t\texcessDomChildren =\n\t\t\texcessDomChildren && EMPTY_ARR.slice.call(dom.childNodes);\n\n\t\toldProps = oldVNode.props || EMPTY_OBJ;\n\n\t\tlet oldHtml = oldProps.dangerouslySetInnerHTML;\n\t\tlet newHtml = newProps.dangerouslySetInnerHTML;\n\n\t\t// During hydration, props are not diffed at all (including dangerouslySetInnerHTML)\n\t\t// @TODO we should warn in debug mode when props don't match here.\n\t\tif (!isHydrating) {\n\t\t\t// But, if we are in a situation where we are using existing DOM (e.g. replaceNode)\n\t\t\t// we should read the existing DOM attributes to diff them\n\t\t\tif (excessDomChildren != null) {\n\t\t\t\toldProps = {};\n\t\t\t\tfor (let i = 0; i < dom.attributes.length; i++) {\n\t\t\t\t\toldProps[dom.attributes[i].name] = dom.attributes[i].value;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (newHtml || oldHtml) {\n\t\t\t\t// Avoid re-applying the same '__html' if it did not changed between re-render\n\t\t\t\tif (\n\t\t\t\t\t!newHtml ||\n\t\t\t\t\t((!oldHtml || newHtml.__html != oldHtml.__html) &&\n\t\t\t\t\t\tnewHtml.__html !== dom.innerHTML)\n\t\t\t\t) {\n\t\t\t\t\tdom.innerHTML = (newHtml && newHtml.__html) || '';\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tdiffProps(dom, newProps, oldProps, isSvg, isHydrating);\n\n\t\t// If the new vnode didn't have dangerouslySetInnerHTML, diff its children\n\t\tif (newHtml) {\n\t\t\tnewVNode._children = [];\n\t\t} else {\n\t\t\ti = newVNode.props.children;\n\t\t\tdiffChildren(\n\t\t\t\tdom,\n\t\t\t\tArray.isArray(i) ? i : [i],\n\t\t\t\tnewVNode,\n\t\t\t\toldVNode,\n\t\t\t\tglobalContext,\n\t\t\t\tisSvg && nodeType !== 'foreignObject',\n\t\t\t\texcessDomChildren,\n\t\t\t\tcommitQueue,\n\t\t\t\tdom.firstChild,\n\t\t\t\tisHydrating\n\t\t\t);\n\n\t\t\t// Remove children that are not part of any vnode.\n\t\t\tif (excessDomChildren != null) {\n\t\t\t\tfor (i = excessDomChildren.length; i--; ) {\n\t\t\t\t\tif (excessDomChildren[i] != null) removeNode(excessDomChildren[i]);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// (as above, don't diff props during hydration)\n\t\tif (!isHydrating) {\n\t\t\tif (\n\t\t\t\t'value' in newProps &&\n\t\t\t\t(i = newProps.value) !== undefined &&\n\t\t\t\t// #2756 For the <progress>-element the initial value is 0,\n\t\t\t\t// despite the attribute not being present. When the attribute\n\t\t\t\t// is missing the progress bar is treated as indeterminate.\n\t\t\t\t// To fix that we'll always update it when it is 0 for progress elements\n\t\t\t\t(i !== dom.value || (nodeType === 'progress' && !i))\n\t\t\t) {\n\t\t\t\tsetProperty(dom, 'value', i, oldProps.value, false);\n\t\t\t}\n\t\t\tif (\n\t\t\t\t'checked' in newProps &&\n\t\t\t\t(i = newProps.checked) !== undefined &&\n\t\t\t\ti !== dom.checked\n\t\t\t) {\n\t\t\t\tsetProperty(dom, 'checked', i, oldProps.checked, false);\n\t\t\t}\n\t\t}\n\t}\n\n\treturn dom;\n}\n\n/**\n * Invoke or update a ref, depending on whether it is a function or object ref.\n * @param {object|function} ref\n * @param {any} value\n * @param {import('../internal').VNode} vnode\n */\nexport function applyRef(ref, value, vnode) {\n\ttry {\n\t\tif (typeof ref == 'function') ref(value);\n\t\telse ref.current = value;\n\t} catch (e) {\n\t\toptions._catchError(e, vnode);\n\t}\n}\n\n/**\n * Unmount a virtual node from the tree and apply DOM changes\n * @param {import('../internal').VNode} vnode The virtual node to unmount\n * @param {import('../internal').VNode} parentVNode The parent of the VNode that\n * initiated the unmount\n * @param {boolean} [skipRemove] Flag that indicates that a parent node of the\n * current element is already detached from the DOM.\n */\nexport function unmount(vnode, parentVNode, skipRemove) {\n\tlet r;\n\tif (options.unmount) options.unmount(vnode);\n\n\tif ((r = vnode.ref)) {\n\t\tif (!r.current || r.current === vnode._dom) applyRef(r, null, parentVNode);\n\t}\n\n\tlet dom;\n\tif (!skipRemove && typeof vnode.type != 'function') {\n\t\tskipRemove = (dom = vnode._dom) != null;\n\t}\n\n\t// Must be set to `undefined` to properly clean up `_nextDom`\n\t// for which `null` is a valid value. See comment in `create-element.js`\n\tvnode._dom = vnode._nextDom = undefined;\n\n\tif ((r = vnode._component) != null) {\n\t\tif (r.componentWillUnmount) {\n\t\t\ttry {\n\t\t\t\tr.componentWillUnmount();\n\t\t\t} catch (e) {\n\t\t\t\toptions._catchError(e, parentVNode);\n\t\t\t}\n\t\t}\n\n\t\tr.base = r._parentDom = null;\n\t}\n\n\tif ((r = vnode._children)) {\n\t\tfor (let i = 0; i < r.length; i++) {\n\t\t\tif (r[i]) unmount(r[i], parentVNode, skipRemove);\n\t\t}\n\t}\n\n\tif (dom != null) removeNode(dom);\n}\n\n/** The `.render()` method for a PFC backing instance. */\nfunction doRender(props, state, context) {\n\treturn this.constructor(props, context);\n}\n","import { EMPTY_OBJ, EMPTY_ARR } from './constants';\nimport { commitRoot, diff } from './diff/index';\nimport { createElement, Fragment } from './create-element';\nimport options from './options';\n\n/**\n * Render a Preact virtual node into a DOM element\n * @param {import('./internal').ComponentChild} vnode The virtual node to render\n * @param {import('./internal').PreactElement} parentDom The DOM element to\n * render into\n * @param {import('./internal').PreactElement | object} [replaceNode] Optional: Attempt to re-use an\n * existing DOM tree rooted at `replaceNode`\n */\nexport function render(vnode, parentDom, replaceNode) {\n\tif (options._root) options._root(vnode, parentDom);\n\n\t// We abuse the `replaceNode` parameter in `hydrate()` to signal if we are in\n\t// hydration mode or not by passing the `hydrate` function instead of a DOM\n\t// element..\n\tlet isHydrating = typeof replaceNode === 'function';\n\n\t// To be able to support calling `render()` multiple times on the same\n\t// DOM node, we need to obtain a reference to the previous tree. We do\n\t// this by assigning a new `_children` property to DOM nodes which points\n\t// to the last rendered tree. By default this property is not present, which\n\t// means that we are mounting a new tree for the first time.\n\tlet oldVNode = isHydrating\n\t\t? null\n\t\t: (replaceNode && replaceNode._children) || parentDom._children;\n\n\tvnode = (\n\t\t(!isHydrating && replaceNode) ||\n\t\tparentDom\n\t)._children = createElement(Fragment, null, [vnode]);\n\n\t// List of effects that need to be called after diffing.\n\tlet commitQueue = [];\n\tdiff(\n\t\tparentDom,\n\t\t// Determine the new vnode tree and store it on the DOM element on\n\t\t// our custom `_children` property.\n\t\tvnode,\n\t\toldVNode || EMPTY_OBJ,\n\t\tEMPTY_OBJ,\n\t\tparentDom.ownerSVGElement !== undefined,\n\t\t!isHydrating && replaceNode\n\t\t\t? [replaceNode]\n\t\t\t: oldVNode\n\t\t\t? null\n\t\t\t: parentDom.firstChild\n\t\t\t? EMPTY_ARR.slice.call(parentDom.childNodes)\n\t\t\t: null,\n\t\tcommitQueue,\n\t\t!isHydrating && replaceNode\n\t\t\t? replaceNode\n\t\t\t: oldVNode\n\t\t\t? oldVNode._dom\n\t\t\t: parentDom.firstChild,\n\t\tisHydrating\n\t);\n\n\t// Flush all queued effects\n\tcommitRoot(commitQueue, vnode);\n}\n\n/**\n * Update an existing DOM element with data from a Preact virtual node\n * @param {import('./internal').ComponentChild} vnode The virtual node to render\n * @param {import('./internal').PreactElement} parentDom The DOM element to\n * update\n */\nexport function hydrate(vnode, parentDom) {\n\trender(vnode, parentDom, hydrate);\n}\n","/**\n * Find the closest error boundary to a thrown error and call it\n * @param {object} error The thrown value\n * @param {import('../internal').VNode} vnode The vnode that threw\n * the error that was caught (except for unmounting when this parameter\n * is the highest parent that was being unmounted)\n */\nexport function _catchError(error, vnode) {\n\t/** @type {import('../internal').Component} */\n\tlet component, ctor, handled;\n\n\tfor (; (vnode = vnode._parent); ) {\n\t\tif ((component = vnode._component) && !component._processingException) {\n\t\t\ttry {\n\t\t\t\tctor = component.constructor;\n\n\t\t\t\tif (ctor && ctor.getDerivedStateFromError != null) {\n\t\t\t\t\tcomponent.setState(ctor.getDerivedStateFromError(error));\n\t\t\t\t\thandled = component._dirty;\n\t\t\t\t}\n\n\t\t\t\tif (component.componentDidCatch != null) {\n\t\t\t\t\tcomponent.componentDidCatch(error);\n\t\t\t\t\thandled = component._dirty;\n\t\t\t\t}\n\n\t\t\t\t// This is an error boundary. Mark it as having bailed out, and whether it was mid-hydration.\n\t\t\t\tif (handled) {\n\t\t\t\t\treturn (component._pendingError = component);\n\t\t\t\t}\n\t\t\t} catch (e) {\n\t\t\t\terror = e;\n\t\t\t}\n\t\t}\n\t}\n\n\tthrow error;\n}\n","import { enqueueRender } from './component';\n\nexport let i = 0;\n\nexport function createContext(defaultValue, contextId) {\n\tcontextId = '__cC' + i++;\n\n\tconst context = {\n\t\t_id: contextId,\n\t\t_defaultValue: defaultValue,\n\t\t/** @type {import('./internal').FunctionComponent} */\n\t\tConsumer(props, contextValue) {\n\t\t\t// return props.children(\n\t\t\t// \tcontext[contextId] ? context[contextId].props.value : defaultValue\n\t\t\t// );\n\t\t\treturn props.children(contextValue);\n\t\t},\n\t\t/** @type {import('./internal').FunctionComponent} */\n\t\tProvider(props) {\n\t\t\tif (!this.getChildContext) {\n\t\t\t\tlet subs = [];\n\t\t\t\tlet ctx = {};\n\t\t\t\tctx[contextId] = this;\n\n\t\t\t\tthis.getChildContext = () => ctx;\n\n\t\t\t\tthis.shouldComponentUpdate = function(_props) {\n\t\t\t\t\tif (this.props.value !== _props.value) {\n\t\t\t\t\t\t// I think the forced value propagation here was only needed when `options.debounceRendering` was being bypassed:\n\t\t\t\t\t\t// https://github.com/preactjs/preact/commit/4d339fb803bea09e9f198abf38ca1bf8ea4b7771#diff-54682ce380935a717e41b8bfc54737f6R358\n\t\t\t\t\t\t// In those cases though, even with the value corrected, we're double-rendering all nodes.\n\t\t\t\t\t\t// It might be better to just tell folks not to use force-sync mode.\n\t\t\t\t\t\t// Currently, using `useContext()` in a class component will overwrite its `this.context` value.\n\t\t\t\t\t\t// subs.some(c => {\n\t\t\t\t\t\t// \tc.context = _props.value;\n\t\t\t\t\t\t// \tenqueueRender(c);\n\t\t\t\t\t\t// });\n\n\t\t\t\t\t\t// subs.some(c => {\n\t\t\t\t\t\t// \tc.context[contextId] = _props.value;\n\t\t\t\t\t\t// \tenqueueRender(c);\n\t\t\t\t\t\t// });\n\t\t\t\t\t\tsubs.some(enqueueRender);\n\t\t\t\t\t}\n\t\t\t\t};\n\n\t\t\t\tthis.sub = c => {\n\t\t\t\t\tsubs.push(c);\n\t\t\t\t\tlet old = c.componentWillUnmount;\n\t\t\t\t\tc.componentWillUnmount = () => {\n\t\t\t\t\t\tsubs.splice(subs.indexOf(c), 1);\n\t\t\t\t\t\tif (old) old.call(c);\n\t\t\t\t\t};\n\t\t\t\t};\n\t\t\t}\n\n\t\t\treturn props.children;\n\t\t}\n\t};\n\n\t// Devtools needs access to the context object when it\n\t// encounters a Provider. This is necessary to support\n\t// setting `displayName` on the context object instead\n\t// of on the component itself. See:\n\t// https://reactjs.org/docs/context.html#contextdisplayname\n\n\treturn (context.Provider._contextRef = context.Consumer.contextType = context);\n}\n","export const Styles: { [styleAlias: string]: Partial<CSSStyleDeclaration> | any} = {\n Error: {\n color: \"red\",\n },\n Alert: {\n error: {\n color: \"red\"\n },\n warning: {\n color: \"yellow\"\n },\n info: {\n color: \"black\"\n }\n },\n Darken: {\n position: \"fixed\",\n top: 0,\n left: 0,\n opacity: 0.5,\n backgroundColor: \"#000\",\n width: \"100vw\",\n height: \"100vh\",\n zIndex: 150,\n webkitBackdropFilter: \"blur(2px)\",\n backdropFilter: \"blur(2px)\",\n },\n DialogOuter: {\n position: \"fixed\",\n top: 0,\n left: 0,\n width: \"100vw\",\n height: \"100vh\",\n zIndex: 150,\n alignItems: \"center\",\n display: \"flex\",\n justifyContent: \"center\",\n },\n DialogInner: {\n position: \"relative\",\n color: \"#222\",\n backgroundColor: \"#fff\",\n padding: \"30px\",\n marginBottom: \"2em\",\n maxWidth: \"90%\",\n maxHeight: \"90%\",\n overflowY: \"auto\",\n border: \"3px solid #3d3d5d\",\n borderRadius: \"8px\",\n boxShadow: \"0 0 80px 10px #666\",\n width: \"auto\"\n },\n Input: {\n height: \"35px\",\n width: \"17em\",\n borderColor: \"#ccf4\",\n outline: \"none\",\n fontSize: \"17pt\",\n padding: \"8px\"\n \n }\n};\n","import { Styles } from './Styles';\nimport { ComponentChildren, h } from 'preact';\n\nexport function Dialog({ children }: { children?: ComponentChildren }) {\n return (\n <div>\n <div style={Styles.Darken} />\n <div style={Styles.DialogOuter}>\n <div style={Styles.DialogInner}>{children}</div>\n </div>\n </div>\n );\n}\n","import { options } from 'preact';\n\n/** @type {number} */\nlet currentIndex;\n\n/** @type {import('./internal').Component} */\nlet currentComponent;\n/**\n * Keep track of the previous component so that we can set\n * `currentComponent` to `null` and throw when a hook is invoked\n * outside of render\n * @type {import('./internal').Component}\n */\nlet previousComponent;\n\n/** @type {number} */\nlet currentHook = 0;\n\n/** @type {Array<import('./internal').Component>} */\nlet afterPaintEffects = [];\n\nlet oldBeforeDiff = options._diff;\nlet oldBeforeRender = options._render;\nlet oldAfterDiff = options.diffed;\nlet oldCommit = options._commit;\nlet oldBeforeUnmount = options.unmount;\n\nconst RAF_TIMEOUT = 100;\nlet prevRaf;\n\noptions._diff = vnode => {\n\tcurrentComponent = null;\n\tif (oldBeforeDiff) oldBeforeDiff(vnode);\n};\n\noptions._render = vnode => {\n\tif (oldBeforeRender) oldBeforeRender(vnode);\n\n\tcurrentComponent = vnode._component;\n\tcurrentIndex = 0;\n\n\tconst hooks = currentComponent.__hooks;\n\tif (hooks) {\n\t\thooks._pendingEffects.forEach(invokeCleanup);\n\t\thooks._pendingEffects.forEach(invokeEffect);\n\t\thooks._pendingEffects = [];\n\t}\n};\n\noptions.diffed = vnode => {\n\tif (oldAfterDiff) oldAfterDiff(vnode);\n\n\tconst c = vnode._component;\n\tif (c && c.__hooks && c.__hooks._pendingEffects.length) {\n\t\tafterPaint(afterPaintEffects.push(c));\n\t}\n\tcurrentComponent = previousComponent;\n};\n\noptions._commit = (vnode, commitQueue) => {\n\tcommitQueue.some(component => {\n\t\ttry {\n\t\t\tcomponent._renderCallbacks.forEach(invokeCleanup);\n\t\t\tcomponent._renderCallbacks = component._renderCallbacks.filter(cb =>\n\t\t\t\tcb._value ? invokeEffect(cb) : true\n\t\t\t);\n\t\t} catch (e) {\n\t\t\tcommitQueue.some(c => {\n\t\t\t\tif (c._renderCallbacks) c._renderCallbacks = [];\n\t\t\t});\n\t\t\tcommitQueue = [];\n\t\t\toptions._catchError(e, component._vnode);\n\t\t}\n\t});\n\n\tif (oldCommit) oldCommit(vnode, commitQueue);\n};\n\noptions.unmount = vnode => {\n\tif (oldBeforeUnmount) oldBeforeUnmount(vnode);\n\n\tconst c = vnode._component;\n\tif (c && c.__hooks) {\n\t\ttry {\n\t\t\tc.__hooks._list.forEach(invokeCleanup);\n\t\t} catch (e) {\n\t\t\toptions._catchError(e, c._vnode);\n\t\t}\n\t}\n};\n\n/**\n * Get a hook's state from the currentComponent\n * @param {number} index The index of the hook to get\n * @param {number} type The index of the hook to get\n * @returns {any}\n */\nfunction getHookState(index, type) {\n\tif (options._hook) {\n\t\toptions._hook(currentComponent, index, currentHook || type);\n\t}\n\tcurrentHook = 0;\n\n\t// Largely inspired by:\n\t// * https://github.com/michael-klein/funcy.js/blob/f6be73468e6ec46b0ff5aa3cc4c9baf72a29025a/src/hooks/core_hooks.mjs\n\t// * https://github.com/michael-klein/funcy.js/blob/650beaa58c43c33a74820a3c98b3c7079cf2e333/src/renderer.mjs\n\t// Other implementations to look at:\n\t// * https://codesandbox.io/s/mnox05qp8\n\tconst hooks =\n\t\tcurrentComponent.__hooks ||\n\t\t(currentComponent.__hooks = {\n\t\t\t_list: [],\n\t\t\t_pendingEffects: []\n\t\t});\n\n\tif (index >= hooks._list.length) {\n\t\thooks._list.push({});\n\t}\n\treturn hooks._list[index];\n}\n\n/**\n * @param {import('./index').StateUpdater<any>} [initialState]\n */\nexport function useState(initialState) {\n\tcurrentHook = 1;\n\treturn useReducer(invokeOrReturn, initialState);\n}\n\n/**\n * @param {import('./index').Reducer<any, any>} reducer\n * @param {import('./index').StateUpdater<any>} initialState\n * @param {(initialState: any) => void} [init]\n * @returns {[ any, (state: any) => void ]}\n */\nexport function useReducer(reducer, initialState, init) {\n\t/** @type {import('./internal').ReducerHookState} */\n\tconst hookState = getHookState(currentIndex++, 2);\n\thookState._reducer = reducer;\n\tif (!hookState._component) {\n\t\thookState._value = [\n\t\t\t!init ? invokeOrReturn(undefined, initialState) : init(initialState),\n\n\t\t\taction => {\n\t\t\t\tconst nextValue = hookState._reducer(hookState._value[0], action);\n\t\t\t\tif (hookState._value[0] !== nextValue) {\n\t\t\t\t\thookState._value = [nextValue, hookState._value[1]];\n\t\t\t\t\thookState._component.setState({});\n\t\t\t\t}\n\t\t\t}\n\t\t];\n\n\t\thookState._component = currentComponent;\n\t}\n\n\treturn hookState._value;\n}\n\n/**\n * @param {import('./internal').Effect} callback\n * @param {any[]} args\n */\nexport function useEffect(callback, args) {\n\t/** @type {import('./internal').EffectHookState} */\n\tconst state = getHookState(currentIndex++, 3);\n\tif (!options._skipEffects && argsChanged(state._args, args)) {\n\t\tstate._value = callback;\n\t\tstate._args = args;\n\n\t\tcurrentComponent.__hooks._pendingEffects.push(state);\n\t}\n}\n\n/**\n * @param {import('./internal').Effect} callback\n * @param {any[]} args\n */\nexport function useLayoutEffect(callback, args) {\n\t/** @type {import('./internal').EffectHookState} */\n\tconst state = getHookState(currentIndex++, 4);\n\tif (!options._skipEffects && argsChanged(state._args, args)) {\n\t\tstate._value = callback;\n\t\tstate._args = args;\n\n\t\tcurrentComponent._renderCallbacks.push(state);\n\t}\n}\n\nexport function useRef(initialValue) {\n\tcurrentHook = 5;\n\treturn useMemo(() => ({ current: initialValue }), []);\n}\n\n/**\n * @param {object} ref\n * @param {() => object} createHandle\n * @param {any[]} args\n */\nexport function useImperativeHandle(ref, createHandle, args) {\n\tcurrentHook = 6;\n\tuseLayoutEffect(\n\t\t() => {\n\t\t\tif (typeof ref == 'function') ref(createHandle());\n\t\t\telse if (ref) ref.current = createHandle();\n\t\t},\n\t\targs == null ? args : args.concat(ref)\n\t);\n}\n\n/**\n * @param {() => any} factory\n * @param {any[]} args\n */\nexport function useMemo(factory, args) {\n\t/** @type {import('./internal').MemoHookState} */\n\tconst state = getHookState(currentIndex++, 7);\n\tif (argsChanged(state._args, args)) {\n\t\tstate._value = factory();\n\t\tstate._args = args;\n\t\tstate._factory = factory;\n\t}\n\n\treturn state._value;\n}\n\n/**\n * @param {() => void} callback\n * @param {any[]} args\n */\nexport function useCallback(callback, args) {\n\tcurrentHook = 8;\n\treturn useMemo(() => callback, args);\n}\n\n/**\n * @param {import('./internal').PreactContext} context\n */\nexport function useContext(context) {\n\tconst provider = currentComponent.context[context._id];\n\t// We could skip this call here, but than we'd not call\n\t// `options._hook`. We need to do that in order to make\n\t// the devtools aware of this hook.\n\t/** @type {import('./internal').ContextHookState} */\n\tconst state = getHookState(currentIndex++, 9);\n\t// The devtools needs access to the context object to\n\t// be able to pull of the default value when no provider\n\t// is present in the tree.\n\tstate._context = context;\n\tif (!provider) return context._defaultValue;\n\t// This is probably not safe to convert to \"!\"\n\tif (state._value == null) {\n\t\tstate._value = true;\n\t\tprovider.sub(currentComponent);\n\t}\n\treturn provider.props.value;\n}\n\n/**\n * Display a custom label for a custom hook for the devtools panel\n * @type {<T>(value: T, cb?: (value: T) => string | number) => void}\n */\nexport function useDebugValue(value, formatter) {\n\tif (options.useDebugValue) {\n\t\toptions.useDebugValue(formatter ? formatter(value) : value);\n\t}\n}\n\n/**\n * @param {(error: any) => void} cb\n */\nexport function useErrorBoundary(cb) {\n\t/** @type {import('./internal').ErrorBoundaryHookState} */\n\tconst state = getHookState(currentIndex++, 10);\n\tconst errState = useState();\n\tstate._value = cb;\n\tif (!currentComponent.componentDidCatch) {\n\t\tcurrentComponent.componentDidCatch = err => {\n\t\t\tif (state._value) state._value(err);\n\t\t\terrState[1](err);\n\t\t};\n\t}\n\treturn [\n\t\terrState[0],\n\t\t() => {\n\t\t\terrState[1](undefined);\n\t\t}\n\t];\n}\n\n/**\n * After paint effects consumer.\n */\nfunction flushAfterPaintEffects() {\n\tafterPaintEffects.forEach(component => {\n\t\tif (component._parentDom) {\n\t\t\ttry {\n\t\t\t\tcomponent.__hooks._pendingEffects.forEach(invokeCleanup);\n\t\t\t\tcomponent.__hooks._pendingEffects.forEach(invokeEffect);\n\t\t\t\tcomponent.__hooks._pendingEffects = [];\n\t\t\t} catch (e) {\n\t\t\t\tcomponent.__hooks._pendingEffects = [];\n\t\t\t\toptions._catchError(e, component._vnode);\n\t\t\t}\n\t\t}\n\t});\n\tafterPaintEffects = [];\n}\n\nlet HAS_RAF = typeof requestAnimationFrame == 'function';\n\n/**\n * Schedule a callback to be invoked after the browser has a chance to paint a new frame.\n * Do this by combining requestAnimationFrame (rAF) + setTimeout to invoke a callback after\n * the next browser frame.\n *\n * Also, schedule a timeout in parallel to the the rAF to ensure the callback is invoked\n * even if RAF doesn't fire (for example if the browser tab is not visible)\n *\n * @param {() => void} callback\n */\nfunction afterNextFrame(callback) {\n\tconst done = () => {\n\t\tclearTimeout(timeout);\n\t\tif (HAS_RAF) cancelAnimationFrame(raf);\n\t\tsetTimeout(callback);\n\t};\n\tconst timeout = setTimeout(done, RAF_TIMEOUT);\n\n\tlet raf;\n\tif (HAS_RAF) {\n\t\traf = requestAnimationFrame(done);\n\t}\n}\n\n// Note: if someone used options.debounceRendering = requestAnimationFrame,\n// then effects will ALWAYS run on the NEXT frame instead of the current one, incurring a ~16ms delay.\n// Perhaps this is not such a big deal.\n/**\n * Schedule afterPaintEffects flush after the browser paints\n * @param {number} newQueueLength\n */\nfunction afterPaint(newQueueLength) {\n\tif (newQueueLength === 1 || prevRaf !== options.requestAnimationFrame) {\n\t\tprevRaf = options.requestAnimationFrame;\n\t\t(prevRaf || afterNextFrame)(flushAfterPaintEffects);\n\t}\n}\n\n/**\n * @param {import('./internal').EffectHookState} hook\n */\nfunction invokeCleanup(hook) {\n\t// A hook cleanup can introduce a call to render which creates a new root, this will call options.vnode\n\t// and move the currentComponent away.\n\tconst comp = currentComponent;\n\tif (typeof hook._cleanup == 'function') hook._cleanup();\n\tcurrentComponent = comp;\n}\n\n/**\n * Invoke a Hook's effect\n * @param {import('./internal').EffectHookState} hook\n */\nfunction invokeEffect(hook) {\n\t// A hook call can introduce a call to render which creates a new root, this will call options.vnode\n\t// and move the currentComponent away.\n\tconst comp = currentComponent;\n\thook._cleanup = hook._value();\n\tcurrentComponent = comp;\n}\n\n/**\n * @param {any[]} oldArgs\n * @param {any[]} newArgs\n */\nfunction argsChanged(oldArgs, newArgs) {\n\treturn (\n\t\t!oldArgs ||\n\t\toldArgs.length !== newArgs.length ||\n\t\tnewArgs.some((arg, index) => arg !== oldArgs[index])\n\t);\n}\n\nfunction invokeOrReturn(arg, f) {\n\treturn typeof f == 'function' ? f(arg) : f;\n}\n","import { DXCAlert } from \"../types/DXCAlert\";\n\nexport function resolveText({message, messageCode, messageParams}: DXCAlert) {\n return message.replace(/\\{\\w+\\}/ig, n => messageParams[n.substr(1, n.length-2)]);\n}\n","import { Dialog } from './Dialog';\nimport { Styles } from './Styles';\nimport { h, Fragment } from 'preact';\nimport { useEffect, useLayoutEffect, useRef, useState } from 'preact/hooks';\nimport {\n DXCGenericUserInteraction,\n DXCUserInteraction,\n} from '../types/DXCUserInteraction';\nimport { resolveText } from '../helpers/resolveText';\nimport { DXCInputField } from '../types/DXCInputField';\n\nexport function LoginDialog({\n title,\n alerts,\n fields,\n onCancel,\n onSubmit,\n}: DXCGenericUserInteraction<string, { [name: string]: DXCInputField }>) {\n const [params, setParams] = useState<{ [param: string]: string }>({});\n\n const firstFieldRef = useRef<HTMLInputElement>();\n useLayoutEffect(()=>firstFieldRef.current?.focus(), []);\n\n return (\n <Dialog>\n <>\n <h3 style={Styles.WindowHeader}>{title}</h3>\n {alerts.map((alert) => (\n <p style={Styles.Alert[alert.type]}>{resolveText(alert)}</p>\n ))}\n <form onSubmit={ev => {\n ev.preventDefault();\n onSubmit(params);\n }}>\n {Object.entries(fields).map(\n ([fieldName, { type, label, placeholder }], idx) => (\n <label style={Styles.Label}>\n {label ? `${label}: ` : ''}\n <input\n ref={idx === 0 ? firstFieldRef : undefined}\n type={type}\n name={fieldName}\n autoComplete=\"on\"\n style={Styles.Input}\n autoFocus\n placeholder={placeholder}\n value={params[fieldName] || ''}\n onInput={(ev) =>\n setParams({ ...params, [fieldName]: valueTransformer(type, ev.target?.['value']) })\n }\n />\n </label>\n )\n )}\n </form>\n </>\n <div style={Styles.ButtonsDiv}>\n <button type=\"submit\" style={Styles.Button} onClick={() => onSubmit(params)}>\n Submit\n </button>\n <button style={Styles.Button} onClick={onCancel}>\n Cancel\n </button>\n </div>\n </Dialog>\n );\n}\n\nfunction valueTransformer(type: string, value: string) {\n switch(type) {\n case \"email\": return value.toLowerCase();\n case \"otp\": return value.toUpperCase();\n default: return value;\n }\n}","import Dexie from \"dexie\";\nimport \"../extend-dexie-interface\";\nimport { h, Component } from \"preact\";\nimport { from, Observer, Subscription } from \"rxjs\";\nimport { LoginDialog } from './LoginDialog';\nimport { Styles } from \"./Styles\";\nimport { DXCGenericUserInteraction, DXCUserInteraction } from \"../types/DXCUserInteraction\";\nimport { DXCInputField } from \"../types/DXCInputField\";\nimport { DexieCloudDB } from \"../db/DexieCloudDB\";\nimport * as preact from \"preact\";\n\nexport interface Props {\n db: Dexie;\n}\n\ninterface State {\n userInteraction: DXCUserInteraction | undefined;\n}\n\nexport default class LoginGui extends Component<Props, State> {\n subscription?: Subscription;\n observer = (userInteraction: DXCUserInteraction | undefined) => this.setState({userInteraction});\n\n constructor(props: Props) {\n super(props);\n this.state = { userInteraction: undefined };\n }\n\n componentDidMount() {\n this.subscription = from(this.props.db.cloud.userInteraction).subscribe(this.observer);\n }\n\n componentWillUnmount() {\n if (this.subscription) {\n this.subscription.unsubscribe();\n delete this.subscription;\n }\n }\n\n render(props: Props, {userInteraction}: State) {\n if (!userInteraction) return null;\n //if (props.db.cloud.userInteraction.observers.length > 1) return null; // Someone else subscribes.\n return <LoginDialog {...userInteraction as DXCGenericUserInteraction<string, {[name: string]: DXCInputField}>} />;\n }\n}\n\nexport function setupDefaultGUI(db: Dexie) {\n const el = document.createElement('div');\n document.body.appendChild(el);\n preact.render(<LoginGui db={db.vip} />, el);\n\n let closed = false;\n\n return {\n unsubscribe() {\n el.remove();\n closed = true;\n },\n get closed() {\n return closed;\n }\n }\n}\n\n// TODO:\n/*\n * Gjort klart allt kring user interaction förutom att mounta default-ui på ett element.\n * Också att kolla först om nån annan subscribar och i så fall inte göra nåt.\n*/","import { combineLatest, Observable, of } from 'rxjs';\nimport { debounceTime, map, startWith, switchMap } from 'rxjs/operators';\nimport { DexieCloudDB } from './db/DexieCloudDB';\nimport { isOnline } from './sync/isOnline';\nimport { SyncState } from './types/SyncState';\nimport { userIsActive, userIsReallyActive } from './userIsActive';\n\nexport function computeSyncState(db: DexieCloudDB): Observable<SyncState> {\n let _prevStatus = db.cloud.webSocketStatus.value;\n const lazyWebSocketStatus = db.cloud.webSocketStatus.pipe(\n switchMap((status) => {\n const prevStatus = _prevStatus;\n _prevStatus = status;\n const rv = of(status);\n switch (status) {\n // A normal scenario is that the WS reconnects and falls shortly in disconnected-->connection-->connected.\n // Don't distract user with this unless these things take more time than normal:\n\n // Only show disconnected if disconnected more than 500ms, or if we can\n // see that the user is indeed not active.\n case 'disconnected':\n return userIsActive.value ? rv.pipe(debounceTime(500)) : rv;\n\n // Only show connecting if previous state was 'not-started' or 'error', or if\n // the time it takes to connect goes beyond 4 seconds.\n case 'connecting':\n return prevStatus === 'not-started' || prevStatus === 'error'\n ? rv\n : rv.pipe(debounceTime(4000));\n default:\n return rv;\n }\n })\n );\n return combineLatest([\n lazyWebSocketStatus,\n db.syncStateChangedEvent.pipe(startWith({ phase: 'initial' } as SyncState)),\n userIsReallyActive\n ]).pipe(\n map(([status, syncState, userIsActive]) => {\n let { phase, error, progress } = syncState;\n let adjustedStatus = status;\n if (phase === 'error') {\n // Let users only rely on the status property to display an icon.\n // If there's an error in the sync phase, let it show on that\n // status icon also.\n adjustedStatus = 'error';\n }\n if (status === 'not-started') {\n // If websocket isn't yet connected becase we're doing\n // the startup sync, let the icon show the symbol for connecting.\n if (phase === 'pushing' || phase === 'pulling') {\n adjustedStatus = 'connecting';\n }\n } \n const previousPhase = db.cloud.syncState.value.phase;\n //const previousStatus = db.cloud.syncState.value.status;\n if (previousPhase === 'error' && (syncState.phase === 'pushing' || syncState.phase === 'pulling')) {\n // We were in an errored state but is now doing sync. Show \"connecting\" icon.\n adjustedStatus = 'connecting';\n }\n /*if (syncState.phase === 'in-sync' && adjustedStatus === 'connecting') {\n adjustedStatus = 'connected';\n }*/\n \n if (!userIsActive) {\n adjustedStatus = 'disconnected';\n }\n\n const retState: SyncState = {\n phase,\n error,\n progress,\n status: isOnline ? adjustedStatus : 'offline',\n };\n\n return retState;\n })\n );\n}\n","import Dexie, { liveQuery, Subscription } from 'dexie';\nimport { getDbNameFromDbUrl } from 'dexie-cloud-common';\nimport { BehaviorSubject, combineLatest, from, fromEvent } from 'rxjs';\nimport { filter, map, skip, startWith, switchMap, take } from 'rxjs/operators';\nimport { login } from './authentication/login';\nimport { UNAUTHORIZED_USER } from './authentication/UNAUTHORIZED_USER';\nimport { DexieCloudDB } from './db/DexieCloudDB';\nimport { PersistedSyncState } from './db/entities/PersistedSyncState';\nimport { DexieCloudOptions } from './DexieCloudOptions';\nimport { DISABLE_SERVICEWORKER_STRATEGY } from './DISABLE_SERVICEWORKER_STRATEGY';\nimport './extend-dexie-interface';\nimport { DexieCloudSyncOptions } from './extend-dexie-interface';\nimport { dbOnClosed } from './helpers/dbOnClosed';\nimport { IS_SERVICE_WORKER } from './helpers/IS_SERVICE_WORKER';\nimport { throwVersionIncrementNeeded } from './helpers/throwVersionIncrementNeeded';\nimport { createIdGenerationMiddleware } from './middlewares/createIdGenerationMiddleware';\nimport { createImplicitPropSetterMiddleware } from './middlewares/createImplicitPropSetterMiddleware';\nimport { createMutationTrackingMiddleware } from './middlewares/createMutationTrackingMiddleware';\n//import { dexieCloudSyncProtocol } from \"./dexieCloudSyncProtocol\";\nimport { overrideParseStoresSpec } from './overrideParseStoresSpec';\nimport { performInitialSync } from './performInitialSync';\nimport { connectWebSocket } from './sync/connectWebSocket';\nimport { isSyncNeeded } from './sync/isSyncNeeded';\nimport { LocalSyncWorker } from './sync/LocalSyncWorker';\nimport {\n registerPeriodicSyncEvent,\n registerSyncEvent,\n} from './sync/registerSyncEvent';\nimport { triggerSync } from './sync/triggerSync';\nimport { DXCUserInteraction } from './types/DXCUserInteraction';\nimport { SyncState } from './types/SyncState';\nimport { updateSchemaFromOptions } from './updateSchemaFromOptions';\nimport { verifySchema } from './verifySchema';\nimport { setupDefaultGUI } from './default-ui';\nimport { DXCWebSocketStatus } from './DXCWebSocketStatus';\nimport { computeSyncState } from './computeSyncState';\n\nexport { DexieCloudTable } from './extend-dexie-interface';\n\nexport function dexieCloud(dexie: Dexie) {\n const origIdbName = dexie.name;\n //\n //\n //\n const currentUserEmitter = new BehaviorSubject(UNAUTHORIZED_USER);\n const subscriptions: Subscription[] = [];\n\n // local sync worker - used when there's no service worker.\n let localSyncWorker: { start: () => void; stop: () => void } | null = null;\n dexie.on(\n 'ready',\n async (dexie: Dexie) => {\n try {\n await onDbReady(dexie);\n } catch (error) {\n console.error(error);\n // Make sure to succeed with database open even if network is down.\n }\n },\n true // true = sticky\n );\n\n /** Void starting subscribers after a close has happened. */\n let closed = false;\n function throwIfClosed() {\n if (closed) throw new Dexie.DatabaseClosedError();\n }\n\n dbOnClosed(dexie, () => {\n subscriptions.forEach((subscription) => subscription.unsubscribe());\n closed = true;\n localSyncWorker && localSyncWorker.stop();\n localSyncWorker = null;\n currentUserEmitter.next(UNAUTHORIZED_USER);\n });\n\n dexie.cloud = {\n version: '{version}',\n options: null,\n schema: null,\n serverState: null,\n get currentUserId() {\n return currentUserEmitter.value.userId || UNAUTHORIZED_USER.userId!;\n },\n currentUser: currentUserEmitter,\n syncState: new BehaviorSubject<SyncState>({\n phase: 'initial',\n status: 'not-started',\n }),\n persistedSyncState: new BehaviorSubject<PersistedSyncState | undefined>(\n undefined\n ),\n userInteraction: new BehaviorSubject<DXCUserInteraction | undefined>(\n undefined\n ),\n webSocketStatus: new BehaviorSubject<DXCWebSocketStatus>('not-started'),\n async login(hint) {\n const db = DexieCloudDB(dexie);\n await db.cloud.sync();\n await login(db, hint);\n },\n configure(options: DexieCloudOptions) {\n dexie.cloud.options = options;\n if (options.databaseUrl) {\n // @ts-ignore\n dexie.name = `${origIdbName}-${getDbNameFromDbUrl(\n options.databaseUrl\n )}`;\n DexieCloudDB(dexie).reconfigure(); // Update observable from new dexie.name\n }\n updateSchemaFromOptions(dexie.cloud.schema, dexie.cloud.options);\n },\n async sync(\n { wait, purpose }: DexieCloudSyncOptions = { wait: true, purpose: \"push\" }\n ) {\n if (wait === undefined) wait = true;\n const db = DexieCloudDB(dexie);\n if (purpose === \"pull\") {\n const syncState = db.cloud.persistedSyncState.value;\n triggerSync(db, purpose);\n if (wait) {\n const newSyncState = await db.cloud.persistedSyncState\n .pipe(\n filter(\n (newSyncState) =>\n newSyncState?.timestamp != null &&\n (!syncState || newSyncState.timestamp > syncState.timestamp!)\n ),\n take(1)\n )\n .toPromise();\n if (newSyncState?.error) {\n throw new Error(`Sync error: ` + newSyncState.error);\n }\n }\n } else if (await isSyncNeeded(db)) {\n const syncState = db.cloud.persistedSyncState.value;\n triggerSync(db, purpose);\n if (wait) {\n console.debug('db.cloud.login() is waiting for sync completion...');\n await from(\n liveQuery(async () => {\n const syncNeeded = await isSyncNeeded(db);\n const newSyncState = await db.getPersistedSyncState();\n if (\n newSyncState?.timestamp !== syncState?.timestamp &&\n newSyncState?.error\n )\n throw new Error(`Sync error: ` + newSyncState.error);\n return syncNeeded;\n })\n )\n .pipe(\n filter((isNeeded) => !isNeeded),\n take(1)\n )\n .toPromise();\n console.debug(\n 'Done waiting for sync completion because we have nothing to push anymore'\n );\n }\n }\n },\n };\n\n dexie.Version.prototype['_parseStoresSpec'] = Dexie.override(\n dexie.Version.prototype['_parseStoresSpec'],\n (origFunc) => overrideParseStoresSpec(origFunc, dexie)\n );\n\n dexie.use(\n createMutationTrackingMiddleware({\n currentUserObservable: dexie.cloud.currentUser,\n db: DexieCloudDB(dexie),\n })\n );\n dexie.use(createImplicitPropSetterMiddleware(DexieCloudDB(dexie)));\n dexie.use(createIdGenerationMiddleware(DexieCloudDB(dexie)));\n\n async function onDbReady(dexie: Dexie) {\n closed = false; // As Dexie calls us, we are not closed anymore. Maybe reopened? Remember db.ready event is registered with sticky flag!\n const db = DexieCloudDB(dexie);\n // Setup default GUI:\n if (!IS_SERVICE_WORKER) {\n if (!db.cloud.options?.customLoginGui) {\n subscriptions.push(setupDefaultGUI(dexie));\n }\n subscriptions.push(computeSyncState(db).subscribe(dexie.cloud.syncState));\n }\n\n //verifyConfig(db.cloud.options); Not needed (yet at least!)\n // Verify the user has allowed version increment.\n if (!db.tables.every((table) => table.core)) {\n throwVersionIncrementNeeded();\n }\n const swRegistrations =\n 'serviceWorker' in navigator\n ? await navigator.serviceWorker.getRegistrations()\n : [];\n\n const initiallySynced = await db.transaction(\n 'rw',\n db.$syncState,\n async () => {\n const { options, schema } = db.cloud;\n const [persistedOptions, persistedSchema, persistedSyncState] =\n await Promise.all([\n db.getOptions(),\n db.getSchema(),\n db.getPersistedSyncState(),\n ]);\n if (!options) {\n // Options not specified programatically (use case for SW!)\n // Take persisted options:\n db.cloud.options = persistedOptions || null;\n } else if (\n !persistedOptions ||\n JSON.stringify(persistedOptions) !== JSON.stringify(options)\n ) {\n // Update persisted options:\n await db.$syncState.put(options, 'options');\n }\n if (\n db.cloud.options?.tryUseServiceWorker &&\n 'serviceWorker' in navigator &&\n swRegistrations.length > 0 &&\n !DISABLE_SERVICEWORKER_STRATEGY\n ) {\n // * Configured for using service worker if available.\n // * Browser supports service workers\n // * There are at least one service worker registration\n console.debug('Dexie Cloud Addon: Using service worker');\n db.cloud.usingServiceWorker = true;\n } else {\n // Not configured for using service worker or no service worker\n // registration exists. Don't rely on service worker to do any job.\n // Use LocalSyncWorker instead.\n if (db.cloud.options?.tryUseServiceWorker && !IS_SERVICE_WORKER) {\n console.debug(\n 'dexie-cloud-addon: Not using service worker.',\n swRegistrations.length === 0\n ? 'No SW registrations found.'\n : 'serviceWorker' in navigator && DISABLE_SERVICEWORKER_STRATEGY\n ? 'Avoiding SW background sync and SW periodic bg sync for this browser due to browser bugs.'\n : 'navigator.serviceWorker not present'\n );\n }\n db.cloud.usingServiceWorker = false;\n }\n updateSchemaFromOptions(schema, db.cloud.options);\n updateSchemaFromOptions(persistedSchema, db.cloud.options);\n if (!schema) {\n // Database opened dynamically (use case for SW!)\n // Take persisted schema:\n db.cloud.schema = persistedSchema || null;\n } else if (\n !persistedSchema ||\n JSON.stringify(persistedSchema) !== JSON.stringify(schema)\n ) {\n // Update persisted schema (but don't overwrite table prefixes)\n const newPersistedSchema = persistedSchema || {};\n for (const [table, tblSchema] of Object.entries(schema)) {\n const newTblSchema = newPersistedSchema[table];\n if (!newTblSchema) {\n newPersistedSchema[table] = { ...tblSchema };\n } else {\n newTblSchema.markedForSync = tblSchema.markedForSync;\n tblSchema.deleted = newTblSchema.deleted;\n newTblSchema.generatedGlobalId = tblSchema.generatedGlobalId;\n }\n }\n await db.$syncState.put(newPersistedSchema, 'schema');\n\n // Make sure persisted table prefixes are being used instead of computed ones:\n // Let's assign all props as the newPersistedSchems should be what we should be working with.\n Object.assign(schema, newPersistedSchema);\n }\n return persistedSyncState?.initiallySynced;\n }\n );\n\n if (initiallySynced) {\n db.setInitiallySynced(true);\n }\n\n verifySchema(db);\n\n if (db.cloud.options?.databaseUrl && !initiallySynced) {\n await performInitialSync(db, db.cloud.options, db.cloud.schema!);\n db.setInitiallySynced(true);\n }\n\n // Manage CurrentUser observable:\n throwIfClosed();\n if (!IS_SERVICE_WORKER) {\n subscriptions.push(\n liveQuery(() => db.getCurrentUser()).subscribe(currentUserEmitter)\n );\n // Manage PersistendSyncState observable:\n subscriptions.push(\n liveQuery(() => db.getPersistedSyncState()).subscribe(\n db.cloud.persistedSyncState\n )\n );\n // Wait till currentUser and persistedSyncState gets populated\n // with things from the database and not just the default values.\n // This is so that when db.open() completes, user should be safe\n // to subscribe to these observables and get actual data.\n await combineLatest([\n currentUserEmitter.pipe(skip(1), take(1)),\n db.cloud.persistedSyncState.pipe(skip(1), take(1))\n ]).toPromise();\n }\n\n // HERE: If requireAuth, do athentication now.\n if (db.cloud.options?.requireAuth) {\n await login(db);\n }\n\n if (localSyncWorker) localSyncWorker.stop();\n localSyncWorker = null;\n throwIfClosed();\n if (db.cloud.usingServiceWorker && db.cloud.options?.databaseUrl) {\n registerSyncEvent(db, \"push\").catch(() => {});\n registerPeriodicSyncEvent(db).catch(() => {});\n } else if (\n db.cloud.options?.databaseUrl &&\n db.cloud.schema &&\n !IS_SERVICE_WORKER\n ) {\n // There's no SW. Start SyncWorker instead.\n localSyncWorker = LocalSyncWorker(db, db.cloud.options, db.cloud.schema!);\n localSyncWorker.start();\n triggerSync(db, \"push\");\n }\n\n // Listen to online event and do sync.\n throwIfClosed();\n if (!IS_SERVICE_WORKER) {\n subscriptions.push(\n fromEvent(self, 'online').subscribe(() => {\n console.debug('online!');\n db.syncStateChangedEvent.next({\n phase: 'not-in-sync',\n });\n triggerSync(db, \"push\");\n }),\n fromEvent(self, 'offline').subscribe(() => {\n console.debug('offline!');\n db.syncStateChangedEvent.next({\n phase: 'offline',\n });\n })\n );\n }\n\n // Connect WebSocket only if we're a browser window\n if (\n typeof window !== 'undefined' &&\n !IS_SERVICE_WORKER &&\n db.cloud.options?.databaseUrl\n ) {\n subscriptions.push(connectWebSocket(db));\n }\n }\n}\n\ndexieCloud.version = '{version}';\n\nDexie.Cloud = dexieCloud;\n\n//Dexie.addons.push(dexieCloud);\n\nexport default dexieCloud;\n","import Dexie from 'dexie';\nimport { DexieCloudDB } from './db/DexieCloudDB';\nimport dexieCloud from './dexie-cloud-client';\nimport { DISABLE_SERVICEWORKER_STRATEGY } from './DISABLE_SERVICEWORKER_STRATEGY';\nimport { isSafari, safariVersion } from './isSafari';\nimport { syncIfPossible } from './sync/syncIfPossible';\nimport { SWMessageEvent } from './types/SWMessageEvent';\nimport { SyncEvent } from './types/SWSyncEvent';\n\n// In case the SW lives for a while, let it reuse already opened connections:\nconst managedDBs = new Map<string, DexieCloudDB>();\n\nfunction getDbNameFromTag(tag: string) {\n return tag.startsWith('dexie-cloud:') && tag.split(':')[1];\n}\n\nconst syncDBSemaphore = new Map<string, Promise<void>>();\n\nfunction syncDB(dbName: string, purpose: 'push' | 'pull') {\n // We're taking hight for being double-signalled both\n // via message event and sync event.\n // Which one comes first doesnt matter, just\n // that we return the existing promise if there is\n // an ongoing sync.\n let promise = syncDBSemaphore.get(dbName + '/' + purpose);\n if (!promise) {\n promise = _syncDB(dbName, purpose)\n .then(() => {\n // When legacy enough across browsers, use .finally() instead of then() and catch():\n syncDBSemaphore.delete(dbName + '/' + purpose);\n })\n .catch((error) => {\n syncDBSemaphore.delete(dbName + '/' + purpose);\n return Promise.reject(error);\n });\n syncDBSemaphore.set(dbName + '/' + purpose, promise);\n }\n return promise;\n\n async function _syncDB(dbName: string, purpose: 'push' | 'pull') {\n let db = managedDBs.get(dbName);\n\n if (!db) {\n console.debug('Dexie Cloud SW: Creating new Dexie instance for', dbName);\n const dexie = new Dexie(dbName, { addons: [dexieCloud] });\n db = DexieCloudDB(dexie);\n dexie.on('versionchange', stopManagingDB);\n await db.dx.open(); // Makes sure db.cloud.options and db.cloud.schema are read from db,\n if (!managedDBs.get(dbName)) {\n // Avoid race conditions.\n managedDBs.set(dbName, db);\n }\n }\n if (!db.cloud.options?.databaseUrl) {\n console.error(`Dexie Cloud: No databaseUrl configured`);\n return; // Nothing to sync.\n }\n if (!db.cloud.schema) {\n console.error(`Dexie Cloud: No schema persisted`);\n return; // Nothing to sync.\n }\n\n function stopManagingDB() {\n db!.dx.on.versionchange.unsubscribe(stopManagingDB);\n if (managedDBs.get(db!.name) === db) {\n // Avoid race conditions.\n managedDBs.delete(db!.name);\n }\n db!.dx.close();\n return false;\n }\n\n try {\n console.debug('Dexie Cloud SW: Syncing');\n await syncIfPossible(db, db.cloud.options, db.cloud.schema, {\n retryImmediatelyOnFetchError: true,\n purpose,\n });\n console.debug('Dexie Cloud SW: Done Syncing');\n } catch (e) {\n console.error(`Dexie Cloud SW Error`, e);\n // Error occured. Stop managing this DB until we wake up again by a sync event,\n // which will open a new Dexie and start trying to sync it.\n stopManagingDB();\n if (e.name !== Dexie.errnames.NoSuchDatabase) {\n // Unless the error was that DB doesn't exist, rethrow to trigger sync retry.\n throw e; // Throw e to make syncEvent.waitUntil() receive a rejected promis, so it will retry.\n }\n }\n }\n}\n\n// Avoid taking care of events if browser bugs out by using dexie cloud from a service worker.\nif (!DISABLE_SERVICEWORKER_STRATEGY) {\n self.addEventListener('sync', (event: SyncEvent) => {\n console.debug('SW \"sync\" Event', event.tag);\n const dbName = getDbNameFromTag(event.tag);\n if (dbName) {\n event.waitUntil(syncDB(dbName, \"push\")); // The purpose of sync events are \"push\"\n }\n });\n\n self.addEventListener('periodicsync', (event: SyncEvent) => {\n console.debug('SW \"periodicsync\" Event', event.tag);\n const dbName = getDbNameFromTag(event.tag);\n if (dbName) {\n event.waitUntil(syncDB(dbName, \"pull\")); // The purpose of periodic sync events are \"pull\"\n }\n });\n\n self.addEventListener('message', (event: SWMessageEvent) => {\n console.debug('SW \"message\" Event', event.data);\n if (event.data.type === 'dexie-cloud-sync') {\n const { dbName } = event.data;\n // Mimic background sync behavior - retry in X minutes on failure.\n // But lesser timeout and more number of times.\n const syncAndRetry = (num = 1) => {\n return syncDB(dbName, event.data.purpuse || \"pull\").catch(async (e) => {\n if (num === 3) throw e;\n await sleep(60_000); // 1 minute\n syncAndRetry(num + 1);\n });\n };\n if ('waitUntil' in event) {\n event.waitUntil(syncAndRetry().catch(error => console.error(error)));\n } else {\n syncAndRetry().catch(error => console.error(error));\n }\n }\n });\n}\n\nfunction sleep(ms: number) {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n"],"names":["Observable","tslib_1.__extends","iterator","observable","Symbol_iterator","this","bigintDef","tsonBuiltinDefs","randomString","Dexie","BehaviorSubject","wm","Subject","counter","from","liveQuery","of","fromEvent","merge","Subscription","sleep","throwError","options","rerenderQueue","defer","prevDebounce","EMPTY_OBJ","EMPTY_ARR","IS_NON_DIMENSIONAL","assign","obj","props","i","removeNode","node","parentNode","removeChild","createElement","type","children","key","ref","normalizedProps","arguments","length","push","defaultProps","undefined","createVNode","original","vnode","constructor","Fragment","Component","context","getDomSibling","childIndex","indexOf","sibling","updateParentDomPointers","child","base","enqueueRender","c","process","debounceRendering","queue","sort","a","b","some","component","commitQueue","oldVNode","oldDom","parentDom","diff","ownerSVGElement","commitRoot","diffChildren","renderResult","newParentVNode","oldParentVNode","globalContext","isSvg","excessDomChildren","isHydrating","j","childVNode","newDom","firstChildDom","refs","oldChildren","oldChildrenLength","Array","isArray","reorderChildren","placeChild","value","unmount","applyRef","tmp","nextDom","sibDom","outer","appendChild","nextSibling","insertBefore","diffProps","dom","newProps","oldProps","hydrate","setProperty","setStyle","style","test","name","oldValue","useCapture","o","cssText","replace","toLowerCase","slice","_listeners","addEventListener","eventProxyCapture","eventProxy","removeEventListener","e","setAttribute","removeAttribute","event","newVNode","isNew","oldState","snapshot","clearProcessingException","provider","componentContext","newType","contextType","prototype","render","doRender","sub","state","getDerivedStateFromProps","componentWillMount","componentDidMount","componentWillReceiveProps","shouldComponentUpdate","forEach","componentWillUpdate","componentDidUpdate","getChildContext","getSnapshotBeforeUpdate","diffElementNodes","diffed","root","cb","call","oldHtml","newHtml","nodeType","localName","document","createTextNode","createElementNS","is","data","childNodes","dangerouslySetInnerHTML","attributes","innerHTML","firstChild","checked","current","parentVNode","skipRemove","r","componentWillUnmount","replaceNode","error","ctor","handled","getDerivedStateFromError","setState","componentDidCatch","update","callback","s","forceUpdate","Promise","then","bind","resolve","setTimeout","h","currentIndex","currentComponent","prevRaf","currentHook","afterPaintEffects","oldBeforeDiff","oldBeforeRender","oldAfterDiff","oldCommit","oldBeforeUnmount","getHookState","index","hooks","useState","initialState","useReducer","invokeOrReturn","reducer","init","hookState","_reducer","action","nextValue","useLayoutEffect","args","argsChanged","useRef","initialValue","useMemo","factory","flushAfterPaintEffects","invokeCleanup","invokeEffect","requestAnimationFrame","raf","done","clearTimeout","timeout","HAS_RAF","cancelAnimationFrame","previousComponent","filter","hook","comp","oldArgs","newArgs","arg","f","preact.render","combineLatest"],"mappings":";;;;;;;;;;IAEO,MAAM,iBAAiB,GAAc;QAC1C,MAAM,EAAE,cAAc;QACtB,IAAI,EAAE,cAAc;QACpB,MAAM,EAAE;YACN,GAAG,EAAE,cAAc;SACpB;QACD,SAAS,EAAE,IAAI,IAAI,CAAC,CAAC,CAAC;KACvB,CAAA;IAED,IAAI;QACF,MAAM,CAAC,MAAM,CAAC,iBAAiB,CAAC,CAAC;QACjC,MAAM,CAAC,MAAM,CAAC,iBAAiB,CAAC,MAAM,CAAC,CAAC;KACzC;IAAC,WAAM;;ICdR,MAAM,QAAQ,GAAiD,EAAE,CAAC;IAClE,MAAM,WAAW,GAAG,IAAI,CAAC,QAAQ,IAAI,SA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AAoB,EAAE,KAAK,CAAC,IAAI,CAAC,CAAC;YAChD,IAAI,KAAK,CAAC,IAAI,CAAC,IAAI,KAAK,kBAAkB,EAAE;gBAC1C,MAAM,EAAE,MAAM,EAAE,GAAG,KAAK,CAAC,IAAI,CAAC;;;gBAG9B,MAAM,YAAY,GAAG,CAAC,GAAG,GAAG,CAAC;oBAC3B,OAAO,MAAM,CAAC,MAAM,EAAE,KAAK,CAAC,IAAI,CAAC,OAAO,IAAI,MAAM,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC;wBAChE,IAAI,GAAG,KAAK,CAAC;4BAAE,MAAM,CAAC,CAAC;wBACvB,MAAM,KAAK,CAAC,KAAM,CAAC,CAAC;wBACpB,YAAY,CAAC,GAAG,GAAG,CAAC,CAAC,CAAC;qBACvB,CAAC,CAAC;iBACJ,CAAC;gBACF,IAAI,WAAW,IAAI,KAAK,EAAE;oBACxB,KAAK,CAAC,SAAS,CAAC,YAAY,EAAE,CAAC,KAAK,CAAC,KAAK,IAAI,OAAO,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC;iBACtE;qBAAM;oBACL,YAAY,EAAE,CAAC,KAAK,CAAC,KAAK,IAAI,OAAO,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC,CAAC;iBACrD;aACF;SACF,CAAC,CAAC;KACJ;IAED,SAAS,KAAK,CAAC,EAAU;QACvB,OAAO,IAAI,OAAO,CAAC,CAAC,OAAO,KAAK,UAAU,CAAC,OAAO,EAAE,EAAE,CAAC,CAAC,CAAC;IAC3D;;;;;;"}
1
+ {"version":3,"file":"service-worker.js","sources":["../../src/authentication/UNAUTHORIZED_USER.ts","../../src/helpers/SWBroadcastChannel.ts","../../src/helpers/BroadcastedAndLocalEvent.ts","../../node_modules/rxjs/node_modules/tslib/tslib.es6.js","../../node_modules/rxjs/src/internal/util/isFunction.ts","../../node_modules/rxjs/src/internal/config.ts","../../node_modules/rxjs/src/internal/util/hostReportError.ts","../../node_modules/rxjs/src/internal/Observer.ts","../../node_modules/rxjs/src/internal/util/isArray.ts","../../node_modules/rxjs/src/internal/util/isObject.ts","../../node_modules/rxjs/src/internal/util/UnsubscriptionError.ts","../../node_modules/rxjs/src/internal/Subscription.ts","../../node_modules/rxjs/src/internal/symbol/rxSubscriber.ts","../../node_modules/rxjs/src/internal/Subscriber.ts","../../node_modules/rxjs/src/internal/util/canReportError.ts","../../node_modules/rxjs/src/internal/util/toSubscriber.ts","../../node_modules/rxjs/src/internal/symbol/observable.ts","../../node_modules/rxjs/src/internal/util/identity.ts","../../node_modules/rxjs/src/internal/util/pipe.ts","../../node_modules/rxjs/src/internal/Observable.ts","../../node_modules/rxjs/src/internal/util/subscribeToArray.ts","../../node_modules/rxjs/src/internal/util/subscribeToPromise.ts","../../node_modules/rxjs/src/internal/symbol/iterator.ts","../../node_modules/rxjs/src/internal/util/subscribeToIterable.ts","../../node_modules/rxjs/src/internal/util/subscribeToObservable.ts","../../node_modules/rxjs/src/internal/util/isArrayLike.ts","../../node_modules/rxjs/src/internal/util/isPromise.ts","../../node_modules/rxjs/src/internal/util/subscribeTo.ts","../../node_modules/rxjs/src/internal/innerSubscribe.ts","../../node_modules/rxjs/src/internal/scheduler/Action.ts","../../node_modules/rxjs/src/internal/scheduler/AsyncAction.ts","../../node_modules/rxjs/src/internal/Scheduler.ts","../../node_modules/rxjs/src/internal/scheduler/AsyncScheduler.ts","../../node_modules/rxjs/src/internal/scheduler/async.ts","../../node_modules/rxjs/src/internal/util/isScheduler.ts","../../node_modules/rxjs/src/internal/operators/catchError.ts","../../node_modules/rxjs/src/internal/scheduled/scheduleArray.ts","../../node_modules/rxjs/src/internal/observable/fromArray.ts","../../node_modules/rxjs/src/internal/scheduled/scheduleObservable.ts","../../node_modules/rxjs/src/internal/scheduled/schedulePromise.ts","../../node_modules/rxjs/src/internal/scheduled/scheduleIterable.ts","../../node_modules/rxjs/src/internal/util/isInteropObservable.ts","../../node_modules/rxjs/src/internal/util/isIterable.ts","../../node_modules/rxjs/src/internal/scheduled/scheduled.ts","../../node_modules/rxjs/src/internal/observable/from.ts","../../node_modules/rxjs/src/internal/observable/of.ts","../../node_modules/rxjs/src/internal/operators/map.ts","../../node_modules/rxjs/src/internal/operators/mergeMap.ts","../../node_modules/rxjs/src/internal/operators/mergeAll.ts","../../node_modules/rxjs/src/internal/operators/concatAll.ts","../../node_modules/rxjs/src/internal/observable/concat.ts","../../node_modules/rxjs/src/internal/operators/debounceTime.ts","../../node_modules/rxjs/src/internal/util/isDate.ts","../../node_modules/rxjs/src/internal/observable/empty.ts","../../node_modules/rxjs/src/internal/observable/throwError.ts","../../node_modules/rxjs/src/internal/Notification.ts","../../node_modules/rxjs/src/internal/operators/delay.ts","../../node_modules/rxjs/src/internal/operators/distinctUntilChanged.ts","../../node_modules/rxjs/src/internal/util/ArgumentOutOfRangeError.ts","../../node_modules/rxjs/src/internal/operators/filter.ts","../../node_modules/rxjs/src/internal/operators/take.ts","../../node_modules/rxjs/src/internal/operators/skip.ts","../../node_modules/rxjs/src/internal/operators/startWith.ts","../../node_modules/rxjs/src/internal/operators/switchMap.ts","../../node_modules/rxjs/src/internal/util/noop.ts","../../node_modules/rxjs/src/internal/operators/tap.ts","../../node_modules/rxjs/src/internal/util/TimeoutError.ts","../../node_modules/rxjs/src/internal/operators/timeoutWith.ts","../../node_modules/rxjs/src/internal/operators/timeout.ts","../../src/sync/registerSyncEvent.ts","../../src/sync/triggerSync.ts","../../node_modules/dreambase-library/dist/common/base64.js","../../src/helpers/computeRealmSetHash.ts","../../src/helpers/getSyncableTables.ts","../../src/helpers/getMutationTable.ts","../../src/helpers/getTableFromMutationTable.ts","../../src/sync/listClientChanges.ts","../../node_modules/universal-imports/index-browser.mjs","../../node_modules/dexie-cloud-common/dist/utils.js","../../node_modules/dexie-cloud-common/dist/validation/isValidSyncableID.js","../../node_modules/dexie-cloud-common/dist/change-processing/applyOperation.js","../../node_modules/dexie-cloud-common/dist/change-processing/applyOperations.js","../../node_modules/dexie-cloud-common/dist/change-processing/subtractChanges.js","../../node_modules/dexie-cloud-common/dist/change-processing/toDBOperationSet.js","../../node_modules/dexie-cloud-common/dist/getDbNameFromDbUrl.js","../../src/sync/listSyncifiedChanges.ts","../../src/sync/getTablesToSyncify.ts","../../src/authentication/interactWithUser.ts","../../src/authentication/authenticate.ts","../../node_modules/dreambase-library/dist/typeson-simplified/TypesonSimplified.js","../../node_modules/dreambase-library/dist/typeson-simplified/BisonBinaryTypes.js","../../node_modules/dreambase-library/dist/typeson-simplified/types/number.js","../../node_modules/dreambase-library/dist/typeson-simplified/types/bigint.js","../../node_modules/dreambase-library/dist/typeson-simplified/types/Date.js","../../node_modules/dreambase-library/dist/typeson-simplified/types/Set.js","../../node_modules/dreambase-library/dist/typeson-simplified/types/Map.js","../../node_modules/dreambase-library/dist/common/_global.js","../../node_modules/dreambase-library/dist/typeson-simplified/types/TypedArray.js","../../node_modules/dreambase-library/dist/common/b64lex.js","../../node_modules/dreambase-library/dist/typeson-simplified/types/ArrayBuffer.js","../../node_modules/dreambase-library/dist/typeson-simplified/FakeBlob.js","../../node_modules/dreambase-library/dist/typeson-simplified/readBlobSync.js","../../node_modules/dreambase-library/dist/typeson-simplified/string2arraybuffer.js","../../node_modules/dreambase-library/dist/typeson-simplified/types/Blob.js","../../node_modules/dreambase-library/dist/typeson-simplified/presets/builtin.js","../../node_modules/dreambase-library/dist/typeson-simplified/Bison.js","../../node_modules/dreambase-library/dist/typeson-simplified/types/undefined.js","../../src/TSON.ts","../../src/errors/HttpError.ts","../../src/sync/syncWithServer.ts","../../src/sync/modifyLocalObjectsWithNewUserId.ts","../../src/helpers/bulkUpdate.ts","../../src/helpers/CancelToken.ts","../../src/sync/isOnline.ts","../../src/sync/updateBaseRevs.ts","../../src/sync/getLatestRevisionsPerTable.ts","../../src/sync/sync.ts","../../src/sync/messagesFromServerQueue.ts","../../src/db/DexieCloudDB.ts","../../src/authentication/AuthPersistedContext.ts","../../src/authentication/otpFetchTokenCallback.ts","../../src/authentication/setCurrentUser.ts","../../src/authentication/login.ts","../../src/isFirefox.ts","../../src/isSafari.ts","../../src/DISABLE_SERVICEWORKER_STRATEGY.ts","../../src/helpers/dbOnClosed.ts","../../src/helpers/IS_SERVICE_WORKER.ts","../../src/helpers/throwVersionIncrementNeeded.ts","../../src/middlewares/createIdGenerationMiddleware.ts","../../src/middlewares/createImplicitPropSetterMiddleware.ts","../../src/helpers/randomString.ts","../../src/helpers/allSettled.ts","../../src/middleware-helpers/guardedTable.ts","../../src/middlewares/outstandingTransaction.ts","../../src/middlewares/createMutationTrackingMiddleware.ts","../../src/overrideParseStoresSpec.ts","../../src/helpers/date-constants.ts","../../src/sync/myId.ts","../../src/sync/performGuardedJob.ts","../../src/performInitialSync.ts","../../src/userIsActive.ts","../../src/authentication/TokenExpiredError.ts","../../src/WSObservable.ts","../../src/sync/connectWebSocket.ts","../../src/sync/isSyncNeeded.ts","../../src/sync/syncIfPossible.ts","../../src/sync/LocalSyncWorker.ts","../../src/updateSchemaFromOptions.ts","../../src/verifySchema.ts","../../node_modules/preact/src/options.js","../../node_modules/preact/src/component.js","../../node_modules/preact/src/constants.js","../../node_modules/preact/src/util.js","../../node_modules/preact/src/create-element.js","../../node_modules/preact/src/diff/children.js","../../node_modules/preact/src/diff/props.js","../../node_modules/preact/src/diff/index.js","../../node_modules/preact/src/render.js","../../node_modules/preact/src/diff/catch-error.js","../../node_modules/preact/src/create-context.js","../../src/default-ui/Styles.ts","../../src/default-ui/Dialog.tsx","../../node_modules/preact/hooks/src/index.js","../../src/helpers/resolveText.ts","../../src/default-ui/LoginDialog.tsx","../../src/default-ui/index.tsx","../../src/computeSyncState.ts","../../src/dexie-cloud-client.ts","../../src/service-worker.ts"],"sourcesContent":["import { UserLogin } from '../db/entities/UserLogin';\n\nexport const UNAUTHORIZED_USER: UserLogin = {\n userId: \"unauthorized\",\n name: \"Unauthorized\",\n claims: {\n sub: \"unauthorized\",\n },\n lastLogin: new Date(0)\n}\n\ntry {\n Object.freeze(UNAUTHORIZED_USER);\n Object.freeze(UNAUTHORIZED_USER.claims);\n} catch {}\n","const swHolder: { registration?: ServiceWorkerRegistration } = {};\nconst swContainer = self.document && navigator.serviceWorker; // self.document is to verify we're not the SW ourself\nif (swContainer)\n swContainer.ready.then(\n (registration) => (swHolder.registration = registration)\n );\n\nif (typeof self !== 'undefined' && 'clients' in self && !self.document) {\n // We are the service worker. Propagate messages to all our clients.\n addEventListener('message', (ev: any) => {\n if (ev.data?.type?.startsWith('sw-broadcast-')) {\n [...self['clients'].matchAll({ includeUncontrolled: true })].forEach(\n (client) => client.id !== ev.source?.id && client.postMessage(ev.data)\n );\n }\n });\n}\n\nexport class SWBroadcastChannel {\n name: string;\n constructor(name: string) {\n this.name = name;\n }\n subscribe(listener: (message: any) => void) {\n if (!swContainer) return ()=>{};\n const forwarder = (ev: MessageEvent) => {\n if (ev.data?.type === `sw-broadcast-${this.name}`) {\n listener(ev.data.message);\n }\n };\n swContainer.addEventListener('message', forwarder);\n return () =>\n swContainer.removeEventListener('message', forwarder);\n }\n postMessage(message: any) {\n if (typeof self['clients'] === 'object') {\n // We're a service worker. Propagate to our browser clients.\n [...self['clients'].matchAll({ includeUncontrolled: true })].forEach(\n (client) =>\n client.postMessage({\n type: `sw-broadcast-${this.name}`,\n message\n })\n );\n } else if (swHolder.registration) {\n // We're a client (browser window or other worker)\n // Post to SW so it can repost to all its clients and to itself\n swHolder.registration.active?.postMessage({\n type: `sw-broadcast-${this.name}`,\n message\n });\n }\n }\n}\n","import { Observable } from \"rxjs\";\nimport { SWBroadcastChannel } from \"./SWBroadcastChannel\";\n\nexport class BroadcastedAndLocalEvent<T> extends Observable<T>{\n name: string;\n bc: BroadcastChannel | SWBroadcastChannel\n\n constructor(name: string) {\n const bc = typeof BroadcastChannel === \"undefined\"\n ? new SWBroadcastChannel(name) : new BroadcastChannel(name);\n super(subscriber => {\n function onCustomEvent(ev: CustomEvent) {\n subscriber.next(ev.detail);\n }\n function onMessageEvent(ev: MessageEvent) {\n console.debug(\"BroadcastedAndLocalEvent: onMessageEvent\", ev);\n subscriber.next(ev.data);\n }\n let unsubscribe: ()=>void;\n self.addEventListener(`lbc-${name}`, onCustomEvent); \n if (bc instanceof SWBroadcastChannel) {\n unsubscribe = bc.subscribe(message => subscriber.next(message));\n } else {\n console.debug(\"BroadcastedAndLocalEvent: bc.addEventListener()\", name, \"bc is a\", bc);\n bc.addEventListener(\"message\", onMessageEvent);\n }\n return () => {\n self.removeEventListener(`lbc-${name}`, onCustomEvent);\n if (bc instanceof SWBroadcastChannel) {\n unsubscribe!();\n } else {\n bc.removeEventListener(\"message\", onMessageEvent);\n }\n }\n });\n this.name = name;\n this.bc = bc;\n }\n\n next(message: T) {\n console.debug(\"BroadcastedAndLocalEvent: bc.postMessage()\", {...message}, \"bc is a\", this.bc);\n this.bc.postMessage(message);\n const ev = new CustomEvent(`lbc-${this.name}`, { detail: message });\n self.dispatchEvent(ev);\n }\n}\n","/*! *****************************************************************************\r\nCopyright (c) Microsoft Corporation.\r\n\r\nPermission to use, copy, modify, and/or distribute this software for any\r\npurpose with or without fee is hereby granted.\r\n\r\nTHE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH\r\nREGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY\r\nAND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,\r\nINDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM\r\nLOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR\r\nOTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR\r\nPERFORMANCE OF THIS SOFTWARE.\r\n***************************************************************************** */\r\n/* global Reflect, Promise */\r\n\r\nvar extendStatics = function(d, b) {\r\n extendStatics = Object.setPrototypeOf ||\r\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\r\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\r\n return extendStatics(d, b);\r\n};\r\n\r\nexport function __extends(d, b) {\r\n extendStatics(d, b);\r\n function __() { this.constructor = d; }\r\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\r\n}\r\n\r\nexport var __assign = function() {\r\n __assign = Object.assign || function __assign(t) {\r\n for (var s, i = 1, n = arguments.length; i < n; i++) {\r\n s = arguments[i];\r\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];\r\n }\r\n return t;\r\n }\r\n return __assign.apply(this, arguments);\r\n}\r\n\r\nexport function __rest(s, e) {\r\n var t = {};\r\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\r\n t[p] = s[p];\r\n if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\r\n for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {\r\n if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))\r\n t[p[i]] = s[p[i]];\r\n }\r\n return t;\r\n}\r\n\r\nexport function __decorate(decorators, target, key, desc) {\r\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\r\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\r\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\r\n return c > 3 && r && Object.defineProperty(target, key, r), r;\r\n}\r\n\r\nexport function __param(paramIndex, decorator) {\r\n return function (target, key) { decorator(target, key, paramIndex); }\r\n}\r\n\r\nexport function __metadata(metadataKey, metadataValue) {\r\n if (typeof Reflect === \"object\" && typeof Reflect.metadata === \"function\") return Reflect.metadata(metadataKey, metadataValue);\r\n}\r\n\r\nexport function __awaiter(thisArg, _arguments, P, generator) {\r\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\r\n return new (P || (P = Promise))(function (resolve, reject) {\r\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\r\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\r\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\r\n step((generator = generator.apply(thisArg, _arguments || [])).next());\r\n });\r\n}\r\n\r\nexport function __generator(thisArg, body) {\r\n var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;\r\n return g = { next: verb(0), \"throw\": verb(1), \"return\": verb(2) }, typeof Symbol === \"function\" && (g[Symbol.iterator] = function() { return this; }), g;\r\n function verb(n) { return function (v) { return step([n, v]); }; }\r\n function step(op) {\r\n if (f) throw new TypeError(\"Generator is already executing.\");\r\n while (_) try {\r\n if (f = 1, y && (t = op[0] & 2 ? y[\"return\"] : op[0] ? y[\"throw\"] || ((t = y[\"return\"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;\r\n if (y = 0, t) op = [op[0] & 2, t.value];\r\n switch (op[0]) {\r\n case 0: case 1: t = op; break;\r\n case 4: _.label++; return { value: op[1], done: false };\r\n case 5: _.label++; y = op[1]; op = [0]; continue;\r\n case 7: op = _.ops.pop(); _.trys.pop(); continue;\r\n default:\r\n if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\r\n if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\r\n if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\r\n if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\r\n if (t[2]) _.ops.pop();\r\n _.trys.pop(); continue;\r\n }\r\n op = body.call(thisArg, _);\r\n } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\r\n if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\r\n }\r\n}\r\n\r\nexport function __createBinding(o, m, k, k2) {\r\n if (k2 === undefined) k2 = k;\r\n o[k2] = m[k];\r\n}\r\n\r\nexport function __exportStar(m, exports) {\r\n for (var p in m) if (p !== \"default\" && !exports.hasOwnProperty(p)) exports[p] = m[p];\r\n}\r\n\r\nexport function __values(o) {\r\n var s = typeof Symbol === \"function\" && Symbol.iterator, m = s && o[s], i = 0;\r\n if (m) return m.call(o);\r\n if (o && typeof o.length === \"number\") return {\r\n next: function () {\r\n if (o && i >= o.length) o = void 0;\r\n return { value: o && o[i++], done: !o };\r\n }\r\n };\r\n throw new TypeError(s ? \"Object is not iterable.\" : \"Symbol.iterator is not defined.\");\r\n}\r\n\r\nexport function __read(o, n) {\r\n var m = typeof Symbol === \"function\" && o[Symbol.iterator];\r\n if (!m) return o;\r\n var i = m.call(o), r, ar = [], e;\r\n try {\r\n while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);\r\n }\r\n catch (error) { e = { error: error }; }\r\n finally {\r\n try {\r\n if (r && !r.done && (m = i[\"return\"])) m.call(i);\r\n }\r\n finally { if (e) throw e.error; }\r\n }\r\n return ar;\r\n}\r\n\r\nexport function __spread() {\r\n for (var ar = [], i = 0; i < arguments.length; i++)\r\n ar = ar.concat(__read(arguments[i]));\r\n return ar;\r\n}\r\n\r\nexport function __spreadArrays() {\r\n for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;\r\n for (var r = Array(s), k = 0, i = 0; i < il; i++)\r\n for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)\r\n r[k] = a[j];\r\n return r;\r\n};\r\n\r\nexport function __await(v) {\r\n return this instanceof __await ? (this.v = v, this) : new __await(v);\r\n}\r\n\r\nexport function __asyncGenerator(thisArg, _arguments, generator) {\r\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\r\n var g = generator.apply(thisArg, _arguments || []), i, q = [];\r\n return i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i;\r\n function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }\r\n function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }\r\n function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }\r\n function fulfill(value) { resume(\"next\", value); }\r\n function reject(value) { resume(\"throw\", value); }\r\n function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }\r\n}\r\n\r\nexport function __asyncDelegator(o) {\r\n var i, p;\r\n return i = {}, verb(\"next\"), verb(\"throw\", function (e) { throw e; }), verb(\"return\"), i[Symbol.iterator] = function () { return this; }, i;\r\n function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === \"return\" } : f ? f(v) : v; } : f; }\r\n}\r\n\r\nexport function __asyncValues(o) {\r\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\r\n var m = o[Symbol.asyncIterator], i;\r\n return m ? m.call(o) : (o = typeof __values === \"function\" ? __values(o) : o[Symbol.iterator](), i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i);\r\n function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }\r\n function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }\r\n}\r\n\r\nexport function __makeTemplateObject(cooked, raw) {\r\n if (Object.defineProperty) { Object.defineProperty(cooked, \"raw\", { value: raw }); } else { cooked.raw = raw; }\r\n return cooked;\r\n};\r\n\r\nexport function __importStar(mod) {\r\n if (mod && mod.__esModule) return mod;\r\n var result = {};\r\n if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];\r\n result.default = mod;\r\n return result;\r\n}\r\n\r\nexport function __importDefault(mod) {\r\n return (mod && mod.__esModule) ? mod : { default: mod };\r\n}\r\n\r\nexport function __classPrivateFieldGet(receiver, privateMap) {\r\n if (!privateMap.has(receiver)) {\r\n throw new TypeError(\"attempted to get private field on non-instance\");\r\n }\r\n return privateMap.get(receiver);\r\n}\r\n\r\nexport function __classPrivateFieldSet(receiver, privateMap, value) {\r\n if (!privateMap.has(receiver)) {\r\n throw new TypeError(\"attempted to set private field on non-instance\");\r\n }\r\n privateMap.set(receiver, value);\r\n return value;\r\n}\r\n","export function isFunction(x: any): x is Function {\n return typeof x === 'function';\n}\n","let _enable_super_gross_mode_that_will_cause_bad_things = false;\n\n/**\n * The global configuration object for RxJS, used to configure things\n * like what Promise contructor should used to create Promises\n */\nexport const config = {\n /**\n * The promise constructor used by default for methods such as\n * {@link toPromise} and {@link forEach}\n */\n Promise: undefined as PromiseConstructorLike,\n\n /**\n * If true, turns on synchronous error rethrowing, which is a deprecated behavior\n * in v6 and higher. This behavior enables bad patterns like wrapping a subscribe\n * call in a try/catch block. It also enables producer interference, a nasty bug\n * where a multicast can be broken for all observers by a downstream consumer with\n * an unhandled error. DO NOT USE THIS FLAG UNLESS IT'S NEEDED TO BY TIME\n * FOR MIGRATION REASONS.\n */\n set useDeprecatedSynchronousErrorHandling(value: boolean) {\n if (value) {\n const error = new Error();\n console.warn('DEPRECATED! RxJS was set to use deprecated synchronous error handling behavior by code at: \\n' + error.stack);\n } else if (_enable_super_gross_mode_that_will_cause_bad_things) {\n console.log('RxJS: Back to a better error behavior. Thank you. <3');\n }\n _enable_super_gross_mode_that_will_cause_bad_things = value;\n },\n\n get useDeprecatedSynchronousErrorHandling() {\n return _enable_super_gross_mode_that_will_cause_bad_things;\n },\n};\n","/**\n * Throws an error on another job so that it's picked up by the runtime's\n * uncaught error handling mechanism.\n * @param err the error to throw\n */\nexport function hostReportError(err: any) {\n setTimeout(() => { throw err; }, 0);\n}","import { Observer } from './types';\nimport { config } from './config';\nimport { hostReportError } from './util/hostReportError';\n\nexport const empty: Observer<any> = {\n closed: true,\n next(value: any): void { /* noop */},\n error(err: any): void {\n if (config.useDeprecatedSynchronousErrorHandling) {\n throw err;\n } else {\n hostReportError(err);\n }\n },\n complete(): void { /*noop*/ }\n};\n","export const isArray = (() => Array.isArray || (<T>(x: any): x is T[] => x && typeof x.length === 'number'))();\n","export function isObject(x: any): x is Object {\n return x !== null && typeof x === 'object';\n}\n","export interface UnsubscriptionError extends Error {\n readonly errors: any[];\n}\n\nexport interface UnsubscriptionErrorCtor {\n new(errors: any[]): UnsubscriptionError;\n}\n\nconst UnsubscriptionErrorImpl = (() => {\n function UnsubscriptionErrorImpl(this: any, errors: any[]) {\n Error.call(this);\n this.message = errors ?\n `${errors.length} errors occurred during unsubscription:\n${errors.map((err, i) => `${i + 1}) ${err.toString()}`).join('\\n ')}` : '';\n this.name = 'UnsubscriptionError';\n this.errors = errors;\n return this;\n }\n\n UnsubscriptionErrorImpl.prototype = Object.create(Error.prototype);\n\n return UnsubscriptionErrorImpl;\n})();\n\n/**\n * An error thrown when one or more errors have occurred during the\n * `unsubscribe` of a {@link Subscription}.\n */\nexport const UnsubscriptionError: UnsubscriptionErrorCtor = UnsubscriptionErrorImpl as any;","import { isArray } from './util/isArray';\nimport { isObject } from './util/isObject';\nimport { isFunction } from './util/isFunction';\nimport { UnsubscriptionError } from './util/UnsubscriptionError';\nimport { SubscriptionLike, TeardownLogic } from './types';\n\n/**\n * Represents a disposable resource, such as the execution of an Observable. A\n * Subscription has one important method, `unsubscribe`, that takes no argument\n * and just disposes the resource held by the subscription.\n *\n * Additionally, subscriptions may be grouped together through the `add()`\n * method, which will attach a child Subscription to the current Subscription.\n * When a Subscription is unsubscribed, all its children (and its grandchildren)\n * will be unsubscribed as well.\n *\n * @class Subscription\n */\nexport class Subscription implements SubscriptionLike {\n /** @nocollapse */\n public static EMPTY: Subscription = (function(empty: any) {\n empty.closed = true;\n return empty;\n }(new Subscription()));\n\n /**\n * A flag to indicate whether this Subscription has already been unsubscribed.\n * @type {boolean}\n */\n public closed: boolean = false;\n\n /** @internal */\n protected _parentOrParents: Subscription | Subscription[] = null;\n /** @internal */\n private _subscriptions: SubscriptionLike[] = null;\n\n /**\n * @param {function(): void} [unsubscribe] A function describing how to\n * perform the disposal of resources when the `unsubscribe` method is called.\n */\n constructor(unsubscribe?: () => void) {\n if (unsubscribe) {\n (this as any)._ctorUnsubscribe = true;\n (this as any)._unsubscribe = unsubscribe;\n }\n }\n\n /**\n * Disposes the resources held by the subscription. May, for instance, cancel\n * an ongoing Observable execution or cancel any other type of work that\n * started when the Subscription was created.\n * @return {void}\n */\n unsubscribe(): void {\n let errors: any[];\n\n if (this.closed) {\n return;\n }\n\n let { _parentOrParents, _ctorUnsubscribe, _unsubscribe, _subscriptions } = (this as any);\n\n this.closed = true;\n this._parentOrParents = null;\n // null out _subscriptions first so any child subscriptions that attempt\n // to remove themselves from this subscription will noop\n this._subscriptions = null;\n\n if (_parentOrParents instanceof Subscription) {\n _parentOrParents.remove(this);\n } else if (_parentOrParents !== null) {\n for (let index = 0; index < _parentOrParents.length; ++index) {\n const parent = _parentOrParents[index];\n parent.remove(this);\n }\n }\n\n if (isFunction(_unsubscribe)) {\n // It's only possible to null _unsubscribe - to release the reference to\n // any teardown function passed in the constructor - if the property was\n // actually assigned in the constructor, as there are some classes that\n // are derived from Subscriber (which derives from Subscription) that\n // implement an _unsubscribe method as a mechanism for obtaining\n // unsubscription notifications and some of those subscribers are\n // recycled. Also, in some of those subscribers, _unsubscribe switches\n // from a prototype method to an instance property - see notifyNext in\n // RetryWhenSubscriber.\n if (_ctorUnsubscribe) {\n (this as any)._unsubscribe = undefined;\n }\n try {\n _unsubscribe.call(this);\n } catch (e) {\n errors = e instanceof UnsubscriptionError ? flattenUnsubscriptionErrors(e.errors) : [e];\n }\n }\n\n if (isArray(_subscriptions)) {\n let index = -1;\n let len = _subscriptions.length;\n\n while (++index < len) {\n const sub = _subscriptions[index];\n if (isObject(sub)) {\n try {\n sub.unsubscribe();\n } catch (e) {\n errors = errors || [];\n if (e instanceof UnsubscriptionError) {\n errors = errors.concat(flattenUnsubscriptionErrors(e.errors));\n } else {\n errors.push(e);\n }\n }\n }\n }\n }\n\n if (errors) {\n throw new UnsubscriptionError(errors);\n }\n }\n\n /**\n * Adds a tear down to be called during the unsubscribe() of this\n * Subscription. Can also be used to add a child subscription.\n *\n * If the tear down being added is a subscription that is already\n * unsubscribed, is the same reference `add` is being called on, or is\n * `Subscription.EMPTY`, it will not be added.\n *\n * If this subscription is already in an `closed` state, the passed\n * tear down logic will be executed immediately.\n *\n * When a parent subscription is unsubscribed, any child subscriptions that were added to it are also unsubscribed.\n *\n * @param {TeardownLogic} teardown The additional logic to execute on\n * teardown.\n * @return {Subscription} Returns the Subscription used or created to be\n * added to the inner subscriptions list. This Subscription can be used with\n * `remove()` to remove the passed teardown logic from the inner subscriptions\n * list.\n */\n add(teardown: TeardownLogic): Subscription {\n let subscription = (<Subscription>teardown);\n\n if (!teardown) {\n return Subscription.EMPTY;\n }\n\n switch (typeof teardown) {\n case 'function':\n subscription = new Subscription(<(() => void)>teardown);\n case 'object':\n if (subscription === this || subscription.closed || typeof subscription.unsubscribe !== 'function') {\n // This also covers the case where `subscription` is `Subscription.EMPTY`, which is always in `closed` state.\n return subscription;\n } else if (this.closed) {\n subscription.unsubscribe();\n return subscription;\n } else if (!(subscription instanceof Subscription)) {\n const tmp = subscription;\n subscription = new Subscription();\n subscription._subscriptions = [tmp];\n }\n break;\n default: {\n throw new Error('unrecognized teardown ' + teardown + ' added to Subscription.');\n }\n }\n\n // Add `this` as parent of `subscription` if that's not already the case.\n let { _parentOrParents } = subscription;\n if (_parentOrParents === null) {\n // If we don't have a parent, then set `subscription._parents` to\n // the `this`, which is the common case that we optimize for.\n subscription._parentOrParents = this;\n } else if (_parentOrParents instanceof Subscription) {\n if (_parentOrParents === this) {\n // The `subscription` already has `this` as a parent.\n return subscription;\n }\n // If there's already one parent, but not multiple, allocate an\n // Array to store the rest of the parent Subscriptions.\n subscription._parentOrParents = [_parentOrParents, this];\n } else if (_parentOrParents.indexOf(this) === -1) {\n // Only add `this` to the _parentOrParents list if it's not already there.\n _parentOrParents.push(this);\n } else {\n // The `subscription` already has `this` as a parent.\n return subscription;\n }\n\n // Optimize for the common case when adding the first subscription.\n const subscriptions = this._subscriptions;\n if (subscriptions === null) {\n this._subscriptions = [subscription];\n } else {\n subscriptions.push(subscription);\n }\n\n return subscription;\n }\n\n /**\n * Removes a Subscription from the internal list of subscriptions that will\n * unsubscribe during the unsubscribe process of this Subscription.\n * @param {Subscription} subscription The subscription to remove.\n * @return {void}\n */\n remove(subscription: Subscription): void {\n const subscriptions = this._subscriptions;\n if (subscriptions) {\n const subscriptionIndex = subscriptions.indexOf(subscription);\n if (subscriptionIndex !== -1) {\n subscriptions.splice(subscriptionIndex, 1);\n }\n }\n }\n}\n\nfunction flattenUnsubscriptionErrors(errors: any[]) {\n return errors.reduce((errs, err) => errs.concat((err instanceof UnsubscriptionError) ? err.errors : err), []);\n}\n","/** @deprecated do not use, this is no longer checked by RxJS internals */\nexport const rxSubscriber = (() =>\n typeof Symbol === 'function'\n ? Symbol('rxSubscriber')\n : '@@rxSubscriber_' + Math.random())();\n\n/**\n * @deprecated use rxSubscriber instead\n */\nexport const $$rxSubscriber = rxSubscriber;\n","import { isFunction } from './util/isFunction';\nimport { empty as emptyObserver } from './Observer';\nimport { Observer, PartialObserver, TeardownLogic } from './types';\nimport { Subscription } from './Subscription';\nimport { rxSubscriber as rxSubscriberSymbol } from '../internal/symbol/rxSubscriber';\nimport { config } from './config';\nimport { hostReportError } from './util/hostReportError';\n\n/**\n * Implements the {@link Observer} interface and extends the\n * {@link Subscription} class. While the {@link Observer} is the public API for\n * consuming the values of an {@link Observable}, all Observers get converted to\n * a Subscriber, in order to provide Subscription-like capabilities such as\n * `unsubscribe`. Subscriber is a common type in RxJS, and crucial for\n * implementing operators, but it is rarely used as a public API.\n *\n * @class Subscriber<T>\n */\nexport class Subscriber<T> extends Subscription implements Observer<T> {\n\n [rxSubscriberSymbol]() { return this; }\n\n /**\n * A static factory for a Subscriber, given a (potentially partial) definition\n * of an Observer.\n * @param {function(x: ?T): void} [next] The `next` callback of an Observer.\n * @param {function(e: ?any): void} [error] The `error` callback of an\n * Observer.\n * @param {function(): void} [complete] The `complete` callback of an\n * Observer.\n * @return {Subscriber<T>} A Subscriber wrapping the (partially defined)\n * Observer represented by the given arguments.\n * @nocollapse\n */\n static create<T>(next?: (x?: T) => void,\n error?: (e?: any) => void,\n complete?: () => void): Subscriber<T> {\n const subscriber = new Subscriber(next, error, complete);\n subscriber.syncErrorThrowable = false;\n return subscriber;\n }\n\n /** @internal */ syncErrorValue: any = null;\n /** @internal */ syncErrorThrown: boolean = false;\n /** @internal */ syncErrorThrowable: boolean = false;\n\n protected isStopped: boolean = false;\n protected destination: PartialObserver<any> | Subscriber<any>; // this `any` is the escape hatch to erase extra type param (e.g. R)\n\n /**\n * @param {Observer|function(value: T): void} [destinationOrNext] A partially\n * defined Observer or a `next` callback function.\n * @param {function(e: ?any): void} [error] The `error` callback of an\n * Observer.\n * @param {function(): void} [complete] The `complete` callback of an\n * Observer.\n */\n constructor(destinationOrNext?: PartialObserver<any> | ((value: T) => void),\n error?: (e?: any) => void,\n complete?: () => void) {\n super();\n\n switch (arguments.length) {\n case 0:\n this.destination = emptyObserver;\n break;\n case 1:\n if (!destinationOrNext) {\n this.destination = emptyObserver;\n break;\n }\n if (typeof destinationOrNext === 'object') {\n if (destinationOrNext instanceof Subscriber) {\n this.syncErrorThrowable = destinationOrNext.syncErrorThrowable;\n this.destination = destinationOrNext;\n destinationOrNext.add(this);\n } else {\n this.syncErrorThrowable = true;\n this.destination = new SafeSubscriber<T>(this, <PartialObserver<any>> destinationOrNext);\n }\n break;\n }\n default:\n this.syncErrorThrowable = true;\n this.destination = new SafeSubscriber<T>(this, <((value: T) => void)> destinationOrNext, error, complete);\n break;\n }\n }\n\n /**\n * The {@link Observer} callback to receive notifications of type `next` from\n * the Observable, with a value. The Observable may call this method 0 or more\n * times.\n * @param {T} [value] The `next` value.\n * @return {void}\n */\n next(value?: T): void {\n if (!this.isStopped) {\n this._next(value);\n }\n }\n\n /**\n * The {@link Observer} callback to receive notifications of type `error` from\n * the Observable, with an attached `Error`. Notifies the Observer that\n * the Observable has experienced an error condition.\n * @param {any} [err] The `error` exception.\n * @return {void}\n */\n error(err?: any): void {\n if (!this.isStopped) {\n this.isStopped = true;\n this._error(err);\n }\n }\n\n /**\n * The {@link Observer} callback to receive a valueless notification of type\n * `complete` from the Observable. Notifies the Observer that the Observable\n * has finished sending push-based notifications.\n * @return {void}\n */\n complete(): void {\n if (!this.isStopped) {\n this.isStopped = true;\n this._complete();\n }\n }\n\n unsubscribe(): void {\n if (this.closed) {\n return;\n }\n this.isStopped = true;\n super.unsubscribe();\n }\n\n protected _next(value: T): void {\n this.destination.next(value);\n }\n\n protected _error(err: any): void {\n this.destination.error(err);\n this.unsubscribe();\n }\n\n protected _complete(): void {\n this.destination.complete();\n this.unsubscribe();\n }\n\n /** @deprecated This is an internal implementation detail, do not use. */\n _unsubscribeAndRecycle(): Subscriber<T> {\n const { _parentOrParents } = this;\n this._parentOrParents = null;\n this.unsubscribe();\n this.closed = false;\n this.isStopped = false;\n this._parentOrParents = _parentOrParents;\n return this;\n }\n}\n\n/**\n * We need this JSDoc comment for affecting ESDoc.\n * @ignore\n * @extends {Ignored}\n */\nexport class SafeSubscriber<T> extends Subscriber<T> {\n\n private _context: any;\n\n constructor(private _parentSubscriber: Subscriber<T>,\n observerOrNext?: PartialObserver<T> | ((value: T) => void),\n error?: (e?: any) => void,\n complete?: () => void) {\n super();\n\n let next: ((value: T) => void);\n let context: any = this;\n\n if (isFunction(observerOrNext)) {\n next = (<((value: T) => void)> observerOrNext);\n } else if (observerOrNext) {\n next = (<PartialObserver<T>> observerOrNext).next;\n error = (<PartialObserver<T>> observerOrNext).error;\n complete = (<PartialObserver<T>> observerOrNext).complete;\n if (observerOrNext !== emptyObserver) {\n context = Object.create(observerOrNext);\n if (isFunction(context.unsubscribe)) {\n this.add(<() => void> context.unsubscribe.bind(context));\n }\n context.unsubscribe = this.unsubscribe.bind(this);\n }\n }\n\n this._context = context;\n this._next = next;\n this._error = error;\n this._complete = complete;\n }\n\n next(value?: T): void {\n if (!this.isStopped && this._next) {\n const { _parentSubscriber } = this;\n if (!config.useDeprecatedSynchronousErrorHandling || !_parentSubscriber.syncErrorThrowable) {\n this.__tryOrUnsub(this._next, value);\n } else if (this.__tryOrSetError(_parentSubscriber, this._next, value)) {\n this.unsubscribe();\n }\n }\n }\n\n error(err?: any): void {\n if (!this.isStopped) {\n const { _parentSubscriber } = this;\n const { useDeprecatedSynchronousErrorHandling } = config;\n if (this._error) {\n if (!useDeprecatedSynchronousErrorHandling || !_parentSubscriber.syncErrorThrowable) {\n this.__tryOrUnsub(this._error, err);\n this.unsubscribe();\n } else {\n this.__tryOrSetError(_parentSubscriber, this._error, err);\n this.unsubscribe();\n }\n } else if (!_parentSubscriber.syncErrorThrowable) {\n this.unsubscribe();\n if (useDeprecatedSynchronousErrorHandling) {\n throw err;\n }\n hostReportError(err);\n } else {\n if (useDeprecatedSynchronousErrorHandling) {\n _parentSubscriber.syncErrorValue = err;\n _parentSubscriber.syncErrorThrown = true;\n } else {\n hostReportError(err);\n }\n this.unsubscribe();\n }\n }\n }\n\n complete(): void {\n if (!this.isStopped) {\n const { _parentSubscriber } = this;\n if (this._complete) {\n const wrappedComplete = () => this._complete.call(this._context);\n\n if (!config.useDeprecatedSynchronousErrorHandling || !_parentSubscriber.syncErrorThrowable) {\n this.__tryOrUnsub(wrappedComplete);\n this.unsubscribe();\n } else {\n this.__tryOrSetError(_parentSubscriber, wrappedComplete);\n this.unsubscribe();\n }\n } else {\n this.unsubscribe();\n }\n }\n }\n\n private __tryOrUnsub(fn: Function, value?: any): void {\n try {\n fn.call(this._context, value);\n } catch (err) {\n this.unsubscribe();\n if (config.useDeprecatedSynchronousErrorHandling) {\n throw err;\n } else {\n hostReportError(err);\n }\n }\n }\n\n private __tryOrSetError(parent: Subscriber<T>, fn: Function, value?: any): boolean {\n if (!config.useDeprecatedSynchronousErrorHandling) {\n throw new Error('bad call');\n }\n try {\n fn.call(this._context, value);\n } catch (err) {\n if (config.useDeprecatedSynchronousErrorHandling) {\n parent.syncErrorValue = err;\n parent.syncErrorThrown = true;\n return true;\n } else {\n hostReportError(err);\n return true;\n }\n }\n return false;\n }\n\n /** @internal This is an internal implementation detail, do not use. */\n _unsubscribe(): void {\n const { _parentSubscriber } = this;\n this._context = null;\n this._parentSubscriber = null;\n _parentSubscriber.unsubscribe();\n }\n}\n","import { Subscriber } from '../Subscriber';\nimport { Subject } from '../Subject';\n\n/**\n * Determines whether the ErrorObserver is closed or stopped or has a\n * destination that is closed or stopped - in which case errors will\n * need to be reported via a different mechanism.\n * @param observer the observer\n */\nexport function canReportError(observer: Subscriber<any> | Subject<any>): boolean {\n while (observer) {\n const { closed, destination, isStopped } = observer as any;\n if (closed || isStopped) {\n return false;\n } else if (destination && destination instanceof Subscriber) {\n observer = destination;\n } else {\n observer = null;\n }\n }\n return true;\n}\n","import { Subscriber } from '../Subscriber';\nimport { rxSubscriber as rxSubscriberSymbol } from '../symbol/rxSubscriber';\nimport { empty as emptyObserver } from '../Observer';\nimport { PartialObserver } from '../types';\n\nexport function toSubscriber<T>(\n nextOrObserver?: PartialObserver<T> | ((value: T) => void),\n error?: (error: any) => void,\n complete?: () => void): Subscriber<T> {\n\n if (nextOrObserver) {\n if (nextOrObserver instanceof Subscriber) {\n return (<Subscriber<T>> nextOrObserver);\n }\n\n if (nextOrObserver[rxSubscriberSymbol]) {\n return nextOrObserver[rxSubscriberSymbol]();\n }\n }\n\n if (!nextOrObserver && !error && !complete) {\n return new Subscriber(emptyObserver);\n }\n\n return new Subscriber(nextOrObserver, error, complete);\n}\n","/** Symbol.observable or a string \"@@observable\". Used for interop */\nexport const observable = (() => typeof Symbol === 'function' && Symbol.observable || '@@observable')();\n","export function identity<T>(x: T): T {\n return x;\n}\n","import { noop } from './noop';\nimport { identity } from './identity';\nimport { UnaryFunction } from '../types';\n\n/* tslint:disable:max-line-length */\nexport function pipe<T>(): UnaryFunction<T, T>;\nexport function pipe<T, A>(fn1: UnaryFunction<T, A>): UnaryFunction<T, A>;\nexport function pipe<T, A, B>(fn1: UnaryFunction<T, A>, fn2: UnaryFunction<A, B>): UnaryFunction<T, B>;\nexport function pipe<T, A, B, C>(fn1: UnaryFunction<T, A>, fn2: UnaryFunction<A, B>, fn3: UnaryFunction<B, C>): UnaryFunction<T, C>;\nexport function pipe<T, A, B, C, D>(fn1: UnaryFunction<T, A>, fn2: UnaryFunction<A, B>, fn3: UnaryFunction<B, C>, fn4: UnaryFunction<C, D>): UnaryFunction<T, D>;\nexport function pipe<T, A, B, C, D, E>(fn1: UnaryFunction<T, A>, fn2: UnaryFunction<A, B>, fn3: UnaryFunction<B, C>, fn4: UnaryFunction<C, D>, fn5: UnaryFunction<D, E>): UnaryFunction<T, E>;\nexport function pipe<T, A, B, C, D, E, F>(fn1: UnaryFunction<T, A>, fn2: UnaryFunction<A, B>, fn3: UnaryFunction<B, C>, fn4: UnaryFunction<C, D>, fn5: UnaryFunction<D, E>, fn6: UnaryFunction<E, F>): UnaryFunction<T, F>;\nexport function pipe<T, A, B, C, D, E, F, G>(fn1: UnaryFunction<T, A>, fn2: UnaryFunction<A, B>, fn3: UnaryFunction<B, C>, fn4: UnaryFunction<C, D>, fn5: UnaryFunction<D, E>, fn6: UnaryFunction<E, F>, fn7: UnaryFunction<F, G>): UnaryFunction<T, G>;\nexport function pipe<T, A, B, C, D, E, F, G, H>(fn1: UnaryFunction<T, A>, fn2: UnaryFunction<A, B>, fn3: UnaryFunction<B, C>, fn4: UnaryFunction<C, D>, fn5: UnaryFunction<D, E>, fn6: UnaryFunction<E, F>, fn7: UnaryFunction<F, G>, fn8: UnaryFunction<G, H>): UnaryFunction<T, H>;\nexport function pipe<T, A, B, C, D, E, F, G, H, I>(fn1: UnaryFunction<T, A>, fn2: UnaryFunction<A, B>, fn3: UnaryFunction<B, C>, fn4: UnaryFunction<C, D>, fn5: UnaryFunction<D, E>, fn6: UnaryFunction<E, F>, fn7: UnaryFunction<F, G>, fn8: UnaryFunction<G, H>, fn9: UnaryFunction<H, I>): UnaryFunction<T, I>;\nexport function pipe<T, A, B, C, D, E, F, G, H, I>(fn1: UnaryFunction<T, A>, fn2: UnaryFunction<A, B>, fn3: UnaryFunction<B, C>, fn4: UnaryFunction<C, D>, fn5: UnaryFunction<D, E>, fn6: UnaryFunction<E, F>, fn7: UnaryFunction<F, G>, fn8: UnaryFunction<G, H>, fn9: UnaryFunction<H, I>, ...fns: UnaryFunction<any, any>[]): UnaryFunction<T, {}>;\n/* tslint:enable:max-line-length */\n\nexport function pipe(...fns: Array<UnaryFunction<any, any>>): UnaryFunction<any, any> {\n return pipeFromArray(fns);\n}\n\n/** @internal */\nexport function pipeFromArray<T, R>(fns: Array<UnaryFunction<T, R>>): UnaryFunction<T, R> {\n if (fns.length === 0) {\n return identity as UnaryFunction<any, any>;\n }\n\n if (fns.length === 1) {\n return fns[0];\n }\n\n return function piped(input: T): R {\n return fns.reduce((prev: any, fn: UnaryFunction<T, R>) => fn(prev), input as any);\n };\n}\n","import { Operator } from './Operator';\nimport { Subscriber } from './Subscriber';\nimport { Subscription } from './Subscription';\nimport { TeardownLogic, OperatorFunction, PartialObserver, Subscribable } from './types';\nimport { canReportError } from './util/canReportError';\nimport { toSubscriber } from './util/toSubscriber';\nimport { iif } from './observable/iif';\nimport { throwError } from './observable/throwError';\nimport { observable as Symbol_observable } from './symbol/observable';\nimport { pipeFromArray } from './util/pipe';\nimport { config } from './config';\n\n/**\n * A representation of any set of values over any amount of time. This is the most basic building block\n * of RxJS.\n *\n * @class Observable<T>\n */\nexport class Observable<T> implements Subscribable<T> {\n\n /** Internal implementation detail, do not use directly. */\n public _isScalar: boolean = false;\n\n /** @deprecated This is an internal implementation detail, do not use. */\n source: Observable<any>;\n\n /** @deprecated This is an internal implementation detail, do not use. */\n operator: Operator<any, T>;\n\n /**\n * @constructor\n * @param {Function} subscribe the function that is called when the Observable is\n * initially subscribed to. This function is given a Subscriber, to which new values\n * can be `next`ed, or an `error` method can be called to raise an error, or\n * `complete` can be called to notify of a successful completion.\n */\n constructor(subscribe?: (this: Observable<T>, subscriber: Subscriber<T>) => TeardownLogic) {\n if (subscribe) {\n this._subscribe = subscribe;\n }\n }\n\n // HACK: Since TypeScript inherits static properties too, we have to\n // fight against TypeScript here so Subject can have a different static create signature\n /**\n * Creates a new cold Observable by calling the Observable constructor\n * @static true\n * @owner Observable\n * @method create\n * @param {Function} subscribe? the subscriber function to be passed to the Observable constructor\n * @return {Observable} a new cold observable\n * @nocollapse\n * @deprecated use new Observable() instead\n */\n static create: Function = <T>(subscribe?: (subscriber: Subscriber<T>) => TeardownLogic) => {\n return new Observable<T>(subscribe);\n }\n\n /**\n * Creates a new Observable, with this Observable as the source, and the passed\n * operator defined as the new observable's operator.\n * @method lift\n * @param {Operator} operator the operator defining the operation to take on the observable\n * @return {Observable} a new observable with the Operator applied\n */\n lift<R>(operator: Operator<T, R>): Observable<R> {\n const observable = new Observable<R>();\n observable.source = this;\n observable.operator = operator;\n return observable;\n }\n\n subscribe(observer?: PartialObserver<T>): Subscription;\n /** @deprecated Use an observer instead of a complete callback */\n subscribe(next: null | undefined, error: null | undefined, complete: () => void): Subscription;\n /** @deprecated Use an observer instead of an error callback */\n subscribe(next: null | undefined, error: (error: any) => void, complete?: () => void): Subscription;\n /** @deprecated Use an observer instead of a complete callback */\n subscribe(next: (value: T) => void, error: null | undefined, complete: () => void): Subscription;\n subscribe(next?: (value: T) => void, error?: (error: any) => void, complete?: () => void): Subscription;\n /**\n * Invokes an execution of an Observable and registers Observer handlers for notifications it will emit.\n *\n * <span class=\"informal\">Use it when you have all these Observables, but still nothing is happening.</span>\n *\n * `subscribe` is not a regular operator, but a method that calls Observable's internal `subscribe` function. It\n * might be for example a function that you passed to Observable's constructor, but most of the time it is\n * a library implementation, which defines what will be emitted by an Observable, and when it be will emitted. This means\n * that calling `subscribe` is actually the moment when Observable starts its work, not when it is created, as it is often\n * the thought.\n *\n * Apart from starting the execution of an Observable, this method allows you to listen for values\n * that an Observable emits, as well as for when it completes or errors. You can achieve this in two\n * of the following ways.\n *\n * The first way is creating an object that implements {@link Observer} interface. It should have methods\n * defined by that interface, but note that it should be just a regular JavaScript object, which you can create\n * yourself in any way you want (ES6 class, classic function constructor, object literal etc.). In particular do\n * not attempt to use any RxJS implementation details to create Observers - you don't need them. Remember also\n * that your object does not have to implement all methods. If you find yourself creating a method that doesn't\n * do anything, you can simply omit it. Note however, if the `error` method is not provided, all errors will\n * be left uncaught.\n *\n * The second way is to give up on Observer object altogether and simply provide callback functions in place of its methods.\n * This means you can provide three functions as arguments to `subscribe`, where the first function is equivalent\n * of a `next` method, the second of an `error` method and the third of a `complete` method. Just as in case of Observer,\n * if you do not need to listen for something, you can omit a function, preferably by passing `undefined` or `null`,\n * since `subscribe` recognizes these functions by where they were placed in function call. When it comes\n * to `error` function, just as before, if not provided, errors emitted by an Observable will be thrown.\n *\n * Whichever style of calling `subscribe` you use, in both cases it returns a Subscription object.\n * This object allows you to call `unsubscribe` on it, which in turn will stop the work that an Observable does and will clean\n * up all resources that an Observable used. Note that cancelling a subscription will not call `complete` callback\n * provided to `subscribe` function, which is reserved for a regular completion signal that comes from an Observable.\n *\n * Remember that callbacks provided to `subscribe` are not guaranteed to be called asynchronously.\n * It is an Observable itself that decides when these functions will be called. For example {@link of}\n * by default emits all its values synchronously. Always check documentation for how given Observable\n * will behave when subscribed and if its default behavior can be modified with a `scheduler`.\n *\n * ## Example\n * ### Subscribe with an Observer\n * ```ts\n * import { of } from 'rxjs';\n *\n * const sumObserver = {\n * sum: 0,\n * next(value) {\n * console.log('Adding: ' + value);\n * this.sum = this.sum + value;\n * },\n * error() {\n * // We actually could just remove this method,\n * // since we do not really care about errors right now.\n * },\n * complete() {\n * console.log('Sum equals: ' + this.sum);\n * }\n * };\n *\n * of(1, 2, 3) // Synchronously emits 1, 2, 3 and then completes.\n * .subscribe(sumObserver);\n *\n * // Logs:\n * // \"Adding: 1\"\n * // \"Adding: 2\"\n * // \"Adding: 3\"\n * // \"Sum equals: 6\"\n * ```\n *\n * ### Subscribe with functions\n * ```ts\n * import { of } from 'rxjs'\n *\n * let sum = 0;\n *\n * of(1, 2, 3).subscribe(\n * value => {\n * console.log('Adding: ' + value);\n * sum = sum + value;\n * },\n * undefined,\n * () => console.log('Sum equals: ' + sum)\n * );\n *\n * // Logs:\n * // \"Adding: 1\"\n * // \"Adding: 2\"\n * // \"Adding: 3\"\n * // \"Sum equals: 6\"\n * ```\n *\n * ### Cancel a subscription\n * ```ts\n * import { interval } from 'rxjs';\n *\n * const subscription = interval(1000).subscribe(\n * num => console.log(num),\n * undefined,\n * () => {\n * // Will not be called, even when cancelling subscription.\n * console.log('completed!');\n * }\n * );\n *\n * setTimeout(() => {\n * subscription.unsubscribe();\n * console.log('unsubscribed!');\n * }, 2500);\n *\n * // Logs:\n * // 0 after 1s\n * // 1 after 2s\n * // \"unsubscribed!\" after 2.5s\n * ```\n *\n * @param {Observer|Function} observerOrNext (optional) Either an observer with methods to be called,\n * or the first of three possible handlers, which is the handler for each value emitted from the subscribed\n * Observable.\n * @param {Function} error (optional) A handler for a terminal event resulting from an error. If no error handler is provided,\n * the error will be thrown as unhandled.\n * @param {Function} complete (optional) A handler for a terminal event resulting from successful completion.\n * @return {ISubscription} a subscription reference to the registered handlers\n * @method subscribe\n */\n subscribe(observerOrNext?: PartialObserver<T> | ((value: T) => void),\n error?: (error: any) => void,\n complete?: () => void): Subscription {\n\n const { operator } = this;\n const sink = toSubscriber(observerOrNext, error, complete);\n\n if (operator) {\n sink.add(operator.call(sink, this.source));\n } else {\n sink.add(\n this.source || (config.useDeprecatedSynchronousErrorHandling && !sink.syncErrorThrowable) ?\n this._subscribe(sink) :\n this._trySubscribe(sink)\n );\n }\n\n if (config.useDeprecatedSynchronousErrorHandling) {\n if (sink.syncErrorThrowable) {\n sink.syncErrorThrowable = false;\n if (sink.syncErrorThrown) {\n throw sink.syncErrorValue;\n }\n }\n }\n\n return sink;\n }\n\n /** @deprecated This is an internal implementation detail, do not use. */\n _trySubscribe(sink: Subscriber<T>): TeardownLogic {\n try {\n return this._subscribe(sink);\n } catch (err) {\n if (config.useDeprecatedSynchronousErrorHandling) {\n sink.syncErrorThrown = true;\n sink.syncErrorValue = err;\n }\n if (canReportError(sink)) {\n sink.error(err);\n } else {\n console.warn(err);\n }\n }\n }\n\n /**\n * @method forEach\n * @param {Function} next a handler for each value emitted by the observable\n * @param {PromiseConstructor} [promiseCtor] a constructor function used to instantiate the Promise\n * @return {Promise} a promise that either resolves on observable completion or\n * rejects with the handled error\n */\n forEach(next: (value: T) => void, promiseCtor?: PromiseConstructorLike): Promise<void> {\n promiseCtor = getPromiseCtor(promiseCtor);\n\n return new promiseCtor<void>((resolve, reject) => {\n // Must be declared in a separate statement to avoid a ReferenceError when\n // accessing subscription below in the closure due to Temporal Dead Zone.\n let subscription: Subscription;\n subscription = this.subscribe((value) => {\n try {\n next(value);\n } catch (err) {\n reject(err);\n if (subscription) {\n subscription.unsubscribe();\n }\n }\n }, reject, resolve);\n }) as Promise<void>;\n }\n\n /** @internal This is an internal implementation detail, do not use. */\n _subscribe(subscriber: Subscriber<any>): TeardownLogic {\n const { source } = this;\n return source && source.subscribe(subscriber);\n }\n\n // `if` and `throw` are special snow flakes, the compiler sees them as reserved words. Deprecated in\n // favor of iif and throwError functions.\n /**\n * @nocollapse\n * @deprecated In favor of iif creation function: import { iif } from 'rxjs';\n */\n static if: typeof iif;\n /**\n * @nocollapse\n * @deprecated In favor of throwError creation function: import { throwError } from 'rxjs';\n */\n static throw: typeof throwError;\n\n /**\n * An interop point defined by the es7-observable spec https://github.com/zenparsing/es-observable\n * @method Symbol.observable\n * @return {Observable} this instance of the observable\n */\n [Symbol_observable]() {\n return this;\n }\n\n /* tslint:disable:max-line-length */\n pipe(): Observable<T>;\n pipe<A>(op1: OperatorFunction<T, A>): Observable<A>;\n pipe<A, B>(op1: OperatorFunction<T, A>, op2: OperatorFunction<A, B>): Observable<B>;\n pipe<A, B, C>(op1: OperatorFunction<T, A>, op2: OperatorFunction<A, B>, op3: OperatorFunction<B, C>): Observable<C>;\n pipe<A, B, C, D>(op1: OperatorFunction<T, A>, op2: OperatorFunction<A, B>, op3: OperatorFunction<B, C>, op4: OperatorFunction<C, D>): Observable<D>;\n pipe<A, B, C, D, E>(op1: OperatorFunction<T, A>, op2: OperatorFunction<A, B>, op3: OperatorFunction<B, C>, op4: OperatorFunction<C, D>, op5: OperatorFunction<D, E>): Observable<E>;\n pipe<A, B, C, D, E, F>(op1: OperatorFunction<T, A>, op2: OperatorFunction<A, B>, op3: OperatorFunction<B, C>, op4: OperatorFunction<C, D>, op5: OperatorFunction<D, E>, op6: OperatorFunction<E, F>): Observable<F>;\n pipe<A, B, C, D, E, F, G>(op1: OperatorFunction<T, A>, op2: OperatorFunction<A, B>, op3: OperatorFunction<B, C>, op4: OperatorFunction<C, D>, op5: OperatorFunction<D, E>, op6: OperatorFunction<E, F>, op7: OperatorFunction<F, G>): Observable<G>;\n pipe<A, B, C, D, E, F, G, H>(op1: OperatorFunction<T, A>, op2: OperatorFunction<A, B>, op3: OperatorFunction<B, C>, op4: OperatorFunction<C, D>, op5: OperatorFunction<D, E>, op6: OperatorFunction<E, F>, op7: OperatorFunction<F, G>, op8: OperatorFunction<G, H>): Observable<H>;\n pipe<A, B, C, D, E, F, G, H, I>(op1: OperatorFunction<T, A>, op2: OperatorFunction<A, B>, op3: OperatorFunction<B, C>, op4: OperatorFunction<C, D>, op5: OperatorFunction<D, E>, op6: OperatorFunction<E, F>, op7: OperatorFunction<F, G>, op8: OperatorFunction<G, H>, op9: OperatorFunction<H, I>): Observable<I>;\n pipe<A, B, C, D, E, F, G, H, I>(op1: OperatorFunction<T, A>, op2: OperatorFunction<A, B>, op3: OperatorFunction<B, C>, op4: OperatorFunction<C, D>, op5: OperatorFunction<D, E>, op6: OperatorFunction<E, F>, op7: OperatorFunction<F, G>, op8: OperatorFunction<G, H>, op9: OperatorFunction<H, I>, ...operations: OperatorFunction<any, any>[]): Observable<{}>;\n /* tslint:enable:max-line-length */\n\n /**\n * Used to stitch together functional operators into a chain.\n * @method pipe\n * @return {Observable} the Observable result of all of the operators having\n * been called in the order they were passed in.\n *\n * ### Example\n * ```ts\n * import { interval } from 'rxjs';\n * import { map, filter, scan } from 'rxjs/operators';\n *\n * interval(1000)\n * .pipe(\n * filter(x => x % 2 === 0),\n * map(x => x + x),\n * scan((acc, x) => acc + x)\n * )\n * .subscribe(x => console.log(x))\n * ```\n */\n pipe(...operations: OperatorFunction<any, any>[]): Observable<any> {\n if (operations.length === 0) {\n return this as any;\n }\n\n return pipeFromArray(operations)(this);\n }\n\n /* tslint:disable:max-line-length */\n toPromise<T>(this: Observable<T>): Promise<T>;\n toPromise<T>(this: Observable<T>, PromiseCtor: typeof Promise): Promise<T>;\n toPromise<T>(this: Observable<T>, PromiseCtor: PromiseConstructorLike): Promise<T>;\n /* tslint:enable:max-line-length */\n\n toPromise(promiseCtor?: PromiseConstructorLike): Promise<T> {\n promiseCtor = getPromiseCtor(promiseCtor);\n\n return new promiseCtor((resolve, reject) => {\n let value: any;\n this.subscribe((x: T) => value = x, (err: any) => reject(err), () => resolve(value));\n }) as Promise<T>;\n }\n}\n\n/**\n * Decides between a passed promise constructor from consuming code,\n * A default configured promise constructor, and the native promise\n * constructor and returns it. If nothing can be found, it will throw\n * an error.\n * @param promiseCtor The optional promise constructor to passed by consuming code\n */\nfunction getPromiseCtor(promiseCtor: PromiseConstructorLike | undefined) {\n if (!promiseCtor) {\n promiseCtor = config.Promise || Promise;\n }\n\n if (!promiseCtor) {\n throw new Error('no Promise impl found');\n }\n\n return promiseCtor;\n}\n","import { Subscriber } from '../Subscriber';\n\n/**\n * Subscribes to an ArrayLike with a subscriber\n * @param array The array or array-like to subscribe to\n */\nexport const subscribeToArray = <T>(array: ArrayLike<T>) => (subscriber: Subscriber<T>) => {\n for (let i = 0, len = array.length; i < len && !subscriber.closed; i++) {\n subscriber.next(array[i]);\n }\n subscriber.complete();\n};\n","import { Subscriber } from '../Subscriber';\nimport { hostReportError } from './hostReportError';\n\nexport const subscribeToPromise = <T>(promise: PromiseLike<T>) => (subscriber: Subscriber<T>) => {\n promise.then(\n (value) => {\n if (!subscriber.closed) {\n subscriber.next(value);\n subscriber.complete();\n }\n },\n (err: any) => subscriber.error(err)\n )\n .then(null, hostReportError);\n return subscriber;\n};\n","export function getSymbolIterator(): symbol {\n if (typeof Symbol !== 'function' || !Symbol.iterator) {\n return '@@iterator' as any;\n }\n\n return Symbol.iterator;\n}\n\nexport const iterator = getSymbolIterator();\n\n/**\n * @deprecated use {@link iterator} instead\n */\nexport const $$iterator = iterator;\n","import { Subscriber } from '../Subscriber';\nimport { iterator as Symbol_iterator } from '../symbol/iterator';\n\nexport const subscribeToIterable = <T>(iterable: Iterable<T>) => (subscriber: Subscriber<T>) => {\n const iterator = (iterable as any)[Symbol_iterator]();\n\n do {\n let item: IteratorResult<T>;\n try {\n item = iterator.next();\n } catch (err) {\n subscriber.error(err);\n return subscriber;\n }\n if (item.done) {\n subscriber.complete();\n break;\n }\n subscriber.next(item.value);\n if (subscriber.closed) {\n break;\n }\n } while (true);\n\n // Finalize the iterator if it happens to be a Generator\n if (typeof iterator.return === 'function') {\n subscriber.add(() => {\n if (iterator.return) {\n iterator.return();\n }\n });\n }\n\n return subscriber;\n};\n","import { Subscriber } from '../Subscriber';\nimport { observable as Symbol_observable } from '../symbol/observable';\n\n/**\n * Subscribes to an object that implements Symbol.observable with the given\n * Subscriber.\n * @param obj An object that implements Symbol.observable\n */\nexport const subscribeToObservable = <T>(obj: any) => (subscriber: Subscriber<T>) => {\n const obs = obj[Symbol_observable]();\n if (typeof obs.subscribe !== 'function') {\n // Should be caught by observable subscribe function error handling.\n throw new TypeError('Provided object does not correctly implement Symbol.observable');\n } else {\n return obs.subscribe(subscriber);\n }\n};\n","export const isArrayLike = (<T>(x: any): x is ArrayLike<T> => x && typeof x.length === 'number' && typeof x !== 'function');","/**\n * Tests to see if the object is an ES2015 (ES6) Promise\n * @see {@link https://www.ecma-international.org/ecma-262/6.0/#sec-promise-objects}\n * @param value the object to test\n */\nexport function isPromise(value: any): value is PromiseLike<any> {\n return !!value && typeof (<any>value).subscribe !== 'function' && typeof (value as any).then === 'function';\n}\n","import { ObservableInput } from '../types';\nimport { subscribeToArray } from './subscribeToArray';\nimport { subscribeToPromise } from './subscribeToPromise';\nimport { subscribeToIterable } from './subscribeToIterable';\nimport { subscribeToObservable } from './subscribeToObservable';\nimport { isArrayLike } from './isArrayLike';\nimport { isPromise } from './isPromise';\nimport { isObject } from './isObject';\nimport { iterator as Symbol_iterator } from '../symbol/iterator';\nimport { observable as Symbol_observable } from '../symbol/observable';\nimport { Subscription } from '../Subscription';\nimport { Subscriber } from '../Subscriber';\n\nexport const subscribeTo = <T>(result: ObservableInput<T>): (subscriber: Subscriber<T>) => Subscription | void => {\n if (!!result && typeof result[Symbol_observable] === 'function') {\n return subscribeToObservable(result as any);\n } else if (isArrayLike(result)) {\n return subscribeToArray(result);\n } else if (isPromise(result)) {\n return subscribeToPromise(result as Promise<any>);\n } else if (!!result && typeof result[Symbol_iterator] === 'function') {\n return subscribeToIterable(result as any);\n } else {\n const value = isObject(result) ? 'an invalid object' : `'${result}'`;\n const msg = `You provided ${value} where a stream was expected.`\n + ' You can provide an Observable, Promise, Array, or Iterable.';\n throw new TypeError(msg);\n }\n};\n","/** @prettier */\nimport { Subscription } from './Subscription';\nimport { Subscriber } from './Subscriber';\nimport { Observable } from './Observable';\nimport { subscribeTo } from './util/subscribeTo';\n\ninterface SimpleOuterSubscriberLike<T> {\n /**\n * A handler for inner next notifications from the inner subscription\n * @param innerValue the value nexted by the inner producer\n */\n notifyNext(innerValue: T): void;\n /**\n * A handler for inner error notifications from the inner subscription\n * @param err the error from the inner producer\n */\n notifyError(err: any): void;\n /**\n * A handler for inner complete notifications from the inner subscription.\n */\n notifyComplete(): void;\n}\n\nexport class SimpleInnerSubscriber<T> extends Subscriber<T> {\n constructor(private parent: SimpleOuterSubscriberLike<any>) {\n super();\n }\n\n protected _next(value: T): void {\n this.parent.notifyNext(value);\n }\n\n protected _error(error: any): void {\n this.parent.notifyError(error);\n this.unsubscribe();\n }\n\n protected _complete(): void {\n this.parent.notifyComplete();\n this.unsubscribe();\n }\n}\n\nexport class ComplexInnerSubscriber<T, R> extends Subscriber<R> {\n constructor(private parent: ComplexOuterSubscriber<T, R>, public outerValue: T, public outerIndex: number) {\n super();\n }\n\n protected _next(value: R): void {\n this.parent.notifyNext(this.outerValue, value, this.outerIndex, this);\n }\n\n protected _error(error: any): void {\n this.parent.notifyError(error);\n this.unsubscribe();\n }\n\n protected _complete(): void {\n this.parent.notifyComplete(this);\n this.unsubscribe();\n }\n}\n\nexport class SimpleOuterSubscriber<T, R> extends Subscriber<T> implements SimpleOuterSubscriberLike<R> {\n notifyNext(innerValue: R): void {\n this.destination.next(innerValue);\n }\n\n notifyError(err: any): void {\n this.destination.error(err);\n }\n\n notifyComplete(): void {\n this.destination.complete();\n }\n}\n\n/**\n * DO NOT USE (formerly \"OuterSubscriber\")\n * TODO: We want to refactor this and remove it. It is retaining values it shouldn't for long\n * periods of time.\n */\nexport class ComplexOuterSubscriber<T, R> extends Subscriber<T> {\n /**\n * @param _outerValue Used by: bufferToggle, delayWhen, windowToggle\n * @param innerValue Used by: subclass default, combineLatest, race, bufferToggle, windowToggle, withLatestFrom\n * @param _outerIndex Used by: combineLatest, race, withLatestFrom\n * @param _innerSub Used by: delayWhen\n */\n notifyNext(_outerValue: T, innerValue: R, _outerIndex: number, _innerSub: ComplexInnerSubscriber<T, R>): void {\n this.destination.next(innerValue);\n }\n\n notifyError(error: any): void {\n this.destination.error(error);\n }\n\n /**\n * @param _innerSub Used by: race, bufferToggle, delayWhen, windowToggle, windowWhen\n */\n notifyComplete(_innerSub: ComplexInnerSubscriber<T, R>): void {\n this.destination.complete();\n }\n}\n\nexport function innerSubscribe(result: any, innerSubscriber: Subscriber<any>): Subscription | undefined {\n if (innerSubscriber.closed) {\n return undefined;\n }\n if (result instanceof Observable) {\n return result.subscribe(innerSubscriber);\n }\n let subscription: Subscription;\n try {\n subscription = subscribeTo(result)(innerSubscriber) as Subscription;\n } catch (error) {\n innerSubscriber.error(error);\n }\n return subscription;\n}\n","import { Scheduler } from '../Scheduler';\nimport { Subscription } from '../Subscription';\nimport { SchedulerAction } from '../types';\n\n/**\n * A unit of work to be executed in a `scheduler`. An action is typically\n * created from within a {@link SchedulerLike} and an RxJS user does not need to concern\n * themselves about creating and manipulating an Action.\n *\n * ```ts\n * class Action<T> extends Subscription {\n * new (scheduler: Scheduler, work: (state?: T) => void);\n * schedule(state?: T, delay: number = 0): Subscription;\n * }\n * ```\n *\n * @class Action<T>\n */\nexport class Action<T> extends Subscription {\n constructor(scheduler: Scheduler, work: (this: SchedulerAction<T>, state?: T) => void) {\n super();\n }\n /**\n * Schedules this action on its parent {@link SchedulerLike} for execution. May be passed\n * some context object, `state`. May happen at some point in the future,\n * according to the `delay` parameter, if specified.\n * @param {T} [state] Some contextual data that the `work` function uses when\n * called by the Scheduler.\n * @param {number} [delay] Time to wait before executing the work, where the\n * time unit is implicit and defined by the Scheduler.\n * @return {void}\n */\n public schedule(state?: T, delay: number = 0): Subscription {\n return this;\n }\n}\n","import { Action } from './Action';\nimport { SchedulerAction } from '../types';\nimport { Subscription } from '../Subscription';\nimport { AsyncScheduler } from './AsyncScheduler';\n\n/**\n * We need this JSDoc comment for affecting ESDoc.\n * @ignore\n * @extends {Ignored}\n */\nexport class AsyncAction<T> extends Action<T> {\n\n public id: any;\n public state: T;\n public delay: number;\n protected pending: boolean = false;\n\n constructor(protected scheduler: AsyncScheduler,\n protected work: (this: SchedulerAction<T>, state?: T) => void) {\n super(scheduler, work);\n }\n\n public schedule(state?: T, delay: number = 0): Subscription {\n\n if (this.closed) {\n return this;\n }\n\n // Always replace the current state with the new state.\n this.state = state;\n\n const id = this.id;\n const scheduler = this.scheduler;\n\n //\n // Important implementation note:\n //\n // Actions only execute once by default, unless rescheduled from within the\n // scheduled callback. This allows us to implement single and repeat\n // actions via the same code path, without adding API surface area, as well\n // as mimic traditional recursion but across asynchronous boundaries.\n //\n // However, JS runtimes and timers distinguish between intervals achieved by\n // serial `setTimeout` calls vs. a single `setInterval` call. An interval of\n // serial `setTimeout` calls can be individually delayed, which delays\n // scheduling the next `setTimeout`, and so on. `setInterval` attempts to\n // guarantee the interval callback will be invoked more precisely to the\n // interval period, regardless of load.\n //\n // Therefore, we use `setInterval` to schedule single and repeat actions.\n // If the action reschedules itself with the same delay, the interval is not\n // canceled. If the action doesn't reschedule, or reschedules with a\n // different delay, the interval will be canceled after scheduled callback\n // execution.\n //\n if (id != null) {\n this.id = this.recycleAsyncId(scheduler, id, delay);\n }\n\n // Set the pending flag indicating that this action has been scheduled, or\n // has recursively rescheduled itself.\n this.pending = true;\n\n this.delay = delay;\n // If this action has already an async Id, don't request a new one.\n this.id = this.id || this.requestAsyncId(scheduler, this.id, delay);\n\n return this;\n }\n\n protected requestAsyncId(scheduler: AsyncScheduler, id?: any, delay: number = 0): any {\n return setInterval(scheduler.flush.bind(scheduler, this), delay);\n }\n\n protected recycleAsyncId(scheduler: AsyncScheduler, id: any, delay: number = 0): any {\n // If this action is rescheduled with the same delay time, don't clear the interval id.\n if (delay !== null && this.delay === delay && this.pending === false) {\n return id;\n }\n // Otherwise, if the action's delay time is different from the current delay,\n // or the action has been rescheduled before it's executed, clear the interval id\n clearInterval(id);\n return undefined;\n }\n\n /**\n * Immediately executes this action and the `work` it contains.\n * @return {any}\n */\n public execute(state: T, delay: number): any {\n\n if (this.closed) {\n return new Error('executing a cancelled action');\n }\n\n this.pending = false;\n const error = this._execute(state, delay);\n if (error) {\n return error;\n } else if (this.pending === false && this.id != null) {\n // Dequeue if the action didn't reschedule itself. Don't call\n // unsubscribe(), because the action could reschedule later.\n // For example:\n // ```\n // scheduler.schedule(function doWork(counter) {\n // /* ... I'm a busy worker bee ... */\n // var originalAction = this;\n // /* wait 100ms before rescheduling the action */\n // setTimeout(function () {\n // originalAction.schedule(counter + 1);\n // }, 100);\n // }, 1000);\n // ```\n this.id = this.recycleAsyncId(this.scheduler, this.id, null);\n }\n }\n\n protected _execute(state: T, delay: number): any {\n let errored: boolean = false;\n let errorValue: any = undefined;\n try {\n this.work(state);\n } catch (e) {\n errored = true;\n errorValue = !!e && e || new Error(e);\n }\n if (errored) {\n this.unsubscribe();\n return errorValue;\n }\n }\n\n /** @deprecated This is an internal implementation detail, do not use. */\n _unsubscribe() {\n\n const id = this.id;\n const scheduler = this.scheduler;\n const actions = scheduler.actions;\n const index = actions.indexOf(this);\n\n this.work = null;\n this.state = null;\n this.pending = false;\n this.scheduler = null;\n\n if (index !== -1) {\n actions.splice(index, 1);\n }\n\n if (id != null) {\n this.id = this.recycleAsyncId(scheduler, id, null);\n }\n\n this.delay = null;\n }\n}\n","import { Action } from './scheduler/Action';\nimport { Subscription } from './Subscription';\nimport { SchedulerLike, SchedulerAction } from './types';\n\n/**\n * An execution context and a data structure to order tasks and schedule their\n * execution. Provides a notion of (potentially virtual) time, through the\n * `now()` getter method.\n *\n * Each unit of work in a Scheduler is called an `Action`.\n *\n * ```ts\n * class Scheduler {\n * now(): number;\n * schedule(work, delay?, state?): Subscription;\n * }\n * ```\n *\n * @class Scheduler\n * @deprecated Scheduler is an internal implementation detail of RxJS, and\n * should not be used directly. Rather, create your own class and implement\n * {@link SchedulerLike}\n */\nexport class Scheduler implements SchedulerLike {\n\n /**\n * Note: the extra arrow function wrapper is to make testing by overriding\n * Date.now easier.\n * @nocollapse\n */\n public static now: () => number = () => Date.now();\n\n constructor(private SchedulerAction: typeof Action,\n now: () => number = Scheduler.now) {\n this.now = now;\n }\n\n /**\n * A getter method that returns a number representing the current time\n * (at the time this function was called) according to the scheduler's own\n * internal clock.\n * @return {number} A number that represents the current time. May or may not\n * have a relation to wall-clock time. May or may not refer to a time unit\n * (e.g. milliseconds).\n */\n public now: () => number;\n\n /**\n * Schedules a function, `work`, for execution. May happen at some point in\n * the future, according to the `delay` parameter, if specified. May be passed\n * some context object, `state`, which will be passed to the `work` function.\n *\n * The given arguments will be processed an stored as an Action object in a\n * queue of actions.\n *\n * @param {function(state: ?T): ?Subscription} work A function representing a\n * task, or some unit of work to be executed by the Scheduler.\n * @param {number} [delay] Time to wait before executing the work, where the\n * time unit is implicit and defined by the Scheduler itself.\n * @param {T} [state] Some contextual data that the `work` function uses when\n * called by the Scheduler.\n * @return {Subscription} A subscription in order to be able to unsubscribe\n * the scheduled work.\n */\n public schedule<T>(work: (this: SchedulerAction<T>, state?: T) => void, delay: number = 0, state?: T): Subscription {\n return new this.SchedulerAction<T>(this, work).schedule(state, delay);\n }\n}\n","import { Scheduler } from '../Scheduler';\nimport { Action } from './Action';\nimport { AsyncAction } from './AsyncAction';\nimport { SchedulerAction } from '../types';\nimport { Subscription } from '../Subscription';\n\nexport class AsyncScheduler extends Scheduler {\n public static delegate?: Scheduler;\n public actions: Array<AsyncAction<any>> = [];\n /**\n * A flag to indicate whether the Scheduler is currently executing a batch of\n * queued actions.\n * @type {boolean}\n * @deprecated internal use only\n */\n public active: boolean = false;\n /**\n * An internal ID used to track the latest asynchronous task such as those\n * coming from `setTimeout`, `setInterval`, `requestAnimationFrame`, and\n * others.\n * @type {any}\n * @deprecated internal use only\n */\n public scheduled: any = undefined;\n\n constructor(SchedulerAction: typeof Action,\n now: () => number = Scheduler.now) {\n super(SchedulerAction, () => {\n if (AsyncScheduler.delegate && AsyncScheduler.delegate !== this) {\n return AsyncScheduler.delegate.now();\n } else {\n return now();\n }\n });\n }\n\n public schedule<T>(work: (this: SchedulerAction<T>, state?: T) => void, delay: number = 0, state?: T): Subscription {\n if (AsyncScheduler.delegate && AsyncScheduler.delegate !== this) {\n return AsyncScheduler.delegate.schedule(work, delay, state);\n } else {\n return super.schedule(work, delay, state);\n }\n }\n\n public flush(action: AsyncAction<any>): void {\n\n const {actions} = this;\n\n if (this.active) {\n actions.push(action);\n return;\n }\n\n let error: any;\n this.active = true;\n\n do {\n if (error = action.execute(action.state, action.delay)) {\n break;\n }\n } while (action = actions.shift()); // exhaust the scheduler queue\n\n this.active = false;\n\n if (error) {\n while (action = actions.shift()) {\n action.unsubscribe();\n }\n throw error;\n }\n }\n}\n","import { AsyncAction } from './AsyncAction';\nimport { AsyncScheduler } from './AsyncScheduler';\n\n/**\n *\n * Async Scheduler\n *\n * <span class=\"informal\">Schedule task as if you used setTimeout(task, duration)</span>\n *\n * `async` scheduler schedules tasks asynchronously, by putting them on the JavaScript\n * event loop queue. It is best used to delay tasks in time or to schedule tasks repeating\n * in intervals.\n *\n * If you just want to \"defer\" task, that is to perform it right after currently\n * executing synchronous code ends (commonly achieved by `setTimeout(deferredTask, 0)`),\n * better choice will be the {@link asapScheduler} scheduler.\n *\n * ## Examples\n * Use async scheduler to delay task\n * ```ts\n * import { asyncScheduler } from 'rxjs';\n *\n * const task = () => console.log('it works!');\n *\n * asyncScheduler.schedule(task, 2000);\n *\n * // After 2 seconds logs:\n * // \"it works!\"\n * ```\n *\n * Use async scheduler to repeat task in intervals\n * ```ts\n * import { asyncScheduler } from 'rxjs';\n *\n * function task(state) {\n * console.log(state);\n * this.schedule(state + 1, 1000); // `this` references currently executing Action,\n * // which we reschedule with new state and delay\n * }\n *\n * asyncScheduler.schedule(task, 3000, 0);\n *\n * // Logs:\n * // 0 after 3s\n * // 1 after 4s\n * // 2 after 5s\n * // 3 after 6s\n * ```\n */\nexport const asyncScheduler = new AsyncScheduler(AsyncAction);\n\n/**\n * @deprecated renamed. Use {@link asyncScheduler}\n */\nexport const async = asyncScheduler;","import { SchedulerLike } from '../types';\n\nexport function isScheduler(value: any): value is SchedulerLike {\n return value && typeof (<any>value).schedule === 'function';\n}\n","import { Operator } from '../Operator';\nimport { Subscriber } from '../Subscriber';\nimport { Observable } from '../Observable';\n\nimport { ObservableInput, OperatorFunction, ObservedValueOf } from '../types';\nimport { SimpleOuterSubscriber, SimpleInnerSubscriber, innerSubscribe } from '../innerSubscribe';\n\n/* tslint:disable:max-line-length */\nexport function catchError<T, O extends ObservableInput<any>>(selector: (err: any, caught: Observable<T>) => O): OperatorFunction<T, T | ObservedValueOf<O>>;\n/* tslint:enable:max-line-length */\n\n/**\n * Catches errors on the observable to be handled by returning a new observable or throwing an error.\n *\n * ![](catch.png)\n *\n * ## Examples\n * Continues with a different Observable when there's an error\n *\n * ```ts\n * import { of } from 'rxjs';\n * import { map, catchError } from 'rxjs/operators';\n *\n * of(1, 2, 3, 4, 5).pipe(\n * map(n => {\n * \t if (n === 4) {\n * \t throw 'four!';\n * }\n *\t return n;\n * }),\n * catchError(err => of('I', 'II', 'III', 'IV', 'V')),\n * )\n * .subscribe(x => console.log(x));\n * // 1, 2, 3, I, II, III, IV, V\n * ```\n *\n * Retries the caught source Observable again in case of error, similar to retry() operator\n *\n * ```ts\n * import { of } from 'rxjs';\n * import { map, catchError, take } from 'rxjs/operators';\n *\n * of(1, 2, 3, 4, 5).pipe(\n * map(n => {\n * \t if (n === 4) {\n * \t throw 'four!';\n * }\n * \t return n;\n * }),\n * catchError((err, caught) => caught),\n * take(30),\n * )\n * .subscribe(x => console.log(x));\n * // 1, 2, 3, 1, 2, 3, ...\n * ```\n *\n * Throws a new error when the source Observable throws an error\n *\n * ```ts\n * import { of } from 'rxjs';\n * import { map, catchError } from 'rxjs/operators';\n *\n * of(1, 2, 3, 4, 5).pipe(\n * map(n => {\n * if (n === 4) {\n * throw 'four!';\n * }\n * return n;\n * }),\n * catchError(err => {\n * throw 'error in source. Details: ' + err;\n * }),\n * )\n * .subscribe(\n * x => console.log(x),\n * err => console.log(err)\n * );\n * // 1, 2, 3, error in source. Details: four!\n * ```\n *\n * @param {function} selector a function that takes as arguments `err`, which is the error, and `caught`, which\n * is the source observable, in case you'd like to \"retry\" that observable by returning it again. Whatever observable\n * is returned by the `selector` will be used to continue the observable chain.\n * @return {Observable} An observable that originates from either the source or the observable returned by the\n * catch `selector` function.\n * @name catchError\n */\nexport function catchError<T, O extends ObservableInput<any>>(\n selector: (err: any, caught: Observable<T>) => O\n): OperatorFunction<T, T | ObservedValueOf<O>> {\n return function catchErrorOperatorFunction(source: Observable<T>): Observable<T | ObservedValueOf<O>> {\n const operator = new CatchOperator(selector);\n const caught = source.lift(operator);\n return (operator.caught = caught as Observable<T>);\n };\n}\n\nclass CatchOperator<T, R> implements Operator<T, T | R> {\n caught: Observable<T>;\n\n constructor(private selector: (err: any, caught: Observable<T>) => ObservableInput<T | R>) {\n }\n\n call(subscriber: Subscriber<R>, source: any): any {\n return source.subscribe(new CatchSubscriber(subscriber, this.selector, this.caught));\n }\n}\n\n/**\n * We need this JSDoc comment for affecting ESDoc.\n * @ignore\n * @extends {Ignored}\n */\nclass CatchSubscriber<T, R> extends SimpleOuterSubscriber<T, T | R> {\n constructor(destination: Subscriber<any>,\n private selector: (err: any, caught: Observable<T>) => ObservableInput<T | R>,\n private caught: Observable<T>) {\n super(destination);\n }\n\n // NOTE: overriding `error` instead of `_error` because we don't want\n // to have this flag this subscriber as `isStopped`. We can mimic the\n // behavior of the RetrySubscriber (from the `retry` operator), where\n // we unsubscribe from our source chain, reset our Subscriber flags,\n // then subscribe to the selector result.\n error(err: any) {\n if (!this.isStopped) {\n let result: any;\n try {\n result = this.selector(err, this.caught);\n } catch (err2) {\n super.error(err2);\n return;\n }\n this._unsubscribeAndRecycle();\n const innerSubscriber = new SimpleInnerSubscriber(this);\n this.add(innerSubscriber);\n const innerSubscription = innerSubscribe(result, innerSubscriber);\n // The returned subscription will usually be the subscriber that was\n // passed. However, interop subscribers will be wrapped and for\n // unsubscriptions to chain correctly, the wrapper needs to be added, too.\n if (innerSubscription !== innerSubscriber) {\n this.add(innerSubscription);\n }\n }\n }\n}\n","import { Observable } from '../Observable';\nimport { SchedulerLike } from '../types';\nimport { Subscription } from '../Subscription';\n\nexport function scheduleArray<T>(input: ArrayLike<T>, scheduler: SchedulerLike) {\n return new Observable<T>(subscriber => {\n const sub = new Subscription();\n let i = 0;\n sub.add(scheduler.schedule(function () {\n if (i === input.length) {\n subscriber.complete();\n return;\n }\n subscriber.next(input[i++]);\n if (!subscriber.closed) {\n sub.add(this.schedule());\n }\n }));\n return sub;\n });\n}\n","import { Observable } from '../Observable';\nimport { SchedulerLike } from '../types';\nimport { subscribeToArray } from '../util/subscribeToArray';\nimport { scheduleArray } from '../scheduled/scheduleArray';\n\nexport function fromArray<T>(input: ArrayLike<T>, scheduler?: SchedulerLike) {\n if (!scheduler) {\n return new Observable<T>(subscribeToArray(input));\n } else {\n return scheduleArray(input, scheduler);\n }\n}\n","import { Observable } from '../Observable';\nimport { Subscription } from '../Subscription';\nimport { observable as Symbol_observable } from '../symbol/observable';\nimport { InteropObservable, SchedulerLike, Subscribable } from '../types';\n\nexport function scheduleObservable<T>(input: InteropObservable<T>, scheduler: SchedulerLike) {\n return new Observable<T>(subscriber => {\n const sub = new Subscription();\n sub.add(scheduler.schedule(() => {\n const observable: Subscribable<T> = input[Symbol_observable]();\n sub.add(observable.subscribe({\n next(value) { sub.add(scheduler.schedule(() => subscriber.next(value))); },\n error(err) { sub.add(scheduler.schedule(() => subscriber.error(err))); },\n complete() { sub.add(scheduler.schedule(() => subscriber.complete())); },\n }));\n }));\n return sub;\n });\n}\n","import { Observable } from '../Observable';\nimport { SchedulerLike } from '../types';\nimport { Subscription } from '../Subscription';\n\nexport function schedulePromise<T>(input: PromiseLike<T>, scheduler: SchedulerLike) {\n return new Observable<T>(subscriber => {\n const sub = new Subscription();\n sub.add(scheduler.schedule(() => input.then(\n value => {\n sub.add(scheduler.schedule(() => {\n subscriber.next(value);\n sub.add(scheduler.schedule(() => subscriber.complete()));\n }));\n },\n err => {\n sub.add(scheduler.schedule(() => subscriber.error(err)));\n }\n )));\n return sub;\n });\n}\n","import { Observable } from '../Observable';\nimport { SchedulerLike } from '../types';\nimport { Subscription } from '../Subscription';\nimport { iterator as Symbol_iterator } from '../symbol/iterator';\n\nexport function scheduleIterable<T>(input: Iterable<T>, scheduler: SchedulerLike) {\n if (!input) {\n throw new Error('Iterable cannot be null');\n }\n return new Observable<T>(subscriber => {\n const sub = new Subscription();\n let iterator: Iterator<T>;\n sub.add(() => {\n // Finalize generators\n if (iterator && typeof iterator.return === 'function') {\n iterator.return();\n }\n });\n sub.add(scheduler.schedule(() => {\n iterator = input[Symbol_iterator]();\n sub.add(scheduler.schedule(function () {\n if (subscriber.closed) {\n return;\n }\n let value: T;\n let done: boolean;\n try {\n const result = iterator.next();\n value = result.value;\n done = result.done;\n } catch (err) {\n subscriber.error(err);\n return;\n }\n if (done) {\n subscriber.complete();\n } else {\n subscriber.next(value);\n this.schedule();\n }\n }));\n }));\n return sub;\n });\n}\n","import { InteropObservable } from '../types';\nimport { observable as Symbol_observable } from '../symbol/observable';\n\n/** Identifies an input as being Observable (but not necessary an Rx Observable) */\nexport function isInteropObservable(input: any): input is InteropObservable<any> {\n return input && typeof input[Symbol_observable] === 'function';\n}\n","import { iterator as Symbol_iterator } from '../symbol/iterator';\n\n/** Identifies an input as being an Iterable */\nexport function isIterable(input: any): input is Iterable<any> {\n return input && typeof input[Symbol_iterator] === 'function';\n}\n","import { scheduleObservable } from './scheduleObservable';\nimport { schedulePromise } from './schedulePromise';\nimport { scheduleArray } from './scheduleArray';\nimport { scheduleIterable } from './scheduleIterable';\nimport { ObservableInput, SchedulerLike, Observable } from 'rxjs';\nimport { isInteropObservable } from '../util/isInteropObservable';\nimport { isPromise } from '../util/isPromise';\nimport { isArrayLike } from '../util/isArrayLike';\nimport { isIterable } from '../util/isIterable';\n\n/**\n * Converts from a common {@link ObservableInput} type to an observable where subscription and emissions\n * are scheduled on the provided scheduler.\n *\n * @see from\n * @see of\n *\n * @param input The observable, array, promise, iterable, etc you would like to schedule\n * @param scheduler The scheduler to use to schedule the subscription and emissions from\n * the returned observable.\n */\nexport function scheduled<T>(input: ObservableInput<T>, scheduler: SchedulerLike): Observable<T> {\n if (input != null) {\n if (isInteropObservable(input)) {\n return scheduleObservable(input, scheduler);\n } else if (isPromise(input)) {\n return schedulePromise(input, scheduler);\n } else if (isArrayLike(input)) {\n return scheduleArray(input, scheduler);\n } else if (isIterable(input) || typeof input === 'string') {\n return scheduleIterable(input, scheduler);\n }\n }\n\n throw new TypeError((input !== null && typeof input || input) + ' is not observable');\n}\n","import { Observable } from '../Observable';\nimport { subscribeTo } from '../util/subscribeTo';\nimport { ObservableInput, SchedulerLike, ObservedValueOf } from '../types';\nimport { scheduled } from '../scheduled/scheduled';\n\nexport function from<O extends ObservableInput<any>>(input: O): Observable<ObservedValueOf<O>>;\n/** @deprecated use {@link scheduled} instead. */\nexport function from<O extends ObservableInput<any>>(input: O, scheduler: SchedulerLike): Observable<ObservedValueOf<O>>;\n\n/**\n * Creates an Observable from an Array, an array-like object, a Promise, an iterable object, or an Observable-like object.\n *\n * <span class=\"informal\">Converts almost anything to an Observable.</span>\n *\n * ![](from.png)\n *\n * `from` converts various other objects and data types into Observables. It also converts a Promise, an array-like, or an\n * <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#iterable\" target=\"_blank\">iterable</a>\n * object into an Observable that emits the items in that promise, array, or iterable. A String, in this context, is treated\n * as an array of characters. Observable-like objects (contains a function named with the ES2015 Symbol for Observable) can also be\n * converted through this operator.\n *\n * ## Examples\n *\n * ### Converts an array to an Observable\n *\n * ```ts\n * import { from } from 'rxjs';\n *\n * const array = [10, 20, 30];\n * const result = from(array);\n *\n * result.subscribe(x => console.log(x));\n *\n * // Logs:\n * // 10\n * // 20\n * // 30\n * ```\n *\n * ---\n *\n * ### Convert an infinite iterable (from a generator) to an Observable\n *\n * ```ts\n * import { from } from 'rxjs';\n * import { take } from 'rxjs/operators';\n *\n * function* generateDoubles(seed) {\n * let i = seed;\n * while (true) {\n * yield i;\n * i = 2 * i; // double it\n * }\n * }\n *\n * const iterator = generateDoubles(3);\n * const result = from(iterator).pipe(take(10));\n *\n * result.subscribe(x => console.log(x));\n *\n * // Logs:\n * // 3\n * // 6\n * // 12\n * // 24\n * // 48\n * // 96\n * // 192\n * // 384\n * // 768\n * // 1536\n * ```\n *\n * ---\n *\n * ### With async scheduler\n *\n * ```ts\n * import { from, asyncScheduler } from 'rxjs';\n *\n * console.log('start');\n *\n * const array = [10, 20, 30];\n * const result = from(array, asyncScheduler);\n *\n * result.subscribe(x => console.log(x));\n *\n * console.log('end');\n *\n * // Logs:\n * // start\n * // end\n * // 10\n * // 20\n * // 30\n * ```\n *\n * @see {@link fromEvent}\n * @see {@link fromEventPattern}\n *\n * @param {ObservableInput<T>} A subscription object, a Promise, an Observable-like,\n * an Array, an iterable, or an array-like object to be converted.\n * @param {SchedulerLike} An optional {@link SchedulerLike} on which to schedule the emission of values.\n * @return {Observable<T>}\n * @name from\n * @owner Observable\n */\nexport function from<T>(input: ObservableInput<T>, scheduler?: SchedulerLike): Observable<T> {\n if (!scheduler) {\n if (input instanceof Observable) {\n return input;\n }\n return new Observable<T>(subscribeTo(input));\n } else {\n return scheduled(input, scheduler);\n }\n}\n","import { SchedulerLike } from '../types';\nimport { isScheduler } from '../util/isScheduler';\nimport { fromArray } from './fromArray';\nimport { Observable } from '../Observable';\nimport { scheduleArray } from '../scheduled/scheduleArray';\n\n/* tslint:disable:max-line-length */\n/** @deprecated use {@link scheduled} instead `scheduled([a, b, c], scheduler)` */\nexport function of<T>(a: T, scheduler: SchedulerLike): Observable<T>;\n/** @deprecated use {@link scheduled} instead `scheduled([a, b, c], scheduler)` */\nexport function of<T, T2>(a: T, b: T2, scheduler: SchedulerLike): Observable<T | T2>;\n/** @deprecated use {@link scheduled} instead `scheduled([a, b, c], scheduler)` */\nexport function of<T, T2, T3>(a: T, b: T2, c: T3, scheduler: SchedulerLike): Observable<T | T2 | T3>;\n/** @deprecated use {@link scheduled} instead `scheduled([a, b, c], scheduler)` */\nexport function of<T, T2, T3, T4>(a: T, b: T2, c: T3, d: T4, scheduler: SchedulerLike): Observable<T | T2 | T3 | T4>;\n/** @deprecated use {@link scheduled} instead `scheduled([a, b, c], scheduler)` */\nexport function of<T, T2, T3, T4, T5>(a: T, b: T2, c: T3, d: T4, e: T5, scheduler: SchedulerLike): Observable<T | T2 | T3 | T4 | T5>;\n/** @deprecated use {@link scheduled} instead `scheduled([a, b, c], scheduler)` */\nexport function of<T, T2, T3, T4, T5, T6>(a: T, b: T2, c: T3, d: T4, e: T5, f: T6, scheduler: SchedulerLike): Observable<T | T2 | T3 | T4 | T5 | T6>;\n/** @deprecated use {@link scheduled} instead `scheduled([a, b, c], scheduler)` */\nexport function of<T, T2, T3, T4, T5, T6, T7>(a: T, b: T2, c: T3, d: T4, e: T5, f: T6, g: T7, scheduler: SchedulerLike):\n Observable<T | T2 | T3 | T4 | T5 | T6 | T7>;\n/** @deprecated use {@link scheduled} instead `scheduled([a, b, c], scheduler)` */\nexport function of<T, T2, T3, T4, T5, T6, T7, T8>(a: T, b: T2, c: T3, d: T4, e: T5, f: T6, g: T7, h: T8, scheduler: SchedulerLike):\n Observable<T | T2 | T3 | T4 | T5 | T6 | T7 | T8>;\n/** @deprecated use {@link scheduled} instead `scheduled([a, b, c], scheduler)` */\nexport function of<T, T2, T3, T4, T5, T6, T7, T8, T9>(a: T, b: T2, c: T3, d: T4, e: T5, f: T6, g: T7, h: T8, i: T9, scheduler: SchedulerLike):\n Observable<T | T2 | T3 | T4 | T5 | T6 | T7 | T8 | T9>;\nexport function of<T>(...args: (T | SchedulerLike)[]): Observable<T>;\n\n// TODO(benlesh): Update the typings for this when we can switch to TS 3.x\nexport function of<T>(a: T): Observable<T>;\nexport function of<T, T2>(a: T, b: T2): Observable<T | T2>;\nexport function of<T, T2, T3>(a: T, b: T2, c: T3): Observable<T | T2 | T3>;\nexport function of<T, T2, T3, T4>(a: T, b: T2, c: T3, d: T4): Observable<T | T2 | T3 | T4>;\nexport function of<T, T2, T3, T4, T5>(a: T, b: T2, c: T3, d: T4, e: T5): Observable<T | T2 | T3 | T4 | T5>;\nexport function of<T, T2, T3, T4, T5, T6>(a: T, b: T2, c: T3, d: T4, e: T5, f: T6): Observable<T | T2 | T3 | T4 | T5 | T6>;\nexport function of<T, T2, T3, T4, T5, T6, T7>(a: T, b: T2, c: T3, d: T4, e: T5, f: T6, g: T7):\n Observable<T | T2 | T3 | T4 | T5 | T6 | T7>;\nexport function of<T, T2, T3, T4, T5, T6, T7, T8>(a: T, b: T2, c: T3, d: T4, e: T5, f: T6, g: T7, h: T8):\n Observable<T | T2 | T3 | T4 | T5 | T6 | T7 | T8>;\nexport function of<T, T2, T3, T4, T5, T6, T7, T8, T9>(a: T, b: T2, c: T3, d: T4, e: T5, f: T6, g: T7, h: T8, i: T9):\n Observable<T | T2 | T3 | T4 | T5 | T6 | T7 | T8 | T9>;\nexport function of<T>(...args: T[]): Observable<T>;\n/* tslint:enable:max-line-length */\n\n/**\n * Converts the arguments to an observable sequence.\n *\n * <span class=\"informal\">Each argument becomes a `next` notification.</span>\n *\n * ![](of.png)\n *\n * Unlike {@link from}, it does not do any flattening and emits each argument in whole\n * as a separate `next` notification.\n *\n * ## Examples\n *\n * Emit the values `10, 20, 30`\n *\n * ```ts\n * import { of } from 'rxjs';\n *\n * of(10, 20, 30)\n * .subscribe(\n * next => console.log('next:', next),\n * err => console.log('error:', err),\n * () => console.log('the end'),\n * );\n * // result:\n * // 'next: 10'\n * // 'next: 20'\n * // 'next: 30'\n *\n * ```\n *\n * Emit the array `[1,2,3]`\n *\n * ```ts\n * import { of } from 'rxjs';\n *\n * of([1,2,3])\n * .subscribe(\n * next => console.log('next:', next),\n * err => console.log('error:', err),\n * () => console.log('the end'),\n * );\n * // result:\n * // 'next: [1,2,3]'\n * ```\n *\n * @see {@link from}\n * @see {@link range}\n *\n * @param {...T} values A comma separated list of arguments you want to be emitted\n * @return {Observable} An Observable that emits the arguments\n * described above and then completes.\n * @method of\n * @owner Observable\n */\n\nexport function of<T>(...args: Array<T | SchedulerLike>): Observable<T> {\n let scheduler = args[args.length - 1] as SchedulerLike;\n if (isScheduler(scheduler)) {\n args.pop();\n return scheduleArray(args as T[], scheduler);\n } else {\n return fromArray(args as T[]);\n }\n}\n","import { Operator } from '../Operator';\nimport { Subscriber } from '../Subscriber';\nimport { Observable } from '../Observable';\nimport { OperatorFunction } from '../types';\n\n/**\n * Applies a given `project` function to each value emitted by the source\n * Observable, and emits the resulting values as an Observable.\n *\n * <span class=\"informal\">Like [Array.prototype.map()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map),\n * it passes each source value through a transformation function to get\n * corresponding output values.</span>\n *\n * ![](map.png)\n *\n * Similar to the well known `Array.prototype.map` function, this operator\n * applies a projection to each value and emits that projection in the output\n * Observable.\n *\n * ## Example\n * Map every click to the clientX position of that click\n * ```ts\n * import { fromEvent } from 'rxjs';\n * import { map } from 'rxjs/operators';\n *\n * const clicks = fromEvent(document, 'click');\n * const positions = clicks.pipe(map(ev => ev.clientX));\n * positions.subscribe(x => console.log(x));\n * ```\n *\n * @see {@link mapTo}\n * @see {@link pluck}\n *\n * @param {function(value: T, index: number): R} project The function to apply\n * to each `value` emitted by the source Observable. The `index` parameter is\n * the number `i` for the i-th emission that has happened since the\n * subscription, starting from the number `0`.\n * @param {any} [thisArg] An optional argument to define what `this` is in the\n * `project` function.\n * @return {Observable<R>} An Observable that emits the values from the source\n * Observable transformed by the given `project` function.\n * @method map\n * @owner Observable\n */\nexport function map<T, R>(project: (value: T, index: number) => R, thisArg?: any): OperatorFunction<T, R> {\n return function mapOperation(source: Observable<T>): Observable<R> {\n if (typeof project !== 'function') {\n throw new TypeError('argument is not a function. Are you looking for `mapTo()`?');\n }\n return source.lift(new MapOperator(project, thisArg));\n };\n}\n\nexport class MapOperator<T, R> implements Operator<T, R> {\n constructor(private project: (value: T, index: number) => R, private thisArg: any) {\n }\n\n call(subscriber: Subscriber<R>, source: any): any {\n return source.subscribe(new MapSubscriber(subscriber, this.project, this.thisArg));\n }\n}\n\n/**\n * We need this JSDoc comment for affecting ESDoc.\n * @ignore\n * @extends {Ignored}\n */\nclass MapSubscriber<T, R> extends Subscriber<T> {\n count: number = 0;\n private thisArg: any;\n\n constructor(destination: Subscriber<R>,\n private project: (value: T, index: number) => R,\n thisArg: any) {\n super(destination);\n this.thisArg = thisArg || this;\n }\n\n // NOTE: This looks unoptimized, but it's actually purposefully NOT\n // using try/catch optimizations.\n protected _next(value: T) {\n let result: R;\n try {\n result = this.project.call(this.thisArg, value, this.count++);\n } catch (err) {\n this.destination.error(err);\n return;\n }\n this.destination.next(result);\n }\n}\n","import { Observable } from '../Observable';\nimport { Operator } from '../Operator';\nimport { Subscriber } from '../Subscriber';\nimport { Subscription } from '../Subscription';\nimport { ObservableInput, OperatorFunction, ObservedValueOf } from '../types';\nimport { map } from './map';\nimport { from } from '../observable/from';\nimport { SimpleOuterSubscriber, SimpleInnerSubscriber, innerSubscribe } from '../innerSubscribe';\n\n/* tslint:disable:max-line-length */\nexport function mergeMap<T, O extends ObservableInput<any>>(project: (value: T, index: number) => O, concurrent?: number): OperatorFunction<T, ObservedValueOf<O>>;\n/** @deprecated resultSelector no longer supported, use inner map instead */\nexport function mergeMap<T, O extends ObservableInput<any>>(project: (value: T, index: number) => O, resultSelector: undefined, concurrent?: number): OperatorFunction<T, ObservedValueOf<O>>;\n/** @deprecated resultSelector no longer supported, use inner map instead */\nexport function mergeMap<T, R, O extends ObservableInput<any>>(project: (value: T, index: number) => O, resultSelector: (outerValue: T, innerValue: ObservedValueOf<O>, outerIndex: number, innerIndex: number) => R, concurrent?: number): OperatorFunction<T, R>;\n/* tslint:enable:max-line-length */\n\n/**\n * Projects each source value to an Observable which is merged in the output\n * Observable.\n *\n * <span class=\"informal\">Maps each value to an Observable, then flattens all of\n * these inner Observables using {@link mergeAll}.</span>\n *\n * ![](mergeMap.png)\n *\n * Returns an Observable that emits items based on applying a function that you\n * supply to each item emitted by the source Observable, where that function\n * returns an Observable, and then merging those resulting Observables and\n * emitting the results of this merger.\n *\n * ## Example\n * Map and flatten each letter to an Observable ticking every 1 second\n * ```ts\n * import { of, interval } from 'rxjs';\n * import { mergeMap, map } from 'rxjs/operators';\n *\n * const letters = of('a', 'b', 'c');\n * const result = letters.pipe(\n * mergeMap(x => interval(1000).pipe(map(i => x+i))),\n * );\n * result.subscribe(x => console.log(x));\n *\n * // Results in the following:\n * // a0\n * // b0\n * // c0\n * // a1\n * // b1\n * // c1\n * // continues to list a,b,c with respective ascending integers\n * ```\n *\n * @see {@link concatMap}\n * @see {@link exhaustMap}\n * @see {@link merge}\n * @see {@link mergeAll}\n * @see {@link mergeMapTo}\n * @see {@link mergeScan}\n * @see {@link switchMap}\n *\n * @param {function(value: T, ?index: number): ObservableInput} project A function\n * that, when applied to an item emitted by the source Observable, returns an\n * Observable.\n * @param {number} [concurrent=Number.POSITIVE_INFINITY] Maximum number of input\n * Observables being subscribed to concurrently.\n * @return {Observable} An Observable that emits the result of applying the\n * projection function (and the optional deprecated `resultSelector`) to each item\n * emitted by the source Observable and merging the results of the Observables\n * obtained from this transformation.\n */\nexport function mergeMap<T, R, O extends ObservableInput<any>>(\n project: (value: T, index: number) => O,\n resultSelector?: ((outerValue: T, innerValue: ObservedValueOf<O>, outerIndex: number, innerIndex: number) => R) | number,\n concurrent: number = Number.POSITIVE_INFINITY\n): OperatorFunction<T, ObservedValueOf<O>|R> {\n if (typeof resultSelector === 'function') {\n // DEPRECATED PATH\n return (source: Observable<T>) => source.pipe(\n mergeMap((a, i) => from(project(a, i)).pipe(\n map((b: any, ii: number) => resultSelector(a, b, i, ii)),\n ), concurrent)\n );\n } else if (typeof resultSelector === 'number') {\n concurrent = resultSelector;\n }\n return (source: Observable<T>) => source.lift(new MergeMapOperator(project, concurrent));\n}\n\nexport class MergeMapOperator<T, R> implements Operator<T, R> {\n constructor(private project: (value: T, index: number) => ObservableInput<R>,\n private concurrent: number = Number.POSITIVE_INFINITY) {\n }\n\n call(observer: Subscriber<R>, source: any): any {\n return source.subscribe(new MergeMapSubscriber(\n observer, this.project, this.concurrent\n ));\n }\n}\n\n/**\n * We need this JSDoc comment for affecting ESDoc.\n * @ignore\n * @extends {Ignored}\n */\nexport class MergeMapSubscriber<T, R> extends SimpleOuterSubscriber<T, R> {\n private hasCompleted: boolean = false;\n private buffer: T[] = [];\n private active: number = 0;\n protected index: number = 0;\n\n constructor(destination: Subscriber<R>,\n private project: (value: T, index: number) => ObservableInput<R>,\n private concurrent: number = Number.POSITIVE_INFINITY) {\n super(destination);\n }\n\n protected _next(value: T): void {\n if (this.active < this.concurrent) {\n this._tryNext(value);\n } else {\n this.buffer.push(value);\n }\n }\n\n protected _tryNext(value: T) {\n let result: ObservableInput<R>;\n const index = this.index++;\n try {\n result = this.project(value, index);\n } catch (err) {\n this.destination.error!(err);\n return;\n }\n this.active++;\n this._innerSub(result);\n }\n\n private _innerSub(ish: ObservableInput<R>): void {\n const innerSubscriber = new SimpleInnerSubscriber(this);\n const destination = this.destination as Subscription;\n destination.add(innerSubscriber);\n const innerSubscription = innerSubscribe(ish, innerSubscriber);\n // The returned subscription will usually be the subscriber that was\n // passed. However, interop subscribers will be wrapped and for\n // unsubscriptions to chain correctly, the wrapper needs to be added, too.\n if (innerSubscription !== innerSubscriber) {\n destination.add(innerSubscription);\n }\n }\n\n protected _complete(): void {\n this.hasCompleted = true;\n if (this.active === 0 && this.buffer.length === 0) {\n this.destination.complete!();\n }\n this.unsubscribe();\n }\n\n notifyNext(innerValue: R): void {\n this.destination.next!(innerValue);\n }\n\n notifyComplete(): void {\n const buffer = this.buffer;\n this.active--;\n if (buffer.length > 0) {\n this._next(buffer.shift()!);\n } else if (this.active === 0 && this.hasCompleted) {\n this.destination.complete!();\n }\n }\n}\n\n/**\n * @deprecated renamed. Use {@link mergeMap}\n */\nexport const flatMap = mergeMap;","\nimport { mergeMap } from './mergeMap';\nimport { identity } from '../util/identity';\nimport { OperatorFunction, ObservableInput } from '../types';\n\n/**\n * Converts a higher-order Observable into a first-order Observable which\n * concurrently delivers all values that are emitted on the inner Observables.\n *\n * <span class=\"informal\">Flattens an Observable-of-Observables.</span>\n *\n * ![](mergeAll.png)\n *\n * `mergeAll` subscribes to an Observable that emits Observables, also known as\n * a higher-order Observable. Each time it observes one of these emitted inner\n * Observables, it subscribes to that and delivers all the values from the\n * inner Observable on the output Observable. The output Observable only\n * completes once all inner Observables have completed. Any error delivered by\n * a inner Observable will be immediately emitted on the output Observable.\n *\n * ## Examples\n * Spawn a new interval Observable for each click event, and blend their outputs as one Observable\n * ```ts\n * import { fromEvent, interval } from 'rxjs';\n * import { map, mergeAll } from 'rxjs/operators';\n *\n * const clicks = fromEvent(document, 'click');\n * const higherOrder = clicks.pipe(map((ev) => interval(1000)));\n * const firstOrder = higherOrder.pipe(mergeAll());\n * firstOrder.subscribe(x => console.log(x));\n * ```\n *\n * Count from 0 to 9 every second for each click, but only allow 2 concurrent timers\n * ```ts\n * import { fromEvent, interval } from 'rxjs';\n * import { take, map, mergeAll } from 'rxjs/operators';\n *\n * const clicks = fromEvent(document, 'click');\n * const higherOrder = clicks.pipe(\n * map((ev) => interval(1000).pipe(take(10))),\n * );\n * const firstOrder = higherOrder.pipe(mergeAll(2));\n * firstOrder.subscribe(x => console.log(x));\n * ```\n *\n * @see {@link combineAll}\n * @see {@link concatAll}\n * @see {@link exhaust}\n * @see {@link merge}\n * @see {@link mergeMap}\n * @see {@link mergeMapTo}\n * @see {@link mergeScan}\n * @see {@link switchAll}\n * @see {@link switchMap}\n * @see {@link zipAll}\n *\n * @param {number} [concurrent=Number.POSITIVE_INFINITY] Maximum number of inner\n * Observables being subscribed to concurrently.\n * @return {Observable} An Observable that emits values coming from all the\n * inner Observables emitted by the source Observable.\n * @method mergeAll\n * @owner Observable\n */\nexport function mergeAll<T>(concurrent: number = Number.POSITIVE_INFINITY): OperatorFunction<ObservableInput<T>, T> {\n return mergeMap(identity, concurrent);\n}\n","\nimport { mergeAll } from './mergeAll';\nimport { OperatorFunction, ObservableInput } from '../types';\n\nexport function concatAll<T>(): OperatorFunction<ObservableInput<T>, T>;\nexport function concatAll<R>(): OperatorFunction<any, R>;\n\n/**\n * Converts a higher-order Observable into a first-order Observable by\n * concatenating the inner Observables in order.\n *\n * <span class=\"informal\">Flattens an Observable-of-Observables by putting one\n * inner Observable after the other.</span>\n *\n * ![](concatAll.png)\n *\n * Joins every Observable emitted by the source (a higher-order Observable), in\n * a serial fashion. It subscribes to each inner Observable only after the\n * previous inner Observable has completed, and merges all of their values into\n * the returned observable.\n *\n * __Warning:__ If the source Observable emits Observables quickly and\n * endlessly, and the inner Observables it emits generally complete slower than\n * the source emits, you can run into memory issues as the incoming Observables\n * collect in an unbounded buffer.\n *\n * Note: `concatAll` is equivalent to `mergeAll` with concurrency parameter set\n * to `1`.\n *\n * ## Example\n *\n * For each click event, tick every second from 0 to 3, with no concurrency\n * ```ts\n * import { fromEvent, interval } from 'rxjs';\n * import { map, take, concatAll } from 'rxjs/operators';\n *\n * const clicks = fromEvent(document, 'click');\n * const higherOrder = clicks.pipe(\n * map(ev => interval(1000).pipe(take(4))),\n * );\n * const firstOrder = higherOrder.pipe(concatAll());\n * firstOrder.subscribe(x => console.log(x));\n *\n * // Results in the following:\n * // (results are not concurrent)\n * // For every click on the \"document\" it will emit values 0 to 3 spaced\n * // on a 1000ms interval\n * // one click = 1000ms-> 0 -1000ms-> 1 -1000ms-> 2 -1000ms-> 3\n * ```\n *\n * @see {@link combineAll}\n * @see {@link concat}\n * @see {@link concatMap}\n * @see {@link concatMapTo}\n * @see {@link exhaust}\n * @see {@link mergeAll}\n * @see {@link switchAll}\n * @see {@link switchMap}\n * @see {@link zipAll}\n *\n * @return {Observable} An Observable emitting values from all the inner\n * Observables concatenated.\n * @method concatAll\n * @owner Observable\n */\nexport function concatAll<T>(): OperatorFunction<ObservableInput<T>, T> {\n return mergeAll<T>(1);\n}\n","import { Observable } from '../Observable';\nimport { ObservableInput, SchedulerLike, ObservedValueOf } from '../types';\nimport { isScheduler } from '../util/isScheduler';\nimport { of } from './of';\nimport { from } from './from';\nimport { concatAll } from '../operators/concatAll';\n\n/* tslint:disable:max-line-length */\n/** @deprecated Use {@link scheduled} and {@link concatAll} (e.g. `scheduled([o1, o2, o3], scheduler).pipe(concatAll())`) */\nexport function concat<O1 extends ObservableInput<any>>(v1: O1, scheduler: SchedulerLike): Observable<ObservedValueOf<O1>>;\n/** @deprecated Use {@link scheduled} and {@link concatAll} (e.g. `scheduled([o1, o2, o3], scheduler).pipe(concatAll())`) */\nexport function concat<O1 extends ObservableInput<any>, O2 extends ObservableInput<any>>(v1: O1, v2: O2, scheduler: SchedulerLike): Observable<ObservedValueOf<O1> | ObservedValueOf<O2>>;\n/** @deprecated Use {@link scheduled} and {@link concatAll} (e.g. `scheduled([o1, o2, o3], scheduler).pipe(concatAll())`) */\nexport function concat<O1 extends ObservableInput<any>, O2 extends ObservableInput<any>, O3 extends ObservableInput<any>>(v1: O1, v2: O2, v3: O3, scheduler: SchedulerLike): Observable<ObservedValueOf<O1> | ObservedValueOf<O2> | ObservedValueOf<O3>>;\n/** @deprecated Use {@link scheduled} and {@link concatAll} (e.g. `scheduled([o1, o2, o3], scheduler).pipe(concatAll())`) */\nexport function concat<O1 extends ObservableInput<any>, O2 extends ObservableInput<any>, O3 extends ObservableInput<any>, O4 extends ObservableInput<any>>(v1: O1, v2: O2, v3: O3, v4: O4, scheduler: SchedulerLike): Observable<ObservedValueOf<O1> | ObservedValueOf<O2> | ObservedValueOf<O3> | ObservedValueOf<O4>>;\n/** @deprecated Use {@link scheduled} and {@link concatAll} (e.g. `scheduled([o1, o2, o3], scheduler).pipe(concatAll())`) */\nexport function concat<O1 extends ObservableInput<any>, O2 extends ObservableInput<any>, O3 extends ObservableInput<any>, O4 extends ObservableInput<any>, O5 extends ObservableInput<any>>(v1: O1, v2: O2, v3: O3, v4: O4, v5: O5, scheduler: SchedulerLike): Observable<ObservedValueOf<O1> | ObservedValueOf<O2> | ObservedValueOf<O3> | ObservedValueOf<O4> | ObservedValueOf<O5>>;\n/** @deprecated Use {@link scheduled} and {@link concatAll} (e.g. `scheduled([o1, o2, o3], scheduler).pipe(concatAll())`) */\nexport function concat<O1 extends ObservableInput<any>, O2 extends ObservableInput<any>, O3 extends ObservableInput<any>, O4 extends ObservableInput<any>, O5 extends ObservableInput<any>, O6 extends ObservableInput<any>>(v1: O1, v2: O2, v3: O3, v4: O4, v5: O5, v6: O6, scheduler: SchedulerLike): Observable<ObservedValueOf<O1> | ObservedValueOf<O2> | ObservedValueOf<O3> | ObservedValueOf<O4> | ObservedValueOf<O5> | ObservedValueOf<O6>>;\n\nexport function concat<O1 extends ObservableInput<any>>(v1: O1): Observable<ObservedValueOf<O1>>;\nexport function concat<O1 extends ObservableInput<any>, O2 extends ObservableInput<any>>(v1: O1, v2: O2): Observable<ObservedValueOf<O1> | ObservedValueOf<O2>>;\nexport function concat<O1 extends ObservableInput<any>, O2 extends ObservableInput<any>, O3 extends ObservableInput<any>>(v1: O1, v2: O2, v3: O3): Observable<ObservedValueOf<O1> | ObservedValueOf<O2> | ObservedValueOf<O3>>;\nexport function concat<O1 extends ObservableInput<any>, O2 extends ObservableInput<any>, O3 extends ObservableInput<any>, O4 extends ObservableInput<any>>(v1: O1, v2: O2, v3: O3, v4: O4): Observable<ObservedValueOf<O1> | ObservedValueOf<O2> | ObservedValueOf<O3> | ObservedValueOf<O4>>;\nexport function concat<O1 extends ObservableInput<any>, O2 extends ObservableInput<any>, O3 extends ObservableInput<any>, O4 extends ObservableInput<any>, O5 extends ObservableInput<any>>(v1: O1, v2: O2, v3: O3, v4: O4, v5: O5): Observable<ObservedValueOf<O1> | ObservedValueOf<O2> | ObservedValueOf<O3> | ObservedValueOf<O4> | ObservedValueOf<O5>>;\nexport function concat<O1 extends ObservableInput<any>, O2 extends ObservableInput<any>, O3 extends ObservableInput<any>, O4 extends ObservableInput<any>, O5 extends ObservableInput<any>, O6 extends ObservableInput<any>>(v1: O1, v2: O2, v3: O3, v4: O4, v5: O5, v6: O6): Observable<ObservedValueOf<O1> | ObservedValueOf<O2> | ObservedValueOf<O3> | ObservedValueOf<O4> | ObservedValueOf<O5> | ObservedValueOf<O6>>;\nexport function concat<O extends ObservableInput<any>>(...observables: O[]): Observable<ObservedValueOf<O>>;\n/** @deprecated Use {@link scheduled} and {@link concatAll} (e.g. `scheduled([o1, o2, o3], scheduler).pipe(concatAll())`) */\nexport function concat<O extends ObservableInput<any>>(...observables: (O | SchedulerLike)[]): Observable<ObservedValueOf<O>>;\nexport function concat<R>(...observables: ObservableInput<any>[]): Observable<R>;\n/** @deprecated Use {@link scheduled} and {@link concatAll} (e.g. `scheduled([o1, o2, o3], scheduler).pipe(concatAll())`) */\nexport function concat<R>(...observables: (ObservableInput<any> | SchedulerLike)[]): Observable<R>;\n/* tslint:enable:max-line-length */\n/**\n * Creates an output Observable which sequentially emits all values from given\n * Observable and then moves on to the next.\n *\n * <span class=\"informal\">Concatenates multiple Observables together by\n * sequentially emitting their values, one Observable after the other.</span>\n *\n * ![](concat.png)\n *\n * `concat` joins multiple Observables together, by subscribing to them one at a time and\n * merging their results into the output Observable. You can pass either an array of\n * Observables, or put them directly as arguments. Passing an empty array will result\n * in Observable that completes immediately.\n *\n * `concat` will subscribe to first input Observable and emit all its values, without\n * changing or affecting them in any way. When that Observable completes, it will\n * subscribe to then next Observable passed and, again, emit its values. This will be\n * repeated, until the operator runs out of Observables. When last input Observable completes,\n * `concat` will complete as well. At any given moment only one Observable passed to operator\n * emits values. If you would like to emit values from passed Observables concurrently, check out\n * {@link merge} instead, especially with optional `concurrent` parameter. As a matter of fact,\n * `concat` is an equivalent of `merge` operator with `concurrent` parameter set to `1`.\n *\n * Note that if some input Observable never completes, `concat` will also never complete\n * and Observables following the one that did not complete will never be subscribed. On the other\n * hand, if some Observable simply completes immediately after it is subscribed, it will be\n * invisible for `concat`, which will just move on to the next Observable.\n *\n * If any Observable in chain errors, instead of passing control to the next Observable,\n * `concat` will error immediately as well. Observables that would be subscribed after\n * the one that emitted error, never will.\n *\n * If you pass to `concat` the same Observable many times, its stream of values\n * will be \"replayed\" on every subscription, which means you can repeat given Observable\n * as many times as you like. If passing the same Observable to `concat` 1000 times becomes tedious,\n * you can always use {@link repeat}.\n *\n * ## Examples\n * ### Concatenate a timer counting from 0 to 3 with a synchronous sequence from 1 to 10\n * ```ts\n * import { concat, interval, range } from 'rxjs';\n * import { take } from 'rxjs/operators';\n *\n * const timer = interval(1000).pipe(take(4));\n * const sequence = range(1, 10);\n * const result = concat(timer, sequence);\n * result.subscribe(x => console.log(x));\n *\n * // results in:\n * // 0 -1000ms-> 1 -1000ms-> 2 -1000ms-> 3 -immediate-> 1 ... 10\n * ```\n *\n * ### Concatenate 3 Observables\n * ```ts\n * import { concat, interval } from 'rxjs';\n * import { take } from 'rxjs/operators';\n *\n * const timer1 = interval(1000).pipe(take(10));\n * const timer2 = interval(2000).pipe(take(6));\n * const timer3 = interval(500).pipe(take(10));\n *\n * const result = concat(timer1, timer2, timer3);\n * result.subscribe(x => console.log(x));\n *\n * // results in the following:\n * // (Prints to console sequentially)\n * // -1000ms-> 0 -1000ms-> 1 -1000ms-> ... 9\n * // -2000ms-> 0 -2000ms-> 1 -2000ms-> ... 5\n * // -500ms-> 0 -500ms-> 1 -500ms-> ... 9\n * ```\n *\n * ### Concatenate the same Observable to repeat it\n * ```ts\n * import { concat, interval } from 'rxjs';\n * import { take } from 'rxjs/operators';\n *\n * const timer = interval(1000).pipe(take(2));\n *\n * concat(timer, timer) // concatenating the same Observable!\n * .subscribe(\n * value => console.log(value),\n * err => {},\n * () => console.log('...and it is done!')\n * );\n *\n * // Logs:\n * // 0 after 1s\n * // 1 after 2s\n * // 0 after 3s\n * // 1 after 4s\n * // \"...and it is done!\" also after 4s\n * ```\n *\n * @see {@link concatAll}\n * @see {@link concatMap}\n * @see {@link concatMapTo}\n * @see {@link startWith}\n * @see {@link endWith}\n *\n * @param {ObservableInput} input1 An input Observable to concatenate with others.\n * @param {ObservableInput} input2 An input Observable to concatenate with others.\n * More than one input Observables may be given as argument.\n * @param {SchedulerLike} [scheduler=null] An optional {@link SchedulerLike} to schedule each\n * Observable subscription on.\n * @return {Observable} All values of each passed Observable merged into a\n * single Observable, in order, in serial fashion.\n * @static true\n * @name concat\n * @owner Observable\n */\nexport function concat<O extends ObservableInput<any>, R>(...observables: Array<O | SchedulerLike>): Observable<ObservedValueOf<O> | R> {\n return concatAll<R>()(of(...observables));\n}\n","import { Operator } from '../Operator';\nimport { Observable } from '../Observable';\nimport { Subscriber } from '../Subscriber';\nimport { Subscription } from '../Subscription';\nimport { async } from '../scheduler/async';\nimport { MonoTypeOperatorFunction, SchedulerLike, TeardownLogic } from '../types';\n\n/**\n * Emits a value from the source Observable only after a particular time span\n * has passed without another source emission.\n *\n * <span class=\"informal\">It's like {@link delay}, but passes only the most\n * recent value from each burst of emissions.</span>\n *\n * ![](debounceTime.png)\n *\n * `debounceTime` delays values emitted by the source Observable, but drops\n * previous pending delayed emissions if a new value arrives on the source\n * Observable. This operator keeps track of the most recent value from the\n * source Observable, and emits that only when `dueTime` enough time has passed\n * without any other value appearing on the source Observable. If a new value\n * appears before `dueTime` silence occurs, the previous value will be dropped\n * and will not be emitted on the output Observable.\n *\n * This is a rate-limiting operator, because it is impossible for more than one\n * value to be emitted in any time window of duration `dueTime`, but it is also\n * a delay-like operator since output emissions do not occur at the same time as\n * they did on the source Observable. Optionally takes a {@link SchedulerLike} for\n * managing timers.\n *\n * ## Example\n * Emit the most recent click after a burst of clicks\n * ```ts\n * import { fromEvent } from 'rxjs';\n * import { debounceTime } from 'rxjs/operators';\n *\n * const clicks = fromEvent(document, 'click');\n * const result = clicks.pipe(debounceTime(1000));\n * result.subscribe(x => console.log(x));\n * ```\n *\n * @see {@link auditTime}\n * @see {@link debounce}\n * @see {@link delay}\n * @see {@link sampleTime}\n * @see {@link throttleTime}\n *\n * @param {number} dueTime The timeout duration in milliseconds (or the time\n * unit determined internally by the optional `scheduler`) for the window of\n * time required to wait for emission silence before emitting the most recent\n * source value.\n * @param {SchedulerLike} [scheduler=async] The {@link SchedulerLike} to use for\n * managing the timers that handle the timeout for each value.\n * @return {Observable} An Observable that delays the emissions of the source\n * Observable by the specified `dueTime`, and may drop some values if they occur\n * too frequently.\n * @method debounceTime\n * @owner Observable\n */\nexport function debounceTime<T>(dueTime: number, scheduler: SchedulerLike = async): MonoTypeOperatorFunction<T> {\n return (source: Observable<T>) => source.lift(new DebounceTimeOperator(dueTime, scheduler));\n}\n\nclass DebounceTimeOperator<T> implements Operator<T, T> {\n constructor(private dueTime: number, private scheduler: SchedulerLike) {\n }\n\n call(subscriber: Subscriber<T>, source: any): TeardownLogic {\n return source.subscribe(new DebounceTimeSubscriber(subscriber, this.dueTime, this.scheduler));\n }\n}\n\n/**\n * We need this JSDoc comment for affecting ESDoc.\n * @ignore\n * @extends {Ignored}\n */\nclass DebounceTimeSubscriber<T> extends Subscriber<T> {\n private debouncedSubscription: Subscription = null;\n private lastValue: T = null;\n private hasValue: boolean = false;\n\n constructor(destination: Subscriber<T>,\n private dueTime: number,\n private scheduler: SchedulerLike) {\n super(destination);\n }\n\n protected _next(value: T) {\n this.clearDebounce();\n this.lastValue = value;\n this.hasValue = true;\n this.add(this.debouncedSubscription = this.scheduler.schedule(dispatchNext, this.dueTime, this));\n }\n\n protected _complete() {\n this.debouncedNext();\n this.destination.complete();\n }\n\n debouncedNext(): void {\n this.clearDebounce();\n\n if (this.hasValue) {\n const { lastValue } = this;\n // This must be done *before* passing the value\n // along to the destination because it's possible for\n // the value to synchronously re-enter this operator\n // recursively when scheduled with things like\n // VirtualScheduler/TestScheduler.\n this.lastValue = null;\n this.hasValue = false;\n this.destination.next(lastValue);\n }\n }\n\n private clearDebounce(): void {\n const debouncedSubscription = this.debouncedSubscription;\n\n if (debouncedSubscription !== null) {\n this.remove(debouncedSubscription);\n debouncedSubscription.unsubscribe();\n this.debouncedSubscription = null;\n }\n }\n}\n\nfunction dispatchNext(subscriber: DebounceTimeSubscriber<any>) {\n subscriber.debouncedNext();\n}\n","export function isDate(value: any): value is Date {\n return value instanceof Date && !isNaN(+value);\n}\n","import { Observable } from '../Observable';\nimport { SchedulerLike } from '../types';\n\n/**\n * The same Observable instance returned by any call to {@link empty} without a\n * `scheduler`. It is preferrable to use this over `empty()`.\n */\nexport const EMPTY = new Observable<never>(subscriber => subscriber.complete());\n\n/**\n * Creates an Observable that emits no items to the Observer and immediately\n * emits a complete notification.\n *\n * <span class=\"informal\">Just emits 'complete', and nothing else.\n * </span>\n *\n * ![](empty.png)\n *\n * This static operator is useful for creating a simple Observable that only\n * emits the complete notification. It can be used for composing with other\n * Observables, such as in a {@link mergeMap}.\n *\n * ## Examples\n * ### Emit the number 7, then complete\n * ```ts\n * import { empty } from 'rxjs';\n * import { startWith } from 'rxjs/operators';\n *\n * const result = empty().pipe(startWith(7));\n * result.subscribe(x => console.log(x));\n * ```\n *\n * ### Map and flatten only odd numbers to the sequence 'a', 'b', 'c'\n * ```ts\n * import { empty, interval, of } from 'rxjs';\n * import { mergeMap } from 'rxjs/operators';\n *\n * const interval$ = interval(1000);\n * const result = interval$.pipe(\n * mergeMap(x => x % 2 === 1 ? of('a', 'b', 'c') : empty()),\n * );\n * result.subscribe(x => console.log(x));\n *\n * // Results in the following to the console:\n * // x is equal to the count on the interval eg(0,1,2,3,...)\n * // x will occur every 1000ms\n * // if x % 2 is equal to 1 print abc\n * // if x % 2 is not equal to 1 nothing will be output\n * ```\n *\n * @see {@link Observable}\n * @see {@link never}\n * @see {@link of}\n * @see {@link throwError}\n *\n * @param scheduler A {@link SchedulerLike} to use for scheduling\n * the emission of the complete notification.\n * @return An \"empty\" Observable: emits only the complete\n * notification.\n * @deprecated Deprecated in favor of using {@link EMPTY} constant, or {@link scheduled} (e.g. `scheduled([], scheduler)`)\n */\nexport function empty(scheduler?: SchedulerLike) {\n return scheduler ? emptyScheduled(scheduler) : EMPTY;\n}\n\nfunction emptyScheduled(scheduler: SchedulerLike) {\n return new Observable<never>(subscriber => scheduler.schedule(() => subscriber.complete()));\n}\n","import { Observable } from '../Observable';\nimport { SchedulerLike } from '../types';\nimport { Subscriber } from '../Subscriber';\n\n/**\n * Creates an Observable that emits no items to the Observer and immediately\n * emits an error notification.\n *\n * <span class=\"informal\">Just emits 'error', and nothing else.\n * </span>\n *\n * ![](throw.png)\n *\n * This static operator is useful for creating a simple Observable that only\n * emits the error notification. It can be used for composing with other\n * Observables, such as in a {@link mergeMap}.\n *\n * ## Examples\n * ### Emit the number 7, then emit an error\n * ```ts\n * import { throwError, concat, of } from 'rxjs';\n *\n * const result = concat(of(7), throwError(new Error('oops!')));\n * result.subscribe(x => console.log(x), e => console.error(e));\n *\n * // Logs:\n * // 7\n * // Error: oops!\n * ```\n *\n * ---\n *\n * ### Map and flatten numbers to the sequence 'a', 'b', 'c', but throw an error for 2\n * ```ts\n * import { throwError, interval, of } from 'rxjs';\n * import { mergeMap } from 'rxjs/operators';\n *\n * interval(1000).pipe(\n * mergeMap(x => x === 2\n * ? throwError('Twos are bad')\n * : of('a', 'b', 'c')\n * ),\n * ).subscribe(x => console.log(x), e => console.error(e));\n *\n * // Logs:\n * // a\n * // b\n * // c\n * // a\n * // b\n * // c\n * // Twos are bad\n * ```\n *\n * @see {@link Observable}\n * @see {@link empty}\n * @see {@link never}\n * @see {@link of}\n *\n * @param {any} error The particular Error to pass to the error notification.\n * @param {SchedulerLike} [scheduler] A {@link SchedulerLike} to use for scheduling\n * the emission of the error notification.\n * @return {Observable} An error Observable: emits only the error notification\n * using the given error argument.\n * @static true\n * @name throwError\n * @owner Observable\n */\nexport function throwError(error: any, scheduler?: SchedulerLike): Observable<never> {\n if (!scheduler) {\n return new Observable(subscriber => subscriber.error(error));\n } else {\n return new Observable(subscriber => scheduler.schedule(dispatch, 0, { error, subscriber }));\n }\n}\n\ninterface DispatchArg {\n error: any;\n subscriber: Subscriber<any>;\n}\n\nfunction dispatch({ error, subscriber }: DispatchArg) {\n subscriber.error(error);\n}\n","import { PartialObserver } from './types';\nimport { Observable } from './Observable';\nimport { empty } from './observable/empty';\nimport { of } from './observable/of';\nimport { throwError } from './observable/throwError';\nimport { deprecate } from 'util';\n\n// TODO: When this enum is removed, replace it with a type alias. See #4556.\n/**\n * @deprecated NotificationKind is deprecated as const enums are not compatible with isolated modules. Use a string literal instead.\n */\nexport enum NotificationKind {\n NEXT = 'N',\n ERROR = 'E',\n COMPLETE = 'C',\n}\n\n/**\n * Represents a push-based event or value that an {@link Observable} can emit.\n * This class is particularly useful for operators that manage notifications,\n * like {@link materialize}, {@link dematerialize}, {@link observeOn}, and\n * others. Besides wrapping the actual delivered value, it also annotates it\n * with metadata of, for instance, what type of push message it is (`next`,\n * `error`, or `complete`).\n *\n * @see {@link materialize}\n * @see {@link dematerialize}\n * @see {@link observeOn}\n *\n * @class Notification<T>\n */\nexport class Notification<T> {\n hasValue: boolean;\n\n constructor(public kind: 'N' | 'E' | 'C', public value?: T, public error?: any) {\n this.hasValue = kind === 'N';\n }\n\n /**\n * Delivers to the given `observer` the value wrapped by this Notification.\n * @param {Observer} observer\n * @return\n */\n observe(observer: PartialObserver<T>): any {\n switch (this.kind) {\n case 'N':\n return observer.next && observer.next(this.value);\n case 'E':\n return observer.error && observer.error(this.error);\n case 'C':\n return observer.complete && observer.complete();\n }\n }\n\n /**\n * Given some {@link Observer} callbacks, deliver the value represented by the\n * current Notification to the correctly corresponding callback.\n * @param {function(value: T): void} next An Observer `next` callback.\n * @param {function(err: any): void} [error] An Observer `error` callback.\n * @param {function(): void} [complete] An Observer `complete` callback.\n * @return {any}\n */\n do(next: (value: T) => void, error?: (err: any) => void, complete?: () => void): any {\n const kind = this.kind;\n switch (kind) {\n case 'N':\n return next && next(this.value);\n case 'E':\n return error && error(this.error);\n case 'C':\n return complete && complete();\n }\n }\n\n /**\n * Takes an Observer or its individual callback functions, and calls `observe`\n * or `do` methods accordingly.\n * @param {Observer|function(value: T): void} nextOrObserver An Observer or\n * the `next` callback.\n * @param {function(err: any): void} [error] An Observer `error` callback.\n * @param {function(): void} [complete] An Observer `complete` callback.\n * @return {any}\n */\n accept(nextOrObserver: PartialObserver<T> | ((value: T) => void), error?: (err: any) => void, complete?: () => void) {\n if (nextOrObserver && typeof (<PartialObserver<T>>nextOrObserver).next === 'function') {\n return this.observe(<PartialObserver<T>>nextOrObserver);\n } else {\n return this.do(<(value: T) => void>nextOrObserver, error, complete);\n }\n }\n\n /**\n * Returns a simple Observable that just delivers the notification represented\n * by this Notification instance.\n * @return {any}\n */\n toObservable(): Observable<T> {\n const kind = this.kind;\n switch (kind) {\n case 'N':\n return of(this.value);\n case 'E':\n return throwError(this.error);\n case 'C':\n return empty();\n }\n throw new Error('unexpected notification kind value');\n }\n\n private static completeNotification: Notification<any> = new Notification('C');\n private static undefinedValueNotification: Notification<any> = new Notification('N', undefined);\n\n /**\n * A shortcut to create a Notification instance of the type `next` from a\n * given value.\n * @param {T} value The `next` value.\n * @return {Notification<T>} The \"next\" Notification representing the\n * argument.\n * @nocollapse\n */\n static createNext<T>(value: T): Notification<T> {\n if (typeof value !== 'undefined') {\n return new Notification('N', value);\n }\n return Notification.undefinedValueNotification;\n }\n\n /**\n * A shortcut to create a Notification instance of the type `error` from a\n * given error.\n * @param {any} [err] The `error` error.\n * @return {Notification<T>} The \"error\" Notification representing the\n * argument.\n * @nocollapse\n */\n static createError<T>(err?: any): Notification<T> {\n return new Notification('E', undefined, err);\n }\n\n /**\n * A shortcut to create a Notification instance of the type `complete`.\n * @return {Notification<any>} The valueless \"complete\" Notification.\n * @nocollapse\n */\n static createComplete(): Notification<any> {\n return Notification.completeNotification;\n }\n}\n","import { async } from '../scheduler/async';\nimport { isDate } from '../util/isDate';\nimport { Operator } from '../Operator';\nimport { Subscriber } from '../Subscriber';\nimport { Subscription } from '../Subscription';\nimport { Notification } from '../Notification';\nimport { Observable } from '../Observable';\nimport { MonoTypeOperatorFunction, PartialObserver, SchedulerAction, SchedulerLike, TeardownLogic } from '../types';\n\n/**\n * Delays the emission of items from the source Observable by a given timeout or\n * until a given Date.\n *\n * <span class=\"informal\">Time shifts each item by some specified amount of\n * milliseconds.</span>\n *\n * ![](delay.png)\n *\n * If the delay argument is a Number, this operator time shifts the source\n * Observable by that amount of time expressed in milliseconds. The relative\n * time intervals between the values are preserved.\n *\n * If the delay argument is a Date, this operator time shifts the start of the\n * Observable execution until the given date occurs.\n *\n * ## Examples\n * Delay each click by one second\n * ```ts\n * import { fromEvent } from 'rxjs';\n * import { delay } from 'rxjs/operators';\n *\n * const clicks = fromEvent(document, 'click');\n * const delayedClicks = clicks.pipe(delay(1000)); // each click emitted after 1 second\n * delayedClicks.subscribe(x => console.log(x));\n * ```\n *\n * Delay all clicks until a future date happens\n * ```ts\n * import { fromEvent } from 'rxjs';\n * import { delay } from 'rxjs/operators';\n *\n * const clicks = fromEvent(document, 'click');\n * const date = new Date('March 15, 2050 12:00:00'); // in the future\n * const delayedClicks = clicks.pipe(delay(date)); // click emitted only after that date\n * delayedClicks.subscribe(x => console.log(x));\n * ```\n *\n * @see {@link debounceTime}\n * @see {@link delayWhen}\n *\n * @param {number|Date} delay The delay duration in milliseconds (a `number`) or\n * a `Date` until which the emission of the source items is delayed.\n * @param {SchedulerLike} [scheduler=async] The {@link SchedulerLike} to use for\n * managing the timers that handle the time-shift for each item.\n * @return {Observable} An Observable that delays the emissions of the source\n * Observable by the specified timeout or Date.\n * @method delay\n * @owner Observable\n */\nexport function delay<T>(delay: number|Date,\n scheduler: SchedulerLike = async): MonoTypeOperatorFunction<T> {\n const absoluteDelay = isDate(delay);\n const delayFor = absoluteDelay ? (+delay - scheduler.now()) : Math.abs(<number>delay);\n return (source: Observable<T>) => source.lift(new DelayOperator(delayFor, scheduler));\n}\n\nclass DelayOperator<T> implements Operator<T, T> {\n constructor(private delay: number,\n private scheduler: SchedulerLike) {\n }\n\n call(subscriber: Subscriber<T>, source: any): TeardownLogic {\n return source.subscribe(new DelaySubscriber(subscriber, this.delay, this.scheduler));\n }\n}\n\ninterface DelayState<T> {\n source: DelaySubscriber<T>;\n destination: PartialObserver<T>;\n scheduler: SchedulerLike;\n}\n\n/**\n * We need this JSDoc comment for affecting ESDoc.\n * @ignore\n * @extends {Ignored}\n */\nclass DelaySubscriber<T> extends Subscriber<T> {\n private queue: Array<DelayMessage<T>> = [];\n private active: boolean = false;\n private errored: boolean = false;\n\n private static dispatch<T>(this: SchedulerAction<DelayState<T>>, state: DelayState<T>): void {\n const source = state.source;\n const queue = source.queue;\n const scheduler = state.scheduler;\n const destination = state.destination;\n\n while (queue.length > 0 && (queue[0].time - scheduler.now()) <= 0) {\n queue.shift().notification.observe(destination);\n }\n\n if (queue.length > 0) {\n const delay = Math.max(0, queue[0].time - scheduler.now());\n this.schedule(state, delay);\n } else {\n this.unsubscribe();\n source.active = false;\n }\n }\n\n constructor(destination: Subscriber<T>,\n private delay: number,\n private scheduler: SchedulerLike) {\n super(destination);\n }\n\n private _schedule(scheduler: SchedulerLike): void {\n this.active = true;\n const destination = this.destination as Subscription;\n destination.add(scheduler.schedule<DelayState<T>>(DelaySubscriber.dispatch, this.delay, {\n source: this, destination: this.destination, scheduler: scheduler\n }));\n }\n\n private scheduleNotification(notification: Notification<T>): void {\n if (this.errored === true) {\n return;\n }\n\n const scheduler = this.scheduler;\n const message = new DelayMessage(scheduler.now() + this.delay, notification);\n this.queue.push(message);\n\n if (this.active === false) {\n this._schedule(scheduler);\n }\n }\n\n protected _next(value: T) {\n this.scheduleNotification(Notification.createNext(value));\n }\n\n protected _error(err: any) {\n this.errored = true;\n this.queue = [];\n this.destination.error(err);\n this.unsubscribe();\n }\n\n protected _complete() {\n this.scheduleNotification(Notification.createComplete());\n this.unsubscribe();\n }\n}\n\nclass DelayMessage<T> {\n constructor(public readonly time: number,\n public readonly notification: Notification<T>) {\n }\n}\n","import { Operator } from '../Operator';\nimport { Subscriber } from '../Subscriber';\nimport { Observable } from '../Observable';\nimport { MonoTypeOperatorFunction, TeardownLogic } from '../types';\n\n/* tslint:disable:max-line-length */\nexport function distinctUntilChanged<T>(compare?: (x: T, y: T) => boolean): MonoTypeOperatorFunction<T>;\nexport function distinctUntilChanged<T, K>(compare: (x: K, y: K) => boolean, keySelector: (x: T) => K): MonoTypeOperatorFunction<T>;\n/* tslint:enable:max-line-length */\n\n/**\n * Returns an Observable that emits all items emitted by the source Observable that are distinct by comparison from the previous item.\n *\n * If a comparator function is provided, then it will be called for each item to test for whether or not that value should be emitted.\n *\n * If a comparator function is not provided, an equality check is used by default.\n *\n * ## Example\n * A simple example with numbers\n * ```ts\n * import { of } from 'rxjs';\n * import { distinctUntilChanged } from 'rxjs/operators';\n *\n * of(1, 1, 2, 2, 2, 1, 1, 2, 3, 3, 4).pipe(\n * distinctUntilChanged(),\n * )\n * .subscribe(x => console.log(x)); // 1, 2, 1, 2, 3, 4\n * ```\n *\n * An example using a compare function\n * ```typescript\n * import { of } from 'rxjs';\n * import { distinctUntilChanged } from 'rxjs/operators';\n *\n * interface Person {\n * age: number,\n * name: string\n * }\n *\n * of<Person>(\n * { age: 4, name: 'Foo'},\n * { age: 7, name: 'Bar'},\n * { age: 5, name: 'Foo'},\n * { age: 6, name: 'Foo'},\n * ).pipe(\n * distinctUntilChanged((p: Person, q: Person) => p.name === q.name),\n * )\n * .subscribe(x => console.log(x));\n *\n * // displays:\n * // { age: 4, name: 'Foo' }\n * // { age: 7, name: 'Bar' }\n * // { age: 5, name: 'Foo' }\n * ```\n *\n * @see {@link distinct}\n * @see {@link distinctUntilKeyChanged}\n *\n * @param {function} [compare] Optional comparison function called to test if an item is distinct from the previous item in the source.\n * @return {Observable} An Observable that emits items from the source Observable with distinct values.\n * @method distinctUntilChanged\n * @owner Observable\n */\nexport function distinctUntilChanged<T, K>(compare?: (x: K, y: K) => boolean, keySelector?: (x: T) => K): MonoTypeOperatorFunction<T> {\n return (source: Observable<T>) => source.lift(new DistinctUntilChangedOperator<T, K>(compare, keySelector));\n}\n\nclass DistinctUntilChangedOperator<T, K> implements Operator<T, T> {\n constructor(private compare: (x: K, y: K) => boolean,\n private keySelector: (x: T) => K) {\n }\n\n call(subscriber: Subscriber<T>, source: any): TeardownLogic {\n return source.subscribe(new DistinctUntilChangedSubscriber(subscriber, this.compare, this.keySelector));\n }\n}\n\n/**\n * We need this JSDoc comment for affecting ESDoc.\n * @ignore\n * @extends {Ignored}\n */\nclass DistinctUntilChangedSubscriber<T, K> extends Subscriber<T> {\n private key: K;\n private hasKey: boolean = false;\n\n constructor(destination: Subscriber<T>,\n compare: (x: K, y: K) => boolean,\n private keySelector: (x: T) => K) {\n super(destination);\n if (typeof compare === 'function') {\n this.compare = compare;\n }\n }\n\n private compare(x: any, y: any): boolean {\n return x === y;\n }\n\n protected _next(value: T): void {\n let key: any;\n try {\n const { keySelector } = this;\n key = keySelector ? keySelector(value) : value;\n } catch (err) {\n return this.destination.error(err);\n }\n let result = false;\n if (this.hasKey) {\n try {\n const { compare } = this;\n result = compare(this.key, key);\n } catch (err) {\n return this.destination.error(err);\n }\n } else {\n this.hasKey = true;\n }\n if (!result) {\n this.key = key;\n this.destination.next(value);\n }\n }\n}\n","export interface ArgumentOutOfRangeError extends Error {\n}\n\nexport interface ArgumentOutOfRangeErrorCtor {\n new(): ArgumentOutOfRangeError;\n}\n\nconst ArgumentOutOfRangeErrorImpl = (() => {\n function ArgumentOutOfRangeErrorImpl(this: any) {\n Error.call(this);\n this.message = 'argument out of range';\n this.name = 'ArgumentOutOfRangeError';\n return this;\n }\n\n ArgumentOutOfRangeErrorImpl.prototype = Object.create(Error.prototype);\n\n return ArgumentOutOfRangeErrorImpl;\n})();\n\n/**\n * An error thrown when an element was queried at a certain index of an\n * Observable, but no such index or position exists in that sequence.\n *\n * @see {@link elementAt}\n * @see {@link take}\n * @see {@link takeLast}\n *\n * @class ArgumentOutOfRangeError\n */\nexport const ArgumentOutOfRangeError: ArgumentOutOfRangeErrorCtor = ArgumentOutOfRangeErrorImpl as any;","import { Operator } from '../Operator';\nimport { Subscriber } from '../Subscriber';\nimport { Observable } from '../Observable';\nimport { OperatorFunction, MonoTypeOperatorFunction, TeardownLogic } from '../types';\n\n/* tslint:disable:max-line-length */\nexport function filter<T, S extends T>(predicate: (value: T, index: number) => value is S,\n thisArg?: any): OperatorFunction<T, S>;\nexport function filter<T>(predicate: (value: T, index: number) => boolean,\n thisArg?: any): MonoTypeOperatorFunction<T>;\n/* tslint:enable:max-line-length */\n\n/**\n * Filter items emitted by the source Observable by only emitting those that\n * satisfy a specified predicate.\n *\n * <span class=\"informal\">Like\n * [Array.prototype.filter()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter),\n * it only emits a value from the source if it passes a criterion function.</span>\n *\n * ![](filter.png)\n *\n * Similar to the well-known `Array.prototype.filter` method, this operator\n * takes values from the source Observable, passes them through a `predicate`\n * function and only emits those values that yielded `true`.\n *\n * ## Example\n * Emit only click events whose target was a DIV element\n * ```ts\n * import { fromEvent } from 'rxjs';\n * import { filter } from 'rxjs/operators';\n *\n * const clicks = fromEvent(document, 'click');\n * const clicksOnDivs = clicks.pipe(filter(ev => ev.target.tagName === 'DIV'));\n * clicksOnDivs.subscribe(x => console.log(x));\n * ```\n *\n * @see {@link distinct}\n * @see {@link distinctUntilChanged}\n * @see {@link distinctUntilKeyChanged}\n * @see {@link ignoreElements}\n * @see {@link partition}\n * @see {@link skip}\n *\n * @param {function(value: T, index: number): boolean} predicate A function that\n * evaluates each value emitted by the source Observable. If it returns `true`,\n * the value is emitted, if `false` the value is not passed to the output\n * Observable. The `index` parameter is the number `i` for the i-th source\n * emission that has happened since the subscription, starting from the number\n * `0`.\n * @param {any} [thisArg] An optional argument to determine the value of `this`\n * in the `predicate` function.\n * @return {Observable} An Observable of values from the source that were\n * allowed by the `predicate` function.\n * @method filter\n * @owner Observable\n */\nexport function filter<T>(predicate: (value: T, index: number) => boolean,\n thisArg?: any): MonoTypeOperatorFunction<T> {\n return function filterOperatorFunction(source: Observable<T>): Observable<T> {\n return source.lift(new FilterOperator(predicate, thisArg));\n };\n}\n\nclass FilterOperator<T> implements Operator<T, T> {\n constructor(private predicate: (value: T, index: number) => boolean,\n private thisArg?: any) {\n }\n\n call(subscriber: Subscriber<T>, source: any): TeardownLogic {\n return source.subscribe(new FilterSubscriber(subscriber, this.predicate, this.thisArg));\n }\n}\n\n/**\n * We need this JSDoc comment for affecting ESDoc.\n * @ignore\n * @extends {Ignored}\n */\nclass FilterSubscriber<T> extends Subscriber<T> {\n\n count: number = 0;\n\n constructor(destination: Subscriber<T>,\n private predicate: (value: T, index: number) => boolean,\n private thisArg: any) {\n super(destination);\n }\n\n // the try catch block below is left specifically for\n // optimization and perf reasons. a tryCatcher is not necessary here.\n protected _next(value: T) {\n let result: any;\n try {\n result = this.predicate.call(this.thisArg, value, this.count++);\n } catch (err) {\n this.destination.error(err);\n return;\n }\n if (result) {\n this.destination.next(value);\n }\n }\n}\n","import { Operator } from '../Operator';\nimport { Subscriber } from '../Subscriber';\nimport { ArgumentOutOfRangeError } from '../util/ArgumentOutOfRangeError';\nimport { empty } from '../observable/empty';\nimport { Observable } from '../Observable';\nimport { MonoTypeOperatorFunction, TeardownLogic } from '../types';\n\n/**\n * Emits only the first `count` values emitted by the source Observable.\n *\n * <span class=\"informal\">Takes the first `count` values from the source, then\n * completes.</span>\n *\n * ![](take.png)\n *\n * `take` returns an Observable that emits only the first `count` values emitted\n * by the source Observable. If the source emits fewer than `count` values then\n * all of its values are emitted. After that, it completes, regardless if the\n * source completes.\n *\n * ## Example\n * Take the first 5 seconds of an infinite 1-second interval Observable\n * ```ts\n * import { interval } from 'rxjs';\n * import { take } from 'rxjs/operators';\n *\n * const intervalCount = interval(1000);\n * const takeFive = intervalCount.pipe(take(5));\n * takeFive.subscribe(x => console.log(x));\n *\n * // Logs:\n * // 0\n * // 1\n * // 2\n * // 3\n * // 4\n * ```\n *\n * @see {@link takeLast}\n * @see {@link takeUntil}\n * @see {@link takeWhile}\n * @see {@link skip}\n *\n * @throws {ArgumentOutOfRangeError} When using `take(i)`, it delivers an\n * ArgumentOutOrRangeError to the Observer's `error` callback if `i < 0`.\n *\n * @param {number} count The maximum number of `next` values to emit.\n * @return {Observable<T>} An Observable that emits only the first `count`\n * values emitted by the source Observable, or all of the values from the source\n * if the source emits fewer than `count` values.\n * @method take\n * @owner Observable\n */\nexport function take<T>(count: number): MonoTypeOperatorFunction<T> {\n return (source: Observable<T>) => {\n if (count === 0) {\n return empty();\n } else {\n return source.lift(new TakeOperator(count));\n }\n };\n}\n\nclass TakeOperator<T> implements Operator<T, T> {\n constructor(private total: number) {\n if (this.total < 0) {\n throw new ArgumentOutOfRangeError;\n }\n }\n\n call(subscriber: Subscriber<T>, source: any): TeardownLogic {\n return source.subscribe(new TakeSubscriber(subscriber, this.total));\n }\n}\n\n/**\n * We need this JSDoc comment for affecting ESDoc.\n * @ignore\n * @extends {Ignored}\n */\nclass TakeSubscriber<T> extends Subscriber<T> {\n private count: number = 0;\n\n constructor(destination: Subscriber<T>, private total: number) {\n super(destination);\n }\n\n protected _next(value: T): void {\n const total = this.total;\n const count = ++this.count;\n if (count <= total) {\n this.destination.next(value);\n if (count === total) {\n this.destination.complete();\n this.unsubscribe();\n }\n }\n }\n}\n","import { Operator } from '../Operator';\nimport { Subscriber } from '../Subscriber';\nimport { Observable } from '../Observable';\nimport { MonoTypeOperatorFunction, TeardownLogic } from '../types';\n\n/**\n * Returns an Observable that skips the first `count` items emitted by the source Observable.\n *\n * ![](skip.png)\n *\n * @param {Number} count - The number of times, items emitted by source Observable should be skipped.\n * @return {Observable} An Observable that skips values emitted by the source Observable.\n *\n * @method skip\n * @owner Observable\n */\nexport function skip<T>(count: number): MonoTypeOperatorFunction<T> {\n return (source: Observable<T>) => source.lift(new SkipOperator(count));\n}\n\nclass SkipOperator<T> implements Operator<T, T> {\n constructor(private total: number) {\n }\n\n call(subscriber: Subscriber<T>, source: any): TeardownLogic {\n return source.subscribe(new SkipSubscriber(subscriber, this.total));\n }\n}\n\n/**\n * We need this JSDoc comment for affecting ESDoc.\n * @ignore\n * @extends {Ignored}\n */\nclass SkipSubscriber<T> extends Subscriber<T> {\n count: number = 0;\n\n constructor(destination: Subscriber<T>, private total: number) {\n super(destination);\n }\n\n protected _next(x: T) {\n if (++this.count > this.total) {\n this.destination.next(x);\n }\n }\n}\n","import { Observable } from '../Observable';\nimport { concat } from '../observable/concat';\nimport { isScheduler } from '../util/isScheduler';\nimport { MonoTypeOperatorFunction, OperatorFunction, SchedulerLike } from '../types';\n\n/* tslint:disable:max-line-length */\n/** @deprecated use {@link scheduled} and {@link concatAll} (e.g. `scheduled([[a, b, c], source], scheduler).pipe(concatAll())`) */\nexport function startWith<T>(scheduler: SchedulerLike): MonoTypeOperatorFunction<T>;\n/** @deprecated use {@link scheduled} and {@link concatAll} (e.g. `scheduled([[a, b, c], source], scheduler).pipe(concatAll())`) */\nexport function startWith<T, D>(v1: D, scheduler: SchedulerLike): OperatorFunction<T, T | D>;\n/** @deprecated use {@link scheduled} and {@link concatAll} (e.g. `scheduled([[a, b, c], source], scheduler).pipe(concatAll())`) */\nexport function startWith<T, D, E>(v1: D, v2: E, scheduler: SchedulerLike): OperatorFunction<T, T | D | E>;\n/** @deprecated use {@link scheduled} and {@link concatAll} (e.g. `scheduled([[a, b, c], source], scheduler).pipe(concatAll())`) */\nexport function startWith<T, D, E, F>(v1: D, v2: E, v3: F, scheduler: SchedulerLike): OperatorFunction<T, T | D | E | F>;\n/** @deprecated use {@link scheduled} and {@link concatAll} (e.g. `scheduled([[a, b, c], source], scheduler).pipe(concatAll())`) */\nexport function startWith<T, D, E, F, G>(v1: D, v2: E, v3: F, v4: G, scheduler: SchedulerLike): OperatorFunction<T, T | D | E | F | G>;\n/** @deprecated use {@link scheduled} and {@link concatAll} (e.g. `scheduled([[a, b, c], source], scheduler).pipe(concatAll())`) */\nexport function startWith<T, D, E, F, G, H>(v1: D, v2: E, v3: F, v4: G, v5: H, scheduler: SchedulerLike): OperatorFunction<T, T | D | E | F | G | H>;\n/** @deprecated use {@link scheduled} and {@link concatAll} (e.g. `scheduled([[a, b, c], source], scheduler).pipe(concatAll())`) */\nexport function startWith<T, D, E, F, G, H, I>(v1: D, v2: E, v3: F, v4: G, v5: H, v6: I, scheduler: SchedulerLike): OperatorFunction<T, T | D | E | F | G | H | I>;\n\nexport function startWith<T, D>(v1: D): OperatorFunction<T, T | D>;\nexport function startWith<T, D, E>(v1: D, v2: E): OperatorFunction<T, T | D | E>;\nexport function startWith<T, D, E, F>(v1: D, v2: E, v3: F): OperatorFunction<T, T | D | E | F>;\nexport function startWith<T, D, E, F, G>(v1: D, v2: E, v3: F, v4: G): OperatorFunction<T, T | D | E | F | G>;\nexport function startWith<T, D, E, F, G, H>(v1: D, v2: E, v3: F, v4: G, v5: H): OperatorFunction<T, T | D | E | F | G | H>;\nexport function startWith<T, D, E, F, G, H, I>(v1: D, v2: E, v3: F, v4: G, v5: H, v6: I): OperatorFunction<T, T | D | E | F | G | H | I>;\nexport function startWith<T, D = T>(...array: D[]): OperatorFunction<T, T | D>;\n/** @deprecated use {@link scheduled} and {@link concatAll} (e.g. `scheduled([[a, b, c], source], scheduler).pipe(concatAll())`) */\nexport function startWith<T, D = T>(...array: Array<D | SchedulerLike>): OperatorFunction<T, T | D>;\n/* tslint:enable:max-line-length */\n\n/**\n * Returns an Observable that emits the items you specify as arguments before it begins to emit\n * items emitted by the source Observable.\n *\n * <span class=\"informal\">First emits its arguments in order, and then any\n * emissions from the source.</span>\n *\n * ![](startWith.png)\n *\n * ## Examples\n *\n * Start the chain of emissions with `\"first\"`, `\"second\"`\n *\n * ```ts\n * import { of } from 'rxjs';\n * import { startWith } from 'rxjs/operators';\n *\n * of(\"from source\")\n * .pipe(startWith(\"first\", \"second\"))\n * .subscribe(x => console.log(x));\n *\n * // results:\n * // \"first\"\n * // \"second\"\n * // \"from source\"\n * ```\n *\n * @param {...T} values - Items you want the modified Observable to emit first.\n * @param {SchedulerLike} [scheduler] - A {@link SchedulerLike} to use for scheduling\n * the emissions of the `next` notifications.\n * @return {Observable} An Observable that emits the items in the specified Iterable and then emits the items\n * emitted by the source Observable.\n * @method startWith\n * @owner Observable\n */\nexport function startWith<T, D>(...array: Array<T | SchedulerLike>): OperatorFunction<T, T | D> {\n const scheduler = array[array.length - 1] as SchedulerLike;\n if (isScheduler(scheduler)) {\n // deprecated path\n array.pop();\n return (source: Observable<T>) => concat(array as T[], source, scheduler);\n } else {\n return (source: Observable<T>) => concat(array as T[], source);\n }\n}\n","import { Operator } from '../Operator';\nimport { Observable } from '../Observable';\nimport { Subscriber } from '../Subscriber';\nimport { Subscription } from '../Subscription';\nimport { ObservableInput, OperatorFunction, ObservedValueOf } from '../types';\nimport { map } from './map';\nimport { from } from '../observable/from';\nimport { SimpleOuterSubscriber, SimpleInnerSubscriber, innerSubscribe } from '../innerSubscribe';\n\n/* tslint:disable:max-line-length */\nexport function switchMap<T, O extends ObservableInput<any>>(project: (value: T, index: number) => O): OperatorFunction<T, ObservedValueOf<O>>;\n/** @deprecated resultSelector is no longer supported, use inner map instead */\nexport function switchMap<T, O extends ObservableInput<any>>(project: (value: T, index: number) => O, resultSelector: undefined): OperatorFunction<T, ObservedValueOf<O>>;\n/** @deprecated resultSelector is no longer supported, use inner map instead */\nexport function switchMap<T, R, O extends ObservableInput<any>>(project: (value: T, index: number) => O, resultSelector: (outerValue: T, innerValue: ObservedValueOf<O>, outerIndex: number, innerIndex: number) => R): OperatorFunction<T, R>;\n/* tslint:enable:max-line-length */\n\n/**\n * Projects each source value to an Observable which is merged in the output\n * Observable, emitting values only from the most recently projected Observable.\n *\n * <span class=\"informal\">Maps each value to an Observable, then flattens all of\n * these inner Observables.</span>\n *\n * ![](switchMap.png)\n *\n * Returns an Observable that emits items based on applying a function that you\n * supply to each item emitted by the source Observable, where that function\n * returns an (so-called \"inner\") Observable. Each time it observes one of these\n * inner Observables, the output Observable begins emitting the items emitted by\n * that inner Observable. When a new inner Observable is emitted, `switchMap`\n * stops emitting items from the earlier-emitted inner Observable and begins\n * emitting items from the new one. It continues to behave like this for\n * subsequent inner Observables.\n *\n * ## Example\n * Generate new Observable according to source Observable values\n * ```typescript\n * import { of } from 'rxjs';\n * import { switchMap } from 'rxjs/operators';\n *\n * const switched = of(1, 2, 3).pipe(switchMap((x: number) => of(x, x ** 2, x ** 3)));\n * switched.subscribe(x => console.log(x));\n * // outputs\n * // 1\n * // 1\n * // 1\n * // 2\n * // 4\n * // 8\n * // ... and so on\n * ```\n *\n * Rerun an interval Observable on every click event\n * ```ts\n * import { fromEvent, interval } from 'rxjs';\n * import { switchMap } from 'rxjs/operators';\n *\n * const clicks = fromEvent(document, 'click');\n * const result = clicks.pipe(switchMap((ev) => interval(1000)));\n * result.subscribe(x => console.log(x));\n * ```\n *\n * @see {@link concatMap}\n * @see {@link exhaustMap}\n * @see {@link mergeMap}\n * @see {@link switchAll}\n * @see {@link switchMapTo}\n *\n * @param {function(value: T, ?index: number): ObservableInput} project A function\n * that, when applied to an item emitted by the source Observable, returns an\n * Observable.\n * @return {Observable} An Observable that emits the result of applying the\n * projection function (and the optional deprecated `resultSelector`) to each item\n * emitted by the source Observable and taking only the values from the most recently\n * projected inner Observable.\n * @method switchMap\n * @owner Observable\n */\nexport function switchMap<T, R, O extends ObservableInput<any>>(\n project: (value: T, index: number) => O,\n resultSelector?: (outerValue: T, innerValue: ObservedValueOf<O>, outerIndex: number, innerIndex: number) => R,\n): OperatorFunction<T, ObservedValueOf<O>|R> {\n if (typeof resultSelector === 'function') {\n return (source: Observable<T>) => source.pipe(\n switchMap((a, i) => from(project(a, i)).pipe(\n map((b, ii) => resultSelector(a, b, i, ii))\n ))\n );\n }\n return (source: Observable<T>) => source.lift(new SwitchMapOperator(project));\n}\n\nclass SwitchMapOperator<T, R> implements Operator<T, R> {\n constructor(private project: (value: T, index: number) => ObservableInput<R>) {\n }\n\n call(subscriber: Subscriber<R>, source: any): any {\n return source.subscribe(new SwitchMapSubscriber(subscriber, this.project));\n }\n}\n\n/**\n * We need this JSDoc comment for affecting ESDoc.\n * @ignore\n * @extends {Ignored}\n */\nclass SwitchMapSubscriber<T, R> extends SimpleOuterSubscriber<T, R> {\n private index = 0;\n private innerSubscription?: Subscription;\n\n constructor(destination: Subscriber<R>,\n private project: (value: T, index: number) => ObservableInput<R>) {\n super(destination);\n }\n\n protected _next(value: T) {\n let result: ObservableInput<R>;\n const index = this.index++;\n try {\n result = this.project(value, index);\n } catch (error) {\n this.destination.error!(error);\n return;\n }\n this._innerSub(result);\n }\n\n private _innerSub(result: ObservableInput<R>) {\n const innerSubscription = this.innerSubscription;\n if (innerSubscription) {\n innerSubscription.unsubscribe();\n }\n const innerSubscriber = new SimpleInnerSubscriber(this);\n const destination = this.destination as Subscription;\n destination.add(innerSubscriber);\n this.innerSubscription = innerSubscribe(result, innerSubscriber);\n // The returned subscription will usually be the subscriber that was\n // passed. However, interop subscribers will be wrapped and for\n // unsubscriptions to chain correctly, the wrapper needs to be added, too.\n if (this.innerSubscription !== innerSubscriber) {\n destination.add(this.innerSubscription);\n }\n }\n\n protected _complete(): void {\n const {innerSubscription} = this;\n if (!innerSubscription || innerSubscription.closed) {\n super._complete();\n }\n this.unsubscribe();\n }\n\n protected _unsubscribe() {\n this.innerSubscription = undefined;\n }\n\n notifyComplete(): void {\n this.innerSubscription = undefined;\n if (this.isStopped) {\n super._complete();\n }\n }\n\n notifyNext(innerValue: R): void {\n this.destination.next!(innerValue);\n }\n}\n","/* tslint:disable:no-empty */\nexport function noop() { }\n","import { Operator } from '../Operator';\nimport { Subscriber } from '../Subscriber';\nimport { Observable } from '../Observable';\nimport { MonoTypeOperatorFunction, PartialObserver, TeardownLogic } from '../types';\nimport { noop } from '../util/noop';\nimport { isFunction } from '../util/isFunction';\n\n/* tslint:disable:max-line-length */\n/** @deprecated Use an observer instead of a complete callback */\nexport function tap<T>(next: null | undefined, error: null | undefined, complete: () => void): MonoTypeOperatorFunction<T>;\n/** @deprecated Use an observer instead of an error callback */\nexport function tap<T>(next: null | undefined, error: (error: any) => void, complete?: () => void): MonoTypeOperatorFunction<T>;\n/** @deprecated Use an observer instead of a complete callback */\nexport function tap<T>(next: (value: T) => void, error: null | undefined, complete: () => void): MonoTypeOperatorFunction<T>;\nexport function tap<T>(next?: (x: T) => void, error?: (e: any) => void, complete?: () => void): MonoTypeOperatorFunction<T>;\nexport function tap<T>(observer: PartialObserver<T>): MonoTypeOperatorFunction<T>;\n/* tslint:enable:max-line-length */\n\n/**\n * Perform a side effect for every emission on the source Observable, but return\n * an Observable that is identical to the source.\n *\n * <span class=\"informal\">Intercepts each emission on the source and runs a\n * function, but returns an output which is identical to the source as long as errors don't occur.</span>\n *\n * ![](do.png)\n *\n * Returns a mirrored Observable of the source Observable, but modified so that\n * the provided Observer is called to perform a side effect for every value,\n * error, and completion emitted by the source. Any errors that are thrown in\n * the aforementioned Observer or handlers are safely sent down the error path\n * of the output Observable.\n *\n * This operator is useful for debugging your Observables for the correct values\n * or performing other side effects.\n *\n * Note: this is different to a `subscribe` on the Observable. If the Observable\n * returned by `tap` is not subscribed, the side effects specified by the\n * Observer will never happen. `tap` therefore simply spies on existing\n * execution, it does not trigger an execution to happen like `subscribe` does.\n *\n * ## Example\n * Map every click to the clientX position of that click, while also logging the click event\n * ```ts\n * import { fromEvent } from 'rxjs';\n * import { tap, map } from 'rxjs/operators';\n *\n * const clicks = fromEvent(document, 'click');\n * const positions = clicks.pipe(\n * tap(ev => console.log(ev)),\n * map(ev => ev.clientX),\n * );\n * positions.subscribe(x => console.log(x));\n * ```\n *\n * @see {@link map}\n * @see {@link Observable#subscribe}\n *\n * @param {Observer|function} [nextOrObserver] A normal Observer object or a\n * callback for `next`.\n * @param {function} [error] Callback for errors in the source.\n * @param {function} [complete] Callback for the completion of the source.\n * @return {Observable} An Observable identical to the source, but runs the\n * specified Observer or callback(s) for each item.\n * @name tap\n */\nexport function tap<T>(nextOrObserver?: PartialObserver<T> | ((x: T) => void),\n error?: (e: any) => void,\n complete?: () => void): MonoTypeOperatorFunction<T> {\n return function tapOperatorFunction(source: Observable<T>): Observable<T> {\n return source.lift(new DoOperator(nextOrObserver, error, complete));\n };\n}\n\nclass DoOperator<T> implements Operator<T, T> {\n constructor(private nextOrObserver?: PartialObserver<T> | ((x: T) => void),\n private error?: (e: any) => void,\n private complete?: () => void) {\n }\n call(subscriber: Subscriber<T>, source: any): TeardownLogic {\n return source.subscribe(new TapSubscriber(subscriber, this.nextOrObserver, this.error, this.complete));\n }\n}\n\n/**\n * We need this JSDoc comment for affecting ESDoc.\n * @ignore\n * @extends {Ignored}\n */\n\nclass TapSubscriber<T> extends Subscriber<T> {\n private _context: any;\n\n private _tapNext: ((value: T) => void) = noop;\n\n private _tapError: ((err: any) => void) = noop;\n\n private _tapComplete: (() => void) = noop;\n\n constructor(destination: Subscriber<T>,\n observerOrNext?: PartialObserver<T> | ((value: T) => void),\n error?: (e?: any) => void,\n complete?: () => void) {\n super(destination);\n this._tapError = error || noop;\n this._tapComplete = complete || noop;\n if (isFunction(observerOrNext)) {\n this._context = this;\n this._tapNext = observerOrNext;\n } else if (observerOrNext) {\n this._context = observerOrNext;\n this._tapNext = observerOrNext.next || noop;\n this._tapError = observerOrNext.error || noop;\n this._tapComplete = observerOrNext.complete || noop;\n }\n }\n\n _next(value: T) {\n try {\n this._tapNext.call(this._context, value);\n } catch (err) {\n this.destination.error(err);\n return;\n }\n this.destination.next(value);\n }\n\n _error(err: any) {\n try {\n this._tapError.call(this._context, err);\n } catch (err) {\n this.destination.error(err);\n return;\n }\n this.destination.error(err);\n }\n\n _complete() {\n try {\n this._tapComplete.call(this._context, );\n } catch (err) {\n this.destination.error(err);\n return;\n }\n return this.destination.complete();\n }\n}\n","export interface TimeoutError extends Error {\n}\n\nexport interface TimeoutErrorCtor {\n new(): TimeoutError;\n}\n\nconst TimeoutErrorImpl = (() => {\n function TimeoutErrorImpl(this: any) {\n Error.call(this);\n this.message = 'Timeout has occurred';\n this.name = 'TimeoutError';\n return this;\n }\n\n TimeoutErrorImpl.prototype = Object.create(Error.prototype);\n\n return TimeoutErrorImpl;\n})();\n\n/**\n * An error thrown when duetime elapses.\n *\n * @see {@link operators/timeout}\n *\n * @class TimeoutError\n */\nexport const TimeoutError: TimeoutErrorCtor = TimeoutErrorImpl as any;\n","import { Operator } from '../Operator';\nimport { Subscriber } from '../Subscriber';\nimport { async } from '../scheduler/async';\nimport { Observable } from '../Observable';\nimport { isDate } from '../util/isDate';\nimport { ObservableInput, OperatorFunction, SchedulerAction, SchedulerLike, TeardownLogic } from '../types';\nimport { SimpleOuterSubscriber, innerSubscribe, SimpleInnerSubscriber } from '../innerSubscribe';\n\n/* tslint:disable:max-line-length */\nexport function timeoutWith<T, R>(due: number | Date, withObservable: ObservableInput<R>, scheduler?: SchedulerLike): OperatorFunction<T, T | R>;\n/* tslint:enable:max-line-length */\n\n/**\n *\n * Errors if Observable does not emit a value in given time span, in case of which\n * subscribes to the second Observable.\n *\n * <span class=\"informal\">It's a version of `timeout` operator that let's you specify fallback Observable.</span>\n *\n * ![](timeoutWith.png)\n *\n * `timeoutWith` is a variation of `timeout` operator. It behaves exactly the same,\n * still accepting as a first argument either a number or a Date, which control - respectively -\n * when values of source Observable should be emitted or when it should complete.\n *\n * The only difference is that it accepts a second, required parameter. This parameter\n * should be an Observable which will be subscribed when source Observable fails any timeout check.\n * So whenever regular `timeout` would emit an error, `timeoutWith` will instead start re-emitting\n * values from second Observable. Note that this fallback Observable is not checked for timeouts\n * itself, so it can emit values and complete at arbitrary points in time. From the moment of a second\n * subscription, Observable returned from `timeoutWith` simply mirrors fallback stream. When that\n * stream completes, it completes as well.\n *\n * Scheduler, which in case of `timeout` is provided as as second argument, can be still provided\n * here - as a third, optional parameter. It still is used to schedule timeout checks and -\n * as a consequence - when second Observable will be subscribed, since subscription happens\n * immediately after failing check.\n *\n * ## Example\n * Add fallback observable\n * ```ts\n * import { interval } from 'rxjs';\n * import { timeoutWith } from 'rxjs/operators';\n *\n * const seconds = interval(1000);\n * const minutes = interval(60 * 1000);\n *\n * seconds.pipe(timeoutWith(900, minutes))\n * .subscribe(\n * value => console.log(value), // After 900ms, will start emitting `minutes`,\n * // since first value of `seconds` will not arrive fast enough.\n * err => console.log(err), // Would be called after 900ms in case of `timeout`,\n * // but here will never be called.\n * );\n * ```\n *\n * @param {number|Date} due Number specifying period within which Observable must emit values\n * or Date specifying before when Observable should complete\n * @param {Observable<T>} withObservable Observable which will be subscribed if source fails timeout check.\n * @param {SchedulerLike} [scheduler] Scheduler controlling when timeout checks occur.\n * @return {Observable<T>} Observable that mirrors behaviour of source or, when timeout check fails, of an Observable\n * passed as a second parameter.\n * @method timeoutWith\n * @owner Observable\n */\nexport function timeoutWith<T, R>(due: number | Date,\n withObservable: ObservableInput<R>,\n scheduler: SchedulerLike = async): OperatorFunction<T, T | R> {\n return (source: Observable<T>) => {\n let absoluteTimeout = isDate(due);\n let waitFor = absoluteTimeout ? (+due - scheduler.now()) : Math.abs(<number>due);\n return source.lift(new TimeoutWithOperator(waitFor, absoluteTimeout, withObservable, scheduler));\n };\n}\n\nclass TimeoutWithOperator<T> implements Operator<T, T> {\n constructor(private waitFor: number,\n private absoluteTimeout: boolean,\n private withObservable: ObservableInput<any>,\n private scheduler: SchedulerLike) {\n }\n\n call(subscriber: Subscriber<T>, source: any): TeardownLogic {\n return source.subscribe(new TimeoutWithSubscriber(\n subscriber, this.absoluteTimeout, this.waitFor, this.withObservable, this.scheduler\n ));\n }\n}\n\n/**\n * We need this JSDoc comment for affecting ESDoc.\n * @ignore\n * @extends {Ignored}\n */\nclass TimeoutWithSubscriber<T, R> extends SimpleOuterSubscriber<T, R> {\n\n private action?: SchedulerAction<TimeoutWithSubscriber<T, R>>;\n\n constructor(destination: Subscriber<T>,\n private absoluteTimeout: boolean,\n private waitFor: number,\n private withObservable: ObservableInput<any>,\n private scheduler: SchedulerLike) {\n super(destination);\n this.scheduleTimeout();\n }\n\n private static dispatchTimeout<T, R>(subscriber: TimeoutWithSubscriber<T, R>): void {\n const { withObservable } = subscriber;\n subscriber._unsubscribeAndRecycle();\n subscriber.add(innerSubscribe(withObservable, new SimpleInnerSubscriber(subscriber)));\n }\n\n private scheduleTimeout(): void {\n const { action } = this;\n if (action) {\n // Recycle the action if we've already scheduled one. All the production\n // Scheduler Actions mutate their state/delay time and return themeselves.\n // VirtualActions are immutable, so they create and return a clone. In this\n // case, we need to set the action reference to the most recent VirtualAction,\n // to ensure that's the one we clone from next time.\n this.action = (<SchedulerAction<TimeoutWithSubscriber<T, R>>> action.schedule(this, this.waitFor));\n } else {\n this.add(this.action = (<SchedulerAction<TimeoutWithSubscriber<T, R>>> this.scheduler.schedule<TimeoutWithSubscriber<T, R>>(\n TimeoutWithSubscriber.dispatchTimeout as any, this.waitFor, this\n )));\n }\n }\n\n protected _next(value: T): void {\n if (!this.absoluteTimeout) {\n this.scheduleTimeout();\n }\n super._next(value);\n }\n\n /** @deprecated This is an internal implementation detail, do not use. */\n _unsubscribe() {\n this.action = undefined;\n this.scheduler = null!;\n this.withObservable = null!;\n }\n}\n","import { async } from '../scheduler/async';\nimport { isDate } from '../util/isDate';\nimport { Operator } from '../Operator';\nimport { Subscriber } from '../Subscriber';\nimport { Observable } from '../Observable';\nimport { TimeoutError } from '../util/TimeoutError';\nimport { MonoTypeOperatorFunction, SchedulerAction, SchedulerLike, TeardownLogic } from '../types';\nimport { timeoutWith } from './timeoutWith';\nimport { throwError } from '../observable/throwError';\n\n/**\n *\n * Errors if Observable does not emit a value in given time span.\n *\n * <span class=\"informal\">Timeouts on Observable that doesn't emit values fast enough.</span>\n *\n * ![](timeout.png)\n *\n * `timeout` operator accepts as an argument either a number or a Date.\n *\n * If number was provided, it returns an Observable that behaves like a source\n * Observable, unless there is a period of time where there is no value emitted.\n * So if you provide `100` as argument and first value comes after 50ms from\n * the moment of subscription, this value will be simply re-emitted by the resulting\n * Observable. If however after that 100ms passes without a second value being emitted,\n * stream will end with an error and source Observable will be unsubscribed.\n * These checks are performed throughout whole lifecycle of Observable - from the moment\n * it was subscribed to, until it completes or errors itself. Thus every value must be\n * emitted within specified period since previous value.\n *\n * If provided argument was Date, returned Observable behaves differently. It throws\n * if Observable did not complete before provided Date. This means that periods between\n * emission of particular values do not matter in this case. If Observable did not complete\n * before provided Date, source Observable will be unsubscribed. Other than that, resulting\n * stream behaves just as source Observable.\n *\n * `timeout` accepts also a Scheduler as a second parameter. It is used to schedule moment (or moments)\n * when returned Observable will check if source stream emitted value or completed.\n *\n * ## Examples\n * Check if ticks are emitted within certain timespan\n * ```ts\n * import { interval } from 'rxjs';\n * import { timeout } from 'rxjs/operators';\n *\n * const seconds = interval(1000);\n *\n * seconds.pipe(timeout(1100)) // Let's use bigger timespan to be safe,\n * // since `interval` might fire a bit later then scheduled.\n * .subscribe(\n * value => console.log(value), // Will emit numbers just as regular `interval` would.\n * err => console.log(err), // Will never be called.\n * );\n *\n * seconds.pipe(timeout(900))\n * .subscribe(\n * value => console.log(value), // Will never be called.\n * err => console.log(err), // Will emit error before even first value is emitted,\n * // since it did not arrive within 900ms period.\n * );\n * ```\n *\n * Use Date to check if Observable completed\n * ```ts\n * import { interval } from 'rxjs';\n * import { timeout } from 'rxjs/operators';\n *\n * const seconds = interval(1000);\n *\n * seconds.pipe(\n * timeout(new Date(\"December 17, 2020 03:24:00\")),\n * )\n * .subscribe(\n * value => console.log(value), // Will emit values as regular `interval` would\n * // until December 17, 2020 at 03:24:00.\n * err => console.log(err) // On December 17, 2020 at 03:24:00 it will emit an error,\n * // since Observable did not complete by then.\n * );\n * ```\n * @see {@link timeoutWith}\n *\n * @param {number|Date} due Number specifying period within which Observable must emit values\n * or Date specifying before when Observable should complete\n * @param {SchedulerLike} [scheduler] Scheduler controlling when timeout checks occur.\n * @return {Observable<T>} Observable that mirrors behaviour of source, unless timeout checks fail.\n * @method timeout\n * @owner Observable\n */\nexport function timeout<T>(due: number | Date,\n scheduler: SchedulerLike = async): MonoTypeOperatorFunction<T> {\n return timeoutWith(due, throwError(new TimeoutError()), scheduler);\n}\n","import Dexie from 'dexie';\nimport { DexieCloudDB } from '../db/DexieCloudDB';\n\n//const hasSW = 'serviceWorker' in navigator;\nlet hasComplainedAboutSyncEvent = false;\n\nexport async function registerSyncEvent(db: DexieCloudDB, purpose: \"push\" | \"pull\") {\n try {\n // Send sync event to SW:\n const sw = await navigator.serviceWorker.ready;\n if (purpose === \"push\" && sw.sync) {\n await sw.sync.register(`dexie-cloud:${db.name}`);\n }\n if (sw.active) {\n // Use postMessage for pull syncs and for browsers not supporting sync event (Firefox, Safari).\n // Also chromium based browsers with sw.sync as a fallback for sleepy sync events not taking action for a while.\n sw.active.postMessage({\n type: 'dexie-cloud-sync',\n dbName: db.name,\n purpose\n });\n } else {\n console.error(`Dexie Cloud: There's no active service worker. Can this ever happen??`);\n }\n return;\n } catch (e) {\n if (!hasComplainedAboutSyncEvent) {\n console.debug(`Dexie Cloud: Could not register sync event`, e);\n hasComplainedAboutSyncEvent = true;\n }\n }\n}\n\nexport async function registerPeriodicSyncEvent(db: DexieCloudDB) {\n try {\n // Register periodicSync event to SW:\n // @ts-ignore\n const { periodicSync } = await navigator.serviceWorker.ready;\n if (periodicSync) {\n try {\n await periodicSync.register(\n `dexie-cloud:${db.name}`,\n db.cloud.options?.periodicSync\n );\n console.debug(\n `Dexie Cloud: Successfully registered periodicsync event for ${db.name}`\n );\n } catch (e) {\n console.debug(`Dexie Cloud: Failed to register periodic sync. Your PWA must be installed to allow background sync.`, e);\n }\n } else {\n console.debug(`Dexie Cloud: periodicSync not supported.`);\n }\n } catch (e) {\n console.debug(\n `Dexie Cloud: Could not register periodicSync for ${db.name}`,\n e\n );\n }\n}\n","import { DexieCloudDB } from \"../db/DexieCloudDB\";\nimport { registerSyncEvent } from \"./registerSyncEvent\";\n\nexport function triggerSync(db: DexieCloudDB, purpose: \"push\" | \"pull\") {\n if (db.cloud.usingServiceWorker) {\n registerSyncEvent(db, purpose);\n } else {\n db.localSyncEvent.next({purpose});\n }\n}","export const b64decode = typeof Buffer !== \"undefined\"\n ? (base64) => Buffer.from(base64, \"base64\")\n : (base64) => {\n const binary_string = atob(base64);\n const len = binary_string.length;\n const bytes = new Uint8Array(len);\n for (var i = 0; i < len; i++) {\n bytes[i] = binary_string.charCodeAt(i);\n }\n return bytes;\n };\nexport const b64encode = typeof Buffer !== \"undefined\"\n ? (b) => ArrayBuffer.isView(b)\n ? Buffer.from(b.buffer, b.byteOffset, b.byteLength).toString(\"base64\")\n : Buffer.from(b).toString(\"base64\")\n : (b) => btoa(String.fromCharCode.apply(null, b));\n","import { PersistedSyncState } from '../db/entities/PersistedSyncState';\nimport { b64encode } from 'dreambase-library/dist/common/base64';\n\nexport async function computeRealmSetHash({\n realms,\n inviteRealms,\n}: PersistedSyncState) {\n const data = JSON.stringify(\n [\n ...realms.map((realmId) => ({ realmId, accepted: true })),\n ...inviteRealms.map((realmId) => ({ realmId, accepted: false })),\n ].sort((a, b) =>\n a.realmId < b.realmId ? -1 : a.realmId > b.realmId ? 1 : 0\n )\n );\n const byteArray = new TextEncoder().encode(data);\n const digestBytes = await crypto.subtle.digest('SHA-1', byteArray);\n const base64 = b64encode(digestBytes);\n return base64;\n}\n","import { IndexableType, Table } from \"dexie\";\nimport { DexieCloudDB } from \"../db/DexieCloudDB\";\nimport { EntityCommon } from \"../db/entities/EntityCommon\";\n\nexport function getSyncableTables(db: DexieCloudDB): Table<EntityCommon>[] {\n return Object.entries(db.cloud.schema || {})\n .filter(([, { markedForSync }]) => markedForSync)\n .map(([tbl]) => db.table(tbl));\n}\n","\n\nexport function getMutationTable(tableName: string) {\n return `$${tableName}_mutations`;\n}\n","\n\nexport function getTableFromMutationTable(mutationTable: string) {\n const tableName = /^\\$(.*)_mutations$/.exec(mutationTable)?.[1];\n if (!tableName) throw new Error(`Given mutationTable ${mutationTable} is not correct`);\n return tableName;\n}\n","import { Table } from \"dexie\";\nimport { getTableFromMutationTable } from \"../helpers/getTableFromMutationTable\";\nimport { DexieCloudDB } from \"../db/DexieCloudDB\";\nimport { DBOperation, DBOperationsSet } from \"dexie-cloud-common\";\n\nexport async function listClientChanges(\n mutationTables: Table[],\n db: DexieCloudDB,\n { since = {} as {[table: string]: number}, limit = Infinity } = {}): Promise<DBOperationsSet> {\n const allMutsOnTables = await Promise.all(\n mutationTables.map(async (mutationTable) => {\n const tableName = getTableFromMutationTable(mutationTable.name);\n const lastRevision = since[tableName];\n\n let query = lastRevision\n ? mutationTable.where(\"rev\").above(lastRevision)\n : mutationTable;\n\n if (limit < Infinity) query = query.limit(limit);\n \n const muts: DBOperation[] = await query.toArray();\n\n //const objTable = db.table(tableName);\n /*for (const mut of muts) {\n if (mut.type === \"insert\" || mut.type === \"upsert\") {\n mut.values = await objTable.bulkGet(mut.keys);\n }\n }*/\n return {\n table: tableName,\n muts,\n };\n })\n );\n\n // Filter out those tables that doesn't have any mutations:\n return allMutsOnTables.filter(({ muts }) => muts.length > 0);\n}\n","//@ts-check\nconst _fetch = fetch;\nexport { _fetch as fetch };\nexport const randomFillSync = crypto.getRandomValues;\n","import { randomFillSync } from \"universal-imports\";\nexport function assert(b) {\n if (!b)\n throw new Error('Assertion Failed');\n}\nexport function setByKeyPath(obj, keyPath, value) {\n if (!obj || keyPath === undefined)\n return;\n if ('isFrozen' in Object && Object.isFrozen(obj))\n return;\n if (typeof keyPath !== 'string' && 'length' in keyPath) {\n assert(typeof value !== 'string' && 'length' in value);\n for (var i = 0, l = keyPath.length; i < l; ++i) {\n setByKeyPath(obj, keyPath[i], value[i]);\n }\n }\n else {\n var period = keyPath.indexOf('.');\n if (period !== -1) {\n var currentKeyPath = keyPath.substr(0, period);\n var remainingKeyPath = keyPath.substr(period + 1);\n if (remainingKeyPath === '')\n if (value === undefined) {\n if (Array.isArray(obj)) {\n if (!isNaN(parseInt(currentKeyPath)))\n obj.splice(parseInt(currentKeyPath), 1);\n }\n else\n delete obj[currentKeyPath];\n // @ts-ignore: even if currentKeyPath would be numeric string and obj would be array - it works.\n }\n else\n obj[currentKeyPath] = value;\n else {\n //@ts-ignore: even if currentKeyPath would be numeric string and obj would be array - it works.\n var innerObj = obj[currentKeyPath];\n //@ts-ignore: even if currentKeyPath would be numeric string and obj would be array - it works.\n if (!innerObj)\n innerObj = obj[currentKeyPath] = {};\n setByKeyPath(innerObj, remainingKeyPath, value);\n }\n }\n else {\n if (value === undefined) {\n if (Array.isArray(obj) && !isNaN(parseInt(keyPath)))\n // @ts-ignore: even if currentKeyPath would be numeric string and obj would be array - it works.\n obj.splice(keyPath, 1);\n //@ts-ignore: even if currentKeyPath would be numeric string and obj would be array - it works.\n else\n delete obj[keyPath];\n //@ts-ignore: even if currentKeyPath would be numeric string and obj would be array - it works.\n }\n else\n obj[keyPath] = value;\n }\n }\n}\nexport const randomString = typeof self === 'undefined' ? (bytes) => {\n // Node\n const buf = Buffer.alloc(bytes);\n randomFillSync(buf);\n return buf.toString(\"base64\");\n} : (bytes) => {\n // Web\n const buf = new Uint8Array(bytes);\n crypto.getRandomValues(buf);\n return btoa(String.fromCharCode.apply(null, buf));\n};\n","const validIDTypes = {\n Uint8Array,\n};\n/** Verifies that given primary key is valid.\n * The reason we narrow validity for valid keys are twofold:\n * 1: Make sure to only support types that can be used as an object index in DBKeyMutationSet.\n * For example, ArrayBuffer cannot be used (gives \"object ArrayBuffer\") but Uint8Array can be\n * used (gives comma-delimited list of included bytes).\n * 2: Avoid using plain numbers and Dates as keys when they are synced, as they are not globally unique.\n * 3: Since we store the key as a VARCHAR server side in current version, try not promote types that stringifies to become very long server side.\n *\n * @param id\n * @returns\n */\nexport function isValidSyncableID(id) {\n if (typeof id === \"string\")\n return true;\n //if (validIDTypes[toStringTag(id)]) return true;\n //if (Array.isArray(id)) return id.every((part) => isValidSyncableID(part));\n if (Array.isArray(id) && id.some(key => isValidSyncableID(key)) && id.every(isValidSyncableIDPart))\n return true;\n return false;\n}\n/** Verifies that given key part is valid.\n * 1: Make sure that arrays of this types are stringified correclty and works with DBKeyMutationSet.\n * For example, ArrayBuffer cannot be used (gives \"object ArrayBuffer\") but Uint8Array can be\n * used (gives comma-delimited list of included bytes).\n * 2: Since we store the key as a VARCHAR server side in current version, try not promote types that stringifies to become very long server side.\n*/\nfunction isValidSyncableIDPart(part) {\n return typeof part === \"string\" || typeof part === \"number\" || Array.isArray(part) && part.every(isValidSyncableIDPart);\n}\nexport function isValidAtID(id, idPrefix) {\n return !idPrefix || (typeof id === \"string\" && id.startsWith(idPrefix));\n}\n","import { setByKeyPath } from \"../utils.js\";\nexport function applyOperation(target, table, op) {\n const tbl = target[table] || (target[table] = {});\n switch (op.type) {\n case \"insert\":\n // TODO: Don't treat insert and upsert the same?\n case \"upsert\":\n op.keys.forEach((key, idx) => {\n tbl[key] = {\n type: \"ups\",\n val: op.values[idx],\n };\n });\n break;\n case \"update\":\n case \"modify\": {\n op.keys.forEach((key, idx) => {\n const changeSpec = op.type === \"update\"\n ? op.changeSpecs[idx]\n : op.changeSpec;\n const entry = tbl[key];\n if (!entry) {\n tbl[key] = {\n type: \"upd\",\n mod: changeSpec,\n };\n }\n else {\n switch (entry.type) {\n case \"ups\":\n // Adjust the existing upsert with additional updates\n for (const [propPath, value] of Object.entries(changeSpec)) {\n setByKeyPath(entry.val, propPath, value);\n }\n break;\n case \"del\":\n // No action.\n break;\n case \"upd\":\n // Adjust existing update with additional updates\n Object.assign(entry.mod, changeSpec); // May work for deep props as well - new keys is added later, right? Does the prop order persist along TSON and all? But it will not be 100% when combined with some server code (seach for \"address.city\": \"Stockholm\" comment)\n break;\n }\n }\n });\n break;\n }\n case \"delete\":\n op.keys.forEach((key) => {\n tbl[key] = {\n type: \"del\",\n };\n });\n break;\n }\n return target;\n}\n","import { applyOperation } from \"./applyOperation.js\";\nexport function applyOperations(target, ops) {\n for (const { table, muts } of ops) {\n for (const mut of muts) {\n applyOperation(target, table, mut);\n }\n }\n}\n","import { setByKeyPath } from '../utils.js';\nexport function subtractChanges(target, // Server change set\nchangesToSubtract // additional mutations on client during syncWithServer()\n) {\n var _a, _b, _c;\n for (const [table, mutationSet] of Object.entries(changesToSubtract)) {\n for (const [key, mut] of Object.entries(mutationSet)) {\n switch (mut.type) {\n case 'ups':\n {\n const targetMut = (_a = target[table]) === null || _a === void 0 ? void 0 : _a[key];\n if (targetMut) {\n switch (targetMut.type) {\n case 'ups':\n delete target[table][key];\n break;\n case 'del':\n // Leave delete operation.\n // (Don't resurrect objects unintenionally (using tx(get, put) pattern locally))\n break;\n case 'upd':\n delete target[table][key];\n break;\n }\n }\n }\n break;\n case 'del':\n (_b = target[table]) === null || _b === void 0 ? true : delete _b[key];\n break;\n case 'upd': {\n const targetMut = (_c = target[table]) === null || _c === void 0 ? void 0 : _c[key];\n if (targetMut) {\n switch (targetMut.type) {\n case 'ups':\n // Adjust the server upsert with locally updated values.\n for (const [propPath, value] of Object.entries(mut.mod)) {\n setByKeyPath(targetMut.val, propPath, value);\n }\n break;\n case 'del':\n // Leave delete.\n break;\n case 'upd':\n // Remove the local update props from the server update mutation.\n for (const propPath of Object.keys(mut.mod)) {\n delete targetMut.mod[propPath];\n }\n break;\n }\n }\n break;\n }\n }\n }\n }\n}\n","import { randomString } from \"../utils.js\";\n/** Convert a DBKeyMutationSet (which is an internal format capable of looking up changes per ID)\n * ...into a DBOperationsSet (which is more optimal for performing DB operations into DB (bulkAdd() etc))\n *\n * @param inSet\n * @returns DBOperationsSet representing inSet\n */\nexport function toDBOperationSet(inSet) {\n // Fictive transaction:\n const txid = randomString(16);\n // Convert data into a temporary map to collect mutations of same table and type\n const map = {};\n for (const [table, ops] of Object.entries(inSet)) {\n for (const [key, op] of Object.entries(ops)) {\n const mapEntry = map[table] || (map[table] = {});\n const ops = mapEntry[op.type] || (mapEntry[op.type] = []);\n ops.push(Object.assign({ key }, op)); // DBKeyMutation doesn't contain key, so we need to bring it in.\n }\n }\n // Start computing the resulting format:\n const result = [];\n for (const [table, ops] of Object.entries(map)) {\n const resultEntry = {\n table,\n muts: [],\n };\n for (const [optype, muts] of Object.entries(ops)) {\n switch (optype) {\n case \"ups\": {\n const op = {\n type: \"upsert\",\n keys: muts.map(mut => mut.key),\n values: muts.map(mut => mut.val),\n txid\n };\n resultEntry.muts.push(op);\n break;\n }\n case \"upd\": {\n const op = {\n type: \"update\",\n keys: muts.map(mut => mut.key),\n changeSpecs: muts.map(mut => mut.mod),\n txid\n };\n resultEntry.muts.push(op);\n break;\n }\n case \"del\": {\n const op = {\n type: \"delete\",\n keys: muts.map(mut => mut.key),\n txid,\n };\n resultEntry.muts.push(op);\n break;\n }\n }\n }\n result.push(resultEntry);\n }\n return result;\n}\n","export function getDbNameFromDbUrl(dbUrl) {\n const url = new URL(dbUrl);\n return url.pathname === \"/\"\n ? url.hostname.split('.')[0]\n : url.pathname.split('/')[1];\n}\n","import { DexieCloudDB } from \"../db/DexieCloudDB\";\nimport { PersistedSyncState } from \"../db/entities/PersistedSyncState\";\nimport { UserLogin } from \"../db/entities/UserLogin\";\nimport { randomString } from \"../helpers/randomString\";\nimport { EntityCommon } from \"../db/entities/EntityCommon\";\nimport { Table } from \"dexie\";\nimport { DBInsertOperation, DBOperationsSet, DexieCloudSchema, isValidAtID, isValidSyncableID } from \"dexie-cloud-common\";\n\nexport async function listSyncifiedChanges(\n tablesToSyncify: Table<EntityCommon>[],\n currentUser: UserLogin,\n schema: DexieCloudSchema,\n alreadySyncedRealms?: string[]\n): Promise<DBOperationsSet> {\n if (currentUser.isLoggedIn) {\n if (tablesToSyncify.length > 0) {\n const ignoredRealms = new Set(alreadySyncedRealms || []);\n const inserts = await Promise.all(\n tablesToSyncify.map(async (table) => {\n const { extractKey } = table.core.schema.primaryKey;\n if (!extractKey) return { table: table.name, muts: [] }; // Outbound tables are not synced.\n\n const dexieCloudTableSchema = schema[table.name];\n const query = dexieCloudTableSchema?.generatedGlobalId\n ? table.filter(\n (item) => !ignoredRealms.has(item.realmId || \"\") && isValidSyncableID(extractKey(item))\n )\n : table.filter(\n (item) => !ignoredRealms.has(item.realmId || \"\") && isValidAtID(extractKey(item), dexieCloudTableSchema?.idPrefix)\n );\n const unsyncedObjects = await query.toArray();\n if (unsyncedObjects.length > 0) {\n const mut: DBInsertOperation = {\n type: \"insert\",\n values: unsyncedObjects,\n keys: unsyncedObjects.map(extractKey),\n userId: currentUser.userId,\n };\n return {\n table: table.name,\n muts: [mut],\n };\n } else {\n return {\n table: table.name,\n muts: []\n }\n }\n })\n );\n return inserts.filter(op => op.muts.length > 0);\n }\n }\n return [];\n}\n","import { getSyncableTables } from \"../helpers/getSyncableTables\";\nimport { DexieCloudDB } from \"../db/DexieCloudDB\";\nimport { PersistedSyncState } from \"../db/entities/PersistedSyncState\";\n\nexport function getTablesToSyncify(db: DexieCloudDB, syncState: PersistedSyncState | undefined) {\n const syncedTables = syncState?.syncedTables || [];\n const syncableTables = getSyncableTables(db);\n const tablesToSyncify = syncableTables.filter(\n (tbl) => !syncedTables.includes(tbl.name)\n );\n return tablesToSyncify;\n}\n","import Dexie from 'dexie';\nimport { BehaviorSubject } from 'rxjs';\nimport { take } from 'rxjs/operators';\nimport { DexieCloudDB } from '../db/DexieCloudDB';\nimport { DXCAlert } from '../types/DXCAlert';\nimport { DXCInputField } from '../types/DXCInputField';\nimport { DXCUserInteraction } from '../types/DXCUserInteraction';\n\nexport interface DXCUserInteractionRequest {\n type: DXCUserInteraction['type'];\n title: string;\n alerts: DXCAlert[];\n fields: { [name: string]: DXCInputField };\n}\n\nexport function interactWithUser<T extends DXCUserInteractionRequest>(\n userInteraction: BehaviorSubject<DXCUserInteraction | undefined>,\n req: T\n): Promise<\n {\n [P in keyof T['fields']]: string;\n }\n> {\n let done = false;\n return new Promise<\n {\n [P in keyof T['fields']]: string;\n }\n >((resolve, reject) => {\n const interactionProps = {\n ...req,\n onSubmit: (\n res: {\n [P in keyof T['fields']]: string;\n }\n ) => {\n userInteraction.next(undefined);\n done = true;\n resolve(res);\n },\n onCancel: () => {\n userInteraction.next(undefined);\n done = true;\n reject(new Dexie.AbortError(\"User cancelled\"));\n },\n } as DXCUserInteraction;\n userInteraction.next(interactionProps);\n // Start subscribing for external updates to db.cloud.userInteraction, and if so, cancel this request.\n /*const subscription = userInteraction.subscribe((currentInteractionProps) => {\n if (currentInteractionProps !== interactionProps) {\n if (subscription) subscription.unsubscribe();\n if (!done) {\n reject(new Dexie.AbortError(\"User cancelled\"));\n }\n }\n });*/\n });\n}\n\nexport function alertUser(\n userInteraction: BehaviorSubject<DXCUserInteraction | undefined>,\n title: string,\n ...alerts: DXCAlert[]\n) {\n return interactWithUser(userInteraction, {\n type: 'message-alert',\n title,\n alerts,\n fields: {}\n });\n}\n\nexport async function promptForEmail(\n userInteraction: BehaviorSubject<DXCUserInteraction | undefined>,\n title: string,\n emailHint?: string\n) {\n let email = emailHint || '';\n while (!email || !/^[\\w-\\.]+@([\\w-]+\\.)+[\\w-]{2,10}$/.test(email)) {\n email = (\n await interactWithUser(userInteraction, {\n type: 'email',\n title,\n alerts: email\n ? [\n {\n type: 'error',\n messageCode: 'INVALID_EMAIL',\n message: 'Please enter a valid email address',\n messageParams: {},\n },\n ]\n : [],\n fields: {\n email: {\n type: 'email',\n placeholder: 'you@somedomain.com',\n },\n },\n })\n ).email;\n }\n return email;\n}\n\nexport async function promptForOTP(\n userInteraction: BehaviorSubject<DXCUserInteraction | undefined>,\n email: string,\n alert?: DXCAlert\n) {\n const alerts: DXCAlert[] = [\n {\n type: 'info',\n messageCode: 'OTP_SENT',\n message: `A One-Time password has been sent to {email}`,\n messageParams: { email },\n },\n ];\n if (alert) {\n alerts.push(alert);\n }\n const { otp } = await interactWithUser(userInteraction, {\n type: 'otp',\n title: 'Enter OTP',\n alerts,\n fields: {\n otp: {\n type: 'otp',\n label: 'OTP',\n placeholder: 'Paste OTP here',\n },\n },\n });\n return otp;\n}\n","import type {\n RefreshTokenRequest,\n TokenFinalResponse,\n} from 'dexie-cloud-common';\nimport { b64encode } from 'dreambase-library/dist/common/base64';\nimport { BehaviorSubject } from 'rxjs';\nimport { DexieCloudDB } from '../db/DexieCloudDB';\nimport { UserLogin } from '../db/entities/UserLogin';\nimport { DXCAlert } from '../types/DXCAlert';\nimport {\n DXCMessageAlert,\n DXCUserInteraction,\n} from '../types/DXCUserInteraction';\nimport { alertUser, interactWithUser } from './interactWithUser';\n\nexport type FetchTokenCallback = (tokenParams: {\n public_key: string;\n hints?: { userId?: string; email?: string; grant_type?: string };\n}) => Promise<TokenFinalResponse>;\n\nexport async function loadAccessToken(\n db: DexieCloudDB\n): Promise<string | undefined> {\n const currentUser = await db.getCurrentUser();\n const {\n accessToken,\n accessTokenExpiration,\n refreshToken,\n refreshTokenExpiration,\n claims,\n } = currentUser;\n if (!accessToken) return;\n const expTime = accessTokenExpiration?.getTime() ?? Infinity;\n if (expTime > Date.now()) {\n return accessToken;\n }\n if (!refreshToken) {\n throw new Error(`Refresh token missing`);\n }\n const refreshExpTime = refreshTokenExpiration?.getTime() ?? Infinity;\n if (refreshExpTime <= Date.now()) {\n throw new Error(`Refresh token has expired`);\n }\n const refreshedLogin = await refreshAccessToken(\n db.cloud.options!.databaseUrl,\n currentUser\n );\n await db.table('$logins').update(claims.sub, {\n accessToken: refreshedLogin.accessToken,\n accessTokenExpiration: refreshedLogin.accessTokenExpiration,\n });\n return refreshedLogin.accessToken;\n}\n\nexport async function authenticate(\n url: string,\n context: UserLogin,\n fetchToken: FetchTokenCallback,\n userInteraction: BehaviorSubject<DXCUserInteraction | undefined>,\n hints?: { userId?: string; email?: string; grant_type?: string }\n): Promise<UserLogin> {\n if (\n context.accessToken &&\n context.accessTokenExpiration!.getTime() > Date.now()\n ) {\n return context;\n } else if (\n context.refreshToken &&\n (!context.refreshTokenExpiration ||\n context.refreshTokenExpiration.getTime() > Date.now())\n ) {\n return await refreshAccessToken(url, context);\n } else {\n return await userAuthenticate(context, fetchToken, userInteraction, hints);\n }\n}\n\nexport async function refreshAccessToken(\n url: string,\n login: UserLogin\n): Promise<UserLogin> {\n if (!login.refreshToken)\n throw new Error(`Cannot refresh token - refresh token is missing.`);\n if (!login.nonExportablePrivateKey)\n throw new Error(\n `login.nonExportablePrivateKey is missing - cannot sign refresh token without a private key.`\n );\n\n const time_stamp = Date.now();\n const signing_algorithm = 'RSASSA-PKCS1-v1_5';\n const textEncoder = new TextEncoder();\n const data = textEncoder.encode(login.refreshToken + time_stamp);\n const binarySignature = await crypto.subtle.sign(\n signing_algorithm,\n login.nonExportablePrivateKey,\n data\n );\n const signature = b64encode(binarySignature);\n\n const tokenRequest: RefreshTokenRequest = {\n grant_type: 'refresh_token',\n refresh_token: login.refreshToken,\n scopes: ['ACCESS_DB'],\n signature,\n signing_algorithm,\n time_stamp,\n };\n const res = await fetch(`${url}/token`, {\n body: JSON.stringify(tokenRequest),\n method: 'post',\n headers: { 'Content-Type': 'application/json' },\n mode: 'cors',\n });\n if (res.status !== 200)\n throw new Error(`RefreshToken: Status ${res.status} from ${url}/token`);\n const response: TokenFinalResponse = await res.json();\n login.accessToken = response.accessToken;\n login.accessTokenExpiration = response.accessTokenExpiration\n ? new Date(response.accessTokenExpiration)\n : undefined;\n return login;\n}\n\nasync function userAuthenticate(\n context: UserLogin,\n fetchToken: FetchTokenCallback,\n userInteraction: BehaviorSubject<DXCUserInteraction | undefined>,\n hints?: { userId?: string; email?: string; grant_type?: string }\n) {\n const { privateKey, publicKey } = await crypto.subtle.generateKey(\n {\n name: 'RSASSA-PKCS1-v1_5',\n modulusLength: 2048,\n publicExponent: new Uint8Array([0x01, 0x00, 0x01]),\n hash: { name: 'SHA-256' },\n },\n false, // Non-exportable...\n ['sign', 'verify']\n );\n context.nonExportablePrivateKey = privateKey; //...but storable!\n const publicKeySPKI = await crypto.subtle.exportKey('spki', publicKey);\n const publicKeyPEM = spkiToPEM(publicKeySPKI);\n context.publicKey = publicKey;\n\n try {\n const response2 = await fetchToken({\n public_key: publicKeyPEM,\n hints,\n });\n\n if (response2.type !== 'tokens')\n throw new Error(\n `Unexpected response type from token endpoint: ${response2.type}`\n );\n\n context.accessToken = response2.accessToken;\n context.accessTokenExpiration = new Date(response2.accessTokenExpiration);\n context.refreshToken = response2.refreshToken;\n if (response2.refreshTokenExpiration) {\n context.refreshTokenExpiration = new Date(\n response2.refreshTokenExpiration\n );\n }\n context.userId = response2.claims.sub;\n context.email = response2.claims.email;\n context.name = response2.claims.name;\n context.claims = response2.claims;\n\n if (response2.alerts && response2.alerts.length > 0) {\n await interactWithUser(userInteraction, {\n type: 'message-alert',\n title: 'Authentication Alert',\n fields: {},\n alerts: response2.alerts as DXCAlert[],\n });\n }\n return context;\n } catch (error) {\n await alertUser(userInteraction, 'Authentication Failed', {\n type: 'error',\n messageCode: 'GENERIC_ERROR',\n message: `We're having a problem to authenticate rigth now.`,\n messageParams: {}\n }).catch(()=>{});\n throw error;\n }\n}\n\nfunction spkiToPEM(keydata: ArrayBuffer) {\n const keydataB64 = b64encode(keydata);\n const keydataB64Pem = formatAsPem(keydataB64);\n return keydataB64Pem;\n}\n\nfunction formatAsPem(str: string) {\n let finalString = '-----BEGIN PUBLIC KEY-----\\n';\n\n while (str.length > 0) {\n finalString += str.substring(0, 64) + '\\n';\n str = str.substring(64);\n }\n\n finalString = finalString + '-----END PUBLIC KEY-----';\n\n return finalString;\n}\n","const { toString: toStr } = {};\nfunction getToStringTag(val) {\n return toStr.call(val).slice(8, -1);\n}\nexport function escapeDollarProps(value) {\n const keys = Object.keys(value);\n let dollarKeys = null;\n for (let i = 0, l = keys.length; i < l; ++i) {\n if (keys[i][0] === \"$\") {\n dollarKeys = dollarKeys || [];\n dollarKeys.push(keys[i]);\n }\n }\n if (!dollarKeys)\n return value;\n const clone = { ...value };\n for (const k of dollarKeys) {\n delete clone[k];\n clone[\"$\" + k] = value[k];\n }\n return clone;\n}\nconst ObjectDef = {\n replace: escapeDollarProps,\n};\nexport function TypesonSimplified(...typeDefsInputs) {\n const typeDefs = typeDefsInputs.reduce((p, c) => ({ ...p, ...c }), typeDefsInputs.reduce((p, c) => ({ ...c, ...p }), {}));\n const protoMap = new WeakMap();\n return {\n stringify(value, alternateChannel, space) {\n const json = JSON.stringify(value, function (key) {\n const realVal = this[key];\n const typeDef = getTypeDef(realVal);\n return typeDef\n ? typeDef.replace(realVal, alternateChannel, typeDefs)\n : realVal;\n }, space);\n return json;\n },\n parse(tson, alternateChannel) {\n let parent = null;\n let unescapeParentKeys = [];\n return JSON.parse(tson, function (key, value) {\n //\n // Parent Part\n //\n const type = value === null || value === void 0 ? void 0 : value.$t;\n if (type) {\n const typeDef = typeDefs[type];\n value = typeDef\n ? typeDef.revive(value, alternateChannel, typeDefs)\n : value;\n }\n if (value === parent) {\n // Do what the kid told us to\n if (unescapeParentKeys.length > 0) {\n // Unescape dollar props\n value = { ...value };\n for (const k of unescapeParentKeys) {\n value[k.substr(1)] = value[k];\n delete value[k];\n }\n }\n unescapeParentKeys = [];\n return value;\n }\n //\n // Child part\n //\n if (key[0] === \"$\" && key !== \"$t\") {\n parent = this;\n unescapeParentKeys.push(key);\n }\n return value;\n });\n },\n };\n function getTypeDef(realVal) {\n const type = typeof realVal;\n switch (typeof realVal) {\n case \"object\":\n case \"function\": {\n // \"object\", \"function\", null\n if (realVal === null)\n return null;\n const proto = Object.getPrototypeOf(realVal);\n if (!proto)\n return ObjectDef;\n let typeDef = protoMap.get(proto);\n if (typeDef !== undefined)\n return typeDef; // Null counts to! So the caching of Array.prototype also counts.\n const toStringTag = getToStringTag(realVal);\n const entry = Object.entries(typeDefs).find(([typeName, typeDef]) => { var _a, _b; return (_b = (_a = typeDef === null || typeDef === void 0 ? void 0 : typeDef.test) === null || _a === void 0 ? void 0 : _a.call(typeDef, realVal, toStringTag)) !== null && _b !== void 0 ? _b : typeName === toStringTag; });\n typeDef = entry === null || entry === void 0 ? void 0 : entry[1];\n if (!typeDef) {\n typeDef = Array.isArray(realVal)\n ? null\n : typeof realVal === \"function\"\n ? typeDefs.function || null\n : ObjectDef;\n }\n protoMap.set(proto, typeDef);\n return typeDef;\n }\n default:\n return typeDefs[type];\n }\n }\n}\n","export const BisonBinaryTypes = {\n Blob: {\n test: (blob, toStringTag) => toStringTag === \"Blob\",\n replace: (blob, altChannel) => {\n const i = altChannel.length;\n altChannel.push(blob);\n return {\n $t: \"Blob\",\n mimeType: blob.type,\n i,\n };\n },\n revive: ({ i, mimeType }, altChannel) => new Blob([altChannel[i]], { type: mimeType }),\n },\n};\n","export default {\n number: {\n replace: (num) => {\n switch (true) {\n case isNaN(num):\n return { $t: \"number\", v: \"NaN\" };\n case num === Infinity:\n return { $t: \"number\", v: \"Infinity\" };\n case num === -Infinity:\n return { $t: \"number\", v: \"-Infinity\" };\n default:\n return num;\n }\n },\n revive: ({ v }) => Number(v),\n },\n};\n","const bigIntDef = {\n bigint: {\n replace: (realVal) => {\n return { $t: \"bigint\", v: \"\" + realVal };\n },\n revive: (obj) => BigInt(obj.v),\n },\n};\nexport default bigIntDef;\n","export default {\n Date: {\n replace: (date) => ({\n $t: \"Date\",\n v: isNaN(date.getTime()) ? \"NaN\" : date.toISOString(),\n }),\n revive: ({ v }) => new Date(v === \"NaN\" ? NaN : Date.parse(v)),\n },\n};\n","export default {\n Set: {\n replace: (set) => ({\n $t: \"Set\",\n v: Array.from(set.entries()),\n }),\n revive: ({ v }) => new Set(v),\n },\n};\n","export default {\n Map: {\n replace: (map) => ({\n $t: \"Map\",\n v: Array.from(map.entries()),\n }),\n revive: ({ v }) => new Map(v),\n },\n};\n","export const _global = typeof globalThis !== \"undefined\"\n ? globalThis\n : typeof self !== \"undefined\"\n ? self\n : typeof global === \"undefined\"\n ? global\n : this;\n","import { _global } from \"../../common/_global.js\";\nexport default [\n \"Int8Array\",\n \"Uint8Array\",\n \"Uint8ClampedArray\",\n \"Int16Array\",\n \"Uint16Array\",\n \"Int32Array\",\n \"Uint32Array\",\n \"Float32Array\",\n \"Float64Array\",\n \"DataView\",\n \"BigInt64Array\",\n \"BigUint64Array\",\n].reduce((specs, typeName) => ({\n ...specs,\n [typeName]: {\n // Replace passes the the typed array into $t, buffer so that\n // the ArrayBuffer typedef takes care of further handling of the buffer:\n // {$t:\"Uint8Array\",buffer:{$t:\"ArrayBuffer\",idx:0}}\n // CHANGED ABOVE! Now shortcutting that for more sparse format of the typed arrays\n // to contain the b64 property directly.\n replace: (a, _, typeDefs) => {\n const result = {\n $t: typeName,\n v: typeDefs.ArrayBuffer.replace(a.byteOffset === 0 && a.byteLength === a.buffer.byteLength\n ? a.buffer\n : a.buffer.slice(a.byteOffset, a.byteOffset + a.byteLength), _, typeDefs).v,\n };\n return result;\n },\n revive: ({ v }, _, typeDefs) => {\n const TypedArray = _global[typeName];\n return (TypedArray &&\n new TypedArray(typeDefs.ArrayBuffer.revive({ v }, _, typeDefs)));\n },\n },\n}), {});\n","import { b64decode, b64encode } from \"./base64.js\";\nexport function b64LexEncode(b) {\n return b64ToLex(b64encode(b));\n}\nexport function b64LexDecode(b64Lex) {\n return b64decode(lexToB64(b64Lex));\n}\nexport function b64ToLex(base64) {\n var encoded = \"\";\n for (var i = 0, length = base64.length; i < length; i++) {\n encoded += ENCODE_TABLE[base64[i]];\n }\n return encoded;\n}\nexport function lexToB64(base64lex) {\n // only accept string input\n if (typeof base64lex !== \"string\") {\n throw new Error(\"invalid decoder input: \" + base64lex);\n }\n var base64 = \"\";\n for (var i = 0, length = base64lex.length; i < length; i++) {\n base64 += DECODE_TABLE[base64lex[i]];\n }\n return base64;\n}\nconst DECODE_TABLE = {\n \"-\": \"=\",\n \"0\": \"A\",\n \"1\": \"B\",\n \"2\": \"C\",\n \"3\": \"D\",\n \"4\": \"E\",\n \"5\": \"F\",\n \"6\": \"G\",\n \"7\": \"H\",\n \"8\": \"I\",\n \"9\": \"J\",\n A: \"K\",\n B: \"L\",\n C: \"M\",\n D: \"N\",\n E: \"O\",\n F: \"P\",\n G: \"Q\",\n H: \"R\",\n I: \"S\",\n J: \"T\",\n K: \"U\",\n L: \"V\",\n M: \"W\",\n N: \"X\",\n O: \"Y\",\n P: \"Z\",\n Q: \"a\",\n R: \"b\",\n S: \"c\",\n T: \"d\",\n U: \"e\",\n V: \"f\",\n W: \"g\",\n X: \"h\",\n Y: \"i\",\n Z: \"j\",\n _: \"k\",\n a: \"l\",\n b: \"m\",\n c: \"n\",\n d: \"o\",\n e: \"p\",\n f: \"q\",\n g: \"r\",\n h: \"s\",\n i: \"t\",\n j: \"u\",\n k: \"v\",\n l: \"w\",\n m: \"x\",\n n: \"y\",\n o: \"z\",\n p: \"0\",\n q: \"1\",\n r: \"2\",\n s: \"3\",\n t: \"4\",\n u: \"5\",\n v: \"6\",\n w: \"7\",\n x: \"8\",\n y: \"9\",\n z: \"+\",\n \"|\": \"/\",\n};\nconst ENCODE_TABLE = {};\nfor (const c of Object.keys(DECODE_TABLE)) {\n ENCODE_TABLE[DECODE_TABLE[c]] = c;\n}\n","import { b64LexDecode, b64LexEncode } from \"../../common/b64lex.js\";\nexport default {\n ArrayBuffer: {\n replace: (ab) => ({\n $t: \"ArrayBuffer\",\n v: b64LexEncode(ab),\n }),\n revive: ({ v }) => {\n const ba = b64LexDecode(v);\n return ba.buffer.byteLength === ba.byteLength\n ? ba.buffer\n : ba.buffer.slice(ba.byteOffset, ba.byteOffset + ba.byteLength);\n },\n },\n};\n","export class FakeBlob {\n constructor(buf, type) {\n this.buf = buf;\n this.type = type;\n }\n}\n","export function readBlobSync(b) {\n const req = new XMLHttpRequest();\n req.overrideMimeType(\"text/plain; charset=x-user-defined\");\n req.open(\"GET\", URL.createObjectURL(b), false); // Sync\n req.send();\n if (req.status !== 200 && req.status !== 0) {\n throw new Error(\"Bad Blob access: \" + req.status);\n }\n return req.responseText;\n}\n","export function string2ArrayBuffer(str) {\n const array = new Uint8Array(str.length);\n for (let i = 0; i < str.length; ++i) {\n array[i] = str.charCodeAt(i); // & 0xff;\n }\n return array.buffer;\n}\nexport function arrayBuffer2String(buf) {\n // TODO: Optimize\n return new Uint8Array(buf).reduce((s, byte) => s + String.fromCharCode(byte), \"\");\n}\n","import { b64decode, b64encode } from \"../../common/base64.js\";\nimport { FakeBlob } from \"../FakeBlob.js\";\nimport { readBlobSync } from \"../readBlobSync.js\";\nimport { string2ArrayBuffer } from \"../string2arraybuffer.js\";\nexport default {\n Blob: {\n test: (blob, toStringTag) => toStringTag === \"Blob\" || blob instanceof FakeBlob,\n replace: (blob) => ({\n $t: \"Blob\",\n v: blob instanceof FakeBlob\n ? b64encode(blob.buf)\n : b64encode(string2ArrayBuffer(readBlobSync(blob))),\n type: blob.type,\n }),\n revive: ({ type, v }) => {\n const ab = b64decode(v);\n return typeof Blob !== undefined\n ? new Blob([ab])\n : new FakeBlob(ab.buffer, type);\n },\n },\n};\n","import numberDef from \"../types/number.js\";\nimport bigintDef from \"../types/bigint.js\";\nimport DateDef from \"../types/Date.js\";\nimport SetDef from \"../types/Set.js\";\nimport MapDef from \"../types/Map.js\";\nimport TypedArraysDefs from \"../types/TypedArray.js\";\nimport ArrayBufferDef from \"../types/ArrayBuffer.js\";\nimport BlobDef from \"../types/Blob.js\";\nconst builtin = {\n ...numberDef,\n ...bigintDef,\n ...DateDef,\n ...SetDef,\n ...MapDef,\n ...TypedArraysDefs,\n ...ArrayBufferDef,\n ...BlobDef,\n};\nexport default builtin;\n","import { BisonBinaryTypes } from \"./BisonBinaryTypes.js\";\nimport builtin from \"./presets/builtin.js\";\nimport { TypesonSimplified } from \"./TypesonSimplified.js\";\nexport function Bison(...typeDefsInputs) {\n const tson = TypesonSimplified(builtin, BisonBinaryTypes, ...typeDefsInputs);\n return {\n toBinary(value) {\n const [blob, json] = this.stringify(value);\n const lenBuf = new ArrayBuffer(4);\n new DataView(lenBuf).setUint32(0, blob.size);\n return new Blob([lenBuf, blob, json]);\n },\n stringify(value) {\n const binaries = [];\n const json = tson.stringify(value, binaries);\n const blob = new Blob(binaries.map((b) => {\n const lenBuf = new ArrayBuffer(4);\n new DataView(lenBuf).setUint32(0, \"byteLength\" in b ? b.byteLength : b.size);\n return new Blob([lenBuf, b]);\n }));\n return [blob, json];\n },\n async parse(json, binData) {\n let pos = 0;\n const arrayBuffers = [];\n const buf = await readBlobBinary(binData);\n const view = new DataView(buf);\n while (pos < buf.byteLength) {\n const len = view.getUint32(pos);\n pos += 4;\n const ab = buf.slice(pos, pos + len);\n pos += len;\n arrayBuffers.push(ab);\n }\n return tson.parse(json, arrayBuffers);\n },\n async fromBinary(blob) {\n const len = new DataView(await readBlobBinary(blob.slice(0, 4))).getUint32(0);\n const binData = blob.slice(4, len + 4);\n const json = await readBlob(blob.slice(len + 4));\n return await this.parse(json, binData);\n },\n };\n}\nexport function readBlob(blob) {\n return new Promise((resolve, reject) => {\n const reader = new FileReader();\n reader.onabort = (ev) => reject(new Error(\"file read aborted\"));\n reader.onerror = (ev) => reject(ev.target.error);\n reader.onload = (ev) => resolve(ev.target.result);\n reader.readAsText(blob);\n });\n}\nexport function readBlobBinary(blob) {\n return new Promise((resolve, reject) => {\n const reader = new FileReader();\n reader.onabort = (ev) => reject(new Error(\"file read aborted\"));\n reader.onerror = (ev) => reject(ev.target.error);\n reader.onload = (ev) => resolve(ev.target.result);\n reader.readAsArrayBuffer(blob);\n });\n}\n","/** The undefined type is not part of builtin but can be manually added.\n * The reason for supporting undefined is if the following object should be revived correctly:\n *\n * {foo: undefined}\n *\n * Without including this typedef, the revived object would just be {}.\n * If including this typedef, the revived object would be {foo: undefined}.\n */\nexport default {\n undefined: {\n replace: () => {\n $t: \"undefined\";\n },\n revive: () => undefined,\n },\n};\n","import { TypesonSimplified } from 'dreambase-library/dist/typeson-simplified/TypesonSimplified';\nimport { Bison } from \"dreambase-library/dist/typeson-simplified/Bison\";\nimport undefinedDef from 'dreambase-library/dist/typeson-simplified/types/undefined.js';\nimport tsonBuiltinDefs from 'dreambase-library/dist/typeson-simplified/presets/builtin.js';\nimport { TypeDefSet } from 'dreambase-library/dist/typeson-simplified/TypeDefSet';\n\n// Since server revisions are stored in bigints, we need to handle clients without\n// bigint support to not fail when serverRevision is passed over to client.\n// We need to not fail when reviving it and we need to somehow store the information.\n// Since the revived version will later on be put into indexedDB we have another\n// issue: When reading it back from indexedDB we will get a poco object that we\n// cannot replace correctly when sending it to server. So we will also need\n// to do an explicit workaround in the protocol where a bigint is supported.\n// The workaround should be there regardless if browser supports BigInt or not, because\n// the serverRev might have been stored in IDB before the browser was upgraded to support bigint.\n//\n// if (typeof serverRev.rev !== \"bigint\")\n// if (hasBigIntSupport)\n// serverRev.rev = bigIntDef.bigint.revive(server.rev)\n// else\n// serverRev.rev = new FakeBigInt(server.rev)\nexport const hasBigIntSupport = typeof BigInt(0) === 'bigint';\n\nfunction getValueOfBigInt(x: bigint | FakeBigInt | string) {\n if (typeof x === 'bigint') {\n return x;\n }\n if (hasBigIntSupport) {\n return typeof x === 'string' ? BigInt(x) : BigInt(x.v);\n } else {\n return typeof x === 'string' ? Number(x) : Number(x.v);\n }\n}\n\nexport function compareBigInts(a: bigint | FakeBigInt | string, b:bigint | FakeBigInt | string) {\n const valA = getValueOfBigInt(a);\n const valB = getValueOfBigInt(b);\n return valA < valB ? -1 : valA > valB ? 1 : 0;\n}\nexport class FakeBigInt {\n v: string;\n toString() {\n return this.v;\n }\n constructor(value: string) {\n this.v = value;\n }\n}\n\nconst defs: TypeDefSet = {\n ...undefinedDef,\n ...(hasBigIntSupport\n ? {}\n : {\n bigint: {\n test: (val: any) => val instanceof FakeBigInt,\n replace: (fakeBigInt: any) => {\n return {\n $t: 'bigint',\n ...fakeBigInt\n };\n },\n revive: ({\n v,\n }: {\n $t: 'bigint';\n v: string;\n }) => new FakeBigInt(v) as any as bigint\n }\n })\n};\n\nexport const TSON = TypesonSimplified(tsonBuiltinDefs, defs);\n\nexport const BISON = Bison(defs);\n","export class HttpError extends Error {\n httpStatus: number;\n constructor(\n res: Response,\n message?: string)\n {\n super(message || `${res.status} ${res.statusText}`);\n this.httpStatus = res.status;\n }\n\n get name() {\n return \"HttpError\";\n }\n}\n","import { DexieCloudDB } from '../db/DexieCloudDB';\nimport { PersistedSyncState } from '../db/entities/PersistedSyncState';\nimport { loadAccessToken } from '../authentication/authenticate';\nimport { BISON, TSON } from '../TSON';\nimport { getSyncableTables } from '../helpers/getSyncableTables';\nimport { BaseRevisionMapEntry } from '../db/entities/BaseRevisionMapEntry';\nimport { HttpError } from '../errors/HttpError';\nimport {\n DBOperationsSet,\n DexieCloudSchema,\n SyncRequest,\n SyncResponse\n} from 'dexie-cloud-common';\n//import {BisonWebStreamReader} from \"dreambase-library/dist/typeson-simplified/BisonWebStreamReader\";\n\nexport async function syncWithServer(\n changes: DBOperationsSet,\n syncState: PersistedSyncState | undefined,\n baseRevs: BaseRevisionMapEntry[],\n db: DexieCloudDB,\n databaseUrl: string,\n schema: DexieCloudSchema | null,\n clientIdentity: string\n): Promise<SyncResponse> {\n //\n // Push changes to server using fetch\n //\n const headers: HeadersInit = {\n Accept: 'application/json, application/x-bison, application/x-bison-stream',\n 'Content-Type': 'application/tson'\n };\n const accessToken = await loadAccessToken(db);\n if (accessToken) {\n headers.Authorization = `Bearer ${accessToken}`;\n }\n\n const syncRequest: SyncRequest = {\n v:2,\n dbID: syncState?.remoteDbId,\n clientIdentity,\n schema: schema || {},\n lastPull: syncState ? {\n serverRevision: syncState.serverRevision!,\n realms: syncState.realms,\n inviteRealms: syncState.inviteRealms\n } : undefined,\n baseRevs,\n //baseRevisions: syncState?.baseRevisions || [],\n changes\n };\n console.debug(\"Sync request\", syncRequest);\n db.syncStateChangedEvent.next({\n phase: 'pushing',\n });\n const res = await fetch(`${databaseUrl}/sync`, {\n method: 'post',\n headers,\n body: TSON.stringify(syncRequest)\n });\n //const contentLength = Number(res.headers.get('content-length'));\n db.syncStateChangedEvent.next({\n phase: 'pulling'\n });\n\n if (!res.ok) {\n throw new HttpError(res);\n }\n\n switch (res.headers.get('content-type')) {\n case 'application/x-bison':\n return BISON.fromBinary(await res.blob());\n case 'application/x-bison-stream': //return BisonWebStreamReader(BISON, res);\n default:\n case 'application/json': {\n const text = await res.text();\n const syncRes = TSON.parse(text);\n return syncRes;\n }\n }\n}\n","import { Table } from \"dexie\";\nimport { EntityCommon } from \"../db/entities/EntityCommon\";\nimport { UserLogin } from \"../db/entities/UserLogin\";\nimport { Member } from \"../db/entities/Member\";\nimport { UNAUTHORIZED_USER } from \"../authentication/UNAUTHORIZED_USER\";\nimport { Realm } from \"../db/entities/Realm\";\n\nexport async function modifyLocalObjectsWithNewUserId(\n syncifiedTables: Table<EntityCommon>[],\n currentUser: UserLogin,\n alreadySyncedRealms?: string[]) {\n const ignoredRealms = new Set(alreadySyncedRealms || []);\n for (const table of syncifiedTables) {\n if (table.name === \"members\") {\n // members\n await table.toCollection().modify((member: Member) => {\n if (!ignoredRealms.has(member.realmId) && member.userId === UNAUTHORIZED_USER.userId) {\n member.userId = currentUser.userId;\n }\n });\n } else if (table.name === \"roles\") {\n // roles\n // No changes needed.\n } else if (table.name === \"realms\") {\n // realms\n await table.toCollection().modify((realm: Realm) => {\n if (!ignoredRealms.has(realm.realmId) && !realm.owner || realm.owner === UNAUTHORIZED_USER.userId) {\n realm.owner = currentUser.userId;\n }\n });\n } else {\n // application entities\n await table.toCollection().modify((obj) => {\n if (!obj.realmId || !ignoredRealms.has(obj.realmId)) {\n if (!obj.owner || obj.owner === UNAUTHORIZED_USER.userId)\n obj.owner = currentUser.userId;\n if (!obj.realmId || obj.realmId === UNAUTHORIZED_USER.userId) {\n obj.realmId = currentUser.userId;\n }\n }\n });\n }\n }\n}\n","import Dexie, { Table } from 'dexie';\n\nexport async function bulkUpdate(\n table: Table,\n keys: any[],\n changeSpecs: { [keyPath: string]: any }[]\n) {\n const objs = await table.bulkGet(keys);\n const resultKeys: any[] = [];\n const resultObjs: any[] = [];\n keys.forEach((key, idx) => {\n const obj = objs[idx];\n if (obj) {\n for (const [keyPath, value] of Object.entries(changeSpecs[idx])) {\n if (keyPath === table.schema.primKey.keyPath) {\n throw new Error(`Cannot change primary key`);\n }\n Dexie.setByKeyPath(obj, keyPath, value);\n }\n resultKeys.push(key);\n resultObjs.push(obj);\n }\n });\n await (table.schema.primKey.keyPath == null\n ? table.bulkPut(resultObjs, resultKeys)\n : table.bulkPut(resultObjs));\n}\n","import Dexie from \"dexie\";\n\nexport interface CancelToken {\n cancelled: boolean;\n}\n\nexport function throwIfCancelled(cancelToken?: CancelToken) {\n if (cancelToken?.cancelled) throw new Dexie.AbortError(`Operation was cancelled`);\n}\n","/* Need this because navigator.onLine seems to say \"false\" when it is actually online.\n This function relies initially on navigator.onLine but then uses online and offline events\n which seem to be more reliable.\n*/\nexport let isOnline = navigator.onLine;\nself.addEventListener('online', ()=>isOnline = true);\nself.addEventListener('offline', ()=>isOnline = false);\n","import { DexieCloudDB } from '../db/DexieCloudDB';\nimport { DexieCloudSchema, SyncResponse } from 'dexie-cloud-common';\n\nexport async function updateBaseRevs(db: DexieCloudDB, schema: DexieCloudSchema, latestRevisions: { [table: string]: number; }, serverRev: any) {\n await db.$baseRevs.bulkPut(\n Object.keys(schema)\n .filter((table) => schema[table].markedForSync)\n .map((tableName) => {\n const lastClientRevOnPreviousServerRev = latestRevisions[tableName] || 0;\n return {\n tableName,\n clientRev: lastClientRevOnPreviousServerRev + 1,\n serverRev,\n };\n })\n );\n}\n","import { DBOperationsSet } from 'dexie-cloud-common';\n\nexport function getLatestRevisionsPerTable(\n clientChangeSet: DBOperationsSet,\n lastRevisions = {} as { [table: string]: number; }) {\n for (const { table, muts } of clientChangeSet) {\n const lastRev = muts.length > 0 ? muts[muts.length - 1].rev : null;\n lastRevisions[table] = lastRev || lastRevisions[table] || 0;\n }\n return lastRevisions;\n}\n","import { getMutationTable } from '../helpers/getMutationTable';\nimport { getSyncableTables } from '../helpers/getSyncableTables';\nimport { DexieCloudDB } from '../db/DexieCloudDB';\nimport { listSyncifiedChanges } from './listSyncifiedChanges';\nimport { getTablesToSyncify } from './getTablesToSyncify';\nimport { listClientChanges } from './listClientChanges';\nimport { syncWithServer } from './syncWithServer';\nimport Dexie from 'dexie';\nimport { modifyLocalObjectsWithNewUserId } from './modifyLocalObjectsWithNewUserId';\nimport { bulkUpdate } from '../helpers/bulkUpdate';\nimport { throwIfCancelled } from '../helpers/CancelToken';\nimport { DexieCloudOptions } from '../DexieCloudOptions';\nimport { BaseRevisionMapEntry } from '../db/entities/BaseRevisionMapEntry';\nimport { getTableFromMutationTable } from '../helpers/getTableFromMutationTable';\nimport {\n applyOperations,\n DBKeyMutationSet,\n DBOperationsSet,\n DexieCloudSchema,\n randomString,\n subtractChanges,\n SyncResponse,\n toDBOperationSet,\n} from 'dexie-cloud-common';\nimport { PersistedSyncState } from '../db/entities/PersistedSyncState';\nimport { isOnline } from './isOnline';\nimport { updateBaseRevs } from './updateBaseRevs';\nimport { getLatestRevisionsPerTable } from './getLatestRevisionsPerTable';\n\nexport const CURRENT_SYNC_WORKER = 'currentSyncWorker';\n\nexport let numberOfSyncRequests = 0;\n\n/*\n TODO:\n 1. V: Rätta flödet och gör det persistent mellan transaktioner\n 2. Sync-requestet ska autenticera sig med nuvarande användare.\n MEN:\n Vissa medskickade operationer kan vara gjorda av annan användare.\n Därför: Om några av client-changes är andra användare, så måste de användarnas\n tokens följa med som extra parameter till fetch-requestet.\n Servern skall då validera och genomföra dessa operationer baserat på alternativt token.\n Kanske kan vi skita i det flödet just nu och hindra att det uppstår istället.\n Hur? Jo, genom:\n 1. Användare är ANONYMOUS\n 2. Data laddas ned.\n 3. Data modifieras.\n 4. Användare loggar in.\n 5. Sync: Några inledande requests är ANONYMOUS men autenticeras som användaren.\n\n X: Se till att vi förhandlar initialt sync state eller uppdaterat sync state (tabell aliases etc)\n\n Y: Använd Bison hjälpare för streamad BISON?\n\n*/\n\nexport interface SyncOptions {\n isInitialSync?: boolean;\n cancelToken?: { cancelled: boolean };\n justCheckIfNeeded?: boolean;\n retryImmediatelyOnFetchError?: boolean;\n purpose?: 'pull' | 'push';\n}\n\nexport function sync(\n db: DexieCloudDB,\n options: DexieCloudOptions,\n schema: DexieCloudSchema,\n syncOptions?: SyncOptions\n): Promise<boolean> {\n return _sync\n .apply(this, arguments)\n .then(() => {\n if (!syncOptions?.justCheckIfNeeded) {\n db.syncStateChangedEvent.next({\n phase: 'in-sync',\n });\n }\n })\n .catch(async (error: any) => {\n if (syncOptions?.justCheckIfNeeded) return Promise.reject(error); // Just rethrow.\n console.debug('Error from _sync', {\n isOnline,\n syncOptions,\n error,\n });\n if (\n isOnline &&\n syncOptions?.retryImmediatelyOnFetchError &&\n error?.name === 'TypeError' &&\n /fetch/.test(error?.message)\n ) {\n db.syncStateChangedEvent.next({\n phase: 'error',\n error,\n });\n // Retry again in 500 ms but if it fails again, don't retry.\n await new Promise((resolve) => setTimeout(resolve, 500));\n return await sync(db, options, schema, {\n ...syncOptions,\n retryImmediatelyOnFetchError: false,\n });\n }\n // Make sure that no matter whether sync() explodes or not,\n // always update the timestamp. Also store the error.\n await db.$syncState.update('syncState', {\n timestamp: new Date(),\n error: '' + error,\n });\n db.syncStateChangedEvent.next({\n phase: isOnline ? 'error' : 'offline',\n error,\n });\n return Promise.reject(error);\n });\n}\n\nasync function _sync(\n db: DexieCloudDB,\n options: DexieCloudOptions,\n schema: DexieCloudSchema,\n { isInitialSync, cancelToken, justCheckIfNeeded, purpose }: SyncOptions = {\n isInitialSync: false,\n }\n): Promise<boolean> {\n if (!justCheckIfNeeded) {\n console.debug('SYNC STARTED', { isInitialSync, purpose });\n }\n if (!db.cloud.options?.databaseUrl)\n throw new Error(\n `Internal error: sync must not be called when no databaseUrl is configured`\n );\n const { databaseUrl } = options;\n const currentUser = await db.getCurrentUser(); // Keep same value across entire sync flow:\n const tablesToSync = currentUser.isLoggedIn ? getSyncableTables(db) : [];\n\n const mutationTables = tablesToSync.map((tbl) =>\n db.table(getMutationTable(tbl.name))\n );\n\n // If this is not the initial sync,\n // go through tables that were previously not synced but should now be according to\n // logged in state and the sync table whitelist in db.cloud.options.\n //\n // Prepare for syncification by modifying locally unauthorized objects:\n //\n const persistedSyncState = await db.getPersistedSyncState();\n const tablesToSyncify =\n !isInitialSync && currentUser.isLoggedIn\n ? getTablesToSyncify(db, persistedSyncState)\n : [];\n throwIfCancelled(cancelToken);\n const doSyncify = tablesToSyncify.length > 0;\n\n if (doSyncify) {\n if (justCheckIfNeeded) return true;\n console.debug('sync doSyncify is true');\n await db.transaction('rw', tablesToSyncify, async (tx) => {\n // @ts-ignore\n tx.idbtrans.disableChangeTracking = true;\n // @ts-ignore\n tx.idbtrans.disableAccessControl = true; // TODO: Take care of this flag in access control middleware!\n await modifyLocalObjectsWithNewUserId(\n tablesToSyncify,\n currentUser,\n persistedSyncState?.realms\n );\n });\n throwIfCancelled(cancelToken);\n }\n //\n // List changes to sync\n //\n const [clientChangeSet, syncState, baseRevs] = await db.transaction(\n 'r',\n db.tables,\n async () => {\n const syncState = await db.getPersistedSyncState();\n const baseRevs = await db.$baseRevs.toArray();\n let clientChanges = await listClientChanges(mutationTables, db);\n throwIfCancelled(cancelToken);\n if (doSyncify) {\n const syncificationInserts = await listSyncifiedChanges(\n tablesToSyncify,\n currentUser,\n schema!,\n persistedSyncState?.realms\n );\n throwIfCancelled(cancelToken);\n clientChanges = clientChanges.concat(syncificationInserts);\n return [clientChanges, syncState, baseRevs];\n }\n return [clientChanges, syncState, baseRevs];\n }\n );\n\n const syncIsNeeded = clientChangeSet.some((set) =>\n set.muts.some((mut) => mut.keys.length > 0)\n );\n if (justCheckIfNeeded) {\n console.debug('Sync is needed:', syncIsNeeded);\n return syncIsNeeded;\n }\n if (purpose === \"push\" && !syncIsNeeded) {\n // The purpose of this request was to push changes\n return false;\n }\n\n const latestRevisions = getLatestRevisionsPerTable(\n clientChangeSet,\n syncState?.latestRevisions\n );\n\n const clientIdentity = syncState?.clientIdentity || randomString(16);\n\n //\n // Push changes to server\n //\n throwIfCancelled(cancelToken);\n const res = await syncWithServer(\n clientChangeSet,\n syncState,\n baseRevs,\n db,\n databaseUrl,\n schema,\n clientIdentity\n );\n console.debug('Sync response', res);\n\n //\n // Apply changes locally and clear old change entries:\n //\n const done = await db.transaction('rw', db.tables, async (tx) => {\n // @ts-ignore\n tx.idbtrans.disableChangeTracking = true;\n // @ts-ignore\n tx.idbtrans.disableAccessControl = true; // TODO: Take care of this flag in access control middleware!\n\n // Update db.cloud.schema from server response.\n // Local schema MAY include a subset of tables, so do not force all tables into local schema.\n for (const tableName of Object.keys(schema)) {\n if (res.schema[tableName]) {\n // Write directly into configured schema. This code can only be executed alone.\n schema[tableName] = res.schema[tableName];\n }\n }\n await db.$syncState.put(schema, 'schema');\n\n // List mutations that happened during our exchange with the server:\n const addedClientChanges = await listClientChanges(mutationTables, db, {\n since: latestRevisions,\n });\n\n //\n // Delete changes now as server has return success\n // (but keep changes that haven't reached server yet)\n //\n for (const mutTable of mutationTables) {\n const tableName = getTableFromMutationTable(mutTable.name);\n if (\n !addedClientChanges.some(\n (ch) => ch.table === tableName && ch.muts.length > 0\n )\n ) {\n // No added mutations for this table during the time we sent changes\n // to the server.\n // It is therefore safe to clear all changes (which is faster than\n // deleting a range)\n await Promise.all([\n mutTable.clear(),\n db.$baseRevs.where({ tableName }).delete(),\n ]);\n } else if (latestRevisions[mutTable.name]) {\n const latestRev = latestRevisions[mutTable.name] || 0;\n //await mutTable.where('rev').belowOrEqual(latestRev).reverse().offset(1).delete();\n await Promise.all([\n mutTable.where('rev').belowOrEqual(latestRev).delete(),\n db.$baseRevs\n .where(':id')\n .between(\n [tableName, -Infinity],\n [tableName, latestRev + 1],\n true,\n true\n )\n .reverse()\n .offset(1) // Keep one entry (the one mapping muts that came during fetch --> previous server revision)\n .delete(),\n ]);\n } else {\n // In this case, the mutation table only contains added items after sending empty changeset to server.\n // We should not clear out anything now.\n }\n }\n\n // Update latestRevisions object according to additional changes:\n getLatestRevisionsPerTable(addedClientChanges, latestRevisions);\n\n // Update/add new entries into baseRevs map.\n // * On tables without mutations since last serverRevision,\n // this will update existing entry.\n // * On tables where mutations have been recorded since last\n // serverRevision, this will create a new entry.\n // The purpose of this operation is to mark a start revision (per table)\n // so that all client-mutations that come after this, will be mapped to current\n // server revision.\n await updateBaseRevs(db, schema, latestRevisions, res.serverRevision);\n\n const syncState = await db.getPersistedSyncState();\n\n //\n // Delete objects from removed realms\n //\n await deleteObjectsFromRemovedRealms(db, res, syncState);\n\n //\n // Update syncState\n //\n const newSyncState: PersistedSyncState = syncState || {\n syncedTables: [],\n latestRevisions: {},\n realms: [],\n inviteRealms: [],\n clientIdentity\n };\n newSyncState.syncedTables = tablesToSync\n .map((tbl) => tbl.name)\n .concat(tablesToSyncify.map((tbl) => tbl.name));\n newSyncState.latestRevisions = latestRevisions;\n newSyncState.remoteDbId = res.dbId;\n newSyncState.initiallySynced = true;\n newSyncState.realms = res.realms;\n newSyncState.inviteRealms = res.inviteRealms;\n newSyncState.serverRevision = res.serverRevision;\n newSyncState.timestamp = new Date();\n delete newSyncState.error;\n\n const filteredChanges = filterServerChangesThroughAddedClientChanges(\n res.changes,\n addedClientChanges\n );\n\n //\n // apply server changes\n //\n await applyServerChanges(filteredChanges, db);\n\n //\n // Update syncState\n //\n db.$syncState.put(newSyncState, 'syncState');\n\n return addedClientChanges.length === 0;\n });\n if (!done) {\n console.debug('MORE SYNC NEEDED. Go for it again!');\n return await _sync(db, options, schema, { isInitialSync, cancelToken });\n }\n console.debug('SYNC DONE', { isInitialSync });\n return false; // Not needed anymore\n}\n\nasync function deleteObjectsFromRemovedRealms(\n db: DexieCloudDB,\n res: SyncResponse,\n prevState: PersistedSyncState | undefined\n) {\n const deletedRealms: string[] = [];\n const previousRealmSet = prevState\n ? prevState.realms.concat(prevState.inviteRealms)\n : [];\n const updatedRealmSet = new Set([...res.realms, ...res.inviteRealms]);\n for (const realmId of previousRealmSet) {\n if (!updatedRealmSet.has(realmId)) deletedRealms.push(realmId);\n }\n if (deletedRealms.length > 0) {\n const deletedRealmSet = new Set(deletedRealms);\n const tables = getSyncableTables(db);\n for (const table of tables) {\n if (\n table.schema.indexes.some(\n (idx) =>\n idx.keyPath === 'realmId' ||\n (Array.isArray(idx.keyPath) && idx.keyPath[0] === 'realmId')\n )\n ) {\n // There's an index to use:\n await table.where('realmId').anyOf(deletedRealms).delete();\n } else {\n // No index to use:\n await table\n .filter((obj) => !!obj?.realmId && deletedRealmSet.has(obj.realmId))\n .delete();\n }\n }\n }\n}\n\nexport async function applyServerChanges(\n changes: DBOperationsSet,\n db: DexieCloudDB\n) {\n console.debug('Applying server changes', changes, Dexie.currentTransaction);\n for (const { table: tableName, muts } of changes) {\n const table = db.table(tableName);\n if (!table) continue; // If server sends changes on a table we don't have, ignore it.\n const { primaryKey } = table.core.schema;\n for (const mut of muts) {\n switch (mut.type) {\n case 'insert':\n if (primaryKey.outbound) {\n await table.bulkAdd(mut.values, mut.keys);\n } else {\n mut.keys.forEach((key, i) => {\n Dexie.setByKeyPath(mut.values[i], primaryKey.keyPath as any, key);\n });\n await table.bulkAdd(mut.values);\n }\n break;\n case 'upsert':\n if (primaryKey.outbound) {\n await table.bulkPut(mut.values, mut.keys);\n } else {\n mut.keys.forEach((key, i) => {\n Dexie.setByKeyPath(mut.values[i], primaryKey.keyPath as any, key);\n });\n await table.bulkPut(mut.values);\n }\n break;\n case 'modify':\n if (mut.keys.length === 1) {\n await table.update(mut.keys[0], mut.changeSpec);\n } else {\n await table.where(':id').anyOf(mut.keys).modify(mut.changeSpec);\n }\n break;\n case 'update':\n await bulkUpdate(table, mut.keys, mut.changeSpecs);\n break;\n case 'delete':\n await table.bulkDelete(mut.keys);\n break;\n }\n }\n }\n}\n\nexport function filterServerChangesThroughAddedClientChanges(\n serverChanges: DBOperationsSet,\n addedClientChanges: DBOperationsSet\n): DBOperationsSet {\n const changes: DBKeyMutationSet = {};\n applyOperations(changes, serverChanges);\n const localPostChanges: DBKeyMutationSet = {};\n applyOperations(localPostChanges, addedClientChanges);\n subtractChanges(changes, localPostChanges);\n return toDBOperationSet(changes);\n}\n","import { BehaviorSubject } from 'rxjs';\nimport { filter, take } from 'rxjs/operators';\nimport { DexieCloudDB } from '../db/DexieCloudDB';\nimport { WSConnectionMsg } from '../WSObservable';\nimport { triggerSync } from './triggerSync';\nimport Dexie from 'dexie';\nimport { computeRealmSetHash } from '../helpers/computeRealmSetHash';\nimport { DBOperationsSet } from 'dexie-cloud-common';\nimport { getSyncableTables } from '../helpers/getSyncableTables';\nimport { getMutationTable } from '../helpers/getMutationTable';\nimport { listClientChanges } from './listClientChanges';\nimport {\n applyServerChanges,\n filterServerChangesThroughAddedClientChanges,\n} from './sync';\nimport { updateBaseRevs } from './updateBaseRevs';\nimport { getLatestRevisionsPerTable } from './getLatestRevisionsPerTable';\nimport { refreshAccessToken } from '../authentication/authenticate';\n\nexport type MessagesFromServerConsumer = ReturnType<\n typeof MessagesFromServerConsumer\n>;\n\nexport function MessagesFromServerConsumer(db: DexieCloudDB) {\n const queue: WSConnectionMsg[] = [];\n const readyToServe = new BehaviorSubject(true);\n const event = new BehaviorSubject(null);\n let isWorking = false;\n\n let loopWarning = 0;\n let loopDetection = [0,0,0,0,0,0,0,0,0,Date.now()];\n\n event.subscribe(async () => {\n if (isWorking) return;\n if (queue.length > 0) {\n isWorking = true;\n loopDetection.shift();\n loopDetection.push(Date.now());\n readyToServe.next(false);\n try {\n await consumeQueue();\n } finally {\n if (loopDetection[loopDetection.length-1] - loopDetection[0] < 10000) {\n // Ten loops within 10 seconds. Slow down!\n if (Date.now() - loopWarning < 5000) {\n // Last time we did this, we ended up here too. Wait for a minute.\n console.warn(`Slowing down websocket loop for one minute`)\n loopWarning = Date.now() + 60000;\n await new Promise(resolve => setTimeout(resolve, 60000));\n } else {\n // This is a one-time event. Just pause 10 seconds.\n console.warn(`Slowing down websocket loop for 10 seconds`);\n loopWarning = Date.now() + 10000;\n await new Promise(resolve => setTimeout(resolve, 10000));\n }\n }\n isWorking = false;\n readyToServe.next(true);\n }\n }\n });\n\n function enqueue(msg: WSConnectionMsg) {\n queue.push(msg);\n event.next(null);\n }\n\n async function consumeQueue() {\n while (queue.length > 0) {\n const msg = queue.shift();\n try {\n console.debug('processing msg', msg);\n // If the sync worker or service worker is syncing, wait 'til thei're done.\n // It's no need to have two channels at the same time - even though it wouldnt\n // be a problem - this is an optimization.\n await db.cloud.syncState\n .pipe(\n filter(({ phase }) => phase === 'in-sync' || phase === 'error'),\n take(1)\n )\n .toPromise();\n console.debug('processing msg', msg);\n const persistedSyncState = db.cloud.persistedSyncState.value;\n //syncState.\n if (!msg) continue;\n switch (msg.type) {\n case 'token-expired':\n console.debug(\n 'WebSocket observable: Token expired. Refreshing token...'\n );\n const user = db.cloud.currentUser.value;\n // Refresh access token\n const refreshedLogin = await refreshAccessToken(\n db.cloud.options!.databaseUrl,\n user\n );\n // Persist updated access token\n await db.table('$logins').update(user.userId, {\n accessToken: refreshedLogin.accessToken,\n accessTokenExpiration: refreshedLogin.accessTokenExpiration,\n });\n // Updating $logins will trigger emission of db.cloud.currentUser observable, which\n // in turn will lead to that connectWebSocket.ts will reconnect the socket with the\n // new token. So we don't need to do anything more here.\n break;\n case 'realm-added':\n if (!persistedSyncState?.realms?.includes(msg.realm)) {\n triggerSync(db, 'pull');\n }\n break;\n case 'realm-removed':\n if (persistedSyncState?.realms?.includes(msg.realm)) {\n triggerSync(db, 'pull');\n }\n break;\n case 'realms-changed':\n triggerSync(db, 'pull');\n break;\n case 'changes':\n console.debug('changes');\n if (db.cloud.syncState.value?.phase === 'error') {\n triggerSync(db, 'pull');\n break;\n }\n await db.transaction('rw', db.dx.tables, async (tx) => {\n // @ts-ignore\n tx.idbtrans.disableChangeTracking = true;\n // @ts-ignore\n tx.idbtrans.disableAccessControl = true;\n const [schema, syncState, currentUser] = await Promise.all([\n db.getSchema(),\n db.getPersistedSyncState(),\n db.getCurrentUser(),\n ]);\n console.debug('ws message queue: in transaction');\n if (!syncState || !schema || !currentUser) {\n console.debug('required vars not present', {\n syncState,\n schema,\n currentUser,\n });\n return; // Initial sync must have taken place - otherwise, ignore this.\n }\n // Verify again in ACID tx that we're on same server revision.\n if (msg.baseRev !== syncState.serverRevision) {\n console.debug(\n `baseRev (${msg.baseRev}) differs from our serverRevision in syncState (${syncState.serverRevision})`\n );\n // Should we trigger a sync now? No. This is a normal case\n // when another local peer (such as the SW or a websocket channel on other tab) has\n // updated syncState from new server information but we are not aware yet. It would\n // be unnescessary to do a sync in that case. Instead, the caller of this consumeQueue()\n // function will do readyToServe.next(true) right after this return, which will lead\n // to a \"ready\" message being sent to server with the new accurate serverRev we have,\n // so that the next message indeed will be correct.\n if (\n typeof msg.baseRev === 'string' && // v2 format\n (typeof syncState.serverRevision === 'bigint' || // v1 format\n typeof syncState.serverRevision === 'object') // v1 format old browser\n ) {\n // The reason for the diff seems to be that server has migrated the revision format.\n // Do a full sync to update revision format.\n // If we don't do a sync request now, we could stuck in an endless loop.\n triggerSync(db, 'pull');\n }\n return; // Ignore message\n }\n // Verify also that the message is based on the exact same set of realms\n const ourRealmSetHash = await Dexie.waitFor(\n // Keep TX in non-IDB work\n computeRealmSetHash(syncState)\n );\n console.debug('ourRealmSetHash', ourRealmSetHash);\n if (ourRealmSetHash !== msg.realmSetHash) {\n console.debug('not same realmSetHash', msg.realmSetHash);\n triggerSync(db, 'pull');\n // The message isn't based on the same realms.\n // Trigger a sync instead to resolve all things up.\n return;\n }\n\n // Get clientChanges\n let clientChanges: DBOperationsSet = [];\n if (currentUser.isLoggedIn) {\n const mutationTables = getSyncableTables(db).map((tbl) =>\n db.table(getMutationTable(tbl.name))\n );\n clientChanges = await listClientChanges(mutationTables, db);\n console.debug('msg queue: client changes', clientChanges);\n }\n if (msg.changes.length > 0) {\n const filteredChanges =\n filterServerChangesThroughAddedClientChanges(\n msg.changes,\n clientChanges\n );\n\n //\n // apply server changes\n //\n console.debug(\n 'applying filtered server changes',\n filteredChanges\n );\n await applyServerChanges(filteredChanges, db);\n }\n\n // Update latest revisions per table in case there are unsynced changes\n // This can be a real case in future when we allow non-eagery sync.\n // And it can actually be realistic now also, but very rare.\n syncState.latestRevisions = getLatestRevisionsPerTable(\n clientChanges,\n syncState.latestRevisions\n );\n\n syncState.serverRevision = msg.newRev;\n\n // Update base revs\n console.debug('Updating baseRefs', syncState.latestRevisions);\n await updateBaseRevs(\n db,\n schema!,\n syncState.latestRevisions,\n msg.newRev\n );\n\n //\n // Update syncState\n //\n console.debug('Updating syncState', syncState);\n await db.$syncState.put(syncState, 'syncState');\n });\n console.debug('msg queue: done with rw transaction');\n break;\n }\n } catch (error) {\n console.error(`Error in msg queue`, error);\n }\n }\n }\n\n return {\n enqueue,\n readyToServe,\n };\n}\n","import Dexie, { Table } from 'dexie';\nimport { GuardedJob } from './entities/GuardedJob';\nimport { UserLogin } from './entities/UserLogin';\nimport { PersistedSyncState } from './entities/PersistedSyncState';\nimport { Realm } from './entities/Realm';\nimport { Member } from './entities/Member';\nimport { Role } from './entities/Role';\nimport { UNAUTHORIZED_USER } from '../authentication/UNAUTHORIZED_USER';\nimport { DexieCloudOptions } from '../DexieCloudOptions';\nimport { BehaviorSubject, Subject } from 'rxjs';\nimport { BaseRevisionMapEntry } from './entities/BaseRevisionMapEntry';\nimport {\n DBRealm,\n DBRealmMember,\n DBRealmRole,\n DexieCloudSchema,\n} from 'dexie-cloud-common';\nimport { BroadcastedAndLocalEvent } from '../helpers/BroadcastedAndLocalEvent';\nimport { SyncState, SyncStatePhase } from '../types/SyncState';\nimport { MessagesFromServerConsumer } from '../sync/messagesFromServerQueue';\n\n/*export interface DexieCloudDB extends Dexie {\n table(name: string): Table<any, any>;\n table(name: \"$jobs\"): Table<GuardedJob, string>;\n table(name: \"$logins\"): Table<UserLogin, string>;\n table(name: \"$syncState\"): Table<SyncState, \"syncState\">;\n //table(name: \"$pendingChangesFromServer\"): Table<DBOperationsSet, number>;\n}\n*/\n\nexport interface SyncStateChangedEventData {\n phase: SyncStatePhase;\n error?: Error;\n progress?: number;\n}\n\ntype SyncStateTable = Table<\n PersistedSyncState | DexieCloudSchema | DexieCloudOptions,\n 'syncState' | 'options' | 'schema'\n>;\nexport interface DexieCloudDBBase {\n readonly name: Dexie['name'];\n readonly close: Dexie['close'];\n transaction: Dexie['transaction'];\n table: Dexie['table'];\n readonly tables: Dexie['tables'];\n readonly cloud: Dexie['cloud'];\n readonly $jobs: Table<GuardedJob, string>;\n readonly $logins: Table<UserLogin, string>;\n readonly $syncState: SyncStateTable;\n readonly $baseRevs: Table<BaseRevisionMapEntry, [string, number]>;\n\n readonly realms: Table<DBRealm, string>;\n readonly members: Table<DBRealmMember, string>;\n readonly roles: Table<DBRealmRole, [string, string]>;\n\n readonly localSyncEvent: BehaviorSubject<{ purpose?: 'pull' | 'push' }>;\n readonly syncStateChangedEvent: BroadcastedAndLocalEvent<SyncStateChangedEventData>;\n readonly dx: Dexie;\n readonly initiallySynced: boolean;\n}\n\nexport interface DexieCloudDB extends DexieCloudDBBase {\n getCurrentUser(): Promise<UserLogin>;\n getSchema(): Promise<DexieCloudSchema | undefined>;\n getOptions(): Promise<DexieCloudOptions | undefined>;\n getPersistedSyncState(): Promise<PersistedSyncState | undefined>;\n setInitiallySynced(initiallySynced: boolean): void;\n reconfigure(): void;\n messageConsumer: MessagesFromServerConsumer;\n}\n\nconst wm = new WeakMap<object, DexieCloudDB>();\n\nexport const DEXIE_CLOUD_SCHEMA = {\n realms: '@realmId',\n members: '@id',\n roles: '[realmId+name]',\n $jobs: '',\n $syncState: '',\n $baseRevs: '[tableName+clientRev]',\n $logins: 'claims.sub, lastLogin',\n};\n\nlet static_counter = 0;\nexport function DexieCloudDB(dx: Dexie): DexieCloudDB {\n if ('vip' in dx) dx = dx['vip']; // Avoid race condition. Always map to a vipped dexie that don't block during db.on.ready().\n let db = wm.get(dx.cloud);\n if (!db) {\n const localSyncEvent = new Subject<{ purpose: 'push' | 'pull' }>();\n let syncStateChangedEvent =\n new BroadcastedAndLocalEvent<SyncStateChangedEventData>(\n `syncstatechanged-${dx.name}`\n );\n localSyncEvent['id'] = ++static_counter;\n let initiallySynced = false;\n db = {\n get name() {\n return dx.name;\n },\n close() {\n return dx.close();\n },\n transaction: dx.transaction.bind(dx),\n table: dx.table.bind(dx),\n get tables() {\n return dx.tables;\n },\n cloud: dx.cloud,\n get $jobs() {\n return dx.table('$jobs') as Table<GuardedJob, string>;\n },\n get $syncState() {\n return dx.table('$syncState') as SyncStateTable;\n },\n get $baseRevs() {\n return dx.table('$baseRevs') as Table<\n BaseRevisionMapEntry,\n [string, number]\n >;\n },\n get $logins() {\n return dx.table('$logins') as Table<UserLogin, string>;\n },\n\n get realms() {\n return dx.realms;\n },\n get members() {\n return dx.members;\n },\n get roles() {\n return dx.roles;\n },\n get initiallySynced() {\n return initiallySynced;\n },\n localSyncEvent,\n get syncStateChangedEvent() {\n return syncStateChangedEvent;\n },\n dx,\n } as DexieCloudDB;\n\n const helperMethods: Partial<DexieCloudDB> = {\n getCurrentUser() {\n return db!.$logins\n .toArray()\n .then(\n (logins) => logins.find((l) => l.isLoggedIn) || UNAUTHORIZED_USER\n );\n },\n getPersistedSyncState() {\n return db!.$syncState.get('syncState') as Promise<\n PersistedSyncState | undefined\n >;\n },\n getSchema() {\n return db!.$syncState.get('schema') as Promise<\n DexieCloudSchema | undefined\n >;\n },\n getOptions() {\n return db!.$syncState.get('options') as Promise<\n DexieCloudOptions | undefined\n >;\n },\n setInitiallySynced(value) {\n initiallySynced = value;\n },\n reconfigure() {\n syncStateChangedEvent = new BroadcastedAndLocalEvent<SyncState>(\n `syncstatechanged-${dx.name}`\n );\n },\n };\n\n Object.assign(db, helperMethods);\n db.messageConsumer = MessagesFromServerConsumer(db);\n wm.set(dx.cloud, db);\n }\n return db;\n}\n","import { DexieCloudDB } from \"../db/DexieCloudDB\";\nimport { UserLogin } from \"../db/entities/UserLogin\";\n\nexport interface AuthPersistedContext extends UserLogin {\n save(): Promise<void>;\n}\n\n// Emulate true-private property db. Why? So it's not stored in DB.\nconst wm = new WeakMap<AuthPersistedContext, DexieCloudDB>();\n\nexport class AuthPersistedContext {\n constructor(db: DexieCloudDB, userLogin: UserLogin) {\n wm.set(this, db);\n Object.assign(this, userLogin);\n }\n\n static load(db: DexieCloudDB, userId: string) {\n return db\n .table(\"$logins\")\n .get(userId)\n .then(\n (userLogin) => new AuthPersistedContext(db, userLogin || {\n userId,\n claims: {\n sub: userId\n },\n lastLogin: new Date(0)\n })\n );\n }\n\n async save() {\n const db = wm.get(this)!;\n db.table(\"$logins\").put(this);\n }\n}\n","import {\n TokenFinalResponse,\n TokenRequest,\n TokenResponse,\n} from 'dexie-cloud-common';\nimport { DexieCloudDB } from '../db/DexieCloudDB';\nimport { HttpError } from '../errors/HttpError';\nimport { FetchTokenCallback } from './authenticate';\nimport { alertUser, promptForEmail, promptForOTP } from './interactWithUser';\n\nexport function otpFetchTokenCallback(db: DexieCloudDB): FetchTokenCallback {\n const { userInteraction } = db.cloud;\n return async function otpAuthenticate({ public_key, hints }) {\n let tokenRequest: TokenRequest;\n const url = db.cloud.options?.databaseUrl;\n if (!url) throw new Error(`No database URL given.`);\n if (hints?.grant_type === 'demo') {\n const demo_user = await promptForEmail(\n userInteraction,\n 'Enter a demo user email',\n hints?.email || hints?.userId\n );\n tokenRequest = {\n demo_user,\n grant_type: 'demo',\n scopes: ['ACCESS_DB'],\n public_key,\n };\n } else {\n const email = await promptForEmail(\n userInteraction,\n 'Enter email address',\n hints?.email\n );\n tokenRequest = {\n email,\n grant_type: 'otp',\n scopes: ['ACCESS_DB'],\n public_key,\n };\n }\n const res1 = await fetch(`${url}/token`, {\n body: JSON.stringify(tokenRequest),\n method: 'post',\n headers: { 'Content-Type': 'application/json', mode: 'cors' },\n });\n if (res1.status !== 200) {\n const errMsg = await res1.text();\n await alertUser(userInteraction, \"Token request failed\", {\n type: 'error',\n messageCode: 'GENERIC_ERROR',\n message: errMsg,\n messageParams: {}\n }).catch(()=>{});\n throw new HttpError(res1, errMsg);\n }\n const response: TokenResponse = await res1.json();\n if (response.type === 'tokens') {\n // Demo user request can get a \"tokens\" response right away\n return response;\n } else if (tokenRequest.grant_type === 'otp') {\n if (response.type !== 'otp-sent')\n throw new Error(`Unexpected response from ${url}/token`);\n const otp = await promptForOTP(userInteraction, tokenRequest.email);\n tokenRequest.otp = otp || '';\n tokenRequest.otp_id = response.otp_id;\n\n let res2 = await fetch(`${url}/token`, {\n body: JSON.stringify(tokenRequest),\n method: 'post',\n headers: { 'Content-Type': 'application/json' },\n mode: 'cors',\n });\n while (res2.status === 401) {\n const errorText = await res2.text();\n tokenRequest.otp = await promptForOTP(userInteraction, tokenRequest.email, {\n type: 'error',\n messageCode: 'INVALID_OTP',\n message: errorText,\n messageParams: {}\n });\n res2 = await fetch(`${url}/token`, {\n body: JSON.stringify(tokenRequest),\n method: 'post',\n headers: { 'Content-Type': 'application/json' },\n mode: 'cors',\n });\n }\n if (res2.status !== 200) {\n const errMsg = await res2.text();\n await alertUser(userInteraction, \"OTP Authentication Failed\", {\n type: 'error',\n messageCode: 'GENERIC_ERROR',\n message: errMsg,\n messageParams: {}\n }).catch(()=>{});\n throw new HttpError(res2, errMsg);\n }\n const response2: TokenFinalResponse = await res2.json();\n return response2;\n } else {\n throw new Error(`Unexpected response from ${url}/token`);\n }\n };\n}\n","import { DexieCloudDB } from \"../db/DexieCloudDB\";\nimport { AuthPersistedContext } from \"./AuthPersistedContext\";\n\n/** This function changes or sets the current user as requested.\n * \n * Use cases:\n * * Initially on db.ready after reading the current user from db.$logins.\n * This will make sure that any unsynced operations from the previous user is synced before\n * changing the user.\n * * Upon user request\n * \n * @param db \n * @param newUser \n */\nexport async function setCurrentUser(db: DexieCloudDB, user: AuthPersistedContext) {\n if (user.userId === db.cloud.currentUserId) return; // Already this user.\n\n const $logins = db.table('$logins');\n await db.transaction('rw', $logins, async tx => {\n const existingLogins = await $logins.toArray();\n await Promise.all(existingLogins.filter(login => login.userId !== user.userId && login.isLoggedIn).map(login => {\n login.isLoggedIn = false;\n return $logins.put(login);\n }));\n user.isLoggedIn = true;\n user.lastLogin = new Date();\n await user.save();\n console.debug(\"Saved new user\", user.email);\n });\n await new Promise(resolve=>{\n if (db.cloud.currentUserId === user.userId) {\n resolve(null);\n } else {\n const subscription = db.cloud.currentUser.subscribe(currentUser=>{\n if (currentUser.userId === user.userId) {\n subscription.unsubscribe();\n resolve(null);\n }\n });\n }\n });\n\n // TANKAR!!!!\n // V: Service workern kommer inte ha tillgång till currentUserObservable om den inte istället härrör från ett liveQuery.\n // V: Samma med andra windows.\n // V: Så kanske göra om den till att häröra från liveQuery som läser $logins.orderBy('lastLogin').last().\n // V: Då bara vara medveten om:\n // V: En sån observable börjar hämta data vid första subscribe\n // V: Vi har inget \"inital value\" men kan emulera det till att vara ANONYMOUS_USER\n // V: Om requireAuth är true, så borde db.on(ready) hålla databasen stängd för alla utom denna observable.\n // V: Om inte så behöver den inte blocka.\n\n // Andra tankar:\n // * Man kan inte byta användare när man är offline. Skulle gå att flytta realms till undanstuff-tabell vid user-change.\n // men troligen inte värt det.\n // * Istället: sälj inte inte switch-user funktionalitet utan tala enbart om inloggat vs icke inloggat läge.\n // * populate $logins med ANONYMOUS så att en påbörjad inloggning inte räknas, alternativt ha en boolean prop!\n // Kanske bäst ha en boolean prop!\n // * Alternativ switch-user funktionalitet:\n // * DBCore gömmer data från realms man inte har tillgång till.\n // * Cursor impl behövs också då.\n // * Då blir det snabba user switch.\n // * claims-settet som skickas till servern blir summan av alla claims. Då måste servern stödja multipla tokens eller\n // att ens token är ett samlad.\n}\n","import { DexieCloudDB } from '../db/DexieCloudDB';\nimport { triggerSync } from '../sync/triggerSync';\nimport { authenticate } from './authenticate';\nimport { AuthPersistedContext } from './AuthPersistedContext';\nimport { otpFetchTokenCallback } from './otpFetchTokenCallback';\nimport { setCurrentUser } from './setCurrentUser';\n\nexport async function login(\n db: DexieCloudDB,\n hints?: { email?: string; userId?: string; grant_type?: string }\n) {\n const currentUser = await db.getCurrentUser();\n if (currentUser.isLoggedIn) {\n if (hints) {\n if (hints.email && db.cloud.currentUser.value.email !== hints.email) {\n throw new Error(`Must logout before changing user`);\n }\n if (hints.userId && db.cloud.currentUserId !== hints.userId) {\n throw new Error(`Must logout before changing user`);\n }\n }\n // Already authenticated according to given hints.\n return;\n }\n const context = new AuthPersistedContext(db, {\n claims: {},\n lastLogin: new Date(0),\n });\n await authenticate(\n db.cloud.options!.databaseUrl,\n context,\n db.cloud.options!.fetchTokens || otpFetchTokenCallback(db),\n db.cloud.userInteraction,\n hints\n );\n await context.save();\n await setCurrentUser(db, context);\n // Make sure to resync as the new login will be authorized\n // for new realms.\n triggerSync(db, \"pull\");\n}\n","// @ts-ignore\nexport const isFirefox = typeof InstallTrigger !== 'undefined';\n","export const isSafari =\n typeof navigator !== 'undefined' &&\n /Safari\\//.test(navigator.userAgent) &&\n !/Chrom(e|ium)\\/|Edge\\//.test(navigator.userAgent);\n\nexport const safariVersion = isSafari\n ? // @ts-ignore\n [].concat(navigator.userAgent.match(/Safari\\/(\\d*)/))[1]\n : NaN;\n","import { isFirefox } from './isFirefox';\nimport { isSafari, safariVersion } from './isSafari';\n\n// What we know: Safari 14.1 (version 605) crashes when using dexie-cloud's service worker.\n// We don't know what exact call is causing this. Have tried safari-14-idb-fix with no luck.\n// Something we do in the service worker is triggering the crash.\n// When next Safari version (606) is out we will start enabling SW again, hoping that the bug is solved.\n// If not, we might increment 605 to 606.\nexport const DISABLE_SERVICEWORKER_STRATEGY =\n (isSafari && safariVersion <= 605) || // Disable for Safari for now.\n isFirefox; // Disable for Firefox for now. Seems to have a bug in reading CryptoKeys from IDB from service workers\n","import Dexie from \"dexie\";\n\n/* Helper function to subscribe to database close no matter if it was unexpectedly closed or manually using db.close()\n */\nexport function dbOnClosed(db: Dexie, handler: () => void) {\n db.on.close.subscribe(handler);\n const origClose = db.close;\n db.close = function () {\n origClose.call(this);\n handler();\n };\n return () => {\n db.on.close.unsubscribe(handler);\n db.close = origClose;\n };\n}\n","export const IS_SERVICE_WORKER =\n typeof self !== \"undefined\" && \"clients\" in self && !self.document;\n","import Dexie from \"dexie\";\n\nexport function throwVersionIncrementNeeded() {\n throw new Dexie.SchemaError(\n `Version increment needed to allow dexie-cloud change tracking`\n );\n}\n","import Dexie, {\n DBCore,\n DBCoreAddRequest,\n DBCoreDeleteRequest,\n DBCoreIndex,\n DBCoreMutateRequest,\n DBCorePutRequest,\n Middleware\n} from 'dexie';\nimport { isValidSyncableID } from 'dexie-cloud-common';\nimport { b64LexEncode } from 'dreambase-library/dist/common/b64lex';\nimport { DexieCloudDB } from '../db/DexieCloudDB';\n\nconst { toString } = {};\nexport function toStringTag(o: Object) {\n return toString.call(o).slice(8, -1);\n}\n\nexport function getEffectiveKeys(\n primaryKey: DBCoreIndex,\n req:\n | (Pick<DBCoreAddRequest | DBCorePutRequest, 'type' | 'values'> & {\n keys?: any[];\n })\n | Pick<DBCoreDeleteRequest, 'keys' | 'type'>\n) {\n if (req.type === 'delete') return req.keys;\n return req.keys?.slice() || req.values.map(primaryKey.extractKey!);\n}\n\nfunction applyToUpperBitFix(orig: string, bits: number) {\n return (\n (bits & 1 ? orig[0].toUpperCase() : orig[0].toLowerCase()) +\n (bits & 2 ? orig[1].toUpperCase() : orig[1].toLowerCase()) +\n (bits & 4 ? orig[2].toUpperCase() : orig[2].toLowerCase())\n );\n}\n\nconst consonants = /b|c|d|f|g|h|j|k|l|m|n|p|q|r|s|t|v|x|y|z/i;\n\nfunction isUpperCase(ch: string) {\n return ch >= 'A' && ch <= 'Z';\n}\n\nexport function generateTablePrefix(\n tableName: string,\n allPrefixes: Set<string>\n) {\n let rv = tableName[0].toLocaleLowerCase(); // \"users\" = \"usr\", \"friends\" = \"frn\", \"realms\" = \"rlm\", etc.\n for (let i = 1, l = tableName.length; i < l && rv.length < 3; ++i) {\n if (consonants.test(tableName[i]) || isUpperCase(tableName[i]))\n rv += tableName[i].toLowerCase();\n }\n while (allPrefixes.has(rv)) {\n if (/\\d/g.test(rv)) {\n rv = rv.substr(0, rv.length - 1) + (rv[rv.length - 1] + 1);\n if (rv.length > 3) rv = rv.substr(0, 3);\n else continue;\n } else if (rv.length < 3) {\n rv = rv + '2';\n continue;\n }\n let bitFix = 1;\n let upperFixed = rv;\n while (allPrefixes.has(upperFixed) && bitFix < 8) {\n upperFixed = applyToUpperBitFix(rv, bitFix);\n ++bitFix;\n }\n if (bitFix < 8) rv = upperFixed;\n else {\n let nextChar = (rv.charCodeAt(2) + 1) & 127;\n rv = rv.substr(0, 2) + String.fromCharCode(nextChar);\n // Here, in theory we could get an infinite loop if having 127*8 table names with identical 3 first consonants.\n }\n }\n return rv;\n}\n\nlet time = 0;\n/**\n *\n * @param prefix A unique 3-letter short-name of the table.\n * @param shardKey 3 last letters from another ID if colocation is requested. Verified on server on inserts - guarantees unique IDs across shards.\n * The shardKey part of the key represent the shardId where it was first created. An object with this\n * primary key can later on be moved to another shard without being altered. The reason for having\n * the origin shardKey as part of the key, is that the server will not need to check uniqueness constraint\n * across all shards on every insert. Updates / moves across shards are already controlled by the server\n * in the sense that the objects needs to be there already - we only need this part for inserts.\n * @returns\n */\nfunction generateKey(prefix: string, shardKey?: string) {\n const a = new Uint8Array(18);\n const timePart = new Uint8Array(a.buffer, 0, 6);\n const now = Date.now(); // Will fit into 6 bytes until year 10 895.\n if (time >= now) {\n // User is bulk-creating objects the same millisecond.\n // Increment the time part by one millisecond for each item.\n // If bulk-creating 1,000,000 rows client-side in 10 seconds,\n // the last time-stamp will be 990 seconds in future, which is no biggie at all.\n // The point is to create a nice order of the generated IDs instead of\n // using random ids.\n ++time;\n } else {\n time = now;\n }\n timePart[0] = time / 0x1_00_00_00_00_00; // Normal division (no bitwise operator) --> works with >= 32 bits.\n timePart[1] = time / 0x1_00_00_00_00;\n timePart[2] = time / 0x1_00_00_00;\n timePart[3] = time / 0x1_00_00;\n timePart[4] = time / 0x1_00;\n timePart[5] = time;\n const randomPart = new Uint8Array(a.buffer, 6);\n crypto.getRandomValues(randomPart);\n const id = new Uint8Array(a.buffer);\n return prefix + b64LexEncode(id) + (shardKey || '');\n}\n\nexport function createIdGenerationMiddleware(\n db: DexieCloudDB\n): Middleware<DBCore> {\n return {\n stack: 'dbcore',\n name: 'idGenerationMiddleware',\n level: 1,\n create: (core) => {\n return {\n ...core,\n table: (tableName) => {\n const table = core.table(tableName);\n\n function generateOrVerifyAtKeys(req: DBCoreAddRequest | DBCorePutRequest, idPrefix: string) {\n let valueClones: null | object[] = null;\n const keys = getEffectiveKeys(table.schema.primaryKey, req);\n keys.forEach((key, idx) => {\n if (key === undefined) {\n // Generate the key\n const colocatedId =\n req.values[idx].realmId || db.cloud.currentUserId;\n const shardKey = colocatedId.substr(colocatedId.length - 3);\n keys[idx] = generateKey(idPrefix, shardKey);\n if (!table.schema.primaryKey.outbound) {\n if (!valueClones) valueClones = req.values.slice();\n valueClones[idx] = Dexie.deepClone(valueClones[idx]);\n Dexie.setByKeyPath(\n valueClones[idx],\n table.schema.primaryKey.keyPath as any, // TODO: fix typings in dexie-constructor.d.ts!\n keys[idx]\n );\n }\n } else if (\n typeof key !== 'string' ||\n !key.startsWith(idPrefix)\n ) {\n // Key was specified by caller. Verify it complies with id prefix.\n throw new Dexie.ConstraintError(\n `The ID \"${key}\" is not valid for table \"${tableName}\". ` +\n `Primary '@' keys requires the key to be prefixed with \"${idPrefix}.\\n\"` +\n `If you want to generate IDs programmatically, remove '@' from the schema to get rid of this constraint. Dexie Cloud supports custom IDs as long as they are random and globally unique.`\n );\n }\n });\n return table.mutate({\n ...req,\n keys,\n values: valueClones || req.values\n });\n }\n\n return {\n ...table,\n mutate: (req) => {\n // @ts-ignore\n if (req.trans.disableChangeTracking) {\n // Disable ID policy checks and ID generation\n return table.mutate(req);\n }\n if (req.type === 'add' || req.type === 'put') {\n const cloudTableSchema = db.cloud.schema?.[tableName];\n if (!cloudTableSchema?.generatedGlobalId) {\n if (cloudTableSchema?.markedForSync) {\n // Just make sure primary key is of a supported type:\n const keys = getEffectiveKeys(table.schema.primaryKey, req);\n keys.forEach((key, idx) => {\n if (!isValidSyncableID(key)) {\n const type = Array.isArray(key) ? key.map(toStringTag).join(',') : toStringTag(key);\n throw new Dexie.ConstraintError(\n `Invalid primary key type ${type} for table ${tableName}. Tables marked for sync has primary keys of type string or Array of string (and optional numbers)`\n );\n }\n });\n }\n } else {\n if (db.cloud.options?.databaseUrl && !db.initiallySynced) {\n // A database URL is configured but no initial sync has been performed.\n const keys = getEffectiveKeys(table.schema.primaryKey, req);\n // Check if the operation would yield any INSERT. If so, complain! We never want wrong ID prefixes stored.\n return table.getMany({keys, trans: req.trans, cache: \"immutable\"}).then(results => {\n if (results.length < keys.length) {\n // At least one of the given objects would be created. Complain since\n // the generated ID would be based on a locally computed ID prefix only - we wouldn't\n // know if the server would give the same ID prefix until an initial sync has been\n // performed.\n throw new Error(`Unable to create new objects without an initial sync having been performed.`);\n }\n return table.mutate(req);\n });\n }\n return generateOrVerifyAtKeys(req, cloudTableSchema.idPrefix!);\n }\n }\n return table.mutate(req);\n }\n };\n }\n };\n }\n };\n}\n","import { DBCore, DBCoreTransaction, Middleware } from 'dexie';\nimport { DexieCloudDB } from '../db/DexieCloudDB';\nimport { TXExpandos } from '../types/TXExpandos';\n\nexport function createImplicitPropSetterMiddleware(\n db: DexieCloudDB\n): Middleware<DBCore> {\n return {\n stack: 'dbcore',\n name: 'implicitPropSetterMiddleware',\n level: 1,\n create: (core) => {\n return {\n ...core,\n table: (tableName) => {\n const table = core.table(tableName);\n return {\n ...table,\n mutate: (req) => {\n const trans = req.trans as DBCoreTransaction & TXExpandos;\n if (\n db.cloud.schema?.[tableName]?.markedForSync &&\n trans.currentUser?.isLoggedIn\n ) {\n if (req.type === 'add' || req.type === 'put') {\n // If user is logged in, make sure \"owner\" and \"realmId\" props are set properly.\n // If not logged in, this will be set upon syncification of the tables (next sync after login)\n for (const obj of req.values) {\n if (!('owner' in obj)) {\n obj.owner = trans.currentUser.userId;\n }\n if (!('realmId' in obj)) {\n obj.realmId = trans.currentUser.userId;\n }\n }\n }\n }\n return table.mutate(req);\n }\n };\n }\n };\n }\n };\n}\n","export function randomString(bytes: number) {\n const buf = new Uint8Array(bytes);\n crypto.getRandomValues(buf);\n return btoa(String.fromCharCode.apply(null, buf));\n}","\nexport function allSettled(possiblePromises: any[]) {\n return new Promise(resolve => {\n if (possiblePromises.length === 0) resolve([]);\n let remaining = possiblePromises.length;\n const results = new Array(remaining);\n possiblePromises.forEach((p, i) => Promise.resolve(p).then(\n value => results[i] = {status: \"fulfilled\", value},\n reason => results[i] = {status: \"rejected\", reason})\n .then(()=>--remaining || resolve(results)));\n });\n}\n","import { DBCoreTable, DBCoreTransaction } from \"dexie\";\nimport { allSettled } from \"../helpers/allSettled\";\n\nlet counter = 0;\n\nexport function guardedTable(table: DBCoreTable) {\n const prop = \"$lock\"+ (++counter);\n return {\n ...table,\n count: readLock(table.count, prop),\n get: readLock(table.get, prop),\n getMany: readLock(table.getMany, prop),\n openCursor: readLock(table.openCursor, prop),\n query: readLock(table.query, prop),\n mutate: writeLock(table.mutate, prop),\n };\n}\n\nfunction readLock<TReq extends { trans: DBCoreTransaction }, TRes>(\n fn: (req: TReq) => Promise<TRes>,\n prop: string\n): (req: TReq) => Promise<TRes> {\n return function readLocker(req): Promise<TRes> {\n const {\n readers,\n writers,\n }: { writers: Promise<any>[]; readers: Promise<any>[] } =\n req.trans[prop] || (req.trans[prop] = { writers: [], readers: [] });\n const numWriters = writers.length;\n const promise = (numWriters > 0\n ? writers[numWriters - 1].then(() => fn(req), () => fn(req))\n : fn(req)\n ).finally(() => readers.splice(readers.indexOf(promise)));\n readers.push(promise);\n return promise;\n };\n}\n\nfunction writeLock<TReq extends { trans: DBCoreTransaction }, TRes>(\n fn: (req: TReq) => Promise<TRes>,\n prop: string\n): (req: TReq) => Promise<TRes> {\n return function writeLocker(req): Promise<TRes> {\n const {\n readers,\n writers,\n }: { writers: Promise<any>[]; readers: Promise<any>[] } =\n req.trans[prop] || (req.trans[prop] = { writers: [], readers: [] });\n let promise = (writers.length > 0\n ? writers[writers.length - 1].then(() => fn(req), () => fn(req))\n : readers.length > 0\n ? allSettled(readers).then(() => fn(req))\n : fn(req)\n ).finally(() => writers.shift());\n writers.push(promise);\n return promise;\n };\n}\n","import { DBCoreTransaction } from 'dexie';\nimport { BehaviorSubject } from 'rxjs';\nimport { TXExpandos } from '../types/TXExpandos';\n\nexport const outstandingTransactions = new BehaviorSubject<Set<DBCoreTransaction & IDBTransaction & TXExpandos>>(new Set());\n","import {\n DBCore,\n DBCoreAddRequest,\n DBCoreDeleteRequest,\n DBCoreMutateResponse,\n DBCorePutRequest,\n DBCoreTable,\n DBCoreTransaction,\n Middleware\n} from 'dexie';\nimport { DBOperation } from 'dexie-cloud-common';\nimport { BehaviorSubject } from 'rxjs';\nimport { DexieCloudDB } from '../db/DexieCloudDB';\nimport { UserLogin } from '../db/entities/UserLogin';\nimport { getMutationTable } from '../helpers/getMutationTable';\nimport { randomString } from '../helpers/randomString';\nimport { throwVersionIncrementNeeded } from '../helpers/throwVersionIncrementNeeded';\nimport { guardedTable } from '../middleware-helpers/guardedTable';\nimport { registerSyncEvent } from '../sync/registerSyncEvent';\nimport { TXExpandos } from '../types/TXExpandos';\nimport { outstandingTransactions } from './outstandingTransaction';\n\nexport interface MutationTrackingMiddlewareArgs {\n currentUserObservable: BehaviorSubject<UserLogin>;\n db: DexieCloudDB;\n}\n\n/** Tracks all mutations in the same transaction as the mutations -\n * so it is guaranteed that no mutation goes untracked - and if transaction\n * aborts, the mutations won't be tracked.\n *\n * The sync job will use the tracked mutations as the source of truth when pushing\n * changes to server and cleanup the tracked mutations once the server has\n * ackowledged that it got them.\n */\nexport function createMutationTrackingMiddleware({\n currentUserObservable,\n db\n}: MutationTrackingMiddlewareArgs): Middleware<DBCore> {\n return {\n stack: 'dbcore',\n name: 'MutationTrackingMiddleware',\n level: 1,\n create: (core) => {\n const ordinaryTables = core.schema.tables.filter(\n (t) => !/^\\$/.test(t.name)\n );\n let mutTableMap: Map<string, DBCoreTable>;\n try {\n mutTableMap = new Map(\n ordinaryTables.map((tbl) => [\n tbl.name,\n core.table(`$${tbl.name}_mutations`)\n ])\n );\n } catch {\n throwVersionIncrementNeeded();\n }\n\n return {\n ...core,\n transaction: (tables, mode) => {\n let tx: DBCoreTransaction & IDBTransaction & TXExpandos;\n if (mode === 'readwrite') {\n const mutationTables = tables\n .filter((tbl) => db.cloud.schema?.[tbl]?.markedForSync)\n .map((tbl) => getMutationTable(tbl));\n tx = core.transaction(\n [...tables, ...mutationTables],\n mode\n ) as DBCoreTransaction & IDBTransaction & TXExpandos;\n } else {\n tx = core.transaction(tables, mode) as DBCoreTransaction &\n IDBTransaction &\n TXExpandos;\n }\n\n if (mode === 'readwrite') {\n // Give each transaction a globally unique id.\n tx.txid = randomString(16);\n // Introduce the concept of current user that lasts through the entire transaction.\n // This is important because the tracked mutations must be connected to the user.\n tx.currentUser = currentUserObservable.value;\n outstandingTransactions.value.add(tx);\n outstandingTransactions.next(outstandingTransactions.value);\n const removeTransaction = () => {\n tx.removeEventListener('complete', txComplete);\n tx.removeEventListener('error', removeTransaction);\n tx.removeEventListener('abort', removeTransaction);\n outstandingTransactions.value.delete(tx);\n outstandingTransactions.next(outstandingTransactions.value);\n };\n const txComplete = () => {\n if (tx.mutationsAdded && db.cloud.options?.databaseUrl) {\n if (db.cloud.usingServiceWorker) {\n console.debug('registering sync event');\n registerSyncEvent(db, \"push\");\n } else {\n db.localSyncEvent.next({purpose: \"push\"});\n }\n }\n removeTransaction();\n };\n tx.addEventListener('complete', txComplete);\n tx.addEventListener('error', removeTransaction);\n tx.addEventListener('abort', removeTransaction);\n }\n return tx;\n },\n table: (tableName) => {\n const table = core.table(tableName);\n if (/^\\$/.test(tableName)) {\n if (tableName.endsWith('_mutations')) {\n // In case application code adds items to ..._mutations tables,\n // make sure to set the mutationsAdded flag on transaction.\n // This is also done in mutateAndLog() as that function talks to a\n // lower level DBCore and wouldn't be catched by this code.\n return {\n ...table,\n mutate: (req) => {\n if (req.type === 'add' || req.type === 'put') {\n (\n req.trans as DBCoreTransaction & TXExpandos\n ).mutationsAdded = true;\n }\n return table.mutate(req);\n }\n };\n } else if (tableName === '$logins') {\n return {\n ...table,\n mutate: (req) => {\n console.debug('Mutating $logins table', req);\n return table\n .mutate(req)\n .then((res) => {\n console.debug('Mutating $logins');\n (\n req.trans as DBCoreTransaction & TXExpandos\n ).mutationsAdded = true;\n console.debug('$logins mutated');\n return res;\n })\n .catch((err) => {\n console.debug('Failed mutation $logins', err);\n return Promise.reject(err);\n });\n }\n };\n } else {\n return table;\n }\n }\n const { schema } = table;\n const mutsTable = mutTableMap.get(tableName)!;\n return guardedTable({\n ...table,\n mutate: (req) => {\n const trans = req.trans as DBCoreTransaction & TXExpandos;\n if (!trans.txid) return table.mutate(req); // Upgrade transactions not guarded by us.\n if (trans.disableChangeTracking) return table.mutate(req);\n if (!trans.currentUser?.isLoggedIn) {\n // Unauthorized user should not log mutations.\n // Instead, after login all local data should be logged at once.\n return table.mutate(req);\n }\n\n return req.type === 'deleteRange'\n ? table\n // Query the actual keys (needed for server sending correct rollback to us)\n .query({\n query: { range: req.range, index: schema.primaryKey },\n trans: req.trans,\n values: false\n })\n // Do a delete request instead, but keep the criteria info for the server to execute\n .then((res) => {\n return mutateAndLog({\n type: 'delete',\n keys: res.result,\n trans: req.trans,\n criteria: { index: null, range: req.range }\n });\n })\n : mutateAndLog(req);\n }\n });\n\n function mutateAndLog(\n req: DBCoreDeleteRequest | DBCoreAddRequest | DBCorePutRequest\n ): Promise<DBCoreMutateResponse> {\n const trans = req.trans as DBCoreTransaction & TXExpandos;\n trans.mutationsAdded = true;\n const {\n txid,\n currentUser: { userId }\n } = trans;\n const { type } = req;\n\n return table.mutate(req).then((res) => {\n const { numFailures: hasFailures, failures } = res;\n let keys = type === 'delete' ? req.keys! : res.results!;\n let values = 'values' in req ? req.values : [];\n let changeSpecs = 'changeSpecs' in req ? req.changeSpecs! : [];\n if (hasFailures) {\n keys = keys.filter((_, idx) => !failures[idx]);\n values = values.filter((_, idx) => !failures[idx]);\n changeSpecs = changeSpecs.filter((_, idx) => !failures[idx]);\n }\n const ts = Date.now();\n\n const mut: DBOperation =\n req.type === 'delete'\n ? {\n type: 'delete',\n ts,\n keys,\n criteria: req.criteria,\n txid,\n userId\n }\n : req.type === 'add'\n ? {\n type: 'insert',\n ts,\n keys,\n txid,\n userId,\n values\n }\n : req.criteria && req.changeSpec\n ? {\n // Common changeSpec for all keys\n type: 'modify',\n ts,\n keys,\n criteria: req.criteria,\n changeSpec: req.changeSpec,\n txid,\n userId\n }\n : req.changeSpecs\n ? {\n // One changeSpec per key\n type: 'update',\n ts,\n keys,\n changeSpecs,\n txid,\n userId\n }\n : {\n type: 'upsert',\n ts,\n keys,\n values,\n txid,\n userId\n };\n return keys.length > 0 || ('criteria' in req && req.criteria)\n ? mutsTable\n .mutate({ type: 'add', trans, values: [mut] }) // Log entry\n .then(() => res) // Return original response\n : res;\n });\n }\n }\n };\n }\n };\n}\n","import Dexie, { DbSchema } from 'dexie';\nimport { DEXIE_CLOUD_SCHEMA } from './db/DexieCloudDB';\nimport { generateTablePrefix } from './middlewares/createIdGenerationMiddleware';\n\nexport function overrideParseStoresSpec(origFunc: Function, dexie: Dexie) {\n return function(stores: {[tableName: string]: string}, dbSchema: DbSchema) {\n const storesClone = {\n ...DEXIE_CLOUD_SCHEMA,\n ...stores,\n };\n const cloudSchema = dexie.cloud.schema || (dexie.cloud.schema = {});\n const allPrefixes = new Set<string>();\n Object.keys(storesClone).forEach(tableName => {\n const schemaSrc = storesClone[tableName];\n const cloudTableSchema = cloudSchema[tableName] || (cloudSchema[tableName] = {});\n if (schemaSrc != null) {\n if (/^\\@/.test(schemaSrc)) {\n storesClone[tableName] = storesClone[tableName].substr(1);\n cloudTableSchema.generatedGlobalId = true;\n cloudTableSchema.idPrefix = generateTablePrefix(tableName, allPrefixes);\n allPrefixes.add(cloudTableSchema.idPrefix);\n }\n if (!/^\\$/.test(tableName)) {\n storesClone[`$${tableName}_mutations`] = '++rev';\n cloudTableSchema.markedForSync = true;\n }\n if (cloudTableSchema.deleted) {\n cloudTableSchema.deleted = false;\n }\n } else {\n cloudTableSchema.deleted = true;\n cloudTableSchema.markedForSync = false;\n storesClone[`$${tableName}_mutations`] = null;\n }\n });\n const rv = origFunc.call(this, storesClone, dbSchema);\n return rv;\n }\n}\n","export const SECONDS = 1000;\nexport const MINUTES = 60 * SECONDS;\nexport const HOURS = 60 * MINUTES;\nexport const DAYS = 24 * HOURS;\nexport const WEEKS = 7 * DAYS;\n","import { randomString } from \"../helpers/randomString\";\n\nexport const myId = randomString(16);\n","import { liveQuery, Table } from 'dexie';\nimport { MINUTES, SECONDS } from '../helpers/date-constants';\nimport { DexieCloudDB } from '../db/DexieCloudDB';\nimport { GuardedJob } from '../db/entities/GuardedJob';\nimport { myId } from './myId';\nimport { from } from 'rxjs';\nimport { filter, timeout } from 'rxjs/operators';\n\nconst GUARDED_JOB_HEARTBEAT = 1 * SECONDS;\nconst GUARDED_JOB_TIMEOUT = 1 * MINUTES;\n\nexport async function performGuardedJob(\n db: DexieCloudDB,\n jobName: string,\n jobsTableName: string,\n job: () => Promise<any>,\n { awaitRemoteJob }: { awaitRemoteJob?: boolean } = {}\n): Promise<void> {\n // Start working.\n //\n // Check if someone else is working on this already.\n //\n const jobsTable = db.table(jobsTableName) as Table<GuardedJob, string>;\n\n async function aquireLock() {\n const gotTheLock = await db.transaction('rw!', jobsTableName, async () => {\n const currentWork = await jobsTable.get(jobName);\n if (!currentWork) {\n // No one else is working. Let's record that we are.\n await jobsTable.add(\n {\n nodeId: myId,\n started: new Date(),\n heartbeat: new Date()\n },\n jobName\n );\n return true;\n } else if (\n currentWork.heartbeat.getTime() <\n Date.now() - GUARDED_JOB_TIMEOUT\n ) {\n console.warn(\n `Latest ${jobName} worker seem to have died.\\n`,\n `The dead job started:`,\n currentWork.started,\n `\\n`,\n `Last heart beat was:`,\n currentWork.heartbeat,\n '\\n',\n `We're now taking over!`\n );\n // Now, take over!\n await jobsTable.put(\n {\n nodeId: myId,\n started: new Date(),\n heartbeat: new Date()\n },\n jobName\n );\n return true;\n }\n return false;\n });\n\n if (gotTheLock) return true;\n\n // Someone else took the job.\n if (awaitRemoteJob) {\n try {\n const jobDoneObservable = from(\n liveQuery(() => jobsTable.get(jobName))\n ).pipe(\n timeout(GUARDED_JOB_TIMEOUT),\n filter((job) => !job)\n ); // Wait til job is not there anymore.\n await jobDoneObservable.toPromise();\n return false;\n } catch (err) {\n if (err.name !== 'TimeoutError') {\n throw err;\n }\n // Timeout stopped us! Try aquire the lock now.\n // It will likely succeed this time unless\n // another client took it.\n return await aquireLock();\n }\n }\n return false;\n }\n\n if (await aquireLock()) {\n // We own the lock entry and can do our job undisturbed.\n // We're not within a transaction, but these type of locks\n // spans over transactions.\n\n // Start our heart beat during the job.\n // Use setInterval to make sure we are updating heartbeat even during long-lived fetch calls.\n const heartbeat = setInterval(() => {\n jobsTable.update(\n jobName,\n (job: GuardedJob) => job.nodeId === myId && (job.heartbeat = new Date())\n );\n }, GUARDED_JOB_HEARTBEAT);\n\n try {\n return await job();\n } finally {\n // Stop heartbeat\n clearInterval(heartbeat);\n // Remove the persisted job state:\n await db.transaction('rw!', jobsTableName, async () => {\n const currentWork = await jobsTable.get(jobName);\n if (currentWork && currentWork.nodeId === myId) {\n jobsTable.delete(jobName);\n }\n });\n }\n }\n}\n","import { DexieCloudSchema } from 'dexie-cloud-common';\nimport { DexieCloudDB } from './db/DexieCloudDB';\nimport { DexieCloudOptions } from './DexieCloudOptions';\nimport { performGuardedJob } from './sync/performGuardedJob';\nimport { sync } from './sync/sync';\n\nexport async function performInitialSync(\n db: DexieCloudDB,\n cloudOptions: DexieCloudOptions,\n cloudSchema: DexieCloudSchema\n) {\n console.debug(\"Performing initial sync\");\n await performGuardedJob(\n db,\n 'initialSync',\n '$jobs',\n async () => {\n // Even though caller has already checked it,\n // Do check again (now within a transaction) that we really do not have a sync state:\n const syncState = await db.getPersistedSyncState();\n if (!syncState?.initiallySynced) {\n await sync(db, cloudOptions, cloudSchema, {isInitialSync: true});\n }\n },\n { awaitRemoteJob: true } // Don't return until the job is done!\n );\n console.debug(\"Done initial sync\");\n}\n","import { BehaviorSubject, fromEvent, merge, of } from 'rxjs';\nimport {\n debounceTime,\n delay,\n distinctUntilChanged,\n filter,\n map,\n skip,\n startWith,\n switchMap,\n tap,\n} from 'rxjs/operators';\n\nconst USER_INACTIVITY_TIMEOUT = 300_000; // 300_000;\nconst ACTIVE_WAIT_TIME = 0; // For now, it's nicer to react instantly on user activity\nconst INACTIVE_WAIT_TIME = 20_000;\n\n// This observable will be emitted to later down....\nexport const userIsActive = new BehaviorSubject<boolean>(true);\n\n// A refined version that waits before changing state:\n// * Wait another INACTIVE_WAIT_TIME before accepting that the user is inactive.\n// Reason 1: Spare resources - no need to setup the entire websocket flow when\n// switching tabs back and forth.\n// Reason 2: Less flickering for the end user when switching tabs back and forth.\n// * Wait another ACTIVE_WAIT_TIME before accepting that the user is active.\n// Possible reason to have a value here: Sparing resources if users often temporary click the tab\n// for just a short time.\nexport const userIsReallyActive = new BehaviorSubject<boolean>(true);\nuserIsActive\n .pipe(\n switchMap((isActive) =>\n isActive\n ? ACTIVE_WAIT_TIME\n ? of(true).pipe(delay(ACTIVE_WAIT_TIME))\n : of(true)\n : of(false).pipe(delay(INACTIVE_WAIT_TIME))\n ),\n distinctUntilChanged()\n )\n .subscribe(userIsReallyActive);\n\n//\n// First create some corner-stone observables to build the flow on\n//\n\n// document.onvisibilitychange:\nexport const visibilityStateIsChanged =\n typeof document !== 'undefined'\n ? fromEvent(document, 'visibilitychange')\n : of({});\n\n// document.onvisibilitychange makes document hidden:\nexport const documentBecomesHidden = visibilityStateIsChanged.pipe(\n filter(() => document.visibilityState === 'hidden')\n);\n\n// document.onvisibilitychange makes document visible\nexport const documentBecomesVisible = visibilityStateIsChanged.pipe(\n filter(() => document.visibilityState === 'visible')\n);\n\n// Any of various user-activity-related events happen:\nexport const userDoesSomething =\n typeof window !== 'undefined'\n ? merge(\n documentBecomesVisible,\n fromEvent(window, 'mousemove'),\n fromEvent(window, 'keydown'),\n fromEvent(window, 'wheel'),\n fromEvent(window, 'touchmove')\n )\n : of({});\n\nif (typeof document !== 'undefined') {\n //\n // Now, create a final observable and start subscribing to it in order\n // to make it emit values to userIsActive BehaviourSubject (which is the\n // most important global hot observable we have here)\n //\n // Live test: https://jsitor.com/LboCDHgbn\n //\n merge(\n of(true), // Make sure something is always emitted from start\n documentBecomesHidden, // so that we can eagerly emit false!\n userDoesSomething\n )\n .pipe(\n // No matter event source, compute whether user is visible using visibilityState:\n map(() => document.visibilityState === 'visible'),\n // Make sure to emit it\n tap((isActive) => {\n if (userIsActive.value !== isActive) {\n // Emit new value unless it already has that value\n userIsActive.next(isActive);\n }\n }),\n // Now, if true was emitted, make sure to set a timeout to emit false\n // unless new user activity things happen (in that case, the timeout will be cancelled!)\n switchMap((isActive) =>\n isActive\n ? of(0).pipe(\n delay(USER_INACTIVITY_TIMEOUT - INACTIVE_WAIT_TIME),\n tap(() => userIsActive.next(false))\n )\n : of(0)\n )\n )\n .subscribe(() => {}); // Unless we subscribe nothing will be propagated to userIsActive observable\n}\n","export class TokenExpiredError extends Error {\n name = \"TokenExpiredError\";\n}\n","import { DBOperationsSet } from 'dexie-cloud-common';\nimport { BehaviorSubject, Observable, Subscriber, Subscription } from 'rxjs';\nimport { TokenExpiredError } from './authentication/TokenExpiredError';\nimport { DXCWebSocketStatus } from './DXCWebSocketStatus';\nimport { TSON } from './TSON';\n\nconst SERVER_PING_TIMEOUT = 20000;\nconst CLIENT_PING_INTERVAL = 30000;\nconst FAIL_RETRY_WAIT_TIME = 60000;\n\nexport type WSClientToServerMsg = ReadyForChangesMessage;\nexport interface ReadyForChangesMessage {\n type: 'ready';\n rev: string;\n}\n\nexport type WSConnectionMsg =\n | RevisionChangedMessage\n | RealmAddedMessage\n | RealmRemovedMessage\n | RealmsChangedMessage\n | ChangesFromServerMessage\n | TokenExpiredMessage;\ninterface PingMessage {\n type: 'ping';\n}\n\ninterface PongMessage {\n type: 'pong';\n}\n\ninterface ErrorMessage {\n type: 'error';\n error: string;\n}\n\nexport interface ChangesFromServerMessage {\n type: 'changes';\n baseRev: string;\n realmSetHash: string;\n newRev: string;\n changes: DBOperationsSet;\n}\nexport interface RevisionChangedMessage {\n type: 'rev';\n rev: string;\n}\n\nexport interface RealmAddedMessage {\n type: 'realm-added';\n realm: string;\n}\n\nexport interface RealmRemovedMessage {\n type: 'realm-removed';\n realm: string;\n}\n\nexport interface RealmsChangedMessage {\n type: 'realms-changed';\n realmsHash: string;\n}\nexport interface TokenExpiredMessage {\n type: 'token-expired';\n}\n\nexport class WSObservable extends Observable<WSConnectionMsg> {\n constructor(\n databaseUrl: string,\n rev: string,\n realmSetHash: string,\n clientIdentity: string,\n messageProducer: Observable<WSClientToServerMsg>,\n webSocketStatus: BehaviorSubject<DXCWebSocketStatus>,\n token?: string,\n tokenExpiration?: Date,\n ) {\n super(\n (subscriber) =>\n new WSConnection(\n databaseUrl,\n rev,\n realmSetHash,\n clientIdentity,\n token,\n tokenExpiration,\n subscriber,\n messageProducer,\n webSocketStatus\n )\n );\n }\n}\n\nlet counter = 0;\n\nexport class WSConnection extends Subscription {\n ws: WebSocket | null;\n lastServerActivity: Date;\n lastUserActivity: Date;\n lastPing: Date;\n databaseUrl: string;\n rev: string;\n realmSetHash: string;\n clientIdentity: string;\n token: string | undefined;\n tokenExpiration: Date | undefined;\n subscriber: Subscriber<WSConnectionMsg>;\n pauseUntil?: Date;\n messageProducer: Observable<WSClientToServerMsg>;\n webSocketStatus: BehaviorSubject<DXCWebSocketStatus>;\n id = ++counter;\n\n private pinger: any;\n private messageProducerSubscription: null | Subscription;\n\n constructor(\n databaseUrl: string,\n rev: string,\n realmSetHash: string,\n clientIdentity: string,\n token: string | undefined,\n tokenExpiration: Date | undefined,\n subscriber: Subscriber<WSConnectionMsg>,\n messageProducer: Observable<WSClientToServerMsg>,\n webSocketStatus: BehaviorSubject<DXCWebSocketStatus>\n ) {\n super(() => this.teardown());\n console.debug(\n 'New WebSocket Connection',\n this.id,\n token ? 'authorized' : 'unauthorized'\n );\n this.databaseUrl = databaseUrl;\n this.rev = rev;\n this.realmSetHash = realmSetHash;\n this.clientIdentity = clientIdentity;\n this.token = token;\n this.tokenExpiration = tokenExpiration;\n this.subscriber = subscriber;\n this.lastUserActivity = new Date();\n this.messageProducer = messageProducer;\n this.messageProducerSubscription = null;\n this.webSocketStatus = webSocketStatus;\n this.connect();\n }\n\n private teardown() {\n console.debug('Teardown WebSocket Connection', this.id);\n this.disconnect();\n }\n\n private disconnect() {\n this.webSocketStatus.next(\"disconnected\");\n if (this.pinger) {\n clearInterval(this.pinger);\n this.pinger = null;\n }\n if (this.ws) {\n try {\n this.ws.close();\n } catch {}\n }\n this.ws = null;\n if (this.messageProducerSubscription) {\n this.messageProducerSubscription.unsubscribe();\n this.messageProducerSubscription = null;\n }\n }\n\n reconnect() {\n this.disconnect();\n this.connect();\n }\n\n async connect() {\n this.webSocketStatus.next(\"connecting\");\n this.lastServerActivity = new Date();\n if (this.pauseUntil && this.pauseUntil > new Date()) {\n console.debug('WS not reconnecting just yet', {\n id: this.id,\n pauseUntil: this.pauseUntil,\n });\n return;\n }\n if (this.ws) {\n throw new Error(`Called connect() when a connection is already open`);\n }\n if (!this.databaseUrl)\n throw new Error(`Cannot connect without a database URL`);\n if (this.closed) {\n return;\n }\n if (this.tokenExpiration && this.tokenExpiration < new Date()) {\n this.subscriber.error(new TokenExpiredError()); // Will be handled in connectWebSocket.ts.\n return;\n }\n this.pinger = setInterval(async () => {\n if (this.closed) {\n console.debug('pinger check', this.id, 'CLOSED.');\n this.teardown();\n return;\n }\n if (this.ws) {\n try {\n this.ws.send(JSON.stringify({ type: 'ping' } as PingMessage));\n setTimeout(() => {\n console.debug(\n 'pinger setTimeout',\n this.id,\n this.pinger ? `alive` : 'dead'\n );\n if (!this.pinger) return;\n if (this.closed) {\n console.debug(\n 'pinger setTimeout',\n this.id,\n 'subscription is closed'\n );\n this.teardown();\n return;\n }\n if (\n this.lastServerActivity <\n new Date(Date.now() - SERVER_PING_TIMEOUT)\n ) {\n // Server inactive. Reconnect if user is active.\n console.debug('pinger: server is inactive');\n console.debug('pinger reconnecting');\n this.reconnect();\n } else {\n console.debug('pinger: server still active');\n }\n }, SERVER_PING_TIMEOUT);\n } catch {\n console.debug('pinger catch error', this.id, 'reconnecting');\n this.reconnect();\n }\n } else {\n console.debug('pinger', this.id, 'reconnecting');\n this.reconnect();\n }\n }, CLIENT_PING_INTERVAL);\n\n // The following vars are needed because we must know which callback to ack when server sends it's ack to us.\n const wsUrl = new URL(this.databaseUrl);\n wsUrl.protocol = wsUrl.protocol === 'http:' ? 'ws' : 'wss';\n const searchParams = new URLSearchParams();\n if (this.subscriber.closed) return;\n searchParams.set('v', \"2\");\n searchParams.set('rev', this.rev);\n searchParams.set('realmsHash', this.realmSetHash);\n searchParams.set('clientId', this.clientIdentity);\n if (this.token) {\n searchParams.set('token', this.token);\n }\n\n // Connect the WebSocket to given url:\n console.debug('dexie-cloud WebSocket create');\n const ws = (this.ws = new WebSocket(`${wsUrl}/changes?${searchParams}`));\n //ws.binaryType = \"arraybuffer\"; // For future when subscribing to actual changes.\n\n ws.onclose = (event: Event) => {\n if (!this.pinger) return;\n console.debug('dexie-cloud WebSocket onclosed', this.id);\n this.reconnect();\n };\n\n ws.onmessage = (event: MessageEvent) => {\n if (!this.pinger) return;\n console.debug('dexie-cloud WebSocket onmessage', event.data);\n\n this.lastServerActivity = new Date();\n try {\n const msg = TSON.parse(event.data) as\n | WSConnectionMsg\n | PongMessage\n | ErrorMessage;\n if (msg.type === 'error') {\n throw new Error(`Error message from dexie-cloud: ${msg.error}`);\n }\n if (msg.type === 'rev') {\n this.rev = msg.rev; // No meaning but seems reasonable.\n }\n if (msg.type !== 'pong') {\n this.subscriber.next(msg);\n }\n } catch (e) {\n this.subscriber.error(e);\n }\n };\n\n try {\n await new Promise((resolve, reject) => {\n ws.onopen = (event) => {\n console.debug('dexie-cloud WebSocket onopen');\n resolve(null);\n };\n ws.onerror = (event: ErrorEvent) => {\n const error = event.error || new Error('WebSocket Error');\n this.disconnect();\n this.subscriber.error(error);\n this.webSocketStatus.next(\"error\");\n reject(error);\n };\n });\n this.messageProducerSubscription = this.messageProducer.subscribe(msg => {\n if (!this.closed) {\n if (msg.type === 'ready' && this.webSocketStatus.value !== 'connected') {\n this.webSocketStatus.next(\"connected\");\n }\n this.ws?.send(TSON.stringify(msg));\n }\n });\n } catch (error) {\n this.pauseUntil = new Date(Date.now() + FAIL_RETRY_WAIT_TIME);\n }\n }\n}\n","import { BehaviorSubject, from, Observable, of, throwError } from 'rxjs';\nimport {\n catchError,\n debounceTime,\n delay,\n distinctUntilChanged,\n filter,\n map,\n switchMap,\n take,\n tap,\n} from 'rxjs/operators';\nimport { refreshAccessToken } from '../authentication/authenticate';\nimport { DexieCloudDB } from '../db/DexieCloudDB';\nimport { PersistedSyncState } from '../db/entities/PersistedSyncState';\nimport { computeRealmSetHash } from '../helpers/computeRealmSetHash';\nimport {\n userDoesSomething,\n userIsActive,\n userIsReallyActive,\n} from '../userIsActive';\nimport {\n ReadyForChangesMessage,\n WSConnectionMsg,\n WSObservable,\n} from '../WSObservable';\n\nfunction sleep(ms: number) {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n\nasync function waitAndReconnectWhenUserDoesSomething(error: Error) {\n console.error(\n `WebSocket observable: error but revive when user does some active thing...`,\n error\n );\n // Sleep some seconds...\n await sleep(3000);\n // Wait til user does something (move mouse, tap, scroll, click etc)\n console.debug('waiting for someone to do something');\n await userDoesSomething.pipe(take(1)).toPromise();\n console.debug('someone did something!');\n}\n\nexport function connectWebSocket(db: DexieCloudDB) {\n if (!db.cloud.options?.databaseUrl) {\n throw new Error(`No database URL to connect WebSocket to`);\n }\n\n const messageProducer = db.messageConsumer.readyToServe.pipe(\n filter((isReady) => isReady), // When consumer is ready for new messages, produce such a message to inform server about it\n switchMap(() => db.getPersistedSyncState()), // We need the info on which server revision we are at:\n filter((syncState) => syncState && syncState.serverRevision), // We wont send anything to server before inital sync has taken place\n map<PersistedSyncState, ReadyForChangesMessage>((syncState) => ({\n // Produce the message to trigger server to send us new messages to consume:\n type: 'ready',\n rev: syncState.serverRevision,\n }))\n );\n\n function createObservable(): Observable<WSConnectionMsg | null> {\n return db.cloud.persistedSyncState.pipe(\n filter(syncState => syncState?.serverRevision),// Don't connect before there's no initial sync performed.\n take(1), // Don't continue waking up whenever syncState change\n switchMap((syncState)=> db.cloud.currentUser.pipe(map(userLogin => [userLogin, syncState] as const))),\n switchMap(([userLogin, syncState]) =>\n userIsReallyActive.pipe(\n map((isActive) => ([isActive ? userLogin : null, syncState] as const))\n )\n ),\n switchMap(async ([userLogin, syncState]) => [userLogin, await computeRealmSetHash(syncState!)] as const),\n switchMap(([userLogin, realmSetHash]) =>\n // Let server end query changes from last entry of same client-ID and forward.\n // If no new entries, server won't bother the client. If new entries, server sends only those\n // and the baseRev of the last from same client-ID.\n userLogin\n ? new WSObservable(\n db.cloud.options!.databaseUrl,\n db.cloud.persistedSyncState!.value!.serverRevision,\n realmSetHash,\n db.cloud.persistedSyncState!.value!.clientIdentity,\n messageProducer,\n db.cloud.webSocketStatus,\n userLogin.accessToken,\n userLogin.accessTokenExpiration\n )\n : from([] as WSConnectionMsg[])\n ),\n catchError((error) => {\n if (error?.name === 'TokenExpiredError') {\n console.debug(\n 'WebSocket observable: Token expired. Refreshing token...'\n );\n return of(true).pipe(\n switchMap(async () => {\n // Refresh access token\n const user = await db.getCurrentUser();\n const refreshedLogin = await refreshAccessToken(\n db.cloud.options!.databaseUrl,\n user\n );\n // Persist updated access token\n await db.table('$logins').update(user.userId, {\n accessToken: refreshedLogin.accessToken,\n accessTokenExpiration: refreshedLogin.accessTokenExpiration,\n });\n }),\n switchMap(() => createObservable())\n );\n } else {\n return throwError(error);\n }\n }),\n catchError((error) =>\n from(waitAndReconnectWhenUserDoesSomething(error)).pipe(\n switchMap(() => createObservable())\n )\n )\n );\n }\n\n return createObservable().subscribe(\n (msg) => {\n if (msg) {\n console.debug('WS got message', msg);\n db.messageConsumer.enqueue(msg);\n }\n },\n (error) => {\n console.error('Oops! The main observable errored!', error);\n },\n () => {\n console.error('Oops! The main observable completed!');\n }\n );\n}\n","import { DexieCloudDB } from \"../db/DexieCloudDB\";\nimport { sync } from \"./sync\";\n\nexport async function isSyncNeeded(db: DexieCloudDB) {\n return db.cloud.options?.databaseUrl && db.cloud.schema\n ? await sync(db, db.cloud.options, db.cloud.schema, {justCheckIfNeeded: true})\n : false;\n}\n","import { IS_SERVICE_WORKER } from '../helpers/IS_SERVICE_WORKER';\nimport { performGuardedJob } from './performGuardedJob';\nimport { DexieCloudDB } from '../db/DexieCloudDB';\nimport { sync, CURRENT_SYNC_WORKER, SyncOptions } from './sync';\nimport { DexieCloudOptions } from '../DexieCloudOptions';\nimport { DexieCloudSchema } from 'dexie-cloud-common';\n\nconst ongoingSyncs = new WeakMap<\n DexieCloudDB,\n { promise: Promise<void>; pull: boolean }\n>();\n\nexport function syncIfPossible(\n db: DexieCloudDB,\n cloudOptions: DexieCloudOptions,\n cloudSchema: DexieCloudSchema,\n options?: SyncOptions\n) {\n const ongoing = ongoingSyncs.get(db);\n if (ongoing) {\n if (ongoing.pull || options?.purpose === 'push') {\n console.debug('syncIfPossible(): returning the ongoing sync promise.');\n return ongoing.promise;\n } else {\n // Ongoing sync may never do anything in case there are no outstanding changes\n // to sync (because its purpose was \"push\" not \"pull\")\n // Now, however, we are asked to do a sync with the purpose of \"pull\"\n // We want to optimize here. We must wait for the ongoing to complete\n // and then, if the ongoing sync never resulted in a sync request,\n // we must redo the sync.\n\n // To inspect what is happening in the ongoing request, let's subscribe\n // to db.cloud.syncState and look for if it is doing any \"pulling\" phase:\n let hasPullTakenPlace = false;\n const subscription = db.cloud.syncState.subscribe((syncState) => {\n if (syncState.phase === 'pulling') {\n hasPullTakenPlace = true;\n }\n });\n // Ok, so now we are watching. At the same time, wait for the ongoing to complete\n // and when it has completed, check if we're all set or if we need to redo\n // the call:\n return (\n ongoing.promise\n // This is a finally block but we are still running tests on\n // browsers that don't support it, so need to do it like this:\n .then(() => {\n subscription.unsubscribe();\n })\n .catch((error) => {\n subscription.unsubscribe();\n return Promise.reject(error);\n })\n .then(() => {\n if (!hasPullTakenPlace) {\n // No pull took place in the ongoing sync but the caller had \"pull\" as\n // an explicit purpose of this call - so we need to redo the call!\n return syncIfPossible(db, cloudOptions, cloudSchema, options);\n }\n })\n );\n }\n }\n const promise = _syncIfPossible();\n ongoingSyncs.set(db, { promise, pull: options?.purpose !== 'push' });\n return promise;\n\n async function _syncIfPossible() {\n try {\n if (db.cloud.usingServiceWorker) {\n if (IS_SERVICE_WORKER) {\n await sync(db, cloudOptions, cloudSchema, options);\n }\n } else {\n // We use a flow that is better suited for the case when multiple workers want to\n // do the same thing.\n await performGuardedJob(db, CURRENT_SYNC_WORKER, '$jobs', () =>\n sync(db, cloudOptions, cloudSchema, options)\n );\n }\n ongoingSyncs.delete(db);\n console.debug('Done sync');\n } catch (error) {\n ongoingSyncs.delete(db);\n console.error(`Failed to sync client changes`, error);\n throw error; // Make sure we rethrow error so that sync event is retried.\n // I don't think we should setTimout or so here.\n // Unless server tells us to in some response.\n // Then we could follow that advice but not by waiting here but by registering\n // Something that triggers an event listened to in startPushWorker()\n }\n }\n}\n","import Dexie from 'dexie';\nimport { Subscription } from 'rxjs';\nimport { syncIfPossible } from './syncIfPossible';\nimport { DexieCloudDB } from '../db/DexieCloudDB';\nimport { MINUTES } from '../helpers/date-constants';\nimport { DexieCloudOptions } from '../DexieCloudOptions';\nimport { DexieCloudSchema } from 'dexie-cloud-common';\n\nexport function LocalSyncWorker(\n db: DexieCloudDB,\n cloudOptions: DexieCloudOptions,\n cloudSchema: DexieCloudSchema\n) {\n let localSyncEventSubscription: Subscription | null = null;\n //let syncHandler: ((event: Event) => void) | null = null;\n //let periodicSyncHandler: ((event: Event) => void) | null = null;\n let cancelToken = { cancelled: false };\n\n function syncAndRetry(purpose: 'pull' | 'push', retryNum = 1) {\n // Use setTimeout() to get onto a clean stack and\n // break free from possible active transaction:\n setTimeout(() => {\n syncIfPossible(db, cloudOptions, cloudSchema, {\n cancelToken,\n retryImmediatelyOnFetchError: true, // workaround for \"net::ERR_NETWORK_CHANGED\" in chrome.\n purpose,\n }).catch((e) => {\n console.error('error in syncIfPossible()', e);\n if (cancelToken.cancelled) {\n stop();\n } else if (retryNum < 3) {\n // Mimic service worker sync event: retry 3 times\n // * first retry after 5 minutes\n // * second retry 15 minutes later\n setTimeout(\n () => syncAndRetry(purpose, retryNum + 1),\n [0, 5, 15][retryNum] * MINUTES\n );\n }\n });\n }, 0);\n }\n\n const start = () => {\n // Sync eagerly whenever a change has happened (+ initially when there's no syncState yet)\n // This initial subscribe will also trigger an sync also now.\n console.debug('Starting LocalSyncWorker', db.localSyncEvent['id']);\n localSyncEventSubscription = db.localSyncEvent.subscribe(({ purpose }) => {\n try {\n syncAndRetry(purpose || 'pull');\n } catch (err) {\n console.error('What-the....', err);\n }\n });\n //setTimeout(()=>db.localSyncEvent.next({}), 5000);\n };\n\n const stop = () => {\n console.debug('Stopping LocalSyncWorker');\n cancelToken.cancelled = true;\n if (localSyncEventSubscription) localSyncEventSubscription.unsubscribe();\n };\n\n return {\n start,\n stop,\n };\n}\n","import { DexieCloudSchema } from \"dexie-cloud-common\";\nimport { DexieCloudOptions } from \"./DexieCloudOptions\";\n\nexport function updateSchemaFromOptions(schema?: DexieCloudSchema | null, options?: DexieCloudOptions | null) {\n if (schema && options) {\n if (options.unsyncedTables) {\n for (const tableName of options.unsyncedTables) {\n if (schema[tableName]) {\n schema[tableName].markedForSync = false;\n }\n }\n }\n }\n}","import Dexie from \"dexie\";\nimport { DexieCloudDB } from \"./db/DexieCloudDB\";\n\nexport function verifySchema(db: DexieCloudDB) {\n for (const table of db.tables) {\n if (db.cloud.schema?.[table.name]?.markedForSync) {\n if (table.schema.primKey.auto) {\n throw new Dexie.SchemaError(\n `Table ${table.name} is both autoIncremented and synced. ` +\n `Use db.cloud.configure({unsyncedTables: [${JSON.stringify(\n table.name\n )}]}) to blacklist it from sync`\n );\n }\n if (!table.schema.primKey.keyPath) {\n throw new Dexie.SchemaError(\n `Table ${table.name} cannot be both synced and outbound. ` +\n `Use db.cloud.configure({unsyncedTables: [${JSON.stringify(\n table.name\n )}]}) to blacklist it from sync`\n );\n }\n }\n }\n}\n","import { _catchError } from './diff/catch-error';\n\n/**\n * The `option` object can potentially contain callback functions\n * that are called during various stages of our renderer. This is the\n * foundation on which all our addons like `preact/debug`, `preact/compat`,\n * and `preact/hooks` are based on. See the `Options` type in `internal.d.ts`\n * for a full list of available option hooks (most editors/IDEs allow you to\n * ctrl+click or cmd+click on mac the type definition below).\n * @type {import('./internal').Options}\n */\nconst options = {\n\t_catchError,\n\t_vnodeId: 0\n};\n\nexport default options;\n","import { assign } from './util';\nimport { diff, commitRoot } from './diff/index';\nimport options from './options';\nimport { Fragment } from './create-element';\n\n/**\n * Base Component class. Provides `setState()` and `forceUpdate()`, which\n * trigger rendering\n * @param {object} props The initial component props\n * @param {object} context The initial context from parent components'\n * getChildContext\n */\nexport function Component(props, context) {\n\tthis.props = props;\n\tthis.context = context;\n}\n\n/**\n * Update component state and schedule a re-render.\n * @this {import('./internal').Component}\n * @param {object | ((s: object, p: object) => object)} update A hash of state\n * properties to update with new values or a function that given the current\n * state and props returns a new partial state\n * @param {() => void} [callback] A function to be called once component state is\n * updated\n */\nComponent.prototype.setState = function(update, callback) {\n\t// only clone state when copying to nextState the first time.\n\tlet s;\n\tif (this._nextState != null && this._nextState !== this.state) {\n\t\ts = this._nextState;\n\t} else {\n\t\ts = this._nextState = assign({}, this.state);\n\t}\n\n\tif (typeof update == 'function') {\n\t\t// Some libraries like `immer` mark the current state as readonly,\n\t\t// preventing us from mutating it, so we need to clone it. See #2716\n\t\tupdate = update(assign({}, s), this.props);\n\t}\n\n\tif (update) {\n\t\tassign(s, update);\n\t}\n\n\t// Skip update if updater function returned null\n\tif (update == null) return;\n\n\tif (this._vnode) {\n\t\tif (callback) this._renderCallbacks.push(callback);\n\t\tenqueueRender(this);\n\t}\n};\n\n/**\n * Immediately perform a synchronous re-render of the component\n * @this {import('./internal').Component}\n * @param {() => void} [callback] A function to be called after component is\n * re-rendered\n */\nComponent.prototype.forceUpdate = function(callback) {\n\tif (this._vnode) {\n\t\t// Set render mode so that we can differentiate where the render request\n\t\t// is coming from. We need this because forceUpdate should never call\n\t\t// shouldComponentUpdate\n\t\tthis._force = true;\n\t\tif (callback) this._renderCallbacks.push(callback);\n\t\tenqueueRender(this);\n\t}\n};\n\n/**\n * Accepts `props` and `state`, and returns a new Virtual DOM tree to build.\n * Virtual DOM is generally constructed via [JSX](http://jasonformat.com/wtf-is-jsx).\n * @param {object} props Props (eg: JSX attributes) received from parent\n * element/component\n * @param {object} state The component's current state\n * @param {object} context Context object, as returned by the nearest\n * ancestor's `getChildContext()`\n * @returns {import('./index').ComponentChildren | void}\n */\nComponent.prototype.render = Fragment;\n\n/**\n * @param {import('./internal').VNode} vnode\n * @param {number | null} [childIndex]\n */\nexport function getDomSibling(vnode, childIndex) {\n\tif (childIndex == null) {\n\t\t// Use childIndex==null as a signal to resume the search from the vnode's sibling\n\t\treturn vnode._parent\n\t\t\t? getDomSibling(vnode._parent, vnode._parent._children.indexOf(vnode) + 1)\n\t\t\t: null;\n\t}\n\n\tlet sibling;\n\tfor (; childIndex < vnode._children.length; childIndex++) {\n\t\tsibling = vnode._children[childIndex];\n\n\t\tif (sibling != null && sibling._dom != null) {\n\t\t\t// Since updateParentDomPointers keeps _dom pointer correct,\n\t\t\t// we can rely on _dom to tell us if this subtree contains a\n\t\t\t// rendered DOM node, and what the first rendered DOM node is\n\t\t\treturn sibling._dom;\n\t\t}\n\t}\n\n\t// If we get here, we have not found a DOM node in this vnode's children.\n\t// We must resume from this vnode's sibling (in it's parent _children array)\n\t// Only climb up and search the parent if we aren't searching through a DOM\n\t// VNode (meaning we reached the DOM parent of the original vnode that began\n\t// the search)\n\treturn typeof vnode.type == 'function' ? getDomSibling(vnode) : null;\n}\n\n/**\n * Trigger in-place re-rendering of a component.\n * @param {import('./internal').Component} component The component to rerender\n */\nfunction renderComponent(component) {\n\tlet vnode = component._vnode,\n\t\toldDom = vnode._dom,\n\t\tparentDom = component._parentDom;\n\n\tif (parentDom) {\n\t\tlet commitQueue = [];\n\t\tconst oldVNode = assign({}, vnode);\n\t\toldVNode._original = vnode._original + 1;\n\n\t\tdiff(\n\t\t\tparentDom,\n\t\t\tvnode,\n\t\t\toldVNode,\n\t\t\tcomponent._globalContext,\n\t\t\tparentDom.ownerSVGElement !== undefined,\n\t\t\tvnode._hydrating != null ? [oldDom] : null,\n\t\t\tcommitQueue,\n\t\t\toldDom == null ? getDomSibling(vnode) : oldDom,\n\t\t\tvnode._hydrating\n\t\t);\n\t\tcommitRoot(commitQueue, vnode);\n\n\t\tif (vnode._dom != oldDom) {\n\t\t\tupdateParentDomPointers(vnode);\n\t\t}\n\t}\n}\n\n/**\n * @param {import('./internal').VNode} vnode\n */\nfunction updateParentDomPointers(vnode) {\n\tif ((vnode = vnode._parent) != null && vnode._component != null) {\n\t\tvnode._dom = vnode._component.base = null;\n\t\tfor (let i = 0; i < vnode._children.length; i++) {\n\t\t\tlet child = vnode._children[i];\n\t\t\tif (child != null && child._dom != null) {\n\t\t\t\tvnode._dom = vnode._component.base = child._dom;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\t\treturn updateParentDomPointers(vnode);\n\t}\n}\n\n/**\n * The render queue\n * @type {Array<import('./internal').Component>}\n */\nlet rerenderQueue = [];\n\n/**\n * Asynchronously schedule a callback\n * @type {(cb: () => void) => void}\n */\n/* istanbul ignore next */\n// Note the following line isn't tree-shaken by rollup cuz of rollup/rollup#2566\nconst defer =\n\ttypeof Promise == 'function'\n\t\t? Promise.prototype.then.bind(Promise.resolve())\n\t\t: setTimeout;\n\n/*\n * The value of `Component.debounce` must asynchronously invoke the passed in callback. It is\n * important that contributors to Preact can consistently reason about what calls to `setState`, etc.\n * do, and when their effects will be applied. See the links below for some further reading on designing\n * asynchronous APIs.\n * * [Designing APIs for Asynchrony](https://blog.izs.me/2013/08/designing-apis-for-asynchrony)\n * * [Callbacks synchronous and asynchronous](https://blog.ometer.com/2011/07/24/callbacks-synchronous-and-asynchronous/)\n */\n\nlet prevDebounce;\n\n/**\n * Enqueue a rerender of a component\n * @param {import('./internal').Component} c The component to rerender\n */\nexport function enqueueRender(c) {\n\tif (\n\t\t(!c._dirty &&\n\t\t\t(c._dirty = true) &&\n\t\t\trerenderQueue.push(c) &&\n\t\t\t!process._rerenderCount++) ||\n\t\tprevDebounce !== options.debounceRendering\n\t) {\n\t\tprevDebounce = options.debounceRendering;\n\t\t(prevDebounce || defer)(process);\n\t}\n}\n\n/** Flush the render queue by rerendering all queued components */\nfunction process() {\n\tlet queue;\n\twhile ((process._rerenderCount = rerenderQueue.length)) {\n\t\tqueue = rerenderQueue.sort((a, b) => a._vnode._depth - b._vnode._depth);\n\t\trerenderQueue = [];\n\t\t// Don't update `renderCount` yet. Keep its value non-zero to prevent unnecessary\n\t\t// process() calls from getting scheduled while `queue` is still being consumed.\n\t\tqueue.some(c => {\n\t\t\tif (c._dirty) renderComponent(c);\n\t\t});\n\t}\n}\nprocess._rerenderCount = 0;\n","export const EMPTY_OBJ = {};\nexport const EMPTY_ARR = [];\nexport const IS_NON_DIMENSIONAL = /acit|ex(?:s|g|n|p|$)|rph|grid|ows|mnc|ntw|ine[ch]|zoo|^ord|itera/i;\n","/**\n * Assign properties from `props` to `obj`\n * @template O, P The obj and props types\n * @param {O} obj The object to copy properties to\n * @param {P} props The object to copy properties from\n * @returns {O & P}\n */\nexport function assign(obj, props) {\n\t// @ts-ignore We change the type of `obj` to be `O & P`\n\tfor (let i in props) obj[i] = props[i];\n\treturn /** @type {O & P} */ (obj);\n}\n\n/**\n * Remove a child node from its parent if attached. This is a workaround for\n * IE11 which doesn't support `Element.prototype.remove()`. Using this function\n * is smaller than including a dedicated polyfill.\n * @param {Node} node The node to remove\n */\nexport function removeNode(node) {\n\tlet parentNode = node.parentNode;\n\tif (parentNode) parentNode.removeChild(node);\n}\n","import options from './options';\n\n/**\n * Create an virtual node (used for JSX)\n * @param {import('./internal').VNode[\"type\"]} type The node name or Component\n * constructor for this virtual node\n * @param {object | null | undefined} [props] The properties of the virtual node\n * @param {Array<import('.').ComponentChildren>} [children] The children of the virtual node\n * @returns {import('./internal').VNode}\n */\nexport function createElement(type, props, children) {\n\tlet normalizedProps = {},\n\t\tkey,\n\t\tref,\n\t\ti;\n\tfor (i in props) {\n\t\tif (i == 'key') key = props[i];\n\t\telse if (i == 'ref') ref = props[i];\n\t\telse normalizedProps[i] = props[i];\n\t}\n\n\tif (arguments.length > 3) {\n\t\tchildren = [children];\n\t\t// https://github.com/preactjs/preact/issues/1916\n\t\tfor (i = 3; i < arguments.length; i++) {\n\t\t\tchildren.push(arguments[i]);\n\t\t}\n\t}\n\tif (children != null) {\n\t\tnormalizedProps.children = children;\n\t}\n\n\t// If a Component VNode, check for and apply defaultProps\n\t// Note: type may be undefined in development, must never error here.\n\tif (typeof type == 'function' && type.defaultProps != null) {\n\t\tfor (i in type.defaultProps) {\n\t\t\tif (normalizedProps[i] === undefined) {\n\t\t\t\tnormalizedProps[i] = type.defaultProps[i];\n\t\t\t}\n\t\t}\n\t}\n\n\treturn createVNode(type, normalizedProps, key, ref, null);\n}\n\n/**\n * Create a VNode (used internally by Preact)\n * @param {import('./internal').VNode[\"type\"]} type The node name or Component\n * Constructor for this virtual node\n * @param {object | string | number | null} props The properties of this virtual node.\n * If this virtual node represents a text node, this is the text of the node (string or number).\n * @param {string | number | null} key The key for this virtual node, used when\n * diffing it against its children\n * @param {import('./internal').VNode[\"ref\"]} ref The ref property that will\n * receive a reference to its created child\n * @returns {import('./internal').VNode}\n */\nexport function createVNode(type, props, key, ref, original) {\n\t// V8 seems to be better at detecting type shapes if the object is allocated from the same call site\n\t// Do not inline into createElement and coerceToVNode!\n\tconst vnode = {\n\t\ttype,\n\t\tprops,\n\t\tkey,\n\t\tref,\n\t\t_children: null,\n\t\t_parent: null,\n\t\t_depth: 0,\n\t\t_dom: null,\n\t\t// _nextDom must be initialized to undefined b/c it will eventually\n\t\t// be set to dom.nextSibling which can return `null` and it is important\n\t\t// to be able to distinguish between an uninitialized _nextDom and\n\t\t// a _nextDom that has been set to `null`\n\t\t_nextDom: undefined,\n\t\t_component: null,\n\t\t_hydrating: null,\n\t\tconstructor: undefined,\n\t\t_original: original == null ? ++options._vnodeId : original\n\t};\n\n\tif (options.vnode != null) options.vnode(vnode);\n\n\treturn vnode;\n}\n\nexport function createRef() {\n\treturn { current: null };\n}\n\nexport function Fragment(props) {\n\treturn props.children;\n}\n\n/**\n * Check if a the argument is a valid Preact VNode.\n * @param {*} vnode\n * @returns {vnode is import('./internal').VNode}\n */\nexport const isValidElement = vnode =>\n\tvnode != null && vnode.constructor === undefined;\n","import { diff, unmount, applyRef } from './index';\nimport { createVNode, Fragment } from '../create-element';\nimport { EMPTY_OBJ, EMPTY_ARR } from '../constants';\nimport { getDomSibling } from '../component';\n\n/**\n * Diff the children of a virtual node\n * @param {import('../internal').PreactElement} parentDom The DOM element whose\n * children are being diffed\n * @param {import('../internal').ComponentChildren[]} renderResult\n * @param {import('../internal').VNode} newParentVNode The new virtual\n * node whose children should be diff'ed against oldParentVNode\n * @param {import('../internal').VNode} oldParentVNode The old virtual\n * node whose children should be diff'ed against newParentVNode\n * @param {object} globalContext The current context object - modified by getChildContext\n * @param {boolean} isSvg Whether or not this DOM node is an SVG node\n * @param {Array<import('../internal').PreactElement>} excessDomChildren\n * @param {Array<import('../internal').Component>} commitQueue List of components\n * which have callbacks to invoke in commitRoot\n * @param {import('../internal').PreactElement} oldDom The current attached DOM\n * element any new dom elements should be placed around. Likely `null` on first\n * render (except when hydrating). Can be a sibling DOM element when diffing\n * Fragments that have siblings. In most cases, it starts out as `oldChildren[0]._dom`.\n * @param {boolean} isHydrating Whether or not we are in hydration\n */\nexport function diffChildren(\n\tparentDom,\n\trenderResult,\n\tnewParentVNode,\n\toldParentVNode,\n\tglobalContext,\n\tisSvg,\n\texcessDomChildren,\n\tcommitQueue,\n\toldDom,\n\tisHydrating\n) {\n\tlet i, j, oldVNode, childVNode, newDom, firstChildDom, refs;\n\n\t// This is a compression of oldParentVNode!=null && oldParentVNode != EMPTY_OBJ && oldParentVNode._children || EMPTY_ARR\n\t// as EMPTY_OBJ._children should be `undefined`.\n\tlet oldChildren = (oldParentVNode && oldParentVNode._children) || EMPTY_ARR;\n\n\tlet oldChildrenLength = oldChildren.length;\n\n\tnewParentVNode._children = [];\n\tfor (i = 0; i < renderResult.length; i++) {\n\t\tchildVNode = renderResult[i];\n\n\t\tif (childVNode == null || typeof childVNode == 'boolean') {\n\t\t\tchildVNode = newParentVNode._children[i] = null;\n\t\t}\n\t\t// If this newVNode is being reused (e.g. <div>{reuse}{reuse}</div>) in the same diff,\n\t\t// or we are rendering a component (e.g. setState) copy the oldVNodes so it can have\n\t\t// it's own DOM & etc. pointers\n\t\telse if (\n\t\t\ttypeof childVNode == 'string' ||\n\t\t\ttypeof childVNode == 'number' ||\n\t\t\t// eslint-disable-next-line valid-typeof\n\t\t\ttypeof childVNode == 'bigint'\n\t\t) {\n\t\t\tchildVNode = newParentVNode._children[i] = createVNode(\n\t\t\t\tnull,\n\t\t\t\tchildVNode,\n\t\t\t\tnull,\n\t\t\t\tnull,\n\t\t\t\tchildVNode\n\t\t\t);\n\t\t} else if (Array.isArray(childVNode)) {\n\t\t\tchildVNode = newParentVNode._children[i] = createVNode(\n\t\t\t\tFragment,\n\t\t\t\t{ children: childVNode },\n\t\t\t\tnull,\n\t\t\t\tnull,\n\t\t\t\tnull\n\t\t\t);\n\t\t} else if (childVNode._depth > 0) {\n\t\t\t// VNode is already in use, clone it. This can happen in the following\n\t\t\t// scenario:\n\t\t\t// const reuse = <div />\n\t\t\t// <div>{reuse}<span />{reuse}</div>\n\t\t\tchildVNode = newParentVNode._children[i] = createVNode(\n\t\t\t\tchildVNode.type,\n\t\t\t\tchildVNode.props,\n\t\t\t\tchildVNode.key,\n\t\t\t\tnull,\n\t\t\t\tchildVNode._original\n\t\t\t);\n\t\t} else {\n\t\t\tchildVNode = newParentVNode._children[i] = childVNode;\n\t\t}\n\n\t\t// Terser removes the `continue` here and wraps the loop body\n\t\t// in a `if (childVNode) { ... } condition\n\t\tif (childVNode == null) {\n\t\t\tcontinue;\n\t\t}\n\n\t\tchildVNode._parent = newParentVNode;\n\t\tchildVNode._depth = newParentVNode._depth + 1;\n\n\t\t// Check if we find a corresponding element in oldChildren.\n\t\t// If found, delete the array item by setting to `undefined`.\n\t\t// We use `undefined`, as `null` is reserved for empty placeholders\n\t\t// (holes).\n\t\toldVNode = oldChildren[i];\n\n\t\tif (\n\t\t\toldVNode === null ||\n\t\t\t(oldVNode &&\n\t\t\t\tchildVNode.key == oldVNode.key &&\n\t\t\t\tchildVNode.type === oldVNode.type)\n\t\t) {\n\t\t\toldChildren[i] = undefined;\n\t\t} else {\n\t\t\t// Either oldVNode === undefined or oldChildrenLength > 0,\n\t\t\t// so after this loop oldVNode == null or oldVNode is a valid value.\n\t\t\tfor (j = 0; j < oldChildrenLength; j++) {\n\t\t\t\toldVNode = oldChildren[j];\n\t\t\t\t// If childVNode is unkeyed, we only match similarly unkeyed nodes, otherwise we match by key.\n\t\t\t\t// We always match by type (in either case).\n\t\t\t\tif (\n\t\t\t\t\toldVNode &&\n\t\t\t\t\tchildVNode.key == oldVNode.key &&\n\t\t\t\t\tchildVNode.type === oldVNode.type\n\t\t\t\t) {\n\t\t\t\t\toldChildren[j] = undefined;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\toldVNode = null;\n\t\t\t}\n\t\t}\n\n\t\toldVNode = oldVNode || EMPTY_OBJ;\n\n\t\t// Morph the old element into the new one, but don't append it to the dom yet\n\t\tdiff(\n\t\t\tparentDom,\n\t\t\tchildVNode,\n\t\t\toldVNode,\n\t\t\tglobalContext,\n\t\t\tisSvg,\n\t\t\texcessDomChildren,\n\t\t\tcommitQueue,\n\t\t\toldDom,\n\t\t\tisHydrating\n\t\t);\n\n\t\tnewDom = childVNode._dom;\n\n\t\tif ((j = childVNode.ref) && oldVNode.ref != j) {\n\t\t\tif (!refs) refs = [];\n\t\t\tif (oldVNode.ref) refs.push(oldVNode.ref, null, childVNode);\n\t\t\trefs.push(j, childVNode._component || newDom, childVNode);\n\t\t}\n\n\t\tif (newDom != null) {\n\t\t\tif (firstChildDom == null) {\n\t\t\t\tfirstChildDom = newDom;\n\t\t\t}\n\n\t\t\tif (\n\t\t\t\ttypeof childVNode.type == 'function' &&\n\t\t\t\tchildVNode._children != null && // Can be null if childVNode suspended\n\t\t\t\tchildVNode._children === oldVNode._children\n\t\t\t) {\n\t\t\t\tchildVNode._nextDom = oldDom = reorderChildren(\n\t\t\t\t\tchildVNode,\n\t\t\t\t\toldDom,\n\t\t\t\t\tparentDom\n\t\t\t\t);\n\t\t\t} else {\n\t\t\t\toldDom = placeChild(\n\t\t\t\t\tparentDom,\n\t\t\t\t\tchildVNode,\n\t\t\t\t\toldVNode,\n\t\t\t\t\toldChildren,\n\t\t\t\t\tnewDom,\n\t\t\t\t\toldDom\n\t\t\t\t);\n\t\t\t}\n\n\t\t\t// Browsers will infer an option's `value` from `textContent` when\n\t\t\t// no value is present. This essentially bypasses our code to set it\n\t\t\t// later in `diff()`. It works fine in all browsers except for IE11\n\t\t\t// where it breaks setting `select.value`. There it will be always set\n\t\t\t// to an empty string. Re-applying an options value will fix that, so\n\t\t\t// there are probably some internal data structures that aren't\n\t\t\t// updated properly.\n\t\t\t//\n\t\t\t// To fix it we make sure to reset the inferred value, so that our own\n\t\t\t// value check in `diff()` won't be skipped.\n\t\t\tif (!isHydrating && newParentVNode.type === 'option') {\n\t\t\t\t// @ts-ignore We have validated that the type of parentDOM is 'option'\n\t\t\t\t// in the above check\n\t\t\t\tparentDom.value = '';\n\t\t\t} else if (typeof newParentVNode.type == 'function') {\n\t\t\t\t// Because the newParentVNode is Fragment-like, we need to set it's\n\t\t\t\t// _nextDom property to the nextSibling of its last child DOM node.\n\t\t\t\t//\n\t\t\t\t// `oldDom` contains the correct value here because if the last child\n\t\t\t\t// is a Fragment-like, then oldDom has already been set to that child's _nextDom.\n\t\t\t\t// If the last child is a DOM VNode, then oldDom will be set to that DOM\n\t\t\t\t// node's nextSibling.\n\t\t\t\tnewParentVNode._nextDom = oldDom;\n\t\t\t}\n\t\t} else if (\n\t\t\toldDom &&\n\t\t\toldVNode._dom == oldDom &&\n\t\t\toldDom.parentNode != parentDom\n\t\t) {\n\t\t\t// The above condition is to handle null placeholders. See test in placeholder.test.js:\n\t\t\t// `efficiently replace null placeholders in parent rerenders`\n\t\t\toldDom = getDomSibling(oldVNode);\n\t\t}\n\t}\n\n\tnewParentVNode._dom = firstChildDom;\n\n\t// Remove remaining oldChildren if there are any.\n\tfor (i = oldChildrenLength; i--; ) {\n\t\tif (oldChildren[i] != null) {\n\t\t\tif (\n\t\t\t\ttypeof newParentVNode.type == 'function' &&\n\t\t\t\toldChildren[i]._dom != null &&\n\t\t\t\toldChildren[i]._dom == newParentVNode._nextDom\n\t\t\t) {\n\t\t\t\t// If the newParentVNode.__nextDom points to a dom node that is about to\n\t\t\t\t// be unmounted, then get the next sibling of that vnode and set\n\t\t\t\t// _nextDom to it\n\t\t\t\tnewParentVNode._nextDom = getDomSibling(oldParentVNode, i + 1);\n\t\t\t}\n\n\t\t\tunmount(oldChildren[i], oldChildren[i]);\n\t\t}\n\t}\n\n\t// Set refs only after unmount\n\tif (refs) {\n\t\tfor (i = 0; i < refs.length; i++) {\n\t\t\tapplyRef(refs[i], refs[++i], refs[++i]);\n\t\t}\n\t}\n}\n\nfunction reorderChildren(childVNode, oldDom, parentDom) {\n\tfor (let tmp = 0; tmp < childVNode._children.length; tmp++) {\n\t\tlet vnode = childVNode._children[tmp];\n\t\tif (vnode) {\n\t\t\t// We typically enter this code path on sCU bailout, where we copy\n\t\t\t// oldVNode._children to newVNode._children. If that is the case, we need\n\t\t\t// to update the old children's _parent pointer to point to the newVNode\n\t\t\t// (childVNode here).\n\t\t\tvnode._parent = childVNode;\n\n\t\t\tif (typeof vnode.type == 'function') {\n\t\t\t\toldDom = reorderChildren(vnode, oldDom, parentDom);\n\t\t\t} else {\n\t\t\t\toldDom = placeChild(\n\t\t\t\t\tparentDom,\n\t\t\t\t\tvnode,\n\t\t\t\t\tvnode,\n\t\t\t\t\tchildVNode._children,\n\t\t\t\t\tvnode._dom,\n\t\t\t\t\toldDom\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t}\n\n\treturn oldDom;\n}\n\n/**\n * Flatten and loop through the children of a virtual node\n * @param {import('../index').ComponentChildren} children The unflattened\n * children of a virtual node\n * @returns {import('../internal').VNode[]}\n */\nexport function toChildArray(children, out) {\n\tout = out || [];\n\tif (children == null || typeof children == 'boolean') {\n\t} else if (Array.isArray(children)) {\n\t\tchildren.some(child => {\n\t\t\ttoChildArray(child, out);\n\t\t});\n\t} else {\n\t\tout.push(children);\n\t}\n\treturn out;\n}\n\nfunction placeChild(\n\tparentDom,\n\tchildVNode,\n\toldVNode,\n\toldChildren,\n\tnewDom,\n\toldDom\n) {\n\tlet nextDom;\n\tif (childVNode._nextDom !== undefined) {\n\t\t// Only Fragments or components that return Fragment like VNodes will\n\t\t// have a non-undefined _nextDom. Continue the diff from the sibling\n\t\t// of last DOM child of this child VNode\n\t\tnextDom = childVNode._nextDom;\n\n\t\t// Eagerly cleanup _nextDom. We don't need to persist the value because\n\t\t// it is only used by `diffChildren` to determine where to resume the diff after\n\t\t// diffing Components and Fragments. Once we store it the nextDOM local var, we\n\t\t// can clean up the property\n\t\tchildVNode._nextDom = undefined;\n\t} else if (\n\t\toldVNode == null ||\n\t\tnewDom != oldDom ||\n\t\tnewDom.parentNode == null\n\t) {\n\t\touter: if (oldDom == null || oldDom.parentNode !== parentDom) {\n\t\t\tparentDom.appendChild(newDom);\n\t\t\tnextDom = null;\n\t\t} else {\n\t\t\t// `j<oldChildrenLength; j+=2` is an alternative to `j++<oldChildrenLength/2`\n\t\t\tfor (\n\t\t\t\tlet sibDom = oldDom, j = 0;\n\t\t\t\t(sibDom = sibDom.nextSibling) && j < oldChildren.length;\n\t\t\t\tj += 2\n\t\t\t) {\n\t\t\t\tif (sibDom == newDom) {\n\t\t\t\t\tbreak outer;\n\t\t\t\t}\n\t\t\t}\n\t\t\tparentDom.insertBefore(newDom, oldDom);\n\t\t\tnextDom = oldDom;\n\t\t}\n\t}\n\n\t// If we have pre-calculated the nextDOM node, use it. Else calculate it now\n\t// Strictly check for `undefined` here cuz `null` is a valid value of `nextDom`.\n\t// See more detail in create-element.js:createVNode\n\tif (nextDom !== undefined) {\n\t\toldDom = nextDom;\n\t} else {\n\t\toldDom = newDom.nextSibling;\n\t}\n\n\treturn oldDom;\n}\n","import { IS_NON_DIMENSIONAL } from '../constants';\nimport options from '../options';\n\n/**\n * Diff the old and new properties of a VNode and apply changes to the DOM node\n * @param {import('../internal').PreactElement} dom The DOM node to apply\n * changes to\n * @param {object} newProps The new props\n * @param {object} oldProps The old props\n * @param {boolean} isSvg Whether or not this node is an SVG node\n * @param {boolean} hydrate Whether or not we are in hydration mode\n */\nexport function diffProps(dom, newProps, oldProps, isSvg, hydrate) {\n\tlet i;\n\n\tfor (i in oldProps) {\n\t\tif (i !== 'children' && i !== 'key' && !(i in newProps)) {\n\t\t\tsetProperty(dom, i, null, oldProps[i], isSvg);\n\t\t}\n\t}\n\n\tfor (i in newProps) {\n\t\tif (\n\t\t\t(!hydrate || typeof newProps[i] == 'function') &&\n\t\t\ti !== 'children' &&\n\t\t\ti !== 'key' &&\n\t\t\ti !== 'value' &&\n\t\t\ti !== 'checked' &&\n\t\t\toldProps[i] !== newProps[i]\n\t\t) {\n\t\t\tsetProperty(dom, i, newProps[i], oldProps[i], isSvg);\n\t\t}\n\t}\n}\n\nfunction setStyle(style, key, value) {\n\tif (key[0] === '-') {\n\t\tstyle.setProperty(key, value);\n\t} else if (value == null) {\n\t\tstyle[key] = '';\n\t} else if (typeof value != 'number' || IS_NON_DIMENSIONAL.test(key)) {\n\t\tstyle[key] = value;\n\t} else {\n\t\tstyle[key] = value + 'px';\n\t}\n}\n\n/**\n * Set a property value on a DOM node\n * @param {import('../internal').PreactElement} dom The DOM node to modify\n * @param {string} name The name of the property to set\n * @param {*} value The value to set the property to\n * @param {*} oldValue The old value the property had\n * @param {boolean} isSvg Whether or not this DOM node is an SVG node or not\n */\nexport function setProperty(dom, name, value, oldValue, isSvg) {\n\tlet useCapture;\n\n\to: if (name === 'style') {\n\t\tif (typeof value == 'string') {\n\t\t\tdom.style.cssText = value;\n\t\t} else {\n\t\t\tif (typeof oldValue == 'string') {\n\t\t\t\tdom.style.cssText = oldValue = '';\n\t\t\t}\n\n\t\t\tif (oldValue) {\n\t\t\t\tfor (name in oldValue) {\n\t\t\t\t\tif (!(value && name in value)) {\n\t\t\t\t\t\tsetStyle(dom.style, name, '');\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (value) {\n\t\t\t\tfor (name in value) {\n\t\t\t\t\tif (!oldValue || value[name] !== oldValue[name]) {\n\t\t\t\t\t\tsetStyle(dom.style, name, value[name]);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\t// Benchmark for comparison: https://esbench.com/bench/574c954bdb965b9a00965ac6\n\telse if (name[0] === 'o' && name[1] === 'n') {\n\t\tuseCapture = name !== (name = name.replace(/Capture$/, ''));\n\n\t\t// Infer correct casing for DOM built-in events:\n\t\tif (name.toLowerCase() in dom) name = name.toLowerCase().slice(2);\n\t\telse name = name.slice(2);\n\n\t\tif (!dom._listeners) dom._listeners = {};\n\t\tdom._listeners[name + useCapture] = value;\n\n\t\tif (value) {\n\t\t\tif (!oldValue) {\n\t\t\t\tconst handler = useCapture ? eventProxyCapture : eventProxy;\n\t\t\t\tdom.addEventListener(name, handler, useCapture);\n\t\t\t}\n\t\t} else {\n\t\t\tconst handler = useCapture ? eventProxyCapture : eventProxy;\n\t\t\tdom.removeEventListener(name, handler, useCapture);\n\t\t}\n\t} else if (name !== 'dangerouslySetInnerHTML') {\n\t\tif (isSvg) {\n\t\t\t// Normalize incorrect prop usage for SVG:\n\t\t\t// - xlink:href / xlinkHref --> href (xlink:href was removed from SVG and isn't needed)\n\t\t\t// - className --> class\n\t\t\tname = name.replace(/xlink[H:h]/, 'h').replace(/sName$/, 's');\n\t\t} else if (\n\t\t\tname !== 'href' &&\n\t\t\tname !== 'list' &&\n\t\t\tname !== 'form' &&\n\t\t\t// Default value in browsers is `-1` and an empty string is\n\t\t\t// cast to `0` instead\n\t\t\tname !== 'tabIndex' &&\n\t\t\tname !== 'download' &&\n\t\t\tname in dom\n\t\t) {\n\t\t\ttry {\n\t\t\t\tdom[name] = value == null ? '' : value;\n\t\t\t\t// labelled break is 1b smaller here than a return statement (sorry)\n\t\t\t\tbreak o;\n\t\t\t} catch (e) {}\n\t\t}\n\n\t\t// ARIA-attributes have a different notion of boolean values.\n\t\t// The value `false` is different from the attribute not\n\t\t// existing on the DOM, so we can't remove it. For non-boolean\n\t\t// ARIA-attributes we could treat false as a removal, but the\n\t\t// amount of exceptions would cost us too many bytes. On top of\n\t\t// that other VDOM frameworks also always stringify `false`.\n\n\t\tif (typeof value === 'function') {\n\t\t\t// never serialize functions as attribute values\n\t\t} else if (\n\t\t\tvalue != null &&\n\t\t\t(value !== false || (name[0] === 'a' && name[1] === 'r'))\n\t\t) {\n\t\t\tdom.setAttribute(name, value);\n\t\t} else {\n\t\t\tdom.removeAttribute(name);\n\t\t}\n\t}\n}\n\n/**\n * Proxy an event to hooked event handlers\n * @param {Event} e The event object from the browser\n * @private\n */\nfunction eventProxy(e) {\n\tthis._listeners[e.type + false](options.event ? options.event(e) : e);\n}\n\nfunction eventProxyCapture(e) {\n\tthis._listeners[e.type + true](options.event ? options.event(e) : e);\n}\n","import { EMPTY_OBJ, EMPTY_ARR } from '../constants';\nimport { Component } from '../component';\nimport { Fragment } from '../create-element';\nimport { diffChildren } from './children';\nimport { diffProps, setProperty } from './props';\nimport { assign, removeNode } from '../util';\nimport options from '../options';\n\n/**\n * Diff two virtual nodes and apply proper changes to the DOM\n * @param {import('../internal').PreactElement} parentDom The parent of the DOM element\n * @param {import('../internal').VNode} newVNode The new virtual node\n * @param {import('../internal').VNode} oldVNode The old virtual node\n * @param {object} globalContext The current context object. Modified by getChildContext\n * @param {boolean} isSvg Whether or not this element is an SVG node\n * @param {Array<import('../internal').PreactElement>} excessDomChildren\n * @param {Array<import('../internal').Component>} commitQueue List of components\n * which have callbacks to invoke in commitRoot\n * @param {import('../internal').PreactElement} oldDom The current attached DOM\n * element any new dom elements should be placed around. Likely `null` on first\n * render (except when hydrating). Can be a sibling DOM element when diffing\n * Fragments that have siblings. In most cases, it starts out as `oldChildren[0]._dom`.\n * @param {boolean} [isHydrating] Whether or not we are in hydration\n */\nexport function diff(\n\tparentDom,\n\tnewVNode,\n\toldVNode,\n\tglobalContext,\n\tisSvg,\n\texcessDomChildren,\n\tcommitQueue,\n\toldDom,\n\tisHydrating\n) {\n\tlet tmp,\n\t\tnewType = newVNode.type;\n\n\t// When passing through createElement it assigns the object\n\t// constructor as undefined. This to prevent JSON-injection.\n\tif (newVNode.constructor !== undefined) return null;\n\n\t// If the previous diff bailed out, resume creating/hydrating.\n\tif (oldVNode._hydrating != null) {\n\t\tisHydrating = oldVNode._hydrating;\n\t\toldDom = newVNode._dom = oldVNode._dom;\n\t\t// if we resume, we want the tree to be \"unlocked\"\n\t\tnewVNode._hydrating = null;\n\t\texcessDomChildren = [oldDom];\n\t}\n\n\tif ((tmp = options._diff)) tmp(newVNode);\n\n\ttry {\n\t\touter: if (typeof newType == 'function') {\n\t\t\tlet c, isNew, oldProps, oldState, snapshot, clearProcessingException;\n\t\t\tlet newProps = newVNode.props;\n\n\t\t\t// Necessary for createContext api. Setting this property will pass\n\t\t\t// the context value as `this.context` just for this component.\n\t\t\ttmp = newType.contextType;\n\t\t\tlet provider = tmp && globalContext[tmp._id];\n\t\t\tlet componentContext = tmp\n\t\t\t\t? provider\n\t\t\t\t\t? provider.props.value\n\t\t\t\t\t: tmp._defaultValue\n\t\t\t\t: globalContext;\n\n\t\t\t// Get component and set it to `c`\n\t\t\tif (oldVNode._component) {\n\t\t\t\tc = newVNode._component = oldVNode._component;\n\t\t\t\tclearProcessingException = c._processingException = c._pendingError;\n\t\t\t} else {\n\t\t\t\t// Instantiate the new component\n\t\t\t\tif ('prototype' in newType && newType.prototype.render) {\n\t\t\t\t\t// @ts-ignore The check above verifies that newType is suppose to be constructed\n\t\t\t\t\tnewVNode._component = c = new newType(newProps, componentContext); // eslint-disable-line new-cap\n\t\t\t\t} else {\n\t\t\t\t\t// @ts-ignore Trust me, Component implements the interface we want\n\t\t\t\t\tnewVNode._component = c = new Component(newProps, componentContext);\n\t\t\t\t\tc.constructor = newType;\n\t\t\t\t\tc.render = doRender;\n\t\t\t\t}\n\t\t\t\tif (provider) provider.sub(c);\n\n\t\t\t\tc.props = newProps;\n\t\t\t\tif (!c.state) c.state = {};\n\t\t\t\tc.context = componentContext;\n\t\t\t\tc._globalContext = globalContext;\n\t\t\t\tisNew = c._dirty = true;\n\t\t\t\tc._renderCallbacks = [];\n\t\t\t}\n\n\t\t\t// Invoke getDerivedStateFromProps\n\t\t\tif (c._nextState == null) {\n\t\t\t\tc._nextState = c.state;\n\t\t\t}\n\t\t\tif (newType.getDerivedStateFromProps != null) {\n\t\t\t\tif (c._nextState == c.state) {\n\t\t\t\t\tc._nextState = assign({}, c._nextState);\n\t\t\t\t}\n\n\t\t\t\tassign(\n\t\t\t\t\tc._nextState,\n\t\t\t\t\tnewType.getDerivedStateFromProps(newProps, c._nextState)\n\t\t\t\t);\n\t\t\t}\n\n\t\t\toldProps = c.props;\n\t\t\toldState = c.state;\n\n\t\t\t// Invoke pre-render lifecycle methods\n\t\t\tif (isNew) {\n\t\t\t\tif (\n\t\t\t\t\tnewType.getDerivedStateFromProps == null &&\n\t\t\t\t\tc.componentWillMount != null\n\t\t\t\t) {\n\t\t\t\t\tc.componentWillMount();\n\t\t\t\t}\n\n\t\t\t\tif (c.componentDidMount != null) {\n\t\t\t\t\tc._renderCallbacks.push(c.componentDidMount);\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tif (\n\t\t\t\t\tnewType.getDerivedStateFromProps == null &&\n\t\t\t\t\tnewProps !== oldProps &&\n\t\t\t\t\tc.componentWillReceiveProps != null\n\t\t\t\t) {\n\t\t\t\t\tc.componentWillReceiveProps(newProps, componentContext);\n\t\t\t\t}\n\n\t\t\t\tif (\n\t\t\t\t\t(!c._force &&\n\t\t\t\t\t\tc.shouldComponentUpdate != null &&\n\t\t\t\t\t\tc.shouldComponentUpdate(\n\t\t\t\t\t\t\tnewProps,\n\t\t\t\t\t\t\tc._nextState,\n\t\t\t\t\t\t\tcomponentContext\n\t\t\t\t\t\t) === false) ||\n\t\t\t\t\tnewVNode._original === oldVNode._original\n\t\t\t\t) {\n\t\t\t\t\tc.props = newProps;\n\t\t\t\t\tc.state = c._nextState;\n\t\t\t\t\t// More info about this here: https://gist.github.com/JoviDeCroock/bec5f2ce93544d2e6070ef8e0036e4e8\n\t\t\t\t\tif (newVNode._original !== oldVNode._original) c._dirty = false;\n\t\t\t\t\tc._vnode = newVNode;\n\t\t\t\t\tnewVNode._dom = oldVNode._dom;\n\t\t\t\t\tnewVNode._children = oldVNode._children;\n\t\t\t\t\tnewVNode._children.forEach(vnode => {\n\t\t\t\t\t\tif (vnode) vnode._parent = newVNode;\n\t\t\t\t\t});\n\t\t\t\t\tif (c._renderCallbacks.length) {\n\t\t\t\t\t\tcommitQueue.push(c);\n\t\t\t\t\t}\n\n\t\t\t\t\tbreak outer;\n\t\t\t\t}\n\n\t\t\t\tif (c.componentWillUpdate != null) {\n\t\t\t\t\tc.componentWillUpdate(newProps, c._nextState, componentContext);\n\t\t\t\t}\n\n\t\t\t\tif (c.componentDidUpdate != null) {\n\t\t\t\t\tc._renderCallbacks.push(() => {\n\t\t\t\t\t\tc.componentDidUpdate(oldProps, oldState, snapshot);\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tc.context = componentContext;\n\t\t\tc.props = newProps;\n\t\t\tc.state = c._nextState;\n\n\t\t\tif ((tmp = options._render)) tmp(newVNode);\n\n\t\t\tc._dirty = false;\n\t\t\tc._vnode = newVNode;\n\t\t\tc._parentDom = parentDom;\n\n\t\t\ttmp = c.render(c.props, c.state, c.context);\n\n\t\t\t// Handle setState called in render, see #2553\n\t\t\tc.state = c._nextState;\n\n\t\t\tif (c.getChildContext != null) {\n\t\t\t\tglobalContext = assign(assign({}, globalContext), c.getChildContext());\n\t\t\t}\n\n\t\t\tif (!isNew && c.getSnapshotBeforeUpdate != null) {\n\t\t\t\tsnapshot = c.getSnapshotBeforeUpdate(oldProps, oldState);\n\t\t\t}\n\n\t\t\tlet isTopLevelFragment =\n\t\t\t\ttmp != null && tmp.type === Fragment && tmp.key == null;\n\t\t\tlet renderResult = isTopLevelFragment ? tmp.props.children : tmp;\n\n\t\t\tdiffChildren(\n\t\t\t\tparentDom,\n\t\t\t\tArray.isArray(renderResult) ? renderResult : [renderResult],\n\t\t\t\tnewVNode,\n\t\t\t\toldVNode,\n\t\t\t\tglobalContext,\n\t\t\t\tisSvg,\n\t\t\t\texcessDomChildren,\n\t\t\t\tcommitQueue,\n\t\t\t\toldDom,\n\t\t\t\tisHydrating\n\t\t\t);\n\n\t\t\tc.base = newVNode._dom;\n\n\t\t\t// We successfully rendered this VNode, unset any stored hydration/bailout state:\n\t\t\tnewVNode._hydrating = null;\n\n\t\t\tif (c._renderCallbacks.length) {\n\t\t\t\tcommitQueue.push(c);\n\t\t\t}\n\n\t\t\tif (clearProcessingException) {\n\t\t\t\tc._pendingError = c._processingException = null;\n\t\t\t}\n\n\t\t\tc._force = false;\n\t\t} else if (\n\t\t\texcessDomChildren == null &&\n\t\t\tnewVNode._original === oldVNode._original\n\t\t) {\n\t\t\tnewVNode._children = oldVNode._children;\n\t\t\tnewVNode._dom = oldVNode._dom;\n\t\t} else {\n\t\t\tnewVNode._dom = diffElementNodes(\n\t\t\t\toldVNode._dom,\n\t\t\t\tnewVNode,\n\t\t\t\toldVNode,\n\t\t\t\tglobalContext,\n\t\t\t\tisSvg,\n\t\t\t\texcessDomChildren,\n\t\t\t\tcommitQueue,\n\t\t\t\tisHydrating\n\t\t\t);\n\t\t}\n\n\t\tif ((tmp = options.diffed)) tmp(newVNode);\n\t} catch (e) {\n\t\tnewVNode._original = null;\n\t\t// if hydrating or creating initial tree, bailout preserves DOM:\n\t\tif (isHydrating || excessDomChildren != null) {\n\t\t\tnewVNode._dom = oldDom;\n\t\t\tnewVNode._hydrating = !!isHydrating;\n\t\t\texcessDomChildren[excessDomChildren.indexOf(oldDom)] = null;\n\t\t\t// ^ could possibly be simplified to:\n\t\t\t// excessDomChildren.length = 0;\n\t\t}\n\t\toptions._catchError(e, newVNode, oldVNode);\n\t}\n}\n\n/**\n * @param {Array<import('../internal').Component>} commitQueue List of components\n * which have callbacks to invoke in commitRoot\n * @param {import('../internal').VNode} root\n */\nexport function commitRoot(commitQueue, root) {\n\tif (options._commit) options._commit(root, commitQueue);\n\n\tcommitQueue.some(c => {\n\t\ttry {\n\t\t\t// @ts-ignore Reuse the commitQueue variable here so the type changes\n\t\t\tcommitQueue = c._renderCallbacks;\n\t\t\tc._renderCallbacks = [];\n\t\t\tcommitQueue.some(cb => {\n\t\t\t\t// @ts-ignore See above ts-ignore on commitQueue\n\t\t\t\tcb.call(c);\n\t\t\t});\n\t\t} catch (e) {\n\t\t\toptions._catchError(e, c._vnode);\n\t\t}\n\t});\n}\n\n/**\n * Diff two virtual nodes representing DOM element\n * @param {import('../internal').PreactElement} dom The DOM element representing\n * the virtual nodes being diffed\n * @param {import('../internal').VNode} newVNode The new virtual node\n * @param {import('../internal').VNode} oldVNode The old virtual node\n * @param {object} globalContext The current context object\n * @param {boolean} isSvg Whether or not this DOM node is an SVG node\n * @param {*} excessDomChildren\n * @param {Array<import('../internal').Component>} commitQueue List of components\n * which have callbacks to invoke in commitRoot\n * @param {boolean} isHydrating Whether or not we are in hydration\n * @returns {import('../internal').PreactElement}\n */\nfunction diffElementNodes(\n\tdom,\n\tnewVNode,\n\toldVNode,\n\tglobalContext,\n\tisSvg,\n\texcessDomChildren,\n\tcommitQueue,\n\tisHydrating\n) {\n\tlet oldProps = oldVNode.props;\n\tlet newProps = newVNode.props;\n\tlet nodeType = newVNode.type;\n\tlet i = 0;\n\n\t// Tracks entering and exiting SVG namespace when descending through the tree.\n\tif (nodeType === 'svg') isSvg = true;\n\n\tif (excessDomChildren != null) {\n\t\tfor (; i < excessDomChildren.length; i++) {\n\t\t\tconst child = excessDomChildren[i];\n\n\t\t\t// if newVNode matches an element in excessDomChildren or the `dom`\n\t\t\t// argument matches an element in excessDomChildren, remove it from\n\t\t\t// excessDomChildren so it isn't later removed in diffChildren\n\t\t\tif (\n\t\t\t\tchild &&\n\t\t\t\t(child === dom ||\n\t\t\t\t\t(nodeType ? child.localName == nodeType : child.nodeType == 3))\n\t\t\t) {\n\t\t\t\tdom = child;\n\t\t\t\texcessDomChildren[i] = null;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\n\tif (dom == null) {\n\t\tif (nodeType === null) {\n\t\t\t// @ts-ignore createTextNode returns Text, we expect PreactElement\n\t\t\treturn document.createTextNode(newProps);\n\t\t}\n\n\t\tif (isSvg) {\n\t\t\tdom = document.createElementNS(\n\t\t\t\t'http://www.w3.org/2000/svg',\n\t\t\t\t// @ts-ignore We know `newVNode.type` is a string\n\t\t\t\tnodeType\n\t\t\t);\n\t\t} else {\n\t\t\tdom = document.createElement(\n\t\t\t\t// @ts-ignore We know `newVNode.type` is a string\n\t\t\t\tnodeType,\n\t\t\t\tnewProps.is && newProps\n\t\t\t);\n\t\t}\n\n\t\t// we created a new parent, so none of the previously attached children can be reused:\n\t\texcessDomChildren = null;\n\t\t// we are creating a new node, so we can assume this is a new subtree (in case we are hydrating), this deopts the hydrate\n\t\tisHydrating = false;\n\t}\n\n\tif (nodeType === null) {\n\t\t// During hydration, we still have to split merged text from SSR'd HTML.\n\t\tif (oldProps !== newProps && (!isHydrating || dom.data !== newProps)) {\n\t\t\tdom.data = newProps;\n\t\t}\n\t} else {\n\t\t// If excessDomChildren was not null, repopulate it with the current element's children:\n\t\texcessDomChildren =\n\t\t\texcessDomChildren && EMPTY_ARR.slice.call(dom.childNodes);\n\n\t\toldProps = oldVNode.props || EMPTY_OBJ;\n\n\t\tlet oldHtml = oldProps.dangerouslySetInnerHTML;\n\t\tlet newHtml = newProps.dangerouslySetInnerHTML;\n\n\t\t// During hydration, props are not diffed at all (including dangerouslySetInnerHTML)\n\t\t// @TODO we should warn in debug mode when props don't match here.\n\t\tif (!isHydrating) {\n\t\t\t// But, if we are in a situation where we are using existing DOM (e.g. replaceNode)\n\t\t\t// we should read the existing DOM attributes to diff them\n\t\t\tif (excessDomChildren != null) {\n\t\t\t\toldProps = {};\n\t\t\t\tfor (let i = 0; i < dom.attributes.length; i++) {\n\t\t\t\t\toldProps[dom.attributes[i].name] = dom.attributes[i].value;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (newHtml || oldHtml) {\n\t\t\t\t// Avoid re-applying the same '__html' if it did not changed between re-render\n\t\t\t\tif (\n\t\t\t\t\t!newHtml ||\n\t\t\t\t\t((!oldHtml || newHtml.__html != oldHtml.__html) &&\n\t\t\t\t\t\tnewHtml.__html !== dom.innerHTML)\n\t\t\t\t) {\n\t\t\t\t\tdom.innerHTML = (newHtml && newHtml.__html) || '';\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tdiffProps(dom, newProps, oldProps, isSvg, isHydrating);\n\n\t\t// If the new vnode didn't have dangerouslySetInnerHTML, diff its children\n\t\tif (newHtml) {\n\t\t\tnewVNode._children = [];\n\t\t} else {\n\t\t\ti = newVNode.props.children;\n\t\t\tdiffChildren(\n\t\t\t\tdom,\n\t\t\t\tArray.isArray(i) ? i : [i],\n\t\t\t\tnewVNode,\n\t\t\t\toldVNode,\n\t\t\t\tglobalContext,\n\t\t\t\tisSvg && nodeType !== 'foreignObject',\n\t\t\t\texcessDomChildren,\n\t\t\t\tcommitQueue,\n\t\t\t\tdom.firstChild,\n\t\t\t\tisHydrating\n\t\t\t);\n\n\t\t\t// Remove children that are not part of any vnode.\n\t\t\tif (excessDomChildren != null) {\n\t\t\t\tfor (i = excessDomChildren.length; i--; ) {\n\t\t\t\t\tif (excessDomChildren[i] != null) removeNode(excessDomChildren[i]);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// (as above, don't diff props during hydration)\n\t\tif (!isHydrating) {\n\t\t\tif (\n\t\t\t\t'value' in newProps &&\n\t\t\t\t(i = newProps.value) !== undefined &&\n\t\t\t\t// #2756 For the <progress>-element the initial value is 0,\n\t\t\t\t// despite the attribute not being present. When the attribute\n\t\t\t\t// is missing the progress bar is treated as indeterminate.\n\t\t\t\t// To fix that we'll always update it when it is 0 for progress elements\n\t\t\t\t(i !== dom.value || (nodeType === 'progress' && !i))\n\t\t\t) {\n\t\t\t\tsetProperty(dom, 'value', i, oldProps.value, false);\n\t\t\t}\n\t\t\tif (\n\t\t\t\t'checked' in newProps &&\n\t\t\t\t(i = newProps.checked) !== undefined &&\n\t\t\t\ti !== dom.checked\n\t\t\t) {\n\t\t\t\tsetProperty(dom, 'checked', i, oldProps.checked, false);\n\t\t\t}\n\t\t}\n\t}\n\n\treturn dom;\n}\n\n/**\n * Invoke or update a ref, depending on whether it is a function or object ref.\n * @param {object|function} ref\n * @param {any} value\n * @param {import('../internal').VNode} vnode\n */\nexport function applyRef(ref, value, vnode) {\n\ttry {\n\t\tif (typeof ref == 'function') ref(value);\n\t\telse ref.current = value;\n\t} catch (e) {\n\t\toptions._catchError(e, vnode);\n\t}\n}\n\n/**\n * Unmount a virtual node from the tree and apply DOM changes\n * @param {import('../internal').VNode} vnode The virtual node to unmount\n * @param {import('../internal').VNode} parentVNode The parent of the VNode that\n * initiated the unmount\n * @param {boolean} [skipRemove] Flag that indicates that a parent node of the\n * current element is already detached from the DOM.\n */\nexport function unmount(vnode, parentVNode, skipRemove) {\n\tlet r;\n\tif (options.unmount) options.unmount(vnode);\n\n\tif ((r = vnode.ref)) {\n\t\tif (!r.current || r.current === vnode._dom) applyRef(r, null, parentVNode);\n\t}\n\n\tlet dom;\n\tif (!skipRemove && typeof vnode.type != 'function') {\n\t\tskipRemove = (dom = vnode._dom) != null;\n\t}\n\n\t// Must be set to `undefined` to properly clean up `_nextDom`\n\t// for which `null` is a valid value. See comment in `create-element.js`\n\tvnode._dom = vnode._nextDom = undefined;\n\n\tif ((r = vnode._component) != null) {\n\t\tif (r.componentWillUnmount) {\n\t\t\ttry {\n\t\t\t\tr.componentWillUnmount();\n\t\t\t} catch (e) {\n\t\t\t\toptions._catchError(e, parentVNode);\n\t\t\t}\n\t\t}\n\n\t\tr.base = r._parentDom = null;\n\t}\n\n\tif ((r = vnode._children)) {\n\t\tfor (let i = 0; i < r.length; i++) {\n\t\t\tif (r[i]) unmount(r[i], parentVNode, skipRemove);\n\t\t}\n\t}\n\n\tif (dom != null) removeNode(dom);\n}\n\n/** The `.render()` method for a PFC backing instance. */\nfunction doRender(props, state, context) {\n\treturn this.constructor(props, context);\n}\n","import { EMPTY_OBJ, EMPTY_ARR } from './constants';\nimport { commitRoot, diff } from './diff/index';\nimport { createElement, Fragment } from './create-element';\nimport options from './options';\n\n/**\n * Render a Preact virtual node into a DOM element\n * @param {import('./internal').ComponentChild} vnode The virtual node to render\n * @param {import('./internal').PreactElement} parentDom The DOM element to\n * render into\n * @param {import('./internal').PreactElement | object} [replaceNode] Optional: Attempt to re-use an\n * existing DOM tree rooted at `replaceNode`\n */\nexport function render(vnode, parentDom, replaceNode) {\n\tif (options._root) options._root(vnode, parentDom);\n\n\t// We abuse the `replaceNode` parameter in `hydrate()` to signal if we are in\n\t// hydration mode or not by passing the `hydrate` function instead of a DOM\n\t// element..\n\tlet isHydrating = typeof replaceNode === 'function';\n\n\t// To be able to support calling `render()` multiple times on the same\n\t// DOM node, we need to obtain a reference to the previous tree. We do\n\t// this by assigning a new `_children` property to DOM nodes which points\n\t// to the last rendered tree. By default this property is not present, which\n\t// means that we are mounting a new tree for the first time.\n\tlet oldVNode = isHydrating\n\t\t? null\n\t\t: (replaceNode && replaceNode._children) || parentDom._children;\n\n\tvnode = (\n\t\t(!isHydrating && replaceNode) ||\n\t\tparentDom\n\t)._children = createElement(Fragment, null, [vnode]);\n\n\t// List of effects that need to be called after diffing.\n\tlet commitQueue = [];\n\tdiff(\n\t\tparentDom,\n\t\t// Determine the new vnode tree and store it on the DOM element on\n\t\t// our custom `_children` property.\n\t\tvnode,\n\t\toldVNode || EMPTY_OBJ,\n\t\tEMPTY_OBJ,\n\t\tparentDom.ownerSVGElement !== undefined,\n\t\t!isHydrating && replaceNode\n\t\t\t? [replaceNode]\n\t\t\t: oldVNode\n\t\t\t? null\n\t\t\t: parentDom.firstChild\n\t\t\t? EMPTY_ARR.slice.call(parentDom.childNodes)\n\t\t\t: null,\n\t\tcommitQueue,\n\t\t!isHydrating && replaceNode\n\t\t\t? replaceNode\n\t\t\t: oldVNode\n\t\t\t? oldVNode._dom\n\t\t\t: parentDom.firstChild,\n\t\tisHydrating\n\t);\n\n\t// Flush all queued effects\n\tcommitRoot(commitQueue, vnode);\n}\n\n/**\n * Update an existing DOM element with data from a Preact virtual node\n * @param {import('./internal').ComponentChild} vnode The virtual node to render\n * @param {import('./internal').PreactElement} parentDom The DOM element to\n * update\n */\nexport function hydrate(vnode, parentDom) {\n\trender(vnode, parentDom, hydrate);\n}\n","/**\n * Find the closest error boundary to a thrown error and call it\n * @param {object} error The thrown value\n * @param {import('../internal').VNode} vnode The vnode that threw\n * the error that was caught (except for unmounting when this parameter\n * is the highest parent that was being unmounted)\n */\nexport function _catchError(error, vnode) {\n\t/** @type {import('../internal').Component} */\n\tlet component, ctor, handled;\n\n\tfor (; (vnode = vnode._parent); ) {\n\t\tif ((component = vnode._component) && !component._processingException) {\n\t\t\ttry {\n\t\t\t\tctor = component.constructor;\n\n\t\t\t\tif (ctor && ctor.getDerivedStateFromError != null) {\n\t\t\t\t\tcomponent.setState(ctor.getDerivedStateFromError(error));\n\t\t\t\t\thandled = component._dirty;\n\t\t\t\t}\n\n\t\t\t\tif (component.componentDidCatch != null) {\n\t\t\t\t\tcomponent.componentDidCatch(error);\n\t\t\t\t\thandled = component._dirty;\n\t\t\t\t}\n\n\t\t\t\t// This is an error boundary. Mark it as having bailed out, and whether it was mid-hydration.\n\t\t\t\tif (handled) {\n\t\t\t\t\treturn (component._pendingError = component);\n\t\t\t\t}\n\t\t\t} catch (e) {\n\t\t\t\terror = e;\n\t\t\t}\n\t\t}\n\t}\n\n\tthrow error;\n}\n","import { enqueueRender } from './component';\n\nexport let i = 0;\n\nexport function createContext(defaultValue, contextId) {\n\tcontextId = '__cC' + i++;\n\n\tconst context = {\n\t\t_id: contextId,\n\t\t_defaultValue: defaultValue,\n\t\t/** @type {import('./internal').FunctionComponent} */\n\t\tConsumer(props, contextValue) {\n\t\t\t// return props.children(\n\t\t\t// \tcontext[contextId] ? context[contextId].props.value : defaultValue\n\t\t\t// );\n\t\t\treturn props.children(contextValue);\n\t\t},\n\t\t/** @type {import('./internal').FunctionComponent} */\n\t\tProvider(props) {\n\t\t\tif (!this.getChildContext) {\n\t\t\t\tlet subs = [];\n\t\t\t\tlet ctx = {};\n\t\t\t\tctx[contextId] = this;\n\n\t\t\t\tthis.getChildContext = () => ctx;\n\n\t\t\t\tthis.shouldComponentUpdate = function(_props) {\n\t\t\t\t\tif (this.props.value !== _props.value) {\n\t\t\t\t\t\t// I think the forced value propagation here was only needed when `options.debounceRendering` was being bypassed:\n\t\t\t\t\t\t// https://github.com/preactjs/preact/commit/4d339fb803bea09e9f198abf38ca1bf8ea4b7771#diff-54682ce380935a717e41b8bfc54737f6R358\n\t\t\t\t\t\t// In those cases though, even with the value corrected, we're double-rendering all nodes.\n\t\t\t\t\t\t// It might be better to just tell folks not to use force-sync mode.\n\t\t\t\t\t\t// Currently, using `useContext()` in a class component will overwrite its `this.context` value.\n\t\t\t\t\t\t// subs.some(c => {\n\t\t\t\t\t\t// \tc.context = _props.value;\n\t\t\t\t\t\t// \tenqueueRender(c);\n\t\t\t\t\t\t// });\n\n\t\t\t\t\t\t// subs.some(c => {\n\t\t\t\t\t\t// \tc.context[contextId] = _props.value;\n\t\t\t\t\t\t// \tenqueueRender(c);\n\t\t\t\t\t\t// });\n\t\t\t\t\t\tsubs.some(enqueueRender);\n\t\t\t\t\t}\n\t\t\t\t};\n\n\t\t\t\tthis.sub = c => {\n\t\t\t\t\tsubs.push(c);\n\t\t\t\t\tlet old = c.componentWillUnmount;\n\t\t\t\t\tc.componentWillUnmount = () => {\n\t\t\t\t\t\tsubs.splice(subs.indexOf(c), 1);\n\t\t\t\t\t\tif (old) old.call(c);\n\t\t\t\t\t};\n\t\t\t\t};\n\t\t\t}\n\n\t\t\treturn props.children;\n\t\t}\n\t};\n\n\t// Devtools needs access to the context object when it\n\t// encounters a Provider. This is necessary to support\n\t// setting `displayName` on the context object instead\n\t// of on the component itself. See:\n\t// https://reactjs.org/docs/context.html#contextdisplayname\n\n\treturn (context.Provider._contextRef = context.Consumer.contextType = context);\n}\n","export const Styles: { [styleAlias: string]: Partial<CSSStyleDeclaration> | any} = {\n Error: {\n color: \"red\",\n },\n Alert: {\n error: {\n color: \"red\"\n },\n warning: {\n color: \"yellow\"\n },\n info: {\n color: \"black\"\n }\n },\n Darken: {\n position: \"fixed\",\n top: 0,\n left: 0,\n opacity: 0.5,\n backgroundColor: \"#000\",\n width: \"100vw\",\n height: \"100vh\",\n zIndex: 150,\n webkitBackdropFilter: \"blur(2px)\",\n backdropFilter: \"blur(2px)\",\n },\n DialogOuter: {\n position: \"fixed\",\n top: 0,\n left: 0,\n width: \"100vw\",\n height: \"100vh\",\n zIndex: 150,\n alignItems: \"center\",\n display: \"flex\",\n justifyContent: \"center\",\n },\n DialogInner: {\n position: \"relative\",\n color: \"#222\",\n backgroundColor: \"#fff\",\n padding: \"30px\",\n marginBottom: \"2em\",\n maxWidth: \"90%\",\n maxHeight: \"90%\",\n overflowY: \"auto\",\n border: \"3px solid #3d3d5d\",\n borderRadius: \"8px\",\n boxShadow: \"0 0 80px 10px #666\",\n width: \"auto\"\n },\n Input: {\n height: \"35px\",\n width: \"17em\",\n borderColor: \"#ccf4\",\n outline: \"none\",\n fontSize: \"17pt\",\n padding: \"8px\"\n \n }\n};\n","import { Styles } from './Styles';\nimport { ComponentChildren, h } from 'preact';\n\nexport function Dialog({ children }: { children?: ComponentChildren }) {\n return (\n <div>\n <div style={Styles.Darken} />\n <div style={Styles.DialogOuter}>\n <div style={Styles.DialogInner}>{children}</div>\n </div>\n </div>\n );\n}\n","import { options } from 'preact';\n\n/** @type {number} */\nlet currentIndex;\n\n/** @type {import('./internal').Component} */\nlet currentComponent;\n/**\n * Keep track of the previous component so that we can set\n * `currentComponent` to `null` and throw when a hook is invoked\n * outside of render\n * @type {import('./internal').Component}\n */\nlet previousComponent;\n\n/** @type {number} */\nlet currentHook = 0;\n\n/** @type {Array<import('./internal').Component>} */\nlet afterPaintEffects = [];\n\nlet oldBeforeDiff = options._diff;\nlet oldBeforeRender = options._render;\nlet oldAfterDiff = options.diffed;\nlet oldCommit = options._commit;\nlet oldBeforeUnmount = options.unmount;\n\nconst RAF_TIMEOUT = 100;\nlet prevRaf;\n\noptions._diff = vnode => {\n\tcurrentComponent = null;\n\tif (oldBeforeDiff) oldBeforeDiff(vnode);\n};\n\noptions._render = vnode => {\n\tif (oldBeforeRender) oldBeforeRender(vnode);\n\n\tcurrentComponent = vnode._component;\n\tcurrentIndex = 0;\n\n\tconst hooks = currentComponent.__hooks;\n\tif (hooks) {\n\t\thooks._pendingEffects.forEach(invokeCleanup);\n\t\thooks._pendingEffects.forEach(invokeEffect);\n\t\thooks._pendingEffects = [];\n\t}\n};\n\noptions.diffed = vnode => {\n\tif (oldAfterDiff) oldAfterDiff(vnode);\n\n\tconst c = vnode._component;\n\tif (c && c.__hooks && c.__hooks._pendingEffects.length) {\n\t\tafterPaint(afterPaintEffects.push(c));\n\t}\n\tcurrentComponent = previousComponent;\n};\n\noptions._commit = (vnode, commitQueue) => {\n\tcommitQueue.some(component => {\n\t\ttry {\n\t\t\tcomponent._renderCallbacks.forEach(invokeCleanup);\n\t\t\tcomponent._renderCallbacks = component._renderCallbacks.filter(cb =>\n\t\t\t\tcb._value ? invokeEffect(cb) : true\n\t\t\t);\n\t\t} catch (e) {\n\t\t\tcommitQueue.some(c => {\n\t\t\t\tif (c._renderCallbacks) c._renderCallbacks = [];\n\t\t\t});\n\t\t\tcommitQueue = [];\n\t\t\toptions._catchError(e, component._vnode);\n\t\t}\n\t});\n\n\tif (oldCommit) oldCommit(vnode, commitQueue);\n};\n\noptions.unmount = vnode => {\n\tif (oldBeforeUnmount) oldBeforeUnmount(vnode);\n\n\tconst c = vnode._component;\n\tif (c && c.__hooks) {\n\t\ttry {\n\t\t\tc.__hooks._list.forEach(invokeCleanup);\n\t\t} catch (e) {\n\t\t\toptions._catchError(e, c._vnode);\n\t\t}\n\t}\n};\n\n/**\n * Get a hook's state from the currentComponent\n * @param {number} index The index of the hook to get\n * @param {number} type The index of the hook to get\n * @returns {any}\n */\nfunction getHookState(index, type) {\n\tif (options._hook) {\n\t\toptions._hook(currentComponent, index, currentHook || type);\n\t}\n\tcurrentHook = 0;\n\n\t// Largely inspired by:\n\t// * https://github.com/michael-klein/funcy.js/blob/f6be73468e6ec46b0ff5aa3cc4c9baf72a29025a/src/hooks/core_hooks.mjs\n\t// * https://github.com/michael-klein/funcy.js/blob/650beaa58c43c33a74820a3c98b3c7079cf2e333/src/renderer.mjs\n\t// Other implementations to look at:\n\t// * https://codesandbox.io/s/mnox05qp8\n\tconst hooks =\n\t\tcurrentComponent.__hooks ||\n\t\t(currentComponent.__hooks = {\n\t\t\t_list: [],\n\t\t\t_pendingEffects: []\n\t\t});\n\n\tif (index >= hooks._list.length) {\n\t\thooks._list.push({});\n\t}\n\treturn hooks._list[index];\n}\n\n/**\n * @param {import('./index').StateUpdater<any>} [initialState]\n */\nexport function useState(initialState) {\n\tcurrentHook = 1;\n\treturn useReducer(invokeOrReturn, initialState);\n}\n\n/**\n * @param {import('./index').Reducer<any, any>} reducer\n * @param {import('./index').StateUpdater<any>} initialState\n * @param {(initialState: any) => void} [init]\n * @returns {[ any, (state: any) => void ]}\n */\nexport function useReducer(reducer, initialState, init) {\n\t/** @type {import('./internal').ReducerHookState} */\n\tconst hookState = getHookState(currentIndex++, 2);\n\thookState._reducer = reducer;\n\tif (!hookState._component) {\n\t\thookState._value = [\n\t\t\t!init ? invokeOrReturn(undefined, initialState) : init(initialState),\n\n\t\t\taction => {\n\t\t\t\tconst nextValue = hookState._reducer(hookState._value[0], action);\n\t\t\t\tif (hookState._value[0] !== nextValue) {\n\t\t\t\t\thookState._value = [nextValue, hookState._value[1]];\n\t\t\t\t\thookState._component.setState({});\n\t\t\t\t}\n\t\t\t}\n\t\t];\n\n\t\thookState._component = currentComponent;\n\t}\n\n\treturn hookState._value;\n}\n\n/**\n * @param {import('./internal').Effect} callback\n * @param {any[]} args\n */\nexport function useEffect(callback, args) {\n\t/** @type {import('./internal').EffectHookState} */\n\tconst state = getHookState(currentIndex++, 3);\n\tif (!options._skipEffects && argsChanged(state._args, args)) {\n\t\tstate._value = callback;\n\t\tstate._args = args;\n\n\t\tcurrentComponent.__hooks._pendingEffects.push(state);\n\t}\n}\n\n/**\n * @param {import('./internal').Effect} callback\n * @param {any[]} args\n */\nexport function useLayoutEffect(callback, args) {\n\t/** @type {import('./internal').EffectHookState} */\n\tconst state = getHookState(currentIndex++, 4);\n\tif (!options._skipEffects && argsChanged(state._args, args)) {\n\t\tstate._value = callback;\n\t\tstate._args = args;\n\n\t\tcurrentComponent._renderCallbacks.push(state);\n\t}\n}\n\nexport function useRef(initialValue) {\n\tcurrentHook = 5;\n\treturn useMemo(() => ({ current: initialValue }), []);\n}\n\n/**\n * @param {object} ref\n * @param {() => object} createHandle\n * @param {any[]} args\n */\nexport function useImperativeHandle(ref, createHandle, args) {\n\tcurrentHook = 6;\n\tuseLayoutEffect(\n\t\t() => {\n\t\t\tif (typeof ref == 'function') ref(createHandle());\n\t\t\telse if (ref) ref.current = createHandle();\n\t\t},\n\t\targs == null ? args : args.concat(ref)\n\t);\n}\n\n/**\n * @param {() => any} factory\n * @param {any[]} args\n */\nexport function useMemo(factory, args) {\n\t/** @type {import('./internal').MemoHookState} */\n\tconst state = getHookState(currentIndex++, 7);\n\tif (argsChanged(state._args, args)) {\n\t\tstate._value = factory();\n\t\tstate._args = args;\n\t\tstate._factory = factory;\n\t}\n\n\treturn state._value;\n}\n\n/**\n * @param {() => void} callback\n * @param {any[]} args\n */\nexport function useCallback(callback, args) {\n\tcurrentHook = 8;\n\treturn useMemo(() => callback, args);\n}\n\n/**\n * @param {import('./internal').PreactContext} context\n */\nexport function useContext(context) {\n\tconst provider = currentComponent.context[context._id];\n\t// We could skip this call here, but than we'd not call\n\t// `options._hook`. We need to do that in order to make\n\t// the devtools aware of this hook.\n\t/** @type {import('./internal').ContextHookState} */\n\tconst state = getHookState(currentIndex++, 9);\n\t// The devtools needs access to the context object to\n\t// be able to pull of the default value when no provider\n\t// is present in the tree.\n\tstate._context = context;\n\tif (!provider) return context._defaultValue;\n\t// This is probably not safe to convert to \"!\"\n\tif (state._value == null) {\n\t\tstate._value = true;\n\t\tprovider.sub(currentComponent);\n\t}\n\treturn provider.props.value;\n}\n\n/**\n * Display a custom label for a custom hook for the devtools panel\n * @type {<T>(value: T, cb?: (value: T) => string | number) => void}\n */\nexport function useDebugValue(value, formatter) {\n\tif (options.useDebugValue) {\n\t\toptions.useDebugValue(formatter ? formatter(value) : value);\n\t}\n}\n\n/**\n * @param {(error: any) => void} cb\n */\nexport function useErrorBoundary(cb) {\n\t/** @type {import('./internal').ErrorBoundaryHookState} */\n\tconst state = getHookState(currentIndex++, 10);\n\tconst errState = useState();\n\tstate._value = cb;\n\tif (!currentComponent.componentDidCatch) {\n\t\tcurrentComponent.componentDidCatch = err => {\n\t\t\tif (state._value) state._value(err);\n\t\t\terrState[1](err);\n\t\t};\n\t}\n\treturn [\n\t\terrState[0],\n\t\t() => {\n\t\t\terrState[1](undefined);\n\t\t}\n\t];\n}\n\n/**\n * After paint effects consumer.\n */\nfunction flushAfterPaintEffects() {\n\tafterPaintEffects.forEach(component => {\n\t\tif (component._parentDom) {\n\t\t\ttry {\n\t\t\t\tcomponent.__hooks._pendingEffects.forEach(invokeCleanup);\n\t\t\t\tcomponent.__hooks._pendingEffects.forEach(invokeEffect);\n\t\t\t\tcomponent.__hooks._pendingEffects = [];\n\t\t\t} catch (e) {\n\t\t\t\tcomponent.__hooks._pendingEffects = [];\n\t\t\t\toptions._catchError(e, component._vnode);\n\t\t\t}\n\t\t}\n\t});\n\tafterPaintEffects = [];\n}\n\nlet HAS_RAF = typeof requestAnimationFrame == 'function';\n\n/**\n * Schedule a callback to be invoked after the browser has a chance to paint a new frame.\n * Do this by combining requestAnimationFrame (rAF) + setTimeout to invoke a callback after\n * the next browser frame.\n *\n * Also, schedule a timeout in parallel to the the rAF to ensure the callback is invoked\n * even if RAF doesn't fire (for example if the browser tab is not visible)\n *\n * @param {() => void} callback\n */\nfunction afterNextFrame(callback) {\n\tconst done = () => {\n\t\tclearTimeout(timeout);\n\t\tif (HAS_RAF) cancelAnimationFrame(raf);\n\t\tsetTimeout(callback);\n\t};\n\tconst timeout = setTimeout(done, RAF_TIMEOUT);\n\n\tlet raf;\n\tif (HAS_RAF) {\n\t\traf = requestAnimationFrame(done);\n\t}\n}\n\n// Note: if someone used options.debounceRendering = requestAnimationFrame,\n// then effects will ALWAYS run on the NEXT frame instead of the current one, incurring a ~16ms delay.\n// Perhaps this is not such a big deal.\n/**\n * Schedule afterPaintEffects flush after the browser paints\n * @param {number} newQueueLength\n */\nfunction afterPaint(newQueueLength) {\n\tif (newQueueLength === 1 || prevRaf !== options.requestAnimationFrame) {\n\t\tprevRaf = options.requestAnimationFrame;\n\t\t(prevRaf || afterNextFrame)(flushAfterPaintEffects);\n\t}\n}\n\n/**\n * @param {import('./internal').EffectHookState} hook\n */\nfunction invokeCleanup(hook) {\n\t// A hook cleanup can introduce a call to render which creates a new root, this will call options.vnode\n\t// and move the currentComponent away.\n\tconst comp = currentComponent;\n\tif (typeof hook._cleanup == 'function') hook._cleanup();\n\tcurrentComponent = comp;\n}\n\n/**\n * Invoke a Hook's effect\n * @param {import('./internal').EffectHookState} hook\n */\nfunction invokeEffect(hook) {\n\t// A hook call can introduce a call to render which creates a new root, this will call options.vnode\n\t// and move the currentComponent away.\n\tconst comp = currentComponent;\n\thook._cleanup = hook._value();\n\tcurrentComponent = comp;\n}\n\n/**\n * @param {any[]} oldArgs\n * @param {any[]} newArgs\n */\nfunction argsChanged(oldArgs, newArgs) {\n\treturn (\n\t\t!oldArgs ||\n\t\toldArgs.length !== newArgs.length ||\n\t\tnewArgs.some((arg, index) => arg !== oldArgs[index])\n\t);\n}\n\nfunction invokeOrReturn(arg, f) {\n\treturn typeof f == 'function' ? f(arg) : f;\n}\n","import { DXCAlert } from \"../types/DXCAlert\";\n\nexport function resolveText({message, messageCode, messageParams}: DXCAlert) {\n return message.replace(/\\{\\w+\\}/ig, n => messageParams[n.substr(1, n.length-2)]);\n}\n","import { Dialog } from './Dialog';\nimport { Styles } from './Styles';\nimport { h, Fragment } from 'preact';\nimport { useEffect, useLayoutEffect, useRef, useState } from 'preact/hooks';\nimport {\n DXCGenericUserInteraction,\n DXCUserInteraction,\n} from '../types/DXCUserInteraction';\nimport { resolveText } from '../helpers/resolveText';\nimport { DXCInputField } from '../types/DXCInputField';\n\nexport function LoginDialog({\n title,\n alerts,\n fields,\n onCancel,\n onSubmit,\n}: DXCGenericUserInteraction<string, { [name: string]: DXCInputField }>) {\n const [params, setParams] = useState<{ [param: string]: string }>({});\n\n const firstFieldRef = useRef<HTMLInputElement>();\n useLayoutEffect(()=>firstFieldRef.current?.focus(), []);\n\n return (\n <Dialog>\n <>\n <h3 style={Styles.WindowHeader}>{title}</h3>\n {alerts.map((alert) => (\n <p style={Styles.Alert[alert.type]}>{resolveText(alert)}</p>\n ))}\n <form onSubmit={ev => {\n ev.preventDefault();\n onSubmit(params);\n }}>\n {Object.entries(fields).map(\n ([fieldName, { type, label, placeholder }], idx) => (\n <label style={Styles.Label}>\n {label ? `${label}: ` : ''}\n <input\n ref={idx === 0 ? firstFieldRef : undefined}\n type={type}\n name={fieldName}\n autoComplete=\"on\"\n style={Styles.Input}\n autoFocus\n placeholder={placeholder}\n value={params[fieldName] || ''}\n onInput={(ev) =>\n setParams({ ...params, [fieldName]: valueTransformer(type, ev.target?.['value']) })\n }\n />\n </label>\n )\n )}\n </form>\n </>\n <div style={Styles.ButtonsDiv}>\n <button type=\"submit\" style={Styles.Button} onClick={() => onSubmit(params)}>\n Submit\n </button>\n <button style={Styles.Button} onClick={onCancel}>\n Cancel\n </button>\n </div>\n </Dialog>\n );\n}\n\nfunction valueTransformer(type: string, value: string) {\n switch(type) {\n case \"email\": return value.toLowerCase();\n case \"otp\": return value.toUpperCase();\n default: return value;\n }\n}","import Dexie from \"dexie\";\nimport \"../extend-dexie-interface\";\nimport { h, Component } from \"preact\";\nimport { from, Observer, Subscription } from \"rxjs\";\nimport { LoginDialog } from './LoginDialog';\nimport { Styles } from \"./Styles\";\nimport { DXCGenericUserInteraction, DXCUserInteraction } from \"../types/DXCUserInteraction\";\nimport { DXCInputField } from \"../types/DXCInputField\";\nimport { DexieCloudDB } from \"../db/DexieCloudDB\";\nimport * as preact from \"preact\";\n\nexport interface Props {\n db: Dexie;\n}\n\ninterface State {\n userInteraction: DXCUserInteraction | undefined;\n}\n\nexport default class LoginGui extends Component<Props, State> {\n subscription?: Subscription;\n observer = (userInteraction: DXCUserInteraction | undefined) => this.setState({userInteraction});\n\n constructor(props: Props) {\n super(props);\n this.state = { userInteraction: undefined };\n }\n\n componentDidMount() {\n this.subscription = from(this.props.db.cloud.userInteraction).subscribe(this.observer);\n }\n\n componentWillUnmount() {\n if (this.subscription) {\n this.subscription.unsubscribe();\n delete this.subscription;\n }\n }\n\n render(props: Props, {userInteraction}: State) {\n if (!userInteraction) return null;\n //if (props.db.cloud.userInteraction.observers.length > 1) return null; // Someone else subscribes.\n return <LoginDialog {...userInteraction as DXCGenericUserInteraction<string, {[name: string]: DXCInputField}>} />;\n }\n}\n\nexport function setupDefaultGUI(db: Dexie) {\n const el = document.createElement('div');\n document.body.appendChild(el);\n preact.render(<LoginGui db={db.vip} />, el);\n\n let closed = false;\n\n return {\n unsubscribe() {\n el.remove();\n closed = true;\n },\n get closed() {\n return closed;\n }\n }\n}\n\n// TODO:\n/*\n * Gjort klart allt kring user interaction förutom att mounta default-ui på ett element.\n * Också att kolla först om nån annan subscribar och i så fall inte göra nåt.\n*/","import { combineLatest, Observable, of } from 'rxjs';\nimport { debounceTime, map, startWith, switchMap } from 'rxjs/operators';\nimport { DexieCloudDB } from './db/DexieCloudDB';\nimport { isOnline } from './sync/isOnline';\nimport { SyncState } from './types/SyncState';\nimport { userIsActive, userIsReallyActive } from './userIsActive';\n\nexport function computeSyncState(db: DexieCloudDB): Observable<SyncState> {\n let _prevStatus = db.cloud.webSocketStatus.value;\n const lazyWebSocketStatus = db.cloud.webSocketStatus.pipe(\n switchMap((status) => {\n const prevStatus = _prevStatus;\n _prevStatus = status;\n const rv = of(status);\n switch (status) {\n // A normal scenario is that the WS reconnects and falls shortly in disconnected-->connection-->connected.\n // Don't distract user with this unless these things take more time than normal:\n\n // Only show disconnected if disconnected more than 500ms, or if we can\n // see that the user is indeed not active.\n case 'disconnected':\n return userIsActive.value ? rv.pipe(debounceTime(500)) : rv;\n\n // Only show connecting if previous state was 'not-started' or 'error', or if\n // the time it takes to connect goes beyond 4 seconds.\n case 'connecting':\n return prevStatus === 'not-started' || prevStatus === 'error'\n ? rv\n : rv.pipe(debounceTime(4000));\n default:\n return rv;\n }\n })\n );\n return combineLatest([\n lazyWebSocketStatus,\n db.syncStateChangedEvent.pipe(startWith({ phase: 'initial' } as SyncState)),\n userIsReallyActive\n ]).pipe(\n map(([status, syncState, userIsActive]) => {\n let { phase, error, progress } = syncState;\n let adjustedStatus = status;\n if (phase === 'error') {\n // Let users only rely on the status property to display an icon.\n // If there's an error in the sync phase, let it show on that\n // status icon also.\n adjustedStatus = 'error';\n }\n if (status === 'not-started') {\n // If websocket isn't yet connected becase we're doing\n // the startup sync, let the icon show the symbol for connecting.\n if (phase === 'pushing' || phase === 'pulling') {\n adjustedStatus = 'connecting';\n }\n } \n const previousPhase = db.cloud.syncState.value.phase;\n //const previousStatus = db.cloud.syncState.value.status;\n if (previousPhase === 'error' && (syncState.phase === 'pushing' || syncState.phase === 'pulling')) {\n // We were in an errored state but is now doing sync. Show \"connecting\" icon.\n adjustedStatus = 'connecting';\n }\n /*if (syncState.phase === 'in-sync' && adjustedStatus === 'connecting') {\n adjustedStatus = 'connected';\n }*/\n \n if (!userIsActive) {\n adjustedStatus = 'disconnected';\n }\n\n const retState: SyncState = {\n phase,\n error,\n progress,\n status: isOnline ? adjustedStatus : 'offline',\n };\n\n return retState;\n })\n );\n}\n","import Dexie, { liveQuery, Subscription } from 'dexie';\nimport { getDbNameFromDbUrl } from 'dexie-cloud-common';\nimport { BehaviorSubject, combineLatest, from, fromEvent } from 'rxjs';\nimport { filter, map, skip, startWith, switchMap, take } from 'rxjs/operators';\nimport { login } from './authentication/login';\nimport { UNAUTHORIZED_USER } from './authentication/UNAUTHORIZED_USER';\nimport { DexieCloudDB } from './db/DexieCloudDB';\nimport { PersistedSyncState } from './db/entities/PersistedSyncState';\nimport { DexieCloudOptions } from './DexieCloudOptions';\nimport { DISABLE_SERVICEWORKER_STRATEGY } from './DISABLE_SERVICEWORKER_STRATEGY';\nimport './extend-dexie-interface';\nimport { DexieCloudSyncOptions } from './extend-dexie-interface';\nimport { dbOnClosed } from './helpers/dbOnClosed';\nimport { IS_SERVICE_WORKER } from './helpers/IS_SERVICE_WORKER';\nimport { throwVersionIncrementNeeded } from './helpers/throwVersionIncrementNeeded';\nimport { createIdGenerationMiddleware } from './middlewares/createIdGenerationMiddleware';\nimport { createImplicitPropSetterMiddleware } from './middlewares/createImplicitPropSetterMiddleware';\nimport { createMutationTrackingMiddleware } from './middlewares/createMutationTrackingMiddleware';\n//import { dexieCloudSyncProtocol } from \"./dexieCloudSyncProtocol\";\nimport { overrideParseStoresSpec } from './overrideParseStoresSpec';\nimport { performInitialSync } from './performInitialSync';\nimport { connectWebSocket } from './sync/connectWebSocket';\nimport { isSyncNeeded } from './sync/isSyncNeeded';\nimport { LocalSyncWorker } from './sync/LocalSyncWorker';\nimport {\n registerPeriodicSyncEvent,\n registerSyncEvent,\n} from './sync/registerSyncEvent';\nimport { triggerSync } from './sync/triggerSync';\nimport { DXCUserInteraction } from './types/DXCUserInteraction';\nimport { SyncState } from './types/SyncState';\nimport { updateSchemaFromOptions } from './updateSchemaFromOptions';\nimport { verifySchema } from './verifySchema';\nimport { setupDefaultGUI } from './default-ui';\nimport { DXCWebSocketStatus } from './DXCWebSocketStatus';\nimport { computeSyncState } from './computeSyncState';\n\nexport { DexieCloudTable } from './extend-dexie-interface';\n\nexport function dexieCloud(dexie: Dexie) {\n const origIdbName = dexie.name;\n //\n //\n //\n const currentUserEmitter = new BehaviorSubject(UNAUTHORIZED_USER);\n const subscriptions: Subscription[] = [];\n\n // local sync worker - used when there's no service worker.\n let localSyncWorker: { start: () => void; stop: () => void } | null = null;\n dexie.on(\n 'ready',\n async (dexie: Dexie) => {\n try {\n await onDbReady(dexie);\n } catch (error) {\n console.error(error);\n // Make sure to succeed with database open even if network is down.\n }\n },\n true // true = sticky\n );\n\n /** Void starting subscribers after a close has happened. */\n let closed = false;\n function throwIfClosed() {\n if (closed) throw new Dexie.DatabaseClosedError();\n }\n\n dbOnClosed(dexie, () => {\n subscriptions.forEach((subscription) => subscription.unsubscribe());\n closed = true;\n localSyncWorker && localSyncWorker.stop();\n localSyncWorker = null;\n currentUserEmitter.next(UNAUTHORIZED_USER);\n });\n\n dexie.cloud = {\n version: '{version}',\n options: null,\n schema: null,\n serverState: null,\n get currentUserId() {\n return currentUserEmitter.value.userId || UNAUTHORIZED_USER.userId!;\n },\n currentUser: currentUserEmitter,\n syncState: new BehaviorSubject<SyncState>({\n phase: 'initial',\n status: 'not-started',\n }),\n persistedSyncState: new BehaviorSubject<PersistedSyncState | undefined>(\n undefined\n ),\n userInteraction: new BehaviorSubject<DXCUserInteraction | undefined>(\n undefined\n ),\n webSocketStatus: new BehaviorSubject<DXCWebSocketStatus>('not-started'),\n async login(hint) {\n const db = DexieCloudDB(dexie);\n await db.cloud.sync();\n await login(db, hint);\n },\n configure(options: DexieCloudOptions) {\n dexie.cloud.options = options;\n if (options.databaseUrl) {\n // @ts-ignore\n dexie.name = `${origIdbName}-${getDbNameFromDbUrl(\n options.databaseUrl\n )}`;\n DexieCloudDB(dexie).reconfigure(); // Update observable from new dexie.name\n }\n updateSchemaFromOptions(dexie.cloud.schema, dexie.cloud.options);\n },\n async sync(\n { wait, purpose }: DexieCloudSyncOptions = { wait: true, purpose: \"push\" }\n ) {\n if (wait === undefined) wait = true;\n const db = DexieCloudDB(dexie);\n if (purpose === \"pull\") {\n const syncState = db.cloud.persistedSyncState.value;\n triggerSync(db, purpose);\n if (wait) {\n const newSyncState = await db.cloud.persistedSyncState\n .pipe(\n filter(\n (newSyncState) =>\n newSyncState?.timestamp != null &&\n (!syncState || newSyncState.timestamp > syncState.timestamp!)\n ),\n take(1)\n )\n .toPromise();\n if (newSyncState?.error) {\n throw new Error(`Sync error: ` + newSyncState.error);\n }\n }\n } else if (await isSyncNeeded(db)) {\n const syncState = db.cloud.persistedSyncState.value;\n triggerSync(db, purpose);\n if (wait) {\n console.debug('db.cloud.login() is waiting for sync completion...');\n await from(\n liveQuery(async () => {\n const syncNeeded = await isSyncNeeded(db);\n const newSyncState = await db.getPersistedSyncState();\n if (\n newSyncState?.timestamp !== syncState?.timestamp &&\n newSyncState?.error\n )\n throw new Error(`Sync error: ` + newSyncState.error);\n return syncNeeded;\n })\n )\n .pipe(\n filter((isNeeded) => !isNeeded),\n take(1)\n )\n .toPromise();\n console.debug(\n 'Done waiting for sync completion because we have nothing to push anymore'\n );\n }\n }\n },\n };\n\n dexie.Version.prototype['_parseStoresSpec'] = Dexie.override(\n dexie.Version.prototype['_parseStoresSpec'],\n (origFunc) => overrideParseStoresSpec(origFunc, dexie)\n );\n\n dexie.use(\n createMutationTrackingMiddleware({\n currentUserObservable: dexie.cloud.currentUser,\n db: DexieCloudDB(dexie),\n })\n );\n dexie.use(createImplicitPropSetterMiddleware(DexieCloudDB(dexie)));\n dexie.use(createIdGenerationMiddleware(DexieCloudDB(dexie)));\n\n async function onDbReady(dexie: Dexie) {\n closed = false; // As Dexie calls us, we are not closed anymore. Maybe reopened? Remember db.ready event is registered with sticky flag!\n const db = DexieCloudDB(dexie);\n // Setup default GUI:\n if (!IS_SERVICE_WORKER) {\n if (!db.cloud.options?.customLoginGui) {\n subscriptions.push(setupDefaultGUI(dexie));\n }\n subscriptions.push(computeSyncState(db).subscribe(dexie.cloud.syncState));\n }\n\n //verifyConfig(db.cloud.options); Not needed (yet at least!)\n // Verify the user has allowed version increment.\n if (!db.tables.every((table) => table.core)) {\n throwVersionIncrementNeeded();\n }\n const swRegistrations =\n 'serviceWorker' in navigator\n ? await navigator.serviceWorker.getRegistrations()\n : [];\n\n const initiallySynced = await db.transaction(\n 'rw',\n db.$syncState,\n async () => {\n const { options, schema } = db.cloud;\n const [persistedOptions, persistedSchema, persistedSyncState] =\n await Promise.all([\n db.getOptions(),\n db.getSchema(),\n db.getPersistedSyncState(),\n ]);\n if (!options) {\n // Options not specified programatically (use case for SW!)\n // Take persisted options:\n db.cloud.options = persistedOptions || null;\n } else if (\n !persistedOptions ||\n JSON.stringify(persistedOptions) !== JSON.stringify(options)\n ) {\n // Update persisted options:\n await db.$syncState.put(options, 'options');\n }\n if (\n db.cloud.options?.tryUseServiceWorker &&\n 'serviceWorker' in navigator &&\n swRegistrations.length > 0 &&\n !DISABLE_SERVICEWORKER_STRATEGY\n ) {\n // * Configured for using service worker if available.\n // * Browser supports service workers\n // * There are at least one service worker registration\n console.debug('Dexie Cloud Addon: Using service worker');\n db.cloud.usingServiceWorker = true;\n } else {\n // Not configured for using service worker or no service worker\n // registration exists. Don't rely on service worker to do any job.\n // Use LocalSyncWorker instead.\n if (db.cloud.options?.tryUseServiceWorker && !IS_SERVICE_WORKER) {\n console.debug(\n 'dexie-cloud-addon: Not using service worker.',\n swRegistrations.length === 0\n ? 'No SW registrations found.'\n : 'serviceWorker' in navigator && DISABLE_SERVICEWORKER_STRATEGY\n ? 'Avoiding SW background sync and SW periodic bg sync for this browser due to browser bugs.'\n : 'navigator.serviceWorker not present'\n );\n }\n db.cloud.usingServiceWorker = false;\n }\n updateSchemaFromOptions(schema, db.cloud.options);\n updateSchemaFromOptions(persistedSchema, db.cloud.options);\n if (!schema) {\n // Database opened dynamically (use case for SW!)\n // Take persisted schema:\n db.cloud.schema = persistedSchema || null;\n } else if (\n !persistedSchema ||\n JSON.stringify(persistedSchema) !== JSON.stringify(schema)\n ) {\n // Update persisted schema (but don't overwrite table prefixes)\n const newPersistedSchema = persistedSchema || {};\n for (const [table, tblSchema] of Object.entries(schema)) {\n const newTblSchema = newPersistedSchema[table];\n if (!newTblSchema) {\n newPersistedSchema[table] = { ...tblSchema };\n } else {\n newTblSchema.markedForSync = tblSchema.markedForSync;\n tblSchema.deleted = newTblSchema.deleted;\n newTblSchema.generatedGlobalId = tblSchema.generatedGlobalId;\n }\n }\n await db.$syncState.put(newPersistedSchema, 'schema');\n\n // Make sure persisted table prefixes are being used instead of computed ones:\n // Let's assign all props as the newPersistedSchems should be what we should be working with.\n Object.assign(schema, newPersistedSchema);\n }\n return persistedSyncState?.initiallySynced;\n }\n );\n\n if (initiallySynced) {\n db.setInitiallySynced(true);\n }\n\n verifySchema(db);\n\n if (db.cloud.options?.databaseUrl && !initiallySynced) {\n await performInitialSync(db, db.cloud.options, db.cloud.schema!);\n db.setInitiallySynced(true);\n }\n\n // Manage CurrentUser observable:\n throwIfClosed();\n if (!IS_SERVICE_WORKER) {\n subscriptions.push(\n liveQuery(() => db.getCurrentUser()).subscribe(currentUserEmitter)\n );\n // Manage PersistendSyncState observable:\n subscriptions.push(\n liveQuery(() => db.getPersistedSyncState()).subscribe(\n db.cloud.persistedSyncState\n )\n );\n // Wait till currentUser and persistedSyncState gets populated\n // with things from the database and not just the default values.\n // This is so that when db.open() completes, user should be safe\n // to subscribe to these observables and get actual data.\n await combineLatest([\n currentUserEmitter.pipe(skip(1), take(1)),\n db.cloud.persistedSyncState.pipe(skip(1), take(1))\n ]).toPromise();\n }\n\n // HERE: If requireAuth, do athentication now.\n if (db.cloud.options?.requireAuth) {\n await login(db);\n }\n\n if (localSyncWorker) localSyncWorker.stop();\n localSyncWorker = null;\n throwIfClosed();\n if (db.cloud.usingServiceWorker && db.cloud.options?.databaseUrl) {\n registerSyncEvent(db, \"push\").catch(() => {});\n registerPeriodicSyncEvent(db).catch(() => {});\n } else if (\n db.cloud.options?.databaseUrl &&\n db.cloud.schema &&\n !IS_SERVICE_WORKER\n ) {\n // There's no SW. Start SyncWorker instead.\n localSyncWorker = LocalSyncWorker(db, db.cloud.options, db.cloud.schema!);\n localSyncWorker.start();\n triggerSync(db, \"push\");\n }\n\n // Listen to online event and do sync.\n throwIfClosed();\n if (!IS_SERVICE_WORKER) {\n subscriptions.push(\n fromEvent(self, 'online').subscribe(() => {\n console.debug('online!');\n db.syncStateChangedEvent.next({\n phase: 'not-in-sync',\n });\n triggerSync(db, \"push\");\n }),\n fromEvent(self, 'offline').subscribe(() => {\n console.debug('offline!');\n db.syncStateChangedEvent.next({\n phase: 'offline',\n });\n })\n );\n }\n\n // Connect WebSocket only if we're a browser window\n if (\n typeof window !== 'undefined' &&\n !IS_SERVICE_WORKER &&\n db.cloud.options?.databaseUrl\n ) {\n subscriptions.push(connectWebSocket(db));\n }\n }\n}\n\ndexieCloud.version = '{version}';\n\nDexie.Cloud = dexieCloud;\n\n//Dexie.addons.push(dexieCloud);\n\nexport default dexieCloud;\n","import Dexie from 'dexie';\nimport { DexieCloudDB } from './db/DexieCloudDB';\nimport dexieCloud from './dexie-cloud-client';\nimport { DISABLE_SERVICEWORKER_STRATEGY } from './DISABLE_SERVICEWORKER_STRATEGY';\nimport { isSafari, safariVersion } from './isSafari';\nimport { syncIfPossible } from './sync/syncIfPossible';\nimport { SWMessageEvent } from './types/SWMessageEvent';\nimport { SyncEvent } from './types/SWSyncEvent';\n\n// In case the SW lives for a while, let it reuse already opened connections:\nconst managedDBs = new Map<string, DexieCloudDB>();\n\nfunction getDbNameFromTag(tag: string) {\n return tag.startsWith('dexie-cloud:') && tag.split(':')[1];\n}\n\nconst syncDBSemaphore = new Map<string, Promise<void>>();\n\nfunction syncDB(dbName: string, purpose: 'push' | 'pull') {\n // We're taking hight for being double-signalled both\n // via message event and sync event.\n // Which one comes first doesnt matter, just\n // that we return the existing promise if there is\n // an ongoing sync.\n let promise = syncDBSemaphore.get(dbName + '/' + purpose);\n if (!promise) {\n promise = _syncDB(dbName, purpose)\n .then(() => {\n // When legacy enough across browsers, use .finally() instead of then() and catch():\n syncDBSemaphore.delete(dbName + '/' + purpose);\n })\n .catch((error) => {\n syncDBSemaphore.delete(dbName + '/' + purpose);\n return Promise.reject(error);\n });\n syncDBSemaphore.set(dbName + '/' + purpose, promise);\n }\n return promise;\n\n async function _syncDB(dbName: string, purpose: 'push' | 'pull') {\n let db = managedDBs.get(dbName);\n\n if (!db) {\n console.debug('Dexie Cloud SW: Creating new Dexie instance for', dbName);\n const dexie = new Dexie(dbName, { addons: [dexieCloud] });\n db = DexieCloudDB(dexie);\n dexie.on('versionchange', stopManagingDB);\n await db.dx.open(); // Makes sure db.cloud.options and db.cloud.schema are read from db,\n if (!managedDBs.get(dbName)) {\n // Avoid race conditions.\n managedDBs.set(dbName, db);\n }\n }\n if (!db.cloud.options?.databaseUrl) {\n console.error(`Dexie Cloud: No databaseUrl configured`);\n return; // Nothing to sync.\n }\n if (!db.cloud.schema) {\n console.error(`Dexie Cloud: No schema persisted`);\n return; // Nothing to sync.\n }\n\n function stopManagingDB() {\n db!.dx.on.versionchange.unsubscribe(stopManagingDB);\n if (managedDBs.get(db!.name) === db) {\n // Avoid race conditions.\n managedDBs.delete(db!.name);\n }\n console.debug(`Dexie Cloud SW: Closing Dexie instance for ${dbName}`);\n db!.dx.close();\n return false;\n }\n\n try {\n console.debug('Dexie Cloud SW: Syncing');\n await syncIfPossible(db, db.cloud.options, db.cloud.schema, {\n retryImmediatelyOnFetchError: true,\n purpose,\n });\n console.debug('Dexie Cloud SW: Done Syncing');\n } catch (e) {\n console.error(`Dexie Cloud SW Error`, e);\n // Error occured. Stop managing this DB until we wake up again by a sync event,\n // which will open a new Dexie and start trying to sync it.\n stopManagingDB();\n if (e.name !== Dexie.errnames.NoSuchDatabase) {\n // Unless the error was that DB doesn't exist, rethrow to trigger sync retry.\n throw e; // Throw e to make syncEvent.waitUntil() receive a rejected promis, so it will retry.\n }\n }\n }\n}\n\n// Avoid taking care of events if browser bugs out by using dexie cloud from a service worker.\nif (!DISABLE_SERVICEWORKER_STRATEGY) {\n self.addEventListener('sync', (event: SyncEvent) => {\n console.debug('SW \"sync\" Event', event.tag);\n const dbName = getDbNameFromTag(event.tag);\n if (dbName) {\n event.waitUntil(syncDB(dbName, \"push\")); // The purpose of sync events are \"push\"\n }\n });\n\n self.addEventListener('periodicsync', (event: SyncEvent) => {\n console.debug('SW \"periodicsync\" Event', event.tag);\n const dbName = getDbNameFromTag(event.tag);\n if (dbName) {\n event.waitUntil(syncDB(dbName, \"pull\")); // The purpose of periodic sync events are \"pull\"\n }\n });\n\n self.addEventListener('message', (event: SWMessageEvent) => {\n console.debug('SW \"message\" Event', event.data);\n if (event.data.type === 'dexie-cloud-sync') {\n const { dbName } = event.data;\n // Mimic background sync behavior - retry in X minutes on failure.\n // But lesser timeout and more number of times.\n const syncAndRetry = (num = 1) => {\n return syncDB(dbName, event.data.purpose || \"pull\").catch(async (e) => {\n if (num === 3) throw e;\n await sleep(60_000); // 1 minute\n syncAndRetry(num + 1);\n });\n };\n if ('waitUntil' in event) {\n event.waitUntil(syncAndRetry().catch(error => console.error(error)));\n } else {\n syncAndRetry().catch(error => console.error(error));\n }\n }\n });\n}\n\nfunction sleep(ms: number) {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n"],"names":["Observable","tslib_1.__extends","iterator","observable","Symbol_iterator","randomString","Dexie","this","bigintDef","tsonBuiltinDefs","BehaviorSubject","wm","Subject","counter","from","liveQuery","of","fromEvent","merge","Subscription","sleep","throwError","options","rerenderQueue","defer","prevDebounce","EMPTY_OBJ","EMPTY_ARR","IS_NON_DIMENSIONAL","assign","obj","props","i","removeNode","node","parentNode","removeChild","createElement","type","children","key","ref","normalizedProps","arguments","length","push","defaultProps","undefined","createVNode","original","vnode","constructor","Fragment","Component","context","getDomSibling","childIndex","indexOf","sibling","updateParentDomPointers","child","base","enqueueRender","c","process","debounceRendering","queue","sort","a","b","some","component","commitQueue","oldVNode","oldDom","parentDom","diff","ownerSVGElement","commitRoot","diffChildren","renderResult","newParentVNode","oldParentVNode","globalContext","isSvg","excessDomChildren","isHydrating","j","childVNode","newDom","firstChildDom","refs","oldChildren","oldChildrenLength","Array","isArray","reorderChildren","placeChild","value","unmount","applyRef","tmp","nextDom","sibDom","outer","appendChild","nextSibling","insertBefore","diffProps","dom","newProps","oldProps","hydrate","setProperty","setStyle","style","test","name","oldValue","useCapture","o","cssText","replace","toLowerCase","slice","_listeners","addEventListener","eventProxyCapture","eventProxy","removeEventListener","e","setAttribute","removeAttribute","event","newVNode","isNew","oldState","snapshot","clearProcessingException","provider","componentContext","newType","contextType","prototype","render","doRender","sub","state","getDerivedStateFromProps","componentWillMount","componentDidMount","componentWillReceiveProps","shouldComponentUpdate","forEach","componentWillUpdate","componentDidUpdate","getChildContext","getSnapshotBeforeUpdate","diffElementNodes","diffed","root","cb","call","oldHtml","newHtml","nodeType","localName","document","createTextNode","createElementNS","is","data","childNodes","dangerouslySetInnerHTML","attributes","innerHTML","firstChild","checked","current","parentVNode","skipRemove","r","componentWillUnmount","replaceNode","error","ctor","handled","getDerivedStateFromError","setState","componentDidCatch","update","callback","s","forceUpdate","Promise","then","bind","resolve","setTimeout","h","currentIndex","currentComponent","prevRaf","currentHook","afterPaintEffects","oldBeforeDiff","oldBeforeRender","oldAfterDiff","oldCommit","oldBeforeUnmount","getHookState","index","hooks","useState","initialState","useReducer","invokeOrReturn","reducer","init","hookState","_reducer","action","nextValue","useLayoutEffect","args","argsChanged","useRef","initialValue","useMemo","factory","flushAfterPaintEffects","invokeCleanup","invokeEffect","requestAnimationFrame","raf","done","clearTimeout","timeout","HAS_RAF","cancelAnimationFrame","previousComponent","filter","hook","comp","oldArgs","newArgs","arg","f","preact.render","combineLatest"],"mappings":";;;;;;;;;;IAEO,MAAM,iBAAiB,GAAc;QAC1C,MAAM,EAAE,cAAc;QACtB,IAAI,EAAE,cAAc;QACpB,MAAM,EAAE;YACN,GAAG,EAAE,cAAc;SACpB;QACD,SAAS,EAAE,IAAI,IAAI,CAAC,CAAC,CAAC;KACvB,CAAA;IAED,IAAI;QACF,MAAM,CAAC,MAAM,CAAC,iBAAiB,CAAC,CAAC;QACjC,MAAM,CAAC,MAAM,CAAC,iBAAiB,CAAC,MAAM,CAAC,CAAC;KACzC;IAAC,WAAM;;ICdR,MAAM,QAAQ,GAAiD,EAAE,CAAC;IAClE,MAAM,WAAW,GAAG,IAAI,CAAC,QAAQ,IAAI,SAAS,CAAC,aAAa,CAAC;IAC7D,IAAI,WAAW;QACb,WAAW,CAAC,KAAK,CAAC,IAAI,CACpB,CAAC,YAAY,MAAM,QAAQ,CAAC,YAAY,GAAG,YAAY,CAAC,CACzD,CAAC;IAEJ,IAAI,OAAO,IAAI,KAAK,WAAW,IAAI,SAAS,IAAI,IAAI,IAAI,CAAC,IAAI,CAAC,QAAQ,EAAE;;QAEtE,gBAAgB,CAAC,SAAS,EAAE,CAAC,EAAO;;YAClC,IAAI,MAAA,M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