any2orca 0.7.0 → 0.7.2

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/CHANGELOG.md CHANGED
@@ -1,5 +1,37 @@
1
1
  # any2orca
2
2
 
3
+ ## 0.7.2
4
+
5
+ ### Other
6
+
7
+ - **The command line's help, the package description and the API reference name PrusaSlicer.** `any2orca --help` and the npm page listed five source slicers and left PrusaSlicer out, though PrusaSlicer projects have converted since 0.5.0. Converted files are unchanged.
8
+ - **The web app names PrusaSlicer everywhere it lists the supported slicers.** The FAQ answer about which files you can drop, the filament names setting and the example preset names now include Prusa, and a PrusaSlicer project is tested end to end in the page, including batch mode and the What changed panel. The README has a Supported slicers table.
9
+
10
+ ## 0.7.1
11
+
12
+ ### Output-affecting
13
+
14
+ - **A PrusaSlicer project with its Brim box unchecked converts with no brim.** PrusaSlicer's Brim checkbox is the brim width: unchecked is a width of 0, with the brim type left as it was ("outer only", say), and PrusaSlicer prints no brim. Snapmaker Orca draws a brim by its type alone, so the converted file had one: "outer only" with the U1's stock 5 mm width, or the stock automatic brim for a project from a PrusaSlicer old enough to have no brim type. A width of 0 now becomes Snapmaker Orca's "no brim". An object with its own brim width keeps its own brim, on or off. Converted PrusaSlicer files change where the box was unchecked; Bambu Studio family files don't.
15
+ - **A PrusaSlicer project's supports convert as PrusaSlicer shows them.** The Supports menu on PrusaSlicer's sidebar (none, everywhere, build plate only, or for support enforcers only) and the filaments supports print from are now carried as the project has them, even when they're the preset's own values. Before, only what differed from the preset came through, so a project that turned supports on got Snapmaker's stock tree supports instead of the snug or grid supports PrusaSlicer showed; an XL or MK4 Input Shaper preset's default, "for support enforcers only", became Snapmaker's stock "off", leaving painted enforcers unused; and a soluble-support preset's support filament and zero contact distance became any filament with a gap. When supports are on, the kind of support (tree for organic, normal for snug and grid) comes with them, for the project and for an object that turns supports on itself. A support or wipe tower filament number the project doesn't have is left to the stock value. Converted PrusaSlicer files with supports on, or on an enforcers-only preset, change; Bambu Studio family files don't.
16
+ - **An object placement that isn't a number is left as written.** A source project whose item transform has the right number of values but one that isn't a number (or is beyond what a number can hold) had that value written into the converted file as `NaN` or `Infinity`, with no warning. The placement is now left exactly as the source had it, and the conversion says so. Projects whose transforms are numbers, which is every project a slicer saves, convert byte for byte as before.
17
+
18
+ ### Features
19
+
20
+ - **The inspection says where a PrusaSlicer project's beds sit.** `inspect()` gains an optional `sourcePlateOrigins`, each plate's offset from the first in the source project, keyed by plate number. PrusaSlicer 2.9 lays its beds out in rings with a gap of at most 100 mm and later rows above the first, not on Bambu Studio's grid, so a plate view that assumed that grid drew the objects of a PrusaSlicer project's third and fourth beds off the bed. Absent for the Bambu Studio family. The web app's plate view uses it, so each bed of such a project is drawn on its own plate. Converted files are unchanged.
21
+
22
+ ### Fixes
23
+
24
+ - **A crafted project can't stall the converter.** Four more parsers scanned the rest of a file again for every tag that never ended: the lookup of an object's mesh block and of its placement (every source), the object names and plate entries (every source), the step that writes the recentered placements into the converted file (every source), and the PrusaSlicer print-preset lookup, which rescanned a long preset name for every "(" in it. A file built to have tens of thousands of such tags took minutes to hours; each reads the text in one pass now, and a regression test holds the time. Converted files are unchanged.
25
+ - **Projects with many filaments or many PrusaSlicer parts open and convert faster.** Four steps did work that grew with the square of the project's size: writing one filament preset per filament name, looking up each filament's color name, reading the parts of a PrusaSlicer object, and splitting PrusaSlicer's multi-part objects. Each now takes one pass. A 38 MB PrusaSlicer model with 200 multi-part objects splits in 27 ms instead of 3.5 seconds, with a third of the memory, and a project with thousands of filament slots opens without a pause. The split also reads a crafted mesh with tags that never end in one pass, where it took seconds. Every filament is still kept, in the file's order, and converted files are unchanged.
26
+ - **A damaged config or state file no longer stops the command line.** A `config.json` in the CLI's config folder whose update-check entry had the wrong shape stopped `convert`, `diff`, `presets` and `profiles` with a type error before any work was done; a `.any2orca-state.json` in an output folder holding something other than records did the same to a batch or watch run. Both files are now checked when read, and an entry of the wrong shape is ignored, as a missing one is.
27
+ - **PrusaSlicer 2.9.7 projects convert without an unknown-setting note, and a crafted bed number is skipped.** PrusaSlicer 2.9.7 adds one printer setting, used filament compensation (it scales the filament statistics, never the extrusion); it's now known, and like every printer setting the U1 keeps its own. A color-change block whose bed number isn't one of PrusaSlicer's beds (a negative one, in a crafted file) is skipped, as PrusaSlicer 2.9.7 now does, instead of being put on plate 1 or on a plate that doesn't exist.
28
+ - **The worker client settles every call, and a bundle can be handed over without a copy.** A reply from the worker that said a call failed but carried no readable error left that call waiting forever (a page showed "Converting..." for good); such a reply now rejects the call with `invalid_file`. `unwrapBundle` takes the same `transfer` option as `open`, so a caller can move a large bundle into the worker instead of copying it, and the worker no longer copies each entry a second time before handing it back.
29
+
30
+ ### Other
31
+
32
+ - Pins any2orca-profiles 0.3.1, which holds the corrected NOTICE for the PrusaSlicer presets.
33
+ - The web app loads its Advanced tools when they're opened instead of with the first screen, so the first load is smaller.
34
+
3
35
  ## 0.7.0
4
36
 
5
37
  ### Output-affecting
@@ -1,6 +1,19 @@
1
1
  // SPDX-License-Identifier: MIT
2
2
  import { FILAMENT_COLOR_ROWS } from "./filamentColorNames.js";
3
- const ENTRIES = FILAMENT_COLOR_ROWS.map(([vendor, type, hex, name]) => ({ vendor, type, hex, name }));
3
+ /**
4
+ * Every entry by its normalized product line, then its hex, built once when
5
+ * the module loads, so looking up a slot reads two maps instead of
6
+ * normalizing every row's product line again. When two rows share a line and
7
+ * a hex, the first one counts, as a scan in row order found it.
8
+ */
9
+ const BY_TYPE_AND_HEX = new Map();
10
+ for (const [vendor, type, hex, name] of FILAMENT_COLOR_ROWS) {
11
+ const key = normalizeType(type);
12
+ const byHex = BY_TYPE_AND_HEX.get(key) ?? new Map();
13
+ if (!byHex.has(hex))
14
+ byHex.set(hex, { vendor, name });
15
+ BY_TYPE_AND_HEX.set(key, byHex);
16
+ }
4
17
  /**
5
18
  * Extracts the product-line string from a Bambu-style `filament_settings_id`
6
19
  * (e.g. `"Bambu PLA Matte @BBL P1S 0.4 nozzle"` -> `"PLA Matte"`), which is
@@ -50,8 +63,6 @@ export function lookupFilamentColorName(filamentSettingsId, hex) {
50
63
  const type = parseFilamentType(filamentSettingsId);
51
64
  if (!type)
52
65
  return null;
53
- const normalizedType = normalizeType(type);
54
- const normalizedHex = normalizeHex(hex);
55
- const match = ENTRIES.find((e) => normalizeType(e.type) === normalizedType && e.hex === normalizedHex);
66
+ const match = BY_TYPE_AND_HEX.get(normalizeType(type))?.get(normalizeHex(hex));
56
67
  return match ? { vendor: match.vendor, name: match.name } : null;
57
68
  }
@@ -1,6 +1,7 @@
1
1
  // SPDX-License-Identifier: MIT
2
2
  import { escapeRegExp } from "./internal/escapeRegExp.js";
3
3
  import { parseVertices } from "./parseVertices.js";
4
+ import { isSelfClosingTag, xmlBlockStartingWith, xmlTags } from "./xmlBlocks.js";
4
5
  import { forEachObjectVertex, LARGE_PART_BYTES } from "./streamObjectVertices.js";
5
6
  import { applyTransform, compose, parseMatrix } from "./transform.js";
6
7
  const utf8Decoder = new TextDecoder("utf-8");
@@ -21,22 +22,42 @@ const utf8Decoder = new TextDecoder("utf-8");
21
22
  * memoization cache, not incidental state).
22
23
  * @returns `[minX, maxX, minY, maxY]`, or `null` if nothing could be found.
23
24
  */
24
- /** Finds the `<object id="...">...</object>` block for `objectId` in `text`, or null. */
25
+ /**
26
+ * Finds the `<object id="...">...</object>` block for `objectId` in `text`, or null.
27
+ * Scanned in one pass: the lazy block pattern this replaces rescanned the rest of the
28
+ * file for every opener that never closed, which a crafted file turned into minutes
29
+ * (40,000 openers in 1 MB took 3.5 s, and the reader calls this once per object).
30
+ */
25
31
  function findObjectBlock(objectId, text) {
26
- const match = new RegExp(`<object id="${escapeRegExp(objectId)}"[^>]*>[\\s\\S]*?</object>`).exec(text);
27
- return match ? match[0] : null;
32
+ return xmlBlockStartingWith(text, "object", `id="${objectId}"`);
33
+ }
34
+ /**
35
+ * The object's own `<item ...>` placement transform, or null: what
36
+ * `<item objectid="N"[^>]*transform="([^"]+)"` captured, which is the first such
37
+ * item that has a transform (and, being greedy, the last transform in that tag).
38
+ */
39
+ function itemTransform(objectId, topModelText) {
40
+ const prefix = ` objectid="${objectId}"`;
41
+ for (const { attrs } of xmlTags(topModelText, "item")) {
42
+ if (!attrs.startsWith(prefix))
43
+ continue;
44
+ const transforms = [...attrs.matchAll(/transform="([^"]+)"/g)];
45
+ if (transforms.length > 0)
46
+ return transforms[transforms.length - 1][1];
47
+ }
48
+ return null;
28
49
  }
29
- /** Order-independent single-attribute lookup within one `<component .../>` tag. */
30
- function componentAttr(tag, name) {
31
- const match = new RegExp(`${escapeRegExp(name)}="([^"]*)"`).exec(tag);
50
+ /** Order-independent single-attribute lookup within one tag's attributes. */
51
+ function componentAttr(attrs, name) {
52
+ const match = new RegExp(`${escapeRegExp(name)}="([^"]*)"`).exec(attrs);
32
53
  return match ? match[1] : null;
33
54
  }
34
55
  export function objectWorldBboxXY(objectId, topModelText, partFileCache, zipEntries) {
35
56
  const objBlock = findObjectBlock(objectId, topModelText);
36
- const itemMatch = new RegExp(`<item objectid="${escapeRegExp(objectId)}"[^>]*transform="([^"]+)"`).exec(topModelText);
57
+ const itemMatch = itemTransform(objectId, topModelText);
37
58
  if (!objBlock || !itemMatch)
38
59
  return null;
39
- const [itemR, itemT] = parseMatrix(itemMatch[1]);
60
+ const [itemR, itemT] = parseMatrix(itemMatch);
40
61
  let minX = Infinity;
41
62
  let maxX = -Infinity;
42
63
  let minY = Infinity;
@@ -48,7 +69,7 @@ export function objectWorldBboxXY(objectId, topModelText, partFileCache, zipEntr
48
69
  // model file (a legitimate "assembled from local sub-parts" case, not
49
70
  // just the "split across separate part files" one) -- when absent,
50
71
  // resolve objectid against topModelText itself instead of an external part.
51
- const componentTags = [...objBlock.matchAll(/<component\b[^>]*\/>/g)].map((m) => m[0]);
72
+ let anyComponent = false;
52
73
  const include = ([wx, wy]) => {
53
74
  if (wx < minX)
54
75
  minX = wx;
@@ -60,60 +81,61 @@ export function objectWorldBboxXY(objectId, topModelText, partFileCache, zipEntr
60
81
  maxY = wy;
61
82
  count++;
62
83
  };
63
- if (componentTags.length > 0) {
64
- for (const tag of componentTags) {
65
- const path = componentAttr(tag, "p:path");
66
- const subObjId = componentAttr(tag, "objectid");
67
- // The 3MF spec makes a component's transform optional (identity when absent); PrusaSlicer leaves it out.
68
- const transform = componentAttr(tag, "transform") ?? "1 0 0 0 1 0 0 0 1 0 0 0";
69
- if (!subObjId)
70
- continue;
71
- const [compR, compT] = parseMatrix(transform);
72
- const [R, T] = compose(itemR, itemT, compR, compT);
73
- let subBlock;
74
- if (path) {
75
- const key = path.replace(/^\/+/, "");
76
- const bytes = zipEntries[key];
77
- // A very large mesh is scanned from its bytes: decoding it whole can exceed the engine's longest string.
78
- if (bytes && bytes.length > LARGE_PART_BYTES) {
79
- // Kept aside until the block is known to close, as the whole-file path only uses a closed block.
80
- let [aMinX, aMaxX, aMinY, aMaxY, aCount] = [Infinity, -Infinity, Infinity, -Infinity, 0];
81
- const closed = forEachObjectVertex(bytes, subObjId, (v) => {
82
- const [wx, wy] = applyTransform(v, R, T);
83
- if (wx < aMinX)
84
- aMinX = wx;
85
- if (wx > aMaxX)
86
- aMaxX = wx;
87
- if (wy < aMinY)
88
- aMinY = wy;
89
- if (wy > aMaxY)
90
- aMaxY = wy;
91
- aCount++;
92
- });
93
- if (closed && aCount > 0) {
94
- minX = Math.min(minX, aMinX);
95
- maxX = Math.max(maxX, aMaxX);
96
- minY = Math.min(minY, aMinY);
97
- maxY = Math.max(maxY, aMaxY);
98
- count += aCount;
99
- }
100
- continue;
101
- }
102
- if (!partFileCache.has(key)) {
103
- partFileCache.set(key, bytes ? utf8Decoder.decode(bytes) : "");
84
+ for (const { attrs } of xmlTags(objBlock, "component")) {
85
+ if (!isSelfClosingTag(attrs))
86
+ continue;
87
+ anyComponent = true;
88
+ const path = componentAttr(attrs, "p:path");
89
+ const subObjId = componentAttr(attrs, "objectid");
90
+ // The 3MF spec makes a component's transform optional (identity when absent); PrusaSlicer leaves it out.
91
+ const transform = componentAttr(attrs, "transform") ?? "1 0 0 0 1 0 0 0 1 0 0 0";
92
+ if (!subObjId)
93
+ continue;
94
+ const [compR, compT] = parseMatrix(transform);
95
+ const [R, T] = compose(itemR, itemT, compR, compT);
96
+ let subBlock;
97
+ if (path) {
98
+ const key = path.replace(/^\/+/, "");
99
+ const bytes = zipEntries[key];
100
+ // A very large mesh is scanned from its bytes: decoding it whole can exceed the engine's longest string.
101
+ if (bytes && bytes.length > LARGE_PART_BYTES) {
102
+ // Kept aside until the block is known to close, as the whole-file path only uses a closed block.
103
+ let [aMinX, aMaxX, aMinY, aMaxY, aCount] = [Infinity, -Infinity, Infinity, -Infinity, 0];
104
+ const closed = forEachObjectVertex(bytes, subObjId, (v) => {
105
+ const [wx, wy] = applyTransform(v, R, T);
106
+ if (wx < aMinX)
107
+ aMinX = wx;
108
+ if (wx > aMaxX)
109
+ aMaxX = wx;
110
+ if (wy < aMinY)
111
+ aMinY = wy;
112
+ if (wy > aMaxY)
113
+ aMaxY = wy;
114
+ aCount++;
115
+ });
116
+ if (closed && aCount > 0) {
117
+ minX = Math.min(minX, aMinX);
118
+ maxX = Math.max(maxX, aMaxX);
119
+ minY = Math.min(minY, aMinY);
120
+ maxY = Math.max(maxY, aMaxY);
121
+ count += aCount;
104
122
  }
105
- subBlock = findObjectBlock(subObjId, partFileCache.get(key));
123
+ continue;
106
124
  }
107
- else {
108
- subBlock = findObjectBlock(subObjId, topModelText);
125
+ if (!partFileCache.has(key)) {
126
+ partFileCache.set(key, bytes ? utf8Decoder.decode(bytes) : "");
109
127
  }
110
- if (!subBlock)
111
- continue;
112
- for (const v of parseVertices(subBlock))
113
- include(applyTransform(v, R, T));
128
+ subBlock = findObjectBlock(subObjId, partFileCache.get(key));
129
+ }
130
+ else {
131
+ subBlock = findObjectBlock(subObjId, topModelText);
114
132
  }
133
+ if (!subBlock)
134
+ continue;
135
+ for (const v of parseVertices(subBlock))
136
+ include(applyTransform(v, R, T));
115
137
  }
116
- else {
138
+ if (!anyComponent) {
117
139
  // Direct mesh in the same object definition (no components at all).
118
140
  for (const v of parseVertices(objBlock))
119
141
  include(applyTransform(v, itemR, itemT));
@@ -1,5 +1,34 @@
1
1
  // SPDX-License-Identifier: MIT
2
- import { xmlBlocks } from "./xmlBlocks.js";
2
+ import { closingTagAt, xmlBlocks, xmlTags } from "./xmlBlocks.js";
3
+ /**
4
+ * The attributes of every `<metadata ...>` in `block`, a self-closing tag's `/` removed:
5
+ * what `/<metadata\s+([^>]*?)\/?>/g` captured (the leading whitespace kept, which the
6
+ * attribute lookups don't see), in one pass over the block. That
7
+ * pattern scans to the end of the block for every `<metadata` that has no `>`, which a
8
+ * crafted file turns into minutes (40,000 of them in 0.4 MB took eight seconds).
9
+ */
10
+ function* metadataAttrs(block) {
11
+ for (const { attrs } of xmlTags(block, "metadata")) {
12
+ if (!/^\s/.test(attrs))
13
+ continue;
14
+ yield attrs.endsWith("/") ? attrs.slice(0, -1) : attrs;
15
+ }
16
+ }
17
+ /**
18
+ * The text of an object's `<metadata ... name="name">text</metadata>` entry, or undefined:
19
+ * the same match as `/<metadata\s+[^>]*?name="name"[^>]*>([^<]+)<\/metadata>/i`, in one pass.
20
+ */
21
+ function metadataNameText(body) {
22
+ for (const { attrs, end } of xmlTags(body, "metadata", true)) {
23
+ if (!/^\s/.test(attrs) || !/name="name"/i.test(attrs))
24
+ continue;
25
+ const textEnd = body.indexOf("<", end);
26
+ if (textEnd === -1 || textEnd === end || !closingTagAt(body, textEnd, "metadata"))
27
+ continue;
28
+ return body.slice(end, textEnd).trim();
29
+ }
30
+ return undefined;
31
+ }
3
32
  export function parseObjectMetadata(topModelText, modelSettingsText) {
4
33
  const result = {};
5
34
  // Helper to extract an attribute value regardless of position or quote style
@@ -17,10 +46,7 @@ export function parseObjectMetadata(topModelText, modelSettingsText) {
17
46
  // Check name in attribute: name="..." or <metadata name="name">...</metadata>
18
47
  let name = getAttr(attrs, "name");
19
48
  if (!name) {
20
- const metaNameMatch = body.match(/<metadata\s+[^>]*?name="name"[^>]*>([^<]+)<\/metadata>/i);
21
- if (metaNameMatch) {
22
- name = metaNameMatch[1].trim();
23
- }
49
+ name = metadataNameText(body);
24
50
  }
25
51
  result[id] = {
26
52
  name,
@@ -36,8 +62,7 @@ export function parseObjectMetadata(topModelText, modelSettingsText) {
36
62
  continue;
37
63
  let name = getAttr(attrs, "name");
38
64
  if (!name) {
39
- for (const metaMatch of body.matchAll(/<metadata\s+([^>]*?)\/?>/g)) {
40
- const metaAttrs = metaMatch[1];
65
+ for (const metaAttrs of metadataAttrs(body)) {
41
66
  const key = getAttr(metaAttrs, "key") || getAttr(metaAttrs, "name");
42
67
  const val = getAttr(metaAttrs, "value");
43
68
  if (key === "name" || key === "object_name") {
@@ -61,8 +86,7 @@ export function parseObjectMetadata(topModelText, modelSettingsText) {
61
86
  for (const { body: block } of xmlBlocks(plateBlock, "model_instance")) {
62
87
  let objectId;
63
88
  let instName;
64
- for (const metaMatch of block.matchAll(/<metadata\s+([^>]*?)\/?>/g)) {
65
- const metaAttrs = metaMatch[1];
89
+ for (const metaAttrs of metadataAttrs(block)) {
66
90
  const key = getAttr(metaAttrs, "key") || getAttr(metaAttrs, "name");
67
91
  const val = getAttr(metaAttrs, "value");
68
92
  if (!key || !val)
@@ -1,5 +1,6 @@
1
1
  // SPDX-License-Identifier: MIT
2
2
  import { fmtNum } from "./fmtNum.js";
3
+ import { replaceXmlTags } from "./xmlBlocks.js";
3
4
  /**
4
5
  * Same idea as `recenterBuildItems`, but for `<assemble_item>` entries
5
6
  * inside `<assemble>` in `model_settings.config`. Only shifts items that
@@ -18,7 +19,9 @@ export function recenterAssembleItems(configXmlText, shifts, warnings) {
18
19
  const section = configXmlText.slice(start, end);
19
20
  let shifted = 0;
20
21
  let skippedRelative = 0;
21
- const newSection = section.replace(/<assemble_item\s+[^>]*>/g, (fullTag) => {
22
+ // One pass over the tags: `/<assemble_item\s+[^>]*>/g` scanned to the end of the section for every
23
+ // `<assemble_item` without a `>`, which a crafted file turned into minutes.
24
+ const newSection = replaceXmlTags(section, "assemble_item", (fullTag) => {
22
25
  if (!fullTag.includes("instance_id")) {
23
26
  skippedRelative++;
24
27
  return fullTag;
@@ -37,6 +40,11 @@ export function recenterAssembleItems(configXmlText, shifts, warnings) {
37
40
  }
38
41
  const tx = Number(tokens[9]);
39
42
  const ty = Number(tokens[10]);
43
+ // A token that isn't a number would be written back as "NaN"; the placement is left as it is instead.
44
+ if (!Number.isFinite(tx) || !Number.isFinite(ty)) {
45
+ warnings.push(` WARN: object ${oid}'s assemble transform holds a value that isn't a number, so its placement is left as it is.`);
46
+ return fullTag;
47
+ }
40
48
  tokens[9] = fmtNum(tx + dx);
41
49
  tokens[10] = fmtNum(ty + dy);
42
50
  shifted++;
@@ -1,5 +1,6 @@
1
1
  // SPDX-License-Identifier: MIT
2
2
  import { fmtNum } from "./fmtNum.js";
3
+ import { replaceXmlTags } from "./xmlBlocks.js";
3
4
  /**
4
5
  * Rewrite every `<item ...transform="...">` in the `<build>` section of
5
6
  * `3dmodel.model`, adding `(dx, dy)` from `shifts[objectid]` to the
@@ -23,7 +24,9 @@ export function recenterBuildItems(modelXmlText, shifts, warnings) {
23
24
  return modelXmlText;
24
25
  const buildSection = modelXmlText.slice(buildStart, buildEnd);
25
26
  let itemCount = 0;
26
- const newBuildSection = buildSection.replace(/<item\s+[^>]*>/g, (fullTag) => {
27
+ // One pass over the tags: `/<item\s+[^>]*>/g` scanned to the end of the section for every
28
+ // `<item` without a `>`, which a crafted file turned into minutes.
29
+ const newBuildSection = replaceXmlTags(buildSection, "item", (fullTag) => {
27
30
  const oidMatch = fullTag.match(/objectid="(\d+)"/);
28
31
  const transMatch = fullTag.match(/transform="([^"]+)"/);
29
32
  if (!oidMatch || !transMatch)
@@ -38,6 +41,11 @@ export function recenterBuildItems(modelXmlText, shifts, warnings) {
38
41
  }
39
42
  const tx = Number(tokens[9]);
40
43
  const ty = Number(tokens[10]);
44
+ // A token that isn't a number would be written back as "NaN"; the placement is left as it is instead.
45
+ if (!Number.isFinite(tx) || !Number.isFinite(ty)) {
46
+ warnings.push(` WARN: object ${oid}'s transform holds a value that isn't a number, so its placement is left as it is.`);
47
+ return fullTag;
48
+ }
41
49
  tokens[9] = fmtNum(tx + dx);
42
50
  tokens[10] = fmtNum(ty + dy);
43
51
  itemCount++;
@@ -1,10 +1,59 @@
1
+ /**
2
+ * Single-pass scanners for the shapes the readers and the writer look for in a
3
+ * 3MF's XML. A pattern whose character class can run to the end of the text,
4
+ * tried again at every tag that never ends, costs the square of the text's
5
+ * size: 40,000 unterminated tags in 0.2 MB took ten seconds, so a file of the
6
+ * size these paths accept took minutes. Every scanner here is linear, and
7
+ * matches what the pattern in its own doc comment matched.
8
+ */
9
+ /** Whether `text` holds `</tag>` at `at`, the tag name without case. */
10
+ export declare function closingTagAt(text: string, at: number, tag: string): boolean;
11
+ /**
12
+ * Every `<tag ...>` and `<tag .../>` in `text`, in order: the attributes as
13
+ * written (everything between `<tag` and the first `>`, a self-closing tag's
14
+ * `/` included) and where the tag starts and ends.
15
+ *
16
+ * The same tags as `/<tag[^>]*>/g`, found in linear time. Each caller applies
17
+ * its own rule for what may follow the tag name by looking at `attrs`: a
18
+ * pattern written `<tag\s` wants `attrs` to start with whitespace, and one
19
+ * written `<tag\b` wants its first character to be something other than a
20
+ * letter, digit or underscore.
21
+ *
22
+ * @param ignoreCase match the tag name without case, as a pattern with the `i` flag does.
23
+ */
24
+ export declare function xmlTags(text: string, tag: string, ignoreCase?: boolean): Generator<{
25
+ attrs: string;
26
+ start: number;
27
+ end: number;
28
+ }>;
29
+ /**
30
+ * Whether a tag from {@link xmlTags} is one `/<tag\b[^>]*\/>/` matched:
31
+ * self-closing, and not a longer tag name that starts the same way
32
+ * (`<vertices>` when looking for `<vertex`).
33
+ */
34
+ export declare function isSelfClosingTag(attrs: string): boolean;
35
+ /**
36
+ * `text` with every `<tag ...>` replaced by what `replace` returns for it: the
37
+ * same replacements as `text.replace(/<tag\s+[^>]*>/g, replace)`, in one pass.
38
+ */
39
+ export declare function replaceXmlTags(text: string, tag: string, replace: (tag: string) => string): string;
40
+ /**
41
+ * The first `<tag prefix...>...</tag>` block in `text`, as written (both tags
42
+ * included), or null: the same match as
43
+ * ``new RegExp(`<tag ${prefix}[^>]*>[\\s\\S]*?</tag>`)``, found in linear time.
44
+ *
45
+ * `prefix` is the attribute text the opening tag must begin with, as written
46
+ * in the file, e.g. `id="7"`.
47
+ */
48
+ export declare function xmlBlockStartingWith(text: string, tag: string, prefix: string): string | null;
1
49
  /**
2
50
  * Every `<tag ...>body</tag>` block in `text`, in order, with the same
3
- * matches as `/<tag(\s[^>]*?)?>([\s\S]*?)<\/tag>/g`, found in linear time.
4
- * A lazy pattern like that one rescans the rest of the text for each opener
5
- * that has no closing tag, which a crafted file can turn into minutes.
51
+ * matches as `/<tag(\s[^>]*?)?>([\s\S]*?)<\/tag>/g`, found in linear time,
52
+ * and where each body starts and ends in `text`.
6
53
  */
7
54
  export declare function xmlBlocks(text: string, tag: string): Generator<{
8
55
  attrs: string;
9
56
  body: string;
57
+ bodyStart: number;
58
+ bodyEnd: number;
10
59
  }>;
@@ -1,9 +1,111 @@
1
1
  // SPDX-License-Identifier: MIT
2
+ /**
3
+ * Single-pass scanners for the shapes the readers and the writer look for in a
4
+ * 3MF's XML. A pattern whose character class can run to the end of the text,
5
+ * tried again at every tag that never ends, costs the square of the text's
6
+ * size: 40,000 unterminated tags in 0.2 MB took ten seconds, so a file of the
7
+ * size these paths accept took minutes. Every scanner here is linear, and
8
+ * matches what the pattern in its own doc comment matched.
9
+ */
10
+ /** Whether `text` has `tag` at `at`, comparing ASCII letters without case. */
11
+ function tagAt(text, at, tag) {
12
+ if (at + tag.length > text.length)
13
+ return false;
14
+ for (let i = 0; i < tag.length; i++) {
15
+ // Folds an ASCII letter's case without building a string per tag: one big mesh has millions of tags.
16
+ if ((text.charCodeAt(at + i) | 32) !== (tag.charCodeAt(i) | 32))
17
+ return false;
18
+ }
19
+ return true;
20
+ }
21
+ /** Whether `text` holds `</tag>` at `at`, the tag name without case. */
22
+ export function closingTagAt(text, at, tag) {
23
+ return text.charCodeAt(at) === 0x3c && text.charCodeAt(at + 1) === 0x2f && tagAt(text, at + 2, tag) && text.charCodeAt(at + 2 + tag.length) === 0x3e;
24
+ }
25
+ /**
26
+ * Every `<tag ...>` and `<tag .../>` in `text`, in order: the attributes as
27
+ * written (everything between `<tag` and the first `>`, a self-closing tag's
28
+ * `/` included) and where the tag starts and ends.
29
+ *
30
+ * The same tags as `/<tag[^>]*>/g`, found in linear time. Each caller applies
31
+ * its own rule for what may follow the tag name by looking at `attrs`: a
32
+ * pattern written `<tag\s` wants `attrs` to start with whitespace, and one
33
+ * written `<tag\b` wants its first character to be something other than a
34
+ * letter, digit or underscore.
35
+ *
36
+ * @param ignoreCase match the tag name without case, as a pattern with the `i` flag does.
37
+ */
38
+ export function* xmlTags(text, tag, ignoreCase = false) {
39
+ const open = `<${tag}`;
40
+ let from = 0;
41
+ for (;;) {
42
+ let start = ignoreCase ? text.indexOf("<", from) : text.indexOf(open, from);
43
+ if (ignoreCase) {
44
+ while (start !== -1 && !tagAt(text, start + 1, tag))
45
+ start = text.indexOf("<", start + 1);
46
+ }
47
+ if (start === -1)
48
+ return;
49
+ const openerEnd = text.indexOf(">", start + open.length);
50
+ // No `>` after this tag means none after any later one either.
51
+ if (openerEnd === -1)
52
+ return;
53
+ yield { attrs: text.slice(start + open.length, openerEnd), start, end: openerEnd + 1 };
54
+ from = openerEnd + 1;
55
+ }
56
+ }
57
+ /**
58
+ * Whether a tag from {@link xmlTags} is one `/<tag\b[^>]*\/>/` matched:
59
+ * self-closing, and not a longer tag name that starts the same way
60
+ * (`<vertices>` when looking for `<vertex`).
61
+ */
62
+ export function isSelfClosingTag(attrs) {
63
+ return attrs.endsWith("/") && !/[A-Za-z0-9_]/.test(attrs[0] ?? "");
64
+ }
65
+ /**
66
+ * `text` with every `<tag ...>` replaced by what `replace` returns for it: the
67
+ * same replacements as `text.replace(/<tag\s+[^>]*>/g, replace)`, in one pass.
68
+ */
69
+ export function replaceXmlTags(text, tag, replace) {
70
+ const pieces = [];
71
+ let copiedTo = 0;
72
+ for (const { attrs, start, end } of xmlTags(text, tag)) {
73
+ // `<tag\s+` : a tag name the text only begins with isn't this tag.
74
+ if (!/^\s/.test(attrs))
75
+ continue;
76
+ pieces.push(text.slice(copiedTo, start), replace(text.slice(start, end)));
77
+ copiedTo = end;
78
+ }
79
+ if (pieces.length === 0)
80
+ return text;
81
+ pieces.push(text.slice(copiedTo));
82
+ return pieces.join("");
83
+ }
84
+ /**
85
+ * The first `<tag prefix...>...</tag>` block in `text`, as written (both tags
86
+ * included), or null: the same match as
87
+ * ``new RegExp(`<tag ${prefix}[^>]*>[\\s\\S]*?</tag>`)``, found in linear time.
88
+ *
89
+ * `prefix` is the attribute text the opening tag must begin with, as written
90
+ * in the file, e.g. `id="7"`.
91
+ */
92
+ export function xmlBlockStartingWith(text, tag, prefix) {
93
+ const open = `<${tag} ${prefix}`;
94
+ const close = `</${tag}>`;
95
+ const start = text.indexOf(open);
96
+ if (start === -1)
97
+ return null;
98
+ const openerEnd = text.indexOf(">", start + open.length);
99
+ if (openerEnd === -1)
100
+ return null;
101
+ // Closing tags come in order, so the first opener with a closer after it is the one that pattern matched.
102
+ const end = text.indexOf(close, openerEnd + 1);
103
+ return end === -1 ? null : text.slice(start, end + close.length);
104
+ }
2
105
  /**
3
106
  * Every `<tag ...>body</tag>` block in `text`, in order, with the same
4
- * matches as `/<tag(\s[^>]*?)?>([\s\S]*?)<\/tag>/g`, found in linear time.
5
- * A lazy pattern like that one rescans the rest of the text for each opener
6
- * that has no closing tag, which a crafted file can turn into minutes.
107
+ * matches as `/<tag(\s[^>]*?)?>([\s\S]*?)<\/tag>/g`, found in linear time,
108
+ * and where each body starts and ends in `text`.
7
109
  */
8
110
  export function* xmlBlocks(text, tag) {
9
111
  const open = `<${tag}`;
@@ -25,7 +127,7 @@ export function* xmlBlocks(text, tag) {
25
127
  // No closing tag after this opener means none after any later one either.
26
128
  if (end === -1)
27
129
  return;
28
- yield { attrs: text.slice(start + open.length, openerEnd).trim(), body: text.slice(openerEnd + 1, end) };
130
+ yield { attrs: text.slice(start + open.length, openerEnd).trim(), body: text.slice(openerEnd + 1, end), bodyStart: openerEnd + 1, bodyEnd: end };
29
131
  from = end + close.length;
30
132
  }
31
133
  }
@@ -29,13 +29,43 @@ export function readCliConfig(env = process.env) {
29
29
  const text = readFileSync(path, "utf-8");
30
30
  if (text.length > MAX_CONFIG_BYTES)
31
31
  return {};
32
- const value = JSON.parse(text);
33
- return value && typeof value === "object" && !Array.isArray(value) ? value : {};
32
+ return checkedConfig(JSON.parse(text));
34
33
  }
35
34
  catch {
36
35
  return {};
37
36
  }
38
37
  }
38
+ const isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
39
+ /** What the update check stores as the latest version (see updateCheck.ts); anything else isn't a version. */
40
+ const VERSION_TEXT = /^\d{1,9}\.\d{1,9}\.\d{1,9}(-[0-9A-Za-z.-]{1,64})?$/;
41
+ /**
42
+ * The parts of a parsed config file that have the shape this tool writes. A
43
+ * value of the wrong type is dropped rather than used: the file can be
44
+ * hand-edited, or sit in a folder someone else controls, and a bad entry once
45
+ * stopped every command before it did any work.
46
+ */
47
+ function checkedConfig(value) {
48
+ if (!isRecord(value))
49
+ return {};
50
+ const config = {};
51
+ const { stats, updateCheck } = value;
52
+ if (isRecord(stats) && (stats.choice === "on" || stats.choice === "off") && typeof stats.decidedOn === "string") {
53
+ config.stats = { choice: stats.choice, decidedOn: stats.decidedOn.slice(0, 64) };
54
+ }
55
+ if (isRecord(updateCheck)) {
56
+ const checked = {};
57
+ if (typeof updateCheck.enabled === "boolean")
58
+ checked.enabled = updateCheck.enabled;
59
+ if (typeof updateCheck.lastCheckedAt === "number" && Number.isFinite(updateCheck.lastCheckedAt))
60
+ checked.lastCheckedAt = updateCheck.lastCheckedAt;
61
+ if (typeof updateCheck.latest === "string" && VERSION_TEXT.test(updateCheck.latest))
62
+ checked.latest = updateCheck.latest;
63
+ if (typeof updateCheck.outputAffecting === "string")
64
+ checked.outputAffecting = updateCheck.outputAffecting.slice(0, 300);
65
+ config.updateCheck = checked;
66
+ }
67
+ return config;
68
+ }
39
69
  /** Writes atomically (temp file + rename), so a crash never leaves a half-written config. */
40
70
  export function writeCliConfig(config, env = process.env) {
41
71
  const dir = configDir(env);
package/dist/cli/main.js CHANGED
@@ -45,7 +45,7 @@ function wrapText(text, width) {
45
45
  lines.push(line);
46
46
  return lines;
47
47
  }
48
- const TOP_LEVEL_HELP = `any2orca ${VERSION}: convert Bambu Studio, Creality Print, Anycubic Slicer Next, ElegooSlicer and Flash Studio .3mf projects to Snapmaker U1 / Orca format, entirely on this machine.
48
+ const TOP_LEVEL_HELP = `any2orca ${VERSION}: convert Bambu Studio, Creality Print, Anycubic Slicer Next, ElegooSlicer, Flash Studio and PrusaSlicer .3mf projects to Snapmaker U1 / Orca format, entirely on this machine.
49
49
 
50
50
  Usage: any2orca <command> [options]
51
51