@uipath/agent-tool 1.202.1 → 1.203.0-preview.180

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.
@@ -1,4241 +0,0 @@
1
- import {
2
- OutputFormatter,
3
- PersonalWorkspacesApi,
4
- RESULTS,
5
- addSdkUserAgentHeader,
6
- catchError,
7
- createApiClient,
8
- findSolutionFile,
9
- getFileSystem,
10
- getLoginStatusAsync,
11
- getSdkUserAgentToken,
12
- installSdkUserAgentHeader,
13
- logger,
14
- readUipxFile,
15
- summarizePlatformBody,
16
- updateSolutionFile,
17
- updateUipxSolutionId
18
- } from "./packager-tool-b20zvjv7.js";
19
- import {
20
- zipSync
21
- } from "./packager-tool-b098y4a2.js";
22
- import {
23
- __commonJS,
24
- __require,
25
- __toESM
26
- } from "./packager-tool-1yh8g550.js";
27
-
28
- // ../../node_modules/adm-zip/util/constants.js
29
- var require_constants = __commonJS(function(exports, module) {
30
- module.exports = {
31
- LOCHDR: 30,
32
- LOCSIG: 67324752,
33
- LOCVER: 4,
34
- LOCFLG: 6,
35
- LOCHOW: 8,
36
- LOCTIM: 10,
37
- LOCCRC: 14,
38
- LOCSIZ: 18,
39
- LOCLEN: 22,
40
- LOCNAM: 26,
41
- LOCEXT: 28,
42
- EXTSIG: 134695760,
43
- EXTHDR: 16,
44
- EXTCRC: 4,
45
- EXTSIZ: 8,
46
- EXTLEN: 12,
47
- CENHDR: 46,
48
- CENSIG: 33639248,
49
- CENVEM: 4,
50
- CENVER: 6,
51
- CENFLG: 8,
52
- CENHOW: 10,
53
- CENTIM: 12,
54
- CENCRC: 16,
55
- CENSIZ: 20,
56
- CENLEN: 24,
57
- CENNAM: 28,
58
- CENEXT: 30,
59
- CENCOM: 32,
60
- CENDSK: 34,
61
- CENATT: 36,
62
- CENATX: 38,
63
- CENOFF: 42,
64
- ENDHDR: 22,
65
- ENDSIG: 101010256,
66
- ENDSUB: 8,
67
- ENDTOT: 10,
68
- ENDSIZ: 12,
69
- ENDOFF: 16,
70
- ENDCOM: 20,
71
- END64HDR: 20,
72
- END64SIG: 117853008,
73
- END64START: 4,
74
- END64OFF: 8,
75
- END64NUMDISKS: 16,
76
- ZIP64SIG: 101075792,
77
- ZIP64HDR: 56,
78
- ZIP64LEAD: 12,
79
- ZIP64SIZE: 4,
80
- ZIP64VEM: 12,
81
- ZIP64VER: 14,
82
- ZIP64DSK: 16,
83
- ZIP64DSKDIR: 20,
84
- ZIP64SUB: 24,
85
- ZIP64TOT: 32,
86
- ZIP64SIZB: 40,
87
- ZIP64OFF: 48,
88
- ZIP64EXTRA: 56,
89
- STORED: 0,
90
- SHRUNK: 1,
91
- REDUCED1: 2,
92
- REDUCED2: 3,
93
- REDUCED3: 4,
94
- REDUCED4: 5,
95
- IMPLODED: 6,
96
- DEFLATED: 8,
97
- ENHANCED_DEFLATED: 9,
98
- PKWARE: 10,
99
- BZIP2: 12,
100
- LZMA: 14,
101
- IBM_TERSE: 18,
102
- IBM_LZ77: 19,
103
- AES_ENCRYPT: 99,
104
- FLG_ENC: 1,
105
- FLG_COMP1: 2,
106
- FLG_COMP2: 4,
107
- FLG_DESC: 8,
108
- FLG_ENH: 16,
109
- FLG_PATCH: 32,
110
- FLG_STR: 64,
111
- FLG_EFS: 2048,
112
- FLG_MSK: 4096,
113
- FILE: 2,
114
- BUFFER: 1,
115
- NONE: 0,
116
- EF_ID: 0,
117
- EF_SIZE: 2,
118
- ID_ZIP64: 1,
119
- ID_AVINFO: 7,
120
- ID_PFS: 8,
121
- ID_OS2: 9,
122
- ID_NTFS: 10,
123
- ID_OPENVMS: 12,
124
- ID_UNIX: 13,
125
- ID_FORK: 14,
126
- ID_PATCH: 15,
127
- ID_X509_PKCS7: 20,
128
- ID_X509_CERTID_F: 21,
129
- ID_X509_CERTID_C: 22,
130
- ID_STRONGENC: 23,
131
- ID_RECORD_MGT: 24,
132
- ID_X509_PKCS7_RL: 25,
133
- ID_IBM1: 101,
134
- ID_IBM2: 102,
135
- ID_POSZIP: 18064,
136
- EF_ZIP64_OR_32: 4294967295,
137
- EF_ZIP64_OR_16: 65535,
138
- EF_ZIP64_SUNCOMP: 0,
139
- EF_ZIP64_SCOMP: 8,
140
- EF_ZIP64_RHO: 16,
141
- EF_ZIP64_DSN: 24
142
- };
143
- });
144
-
145
- // ../../node_modules/adm-zip/util/errors.js
146
- var require_errors = __commonJS(function(exports) {
147
- var errors = {
148
- INVALID_LOC: "Invalid LOC header (bad signature)",
149
- INVALID_CEN: "Invalid CEN header (bad signature)",
150
- INVALID_END: "Invalid END header (bad signature)",
151
- DESCRIPTOR_NOT_EXIST: "No descriptor present",
152
- DESCRIPTOR_UNKNOWN: "Unknown descriptor format",
153
- DESCRIPTOR_FAULTY: "Descriptor data is malformed",
154
- NO_DATA: "Nothing to decompress",
155
- BAD_CRC: "CRC32 checksum failed {0}",
156
- MAX_OUTPUT_EXCEEDED: "Decompressed data exceeds the declared uncompressed size",
157
- FILE_IN_THE_WAY: "There is a file in the way: {0}",
158
- UNKNOWN_METHOD: "Invalid/unsupported compression method",
159
- AVAIL_DATA: "inflate::Available inflate data did not terminate",
160
- INVALID_DISTANCE: "inflate::Invalid literal/length or distance code in fixed or dynamic block",
161
- TO_MANY_CODES: "inflate::Dynamic block code description: too many length or distance codes",
162
- INVALID_REPEAT_LEN: "inflate::Dynamic block code description: repeat more than specified lengths",
163
- INVALID_REPEAT_FIRST: "inflate::Dynamic block code description: repeat lengths with no first length",
164
- INCOMPLETE_CODES: "inflate::Dynamic block code description: code lengths codes incomplete",
165
- INVALID_DYN_DISTANCE: "inflate::Dynamic block code description: invalid distance code lengths",
166
- INVALID_CODES_LEN: "inflate::Dynamic block code description: invalid literal/length code lengths",
167
- INVALID_STORE_BLOCK: "inflate::Stored block length did not match one's complement",
168
- INVALID_BLOCK_TYPE: "inflate::Invalid block type (type == 3)",
169
- CANT_EXTRACT_FILE: "Could not extract the file",
170
- CANT_OVERRIDE: "Target file already exists",
171
- DISK_ENTRY_TOO_LARGE: "Number of disk entries is too large",
172
- NO_ZIP: "No zip file was loaded",
173
- NO_ENTRY: "Entry doesn't exist",
174
- DUPLICATE_ENTRY: "Duplicate entry name {0}",
175
- DIRECTORY_CONTENT_ERROR: "A directory cannot have content",
176
- FILE_NOT_FOUND: 'File not found: "{0}"',
177
- NOT_IMPLEMENTED: "Not implemented",
178
- INVALID_FILENAME: "Invalid filename",
179
- INVALID_FORMAT: "Invalid or unsupported zip format. No END header found",
180
- ZIP64_VALUE_TOO_LARGE: "Zip64 value exceeds the maximum safe integer",
181
- INVALID_PASS_PARAM: "Incompatible password parameter",
182
- WRONG_PASSWORD: "Wrong Password",
183
- COMMENT_TOO_LONG: "Comment is too long",
184
- EXTRA_FIELD_PARSE_ERROR: "Extra field parsing error"
185
- };
186
- function E(message) {
187
- return function(...args) {
188
- if (args.length) {
189
- message = message.replace(/\{(\d)\}/g, (_, n) => args[n] || "");
190
- }
191
- return new Error("ADM-ZIP: " + message);
192
- };
193
- }
194
- for (const msg of Object.keys(errors)) {
195
- exports[msg] = E(errors[msg]);
196
- }
197
- });
198
-
199
- // ../../node_modules/adm-zip/util/utils.js
200
- var require_utils = __commonJS(function(exports, module) {
201
- var fsystem = __require("fs");
202
- var pth = __require("path");
203
- var Constants = require_constants();
204
- var Errors = require_errors();
205
- var isWin = typeof process === "object" && process.platform === "win32";
206
- var is_Obj = (obj) => typeof obj === "object" && obj !== null;
207
- var crcTable = new Uint32Array(256).map((t, c) => {
208
- for (let k = 0;k < 8; k++) {
209
- if ((c & 1) !== 0) {
210
- c = 3988292384 ^ c >>> 1;
211
- } else {
212
- c >>>= 1;
213
- }
214
- }
215
- return c >>> 0;
216
- });
217
- function Utils(opts) {
218
- this.sep = pth.sep;
219
- this.fs = fsystem;
220
- if (is_Obj(opts)) {
221
- if (is_Obj(opts.fs) && typeof opts.fs.statSync === "function") {
222
- this.fs = opts.fs;
223
- }
224
- }
225
- }
226
- module.exports = Utils;
227
- Utils.prototype.makeDir = function(folder) {
228
- const self = this;
229
- function mkdirSync(fpath) {
230
- let resolvedPath = fpath.split(self.sep)[0];
231
- fpath.split(self.sep).forEach(function(name) {
232
- if (!name || name.substr(-1, 1) === ":")
233
- return;
234
- resolvedPath += self.sep + name;
235
- var stat;
236
- try {
237
- stat = self.fs.statSync(resolvedPath);
238
- } catch (e) {
239
- if (e.message && e.message.startsWith("ENOENT")) {
240
- self.fs.mkdirSync(resolvedPath);
241
- } else {
242
- throw e;
243
- }
244
- }
245
- if (stat && stat.isFile())
246
- throw Errors.FILE_IN_THE_WAY(`"${resolvedPath}"`);
247
- });
248
- }
249
- mkdirSync(folder);
250
- };
251
- Utils.prototype.writeFileTo = function(path, content, overwrite, attr) {
252
- const self = this;
253
- if (self.fs.existsSync(path)) {
254
- if (!overwrite)
255
- return false;
256
- var stat = self.fs.statSync(path);
257
- if (stat.isDirectory()) {
258
- return false;
259
- }
260
- }
261
- var folder = pth.dirname(path);
262
- if (!self.fs.existsSync(folder)) {
263
- self.makeDir(folder);
264
- }
265
- var fd;
266
- try {
267
- fd = self.fs.openSync(path, "w", 438);
268
- } catch (e) {
269
- self.fs.chmodSync(path, 438);
270
- fd = self.fs.openSync(path, "w", 438);
271
- }
272
- if (fd) {
273
- try {
274
- self.fs.writeSync(fd, content, 0, content.length, 0);
275
- } finally {
276
- self.fs.closeSync(fd);
277
- }
278
- }
279
- self.fs.chmodSync(path, attr || 438);
280
- return true;
281
- };
282
- Utils.prototype.writeFileToAsync = function(path, content, overwrite, attr, callback) {
283
- if (typeof attr === "function") {
284
- callback = attr;
285
- attr = undefined;
286
- }
287
- const self = this;
288
- self.fs.exists(path, function(exist) {
289
- if (exist && !overwrite)
290
- return callback(false);
291
- self.fs.stat(path, function(err, stat) {
292
- if (exist && stat && stat.isDirectory()) {
293
- return callback(false);
294
- }
295
- var folder = pth.dirname(path);
296
- self.fs.exists(folder, function(exists) {
297
- if (!exists) {
298
- try {
299
- self.makeDir(folder);
300
- } catch (e) {
301
- return callback(false);
302
- }
303
- }
304
- const writeToFd = function(fd) {
305
- self.fs.write(fd, content, 0, content.length, 0, function(writeErr) {
306
- self.fs.close(fd, function() {
307
- if (writeErr)
308
- return callback(false);
309
- self.fs.chmod(path, attr || 438, function() {
310
- callback(true);
311
- });
312
- });
313
- });
314
- };
315
- self.fs.open(path, "w", 438, function(err2, fd) {
316
- if (err2) {
317
- self.fs.chmod(path, 438, function() {
318
- self.fs.open(path, "w", 438, function(retryErr, fd2) {
319
- if (retryErr || !fd2)
320
- return callback(false);
321
- writeToFd(fd2);
322
- });
323
- });
324
- } else if (fd) {
325
- writeToFd(fd);
326
- } else {
327
- callback(false);
328
- }
329
- });
330
- });
331
- });
332
- });
333
- };
334
- Utils.prototype.assertPathSafe = function(root, target) {
335
- const self = this;
336
- if (typeof self.fs.lstatSync !== "function")
337
- return;
338
- const resolvedRoot = pth.resolve(root);
339
- const resolvedTarget = pth.resolve(target);
340
- if (resolvedTarget === resolvedRoot)
341
- return;
342
- const rel = pth.relative(resolvedRoot, resolvedTarget);
343
- if (!rel || rel === ".." || rel.startsWith(".." + pth.sep) || pth.isAbsolute(rel))
344
- return;
345
- let cur = resolvedRoot;
346
- for (const part of rel.split(pth.sep)) {
347
- if (!part || part === ".")
348
- continue;
349
- cur = pth.join(cur, part);
350
- let stat;
351
- try {
352
- stat = self.fs.lstatSync(cur);
353
- } catch (e) {
354
- break;
355
- }
356
- if (stat.isSymbolicLink())
357
- throw Errors.FILE_IN_THE_WAY(`"${cur}"`);
358
- }
359
- };
360
- Utils.prototype.findFiles = function(path) {
361
- const self = this;
362
- const canLstat = typeof self.fs.lstatSync === "function";
363
- const rootReal = self.fs.realpathSync(path);
364
- function escapesRoot(p) {
365
- if (!canLstat)
366
- return false;
367
- if (!self.fs.lstatSync(p).isSymbolicLink())
368
- return false;
369
- let real;
370
- try {
371
- real = self.fs.realpathSync(p);
372
- } catch (e) {
373
- return true;
374
- }
375
- return !(real === rootReal || real.startsWith(rootReal + pth.sep));
376
- }
377
- function findSync(dir, pattern, recursive, visited) {
378
- if (typeof pattern === "boolean") {
379
- recursive = pattern;
380
- pattern = undefined;
381
- }
382
- let files = [];
383
- self.fs.readdirSync(dir).forEach(function(file) {
384
- const path2 = pth.join(dir, file);
385
- if (escapesRoot(path2))
386
- return;
387
- const stat = self.fs.statSync(path2);
388
- if (!pattern || pattern.test(path2)) {
389
- files.push(pth.normalize(path2) + (stat.isDirectory() ? self.sep : ""));
390
- }
391
- if (stat.isDirectory() && recursive) {
392
- const realDir = self.fs.realpathSync(path2);
393
- if (!visited.has(realDir)) {
394
- visited.add(realDir);
395
- files = files.concat(findSync(path2, pattern, recursive, visited));
396
- }
397
- }
398
- });
399
- return files;
400
- }
401
- return findSync(path, undefined, true, new Set([rootReal]));
402
- };
403
- Utils.prototype.findFilesAsync = function(dir, cb) {
404
- const self = this;
405
- const results = [];
406
- let finished = false;
407
- const finish = function(err) {
408
- if (finished)
409
- return;
410
- finished = true;
411
- cb(err, err ? undefined : results);
412
- };
413
- const canLstat = typeof self.fs.lstat === "function";
414
- let rootReal = null;
415
- const escapesRoot = function(file, cb2) {
416
- if (!canLstat)
417
- return cb2(null, false);
418
- self.fs.lstat(file, function(err, lst) {
419
- if (err)
420
- return cb2(err);
421
- if (!lst || !lst.isSymbolicLink())
422
- return cb2(null, false);
423
- self.fs.realpath(file, function(err2, real) {
424
- if (err2)
425
- return cb2(null, true);
426
- cb2(null, !(real === rootReal || real.startsWith(rootReal + pth.sep)));
427
- });
428
- });
429
- };
430
- const walk = function(dir2, visited, done) {
431
- self.fs.readdir(dir2, function(err, list) {
432
- if (err)
433
- return done(err);
434
- let pending = list.length;
435
- if (!pending)
436
- return done();
437
- list.forEach(function(name) {
438
- const file = pth.join(dir2, name);
439
- escapesRoot(file, function(err2, escapes) {
440
- if (err2)
441
- return done(err2);
442
- if (escapes) {
443
- if (!--pending)
444
- done();
445
- return;
446
- }
447
- self.fs.stat(file, function(err3, stat) {
448
- if (err3)
449
- return done(err3);
450
- if (!stat) {
451
- if (!--pending)
452
- done();
453
- return;
454
- }
455
- results.push(pth.normalize(file) + (stat.isDirectory() ? self.sep : ""));
456
- if (!stat.isDirectory()) {
457
- if (!--pending)
458
- done();
459
- return;
460
- }
461
- self.fs.realpath(file, function(err4, realDir) {
462
- if (err4)
463
- return done(err4);
464
- if (visited.has(realDir)) {
465
- if (!--pending)
466
- done();
467
- return;
468
- }
469
- visited.add(realDir);
470
- walk(file, visited, function(err5) {
471
- if (err5)
472
- return done(err5);
473
- if (!--pending)
474
- done();
475
- });
476
- });
477
- });
478
- });
479
- });
480
- });
481
- };
482
- self.fs.realpath(dir, function(err, realDir) {
483
- if (err)
484
- return finish(err);
485
- rootReal = realDir;
486
- walk(dir, new Set([realDir]), finish);
487
- });
488
- };
489
- Utils.prototype.getAttributes = function() {};
490
- Utils.prototype.setAttributes = function() {};
491
- Utils.crc32update = function(crc, byte) {
492
- return crcTable[(crc ^ byte) & 255] ^ crc >>> 8;
493
- };
494
- Utils.crc32 = function(buf) {
495
- if (typeof buf === "string") {
496
- buf = Buffer.from(buf, "utf8");
497
- }
498
- let len = buf.length;
499
- let crc = ~0;
500
- for (let off = 0;off < len; )
501
- crc = Utils.crc32update(crc, buf[off++]);
502
- return ~crc >>> 0;
503
- };
504
- Utils.methodToString = function(method) {
505
- switch (method) {
506
- case Constants.STORED:
507
- return "STORED (" + method + ")";
508
- case Constants.DEFLATED:
509
- return "DEFLATED (" + method + ")";
510
- default:
511
- return "UNSUPPORTED (" + method + ")";
512
- }
513
- };
514
- Utils.canonical = function(path) {
515
- if (!path)
516
- return "";
517
- const safeSuffix = pth.posix.normalize("/" + path.split("\\").join("/"));
518
- return pth.join(".", safeSuffix);
519
- };
520
- Utils.zipnamefix = function(path) {
521
- if (!path)
522
- return "";
523
- const safeSuffix = pth.posix.normalize("/" + path.split("\\").join("/"));
524
- return pth.posix.join(".", safeSuffix);
525
- };
526
- Utils.findLast = function(arr, callback) {
527
- if (!Array.isArray(arr))
528
- throw new TypeError("arr is not array");
529
- const len = arr.length >>> 0;
530
- for (let i = len - 1;i >= 0; i--) {
531
- if (callback(arr[i], i, arr)) {
532
- return arr[i];
533
- }
534
- }
535
- return;
536
- };
537
- Utils.sanitize = function(prefix, name) {
538
- prefix = pth.resolve(pth.normalize(prefix));
539
- var parts = name.split("/");
540
- for (var i = 0, l = parts.length;i < l; i++) {
541
- var path = pth.normalize(pth.join(prefix, parts.slice(i, l).join(pth.sep)));
542
- if (path === prefix || path.startsWith(prefix + pth.sep)) {
543
- return path;
544
- }
545
- }
546
- return pth.normalize(pth.join(prefix, pth.basename(name)));
547
- };
548
- Utils.toBuffer = function toBuffer(input, encoder) {
549
- if (Buffer.isBuffer(input)) {
550
- return input;
551
- } else if (input instanceof Uint8Array) {
552
- return Buffer.from(input);
553
- } else {
554
- return typeof input === "string" ? encoder(input) : Buffer.alloc(0);
555
- }
556
- };
557
- Utils.readBigUInt64LE = function(buffer, index) {
558
- const lo = buffer.readUInt32LE(index);
559
- const hi = buffer.readUInt32LE(index + 4);
560
- const value = hi * 4294967296 + lo;
561
- if (value > Number.MAX_SAFE_INTEGER) {
562
- throw Errors.ZIP64_VALUE_TOO_LARGE();
563
- }
564
- return value;
565
- };
566
- Utils.writeBigUInt64LE = function(buffer, value, index) {
567
- const lo = value >>> 0;
568
- const hi = Math.floor(value / 4294967296) >>> 0;
569
- buffer.writeUInt32LE(lo, index);
570
- buffer.writeUInt32LE(hi, index + 4);
571
- };
572
- Utils.fromDOS2Date = function(val) {
573
- return new Date((val >> 25 & 127) + 1980, Math.max((val >> 21 & 15) - 1, 0), Math.max(val >> 16 & 31, 1), val >> 11 & 31, val >> 5 & 63, (val & 31) << 1);
574
- };
575
- Utils.fromDate2DOS = function(val) {
576
- let date = 0;
577
- let time = 0;
578
- if (val.getFullYear() > 1979) {
579
- date = (val.getFullYear() - 1980 & 127) << 9 | val.getMonth() + 1 << 5 | val.getDate();
580
- time = val.getHours() << 11 | val.getMinutes() << 5 | val.getSeconds() >> 1;
581
- }
582
- return date << 16 | time;
583
- };
584
- Utils.isWin = isWin;
585
- Utils.crcTable = crcTable;
586
- });
587
-
588
- // ../../node_modules/adm-zip/util/fattr.js
589
- var require_fattr = __commonJS(function(exports, module) {
590
- var pth = __require("path");
591
- module.exports = function(path, { fs }) {
592
- var _path = path || "", _obj = newAttr(), _stat = null;
593
- function newAttr() {
594
- return {
595
- directory: false,
596
- readonly: false,
597
- hidden: false,
598
- executable: false,
599
- mtime: 0,
600
- atime: 0
601
- };
602
- }
603
- if (_path && fs.existsSync(_path)) {
604
- _stat = fs.statSync(_path);
605
- _obj.directory = _stat.isDirectory();
606
- _obj.mtime = _stat.mtime;
607
- _obj.atime = _stat.atime;
608
- _obj.executable = (73 & _stat.mode) !== 0;
609
- _obj.readonly = (128 & _stat.mode) === 0;
610
- _obj.hidden = pth.basename(_path)[0] === ".";
611
- } else {
612
- console.warn("Invalid path: " + _path);
613
- }
614
- return {
615
- get directory() {
616
- return _obj.directory;
617
- },
618
- get readOnly() {
619
- return _obj.readonly;
620
- },
621
- get hidden() {
622
- return _obj.hidden;
623
- },
624
- get mtime() {
625
- return _obj.mtime;
626
- },
627
- get atime() {
628
- return _obj.atime;
629
- },
630
- get executable() {
631
- return _obj.executable;
632
- },
633
- decodeAttributes: function() {},
634
- encodeAttributes: function() {},
635
- toJSON: function() {
636
- return {
637
- path: _path,
638
- isDirectory: _obj.directory,
639
- isReadOnly: _obj.readonly,
640
- isHidden: _obj.hidden,
641
- isExecutable: _obj.executable,
642
- mTime: _obj.mtime,
643
- aTime: _obj.atime
644
- };
645
- },
646
- toString: function() {
647
- return JSON.stringify(this.toJSON(), null, "\t");
648
- }
649
- };
650
- };
651
- });
652
-
653
- // ../../node_modules/adm-zip/util/decoder.js
654
- var require_decoder = __commonJS(function(exports, module) {
655
- module.exports = {
656
- efs: true,
657
- encode: (data) => Buffer.from(data, "utf8"),
658
- decode: (data) => data.toString("utf8")
659
- };
660
- });
661
-
662
- // ../../node_modules/adm-zip/util/index.js
663
- var require_util = __commonJS(function(exports, module) {
664
- module.exports = require_utils();
665
- module.exports.Constants = require_constants();
666
- module.exports.Errors = require_errors();
667
- module.exports.FileAttr = require_fattr();
668
- module.exports.decoder = require_decoder();
669
- });
670
-
671
- // ../../node_modules/adm-zip/headers/entryHeader.js
672
- var require_entryHeader = __commonJS(function(exports, module) {
673
- var Utils = require_util();
674
- var Constants = Utils.Constants;
675
- module.exports = function() {
676
- var _verMade = 20, _version = 10, _flags = 0, _method = 0, _time = 0, _crc = 0, _compressedSize = 0, _size = 0, _fnameLen = 0, _extraLen = 0, _comLen = 0, _diskStart = 0, _inattr = 0, _attr = 0, _offset = 0;
677
- _verMade |= Utils.isWin ? 2560 : 768;
678
- _flags |= Constants.FLG_EFS;
679
- const _localHeader = {
680
- extraLen: 0
681
- };
682
- const uint32 = (val) => Math.max(0, val) >>> 0;
683
- const uint16 = (val) => Math.max(0, val) & 65535;
684
- const uint8 = (val) => Math.max(0, val) & 255;
685
- _time = Utils.fromDate2DOS(new Date);
686
- return {
687
- get made() {
688
- return _verMade;
689
- },
690
- set made(val) {
691
- _verMade = val;
692
- },
693
- get version() {
694
- return _version;
695
- },
696
- set version(val) {
697
- _version = val;
698
- },
699
- get flags() {
700
- return _flags;
701
- },
702
- set flags(val) {
703
- _flags = val;
704
- },
705
- get flags_efs() {
706
- return (_flags & Constants.FLG_EFS) > 0;
707
- },
708
- set flags_efs(val) {
709
- if (val) {
710
- _flags |= Constants.FLG_EFS;
711
- } else {
712
- _flags &= ~Constants.FLG_EFS;
713
- }
714
- },
715
- get flags_desc() {
716
- return (_flags & Constants.FLG_DESC) > 0;
717
- },
718
- set flags_desc(val) {
719
- if (val) {
720
- _flags |= Constants.FLG_DESC;
721
- } else {
722
- _flags &= ~Constants.FLG_DESC;
723
- }
724
- },
725
- get method() {
726
- return _method;
727
- },
728
- set method(val) {
729
- switch (val) {
730
- case Constants.STORED:
731
- this.version = 10;
732
- break;
733
- case Constants.DEFLATED:
734
- default:
735
- this.version = 20;
736
- }
737
- _method = val;
738
- },
739
- get time() {
740
- return Utils.fromDOS2Date(this.timeval);
741
- },
742
- set time(val) {
743
- val = new Date(val);
744
- this.timeval = Utils.fromDate2DOS(val);
745
- },
746
- get timeval() {
747
- return _time;
748
- },
749
- set timeval(val) {
750
- _time = uint32(val);
751
- },
752
- get timeHighByte() {
753
- return uint8(_time >>> 8);
754
- },
755
- get crc() {
756
- return _crc;
757
- },
758
- set crc(val) {
759
- _crc = uint32(val);
760
- },
761
- get compressedSize() {
762
- return _compressedSize;
763
- },
764
- set compressedSize(val) {
765
- _compressedSize = uint32(val);
766
- },
767
- get size() {
768
- return _size;
769
- },
770
- set size(val) {
771
- _size = uint32(val);
772
- },
773
- get fileNameLength() {
774
- return _fnameLen;
775
- },
776
- set fileNameLength(val) {
777
- _fnameLen = val;
778
- },
779
- get extraLength() {
780
- return _extraLen;
781
- },
782
- set extraLength(val) {
783
- _extraLen = val;
784
- },
785
- get extraLocalLength() {
786
- return _localHeader.extraLen;
787
- },
788
- set extraLocalLength(val) {
789
- _localHeader.extraLen = val;
790
- },
791
- get commentLength() {
792
- return _comLen;
793
- },
794
- set commentLength(val) {
795
- _comLen = val;
796
- },
797
- get diskNumStart() {
798
- return _diskStart;
799
- },
800
- set diskNumStart(val) {
801
- _diskStart = uint32(val);
802
- },
803
- get inAttr() {
804
- return _inattr;
805
- },
806
- set inAttr(val) {
807
- _inattr = uint32(val);
808
- },
809
- get attr() {
810
- return _attr;
811
- },
812
- set attr(val) {
813
- _attr = uint32(val);
814
- },
815
- get fileAttr() {
816
- return (_attr || 0) >> 16 & 511;
817
- },
818
- get offset() {
819
- return _offset;
820
- },
821
- set offset(val) {
822
- _offset = uint32(val);
823
- },
824
- get encrypted() {
825
- return (_flags & Constants.FLG_ENC) === Constants.FLG_ENC;
826
- },
827
- get centralHeaderSize() {
828
- return Constants.CENHDR + _fnameLen + _extraLen + _comLen;
829
- },
830
- get realDataOffset() {
831
- return _offset + Constants.LOCHDR + _localHeader.fnameLen + _localHeader.extraLen;
832
- },
833
- get localHeader() {
834
- return _localHeader;
835
- },
836
- loadLocalHeaderFromBinary: function(input) {
837
- if (_offset < 0 || _offset + Constants.LOCHDR > input.length) {
838
- throw Utils.Errors.INVALID_LOC();
839
- }
840
- var data = input.slice(_offset, _offset + Constants.LOCHDR);
841
- if (data.readUInt32LE(0) !== Constants.LOCSIG) {
842
- throw Utils.Errors.INVALID_LOC();
843
- }
844
- _localHeader.version = data.readUInt16LE(Constants.LOCVER);
845
- _localHeader.flags = data.readUInt16LE(Constants.LOCFLG);
846
- _localHeader.flags_desc = (_localHeader.flags & Constants.FLG_DESC) > 0;
847
- _localHeader.method = data.readUInt16LE(Constants.LOCHOW);
848
- _localHeader.time = data.readUInt32LE(Constants.LOCTIM);
849
- _localHeader.crc = data.readUInt32LE(Constants.LOCCRC);
850
- _localHeader.compressedSize = data.readUInt32LE(Constants.LOCSIZ);
851
- _localHeader.size = data.readUInt32LE(Constants.LOCLEN);
852
- _localHeader.fnameLen = data.readUInt16LE(Constants.LOCNAM);
853
- _localHeader.extraLen = data.readUInt16LE(Constants.LOCEXT);
854
- const extraStart = _offset + Constants.LOCHDR + _localHeader.fnameLen;
855
- const extraEnd = extraStart + _localHeader.extraLen;
856
- return input.slice(extraStart, extraEnd);
857
- },
858
- loadFromBinary: function(data) {
859
- if (data.length !== Constants.CENHDR || data.readUInt32LE(0) !== Constants.CENSIG) {
860
- throw Utils.Errors.INVALID_CEN();
861
- }
862
- _verMade = data.readUInt16LE(Constants.CENVEM);
863
- _version = data.readUInt16LE(Constants.CENVER);
864
- _flags = data.readUInt16LE(Constants.CENFLG);
865
- _method = data.readUInt16LE(Constants.CENHOW);
866
- _time = data.readUInt32LE(Constants.CENTIM);
867
- _crc = data.readUInt32LE(Constants.CENCRC);
868
- _compressedSize = data.readUInt32LE(Constants.CENSIZ);
869
- _size = data.readUInt32LE(Constants.CENLEN);
870
- _fnameLen = data.readUInt16LE(Constants.CENNAM);
871
- _extraLen = data.readUInt16LE(Constants.CENEXT);
872
- _comLen = data.readUInt16LE(Constants.CENCOM);
873
- _diskStart = data.readUInt16LE(Constants.CENDSK);
874
- _inattr = data.readUInt16LE(Constants.CENATT);
875
- _attr = data.readUInt32LE(Constants.CENATX);
876
- _offset = data.readUInt32LE(Constants.CENOFF);
877
- },
878
- localHeaderToBinary: function() {
879
- var data = Buffer.alloc(Constants.LOCHDR);
880
- data.writeUInt32LE(Constants.LOCSIG, 0);
881
- data.writeUInt16LE(_version, Constants.LOCVER);
882
- data.writeUInt16LE(_flags & ~Constants.FLG_DESC, Constants.LOCFLG);
883
- data.writeUInt16LE(_method, Constants.LOCHOW);
884
- data.writeUInt32LE(_time, Constants.LOCTIM);
885
- data.writeUInt32LE(_crc, Constants.LOCCRC);
886
- data.writeUInt32LE(_compressedSize, Constants.LOCSIZ);
887
- data.writeUInt32LE(_size, Constants.LOCLEN);
888
- data.writeUInt16LE(_fnameLen, Constants.LOCNAM);
889
- data.writeUInt16LE(_localHeader.extraLen, Constants.LOCEXT);
890
- return data;
891
- },
892
- centralHeaderToBinary: function() {
893
- var data = Buffer.alloc(Constants.CENHDR + _fnameLen + _extraLen + _comLen);
894
- data.writeUInt32LE(Constants.CENSIG, 0);
895
- data.writeUInt16LE(_verMade, Constants.CENVEM);
896
- data.writeUInt16LE(_version, Constants.CENVER);
897
- data.writeUInt16LE(_flags & ~Constants.FLG_DESC, Constants.CENFLG);
898
- data.writeUInt16LE(_method, Constants.CENHOW);
899
- data.writeUInt32LE(_time, Constants.CENTIM);
900
- data.writeUInt32LE(_crc, Constants.CENCRC);
901
- data.writeUInt32LE(_compressedSize, Constants.CENSIZ);
902
- data.writeUInt32LE(_size, Constants.CENLEN);
903
- data.writeUInt16LE(_fnameLen, Constants.CENNAM);
904
- data.writeUInt16LE(_extraLen, Constants.CENEXT);
905
- data.writeUInt16LE(_comLen, Constants.CENCOM);
906
- data.writeUInt16LE(_diskStart, Constants.CENDSK);
907
- data.writeUInt16LE(_inattr, Constants.CENATT);
908
- data.writeUInt32LE(_attr, Constants.CENATX);
909
- data.writeUInt32LE(_offset, Constants.CENOFF);
910
- return data;
911
- },
912
- toJSON: function() {
913
- const bytes = function(nr) {
914
- return nr + " bytes";
915
- };
916
- return {
917
- made: _verMade,
918
- version: _version,
919
- flags: _flags,
920
- method: Utils.methodToString(_method),
921
- time: this.time,
922
- crc: "0x" + _crc.toString(16).toUpperCase(),
923
- compressedSize: bytes(_compressedSize),
924
- size: bytes(_size),
925
- fileNameLength: bytes(_fnameLen),
926
- extraLength: bytes(_extraLen),
927
- commentLength: bytes(_comLen),
928
- diskNumStart: _diskStart,
929
- inAttr: _inattr,
930
- attr: _attr,
931
- offset: _offset,
932
- centralHeaderSize: bytes(Constants.CENHDR + _fnameLen + _extraLen + _comLen)
933
- };
934
- },
935
- toString: function() {
936
- return JSON.stringify(this.toJSON(), null, "\t");
937
- }
938
- };
939
- };
940
- });
941
-
942
- // ../../node_modules/adm-zip/headers/mainHeader.js
943
- var require_mainHeader = __commonJS(function(exports, module) {
944
- var Utils = require_util();
945
- var Constants = Utils.Constants;
946
- module.exports = function() {
947
- var _volumeEntries = 0, _totalEntries = 0, _size = 0, _offset = 0, _commentLength = 0;
948
- const needsZip64 = () => _volumeEntries > Constants.EF_ZIP64_OR_16 || _totalEntries > Constants.EF_ZIP64_OR_16 || _size > Constants.EF_ZIP64_OR_32 || _offset > Constants.EF_ZIP64_OR_32;
949
- return {
950
- get diskEntries() {
951
- return _volumeEntries;
952
- },
953
- set diskEntries(val) {
954
- _volumeEntries = _totalEntries = val;
955
- },
956
- get totalEntries() {
957
- return _totalEntries;
958
- },
959
- set totalEntries(val) {
960
- _totalEntries = _volumeEntries = val;
961
- },
962
- get size() {
963
- return _size;
964
- },
965
- set size(val) {
966
- _size = val;
967
- },
968
- get offset() {
969
- return _offset;
970
- },
971
- set offset(val) {
972
- _offset = val;
973
- },
974
- get commentLength() {
975
- return _commentLength;
976
- },
977
- set commentLength(val) {
978
- _commentLength = val;
979
- },
980
- get mainHeaderSize() {
981
- return (needsZip64() ? Constants.ZIP64HDR + Constants.END64HDR : 0) + Constants.ENDHDR + _commentLength;
982
- },
983
- loadFromBinary: function(data) {
984
- if ((data.length !== Constants.ENDHDR || data.readUInt32LE(0) !== Constants.ENDSIG) && (data.length < Constants.ZIP64HDR || data.readUInt32LE(0) !== Constants.ZIP64SIG)) {
985
- throw Utils.Errors.INVALID_END();
986
- }
987
- if (data.readUInt32LE(0) === Constants.ENDSIG) {
988
- _volumeEntries = data.readUInt16LE(Constants.ENDSUB);
989
- _totalEntries = data.readUInt16LE(Constants.ENDTOT);
990
- _size = data.readUInt32LE(Constants.ENDSIZ);
991
- _offset = data.readUInt32LE(Constants.ENDOFF);
992
- _commentLength = data.readUInt16LE(Constants.ENDCOM);
993
- } else {
994
- _volumeEntries = Utils.readBigUInt64LE(data, Constants.ZIP64SUB);
995
- _totalEntries = Utils.readBigUInt64LE(data, Constants.ZIP64TOT);
996
- _size = Utils.readBigUInt64LE(data, Constants.ZIP64SIZB);
997
- _offset = Utils.readBigUInt64LE(data, Constants.ZIP64OFF);
998
- _commentLength = 0;
999
- }
1000
- },
1001
- toBinary: function() {
1002
- if (!needsZip64()) {
1003
- var b = Buffer.alloc(Constants.ENDHDR + _commentLength);
1004
- b.writeUInt32LE(Constants.ENDSIG, 0);
1005
- b.writeUInt32LE(0, 4);
1006
- b.writeUInt16LE(_volumeEntries, Constants.ENDSUB);
1007
- b.writeUInt16LE(_totalEntries, Constants.ENDTOT);
1008
- b.writeUInt32LE(_size, Constants.ENDSIZ);
1009
- b.writeUInt32LE(_offset, Constants.ENDOFF);
1010
- b.writeUInt16LE(_commentLength, Constants.ENDCOM);
1011
- b.fill(" ", Constants.ENDHDR);
1012
- return b;
1013
- }
1014
- var b = Buffer.alloc(this.mainHeaderSize);
1015
- let offset = 0;
1016
- b.writeUInt32LE(Constants.ZIP64SIG, offset);
1017
- Utils.writeBigUInt64LE(b, Constants.ZIP64HDR - Constants.ZIP64LEAD, offset + Constants.ZIP64SIZE);
1018
- b.writeUInt16LE(45, offset + Constants.ZIP64VEM);
1019
- b.writeUInt16LE(45, offset + Constants.ZIP64VER);
1020
- b.writeUInt32LE(0, offset + Constants.ZIP64DSK);
1021
- b.writeUInt32LE(0, offset + Constants.ZIP64DSKDIR);
1022
- Utils.writeBigUInt64LE(b, _volumeEntries, offset + Constants.ZIP64SUB);
1023
- Utils.writeBigUInt64LE(b, _totalEntries, offset + Constants.ZIP64TOT);
1024
- Utils.writeBigUInt64LE(b, _size, offset + Constants.ZIP64SIZB);
1025
- Utils.writeBigUInt64LE(b, _offset, offset + Constants.ZIP64OFF);
1026
- const zip64EndOffset = _offset + _size;
1027
- offset += Constants.ZIP64HDR;
1028
- b.writeUInt32LE(Constants.END64SIG, offset);
1029
- b.writeUInt32LE(0, offset + Constants.END64START);
1030
- Utils.writeBigUInt64LE(b, zip64EndOffset, offset + Constants.END64OFF);
1031
- b.writeUInt32LE(1, offset + Constants.END64NUMDISKS);
1032
- offset += Constants.END64HDR;
1033
- b.writeUInt32LE(Constants.ENDSIG, offset);
1034
- b.writeUInt32LE(0, offset + 4);
1035
- b.writeUInt16LE(Math.min(_volumeEntries, Constants.EF_ZIP64_OR_16), offset + Constants.ENDSUB);
1036
- b.writeUInt16LE(Math.min(_totalEntries, Constants.EF_ZIP64_OR_16), offset + Constants.ENDTOT);
1037
- b.writeUInt32LE(Math.min(_size, Constants.EF_ZIP64_OR_32), offset + Constants.ENDSIZ);
1038
- b.writeUInt32LE(Math.min(_offset, Constants.EF_ZIP64_OR_32), offset + Constants.ENDOFF);
1039
- b.writeUInt16LE(_commentLength, offset + Constants.ENDCOM);
1040
- b.fill(" ", offset + Constants.ENDHDR);
1041
- return b;
1042
- },
1043
- toJSON: function() {
1044
- const offset = function(nr, len) {
1045
- let offs = nr.toString(16).toUpperCase();
1046
- while (offs.length < len)
1047
- offs = "0" + offs;
1048
- return "0x" + offs;
1049
- };
1050
- return {
1051
- diskEntries: _volumeEntries,
1052
- totalEntries: _totalEntries,
1053
- size: _size + " bytes",
1054
- offset: offset(_offset, 4),
1055
- commentLength: _commentLength
1056
- };
1057
- },
1058
- toString: function() {
1059
- return JSON.stringify(this.toJSON(), null, "\t");
1060
- }
1061
- };
1062
- };
1063
- });
1064
-
1065
- // ../../node_modules/adm-zip/headers/index.js
1066
- var require_headers = __commonJS(function(exports) {
1067
- exports.EntryHeader = require_entryHeader();
1068
- exports.MainHeader = require_mainHeader();
1069
- });
1070
-
1071
- // ../../node_modules/adm-zip/methods/deflater.js
1072
- var require_deflater = __commonJS(function(exports, module) {
1073
- module.exports = function(inbuf) {
1074
- var zlib = __require("zlib");
1075
- var opts = { chunkSize: (parseInt(inbuf.length / 1024) + 1) * 1024 };
1076
- return {
1077
- deflate: function() {
1078
- return zlib.deflateRawSync(inbuf, opts);
1079
- },
1080
- deflateAsync: function(callback) {
1081
- var tmp = zlib.createDeflateRaw(opts), parts = [], total = 0;
1082
- tmp.on("data", function(data) {
1083
- parts.push(data);
1084
- total += data.length;
1085
- });
1086
- tmp.on("end", function() {
1087
- var buf = Buffer.alloc(total), written = 0;
1088
- buf.fill(0);
1089
- for (var i = 0;i < parts.length; i++) {
1090
- var part = parts[i];
1091
- part.copy(buf, written);
1092
- written += part.length;
1093
- }
1094
- callback && callback(buf);
1095
- });
1096
- tmp.end(inbuf);
1097
- }
1098
- };
1099
- };
1100
- });
1101
-
1102
- // ../../node_modules/adm-zip/methods/inflater.js
1103
- var require_inflater = __commonJS(function(exports, module) {
1104
- var version = +(process?.versions?.node ?? "").split(".")[0] || 0;
1105
- var Errors = require_errors();
1106
- module.exports = function(inbuf, expectedLength) {
1107
- var zlib = __require("zlib");
1108
- const maxOutputLength = expectedLength > 0 ? expectedLength : 1;
1109
- const option = version >= 15 ? { maxOutputLength } : {};
1110
- return {
1111
- inflate: function() {
1112
- return zlib.inflateRawSync(inbuf, option);
1113
- },
1114
- inflateAsync: function(callback) {
1115
- var tmp = zlib.createInflateRaw(option), parts = [], total = 0, done = false;
1116
- const fail = function(err) {
1117
- if (done)
1118
- return;
1119
- done = true;
1120
- tmp.destroy();
1121
- callback && callback(Buffer.alloc(0), err);
1122
- };
1123
- tmp.on("error", function(err) {
1124
- fail(err);
1125
- });
1126
- tmp.on("data", function(data) {
1127
- if (done)
1128
- return;
1129
- total += data.length;
1130
- if (total > maxOutputLength) {
1131
- return fail(Errors.MAX_OUTPUT_EXCEEDED());
1132
- }
1133
- parts.push(data);
1134
- });
1135
- tmp.on("end", function() {
1136
- if (done)
1137
- return;
1138
- done = true;
1139
- var buf = Buffer.alloc(total), written = 0;
1140
- buf.fill(0);
1141
- for (var i = 0;i < parts.length; i++) {
1142
- var part = parts[i];
1143
- part.copy(buf, written);
1144
- written += part.length;
1145
- }
1146
- callback && callback(buf);
1147
- });
1148
- tmp.end(inbuf);
1149
- }
1150
- };
1151
- };
1152
- });
1153
-
1154
- // ../../node_modules/adm-zip/methods/zipcrypto.js
1155
- var require_zipcrypto = __commonJS(function(exports, module) {
1156
- var { randomFillSync } = __require("crypto");
1157
- var Errors = require_errors();
1158
- var crctable = new Uint32Array(256).map((t, crc) => {
1159
- for (let j = 0;j < 8; j++) {
1160
- if ((crc & 1) !== 0) {
1161
- crc = crc >>> 1 ^ 3988292384;
1162
- } else {
1163
- crc >>>= 1;
1164
- }
1165
- }
1166
- return crc >>> 0;
1167
- });
1168
- var uMul = (a, b) => Math.imul(a, b) >>> 0;
1169
- var crc32update = (pCrc32, bval) => {
1170
- return crctable[(pCrc32 ^ bval) & 255] ^ pCrc32 >>> 8;
1171
- };
1172
- var genSalt = () => {
1173
- if (typeof randomFillSync === "function") {
1174
- return randomFillSync(Buffer.alloc(12));
1175
- } else {
1176
- return genSalt.node();
1177
- }
1178
- };
1179
- genSalt.node = () => {
1180
- const salt = Buffer.alloc(12);
1181
- const len = salt.length;
1182
- for (let i = 0;i < len; i++)
1183
- salt[i] = Math.random() * 256 & 255;
1184
- return salt;
1185
- };
1186
- var config = {
1187
- genSalt
1188
- };
1189
- function Initkeys(pw) {
1190
- const pass = Buffer.isBuffer(pw) ? pw : Buffer.from(pw);
1191
- this.keys = new Uint32Array([305419896, 591751049, 878082192]);
1192
- for (let i = 0;i < pass.length; i++) {
1193
- this.updateKeys(pass[i]);
1194
- }
1195
- }
1196
- Initkeys.prototype.updateKeys = function(byteValue) {
1197
- const keys = this.keys;
1198
- keys[0] = crc32update(keys[0], byteValue);
1199
- keys[1] += keys[0] & 255;
1200
- keys[1] = uMul(keys[1], 134775813) + 1;
1201
- keys[2] = crc32update(keys[2], keys[1] >>> 24);
1202
- return byteValue;
1203
- };
1204
- Initkeys.prototype.next = function() {
1205
- const k = (this.keys[2] | 2) >>> 0;
1206
- return uMul(k, k ^ 1) >> 8 & 255;
1207
- };
1208
- function make_decrypter(pwd) {
1209
- const keys = new Initkeys(pwd);
1210
- return function(data) {
1211
- const result = Buffer.alloc(data.length);
1212
- let pos = 0;
1213
- for (let c of data) {
1214
- result[pos++] = keys.updateKeys(c ^ keys.next());
1215
- }
1216
- return result;
1217
- };
1218
- }
1219
- function make_encrypter(pwd) {
1220
- const keys = new Initkeys(pwd);
1221
- return function(data, result, pos = 0) {
1222
- if (!result)
1223
- result = Buffer.alloc(data.length);
1224
- for (let c of data) {
1225
- const k = keys.next();
1226
- result[pos++] = c ^ k;
1227
- keys.updateKeys(c);
1228
- }
1229
- return result;
1230
- };
1231
- }
1232
- function decrypt(data, header, pwd) {
1233
- if (!data || !Buffer.isBuffer(data) || data.length < 12) {
1234
- return Buffer.alloc(0);
1235
- }
1236
- const decrypter = make_decrypter(pwd);
1237
- const salt = decrypter(data.slice(0, 12));
1238
- const verifyByte = (header.flags & 8) === 8 ? header.timeHighByte : header.crc >>> 24;
1239
- if (salt[11] !== verifyByte) {
1240
- throw Errors.WRONG_PASSWORD();
1241
- }
1242
- return decrypter(data.slice(12));
1243
- }
1244
- function _salter(data) {
1245
- if (Buffer.isBuffer(data) && data.length >= 12) {
1246
- config.genSalt = function() {
1247
- return data.slice(0, 12);
1248
- };
1249
- } else if (data === "node") {
1250
- config.genSalt = genSalt.node;
1251
- } else {
1252
- config.genSalt = genSalt;
1253
- }
1254
- }
1255
- function encrypt(data, header, pwd, oldlike = false) {
1256
- if (data == null)
1257
- data = Buffer.alloc(0);
1258
- if (!Buffer.isBuffer(data))
1259
- data = Buffer.from(data.toString());
1260
- const encrypter = make_encrypter(pwd);
1261
- const salt = config.genSalt();
1262
- salt[11] = header.crc >>> 24 & 255;
1263
- if (oldlike)
1264
- salt[10] = header.crc >>> 16 & 255;
1265
- const result = Buffer.alloc(data.length + 12);
1266
- encrypter(salt, result);
1267
- return encrypter(data, result, 12);
1268
- }
1269
- module.exports = { decrypt, encrypt, _salter };
1270
- });
1271
-
1272
- // ../../node_modules/adm-zip/methods/index.js
1273
- var require_methods = __commonJS(function(exports) {
1274
- exports.Deflater = require_deflater();
1275
- exports.Inflater = require_inflater();
1276
- exports.ZipCrypto = require_zipcrypto();
1277
- });
1278
-
1279
- // ../../node_modules/adm-zip/zipEntry.js
1280
- var require_zipEntry = __commonJS(function(exports, module) {
1281
- var Utils = require_util();
1282
- var Headers = require_headers();
1283
- var Constants = Utils.Constants;
1284
- var Methods = require_methods();
1285
- module.exports = function(options, input) {
1286
- var _centralHeader = new Headers.EntryHeader, _entryName = Buffer.alloc(0), _comment = Buffer.alloc(0), _isDirectory = false, uncompressedData = null, _extra = Buffer.alloc(0), _extralocal = Buffer.alloc(0), _efs = true;
1287
- const opts = options;
1288
- const decoder = typeof opts.decoder === "object" ? opts.decoder : Utils.decoder;
1289
- _efs = decoder.hasOwnProperty("efs") ? decoder.efs : false;
1290
- function getCompressedDataFromZip() {
1291
- if (!input || !(input instanceof Uint8Array)) {
1292
- return Buffer.alloc(0);
1293
- }
1294
- _extralocal = _centralHeader.loadLocalHeaderFromBinary(input);
1295
- const dataOffset = _centralHeader.realDataOffset;
1296
- const dataEnd = dataOffset + _centralHeader.compressedSize;
1297
- if (dataOffset < 0 || dataEnd < dataOffset || dataEnd > input.length) {
1298
- throw Utils.Errors.INVALID_LOC();
1299
- }
1300
- return input.slice(dataOffset, dataEnd);
1301
- }
1302
- function crc32OK(data) {
1303
- const expectedCrc = _centralHeader.flags_desc || _centralHeader.localHeader.flags_desc ? _centralHeader.crc : _centralHeader.localHeader.crc;
1304
- return Utils.crc32(data) === expectedCrc;
1305
- }
1306
- function decompress(async, callback, pass) {
1307
- if (typeof callback === "undefined" && typeof async === "string") {
1308
- pass = async;
1309
- async = undefined;
1310
- }
1311
- if (_isDirectory) {
1312
- if (async && callback) {
1313
- callback(Buffer.alloc(0), Utils.Errors.DIRECTORY_CONTENT_ERROR());
1314
- }
1315
- return Buffer.alloc(0);
1316
- }
1317
- var compressedData;
1318
- try {
1319
- compressedData = getCompressedDataFromZip();
1320
- if (compressedData.length === 0) {
1321
- if (async && callback)
1322
- callback(compressedData);
1323
- return compressedData;
1324
- }
1325
- if (_centralHeader.encrypted) {
1326
- if (typeof pass !== "string" && !Buffer.isBuffer(pass)) {
1327
- throw Utils.Errors.INVALID_PASS_PARAM();
1328
- }
1329
- compressedData = Methods.ZipCrypto.decrypt(compressedData, _centralHeader, pass);
1330
- }
1331
- } catch (err) {
1332
- if (async && callback) {
1333
- callback(Buffer.alloc(0), err);
1334
- return Buffer.alloc(0);
1335
- }
1336
- throw err;
1337
- }
1338
- var data;
1339
- switch (_centralHeader.method) {
1340
- case Utils.Constants.STORED:
1341
- data = Buffer.alloc(compressedData.length);
1342
- compressedData.copy(data);
1343
- if (!crc32OK(data)) {
1344
- if (async && callback)
1345
- callback(data, Utils.Errors.BAD_CRC());
1346
- throw Utils.Errors.BAD_CRC();
1347
- } else {
1348
- if (async && callback)
1349
- callback(data);
1350
- return data;
1351
- }
1352
- case Utils.Constants.DEFLATED:
1353
- var inflater = new Methods.Inflater(compressedData, _centralHeader.size);
1354
- if (!async) {
1355
- data = inflater.inflate();
1356
- if (!crc32OK(data)) {
1357
- throw Utils.Errors.BAD_CRC(`"${decoder.decode(_entryName)}"`);
1358
- }
1359
- return data;
1360
- } else {
1361
- inflater.inflateAsync(function(result, err) {
1362
- if (!callback)
1363
- return;
1364
- if (err) {
1365
- callback(Buffer.alloc(0), err);
1366
- } else if (!crc32OK(result)) {
1367
- callback(result, Utils.Errors.BAD_CRC());
1368
- } else {
1369
- callback(result);
1370
- }
1371
- });
1372
- }
1373
- break;
1374
- default:
1375
- if (async && callback)
1376
- callback(Buffer.alloc(0), Utils.Errors.UNKNOWN_METHOD());
1377
- throw Utils.Errors.UNKNOWN_METHOD();
1378
- }
1379
- }
1380
- function compress(async, callback) {
1381
- if ((!uncompressedData || !uncompressedData.length) && Buffer.isBuffer(input)) {
1382
- if (async && callback)
1383
- callback(getCompressedDataFromZip());
1384
- return getCompressedDataFromZip();
1385
- }
1386
- if (uncompressedData.length && !_isDirectory) {
1387
- var compressedData;
1388
- switch (_centralHeader.method) {
1389
- case Utils.Constants.STORED:
1390
- _centralHeader.compressedSize = _centralHeader.size;
1391
- compressedData = Buffer.alloc(uncompressedData.length);
1392
- uncompressedData.copy(compressedData);
1393
- if (async && callback)
1394
- callback(compressedData);
1395
- return compressedData;
1396
- default:
1397
- case Utils.Constants.DEFLATED:
1398
- var deflater = new Methods.Deflater(uncompressedData);
1399
- if (!async) {
1400
- var deflated = deflater.deflate();
1401
- _centralHeader.compressedSize = deflated.length;
1402
- return deflated;
1403
- } else {
1404
- deflater.deflateAsync(function(data) {
1405
- compressedData = Buffer.alloc(data.length);
1406
- _centralHeader.compressedSize = data.length;
1407
- data.copy(compressedData);
1408
- callback && callback(compressedData);
1409
- });
1410
- }
1411
- deflater = null;
1412
- break;
1413
- }
1414
- } else if (async && callback) {
1415
- callback(Buffer.alloc(0));
1416
- } else {
1417
- return Buffer.alloc(0);
1418
- }
1419
- }
1420
- function readUInt64LE(buffer, offset) {
1421
- return Utils.readBigUInt64LE(buffer, offset);
1422
- }
1423
- function parseExtra(data) {
1424
- try {
1425
- var offset = 0;
1426
- var signature, size, part;
1427
- while (offset + 4 < data.length) {
1428
- signature = data.readUInt16LE(offset);
1429
- offset += 2;
1430
- size = data.readUInt16LE(offset);
1431
- offset += 2;
1432
- part = data.slice(offset, offset + size);
1433
- offset += size;
1434
- if (Constants.ID_ZIP64 === signature) {
1435
- parseZip64ExtendedInformation(part);
1436
- }
1437
- }
1438
- } catch (error) {
1439
- throw Utils.Errors.EXTRA_FIELD_PARSE_ERROR();
1440
- }
1441
- }
1442
- function parseZip64ExtendedInformation(data) {
1443
- var size, compressedSize, offset, diskNumStart;
1444
- if (data.length >= Constants.EF_ZIP64_SCOMP) {
1445
- size = readUInt64LE(data, Constants.EF_ZIP64_SUNCOMP);
1446
- if (_centralHeader.size === Constants.EF_ZIP64_OR_32) {
1447
- _centralHeader.size = size;
1448
- }
1449
- }
1450
- if (data.length >= Constants.EF_ZIP64_RHO) {
1451
- compressedSize = readUInt64LE(data, Constants.EF_ZIP64_SCOMP);
1452
- if (_centralHeader.compressedSize === Constants.EF_ZIP64_OR_32) {
1453
- _centralHeader.compressedSize = compressedSize;
1454
- }
1455
- }
1456
- if (data.length >= Constants.EF_ZIP64_DSN) {
1457
- offset = readUInt64LE(data, Constants.EF_ZIP64_RHO);
1458
- if (_centralHeader.offset === Constants.EF_ZIP64_OR_32) {
1459
- _centralHeader.offset = offset;
1460
- }
1461
- }
1462
- if (data.length >= Constants.EF_ZIP64_DSN + 4) {
1463
- diskNumStart = data.readUInt32LE(Constants.EF_ZIP64_DSN);
1464
- if (_centralHeader.diskNumStart === Constants.EF_ZIP64_OR_16) {
1465
- _centralHeader.diskNumStart = diskNumStart;
1466
- }
1467
- }
1468
- }
1469
- return {
1470
- get entryName() {
1471
- return decoder.decode(_entryName);
1472
- },
1473
- get rawEntryName() {
1474
- return _entryName;
1475
- },
1476
- set entryName(val) {
1477
- _entryName = Utils.toBuffer(val, decoder.encode);
1478
- var lastChar = _entryName[_entryName.length - 1];
1479
- _isDirectory = lastChar === 47 || lastChar === 92;
1480
- _centralHeader.fileNameLength = _entryName.length;
1481
- },
1482
- get efs() {
1483
- if (typeof _efs === "function") {
1484
- return _efs(this.entryName);
1485
- } else {
1486
- return _efs;
1487
- }
1488
- },
1489
- get extra() {
1490
- return _extra;
1491
- },
1492
- set extra(val) {
1493
- _extra = val;
1494
- _centralHeader.extraLength = val.length;
1495
- parseExtra(val);
1496
- },
1497
- get comment() {
1498
- return decoder.decode(_comment);
1499
- },
1500
- set comment(val) {
1501
- _comment = Utils.toBuffer(val, decoder.encode);
1502
- _centralHeader.commentLength = _comment.length;
1503
- if (_comment.length > 65535)
1504
- throw Utils.Errors.COMMENT_TOO_LONG();
1505
- },
1506
- get name() {
1507
- const n = decoder.decode(_entryName);
1508
- return _isDirectory ? n.replace(/[/\\]$/, "").split("/").pop() : n.split("/").pop();
1509
- },
1510
- get isDirectory() {
1511
- return _isDirectory;
1512
- },
1513
- getCompressedData: function() {
1514
- return compress(false, null);
1515
- },
1516
- getCompressedDataAsync: function(callback) {
1517
- compress(true, callback);
1518
- },
1519
- setData: function(value) {
1520
- uncompressedData = Utils.toBuffer(value, Utils.decoder.encode);
1521
- if (!_isDirectory && uncompressedData.length) {
1522
- _centralHeader.size = uncompressedData.length;
1523
- _centralHeader.method = Utils.Constants.DEFLATED;
1524
- _centralHeader.crc = Utils.crc32(value);
1525
- _centralHeader.changed = true;
1526
- } else {
1527
- _centralHeader.method = Utils.Constants.STORED;
1528
- }
1529
- },
1530
- getData: function(pass) {
1531
- if (_centralHeader.changed) {
1532
- return uncompressedData;
1533
- } else {
1534
- return decompress(false, null, pass);
1535
- }
1536
- },
1537
- getDataAsync: function(callback, pass) {
1538
- if (_centralHeader.changed) {
1539
- callback(uncompressedData);
1540
- } else {
1541
- decompress(true, callback, pass);
1542
- }
1543
- },
1544
- set attr(attr) {
1545
- _centralHeader.attr = attr;
1546
- },
1547
- get attr() {
1548
- return _centralHeader.attr;
1549
- },
1550
- set header(data) {
1551
- _centralHeader.loadFromBinary(data);
1552
- },
1553
- get header() {
1554
- return _centralHeader;
1555
- },
1556
- packCentralHeader: function() {
1557
- _centralHeader.flags_efs = this.efs;
1558
- _centralHeader.extraLength = _extra.length;
1559
- var header = _centralHeader.centralHeaderToBinary();
1560
- var addpos = Utils.Constants.CENHDR;
1561
- _entryName.copy(header, addpos);
1562
- addpos += _entryName.length;
1563
- _extra.copy(header, addpos);
1564
- addpos += _centralHeader.extraLength;
1565
- _comment.copy(header, addpos);
1566
- return header;
1567
- },
1568
- packLocalHeader: function() {
1569
- let addpos = 0;
1570
- _centralHeader.flags_efs = this.efs;
1571
- _centralHeader.extraLocalLength = _extralocal.length;
1572
- const localHeaderBuf = _centralHeader.localHeaderToBinary();
1573
- const localHeader = Buffer.alloc(localHeaderBuf.length + _entryName.length + _centralHeader.extraLocalLength);
1574
- localHeaderBuf.copy(localHeader, addpos);
1575
- addpos += localHeaderBuf.length;
1576
- _entryName.copy(localHeader, addpos);
1577
- addpos += _entryName.length;
1578
- _extralocal.copy(localHeader, addpos);
1579
- addpos += _extralocal.length;
1580
- return localHeader;
1581
- },
1582
- toJSON: function() {
1583
- const bytes = function(nr) {
1584
- return "<" + (nr && nr.length + " bytes buffer" || "null") + ">";
1585
- };
1586
- return {
1587
- entryName: this.entryName,
1588
- name: this.name,
1589
- comment: this.comment,
1590
- isDirectory: this.isDirectory,
1591
- header: _centralHeader.toJSON(),
1592
- compressedData: bytes(input),
1593
- data: bytes(uncompressedData)
1594
- };
1595
- },
1596
- toString: function() {
1597
- return JSON.stringify(this.toJSON(), null, "\t");
1598
- }
1599
- };
1600
- };
1601
- });
1602
-
1603
- // ../../node_modules/adm-zip/zipFile.js
1604
- var require_zipFile = __commonJS(function(exports, module) {
1605
- var ZipEntry = require_zipEntry();
1606
- var Headers = require_headers();
1607
- var Utils = require_util();
1608
- module.exports = function(inBuffer, options) {
1609
- var entryList = [], entryTable = Object.create(null), _comment = Buffer.alloc(0), mainHeader = new Headers.MainHeader, loadedEntries = false;
1610
- var password = null;
1611
- const temporary = new Set;
1612
- const opts = options;
1613
- const { noSort, decoder } = opts;
1614
- if (inBuffer) {
1615
- readMainHeader(opts.readEntries);
1616
- } else {
1617
- loadedEntries = true;
1618
- }
1619
- function makeTemporaryFolders() {
1620
- const foldersList = new Set;
1621
- for (const elem of Object.keys(entryTable)) {
1622
- const elements = elem.split("/");
1623
- elements.pop();
1624
- if (!elements.length)
1625
- continue;
1626
- for (let i = 0;i < elements.length; i++) {
1627
- const sub = elements.slice(0, i + 1).join("/") + "/";
1628
- foldersList.add(sub);
1629
- }
1630
- }
1631
- for (const elem of foldersList) {
1632
- if (!(elem in entryTable)) {
1633
- const tempfolder = new ZipEntry(opts);
1634
- tempfolder.entryName = elem;
1635
- tempfolder.attr = 16;
1636
- tempfolder.temporary = true;
1637
- entryList.push(tempfolder);
1638
- entryTable[tempfolder.entryName] = tempfolder;
1639
- temporary.add(tempfolder);
1640
- }
1641
- }
1642
- }
1643
- function readEntries() {
1644
- loadedEntries = true;
1645
- entryTable = Object.create(null);
1646
- if (mainHeader.diskEntries > (inBuffer.length - mainHeader.offset) / Utils.Constants.CENHDR) {
1647
- throw Utils.Errors.DISK_ENTRY_TOO_LARGE();
1648
- }
1649
- entryList = new Array(mainHeader.diskEntries);
1650
- var index = mainHeader.offset;
1651
- for (var i = 0;i < entryList.length; i++) {
1652
- var tmp = index, entry = new ZipEntry(opts, inBuffer);
1653
- entry.header = inBuffer.slice(tmp, tmp += Utils.Constants.CENHDR);
1654
- entry.entryName = inBuffer.slice(tmp, tmp += entry.header.fileNameLength);
1655
- if (entry.header.extraLength) {
1656
- entry.extra = inBuffer.slice(tmp, tmp += entry.header.extraLength);
1657
- }
1658
- if (entry.header.commentLength)
1659
- entry.comment = inBuffer.slice(tmp, tmp + entry.header.commentLength);
1660
- index += entry.header.centralHeaderSize;
1661
- if (entry.entryName in entryTable) {
1662
- throw Utils.Errors.DUPLICATE_ENTRY(`"${entry.entryName}"`);
1663
- }
1664
- entryList[i] = entry;
1665
- entryTable[entry.entryName] = entry;
1666
- }
1667
- temporary.clear();
1668
- makeTemporaryFolders();
1669
- }
1670
- function readMainHeader(readNow) {
1671
- var i = inBuffer.length - Utils.Constants.ENDHDR, max = Math.max(0, i - 65535), n = max, endStart = inBuffer.length, endOffset = -1, commentEnd = 0;
1672
- const trailingSpace = typeof opts.trailingSpace === "boolean" ? opts.trailingSpace : false;
1673
- if (trailingSpace)
1674
- max = 0;
1675
- for (i;i >= n; i--) {
1676
- if (inBuffer[i] !== 80)
1677
- continue;
1678
- if (inBuffer.readUInt32LE(i) === Utils.Constants.ENDSIG) {
1679
- endOffset = i;
1680
- commentEnd = i;
1681
- endStart = i + Utils.Constants.ENDHDR;
1682
- n = i - Utils.Constants.END64HDR;
1683
- continue;
1684
- }
1685
- if (inBuffer.readUInt32LE(i) === Utils.Constants.END64SIG) {
1686
- n = max;
1687
- continue;
1688
- }
1689
- if (inBuffer.readUInt32LE(i) === Utils.Constants.ZIP64SIG) {
1690
- endOffset = i;
1691
- endStart = i + Utils.readBigUInt64LE(inBuffer, i + Utils.Constants.ZIP64SIZE) + Utils.Constants.ZIP64LEAD;
1692
- break;
1693
- }
1694
- }
1695
- if (endOffset == -1)
1696
- throw Utils.Errors.INVALID_FORMAT();
1697
- mainHeader.loadFromBinary(inBuffer.slice(endOffset, endStart));
1698
- if (mainHeader.commentLength) {
1699
- _comment = inBuffer.slice(commentEnd + Utils.Constants.ENDHDR);
1700
- }
1701
- if (readNow)
1702
- readEntries();
1703
- }
1704
- function sortEntries() {
1705
- if (entryList.length > 1 && !noSort) {
1706
- entryList = entryList.map((entry) => ({ entry, key: entry.entryName.toLowerCase() })).sort((a, b) => a.key.localeCompare(b.key)).map((pair) => pair.entry);
1707
- }
1708
- }
1709
- return {
1710
- get entries() {
1711
- if (!loadedEntries) {
1712
- readEntries();
1713
- }
1714
- return entryList.filter((e) => !temporary.has(e));
1715
- },
1716
- get comment() {
1717
- return decoder.decode(_comment);
1718
- },
1719
- set comment(val) {
1720
- _comment = Utils.toBuffer(val, decoder.encode);
1721
- mainHeader.commentLength = _comment.length;
1722
- },
1723
- getEntryCount: function() {
1724
- if (!loadedEntries) {
1725
- return mainHeader.diskEntries;
1726
- }
1727
- return entryList.length;
1728
- },
1729
- forEach: function(callback) {
1730
- this.entries.forEach(callback);
1731
- },
1732
- getEntry: function(entryName) {
1733
- if (!loadedEntries) {
1734
- readEntries();
1735
- }
1736
- return entryTable[entryName] || null;
1737
- },
1738
- setEntry: function(entry) {
1739
- if (!loadedEntries) {
1740
- readEntries();
1741
- }
1742
- entryList.push(entry);
1743
- entryTable[entry.entryName] = entry;
1744
- mainHeader.totalEntries = entryList.length;
1745
- },
1746
- deleteFile: function(entryName, withsubfolders = true) {
1747
- if (!loadedEntries) {
1748
- readEntries();
1749
- }
1750
- const entry = entryTable[entryName];
1751
- const list = this.getEntryChildren(entry, withsubfolders).map((child) => child.entryName);
1752
- list.forEach(this.deleteEntry);
1753
- },
1754
- deleteEntry: function(entryName) {
1755
- if (!loadedEntries) {
1756
- readEntries();
1757
- }
1758
- const entry = entryTable[entryName];
1759
- const index = entryList.indexOf(entry);
1760
- if (index >= 0) {
1761
- entryList.splice(index, 1);
1762
- delete entryTable[entryName];
1763
- mainHeader.totalEntries = entryList.length;
1764
- }
1765
- },
1766
- getEntryChildren: function(entry, subfolders = true) {
1767
- if (!loadedEntries) {
1768
- readEntries();
1769
- }
1770
- if (typeof entry === "object") {
1771
- if (entry.isDirectory && subfolders) {
1772
- const list = [];
1773
- const name = entry.entryName;
1774
- for (const zipEntry of entryList) {
1775
- if (zipEntry.entryName.startsWith(name)) {
1776
- list.push(zipEntry);
1777
- }
1778
- }
1779
- return list;
1780
- } else {
1781
- return [entry];
1782
- }
1783
- }
1784
- return [];
1785
- },
1786
- getChildCount: function(entry) {
1787
- if (entry && entry.isDirectory) {
1788
- const list = this.getEntryChildren(entry);
1789
- return list.includes(entry) ? list.length - 1 : list.length;
1790
- }
1791
- return 0;
1792
- },
1793
- compressToBuffer: function() {
1794
- if (!loadedEntries) {
1795
- readEntries();
1796
- }
1797
- sortEntries();
1798
- const dataBlock = [];
1799
- const headerBlocks = [];
1800
- let totalSize = 0;
1801
- let dindex = 0;
1802
- mainHeader.size = 0;
1803
- mainHeader.offset = 0;
1804
- let totalEntries = 0;
1805
- for (const entry of this.entries) {
1806
- const compressedData = entry.getCompressedData();
1807
- entry.header.offset = dindex;
1808
- const localHeader = entry.packLocalHeader();
1809
- const dataLength = localHeader.length + compressedData.length;
1810
- dindex += dataLength;
1811
- dataBlock.push(localHeader);
1812
- dataBlock.push(compressedData);
1813
- const centralHeader = entry.packCentralHeader();
1814
- headerBlocks.push(centralHeader);
1815
- mainHeader.size += centralHeader.length;
1816
- totalSize += dataLength + centralHeader.length;
1817
- totalEntries++;
1818
- }
1819
- totalSize += mainHeader.mainHeaderSize;
1820
- mainHeader.offset = dindex;
1821
- mainHeader.totalEntries = totalEntries;
1822
- dindex = 0;
1823
- const outBuffer = Buffer.alloc(totalSize);
1824
- for (const content of dataBlock) {
1825
- content.copy(outBuffer, dindex);
1826
- dindex += content.length;
1827
- }
1828
- for (const content of headerBlocks) {
1829
- content.copy(outBuffer, dindex);
1830
- dindex += content.length;
1831
- }
1832
- const mh = mainHeader.toBinary();
1833
- if (_comment) {
1834
- _comment.copy(mh, mh.length - _comment.length);
1835
- }
1836
- mh.copy(outBuffer, dindex);
1837
- inBuffer = outBuffer;
1838
- loadedEntries = false;
1839
- return outBuffer;
1840
- },
1841
- toAsyncBuffer: function(onSuccess, onFail, onItemStart, onItemEnd) {
1842
- try {
1843
- if (!loadedEntries) {
1844
- readEntries();
1845
- }
1846
- sortEntries();
1847
- const dataBlock = [];
1848
- const centralHeaders = [];
1849
- let totalSize = 0;
1850
- let dindex = 0;
1851
- let totalEntries = 0;
1852
- mainHeader.size = 0;
1853
- mainHeader.offset = 0;
1854
- const compress2Buffer = function(entryLists) {
1855
- if (entryLists.length > 0) {
1856
- const entry = entryLists.shift();
1857
- const name = entry.entryName + entry.extra.toString();
1858
- if (onItemStart)
1859
- onItemStart(name);
1860
- entry.getCompressedDataAsync(function(compressedData) {
1861
- if (onItemEnd)
1862
- onItemEnd(name);
1863
- entry.header.offset = dindex;
1864
- const localHeader = entry.packLocalHeader();
1865
- const dataLength = localHeader.length + compressedData.length;
1866
- dindex += dataLength;
1867
- dataBlock.push(localHeader);
1868
- dataBlock.push(compressedData);
1869
- const centalHeader = entry.packCentralHeader();
1870
- centralHeaders.push(centalHeader);
1871
- mainHeader.size += centalHeader.length;
1872
- totalSize += dataLength + centalHeader.length;
1873
- totalEntries++;
1874
- compress2Buffer(entryLists);
1875
- });
1876
- } else {
1877
- totalSize += mainHeader.mainHeaderSize;
1878
- mainHeader.offset = dindex;
1879
- mainHeader.totalEntries = totalEntries;
1880
- dindex = 0;
1881
- const outBuffer = Buffer.alloc(totalSize);
1882
- dataBlock.forEach(function(content) {
1883
- content.copy(outBuffer, dindex);
1884
- dindex += content.length;
1885
- });
1886
- centralHeaders.forEach(function(content) {
1887
- content.copy(outBuffer, dindex);
1888
- dindex += content.length;
1889
- });
1890
- const mh = mainHeader.toBinary();
1891
- if (_comment) {
1892
- _comment.copy(mh, mh.length - _comment.length);
1893
- }
1894
- mh.copy(outBuffer, dindex);
1895
- inBuffer = outBuffer;
1896
- loadedEntries = false;
1897
- onSuccess(outBuffer);
1898
- }
1899
- };
1900
- compress2Buffer(Array.from(this.entries));
1901
- } catch (e) {
1902
- onFail(e);
1903
- }
1904
- }
1905
- };
1906
- };
1907
- });
1908
-
1909
- // ../../node_modules/adm-zip/adm-zip.js
1910
- var require_adm_zip = __commonJS(function(exports, module) {
1911
- var Utils = require_util();
1912
- var pth = __require("path");
1913
- var ZipEntry = require_zipEntry();
1914
- var ZipFile = require_zipFile();
1915
- var get_Bool = (...val) => Utils.findLast(val, (c) => typeof c === "boolean");
1916
- var get_Str = (...val) => Utils.findLast(val, (c) => typeof c === "string");
1917
- var get_Fun = (...val) => Utils.findLast(val, (c) => typeof c === "function");
1918
- var defaultOptions = {
1919
- noSort: false,
1920
- readEntries: false,
1921
- method: Utils.Constants.NONE,
1922
- fs: null
1923
- };
1924
- module.exports = function(input, options) {
1925
- let inBuffer = null;
1926
- const opts = Object.assign(Object.create(null), defaultOptions);
1927
- if (input && typeof input === "object") {
1928
- if (!(input instanceof Uint8Array)) {
1929
- Object.assign(opts, input);
1930
- input = opts.input ? opts.input : undefined;
1931
- if (opts.input)
1932
- delete opts.input;
1933
- }
1934
- if (Buffer.isBuffer(input)) {
1935
- inBuffer = input;
1936
- opts.method = Utils.Constants.BUFFER;
1937
- input = undefined;
1938
- }
1939
- }
1940
- Object.assign(opts, options);
1941
- const filetools = new Utils(opts);
1942
- const applyDirAttributes = (dirEntries) => {
1943
- dirEntries.filter((d) => d.attr).sort((a, b) => b.path.length - a.path.length).forEach((d) => filetools.fs.chmodSync(d.path, d.attr));
1944
- };
1945
- if (typeof opts.decoder !== "object" || typeof opts.decoder.encode !== "function" || typeof opts.decoder.decode !== "function") {
1946
- opts.decoder = Utils.decoder;
1947
- }
1948
- if (input && typeof input === "string") {
1949
- if (filetools.fs.existsSync(input)) {
1950
- opts.method = Utils.Constants.FILE;
1951
- opts.filename = input;
1952
- inBuffer = filetools.fs.readFileSync(input);
1953
- } else {
1954
- throw Utils.Errors.INVALID_FILENAME();
1955
- }
1956
- }
1957
- const _zip = new ZipFile(inBuffer, opts);
1958
- const { canonical, sanitize, zipnamefix } = Utils;
1959
- function getEntry(entry) {
1960
- if (entry && _zip) {
1961
- var item;
1962
- if (typeof entry === "string")
1963
- item = _zip.getEntry(pth.posix.normalize(entry));
1964
- if (typeof entry === "object" && typeof entry.entryName !== "undefined" && typeof entry.header !== "undefined")
1965
- item = _zip.getEntry(entry.entryName);
1966
- if (item) {
1967
- return item;
1968
- }
1969
- }
1970
- return null;
1971
- }
1972
- function fixPath(zipPath) {
1973
- const { join, normalize, sep } = pth.posix;
1974
- return join(pth.isAbsolute(zipPath) ? "/" : ".", normalize(sep + zipPath.split("\\").join(sep) + sep));
1975
- }
1976
- function filenameFilter(filterfn) {
1977
- if (filterfn instanceof RegExp) {
1978
- return function(rx) {
1979
- return function(filename) {
1980
- return rx.test(filename);
1981
- };
1982
- }(filterfn);
1983
- } else if (typeof filterfn !== "function") {
1984
- return () => true;
1985
- }
1986
- return filterfn;
1987
- }
1988
- const relativePath = (local, entry) => {
1989
- let lastChar = entry.slice(-1);
1990
- lastChar = lastChar === filetools.sep ? filetools.sep : "";
1991
- return pth.relative(local, entry) + lastChar;
1992
- };
1993
- return {
1994
- readFile: function(entry, pass) {
1995
- var item = getEntry(entry);
1996
- return item && item.getData(pass) || null;
1997
- },
1998
- childCount: function(entry) {
1999
- const item = getEntry(entry);
2000
- if (item) {
2001
- return _zip.getChildCount(item);
2002
- }
2003
- },
2004
- readFileAsync: function(entry, callback) {
2005
- var item = getEntry(entry);
2006
- if (item) {
2007
- item.getDataAsync(callback);
2008
- } else {
2009
- callback(null, "getEntry failed for:" + entry);
2010
- }
2011
- },
2012
- readAsText: function(entry, encoding) {
2013
- var item = getEntry(entry);
2014
- if (item) {
2015
- var data = item.getData();
2016
- if (data && data.length) {
2017
- return data.toString(encoding || "utf8");
2018
- }
2019
- }
2020
- return "";
2021
- },
2022
- readAsTextAsync: function(entry, callback, encoding) {
2023
- var item = getEntry(entry);
2024
- if (item) {
2025
- item.getDataAsync(function(data, err) {
2026
- if (err) {
2027
- callback(data, err);
2028
- return;
2029
- }
2030
- if (data && data.length) {
2031
- callback(data.toString(encoding || "utf8"));
2032
- } else {
2033
- callback("");
2034
- }
2035
- });
2036
- } else {
2037
- callback("");
2038
- }
2039
- },
2040
- deleteFile: function(entry, withsubfolders = true) {
2041
- var item = getEntry(entry);
2042
- if (item) {
2043
- _zip.deleteFile(item.entryName, withsubfolders);
2044
- }
2045
- },
2046
- deleteEntry: function(entry) {
2047
- var item = getEntry(entry);
2048
- if (item) {
2049
- _zip.deleteEntry(item.entryName);
2050
- }
2051
- },
2052
- addZipComment: function(comment) {
2053
- _zip.comment = comment;
2054
- },
2055
- getZipComment: function() {
2056
- return _zip.comment || "";
2057
- },
2058
- addZipEntryComment: function(entry, comment) {
2059
- var item = getEntry(entry);
2060
- if (item) {
2061
- item.comment = comment;
2062
- }
2063
- },
2064
- getZipEntryComment: function(entry) {
2065
- var item = getEntry(entry);
2066
- if (item) {
2067
- return item.comment || "";
2068
- }
2069
- return "";
2070
- },
2071
- updateFile: function(entry, content) {
2072
- var item = getEntry(entry);
2073
- if (item) {
2074
- item.setData(content);
2075
- }
2076
- },
2077
- addLocalFile: function(localPath, zipPath, zipName, comment) {
2078
- if (filetools.fs.existsSync(localPath)) {
2079
- zipPath = zipPath ? fixPath(zipPath) : "";
2080
- const p = pth.win32.basename(pth.win32.normalize(localPath));
2081
- zipPath += zipName ? zipName : p;
2082
- const _attr = filetools.fs.statSync(localPath);
2083
- const data = _attr.isFile() ? filetools.fs.readFileSync(localPath) : Buffer.alloc(0);
2084
- if (_attr.isDirectory())
2085
- zipPath += filetools.sep;
2086
- this.addFile(zipPath, data, comment, _attr);
2087
- } else {
2088
- throw Utils.Errors.FILE_NOT_FOUND(localPath);
2089
- }
2090
- },
2091
- addLocalFileAsync: function(options2, callback) {
2092
- options2 = typeof options2 === "object" ? options2 : { localPath: options2 };
2093
- const localPath = pth.resolve(options2.localPath);
2094
- const { comment } = options2;
2095
- let { zipPath, zipName } = options2;
2096
- const self = this;
2097
- filetools.fs.stat(localPath, function(err, stats) {
2098
- if (err)
2099
- return callback(err, false);
2100
- zipPath = zipPath ? fixPath(zipPath) : "";
2101
- const p = pth.win32.basename(pth.win32.normalize(localPath));
2102
- zipPath += zipName ? zipName : p;
2103
- if (stats.isFile()) {
2104
- filetools.fs.readFile(localPath, function(err2, data) {
2105
- if (err2)
2106
- return callback(err2, false);
2107
- self.addFile(zipPath, data, comment, stats);
2108
- return setImmediate(callback, undefined, true);
2109
- });
2110
- } else if (stats.isDirectory()) {
2111
- zipPath += filetools.sep;
2112
- self.addFile(zipPath, Buffer.alloc(0), comment, stats);
2113
- return setImmediate(callback, undefined, true);
2114
- }
2115
- });
2116
- },
2117
- addLocalFolder: function(localPath, zipPath, filter) {
2118
- filter = filenameFilter(filter);
2119
- zipPath = zipPath ? fixPath(zipPath) : "";
2120
- localPath = pth.normalize(localPath);
2121
- if (filetools.fs.existsSync(localPath)) {
2122
- const items = filetools.findFiles(localPath);
2123
- const self = this;
2124
- if (items.length) {
2125
- for (const filepath of items) {
2126
- const p = pth.join(zipPath, relativePath(localPath, filepath));
2127
- if (filter(p)) {
2128
- self.addLocalFile(filepath, pth.dirname(p));
2129
- }
2130
- }
2131
- }
2132
- } else {
2133
- throw Utils.Errors.FILE_NOT_FOUND(localPath);
2134
- }
2135
- },
2136
- addLocalFolderAsync: function(localPath, callback, zipPath, filter) {
2137
- filter = filenameFilter(filter);
2138
- zipPath = zipPath ? fixPath(zipPath) : "";
2139
- localPath = pth.normalize(localPath);
2140
- var self = this;
2141
- filetools.fs.open(localPath, "r", function(err) {
2142
- if (err && err.code === "ENOENT") {
2143
- callback(undefined, Utils.Errors.FILE_NOT_FOUND(localPath));
2144
- } else if (err) {
2145
- callback(undefined, err);
2146
- } else {
2147
- var items = filetools.findFiles(localPath);
2148
- var i = -1;
2149
- var next = function() {
2150
- i += 1;
2151
- if (i < items.length) {
2152
- var filepath = items[i];
2153
- var p = relativePath(localPath, filepath).split("\\").join("/");
2154
- p = p.normalize("NFD").replace(/[\u0300-\u036f]/g, "").replace(/[^\x20-\x7E]/g, "");
2155
- if (filter(p)) {
2156
- filetools.fs.stat(filepath, function(er0, stats) {
2157
- if (er0)
2158
- callback(undefined, er0);
2159
- if (stats.isFile()) {
2160
- filetools.fs.readFile(filepath, function(er1, data) {
2161
- if (er1) {
2162
- callback(undefined, er1);
2163
- } else {
2164
- self.addFile(zipPath + p, data, "", stats);
2165
- next();
2166
- }
2167
- });
2168
- } else {
2169
- self.addFile(zipPath + p + "/", Buffer.alloc(0), "", stats);
2170
- next();
2171
- }
2172
- });
2173
- } else {
2174
- process.nextTick(() => {
2175
- next();
2176
- });
2177
- }
2178
- } else {
2179
- callback(true, undefined);
2180
- }
2181
- };
2182
- next();
2183
- }
2184
- });
2185
- },
2186
- addLocalFolderAsync2: function(options2, callback) {
2187
- const self = this;
2188
- options2 = typeof options2 === "object" ? options2 : { localPath: options2 };
2189
- const localPath = pth.resolve(options2.localPath);
2190
- let { zipPath, filter, namefix } = options2;
2191
- if (filter instanceof RegExp) {
2192
- filter = function(rx) {
2193
- return function(filename) {
2194
- return rx.test(filename);
2195
- };
2196
- }(filter);
2197
- } else if (typeof filter !== "function") {
2198
- filter = function() {
2199
- return true;
2200
- };
2201
- }
2202
- zipPath = zipPath ? fixPath(zipPath) : "";
2203
- if (namefix === "latin1") {
2204
- namefix = (str) => str.normalize("NFD").replace(/[\u0300-\u036f]/g, "").replace(/[^\x20-\x7E]/g, "");
2205
- }
2206
- if (typeof namefix !== "function")
2207
- namefix = (str) => str;
2208
- const relPathFix = (entry) => pth.join(zipPath, namefix(relativePath(localPath, entry)));
2209
- const fileNameFix = (entry) => pth.win32.basename(pth.win32.normalize(namefix(entry)));
2210
- filetools.fs.open(localPath, "r", function(err) {
2211
- if (err && err.code === "ENOENT") {
2212
- callback(Utils.Errors.FILE_NOT_FOUND(localPath), false);
2213
- } else if (err) {
2214
- callback(err, false);
2215
- } else {
2216
- filetools.findFilesAsync(localPath, function(err2, fileEntries) {
2217
- if (err2)
2218
- return callback(err2, false);
2219
- fileEntries = fileEntries.filter((dir) => filter(relPathFix(dir)));
2220
- if (!fileEntries.length)
2221
- return callback(undefined, true);
2222
- setImmediate(fileEntries.reverse().reduce(function(next, entry) {
2223
- return function(err3, done) {
2224
- if (err3 || done === false)
2225
- return setImmediate(next, err3, false);
2226
- self.addLocalFileAsync({
2227
- localPath: entry,
2228
- zipPath: pth.dirname(relPathFix(entry)),
2229
- zipName: fileNameFix(entry)
2230
- }, next);
2231
- };
2232
- }, callback));
2233
- });
2234
- }
2235
- });
2236
- },
2237
- addLocalFolderPromise: function(localPath, props) {
2238
- return new Promise((resolve, reject) => {
2239
- this.addLocalFolderAsync2(Object.assign({ localPath }, props), (err, done) => {
2240
- if (err)
2241
- return reject(err);
2242
- if (done)
2243
- resolve(this);
2244
- });
2245
- });
2246
- },
2247
- addFile: function(entryName, content, comment, attr) {
2248
- entryName = zipnamefix(entryName);
2249
- let entry = getEntry(entryName);
2250
- const update = entry != null;
2251
- if (!update) {
2252
- entry = new ZipEntry(opts);
2253
- entry.entryName = entryName;
2254
- }
2255
- entry.comment = comment || "";
2256
- const isStat = typeof attr === "object" && attr instanceof filetools.fs.Stats;
2257
- if (isStat) {
2258
- entry.header.time = attr.mtime;
2259
- }
2260
- var fileattr = entry.isDirectory ? 16 : 0;
2261
- let unix = entry.isDirectory ? 16384 : 32768;
2262
- if (isStat) {
2263
- unix |= 4095 & attr.mode;
2264
- } else if (typeof attr === "number") {
2265
- unix |= 4095 & attr;
2266
- } else {
2267
- unix |= entry.isDirectory ? 493 : 420;
2268
- }
2269
- fileattr = (fileattr | unix << 16) >>> 0;
2270
- entry.attr = fileattr;
2271
- entry.setData(content);
2272
- if (!update)
2273
- _zip.setEntry(entry);
2274
- return entry;
2275
- },
2276
- getEntries: function(password) {
2277
- _zip.password = password;
2278
- return _zip ? _zip.entries : [];
2279
- },
2280
- getEntry: function(name) {
2281
- return getEntry(name);
2282
- },
2283
- getEntryCount: function() {
2284
- return _zip.getEntryCount();
2285
- },
2286
- forEach: function(callback) {
2287
- return _zip.forEach(callback);
2288
- },
2289
- extractEntryTo: function(entry, targetPath, maintainEntryPath, overwrite, keepOriginalPermission, outFileName) {
2290
- overwrite = get_Bool(false, overwrite);
2291
- keepOriginalPermission = get_Bool(false, keepOriginalPermission);
2292
- maintainEntryPath = get_Bool(true, maintainEntryPath);
2293
- outFileName = get_Str(keepOriginalPermission, outFileName);
2294
- var item = getEntry(entry);
2295
- if (!item) {
2296
- throw Utils.Errors.NO_ENTRY();
2297
- }
2298
- var entryName = canonical(item.entryName);
2299
- var target = sanitize(targetPath, outFileName && !item.isDirectory ? canonical(outFileName) : maintainEntryPath ? entryName : pth.basename(entryName));
2300
- if (item.isDirectory) {
2301
- var children = _zip.getEntryChildren(item);
2302
- children.forEach(function(child) {
2303
- if (child.isDirectory)
2304
- return;
2305
- var content2 = child.getData();
2306
- if (!content2) {
2307
- throw Utils.Errors.CANT_EXTRACT_FILE();
2308
- }
2309
- var name = canonical(maintainEntryPath ? child.entryName : child.entryName.substring(item.entryName.length));
2310
- var childName = sanitize(targetPath, name);
2311
- filetools.assertPathSafe(targetPath, childName);
2312
- const fileAttr2 = keepOriginalPermission ? child.header.fileAttr : undefined;
2313
- filetools.writeFileTo(childName, content2, overwrite, fileAttr2);
2314
- });
2315
- return true;
2316
- }
2317
- var content = item.getData(_zip.password);
2318
- if (!content)
2319
- throw Utils.Errors.CANT_EXTRACT_FILE();
2320
- filetools.assertPathSafe(targetPath, target);
2321
- if (filetools.fs.existsSync(target) && !overwrite) {
2322
- throw Utils.Errors.CANT_OVERRIDE();
2323
- }
2324
- const fileAttr = keepOriginalPermission ? entry.header.fileAttr : undefined;
2325
- filetools.writeFileTo(target, content, overwrite, fileAttr);
2326
- return true;
2327
- },
2328
- test: function(pass) {
2329
- if (!_zip) {
2330
- return false;
2331
- }
2332
- for (var entry of _zip.entries) {
2333
- try {
2334
- if (entry.isDirectory) {
2335
- continue;
2336
- }
2337
- var content = entry.getData(pass);
2338
- if (!content) {
2339
- return false;
2340
- }
2341
- } catch (err) {
2342
- return false;
2343
- }
2344
- }
2345
- return true;
2346
- },
2347
- extractAllTo: function(targetPath, overwrite, keepOriginalPermission, pass) {
2348
- keepOriginalPermission = get_Bool(false, keepOriginalPermission);
2349
- pass = get_Str(keepOriginalPermission, pass);
2350
- overwrite = get_Bool(false, overwrite);
2351
- if (!_zip)
2352
- throw Utils.Errors.NO_ZIP();
2353
- const dirEntries = [];
2354
- _zip.entries.forEach(function(entry) {
2355
- var entryName = sanitize(targetPath, canonical(entry.entryName));
2356
- filetools.assertPathSafe(targetPath, entryName);
2357
- if (entry.isDirectory) {
2358
- filetools.makeDir(entryName);
2359
- if (keepOriginalPermission)
2360
- dirEntries.push({ path: entryName, attr: entry.header.fileAttr });
2361
- return;
2362
- }
2363
- var content = entry.getData(pass);
2364
- if (!content) {
2365
- throw Utils.Errors.CANT_EXTRACT_FILE();
2366
- }
2367
- const fileAttr = keepOriginalPermission ? entry.header.fileAttr : undefined;
2368
- filetools.writeFileTo(entryName, content, overwrite, fileAttr);
2369
- try {
2370
- filetools.fs.utimesSync(entryName, entry.header.time, entry.header.time);
2371
- } catch (err) {}
2372
- });
2373
- applyDirAttributes(dirEntries);
2374
- },
2375
- extractAllToAsync: function(targetPath, overwrite, keepOriginalPermission, callback) {
2376
- callback = get_Fun(overwrite, keepOriginalPermission, callback);
2377
- keepOriginalPermission = get_Bool(false, keepOriginalPermission);
2378
- overwrite = get_Bool(false, overwrite);
2379
- if (!callback) {
2380
- return new Promise((resolve, reject) => {
2381
- this.extractAllToAsync(targetPath, overwrite, keepOriginalPermission, function(err) {
2382
- if (err) {
2383
- reject(err);
2384
- } else {
2385
- resolve(this);
2386
- }
2387
- });
2388
- });
2389
- }
2390
- if (!_zip) {
2391
- callback(Utils.Errors.NO_ZIP());
2392
- return;
2393
- }
2394
- targetPath = pth.resolve(targetPath);
2395
- const getPath = (entry) => sanitize(targetPath, pth.normalize(canonical(entry.entryName)));
2396
- const getError = (msg, file) => new Error(msg + ': "' + file + '"');
2397
- const dirEntries = [];
2398
- const fileEntries = [];
2399
- _zip.entries.forEach((e) => {
2400
- if (e.isDirectory) {
2401
- dirEntries.push(e);
2402
- } else {
2403
- fileEntries.push(e);
2404
- }
2405
- });
2406
- const deferredDirAttr = [];
2407
- for (const entry of dirEntries) {
2408
- const dirPath = getPath(entry);
2409
- const dirAttr = keepOriginalPermission ? entry.header.fileAttr : undefined;
2410
- try {
2411
- filetools.assertPathSafe(targetPath, dirPath);
2412
- filetools.makeDir(dirPath);
2413
- } catch (er) {
2414
- callback(getError("Unable to create folder", dirPath));
2415
- continue;
2416
- }
2417
- if (dirAttr)
2418
- deferredDirAttr.push({ path: dirPath, attr: dirAttr });
2419
- try {
2420
- filetools.fs.utimesSync(dirPath, entry.header.time, entry.header.time);
2421
- } catch (er) {}
2422
- }
2423
- const done = (err) => {
2424
- if (!err) {
2425
- try {
2426
- applyDirAttributes(deferredDirAttr);
2427
- } catch (er) {
2428
- return callback(getError("Unable to set folder permissions", er.path || ""));
2429
- }
2430
- }
2431
- callback(err);
2432
- };
2433
- fileEntries.reverse().reduce(function(next, entry) {
2434
- return function(err) {
2435
- if (err) {
2436
- next(err);
2437
- } else {
2438
- const entryName = pth.normalize(canonical(entry.entryName));
2439
- const filePath = sanitize(targetPath, entryName);
2440
- try {
2441
- filetools.assertPathSafe(targetPath, filePath);
2442
- } catch (er) {
2443
- return next(er);
2444
- }
2445
- entry.getDataAsync(function(content, err_1) {
2446
- if (err_1) {
2447
- next(err_1);
2448
- } else if (!content) {
2449
- next(Utils.Errors.CANT_EXTRACT_FILE());
2450
- } else {
2451
- const fileAttr = keepOriginalPermission ? entry.header.fileAttr : undefined;
2452
- filetools.writeFileToAsync(filePath, content, overwrite, fileAttr, function(succ) {
2453
- if (!succ) {
2454
- return next(getError("Unable to write file", filePath));
2455
- }
2456
- filetools.fs.utimes(filePath, entry.header.time, entry.header.time, function() {
2457
- next();
2458
- });
2459
- });
2460
- }
2461
- });
2462
- }
2463
- };
2464
- }, done)();
2465
- },
2466
- writeZip: function(targetFileName, callback) {
2467
- if (arguments.length === 1) {
2468
- if (typeof targetFileName === "function") {
2469
- callback = targetFileName;
2470
- targetFileName = "";
2471
- }
2472
- }
2473
- if (!targetFileName && opts.filename) {
2474
- targetFileName = opts.filename;
2475
- }
2476
- if (!targetFileName)
2477
- return;
2478
- var zipData = _zip.compressToBuffer();
2479
- if (zipData) {
2480
- var ok = filetools.writeFileTo(targetFileName, zipData, true);
2481
- if (typeof callback === "function")
2482
- callback(!ok ? new Error("failed") : null, "");
2483
- }
2484
- },
2485
- writeZipPromise: function(targetFileName, props) {
2486
- const { overwrite, perm } = Object.assign({ overwrite: true }, props);
2487
- return new Promise((resolve, reject) => {
2488
- if (!targetFileName && opts.filename)
2489
- targetFileName = opts.filename;
2490
- if (!targetFileName)
2491
- reject("ADM-ZIP: ZIP File Name Missing");
2492
- this.toBufferPromise().then((zipData) => {
2493
- const ret = (done) => done ? resolve(done) : reject("ADM-ZIP: Wasn't able to write zip file");
2494
- filetools.writeFileToAsync(targetFileName, zipData, overwrite, perm, ret);
2495
- }, reject);
2496
- });
2497
- },
2498
- toBufferPromise: function() {
2499
- return new Promise((resolve, reject) => {
2500
- _zip.toAsyncBuffer(resolve, reject);
2501
- });
2502
- },
2503
- toBuffer: function(onSuccess, onFail, onItemStart, onItemEnd) {
2504
- if (typeof onSuccess === "function") {
2505
- _zip.toAsyncBuffer(onSuccess, onFail, onItemStart, onItemEnd);
2506
- return null;
2507
- }
2508
- return _zip.compressToBuffer();
2509
- }
2510
- };
2511
- };
2512
- });
2513
-
2514
- // ../solution-sdk/src/studio-web-compat.ts
2515
- var API_PROJECT_TYPES = new Set(["api", "apiautomation"]);
2516
-
2517
- class StudioWebIncompatibleProjectError extends Error {
2518
- offendingProjects;
2519
- constructor(offendingProjects) {
2520
- super(`Studio Web cannot import API Workflow project(s) manifested by project.json: ${offendingProjects.join(", ")}. Studio Web's solution import accepts only project.uiproj-manifested projects.`);
2521
- this.offendingProjects = offendingProjects;
2522
- this.name = "StudioWebIncompatibleProjectError";
2523
- }
2524
- }
2525
- function assertStudioWebCompatibleProjects(projects) {
2526
- const incompatible = projects.filter((p) => typeof p.Type === "string" && API_PROJECT_TYPES.has(p.Type.toLowerCase()) && p.ProjectRelativePath.replace(/\\/g, "/").split("/").pop() === "project.json");
2527
- if (incompatible.length > 0) {
2528
- throw new StudioWebIncompatibleProjectError(incompatible.map((p) => p.ProjectRelativePath));
2529
- }
2530
- }
2531
-
2532
- // ../studioweb-sdk/generated/src/runtime.ts
2533
- var BASE_PATH = "https://alpha.uipath.com/studio_/backend".replace(/\/+$/, "");
2534
-
2535
- class Configuration {
2536
- configuration;
2537
- constructor(configuration = {}) {
2538
- this.configuration = configuration;
2539
- }
2540
- set config(configuration) {
2541
- this.configuration = configuration;
2542
- }
2543
- get basePath() {
2544
- return this.configuration.basePath != null ? this.configuration.basePath : BASE_PATH;
2545
- }
2546
- get fetchApi() {
2547
- return this.configuration.fetchApi;
2548
- }
2549
- get middleware() {
2550
- return this.configuration.middleware || [];
2551
- }
2552
- get queryParamsStringify() {
2553
- return this.configuration.queryParamsStringify || querystring;
2554
- }
2555
- get username() {
2556
- return this.configuration.username;
2557
- }
2558
- get password() {
2559
- return this.configuration.password;
2560
- }
2561
- get apiKey() {
2562
- const apiKey = this.configuration.apiKey;
2563
- if (apiKey) {
2564
- return typeof apiKey === "function" ? apiKey : () => apiKey;
2565
- }
2566
- return;
2567
- }
2568
- get accessToken() {
2569
- const accessToken = this.configuration.accessToken;
2570
- if (accessToken) {
2571
- return typeof accessToken === "function" ? accessToken : async () => accessToken;
2572
- }
2573
- return;
2574
- }
2575
- get headers() {
2576
- return this.configuration.headers;
2577
- }
2578
- get credentials() {
2579
- return this.configuration.credentials;
2580
- }
2581
- }
2582
- var DefaultConfig = new Configuration;
2583
-
2584
- class BaseAPI {
2585
- configuration;
2586
- static jsonRegex = new RegExp("^(:?application/json|[^;/ \t]+/[^;/ \t]+[+]json)[ \t]*(:?;.*)?$", "i");
2587
- middleware;
2588
- constructor(configuration = DefaultConfig) {
2589
- this.configuration = configuration;
2590
- this.middleware = configuration.middleware;
2591
- }
2592
- withMiddleware(...middlewares) {
2593
- const next = this.clone();
2594
- next.middleware = next.middleware.concat(...middlewares);
2595
- return next;
2596
- }
2597
- withPreMiddleware(...preMiddlewares) {
2598
- const middlewares = preMiddlewares.map((pre) => ({ pre }));
2599
- return this.withMiddleware(...middlewares);
2600
- }
2601
- withPostMiddleware(...postMiddlewares) {
2602
- const middlewares = postMiddlewares.map((post) => ({ post }));
2603
- return this.withMiddleware(...middlewares);
2604
- }
2605
- isJsonMime(mime) {
2606
- if (!mime) {
2607
- return false;
2608
- }
2609
- return BaseAPI.jsonRegex.test(mime);
2610
- }
2611
- async request(context, initOverrides) {
2612
- const { url, init } = await this.createFetchParams(context, initOverrides);
2613
- const response = await this.fetchApi(url, init);
2614
- if (response && (response.status >= 200 && response.status < 300)) {
2615
- return response;
2616
- }
2617
- throw new ResponseError(response, "Response returned an error code");
2618
- }
2619
- async createFetchParams(context, initOverrides) {
2620
- let url = this.configuration.basePath + context.path;
2621
- if (context.query !== undefined && Object.keys(context.query).length !== 0) {
2622
- url += "?" + this.configuration.queryParamsStringify(context.query);
2623
- }
2624
- const headers = Object.assign({}, this.configuration.headers, context.headers);
2625
- Object.keys(headers).forEach((key) => headers[key] === undefined ? delete headers[key] : {});
2626
- const initOverrideFn = typeof initOverrides === "function" ? initOverrides : async () => initOverrides;
2627
- const initParams = {
2628
- method: context.method,
2629
- headers,
2630
- body: context.body,
2631
- credentials: this.configuration.credentials
2632
- };
2633
- const overriddenInit = {
2634
- ...initParams,
2635
- ...await initOverrideFn({
2636
- init: initParams,
2637
- context
2638
- })
2639
- };
2640
- let body;
2641
- if (isFormData(overriddenInit.body) || overriddenInit.body instanceof URLSearchParams || isBlob(overriddenInit.body)) {
2642
- body = overriddenInit.body;
2643
- } else if (this.isJsonMime(headers["Content-Type"])) {
2644
- body = JSON.stringify(overriddenInit.body);
2645
- } else {
2646
- body = overriddenInit.body;
2647
- }
2648
- const init = {
2649
- ...overriddenInit,
2650
- body
2651
- };
2652
- return { url, init };
2653
- }
2654
- fetchApi = async (url, init) => {
2655
- let fetchParams = { url, init };
2656
- for (const middleware of this.middleware) {
2657
- if (middleware.pre) {
2658
- fetchParams = await middleware.pre({
2659
- fetch: this.fetchApi,
2660
- ...fetchParams
2661
- }) || fetchParams;
2662
- }
2663
- }
2664
- let response = undefined;
2665
- try {
2666
- response = await (this.configuration.fetchApi || fetch)(fetchParams.url, fetchParams.init);
2667
- } catch (e) {
2668
- for (const middleware of this.middleware) {
2669
- if (middleware.onError) {
2670
- response = await middleware.onError({
2671
- fetch: this.fetchApi,
2672
- url: fetchParams.url,
2673
- init: fetchParams.init,
2674
- error: e,
2675
- response: response ? response.clone() : undefined
2676
- }) || response;
2677
- }
2678
- }
2679
- if (response === undefined) {
2680
- if (e instanceof Error) {
2681
- throw new FetchError(e, "The request failed and the interceptors did not return an alternative response");
2682
- } else {
2683
- throw e;
2684
- }
2685
- }
2686
- }
2687
- for (const middleware of this.middleware) {
2688
- if (middleware.post) {
2689
- response = await middleware.post({
2690
- fetch: this.fetchApi,
2691
- url: fetchParams.url,
2692
- init: fetchParams.init,
2693
- response: response.clone()
2694
- }) || response;
2695
- }
2696
- }
2697
- return response;
2698
- };
2699
- clone() {
2700
- const constructor = this.constructor;
2701
- const next = new constructor(this.configuration);
2702
- next.middleware = this.middleware.slice();
2703
- return next;
2704
- }
2705
- }
2706
- function isBlob(value) {
2707
- return typeof Blob !== "undefined" && value instanceof Blob;
2708
- }
2709
- function isFormData(value) {
2710
- return typeof FormData !== "undefined" && value instanceof FormData;
2711
- }
2712
-
2713
- class ResponseError extends Error {
2714
- response;
2715
- name = "ResponseError";
2716
- constructor(response, msg) {
2717
- super(msg);
2718
- this.response = response;
2719
- }
2720
- }
2721
-
2722
- class FetchError extends Error {
2723
- cause;
2724
- name = "FetchError";
2725
- constructor(cause, msg) {
2726
- super(msg);
2727
- this.cause = cause;
2728
- }
2729
- }
2730
- function querystring(params, prefix = "") {
2731
- return Object.keys(params).map((key) => querystringSingleKey(key, params[key], prefix)).filter((part) => part.length > 0).join("&");
2732
- }
2733
- function querystringSingleKey(key, value, keyPrefix = "") {
2734
- const fullKey = keyPrefix + (keyPrefix.length ? `[${key}]` : key);
2735
- if (value instanceof Array) {
2736
- const multiValue = value.map((singleValue) => encodeURIComponent(String(singleValue))).join(`&${encodeURIComponent(fullKey)}=`);
2737
- return `${encodeURIComponent(fullKey)}=${multiValue}`;
2738
- }
2739
- if (value instanceof Set) {
2740
- const valueAsArray = Array.from(value);
2741
- return querystringSingleKey(key, valueAsArray, keyPrefix);
2742
- }
2743
- if (value instanceof Date) {
2744
- return `${encodeURIComponent(fullKey)}=${encodeURIComponent(value.toISOString())}`;
2745
- }
2746
- if (value instanceof Object) {
2747
- return querystring(value, fullKey);
2748
- }
2749
- return `${encodeURIComponent(fullKey)}=${encodeURIComponent(String(value))}`;
2750
- }
2751
- // ../solution-sdk/generated/src/runtime.ts
2752
- var BASE_PATH2 = "https://alpha.uipath.com/uipattycyrhx/abizon_1/automationsolutions_".replace(/\/+$/, "");
2753
-
2754
- class Configuration2 {
2755
- configuration;
2756
- constructor(configuration = {}) {
2757
- this.configuration = configuration;
2758
- }
2759
- set config(configuration) {
2760
- this.configuration = configuration;
2761
- }
2762
- get basePath() {
2763
- return this.configuration.basePath != null ? this.configuration.basePath : BASE_PATH2;
2764
- }
2765
- get fetchApi() {
2766
- return this.configuration.fetchApi;
2767
- }
2768
- get middleware() {
2769
- return this.configuration.middleware || [];
2770
- }
2771
- get queryParamsStringify() {
2772
- return this.configuration.queryParamsStringify || querystring2;
2773
- }
2774
- get username() {
2775
- return this.configuration.username;
2776
- }
2777
- get password() {
2778
- return this.configuration.password;
2779
- }
2780
- get apiKey() {
2781
- const apiKey = this.configuration.apiKey;
2782
- if (apiKey) {
2783
- return typeof apiKey === "function" ? apiKey : () => apiKey;
2784
- }
2785
- return;
2786
- }
2787
- get accessToken() {
2788
- const accessToken = this.configuration.accessToken;
2789
- if (accessToken) {
2790
- return typeof accessToken === "function" ? accessToken : async () => accessToken;
2791
- }
2792
- return;
2793
- }
2794
- get headers() {
2795
- return this.configuration.headers;
2796
- }
2797
- get credentials() {
2798
- return this.configuration.credentials;
2799
- }
2800
- }
2801
- var DefaultConfig2 = new Configuration2;
2802
-
2803
- class BaseAPI2 {
2804
- configuration;
2805
- static jsonRegex = new RegExp("^(:?application/json|[^;/ \t]+/[^;/ \t]+[+]json)[ \t]*(:?;.*)?$", "i");
2806
- middleware;
2807
- constructor(configuration = DefaultConfig2) {
2808
- this.configuration = configuration;
2809
- this.middleware = configuration.middleware;
2810
- }
2811
- withMiddleware(...middlewares) {
2812
- const next = this.clone();
2813
- next.middleware = next.middleware.concat(...middlewares);
2814
- return next;
2815
- }
2816
- withPreMiddleware(...preMiddlewares) {
2817
- const middlewares = preMiddlewares.map((pre) => ({ pre }));
2818
- return this.withMiddleware(...middlewares);
2819
- }
2820
- withPostMiddleware(...postMiddlewares) {
2821
- const middlewares = postMiddlewares.map((post) => ({ post }));
2822
- return this.withMiddleware(...middlewares);
2823
- }
2824
- isJsonMime(mime) {
2825
- if (!mime) {
2826
- return false;
2827
- }
2828
- return BaseAPI2.jsonRegex.test(mime);
2829
- }
2830
- async request(context, initOverrides) {
2831
- const { url, init } = await this.createFetchParams(context, initOverrides);
2832
- const response = await this.fetchApi(url, init);
2833
- if (response && (response.status >= 200 && response.status < 300)) {
2834
- return response;
2835
- }
2836
- throw new ResponseError2(response, "Response returned an error code");
2837
- }
2838
- async createFetchParams(context, initOverrides) {
2839
- let url = this.configuration.basePath + context.path;
2840
- if (context.query !== undefined && Object.keys(context.query).length !== 0) {
2841
- url += "?" + this.configuration.queryParamsStringify(context.query);
2842
- }
2843
- const headers = Object.assign({}, this.configuration.headers, context.headers);
2844
- Object.keys(headers).forEach((key) => headers[key] === undefined ? delete headers[key] : {});
2845
- const initOverrideFn = typeof initOverrides === "function" ? initOverrides : async () => initOverrides;
2846
- const initParams = {
2847
- method: context.method,
2848
- headers,
2849
- body: context.body,
2850
- credentials: this.configuration.credentials
2851
- };
2852
- const overriddenInit = {
2853
- ...initParams,
2854
- ...await initOverrideFn({
2855
- init: initParams,
2856
- context
2857
- })
2858
- };
2859
- let body;
2860
- if (isFormData2(overriddenInit.body) || overriddenInit.body instanceof URLSearchParams || isBlob2(overriddenInit.body)) {
2861
- body = overriddenInit.body;
2862
- } else if (this.isJsonMime(headers["Content-Type"])) {
2863
- body = JSON.stringify(overriddenInit.body);
2864
- } else {
2865
- body = overriddenInit.body;
2866
- }
2867
- const init = {
2868
- ...overriddenInit,
2869
- body
2870
- };
2871
- return { url, init };
2872
- }
2873
- fetchApi = async (url, init) => {
2874
- let fetchParams = { url, init };
2875
- for (const middleware of this.middleware) {
2876
- if (middleware.pre) {
2877
- fetchParams = await middleware.pre({
2878
- fetch: this.fetchApi,
2879
- ...fetchParams
2880
- }) || fetchParams;
2881
- }
2882
- }
2883
- let response = undefined;
2884
- try {
2885
- response = await (this.configuration.fetchApi || fetch)(fetchParams.url, fetchParams.init);
2886
- } catch (e) {
2887
- for (const middleware of this.middleware) {
2888
- if (middleware.onError) {
2889
- response = await middleware.onError({
2890
- fetch: this.fetchApi,
2891
- url: fetchParams.url,
2892
- init: fetchParams.init,
2893
- error: e,
2894
- response: response ? response.clone() : undefined
2895
- }) || response;
2896
- }
2897
- }
2898
- if (response === undefined) {
2899
- if (e instanceof Error) {
2900
- throw new FetchError2(e, "The request failed and the interceptors did not return an alternative response");
2901
- } else {
2902
- throw e;
2903
- }
2904
- }
2905
- }
2906
- for (const middleware of this.middleware) {
2907
- if (middleware.post) {
2908
- response = await middleware.post({
2909
- fetch: this.fetchApi,
2910
- url: fetchParams.url,
2911
- init: fetchParams.init,
2912
- response: response.clone()
2913
- }) || response;
2914
- }
2915
- }
2916
- return response;
2917
- };
2918
- clone() {
2919
- const constructor = this.constructor;
2920
- const next = new constructor(this.configuration);
2921
- next.middleware = this.middleware.slice();
2922
- return next;
2923
- }
2924
- }
2925
- function isBlob2(value) {
2926
- return typeof Blob !== "undefined" && value instanceof Blob;
2927
- }
2928
- function isFormData2(value) {
2929
- return typeof FormData !== "undefined" && value instanceof FormData;
2930
- }
2931
-
2932
- class ResponseError2 extends Error {
2933
- response;
2934
- name = "ResponseError";
2935
- constructor(response, msg) {
2936
- super(msg);
2937
- this.response = response;
2938
- }
2939
- }
2940
-
2941
- class FetchError2 extends Error {
2942
- cause;
2943
- name = "FetchError";
2944
- constructor(cause, msg) {
2945
- super(msg);
2946
- this.cause = cause;
2947
- }
2948
- }
2949
- function querystring2(params, prefix = "") {
2950
- return Object.keys(params).map((key) => querystringSingleKey2(key, params[key], prefix)).filter((part) => part.length > 0).join("&");
2951
- }
2952
- function querystringSingleKey2(key, value, keyPrefix = "") {
2953
- const fullKey = keyPrefix + (keyPrefix.length ? `[${key}]` : key);
2954
- if (value instanceof Array) {
2955
- const multiValue = value.map((singleValue) => encodeURIComponent(String(singleValue))).join(`&${encodeURIComponent(fullKey)}=`);
2956
- return `${encodeURIComponent(fullKey)}=${multiValue}`;
2957
- }
2958
- if (value instanceof Set) {
2959
- const valueAsArray = Array.from(value);
2960
- return querystringSingleKey2(key, valueAsArray, keyPrefix);
2961
- }
2962
- if (value instanceof Date) {
2963
- return `${encodeURIComponent(fullKey)}=${encodeURIComponent(value.toISOString())}`;
2964
- }
2965
- if (value instanceof Object) {
2966
- return querystring2(value, fullKey);
2967
- }
2968
- return `${encodeURIComponent(fullKey)}=${encodeURIComponent(String(value))}`;
2969
- }
2970
- // ../solution-sdk/package.json
2971
- var package_default = {
2972
- name: "@uipath/solution-sdk",
2973
- license: "SEE LICENSE IN LICENSE.txt",
2974
- version: "1.202.1",
2975
- repository: {
2976
- type: "git",
2977
- url: "https://github.com/UiPath/cli.git",
2978
- directory: "packages/solution-sdk"
2979
- },
2980
- publishConfig: {
2981
- registry: "https://npm.pkg.github.com/@uipath"
2982
- },
2983
- keywords: [
2984
- "uipath",
2985
- "solution",
2986
- "sdk"
2987
- ],
2988
- type: "module",
2989
- main: "./dist/index.js",
2990
- types: "./dist/src/index.d.ts",
2991
- exports: {
2992
- ".": {
2993
- types: "./dist/src/index.d.ts",
2994
- default: "./dist/index.js"
2995
- },
2996
- "./resources": {
2997
- types: "./dist/src/resources/index.d.ts",
2998
- default: "./dist/resources/index.js"
2999
- },
3000
- "./auth": {
3001
- types: "./dist/src/solution-auth.d.ts",
3002
- default: "./dist/solution-auth.js"
3003
- }
3004
- },
3005
- bin: {
3006
- "generate-sdk": "./dist/scripts/generate-sdk.js"
3007
- },
3008
- files: [
3009
- "dist"
3010
- ],
3011
- private: false,
3012
- scripts: {
3013
- build: "bun build ./src/index.ts ./src/resources/index.ts ./src/solution-auth.ts --outdir dist --format esm --target node --sourcemap=linked && bun build ./src/scripts/generate-sdk.ts --outdir dist/scripts --format esm --target node --sourcemap=linked && tsc -p tsconfig.build.json --noCheck",
3014
- generate: "bun run src/scripts/generate-sdk.ts",
3015
- lint: "biome check .",
3016
- test: "vitest run",
3017
- "test:coverage": "vitest run --coverage"
3018
- },
3019
- devDependencies: {
3020
- "@openapitools/openapi-generator-cli": "^2.31.1",
3021
- "@uipath/auth": "workspace:*",
3022
- "@uipath/common": "workspace:*",
3023
- "@uipath/filesystem": "workspace:*",
3024
- "@uipath/orchestrator-sdk": "workspace:*",
3025
- "@uipath/resource-builder-sdk": "^2025.11.0-alpha4202-3459",
3026
- "@uipath/solutionpackager-tool-core": "workspace:*",
3027
- "@uipath/studioweb-sdk": "workspace:*",
3028
- "@types/node": "^25.5.2",
3029
- fflate: "^0.8.2",
3030
- typescript: "^7.0.2"
3031
- }
3032
- };
3033
-
3034
- // ../solution-sdk/src/user-agent.ts
3035
- var SDK_USER_AGENT = getSdkUserAgentToken(package_default);
3036
- installSdkUserAgentHeader(BaseAPI2, SDK_USER_AGENT);
3037
-
3038
- // ../solution-sdk/src/upload-service.ts
3039
- class SolutionUploadHttpError extends Error {
3040
- status;
3041
- operation;
3042
- method;
3043
- endpoint;
3044
- url;
3045
- body;
3046
- solutionId;
3047
- parsedErrorCode;
3048
- parsedErrorMessage;
3049
- authChallenge;
3050
- constructor(details) {
3051
- super(details.message);
3052
- this.name = "SolutionUploadHttpError";
3053
- this.status = details.status;
3054
- this.operation = details.operation;
3055
- this.method = details.method;
3056
- this.endpoint = details.endpoint;
3057
- this.url = details.url;
3058
- this.body = details.body;
3059
- if (details.operation === "overwrite") {
3060
- this.solutionId = details.solutionId;
3061
- }
3062
- this.authChallenge = details.authChallenge;
3063
- const parsed = parseUploadErrorBody(details.body);
3064
- this.parsedErrorCode = parsed.code;
3065
- this.parsedErrorMessage = parsed.message;
3066
- }
3067
- }
3068
- function parseUploadErrorBody(body) {
3069
- const [, parsed] = catchError(() => JSON.parse(body));
3070
- if (!parsed || typeof parsed !== "object")
3071
- return {};
3072
- const rawCode = parsed.code ?? parsed.Code;
3073
- const rawMessage = parsed.message ?? parsed.Message;
3074
- return {
3075
- code: typeof rawCode === "string" || typeof rawCode === "number" ? String(rawCode) : undefined,
3076
- message: typeof rawMessage === "string" && rawMessage.trim() ? rawMessage : undefined
3077
- };
3078
- }
3079
- function isSolutionUploadHttpError(error) {
3080
- return error instanceof Error && error.name === "SolutionUploadHttpError" && "operation" in error && (error.operation === "import" || error.operation === "overwrite") && "status" in error && typeof error.status === "number" && "body" in error && typeof error.body === "string";
3081
- }
3082
- function requestPath(url) {
3083
- const [, parsed] = catchError(() => new URL(url));
3084
- return parsed ? `${parsed.pathname}${parsed.search}` : url;
3085
- }
3086
- var TOKEN_SHAPED = /\beyJ[A-Za-z0-9_-]{6,}\.[A-Za-z0-9_-]+(?:\.[A-Za-z0-9_-]*)?|\bBearer\s+[A-Za-z0-9._~+/=-]{8,}/gi;
3087
- function redactTokens(text) {
3088
- return text.replace(TOKEN_SHAPED, "[REDACTED]");
3089
- }
3090
- var MAX_CHALLENGE_DESCRIPTION = 200;
3091
- function parseAuthChallenge(header) {
3092
- if (!header)
3093
- return {};
3094
- const code = /\berror="([^"]*)"/.exec(header)?.[1]?.trim();
3095
- const raw = /\berror_description="([^"]*)"/.exec(header)?.[1]?.trim();
3096
- const description = raw ? redactTokens(raw).slice(0, MAX_CHALLENGE_DESCRIPTION) : undefined;
3097
- return {
3098
- error: code || undefined,
3099
- description: description || undefined
3100
- };
3101
- }
3102
- function summarizeAuthRefusalBody(body) {
3103
- return summarizePlatformBody(redactTokens(body));
3104
- }
3105
- function isAuthRefusal(status) {
3106
- return status === 401 || status === 403;
3107
- }
3108
- function buildAuthRefusalInstructions({
3109
- err,
3110
- subject,
3111
- target,
3112
- bodySuffix,
3113
- identityType,
3114
- clientId
3115
- }) {
3116
- const refusal = err.status === 401 ? "rejected the call as unauthorized (401)" : "forbade the call (403)";
3117
- const what = err.operation === "overwrite" ? `replacing the contents of solution ${target}` : "importing the solution package";
3118
- const actor = identityType === "Application" ? `This session acts as external application ${clientId ?? "(client id unknown)"}, so ` + `check what that application is allowed to do: it needs the Studio ` + `Web scopes that cover writing a solution (the StudioWebS2S grants ` + `on the external application), not just the Orchestrator or ` + `Solutions ones. ` : identityType === "User" ? `This session acts as a user, so check that your account has ` + `Studio Web access in this tenant. ` : `Check what this session is allowed to do in Studio Web — an ` + `external application needs the StudioWebS2S grants that cover ` + `writing a solution, a user needs Studio Web access in the tenant. `;
3119
- const tenant = err.operation === "overwrite" ? `Also confirm that ${target} is the solution this project should ` + `publish to, and that it lives in the organization and tenant ` + `this session logged into — the id comes from the SolutionId ` + `recorded in the enclosing solution file. An id this session ` + `cannot see at all is reported separately, as nothing to ` + `overwrite, so a refusal here points at the grants first. ` : `Also confirm you are logged into the organization and tenant the ` + `solution should land in. `;
3120
- const challenge = parseAuthChallenge(err.authChallenge);
3121
- const quoted = challenge.description ? ` ("${challenge.description}")` : "";
3122
- if (challenge.error === "invalid_token") {
3123
- return `Studio Web ${refusal} while ${what}, and rejected the credential ` + `itself with the reason \`invalid_token\`${quoted}. That is the ` + `platform refusing this token rather than the permissions behind ` + `it, so unlike a grants refusal this one is worth a fresh ` + `\`uip login\` — or, in a pipeline, a newly minted ` + `client-credentials token. Check too that the token was issued for ` + `the organization being called: one minted against a different ` + `environment or audience is refused this way. Nothing was uploaded ` + `and nothing ran, so the ${subject} is not the cause.${bodySuffix}`;
3124
- }
3125
- const authenticated = `The session is authenticated — the token was issued and had not ` + `expired when the call went out — so re-running \`uip login\` mints ` + `the same token and fails the same way. `;
3126
- const diagnosis = challenge.error === "insufficient_scope" ? `Studio Web reported \`insufficient_scope\`${quoted}, so the ` + `token is valid and simply not allowed to do this: logging in ` + `again will not change it. ` : challenge.error ? `${authenticated}Studio Web gave the reason ` + `\`${challenge.error}\`${quoted}. ` : authenticated;
3127
- const closing = bodySuffix ? `If the grants and the tenant are already right, report the platform ` + `response, including its traceId.${bodySuffix}` : challenge.error ? `If the grants and the tenant are already right, report that reason ` + `together with the request path and status above.` : `If the grants and the tenant are already right, report the request ` + `path and status above — Studio Web returned no response body and ` + `no authentication challenge, so there is nothing further to quote.`;
3128
- return `Studio Web ${refusal} while ${what}. ${diagnosis}${actor}${tenant}` + `Nothing was uploaded and nothing ran, so the ${subject} is not the ` + `cause. ${closing}`;
3129
- }
3130
- function buildSolutionUploadFailureOutput(err, options = {}) {
3131
- const stage = err.operation === "overwrite" ? "overwrite-solution" : "import-solution";
3132
- const authRefusal = isAuthRefusal(err.status);
3133
- const parsedMessage = authRefusal && err.parsedErrorMessage ? redactTokens(err.parsedErrorMessage) : err.parsedErrorMessage;
3134
- const detail = parsedMessage ? ` — ${parsedMessage}` : "";
3135
- const Message = `Failed during ${stage}: HTTP ${err.status} on ${err.method} ` + `${err.endpoint}${detail}`;
3136
- const quote = authRefusal ? summarizeAuthRefusalBody : summarizePlatformBody;
3137
- const body = err.parsedErrorMessage ? "" : quote(err.body);
3138
- const bodySuffix = body ? ` Platform response: "${body}".` : "";
3139
- const importHint = options.importCheckHint ? ` ${options.importCheckHint}` : "";
3140
- const subject = options.subject ?? "project";
3141
- const target = err.solutionId ?? `the solution at ${err.endpoint}`;
3142
- const authInstructions = isAuthRefusal(err.status) ? buildAuthRefusalInstructions({
3143
- err,
3144
- subject,
3145
- target,
3146
- bodySuffix,
3147
- identityType: options.identityType,
3148
- clientId: options.clientId
3149
- }) : undefined;
3150
- const Instructions = authInstructions ?? (err.operation === "overwrite" ? `Studio Web refused to replace the contents of solution ` + `${target}. Nothing was uploaded and nothing ran, so the ` + `${subject} is not the cause: do not re-author it, and do not ` + `copy the project into another solution. Confirm that ${target} ` + `is a solution you can still write to, and that it is the one ` + `this project should publish to — it comes from the SolutionId ` + `recorded in the enclosing solution file. If it is right, report ` + `the platform response.${bodySuffix}` : `Studio Web refused to import the solution package. Nothing was ` + `uploaded and nothing ran, so no part of the ${subject} executed ` + `— but the package itself may be what was rejected.${importHint} ` + `Report the platform response if the ${subject} is ` + `well-formed.${bodySuffix}`);
3151
- const Context = {
3152
- httpStatus: err.status,
3153
- stage,
3154
- endpoint: err.endpoint,
3155
- method: err.method
3156
- };
3157
- if (err.parsedErrorCode !== undefined) {
3158
- Context.errorCode = err.parsedErrorCode;
3159
- }
3160
- const output = {
3161
- Result: RESULTS.Failure,
3162
- Message,
3163
- Instructions,
3164
- Context
3165
- };
3166
- if (err.status === 401 && options.identityType === "Application") {
3167
- output.ErrorCode = "permission_denied";
3168
- }
3169
- if (err.operation === "overwrite" && err.status >= 500 && err.status < 600) {
3170
- output.Retry = "RetryAfter30Seconds";
3171
- }
3172
- return output;
3173
- }
3174
- var DEFAULT_UPLOAD_TIMEOUT_MS = 120000;
3175
- function resolveUploadTimeoutMs() {
3176
- const raw = Number(process.env?.UIPATH_SOLUTION_UPLOAD_TIMEOUT_MS);
3177
- return Number.isFinite(raw) && raw > 0 ? raw : DEFAULT_UPLOAD_TIMEOUT_MS;
3178
- }
3179
- function formatTimeout(timeoutMs) {
3180
- return timeoutMs < 1000 ? `${Math.round(timeoutMs)}ms` : `${Math.round(timeoutMs / 1000)}s`;
3181
- }
3182
- function timeoutMessage(what, timeoutMs) {
3183
- return `${what} timed out after ${formatTimeout(timeoutMs)} — the connection ` + `stalled with no response from Studio Web. Retry the command; if it keeps ` + `timing out, check connectivity (VPN/proxy) to the tenant, or raise the ` + `ceiling with UIPATH_SOLUTION_UPLOAD_TIMEOUT_MS.`;
3184
- }
3185
- function isTimeoutError(error) {
3186
- let current = error;
3187
- for (let depth = 0;depth < 5 && current instanceof Error; depth += 1) {
3188
- if (current.name === "TimeoutError")
3189
- return true;
3190
- current = current.cause;
3191
- }
3192
- return false;
3193
- }
3194
- async function fetchWithUploadTimeout(url, init, what) {
3195
- const timeoutMs = resolveUploadTimeoutMs();
3196
- const [error, response] = await catchError(fetch(url, { ...init, signal: AbortSignal.timeout(timeoutMs) }));
3197
- if (error) {
3198
- if (isTimeoutError(error)) {
3199
- throw new Error(timeoutMessage(what, timeoutMs));
3200
- }
3201
- throw error;
3202
- }
3203
- return response;
3204
- }
3205
- async function importSolution(config, organizationName, fileBuffer, fileName) {
3206
- const importUrl = `${config.baseUrl}/${encodeURIComponent(organizationName)}/studio_/backend/api/Solution/Import?desktopJit=true&useFileRest=true&enableUnifiedBuild=true`;
3207
- const formData = new FormData;
3208
- const fileBlob = new Blob([fileBuffer], {
3209
- type: "application/octet-stream"
3210
- });
3211
- formData.append("uploadFile", fileBlob, fileName);
3212
- formData.append("telemetryData", JSON.stringify({ FirstRun: false }));
3213
- const headers = addSdkUserAgentHeader({
3214
- Authorization: `Bearer ${config.authToken}`
3215
- }, SDK_USER_AGENT);
3216
- if (config.tenantId) {
3217
- headers["x-uipath-tenantid"] = config.tenantId;
3218
- }
3219
- const response = await fetchWithUploadTimeout(importUrl, { method: "POST", headers, body: formData }, "Studio Web solution import");
3220
- if (!response.ok) {
3221
- const text = await response.text().catch(() => "");
3222
- throw new SolutionUploadHttpError({
3223
- operation: "import",
3224
- status: response.status,
3225
- method: "POST",
3226
- endpoint: requestPath(importUrl),
3227
- url: importUrl,
3228
- body: text,
3229
- authChallenge: response.headers?.get("www-authenticate") ?? undefined,
3230
- message: `Import failed (${response.status}): ${text}`
3231
- });
3232
- }
3233
- return await response.json();
3234
- }
3235
- async function overwriteSolution(config, organizationName, fileBuffer, fileName, solutionId, createSnapshot = false) {
3236
- const overwriteUrl = `${config.baseUrl}/${encodeURIComponent(organizationName)}/studio_/backend/api/Solution/${encodeURIComponent(solutionId)}/Overwrite`;
3237
- const formData = new FormData;
3238
- const fileBlob = new Blob([fileBuffer], {
3239
- type: "application/octet-stream"
3240
- });
3241
- formData.append("UploadFile", fileBlob, fileName);
3242
- if (createSnapshot) {
3243
- formData.append("createSnapshot", "true");
3244
- }
3245
- const headers = addSdkUserAgentHeader({
3246
- Authorization: `Bearer ${config.authToken}`
3247
- }, SDK_USER_AGENT);
3248
- if (config.tenantId) {
3249
- headers["x-uipath-tenantid"] = config.tenantId;
3250
- }
3251
- const response = await fetchWithUploadTimeout(overwriteUrl, { method: "POST", headers, body: formData }, "Studio Web solution overwrite");
3252
- if (!response.ok) {
3253
- const text = await response.text().catch(() => "");
3254
- throw new SolutionUploadHttpError({
3255
- operation: "overwrite",
3256
- status: response.status,
3257
- method: "POST",
3258
- endpoint: requestPath(overwriteUrl),
3259
- url: overwriteUrl,
3260
- body: text,
3261
- authChallenge: response.headers?.get("www-authenticate") ?? undefined,
3262
- message: `Overwrite failed (${response.status}): ${text}`,
3263
- solutionId
3264
- });
3265
- }
3266
- return await response.json();
3267
- }
3268
- async function uploadOrOverwriteSolution(config, organizationName, fileBufferOrPath, solutionId, fs) {
3269
- let fileBuffer;
3270
- let fileName;
3271
- if (typeof fileBufferOrPath === "string") {
3272
- if (!fs) {
3273
- throw new Error("IFileSystem is required when passing a file path to uploadOrOverwriteSolution");
3274
- }
3275
- const content = await fs.readFile(fileBufferOrPath);
3276
- if (content === null) {
3277
- throw new Error(`Failed to read file: ${fileBufferOrPath}`);
3278
- }
3279
- fileBuffer = new Uint8Array(content);
3280
- fileName = fs.path.basename(fileBufferOrPath);
3281
- } else {
3282
- fileBuffer = fileBufferOrPath;
3283
- fileName = "solution.uis";
3284
- }
3285
- if (solutionId) {
3286
- logger.info(`Attempting to overwrite existing solution ${solutionId} on Studio Web...`);
3287
- const [overwriteError, overwriteResult] = await catchError(overwriteSolution(config, organizationName, fileBuffer, fileName, solutionId));
3288
- if (!overwriteError) {
3289
- logger.info("Solution overwritten successfully.");
3290
- return overwriteResult;
3291
- }
3292
- if (isSolutionUploadHttpError(overwriteError) && overwriteError.status === 404) {
3293
- logger.info(`Solution ${solutionId} not found on Studio Web. Importing as new solution...`);
3294
- } else {
3295
- throw overwriteError;
3296
- }
3297
- }
3298
- logger.info("Importing new solution to Studio Web...");
3299
- return importSolution(config, organizationName, fileBuffer, fileName);
3300
- }
3301
- // ../solution-sdk/src/zip-utils.ts
3302
- var DEFAULT_EXCLUDED_DIR_NAMES = new Set([
3303
- ".venv",
3304
- "node_modules",
3305
- "__pycache__",
3306
- ".git",
3307
- ".local"
3308
- ]);
3309
- var DEFAULT_EXCLUDED_FILE_PATTERNS = [
3310
- /^\.env($|\..+)/
3311
- ];
3312
- function isDefaultExcludedFileName(name) {
3313
- for (const pattern of DEFAULT_EXCLUDED_FILE_PATTERNS) {
3314
- if (pattern.test(name)) {
3315
- return true;
3316
- }
3317
- }
3318
- return false;
3319
- }
3320
- var UIPIGNORE_FILENAME = ".uipignore";
3321
- function parseUipignore(body) {
3322
- const names = new Set;
3323
- for (const rawLine of body.split(/\r?\n/)) {
3324
- const line = rawLine.split("#")[0]?.trim();
3325
- if (!line) {
3326
- continue;
3327
- }
3328
- if (line.includes("/") || line.includes("\\")) {
3329
- continue;
3330
- }
3331
- names.add(line);
3332
- }
3333
- return names;
3334
- }
3335
- async function collectTree(fs, dir, options = {}) {
3336
- const files = [];
3337
- const emptyDirs = [];
3338
- const excluded = new Set(DEFAULT_EXCLUDED_DIR_NAMES);
3339
- if (options.additionalExcludeDirs) {
3340
- for (const name of options.additionalExcludeDirs) {
3341
- excluded.add(name);
3342
- }
3343
- }
3344
- async function walk(current, isRoot) {
3345
- const entries = await fs.readdir(current);
3346
- if (entries.length === 0) {
3347
- if (!isRoot) {
3348
- emptyDirs.push(current);
3349
- }
3350
- return;
3351
- }
3352
- for (const entryName of entries) {
3353
- const fullPath = fs.path.join(current, entryName);
3354
- const entryStat = await fs.stat(fullPath);
3355
- if (entryStat?.isDirectory()) {
3356
- if (excluded.has(entryName)) {
3357
- continue;
3358
- }
3359
- await walk(fullPath, false);
3360
- } else if (entryStat?.isFile()) {
3361
- if (isDefaultExcludedFileName(entryName)) {
3362
- continue;
3363
- }
3364
- files.push(fullPath);
3365
- }
3366
- }
3367
- }
3368
- await walk(dir, true);
3369
- return { files, emptyDirs };
3370
- }
3371
- async function createZipFromDir(fs, dir, options = {}) {
3372
- const { files, emptyDirs } = await collectTree(fs, dir, options);
3373
- const zippable = {};
3374
- for (const filePath of files) {
3375
- const relPath = fs.path.relative(dir, filePath).replace(/\\/g, "/");
3376
- const data = await fs.readFile(filePath);
3377
- if (data) {
3378
- zippable[relPath] = new Uint8Array(data);
3379
- }
3380
- }
3381
- for (const emptyDir of emptyDirs) {
3382
- const relPath = fs.path.relative(dir, emptyDir).replace(/\\/g, "/");
3383
- if (!relPath) {
3384
- continue;
3385
- }
3386
- zippable[`${relPath}/`] = new Uint8Array(0);
3387
- }
3388
- return finalizeZip64(zipSync(zippable, { level: 6 }));
3389
- }
3390
- var EOCD_SIZE = 22;
3391
- var EOCD_SIGNATURE = 101010256;
3392
- var CD_HEADER_SIGNATURE = 33639248;
3393
- var ZIP64_EOCD_SIGNATURE = 101075792;
3394
- var ZIP64_EOCD_SIZE = 56;
3395
- var ZIP64_LOCATOR_SIGNATURE = 117853008;
3396
- var ZIP64_LOCATOR_SIZE = 20;
3397
- var MAX_ZIP32_ENTRIES = 65535;
3398
- var MAX_ZIP32_OFFSET = 4294967295;
3399
- function finalizeZip64(zip) {
3400
- const view = new DataView(zip.buffer, zip.byteOffset, zip.byteLength);
3401
- const eocdStart = zip.byteLength - EOCD_SIZE;
3402
- if (eocdStart < 0 || view.getUint32(eocdStart, true) !== EOCD_SIGNATURE) {
3403
- throw new Error("Cannot finalize the solution archive: it does not end with an end-of-central-directory record.");
3404
- }
3405
- const cdSize = view.getUint32(eocdStart + 12, true);
3406
- const cdOffset = view.getUint32(eocdStart + 16, true);
3407
- const entryCount = countCentralDirectoryEntries(view, cdOffset, cdSize);
3408
- if (entryCount <= MAX_ZIP32_ENTRIES) {
3409
- return zip;
3410
- }
3411
- if (cdOffset >= MAX_ZIP32_OFFSET || zip.byteLength >= MAX_ZIP32_OFFSET) {
3412
- throw new Error(`The solution archive is ${zip.byteLength} bytes, past the 4 GB limit this packer supports. Exclude large directories from the solution with a .uipignore file.`);
3413
- }
3414
- const tail = new Uint8Array(ZIP64_EOCD_SIZE + ZIP64_LOCATOR_SIZE + EOCD_SIZE);
3415
- const tailView = new DataView(tail.buffer);
3416
- const count = BigInt(entryCount);
3417
- tailView.setUint32(0, ZIP64_EOCD_SIGNATURE, true);
3418
- tailView.setBigUint64(4, BigInt(ZIP64_EOCD_SIZE - 12), true);
3419
- tailView.setUint16(12, 45, true);
3420
- tailView.setUint16(14, 45, true);
3421
- tailView.setUint32(16, 0, true);
3422
- tailView.setUint32(20, 0, true);
3423
- tailView.setBigUint64(24, count, true);
3424
- tailView.setBigUint64(32, count, true);
3425
- tailView.setBigUint64(40, BigInt(cdSize), true);
3426
- tailView.setBigUint64(48, BigInt(cdOffset), true);
3427
- const locator = ZIP64_EOCD_SIZE;
3428
- tailView.setUint32(locator, ZIP64_LOCATOR_SIGNATURE, true);
3429
- tailView.setUint32(locator + 4, 0, true);
3430
- tailView.setBigUint64(locator + 8, BigInt(eocdStart), true);
3431
- tailView.setUint32(locator + 16, 1, true);
3432
- const eocd = ZIP64_EOCD_SIZE + ZIP64_LOCATOR_SIZE;
3433
- tailView.setUint32(eocd, EOCD_SIGNATURE, true);
3434
- tailView.setUint16(eocd + 4, 0, true);
3435
- tailView.setUint16(eocd + 6, 0, true);
3436
- tailView.setUint16(eocd + 8, MAX_ZIP32_ENTRIES, true);
3437
- tailView.setUint16(eocd + 10, MAX_ZIP32_ENTRIES, true);
3438
- tailView.setUint32(eocd + 12, cdSize, true);
3439
- tailView.setUint32(eocd + 16, cdOffset, true);
3440
- tailView.setUint16(eocd + 20, 0, true);
3441
- const out = new Uint8Array(eocdStart + tail.byteLength);
3442
- out.set(zip.subarray(0, eocdStart), 0);
3443
- out.set(tail, eocdStart);
3444
- return out;
3445
- }
3446
- function countCentralDirectoryEntries(view, cdOffset, cdSize) {
3447
- const end = cdOffset + cdSize;
3448
- let position = cdOffset;
3449
- let count = 0;
3450
- while (position + 46 <= end && view.getUint32(position, true) === CD_HEADER_SIGNATURE) {
3451
- const nameLength = view.getUint16(position + 28, true);
3452
- const extraLength = view.getUint16(position + 30, true);
3453
- const commentLength = view.getUint16(position + 32, true);
3454
- position += 46 + nameLength + extraLength + commentLength;
3455
- count++;
3456
- }
3457
- return count;
3458
- }
3459
-
3460
- // ../solution-sdk/src/bundle-service.ts
3461
- async function readUipignore(fs, dir) {
3462
- const ignorePath = fs.path.join(dir, UIPIGNORE_FILENAME);
3463
- if (!await fs.exists(ignorePath)) {
3464
- return new Set;
3465
- }
3466
- try {
3467
- const body = await fs.readFile(ignorePath, "utf-8");
3468
- if (!body) {
3469
- return new Set;
3470
- }
3471
- return parseUipignore(body);
3472
- } catch (err) {
3473
- logger.warn(`Could not read ${UIPIGNORE_FILENAME}; ignoring it: ${String(err)}`);
3474
- return new Set;
3475
- }
3476
- }
3477
- async function mergeProjectUipignore(fs, projectPath, projectLabel, solutionExcludeDirs) {
3478
- const projectExtra = await readUipignore(fs, projectPath);
3479
- if (projectExtra.size === 0) {
3480
- return solutionExcludeDirs;
3481
- }
3482
- const merged = new Set(solutionExcludeDirs);
3483
- for (const name of projectExtra) {
3484
- merged.add(name);
3485
- }
3486
- logger.info(`[${projectLabel}] Applying ${projectExtra.size} extra exclude(s) from project ${UIPIGNORE_FILENAME}: ${[...projectExtra].join(", ")}`);
3487
- return merged;
3488
- }
3489
- var toForwardSlash = (p) => p.replace(/\\/g, "/");
3490
- async function mirrorTree(fs, srcDir, relativeBase, destBaseDir, additionalExcludeDirs) {
3491
- const { files, emptyDirs } = await collectTree(fs, srcDir, {
3492
- additionalExcludeDirs
3493
- });
3494
- if (files.length === 0 && emptyDirs.length === 0) {
3495
- const rootRel = fs.path.relative(relativeBase, srcDir);
3496
- if (rootRel) {
3497
- await fs.mkdir(fs.path.join(destBaseDir, rootRel));
3498
- }
3499
- return;
3500
- }
3501
- for (const f of files) {
3502
- const relPath = fs.path.relative(relativeBase, f);
3503
- const destPath = fs.path.join(destBaseDir, relPath);
3504
- const data = await fs.readFile(f);
3505
- if (data) {
3506
- await fs.writeFile(destPath, data);
3507
- } else {
3508
- logger.warn(`Skipping empty or unreadable file: ${f}`);
3509
- }
3510
- }
3511
- for (const dir of emptyDirs) {
3512
- const relPath = fs.path.relative(relativeBase, dir);
3513
- if (!relPath) {
3514
- continue;
3515
- }
3516
- await fs.mkdir(fs.path.join(destBaseDir, relPath));
3517
- }
3518
- }
3519
- async function flattenProjectDir(fs, srcProjectDir, destProjectDir, additionalExcludeDirs) {
3520
- await fs.mkdir(destProjectDir);
3521
- const topLevelExclude = new Set(DEFAULT_EXCLUDED_DIR_NAMES);
3522
- if (additionalExcludeDirs) {
3523
- for (const name of additionalExcludeDirs) {
3524
- topLevelExclude.add(name);
3525
- }
3526
- }
3527
- const entries = await fs.readdir(srcProjectDir);
3528
- for (const entryName of entries) {
3529
- const srcPath = fs.path.join(srcProjectDir, entryName);
3530
- const entryStat = await fs.stat(srcPath);
3531
- if (!entryStat) {
3532
- continue;
3533
- }
3534
- if (entryStat.isFile()) {
3535
- if (isDefaultExcludedFileName(entryName)) {
3536
- continue;
3537
- }
3538
- const data = await fs.readFile(srcPath);
3539
- if (data) {
3540
- await fs.writeFile(fs.path.join(destProjectDir, entryName), data);
3541
- }
3542
- } else if (entryStat.isDirectory()) {
3543
- if (topLevelExclude.has(entryName)) {
3544
- continue;
3545
- }
3546
- if (entryName === "content" || entryName === "flow_files") {
3547
- await mirrorTree(fs, srcPath, srcPath, destProjectDir, additionalExcludeDirs);
3548
- } else {
3549
- await mirrorTree(fs, srcPath, srcProjectDir, destProjectDir, additionalExcludeDirs);
3550
- }
3551
- }
3552
- }
3553
- }
3554
- async function bundleSolution(fs, solutionDir, outputDir, outputName) {
3555
- const resolvedPath = fs.path.resolve(solutionDir);
3556
- const solStat = await fs.stat(resolvedPath);
3557
- if (!solStat) {
3558
- throw new Error(`Path not found: ${resolvedPath}`);
3559
- }
3560
- if (!solStat.isDirectory()) {
3561
- throw new Error(`Not a directory: ${resolvedPath}. Provide the solution directory containing a .uipx file.`);
3562
- }
3563
- const { uipx, uipxFileName } = await readUipxFile(fs, resolvedPath);
3564
- const additionalExcludeDirs = await readUipignore(fs, resolvedPath);
3565
- if (additionalExcludeDirs.size > 0) {
3566
- logger.info(`Applying ${additionalExcludeDirs.size} extra exclude(s) from .uipignore: ${[...additionalExcludeDirs].join(", ")}`);
3567
- }
3568
- const effectiveExclude = new Set(DEFAULT_EXCLUDED_DIR_NAMES);
3569
- for (const name of additionalExcludeDirs) {
3570
- effectiveExclude.add(name);
3571
- }
3572
- for (const project of uipx.Projects) {
3573
- project.ProjectRelativePath = toForwardSlash(project.ProjectRelativePath);
3574
- }
3575
- assertStudioWebCompatibleProjects(uipx.Projects);
3576
- const solutionStorage = {
3577
- SolutionId: uipx.SolutionId,
3578
- Projects: uipx.Projects.map((p) => ({
3579
- ProjectId: p.Id,
3580
- ProjectRelativePath: p.ProjectRelativePath
3581
- }))
3582
- };
3583
- const solutionName = outputName || fs.path.basename(uipxFileName, ".uipx");
3584
- const stagingDir = fs.path.join(resolvedPath, `.uis-staging-${Date.now()}`);
3585
- await fs.mkdir(stagingDir);
3586
- try {
3587
- await fs.writeFile(fs.path.join(stagingDir, "SolutionStorage.json"), JSON.stringify(solutionStorage));
3588
- await fs.writeFile(fs.path.join(stagingDir, uipxFileName), JSON.stringify(uipx));
3589
- for (const project of uipx.Projects) {
3590
- const projectDir = fs.path.dirname(project.ProjectRelativePath);
3591
- const srcProjectPath = fs.path.join(resolvedPath, projectDir);
3592
- const projectStat = await fs.stat(srcProjectPath);
3593
- if (!projectStat) {
3594
- throw new Error(`Project directory not found: ${srcProjectPath}`);
3595
- }
3596
- const projectExcludeDirs = await mergeProjectUipignore(fs, srcProjectPath, projectDir, additionalExcludeDirs);
3597
- await flattenProjectDir(fs, srcProjectPath, fs.path.join(stagingDir, projectDir), projectExcludeDirs);
3598
- }
3599
- const resourcesPath = fs.path.join(resolvedPath, "resources");
3600
- if (!effectiveExclude.has("resources") && await fs.exists(resourcesPath)) {
3601
- await mirrorTree(fs, resourcesPath, resolvedPath, stagingDir, additionalExcludeDirs);
3602
- }
3603
- const userProfilePath = fs.path.join(resolvedPath, "userProfile");
3604
- if (!effectiveExclude.has("userProfile") && await fs.exists(userProfilePath)) {
3605
- await mirrorTree(fs, userProfilePath, resolvedPath, stagingDir, additionalExcludeDirs);
3606
- }
3607
- const resolvedOutputDir = fs.path.resolve(outputDir);
3608
- if (!await fs.exists(resolvedOutputDir)) {
3609
- await fs.mkdir(resolvedOutputDir);
3610
- }
3611
- const uisPath = fs.path.join(resolvedOutputDir, `${solutionName}.uis`);
3612
- const zipData = await createZipFromDir(fs, stagingDir);
3613
- await fs.writeFile(uisPath, zipData);
3614
- const uipxPath = fs.path.join(resolvedPath, uipxFileName);
3615
- return {
3616
- uisPath,
3617
- solutionName,
3618
- solutionId: uipx.SolutionId,
3619
- uipxPath,
3620
- projects: uipx.Projects.map((p) => ({
3621
- Name: fs.path.dirname(p.ProjectRelativePath),
3622
- Type: p.Type
3623
- }))
3624
- };
3625
- } finally {
3626
- await fs.rm(stagingDir);
3627
- }
3628
- }
3629
- // ../solution-sdk/src/project-debug-status.ts
3630
- var SUCCEEDED = "creationsucceeded";
3631
- var TERMINAL = new Set([SUCCEEDED, "creationfailed", "validationfailed"]);
3632
- // src/services/agent-debug-service.ts
3633
- import { randomUUID } from "node:crypto";
3634
-
3635
- // src/services/agent-builder-migrations.ts
3636
- var warnedLegacyToolGuardrailPolicies = false;
3637
- function migrateLegacyToolGuardrailPolicies(builder) {
3638
- let migrated = false;
3639
- for (const resource of builder.resources ?? []) {
3640
- if (resource.$resourceType !== "tool" || !Array.isArray(resource.guardrailPolicies)) {
3641
- continue;
3642
- }
3643
- if (!resource.guardrail?.policies?.length) {
3644
- resource.guardrail = { policies: resource.guardrailPolicies };
3645
- migrated = true;
3646
- }
3647
- delete resource.guardrailPolicies;
3648
- }
3649
- if (migrated && !warnedLegacyToolGuardrailPolicies) {
3650
- OutputFormatter.log({
3651
- Warning: "Migrated legacy guardrailPolicies to guardrail.policies."
3652
- });
3653
- warnedLegacyToolGuardrailPolicies = true;
3654
- }
3655
- }
3656
-
3657
- // src/services/agent-project-service.ts
3658
- class AgentProjectService {
3659
- fs = getFileSystem();
3660
- resolvedAgentDirs = new Map;
3661
- getAgentDir(projectPath) {
3662
- const cached = this.resolvedAgentDirs.get(projectPath);
3663
- if (cached) {
3664
- return cached;
3665
- }
3666
- return projectPath;
3667
- }
3668
- async resolveAgentDir(projectPath) {
3669
- const cached = this.resolvedAgentDirs.get(projectPath);
3670
- if (cached) {
3671
- return cached;
3672
- }
3673
- const flatAgent = this.fs.path.join(projectPath, "agent.json");
3674
- if (await this.fs.stat(flatAgent)) {
3675
- this.resolvedAgentDirs.set(projectPath, projectPath);
3676
- return projectPath;
3677
- }
3678
- const entries = await this.fs.readdir(projectPath);
3679
- for (const entry of entries) {
3680
- if (entry.startsWith(".") || entry === "evals" || entry === "features" || entry === "resources" || entry === "userProfile") {
3681
- continue;
3682
- }
3683
- const candidate = this.fs.path.join(projectPath, entry);
3684
- const candidateStat = await this.fs.stat(candidate);
3685
- if (!candidateStat?.isDirectory())
3686
- continue;
3687
- const agentStat = await this.fs.stat(this.fs.path.join(candidate, "agent.json"));
3688
- if (agentStat) {
3689
- this.resolvedAgentDirs.set(projectPath, candidate);
3690
- return candidate;
3691
- }
3692
- }
3693
- this.resolvedAgentDirs.set(projectPath, projectPath);
3694
- return projectPath;
3695
- }
3696
- async readAgentJson(projectPath) {
3697
- const agentDir = this.getAgentDir(projectPath);
3698
- const raw = await this.fs.readFile(this.fs.path.join(agentDir, "agent.json"), "utf-8");
3699
- return JSON.parse(raw);
3700
- }
3701
- async writeAgentJson(projectPath, agent) {
3702
- const agentDir = this.getAgentDir(projectPath);
3703
- await this.fs.writeFile(this.fs.path.join(agentDir, "agent.json"), `${JSON.stringify(agent, null, 2)}
3704
- `);
3705
- const builderDir = this.fs.path.join(agentDir, ".agent-builder");
3706
- await this.safeMkdir(builderDir);
3707
- let existingBuilder;
3708
- const [builderReadError, builderRaw] = await catchError(this.fs.readFile(this.fs.path.join(builderDir, "agent.json"), "utf-8"));
3709
- if (!builderReadError && builderRaw) {
3710
- try {
3711
- existingBuilder = JSON.parse(builderRaw);
3712
- migrateLegacyToolGuardrailPolicies(existingBuilder);
3713
- } catch {}
3714
- }
3715
- const builderAgent = {
3716
- id: agent.projectId,
3717
- name: existingBuilder?.name ?? "Agent",
3718
- ...agent,
3719
- resources: existingBuilder?.resources ?? agent.resources ?? [],
3720
- features: existingBuilder?.features ?? agent.features ?? []
3721
- };
3722
- await this.fs.writeFile(this.fs.path.join(builderDir, "agent.json"), `${JSON.stringify(builderAgent, null, 2)}
3723
- `);
3724
- }
3725
- async readSolutionStorage(projectPath) {
3726
- const raw = await this.fs.readFile(this.fs.path.join(projectPath, "SolutionStorage.json"), "utf-8");
3727
- return JSON.parse(raw);
3728
- }
3729
- async writeSolutionStorage(projectPath, storage) {
3730
- await this.fs.writeFile(this.fs.path.join(projectPath, "SolutionStorage.json"), `${JSON.stringify(storage, null, 2)}
3731
- `);
3732
- }
3733
- async readEvaluator(projectPath, fileName) {
3734
- const filePath = this.fs.path.join(this.getAgentDir(projectPath), "evals", "evaluators", fileName);
3735
- const raw = await this.fs.readFile(filePath, "utf-8");
3736
- return JSON.parse(raw);
3737
- }
3738
- async writeEvaluator(projectPath, evaluator) {
3739
- const dir = this.fs.path.join(this.getAgentDir(projectPath), "evals", "evaluators");
3740
- await this.safeMkdir(dir);
3741
- await this.fs.writeFile(this.fs.path.join(dir, evaluator.fileName), `${JSON.stringify(evaluator, null, 2)}
3742
- `);
3743
- }
3744
- async listEvaluators(projectPath) {
3745
- const dir = this.fs.path.join(this.getAgentDir(projectPath), "evals", "evaluators");
3746
- const [error, files] = await catchError(this.fs.readdir(dir));
3747
- if (error) {
3748
- return [];
3749
- }
3750
- const evaluators = [];
3751
- for (const file of files) {
3752
- if (file.endsWith(".json")) {
3753
- const raw = await this.fs.readFile(this.fs.path.join(dir, file), "utf-8");
3754
- evaluators.push(JSON.parse(raw));
3755
- }
3756
- }
3757
- return evaluators;
3758
- }
3759
- async deleteEvaluator(projectPath, fileName) {
3760
- const filePath = this.fs.path.join(this.getAgentDir(projectPath), "evals", "evaluators", fileName);
3761
- await this.fs.rm(filePath);
3762
- }
3763
- async readEvalSet(projectPath, fileName) {
3764
- const filePath = this.fs.path.join(this.getAgentDir(projectPath), "evals", "eval-sets", fileName);
3765
- const raw = await this.fs.readFile(filePath, "utf-8");
3766
- return JSON.parse(raw);
3767
- }
3768
- async writeEvalSet(projectPath, evalSet, fileName) {
3769
- const dir = this.fs.path.join(this.getAgentDir(projectPath), "evals", "eval-sets");
3770
- await this.safeMkdir(dir);
3771
- await this.fs.writeFile(this.fs.path.join(dir, fileName), `${JSON.stringify(evalSet, null, 2)}
3772
- `);
3773
- }
3774
- async listEvalSets(projectPath) {
3775
- const dir = this.fs.path.join(this.getAgentDir(projectPath), "evals", "eval-sets");
3776
- const [error, files] = await catchError(this.fs.readdir(dir));
3777
- if (error) {
3778
- return [];
3779
- }
3780
- const sets = [];
3781
- for (const file of files) {
3782
- if (file.endsWith(".json")) {
3783
- const raw = await this.fs.readFile(this.fs.path.join(dir, file), "utf-8");
3784
- sets.push(JSON.parse(raw));
3785
- }
3786
- }
3787
- return sets;
3788
- }
3789
- async deleteEvalSet(projectPath, fileName) {
3790
- const filePath = this.fs.path.join(this.getAgentDir(projectPath), "evals", "eval-sets", fileName);
3791
- await this.fs.rm(filePath);
3792
- }
3793
- async writeFeature(projectPath, featureName, feature) {
3794
- this.validateFeatureName(featureName);
3795
- const dir = this.fs.path.join(this.getAgentDir(projectPath), "features", featureName);
3796
- await this.safeMkdir(dir);
3797
- await this.fs.writeFile(this.fs.path.join(dir, "feature.json"), `${JSON.stringify(feature, null, 2)}
3798
- `);
3799
- }
3800
- async readFeature(projectPath, featureName) {
3801
- this.validateFeatureName(featureName);
3802
- const filePath = this.fs.path.join(this.getAgentDir(projectPath), "features", featureName, "feature.json");
3803
- const raw = await this.fs.readFile(filePath, "utf-8");
3804
- if (!raw) {
3805
- throw new Error(`Feature file not found: ${filePath}`);
3806
- }
3807
- const parsed = JSON.parse(raw);
3808
- if (!parsed) {
3809
- throw new Error(`Feature file is empty: ${filePath}`);
3810
- }
3811
- return parsed;
3812
- }
3813
- async listFeatureDirs(projectPath) {
3814
- const dir = this.fs.path.join(this.getAgentDir(projectPath), "features");
3815
- const [error, entries] = await catchError(this.fs.readdir(dir));
3816
- if (error) {
3817
- return [];
3818
- }
3819
- return entries;
3820
- }
3821
- async deleteFeature(projectPath, featureName) {
3822
- this.validateFeatureName(featureName);
3823
- const dir = this.fs.path.join(this.getAgentDir(projectPath), "features", featureName);
3824
- await this.fs.rm(dir);
3825
- }
3826
- async safeMkdir(dir) {
3827
- await this.fs.mkdir(dir);
3828
- }
3829
- async writeJsonFile(filePath, data) {
3830
- await this.fs.writeFile(filePath, `${JSON.stringify(data, null, 2)}
3831
- `);
3832
- }
3833
- validateFeatureName(featureName) {
3834
- if (featureName.trim().length === 0 || featureName === "." || featureName === ".." || featureName.includes("/") || featureName.includes("\\") || featureName.includes("\x00") || featureName !== this.fs.path.basename(featureName)) {
3835
- throw new Error(`Invalid feature name: "${featureName}"`);
3836
- }
3837
- }
3838
- }
3839
-
3840
- // src/services/pack-helpers.ts
3841
- var import_adm_zip = __toESM(require_adm_zip(), 1);
3842
- async function collectProjectFiles(rootDir) {
3843
- const files = [];
3844
- await collectRecursive(rootDir, rootDir, files);
3845
- return files;
3846
- }
3847
- async function collectRecursive(rootDir, currentDir, files) {
3848
- const fs = getFileSystem();
3849
- const entries = await fs.readdir(currentDir);
3850
- for (const entry of entries) {
3851
- const fullPath = fs.path.join(currentDir, entry);
3852
- const stats = await fs.stat(fullPath);
3853
- if (stats?.isDirectory()) {
3854
- await collectRecursive(rootDir, fullPath, files);
3855
- } else if (stats) {
3856
- files.push(fs.path.relative(rootDir, fullPath).replace(/\\/g, "/"));
3857
- }
3858
- }
3859
- }
3860
- function matchesExclude(relPath, exclude) {
3861
- for (const pattern of exclude) {
3862
- const cleaned = pattern.replace(/^\.\//, "").replace(/\/\*$/, "");
3863
- if (cleaned.startsWith("*")) {
3864
- const suffix = cleaned.slice(1).replace(/^\//, "");
3865
- if (relPath.includes(`/${suffix}/`) || relPath.includes(`/${suffix}`)) {
3866
- return true;
3867
- }
3868
- }
3869
- if (relPath === cleaned || relPath.startsWith(`${cleaned}/`)) {
3870
- return true;
3871
- }
3872
- }
3873
- return false;
3874
- }
3875
- async function createArchive(sourceDir, outputPath, exclude) {
3876
- const fs = getFileSystem();
3877
- const zip = new import_adm_zip.default;
3878
- const files = await collectProjectFiles(sourceDir);
3879
- for (const relPath of files) {
3880
- if (exclude && matchesExclude(relPath, exclude)) {
3881
- continue;
3882
- }
3883
- const fullPath = fs.path.join(sourceDir, relPath);
3884
- const dirInZip = relPath.includes("/") ? relPath.substring(0, relPath.lastIndexOf("/")) : "";
3885
- zip.addLocalFile(fullPath, dirInZip);
3886
- }
3887
- zip.writeZip(outputPath);
3888
- }
3889
-
3890
- // src/services/agent-local-workspace-eval-preparer.ts
3891
- var UUID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
3892
- function isUUID(value) {
3893
- return UUID_PATTERN.test(value);
3894
- }
3895
- function isRecord(value) {
3896
- return typeof value === "object" && value !== null && !Array.isArray(value);
3897
- }
3898
- function toForwardSlash2(path) {
3899
- return path.replace(/\\/g, "/");
3900
- }
3901
- async function resolveStudioWebConfig() {
3902
- const [loginError, login] = await catchError(getLoginStatusAsync());
3903
- if (loginError) {
3904
- throw new Error(loginError.message);
3905
- }
3906
- if (login.loginStatus !== "Logged in" || !login.baseUrl) {
3907
- throw new Error("Not logged in. Run 'uip login' first.");
3908
- }
3909
- if (!login.accessToken) {
3910
- throw new Error("Access token not available from login.");
3911
- }
3912
- if (!login.organizationName) {
3913
- throw new Error("Organization name not available from login. Required for Studio Web evaluation.");
3914
- }
3915
- return {
3916
- baseUrl: login.baseUrl,
3917
- tenantId: login.tenantId,
3918
- authToken: login.accessToken,
3919
- organizationName: login.organizationName
3920
- };
3921
- }
3922
-
3923
- class AgentLocalWorkspaceEvalPreparer {
3924
- fs;
3925
- constructor(fs = getFileSystem()) {
3926
- this.fs = fs;
3927
- }
3928
- async isLocalWorkspace(projectPath) {
3929
- return await this.readLocalWorkspaceMarker(projectPath) !== undefined;
3930
- }
3931
- async prepare(projectPath, config, existingSolutionIdOverride) {
3932
- const absoluteProjectPath = this.fs.path.resolve(projectPath);
3933
- const marker = await this.readLocalWorkspaceMarker(absoluteProjectPath);
3934
- const packageRoot = marker?.rootPath ?? absoluteProjectPath;
3935
- const projectService = new AgentProjectService;
3936
- const agentDir = await projectService.resolveAgentDir(absoluteProjectPath);
3937
- const agent = await projectService.readAgentJson(absoluteProjectPath);
3938
- const projectFilePath = this.fs.path.join(agentDir, "project.uiproj");
3939
- if (!await this.fs.exists(projectFilePath)) {
3940
- throw new Error(`Not a valid agent project directory: missing project.uiproj in ${agentDir}`);
3941
- }
3942
- const projectFileContent = await this.fs.readFile(projectFilePath, "utf-8");
3943
- const [projectFileError, parsedProjectFile] = catchError(() => JSON.parse(String(projectFileContent)));
3944
- if (projectFileError || !isRecord(parsedProjectFile)) {
3945
- throw new Error(`Invalid project.uiproj in ${agentDir}: ${projectFileError?.message ?? "expected a JSON object"}`);
3946
- }
3947
- const projectFile = {
3948
- Name: typeof parsedProjectFile.Name === "string" ? parsedProjectFile.Name : undefined
3949
- };
3950
- const solutionInfo = await findSolutionFile(this.fs, agentDir);
3951
- const solutionId = existingSolutionIdOverride ?? marker?.solutionId ?? solutionInfo?.solutionId;
3952
- const solutionName = projectFile.Name ?? agent.metadata.name ?? this.fs.path.basename(agentDir);
3953
- const safeSolutionName = solutionName.replace(/[^a-zA-Z0-9_-]/g, "_");
3954
- const stagingDir = this.fs.path.join(this.fs.env.tmpdir(), `.agent-eval-staging-${safeSolutionName}-${Date.now()}`);
3955
- await this.fs.mkdir(stagingDir);
3956
- const uisPath = this.fs.path.join(stagingDir, `${safeSolutionName}.uis`);
3957
- try {
3958
- logger.info("Building agent package for local workspace eval...");
3959
- await createArchive(packageRoot, uisPath, [
3960
- "./.agent-builder/*",
3961
- "*/.agent-builder/*",
3962
- ".sw-path-marker",
3963
- "*/.sw-path-marker"
3964
- ]);
3965
- logger.info("Uploading local workspace agent for eval...");
3966
- const importResult = await uploadOrOverwriteSolution({
3967
- baseUrl: config.baseUrl,
3968
- tenantId: config.tenantId,
3969
- authToken: config.authToken
3970
- }, config.organizationName, uisPath, solutionId, this.fs);
3971
- const matchedProject = this.resolveImportedProject(importResult, solutionName);
3972
- await this.persistSolutionStorage(projectService, absoluteProjectPath, packageRoot, projectFilePath, importResult.id, agent.projectId, matchedProject.id);
3973
- if (packageRoot !== absoluteProjectPath) {
3974
- await this.persistSolutionStorage(projectService, packageRoot, packageRoot, projectFilePath, importResult.id, agent.projectId, matchedProject.id);
3975
- }
3976
- await updateSolutionFile(this.fs, agentDir, importResult.id);
3977
- if (marker) {
3978
- await this.updateLocalWorkspaceMarker(marker.rootPath, importResult.id);
3979
- }
3980
- return {
3981
- solutionId: importResult.id,
3982
- agentProjectId: matchedProject.id
3983
- };
3984
- } finally {
3985
- const [cleanupError] = await catchError(this.fs.rm(stagingDir, { recursive: true }));
3986
- if (cleanupError) {
3987
- logger.warn(`Cleanup failed: ${cleanupError.message}`);
3988
- }
3989
- }
3990
- }
3991
- async readLocalWorkspaceMarker(projectPath) {
3992
- const absoluteProjectPath = this.fs.path.resolve(projectPath);
3993
- const candidates = [
3994
- absoluteProjectPath,
3995
- this.fs.path.dirname(absoluteProjectPath)
3996
- ];
3997
- for (const candidate of candidates) {
3998
- const markerPath = this.fs.path.join(candidate, ".sw-path-marker");
3999
- if (!await this.fs.exists(markerPath)) {
4000
- continue;
4001
- }
4002
- const content = String(await this.fs.readFile(markerPath, "utf-8"));
4003
- const solutionId = content.trim();
4004
- return {
4005
- rootPath: candidate,
4006
- ...isUUID(solutionId) ? { solutionId } : {}
4007
- };
4008
- }
4009
- return;
4010
- }
4011
- resolveImportedProject(importResult, agentName) {
4012
- const exactProject = importResult.projects.find((project) => project.name === agentName);
4013
- if (exactProject?.id) {
4014
- return exactProject;
4015
- }
4016
- const [onlyProject] = importResult.projects;
4017
- if (importResult.projects.length === 1 && onlyProject?.id) {
4018
- return onlyProject;
4019
- }
4020
- throw new Error(`Upload response had ${importResult.projects.length} projects and none matched "${agentName}"; refusing to guess.`);
4021
- }
4022
- async persistSolutionStorage(projectService, storagePath, packageRoot, projectFilePath, solutionId, localProjectId, cloudProjectId) {
4023
- const projectRelativePath = toForwardSlash2(this.fs.path.relative(packageRoot, projectFilePath));
4024
- const projectEntry = {
4025
- ProjectId: localProjectId,
4026
- ProjectRelativePath: projectRelativePath || "project.uiproj",
4027
- CloudProjectId: cloudProjectId
4028
- };
4029
- const [, existingStorage] = await catchError(projectService.readSolutionStorage(storagePath));
4030
- const existingProjects = existingStorage?.Projects ?? [];
4031
- const projectIndex = existingProjects.findIndex((project) => project.ProjectId === localProjectId);
4032
- const projects = projectIndex === -1 ? [...existingProjects, projectEntry] : existingProjects.map((project, index) => index === projectIndex ? { ...project, ...projectEntry } : project);
4033
- await projectService.writeSolutionStorage(storagePath, {
4034
- SolutionId: solutionId,
4035
- Projects: projects
4036
- });
4037
- }
4038
- async updateLocalWorkspaceMarker(workspaceRoot, solutionId) {
4039
- await this.fs.writeFile(this.fs.path.join(workspaceRoot, ".sw-path-marker"), solutionId);
4040
- }
4041
- }
4042
-
4043
- // src/services/agent-debug-service.ts
4044
- class AgentDebugCancelledError extends Error {
4045
- jobKey;
4046
- constructor(jobKey) {
4047
- super(jobKey ? `Debug run cancelled. Job ${jobKey} may still be running on the serverless runtime.` : "Debug run cancelled before the job started.");
4048
- this.name = "AgentDebugCancelledError";
4049
- this.jobKey = jobKey;
4050
- }
4051
- }
4052
- var TERMINAL_STATES = new Set([
4053
- "Successful",
4054
- "Faulted",
4055
- "Stopped",
4056
- "Suspended"
4057
- ]);
4058
- var delay = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
4059
-
4060
- class AgentDebugService {
4061
- fs = getFileSystem();
4062
- projectService = new AgentProjectService;
4063
- async debug(options, auth) {
4064
- throwIfAborted(options.signal);
4065
- const projectId = await this.resolveProjectId(options.projectPath);
4066
- throwIfAborted(options.signal);
4067
- const folderKey = await this.resolvePersonalWorkspaceKey();
4068
- throwIfAborted(options.signal);
4069
- const { jobKey, traceId } = await asCancellation(() => this.startDebugJob(auth, folderKey, projectId, options.inputs, options.signal));
4070
- const job = await asCancellation(() => this.pollJob(auth, folderKey, jobKey, options), jobKey);
4071
- return {
4072
- jobKey,
4073
- traceId,
4074
- finalState: job.state,
4075
- success: job.state === "Successful",
4076
- output: job.output,
4077
- info: job.info
4078
- };
4079
- }
4080
- async resolveProjectId(projectPath) {
4081
- const preparer = new AgentLocalWorkspaceEvalPreparer;
4082
- if (await preparer.isLocalWorkspace(projectPath)) {
4083
- const [, storage] = await catchError(this.projectService.readSolutionStorage(projectPath));
4084
- const config = await resolveStudioWebConfig();
4085
- const prepared = await preparer.prepare(projectPath, config, storage?.SolutionId);
4086
- return prepared.agentProjectId;
4087
- }
4088
- return this.uploadSolutionAndResolveProjectId(projectPath);
4089
- }
4090
- async uploadSolutionAndResolveProjectId(projectPath) {
4091
- const solution = await findSolutionFile(this.fs, projectPath);
4092
- if (!solution) {
4093
- throw new Error(`No enclosing .uipx solution found for '${projectPath}'. Create one with 'uip solution init' and add the agent to it.`);
4094
- }
4095
- const config = await resolveStudioWebConfig();
4096
- const solutionDir = this.fs.path.resolve(projectPath, "..");
4097
- const tempDir = await this.fs.getTempDir();
4098
- try {
4099
- const bundle = await bundleSolution(this.fs, solutionDir, tempDir);
4100
- const importResult = await uploadOrOverwriteSolution(config, config.organizationName, bundle.uisPath, bundle.solutionId, this.fs);
4101
- if (importResult.id && bundle.uipxPath) {
4102
- await updateUipxSolutionId(this.fs, bundle.uipxPath, importResult.id);
4103
- }
4104
- const projectName = await this.readProjectName(projectPath);
4105
- const byName = importResult.projects.find((p) => p.name === projectName);
4106
- if (byName?.id) {
4107
- return byName.id;
4108
- }
4109
- const [only] = importResult.projects;
4110
- if (importResult.projects.length === 1 && only?.id) {
4111
- return only.id;
4112
- }
4113
- throw new Error(`Could not resolve the Studio Web project for "${projectName}": the upload returned ${importResult.projects.length} projects and none is named "${projectName}". Ensure the Name in project.uiproj matches the agent project in the solution.`);
4114
- } finally {
4115
- const [cleanupError] = await catchError(this.fs.rm(tempDir));
4116
- if (cleanupError) {
4117
- logger.debug(`Failed to clean up temp dir: ${cleanupError.message}`);
4118
- }
4119
- }
4120
- }
4121
- async readProjectName(projectPath) {
4122
- const [, content] = await catchError(this.fs.readFile(this.fs.path.join(projectPath, "project.uiproj"), "utf-8"));
4123
- const [, parsed] = catchError(() => JSON.parse(String(content)));
4124
- return parsed?.Name ?? this.fs.path.basename(projectPath);
4125
- }
4126
- async resolvePersonalWorkspaceKey() {
4127
- const wsApi = await createApiClient(PersonalWorkspacesApi, {});
4128
- const workspace = await wsApi.personalWorkspacesGetPersonalWorkspace();
4129
- if (!workspace?.key) {
4130
- throw new Error("Could not resolve your personal workspace. Ensure it is enabled for your account.");
4131
- }
4132
- return workspace.key;
4133
- }
4134
- orchestratorBaseUrl(auth) {
4135
- return `${auth.baseUrl}/${auth.organizationId}/${auth.tenantName}/orchestrator_`;
4136
- }
4137
- async startDebugJob(auth, folderKey, projectId, inputs, signal) {
4138
- const traceId = randomUUID();
4139
- const inputArguments = JSON.stringify({
4140
- Command: "debug",
4141
- EntryPoint: "agent.json",
4142
- Input: JSON.stringify(inputs),
4143
- args: "--attach=none"
4144
- });
4145
- const response = await fetch(`${this.orchestratorBaseUrl(auth)}/api/serverless/jobs`, {
4146
- method: "POST",
4147
- headers: {
4148
- Authorization: `Bearer ${auth.accessToken}`,
4149
- "Content-Type": "application/json",
4150
- "X-UIPATH-FolderKey": folderKey
4151
- },
4152
- body: JSON.stringify({
4153
- JobType: "PythonAgent",
4154
- InputArguments: inputArguments,
4155
- Source: "StudioWeb",
4156
- RunAsMe: true,
4157
- EnvironmentVariables: `UIPATH_PROJECT_ID=${projectId}`,
4158
- TraceId: traceId,
4159
- Reference: randomUUID()
4160
- }),
4161
- signal
4162
- });
4163
- if (!response.ok) {
4164
- throw new Error(`Failed to start debug job: ${response.status} ${await response.text()}`);
4165
- }
4166
- const data = await response.json();
4167
- if (!data.key) {
4168
- throw new Error("Debug job started but no job key was returned.");
4169
- }
4170
- return { jobKey: data.key, traceId };
4171
- }
4172
- async pollJob(auth, folderKey, jobKey, options) {
4173
- const url = `${this.orchestratorBaseUrl(auth)}/odata/Jobs/UiPath.Server.Configuration.OData.GetByKey(identifier=${jobKey})`;
4174
- const headers = {
4175
- Authorization: `Bearer ${auth.accessToken}`,
4176
- "X-UIPATH-FolderKey": folderKey
4177
- };
4178
- let lastState = "";
4179
- let consecutiveErrors = 0;
4180
- const maxConsecutiveErrors = 3;
4181
- for (let poll = 0;poll < options.maxPolls; poll++) {
4182
- await delay(options.pollIntervalMs);
4183
- throwIfAborted(options.signal, jobKey);
4184
- const response = await fetch(url, {
4185
- headers,
4186
- signal: options.signal
4187
- });
4188
- if (!response.ok) {
4189
- consecutiveErrors++;
4190
- if (response.status < 500 || consecutiveErrors > maxConsecutiveErrors) {
4191
- const body = await response.text();
4192
- throw new Error(`Failed to poll debug job (HTTP ${response.status}): ${body.slice(0, 300)}`);
4193
- }
4194
- continue;
4195
- }
4196
- consecutiveErrors = 0;
4197
- const job = await response.json();
4198
- if (job.State !== lastState) {
4199
- lastState = job.State;
4200
- options.onState?.(job.State);
4201
- }
4202
- if (TERMINAL_STATES.has(job.State)) {
4203
- return {
4204
- state: job.State,
4205
- output: parseOutput(job.OutputArguments),
4206
- info: job.Info?.trim() || undefined
4207
- };
4208
- }
4209
- }
4210
- throw new Error(`Debug run did not reach a terminal state within the timeout (last state: ${lastState || "unknown"}). Increase --timeout and retry.`);
4211
- }
4212
- }
4213
- function throwIfAborted(signal, jobKey) {
4214
- if (signal?.aborted) {
4215
- throw new AgentDebugCancelledError(jobKey);
4216
- }
4217
- }
4218
- async function asCancellation(step, jobKey) {
4219
- try {
4220
- return await step();
4221
- } catch (error) {
4222
- if (isAbortError(error)) {
4223
- throw new AgentDebugCancelledError(jobKey);
4224
- }
4225
- throw error;
4226
- }
4227
- }
4228
- function isAbortError(error) {
4229
- return error instanceof Error && (error.name === "AbortError" || error.name === "TimeoutError");
4230
- }
4231
- function parseOutput(outputArguments) {
4232
- if (!outputArguments) {
4233
- return;
4234
- }
4235
- const [error, parsed] = catchError(() => JSON.parse(outputArguments));
4236
- return error ? outputArguments : parsed;
4237
- }
4238
-
4239
- export { StudioWebIncompatibleProjectError, isSolutionUploadHttpError, buildSolutionUploadFailureOutput, migrateLegacyToolGuardrailPolicies, AgentProjectService, resolveStudioWebConfig, AgentLocalWorkspaceEvalPreparer, AgentDebugCancelledError, AgentDebugService };
4240
-
4241
- //# debugId=E79F97B74780998E64756E2164756E21