@bitbybit-dev/create-app 1.0.0-rc.2 → 1.0.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 (48) hide show
  1. package/README.md +19 -5
  2. package/dist/index.js +478 -32
  3. package/dist/index.js.map +1 -1
  4. package/package.json +1 -1
  5. package/templates/cloud/backends/dotnet-rest/BitbybitClient.cs +371 -0
  6. package/templates/cloud/backends/dotnet-rest/Program.cs +147 -0
  7. package/templates/cloud/backends/dotnet-rest/Properties/launchSettings.json +14 -0
  8. package/templates/cloud/backends/dotnet-rest/appsettings.json +13 -0
  9. package/templates/cloud/backends/dotnet-rest/dotnet-rest.csproj +10 -0
  10. package/templates/cloud/backends/hono-rest/package.json +19 -0
  11. package/templates/cloud/backends/hono-rest/src/bitbybit-client.ts +387 -0
  12. package/templates/cloud/backends/hono-rest/src/index.ts +128 -0
  13. package/templates/cloud/backends/hono-rest/src/types.ts +4 -0
  14. package/templates/cloud/backends/hono-rest/tsconfig.json +16 -0
  15. package/templates/cloud/backends/hono-rest/wrangler.jsonc +11 -0
  16. package/templates/cloud/backends/hono-sdk/package.json +19 -0
  17. package/templates/cloud/backends/hono-sdk/src/bitbybit-client.ts +239 -0
  18. package/templates/cloud/backends/hono-sdk/src/index.ts +155 -0
  19. package/templates/cloud/backends/hono-sdk/src/types.ts +4 -0
  20. package/templates/cloud/backends/hono-sdk/tsconfig.json +16 -0
  21. package/templates/cloud/backends/hono-sdk/wrangler.jsonc +11 -0
  22. package/templates/cloud/backends/nodejs-rest/.env.example +3 -0
  23. package/templates/cloud/backends/nodejs-rest/package.json +22 -0
  24. package/templates/cloud/backends/nodejs-rest/src/bitbybit-client.ts +387 -0
  25. package/templates/cloud/backends/nodejs-rest/src/index.ts +143 -0
  26. package/templates/cloud/backends/nodejs-rest/src/types.ts +4 -0
  27. package/templates/cloud/backends/nodejs-rest/tsconfig.json +17 -0
  28. package/templates/cloud/backends/nodejs-sdk/.env.example +3 -0
  29. package/templates/cloud/backends/nodejs-sdk/package.json +23 -0
  30. package/templates/cloud/backends/nodejs-sdk/src/bitbybit-client.ts +235 -0
  31. package/templates/cloud/backends/nodejs-sdk/src/index.ts +161 -0
  32. package/templates/cloud/backends/nodejs-sdk/tsconfig.json +17 -0
  33. package/templates/cloud/frontend/index.html +13 -0
  34. package/templates/cloud/frontend/package.json +24 -0
  35. package/templates/cloud/frontend/src/App.tsx +42 -0
  36. package/templates/cloud/frontend/src/components/ApiKeyWarning.tsx +41 -0
  37. package/templates/cloud/frontend/src/components/Header.tsx +8 -0
  38. package/templates/cloud/frontend/src/components/Tabs.tsx +25 -0
  39. package/templates/cloud/frontend/src/components/Viewer.tsx +155 -0
  40. package/templates/cloud/frontend/src/main.tsx +10 -0
  41. package/templates/cloud/frontend/src/panels/ModelsPanel.tsx +134 -0
  42. package/templates/cloud/frontend/src/panels/PipelinesPanel.tsx +213 -0
  43. package/templates/cloud/frontend/src/styles.css +320 -0
  44. package/templates/cloud/frontend/tsconfig.json +17 -0
  45. package/templates/cloud/frontend/vite.config.ts +15 -0
  46. package/templates/vite/babylonjs/typescript/package.json +1 -1
  47. package/templates/vite/playcanvas/typescript/package.json +1 -1
  48. package/templates/vite/threejs/typescript/package.json +1 -1
@@ -0,0 +1,387 @@
1
+ import type { Env } from "./types.js";
2
+
3
+ const POLL_INTERVAL_MS = 2_000;
4
+ const MAX_POLL_ATTEMPTS = 120; // 4 minutes max
5
+
6
+ interface TaskResponse {
7
+ ok: boolean;
8
+ data?: {
9
+ taskId: string;
10
+ status: string;
11
+ statusUrl?: string;
12
+ resultParts?: Record<string, unknown> | null;
13
+ error?: string | null;
14
+ };
15
+ error?: { code: string; message: string };
16
+ }
17
+
18
+ interface SubTaskSummary {
19
+ taskId: string;
20
+ index: number;
21
+ status: string;
22
+ }
23
+
24
+ interface CompoundTaskResponse {
25
+ ok: boolean;
26
+ data?: {
27
+ taskId: string;
28
+ kind: string;
29
+ subTaskCount: number;
30
+ statusUrl: string;
31
+ subTasks: SubTaskSummary[];
32
+ };
33
+ error?: { code: string; message: string };
34
+ }
35
+
36
+ interface ResultResponse {
37
+ ok: boolean;
38
+ data?: { downloadUrl: string; filename: string };
39
+ error?: { code: string; message: string };
40
+ }
41
+
42
+ async function apiRequest(env: Env, method: string, path: string, body?: unknown): Promise<Response> {
43
+ const url = `${env.BITBYBIT_API_URL}${path}`;
44
+ const headers: Record<string, string> = {
45
+ "x-api-key": env.BITBYBIT_API_KEY,
46
+ };
47
+ if (body != null) {
48
+ headers["Content-Type"] = "application/json";
49
+ }
50
+
51
+ return fetch(url, {
52
+ method,
53
+ headers,
54
+ body: body ? JSON.stringify(body) : undefined,
55
+ });
56
+ }
57
+
58
+ export async function createDragonCup(env: Env): Promise<{ taskId: string; downloads: { format: string; downloadUrl: string; filename: string }[] }> {
59
+ // 1. Create dragon cup model — returns 202 with taskId
60
+ const createRes = await apiRequest(env, "POST", "/api/v1/models/dragon-cup", {
61
+ params: {
62
+ height: 8,
63
+ radiusBottom: 4,
64
+ radiusTopOffset: 2,
65
+ radiusMidOffset: 2,
66
+ rotationTopAngle: 20,
67
+ rotationMidAngle: 20,
68
+ nrSkinCellsVertical: 5,
69
+ nrSkinCellsHorizontal: 10,
70
+ thickness: 0.6,
71
+ bottomThickness: 1,
72
+ scale: 1,
73
+ origin: [0, 0, 0],
74
+ direction: [0, 1, 0],
75
+ },
76
+ outputs: {
77
+ formats: ["gltf"],
78
+ },
79
+ });
80
+
81
+ if (!createRes.ok && createRes.status !== 202) {
82
+ const err = await createRes.text();
83
+ throw new Error(`Failed to create dragon cup: ${createRes.status} ${err}`);
84
+ }
85
+
86
+ const createData: TaskResponse = await createRes.json() as TaskResponse;
87
+ if (!createData.ok || !createData.data?.taskId) {
88
+ throw new Error(`API error: ${createData.error?.message ?? "unknown"}`);
89
+ }
90
+
91
+ const { taskId } = createData.data;
92
+ const downloads = await pollAndGetResult(env, taskId);
93
+ return { taskId, downloads };
94
+ }
95
+
96
+ export async function createDragonCupBatch(
97
+ env: Env,
98
+ ): Promise<{ taskId: string; downloadUrls: string[] }> {
99
+ const createRes = await apiRequest(env, "POST", "/api/v1/models/dragon-cup/batch", {
100
+ items: [
101
+ {
102
+ params: {
103
+ height: 4, radiusBottom: 4, radiusTopOffset: 2, radiusMidOffset: 2,
104
+ rotationTopAngle: 20, rotationMidAngle: 20,
105
+ nrSkinCellsVertical: 2, nrSkinCellsHorizontal: 6,
106
+ nrSkinCellDivisionsTop: 2, nrSkinCellDivisionsBottom: 3,
107
+ skinCellOuterHeight: 1, skinCellInnerHeight: 0.3,
108
+ skinCellBottomHeight: 1, skinCellTopHeight: 1,
109
+ thickness: 2,
110
+ },
111
+ },
112
+ {
113
+ params: {
114
+ height: 7, radiusBottom: 4, radiusTopOffset: 2, radiusMidOffset: 2,
115
+ rotationTopAngle: 20, rotationMidAngle: 20,
116
+ nrSkinCellsVertical: 1, nrSkinCellsHorizontal: 12,
117
+ nrSkinCellDivisionsTop: 1, nrSkinCellDivisionsBottom: 1,
118
+ skinCellOuterHeight: 2, skinCellInnerHeight: 1,
119
+ skinCellBottomHeight: 1, skinCellTopHeight: 1,
120
+ thickness: 0.5,
121
+ },
122
+ },
123
+ {
124
+ params: {
125
+ height: 9, radiusBottom: 2, radiusTopOffset: 1, radiusMidOffset: 1,
126
+ rotationTopAngle: -30, rotationMidAngle: -30,
127
+ nrSkinCellsVertical: 1, nrSkinCellsHorizontal: 5,
128
+ nrSkinCellDivisionsTop: 1, nrSkinCellDivisionsBottom: 1,
129
+ skinCellOuterHeight: 4, skinCellInnerHeight: -0.3,
130
+ skinCellBottomHeight: 0.5, skinCellTopHeight: 0.3,
131
+ thickness: 0.5,
132
+ },
133
+ },
134
+ ],
135
+ outputs: { formats: ["gltf"] },
136
+ });
137
+
138
+ if (!createRes.ok && createRes.status !== 202) {
139
+ const err = await createRes.text();
140
+ throw new Error(`Failed to create batch: ${createRes.status} ${err}`);
141
+ }
142
+
143
+ const createData: CompoundTaskResponse = await createRes.json() as CompoundTaskResponse;
144
+ if (!createData.ok || !createData.data?.taskId) {
145
+ throw new Error(`API error: ${createData.error?.message ?? "unknown"}`);
146
+ }
147
+
148
+ const { taskId, subTasks } = createData.data;
149
+
150
+ // Poll compound task until all sub-tasks complete
151
+ await pollUntilDone(env, taskId);
152
+
153
+ // Fetch each sub-task result
154
+ const downloadUrls: string[] = [];
155
+ for (const sub of subTasks) {
156
+ const resultRes = await apiRequest(env, "GET", `/api/v1/tasks/${sub.taskId}/result/glb`);
157
+ const resultData: ResultResponse = await resultRes.json() as ResultResponse;
158
+ if (!resultData.ok || !resultData.data?.downloadUrl) {
159
+ throw new Error(`Sub-task ${sub.index} result error: ${resultData.error?.message ?? "no download URL"}`);
160
+ }
161
+ downloadUrls.push(resultData.data.downloadUrl);
162
+ }
163
+
164
+ return { taskId, downloadUrls };
165
+ }
166
+
167
+ export async function getTaskResult(env: Env, taskId: string): Promise<{ status: string; downloads?: { format: string; downloadUrl: string; filename: string }[] }> {
168
+ const statusRes = await apiRequest(env, "GET", `/api/v1/tasks/${taskId}`);
169
+ const statusData: TaskResponse = await statusRes.json() as TaskResponse;
170
+
171
+ if (!statusData.ok || !statusData.data) {
172
+ throw new Error(`Task error: ${statusData.error?.message ?? "unknown"}`);
173
+ }
174
+
175
+ const { status } = statusData.data;
176
+
177
+ if (status === "failed" || status === "cancelled" || status === "expired") {
178
+ throw new Error(`Task ${status}: ${statusData.data.error ?? "no details"}`);
179
+ }
180
+
181
+ if (status !== "completed") {
182
+ return { status };
183
+ }
184
+
185
+ const resultRes = await apiRequest(env, "GET", `/api/v1/tasks/${taskId}/results`);
186
+ const resultData = await resultRes.json() as { ok: boolean; data?: { downloads: { format: string; downloadUrl: string; filename: string }[] }; error?: { message: string } };
187
+
188
+ if (!resultData.ok || !resultData.data?.downloads) {
189
+ throw new Error(`Result error: ${resultData.error?.message ?? "no downloads"}`);
190
+ }
191
+
192
+ return { status: "completed", downloads: resultData.data.downloads };
193
+ }
194
+
195
+ async function pollUntilDone(env: Env, taskId: string): Promise<void> {
196
+ for (let attempt = 0; attempt < MAX_POLL_ATTEMPTS; attempt++) {
197
+ await sleep(POLL_INTERVAL_MS);
198
+
199
+ const statusRes = await apiRequest(env, "GET", `/api/v1/tasks/${taskId}`);
200
+ const statusData: TaskResponse = await statusRes.json() as TaskResponse;
201
+
202
+ if (!statusData.ok || !statusData.data) {
203
+ throw new Error(`Task poll error: ${statusData.error?.message ?? "unknown"}`);
204
+ }
205
+
206
+ const { status } = statusData.data;
207
+
208
+ if (status === "completed") {
209
+ return;
210
+ }
211
+ if (status === "failed" || status === "cancelled" || status === "expired") {
212
+ throw new Error(`Task ${status}: ${statusData.data.error ?? "no details"}`);
213
+ }
214
+ }
215
+ throw new Error("Polling timed out");
216
+ }
217
+
218
+ async function pollAndGetResult(env: Env, taskId: string): Promise<{ format: string; downloadUrl: string; filename: string }[]> {
219
+ await pollUntilDone(env, taskId);
220
+
221
+ const resultRes = await apiRequest(env, "GET", `/api/v1/tasks/${taskId}/results`);
222
+ const resultData = await resultRes.json() as { ok: boolean; data?: { downloads: { format: string; downloadUrl: string; filename: string }[] }; error?: { message: string } };
223
+
224
+ if (!resultData.ok || !resultData.data?.downloads) {
225
+ throw new Error(`Result error: ${resultData.error?.message ?? "no downloads"}`);
226
+ }
227
+
228
+ return resultData.data.downloads;
229
+ }
230
+
231
+ // ---------------------------------------------------------------------------
232
+ // Pipeline examples
233
+ // ---------------------------------------------------------------------------
234
+
235
+ async function submitPipeline(env: Env, body: unknown): Promise<{ taskId: string; downloads: { format: string; downloadUrl: string; filename: string }[] }> {
236
+ const createRes = await apiRequest(env, "POST", "/api/v1/cad/pipeline", body);
237
+ if (!createRes.ok && createRes.status !== 202) {
238
+ const err = await createRes.text();
239
+ throw new Error(`Pipeline failed: ${createRes.status} ${err}`);
240
+ }
241
+
242
+ const createData: TaskResponse = await createRes.json() as TaskResponse;
243
+ if (!createData.ok || !createData.data?.taskId) {
244
+ throw new Error(`API error: ${createData.error?.message ?? "unknown"}`);
245
+ }
246
+
247
+ const { taskId } = createData.data;
248
+ const downloads = await pollAndGetResult(env, taskId);
249
+ return { taskId, downloads };
250
+ }
251
+
252
+ /**
253
+ * Translate, Union + Fillet: createBox → translate → union → fillet
254
+ */
255
+ export async function runTranslateUnionFilletPipeline(env: Env): Promise<{ taskId: string; downloads: { format: string; downloadUrl: string; filename: string }[] }> {
256
+ return submitPipeline(env, {
257
+ steps: [
258
+ { operation: "occt.shapes.solid.createBox", params: { width: 8, length: 6, height: 4, center: [0, 0, 0] } },
259
+ { operation: "occt.transforms.translate", params: { shape: "$ref:0", translation: [4, 2, 3] } },
260
+ { operation: "occt.booleans.union", params: { shapes: ["$ref:0", "$ref:1"] } },
261
+ { operation: "occt.fillets.filletEdges", params: { shape: "$ref:2", radius: 0.5 } },
262
+ ],
263
+ outputs: { formats: ["stpz", "gltf"] },
264
+ });
265
+ }
266
+
267
+ /**
268
+ * Map: Cylinders at Positions
269
+ */
270
+ export async function runMapCylindersPipeline(env: Env): Promise<{ taskId: string; downloads: { format: string; downloadUrl: string; filename: string }[] }> {
271
+ return submitPipeline(env, {
272
+ steps: [
273
+ { operation: "json.parse", params: { text: "[[0,0,0],[1.5,0,0],[3,0,0],[4.5,0,0]]" } },
274
+ {
275
+ type: "map",
276
+ items: "$ref:0",
277
+ steps: [{ operation: "occt.shapes.solid.createCylinder", params: { radius: 1, height: 5, center: "$item" } }],
278
+ },
279
+ { operation: "occt.booleans.union", params: { shapes: "$ref:5" } },
280
+ ],
281
+ outputs: { formats: ["stpz", "gltf"] },
282
+ });
283
+ }
284
+
285
+ /**
286
+ * Map: Spheres at Different Radii
287
+ */
288
+ export async function runMapSpheresPipeline(env: Env): Promise<{ taskId: string; downloads: { format: string; downloadUrl: string; filename: string }[] }> {
289
+ return submitPipeline(env, {
290
+ steps: [
291
+ { operation: "json.parse", params: { text: "[[0,0,0],[4,0,0],[10,0,0],[18,0,0],[28,0,0]]" } },
292
+ {
293
+ type: "map",
294
+ items: "$ref:0",
295
+ steps: [
296
+ { operation: "math.twoNrOperation", params: { first: "$index", second: 1, operation: "add" } },
297
+ { operation: "occt.shapes.solid.createSphere", params: { radius: "$prev", center: "$item" } },
298
+ ],
299
+ },
300
+ { operation: "occt.shapes.compound.makeCompound", params: { shapes: "$ref:11" } },
301
+ ],
302
+ outputs: { formats: ["stpz", "gltf"] },
303
+ });
304
+ }
305
+
306
+ /**
307
+ * Choice: Conditional Shape Size
308
+ */
309
+ export async function runChoicePipeline(env: Env): Promise<{ taskId: string; downloads: { format: string; downloadUrl: string; filename: string }[] }> {
310
+ return submitPipeline(env, {
311
+ steps: [
312
+ { operation: "json.parse", params: { text: "10" } },
313
+ { operation: "math.twoNrOperation", params: { first: "$ref:0", second: 1, operation: "add" } },
314
+ {
315
+ type: "choice",
316
+ value: "$ref:1",
317
+ operator: "gt",
318
+ compareTo: 5,
319
+ then: [{ operation: "occt.shapes.solid.createBox", params: { width: 10, length: 10, height: 10, center: [0, 0, 0] } }],
320
+ else: [{ operation: "occt.shapes.solid.createSphere", params: { radius: 2, center: [0, 0, 0] } }],
321
+ },
322
+ ],
323
+ outputs: { formats: ["stpz", "gltf"] },
324
+ });
325
+ }
326
+
327
+ /**
328
+ * File-input pipeline: upload a STEP file, fillet all edges, export.
329
+ */
330
+ export async function runFileInputPipeline(env: Env, fileId: string): Promise<{ taskId: string; downloads: { format: string; downloadUrl: string; filename: string }[] }> {
331
+ return submitPipeline(env, {
332
+ steps: [
333
+ { operation: "occt.io.loadSTEPorIGES", params: { filetext: "$file:0", fileName: "shape.step", adjustZtoY: true } },
334
+ { operation: "occt.fillets.filletEdges", params: { shape: "$ref:0", radius: 0.1 } },
335
+ ],
336
+ inputFiles: [{ fileId, role: "input" }],
337
+ outputs: { formats: ["stpz", "gltf"], meshPrecision: 0.001 },
338
+ });
339
+ }
340
+
341
+ /**
342
+ * Upload a file to the Bitbybit API, returns a fileId for use in pipelines.
343
+ */
344
+ export async function uploadFile(env: Env, fileBuffer: ArrayBuffer, filename: string): Promise<string> {
345
+ // 1. Request a pre-signed upload URL
346
+ const uploadRes = await apiRequest(env, "POST", "/api/v1/files/upload", {
347
+ filename,
348
+ contentType: "application/octet-stream",
349
+ bytes: fileBuffer.byteLength,
350
+ });
351
+
352
+ if (!uploadRes.ok) {
353
+ const err = await uploadRes.text();
354
+ throw new Error(`File upload request failed: ${uploadRes.status} ${err}`);
355
+ }
356
+
357
+ const uploadData = await uploadRes.json() as { ok: boolean; data?: { fileId: string; uploadUrl: string }; error?: { message: string } };
358
+ if (!uploadData.ok || !uploadData.data?.uploadUrl) {
359
+ throw new Error(`Upload error: ${uploadData.error?.message ?? "no uploadUrl"}`);
360
+ }
361
+
362
+ const { fileId, uploadUrl } = uploadData.data;
363
+
364
+ // 2. PUT raw bytes to the pre-signed URL
365
+ const putRes = await fetch(uploadUrl, {
366
+ method: "PUT",
367
+ headers: { "Content-Type": "application/octet-stream" },
368
+ body: fileBuffer,
369
+ });
370
+
371
+ if (!putRes.ok) {
372
+ throw new Error(`PUT to upload URL failed: ${putRes.status} ${putRes.statusText}`);
373
+ }
374
+
375
+ // 3. Confirm the upload
376
+ const confirmRes = await apiRequest(env, "POST", `/api/v1/files/${encodeURIComponent(fileId)}/confirm`);
377
+ if (!confirmRes.ok) {
378
+ const err = await confirmRes.text();
379
+ throw new Error(`File confirm failed: ${confirmRes.status} ${err}`);
380
+ }
381
+
382
+ return fileId;
383
+ }
384
+
385
+ function sleep(ms: number): Promise<void> {
386
+ return new Promise((resolve) => setTimeout(resolve, ms));
387
+ }
@@ -0,0 +1,143 @@
1
+ import express from "express";
2
+ import multer from "multer";
3
+ import type { Env } from "./types.js";
4
+ import { createDragonCup, createDragonCupBatch, getTaskResult, runTranslateUnionFilletPipeline, runMapCylindersPipeline, runMapSpheresPipeline, runChoicePipeline, runFileInputPipeline, uploadFile } from "./bitbybit-client.js";
5
+
6
+ const upload = multer({ storage: multer.memoryStorage(), limits: { fileSize: 50 * 1024 * 1024 } });
7
+ const app = express();
8
+ app.use(express.json());
9
+
10
+ const env: Env = {
11
+ BITBYBIT_API_KEY: process.env.BITBYBIT_API_KEY ?? "",
12
+ BITBYBIT_API_URL: process.env.BITBYBIT_API_URL ?? "https://api.bitbybit.dev",
13
+ };
14
+
15
+ // Check for missing API key and return a helpful error
16
+ app.use("/api", (_req, res, next) => {
17
+ if (!env.BITBYBIT_API_KEY) {
18
+ res.status(503).json({
19
+ error: "BITBYBIT_API_KEY is not configured.",
20
+ help: "You need a Bitbybit API key to use this service. Create an account on https://bitbybit.dev and purchase an API key plan at https://bitbybit.dev/auth/pick-plan?api-keys=true to get access to managed CAD cloud servers.",
21
+ });
22
+ return;
23
+ }
24
+ next();
25
+ });
26
+
27
+ // Backend endpoint — calls bitbybit API with server-side API key
28
+ app.post("/api/generate", async (_req, res) => {
29
+ try {
30
+ const result = await createDragonCup(env);
31
+ res.json(result);
32
+ } catch (e: unknown) {
33
+ const message = e instanceof Error ? e.message : "Unknown error";
34
+ res.status(500).json({ error: message });
35
+ }
36
+ });
37
+
38
+ // Batch generation — creates 3 dragon cup variations in parallel
39
+ app.post("/api/generate-batch", async (_req, res) => {
40
+ try {
41
+ const result = await createDragonCupBatch(env);
42
+ res.json(result);
43
+ } catch (e: unknown) {
44
+ const message = e instanceof Error ? e.message : "Unknown error";
45
+ res.status(500).json({ error: message });
46
+ }
47
+ });
48
+
49
+ // Fetch result for an existing task
50
+ app.get("/api/task/:id", async (req, res) => {
51
+ try {
52
+ const taskId = req.params.id;
53
+ const result = await getTaskResult(env, taskId);
54
+ res.json(result);
55
+ } catch (e: unknown) {
56
+ const message = e instanceof Error ? e.message : "Unknown error";
57
+ res.status(500).json({ error: message });
58
+ }
59
+ });
60
+
61
+ // Pipeline: translate → union → fillet
62
+ app.post("/api/pipeline/translate-union-fillet", async (_req, res) => {
63
+ try {
64
+ const result = await runTranslateUnionFilletPipeline(env);
65
+ res.json(result);
66
+ } catch (e: unknown) {
67
+ const message = e instanceof Error ? e.message : "Unknown error";
68
+ res.status(500).json({ error: message });
69
+ }
70
+ });
71
+
72
+ // Pipeline: map cylinders at positions
73
+ app.post("/api/pipeline/map-cylinders", async (_req, res) => {
74
+ try {
75
+ const result = await runMapCylindersPipeline(env);
76
+ res.json(result);
77
+ } catch (e: unknown) {
78
+ const message = e instanceof Error ? e.message : "Unknown error";
79
+ res.status(500).json({ error: message });
80
+ }
81
+ });
82
+
83
+ // Pipeline: map spheres at different radii
84
+ app.post("/api/pipeline/map-spheres", async (_req, res) => {
85
+ try {
86
+ const result = await runMapSpheresPipeline(env);
87
+ res.json(result);
88
+ } catch (e: unknown) {
89
+ const message = e instanceof Error ? e.message : "Unknown error";
90
+ res.status(500).json({ error: message });
91
+ }
92
+ });
93
+
94
+ // Pipeline: choice conditional
95
+ app.post("/api/pipeline/choice", async (_req, res) => {
96
+ try {
97
+ const result = await runChoicePipeline(env);
98
+ res.json(result);
99
+ } catch (e: unknown) {
100
+ const message = e instanceof Error ? e.message : "Unknown error";
101
+ res.status(500).json({ error: message });
102
+ }
103
+ });
104
+
105
+ // Pipeline: file input (upload STEP → fillet)
106
+ app.post("/api/pipeline/file-input", upload.single("file"), async (req, res) => {
107
+ try {
108
+ const file = req.file;
109
+ if (!file) { res.status(400).json({ error: "No file uploaded" }); return; }
110
+
111
+ const fileId = await uploadFile(env, file.buffer.buffer as ArrayBuffer, file.originalname);
112
+ const result = await runFileInputPipeline(env, fileId);
113
+ res.json(result);
114
+ } catch (e: unknown) {
115
+ const message = e instanceof Error ? e.message : "Unknown error";
116
+ res.status(500).json({ error: message });
117
+ }
118
+ });
119
+
120
+ // Proxy download — streams a remote file through the backend to avoid CORS issues with GLTFLoader
121
+ app.get("/api/proxy-download", async (req, res) => {
122
+ const url = req.query.url as string | undefined;
123
+ if (!url) { res.status(400).json({ error: "Missing url parameter" }); return; }
124
+
125
+ try {
126
+ const response = await fetch(url);
127
+ if (!response.ok || !response.body) {
128
+ res.status(502).json({ error: `Upstream error: ${response.status}` });
129
+ return;
130
+ }
131
+ res.setHeader("Content-Type", response.headers.get("Content-Type") || "model/gltf-binary");
132
+ const arrayBuffer = await response.arrayBuffer();
133
+ res.send(Buffer.from(arrayBuffer));
134
+ } catch (e: unknown) {
135
+ const message = e instanceof Error ? e.message : "Unknown error";
136
+ res.status(500).json({ error: message });
137
+ }
138
+ });
139
+
140
+ const PORT = parseInt(process.env.PORT ?? "3000", 10);
141
+ app.listen(PORT, () => {
142
+ console.log(`Server running at http://localhost:${PORT}`);
143
+ });
@@ -0,0 +1,4 @@
1
+ export interface Env {
2
+ BITBYBIT_API_KEY: string;
3
+ BITBYBIT_API_URL: string;
4
+ }
@@ -0,0 +1,17 @@
1
+ {
2
+ "compilerOptions": {
3
+ "target": "ES2022",
4
+ "module": "NodeNext",
5
+ "moduleResolution": "NodeNext",
6
+ "strict": true,
7
+ "skipLibCheck": true,
8
+ "lib": ["ES2022"],
9
+ "types": ["node"],
10
+ "outDir": "dist",
11
+ "rootDir": "src",
12
+ "resolveJsonModule": true,
13
+ "isolatedModules": true,
14
+ "esModuleInterop": true
15
+ },
16
+ "include": ["src/**/*.ts"]
17
+ }
@@ -0,0 +1,3 @@
1
+ # Get your API key at https://bitbybit.dev/auth/pick-plan?api-keys=true
2
+ BITBYBIT_API_KEY=
3
+ BITBYBIT_API_URL=https://api.bitbybit.dev
@@ -0,0 +1,23 @@
1
+ {
2
+ "name": "bitbybit-api-nodejs-sdk-threejs",
3
+ "version": "1.0.0",
4
+ "private": true,
5
+ "type": "module",
6
+ "scripts": {
7
+ "dev": "tsx watch --env-file=.env src/index.ts",
8
+ "build": "tsc",
9
+ "start": "node --env-file=.env dist/index.js"
10
+ },
11
+ "dependencies": {
12
+ "express": "^5.1.0",
13
+ "multer": "^1.4.5-lts.2",
14
+ "@bitbybit-dev/cad-cloud-sdk": "1.0.0"
15
+ },
16
+ "devDependencies": {
17
+ "@types/express": "^5.0.2",
18
+ "@types/multer": "^1.4.12",
19
+ "@types/node": "^22.15.0",
20
+ "tsx": "^4.19.0",
21
+ "typescript": "^5.8.0"
22
+ }
23
+ }