Public: anyone can read this; the crew can change it.

A .step file's part card lists its bodies and units from the file's header #15861

Merged opened this

Check · Review · Land · Live done — Landed and live in production.

Merged

scout/forge:scout/15837-a-step-file-s-part-card-lists-its-bodies → main 0 commits fork 6 threads · 6 unresolved

  • Merged. scout/15837-a-step-file-s-part-card-lists-its-bodies was merged into main as 7404567.

Review

Sign in to review this change.
3 files changed +140 −5
docs/features/step.md +2 −2
@@ -10,7 +10,7 @@ A `.step` or `.stp` file (ISO 10303-21 text) opens on its blob page as a card of
1010
1111 Open the file. The card shows, as rows:
1212
13 - the header's schema, name, description, time stamp and the system that wrote it;
13 - the header's schema, name, description, time stamp, author and organisation, the system that wrote it and the length unit (each only when the file says it, none invented);
1414 - how many entities the file holds, in how many types;
1515 - the 20 most common entity types with their counts, and "N more types" past those;
1616 - the PRODUCT names, the first 50, and "N more" past those.
@@ -19,7 +19,7 @@ The sample repository of a preview has `part.step` to try it on.
1919
2020 ## What is read
2121
22 The HEADER section's `FILE_DESCRIPTION`, `FILE_NAME` and `FILE_SCHEMA`, and one scan of DATA for `#n=NAME(` entities and `PRODUCT('name'`. It is a summary, not a parse: a `#n=NAME(` inside a quoted string is counted too.
22 `readStep` in `src/web/render/step.ts` reads, with no dependency, the HEADER section's `FILE_DESCRIPTION`, `FILE_NAME` (name, time stamp, author, organisation, system) and `FILE_SCHEMA`, then scans DATA once for `#n=NAME(` entities, `PRODUCT('name'` and the length unit (`SI_UNIT` or `CONVERSION_BASED_UNIT` on the first `LENGTH_UNIT()` entity, looked at within 1,000 characters, so a hostile file costs linear time). It is a summary, not a parse: a `#n=NAME(` inside a quoted string is counted too.
2323
2424 A file that does not open with `ISO-10303-21;`, has no HEADER, or whose HEADER never ends is shown as text, with the reason. Over 5 MB the card is not made and the source is shown.
2525
src/web/render/step.ts +70 −3
@@ -28,6 +28,14 @@ export interface Card {
2828 readonly entities: number;
2929 readonly products: string[];
3030 readonly moreProducts: number;
31 /** All PRODUCT entities in DATA. */
32 readonly productTotal: number;

Non-blocking: productTotal has no reader after the Products row was removed. Remove it, or it is dead data.

33 /** FILE_NAME's authors and organisations, and the system that wrote the file. */
34 readonly authors: string[];
35 readonly organisations: string[];
36 readonly system: string;
37 /** "millimetres", "inches"…; "" when DATA names no length unit. */
38 readonly unit: string;
3139 }
3240
3341 /** The quoted strings of one HEADER statement, `''` read as an apostrophe. */
@@ -39,6 +47,56 @@ const strings = (statement: string): string[] =>
3947 const statement = (header: string, name: string): string =>
4048 new RegExp(`${name}\\s*\\(([\\s\\S]*?)\\)\\s*;`, "i").exec(header)?.[1] ?? "";
4149
50 /** FILE_NAME's slots, split at the commas outside quotes and brackets. */
51 function slots(args: string): string[] {
52 const out: string[] = [];
53 let depth = 0;
54 let inStr = false;
55 let cur = "";
56 for (const c of args) {
57 if (c === "'") inStr = !inStr;
58 if (!inStr && c === "(") depth++;
59 if (!inStr && c === ")") depth--;
60 if (!inStr && depth === 0 && c === ",") {
61 out.push(cur);
62 cur = "";
63 } else cur += c;
64 }
65 out.push(cur);
66 return out;
67 }
68
69 const SI_PREFIX: Readonly<Record<string, string>> = {
70 MILLI: "milli", CENTI: "centi", KILO: "kilo", MICRO: "micro", DECI: "deci",
71 };
72 const KNOWN: Readonly<Record<string, string>> = { INCH: "inches", FOOT: "feet", MILE: "miles", YARD: "yards" };
73 const UNIT_SPAN = 1000;
74 const UNIT_TRIES = 20;
75
76 /**
77 * The length unit of the first complex entity that says `LENGTH_UNIT()`.
78 * Linear: it looks at the text around at most UNIT_TRIES hits, UNIT_SPAN
79 * characters each side, never from every `#n=(`.
80 */
81 function lengthUnit(body: string): string {
82 let tries = 0;
83 for (const m of body.matchAll(/\bLENGTH_UNIT\s*\(\s*\)/gi)) {
84 if (tries++ >= UNIT_TRIES) break;
85 const at = m.index ?? 0;
86 const from = Math.max(body.lastIndexOf(";", at) + 1, at - UNIT_SPAN);
87 const to = body.indexOf(";", at);
88 const ent = body.slice(from, to < 0 ? at + UNIT_SPAN : Math.min(to, at + UNIT_SPAN));
89 const si = /\bSI_UNIT\s*\(\s*(?:\.([A-Z]+)\.|\$)\s*,\s*\.METRE\.\s*\)/i.exec(ent);
90 if (si !== null) return `${SI_PREFIX[(si[1] ?? "").toUpperCase()] ?? ""}metres`;
91 const conv = /\bCONVERSION_BASED_UNIT\s*\(\s*'((?:[^']|'')*)'/i.exec(ent);
92 if (conv !== null) {
93 const word = (conv[1] ?? "").replaceAll("''", "'").trim().slice(0, TEXT_CHARS);
94 return KNOWN[word.toUpperCase()] ?? word.toLowerCase();
95 }
96 }
97 return "";
98 }
99
42100 /** Read a STEP file's text. Pure. An error string when it is no part card. */
43101 export function readStep(text: string): Card | { error: string } {
44102 const src = text.replace(/^/, "").replace(/\/\*[\s\S]*?\*\//g, "");
@@ -66,16 +124,23 @@ export function readStep(text: string): Card | { error: string } {
66124 productTotal++;
67125 if (products.length < PRODUCT_CAP) products.push((m[1] ?? "").replaceAll("''", "'").slice(0, TEXT_CHARS));
68126 }
127 const fileName = slots(statement(header, "FILE_NAME"));
69128 const types = [...counts].sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0]));
70129 return {
71130 description: strings(statement(header, "FILE_DESCRIPTION")),
72 name: strings(statement(header, "FILE_NAME")),
131 name: strings(fileName.join(",")),
73132 schema: strings(statement(header, "FILE_SCHEMA")),
74133 types: types.slice(0, TOP_TYPES),
75134 typeKinds: types.length,
76135 entities,
77136 products,
78137 moreProducts: productTotal - products.length,
138 productTotal,
139 // FILE_NAME: name, time stamp, authors, organisations, preprocessor, system, authorisation.
140 authors: strings(fileName[2] ?? ""),
141 organisations: strings(fileName[3] ?? ""),
142 system: strings(fileName[5] ?? "")[0] ?? "",
143 unit: lengthUnit(body),
79144 };
80145 }
81146
@@ -87,13 +152,15 @@ const n = (x: number): string => x.toLocaleString("en");
87152 */
88153 export function stepFacts(card: Card): [string, string][] {
89154 // FILE_NAME: name, time stamp, authors, organisations, preprocessor, system, authorisation.
90 const [name, stamp, ...made] = card.name;
155 const [name, stamp] = card.name;
91156 const facts: [string, string][] = [
92157 ["Schema", card.schema.join(", ")],
93158 ["Name", name ?? ""],
94159 ["Description", card.description.join(" · ")],
95160 ["Written", stamp ?? ""],
96 ["Made with", made.join(" · ")],
161 ["Author", [...card.authors, ...card.organisations].join(" · ")],
162 ["System", card.system],
163 ["Unit", card.unit],
97164 ];
98165 return [...facts.filter(([, v]) => v !== ""), ["Entities", `${n(card.entities)} in ${n(card.typeKinds)} types`]];
99166 }
test/step-header.test.ts added +68
@@ -0,0 +1,68 @@
1 /** The STEP part card's header facts: author, system and length unit. */
2 import { describe, expect, test } from "bun:test";
3 import { readStep, type Card } from "../src/web/render/step.ts";
4 import { step } from "../src/web/render/step.ts";
5
6 const enc = (s: string): Uint8Array => new TextEncoder().encode(s);
7 const SAMPLE = `ISO-10303-21;
8 HEADER;
9 FILE_DESCRIPTION(('Bracket','ViewDefinition [x]'),'2;1');
10 FILE_NAME('bracket.stp','2026-01-02T03:04:05',('Ada; Lovelace'),('Acme'),'pre','CAD 1.0','');
11 FILE_SCHEMA(('AUTOMOTIVE_DESIGN { 1 0 10303 214 }'));
12 ENDSEC;
13 DATA;
14 #1=PRODUCT('Bracket','Bracket','',(#9));
15 #2=PRODUCT('Bolt','Bolt','',(#9));
16 #3=(LENGTH_UNIT()NAMED_UNIT(*)SI_UNIT(.MILLI.,.METRE.));
17 ENDSEC;
18 END-ISO-10303-21;
19 `;
20 const card = (s: string): Card => readStep(s) as Card;
21 const html = (s: string): string => String(step({ path: "a.step", size: s.length, body: enc(s), media: "/m", download: "/d" }).content);
22
23 describe("step header facts", () => {
24 test("reads authors, organisations, system and unit", () => {
25 const c = card(SAMPLE);
26 expect(c.authors).toEqual(["Ada; Lovelace"]);
27 expect(c.organisations).toEqual(["Acme"]);
28 expect(c.system).toBe("CAD 1.0");
29 expect(c.unit).toBe("millimetres");
30 });
31
32 test("inch and bare metre units", () => {
33 const inch = SAMPLE.replace(/#3=.*\n/, "#3=(CONVERSION_BASED_UNIT('INCH',#5)LENGTH_UNIT()NAMED_UNIT(#4));\n");
34 expect(card(inch).unit).toBe("inches");
35 expect(card(SAMPLE.replace(".MILLI.", "$")).unit).toBe("metres");
36 });
37
38 test("a unit far past 64 KB is still found", () => {
outdated

This replace changes nothing. The test asserts fields the card ignores; assert the card instead.

39 const late = SAMPLE.replace("#3=", "/*" + "x".repeat(70000) + "*/\n#3=");
40 expect(card(late).unit).toBe("millimetres");
41 const pad = SAMPLE.replace("#3=", "#7=PRODUCT('" + "y".repeat(70000) + "','','',(#9));\n#3=");
42 expect(card(pad).unit).toBe("millimetres");
43 });
44
45 test("a hostile file of repeated '#1=(' is read in linear time", () => {
46 const bad = SAMPLE.replace("#3=", "#1=(".repeat(200000) + "\n#3=");
47 const t = performance.now();
48 card(bad);
49 html(bad);
50 expect(performance.now() - t).toBeLessThan(1500);
51 });
52
53 test("a non-STEP file named .step falls back", () => {
54 const out = step({ path: "a.step", size: 12, body: enc("hello world\n"), media: "/m", download: "/d" });
55 expect(out.fallback).toContain("ISO-10303-21");
56 });
57
58 test("the card shows the facts once, and omits what is absent", () => {
59 const full = html(SAMPLE);
60 expect(full).toContain("<dt>Author</dt><dd>Ada; Lovelace · Acme</dd>");
61 expect(full).toContain("<dt>System</dt><dd>CAD 1.0</dd>");
62 expect(full).toContain("<dt>Unit</dt><dd>millimetres</dd>");
63 expect(full).not.toContain("<dt>Products</dt>");
64 const bare = SAMPLE.replace(/#3=.*\n/, "").replace("('Ada; Lovelace'),('Acme'),'pre','CAD 1.0'", "(''),(''),'',''");
65 const out = html(bare);
66 for (const k of ["Author", "System", "Unit"]) expect(out).not.toContain(`<dt>${k}</dt>`);
67 });
68 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs