mapshaper 0.6.14 → 0.6.16

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/www/mapshaper.js CHANGED
@@ -1,6 +1,6 @@
1
1
  (function () {
2
2
 
3
- var VERSION = "0.6.14";
3
+ var VERSION = "0.6.16";
4
4
 
5
5
 
6
6
  var utils = /*#__PURE__*/Object.freeze({
@@ -5560,7 +5560,9 @@
5560
5560
  len = _nn[absId];
5561
5561
  if (nth < 0) nth = len + nth;
5562
5562
  if (absId != arcId) nth = len - nth - 1;
5563
- if (nth < 0 || nth >= len) error("[ArcCollection] out-of-range vertex id");
5563
+ if (nth < 0 || nth >= len) {
5564
+ error("[ArcCollection] out-of-range vertex id");
5565
+ }
5564
5566
  return _ii[absId] + nth;
5565
5567
  };
5566
5568
 
@@ -7115,7 +7117,8 @@
7115
7117
  }
7116
7118
 
7117
7119
  function replaceFileExtension(path, ext) {
7118
- return getPathBase(path) + '.' + ext;
7120
+ var base = getPathBase(path);
7121
+ return ext ? base + '.' + ext : base;
7119
7122
  }
7120
7123
 
7121
7124
  function toLowerCaseExtension(name) {
@@ -7161,6 +7164,8 @@
7161
7164
  type = 'json';
7162
7165
  } else if (ext == 'csv' || ext == 'tsv' || ext == 'txt' || ext == 'tab') {
7163
7166
  type = 'text';
7167
+ } else if (ext == 'mshp') {
7168
+ type = 'mshp';
7164
7169
  }
7165
7170
  return type;
7166
7171
  }
@@ -7194,12 +7199,37 @@
7194
7199
  return /csv|tsv|txt$/.test(ext);
7195
7200
  }
7196
7201
 
7202
+ // File looks like an importable file type
7203
+ // name: filename or path
7204
+ function looksLikeImportableFile(name) {
7205
+ return !!guessInputFileType(name);
7206
+ }
7207
+
7208
+ // File looks like a directly readable data file type
7209
+ // name: filename or path
7210
+ function looksLikeContentFile(name) {
7211
+ var type = guessInputFileType(name);
7212
+ return !!type && type != 'gz' && type != 'zip';
7213
+ }
7214
+
7215
+ function isMshpFile(file) {
7216
+ return /\.mshp$/.test(file);
7217
+ }
7218
+
7197
7219
  function isZipFile(file) {
7198
7220
  return /\.zip$/i.test(file);
7199
7221
  }
7200
7222
 
7223
+ function isKmzFile(file) {
7224
+ return /\.kmz$/i.test(file);
7225
+ }
7226
+
7227
+ function isGzipFile(file) {
7228
+ return /\.gz/i.test(file);
7229
+ }
7230
+
7201
7231
  function isSupportedOutputFormat(fmt) {
7202
- var types = ['geojson', 'topojson', 'json', 'dsv', 'dbf', 'shapefile', 'svg'];
7232
+ var types = ['geojson', 'topojson', 'json', 'dsv', 'dbf', 'shapefile', 'svg', 'kml', 'mshp'];
7203
7233
  return types.indexOf(fmt) > -1;
7204
7234
  }
7205
7235
 
@@ -7210,6 +7240,9 @@
7210
7240
  json: 'JSON records',
7211
7241
  dsv: 'CSV',
7212
7242
  dbf: 'DBF',
7243
+ kml: 'KML',
7244
+ kmz: 'KMZ',
7245
+ mshp: 'Mapshaper project',
7213
7246
  shapefile: 'Shapefile',
7214
7247
  svg: 'SVG'
7215
7248
  }[fmt] || '';
@@ -7218,12 +7251,19 @@
7218
7251
  // Assumes file at @path is one of Mapshaper's supported file types
7219
7252
  function isSupportedBinaryInputType(path) {
7220
7253
  var ext = getFileExtension(path).toLowerCase();
7221
- return ext == 'shp' || ext == 'shx' || ext == 'dbf'; // GUI also supports zip files
7254
+ return ext == 'shp' || ext == 'shx' || ext == 'dbf' || ext == 'mshp'; // GUI also supports zip files
7255
+ }
7256
+
7257
+ function isImportableAsBinary(path) {
7258
+ var type = guessInputFileType(path);
7259
+ return isSupportedBinaryInputType(path) || isZipFile(path) ||
7260
+ isGzipFile(path) || isKmzFile(path) || isMshpFile(path) ||
7261
+ type == 'json' || type == 'text';
7222
7262
  }
7223
7263
 
7224
7264
  // Detect extensions of some unsupported file types, for cmd line validation
7225
7265
  function filenameIsUnsupportedOutputType(file) {
7226
- var rxp = /\.(shx|prj|xls|xlsx|gdb|sbn|sbx|xml|kml)$/i;
7266
+ var rxp = /\.(shx|prj|xls|xlsx|gdb|sbn|sbx|xml)$/i;
7227
7267
  return rxp.test(file);
7228
7268
  }
7229
7269
 
@@ -7235,66 +7275,2656 @@
7235
7275
  stringLooksLikeJSON: stringLooksLikeJSON,
7236
7276
  stringLooksLikeKML: stringLooksLikeKML,
7237
7277
  couldBeDsvFile: couldBeDsvFile,
7278
+ looksLikeImportableFile: looksLikeImportableFile,
7279
+ looksLikeContentFile: looksLikeContentFile,
7280
+ isMshpFile: isMshpFile,
7238
7281
  isZipFile: isZipFile,
7282
+ isKmzFile: isKmzFile,
7283
+ isGzipFile: isGzipFile,
7239
7284
  isSupportedOutputFormat: isSupportedOutputFormat,
7240
7285
  getFormatName: getFormatName,
7241
7286
  isSupportedBinaryInputType: isSupportedBinaryInputType,
7287
+ isImportableAsBinary: isImportableAsBinary,
7242
7288
  filenameIsUnsupportedOutputType: filenameIsUnsupportedOutputType
7243
7289
  });
7244
7290
 
7291
+ // DEFLATE is a complex format; to read this code, you should probably check the RFC first:
7292
+ // https://tools.ietf.org/html/rfc1951
7293
+ // You may also wish to take a look at the guide I made about this program:
7294
+ // https://gist.github.com/101arrowz/253f31eb5abc3d9275ab943003ffecad
7295
+ // Some of the following code is similar to that of UZIP.js:
7296
+ // https://github.com/photopea/UZIP.js
7297
+ // However, the vast majority of the codebase has diverged from UZIP.js to increase performance and reduce bundle size.
7298
+ // Sometimes 0 will appear where -1 would be more appropriate. This is because using a uint
7299
+ // is better for memory in most engines (I *think*).
7300
+ var ch2 = {};
7301
+ var wk = (function (c, id, msg, transfer, cb) {
7302
+ var w = new Worker(ch2[id] || (ch2[id] = URL.createObjectURL(new Blob([
7303
+ c + ';addEventListener("error",function(e){e=e.error;postMessage({$e$:[e.message,e.code,e.stack]})})'
7304
+ ], { type: 'text/javascript' }))));
7305
+ w.onmessage = function (e) {
7306
+ var d = e.data, ed = d.$e$;
7307
+ if (ed) {
7308
+ var err = new Error(ed[0]);
7309
+ err['code'] = ed[1];
7310
+ err.stack = ed[2];
7311
+ cb(err, null);
7312
+ }
7313
+ else
7314
+ cb(null, d);
7315
+ };
7316
+ w.postMessage(msg, transfer);
7317
+ return w;
7318
+ });
7319
+
7320
+ // aliases for shorter compressed code (most minifers don't do this)
7321
+ var u8 = Uint8Array, u16 = Uint16Array, u32 = Uint32Array;
7322
+ // fixed length extra bits
7323
+ var fleb = new u8([0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0, /* unused */ 0, 0, /* impossible */ 0]);
7324
+ // fixed distance extra bits
7325
+ // see fleb note
7326
+ var fdeb = new u8([0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13, /* unused */ 0, 0]);
7327
+ // code length index map
7328
+ var clim = new u8([16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15]);
7329
+ // get base, reverse index map from extra bits
7330
+ var freb = function (eb, start) {
7331
+ var b = new u16(31);
7332
+ for (var i = 0; i < 31; ++i) {
7333
+ b[i] = start += 1 << eb[i - 1];
7334
+ }
7335
+ // numbers here are at max 18 bits
7336
+ var r = new u32(b[30]);
7337
+ for (var i = 1; i < 30; ++i) {
7338
+ for (var j = b[i]; j < b[i + 1]; ++j) {
7339
+ r[j] = ((j - b[i]) << 5) | i;
7340
+ }
7341
+ }
7342
+ return [b, r];
7343
+ };
7344
+ var _a = freb(fleb, 2), fl = _a[0], revfl = _a[1];
7345
+ // we can ignore the fact that the other numbers are wrong; they never happen anyway
7346
+ fl[28] = 258, revfl[258] = 28;
7347
+ var _b = freb(fdeb, 0), fd = _b[0], revfd = _b[1];
7348
+ // map of value to reverse (assuming 16 bits)
7349
+ var rev = new u16(32768);
7350
+ for (var i = 0; i < 32768; ++i) {
7351
+ // reverse table algorithm from SO
7352
+ var x = ((i & 0xAAAA) >>> 1) | ((i & 0x5555) << 1);
7353
+ x = ((x & 0xCCCC) >>> 2) | ((x & 0x3333) << 2);
7354
+ x = ((x & 0xF0F0) >>> 4) | ((x & 0x0F0F) << 4);
7355
+ rev[i] = (((x & 0xFF00) >>> 8) | ((x & 0x00FF) << 8)) >>> 1;
7356
+ }
7357
+ // create huffman tree from u8 "map": index -> code length for code index
7358
+ // mb (max bits) must be at most 15
7359
+ // TODO: optimize/split up?
7360
+ var hMap = (function (cd, mb, r) {
7361
+ var s = cd.length;
7362
+ // index
7363
+ var i = 0;
7364
+ // u16 "map": index -> # of codes with bit length = index
7365
+ var l = new u16(mb);
7366
+ // length of cd must be 288 (total # of codes)
7367
+ for (; i < s; ++i) {
7368
+ if (cd[i])
7369
+ ++l[cd[i] - 1];
7370
+ }
7371
+ // u16 "map": index -> minimum code for bit length = index
7372
+ var le = new u16(mb);
7373
+ for (i = 0; i < mb; ++i) {
7374
+ le[i] = (le[i - 1] + l[i - 1]) << 1;
7375
+ }
7376
+ var co;
7377
+ if (r) {
7378
+ // u16 "map": index -> number of actual bits, symbol for code
7379
+ co = new u16(1 << mb);
7380
+ // bits to remove for reverser
7381
+ var rvb = 15 - mb;
7382
+ for (i = 0; i < s; ++i) {
7383
+ // ignore 0 lengths
7384
+ if (cd[i]) {
7385
+ // num encoding both symbol and bits read
7386
+ var sv = (i << 4) | cd[i];
7387
+ // free bits
7388
+ var r_1 = mb - cd[i];
7389
+ // start value
7390
+ var v = le[cd[i] - 1]++ << r_1;
7391
+ // m is end value
7392
+ for (var m = v | ((1 << r_1) - 1); v <= m; ++v) {
7393
+ // every 16 bit value starting with the code yields the same result
7394
+ co[rev[v] >>> rvb] = sv;
7395
+ }
7396
+ }
7397
+ }
7398
+ }
7399
+ else {
7400
+ co = new u16(s);
7401
+ for (i = 0; i < s; ++i) {
7402
+ if (cd[i]) {
7403
+ co[i] = rev[le[cd[i] - 1]++] >>> (15 - cd[i]);
7404
+ }
7405
+ }
7406
+ }
7407
+ return co;
7408
+ });
7409
+ // fixed length tree
7410
+ var flt = new u8(288);
7411
+ for (var i = 0; i < 144; ++i)
7412
+ flt[i] = 8;
7413
+ for (var i = 144; i < 256; ++i)
7414
+ flt[i] = 9;
7415
+ for (var i = 256; i < 280; ++i)
7416
+ flt[i] = 7;
7417
+ for (var i = 280; i < 288; ++i)
7418
+ flt[i] = 8;
7419
+ // fixed distance tree
7420
+ var fdt = new u8(32);
7421
+ for (var i = 0; i < 32; ++i)
7422
+ fdt[i] = 5;
7423
+ // fixed length map
7424
+ var flm = /*#__PURE__*/ hMap(flt, 9, 0), flrm = /*#__PURE__*/ hMap(flt, 9, 1);
7425
+ // fixed distance map
7426
+ var fdm = /*#__PURE__*/ hMap(fdt, 5, 0), fdrm = /*#__PURE__*/ hMap(fdt, 5, 1);
7427
+ // find max of array
7428
+ var max = function (a) {
7429
+ var m = a[0];
7430
+ for (var i = 1; i < a.length; ++i) {
7431
+ if (a[i] > m)
7432
+ m = a[i];
7433
+ }
7434
+ return m;
7435
+ };
7436
+ // read d, starting at bit p and mask with m
7437
+ var bits = function (d, p, m) {
7438
+ var o = (p / 8) | 0;
7439
+ return ((d[o] | (d[o + 1] << 8)) >> (p & 7)) & m;
7440
+ };
7441
+ // read d, starting at bit p continuing for at least 16 bits
7442
+ var bits16 = function (d, p) {
7443
+ var o = (p / 8) | 0;
7444
+ return ((d[o] | (d[o + 1] << 8) | (d[o + 2] << 16)) >> (p & 7));
7445
+ };
7446
+ // get end of byte
7447
+ var shft = function (p) { return ((p + 7) / 8) | 0; };
7448
+ // typed array slice - allows garbage collector to free original reference,
7449
+ // while being more compatible than .slice
7450
+ var slc = function (v, s, e) {
7451
+ if (s == null || s < 0)
7452
+ s = 0;
7453
+ if (e == null || e > v.length)
7454
+ e = v.length;
7455
+ // can't use .constructor in case user-supplied
7456
+ var n = new (v.BYTES_PER_ELEMENT == 2 ? u16 : v.BYTES_PER_ELEMENT == 4 ? u32 : u8)(e - s);
7457
+ n.set(v.subarray(s, e));
7458
+ return n;
7459
+ };
7460
+ /**
7461
+ * Codes for errors generated within this library
7462
+ */
7463
+ var FlateErrorCode = {
7464
+ UnexpectedEOF: 0,
7465
+ InvalidBlockType: 1,
7466
+ InvalidLengthLiteral: 2,
7467
+ InvalidDistance: 3,
7468
+ StreamFinished: 4,
7469
+ NoStreamHandler: 5,
7470
+ InvalidHeader: 6,
7471
+ NoCallback: 7,
7472
+ InvalidUTF8: 8,
7473
+ ExtraFieldTooLong: 9,
7474
+ InvalidDate: 10,
7475
+ FilenameTooLong: 11,
7476
+ StreamFinishing: 12,
7477
+ InvalidZipData: 13,
7478
+ UnknownCompressionMethod: 14
7479
+ };
7480
+ // error codes
7481
+ var ec = [
7482
+ 'unexpected EOF',
7483
+ 'invalid block type',
7484
+ 'invalid length/literal',
7485
+ 'invalid distance',
7486
+ 'stream finished',
7487
+ 'no stream handler',
7488
+ ,
7489
+ 'no callback',
7490
+ 'invalid UTF-8 data',
7491
+ 'extra field too long',
7492
+ 'date not in range 1980-2099',
7493
+ 'filename too long',
7494
+ 'stream finishing',
7495
+ 'invalid zip data'
7496
+ // determined by unknown compression method
7497
+ ];
7498
+ ;
7499
+ var err = function (ind, msg, nt) {
7500
+ var e = new Error(msg || ec[ind]);
7501
+ e.code = ind;
7502
+ if (Error.captureStackTrace)
7503
+ Error.captureStackTrace(e, err);
7504
+ if (!nt)
7505
+ throw e;
7506
+ return e;
7507
+ };
7508
+ // expands raw DEFLATE data
7509
+ var inflt = function (dat, buf, st) {
7510
+ // source length
7511
+ var sl = dat.length;
7512
+ if (!sl || (st && st.f && !st.l))
7513
+ return buf || new u8(0);
7514
+ // have to estimate size
7515
+ var noBuf = !buf || st;
7516
+ // no state
7517
+ var noSt = !st || st.i;
7518
+ if (!st)
7519
+ st = {};
7520
+ // Assumes roughly 33% compression ratio average
7521
+ if (!buf)
7522
+ buf = new u8(sl * 3);
7523
+ // ensure buffer can fit at least l elements
7524
+ var cbuf = function (l) {
7525
+ var bl = buf.length;
7526
+ // need to increase size to fit
7527
+ if (l > bl) {
7528
+ // Double or set to necessary, whichever is greater
7529
+ var nbuf = new u8(Math.max(bl * 2, l));
7530
+ nbuf.set(buf);
7531
+ buf = nbuf;
7532
+ }
7533
+ };
7534
+ // last chunk bitpos bytes
7535
+ var final = st.f || 0, pos = st.p || 0, bt = st.b || 0, lm = st.l, dm = st.d, lbt = st.m, dbt = st.n;
7536
+ // total bits
7537
+ var tbts = sl * 8;
7538
+ do {
7539
+ if (!lm) {
7540
+ // BFINAL - this is only 1 when last chunk is next
7541
+ final = bits(dat, pos, 1);
7542
+ // type: 0 = no compression, 1 = fixed huffman, 2 = dynamic huffman
7543
+ var type = bits(dat, pos + 1, 3);
7544
+ pos += 3;
7545
+ if (!type) {
7546
+ // go to end of byte boundary
7547
+ var s = shft(pos) + 4, l = dat[s - 4] | (dat[s - 3] << 8), t = s + l;
7548
+ if (t > sl) {
7549
+ if (noSt)
7550
+ err(0);
7551
+ break;
7552
+ }
7553
+ // ensure size
7554
+ if (noBuf)
7555
+ cbuf(bt + l);
7556
+ // Copy over uncompressed data
7557
+ buf.set(dat.subarray(s, t), bt);
7558
+ // Get new bitpos, update byte count
7559
+ st.b = bt += l, st.p = pos = t * 8, st.f = final;
7560
+ continue;
7561
+ }
7562
+ else if (type == 1)
7563
+ lm = flrm, dm = fdrm, lbt = 9, dbt = 5;
7564
+ else if (type == 2) {
7565
+ // literal lengths
7566
+ var hLit = bits(dat, pos, 31) + 257, hcLen = bits(dat, pos + 10, 15) + 4;
7567
+ var tl = hLit + bits(dat, pos + 5, 31) + 1;
7568
+ pos += 14;
7569
+ // length+distance tree
7570
+ var ldt = new u8(tl);
7571
+ // code length tree
7572
+ var clt = new u8(19);
7573
+ for (var i = 0; i < hcLen; ++i) {
7574
+ // use index map to get real code
7575
+ clt[clim[i]] = bits(dat, pos + i * 3, 7);
7576
+ }
7577
+ pos += hcLen * 3;
7578
+ // code lengths bits
7579
+ var clb = max(clt), clbmsk = (1 << clb) - 1;
7580
+ // code lengths map
7581
+ var clm = hMap(clt, clb, 1);
7582
+ for (var i = 0; i < tl;) {
7583
+ var r = clm[bits(dat, pos, clbmsk)];
7584
+ // bits read
7585
+ pos += r & 15;
7586
+ // symbol
7587
+ var s = r >>> 4;
7588
+ // code length to copy
7589
+ if (s < 16) {
7590
+ ldt[i++] = s;
7591
+ }
7592
+ else {
7593
+ // copy count
7594
+ var c = 0, n = 0;
7595
+ if (s == 16)
7596
+ n = 3 + bits(dat, pos, 3), pos += 2, c = ldt[i - 1];
7597
+ else if (s == 17)
7598
+ n = 3 + bits(dat, pos, 7), pos += 3;
7599
+ else if (s == 18)
7600
+ n = 11 + bits(dat, pos, 127), pos += 7;
7601
+ while (n--)
7602
+ ldt[i++] = c;
7603
+ }
7604
+ }
7605
+ // length tree distance tree
7606
+ var lt = ldt.subarray(0, hLit), dt = ldt.subarray(hLit);
7607
+ // max length bits
7608
+ lbt = max(lt);
7609
+ // max dist bits
7610
+ dbt = max(dt);
7611
+ lm = hMap(lt, lbt, 1);
7612
+ dm = hMap(dt, dbt, 1);
7613
+ }
7614
+ else
7615
+ err(1);
7616
+ if (pos > tbts) {
7617
+ if (noSt)
7618
+ err(0);
7619
+ break;
7620
+ }
7621
+ }
7622
+ // Make sure the buffer can hold this + the largest possible addition
7623
+ // Maximum chunk size (practically, theoretically infinite) is 2^17;
7624
+ if (noBuf)
7625
+ cbuf(bt + 131072);
7626
+ var lms = (1 << lbt) - 1, dms = (1 << dbt) - 1;
7627
+ var lpos = pos;
7628
+ for (;; lpos = pos) {
7629
+ // bits read, code
7630
+ var c = lm[bits16(dat, pos) & lms], sym = c >>> 4;
7631
+ pos += c & 15;
7632
+ if (pos > tbts) {
7633
+ if (noSt)
7634
+ err(0);
7635
+ break;
7636
+ }
7637
+ if (!c)
7638
+ err(2);
7639
+ if (sym < 256)
7640
+ buf[bt++] = sym;
7641
+ else if (sym == 256) {
7642
+ lpos = pos, lm = null;
7643
+ break;
7644
+ }
7645
+ else {
7646
+ var add = sym - 254;
7647
+ // no extra bits needed if less
7648
+ if (sym > 264) {
7649
+ // index
7650
+ var i = sym - 257, b = fleb[i];
7651
+ add = bits(dat, pos, (1 << b) - 1) + fl[i];
7652
+ pos += b;
7653
+ }
7654
+ // dist
7655
+ var d = dm[bits16(dat, pos) & dms], dsym = d >>> 4;
7656
+ if (!d)
7657
+ err(3);
7658
+ pos += d & 15;
7659
+ var dt = fd[dsym];
7660
+ if (dsym > 3) {
7661
+ var b = fdeb[dsym];
7662
+ dt += bits16(dat, pos) & ((1 << b) - 1), pos += b;
7663
+ }
7664
+ if (pos > tbts) {
7665
+ if (noSt)
7666
+ err(0);
7667
+ break;
7668
+ }
7669
+ if (noBuf)
7670
+ cbuf(bt + 131072);
7671
+ var end = bt + add;
7672
+ for (; bt < end; bt += 4) {
7673
+ buf[bt] = buf[bt - dt];
7674
+ buf[bt + 1] = buf[bt + 1 - dt];
7675
+ buf[bt + 2] = buf[bt + 2 - dt];
7676
+ buf[bt + 3] = buf[bt + 3 - dt];
7677
+ }
7678
+ bt = end;
7679
+ }
7680
+ }
7681
+ st.l = lm, st.p = lpos, st.b = bt, st.f = final;
7682
+ if (lm)
7683
+ final = 1, st.m = lbt, st.d = dm, st.n = dbt;
7684
+ } while (!final);
7685
+ return bt == buf.length ? buf : slc(buf, 0, bt);
7686
+ };
7687
+ // starting at p, write the minimum number of bits that can hold v to d
7688
+ var wbits = function (d, p, v) {
7689
+ v <<= p & 7;
7690
+ var o = (p / 8) | 0;
7691
+ d[o] |= v;
7692
+ d[o + 1] |= v >>> 8;
7693
+ };
7694
+ // starting at p, write the minimum number of bits (>8) that can hold v to d
7695
+ var wbits16 = function (d, p, v) {
7696
+ v <<= p & 7;
7697
+ var o = (p / 8) | 0;
7698
+ d[o] |= v;
7699
+ d[o + 1] |= v >>> 8;
7700
+ d[o + 2] |= v >>> 16;
7701
+ };
7702
+ // creates code lengths from a frequency table
7703
+ var hTree = function (d, mb) {
7704
+ // Need extra info to make a tree
7705
+ var t = [];
7706
+ for (var i = 0; i < d.length; ++i) {
7707
+ if (d[i])
7708
+ t.push({ s: i, f: d[i] });
7709
+ }
7710
+ var s = t.length;
7711
+ var t2 = t.slice();
7712
+ if (!s)
7713
+ return [et, 0];
7714
+ if (s == 1) {
7715
+ var v = new u8(t[0].s + 1);
7716
+ v[t[0].s] = 1;
7717
+ return [v, 1];
7718
+ }
7719
+ t.sort(function (a, b) { return a.f - b.f; });
7720
+ // after i2 reaches last ind, will be stopped
7721
+ // freq must be greater than largest possible number of symbols
7722
+ t.push({ s: -1, f: 25001 });
7723
+ var l = t[0], r = t[1], i0 = 0, i1 = 1, i2 = 2;
7724
+ t[0] = { s: -1, f: l.f + r.f, l: l, r: r };
7725
+ // efficient algorithm from UZIP.js
7726
+ // i0 is lookbehind, i2 is lookahead - after processing two low-freq
7727
+ // symbols that combined have high freq, will start processing i2 (high-freq,
7728
+ // non-composite) symbols instead
7729
+ // see https://reddit.com/r/photopea/comments/ikekht/uzipjs_questions/
7730
+ while (i1 != s - 1) {
7731
+ l = t[t[i0].f < t[i2].f ? i0++ : i2++];
7732
+ r = t[i0 != i1 && t[i0].f < t[i2].f ? i0++ : i2++];
7733
+ t[i1++] = { s: -1, f: l.f + r.f, l: l, r: r };
7734
+ }
7735
+ var maxSym = t2[0].s;
7736
+ for (var i = 1; i < s; ++i) {
7737
+ if (t2[i].s > maxSym)
7738
+ maxSym = t2[i].s;
7739
+ }
7740
+ // code lengths
7741
+ var tr = new u16(maxSym + 1);
7742
+ // max bits in tree
7743
+ var mbt = ln(t[i1 - 1], tr, 0);
7744
+ if (mbt > mb) {
7745
+ // more algorithms from UZIP.js
7746
+ // TODO: find out how this code works (debt)
7747
+ // ind debt
7748
+ var i = 0, dt = 0;
7749
+ // left cost
7750
+ var lft = mbt - mb, cst = 1 << lft;
7751
+ t2.sort(function (a, b) { return tr[b.s] - tr[a.s] || a.f - b.f; });
7752
+ for (; i < s; ++i) {
7753
+ var i2_1 = t2[i].s;
7754
+ if (tr[i2_1] > mb) {
7755
+ dt += cst - (1 << (mbt - tr[i2_1]));
7756
+ tr[i2_1] = mb;
7757
+ }
7758
+ else
7759
+ break;
7760
+ }
7761
+ dt >>>= lft;
7762
+ while (dt > 0) {
7763
+ var i2_2 = t2[i].s;
7764
+ if (tr[i2_2] < mb)
7765
+ dt -= 1 << (mb - tr[i2_2]++ - 1);
7766
+ else
7767
+ ++i;
7768
+ }
7769
+ for (; i >= 0 && dt; --i) {
7770
+ var i2_3 = t2[i].s;
7771
+ if (tr[i2_3] == mb) {
7772
+ --tr[i2_3];
7773
+ ++dt;
7774
+ }
7775
+ }
7776
+ mbt = mb;
7777
+ }
7778
+ return [new u8(tr), mbt];
7779
+ };
7780
+ // get the max length and assign length codes
7781
+ var ln = function (n, l, d) {
7782
+ return n.s == -1
7783
+ ? Math.max(ln(n.l, l, d + 1), ln(n.r, l, d + 1))
7784
+ : (l[n.s] = d);
7785
+ };
7786
+ // length codes generation
7787
+ var lc = function (c) {
7788
+ var s = c.length;
7789
+ // Note that the semicolon was intentional
7790
+ while (s && !c[--s])
7791
+ ;
7792
+ var cl = new u16(++s);
7793
+ // ind num streak
7794
+ var cli = 0, cln = c[0], cls = 1;
7795
+ var w = function (v) { cl[cli++] = v; };
7796
+ for (var i = 1; i <= s; ++i) {
7797
+ if (c[i] == cln && i != s)
7798
+ ++cls;
7799
+ else {
7800
+ if (!cln && cls > 2) {
7801
+ for (; cls > 138; cls -= 138)
7802
+ w(32754);
7803
+ if (cls > 2) {
7804
+ w(cls > 10 ? ((cls - 11) << 5) | 28690 : ((cls - 3) << 5) | 12305);
7805
+ cls = 0;
7806
+ }
7807
+ }
7808
+ else if (cls > 3) {
7809
+ w(cln), --cls;
7810
+ for (; cls > 6; cls -= 6)
7811
+ w(8304);
7812
+ if (cls > 2)
7813
+ w(((cls - 3) << 5) | 8208), cls = 0;
7814
+ }
7815
+ while (cls--)
7816
+ w(cln);
7817
+ cls = 1;
7818
+ cln = c[i];
7819
+ }
7820
+ }
7821
+ return [cl.subarray(0, cli), s];
7822
+ };
7823
+ // calculate the length of output from tree, code lengths
7824
+ var clen = function (cf, cl) {
7825
+ var l = 0;
7826
+ for (var i = 0; i < cl.length; ++i)
7827
+ l += cf[i] * cl[i];
7828
+ return l;
7829
+ };
7830
+ // writes a fixed block
7831
+ // returns the new bit pos
7832
+ var wfblk = function (out, pos, dat) {
7833
+ // no need to write 00 as type: TypedArray defaults to 0
7834
+ var s = dat.length;
7835
+ var o = shft(pos + 2);
7836
+ out[o] = s & 255;
7837
+ out[o + 1] = s >>> 8;
7838
+ out[o + 2] = out[o] ^ 255;
7839
+ out[o + 3] = out[o + 1] ^ 255;
7840
+ for (var i = 0; i < s; ++i)
7841
+ out[o + i + 4] = dat[i];
7842
+ return (o + 4 + s) * 8;
7843
+ };
7844
+ // writes a block
7845
+ var wblk = function (dat, out, final, syms, lf, df, eb, li, bs, bl, p) {
7846
+ wbits(out, p++, final);
7847
+ ++lf[256];
7848
+ var _a = hTree(lf, 15), dlt = _a[0], mlb = _a[1];
7849
+ var _b = hTree(df, 15), ddt = _b[0], mdb = _b[1];
7850
+ var _c = lc(dlt), lclt = _c[0], nlc = _c[1];
7851
+ var _d = lc(ddt), lcdt = _d[0], ndc = _d[1];
7852
+ var lcfreq = new u16(19);
7853
+ for (var i = 0; i < lclt.length; ++i)
7854
+ lcfreq[lclt[i] & 31]++;
7855
+ for (var i = 0; i < lcdt.length; ++i)
7856
+ lcfreq[lcdt[i] & 31]++;
7857
+ var _e = hTree(lcfreq, 7), lct = _e[0], mlcb = _e[1];
7858
+ var nlcc = 19;
7859
+ for (; nlcc > 4 && !lct[clim[nlcc - 1]]; --nlcc)
7860
+ ;
7861
+ var flen = (bl + 5) << 3;
7862
+ var ftlen = clen(lf, flt) + clen(df, fdt) + eb;
7863
+ var dtlen = clen(lf, dlt) + clen(df, ddt) + eb + 14 + 3 * nlcc + clen(lcfreq, lct) + (2 * lcfreq[16] + 3 * lcfreq[17] + 7 * lcfreq[18]);
7864
+ if (flen <= ftlen && flen <= dtlen)
7865
+ return wfblk(out, p, dat.subarray(bs, bs + bl));
7866
+ var lm, ll, dm, dl;
7867
+ wbits(out, p, 1 + (dtlen < ftlen)), p += 2;
7868
+ if (dtlen < ftlen) {
7869
+ lm = hMap(dlt, mlb, 0), ll = dlt, dm = hMap(ddt, mdb, 0), dl = ddt;
7870
+ var llm = hMap(lct, mlcb, 0);
7871
+ wbits(out, p, nlc - 257);
7872
+ wbits(out, p + 5, ndc - 1);
7873
+ wbits(out, p + 10, nlcc - 4);
7874
+ p += 14;
7875
+ for (var i = 0; i < nlcc; ++i)
7876
+ wbits(out, p + 3 * i, lct[clim[i]]);
7877
+ p += 3 * nlcc;
7878
+ var lcts = [lclt, lcdt];
7879
+ for (var it = 0; it < 2; ++it) {
7880
+ var clct = lcts[it];
7881
+ for (var i = 0; i < clct.length; ++i) {
7882
+ var len = clct[i] & 31;
7883
+ wbits(out, p, llm[len]), p += lct[len];
7884
+ if (len > 15)
7885
+ wbits(out, p, (clct[i] >>> 5) & 127), p += clct[i] >>> 12;
7886
+ }
7887
+ }
7888
+ }
7889
+ else {
7890
+ lm = flm, ll = flt, dm = fdm, dl = fdt;
7891
+ }
7892
+ for (var i = 0; i < li; ++i) {
7893
+ if (syms[i] > 255) {
7894
+ var len = (syms[i] >>> 18) & 31;
7895
+ wbits16(out, p, lm[len + 257]), p += ll[len + 257];
7896
+ if (len > 7)
7897
+ wbits(out, p, (syms[i] >>> 23) & 31), p += fleb[len];
7898
+ var dst = syms[i] & 31;
7899
+ wbits16(out, p, dm[dst]), p += dl[dst];
7900
+ if (dst > 3)
7901
+ wbits16(out, p, (syms[i] >>> 5) & 8191), p += fdeb[dst];
7902
+ }
7903
+ else {
7904
+ wbits16(out, p, lm[syms[i]]), p += ll[syms[i]];
7905
+ }
7906
+ }
7907
+ wbits16(out, p, lm[256]);
7908
+ return p + ll[256];
7909
+ };
7910
+ // deflate options (nice << 13) | chain
7911
+ var deo = /*#__PURE__*/ new u32([65540, 131080, 131088, 131104, 262176, 1048704, 1048832, 2114560, 2117632]);
7912
+ // empty
7913
+ var et = /*#__PURE__*/ new u8(0);
7914
+ // compresses data into a raw DEFLATE buffer
7915
+ var dflt = function (dat, lvl, plvl, pre, post, lst) {
7916
+ var s = dat.length;
7917
+ var o = new u8(pre + s + 5 * (1 + Math.ceil(s / 7000)) + post);
7918
+ // writing to this writes to the output buffer
7919
+ var w = o.subarray(pre, o.length - post);
7920
+ var pos = 0;
7921
+ if (!lvl || s < 8) {
7922
+ for (var i = 0; i <= s; i += 65535) {
7923
+ // end
7924
+ var e = i + 65535;
7925
+ if (e >= s) {
7926
+ // write final block
7927
+ w[pos >> 3] = lst;
7928
+ }
7929
+ pos = wfblk(w, pos + 1, dat.subarray(i, e));
7930
+ }
7931
+ }
7932
+ else {
7933
+ var opt = deo[lvl - 1];
7934
+ var n = opt >>> 13, c = opt & 8191;
7935
+ var msk_1 = (1 << plvl) - 1;
7936
+ // prev 2-byte val map curr 2-byte val map
7937
+ var prev = new u16(32768), head = new u16(msk_1 + 1);
7938
+ var bs1_1 = Math.ceil(plvl / 3), bs2_1 = 2 * bs1_1;
7939
+ var hsh = function (i) { return (dat[i] ^ (dat[i + 1] << bs1_1) ^ (dat[i + 2] << bs2_1)) & msk_1; };
7940
+ // 24576 is an arbitrary number of maximum symbols per block
7941
+ // 424 buffer for last block
7942
+ var syms = new u32(25000);
7943
+ // length/literal freq distance freq
7944
+ var lf = new u16(288), df = new u16(32);
7945
+ // l/lcnt exbits index l/lind waitdx bitpos
7946
+ var lc_1 = 0, eb = 0, i = 0, li = 0, wi = 0, bs = 0;
7947
+ for (; i < s; ++i) {
7948
+ // hash value
7949
+ // deopt when i > s - 3 - at end, deopt acceptable
7950
+ var hv = hsh(i);
7951
+ // index mod 32768 previous index mod
7952
+ var imod = i & 32767, pimod = head[hv];
7953
+ prev[imod] = pimod;
7954
+ head[hv] = imod;
7955
+ // We always should modify head and prev, but only add symbols if
7956
+ // this data is not yet processed ("wait" for wait index)
7957
+ if (wi <= i) {
7958
+ // bytes remaining
7959
+ var rem = s - i;
7960
+ if ((lc_1 > 7000 || li > 24576) && rem > 423) {
7961
+ pos = wblk(dat, w, 0, syms, lf, df, eb, li, bs, i - bs, pos);
7962
+ li = lc_1 = eb = 0, bs = i;
7963
+ for (var j = 0; j < 286; ++j)
7964
+ lf[j] = 0;
7965
+ for (var j = 0; j < 30; ++j)
7966
+ df[j] = 0;
7967
+ }
7968
+ // len dist chain
7969
+ var l = 2, d = 0, ch_1 = c, dif = (imod - pimod) & 32767;
7970
+ if (rem > 2 && hv == hsh(i - dif)) {
7971
+ var maxn = Math.min(n, rem) - 1;
7972
+ var maxd = Math.min(32767, i);
7973
+ // max possible length
7974
+ // not capped at dif because decompressors implement "rolling" index population
7975
+ var ml = Math.min(258, rem);
7976
+ while (dif <= maxd && --ch_1 && imod != pimod) {
7977
+ if (dat[i + l] == dat[i + l - dif]) {
7978
+ var nl = 0;
7979
+ for (; nl < ml && dat[i + nl] == dat[i + nl - dif]; ++nl)
7980
+ ;
7981
+ if (nl > l) {
7982
+ l = nl, d = dif;
7983
+ // break out early when we reach "nice" (we are satisfied enough)
7984
+ if (nl > maxn)
7985
+ break;
7986
+ // now, find the rarest 2-byte sequence within this
7987
+ // length of literals and search for that instead.
7988
+ // Much faster than just using the start
7989
+ var mmd = Math.min(dif, nl - 2);
7990
+ var md = 0;
7991
+ for (var j = 0; j < mmd; ++j) {
7992
+ var ti = (i - dif + j + 32768) & 32767;
7993
+ var pti = prev[ti];
7994
+ var cd = (ti - pti + 32768) & 32767;
7995
+ if (cd > md)
7996
+ md = cd, pimod = ti;
7997
+ }
7998
+ }
7999
+ }
8000
+ // check the previous match
8001
+ imod = pimod, pimod = prev[imod];
8002
+ dif += (imod - pimod + 32768) & 32767;
8003
+ }
8004
+ }
8005
+ // d will be nonzero only when a match was found
8006
+ if (d) {
8007
+ // store both dist and len data in one Uint32
8008
+ // Make sure this is recognized as a len/dist with 28th bit (2^28)
8009
+ syms[li++] = 268435456 | (revfl[l] << 18) | revfd[d];
8010
+ var lin = revfl[l] & 31, din = revfd[d] & 31;
8011
+ eb += fleb[lin] + fdeb[din];
8012
+ ++lf[257 + lin];
8013
+ ++df[din];
8014
+ wi = i + l;
8015
+ ++lc_1;
8016
+ }
8017
+ else {
8018
+ syms[li++] = dat[i];
8019
+ ++lf[dat[i]];
8020
+ }
8021
+ }
8022
+ }
8023
+ pos = wblk(dat, w, lst, syms, lf, df, eb, li, bs, i - bs, pos);
8024
+ // this is the easiest way to avoid needing to maintain state
8025
+ if (!lst && pos & 7)
8026
+ pos = wfblk(w, pos + 1, et);
8027
+ }
8028
+ return slc(o, 0, pre + shft(pos) + post);
8029
+ };
8030
+ // CRC32 table
8031
+ var crct = /*#__PURE__*/ (function () {
8032
+ var t = new Int32Array(256);
8033
+ for (var i = 0; i < 256; ++i) {
8034
+ var c = i, k = 9;
8035
+ while (--k)
8036
+ c = ((c & 1) && -306674912) ^ (c >>> 1);
8037
+ t[i] = c;
8038
+ }
8039
+ return t;
8040
+ })();
8041
+ // CRC32
8042
+ var crc = function () {
8043
+ var c = -1;
8044
+ return {
8045
+ p: function (d) {
8046
+ // closures have awful performance
8047
+ var cr = c;
8048
+ for (var i = 0; i < d.length; ++i)
8049
+ cr = crct[(cr & 255) ^ d[i]] ^ (cr >>> 8);
8050
+ c = cr;
8051
+ },
8052
+ d: function () { return ~c; }
8053
+ };
8054
+ };
8055
+ // Alder32
8056
+ var adler = function () {
8057
+ var a = 1, b = 0;
8058
+ return {
8059
+ p: function (d) {
8060
+ // closures have awful performance
8061
+ var n = a, m = b;
8062
+ var l = d.length | 0;
8063
+ for (var i = 0; i != l;) {
8064
+ var e = Math.min(i + 2655, l);
8065
+ for (; i < e; ++i)
8066
+ m += n += d[i];
8067
+ n = (n & 65535) + 15 * (n >> 16), m = (m & 65535) + 15 * (m >> 16);
8068
+ }
8069
+ a = n, b = m;
8070
+ },
8071
+ d: function () {
8072
+ a %= 65521, b %= 65521;
8073
+ return (a & 255) << 24 | (a >>> 8) << 16 | (b & 255) << 8 | (b >>> 8);
8074
+ }
8075
+ };
8076
+ };
8077
+ ;
8078
+ // deflate with opts
8079
+ var dopt = function (dat, opt, pre, post, st) {
8080
+ return dflt(dat, opt.level == null ? 6 : opt.level, opt.mem == null ? Math.ceil(Math.max(8, Math.min(13, Math.log(dat.length))) * 1.5) : (12 + opt.mem), pre, post, !st);
8081
+ };
8082
+ // Walmart object spread
8083
+ var mrg = function (a, b) {
8084
+ var o = {};
8085
+ for (var k in a)
8086
+ o[k] = a[k];
8087
+ for (var k in b)
8088
+ o[k] = b[k];
8089
+ return o;
8090
+ };
8091
+ // worker clone
8092
+ // This is possibly the craziest part of the entire codebase, despite how simple it may seem.
8093
+ // The only parameter to this function is a closure that returns an array of variables outside of the function scope.
8094
+ // We're going to try to figure out the variable names used in the closure as strings because that is crucial for workerization.
8095
+ // We will return an object mapping of true variable name to value (basically, the current scope as a JS object).
8096
+ // The reason we can't just use the original variable names is minifiers mangling the toplevel scope.
8097
+ // This took me three weeks to figure out how to do.
8098
+ var wcln = function (fn, fnStr, td) {
8099
+ var dt = fn();
8100
+ var st = fn.toString();
8101
+ var ks = st.slice(st.indexOf('[') + 1, st.lastIndexOf(']')).replace(/\s+/g, '').split(',');
8102
+ for (var i = 0; i < dt.length; ++i) {
8103
+ var v = dt[i], k = ks[i];
8104
+ if (typeof v == 'function') {
8105
+ fnStr += ';' + k + '=';
8106
+ var st_1 = v.toString();
8107
+ if (v.prototype) {
8108
+ // for global objects
8109
+ if (st_1.indexOf('[native code]') != -1) {
8110
+ var spInd = st_1.indexOf(' ', 8) + 1;
8111
+ fnStr += st_1.slice(spInd, st_1.indexOf('(', spInd));
8112
+ }
8113
+ else {
8114
+ fnStr += st_1;
8115
+ for (var t in v.prototype)
8116
+ fnStr += ';' + k + '.prototype.' + t + '=' + v.prototype[t].toString();
8117
+ }
8118
+ }
8119
+ else
8120
+ fnStr += st_1;
8121
+ }
8122
+ else
8123
+ td[k] = v;
8124
+ }
8125
+ return [fnStr, td];
8126
+ };
8127
+ var ch = [];
8128
+ // clone bufs
8129
+ var cbfs = function (v) {
8130
+ var tl = [];
8131
+ for (var k in v) {
8132
+ if (v[k].buffer) {
8133
+ tl.push((v[k] = new v[k].constructor(v[k])).buffer);
8134
+ }
8135
+ }
8136
+ return tl;
8137
+ };
8138
+ // use a worker to execute code
8139
+ var wrkr = function (fns, init, id, cb) {
8140
+ var _a;
8141
+ if (!ch[id]) {
8142
+ var fnStr = '', td_1 = {}, m = fns.length - 1;
8143
+ for (var i = 0; i < m; ++i)
8144
+ _a = wcln(fns[i], fnStr, td_1), fnStr = _a[0], td_1 = _a[1];
8145
+ ch[id] = wcln(fns[m], fnStr, td_1);
8146
+ }
8147
+ var td = mrg({}, ch[id][1]);
8148
+ return wk(ch[id][0] + ';onmessage=function(e){for(var k in e.data)self[k]=e.data[k];onmessage=' + init.toString() + '}', id, td, cbfs(td), cb);
8149
+ };
8150
+ // base async inflate fn
8151
+ var bInflt = function () { return [u8, u16, u32, fleb, fdeb, clim, fl, fd, flrm, fdrm, rev, ec, hMap, max, bits, bits16, shft, slc, err, inflt, inflateSync, pbf, gu8]; };
8152
+ var bDflt = function () { return [u8, u16, u32, fleb, fdeb, clim, revfl, revfd, flm, flt, fdm, fdt, rev, deo, et, hMap, wbits, wbits16, hTree, ln, lc, clen, wfblk, wblk, shft, slc, dflt, dopt, deflateSync, pbf]; };
8153
+ // gzip extra
8154
+ var gze = function () { return [gzh, gzhl, wbytes, crc, crct]; };
8155
+ // gunzip extra
8156
+ var guze = function () { return [gzs, gzl]; };
8157
+ // zlib extra
8158
+ var zle = function () { return [zlh, wbytes, adler]; };
8159
+ // unzlib extra
8160
+ var zule = function () { return [zlv]; };
8161
+ // post buf
8162
+ var pbf = function (msg) { return postMessage(msg, [msg.buffer]); };
8163
+ // get u8
8164
+ var gu8 = function (o) { return o && o.size && new u8(o.size); };
8165
+ // async helper
8166
+ var cbify = function (dat, opts, fns, init, id, cb) {
8167
+ var w = wrkr(fns, init, id, function (err, dat) {
8168
+ w.terminate();
8169
+ cb(err, dat);
8170
+ });
8171
+ w.postMessage([dat, opts], opts.consume ? [dat.buffer] : []);
8172
+ return function () { w.terminate(); };
8173
+ };
8174
+ // auto stream
8175
+ var astrm = function (strm) {
8176
+ strm.ondata = function (dat, final) { return postMessage([dat, final], [dat.buffer]); };
8177
+ return function (ev) { return strm.push(ev.data[0], ev.data[1]); };
8178
+ };
8179
+ // async stream attach
8180
+ var astrmify = function (fns, strm, opts, init, id) {
8181
+ var t;
8182
+ var w = wrkr(fns, init, id, function (err, dat) {
8183
+ if (err)
8184
+ w.terminate(), strm.ondata.call(strm, err);
8185
+ else {
8186
+ if (dat[1])
8187
+ w.terminate();
8188
+ strm.ondata.call(strm, err, dat[0], dat[1]);
8189
+ }
8190
+ });
8191
+ w.postMessage(opts);
8192
+ strm.push = function (d, f) {
8193
+ if (!strm.ondata)
8194
+ err(5);
8195
+ if (t)
8196
+ strm.ondata(err(4, 0, 1), null, !!f);
8197
+ w.postMessage([d, t = f], [d.buffer]);
8198
+ };
8199
+ strm.terminate = function () { w.terminate(); };
8200
+ };
8201
+ // read 2 bytes
8202
+ var b2 = function (d, b) { return d[b] | (d[b + 1] << 8); };
8203
+ // read 4 bytes
8204
+ var b4 = function (d, b) { return (d[b] | (d[b + 1] << 8) | (d[b + 2] << 16) | (d[b + 3] << 24)) >>> 0; };
8205
+ var b8 = function (d, b) { return b4(d, b) + (b4(d, b + 4) * 4294967296); };
8206
+ // write bytes
8207
+ var wbytes = function (d, b, v) {
8208
+ for (; v; ++b)
8209
+ d[b] = v, v >>>= 8;
8210
+ };
8211
+ // gzip header
8212
+ var gzh = function (c, o) {
8213
+ var fn = o.filename;
8214
+ c[0] = 31, c[1] = 139, c[2] = 8, c[8] = o.level < 2 ? 4 : o.level == 9 ? 2 : 0, c[9] = 3; // assume Unix
8215
+ if (o.mtime != 0)
8216
+ wbytes(c, 4, Math.floor(new Date(o.mtime || Date.now()) / 1000));
8217
+ if (fn) {
8218
+ c[3] = 8;
8219
+ for (var i = 0; i <= fn.length; ++i)
8220
+ c[i + 10] = fn.charCodeAt(i);
8221
+ }
8222
+ };
8223
+ // gzip footer: -8 to -4 = CRC, -4 to -0 is length
8224
+ // gzip start
8225
+ var gzs = function (d) {
8226
+ if (d[0] != 31 || d[1] != 139 || d[2] != 8)
8227
+ err(6, 'invalid gzip data');
8228
+ var flg = d[3];
8229
+ var st = 10;
8230
+ if (flg & 4)
8231
+ st += d[10] | (d[11] << 8) + 2;
8232
+ for (var zs = (flg >> 3 & 1) + (flg >> 4 & 1); zs > 0; zs -= !d[st++])
8233
+ ;
8234
+ return st + (flg & 2);
8235
+ };
8236
+ // gzip length
8237
+ var gzl = function (d) {
8238
+ var l = d.length;
8239
+ return ((d[l - 4] | d[l - 3] << 8 | d[l - 2] << 16) | (d[l - 1] << 24)) >>> 0;
8240
+ };
8241
+ // gzip header length
8242
+ var gzhl = function (o) { return 10 + ((o.filename && (o.filename.length + 1)) || 0); };
8243
+ // zlib header
8244
+ var zlh = function (c, o) {
8245
+ var lv = o.level, fl = lv == 0 ? 0 : lv < 6 ? 1 : lv == 9 ? 3 : 2;
8246
+ c[0] = 120, c[1] = (fl << 6) | (fl ? (32 - 2 * fl) : 1);
8247
+ };
8248
+ // zlib valid
8249
+ var zlv = function (d) {
8250
+ if ((d[0] & 15) != 8 || (d[0] >>> 4) > 7 || ((d[0] << 8 | d[1]) % 31))
8251
+ err(6, 'invalid zlib data');
8252
+ if (d[1] & 32)
8253
+ err(6, 'invalid zlib data: preset dictionaries not supported');
8254
+ };
8255
+ function AsyncCmpStrm(opts, cb) {
8256
+ if (!cb && typeof opts == 'function')
8257
+ cb = opts, opts = {};
8258
+ this.ondata = cb;
8259
+ return opts;
8260
+ }
8261
+ // zlib footer: -4 to -0 is Adler32
8262
+ /**
8263
+ * Streaming DEFLATE compression
8264
+ */
8265
+ var Deflate = /*#__PURE__*/ (function () {
8266
+ function Deflate(opts, cb) {
8267
+ if (!cb && typeof opts == 'function')
8268
+ cb = opts, opts = {};
8269
+ this.ondata = cb;
8270
+ this.o = opts || {};
8271
+ }
8272
+ Deflate.prototype.p = function (c, f) {
8273
+ this.ondata(dopt(c, this.o, 0, 0, !f), f);
8274
+ };
8275
+ /**
8276
+ * Pushes a chunk to be deflated
8277
+ * @param chunk The chunk to push
8278
+ * @param final Whether this is the last chunk
8279
+ */
8280
+ Deflate.prototype.push = function (chunk, final) {
8281
+ if (!this.ondata)
8282
+ err(5);
8283
+ if (this.d)
8284
+ err(4);
8285
+ this.d = final;
8286
+ this.p(chunk, final || false);
8287
+ };
8288
+ return Deflate;
8289
+ }());
8290
+ /**
8291
+ * Asynchronous streaming DEFLATE compression
8292
+ */
8293
+ var AsyncDeflate = /*#__PURE__*/ (function () {
8294
+ function AsyncDeflate(opts, cb) {
8295
+ astrmify([
8296
+ bDflt,
8297
+ function () { return [astrm, Deflate]; }
8298
+ ], this, AsyncCmpStrm.call(this, opts, cb), function (ev) {
8299
+ var strm = new Deflate(ev.data);
8300
+ onmessage = astrm(strm);
8301
+ }, 6);
8302
+ }
8303
+ return AsyncDeflate;
8304
+ }());
8305
+ function deflate(data, opts, cb) {
8306
+ if (!cb)
8307
+ cb = opts, opts = {};
8308
+ if (typeof cb != 'function')
8309
+ err(7);
8310
+ return cbify(data, opts, [
8311
+ bDflt,
8312
+ ], function (ev) { return pbf(deflateSync(ev.data[0], ev.data[1])); }, 0, cb);
8313
+ }
8314
+ /**
8315
+ * Compresses data with DEFLATE without any wrapper
8316
+ * @param data The data to compress
8317
+ * @param opts The compression options
8318
+ * @returns The deflated version of the data
8319
+ */
8320
+ function deflateSync(data, opts) {
8321
+ return dopt(data, opts || {}, 0, 0);
8322
+ }
8323
+ /**
8324
+ * Streaming DEFLATE decompression
8325
+ */
8326
+ var Inflate = /*#__PURE__*/ (function () {
8327
+ /**
8328
+ * Creates an inflation stream
8329
+ * @param cb The callback to call whenever data is inflated
8330
+ */
8331
+ function Inflate(cb) {
8332
+ this.s = {};
8333
+ this.p = new u8(0);
8334
+ this.ondata = cb;
8335
+ }
8336
+ Inflate.prototype.e = function (c) {
8337
+ if (!this.ondata)
8338
+ err(5);
8339
+ if (this.d)
8340
+ err(4);
8341
+ var l = this.p.length;
8342
+ var n = new u8(l + c.length);
8343
+ n.set(this.p), n.set(c, l), this.p = n;
8344
+ };
8345
+ Inflate.prototype.c = function (final) {
8346
+ this.d = this.s.i = final || false;
8347
+ var bts = this.s.b;
8348
+ var dt = inflt(this.p, this.o, this.s);
8349
+ this.ondata(slc(dt, bts, this.s.b), this.d);
8350
+ this.o = slc(dt, this.s.b - 32768), this.s.b = this.o.length;
8351
+ this.p = slc(this.p, (this.s.p / 8) | 0), this.s.p &= 7;
8352
+ };
8353
+ /**
8354
+ * Pushes a chunk to be inflated
8355
+ * @param chunk The chunk to push
8356
+ * @param final Whether this is the final chunk
8357
+ */
8358
+ Inflate.prototype.push = function (chunk, final) {
8359
+ this.e(chunk), this.c(final);
8360
+ };
8361
+ return Inflate;
8362
+ }());
8363
+ /**
8364
+ * Asynchronous streaming DEFLATE decompression
8365
+ */
8366
+ var AsyncInflate = /*#__PURE__*/ (function () {
8367
+ /**
8368
+ * Creates an asynchronous inflation stream
8369
+ * @param cb The callback to call whenever data is deflated
8370
+ */
8371
+ function AsyncInflate(cb) {
8372
+ this.ondata = cb;
8373
+ astrmify([
8374
+ bInflt,
8375
+ function () { return [astrm, Inflate]; }
8376
+ ], this, 0, function () {
8377
+ var strm = new Inflate();
8378
+ onmessage = astrm(strm);
8379
+ }, 7);
8380
+ }
8381
+ return AsyncInflate;
8382
+ }());
8383
+ function inflate(data, opts, cb) {
8384
+ if (!cb)
8385
+ cb = opts, opts = {};
8386
+ if (typeof cb != 'function')
8387
+ err(7);
8388
+ return cbify(data, opts, [
8389
+ bInflt
8390
+ ], function (ev) { return pbf(inflateSync(ev.data[0], gu8(ev.data[1]))); }, 1, cb);
8391
+ }
8392
+ /**
8393
+ * Expands DEFLATE data with no wrapper
8394
+ * @param data The data to decompress
8395
+ * @param out Where to write the data. Saves memory if you know the decompressed size and provide an output buffer of that length.
8396
+ * @returns The decompressed version of the data
8397
+ */
8398
+ function inflateSync(data, out) {
8399
+ return inflt(data, out);
8400
+ }
8401
+ // before you yell at me for not just using extends, my reason is that TS inheritance is hard to workerize.
8402
+ /**
8403
+ * Streaming GZIP compression
8404
+ */
8405
+ var Gzip$1 = /*#__PURE__*/ (function () {
8406
+ function Gzip(opts, cb) {
8407
+ this.c = crc();
8408
+ this.l = 0;
8409
+ this.v = 1;
8410
+ Deflate.call(this, opts, cb);
8411
+ }
8412
+ /**
8413
+ * Pushes a chunk to be GZIPped
8414
+ * @param chunk The chunk to push
8415
+ * @param final Whether this is the last chunk
8416
+ */
8417
+ Gzip.prototype.push = function (chunk, final) {
8418
+ Deflate.prototype.push.call(this, chunk, final);
8419
+ };
8420
+ Gzip.prototype.p = function (c, f) {
8421
+ this.c.p(c);
8422
+ this.l += c.length;
8423
+ var raw = dopt(c, this.o, this.v && gzhl(this.o), f && 8, !f);
8424
+ if (this.v)
8425
+ gzh(raw, this.o), this.v = 0;
8426
+ if (f)
8427
+ wbytes(raw, raw.length - 8, this.c.d()), wbytes(raw, raw.length - 4, this.l);
8428
+ this.ondata(raw, f);
8429
+ };
8430
+ return Gzip;
8431
+ }());
8432
+ /**
8433
+ * Asynchronous streaming GZIP compression
8434
+ */
8435
+ var AsyncGzip = /*#__PURE__*/ (function () {
8436
+ function AsyncGzip(opts, cb) {
8437
+ astrmify([
8438
+ bDflt,
8439
+ gze,
8440
+ function () { return [astrm, Deflate, Gzip$1]; }
8441
+ ], this, AsyncCmpStrm.call(this, opts, cb), function (ev) {
8442
+ var strm = new Gzip$1(ev.data);
8443
+ onmessage = astrm(strm);
8444
+ }, 8);
8445
+ }
8446
+ return AsyncGzip;
8447
+ }());
8448
+ function gzip(data, opts, cb) {
8449
+ if (!cb)
8450
+ cb = opts, opts = {};
8451
+ if (typeof cb != 'function')
8452
+ err(7);
8453
+ return cbify(data, opts, [
8454
+ bDflt,
8455
+ gze,
8456
+ function () { return [gzipSync$1]; }
8457
+ ], function (ev) { return pbf(gzipSync$1(ev.data[0], ev.data[1])); }, 2, cb);
8458
+ }
8459
+ /**
8460
+ * Compresses data with GZIP
8461
+ * @param data The data to compress
8462
+ * @param opts The compression options
8463
+ * @returns The gzipped version of the data
8464
+ */
8465
+ function gzipSync$1(data, opts) {
8466
+ if (!opts)
8467
+ opts = {};
8468
+ var c = crc(), l = data.length;
8469
+ c.p(data);
8470
+ var d = dopt(data, opts, gzhl(opts), 8), s = d.length;
8471
+ return gzh(d, opts), wbytes(d, s - 8, c.d()), wbytes(d, s - 4, l), d;
8472
+ }
8473
+ /**
8474
+ * Streaming GZIP decompression
8475
+ */
8476
+ var Gunzip = /*#__PURE__*/ (function () {
8477
+ /**
8478
+ * Creates a GUNZIP stream
8479
+ * @param cb The callback to call whenever data is inflated
8480
+ */
8481
+ function Gunzip(cb) {
8482
+ this.v = 1;
8483
+ Inflate.call(this, cb);
8484
+ }
8485
+ /**
8486
+ * Pushes a chunk to be GUNZIPped
8487
+ * @param chunk The chunk to push
8488
+ * @param final Whether this is the last chunk
8489
+ */
8490
+ Gunzip.prototype.push = function (chunk, final) {
8491
+ Inflate.prototype.e.call(this, chunk);
8492
+ if (this.v) {
8493
+ var s = this.p.length > 3 ? gzs(this.p) : 4;
8494
+ if (s >= this.p.length && !final)
8495
+ return;
8496
+ this.p = this.p.subarray(s), this.v = 0;
8497
+ }
8498
+ if (final) {
8499
+ if (this.p.length < 8)
8500
+ err(6, 'invalid gzip data');
8501
+ this.p = this.p.subarray(0, -8);
8502
+ }
8503
+ // necessary to prevent TS from using the closure value
8504
+ // This allows for workerization to function correctly
8505
+ Inflate.prototype.c.call(this, final);
8506
+ };
8507
+ return Gunzip;
8508
+ }());
8509
+ /**
8510
+ * Asynchronous streaming GZIP decompression
8511
+ */
8512
+ var AsyncGunzip = /*#__PURE__*/ (function () {
8513
+ /**
8514
+ * Creates an asynchronous GUNZIP stream
8515
+ * @param cb The callback to call whenever data is deflated
8516
+ */
8517
+ function AsyncGunzip(cb) {
8518
+ this.ondata = cb;
8519
+ astrmify([
8520
+ bInflt,
8521
+ guze,
8522
+ function () { return [astrm, Inflate, Gunzip]; }
8523
+ ], this, 0, function () {
8524
+ var strm = new Gunzip();
8525
+ onmessage = astrm(strm);
8526
+ }, 9);
8527
+ }
8528
+ return AsyncGunzip;
8529
+ }());
8530
+ function gunzip(data, opts, cb) {
8531
+ if (!cb)
8532
+ cb = opts, opts = {};
8533
+ if (typeof cb != 'function')
8534
+ err(7);
8535
+ return cbify(data, opts, [
8536
+ bInflt,
8537
+ guze,
8538
+ function () { return [gunzipSync$1]; }
8539
+ ], function (ev) { return pbf(gunzipSync$1(ev.data[0])); }, 3, cb);
8540
+ }
8541
+ /**
8542
+ * Expands GZIP data
8543
+ * @param data The data to decompress
8544
+ * @param out Where to write the data. GZIP already encodes the output size, so providing this doesn't save memory.
8545
+ * @returns The decompressed version of the data
8546
+ */
8547
+ function gunzipSync$1(data, out) {
8548
+ return inflt(data.subarray(gzs(data), -8), out || new u8(gzl(data)));
8549
+ }
8550
+ /**
8551
+ * Streaming Zlib compression
8552
+ */
8553
+ var Zlib = /*#__PURE__*/ (function () {
8554
+ function Zlib(opts, cb) {
8555
+ this.c = adler();
8556
+ this.v = 1;
8557
+ Deflate.call(this, opts, cb);
8558
+ }
8559
+ /**
8560
+ * Pushes a chunk to be zlibbed
8561
+ * @param chunk The chunk to push
8562
+ * @param final Whether this is the last chunk
8563
+ */
8564
+ Zlib.prototype.push = function (chunk, final) {
8565
+ Deflate.prototype.push.call(this, chunk, final);
8566
+ };
8567
+ Zlib.prototype.p = function (c, f) {
8568
+ this.c.p(c);
8569
+ var raw = dopt(c, this.o, this.v && 2, f && 4, !f);
8570
+ if (this.v)
8571
+ zlh(raw, this.o), this.v = 0;
8572
+ if (f)
8573
+ wbytes(raw, raw.length - 4, this.c.d());
8574
+ this.ondata(raw, f);
8575
+ };
8576
+ return Zlib;
8577
+ }());
8578
+ /**
8579
+ * Asynchronous streaming Zlib compression
8580
+ */
8581
+ var AsyncZlib = /*#__PURE__*/ (function () {
8582
+ function AsyncZlib(opts, cb) {
8583
+ astrmify([
8584
+ bDflt,
8585
+ zle,
8586
+ function () { return [astrm, Deflate, Zlib]; }
8587
+ ], this, AsyncCmpStrm.call(this, opts, cb), function (ev) {
8588
+ var strm = new Zlib(ev.data);
8589
+ onmessage = astrm(strm);
8590
+ }, 10);
8591
+ }
8592
+ return AsyncZlib;
8593
+ }());
8594
+ function zlib(data, opts, cb) {
8595
+ if (!cb)
8596
+ cb = opts, opts = {};
8597
+ if (typeof cb != 'function')
8598
+ err(7);
8599
+ return cbify(data, opts, [
8600
+ bDflt,
8601
+ zle,
8602
+ function () { return [zlibSync]; }
8603
+ ], function (ev) { return pbf(zlibSync(ev.data[0], ev.data[1])); }, 4, cb);
8604
+ }
8605
+ /**
8606
+ * Compress data with Zlib
8607
+ * @param data The data to compress
8608
+ * @param opts The compression options
8609
+ * @returns The zlib-compressed version of the data
8610
+ */
8611
+ function zlibSync(data, opts) {
8612
+ if (!opts)
8613
+ opts = {};
8614
+ var a = adler();
8615
+ a.p(data);
8616
+ var d = dopt(data, opts, 2, 4);
8617
+ return zlh(d, opts), wbytes(d, d.length - 4, a.d()), d;
8618
+ }
8619
+ /**
8620
+ * Streaming Zlib decompression
8621
+ */
8622
+ var Unzlib = /*#__PURE__*/ (function () {
8623
+ /**
8624
+ * Creates a Zlib decompression stream
8625
+ * @param cb The callback to call whenever data is inflated
8626
+ */
8627
+ function Unzlib(cb) {
8628
+ this.v = 1;
8629
+ Inflate.call(this, cb);
8630
+ }
8631
+ /**
8632
+ * Pushes a chunk to be unzlibbed
8633
+ * @param chunk The chunk to push
8634
+ * @param final Whether this is the last chunk
8635
+ */
8636
+ Unzlib.prototype.push = function (chunk, final) {
8637
+ Inflate.prototype.e.call(this, chunk);
8638
+ if (this.v) {
8639
+ if (this.p.length < 2 && !final)
8640
+ return;
8641
+ this.p = this.p.subarray(2), this.v = 0;
8642
+ }
8643
+ if (final) {
8644
+ if (this.p.length < 4)
8645
+ err(6, 'invalid zlib data');
8646
+ this.p = this.p.subarray(0, -4);
8647
+ }
8648
+ // necessary to prevent TS from using the closure value
8649
+ // This allows for workerization to function correctly
8650
+ Inflate.prototype.c.call(this, final);
8651
+ };
8652
+ return Unzlib;
8653
+ }());
8654
+ /**
8655
+ * Asynchronous streaming Zlib decompression
8656
+ */
8657
+ var AsyncUnzlib = /*#__PURE__*/ (function () {
8658
+ /**
8659
+ * Creates an asynchronous Zlib decompression stream
8660
+ * @param cb The callback to call whenever data is deflated
8661
+ */
8662
+ function AsyncUnzlib(cb) {
8663
+ this.ondata = cb;
8664
+ astrmify([
8665
+ bInflt,
8666
+ zule,
8667
+ function () { return [astrm, Inflate, Unzlib]; }
8668
+ ], this, 0, function () {
8669
+ var strm = new Unzlib();
8670
+ onmessage = astrm(strm);
8671
+ }, 11);
8672
+ }
8673
+ return AsyncUnzlib;
8674
+ }());
8675
+ function unzlib(data, opts, cb) {
8676
+ if (!cb)
8677
+ cb = opts, opts = {};
8678
+ if (typeof cb != 'function')
8679
+ err(7);
8680
+ return cbify(data, opts, [
8681
+ bInflt,
8682
+ zule,
8683
+ function () { return [unzlibSync]; }
8684
+ ], function (ev) { return pbf(unzlibSync(ev.data[0], gu8(ev.data[1]))); }, 5, cb);
8685
+ }
8686
+ /**
8687
+ * Expands Zlib data
8688
+ * @param data The data to decompress
8689
+ * @param out Where to write the data. Saves memory if you know the decompressed size and provide an output buffer of that length.
8690
+ * @returns The decompressed version of the data
8691
+ */
8692
+ function unzlibSync(data, out) {
8693
+ return inflt((zlv(data), data.subarray(2, -4)), out);
8694
+ }
8695
+ /**
8696
+ * Streaming GZIP, Zlib, or raw DEFLATE decompression
8697
+ */
8698
+ var Decompress = /*#__PURE__*/ (function () {
8699
+ /**
8700
+ * Creates a decompression stream
8701
+ * @param cb The callback to call whenever data is decompressed
8702
+ */
8703
+ function Decompress(cb) {
8704
+ this.G = Gunzip;
8705
+ this.I = Inflate;
8706
+ this.Z = Unzlib;
8707
+ this.ondata = cb;
8708
+ }
8709
+ /**
8710
+ * Pushes a chunk to be decompressed
8711
+ * @param chunk The chunk to push
8712
+ * @param final Whether this is the last chunk
8713
+ */
8714
+ Decompress.prototype.push = function (chunk, final) {
8715
+ if (!this.ondata)
8716
+ err(5);
8717
+ if (!this.s) {
8718
+ if (this.p && this.p.length) {
8719
+ var n = new u8(this.p.length + chunk.length);
8720
+ n.set(this.p), n.set(chunk, this.p.length);
8721
+ }
8722
+ else
8723
+ this.p = chunk;
8724
+ if (this.p.length > 2) {
8725
+ var _this_1 = this;
8726
+ var cb = function () { _this_1.ondata.apply(_this_1, arguments); };
8727
+ this.s = (this.p[0] == 31 && this.p[1] == 139 && this.p[2] == 8)
8728
+ ? new this.G(cb)
8729
+ : ((this.p[0] & 15) != 8 || (this.p[0] >> 4) > 7 || ((this.p[0] << 8 | this.p[1]) % 31))
8730
+ ? new this.I(cb)
8731
+ : new this.Z(cb);
8732
+ this.s.push(this.p, final);
8733
+ this.p = null;
8734
+ }
8735
+ }
8736
+ else
8737
+ this.s.push(chunk, final);
8738
+ };
8739
+ return Decompress;
8740
+ }());
8741
+ /**
8742
+ * Asynchronous streaming GZIP, Zlib, or raw DEFLATE decompression
8743
+ */
8744
+ var AsyncDecompress = /*#__PURE__*/ (function () {
8745
+ /**
8746
+ * Creates an asynchronous decompression stream
8747
+ * @param cb The callback to call whenever data is decompressed
8748
+ */
8749
+ function AsyncDecompress(cb) {
8750
+ this.G = AsyncGunzip;
8751
+ this.I = AsyncInflate;
8752
+ this.Z = AsyncUnzlib;
8753
+ this.ondata = cb;
8754
+ }
8755
+ /**
8756
+ * Pushes a chunk to be decompressed
8757
+ * @param chunk The chunk to push
8758
+ * @param final Whether this is the last chunk
8759
+ */
8760
+ AsyncDecompress.prototype.push = function (chunk, final) {
8761
+ Decompress.prototype.push.call(this, chunk, final);
8762
+ };
8763
+ return AsyncDecompress;
8764
+ }());
8765
+ function decompress(data, opts, cb) {
8766
+ if (!cb)
8767
+ cb = opts, opts = {};
8768
+ if (typeof cb != 'function')
8769
+ err(7);
8770
+ return (data[0] == 31 && data[1] == 139 && data[2] == 8)
8771
+ ? gunzip(data, opts, cb)
8772
+ : ((data[0] & 15) != 8 || (data[0] >> 4) > 7 || ((data[0] << 8 | data[1]) % 31))
8773
+ ? inflate(data, opts, cb)
8774
+ : unzlib(data, opts, cb);
8775
+ }
8776
+ /**
8777
+ * Expands compressed GZIP, Zlib, or raw DEFLATE data, automatically detecting the format
8778
+ * @param data The data to decompress
8779
+ * @param out Where to write the data. Saves memory if you know the decompressed size and provide an output buffer of that length.
8780
+ * @returns The decompressed version of the data
8781
+ */
8782
+ function decompressSync(data, out) {
8783
+ return (data[0] == 31 && data[1] == 139 && data[2] == 8)
8784
+ ? gunzipSync$1(data, out)
8785
+ : ((data[0] & 15) != 8 || (data[0] >> 4) > 7 || ((data[0] << 8 | data[1]) % 31))
8786
+ ? inflateSync(data, out)
8787
+ : unzlibSync(data, out);
8788
+ }
8789
+ // flatten a directory structure
8790
+ var fltn = function (d, p, t, o) {
8791
+ for (var k in d) {
8792
+ var val = d[k], n = p + k, op = o;
8793
+ if (Array.isArray(val))
8794
+ op = mrg(o, val[1]), val = val[0];
8795
+ if (val instanceof u8)
8796
+ t[n] = [val, op];
8797
+ else {
8798
+ t[n += '/'] = [new u8(0), op];
8799
+ fltn(val, n, t, o);
8800
+ }
8801
+ }
8802
+ };
8803
+ // text encoder
8804
+ var te = typeof TextEncoder != 'undefined' && /*#__PURE__*/ new TextEncoder();
8805
+ // text decoder
8806
+ var td = typeof TextDecoder != 'undefined' && /*#__PURE__*/ new TextDecoder();
8807
+ // text decoder stream
8808
+ var tds = 0;
8809
+ try {
8810
+ td.decode(et, { stream: true });
8811
+ tds = 1;
8812
+ }
8813
+ catch (e) { }
8814
+ // decode UTF8
8815
+ var dutf8 = function (d) {
8816
+ for (var r = '', i = 0;;) {
8817
+ var c = d[i++];
8818
+ var eb = (c > 127) + (c > 223) + (c > 239);
8819
+ if (i + eb > d.length)
8820
+ return [r, slc(d, i - 1)];
8821
+ if (!eb)
8822
+ r += String.fromCharCode(c);
8823
+ else if (eb == 3) {
8824
+ c = ((c & 15) << 18 | (d[i++] & 63) << 12 | (d[i++] & 63) << 6 | (d[i++] & 63)) - 65536,
8825
+ r += String.fromCharCode(55296 | (c >> 10), 56320 | (c & 1023));
8826
+ }
8827
+ else if (eb & 1)
8828
+ r += String.fromCharCode((c & 31) << 6 | (d[i++] & 63));
8829
+ else
8830
+ r += String.fromCharCode((c & 15) << 12 | (d[i++] & 63) << 6 | (d[i++] & 63));
8831
+ }
8832
+ };
8833
+ /**
8834
+ * Streaming UTF-8 decoding
8835
+ */
8836
+ var DecodeUTF8 = /*#__PURE__*/ (function () {
8837
+ /**
8838
+ * Creates a UTF-8 decoding stream
8839
+ * @param cb The callback to call whenever data is decoded
8840
+ */
8841
+ function DecodeUTF8(cb) {
8842
+ this.ondata = cb;
8843
+ if (tds)
8844
+ this.t = new TextDecoder();
8845
+ else
8846
+ this.p = et;
8847
+ }
8848
+ /**
8849
+ * Pushes a chunk to be decoded from UTF-8 binary
8850
+ * @param chunk The chunk to push
8851
+ * @param final Whether this is the last chunk
8852
+ */
8853
+ DecodeUTF8.prototype.push = function (chunk, final) {
8854
+ if (!this.ondata)
8855
+ err(5);
8856
+ final = !!final;
8857
+ if (this.t) {
8858
+ this.ondata(this.t.decode(chunk, { stream: true }), final);
8859
+ if (final) {
8860
+ if (this.t.decode().length)
8861
+ err(8);
8862
+ this.t = null;
8863
+ }
8864
+ return;
8865
+ }
8866
+ if (!this.p)
8867
+ err(4);
8868
+ var dat = new u8(this.p.length + chunk.length);
8869
+ dat.set(this.p);
8870
+ dat.set(chunk, this.p.length);
8871
+ var _a = dutf8(dat), ch = _a[0], np = _a[1];
8872
+ if (final) {
8873
+ if (np.length)
8874
+ err(8);
8875
+ this.p = null;
8876
+ }
8877
+ else
8878
+ this.p = np;
8879
+ this.ondata(ch, final);
8880
+ };
8881
+ return DecodeUTF8;
8882
+ }());
8883
+ /**
8884
+ * Streaming UTF-8 encoding
8885
+ */
8886
+ var EncodeUTF8 = /*#__PURE__*/ (function () {
8887
+ /**
8888
+ * Creates a UTF-8 decoding stream
8889
+ * @param cb The callback to call whenever data is encoded
8890
+ */
8891
+ function EncodeUTF8(cb) {
8892
+ this.ondata = cb;
8893
+ }
8894
+ /**
8895
+ * Pushes a chunk to be encoded to UTF-8
8896
+ * @param chunk The string data to push
8897
+ * @param final Whether this is the last chunk
8898
+ */
8899
+ EncodeUTF8.prototype.push = function (chunk, final) {
8900
+ if (!this.ondata)
8901
+ err(5);
8902
+ if (this.d)
8903
+ err(4);
8904
+ this.ondata(strToU8(chunk), this.d = final || false);
8905
+ };
8906
+ return EncodeUTF8;
8907
+ }());
8908
+ /**
8909
+ * Converts a string into a Uint8Array for use with compression/decompression methods
8910
+ * @param str The string to encode
8911
+ * @param latin1 Whether or not to interpret the data as Latin-1. This should
8912
+ * not need to be true unless decoding a binary string.
8913
+ * @returns The string encoded in UTF-8/Latin-1 binary
8914
+ */
8915
+ function strToU8(str, latin1) {
8916
+ if (latin1) {
8917
+ var ar_1 = new u8(str.length);
8918
+ for (var i = 0; i < str.length; ++i)
8919
+ ar_1[i] = str.charCodeAt(i);
8920
+ return ar_1;
8921
+ }
8922
+ if (te)
8923
+ return te.encode(str);
8924
+ var l = str.length;
8925
+ var ar = new u8(str.length + (str.length >> 1));
8926
+ var ai = 0;
8927
+ var w = function (v) { ar[ai++] = v; };
8928
+ for (var i = 0; i < l; ++i) {
8929
+ if (ai + 5 > ar.length) {
8930
+ var n = new u8(ai + 8 + ((l - i) << 1));
8931
+ n.set(ar);
8932
+ ar = n;
8933
+ }
8934
+ var c = str.charCodeAt(i);
8935
+ if (c < 128 || latin1)
8936
+ w(c);
8937
+ else if (c < 2048)
8938
+ w(192 | (c >> 6)), w(128 | (c & 63));
8939
+ else if (c > 55295 && c < 57344)
8940
+ c = 65536 + (c & 1023 << 10) | (str.charCodeAt(++i) & 1023),
8941
+ w(240 | (c >> 18)), w(128 | ((c >> 12) & 63)), w(128 | ((c >> 6) & 63)), w(128 | (c & 63));
8942
+ else
8943
+ w(224 | (c >> 12)), w(128 | ((c >> 6) & 63)), w(128 | (c & 63));
8944
+ }
8945
+ return slc(ar, 0, ai);
8946
+ }
8947
+ /**
8948
+ * Converts a Uint8Array to a string
8949
+ * @param dat The data to decode to string
8950
+ * @param latin1 Whether or not to interpret the data as Latin-1. This should
8951
+ * not need to be true unless encoding to binary string.
8952
+ * @returns The original UTF-8/Latin-1 string
8953
+ */
8954
+ function strFromU8(dat, latin1) {
8955
+ if (latin1) {
8956
+ var r = '';
8957
+ for (var i = 0; i < dat.length; i += 16384)
8958
+ r += String.fromCharCode.apply(null, dat.subarray(i, i + 16384));
8959
+ return r;
8960
+ }
8961
+ else if (td)
8962
+ return td.decode(dat);
8963
+ else {
8964
+ var _a = dutf8(dat), out = _a[0], ext = _a[1];
8965
+ if (ext.length)
8966
+ err(8);
8967
+ return out;
8968
+ }
8969
+ }
8970
+ ;
8971
+ // deflate bit flag
8972
+ var dbf = function (l) { return l == 1 ? 3 : l < 6 ? 2 : l == 9 ? 1 : 0; };
8973
+ // skip local zip header
8974
+ var slzh = function (d, b) { return b + 30 + b2(d, b + 26) + b2(d, b + 28); };
8975
+ // read zip header
8976
+ var zh = function (d, b, z) {
8977
+ var fnl = b2(d, b + 28), fn = strFromU8(d.subarray(b + 46, b + 46 + fnl), !(b2(d, b + 8) & 2048)), es = b + 46 + fnl, bs = b4(d, b + 20);
8978
+ var _a = z && bs == 4294967295 ? z64e(d, es) : [bs, b4(d, b + 24), b4(d, b + 42)], sc = _a[0], su = _a[1], off = _a[2];
8979
+ return [b2(d, b + 10), sc, su, fn, es + b2(d, b + 30) + b2(d, b + 32), off];
8980
+ };
8981
+ // read zip64 extra field
8982
+ var z64e = function (d, b) {
8983
+ for (; b2(d, b) != 1; b += 4 + b2(d, b + 2))
8984
+ ;
8985
+ return [b8(d, b + 12), b8(d, b + 4), b8(d, b + 20)];
8986
+ };
8987
+ // extra field length
8988
+ var exfl = function (ex) {
8989
+ var le = 0;
8990
+ if (ex) {
8991
+ for (var k in ex) {
8992
+ var l = ex[k].length;
8993
+ if (l > 65535)
8994
+ err(9);
8995
+ le += l + 4;
8996
+ }
8997
+ }
8998
+ return le;
8999
+ };
9000
+ // write zip header
9001
+ var wzh = function (d, b, f, fn, u, c, ce, co) {
9002
+ var fl = fn.length, ex = f.extra, col = co && co.length;
9003
+ var exl = exfl(ex);
9004
+ wbytes(d, b, ce != null ? 0x2014B50 : 0x4034B50), b += 4;
9005
+ if (ce != null)
9006
+ d[b++] = 20, d[b++] = f.os;
9007
+ d[b] = 20, b += 2; // spec compliance? what's that?
9008
+ d[b++] = (f.flag << 1) | (c < 0 && 8), d[b++] = u && 8;
9009
+ d[b++] = f.compression & 255, d[b++] = f.compression >> 8;
9010
+ var dt = new Date(f.mtime == null ? Date.now() : f.mtime), y = dt.getFullYear() - 1980;
9011
+ if (y < 0 || y > 119)
9012
+ err(10);
9013
+ wbytes(d, b, (y << 25) | ((dt.getMonth() + 1) << 21) | (dt.getDate() << 16) | (dt.getHours() << 11) | (dt.getMinutes() << 5) | (dt.getSeconds() >>> 1)), b += 4;
9014
+ if (c != -1) {
9015
+ wbytes(d, b, f.crc);
9016
+ wbytes(d, b + 4, c < 0 ? -c - 2 : c);
9017
+ wbytes(d, b + 8, f.size);
9018
+ }
9019
+ wbytes(d, b + 12, fl);
9020
+ wbytes(d, b + 14, exl), b += 16;
9021
+ if (ce != null) {
9022
+ wbytes(d, b, col);
9023
+ wbytes(d, b + 6, f.attrs);
9024
+ wbytes(d, b + 10, ce), b += 14;
9025
+ }
9026
+ d.set(fn, b);
9027
+ b += fl;
9028
+ if (exl) {
9029
+ for (var k in ex) {
9030
+ var exf = ex[k], l = exf.length;
9031
+ wbytes(d, b, +k);
9032
+ wbytes(d, b + 2, l);
9033
+ d.set(exf, b + 4), b += 4 + l;
9034
+ }
9035
+ }
9036
+ if (col)
9037
+ d.set(co, b), b += col;
9038
+ return b;
9039
+ };
9040
+ // write zip footer (end of central directory)
9041
+ var wzf = function (o, b, c, d, e) {
9042
+ wbytes(o, b, 0x6054B50); // skip disk
9043
+ wbytes(o, b + 8, c);
9044
+ wbytes(o, b + 10, c);
9045
+ wbytes(o, b + 12, d);
9046
+ wbytes(o, b + 16, e);
9047
+ };
9048
+ /**
9049
+ * A pass-through stream to keep data uncompressed in a ZIP archive.
9050
+ */
9051
+ var ZipPassThrough = /*#__PURE__*/ (function () {
9052
+ /**
9053
+ * Creates a pass-through stream that can be added to ZIP archives
9054
+ * @param filename The filename to associate with this data stream
9055
+ */
9056
+ function ZipPassThrough(filename) {
9057
+ this.filename = filename;
9058
+ this.c = crc();
9059
+ this.size = 0;
9060
+ this.compression = 0;
9061
+ }
9062
+ /**
9063
+ * Processes a chunk and pushes to the output stream. You can override this
9064
+ * method in a subclass for custom behavior, but by default this passes
9065
+ * the data through. You must call this.ondata(err, chunk, final) at some
9066
+ * point in this method.
9067
+ * @param chunk The chunk to process
9068
+ * @param final Whether this is the last chunk
9069
+ */
9070
+ ZipPassThrough.prototype.process = function (chunk, final) {
9071
+ this.ondata(null, chunk, final);
9072
+ };
9073
+ /**
9074
+ * Pushes a chunk to be added. If you are subclassing this with a custom
9075
+ * compression algorithm, note that you must push data from the source
9076
+ * file only, pre-compression.
9077
+ * @param chunk The chunk to push
9078
+ * @param final Whether this is the last chunk
9079
+ */
9080
+ ZipPassThrough.prototype.push = function (chunk, final) {
9081
+ if (!this.ondata)
9082
+ err(5);
9083
+ this.c.p(chunk);
9084
+ this.size += chunk.length;
9085
+ if (final)
9086
+ this.crc = this.c.d();
9087
+ this.process(chunk, final || false);
9088
+ };
9089
+ return ZipPassThrough;
9090
+ }());
9091
+ // I don't extend because TypeScript extension adds 1kB of runtime bloat
9092
+ /**
9093
+ * Streaming DEFLATE compression for ZIP archives. Prefer using AsyncZipDeflate
9094
+ * for better performance
9095
+ */
9096
+ var ZipDeflate = /*#__PURE__*/ (function () {
9097
+ /**
9098
+ * Creates a DEFLATE stream that can be added to ZIP archives
9099
+ * @param filename The filename to associate with this data stream
9100
+ * @param opts The compression options
9101
+ */
9102
+ function ZipDeflate(filename, opts) {
9103
+ var _this_1 = this;
9104
+ if (!opts)
9105
+ opts = {};
9106
+ ZipPassThrough.call(this, filename);
9107
+ this.d = new Deflate(opts, function (dat, final) {
9108
+ _this_1.ondata(null, dat, final);
9109
+ });
9110
+ this.compression = 8;
9111
+ this.flag = dbf(opts.level);
9112
+ }
9113
+ ZipDeflate.prototype.process = function (chunk, final) {
9114
+ try {
9115
+ this.d.push(chunk, final);
9116
+ }
9117
+ catch (e) {
9118
+ this.ondata(e, null, final);
9119
+ }
9120
+ };
9121
+ /**
9122
+ * Pushes a chunk to be deflated
9123
+ * @param chunk The chunk to push
9124
+ * @param final Whether this is the last chunk
9125
+ */
9126
+ ZipDeflate.prototype.push = function (chunk, final) {
9127
+ ZipPassThrough.prototype.push.call(this, chunk, final);
9128
+ };
9129
+ return ZipDeflate;
9130
+ }());
9131
+ /**
9132
+ * Asynchronous streaming DEFLATE compression for ZIP archives
9133
+ */
9134
+ var AsyncZipDeflate = /*#__PURE__*/ (function () {
9135
+ /**
9136
+ * Creates a DEFLATE stream that can be added to ZIP archives
9137
+ * @param filename The filename to associate with this data stream
9138
+ * @param opts The compression options
9139
+ */
9140
+ function AsyncZipDeflate(filename, opts) {
9141
+ var _this_1 = this;
9142
+ if (!opts)
9143
+ opts = {};
9144
+ ZipPassThrough.call(this, filename);
9145
+ this.d = new AsyncDeflate(opts, function (err, dat, final) {
9146
+ _this_1.ondata(err, dat, final);
9147
+ });
9148
+ this.compression = 8;
9149
+ this.flag = dbf(opts.level);
9150
+ this.terminate = this.d.terminate;
9151
+ }
9152
+ AsyncZipDeflate.prototype.process = function (chunk, final) {
9153
+ this.d.push(chunk, final);
9154
+ };
9155
+ /**
9156
+ * Pushes a chunk to be deflated
9157
+ * @param chunk The chunk to push
9158
+ * @param final Whether this is the last chunk
9159
+ */
9160
+ AsyncZipDeflate.prototype.push = function (chunk, final) {
9161
+ ZipPassThrough.prototype.push.call(this, chunk, final);
9162
+ };
9163
+ return AsyncZipDeflate;
9164
+ }());
9165
+ // TODO: Better tree shaking
9166
+ /**
9167
+ * A zippable archive to which files can incrementally be added
9168
+ */
9169
+ var Zip$1 = /*#__PURE__*/ (function () {
9170
+ /**
9171
+ * Creates an empty ZIP archive to which files can be added
9172
+ * @param cb The callback to call whenever data for the generated ZIP archive
9173
+ * is available
9174
+ */
9175
+ function Zip(cb) {
9176
+ this.ondata = cb;
9177
+ this.u = [];
9178
+ this.d = 1;
9179
+ }
9180
+ /**
9181
+ * Adds a file to the ZIP archive
9182
+ * @param file The file stream to add
9183
+ */
9184
+ Zip.prototype.add = function (file) {
9185
+ var _this_1 = this;
9186
+ if (!this.ondata)
9187
+ err(5);
9188
+ // finishing or finished
9189
+ if (this.d & 2)
9190
+ this.ondata(err(4 + (this.d & 1) * 8, 0, 1), null, false);
9191
+ else {
9192
+ var f = strToU8(file.filename), fl_1 = f.length;
9193
+ var com = file.comment, o = com && strToU8(com);
9194
+ var u = fl_1 != file.filename.length || (o && (com.length != o.length));
9195
+ var hl_1 = fl_1 + exfl(file.extra) + 30;
9196
+ if (fl_1 > 65535)
9197
+ this.ondata(err(11, 0, 1), null, false);
9198
+ var header = new u8(hl_1);
9199
+ wzh(header, 0, file, f, u, -1);
9200
+ var chks_1 = [header];
9201
+ var pAll_1 = function () {
9202
+ for (var _i = 0, chks_2 = chks_1; _i < chks_2.length; _i++) {
9203
+ var chk = chks_2[_i];
9204
+ _this_1.ondata(null, chk, false);
9205
+ }
9206
+ chks_1 = [];
9207
+ };
9208
+ var tr_1 = this.d;
9209
+ this.d = 0;
9210
+ var ind_1 = this.u.length;
9211
+ var uf_1 = mrg(file, {
9212
+ f: f,
9213
+ u: u,
9214
+ o: o,
9215
+ t: function () {
9216
+ if (file.terminate)
9217
+ file.terminate();
9218
+ },
9219
+ r: function () {
9220
+ pAll_1();
9221
+ if (tr_1) {
9222
+ var nxt = _this_1.u[ind_1 + 1];
9223
+ if (nxt)
9224
+ nxt.r();
9225
+ else
9226
+ _this_1.d = 1;
9227
+ }
9228
+ tr_1 = 1;
9229
+ }
9230
+ });
9231
+ var cl_1 = 0;
9232
+ file.ondata = function (err, dat, final) {
9233
+ if (err) {
9234
+ _this_1.ondata(err, dat, final);
9235
+ _this_1.terminate();
9236
+ }
9237
+ else {
9238
+ cl_1 += dat.length;
9239
+ chks_1.push(dat);
9240
+ if (final) {
9241
+ var dd = new u8(16);
9242
+ wbytes(dd, 0, 0x8074B50);
9243
+ wbytes(dd, 4, file.crc);
9244
+ wbytes(dd, 8, cl_1);
9245
+ wbytes(dd, 12, file.size);
9246
+ chks_1.push(dd);
9247
+ uf_1.c = cl_1, uf_1.b = hl_1 + cl_1 + 16, uf_1.crc = file.crc, uf_1.size = file.size;
9248
+ if (tr_1)
9249
+ uf_1.r();
9250
+ tr_1 = 1;
9251
+ }
9252
+ else if (tr_1)
9253
+ pAll_1();
9254
+ }
9255
+ };
9256
+ this.u.push(uf_1);
9257
+ }
9258
+ };
9259
+ /**
9260
+ * Ends the process of adding files and prepares to emit the final chunks.
9261
+ * This *must* be called after adding all desired files for the resulting
9262
+ * ZIP file to work properly.
9263
+ */
9264
+ Zip.prototype.end = function () {
9265
+ var _this_1 = this;
9266
+ if (this.d & 2) {
9267
+ this.ondata(err(4 + (this.d & 1) * 8, 0, 1), null, true);
9268
+ return;
9269
+ }
9270
+ if (this.d)
9271
+ this.e();
9272
+ else
9273
+ this.u.push({
9274
+ r: function () {
9275
+ if (!(_this_1.d & 1))
9276
+ return;
9277
+ _this_1.u.splice(-1, 1);
9278
+ _this_1.e();
9279
+ },
9280
+ t: function () { }
9281
+ });
9282
+ this.d = 3;
9283
+ };
9284
+ Zip.prototype.e = function () {
9285
+ var bt = 0, l = 0, tl = 0;
9286
+ for (var _i = 0, _a = this.u; _i < _a.length; _i++) {
9287
+ var f = _a[_i];
9288
+ tl += 46 + f.f.length + exfl(f.extra) + (f.o ? f.o.length : 0);
9289
+ }
9290
+ var out = new u8(tl + 22);
9291
+ for (var _b = 0, _c = this.u; _b < _c.length; _b++) {
9292
+ var f = _c[_b];
9293
+ wzh(out, bt, f, f.f, f.u, -f.c - 2, l, f.o);
9294
+ bt += 46 + f.f.length + exfl(f.extra) + (f.o ? f.o.length : 0), l += f.b;
9295
+ }
9296
+ wzf(out, bt, this.u.length, tl, l);
9297
+ this.ondata(null, out, true);
9298
+ this.d = 2;
9299
+ };
9300
+ /**
9301
+ * A method to terminate any internal workers used by the stream. Subsequent
9302
+ * calls to add() will fail.
9303
+ */
9304
+ Zip.prototype.terminate = function () {
9305
+ for (var _i = 0, _a = this.u; _i < _a.length; _i++) {
9306
+ var f = _a[_i];
9307
+ f.t();
9308
+ }
9309
+ this.d = 2;
9310
+ };
9311
+ return Zip;
9312
+ }());
9313
+ function zip(data, opts, cb) {
9314
+ if (!cb)
9315
+ cb = opts, opts = {};
9316
+ if (typeof cb != 'function')
9317
+ err(7);
9318
+ var r = {};
9319
+ fltn(data, '', r, opts);
9320
+ var k = Object.keys(r);
9321
+ var lft = k.length, o = 0, tot = 0;
9322
+ var slft = lft, files = new Array(lft);
9323
+ var term = [];
9324
+ var tAll = function () {
9325
+ for (var i = 0; i < term.length; ++i)
9326
+ term[i]();
9327
+ };
9328
+ var cbd = function (a, b) {
9329
+ mt(function () { cb(a, b); });
9330
+ };
9331
+ mt(function () { cbd = cb; });
9332
+ var cbf = function () {
9333
+ var out = new u8(tot + 22), oe = o, cdl = tot - o;
9334
+ tot = 0;
9335
+ for (var i = 0; i < slft; ++i) {
9336
+ var f = files[i];
9337
+ try {
9338
+ var l = f.c.length;
9339
+ wzh(out, tot, f, f.f, f.u, l);
9340
+ var badd = 30 + f.f.length + exfl(f.extra);
9341
+ var loc = tot + badd;
9342
+ out.set(f.c, loc);
9343
+ wzh(out, o, f, f.f, f.u, l, tot, f.m), o += 16 + badd + (f.m ? f.m.length : 0), tot = loc + l;
9344
+ }
9345
+ catch (e) {
9346
+ return cbd(e, null);
9347
+ }
9348
+ }
9349
+ wzf(out, o, files.length, cdl, oe);
9350
+ cbd(null, out);
9351
+ };
9352
+ if (!lft)
9353
+ cbf();
9354
+ var _loop_1 = function (i) {
9355
+ var fn = k[i];
9356
+ var _a = r[fn], file = _a[0], p = _a[1];
9357
+ var c = crc(), size = file.length;
9358
+ c.p(file);
9359
+ var f = strToU8(fn), s = f.length;
9360
+ var com = p.comment, m = com && strToU8(com), ms = m && m.length;
9361
+ var exl = exfl(p.extra);
9362
+ var compression = p.level == 0 ? 0 : 8;
9363
+ var cbl = function (e, d) {
9364
+ if (e) {
9365
+ tAll();
9366
+ cbd(e, null);
9367
+ }
9368
+ else {
9369
+ var l = d.length;
9370
+ files[i] = mrg(p, {
9371
+ size: size,
9372
+ crc: c.d(),
9373
+ c: d,
9374
+ f: f,
9375
+ m: m,
9376
+ u: s != fn.length || (m && (com.length != ms)),
9377
+ compression: compression
9378
+ });
9379
+ o += 30 + s + exl + l;
9380
+ tot += 76 + 2 * (s + exl) + (ms || 0) + l;
9381
+ if (!--lft)
9382
+ cbf();
9383
+ }
9384
+ };
9385
+ if (s > 65535)
9386
+ cbl(err(11, 0, 1), null);
9387
+ if (!compression)
9388
+ cbl(null, file);
9389
+ else if (size < 160000) {
9390
+ try {
9391
+ cbl(null, deflateSync(file, p));
9392
+ }
9393
+ catch (e) {
9394
+ cbl(e, null);
9395
+ }
9396
+ }
9397
+ else
9398
+ term.push(deflate(file, p, cbl));
9399
+ };
9400
+ // Cannot use lft because it can decrease
9401
+ for (var i = 0; i < slft; ++i) {
9402
+ _loop_1(i);
9403
+ }
9404
+ return tAll;
9405
+ }
9406
+ /**
9407
+ * Synchronously creates a ZIP file. Prefer using `zip` for better performance
9408
+ * with more than one file.
9409
+ * @param data The directory structure for the ZIP archive
9410
+ * @param opts The main options, merged with per-file options
9411
+ * @returns The generated ZIP archive
9412
+ */
9413
+ function zipSync$1(data, opts) {
9414
+ if (!opts)
9415
+ opts = {};
9416
+ var r = {};
9417
+ var files = [];
9418
+ fltn(data, '', r, opts);
9419
+ var o = 0;
9420
+ var tot = 0;
9421
+ for (var fn in r) {
9422
+ var _a = r[fn], file = _a[0], p = _a[1];
9423
+ var compression = p.level == 0 ? 0 : 8;
9424
+ var f = strToU8(fn), s = f.length;
9425
+ var com = p.comment, m = com && strToU8(com), ms = m && m.length;
9426
+ var exl = exfl(p.extra);
9427
+ if (s > 65535)
9428
+ err(11);
9429
+ var d = compression ? deflateSync(file, p) : file, l = d.length;
9430
+ var c = crc();
9431
+ c.p(file);
9432
+ files.push(mrg(p, {
9433
+ size: file.length,
9434
+ crc: c.d(),
9435
+ c: d,
9436
+ f: f,
9437
+ m: m,
9438
+ u: s != fn.length || (m && (com.length != ms)),
9439
+ o: o,
9440
+ compression: compression
9441
+ }));
9442
+ o += 30 + s + exl + l;
9443
+ tot += 76 + 2 * (s + exl) + (ms || 0) + l;
9444
+ }
9445
+ var out = new u8(tot + 22), oe = o, cdl = tot - o;
9446
+ for (var i = 0; i < files.length; ++i) {
9447
+ var f = files[i];
9448
+ wzh(out, f.o, f, f.f, f.u, f.c.length);
9449
+ var badd = 30 + f.f.length + exfl(f.extra);
9450
+ out.set(f.c, f.o + badd);
9451
+ wzh(out, o, f, f.f, f.u, f.c.length, f.o, f.m), o += 16 + badd + (f.m ? f.m.length : 0);
9452
+ }
9453
+ wzf(out, o, files.length, cdl, oe);
9454
+ return out;
9455
+ }
9456
+ /**
9457
+ * Streaming pass-through decompression for ZIP archives
9458
+ */
9459
+ var UnzipPassThrough = /*#__PURE__*/ (function () {
9460
+ function UnzipPassThrough() {
9461
+ }
9462
+ UnzipPassThrough.prototype.push = function (data, final) {
9463
+ this.ondata(null, data, final);
9464
+ };
9465
+ UnzipPassThrough.compression = 0;
9466
+ return UnzipPassThrough;
9467
+ }());
9468
+ /**
9469
+ * Streaming DEFLATE decompression for ZIP archives. Prefer AsyncZipInflate for
9470
+ * better performance.
9471
+ */
9472
+ var UnzipInflate = /*#__PURE__*/ (function () {
9473
+ /**
9474
+ * Creates a DEFLATE decompression that can be used in ZIP archives
9475
+ */
9476
+ function UnzipInflate() {
9477
+ var _this_1 = this;
9478
+ this.i = new Inflate(function (dat, final) {
9479
+ _this_1.ondata(null, dat, final);
9480
+ });
9481
+ }
9482
+ UnzipInflate.prototype.push = function (data, final) {
9483
+ try {
9484
+ this.i.push(data, final);
9485
+ }
9486
+ catch (e) {
9487
+ this.ondata(e, null, final);
9488
+ }
9489
+ };
9490
+ UnzipInflate.compression = 8;
9491
+ return UnzipInflate;
9492
+ }());
9493
+ /**
9494
+ * Asynchronous streaming DEFLATE decompression for ZIP archives
9495
+ */
9496
+ var AsyncUnzipInflate = /*#__PURE__*/ (function () {
9497
+ /**
9498
+ * Creates a DEFLATE decompression that can be used in ZIP archives
9499
+ */
9500
+ function AsyncUnzipInflate(_, sz) {
9501
+ var _this_1 = this;
9502
+ if (sz < 320000) {
9503
+ this.i = new Inflate(function (dat, final) {
9504
+ _this_1.ondata(null, dat, final);
9505
+ });
9506
+ }
9507
+ else {
9508
+ this.i = new AsyncInflate(function (err, dat, final) {
9509
+ _this_1.ondata(err, dat, final);
9510
+ });
9511
+ this.terminate = this.i.terminate;
9512
+ }
9513
+ }
9514
+ AsyncUnzipInflate.prototype.push = function (data, final) {
9515
+ if (this.i.terminate)
9516
+ data = slc(data, 0);
9517
+ this.i.push(data, final);
9518
+ };
9519
+ AsyncUnzipInflate.compression = 8;
9520
+ return AsyncUnzipInflate;
9521
+ }());
9522
+ /**
9523
+ * A ZIP archive decompression stream that emits files as they are discovered
9524
+ */
9525
+ var Unzip = /*#__PURE__*/ (function () {
9526
+ /**
9527
+ * Creates a ZIP decompression stream
9528
+ * @param cb The callback to call whenever a file in the ZIP archive is found
9529
+ */
9530
+ function Unzip(cb) {
9531
+ this.onfile = cb;
9532
+ this.k = [];
9533
+ this.o = {
9534
+ 0: UnzipPassThrough
9535
+ };
9536
+ this.p = et;
9537
+ }
9538
+ /**
9539
+ * Pushes a chunk to be unzipped
9540
+ * @param chunk The chunk to push
9541
+ * @param final Whether this is the last chunk
9542
+ */
9543
+ Unzip.prototype.push = function (chunk, final) {
9544
+ var _this_1 = this;
9545
+ if (!this.onfile)
9546
+ err(5);
9547
+ if (!this.p)
9548
+ err(4);
9549
+ if (this.c > 0) {
9550
+ var len = Math.min(this.c, chunk.length);
9551
+ var toAdd = chunk.subarray(0, len);
9552
+ this.c -= len;
9553
+ if (this.d)
9554
+ this.d.push(toAdd, !this.c);
9555
+ else
9556
+ this.k[0].push(toAdd);
9557
+ chunk = chunk.subarray(len);
9558
+ if (chunk.length)
9559
+ return this.push(chunk, final);
9560
+ }
9561
+ else {
9562
+ var f = 0, i = 0, is = void 0, buf = void 0;
9563
+ if (!this.p.length)
9564
+ buf = chunk;
9565
+ else if (!chunk.length)
9566
+ buf = this.p;
9567
+ else {
9568
+ buf = new u8(this.p.length + chunk.length);
9569
+ buf.set(this.p), buf.set(chunk, this.p.length);
9570
+ }
9571
+ var l = buf.length, oc = this.c, add = oc && this.d;
9572
+ var _loop_2 = function () {
9573
+ var _a;
9574
+ var sig = b4(buf, i);
9575
+ if (sig == 0x4034B50) {
9576
+ f = 1, is = i;
9577
+ this_1.d = null;
9578
+ this_1.c = 0;
9579
+ var bf = b2(buf, i + 6), cmp_1 = b2(buf, i + 8), u = bf & 2048, dd = bf & 8, fnl = b2(buf, i + 26), es = b2(buf, i + 28);
9580
+ if (l > i + 30 + fnl + es) {
9581
+ var chks_3 = [];
9582
+ this_1.k.unshift(chks_3);
9583
+ f = 2;
9584
+ var sc_1 = b4(buf, i + 18), su_1 = b4(buf, i + 22);
9585
+ var fn_1 = strFromU8(buf.subarray(i + 30, i += 30 + fnl), !u);
9586
+ if (sc_1 == 4294967295) {
9587
+ _a = dd ? [-2] : z64e(buf, i), sc_1 = _a[0], su_1 = _a[1];
9588
+ }
9589
+ else if (dd)
9590
+ sc_1 = -1;
9591
+ i += es;
9592
+ this_1.c = sc_1;
9593
+ var d_1;
9594
+ var file_1 = {
9595
+ name: fn_1,
9596
+ compression: cmp_1,
9597
+ start: function () {
9598
+ if (!file_1.ondata)
9599
+ err(5);
9600
+ if (!sc_1)
9601
+ file_1.ondata(null, et, true);
9602
+ else {
9603
+ var ctr = _this_1.o[cmp_1];
9604
+ if (!ctr)
9605
+ file_1.ondata(err(14, 'unknown compression type ' + cmp_1, 1), null, false);
9606
+ d_1 = sc_1 < 0 ? new ctr(fn_1) : new ctr(fn_1, sc_1, su_1);
9607
+ d_1.ondata = function (err, dat, final) { file_1.ondata(err, dat, final); };
9608
+ for (var _i = 0, chks_4 = chks_3; _i < chks_4.length; _i++) {
9609
+ var dat = chks_4[_i];
9610
+ d_1.push(dat, false);
9611
+ }
9612
+ if (_this_1.k[0] == chks_3 && _this_1.c)
9613
+ _this_1.d = d_1;
9614
+ else
9615
+ d_1.push(et, true);
9616
+ }
9617
+ },
9618
+ terminate: function () {
9619
+ if (d_1 && d_1.terminate)
9620
+ d_1.terminate();
9621
+ }
9622
+ };
9623
+ if (sc_1 >= 0)
9624
+ file_1.size = sc_1, file_1.originalSize = su_1;
9625
+ this_1.onfile(file_1);
9626
+ }
9627
+ return "break";
9628
+ }
9629
+ else if (oc) {
9630
+ if (sig == 0x8074B50) {
9631
+ is = i += 12 + (oc == -2 && 8), f = 3, this_1.c = 0;
9632
+ return "break";
9633
+ }
9634
+ else if (sig == 0x2014B50) {
9635
+ is = i -= 4, f = 3, this_1.c = 0;
9636
+ return "break";
9637
+ }
9638
+ }
9639
+ };
9640
+ var this_1 = this;
9641
+ for (; i < l - 4; ++i) {
9642
+ var state_1 = _loop_2();
9643
+ if (state_1 === "break")
9644
+ break;
9645
+ }
9646
+ this.p = et;
9647
+ if (oc < 0) {
9648
+ var dat = f ? buf.subarray(0, is - 12 - (oc == -2 && 8) - (b4(buf, is - 16) == 0x8074B50 && 4)) : buf.subarray(0, i);
9649
+ if (add)
9650
+ add.push(dat, !!f);
9651
+ else
9652
+ this.k[+(f == 2)].push(dat);
9653
+ }
9654
+ if (f & 2)
9655
+ return this.push(buf.subarray(i), final);
9656
+ this.p = buf.subarray(i);
9657
+ }
9658
+ if (final) {
9659
+ if (this.c)
9660
+ err(13);
9661
+ this.p = null;
9662
+ }
9663
+ };
9664
+ /**
9665
+ * Registers a decoder with the stream, allowing for files compressed with
9666
+ * the compression type provided to be expanded correctly
9667
+ * @param decoder The decoder constructor
9668
+ */
9669
+ Unzip.prototype.register = function (decoder) {
9670
+ this.o[decoder.compression] = decoder;
9671
+ };
9672
+ return Unzip;
9673
+ }());
9674
+ var mt = typeof queueMicrotask == 'function' ? queueMicrotask : typeof setTimeout == 'function' ? setTimeout : function (fn) { fn(); };
9675
+ function unzip(data, opts, cb) {
9676
+ if (!cb)
9677
+ cb = opts, opts = {};
9678
+ if (typeof cb != 'function')
9679
+ err(7);
9680
+ var term = [];
9681
+ var tAll = function () {
9682
+ for (var i = 0; i < term.length; ++i)
9683
+ term[i]();
9684
+ };
9685
+ var files = {};
9686
+ var cbd = function (a, b) {
9687
+ mt(function () { cb(a, b); });
9688
+ };
9689
+ mt(function () { cbd = cb; });
9690
+ var e = data.length - 22;
9691
+ for (; b4(data, e) != 0x6054B50; --e) {
9692
+ if (!e || data.length - e > 65558) {
9693
+ cbd(err(13, 0, 1), null);
9694
+ return tAll;
9695
+ }
9696
+ }
9697
+ ;
9698
+ var lft = b2(data, e + 8);
9699
+ if (lft) {
9700
+ var c = lft;
9701
+ var o = b4(data, e + 16);
9702
+ var z = o == 4294967295 || c == 65535;
9703
+ if (z) {
9704
+ var ze = b4(data, e - 12);
9705
+ z = b4(data, ze) == 0x6064B50;
9706
+ if (z) {
9707
+ c = lft = b4(data, ze + 32);
9708
+ o = b4(data, ze + 48);
9709
+ }
9710
+ }
9711
+ var fltr = opts && opts.filter;
9712
+ var _loop_3 = function (i) {
9713
+ var _a = zh(data, o, z), c_1 = _a[0], sc = _a[1], su = _a[2], fn = _a[3], no = _a[4], off = _a[5], b = slzh(data, off);
9714
+ o = no;
9715
+ var cbl = function (e, d) {
9716
+ if (e) {
9717
+ tAll();
9718
+ cbd(e, null);
9719
+ }
9720
+ else {
9721
+ if (d)
9722
+ files[fn] = d;
9723
+ if (!--lft)
9724
+ cbd(null, files);
9725
+ }
9726
+ };
9727
+ if (!fltr || fltr({
9728
+ name: fn,
9729
+ size: sc,
9730
+ originalSize: su,
9731
+ compression: c_1
9732
+ })) {
9733
+ if (!c_1)
9734
+ cbl(null, slc(data, b, b + sc));
9735
+ else if (c_1 == 8) {
9736
+ var infl = data.subarray(b, b + sc);
9737
+ if (sc < 320000) {
9738
+ try {
9739
+ cbl(null, inflateSync(infl, new u8(su)));
9740
+ }
9741
+ catch (e) {
9742
+ cbl(e, null);
9743
+ }
9744
+ }
9745
+ else
9746
+ term.push(inflate(infl, { size: su }, cbl));
9747
+ }
9748
+ else
9749
+ cbl(err(14, 'unknown compression type ' + c_1, 1), null);
9750
+ }
9751
+ else
9752
+ cbl(null, null);
9753
+ };
9754
+ for (var i = 0; i < c; ++i) {
9755
+ _loop_3(i);
9756
+ }
9757
+ }
9758
+ else
9759
+ cbd(null, {});
9760
+ return tAll;
9761
+ }
9762
+ /**
9763
+ * Synchronously decompresses a ZIP archive. Prefer using `unzip` for better
9764
+ * performance with more than one file.
9765
+ * @param data The raw compressed ZIP file
9766
+ * @param opts The ZIP extraction options
9767
+ * @returns The decompressed files
9768
+ */
9769
+ function unzipSync$1(data, opts) {
9770
+ var files = {};
9771
+ var e = data.length - 22;
9772
+ for (; b4(data, e) != 0x6054B50; --e) {
9773
+ if (!e || data.length - e > 65558)
9774
+ err(13);
9775
+ }
9776
+ ;
9777
+ var c = b2(data, e + 8);
9778
+ if (!c)
9779
+ return {};
9780
+ var o = b4(data, e + 16);
9781
+ var z = o == 4294967295 || c == 65535;
9782
+ if (z) {
9783
+ var ze = b4(data, e - 12);
9784
+ z = b4(data, ze) == 0x6064B50;
9785
+ if (z) {
9786
+ c = b4(data, ze + 32);
9787
+ o = b4(data, ze + 48);
9788
+ }
9789
+ }
9790
+ var fltr = opts && opts.filter;
9791
+ for (var i = 0; i < c; ++i) {
9792
+ var _a = zh(data, o, z), c_2 = _a[0], sc = _a[1], su = _a[2], fn = _a[3], no = _a[4], off = _a[5], b = slzh(data, off);
9793
+ o = no;
9794
+ if (!fltr || fltr({
9795
+ name: fn,
9796
+ size: sc,
9797
+ originalSize: su,
9798
+ compression: c_2
9799
+ })) {
9800
+ if (!c_2)
9801
+ files[fn] = slc(data, b, b + sc);
9802
+ else if (c_2 == 8)
9803
+ files[fn] = inflateSync(data.subarray(b, b + sc), new u8(su));
9804
+ else
9805
+ err(14, 'unknown compression type ' + c_2);
9806
+ }
9807
+ }
9808
+ return files;
9809
+ }
9810
+
9811
+ function runningInBrowser() {
9812
+ return typeof window !== 'undefined' && typeof window.document !== 'undefined';
9813
+ }
9814
+
9815
+ var Env = /*#__PURE__*/Object.freeze({
9816
+ __proto__: null,
9817
+ runningInBrowser: runningInBrowser
9818
+ });
9819
+
9820
+ // input: A file path or a buffer
9821
+ function unzipSync(input) {
9822
+ if (input instanceof ArrayBuffer) {
9823
+ input = new Uint8Array(input);
9824
+ }
9825
+ if (!runningInBrowser()) {
9826
+ return unzipSyncNode(input);
9827
+ }
9828
+ var obj = unzipSync$1(input, {filter: fflateFilter});
9829
+ return fflatePostprocess(obj);
9830
+ }
9831
+
9832
+ function unzipAsync(buf, cb) {
9833
+ if (!runningInBrowser()) {
9834
+ error('Async unzipping only supported in the browser');
9835
+ }
9836
+ if (buf instanceof ArrayBuffer) {
9837
+ buf = new Uint8Array(buf);
9838
+ }
9839
+ var obj = unzip(buf, {filter: fflateFilter}, cb);
9840
+ return fflatePostprocess(obj);
9841
+ }
9842
+
9843
+ function zipSync(files) {
9844
+ if (runningInBrowser()) {
9845
+ return zipSync$1(fflatePreprocess(files));
9846
+ }
9847
+ return zipSyncNode(files);
9848
+ }
9849
+
9850
+ function zipAsync(files, cb) {
9851
+ zip(fflatePreprocess(files), {}, cb);
9852
+ }
9853
+
9854
+ function fflateFilter(file) {
9855
+ return isImportableZipPath(file.name);
9856
+ }
9857
+
9858
+ function fflatePostprocess(output) {
9859
+ return Object.keys(output).reduce(function(memo, path) {
9860
+ var file = parseLocalPath(path).filename;
9861
+ var content = output[path];
9862
+ if (!isImportableAsBinary(file)) {
9863
+ content = strFromU8(content);
9864
+ }
9865
+ memo[file] = content;
9866
+ return memo;
9867
+ }, {});
9868
+ }
9869
+
9870
+ function isImportableZipPath(name) {
9871
+ var info = parseLocalPath(name);
9872
+ return looksLikeContentFile(name) &&
9873
+ !/^__MACOSX/.test(name) && // ignore "resource-fork" files
9874
+ info.filename[0] != '.'; // ignore dot files
9875
+ }
9876
+
7245
9877
  // input: input file path or a Buffer containing .zip file bytes
7246
- // cache: destination for extracted file contents
7247
- function extractFiles(input, cache) {
9878
+ function unzipSyncNode(input) {
7248
9879
  var zip = new require('adm-zip')(input);
7249
- var files = zip.getEntries().map(function(entry) {
9880
+ var index = {};
9881
+ zip.getEntries().forEach(function(entry) {
7250
9882
  // entry.entryName // path, including filename
7251
9883
  // entry.name // filename
7252
9884
  var file = toLowerCaseExtension(entry.name);
7253
- if (file[0] == '.') return ''; // skip hidden system file
7254
- var type = guessInputFileType(file);
7255
- if (!type) return ''; // skip unrecognized extensions
7256
- cache[file] = entry.getData();
7257
- return file;
7258
- });
7259
- // remove auxiliary files from the import list
7260
- // (these are files that can't be converted into datasets);
7261
- return files.filter(function(file) {
7262
- if (!file) return false;
7263
- var type = guessInputFileType(file);
7264
- if (type == 'dbf') {
7265
- // don't import .dbf separately if .shp is present
7266
- if (replaceFileExtension(file, 'shp') in cache) return false;
9885
+ if (isImportableZipPath(file)) {
9886
+ index[file] = entry.getData();
7267
9887
  }
7268
- return type == 'text' || type == 'json' || type == 'shp' || type == 'dbf';
7269
9888
  });
9889
+ return index;
7270
9890
  }
7271
9891
 
7272
- function convertOutputFiles(files, opts) {
7273
- var filename = opts.zipfile || 'output.zip';
7274
- var dirname = parseLocalPath(filename).basename;
9892
+ function zipSyncNode(files) {
7275
9893
  var zip = new require('adm-zip')();
7276
9894
  files.forEach(function(o) {
7277
- var ofile = require('path').join(dirname, o.filename);
7278
- var buf = Buffer.from(o.content);
9895
+ var buf = o.content;
7279
9896
  if (buf instanceof ArrayBuffer) {
7280
9897
  buf = new Uint8Array(buf);
9898
+ } else if (!(buf instanceof Buffer || buf instanceof Uint8Array)) {
9899
+ buf = Buffer.from(o.content);
7281
9900
  }
7282
- zip.addFile(ofile, buf);
7283
- delete o.content; // for gc?
9901
+ zip.addFile(o.filename, buf);
9902
+ // delete o.content; // for gc?
7284
9903
  });
7285
- return [{
7286
- filename: filename,
7287
- content: zip.toBuffer()
7288
- }];
9904
+ return zip.toBuffer();
7289
9905
  }
7290
9906
 
7291
- function runningInBrowser() {
7292
- return typeof window !== 'undefined' && typeof window.document !== 'undefined';
9907
+ // Convert array of output file data to input format used by fflate zip
9908
+ function fflatePreprocess(files) {
9909
+ var obj = {};
9910
+ files.forEach(function(file) {
9911
+ if (typeof file.content == 'string') {
9912
+ file.content = strToU8(file.content);
9913
+ } else if (file.content instanceof ArrayBuffer) {
9914
+ file.content = new Uint8Array(file.content);
9915
+ }
9916
+ obj[file.filename] = file.content;
9917
+ });
9918
+ return obj;
7293
9919
  }
7294
9920
 
7295
- var Env = /*#__PURE__*/Object.freeze({
9921
+ var Zip = /*#__PURE__*/Object.freeze({
7296
9922
  __proto__: null,
7297
- runningInBrowser: runningInBrowser
9923
+ unzipSync: unzipSync,
9924
+ unzipAsync: unzipAsync,
9925
+ zipSync: zipSync,
9926
+ zipAsync: zipAsync,
9927
+ isImportableZipPath: isImportableZipPath
7298
9928
  });
7299
9929
 
7300
9930
  var cli = {};
@@ -7306,6 +9936,13 @@
7306
9936
  return ss && ss.isFile() || false;
7307
9937
  };
7308
9938
 
9939
+ cli.checkCommandEnv = function(cname) {
9940
+ var blocked = ['i', 'include', 'require', 'external'];
9941
+ if (runningInBrowser() && blocked.includes(cname)) {
9942
+ stop('The -' + cname + ' command cannot be run in the browser');
9943
+ }
9944
+ };
9945
+
7309
9946
  // cli.fileSize = function(path) {
7310
9947
  // var ss = cli.statSync(path);
7311
9948
  // return ss && ss.size || 0;
@@ -7447,7 +10084,11 @@
7447
10084
  return cli.writeFile('/dev/stdout', exports[0].content, cb);
7448
10085
  } else {
7449
10086
  if (opts.zip) {
7450
- exports = convertOutputFiles(exports, opts);
10087
+ exports = [{
10088
+ // TODO: add output subdirectory, if relevant
10089
+ filename: opts.zipfile || 'output.zip',
10090
+ content: zipSync(exports)
10091
+ }];
7451
10092
  }
7452
10093
  var paths = getOutputPaths(utils.pluck(exports, 'filename'), opts);
7453
10094
  var inputFiles = getStashedVar('input_files');
@@ -7457,14 +10098,11 @@
7457
10098
  // replacing content so ArrayBuffers can be gc'd
7458
10099
  obj.content = cli.convertArrayBuffer(obj.content); // convert to Buffer
7459
10100
  }
7460
- if (opts.gzip) {
7461
- path = /gz$/i.test(path) ? path : path + '.gz';
7462
- obj.content = require$1('zlib').gzipSync(obj.content);
7463
- }
7464
10101
  if (opts.output) {
7465
10102
  opts.output.push({filename: path, content: obj.content});
7466
10103
  return;
7467
- } if (!opts.force && inputFiles.indexOf(path) > -1) {
10104
+ }
10105
+ if (!opts.force && inputFiles.indexOf(path) > -1) {
7468
10106
  stop('Need to use the "-o force" option to overwrite input files.');
7469
10107
  }
7470
10108
  cli.writeFile(path, obj.content);
@@ -8226,55 +10864,71 @@
8226
10864
  getFormattedStringify: getFormattedStringify
8227
10865
  });
8228
10866
 
8229
- // Return id of rightmost connected arc in relation to @arcId
8230
- // Return @arcId if no arcs can be found
8231
- function getRightmostArc(arcId, nodes, filter) {
8232
- var ids = nodes.getConnectedArcs(arcId);
10867
+ function isValidArc(arcId, arcs) {
10868
+ // check for arcs with no vertices
10869
+ // TODO: also check for other kinds of degenerate arcs
10870
+ // (e.g. collapsed arcs consisting of identical points)
10871
+ return arcs.getArcLength(arcId) > 1;
10872
+ }
10873
+
10874
+ // Return id of rightmost connected arc in relation to @fromArcId
10875
+ // Return @fromArcId if no arcs can be found
10876
+ function getRightmostArc(fromArcId, nodes, filter) {
10877
+ var arcs = nodes.arcs,
10878
+ coords = arcs.getVertexData(),
10879
+ xx = coords.xx,
10880
+ yy = coords.yy,
10881
+ ids = nodes.getConnectedArcs(fromArcId),
10882
+ toArcId = fromArcId; // initialize to fromArcId -- an error condition
10883
+
8233
10884
  if (filter) {
8234
10885
  ids = ids.filter(filter);
8235
10886
  }
8236
- if (ids.length === 0) {
8237
- return arcId; // error condition, handled by caller
10887
+
10888
+ if (!isValidArc(fromArcId, arcs) || ids.length === 0) {
10889
+ return fromArcId;
8238
10890
  }
8239
- return getRighmostArc2(arcId, ids, nodes.arcs);
8240
- }
8241
10891
 
8242
- function getRighmostArc2 (fromId, ids, arcs) {
8243
- var coords = arcs.getVertexData(),
8244
- xx = coords.xx,
8245
- yy = coords.yy,
8246
- inode = arcs.indexOfVertex(fromId, -1),
10892
+ var inode = arcs.indexOfVertex(fromArcId, -1),
8247
10893
  nodeX = xx[inode],
8248
10894
  nodeY = yy[inode],
8249
- ifrom = arcs.indexOfVertex(fromId, -2),
10895
+ ifrom = arcs.indexOfVertex(fromArcId, -2),
8250
10896
  fromX = xx[ifrom],
8251
10897
  fromY = yy[ifrom],
8252
- toId = fromId, // initialize to from-arc -- an error
8253
10898
  ito, candId, icand, code, j;
8254
10899
 
8255
10900
  /*if (x == ax && y == ay) {
8256
10901
  error("Duplicate point error");
8257
10902
  }*/
8258
- if (ids.length > 0) {
8259
- toId = ids[0];
8260
- ito = arcs.indexOfVertex(toId, -2);
8261
- }
8262
10903
 
8263
- for (j=1; j<ids.length; j++) {
10904
+
10905
+ for (j=0; j<ids.length; j++) {
8264
10906
  candId = ids[j];
10907
+ if (!isValidArc(candId, arcs)) {
10908
+ // skip empty arcs
10909
+ continue;
10910
+ }
8265
10911
  icand = arcs.indexOfVertex(candId, -2);
10912
+
10913
+ if (toArcId == fromArcId) {
10914
+ // first valid candidate
10915
+ ito = icand;
10916
+ toArcId = candId;
10917
+ continue;
10918
+ }
10919
+
8266
10920
  code = chooseRighthandPath(fromX, fromY, nodeX, nodeY, xx[ito], yy[ito], xx[icand], yy[icand]);
8267
- // code = internal.chooseRighthandPath(0, 0, nodeX - fromX, nodeY - fromY, xx[ito] - fromX, yy[ito] - fromY, xx[icand] - fromX, yy[icand] - fromY);
8268
10921
  if (code == 2) {
8269
- toId = candId;
8270
10922
  ito = icand;
10923
+ toArcId = candId;
8271
10924
  }
8272
10925
  }
8273
- if (toId == fromId) {
10926
+
10927
+ if (toArcId == fromArcId) {
8274
10928
  // This shouldn't occur, assuming that other arcs are present
8275
10929
  error("Pathfinder error");
8276
10930
  }
8277
- return toId;
10931
+ return toArcId;
8278
10932
  }
8279
10933
 
8280
10934
  function chooseRighthandPath2(fromX, fromY, nodeX, nodeY, ax, ay, bx, by) {
@@ -8473,11 +11127,19 @@
8473
11127
  return ~getRightmostArc(prevId, nodes, testArc);
8474
11128
  }
8475
11129
 
11130
+ function isEmptyArc(id) {
11131
+ return nodes.arcs.getArcLength(id) > 1 === false;
11132
+ }
11133
+
8476
11134
  return function(startId) {
8477
11135
  var path = [],
8478
11136
  nextId, msg,
8479
11137
  candId = startId;
8480
11138
 
11139
+ if (isEmptyArc(startId)) {
11140
+ return null;
11141
+ }
11142
+
8481
11143
  do {
8482
11144
  if (useRoute(candId)) {
8483
11145
  path.push(candId);
@@ -15766,6 +18428,22 @@ ${svg}
15766
18428
  layerHasLabels: layerHasLabels
15767
18429
  });
15768
18430
 
18431
+ // import { isKmzFile } from '../io/mapshaper-file-types';
18432
+
18433
+ function exportKML(dataset, opts) {
18434
+ var toKML = require("@placemarkio/tokml").toKML;
18435
+ var geojsonOpts = Object.assign({combine_layers: true, geojson_type: 'FeatureCollection'}, opts);
18436
+ var geojson = exportDatasetAsGeoJSON(dataset, geojsonOpts);
18437
+ var kml = toKML(geojson);
18438
+ // TODO: add KMZ output
18439
+ // var useKmz = opts.file && isKmzFile(opts.file);
18440
+ var ofile = opts.file || getOutputFileBase(dataset) + '.kml';
18441
+ return [{
18442
+ content: kml,
18443
+ filename: ofile
18444
+ }];
18445
+ }
18446
+
15769
18447
  function buffersAreIdentical(a, b) {
15770
18448
  var alen = BinArray.bufferSize(a);
15771
18449
  var blen = BinArray.bufferSize(b);
@@ -15789,7 +18467,7 @@ ${svg}
15789
18467
  buf = new ArrayBuffer(buf);
15790
18468
  } else if (buf instanceof ArrayBuffer) {
15791
18469
  // we're good
15792
- } else if (typeof B$3 == 'function' && buf instanceof B$3) {
18470
+ } else if (typeof B$3 == 'function' && buf instanceof B$3 || buf instanceof Uint8Array) {
15793
18471
  if (buf.buffer && buf.buffer.byteLength == buf.length) {
15794
18472
  buf = buf.buffer;
15795
18473
  } else {
@@ -16485,6 +19163,69 @@ ${svg}
16485
19163
  }];
16486
19164
  }
16487
19165
 
19166
+ function exportBSON(datasets, opts) {
19167
+ var { serialize } = require('bson');
19168
+ var obj = exportDatasets$1(datasets);
19169
+ var content = serialize(obj);
19170
+ return [{
19171
+ content: content,
19172
+ filename: opts.file || 'output.mshp'
19173
+ }];
19174
+ }
19175
+
19176
+ // gui: (optional) gui instance
19177
+ //
19178
+ function exportDatasets$1(datasets) {
19179
+ // TODO: add targets
19180
+ // TODO: add gui state
19181
+ return {
19182
+ version: 1,
19183
+ datasets: datasets.map(exportDataset)
19184
+ };
19185
+ }
19186
+
19187
+ // TODO..
19188
+ // export function serializeSession(catalog) {
19189
+ // var obj = exportDatasets(catalog.getDatasets());
19190
+ // return BSON.serialize(obj);
19191
+ // }
19192
+
19193
+ function exportDataset(dataset) {
19194
+ return Object.assign(dataset, {
19195
+ arcs: dataset.arcs ? exportArcs(dataset.arcs) : null,
19196
+ info: dataset.info ? exportInfo(dataset.info) : null,
19197
+ layers: (dataset.layers || []).map(exportLayer)
19198
+ });
19199
+ }
19200
+
19201
+ function typedArrayToBuffer(arr) {
19202
+ return new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength);
19203
+ }
19204
+
19205
+ function exportArcs(arcs) {
19206
+ var data = arcs.getVertexData();
19207
+ var obj = {
19208
+ nn: typedArrayToBuffer(data.nn),
19209
+ xx: typedArrayToBuffer(data.xx),
19210
+ yy: typedArrayToBuffer(data.yy)
19211
+ };
19212
+ return obj;
19213
+ }
19214
+
19215
+ function exportLayer(lyr) {
19216
+ return {
19217
+ name: lyr.name || null,
19218
+ geometry_type: lyr.geometry_type || null,
19219
+ shapes: lyr.shapes || null,
19220
+ data: lyr.data ? lyr.data.getRecords() : null
19221
+ };
19222
+ }
19223
+
19224
+ function exportInfo(info) {
19225
+ // TODO: export CRS
19226
+ return info;
19227
+ }
19228
+
16488
19229
  function exportRecordsAsFixedWidthString(fields, records, opts) {
16489
19230
  var rows = [], col;
16490
19231
  for (var i=0; i<fields.length; i++) {
@@ -17469,12 +20210,18 @@ ${svg}
17469
20210
  function inferOutputFormat(file, inputFormat) {
17470
20211
  var ext = getFileExtension(file).toLowerCase(),
17471
20212
  format = null;
17472
- if (ext == 'shp') {
20213
+ if (ext == 'gz') {
20214
+ return inferOutputFormat(replaceFileExtension(file, ''), inputFormat);
20215
+ } else if (ext == 'mshp') {
20216
+ format = 'mshp';
20217
+ } else if (ext == 'shp') {
17473
20218
  format = 'shapefile';
17474
20219
  } else if (ext == 'dbf') {
17475
20220
  format = 'dbf';
17476
20221
  } else if (ext == 'svg') {
17477
20222
  format = 'svg';
20223
+ } else if (ext == 'kml' || ext == 'kmz') {
20224
+ format = 'kml';
17478
20225
  } else if (/json$/.test(ext)) {
17479
20226
  format = 'geojson';
17480
20227
  if (ext == 'topojson' || inputFormat == 'topojson' && ext != 'geojson') {
@@ -17498,6 +20245,34 @@ ${svg}
17498
20245
  inferOutputFormat: inferOutputFormat
17499
20246
  });
17500
20247
 
20248
+ function gzipSync(content) {
20249
+ // TODO: use native module in Node if available
20250
+ // require('zlib').
20251
+ if (typeof content == 'string') {
20252
+ content = strToU8(content);
20253
+ }
20254
+ return gzipSync$1(content);
20255
+ }
20256
+
20257
+ function gunzipSync(buf, filename) {
20258
+ // TODO: use native module in Node
20259
+ // require('zlib').
20260
+ if (buf instanceof ArrayBuffer) {
20261
+ buf = new Uint8Array(buf);
20262
+ }
20263
+ var out = gunzipSync$1(buf); // returns Uint8Array
20264
+ if (!isImportableAsBinary(filename)) {
20265
+ out = strFromU8(out);
20266
+ }
20267
+ return out;
20268
+ }
20269
+
20270
+ var Gzip = /*#__PURE__*/Object.freeze({
20271
+ __proto__: null,
20272
+ gzipSync: gzipSync,
20273
+ gunzipSync: gunzipSync
20274
+ });
20275
+
17501
20276
  // @targets - non-empty output from Catalog#findCommandTargets()
17502
20277
  //
17503
20278
  function exportTargetLayers(targets, opts) {
@@ -17513,7 +20288,10 @@ ${svg}
17513
20288
  function exportDatasets(datasets, opts) {
17514
20289
  var format = getOutputFormat(datasets[0], opts);
17515
20290
  var files;
17516
- if (format == 'svg' || format == 'topojson' || format == 'geojson' && opts.combine_layers) {
20291
+ if (format == 'mshp') {
20292
+ return exportBSON(datasets, opts);
20293
+ }
20294
+ if (format == 'kml' || format == 'svg' || format == 'topojson' || format == 'geojson' && opts.combine_layers) {
17517
20295
  // multi-layer formats: combine multiple datasets into one
17518
20296
  if (datasets.length > 1) {
17519
20297
  datasets = [mergeDatasetsForExport(datasets)];
@@ -17545,6 +20323,13 @@ ${svg}
17545
20323
  }, []);
17546
20324
  // need unique names for multiple output files
17547
20325
  assignUniqueFileNames(files);
20326
+
20327
+ if (opts.gzip) {
20328
+ files.forEach(function(obj) {
20329
+ obj.filename += '.gz';
20330
+ obj.content = gzipSync(obj.content);
20331
+ });
20332
+ }
17548
20333
  return files;
17549
20334
  }
17550
20335
 
@@ -17567,8 +20352,8 @@ ${svg}
17567
20352
  }, dataset);
17568
20353
 
17569
20354
  // Adjust layer names, so they can be used as output file names
17570
- // (except for multi-layer formats TopoJSON and SVG)
17571
- if (opts.file && outFmt != 'topojson' && outFmt != 'svg') {
20355
+ // (except for multi-layer formats TopoJSON, SVG, KML)
20356
+ if (opts.file && outFmt != 'topojson' && outFmt != 'svg'&& outFmt != 'kml') {
17572
20357
  dataset.layers.forEach(function(lyr) {
17573
20358
  lyr.name = getFileBase(opts.file);
17574
20359
  });
@@ -17607,13 +20392,15 @@ ${svg}
17607
20392
  }
17608
20393
 
17609
20394
  var exporters = {
20395
+ bson: exportBSON,
17610
20396
  geojson: exportGeoJSON2,
17611
20397
  topojson: exportTopoJSON,
17612
20398
  shapefile: exportShapefile,
17613
20399
  dsv: exportDelim,
17614
20400
  dbf: exportDbf,
17615
20401
  json: exportJSON,
17616
- svg: exportSVG
20402
+ svg: exportSVG,
20403
+ kml: exportKML
17617
20404
  };
17618
20405
 
17619
20406
 
@@ -18215,15 +21002,20 @@ ${svg}
18215
21002
  // TODO: Improve reliability and number of detectable encodings.
18216
21003
  function detectEncoding(samples) {
18217
21004
  var encoding = null;
18218
- if (looksLikeUtf8(samples)) {
21005
+ var utf8 = looksLikeUtf8(samples);
21006
+ var win1252 = looksLikeWin1252(samples);
21007
+ if (utf8 == 2 || utf8 > win1252) {
18219
21008
  encoding = 'utf8';
18220
- } else if (looksLikeWin1252(samples)) {
18221
- // Win1252 is the same as Latin1, except it replaces a block of control
18222
- // characters with n-dash, Euro and other glyphs. Encountered in-the-wild
18223
- // in Natural Earth (airports.dbf uses n-dash).
21009
+ } else if (win1252 > 0) {
18224
21010
  encoding = 'win1252';
21011
+ } else {
21012
+ encoding = 'latin1'; // the original Shapefile encoding, using as an (imperfect) fallback
18225
21013
  }
18226
- return encoding;
21014
+
21015
+ return {
21016
+ encoding: encoding,
21017
+ confidence: Math.max(utf8, win1252)
21018
+ };
18227
21019
  }
18228
21020
 
18229
21021
  // Convert an array of text samples to a single string using a given encoding
@@ -18233,19 +21025,26 @@ ${svg}
18233
21025
  }).join('\n');
18234
21026
  }
18235
21027
 
18236
-
21028
+ // Win1252 is the same as Latin1, except it replaces a block of control
21029
+ // characters with n-dash, Euro and other glyphs. Encountered in-the-wild
21030
+ // in Natural Earth (airports.dbf uses n-dash).
21031
+ //
18237
21032
  // Quick-and-dirty win1251 detection: decoded string contains mostly common ascii
18238
21033
  // chars and almost no chars other than word chars + punctuation.
18239
21034
  // This excludes encodings like Greek, Cyrillic or Thai, but
18240
21035
  // is susceptible to false positives with encodings like codepage 1250 ("Eastern
18241
21036
  // European").
21037
+ //
18242
21038
  function looksLikeWin1252(samples) {
18243
- var ascii = 'abcdefghijklmnopqrstuvwxyz0123456789.\'"?+-\n,:;/|_$% ', //common l.c. ascii chars
18244
- extended = 'ßàáâãäåæçèéêëìíîïðñòóôõöøùúûüýÿ°–±’‘', // common extended
21039
+ //common l.c. ascii chars
21040
+ var ascii = 'abcdefghijklmnopqrstuvwxyz0123456789.()\'"?+-\n,:;/|_$% ',
21041
+ // common extended + NBS (found in the wild)
21042
+ extended = 'ßàáâãäåæçèéêëìíîïðñòóôõöøùúûüýÿ°–±’‘' + '\xA0',
18245
21043
  str = decodeSamples('win1252', samples),
18246
21044
  asciiScore = getCharScore(str, ascii),
18247
21045
  totalScore = getCharScore(str, extended + ascii);
18248
- return totalScore > 0.97 && asciiScore >= 0.6; // mostly unaccented ascii chars
21046
+ return totalScore > 0.98 && asciiScore >= 0.8 && 2 ||
21047
+ totalScore > 0.97 && asciiScore >= 0.6 && 1 || 0;
18249
21048
  }
18250
21049
 
18251
21050
  // Reject string if it contains the "replacement character" after decoding to UTF-8
@@ -18254,7 +21053,9 @@ ${svg}
18254
21053
  // in case the file is in utf-8, but contains some previously corrupted text.
18255
21054
  // samples = samples.map(internal.replaceUtf8ReplacementChar);
18256
21055
  var str = decodeSamples('utf8', samples);
18257
- return str.indexOf('\ufffd') == -1;
21056
+ var count = (str.match(/\ufffd/g) || []).length;
21057
+ var score = 1 - count / str.length;
21058
+ return score == 1 && 2 || score > 0.97 && 1 || 0;
18258
21059
  }
18259
21060
 
18260
21061
  // function replaceUtf8ReplacementChar(buf) {
@@ -18308,7 +21109,7 @@ ${svg}
18308
21109
 
18309
21110
  if (readFromFile) {
18310
21111
  reader = new FileReader(data.filename);
18311
- } else if (content instanceof ArrayBuffer || content instanceof B$3) {
21112
+ } else if (content instanceof ArrayBuffer || content instanceof B$3 || content instanceof Uint8Array) {
18312
21113
  // Web API may import as ArrayBuffer, to support larger files
18313
21114
  reader = new BufferReader(content);
18314
21115
  content = null;
@@ -21312,8 +24113,8 @@ ${svg}
21312
24113
  };
21313
24114
 
21314
24115
  var ENCODING_PROMPT =
21315
- "To avoid corrupted text, re-import using the \"encoding=\" option.\n" +
21316
- "To see a list of supported encodings, run the \"encodings\" command.";
24116
+ "To set the text encoding, re-import using the \"encoding=\" option.\n" +
24117
+ "To list the supported encodings, run the \"encodings\" command.";
21317
24118
 
21318
24119
  function lookupCodePage(lid) {
21319
24120
  var i = languageIds.indexOf(lid);
@@ -21452,7 +24253,6 @@ ${svg}
21452
24253
  // TODO: switch to streaming output under Node.js
21453
24254
  this.getBuffer = function() {
21454
24255
  return dbfFile.readSync(0, dbfFile.size());
21455
- // return bin.buffer();
21456
24256
  };
21457
24257
 
21458
24258
  this.deleteField = function(f) {
@@ -21560,16 +24360,12 @@ ${svg}
21560
24360
  }
21561
24361
 
21562
24362
  function initEncoding() {
24363
+ if (encoding) return;
21563
24364
  encoding = encodingArg || findStringEncoding();
21564
- if (!encoding) {
21565
- // fall back to utf8 if detection fails (so GUI can continue without further errors)
21566
- encoding = 'utf8';
21567
- stop("Unable to auto-detect the text encoding of the DBF file.\n" + ENCODING_PROMPT);
21568
- }
21569
24365
  }
21570
24366
 
21571
24367
  function getEncoding() {
21572
- if (!encoding) initEncoding();
24368
+ initEncoding();
21573
24369
  return encoding;
21574
24370
  }
21575
24371
 
@@ -21661,18 +24457,28 @@ ${svg}
21661
24457
 
21662
24458
  // As a last resort, try to guess the encoding:
21663
24459
  if (!encoding) {
21664
- encoding = detectEncoding(samples);
24460
+ var info = detectEncoding(samples);
24461
+ encoding = info.encoding;
24462
+ if (info.confidence < 2) {
24463
+ msg = 'Warning: Unable to auto-detect the text encoding of a DBF file with high confidence.';
24464
+ msg += '\n\nDefaulting to: ' + encoding + (encoding in encodingNames ? ' (' + encodingNames[encoding] + ')' : '');
24465
+ msg += '\n\nSample of how non-ascii text was imported:';
24466
+ msg += '\n' + formatStringsAsGrid(decodeSamples(encoding, samples).split('\n'));
24467
+ msg += decodeSamples(encoding, samples);
24468
+ msg += '\n\n' + ENCODING_PROMPT + '\n';
24469
+ message(msg);
24470
+ }
21665
24471
  }
21666
24472
 
21667
24473
  // Show a sample of decoded text if non-ascii-range text has been found
21668
- if (encoding && samples.length > 0) {
21669
- msg = "Detected DBF text encoding: " + encoding + (encoding in encodingNames ? " (" + encodingNames[encoding] + ")" : "");
21670
- message(msg);
21671
- msg = decodeSamples(encoding, samples);
21672
- msg = formatStringsAsGrid(msg.split('\n'));
21673
- msg = "\nSample text containing non-ascii characters:" + (msg.length > 60 ? '\n' : '') + msg;
21674
- verbose(msg);
21675
- }
24474
+ // if (encoding && samples.length > 0) {
24475
+ // msg = "Detected DBF text encoding: " + encoding + (encoding in encodingNames ? " (" + encodingNames[encoding] + ")" : "");
24476
+ // message(msg);
24477
+ // msg = decodeSamples(encoding, samples);
24478
+ // msg = formatStringsAsGrid(msg.split('\n'));
24479
+ // msg = "\nSample text containing non-ascii characters:" + (msg.length > 60 ? '\n' : '') + msg;
24480
+ // verbose(msg);
24481
+ // }
21676
24482
  return encoding;
21677
24483
  }
21678
24484
 
@@ -23574,7 +26380,7 @@ ${svg}
23574
26380
 
23575
26381
  if (!content) {
23576
26382
  reader = new FileReader(filename);
23577
- } else if (content instanceof ArrayBuffer || content instanceof Buffer) {
26383
+ } else if (content instanceof ArrayBuffer || content instanceof B$3 || content instanceof Uint8Array) {
23578
26384
  // Web API imports JSON as ArrayBuffer, to support larger files
23579
26385
  if ((content.byteLength || content.length) < 1e7) {
23580
26386
  // content = utils.createBuffer(content).toString();
@@ -23666,7 +26472,7 @@ ${svg}
23666
26472
  // Parse content of one or more input files and return a dataset
23667
26473
  // @obj: file data, indexed by file type
23668
26474
  // File data objects have two properties:
23669
- // content: Buffer, ArrayBuffer, String or Object
26475
+ // content: Uint8Array, Buffer, ArrayBuffer, String or Object
23670
26476
  // filename: String or null
23671
26477
  //
23672
26478
  function importContent(obj, opts) {
@@ -23794,10 +26600,67 @@ ${svg}
23794
26600
  importFileContent: importFileContent
23795
26601
  });
23796
26602
 
23797
- cmd.importFiles = function(opts) {
23798
- var files = opts.files || [],
23799
- dataset;
26603
+ // Import datasets contained in a BSON blob
26604
+ // Return command target as a dataset
26605
+ //
26606
+ function importBSON(buf) {
26607
+ var { deserialize } = require('bson');
26608
+ var obj = deserialize(buf, {
26609
+ promoteBuffers: true,
26610
+ promoteValues: true
26611
+ });
26612
+ if (!isValidSession(obj)) {
26613
+ stop('Invalid mapshaper session data object');
26614
+ }
26615
+
26616
+ var datasets = obj.datasets.map(importDataset);
26617
+ var target = datasets[0]; // TODO: improve
26618
+ return {
26619
+ datasets: datasets,
26620
+ target: target
26621
+ };
26622
+ }
26623
+
26624
+ function isValidSession(obj) {
26625
+ if (!Array.isArray(obj.datasets)) {
26626
+ return false;
26627
+ }
26628
+ return true;
26629
+ }
26630
+
26631
+ function importDataset(obj) {
26632
+ return {
26633
+ info: obj.info,
26634
+ layers: (obj.layers || []).map(importLayer),
26635
+ arcs: obj.arcs ? importArcs(obj.arcs) : null
26636
+ };
26637
+ }
26638
+
26639
+ function bufferToDataView(buf, constructor) {
26640
+ return new constructor(BinArray.copyToArrayBuffer(buf));
26641
+ // this doesn't work: "RangeError: start offset of Float64Array should be a multiple of 8"
26642
+ // return new constructor(buf.buffer, buf.byteOffset, buf.byteLength);
26643
+ }
26644
+
26645
+ function importArcs(obj) {
26646
+ var nn = bufferToDataView(obj.nn, Uint32Array);
26647
+ var xx = bufferToDataView(obj.xx, Float64Array);
26648
+ var yy = bufferToDataView(obj.yy, Float64Array);
26649
+ var arcs = new ArcCollection(nn, xx, yy);
26650
+ return arcs;
26651
+ }
26652
+
26653
+ function importLayer(lyr) {
26654
+ return Object.assign(lyr, {
26655
+ data: lyr.data ? new DataTable(lyr.data) : null
26656
+ });
26657
+ }
26658
+
26659
+ cmd.importFiles = function(catalog, opts) {
26660
+ var files = opts.files || [];
26661
+ var dataset;
23800
26662
 
26663
+ cli.checkCommandEnv('i');
23801
26664
  if (opts.stdin) {
23802
26665
  return importFile('/dev/stdin', opts);
23803
26666
  }
@@ -23807,20 +26670,102 @@ ${svg}
23807
26670
  }
23808
26671
 
23809
26672
  verbose("Importing: " + files.join(' '));
23810
- if (files.length == 1 && /\.zip/i.test(files[0])) {
23811
- dataset = importZipFile(files[0], opts);
23812
- } else if (files.length == 1) {
26673
+
26674
+ // copy opts, so parameters can be modified within this command
26675
+ opts = Object.assign({}, opts);
26676
+ opts.input = Object.assign({}, opts.input); // make sure we have a cache
26677
+
26678
+ files = expandFiles(files, opts.input);
26679
+
26680
+ if (files.length === 0) {
26681
+ stop('Missing importable files');
26682
+ }
26683
+
26684
+ // special case: .mshp file
26685
+ if (files.some(isMshpFile)) {
26686
+ if (files.length > 1) {
26687
+ stop('Expected a single mshp file');
26688
+ }
26689
+ dataset = importMshpFile(files[0], catalog, opts);
26690
+ return dataset;
26691
+ }
26692
+
26693
+ if (files.length == 1) {
23813
26694
  dataset = importFile(files[0], opts);
23814
- } else if (opts.merge_files) {
23815
- // TODO: deprecate and remove this option (use -merge-layers cmd instead)
23816
- dataset = importFilesTogether(files, opts);
23817
- dataset.layers = cmd.mergeLayers(dataset.layers);
23818
26695
  } else {
23819
26696
  dataset = importFilesTogether(files, opts);
23820
26697
  }
26698
+
26699
+ if (opts.merge_files && files.length > 1) {
26700
+ // TODO: deprecate and remove this option (use -merge-layers cmd instead)
26701
+ dataset.layers = cmd.mergeLayers(dataset.layers);
26702
+ }
26703
+
26704
+ catalog.addDataset(dataset);
23821
26705
  return dataset;
23822
26706
  };
23823
26707
 
26708
+ function importMshpFile(file, catalog, opts) {
26709
+ var buf = cli.readFile(file, null, opts.input);
26710
+ var obj = importBSON(buf);
26711
+ obj.datasets.forEach(function(dataset) {
26712
+ catalog.addDataset(dataset);
26713
+ });
26714
+ return obj.target;
26715
+ }
26716
+
26717
+ function expandFiles(files, cache) {
26718
+ var files2 = [];
26719
+ files.forEach(function(file) {
26720
+ var expanded;
26721
+ if (isZipFile(file)) {
26722
+ expanded = expandZipFile(file, cache);
26723
+ } else if (isKmzFile(file)) {
26724
+ expanded = expandKmzFile(file, cache);
26725
+ } else {
26726
+ expanded = [file]; // ordinary file, no change
26727
+ }
26728
+ files2 = files2.concat(expanded);
26729
+ });
26730
+ return files2;
26731
+ }
26732
+
26733
+ function expandKmzFile(file, cache) {
26734
+ var files = expandZipFile(file, cache);
26735
+ var name = replaceFileExtension(parseLocalPath(file).filename, 'kml');
26736
+ if (files[0] == 'doc.kml') {
26737
+ files[0] = name;
26738
+ cache[name] = cache['doc.kml'];
26739
+ }
26740
+ return files;
26741
+ }
26742
+
26743
+ function expandZipFile(file, cache) {
26744
+ var input;
26745
+ if (file in cache) {
26746
+ input = cache[file];
26747
+ } else {
26748
+ input = file;
26749
+ cli.checkFileExists(file);
26750
+ }
26751
+ var index = unzipSync(input);
26752
+ Object.assign(cache, index);
26753
+ return findPrimaryFiles(index);
26754
+ }
26755
+
26756
+ // Return the names of primary files in a file cache
26757
+ // (exclude auxiliary files, which can't be converted into datasets)
26758
+ function findPrimaryFiles(cache) {
26759
+ return Object.keys(cache).filter(function(filename) {
26760
+ var type = guessInputFileType(filename);
26761
+ if (type == 'dbf') {
26762
+ // don't import .dbf separately if .shp is present
26763
+ if (replaceFileExtension(filename, 'shp') in cache) return false;
26764
+ }
26765
+ return type == 'text' || type == 'json' || type == 'shp' || type == 'dbf' || type == 'kml';
26766
+ });
26767
+ }
26768
+
23824
26769
  // Let the web UI replace importFile() with a browser-friendly version
23825
26770
  function replaceImportFile(func) {
23826
26771
  _importFile = func;
@@ -23839,6 +26784,7 @@ ${svg}
23839
26784
  content;
23840
26785
 
23841
26786
  cli.checkFileExists(path, cache);
26787
+
23842
26788
  if ((fileType == 'shp' || fileType == 'json' || fileType == 'text' || fileType == 'dbf') && !cached) {
23843
26789
  // these file types are read incrementally
23844
26790
  content = null;
@@ -23860,8 +26806,7 @@ ${svg}
23860
26806
  if (!fileType) {
23861
26807
  stop('Unrecognized file type:', path);
23862
26808
  }
23863
- // TODO: consider using a temp file, to support incremental reading
23864
- content = require('zlib').gunzipSync(cli.readFile(pathgz));
26809
+ content = gunzipSync(cli.readFile(pathgz, null, cache), path);
23865
26810
 
23866
26811
  } else { // type can't be inferred from filename -- try reading as text
23867
26812
  content = cli.readFile(path, encoding || 'utf-8', cache);
@@ -23886,23 +26831,6 @@ ${svg}
23886
26831
  return importContent(input, opts);
23887
26832
  };
23888
26833
 
23889
-
23890
- function importZipFile(path, opts) {
23891
- var cache = {};
23892
- var input;
23893
- if (opts.input && (path in opts.input)) {
23894
- // reading from a buffer
23895
- input = opts.input[path];
23896
- } else {
23897
- // reading from a file
23898
- cli.checkFileExists(path);
23899
- input = path;
23900
- }
23901
- var files = extractFiles(input, cache);
23902
- var zipOpts = Object.assign({}, opts, {input: cache});
23903
- return importFilesTogether(files, zipOpts);
23904
- }
23905
-
23906
26834
  // Import multiple files to a single dataset
23907
26835
  function importFilesTogether(files, opts) {
23908
26836
  var unbuiltTopology = false;
@@ -23928,7 +26856,6 @@ ${svg}
23928
26856
  return combined;
23929
26857
  }
23930
26858
 
23931
-
23932
26859
  function getUnsupportedFileMessage(path) {
23933
26860
  var ext = getFileExtension(path);
23934
26861
  var msg = 'Unable to import ' + path;
@@ -28547,15 +31474,15 @@ ${svg}
28547
31474
  var brighter = 1 / darker;
28548
31475
 
28549
31476
  var reI = "\\s*([+-]?\\d+)\\s*",
28550
- reN = "\\s*([+-]?\\d*\\.?\\d+(?:[eE][+-]?\\d+)?)\\s*",
28551
- reP = "\\s*([+-]?\\d*\\.?\\d+(?:[eE][+-]?\\d+)?)%\\s*",
31477
+ reN = "\\s*([+-]?(?:\\d*\\.)?\\d+(?:[eE][+-]?\\d+)?)\\s*",
31478
+ reP = "\\s*([+-]?(?:\\d*\\.)?\\d+(?:[eE][+-]?\\d+)?)%\\s*",
28552
31479
  reHex = /^#([0-9a-f]{3,8})$/,
28553
- reRgbInteger = new RegExp("^rgb\\(" + [reI, reI, reI] + "\\)$"),
28554
- reRgbPercent = new RegExp("^rgb\\(" + [reP, reP, reP] + "\\)$"),
28555
- reRgbaInteger = new RegExp("^rgba\\(" + [reI, reI, reI, reN] + "\\)$"),
28556
- reRgbaPercent = new RegExp("^rgba\\(" + [reP, reP, reP, reN] + "\\)$"),
28557
- reHslPercent = new RegExp("^hsl\\(" + [reN, reP, reP] + "\\)$"),
28558
- reHslaPercent = new RegExp("^hsla\\(" + [reN, reP, reP, reN] + "\\)$");
31480
+ reRgbInteger = new RegExp(`^rgb\\(${reI},${reI},${reI}\\)$`),
31481
+ reRgbPercent = new RegExp(`^rgb\\(${reP},${reP},${reP}\\)$`),
31482
+ reRgbaInteger = new RegExp(`^rgba\\(${reI},${reI},${reI},${reN}\\)$`),
31483
+ reRgbaPercent = new RegExp(`^rgba\\(${reP},${reP},${reP},${reN}\\)$`),
31484
+ reHslPercent = new RegExp(`^hsl\\(${reN},${reP},${reP}\\)$`),
31485
+ reHslaPercent = new RegExp(`^hsla\\(${reN},${reP},${reP},${reN}\\)$`);
28559
31486
 
28560
31487
  var named = {
28561
31488
  aliceblue: 0xf0f8ff,
@@ -28709,14 +31636,15 @@ ${svg}
28709
31636
  };
28710
31637
 
28711
31638
  define(Color, color, {
28712
- copy: function(channels) {
31639
+ copy(channels) {
28713
31640
  return Object.assign(new this.constructor, this, channels);
28714
31641
  },
28715
- displayable: function() {
31642
+ displayable() {
28716
31643
  return this.rgb().displayable();
28717
31644
  },
28718
31645
  hex: color_formatHex, // Deprecated! Use color.formatHex.
28719
31646
  formatHex: color_formatHex,
31647
+ formatHex8: color_formatHex8,
28720
31648
  formatHsl: color_formatHsl,
28721
31649
  formatRgb: color_formatRgb,
28722
31650
  toString: color_formatRgb
@@ -28726,6 +31654,10 @@ ${svg}
28726
31654
  return this.rgb().formatHex();
28727
31655
  }
28728
31656
 
31657
+ function color_formatHex8() {
31658
+ return this.rgb().formatHex8();
31659
+ }
31660
+
28729
31661
  function color_formatHsl() {
28730
31662
  return hslConvert(this).formatHsl();
28731
31663
  }
@@ -28781,18 +31713,21 @@ ${svg}
28781
31713
  }
28782
31714
 
28783
31715
  define(Rgb, rgb$1, extend(Color, {
28784
- brighter: function(k) {
31716
+ brighter(k) {
28785
31717
  k = k == null ? brighter : Math.pow(brighter, k);
28786
31718
  return new Rgb(this.r * k, this.g * k, this.b * k, this.opacity);
28787
31719
  },
28788
- darker: function(k) {
31720
+ darker(k) {
28789
31721
  k = k == null ? darker : Math.pow(darker, k);
28790
31722
  return new Rgb(this.r * k, this.g * k, this.b * k, this.opacity);
28791
31723
  },
28792
- rgb: function() {
31724
+ rgb() {
28793
31725
  return this;
28794
31726
  },
28795
- displayable: function() {
31727
+ clamp() {
31728
+ return new Rgb(clampi(this.r), clampi(this.g), clampi(this.b), clampa(this.opacity));
31729
+ },
31730
+ displayable() {
28796
31731
  return (-0.5 <= this.r && this.r < 255.5)
28797
31732
  && (-0.5 <= this.g && this.g < 255.5)
28798
31733
  && (-0.5 <= this.b && this.b < 255.5)
@@ -28800,25 +31735,34 @@ ${svg}
28800
31735
  },
28801
31736
  hex: rgb_formatHex, // Deprecated! Use color.formatHex.
28802
31737
  formatHex: rgb_formatHex,
31738
+ formatHex8: rgb_formatHex8,
28803
31739
  formatRgb: rgb_formatRgb,
28804
31740
  toString: rgb_formatRgb
28805
31741
  }));
28806
31742
 
28807
31743
  function rgb_formatHex() {
28808
- return "#" + hex(this.r) + hex(this.g) + hex(this.b);
31744
+ return `#${hex(this.r)}${hex(this.g)}${hex(this.b)}`;
31745
+ }
31746
+
31747
+ function rgb_formatHex8() {
31748
+ return `#${hex(this.r)}${hex(this.g)}${hex(this.b)}${hex((isNaN(this.opacity) ? 1 : this.opacity) * 255)}`;
28809
31749
  }
28810
31750
 
28811
31751
  function rgb_formatRgb() {
28812
- var a = this.opacity; a = isNaN(a) ? 1 : Math.max(0, Math.min(1, a));
28813
- return (a === 1 ? "rgb(" : "rgba(")
28814
- + Math.max(0, Math.min(255, Math.round(this.r) || 0)) + ", "
28815
- + Math.max(0, Math.min(255, Math.round(this.g) || 0)) + ", "
28816
- + Math.max(0, Math.min(255, Math.round(this.b) || 0))
28817
- + (a === 1 ? ")" : ", " + a + ")");
31752
+ const a = clampa(this.opacity);
31753
+ return `${a === 1 ? "rgb(" : "rgba("}${clampi(this.r)}, ${clampi(this.g)}, ${clampi(this.b)}${a === 1 ? ")" : `, ${a})`}`;
31754
+ }
31755
+
31756
+ function clampa(opacity) {
31757
+ return isNaN(opacity) ? 1 : Math.max(0, Math.min(1, opacity));
31758
+ }
31759
+
31760
+ function clampi(value) {
31761
+ return Math.max(0, Math.min(255, Math.round(value) || 0));
28818
31762
  }
28819
31763
 
28820
31764
  function hex(value) {
28821
- value = Math.max(0, Math.min(255, Math.round(value) || 0));
31765
+ value = clampi(value);
28822
31766
  return (value < 16 ? "0" : "") + value.toString(16);
28823
31767
  }
28824
31768
 
@@ -28867,15 +31811,15 @@ ${svg}
28867
31811
  }
28868
31812
 
28869
31813
  define(Hsl, hsl$2, extend(Color, {
28870
- brighter: function(k) {
31814
+ brighter(k) {
28871
31815
  k = k == null ? brighter : Math.pow(brighter, k);
28872
31816
  return new Hsl(this.h, this.s, this.l * k, this.opacity);
28873
31817
  },
28874
- darker: function(k) {
31818
+ darker(k) {
28875
31819
  k = k == null ? darker : Math.pow(darker, k);
28876
31820
  return new Hsl(this.h, this.s, this.l * k, this.opacity);
28877
31821
  },
28878
- rgb: function() {
31822
+ rgb() {
28879
31823
  var h = this.h % 360 + (this.h < 0) * 360,
28880
31824
  s = isNaN(h) || isNaN(this.s) ? 0 : this.s,
28881
31825
  l = this.l,
@@ -28888,21 +31832,29 @@ ${svg}
28888
31832
  this.opacity
28889
31833
  );
28890
31834
  },
28891
- displayable: function() {
31835
+ clamp() {
31836
+ return new Hsl(clamph(this.h), clampt(this.s), clampt(this.l), clampa(this.opacity));
31837
+ },
31838
+ displayable() {
28892
31839
  return (0 <= this.s && this.s <= 1 || isNaN(this.s))
28893
31840
  && (0 <= this.l && this.l <= 1)
28894
31841
  && (0 <= this.opacity && this.opacity <= 1);
28895
31842
  },
28896
- formatHsl: function() {
28897
- var a = this.opacity; a = isNaN(a) ? 1 : Math.max(0, Math.min(1, a));
28898
- return (a === 1 ? "hsl(" : "hsla(")
28899
- + (this.h || 0) + ", "
28900
- + (this.s || 0) * 100 + "%, "
28901
- + (this.l || 0) * 100 + "%"
28902
- + (a === 1 ? ")" : ", " + a + ")");
31843
+ formatHsl() {
31844
+ const a = clampa(this.opacity);
31845
+ return `${a === 1 ? "hsl(" : "hsla("}${clamph(this.h)}, ${clampt(this.s) * 100}%, ${clampt(this.l) * 100}%${a === 1 ? ")" : `, ${a})`}`;
28903
31846
  }
28904
31847
  }));
28905
31848
 
31849
+ function clamph(value) {
31850
+ value = (value || 0) % 360;
31851
+ return value < 0 ? value + 360 : value;
31852
+ }
31853
+
31854
+ function clampt(value) {
31855
+ return Math.max(0, Math.min(1, value || 0));
31856
+ }
31857
+
28906
31858
  /* From FvD 13.37, CSS Color Module Level 3 */
28907
31859
  function hsl2rgb(h, m1, m2) {
28908
31860
  return (h < 60 ? m1 + (m2 - m1) * h / 60
@@ -28955,13 +31907,13 @@ ${svg}
28955
31907
  }
28956
31908
 
28957
31909
  define(Lab, lab$1, extend(Color, {
28958
- brighter: function(k) {
31910
+ brighter(k) {
28959
31911
  return new Lab(this.l + K * (k == null ? 1 : k), this.a, this.b, this.opacity);
28960
31912
  },
28961
- darker: function(k) {
31913
+ darker(k) {
28962
31914
  return new Lab(this.l - K * (k == null ? 1 : k), this.a, this.b, this.opacity);
28963
31915
  },
28964
- rgb: function() {
31916
+ rgb() {
28965
31917
  var y = (this.l + 16) / 116,
28966
31918
  x = isNaN(this.a) ? y : y + this.a / 500,
28967
31919
  z = isNaN(this.b) ? y : y - this.b / 200;
@@ -29023,13 +31975,13 @@ ${svg}
29023
31975
  }
29024
31976
 
29025
31977
  define(Hcl, hcl$2, extend(Color, {
29026
- brighter: function(k) {
31978
+ brighter(k) {
29027
31979
  return new Hcl(this.h, this.c, this.l + K * (k == null ? 1 : k), this.opacity);
29028
31980
  },
29029
- darker: function(k) {
31981
+ darker(k) {
29030
31982
  return new Hcl(this.h, this.c, this.l - K * (k == null ? 1 : k), this.opacity);
29031
31983
  },
29032
- rgb: function() {
31984
+ rgb() {
29033
31985
  return hcl2lab(this).rgb();
29034
31986
  }
29035
31987
  }));
@@ -29069,15 +32021,15 @@ ${svg}
29069
32021
  }
29070
32022
 
29071
32023
  define(Cubehelix, cubehelix$3, extend(Color, {
29072
- brighter: function(k) {
32024
+ brighter(k) {
29073
32025
  k = k == null ? brighter : Math.pow(brighter, k);
29074
32026
  return new Cubehelix(this.h, this.s, this.l * k, this.opacity);
29075
32027
  },
29076
- darker: function(k) {
32028
+ darker(k) {
29077
32029
  k = k == null ? darker : Math.pow(darker, k);
29078
32030
  return new Cubehelix(this.h, this.s, this.l * k, this.opacity);
29079
32031
  },
29080
- rgb: function() {
32032
+ rgb() {
29081
32033
  var h = isNaN(this.h) ? 0 : (this.h + 120) * radians,
29082
32034
  l = +this.l,
29083
32035
  a = isNaN(this.s) ? 0 : this.s * l * (1 - l),
@@ -39434,12 +42386,12 @@ ${svg}
39434
42386
  var parser = getOptionParser();
39435
42387
  // support multiline string of commands pasted into console
39436
42388
  str = str.split(/\n+/g).map(function(str) {
39437
- var match = /^[a-z][\w-]*/.exec(str = str.trim());
42389
+ var match = /^[a-z][\w-]*/i.exec(str = str.trim());
39438
42390
  //if (match && parser.isCommandName(match[0])) {
39439
42391
  if (match) {
39440
42392
  // add hyphen prefix to bare command
39441
- // also add hyphen to non-command strings, for a better error message
39442
- // ("unsupported command" instead of "The -i command cannot be run in the browser")
42393
+ // also add hyphen to non-command strings, for a better error message
42394
+ // ("unsupported command" instead of "The -i command cannot be run in the browser")
39443
42395
  str = '-' + str;
39444
42396
  }
39445
42397
  return str;
@@ -39449,15 +42401,10 @@ ${svg}
39449
42401
 
39450
42402
  // Parse a command line string for the browser console
39451
42403
  function parseConsoleCommands(raw) {
39452
- var blocked = ['i', 'include', 'require', 'external'];
39453
42404
  var str = standardizeConsoleCommands(raw);
39454
- var parsed;
39455
- parsed = parseCommands(str);
42405
+ var parsed = parseCommands(str);
39456
42406
  parsed.forEach(function(cmd) {
39457
- var i = blocked.indexOf(cmd.name);
39458
- if (i > -1) {
39459
- stop("The -" + blocked[i] + " command cannot be run in the browser");
39460
- }
42407
+ cli.checkCommandEnv(cmd.name);
39461
42408
  });
39462
42409
  return parsed;
39463
42410
  }
@@ -41869,9 +44816,8 @@ ${svg}
41869
44816
 
41870
44817
  } else if (name == 'i') {
41871
44818
  if (opts.replace) job.catalog = new Catalog(); // is this what we want?
41872
- targetDataset = cmd.importFiles(command.options);
44819
+ targetDataset = cmd.importFiles(job.catalog, command.options);
41873
44820
  if (targetDataset) {
41874
- job.catalog.addDataset(targetDataset);
41875
44821
  outputLayers = targetDataset.layers; // kludge to allow layer naming below
41876
44822
  }
41877
44823
 
@@ -42847,6 +45793,7 @@ ${svg}
42847
45793
  Geodesic,
42848
45794
  GeojsonExport,
42849
45795
  GeojsonImport,
45796
+ Gzip,
42850
45797
  Import,
42851
45798
  Info,
42852
45799
  IntersectionCuts,
@@ -42920,7 +45867,8 @@ ${svg}
42920
45867
  Topology,
42921
45868
  Units,
42922
45869
  SvgHatch,
42923
- VertexUtils
45870
+ VertexUtils,
45871
+ Zip
42924
45872
  );
42925
45873
 
42926
45874
  // The entry point for the core mapshaper module