@bitbybit-dev/create-app 1.3.2 → 1.4.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.
Files changed (190) hide show
  1. package/README.md +47 -124
  2. package/dist/index.js +253 -21
  3. package/dist/index.js.map +1 -1
  4. package/dist/scaffold.d.ts +30 -0
  5. package/dist/scaffold.d.ts.map +1 -0
  6. package/dist/scaffold.js +107 -0
  7. package/dist/scaffold.js.map +1 -0
  8. package/package.json +4 -3
  9. package/src/index.test.ts +309 -8
  10. package/src/index.ts +285 -24
  11. package/src/scaffold.test.ts +177 -0
  12. package/src/scaffold.ts +99 -0
  13. package/templates/_agent/AGENTS.md +39 -0
  14. package/templates/_agent/CLAUDE.md +1 -0
  15. package/templates/_agent/_dot-cursor/mcp.json +5 -0
  16. package/templates/_agent/_dot-gitignore +7 -0
  17. package/templates/_agent/_dot-mcp.json +5 -0
  18. package/templates/_agent/_dot-vscode/mcp.json +5 -0
  19. package/templates/apps/drone-assembly/AGENTS.section.md +20 -0
  20. package/templates/apps/drone-assembly/README.md +35 -0
  21. package/templates/apps/drone-assembly/eslint.config.js +47 -0
  22. package/templates/apps/drone-assembly/index.html +17 -0
  23. package/templates/apps/drone-assembly/package.json +31 -0
  24. package/templates/apps/drone-assembly/public/favicon.ico +0 -0
  25. package/templates/apps/drone-assembly/public/logo.png +0 -0
  26. package/templates/apps/drone-assembly/scripts/smoke.ts +172 -0
  27. package/templates/apps/drone-assembly/src/assembly.ts +99 -0
  28. package/templates/apps/drone-assembly/src/exports.ts +10 -0
  29. package/templates/apps/drone-assembly/src/kernel.ts +14 -0
  30. package/templates/apps/drone-assembly/src/main.ts +298 -0
  31. package/templates/apps/drone-assembly/src/materials.ts +58 -0
  32. package/templates/apps/drone-assembly/src/model.ts +280 -0
  33. package/templates/apps/drone-assembly/src/parts.ts +343 -0
  34. package/templates/apps/drone-assembly/src/style.css +219 -0
  35. package/templates/apps/drone-assembly/src/ui.ts +180 -0
  36. package/templates/apps/drone-assembly/src/vite-env.d.ts +1 -0
  37. package/templates/apps/drone-assembly/tsconfig.json +29 -0
  38. package/templates/apps/laser-cut-box/AGENTS.section.md +17 -0
  39. package/templates/apps/laser-cut-box/README.md +34 -0
  40. package/templates/apps/laser-cut-box/eslint.config.js +47 -0
  41. package/templates/apps/laser-cut-box/index.html +17 -0
  42. package/templates/apps/laser-cut-box/package.json +30 -0
  43. package/templates/apps/laser-cut-box/public/favicon.ico +0 -0
  44. package/templates/apps/laser-cut-box/public/logo.png +0 -0
  45. package/templates/apps/laser-cut-box/scripts/smoke.ts +106 -0
  46. package/templates/apps/laser-cut-box/src/exports.ts +28 -0
  47. package/templates/apps/laser-cut-box/src/main.ts +176 -0
  48. package/templates/apps/laser-cut-box/src/model.ts +92 -0
  49. package/templates/apps/laser-cut-box/src/panels.ts +229 -0
  50. package/templates/apps/laser-cut-box/src/style.css +223 -0
  51. package/templates/apps/laser-cut-box/src/ui.ts +136 -0
  52. package/templates/apps/laser-cut-box/src/vite-env.d.ts +1 -0
  53. package/templates/apps/laser-cut-box/tsconfig.json +29 -0
  54. package/templates/apps/product-configurator/AGENTS.section.md +19 -0
  55. package/templates/apps/product-configurator/README.md +33 -0
  56. package/templates/apps/product-configurator/eslint.config.js +47 -0
  57. package/templates/apps/product-configurator/index.html +17 -0
  58. package/templates/apps/product-configurator/package.json +30 -0
  59. package/templates/apps/product-configurator/public/favicon.ico +0 -0
  60. package/templates/apps/product-configurator/public/logo.png +0 -0
  61. package/templates/apps/product-configurator/scripts/smoke.ts +69 -0
  62. package/templates/apps/product-configurator/src/catalog.ts +56 -0
  63. package/templates/apps/product-configurator/src/exports.ts +19 -0
  64. package/templates/apps/product-configurator/src/main.ts +134 -0
  65. package/templates/apps/product-configurator/src/model.ts +153 -0
  66. package/templates/apps/product-configurator/src/style.css +177 -0
  67. package/templates/apps/product-configurator/src/ui.ts +150 -0
  68. package/templates/apps/product-configurator/src/vite-env.d.ts +1 -0
  69. package/templates/apps/product-configurator/tsconfig.json +29 -0
  70. package/templates/apps/sheet-metal-unfold/AGENTS.section.md +26 -0
  71. package/templates/apps/sheet-metal-unfold/README.md +41 -0
  72. package/templates/apps/sheet-metal-unfold/backend/_dot-env.example +5 -0
  73. package/templates/apps/sheet-metal-unfold/backend/eslint.config.js +47 -0
  74. package/templates/apps/sheet-metal-unfold/backend/package.json +28 -0
  75. package/templates/apps/sheet-metal-unfold/backend/scripts/smoke.ts +52 -0
  76. package/templates/apps/sheet-metal-unfold/backend/src/app.ts +65 -0
  77. package/templates/apps/sheet-metal-unfold/backend/src/cloud.ts +42 -0
  78. package/templates/apps/sheet-metal-unfold/backend/src/index.ts +13 -0
  79. package/templates/apps/sheet-metal-unfold/backend/tsconfig.build.json +9 -0
  80. package/templates/apps/sheet-metal-unfold/backend/tsconfig.json +27 -0
  81. package/templates/apps/sheet-metal-unfold/frontend/eslint.config.js +47 -0
  82. package/templates/apps/sheet-metal-unfold/frontend/index.html +17 -0
  83. package/templates/apps/sheet-metal-unfold/frontend/package.json +30 -0
  84. package/templates/apps/sheet-metal-unfold/frontend/public/favicon.ico +0 -0
  85. package/templates/apps/sheet-metal-unfold/frontend/public/logo.png +0 -0
  86. package/templates/apps/sheet-metal-unfold/frontend/scripts/smoke.ts +84 -0
  87. package/templates/apps/sheet-metal-unfold/frontend/src/cloud-access.ts +37 -0
  88. package/templates/apps/sheet-metal-unfold/frontend/src/exports.ts +10 -0
  89. package/templates/apps/sheet-metal-unfold/frontend/src/flat.ts +71 -0
  90. package/templates/apps/sheet-metal-unfold/frontend/src/main.ts +193 -0
  91. package/templates/apps/sheet-metal-unfold/frontend/src/model.ts +166 -0
  92. package/templates/apps/sheet-metal-unfold/frontend/src/style.css +291 -0
  93. package/templates/apps/sheet-metal-unfold/frontend/src/ui.ts +150 -0
  94. package/templates/apps/sheet-metal-unfold/frontend/src/vite-env.d.ts +1 -0
  95. package/templates/apps/sheet-metal-unfold/frontend/tsconfig.json +29 -0
  96. package/templates/apps/sheet-metal-unfold/frontend/vite.config.ts +9 -0
  97. package/templates/apps/sheet-metal-unfold/package.json +18 -0
  98. package/templates/apps/step-to-gltf-cli/AGENTS.section.md +20 -0
  99. package/templates/apps/step-to-gltf-cli/README.md +34 -0
  100. package/templates/apps/step-to-gltf-cli/eslint.config.js +47 -0
  101. package/templates/apps/step-to-gltf-cli/package.json +26 -0
  102. package/templates/apps/step-to-gltf-cli/samples/bracket.step +2545 -0
  103. package/templates/apps/step-to-gltf-cli/scripts/smoke.ts +49 -0
  104. package/templates/apps/step-to-gltf-cli/src/cli.ts +106 -0
  105. package/templates/apps/step-to-gltf-cli/src/cloud.ts +34 -0
  106. package/templates/apps/step-to-gltf-cli/src/convert.ts +65 -0
  107. package/templates/apps/step-to-gltf-cli/src/kernel.ts +14 -0
  108. package/templates/apps/step-to-gltf-cli/tsconfig.json +27 -0
  109. package/templates/cloud/AGENTS.section.md +22 -0
  110. package/templates/cloud/backends/dotnet-rest/BitbybitClient.cs +22 -50
  111. package/templates/cloud/backends/dotnet-rest/Program.cs +1 -11
  112. package/templates/cloud/backends/dotnet-rest/dotnet-rest.csproj +4 -1
  113. package/templates/cloud/backends/hono-rest/eslint.config.js +47 -0
  114. package/templates/cloud/backends/hono-rest/package.json +11 -4
  115. package/templates/cloud/backends/hono-rest/src/bitbybit-client.ts +34 -45
  116. package/templates/cloud/backends/hono-rest/src/index.ts +1 -11
  117. package/templates/cloud/backends/hono-rest/tsconfig.json +19 -8
  118. package/templates/cloud/backends/hono-sdk/eslint.config.js +47 -0
  119. package/templates/cloud/backends/hono-sdk/package.json +12 -5
  120. package/templates/cloud/backends/hono-sdk/src/bitbybit-client.ts +6 -37
  121. package/templates/cloud/backends/hono-sdk/src/index.ts +1 -12
  122. package/templates/cloud/backends/hono-sdk/tsconfig.json +19 -8
  123. package/templates/cloud/backends/nodejs-rest/eslint.config.js +47 -0
  124. package/templates/cloud/backends/nodejs-rest/package.json +12 -5
  125. package/templates/cloud/backends/nodejs-rest/src/bitbybit-client.ts +6 -35
  126. package/templates/cloud/backends/nodejs-rest/src/index.ts +6 -16
  127. package/templates/cloud/backends/nodejs-rest/tsconfig.build.json +9 -0
  128. package/templates/cloud/backends/nodejs-rest/tsconfig.json +17 -7
  129. package/templates/cloud/backends/nodejs-sdk/eslint.config.js +47 -0
  130. package/templates/cloud/backends/nodejs-sdk/package.json +14 -7
  131. package/templates/cloud/backends/nodejs-sdk/src/bitbybit-client.ts +8 -33
  132. package/templates/cloud/backends/nodejs-sdk/src/index.ts +5 -16
  133. package/templates/cloud/backends/nodejs-sdk/tsconfig.build.json +9 -0
  134. package/templates/cloud/backends/nodejs-sdk/tsconfig.json +19 -9
  135. package/templates/cloud/frontend/eslint.config.js +50 -0
  136. package/templates/cloud/frontend/index.html +3 -1
  137. package/templates/cloud/frontend/package.json +13 -4
  138. package/templates/cloud/frontend/public/favicon.ico +0 -0
  139. package/templates/cloud/frontend/public/logo.png +0 -0
  140. package/templates/cloud/frontend/src/App.tsx +11 -9
  141. package/templates/cloud/frontend/src/api.ts +31 -0
  142. package/templates/cloud/frontend/src/components/ApiKeyWarning.tsx +28 -25
  143. package/templates/cloud/frontend/src/components/Header.tsx +4 -2
  144. package/templates/cloud/frontend/src/components/Tabs.tsx +4 -3
  145. package/templates/cloud/frontend/src/components/Viewer.tsx +57 -77
  146. package/templates/cloud/frontend/src/main.tsx +6 -1
  147. package/templates/cloud/frontend/src/panels/ModelsPanel.tsx +65 -73
  148. package/templates/cloud/frontend/src/panels/PipelinesPanel.tsx +82 -83
  149. package/templates/cloud/frontend/src/vite-env.d.ts +1 -0
  150. package/templates/cloud/frontend/tsconfig.json +19 -7
  151. package/templates/vite/babylonjs/typescript/AGENTS.section.md +13 -0
  152. package/templates/vite/babylonjs/typescript/eslint.config.js +47 -0
  153. package/templates/vite/babylonjs/typescript/index.html +4 -2
  154. package/templates/vite/babylonjs/typescript/package.json +14 -4
  155. package/templates/vite/babylonjs/typescript/public/favicon.ico +0 -0
  156. package/templates/vite/babylonjs/typescript/public/logo.png +0 -0
  157. package/templates/vite/babylonjs/typescript/scripts/smoke.ts +41 -0
  158. package/templates/vite/babylonjs/typescript/src/main.ts +8 -17
  159. package/templates/vite/babylonjs/typescript/src/model.ts +24 -0
  160. package/templates/vite/babylonjs/typescript/tsconfig.json +16 -12
  161. package/templates/vite/playcanvas/typescript/AGENTS.section.md +13 -0
  162. package/templates/vite/playcanvas/typescript/eslint.config.js +47 -0
  163. package/templates/vite/playcanvas/typescript/index.html +4 -2
  164. package/templates/vite/playcanvas/typescript/package.json +14 -4
  165. package/templates/vite/playcanvas/typescript/public/favicon.ico +0 -0
  166. package/templates/vite/playcanvas/typescript/public/logo.png +0 -0
  167. package/templates/vite/playcanvas/typescript/scripts/smoke.ts +41 -0
  168. package/templates/vite/playcanvas/typescript/src/main.ts +11 -22
  169. package/templates/vite/playcanvas/typescript/src/model.ts +24 -0
  170. package/templates/vite/playcanvas/typescript/tsconfig.json +16 -12
  171. package/templates/vite/threejs/typescript/AGENTS.section.md +13 -0
  172. package/templates/vite/threejs/typescript/eslint.config.js +47 -0
  173. package/templates/vite/threejs/typescript/index.html +4 -2
  174. package/templates/vite/threejs/typescript/package.json +16 -6
  175. package/templates/vite/threejs/typescript/public/favicon.ico +0 -0
  176. package/templates/vite/threejs/typescript/public/logo.png +0 -0
  177. package/templates/vite/threejs/typescript/scripts/smoke.ts +41 -0
  178. package/templates/vite/threejs/typescript/src/main.ts +11 -22
  179. package/templates/vite/threejs/typescript/src/model.ts +24 -0
  180. package/templates/vite/threejs/typescript/tsconfig.json +16 -12
  181. package/templates/vite/babylonjs/typescript/public/vite.svg +0 -1
  182. package/templates/vite/playcanvas/typescript/public/vite.svg +0 -1
  183. package/templates/vite/threejs/typescript/public/vite.svg +0 -1
  184. /package/templates/cloud/backends/dotnet-rest/{_gitignore → _dot-gitignore} +0 -0
  185. /package/templates/cloud/backends/hono-rest/{_gitignore → _dot-gitignore} +0 -0
  186. /package/templates/cloud/backends/hono-sdk/{_gitignore → _dot-gitignore} +0 -0
  187. /package/templates/cloud/backends/nodejs-rest/{.env.example → _dot-env.example} +0 -0
  188. /package/templates/cloud/backends/nodejs-rest/{_gitignore → _dot-gitignore} +0 -0
  189. /package/templates/cloud/backends/nodejs-sdk/{.env.example → _dot-env.example} +0 -0
  190. /package/templates/cloud/backends/nodejs-sdk/{_gitignore → _dot-gitignore} +0 -0
@@ -0,0 +1,29 @@
1
+ {
2
+ "compilerOptions": {
3
+ "target": "ES2022",
4
+ "module": "ESNext",
5
+ "moduleResolution": "bundler",
6
+ "lib": ["ES2022", "DOM", "DOM.Iterable"],
7
+ "types": ["node"],
8
+ "allowImportingTsExtensions": true,
9
+ "moduleDetection": "force",
10
+ "noEmit": true,
11
+ "strict": true,
12
+ "noUncheckedIndexedAccess": true,
13
+ "exactOptionalPropertyTypes": true,
14
+ "noImplicitReturns": true,
15
+ "noImplicitOverride": true,
16
+ "noPropertyAccessFromIndexSignature": true,
17
+ "noFallthroughCasesInSwitch": true,
18
+ "noUnusedLocals": true,
19
+ "noUnusedParameters": true,
20
+ "useUnknownInCatchVariables": true,
21
+ "forceConsistentCasingInFileNames": true,
22
+ "isolatedModules": true,
23
+ "verbatimModuleSyntax": true,
24
+ "erasableSyntaxOnly": true,
25
+ "noUncheckedSideEffectImports": true,
26
+ "skipLibCheck": true
27
+ },
28
+ "include": ["src", "scripts"]
29
+ }
@@ -0,0 +1,26 @@
1
+ ## This template: sheet-metal unfold
2
+
3
+ A sheet-metal channel that is built in the browser on the open-source packages and unfolded on CAD Cloud, because the unfold is a Pro algorithm that exists only there. Two packages in one npm workspace: `frontend/` (Vite, Three.js, the OCCT kernel in a worker) and `backend/` (Express, the CAD Cloud SDK, the key).
4
+
5
+ - `frontend/src/model.ts` is the open-source geometry. `centreLine` is the sheet's centre line through the channel's cross-section as a sharp polyline; `buildModel(occt, params)` rounds every corner of it with `fillet2d` at the mid-sheet radius (inner radius plus half the thickness), then sweeps a thickness-by-depth rectangle along it with `pipe`. A swept sheet has concentric bend arcs and one thickness everywhere, which is what the unfold needs. `mounting` then adds two holes through the base and a slot through each flange, on the flat sheet between the bends and never in a bend zone, leaving out any feature that does not fit with its margin (`MOUNTING`); the slot is a rectangle rounded to a stadium. The part's volume is exactly the thickness times the centre line's length times the depth minus what those features remove (`removedVolume`, analytic because every feature goes through flat sheet), which is what the smoke checks. `flatLengthEstimate` is the K-factor estimate of the developed length, computed without any kernel, so the page shows a number before the cloud answers and the difference afterwards.
6
+ - `frontend/src/flat.ts` reads the cloud's report: bend lines to draw over the flat pattern, and `summarize` for the facts. `toScene` maps the report's Z-up frame onto the ground plane the flat STEP is loaded onto with `adjustZtoY`.
7
+ - `frontend/src/main.ts` is the wiring: scene, kernel, debounced rebuilds, the part and flat views (the flat pattern drawn one millimetre above the ground so it never fights the ground plane for pixels), the unfold call and the downloads, the sheet in a brushed steel material under a room environment. `cameraOptions` gives the orbit camera explicit distance limits from the scene size and leaves its sensitivities at their base values: the engine's defaults scale zoom and pan by the scene size although both already follow the camera's distance, so a scene this large would jump a third of the way in per wheel notch.
8
+ - `frontend/src/cloud-access.ts` is the access state: `accessFromResponse` turns the backend's answer into `ready`, `locked` (503 with `NO_API_KEY`), `unreachable` or `error`, and `renderAccess` shows the locked state with the CAD Cloud page, the Studio keys page and the `.env` line. That state is part of the app: keep it working and keep its links current.
9
+ - `backend/src/app.ts` is the whole server: `GET /api/health` and `POST /api/unfold`. Without a gateway it answers 503 with the code above. With one it uploads the STEP text, calls the Pro unfold, waits for the task, fetches the flat STEP and returns it with the report from the task metadata. `backend/src/cloud.ts` is the gateway over the SDK: uploads, tasks and results through the SDK's endpoints, the unfold through the client's `request` method because the SDK has no wrapper for the Pro endpoints yet.
10
+ - Smokes: `frontend` (typecheck and lint, then the kernel, typed as the browser's `Occt` through one `inProcess` cast and awaited, builds three channels and checks each is a valid solid whose volume is the thickness times the rounded centre line times the depth minus the mounting features, with the declared extents, the estimate is below the outer lengths, and the pure cloud code maps a canned report and the three access states; The kernel is loaded in-process from `node_modules`, the same WebAssembly the browser runs inside a worker; its content-hashed `.wasm` is found beside the loader rather than spelled out.) and `backend` (typecheck and lint, then the app is started twice on a free port: without a key it must answer 503 with the code and both links; with a fake gateway it must call upload, unfold, wait, downloads and fetch in that order and pass the report, the flat STEP and the downloads through). Neither needs a key or a network.
11
+
12
+ Commands, from the project root:
13
+
14
+ - `npm install` installs both workspaces
15
+ - `npm run dev:backend` serves the backend on http://localhost:3000; `npm run dev:frontend` serves the page at http://localhost:5173 with `/api` proxied to it
16
+ - `npm run smoke` runs both smokes, each typechecking and linting first; `npm run build` builds both; `npm run typecheck` and `npm run lint` run across both
17
+
18
+ ## What needs CAD Cloud and where to get it
19
+
20
+ Only the unfold. Building the part, measuring it, estimating the flat length and downloading the part as STEP run in the browser on the MIT packages; nothing of Bitbybit's is in that loop. The unfold (`POST /api/v1/cad/pro/unfold/solid`) is a Pro algorithm available only on [CAD Cloud](https://bitbybit.dev/cad-cloud): it returns the flat pattern as STEP and glTF and a report with every bend's angle, radii and allowance. That is the one call in `backend/src/cloud.ts`.
21
+
22
+ - The plan needed: any CAD Cloud plan. The key needs the `cad`, `files` and `tasks` scopes. Every unfold is one metered task on the key's account.
23
+ - Where the key comes from: [Bitbybit Studio](https://studio.bitbybit.dev/keys/billing), which also lists the tasks this app ran.
24
+ - Where the key goes: `backend/.env` as `BITBYBIT_API_KEY=...`, which `.gitignore` already ignores. Never in `frontend/`, never in a prompt, never in a log.
25
+ - Without a key: the backend answers 503 with `NO_API_KEY`, the page shows the access state with the links above, and everything else keeps working. Do not move the unfold call into the browser to avoid the backend: that would put the key in the client.
26
+ - Do not replace the cloud unfold with a browser approximation and present it as the flat pattern: the K-factor estimate is shown as an estimate, on purpose. A one-line manual check with a real key against staging is part of releasing this template, because the fake gateway proves the plumbing, not the algorithm.
@@ -0,0 +1,41 @@
1
+ # {{PROJECT_NAME}}
2
+
3
+ A sheet-metal channel that you shape in the browser and unfold on [Bitbybit CAD Cloud](https://bitbybit.dev/cad-cloud). The part, its measurements, the K-factor estimate of its flat length and the STEP download all run in your browser on the open-source [Bitbybit](https://bitbybit.dev) packages. The exact flat pattern, with its bend lines and bend table, comes from the cloud's sheet-metal unfold, a Pro algorithm that exists only there, and comes back as STEP and as a DXF written in the browser.
4
+
5
+ ```bash
6
+ npm install # both workspaces
7
+ npm run dev:backend # http://localhost:3000, holds the key
8
+ npm run dev:frontend # http://localhost:5173, proxies /api to the backend
9
+ npm run smoke # both smokes, each typechecking and linting first; no key and no network needed
10
+ npm run lint # the lint rules, at error, across both
11
+ ```
12
+
13
+ ## What needs CAD Cloud and where to get it
14
+
15
+ | | |
16
+ |---|---|
17
+ | What runs in the browser | building the channel, measuring it, the flat-length estimate, the STEP download of the part, the DXF of the flat pattern once it is back |
18
+ | What runs on CAD Cloud | the unfold itself: one call from `backend/src/cloud.ts` to the Pro endpoint, returning the flat pattern and the bend report |
19
+ | Plan needed | any [CAD Cloud plan](https://bitbybit.dev/cad-cloud); the key needs the `cad`, `files` and `tasks` scopes; every unfold is one metered task |
20
+ | Where keys live | [Bitbybit Studio](https://studio.bitbybit.dev/keys/billing), which also shows the tasks this app ran |
21
+ | Where the key goes | `backend/.env` as `BITBYBIT_API_KEY=...`; it never reaches the browser |
22
+ | Without a key | the backend answers 503, the page explains it with these links, and everything that runs in the browser keeps working |
23
+
24
+ Why a backend at all: the browser could not hold the key without exposing it. The backend is forty lines of Express whose only job is to keep the key on the server and forward one request.
25
+
26
+ ## How it is put together
27
+
28
+ | File | Role |
29
+ |---|---|
30
+ | `frontend/src/model.ts` | the channel as a rounded centre line swept with the sheet's section, with mounting holes in the base and a slot in each flange where they fit, its volume, the K-factor estimate |
31
+ | `frontend/src/flat.ts` | reads the cloud's report: bend lines and a summary |
32
+ | `frontend/src/cloud-access.ts` | the access state: ready, locked without a key, backend unreachable, error |
33
+ | `frontend/src/main.ts` | scene, kernel, rebuilds, the unfold call, the two views, the downloads |
34
+ | `backend/src/app.ts`, `backend/src/cloud.ts` | the unfold route and the gateway over the CAD Cloud SDK |
35
+ | `frontend/scripts/smoke.ts`, `backend/scripts/smoke.ts` | headless checks of the geometry and of the route, with a fake gateway |
36
+
37
+ ## Working with an AI agent
38
+
39
+ `AGENTS.md` explains the project to a coding agent, including what needs the cloud and why, and the free Bitbybit CAD MCP server is configured for Claude Code, Cursor and VS Code. Ask for a different profile or a hole pattern, then let it run `npm run smoke`.
40
+
41
+ Scaffolded by `@bitbybit-dev/create-app` {{CLI_VERSION}}. [Documentation](https://learn.bitbybit.dev), [the packages](https://github.com/bitbybit-dev/bitbybit), [Discord](https://discord.gg/GSe3VMe).
@@ -0,0 +1,5 @@
1
+ # The CAD Cloud API key this backend unfolds with. Keys come from Bitbybit Studio:
2
+ # https://studio.bitbybit.dev/keys/billing (any plan: https://bitbybit.dev/cad-cloud)
3
+ BITBYBIT_API_KEY=
4
+ BITBYBIT_API_URL=https://api.bitbybit.dev
5
+ PORT=3000
@@ -0,0 +1,47 @@
1
+ import { defineConfig, globalIgnores } from "eslint/config";
2
+ import eslint from "@eslint/js";
3
+ import tseslint from "typescript-eslint";
4
+ import noComments from "eslint-plugin-no-comments";
5
+
6
+ const DOUBLE_ASSERTION = ":matches(TSAsExpression, TSTypeAssertion) > :matches(TSAsExpression, TSTypeAssertion).expression[typeAnnotation.type=/^TS(Unknown|Any)Keyword$/]";
7
+
8
+ export default defineConfig([
9
+ globalIgnores(["dist/", "node_modules/", "**/*.d.ts"]),
10
+ {
11
+ files: ["**/*.ts"],
12
+ extends: [eslint.configs.recommended, tseslint.configs.strictTypeChecked, tseslint.configs.stylisticTypeChecked],
13
+ plugins: { "no-comments": noComments },
14
+ languageOptions: { parserOptions: { projectService: true, tsconfigRootDir: import.meta.dirname } },
15
+ rules: {
16
+ quotes: ["error", "double", { avoidEscape: true, allowTemplateLiterals: true }],
17
+ semi: ["error", "always"],
18
+ eqeqeq: ["error", "always"],
19
+ curly: ["error", "multi-line"],
20
+ "prefer-const": "error",
21
+ "no-var": "error",
22
+ "max-lines": ["error", { max: 600, skipBlankLines: true, skipComments: true }],
23
+ "no-warning-comments": ["error", { terms: ["todo", "fixme", "hack"], location: "anywhere" }],
24
+ "no-comments/disallowComments": ["error", { allow: ["global", "eslint", "/ <reference"] }],
25
+ "no-restricted-syntax": ["error", { selector: DOUBLE_ASSERTION, message: "A double assertion replaces a type instead of narrowing it: write a type predicate, constrain a generic to the union, or fix the type this is arguing with." }],
26
+ "@typescript-eslint/no-unused-vars": ["error", { argsIgnorePattern: "^_", varsIgnorePattern: "^_", caughtErrorsIgnorePattern: "^_", ignoreRestSiblings: true }],
27
+ "@typescript-eslint/no-explicit-any": "error",
28
+ "@typescript-eslint/no-non-null-assertion": "error",
29
+ "@typescript-eslint/explicit-function-return-type": ["error", { allowExpressions: true, allowTypedFunctionExpressions: true, allowHigherOrderFunctions: true, allowDirectConstAssertionInArrowFunctions: true }],
30
+ "@typescript-eslint/consistent-type-imports": ["error", { prefer: "type-imports", fixStyle: "separate-type-imports", disallowTypeAnnotations: false }],
31
+ "@typescript-eslint/restrict-template-expressions": ["error", { allowNumber: true, allowBoolean: true, allowNullish: false, allowRegExp: false }],
32
+ "@typescript-eslint/naming-convention": [
33
+ "error",
34
+ { selector: "default", format: ["camelCase"], leadingUnderscore: "allow" },
35
+ { selector: "variable", format: ["camelCase", "UPPER_CASE"], leadingUnderscore: "allow" },
36
+ { selector: "parameter", format: ["camelCase"], leadingUnderscore: "allow" },
37
+ { selector: "typeLike", format: ["PascalCase"] },
38
+ { selector: "property", format: null },
39
+ { selector: "method", format: ["camelCase"] },
40
+ { selector: "import", format: null },
41
+ ],
42
+ "@typescript-eslint/only-throw-error": "error",
43
+ "@typescript-eslint/unbound-method": ["error", { ignoreStatic: true }],
44
+ "@typescript-eslint/non-nullable-type-assertion-style": "off",
45
+ },
46
+ },
47
+ ]);
@@ -0,0 +1,28 @@
1
+ {
2
+ "name": "bitbybit-sheet-metal-unfold-backend",
3
+ "private": true,
4
+ "version": "0.0.0",
5
+ "type": "module",
6
+ "scripts": {
7
+ "dev": "tsx watch --env-file=.env src/index.ts",
8
+ "build": "tsc -p tsconfig.build.json",
9
+ "start": "node --env-file=.env dist/index.js",
10
+ "smoke": "npm run typecheck && npm run lint && tsx scripts/smoke.ts",
11
+ "typecheck": "tsc --noEmit",
12
+ "lint": "eslint . --max-warnings 0"
13
+ },
14
+ "dependencies": {
15
+ "@bitbybit-dev/cad-cloud-sdk": "1.4.0",
16
+ "express": "^5.1.0"
17
+ },
18
+ "devDependencies": {
19
+ "@eslint/js": "10.0.1",
20
+ "@types/express": "^5.0.2",
21
+ "@types/node": "22.20.1",
22
+ "eslint": "10.10.0",
23
+ "eslint-plugin-no-comments": "1.2.1",
24
+ "tsx": "^4.19.0",
25
+ "typescript": "5.9.3",
26
+ "typescript-eslint": "8.70.0"
27
+ }
28
+ }
@@ -0,0 +1,52 @@
1
+ import type { AddressInfo } from "node:net";
2
+ import { createApp, NO_KEY_CODE } from "../src/app.js";
3
+ import type { CloudGateway } from "../src/cloud.js";
4
+
5
+ const problems: string[] = [];
6
+
7
+ async function serve(gateway: CloudGateway | null): Promise<{ url: string; close: () => void }> {
8
+ const server = createApp(gateway).listen(0);
9
+ await new Promise<void>((resolve) => server.once("listening", () => { resolve(); }));
10
+ const { port } = server.address() as AddressInfo;
11
+ return { url: `http://127.0.0.1:${port}`, close: () => server.close() };
12
+ }
13
+
14
+ const FLAT_STEP = "ISO-10303-21;\nHEADER;\nENDSEC;\nDATA;\nENDSEC;\nEND-ISO-10303-21;\n";
15
+ const calls: string[] = [];
16
+ const fake: CloudGateway = {
17
+ uploadStep(fileName, stepText) { calls.push(`upload ${fileName} ${stepText.length}`); return Promise.resolve("file-1"); },
18
+ unfoldSolid(body) { calls.push(`unfold ${body.stepFileId} k=${body.kFactor} ${body.outputs.formats.join("+")}`); return Promise.resolve({ taskId: "task-1" }); },
19
+ waitForTask(taskId) { calls.push(`wait ${taskId}`); return Promise.resolve({ status: "completed", metadata: { report: [{ solidIndex: 0, ok: true, thickness: 2, kFactor: 0.44, bends: [], flatBBox: [0, 0, 120, 60], flatArea: 7200 }] }, error: null }); },
20
+ downloads(taskId) { calls.push(`downloads ${taskId}`); return Promise.resolve([{ format: "step", downloadUrl: "https://example.test/flat.step", filename: "flat.step" }, { format: "glb", downloadUrl: "https://example.test/flat.glb", filename: "flat.glb" }]); },
21
+ fetchText(url) { calls.push(`fetch ${url}`); return Promise.resolve(FLAT_STEP); },
22
+ };
23
+
24
+ const withoutKey = await serve(null);
25
+ const locked = await fetch(`${withoutKey.url}/api/unfold`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ stepText: "x" }) });
26
+ const lockedBody = (await locked.json()) as { code?: string; help?: string };
27
+ if (locked.status !== 503) problems.push(`without a key the unfold answered ${locked.status}, expected 503`);
28
+ if (lockedBody.code !== NO_KEY_CODE) problems.push(`without a key the code was ${lockedBody.code ?? "missing"}, expected ${NO_KEY_CODE}`);
29
+ if (!lockedBody.help?.includes("https://bitbybit.dev/cad-cloud") || !lockedBody.help.includes("https://studio.bitbybit.dev/keys/billing")) problems.push("the no-key answer does not say where to get a key");
30
+ const health = (await (await fetch(`${withoutKey.url}/api/health`)).json()) as { cloud: string };
31
+ if (health.cloud !== "no key") problems.push(`health without a key reports ${health.cloud}`);
32
+ withoutKey.close();
33
+
34
+ const withKey = await serve(fake);
35
+ const unfolded = await fetch(`${withKey.url}/api/unfold`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ stepText: "ISO-10303-21;", fileName: "channel.step", kFactor: 0.4 }) });
36
+ const result = (await unfolded.json()) as { taskId?: string; report?: unknown[]; flatStep?: string; downloads?: unknown[] };
37
+ if (unfolded.status !== 200) problems.push(`with a key the unfold answered ${unfolded.status}: ${JSON.stringify(result)}`);
38
+ if (result.taskId !== "task-1") problems.push("the task id is not passed through");
39
+ if (!Array.isArray(result.report) || result.report.length !== 1) problems.push("the report from the task metadata is not passed through");
40
+ if (result.flatStep !== FLAT_STEP) problems.push("the flat STEP text is not fetched and passed through");
41
+ if (!Array.isArray(result.downloads) || result.downloads.length !== 2) problems.push("the downloads are not passed through");
42
+ const expectedCalls = ["upload channel.step 13", "unfold file-1 k=0.4 step+gltf", "wait task-1", "downloads task-1", "fetch https://example.test/flat.step"];
43
+ if (JSON.stringify(calls) !== JSON.stringify(expectedCalls)) problems.push(`the gateway was called as ${JSON.stringify(calls)}, expected ${JSON.stringify(expectedCalls)}`);
44
+ const rejected = await fetch(`${withKey.url}/api/unfold`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({}) });
45
+ if (rejected.status !== 400) problems.push(`a request without stepText answered ${rejected.status}, expected 400`);
46
+ withKey.close();
47
+
48
+ console.log(JSON.stringify({ template: "sheet-metal-unfold/backend", noKey: { status: locked.status, code: lockedBody.code }, unfold: { status: unfolded.status, calls } }));
49
+ if (problems.length) {
50
+ console.error(`smoke: ${problems.join("; ")}`);
51
+ process.exit(1);
52
+ }
@@ -0,0 +1,65 @@
1
+ import express, { type Express } from "express";
2
+ import type { CloudGateway } from "./cloud.js";
3
+
4
+ export const NO_KEY_CODE = "NO_API_KEY";
5
+ export const CAD_CLOUD_URL = "https://bitbybit.dev/cad-cloud";
6
+ export const STUDIO_KEYS_URL = "https://studio.bitbybit.dev/keys/billing";
7
+ const MAX_STEP_BYTES = "20mb";
8
+
9
+ export interface UnfoldRequest {
10
+ stepText: string;
11
+ fileName?: string;
12
+ kFactor?: number;
13
+ }
14
+
15
+ export function createApp(gateway: CloudGateway | null): Express {
16
+ const app = express();
17
+ app.use(express.json({ limit: MAX_STEP_BYTES }));
18
+
19
+ app.get("/api/health", (_request, response) => {
20
+ response.json({ ok: true, cloud: gateway ? "configured" : "no key" });
21
+ });
22
+
23
+ app.post("/api/unfold", async (request, response) => {
24
+ if (!gateway) {
25
+ response.status(503).json({
26
+ code: NO_KEY_CODE,
27
+ error: "BITBYBIT_API_KEY is not configured, so this backend cannot unfold.",
28
+ help: `The unfold runs on CAD Cloud (${CAD_CLOUD_URL}); create a key in Bitbybit Studio (${STUDIO_KEYS_URL}), put it in backend/.env and restart.`,
29
+ });
30
+ return;
31
+ }
32
+ const body = request.body as Partial<UnfoldRequest> | undefined;
33
+ if (!body || typeof body.stepText !== "string" || body.stepText.length === 0) {
34
+ response.status(400).json({ error: "stepText (the part as STEP text) is required" });
35
+ return;
36
+ }
37
+ try {
38
+ const fileName = body.fileName ?? "part.step";
39
+ const fileId = await gateway.uploadStep(fileName, body.stepText);
40
+ const { taskId } = await gateway.unfoldSolid({
41
+ stepFileId: fileId,
42
+ kFactor: body.kFactor ?? 0.44,
43
+ thicknessOverride: 0,
44
+ outputs: { formats: ["step", "gltf"] },
45
+ });
46
+ const task = await gateway.waitForTask(taskId);
47
+ if (task.status !== "completed") {
48
+ response.status(502).json({ error: `CAD Cloud task ${taskId} ended as ${task.status}: ${JSON.stringify(task.error ?? "")}` });
49
+ return;
50
+ }
51
+ const downloads = await gateway.downloads(taskId);
52
+ const step = downloads.find((download) => download.format === "step" || download.format === "stpz");
53
+ if (!step) {
54
+ response.status(502).json({ error: `CAD Cloud task ${taskId} returned no STEP flat pattern` });
55
+ return;
56
+ }
57
+ const report = (task.metadata as { report?: unknown } | null)?.report ?? [];
58
+ response.json({ taskId, report, flatStep: await gateway.fetchText(step.downloadUrl), downloads });
59
+ } catch (error) {
60
+ response.status(500).json({ error: error instanceof Error ? error.message : String(error) });
61
+ }
62
+ });
63
+
64
+ return app;
65
+ }
@@ -0,0 +1,42 @@
1
+ import { BitbybitClient, unwrap, type TaskDetail, type TaskDownload } from "@bitbybit-dev/cad-cloud-sdk";
2
+
3
+ export interface UnfoldSolidBody {
4
+ stepFileId: string;
5
+ kFactor: number;
6
+ thicknessOverride: number;
7
+ outputs: { formats: ("step" | "gltf")[] };
8
+ }
9
+
10
+ export interface CloudGateway {
11
+ uploadStep(fileName: string, stepText: string): Promise<string>;
12
+ unfoldSolid(body: UnfoldSolidBody): Promise<{ taskId: string }>;
13
+ waitForTask(taskId: string): Promise<Pick<TaskDetail, "status" | "metadata" | "error">>;
14
+ downloads(taskId: string): Promise<TaskDownload[]>;
15
+ fetchText(url: string): Promise<string>;
16
+ }
17
+
18
+ export const UNFOLD_SOLID_PATH = "/api/v1/cad/pro/unfold/solid";
19
+
20
+ export function sdkGateway(apiKey: string, baseUrl: string): CloudGateway {
21
+ const client = new BitbybitClient({ apiKey, baseUrl });
22
+ return {
23
+ async uploadStep(fileName, stepText) {
24
+ const confirmed = await client.files.uploadBytes(fileName, new TextEncoder().encode(stepText), "application/step");
25
+ return confirmed.fileId;
26
+ },
27
+ async unfoldSolid(body) {
28
+ return unwrap<{ taskId: string }>(await client.request("POST", UNFOLD_SOLID_PATH, body));
29
+ },
30
+ async waitForTask(taskId) {
31
+ return client.tasks.poll(taskId, { intervalMs: 1500, maxAttempts: 200 });
32
+ },
33
+ async downloads(taskId) {
34
+ return client.tasks.getResults(taskId);
35
+ },
36
+ async fetchText(url) {
37
+ const response = await fetch(url);
38
+ if (!response.ok) throw new Error(`downloading the flat pattern failed: HTTP ${response.status}`);
39
+ return response.text();
40
+ },
41
+ };
42
+ }
@@ -0,0 +1,13 @@
1
+ import { createApp } from "./app.js";
2
+ import { sdkGateway } from "./cloud.js";
3
+
4
+ const apiKey = process.env["BITBYBIT_API_KEY"] ?? "";
5
+ const baseUrl = process.env["BITBYBIT_API_URL"] ?? "https://api.bitbybit.dev";
6
+ const port = Number(process.env["PORT"] ?? 3000);
7
+
8
+ const gateway = apiKey ? sdkGateway(apiKey, baseUrl) : null;
9
+ if (!gateway) console.warn("BITBYBIT_API_KEY is empty: the part builds in the browser, the unfold will answer 503 until a key is in backend/.env");
10
+
11
+ createApp(gateway).listen(port, () => {
12
+ console.log(`sheet-metal unfold backend on http://localhost:${port} (${gateway ? "CAD Cloud configured" : "no key"})`);
13
+ });
@@ -0,0 +1,9 @@
1
+ {
2
+ "extends": "./tsconfig.json",
3
+ "compilerOptions": {
4
+ "noEmit": false,
5
+ "rootDir": "src",
6
+ "outDir": "dist"
7
+ },
8
+ "include": ["src"]
9
+ }
@@ -0,0 +1,27 @@
1
+ {
2
+ "compilerOptions": {
3
+ "target": "ES2022",
4
+ "module": "NodeNext",
5
+ "moduleResolution": "NodeNext",
6
+ "lib": ["ES2022"],
7
+ "types": ["node"],
8
+ "noEmit": true,
9
+ "strict": true,
10
+ "noUncheckedIndexedAccess": true,
11
+ "exactOptionalPropertyTypes": true,
12
+ "noImplicitReturns": true,
13
+ "noImplicitOverride": true,
14
+ "noPropertyAccessFromIndexSignature": true,
15
+ "noFallthroughCasesInSwitch": true,
16
+ "noUnusedLocals": true,
17
+ "noUnusedParameters": true,
18
+ "useUnknownInCatchVariables": true,
19
+ "forceConsistentCasingInFileNames": true,
20
+ "isolatedModules": true,
21
+ "verbatimModuleSyntax": true,
22
+ "erasableSyntaxOnly": true,
23
+ "noUncheckedSideEffectImports": true,
24
+ "skipLibCheck": true
25
+ },
26
+ "include": ["src", "scripts"]
27
+ }
@@ -0,0 +1,47 @@
1
+ import { defineConfig, globalIgnores } from "eslint/config";
2
+ import eslint from "@eslint/js";
3
+ import tseslint from "typescript-eslint";
4
+ import noComments from "eslint-plugin-no-comments";
5
+
6
+ const DOUBLE_ASSERTION = ":matches(TSAsExpression, TSTypeAssertion) > :matches(TSAsExpression, TSTypeAssertion).expression[typeAnnotation.type=/^TS(Unknown|Any)Keyword$/]";
7
+
8
+ export default defineConfig([
9
+ globalIgnores(["dist/", "node_modules/", "**/*.d.ts"]),
10
+ {
11
+ files: ["**/*.ts"],
12
+ extends: [eslint.configs.recommended, tseslint.configs.strictTypeChecked, tseslint.configs.stylisticTypeChecked],
13
+ plugins: { "no-comments": noComments },
14
+ languageOptions: { parserOptions: { projectService: true, tsconfigRootDir: import.meta.dirname } },
15
+ rules: {
16
+ quotes: ["error", "double", { avoidEscape: true, allowTemplateLiterals: true }],
17
+ semi: ["error", "always"],
18
+ eqeqeq: ["error", "always"],
19
+ curly: ["error", "multi-line"],
20
+ "prefer-const": "error",
21
+ "no-var": "error",
22
+ "max-lines": ["error", { max: 600, skipBlankLines: true, skipComments: true }],
23
+ "no-warning-comments": ["error", { terms: ["todo", "fixme", "hack"], location: "anywhere" }],
24
+ "no-comments/disallowComments": ["error", { allow: ["global", "eslint", "/ <reference"] }],
25
+ "no-restricted-syntax": ["error", { selector: DOUBLE_ASSERTION, message: "A double assertion replaces a type instead of narrowing it: write a type predicate, constrain a generic to the union, or fix the type this is arguing with." }],
26
+ "@typescript-eslint/no-unused-vars": ["error", { argsIgnorePattern: "^_", varsIgnorePattern: "^_", caughtErrorsIgnorePattern: "^_", ignoreRestSiblings: true }],
27
+ "@typescript-eslint/no-explicit-any": "error",
28
+ "@typescript-eslint/no-non-null-assertion": "error",
29
+ "@typescript-eslint/explicit-function-return-type": ["error", { allowExpressions: true, allowTypedFunctionExpressions: true, allowHigherOrderFunctions: true, allowDirectConstAssertionInArrowFunctions: true }],
30
+ "@typescript-eslint/consistent-type-imports": ["error", { prefer: "type-imports", fixStyle: "separate-type-imports", disallowTypeAnnotations: false }],
31
+ "@typescript-eslint/restrict-template-expressions": ["error", { allowNumber: true, allowBoolean: true, allowNullish: false, allowRegExp: false }],
32
+ "@typescript-eslint/naming-convention": [
33
+ "error",
34
+ { selector: "default", format: ["camelCase"], leadingUnderscore: "allow" },
35
+ { selector: "variable", format: ["camelCase", "UPPER_CASE"], leadingUnderscore: "allow" },
36
+ { selector: "parameter", format: ["camelCase"], leadingUnderscore: "allow" },
37
+ { selector: "typeLike", format: ["PascalCase"] },
38
+ { selector: "property", format: null },
39
+ { selector: "method", format: ["camelCase"] },
40
+ { selector: "import", format: null },
41
+ ],
42
+ "@typescript-eslint/only-throw-error": "error",
43
+ "@typescript-eslint/unbound-method": ["error", { ignoreStatic: true }],
44
+ "@typescript-eslint/non-nullable-type-assertion-style": "off",
45
+ },
46
+ },
47
+ ]);
@@ -0,0 +1,17 @@
1
+ <!DOCTYPE html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="UTF-8" />
5
+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />
6
+ <link rel="icon" href="/favicon.ico" sizes="48x48" />
7
+ <link rel="icon" type="image/png" href="/logo.png" sizes="150x150" />
8
+ <link rel="apple-touch-icon" href="/logo.png" />
9
+ <title>Sheet-metal unfold</title>
10
+ </head>
11
+ <body>
12
+ <canvas id="three-canvas"></canvas>
13
+ <aside id="panel" aria-label="Configure the part"></aside>
14
+ <a class="credit" href="https://bitbybit.dev" target="_blank" rel="noopener noreferrer"><img src="/logo.png" alt="" />geometry by bitbybit.dev</a>
15
+ <script type="module" src="/src/main.ts"></script>
16
+ </body>
17
+ </html>
@@ -0,0 +1,30 @@
1
+ {
2
+ "name": "bitbybit-sheet-metal-unfold-frontend",
3
+ "private": true,
4
+ "version": "0.0.0",
5
+ "type": "module",
6
+ "scripts": {
7
+ "dev": "vite",
8
+ "build": "npm run typecheck && vite build",
9
+ "preview": "vite preview",
10
+ "smoke": "npm run typecheck && npm run lint && tsx scripts/smoke.ts",
11
+ "typecheck": "tsc --noEmit",
12
+ "lint": "eslint . --max-warnings 0"
13
+ },
14
+ "dependencies": {
15
+ "@bitbybit-dev/threejs": "1.4.0",
16
+ "three": "0.186.0"
17
+ },
18
+ "devDependencies": {
19
+ "@bitbybit-dev/occt": "1.4.0",
20
+ "@eslint/js": "10.0.1",
21
+ "@types/node": "22.20.1",
22
+ "@types/three": "0.186.0",
23
+ "eslint": "10.10.0",
24
+ "eslint-plugin-no-comments": "1.2.1",
25
+ "tsx": "^4.19.0",
26
+ "typescript": "5.9.3",
27
+ "typescript-eslint": "8.70.0",
28
+ "vite": "^6.3.2"
29
+ }
30
+ }
@@ -0,0 +1,84 @@
1
+ import { createRequire } from "node:module";
2
+ import { readdirSync } from "node:fs";
3
+ import { dirname, join } from "node:path";
4
+ import initOpenCascade from "@bitbybit-dev/occt/bitbybit-dev-occt/index.js";
5
+ import { OCCTService, OccHelper, VectorHelperService, ShapesHelperService } from "@bitbybit-dev/occt";
6
+ import { buildModel, clampParams, defaultParams, flatLengthEstimate, profileArea, removedVolume, type Occt, type PartParams } from "../src/model.ts";
7
+ import { bendLines, summarize, toScene, type UnfoldSolidReport } from "../src/flat.ts";
8
+ import { accessFromResponse, NO_KEY_CODE } from "../src/cloud-access.ts";
9
+
10
+ interface PartCheck {
11
+ valid: boolean;
12
+ faces: number;
13
+ volume: number;
14
+ holes: number;
15
+ slots: number;
16
+ bends: number;
17
+ flatEstimate: number;
18
+ }
19
+
20
+ function inProcess(service: object): Occt {
21
+ return service as Occt;
22
+ }
23
+
24
+ const require = createRequire(import.meta.url);
25
+ const kernelDir = dirname(require.resolve("@bitbybit-dev/occt/bitbybit-dev-occt/index.js"));
26
+ const wasmFile = readdirSync(kernelDir).find((file) => file.endsWith(".wasm"));
27
+ if (!wasmFile) throw new Error(`no OCCT kernel (.wasm) found in ${kernelDir}`);
28
+ const occ = await initOpenCascade({ locateFile: (file: string) => (file.endsWith(".wasm") ? join(kernelDir, wasmFile) : file) });
29
+ const occt = inProcess(new OCCTService(occ, new OccHelper(new VectorHelperService(), new ShapesHelperService(), occ)));
30
+
31
+ const round = (n: number): number => Math.round(n * 1000) / 1000;
32
+ const spans = (box: number[], expected: [number, number, number]): boolean => expected.every((value, i) => Math.abs((box[i] ?? Number.NaN) - value) < 0.001);
33
+ const problems: string[] = [];
34
+
35
+ async function check(name: string, params: PartParams): Promise<PartCheck> {
36
+ const p = clampParams(params);
37
+ const model = await buildModel(occt, params);
38
+ const info = await occt.shapes.solid.debugInfo({ shape: model.shape });
39
+ const bbox = await occt.operations.boundingBoxOfShape({ shape: model.shape });
40
+ const expectedVolume = profileArea(p) * p.depth - removedVolume(p);
41
+ const estimate = flatLengthEstimate(p);
42
+ const expectedMin: [number, number, number] = [-p.baseWidth / 2, 0, -p.depth / 2];
43
+ const expectedMax: [number, number, number] = [p.baseWidth / 2, p.flangeHeight, p.depth / 2];
44
+ const within = spans(bbox.min, expectedMin) && spans(bbox.max, expectedMax);
45
+ if (!info.valid) problems.push(`${name}: the part is not a valid solid`);
46
+ if (Math.abs(model.volume - expectedVolume) > expectedVolume * 1e-4) problems.push(`${name}: volume ${round(model.volume)} is not the thickness times the rounded centre line times the depth minus the mounting features (${round(expectedVolume)}); the sheet is not one thickness along its bends or a feature sits in a bend`);
47
+ if (!within) problems.push(`${name}: the part spans ${JSON.stringify([bbox.min.map(round), bbox.max.map(round)])}, expected ${JSON.stringify([expectedMin, expectedMax])}`);
48
+ if (!(estimate.total > 0 && estimate.total < estimate.outerLengths)) problems.push(`${name}: the flat length estimate ${round(estimate.total)} is not below the outer lengths ${round(estimate.outerLengths)}`);
49
+ return { valid: info.valid, faces: info.nbFaces, volume: round(model.volume), holes: model.mounting.baseHoles.length, slots: model.mounting.flangeSlots.length, bends: estimate.bends, flatEstimate: round(estimate.total) };
50
+ }
51
+
52
+ const report: UnfoldSolidReport[] = [
53
+ { solidIndex: 0, ok: true, thickness: 2, kFactor: 0.44, flatBBox: [0, 0, 150.2, 60], flatArea: 9012, bends: [
54
+ { angleDeg: 90, innerRadius: 2, allowance: 4.52, bendDeduction: 3.48, bendLineLength: 60, lineStart: [30, 0, 0], lineEnd: [30, 60, 0], direction: "up" },
55
+ { angleDeg: 90, innerRadius: 2, allowance: 4.52, bendDeduction: 3.48, bendLineLength: 60, lineStart: [120.2, 0, 0], lineEnd: [120.2, 60, 0], direction: "up" },
56
+ ] },
57
+ { solidIndex: 1, ok: false, error: "no constant thickness found" },
58
+ ];
59
+ const lines = bendLines(report);
60
+ const summary = summarize(report);
61
+ if (lines.length !== 2) problems.push(`${lines.length} bend lines from a report with two bends`);
62
+ if (JSON.stringify(toScene([1, 2, 3])) !== JSON.stringify([1, 3, -2])) problems.push("the flat frame is not mapped onto the ground plane");
63
+ if (summary.unfolded !== 1 || summary.bends !== 2 || summary.problems.length !== 1 || round(summary.developedLength ?? 0) !== 150.2) problems.push(`the summary is ${JSON.stringify(summary)}`);
64
+
65
+ const locked = accessFromResponse(503, { code: NO_KEY_CODE, error: "no key" });
66
+ const ready = accessFromResponse(200, { taskId: "t" });
67
+ const down = accessFromResponse(0, null);
68
+ if (locked.state !== "locked") problems.push(`a 503 with ${NO_KEY_CODE} is ${locked.state}, expected locked`);
69
+ if (ready.state !== "ready") problems.push(`a 200 is ${ready.state}, expected ready`);
70
+ if (down.state !== "unreachable") problems.push(`no answer is ${down.state}, expected unreachable`);
71
+
72
+ console.log(JSON.stringify({
73
+ template: "sheet-metal-unfold/frontend",
74
+ params: defaultParams,
75
+ default: await check("default", defaultParams),
76
+ noLip: await check("noLip", { ...defaultParams, lipHeight: 0 }),
77
+ thick: await check("thick", { ...defaultParams, thickness: 4, bendRadius: 6, flangeHeight: 80 }),
78
+ cloud: { bendLines: lines.length, summary, access: { locked: locked.state, ready: ready.state, backendDown: down.state } },
79
+ }));
80
+
81
+ if (problems.length) {
82
+ console.error(`smoke: ${problems.join("; ")}`);
83
+ process.exit(1);
84
+ }