@balancy/utils 1.0.34

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.
@@ -0,0 +1,3230 @@
1
+ (function (global, factory) {
2
+ typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
3
+ typeof define === 'function' && define.amd ? define(['exports'], factory) :
4
+ (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global["@balancy/utils"] = {}));
5
+ })(this, (function (exports) { 'use strict';
6
+
7
+ // Временный импорт для типизации - будет заменен на динамическую инъекцию
8
+ // import {DataObjectsManager} from "@balancy/core";
9
+ function asyncGeneratorStep$2(gen, resolve, reject, _next, _throw, key, arg) {
10
+ try {
11
+ var info = gen[key](arg);
12
+ var value = info.value;
13
+ } catch (error) {
14
+ reject(error);
15
+ return;
16
+ }
17
+ if (info.done) {
18
+ resolve(value);
19
+ } else {
20
+ Promise.resolve(value).then(_next, _throw);
21
+ }
22
+ }
23
+ function _async_to_generator$2(fn) {
24
+ return function() {
25
+ var self = this, args = arguments;
26
+ return new Promise(function(resolve, reject) {
27
+ var gen = fn.apply(self, args);
28
+ function _next(value) {
29
+ asyncGeneratorStep$2(gen, resolve, reject, _next, _throw, "next", value);
30
+ }
31
+ function _throw(err) {
32
+ asyncGeneratorStep$2(gen, resolve, reject, _next, _throw, "throw", err);
33
+ }
34
+ _next(undefined);
35
+ });
36
+ };
37
+ }
38
+ function _class_call_check$1(instance, Constructor) {
39
+ if (!(instance instanceof Constructor)) {
40
+ throw new TypeError("Cannot call a class as a function");
41
+ }
42
+ }
43
+ function _defineProperties$1(target, props) {
44
+ for(var i = 0; i < props.length; i++){
45
+ var descriptor = props[i];
46
+ descriptor.enumerable = descriptor.enumerable || false;
47
+ descriptor.configurable = true;
48
+ if ("value" in descriptor) descriptor.writable = true;
49
+ Object.defineProperty(target, descriptor.key, descriptor);
50
+ }
51
+ }
52
+ function _create_class$1(Constructor, protoProps, staticProps) {
53
+ if (protoProps) _defineProperties$1(Constructor.prototype, protoProps);
54
+ return Constructor;
55
+ }
56
+ function _define_property$1(obj, key, value) {
57
+ if (key in obj) {
58
+ Object.defineProperty(obj, key, {
59
+ value: value,
60
+ enumerable: true,
61
+ configurable: true,
62
+ writable: true
63
+ });
64
+ } else {
65
+ obj[key] = value;
66
+ }
67
+ return obj;
68
+ }
69
+ function _instanceof$2(left, right) {
70
+ if (right != null && typeof Symbol !== "undefined" && right[Symbol.hasInstance]) {
71
+ return !!right[Symbol.hasInstance](left);
72
+ } else {
73
+ return left instanceof right;
74
+ }
75
+ }
76
+ function _ts_generator$2(thisArg, body) {
77
+ var f, y, t, g, _ = {
78
+ label: 0,
79
+ sent: function() {
80
+ if (t[0] & 1) throw t[1];
81
+ return t[1];
82
+ },
83
+ trys: [],
84
+ ops: []
85
+ };
86
+ return g = {
87
+ next: verb(0),
88
+ "throw": verb(1),
89
+ "return": verb(2)
90
+ }, typeof Symbol === "function" && (g[Symbol.iterator] = function() {
91
+ return this;
92
+ }), g;
93
+ function verb(n) {
94
+ return function(v) {
95
+ return step([
96
+ n,
97
+ v
98
+ ]);
99
+ };
100
+ }
101
+ function step(op) {
102
+ if (f) throw new TypeError("Generator is already executing.");
103
+ while(_)try {
104
+ if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
105
+ if (y = 0, t) op = [
106
+ op[0] & 2,
107
+ t.value
108
+ ];
109
+ switch(op[0]){
110
+ case 0:
111
+ case 1:
112
+ t = op;
113
+ break;
114
+ case 4:
115
+ _.label++;
116
+ return {
117
+ value: op[1],
118
+ done: false
119
+ };
120
+ case 5:
121
+ _.label++;
122
+ y = op[1];
123
+ op = [
124
+ 0
125
+ ];
126
+ continue;
127
+ case 7:
128
+ op = _.ops.pop();
129
+ _.trys.pop();
130
+ continue;
131
+ default:
132
+ if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) {
133
+ _ = 0;
134
+ continue;
135
+ }
136
+ if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) {
137
+ _.label = op[1];
138
+ break;
139
+ }
140
+ if (op[0] === 6 && _.label < t[1]) {
141
+ _.label = t[1];
142
+ t = op;
143
+ break;
144
+ }
145
+ if (t && _.label < t[2]) {
146
+ _.label = t[2];
147
+ _.ops.push(op);
148
+ break;
149
+ }
150
+ if (t[2]) _.ops.pop();
151
+ _.trys.pop();
152
+ continue;
153
+ }
154
+ op = body.call(thisArg, _);
155
+ } catch (e) {
156
+ op = [
157
+ 6,
158
+ e
159
+ ];
160
+ y = 0;
161
+ } finally{
162
+ f = t = 0;
163
+ }
164
+ if (op[0] & 5) throw op[1];
165
+ return {
166
+ value: op[0] ? op[1] : void 0,
167
+ done: true
168
+ };
169
+ }
170
+ }
171
+ function _ts_values(o) {
172
+ var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
173
+ if (m) return m.call(o);
174
+ if (o && typeof o.length === "number") return {
175
+ next: function() {
176
+ if (o && i >= o.length) o = void 0;
177
+ return {
178
+ value: o && o[i++],
179
+ done: !o
180
+ };
181
+ }
182
+ };
183
+ throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
184
+ }
185
+ var IndexedDBFileHelper = /*#__PURE__*/ function() {
186
+ function IndexedDBFileHelper(paths) {
187
+ _class_call_check$1(this, IndexedDBFileHelper);
188
+ _define_property$1(this, "cacheDir", void 0);
189
+ _define_property$1(this, "codeDir", void 0);
190
+ _define_property$1(this, "resourcesDir", void 0);
191
+ _define_property$1(this, "db", null);
192
+ _define_property$1(this, "isInitialized", false);
193
+ _define_property$1(this, "isTempActive", false);
194
+ _define_property$1(this, "spriteLoader", void 0);
195
+ _define_property$1(this, "DB_NAME", 'BalancyFileStorage');
196
+ _define_property$1(this, "DB_VERSION", 1);
197
+ _define_property$1(this, "STORES", {
198
+ FILES: 'files',
199
+ DIRECTORIES: 'directories'
200
+ });
201
+ this.cacheDir = paths.cachePath;
202
+ this.codeDir = paths.codePath;
203
+ this.resourcesDir = paths.resourcesPath;
204
+ }
205
+ _create_class$1(IndexedDBFileHelper, [
206
+ {
207
+ key: "getCachedDirectory",
208
+ value: function getCachedDirectory() {
209
+ return this.cacheDir;
210
+ }
211
+ },
212
+ {
213
+ key: "ensureInitialized",
214
+ value: function ensureInitialized() {
215
+ var _this = this;
216
+ return _async_to_generator$2(function() {
217
+ return _ts_generator$2(this, function(_state) {
218
+ switch(_state.label){
219
+ case 0:
220
+ if (!!_this.isInitialized) return [
221
+ 3,
222
+ 2
223
+ ];
224
+ return [
225
+ 4,
226
+ _this.initIndexedDB()
227
+ ];
228
+ case 1:
229
+ _state.sent();
230
+ _this.isInitialized = true;
231
+ _state.label = 2;
232
+ case 2:
233
+ return [
234
+ 2
235
+ ];
236
+ }
237
+ });
238
+ })();
239
+ }
240
+ },
241
+ {
242
+ key: "initIndexedDB",
243
+ value: function initIndexedDB() {
244
+ var _this = this;
245
+ return _async_to_generator$2(function() {
246
+ return _ts_generator$2(this, function(_state) {
247
+ return [
248
+ 2,
249
+ new Promise(function(resolve, reject) {
250
+ var request = indexedDB.open(_this.DB_NAME, _this.DB_VERSION);
251
+ request.onerror = function() {
252
+ return reject(request.error);
253
+ };
254
+ request.onsuccess = function() {
255
+ _this.db = request.result;
256
+ resolve();
257
+ };
258
+ request.onupgradeneeded = function(event) {
259
+ var db = event.target.result;
260
+ // Хранилище файлов
261
+ if (!db.objectStoreNames.contains(_this.STORES.FILES)) {
262
+ var filesStore = db.createObjectStore(_this.STORES.FILES, {
263
+ keyPath: 'fileName'
264
+ });
265
+ filesStore.createIndex('directory', 'directory', {
266
+ unique: false
267
+ });
268
+ filesStore.createIndex('fileType', 'fileType', {
269
+ unique: false
270
+ });
271
+ }
272
+ // Хранилище директорий
273
+ if (!db.objectStoreNames.contains(_this.STORES.DIRECTORIES)) {
274
+ var dirsStore = db.createObjectStore(_this.STORES.DIRECTORIES, {
275
+ keyPath: 'path'
276
+ });
277
+ dirsStore.createIndex('parentPath', 'parentPath', {
278
+ unique: false
279
+ });
280
+ }
281
+ };
282
+ })
283
+ ];
284
+ });
285
+ })();
286
+ }
287
+ },
288
+ {
289
+ key: "getFullPath",
290
+ value: function getFullPath(directory, fileName) {
291
+ return "".concat(directory, "/").concat(fileName);
292
+ }
293
+ },
294
+ {
295
+ key: "getTempPath",
296
+ value: function getTempPath(directory) {
297
+ return "".concat(directory, "/temp");
298
+ }
299
+ },
300
+ {
301
+ key: "normalizeData",
302
+ value: function normalizeData(data) {
303
+ if (typeof data === 'string') {
304
+ return {
305
+ data: data,
306
+ fileType: 'text'
307
+ };
308
+ } else if (_instanceof$2(data, Uint8Array)) {
309
+ return {
310
+ data: data.buffer,
311
+ fileType: 'binary'
312
+ };
313
+ } else {
314
+ return {
315
+ data: data,
316
+ fileType: 'binary'
317
+ };
318
+ }
319
+ }
320
+ },
321
+ {
322
+ key: "saveFile",
323
+ value: function saveFile(directory, fileName, data) {
324
+ var _this = this;
325
+ return _async_to_generator$2(function() {
326
+ var actualDirectory, fullPath, _this_normalizeData, normalizedData, fileType, fileRecord, transaction;
327
+ return _ts_generator$2(this, function(_state) {
328
+ switch(_state.label){
329
+ case 0:
330
+ return [
331
+ 4,
332
+ _this.ensureInitialized()
333
+ ];
334
+ case 1:
335
+ _state.sent();
336
+ actualDirectory = _this.isTempActive ? _this.getTempPath(directory) : directory;
337
+ fullPath = _this.getFullPath(actualDirectory, fileName);
338
+ _this_normalizeData = _this.normalizeData(data), normalizedData = _this_normalizeData.data, fileType = _this_normalizeData.fileType;
339
+ fileRecord = {
340
+ fileName: fullPath,
341
+ directory: actualDirectory,
342
+ data: normalizedData,
343
+ fileType: fileType,
344
+ size: typeof normalizedData === 'string' ? normalizedData.length : normalizedData.byteLength,
345
+ lastModified: Date.now()
346
+ };
347
+ transaction = _this.db.transaction([
348
+ _this.STORES.FILES
349
+ ], 'readwrite');
350
+ return [
351
+ 4,
352
+ new Promise(function(resolve, reject) {
353
+ var request = transaction.objectStore(_this.STORES.FILES).put(fileRecord);
354
+ request.onsuccess = function() {
355
+ return resolve();
356
+ };
357
+ request.onerror = function() {
358
+ return reject(request.error);
359
+ };
360
+ })
361
+ ];
362
+ case 2:
363
+ _state.sent();
364
+ return [
365
+ 2
366
+ ];
367
+ }
368
+ });
369
+ })();
370
+ }
371
+ },
372
+ {
373
+ key: "loadFile",
374
+ value: function loadFile(directory, fileName) {
375
+ var _this = this;
376
+ return _async_to_generator$2(function() {
377
+ var fullPath;
378
+ return _ts_generator$2(this, function(_state) {
379
+ switch(_state.label){
380
+ case 0:
381
+ return [
382
+ 4,
383
+ _this.ensureInitialized()
384
+ ];
385
+ case 1:
386
+ _state.sent();
387
+ fullPath = _this.getFullPath(directory, fileName);
388
+ return [
389
+ 2,
390
+ new Promise(function(resolve, reject) {
391
+ var transaction = _this.db.transaction([
392
+ _this.STORES.FILES
393
+ ], 'readonly');
394
+ var request = transaction.objectStore(_this.STORES.FILES).get(fullPath);
395
+ request.onsuccess = function() {
396
+ var result = request.result;
397
+ resolve(result ? result.data : null);
398
+ };
399
+ request.onerror = function() {
400
+ return reject(request.error);
401
+ };
402
+ })
403
+ ];
404
+ }
405
+ });
406
+ })();
407
+ }
408
+ },
409
+ {
410
+ key: "fileExists",
411
+ value: function fileExists(directory, fileName) {
412
+ var _this = this;
413
+ return _async_to_generator$2(function() {
414
+ var fullPath;
415
+ return _ts_generator$2(this, function(_state) {
416
+ switch(_state.label){
417
+ case 0:
418
+ return [
419
+ 4,
420
+ _this.ensureInitialized()
421
+ ];
422
+ case 1:
423
+ _state.sent();
424
+ fullPath = _this.getFullPath(directory, fileName);
425
+ return [
426
+ 2,
427
+ new Promise(function(resolve, reject) {
428
+ var transaction = _this.db.transaction([
429
+ _this.STORES.FILES
430
+ ], 'readonly');
431
+ var request = transaction.objectStore(_this.STORES.FILES).get(fullPath);
432
+ request.onsuccess = function() {
433
+ return resolve(!!request.result);
434
+ };
435
+ request.onerror = function() {
436
+ return reject(request.error);
437
+ };
438
+ })
439
+ ];
440
+ }
441
+ });
442
+ })();
443
+ }
444
+ },
445
+ {
446
+ key: "deleteFile",
447
+ value: function deleteFile(directory, fileName) {
448
+ var _this = this;
449
+ return _async_to_generator$2(function() {
450
+ var fullPath, transaction;
451
+ return _ts_generator$2(this, function(_state) {
452
+ switch(_state.label){
453
+ case 0:
454
+ return [
455
+ 4,
456
+ _this.ensureInitialized()
457
+ ];
458
+ case 1:
459
+ _state.sent();
460
+ fullPath = _this.getFullPath(directory, fileName);
461
+ transaction = _this.db.transaction([
462
+ _this.STORES.FILES
463
+ ], 'readwrite');
464
+ return [
465
+ 4,
466
+ new Promise(function(resolve, reject) {
467
+ var request = transaction.objectStore(_this.STORES.FILES).delete(fullPath);
468
+ request.onsuccess = function() {
469
+ return resolve();
470
+ };
471
+ request.onerror = function() {
472
+ return reject(request.error);
473
+ };
474
+ })
475
+ ];
476
+ case 2:
477
+ _state.sent();
478
+ return [
479
+ 2
480
+ ];
481
+ }
482
+ });
483
+ })();
484
+ }
485
+ },
486
+ {
487
+ key: "clearDirectory",
488
+ value: function clearDirectory(directory) {
489
+ var _this = this;
490
+ return _async_to_generator$2(function() {
491
+ var transaction, store, index;
492
+ return _ts_generator$2(this, function(_state) {
493
+ switch(_state.label){
494
+ case 0:
495
+ return [
496
+ 4,
497
+ _this.ensureInitialized()
498
+ ];
499
+ case 1:
500
+ _state.sent();
501
+ transaction = _this.db.transaction([
502
+ _this.STORES.FILES
503
+ ], 'readwrite');
504
+ store = transaction.objectStore(_this.STORES.FILES);
505
+ index = store.index('directory');
506
+ return [
507
+ 4,
508
+ new Promise(function(resolve, reject) {
509
+ var request = index.openCursor(IDBKeyRange.only(directory));
510
+ request.onsuccess = function(event) {
511
+ var cursor = event.target.result;
512
+ if (cursor) {
513
+ cursor.delete();
514
+ cursor.continue();
515
+ } else {
516
+ resolve();
517
+ }
518
+ };
519
+ request.onerror = function() {
520
+ return reject(request.error);
521
+ };
522
+ })
523
+ ];
524
+ case 2:
525
+ _state.sent();
526
+ return [
527
+ 2
528
+ ];
529
+ }
530
+ });
531
+ })();
532
+ }
533
+ },
534
+ {
535
+ key: "getFilesInDirectory",
536
+ value: function getFilesInDirectory(directory) {
537
+ var _this = this;
538
+ return _async_to_generator$2(function() {
539
+ return _ts_generator$2(this, function(_state) {
540
+ switch(_state.label){
541
+ case 0:
542
+ return [
543
+ 4,
544
+ _this.ensureInitialized()
545
+ ];
546
+ case 1:
547
+ _state.sent();
548
+ return [
549
+ 2,
550
+ new Promise(function(resolve, reject) {
551
+ var transaction = _this.db.transaction([
552
+ _this.STORES.FILES
553
+ ], 'readonly');
554
+ var store = transaction.objectStore(_this.STORES.FILES);
555
+ var index = store.index('directory');
556
+ var files = [];
557
+ var request = index.openCursor(IDBKeyRange.only(directory));
558
+ request.onsuccess = function(event) {
559
+ var cursor = event.target.result;
560
+ if (cursor) {
561
+ var record = cursor.value;
562
+ // Извлекаем только имя файла без пути к директории
563
+ var fileName = record.fileName.substring(directory.length + 1);
564
+ // Проверяем что это файл в этой директории, а не в поддиректории
565
+ if (fileName && !fileName.includes('/')) {
566
+ files.push(fileName);
567
+ }
568
+ cursor.continue();
569
+ } else {
570
+ resolve(files);
571
+ }
572
+ };
573
+ request.onerror = function() {
574
+ return reject(request.error);
575
+ };
576
+ })
577
+ ];
578
+ }
579
+ });
580
+ })();
581
+ }
582
+ },
583
+ {
584
+ key: "arrayBufferToBase64",
585
+ value: function arrayBufferToBase64(buffer) {
586
+ var bytes = new Uint8Array(buffer);
587
+ var binary = '';
588
+ for(var i = 0; i < bytes.byteLength; i++){
589
+ binary += String.fromCharCode(bytes[i]);
590
+ }
591
+ return btoa(binary);
592
+ }
593
+ },
594
+ {
595
+ key: "createSubDirectoryInCacheCallback",
596
+ value: // Реализация интерфейса JSFileHelper
597
+ function createSubDirectoryInCacheCallback(fileName) {
598
+ var _this = this;
599
+ return _async_to_generator$2(function() {
600
+ var actualDirectory, dirPath, dirRecord, transaction;
601
+ return _ts_generator$2(this, function(_state) {
602
+ switch(_state.label){
603
+ case 0:
604
+ return [
605
+ 4,
606
+ _this.ensureInitialized()
607
+ ];
608
+ case 1:
609
+ _state.sent();
610
+ actualDirectory = _this.isTempActive ? _this.getTempPath(_this.cacheDir) : _this.cacheDir;
611
+ dirPath = _this.getFullPath(actualDirectory, fileName);
612
+ dirRecord = {
613
+ path: dirPath,
614
+ parentPath: actualDirectory,
615
+ name: fileName,
616
+ created: Date.now()
617
+ };
618
+ transaction = _this.db.transaction([
619
+ _this.STORES.DIRECTORIES
620
+ ], 'readwrite');
621
+ return [
622
+ 4,
623
+ new Promise(function(resolve, reject) {
624
+ var request = transaction.objectStore(_this.STORES.DIRECTORIES).put(dirRecord);
625
+ request.onsuccess = function() {
626
+ return resolve();
627
+ };
628
+ request.onerror = function() {
629
+ return reject(request.error);
630
+ };
631
+ })
632
+ ];
633
+ case 2:
634
+ _state.sent();
635
+ return [
636
+ 2
637
+ ];
638
+ }
639
+ });
640
+ })();
641
+ }
642
+ },
643
+ {
644
+ key: "saveFileInCacheCallback",
645
+ value: function saveFileInCacheCallback(fileName, data) {
646
+ var _this = this;
647
+ return _async_to_generator$2(function() {
648
+ return _ts_generator$2(this, function(_state) {
649
+ switch(_state.label){
650
+ case 0:
651
+ return [
652
+ 4,
653
+ _this.saveFile(_this.cacheDir, fileName, data)
654
+ ];
655
+ case 1:
656
+ _state.sent();
657
+ return [
658
+ 2
659
+ ];
660
+ }
661
+ });
662
+ })();
663
+ }
664
+ },
665
+ {
666
+ key: "saveFileInCacheBinaryCallback",
667
+ value: function saveFileInCacheBinaryCallback(fileName, data) {
668
+ var _this = this;
669
+ return _async_to_generator$2(function() {
670
+ return _ts_generator$2(this, function(_state) {
671
+ switch(_state.label){
672
+ case 0:
673
+ return [
674
+ 4,
675
+ _this.saveFile(_this.cacheDir, fileName, data)
676
+ ];
677
+ case 1:
678
+ _state.sent();
679
+ return [
680
+ 2
681
+ ];
682
+ }
683
+ });
684
+ })();
685
+ }
686
+ },
687
+ {
688
+ key: "saveFileInResourcesCallback",
689
+ value: function saveFileInResourcesCallback(fileName, data) {
690
+ var _this = this;
691
+ return _async_to_generator$2(function() {
692
+ return _ts_generator$2(this, function(_state) {
693
+ switch(_state.label){
694
+ case 0:
695
+ if (!_this.resourcesDir) throw new Error('Resources directory not configured');
696
+ return [
697
+ 4,
698
+ _this.saveFile(_this.resourcesDir, fileName, data)
699
+ ];
700
+ case 1:
701
+ _state.sent();
702
+ return [
703
+ 2
704
+ ];
705
+ }
706
+ });
707
+ })();
708
+ }
709
+ },
710
+ {
711
+ key: "saveFileInResourcesBinaryCallback",
712
+ value: function saveFileInResourcesBinaryCallback(fileName, data) {
713
+ var _this = this;
714
+ return _async_to_generator$2(function() {
715
+ return _ts_generator$2(this, function(_state) {
716
+ switch(_state.label){
717
+ case 0:
718
+ if (!_this.resourcesDir) throw new Error('Resources directory not configured');
719
+ return [
720
+ 4,
721
+ _this.saveFile(_this.resourcesDir, fileName, data)
722
+ ];
723
+ case 1:
724
+ _state.sent();
725
+ return [
726
+ 2
727
+ ];
728
+ }
729
+ });
730
+ })();
731
+ }
732
+ },
733
+ {
734
+ key: "cleanUpResourcesFolderCallback",
735
+ value: function cleanUpResourcesFolderCallback() {
736
+ var _this = this;
737
+ return _async_to_generator$2(function() {
738
+ return _ts_generator$2(this, function(_state) {
739
+ switch(_state.label){
740
+ case 0:
741
+ if (!_this.resourcesDir) return [
742
+ 2
743
+ ];
744
+ return [
745
+ 4,
746
+ _this.clearDirectory(_this.resourcesDir)
747
+ ];
748
+ case 1:
749
+ _state.sent();
750
+ return [
751
+ 2
752
+ ];
753
+ }
754
+ });
755
+ })();
756
+ }
757
+ },
758
+ {
759
+ key: "cleanGeneratedCodeFolderCallback",
760
+ value: function cleanGeneratedCodeFolderCallback() {
761
+ var _this = this;
762
+ return _async_to_generator$2(function() {
763
+ return _ts_generator$2(this, function(_state) {
764
+ switch(_state.label){
765
+ case 0:
766
+ if (!_this.codeDir) return [
767
+ 2
768
+ ];
769
+ return [
770
+ 4,
771
+ _this.clearDirectory(_this.codeDir)
772
+ ];
773
+ case 1:
774
+ _state.sent();
775
+ return [
776
+ 2
777
+ ];
778
+ }
779
+ });
780
+ })();
781
+ }
782
+ },
783
+ {
784
+ key: "saveGeneratedCodeCallback",
785
+ value: function saveGeneratedCodeCallback(fileName, data) {
786
+ var _this = this;
787
+ return _async_to_generator$2(function() {
788
+ return _ts_generator$2(this, function(_state) {
789
+ switch(_state.label){
790
+ case 0:
791
+ if (!_this.codeDir) throw new Error('Code directory not configured');
792
+ return [
793
+ 4,
794
+ _this.saveFile(_this.codeDir, fileName, data)
795
+ ];
796
+ case 1:
797
+ _state.sent();
798
+ return [
799
+ 2
800
+ ];
801
+ }
802
+ });
803
+ })();
804
+ }
805
+ },
806
+ {
807
+ key: "loadFileFromCacheCallback",
808
+ value: function loadFileFromCacheCallback(fileName) {
809
+ var _this = this;
810
+ return _async_to_generator$2(function() {
811
+ var data;
812
+ return _ts_generator$2(this, function(_state) {
813
+ switch(_state.label){
814
+ case 0:
815
+ return [
816
+ 4,
817
+ _this.loadFile(_this.cacheDir, fileName)
818
+ ];
819
+ case 1:
820
+ data = _state.sent();
821
+ return [
822
+ 2,
823
+ typeof data === 'string' ? data : ''
824
+ ];
825
+ }
826
+ });
827
+ })();
828
+ }
829
+ },
830
+ {
831
+ key: "loadFileFromResourcesCallback",
832
+ value: function loadFileFromResourcesCallback(fileName) {
833
+ var _this = this;
834
+ return _async_to_generator$2(function() {
835
+ var data;
836
+ return _ts_generator$2(this, function(_state) {
837
+ switch(_state.label){
838
+ case 0:
839
+ if (!_this.resourcesDir) return [
840
+ 2,
841
+ ''
842
+ ];
843
+ return [
844
+ 4,
845
+ _this.loadFile(_this.resourcesDir, fileName)
846
+ ];
847
+ case 1:
848
+ data = _state.sent();
849
+ return [
850
+ 2,
851
+ typeof data === 'string' ? data : ''
852
+ ];
853
+ }
854
+ });
855
+ })();
856
+ }
857
+ },
858
+ {
859
+ key: "loadFileFromResourcesAsBase64Callback",
860
+ value: function loadFileFromResourcesAsBase64Callback(fileName) {
861
+ var _this = this;
862
+ return _async_to_generator$2(function() {
863
+ var data;
864
+ return _ts_generator$2(this, function(_state) {
865
+ switch(_state.label){
866
+ case 0:
867
+ if (!_this.resourcesDir) return [
868
+ 2,
869
+ ''
870
+ ];
871
+ return [
872
+ 4,
873
+ _this.loadFile(_this.resourcesDir, fileName)
874
+ ];
875
+ case 1:
876
+ data = _state.sent();
877
+ if (typeof data === 'string') {
878
+ return [
879
+ 2,
880
+ btoa(data)
881
+ ];
882
+ } else if (_instanceof$2(data, ArrayBuffer)) {
883
+ return [
884
+ 2,
885
+ _this.arrayBufferToBase64(data)
886
+ ];
887
+ }
888
+ return [
889
+ 2,
890
+ ''
891
+ ];
892
+ }
893
+ });
894
+ })();
895
+ }
896
+ },
897
+ {
898
+ key: "deleteCachedFolderCallback",
899
+ value: function deleteCachedFolderCallback(path) {
900
+ var _this = this;
901
+ return _async_to_generator$2(function() {
902
+ var folderPath;
903
+ return _ts_generator$2(this, function(_state) {
904
+ switch(_state.label){
905
+ case 0:
906
+ folderPath = _this.getFullPath(_this.cacheDir, path);
907
+ return [
908
+ 4,
909
+ _this.clearDirectory(folderPath)
910
+ ];
911
+ case 1:
912
+ _state.sent();
913
+ return [
914
+ 2
915
+ ];
916
+ }
917
+ });
918
+ })();
919
+ }
920
+ },
921
+ {
922
+ key: "deleteCachedFileCallback",
923
+ value: function deleteCachedFileCallback(path) {
924
+ var _this = this;
925
+ return _async_to_generator$2(function() {
926
+ return _ts_generator$2(this, function(_state) {
927
+ switch(_state.label){
928
+ case 0:
929
+ return [
930
+ 4,
931
+ _this.deleteFile(_this.cacheDir, path)
932
+ ];
933
+ case 1:
934
+ _state.sent();
935
+ return [
936
+ 2
937
+ ];
938
+ }
939
+ });
940
+ })();
941
+ }
942
+ },
943
+ {
944
+ key: "fileExistsInCacheCallback",
945
+ value: function fileExistsInCacheCallback(fileName) {
946
+ var _this = this;
947
+ return _async_to_generator$2(function() {
948
+ return _ts_generator$2(this, function(_state) {
949
+ switch(_state.label){
950
+ case 0:
951
+ return [
952
+ 4,
953
+ _this.fileExists(_this.cacheDir, fileName)
954
+ ];
955
+ case 1:
956
+ return [
957
+ 2,
958
+ _state.sent()
959
+ ];
960
+ }
961
+ });
962
+ })();
963
+ }
964
+ },
965
+ {
966
+ key: "fileExistsInResourcesCallback",
967
+ value: function fileExistsInResourcesCallback(fileName) {
968
+ var _this = this;
969
+ return _async_to_generator$2(function() {
970
+ return _ts_generator$2(this, function(_state) {
971
+ switch(_state.label){
972
+ case 0:
973
+ if (!_this.resourcesDir) return [
974
+ 2,
975
+ false
976
+ ];
977
+ return [
978
+ 4,
979
+ _this.fileExists(_this.resourcesDir, fileName)
980
+ ];
981
+ case 1:
982
+ return [
983
+ 2,
984
+ _state.sent()
985
+ ];
986
+ }
987
+ });
988
+ })();
989
+ }
990
+ },
991
+ {
992
+ key: "getUrlCachePathCallback",
993
+ value: function getUrlCachePathCallback(id, fileName) {
994
+ if (this.spriteLoader) {
995
+ this.spriteLoader(id, function(path) {});
996
+ } else {
997
+ console.warn('No sprite loader configured. Call setSpriteLoader() to set DataObjectsManager integration.');
998
+ }
999
+ }
1000
+ },
1001
+ {
1002
+ /**
1003
+ * Устанавливает функцию для загрузки спрайтов
1004
+ * Должна быть вызвана из приложения для интеграции с DataObjectsManager
1005
+ */ key: "setSpriteLoader",
1006
+ value: function setSpriteLoader(loader) {
1007
+ this.spriteLoader = loader;
1008
+ }
1009
+ },
1010
+ {
1011
+ key: "getCachePathCallback",
1012
+ value: function getCachePathCallback(fileName) {
1013
+ return this.getFullPath(this.cacheDir, fileName);
1014
+ }
1015
+ },
1016
+ {
1017
+ key: "getResourcesPathCallback",
1018
+ value: function getResourcesPathCallback(fileName) {
1019
+ if (!this.resourcesDir) return '';
1020
+ return this.getFullPath(this.resourcesDir, fileName);
1021
+ }
1022
+ },
1023
+ {
1024
+ key: "getFilesInCachedFolderCallback",
1025
+ value: function getFilesInCachedFolderCallback(path) {
1026
+ var _this = this;
1027
+ return _async_to_generator$2(function() {
1028
+ var folderPath;
1029
+ return _ts_generator$2(this, function(_state) {
1030
+ switch(_state.label){
1031
+ case 0:
1032
+ folderPath = path === '' ? _this.cacheDir : _this.getFullPath(_this.cacheDir, path);
1033
+ return [
1034
+ 4,
1035
+ _this.getFilesInDirectory(folderPath)
1036
+ ];
1037
+ case 1:
1038
+ return [
1039
+ 2,
1040
+ _state.sent()
1041
+ ];
1042
+ }
1043
+ });
1044
+ })();
1045
+ }
1046
+ },
1047
+ {
1048
+ key: "getFoldersInCachedFolderCallback",
1049
+ value: function getFoldersInCachedFolderCallback(path) {
1050
+ var _this = this;
1051
+ return _async_to_generator$2(function() {
1052
+ var folderPath;
1053
+ return _ts_generator$2(this, function(_state) {
1054
+ switch(_state.label){
1055
+ case 0:
1056
+ return [
1057
+ 4,
1058
+ _this.ensureInitialized()
1059
+ ];
1060
+ case 1:
1061
+ _state.sent();
1062
+ folderPath = path === '' ? _this.cacheDir : _this.getFullPath(_this.cacheDir, path);
1063
+ return [
1064
+ 2,
1065
+ new Promise(function(resolve, reject) {
1066
+ var transaction = _this.db.transaction([
1067
+ _this.STORES.DIRECTORIES
1068
+ ], 'readonly');
1069
+ var store = transaction.objectStore(_this.STORES.DIRECTORIES);
1070
+ var index = store.index('parentPath');
1071
+ var folders = [];
1072
+ var request = index.openCursor(IDBKeyRange.only(folderPath));
1073
+ request.onsuccess = function(event) {
1074
+ var cursor = event.target.result;
1075
+ if (cursor) {
1076
+ var record = cursor.value;
1077
+ folders.push(record.name);
1078
+ cursor.continue();
1079
+ } else {
1080
+ resolve(folders);
1081
+ }
1082
+ };
1083
+ request.onerror = function() {
1084
+ return reject(request.error);
1085
+ };
1086
+ })
1087
+ ];
1088
+ }
1089
+ });
1090
+ })();
1091
+ }
1092
+ },
1093
+ {
1094
+ key: "getFilesInResourcesFolderCallback",
1095
+ value: // Метод для получения всех файлов из resources директории
1096
+ function getFilesInResourcesFolderCallback() {
1097
+ var path = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : '';
1098
+ var _this = this;
1099
+ return _async_to_generator$2(function() {
1100
+ var folderPath;
1101
+ return _ts_generator$2(this, function(_state) {
1102
+ switch(_state.label){
1103
+ case 0:
1104
+ if (!_this.resourcesDir) return [
1105
+ 2,
1106
+ []
1107
+ ];
1108
+ folderPath = path === '' ? _this.resourcesDir : _this.getFullPath(_this.resourcesDir, path);
1109
+ return [
1110
+ 4,
1111
+ _this.getFilesInDirectory(folderPath)
1112
+ ];
1113
+ case 1:
1114
+ return [
1115
+ 2,
1116
+ _state.sent()
1117
+ ];
1118
+ }
1119
+ });
1120
+ })();
1121
+ }
1122
+ },
1123
+ {
1124
+ key: "getFilesInCodeFolderCallback",
1125
+ value: // Метод для получения всех файлов из code директории
1126
+ function getFilesInCodeFolderCallback() {
1127
+ var path = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : '';
1128
+ var _this = this;
1129
+ return _async_to_generator$2(function() {
1130
+ var folderPath;
1131
+ return _ts_generator$2(this, function(_state) {
1132
+ switch(_state.label){
1133
+ case 0:
1134
+ if (!_this.codeDir) return [
1135
+ 2,
1136
+ []
1137
+ ];
1138
+ folderPath = path === '' ? _this.codeDir : _this.getFullPath(_this.codeDir, path);
1139
+ return [
1140
+ 4,
1141
+ _this.getFilesInDirectory(folderPath)
1142
+ ];
1143
+ case 1:
1144
+ return [
1145
+ 2,
1146
+ _state.sent()
1147
+ ];
1148
+ }
1149
+ });
1150
+ })();
1151
+ }
1152
+ },
1153
+ {
1154
+ key: "activateTempFolderCallback",
1155
+ value: function activateTempFolderCallback() {
1156
+ this.isTempActive = true;
1157
+ }
1158
+ },
1159
+ {
1160
+ key: "deactivateTempFolderCallback",
1161
+ value: function deactivateTempFolderCallback() {
1162
+ this.isTempActive = false;
1163
+ }
1164
+ },
1165
+ {
1166
+ key: "applyTempFolderCallback",
1167
+ value: function applyTempFolderCallback(tempFolder) {
1168
+ var _this = this;
1169
+ return _async_to_generator$2(function() {
1170
+ var tempPath, tempFolderPath, tempFiles, _iteratorNormalCompletion, _didIteratorError, _iteratorError, _loop, _iterator, _step, err;
1171
+ return _ts_generator$2(this, function(_state) {
1172
+ switch(_state.label){
1173
+ case 0:
1174
+ tempPath = _this.getTempPath(_this.cacheDir);
1175
+ tempFolderPath = _this.getFullPath(tempPath, tempFolder);
1176
+ return [
1177
+ 4,
1178
+ _this.getFilesInDirectory(tempFolderPath)
1179
+ ];
1180
+ case 1:
1181
+ tempFiles = _state.sent();
1182
+ _iteratorNormalCompletion = true, _didIteratorError = false, _iteratorError = undefined;
1183
+ _state.label = 2;
1184
+ case 2:
1185
+ _state.trys.push([
1186
+ 2,
1187
+ 7,
1188
+ 8,
1189
+ 9
1190
+ ]);
1191
+ _loop = function() {
1192
+ var fileName, cacheFilePath, data, _this_normalizeData, normalizedData, fileType, fileRecord, transaction;
1193
+ return _ts_generator$2(this, function(_state) {
1194
+ switch(_state.label){
1195
+ case 0:
1196
+ fileName = _step.value;
1197
+ _this.getFullPath(tempFolderPath, fileName);
1198
+ cacheFilePath = _this.getFullPath(_this.cacheDir, fileName);
1199
+ return [
1200
+ 4,
1201
+ _this.loadFile(tempFolderPath, fileName)
1202
+ ];
1203
+ case 1:
1204
+ data = _state.sent();
1205
+ if (!data) return [
1206
+ 3,
1207
+ 4
1208
+ ];
1209
+ // Сохраняем в основную папку
1210
+ _this_normalizeData = _this.normalizeData(data), normalizedData = _this_normalizeData.data, fileType = _this_normalizeData.fileType;
1211
+ fileRecord = {
1212
+ fileName: cacheFilePath,
1213
+ directory: _this.cacheDir,
1214
+ data: normalizedData,
1215
+ fileType: fileType,
1216
+ size: typeof normalizedData === 'string' ? normalizedData.length : normalizedData.byteLength,
1217
+ lastModified: Date.now()
1218
+ };
1219
+ transaction = _this.db.transaction([
1220
+ _this.STORES.FILES
1221
+ ], 'readwrite');
1222
+ return [
1223
+ 4,
1224
+ new Promise(function(resolve, reject) {
1225
+ var request = transaction.objectStore(_this.STORES.FILES).put(fileRecord);
1226
+ request.onsuccess = function() {
1227
+ return resolve();
1228
+ };
1229
+ request.onerror = function() {
1230
+ return reject(request.error);
1231
+ };
1232
+ })
1233
+ ];
1234
+ case 2:
1235
+ _state.sent();
1236
+ // Удаляем из временной папки
1237
+ return [
1238
+ 4,
1239
+ _this.deleteFile(tempFolderPath, fileName)
1240
+ ];
1241
+ case 3:
1242
+ _state.sent();
1243
+ _state.label = 4;
1244
+ case 4:
1245
+ return [
1246
+ 2
1247
+ ];
1248
+ }
1249
+ });
1250
+ };
1251
+ _iterator = tempFiles[Symbol.iterator]();
1252
+ _state.label = 3;
1253
+ case 3:
1254
+ if (!!(_iteratorNormalCompletion = (_step = _iterator.next()).done)) return [
1255
+ 3,
1256
+ 6
1257
+ ];
1258
+ return [
1259
+ 5,
1260
+ _ts_values(_loop())
1261
+ ];
1262
+ case 4:
1263
+ _state.sent();
1264
+ _state.label = 5;
1265
+ case 5:
1266
+ _iteratorNormalCompletion = true;
1267
+ return [
1268
+ 3,
1269
+ 3
1270
+ ];
1271
+ case 6:
1272
+ return [
1273
+ 3,
1274
+ 9
1275
+ ];
1276
+ case 7:
1277
+ err = _state.sent();
1278
+ _didIteratorError = true;
1279
+ _iteratorError = err;
1280
+ return [
1281
+ 3,
1282
+ 9
1283
+ ];
1284
+ case 8:
1285
+ try {
1286
+ if (!_iteratorNormalCompletion && _iterator.return != null) {
1287
+ _iterator.return();
1288
+ }
1289
+ } finally{
1290
+ if (_didIteratorError) {
1291
+ throw _iteratorError;
1292
+ }
1293
+ }
1294
+ return [
1295
+ 7
1296
+ ];
1297
+ case 9:
1298
+ // Очищаем временную папку
1299
+ return [
1300
+ 4,
1301
+ _this.clearDirectory(tempFolderPath)
1302
+ ];
1303
+ case 10:
1304
+ _state.sent();
1305
+ _this.isTempActive = false;
1306
+ return [
1307
+ 2
1308
+ ];
1309
+ }
1310
+ });
1311
+ })();
1312
+ }
1313
+ },
1314
+ {
1315
+ key: "isTempFolderActiveCallback",
1316
+ value: function isTempFolderActiveCallback() {
1317
+ return this.isTempActive;
1318
+ }
1319
+ },
1320
+ {
1321
+ key: "createObjectUrl",
1322
+ value: // Дополнительные методы для работы с Object URL (бонус)
1323
+ function createObjectUrl(directory, fileName) {
1324
+ var _this = this;
1325
+ return _async_to_generator$2(function() {
1326
+ var data, blob;
1327
+ return _ts_generator$2(this, function(_state) {
1328
+ switch(_state.label){
1329
+ case 0:
1330
+ return [
1331
+ 4,
1332
+ _this.loadFile(directory, fileName)
1333
+ ];
1334
+ case 1:
1335
+ data = _state.sent();
1336
+ if (!data || typeof data === 'string') return [
1337
+ 2,
1338
+ null
1339
+ ];
1340
+ blob = new Blob([
1341
+ data
1342
+ ]);
1343
+ return [
1344
+ 2,
1345
+ URL.createObjectURL(blob)
1346
+ ];
1347
+ }
1348
+ });
1349
+ })();
1350
+ }
1351
+ },
1352
+ {
1353
+ // Получение доступа к базе данных (для расширенных операций)
1354
+ key: "getDatabase",
1355
+ value: function getDatabase() {
1356
+ return this.db;
1357
+ }
1358
+ },
1359
+ {
1360
+ // Очистка ресурсов
1361
+ key: "close",
1362
+ value: function close() {
1363
+ if (this.db) {
1364
+ this.db.close();
1365
+ this.db = null;
1366
+ this.isInitialized = false;
1367
+ }
1368
+ }
1369
+ }
1370
+ ]);
1371
+ return IndexedDBFileHelper;
1372
+ }();
1373
+
1374
+ function _array_like_to_array(arr, len) {
1375
+ if (len == null || len > arr.length) len = arr.length;
1376
+ for(var i = 0, arr2 = new Array(len); i < len; i++)arr2[i] = arr[i];
1377
+ return arr2;
1378
+ }
1379
+ function _array_with_holes(arr) {
1380
+ if (Array.isArray(arr)) return arr;
1381
+ }
1382
+ function asyncGeneratorStep$1(gen, resolve, reject, _next, _throw, key, arg) {
1383
+ try {
1384
+ var info = gen[key](arg);
1385
+ var value = info.value;
1386
+ } catch (error) {
1387
+ reject(error);
1388
+ return;
1389
+ }
1390
+ if (info.done) {
1391
+ resolve(value);
1392
+ } else {
1393
+ Promise.resolve(value).then(_next, _throw);
1394
+ }
1395
+ }
1396
+ function _async_to_generator$1(fn) {
1397
+ return function() {
1398
+ var self = this, args = arguments;
1399
+ return new Promise(function(resolve, reject) {
1400
+ var gen = fn.apply(self, args);
1401
+ function _next(value) {
1402
+ asyncGeneratorStep$1(gen, resolve, reject, _next, _throw, "next", value);
1403
+ }
1404
+ function _throw(err) {
1405
+ asyncGeneratorStep$1(gen, resolve, reject, _next, _throw, "throw", err);
1406
+ }
1407
+ _next(undefined);
1408
+ });
1409
+ };
1410
+ }
1411
+ function _class_call_check(instance, Constructor) {
1412
+ if (!(instance instanceof Constructor)) {
1413
+ throw new TypeError("Cannot call a class as a function");
1414
+ }
1415
+ }
1416
+ function _defineProperties(target, props) {
1417
+ for(var i = 0; i < props.length; i++){
1418
+ var descriptor = props[i];
1419
+ descriptor.enumerable = descriptor.enumerable || false;
1420
+ descriptor.configurable = true;
1421
+ if ("value" in descriptor) descriptor.writable = true;
1422
+ Object.defineProperty(target, descriptor.key, descriptor);
1423
+ }
1424
+ }
1425
+ function _create_class(Constructor, protoProps, staticProps) {
1426
+ if (protoProps) _defineProperties(Constructor.prototype, protoProps);
1427
+ if (staticProps) _defineProperties(Constructor, staticProps);
1428
+ return Constructor;
1429
+ }
1430
+ function _define_property(obj, key, value) {
1431
+ if (key in obj) {
1432
+ Object.defineProperty(obj, key, {
1433
+ value: value,
1434
+ enumerable: true,
1435
+ configurable: true,
1436
+ writable: true
1437
+ });
1438
+ } else {
1439
+ obj[key] = value;
1440
+ }
1441
+ return obj;
1442
+ }
1443
+ function _instanceof$1(left, right) {
1444
+ if (right != null && typeof Symbol !== "undefined" && right[Symbol.hasInstance]) {
1445
+ return !!right[Symbol.hasInstance](left);
1446
+ } else {
1447
+ return left instanceof right;
1448
+ }
1449
+ }
1450
+ function _iterable_to_array_limit(arr, i) {
1451
+ var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"];
1452
+ if (_i == null) return;
1453
+ var _arr = [];
1454
+ var _n = true;
1455
+ var _d = false;
1456
+ var _s, _e;
1457
+ try {
1458
+ for(_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true){
1459
+ _arr.push(_s.value);
1460
+ if (i && _arr.length === i) break;
1461
+ }
1462
+ } catch (err) {
1463
+ _d = true;
1464
+ _e = err;
1465
+ } finally{
1466
+ try {
1467
+ if (!_n && _i["return"] != null) _i["return"]();
1468
+ } finally{
1469
+ if (_d) throw _e;
1470
+ }
1471
+ }
1472
+ return _arr;
1473
+ }
1474
+ function _non_iterable_rest() {
1475
+ throw new TypeError("Invalid attempt to destructure non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
1476
+ }
1477
+ function _sliced_to_array(arr, i) {
1478
+ return _array_with_holes(arr) || _iterable_to_array_limit(arr, i) || _unsupported_iterable_to_array(arr, i) || _non_iterable_rest();
1479
+ }
1480
+ function _unsupported_iterable_to_array(o, minLen) {
1481
+ if (!o) return;
1482
+ if (typeof o === "string") return _array_like_to_array(o, minLen);
1483
+ var n = Object.prototype.toString.call(o).slice(8, -1);
1484
+ if (n === "Object" && o.constructor) n = o.constructor.name;
1485
+ if (n === "Map" || n === "Set") return Array.from(n);
1486
+ if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _array_like_to_array(o, minLen);
1487
+ }
1488
+ function _ts_generator$1(thisArg, body) {
1489
+ var f, y, t, g, _ = {
1490
+ label: 0,
1491
+ sent: function() {
1492
+ if (t[0] & 1) throw t[1];
1493
+ return t[1];
1494
+ },
1495
+ trys: [],
1496
+ ops: []
1497
+ };
1498
+ return g = {
1499
+ next: verb(0),
1500
+ "throw": verb(1),
1501
+ "return": verb(2)
1502
+ }, typeof Symbol === "function" && (g[Symbol.iterator] = function() {
1503
+ return this;
1504
+ }), g;
1505
+ function verb(n) {
1506
+ return function(v) {
1507
+ return step([
1508
+ n,
1509
+ v
1510
+ ]);
1511
+ };
1512
+ }
1513
+ function step(op) {
1514
+ if (f) throw new TypeError("Generator is already executing.");
1515
+ while(_)try {
1516
+ if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
1517
+ if (y = 0, t) op = [
1518
+ op[0] & 2,
1519
+ t.value
1520
+ ];
1521
+ switch(op[0]){
1522
+ case 0:
1523
+ case 1:
1524
+ t = op;
1525
+ break;
1526
+ case 4:
1527
+ _.label++;
1528
+ return {
1529
+ value: op[1],
1530
+ done: false
1531
+ };
1532
+ case 5:
1533
+ _.label++;
1534
+ y = op[1];
1535
+ op = [
1536
+ 0
1537
+ ];
1538
+ continue;
1539
+ case 7:
1540
+ op = _.ops.pop();
1541
+ _.trys.pop();
1542
+ continue;
1543
+ default:
1544
+ if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) {
1545
+ _ = 0;
1546
+ continue;
1547
+ }
1548
+ if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) {
1549
+ _.label = op[1];
1550
+ break;
1551
+ }
1552
+ if (op[0] === 6 && _.label < t[1]) {
1553
+ _.label = t[1];
1554
+ t = op;
1555
+ break;
1556
+ }
1557
+ if (t && _.label < t[2]) {
1558
+ _.label = t[2];
1559
+ _.ops.push(op);
1560
+ break;
1561
+ }
1562
+ if (t[2]) _.ops.pop();
1563
+ _.trys.pop();
1564
+ continue;
1565
+ }
1566
+ op = body.call(thisArg, _);
1567
+ } catch (e) {
1568
+ op = [
1569
+ 6,
1570
+ e
1571
+ ];
1572
+ y = 0;
1573
+ } finally{
1574
+ f = t = 0;
1575
+ }
1576
+ if (op[0] & 5) throw op[1];
1577
+ return {
1578
+ value: op[0] ? op[1] : void 0,
1579
+ done: true
1580
+ };
1581
+ }
1582
+ }
1583
+ var IndexedDBFileHelperAdapter = /*#__PURE__*/ function() {
1584
+ function IndexedDBFileHelperAdapter(paths) {
1585
+ _class_call_check(this, IndexedDBFileHelperAdapter);
1586
+ _define_property(this, "indexedDBHelper", void 0);
1587
+ _define_property(this, "initPromise", void 0);
1588
+ _define_property(this, "isReady", false);
1589
+ // Кэш для синхронных операций чтения
1590
+ _define_property(this, "fileCache", new Map());
1591
+ _define_property(this, "existsCache", new Map());
1592
+ this.indexedDBHelper = new IndexedDBFileHelper(paths);
1593
+ this.initPromise = this.initialize();
1594
+ }
1595
+ _create_class(IndexedDBFileHelperAdapter, [
1596
+ {
1597
+ key: "initialize",
1598
+ value: function initialize() {
1599
+ var _this = this;
1600
+ return _async_to_generator$1(function() {
1601
+ var error;
1602
+ return _ts_generator$1(this, function(_state) {
1603
+ switch(_state.label){
1604
+ case 0:
1605
+ _state.trys.push([
1606
+ 0,
1607
+ 2,
1608
+ ,
1609
+ 3
1610
+ ]);
1611
+ return [
1612
+ 4,
1613
+ _this.indexedDBHelper.createSubDirectoryInCacheCallback('init')
1614
+ ];
1615
+ case 1:
1616
+ _state.sent();
1617
+ _this.isReady = true;
1618
+ return [
1619
+ 3,
1620
+ 3
1621
+ ];
1622
+ case 2:
1623
+ error = _state.sent();
1624
+ console.error('Failed to initialize IndexedDB FileHelper:', error);
1625
+ throw error;
1626
+ case 3:
1627
+ return [
1628
+ 2
1629
+ ];
1630
+ }
1631
+ });
1632
+ })();
1633
+ }
1634
+ },
1635
+ {
1636
+ key: "waitForReady",
1637
+ value: function waitForReady() {
1638
+ var _this = this;
1639
+ return _async_to_generator$1(function() {
1640
+ return _ts_generator$1(this, function(_state) {
1641
+ switch(_state.label){
1642
+ case 0:
1643
+ return [
1644
+ 4,
1645
+ _this.initPromise
1646
+ ];
1647
+ case 1:
1648
+ _state.sent();
1649
+ return [
1650
+ 2
1651
+ ];
1652
+ }
1653
+ });
1654
+ })();
1655
+ }
1656
+ },
1657
+ {
1658
+ key: "stringToArrayBuffer",
1659
+ value: // Преобразование string в ArrayBuffer для бинарных данных
1660
+ function stringToArrayBuffer(str) {
1661
+ // Предполагаем, что это base64 или бинарные данные как строка
1662
+ try {
1663
+ // Попробуем декодировать как base64
1664
+ var binaryString = atob(str);
1665
+ var bytes = new Uint8Array(binaryString.length);
1666
+ for(var i = 0; i < binaryString.length; i++){
1667
+ bytes[i] = binaryString.charCodeAt(i);
1668
+ }
1669
+ return bytes.buffer;
1670
+ } catch (e) {
1671
+ // Если не base64, конвертируем строку в UTF-8 байты
1672
+ var encoder = new TextEncoder();
1673
+ return encoder.encode(str).buffer;
1674
+ }
1675
+ }
1676
+ },
1677
+ {
1678
+ // Реализация старого синхронного интерфейса
1679
+ key: "createSubDirectoryInCacheCallback",
1680
+ value: function createSubDirectoryInCacheCallback(fileName) {
1681
+ var _this = this;
1682
+ if (!this.isReady) {
1683
+ console.warn('IndexedDB not ready yet, queuing operation');
1684
+ this.initPromise.then(function() {
1685
+ _this.indexedDBHelper.createSubDirectoryInCacheCallback(fileName);
1686
+ });
1687
+ return;
1688
+ }
1689
+ // Асинхронно выполняем операцию
1690
+ this.indexedDBHelper.createSubDirectoryInCacheCallback(fileName).catch(function(error) {
1691
+ console.error('Error creating subdirectory:', error);
1692
+ });
1693
+ }
1694
+ },
1695
+ {
1696
+ key: "fileExistsInCacheCallback",
1697
+ value: function fileExistsInCacheCallback(path) {
1698
+ var _this = this;
1699
+ // console.log("fileExistsInCacheCallback " + path);
1700
+ var cacheKey = "".concat(path);
1701
+ if (this.existsCache.has(cacheKey)) {
1702
+ // console.log("cache hit for existsCache: " + cacheKey + " => " + this.existsCache.get(cacheKey));
1703
+ return this.existsCache.get(cacheKey);
1704
+ }
1705
+ // Если нет в кэше, проверяем IndexedDB
1706
+ if (this.isReady) {
1707
+ this.indexedDBHelper.fileExistsInCacheCallback(path).then(function(exists) {
1708
+ // console.log("DB for existsCache: " + cacheKey + " => " + this.existsCache.get(cacheKey));
1709
+ _this.existsCache.set(cacheKey, exists);
1710
+ }).catch(function(error) {
1711
+ console.error('Error checking file existence in cache:', error);
1712
+ _this.existsCache.set(cacheKey, false);
1713
+ });
1714
+ }
1715
+ // console.warn(`File ${path} not found in cache, returning false: this.isReady = ${this.isReady}`);
1716
+ return false;
1717
+ }
1718
+ },
1719
+ {
1720
+ key: "getUrlCachePathCallback",
1721
+ value: function getUrlCachePathCallback(id, path) {
1722
+ if (!this.isReady) {
1723
+ console.warn('IndexedDB not ready yet, returning empty path');
1724
+ return;
1725
+ }
1726
+ // Возвращаем путь к кэшу
1727
+ this.indexedDBHelper.getUrlCachePathCallback(id, path);
1728
+ }
1729
+ },
1730
+ {
1731
+ key: "getCachePathCallback",
1732
+ value: function getCachePathCallback(path) {
1733
+ if (!this.isReady) {
1734
+ console.warn('IndexedDB not ready yet, returning empty path');
1735
+ return '';
1736
+ }
1737
+ // Возвращаем путь к кэшу
1738
+ return this.indexedDBHelper.getCachePathCallback(path);
1739
+ }
1740
+ },
1741
+ {
1742
+ key: "getResourcesPathCallback",
1743
+ value: function getResourcesPathCallback(path) {
1744
+ if (!this.isReady) {
1745
+ console.warn('IndexedDB not ready yet, returning empty path');
1746
+ return '';
1747
+ }
1748
+ // Возвращаем путь к ресурсам
1749
+ return this.indexedDBHelper.getResourcesPathCallback(path);
1750
+ }
1751
+ },
1752
+ {
1753
+ key: "fileExistsInResourcesCallback",
1754
+ value: function fileExistsInResourcesCallback(path) {
1755
+ return false;
1756
+ }
1757
+ },
1758
+ {
1759
+ key: "saveFileInCacheCallback",
1760
+ value: function saveFileInCacheCallback(fileName, data) {
1761
+ var _this = this;
1762
+ if (!this.isReady) {
1763
+ console.warn('IndexedDB not ready yet, queuing operation');
1764
+ this.initPromise.then(function() {
1765
+ _this.indexedDBHelper.saveFileInCacheCallback(fileName, data);
1766
+ });
1767
+ return;
1768
+ }
1769
+ this.fileCache.set(fileName, data);
1770
+ this.existsCache.set(fileName, true);
1771
+ // console.log("saveFileInCacheCallback... " + fileName + " data: " + data.length + " bytes == " + data);
1772
+ // Асинхронно сохраняем в IndexedDB
1773
+ this.indexedDBHelper.saveFileInCacheCallback(fileName, data).catch(function(error) {
1774
+ console.error('Error saving file to cache:', error);
1775
+ // Удаляем из кэша при ошибке
1776
+ _this.fileCache.delete(fileName);
1777
+ _this.existsCache.set(fileName, false);
1778
+ });
1779
+ }
1780
+ },
1781
+ {
1782
+ key: "saveFileInCacheBinaryCallback",
1783
+ value: function saveFileInCacheBinaryCallback(fileName, memoryView) {
1784
+ var _this = this;
1785
+ // console.log('saveFileInCacheBinaryCallback... ' + fileName + ' data: ' + memoryView.length + ' bytes');
1786
+ if (!this.isReady) {
1787
+ console.warn('IndexedDB not ready yet, queuing operation');
1788
+ this.initPromise.then(function() {
1789
+ // memoryView уже Uint8Array, создаем копию для безопасности
1790
+ var dataCopy = new Uint8Array(memoryView);
1791
+ _this.indexedDBHelper.saveFileInCacheBinaryCallback(fileName, dataCopy.buffer);
1792
+ });
1793
+ return;
1794
+ }
1795
+ // Создаем копию данных для безопасности (так как memoryView может быть invalidated)
1796
+ var dataCopy = new Uint8Array(memoryView);
1797
+ var arrayBuffer = dataCopy.buffer.slice(dataCopy.byteOffset, dataCopy.byteOffset + dataCopy.byteLength);
1798
+ // Сохраняем как Uint8Array в память для быстрого доступа
1799
+ this.fileCache.set(fileName, dataCopy);
1800
+ this.existsCache.set(fileName, true);
1801
+ // console.log('=>DONE saveFileInCacheBinaryCallback... ' + fileName + ' data: ' + memoryView.length + ' bytes');
1802
+ // Асинхронно сохраняем в IndexedDB
1803
+ this.indexedDBHelper.saveFileInCacheBinaryCallback(fileName, arrayBuffer).then(function() {
1804
+ // console.log('ALL Saved!!');
1805
+ }).catch(function(error) {
1806
+ console.error('Error saving binary file to cache:', error);
1807
+ _this.fileCache.delete(fileName);
1808
+ _this.existsCache.set(fileName, false);
1809
+ });
1810
+ }
1811
+ },
1812
+ {
1813
+ key: "saveFileInResourcesCallback",
1814
+ value: function saveFileInResourcesCallback(fileName, data) {
1815
+ var _this = this;
1816
+ if (!this.isReady) {
1817
+ console.warn('IndexedDB not ready yet, queuing operation');
1818
+ this.initPromise.then(function() {
1819
+ _this.indexedDBHelper.saveFileInResourcesCallback(fileName, data);
1820
+ });
1821
+ return;
1822
+ }
1823
+ var cacheKey = "resources/".concat(fileName);
1824
+ this.fileCache.set(cacheKey, data);
1825
+ this.existsCache.set(cacheKey, true);
1826
+ this.indexedDBHelper.saveFileInResourcesCallback(fileName, data).catch(function(error) {
1827
+ console.error('Error saving file to resources:', error);
1828
+ _this.fileCache.delete(cacheKey);
1829
+ _this.existsCache.set(cacheKey, false);
1830
+ });
1831
+ }
1832
+ },
1833
+ {
1834
+ key: "cleanUpResourcesFolderCallback",
1835
+ value: function cleanUpResourcesFolderCallback() {
1836
+ var _this = this;
1837
+ if (!this.isReady) {
1838
+ console.warn('IndexedDB not ready yet, queuing operation');
1839
+ this.initPromise.then(function() {
1840
+ _this.indexedDBHelper.cleanUpResourcesFolderCallback();
1841
+ });
1842
+ return;
1843
+ }
1844
+ var _iteratorNormalCompletion = true, _didIteratorError = false, _iteratorError = undefined;
1845
+ try {
1846
+ // Очищаем кэш ресурсов
1847
+ for(var _iterator = this.fileCache[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true){
1848
+ var _step_value = _sliced_to_array(_step.value, 1), key = _step_value[0];
1849
+ if (key.startsWith('resources/')) {
1850
+ this.fileCache.delete(key);
1851
+ this.existsCache.set(key, false);
1852
+ }
1853
+ }
1854
+ } catch (err) {
1855
+ _didIteratorError = true;
1856
+ _iteratorError = err;
1857
+ } finally{
1858
+ try {
1859
+ if (!_iteratorNormalCompletion && _iterator.return != null) {
1860
+ _iterator.return();
1861
+ }
1862
+ } finally{
1863
+ if (_didIteratorError) {
1864
+ throw _iteratorError;
1865
+ }
1866
+ }
1867
+ }
1868
+ this.indexedDBHelper.cleanUpResourcesFolderCallback().catch(function(error) {
1869
+ console.error('Error cleaning resources folder:', error);
1870
+ });
1871
+ }
1872
+ },
1873
+ {
1874
+ key: "cleanGeneratedCodeFolderCallback",
1875
+ value: function cleanGeneratedCodeFolderCallback() {
1876
+ var _this = this;
1877
+ if (!this.isReady) {
1878
+ console.warn('IndexedDB not ready yet, queuing operation');
1879
+ this.initPromise.then(function() {
1880
+ _this.indexedDBHelper.cleanGeneratedCodeFolderCallback();
1881
+ });
1882
+ return;
1883
+ }
1884
+ this.indexedDBHelper.cleanGeneratedCodeFolderCallback().catch(function(error) {
1885
+ console.error('Error cleaning code folder:', error);
1886
+ });
1887
+ }
1888
+ },
1889
+ {
1890
+ key: "saveGeneratedCodeCallback",
1891
+ value: function saveGeneratedCodeCallback(fileName, data) {
1892
+ var _this = this;
1893
+ if (!this.isReady) {
1894
+ console.warn('IndexedDB not ready yet, queuing operation');
1895
+ this.initPromise.then(function() {
1896
+ _this.indexedDBHelper.saveGeneratedCodeCallback(fileName, data);
1897
+ });
1898
+ return;
1899
+ }
1900
+ this.indexedDBHelper.saveGeneratedCodeCallback(fileName, data).catch(function(error) {
1901
+ console.error('Error saving generated code:', error);
1902
+ });
1903
+ }
1904
+ },
1905
+ {
1906
+ key: "loadFileFromCacheCallback",
1907
+ value: function loadFileFromCacheCallback(fileName) {
1908
+ var _this = this;
1909
+ var directory = this.indexedDBHelper.getCachedDirectory();
1910
+ if (fileName.startsWith(directory)) fileName = fileName.substring(directory.length + 1); // Убираем префикс директории
1911
+ if (this.fileCache.has(fileName)) {
1912
+ var cachedData = this.fileCache.get(fileName);
1913
+ // Если это бинарные данные (Uint8Array), конвертируем в строку
1914
+ if (_instanceof$1(cachedData, Uint8Array)) {
1915
+ return new TextDecoder().decode(cachedData);
1916
+ }
1917
+ // Если это строка, возвращаем как есть
1918
+ return cachedData;
1919
+ }
1920
+ // Если нет в кэше и IndexedDB готов, пытаемся загрузить асинхронно
1921
+ if (this.isReady) {
1922
+ // Запускаем асинхронную загрузку для будущих вызовов
1923
+ this.indexedDBHelper.loadFileFromCacheCallback(fileName).then(function(data) {
1924
+ if (data) {
1925
+ _this.fileCache.set(fileName, data);
1926
+ _this.existsCache.set(fileName, true);
1927
+ }
1928
+ }).catch(function(error) {
1929
+ console.error('Error loading file from cache:', error);
1930
+ _this.existsCache.set(fileName, false);
1931
+ });
1932
+ }
1933
+ // console.warn(`File ${fileName} not found in cache, returning empty string`);
1934
+ return '';
1935
+ }
1936
+ },
1937
+ {
1938
+ key: "loadFileFromResourcesCallback",
1939
+ value: function loadFileFromResourcesCallback(fileName) {
1940
+ var _this = this;
1941
+ var cacheKey = "resources/".concat(fileName);
1942
+ if (this.fileCache.has(cacheKey)) {
1943
+ var cachedData = this.fileCache.get(cacheKey);
1944
+ // Если это бинарные данные (Uint8Array), конвертируем в строку
1945
+ if (_instanceof$1(cachedData, Uint8Array)) {
1946
+ return new TextDecoder().decode(cachedData);
1947
+ }
1948
+ // Если это строка, возвращаем как есть
1949
+ return cachedData;
1950
+ }
1951
+ if (this.isReady) {
1952
+ this.indexedDBHelper.loadFileFromResourcesCallback(fileName).then(function(data) {
1953
+ if (data) {
1954
+ _this.fileCache.set(cacheKey, data);
1955
+ _this.existsCache.set(cacheKey, true);
1956
+ }
1957
+ }).catch(function(error) {
1958
+ console.error('Error loading file from resources:', error);
1959
+ _this.existsCache.set(cacheKey, false);
1960
+ });
1961
+ }
1962
+ // console.warn(`Resource ${fileName} not found in cache, returning empty string`);
1963
+ return '';
1964
+ }
1965
+ },
1966
+ {
1967
+ key: "deleteCachedFolderCallback",
1968
+ value: function deleteCachedFolderCallback(path) {
1969
+ var _this = this;
1970
+ if (!this.isReady) {
1971
+ console.warn('IndexedDB not ready yet, queuing operation');
1972
+ this.initPromise.then(function() {
1973
+ _this.indexedDBHelper.deleteCachedFolderCallback(path);
1974
+ });
1975
+ return;
1976
+ }
1977
+ var _iteratorNormalCompletion = true, _didIteratorError = false, _iteratorError = undefined;
1978
+ try {
1979
+ // Очищаем кэш для этой папки
1980
+ for(var _iterator = this.fileCache[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true){
1981
+ var _step_value = _sliced_to_array(_step.value, 1), key = _step_value[0];
1982
+ if (key.startsWith(path)) {
1983
+ this.fileCache.delete(key);
1984
+ this.existsCache.set(key, false);
1985
+ }
1986
+ }
1987
+ } catch (err) {
1988
+ _didIteratorError = true;
1989
+ _iteratorError = err;
1990
+ } finally{
1991
+ try {
1992
+ if (!_iteratorNormalCompletion && _iterator.return != null) {
1993
+ _iterator.return();
1994
+ }
1995
+ } finally{
1996
+ if (_didIteratorError) {
1997
+ throw _iteratorError;
1998
+ }
1999
+ }
2000
+ }
2001
+ this.indexedDBHelper.deleteCachedFolderCallback(path).catch(function(error) {
2002
+ console.error('Error deleting cached folder:', error);
2003
+ });
2004
+ }
2005
+ },
2006
+ {
2007
+ key: "deleteCachedFileCallback",
2008
+ value: function deleteCachedFileCallback(path) {
2009
+ var _this = this;
2010
+ if (!this.isReady) {
2011
+ console.warn('IndexedDB not ready yet, queuing operation');
2012
+ this.initPromise.then(function() {
2013
+ _this.indexedDBHelper.deleteCachedFileCallback(path);
2014
+ });
2015
+ return;
2016
+ }
2017
+ this.fileCache.delete(path);
2018
+ this.existsCache.set(path, false);
2019
+ this.indexedDBHelper.deleteCachedFileCallback(path).catch(function(error) {
2020
+ console.error('Error deleting cached file:', error);
2021
+ });
2022
+ }
2023
+ },
2024
+ {
2025
+ key: "getFilesInCachedFolderCallback",
2026
+ value: function getFilesInCachedFolderCallback(path) {
2027
+ var _this = this;
2028
+ if (!this.isReady) {
2029
+ console.warn('IndexedDB not ready yet, returning empty array');
2030
+ return [];
2031
+ }
2032
+ // Пытаемся получить из кэша
2033
+ var cachedFiles = [];
2034
+ var _iteratorNormalCompletion = true, _didIteratorError = false, _iteratorError = undefined;
2035
+ try {
2036
+ for(var _iterator = this.fileCache[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true){
2037
+ var _step_value = _sliced_to_array(_step.value, 1), key = _step_value[0];
2038
+ if (key.startsWith(path)) {
2039
+ var fileName = key.substring(path.length + 1);
2040
+ cachedFiles.push(fileName);
2041
+ }
2042
+ }
2043
+ } catch (err) {
2044
+ _didIteratorError = true;
2045
+ _iteratorError = err;
2046
+ } finally{
2047
+ try {
2048
+ if (!_iteratorNormalCompletion && _iterator.return != null) {
2049
+ _iterator.return();
2050
+ }
2051
+ } finally{
2052
+ if (_didIteratorError) {
2053
+ throw _iteratorError;
2054
+ }
2055
+ }
2056
+ }
2057
+ // Асинхронно обновляем кэш
2058
+ this.indexedDBHelper.getFilesInCachedFolderCallback(path).then(function(files) {
2059
+ // Обновляем информацию о существующих файлах
2060
+ files.forEach(function(fileName) {
2061
+ var cacheKey = "".concat(path, "/").concat(fileName);
2062
+ _this.existsCache.set(cacheKey, true);
2063
+ });
2064
+ }).catch(function(error) {
2065
+ console.error('Error getting files in cached folder:', error);
2066
+ });
2067
+ return cachedFiles;
2068
+ }
2069
+ },
2070
+ {
2071
+ key: "applyTempFolderCallback",
2072
+ value: function applyTempFolderCallback(tempFolder) {
2073
+ var _this = this;
2074
+ if (!this.isReady) {
2075
+ console.warn('IndexedDB not ready yet, queuing operation');
2076
+ this.initPromise.then(function() {
2077
+ _this.indexedDBHelper.applyTempFolderCallback(tempFolder);
2078
+ });
2079
+ return;
2080
+ }
2081
+ this.indexedDBHelper.applyTempFolderCallback(tempFolder).catch(function(error) {
2082
+ console.error('Error applying temp folder:', error);
2083
+ });
2084
+ }
2085
+ },
2086
+ {
2087
+ key: "preloadCache",
2088
+ value: function preloadCache() {
2089
+ var _this = this;
2090
+ return _async_to_generator$1(function() {
2091
+ var cacheFiles, _iteratorNormalCompletion, _didIteratorError, _iteratorError, _iterator, _step, fileName, data, error, err, error1;
2092
+ return _ts_generator$1(this, function(_state) {
2093
+ switch(_state.label){
2094
+ case 0:
2095
+ return [
2096
+ 4,
2097
+ _this.waitForReady()
2098
+ ];
2099
+ case 1:
2100
+ _state.sent();
2101
+ _state.label = 2;
2102
+ case 2:
2103
+ _state.trys.push([
2104
+ 2,
2105
+ 14,
2106
+ ,
2107
+ 15
2108
+ ]);
2109
+ return [
2110
+ 4,
2111
+ _this.indexedDBHelper.getFilesInCachedFolderCallback('')
2112
+ ];
2113
+ case 3:
2114
+ cacheFiles = _state.sent();
2115
+ _iteratorNormalCompletion = true, _didIteratorError = false, _iteratorError = undefined;
2116
+ _state.label = 4;
2117
+ case 4:
2118
+ _state.trys.push([
2119
+ 4,
2120
+ 11,
2121
+ 12,
2122
+ 13
2123
+ ]);
2124
+ _iterator = cacheFiles[Symbol.iterator]();
2125
+ _state.label = 5;
2126
+ case 5:
2127
+ if (!!(_iteratorNormalCompletion = (_step = _iterator.next()).done)) return [
2128
+ 3,
2129
+ 10
2130
+ ];
2131
+ fileName = _step.value;
2132
+ _state.label = 6;
2133
+ case 6:
2134
+ _state.trys.push([
2135
+ 6,
2136
+ 8,
2137
+ ,
2138
+ 9
2139
+ ]);
2140
+ return [
2141
+ 4,
2142
+ _this.indexedDBHelper.loadFileFromCacheCallback(fileName)
2143
+ ];
2144
+ case 7:
2145
+ data = _state.sent();
2146
+ if (data) {
2147
+ _this.fileCache.set(fileName, data);
2148
+ _this.existsCache.set(fileName, true);
2149
+ }
2150
+ return [
2151
+ 3,
2152
+ 9
2153
+ ];
2154
+ case 8:
2155
+ error = _state.sent();
2156
+ console.error("Error preloading file ".concat(fileName, ":"), error);
2157
+ return [
2158
+ 3,
2159
+ 9
2160
+ ];
2161
+ case 9:
2162
+ _iteratorNormalCompletion = true;
2163
+ return [
2164
+ 3,
2165
+ 5
2166
+ ];
2167
+ case 10:
2168
+ return [
2169
+ 3,
2170
+ 13
2171
+ ];
2172
+ case 11:
2173
+ err = _state.sent();
2174
+ _didIteratorError = true;
2175
+ _iteratorError = err;
2176
+ return [
2177
+ 3,
2178
+ 13
2179
+ ];
2180
+ case 12:
2181
+ try {
2182
+ if (!_iteratorNormalCompletion && _iterator.return != null) {
2183
+ _iterator.return();
2184
+ }
2185
+ } finally{
2186
+ if (_didIteratorError) {
2187
+ throw _iteratorError;
2188
+ }
2189
+ }
2190
+ return [
2191
+ 7
2192
+ ];
2193
+ case 13:
2194
+ console.log("Preloaded ".concat(cacheFiles.length, " files into memory cache"));
2195
+ return [
2196
+ 3,
2197
+ 15
2198
+ ];
2199
+ case 14:
2200
+ error1 = _state.sent();
2201
+ console.error('Error during cache preload:', error1);
2202
+ return [
2203
+ 3,
2204
+ 15
2205
+ ];
2206
+ case 15:
2207
+ return [
2208
+ 2
2209
+ ];
2210
+ }
2211
+ });
2212
+ })();
2213
+ }
2214
+ },
2215
+ {
2216
+ key: "preloadEverything",
2217
+ value: function preloadEverything() {
2218
+ var _this = this;
2219
+ return _async_to_generator$1(function() {
2220
+ var totalFiles, totalSize, allFiles, _iteratorNormalCompletion, _didIteratorError, _iteratorError, _iterator, _step, fileInfo, data, cacheKey, uint8Array, error, err, sampleKeys, error1;
2221
+ return _ts_generator$1(this, function(_state) {
2222
+ switch(_state.label){
2223
+ case 0:
2224
+ return [
2225
+ 4,
2226
+ _this.waitForReady()
2227
+ ];
2228
+ case 1:
2229
+ _state.sent();
2230
+ console.log('🚀 Starting full preload of all files...');
2231
+ totalFiles = 0;
2232
+ totalSize = 0;
2233
+ _state.label = 2;
2234
+ case 2:
2235
+ _state.trys.push([
2236
+ 2,
2237
+ 14,
2238
+ ,
2239
+ 15
2240
+ ]);
2241
+ return [
2242
+ 4,
2243
+ _this.getAllFilesFromIndexedDB()
2244
+ ];
2245
+ case 3:
2246
+ allFiles = _state.sent();
2247
+ console.log('🗂️ All files in IndexedDB:', allFiles.length);
2248
+ _iteratorNormalCompletion = true, _didIteratorError = false, _iteratorError = undefined;
2249
+ _state.label = 4;
2250
+ case 4:
2251
+ _state.trys.push([
2252
+ 4,
2253
+ 11,
2254
+ 12,
2255
+ 13
2256
+ ]);
2257
+ _iterator = allFiles[Symbol.iterator]();
2258
+ _state.label = 5;
2259
+ case 5:
2260
+ if (!!(_iteratorNormalCompletion = (_step = _iterator.next()).done)) return [
2261
+ 3,
2262
+ 10
2263
+ ];
2264
+ fileInfo = _step.value;
2265
+ _state.label = 6;
2266
+ case 6:
2267
+ _state.trys.push([
2268
+ 6,
2269
+ 8,
2270
+ ,
2271
+ 9
2272
+ ]);
2273
+ data = null;
2274
+ cacheKey = '';
2275
+ return [
2276
+ 4,
2277
+ _this.indexedDBHelper.loadFile(fileInfo.directory, fileInfo.fileName)
2278
+ ];
2279
+ case 7:
2280
+ // Определяем как загружать файл в зависимости от директории
2281
+ // if (fileInfo.directory.includes('cache') || fileInfo.directory === '.balancy') {
2282
+ // data = await this.indexedDBHelper.loadFileFromCacheCallback(fileInfo.fileName);
2283
+ // console.log("*** " + fileInfo.fileName + " :: " + data.length + " == " + data);
2284
+ // cacheKey = `${fileInfo.fileName}`;
2285
+ // } else if (fileInfo.directory.includes('resources')) {
2286
+ // data = await this.indexedDBHelper.loadFileFromResourcesCallback(fileInfo.fileName);
2287
+ // cacheKey = `resources/${fileInfo.fileName}`;
2288
+ // } else {
2289
+ // Используем общий метод loadFile для всех остальных директорий
2290
+ data = _state.sent();
2291
+ cacheKey = fileInfo.fileName;
2292
+ // }
2293
+ if (data) {
2294
+ // Для ВСЕХ файлов (включая бинарные) сохраняем как есть
2295
+ if (_instanceof$1(data, ArrayBuffer)) {
2296
+ // Сохраняем бинарные данные как Uint8Array для прямого доступа
2297
+ uint8Array = new Uint8Array(data);
2298
+ _this.fileCache.set(cacheKey, uint8Array);
2299
+ totalSize += uint8Array.byteLength;
2300
+ // console.log(`✅ Loaded BINARY: ${cacheKey} (${uint8Array.byteLength} bytes)`);
2301
+ } else {
2302
+ // Текстовые файлы сохраняем как строки
2303
+ _this.fileCache.set(cacheKey, data);
2304
+ totalSize += data.length;
2305
+ // console.log(`✅ Loaded TEXT: ${cacheKey} (${data.length} chars)`);
2306
+ }
2307
+ _this.existsCache.set(cacheKey, true);
2308
+ totalFiles++;
2309
+ }
2310
+ return [
2311
+ 3,
2312
+ 9
2313
+ ];
2314
+ case 8:
2315
+ error = _state.sent();
2316
+ console.error("❌ Error preloading file ".concat(fileInfo.directory, "/").concat(fileInfo.fileName, ":"), error);
2317
+ return [
2318
+ 3,
2319
+ 9
2320
+ ];
2321
+ case 9:
2322
+ _iteratorNormalCompletion = true;
2323
+ return [
2324
+ 3,
2325
+ 5
2326
+ ];
2327
+ case 10:
2328
+ return [
2329
+ 3,
2330
+ 13
2331
+ ];
2332
+ case 11:
2333
+ err = _state.sent();
2334
+ _didIteratorError = true;
2335
+ _iteratorError = err;
2336
+ return [
2337
+ 3,
2338
+ 13
2339
+ ];
2340
+ case 12:
2341
+ try {
2342
+ if (!_iteratorNormalCompletion && _iterator.return != null) {
2343
+ _iterator.return();
2344
+ }
2345
+ } finally{
2346
+ if (_didIteratorError) {
2347
+ throw _iteratorError;
2348
+ }
2349
+ }
2350
+ return [
2351
+ 7
2352
+ ];
2353
+ case 13:
2354
+ console.log("✅ Full preload completed: ".concat(totalFiles, " files (").concat(_this.formatBytes(totalSize), ") loaded into memory"));
2355
+ console.log("\uD83D\uDCCA Memory cache size: ".concat(_this.fileCache.size, " files, exists cache: ").concat(_this.existsCache.size, " entries"));
2356
+ // Показываем примеры ключей в кэше
2357
+ sampleKeys = Array.from(_this.fileCache.keys()).slice(0, 5);
2358
+ console.log('🔍 Sample cached keys:', sampleKeys);
2359
+ return [
2360
+ 3,
2361
+ 15
2362
+ ];
2363
+ case 14:
2364
+ error1 = _state.sent();
2365
+ console.error('❌ Error during full preload:', error1);
2366
+ throw error1;
2367
+ case 15:
2368
+ return [
2369
+ 2
2370
+ ];
2371
+ }
2372
+ });
2373
+ })();
2374
+ }
2375
+ },
2376
+ {
2377
+ key: "getAllFilesFromIndexedDB",
2378
+ value: function getAllFilesFromIndexedDB() {
2379
+ var _this = this;
2380
+ return _async_to_generator$1(function() {
2381
+ var db;
2382
+ return _ts_generator$1(this, function(_state) {
2383
+ switch(_state.label){
2384
+ case 0:
2385
+ return [
2386
+ 4,
2387
+ _this.waitForReady()
2388
+ ];
2389
+ case 1:
2390
+ _state.sent();
2391
+ db = _this.indexedDBHelper.getDatabase();
2392
+ if (!db) {
2393
+ console.warn('Database not available for file enumeration');
2394
+ return [
2395
+ 2,
2396
+ []
2397
+ ];
2398
+ }
2399
+ return [
2400
+ 2,
2401
+ new Promise(function(resolve, reject) {
2402
+ var transaction = db.transaction([
2403
+ 'files'
2404
+ ], 'readonly');
2405
+ var store = transaction.objectStore('files');
2406
+ var files = [];
2407
+ var request = store.openCursor();
2408
+ request.onsuccess = function(event) {
2409
+ var target = event.target;
2410
+ var cursor = target.result;
2411
+ if (cursor) {
2412
+ var record = cursor.value;
2413
+ record.fileName.split('/');
2414
+ files.push({
2415
+ // fileName: record.fileName.split('/').pop() || record.fileName,
2416
+ fileName: record.fileName.substring(record.directory.length + 1),
2417
+ directory: record.directory,
2418
+ fileType: record.fileType || 'text'
2419
+ });
2420
+ cursor.continue();
2421
+ } else {
2422
+ resolve(files);
2423
+ }
2424
+ };
2425
+ request.onerror = function() {
2426
+ console.error('Error reading files from IndexedDB');
2427
+ reject(request.error);
2428
+ };
2429
+ })
2430
+ ];
2431
+ }
2432
+ });
2433
+ })();
2434
+ }
2435
+ },
2436
+ {
2437
+ key: "arrayBufferToBase64",
2438
+ value: function arrayBufferToBase64(buffer) {
2439
+ var bytes = new Uint8Array(buffer);
2440
+ var binary = '';
2441
+ for(var i = 0; i < bytes.byteLength; i++){
2442
+ binary += String.fromCharCode(bytes[i]);
2443
+ }
2444
+ return btoa(binary);
2445
+ }
2446
+ },
2447
+ {
2448
+ key: "formatBytes",
2449
+ value: function formatBytes(bytes) {
2450
+ if (bytes === 0) return '0 Bytes';
2451
+ var k = 1024;
2452
+ var sizes = [
2453
+ 'Bytes',
2454
+ 'KB',
2455
+ 'MB',
2456
+ 'GB'
2457
+ ];
2458
+ var i = Math.floor(Math.log(bytes) / Math.log(k));
2459
+ return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
2460
+ }
2461
+ },
2462
+ {
2463
+ key: "getCacheStats",
2464
+ value: function getCacheStats() {
2465
+ var totalSize = 0;
2466
+ var _iteratorNormalCompletion = true, _didIteratorError = false, _iteratorError = undefined;
2467
+ try {
2468
+ for(var _iterator = this.fileCache[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true){
2469
+ var _step_value = _sliced_to_array(_step.value, 2), data = _step_value[1];
2470
+ if (typeof data === 'string') {
2471
+ totalSize += data.length;
2472
+ } else if (_instanceof$1(data, Uint8Array)) {
2473
+ totalSize += data.byteLength;
2474
+ }
2475
+ }
2476
+ } catch (err) {
2477
+ _didIteratorError = true;
2478
+ _iteratorError = err;
2479
+ } finally{
2480
+ try {
2481
+ if (!_iteratorNormalCompletion && _iterator.return != null) {
2482
+ _iterator.return();
2483
+ }
2484
+ } finally{
2485
+ if (_didIteratorError) {
2486
+ throw _iteratorError;
2487
+ }
2488
+ }
2489
+ }
2490
+ return {
2491
+ fileCount: this.fileCache.size,
2492
+ memoryUsage: this.formatBytes(totalSize)
2493
+ };
2494
+ }
2495
+ },
2496
+ {
2497
+ key: "clearMemoryCache",
2498
+ value: function clearMemoryCache() {
2499
+ this.fileCache.clear();
2500
+ this.existsCache.clear();
2501
+ console.log('Memory cache cleared');
2502
+ }
2503
+ },
2504
+ {
2505
+ key: "close",
2506
+ value: function close() {
2507
+ this.fileCache.clear();
2508
+ this.existsCache.clear();
2509
+ this.indexedDBHelper.close();
2510
+ }
2511
+ },
2512
+ {
2513
+ key: "loadFile",
2514
+ value: function loadFile(directory, fileName) {
2515
+ var _this = this;
2516
+ return _async_to_generator$1(function() {
2517
+ return _ts_generator$1(this, function(_state) {
2518
+ switch(_state.label){
2519
+ case 0:
2520
+ return [
2521
+ 4,
2522
+ _this.indexedDBHelper.loadFile(directory, fileName)
2523
+ ];
2524
+ case 1:
2525
+ return [
2526
+ 2,
2527
+ _state.sent()
2528
+ ];
2529
+ }
2530
+ });
2531
+ })();
2532
+ }
2533
+ },
2534
+ {
2535
+ key: "getIndexedDBHelper",
2536
+ value: function getIndexedDBHelper() {
2537
+ return this.indexedDBHelper;
2538
+ }
2539
+ },
2540
+ {
2541
+ key: "setSpriteLoader",
2542
+ value: function setSpriteLoader(loader) {
2543
+ this.indexedDBHelper.setSpriteLoader(loader);
2544
+ }
2545
+ },
2546
+ {
2547
+ key: "getBinaryFile",
2548
+ value: function getBinaryFile(key) {
2549
+ var _this = this;
2550
+ return _async_to_generator$1(function() {
2551
+ var cacheKey, cachedData, data, binaryData, error;
2552
+ return _ts_generator$1(this, function(_state) {
2553
+ switch(_state.label){
2554
+ case 0:
2555
+ // console.log("==>> getBinaryFile:", key);
2556
+ return [
2557
+ 4,
2558
+ _this.waitForReady()
2559
+ ];
2560
+ case 1:
2561
+ _state.sent();
2562
+ // Проверяем кэш в памяти
2563
+ cacheKey = "".concat(key);
2564
+ if (_this.fileCache.has(cacheKey)) {
2565
+ cachedData = _this.fileCache.get(cacheKey);
2566
+ // console.log("==>> Found in memory cache");
2567
+ if (_instanceof$1(cachedData, Uint8Array)) {
2568
+ return [
2569
+ 2,
2570
+ cachedData
2571
+ ];
2572
+ } else if (typeof cachedData === 'string') {
2573
+ // Попытка декодировать base64
2574
+ try {
2575
+ return [
2576
+ 2,
2577
+ _this.base64ToUint8Array(cachedData)
2578
+ ];
2579
+ } catch (error) {
2580
+ console.warn('Failed to decode base64, trying as text:', error);
2581
+ return [
2582
+ 2,
2583
+ new TextEncoder().encode(cachedData)
2584
+ ];
2585
+ }
2586
+ }
2587
+ }
2588
+ _state.label = 2;
2589
+ case 2:
2590
+ _state.trys.push([
2591
+ 2,
2592
+ 4,
2593
+ ,
2594
+ 5
2595
+ ]);
2596
+ return [
2597
+ 4,
2598
+ _this.indexedDBHelper.loadFile('.balancy', key)
2599
+ ];
2600
+ case 3:
2601
+ data = _state.sent();
2602
+ if (data) {
2603
+ if (_instanceof$1(data, ArrayBuffer)) {
2604
+ binaryData = new Uint8Array(data);
2605
+ } else {
2606
+ // Если это строка, пробуем декодировать как base64
2607
+ try {
2608
+ binaryData = _this.base64ToUint8Array(data);
2609
+ } catch (e) {
2610
+ binaryData = new TextEncoder().encode(data);
2611
+ }
2612
+ }
2613
+ // Кэшируем для будущих вызов
2614
+ _this.fileCache.set(cacheKey, binaryData);
2615
+ _this.existsCache.set(cacheKey, true);
2616
+ // console.log("==>> Successfully loaded binary data:", binaryData.length, "bytes");
2617
+ return [
2618
+ 2,
2619
+ binaryData
2620
+ ];
2621
+ }
2622
+ return [
2623
+ 3,
2624
+ 5
2625
+ ];
2626
+ case 4:
2627
+ error = _state.sent();
2628
+ console.error('Error loading binary file:', error);
2629
+ return [
2630
+ 3,
2631
+ 5
2632
+ ];
2633
+ case 5:
2634
+ console.log("==>> Binary file not found");
2635
+ return [
2636
+ 2,
2637
+ null
2638
+ ];
2639
+ }
2640
+ });
2641
+ })();
2642
+ }
2643
+ },
2644
+ {
2645
+ key: "base64ToUint8Array",
2646
+ value: function base64ToUint8Array(base64) {
2647
+ var binaryString = atob(base64);
2648
+ var bytes = new Uint8Array(binaryString.length);
2649
+ for(var i = 0; i < binaryString.length; i++){
2650
+ bytes[i] = binaryString.charCodeAt(i);
2651
+ }
2652
+ return bytes;
2653
+ }
2654
+ },
2655
+ {
2656
+ key: "saveBinaryFile",
2657
+ value: function saveBinaryFile(key, data) {
2658
+ var _this = this;
2659
+ return _async_to_generator$1(function() {
2660
+ var cacheKey, arrayBuffer, error;
2661
+ return _ts_generator$1(this, function(_state) {
2662
+ switch(_state.label){
2663
+ case 0:
2664
+ _state.trys.push([
2665
+ 0,
2666
+ 3,
2667
+ ,
2668
+ 4
2669
+ ]);
2670
+ return [
2671
+ 4,
2672
+ _this.waitForReady()
2673
+ ];
2674
+ case 1:
2675
+ _state.sent();
2676
+ // Кэшируем в памяти
2677
+ cacheKey = "".concat(key);
2678
+ _this.fileCache.set(cacheKey, new Uint8Array(data)); // Создаем копию
2679
+ _this.existsCache.set(cacheKey, true);
2680
+ // console.log("Saving:: " + key);
2681
+ // Сохраняем в IndexedDB
2682
+ arrayBuffer = data.buffer.slice(data.byteOffset, data.byteOffset + data.byteLength);
2683
+ return [
2684
+ 4,
2685
+ _this.indexedDBHelper.saveFileInCacheBinaryCallback(key, arrayBuffer)
2686
+ ];
2687
+ case 2:
2688
+ _state.sent();
2689
+ return [
2690
+ 2,
2691
+ true
2692
+ ];
2693
+ case 3:
2694
+ error = _state.sent();
2695
+ console.error('Error saving binary file:', error);
2696
+ return [
2697
+ 2,
2698
+ false
2699
+ ];
2700
+ case 4:
2701
+ return [
2702
+ 2
2703
+ ];
2704
+ }
2705
+ });
2706
+ })();
2707
+ }
2708
+ },
2709
+ {
2710
+ key: "hasFile",
2711
+ value: function hasFile(key) {
2712
+ var _this = this;
2713
+ return _async_to_generator$1(function() {
2714
+ var cacheKey, exists, error;
2715
+ return _ts_generator$1(this, function(_state) {
2716
+ switch(_state.label){
2717
+ case 0:
2718
+ cacheKey = "".concat(key);
2719
+ // Проверяем кэш в памяти
2720
+ if (_this.existsCache.has(cacheKey)) {
2721
+ return [
2722
+ 2,
2723
+ _this.existsCache.get(cacheKey)
2724
+ ];
2725
+ }
2726
+ if (!_this.isReady) return [
2727
+ 3,
2728
+ 4
2729
+ ];
2730
+ _state.label = 1;
2731
+ case 1:
2732
+ _state.trys.push([
2733
+ 1,
2734
+ 3,
2735
+ ,
2736
+ 4
2737
+ ]);
2738
+ return [
2739
+ 4,
2740
+ _this.indexedDBHelper.fileExistsInCacheCallback(key)
2741
+ ];
2742
+ case 2:
2743
+ exists = _state.sent();
2744
+ _this.existsCache.set(cacheKey, exists);
2745
+ return [
2746
+ 2,
2747
+ exists
2748
+ ];
2749
+ case 3:
2750
+ error = _state.sent();
2751
+ console.error('Error checking file existence:', error);
2752
+ return [
2753
+ 2,
2754
+ false
2755
+ ];
2756
+ case 4:
2757
+ return [
2758
+ 2,
2759
+ false
2760
+ ];
2761
+ }
2762
+ });
2763
+ })();
2764
+ }
2765
+ },
2766
+ {
2767
+ key: "deleteFile",
2768
+ value: function deleteFile(key) {
2769
+ var _this = this;
2770
+ return _async_to_generator$1(function() {
2771
+ var cacheKey, error;
2772
+ return _ts_generator$1(this, function(_state) {
2773
+ switch(_state.label){
2774
+ case 0:
2775
+ _state.trys.push([
2776
+ 0,
2777
+ 3,
2778
+ ,
2779
+ 4
2780
+ ]);
2781
+ return [
2782
+ 4,
2783
+ _this.waitForReady()
2784
+ ];
2785
+ case 1:
2786
+ _state.sent();
2787
+ cacheKey = "".concat(key);
2788
+ _this.fileCache.delete(cacheKey);
2789
+ _this.existsCache.set(cacheKey, false);
2790
+ return [
2791
+ 4,
2792
+ _this.indexedDBHelper.deleteCachedFileCallback(key)
2793
+ ];
2794
+ case 2:
2795
+ _state.sent();
2796
+ return [
2797
+ 2,
2798
+ true
2799
+ ];
2800
+ case 3:
2801
+ error = _state.sent();
2802
+ console.error('Error deleting file:', error);
2803
+ return [
2804
+ 2,
2805
+ false
2806
+ ];
2807
+ case 4:
2808
+ return [
2809
+ 2
2810
+ ];
2811
+ }
2812
+ });
2813
+ })();
2814
+ }
2815
+ },
2816
+ {
2817
+ key: "clearCache",
2818
+ value: function clearCache() {
2819
+ var _this = this;
2820
+ return _async_to_generator$1(function() {
2821
+ var error;
2822
+ return _ts_generator$1(this, function(_state) {
2823
+ switch(_state.label){
2824
+ case 0:
2825
+ _state.trys.push([
2826
+ 0,
2827
+ 2,
2828
+ ,
2829
+ 3
2830
+ ]);
2831
+ return [
2832
+ 4,
2833
+ _this.waitForReady()
2834
+ ];
2835
+ case 1:
2836
+ _state.sent();
2837
+ // Очищаем кэш в памяти
2838
+ _this.fileCache.clear();
2839
+ _this.existsCache.clear();
2840
+ // Очищаем IndexedDB (здесь нужно добавить метод в IndexedDBFileHelper)
2841
+ // Пока просто очищаем кэш в памяти
2842
+ return [
2843
+ 2,
2844
+ true
2845
+ ];
2846
+ case 2:
2847
+ error = _state.sent();
2848
+ console.error('Error clearing cache:', error);
2849
+ return [
2850
+ 2,
2851
+ false
2852
+ ];
2853
+ case 3:
2854
+ return [
2855
+ 2
2856
+ ];
2857
+ }
2858
+ });
2859
+ })();
2860
+ }
2861
+ }
2862
+ ], [
2863
+ {
2864
+ key: "create",
2865
+ value: function create(paths) {
2866
+ var fullPreload = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : true;
2867
+ return _async_to_generator$1(function() {
2868
+ var adapter;
2869
+ return _ts_generator$1(this, function(_state) {
2870
+ switch(_state.label){
2871
+ case 0:
2872
+ adapter = new IndexedDBFileHelperAdapter(paths);
2873
+ return [
2874
+ 4,
2875
+ adapter.waitForReady()
2876
+ ];
2877
+ case 1:
2878
+ _state.sent();
2879
+ if (!fullPreload) return [
2880
+ 3,
2881
+ 3
2882
+ ];
2883
+ return [
2884
+ 4,
2885
+ adapter.preloadEverything()
2886
+ ];
2887
+ case 2:
2888
+ _state.sent(); // ПОЛНАЯ предзагрузка
2889
+ _state.label = 3;
2890
+ case 3:
2891
+ return [
2892
+ 2,
2893
+ adapter
2894
+ ];
2895
+ }
2896
+ });
2897
+ })();
2898
+ }
2899
+ },
2900
+ {
2901
+ key: "createFast",
2902
+ value: function createFast(paths) {
2903
+ return _async_to_generator$1(function() {
2904
+ return _ts_generator$1(this, function(_state) {
2905
+ switch(_state.label){
2906
+ case 0:
2907
+ return [
2908
+ 4,
2909
+ IndexedDBFileHelperAdapter.create(paths, false)
2910
+ ];
2911
+ case 1:
2912
+ return [
2913
+ 2,
2914
+ _state.sent()
2915
+ ];
2916
+ }
2917
+ });
2918
+ })();
2919
+ }
2920
+ },
2921
+ {
2922
+ key: "createWithPartialPreload",
2923
+ value: function createWithPartialPreload(paths) {
2924
+ return _async_to_generator$1(function() {
2925
+ var adapter;
2926
+ return _ts_generator$1(this, function(_state) {
2927
+ switch(_state.label){
2928
+ case 0:
2929
+ adapter = new IndexedDBFileHelperAdapter(paths);
2930
+ return [
2931
+ 4,
2932
+ adapter.waitForReady()
2933
+ ];
2934
+ case 1:
2935
+ _state.sent();
2936
+ return [
2937
+ 4,
2938
+ adapter.preloadCache()
2939
+ ];
2940
+ case 2:
2941
+ _state.sent(); // Только cache, не все
2942
+ return [
2943
+ 2,
2944
+ adapter
2945
+ ];
2946
+ }
2947
+ });
2948
+ })();
2949
+ }
2950
+ }
2951
+ ]);
2952
+ return IndexedDBFileHelperAdapter;
2953
+ }();
2954
+
2955
+ // @balancy/utils - Utility functions and helpers for Balancy
2956
+ // ============================================
2957
+ // IndexedDB File Helper (основной функционал)
2958
+ // ============================================
2959
+ function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
2960
+ try {
2961
+ var info = gen[key](arg);
2962
+ var value = info.value;
2963
+ } catch (error) {
2964
+ reject(error);
2965
+ return;
2966
+ }
2967
+ if (info.done) {
2968
+ resolve(value);
2969
+ } else {
2970
+ Promise.resolve(value).then(_next, _throw);
2971
+ }
2972
+ }
2973
+ function _async_to_generator(fn) {
2974
+ return function() {
2975
+ var self = this, args = arguments;
2976
+ return new Promise(function(resolve, reject) {
2977
+ var gen = fn.apply(self, args);
2978
+ function _next(value) {
2979
+ asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
2980
+ }
2981
+ function _throw(err) {
2982
+ asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
2983
+ }
2984
+ _next(undefined);
2985
+ });
2986
+ };
2987
+ }
2988
+ function _instanceof(left, right) {
2989
+ if (right != null && typeof Symbol !== "undefined" && right[Symbol.hasInstance]) {
2990
+ return !!right[Symbol.hasInstance](left);
2991
+ } else {
2992
+ return left instanceof right;
2993
+ }
2994
+ }
2995
+ function _type_of(obj) {
2996
+ "@swc/helpers - typeof";
2997
+ return obj && typeof Symbol !== "undefined" && obj.constructor === Symbol ? "symbol" : typeof obj;
2998
+ }
2999
+ function _ts_generator(thisArg, body) {
3000
+ var f, y, t, g, _ = {
3001
+ label: 0,
3002
+ sent: function() {
3003
+ if (t[0] & 1) throw t[1];
3004
+ return t[1];
3005
+ },
3006
+ trys: [],
3007
+ ops: []
3008
+ };
3009
+ return g = {
3010
+ next: verb(0),
3011
+ "throw": verb(1),
3012
+ "return": verb(2)
3013
+ }, typeof Symbol === "function" && (g[Symbol.iterator] = function() {
3014
+ return this;
3015
+ }), g;
3016
+ function verb(n) {
3017
+ return function(v) {
3018
+ return step([
3019
+ n,
3020
+ v
3021
+ ]);
3022
+ };
3023
+ }
3024
+ function step(op) {
3025
+ if (f) throw new TypeError("Generator is already executing.");
3026
+ while(_)try {
3027
+ if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
3028
+ if (y = 0, t) op = [
3029
+ op[0] & 2,
3030
+ t.value
3031
+ ];
3032
+ switch(op[0]){
3033
+ case 0:
3034
+ case 1:
3035
+ t = op;
3036
+ break;
3037
+ case 4:
3038
+ _.label++;
3039
+ return {
3040
+ value: op[1],
3041
+ done: false
3042
+ };
3043
+ case 5:
3044
+ _.label++;
3045
+ y = op[1];
3046
+ op = [
3047
+ 0
3048
+ ];
3049
+ continue;
3050
+ case 7:
3051
+ op = _.ops.pop();
3052
+ _.trys.pop();
3053
+ continue;
3054
+ default:
3055
+ if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) {
3056
+ _ = 0;
3057
+ continue;
3058
+ }
3059
+ if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) {
3060
+ _.label = op[1];
3061
+ break;
3062
+ }
3063
+ if (op[0] === 6 && _.label < t[1]) {
3064
+ _.label = t[1];
3065
+ t = op;
3066
+ break;
3067
+ }
3068
+ if (t && _.label < t[2]) {
3069
+ _.label = t[2];
3070
+ _.ops.push(op);
3071
+ break;
3072
+ }
3073
+ if (t[2]) _.ops.pop();
3074
+ _.trys.pop();
3075
+ continue;
3076
+ }
3077
+ op = body.call(thisArg, _);
3078
+ } catch (e) {
3079
+ op = [
3080
+ 6,
3081
+ e
3082
+ ];
3083
+ y = 0;
3084
+ } finally{
3085
+ f = t = 0;
3086
+ }
3087
+ if (op[0] & 5) throw op[1];
3088
+ return {
3089
+ value: op[0] ? op[1] : void 0,
3090
+ done: true
3091
+ };
3092
+ }
3093
+ }
3094
+ // ============================================
3095
+ // General Utility Functions
3096
+ // ============================================
3097
+ /**
3098
+ * Проверяет, является ли значение пустым (null, undefined, пустая строка, пустой массив, пустой объект)
3099
+ */ function isEmpty(value) {
3100
+ if (value == null) return true;
3101
+ if (typeof value === 'string') return value.trim().length === 0;
3102
+ if (Array.isArray(value)) return value.length === 0;
3103
+ if ((typeof value === "undefined" ? "undefined" : _type_of(value)) === 'object') return Object.keys(value).length === 0;
3104
+ return false;
3105
+ }
3106
+ /**
3107
+ * Глубокое клонирование объекта
3108
+ */ function deepClone(obj) {
3109
+ if (obj === null || (typeof obj === "undefined" ? "undefined" : _type_of(obj)) !== 'object') return obj;
3110
+ if (_instanceof(obj, Date)) return new Date(obj.getTime());
3111
+ if (_instanceof(obj, Array)) {
3112
+ return obj.map(function(item) {
3113
+ return deepClone(item);
3114
+ });
3115
+ }
3116
+ if ((typeof obj === "undefined" ? "undefined" : _type_of(obj)) === 'object') {
3117
+ var copy = {};
3118
+ Object.keys(obj).forEach(function(key) {
3119
+ copy[key] = deepClone(obj[key]);
3120
+ });
3121
+ return copy;
3122
+ }
3123
+ return obj;
3124
+ }
3125
+ /**
3126
+ * Форматирование чисел с разделителями тысяч
3127
+ */ function formatNumber(num) {
3128
+ var locale = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : 'en-US';
3129
+ return new Intl.NumberFormat(locale).format(num);
3130
+ }
3131
+ /**
3132
+ * Генерация случайного ID
3133
+ */ function generateId() {
3134
+ var length = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : 8;
3135
+ var chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
3136
+ var result = '';
3137
+ for(var i = 0; i < length; i++){
3138
+ result += chars.charAt(Math.floor(Math.random() * chars.length));
3139
+ }
3140
+ return result;
3141
+ }
3142
+ /**
3143
+ * Задержка выполнения (Promise-based sleep)
3144
+ */ function delay(ms) {
3145
+ return new Promise(function(resolve) {
3146
+ return setTimeout(resolve, ms);
3147
+ });
3148
+ }
3149
+ /**
3150
+ * Retry функция с экспоненциальной задержкой
3151
+ */ function retry(fn) {
3152
+ return _retry.apply(this, arguments);
3153
+ }
3154
+ function _retry() {
3155
+ _retry = _async_to_generator(function(fn) {
3156
+ var maxAttempts, baseDelay, attempt, error, delayMs;
3157
+ var _arguments = arguments;
3158
+ return _ts_generator(this, function(_state) {
3159
+ switch(_state.label){
3160
+ case 0:
3161
+ maxAttempts = _arguments.length > 1 && _arguments[1] !== void 0 ? _arguments[1] : 3, baseDelay = _arguments.length > 2 && _arguments[2] !== void 0 ? _arguments[2] : 1000;
3162
+ attempt = 0;
3163
+ _state.label = 1;
3164
+ case 1:
3165
+ if (!(attempt < maxAttempts)) return [
3166
+ 3,
3167
+ 7
3168
+ ];
3169
+ _state.label = 2;
3170
+ case 2:
3171
+ _state.trys.push([
3172
+ 2,
3173
+ 4,
3174
+ ,
3175
+ 6
3176
+ ]);
3177
+ return [
3178
+ 4,
3179
+ fn()
3180
+ ];
3181
+ case 3:
3182
+ return [
3183
+ 2,
3184
+ _state.sent()
3185
+ ];
3186
+ case 4:
3187
+ error = _state.sent();
3188
+ attempt++;
3189
+ if (attempt >= maxAttempts) {
3190
+ throw error;
3191
+ }
3192
+ delayMs = baseDelay * Math.pow(2, attempt - 1);
3193
+ return [
3194
+ 4,
3195
+ delay(delayMs)
3196
+ ];
3197
+ case 5:
3198
+ _state.sent();
3199
+ return [
3200
+ 3,
3201
+ 6
3202
+ ];
3203
+ case 6:
3204
+ return [
3205
+ 3,
3206
+ 1
3207
+ ];
3208
+ case 7:
3209
+ throw new Error('Max attempts reached');
3210
+ }
3211
+ });
3212
+ });
3213
+ return _retry.apply(this, arguments);
3214
+ }
3215
+ // Версия пакета
3216
+ var VERSION = '1.0.0-rc.24';
3217
+
3218
+ exports.IndexedDBFileHelper = IndexedDBFileHelper;
3219
+ exports.IndexedDBFileHelperAdapter = IndexedDBFileHelperAdapter;
3220
+ exports.VERSION = VERSION;
3221
+ exports.deepClone = deepClone;
3222
+ exports.delay = delay;
3223
+ exports.formatNumber = formatNumber;
3224
+ exports.generateId = generateId;
3225
+ exports.isEmpty = isEmpty;
3226
+ exports.retry = retry;
3227
+
3228
+ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
3229
+
3230
+ }));