@vrtmrz/livesync-commonlib 0.1.0-rc.12 → 0.1.0-rc.14
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/interfaces/FileHandler.d.ts +17 -1
- package/dist/serviceFeatures/remoteConfig.d.ts +2 -2
- package/dist/serviceFeatures/remoteConfig.js +2 -2
- package/dist/serviceModules/ServiceFileHandlerBase.d.ts +2 -1
- package/dist/serviceModules/ServiceFileHandlerBase.js +100 -10
- package/dist/worker/bgWorker.js +1 -1
- package/docs/conflict-resolution.md +4 -0
- package/docs/development.md +1 -1
- package/docs/proven-in-use.md +1 -1
- package/docs/releasing.md +10 -7
- package/package.json +1 -1
|
@@ -3,11 +3,27 @@ import type { UXFileInfo, UXFileInfoStub, UXInternalFileInfoStub } from "../comm
|
|
|
3
3
|
export interface IFileHandler {
|
|
4
4
|
readFileFromStub(file: UXFileInfoStub | UXFileInfo): Promise<UXFileInfo>;
|
|
5
5
|
storeFileToDB(info: UXFileInfoStub | UXFileInfo | UXInternalFileInfoStub | FilePathWithPrefix, force?: boolean, onlyChunks?: boolean): Promise<boolean>;
|
|
6
|
+
/**
|
|
7
|
+
* Store the current storage content as a child of an exact live database revision.
|
|
8
|
+
*
|
|
9
|
+
* This explicit branch-selection boundary is intended for user-directed
|
|
10
|
+
* reconciliation. It rechecks that the selected revision is still live,
|
|
11
|
+
* and records the resulting revision as the storage provenance. When
|
|
12
|
+
* `createIfDifferent` is false, differing storage content is rejected
|
|
13
|
+
* instead of creating a child revision.
|
|
14
|
+
*/
|
|
15
|
+
storeFileToDBWithBaseRevision(info: UXFileInfoStub | UXFileInfo | FilePathWithPrefix, baseRevision: string, createIfDifferent?: boolean): Promise<boolean>;
|
|
6
16
|
deleteFileFromDB(info: UXFileInfoStub | UXInternalFileInfoStub | FilePath): Promise<boolean>;
|
|
7
17
|
renameFileInDB(info: UXFileInfoStub | UXFileInfo, oldPath: FilePath | FilePathWithPrefix): Promise<boolean>;
|
|
18
|
+
/**
|
|
19
|
+
* Create a logical deletion on one exact database revision.
|
|
20
|
+
*
|
|
21
|
+
* When device-local storage provenance names the deleted revision, the
|
|
22
|
+
* implementation clears that stale provenance without changing storage.
|
|
23
|
+
*/
|
|
8
24
|
deleteRevisionFromDB(info: UXFileInfoStub | FilePath | FilePathWithPrefix, rev: string): Promise<boolean | undefined>;
|
|
9
25
|
resolveConflictedByDeletingRevision(info: UXFileInfoStub | FilePath, rev: string): Promise<boolean | undefined>;
|
|
10
|
-
dbToStorageWithSpecificRev(info: UXFileInfoStub | UXFileInfo | FilePath | null, rev: string, force?: boolean): Promise<boolean>;
|
|
26
|
+
dbToStorageWithSpecificRev(info: UXFileInfoStub | UXFileInfo | FilePath | FilePathWithPrefix | null, rev: string, force?: boolean): Promise<boolean>;
|
|
11
27
|
dbToStorage(entryInfo: MetaEntry | FilePathWithPrefix, info: UXFileInfoStub | UXFileInfo | FilePath | null, force?: boolean): Promise<boolean>;
|
|
12
28
|
createAllChunks(showingNotice?: boolean): Promise<void>;
|
|
13
29
|
}
|
|
@@ -65,11 +65,11 @@ export declare function activateRemoteConfiguration(settings: ObsidianLiveSyncSe
|
|
|
65
65
|
*/
|
|
66
66
|
export declare function activateP2PRemoteConfiguration(settings: ObsidianLiveSyncSettings, id: string): ObsidianLiveSyncSettings | false;
|
|
67
67
|
/**
|
|
68
|
-
* Command: Switch
|
|
68
|
+
* Command: Switch active connection
|
|
69
69
|
*/
|
|
70
70
|
export declare function commandSwitchActiveRemote(host: RemoteConfigHost): Promise<void>;
|
|
71
71
|
/**
|
|
72
|
-
* Command:
|
|
72
|
+
* Command: Sync with a saved connection
|
|
73
73
|
*/
|
|
74
74
|
export declare function commandReplicateWithSpecificRemote(host: RemoteConfigHost): Promise<void>;
|
|
75
75
|
/**
|
|
@@ -311,12 +311,12 @@ function useRemoteConfigurationMigration(host) {
|
|
|
311
311
|
function useRemoteConfiguration(host) {
|
|
312
312
|
host.services.API.addCommand({
|
|
313
313
|
id: "livesync-switch-remote",
|
|
314
|
-
name: "Switch
|
|
314
|
+
name: "Switch active connection",
|
|
315
315
|
callback: () => commandSwitchActiveRemote(host)
|
|
316
316
|
});
|
|
317
317
|
host.services.API.addCommand({
|
|
318
318
|
id: "livesync-replicate-with-specific",
|
|
319
|
-
name: "
|
|
319
|
+
name: "Sync with a saved connection",
|
|
320
320
|
callback: () => commandReplicateWithSpecificRemote(host)
|
|
321
321
|
});
|
|
322
322
|
return true;
|
|
@@ -57,12 +57,13 @@ export declare abstract class ServiceFileHandlerBase extends ServiceModuleBase<S
|
|
|
57
57
|
readFileFromStub(file: UXFileInfoStub | UXFileInfo): Promise<UXFileInfo>;
|
|
58
58
|
private infoToStub;
|
|
59
59
|
storeFileToDB(info: UXFileInfoStub | UXFileInfo | UXInternalFileInfoStub | FilePathWithPrefix, force?: boolean, onlyChunks?: boolean): Promise<boolean>;
|
|
60
|
+
storeFileToDBWithBaseRevision(info: UXFileInfoStub | UXFileInfo | FilePathWithPrefix, baseRevision: string, createIfDifferent?: boolean): Promise<boolean>;
|
|
60
61
|
private storeFileToDBFromRevision;
|
|
61
62
|
deleteFileFromDB(info: UXFileInfoStub | UXInternalFileInfoStub | FilePath): Promise<boolean>;
|
|
62
63
|
renameFileInDB(info: UXFileInfoStub | UXFileInfo, oldPath: FilePath | FilePathWithPrefix): Promise<boolean>;
|
|
63
64
|
deleteRevisionFromDB(info: UXFileInfoStub | FilePath | FilePathWithPrefix, rev: string): Promise<boolean | undefined>;
|
|
64
65
|
resolveConflictedByDeletingRevision(info: UXFileInfoStub | FilePath, rev: string): Promise<boolean | undefined>;
|
|
65
|
-
dbToStorageWithSpecificRev(info: UXFileInfoStub | UXFileInfo | FilePath | null, rev: string, force?: boolean): Promise<boolean>;
|
|
66
|
+
dbToStorageWithSpecificRev(info: UXFileInfoStub | UXFileInfo | FilePath | FilePathWithPrefix | null, rev: string, force?: boolean): Promise<boolean>;
|
|
66
67
|
dbToStorage(entryInfo: MetaEntry | FilePathWithPrefix, info: UXFileInfoStub | UXFileInfo | FilePath | null, force?: boolean): Promise<boolean>;
|
|
67
68
|
private applyDatabaseEntryToStorage;
|
|
68
69
|
private preserveUnsyncedStorageAsConflict;
|
|
@@ -149,6 +149,59 @@ class ServiceFileHandlerBase extends ServiceModuleBase {
|
|
|
149
149
|
async storeFileToDB(info, force = false, onlyChunks = false) {
|
|
150
150
|
return await this.storeFileToDBFromRevision(info, force, onlyChunks);
|
|
151
151
|
}
|
|
152
|
+
async storeFileToDBWithBaseRevision(info, baseRevision, createIfDifferent = true) {
|
|
153
|
+
const file = await this.infoToStub(info);
|
|
154
|
+
if (file == null) {
|
|
155
|
+
this._log(`File ${tryGetFilePath(info)} is not exist on the storage`, LOG_LEVEL_VERBOSE);
|
|
156
|
+
return false;
|
|
157
|
+
}
|
|
158
|
+
if (file.isInternal) {
|
|
159
|
+
this._log(
|
|
160
|
+
`Internal file ${file.path} is not allowed to be stored through the ordinary file handler`,
|
|
161
|
+
LOG_LEVEL_VERBOSE
|
|
162
|
+
);
|
|
163
|
+
return false;
|
|
164
|
+
}
|
|
165
|
+
const [baseEntry, currentEntry, conflictedRevisions] = await Promise.all([
|
|
166
|
+
this.db.fetchEntryMeta(file, baseRevision, true),
|
|
167
|
+
this.db.fetchEntryMeta(file, void 0, true),
|
|
168
|
+
this.db.getConflictedRevs(file)
|
|
169
|
+
]);
|
|
170
|
+
const liveRevisions = /* @__PURE__ */ new Set([
|
|
171
|
+
...currentEntry && currentEntry._rev ? [currentEntry._rev] : [],
|
|
172
|
+
...conflictedRevisions
|
|
173
|
+
]);
|
|
174
|
+
if (!baseEntry || baseEntry._rev !== baseRevision || !liveRevisions.has(baseRevision)) {
|
|
175
|
+
this._log(
|
|
176
|
+
`Could not store ${file.path} on revision ${baseRevision}; the selected revision is no longer live`,
|
|
177
|
+
LOG_LEVEL_NOTICE
|
|
178
|
+
);
|
|
179
|
+
return false;
|
|
180
|
+
}
|
|
181
|
+
const readFile = await this.readFileFromStub(file);
|
|
182
|
+
if (!baseEntry.deleted && !baseEntry._deleted) {
|
|
183
|
+
const loadedBase = await this.db.fetchEntry(file, baseRevision, true, true);
|
|
184
|
+
if (loadedBase && await isDocContentSame(getDocDataAsArray(loadedBase.data), readFile.body)) {
|
|
185
|
+
await this.setProvenance(file.path, baseRevision, readFile.stat.mtime);
|
|
186
|
+
await this.conflict.queueCheckFor(file.path);
|
|
187
|
+
return true;
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
if (!createIfDifferent) {
|
|
191
|
+
this._log(
|
|
192
|
+
`Could not mark ${file.path} as revision ${baseRevision}; the storage content differs`,
|
|
193
|
+
LOG_LEVEL_NOTICE
|
|
194
|
+
);
|
|
195
|
+
return false;
|
|
196
|
+
}
|
|
197
|
+
const storedRevision = await this.db.storeWithBaseRevision(readFile, baseRevision, true);
|
|
198
|
+
if (storedRevision === false) {
|
|
199
|
+
return false;
|
|
200
|
+
}
|
|
201
|
+
await this.setProvenance(file.path, storedRevision, readFile.stat.mtime);
|
|
202
|
+
await this.conflict.queueCheckFor(file.path);
|
|
203
|
+
return true;
|
|
204
|
+
}
|
|
152
205
|
async storeFileToDBFromRevision(info, force = false, onlyChunks = false, preferredBasePath) {
|
|
153
206
|
const file = await this.infoToStub(info);
|
|
154
207
|
if (file == null) {
|
|
@@ -381,31 +434,60 @@ class ServiceFileHandlerBase extends ServiceModuleBase {
|
|
|
381
434
|
return deleted;
|
|
382
435
|
}
|
|
383
436
|
async deleteRevisionFromDB(info, rev) {
|
|
384
|
-
|
|
437
|
+
const path = getStoragePathFromUXFileInfo(info);
|
|
438
|
+
const provenance = await this.getProvenance(path);
|
|
439
|
+
const deleted = await this.db.delete(info, rev);
|
|
440
|
+
if (deleted && provenance?.revision === rev) {
|
|
441
|
+
await this.deleteProvenance(path);
|
|
442
|
+
}
|
|
443
|
+
return deleted;
|
|
385
444
|
}
|
|
386
445
|
async resolveConflictedByDeletingRevision(info, rev) {
|
|
387
446
|
const path = getStoragePathFromUXFileInfo(info);
|
|
447
|
+
const file = await this.infoToStub(info);
|
|
448
|
+
const docEntry = await this.db.fetchEntryMeta(file ?? info, rev, true);
|
|
449
|
+
if (!docEntry) {
|
|
450
|
+
this._log(`Failed to read the conflicted revision ${rev} of ${path}`, LOG_LEVEL_VERBOSE);
|
|
451
|
+
return false;
|
|
452
|
+
}
|
|
388
453
|
if (!await this.deleteRevisionFromDB(info, rev)) {
|
|
389
454
|
this._log(`Failed to delete the conflicted revision ${rev} of ${path}`, LOG_LEVEL_VERBOSE);
|
|
390
455
|
return false;
|
|
391
456
|
}
|
|
392
|
-
if (!await this.
|
|
457
|
+
if (!await this.applyDatabaseEntryToStorage(docEntry, file, true)) {
|
|
393
458
|
this._log(`Failed to apply the resolved revision ${rev} of ${path} to the storage`, LOG_LEVEL_VERBOSE);
|
|
394
459
|
return false;
|
|
395
460
|
}
|
|
461
|
+
await this.deleteProvenance(path);
|
|
396
462
|
}
|
|
397
463
|
async dbToStorageWithSpecificRev(info, rev, force) {
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
this._log(`File ${tryGetFilePath(info)} is not exist on the storage`, LOG_LEVEL_VERBOSE);
|
|
464
|
+
if (info == null) {
|
|
465
|
+
this._log(`Cannot select database revision ${rev} without a file path`, LOG_LEVEL_VERBOSE);
|
|
401
466
|
return false;
|
|
402
467
|
}
|
|
403
|
-
const
|
|
468
|
+
const file = await this.infoToStub(info);
|
|
469
|
+
const databaseTarget = file ?? info;
|
|
470
|
+
const [docEntry, currentEntry, conflictedRevisions] = await Promise.all([
|
|
471
|
+
this.db.fetchEntryMeta(databaseTarget, rev, true),
|
|
472
|
+
this.db.fetchEntryMeta(databaseTarget, void 0, true),
|
|
473
|
+
this.db.getConflictedRevs(databaseTarget)
|
|
474
|
+
]);
|
|
404
475
|
if (!docEntry) {
|
|
405
|
-
this._log(`File ${
|
|
476
|
+
this._log(`File ${tryGetFilePath(info)} is not exist on the database`, LOG_LEVEL_VERBOSE);
|
|
406
477
|
return false;
|
|
407
478
|
}
|
|
408
|
-
|
|
479
|
+
const liveRevisions = /* @__PURE__ */ new Set([
|
|
480
|
+
...currentEntry && currentEntry._rev ? [currentEntry._rev] : [],
|
|
481
|
+
...conflictedRevisions
|
|
482
|
+
]);
|
|
483
|
+
if (!liveRevisions.has(rev)) {
|
|
484
|
+
this._log(
|
|
485
|
+
`Could not apply ${tryGetFilePath(info)} revision ${rev}; the selected revision is no longer live`,
|
|
486
|
+
LOG_LEVEL_NOTICE
|
|
487
|
+
);
|
|
488
|
+
return false;
|
|
489
|
+
}
|
|
490
|
+
return await this.applyDatabaseEntryToStorage(docEntry, file, force, true);
|
|
409
491
|
}
|
|
410
492
|
async dbToStorage(entryInfo, info, force) {
|
|
411
493
|
const file = await this.infoToStub(info);
|
|
@@ -417,12 +499,12 @@ class ServiceFileHandlerBase extends ServiceModuleBase {
|
|
|
417
499
|
}
|
|
418
500
|
return await this.applyDatabaseEntryToStorage(docEntry, file, force);
|
|
419
501
|
}
|
|
420
|
-
async applyDatabaseEntryToStorage(docEntry, file, force) {
|
|
502
|
+
async applyDatabaseEntryToStorage(docEntry, file, force, allowExistingConflicts = false) {
|
|
421
503
|
const mode = file == null ? "create" : "modify";
|
|
422
504
|
const path = this.getPath(docEntry);
|
|
423
505
|
const settings = this.setting.currentSettings();
|
|
424
506
|
const revs = await this.db.getConflictedRevs(path);
|
|
425
|
-
if (revs.length > 0) {
|
|
507
|
+
if (revs.length > 0 && !allowExistingConflicts) {
|
|
426
508
|
if (settings.writeDocumentsIfConflicted) {
|
|
427
509
|
} else {
|
|
428
510
|
await this.conflict.queueCheckForIfOpen(path);
|
|
@@ -490,6 +572,14 @@ class ServiceFileHandlerBase extends ServiceModuleBase {
|
|
|
490
572
|
}
|
|
491
573
|
}
|
|
492
574
|
const docData = readContent(docRead);
|
|
575
|
+
if (allowExistingConflicts && existDoc && !force) {
|
|
576
|
+
const readFile = await this.readFileFromStub(existDoc);
|
|
577
|
+
if (await isDocContentSame(docData, readFile.body)) {
|
|
578
|
+
await this.setProvenance(path, docEntry._rev, existDoc.stat.mtime);
|
|
579
|
+
this.path.markChangesAreSame(docRead, docRead.mtime, existDoc.stat.mtime);
|
|
580
|
+
return true;
|
|
581
|
+
}
|
|
582
|
+
}
|
|
493
583
|
if (existDoc && !force) {
|
|
494
584
|
let shouldApplied = false;
|
|
495
585
|
const freshness = this.path.compareFileFreshness(existDoc, docEntry);
|
package/dist/worker/bgWorker.js
CHANGED
|
@@ -16,7 +16,7 @@ var __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, "defau
|
|
|
16
16
|
import { promiseWithResolvers } from "octagonal-wheels/promises.js";
|
|
17
17
|
|
|
18
18
|
// commonlib-inline-worker:bg.worker.ts
|
|
19
|
-
var workerSource = '"use strict";\n(() => {\n var __create = Object.create;\n var __defProp = Object.defineProperty;\n var __getOwnPropDesc = Object.getOwnPropertyDescriptor;\n var __getOwnPropNames = Object.getOwnPropertyNames;\n var __getProtoOf = Object.getPrototypeOf;\n var __hasOwnProp = Object.prototype.hasOwnProperty;\n var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {\n get: (a, b) => (typeof require !== "undefined" ? require : a)[b]\n }) : x)(function(x) {\n if (typeof require !== "undefined") return require.apply(this, arguments);\n throw Error(\'Dynamic require of "\' + x + \'" is not supported\');\n });\n var __copyProps = (to, from, except, desc) => {\n if (from && typeof from === "object" || typeof from === "function") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n };\n var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(\n // If the importer is in node compatibility mode or this is not an ESM\n // file that has been converted to a CommonJS file using a Babel-\n // compatible transform (i.e. "__esModule" has not been set), then set\n // "default" to the CommonJS "module.exports" for node compatibility.\n isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,\n mod\n ));\n\n // node_modules/octagonal-wheels/dist/common/logger.js\n var LOG_LEVEL_VERBOSE = 16;\n var LOG_LEVEL_INFO = 32;\n var LOG_KIND_DEBUG = 1;\n var LOG_KIND_VERBOSE = 2;\n var LOG_KIND_WARNING = 4;\n var LOG_KIND_ERROR = 8;\n var LEVEL_INFO = LOG_LEVEL_INFO;\n var defaultLoggerEnv = {\n minLogLevel: LOG_LEVEL_INFO\n };\n var defaultLogger = function defaultLogger2(message, level = LEVEL_INFO, key) {\n if (level < defaultLoggerEnv.minLogLevel) {\n return;\n }\n const now = /* @__PURE__ */ new Date();\n const timestamp = now.toLocaleString();\n const messageContent = typeof message == "string" ? message : message instanceof Error ? `${message.name}:${message.message}` : JSON.stringify(message, null, 2);\n const newMessage = `${timestamp} ${level} ${messageContent}`;\n if (level & LOG_KIND_DEBUG) {\n console.debug(newMessage);\n } else if (level & LOG_KIND_WARNING) {\n console.warn(newMessage);\n } else if (level & LOG_KIND_ERROR) {\n console.error(newMessage);\n } else if (level & LOG_KIND_VERBOSE) {\n console.info(newMessage);\n } else {\n console.log(newMessage);\n }\n if (message instanceof Error) {\n console.dir(message.stack);\n }\n };\n var _logger = defaultLogger;\n function Logger(message, level, key) {\n _logger(message, level, key);\n }\n\n // node_modules/octagonal-wheels/dist/binary/base64.js\n var isProposalArrayBufferBase64Available = typeof Uint8Array !== "undefined" && //@ts-ignore: Not typed in project target level\n typeof Uint8Array.prototype.toBase64 === "function" && //@ts-ignore: Not typed in project target level\n typeof Uint8Array.fromBase64 === "function";\n function base64ToArrayBufferNative(base64) {\n if (base64.length === 0)\n return new ArrayBuffer(0);\n try {\n if (typeof base64 == "string")\n return Uint8Array.fromBase64(base64).buffer;\n const bufItems = base64.map((e) => Uint8Array.fromBase64(e).buffer);\n const len = bufItems.reduce((p, c) => p + c.byteLength, 0);\n const joinedArray = new Uint8Array(len);\n let offset = 0;\n bufItems.forEach((e) => {\n joinedArray.set(new Uint8Array(e), offset);\n offset += e.byteLength;\n });\n return joinedArray.buffer;\n } catch (ex) {\n Logger("Base64 Decode error", LOG_LEVEL_VERBOSE);\n Logger(ex, LOG_LEVEL_VERBOSE);\n return new ArrayBuffer(0);\n }\n }\n function base64ToArrayBufferBrowser(base64) {\n if (typeof base64 == "string")\n return base64ToArrayBufferInternalBrowser(base64);\n const bufItems = base64.map((e) => base64ToArrayBufferInternalBrowser(e));\n const len = bufItems.reduce((p, c) => p + c.byteLength, 0);\n const joinedArray = new Uint8Array(len);\n let offset = 0;\n bufItems.forEach((e) => {\n joinedArray.set(new Uint8Array(e), offset);\n offset += e.byteLength;\n });\n return joinedArray.buffer;\n }\n var base64ToArrayBuffer = isProposalArrayBufferBase64Available ? base64ToArrayBufferNative : base64ToArrayBufferBrowser;\n function base64ToArrayBufferInternalBrowser(base64) {\n try {\n const binary_string = globalThis.atob(base64);\n const len = binary_string.length;\n const bytes = new Uint8Array(len);\n for (let i = 0; i < len; i++) {\n bytes[i] = binary_string.charCodeAt(i);\n }\n return bytes.buffer;\n } catch (ex) {\n Logger("Base64 Decode error", LOG_LEVEL_VERBOSE);\n Logger(ex, LOG_LEVEL_VERBOSE);\n return new ArrayBuffer(0);\n }\n }\n var encodeChunkSize = 3 * 5e7;\n function arrayBufferToBase64internalBrowser(buffer) {\n return new Promise((res, rej) => {\n const blob = new Blob([buffer], { type: "application/octet-binary" });\n const reader = new FileReader();\n reader.onload = function(evt) {\n const dataURI = evt.target?.result?.toString() || "";\n if (buffer.byteLength != 0 && (dataURI == "" || dataURI == "data:"))\n return rej(new TypeError("Could not parse the encoded string"));\n const result = dataURI.substring(dataURI.indexOf(",") + 1);\n res(result);\n };\n reader.readAsDataURL(blob);\n });\n }\n async function arrayBufferToBase64SingleBrowser(buffer) {\n const buf = buffer instanceof Uint8Array ? buffer : new Uint8Array(buffer);\n if (buf.byteLength < QUANTUM)\n return btoa(String.fromCharCode.apply(null, [...buf]));\n return await arrayBufferToBase64internalBrowser(buf);\n }\n function arrayBufferToBase64SingleNative(buffer) {\n const buf = buffer instanceof Uint8Array ? buffer : new Uint8Array(buffer);\n return Promise.resolve(buf.toBase64());\n }\n var arrayBufferToBase64Single = isProposalArrayBufferBase64Available ? arrayBufferToBase64SingleNative : arrayBufferToBase64SingleBrowser;\n var QUANTUM = 32768;\n var te = new TextEncoder();\n var td = new TextDecoder("utf-8", { ignoreBOM: true });\n function writeString(string) {\n if (string.length > 128) {\n const buf = te.encode(string);\n return buf;\n }\n const buffer = new Uint8Array(string.length * 4);\n const length = string.length;\n let index = 0;\n let chr = 0;\n let idx = 0;\n while (idx < length) {\n chr = string.charCodeAt(idx++);\n if (chr < 128) {\n buffer[index++] = chr;\n } else if (chr < 2048) {\n buffer[index++] = 192 | chr >>> 6;\n buffer[index++] = 128 | chr & 63;\n } else if (chr < 55296 || chr > 57343) {\n buffer[index++] = 224 | chr >>> 12;\n buffer[index++] = 128 | chr >>> 6 & 63;\n buffer[index++] = 128 | chr & 63;\n } else {\n chr = (chr - 55296 << 10 | string.charCodeAt(idx++) - 56320) + 65536;\n buffer[index++] = 240 | chr >>> 18;\n buffer[index++] = 128 | chr >>> 12 & 63;\n buffer[index++] = 128 | chr >>> 6 & 63;\n buffer[index++] = 128 | chr & 63;\n }\n }\n return buffer.slice(0, index);\n }\n function readString(buffer) {\n const length = buffer.length;\n if (length > 128)\n return td.decode(buffer);\n let index = 0;\n const end = length;\n let string = "";\n while (index < end) {\n const chunk = [];\n const cEnd = Math.min(index + QUANTUM, end);\n while (index < cEnd) {\n const chr = buffer[index++];\n if (chr < 128) {\n chunk.push(chr);\n } else if ((chr & 224) === 192) {\n chunk.push((chr & 31) << 6 | buffer[index++] & 63);\n } else if ((chr & 240) === 224) {\n chunk.push((chr & 15) << 12 | (buffer[index++] & 63) << 6 | buffer[index++] & 63);\n } else if ((chr & 248) === 240) {\n let code = (chr & 7) << 18 | (buffer[index++] & 63) << 12 | (buffer[index++] & 63) << 6 | buffer[index++] & 63;\n if (code < 65536) {\n chunk.push(code);\n } else {\n code -= 65536;\n chunk.push((code >>> 10) + 55296, (code & 1023) + 56320);\n }\n }\n }\n string += String.fromCharCode(...chunk);\n }\n return string;\n }\n\n // node_modules/octagonal-wheels/dist/collection.js\n function* range(from, to) {\n for (let i = from; i <= to; i++) {\n yield i;\n }\n return;\n }\n\n // node_modules/octagonal-wheels/dist/binary/encodedUTF16.js\n var BINARY_CHUNK_MAX = 1024 * 1024 * 30;\n var table = {};\n var revTable = {};\n [...range(192, 447)].forEach((e, i) => {\n table[i] = e;\n revTable[e] = i;\n });\n function decodeToArrayBuffer(src) {\n if (src.length == 1)\n return _decodeToArrayBuffer(src[0]);\n const bufItems = src.map((e) => _decodeToArrayBuffer(e));\n const len = bufItems.reduce((p, c) => p + c.byteLength, 0);\n const joinedArray = new Uint8Array(len);\n let offset = 0;\n bufItems.forEach((e) => {\n joinedArray.set(new Uint8Array(e), offset);\n offset += e.byteLength;\n });\n return joinedArray.buffer;\n }\n function _decodeToArrayBuffer(src) {\n const out = new Uint8Array(src.length);\n const len = src.length;\n for (let i = 0; i < len; i++) {\n const char = src.charCodeAt(i);\n if (char >= 38 && char <= 126 && char != 58) {\n out[i] = char;\n } else {\n out[i] = revTable[char];\n }\n }\n return out.buffer;\n }\n\n // node_modules/octagonal-wheels/dist/binary/hex.js\n var revMap = {};\n var numMap = {};\n for (let i = 0; i < 256; i++) {\n revMap[`00${i.toString(16)}`.slice(-2)] = i;\n numMap[i] = `00${i.toString(16)}`.slice(-2);\n }\n var isProposalArrayBufferBase64Available2 = typeof Uint8Array !== "undefined" && //@ts-ignore: Not typed in project target level\n typeof Uint8Array.prototype.toBase64 === "function" && //@ts-ignore: Not typed in project target level\n typeof Uint8Array.fromBase64 === "function";\n var hexStringToUint8Array = isProposalArrayBufferBase64Available2 ? hexStringToUint8ArrayNative : hexStringToUint8ArrayBrowser;\n function hexStringToUint8ArrayNative(src) {\n return Uint8Array.fromHex(src);\n }\n function hexStringToUint8ArrayBrowser(src) {\n const len = src.length / 2;\n const ret = new Uint8Array(len);\n for (let i = 0; i < len; i++) {\n ret[i] = revMap[src[i * 2] + src[i * 2 + 1]];\n }\n return ret;\n }\n var uint8ArrayToHexString = isProposalArrayBufferBase64Available2 ? uint8ArrayToHexStringNative : uint8ArrayToHexStringBrowser;\n function uint8ArrayToHexStringBrowser(src) {\n return [...src].map((e) => numMap[e]).join("");\n }\n function uint8ArrayToHexStringNative(src) {\n return src.toHex();\n }\n\n // node_modules/octagonal-wheels/dist/binary/index.js\n function decodeBinary(src) {\n if (src.length == 0)\n return new Uint8Array().buffer;\n if (typeof src === "string") {\n if (src[0] === "%") {\n return _decodeToArrayBuffer(src.substring(1));\n }\n } else {\n if (src[0][0] === "%") {\n const [head, ...last] = src;\n return decodeToArrayBuffer([head.substring(1), ...last]);\n }\n }\n return base64ToArrayBuffer(src);\n }\n\n // src/common/coreEnvFunctions.ts\n var compatGlobal = typeof window !== "undefined" ? window : (\n // compatibility for CLIs, tests, and other non-browser environments.\n // eslint-disable-next-line obsidianmd/no-global-this\n globalThis\n );\n var _fetch = compatGlobal.fetch.bind(compatGlobal);\n var activeDocumentWindow = compatGlobal;\n var _activeDocument = activeDocumentWindow.activeDocument ?? activeDocumentWindow.document;\n\n // src/string_and_binary/convert.ts\n async function arrayBufferToBase64Single2(buffer) {\n try {\n return await arrayBufferToBase64Single(buffer);\n } catch (ex) {\n const maybeBuffer = compatGlobal?.Buffer;\n if (typeof maybeBuffer?.from === "function") {\n const view = buffer instanceof Uint8Array ? buffer : new Uint8Array(buffer);\n return maybeBuffer.from(view.buffer, view.byteOffset, view.byteLength).toString("base64");\n }\n throw ex;\n }\n }\n\n // node_modules/octagonal-wheels/dist/memory/LRUCache.js\n var LRUCache = class {\n /**\n * Creates a new instance of the LRUCache class.\n * @param maxCache The maximum number of items to cache.\n * @param maxCacheLength The maximum length of the cached values.\n * @param forwardOnly True if we only need to cache forward values.\n */\n constructor(maxCache, maxCacheLength, forwardOnly = false) {\n Object.defineProperty(this, "cache", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: /* @__PURE__ */ new Map([])\n });\n Object.defineProperty(this, "revCache", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: /* @__PURE__ */ new Map([])\n });\n Object.defineProperty(this, "maxCache", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: 200\n });\n Object.defineProperty(this, "maxCachedLength", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: 5e7\n });\n Object.defineProperty(this, "cachedLength", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: 0\n });\n Object.defineProperty(this, "enableReversed", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: true\n });\n this.maxCache = maxCache || 200;\n this.maxCachedLength = (maxCacheLength || 1) * 1e6;\n this.enableReversed = !forwardOnly;\n Logger(`Cache initialized ${this.maxCache} / ${this.maxCachedLength}`, LOG_LEVEL_VERBOSE);\n }\n /**\n * Clears the cache.\n */\n clear() {\n this.cache.clear();\n this.revCache.clear();\n }\n /**\n * Checks if the cache contains the specified key.\n * @param key The key to check.\n * @returns A boolean indicating whether the cache contains the key.\n */\n has(key) {\n return this.cache.has(key);\n }\n /**\n * Gets the value associated with the specified key from the cache.\n * @param key The key to retrieve the value for.\n * @returns The value associated with the key, or undefined if the key is not found.\n * @remarks After calling this method, the key will be updated to recently used.\n */\n get(key) {\n const v = this.cache.get(key);\n if (v) {\n this.cache.delete(key);\n this.cache.set(key, v);\n if (this.enableReversed) {\n this.revCache.delete(v);\n this.revCache.set(v, key);\n }\n }\n return v;\n }\n /**\n * Gets the key associated with the specified value from the cache.\n * @param value The value to retrieve the key for.\n * @returns The key associated with the value, or undefined if the value is not found.\n * @remarks After calling this method, the key will be updated to recently used.\n */\n revGet(value) {\n const key = this.revCache.get(value);\n if (key) {\n this.cache.delete(key);\n this.revCache.delete(value);\n this.cache.set(key, value);\n this.revCache.set(value, key);\n }\n return key;\n }\n /**\n * Sets the value associated with the specified key in the cache.\n * @param key The key to set the value for.\n * @param value The value to set.\n */\n set(key, value) {\n this.cache.set(key, value);\n if (this.enableReversed)\n this.revCache.set(value, key);\n this.cachedLength += `${value}`.length;\n if (this.cache.size > this.maxCache || this.cachedLength > this.maxCachedLength) {\n for (const [key2, value2] of this.cache) {\n this.cache.delete(key2);\n if (this.enableReversed)\n this.revCache.delete(value2);\n this.cachedLength -= `${value2}`.length;\n if (this.cache.size <= this.maxCache && this.cachedLength <= this.maxCachedLength)\n break;\n }\n }\n }\n };\n\n // node_modules/balanced-match/dist/esm/index.js\n var balanced = (a, b, str) => {\n const ma = a instanceof RegExp ? maybeMatch(a, str) : a;\n const mb = b instanceof RegExp ? maybeMatch(b, str) : b;\n const r = ma !== null && mb != null && range2(ma, mb, str);\n return r && {\n start: r[0],\n end: r[1],\n pre: str.slice(0, r[0]),\n body: str.slice(r[0] + ma.length, r[1]),\n post: str.slice(r[1] + mb.length)\n };\n };\n var maybeMatch = (reg, str) => {\n const m = str.match(reg);\n return m ? m[0] : null;\n };\n var range2 = (a, b, str) => {\n let begs, beg, left, right = void 0, result;\n let ai = str.indexOf(a);\n let bi = str.indexOf(b, ai + 1);\n let i = ai;\n if (ai >= 0 && bi > 0) {\n if (a === b) {\n return [ai, bi];\n }\n begs = [];\n left = str.length;\n while (i >= 0 && !result) {\n if (i === ai) {\n begs.push(i);\n ai = str.indexOf(a, i + 1);\n } else if (begs.length === 1) {\n const r = begs.pop();\n if (r !== void 0)\n result = [r, bi];\n } else {\n beg = begs.pop();\n if (beg !== void 0 && beg < left) {\n left = beg;\n right = bi;\n }\n bi = str.indexOf(b, i + 1);\n }\n i = ai < bi && ai >= 0 ? ai : bi;\n }\n if (begs.length && right !== void 0) {\n result = [left, right];\n }\n }\n return result;\n };\n\n // node_modules/brace-expansion/dist/esm/index.js\n var escSlash = "\\0SLASH" + Math.random() + "\\0";\n var escOpen = "\\0OPEN" + Math.random() + "\\0";\n var escClose = "\\0CLOSE" + Math.random() + "\\0";\n var escComma = "\\0COMMA" + Math.random() + "\\0";\n var escPeriod = "\\0PERIOD" + Math.random() + "\\0";\n var escSlashPattern = new RegExp(escSlash, "g");\n var escOpenPattern = new RegExp(escOpen, "g");\n var escClosePattern = new RegExp(escClose, "g");\n var escCommaPattern = new RegExp(escComma, "g");\n var escPeriodPattern = new RegExp(escPeriod, "g");\n var slashPattern = /\\\\\\\\/g;\n var openPattern = /\\\\{/g;\n var closePattern = /\\\\}/g;\n var commaPattern = /\\\\,/g;\n var periodPattern = /\\\\\\./g;\n var EXPANSION_MAX = 1e5;\n function numeric(str) {\n return !isNaN(str) ? parseInt(str, 10) : str.charCodeAt(0);\n }\n function escapeBraces(str) {\n return str.replace(slashPattern, escSlash).replace(openPattern, escOpen).replace(closePattern, escClose).replace(commaPattern, escComma).replace(periodPattern, escPeriod);\n }\n function unescapeBraces(str) {\n return str.replace(escSlashPattern, "\\\\").replace(escOpenPattern, "{").replace(escClosePattern, "}").replace(escCommaPattern, ",").replace(escPeriodPattern, ".");\n }\n function parseCommaParts(str) {\n if (!str) {\n return [""];\n }\n const parts = [];\n const m = balanced("{", "}", str);\n if (!m) {\n return str.split(",");\n }\n const { pre, body, post } = m;\n const p = pre.split(",");\n p[p.length - 1] += "{" + body + "}";\n const postParts = parseCommaParts(post);\n if (post.length) {\n ;\n p[p.length - 1] += postParts.shift();\n p.push.apply(p, postParts);\n }\n parts.push.apply(parts, p);\n return parts;\n }\n function expand(str, options = {}) {\n if (!str) {\n return [];\n }\n const { max = EXPANSION_MAX } = options;\n if (str.slice(0, 2) === "{}") {\n str = "\\\\{\\\\}" + str.slice(2);\n }\n return expand_(escapeBraces(str), max, true).map(unescapeBraces);\n }\n function embrace(str) {\n return "{" + str + "}";\n }\n function isPadded(el) {\n return /^-?0\\d/.test(el);\n }\n function lte(i, y) {\n return i <= y;\n }\n function gte(i, y) {\n return i >= y;\n }\n function expand_(str, max, isTop) {\n const expansions = [];\n for (; ; ) {\n const m = balanced("{", "}", str);\n if (!m)\n return [str];\n const pre = m.pre;\n if (/\\$$/.test(m.pre)) {\n const post2 = m.post.length ? expand_(m.post, max, false) : [""];\n for (let k = 0; k < post2.length && k < max; k++) {\n const expansion = pre + "{" + m.body + "}" + post2[k];\n expansions.push(expansion);\n }\n return expansions;\n }\n const isNumericSequence = /^-?\\d+\\.\\.-?\\d+(?:\\.\\.-?\\d+)?$/.test(m.body);\n const isAlphaSequence = /^[a-zA-Z]\\.\\.[a-zA-Z](?:\\.\\.-?\\d+)?$/.test(m.body);\n const isSequence = isNumericSequence || isAlphaSequence;\n const isOptions = m.body.indexOf(",") >= 0;\n if (!isSequence && !isOptions) {\n if (m.post.match(/,(?!,).*\\}/)) {\n str = m.pre + "{" + m.body + escClose + m.post;\n isTop = true;\n continue;\n }\n return [str];\n }\n const post = m.post.length ? expand_(m.post, max, false) : [""];\n let n;\n if (isSequence) {\n n = m.body.split(/\\.\\./);\n } else {\n n = parseCommaParts(m.body);\n if (n.length === 1 && n[0] !== void 0) {\n n = expand_(n[0], max, false).map(embrace);\n if (n.length === 1) {\n return post.map((p) => m.pre + n[0] + p);\n }\n }\n }\n let N;\n if (isSequence && n[0] !== void 0 && n[1] !== void 0) {\n const x = numeric(n[0]);\n const y = numeric(n[1]);\n const width = Math.max(n[0].length, n[1].length);\n let incr = n.length === 3 && n[2] !== void 0 ? Math.max(Math.abs(numeric(n[2])), 1) : 1;\n let test = lte;\n const reverse = y < x;\n if (reverse) {\n incr *= -1;\n test = gte;\n }\n const pad = n.some(isPadded);\n N = [];\n for (let i = x; test(i, y) && N.length < max; i += incr) {\n let c;\n if (isAlphaSequence) {\n c = String.fromCharCode(i);\n if (c === "\\\\") {\n c = "";\n }\n } else {\n c = String(i);\n if (pad) {\n const need = width - c.length;\n if (need > 0) {\n const z = new Array(need + 1).join("0");\n if (i < 0) {\n c = "-" + z + c.slice(1);\n } else {\n c = z + c;\n }\n }\n }\n }\n N.push(c);\n }\n } else {\n N = [];\n for (let j = 0; j < n.length; j++) {\n N.push.apply(N, expand_(n[j], max, false));\n }\n }\n for (let j = 0; j < N.length; j++) {\n for (let k = 0; k < post.length && expansions.length < max; k++) {\n const expansion = pre + N[j] + post[k];\n if (!isTop || isSequence || expansion) {\n expansions.push(expansion);\n }\n }\n }\n return expansions;\n }\n }\n\n // node_modules/minimatch/dist/esm/assert-valid-pattern.js\n var MAX_PATTERN_LENGTH = 1024 * 64;\n var assertValidPattern = (pattern) => {\n if (typeof pattern !== "string") {\n throw new TypeError("invalid pattern");\n }\n if (pattern.length > MAX_PATTERN_LENGTH) {\n throw new TypeError("pattern is too long");\n }\n };\n\n // node_modules/minimatch/dist/esm/brace-expressions.js\n var posixClasses = {\n "[:alnum:]": ["\\\\p{L}\\\\p{Nl}\\\\p{Nd}", true],\n "[:alpha:]": ["\\\\p{L}\\\\p{Nl}", true],\n "[:ascii:]": ["\\\\x00-\\\\x7f", false],\n "[:blank:]": ["\\\\p{Zs}\\\\t", true],\n "[:cntrl:]": ["\\\\p{Cc}", true],\n "[:digit:]": ["\\\\p{Nd}", true],\n "[:graph:]": ["\\\\p{Z}\\\\p{C}", true, true],\n "[:lower:]": ["\\\\p{Ll}", true],\n "[:print:]": ["\\\\p{C}", true],\n "[:punct:]": ["\\\\p{P}", true],\n "[:space:]": ["\\\\p{Z}\\\\t\\\\r\\\\n\\\\v\\\\f", true],\n "[:upper:]": ["\\\\p{Lu}", true],\n "[:word:]": ["\\\\p{L}\\\\p{Nl}\\\\p{Nd}\\\\p{Pc}", true],\n "[:xdigit:]": ["A-Fa-f0-9", false]\n };\n var braceEscape = (s) => s.replace(/[[\\]\\\\-]/g, "\\\\$&");\n var regexpEscape = (s) => s.replace(/[-[\\]{}()*+?.,\\\\^$|#\\s]/g, "\\\\$&");\n var rangesToString = (ranges) => ranges.join("");\n var parseClass = (glob, position) => {\n const pos = position;\n if (glob.charAt(pos) !== "[") {\n throw new Error("not in a brace expression");\n }\n const ranges = [];\n const negs = [];\n let i = pos + 1;\n let sawStart = false;\n let uflag = false;\n let escaping = false;\n let negate = false;\n let endPos = pos;\n let rangeStart = "";\n WHILE: while (i < glob.length) {\n const c = glob.charAt(i);\n if ((c === "!" || c === "^") && i === pos + 1) {\n negate = true;\n i++;\n continue;\n }\n if (c === "]" && sawStart && !escaping) {\n endPos = i + 1;\n break;\n }\n sawStart = true;\n if (c === "\\\\") {\n if (!escaping) {\n escaping = true;\n i++;\n continue;\n }\n }\n if (c === "[" && !escaping) {\n for (const [cls, [unip, u, neg]] of Object.entries(posixClasses)) {\n if (glob.startsWith(cls, i)) {\n if (rangeStart) {\n return ["$.", false, glob.length - pos, true];\n }\n i += cls.length;\n if (neg)\n negs.push(unip);\n else\n ranges.push(unip);\n uflag = uflag || u;\n continue WHILE;\n }\n }\n }\n escaping = false;\n if (rangeStart) {\n if (c > rangeStart) {\n ranges.push(braceEscape(rangeStart) + "-" + braceEscape(c));\n } else if (c === rangeStart) {\n ranges.push(braceEscape(c));\n }\n rangeStart = "";\n i++;\n continue;\n }\n if (glob.startsWith("-]", i + 1)) {\n ranges.push(braceEscape(c + "-"));\n i += 2;\n continue;\n }\n if (glob.startsWith("-", i + 1)) {\n rangeStart = c;\n i += 2;\n continue;\n }\n ranges.push(braceEscape(c));\n i++;\n }\n if (endPos < i) {\n return ["", false, 0, false];\n }\n if (!ranges.length && !negs.length) {\n return ["$.", false, glob.length - pos, true];\n }\n if (negs.length === 0 && ranges.length === 1 && /^\\\\?.$/.test(ranges[0]) && !negate) {\n const r = ranges[0].length === 2 ? ranges[0].slice(-1) : ranges[0];\n return [regexpEscape(r), false, endPos - pos, false];\n }\n const sranges = "[" + (negate ? "^" : "") + rangesToString(ranges) + "]";\n const snegs = "[" + (negate ? "" : "^") + rangesToString(negs) + "]";\n const comb = ranges.length && negs.length ? "(" + sranges + "|" + snegs + ")" : ranges.length ? sranges : snegs;\n return [comb, uflag, endPos - pos, true];\n };\n\n // node_modules/minimatch/dist/esm/unescape.js\n var unescape = (s, { windowsPathsNoEscape = false, magicalBraces = true } = {}) => {\n if (magicalBraces) {\n return windowsPathsNoEscape ? s.replace(/\\[([^/\\\\])\\]/g, "$1") : s.replace(/((?!\\\\).|^)\\[([^/\\\\])\\]/g, "$1$2").replace(/\\\\([^/])/g, "$1");\n }\n return windowsPathsNoEscape ? s.replace(/\\[([^/\\\\{}])\\]/g, "$1") : s.replace(/((?!\\\\).|^)\\[([^/\\\\{}])\\]/g, "$1$2").replace(/\\\\([^/{}])/g, "$1");\n };\n\n // node_modules/minimatch/dist/esm/ast.js\n var _a;\n var types = /* @__PURE__ */ new Set(["!", "?", "+", "*", "@"]);\n var isExtglobType = (c) => types.has(c);\n var isExtglobAST = (c) => isExtglobType(c.type);\n var adoptionMap = /* @__PURE__ */ new Map([\n ["!", ["@"]],\n ["?", ["?", "@"]],\n ["@", ["@"]],\n ["*", ["*", "+", "?", "@"]],\n ["+", ["+", "@"]]\n ]);\n var adoptionWithSpaceMap = /* @__PURE__ */ new Map([\n ["!", ["?"]],\n ["@", ["?"]],\n ["+", ["?", "*"]]\n ]);\n var adoptionAnyMap = /* @__PURE__ */ new Map([\n ["!", ["?", "@"]],\n ["?", ["?", "@"]],\n ["@", ["?", "@"]],\n ["*", ["*", "+", "?", "@"]],\n ["+", ["+", "@", "?", "*"]]\n ]);\n var usurpMap = /* @__PURE__ */ new Map([\n ["!", /* @__PURE__ */ new Map([["!", "@"]])],\n [\n "?",\n /* @__PURE__ */ new Map([\n ["*", "*"],\n ["+", "*"]\n ])\n ],\n [\n "@",\n /* @__PURE__ */ new Map([\n ["!", "!"],\n ["?", "?"],\n ["@", "@"],\n ["*", "*"],\n ["+", "+"]\n ])\n ],\n [\n "+",\n /* @__PURE__ */ new Map([\n ["?", "*"],\n ["*", "*"]\n ])\n ]\n ]);\n var startNoTraversal = "(?!(?:^|/)\\\\.\\\\.?(?:$|/))";\n var startNoDot = "(?!\\\\.)";\n var addPatternStart = /* @__PURE__ */ new Set(["[", "."]);\n var justDots = /* @__PURE__ */ new Set(["..", "."]);\n var reSpecials = new Set("().*{}+?[]^$\\\\!");\n var regExpEscape = (s) => s.replace(/[-[\\]{}()*+?.,\\\\^$|#\\s]/g, "\\\\$&");\n var qmark = "[^/]";\n var star = qmark + "*?";\n var starNoEmpty = qmark + "+?";\n var ID = 0;\n var AST = class {\n type;\n #root;\n #hasMagic;\n #uflag = false;\n #parts = [];\n #parent;\n #parentIndex;\n #negs;\n #filledNegs = false;\n #options;\n #toString;\n // set to true if it\'s an extglob with no children\n // (which really means one child of \'\')\n #emptyExt = false;\n id = ++ID;\n get depth() {\n return (this.#parent?.depth ?? -1) + 1;\n }\n [/* @__PURE__ */ Symbol.for("nodejs.util.inspect.custom")]() {\n return {\n "@@type": "AST",\n id: this.id,\n type: this.type,\n root: this.#root.id,\n parent: this.#parent?.id,\n depth: this.depth,\n partsLength: this.#parts.length,\n parts: this.#parts\n };\n }\n constructor(type, parent, options = {}) {\n this.type = type;\n if (type)\n this.#hasMagic = true;\n this.#parent = parent;\n this.#root = this.#parent ? this.#parent.#root : this;\n this.#options = this.#root === this ? options : this.#root.#options;\n this.#negs = this.#root === this ? [] : this.#root.#negs;\n if (type === "!" && !this.#root.#filledNegs)\n this.#negs.push(this);\n this.#parentIndex = this.#parent ? this.#parent.#parts.length : 0;\n }\n get hasMagic() {\n if (this.#hasMagic !== void 0)\n return this.#hasMagic;\n for (const p of this.#parts) {\n if (typeof p === "string")\n continue;\n if (p.type || p.hasMagic)\n return this.#hasMagic = true;\n }\n return this.#hasMagic;\n }\n // reconstructs the pattern\n toString() {\n return this.#toString !== void 0 ? this.#toString : !this.type ? this.#toString = this.#parts.map((p) => String(p)).join("") : this.#toString = this.type + "(" + this.#parts.map((p) => String(p)).join("|") + ")";\n }\n #fillNegs() {\n if (this !== this.#root)\n throw new Error("should only call on root");\n if (this.#filledNegs)\n return this;\n this.toString();\n this.#filledNegs = true;\n let n;\n while (n = this.#negs.pop()) {\n if (n.type !== "!")\n continue;\n let p = n;\n let pp = p.#parent;\n while (pp) {\n for (let i = p.#parentIndex + 1; !pp.type && i < pp.#parts.length; i++) {\n for (const part of n.#parts) {\n if (typeof part === "string") {\n throw new Error("string part in extglob AST??");\n }\n part.copyIn(pp.#parts[i]);\n }\n }\n p = pp;\n pp = p.#parent;\n }\n }\n return this;\n }\n push(...parts) {\n for (const p of parts) {\n if (p === "")\n continue;\n if (typeof p !== "string" && !(p instanceof _a && p.#parent === this)) {\n throw new Error("invalid part: " + p);\n }\n this.#parts.push(p);\n }\n }\n toJSON() {\n const ret = this.type === null ? this.#parts.slice().map((p) => typeof p === "string" ? p : p.toJSON()) : [this.type, ...this.#parts.map((p) => p.toJSON())];\n if (this.isStart() && !this.type)\n ret.unshift([]);\n if (this.isEnd() && (this === this.#root || this.#root.#filledNegs && this.#parent?.type === "!")) {\n ret.push({});\n }\n return ret;\n }\n isStart() {\n if (this.#root === this)\n return true;\n if (!this.#parent?.isStart())\n return false;\n if (this.#parentIndex === 0)\n return true;\n const p = this.#parent;\n for (let i = 0; i < this.#parentIndex; i++) {\n const pp = p.#parts[i];\n if (!(pp instanceof _a && pp.type === "!")) {\n return false;\n }\n }\n return true;\n }\n isEnd() {\n if (this.#root === this)\n return true;\n if (this.#parent?.type === "!")\n return true;\n if (!this.#parent?.isEnd())\n return false;\n if (!this.type)\n return this.#parent?.isEnd();\n const pl = this.#parent ? this.#parent.#parts.length : 0;\n return this.#parentIndex === pl - 1;\n }\n copyIn(part) {\n if (typeof part === "string")\n this.push(part);\n else\n this.push(part.clone(this));\n }\n clone(parent) {\n const c = new _a(this.type, parent);\n for (const p of this.#parts) {\n c.copyIn(p);\n }\n return c;\n }\n static #parseAST(str, ast, pos, opt, extDepth) {\n const maxDepth = opt.maxExtglobRecursion ?? 2;\n let escaping = false;\n let inBrace = false;\n let braceStart = -1;\n let braceNeg = false;\n if (ast.type === null) {\n let i2 = pos;\n let acc2 = "";\n while (i2 < str.length) {\n const c = str.charAt(i2++);\n if (escaping || c === "\\\\") {\n escaping = !escaping;\n acc2 += c;\n continue;\n }\n if (inBrace) {\n if (i2 === braceStart + 1) {\n if (c === "^" || c === "!") {\n braceNeg = true;\n }\n } else if (c === "]" && !(i2 === braceStart + 2 && braceNeg)) {\n inBrace = false;\n }\n acc2 += c;\n continue;\n } else if (c === "[") {\n inBrace = true;\n braceStart = i2;\n braceNeg = false;\n acc2 += c;\n continue;\n }\n const doRecurse = !opt.noext && isExtglobType(c) && str.charAt(i2) === "(" && extDepth <= maxDepth;\n if (doRecurse) {\n ast.push(acc2);\n acc2 = "";\n const ext2 = new _a(c, ast);\n i2 = _a.#parseAST(str, ext2, i2, opt, extDepth + 1);\n ast.push(ext2);\n continue;\n }\n acc2 += c;\n }\n ast.push(acc2);\n return i2;\n }\n let i = pos + 1;\n let part = new _a(null, ast);\n const parts = [];\n let acc = "";\n while (i < str.length) {\n const c = str.charAt(i++);\n if (escaping || c === "\\\\") {\n escaping = !escaping;\n acc += c;\n continue;\n }\n if (inBrace) {\n if (i === braceStart + 1) {\n if (c === "^" || c === "!") {\n braceNeg = true;\n }\n } else if (c === "]" && !(i === braceStart + 2 && braceNeg)) {\n inBrace = false;\n }\n acc += c;\n continue;\n } else if (c === "[") {\n inBrace = true;\n braceStart = i;\n braceNeg = false;\n acc += c;\n continue;\n }\n const doRecurse = !opt.noext && isExtglobType(c) && str.charAt(i) === "(" && /* c8 ignore start - the maxDepth is sufficient here */\n (extDepth <= maxDepth || ast && ast.#canAdoptType(c));\n if (doRecurse) {\n const depthAdd = ast && ast.#canAdoptType(c) ? 0 : 1;\n part.push(acc);\n acc = "";\n const ext2 = new _a(c, part);\n part.push(ext2);\n i = _a.#parseAST(str, ext2, i, opt, extDepth + depthAdd);\n continue;\n }\n if (c === "|") {\n part.push(acc);\n acc = "";\n parts.push(part);\n part = new _a(null, ast);\n continue;\n }\n if (c === ")") {\n if (acc === "" && ast.#parts.length === 0) {\n ast.#emptyExt = true;\n }\n part.push(acc);\n acc = "";\n ast.push(...parts, part);\n return i;\n }\n acc += c;\n }\n ast.type = null;\n ast.#hasMagic = void 0;\n ast.#parts = [str.substring(pos - 1)];\n return i;\n }\n #canAdoptWithSpace(child) {\n return this.#canAdopt(child, adoptionWithSpaceMap);\n }\n #canAdopt(child, map = adoptionMap) {\n if (!child || typeof child !== "object" || child.type !== null || child.#parts.length !== 1 || this.type === null) {\n return false;\n }\n const gc = child.#parts[0];\n if (!gc || typeof gc !== "object" || gc.type === null) {\n return false;\n }\n return this.#canAdoptType(gc.type, map);\n }\n #canAdoptType(c, map = adoptionAnyMap) {\n return !!map.get(this.type)?.includes(c);\n }\n #adoptWithSpace(child, index) {\n const gc = child.#parts[0];\n const blank = new _a(null, gc, this.options);\n blank.#parts.push("");\n gc.push(blank);\n this.#adopt(child, index);\n }\n #adopt(child, index) {\n const gc = child.#parts[0];\n this.#parts.splice(index, 1, ...gc.#parts);\n for (const p of gc.#parts) {\n if (typeof p === "object")\n p.#parent = this;\n }\n this.#toString = void 0;\n }\n #canUsurpType(c) {\n const m = usurpMap.get(this.type);\n return !!m?.has(c);\n }\n #canUsurp(child) {\n if (!child || typeof child !== "object" || child.type !== null || child.#parts.length !== 1 || this.type === null || this.#parts.length !== 1) {\n return false;\n }\n const gc = child.#parts[0];\n if (!gc || typeof gc !== "object" || gc.type === null) {\n return false;\n }\n return this.#canUsurpType(gc.type);\n }\n #usurp(child) {\n const m = usurpMap.get(this.type);\n const gc = child.#parts[0];\n const nt = m?.get(gc.type);\n if (!nt)\n return false;\n this.#parts = gc.#parts;\n for (const p of this.#parts) {\n if (typeof p === "object") {\n p.#parent = this;\n }\n }\n this.type = nt;\n this.#toString = void 0;\n this.#emptyExt = false;\n }\n static fromGlob(pattern, options = {}) {\n const ast = new _a(null, void 0, options);\n _a.#parseAST(pattern, ast, 0, options, 0);\n return ast;\n }\n // returns the regular expression if there\'s magic, or the unescaped\n // string if not.\n toMMPattern() {\n if (this !== this.#root)\n return this.#root.toMMPattern();\n const glob = this.toString();\n const [re, body, hasMagic, uflag] = this.toRegExpSource();\n const anyMagic = hasMagic || this.#hasMagic || this.#options.nocase && !this.#options.nocaseMagicOnly && glob.toUpperCase() !== glob.toLowerCase();\n if (!anyMagic) {\n return body;\n }\n const flags = (this.#options.nocase ? "i" : "") + (uflag ? "u" : "");\n return Object.assign(new RegExp(`^${re}$`, flags), {\n _src: re,\n _glob: glob\n });\n }\n get options() {\n return this.#options;\n }\n // returns the string match, the regexp source, whether there\'s magic\n // in the regexp (so a regular expression is required) and whether or\n // not the uflag is needed for the regular expression (for posix classes)\n // TODO: instead of injecting the start/end at this point, just return\n // the BODY of the regexp, along with the start/end portions suitable\n // for binding the start/end in either a joined full-path makeRe context\n // (where we bind to (^|/), or a standalone matchPart context (where\n // we bind to ^, and not /). Otherwise slashes get duped!\n //\n // In part-matching mode, the start is:\n // - if not isStart: nothing\n // - if traversal possible, but not allowed: ^(?!\\.\\.?$)\n // - if dots allowed or not possible: ^\n // - if dots possible and not allowed: ^(?!\\.)\n // end is:\n // - if not isEnd(): nothing\n // - else: $\n //\n // In full-path matching mode, we put the slash at the START of the\n // pattern, so start is:\n // - if first pattern: same as part-matching mode\n // - if not isStart(): nothing\n // - if traversal possible, but not allowed: /(?!\\.\\.?(?:$|/))\n // - if dots allowed or not possible: /\n // - if dots possible and not allowed: /(?!\\.)\n // end is:\n // - if last pattern, same as part-matching mode\n // - else nothing\n //\n // Always put the (?:$|/) on negated tails, though, because that has to be\n // there to bind the end of the negated pattern portion, and it\'s easier to\n // just stick it in now rather than try to inject it later in the middle of\n // the pattern.\n //\n // We can just always return the same end, and leave it up to the caller\n // to know whether it\'s going to be used joined or in parts.\n // And, if the start is adjusted slightly, can do the same there:\n // - if not isStart: nothing\n // - if traversal possible, but not allowed: (?:/|^)(?!\\.\\.?$)\n // - if dots allowed or not possible: (?:/|^)\n // - if dots possible and not allowed: (?:/|^)(?!\\.)\n //\n // But it\'s better to have a simpler binding without a conditional, for\n // performance, so probably better to return both start options.\n //\n // Then the caller just ignores the end if it\'s not the first pattern,\n // and the start always gets applied.\n //\n // But that\'s always going to be $ if it\'s the ending pattern, or nothing,\n // so the caller can just attach $ at the end of the pattern when building.\n //\n // So the todo is:\n // - better detect what kind of start is needed\n // - return both flavors of starting pattern\n // - attach $ at the end of the pattern when creating the actual RegExp\n //\n // Ah, but wait, no, that all only applies to the root when the first pattern\n // is not an extglob. If the first pattern IS an extglob, then we need all\n // that dot prevention biz to live in the extglob portions, because eg\n // +(*|.x*) can match .xy but not .yx.\n //\n // So, return the two flavors if it\'s #root and the first child is not an\n // AST, otherwise leave it to the child AST to handle it, and there,\n // use the (?:^|/) style of start binding.\n //\n // Even simplified further:\n // - Since the start for a join is eg /(?!\\.) and the start for a part\n // is ^(?!\\.), we can just prepend (?!\\.) to the pattern (either root\n // or start or whatever) and prepend ^ or / at the Regexp construction.\n toRegExpSource(allowDot) {\n const dot = allowDot ?? !!this.#options.dot;\n if (this.#root === this) {\n this.#flatten();\n this.#fillNegs();\n }\n if (!isExtglobAST(this)) {\n const noEmpty = this.isStart() && this.isEnd() && !this.#parts.some((s) => typeof s !== "string");\n const src = this.#parts.map((p) => {\n const [re, _, hasMagic, uflag] = typeof p === "string" ? _a.#parseGlob(p, this.#hasMagic, noEmpty) : p.toRegExpSource(allowDot);\n this.#hasMagic = this.#hasMagic || hasMagic;\n this.#uflag = this.#uflag || uflag;\n return re;\n }).join("");\n let start2 = "";\n if (this.isStart()) {\n if (typeof this.#parts[0] === "string") {\n const dotTravAllowed = this.#parts.length === 1 && justDots.has(this.#parts[0]);\n if (!dotTravAllowed) {\n const aps = addPatternStart;\n const needNoTrav = (\n // dots are allowed, and the pattern starts with [ or .\n dot && aps.has(src.charAt(0)) || // the pattern starts with \\., and then [ or .\n src.startsWith("\\\\.") && aps.has(src.charAt(2)) || // the pattern starts with \\.\\., and then [ or .\n src.startsWith("\\\\.\\\\.") && aps.has(src.charAt(4))\n );\n const needNoDot = !dot && !allowDot && aps.has(src.charAt(0));\n start2 = needNoTrav ? startNoTraversal : needNoDot ? startNoDot : "";\n }\n }\n }\n let end = "";\n if (this.isEnd() && this.#root.#filledNegs && this.#parent?.type === "!") {\n end = "(?:$|\\\\/)";\n }\n const final2 = start2 + src + end;\n return [\n final2,\n unescape(src),\n this.#hasMagic = !!this.#hasMagic,\n this.#uflag\n ];\n }\n const repeated = this.type === "*" || this.type === "+";\n const start = this.type === "!" ? "(?:(?!(?:" : "(?:";\n let body = this.#partsToRegExp(dot);\n if (this.isStart() && this.isEnd() && !body && this.type !== "!") {\n const s = this.toString();\n const me = this;\n me.#parts = [s];\n me.type = null;\n me.#hasMagic = void 0;\n return [s, unescape(this.toString()), false, false];\n }\n let bodyDotAllowed = !repeated || allowDot || dot || !startNoDot ? "" : this.#partsToRegExp(true);\n if (bodyDotAllowed === body) {\n bodyDotAllowed = "";\n }\n if (bodyDotAllowed) {\n body = `(?:${body})(?:${bodyDotAllowed})*?`;\n }\n let final = "";\n if (this.type === "!" && this.#emptyExt) {\n final = (this.isStart() && !dot ? startNoDot : "") + starNoEmpty;\n } else {\n const close = this.type === "!" ? (\n // !() must match something,but !(x) can match \'\'\n "))" + (this.isStart() && !dot && !allowDot ? startNoDot : "") + star + ")"\n ) : this.type === "@" ? ")" : this.type === "?" ? ")?" : this.type === "+" && bodyDotAllowed ? ")" : this.type === "*" && bodyDotAllowed ? `)?` : `)${this.type}`;\n final = start + body + close;\n }\n return [\n final,\n unescape(body),\n this.#hasMagic = !!this.#hasMagic,\n this.#uflag\n ];\n }\n #flatten() {\n if (!isExtglobAST(this)) {\n for (const p of this.#parts) {\n if (typeof p === "object") {\n p.#flatten();\n }\n }\n } else {\n let iterations = 0;\n let done = false;\n do {\n done = true;\n for (let i = 0; i < this.#parts.length; i++) {\n const c = this.#parts[i];\n if (typeof c === "object") {\n c.#flatten();\n if (this.#canAdopt(c)) {\n done = false;\n this.#adopt(c, i);\n } else if (this.#canAdoptWithSpace(c)) {\n done = false;\n this.#adoptWithSpace(c, i);\n } else if (this.#canUsurp(c)) {\n done = false;\n this.#usurp(c);\n }\n }\n }\n } while (!done && ++iterations < 10);\n }\n this.#toString = void 0;\n }\n #partsToRegExp(dot) {\n return this.#parts.map((p) => {\n if (typeof p === "string") {\n throw new Error("string type in extglob ast??");\n }\n const [re, _, _hasMagic, uflag] = p.toRegExpSource(dot);\n this.#uflag = this.#uflag || uflag;\n return re;\n }).filter((p) => !(this.isStart() && this.isEnd()) || !!p).join("|");\n }\n static #parseGlob(glob, hasMagic, noEmpty = false) {\n let escaping = false;\n let re = "";\n let uflag = false;\n let inStar = false;\n for (let i = 0; i < glob.length; i++) {\n const c = glob.charAt(i);\n if (escaping) {\n escaping = false;\n re += (reSpecials.has(c) ? "\\\\" : "") + c;\n continue;\n }\n if (c === "*") {\n if (inStar)\n continue;\n inStar = true;\n re += noEmpty && /^[*]+$/.test(glob) ? starNoEmpty : star;\n hasMagic = true;\n continue;\n } else {\n inStar = false;\n }\n if (c === "\\\\") {\n if (i === glob.length - 1) {\n re += "\\\\\\\\";\n } else {\n escaping = true;\n }\n continue;\n }\n if (c === "[") {\n const [src, needUflag, consumed, magic] = parseClass(glob, i);\n if (consumed) {\n re += src;\n uflag = uflag || needUflag;\n i += consumed - 1;\n hasMagic = hasMagic || magic;\n continue;\n }\n }\n if (c === "?") {\n re += qmark;\n hasMagic = true;\n continue;\n }\n re += regExpEscape(c);\n }\n return [re, unescape(glob), !!hasMagic, uflag];\n }\n };\n _a = AST;\n\n // node_modules/minimatch/dist/esm/escape.js\n var escape = (s, { windowsPathsNoEscape = false, magicalBraces = false } = {}) => {\n if (magicalBraces) {\n return windowsPathsNoEscape ? s.replace(/[?*()[\\]{}]/g, "[$&]") : s.replace(/[?*()[\\]\\\\{}]/g, "\\\\$&");\n }\n return windowsPathsNoEscape ? s.replace(/[?*()[\\]]/g, "[$&]") : s.replace(/[?*()[\\]\\\\]/g, "\\\\$&");\n };\n\n // node_modules/minimatch/dist/esm/index.js\n var minimatch = (p, pattern, options = {}) => {\n assertValidPattern(pattern);\n if (!options.nocomment && pattern.charAt(0) === "#") {\n return false;\n }\n return new Minimatch(pattern, options).match(p);\n };\n var starDotExtRE = /^\\*+([^+@!?*[(]*)$/;\n var starDotExtTest = (ext2) => (f) => !f.startsWith(".") && f.endsWith(ext2);\n var starDotExtTestDot = (ext2) => (f) => f.endsWith(ext2);\n var starDotExtTestNocase = (ext2) => {\n ext2 = ext2.toLowerCase();\n return (f) => !f.startsWith(".") && f.toLowerCase().endsWith(ext2);\n };\n var starDotExtTestNocaseDot = (ext2) => {\n ext2 = ext2.toLowerCase();\n return (f) => f.toLowerCase().endsWith(ext2);\n };\n var starDotStarRE = /^\\*+\\.\\*+$/;\n var starDotStarTest = (f) => !f.startsWith(".") && f.includes(".");\n var starDotStarTestDot = (f) => f !== "." && f !== ".." && f.includes(".");\n var dotStarRE = /^\\.\\*+$/;\n var dotStarTest = (f) => f !== "." && f !== ".." && f.startsWith(".");\n var starRE = /^\\*+$/;\n var starTest = (f) => f.length !== 0 && !f.startsWith(".");\n var starTestDot = (f) => f.length !== 0 && f !== "." && f !== "..";\n var qmarksRE = /^\\?+([^+@!?*[(]*)?$/;\n var qmarksTestNocase = ([$0, ext2 = ""]) => {\n const noext = qmarksTestNoExt([$0]);\n if (!ext2)\n return noext;\n ext2 = ext2.toLowerCase();\n return (f) => noext(f) && f.toLowerCase().endsWith(ext2);\n };\n var qmarksTestNocaseDot = ([$0, ext2 = ""]) => {\n const noext = qmarksTestNoExtDot([$0]);\n if (!ext2)\n return noext;\n ext2 = ext2.toLowerCase();\n return (f) => noext(f) && f.toLowerCase().endsWith(ext2);\n };\n var qmarksTestDot = ([$0, ext2 = ""]) => {\n const noext = qmarksTestNoExtDot([$0]);\n return !ext2 ? noext : (f) => noext(f) && f.endsWith(ext2);\n };\n var qmarksTest = ([$0, ext2 = ""]) => {\n const noext = qmarksTestNoExt([$0]);\n return !ext2 ? noext : (f) => noext(f) && f.endsWith(ext2);\n };\n var qmarksTestNoExt = ([$0]) => {\n const len = $0.length;\n return (f) => f.length === len && !f.startsWith(".");\n };\n var qmarksTestNoExtDot = ([$0]) => {\n const len = $0.length;\n return (f) => f.length === len && f !== "." && f !== "..";\n };\n var defaultPlatform = typeof process === "object" && process ? typeof process.env === "object" && process.env && process.env.__MINIMATCH_TESTING_PLATFORM__ || process.platform : "posix";\n var path = {\n win32: { sep: "\\\\" },\n posix: { sep: "/" }\n };\n var sep = defaultPlatform === "win32" ? path.win32.sep : path.posix.sep;\n minimatch.sep = sep;\n var GLOBSTAR = /* @__PURE__ */ Symbol("globstar **");\n minimatch.GLOBSTAR = GLOBSTAR;\n var qmark2 = "[^/]";\n var star2 = qmark2 + "*?";\n var twoStarDot = "(?:(?!(?:\\\\/|^)(?:\\\\.{1,2})($|\\\\/)).)*?";\n var twoStarNoDot = "(?:(?!(?:\\\\/|^)\\\\.).)*?";\n var filter = (pattern, options = {}) => (p) => minimatch(p, pattern, options);\n minimatch.filter = filter;\n var ext = (a, b = {}) => Object.assign({}, a, b);\n var defaults = (def) => {\n if (!def || typeof def !== "object" || !Object.keys(def).length) {\n return minimatch;\n }\n const orig = minimatch;\n const m = (p, pattern, options = {}) => orig(p, pattern, ext(def, options));\n return Object.assign(m, {\n Minimatch: class Minimatch extends orig.Minimatch {\n constructor(pattern, options = {}) {\n super(pattern, ext(def, options));\n }\n static defaults(options) {\n return orig.defaults(ext(def, options)).Minimatch;\n }\n },\n AST: class AST extends orig.AST {\n /* c8 ignore start */\n constructor(type, parent, options = {}) {\n super(type, parent, ext(def, options));\n }\n /* c8 ignore stop */\n static fromGlob(pattern, options = {}) {\n return orig.AST.fromGlob(pattern, ext(def, options));\n }\n },\n unescape: (s, options = {}) => orig.unescape(s, ext(def, options)),\n escape: (s, options = {}) => orig.escape(s, ext(def, options)),\n filter: (pattern, options = {}) => orig.filter(pattern, ext(def, options)),\n defaults: (options) => orig.defaults(ext(def, options)),\n makeRe: (pattern, options = {}) => orig.makeRe(pattern, ext(def, options)),\n braceExpand: (pattern, options = {}) => orig.braceExpand(pattern, ext(def, options)),\n match: (list, pattern, options = {}) => orig.match(list, pattern, ext(def, options)),\n sep: orig.sep,\n GLOBSTAR\n });\n };\n minimatch.defaults = defaults;\n var braceExpand = (pattern, options = {}) => {\n assertValidPattern(pattern);\n if (options.nobrace || !/\\{(?:(?!\\{).)*\\}/.test(pattern)) {\n return [pattern];\n }\n return expand(pattern, { max: options.braceExpandMax });\n };\n minimatch.braceExpand = braceExpand;\n var makeRe = (pattern, options = {}) => new Minimatch(pattern, options).makeRe();\n minimatch.makeRe = makeRe;\n var match = (list, pattern, options = {}) => {\n const mm = new Minimatch(pattern, options);\n list = list.filter((f) => mm.match(f));\n if (mm.options.nonull && !list.length) {\n list.push(pattern);\n }\n return list;\n };\n minimatch.match = match;\n var globMagic = /[?*]|[+@!]\\(.*?\\)|\\[|\\]/;\n var regExpEscape2 = (s) => s.replace(/[-[\\]{}()*+?.,\\\\^$|#\\s]/g, "\\\\$&");\n var Minimatch = class {\n options;\n set;\n pattern;\n windowsPathsNoEscape;\n nonegate;\n negate;\n comment;\n empty;\n preserveMultipleSlashes;\n partial;\n globSet;\n globParts;\n nocase;\n isWindows;\n platform;\n windowsNoMagicRoot;\n maxGlobstarRecursion;\n regexp;\n constructor(pattern, options = {}) {\n assertValidPattern(pattern);\n options = options || {};\n this.options = options;\n this.maxGlobstarRecursion = options.maxGlobstarRecursion ?? 200;\n this.pattern = pattern;\n this.platform = options.platform || defaultPlatform;\n this.isWindows = this.platform === "win32";\n const awe = "allowWindowsEscape";\n this.windowsPathsNoEscape = !!options.windowsPathsNoEscape || options[awe] === false;\n if (this.windowsPathsNoEscape) {\n this.pattern = this.pattern.replace(/\\\\/g, "/");\n }\n this.preserveMultipleSlashes = !!options.preserveMultipleSlashes;\n this.regexp = null;\n this.negate = false;\n this.nonegate = !!options.nonegate;\n this.comment = false;\n this.empty = false;\n this.partial = !!options.partial;\n this.nocase = !!this.options.nocase;\n this.windowsNoMagicRoot = options.windowsNoMagicRoot !== void 0 ? options.windowsNoMagicRoot : !!(this.isWindows && this.nocase);\n this.globSet = [];\n this.globParts = [];\n this.set = [];\n this.make();\n }\n hasMagic() {\n if (this.options.magicalBraces && this.set.length > 1) {\n return true;\n }\n for (const pattern of this.set) {\n for (const part of pattern) {\n if (typeof part !== "string")\n return true;\n }\n }\n return false;\n }\n debug(..._) {\n }\n make() {\n const pattern = this.pattern;\n const options = this.options;\n if (!options.nocomment && pattern.charAt(0) === "#") {\n this.comment = true;\n return;\n }\n if (!pattern) {\n this.empty = true;\n return;\n }\n this.parseNegate();\n this.globSet = [...new Set(this.braceExpand())];\n if (options.debug) {\n this.debug = (...args) => console.error(...args);\n }\n this.debug(this.pattern, this.globSet);\n const rawGlobParts = this.globSet.map((s) => this.slashSplit(s));\n this.globParts = this.preprocess(rawGlobParts);\n this.debug(this.pattern, this.globParts);\n let set = this.globParts.map((s, _, __) => {\n if (this.isWindows && this.windowsNoMagicRoot) {\n const isUNC = s[0] === "" && s[1] === "" && (s[2] === "?" || !globMagic.test(s[2])) && !globMagic.test(s[3]);\n const isDrive = /^[a-z]:/i.test(s[0]);\n if (isUNC) {\n return [\n ...s.slice(0, 4),\n ...s.slice(4).map((ss) => this.parse(ss))\n ];\n } else if (isDrive) {\n return [s[0], ...s.slice(1).map((ss) => this.parse(ss))];\n }\n }\n return s.map((ss) => this.parse(ss));\n });\n this.debug(this.pattern, set);\n this.set = set.filter((s) => s.indexOf(false) === -1);\n if (this.isWindows) {\n for (let i = 0; i < this.set.length; i++) {\n const p = this.set[i];\n if (p[0] === "" && p[1] === "" && this.globParts[i][2] === "?" && typeof p[3] === "string" && /^[a-z]:$/i.test(p[3])) {\n p[2] = "?";\n }\n }\n }\n this.debug(this.pattern, this.set);\n }\n // various transforms to equivalent pattern sets that are\n // faster to process in a filesystem walk. The goal is to\n // eliminate what we can, and push all ** patterns as far\n // to the right as possible, even if it increases the number\n // of patterns that we have to process.\n preprocess(globParts) {\n if (this.options.noglobstar) {\n for (const partset of globParts) {\n for (let j = 0; j < partset.length; j++) {\n if (partset[j] === "**") {\n partset[j] = "*";\n }\n }\n }\n }\n const { optimizationLevel = 1 } = this.options;\n if (optimizationLevel >= 2) {\n globParts = this.firstPhasePreProcess(globParts);\n globParts = this.secondPhasePreProcess(globParts);\n } else if (optimizationLevel >= 1) {\n globParts = this.levelOneOptimize(globParts);\n } else {\n globParts = this.adjascentGlobstarOptimize(globParts);\n }\n return globParts;\n }\n // just get rid of adjascent ** portions\n adjascentGlobstarOptimize(globParts) {\n return globParts.map((parts) => {\n let gs = -1;\n while (-1 !== (gs = parts.indexOf("**", gs + 1))) {\n let i = gs;\n while (parts[i + 1] === "**") {\n i++;\n }\n if (i !== gs) {\n parts.splice(gs, i - gs);\n }\n }\n return parts;\n });\n }\n // get rid of adjascent ** and resolve .. portions\n levelOneOptimize(globParts) {\n return globParts.map((parts) => {\n parts = parts.reduce((set, part) => {\n const prev = set[set.length - 1];\n if (part === "**" && prev === "**") {\n return set;\n }\n if (part === "..") {\n if (prev && prev !== ".." && prev !== "." && prev !== "**") {\n set.pop();\n return set;\n }\n }\n set.push(part);\n return set;\n }, []);\n return parts.length === 0 ? [""] : parts;\n });\n }\n levelTwoFileOptimize(parts) {\n if (!Array.isArray(parts)) {\n parts = this.slashSplit(parts);\n }\n let didSomething = false;\n do {\n didSomething = false;\n if (!this.preserveMultipleSlashes) {\n for (let i = 1; i < parts.length - 1; i++) {\n const p = parts[i];\n if (i === 1 && p === "" && parts[0] === "")\n continue;\n if (p === "." || p === "") {\n didSomething = true;\n parts.splice(i, 1);\n i--;\n }\n }\n if (parts[0] === "." && parts.length === 2 && (parts[1] === "." || parts[1] === "")) {\n didSomething = true;\n parts.pop();\n }\n }\n let dd = 0;\n while (-1 !== (dd = parts.indexOf("..", dd + 1))) {\n const p = parts[dd - 1];\n if (p && p !== "." && p !== ".." && p !== "**" && !(this.isWindows && /^[a-z]:$/i.test(p))) {\n didSomething = true;\n parts.splice(dd - 1, 2);\n dd -= 2;\n }\n }\n } while (didSomething);\n return parts.length === 0 ? [""] : parts;\n }\n // First phase: single-pattern processing\n // <pre> is 1 or more portions\n // <rest> is 1 or more portions\n // <p> is any portion other than ., .., \'\', or **\n // <e> is . or \'\'\n //\n // **/.. is *brutal* for filesystem walking performance, because\n // it effectively resets the recursive walk each time it occurs,\n // and ** cannot be reduced out by a .. pattern part like a regexp\n // or most strings (other than .., ., and \'\') can be.\n //\n // <pre>/**/../<p>/<p>/<rest> -> {<pre>/../<p>/<p>/<rest>,<pre>/**/<p>/<p>/<rest>}\n // <pre>/<e>/<rest> -> <pre>/<rest>\n // <pre>/<p>/../<rest> -> <pre>/<rest>\n // **/**/<rest> -> **/<rest>\n //\n // **/*/<rest> -> */**/<rest> <== not valid because ** doesn\'t follow\n // this WOULD be allowed if ** did follow symlinks, or * didn\'t\n firstPhasePreProcess(globParts) {\n let didSomething = false;\n do {\n didSomething = false;\n for (let parts of globParts) {\n let gs = -1;\n while (-1 !== (gs = parts.indexOf("**", gs + 1))) {\n let gss = gs;\n while (parts[gss + 1] === "**") {\n gss++;\n }\n if (gss > gs) {\n parts.splice(gs + 1, gss - gs);\n }\n let next = parts[gs + 1];\n const p = parts[gs + 2];\n const p2 = parts[gs + 3];\n if (next !== "..")\n continue;\n if (!p || p === "." || p === ".." || !p2 || p2 === "." || p2 === "..") {\n continue;\n }\n didSomething = true;\n parts.splice(gs, 1);\n const other = parts.slice(0);\n other[gs] = "**";\n globParts.push(other);\n gs--;\n }\n if (!this.preserveMultipleSlashes) {\n for (let i = 1; i < parts.length - 1; i++) {\n const p = parts[i];\n if (i === 1 && p === "" && parts[0] === "")\n continue;\n if (p === "." || p === "") {\n didSomething = true;\n parts.splice(i, 1);\n i--;\n }\n }\n if (parts[0] === "." && parts.length === 2 && (parts[1] === "." || parts[1] === "")) {\n didSomething = true;\n parts.pop();\n }\n }\n let dd = 0;\n while (-1 !== (dd = parts.indexOf("..", dd + 1))) {\n const p = parts[dd - 1];\n if (p && p !== "." && p !== ".." && p !== "**") {\n didSomething = true;\n const needDot = dd === 1 && parts[dd + 1] === "**";\n const splin = needDot ? ["."] : [];\n parts.splice(dd - 1, 2, ...splin);\n if (parts.length === 0)\n parts.push("");\n dd -= 2;\n }\n }\n }\n } while (didSomething);\n return globParts;\n }\n // second phase: multi-pattern dedupes\n // {<pre>/*/<rest>,<pre>/<p>/<rest>} -> <pre>/*/<rest>\n // {<pre>/<rest>,<pre>/<rest>} -> <pre>/<rest>\n // {<pre>/**/<rest>,<pre>/<rest>} -> <pre>/**/<rest>\n //\n // {<pre>/**/<rest>,<pre>/**/<p>/<rest>} -> <pre>/**/<rest>\n // ^-- not valid because ** doens\'t follow symlinks\n secondPhasePreProcess(globParts) {\n for (let i = 0; i < globParts.length - 1; i++) {\n for (let j = i + 1; j < globParts.length; j++) {\n const matched = this.partsMatch(globParts[i], globParts[j], !this.preserveMultipleSlashes);\n if (matched) {\n globParts[i] = [];\n globParts[j] = matched;\n break;\n }\n }\n }\n return globParts.filter((gs) => gs.length);\n }\n partsMatch(a, b, emptyGSMatch = false) {\n let ai = 0;\n let bi = 0;\n let result = [];\n let which = "";\n while (ai < a.length && bi < b.length) {\n if (a[ai] === b[bi]) {\n result.push(which === "b" ? b[bi] : a[ai]);\n ai++;\n bi++;\n } else if (emptyGSMatch && a[ai] === "**" && b[bi] === a[ai + 1]) {\n result.push(a[ai]);\n ai++;\n } else if (emptyGSMatch && b[bi] === "**" && a[ai] === b[bi + 1]) {\n result.push(b[bi]);\n bi++;\n } else if (a[ai] === "*" && b[bi] && (this.options.dot || !b[bi].startsWith(".")) && b[bi] !== "**") {\n if (which === "b")\n return false;\n which = "a";\n result.push(a[ai]);\n ai++;\n bi++;\n } else if (b[bi] === "*" && a[ai] && (this.options.dot || !a[ai].startsWith(".")) && a[ai] !== "**") {\n if (which === "a")\n return false;\n which = "b";\n result.push(b[bi]);\n ai++;\n bi++;\n } else {\n return false;\n }\n }\n return a.length === b.length && result;\n }\n parseNegate() {\n if (this.nonegate)\n return;\n const pattern = this.pattern;\n let negate = false;\n let negateOffset = 0;\n for (let i = 0; i < pattern.length && pattern.charAt(i) === "!"; i++) {\n negate = !negate;\n negateOffset++;\n }\n if (negateOffset)\n this.pattern = pattern.slice(negateOffset);\n this.negate = negate;\n }\n // set partial to true to test if, for example,\n // "/a/b" matches the start of "/*/b/*/d"\n // Partial means, if you run out of file before you run\n // out of pattern, then that\'s fine, as long as all\n // the parts match.\n matchOne(file, pattern, partial = false) {\n let fileStartIndex = 0;\n let patternStartIndex = 0;\n if (this.isWindows) {\n const fileDrive = typeof file[0] === "string" && /^[a-z]:$/i.test(file[0]);\n const fileUNC = !fileDrive && file[0] === "" && file[1] === "" && file[2] === "?" && /^[a-z]:$/i.test(file[3]);\n const patternDrive = typeof pattern[0] === "string" && /^[a-z]:$/i.test(pattern[0]);\n const patternUNC = !patternDrive && pattern[0] === "" && pattern[1] === "" && pattern[2] === "?" && typeof pattern[3] === "string" && /^[a-z]:$/i.test(pattern[3]);\n const fdi = fileUNC ? 3 : fileDrive ? 0 : void 0;\n const pdi = patternUNC ? 3 : patternDrive ? 0 : void 0;\n if (typeof fdi === "number" && typeof pdi === "number") {\n const [fd, pd] = [\n file[fdi],\n pattern[pdi]\n ];\n if (fd.toLowerCase() === pd.toLowerCase()) {\n pattern[pdi] = fd;\n patternStartIndex = pdi;\n fileStartIndex = fdi;\n }\n }\n }\n const { optimizationLevel = 1 } = this.options;\n if (optimizationLevel >= 2) {\n file = this.levelTwoFileOptimize(file);\n }\n if (pattern.includes(GLOBSTAR)) {\n return this.#matchGlobstar(file, pattern, partial, fileStartIndex, patternStartIndex);\n }\n return this.#matchOne(file, pattern, partial, fileStartIndex, patternStartIndex);\n }\n #matchGlobstar(file, pattern, partial, fileIndex, patternIndex) {\n const firstgs = pattern.indexOf(GLOBSTAR, patternIndex);\n const lastgs = pattern.lastIndexOf(GLOBSTAR);\n const [head, body, tail] = partial ? [\n pattern.slice(patternIndex, firstgs),\n pattern.slice(firstgs + 1),\n []\n ] : [\n pattern.slice(patternIndex, firstgs),\n pattern.slice(firstgs + 1, lastgs),\n pattern.slice(lastgs + 1)\n ];\n if (head.length) {\n const fileHead = file.slice(fileIndex, fileIndex + head.length);\n if (!this.#matchOne(fileHead, head, partial, 0, 0)) {\n return false;\n }\n fileIndex += head.length;\n patternIndex += head.length;\n }\n let fileTailMatch = 0;\n if (tail.length) {\n if (tail.length + fileIndex > file.length)\n return false;\n let tailStart = file.length - tail.length;\n if (this.#matchOne(file, tail, partial, tailStart, 0)) {\n fileTailMatch = tail.length;\n } else {\n if (file[file.length - 1] !== "" || fileIndex + tail.length === file.length) {\n return false;\n }\n tailStart--;\n if (!this.#matchOne(file, tail, partial, tailStart, 0)) {\n return false;\n }\n fileTailMatch = tail.length + 1;\n }\n }\n if (!body.length) {\n let sawSome = !!fileTailMatch;\n for (let i2 = fileIndex; i2 < file.length - fileTailMatch; i2++) {\n const f = String(file[i2]);\n sawSome = true;\n if (f === "." || f === ".." || !this.options.dot && f.startsWith(".")) {\n return false;\n }\n }\n return partial || sawSome;\n }\n const bodySegments = [[[], 0]];\n let currentBody = bodySegments[0];\n let nonGsParts = 0;\n const nonGsPartsSums = [0];\n for (const b of body) {\n if (b === GLOBSTAR) {\n nonGsPartsSums.push(nonGsParts);\n currentBody = [[], 0];\n bodySegments.push(currentBody);\n } else {\n currentBody[0].push(b);\n nonGsParts++;\n }\n }\n let i = bodySegments.length - 1;\n const fileLength = file.length - fileTailMatch;\n for (const b of bodySegments) {\n b[1] = fileLength - (nonGsPartsSums[i--] + b[0].length);\n }\n return !!this.#matchGlobStarBodySections(file, bodySegments, fileIndex, 0, partial, 0, !!fileTailMatch);\n }\n // return false for "nope, not matching"\n // return null for "not matching, cannot keep trying"\n #matchGlobStarBodySections(file, bodySegments, fileIndex, bodyIndex, partial, globStarDepth, sawTail) {\n const bs = bodySegments[bodyIndex];\n if (!bs) {\n for (let i = fileIndex; i < file.length; i++) {\n sawTail = true;\n const f = file[i];\n if (f === "." || f === ".." || !this.options.dot && f.startsWith(".")) {\n return false;\n }\n }\n return sawTail;\n }\n const [body, after] = bs;\n while (fileIndex <= after) {\n const m = this.#matchOne(file.slice(0, fileIndex + body.length), body, partial, fileIndex, 0);\n if (m && globStarDepth < this.maxGlobstarRecursion) {\n const sub = this.#matchGlobStarBodySections(file, bodySegments, fileIndex + body.length, bodyIndex + 1, partial, globStarDepth + 1, sawTail);\n if (sub !== false) {\n return sub;\n }\n }\n const f = file[fileIndex];\n if (f === "." || f === ".." || !this.options.dot && f.startsWith(".")) {\n return false;\n }\n fileIndex++;\n }\n return partial || null;\n }\n #matchOne(file, pattern, partial, fileIndex, patternIndex) {\n let fi;\n let pi;\n let pl;\n let fl;\n for (fi = fileIndex, pi = patternIndex, fl = file.length, pl = pattern.length; fi < fl && pi < pl; fi++, pi++) {\n this.debug("matchOne loop");\n let p = pattern[pi];\n let f = file[fi];\n this.debug(pattern, p, f);\n if (p === false || p === GLOBSTAR) {\n return false;\n }\n let hit;\n if (typeof p === "string") {\n hit = f === p;\n this.debug("string match", p, f, hit);\n } else {\n hit = p.test(f);\n this.debug("pattern match", p, f, hit);\n }\n if (!hit)\n return false;\n }\n if (fi === fl && pi === pl) {\n return true;\n } else if (fi === fl) {\n return partial;\n } else if (pi === pl) {\n return fi === fl - 1 && file[fi] === "";\n } else {\n throw new Error("wtf?");\n }\n }\n braceExpand() {\n return braceExpand(this.pattern, this.options);\n }\n parse(pattern) {\n assertValidPattern(pattern);\n const options = this.options;\n if (pattern === "**")\n return GLOBSTAR;\n if (pattern === "")\n return "";\n let m;\n let fastTest = null;\n if (m = pattern.match(starRE)) {\n fastTest = options.dot ? starTestDot : starTest;\n } else if (m = pattern.match(starDotExtRE)) {\n fastTest = (options.nocase ? options.dot ? starDotExtTestNocaseDot : starDotExtTestNocase : options.dot ? starDotExtTestDot : starDotExtTest)(m[1]);\n } else if (m = pattern.match(qmarksRE)) {\n fastTest = (options.nocase ? options.dot ? qmarksTestNocaseDot : qmarksTestNocase : options.dot ? qmarksTestDot : qmarksTest)(m);\n } else if (m = pattern.match(starDotStarRE)) {\n fastTest = options.dot ? starDotStarTestDot : starDotStarTest;\n } else if (m = pattern.match(dotStarRE)) {\n fastTest = dotStarTest;\n }\n const re = AST.fromGlob(pattern, this.options).toMMPattern();\n if (fastTest && typeof re === "object") {\n Reflect.defineProperty(re, "test", { value: fastTest });\n }\n return re;\n }\n makeRe() {\n if (this.regexp || this.regexp === false)\n return this.regexp;\n const set = this.set;\n if (!set.length) {\n this.regexp = false;\n return this.regexp;\n }\n const options = this.options;\n const twoStar = options.noglobstar ? star2 : options.dot ? twoStarDot : twoStarNoDot;\n const flags = new Set(options.nocase ? ["i"] : []);\n let re = set.map((pattern) => {\n const pp = pattern.map((p) => {\n if (p instanceof RegExp) {\n for (const f of p.flags.split(""))\n flags.add(f);\n }\n return typeof p === "string" ? regExpEscape2(p) : p === GLOBSTAR ? GLOBSTAR : p._src;\n });\n pp.forEach((p, i) => {\n const next = pp[i + 1];\n const prev = pp[i - 1];\n if (p !== GLOBSTAR || prev === GLOBSTAR) {\n return;\n }\n if (prev === void 0) {\n if (next !== void 0 && next !== GLOBSTAR) {\n pp[i + 1] = "(?:\\\\/|" + twoStar + "\\\\/)?" + next;\n } else {\n pp[i] = twoStar;\n }\n } else if (next === void 0) {\n pp[i - 1] = prev + "(?:\\\\/|\\\\/" + twoStar + ")?";\n } else if (next !== GLOBSTAR) {\n pp[i - 1] = prev + "(?:\\\\/|\\\\/" + twoStar + "\\\\/)" + next;\n pp[i + 1] = GLOBSTAR;\n }\n });\n const filtered = pp.filter((p) => p !== GLOBSTAR);\n if (this.partial && filtered.length >= 1) {\n const prefixes = [];\n for (let i = 1; i <= filtered.length; i++) {\n prefixes.push(filtered.slice(0, i).join("/"));\n }\n return "(?:" + prefixes.join("|") + ")";\n }\n return filtered.join("/");\n }).join("|");\n const [open, close] = set.length > 1 ? ["(?:", ")"] : ["", ""];\n re = "^" + open + re + close + "$";\n if (this.partial) {\n re = "^(?:\\\\/|" + open + re.slice(1, -1) + close + ")$";\n }\n if (this.negate)\n re = "^(?!" + re + ").+$";\n try {\n this.regexp = new RegExp(re, [...flags].join(""));\n } catch {\n this.regexp = false;\n }\n return this.regexp;\n }\n slashSplit(p) {\n if (this.preserveMultipleSlashes) {\n return p.split("/");\n } else if (this.isWindows && /^\\/\\/[^/]+/.test(p)) {\n return ["", ...p.split(/\\/+/)];\n } else {\n return p.split(/\\/+/);\n }\n }\n match(f, partial = this.partial) {\n this.debug("match", f, this.pattern);\n if (this.comment) {\n return false;\n }\n if (this.empty) {\n return f === "";\n }\n if (f === "/" && partial) {\n return true;\n }\n const options = this.options;\n if (this.isWindows) {\n f = f.split("\\\\").join("/");\n }\n const ff = this.slashSplit(f);\n this.debug(this.pattern, "split", ff);\n const set = this.set;\n this.debug(this.pattern, "set", set);\n let filename = ff[ff.length - 1];\n if (!filename) {\n for (let i = ff.length - 2; !filename && i >= 0; i--) {\n filename = ff[i];\n }\n }\n for (const pattern of set) {\n let file = ff;\n if (options.matchBase && pattern.length === 1) {\n file = [filename];\n }\n const hit = this.matchOne(file, pattern, partial);\n if (hit) {\n if (options.flipNegate) {\n return true;\n }\n return !this.negate;\n }\n }\n if (options.flipNegate) {\n return false;\n }\n return this.negate;\n }\n static defaults(def) {\n return minimatch.defaults(def).Minimatch;\n }\n };\n minimatch.AST = AST;\n minimatch.Minimatch = Minimatch;\n minimatch.escape = escape;\n minimatch.unescape = unescape;\n\n // src/mods.ts\n var webcrypto;\n async function getWebCrypto() {\n if (webcrypto) {\n return webcrypto;\n }\n if (compatGlobal.crypto) {\n webcrypto = compatGlobal.crypto;\n return webcrypto;\n } else {\n const module = await import("crypto");\n webcrypto = module.webcrypto;\n return webcrypto;\n }\n }\n\n // src/common/models/db.const.ts\n var EntryTypes = {\n NOTE_LEGACY: "notes",\n NOTE_BINARY: "newnote",\n NOTE_PLAIN: "plain",\n INTERNAL_FILE: "internalfile",\n CHUNK: "leaf",\n CHUNK_PACK: "chunkpack",\n VERSION_INFO: "versioninfo",\n SYNC_INFO: "syncinfo",\n SYNC_PARAMETERS: "sync-parameters",\n MILESTONE_INFO: "milestoneinfo",\n NODE_INFO: "nodeinfo"\n };\n var NoteTypes = [EntryTypes.NOTE_LEGACY, EntryTypes.NOTE_BINARY, EntryTypes.NOTE_PLAIN];\n var ChunkTypes = [EntryTypes.CHUNK, EntryTypes.CHUNK_PACK];\n\n // src/common/models/setting.const.ts\n var SETTING_VERSION_SUPPORT_CASE_INSENSITIVE = 10;\n var CURRENT_SETTING_VERSION = SETTING_VERSION_SUPPORT_CASE_INSENSITIVE;\n var RemoteTypes = {\n REMOTE_COUCHDB: "",\n REMOTE_MINIO: "MINIO",\n REMOTE_P2P: "ONLY_P2P"\n };\n var REMOTE_COUCHDB = RemoteTypes.REMOTE_COUCHDB;\n var REMOTE_MINIO = RemoteTypes.REMOTE_MINIO;\n var REMOTE_P2P = RemoteTypes.REMOTE_P2P;\n var E2EEAlgorithms = {\n V1: "",\n V2: "v2",\n ForceV1: "forceV1"\n };\n var ChunkAlgorithms = {\n V1: "v1",\n V2: "v2",\n V2Segmenter: "v2-segmenter",\n RabinKarp: "v3-rabin-karp"\n };\n\n // src/common/models/setting.const.preferred.ts\n var PREFERRED_BASE = {\n syncMaxSizeInMB: 50,\n chunkSplitterVersion: "v3-rabin-karp",\n usePluginSyncV2: true,\n handleFilenameCaseSensitive: false,\n E2EEAlgorithm: E2EEAlgorithms.V2\n };\n var PREFERRED_SETTING_CLOUDANT = {\n ...PREFERRED_BASE,\n customChunkSize: 0,\n sendChunksBulkMaxSize: 1,\n concurrencyOfReadChunksOnline: 100,\n minimumIntervalOfReadChunksOnline: 333\n };\n var PREFERRED_SETTING_SELF_HOSTED = {\n ...PREFERRED_BASE,\n customChunkSize: 60,\n sendChunksBulkMaxSize: 1,\n concurrencyOfReadChunksOnline: 30,\n minimumIntervalOfReadChunksOnline: 25\n };\n var PREFERRED_JOURNAL_SYNC = {\n ...PREFERRED_BASE,\n customChunkSize: 10,\n concurrencyOfReadChunksOnline: 30,\n minimumIntervalOfReadChunksOnline: 25\n };\n\n // src/common/models/setting.const.defaults.ts\n var P2P_DEFAULT_SETTINGS = {\n P2P_Enabled: false,\n P2P_AutoAccepting: 0 /* NONE */,\n P2P_AppID: "self-hosted-livesync",\n P2P_roomID: "",\n P2P_passphrase: "",\n P2P_relays: "wss://exp-relay.vrtmrz.net/",\n P2P_AutoBroadcast: false,\n P2P_AutoStart: false,\n P2P_AutoSyncPeers: "",\n P2P_AutoWatchPeers: "",\n P2P_SyncOnReplication: "",\n P2P_RebuildFrom: "",\n P2P_AutoAcceptingPeers: "",\n P2P_AutoDenyingPeers: "",\n P2P_IsHeadless: false,\n P2P_DevicePeerName: "",\n P2P_turnServers: "",\n P2P_turnUsername: "",\n P2P_turnCredential: "",\n P2P_useDiagRTC: false\n };\n var SETTINGS_SCHEMA_DEFAULTS = {\n remoteType: REMOTE_COUCHDB,\n useCustomRequestHandler: false,\n couchDB_URI: "",\n couchDB_USER: "",\n couchDB_PASSWORD: "",\n couchDB_DBNAME: "",\n liveSync: false,\n syncOnSave: false,\n syncOnStart: false,\n savingDelay: 200,\n lessInformationInLog: false,\n gcDelay: 300,\n versionUpFlash: "",\n minimumChunkSize: 20,\n longLineThreshold: 250,\n showVerboseLog: false,\n suspendFileWatching: false,\n trashInsteadDelete: true,\n periodicReplication: false,\n periodicReplicationInterval: 60,\n syncOnFileOpen: false,\n encrypt: false,\n passphrase: "",\n usePathObfuscation: false,\n doNotDeleteFolder: false,\n resolveConflictsByNewerFile: false,\n batchSave: false,\n batchSaveMinimumDelay: 5,\n batchSaveMaximumDelay: 60,\n deviceAndVaultName: "",\n usePluginSettings: false,\n showOwnPlugins: false,\n showStatusOnEditor: true,\n showStatusOnStatusbar: true,\n showOnlyIconsOnEditor: false,\n hideFileWarningNotice: false,\n networkWarningStyle: "",\n usePluginSync: false,\n autoSweepPlugins: false,\n autoSweepPluginsPeriodic: false,\n notifyPluginOrSettingUpdated: false,\n checkIntegrityOnSave: false,\n batch_size: 25,\n batches_limit: 25,\n useHistory: false,\n disableRequestURI: false,\n skipOlderFilesOnSync: true,\n checkConflictOnlyOnOpen: false,\n showMergeDialogOnlyOnActive: false,\n syncInternalFiles: false,\n syncInternalFilesBeforeReplication: false,\n syncInternalFilesIgnorePatterns: "\\\\/node_modules\\\\/, \\\\/\\\\.git\\\\/, \\\\/obsidian-livesync\\\\/",\n syncInternalFilesTargetPatterns: "",\n syncInternalFilesInterval: 60,\n additionalSuffixOfDatabaseName: "",\n ignoreVersionCheck: false,\n lastReadUpdates: 0,\n deleteMetadataOfDeletedFiles: false,\n syncIgnoreRegEx: "",\n syncOnlyRegEx: "",\n customChunkSize: 0,\n readChunksOnline: true,\n watchInternalFileChanges: true,\n automaticallyDeleteMetadataOfDeletedFiles: 0,\n disableMarkdownAutoMerge: false,\n writeDocumentsIfConflicted: false,\n useDynamicIterationCount: false,\n syncAfterMerge: false,\n configPassphraseStore: "",\n encryptedPassphrase: "",\n encryptedCouchDBConnection: "",\n permitEmptyPassphrase: false,\n remoteConfigurations: {},\n activeConfigurationId: "",\n P2P_ActiveRemoteConfigurationId: "",\n useIndexedDBAdapter: false,\n useTimeouts: false,\n writeLogToTheFile: false,\n doNotPaceReplication: false,\n hashCacheMaxCount: 300,\n hashCacheMaxAmount: 50,\n concurrencyOfReadChunksOnline: 40,\n minimumIntervalOfReadChunksOnline: 50,\n hashAlg: "xxhash64",\n suspendParseReplicationResult: false,\n doNotSuspendOnFetching: false,\n useIgnoreFiles: false,\n ignoreFiles: ".gitignore",\n syncOnEditorSave: false,\n keepReplicationActiveInBackground: false,\n pluginSyncExtendedSetting: {},\n syncMaxSizeInMB: 50,\n settingSyncFile: "",\n writeCredentialsForSettingSync: false,\n notifyAllSettingSyncFile: false,\n isConfigured: void 0,\n settingVersion: CURRENT_SETTING_VERSION,\n enableCompression: false,\n accessKey: "",\n bucket: "",\n endpoint: "",\n region: "auto",\n secretKey: "",\n useEden: false,\n maxChunksInEden: 10,\n maxTotalLengthInEden: 1024,\n maxAgeInEden: 10,\n disableCheckingConfigMismatch: false,\n autoAcceptCompatibleTweak: void 0,\n displayLanguage: "",\n /**\n * @deprecated\n */\n enableChunkSplitterV2: false,\n disableWorkerForGeneratingChunks: false,\n processSmallFilesInUIThread: false,\n notifyThresholdOfRemoteStorageSize: -1,\n usePluginSyncV2: false,\n usePluginEtc: false,\n handleFilenameCaseSensitive: void 0,\n doNotUseFixedRevisionForChunks: true,\n showLongerLogInsideEditor: false,\n /** @deprecated Retained for settings and Setup URI compatibility. */\n sendChunksBulk: false,\n sendChunksBulkMaxSize: 1,\n /**\n * @deprecated\n * This setting is no longer used and will be removed in the future.\n */\n useSegmenter: false,\n useAdvancedMode: false,\n usePowerUserMode: false,\n useEdgeCaseMode: false,\n enableDebugTools: false,\n suppressNotifyHiddenFilesChange: false,\n syncMinimumInterval: 2e3,\n ...P2P_DEFAULT_SETTINGS,\n doctorProcessedVersion: "",\n bucketCustomHeaders: "",\n couchDB_CustomHeaders: "",\n useJWT: false,\n jwtAlgorithm: "",\n jwtKey: "",\n jwtKid: "",\n jwtSub: "",\n jwtExpDuration: 5,\n useRequestAPI: false,\n bucketPrefix: "",\n chunkSplitterVersion: ChunkAlgorithms.RabinKarp,\n E2EEAlgorithm: E2EEAlgorithms.V2,\n processSizeMismatchedFiles: false,\n forcePathStyle: true,\n syncInternalFileOverwritePatterns: "",\n useOnlyLocalChunk: false,\n maxMTimeForReflectEvents: 0,\n tweakModified: void 0\n };\n var NEW_VAULT_SETTINGS = {\n ...SETTINGS_SCHEMA_DEFAULTS,\n ...PREFERRED_BASE,\n remoteConfigurations: {},\n pluginSyncExtendedSetting: {}\n };\n var DEFAULT_SETTINGS = SETTINGS_SCHEMA_DEFAULTS;\n\n // src/common/models/sync.definition.ts\n var ProtocolVersions = {\n UNSET: void 0,\n LEGACY: 1,\n ADVANCED_E2EE: 2\n };\n var DOCID_SYNC_PARAMETERS = "_local/obsidian_livesync_sync_parameters";\n var DEFAULT_SYNC_PARAMETERS = {\n _id: DOCID_SYNC_PARAMETERS,\n type: EntryTypes["SYNC_PARAMETERS"],\n protocolVersion: ProtocolVersions.ADVANCED_E2EE,\n pbkdf2salt: ""\n };\n\n // src/common/models/tweak.definition.ts\n var TweakValuesShouldMatchedTemplate = {\n minimumChunkSize: 20,\n longLineThreshold: 250,\n encrypt: false,\n usePathObfuscation: false,\n enableCompression: false,\n useEden: false,\n customChunkSize: 0,\n useDynamicIterationCount: false,\n hashAlg: "xxhash64",\n enableChunkSplitterV2: false,\n maxChunksInEden: 10,\n maxTotalLengthInEden: 1024,\n maxAgeInEden: 10,\n usePluginSyncV2: false,\n handleFilenameCaseSensitive: false,\n useSegmenter: false,\n E2EEAlgorithm: E2EEAlgorithms.V2,\n chunkSplitterVersion: ChunkAlgorithms.RabinKarp\n };\n var TweakValuesRecommendedTemplate = {\n useIgnoreFiles: false,\n useCustomRequestHandler: false,\n batch_size: 25,\n batches_limit: 25,\n // useIndexedDBAdapter: false,\n useTimeouts: false,\n readChunksOnline: true,\n hashCacheMaxCount: 300,\n hashCacheMaxAmount: 50,\n concurrencyOfReadChunksOnline: 40,\n minimumIntervalOfReadChunksOnline: 50,\n ignoreFiles: ".gitignore",\n syncMaxSizeInMB: 50,\n enableChunkSplitterV2: false,\n usePluginSyncV2: true,\n handleFilenameCaseSensitive: false,\n E2EEAlgorithm: E2EEAlgorithms.V2,\n chunkSplitterVersion: ChunkAlgorithms.RabinKarp\n };\n var TweakValuesDefault = {\n usePluginSyncV2: false,\n E2EEAlgorithm: DEFAULT_SETTINGS.E2EEAlgorithm,\n chunkSplitterVersion: DEFAULT_SETTINGS.chunkSplitterVersion,\n tweakModified: DEFAULT_SETTINGS.tweakModified\n };\n var TweakValuesTemplate = {\n ...TweakValuesRecommendedTemplate,\n ...TweakValuesShouldMatchedTemplate,\n tweakModified: 0\n };\n\n // src/common/models/redflag.const.ts\n var FlagFilesOriginal = {\n SUSPEND_ALL: "redflag.md",\n REBUILD_ALL: "redflag2.md",\n FETCH_ALL: "redflag3.md"\n };\n var FlagFilesHumanReadable = {\n REBUILD_ALL: "flag_rebuild.md",\n FETCH_ALL: "flag_fetch.md"\n };\n var FLAGMD_REDFLAG = FlagFilesOriginal.SUSPEND_ALL;\n var FLAGMD_REDFLAG2 = FlagFilesOriginal.REBUILD_ALL;\n var FLAGMD_REDFLAG2_HR = FlagFilesHumanReadable.REBUILD_ALL;\n var FLAGMD_REDFLAG3 = FlagFilesOriginal.FETCH_ALL;\n var FLAGMD_REDFLAG3_HR = FlagFilesHumanReadable.FETCH_ALL;\n\n // src/common/models/shared.definition.ts\n var DatabaseConnectingStatuses = {\n STARTED: "STARTED",\n NOT_CONNECTED: "NOT_CONNECTED",\n PAUSED: "PAUSED",\n CONNECTED: "CONNECTED",\n COMPLETED: "COMPLETED",\n CLOSED: "CLOSED",\n ERRORED: "ERRORED",\n JOURNAL_SEND: "JOURNAL_SEND",\n JOURNAL_RECEIVE: "JOURNAL_RECEIVE"\n };\n var DEFAULT_REPLICATION_STATICS = {\n sent: 0,\n arrived: 0,\n maxPullSeq: 0,\n maxPushSeq: 0,\n lastSyncPullSeq: 0,\n lastSyncPushSeq: 0,\n syncStatus: DatabaseConnectingStatuses.CLOSED\n };\n\n // src/string_and_binary/path.ts\n var _hashString = memorizeFuncWithLRUCache(async (key) => {\n const buff = writeString(key);\n const webcrypto7 = await getWebCrypto();\n let digest = await webcrypto7.subtle.digest("SHA-256", buff);\n const len = key.length;\n for (let i = 0; i < len; i++) {\n digest = await webcrypto7.subtle.digest("SHA-256", buff);\n }\n return uint8ArrayToHexString(new Uint8Array(digest));\n });\n\n // node_modules/octagonal-wheels/dist/promises.js\n function polyfillPromiseWithResolvers() {\n let resolve;\n let reject;\n const promise = new Promise((res, rej) => {\n resolve = res;\n reject = rej;\n });\n return { promise, resolve, reject };\n }\n function nativePromiseWithResolvers() {\n const p = Promise.withResolvers();\n const { promise, resolve, reject } = p;\n return { promise, resolve, reject };\n }\n var polyfilledFunc = "withResolvers" in Promise ? nativePromiseWithResolvers : polyfillPromiseWithResolvers;\n var promiseWithResolvers = polyfilledFunc;\n var noop = () => {\n };\n function fireAndForget(p) {\n if (typeof p == "function")\n return fireAndForget(p());\n p.then(noop).catch(noop);\n }\n function yieldMicrotask() {\n return new Promise((res) => queueMicrotask(res));\n }\n var TIMED_OUT_SIGNAL = /* @__PURE__ */ Symbol("timed out");\n function cancelableDelay(timeout, cancel = TIMED_OUT_SIGNAL) {\n let timer = void 0;\n const promise = promiseWithResolvers();\n timer = setTimeout(() => {\n timer = void 0;\n promise.resolve(cancel);\n }, timeout);\n return {\n promise: promise.promise,\n cancel() {\n if (timer) {\n clearTimeout(timer);\n timer = void 0;\n }\n }\n };\n }\n\n // node_modules/octagonal-wheels/dist/concurrency/semaphore_v2.js\n function Semaphore(limit) {\n let counter = 0;\n const _limit = limit;\n const queue = [];\n const semaphore = {\n get waiting() {\n return queue.length;\n },\n async tryAcquire(quantity = 1, timeout) {\n if (counter < _limit) {\n counter += quantity;\n return () => {\n this.release(quantity);\n };\n }\n const d = cancelableDelay(timeout, TIMED_OUT_SIGNAL);\n const aq = this.acquire(quantity);\n const p = await Promise.race([d.promise, aq]);\n if (p === TIMED_OUT_SIGNAL) {\n fireAndForget(() => aq.then((release) => release()));\n return false;\n }\n return p;\n },\n async acquire(quantity = 1) {\n if (counter < _limit) {\n counter += quantity;\n return () => this.release();\n }\n const n = promiseWithResolvers();\n queue.push(n);\n await n.promise;\n return () => {\n this.release(quantity);\n };\n },\n release(quantity = 1) {\n if (queue.length > 0) {\n const next = queue.shift();\n if (next) {\n fireAndForget(async () => await yieldMicrotask().then(() => next.resolve()));\n }\n } else {\n if (counter > 0) {\n counter -= quantity;\n }\n }\n }\n };\n return semaphore;\n }\n\n // node_modules/octagonal-wheels/dist/encoding/encodeobject.js\n var prefixMapObject = {\n s: {\n 1: "V",\n 2: "W",\n 3: "X",\n 4: "Y",\n 5: "Z"\n },\n o: {\n 1: "v",\n 2: "w",\n 3: "x",\n 4: "y",\n 5: "z"\n }\n };\n var decodePrefixMapObject = Object.fromEntries(Object.entries(prefixMapObject).flatMap(([prefix, map]) => Object.entries(map).map(([len, char]) => [char, { prefix, len: parseInt(len) }])));\n var prefixMapNumber = {\n n: {\n 1: "a",\n 2: "b",\n 3: "c",\n 4: "d",\n 5: "e"\n },\n N: {\n 1: "A",\n 2: "B",\n 3: "C",\n 4: "D",\n 5: "E"\n }\n };\n var decodePrefixMapNumber = Object.fromEntries(Object.entries(prefixMapNumber).flatMap(([prefix, map]) => Object.entries(map).map(([len, char]) => [char, { prefix, len: parseInt(len) }])));\n\n // node_modules/octagonal-wheels/dist/bureau/SlipBoard.js\n var SlipBoard = class {\n constructor() {\n Object.defineProperty(this, "_clip", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: /* @__PURE__ */ new Map()\n });\n }\n /**\n * Checks if a specific key is awaiting.\n *\n * @template ET - The type of the events.\n * @template K - The key of the event in the events type.\n * @param {SlipType<ET, K>} type - The key representing the event type.\n * @param {string} key - The key representing the specific sub-event.\n * @returns {boolean} - Returns `true` if the event and sub-event combination is awaiting, otherwise `false`.\n */\n isAwaiting(type, key) {\n return this._clip.has(`${String(type)}:${key}`);\n }\n /**\n * Issues a slip of process and proceeds with the provided options.\n *\n * @template T - The type of the result expected from the process.\n * @param {string} type - The type of the process to be issued.\n * @param {string} [key=""] - An optional key to identify the process.\n * @param {SlipProcessOptions<T>} opt - The options for the process, including the callback to be executed.\n * @returns {Promise<T>} - A promise that resolves with the result of the process.\n *\n * @remarks\n * - If the process is not already awaiting, it will be issued and the callback will be executed.\n * - If the callback succeeds, the result will be submitted.\n * - If the callback fails, the error handling depends on the options provided:\n * - If `submitAsSuccess` is true, the error (or transformed error) will be submitted as a success.\n * - If `dropSlipWithRisks` is true, the process will be deleted from the clip.\n * - Otherwise, the error will be rejected.\n * - The method returns a promise that resolves with the next result of the process.\n */\n issueAndProceed(type, key = "", opt) {\n if (!this.isAwaiting(type, key)) {\n fireAndForget(async () => {\n try {\n const ret = await opt.callback();\n this.submit(type, key, ret);\n } catch (ex) {\n if (opt.submitAsSuccess) {\n this.submit(type, key, opt.transformError ? opt.transformError(ex) : ex);\n } else {\n if (opt.dropSlipWithRisks) {\n this._clip.delete(type);\n } else {\n this.reject(type, key, ex);\n }\n }\n }\n });\n }\n return this.awaitNext(type, key);\n }\n /**\n * Waits for the next event of the specified type and key, with an optional timeout.\n *\n * @template ET - The type of the events.\n * @template K - The key of the event type.\n * @param {SlipType<ET, K>} type - The type of the event to wait for.\n * @param {string} [key=""] - The key associated with the event.\n * @param {number} [timeout] - The optional timeout in milliseconds.\n * @returns {Promise<void | ET[K] | TIMED_OUT_SIGNAL>} A promise that resolves with the event data,\n * resolves with `TIMED_OUT_SIGNAL` if the timeout is reached, or resolves to void if no event is found.\n */\n async awaitNext(type, key = "", { timeout, onNotAwaited } = { timeout: void 0, onNotAwaited: void 0 }) {\n let taskPromise = this._clip.get(`${String(type)}:${key}`);\n if (!taskPromise) {\n taskPromise = promiseWithResolvers();\n taskPromise.promise = taskPromise.promise.then((ret) => {\n return ret;\n }).finally(() => {\n this._clip.delete(`${String(type)}:${key}`);\n });\n this._clip.set(`${String(type)}:${key}`, taskPromise);\n if (onNotAwaited) {\n fireAndForget(async () => (await yieldMicrotask(), onNotAwaited()));\n }\n }\n if (timeout) {\n const cDelay = cancelableDelay(timeout);\n return Promise.race([\n cDelay.promise,\n taskPromise.promise.then((ret) => ret).finally(() => cDelay.cancel())\n ]);\n }\n return await taskPromise.promise;\n }\n /**\n * Submits an event of a specified type with optional data.\n *\n * @template ET - The type of events.\n * @template K - The key of the event type in ET.\n * @param {SlipType<ET, K>} type - The type of the event to submit.\n * @param {string} [key=""] - An optional key associated with the event.\n * @param {SlipDataType<ET, K>} [data] - Optional data to be passed with the event.\n * @returns {void}\n */\n submit(type, key, data) {\n const taskPromise = this._clip.get(`${String(type)}:${key}`);\n if (taskPromise) {\n taskPromise.resolve(data);\n }\n }\n /**\n * Submits an event of a specified type to all listeners.\n *\n * @template ET - The type of events.\n * @template K - The key of the event type in ET.\n * @param {SlipType<ET, K>} type - The type of the event to submit.\n * @param {string} prefix - The prefix to match the keys of the listeners.\n * @param {SlipDataType<ET, K>} [data] - Optional data to be passed with the event.\n * @returns {void}\n */\n submitToAll(type, prefix, data) {\n for (const [key, taskPromise] of this._clip.entries()) {\n if (`${String(key)}`.startsWith(`${String(type)}:${prefix}`)) {\n taskPromise.resolve(data);\n }\n }\n }\n /**\n * Rejects a task promise associated with a specific event type and key.\n *\n * @template ET - The type of events.\n * @template K - The keys of the events.\n * @param {SlipType<ET, K>} type - The type of the event.\n * @param {string} [key=""] - The key associated with the event. Defaults to an empty string.\n * @param {any} reason - The reason for rejecting the promise.\n */\n reject(type, key = "", reason) {\n const taskPromise = this._clip.get(`${String(type)}:${key}`);\n if (taskPromise) {\n taskPromise.reject(reason);\n }\n }\n };\n var globalSlipBoard = new SlipBoard();\n\n // src/common/utils.patch.ts\n var MARK_OPERATOR = ``;\n var MARK_DELETED = `${MARK_OPERATOR}__DELETED`;\n var MARK_ISARRAY = `${MARK_OPERATOR}__ARRAY`;\n var MARK_SWAPPED = `${MARK_OPERATOR}__SWAP`;\n\n // src/common/utils.ts\n var isIndexDBCmpExist = typeof compatGlobal?.indexedDB?.cmp !== "undefined";\n function memorizeFuncWithLRUCache(func) {\n const cache = new LRUCache(100, 1e5, true);\n return (key) => {\n const isExists = cache.has(key);\n if (isExists) return cache.get(key);\n const value = func(key);\n cache.set(key, value);\n return value;\n };\n }\n var globalConcurrencyController = Semaphore(50);\n function wrapByDefault(func, onError) {\n try {\n return func();\n } catch (ex) {\n const error = ex instanceof Error ? ex : new Error(String(ex));\n return onError(error);\n }\n }\n\n // src/string_and_binary/chunks.ts\n function isTextBlob(blob) {\n return blob.type === "text/plain";\n }\n function* pickPiece(leftData, minimumChunkSize) {\n let buffer = "";\n L1: do {\n const curLine = leftData.shift();\n if (typeof curLine === "undefined") {\n yield buffer;\n break L1;\n }\n if (curLine.startsWith("```") || curLine.startsWith(" ```") || curLine.startsWith(" ```") || curLine.startsWith(" ```")) {\n yield buffer;\n buffer = curLine + (leftData.length != 0 ? "\\n" : "");\n L2: do {\n const curPx = leftData.shift();\n if (typeof curPx === "undefined") {\n break L2;\n }\n buffer += curPx + (leftData.length != 0 ? "\\n" : "");\n } while (leftData.length > 0 && !(leftData[0].startsWith("```") || leftData[0].startsWith(" ```") || leftData[0].startsWith(" ```") || leftData[0].startsWith(" ```")));\n const isLooksLikeBASE64 = buffer.endsWith("=");\n const maybeUneditable = buffer.length > 2048;\n const endOfCodeBlock = leftData.shift();\n if (typeof endOfCodeBlock !== "undefined") {\n buffer += endOfCodeBlock;\n buffer += leftData.length != 0 ? "\\n" : "";\n }\n if (!isLooksLikeBASE64 && !maybeUneditable) {\n const splitExpr = /(.*?[;,:<])/g;\n const sx = buffer.split(splitExpr).filter((e) => e != "");\n for (const v of sx) {\n yield v;\n }\n } else {\n yield buffer;\n }\n buffer = "";\n } else {\n buffer += curLine + (leftData.length != 0 ? "\\n" : "");\n if (buffer.length >= minimumChunkSize || leftData.length == 0 || leftData[0] == "#" || buffer[0] == "#") {\n yield buffer;\n buffer = "";\n }\n }\n } while (leftData.length > 0);\n }\n var charNewLine = "\\n".charCodeAt(0);\n var segmenter = "Segmenter" in Intl ? wrapByDefault(\n // @ts-ignore We have checked Intl existence above.\n // eslint-disable-next-line @typescript-eslint/no-unsafe-call, @typescript-eslint/no-unsafe-return\n () => new Intl.Segmenter(compatGlobal.navigator.language, { granularity: "sentence" }),\n (err) => {\n Logger(`Failed to create Intl.Segmenter: ${err.message}`, LOG_LEVEL_VERBOSE);\n return void 0;\n }\n ) : void 0;\n function* splitStringWithinLength(text, pieceSize) {\n let leftData = text;\n do {\n const splitSize = pieceSize;\n const piece = leftData.substring(0, splitSize);\n leftData = leftData.substring(splitSize);\n yield piece;\n } while (leftData != "");\n }\n function* splitTextInSegment(text, pieceSize, minimumChunkSize) {\n const segments = segmenter.segment(text);\n let prev = "";\n let buf = "";\n for (const seg of segments) {\n const buffer = seg.segment;\n if (prev == buffer || buf.length < minimumChunkSize) {\n buf += buffer;\n prev = buffer;\n } else {\n prev = buffer;\n if (buf.length > 0) {\n yield* splitStringWithinLength(buf, pieceSize);\n }\n buf = buffer;\n }\n }\n if (buf.length > 0) {\n yield* splitStringWithinLength(buf, pieceSize);\n }\n }\n function* splitInNewLine(texts) {\n for (const text of texts) {\n let start = -1;\n let end = -1;\n do {\n end = text.indexOf("\\n", start);\n if (end == -1) {\n yield text.substring(start);\n break;\n }\n while (text[end] == "\\n") {\n end++;\n }\n yield text.substring(start, end);\n start = end;\n } while (end != -1);\n }\n return;\n }\n function splitPiecesTextV2(dataSrc, pieceSize, minimumChunkSize) {\n const dataListAllArray = typeof dataSrc == "string" ? [dataSrc] : dataSrc;\n const dataListAll = splitInNewLine(dataListAllArray);\n let inCodeBlock = 0;\n let flush = false;\n let flushBefore = false;\n return function* () {\n const buf = [];\n for (const line of dataListAll) {\n if (line.startsWith("````")) {\n if (inCodeBlock == 0) {\n inCodeBlock = 4;\n flushBefore = true;\n } else if (inCodeBlock == 4) {\n inCodeBlock = 0;\n flush = true;\n }\n } else if (line.startsWith("```")) {\n if (inCodeBlock == 0) {\n inCodeBlock = 3;\n flushBefore = true;\n } else if (inCodeBlock == 3) {\n inCodeBlock = 0;\n flush = true;\n }\n }\n if (flushBefore) {\n if (buf.length > 0) {\n yield* splitTextInSegment(buf.join(""), pieceSize, minimumChunkSize);\n buf.length = 0;\n }\n flushBefore = false;\n }\n buf.push(line);\n if (flush) {\n if (buf.length > 0) {\n yield* splitStringWithinLength(buf.join(""), pieceSize);\n buf.length = 0;\n }\n flush = false;\n }\n }\n if (buf.length > 0) {\n if (inCodeBlock == 0) {\n yield* splitTextInSegment(buf.join(""), pieceSize, minimumChunkSize);\n } else {\n yield* splitStringWithinLength(buf.join(""), pieceSize);\n }\n }\n };\n }\n function binaryTextSplit(data, pieceSize, minimumChunkSize) {\n return function* pieces() {\n yield* splitStringWithinLength(data, pieceSize);\n };\n }\n function splitPiecesText(dataSrc, pieceSize, plainSplit, minimumChunkSize, useSegmenter) {\n if (!useSegmenter || !segmenter) {\n return splitPiecesTextV1(dataSrc, pieceSize, plainSplit, minimumChunkSize);\n }\n if (!plainSplit) {\n return binaryTextSplit(dataSrc, pieceSize, minimumChunkSize);\n }\n return splitPiecesTextV2(dataSrc, pieceSize, minimumChunkSize);\n }\n function splitPiecesTextV1(dataSrc, pieceSize, plainSplit, minimumChunkSize) {\n const dataList = typeof dataSrc == "string" ? [dataSrc] : dataSrc;\n return function* pieces() {\n for (const data of dataList) {\n if (plainSplit) {\n const leftData = data.split("\\n");\n const f = pickPiece(leftData, minimumChunkSize);\n for (const piece of f) {\n let buffer = piece;\n do {\n let ps = pieceSize;\n if (buffer.charCodeAt(ps - 1) != buffer.codePointAt(ps - 1)) {\n ps++;\n }\n yield buffer.substring(0, ps);\n buffer = buffer.substring(ps);\n } while (buffer != "");\n }\n } else {\n let leftData = data;\n do {\n const splitSize = pieceSize;\n const piece = leftData.substring(0, splitSize);\n leftData = leftData.substring(splitSize);\n yield piece;\n } while (leftData != "");\n }\n }\n };\n }\n function* splitByDelimiterWithMinLength(sources, delimiter, minimumChunkLength = 25, splitThreshold) {\n let buf = "";\n let last = false;\n const dl = delimiter.length;\n for (const source of sources) {\n const max = source.length;\n if (splitThreshold && max > splitThreshold) {\n yield buf + source;\n last = false;\n buf = "";\n continue;\n }\n let i = -1;\n let prev = 0;\n L1: do {\n i = source.indexOf(delimiter, prev);\n if (i == -1) break L1;\n buf += source.slice(prev, i) + delimiter;\n if (buf.length > minimumChunkLength) {\n yield buf;\n buf = "";\n last = false;\n } else {\n last = true;\n }\n prev = i + dl;\n } while (i < max);\n if (prev != i || prev == -1 && i == -1) {\n buf += source.slice(prev);\n last = true;\n }\n }\n if (last) {\n yield buf;\n }\n }\n function* chunkStringGenerator(source, maxLength) {\n const strLen = source.length;\n if (strLen > maxLength) {\n let from = 0;\n do {\n let end = from + maxLength;\n if (end > strLen) {\n yield source.substring(from);\n break;\n }\n while (source.charCodeAt(end - 1) != source.codePointAt(end - 1)) {\n end++;\n }\n yield source.substring(from, end);\n from = end;\n } while (from < strLen);\n } else {\n yield source;\n }\n }\n function* chunkStringGeneratorFromGenerator(sources, maxLength) {\n for (const source of sources) {\n yield* chunkStringGenerator(source, maxLength);\n }\n }\n function* stringGenerator(sources) {\n for (const str of sources) {\n yield str;\n }\n }\n var MAX_ITEMS = 100;\n async function splitPieces2V2(dataSrc, pieceSize, plainSplit, minimumChunkSize, filename, useSegmenter) {\n if (dataSrc.size == 0) {\n return function* noItems() {\n return;\n };\n }\n if (isTextBlob(dataSrc)) {\n const text = await dataSrc.text();\n if (!plainSplit) {\n const gen2 = chunkStringGenerator(text, pieceSize);\n return function* pieces() {\n yield* gen2;\n };\n }\n const textLen = text.length;\n let xMinimumChunkSize = minimumChunkSize;\n while (textLen / xMinimumChunkSize > MAX_ITEMS) {\n xMinimumChunkSize += minimumChunkSize;\n }\n const org = stringGenerator([text]);\n const gen1 = splitByDelimiterWithMinLength(org, "\\n", xMinimumChunkSize);\n const gen = chunkStringGeneratorFromGenerator(gen1, pieceSize);\n return function* pieces() {\n yield* gen;\n };\n }\n let canBeSmall = false;\n let delimiter = 0;\n if (filename && filename.endsWith(".pdf")) {\n delimiter = "/".charCodeAt(0);\n } else if (filename && filename.endsWith(".json")) {\n canBeSmall = true;\n delimiter = ",".charCodeAt(0);\n }\n const clampMin = canBeSmall ? 100 : 1e5;\n const clampMax = 1e8;\n const clampedSize = Math.max(clampMin, Math.min(clampMax, dataSrc.size));\n let step = 1;\n let w = clampedSize;\n while (w > 10) {\n w /= 12.5;\n step++;\n }\n minimumChunkSize = Math.floor(10 ** (step - 1));\n return async function* piecesBlob() {\n const size = dataSrc.size;\n let i = 0;\n const buf = new Uint8Array(await dataSrc.arrayBuffer());\n do {\n const findStart = i + minimumChunkSize;\n const defaultSplitEnd = i + pieceSize;\n let splitEnd;\n let i1 = buf.indexOf(delimiter, findStart);\n if (i1 == -1) {\n i1 = buf.indexOf(charNewLine, findStart);\n }\n if (i1 == -1) {\n splitEnd = defaultSplitEnd;\n } else {\n splitEnd = i1 < defaultSplitEnd ? i1 : defaultSplitEnd;\n }\n yield await arrayBufferToBase64Single2(buf.slice(i, splitEnd));\n i = splitEnd;\n } while (i < size);\n };\n }\n async function splitPieces2(dataSrc, pieceSize, plainSplit, minimumChunkSize, filename, useSegmenter) {\n if (isTextBlob(dataSrc)) {\n return splitPiecesText(await dataSrc.text(), pieceSize, plainSplit, minimumChunkSize, useSegmenter ?? false);\n }\n let delimiter = 0;\n let canBeSmall = false;\n if (filename && filename.endsWith(".pdf")) {\n delimiter = "/".charCodeAt(0);\n } else if (filename && filename.endsWith(".json")) {\n canBeSmall = true;\n delimiter = ",".charCodeAt(0);\n }\n const clampMin = canBeSmall ? 100 : 1e5;\n const clampMax = 1e8;\n const clampedSize = Math.max(clampMin, Math.min(clampMax, dataSrc.size));\n let step = 1;\n let w = clampedSize;\n while (w > 10) {\n w /= 12.5;\n step++;\n }\n minimumChunkSize = Math.floor(10 ** (step - 1));\n return async function* piecesBlob() {\n const size = dataSrc.size;\n let i = 0;\n do {\n let splitSize = pieceSize;\n const currentData = new Uint8Array(await dataSrc.slice(i, i + pieceSize).arrayBuffer());\n let nextIdx = currentData.indexOf(delimiter, minimumChunkSize);\n splitSize = nextIdx == -1 ? pieceSize : Math.min(pieceSize, nextIdx);\n if (nextIdx == -1) nextIdx = currentData.indexOf(charNewLine, minimumChunkSize);\n const piece = currentData.slice(0, splitSize);\n i += piece.length;\n const b64 = await arrayBufferToBase64Single2(piece);\n yield b64;\n } while (i < size);\n };\n }\n async function splitPiecesRabinKarp(dataSrc, absoluteMaxPieceSize, doPlainSplit, minimumChunkSize, _filename, _useSegmenter) {\n let plainSplit = doPlainSplit || isTextBlob(dataSrc);\n const dataSize = dataSrc.size;\n let chunkUnitPlain = 64;\n const MAX_CHUNK_COUNT = 500;\n if (plainSplit) {\n const isDataSizeTooLargeForPlainSplit = dataSize >= 4 * 1024 * 1024;\n if (isDataSizeTooLargeForPlainSplit) {\n plainSplit = false;\n } else {\n let estimatedChunkCount;\n do {\n estimatedChunkCount = dataSize / (chunkUnitPlain * 4);\n if (estimatedChunkCount > MAX_CHUNK_COUNT) {\n chunkUnitPlain += 32;\n }\n } while (estimatedChunkCount > MAX_CHUNK_COUNT);\n }\n }\n const chunkUnitBinary = 256 * 1024;\n const fixedAvgChunkSize = plainSplit ? chunkUnitPlain * 4 : chunkUnitBinary * 4;\n const fixedMaxChunkSize = plainSplit ? chunkUnitPlain * 16 : chunkUnitBinary * 16;\n const fixedMinChunkSize = plainSplit ? chunkUnitPlain * 2 : chunkUnitBinary;\n const rkAbsoluteMaxPieceSizeFloor = 30 * 1024;\n const effectiveAbsoluteMaxPieceSize = Math.max(absoluteMaxPieceSize, rkAbsoluteMaxPieceSizeFloor);\n const maxChunkSize = Math.min(fixedMaxChunkSize, effectiveAbsoluteMaxPieceSize);\n const minChunkSize = Math.min(Math.max(fixedMinChunkSize, minimumChunkSize), maxChunkSize);\n const avgChunkSize = Math.min(Math.max(fixedAvgChunkSize, minChunkSize), maxChunkSize);\n const windowSize = 48;\n const hashModulus = avgChunkSize;\n const boundaryPattern = 1;\n const PRIME = 31;\n let P_pow_w = 1;\n for (let i = 0; i < windowSize - 1; i++) {\n P_pow_w = Math.imul(P_pow_w, PRIME);\n }\n const buffer = new Uint8Array(await dataSrc.arrayBuffer());\n let pos = 0;\n let hash = 0;\n let start = 0;\n const isText = isTextBlob(dataSrc);\n const length = buffer.length;\n return async function* piecesBlob() {\n while (pos < length) {\n const byte = buffer[pos];\n if (pos >= start + windowSize) {\n const oldByte = buffer[pos - windowSize];\n const oldByteTerm = Math.imul(oldByte, P_pow_w);\n hash = hash - oldByteTerm | 0;\n hash = Math.imul(hash, PRIME);\n hash = hash + byte | 0;\n } else {\n hash = Math.imul(hash, PRIME);\n hash = hash + byte | 0;\n }\n const currentChunkSize = pos - start + 1;\n let isBoundaryCandidate = false;\n if (currentChunkSize >= minChunkSize) {\n if ((hash >>> 0) % hashModulus === boundaryPattern) {\n isBoundaryCandidate = true;\n }\n }\n if (currentChunkSize >= maxChunkSize) {\n isBoundaryCandidate = true;\n }\n if (isBoundaryCandidate) {\n let isSafeBoundary = true;\n if (isText) {\n if (pos + 1 < length && (buffer[pos + 1] & 192) === 128) {\n isSafeBoundary = false;\n }\n }\n if (isSafeBoundary) {\n if (isText) {\n yield Promise.resolve(readString(buffer.subarray(start, pos + 1)));\n } else {\n yield await arrayBufferToBase64Single2(buffer.subarray(start, pos + 1));\n }\n start = pos + 1;\n }\n }\n pos++;\n }\n if (start < length) {\n if (isText) {\n yield Promise.resolve(readString(buffer.subarray(start, length)));\n } else {\n yield await arrayBufferToBase64Single2(buffer.subarray(start, length));\n }\n }\n };\n }\n\n // src/worker/bg.common.ts\n function postBack(key, seq, data) {\n self.postMessage({ key, seq, result: data });\n }\n\n // src/worker/universalTypes.ts\n var END_OF_DATA = null;\n\n // src/worker/bg.worker.splitting.ts\n function getMainThreadPostBack(key) {\n const _key = key;\n let seq = 0;\n return function(data) {\n if (data === END_OF_DATA) {\n if (seq === 0) {\n postBack(_key, seq++, "");\n }\n postBack(_key, seq++, END_OF_DATA);\n } else {\n postBack(_key, seq++, data);\n }\n };\n }\n async function processSplit(data) {\n const key = data.key;\n const dataSrc = data.dataSrc;\n const pieceSize = data.pieceSize;\n const plainSplit = data.plainSplit;\n const minimumChunkSize = data.minimumChunkSize;\n const filename = data.filename;\n const useSegmenter = data.useSegmenter;\n const func = data.splitVersion == 3 ? splitPiecesRabinKarp : data.splitVersion == 2 ? splitPieces2V2 : splitPieces2;\n const gen = await func(dataSrc, pieceSize, plainSplit, minimumChunkSize, filename, useSegmenter);\n const emit = getMainThreadPostBack(key);\n for await (const v of gen()) {\n emit(v);\n }\n emit(END_OF_DATA);\n }\n\n // node_modules/octagonal-wheels/dist/encryption/encryptionv3.js\n var webcrypto2 = globalThis.crypto;\n var SALT_STR = "fancySyncForYou!";\n var SALT = new TextEncoder().encode(SALT_STR);\n var _nonceV3 = new Uint32Array(1);\n var bufV3 = new Uint8Array(12);\n async function generateKey(passphrase) {\n const passphraseBin = new TextEncoder().encode(passphrase);\n const digestOfPassphrase = await webcrypto2.subtle.digest("SHA-256", new Uint8Array([...passphraseBin, ...SALT]));\n const salt = digestOfPassphrase.slice(0, 16);\n const baseKey = await webcrypto2.subtle.importKey("raw", passphraseBin, "PBKDF2", false, [\n "deriveBits",\n "deriveKey"\n ]);\n const pbkdf2Params = {\n name: "PBKDF2",\n hash: "SHA-256",\n salt,\n iterations: 1e5\n // Increased iterations for better security\n };\n const derivedKey = await webcrypto2.subtle.deriveKey(pbkdf2Params, baseKey, { name: "AES-GCM", length: 256 }, false, ["decrypt", "encrypt"]);\n return derivedKey;\n }\n var previousDecryptionPassphrase = "";\n var decryptionKey;\n async function decryptV3(encryptedResult, passphrase) {\n if (previousDecryptionPassphrase !== passphrase) {\n const key = await generateKey(passphrase);\n decryptionKey = key;\n previousDecryptionPassphrase = passphrase;\n }\n const ivStr = encryptedResult.substring(2, 26);\n const encryptedData = encryptedResult.substring(26);\n const iv = hexStringToUint8Array(ivStr);\n const encryptedDataArrayBuffer = base64ToArrayBuffer(encryptedData);\n const dataBuffer = await webcrypto2.subtle.decrypt({ name: "AES-GCM", iv }, decryptionKey, encryptedDataArrayBuffer);\n const plain = readString(new Uint8Array(dataBuffer));\n return plain;\n }\n\n // node_modules/octagonal-wheels/dist/memory/memo.js\n var UNDEFINED = /* @__PURE__ */ Symbol("undefined");\n function memoWithMap(bufferLength, fn, keyFunction) {\n if (bufferLength <= 0) {\n throw new Error("Buffer length must be greater than 0");\n }\n const cache = /* @__PURE__ */ new Map();\n const getKey = (args) => {\n return args.length > 0 && typeof args[0] === "string" ? args[0] : JSON.stringify(args, (key, value) => value === void 0 ? UNDEFINED : value);\n };\n return function(...args) {\n const key = keyFunction ? keyFunction(args) : getKey(args);\n if (cache.has(key)) {\n const hitPromise = cache.get(key);\n cache.delete(key);\n cache.set(key, hitPromise);\n return hitPromise;\n }\n const newPromise = fn(...args);\n cache.set(key, newPromise);\n newPromise.catch(() => {\n if (cache.get(key) === newPromise) {\n cache.delete(key);\n }\n });\n if (cache.size > bufferLength) {\n const oldest = cache.keys().next();\n if (!oldest.done)\n cache.delete(oldest.value);\n }\n return newPromise;\n };\n }\n\n // node_modules/octagonal-wheels/dist/encryption/hkdf.js\n var webcrypto3 = globalThis.crypto;\n var IV_LENGTH = 12;\n var PBKDF2_ITERATIONS = 31e4;\n var HKDF_SALT_LENGTH = 32;\n var gcmTagLength = 128;\n var HKDF_ENCRYPTED_PREFIX = "%=";\n var deriveMasterKey = memoWithMap(10, async (passphrase, pbkdf2Salt) => {\n const binaryPassphrase = writeString(passphrase);\n const keyMaterial = await webcrypto3.subtle.importKey("raw", binaryPassphrase, {\n name: "PBKDF2",\n length: 256\n // Length of the key in bits\n }, false, ["deriveKey"]);\n const masterKeyRaw = await webcrypto3.subtle.deriveKey(\n {\n name: "PBKDF2",\n salt: pbkdf2Salt,\n iterations: PBKDF2_ITERATIONS,\n hash: "SHA-256"\n },\n keyMaterial,\n // Output the "raw" key\n { name: "AES-GCM", length: 256 },\n true,\n // extractable\n ["encrypt", "decrypt"]\n // The master key is used for encryption/decryption\n );\n const masterKeyBuffer = await webcrypto3.subtle.exportKey("raw", masterKeyRaw);\n const hkdfKey = await webcrypto3.subtle.importKey("raw", masterKeyBuffer, { name: "HKDF" }, false, [\n "deriveKey"\n ]);\n return hkdfKey;\n }, ([passphrase, salt]) => {\n return `${passphrase}-${uint8ArrayToHexString(salt)}`;\n });\n async function deriveKey(passphrase, pbkdf2Salt, hkdfSalt) {\n const masterKey = await deriveMasterKey(passphrase, pbkdf2Salt);\n const chunkKey = await webcrypto3.subtle.deriveKey(\n {\n name: "HKDF",\n salt: hkdfSalt,\n info: new Uint8Array(),\n // Context info (if needed)\n hash: "SHA-256"\n },\n masterKey,\n // Specify the algorithm and usage for the chunk key\n { name: "AES-GCM", length: 256 },\n false,\n ["encrypt", "decrypt"]\n // The chunk key is used only for encryption/decryption\n );\n return chunkKey;\n }\n async function encryptData(key, iv, data) {\n return await webcrypto3.subtle.encrypt({\n name: "AES-GCM",\n iv,\n tagLength: gcmTagLength\n }, key, data);\n }\n async function _encrypt(input, passphrase, pbkdf2Salt) {\n const hkdfSalt = webcrypto3.getRandomValues(new Uint8Array(HKDF_SALT_LENGTH));\n const key = await deriveKey(passphrase, pbkdf2Salt, hkdfSalt);\n const iv = webcrypto3.getRandomValues(new Uint8Array(IV_LENGTH));\n const encryptedDataArrayBuffer = await encryptData(key, iv, input);\n const encryptedData = new Uint8Array(encryptedDataArrayBuffer);\n return [iv, hkdfSalt, encryptedData];\n }\n async function encryptBinary(input, passphrase, pbkdf2Salt) {\n const [iv, hkdfSalt, encryptedData] = await _encrypt(input, passphrase, pbkdf2Salt);\n const totalLength = iv.length + hkdfSalt.length + encryptedData.length;\n const result = new Uint8Array(totalLength);\n result.set(iv, 0);\n result.set(hkdfSalt, iv.length);\n result.set(encryptedData, iv.length + hkdfSalt.length);\n return result;\n }\n async function encrypt(input, passphrase, pbkdf2Salt) {\n const inputBuffer = writeString(input);\n const encrypted = await encryptBinary(inputBuffer, passphrase, pbkdf2Salt);\n const inBase64 = await arrayBufferToBase64Single(encrypted);\n return `${HKDF_ENCRYPTED_PREFIX}${inBase64}`;\n }\n async function _decrypt(iv, pbkdf2Salt, hkdfSalt, encryptedData, passphrase) {\n const key = await deriveKey(passphrase, pbkdf2Salt, hkdfSalt);\n const decryptedDataArrayBuffer = await webcrypto3.subtle.decrypt({\n name: "AES-GCM",\n iv,\n tagLength: gcmTagLength\n }, key, encryptedData);\n return new Uint8Array(decryptedDataArrayBuffer);\n }\n async function decryptBinary(binary, passphrase, pbkdf2Salt) {\n if (binary.length < IV_LENGTH + HKDF_SALT_LENGTH) {\n throw new Error("Invalid binary data length. Expected at least ivLength + saltLength bytes.");\n }\n const iv = binary.slice(0, IV_LENGTH);\n const hkdfSalt = binary.slice(IV_LENGTH, IV_LENGTH + HKDF_SALT_LENGTH);\n const encryptedData = binary.slice(IV_LENGTH + HKDF_SALT_LENGTH);\n const decryptedData = await _decrypt(iv, pbkdf2Salt, hkdfSalt, encryptedData, passphrase);\n return decryptedData;\n }\n async function decrypt(input, passphrase, pbkdf2Salt) {\n if (!input.startsWith(HKDF_ENCRYPTED_PREFIX)) {\n throw new Error(`Invalid input format. Expected input to start with \'${HKDF_ENCRYPTED_PREFIX}\'.`);\n }\n const headerLength = HKDF_ENCRYPTED_PREFIX.length;\n const encryptedData = base64ToArrayBuffer(input.slice(headerLength));\n const decrypted = await decryptBinary(new Uint8Array(encryptedData), passphrase, pbkdf2Salt);\n return readString(decrypted);\n }\n\n // node_modules/octagonal-wheels/dist/encryption/obfuscatePath.js\n var webcrypto4 = globalThis.crypto;\n\n // node_modules/octagonal-wheels/dist/encryption/encryption.js\n var KeyBuffs = /* @__PURE__ */ new Map();\n var decKeyBuffs = /* @__PURE__ */ new Map();\n var KEY_RECYCLE_COUNT = 100;\n var semiStaticFieldBuffer;\n var nonceBuffer = new Uint32Array(1);\n var webcrypto5 = globalThis.crypto;\n async function getKeyForEncrypt(passphrase, autoCalculateIterations) {\n const buffKey = `${passphrase}-${autoCalculateIterations}`;\n const f = KeyBuffs.get(buffKey);\n if (f) {\n f.count--;\n if (f.count > 0) {\n return [f.key, f.salt];\n }\n f.count--;\n }\n const passphraseLen = 15 - passphrase.length;\n const iteration = autoCalculateIterations ? (passphraseLen > 0 ? passphraseLen : 0) * 1e3 + 121 - passphraseLen : 1e5;\n const passphraseBin = new TextEncoder().encode(passphrase);\n const digest = await webcrypto5.subtle.digest({ name: "SHA-256" }, passphraseBin);\n const keyMaterial = await webcrypto5.subtle.importKey("raw", digest, { name: "PBKDF2" }, false, ["deriveKey"]);\n const salt = webcrypto5.getRandomValues(new Uint8Array(16));\n const key = await webcrypto5.subtle.deriveKey({\n name: "PBKDF2",\n salt,\n iterations: iteration,\n hash: "SHA-256"\n }, keyMaterial, { name: "AES-GCM", length: 256 }, false, ["encrypt"]);\n KeyBuffs.set(buffKey, {\n key,\n salt,\n count: KEY_RECYCLE_COUNT\n });\n return [key, salt];\n }\n var keyGCCount = KEY_RECYCLE_COUNT * 5;\n var decKeyIdx = 0;\n var decKeyMin = 0;\n async function getKeyForDecryption(passphrase, salt, autoCalculateIterations) {\n keyGCCount--;\n if (keyGCCount < 0) {\n keyGCCount = KEY_RECYCLE_COUNT;\n const threshold = (decKeyIdx - decKeyMin) / 2;\n for (const [key2, buff] of decKeyBuffs) {\n if (buff.count < threshold) {\n decKeyBuffs.delete(key2);\n }\n decKeyMin = decKeyIdx;\n }\n }\n decKeyIdx++;\n const bufKey = passphrase + uint8ArrayToHexString(salt) + autoCalculateIterations;\n const f = decKeyBuffs.get(bufKey);\n if (f) {\n f.count = decKeyIdx;\n return [f.key, f.salt];\n }\n const passphraseLen = 15 - passphrase.length;\n const iteration = autoCalculateIterations ? (passphraseLen > 0 ? passphraseLen : 0) * 1e3 + 121 - passphraseLen : 1e5;\n const passphraseBin = new TextEncoder().encode(passphrase);\n const digest = await webcrypto5.subtle.digest({ name: "SHA-256" }, passphraseBin);\n const keyMaterial = await webcrypto5.subtle.importKey("raw", digest, { name: "PBKDF2" }, false, ["deriveKey"]);\n const key = await webcrypto5.subtle.deriveKey({\n name: "PBKDF2",\n salt,\n iterations: iteration,\n hash: "SHA-256"\n }, keyMaterial, { name: "AES-GCM", length: 256 }, false, ["decrypt"]);\n decKeyBuffs.set(bufKey, {\n key,\n salt,\n count: 0\n });\n return [key, salt];\n }\n function getSemiStaticField(reset) {\n if (semiStaticFieldBuffer != null && !reset) {\n return semiStaticFieldBuffer;\n }\n semiStaticFieldBuffer = webcrypto5.getRandomValues(new Uint8Array(12));\n return semiStaticFieldBuffer;\n }\n function getNonce() {\n nonceBuffer[0]++;\n if (nonceBuffer[0] > 1e4) {\n getSemiStaticField(true);\n }\n return nonceBuffer;\n }\n async function encrypt2(input, passphrase, autoCalculateIterations) {\n const [key, salt] = await getKeyForEncrypt(passphrase, autoCalculateIterations);\n const fixedPart = getSemiStaticField();\n const invocationPart = getNonce();\n const iv = new Uint8Array([...fixedPart, ...new Uint8Array(invocationPart.buffer)]);\n const dataBuf = writeString(input);\n const encryptedDataArrayBuffer = await webcrypto5.subtle.encrypt({ name: "AES-GCM", iv }, key, dataBuf);\n const encryptedData2 = "" + await arrayBufferToBase64Single(new Uint8Array(encryptedDataArrayBuffer));\n const ret = `%${uint8ArrayToHexString(iv)}${uint8ArrayToHexString(salt)}${encryptedData2}`;\n return ret;\n }\n async function decryptV2(encryptedResult, passphrase, autoCalculateIterations) {\n try {\n const ivStr = encryptedResult.substring(1, 33);\n const salt = encryptedResult.substring(33, 65);\n const encryptedData = encryptedResult.substring(65);\n const [key] = await getKeyForDecryption(passphrase, hexStringToUint8Array(salt), autoCalculateIterations);\n const iv = hexStringToUint8Array(ivStr);\n const encryptedDataArrayBuffer = decodeBinary(encryptedData);\n const dataBuffer = await webcrypto5.subtle.decrypt({ name: "AES-GCM", iv }, key, encryptedDataArrayBuffer);\n const plain = readString(new Uint8Array(dataBuffer));\n return plain;\n } catch (ex) {\n Logger("Couldn\'t decode! You should wrong the passphrases (V2)", LOG_LEVEL_VERBOSE);\n Logger(ex, LOG_LEVEL_VERBOSE);\n throw ex;\n }\n }\n async function decrypt2(encryptedResult, passphrase, autoCalculateIterations) {\n try {\n if (encryptedResult[0] == "%") {\n if (encryptedResult[1] === "~") {\n return decryptV3(encryptedResult, passphrase);\n }\n return decryptV2(encryptedResult, passphrase, autoCalculateIterations);\n }\n if (!encryptedResult.startsWith("[") || !encryptedResult.endsWith("]")) {\n throw new Error("Encrypted data corrupted!");\n }\n const w = encryptedResult.substring(1, encryptedResult.length - 1).split(",").map((e) => e[0] == \'"\' ? e.substring(1, e.length - 1) : e);\n const [encryptedData, ivString, salt] = w;\n const [key] = await getKeyForDecryption(passphrase, hexStringToUint8Array(salt), autoCalculateIterations);\n const iv = hexStringToUint8Array(ivString);\n const encryptedDataBin = atob(encryptedData);\n const len = encryptedDataBin.length;\n const encryptedDataArrayBuffer = new Uint8Array(len);\n for (let i = len; i >= 0; --i) {\n encryptedDataArrayBuffer[i] = encryptedDataBin.charCodeAt(i);\n }\n const plainStringBuffer = await webcrypto5.subtle.decrypt({ name: "AES-GCM", iv }, key, encryptedDataArrayBuffer);\n const plainStringified = readString(new Uint8Array(plainStringBuffer));\n const plain = JSON.parse(plainStringified);\n return plain;\n } catch (ex) {\n Logger("Couldn\'t decode! You should wrong the passphrases", LOG_LEVEL_VERBOSE);\n Logger(ex, LOG_LEVEL_VERBOSE);\n throw ex;\n }\n }\n\n // node_modules/octagonal-wheels/dist/encryption/openSSLCompat/CBC.js\n var SALT_PREFIX = new Uint8Array([83, 97, 108, 116, 101, 100, 95, 95]);\n\n // node_modules/octagonal-wheels/dist/encryption/asymmetric/common.js\n var webCrypto = globalThis.crypto || window.crypto;\n var DEFAULT_RSA_PUBLIC_EXPONENT = new Uint8Array([1, 0, 1]);\n var HEAD_RSA = new Uint8Array([10, 244, 193]);\n var HEAD_ECDH = new Uint8Array([10, 244, 194]);\n\n // node_modules/octagonal-wheels/dist/encryption/obfuscatePathV2.js\n var webcrypto6 = globalThis.crypto;\n async function _deriveKeyFromPassphrase(passphrase, hkdfSalt) {\n const passphraseBin = writeString(passphrase);\n const keyMaterial = await webcrypto6.subtle.importKey("raw", passphraseBin, { name: "HKDF" }, false, ["deriveKey"]);\n const derivedKey = await webcrypto6.subtle.deriveKey({\n name: "HKDF",\n hash: "SHA-256",\n salt: hkdfSalt,\n info: new Uint8Array([])\n }, keyMaterial, { name: "HMAC", hash: "SHA-256", length: 256 }, false, ["sign"]);\n return derivedKey;\n }\n var deriveKeyFromPassphrase = memoWithMap(10, _deriveKeyFromPassphrase, ([passphrase, hkdfSalt]) => {\n return `${writeString(passphrase)}-${uint8ArrayToHexString(hkdfSalt)}`;\n });\n\n // src/worker/bg.worker.encryption.ts\n async function processEncryption(data) {\n const key = data.key;\n const { type, input, passphrase } = data;\n try {\n if (type == "encrypt") {\n const autoCalculateIterations = data.autoCalculateIterations;\n const result = await encrypt2(input, passphrase, autoCalculateIterations);\n self.postMessage({ key, result });\n } else if (type == "decrypt") {\n const autoCalculateIterations = data.autoCalculateIterations;\n const result = await decrypt2(input, passphrase, autoCalculateIterations);\n self.postMessage({ key, result });\n } else if (type == "encryptHKDF") {\n const pbkdf2Salt = data.pbkdf2Salt;\n const result = await encrypt(input, passphrase, pbkdf2Salt);\n self.postMessage({ key, result });\n } else if (type == "decryptHKDF") {\n const pbkdf2Salt = data.pbkdf2Salt;\n const result = await decrypt(input, passphrase, pbkdf2Salt);\n self.postMessage({ key, result });\n }\n } catch (ex) {\n self.postMessage({ key, error: ex });\n }\n }\n\n // src/worker/bg.worker.ts\n self.onmessage = (e) => {\n const data = e.data.data;\n if (data.type === "split") {\n return processSplit(data);\n } else if (data.type === "encrypt" || data.type === "decrypt") {\n return processEncryption(data);\n } else if (data.type === "encryptHKDF" || data.type === "decryptHKDF") {\n return processEncryption(data);\n } else {\n self.postMessage({ key: data.key, error: new Error("Invalid type") });\n }\n };\n})();\n/*! Bundled license information:\n\noctagonal-wheels/dist/encryption/asymmetric/common.js:\n (* istanbul ignore next -- @preserve *)\n*/\n';
|
|
19
|
+
var workerSource = '"use strict";\n(() => {\n var __create = Object.create;\n var __defProp = Object.defineProperty;\n var __getOwnPropDesc = Object.getOwnPropertyDescriptor;\n var __getOwnPropNames = Object.getOwnPropertyNames;\n var __getProtoOf = Object.getPrototypeOf;\n var __hasOwnProp = Object.prototype.hasOwnProperty;\n var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {\n get: (a, b) => (typeof require !== "undefined" ? require : a)[b]\n }) : x)(function(x) {\n if (typeof require !== "undefined") return require.apply(this, arguments);\n throw Error(\'Dynamic require of "\' + x + \'" is not supported\');\n });\n var __copyProps = (to, from, except, desc) => {\n if (from && typeof from === "object" || typeof from === "function") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n };\n var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(\n // If the importer is in node compatibility mode or this is not an ESM\n // file that has been converted to a CommonJS file using a Babel-\n // compatible transform (i.e. "__esModule" has not been set), then set\n // "default" to the CommonJS "module.exports" for node compatibility.\n isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,\n mod\n ));\n\n // node_modules/octagonal-wheels/dist/common/logger.js\n var LOG_LEVEL_VERBOSE = 16;\n var LOG_LEVEL_INFO = 32;\n var LOG_KIND_DEBUG = 1;\n var LOG_KIND_VERBOSE = 2;\n var LOG_KIND_WARNING = 4;\n var LOG_KIND_ERROR = 8;\n var LEVEL_INFO = LOG_LEVEL_INFO;\n var defaultLoggerEnv = {\n minLogLevel: LOG_LEVEL_INFO\n };\n var defaultLogger = function defaultLogger2(message, level = LEVEL_INFO, key) {\n if (level < defaultLoggerEnv.minLogLevel) {\n return;\n }\n const now = /* @__PURE__ */ new Date();\n const timestamp = now.toLocaleString();\n const messageContent = typeof message == "string" ? message : message instanceof Error ? `${message.name}:${message.message}` : JSON.stringify(message, null, 2);\n const newMessage = `${timestamp} ${level} ${messageContent}`;\n if (level & LOG_KIND_DEBUG) {\n console.debug(newMessage);\n } else if (level & LOG_KIND_WARNING) {\n console.warn(newMessage);\n } else if (level & LOG_KIND_ERROR) {\n console.error(newMessage);\n } else if (level & LOG_KIND_VERBOSE) {\n console.info(newMessage);\n } else {\n console.log(newMessage);\n }\n if (message instanceof Error) {\n console.dir(message.stack);\n }\n };\n var _logger = defaultLogger;\n function Logger(message, level, key) {\n _logger(message, level, key);\n }\n\n // node_modules/octagonal-wheels/dist/binary/base64.js\n var isProposalArrayBufferBase64Available = typeof Uint8Array !== "undefined" && //@ts-ignore: Not typed in project target level\n typeof Uint8Array.prototype.toBase64 === "function" && //@ts-ignore: Not typed in project target level\n typeof Uint8Array.fromBase64 === "function";\n function base64ToArrayBufferNative(base64) {\n if (base64.length === 0)\n return new ArrayBuffer(0);\n try {\n if (typeof base64 == "string")\n return Uint8Array.fromBase64(base64).buffer;\n const bufItems = base64.map((e) => Uint8Array.fromBase64(e).buffer);\n const len = bufItems.reduce((p, c) => p + c.byteLength, 0);\n const joinedArray = new Uint8Array(len);\n let offset = 0;\n bufItems.forEach((e) => {\n joinedArray.set(new Uint8Array(e), offset);\n offset += e.byteLength;\n });\n return joinedArray.buffer;\n } catch (ex) {\n Logger("Base64 Decode error", LOG_LEVEL_VERBOSE);\n Logger(ex, LOG_LEVEL_VERBOSE);\n return new ArrayBuffer(0);\n }\n }\n function base64ToArrayBufferBrowser(base64) {\n if (typeof base64 == "string")\n return base64ToArrayBufferInternalBrowser(base64);\n const bufItems = base64.map((e) => base64ToArrayBufferInternalBrowser(e));\n const len = bufItems.reduce((p, c) => p + c.byteLength, 0);\n const joinedArray = new Uint8Array(len);\n let offset = 0;\n bufItems.forEach((e) => {\n joinedArray.set(new Uint8Array(e), offset);\n offset += e.byteLength;\n });\n return joinedArray.buffer;\n }\n var base64ToArrayBuffer = isProposalArrayBufferBase64Available ? base64ToArrayBufferNative : base64ToArrayBufferBrowser;\n function base64ToArrayBufferInternalBrowser(base64) {\n try {\n const binary_string = globalThis.atob(base64);\n const len = binary_string.length;\n const bytes = new Uint8Array(len);\n for (let i = 0; i < len; i++) {\n bytes[i] = binary_string.charCodeAt(i);\n }\n return bytes.buffer;\n } catch (ex) {\n Logger("Base64 Decode error", LOG_LEVEL_VERBOSE);\n Logger(ex, LOG_LEVEL_VERBOSE);\n return new ArrayBuffer(0);\n }\n }\n var encodeChunkSize = 3 * 5e7;\n function arrayBufferToBase64internalBrowser(buffer) {\n return new Promise((res, rej) => {\n const blob = new Blob([buffer], { type: "application/octet-binary" });\n const reader = new FileReader();\n reader.onload = function(evt) {\n const dataURI = evt.target?.result?.toString() || "";\n if (buffer.byteLength != 0 && (dataURI == "" || dataURI == "data:"))\n return rej(new TypeError("Could not parse the encoded string"));\n const result = dataURI.substring(dataURI.indexOf(",") + 1);\n res(result);\n };\n reader.readAsDataURL(blob);\n });\n }\n async function arrayBufferToBase64SingleBrowser(buffer) {\n const buf = buffer instanceof Uint8Array ? buffer : new Uint8Array(buffer);\n if (buf.byteLength < QUANTUM)\n return btoa(String.fromCharCode.apply(null, [...buf]));\n return await arrayBufferToBase64internalBrowser(buf);\n }\n function arrayBufferToBase64SingleNative(buffer) {\n const buf = buffer instanceof Uint8Array ? buffer : new Uint8Array(buffer);\n return Promise.resolve(buf.toBase64());\n }\n var arrayBufferToBase64Single = isProposalArrayBufferBase64Available ? arrayBufferToBase64SingleNative : arrayBufferToBase64SingleBrowser;\n var QUANTUM = 32768;\n var te = new TextEncoder();\n var td = new TextDecoder("utf-8", { ignoreBOM: true });\n function writeString(string) {\n if (string.length > 128) {\n const buf = te.encode(string);\n return buf;\n }\n const buffer = new Uint8Array(string.length * 4);\n const length = string.length;\n let index = 0;\n let chr = 0;\n let idx = 0;\n while (idx < length) {\n chr = string.charCodeAt(idx++);\n if (chr < 128) {\n buffer[index++] = chr;\n } else if (chr < 2048) {\n buffer[index++] = 192 | chr >>> 6;\n buffer[index++] = 128 | chr & 63;\n } else if (chr < 55296 || chr > 57343) {\n buffer[index++] = 224 | chr >>> 12;\n buffer[index++] = 128 | chr >>> 6 & 63;\n buffer[index++] = 128 | chr & 63;\n } else {\n chr = (chr - 55296 << 10 | string.charCodeAt(idx++) - 56320) + 65536;\n buffer[index++] = 240 | chr >>> 18;\n buffer[index++] = 128 | chr >>> 12 & 63;\n buffer[index++] = 128 | chr >>> 6 & 63;\n buffer[index++] = 128 | chr & 63;\n }\n }\n return buffer.slice(0, index);\n }\n function readString(buffer) {\n const length = buffer.length;\n if (length > 128)\n return td.decode(buffer);\n let index = 0;\n const end = length;\n let string = "";\n while (index < end) {\n const chunk = [];\n const cEnd = Math.min(index + QUANTUM, end);\n while (index < cEnd) {\n const chr = buffer[index++];\n if (chr < 128) {\n chunk.push(chr);\n } else if ((chr & 224) === 192) {\n chunk.push((chr & 31) << 6 | buffer[index++] & 63);\n } else if ((chr & 240) === 224) {\n chunk.push((chr & 15) << 12 | (buffer[index++] & 63) << 6 | buffer[index++] & 63);\n } else if ((chr & 248) === 240) {\n let code = (chr & 7) << 18 | (buffer[index++] & 63) << 12 | (buffer[index++] & 63) << 6 | buffer[index++] & 63;\n if (code < 65536) {\n chunk.push(code);\n } else {\n code -= 65536;\n chunk.push((code >>> 10) + 55296, (code & 1023) + 56320);\n }\n }\n }\n string += String.fromCharCode(...chunk);\n }\n return string;\n }\n\n // node_modules/octagonal-wheels/dist/collection.js\n function* range(from, to) {\n for (let i = from; i <= to; i++) {\n yield i;\n }\n return;\n }\n\n // node_modules/octagonal-wheels/dist/binary/encodedUTF16.js\n var BINARY_CHUNK_MAX = 1024 * 1024 * 30;\n var table = {};\n var revTable = {};\n [...range(192, 447)].forEach((e, i) => {\n table[i] = e;\n revTable[e] = i;\n });\n function decodeToArrayBuffer(src) {\n if (src.length == 1)\n return _decodeToArrayBuffer(src[0]);\n const bufItems = src.map((e) => _decodeToArrayBuffer(e));\n const len = bufItems.reduce((p, c) => p + c.byteLength, 0);\n const joinedArray = new Uint8Array(len);\n let offset = 0;\n bufItems.forEach((e) => {\n joinedArray.set(new Uint8Array(e), offset);\n offset += e.byteLength;\n });\n return joinedArray.buffer;\n }\n function _decodeToArrayBuffer(src) {\n const out = new Uint8Array(src.length);\n const len = src.length;\n for (let i = 0; i < len; i++) {\n const char = src.charCodeAt(i);\n if (char >= 38 && char <= 126 && char != 58) {\n out[i] = char;\n } else {\n out[i] = revTable[char];\n }\n }\n return out.buffer;\n }\n\n // node_modules/octagonal-wheels/dist/binary/hex.js\n var revMap = {};\n var numMap = {};\n for (let i = 0; i < 256; i++) {\n revMap[`00${i.toString(16)}`.slice(-2)] = i;\n numMap[i] = `00${i.toString(16)}`.slice(-2);\n }\n var isProposalArrayBufferBase64Available2 = typeof Uint8Array !== "undefined" && //@ts-ignore: Not typed in project target level\n typeof Uint8Array.prototype.toBase64 === "function" && //@ts-ignore: Not typed in project target level\n typeof Uint8Array.fromBase64 === "function";\n var hexStringToUint8Array = isProposalArrayBufferBase64Available2 ? hexStringToUint8ArrayNative : hexStringToUint8ArrayBrowser;\n function hexStringToUint8ArrayNative(src) {\n return Uint8Array.fromHex(src);\n }\n function hexStringToUint8ArrayBrowser(src) {\n const len = src.length / 2;\n const ret = new Uint8Array(len);\n for (let i = 0; i < len; i++) {\n ret[i] = revMap[src[i * 2] + src[i * 2 + 1]];\n }\n return ret;\n }\n var uint8ArrayToHexString = isProposalArrayBufferBase64Available2 ? uint8ArrayToHexStringNative : uint8ArrayToHexStringBrowser;\n function uint8ArrayToHexStringBrowser(src) {\n return [...src].map((e) => numMap[e]).join("");\n }\n function uint8ArrayToHexStringNative(src) {\n return src.toHex();\n }\n\n // node_modules/octagonal-wheels/dist/binary/index.js\n function decodeBinary(src) {\n if (src.length == 0)\n return new Uint8Array().buffer;\n if (typeof src === "string") {\n if (src[0] === "%") {\n return _decodeToArrayBuffer(src.substring(1));\n }\n } else {\n if (src[0][0] === "%") {\n const [head, ...last] = src;\n return decodeToArrayBuffer([head.substring(1), ...last]);\n }\n }\n return base64ToArrayBuffer(src);\n }\n\n // src/common/coreEnvFunctions.ts\n var compatGlobal = typeof window !== "undefined" ? window : (\n // compatibility for CLIs, tests, and other non-browser environments.\n // eslint-disable-next-line obsidianmd/no-global-this\n globalThis\n );\n var _fetch = compatGlobal.fetch.bind(compatGlobal);\n var activeDocumentWindow = compatGlobal;\n var _activeDocument = activeDocumentWindow.activeDocument ?? activeDocumentWindow.document;\n\n // src/string_and_binary/convert.ts\n async function arrayBufferToBase64Single2(buffer) {\n try {\n return await arrayBufferToBase64Single(buffer);\n } catch (ex) {\n const maybeBuffer = compatGlobal?.Buffer;\n if (typeof maybeBuffer?.from === "function") {\n const view = buffer instanceof Uint8Array ? buffer : new Uint8Array(buffer);\n return maybeBuffer.from(view.buffer, view.byteOffset, view.byteLength).toString("base64");\n }\n throw ex;\n }\n }\n\n // node_modules/octagonal-wheels/dist/memory/LRUCache.js\n var LRUCache = class {\n /**\n * Creates a new instance of the LRUCache class.\n * @param maxCache The maximum number of items to cache.\n * @param maxCacheLength The maximum length of the cached values.\n * @param forwardOnly True if we only need to cache forward values.\n */\n constructor(maxCache, maxCacheLength, forwardOnly = false) {\n Object.defineProperty(this, "cache", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: /* @__PURE__ */ new Map([])\n });\n Object.defineProperty(this, "revCache", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: /* @__PURE__ */ new Map([])\n });\n Object.defineProperty(this, "maxCache", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: 200\n });\n Object.defineProperty(this, "maxCachedLength", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: 5e7\n });\n Object.defineProperty(this, "cachedLength", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: 0\n });\n Object.defineProperty(this, "enableReversed", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: true\n });\n this.maxCache = maxCache || 200;\n this.maxCachedLength = (maxCacheLength || 1) * 1e6;\n this.enableReversed = !forwardOnly;\n Logger(`Cache initialized ${this.maxCache} / ${this.maxCachedLength}`, LOG_LEVEL_VERBOSE);\n }\n /**\n * Clears the cache.\n */\n clear() {\n this.cache.clear();\n this.revCache.clear();\n }\n /**\n * Checks if the cache contains the specified key.\n * @param key The key to check.\n * @returns A boolean indicating whether the cache contains the key.\n */\n has(key) {\n return this.cache.has(key);\n }\n /**\n * Gets the value associated with the specified key from the cache.\n * @param key The key to retrieve the value for.\n * @returns The value associated with the key, or undefined if the key is not found.\n * @remarks After calling this method, the key will be updated to recently used.\n */\n get(key) {\n const v = this.cache.get(key);\n if (v) {\n this.cache.delete(key);\n this.cache.set(key, v);\n if (this.enableReversed) {\n this.revCache.delete(v);\n this.revCache.set(v, key);\n }\n }\n return v;\n }\n /**\n * Gets the key associated with the specified value from the cache.\n * @param value The value to retrieve the key for.\n * @returns The key associated with the value, or undefined if the value is not found.\n * @remarks After calling this method, the key will be updated to recently used.\n */\n revGet(value) {\n const key = this.revCache.get(value);\n if (key) {\n this.cache.delete(key);\n this.revCache.delete(value);\n this.cache.set(key, value);\n this.revCache.set(value, key);\n }\n return key;\n }\n /**\n * Sets the value associated with the specified key in the cache.\n * @param key The key to set the value for.\n * @param value The value to set.\n */\n set(key, value) {\n this.cache.set(key, value);\n if (this.enableReversed)\n this.revCache.set(value, key);\n this.cachedLength += `${value}`.length;\n if (this.cache.size > this.maxCache || this.cachedLength > this.maxCachedLength) {\n for (const [key2, value2] of this.cache) {\n this.cache.delete(key2);\n if (this.enableReversed)\n this.revCache.delete(value2);\n this.cachedLength -= `${value2}`.length;\n if (this.cache.size <= this.maxCache && this.cachedLength <= this.maxCachedLength)\n break;\n }\n }\n }\n };\n\n // node_modules/balanced-match/dist/esm/index.js\n var balanced = (a, b, str) => {\n const ma = a instanceof RegExp ? maybeMatch(a, str) : a;\n const mb = b instanceof RegExp ? maybeMatch(b, str) : b;\n const r = ma !== null && mb != null && range2(ma, mb, str);\n return r && {\n start: r[0],\n end: r[1],\n pre: str.slice(0, r[0]),\n body: str.slice(r[0] + ma.length, r[1]),\n post: str.slice(r[1] + mb.length)\n };\n };\n var maybeMatch = (reg, str) => {\n const m = str.match(reg);\n return m ? m[0] : null;\n };\n var range2 = (a, b, str) => {\n let begs, beg, left, right = void 0, result;\n let ai = str.indexOf(a);\n let bi = str.indexOf(b, ai + 1);\n let i = ai;\n if (ai >= 0 && bi > 0) {\n if (a === b) {\n return [ai, bi];\n }\n begs = [];\n left = str.length;\n while (i >= 0 && !result) {\n if (i === ai) {\n begs.push(i);\n ai = str.indexOf(a, i + 1);\n } else if (begs.length === 1) {\n const r = begs.pop();\n if (r !== void 0)\n result = [r, bi];\n } else {\n beg = begs.pop();\n if (beg !== void 0 && beg < left) {\n left = beg;\n right = bi;\n }\n bi = str.indexOf(b, i + 1);\n }\n i = ai < bi && ai >= 0 ? ai : bi;\n }\n if (begs.length && right !== void 0) {\n result = [left, right];\n }\n }\n return result;\n };\n\n // node_modules/brace-expansion/dist/esm/index.js\n var escSlash = "\\0SLASH" + Math.random() + "\\0";\n var escOpen = "\\0OPEN" + Math.random() + "\\0";\n var escClose = "\\0CLOSE" + Math.random() + "\\0";\n var escComma = "\\0COMMA" + Math.random() + "\\0";\n var escPeriod = "\\0PERIOD" + Math.random() + "\\0";\n var escSlashPattern = new RegExp(escSlash, "g");\n var escOpenPattern = new RegExp(escOpen, "g");\n var escClosePattern = new RegExp(escClose, "g");\n var escCommaPattern = new RegExp(escComma, "g");\n var escPeriodPattern = new RegExp(escPeriod, "g");\n var slashPattern = /\\\\\\\\/g;\n var openPattern = /\\\\{/g;\n var closePattern = /\\\\}/g;\n var commaPattern = /\\\\,/g;\n var periodPattern = /\\\\\\./g;\n var EXPANSION_MAX = 1e5;\n var EXPANSION_MAX_LENGTH = 4e6;\n function numeric(str) {\n return !isNaN(str) ? parseInt(str, 10) : str.charCodeAt(0);\n }\n function escapeBraces(str) {\n return str.replace(slashPattern, escSlash).replace(openPattern, escOpen).replace(closePattern, escClose).replace(commaPattern, escComma).replace(periodPattern, escPeriod);\n }\n function unescapeBraces(str) {\n return str.replace(escSlashPattern, "\\\\").replace(escOpenPattern, "{").replace(escClosePattern, "}").replace(escCommaPattern, ",").replace(escPeriodPattern, ".");\n }\n function parseCommaParts(str) {\n if (!str) {\n return [""];\n }\n const parts = [];\n const m = balanced("{", "}", str);\n if (!m) {\n return str.split(",");\n }\n const { pre, body, post } = m;\n const p = pre.split(",");\n p[p.length - 1] += "{" + body + "}";\n const postParts = parseCommaParts(post);\n if (post.length) {\n ;\n p[p.length - 1] += postParts.shift();\n p.push.apply(p, postParts);\n }\n parts.push.apply(parts, p);\n return parts;\n }\n function expand(str, options = {}) {\n if (!str) {\n return [];\n }\n const { max = EXPANSION_MAX, maxLength = EXPANSION_MAX_LENGTH } = options;\n if (str.slice(0, 2) === "{}") {\n str = "\\\\{\\\\}" + str.slice(2);\n }\n return expand_(escapeBraces(str), max, maxLength, true).map(unescapeBraces);\n }\n function embrace(str) {\n return "{" + str + "}";\n }\n function isPadded(el) {\n return /^-?0\\d/.test(el);\n }\n function lte(i, y) {\n return i <= y;\n }\n function gte(i, y) {\n return i >= y;\n }\n function combine(acc, pre, values, max, maxLength, dropEmpties) {\n const out = [];\n let length = 0;\n for (let a = 0; a < acc.length; a++) {\n for (let v = 0; v < values.length; v++) {\n if (out.length >= max)\n return out;\n const expansion = acc[a] + pre + values[v];\n if (dropEmpties && !expansion)\n continue;\n if (length + expansion.length > maxLength)\n return out;\n out.push(expansion);\n length += expansion.length;\n }\n }\n return out;\n }\n function expandSequence(body, isAlphaSequence, max) {\n const n = body.split(/\\.\\./);\n const N = [];\n if (n[0] === void 0 || n[1] === void 0) {\n return N;\n }\n const x = numeric(n[0]);\n const y = numeric(n[1]);\n const width = Math.max(n[0].length, n[1].length);\n let incr = n.length === 3 && n[2] !== void 0 ? Math.max(Math.abs(numeric(n[2])), 1) : 1;\n let test = lte;\n const reverse = y < x;\n if (reverse) {\n incr *= -1;\n test = gte;\n }\n const pad = n.some(isPadded);\n for (let i = x; test(i, y) && N.length < max; i += incr) {\n let c;\n if (isAlphaSequence) {\n c = String.fromCharCode(i);\n if (c === "\\\\") {\n c = "";\n }\n } else {\n c = String(i);\n if (pad) {\n const need = width - c.length;\n if (need > 0) {\n const z = new Array(need + 1).join("0");\n if (i < 0) {\n c = "-" + z + c.slice(1);\n } else {\n c = z + c;\n }\n }\n }\n }\n N.push(c);\n }\n return N;\n }\n function expand_(str, max, maxLength, isTop) {\n let acc = [""];\n let dropEmpties = false;\n let firstGroup = true;\n for (; ; ) {\n const m = balanced("{", "}", str);\n if (!m) {\n return combine(acc, str, [""], max, maxLength, dropEmpties);\n }\n const pre = m.pre;\n if (/\\$$/.test(pre)) {\n acc = combine(acc, pre + "{" + m.body + "}", [""], max, maxLength, dropEmpties && !m.post.length);\n firstGroup = false;\n if (!m.post.length)\n break;\n str = m.post;\n continue;\n }\n const isNumericSequence = /^-?\\d+\\.\\.-?\\d+(?:\\.\\.-?\\d+)?$/.test(m.body);\n const isAlphaSequence = /^[a-zA-Z]\\.\\.[a-zA-Z](?:\\.\\.-?\\d+)?$/.test(m.body);\n const isSequence = isNumericSequence || isAlphaSequence;\n const isOptions = m.body.indexOf(",") >= 0;\n if (!isSequence && !isOptions) {\n if (m.post.match(/,(?!,).*\\}/)) {\n str = m.pre + "{" + m.body + escClose + m.post;\n isTop = true;\n continue;\n }\n return combine(acc, pre + "{" + m.body + "}" + m.post, [""], max, maxLength, dropEmpties);\n }\n if (firstGroup) {\n dropEmpties = isTop && !isSequence;\n firstGroup = false;\n }\n let values;\n if (isSequence) {\n values = expandSequence(m.body, isAlphaSequence, max);\n } else {\n let n = parseCommaParts(m.body);\n if (n.length === 1 && n[0] !== void 0) {\n n = expand_(n[0], max, maxLength, false).map(embrace);\n if (n.length === 1) {\n acc = combine(acc, pre + n[0], [""], max, maxLength, dropEmpties && !m.post.length);\n if (!m.post.length)\n break;\n str = m.post;\n continue;\n }\n }\n values = [];\n for (let j = 0; j < n.length; j++) {\n values.push.apply(values, expand_(n[j], max, maxLength, false));\n }\n }\n acc = combine(acc, pre, values, max, maxLength, dropEmpties && !m.post.length);\n if (!m.post.length)\n break;\n str = m.post;\n }\n return acc;\n }\n\n // node_modules/minimatch/dist/esm/assert-valid-pattern.js\n var MAX_PATTERN_LENGTH = 1024 * 64;\n var assertValidPattern = (pattern) => {\n if (typeof pattern !== "string") {\n throw new TypeError("invalid pattern");\n }\n if (pattern.length > MAX_PATTERN_LENGTH) {\n throw new TypeError("pattern is too long");\n }\n };\n\n // node_modules/minimatch/dist/esm/brace-expressions.js\n var posixClasses = {\n "[:alnum:]": ["\\\\p{L}\\\\p{Nl}\\\\p{Nd}", true],\n "[:alpha:]": ["\\\\p{L}\\\\p{Nl}", true],\n "[:ascii:]": ["\\\\x00-\\\\x7f", false],\n "[:blank:]": ["\\\\p{Zs}\\\\t", true],\n "[:cntrl:]": ["\\\\p{Cc}", true],\n "[:digit:]": ["\\\\p{Nd}", true],\n "[:graph:]": ["\\\\p{Z}\\\\p{C}", true, true],\n "[:lower:]": ["\\\\p{Ll}", true],\n "[:print:]": ["\\\\p{C}", true],\n "[:punct:]": ["\\\\p{P}", true],\n "[:space:]": ["\\\\p{Z}\\\\t\\\\r\\\\n\\\\v\\\\f", true],\n "[:upper:]": ["\\\\p{Lu}", true],\n "[:word:]": ["\\\\p{L}\\\\p{Nl}\\\\p{Nd}\\\\p{Pc}", true],\n "[:xdigit:]": ["A-Fa-f0-9", false]\n };\n var braceEscape = (s) => s.replace(/[[\\]\\\\-]/g, "\\\\$&");\n var regexpEscape = (s) => s.replace(/[-[\\]{}()*+?.,\\\\^$|#\\s]/g, "\\\\$&");\n var rangesToString = (ranges) => ranges.join("");\n var parseClass = (glob, position) => {\n const pos = position;\n if (glob.charAt(pos) !== "[") {\n throw new Error("not in a brace expression");\n }\n const ranges = [];\n const negs = [];\n let i = pos + 1;\n let sawStart = false;\n let uflag = false;\n let escaping = false;\n let negate = false;\n let endPos = pos;\n let rangeStart = "";\n WHILE: while (i < glob.length) {\n const c = glob.charAt(i);\n if ((c === "!" || c === "^") && i === pos + 1) {\n negate = true;\n i++;\n continue;\n }\n if (c === "]" && sawStart && !escaping) {\n endPos = i + 1;\n break;\n }\n sawStart = true;\n if (c === "\\\\") {\n if (!escaping) {\n escaping = true;\n i++;\n continue;\n }\n }\n if (c === "[" && !escaping) {\n for (const [cls, [unip, u, neg]] of Object.entries(posixClasses)) {\n if (glob.startsWith(cls, i)) {\n if (rangeStart) {\n return ["$.", false, glob.length - pos, true];\n }\n i += cls.length;\n if (neg)\n negs.push(unip);\n else\n ranges.push(unip);\n uflag = uflag || u;\n continue WHILE;\n }\n }\n }\n escaping = false;\n if (rangeStart) {\n if (c > rangeStart) {\n ranges.push(braceEscape(rangeStart) + "-" + braceEscape(c));\n } else if (c === rangeStart) {\n ranges.push(braceEscape(c));\n }\n rangeStart = "";\n i++;\n continue;\n }\n if (glob.startsWith("-]", i + 1)) {\n ranges.push(braceEscape(c + "-"));\n i += 2;\n continue;\n }\n if (glob.startsWith("-", i + 1)) {\n rangeStart = c;\n i += 2;\n continue;\n }\n ranges.push(braceEscape(c));\n i++;\n }\n if (endPos < i) {\n return ["", false, 0, false];\n }\n if (!ranges.length && !negs.length) {\n return ["$.", false, glob.length - pos, true];\n }\n if (negs.length === 0 && ranges.length === 1 && /^\\\\?.$/.test(ranges[0]) && !negate) {\n const r = ranges[0].length === 2 ? ranges[0].slice(-1) : ranges[0];\n return [regexpEscape(r), false, endPos - pos, false];\n }\n const sranges = "[" + (negate ? "^" : "") + rangesToString(ranges) + "]";\n const snegs = "[" + (negate ? "" : "^") + rangesToString(negs) + "]";\n const comb = ranges.length && negs.length ? "(" + sranges + "|" + snegs + ")" : ranges.length ? sranges : snegs;\n return [comb, uflag, endPos - pos, true];\n };\n\n // node_modules/minimatch/dist/esm/unescape.js\n var unescape = (s, { windowsPathsNoEscape = false, magicalBraces = true } = {}) => {\n if (magicalBraces) {\n return windowsPathsNoEscape ? s.replace(/\\[([^/\\\\])\\]/g, "$1") : s.replace(/((?!\\\\).|^)\\[([^/\\\\])\\]/g, "$1$2").replace(/\\\\([^/])/g, "$1");\n }\n return windowsPathsNoEscape ? s.replace(/\\[([^/\\\\{}])\\]/g, "$1") : s.replace(/((?!\\\\).|^)\\[([^/\\\\{}])\\]/g, "$1$2").replace(/\\\\([^/{}])/g, "$1");\n };\n\n // node_modules/minimatch/dist/esm/ast.js\n var _a;\n var types = /* @__PURE__ */ new Set(["!", "?", "+", "*", "@"]);\n var isExtglobType = (c) => types.has(c);\n var isExtglobAST = (c) => isExtglobType(c.type);\n var adoptionMap = /* @__PURE__ */ new Map([\n ["!", ["@"]],\n ["?", ["?", "@"]],\n ["@", ["@"]],\n ["*", ["*", "+", "?", "@"]],\n ["+", ["+", "@"]]\n ]);\n var adoptionWithSpaceMap = /* @__PURE__ */ new Map([\n ["!", ["?"]],\n ["@", ["?"]],\n ["+", ["?", "*"]]\n ]);\n var adoptionAnyMap = /* @__PURE__ */ new Map([\n ["!", ["?", "@"]],\n ["?", ["?", "@"]],\n ["@", ["?", "@"]],\n ["*", ["*", "+", "?", "@"]],\n ["+", ["+", "@", "?", "*"]]\n ]);\n var usurpMap = /* @__PURE__ */ new Map([\n ["!", /* @__PURE__ */ new Map([["!", "@"]])],\n [\n "?",\n /* @__PURE__ */ new Map([\n ["*", "*"],\n ["+", "*"]\n ])\n ],\n [\n "@",\n /* @__PURE__ */ new Map([\n ["!", "!"],\n ["?", "?"],\n ["@", "@"],\n ["*", "*"],\n ["+", "+"]\n ])\n ],\n [\n "+",\n /* @__PURE__ */ new Map([\n ["?", "*"],\n ["*", "*"]\n ])\n ]\n ]);\n var startNoTraversal = "(?!(?:^|/)\\\\.\\\\.?(?:$|/))";\n var startNoDot = "(?!\\\\.)";\n var addPatternStart = /* @__PURE__ */ new Set(["[", "."]);\n var justDots = /* @__PURE__ */ new Set(["..", "."]);\n var reSpecials = new Set("().*{}+?[]^$\\\\!");\n var regExpEscape = (s) => s.replace(/[-[\\]{}()*+?.,\\\\^$|#\\s]/g, "\\\\$&");\n var qmark = "[^/]";\n var star = qmark + "*?";\n var starNoEmpty = qmark + "+?";\n var ID = 0;\n var AST = class {\n type;\n #root;\n #hasMagic;\n #uflag = false;\n #parts = [];\n #parent;\n #parentIndex;\n #negs;\n #filledNegs = false;\n #options;\n #toString;\n // set to true if it\'s an extglob with no children\n // (which really means one child of \'\')\n #emptyExt = false;\n id = ++ID;\n get depth() {\n return (this.#parent?.depth ?? -1) + 1;\n }\n [/* @__PURE__ */ Symbol.for("nodejs.util.inspect.custom")]() {\n return {\n "@@type": "AST",\n id: this.id,\n type: this.type,\n root: this.#root.id,\n parent: this.#parent?.id,\n depth: this.depth,\n partsLength: this.#parts.length,\n parts: this.#parts\n };\n }\n constructor(type, parent, options = {}) {\n this.type = type;\n if (type)\n this.#hasMagic = true;\n this.#parent = parent;\n this.#root = this.#parent ? this.#parent.#root : this;\n this.#options = this.#root === this ? options : this.#root.#options;\n this.#negs = this.#root === this ? [] : this.#root.#negs;\n if (type === "!" && !this.#root.#filledNegs)\n this.#negs.push(this);\n this.#parentIndex = this.#parent ? this.#parent.#parts.length : 0;\n }\n get hasMagic() {\n if (this.#hasMagic !== void 0)\n return this.#hasMagic;\n for (const p of this.#parts) {\n if (typeof p === "string")\n continue;\n if (p.type || p.hasMagic)\n return this.#hasMagic = true;\n }\n return this.#hasMagic;\n }\n // reconstructs the pattern\n toString() {\n return this.#toString !== void 0 ? this.#toString : !this.type ? this.#toString = this.#parts.map((p) => String(p)).join("") : this.#toString = this.type + "(" + this.#parts.map((p) => String(p)).join("|") + ")";\n }\n #fillNegs() {\n if (this !== this.#root)\n throw new Error("should only call on root");\n if (this.#filledNegs)\n return this;\n this.toString();\n this.#filledNegs = true;\n let n;\n while (n = this.#negs.pop()) {\n if (n.type !== "!")\n continue;\n let p = n;\n let pp = p.#parent;\n while (pp) {\n for (let i = p.#parentIndex + 1; !pp.type && i < pp.#parts.length; i++) {\n for (const part of n.#parts) {\n if (typeof part === "string") {\n throw new Error("string part in extglob AST??");\n }\n part.copyIn(pp.#parts[i]);\n }\n }\n p = pp;\n pp = p.#parent;\n }\n }\n return this;\n }\n push(...parts) {\n for (const p of parts) {\n if (p === "")\n continue;\n if (typeof p !== "string" && !(p instanceof _a && p.#parent === this)) {\n throw new Error("invalid part: " + p);\n }\n this.#parts.push(p);\n }\n }\n toJSON() {\n const ret = this.type === null ? this.#parts.slice().map((p) => typeof p === "string" ? p : p.toJSON()) : [this.type, ...this.#parts.map((p) => p.toJSON())];\n if (this.isStart() && !this.type)\n ret.unshift([]);\n if (this.isEnd() && (this === this.#root || this.#root.#filledNegs && this.#parent?.type === "!")) {\n ret.push({});\n }\n return ret;\n }\n isStart() {\n if (this.#root === this)\n return true;\n if (!this.#parent?.isStart())\n return false;\n if (this.#parentIndex === 0)\n return true;\n const p = this.#parent;\n for (let i = 0; i < this.#parentIndex; i++) {\n const pp = p.#parts[i];\n if (!(pp instanceof _a && pp.type === "!")) {\n return false;\n }\n }\n return true;\n }\n isEnd() {\n if (this.#root === this)\n return true;\n if (this.#parent?.type === "!")\n return true;\n if (!this.#parent?.isEnd())\n return false;\n if (!this.type)\n return this.#parent?.isEnd();\n const pl = this.#parent ? this.#parent.#parts.length : 0;\n return this.#parentIndex === pl - 1;\n }\n copyIn(part) {\n if (typeof part === "string")\n this.push(part);\n else\n this.push(part.clone(this));\n }\n clone(parent) {\n const c = new _a(this.type, parent);\n for (const p of this.#parts) {\n c.copyIn(p);\n }\n return c;\n }\n static #parseAST(str, ast, pos, opt, extDepth) {\n const maxDepth = opt.maxExtglobRecursion ?? 2;\n let escaping = false;\n let inBrace = false;\n let braceStart = -1;\n let braceNeg = false;\n if (ast.type === null) {\n let i2 = pos;\n let acc2 = "";\n while (i2 < str.length) {\n const c = str.charAt(i2++);\n if (escaping || c === "\\\\") {\n escaping = !escaping;\n acc2 += c;\n continue;\n }\n if (inBrace) {\n if (i2 === braceStart + 1) {\n if (c === "^" || c === "!") {\n braceNeg = true;\n }\n } else if (c === "]" && !(i2 === braceStart + 2 && braceNeg)) {\n inBrace = false;\n }\n acc2 += c;\n continue;\n } else if (c === "[") {\n inBrace = true;\n braceStart = i2;\n braceNeg = false;\n acc2 += c;\n continue;\n }\n const doRecurse = !opt.noext && isExtglobType(c) && str.charAt(i2) === "(" && extDepth <= maxDepth;\n if (doRecurse) {\n ast.push(acc2);\n acc2 = "";\n const ext2 = new _a(c, ast);\n i2 = _a.#parseAST(str, ext2, i2, opt, extDepth + 1);\n ast.push(ext2);\n continue;\n }\n acc2 += c;\n }\n ast.push(acc2);\n return i2;\n }\n let i = pos + 1;\n let part = new _a(null, ast);\n const parts = [];\n let acc = "";\n while (i < str.length) {\n const c = str.charAt(i++);\n if (escaping || c === "\\\\") {\n escaping = !escaping;\n acc += c;\n continue;\n }\n if (inBrace) {\n if (i === braceStart + 1) {\n if (c === "^" || c === "!") {\n braceNeg = true;\n }\n } else if (c === "]" && !(i === braceStart + 2 && braceNeg)) {\n inBrace = false;\n }\n acc += c;\n continue;\n } else if (c === "[") {\n inBrace = true;\n braceStart = i;\n braceNeg = false;\n acc += c;\n continue;\n }\n const doRecurse = !opt.noext && isExtglobType(c) && str.charAt(i) === "(" && /* c8 ignore start - the maxDepth is sufficient here */\n (extDepth <= maxDepth || ast && ast.#canAdoptType(c));\n if (doRecurse) {\n const depthAdd = ast && ast.#canAdoptType(c) ? 0 : 1;\n part.push(acc);\n acc = "";\n const ext2 = new _a(c, part);\n part.push(ext2);\n i = _a.#parseAST(str, ext2, i, opt, extDepth + depthAdd);\n continue;\n }\n if (c === "|") {\n part.push(acc);\n acc = "";\n parts.push(part);\n part = new _a(null, ast);\n continue;\n }\n if (c === ")") {\n if (acc === "" && ast.#parts.length === 0) {\n ast.#emptyExt = true;\n }\n part.push(acc);\n acc = "";\n ast.push(...parts, part);\n return i;\n }\n acc += c;\n }\n ast.type = null;\n ast.#hasMagic = void 0;\n ast.#parts = [str.substring(pos - 1)];\n return i;\n }\n #canAdoptWithSpace(child) {\n return this.#canAdopt(child, adoptionWithSpaceMap);\n }\n #canAdopt(child, map = adoptionMap) {\n if (!child || typeof child !== "object" || child.type !== null || child.#parts.length !== 1 || this.type === null) {\n return false;\n }\n const gc = child.#parts[0];\n if (!gc || typeof gc !== "object" || gc.type === null) {\n return false;\n }\n return this.#canAdoptType(gc.type, map);\n }\n #canAdoptType(c, map = adoptionAnyMap) {\n return !!map.get(this.type)?.includes(c);\n }\n #adoptWithSpace(child, index) {\n const gc = child.#parts[0];\n const blank = new _a(null, gc, this.options);\n blank.#parts.push("");\n gc.push(blank);\n this.#adopt(child, index);\n }\n #adopt(child, index) {\n const gc = child.#parts[0];\n this.#parts.splice(index, 1, ...gc.#parts);\n for (const p of gc.#parts) {\n if (typeof p === "object")\n p.#parent = this;\n }\n this.#toString = void 0;\n }\n #canUsurpType(c) {\n const m = usurpMap.get(this.type);\n return !!m?.has(c);\n }\n #canUsurp(child) {\n if (!child || typeof child !== "object" || child.type !== null || child.#parts.length !== 1 || this.type === null || this.#parts.length !== 1) {\n return false;\n }\n const gc = child.#parts[0];\n if (!gc || typeof gc !== "object" || gc.type === null) {\n return false;\n }\n return this.#canUsurpType(gc.type);\n }\n #usurp(child) {\n const m = usurpMap.get(this.type);\n const gc = child.#parts[0];\n const nt = m?.get(gc.type);\n if (!nt)\n return false;\n this.#parts = gc.#parts;\n for (const p of this.#parts) {\n if (typeof p === "object") {\n p.#parent = this;\n }\n }\n this.type = nt;\n this.#toString = void 0;\n this.#emptyExt = false;\n }\n static fromGlob(pattern, options = {}) {\n const ast = new _a(null, void 0, options);\n _a.#parseAST(pattern, ast, 0, options, 0);\n return ast;\n }\n // returns the regular expression if there\'s magic, or the unescaped\n // string if not.\n toMMPattern() {\n if (this !== this.#root)\n return this.#root.toMMPattern();\n const glob = this.toString();\n const [re, body, hasMagic, uflag] = this.toRegExpSource();\n const anyMagic = hasMagic || this.#hasMagic || this.#options.nocase && !this.#options.nocaseMagicOnly && glob.toUpperCase() !== glob.toLowerCase();\n if (!anyMagic) {\n return body;\n }\n const flags = (this.#options.nocase ? "i" : "") + (uflag ? "u" : "");\n return Object.assign(new RegExp(`^${re}$`, flags), {\n _src: re,\n _glob: glob\n });\n }\n get options() {\n return this.#options;\n }\n // returns the string match, the regexp source, whether there\'s magic\n // in the regexp (so a regular expression is required) and whether or\n // not the uflag is needed for the regular expression (for posix classes)\n // TODO: instead of injecting the start/end at this point, just return\n // the BODY of the regexp, along with the start/end portions suitable\n // for binding the start/end in either a joined full-path makeRe context\n // (where we bind to (^|/), or a standalone matchPart context (where\n // we bind to ^, and not /). Otherwise slashes get duped!\n //\n // In part-matching mode, the start is:\n // - if not isStart: nothing\n // - if traversal possible, but not allowed: ^(?!\\.\\.?$)\n // - if dots allowed or not possible: ^\n // - if dots possible and not allowed: ^(?!\\.)\n // end is:\n // - if not isEnd(): nothing\n // - else: $\n //\n // In full-path matching mode, we put the slash at the START of the\n // pattern, so start is:\n // - if first pattern: same as part-matching mode\n // - if not isStart(): nothing\n // - if traversal possible, but not allowed: /(?!\\.\\.?(?:$|/))\n // - if dots allowed or not possible: /\n // - if dots possible and not allowed: /(?!\\.)\n // end is:\n // - if last pattern, same as part-matching mode\n // - else nothing\n //\n // Always put the (?:$|/) on negated tails, though, because that has to be\n // there to bind the end of the negated pattern portion, and it\'s easier to\n // just stick it in now rather than try to inject it later in the middle of\n // the pattern.\n //\n // We can just always return the same end, and leave it up to the caller\n // to know whether it\'s going to be used joined or in parts.\n // And, if the start is adjusted slightly, can do the same there:\n // - if not isStart: nothing\n // - if traversal possible, but not allowed: (?:/|^)(?!\\.\\.?$)\n // - if dots allowed or not possible: (?:/|^)\n // - if dots possible and not allowed: (?:/|^)(?!\\.)\n //\n // But it\'s better to have a simpler binding without a conditional, for\n // performance, so probably better to return both start options.\n //\n // Then the caller just ignores the end if it\'s not the first pattern,\n // and the start always gets applied.\n //\n // But that\'s always going to be $ if it\'s the ending pattern, or nothing,\n // so the caller can just attach $ at the end of the pattern when building.\n //\n // So the todo is:\n // - better detect what kind of start is needed\n // - return both flavors of starting pattern\n // - attach $ at the end of the pattern when creating the actual RegExp\n //\n // Ah, but wait, no, that all only applies to the root when the first pattern\n // is not an extglob. If the first pattern IS an extglob, then we need all\n // that dot prevention biz to live in the extglob portions, because eg\n // +(*|.x*) can match .xy but not .yx.\n //\n // So, return the two flavors if it\'s #root and the first child is not an\n // AST, otherwise leave it to the child AST to handle it, and there,\n // use the (?:^|/) style of start binding.\n //\n // Even simplified further:\n // - Since the start for a join is eg /(?!\\.) and the start for a part\n // is ^(?!\\.), we can just prepend (?!\\.) to the pattern (either root\n // or start or whatever) and prepend ^ or / at the Regexp construction.\n toRegExpSource(allowDot) {\n const dot = allowDot ?? !!this.#options.dot;\n if (this.#root === this) {\n this.#flatten();\n this.#fillNegs();\n }\n if (!isExtglobAST(this)) {\n const noEmpty = this.isStart() && this.isEnd() && !this.#parts.some((s) => typeof s !== "string");\n const src = this.#parts.map((p) => {\n const [re, _, hasMagic, uflag] = typeof p === "string" ? _a.#parseGlob(p, this.#hasMagic, noEmpty) : p.toRegExpSource(allowDot);\n this.#hasMagic = this.#hasMagic || hasMagic;\n this.#uflag = this.#uflag || uflag;\n return re;\n }).join("");\n let start2 = "";\n if (this.isStart()) {\n if (typeof this.#parts[0] === "string") {\n const dotTravAllowed = this.#parts.length === 1 && justDots.has(this.#parts[0]);\n if (!dotTravAllowed) {\n const aps = addPatternStart;\n const needNoTrav = (\n // dots are allowed, and the pattern starts with [ or .\n dot && aps.has(src.charAt(0)) || // the pattern starts with \\., and then [ or .\n src.startsWith("\\\\.") && aps.has(src.charAt(2)) || // the pattern starts with \\.\\., and then [ or .\n src.startsWith("\\\\.\\\\.") && aps.has(src.charAt(4))\n );\n const needNoDot = !dot && !allowDot && aps.has(src.charAt(0));\n start2 = needNoTrav ? startNoTraversal : needNoDot ? startNoDot : "";\n }\n }\n }\n let end = "";\n if (this.isEnd() && this.#root.#filledNegs && this.#parent?.type === "!") {\n end = "(?:$|\\\\/)";\n }\n const final2 = start2 + src + end;\n return [\n final2,\n unescape(src),\n this.#hasMagic = !!this.#hasMagic,\n this.#uflag\n ];\n }\n const repeated = this.type === "*" || this.type === "+";\n const start = this.type === "!" ? "(?:(?!(?:" : "(?:";\n let body = this.#partsToRegExp(dot);\n if (this.isStart() && this.isEnd() && !body && this.type !== "!") {\n const s = this.toString();\n const me = this;\n me.#parts = [s];\n me.type = null;\n me.#hasMagic = void 0;\n return [s, unescape(this.toString()), false, false];\n }\n let bodyDotAllowed = !repeated || allowDot || dot || !startNoDot ? "" : this.#partsToRegExp(true);\n if (bodyDotAllowed === body) {\n bodyDotAllowed = "";\n }\n if (bodyDotAllowed) {\n body = `(?:${body})(?:${bodyDotAllowed})*?`;\n }\n let final = "";\n if (this.type === "!" && this.#emptyExt) {\n final = (this.isStart() && !dot ? startNoDot : "") + starNoEmpty;\n } else {\n const close = this.type === "!" ? (\n // !() must match something,but !(x) can match \'\'\n "))" + (this.isStart() && !dot && !allowDot ? startNoDot : "") + star + ")"\n ) : this.type === "@" ? ")" : this.type === "?" ? ")?" : this.type === "+" && bodyDotAllowed ? ")" : this.type === "*" && bodyDotAllowed ? `)?` : `)${this.type}`;\n final = start + body + close;\n }\n return [\n final,\n unescape(body),\n this.#hasMagic = !!this.#hasMagic,\n this.#uflag\n ];\n }\n #flatten() {\n if (!isExtglobAST(this)) {\n for (const p of this.#parts) {\n if (typeof p === "object") {\n p.#flatten();\n }\n }\n } else {\n let iterations = 0;\n let done = false;\n do {\n done = true;\n for (let i = 0; i < this.#parts.length; i++) {\n const c = this.#parts[i];\n if (typeof c === "object") {\n c.#flatten();\n if (this.#canAdopt(c)) {\n done = false;\n this.#adopt(c, i);\n } else if (this.#canAdoptWithSpace(c)) {\n done = false;\n this.#adoptWithSpace(c, i);\n } else if (this.#canUsurp(c)) {\n done = false;\n this.#usurp(c);\n }\n }\n }\n } while (!done && ++iterations < 10);\n }\n this.#toString = void 0;\n }\n #partsToRegExp(dot) {\n return this.#parts.map((p) => {\n if (typeof p === "string") {\n throw new Error("string type in extglob ast??");\n }\n const [re, _, _hasMagic, uflag] = p.toRegExpSource(dot);\n this.#uflag = this.#uflag || uflag;\n return re;\n }).filter((p) => !(this.isStart() && this.isEnd()) || !!p).join("|");\n }\n static #parseGlob(glob, hasMagic, noEmpty = false) {\n let escaping = false;\n let re = "";\n let uflag = false;\n let inStar = false;\n for (let i = 0; i < glob.length; i++) {\n const c = glob.charAt(i);\n if (escaping) {\n escaping = false;\n re += (reSpecials.has(c) ? "\\\\" : "") + c;\n continue;\n }\n if (c === "*") {\n if (inStar)\n continue;\n inStar = true;\n re += noEmpty && /^[*]+$/.test(glob) ? starNoEmpty : star;\n hasMagic = true;\n continue;\n } else {\n inStar = false;\n }\n if (c === "\\\\") {\n if (i === glob.length - 1) {\n re += "\\\\\\\\";\n } else {\n escaping = true;\n }\n continue;\n }\n if (c === "[") {\n const [src, needUflag, consumed, magic] = parseClass(glob, i);\n if (consumed) {\n re += src;\n uflag = uflag || needUflag;\n i += consumed - 1;\n hasMagic = hasMagic || magic;\n continue;\n }\n }\n if (c === "?") {\n re += qmark;\n hasMagic = true;\n continue;\n }\n re += regExpEscape(c);\n }\n return [re, unescape(glob), !!hasMagic, uflag];\n }\n };\n _a = AST;\n\n // node_modules/minimatch/dist/esm/escape.js\n var escape = (s, { windowsPathsNoEscape = false, magicalBraces = false } = {}) => {\n if (magicalBraces) {\n return windowsPathsNoEscape ? s.replace(/[?*()[\\]{}]/g, "[$&]") : s.replace(/[?*()[\\]\\\\{}]/g, "\\\\$&");\n }\n return windowsPathsNoEscape ? s.replace(/[?*()[\\]]/g, "[$&]") : s.replace(/[?*()[\\]\\\\]/g, "\\\\$&");\n };\n\n // node_modules/minimatch/dist/esm/index.js\n var minimatch = (p, pattern, options = {}) => {\n assertValidPattern(pattern);\n if (!options.nocomment && pattern.charAt(0) === "#") {\n return false;\n }\n return new Minimatch(pattern, options).match(p);\n };\n var starDotExtRE = /^\\*+([^+@!?*[(]*)$/;\n var starDotExtTest = (ext2) => (f) => !f.startsWith(".") && f.endsWith(ext2);\n var starDotExtTestDot = (ext2) => (f) => f.endsWith(ext2);\n var starDotExtTestNocase = (ext2) => {\n ext2 = ext2.toLowerCase();\n return (f) => !f.startsWith(".") && f.toLowerCase().endsWith(ext2);\n };\n var starDotExtTestNocaseDot = (ext2) => {\n ext2 = ext2.toLowerCase();\n return (f) => f.toLowerCase().endsWith(ext2);\n };\n var starDotStarRE = /^\\*+\\.\\*+$/;\n var starDotStarTest = (f) => !f.startsWith(".") && f.includes(".");\n var starDotStarTestDot = (f) => f !== "." && f !== ".." && f.includes(".");\n var dotStarRE = /^\\.\\*+$/;\n var dotStarTest = (f) => f !== "." && f !== ".." && f.startsWith(".");\n var starRE = /^\\*+$/;\n var starTest = (f) => f.length !== 0 && !f.startsWith(".");\n var starTestDot = (f) => f.length !== 0 && f !== "." && f !== "..";\n var qmarksRE = /^\\?+([^+@!?*[(]*)?$/;\n var qmarksTestNocase = ([$0, ext2 = ""]) => {\n const noext = qmarksTestNoExt([$0]);\n if (!ext2)\n return noext;\n ext2 = ext2.toLowerCase();\n return (f) => noext(f) && f.toLowerCase().endsWith(ext2);\n };\n var qmarksTestNocaseDot = ([$0, ext2 = ""]) => {\n const noext = qmarksTestNoExtDot([$0]);\n if (!ext2)\n return noext;\n ext2 = ext2.toLowerCase();\n return (f) => noext(f) && f.toLowerCase().endsWith(ext2);\n };\n var qmarksTestDot = ([$0, ext2 = ""]) => {\n const noext = qmarksTestNoExtDot([$0]);\n return !ext2 ? noext : (f) => noext(f) && f.endsWith(ext2);\n };\n var qmarksTest = ([$0, ext2 = ""]) => {\n const noext = qmarksTestNoExt([$0]);\n return !ext2 ? noext : (f) => noext(f) && f.endsWith(ext2);\n };\n var qmarksTestNoExt = ([$0]) => {\n const len = $0.length;\n return (f) => f.length === len && !f.startsWith(".");\n };\n var qmarksTestNoExtDot = ([$0]) => {\n const len = $0.length;\n return (f) => f.length === len && f !== "." && f !== "..";\n };\n var defaultPlatform = typeof process === "object" && process ? typeof process.env === "object" && process.env && process.env.__MINIMATCH_TESTING_PLATFORM__ || process.platform : "posix";\n var path = {\n win32: { sep: "\\\\" },\n posix: { sep: "/" }\n };\n var sep = defaultPlatform === "win32" ? path.win32.sep : path.posix.sep;\n minimatch.sep = sep;\n var GLOBSTAR = /* @__PURE__ */ Symbol("globstar **");\n minimatch.GLOBSTAR = GLOBSTAR;\n var qmark2 = "[^/]";\n var star2 = qmark2 + "*?";\n var twoStarDot = "(?:(?!(?:\\\\/|^)(?:\\\\.{1,2})($|\\\\/)).)*?";\n var twoStarNoDot = "(?:(?!(?:\\\\/|^)\\\\.).)*?";\n var filter = (pattern, options = {}) => (p) => minimatch(p, pattern, options);\n minimatch.filter = filter;\n var ext = (a, b = {}) => Object.assign({}, a, b);\n var defaults = (def) => {\n if (!def || typeof def !== "object" || !Object.keys(def).length) {\n return minimatch;\n }\n const orig = minimatch;\n const m = (p, pattern, options = {}) => orig(p, pattern, ext(def, options));\n return Object.assign(m, {\n Minimatch: class Minimatch extends orig.Minimatch {\n constructor(pattern, options = {}) {\n super(pattern, ext(def, options));\n }\n static defaults(options) {\n return orig.defaults(ext(def, options)).Minimatch;\n }\n },\n AST: class AST extends orig.AST {\n /* c8 ignore start */\n constructor(type, parent, options = {}) {\n super(type, parent, ext(def, options));\n }\n /* c8 ignore stop */\n static fromGlob(pattern, options = {}) {\n return orig.AST.fromGlob(pattern, ext(def, options));\n }\n },\n unescape: (s, options = {}) => orig.unescape(s, ext(def, options)),\n escape: (s, options = {}) => orig.escape(s, ext(def, options)),\n filter: (pattern, options = {}) => orig.filter(pattern, ext(def, options)),\n defaults: (options) => orig.defaults(ext(def, options)),\n makeRe: (pattern, options = {}) => orig.makeRe(pattern, ext(def, options)),\n braceExpand: (pattern, options = {}) => orig.braceExpand(pattern, ext(def, options)),\n match: (list, pattern, options = {}) => orig.match(list, pattern, ext(def, options)),\n sep: orig.sep,\n GLOBSTAR\n });\n };\n minimatch.defaults = defaults;\n var braceExpand = (pattern, options = {}) => {\n assertValidPattern(pattern);\n if (options.nobrace || !/\\{(?:(?!\\{).)*\\}/.test(pattern)) {\n return [pattern];\n }\n return expand(pattern, { max: options.braceExpandMax });\n };\n minimatch.braceExpand = braceExpand;\n var makeRe = (pattern, options = {}) => new Minimatch(pattern, options).makeRe();\n minimatch.makeRe = makeRe;\n var match = (list, pattern, options = {}) => {\n const mm = new Minimatch(pattern, options);\n list = list.filter((f) => mm.match(f));\n if (mm.options.nonull && !list.length) {\n list.push(pattern);\n }\n return list;\n };\n minimatch.match = match;\n var globMagic = /[?*]|[+@!]\\(.*?\\)|\\[|\\]/;\n var regExpEscape2 = (s) => s.replace(/[-[\\]{}()*+?.,\\\\^$|#\\s]/g, "\\\\$&");\n var Minimatch = class {\n options;\n set;\n pattern;\n windowsPathsNoEscape;\n nonegate;\n negate;\n comment;\n empty;\n preserveMultipleSlashes;\n partial;\n globSet;\n globParts;\n nocase;\n isWindows;\n platform;\n windowsNoMagicRoot;\n maxGlobstarRecursion;\n regexp;\n constructor(pattern, options = {}) {\n assertValidPattern(pattern);\n options = options || {};\n this.options = options;\n this.maxGlobstarRecursion = options.maxGlobstarRecursion ?? 200;\n this.pattern = pattern;\n this.platform = options.platform || defaultPlatform;\n this.isWindows = this.platform === "win32";\n const awe = "allowWindowsEscape";\n this.windowsPathsNoEscape = !!options.windowsPathsNoEscape || options[awe] === false;\n if (this.windowsPathsNoEscape) {\n this.pattern = this.pattern.replace(/\\\\/g, "/");\n }\n this.preserveMultipleSlashes = !!options.preserveMultipleSlashes;\n this.regexp = null;\n this.negate = false;\n this.nonegate = !!options.nonegate;\n this.comment = false;\n this.empty = false;\n this.partial = !!options.partial;\n this.nocase = !!this.options.nocase;\n this.windowsNoMagicRoot = options.windowsNoMagicRoot !== void 0 ? options.windowsNoMagicRoot : !!(this.isWindows && this.nocase);\n this.globSet = [];\n this.globParts = [];\n this.set = [];\n this.make();\n }\n hasMagic() {\n if (this.options.magicalBraces && this.set.length > 1) {\n return true;\n }\n for (const pattern of this.set) {\n for (const part of pattern) {\n if (typeof part !== "string")\n return true;\n }\n }\n return false;\n }\n debug(..._) {\n }\n make() {\n const pattern = this.pattern;\n const options = this.options;\n if (!options.nocomment && pattern.charAt(0) === "#") {\n this.comment = true;\n return;\n }\n if (!pattern) {\n this.empty = true;\n return;\n }\n this.parseNegate();\n this.globSet = [...new Set(this.braceExpand())];\n if (options.debug) {\n this.debug = (...args) => console.error(...args);\n }\n this.debug(this.pattern, this.globSet);\n const rawGlobParts = this.globSet.map((s) => this.slashSplit(s));\n this.globParts = this.preprocess(rawGlobParts);\n this.debug(this.pattern, this.globParts);\n let set = this.globParts.map((s, _, __) => {\n if (this.isWindows && this.windowsNoMagicRoot) {\n const isUNC = s[0] === "" && s[1] === "" && (s[2] === "?" || !globMagic.test(s[2])) && !globMagic.test(s[3]);\n const isDrive = /^[a-z]:/i.test(s[0]);\n if (isUNC) {\n return [\n ...s.slice(0, 4),\n ...s.slice(4).map((ss) => this.parse(ss))\n ];\n } else if (isDrive) {\n return [s[0], ...s.slice(1).map((ss) => this.parse(ss))];\n }\n }\n return s.map((ss) => this.parse(ss));\n });\n this.debug(this.pattern, set);\n this.set = set.filter((s) => s.indexOf(false) === -1);\n if (this.isWindows) {\n for (let i = 0; i < this.set.length; i++) {\n const p = this.set[i];\n if (p[0] === "" && p[1] === "" && this.globParts[i][2] === "?" && typeof p[3] === "string" && /^[a-z]:$/i.test(p[3])) {\n p[2] = "?";\n }\n }\n }\n this.debug(this.pattern, this.set);\n }\n // various transforms to equivalent pattern sets that are\n // faster to process in a filesystem walk. The goal is to\n // eliminate what we can, and push all ** patterns as far\n // to the right as possible, even if it increases the number\n // of patterns that we have to process.\n preprocess(globParts) {\n if (this.options.noglobstar) {\n for (const partset of globParts) {\n for (let j = 0; j < partset.length; j++) {\n if (partset[j] === "**") {\n partset[j] = "*";\n }\n }\n }\n }\n const { optimizationLevel = 1 } = this.options;\n if (optimizationLevel >= 2) {\n globParts = this.firstPhasePreProcess(globParts);\n globParts = this.secondPhasePreProcess(globParts);\n } else if (optimizationLevel >= 1) {\n globParts = this.levelOneOptimize(globParts);\n } else {\n globParts = this.adjascentGlobstarOptimize(globParts);\n }\n return globParts;\n }\n // just get rid of adjascent ** portions\n adjascentGlobstarOptimize(globParts) {\n return globParts.map((parts) => {\n let gs = -1;\n while (-1 !== (gs = parts.indexOf("**", gs + 1))) {\n let i = gs;\n while (parts[i + 1] === "**") {\n i++;\n }\n if (i !== gs) {\n parts.splice(gs, i - gs);\n }\n }\n return parts;\n });\n }\n // get rid of adjascent ** and resolve .. portions\n levelOneOptimize(globParts) {\n return globParts.map((parts) => {\n parts = parts.reduce((set, part) => {\n const prev = set[set.length - 1];\n if (part === "**" && prev === "**") {\n return set;\n }\n if (part === "..") {\n if (prev && prev !== ".." && prev !== "." && prev !== "**") {\n set.pop();\n return set;\n }\n }\n set.push(part);\n return set;\n }, []);\n return parts.length === 0 ? [""] : parts;\n });\n }\n levelTwoFileOptimize(parts) {\n if (!Array.isArray(parts)) {\n parts = this.slashSplit(parts);\n }\n let didSomething = false;\n do {\n didSomething = false;\n if (!this.preserveMultipleSlashes) {\n for (let i = 1; i < parts.length - 1; i++) {\n const p = parts[i];\n if (i === 1 && p === "" && parts[0] === "")\n continue;\n if (p === "." || p === "") {\n didSomething = true;\n parts.splice(i, 1);\n i--;\n }\n }\n if (parts[0] === "." && parts.length === 2 && (parts[1] === "." || parts[1] === "")) {\n didSomething = true;\n parts.pop();\n }\n }\n let dd = 0;\n while (-1 !== (dd = parts.indexOf("..", dd + 1))) {\n const p = parts[dd - 1];\n if (p && p !== "." && p !== ".." && p !== "**" && !(this.isWindows && /^[a-z]:$/i.test(p))) {\n didSomething = true;\n parts.splice(dd - 1, 2);\n dd -= 2;\n }\n }\n } while (didSomething);\n return parts.length === 0 ? [""] : parts;\n }\n // First phase: single-pattern processing\n // <pre> is 1 or more portions\n // <rest> is 1 or more portions\n // <p> is any portion other than ., .., \'\', or **\n // <e> is . or \'\'\n //\n // **/.. is *brutal* for filesystem walking performance, because\n // it effectively resets the recursive walk each time it occurs,\n // and ** cannot be reduced out by a .. pattern part like a regexp\n // or most strings (other than .., ., and \'\') can be.\n //\n // <pre>/**/../<p>/<p>/<rest> -> {<pre>/../<p>/<p>/<rest>,<pre>/**/<p>/<p>/<rest>}\n // <pre>/<e>/<rest> -> <pre>/<rest>\n // <pre>/<p>/../<rest> -> <pre>/<rest>\n // **/**/<rest> -> **/<rest>\n //\n // **/*/<rest> -> */**/<rest> <== not valid because ** doesn\'t follow\n // this WOULD be allowed if ** did follow symlinks, or * didn\'t\n firstPhasePreProcess(globParts) {\n let didSomething = false;\n do {\n didSomething = false;\n for (let parts of globParts) {\n let gs = -1;\n while (-1 !== (gs = parts.indexOf("**", gs + 1))) {\n let gss = gs;\n while (parts[gss + 1] === "**") {\n gss++;\n }\n if (gss > gs) {\n parts.splice(gs + 1, gss - gs);\n }\n let next = parts[gs + 1];\n const p = parts[gs + 2];\n const p2 = parts[gs + 3];\n if (next !== "..")\n continue;\n if (!p || p === "." || p === ".." || !p2 || p2 === "." || p2 === "..") {\n continue;\n }\n didSomething = true;\n parts.splice(gs, 1);\n const other = parts.slice(0);\n other[gs] = "**";\n globParts.push(other);\n gs--;\n }\n if (!this.preserveMultipleSlashes) {\n for (let i = 1; i < parts.length - 1; i++) {\n const p = parts[i];\n if (i === 1 && p === "" && parts[0] === "")\n continue;\n if (p === "." || p === "") {\n didSomething = true;\n parts.splice(i, 1);\n i--;\n }\n }\n if (parts[0] === "." && parts.length === 2 && (parts[1] === "." || parts[1] === "")) {\n didSomething = true;\n parts.pop();\n }\n }\n let dd = 0;\n while (-1 !== (dd = parts.indexOf("..", dd + 1))) {\n const p = parts[dd - 1];\n if (p && p !== "." && p !== ".." && p !== "**") {\n didSomething = true;\n const needDot = dd === 1 && parts[dd + 1] === "**";\n const splin = needDot ? ["."] : [];\n parts.splice(dd - 1, 2, ...splin);\n if (parts.length === 0)\n parts.push("");\n dd -= 2;\n }\n }\n }\n } while (didSomething);\n return globParts;\n }\n // second phase: multi-pattern dedupes\n // {<pre>/*/<rest>,<pre>/<p>/<rest>} -> <pre>/*/<rest>\n // {<pre>/<rest>,<pre>/<rest>} -> <pre>/<rest>\n // {<pre>/**/<rest>,<pre>/<rest>} -> <pre>/**/<rest>\n //\n // {<pre>/**/<rest>,<pre>/**/<p>/<rest>} -> <pre>/**/<rest>\n // ^-- not valid because ** doens\'t follow symlinks\n secondPhasePreProcess(globParts) {\n for (let i = 0; i < globParts.length - 1; i++) {\n for (let j = i + 1; j < globParts.length; j++) {\n const matched = this.partsMatch(globParts[i], globParts[j], !this.preserveMultipleSlashes);\n if (matched) {\n globParts[i] = [];\n globParts[j] = matched;\n break;\n }\n }\n }\n return globParts.filter((gs) => gs.length);\n }\n partsMatch(a, b, emptyGSMatch = false) {\n let ai = 0;\n let bi = 0;\n let result = [];\n let which = "";\n while (ai < a.length && bi < b.length) {\n if (a[ai] === b[bi]) {\n result.push(which === "b" ? b[bi] : a[ai]);\n ai++;\n bi++;\n } else if (emptyGSMatch && a[ai] === "**" && b[bi] === a[ai + 1]) {\n result.push(a[ai]);\n ai++;\n } else if (emptyGSMatch && b[bi] === "**" && a[ai] === b[bi + 1]) {\n result.push(b[bi]);\n bi++;\n } else if (a[ai] === "*" && b[bi] && (this.options.dot || !b[bi].startsWith(".")) && b[bi] !== "**") {\n if (which === "b")\n return false;\n which = "a";\n result.push(a[ai]);\n ai++;\n bi++;\n } else if (b[bi] === "*" && a[ai] && (this.options.dot || !a[ai].startsWith(".")) && a[ai] !== "**") {\n if (which === "a")\n return false;\n which = "b";\n result.push(b[bi]);\n ai++;\n bi++;\n } else {\n return false;\n }\n }\n return a.length === b.length && result;\n }\n parseNegate() {\n if (this.nonegate)\n return;\n const pattern = this.pattern;\n let negate = false;\n let negateOffset = 0;\n for (let i = 0; i < pattern.length && pattern.charAt(i) === "!"; i++) {\n negate = !negate;\n negateOffset++;\n }\n if (negateOffset)\n this.pattern = pattern.slice(negateOffset);\n this.negate = negate;\n }\n // set partial to true to test if, for example,\n // "/a/b" matches the start of "/*/b/*/d"\n // Partial means, if you run out of file before you run\n // out of pattern, then that\'s fine, as long as all\n // the parts match.\n matchOne(file, pattern, partial = false) {\n let fileStartIndex = 0;\n let patternStartIndex = 0;\n if (this.isWindows) {\n const fileDrive = typeof file[0] === "string" && /^[a-z]:$/i.test(file[0]);\n const fileUNC = !fileDrive && file[0] === "" && file[1] === "" && file[2] === "?" && /^[a-z]:$/i.test(file[3]);\n const patternDrive = typeof pattern[0] === "string" && /^[a-z]:$/i.test(pattern[0]);\n const patternUNC = !patternDrive && pattern[0] === "" && pattern[1] === "" && pattern[2] === "?" && typeof pattern[3] === "string" && /^[a-z]:$/i.test(pattern[3]);\n const fdi = fileUNC ? 3 : fileDrive ? 0 : void 0;\n const pdi = patternUNC ? 3 : patternDrive ? 0 : void 0;\n if (typeof fdi === "number" && typeof pdi === "number") {\n const [fd, pd] = [\n file[fdi],\n pattern[pdi]\n ];\n if (fd.toLowerCase() === pd.toLowerCase()) {\n pattern[pdi] = fd;\n patternStartIndex = pdi;\n fileStartIndex = fdi;\n }\n }\n }\n const { optimizationLevel = 1 } = this.options;\n if (optimizationLevel >= 2) {\n file = this.levelTwoFileOptimize(file);\n }\n if (pattern.includes(GLOBSTAR)) {\n return this.#matchGlobstar(file, pattern, partial, fileStartIndex, patternStartIndex);\n }\n return this.#matchOne(file, pattern, partial, fileStartIndex, patternStartIndex);\n }\n #matchGlobstar(file, pattern, partial, fileIndex, patternIndex) {\n const firstgs = pattern.indexOf(GLOBSTAR, patternIndex);\n const lastgs = pattern.lastIndexOf(GLOBSTAR);\n const [head, body, tail] = partial ? [\n pattern.slice(patternIndex, firstgs),\n pattern.slice(firstgs + 1),\n []\n ] : [\n pattern.slice(patternIndex, firstgs),\n pattern.slice(firstgs + 1, lastgs),\n pattern.slice(lastgs + 1)\n ];\n if (head.length) {\n const fileHead = file.slice(fileIndex, fileIndex + head.length);\n if (!this.#matchOne(fileHead, head, partial, 0, 0)) {\n return false;\n }\n fileIndex += head.length;\n patternIndex += head.length;\n }\n let fileTailMatch = 0;\n if (tail.length) {\n if (tail.length + fileIndex > file.length)\n return false;\n let tailStart = file.length - tail.length;\n if (this.#matchOne(file, tail, partial, tailStart, 0)) {\n fileTailMatch = tail.length;\n } else {\n if (file[file.length - 1] !== "" || fileIndex + tail.length === file.length) {\n return false;\n }\n tailStart--;\n if (!this.#matchOne(file, tail, partial, tailStart, 0)) {\n return false;\n }\n fileTailMatch = tail.length + 1;\n }\n }\n if (!body.length) {\n let sawSome = !!fileTailMatch;\n for (let i2 = fileIndex; i2 < file.length - fileTailMatch; i2++) {\n const f = String(file[i2]);\n sawSome = true;\n if (f === "." || f === ".." || !this.options.dot && f.startsWith(".")) {\n return false;\n }\n }\n return partial || sawSome;\n }\n const bodySegments = [[[], 0]];\n let currentBody = bodySegments[0];\n let nonGsParts = 0;\n const nonGsPartsSums = [0];\n for (const b of body) {\n if (b === GLOBSTAR) {\n nonGsPartsSums.push(nonGsParts);\n currentBody = [[], 0];\n bodySegments.push(currentBody);\n } else {\n currentBody[0].push(b);\n nonGsParts++;\n }\n }\n let i = bodySegments.length - 1;\n const fileLength = file.length - fileTailMatch;\n for (const b of bodySegments) {\n b[1] = fileLength - (nonGsPartsSums[i--] + b[0].length);\n }\n return !!this.#matchGlobStarBodySections(file, bodySegments, fileIndex, 0, partial, 0, !!fileTailMatch);\n }\n // return false for "nope, not matching"\n // return null for "not matching, cannot keep trying"\n #matchGlobStarBodySections(file, bodySegments, fileIndex, bodyIndex, partial, globStarDepth, sawTail) {\n const bs = bodySegments[bodyIndex];\n if (!bs) {\n for (let i = fileIndex; i < file.length; i++) {\n sawTail = true;\n const f = file[i];\n if (f === "." || f === ".." || !this.options.dot && f.startsWith(".")) {\n return false;\n }\n }\n return sawTail;\n }\n const [body, after] = bs;\n while (fileIndex <= after) {\n const m = this.#matchOne(file.slice(0, fileIndex + body.length), body, partial, fileIndex, 0);\n if (m && globStarDepth < this.maxGlobstarRecursion) {\n const sub = this.#matchGlobStarBodySections(file, bodySegments, fileIndex + body.length, bodyIndex + 1, partial, globStarDepth + 1, sawTail);\n if (sub !== false) {\n return sub;\n }\n }\n const f = file[fileIndex];\n if (f === "." || f === ".." || !this.options.dot && f.startsWith(".")) {\n return false;\n }\n fileIndex++;\n }\n return partial || null;\n }\n #matchOne(file, pattern, partial, fileIndex, patternIndex) {\n let fi;\n let pi;\n let pl;\n let fl;\n for (fi = fileIndex, pi = patternIndex, fl = file.length, pl = pattern.length; fi < fl && pi < pl; fi++, pi++) {\n this.debug("matchOne loop");\n let p = pattern[pi];\n let f = file[fi];\n this.debug(pattern, p, f);\n if (p === false || p === GLOBSTAR) {\n return false;\n }\n let hit;\n if (typeof p === "string") {\n hit = f === p;\n this.debug("string match", p, f, hit);\n } else {\n hit = p.test(f);\n this.debug("pattern match", p, f, hit);\n }\n if (!hit)\n return false;\n }\n if (fi === fl && pi === pl) {\n return true;\n } else if (fi === fl) {\n return partial;\n } else if (pi === pl) {\n return fi === fl - 1 && file[fi] === "";\n } else {\n throw new Error("wtf?");\n }\n }\n braceExpand() {\n return braceExpand(this.pattern, this.options);\n }\n parse(pattern) {\n assertValidPattern(pattern);\n const options = this.options;\n if (pattern === "**")\n return GLOBSTAR;\n if (pattern === "")\n return "";\n let m;\n let fastTest = null;\n if (m = pattern.match(starRE)) {\n fastTest = options.dot ? starTestDot : starTest;\n } else if (m = pattern.match(starDotExtRE)) {\n fastTest = (options.nocase ? options.dot ? starDotExtTestNocaseDot : starDotExtTestNocase : options.dot ? starDotExtTestDot : starDotExtTest)(m[1]);\n } else if (m = pattern.match(qmarksRE)) {\n fastTest = (options.nocase ? options.dot ? qmarksTestNocaseDot : qmarksTestNocase : options.dot ? qmarksTestDot : qmarksTest)(m);\n } else if (m = pattern.match(starDotStarRE)) {\n fastTest = options.dot ? starDotStarTestDot : starDotStarTest;\n } else if (m = pattern.match(dotStarRE)) {\n fastTest = dotStarTest;\n }\n const re = AST.fromGlob(pattern, this.options).toMMPattern();\n if (fastTest && typeof re === "object") {\n Reflect.defineProperty(re, "test", { value: fastTest });\n }\n return re;\n }\n makeRe() {\n if (this.regexp || this.regexp === false)\n return this.regexp;\n const set = this.set;\n if (!set.length) {\n this.regexp = false;\n return this.regexp;\n }\n const options = this.options;\n const twoStar = options.noglobstar ? star2 : options.dot ? twoStarDot : twoStarNoDot;\n const flags = new Set(options.nocase ? ["i"] : []);\n let re = set.map((pattern) => {\n const pp = pattern.map((p) => {\n if (p instanceof RegExp) {\n for (const f of p.flags.split(""))\n flags.add(f);\n }\n return typeof p === "string" ? regExpEscape2(p) : p === GLOBSTAR ? GLOBSTAR : p._src;\n });\n pp.forEach((p, i) => {\n const next = pp[i + 1];\n const prev = pp[i - 1];\n if (p !== GLOBSTAR || prev === GLOBSTAR) {\n return;\n }\n if (prev === void 0) {\n if (next !== void 0 && next !== GLOBSTAR) {\n pp[i + 1] = "(?:\\\\/|" + twoStar + "\\\\/)?" + next;\n } else {\n pp[i] = twoStar;\n }\n } else if (next === void 0) {\n pp[i - 1] = prev + "(?:\\\\/|\\\\/" + twoStar + ")?";\n } else if (next !== GLOBSTAR) {\n pp[i - 1] = prev + "(?:\\\\/|\\\\/" + twoStar + "\\\\/)" + next;\n pp[i + 1] = GLOBSTAR;\n }\n });\n const filtered = pp.filter((p) => p !== GLOBSTAR);\n if (this.partial && filtered.length >= 1) {\n const prefixes = [];\n for (let i = 1; i <= filtered.length; i++) {\n prefixes.push(filtered.slice(0, i).join("/"));\n }\n return "(?:" + prefixes.join("|") + ")";\n }\n return filtered.join("/");\n }).join("|");\n const [open, close] = set.length > 1 ? ["(?:", ")"] : ["", ""];\n re = "^" + open + re + close + "$";\n if (this.partial) {\n re = "^(?:\\\\/|" + open + re.slice(1, -1) + close + ")$";\n }\n if (this.negate)\n re = "^(?!" + re + ").+$";\n try {\n this.regexp = new RegExp(re, [...flags].join(""));\n } catch {\n this.regexp = false;\n }\n return this.regexp;\n }\n slashSplit(p) {\n if (this.preserveMultipleSlashes) {\n return p.split("/");\n } else if (this.isWindows && /^\\/\\/[^/]+/.test(p)) {\n return ["", ...p.split(/\\/+/)];\n } else {\n return p.split(/\\/+/);\n }\n }\n match(f, partial = this.partial) {\n this.debug("match", f, this.pattern);\n if (this.comment) {\n return false;\n }\n if (this.empty) {\n return f === "";\n }\n if (f === "/" && partial) {\n return true;\n }\n const options = this.options;\n if (this.isWindows) {\n f = f.split("\\\\").join("/");\n }\n const ff = this.slashSplit(f);\n this.debug(this.pattern, "split", ff);\n const set = this.set;\n this.debug(this.pattern, "set", set);\n let filename = ff[ff.length - 1];\n if (!filename) {\n for (let i = ff.length - 2; !filename && i >= 0; i--) {\n filename = ff[i];\n }\n }\n for (const pattern of set) {\n let file = ff;\n if (options.matchBase && pattern.length === 1) {\n file = [filename];\n }\n const hit = this.matchOne(file, pattern, partial);\n if (hit) {\n if (options.flipNegate) {\n return true;\n }\n return !this.negate;\n }\n }\n if (options.flipNegate) {\n return false;\n }\n return this.negate;\n }\n static defaults(def) {\n return minimatch.defaults(def).Minimatch;\n }\n };\n minimatch.AST = AST;\n minimatch.Minimatch = Minimatch;\n minimatch.escape = escape;\n minimatch.unescape = unescape;\n\n // src/mods.ts\n var webcrypto;\n async function getWebCrypto() {\n if (webcrypto) {\n return webcrypto;\n }\n if (compatGlobal.crypto) {\n webcrypto = compatGlobal.crypto;\n return webcrypto;\n } else {\n const module = await import("crypto");\n webcrypto = module.webcrypto;\n return webcrypto;\n }\n }\n\n // src/common/models/db.const.ts\n var EntryTypes = {\n NOTE_LEGACY: "notes",\n NOTE_BINARY: "newnote",\n NOTE_PLAIN: "plain",\n INTERNAL_FILE: "internalfile",\n CHUNK: "leaf",\n CHUNK_PACK: "chunkpack",\n VERSION_INFO: "versioninfo",\n SYNC_INFO: "syncinfo",\n SYNC_PARAMETERS: "sync-parameters",\n MILESTONE_INFO: "milestoneinfo",\n NODE_INFO: "nodeinfo"\n };\n var NoteTypes = [EntryTypes.NOTE_LEGACY, EntryTypes.NOTE_BINARY, EntryTypes.NOTE_PLAIN];\n var ChunkTypes = [EntryTypes.CHUNK, EntryTypes.CHUNK_PACK];\n\n // src/common/models/setting.const.ts\n var SETTING_VERSION_SUPPORT_CASE_INSENSITIVE = 10;\n var CURRENT_SETTING_VERSION = SETTING_VERSION_SUPPORT_CASE_INSENSITIVE;\n var RemoteTypes = {\n REMOTE_COUCHDB: "",\n REMOTE_MINIO: "MINIO",\n REMOTE_P2P: "ONLY_P2P"\n };\n var REMOTE_COUCHDB = RemoteTypes.REMOTE_COUCHDB;\n var REMOTE_MINIO = RemoteTypes.REMOTE_MINIO;\n var REMOTE_P2P = RemoteTypes.REMOTE_P2P;\n var E2EEAlgorithms = {\n V1: "",\n V2: "v2",\n ForceV1: "forceV1"\n };\n var ChunkAlgorithms = {\n V1: "v1",\n V2: "v2",\n V2Segmenter: "v2-segmenter",\n RabinKarp: "v3-rabin-karp"\n };\n\n // src/common/models/setting.const.preferred.ts\n var PREFERRED_BASE = {\n syncMaxSizeInMB: 50,\n chunkSplitterVersion: "v3-rabin-karp",\n usePluginSyncV2: true,\n handleFilenameCaseSensitive: false,\n E2EEAlgorithm: E2EEAlgorithms.V2\n };\n var PREFERRED_SETTING_CLOUDANT = {\n ...PREFERRED_BASE,\n customChunkSize: 0,\n sendChunksBulkMaxSize: 1,\n concurrencyOfReadChunksOnline: 100,\n minimumIntervalOfReadChunksOnline: 333\n };\n var PREFERRED_SETTING_SELF_HOSTED = {\n ...PREFERRED_BASE,\n customChunkSize: 60,\n sendChunksBulkMaxSize: 1,\n concurrencyOfReadChunksOnline: 30,\n minimumIntervalOfReadChunksOnline: 25\n };\n var PREFERRED_JOURNAL_SYNC = {\n ...PREFERRED_BASE,\n customChunkSize: 10,\n concurrencyOfReadChunksOnline: 30,\n minimumIntervalOfReadChunksOnline: 25\n };\n\n // src/common/models/setting.const.defaults.ts\n var P2P_DEFAULT_SETTINGS = {\n P2P_Enabled: false,\n P2P_AutoAccepting: 0 /* NONE */,\n P2P_AppID: "self-hosted-livesync",\n P2P_roomID: "",\n P2P_passphrase: "",\n P2P_relays: "wss://exp-relay.vrtmrz.net/",\n P2P_AutoBroadcast: false,\n P2P_AutoStart: false,\n P2P_AutoSyncPeers: "",\n P2P_AutoWatchPeers: "",\n P2P_SyncOnReplication: "",\n P2P_RebuildFrom: "",\n P2P_AutoAcceptingPeers: "",\n P2P_AutoDenyingPeers: "",\n P2P_IsHeadless: false,\n P2P_DevicePeerName: "",\n P2P_turnServers: "",\n P2P_turnUsername: "",\n P2P_turnCredential: "",\n P2P_useDiagRTC: false\n };\n var SETTINGS_SCHEMA_DEFAULTS = {\n remoteType: REMOTE_COUCHDB,\n useCustomRequestHandler: false,\n couchDB_URI: "",\n couchDB_USER: "",\n couchDB_PASSWORD: "",\n couchDB_DBNAME: "",\n liveSync: false,\n syncOnSave: false,\n syncOnStart: false,\n savingDelay: 200,\n lessInformationInLog: false,\n gcDelay: 300,\n versionUpFlash: "",\n minimumChunkSize: 20,\n longLineThreshold: 250,\n showVerboseLog: false,\n suspendFileWatching: false,\n trashInsteadDelete: true,\n periodicReplication: false,\n periodicReplicationInterval: 60,\n syncOnFileOpen: false,\n encrypt: false,\n passphrase: "",\n usePathObfuscation: false,\n doNotDeleteFolder: false,\n resolveConflictsByNewerFile: false,\n batchSave: false,\n batchSaveMinimumDelay: 5,\n batchSaveMaximumDelay: 60,\n deviceAndVaultName: "",\n usePluginSettings: false,\n showOwnPlugins: false,\n showStatusOnEditor: true,\n showStatusOnStatusbar: true,\n showOnlyIconsOnEditor: false,\n hideFileWarningNotice: false,\n networkWarningStyle: "",\n usePluginSync: false,\n autoSweepPlugins: false,\n autoSweepPluginsPeriodic: false,\n notifyPluginOrSettingUpdated: false,\n checkIntegrityOnSave: false,\n batch_size: 25,\n batches_limit: 25,\n useHistory: false,\n disableRequestURI: false,\n skipOlderFilesOnSync: true,\n checkConflictOnlyOnOpen: false,\n showMergeDialogOnlyOnActive: false,\n syncInternalFiles: false,\n syncInternalFilesBeforeReplication: false,\n syncInternalFilesIgnorePatterns: "\\\\/node_modules\\\\/, \\\\/\\\\.git\\\\/, \\\\/obsidian-livesync\\\\/",\n syncInternalFilesTargetPatterns: "",\n syncInternalFilesInterval: 60,\n additionalSuffixOfDatabaseName: "",\n ignoreVersionCheck: false,\n lastReadUpdates: 0,\n deleteMetadataOfDeletedFiles: false,\n syncIgnoreRegEx: "",\n syncOnlyRegEx: "",\n customChunkSize: 0,\n readChunksOnline: true,\n watchInternalFileChanges: true,\n automaticallyDeleteMetadataOfDeletedFiles: 0,\n disableMarkdownAutoMerge: false,\n writeDocumentsIfConflicted: false,\n useDynamicIterationCount: false,\n syncAfterMerge: false,\n configPassphraseStore: "",\n encryptedPassphrase: "",\n encryptedCouchDBConnection: "",\n permitEmptyPassphrase: false,\n remoteConfigurations: {},\n activeConfigurationId: "",\n P2P_ActiveRemoteConfigurationId: "",\n useIndexedDBAdapter: false,\n useTimeouts: false,\n writeLogToTheFile: false,\n doNotPaceReplication: false,\n hashCacheMaxCount: 300,\n hashCacheMaxAmount: 50,\n concurrencyOfReadChunksOnline: 40,\n minimumIntervalOfReadChunksOnline: 50,\n hashAlg: "xxhash64",\n suspendParseReplicationResult: false,\n doNotSuspendOnFetching: false,\n useIgnoreFiles: false,\n ignoreFiles: ".gitignore",\n syncOnEditorSave: false,\n keepReplicationActiveInBackground: false,\n pluginSyncExtendedSetting: {},\n syncMaxSizeInMB: 50,\n settingSyncFile: "",\n writeCredentialsForSettingSync: false,\n notifyAllSettingSyncFile: false,\n isConfigured: void 0,\n settingVersion: CURRENT_SETTING_VERSION,\n enableCompression: false,\n accessKey: "",\n bucket: "",\n endpoint: "",\n region: "auto",\n secretKey: "",\n useEden: false,\n maxChunksInEden: 10,\n maxTotalLengthInEden: 1024,\n maxAgeInEden: 10,\n disableCheckingConfigMismatch: false,\n autoAcceptCompatibleTweak: void 0,\n displayLanguage: "",\n /**\n * @deprecated\n */\n enableChunkSplitterV2: false,\n disableWorkerForGeneratingChunks: false,\n processSmallFilesInUIThread: false,\n notifyThresholdOfRemoteStorageSize: -1,\n usePluginSyncV2: false,\n usePluginEtc: false,\n handleFilenameCaseSensitive: void 0,\n doNotUseFixedRevisionForChunks: true,\n showLongerLogInsideEditor: false,\n /** @deprecated Retained for settings and Setup URI compatibility. */\n sendChunksBulk: false,\n sendChunksBulkMaxSize: 1,\n /**\n * @deprecated\n * This setting is no longer used and will be removed in the future.\n */\n useSegmenter: false,\n useAdvancedMode: false,\n usePowerUserMode: false,\n useEdgeCaseMode: false,\n enableDebugTools: false,\n suppressNotifyHiddenFilesChange: false,\n syncMinimumInterval: 2e3,\n ...P2P_DEFAULT_SETTINGS,\n doctorProcessedVersion: "",\n bucketCustomHeaders: "",\n couchDB_CustomHeaders: "",\n useJWT: false,\n jwtAlgorithm: "",\n jwtKey: "",\n jwtKid: "",\n jwtSub: "",\n jwtExpDuration: 5,\n useRequestAPI: false,\n bucketPrefix: "",\n chunkSplitterVersion: ChunkAlgorithms.RabinKarp,\n E2EEAlgorithm: E2EEAlgorithms.V2,\n processSizeMismatchedFiles: false,\n forcePathStyle: true,\n syncInternalFileOverwritePatterns: "",\n useOnlyLocalChunk: false,\n maxMTimeForReflectEvents: 0,\n tweakModified: void 0\n };\n var NEW_VAULT_SETTINGS = {\n ...SETTINGS_SCHEMA_DEFAULTS,\n ...PREFERRED_BASE,\n remoteConfigurations: {},\n pluginSyncExtendedSetting: {}\n };\n var DEFAULT_SETTINGS = SETTINGS_SCHEMA_DEFAULTS;\n\n // src/common/models/sync.definition.ts\n var ProtocolVersions = {\n UNSET: void 0,\n LEGACY: 1,\n ADVANCED_E2EE: 2\n };\n var DOCID_SYNC_PARAMETERS = "_local/obsidian_livesync_sync_parameters";\n var DEFAULT_SYNC_PARAMETERS = {\n _id: DOCID_SYNC_PARAMETERS,\n type: EntryTypes["SYNC_PARAMETERS"],\n protocolVersion: ProtocolVersions.ADVANCED_E2EE,\n pbkdf2salt: ""\n };\n\n // src/common/models/tweak.definition.ts\n var TweakValuesShouldMatchedTemplate = {\n minimumChunkSize: 20,\n longLineThreshold: 250,\n encrypt: false,\n usePathObfuscation: false,\n enableCompression: false,\n useEden: false,\n customChunkSize: 0,\n useDynamicIterationCount: false,\n hashAlg: "xxhash64",\n enableChunkSplitterV2: false,\n maxChunksInEden: 10,\n maxTotalLengthInEden: 1024,\n maxAgeInEden: 10,\n usePluginSyncV2: false,\n handleFilenameCaseSensitive: false,\n useSegmenter: false,\n E2EEAlgorithm: E2EEAlgorithms.V2,\n chunkSplitterVersion: ChunkAlgorithms.RabinKarp\n };\n var TweakValuesRecommendedTemplate = {\n useIgnoreFiles: false,\n useCustomRequestHandler: false,\n batch_size: 25,\n batches_limit: 25,\n // useIndexedDBAdapter: false,\n useTimeouts: false,\n readChunksOnline: true,\n hashCacheMaxCount: 300,\n hashCacheMaxAmount: 50,\n concurrencyOfReadChunksOnline: 40,\n minimumIntervalOfReadChunksOnline: 50,\n ignoreFiles: ".gitignore",\n syncMaxSizeInMB: 50,\n enableChunkSplitterV2: false,\n usePluginSyncV2: true,\n handleFilenameCaseSensitive: false,\n E2EEAlgorithm: E2EEAlgorithms.V2,\n chunkSplitterVersion: ChunkAlgorithms.RabinKarp\n };\n var TweakValuesDefault = {\n usePluginSyncV2: false,\n E2EEAlgorithm: DEFAULT_SETTINGS.E2EEAlgorithm,\n chunkSplitterVersion: DEFAULT_SETTINGS.chunkSplitterVersion,\n tweakModified: DEFAULT_SETTINGS.tweakModified\n };\n var TweakValuesTemplate = {\n ...TweakValuesRecommendedTemplate,\n ...TweakValuesShouldMatchedTemplate,\n tweakModified: 0\n };\n\n // src/common/models/redflag.const.ts\n var FlagFilesOriginal = {\n SUSPEND_ALL: "redflag.md",\n REBUILD_ALL: "redflag2.md",\n FETCH_ALL: "redflag3.md"\n };\n var FlagFilesHumanReadable = {\n REBUILD_ALL: "flag_rebuild.md",\n FETCH_ALL: "flag_fetch.md"\n };\n var FLAGMD_REDFLAG = FlagFilesOriginal.SUSPEND_ALL;\n var FLAGMD_REDFLAG2 = FlagFilesOriginal.REBUILD_ALL;\n var FLAGMD_REDFLAG2_HR = FlagFilesHumanReadable.REBUILD_ALL;\n var FLAGMD_REDFLAG3 = FlagFilesOriginal.FETCH_ALL;\n var FLAGMD_REDFLAG3_HR = FlagFilesHumanReadable.FETCH_ALL;\n\n // src/common/models/shared.definition.ts\n var DatabaseConnectingStatuses = {\n STARTED: "STARTED",\n NOT_CONNECTED: "NOT_CONNECTED",\n PAUSED: "PAUSED",\n CONNECTED: "CONNECTED",\n COMPLETED: "COMPLETED",\n CLOSED: "CLOSED",\n ERRORED: "ERRORED",\n JOURNAL_SEND: "JOURNAL_SEND",\n JOURNAL_RECEIVE: "JOURNAL_RECEIVE"\n };\n var DEFAULT_REPLICATION_STATICS = {\n sent: 0,\n arrived: 0,\n maxPullSeq: 0,\n maxPushSeq: 0,\n lastSyncPullSeq: 0,\n lastSyncPushSeq: 0,\n syncStatus: DatabaseConnectingStatuses.CLOSED\n };\n\n // src/string_and_binary/path.ts\n var _hashString = memorizeFuncWithLRUCache(async (key) => {\n const buff = writeString(key);\n const webcrypto7 = await getWebCrypto();\n let digest = await webcrypto7.subtle.digest("SHA-256", buff);\n const len = key.length;\n for (let i = 0; i < len; i++) {\n digest = await webcrypto7.subtle.digest("SHA-256", buff);\n }\n return uint8ArrayToHexString(new Uint8Array(digest));\n });\n\n // node_modules/octagonal-wheels/dist/promises.js\n function polyfillPromiseWithResolvers() {\n let resolve;\n let reject;\n const promise = new Promise((res, rej) => {\n resolve = res;\n reject = rej;\n });\n return { promise, resolve, reject };\n }\n function nativePromiseWithResolvers() {\n const p = Promise.withResolvers();\n const { promise, resolve, reject } = p;\n return { promise, resolve, reject };\n }\n var polyfilledFunc = "withResolvers" in Promise ? nativePromiseWithResolvers : polyfillPromiseWithResolvers;\n var promiseWithResolvers = polyfilledFunc;\n var noop = () => {\n };\n function fireAndForget(p) {\n if (typeof p == "function")\n return fireAndForget(p());\n p.then(noop).catch(noop);\n }\n function yieldMicrotask() {\n return new Promise((res) => queueMicrotask(res));\n }\n var TIMED_OUT_SIGNAL = /* @__PURE__ */ Symbol("timed out");\n function cancelableDelay(timeout, cancel = TIMED_OUT_SIGNAL) {\n let timer = void 0;\n const promise = promiseWithResolvers();\n timer = setTimeout(() => {\n timer = void 0;\n promise.resolve(cancel);\n }, timeout);\n return {\n promise: promise.promise,\n cancel() {\n if (timer) {\n clearTimeout(timer);\n timer = void 0;\n }\n }\n };\n }\n\n // node_modules/octagonal-wheels/dist/concurrency/semaphore_v2.js\n function Semaphore(limit) {\n let counter = 0;\n const _limit = limit;\n const queue = [];\n const semaphore = {\n get waiting() {\n return queue.length;\n },\n async tryAcquire(quantity = 1, timeout) {\n if (counter < _limit) {\n counter += quantity;\n return () => {\n this.release(quantity);\n };\n }\n const d = cancelableDelay(timeout, TIMED_OUT_SIGNAL);\n const aq = this.acquire(quantity);\n const p = await Promise.race([d.promise, aq]);\n if (p === TIMED_OUT_SIGNAL) {\n fireAndForget(() => aq.then((release) => release()));\n return false;\n }\n return p;\n },\n async acquire(quantity = 1) {\n if (counter < _limit) {\n counter += quantity;\n return () => this.release();\n }\n const n = promiseWithResolvers();\n queue.push(n);\n await n.promise;\n return () => {\n this.release(quantity);\n };\n },\n release(quantity = 1) {\n if (queue.length > 0) {\n const next = queue.shift();\n if (next) {\n fireAndForget(async () => await yieldMicrotask().then(() => next.resolve()));\n }\n } else {\n if (counter > 0) {\n counter -= quantity;\n }\n }\n }\n };\n return semaphore;\n }\n\n // node_modules/octagonal-wheels/dist/encoding/encodeobject.js\n var prefixMapObject = {\n s: {\n 1: "V",\n 2: "W",\n 3: "X",\n 4: "Y",\n 5: "Z"\n },\n o: {\n 1: "v",\n 2: "w",\n 3: "x",\n 4: "y",\n 5: "z"\n }\n };\n var decodePrefixMapObject = Object.fromEntries(Object.entries(prefixMapObject).flatMap(([prefix, map]) => Object.entries(map).map(([len, char]) => [char, { prefix, len: parseInt(len) }])));\n var prefixMapNumber = {\n n: {\n 1: "a",\n 2: "b",\n 3: "c",\n 4: "d",\n 5: "e"\n },\n N: {\n 1: "A",\n 2: "B",\n 3: "C",\n 4: "D",\n 5: "E"\n }\n };\n var decodePrefixMapNumber = Object.fromEntries(Object.entries(prefixMapNumber).flatMap(([prefix, map]) => Object.entries(map).map(([len, char]) => [char, { prefix, len: parseInt(len) }])));\n\n // node_modules/octagonal-wheels/dist/bureau/SlipBoard.js\n var SlipBoard = class {\n constructor() {\n Object.defineProperty(this, "_clip", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: /* @__PURE__ */ new Map()\n });\n }\n /**\n * Checks if a specific key is awaiting.\n *\n * @template ET - The type of the events.\n * @template K - The key of the event in the events type.\n * @param {SlipType<ET, K>} type - The key representing the event type.\n * @param {string} key - The key representing the specific sub-event.\n * @returns {boolean} - Returns `true` if the event and sub-event combination is awaiting, otherwise `false`.\n */\n isAwaiting(type, key) {\n return this._clip.has(`${String(type)}:${key}`);\n }\n /**\n * Issues a slip of process and proceeds with the provided options.\n *\n * @template T - The type of the result expected from the process.\n * @param {string} type - The type of the process to be issued.\n * @param {string} [key=""] - An optional key to identify the process.\n * @param {SlipProcessOptions<T>} opt - The options for the process, including the callback to be executed.\n * @returns {Promise<T>} - A promise that resolves with the result of the process.\n *\n * @remarks\n * - If the process is not already awaiting, it will be issued and the callback will be executed.\n * - If the callback succeeds, the result will be submitted.\n * - If the callback fails, the error handling depends on the options provided:\n * - If `submitAsSuccess` is true, the error (or transformed error) will be submitted as a success.\n * - If `dropSlipWithRisks` is true, the process will be deleted from the clip.\n * - Otherwise, the error will be rejected.\n * - The method returns a promise that resolves with the next result of the process.\n */\n issueAndProceed(type, key = "", opt) {\n if (!this.isAwaiting(type, key)) {\n fireAndForget(async () => {\n try {\n const ret = await opt.callback();\n this.submit(type, key, ret);\n } catch (ex) {\n if (opt.submitAsSuccess) {\n this.submit(type, key, opt.transformError ? opt.transformError(ex) : ex);\n } else {\n if (opt.dropSlipWithRisks) {\n this._clip.delete(type);\n } else {\n this.reject(type, key, ex);\n }\n }\n }\n });\n }\n return this.awaitNext(type, key);\n }\n /**\n * Waits for the next event of the specified type and key, with an optional timeout.\n *\n * @template ET - The type of the events.\n * @template K - The key of the event type.\n * @param {SlipType<ET, K>} type - The type of the event to wait for.\n * @param {string} [key=""] - The key associated with the event.\n * @param {number} [timeout] - The optional timeout in milliseconds.\n * @returns {Promise<void | ET[K] | TIMED_OUT_SIGNAL>} A promise that resolves with the event data,\n * resolves with `TIMED_OUT_SIGNAL` if the timeout is reached, or resolves to void if no event is found.\n */\n async awaitNext(type, key = "", { timeout, onNotAwaited } = { timeout: void 0, onNotAwaited: void 0 }) {\n let taskPromise = this._clip.get(`${String(type)}:${key}`);\n if (!taskPromise) {\n taskPromise = promiseWithResolvers();\n taskPromise.promise = taskPromise.promise.then((ret) => {\n return ret;\n }).finally(() => {\n this._clip.delete(`${String(type)}:${key}`);\n });\n this._clip.set(`${String(type)}:${key}`, taskPromise);\n if (onNotAwaited) {\n fireAndForget(async () => (await yieldMicrotask(), onNotAwaited()));\n }\n }\n if (timeout) {\n const cDelay = cancelableDelay(timeout);\n return Promise.race([\n cDelay.promise,\n taskPromise.promise.then((ret) => ret).finally(() => cDelay.cancel())\n ]);\n }\n return await taskPromise.promise;\n }\n /**\n * Submits an event of a specified type with optional data.\n *\n * @template ET - The type of events.\n * @template K - The key of the event type in ET.\n * @param {SlipType<ET, K>} type - The type of the event to submit.\n * @param {string} [key=""] - An optional key associated with the event.\n * @param {SlipDataType<ET, K>} [data] - Optional data to be passed with the event.\n * @returns {void}\n */\n submit(type, key, data) {\n const taskPromise = this._clip.get(`${String(type)}:${key}`);\n if (taskPromise) {\n taskPromise.resolve(data);\n }\n }\n /**\n * Submits an event of a specified type to all listeners.\n *\n * @template ET - The type of events.\n * @template K - The key of the event type in ET.\n * @param {SlipType<ET, K>} type - The type of the event to submit.\n * @param {string} prefix - The prefix to match the keys of the listeners.\n * @param {SlipDataType<ET, K>} [data] - Optional data to be passed with the event.\n * @returns {void}\n */\n submitToAll(type, prefix, data) {\n for (const [key, taskPromise] of this._clip.entries()) {\n if (`${String(key)}`.startsWith(`${String(type)}:${prefix}`)) {\n taskPromise.resolve(data);\n }\n }\n }\n /**\n * Rejects a task promise associated with a specific event type and key.\n *\n * @template ET - The type of events.\n * @template K - The keys of the events.\n * @param {SlipType<ET, K>} type - The type of the event.\n * @param {string} [key=""] - The key associated with the event. Defaults to an empty string.\n * @param {any} reason - The reason for rejecting the promise.\n */\n reject(type, key = "", reason) {\n const taskPromise = this._clip.get(`${String(type)}:${key}`);\n if (taskPromise) {\n taskPromise.reject(reason);\n }\n }\n };\n var globalSlipBoard = new SlipBoard();\n\n // src/common/utils.patch.ts\n var MARK_OPERATOR = ``;\n var MARK_DELETED = `${MARK_OPERATOR}__DELETED`;\n var MARK_ISARRAY = `${MARK_OPERATOR}__ARRAY`;\n var MARK_SWAPPED = `${MARK_OPERATOR}__SWAP`;\n\n // src/common/utils.ts\n var isIndexDBCmpExist = typeof compatGlobal?.indexedDB?.cmp !== "undefined";\n function memorizeFuncWithLRUCache(func) {\n const cache = new LRUCache(100, 1e5, true);\n return (key) => {\n const isExists = cache.has(key);\n if (isExists) return cache.get(key);\n const value = func(key);\n cache.set(key, value);\n return value;\n };\n }\n var globalConcurrencyController = Semaphore(50);\n function wrapByDefault(func, onError) {\n try {\n return func();\n } catch (ex) {\n const error = ex instanceof Error ? ex : new Error(String(ex));\n return onError(error);\n }\n }\n\n // src/string_and_binary/chunks.ts\n function isTextBlob(blob) {\n return blob.type === "text/plain";\n }\n function* pickPiece(leftData, minimumChunkSize) {\n let buffer = "";\n L1: do {\n const curLine = leftData.shift();\n if (typeof curLine === "undefined") {\n yield buffer;\n break L1;\n }\n if (curLine.startsWith("```") || curLine.startsWith(" ```") || curLine.startsWith(" ```") || curLine.startsWith(" ```")) {\n yield buffer;\n buffer = curLine + (leftData.length != 0 ? "\\n" : "");\n L2: do {\n const curPx = leftData.shift();\n if (typeof curPx === "undefined") {\n break L2;\n }\n buffer += curPx + (leftData.length != 0 ? "\\n" : "");\n } while (leftData.length > 0 && !(leftData[0].startsWith("```") || leftData[0].startsWith(" ```") || leftData[0].startsWith(" ```") || leftData[0].startsWith(" ```")));\n const isLooksLikeBASE64 = buffer.endsWith("=");\n const maybeUneditable = buffer.length > 2048;\n const endOfCodeBlock = leftData.shift();\n if (typeof endOfCodeBlock !== "undefined") {\n buffer += endOfCodeBlock;\n buffer += leftData.length != 0 ? "\\n" : "";\n }\n if (!isLooksLikeBASE64 && !maybeUneditable) {\n const splitExpr = /(.*?[;,:<])/g;\n const sx = buffer.split(splitExpr).filter((e) => e != "");\n for (const v of sx) {\n yield v;\n }\n } else {\n yield buffer;\n }\n buffer = "";\n } else {\n buffer += curLine + (leftData.length != 0 ? "\\n" : "");\n if (buffer.length >= minimumChunkSize || leftData.length == 0 || leftData[0] == "#" || buffer[0] == "#") {\n yield buffer;\n buffer = "";\n }\n }\n } while (leftData.length > 0);\n }\n var charNewLine = "\\n".charCodeAt(0);\n var segmenter = "Segmenter" in Intl ? wrapByDefault(\n // @ts-ignore We have checked Intl existence above.\n // eslint-disable-next-line @typescript-eslint/no-unsafe-call, @typescript-eslint/no-unsafe-return\n () => new Intl.Segmenter(compatGlobal.navigator.language, { granularity: "sentence" }),\n (err) => {\n Logger(`Failed to create Intl.Segmenter: ${err.message}`, LOG_LEVEL_VERBOSE);\n return void 0;\n }\n ) : void 0;\n function* splitStringWithinLength(text, pieceSize) {\n let leftData = text;\n do {\n const splitSize = pieceSize;\n const piece = leftData.substring(0, splitSize);\n leftData = leftData.substring(splitSize);\n yield piece;\n } while (leftData != "");\n }\n function* splitTextInSegment(text, pieceSize, minimumChunkSize) {\n const segments = segmenter.segment(text);\n let prev = "";\n let buf = "";\n for (const seg of segments) {\n const buffer = seg.segment;\n if (prev == buffer || buf.length < minimumChunkSize) {\n buf += buffer;\n prev = buffer;\n } else {\n prev = buffer;\n if (buf.length > 0) {\n yield* splitStringWithinLength(buf, pieceSize);\n }\n buf = buffer;\n }\n }\n if (buf.length > 0) {\n yield* splitStringWithinLength(buf, pieceSize);\n }\n }\n function* splitInNewLine(texts) {\n for (const text of texts) {\n let start = -1;\n let end = -1;\n do {\n end = text.indexOf("\\n", start);\n if (end == -1) {\n yield text.substring(start);\n break;\n }\n while (text[end] == "\\n") {\n end++;\n }\n yield text.substring(start, end);\n start = end;\n } while (end != -1);\n }\n return;\n }\n function splitPiecesTextV2(dataSrc, pieceSize, minimumChunkSize) {\n const dataListAllArray = typeof dataSrc == "string" ? [dataSrc] : dataSrc;\n const dataListAll = splitInNewLine(dataListAllArray);\n let inCodeBlock = 0;\n let flush = false;\n let flushBefore = false;\n return function* () {\n const buf = [];\n for (const line of dataListAll) {\n if (line.startsWith("````")) {\n if (inCodeBlock == 0) {\n inCodeBlock = 4;\n flushBefore = true;\n } else if (inCodeBlock == 4) {\n inCodeBlock = 0;\n flush = true;\n }\n } else if (line.startsWith("```")) {\n if (inCodeBlock == 0) {\n inCodeBlock = 3;\n flushBefore = true;\n } else if (inCodeBlock == 3) {\n inCodeBlock = 0;\n flush = true;\n }\n }\n if (flushBefore) {\n if (buf.length > 0) {\n yield* splitTextInSegment(buf.join(""), pieceSize, minimumChunkSize);\n buf.length = 0;\n }\n flushBefore = false;\n }\n buf.push(line);\n if (flush) {\n if (buf.length > 0) {\n yield* splitStringWithinLength(buf.join(""), pieceSize);\n buf.length = 0;\n }\n flush = false;\n }\n }\n if (buf.length > 0) {\n if (inCodeBlock == 0) {\n yield* splitTextInSegment(buf.join(""), pieceSize, minimumChunkSize);\n } else {\n yield* splitStringWithinLength(buf.join(""), pieceSize);\n }\n }\n };\n }\n function binaryTextSplit(data, pieceSize, minimumChunkSize) {\n return function* pieces() {\n yield* splitStringWithinLength(data, pieceSize);\n };\n }\n function splitPiecesText(dataSrc, pieceSize, plainSplit, minimumChunkSize, useSegmenter) {\n if (!useSegmenter || !segmenter) {\n return splitPiecesTextV1(dataSrc, pieceSize, plainSplit, minimumChunkSize);\n }\n if (!plainSplit) {\n return binaryTextSplit(dataSrc, pieceSize, minimumChunkSize);\n }\n return splitPiecesTextV2(dataSrc, pieceSize, minimumChunkSize);\n }\n function splitPiecesTextV1(dataSrc, pieceSize, plainSplit, minimumChunkSize) {\n const dataList = typeof dataSrc == "string" ? [dataSrc] : dataSrc;\n return function* pieces() {\n for (const data of dataList) {\n if (plainSplit) {\n const leftData = data.split("\\n");\n const f = pickPiece(leftData, minimumChunkSize);\n for (const piece of f) {\n let buffer = piece;\n do {\n let ps = pieceSize;\n if (buffer.charCodeAt(ps - 1) != buffer.codePointAt(ps - 1)) {\n ps++;\n }\n yield buffer.substring(0, ps);\n buffer = buffer.substring(ps);\n } while (buffer != "");\n }\n } else {\n let leftData = data;\n do {\n const splitSize = pieceSize;\n const piece = leftData.substring(0, splitSize);\n leftData = leftData.substring(splitSize);\n yield piece;\n } while (leftData != "");\n }\n }\n };\n }\n function* splitByDelimiterWithMinLength(sources, delimiter, minimumChunkLength = 25, splitThreshold) {\n let buf = "";\n let last = false;\n const dl = delimiter.length;\n for (const source of sources) {\n const max = source.length;\n if (splitThreshold && max > splitThreshold) {\n yield buf + source;\n last = false;\n buf = "";\n continue;\n }\n let i = -1;\n let prev = 0;\n L1: do {\n i = source.indexOf(delimiter, prev);\n if (i == -1) break L1;\n buf += source.slice(prev, i) + delimiter;\n if (buf.length > minimumChunkLength) {\n yield buf;\n buf = "";\n last = false;\n } else {\n last = true;\n }\n prev = i + dl;\n } while (i < max);\n if (prev != i || prev == -1 && i == -1) {\n buf += source.slice(prev);\n last = true;\n }\n }\n if (last) {\n yield buf;\n }\n }\n function* chunkStringGenerator(source, maxLength) {\n const strLen = source.length;\n if (strLen > maxLength) {\n let from = 0;\n do {\n let end = from + maxLength;\n if (end > strLen) {\n yield source.substring(from);\n break;\n }\n while (source.charCodeAt(end - 1) != source.codePointAt(end - 1)) {\n end++;\n }\n yield source.substring(from, end);\n from = end;\n } while (from < strLen);\n } else {\n yield source;\n }\n }\n function* chunkStringGeneratorFromGenerator(sources, maxLength) {\n for (const source of sources) {\n yield* chunkStringGenerator(source, maxLength);\n }\n }\n function* stringGenerator(sources) {\n for (const str of sources) {\n yield str;\n }\n }\n var MAX_ITEMS = 100;\n async function splitPieces2V2(dataSrc, pieceSize, plainSplit, minimumChunkSize, filename, useSegmenter) {\n if (dataSrc.size == 0) {\n return function* noItems() {\n return;\n };\n }\n if (isTextBlob(dataSrc)) {\n const text = await dataSrc.text();\n if (!plainSplit) {\n const gen2 = chunkStringGenerator(text, pieceSize);\n return function* pieces() {\n yield* gen2;\n };\n }\n const textLen = text.length;\n let xMinimumChunkSize = minimumChunkSize;\n while (textLen / xMinimumChunkSize > MAX_ITEMS) {\n xMinimumChunkSize += minimumChunkSize;\n }\n const org = stringGenerator([text]);\n const gen1 = splitByDelimiterWithMinLength(org, "\\n", xMinimumChunkSize);\n const gen = chunkStringGeneratorFromGenerator(gen1, pieceSize);\n return function* pieces() {\n yield* gen;\n };\n }\n let canBeSmall = false;\n let delimiter = 0;\n if (filename && filename.endsWith(".pdf")) {\n delimiter = "/".charCodeAt(0);\n } else if (filename && filename.endsWith(".json")) {\n canBeSmall = true;\n delimiter = ",".charCodeAt(0);\n }\n const clampMin = canBeSmall ? 100 : 1e5;\n const clampMax = 1e8;\n const clampedSize = Math.max(clampMin, Math.min(clampMax, dataSrc.size));\n let step = 1;\n let w = clampedSize;\n while (w > 10) {\n w /= 12.5;\n step++;\n }\n minimumChunkSize = Math.floor(10 ** (step - 1));\n return async function* piecesBlob() {\n const size = dataSrc.size;\n let i = 0;\n const buf = new Uint8Array(await dataSrc.arrayBuffer());\n do {\n const findStart = i + minimumChunkSize;\n const defaultSplitEnd = i + pieceSize;\n let splitEnd;\n let i1 = buf.indexOf(delimiter, findStart);\n if (i1 == -1) {\n i1 = buf.indexOf(charNewLine, findStart);\n }\n if (i1 == -1) {\n splitEnd = defaultSplitEnd;\n } else {\n splitEnd = i1 < defaultSplitEnd ? i1 : defaultSplitEnd;\n }\n yield await arrayBufferToBase64Single2(buf.slice(i, splitEnd));\n i = splitEnd;\n } while (i < size);\n };\n }\n async function splitPieces2(dataSrc, pieceSize, plainSplit, minimumChunkSize, filename, useSegmenter) {\n if (isTextBlob(dataSrc)) {\n return splitPiecesText(await dataSrc.text(), pieceSize, plainSplit, minimumChunkSize, useSegmenter ?? false);\n }\n let delimiter = 0;\n let canBeSmall = false;\n if (filename && filename.endsWith(".pdf")) {\n delimiter = "/".charCodeAt(0);\n } else if (filename && filename.endsWith(".json")) {\n canBeSmall = true;\n delimiter = ",".charCodeAt(0);\n }\n const clampMin = canBeSmall ? 100 : 1e5;\n const clampMax = 1e8;\n const clampedSize = Math.max(clampMin, Math.min(clampMax, dataSrc.size));\n let step = 1;\n let w = clampedSize;\n while (w > 10) {\n w /= 12.5;\n step++;\n }\n minimumChunkSize = Math.floor(10 ** (step - 1));\n return async function* piecesBlob() {\n const size = dataSrc.size;\n let i = 0;\n do {\n let splitSize = pieceSize;\n const currentData = new Uint8Array(await dataSrc.slice(i, i + pieceSize).arrayBuffer());\n let nextIdx = currentData.indexOf(delimiter, minimumChunkSize);\n splitSize = nextIdx == -1 ? pieceSize : Math.min(pieceSize, nextIdx);\n if (nextIdx == -1) nextIdx = currentData.indexOf(charNewLine, minimumChunkSize);\n const piece = currentData.slice(0, splitSize);\n i += piece.length;\n const b64 = await arrayBufferToBase64Single2(piece);\n yield b64;\n } while (i < size);\n };\n }\n async function splitPiecesRabinKarp(dataSrc, absoluteMaxPieceSize, doPlainSplit, minimumChunkSize, _filename, _useSegmenter) {\n let plainSplit = doPlainSplit || isTextBlob(dataSrc);\n const dataSize = dataSrc.size;\n let chunkUnitPlain = 64;\n const MAX_CHUNK_COUNT = 500;\n if (plainSplit) {\n const isDataSizeTooLargeForPlainSplit = dataSize >= 4 * 1024 * 1024;\n if (isDataSizeTooLargeForPlainSplit) {\n plainSplit = false;\n } else {\n let estimatedChunkCount;\n do {\n estimatedChunkCount = dataSize / (chunkUnitPlain * 4);\n if (estimatedChunkCount > MAX_CHUNK_COUNT) {\n chunkUnitPlain += 32;\n }\n } while (estimatedChunkCount > MAX_CHUNK_COUNT);\n }\n }\n const chunkUnitBinary = 256 * 1024;\n const fixedAvgChunkSize = plainSplit ? chunkUnitPlain * 4 : chunkUnitBinary * 4;\n const fixedMaxChunkSize = plainSplit ? chunkUnitPlain * 16 : chunkUnitBinary * 16;\n const fixedMinChunkSize = plainSplit ? chunkUnitPlain * 2 : chunkUnitBinary;\n const rkAbsoluteMaxPieceSizeFloor = 30 * 1024;\n const effectiveAbsoluteMaxPieceSize = Math.max(absoluteMaxPieceSize, rkAbsoluteMaxPieceSizeFloor);\n const maxChunkSize = Math.min(fixedMaxChunkSize, effectiveAbsoluteMaxPieceSize);\n const minChunkSize = Math.min(Math.max(fixedMinChunkSize, minimumChunkSize), maxChunkSize);\n const avgChunkSize = Math.min(Math.max(fixedAvgChunkSize, minChunkSize), maxChunkSize);\n const windowSize = 48;\n const hashModulus = avgChunkSize;\n const boundaryPattern = 1;\n const PRIME = 31;\n let P_pow_w = 1;\n for (let i = 0; i < windowSize - 1; i++) {\n P_pow_w = Math.imul(P_pow_w, PRIME);\n }\n const buffer = new Uint8Array(await dataSrc.arrayBuffer());\n let pos = 0;\n let hash = 0;\n let start = 0;\n const isText = isTextBlob(dataSrc);\n const length = buffer.length;\n return async function* piecesBlob() {\n while (pos < length) {\n const byte = buffer[pos];\n if (pos >= start + windowSize) {\n const oldByte = buffer[pos - windowSize];\n const oldByteTerm = Math.imul(oldByte, P_pow_w);\n hash = hash - oldByteTerm | 0;\n hash = Math.imul(hash, PRIME);\n hash = hash + byte | 0;\n } else {\n hash = Math.imul(hash, PRIME);\n hash = hash + byte | 0;\n }\n const currentChunkSize = pos - start + 1;\n let isBoundaryCandidate = false;\n if (currentChunkSize >= minChunkSize) {\n if ((hash >>> 0) % hashModulus === boundaryPattern) {\n isBoundaryCandidate = true;\n }\n }\n if (currentChunkSize >= maxChunkSize) {\n isBoundaryCandidate = true;\n }\n if (isBoundaryCandidate) {\n let isSafeBoundary = true;\n if (isText) {\n if (pos + 1 < length && (buffer[pos + 1] & 192) === 128) {\n isSafeBoundary = false;\n }\n }\n if (isSafeBoundary) {\n if (isText) {\n yield Promise.resolve(readString(buffer.subarray(start, pos + 1)));\n } else {\n yield await arrayBufferToBase64Single2(buffer.subarray(start, pos + 1));\n }\n start = pos + 1;\n }\n }\n pos++;\n }\n if (start < length) {\n if (isText) {\n yield Promise.resolve(readString(buffer.subarray(start, length)));\n } else {\n yield await arrayBufferToBase64Single2(buffer.subarray(start, length));\n }\n }\n };\n }\n\n // src/worker/bg.common.ts\n function postBack(key, seq, data) {\n self.postMessage({ key, seq, result: data });\n }\n\n // src/worker/universalTypes.ts\n var END_OF_DATA = null;\n\n // src/worker/bg.worker.splitting.ts\n function getMainThreadPostBack(key) {\n const _key = key;\n let seq = 0;\n return function(data) {\n if (data === END_OF_DATA) {\n if (seq === 0) {\n postBack(_key, seq++, "");\n }\n postBack(_key, seq++, END_OF_DATA);\n } else {\n postBack(_key, seq++, data);\n }\n };\n }\n async function processSplit(data) {\n const key = data.key;\n const dataSrc = data.dataSrc;\n const pieceSize = data.pieceSize;\n const plainSplit = data.plainSplit;\n const minimumChunkSize = data.minimumChunkSize;\n const filename = data.filename;\n const useSegmenter = data.useSegmenter;\n const func = data.splitVersion == 3 ? splitPiecesRabinKarp : data.splitVersion == 2 ? splitPieces2V2 : splitPieces2;\n const gen = await func(dataSrc, pieceSize, plainSplit, minimumChunkSize, filename, useSegmenter);\n const emit = getMainThreadPostBack(key);\n for await (const v of gen()) {\n emit(v);\n }\n emit(END_OF_DATA);\n }\n\n // node_modules/octagonal-wheels/dist/encryption/encryptionv3.js\n var webcrypto2 = globalThis.crypto;\n var SALT_STR = "fancySyncForYou!";\n var SALT = new TextEncoder().encode(SALT_STR);\n var _nonceV3 = new Uint32Array(1);\n var bufV3 = new Uint8Array(12);\n async function generateKey(passphrase) {\n const passphraseBin = new TextEncoder().encode(passphrase);\n const digestOfPassphrase = await webcrypto2.subtle.digest("SHA-256", new Uint8Array([...passphraseBin, ...SALT]));\n const salt = digestOfPassphrase.slice(0, 16);\n const baseKey = await webcrypto2.subtle.importKey("raw", passphraseBin, "PBKDF2", false, [\n "deriveBits",\n "deriveKey"\n ]);\n const pbkdf2Params = {\n name: "PBKDF2",\n hash: "SHA-256",\n salt,\n iterations: 1e5\n // Increased iterations for better security\n };\n const derivedKey = await webcrypto2.subtle.deriveKey(pbkdf2Params, baseKey, { name: "AES-GCM", length: 256 }, false, ["decrypt", "encrypt"]);\n return derivedKey;\n }\n var previousDecryptionPassphrase = "";\n var decryptionKey;\n async function decryptV3(encryptedResult, passphrase) {\n if (previousDecryptionPassphrase !== passphrase) {\n const key = await generateKey(passphrase);\n decryptionKey = key;\n previousDecryptionPassphrase = passphrase;\n }\n const ivStr = encryptedResult.substring(2, 26);\n const encryptedData = encryptedResult.substring(26);\n const iv = hexStringToUint8Array(ivStr);\n const encryptedDataArrayBuffer = base64ToArrayBuffer(encryptedData);\n const dataBuffer = await webcrypto2.subtle.decrypt({ name: "AES-GCM", iv }, decryptionKey, encryptedDataArrayBuffer);\n const plain = readString(new Uint8Array(dataBuffer));\n return plain;\n }\n\n // node_modules/octagonal-wheels/dist/memory/memo.js\n var UNDEFINED = /* @__PURE__ */ Symbol("undefined");\n function memoWithMap(bufferLength, fn, keyFunction) {\n if (bufferLength <= 0) {\n throw new Error("Buffer length must be greater than 0");\n }\n const cache = /* @__PURE__ */ new Map();\n const getKey = (args) => {\n return args.length > 0 && typeof args[0] === "string" ? args[0] : JSON.stringify(args, (key, value) => value === void 0 ? UNDEFINED : value);\n };\n return function(...args) {\n const key = keyFunction ? keyFunction(args) : getKey(args);\n if (cache.has(key)) {\n const hitPromise = cache.get(key);\n cache.delete(key);\n cache.set(key, hitPromise);\n return hitPromise;\n }\n const newPromise = fn(...args);\n cache.set(key, newPromise);\n newPromise.catch(() => {\n if (cache.get(key) === newPromise) {\n cache.delete(key);\n }\n });\n if (cache.size > bufferLength) {\n const oldest = cache.keys().next();\n if (!oldest.done)\n cache.delete(oldest.value);\n }\n return newPromise;\n };\n }\n\n // node_modules/octagonal-wheels/dist/encryption/hkdf.js\n var webcrypto3 = globalThis.crypto;\n var IV_LENGTH = 12;\n var PBKDF2_ITERATIONS = 31e4;\n var HKDF_SALT_LENGTH = 32;\n var gcmTagLength = 128;\n var HKDF_ENCRYPTED_PREFIX = "%=";\n var deriveMasterKey = memoWithMap(10, async (passphrase, pbkdf2Salt) => {\n const binaryPassphrase = writeString(passphrase);\n const keyMaterial = await webcrypto3.subtle.importKey("raw", binaryPassphrase, {\n name: "PBKDF2",\n length: 256\n // Length of the key in bits\n }, false, ["deriveKey"]);\n const masterKeyRaw = await webcrypto3.subtle.deriveKey(\n {\n name: "PBKDF2",\n salt: pbkdf2Salt,\n iterations: PBKDF2_ITERATIONS,\n hash: "SHA-256"\n },\n keyMaterial,\n // Output the "raw" key\n { name: "AES-GCM", length: 256 },\n true,\n // extractable\n ["encrypt", "decrypt"]\n // The master key is used for encryption/decryption\n );\n const masterKeyBuffer = await webcrypto3.subtle.exportKey("raw", masterKeyRaw);\n const hkdfKey = await webcrypto3.subtle.importKey("raw", masterKeyBuffer, { name: "HKDF" }, false, [\n "deriveKey"\n ]);\n return hkdfKey;\n }, ([passphrase, salt]) => {\n return `${passphrase}-${uint8ArrayToHexString(salt)}`;\n });\n async function deriveKey(passphrase, pbkdf2Salt, hkdfSalt) {\n const masterKey = await deriveMasterKey(passphrase, pbkdf2Salt);\n const chunkKey = await webcrypto3.subtle.deriveKey(\n {\n name: "HKDF",\n salt: hkdfSalt,\n info: new Uint8Array(),\n // Context info (if needed)\n hash: "SHA-256"\n },\n masterKey,\n // Specify the algorithm and usage for the chunk key\n { name: "AES-GCM", length: 256 },\n false,\n ["encrypt", "decrypt"]\n // The chunk key is used only for encryption/decryption\n );\n return chunkKey;\n }\n async function encryptData(key, iv, data) {\n return await webcrypto3.subtle.encrypt({\n name: "AES-GCM",\n iv,\n tagLength: gcmTagLength\n }, key, data);\n }\n async function _encrypt(input, passphrase, pbkdf2Salt) {\n const hkdfSalt = webcrypto3.getRandomValues(new Uint8Array(HKDF_SALT_LENGTH));\n const key = await deriveKey(passphrase, pbkdf2Salt, hkdfSalt);\n const iv = webcrypto3.getRandomValues(new Uint8Array(IV_LENGTH));\n const encryptedDataArrayBuffer = await encryptData(key, iv, input);\n const encryptedData = new Uint8Array(encryptedDataArrayBuffer);\n return [iv, hkdfSalt, encryptedData];\n }\n async function encryptBinary(input, passphrase, pbkdf2Salt) {\n const [iv, hkdfSalt, encryptedData] = await _encrypt(input, passphrase, pbkdf2Salt);\n const totalLength = iv.length + hkdfSalt.length + encryptedData.length;\n const result = new Uint8Array(totalLength);\n result.set(iv, 0);\n result.set(hkdfSalt, iv.length);\n result.set(encryptedData, iv.length + hkdfSalt.length);\n return result;\n }\n async function encrypt(input, passphrase, pbkdf2Salt) {\n const inputBuffer = writeString(input);\n const encrypted = await encryptBinary(inputBuffer, passphrase, pbkdf2Salt);\n const inBase64 = await arrayBufferToBase64Single(encrypted);\n return `${HKDF_ENCRYPTED_PREFIX}${inBase64}`;\n }\n async function _decrypt(iv, pbkdf2Salt, hkdfSalt, encryptedData, passphrase) {\n const key = await deriveKey(passphrase, pbkdf2Salt, hkdfSalt);\n const decryptedDataArrayBuffer = await webcrypto3.subtle.decrypt({\n name: "AES-GCM",\n iv,\n tagLength: gcmTagLength\n }, key, encryptedData);\n return new Uint8Array(decryptedDataArrayBuffer);\n }\n async function decryptBinary(binary, passphrase, pbkdf2Salt) {\n if (binary.length < IV_LENGTH + HKDF_SALT_LENGTH) {\n throw new Error("Invalid binary data length. Expected at least ivLength + saltLength bytes.");\n }\n const iv = binary.slice(0, IV_LENGTH);\n const hkdfSalt = binary.slice(IV_LENGTH, IV_LENGTH + HKDF_SALT_LENGTH);\n const encryptedData = binary.slice(IV_LENGTH + HKDF_SALT_LENGTH);\n const decryptedData = await _decrypt(iv, pbkdf2Salt, hkdfSalt, encryptedData, passphrase);\n return decryptedData;\n }\n async function decrypt(input, passphrase, pbkdf2Salt) {\n if (!input.startsWith(HKDF_ENCRYPTED_PREFIX)) {\n throw new Error(`Invalid input format. Expected input to start with \'${HKDF_ENCRYPTED_PREFIX}\'.`);\n }\n const headerLength = HKDF_ENCRYPTED_PREFIX.length;\n const encryptedData = base64ToArrayBuffer(input.slice(headerLength));\n const decrypted = await decryptBinary(new Uint8Array(encryptedData), passphrase, pbkdf2Salt);\n return readString(decrypted);\n }\n\n // node_modules/octagonal-wheels/dist/encryption/obfuscatePath.js\n var webcrypto4 = globalThis.crypto;\n\n // node_modules/octagonal-wheels/dist/encryption/encryption.js\n var KeyBuffs = /* @__PURE__ */ new Map();\n var decKeyBuffs = /* @__PURE__ */ new Map();\n var KEY_RECYCLE_COUNT = 100;\n var semiStaticFieldBuffer;\n var nonceBuffer = new Uint32Array(1);\n var webcrypto5 = globalThis.crypto;\n async function getKeyForEncrypt(passphrase, autoCalculateIterations) {\n const buffKey = `${passphrase}-${autoCalculateIterations}`;\n const f = KeyBuffs.get(buffKey);\n if (f) {\n f.count--;\n if (f.count > 0) {\n return [f.key, f.salt];\n }\n f.count--;\n }\n const passphraseLen = 15 - passphrase.length;\n const iteration = autoCalculateIterations ? (passphraseLen > 0 ? passphraseLen : 0) * 1e3 + 121 - passphraseLen : 1e5;\n const passphraseBin = new TextEncoder().encode(passphrase);\n const digest = await webcrypto5.subtle.digest({ name: "SHA-256" }, passphraseBin);\n const keyMaterial = await webcrypto5.subtle.importKey("raw", digest, { name: "PBKDF2" }, false, ["deriveKey"]);\n const salt = webcrypto5.getRandomValues(new Uint8Array(16));\n const key = await webcrypto5.subtle.deriveKey({\n name: "PBKDF2",\n salt,\n iterations: iteration,\n hash: "SHA-256"\n }, keyMaterial, { name: "AES-GCM", length: 256 }, false, ["encrypt"]);\n KeyBuffs.set(buffKey, {\n key,\n salt,\n count: KEY_RECYCLE_COUNT\n });\n return [key, salt];\n }\n var keyGCCount = KEY_RECYCLE_COUNT * 5;\n var decKeyIdx = 0;\n var decKeyMin = 0;\n async function getKeyForDecryption(passphrase, salt, autoCalculateIterations) {\n keyGCCount--;\n if (keyGCCount < 0) {\n keyGCCount = KEY_RECYCLE_COUNT;\n const threshold = (decKeyIdx - decKeyMin) / 2;\n for (const [key2, buff] of decKeyBuffs) {\n if (buff.count < threshold) {\n decKeyBuffs.delete(key2);\n }\n decKeyMin = decKeyIdx;\n }\n }\n decKeyIdx++;\n const bufKey = passphrase + uint8ArrayToHexString(salt) + autoCalculateIterations;\n const f = decKeyBuffs.get(bufKey);\n if (f) {\n f.count = decKeyIdx;\n return [f.key, f.salt];\n }\n const passphraseLen = 15 - passphrase.length;\n const iteration = autoCalculateIterations ? (passphraseLen > 0 ? passphraseLen : 0) * 1e3 + 121 - passphraseLen : 1e5;\n const passphraseBin = new TextEncoder().encode(passphrase);\n const digest = await webcrypto5.subtle.digest({ name: "SHA-256" }, passphraseBin);\n const keyMaterial = await webcrypto5.subtle.importKey("raw", digest, { name: "PBKDF2" }, false, ["deriveKey"]);\n const key = await webcrypto5.subtle.deriveKey({\n name: "PBKDF2",\n salt,\n iterations: iteration,\n hash: "SHA-256"\n }, keyMaterial, { name: "AES-GCM", length: 256 }, false, ["decrypt"]);\n decKeyBuffs.set(bufKey, {\n key,\n salt,\n count: 0\n });\n return [key, salt];\n }\n function getSemiStaticField(reset) {\n if (semiStaticFieldBuffer != null && !reset) {\n return semiStaticFieldBuffer;\n }\n semiStaticFieldBuffer = webcrypto5.getRandomValues(new Uint8Array(12));\n return semiStaticFieldBuffer;\n }\n function getNonce() {\n nonceBuffer[0]++;\n if (nonceBuffer[0] > 1e4) {\n getSemiStaticField(true);\n }\n return nonceBuffer;\n }\n async function encrypt2(input, passphrase, autoCalculateIterations) {\n const [key, salt] = await getKeyForEncrypt(passphrase, autoCalculateIterations);\n const fixedPart = getSemiStaticField();\n const invocationPart = getNonce();\n const iv = new Uint8Array([...fixedPart, ...new Uint8Array(invocationPart.buffer)]);\n const dataBuf = writeString(input);\n const encryptedDataArrayBuffer = await webcrypto5.subtle.encrypt({ name: "AES-GCM", iv }, key, dataBuf);\n const encryptedData2 = "" + await arrayBufferToBase64Single(new Uint8Array(encryptedDataArrayBuffer));\n const ret = `%${uint8ArrayToHexString(iv)}${uint8ArrayToHexString(salt)}${encryptedData2}`;\n return ret;\n }\n async function decryptV2(encryptedResult, passphrase, autoCalculateIterations) {\n try {\n const ivStr = encryptedResult.substring(1, 33);\n const salt = encryptedResult.substring(33, 65);\n const encryptedData = encryptedResult.substring(65);\n const [key] = await getKeyForDecryption(passphrase, hexStringToUint8Array(salt), autoCalculateIterations);\n const iv = hexStringToUint8Array(ivStr);\n const encryptedDataArrayBuffer = decodeBinary(encryptedData);\n const dataBuffer = await webcrypto5.subtle.decrypt({ name: "AES-GCM", iv }, key, encryptedDataArrayBuffer);\n const plain = readString(new Uint8Array(dataBuffer));\n return plain;\n } catch (ex) {\n Logger("Couldn\'t decode! You should wrong the passphrases (V2)", LOG_LEVEL_VERBOSE);\n Logger(ex, LOG_LEVEL_VERBOSE);\n throw ex;\n }\n }\n async function decrypt2(encryptedResult, passphrase, autoCalculateIterations) {\n try {\n if (encryptedResult[0] == "%") {\n if (encryptedResult[1] === "~") {\n return decryptV3(encryptedResult, passphrase);\n }\n return decryptV2(encryptedResult, passphrase, autoCalculateIterations);\n }\n if (!encryptedResult.startsWith("[") || !encryptedResult.endsWith("]")) {\n throw new Error("Encrypted data corrupted!");\n }\n const w = encryptedResult.substring(1, encryptedResult.length - 1).split(",").map((e) => e[0] == \'"\' ? e.substring(1, e.length - 1) : e);\n const [encryptedData, ivString, salt] = w;\n const [key] = await getKeyForDecryption(passphrase, hexStringToUint8Array(salt), autoCalculateIterations);\n const iv = hexStringToUint8Array(ivString);\n const encryptedDataBin = atob(encryptedData);\n const len = encryptedDataBin.length;\n const encryptedDataArrayBuffer = new Uint8Array(len);\n for (let i = len; i >= 0; --i) {\n encryptedDataArrayBuffer[i] = encryptedDataBin.charCodeAt(i);\n }\n const plainStringBuffer = await webcrypto5.subtle.decrypt({ name: "AES-GCM", iv }, key, encryptedDataArrayBuffer);\n const plainStringified = readString(new Uint8Array(plainStringBuffer));\n const plain = JSON.parse(plainStringified);\n return plain;\n } catch (ex) {\n Logger("Couldn\'t decode! You should wrong the passphrases", LOG_LEVEL_VERBOSE);\n Logger(ex, LOG_LEVEL_VERBOSE);\n throw ex;\n }\n }\n\n // node_modules/octagonal-wheels/dist/encryption/openSSLCompat/CBC.js\n var SALT_PREFIX = new Uint8Array([83, 97, 108, 116, 101, 100, 95, 95]);\n\n // node_modules/octagonal-wheels/dist/encryption/asymmetric/common.js\n var webCrypto = globalThis.crypto || window.crypto;\n var DEFAULT_RSA_PUBLIC_EXPONENT = new Uint8Array([1, 0, 1]);\n var HEAD_RSA = new Uint8Array([10, 244, 193]);\n var HEAD_ECDH = new Uint8Array([10, 244, 194]);\n\n // node_modules/octagonal-wheels/dist/encryption/obfuscatePathV2.js\n var webcrypto6 = globalThis.crypto;\n async function _deriveKeyFromPassphrase(passphrase, hkdfSalt) {\n const passphraseBin = writeString(passphrase);\n const keyMaterial = await webcrypto6.subtle.importKey("raw", passphraseBin, { name: "HKDF" }, false, ["deriveKey"]);\n const derivedKey = await webcrypto6.subtle.deriveKey({\n name: "HKDF",\n hash: "SHA-256",\n salt: hkdfSalt,\n info: new Uint8Array([])\n }, keyMaterial, { name: "HMAC", hash: "SHA-256", length: 256 }, false, ["sign"]);\n return derivedKey;\n }\n var deriveKeyFromPassphrase = memoWithMap(10, _deriveKeyFromPassphrase, ([passphrase, hkdfSalt]) => {\n return `${writeString(passphrase)}-${uint8ArrayToHexString(hkdfSalt)}`;\n });\n\n // src/worker/bg.worker.encryption.ts\n async function processEncryption(data) {\n const key = data.key;\n const { type, input, passphrase } = data;\n try {\n if (type == "encrypt") {\n const autoCalculateIterations = data.autoCalculateIterations;\n const result = await encrypt2(input, passphrase, autoCalculateIterations);\n self.postMessage({ key, result });\n } else if (type == "decrypt") {\n const autoCalculateIterations = data.autoCalculateIterations;\n const result = await decrypt2(input, passphrase, autoCalculateIterations);\n self.postMessage({ key, result });\n } else if (type == "encryptHKDF") {\n const pbkdf2Salt = data.pbkdf2Salt;\n const result = await encrypt(input, passphrase, pbkdf2Salt);\n self.postMessage({ key, result });\n } else if (type == "decryptHKDF") {\n const pbkdf2Salt = data.pbkdf2Salt;\n const result = await decrypt(input, passphrase, pbkdf2Salt);\n self.postMessage({ key, result });\n }\n } catch (ex) {\n self.postMessage({ key, error: ex });\n }\n }\n\n // src/worker/bg.worker.ts\n self.onmessage = (e) => {\n const data = e.data.data;\n if (data.type === "split") {\n return processSplit(data);\n } else if (data.type === "encrypt" || data.type === "decrypt") {\n return processEncryption(data);\n } else if (data.type === "encryptHKDF" || data.type === "decryptHKDF") {\n return processEncryption(data);\n } else {\n self.postMessage({ key: data.key, error: new Error("Invalid type") });\n }\n };\n})();\n/*! Bundled license information:\n\noctagonal-wheels/dist/encryption/asymmetric/common.js:\n (* istanbul ignore next -- @preserve *)\n*/\n';
|
|
20
20
|
function createWorker() {
|
|
21
21
|
const blob = new Blob([workerSource], { type: "text/javascript" });
|
|
22
22
|
const url = URL.createObjectURL(blob);
|
|
@@ -76,6 +76,10 @@ path -> { revision, observedStorageMtime? }
|
|
|
76
76
|
|
|
77
77
|
The record is updated only after a successful database-to-storage reflection or storage-to-database write. A plain read does not change provenance. A record remains authoritative when a user edits the displayed file to bytes which happen to equal another branch; content equality must not silently change the branch being extended.
|
|
78
78
|
|
|
79
|
+
User-directed reconciliation may select any exact current live revision, including a conflict leaf rather than the deterministic winner. `dbToStorageWithSpecificRev()` rechecks that the selected revision is still live before reflecting its content. `storeFileToDBWithBaseRevision()` performs the same live check before storing current storage content as a child of that revision. If the content already matches the selected non-deleted revision, it records that revision directly without creating a child. A host can set `createIfDifferent` to `false` when it intends only to record an exact content match; differing content then fails instead of changing the revision tree. A host may also create a logical deletion on an explicitly selected branch with `deleteRevisionFromDB()` after performing its own current-live-revision check. This leaves storage unchanged and clears device-local provenance only when that record names the deleted revision.
|
|
80
|
+
|
|
81
|
+
A successful non-deleted reconciliation records the exact selected or newly created revision as provenance. Applying a logical deletion removes the storage item and its provenance record. Deletion provenance is not retained indefinitely: an absent storage item and a current logical-deletion winner already agree and need no further reconciliation.
|
|
82
|
+
|
|
79
83
|
Hosts may construct the namespaced store handle during service composition, before its backing database is open. Store operations begin only after the host's storage lifecycle is ready. They fail rather than wait when that lifecycle contract is violated, because an implicit readiness wait could hang after failed initialisation or wait on its own initialisation handler. Database reset is a transient unavailable boundary; the host must avoid file processing during it and reconstruct derived provenance after reopening.
|
|
80
84
|
|
|
81
85
|
When a record is absent, the implementation reconstructs it only if the current storage bytes match exactly one available revision body. No match, or more than one match, leaves the branch identity unknown.
|
package/docs/development.md
CHANGED
|
@@ -57,7 +57,7 @@ The settings lifecycle has an additional focused unit table in `src/common/model
|
|
|
57
57
|
|
|
58
58
|
The multiple-remote profile contract has focused unit coverage in `src/serviceFeatures/remoteConfig.unit.spec.ts`. Extend it whenever profile identity, generated display names, activation, P2P selection, URI serialisation, or legacy migration changes. New hosts should import the reviewed primitives through `/remote-configurations`; `compat/serviceFeatures/remoteConfig` remains the wider migration surface used by existing clients.
|
|
59
59
|
|
|
60
|
-
The revision-tree safety rules are documented in [Conflict resolution and file provenance](conflict-resolution.md). `ConflictManager.unit.spec.ts` owns common-ancestor and conservative merge behaviour, deterministic pair selection for multiple live leaves, and reconstruction from the committed tree between stages. `ServiceDatabaseFileAccessBase.unit.spec.ts` owns all-branch content discovery and exact-revision logical deletion. `ServiceFileHandlerBase.unit.spec.ts` owns the injected provenance policy for edit, deletion, and rename operations. `LiveSyncLocalDB.unit.spec.ts` owns chunk reachability across current winners, shared chunks, live conflicts, available merge ancestry, conflict resolution, and PouchDB replication of collection and recreation. Extend the relevant sides when changing conflict resolution, compaction handling, provenance, chunk collection, or database-to-storage overwrite protection.
|
|
60
|
+
The revision-tree safety rules are documented in [Conflict resolution and file provenance](conflict-resolution.md). `ConflictManager.unit.spec.ts` owns common-ancestor and conservative merge behaviour, deterministic pair selection for multiple live leaves, and reconstruction from the committed tree between stages. `ServiceDatabaseFileAccessBase.unit.spec.ts` owns all-branch content discovery and exact-revision logical deletion. `ServiceFileHandlerBase.unit.spec.ts` owns the injected provenance policy for edit, deletion, and rename operations, together with user-selected reflection, child creation, strict matching, matching-provenance cleanup after exact branch deletion, and stale-revision refusal. `LiveSyncLocalDB.unit.spec.ts` owns chunk reachability across current winners, shared chunks, live conflicts, available merge ancestry, conflict resolution, and PouchDB replication of collection and recreation. Extend the relevant sides when changing conflict resolution, compaction handling, provenance, chunk collection, or database-to-storage overwrite protection.
|
|
61
61
|
|
|
62
62
|
`openSimpleStore()` may create an inert namespace handle during composition, before the backing key-value database has opened. Maintained hosts must complete their sequential settings lifecycle before scans, watchers, or replication invoke the handle. Operations fail on a lifecycle violation rather than waiting for readiness; do not introduce an implicit wait which can hang after failed initialisation or become self-referential from an initialisation handler. Treat database reset as a transient unavailable boundary and reconstruct derived local state after reopening.
|
|
63
63
|
|
package/docs/proven-in-use.md
CHANGED
|
@@ -12,7 +12,7 @@ The plug-in extends the neutral `ServiceContext` with Obsidian-owned capabilitie
|
|
|
12
12
|
|
|
13
13
|
The consumer contract in `test/contracts/serviceContext.ts` checks shared result semantics and exact context identity across the composed services. The real-Obsidian suite documented in `test/e2e-obsidian/README.md` then covers plug-in loading, representative Svelte dialogue mounts, Vault reflection, CouchDB and Object Storage synchronisation, a two-device P2P Setup URI round-trip, two-Vault behaviour, and other Obsidian-owned boundaries.
|
|
14
14
|
|
|
15
|
-
Commonlib's real-PouchDB and injected-boundary unit tests prove that conservative merge uses the nearest revision actually shared by both conflict leaves, multiple remaining leaves are selected in a deterministic order, each completed pair is reconstructed from the committed tree, storage content from a deleted losing branch remains recognisable after resolution, and conflict-time operations retain the exact displayed branch or preserve every branch when that identity cannot be proved. They also verify that a local edit remains a readable sibling branch when the winning body is unavailable but its exact revision and parent metadata remain, that a generation-one revision without a parent is left unresolved, and that a separately confirmed exact deletion of that unreadable live leaf permits a replacement to be stored without reading the missing chunk. Self-hosted LiveSync supplies the host composition
|
|
15
|
+
Commonlib's real-PouchDB and injected-boundary unit tests prove that conservative merge uses the nearest revision actually shared by both conflict leaves, multiple remaining leaves are selected in a deterministic order, each completed pair is reconstructed from the committed tree, storage content from a deleted losing branch remains recognisable after resolution, and conflict-time operations retain the exact displayed branch or preserve every branch when that identity cannot be proved. They also verify that a local edit remains a readable sibling branch when the winning body is unavailable but its exact revision and parent metadata remain, that a generation-one revision without a parent is left unresolved, and that a separately confirmed exact deletion of that unreadable live leaf permits a replacement to be stored without reading the missing chunk. Exact reconciliation tests cover reflecting a selected live leaf, storing Vault content as its child, recording a matching leaf without creating a revision, clearing matching provenance after exact branch deletion, and refusing to record a stale revision or a revision whose content differs. Self-hosted LiveSync supplies the host composition, persistent device-local provenance, and the per-revision repair interface. Its optional two-Vault scopes cover post-resolution propagation and edit, logical deletion, case-only rename, and cross-path rename while conflicts remain active. The conflict-operation scope passes in real Obsidian against the exact locally packed Commonlib artefact, including replicated parent revisions and preservation of the other live branches.
|
|
16
16
|
|
|
17
17
|
Commonlib's chunk-reachability tests use real PouchDB revision trees. They verify that an ordinary superseded revision releases its unique chunks, a chunk shared by current files remains reachable, live conflict branches and their nearest available shared ancestor remain protected, and losing-branch ancestry becomes eligible after resolution. They also replicate a collected chunk deletion to another PouchDB database and verify that writing the same content can recreate and replicate the content-addressed chunk. Self-hosted LiveSync owns the CouchDB-specific Garbage Collection V3 workflow, including device checks, confirmation, deletion, push-only replication, and remote compaction.
|
|
18
18
|
|
package/docs/releasing.md
CHANGED
|
@@ -33,7 +33,7 @@ Before publication, run the downstream workflow against an exact Self-hosted Liv
|
|
|
33
33
|
|
|
34
34
|
Choose the version explicitly. Use a prerelease such as `0.1.0-rc.0` when registry installation must be validated before the first stable version. Package-proof versions are local artefacts and cannot be staged.
|
|
35
35
|
|
|
36
|
-
|
|
36
|
+
Prepare both stable releases and pre-releases on a reviewed pull request based on `main`. A pre-release may be staged from the exact reviewed pull-request branch commit so that the registry artefact can be validated in Self-hosted LiveSync before the Commonlib change is merged. A stable release must be staged only after its exact reviewed release commit is present on `main`.
|
|
37
37
|
|
|
38
38
|
```bash
|
|
39
39
|
npm ci
|
|
@@ -42,7 +42,7 @@ npm run verify:package
|
|
|
42
42
|
npm publish --dry-run .package --tag next --access public
|
|
43
43
|
```
|
|
44
44
|
|
|
45
|
-
Review `package.json`, `package-lock.json`, the generated manifest, the tarball contents, the test results, and the downstream evidence. Commit only the source manifest and lockfile for the version change; `.package`, `.package-consumer`, and `artifacts` are generated and ignored. Push and open a release pull request only after the usual user checkpoint.
|
|
45
|
+
Review `package.json`, `package-lock.json`, the generated manifest, the tarball contents, the test results, and the downstream evidence. Commit only the source manifest and lockfile for the version change; `.package`, `.package-consumer`, and `artifacts` are generated and ignored. Push and open a release pull request only after the usual user checkpoint. Keep a pre-release pull request in draft while its exact registry artefact is validated in Self-hosted LiveSync. Merge and stable publication remain separate later checkpoints.
|
|
46
46
|
|
|
47
47
|
## Historical initial npm bootstrap
|
|
48
48
|
|
|
@@ -58,7 +58,7 @@ npm publish .package --tag next --access public
|
|
|
58
58
|
|
|
59
59
|
Confirm the authenticated npm account, `@vrtmrz` scope ownership, package name, version, tarball checksum, packed contents, source commit, and target tag immediately before publication. Treat bootstrap publication as a separate user-authorised operation. npm may assign `latest` to the first published version even when `next` is requested; leave the immutable version in place and replace `latest` only after a stable release has passed consumer validation.
|
|
60
60
|
|
|
61
|
-
|
|
61
|
+
Bootstrap publication was the one historical exception which used direct `npm publish`. Do not repeat that operation for routine releases. Current pre-releases use protected staged publishing and may select an exact reviewed branch commit; stable releases use an exact `main` commit. If validation fails, leave the published version immutable and prepare a new pre-release version.
|
|
62
62
|
|
|
63
63
|
## Trusted staged publishing
|
|
64
64
|
|
|
@@ -69,12 +69,15 @@ After bootstrap, configure the npm Trusted Publisher for:
|
|
|
69
69
|
- environment: `npm`; and
|
|
70
70
|
- allowed action: staged publishing only.
|
|
71
71
|
|
|
72
|
-
Protect the GitHub `npm` environment with a required reviewer and permit only `main`. The trusted workflow definition always runs from `main
|
|
72
|
+
Protect the GitHub `npm` environment with a required reviewer and permit only `main`. The trusted workflow definition always runs from `main`. A pre-release may package an exact commit from a reviewed draft branch, while a stable release also requires the package source and workflow-triggering commit to be the exact current `main` commit. The workflow confirms that the selected source branch still points to the requested full commit SHA, checks out that SHA, runs `verify:package`, validates the requested version and confirmation text, packs the reviewed output, records its checksum, and passes the same tarball to the protected staging job.
|
|
73
73
|
|
|
74
|
-
|
|
74
|
+
npm's automatic provenance identifies the `main` commit which triggered the trusted workflow. For a pre-release selected from a draft branch, this identifies the trusted workflow source rather than the packaged source commit. Record and verify the separate `source_ref`, exact package SHA, and tarball checksum before approving the staged version. This provenance distinction is accepted for an immutable pre-release used to validate the consumer before merge. A stable release requires the workflow and package source to be the same exact `main` commit.
|
|
75
|
+
|
|
76
|
+
Dispatch a pre-release from its exact reviewed draft branch commit:
|
|
75
77
|
|
|
76
78
|
```bash
|
|
77
79
|
source_ref=separate-setting-lifecycle
|
|
80
|
+
git fetch origin "$source_ref"
|
|
78
81
|
sha=$(git rev-parse "origin/$source_ref")
|
|
79
82
|
gh workflow run publish-npm.yml \
|
|
80
83
|
--ref main \
|
|
@@ -84,6 +87,6 @@ gh workflow run publish-npm.yml \
|
|
|
84
87
|
-f confirmation="stage @vrtmrz/livesync-commonlib@<version> from $sha"
|
|
85
88
|
```
|
|
86
89
|
|
|
87
|
-
For a stable
|
|
90
|
+
For a stable release, use `source_ref=main`. The workflow rejects a stable release selected from another branch, rejects a stable release without its trusted workflow commit, and requires the workflow-triggering SHA to equal the packaged `main` SHA. The workflow dispatch itself uses `--ref main` for every release, so an unmerged branch cannot change the trusted publication job or acquire access to the `npm` environment.
|
|
88
91
|
|
|
89
|
-
The workflow always stages to `next`. Inspect the staged package name, version, access, dist-tag, provenance, checksum, files, source branch, and source commit before approving it through npm. Approval and later promotion to `latest` are separate user-authorised operations. Keep
|
|
92
|
+
The workflow always stages to `next`. Inspect the staged package name, version, access, dist-tag, provenance, checksum, files, selected source branch, and source commit before approving it through npm. Approval and later promotion to `latest` are separate user-authorised operations. Keep the Commonlib and Self-hosted LiveSync consumer pull requests in draft while validating the exact registry pre-release. If validation fails, leave that published version immutable and prepare a new pre-release. After successful consumer validation, merge Commonlib only through its separate maintainer gate. Validate a stable release in Self-hosted LiveSync before promoting it to `latest`.
|
package/package.json
CHANGED