Repository navigation
Expand file tree
/
Copy pathstorage.js
More file actions
2079 lines (2069 loc) · 75.7 KB
/
Copy pathstorage.js
File metadata and controls
2079 lines (2069 loc) · 75.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// ============================================================================
// Generated from src/modules/storage.ts; do not edit by hand.
// Run `node scripts/generate-ts-runtime-modules.mjs` or `npm run build:bg`.
// ============================================================================
const StorageModule = (() => {
const module = { exports: {} };
const exports = module.exports;
"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
// src/modules/storage.ts
var storage_exports = {};
__export(storage_exports, {
BackupsDAO: () => BackupsDAO,
FolderStorage: () => FolderStorage,
LocalWorkspaceBindings: () => LocalWorkspaceBindings,
ScriptStorage: () => ScriptStorage,
ScriptValues: () => ScriptValues,
SettingsManager: () => SettingsManager,
TabStorage: () => TabStorage,
_openTabTrackers: () => _openTabTrackers,
debugLog: () => debugLog,
setScriptChangeListener: () => setScriptChangeListener
});
module.exports = __toCommonJS(storage_exports);
// src/shared/utils.ts
function generateId() {
return "script_" + crypto.randomUUID();
}
// src/config/settings-defaults.json
var settings_defaults_default = {
enabled: true,
showBadge: true,
badgeColor: "#22c55e",
theme: "dark",
layout: "dark",
notifyOnInstall: true,
notifyOnUpdate: true,
notifyOnError: false,
editorTheme: "default",
editorFontSize: 13,
editorTabSize: 2,
editorLineWrapping: false,
editorAutoComplete: true,
editorMatchBrackets: true,
editorAutoCloseBrackets: true,
editorHighlightActiveLine: true,
editorShowInvisibles: false,
editorKeyMap: "default",
autoUpdate: true,
autoUpdateMode: "notify",
updateInterval: 864e5,
lastUpdateCheck: 0,
subscriptionAutoRefresh: true,
subscriptionRefreshInterval: 24,
syncEnabled: false,
syncProvider: "none",
syncInterval: 36e5,
lastSync: 0,
syncHoldExecutionUntilFirstSync: false,
syncCredentialsSessionOnly: false,
syncEncryptionEnabled: false,
syncEncryptionPassphrase: "",
syncEncryptionKdfIterations: 21e4,
syncEncryptionEstablished: false,
gmValueSyncConflictPolicy: "hlc",
webdavUrl: "",
webdavUsername: "",
webdavPassword: "",
googleDriveConnected: false,
googleDriveToken: "",
googleDriveRefreshToken: "",
googleClientId: "",
googleDriveUser: null,
dropboxToken: "",
dropboxRefreshToken: "",
dropboxUser: null,
dropboxClientId: "",
onedriveToken: "",
onedriveRefreshToken: "",
onedriveClientId: "",
onedriveConnected: false,
onedriveUser: null,
s3Endpoint: "",
s3Region: "",
s3Bucket: "",
s3AccessKeyId: "",
s3SecretKey: "",
s3ObjectKey: "",
language: "auto",
debugMode: false,
experimentalESMUserscripts: false,
experimentalBackgroundScripts: false,
findScriptsSources: {
builtin: {
greasyfork: true,
openuserjs: true,
github: true
},
custom: []
},
dashboardVirtualizationThreshold: 500,
injectIntoFrames: true,
xhrTimeout: 3e4,
allowInternalXhr: false,
allowInternalSyncEndpoints: false,
allowHighPrivilegeScriptApis: false,
scopedHostPermissions: false,
onDeviceAiEnabled: false,
modifyCSP: "auto",
statsUrlRetention: "origin",
blacklist: [],
badgeInfo: "running",
badgeErrorStates: true,
autoReload: false,
pageFilterMode: "blacklist",
blacklistedPages: "",
whitelistedPages: "",
deniedHosts: [],
trustedSigningKeys: {},
trashMode: "30"
};
// src/storage/idb.ts
var DB_NAME = "scriptvault";
var DB_VERSION = 3;
var StorageBucketNames = {
scripts: "scriptvault-script-storage",
values: "scriptvault-script-values",
backups: "scriptvault-backup-scheduler"
};
var Stores = {
scripts: "scripts",
values: "values",
stats: "stats",
backups: "backups",
localWorkspaceBindings: "localWorkspaceBindings",
publicationReceipts: "publicationReceipts"
};
var StorePartitions = {
[Stores.scripts]: "scripts",
[Stores.values]: "values",
[Stores.stats]: "scripts",
[Stores.backups]: "backups",
[Stores.localWorkspaceBindings]: "scripts",
[Stores.publicationReceipts]: "backups"
};
var _connections = /* @__PURE__ */ new Map();
var _bucketModeProbe = null;
var _bucketMode = null;
function connectionFor(partition) {
const existing = _connections.get(partition);
if (existing) return existing;
const state = {
db: null,
opening: null,
factory: null,
name: null,
bucketed: false
};
_connections.set(partition, state);
return state;
}
function globalIndexedDBFactory() {
return typeof indexedDB !== "undefined" ? indexedDB : null;
}
function hasStorageBucketsAPI() {
const storageBuckets = typeof navigator !== "undefined" ? navigator.storageBuckets : void 0;
return !!storageBuckets && typeof storageBuckets.open === "function";
}
async function resolveOpenTarget(partition, name) {
const globalFactory = globalIndexedDBFactory();
const storageBuckets = typeof navigator !== "undefined" ? navigator.storageBuckets : void 0;
if (storageBuckets && typeof storageBuckets.open === "function") {
try {
const bucketName = StorageBucketNames[partition];
const bucket = await storageBuckets.open(bucketName);
if (bucket?.indexedDB && typeof bucket.indexedDB.open === "function") {
_bucketMode = true;
return { partition, bucketName, bucketed: true, name, factory: bucket.indexedDB };
}
} catch {
}
}
if (!globalFactory) {
throw new Error("IndexedDB is not available in this context");
}
if (_bucketMode !== true) _bucketMode = false;
return { partition, bucketName: null, bucketed: false, name, factory: globalFactory };
}
async function isStorageBucketPartitioningActive() {
if (!hasStorageBucketsAPI()) {
_bucketMode = false;
return false;
}
if (_bucketMode !== null) return _bucketMode;
if (!_bucketModeProbe) {
_bucketModeProbe = resolveOpenTarget("scripts", DB_NAME).then((target) => target.bucketed).catch(() => false).finally(() => {
_bucketModeProbe = null;
});
}
_bucketMode = await _bucketModeProbe;
return _bucketMode;
}
async function openDB(options = {}) {
const partition = options.partition ?? "scripts";
const state = connectionFor(partition);
const name = options.name ?? DB_NAME;
const version = options.version ?? DB_VERSION;
if (state.db && state.name === name) {
if (state.bucketed) return state.db;
if (state.factory && state.factory === globalIndexedDBFactory()) return state.db;
}
const target = await resolveOpenTarget(partition, name);
if (state.db && (state.factory !== target.factory || state.name !== name || state.bucketed !== target.bucketed)) {
try {
state.db.close();
} catch {
}
state.db = null;
state.factory = null;
state.name = null;
}
if (state.db) return state.db;
if (state.opening) return state.opening;
state.opening = new Promise((resolve, reject) => {
const req = target.factory.open(name, version);
req.onupgradeneeded = (ev) => {
const db = req.result;
const tx = req.transaction;
if (!tx) return;
try {
options.upgrade?.(db, ev.oldVersion, ev.newVersion ?? version, tx, target);
} catch (e) {
try {
tx.abort();
} catch {
}
reject(e);
}
};
req.onsuccess = () => {
const db = req.result;
db.onversionchange = () => {
try {
db.close();
} catch {
}
if (state.db === db) state.db = null;
};
db.onclose = () => {
if (state.db === db) state.db = null;
};
resolve(db);
};
req.onerror = () => reject(req.error ?? new Error("IndexedDB open failed"));
req.onblocked = () => reject(new Error("IndexedDB open blocked by another connection"));
});
try {
state.db = await state.opening;
state.factory = target.factory;
state.name = name;
state.bucketed = target.bucketed;
return state.db;
} finally {
state.opening = null;
}
}
function reqToPromise(req) {
return new Promise((resolve, reject) => {
req.onsuccess = () => resolve(req.result);
req.onerror = () => reject(req.error ?? new Error("IDB request failed"));
});
}
function txComplete(tx) {
return new Promise((resolve, reject) => {
tx.oncomplete = () => resolve();
tx.onerror = () => reject(tx.error ?? new Error("IDB transaction failed"));
tx.onabort = () => reject(tx.error ?? new Error("IDB transaction aborted"));
});
}
function forEachCursor(source, fn, range, direction) {
return new Promise((resolve, reject) => {
const req = source.openCursor(range, direction);
req.onsuccess = () => {
const cursor = req.result;
if (!cursor) {
resolve();
return;
}
try {
const r = fn(cursor.value, cursor.key, cursor.primaryKey);
if (r && typeof r.then === "function") {
r.then(() => cursor.continue(), reject);
} else {
cursor.continue();
}
} catch (e) {
reject(e);
}
};
req.onerror = () => reject(req.error ?? new Error("cursor failed"));
});
}
// src/storage/transaction.ts
async function withTransaction(stores, mode, fn) {
const storeList = Array.isArray(stores) ? stores : [stores];
const partition = sharedPartition(storeList);
if (!partition && await isStorageBucketPartitioningActive()) {
throw new Error("Cannot run one IndexedDB transaction across storage bucket partitions");
}
const db = await openDB({ partition: partition ?? "scripts" });
const tx = db.transaction(stores, mode);
let result;
try {
result = await fn(tx);
} catch (e) {
try {
tx.abort();
} catch {
}
throw e;
}
await txComplete(tx);
return result;
}
function sharedPartition(stores) {
let partition = null;
for (const store of stores) {
const next = StorePartitions[store];
if (!partition) {
partition = next;
continue;
}
if (partition !== next) return null;
}
return partition;
}
// src/storage/script-db.ts
function retainStatsUrl(url, mode) {
if (mode === "none" || typeof url !== "string" || !url) return void 0;
try {
const origin = new URL(url).origin;
return origin === "null" ? void 0 : origin;
} catch (_) {
return void 0;
}
}
function setRecordKey(record, key, value) {
Object.defineProperty(record, String(key), {
value,
enumerable: true,
configurable: true,
writable: true
});
}
var ALL_SCHEMA_STORES = Object.values(Stores);
var PARTITION_SCHEMA_STORES = {
scripts: [Stores.scripts, Stores.stats, Stores.localWorkspaceBindings],
values: [Stores.values],
backups: [Stores.backups, Stores.publicationReceipts]
};
var SCRIPT_CODE_COMPRESSION_THRESHOLD_BYTES = 64 * 1024;
var SCRIPT_CODE_ENCODER = new TextEncoder();
var SCRIPT_CODE_DECODER = new TextDecoder();
var GM_VALUE_SYNC_HLC_STATE_KEY = "gmValueSyncHlcState";
var GM_VALUE_SYNC_CONFLICT_MAX_BYTES = 256 * 1024;
var GM_VALUE_SYNC_CONFLICT_RETENTION_MS = 30 * 24 * 60 * 60 * 1e3;
var _gmValueHlcState = null;
var _gmValueHlcStatePromise = null;
var _gmValueHlcWriteChain = Promise.resolve();
function makeGmValueDeviceId() {
const randomUuid = globalThis.crypto?.randomUUID?.();
if (randomUuid) return randomUuid;
const random = Math.random().toString(36).slice(2);
return `device-${Date.now().toString(36)}-${random}`.slice(0, 128);
}
function normalizeGmValueClockRecord(value) {
if (!value || typeof value !== "object" || Array.isArray(value)) return void 0;
const ts = Number(value.ts);
const counter = Number(value.counter);
const deviceId = typeof value.deviceId === "string" ? value.deviceId.trim() : "";
if (!Number.isFinite(ts) || ts < 0 || !Number.isFinite(counter) || counter < 0 || !deviceId || deviceId.length > 128) {
return void 0;
}
return { ts: Math.floor(ts), counter: Math.floor(counter), deviceId };
}
async function loadGmValueHlcState() {
if (_gmValueHlcState) return { ..._gmValueHlcState };
if (_gmValueHlcStatePromise) return _gmValueHlcStatePromise;
_gmValueHlcStatePromise = (async () => {
let stored;
try {
stored = (await chrome.storage.local.get(GM_VALUE_SYNC_HLC_STATE_KEY))[GM_VALUE_SYNC_HLC_STATE_KEY];
} catch (_) {
stored = void 0;
}
const record = stored && typeof stored === "object" ? stored : {};
const state = {
deviceId: typeof record.deviceId === "string" && record.deviceId.trim() ? record.deviceId.trim().slice(0, 128) : makeGmValueDeviceId(),
lastTs: Number.isFinite(Number(record.lastTs)) && Number(record.lastTs) >= 0 ? Math.floor(Number(record.lastTs)) : 0,
counter: Number.isFinite(Number(record.counter)) && Number(record.counter) >= 0 ? Math.floor(Number(record.counter)) : 0
};
_gmValueHlcState = state;
try {
await chrome.storage.local.set({ [GM_VALUE_SYNC_HLC_STATE_KEY]: state });
} catch (_) {
}
return { ...state };
})();
try {
return await _gmValueHlcStatePromise;
} finally {
_gmValueHlcStatePromise = null;
}
}
function queueGmValueHlcWrite(operation) {
const result = _gmValueHlcWriteChain.then(operation, operation);
_gmValueHlcWriteChain = result.then(() => void 0, () => void 0);
return result;
}
async function nextGmValueClock() {
return queueGmValueHlcWrite(async () => {
const state = await loadGmValueHlcState();
const now = Date.now();
const ts = Math.max(now, state.lastTs);
const counter = ts === state.lastTs ? state.counter + 1 : 0;
const nextState = { ...state, lastTs: ts, counter };
_gmValueHlcState = nextState;
try {
await chrome.storage.local.set({ [GM_VALUE_SYNC_HLC_STATE_KEY]: nextState });
} catch (_) {
}
return { ts, counter, deviceId: state.deviceId };
});
}
async function observeGmValueClocks(clocks) {
const valid = clocks.map(normalizeGmValueClockRecord).filter((clock) => !!clock);
if (valid.length === 0) return;
await queueGmValueHlcWrite(async () => {
const state = await loadGmValueHlcState();
let nextState = { ...state };
for (const clock of valid) {
if (clock.ts > nextState.lastTs) {
nextState.lastTs = clock.ts;
nextState.counter = clock.counter + 1;
} else if (clock.ts === nextState.lastTs) {
nextState.counter = Math.max(nextState.counter, clock.counter + 1);
}
}
_gmValueHlcState = nextState;
try {
await chrome.storage.local.set({ [GM_VALUE_SYNC_HLC_STATE_KEY]: nextState });
} catch (_) {
}
});
}
function targetStores(target) {
return new Set(target.bucketed ? PARTITION_SCHEMA_STORES[target.partition] : ALL_SCHEMA_STORES);
}
function shouldCreateStore(db, stores, store) {
return stores.has(store) && !db.objectStoreNames.contains(store);
}
async function gzipScriptCode(bytes) {
const stream = new globalThis.ReadableStream({
start(controller) {
controller.enqueue(bytes);
controller.close();
}
}).pipeThrough(new globalThis.CompressionStream("gzip"));
return new globalThis.Response(stream).arrayBuffer();
}
async function gunzipScriptCode(data) {
const stream = new globalThis.ReadableStream({
start(controller) {
controller.enqueue(new Uint8Array(data));
controller.close();
}
}).pipeThrough(new globalThis.DecompressionStream("gzip"));
const bytes = await new globalThis.Response(stream).arrayBuffer();
return SCRIPT_CODE_DECODER.decode(bytes);
}
function coerceArrayBuffer(value) {
if (value instanceof ArrayBuffer) return value;
if (value && typeof value === "object" && typeof value.byteLength === "number") {
try {
const source = new Uint8Array(value);
const copy = new Uint8Array(source.byteLength);
copy.set(source);
return copy.buffer;
} catch (_) {
}
}
if (ArrayBuffer.isView(value)) {
const view = value;
const copy = new Uint8Array(view.byteLength);
copy.set(new Uint8Array(view.buffer, view.byteOffset, view.byteLength));
return copy.buffer;
}
return null;
}
async function encodeScriptForStorage(script) {
const row = { ...script };
const code = typeof script.code === "string" ? script.code : "";
const raw = SCRIPT_CODE_ENCODER.encode(code);
delete row.codeCompressed;
delete row.codeGzip;
delete row.codeByteSize;
if (raw.byteLength > SCRIPT_CODE_COMPRESSION_THRESHOLD_BYTES && typeof globalThis.CompressionStream === "function" && typeof globalThis.DecompressionStream === "function" && typeof globalThis.ReadableStream === "function" && typeof globalThis.Response === "function") {
try {
row.codeGzip = await gzipScriptCode(raw);
row.codeCompressed = true;
row.codeByteSize = raw.byteLength;
delete row.code;
return row;
} catch (_) {
}
}
row.code = code;
return row;
}
async function decodeScriptFromStorage(row) {
if (!row) return null;
const script = { ...row };
if (script.codeCompressed) {
const data = coerceArrayBuffer(script.codeGzip);
if (data) {
script.code = await gunzipScriptCode(data);
} else {
script.code = typeof script.code === "string" ? script.code : "";
}
} else {
script.code = typeof script.code === "string" ? script.code : "";
}
delete script.codeCompressed;
delete script.codeGzip;
delete script.codeByteSize;
return script;
}
function upgradeSchema(db, oldVersion, _newVersion, _tx, target) {
const stores = targetStores(target);
if (oldVersion < 1) {
if (shouldCreateStore(db, stores, Stores.scripts)) {
const scripts = db.createObjectStore(Stores.scripts, { keyPath: "id" });
scripts.createIndex("by-enabled", "enabled", { unique: false });
scripts.createIndex("by-position", "position", { unique: false });
scripts.createIndex("by-namespace", "meta.namespace", { unique: false });
}
if (shouldCreateStore(db, stores, Stores.values)) {
const values = db.createObjectStore(Stores.values, {
keyPath: ["scriptId", "key"]
});
values.createIndex("by-script", "scriptId", { unique: false });
}
if (shouldCreateStore(db, stores, Stores.stats)) {
db.createObjectStore(Stores.stats, { keyPath: "scriptId" });
}
if (shouldCreateStore(db, stores, Stores.backups)) {
const backups = db.createObjectStore(Stores.backups, { keyPath: "id" });
backups.createIndex("by-created", "createdAt", { unique: false });
}
}
if (oldVersion < 2 && shouldCreateStore(db, stores, Stores.localWorkspaceBindings)) {
const bindings = db.createObjectStore(Stores.localWorkspaceBindings, { keyPath: "bindingId" });
bindings.createIndex("by-script", "scriptId", { unique: false });
}
if (oldVersion < 3 && shouldCreateStore(db, stores, Stores.publicationReceipts)) {
const receipts = db.createObjectStore(Stores.publicationReceipts, { keyPath: "receiptId" });
receipts.createIndex("by-script", "scriptId", { unique: false });
receipts.createIndex("by-created", "createdAt", { unique: false });
}
if (oldVersion < 3 && db.objectStoreNames.contains(Stores.localWorkspaceBindings)) {
const bindings = _tx.objectStore(Stores.localWorkspaceBindings);
if (!bindings.indexNames.contains("by-project")) bindings.createIndex("by-project", "projectId", { unique: false });
if (!bindings.indexNames.contains("by-relative-path")) bindings.createIndex("by-relative-path", "relativePath", { unique: false });
}
}
async function openScriptDB() {
return openStoragePartitionDB("scripts");
}
async function openStoragePartitionDB(partition) {
return openDB({ name: DB_NAME, version: DB_VERSION, upgrade: upgradeSchema, partition });
}
async function openValuesDB() {
return openStoragePartitionDB("values");
}
async function openBackupsDB() {
return openStoragePartitionDB("backups");
}
var ScriptsDAO = {
async get(id) {
await openScriptDB();
return withTransaction(Stores.scripts, "readonly", async (tx) => {
const row = await reqToPromise(tx.objectStore(Stores.scripts).get(id));
return decodeScriptFromStorage(row);
});
},
async getAll() {
await openScriptDB();
return withTransaction(Stores.scripts, "readonly", async (tx) => {
const rows = await reqToPromise(tx.objectStore(Stores.scripts).getAll());
return Promise.all((rows ?? []).map((row) => decodeScriptFromStorage(row)));
});
},
async put(script) {
await openScriptDB();
const row = await encodeScriptForStorage(script);
await withTransaction(Stores.scripts, "readwrite", async (tx) => {
await reqToPromise(tx.objectStore(Stores.scripts).put(row));
});
},
/**
* Restore a script with an atomic collision check in the scripts store.
* Returning the current raw row keeps the check inside the transaction;
* callers only need its metadata when a replace decision is required.
*/
async restore(script, replaceExisting = false) {
await openScriptDB();
const row = await encodeScriptForStorage(script);
return withTransaction(Stores.scripts, "readwrite", async (tx) => {
const store = tx.objectStore(Stores.scripts);
const existing = await reqToPromise(store.get(script.id));
if (existing && !replaceExisting) {
return { collision: true, existing: { ...existing } };
}
await reqToPromise(store.put(row));
return { collision: false };
});
},
/**
* Update every script position in one transaction without rewriting the
* rest of any script record. The transaction re-reads the store so a
* concurrent save cannot be overwritten by a stale in-memory snapshot.
*/
async reorderPositions(orderedIds) {
if (!Array.isArray(orderedIds) || orderedIds.some((id) => typeof id !== "string" || id.length === 0)) {
throw new TypeError("Script order must contain non-empty string IDs");
}
await openScriptDB();
await withTransaction(Stores.scripts, "readwrite", async (tx) => {
const store = tx.objectStore(Stores.scripts);
const rows = await reqToPromise(store.getAll()) ?? [];
const rowsById = new Map(rows.map((row) => [row.id, row]));
const submittedIds = new Set(orderedIds);
if (orderedIds.length !== rows.length || submittedIds.size !== rows.length || rows.some((row) => !submittedIds.has(row.id))) {
throw new Error("Script order must be a permutation of the stored script IDs");
}
for (const [position, id] of orderedIds.entries()) {
const row = rowsById.get(id);
if (!row) throw new Error("Script order contains an unknown script ID");
if (row.position === position) continue;
row.position = position;
await reqToPromise(store.put(row));
}
});
},
/**
* Irreversibly reduce every persisted execution URL in one IDB transaction.
* Returning only the minimized values lets ScriptStorage update its mirror
* without re-reading (or accidentally retaining) the original full URLs.
*/
async rewriteStatsUrls(mode) {
await openScriptDB();
return withTransaction(Stores.scripts, "readwrite", async (tx) => {
const store = tx.objectStore(Stores.scripts);
const rows = await reqToPromise(store.getAll()) ?? [];
const changed = [];
for (const row of rows) {
if (!row.stats || !Object.prototype.hasOwnProperty.call(row.stats, "lastUrl")) continue;
const lastUrl = retainStatsUrl(row.stats.lastUrl, mode);
if (lastUrl === row.stats.lastUrl) continue;
row.stats = { ...row.stats };
if (lastUrl) row.stats.lastUrl = lastUrl;
else delete row.stats.lastUrl;
await reqToPromise(store.put(row));
changed.push(lastUrl ? { id: row.id, lastUrl } : { id: row.id });
}
return changed;
});
},
async delete(id) {
await openScriptDB();
if (await isStorageBucketPartitioningActive()) {
await withTransaction(
[Stores.scripts, Stores.stats, Stores.localWorkspaceBindings],
"readwrite",
async (tx) => {
await reqToPromise(tx.objectStore(Stores.scripts).delete(id));
await reqToPromise(tx.objectStore(Stores.stats).delete(id));
const bindingIdx = tx.objectStore(Stores.localWorkspaceBindings).index("by-script");
await forEachCursor(bindingIdx, (_v, _k, primaryKey) => {
tx.objectStore(Stores.localWorkspaceBindings).delete(primaryKey);
}, IDBKeyRange.only(id));
}
);
try {
await ValuesDAO.deleteAll(id);
} catch (e) {
console.warn("[ScriptVault] Removed script but could not clean up orphaned GM values:", e);
}
return;
}
await withTransaction(
[Stores.scripts, Stores.values, Stores.stats, Stores.localWorkspaceBindings],
"readwrite",
async (tx) => {
await reqToPromise(tx.objectStore(Stores.scripts).delete(id));
await reqToPromise(tx.objectStore(Stores.stats).delete(id));
const valuesIdx = tx.objectStore(Stores.values).index("by-script");
await forEachCursor(valuesIdx, (_v, _k, primaryKey) => {
tx.objectStore(Stores.values).delete(primaryKey);
}, IDBKeyRange.only(id));
const bindingIdx = tx.objectStore(Stores.localWorkspaceBindings).index("by-script");
await forEachCursor(bindingIdx, (_v, _k, primaryKey) => {
tx.objectStore(Stores.localWorkspaceBindings).delete(primaryKey);
}, IDBKeyRange.only(id));
}
);
},
async clear() {
await openScriptDB();
if (await isStorageBucketPartitioningActive()) {
await withTransaction(
[Stores.scripts, Stores.stats, Stores.localWorkspaceBindings],
"readwrite",
async (tx) => {
await reqToPromise(tx.objectStore(Stores.scripts).clear());
await reqToPromise(tx.objectStore(Stores.stats).clear());
await reqToPromise(tx.objectStore(Stores.localWorkspaceBindings).clear());
}
);
try {
await ValuesDAO.clear();
} catch (e) {
console.warn("[ScriptVault] Removed scripts but could not clean up orphaned GM values:", e);
}
return;
}
await withTransaction(
[Stores.scripts, Stores.values, Stores.stats, Stores.localWorkspaceBindings],
"readwrite",
async (tx) => {
await reqToPromise(tx.objectStore(Stores.scripts).clear());
await reqToPromise(tx.objectStore(Stores.values).clear());
await reqToPromise(tx.objectStore(Stores.stats).clear());
await reqToPromise(tx.objectStore(Stores.localWorkspaceBindings).clear());
}
);
},
async count() {
await openScriptDB();
return withTransaction(Stores.scripts, "readonly", async (tx) => {
return reqToPromise(tx.objectStore(Stores.scripts).count());
});
},
// Bulk insert used by the v2→v3 migration. Single transaction so a partial
// failure leaves the DB empty rather than half-imported.
async bulkPut(scripts) {
if (scripts.length === 0) return;
await openScriptDB();
const rows = await Promise.all(scripts.map((script) => encodeScriptForStorage(script)));
await withTransaction(Stores.scripts, "readwrite", async (tx) => {
const store = tx.objectStore(Stores.scripts);
for (const s of rows) {
await reqToPromise(store.put(s));
}
});
}
};
var ValuesDAO = {
async getSyncDeviceId() {
const state = await loadGmValueHlcState();
return state.deviceId;
},
async get(scriptId, key) {
await openValuesDB();
return withTransaction(Stores.values, "readonly", async (tx) => {
const row = await reqToPromise(
tx.objectStore(Stores.values).get([scriptId, key])
);
return row ? row.value : void 0;
});
},
async set(scriptId, key, value) {
await openValuesDB();
const clock = await nextGmValueClock();
await withTransaction(Stores.values, "readwrite", async (tx) => {
const row = { scriptId, key, value, updatedAt: clock.ts, clock };
await reqToPromise(tx.objectStore(Stores.values).put(row));
});
},
async delete(scriptId, key) {
await openValuesDB();
await withTransaction(Stores.values, "readwrite", async (tx) => {
await reqToPromise(tx.objectStore(Stores.values).delete([scriptId, key]));
});
},
async getAll(scriptId) {
await openValuesDB();
return withTransaction(Stores.values, "readonly", async (tx) => {
const out = {};
const idx = tx.objectStore(Stores.values).index("by-script");
await forEachCursor(idx, (row) => {
setRecordKey(out, row.key, row.value);
}, IDBKeyRange.only(scriptId));
return out;
});
},
async getAllMetadata(scriptId) {
await openValuesDB();
return withTransaction(Stores.values, "readonly", async (tx) => {
let valueCount = 0;
let lastUpdatedAt = null;
const idx = tx.objectStore(Stores.values).index("by-script");
await forEachCursor(idx, (row) => {
valueCount += 1;
const updatedAt = Number(row.updatedAt);
if (Number.isFinite(updatedAt) && updatedAt > 0) {
lastUpdatedAt = Math.max(lastUpdatedAt ?? 0, updatedAt);
}
}, IDBKeyRange.only(scriptId));
return { valueCount, lastUpdatedAt };
});
},
async getAllKeyMetadata(scriptId) {
await openValuesDB();
return withTransaction(Stores.values, "readonly", async (tx) => {
const out = {};
const idx = tx.objectStore(Stores.values).index("by-script");
await forEachCursor(idx, (row) => {
const updatedAt = Number(row.updatedAt);
const clock = normalizeGmValueClockRecord(row.clock);
if (Number.isFinite(updatedAt) && updatedAt > 0) {
setRecordKey(out, row.key, {
updatedAt: Math.floor(updatedAt),
...clock ? { clock } : {}
});
} else if (clock) {
setRecordKey(out, row.key, { clock });
}
}, IDBKeyRange.only(scriptId));
return out;
});
},
async list(scriptId) {
const all = await this.getAll(scriptId);
return Object.keys(all);
},
async setAll(scriptId, values) {
await openValuesDB();
const clock = await nextGmValueClock();
await withTransaction(Stores.values, "readwrite", async (tx) => {
const store = tx.objectStore(Stores.values);
for (const [key, value] of Object.entries(values)) {
await reqToPromise(store.put({ scriptId, key, value, updatedAt: clock.ts, clock }));
}
});
},
async setAllWithClocks(scriptId, values, keyMetadata = {}) {
await openValuesDB();
const fallbackClock = await nextGmValueClock();
const clocks = [];
const rows = Object.entries(values).map(([key, value]) => {
const clock = normalizeGmValueClockRecord(keyMetadata[key]?.clock) || fallbackClock;
clocks.push(clock);
const updatedAt = Number(keyMetadata[key]?.updatedAt);
return {
scriptId,
key,
value,
updatedAt: Number.isFinite(updatedAt) && updatedAt > 0 ? Math.floor(updatedAt) : clock.ts,
clock
};
});
await observeGmValueClocks(clocks);
await withTransaction(Stores.values, "readwrite", async (tx) => {
const store = tx.objectStore(Stores.values);
for (const row of rows) await reqToPromise(store.put(row));
});
},
async deleteMultiple(scriptId, keys) {
if (keys.length === 0) return;
await openValuesDB();
await withTransaction(Stores.values, "readwrite", async (tx) => {
const store = tx.objectStore(Stores.values);
for (const key of keys) {
await reqToPromise(store.delete([scriptId, key]));
}
});
},
async deleteAll(scriptId) {
await openValuesDB();
await withTransaction(Stores.values, "readwrite", async (tx) => {
const store = tx.objectStore(Stores.values);
const idx = store.index("by-script");
await forEachCursor(idx, (_row, _k, primaryKey) => {
store.delete(primaryKey);
}, IDBKeyRange.only(scriptId));
});
},
async clear() {
await openValuesDB();
await withTransaction(Stores.values, "readwrite", async (tx) => {
await reqToPromise(tx.objectStore(Stores.values).clear());
});
},
async byteSize(scriptId) {
const all = await this.getAll(scriptId);
return new TextEncoder().encode(JSON.stringify(all)).length;
}
};
function summarizeLocalWorkspaceBinding(row) {
const {
bindingId,
scriptId,
bindingKind,
libraryId,
projectId,
relativePath,
displayName,
lastKnownSha256,
lastKnownSize,
lastKnownModified,
permissionState,
createdAt,
updatedAt,
lastRefreshAt,
lastErrorKind,
lastStatusKind
} = row;
return {
bindingId,
scriptId,
bindingKind: bindingKind === "library" ? "library" : bindingKind === "project" ? "project" : bindingKind === "project-file" ? "project-file" : "script",
libraryId: bindingKind === "library" ? libraryId : void 0,
projectId: projectId || void 0,
relativePath: relativePath || void 0,
displayName,
lastKnownSha256,
lastKnownSize,
lastKnownModified,
permissionState,
createdAt,
updatedAt,
lastRefreshAt: lastRefreshAt ?? null,
lastErrorKind,
lastStatusKind
};
}
var LocalWorkspaceBindingsDAO = {
async put(record) {
const now = Date.now();
const row = {
...record,
displayName: String(record.displayName || "").slice(0, 160),
createdAt: record.createdAt || now,
updatedAt: now,
lastRefreshAt: record.lastRefreshAt ?? null
};
await openScriptDB();
await withTransaction(Stores.localWorkspaceBindings, "readwrite", async (tx) => {
await reqToPromise(tx.objectStore(Stores.localWorkspaceBindings).put(row));
});
return summarizeLocalWorkspaceBinding(row);
},
async get(bindingId) {
await openScriptDB();
return withTransaction(Stores.localWorkspaceBindings, "readonly", async (tx) => {
const row = await reqToPromise(
tx.objectStore(Stores.localWorkspaceBindings).get(bindingId)
);
return row ? summarizeLocalWorkspaceBinding(row) : null;
});
},
async getHandle(bindingId) {
await openScriptDB();
return withTransaction(Stores.localWorkspaceBindings, "readonly", async (tx) => {
const row = await reqToPromise(
tx.objectStore(Stores.localWorkspaceBindings).get(bindingId)