@mylasertools/kerfscript 0.5.0 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.js CHANGED
@@ -64,19 +64,19 @@ var require_opentype = __commonJS({
64
64
  if (index < 0 || index >= size) {
65
65
  return void 0;
66
66
  }
67
- var first = string.charCodeAt(index);
67
+ var first2 = string.charCodeAt(index);
68
68
  var second;
69
69
  if (
70
70
  // check if it’s the start of a surrogate pair
71
- first >= 55296 && first <= 56319 && // high surrogate
71
+ first2 >= 55296 && first2 <= 56319 && // high surrogate
72
72
  size > index + 1
73
73
  ) {
74
74
  second = string.charCodeAt(index + 1);
75
75
  if (second >= 56320 && second <= 57343) {
76
- return (first - 55296) * 1024 + second - 56320 + 65536;
76
+ return (first2 - 55296) * 1024 + second - 56320 + 65536;
77
77
  }
78
78
  }
79
- return first;
79
+ return first2;
80
80
  };
81
81
  if (defineProperty) {
82
82
  defineProperty(String.prototype, "codePointAt", {
@@ -134,7 +134,7 @@ var require_opentype = __commonJS({
134
134
  ]);
135
135
  var code_tree = new Tree();
136
136
  var lengths = new Uint8Array(288 + 32);
137
- function tinf_build_bits_base(bits, base, delta, first) {
137
+ function tinf_build_bits_base(bits, base, delta, first2) {
138
138
  var i, sum;
139
139
  for (i = 0; i < delta; ++i) {
140
140
  bits[i] = 0;
@@ -142,7 +142,7 @@ var require_opentype = __commonJS({
142
142
  for (i = 0; i < 30 - delta; ++i) {
143
143
  bits[i + delta] = i / delta | 0;
144
144
  }
145
- for (sum = first, i = 0; i < 30; ++i) {
145
+ for (sum = first2, i = 0; i < 30; ++i) {
146
146
  base[i] = sum;
147
147
  sum += 1 << bits[i];
148
148
  }
@@ -176,12 +176,12 @@ var require_opentype = __commonJS({
176
176
  }
177
177
  }
178
178
  var offs = new Uint16Array(16);
179
- function tinf_build_tree(t, lengths2, off, num2) {
179
+ function tinf_build_tree(t, lengths2, off, num3) {
180
180
  var i, sum;
181
181
  for (i = 0; i < 16; ++i) {
182
182
  t.table[i] = 0;
183
183
  }
184
- for (i = 0; i < num2; ++i) {
184
+ for (i = 0; i < num3; ++i) {
185
185
  t.table[lengths2[off + i]]++;
186
186
  }
187
187
  t.table[0] = 0;
@@ -189,7 +189,7 @@ var require_opentype = __commonJS({
189
189
  offs[i] = sum;
190
190
  sum += t.table[i];
191
191
  }
192
- for (i = 0; i < num2; ++i) {
192
+ for (i = 0; i < num3; ++i) {
193
193
  if (lengths2[off + i]) {
194
194
  t.trans[offs[lengths2[off + i]]++] = i;
195
195
  }
@@ -204,17 +204,17 @@ var require_opentype = __commonJS({
204
204
  d2.tag >>>= 1;
205
205
  return bit;
206
206
  }
207
- function tinf_read_bits(d2, num2, base) {
208
- if (!num2) {
207
+ function tinf_read_bits(d2, num3, base) {
208
+ if (!num3) {
209
209
  return base;
210
210
  }
211
211
  while (d2.bitcount < 24) {
212
212
  d2.tag |= d2.source[d2.sourceIndex++] << d2.bitcount;
213
213
  d2.bitcount += 8;
214
214
  }
215
- var val = d2.tag & 65535 >>> 16 - num2;
216
- d2.tag >>>= num2;
217
- d2.bitcount -= num2;
215
+ var val = d2.tag & 65535 >>> 16 - num3;
216
+ d2.tag >>>= num3;
217
+ d2.bitcount -= num3;
218
218
  return val + base;
219
219
  }
220
220
  function tinf_decode_symbol(d2, t) {
@@ -237,7 +237,7 @@ var require_opentype = __commonJS({
237
237
  }
238
238
  function tinf_decode_trees(d2, lt, dt) {
239
239
  var hlit, hdist, hclen;
240
- var i, num2, length;
240
+ var i, num3, length2;
241
241
  hlit = tinf_read_bits(d2, 5, 257);
242
242
  hdist = tinf_read_bits(d2, 5, 1);
243
243
  hclen = tinf_read_bits(d2, 4, 4);
@@ -249,27 +249,27 @@ var require_opentype = __commonJS({
249
249
  lengths[clcidx[i]] = clen;
250
250
  }
251
251
  tinf_build_tree(code_tree, lengths, 0, 19);
252
- for (num2 = 0; num2 < hlit + hdist; ) {
252
+ for (num3 = 0; num3 < hlit + hdist; ) {
253
253
  var sym = tinf_decode_symbol(d2, code_tree);
254
254
  switch (sym) {
255
255
  case 16:
256
- var prev = lengths[num2 - 1];
257
- for (length = tinf_read_bits(d2, 2, 3); length; --length) {
258
- lengths[num2++] = prev;
256
+ var prev = lengths[num3 - 1];
257
+ for (length2 = tinf_read_bits(d2, 2, 3); length2; --length2) {
258
+ lengths[num3++] = prev;
259
259
  }
260
260
  break;
261
261
  case 17:
262
- for (length = tinf_read_bits(d2, 3, 3); length; --length) {
263
- lengths[num2++] = 0;
262
+ for (length2 = tinf_read_bits(d2, 3, 3); length2; --length2) {
263
+ lengths[num3++] = 0;
264
264
  }
265
265
  break;
266
266
  case 18:
267
- for (length = tinf_read_bits(d2, 7, 11); length; --length) {
268
- lengths[num2++] = 0;
267
+ for (length2 = tinf_read_bits(d2, 7, 11); length2; --length2) {
268
+ lengths[num3++] = 0;
269
269
  }
270
270
  break;
271
271
  default:
272
- lengths[num2++] = sym;
272
+ lengths[num3++] = sym;
273
273
  break;
274
274
  }
275
275
  }
@@ -285,34 +285,34 @@ var require_opentype = __commonJS({
285
285
  if (sym < 256) {
286
286
  d2.dest[d2.destLen++] = sym;
287
287
  } else {
288
- var length, dist, offs2;
288
+ var length2, dist2, offs2;
289
289
  var i;
290
290
  sym -= 257;
291
- length = tinf_read_bits(d2, length_bits[sym], length_base[sym]);
292
- dist = tinf_decode_symbol(d2, dt);
293
- offs2 = d2.destLen - tinf_read_bits(d2, dist_bits[dist], dist_base[dist]);
294
- for (i = offs2; i < offs2 + length; ++i) {
291
+ length2 = tinf_read_bits(d2, length_bits[sym], length_base[sym]);
292
+ dist2 = tinf_decode_symbol(d2, dt);
293
+ offs2 = d2.destLen - tinf_read_bits(d2, dist_bits[dist2], dist_base[dist2]);
294
+ for (i = offs2; i < offs2 + length2; ++i) {
295
295
  d2.dest[d2.destLen++] = d2.dest[i];
296
296
  }
297
297
  }
298
298
  }
299
299
  }
300
300
  function tinf_inflate_uncompressed_block(d2) {
301
- var length, invlength;
301
+ var length2, invlength;
302
302
  var i;
303
303
  while (d2.bitcount > 8) {
304
304
  d2.sourceIndex--;
305
305
  d2.bitcount -= 8;
306
306
  }
307
- length = d2.source[d2.sourceIndex + 1];
308
- length = 256 * length + d2.source[d2.sourceIndex];
307
+ length2 = d2.source[d2.sourceIndex + 1];
308
+ length2 = 256 * length2 + d2.source[d2.sourceIndex];
309
309
  invlength = d2.source[d2.sourceIndex + 3];
310
310
  invlength = 256 * invlength + d2.source[d2.sourceIndex + 2];
311
- if (length !== (~invlength & 65535)) {
311
+ if (length2 !== (~invlength & 65535)) {
312
312
  return TINF_DATA_ERROR;
313
313
  }
314
314
  d2.sourceIndex += 4;
315
- for (i = length; i; --i) {
315
+ for (i = length2; i; --i) {
316
316
  d2.dest[d2.destLen++] = d2.source[d2.sourceIndex++];
317
317
  }
318
318
  d2.bitcount = 0;
@@ -657,7 +657,7 @@ var require_opentype = __commonJS({
657
657
  var check3 = { fail: fail3, argument, assert: argument };
658
658
  var LIMIT16 = 32768;
659
659
  var LIMIT32 = 2147483648;
660
- var decode = {};
660
+ var decode2 = {};
661
661
  var encode = {};
662
662
  var sizeOf = {};
663
663
  function constant(v) {
@@ -805,7 +805,7 @@ var require_opentype = __commonJS({
805
805
  sizeOf.NAME = sizeOf.CHARARRAY;
806
806
  encode.STRING = encode.CHARARRAY;
807
807
  sizeOf.STRING = sizeOf.CHARARRAY;
808
- decode.UTF8 = function(data, offset2, numBytes) {
808
+ decode2.UTF8 = function(data, offset2, numBytes) {
809
809
  var codePoints = [];
810
810
  var numChars = numBytes;
811
811
  for (var j = 0; j < numChars; j++, offset2 += 1) {
@@ -813,7 +813,7 @@ var require_opentype = __commonJS({
813
813
  }
814
814
  return String.fromCharCode.apply(null, codePoints);
815
815
  };
816
- decode.UTF16 = function(data, offset2, numBytes) {
816
+ decode2.UTF16 = function(data, offset2, numBytes) {
817
817
  var codePoints = [];
818
818
  var numChars = numBytes / 2;
819
819
  for (var j = 0; j < numChars; j++, offset2 += 2) {
@@ -875,7 +875,7 @@ var require_opentype = __commonJS({
875
875
  "\xC4\xC5\xC7\xC9\xD1\xD6\xDC\xE1\xE0\xE2\xE4\xE3\xE5\xE7\xE9\xE8\xEA\xEB\xED\xEC\xEE\xEF\xF1\xF3\xF2\xF4\xF6\xF5\xFA\xF9\xFB\xFC\u2020\xB0\xA2\xA3\xA7\u2022\xB6\xDF\xAE\xA9\u2122\xB4\xA8\u2260\xC6\xD8\u221E\xB1\u2264\u2265\xA5\xB5\u2202\u2211\u220F\u03C0\u222B\xAA\xBA\u03A9\xE6\xF8\xBF\xA1\xAC\u221A\u0192\u2248\u2206\xAB\xBB\u2026\xA0\xC0\xC3\xD5\u0152\u0153\u2013\u2014\u201C\u201D\u2018\u2019\xF7\u25CA\xFF\u0178\u011E\u011F\u0130\u0131\u015E\u015F\u2021\xB7\u201A\u201E\u2030\xC2\xCA\xC1\xCB\xC8\xCD\xCE\xCF\xCC\xD3\xD4\uF8FF\xD2\xDA\xDB\xD9\uF8A0\u02C6\u02DC\xAF\u02D8\u02D9\u02DA\xB8\u02DD\u02DB\u02C7"
876
876
  )
877
877
  };
878
- decode.MACSTRING = function(dataView, offset2, dataLength, encoding) {
878
+ decode2.MACSTRING = function(dataView, offset2, dataLength, encoding) {
879
879
  var table2 = eightBitMacEncodings[encoding];
880
880
  if (table2 === void 0) {
881
881
  return void 0;
@@ -1053,8 +1053,8 @@ var require_opentype = __commonJS({
1053
1053
  encode.DICT = function(m) {
1054
1054
  var d2 = [];
1055
1055
  var keys = Object.keys(m);
1056
- var length = keys.length;
1057
- for (var i = 0; i < length; i += 1) {
1056
+ var length2 = keys.length;
1057
+ for (var i = 0; i < length2; i += 1) {
1058
1058
  var k = parseInt(keys[i], 0);
1059
1059
  var v = m[k];
1060
1060
  d2 = d2.concat(encode.OPERAND(v.value, v.type));
@@ -1105,8 +1105,8 @@ var require_opentype = __commonJS({
1105
1105
  }
1106
1106
  }
1107
1107
  var d2 = [];
1108
- var length = ops.length;
1109
- for (var i = 0; i < length; i += 1) {
1108
+ var length2 = ops.length;
1109
+ for (var i = 0; i < length2; i += 1) {
1110
1110
  var op = ops[i];
1111
1111
  d2 = d2.concat(encode[op.type](op.value));
1112
1112
  }
@@ -1130,10 +1130,10 @@ var require_opentype = __commonJS({
1130
1130
  };
1131
1131
  encode.TABLE = function(table2) {
1132
1132
  var d2 = [];
1133
- var length = table2.fields.length;
1133
+ var length2 = table2.fields.length;
1134
1134
  var subtables = [];
1135
1135
  var subtableOffsets = [];
1136
- for (var i = 0; i < length; i += 1) {
1136
+ for (var i = 0; i < length2; i += 1) {
1137
1137
  var field = table2.fields[i];
1138
1138
  var encodingFunction = encode[field.type];
1139
1139
  check3.argument(encodingFunction !== void 0, "No encoding function for field type " + field.type + " (" + field.name + ")");
@@ -1162,8 +1162,8 @@ var require_opentype = __commonJS({
1162
1162
  };
1163
1163
  sizeOf.TABLE = function(table2) {
1164
1164
  var numBytes = 0;
1165
- var length = table2.fields.length;
1166
- for (var i = 0; i < length; i += 1) {
1165
+ var length2 = table2.fields.length;
1166
+ for (var i = 0; i < length2; i += 1) {
1167
1167
  var field = table2.fields[i];
1168
1168
  var sizeOfFunction = sizeOf[field.type];
1169
1169
  check3.argument(sizeOfFunction !== void 0, "No sizeOf function for field type " + field.type + " (" + field.name + ")");
@@ -1437,12 +1437,12 @@ var require_opentype = __commonJS({
1437
1437
  this.relativeOffset += 4;
1438
1438
  return v;
1439
1439
  };
1440
- Parser2.prototype.parseString = function(length) {
1440
+ Parser2.prototype.parseString = function(length2) {
1441
1441
  var dataView = this.data;
1442
1442
  var offset2 = this.offset + this.relativeOffset;
1443
1443
  var string = "";
1444
- this.relativeOffset += length;
1445
- for (var i = 0; i < length; i++) {
1444
+ this.relativeOffset += length2;
1445
+ for (var i = 0; i < length2; i++) {
1446
1446
  string += String.fromCharCode(dataView.getUint8(offset2 + i));
1447
1447
  }
1448
1448
  return string;
@@ -3988,9 +3988,9 @@ var require_opentype = __commonJS({
3988
3988
  var nRanges = parser.parseCard8();
3989
3989
  code2 = 1;
3990
3990
  for (var i$1 = 0; i$1 < nRanges; i$1 += 1) {
3991
- var first = parser.parseCard8();
3991
+ var first2 = parser.parseCard8();
3992
3992
  var nLeft = parser.parseCard8();
3993
- for (var j = first; j <= first + nLeft; j += 1) {
3993
+ for (var j = first2; j <= first2 + nLeft; j += 1) {
3994
3994
  enc[j] = code2;
3995
3995
  code2 += 1;
3996
3996
  }
@@ -4396,9 +4396,9 @@ var require_opentype = __commonJS({
4396
4396
  }
4397
4397
  } else if (format2 === 3) {
4398
4398
  var nRanges = parser.parseCard16();
4399
- var first = parser.parseCard16();
4400
- if (first !== 0) {
4401
- throw new Error("CFF Table CID Font FDSelect format 3 range has bad initial GID " + first);
4399
+ var first2 = parser.parseCard16();
4400
+ if (first2 !== 0) {
4401
+ throw new Error("CFF Table CID Font FDSelect format 3 range has bad initial GID " + first2);
4402
4402
  }
4403
4403
  var next;
4404
4404
  for (var iRange = 0; iRange < nRanges; iRange++) {
@@ -4410,10 +4410,10 @@ var require_opentype = __commonJS({
4410
4410
  if (next > nGlyphs) {
4411
4411
  throw new Error("CFF Table CID Font FDSelect format 3 range has bad GID " + next);
4412
4412
  }
4413
- for (; first < next; first++) {
4413
+ for (; first2 < next; first2++) {
4414
4414
  fdSelect.push(fdIndex);
4415
4415
  }
4416
- first = next;
4416
+ first2 = next;
4417
4417
  }
4418
4418
  if (next !== nGlyphs) {
4419
4419
  throw new Error("CFF Table CID Font FDSelect format 3 range has bad final GID " + next);
@@ -4887,8 +4887,8 @@ var require_opentype = __commonJS({
4887
4887
  for (var i = 0; i < numTags; i++) {
4888
4888
  var tag = "";
4889
4889
  var offset2 = start + p2.parseUShort();
4890
- var length = p2.parseUShort();
4891
- for (var j = offset2; j < offset2 + length; ++j) {
4890
+ var length2 = p2.parseUShort();
4891
+ for (var j = offset2; j < offset2 + length2; ++j) {
4892
4892
  tag += String.fromCharCode(data.getInt8(j));
4893
4893
  }
4894
4894
  tags.push(tag);
@@ -5690,9 +5690,9 @@ var require_opentype = __commonJS({
5690
5690
  if (encoding !== void 0 && language !== void 0) {
5691
5691
  var text3 = void 0;
5692
5692
  if (encoding === utf16) {
5693
- text3 = decode.UTF16(data, stringOffset + offset2, byteLength);
5693
+ text3 = decode2.UTF16(data, stringOffset + offset2, byteLength);
5694
5694
  } else {
5695
- text3 = decode.MACSTRING(data, stringOffset + offset2, byteLength, encoding);
5695
+ text3 = decode2.MACSTRING(data, stringOffset + offset2, byteLength, encoding);
5696
5696
  }
5697
5697
  if (text3) {
5698
5698
  var translations = name[property];
@@ -5716,13 +5716,13 @@ var require_opentype = __commonJS({
5716
5716
  }
5717
5717
  return result;
5718
5718
  }
5719
- function makeNameRecord(platformID, encodingID, languageID, nameID, length, offset2) {
5719
+ function makeNameRecord(platformID, encodingID, languageID, nameID, length2, offset2) {
5720
5720
  return new table.Record("NameRecord", [
5721
5721
  { name: "platformID", type: "USHORT", value: platformID },
5722
5722
  { name: "encodingID", type: "USHORT", value: encodingID },
5723
5723
  { name: "languageID", type: "USHORT", value: languageID },
5724
5724
  { name: "nameID", type: "USHORT", value: nameID },
5725
- { name: "length", type: "USHORT", value: length },
5725
+ { name: "length", type: "USHORT", value: length2 },
5726
5726
  { name: "offset", type: "USHORT", value: offset2 }
5727
5727
  ]);
5728
5728
  }
@@ -6538,7 +6538,7 @@ var require_opentype = __commonJS({
6538
6538
  var tag = p2.parseTag();
6539
6539
  var dataOffset = p2.parseULong();
6540
6540
  var dataLength = p2.parseULong();
6541
- var text3 = decode.UTF8(data, start + dataOffset, dataLength);
6541
+ var text3 = decode2.UTF8(data, start + dataOffset, dataLength);
6542
6542
  tags[tag] = text3;
6543
6543
  }
6544
6544
  return tags;
@@ -6578,12 +6578,12 @@ var require_opentype = __commonJS({
6578
6578
  sum %= Math.pow(2, 32);
6579
6579
  return sum;
6580
6580
  }
6581
- function makeTableRecord(tag, checkSum, offset2, length) {
6581
+ function makeTableRecord(tag, checkSum, offset2, length2) {
6582
6582
  return new table.Record("Table Record", [
6583
6583
  { name: "tag", type: "TAG", value: tag !== void 0 ? tag : "" },
6584
6584
  { name: "checkSum", type: "ULONG", value: checkSum !== void 0 ? checkSum : 0 },
6585
6585
  { name: "offset", type: "ULONG", value: offset2 !== void 0 ? offset2 : 0 },
6586
- { name: "length", type: "ULONG", value: length !== void 0 ? length : 0 }
6586
+ { name: "length", type: "ULONG", value: length2 !== void 0 ? length2 : 0 }
6587
6587
  ]);
6588
6588
  }
6589
6589
  function makeSfntTable(tables) {
@@ -7427,26 +7427,26 @@ var require_opentype = __commonJS({
7427
7427
  }
7428
7428
  return void 0;
7429
7429
  };
7430
- Substitution.prototype.add = function(feature, sub, script, language) {
7430
+ Substitution.prototype.add = function(feature, sub2, script, language) {
7431
7431
  if (/ss\d\d/.test(feature)) {
7432
- return this.addSingle(feature, sub, script, language);
7432
+ return this.addSingle(feature, sub2, script, language);
7433
7433
  }
7434
7434
  switch (feature) {
7435
7435
  case "aalt":
7436
7436
  case "salt":
7437
- if (typeof sub.by === "number") {
7438
- return this.addSingle(feature, sub, script, language);
7437
+ if (typeof sub2.by === "number") {
7438
+ return this.addSingle(feature, sub2, script, language);
7439
7439
  }
7440
- return this.addAlternate(feature, sub, script, language);
7440
+ return this.addAlternate(feature, sub2, script, language);
7441
7441
  case "dlig":
7442
7442
  case "liga":
7443
7443
  case "rlig":
7444
- return this.addLigature(feature, sub, script, language);
7444
+ return this.addLigature(feature, sub2, script, language);
7445
7445
  case "ccmp":
7446
- if (sub.by instanceof Array) {
7447
- return this.addMultiple(feature, sub, script, language);
7446
+ if (sub2.by instanceof Array) {
7447
+ return this.addMultiple(feature, sub2, script, language);
7448
7448
  }
7449
- return this.addLigature(feature, sub, script, language);
7449
+ return this.addLigature(feature, sub2, script, language);
7450
7450
  }
7451
7451
  return void 0;
7452
7452
  };
@@ -11419,10 +11419,10 @@ var require_opentype = __commonJS({
11419
11419
  var features = options ? this.updateFeatures(options.features) : this.defaultRenderOptions.features;
11420
11420
  bidi.applyFeatures(this, features);
11421
11421
  var indexes = bidi.getTextGlyphs(s);
11422
- var length = indexes.length;
11423
- var glyphs = new Array(length);
11422
+ var length2 = indexes.length;
11423
+ var glyphs = new Array(length2);
11424
11424
  var notdef = this.glyphs.get(0);
11425
- for (var i = 0; i < length; i += 1) {
11425
+ for (var i = 0; i < length2; i += 1) {
11426
11426
  glyphs[i] = this.glyphs.get(indexes[i]) || notdef;
11427
11427
  }
11428
11428
  return glyphs;
@@ -12011,8 +12011,8 @@ var require_opentype = __commonJS({
12011
12011
  var tag = parse2.getTag(data, p2);
12012
12012
  var checksum = parse2.getULong(data, p2 + 4);
12013
12013
  var offset2 = parse2.getULong(data, p2 + 8);
12014
- var length = parse2.getULong(data, p2 + 12);
12015
- tableEntries.push({ tag, checksum, offset: offset2, length, compression: false });
12014
+ var length2 = parse2.getULong(data, p2 + 12);
12015
+ tableEntries.push({ tag, checksum, offset: offset2, length: length2, compression: false });
12016
12016
  p2 += 16;
12017
12017
  }
12018
12018
  return tableEntries;
@@ -12360,8 +12360,8 @@ function invertRigid(m) {
12360
12360
  }
12361
12361
  function bounds2(regions) {
12362
12362
  let [x0, y0, x1, y1] = [Infinity, Infinity, -Infinity, -Infinity];
12363
- for (const ring of regions)
12364
- for (const [x2, y] of ring) {
12363
+ for (const ring2 of regions)
12364
+ for (const [x2, y] of ring2) {
12365
12365
  x0 = Math.min(x0, x2);
12366
12366
  y0 = Math.min(y0, y);
12367
12367
  x1 = Math.max(x1, x2);
@@ -12445,10 +12445,10 @@ var turn = (m, v) => [
12445
12445
  function spans(regions, from, dir) {
12446
12446
  const len = dir[0] * dir[0] + dir[1] * dir[1];
12447
12447
  const hits = [];
12448
- for (const ring of regions)
12449
- for (let i = 0, j = ring.length - 1; i < ring.length; j = i++) {
12450
- const a = ring[j];
12451
- const b = ring[i];
12448
+ for (const ring2 of regions)
12449
+ for (let i = 0, j = ring2.length - 1; i < ring2.length; j = i++) {
12450
+ const a = ring2[j];
12451
+ const b = ring2[i];
12452
12452
  const da = dir[0] * (a[1] - from[1]) - dir[1] * (a[0] - from[0]);
12453
12453
  const db = dir[0] * (b[1] - from[1]) - dir[1] * (b[0] - from[0]);
12454
12454
  if (da > 0 === db > 0) continue;
@@ -12464,8 +12464,8 @@ function shared(a, b, eps) {
12464
12464
  let i = 0;
12465
12465
  let j = 0;
12466
12466
  while (i + 1 < a.length && j + 1 < b.length) {
12467
- const length = Math.min(a[i + 1], b[j + 1]) - Math.max(a[i], b[j]);
12468
- if (length > eps) total += length;
12467
+ const length2 = Math.min(a[i + 1], b[j + 1]) - Math.max(a[i], b[j]);
12468
+ if (length2 > eps) total += length2;
12469
12469
  if (a[i + 1] < b[j + 1]) i += 2;
12470
12470
  else j += 2;
12471
12471
  }
@@ -12529,16 +12529,16 @@ function stacked(A, B, invA, eps, pitch, volume) {
12529
12529
  const depth = Math.min(A.thickness, Math.max(z0, z1)) - Math.max(0, Math.min(z0, z1));
12530
12530
  if (depth <= eps) return false;
12531
12531
  const moved = B.outline.map(
12532
- (ring) => ring.map(
12532
+ (ring2) => ring2.map(
12533
12533
  ([x2, y]) => [rel[0] * x2 + rel[1] * y + rel[3], rel[4] * x2 + rel[5] * y + rel[7]]
12534
12534
  )
12535
12535
  );
12536
12536
  const [ax0, ay0, ax1, ay1] = bounds2(A.outline);
12537
12537
  const [bx0, by0, bx1, by1] = bounds2(moved);
12538
- const rows = steps(Math.max(ay0, by0), Math.min(ay1, by1), eps, pitch);
12538
+ const rows2 = steps(Math.max(ay0, by0), Math.min(ay1, by1), eps, pitch);
12539
12539
  let across = 0;
12540
- for (const y of rows.at) {
12541
- across += shared(spans(A.outline, [0, y], [1, 0]), spans(moved, [0, y], [1, 0]), eps) * rows.size * depth;
12540
+ for (const y of rows2.at) {
12541
+ across += shared(spans(A.outline, [0, y], [1, 0]), spans(moved, [0, y], [1, 0]), eps) * rows2.size * depth;
12542
12542
  if (across > volume) return true;
12543
12543
  }
12544
12544
  const columns = steps(Math.max(ax0, bx0), Math.min(ax1, bx1), eps, pitch);
@@ -12903,15 +12903,15 @@ var FUNCTIONS = {
12903
12903
  const key = num(a[0], "lookup");
12904
12904
  const table = list(a[1], "lookup", c);
12905
12905
  if (!table.length) return void 0;
12906
- const rows = table.map((r) => [num(r[0], "lookup"), num(r[1], "lookup")]).sort((p2, q) => p2[0] - q[0]);
12907
- if (key <= rows[0][0]) return rows[0][1];
12908
- for (let i = 1; i < rows.length; i++)
12909
- if (key <= rows[i][0]) {
12910
- const [x0, y0] = rows[i - 1];
12911
- const [x1, y1] = rows[i];
12906
+ const rows2 = table.map((r) => [num(r[0], "lookup"), num(r[1], "lookup")]).sort((p2, q) => p2[0] - q[0]);
12907
+ if (key <= rows2[0][0]) return rows2[0][1];
12908
+ for (let i = 1; i < rows2.length; i++)
12909
+ if (key <= rows2[i][0]) {
12910
+ const [x0, y0] = rows2[i - 1];
12911
+ const [x1, y1] = rows2[i];
12912
12912
  return y0 + (key - x0) / (x1 - x0) * (y1 - y0);
12913
12913
  }
12914
- return rows[rows.length - 1][1];
12914
+ return rows2[rows2.length - 1][1];
12915
12915
  }),
12916
12916
  rands: def("min, max, count, seed", (a) => {
12917
12917
  const lo = num(a[0], "rands"), hi = num(a[1], "rands"), n2 = num(a[2], "rands");
@@ -13611,9 +13611,9 @@ var ScanlineHeap = class {
13611
13611
  if (this.data.length === 0)
13612
13612
  return null;
13613
13613
  const max = this.data[0];
13614
- const last = this.data.pop();
13614
+ const last2 = this.data.pop();
13615
13615
  if (this.data.length > 0) {
13616
- this.data[0] = last;
13616
+ this.data[0] = last2;
13617
13617
  this.siftDown(0);
13618
13618
  }
13619
13619
  return max;
@@ -13635,15 +13635,15 @@ var ScanlineHeap = class {
13635
13635
  this.data[index] = val;
13636
13636
  }
13637
13637
  siftDown(index) {
13638
- const length = this.data.length;
13638
+ const length2 = this.data.length;
13639
13639
  const val = this.data[index];
13640
13640
  while (true) {
13641
13641
  const left = (index << 1) + 1;
13642
- if (left >= length)
13642
+ if (left >= length2)
13643
13643
  break;
13644
13644
  const right = left + 1;
13645
13645
  let child = left;
13646
- if (right < length && this.data[right] > this.data[left])
13646
+ if (right < length2 && this.data[right] > this.data[left])
13647
13647
  child = right;
13648
13648
  if (this.data[child] <= val)
13649
13649
  break;
@@ -15946,13 +15946,13 @@ var ClipperBase = class _ClipperBase {
15946
15946
  static isVerySmallTriangle(op) {
15947
15947
  return op.next.next === op.prev && (_ClipperBase.ptsReallyClose(op.prev.pt, op.next.pt) || _ClipperBase.ptsReallyClose(op.pt, op.next.pt) || _ClipperBase.ptsReallyClose(op.pt, op.prev.pt));
15948
15948
  }
15949
- static buildPath(op, reverse, isOpen, path) {
15949
+ static buildPath(op, reverse2, isOpen, path) {
15950
15950
  if (op === null || op.next === op || !isOpen && op.next === op.prev)
15951
15951
  return false;
15952
15952
  path.length = 0;
15953
15953
  let lastPt;
15954
15954
  let op2;
15955
- if (reverse) {
15955
+ if (reverse2) {
15956
15956
  lastPt = op.pt;
15957
15957
  op2 = op.prev;
15958
15958
  } else {
@@ -15966,7 +15966,7 @@ var ClipperBase = class _ClipperBase {
15966
15966
  lastPt = op2.pt;
15967
15967
  path.push(lastPt);
15968
15968
  }
15969
- if (reverse) {
15969
+ if (reverse2) {
15970
15970
  op2 = op2.prev;
15971
15971
  } else {
15972
15972
  op2 = op2.next;
@@ -16575,12 +16575,12 @@ var ClipperOffset = class _ClipperOffset {
16575
16575
  static hypotenuse(x2, y) {
16576
16576
  return Math.sqrt(x2 * x2 + y * y);
16577
16577
  }
16578
- static normalizeVector(vec) {
16579
- const h = _ClipperOffset.hypotenuse(vec.x, vec.y);
16578
+ static normalizeVector(vec2) {
16579
+ const h = _ClipperOffset.hypotenuse(vec2.x, vec2.y);
16580
16580
  if (_ClipperOffset.almostZero(h))
16581
16581
  return { x: 0, y: 0 };
16582
16582
  const inverseHypot = 1 / h;
16583
- return { x: vec.x * inverseHypot, y: vec.y * inverseHypot };
16583
+ return { x: vec2.x * inverseHypot, y: vec2.y * inverseHypot };
16584
16584
  }
16585
16585
  static getAvgUnitVector(vec1, vec2) {
16586
16586
  return _ClipperOffset.normalizeVector({ x: vec1.x + vec2.x, y: vec1.y + vec2.y });
@@ -16653,22 +16653,22 @@ var ClipperOffset = class _ClipperOffset {
16653
16653
  this.pathOut.push(pt2);
16654
16654
  }
16655
16655
  doSquare(path, j, k) {
16656
- let vec;
16656
+ let vec2;
16657
16657
  if (j === k) {
16658
- vec = { x: this.normals[j].y, y: -this.normals[j].x };
16658
+ vec2 = { x: this.normals[j].y, y: -this.normals[j].x };
16659
16659
  } else {
16660
- vec = _ClipperOffset.getAvgUnitVector({ x: -this.normals[k].y, y: this.normals[k].x }, { x: this.normals[j].y, y: -this.normals[j].x });
16660
+ vec2 = _ClipperOffset.getAvgUnitVector({ x: -this.normals[k].y, y: this.normals[k].x }, { x: this.normals[j].y, y: -this.normals[j].x });
16661
16661
  }
16662
16662
  const absDelta = Math.abs(this.groupDelta);
16663
16663
  let ptQ = { x: path[j].x, y: path[j].y, z: path[j].z || 0 };
16664
- ptQ = _ClipperOffset.translatePoint(ptQ, absDelta * vec.x, absDelta * vec.y);
16665
- const pt1 = _ClipperOffset.translatePoint(ptQ, this.groupDelta * vec.y, this.groupDelta * -vec.x);
16666
- const pt2 = _ClipperOffset.translatePoint(ptQ, this.groupDelta * -vec.y, this.groupDelta * vec.x);
16664
+ ptQ = _ClipperOffset.translatePoint(ptQ, absDelta * vec2.x, absDelta * vec2.y);
16665
+ const pt1 = _ClipperOffset.translatePoint(ptQ, this.groupDelta * vec2.y, this.groupDelta * -vec2.x);
16666
+ const pt2 = _ClipperOffset.translatePoint(ptQ, this.groupDelta * -vec2.y, this.groupDelta * vec2.x);
16667
16667
  const pt3 = this.getPerpendicD(path[k], this.normals[k]);
16668
16668
  if (j === k) {
16669
16669
  const pt4 = {
16670
- x: pt3.x + vec.x * this.groupDelta,
16671
- y: pt3.y + vec.y * this.groupDelta
16670
+ x: pt3.x + vec2.x * this.groupDelta,
16671
+ y: pt3.y + vec2.y * this.groupDelta
16672
16672
  };
16673
16673
  const pt = _ClipperOffset.intersectPoint(pt1, pt2, pt3, pt4);
16674
16674
  pt.z = ptQ.z;
@@ -16690,7 +16690,7 @@ var ClipperOffset = class _ClipperOffset {
16690
16690
  z: path[j].z || 0
16691
16691
  });
16692
16692
  }
16693
- doRound(path, j, k, angle) {
16693
+ doRound(path, j, k, angle2) {
16694
16694
  if (this.deltaCallback !== null) {
16695
16695
  const absDelta = Math.abs(this.groupDelta);
16696
16696
  const arcTol = this.arcTolerance > 0.01 ? this.arcTolerance : absDelta * _ClipperOffset.arc_const;
@@ -16711,7 +16711,7 @@ var ClipperOffset = class _ClipperOffset {
16711
16711
  y: Math.round(pt.y + offsetVec.y),
16712
16712
  z: ptz
16713
16713
  });
16714
- const steps2 = Math.ceil(this.stepsPerRad * Math.abs(angle));
16714
+ const steps2 = Math.ceil(this.stepsPerRad * Math.abs(angle2));
16715
16715
  for (let i = 1; i < steps2; i++) {
16716
16716
  offsetVec = {
16717
16717
  x: offsetVec.x * this.stepCos - this.stepSin * offsetVec.y,
@@ -16998,6 +16998,7 @@ function inflatePaths(paths, delta, joinType, endType, miterLimit = 2, arcTolera
16998
16998
 
16999
16999
  // src/geometry.ts
17000
17000
  var SCALE = 1e4;
17001
+ var IDENTITY = [1, 0, 0, 1, 0, 0];
17001
17002
  function emptyShape() {
17002
17003
  return { layers: /* @__PURE__ */ new Map(), parts: [] };
17003
17004
  }
@@ -17013,17 +17014,36 @@ function isEmpty(s) {
17013
17014
  return true;
17014
17015
  }
17015
17016
  var to64 = (polys) => polys.map((p2) => p2.map(([x2, y]) => ({ x: Math.round(x2 * SCALE), y: Math.round(y * SCALE) })));
17017
+ function ring(p2) {
17018
+ const straight = (a, b, c) => (b.x - a.x) * (c.y - b.y) - (b.y - a.y) * (c.x - b.x) === 0;
17019
+ const out = [];
17020
+ for (const q of p2) {
17021
+ while (out.length >= 2 && straight(out[out.length - 2], out[out.length - 1], q)) out.pop();
17022
+ const last2 = out[out.length - 1];
17023
+ if (!last2 || last2.x !== q.x || last2.y !== q.y) out.push(q);
17024
+ }
17025
+ for (let changed = true; changed && out.length >= 3; ) {
17026
+ const n2 = out.length;
17027
+ changed = true;
17028
+ if (out[n2 - 1].x === out[0].x && out[n2 - 1].y === out[0].y) out.pop();
17029
+ else if (straight(out[n2 - 2], out[n2 - 1], out[0])) out.pop();
17030
+ else if (straight(out[n2 - 1], out[0], out[1])) out.shift();
17031
+ else changed = false;
17032
+ }
17033
+ return out;
17034
+ }
17035
+ var rings = (polys) => to64(polys).map(ring);
17016
17036
  var from64 = (paths) => paths.filter((p2) => p2.length >= 2).map((p2) => p2.map((q) => [q.x / SCALE, q.y / SCALE]));
17017
17037
  function union2(regions, fill = "nonzero") {
17018
17038
  if (!regions.length) return [];
17019
17039
  const rule = fill === "evenodd" ? FillRule.EvenOdd : FillRule.NonZero;
17020
- return from64(union(to64(regions), rule)).filter((p2) => p2.length >= 3);
17040
+ return from64(union(rings(regions), rule)).filter((p2) => p2.length >= 3);
17021
17041
  }
17022
17042
  function boolean(type, a, b) {
17023
17043
  if (!a.length) return [];
17024
17044
  const c = new Clipper64();
17025
- c.addSubject(to64(a));
17026
- if (b.length) c.addClip(to64(b));
17045
+ c.addSubject(rings(a));
17046
+ if (b.length) c.addClip(rings(b));
17027
17047
  const out = [];
17028
17048
  c.execute(type, FillRule.NonZero, out);
17029
17049
  return from64(out).filter((p2) => p2.length >= 3);
@@ -17033,25 +17053,120 @@ var intersection = (a, b) => boolean(ClipType.Intersection, a, b);
17033
17053
  function clipLines(lines, region, keep) {
17034
17054
  if (!lines.length) return [];
17035
17055
  if (!region.length) return keep === "outside" ? lines : [];
17036
- const c = new Clipper64();
17037
- c.addOpenSubject(to64(lines));
17038
- c.addClip(to64(region));
17039
- const closed = [];
17040
- const open = [];
17041
- c.execute(
17042
- keep === "inside" ? ClipType.Intersection : ClipType.Difference,
17043
- FillRule.NonZero,
17044
- closed,
17045
- open
17046
- );
17047
- return from64(open);
17056
+ const edges = [];
17057
+ for (const r of region)
17058
+ for (let i = 0; i < r.length; i++) {
17059
+ const a = r[i], b = r[(i + 1) % r.length];
17060
+ if (a[0] !== b[0] || a[1] !== b[1]) edges.push([a, b]);
17061
+ }
17062
+ if (!edges.length) return keep === "outside" ? lines : [];
17063
+ const box = bounds(region);
17064
+ const size = Math.max(box[2] - box[0], box[3] - box[1], 1e-6) / Math.max(1, Math.sqrt(edges.length));
17065
+ const cell = (v) => Math.floor(v / size);
17066
+ const cells = /* @__PURE__ */ new Map();
17067
+ const rows2 = /* @__PURE__ */ new Map();
17068
+ const add4 = (m, k, i) => {
17069
+ const l = m.get(k);
17070
+ if (!l) m.set(k, [i]);
17071
+ else if (l[l.length - 1] !== i) l.push(i);
17072
+ };
17073
+ edges.forEach(([a, b], i) => {
17074
+ const n2 = Math.max(1, Math.ceil(Math.hypot(b[0] - a[0], b[1] - a[1]) / size * 2));
17075
+ for (let k = 0; k <= n2; k++) {
17076
+ const x2 = a[0] + (b[0] - a[0]) * k / n2, y = a[1] + (b[1] - a[1]) * k / n2;
17077
+ for (const dx of [-1, 0, 1])
17078
+ for (const dy of [-1, 0, 1]) add4(cells, `${cell(x2) + dx},${cell(y) + dy}`, i);
17079
+ }
17080
+ for (let y = cell(Math.min(a[1], b[1])); y <= cell(Math.max(a[1], b[1])); y++) add4(rows2, y, i);
17081
+ });
17082
+ const near = (a, b) => {
17083
+ const out2 = /* @__PURE__ */ new Set();
17084
+ const n2 = Math.max(1, Math.ceil(Math.hypot(b[0] - a[0], b[1] - a[1]) / size * 2));
17085
+ for (let k = 0; k <= n2; k++) {
17086
+ const x2 = a[0] + (b[0] - a[0]) * k / n2, y = a[1] + (b[1] - a[1]) * k / n2;
17087
+ for (const i of cells.get(`${cell(x2)},${cell(y)}`) ?? []) out2.add(i);
17088
+ }
17089
+ return out2;
17090
+ };
17091
+ const edge = 0.5 / SCALE;
17092
+ const within = (p2) => {
17093
+ for (const i of cells.get(`${cell(p2[0])},${cell(p2[1])}`) ?? []) {
17094
+ const [a, b] = edges[i];
17095
+ const dx = b[0] - a[0], dy = b[1] - a[1];
17096
+ const t = Math.max(
17097
+ 0,
17098
+ Math.min(1, ((p2[0] - a[0]) * dx + (p2[1] - a[1]) * dy) / (dx * dx + dy * dy))
17099
+ );
17100
+ if (Math.hypot(p2[0] - a[0] - t * dx, p2[1] - a[1] - t * dy) <= edge) return void 0;
17101
+ }
17102
+ let wn = 0;
17103
+ for (const i of rows2.get(cell(p2[1])) ?? []) {
17104
+ const [a, b] = edges[i];
17105
+ const side = (b[0] - a[0]) * (p2[1] - a[1]) - (p2[0] - a[0]) * (b[1] - a[1]);
17106
+ if (a[1] <= p2[1]) {
17107
+ if (b[1] > p2[1] && side > 0) wn++;
17108
+ } else if (b[1] <= p2[1] && side < 0) wn--;
17109
+ }
17110
+ return wn !== 0;
17111
+ };
17112
+ const r4 = (v) => Math.round(v * SCALE) / SCALE;
17113
+ const out = [];
17114
+ for (const line of lines) {
17115
+ let cur = null;
17116
+ const flush = () => {
17117
+ if (cur && cur.length >= 2) out.push(cur);
17118
+ cur = null;
17119
+ };
17120
+ for (let k = 1; k < line.length; k++) {
17121
+ const s = line[k - 1], e = line[k];
17122
+ const dx = e[0] - s[0], dy = e[1] - s[1];
17123
+ if (!dx && !dy) continue;
17124
+ const ts = [0, 1];
17125
+ for (const i of near(s, e)) {
17126
+ const [a, b] = edges[i];
17127
+ const ex = b[0] - a[0], ey = b[1] - a[1];
17128
+ const den = dx * ey - dy * ex;
17129
+ if (Math.abs(den) > 1e-15) {
17130
+ const t = ((a[0] - s[0]) * ey - (a[1] - s[1]) * ex) / den;
17131
+ const u = ((a[0] - s[0]) * dy - (a[1] - s[1]) * dx) / den;
17132
+ if (t > 0 && t < 1 && u >= 0 && u <= 1) ts.push(t);
17133
+ } else {
17134
+ const l2 = dx * dx + dy * dy;
17135
+ for (const q of [a, b]) {
17136
+ const t = ((q[0] - s[0]) * dx + (q[1] - s[1]) * dy) / l2;
17137
+ const off = Math.abs((q[0] - s[0]) * dy - (q[1] - s[1]) * dx) / Math.sqrt(l2);
17138
+ if (t > 0 && t < 1 && off <= edge) ts.push(t);
17139
+ }
17140
+ }
17141
+ }
17142
+ ts.sort((x2, y) => x2 - y);
17143
+ for (let j = 1; j < ts.length; j++) {
17144
+ if (ts[j] - ts[j - 1] < 1e-12) continue;
17145
+ const p0 = [r4(s[0] + dx * ts[j - 1]), r4(s[1] + dy * ts[j - 1])];
17146
+ const p1 = [r4(s[0] + dx * ts[j]), r4(s[1] + dy * ts[j])];
17147
+ const tm = (ts[j - 1] + ts[j]) / 2;
17148
+ const inside2 = within([s[0] + dx * tm, s[1] + dy * tm]);
17149
+ if (inside2 !== void 0 && inside2 === (keep === "inside")) {
17150
+ const last2 = cur ? cur[cur.length - 1] : void 0;
17151
+ if (cur && last2 && last2[0] === p0[0] && last2[1] === p0[1]) {
17152
+ if (p1[0] !== last2[0] || p1[1] !== last2[1]) cur.push(p1);
17153
+ } else {
17154
+ flush();
17155
+ cur = [p0, p1];
17156
+ }
17157
+ } else flush();
17158
+ }
17159
+ }
17160
+ flush();
17161
+ }
17162
+ return out;
17048
17163
  }
17049
17164
  function offset(regions, delta, join4 = "round", arcTolerance = 0.01) {
17050
17165
  if (!regions.length) return [];
17051
17166
  if (delta === 0) return union2(regions);
17052
17167
  const jt = join4 === "round" ? JoinType.Round : join4 === "square" ? JoinType.Square : JoinType.Miter;
17053
17168
  const out = inflatePaths(
17054
- to64(union2(regions)),
17169
+ rings(union2(regions)),
17055
17170
  delta * SCALE,
17056
17171
  jt,
17057
17172
  EndType.Polygon,
@@ -17076,7 +17191,7 @@ function pieces(regions) {
17076
17191
  if (!regions.length) return [];
17077
17192
  const tree = new PolyTree64();
17078
17193
  const c = new Clipper64();
17079
- c.addSubject(to64(regions));
17194
+ c.addSubject(rings(regions));
17080
17195
  c.execute(ClipType.Union, FillRule.NonZero, tree);
17081
17196
  const out = [];
17082
17197
  const walk2 = (node) => {
@@ -17100,6 +17215,16 @@ function area2(p2) {
17100
17215
  a += (p2[j][0] + p2[i][0]) * (p2[j][1] - p2[i][1]);
17101
17216
  return -a / 2;
17102
17217
  }
17218
+ function multiply2(m, n2) {
17219
+ return [
17220
+ m[0] * n2[0] + m[2] * n2[1],
17221
+ m[1] * n2[0] + m[3] * n2[1],
17222
+ m[0] * n2[2] + m[2] * n2[3],
17223
+ m[1] * n2[2] + m[3] * n2[3],
17224
+ m[0] * n2[4] + m[2] * n2[5] + m[4],
17225
+ m[1] * n2[4] + m[3] * n2[5] + m[5]
17226
+ ];
17227
+ }
17103
17228
  function apply2(m, [x2, y]) {
17104
17229
  return [m[0] * x2 + m[2] * y + m[4], m[1] * x2 + m[3] * y + m[5]];
17105
17230
  }
@@ -17233,9 +17358,9 @@ function roundedRect(w, h, r, segs) {
17233
17358
  }
17234
17359
 
17235
17360
  // src/joinery.ts
17236
- function fingerCount(length, finger) {
17237
- let n2 = Math.round(length / finger);
17238
- if (n2 % 2 === 0) n2 += length / finger > n2 ? 1 : -1;
17361
+ function fingerCount(length2, finger) {
17362
+ let n2 = Math.round(length2 / finger);
17363
+ if (n2 % 2 === 0) n2 += length2 / finger > n2 ? 1 : -1;
17239
17364
  return Math.max(3, n2);
17240
17365
  }
17241
17366
  var rect = (x0, y0, x1, y1) => [
@@ -17244,10 +17369,10 @@ var rect = (x0, y0, x1, y1) => [
17244
17369
  [x1, y1],
17245
17370
  [x0, y1]
17246
17371
  ];
17247
- function edgeNotches(length, edge, t, finger) {
17372
+ function edgeNotches(length2, edge, t, finger) {
17248
17373
  if (edge === "flat") return [];
17249
- const n2 = fingerCount(length, finger);
17250
- const seg = length / n2;
17374
+ const n2 = fingerCount(length2, finger);
17375
+ const seg = length2 / n2;
17251
17376
  const out = [];
17252
17377
  for (let k = 0; k < n2; k++) {
17253
17378
  const notch = edge === "out" ? k % 2 === 1 : k % 2 === 0;
@@ -17256,7 +17381,7 @@ function edgeNotches(length, edge, t, finger) {
17256
17381
  return out;
17257
17382
  }
17258
17383
  function fingerRect(w, h, edges, t, finger) {
17259
- const place = [
17384
+ const place2 = [
17260
17385
  ([x2, y]) => [x2, y],
17261
17386
  ([x2, y]) => [w - y, x2],
17262
17387
  ([x2, y]) => [w - x2, h - y],
@@ -17265,13 +17390,13 @@ function fingerRect(w, h, edges, t, finger) {
17265
17390
  const lengths = [w, h, w, h];
17266
17391
  const notches = [];
17267
17392
  edges.forEach((e, i) => {
17268
- for (const n2 of edgeNotches(lengths[i], e, t, finger)) notches.push(n2.map(place[i]));
17393
+ for (const n2 of edgeNotches(lengths[i], e, t, finger)) notches.push(n2.map(place2[i]));
17269
17394
  });
17270
17395
  return difference2([rect(0, 0, w, h)], notches);
17271
17396
  }
17272
- function fingerHoles(length, edge, t, finger) {
17273
- const n2 = fingerCount(length, finger);
17274
- const seg = length / n2;
17397
+ function fingerHoles(length2, edge, t, finger) {
17398
+ const n2 = fingerCount(length2, finger);
17399
+ const seg = length2 / n2;
17275
17400
  const out = [];
17276
17401
  for (let k = 0; k < n2; k++) {
17277
17402
  const tab = edge === "out" ? k % 2 === 0 : k % 2 === 1;
@@ -17279,8 +17404,8 @@ function fingerHoles(length, edge, t, finger) {
17279
17404
  }
17280
17405
  return out;
17281
17406
  }
17282
- function tslot(d2, length, nutW, nutH, nutAt) {
17283
- const slot = rect(-d2 / 2, -1, d2 / 2, length);
17407
+ function tslot(d2, length2, nutW, nutH, nutAt) {
17408
+ const slot = rect(-d2 / 2, -1, d2 / 2, length2);
17284
17409
  const nut = rect(-nutW / 2, nutAt, nutW / 2, nutAt + nutH);
17285
17410
  return [slot, nut];
17286
17411
  }
@@ -17818,7 +17943,7 @@ var Parser = class _Parser {
17818
17943
  return { kind: "list", items: [], pos: open.pos };
17819
17944
  }
17820
17945
  if (!this.isK("for") && !this.isK("if") && !this.isK("each") && !(this.isK("let") && this.isP("(", 1)) && !(this.isP("(") && (this.isK("for", 1) || this.isK("if", 1)))) {
17821
- const first = this.expr();
17946
+ const first2 = this.expr();
17822
17947
  if (this.isP(":")) {
17823
17948
  this.next();
17824
17949
  let step = null;
@@ -17829,9 +17954,9 @@ var Parser = class _Parser {
17829
17954
  end = this.expr();
17830
17955
  }
17831
17956
  this.expectP("]");
17832
- return { kind: "range", start: first, step, end, pos: open.pos };
17957
+ return { kind: "range", start: first2, step, end, pos: open.pos };
17833
17958
  }
17834
- const items2 = [{ kind: "item", expr: first }];
17959
+ const items2 = [{ kind: "item", expr: first2 }];
17835
17960
  return this.listRest(items2, open.pos);
17836
17961
  }
17837
17962
  return this.listRest([], open.pos);
@@ -18558,7 +18683,7 @@ function flatten(cmds, tolerance = 0.02) {
18558
18683
  const open = [];
18559
18684
  let cur = [];
18560
18685
  let start = [0, 0];
18561
- let last = [0, 0];
18686
+ let last2 = [0, 0];
18562
18687
  const finish = (close) => {
18563
18688
  if (cur.length >= 2) (close ? closed : open).push(cur);
18564
18689
  cur = [];
@@ -18567,13 +18692,13 @@ function flatten(cmds, tolerance = 0.02) {
18567
18692
  for (const c of cmds) {
18568
18693
  if (c.type === "M") {
18569
18694
  finish(false);
18570
- start = last = [c.x, c.y];
18571
- cur = [last];
18695
+ start = last2 = [c.x, c.y];
18696
+ cur = [last2];
18572
18697
  } else if (c.type === "L") {
18573
- last = [c.x, c.y];
18574
- cur.push(last);
18698
+ last2 = [c.x, c.y];
18699
+ cur.push(last2);
18575
18700
  } else if (c.type === "Q") {
18576
- const [x0, y0] = last;
18701
+ const [x0, y0] = last2;
18577
18702
  const n2 = steps2(Math.hypot(c.x1 - x0, c.y1 - y0) + Math.hypot(c.x - c.x1, c.y - c.y1));
18578
18703
  for (let i = 1; i <= n2; i++) {
18579
18704
  const t = i / n2, u = 1 - t;
@@ -18582,9 +18707,9 @@ function flatten(cmds, tolerance = 0.02) {
18582
18707
  u * u * y0 + 2 * u * t * c.y1 + t * t * c.y
18583
18708
  ]);
18584
18709
  }
18585
- last = [c.x, c.y];
18710
+ last2 = [c.x, c.y];
18586
18711
  } else if (c.type === "C") {
18587
- const [x0, y0] = last;
18712
+ const [x0, y0] = last2;
18588
18713
  const n2 = steps2(
18589
18714
  Math.hypot(c.x1 - x0, c.y1 - y0) + Math.hypot(c.x2 - c.x1, c.y2 - c.y1) + Math.hypot(c.x - c.x2, c.y - c.y2)
18590
18715
  );
@@ -18595,17 +18720,17 @@ function flatten(cmds, tolerance = 0.02) {
18595
18720
  u * u * u * y0 + 3 * u * u * t * c.y1 + 3 * u * t * t * c.y2 + t * t * t * c.y
18596
18721
  ]);
18597
18722
  }
18598
- last = [c.x, c.y];
18723
+ last2 = [c.x, c.y];
18599
18724
  } else {
18600
18725
  finish(true);
18601
- last = start;
18726
+ last2 = start;
18602
18727
  cur = [start];
18603
18728
  }
18604
18729
  }
18605
18730
  finish(false);
18606
18731
  return { closed, open };
18607
18732
  }
18608
- function parseSvgPath(d2) {
18733
+ function parseSvgPath(d2, arcStep = Math.PI / 2, onError) {
18609
18734
  const isCommand = (t) => /^[a-zA-Z]$/.test(t);
18610
18735
  const tokens = d2.match(/[a-zA-Z]|[-+]?(?:\d+\.?\d*|\.\d+)(?:[eE][-+]?\d+)?/g) ?? [];
18611
18736
  const out = [];
@@ -18614,7 +18739,7 @@ function parseSvgPath(d2) {
18614
18739
  let x2 = 0, y = 0, sx = 0, sy = 0;
18615
18740
  let cx = 0, cy = 0, qx = 0, qy = 0;
18616
18741
  let prev = "";
18617
- const num2 = () => {
18742
+ const num3 = () => {
18618
18743
  const t = tokens[i++];
18619
18744
  if (t === void 0 || isCommand(t)) throw new Error(`Bad path data near "${t ?? "end"}"`);
18620
18745
  return Number(t);
@@ -18629,78 +18754,86 @@ function parseSvgPath(d2) {
18629
18754
  i++;
18630
18755
  return Number(t);
18631
18756
  };
18632
- while (i < tokens.length) {
18633
- if (isCommand(tokens[i])) cmd = tokens[i++];
18634
- else if (!cmd) throw new Error("Path data must start with a command");
18635
- else if (cmd === "Z" || cmd === "z")
18636
- throw new Error(`Bad path data near "${tokens[i]}": Z takes no numbers`);
18637
- const rel = cmd === cmd.toLowerCase();
18638
- const C = cmd.toUpperCase();
18639
- const ox = rel ? x2 : 0, oy = rel ? y : 0;
18640
- if (C === "M") {
18641
- x2 = ox + num2();
18642
- y = oy + num2();
18643
- sx = x2;
18644
- sy = y;
18645
- out.push({ type: "M", x: x2, y });
18646
- cmd = rel ? "l" : "L";
18647
- } else if (C === "L") {
18648
- x2 = ox + num2();
18649
- y = oy + num2();
18650
- out.push({ type: "L", x: x2, y });
18651
- } else if (C === "H") {
18652
- x2 = ox + num2();
18653
- out.push({ type: "L", x: x2, y });
18654
- } else if (C === "V") {
18655
- y = oy + num2();
18656
- out.push({ type: "L", x: x2, y });
18657
- } else if (C === "C" || C === "S") {
18658
- let x1, y1;
18659
- if (C === "C") {
18660
- x1 = ox + num2();
18661
- y1 = oy + num2();
18662
- } else {
18663
- const smooth = prev === "C" || prev === "S";
18664
- x1 = smooth ? 2 * x2 - cx : x2;
18665
- y1 = smooth ? 2 * y - cy : y;
18666
- }
18667
- const x22 = ox + num2(), y2 = oy + num2();
18668
- x2 = ox + num2();
18669
- y = oy + num2();
18670
- cx = x22;
18671
- cy = y2;
18672
- out.push({ type: "C", x1, y1, x2: x22, y2, x: x2, y });
18673
- } else if (C === "Q" || C === "T") {
18674
- let x1, y1;
18675
- if (C === "Q") {
18676
- x1 = ox + num2();
18677
- y1 = oy + num2();
18678
- } else {
18679
- const smooth = prev === "Q" || prev === "T";
18680
- x1 = smooth ? 2 * x2 - qx : x2;
18681
- y1 = smooth ? 2 * y - qy : y;
18682
- }
18683
- x2 = ox + num2();
18684
- y = oy + num2();
18685
- qx = x1;
18686
- qy = y1;
18687
- out.push({ type: "Q", x1, y1, x: x2, y });
18688
- } else if (C === "A") {
18689
- const rx = num2(), ry = num2(), rot = num2(), large = flag(), sweep = flag();
18690
- const x22 = ox + num2(), y2 = oy + num2();
18691
- out.push(...arcToCubics(x2, y, rx, ry, rot, large, sweep, x22, y2));
18692
- x2 = x22;
18693
- y = y2;
18694
- } else if (C === "Z") {
18695
- out.push({ type: "Z" });
18696
- x2 = sx;
18697
- y = sy;
18698
- } else throw new Error(`Unknown path command "${cmd}"`);
18699
- prev = C;
18757
+ try {
18758
+ readCommands();
18759
+ } catch (e) {
18760
+ if (!onError) throw e;
18761
+ onError(e.message);
18700
18762
  }
18701
18763
  return out;
18764
+ function readCommands() {
18765
+ while (i < tokens.length) {
18766
+ if (isCommand(tokens[i])) cmd = tokens[i++];
18767
+ else if (!cmd) throw new Error("Path data must start with a command");
18768
+ else if (cmd === "Z" || cmd === "z")
18769
+ throw new Error(`Bad path data near "${tokens[i]}": Z takes no numbers`);
18770
+ const rel = cmd === cmd.toLowerCase();
18771
+ const C = cmd.toUpperCase();
18772
+ const ox = rel ? x2 : 0, oy = rel ? y : 0;
18773
+ if (C === "M") {
18774
+ x2 = ox + num3();
18775
+ y = oy + num3();
18776
+ sx = x2;
18777
+ sy = y;
18778
+ out.push({ type: "M", x: x2, y });
18779
+ cmd = rel ? "l" : "L";
18780
+ } else if (C === "L") {
18781
+ x2 = ox + num3();
18782
+ y = oy + num3();
18783
+ out.push({ type: "L", x: x2, y });
18784
+ } else if (C === "H") {
18785
+ x2 = ox + num3();
18786
+ out.push({ type: "L", x: x2, y });
18787
+ } else if (C === "V") {
18788
+ y = oy + num3();
18789
+ out.push({ type: "L", x: x2, y });
18790
+ } else if (C === "C" || C === "S") {
18791
+ let x1, y1;
18792
+ if (C === "C") {
18793
+ x1 = ox + num3();
18794
+ y1 = oy + num3();
18795
+ } else {
18796
+ const smooth = prev === "C" || prev === "S";
18797
+ x1 = smooth ? 2 * x2 - cx : x2;
18798
+ y1 = smooth ? 2 * y - cy : y;
18799
+ }
18800
+ const x22 = ox + num3(), y2 = oy + num3();
18801
+ x2 = ox + num3();
18802
+ y = oy + num3();
18803
+ cx = x22;
18804
+ cy = y2;
18805
+ out.push({ type: "C", x1, y1, x2: x22, y2, x: x2, y });
18806
+ } else if (C === "Q" || C === "T") {
18807
+ let x1, y1;
18808
+ if (C === "Q") {
18809
+ x1 = ox + num3();
18810
+ y1 = oy + num3();
18811
+ } else {
18812
+ const smooth = prev === "Q" || prev === "T";
18813
+ x1 = smooth ? 2 * x2 - qx : x2;
18814
+ y1 = smooth ? 2 * y - qy : y;
18815
+ }
18816
+ x2 = ox + num3();
18817
+ y = oy + num3();
18818
+ qx = x1;
18819
+ qy = y1;
18820
+ out.push({ type: "Q", x1, y1, x: x2, y });
18821
+ } else if (C === "A") {
18822
+ const rx = num3(), ry = num3(), rot2 = num3(), large = flag(), sweep = flag();
18823
+ const x22 = ox + num3(), y2 = oy + num3();
18824
+ out.push(...arcToCubics(x2, y, rx, ry, rot2, large, sweep, x22, y2, arcStep));
18825
+ x2 = x22;
18826
+ y = y2;
18827
+ } else if (C === "Z") {
18828
+ out.push({ type: "Z" });
18829
+ x2 = sx;
18830
+ y = sy;
18831
+ } else throw new Error(`Unknown path command "${cmd}"`);
18832
+ prev = C;
18833
+ }
18834
+ }
18702
18835
  }
18703
- function arcToCubics(x1, y1, rx, ry, rotDeg, large, sweep, x2, y2) {
18836
+ function arcToCubics(x1, y1, rx, ry, rotDeg, large, sweep, x2, y2, step = Math.PI / 2) {
18704
18837
  if (rx === 0 || ry === 0 || x1 === x2 && y1 === y2) return [{ type: "L", x: x2, y: y2 }];
18705
18838
  rx = Math.abs(rx);
18706
18839
  ry = Math.abs(ry);
@@ -18713,9 +18846,9 @@ function arcToCubics(x1, y1, rx, ry, rotDeg, large, sweep, x2, y2) {
18713
18846
  rx *= Math.sqrt(lambda);
18714
18847
  ry *= Math.sqrt(lambda);
18715
18848
  }
18716
- const num2 = rx * rx * ry * ry - rx * rx * y1p * y1p - ry * ry * x1p * x1p;
18849
+ const num3 = rx * rx * ry * ry - rx * rx * y1p * y1p - ry * ry * x1p * x1p;
18717
18850
  const den = rx * rx * y1p * y1p + ry * ry * x1p * x1p;
18718
- let coef = Math.sqrt(Math.max(0, num2 / den));
18851
+ let coef = Math.sqrt(Math.max(0, num3 / den));
18719
18852
  if (large === sweep) coef = -coef;
18720
18853
  const cxp = coef * rx * y1p / ry, cyp = -coef * ry * x1p / rx;
18721
18854
  const cxa = cos * cxp - sin * cyp + (x1 + x2) / 2, cya = sin * cxp + cos * cyp + (y1 + y2) / 2;
@@ -18727,7 +18860,7 @@ function arcToCubics(x1, y1, rx, ry, rotDeg, large, sweep, x2, y2) {
18727
18860
  let dt = ang((x1p - cxp) / rx, (y1p - cyp) / ry, (-x1p - cxp) / rx, (-y1p - cyp) / ry);
18728
18861
  if (!sweep && dt > 0) dt -= 2 * Math.PI;
18729
18862
  if (sweep && dt < 0) dt += 2 * Math.PI;
18730
- const n2 = Math.ceil(Math.abs(dt) / (Math.PI / 2));
18863
+ const n2 = Math.ceil(Math.abs(dt) / step);
18731
18864
  const out = [];
18732
18865
  const pt = (t) => [
18733
18866
  cxa + rx * Math.cos(t) * cos - ry * Math.sin(t) * sin,
@@ -18864,14 +18997,14 @@ var LIST_COST = 4;
18864
18997
  var CHARS_PER_ITEM = 8;
18865
18998
  var shapePoints = (s) => {
18866
18999
  let n2 = SHAPE_COST;
18867
- const add3 = (layers) => {
19000
+ const add4 = (layers) => {
18868
19001
  for (const l of layers.values()) {
18869
19002
  for (const p2 of l.regions) n2 += p2.length;
18870
19003
  for (const p2 of l.lines) n2 += p2.length;
18871
19004
  }
18872
19005
  };
18873
- add3(s.layers);
18874
- for (const p2 of s.parts) add3(p2.layers);
19006
+ add4(s.layers);
19007
+ for (const p2 of s.parts) add4(p2.layers);
18875
19008
  return n2;
18876
19009
  };
18877
19010
  var Env = class {
@@ -19020,15 +19153,15 @@ var Evaluator = class {
19020
19153
  }
19021
19154
  }
19022
19155
  }
19023
- enter(chain, path, at2, verb) {
19024
- if (chain.includes(path)) {
19025
- const loop = [...chain.slice(chain.indexOf(path)), path].map((p2) => `<${p2}>`);
19156
+ enter(chain2, path, at2, verb) {
19157
+ if (chain2.includes(path)) {
19158
+ const loop = [...chain2.slice(chain2.indexOf(path)), path].map((p2) => `<${p2}>`);
19026
19159
  throw new KerfError(
19027
19160
  loop.length === 2 ? `Library ${loop[0]} ${verb}s itself` : `Libraries ${verb} each other in a loop: ${loop.join(" \u2192 ")}`,
19028
19161
  at2
19029
19162
  );
19030
19163
  }
19031
- chain.push(path);
19164
+ chain2.push(path);
19032
19165
  }
19033
19166
  // A library's statements with the files it includes written out in place
19034
19167
  included(stmts, seen) {
@@ -19503,7 +19636,7 @@ var Evaluator = class {
19503
19636
  const max = this.limits.maxListLength;
19504
19637
  const parts = [];
19505
19638
  let n2 = 0;
19506
- const add3 = (label, v, quote) => {
19639
+ const add4 = (label, v, quote) => {
19507
19640
  if (parts.length) n2 += 2;
19508
19641
  const r = write(v, max - n2 - label.length, quote);
19509
19642
  n2 += label.length + r.text.length;
@@ -19515,8 +19648,8 @@ var Evaluator = class {
19515
19648
  parts.push(label + r.text);
19516
19649
  };
19517
19650
  for (const { name, value: value2 } of a.all)
19518
- if (name === null) add3("", value2, false);
19519
- else add3(`${name} = `, value2, true);
19651
+ if (name === null) add4("", value2, false);
19652
+ else add4(`${name} = `, value2, true);
19520
19653
  return parts.join(", ");
19521
19654
  }
19522
19655
  arith(op, a, b, at2) {
@@ -19876,18 +20009,18 @@ var Evaluator = class {
19876
20009
  union: (c) => c.children(),
19877
20010
  group: (c) => c.children(),
19878
20011
  difference: (c) => {
19879
- const [first, ...rest] = c.childList();
19880
- if (!first) return emptyShape();
20012
+ const [first2, ...rest] = c.childList();
20013
+ if (!first2) return emptyShape();
19881
20014
  const cutter = flat(rest, "difference");
19882
- return mapLayers(first, (l) => ({
20015
+ return mapLayers(first2, (l) => ({
19883
20016
  regions: difference2(l.regions, cutter.regions),
19884
20017
  lines: clipLines(l.lines, union2(cutter.regions), "outside")
19885
20018
  }));
19886
20019
  },
19887
20020
  intersection: (c) => {
19888
- const [first, ...rest] = c.childList();
19889
- if (!first) return emptyShape();
19890
- let out = first;
20021
+ const [first2, ...rest] = c.childList();
20022
+ if (!first2) return emptyShape();
20023
+ let out = first2;
19891
20024
  for (const r of rest) {
19892
20025
  const keep = union2(flat([r], "intersection").regions);
19893
20026
  out = mapLayers(out, (l) => ({
@@ -19903,11 +20036,11 @@ var Evaluator = class {
19903
20036
  const each = (layers) => {
19904
20037
  const pts = [];
19905
20038
  let key = "cut";
19906
- let first = true;
20039
+ let first2 = true;
19907
20040
  for (const [k, l] of layers) {
19908
- if (first && (l.regions.length || l.lines.length)) {
20041
+ if (first2 && (l.regions.length || l.lines.length)) {
19909
20042
  key = k;
19910
- first = false;
20043
+ first2 = false;
19911
20044
  }
19912
20045
  for (const p2 of [...l.regions, ...l.lines]) for (const q of p2) pts.push(q);
19913
20046
  }
@@ -19949,13 +20082,13 @@ var Evaluator = class {
19949
20082
  const name = this.arg(c.args, "name", 0);
19950
20083
  if (typeof name !== "string" || !name) throw new Error("layer() needs a name");
19951
20084
  const mode = this.arg(c.args, "mode", 1);
19952
- const color = this.arg(c.args, "color", 2);
20085
+ const color2 = this.arg(c.args, "color", 2);
19953
20086
  const known = this.layers.get(name);
19954
- if (mode !== void 0 || color !== void 0 || !known) {
20087
+ if (mode !== void 0 || color2 !== void 0 || !known) {
19955
20088
  const m = mode ?? known?.mode ?? "line";
19956
20089
  if (!["cut", "line", "fill", "guide"].includes(m))
19957
20090
  throw new Error('mode must be "cut", "line", "fill" or "guide"');
19958
- const col = toText(color ?? known?.color ?? "#00aa00");
20091
+ const col = toText(color2 ?? known?.color ?? "#00aa00");
19959
20092
  if (!/^#[0-9a-fA-F]{6}$/.test(col)) throw new Error('color must look like "#00aa00"');
19960
20093
  this.layers.set(name, { name, mode: m, color: col });
19961
20094
  }
@@ -20044,10 +20177,10 @@ var Evaluator = class {
20044
20177
  },
20045
20178
  tslot: (c) => {
20046
20179
  const d2 = this.num(this.arg(c.args, "d", 0, 3), "tslot", "d");
20047
- const length = this.num(this.arg(c.args, "length", 1, 12), "tslot", "length");
20180
+ const length2 = this.num(this.arg(c.args, "length", 1, 12), "tslot", "length");
20048
20181
  const [nw, nh] = this.vec2(this.arg(c.args, "nut", 2, [d2 * 1.85, d2 * 0.8]), "nut", false);
20049
- const at2 = this.num(this.arg(c.args, "nut_at", 3, length / 2), "tslot", "nut_at");
20050
- return regionShape(union2(tslot(d2, length, nw, nh, at2)));
20182
+ const at2 = this.num(this.arg(c.args, "nut_at", 3, length2 / 2), "tslot", "nut_at");
20183
+ return regionShape(union2(tslot(d2, length2, nw, nh, at2)));
20051
20184
  },
20052
20185
  living_hinge: (c) => {
20053
20186
  const [w, h] = this.vec2(this.arg(c.args, "size", 0), "size");
@@ -20176,10 +20309,10 @@ var ACI = {
20176
20309
  "#ff00ff": 6,
20177
20310
  "#000000": 7
20178
20311
  };
20179
- var aci = (color) => {
20180
- const hit = ACI[color.toLowerCase()];
20312
+ var aci = (color2) => {
20313
+ const hit = ACI[color2.toLowerCase()];
20181
20314
  if (hit) return hit;
20182
- const [r, g, b] = [1, 3, 5].map((i) => parseInt(color.slice(i, i + 2), 16));
20315
+ const [r, g, b] = [1, 3, 5].map((i) => parseInt(color2.slice(i, i + 2), 16));
20183
20316
  if (r > g && r > b) return 1;
20184
20317
  if (g > r && g > b) return 3;
20185
20318
  if (b > r && b > g) return 5;
@@ -20667,8 +20800,8 @@ function parameters(source) {
20667
20800
  if (body.includes(",") || /[a-zA-Z"]/.test(body) && !/^-?[\d.]+(:-?[\d.]+){0,2}$/.test(body)) {
20668
20801
  p2.options = body.split(",").map((raw2) => {
20669
20802
  const [val, label] = raw2.split(":").map((x2) => x2.trim().replace(/^"|"$/g, ""));
20670
- const num2 = parseNumber(val);
20671
- const value2 = p2.type === "number" && num2 !== void 0 ? num2 : val;
20803
+ const num3 = parseNumber(val);
20804
+ const value2 = p2.type === "number" && num3 !== void 0 ? num3 : val;
20672
20805
  return { name: label ?? val, value: value2 };
20673
20806
  });
20674
20807
  } else {
@@ -20699,29 +20832,29 @@ function formatError(error, source, options = {}) {
20699
20832
  if (!(error instanceof KerfError))
20700
20833
  return `error: ${error instanceof Error ? error.message : String(error)}`;
20701
20834
  const name = options.file ?? "design.kerf";
20702
- const place = (file, line, col) => `${file ? `<${file}>` : name}:${line}:${col}`;
20835
+ const place2 = (file, line, col) => `${file ? `<${file}>` : name}:${line}:${col}`;
20703
20836
  const text3 = (file) => file === void 0 ? source : (Object.prototype.hasOwnProperty.call(LIBRARIES, file) ? LIBRARIES[file] : void 0) ?? options.resolve?.(file);
20704
20837
  const out = [`error: ${error.reason}`];
20705
20838
  if (error.line !== void 0 && error.col !== void 0) {
20706
- out.push(` --> ${place(error.file, error.line, error.col)}`);
20839
+ out.push(` --> ${place2(error.file, error.line, error.col)}`);
20707
20840
  const lines = text3(error.file)?.split("\n");
20708
20841
  const line = lines?.[error.line - 1]?.replace(/\r$/, "");
20709
20842
  if (line !== void 0) {
20710
- const num2 = String(error.line);
20711
- const pad = " ".repeat(num2.length);
20843
+ const num3 = String(error.line);
20844
+ const pad = " ".repeat(num3.length);
20712
20845
  const before = line.slice(0, error.col - 1);
20713
- const length = markLength(line, error.col);
20846
+ const length2 = markLength(line, error.col);
20714
20847
  const indent = before.replace(/[^\t]/g, " ");
20715
- out.push(`${pad} |`, `${num2} | ${line}`, `${pad} | ${indent}${"^".repeat(length)}`);
20848
+ out.push(`${pad} |`, `${num3} | ${line}`, `${pad} | ${indent}${"^".repeat(length2)}`);
20716
20849
  }
20717
20850
  }
20718
- for (const note of traceNotes(error, place)) out.push(` = ${note}`);
20851
+ for (const note of traceNotes(error, place2)) out.push(` = ${note}`);
20719
20852
  const sig = error.call ? signature(error.call) : void 0;
20720
20853
  if (sig) out.push(` = ${formatSignature(sig)}: ${sig.doc}`);
20721
20854
  return out.join("\n");
20722
20855
  }
20723
- function traceNotes(error, place) {
20724
- const line = (f) => `in ${f.kind === "module" ? "module " : ""}${f.name}(), called at ${place(f.file, f.line, f.col)}${f.count > 1 ? ` (${f.count} times)` : ""}`;
20856
+ function traceNotes(error, place2) {
20857
+ const line = (f) => `in ${f.kind === "module" ? "module " : ""}${f.name}(), called at ${place2(f.file, f.line, f.col)}${f.count > 1 ? ` (${f.count} times)` : ""}`;
20725
20858
  const notes = error.trace.slice(0, SHOWN).map(line);
20726
20859
  const more = error.trace.length - notes.length + error.traceMore;
20727
20860
  if (more) notes.push(`and ${more} more call${more === 1 ? "" : "s"}`);
@@ -20819,7 +20952,7 @@ function format(source, options = {}) {
20819
20952
  let chainLevel = 0;
20820
20953
  let headerLevel = 0;
20821
20954
  let prev;
20822
- let last;
20955
+ let last2;
20823
20956
  const top = () => stack[stack.length - 1];
20824
20957
  const atBlock = () => !top() || top().open === "{";
20825
20958
  const closes = (t) => t.kind === "token" && !!top() && t.text === CLOSE[top().open];
@@ -20829,7 +20962,7 @@ function format(source, options = {}) {
20829
20962
  lineNo++;
20830
20963
  level = indent;
20831
20964
  line = unit.repeat(indent);
20832
- last = void 0;
20965
+ last2 = void 0;
20833
20966
  };
20834
20967
  const indentFor = (t) => {
20835
20968
  if (closes(t)) return top().outer;
@@ -20853,7 +20986,7 @@ function format(source, options = {}) {
20853
20986
  newLine(indent, it.breaks > 1 && lineNo >= 0);
20854
20987
  } else line += " ";
20855
20988
  line += it.text;
20856
- last = it;
20989
+ last2 = it;
20857
20990
  continue;
20858
20991
  }
20859
20992
  const text3 = it.text;
@@ -20874,7 +21007,7 @@ function format(source, options = {}) {
20874
21007
  const indent = indentFor(it);
20875
21008
  newLine(indent, it.breaks > 1 && lineNo >= 0);
20876
21009
  if (atBlock() && !closes(it)) chainLevel = indent;
20877
- } else if (last && space(last, it)) line += " ";
21010
+ } else if (last2 && space(last2, it)) line += " ";
20878
21011
  if (atBlock() && stmtStart && !closes(it)) {
20879
21012
  stmtLevel = level;
20880
21013
  stmtAssign = type === "id" && list2[i + 1]?.kind === "token" && list2[i + 1].text === "=" || text3 === "function";
@@ -20907,7 +21040,7 @@ function format(source, options = {}) {
20907
21040
  else ternaries++;
20908
21041
  }
20909
21042
  prev = it;
20910
- last = it;
21043
+ last2 = it;
20911
21044
  }
20912
21045
  if (line !== null) lines.push(line.trimEnd());
20913
21046
  while (lines.length && lines[lines.length - 1] === "") lines.pop();
@@ -20939,8 +21072,2372 @@ function check(before, after) {
20939
21072
  if (!same2) throw new KerfError("The formatter would change the program, so it was left as it is");
20940
21073
  }
20941
21074
 
21075
+ // src/import/xml.ts
21076
+ var ENTITIES = { lt: "<", gt: ">", amp: "&", quot: '"', apos: "'" };
21077
+ function decode(s, custom = {}) {
21078
+ return s.replace(/&(#x[0-9a-fA-F]+|#\d+|[A-Za-z_][\w.-]*);/g, (m, e) => {
21079
+ if (e[0] === "#") {
21080
+ const code2 = e[1] === "x" ? parseInt(e.slice(2), 16) : parseInt(e.slice(1), 10);
21081
+ return Number.isFinite(code2) && code2 <= 1114111 ? String.fromCodePoint(code2) : m;
21082
+ }
21083
+ return ENTITIES[e] ?? custom[e] ?? m;
21084
+ });
21085
+ }
21086
+ function parseXml(src) {
21087
+ const comments = [];
21088
+ const entities = {};
21089
+ const top = { name: "#document", attrs: {}, children: [], text: "" };
21090
+ const stack = [top];
21091
+ let i = 0;
21092
+ const fail3 = (msg) => {
21093
+ const line = src.slice(0, i).split("\n").length;
21094
+ throw new Error(`${msg} (line ${line})`);
21095
+ };
21096
+ while (i < src.length) {
21097
+ const lt = src.indexOf("<", i);
21098
+ const textEnd = lt < 0 ? src.length : lt;
21099
+ if (textEnd > i) stack[stack.length - 1].text += decode(src.slice(i, textEnd), entities);
21100
+ if (lt < 0) break;
21101
+ i = lt;
21102
+ if (src.startsWith("<!--", i)) {
21103
+ const end = src.indexOf("-->", i + 4);
21104
+ if (end < 0) fail3("Unclosed comment");
21105
+ comments.push(src.slice(i + 4, end));
21106
+ i = end + 3;
21107
+ } else if (src.startsWith("<![CDATA[", i)) {
21108
+ const end = src.indexOf("]]>", i + 9);
21109
+ if (end < 0) fail3("Unclosed CDATA section");
21110
+ stack[stack.length - 1].text += src.slice(i + 9, end);
21111
+ i = end + 3;
21112
+ } else if (src.startsWith("<?", i)) {
21113
+ const end = src.indexOf("?>", i + 2);
21114
+ if (end < 0) fail3("Unclosed processing instruction");
21115
+ i = end + 2;
21116
+ } else if (src.startsWith("<!", i)) {
21117
+ let depth = 0;
21118
+ let j = i + 2;
21119
+ for (; j < src.length; j++) {
21120
+ const c = src[j];
21121
+ if (c === "[") depth++;
21122
+ else if (c === "]") depth--;
21123
+ else if (c === ">" && depth <= 0) break;
21124
+ }
21125
+ const body = src.slice(i, j);
21126
+ for (const m of body.matchAll(/<!ENTITY\s+([\w.-]+)\s+(["'])([\s\S]*?)\2\s*>/g))
21127
+ entities[m[1]] = m[3];
21128
+ i = j + 1;
21129
+ } else if (src[i + 1] === "/") {
21130
+ const end = src.indexOf(">", i);
21131
+ if (end < 0) fail3("Unclosed end tag");
21132
+ const name = src.slice(i + 2, end).trim();
21133
+ const open = stack.pop();
21134
+ if (!open || open === top || open.name !== name)
21135
+ fail3(`</${name}> does not match <${open?.name ?? "nothing"}>`);
21136
+ i = end + 1;
21137
+ } else {
21138
+ const m = /^<([^\s/>]+)/.exec(src.slice(i, i + 256));
21139
+ if (!m) fail3("Bad tag");
21140
+ const el = { name: m[1], attrs: {}, children: [], text: "" };
21141
+ i += m[0].length;
21142
+ const attr = /\s*([^\s=/>]+)\s*=\s*("([^"]*)"|'([^']*)')|\s*(\/?>)/y;
21143
+ for (; ; ) {
21144
+ attr.lastIndex = i;
21145
+ const a = attr.exec(src);
21146
+ if (!a) fail3(`Bad attribute in <${el.name}>`);
21147
+ i = attr.lastIndex;
21148
+ if (a[5]) {
21149
+ stack[stack.length - 1].children.push(el);
21150
+ if (a[5] === ">") stack.push(el);
21151
+ break;
21152
+ }
21153
+ el.attrs[a[1]] = decode(a[3] ?? a[4] ?? "", entities);
21154
+ }
21155
+ }
21156
+ }
21157
+ if (stack.length > 1) fail3(`<${stack[stack.length - 1].name}> is not closed`);
21158
+ const root = top.children[0];
21159
+ if (!root) throw new Error("The file has no elements");
21160
+ return { root, comments };
21161
+ }
21162
+
21163
+ // src/import/svg.ts
21164
+ var LAYERS = {
21165
+ cut: { name: "cut", mode: "cut", color: "#ff0000" },
21166
+ score: { name: "score", mode: "line", color: "#0000ff" },
21167
+ engrave: { name: "engrave", mode: "fill", color: "#000000" },
21168
+ guide: { name: "guide", mode: "guide", color: "#00a0ff" }
21169
+ };
21170
+ var NAMED = {
21171
+ black: "#000000",
21172
+ white: "#ffffff",
21173
+ red: "#ff0000",
21174
+ lime: "#00ff00",
21175
+ green: "#008000",
21176
+ blue: "#0000ff",
21177
+ yellow: "#ffff00",
21178
+ cyan: "#00ffff",
21179
+ aqua: "#00ffff",
21180
+ magenta: "#ff00ff",
21181
+ fuchsia: "#ff00ff",
21182
+ gray: "#808080",
21183
+ grey: "#808080",
21184
+ silver: "#c0c0c0",
21185
+ maroon: "#800000",
21186
+ navy: "#000080",
21187
+ olive: "#808000",
21188
+ purple: "#800080",
21189
+ teal: "#008080",
21190
+ orange: "#ffa500"
21191
+ };
21192
+ var COLOR_NAMES = Object.fromEntries(
21193
+ Object.entries(NAMED).reverse().map(([k, v]) => [v, k])
21194
+ );
21195
+ function color(v, current) {
21196
+ if (v === void 0) return void 0;
21197
+ v = v.trim().toLowerCase();
21198
+ if (v === "none" || v === "transparent") return "none";
21199
+ if (v === "currentcolor") return current;
21200
+ if (v.startsWith("url(")) return "paint";
21201
+ if (NAMED[v]) return NAMED[v];
21202
+ let m = /^#([0-9a-f]{3,8})$/.exec(v);
21203
+ if (m) {
21204
+ const h = m[1];
21205
+ if (h.length === 3 || h.length === 4)
21206
+ return "#" + [...h.slice(0, 3)].map((c) => c + c).join("");
21207
+ if (h.length === 6 || h.length === 8) return "#" + h.slice(0, 6);
21208
+ }
21209
+ m = /^rgba?\(([^)]*)\)$/.exec(v);
21210
+ if (m) {
21211
+ const parts = m[1].split(/[\s,/]+/).filter(Boolean);
21212
+ if (parts.length >= 3) {
21213
+ const ch = parts.slice(0, 3).map((p2) => {
21214
+ const n2 = p2.endsWith("%") ? parseFloat(p2) * 255 / 100 : parseFloat(p2);
21215
+ return Math.max(0, Math.min(255, Math.round(n2 || 0)));
21216
+ });
21217
+ if (parts[3] !== void 0 && parseFloat(parts[3]) === 0) return "none";
21218
+ return "#" + ch.map((c) => c.toString(16).padStart(2, "0")).join("");
21219
+ }
21220
+ }
21221
+ return "#000000";
21222
+ }
21223
+ var parseSvgPath2 = (d2, onError) => parseSvgPath(d2, Math.PI / 12, onError);
21224
+ var numbers = (s) => (s.match(/[-+]?(?:\d+\.?\d*|\.\d+)(?:[eE][-+]?\d+)?/g) ?? []).map(Number);
21225
+ function parseTransform(s) {
21226
+ let m = IDENTITY;
21227
+ if (!s) return m;
21228
+ for (const [, fn, args] of s.matchAll(/(\w+)\s*\(([^)]*)\)/g)) {
21229
+ const a = numbers(args);
21230
+ const rad = (a[0] ?? 0) * Math.PI / 180;
21231
+ let t = IDENTITY;
21232
+ if (fn === "matrix" && a.length === 6) t = a;
21233
+ else if (fn === "translate") t = [1, 0, 0, 1, a[0] ?? 0, a[1] ?? 0];
21234
+ else if (fn === "scale") t = [a[0] ?? 1, 0, 0, a[1] ?? a[0] ?? 1, 0, 0];
21235
+ else if (fn === "rotate") {
21236
+ const c = Math.cos(rad), sn = Math.sin(rad);
21237
+ const [cx, cy] = [a[1] ?? 0, a[2] ?? 0];
21238
+ t = [c, sn, -sn, c, cx - c * cx + sn * cy, cy - sn * cx - c * cy];
21239
+ } else if (fn === "skewX") t = [1, 0, Math.tan(rad), 1, 0, 0];
21240
+ else if (fn === "skewY") t = [1, Math.tan(rad), 0, 1, 0, 0];
21241
+ m = multiply2(m, t);
21242
+ }
21243
+ return m;
21244
+ }
21245
+ function cmdsToSubs(cmds, m) {
21246
+ const out = [];
21247
+ let segs = [];
21248
+ let start = [0, 0];
21249
+ let last2 = [0, 0];
21250
+ const p2 = (x2, y) => apply2(m, [x2, y]);
21251
+ const same2 = (a, b) => Math.abs(a[0] - b[0]) < 1e-9 && Math.abs(a[1] - b[1]) < 1e-9;
21252
+ const flush = (closed) => {
21253
+ if (segs.length) out.push({ segs, closed });
21254
+ segs = [];
21255
+ };
21256
+ for (const c of cmds) {
21257
+ if (c.type === "M") {
21258
+ flush(false);
21259
+ start = last2 = p2(c.x, c.y);
21260
+ } else if (c.type === "L") {
21261
+ const b = p2(c.x, c.y);
21262
+ if (!same2(last2, b)) segs.push({ c: "L", a: last2, b });
21263
+ last2 = b;
21264
+ } else if (c.type === "Q") {
21265
+ const q = p2(c.x1, c.y1);
21266
+ const b = p2(c.x, c.y);
21267
+ segs.push({
21268
+ c: "C",
21269
+ a: last2,
21270
+ p1: [last2[0] + 2 / 3 * (q[0] - last2[0]), last2[1] + 2 / 3 * (q[1] - last2[1])],
21271
+ p2: [b[0] + 2 / 3 * (q[0] - b[0]), b[1] + 2 / 3 * (q[1] - b[1])],
21272
+ b
21273
+ });
21274
+ last2 = b;
21275
+ } else if (c.type === "C") {
21276
+ const b = p2(c.x, c.y);
21277
+ segs.push({ c: "C", a: last2, p1: p2(c.x1, c.y1), p2: p2(c.x2, c.y2), b });
21278
+ last2 = b;
21279
+ } else {
21280
+ if (segs.length && !same2(last2, start)) segs.push({ c: "L", a: last2, b: start });
21281
+ flush(true);
21282
+ last2 = start;
21283
+ }
21284
+ }
21285
+ flush(false);
21286
+ return out;
21287
+ }
21288
+ var STYLE_PROPS = [
21289
+ "fill",
21290
+ "stroke",
21291
+ "stroke-width",
21292
+ "fill-rule",
21293
+ "display",
21294
+ "visibility",
21295
+ "opacity",
21296
+ "fill-opacity",
21297
+ "stroke-opacity",
21298
+ "color",
21299
+ "font-size",
21300
+ "font-family",
21301
+ "text-anchor"
21302
+ ];
21303
+ var INHERITED = /* @__PURE__ */ new Set([
21304
+ "fill",
21305
+ "stroke",
21306
+ "stroke-width",
21307
+ "fill-rule",
21308
+ "visibility",
21309
+ "fill-opacity",
21310
+ "stroke-opacity",
21311
+ "color",
21312
+ "font-size",
21313
+ "font-family",
21314
+ "text-anchor"
21315
+ ]);
21316
+ function declarations(s) {
21317
+ const out = {};
21318
+ for (const d2 of s.split(";")) {
21319
+ const i = d2.indexOf(":");
21320
+ if (i < 0) continue;
21321
+ const k = d2.slice(0, i).trim().toLowerCase();
21322
+ const v = d2.slice(i + 1).replace(/!important/i, "").trim();
21323
+ if (k && v) out[k] = v;
21324
+ }
21325
+ return out;
21326
+ }
21327
+ function parseCss(css) {
21328
+ const rules = [];
21329
+ css = css.replace(/\/\*[\s\S]*?\*\//g, "");
21330
+ for (const [, sel, body] of css.matchAll(/([^{}@]+)\{([^}]*)\}/g)) {
21331
+ const decls = declarations(body);
21332
+ for (const one of sel.split(",")) {
21333
+ const s = one.trim();
21334
+ const m = /^([a-zA-Z][\w-]*|\*)?((?:[.#][\w-]+)*)$/.exec(s);
21335
+ if (!m) continue;
21336
+ const classes = [];
21337
+ let id;
21338
+ for (const [, kind, name] of m[2].matchAll(/([.#])([\w-]+)/g))
21339
+ if (kind === ".") classes.push(name);
21340
+ else id = name;
21341
+ rules.push({ tag: m[1] && m[1] !== "*" ? m[1] : void 0, id, classes, decls });
21342
+ }
21343
+ }
21344
+ return rules;
21345
+ }
21346
+ function unitScale(unit, dpi) {
21347
+ switch (unit) {
21348
+ case "mm":
21349
+ return 1;
21350
+ case "cm":
21351
+ return 10;
21352
+ case "in":
21353
+ return 25.4;
21354
+ case "pt":
21355
+ return 25.4 / 72;
21356
+ case "pc":
21357
+ return 25.4 / 6;
21358
+ case "q":
21359
+ return 0.25;
21360
+ default:
21361
+ return 25.4 / dpi;
21362
+ }
21363
+ }
21364
+ function length(v, dpi) {
21365
+ if (!v) return void 0;
21366
+ const m = /^\s*([-+]?(?:\d+\.?\d*|\.\d+)(?:[eE][-+]?\d+)?)\s*([a-zA-Z%]*)\s*$/.exec(v);
21367
+ if (!m || m[2] === "%") return void 0;
21368
+ return Number(m[1]) * unitScale(m[2].toLowerCase(), dpi);
21369
+ }
21370
+ var AUTO_NAME = /^(path|g|rect|circle|ellipse|line|polyline|polygon|layer|svg|use|text|tspan|group|shape|cls|clip|mask|defs|_?x?\d|Layer_\d|Ebene|Calque|Capa|Livello|Laag|Warstwa)[-_ ]*[\d-]*$/i;
21371
+ function nameOf(el) {
21372
+ for (const k of ["data-part", "inkscape:label", "data-name", "id"]) {
21373
+ const v = el.attrs[k]?.trim();
21374
+ if (v && !AUTO_NAME.test(v) && !/^[\d_-]+$/.test(v)) return v.replace(/_x5F_|_/g, " ").trim();
21375
+ }
21376
+ return void 0;
21377
+ }
21378
+ function layerByName(name) {
21379
+ if (!name) return void 0;
21380
+ const n2 = name.toLowerCase();
21381
+ if (/\bscor|\bscoring/.test(n2)) return LAYERS.score;
21382
+ if (/engrav|raster|etch/.test(n2)) return LAYERS.engrave;
21383
+ if (/\bguide/.test(n2)) return LAYERS.guide;
21384
+ if (/^cut|\bcut\b|cutting|\bcuts\b/.test(n2)) return LAYERS.cut;
21385
+ return void 0;
21386
+ }
21387
+ function readSvg(src, opts = {}) {
21388
+ src = src.replace(/^\uFEFF/, "");
21389
+ if (!/^\s*</.test(src) || src.includes("\0"))
21390
+ throw new Error("This is not an SVG file: it does not start with a tag");
21391
+ const doc = parseXml(src);
21392
+ const root = doc.root;
21393
+ if (root.name.replace(/^.*:/, "") !== "svg") throw new Error("This is not an SVG file");
21394
+ const notes = [];
21395
+ const illustrator = doc.comments.some((c) => /Adobe Illustrator/i.test(c));
21396
+ const dpi = opts.dpi ?? (illustrator ? 72 : 96);
21397
+ if (opts.dpi === void 0 && illustrator)
21398
+ notes.push("Adobe Illustrator file: px measured at 72 per inch.");
21399
+ const vb = numbers(root.attrs.viewBox ?? "");
21400
+ const w = length(root.attrs.width, dpi);
21401
+ const h = length(root.attrs.height, dpi);
21402
+ const px = 25.4 / dpi;
21403
+ let sx = px, sy = px, ox = 0, oy = 0;
21404
+ if (vb.length === 4 && vb[2] > 0 && vb[3] > 0) {
21405
+ sx = w !== void 0 ? w / vb[2] : h !== void 0 ? h / vb[3] : px;
21406
+ sy = h !== void 0 ? h / vb[3] : sx;
21407
+ ox = vb[0];
21408
+ oy = vb[1];
21409
+ }
21410
+ if (w === void 0 && h === void 0 && opts.dpi === void 0 && !illustrator)
21411
+ notes.push(`The file gives no page size in mm or inches: px measured at ${dpi} per inch.`);
21412
+ const pageH = h ?? (vb.length === 4 ? vb[3] * sy : 0);
21413
+ const base = multiply2([1, 0, 0, -1, 0, pageH], [sx, 0, 0, sy, -ox * sx, -oy * sy]);
21414
+ const rules = [];
21415
+ const byId = /* @__PURE__ */ new Map();
21416
+ const index = (el) => {
21417
+ if (el.name === "style") rules.push(...parseCss(el.text));
21418
+ if (el.attrs.id) byId.set(el.attrs.id, el);
21419
+ el.children.forEach(index);
21420
+ };
21421
+ index(root);
21422
+ const styleOf = (el, parent) => {
21423
+ const s = {};
21424
+ for (const k of Object.keys(parent)) if (INHERITED.has(k)) s[k] = parent[k];
21425
+ for (const k of STYLE_PROPS) if (el.attrs[k] !== void 0) s[k] = el.attrs[k];
21426
+ const classes = (el.attrs.class ?? "").split(/\s+/).filter(Boolean);
21427
+ for (const r of rules)
21428
+ if ((!r.tag || r.tag === el.name) && (!r.id || r.id === el.attrs.id) && r.classes.every((c) => classes.includes(c)))
21429
+ Object.assign(s, r.decls);
21430
+ if (el.attrs.style) Object.assign(s, declarations(el.attrs.style));
21431
+ return s;
21432
+ };
21433
+ const raws = [];
21434
+ const rawTexts = [];
21435
+ let skippedImages = 0;
21436
+ let skippedHidden = 0;
21437
+ let badPaths = 0;
21438
+ let tooLarge = 0;
21439
+ let copying = 0;
21440
+ let copies = 0;
21441
+ const MAX_COPIES = 2e4;
21442
+ const inside2 = [];
21443
+ const finite = (q) => Number.isFinite(q[0]) && Number.isFinite(q[1]);
21444
+ const GEOMETRY = ["x", "y", "width", "height", "rx", "ry", "cx", "cy", "r"];
21445
+ const huge = (el) => [...GEOMETRY, "x1", "y1", "x2", "y2", "points"].some(
21446
+ (k) => el.attrs[k] !== void 0 && numbers(el.attrs[k]).some((n2) => !Number.isFinite(n2))
21447
+ );
21448
+ const SKIP = /* @__PURE__ */ new Set([
21449
+ "defs",
21450
+ "clipPath",
21451
+ "mask",
21452
+ "pattern",
21453
+ "marker",
21454
+ "symbol",
21455
+ "metadata",
21456
+ "title",
21457
+ "desc",
21458
+ "style",
21459
+ "script",
21460
+ "linearGradient",
21461
+ "radialGradient",
21462
+ "filter",
21463
+ "sodipodi:namedview",
21464
+ "foreignObject"
21465
+ ]);
21466
+ const SHAPES = /* @__PURE__ */ new Set(["path", "rect", "circle", "ellipse", "line", "polyline", "polygon"]);
21467
+ const shapeCmds = (el) => {
21468
+ const a = (k) => parseFloat(el.attrs[k] ?? "0") || 0;
21469
+ switch (el.name) {
21470
+ case "path":
21471
+ return parseSvgPath2(el.attrs.d ?? "", () => badPaths++);
21472
+ case "rect": {
21473
+ const [x2, y, rw, rh] = [a("x"), a("y"), a("width"), a("height")];
21474
+ if (rw <= 0 || rh <= 0) return [];
21475
+ let rx = el.attrs.rx !== void 0 ? a("rx") : el.attrs.ry !== void 0 ? a("ry") : 0;
21476
+ let ry = el.attrs.ry !== void 0 ? a("ry") : rx;
21477
+ rx = Math.min(Math.abs(rx), rw / 2);
21478
+ ry = Math.min(Math.abs(ry), rh / 2);
21479
+ if (rx <= 0 || ry <= 0) return parseSvgPath2(`M${x2} ${y}H${x2 + rw}V${y + rh}H${x2}Z`);
21480
+ return parseSvgPath2(
21481
+ `M${x2 + rx} ${y}H${x2 + rw - rx}A${rx} ${ry} 0 0 1 ${x2 + rw} ${y + ry}V${y + rh - ry}A${rx} ${ry} 0 0 1 ${x2 + rw - rx} ${y + rh}H${x2 + rx}A${rx} ${ry} 0 0 1 ${x2} ${y + rh - ry}V${y + ry}A${rx} ${ry} 0 0 1 ${x2 + rx} ${y}Z`
21482
+ );
21483
+ }
21484
+ case "circle":
21485
+ case "ellipse": {
21486
+ const [cx, cy] = [a("cx"), a("cy")];
21487
+ const rx = el.name === "circle" ? a("r") : a("rx");
21488
+ const ry = el.name === "circle" ? a("r") : el.attrs.ry !== void 0 ? a("ry") : rx;
21489
+ if (rx <= 0 || ry <= 0) return [];
21490
+ return parseSvgPath2(
21491
+ `M${cx + rx} ${cy}A${rx} ${ry} 0 0 1 ${cx} ${cy + ry}A${rx} ${ry} 0 0 1 ${cx - rx} ${cy}A${rx} ${ry} 0 0 1 ${cx} ${cy - ry}A${rx} ${ry} 0 0 1 ${cx + rx} ${cy}Z`
21492
+ );
21493
+ }
21494
+ case "line":
21495
+ return parseSvgPath2(`M${a("x1")} ${a("y1")}L${a("x2")} ${a("y2")}`);
21496
+ case "polyline":
21497
+ case "polygon": {
21498
+ const n2 = numbers(el.attrs.points ?? "");
21499
+ if (n2.length < 4) return [];
21500
+ let d2 = `M${n2[0]} ${n2[1]}`;
21501
+ for (let i = 2; i + 1 < n2.length; i += 2) d2 += `L${n2[i]} ${n2[i + 1]}`;
21502
+ return parseSvgPath2(el.name === "polygon" ? d2 + "Z" : d2);
21503
+ }
21504
+ }
21505
+ return void 0;
21506
+ };
21507
+ const textOf = (el) => (el.text + el.children.map((c) => c.name === "tspan" ? " " + textOf(c) : "").join("")).replace(/\s+/g, " ").trim();
21508
+ const walk2 = (el, m, parent, layer, names, depth) => {
21509
+ if (depth > 64 || SKIP.has(el.name) || copying && ++copies > MAX_COPIES) return;
21510
+ const style = styleOf(el, parent);
21511
+ if (style.display === "none" || style.visibility === "hidden" || style.opacity === "0") {
21512
+ if (el.children.length || SHAPES.has(el.name)) skippedHidden++;
21513
+ return;
21514
+ }
21515
+ let mm = multiply2(m, parseTransform(el.attrs.transform));
21516
+ if (!mm.every(Number.isFinite)) {
21517
+ tooLarge++;
21518
+ return;
21519
+ }
21520
+ const own4 = nameOf(el);
21521
+ const isLayer = el.attrs["inkscape:groupmode"] === "layer";
21522
+ let here = layer;
21523
+ if (el.name === "g" || el.name === "svg" || el.name === "a" || el.name === "switch") {
21524
+ const label = el.attrs["inkscape:label"] ?? el.attrs["data-name"] ?? el.attrs.id;
21525
+ const known = layerByName(label);
21526
+ if (el.attrs["data-mode"] && label && /^(cut|line|fill|guide)$/.test(el.attrs["data-mode"])) {
21527
+ const stroke2 = color(style.stroke, "#000000");
21528
+ const fill2 = color(style.fill, "#000000");
21529
+ const col = el.attrs["data-mode"] === "fill" ? fill2 : stroke2;
21530
+ here = LAYERS[label] ?? {
21531
+ name: label,
21532
+ mode: el.attrs["data-mode"],
21533
+ color: col && col.startsWith("#") ? col : "#00aa00"
21534
+ };
21535
+ } else if (known) here = known;
21536
+ if (el !== root && el.name === "svg") {
21537
+ const a = (k) => parseFloat(el.attrs[k] ?? "0") || 0;
21538
+ mm = multiply2(mm, [1, 0, 0, 1, a("x"), a("y")]);
21539
+ }
21540
+ const kids = isLayer || known || el === root || !own4 ? names : [own4, ...names];
21541
+ inside2.push(el);
21542
+ for (const c of el.children) walk2(c, mm, style, here, kids, depth + 1);
21543
+ inside2.pop();
21544
+ return;
21545
+ }
21546
+ if (el.name === "use") {
21547
+ const ref = byId.get((el.attrs.href ?? el.attrs["xlink:href"] ?? "").replace(/^#/, ""));
21548
+ if (!ref || inside2.includes(ref)) return;
21549
+ const a = (k) => parseFloat(el.attrs[k] ?? "0") || 0;
21550
+ const t = multiply2(mm, [1, 0, 0, 1, a("x"), a("y")]);
21551
+ const target = ref.name === "symbol" ? { ...ref, name: "g" } : ref;
21552
+ inside2.push(ref);
21553
+ copying++;
21554
+ walk2(target, t, style, here, own4 ? [own4, ...names] : names, depth + 1);
21555
+ copying--;
21556
+ inside2.pop();
21557
+ return;
21558
+ }
21559
+ if (el.name === "image") {
21560
+ skippedImages++;
21561
+ return;
21562
+ }
21563
+ const cur = color(style.color, "#000000") ?? "#000000";
21564
+ const strokeWidth = parseFloat(style["stroke-width"] ?? "1");
21565
+ let stroke = color(style.stroke, cur);
21566
+ if (stroke && (strokeWidth === 0 || style["stroke-opacity"] === "0")) stroke = "none";
21567
+ let fill = color(style.fill ?? "black", cur);
21568
+ if (style["fill-opacity"] === "0") fill = "none";
21569
+ if (el.name === "text") {
21570
+ const text3 = textOf(el);
21571
+ if (!text3) return;
21572
+ const first2 = el.children.find((c) => c.name === "tspan");
21573
+ const num3 = (k) => numbers(el.attrs[k] ?? first2?.attrs[k] ?? "0")[0] ?? 0;
21574
+ const at2 = apply2(mm, [num3("x"), num3("y")]);
21575
+ const scale = Math.sqrt(Math.abs(mm[0] * mm[3] - mm[1] * mm[2]));
21576
+ const size = (length(style["font-size"], 96) ?? 16 * px) / px;
21577
+ if (!finite(at2) || !Number.isFinite(size * scale)) {
21578
+ tooLarge++;
21579
+ return;
21580
+ }
21581
+ const anchor = style["text-anchor"];
21582
+ rawTexts.push({
21583
+ text: text3,
21584
+ at: at2,
21585
+ size: size * scale,
21586
+ angle: Math.atan2(-mm[1], mm[0]) * 180 / Math.PI,
21587
+ font: (style["font-family"] ?? "").split(",")[0].replace(/['"]/g, "").trim(),
21588
+ anchor: anchor === "middle" ? "center" : anchor === "end" ? "right" : "left",
21589
+ stroke,
21590
+ fill,
21591
+ layer: here
21592
+ });
21593
+ return;
21594
+ }
21595
+ if (el.name !== "path" && huge(el)) {
21596
+ tooLarge++;
21597
+ return;
21598
+ }
21599
+ const cmds = shapeCmds(el);
21600
+ if (!cmds) {
21601
+ for (const c of el.children) walk2(c, mm, style, here, names, depth + 1);
21602
+ return;
21603
+ }
21604
+ const all = cmdsToSubs(cmds, mm);
21605
+ const subs = all.filter(
21606
+ (s) => s.segs.every(
21607
+ (g) => finite(g.a) && finite(g.b) && (g.c === "L" || finite(g.p1) && finite(g.p2))
21608
+ )
21609
+ );
21610
+ if (subs.length < all.length) tooLarge++;
21611
+ if (!subs.length) return;
21612
+ raws.push({
21613
+ subs,
21614
+ stroke,
21615
+ fill: el.name === "line" || el.name === "polyline" ? "none" : fill,
21616
+ fillRule: style["fill-rule"] === "evenodd" ? "evenodd" : "nonzero",
21617
+ layer: here,
21618
+ names: own4 ? [own4, ...names] : names
21619
+ });
21620
+ };
21621
+ walk2(root, base, {}, void 0, [], 0);
21622
+ if (skippedImages)
21623
+ notes.push(
21624
+ `${skippedImages} embedded image${skippedImages === 1 ? " was" : "s were"} left out: trace ${skippedImages === 1 ? "it" : "them"} to paths first.`
21625
+ );
21626
+ if (skippedHidden)
21627
+ notes.push(
21628
+ `${skippedHidden} hidden element${skippedHidden === 1 ? " was" : "s were"} left out.`
21629
+ );
21630
+ if (badPaths)
21631
+ notes.push(
21632
+ `${badPaths} path${badPaths === 1 ? " has" : "s have"} bad data: read up to the error, as browsers draw ${badPaths === 1 ? "it" : "them"}.`
21633
+ );
21634
+ if (tooLarge)
21635
+ notes.push(
21636
+ `${tooLarge} element${tooLarge === 1 ? " was" : "s were"} left out: ${tooLarge === 1 ? "its" : "their"} numbers are too large to draw.`
21637
+ );
21638
+ if (copies > MAX_COPIES)
21639
+ notes.push(
21640
+ `The drawing repeats its elements with <use> more than ${MAX_COPIES.toLocaleString("en")} times: only the first ${MAX_COPIES.toLocaleString("en")} copies were read.`
21641
+ );
21642
+ const isRed = (c) => {
21643
+ const [r, g, b] = [1, 3, 5].map((i) => parseInt(c.slice(i, i + 2), 16));
21644
+ return r >= 200 && g <= 80 && b <= 80;
21645
+ };
21646
+ const isBlue = (c) => {
21647
+ const [r, g, b] = [1, 3, 5].map((i) => parseInt(c.slice(i, i + 2), 16));
21648
+ return b >= 200 && r <= 80 && g <= 80;
21649
+ };
21650
+ const stroked = (r) => !!r.stroke && r.stroke !== "none";
21651
+ const free = raws.filter((r) => !r.layer);
21652
+ const counts = /* @__PURE__ */ new Map();
21653
+ for (const r of free)
21654
+ if (stroked(r) && r.stroke.startsWith("#"))
21655
+ counts.set(r.stroke, (counts.get(r.stroke) ?? 0) + r.subs.length);
21656
+ const colors = [...counts.keys()];
21657
+ const red = colors.filter(isRed);
21658
+ const cutColors = new Set(
21659
+ red.length ? red : colors.length ? [colors.reduce((a, b) => (counts.get(b) ?? 0) > (counts.get(a) ?? 0) ? b : a)] : []
21660
+ );
21661
+ const anyStroke = raws.some((r) => stroked(r) && !r.layer) || raws.some((r) => r.layer);
21662
+ const custom = /* @__PURE__ */ new Map();
21663
+ const byColor = (stroke, fill) => {
21664
+ if (stroke && stroke !== "none") {
21665
+ const c = stroke.startsWith("#") ? stroke : "#000000";
21666
+ if (cutColors.has(c)) return LAYERS.cut;
21667
+ if (c === "#00a0ff") return LAYERS.guide;
21668
+ if (isBlue(c)) return LAYERS.score;
21669
+ if (!custom.has(c)) {
21670
+ const name = COLOR_NAMES[c] ?? "color_" + c.slice(1);
21671
+ custom.set(c, { name, mode: "line", color: c });
21672
+ }
21673
+ return custom.get(c);
21674
+ }
21675
+ if (fill && fill !== "none") return anyStroke ? LAYERS.engrave : LAYERS.cut;
21676
+ return void 0;
21677
+ };
21678
+ if (!anyStroke && raws.some((r) => r.fill && r.fill !== "none"))
21679
+ notes.push("The file has filled shapes and no strokes: the shapes are cut out.");
21680
+ else if (!red.length && cutColors.size)
21681
+ notes.push(`No red lines: ${[...cutColors][0]} lines, the most common colour, are cut.`);
21682
+ if (custom.size)
21683
+ notes.push(
21684
+ `Lines in ${[...custom.values()].map((l) => l.color).join(", ")} went on their own layer${custom.size === 1 ? "" : "s"}, set to mark, not cut.`
21685
+ );
21686
+ const items2 = [];
21687
+ for (const r of raws) {
21688
+ const layer = r.layer ?? byColor(r.stroke, r.fill);
21689
+ if (!layer) continue;
21690
+ const filled = !r.layer && layer === LAYERS.cut && !stroked(r);
21691
+ items2.push({ subs: r.subs, layer, fillRule: r.fillRule, names: r.names, filled });
21692
+ }
21693
+ const texts = [];
21694
+ for (const t of rawTexts) {
21695
+ const layer = t.layer ?? byColor(t.fill !== "none" ? void 0 : t.stroke, t.fill);
21696
+ if (layer)
21697
+ texts.push({ ...t, layer: layer.mode === "cut" && anyStroke ? LAYERS.engrave : layer });
21698
+ }
21699
+ return { items: items2, texts, notes };
21700
+ }
21701
+
21702
+ // src/import/shapes.ts
21703
+ var dist = (a, b) => Math.hypot(a[0] - b[0], a[1] - b[1]);
21704
+ var rot = ([x2, y], deg) => {
21705
+ const a = deg * Math.PI / 180;
21706
+ const c = Math.cos(a), s = Math.sin(a);
21707
+ return [x2 * c - y * s, x2 * s + y * c];
21708
+ };
21709
+ var add2 = (a, b) => [a[0] + b[0], a[1] + b[1]];
21710
+ var sub = (a, b) => [a[0] - b[0], a[1] - b[1]];
21711
+ function flattenSub(s, tol = 5e-3) {
21712
+ const out = [s.segs[0].a];
21713
+ for (const g of s.segs) {
21714
+ if (g.c === "L") out.push(g.b);
21715
+ else {
21716
+ const len = dist(g.a, g.p1) + dist(g.p1, g.p2) + dist(g.p2, g.b);
21717
+ const n2 = Math.max(2, Math.min(512, Math.ceil(Math.sqrt(len / tol))));
21718
+ for (let i = 1; i <= n2; i++) {
21719
+ const t = i / n2, u = 1 - t;
21720
+ out.push([
21721
+ u * u * u * g.a[0] + 3 * u * u * t * g.p1[0] + 3 * u * t * t * g.p2[0] + t * t * t * g.b[0],
21722
+ u * u * u * g.a[1] + 3 * u * u * t * g.p1[1] + 3 * u * t * t * g.p2[1] + t * t * t * g.b[1]
21723
+ ]);
21724
+ }
21725
+ }
21726
+ }
21727
+ if (s.closed && out.length > 1 && dist(out[0], out[out.length - 1]) < 1e-9) out.pop();
21728
+ return out;
21729
+ }
21730
+ function perimeter2(p2, closed = true) {
21731
+ let s = 0;
21732
+ for (let i = 1; i < p2.length; i++) s += dist(p2[i - 1], p2[i]);
21733
+ return closed && p2.length > 2 ? s + dist(p2[p2.length - 1], p2[0]) : s;
21734
+ }
21735
+ function resample(p2, closed, step) {
21736
+ const out = [];
21737
+ const n2 = closed ? p2.length : p2.length - 1;
21738
+ for (let i = 0; i < n2; i++) {
21739
+ const a = p2[i], b = p2[(i + 1) % p2.length];
21740
+ out.push(a);
21741
+ const k = Math.floor(dist(a, b) / step);
21742
+ for (let j = 1; j < k; j++)
21743
+ out.push([a[0] + (b[0] - a[0]) * j / k, a[1] + (b[1] - a[1]) * j / k]);
21744
+ }
21745
+ if (!closed && p2.length) out.push(p2[p2.length - 1]);
21746
+ return out;
21747
+ }
21748
+ function segDist(p2, a, b) {
21749
+ const dx = b[0] - a[0], dy = b[1] - a[1];
21750
+ const l = dx * dx + dy * dy;
21751
+ let t = l ? ((p2[0] - a[0]) * dx + (p2[1] - a[1]) * dy) / l : 0;
21752
+ t = Math.max(0, Math.min(1, t));
21753
+ return Math.hypot(p2[0] - a[0] - t * dx, p2[1] - a[1] - t * dy);
21754
+ }
21755
+ var EdgeIndex = class {
21756
+ constructor(polys, closed, size) {
21757
+ this.size = size;
21758
+ this.cells = /* @__PURE__ */ new Map();
21759
+ for (const p2 of polys) {
21760
+ const n2 = closed ? p2.length : p2.length - 1;
21761
+ for (let i = 0; i < n2; i++) {
21762
+ const a = p2[i], b = p2[(i + 1) % p2.length];
21763
+ const k = Math.max(1, Math.ceil(dist(a, b) / (size * 2)));
21764
+ for (let j = 0; j < k; j++) {
21765
+ const s = [a[0] + (b[0] - a[0]) * j / k, a[1] + (b[1] - a[1]) * j / k];
21766
+ const e = [
21767
+ a[0] + (b[0] - a[0]) * (j + 1) / k,
21768
+ a[1] + (b[1] - a[1]) * (j + 1) / k
21769
+ ];
21770
+ const x0 = Math.floor(Math.min(s[0], e[0]) / size), x1 = Math.floor(Math.max(s[0], e[0]) / size);
21771
+ const y0 = Math.floor(Math.min(s[1], e[1]) / size), y1 = Math.floor(Math.max(s[1], e[1]) / size);
21772
+ for (let x2 = x0; x2 <= x1; x2++)
21773
+ for (let y = y0; y <= y1; y++) {
21774
+ const key = `${x2},${y}`;
21775
+ const list2 = this.cells.get(key);
21776
+ if (list2) list2.push([s, e]);
21777
+ else this.cells.set(key, [[s, e]]);
21778
+ }
21779
+ }
21780
+ }
21781
+ }
21782
+ }
21783
+ near(p2, tol) {
21784
+ const x0 = Math.floor((p2[0] - tol) / this.size), x1 = Math.floor((p2[0] + tol) / this.size);
21785
+ const y0 = Math.floor((p2[1] - tol) / this.size), y1 = Math.floor((p2[1] + tol) / this.size);
21786
+ for (let x2 = x0; x2 <= x1; x2++)
21787
+ for (let y = y0; y <= y1; y++)
21788
+ for (const [a, b] of this.cells.get(`${x2},${y}`) ?? [])
21789
+ if (segDist(p2, a, b) <= tol) return true;
21790
+ return false;
21791
+ }
21792
+ // Whether the segment from a to b touches or crosses an edge
21793
+ meets(a, b, tol) {
21794
+ const k = Math.max(1, Math.ceil(dist(a, b) / (this.size * 2)));
21795
+ for (let j = 0; j < k; j++) {
21796
+ const s = [a[0] + (b[0] - a[0]) * j / k, a[1] + (b[1] - a[1]) * j / k];
21797
+ const e = [a[0] + (b[0] - a[0]) * (j + 1) / k, a[1] + (b[1] - a[1]) * (j + 1) / k];
21798
+ const x0 = Math.floor((Math.min(s[0], e[0]) - tol) / this.size), x1 = Math.floor((Math.max(s[0], e[0]) + tol) / this.size);
21799
+ const y0 = Math.floor((Math.min(s[1], e[1]) - tol) / this.size), y1 = Math.floor((Math.max(s[1], e[1]) + tol) / this.size);
21800
+ for (let x2 = x0; x2 <= x1; x2++)
21801
+ for (let y = y0; y <= y1; y++)
21802
+ for (const [c, d2] of this.cells.get(`${x2},${y}`) ?? [])
21803
+ if (segSeg(s, e, c, d2) <= tol) return true;
21804
+ }
21805
+ return false;
21806
+ }
21807
+ };
21808
+ function segSeg(a, b, c, d2) {
21809
+ const o = (p2, q, r) => (q[0] - p2[0]) * (r[1] - p2[1]) - (q[1] - p2[1]) * (r[0] - p2[0]);
21810
+ const d1 = o(c, d2, a), d22 = o(c, d2, b), d3 = o(a, b, c), d4 = o(a, b, d2);
21811
+ if (d1 * d22 < 0 && d3 * d4 < 0) return 0;
21812
+ return Math.min(segDist(a, c, d2), segDist(b, c, d2), segDist(c, a, b), segDist(d2, a, b));
21813
+ }
21814
+ function touchesItself(p2, tol, apart2 = 0.2) {
21815
+ const n2 = p2.length;
21816
+ if (n2 < 4) return false;
21817
+ const at2 = [0];
21818
+ for (let i = 1; i <= n2; i++) at2.push(at2[i - 1] + dist(p2[i - 1], p2[i % n2]));
21819
+ const per = at2[n2];
21820
+ const box = bounds([p2]);
21821
+ const size = Math.max(box[2] - box[0], box[3] - box[1], tol) / Math.max(1, Math.sqrt(n2));
21822
+ const cells = /* @__PURE__ */ new Map();
21823
+ const cellsOf = (a, b) => {
21824
+ const keys = [];
21825
+ const x0 = Math.floor((Math.min(a[0], b[0]) - tol) / size), x1 = Math.floor((Math.max(a[0], b[0]) + tol) / size);
21826
+ const y0 = Math.floor((Math.min(a[1], b[1]) - tol) / size), y1 = Math.floor((Math.max(a[1], b[1]) + tol) / size);
21827
+ if ((x1 - x0 + 1) * (y1 - y0 + 1) > 4096) return null;
21828
+ for (let x2 = x0; x2 <= x1; x2++) for (let y = y0; y <= y1; y++) keys.push(`${x2},${y}`);
21829
+ return keys;
21830
+ };
21831
+ for (let i = 0; i < n2; i++) {
21832
+ const a = p2[i], b = p2[(i + 1) % n2];
21833
+ const keys = cellsOf(a, b);
21834
+ if (!keys) return false;
21835
+ for (const k of keys) {
21836
+ for (const j of cells.get(k) ?? []) {
21837
+ const along = Math.abs(at2[i] - at2[j]);
21838
+ if (Math.min(along, per - along) - dist(a, b) - dist(p2[j], p2[(j + 1) % n2]) < apart2)
21839
+ continue;
21840
+ if (segSeg(a, b, p2[j], p2[(j + 1) % n2]) <= tol) return true;
21841
+ }
21842
+ }
21843
+ for (const k of keys) {
21844
+ const l = cells.get(k);
21845
+ if (l) l.push(i);
21846
+ else cells.set(k, [i]);
21847
+ }
21848
+ }
21849
+ return false;
21850
+ }
21851
+ function tangled(polys, tol) {
21852
+ const out = polys.map(() => false);
21853
+ const pairs = [];
21854
+ const boxes = polys.map((p2) => bounds([p2]));
21855
+ polys.forEach((p2, i) => {
21856
+ const u = union2([p2]);
21857
+ const a = u.reduce((s, q) => s + area2(q), 0);
21858
+ const per = perimeter2(p2);
21859
+ const uper = u.reduce((s, q) => s + perimeter2(q), 0);
21860
+ if (u.length !== 1 || Math.abs(a - Math.abs(area2(p2))) > per * 1e-3 + 1e-6 || Math.abs(uper - per) > per * 1e-3 + 0.05 || touchesItself(p2, tol))
21861
+ out[i] = true;
21862
+ });
21863
+ const index = /* @__PURE__ */ new Map();
21864
+ const idx = (i) => {
21865
+ let e = index.get(i);
21866
+ if (!e) index.set(i, e = new EdgeIndex([polys[i]], true, Math.max(tol * 4, 1)));
21867
+ return e;
21868
+ };
21869
+ const order = polys.map((_, i) => i).sort((i, j) => boxes[i][0] - boxes[j][0]);
21870
+ const active = [];
21871
+ for (const i of order) {
21872
+ const [x0, y0, x1, y1] = boxes[i];
21873
+ for (let k = active.length - 1; k >= 0; k--)
21874
+ if (boxes[active[k]][2] < x0 - tol) active.splice(k, 1);
21875
+ for (const j of active) {
21876
+ const b = boxes[j];
21877
+ if (b[1] > y1 + tol || b[3] < y0 - tol) continue;
21878
+ const [s, big] = polys[i].length <= polys[j].length ? [i, j] : [j, i];
21879
+ const p2 = polys[s];
21880
+ const e = idx(big);
21881
+ for (let k = 0; k < p2.length; k++)
21882
+ if (e.meets(p2[k], p2[(k + 1) % p2.length], tol)) {
21883
+ pairs.push([i, j]);
21884
+ break;
21885
+ }
21886
+ }
21887
+ active.push(i);
21888
+ }
21889
+ return { self: out, pairs };
21890
+ }
21891
+ function sameOutlines(a, b, tol, closed = true) {
21892
+ if (!a.length || !b.length) return a.length === b.length;
21893
+ const step = Math.max(tol * 2, 0.2);
21894
+ const ia = new EdgeIndex(a, closed, Math.max(tol * 4, 1));
21895
+ const ib = new EdgeIndex(b, closed, Math.max(tol * 4, 1));
21896
+ for (const p2 of a) for (const q of resample(p2, closed, step)) if (!ib.near(q, tol)) return false;
21897
+ for (const p2 of b) for (const q of resample(p2, closed, step)) if (!ia.near(q, tol)) return false;
21898
+ return true;
21899
+ }
21900
+ function materialTest(outline2, holes, tol) {
21901
+ const idx = new EdgeIndex([outline2, ...holes], true, Math.max(tol * 4, 1));
21902
+ const solid = (q) => inside(q, outline2) && !holes.some((h) => inside(q, h));
21903
+ return (line, closed) => {
21904
+ const n2 = closed ? line.length : line.length - 1;
21905
+ if (n2 < 1) return false;
21906
+ let away;
21907
+ for (let i = 0; i < n2; i++) {
21908
+ const a = line[i], b = line[(i + 1) % line.length];
21909
+ if (!idx.meets(a, b, tol)) {
21910
+ away ??= [(a[0] + b[0]) / 2, (a[1] + b[1]) / 2];
21911
+ continue;
21912
+ }
21913
+ if (closed || i !== 0 && i !== n2 - 1) return false;
21914
+ const l = dist(a, b);
21915
+ const cut = Math.min(tol * 3, l / 3) / l;
21916
+ const s0 = i === 0 ? [a[0] + (b[0] - a[0]) * cut, a[1] + (b[1] - a[1]) * cut] : a;
21917
+ const s1 = i === n2 - 1 ? [b[0] - (b[0] - a[0]) * cut, b[1] - (b[1] - a[1]) * cut] : b;
21918
+ if (idx.meets(s0, s1, tol)) return false;
21919
+ away ??= [(a[0] + b[0]) / 2, (a[1] + b[1]) / 2];
21920
+ }
21921
+ return away ? solid(away) : true;
21922
+ };
21923
+ }
21924
+ function touches(lines, outline2, tol) {
21925
+ if (!lines.length) return false;
21926
+ const idx = new EdgeIndex([outline2], true, Math.max(tol * 4, 1));
21927
+ return lines.some(
21928
+ (l) => resample(l, false, Math.max(tol * 2, 0.2)).some((q) => idx.near(q, tol))
21929
+ );
21930
+ }
21931
+ function inside(pt, poly) {
21932
+ let c = false;
21933
+ for (let i = 0, j = poly.length - 1; i < poly.length; j = i++) {
21934
+ const [xi, yi] = poly[i], [xj, yj] = poly[j];
21935
+ if (yi > pt[1] !== yj > pt[1] && pt[0] < (xj - xi) * (pt[1] - yi) / (yj - yi) + xi) c = !c;
21936
+ }
21937
+ return c;
21938
+ }
21939
+ function fitCircle(pts) {
21940
+ const n2 = pts.length;
21941
+ if (n2 < 3) return null;
21942
+ let mx = 0, my = 0;
21943
+ for (const [x2, y] of pts) {
21944
+ mx += x2;
21945
+ my += y;
21946
+ }
21947
+ mx /= n2;
21948
+ my /= n2;
21949
+ let suu = 0, suv = 0, svv = 0, suuu = 0, svvv = 0, suvv = 0, svuu = 0;
21950
+ for (const [x2, y] of pts) {
21951
+ const u = x2 - mx, v = y - my;
21952
+ suu += u * u;
21953
+ suv += u * v;
21954
+ svv += v * v;
21955
+ suuu += u * u * u;
21956
+ svvv += v * v * v;
21957
+ suvv += u * v * v;
21958
+ svuu += v * u * u;
21959
+ }
21960
+ const det = suu * svv - suv * suv;
21961
+ if (Math.abs(det) < 1e-12) return null;
21962
+ const b1 = (suuu + suvv) / 2, b2 = (svvv + svuu) / 2;
21963
+ const uc = (b1 * svv - b2 * suv) / det, vc = (b2 * suu - b1 * suv) / det;
21964
+ return { c: [uc + mx, vc + my], r: Math.sqrt(uc * uc + vc * vc + (suu + svv) / n2) };
21965
+ }
21966
+ function simplify(p2, tol = 0.01) {
21967
+ if (p2.length < 4) return p2;
21968
+ let far = 0;
21969
+ for (let i = 1; i < p2.length; i++) if (dist(p2[0], p2[i]) > dist(p2[0], p2[far])) far = i;
21970
+ const run = (pts) => {
21971
+ if (pts.length < 3) return pts;
21972
+ let best = 0, at2 = 0;
21973
+ for (let i = 1; i < pts.length - 1; i++) {
21974
+ const d2 = segDist(pts[i], pts[0], pts[pts.length - 1]);
21975
+ if (d2 > best) {
21976
+ best = d2;
21977
+ at2 = i;
21978
+ }
21979
+ }
21980
+ if (best <= tol) return [pts[0], pts[pts.length - 1]];
21981
+ const l = run(pts.slice(0, at2 + 1));
21982
+ return [...l.slice(0, -1), ...run(pts.slice(at2))];
21983
+ };
21984
+ const a = run(p2.slice(0, far + 1));
21985
+ const b = run([...p2.slice(far), p2[0]]);
21986
+ const out = [...a.slice(0, -1), ...b.slice(0, -1)];
21987
+ const tidy2 = [];
21988
+ for (let i = 0; i < out.length; i++) {
21989
+ const prev = out[(i - 1 + out.length) % out.length], next = out[(i + 1) % out.length];
21990
+ if (segDist(out[i], prev, next) > tol) tidy2.push(out[i]);
21991
+ }
21992
+ return tidy2.length >= 3 ? tidy2 : out;
21993
+ }
21994
+ function kerfRadius(polys) {
21995
+ const outer = [];
21996
+ const inner = [];
21997
+ for (const poly of polys.slice(0, 300)) {
21998
+ const c = simplify(poly, 2e-3);
21999
+ const n2 = c.length;
22000
+ const start = c.findIndex((p2, k) => dist(p2, c[(k + 1) % n2]) >= 0.5);
22001
+ if (n2 < 4 || start < 0) continue;
22002
+ const ccw = area2(poly) > 0;
22003
+ let run = [];
22004
+ for (let s = 1; s <= n2; s++) {
22005
+ const k = (start + s) % n2;
22006
+ const p2 = c[k], q = c[(k + 1) % n2];
22007
+ if (dist(p2, q) < 0.3) {
22008
+ if (!run.length) run.push(p2);
22009
+ run.push(q);
22010
+ continue;
22011
+ }
22012
+ if (run.length >= 3) {
22013
+ const f = fitCircle(run);
22014
+ const [a, b, z] = [run[0], run[1], run[run.length - 1]];
22015
+ const turn2 = (b[0] - a[0]) * (z[1] - a[1]) - (b[1] - a[1]) * (z[0] - a[0]);
22016
+ if (f && f.r > 5e-3 && f.r < 0.6) (turn2 > 0 === ccw ? outer : inner).push(f.r);
22017
+ }
22018
+ run = [];
22019
+ }
22020
+ }
22021
+ if (outer.length < 4) return void 0;
22022
+ outer.sort((a, b) => a - b);
22023
+ const mid = outer[Math.floor(outer.length / 2)];
22024
+ const near = (r) => Math.abs(r - mid) <= Math.max(5e-3, mid * 0.1);
22025
+ if (mid > 0.2 || inner.filter(near).length > outer.length * 0.2) return void 0;
22026
+ return outer.filter(near).length >= outer.length * 0.8 ? mid : void 0;
22027
+ }
22028
+ function sharpen(p2, r) {
22029
+ const n2 = p2.length;
22030
+ const short = (i2) => dist(p2[i2], p2[(i2 + 1) % n2]) < r * 1.5;
22031
+ const first2 = p2.findIndex((_, i2) => !short(i2));
22032
+ if (first2 < 0) return p2;
22033
+ const out = [];
22034
+ let i = first2;
22035
+ do {
22036
+ let j = (i + 1) % n2;
22037
+ while (short(j) && j !== i) j = (j + 1) % n2;
22038
+ const run = (j - i - 1 + n2) % n2;
22039
+ const a = p2[i], b = p2[(i + 1) % n2], c = p2[j], d2 = p2[(j + 1) % n2];
22040
+ let corner;
22041
+ if (run > 0) {
22042
+ const den = (b[0] - a[0]) * (d2[1] - c[1]) - (b[1] - a[1]) * (d2[0] - c[0]);
22043
+ if (Math.abs(den) > 1e-12) {
22044
+ const t = ((c[0] - a[0]) * (d2[1] - c[1]) - (c[1] - a[1]) * (d2[0] - c[0])) / den;
22045
+ const x2 = [a[0] + t * (b[0] - a[0]), a[1] + t * (b[1] - a[1])];
22046
+ const mid = p2[(i + 1 + Math.floor(run / 2)) % n2];
22047
+ const arc = [];
22048
+ for (let k = 1; k <= run + 1; k++) arc.push(p2[(i + k) % n2]);
22049
+ const fit = arc.length >= 3 ? fitCircle(arc) : { c: x2, r };
22050
+ const round = !!fit && Math.abs(fit.r - r) <= r * 0.3;
22051
+ if (round && dist(x2, mid) <= r * 2 && t >= 1 - 1e-9) corner = x2;
22052
+ }
22053
+ }
22054
+ out.push(a);
22055
+ if (corner) out.push(corner);
22056
+ else for (let k = 1; k <= run; k++) out.push(p2[(i + k) % n2]);
22057
+ i = j;
22058
+ } while (i !== first2);
22059
+ return out;
22060
+ }
22061
+ function snap(v) {
22062
+ const near = 3e-3;
22063
+ for (const d2 of [0, 1, 2]) {
22064
+ const f = 10 ** d2;
22065
+ const r2 = Math.round(v * f) / f;
22066
+ if (Math.abs(v - r2) <= near) return Object.is(r2, -0) ? 0 : r2;
22067
+ }
22068
+ const r = Math.round(v * 1e3) / 1e3;
22069
+ return Object.is(r, -0) ? 0 : r;
22070
+ }
22071
+ var num2 = (v) => String(snap(v));
22072
+ var vec = (p2) => `[${num2(p2[0])}, ${num2(p2[1])}]`;
22073
+ function angle(a) {
22074
+ a = (a % 360 + 540) % 360 - 180;
22075
+ const r = Math.round(a * 100) / 100;
22076
+ return Math.abs(r - Math.round(r)) < 0.02 ? Math.round(r) : r;
22077
+ }
22078
+ function place(at2, deg, body) {
22079
+ const out = [];
22080
+ if (snap(at2[0]) !== 0 || snap(at2[1]) !== 0) out.push(`translate(${vec(at2)})`);
22081
+ const a = angle(deg);
22082
+ if (a !== 0) out.push(`rotate(${a})`);
22083
+ return [...out, body].join(" ");
22084
+ }
22085
+ function outlineOf(poly, s) {
22086
+ return { poly, area: Math.abs(area2(poly)), box: bounds([poly]), ends: s?.segs.map((g) => g.a) };
22087
+ }
22088
+ var rectPoly = (x0, y0, x1, y1) => [
22089
+ [x0, y0],
22090
+ [x1, y0],
22091
+ [x1, y1],
22092
+ [x0, y1]
22093
+ ];
22094
+ function circleOf(o, tol) {
22095
+ const per = perimeter2(o.poly);
22096
+ const pts = resample(o.poly, true, Math.min(0.5, per / 256));
22097
+ const fit = fitCircle(o.ends && o.ends.length >= 3 ? o.ends : o.poly.length >= 8 ? o.poly : pts);
22098
+ if (!fit || fit.r < 0.05) return void 0;
22099
+ const t = Math.min(tol * 0.6, Math.max(tol / 2, fit.r * 3e-4));
22100
+ for (const p2 of o.poly) if (Math.abs(dist(p2, fit.c) - fit.r) > t) return void 0;
22101
+ const sag = t + fit.r * 2e-4;
22102
+ for (const p2 of pts) if (Math.abs(dist(p2, fit.c) - fit.r) > sag) return void 0;
22103
+ if (Math.abs(o.area - Math.PI * fit.r * fit.r) > per * t * 2) return void 0;
22104
+ return {
22105
+ kind: "circle",
22106
+ body: `circle(d = ${num2(fit.r * 2)})`,
22107
+ at: fit.c,
22108
+ angle: 0,
22109
+ center: fit.c,
22110
+ circle: fit,
22111
+ radius: fit.r
22112
+ };
22113
+ }
22114
+ function principalAngle(pts) {
22115
+ let mx = 0, my = 0;
22116
+ for (const [x2, y] of pts) {
22117
+ mx += x2;
22118
+ my += y;
22119
+ }
22120
+ mx /= pts.length;
22121
+ my /= pts.length;
22122
+ let sxx = 0, syy = 0, sxy = 0;
22123
+ for (const [x2, y] of pts) {
22124
+ sxx += (x2 - mx) ** 2;
22125
+ syy += (y - my) ** 2;
22126
+ sxy += (x2 - mx) * (y - my);
22127
+ }
22128
+ return 0.5 * Math.atan2(2 * sxy, sxx - syy) * 180 / Math.PI;
22129
+ }
22130
+ function ellipseOf(o, tol) {
22131
+ const per = perimeter2(o.poly);
22132
+ const pts = resample(o.poly, true, Math.min(0.5, per / 256));
22133
+ const a = principalAngle(pts);
22134
+ const local = pts.map((p2) => rot(p2, -a));
22135
+ const [x0, y0, x1, y1] = bounds([local]);
22136
+ const rx = (x1 - x0) / 2, ry = (y1 - y0) / 2;
22137
+ if (rx < 0.05 || ry < 0.05 || Math.abs(rx - ry) <= tol) return void 0;
22138
+ const c = [(x0 + x1) / 2, (y0 + y1) / 2];
22139
+ const t = Math.min(tol * 0.6, Math.max(tol / 2, Math.max(rx, ry) * 3e-4)) + Math.max(rx, ry) * 2e-4;
22140
+ for (const [x2, y] of local) {
22141
+ const k = Math.hypot((x2 - c[0]) / rx, (y - c[1]) / ry);
22142
+ if (Math.abs(k - 1) * Math.min(rx, ry) > t) return void 0;
22143
+ }
22144
+ if (Math.abs(o.area - Math.PI * rx * ry) > per * t * 2) return void 0;
22145
+ const center = rot(c, a);
22146
+ return {
22147
+ kind: "ellipse",
22148
+ radius: Math.max(rx, ry),
22149
+ body: `ellipse(${vec([rx, ry])})`,
22150
+ at: center,
22151
+ angle: a,
22152
+ center
22153
+ };
22154
+ }
22155
+ function edgeAngle(corners) {
22156
+ let best = 0, a = 0;
22157
+ for (let i = 0; i < corners.length; i++) {
22158
+ const p2 = corners[i], q = corners[(i + 1) % corners.length];
22159
+ const l = dist(p2, q);
22160
+ if (l > best) {
22161
+ best = l;
22162
+ a = Math.atan2(q[1] - p2[1], q[0] - p2[0]) * 180 / Math.PI;
22163
+ }
22164
+ }
22165
+ a = (a % 90 + 90) % 90;
22166
+ return a > 45 ? a - 90 : a;
22167
+ }
22168
+ function rectOf(o, tol) {
22169
+ const corners = simplify(o.poly, tol / 4);
22170
+ const a = edgeAngle(corners);
22171
+ const per = perimeter2(o.poly);
22172
+ const pts = resample(o.poly, true, Math.min(0.5, per / 256)).map((p2) => rot(p2, -a));
22173
+ const [x0, y0, x1, y1] = bounds([pts]);
22174
+ const w = x1 - x0, h = y1 - y0;
22175
+ if (w < 0.05 || h < 0.05) return void 0;
22176
+ const k = Math.SQRT2 + 1;
22177
+ const rs = [
22178
+ [x0, y0],
22179
+ [x1, y0],
22180
+ [x1, y1],
22181
+ [x0, y1]
22182
+ ].map((c2) => Math.min(...pts.map((p2) => dist(p2, c2))) * k);
22183
+ let r = rs.reduce((s, v) => s + v, 0) / 4;
22184
+ if (Math.max(...rs) - Math.min(...rs) > tol * k) return void 0;
22185
+ if (r < tol) r = 0;
22186
+ r = Math.min(r, w / 2, h / 2);
22187
+ const c = [(x0 + x1) / 2, (y0 + y1) / 2];
22188
+ for (const [x2, y] of pts) {
22189
+ const qx = Math.abs(x2 - c[0]) - (w / 2 - r), qy = Math.abs(y - c[1]) - (h / 2 - r);
22190
+ const sd = Math.hypot(Math.max(qx, 0), Math.max(qy, 0)) + Math.min(Math.max(qx, qy), 0) - r;
22191
+ if (Math.abs(sd) > tol / 2) return void 0;
22192
+ }
22193
+ if (Math.abs(o.area - (w * h - (4 - Math.PI) * r * r)) > per * tol) return void 0;
22194
+ const center = rot(c, a);
22195
+ const rr = snap(r) > 0 ? `, r = ${num2(r)}` : "";
22196
+ return {
22197
+ kind: "rect",
22198
+ radius: r,
22199
+ body: `rect(${vec([w, h])}, center = true${rr})`,
22200
+ at: center,
22201
+ angle: a,
22202
+ center,
22203
+ rect: { w, h, r }
22204
+ };
22205
+ }
22206
+ function regularOf(o, tol) {
22207
+ const corners = simplify(o.poly, tol / 4);
22208
+ const n2 = corners.length;
22209
+ if (n2 < 3 || n2 > 48) return void 0;
22210
+ let cx = 0, cy = 0;
22211
+ for (const [x2, y] of corners) {
22212
+ cx += x2 / n2;
22213
+ cy += y / n2;
22214
+ }
22215
+ const c = [cx, cy];
22216
+ const radii = corners.map((p2) => dist(p2, c));
22217
+ const edges = corners.map((p2, i) => dist(p2, corners[(i + 1) % n2]));
22218
+ const spread = (v) => Math.max(...v) - Math.min(...v);
22219
+ const turns = corners.map((p2) => Math.atan2(p2[1] - cy, p2[0] - cx) * 180 / Math.PI);
22220
+ if (spread(edges) <= tol && spread(radii) <= tol && n2 <= 24) {
22221
+ const r = radii.reduce((s, v) => s + v, 0) / n2;
22222
+ const step = 360 / n2;
22223
+ let a = (turns[0] % step + step) % step;
22224
+ if (step - a < 0.01) a = 0;
22225
+ return {
22226
+ kind: "polygon",
22227
+ body: `regular_polygon(${n2}, ${num2(r)})`,
22228
+ at: c,
22229
+ angle: a,
22230
+ center: c
22231
+ };
22232
+ }
22233
+ if (n2 % 2 === 0 && n2 >= 4 && spread(edges) <= tol) {
22234
+ const outer = radii.filter((_, i) => i % 2 === 0), inner = radii.filter((_, i) => i % 2 === 1);
22235
+ if (spread(outer) > tol || spread(inner) > tol) return void 0;
22236
+ let ro = outer.reduce((s, v) => s + v, 0) / outer.length;
22237
+ let ri = inner.reduce((s, v) => s + v, 0) / inner.length;
22238
+ let first2 = turns[0];
22239
+ if (ri > ro) {
22240
+ [ro, ri] = [ri, ro];
22241
+ first2 = turns[1];
22242
+ }
22243
+ if (ro - ri < tol) return void 0;
22244
+ const pts = n2 / 2;
22245
+ const step = 360 / pts;
22246
+ let a = ((first2 - 90) % step + step) % step;
22247
+ if (step - a < 0.01) a = 0;
22248
+ const def2 = snap(ri) === snap(ro * 0.45);
22249
+ return {
22250
+ kind: "star",
22251
+ body: `star(${pts}, ${num2(ro)}${def2 ? "" : `, ${num2(ri)}`})`,
22252
+ at: c,
22253
+ angle: a,
22254
+ center: c
22255
+ };
22256
+ }
22257
+ return void 0;
22258
+ }
22259
+ function profile(corners, box, eps) {
22260
+ const [X0, Y0, X1, Y1] = box;
22261
+ const outer = [[], [], [], []];
22262
+ const levels = [[], [], [], []];
22263
+ for (let i = 0; i < corners.length; i++) {
22264
+ const a = corners[i], b = corners[(i + 1) % corners.length];
22265
+ if (Math.abs(a[1] - b[1]) <= eps) {
22266
+ const y = a[1];
22267
+ if (Math.abs(y - Y0) <= eps) outer[0].push(sorted(a[0] - X0, b[0] - X0));
22268
+ else if (Math.abs(y - Y1) <= eps) outer[2].push(sorted(X1 - a[0], X1 - b[0]));
22269
+ else {
22270
+ levels[0].push(y - Y0);
22271
+ levels[2].push(Y1 - y);
22272
+ }
22273
+ } else {
22274
+ const x2 = a[0];
22275
+ if (Math.abs(x2 - X1) <= eps) outer[1].push(sorted(a[1] - Y0, b[1] - Y0));
22276
+ else if (Math.abs(x2 - X0) <= eps) outer[3].push(sorted(Y1 - a[1], Y1 - b[1]));
22277
+ else {
22278
+ levels[1].push(X1 - x2);
22279
+ levels[3].push(x2 - X0);
22280
+ }
22281
+ }
22282
+ }
22283
+ const length2 = [X1 - X0, Y1 - Y0, X1 - X0, Y1 - Y0];
22284
+ const depth = levels.map((l) => l.length ? Math.min(...l.filter((v) => v > eps)) : void 0);
22285
+ return { outer: outer.map((iv) => merge2(iv, eps)), depth, length: length2 };
22286
+ }
22287
+ var sorted = (a, b) => a < b ? [a, b] : [b, a];
22288
+ function merge2(iv, eps) {
22289
+ iv.sort((a, b) => a[0] - b[0]);
22290
+ const out = [];
22291
+ for (const [a, b] of iv) {
22292
+ const last2 = out[out.length - 1];
22293
+ if (last2 && a <= last2[1] + eps) last2[1] = Math.max(last2[1], b);
22294
+ else out.push([a, b]);
22295
+ }
22296
+ return out;
22297
+ }
22298
+ var covered = (iv) => iv.reduce((s, [a, b]) => s + b - a, 0);
22299
+ function tabsPoly(w, h, edges, n2, width, t) {
22300
+ const polys = [rectPoly(0, 0, w, h)];
22301
+ const place2 = [
22302
+ ([x2, y]) => [x2, y],
22303
+ ([x2, y]) => [w - y, x2],
22304
+ ([x2, y]) => [w - x2, h - y],
22305
+ ([x2, y]) => [y, h - x2]
22306
+ ];
22307
+ const lengths = [w, h, w, h];
22308
+ edges.forEach((on, i) => {
22309
+ if (!on) return;
22310
+ const L = lengths[i];
22311
+ for (let k = 0; k < n2[i]; k++) {
22312
+ const x2 = L * (k + 0.5) / n2[i];
22313
+ polys.push(rectPoly(x2 - width[i] / 2, -t, x2 + width[i] / 2, 0).map(place2[i]));
22314
+ }
22315
+ });
22316
+ return union2(polys);
22317
+ }
22318
+ function jointOf(o, tol, preferThickness) {
22319
+ const corners = simplify(o.poly, tol / 4);
22320
+ if (corners.length < 8) return void 0;
22321
+ const a = edgeAngle(corners);
22322
+ const local = corners.map((p2) => rot(p2, -a));
22323
+ const eps = tol / 2;
22324
+ for (let i = 0; i < local.length; i++) {
22325
+ const p2 = local[i], q = local[(i + 1) % local.length];
22326
+ if (Math.abs(p2[0] - q[0]) > eps && Math.abs(p2[1] - q[1]) > eps) return void 0;
22327
+ }
22328
+ const box = bounds([local]);
22329
+ const prof = profile(local, box, eps);
22330
+ const shift = (polys, by) => polys.map((p2) => p2.map((q) => add2(q, by)));
22331
+ const matches = (cand, origin2) => sameOutlines([local], shift(cand, origin2), tol);
22332
+ const placed = (corner2, body2, extra) => {
22333
+ const at2 = rot(corner2, a);
22334
+ return {
22335
+ kind: "tabs",
22336
+ body: body2,
22337
+ at: at2,
22338
+ angle: a,
22339
+ center: rot([(box[0] + box[2]) / 2, (box[1] + box[3]) / 2], a),
22340
+ ...extra
22341
+ };
22342
+ };
22343
+ const per = perimeter2(o.poly);
22344
+ const notFlat = [0, 1, 2, 3].filter((i) => covered(prof.outer[i]) < prof.length[i] - eps);
22345
+ if (!notFlat.length) return void 0;
22346
+ const depths = notFlat.map((i) => prof.depth[i]).filter((d3) => d3 !== void 0);
22347
+ if (!depths.length) return void 0;
22348
+ const ts = [...new Set([preferThickness, ...depths].filter((d3) => !!d3).map(snap))];
22349
+ for (const t of ts) {
22350
+ const w = snap(box[2] - box[0]), h = snap(box[3] - box[1]);
22351
+ const edgeSets = [[]];
22352
+ for (let i = 0; i < 4; i++) {
22353
+ const flat = covered(prof.outer[i]) >= prof.length[i] - 2 * t - eps;
22354
+ const opts = flat ? ["flat"] : ["out", "in"];
22355
+ const next = [];
22356
+ for (const s of edgeSets) for (const e of opts) next.push([...s, e]);
22357
+ edgeSets.splice(0, edgeSets.length, ...next);
22358
+ }
22359
+ const def2 = Math.max(3 * t, 6);
22360
+ const fingers = /* @__PURE__ */ new Set([def2]);
22361
+ for (const i of notFlat) {
22362
+ const m = prof.outer[i].length;
22363
+ for (const n3 of [2 * m - 1, 2 * m + 1, 2 * m - 3, 2 * m + 3])
22364
+ if (n3 >= 3) fingers.add(snap(prof.length[i] / n3));
22365
+ }
22366
+ for (const f of fingers)
22367
+ for (const edges2 of edgeSets) {
22368
+ if (edges2.every((e2) => e2 === "flat")) continue;
22369
+ const cand = fingerRect(w, h, edges2, t, f);
22370
+ if (Math.abs(Math.abs(cand.reduce((s, p2) => s + area2(p2), 0)) - o.area) > per * tol)
22371
+ continue;
22372
+ if (!matches(cand, [box[0], box[1]])) continue;
22373
+ const same2 = edges2.every((e2) => e2 === edges2[0]);
22374
+ const e = same2 ? `"${edges2[0]}"` : `[${edges2.map((x2) => `"${x2}"`).join(", ")}]`;
22375
+ const isDef = f === def2 || [0, 1].every((i) => fingerCount(prof.length[i], f) === fingerCount(prof.length[i], def2));
22376
+ return placed(
22377
+ [box[0], box[1]],
22378
+ `finger_rect(${vec([w, h])}, ${e}${isDef ? "" : `, finger = ${num2(f)}`})`,
22379
+ {
22380
+ kind: "fingers",
22381
+ thickness: t,
22382
+ edges: edges2,
22383
+ finger: isDef ? def2 : f
22384
+ }
22385
+ );
22386
+ }
22387
+ const on = [0, 1, 2, 3].map(
22388
+ (i) => notFlat.includes(i) && prof.depth[i] !== void 0 && Math.abs(prof.depth[i] - t) <= eps
22389
+ );
22390
+ if (!on.some(Boolean)) continue;
22391
+ const bx02 = box[0] + (on[3] ? t : 0), by02 = box[1] + (on[0] ? t : 0);
22392
+ const bw2 = snap(box[2] - (on[1] ? t : 0) - bx02), bh2 = snap(box[3] - (on[2] ? t : 0) - by02);
22393
+ const L = [bw2, bh2, bw2, bh2];
22394
+ const offset2 = [on[3] ? t : 0, on[0] ? t : 0, on[1] ? t : 0, on[2] ? t : 0];
22395
+ const n2 = [0, 0, 0, 0], wd = [0, 0, 0, 0];
22396
+ let ok = true;
22397
+ for (let i = 0; i < 4 && ok; i++) {
22398
+ if (!on[i]) continue;
22399
+ const tips = prof.outer[i].map(
22400
+ ([s, e]) => [s - offset2[i], e - offset2[i]]
22401
+ );
22402
+ n2[i] = tips.length;
22403
+ wd[i] = tips.length ? snap(tips.reduce((s, [p2, q]) => s + q - p2, 0) / tips.length) : 0;
22404
+ tips.forEach(([p2, q], k) => {
22405
+ if (Math.abs((p2 + q) / 2 - L[i] * (k + 0.5) / n2[i]) > eps || Math.abs(q - p2 - wd[i]) > eps)
22406
+ ok = false;
22407
+ });
22408
+ }
22409
+ if (!ok || !matches(tabsPoly(bw2, bh2, on, n2, wd, t), [bx02, by02])) continue;
22410
+ const edges = on.every(Boolean) ? "" : `[${on.join(", ")}]`;
22411
+ const used = [0, 1, 2, 3].filter((i) => on[i]);
22412
+ const defCount = (i) => Math.max(1, Math.round(L[i] / 50));
22413
+ const countsDefault = used.every((i) => n2[i] === defCount(i));
22414
+ const oneCount = used.every((i) => n2[i] === n2[used[0]]);
22415
+ const count = countsDefault ? void 0 : oneCount ? n2[used[0]] : null;
22416
+ const widthsDefault = used.every((i) => Math.abs(wd[i] - L[i] / (2 * n2[i])) <= eps);
22417
+ const oneWidth = used.every((i) => Math.abs(wd[i] - wd[used[0]]) <= eps);
22418
+ const width = widthsDefault ? void 0 : oneWidth ? wd[used[0]] : null;
22419
+ let body2;
22420
+ if (count !== null && width !== null) {
22421
+ const args = [vec([bw2, bh2])];
22422
+ if (edges) args.push(edges);
22423
+ else if (count !== void 0 || width !== void 0) args.push("true");
22424
+ if (count !== void 0) args.push(`count = ${count}`);
22425
+ if (width !== void 0) args.push(`width = ${num2(width)}`);
22426
+ body2 = `tab_rect(${args.join(", ")})`;
22427
+ } else {
22428
+ const at2 = [
22429
+ (s) => s,
22430
+ (s) => `translate(${vec([bw2, 0])}) rotate(90) ${s}`,
22431
+ (s) => `translate(${vec([bw2, bh2])}) rotate(180) ${s}`,
22432
+ (s) => `translate(${vec([0, bh2])}) rotate(270) ${s}`
22433
+ ];
22434
+ const lines = [`rect(${vec([bw2, bh2])});`];
22435
+ for (const i of used) {
22436
+ const args = [num2(L[i])];
22437
+ if (n2[i] !== defCount(i)) args.push(`count = ${n2[i]}`);
22438
+ if (Math.abs(wd[i] - L[i] / (2 * n2[i])) > eps) args.push(`width = ${num2(wd[i])}`);
22439
+ lines.push(at2[i](`tabs(${args.join(", ")});`));
22440
+ }
22441
+ body2 = `{
22442
+ ${lines.map((l) => " " + l).join("\n")}
22443
+ }`;
22444
+ }
22445
+ return placed([bx02, by02], body2, {
22446
+ kind: "tabs",
22447
+ thickness: t,
22448
+ library: "tabs",
22449
+ label: `tabs ${num2(t)} mm deep`
22450
+ });
22451
+ }
22452
+ const d2 = prof.depth;
22453
+ if (notFlat.some((i) => d2[i] === void 0)) return void 0;
22454
+ const tabbed = [0, 1, 2, 3].map(
22455
+ (i) => notFlat.includes(i) && covered(prof.outer[i]) < prof.length[i] * 0.4
22456
+ );
22457
+ const bx0 = box[0] + (tabbed[3] ? d2[3] : 0), by0 = box[1] + (tabbed[0] ? d2[0] : 0);
22458
+ const bw = box[2] - (tabbed[1] ? d2[1] : 0) - bx0, bh = box[3] - (tabbed[2] ? d2[2] : 0) - by0;
22459
+ const toBody = (i, s, e, y0, y1) => {
22460
+ if (i === 0) return [box[0] + s - bx0, y0, e - s, y1 - y0];
22461
+ if (i === 1) return [bw - y1, box[1] + s - by0, y1 - y0, e - s];
22462
+ if (i === 2) return [box[2] - e - bx0, bh - y1, e - s, y1 - y0];
22463
+ return [y0, box[3] - e - by0, y1 - y0, e - s];
22464
+ };
22465
+ const tabs = [[], [], [], []];
22466
+ const notches = [[], [], [], []];
22467
+ const corner = [];
22468
+ const span = [
22469
+ [bx0 - box[0], bx0 - box[0] + bw],
22470
+ [by0 - box[1], by0 - box[1] + bh],
22471
+ [box[2] - (bx0 + bw), box[2] - bx0],
22472
+ [box[3] - (by0 + bh), box[3] - by0]
22473
+ ];
22474
+ for (const i of notFlat) {
22475
+ if (tabbed[i]) for (const [s, e] of prof.outer[i]) tabs[i].push(toBody(i, s, e, -d2[i], 0));
22476
+ else {
22477
+ let at2 = span[i][0];
22478
+ for (const [s, e] of [...prof.outer[i], [span[i][1], span[i][1]]]) {
22479
+ const [g0, g1] = [Math.max(at2, span[i][0]), Math.min(s, span[i][1])];
22480
+ if (g1 - g0 > eps) {
22481
+ if (g0 - span[i][0] <= eps || span[i][1] - g1 <= eps) corner.push([i, notches[i].length]);
22482
+ notches[i].push(toBody(i, g0, g1, -1, d2[i]));
22483
+ }
22484
+ at2 = Math.max(at2, e);
22485
+ }
22486
+ }
22487
+ }
22488
+ const rp = ([x2, y, w, h]) => rectPoly(x2, y, x2 + w, y + h);
22489
+ const solidPolys = union2([rectPoly(0, 0, bw, bh), ...tabs.flat().map(rp)]);
22490
+ const fits = () => matches(difference2(solidPolys, notches.flat().map(rp)), [bx0, by0]);
22491
+ if (!fits()) return void 0;
22492
+ for (const [i, k] of corner.reverse()) {
22493
+ const [gone] = notches[i].splice(k, 1);
22494
+ if (!fits()) notches[i].splice(k, 0, gone);
22495
+ }
22496
+ const rows2 = (list2, i) => {
22497
+ const alongX = i % 2 === 0;
22498
+ const pos = (r) => alongX ? r[0] : r[1];
22499
+ list2.sort((p2, q) => pos(p2) - pos(q));
22500
+ const same2 = list2.every(
22501
+ (r) => Math.abs(r[2] - list2[0][2]) <= eps && Math.abs(r[3] - list2[0][3]) <= eps
22502
+ );
22503
+ const step = list2.length > 1 ? pos(list2[1]) - pos(list2[0]) : 0;
22504
+ const even = list2.every((r, k) => Math.abs(pos(r) - pos(list2[0]) - k * step) <= eps);
22505
+ const s = snap(step);
22506
+ const a2 = snap(pos(list2[0]));
22507
+ const b = snap(a2 + s * (list2.length - 1));
22508
+ if (list2.length >= 3 && same2 && even && s > 0 && Math.floor((b - a2) / s + 1e-9) + 1 === list2.length) {
22509
+ const [, , w, h] = list2[0];
22510
+ const v = alongX ? `[x, ${num2(list2[0][1])}]` : `[${num2(list2[0][0])}, y]`;
22511
+ return [
22512
+ `for (${alongX ? "x" : "y"} = [${num2(a2)}:${num2(s)}:${num2(b)}]) translate(${v}) rect(${vec([w, h])});`
22513
+ ];
22514
+ }
22515
+ return list2.map(([x2, y, w, h]) => `translate(${vec([x2, y])}) rect(${vec([w, h])});`);
22516
+ };
22517
+ const plus = [0, 1, 2, 3].flatMap((i) => tabs[i].length ? rows2(tabs[i], i) : []);
22518
+ const minus = [0, 1, 2, 3].flatMap((i) => notches[i].length ? rows2(notches[i], i) : []);
22519
+ const solid = plus.length ? `union() {
22520
+ ${[`rect(${vec([bw, bh])});`, ...plus].join("\n")}
22521
+ }` : `rect(${vec([bw, bh])})`;
22522
+ const body = minus.length ? `difference() {
22523
+ ${[solid.endsWith("}") ? solid : solid + ";", ...minus].join("\n")}
22524
+ }` : solid;
22525
+ const ds = notFlat.map((i) => snap(d2[i]));
22526
+ const common = ds.sort(
22527
+ (p2, q) => ds.filter((v) => v === q).length - ds.filter((v) => v === p2).length
22528
+ )[0];
22529
+ return placed([bx0, by0], body, {
22530
+ kind: minus.length ? "fingers" : "tabs",
22531
+ thickness: common,
22532
+ generic: true,
22533
+ label: `${minus.length ? "finger joints" : "tabs"} ${num2(common)} mm deep`
22534
+ });
22535
+ }
22536
+ function deepest(poly) {
22537
+ const [x0, y0, x1, y1] = bounds([poly]);
22538
+ const d2 = (p2) => {
22539
+ let m = Infinity;
22540
+ for (let i = 0, j = poly.length - 1; i < poly.length; j = i++)
22541
+ m = Math.min(m, segDist(p2, poly[j], poly[i]));
22542
+ return m;
22543
+ };
22544
+ let best = [(x0 + x1) / 2, (y0 + y1) / 2], bestD = inside(best, poly) ? d2(best) : 0;
22545
+ const n2 = 24;
22546
+ for (let i = 0; i <= n2; i++)
22547
+ for (let j = 0; j <= n2; j++) {
22548
+ const p2 = [x0 + (x1 - x0) * i / n2, y0 + (y1 - y0) * j / n2];
22549
+ if (!inside(p2, poly)) continue;
22550
+ const v = d2(p2);
22551
+ if (v > bestD) {
22552
+ best = p2;
22553
+ bestD = v;
22554
+ }
22555
+ }
22556
+ let step = Math.max(x1 - x0, y1 - y0) / n2;
22557
+ while (step > 1e-4) {
22558
+ let moved = false;
22559
+ for (const [dx, dy] of [
22560
+ [1, 0],
22561
+ [-1, 0],
22562
+ [0, 1],
22563
+ [0, -1]
22564
+ ]) {
22565
+ const p2 = [best[0] + dx * step, best[1] + dy * step];
22566
+ if (!inside(p2, poly)) continue;
22567
+ const v = d2(p2);
22568
+ if (v > bestD) {
22569
+ best = p2;
22570
+ bestD = v;
22571
+ moved = true;
22572
+ }
22573
+ }
22574
+ if (!moved) step /= 2;
22575
+ }
22576
+ return { c: best, r: bestD };
22577
+ }
22578
+ function capsule(a, b, r) {
22579
+ const n2 = 64;
22580
+ const ang = Math.atan2(b[1] - a[1], b[0] - a[0]);
22581
+ const out = [];
22582
+ for (let i = 0; i <= n2; i++) {
22583
+ const t = ang + Math.PI / 2 + Math.PI * i / n2;
22584
+ out.push([a[0] + r * Math.cos(t), a[1] + r * Math.sin(t)]);
22585
+ }
22586
+ for (let i = 0; i <= n2; i++) {
22587
+ const t = ang - Math.PI / 2 + Math.PI * i / n2;
22588
+ out.push([b[0] + r * Math.cos(t), b[1] + r * Math.sin(t)]);
22589
+ }
22590
+ return out;
22591
+ }
22592
+ function keyholeOf(o, tol) {
22593
+ const [x0, y0, x1, y1] = o.box;
22594
+ if (Math.max(x1 - x0, y1 - y0) > 80) return void 0;
22595
+ const per = perimeter2(o.poly);
22596
+ const pts = resample(o.poly, true, Math.min(0.25, per / 400));
22597
+ const head = deepest(o.poly);
22598
+ const onHead = pts.filter((p2) => Math.abs(dist(p2, head.c) - head.r) <= tol);
22599
+ const fit = fitCircle(onHead);
22600
+ if (!fit || onHead.length < 8) return void 0;
22601
+ let end = pts[0];
22602
+ for (const p2 of pts) if (dist(p2, fit.c) > dist(end, fit.c)) end = p2;
22603
+ const far = dist(end, fit.c);
22604
+ let dir = [(end[0] - fit.c[0]) / far, (end[1] - fit.c[1]) / far];
22605
+ const along = (p2) => (p2[0] - fit.c[0]) * dir[0] + (p2[1] - fit.c[1]) * dir[1];
22606
+ const across = (p2) => -(p2[0] - fit.c[0]) * dir[1] + (p2[1] - fit.c[1]) * dir[0];
22607
+ let side = pts.filter((p2) => along(p2) > fit.r + tol && along(p2) < far - fit.r);
22608
+ if (side.length < 4) return void 0;
22609
+ const sides = [side.filter((p2) => across(p2) > 0), side.filter((p2) => across(p2) < 0)];
22610
+ if (sides.some((s) => s.length < 2)) return void 0;
22611
+ const turned = sides.map((s) => rot([1, 0], principalAngle(s))).map((u) => u[0] * dir[0] + u[1] * dir[1] < 0 ? [-u[0], -u[1]] : u);
22612
+ const mean = [turned[0][0] + turned[1][0], turned[0][1] + turned[1][1]];
22613
+ const m = Math.hypot(mean[0], mean[1]);
22614
+ dir = [mean[0] / m, mean[1] / m];
22615
+ side = pts.filter((p2) => along(p2) > fit.r + tol && along(p2) < far - fit.r);
22616
+ if (side.length < 4) return void 0;
22617
+ if (Math.abs(side.reduce((s, p2) => s + across(p2), 0) / side.length) > tol) return void 0;
22618
+ const halves = side.map((p2) => Math.abs(across(p2))).sort((a, b) => a - b);
22619
+ const shank = halves[Math.floor(halves.length / 2)] * 2;
22620
+ if (shank >= fit.r * 2 - tol || shank < 0.3) return void 0;
22621
+ const len = Math.max(...pts.map(along));
22622
+ const top = add2(fit.c, [dir[0] * (len - shank / 2), dir[1] * (len - shank / 2)]);
22623
+ const cand = union2([
22624
+ ellipsePoly(fit.r, fit.r, 256).map((p2) => add2(p2, fit.c)),
22625
+ capsule(fit.c, top, shank / 2)
22626
+ ]);
22627
+ if (!sameOutlines([o.poly], cand, tol)) return void 0;
22628
+ const drop = len - shank / 2;
22629
+ const headD = fit.r * 2;
22630
+ const deg = Math.atan2(dir[1], dir[0]) * 180 / Math.PI - 90;
22631
+ const args = [];
22632
+ if (snap(headD) !== 9) args.push(`head = ${num2(headD)}`);
22633
+ if (snap(shank) !== 4.5) args.push(`shank = ${num2(shank)}`);
22634
+ if (snap(drop) !== 10) args.push(`drop = ${num2(drop)}`);
22635
+ const fits = drop >= (headD + shank) / 2 - 1e-9;
22636
+ const body = fits ? `keyhole(${args.join(", ")})` : `{ translate(${vec([0, -drop])}) circle(d = ${num2(headD)}); hull() { circle(d = ${num2(shank)}); translate(${vec([0, -drop])}) circle(d = ${num2(shank)}); } }`;
22637
+ return {
22638
+ kind: "keyhole",
22639
+ radius: headD / 2,
22640
+ body,
22641
+ at: top,
22642
+ angle: deg,
22643
+ center: top,
22644
+ label: "keyhole",
22645
+ keyhole: { head: headD, shank, drop, top },
22646
+ library: fits ? "hanging" : void 0
22647
+ };
22648
+ }
22649
+ var SAME = 25e-4;
22650
+ var apart = (a, b) => Math.abs(a[0] - b[0]) > SAME || Math.abs(a[1] - b[1]) > SAME;
22651
+ function outlineCode(s, origin2) {
22652
+ if (s.segs.every((g) => g.c === "L") && s.segs.length < 400) {
22653
+ const all = s.segs.map((g) => g.a);
22654
+ if (!s.closed) all.push(s.segs[s.segs.length - 1].b);
22655
+ const pts = [all[0]];
22656
+ for (const q of all.slice(1)) if (apart(q, pts[pts.length - 1])) pts.push(q);
22657
+ if (!s.closed && pts.length < 2) pts.push(all[all.length - 1]);
22658
+ const list2 = `[${pts.map((q) => vec(sub(q, origin2))).join(", ")}]`;
22659
+ if (!s.closed)
22660
+ return pts.length === 2 ? `line(${vec(sub(pts[0], origin2))}, ${vec(sub(pts[1], origin2))})` : `polyline(${list2})`;
22661
+ return `polygon(${list2})`;
22662
+ }
22663
+ return `path("${pathData([s], origin2)}")`;
22664
+ }
22665
+ function pathData(subs, origin2) {
22666
+ const p2 = (q) => `${num2(q[0] - origin2[0])} ${num2(q[1] - origin2[1])}`;
22667
+ return subs.map((s) => {
22668
+ let d2 = `M${p2(s.segs[0].a)}`;
22669
+ let at2 = s.segs[0].a;
22670
+ for (const g of s.segs) {
22671
+ if (!apart(g.b, at2) && (g.c === "L" || !apart(g.p1, at2) && !apart(g.p2, at2))) continue;
22672
+ d2 += g.c === "L" ? `L${p2(g.b)}` : `C${p2(g.p1)} ${p2(g.p2)} ${p2(g.b)}`;
22673
+ at2 = g.b;
22674
+ }
22675
+ return s.closed ? d2 + "Z" : d2;
22676
+ }).join("");
22677
+ }
22678
+
22679
+ // src/import/index.ts
22680
+ var JOIN = 0.01;
22681
+ function reverse(s) {
22682
+ return {
22683
+ closed: s.closed,
22684
+ segs: s.segs.slice().reverse().map(
22685
+ (g) => g.c === "L" ? { c: "L", a: g.b, b: g.a } : { c: "C", a: g.b, p1: g.p2, p2: g.p1, b: g.a }
22686
+ )
22687
+ };
22688
+ }
22689
+ var first = (s) => s.segs[0].a;
22690
+ var last = (s) => s.segs[s.segs.length - 1].b;
22691
+ function chain(open) {
22692
+ const used = /* @__PURE__ */ new Set();
22693
+ const out = [];
22694
+ const cell = (p2) => `${Math.round(p2[0] / JOIN)},${Math.round(p2[1] / JOIN)}`;
22695
+ const ends = /* @__PURE__ */ new Map();
22696
+ open.forEach((s, i) => {
22697
+ for (const p2 of [first(s), last(s)]) {
22698
+ const k = cell(p2);
22699
+ ends.set(k, [...ends.get(k) ?? [], i]);
22700
+ }
22701
+ });
22702
+ const near = (p2) => {
22703
+ const [cx, cy] = [Math.round(p2[0] / JOIN), Math.round(p2[1] / JOIN)];
22704
+ for (let dx = -1; dx <= 1; dx++)
22705
+ for (let dy = -1; dy <= 1; dy++)
22706
+ for (const i of ends.get(`${cx + dx},${cy + dy}`) ?? [])
22707
+ if (!used.has(i) && (dist(first(open[i]), p2) <= JOIN || dist(last(open[i]), p2) <= JOIN))
22708
+ return i;
22709
+ return void 0;
22710
+ };
22711
+ for (let i = 0; i < open.length; i++) {
22712
+ if (used.has(i)) continue;
22713
+ used.add(i);
22714
+ let segs = open[i].segs.slice();
22715
+ for (let pass = 0; pass < 2; pass++) {
22716
+ for (; ; ) {
22717
+ const end = segs[segs.length - 1].b;
22718
+ if (dist(end, segs[0].a) <= JOIN && segs.length > 1) break;
22719
+ const j = near(end);
22720
+ if (j === void 0) break;
22721
+ used.add(j);
22722
+ const s = dist(first(open[j]), end) <= JOIN ? open[j] : reverse(open[j]);
22723
+ segs = segs.concat(s.segs);
22724
+ }
22725
+ segs = reverse({ segs, closed: false }).segs;
22726
+ }
22727
+ const closed = segs.length > 1 && dist(segs[segs.length - 1].b, segs[0].a) <= JOIN;
22728
+ out.push({ sub: { segs, closed }, from: open[i] });
22729
+ }
22730
+ return out;
22731
+ }
22732
+ var DEFAULT_TOL = 0.05;
22733
+ function decodeSvg(bytes) {
22734
+ const b = bytes instanceof Uint8Array ? bytes : new Uint8Array(bytes);
22735
+ const encoding = b[0] === 255 && b[1] === 254 || b[0] === 60 && b[1] === 0 ? "utf-16le" : b[0] === 254 && b[1] === 255 || b[0] === 0 && b[1] === 60 ? "utf-16be" : "utf-8";
22736
+ return new TextDecoder(encoding).decode(b);
22737
+ }
22738
+ function importSvg(svg, options = {}) {
22739
+ const tol = options.tolerance ?? DEFAULT_TOL;
22740
+ const text3 = typeof svg === "string" ? svg : decodeSvg(svg);
22741
+ const drawing = readSvg(text3, { dpi: options.dpi });
22742
+ const notes = [...drawing.notes];
22743
+ const found = {};
22744
+ const count = (k, n2 = 1) => found[k] = (found[k] ?? 0) + n2;
22745
+ const closed = [];
22746
+ let open = [];
22747
+ const openNames = /* @__PURE__ */ new Map();
22748
+ for (const it of drawing.items) {
22749
+ if (it.layer.mode !== "cut") continue;
22750
+ for (const s of it.subs) {
22751
+ if (s.closed) closed.push({ sub: s, names: it.names, group: it.filled ? it : void 0 });
22752
+ else {
22753
+ open.push(s);
22754
+ openNames.set(s, it.names);
22755
+ }
22756
+ }
22757
+ }
22758
+ const chained = chain(open);
22759
+ open = [];
22760
+ for (const { sub: s, from } of chained)
22761
+ if (s.closed)
22762
+ closed.push({
22763
+ sub: s,
22764
+ names: openNames.get(from) ?? [],
22765
+ line: { segs: s.segs, closed: false }
22766
+ });
22767
+ else open.push(s);
22768
+ const all = closed.map((c) => ({ ...c, outline: outlineOf(flattenSub(c.sub), c.sub) }));
22769
+ const flat = all.filter(
22770
+ (c) => c.outline.poly.length >= 3 && c.outline.area > perimeter2(c.outline.poly) * JOIN
22771
+ );
22772
+ for (const c of all)
22773
+ if (!flat.includes(c)) open.push(c.line ?? { segs: c.sub.segs, closed: false });
22774
+ const within = (o, p2, og, pg) => {
22775
+ if (og !== pg) return false;
22776
+ const [a0, b0, a1, b1] = o.box, [c0, d0, c1, d1] = p2.box;
22777
+ if (a0 < c0 - JOIN || b0 < d0 - JOIN || a1 > c1 + JOIN || b1 > d1 + JOIN) return false;
22778
+ const n2 = o.poly.length;
22779
+ const votes2 = [0, Math.floor(n2 / 3), Math.floor(2 * n2 / 3)].filter(
22780
+ (i) => inside(o.poly[i], p2.poly)
22781
+ ).length;
22782
+ return votes2 >= 2;
22783
+ };
22784
+ const nestOf = (skip) => {
22785
+ const order = flat.map((_, i) => i).filter((i) => !skip.has(i)).sort((i, j) => flat[j].outline.area - flat[i].outline.area);
22786
+ const parent2 = /* @__PURE__ */ new Map(), depth2 = /* @__PURE__ */ new Map();
22787
+ order.forEach((i, k) => {
22788
+ let best = -1;
22789
+ for (let m = k - 1; m >= 0; m--) {
22790
+ const j = order[m];
22791
+ if (flat[j].outline.area > flat[i].outline.area && within(flat[i].outline, flat[j].outline, flat[i].group, flat[j].group)) {
22792
+ best = j;
22793
+ break;
22794
+ }
22795
+ }
22796
+ parent2.set(i, best);
22797
+ depth2.set(i, best < 0 ? 0 : depth2.get(best) + 1);
22798
+ });
22799
+ return { order, parent: parent2, depth: depth2 };
22800
+ };
22801
+ const knots = tangled(
22802
+ flat.map((c) => c.outline.poly),
22803
+ JOIN * 2
22804
+ );
22805
+ const nest = nestOf(/* @__PURE__ */ new Set());
22806
+ const { parent, depth } = nest;
22807
+ const part = (k) => depth.get(k) % 2 === 0 ? k : parent.get(k);
22808
+ const lined = new Set(flat.map((_, i) => i).filter((i) => knots.self[i]));
22809
+ for (const [i, j] of knots.pairs) if (part(i) === part(j)) lined.add(i).add(j);
22810
+ for (const i of nest.order)
22811
+ if (depth.get(i) % 2 === 1 && lined.has(parent.get(i))) lined.add(i);
22812
+ for (const i of lined) open.push(flat[i].line ?? { segs: flat[i].sub.segs, closed: false });
22813
+ if (lined.size)
22814
+ notes.push(
22815
+ `${lined.size} outline${lined.size === 1 ? " touches or crosses" : "s touch or cross"} a hole or ${lined.size === 1 ? "itself" : "themselves"}, so ${lined.size === 1 ? "it is" : "they are"} kept as cut lines.`
22816
+ );
22817
+ const bodies = [];
22818
+ const bodyOf = /* @__PURE__ */ new Map();
22819
+ for (const i of nest.order) {
22820
+ if (lined.has(i)) continue;
22821
+ const o = flat[i];
22822
+ if (depth.get(i) % 2 === 0) {
22823
+ const b = {
22824
+ sub: o.sub,
22825
+ outline: o.outline,
22826
+ names: o.names,
22827
+ holes: [],
22828
+ lines: [],
22829
+ marks: /* @__PURE__ */ new Map(),
22830
+ texts: []
22831
+ };
22832
+ bodies.push(b);
22833
+ bodyOf.set(i, b);
22834
+ } else bodyOf.get(parent.get(i)).holes.push({ sub: o.sub, outline: o.outline, line: o.line });
22835
+ }
22836
+ const half = options.kerf !== void 0 ? options.kerf / 2 : kerfRadius(bodies.map((b) => b.outline.poly));
22837
+ let kerf = 0;
22838
+ if (half && half > 0) {
22839
+ const asSub = (p2) => ({
22840
+ closed: true,
22841
+ segs: p2.map((a, i) => ({ c: "L", a, b: p2[(i + 1) % p2.length] }))
22842
+ });
22843
+ for (const b of bodies) {
22844
+ const material = difference2(
22845
+ [sharpen(b.outline.poly, half)],
22846
+ b.holes.map((h) => sharpen(h.outline.poly, half))
22847
+ );
22848
+ const back = pieces(offset(material, -half, "miter"));
22849
+ const again = offset(back.flat(), half, "round", Math.min(0.01, half / 10));
22850
+ const drawn = difference2(
22851
+ [b.outline.poly],
22852
+ b.holes.map((h) => h.outline.poly)
22853
+ );
22854
+ const thin = (p2) => Math.abs(area2(p2)) <= perimeter2(p2) * JOIN;
22855
+ if (back.length !== 1 || back[0].length !== b.holes.length + 1 || back[0].some(thin) || !sameOutlines(again, drawn, tol)) {
22856
+ b.noKerf = true;
22857
+ continue;
22858
+ }
22859
+ b.drawn = [b.sub, ...b.holes.map((h) => h.sub)];
22860
+ const [outer, ...inner] = back[0].map((p2) => simplify(p2, 1e-3));
22861
+ b.outline = outlineOf(outer);
22862
+ b.sub = asSub(outer);
22863
+ const mid = (o) => [(o.box[0] + o.box[2]) / 2, (o.box[1] + o.box[3]) / 2];
22864
+ const left = inner.map((p2) => outlineOf(p2));
22865
+ for (const h of b.holes) {
22866
+ const c = mid(h.outline);
22867
+ const hit = left.reduce((x2, y) => dist(mid(y), c) < dist(mid(x2), c) ? y : x2);
22868
+ left.splice(left.indexOf(hit), 1);
22869
+ h.outline = hit;
22870
+ h.sub = asSub(hit.poly);
22871
+ h.line = void 0;
22872
+ }
22873
+ }
22874
+ kerf = half * 2;
22875
+ if (options.kerf === void 0)
22876
+ notes.push(
22877
+ `The cut outlines are offset for a ${num2(kerf)} mm kerf: they are moved back, and $kerf is set.`
22878
+ );
22879
+ }
22880
+ const owner = (p2) => {
22881
+ let best;
22882
+ for (const b of bodies) {
22883
+ const [x0, y0, x1, y1] = b.outline.box;
22884
+ if (p2[0] < x0 || p2[0] > x1 || p2[1] < y0 || p2[1] > y1) continue;
22885
+ if (!inside(p2, b.outline.poly)) continue;
22886
+ if (!best || b.outline.area < best.outline.area) best = b;
22887
+ }
22888
+ return best;
22889
+ };
22890
+ const loose = { lines: [], marks: /* @__PURE__ */ new Map(), texts: [] };
22891
+ const tests = /* @__PURE__ */ new Map();
22892
+ const home = (s) => {
22893
+ const b = owner(first(s));
22894
+ if (!b) return void 0;
22895
+ let test = tests.get(b);
22896
+ if (!test) {
22897
+ test = materialTest(
22898
+ b.outline.poly,
22899
+ b.holes.map((h) => h.outline.poly),
22900
+ tol
22901
+ );
22902
+ tests.set(b, test);
22903
+ }
22904
+ return test(flattenSub(s, 0.02), s.closed) ? b : void 0;
22905
+ };
22906
+ for (const s of open) {
22907
+ const b = home(s);
22908
+ (b ? b.lines : loose.lines).push(s);
22909
+ }
22910
+ for (const it of drawing.items) {
22911
+ if (it.layer.mode === "cut") continue;
22912
+ for (const s of it.subs) {
22913
+ const marks = (home(s) ?? loose).marks;
22914
+ marks.set(it, [...marks.get(it) ?? [], s]);
22915
+ }
22916
+ }
22917
+ for (const t of drawing.texts) (owner(t.at) ?? loose).texts.push(t);
22918
+ if (drawing.texts.some((t) => t.layer.mode === "cut"))
22919
+ notes.push(
22920
+ "Text to cut is written with the built-in font, so its letters are not the drawing's: convert the text to paths in your editor to cut it as drawn."
22921
+ );
22922
+ for (const b of bodies) {
22923
+ const flat2 = b.lines.map((l) => flattenSub(l));
22924
+ b.holes = b.holes.filter((h) => {
22925
+ if (!h.line) return true;
22926
+ const into = (p2) => inside(p2, h.outline.poly);
22927
+ const full = touches(flat2, h.outline.poly, JOIN * 2) || b.lines.some((l) => into(first(l))) || [...b.marks.values()].some((subs) => subs.some((m) => into(first(m)))) || b.texts.some((t) => into(t.at)) || bodies.some((o) => o !== b && o.outline.area < h.outline.area && into(o.outline.poly[0]));
22928
+ if (full) b.lines.push(h.line);
22929
+ return !full;
22930
+ });
22931
+ }
22932
+ const recogniseHole = (o) => circleOf(o, tol) ?? rectOf(o, tol) ?? ellipseOf(o, tol) ?? regularOf(o, tol) ?? keyholeOf(o, tol);
22933
+ const bodyFound = /* @__PURE__ */ new Map();
22934
+ for (const b of bodies) {
22935
+ const f = circleOf(b.outline, tol) ?? rectOf(b.outline, tol) ?? ellipseOf(b.outline, tol) ?? regularOf(b.outline, tol) ?? jointOf(b.outline, tol);
22936
+ bodyFound.set(b, f);
22937
+ for (const h of b.holes) h.found = recogniseHole(h.outline);
22938
+ }
22939
+ const votes = /* @__PURE__ */ new Map();
22940
+ const own4 = [...bodyFound.values()].some((f) => f?.thickness && !f.generic);
22941
+ for (const f of bodyFound.values())
22942
+ if (f?.thickness && f.thickness <= 10 && (own4 ? !f.generic : true))
22943
+ votes.set(f.thickness, (votes.get(f.thickness) ?? 0) + 1);
22944
+ let thickness = [...votes.entries()].sort((a, b) => b[1] - a[1])[0]?.[0];
22945
+ if (thickness !== void 0)
22946
+ for (const b of bodies) {
22947
+ const f = bodyFound.get(b);
22948
+ if (f?.thickness !== void 0 && f.thickness !== thickness) {
22949
+ const again = jointOf(b.outline, tol, thickness);
22950
+ if (again && again.thickness === thickness) bodyFound.set(b, again);
22951
+ }
22952
+ }
22953
+ const fingerWidths = /* @__PURE__ */ new Set();
22954
+ for (const f of bodyFound.values())
22955
+ if (f?.kind === "fingers" && f.finger) fingerWidths.add(snap(f.finger));
22956
+ bodies.sort((a, b) => {
22957
+ const dy = b.outline.box[3] - a.outline.box[3];
22958
+ return Math.abs(dy) > 1 ? dy : a.outline.box[0] - b.outline.box[0];
22959
+ });
22960
+ const libraries2 = /* @__PURE__ */ new Set();
22961
+ const usedNames = /* @__PURE__ */ new Map();
22962
+ const parts = [];
22963
+ for (const [i, b] of bodies.entries()) {
22964
+ const base = b.names[0] ?? `part ${i + 1}`;
22965
+ const k = (usedNames.get(base) ?? 0) + 1;
22966
+ usedNames.set(base, k);
22967
+ const name = k > 1 ? `${base} ${k}` : base;
22968
+ let done;
22969
+ for (const level of [2, 1, 0]) {
22970
+ const attempt = writePart(b, bodyFound.get(b), level, thickness, fingerWidths, tol);
22971
+ if (verify(attempt, b, tol)) {
22972
+ done = attempt;
22973
+ if (level < 2)
22974
+ notes.push(
22975
+ level === 1 ? `Part "${name}": its holes are written one by one; grouping them did not match the drawing.` : `Part "${name}" is written as drawn: no recognised shape matched it closely enough.`
22976
+ );
22977
+ break;
22978
+ }
22979
+ }
22980
+ if (!done) {
22981
+ const drawn = b.drawn ?? [b.sub, ...b.holes.map((h) => h.sub)];
22982
+ loose.lines.push(...drawn.map((s) => ({ segs: s.segs, closed: false })), ...b.lines);
22983
+ for (const [it, subs] of b.marks)
22984
+ loose.marks.set(it, [...loose.marks.get(it) ?? [], ...subs]);
22985
+ loose.texts.push(...b.texts);
22986
+ notes.push(`Part "${name}" is cut as lines: no shape reproduces its outline exactly.`);
22987
+ continue;
22988
+ }
22989
+ for (const k2 of done.found) count(k2);
22990
+ for (const l of done.libraries) libraries2.add(l);
22991
+ const marks = writeMarks(b.marks, [], b.texts, done.origin);
22992
+ const inner = [...done.cut, ...marks];
22993
+ const t = done.thickness;
22994
+ const own5 = [
22995
+ ...t !== void 0 && (thickness === void 0 || snap(t) !== snap(thickness)) ? [`thickness = ${num2(t)}`] : [],
22996
+ ...b.noKerf && kerf > 0 ? ["kerf = 0"] : []
22997
+ ];
22998
+ const wrap = own5.length ? `material(${own5.join(", ")}) ` : "";
22999
+ const head = `part("${name.replace(/["\\]/g, "")}")`;
23000
+ const local = inner.length === 1 && !inner[0].includes("\n") ? `${wrap}${head} ${inner[0]}` : `${wrap}${head} {
23001
+ ${inner.join("\n")}
23002
+ }`;
23003
+ parts.push({ name, code: place(done.origin, 0, local), local, thickness: t });
23004
+ }
23005
+ const looseCode = writeMarks(loose.marks, loose.lines, loose.texts, [0, 0]);
23006
+ if (looseCode.length && bodies.length)
23007
+ notes.push("Some lines or marks are outside every part; they are kept on their own.");
23008
+ let body;
23009
+ if (options.pack) {
23010
+ const groups = /* @__PURE__ */ new Map();
23011
+ for (const p2 of parts) {
23012
+ const key = p2.local.replace(/part\("[^"]*"\)/, "part()");
23013
+ const g = groups.get(key);
23014
+ if (g) g.qty++;
23015
+ else groups.set(key, { name: p2.name, qty: 1 });
23016
+ }
23017
+ body = [...groups.entries()].map(
23018
+ ([key, g]) => key.replace(
23019
+ "part()",
23020
+ `part("${g.name.replace(/["\\]/g, "")}"${g.qty > 1 ? `, qty = ${g.qty}` : ""})`
23021
+ )
23022
+ );
23023
+ const merged = parts.length - groups.size;
23024
+ if (merged)
23025
+ notes.push(
23026
+ `${merged} part${merged === 1 ? " is" : "s are"} the same as another and became a quantity.`
23027
+ );
23028
+ } else body = parts.map((p2) => p2.code);
23029
+ const kinds = Object.entries(found).filter(([k]) => k !== "outline").map(([k, n2]) => `${n2} ${k}${n2 === 1 ? "" : PLURAL[k] ?? "s"}`).join(", ");
23030
+ const summary = `${parts.length} part${parts.length === 1 ? "" : "s"}${kinds ? `; found ${kinds}` : ""}.`;
23031
+ const header2 = [
23032
+ `// ${options.name ? options.name + ": " : ""}imported from an SVG drawing.`,
23033
+ `// ${summary}`,
23034
+ ...notes.map((n2) => `// ${n2}`),
23035
+ "",
23036
+ ...[...libraries2].sort().map((l) => `use <kerf/${l}>`),
23037
+ ...libraries2.size ? [""] : []
23038
+ ];
23039
+ const settings = [];
23040
+ if (thickness !== void 0) settings.push(`$thickness = ${num2(thickness)}; // from the joints`);
23041
+ if (kerf > 0)
23042
+ settings.push(`$kerf = ${num2(kerf)}; // the drawing's outlines were offset by half of this`);
23043
+ if (!options.pack && parts.length)
23044
+ settings.push('$layout = "none"; // keep the parts where the drawing has them');
23045
+ const sections = [
23046
+ header2.join("\n"),
23047
+ settings.join("\n"),
23048
+ body.join("\n\n"),
23049
+ looseCode.join("\n")
23050
+ ].filter(Boolean);
23051
+ let source = sections.join("\n\n").replace(/\n{3,}/g, "\n\n") + "\n";
23052
+ try {
23053
+ source = format(source);
23054
+ } catch {
23055
+ }
23056
+ return { source, parts: parts.length, found, summary, notes };
23057
+ }
23058
+ var PLURAL = {
23059
+ "finger jointed panel": "s",
23060
+ "hanger hole": "s",
23061
+ "slot row": "s",
23062
+ "hanging loop": "s",
23063
+ "hole pattern": "s"
23064
+ };
23065
+ var stmt = (s) => s.trimEnd().endsWith("}") ? s : s + ";";
23066
+ function writePart(b, bf, level, thickness, fingerWidths, tol) {
23067
+ const found = [];
23068
+ const libraries2 = /* @__PURE__ */ new Set();
23069
+ const bodyF = level > 0 ? bf : void 0;
23070
+ const box = b.outline.box;
23071
+ let origin2;
23072
+ let bodyCode;
23073
+ if (bodyF?.kind === "rect") {
23074
+ const { w, h, r } = bodyF.rect;
23075
+ origin2 = sub(bodyF.center, rot([w / 2, h / 2], bodyF.angle));
23076
+ origin2 = [snap(origin2[0]), snap(origin2[1])];
23077
+ bodyCode = place(
23078
+ [0, 0],
23079
+ bodyF.angle,
23080
+ `rect(${vec([w, h])}${snap(r) > 0 ? `, r = ${num2(r)}` : ""})`
23081
+ );
23082
+ found.push("rectangle");
23083
+ } else if (bodyF) {
23084
+ origin2 = [snap(bodyF.at[0]), snap(bodyF.at[1])];
23085
+ bodyCode = place(sub(bodyF.at, origin2), bodyF.angle, bodyF.body);
23086
+ found.push(KIND[bodyF.kind]);
23087
+ if (bodyF.library) libraries2.add(bodyF.library);
23088
+ } else {
23089
+ origin2 = [snap(box[0]), snap(box[1])];
23090
+ bodyCode = outlineCode(b.sub, origin2);
23091
+ found.push("outline");
23092
+ }
23093
+ const holes = b.holes.map((h) => ({ ...h, found: level > 0 ? h.found : void 0 }));
23094
+ const out = [];
23095
+ const rel = (p2) => sub(p2, origin2);
23096
+ let wrapBody = (s) => s;
23097
+ let loopRadius = 0;
23098
+ const rest = new Set(holes);
23099
+ if (level === 2 && !bodyF)
23100
+ for (const h of holes) {
23101
+ const c = h.found?.circle;
23102
+ if (!c || c.r * 2 > 15) continue;
23103
+ const pts = resample(b.outline.poly, true, 0.25);
23104
+ const R = Math.min(...pts.map((p2) => dist(p2, c.c)));
23105
+ const wall = R - c.r;
23106
+ if (wall < 0.5) continue;
23107
+ const arc = pts.filter((p2) => Math.abs(dist(p2, c.c) - R) <= tol).length * 0.25;
23108
+ if (arc < R * Math.PI * 0.8) continue;
23109
+ const args = [vec(rel(c.c))];
23110
+ if (snap(c.r * 2) !== 4) args.push(`d = ${num2(c.r * 2)}`);
23111
+ if (snap(wall) !== 3) args.push(`wall = ${num2(wall)}`);
23112
+ wrapBody = (s) => `hanging_loop(${args.join(", ")}) ${s}`;
23113
+ loopRadius = R;
23114
+ libraries2.add("hanging");
23115
+ found.push("hanging loop");
23116
+ rest.delete(h);
23117
+ break;
23118
+ }
23119
+ if (level === 2) {
23120
+ const [x0, y0, x1, y1] = box;
23121
+ const cx = (x0 + x1) / 2, w = x1 - x0, h = y1 - y0;
23122
+ const high = (p2) => p2[1] >= y0 + h * 0.66;
23123
+ const same2 = (r) => [...rest].filter(
23124
+ (o) => o.found?.circle && snap(o.found.circle.r) === snap(r.found.circle.r)
23125
+ ).length;
23126
+ const round3 = [...rest].filter(
23127
+ (r) => r.found?.circle && r.found.circle.r * 2 >= 1.5 && r.found.circle.r * 2 <= 15 && high(r.found.circle.c) && same2(r) <= 2
23128
+ );
23129
+ let hung = false;
23130
+ for (const a of round3) {
23131
+ const ca = a.found.circle;
23132
+ if (Math.abs(ca.c[0] - cx) > Math.max(0.5, w * 0.02)) continue;
23133
+ const d2 = ca.r * 2;
23134
+ out.push(`hanging_hole(${vec(rel(ca.c))}${snap(d2) !== 5 ? `, d = ${num2(d2)}` : ""})`);
23135
+ rest.delete(a);
23136
+ hung = true;
23137
+ break;
23138
+ }
23139
+ if (!hung)
23140
+ for (const a of round3)
23141
+ for (const c of round3) {
23142
+ if (hung || a === c) continue;
23143
+ const [p2, q] = [a.found.circle, c.found.circle];
23144
+ if (Math.abs(p2.r - q.r) > tol || Math.abs(p2.c[1] - q.c[1]) > tol || p2.c[0] >= q.c[0])
23145
+ continue;
23146
+ const mid = [(p2.c[0] + q.c[0]) / 2, p2.c[1]];
23147
+ if (Math.abs(mid[0] - cx) > Math.max(1, w * 0.02)) continue;
23148
+ const d2 = p2.r * 2;
23149
+ out.push(
23150
+ `hanging_hole(${vec(rel(mid))}${snap(d2) !== 5 ? `, d = ${num2(d2)}` : ""}, spacing = ${num2(q.c[0] - p2.c[0])})`
23151
+ );
23152
+ rest.delete(a);
23153
+ rest.delete(c);
23154
+ hung = true;
23155
+ }
23156
+ if (hung) {
23157
+ libraries2.add("hanging");
23158
+ found.push("hanger hole");
23159
+ }
23160
+ const keys = [...rest].filter(
23161
+ (r) => r.found?.kind === "keyhole" && r.found.library && Math.abs(r.found.angle) < 0.01
23162
+ );
23163
+ for (const a of keys)
23164
+ for (const c of keys) {
23165
+ if (!rest.has(a) || !rest.has(c) || a === c) continue;
23166
+ const [p2, q] = [a.found, c.found];
23167
+ if (p2.body !== q.body || Math.abs(p2.at[1] - q.at[1]) > tol || p2.at[0] >= q.at[0]) continue;
23168
+ const args = [num2(q.at[0] - p2.at[0])];
23169
+ const mid = rel([(p2.at[0] + q.at[0]) / 2, p2.at[1]]);
23170
+ const extra = p2.body.slice("keyhole(".length, -1);
23171
+ args.push(snap(mid[0]) || snap(mid[1]) ? `at = ${vec(mid)}` : "");
23172
+ if (extra) args.push(extra);
23173
+ out.push(`keyholes(${args.filter(Boolean).join(", ")})`);
23174
+ rest.delete(a);
23175
+ rest.delete(c);
23176
+ libraries2.add("hanging");
23177
+ found.push("keyhole", "keyhole");
23178
+ }
23179
+ if (thickness !== void 0) {
23180
+ const rects = [...rest].filter(
23181
+ (r) => r.found?.kind === "rect" && snap(r.found.rect.r) === 0
23182
+ );
23183
+ for (const row of rows(rects, tol)) {
23184
+ const { items: items2, dir, spacing, along, across } = row;
23185
+ const n2 = items2.length;
23186
+ const t = thickness;
23187
+ const c = across - t;
23188
+ const start = sub(items2[0].found.center, [dir[0] * spacing / 2, dir[1] * spacing / 2]);
23189
+ const deg = Math.atan2(dir[1], dir[0]) * 180 / Math.PI;
23190
+ const L = n2 * spacing;
23191
+ if (Math.abs(c) <= tol && Math.abs(along - spacing / 2) <= tol && n2 >= 2) {
23192
+ const fn = 2 * n2 - 1;
23193
+ const len = fn * along;
23194
+ const def2 = Math.max(3 * t, 6);
23195
+ const fingerCount2 = (l, f) => {
23196
+ let k = Math.round(l / f);
23197
+ if (k % 2 === 0) k += l / f > k ? 1 : -1;
23198
+ return Math.max(3, k);
23199
+ };
23200
+ if (fingerCount2(len, def2) !== fn && fingerCount2(len, along) !== fn) continue;
23201
+ const s0 = sub(items2[0].found.center, [dir[0] * along / 2, dir[1] * along / 2]);
23202
+ const finger = fingerCount2(len, def2) === fn ? "" : `, finger = ${num2(along)}`;
23203
+ out.push(place(rel(s0), deg, `finger_holes(${num2(len)}${finger})`));
23204
+ found.push("finger joint slot row");
23205
+ } else if (c >= -tol && c <= 1) {
23206
+ const args = [num2(L)];
23207
+ if (n2 !== Math.max(1, Math.round(L / 50))) args.push(`count = ${n2}`);
23208
+ const width = along - c;
23209
+ if (Math.abs(width - L / (2 * n2)) > tol) args.push(`width = ${num2(width)}`);
23210
+ if (Math.abs(c - 0.1) > 1e-3) args.push(`clearance = ${num2(c)}`);
23211
+ out.push(place(rel(start), deg, `slots(${args.join(", ")})`));
23212
+ libraries2.add("tabs");
23213
+ found.push("slot row");
23214
+ } else continue;
23215
+ for (const it of items2) rest.delete(it);
23216
+ }
23217
+ }
23218
+ }
23219
+ const recognised = [...rest].filter((r) => r.found);
23220
+ const raw2 = [...rest].filter((r) => !r.found);
23221
+ if (level === 2) {
23222
+ const groups = /* @__PURE__ */ new Map();
23223
+ for (const r of recognised) {
23224
+ const key = place([0, 0], r.found.angle, r.found.body);
23225
+ groups.set(key, [...groups.get(key) ?? [], r]);
23226
+ }
23227
+ for (const [shape, list2] of groups) {
23228
+ const pattern = grid(
23229
+ list2.map((r) => rel(r.found.at)),
23230
+ tol
23231
+ );
23232
+ if (pattern) {
23233
+ out.push(`${pattern} ${shape}`);
23234
+ for (const r of list2) {
23235
+ found.push(KIND[r.found.kind]);
23236
+ if (r.found.library) libraries2.add(r.found.library);
23237
+ }
23238
+ found.push("hole pattern");
23239
+ for (const r of list2) rest.delete(r);
23240
+ }
23241
+ }
23242
+ }
23243
+ for (const r of rest) {
23244
+ if (!r.found) continue;
23245
+ out.push(place(rel(r.found.at), r.found.angle, r.found.body));
23246
+ found.push(KIND[r.found.kind]);
23247
+ if (r.found.library) libraries2.add(r.found.library);
23248
+ }
23249
+ for (const r of raw2) {
23250
+ out.push(outlineCode(r.sub, origin2));
23251
+ found.push("outline");
23252
+ }
23253
+ const bodyStmt = wrapBody(bodyCode);
23254
+ const cut = out.length ? [`difference() {
23255
+ ${[bodyStmt, ...out].map(stmt).join("\n")}
23256
+ }`] : [stmt(bodyStmt)];
23257
+ const lines = b.lines.map((s) => stmt(outlineCode(s, origin2)));
23258
+ const thicknessHere = bf?.thickness ?? thickness;
23259
+ const check3 = [
23260
+ ...[...libraries2].map((l) => `use <kerf/${l}>`),
23261
+ `$thickness = ${thicknessHere ?? 3};`,
23262
+ `translate(${vec(origin2)}) {
23263
+ ${[...cut, ...lines].join("\n")}
23264
+ }`
23265
+ ].join("\n");
23266
+ const round = Math.max(
23267
+ 0,
23268
+ loopRadius,
23269
+ bodyF?.radius ?? 0,
23270
+ ...holes.map((h) => level > 0 ? h.found?.radius ?? 0 : 0)
23271
+ );
23272
+ return {
23273
+ origin: origin2,
23274
+ round,
23275
+ cut: [...cut, ...lines],
23276
+ check: check3,
23277
+ found,
23278
+ libraries: libraries2,
23279
+ thickness: bodyF?.thickness
23280
+ };
23281
+ }
23282
+ var KIND = {
23283
+ circle: "circle",
23284
+ ellipse: "ellipse",
23285
+ rect: "rectangle",
23286
+ polygon: "polygon",
23287
+ star: "star",
23288
+ tabs: "tabbed panel",
23289
+ fingers: "finger jointed panel",
23290
+ keyhole: "keyhole",
23291
+ outline: "outline"
23292
+ };
23293
+ function rows(holes, tol) {
23294
+ const out = [];
23295
+ const used = /* @__PURE__ */ new Set();
23296
+ const key = (h) => {
23297
+ const r = h.found.rect;
23298
+ return `${Math.round((h.found.angle % 180 + 180) % 180)}|${snap(r.w)}|${snap(r.h)}`;
23299
+ };
23300
+ const groups = /* @__PURE__ */ new Map();
23301
+ for (const h of holes) groups.set(key(h), [...groups.get(key(h)) ?? [], h]);
23302
+ for (const group of groups.values()) {
23303
+ if (group.length < 2) continue;
23304
+ const { w, h } = group[0].found.rect;
23305
+ const a = group[0].found.angle;
23306
+ for (const [deg, along, across] of [
23307
+ [a, w, h],
23308
+ [a + 90, h, w]
23309
+ ]) {
23310
+ const dir = rot([1, 0], deg);
23311
+ const normal2 = [-dir[1], dir[0]];
23312
+ const left = group.filter((g) => !used.has(g));
23313
+ const lines = /* @__PURE__ */ new Map();
23314
+ for (const g of left) {
23315
+ const c = g.found.center;
23316
+ const off = Math.round((c[0] * normal2[0] + c[1] * normal2[1]) / tol);
23317
+ const k = [...lines.keys()].find((x2) => Math.abs(x2 - off) <= 1) ?? off;
23318
+ lines.set(k, [...lines.get(k) ?? [], g]);
23319
+ }
23320
+ for (const line of lines.values()) {
23321
+ const pos = (g) => g.found.center[0] * dir[0] + g.found.center[1] * dir[1];
23322
+ line.sort((p2, q) => pos(p2) - pos(q));
23323
+ let i = 0;
23324
+ while (i < line.length - 1) {
23325
+ const step = pos(line[i + 1]) - pos(line[i]);
23326
+ let j = i + 1;
23327
+ while (j + 1 < line.length && Math.abs(pos(line[j + 1]) - pos(line[j]) - step) <= tol)
23328
+ j++;
23329
+ if (j > i && step > along) {
23330
+ const items2 = line.slice(i, j + 1);
23331
+ for (const it of items2) used.add(it);
23332
+ out.push({ items: items2, dir, spacing: step, along, across });
23333
+ }
23334
+ i = j;
23335
+ }
23336
+ }
23337
+ }
23338
+ }
23339
+ return out;
23340
+ }
23341
+ function grid(ps, tol) {
23342
+ if (ps.length < 3) return void 0;
23343
+ const series = (vals) => {
23344
+ const v = [];
23345
+ for (const x2 of [...vals].sort((a2, b2) => a2 - b2))
23346
+ if (!v.length || x2 - v[v.length - 1] > tol * 2) v.push(x2);
23347
+ if (v.length === 1) return void 0;
23348
+ const [a, s] = [snap(v[0]), snap((v[v.length - 1] - v[0]) / (v.length - 1))];
23349
+ const b = snap(a + s * (v.length - 1));
23350
+ if (s <= 0 || Math.floor((b - a) / s + 1e-9) + 1 !== v.length) return void 0;
23351
+ if (v.some((x2, i) => Math.abs(x2 - (a + i * s)) > tol)) return void 0;
23352
+ return `[${num2(a)}:${num2(s)}:${num2(b)}]`;
23353
+ };
23354
+ const xs = ps.map((p2) => p2[0]), ys = ps.map((p2) => p2[1]);
23355
+ const distinct = (vals) => new Set(vals.map((x2) => Math.round(x2 / (tol * 2)))).size;
23356
+ const nx = distinct(xs), ny = distinct(ys);
23357
+ if (ny === 1 || nx === 1) {
23358
+ const along = ny === 1 ? xs : ys;
23359
+ if (distinct(along) !== ps.length) return void 0;
23360
+ const r = series(along);
23361
+ if (!r) return void 0;
23362
+ return ny === 1 ? `for (x = ${r}) translate([x, ${num2(ys[0])}])` : `for (y = ${r}) translate([${num2(xs[0])}, y])`;
23363
+ }
23364
+ if (nx * ny !== ps.length) return void 0;
23365
+ const rx = series(xs), ry = series(ys);
23366
+ if (!rx || !ry) return void 0;
23367
+ return `for (x = ${rx}, y = ${ry}) translate([x, y])`;
23368
+ }
23369
+ function writeMarks(marks, lines, texts, origin2) {
23370
+ const out = [];
23371
+ for (const s of lines) out.push(stmt(outlineCode(s, origin2)));
23372
+ const byLayer = /* @__PURE__ */ new Map();
23373
+ const put = (layer, code2, note) => {
23374
+ const k = layer.name;
23375
+ const e = byLayer.get(k) ?? { layer, code: [] };
23376
+ e.code.push(stmt(code2) + (note ? ` // ${note}` : ""));
23377
+ byLayer.set(k, e);
23378
+ };
23379
+ for (const [item, subs] of marks) {
23380
+ const tol = DEFAULT_TOL;
23381
+ if (subs.length === 1 && subs[0].closed) {
23382
+ const o = outlineOf(flattenSub(subs[0]), subs[0]);
23383
+ const f = o.area > 1e-6 ? circleOf(o, tol) ?? rectOf(o, tol) ?? ellipseOf(o, tol) ?? regularOf(o, tol) : void 0;
23384
+ if (f) {
23385
+ put(item.layer, place(sub(f.at, origin2), f.angle, f.body));
23386
+ continue;
23387
+ }
23388
+ }
23389
+ if (item.layer.mode !== "fill" || subs.every((s) => !s.closed)) {
23390
+ for (const s of subs) put(item.layer, outlineCode(s, origin2));
23391
+ continue;
23392
+ }
23393
+ const d2 = pathData(subs, origin2);
23394
+ const polys = subs.filter((s) => s.closed).map((s) => flattenSub(s));
23395
+ const same2 = item.fillRule === "evenodd" || sameOutlines(union2(polys, "nonzero"), union2(polys, "evenodd"), 0.01);
23396
+ put(item.layer, `path("${d2}"${same2 ? "" : ', fill = "nonzero"'})`);
23397
+ }
23398
+ for (const t of texts) {
23399
+ const args = [JSON.stringify(t.text), `size = ${num2(t.size)}`];
23400
+ if (t.anchor !== "left") args.push(`halign = "${t.anchor}"`);
23401
+ put(
23402
+ t.layer,
23403
+ place(sub(t.at, origin2), t.angle, `text(${args.join(", ")})`),
23404
+ t.font ? `${t.font} in the drawing` : void 0
23405
+ );
23406
+ }
23407
+ for (const { layer, code: code2 } of byLayer.values()) {
23408
+ const tag = ["cut", "score", "engrave", "guide"].includes(layer.name) ? `${layer.name}()` : `layer("${layer.name}", mode = "${layer.mode}", color = "${layer.color}")`;
23409
+ out.push(
23410
+ code2.length === 1 && !code2[0].includes("//") ? `${tag} ${code2[0]}` : `${tag} {
23411
+ ${code2.join("\n")}
23412
+ }`
23413
+ );
23414
+ }
23415
+ return out;
23416
+ }
23417
+ function verify(w, b, tol) {
23418
+ let shape;
23419
+ try {
23420
+ const ev = new Evaluator({ maxSteps: 2e6 });
23421
+ shape = ev.run(parse(w.check).program).shape;
23422
+ } catch {
23423
+ return false;
23424
+ }
23425
+ const cut = shape.layers.get("cut");
23426
+ if (!cut) return false;
23427
+ const want = difference2(
23428
+ [b.outline.poly],
23429
+ b.holes.map((h) => h.outline.poly)
23430
+ );
23431
+ const got = union2(cut.regions);
23432
+ const t = tol + w.round * 16e-5;
23433
+ if (!sameOutlines(want, got, t)) return false;
23434
+ const lines = b.lines.map((s) => flattenSub(s));
23435
+ if (lines.length && !sameOutlines(lines, cut.lines, t, false)) return false;
23436
+ return true;
23437
+ }
23438
+
20942
23439
  // src/index.ts
20943
- var VERSION = "0.5.0";
23440
+ var VERSION = "0.6.0";
20944
23441
  var LANGUAGE_VERSION = "0.2";
20945
23442
 
20946
23443
  // fonts/AtkinsonHyperlegible-Regular.ttf
@@ -21108,8 +23605,8 @@ var Walker = class {
21108
23605
  for (let k = this.comments.length - 1; k >= 0; k--) {
21109
23606
  const c = this.comments[k];
21110
23607
  if (c.line > want) continue;
21111
- const last = c.line + (this.src.slice(c.start, c.end).match(/\n/g)?.length ?? 0);
21112
- if (!c.own || last !== want || /^\[[^\]]*\]$/.test(c.text)) break;
23608
+ const last2 = c.line + (this.src.slice(c.start, c.end).match(/\n/g)?.length ?? 0);
23609
+ if (!c.own || last2 !== want || /^\[[^\]]*\]$/.test(c.text)) break;
21113
23610
  out.unshift(c.block ? c.text.replace(/^[ \t]*\* ?/gm, "") : c.text);
21114
23611
  want = c.line - 1;
21115
23612
  }
@@ -21345,8 +23842,8 @@ function readable(source) {
21345
23842
  if (closed && (atEnd || e.line > lineCount(source))) {
21346
23843
  text3 = text3.slice(0, source.length);
21347
23844
  closed = false;
21348
- const last = text3.trimEnd().split("\n").length;
21349
- text3 = blank(text3, last);
23845
+ const last2 = text3.trimEnd().split("\n").length;
23846
+ text3 = blank(text3, last2);
21350
23847
  continue;
21351
23848
  }
21352
23849
  if (atEnd) {
@@ -21406,10 +23903,10 @@ function loader(resolve3, loading) {
21406
23903
  loader(resolve3, [...loading, path])
21407
23904
  );
21408
23905
  const top = w.run(read.body);
21409
- const last = (m) => [...m.values()].map((l) => l[l.length - 1]);
21410
- exports.mods = last(top.mods);
21411
- exports.fns = last(top.fns);
21412
- exports.vars = last(top.vars);
23906
+ const last2 = (m) => [...m.values()].map((l) => l[l.length - 1]);
23907
+ exports.mods = last2(top.mods);
23908
+ exports.fns = last2(top.fns);
23909
+ exports.vars = last2(top.vars);
21413
23910
  }
21414
23911
  if (std !== void 0) STDLIB_EXPORTS.set(path, exports);
21415
23912
  return exports;
@@ -21669,7 +24166,7 @@ function complete(a, offset2) {
21669
24166
  if (top?.params && argStart) return none;
21670
24167
  const items2 = [];
21671
24168
  const seen = /* @__PURE__ */ new Set();
21672
- const add3 = (c) => {
24169
+ const add4 = (c) => {
21673
24170
  if (seen.has(c.kind + " " + c.label)) return;
21674
24171
  seen.add(c.kind + " " + c.label);
21675
24172
  items2.push(c);
@@ -21678,7 +24175,7 @@ function complete(a, offset2) {
21678
24175
  const c = callee(a, top.callee);
21679
24176
  if (c?.def)
21680
24177
  for (const p2 of c.def.params)
21681
- add3({
24178
+ add4({
21682
24179
  label: p2.name,
21683
24180
  kind: "argument",
21684
24181
  insert: `${p2.name} = `,
@@ -21688,7 +24185,7 @@ function complete(a, offset2) {
21688
24185
  });
21689
24186
  if (c?.sig)
21690
24187
  for (const p2 of c.sig.params)
21691
- add3({
24188
+ add4({
21692
24189
  label: p2.name,
21693
24190
  kind: "argument",
21694
24191
  insert: `${p2.name} = `,
@@ -21698,8 +24195,8 @@ function complete(a, offset2) {
21698
24195
  });
21699
24196
  }
21700
24197
  const blockLevel = !top || top.token.value === "{";
21701
- const first = tokens[stmtStart];
21702
- const assigning = first?.type === "id" && tokens[stmtStart + 1]?.value === "=" && tokens.length > stmtStart + 1;
24198
+ const first2 = tokens[stmtStart];
24199
+ const assigning = first2?.type === "id" && tokens[stmtStart + 1]?.value === "=" && tokens.length > stmtStart + 1;
21703
24200
  const statement = blockLevel && !assigning && (!prev || prev.type === "punct" && [";", "{", "}", ")", "*", "#", "%", "!"].includes(prev.value) || prev.type === "id" && prev.value === "else");
21704
24201
  const scopes = scopesAt(a, from);
21705
24202
  const user = (ns) => {
@@ -21728,9 +24225,9 @@ function complete(a, offset2) {
21728
24225
  doc: s.doc,
21729
24226
  builtin: true
21730
24227
  });
21731
- for (const d2 of user("vars")) if (d2.name !== around.word || d2.start < from) add3(fromDef(d2));
24228
+ for (const d2 of user("vars")) if (d2.name !== around.word || d2.start < from) add4(fromDef(d2));
21732
24229
  for (const [name, s] of Object.entries(SPECIAL2))
21733
- add3({
24230
+ add4({
21734
24231
  label: name,
21735
24232
  kind: name === "PI" ? "constant" : "variable",
21736
24233
  detail: s.value !== void 0 ? `${name} = ${s.value}` : name,
@@ -21738,19 +24235,19 @@ function complete(a, offset2) {
21738
24235
  builtin: true
21739
24236
  });
21740
24237
  if (statement) {
21741
- for (const d2 of user("mods")) add3(fromDef(d2));
21742
- for (const s of SIGNATURES) if (s.kind !== "function") add3(fromSig(s));
24238
+ for (const d2 of user("mods")) add4(fromDef(d2));
24239
+ for (const s of SIGNATURES) if (s.kind !== "function") add4(fromSig(s));
21743
24240
  for (const k of ["module", "function", "for", "if", "let", "use", "include"])
21744
- add3({ label: k, kind: "keyword" });
21745
- if (prev?.type === "punct" && prev.value === "}") add3({ label: "else", kind: "keyword" });
24241
+ add4({ label: k, kind: "keyword" });
24242
+ if (prev?.type === "punct" && prev.value === "}") add4({ label: "else", kind: "keyword" });
21746
24243
  } else {
21747
- for (const d2 of user("fns")) add3(fromDef(d2));
21748
- for (const s of SIGNATURES) if (s.kind !== "module") add3(fromSig(s));
21749
- for (const c of CONSTANTS) add3({ label: c, kind: "constant", builtin: true });
21750
- add3({ label: "let", kind: "keyword" });
21751
- add3({ label: "function", kind: "keyword" });
24244
+ for (const d2 of user("fns")) add4(fromDef(d2));
24245
+ for (const s of SIGNATURES) if (s.kind !== "module") add4(fromSig(s));
24246
+ for (const c of CONSTANTS) add4({ label: c, kind: "constant", builtin: true });
24247
+ add4({ label: "let", kind: "keyword" });
24248
+ add4({ label: "function", kind: "keyword" });
21752
24249
  if (top?.token.value === "[")
21753
- for (const k of ["for", "if", "else", "each"]) add3({ label: k, kind: "keyword" });
24250
+ for (const k of ["for", "if", "else", "each"]) add4({ label: k, kind: "keyword" });
21754
24251
  }
21755
24252
  return result(items2);
21756
24253
  }
@@ -22004,9 +24501,9 @@ function libraryFile(base, path, exists = isFile) {
22004
24501
  const slash = path.indexOf("/");
22005
24502
  const root = slash > 0 ? findProject(base) : void 0;
22006
24503
  if (root) {
22007
- const first = path.slice(0, slash);
22008
- if (first === ownName(root)) return tries(root, path.slice(slash + 1));
22009
- if (isDir(join(root, FOLDER, first))) return tries(join(root, FOLDER), path);
24504
+ const first2 = path.slice(0, slash);
24505
+ if (first2 === ownName(root)) return tries(root, path.slice(slash + 1));
24506
+ if (isDir(join(root, FOLDER, first2))) return tries(join(root, FOLDER), path);
22010
24507
  }
22011
24508
  return tries(base, path);
22012
24509
  }
@@ -22265,8 +24762,8 @@ function writeLibrary(dir, files) {
22265
24762
  }
22266
24763
  }
22267
24764
  var lockText = (libraries2) => {
22268
- const sorted = [...libraries2].sort(([a], [b]) => a < b ? -1 : 1);
22269
- return JSON.stringify({ lockVersion: 1, libraries: Object.fromEntries(sorted) }, null, 2) + "\n";
24765
+ const sorted2 = [...libraries2].sort(([a], [b]) => a < b ? -1 : 1);
24766
+ return JSON.stringify({ lockVersion: 1, libraries: Object.fromEntries(sorted2) }, null, 2) + "\n";
22270
24767
  };
22271
24768
  async function install(root, options = {}) {
22272
24769
  const fetchFn = options.fetch ?? globalThis.fetch;
@@ -22416,7 +24913,7 @@ async function withManifest(root, edit, options) {
22416
24913
  throw e;
22417
24914
  }
22418
24915
  }
22419
- async function add2(root, source, options = {}) {
24916
+ async function add3(root, source, options = {}) {
22420
24917
  const cache = /* @__PURE__ */ new Map();
22421
24918
  const got = await fetchLibrary(
22422
24919
  source,
@@ -22507,8 +25004,8 @@ function pack(root, out) {
22507
25004
  continue;
22508
25005
  }
22509
25006
  for (const u of usePaths(program)) {
22510
- const first = u.path.split("/")[0];
22511
- const ok = Object.prototype.hasOwnProperty.call(LIBRARIES, u.path) || first === name && has(u.path.slice(name.length + 1)) || u.path.includes("/") && own3(manifest.libraries, first) !== void 0;
25007
+ const first2 = u.path.split("/")[0];
25008
+ const ok = Object.prototype.hasOwnProperty.call(LIBRARIES, u.path) || first2 === name && has(u.path.slice(name.length + 1)) || u.path.includes("/") && own3(manifest.libraries, first2) !== void 0;
22512
25009
  if (!ok)
22513
25010
  problems2.push(
22514
25011
  `${p2}, line ${u.line}: <${u.path}> will not be found once the library is installed` + (has(u.path) ? `. Write <${name}/${u.path}> for the library's own file.` : ".")
@@ -23047,12 +25544,12 @@ ${body}`);
23047
25544
  for (; ; ) {
23048
25545
  const headerEnd = buffer.indexOf("\r\n\r\n");
23049
25546
  if (headerEnd < 0) return;
23050
- const length = /Content-Length:\s*(\d+)/i.exec(buffer.subarray(0, headerEnd).toString());
23051
- if (!length) {
25547
+ const length2 = /Content-Length:\s*(\d+)/i.exec(buffer.subarray(0, headerEnd).toString());
25548
+ if (!length2) {
23052
25549
  buffer = buffer.subarray(headerEnd + 4);
23053
25550
  continue;
23054
25551
  }
23055
- const end = headerEnd + 4 + Number(length[1]);
25552
+ const end = headerEnd + 4 + Number(length2[1]);
23056
25553
  if (buffer.length < end) return;
23057
25554
  const body = buffer.subarray(headerEnd + 4, end).toString("utf8");
23058
25555
  buffer = buffer.subarray(end);
@@ -23079,6 +25576,16 @@ Usage:
23079
25576
  kerf fmt <files or folders> format .kerf files in place
23080
25577
  kerf fmt --check <files> list files that are not formatted; exit 1 if any
23081
25578
  kerf fmt - format standard input to standard output
25579
+ kerf import <file.svg> [-o out.kerf] turn an SVG drawing into a .kerf program,
25580
+ finding circles, tabs, finger joints, slots,
25581
+ hanger holes and keyholes; -o - prints it
25582
+ --dpi <n> px per inch for drawings measured in px
25583
+ (96; 72 for Adobe Illustrator files)
25584
+ --tolerance <mm> how close a found shape must be (0.05)
25585
+ --pack merge identical parts into a quantity and
25586
+ pack them, instead of keeping the layout
25587
+ --kerf <mm> the kerf the drawing's outlines were offset
25588
+ for; 0 takes them as drawn (found if left out)
23082
25589
  kerf lsp [--timeout <s>] run the language server for editors (stdio);
23083
25590
  stop checking a design after s seconds (10)
23084
25591
 
@@ -23131,6 +25638,7 @@ function main(argv) {
23131
25638
  }
23132
25639
  const cmd = argv[0];
23133
25640
  if (cmd === "fmt") return fmt2(argv.slice(1));
25641
+ if (cmd === "import") return importCommand(argv.slice(1));
23134
25642
  if (["install", "add", "remove", "pack"].includes(cmd)) return libraries(cmd, argv.slice(1));
23135
25643
  if (cmd === "lsp") {
23136
25644
  const i = argv.indexOf("--timeout");
@@ -23258,6 +25766,49 @@ function main(argv) {
23258
25766
  process.stderr.write(`Wrote ${target}
23259
25767
  `);
23260
25768
  }
25769
+ function importCommand(argv) {
25770
+ let file = "";
25771
+ let out = "";
25772
+ const opts = {};
25773
+ for (let i = 0; i < argv.length; i++) {
25774
+ const a = argv[i];
25775
+ const next = () => argv[++i] ?? fail2(`${a} needs a value`);
25776
+ const positive = (v) => {
25777
+ const n2 = Number(v);
25778
+ if (!(n2 > 0)) fail2(`${a} needs a number more than 0`);
25779
+ return n2;
25780
+ };
25781
+ if (a === "-o" || a === "--out") out = next();
25782
+ else if (a === "--dpi") opts.dpi = positive(next());
25783
+ else if (a === "--tolerance") opts.tolerance = positive(next());
25784
+ else if (a === "--pack") opts.pack = true;
25785
+ else if (a === "--kerf") {
25786
+ opts.kerf = Number(next());
25787
+ if (!(opts.kerf >= 0 && opts.kerf < 5))
25788
+ fail2("--kerf needs a width in mm, from 0 to less than 5");
25789
+ } else if (a.startsWith("-")) fail2(`Unknown option ${a} for kerf import`);
25790
+ else if (!file) file = a;
25791
+ else fail2(`Unexpected argument ${a}`);
25792
+ }
25793
+ if (!file) fail2("Give an .svg file to import.");
25794
+ if (!existsSync3(file)) fail2(`No such file: ${file}`);
25795
+ const target = out || file.replace(/\.svg$/i, "") + ".kerf";
25796
+ if (!out && existsSync3(target))
25797
+ fail2(`${target} already exists. Give -o ${target} to replace it.`);
25798
+ let result;
25799
+ try {
25800
+ result = importSvg(readFileSync3(file), { ...opts, name: basename(file) });
25801
+ } catch (e) {
25802
+ fail2(`error: ${file}: ${e.message}`);
25803
+ }
25804
+ if (out === "-") {
25805
+ process.stdout.write(result.source);
25806
+ return;
25807
+ }
25808
+ writeFileSync2(target, result.source);
25809
+ process.stderr.write(`Wrote ${target}: ${result.summary}
25810
+ `);
25811
+ }
23261
25812
  function kerfFiles(paths) {
23262
25813
  const out = [];
23263
25814
  const walk2 = (p2) => {
@@ -23332,7 +25883,7 @@ async function libraries(cmd, argv) {
23332
25883
  } else if (cmd === "add") {
23333
25884
  if (args.length !== 1)
23334
25885
  fail2("Give one library source, like kerf add github:owner/repo@v1.0.0");
23335
- const { name, lock } = await add2(findProject(process.cwd()) ?? process.cwd(), args[0], {
25886
+ const { name, lock } = await add3(findProject(process.cwd()) ?? process.cwd(), args[0], {
23336
25887
  log
23337
25888
  });
23338
25889
  const v = lock.libraries[name].version;