Skip to content

Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.

feat(slicer): open any saved model in OrcaSlicer or Bambu Studio, served as a sized STL or 3MF from /api/slicer, with a 3D print action on the model page

nirholasa68db7fa0f2b
diff --git a/api/_lib/print/slicer.js b/api/_lib/print/slicer.js
new file mode 100644
index 000000000..f96ef25f5
--- /dev/null
+++ b/api/_lib/print/slicer.js
@@ -0,0 +1,72 @@
+// Place a model on a slicer's build plate: Z-up, millimetres, a printable size.
+//
+// Adapted from Modly (https://github.com/lightningpixel/modly), MIT License,
+// Copyright (c) 2026 Lightning Pixel. Modly's slicer export rotates glTF's
+// Y-up into the Z-up world every slicer uses and rescales unit-sized AI output
+// so it does not import as a 1 mm speck. This version keeps both rules and adds
+// two more a print-ready file needs: the part sits on the bed (lowest point at
+// Z = 0) and is centred on the plate origin, so it lands where the user expects
+// instead of floating above or beside the plate.
+//
+// Sizing policy. glTF geometry is in meters. A model whose longest edge comes
+// out between 10 mm and 250 mm in real units is a believable physical object and
+// is kept exactly as authored. Anything else (generated models are usually
+// normalised to about 1 m, scans can be centimetres or kilometres) is scaled so
+// its longest edge is 100 mm, a size every consumer printer can run. A caller
+// that wants a specific size passes `sizeMm` and gets exactly that.
+
+import { boundsOf } from './mesh-io.js';
+
+const MM_PER_METER = 1000;
+export const AUTO_SIZE_MM = 100;
+export const REAL_SIZE_RANGE_MM = Object.freeze([10, 250]);
+export const SIZE_LIMITS_MM = Object.freeze([5, 500]);
+
+/**
+ * Resolve the longest edge, in millimetres, the placed model will have.
+ *
+ * @param {number} longestMeters the model's longest bounding-box edge in glTF units
+ * @param {number|null} sizeMm an explicit size, or null for the automatic policy
+ * @returns {{ longestMm: number, mode: 'requested'|'real'|'auto' }}
+ */
+export function resolvePrintSize(longestMeters, sizeMm = null) {
+ if (sizeMm !== null && sizeMm !== undefined) {
+ const n = Number(sizeMm);
+ if (!Number.isFinite(n) || n < SIZE_LIMITS_MM[0] || n > SIZE_LIMITS_MM[1]) {
+ throw new RangeError(`size must be between ${SIZE_LIMITS_MM[0]} and ${SIZE_LIMITS_MM[1]} mm`);
+ }
+ return { longestMm: n, mode: 'requested' };
+ }
+ const real = longestMeters * MM_PER_METER;
+ if (real >= REAL_SIZE_RANGE_MM[0] && real <= REAL_SIZE_RANGE_MM[1]) return { longestMm: real, mode: 'real' };
+ return { longestMm: AUTO_SIZE_MM, mode: 'auto' };
+}
+
+/**
+ * Rotate Y-up to Z-up, scale to millimetres, rest on Z = 0 and centre in XY.
+ * Returns new positions; the input is untouched. The exporters are then called
+ * with `scale: 1`, because these numbers are already millimetres.
+ *
+ * @param {Float64Array|number[]} positions xyz triples in glTF meters, Y-up
+ * @param {{ sizeMm?: number|null }} [opts]
+ * @returns {{ positions: Float64Array, longestMm: number, mode: string, sizeMm: number[] }}
+ */
+export function placeOnBed(positions, { sizeMm = null } = {}) {
+ const bounds = boundsOf(positions);
+ if (!bounds || !(bounds.longest > 0)) throw new RangeError('model has no extent to place');
+ const { longestMm, mode } = resolvePrintSize(bounds.longest, sizeMm);
+ const k = longestMm / bounds.longest;
+
+ // (x, y, z) Y-up becomes (x, -z, y) Z-up: a +90 degree turn about X, so the
+ // model's "up" is the slicer's "up" and its front faces the user.
+ const [cx, , cz] = bounds.center;
+ const minY = bounds.min[1];
+ const out = new Float64Array(positions.length);
+ for (let i = 0; i < positions.length; i += 3) {
+ out[i] = (positions[i] - cx) * k;
+ out[i + 1] = -(positions[i + 2] - cz) * k;
+ out[i + 2] = (positions[i + 1] - minY) * k;
+ }
+ const size = [bounds.size[0] * k, bounds.size[2] * k, bounds.size[1] * k];
+ return { positions: out, longestMm, mode, sizeMm: size };
+}
diff --git a/api/_lib/rate-limit.js b/api/_lib/rate-limit.js
index 1b63eaf75..3107288d7 100644
--- a/api/_lib/rate-limit.js
+++ b/api/_lib/rate-limit.js
@@ -2097,6 +2097,13 @@ export const limits = {
// stopping a script from using the analyzer as a free mesh-processing service.
printQuoteIp: (ip) =>
getLimiter('print:quote:ip', { limit: 90, window: '5 m', local: true }).limit(ip),
+ // Slicer handoff file (api/slicer/model.js). A miss downloads the creation's
+ // GLB and writes an STL or 3MF, so it is CPU-bound like the quote analyzer;
+ // hits are served from the converted-file cache and the CDN and never reach
+ // this bucket. Sized for someone opening a few models in OrcaSlicer, re-sizing
+ // them, and downloading the fallback file, not for bulk conversion.
+ slicerFileIp: (ip) =>
+ getLimiter('slicer:file:ip', { limit: 30, window: '5 m', local: true }).limit(ip),
// Materialize checkout (api/print/orders.js and its confirm step). Both are
// session-gated and CSRF-gated already, so this is not the security boundary;
// it caps how often one IP can open orders or poll the chain for a payment.
diff --git a/api/slicer/model.js b/api/slicer/model.js
new file mode 100644
index 000000000..546000e7c
--- /dev/null
+++ b/api/slicer/model.js
@@ -0,0 +1,181 @@
+// GET /api/slicer/:id/model.stl, /api/slicer/:id/model.3mf
+// GET /api/slicer/:id/:size mm/model.stl (for example /api/slicer/<id>/80mm/model.stl)
+//
+// A stored creation, converted on the fly into a file a 3D-printing slicer can
+// open. This is the URL behind the "Open in OrcaSlicer" and "Open in Bambu
+// Studio" buttons: their deep links (`orcaslicer://open?file=<url>`) download
+// whatever URL they are handed and pick the importer from the LAST path
+// segment, so the path has to end in a literal `model.stl` and carry no query
+// string. vercel.json rewrites the pretty path onto this handler.
+//
+// The file is print-ready, not just converted: Z-up, millimetres, resting on
+// the bed and centred (api/_lib/print/slicer.js). Geometry comes from the same
+// loader and exporters Materialize uses (api/_lib/print/), so the STL a slicer
+// receives here is byte-for-byte the kind a print bureau receives there.
+//
+// Public creations and unlisted ones (which are reachable by link anyway) are
+// served; private ones are a 404, exactly like /api/forge-creation. Responses
+// are immutable per (id, format, size), so they carry a long CDN lifetime and a
+// strong ETag, and a small in-process cache keeps a slicer's retry from
+// converting the model twice.
+
+import { createHash } from 'node:crypto';
+
+import { cors, error, method, rateLimited, wrap } from '../_lib/http.js';
+import { clientIp, limits } from '../_lib/rate-limit.js';
+import { isUuid } from '../_lib/validate.js';
+import { getPublicCreation } from '../_lib/forge-store.js';
+import { loadMeshFromUrl, MeshIoError } from '../_lib/print/mesh-io.js';
+import { exportStl } from '../_lib/print/export-stl.js';
+import { export3mf } from '../_lib/print/export-3mf.js';
+import { placeOnBed, SIZE_LIMITS_MM } from '../_lib/print/slicer.js';
+
+export const FORMATS = Object.freeze({
+ stl: { contentType: 'model/stl' },
+ '3mf': { contentType: 'model/3mf' },
+});
+
+// A slicer handoff is for a single printable part. Above this the STL alone
+// passes 75 MB and slicers struggle; Materialize's own cap is 2M for orders a
+// person has deliberately sized and paid for.
+export const MAX_SLICER_TRIANGLES = 1_500_000;
+
+const CACHE_CONTROL = 'public, max-age=3600, s-maxage=86400, stale-while-revalidate=604800';
+const CACHE_ENTRIES = 12;
+const CACHE_BYTES = 256 * 1024 * 1024;
+
+const MESH_ERROR_STATUS = {
+ invalid_model: 422,
+ no_geometry: 422,
+ too_large: 413,
+ too_complex: 413,
+ invalid_url: 422,
+ fetch_failed: 502,
+};
+
+function slug(text) {
+ return (
+ String(text || '')
+ .toLowerCase()
+ .replace(/[^a-z0-9]+/g, '-')
+ .replace(/^-+|-+$/g, '')
+ .slice(0, 60) || 'model'
+ );
+}
+
+/** The production source: a finished public creation's GLB, through the SSRF-safe fetcher. */
+export async function loadCreationMesh(id, { color }) {
+ const creation = await getPublicCreation({ id });
+ if (!creation?.glb_url) return null;
+ const mesh = await loadMeshFromUrl(creation.glb_url, { maxTriangles: MAX_SLICER_TRIANGLES, color });
+ return { mesh, title: creation.prompt };
+}
+
+function readParams(req) {
+ const url = new URL(req.url, 'http://localhost');
+ const q = req.query || {};
+ const pick = (k) => String(q[k] ?? url.searchParams.get(k) ?? '').trim();
+ return { id: pick('id').toLowerCase(), format: pick('format').toLowerCase(), size: pick('size') };
+}
+
+/**
+ * Build the handler. `loadSource(id, { color })` resolves to `{ mesh, title }`
+ * (mesh as api/_lib/print/mesh-io.js returns it) or null when the creation is
+ * not public. Production uses loadCreationMesh; the test suite hands in a GLB it
+ * builds itself, because the production fetcher refuses loopback hosts.
+ */
+export function createSlicerModelHandler({ loadSource = loadCreationMesh } = {}) {
+ const cache = new Map();
+ let cachedBytes = 0;
+
+ function remember(key, entry) {
+ cache.set(key, entry);
+ cachedBytes += entry.body.length;
+ while (cache.size > CACHE_ENTRIES || cachedBytes > CACHE_BYTES) {
+ const [oldest, value] = cache.entries().next().value;
+ cache.delete(oldest);
+ cachedBytes -= value.body.length;
+ }
+ }
+
+ async function convert(id, format, sizeMm) {
+ const source = await loadSource(id, { color: format === '3mf' });
+ if (!source) return null;
+ const placed = placeOnBed(source.mesh.positions, { sizeMm });
+ const mesh = { positions: placed.positions, indices: source.mesh.indices, colors: source.mesh.colors };
+ const sizeLabel = placed.sizeMm.map((n) => n.toFixed(1)).join(' x ');
+ const body =
+ format === 'stl'
+ ? exportStl(mesh, { scale: 1, header: `three.ws ${id.slice(0, 8)} mm ${sizeLabel}` })
+ : export3mf(mesh, { scale: 1, title: String(source.title || '').slice(0, 200), designer: 'three.ws' });
+ const digest = createHash('sha256').update(body).digest('hex').slice(0, 32);
+ return {
+ body,
+ etag: `"slc-${digest}"`,
+ filename: `${slug(source.title)}${sizeMm ? `-${sizeMm}mm` : ''}.${format}`,
+ triangles: mesh.indices.length / 3,
+ sizeLabel,
+ mode: placed.mode,
+ };
+ }
+
+ return wrap(async (req, res) => {
+ if (cors(req, res, { origins: '*', methods: 'GET,HEAD,OPTIONS', payments: false })) return;
+ if (!method(req, res, ['GET'])) return; // HEAD is folded into GET and its body stripped
+
+ const { id, format, size } = readParams(req);
+ if (!isUuid(id)) return error(res, 400, 'validation_error', 'id must be a creation id (a UUID).');
+ if (!FORMATS[format]) return error(res, 400, 'validation_error', 'format must be stl or 3mf.');
+ let sizeMm = null;
+ if (size) {
+ sizeMm = Number(size);
+ if (!Number.isInteger(sizeMm) || sizeMm < SIZE_LIMITS_MM[0] || sizeMm > SIZE_LIMITS_MM[1]) {
+ return error(
+ res,
+ 400,
+ 'validation_error',
+ `size must be a whole number of millimetres from ${SIZE_LIMITS_MM[0]} to ${SIZE_LIMITS_MM[1]}.`,
+ );
+ }
+ }
+
+ const key = `${id}:${format}:${sizeMm ?? 'auto'}`;
+ let entry = cache.get(key);
+ if (!entry) {
+ const rate = await limits.slicerFileIp(clientIp(req));
+ if (!rate.success) return rateLimited(res, rate, 'too many slicer file conversions');
+ try {
+ entry = await convert(id, format, sizeMm);
+ } catch (err) {
+ if (err instanceof MeshIoError) {
+ return error(res, MESH_ERROR_STATUS[err.code] ?? 422, err.code, err.message, err.extra || {});
+ }
+ throw err;
+ }
+ if (!entry) {
+ return error(res, 404, 'creation_not_found', 'No finished public creation with that id.');
+ }
+ remember(key, entry);
+ }
+
+ res.setHeader('cache-control', CACHE_CONTROL);
+ res.setHeader('etag', entry.etag);
+ res.setHeader('x-slicer-size-mm', entry.sizeLabel);
+ res.setHeader('x-slicer-scale', entry.mode);
+ res.setHeader('access-control-expose-headers', 'etag, x-slicer-size-mm, x-slicer-scale, content-disposition');
+ const inm = req.headers['if-none-match'];
+ if (inm && inm.split(',').some((tag) => tag.trim() === entry.etag)) {
+ res.statusCode = 304;
+ res.end();
+ return;
+ }
+ res.statusCode = 200;
+ res.setHeader('content-type', FORMATS[format].contentType);
+ res.setHeader('content-length', String(entry.body.length));
+ res.setHeader('content-disposition', `attachment; filename="${entry.filename}"`);
+ res.setHeader('x-content-type-options', 'nosniff');
+ res.end(entry.body);
+ });
+}
+
+export default createSlicerModelHandler();
diff --git a/src/forge-export.js b/src/forge-export.js
index 64472c780..2d600e2a7 100644
--- a/src/forge-export.js
+++ b/src/forge-export.js
@@ -26,6 +26,7 @@
// styles and only needs the result panel's download anchor to exist.
import { createLogger } from './shared/log.js';
+import { creationIdFromGlbUrl, mountSlicerMenuItems } from './slicer-handoff.js';
const log = createLogger('forge-export');
@@ -167,7 +168,7 @@ if (download && resultPanel) {
caret.setAttribute('aria-haspopup', 'menu');
caret.setAttribute('aria-expanded', 'false');
caret.setAttribute('aria-label', 'More download formats');
- caret.title = 'More formats: OBJ, STL, PLY, USDZ';
+ caret.title = 'More formats, or open in a 3D-printing slicer';
caret.innerHTML =
'<svg viewBox="0 0 12 12" fill="none" aria-hidden="true"><path d="M2 4.5 6 8.5 10 4.5" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"/></svg>';
split.appendChild(caret);
@@ -195,6 +196,13 @@ if (download && resultPanel) {
itemStatus.set(f.id, item.querySelector('.status'));
}
+ // Slicer handoff rows (OrcaSlicer, Bambu Studio). They download the stored
+ // creation from /api/slicer/<id>/model.stl, so they appear only for a model
+ // that has a creation id, and say so when the viewer shows an unsaved edit.
+ const slicerItems = mountSlicerMenuItems(menu, {
+ isLocalEdit: () => (download.getAttribute('href') || '').startsWith('blob:'),
+ });
+
// ---- menu behavior -------------------------------------------------------
// The menu is right-anchored to the split button, which sits inset from the
@@ -232,7 +240,7 @@ if (download && resultPanel) {
});
split.addEventListener('keydown', (e) => {
if (!isOpen()) return;
- const items = [...menu.querySelectorAll('.export-item')];
+ const items = [...menu.querySelectorAll('.export-item:not([hidden])')];
const idx = items.indexOf(document.activeElement);
if (e.key === 'Escape') {
setOpen(false);
@@ -382,6 +390,14 @@ if (download && resultPanel) {
const url = download.getAttribute('href');
if (!url) return;
const status = itemStatus.get(format.id);
+ // A server conversion fetches its source over the network, and an
+ // in-browser mesh edit only exists as a blob in this tab. Say so rather
+ // than silently converting the unedited model.
+ if (format.server && url.startsWith('blob:')) {
+ status.textContent = 'converts the saved model only: reset your mesh edits, or pick OBJ, STL or PLY';
+ status.classList.add('is-error');
+ return;
+ }
busy.add(format.id);
item.setAttribute('aria-disabled', 'true');
status.classList.remove('is-error');
@@ -444,8 +460,9 @@ if (download && resultPanel) {
// A new generation invalidates the parsed-scene cache (the href changes, but
// clearing eagerly also frees the old scene graph for GC).
- document.addEventListener('forge:model-ready', () => {
+ document.addEventListener('forge:model-ready', (e) => {
sceneCache = { url: null, scene: null };
+ slicerItems.setCreation(e.detail?.creationId || creationIdFromGlbUrl(e.detail?.glbUrl));
// Retire any conversion still polling for the previous model.
convertEpoch += 1;
for (const status of itemStatus.values()) {
diff --git a/src/forge-studio/forge-export.js b/src/forge-studio/forge-export.js
index b6330fbb8..a46472f4a 100644
--- a/src/forge-studio/forge-export.js
+++ b/src/forge-studio/forge-export.js
@@ -14,6 +14,7 @@
// styles and only needs the result panel's download anchor to exist.
import { createLogger } from '../shared/log.js';
+import { creationIdFromGlbUrl, mountSlicerMenuItems } from '../slicer-handoff.js';
const log = createLogger('forge-export');
@@ -125,7 +126,7 @@ if (download && resultPanel) {
caret.setAttribute('aria-haspopup', 'menu');
caret.setAttribute('aria-expanded', 'false');
caret.setAttribute('aria-label', 'More download formats');
- caret.title = 'More formats: OBJ, STL, PLY, USDZ';
+ caret.title = 'More formats, or open in a 3D-printing slicer';
caret.innerHTML =
'<svg viewBox="0 0 12 12" fill="none" aria-hidden="true"><path d="M2 4.5 6 8.5 10 4.5" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"/></svg>';
split.appendChild(caret);
@@ -153,6 +154,13 @@ if (download && resultPanel) {
itemStatus.set(f.id, item.querySelector('.status'));
}
+ // Slicer handoff rows (OrcaSlicer, Bambu Studio). They download the stored
+ // creation from /api/slicer/<id>/model.stl, so they appear only for a model
+ // that has a creation id, and say so when the viewer shows an unsaved edit.
+ const slicerItems = mountSlicerMenuItems(menu, {
+ isLocalEdit: () => (download.getAttribute('href') || '').startsWith('blob:'),
+ });
+
// ---- menu behavior -------------------------------------------------------
function setOpen(open) {
@@ -168,7 +176,7 @@ if (download && resultPanel) {
});
split.addEventListener('keydown', (e) => {
if (!isOpen()) return;
- const items = [...menu.querySelectorAll('.export-item')];
+ const items = [...menu.querySelectorAll('.export-item:not([hidden])')];
const idx = items.indexOf(document.activeElement);
if (e.key === 'Escape') {
setOpen(false);
@@ -297,8 +305,9 @@ if (download && resultPanel) {
// A new generation invalidates the parsed-scene cache (the href changes, but
// clearing eagerly also frees the old scene graph for GC).
- document.addEventListener('forge:model-ready', () => {
+ document.addEventListener('forge:model-ready', (e) => {
sceneCache = { url: null, scene: null };
+ slicerItems.setCreation(e.detail?.creationId || creationIdFromGlbUrl(e.detail?.glbUrl));
for (const status of itemStatus.values()) {
status.textContent = '';
status.classList.remove('is-error');
diff --git a/src/model-page.js b/src/model-page.js
index ab3b0e9e1..31ed4e863 100644
--- a/src/model-page.js
+++ b/src/model-page.js
@@ -266,10 +266,21 @@ function renderInfo() {
<a class="mp-action" href="/materialize?creation=${encodeURIComponent(c.id)}" title="Order this model as a real physical print, shipped to you">⬢ Materialize</a>
<button class="mp-action" id="mp-embed" type="button">&lt;/&gt; Embed</button>
<button class="mp-action" id="mp-share" type="button">↗ Share</button>
+ <button class="mp-action" id="mp-slicer" type="button" aria-controls="mp-print-tools" title="Open this model in OrcaSlicer or Bambu Studio, or download a print-ready STL">⎙ 3D print</button>
${c.remixable ? `<button class="mp-action" id="mp-remix" type="button">Remix · $0.25</button>` : ''}
</div>
<div class="mp-geo" id="mp-geo"><span>Reading geometry…</span></div>
<div class="mp-sim" id="mp-sim"></div>
+ <section class="mp-tools" aria-label="Model tools">
+ <details class="mp-tool" id="mp-mesh-tools">
+ <summary>Edit mesh <span>repair, smooth, decimate in your browser</span></summary>
+ <div class="mp-tool-body" id="mp-mesh-host"></div>
+ </details>
+ <details class="mp-tool" id="mp-print-tools">
+ <summary>3D print <span>open in OrcaSlicer or Bambu Studio, or download STL</span></summary>
+ <div class="mp-tool-body" id="mp-slicer-host"></div>
+ </details>
+ </section>
<p class="mp-desc">${esc(c.prompt)}</p>
<div class="mp-published" title="${esc(publishedAbs)}">🕒 Published ${esc(timeAgo(c.created_at))}</div>
${chips ? `<div class="mp-chips">${chips}</div>` : ''}
@@ -279,6 +290,63 @@ function renderInfo() {
wireActions();
wireFollow();
renderEdition();
+ wireTools();
+}
+
+// ── model tools: in-browser mesh edits and the slicer handoff ───────────────
+//
+// Both modules load on first open, so a visitor who never edits or prints a
+// model never downloads the mesh-processing code. Mesh edits only change what
+// this tab shows and offers for download; the stored creation is untouched.
+
+function wireTools() {
+ const c = state.creation;
+ const meshTools = $('mp-mesh-tools');
+ const printTools = $('mp-print-tools');
+
+ meshTools?.addEventListener('toggle', async () => {
+ if (!meshTools.open || meshTools.dataset.mounted) return;
+ meshTools.dataset.mounted = '1';
+ const host = $('mp-mesh-host');
+ host.textContent = 'Loading mesh tools…';
+ try {
+ const { mountMeshTools } = await import('./mesh-ops/panel.js');
+ host.textContent = '';
+ const tools = mountMeshTools(host, {
+ onChange({ url, edited }) {
+ const mv = document.querySelector('#mp-viewer model-viewer');
+ if (mv) mv.setAttribute('src', edited ? url : viewerSrc(c));
+ },
+ });
+ tools.setSource(c.glb_url, { label: titleFromPrompt(c.prompt) });
+ tools.activate();
+ } catch (err) {
+ log.error('mesh tools failed to load', err);
+ delete meshTools.dataset.mounted;
+ host.textContent = 'The mesh tools could not load. Close and reopen this section to try again.';
+ }
+ });
+
+ printTools?.addEventListener('toggle', async () => {
+ if (!printTools.open || printTools.dataset.mounted) return;
+ printTools.dataset.mounted = '1';
+ const host = $('mp-slicer-host');
+ try {
+ const { renderSlicerHandoff } = await import('./slicer-handoff.js');
+ renderSlicerHandoff(host, { creationId: c.id });
+ } catch (err) {
+ log.error('slicer handoff failed to load', err);
+ delete printTools.dataset.mounted;
+ host.textContent = 'The print options could not load. Close and reopen this section to try again.';
+ }
+ });
+
+ $('mp-slicer')?.addEventListener('click', () => {
+ if (!printTools) return;
+ printTools.open = true;
+ printTools.scrollIntoView({ behavior: 'smooth', block: 'center' });
+ printTools.querySelector('summary')?.focus({ preventScroll: true });
+ });
}
// ── physical editions ────────────────────────────────────────────────────────
diff --git a/src/model.css b/src/model.css
index c5bfc4bc7..c4744c276 100644
--- a/src/model.css
+++ b/src/model.css
@@ -259,6 +259,52 @@ a.mp-creator-name:hover, a.mp-creator-name:focus-visible { text-decoration: unde
margin: 0 0 var(--space-md);
}
+/* ── Model tools (mesh edits, slicer handoff) ───────────────────────────── */
+
+.mp-tools {
+ display: flex;
+ flex-direction: column;
+ gap: var(--space-sm);
+ margin: 0 0 var(--space-md);
+}
+.mp-tool {
+ border: 1px solid var(--stroke);
+ border-radius: var(--radius-md);
+ background: var(--surface-1);
+ transition: border-color var(--duration-fast) var(--ease-standard);
+}
+.mp-tool:hover, .mp-tool[open] { border-color: var(--stroke-strong); }
+.mp-tool > summary {
+ display: flex;
+ align-items: baseline;
+ gap: var(--space-sm);
+ flex-wrap: wrap;
+ padding: 10px 14px;
+ cursor: pointer;
+ list-style: none;
+ font-family: var(--font-display);
+ font-size: var(--text-sm);
+ color: var(--ink-bright);
+ border-radius: var(--radius-md);
+}
+.mp-tool > summary::-webkit-details-marker { display: none; }
+.mp-tool > summary::after {
+ content: '';
+ margin-left: auto;
+ align-self: center;
+ width: 7px;
+ height: 7px;
+ border-right: 1.5px solid var(--ink-dim);
+ border-bottom: 1.5px solid var(--ink-dim);
+ transform: rotate(45deg);
+ transition: transform var(--duration-fast) var(--ease-standard);
+}
+.mp-tool[open] > summary::after { transform: rotate(225deg); }
+.mp-tool > summary span { font-family: var(--font-body); font-size: var(--text-xs); color: var(--ink-dim); }
+.mp-tool > summary:hover { background: var(--surface-2); }
+.mp-tool > summary:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }
+.mp-tool-body { padding: 4px 14px 14px; font-size: var(--text-sm); color: var(--ink-dim); }
+
/* ── Description + meta + chips ──────────────────────────────────────────── */
.mp-desc {
diff --git a/src/slicer-handoff.js b/src/slicer-handoff.js
new file mode 100644
index 000000000..886f5b6bd
--- /dev/null
+++ b/src/slicer-handoff.js
@@ -0,0 +1,285 @@
+// "Open in OrcaSlicer" and friends: hand a stored creation to a desktop slicer.
+//
+// Adapted from Modly (https://github.com/lightningpixel/modly), MIT License,
+// Copyright (c) 2026 Lightning Pixel. Modly's orcaSlicerLink.ts established the
+// contract this follows: OrcaSlicer registers `orcaslicer://open?file=<url>`,
+// downloads the http(s) URL it is given, and picks the importer from the URL's
+// FINAL path segment, so the file URL must end in a literal `model.stl` with no
+// query string and must be percent-encoded as a whole.
+//
+// Verified against each slicer's own source before a button was offered:
+// OrcaSlicer orcaslicer://open?file=<encoded url> any https host
+// Bambu Studio bambustudio://open?file=<encoded url> any host, after the
+// app's own "not from a trusted site" confirmation
+// PrusaSlicer prusaslicer://open?file=... only printables.com
+// and thingiverse.com URLs are accepted, so no button: the STL
+// download is the honest path there
+//
+// The file itself is served by api/slicer/model.js: Z-up, millimetres, on the
+// bed. A browser cannot tell whether a custom scheme has a handler, so the
+// handoff watches for the page losing focus (which is what happens when the OS
+// switches to the slicer) and, if nothing happens, offers the download and the
+// install links instead of leaving the user looking at a button that did nothing.
+
+const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
+const GLB_ID_RE = /([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})(?:\.web)?\.glb(?:$|[?#])/i;
+
+export const SLICERS = Object.freeze({
+ orca: Object.freeze({
+ id: 'orca',
+ name: 'OrcaSlicer',
+ scheme: 'orcaslicer',
+ install: 'https://github.com/SoftFever/OrcaSlicer/releases/latest',
+ }),
+ bambu: Object.freeze({
+ id: 'bambu',
+ name: 'Bambu Studio',
+ scheme: 'bambustudio',
+ install: 'https://bambulab.com/en/download/studio',
+ }),
+});
+
+export const PRUSA_NOTE =
+ 'PrusaSlicer only opens links from Printables and Thingiverse, so download the STL and open it from PrusaSlicer instead.';
+
+/** The creation id embedded in a forge storage URL (`.../<uuid>.glb` or `.web.glb`), or null. */
+export function creationIdFromGlbUrl(url) {
+ const match = GLB_ID_RE.exec(String(url || ''));
+ return match ? match[1].toLowerCase() : null;
+}
+
+/**
+ * The print-ready file URL for a creation. Path only, ending in `model.<ext>`,
+ * because slicers name and parse the download from the last path segment.
+ *
+ * @param {string} origin e.g. https://three.ws
+ * @param {string} id creation UUID
+ * @param {{ format?: 'stl'|'3mf', sizeMm?: number|null }} [opts]
+ */
+export function slicerModelUrl(origin, id, { format = 'stl', sizeMm = null } = {}) {
+ if (!UUID_RE.test(String(id || ''))) throw new TypeError('slicerModelUrl needs a creation UUID');
+ if (format !== 'stl' && format !== '3mf') throw new TypeError('format must be stl or 3mf');
+ const base = String(origin || '').replace(/\/+$/, '');
+ const size = sizeMm ? `${Math.round(sizeMm)}mm/` : '';
+ return `${base}/api/slicer/${String(id).toLowerCase()}/${size}model.${format}`;
+}
+
+/** The deep link that asks `slicer` to download and import `fileUrl`. */
+export function buildSlicerLink(slicer, fileUrl) {
+ const s = typeof slicer === 'string' ? SLICERS[slicer] : slicer;
+ if (!s?.scheme) throw new TypeError(`unknown slicer: ${slicer}`);
+ const url = String(fileUrl || '');
+ if (!/^https?:\/\//i.test(url)) throw new TypeError('slicers can only download http(s) URLs');
+ if (/[?#]/.test(url)) throw new TypeError('slicer file URLs must not carry a query string or fragment');
+ return `${s.scheme}://open?file=${encodeURIComponent(url)}`;
+}
+
+// How long the page waits for the OS to switch to the slicer before it offers
+// the fallback. Long enough for a cold app launch to steal focus on a slow
+// machine, short enough that the help appears while the user is still looking.
+const HANDOFF_WINDOW_MS = 2500;
+
+/**
+ * Fire a slicer deep link. Resolves to true when the page lost focus (the
+ * slicer, or the browser's "open this app?" prompt, took over) and false when
+ * nothing happened in the window, which almost always means no app is
+ * registered for the scheme.
+ */
+export function openInSlicer(slicer, fileUrl) {
+ const link = buildSlicerLink(slicer, fileUrl);
+ return new Promise((resolve) => {
+ let settled = false;
+ const finish = (opened) => {
+ if (settled) return;
+ settled = true;
+ window.removeEventListener('blur', onBlur);
+ document.removeEventListener('visibilitychange', onHide);
+ clearTimeout(timer);
+ resolve(opened);
+ };
+ const onBlur = () => finish(true);
+ const onHide = () => {
+ if (document.visibilityState === 'hidden') finish(true);
+ };
+ window.addEventListener('blur', onBlur);
+ document.addEventListener('visibilitychange', onHide);
+ const timer = setTimeout(() => finish(false), HANDOFF_WINDOW_MS);
+ const a = document.createElement('a');
+ a.href = link;
+ a.rel = 'noopener';
+ document.body.appendChild(a);
+ a.click();
+ a.remove();
+ });
+}
+
+const SIZES = [
+ ['', 'Auto size'],
+ ['50', '50 mm'],
+ ['80', '80 mm'],
+ ['100', '100 mm'],
+ ['150', '150 mm'],
+ ['200', '200 mm'],
+];
+
+function injectStyles() {
+ if (document.getElementById('slicer-handoff-styles')) return;
+ const style = document.createElement('style');
+ style.id = 'slicer-handoff-styles';
+ style.textContent = `
+ .sh { display: flex; flex-direction: column; gap: var(--space-sm, 0.6rem); }
+ .sh-row { display: flex; flex-wrap: wrap; align-items: center; gap: var(--space-sm, 0.6rem); }
+ .sh-btn {
+ display: inline-flex; align-items: center; gap: 0.45rem; cursor: pointer; text-decoration: none;
+ background: var(--surface-1, #16161d); color: var(--ink, #eee); border: 1px solid var(--stroke, rgba(255,255,255,0.12));
+ border-radius: var(--radius-md, 8px); padding: 0.5rem 0.85rem; font: inherit; font-size: var(--text-sm, 0.85rem);
+ transition: border-color 0.15s ease, background 0.15s ease, transform 0.15s ease;
+ }
+ .sh-btn:hover { border-color: var(--stroke-strong, rgba(255,255,255,0.24)); background: var(--surface-2, rgba(255,255,255,0.06)); }
+ .sh-btn:active { transform: translateY(1px); }
+ .sh-btn:focus-visible, .sh-size:focus-visible, .sh-help a:focus-visible { outline: 2px solid var(--accent, #7c6cff); outline-offset: 2px; }
+ .sh-btn[aria-busy='true'] { opacity: 0.6; cursor: progress; }
+ .sh-btn.is-primary { background: var(--accent, #7c6cff); border-color: var(--accent, #7c6cff); color: var(--bg-0, #0a0a0a); font-weight: 600; }
+ .sh-size {
+ background: var(--surface-1, #16161d); border: 1px solid var(--stroke, rgba(255,255,255,0.12)); border-radius: var(--radius-md, 8px);
+ color: var(--ink, #eee); font: inherit; font-size: var(--text-sm, 0.85rem); padding: 0.45rem 0.6rem;
+ }
+ .sh-note { margin: 0; font-size: var(--text-xs, 0.78rem); color: var(--ink-dim, #999); line-height: 1.5; }
+ .sh-help {
+ margin: 0; padding: 0.7rem 0.85rem; border-radius: var(--radius-md, 8px); line-height: 1.5;
+ border: 1px solid var(--stroke, rgba(255,255,255,0.12)); background: var(--surface-1, #16161d);
+ font-size: var(--text-xs, 0.78rem); color: var(--ink, #eee);
+ animation: sh-in 0.18s ease;
+ }
+ .sh-help[hidden] { display: none; }
+ .sh-help a { color: var(--accent, #7c6cff); }
+ @keyframes sh-in { from { opacity: 0; transform: translateY(-3px); } to { opacity: 1; transform: none; } }
+ @media (prefers-reduced-motion: reduce) { .sh-help { animation: none; } }
+ `;
+ document.head.appendChild(style);
+}
+
+function esc(s) {
+ return String(s ?? '').replace(/[&<>"]/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;' })[c]);
+}
+
+/**
+ * Explain a deep link that did nothing, with the file one click away. Shared by
+ * the model page block and the forge export menu so both say the same thing.
+ */
+export function missedHandoffHtml(slicer, fileUrl) {
+ const s = typeof slicer === 'string' ? SLICERS[slicer] : slicer;
+ return `${esc(s.name)} did not open. If it is not installed, <a href="${esc(s.install)}" target="_blank" rel="noopener">get ${esc(s.name)}</a>, or <a href="${esc(fileUrl)}" download>download the STL</a> and drag it into any slicer. In Bambu Studio, accept the "open from an untrusted site" prompt.`;
+}
+
+/**
+ * Render the full handoff block: a size picker, one button per supported
+ * slicer, the STL and 3MF downloads, and the PrusaSlicer explanation.
+ *
+ * @param {HTMLElement} host
+ * @param {{ creationId: string, origin?: string }} opts
+ */
+export function renderSlicerHandoff(host, { creationId, origin = location.origin } = {}) {
+ injectStyles();
+ const urlFor = (format) => slicerModelUrl(origin, creationId, { format, sizeMm: Number(sizeSel.value) || null });
+ host.innerHTML = `
+ <div class="sh">
+ <div class="sh-row">
+ <label class="sh-note" for="sh-size-${esc(creationId)}">Print size</label>
+ <select class="sh-size" id="sh-size-${esc(creationId)}" aria-describedby="sh-size-note-${esc(creationId)}">
+ ${SIZES.map(([v, t]) => `<option value="${v}">${t}</option>`).join('')}
+ </select>
+ </div>
+ <p class="sh-note" id="sh-size-note-${esc(creationId)}">Auto keeps real-world units when the model has them and otherwise makes the longest side 100 mm. The file opens Z-up, on the bed, in millimetres.</p>
+ <div class="sh-row">
+ ${Object.values(SLICERS)
+ .map((s, i) => `<button class="sh-btn${i === 0 ? ' is-primary' : ''}" type="button" data-slicer="${s.id}">Open in ${esc(s.name)}</button>`)
+ .join('')}
+ <a class="sh-btn" data-format="stl" download>Download STL</a>
+ <a class="sh-btn" data-format="3mf" download>Download 3MF</a>
+ </div>
+ <p class="sh-help" role="status" aria-live="polite" hidden></p>
+ <p class="sh-note">${esc(PRUSA_NOTE)}</p>
+ </div>`;
+ const sizeSel = host.querySelector('.sh-size');
+ const help = host.querySelector('.sh-help');
+ const syncLinks = () => {
+ for (const a of host.querySelectorAll('a[data-format]')) a.href = urlFor(a.dataset.format);
+ };
+ sizeSel.addEventListener('change', () => {
+ syncLinks();
+ help.hidden = true;
+ });
+ syncLinks();
+ for (const btn of host.querySelectorAll('[data-slicer]')) {
+ btn.addEventListener('click', async () => {
+ if (btn.getAttribute('aria-busy') === 'true') return;
+ const slicer = SLICERS[btn.dataset.slicer];
+ const fileUrl = urlFor('stl');
+ btn.setAttribute('aria-busy', 'true');
+ help.hidden = false;
+ help.textContent = `Opening ${slicer.name}…`;
+ const opened = await openInSlicer(slicer, fileUrl);
+ btn.removeAttribute('aria-busy');
+ if (opened) {
+ help.textContent = `Sent to ${slicer.name}. It downloads the file itself, so give it a moment on large models.`;
+ } else {
+ help.innerHTML = missedHandoffHtml(slicer, fileUrl);
+ }
+ });
+ }
+}
+
+/**
+ * Add "Open in <slicer>" rows to a forge export menu. The rows reuse the menu's
+ * own `.export-item` markup so arrow-key navigation and styling apply to them
+ * unchanged, and stay hidden until the model has a stored creation id (a file
+ * dropped from disk has none, so there is nothing a slicer could download).
+ *
+ * @param {HTMLElement} menu the export menu (role="menu")
+ * @param {{ isLocalEdit?: () => boolean }} [opts] true while the viewer shows
+ * an unsaved in-browser edit, which the slicer cannot see
+ * @returns {{ setCreation: (id: string|null) => void }}
+ */
+export function mountSlicerMenuItems(menu, { isLocalEdit = () => false } = {}) {
+ let creationId = null;
+ const rows = Object.values(SLICERS).map((slicer) => {
+ const item = document.createElement('button');
+ item.type = 'button';
+ item.className = 'export-item';
+ item.setAttribute('role', 'menuitem');
+ item.dataset.slicer = slicer.id;
+ item.hidden = true;
+ item.innerHTML = `
+ <span class="fmt">${slicer.id === 'orca' ? 'Orca' : 'Bambu'}</span>
+ <span class="blurb">Open in ${esc(slicer.name)}: print-ready STL, Z-up, on the bed, in millimetres.</span>
+ <span class="status" aria-live="polite"></span>`;
+ const status = item.querySelector('.status');
+ item.addEventListener('click', async () => {
+ if (!creationId || item.getAttribute('aria-disabled') === 'true') return;
+ const fileUrl = slicerModelUrl(location.origin, creationId);
+ item.setAttribute('aria-disabled', 'true');
+ status.classList.remove('is-error');
+ status.textContent = 'opening';
+ const opened = await openInSlicer(slicer, fileUrl);
+ item.removeAttribute('aria-disabled');
+ if (opened) {
+ status.textContent = isLocalEdit() ? 'sent (saved model, not your edits)' : 'sent ✓';
+ } else {
+ status.innerHTML = `not installed? <a class="export-again" href="${esc(fileUrl)}" download>download STL</a> or <a class="export-again" href="${esc(slicer.install)}" target="_blank" rel="noopener">get it</a>`;
+ }
+ });
+ menu.appendChild(item);
+ return { item, status };
+ });
+ return {
+ setCreation(id) {
+ creationId = id && UUID_RE.test(id) ? id.toLowerCase() : null;
+ for (const { item, status } of rows) {
+ item.hidden = !creationId;
+ status.textContent = '';
+ status.classList.remove('is-error');
+ }
+ },
+ };
+}
diff --git a/tests/slicer-handoff.test.js b/tests/slicer-handoff.test.js
new file mode 100644
index 000000000..1aae0344e
--- /dev/null
+++ b/tests/slicer-handoff.test.js
@@ -0,0 +1,202 @@
+// Slicer handoff: the deep-link builder, the bed placement, and the real
+// /api/slicer route serving a GLB built in this file as STL and 3MF.
+
+import { createServer } from 'node:http';
+import { readFileSync } from 'node:fs';
+import { resolve } from 'node:path';
+
+import { Document, NodeIO } from '@gltf-transform/core';
+import { unzipSync, strFromU8 } from 'fflate';
+import { afterAll, beforeAll, describe, expect, it } from 'vitest';
+
+import {
+ SLICERS,
+ buildSlicerLink,
+ creationIdFromGlbUrl,
+ slicerModelUrl,
+} from '../src/slicer-handoff.js';
+import { placeOnBed, resolvePrintSize } from '../api/_lib/print/slicer.js';
+import { loadMesh } from '../api/_lib/print/mesh-io.js';
+import { readStlHeader } from '../api/_lib/print/export-stl.js';
+import { createSlicerModelHandler } from '../api/slicer/model.js';
+
+const ID = '5b1e8c21-6516-4741-ab2b-1efc838c0cdc';
+
+describe('slicer link builder', () => {
+ it('builds a path-only model URL that ends in model.<ext>', () => {
+ expect(slicerModelUrl('https://three.ws/', ID)).toBe(`https://three.ws/api/slicer/${ID}/model.stl`);
+ expect(slicerModelUrl('https://three.ws', ID.toUpperCase(), { format: '3mf', sizeMm: 80 })).toBe(
+ `https://three.ws/api/slicer/${ID}/80mm/model.3mf`,
+ );
+ expect(() => slicerModelUrl('https://three.ws', 'not-a-uuid')).toThrow(TypeError);
+ expect(() => slicerModelUrl('https://three.ws', ID, { format: 'obj' })).toThrow(TypeError);
+ });
+
+ it('percent-encodes the whole file URL into the slicer scheme', () => {
+ const file = slicerModelUrl('https://three.ws', ID);
+ const orca = buildSlicerLink('orca', file);
+ expect(orca).toBe(`orcaslicer://open?file=https%3A%2F%2Fthree.ws%2Fapi%2Fslicer%2F${ID}%2Fmodel.stl`);
+ expect(decodeURIComponent(orca.split('file=')[1])).toBe(file);
+ expect(buildSlicerLink(SLICERS.bambu, file)).toMatch(/^bambustudio:\/\/open\?file=https%3A/);
+ });
+
+ it('refuses URLs a slicer would mis-name or cannot fetch', () => {
+ expect(() => buildSlicerLink('orca', `https://three.ws/api/slicer/model?id=${ID}`)).toThrow(/query/);
+ expect(() => buildSlicerLink('orca', 'blob:https://three.ws/abc')).toThrow(/http/);
+ expect(() => buildSlicerLink('prusa', 'https://three.ws/model.stl')).toThrow(/unknown slicer/);
+ });
+
+ it('reads the creation id out of forge storage URLs', () => {
+ const base = 'https://pub-2534e921bf9c4314addcd4d8a6e98b7b.r2.dev/forge/ab12cd';
+ expect(creationIdFromGlbUrl(`${base}/${ID}.glb`)).toBe(ID);
+ expect(creationIdFromGlbUrl(`${base}/${ID.toUpperCase()}.web.glb`)).toBe(ID);
+ expect(creationIdFromGlbUrl('blob:https://three.ws/1234')).toBeNull();
+ expect(creationIdFromGlbUrl(null)).toBeNull();
+ });
+});
+
+describe('bed placement', () => {
+ it('keeps believable real-world sizes and rescales the rest to 100 mm', () => {
+ expect(resolvePrintSize(0.05)).toEqual({ longestMm: 50, mode: 'real' });
+ expect(resolvePrintSize(1)).toEqual({ longestMm: 100, mode: 'auto' });
+ expect(resolvePrintSize(0.001)).toEqual({ longestMm: 100, mode: 'auto' });
+ expect(resolvePrintSize(1, 80)).toEqual({ longestMm: 80, mode: 'requested' });
+ expect(() => resolvePrintSize(1, 900)).toThrow(RangeError);
+ });
+
+ it('turns Y-up into Z-up, rests on Z = 0 and centres in XY', () => {
+ // A 1 x 2 x 0.5 m box offset from the origin, tallest along glTF +Y.
+ const p = [];
+ for (const x of [3, 4]) for (const y of [1, 3]) for (const z of [-1, -0.5]) p.push(x, y, z);
+ const placed = placeOnBed(Float64Array.from(p));
+ expect(placed.mode).toBe('auto');
+ const min = [Infinity, Infinity, Infinity];
+ const max = [-Infinity, -Infinity, -Infinity];
+ for (let i = 0; i < placed.positions.length; i += 3) {
+ for (let a = 0; a < 3; a += 1) {
+ min[a] = Math.min(min[a], placed.positions[i + a]);
+ max[a] = Math.max(max[a], placed.positions[i + a]);
+ }
+ }
+ expect(min[2]).toBeCloseTo(0, 9);
+ expect(max[2]).toBeCloseTo(100, 9); // glTF height became slicer height
+ expect(max[0] - min[0]).toBeCloseTo(50, 9);
+ expect(max[1] - min[1]).toBeCloseTo(25, 9);
+ expect(min[0] + max[0]).toBeCloseTo(0, 9);
+ expect(min[1] + max[1]).toBeCloseTo(0, 9);
+ expect(placed.sizeMm.map((n) => Math.round(n))).toEqual([50, 25, 100]);
+ });
+});
+
+/** A closed, coloured tetrahedron as real GLB bytes: 4 triangles, 0.2 m tall. */
+async function tetraGlb() {
+ const doc = new Document();
+ const buffer = doc.createBuffer();
+ const positions = new Float32Array([0, 0, 0, 0.1, 0, 0, 0, 0, 0.1, 0.03, 0.2, 0.03]);
+ const indices = new Uint16Array([0, 1, 2, 0, 3, 1, 1, 3, 2, 2, 3, 0]);
+ const material = doc.createMaterial('red').setBaseColorFactor([1, 0, 0, 1]);
+ const prim = doc
+ .createPrimitive()
+ .setAttribute('POSITION', doc.createAccessor().setType('VEC3').setArray(positions).setBuffer(buffer))
+ .setIndices(doc.createAccessor().setType('SCALAR').setArray(indices).setBuffer(buffer))
+ .setMaterial(material);
+ doc.createScene('s').addChild(doc.createNode('n').setMesh(doc.createMesh('m').addPrimitive(prim)));
+ return new NodeIO().writeBinary(doc);
+}
+
+describe('GET /api/slicer/:id/model.stl', () => {
+ let server;
+ let base;
+ let loads = 0;
+
+ beforeAll(async () => {
+ const glb = await tetraGlb();
+ const handler = createSlicerModelHandler({
+ loadSource: async (id, { color }) => {
+ if (id !== ID) return null;
+ loads += 1;
+ return { mesh: await loadMesh(glb, { color }), title: 'A red test tetrahedron' };
+ },
+ });
+ server = createServer((req, res) => handler(req, res));
+ await new Promise((r) => server.listen(0, '127.0.0.1', r));
+ base = `http://127.0.0.1:${server.address().port}`;
+ });
+
+ afterAll(() => new Promise((r) => server.close(r)));
+
+ it('serves a binary STL in millimetres, Z-up, on the bed, with cache headers', async () => {
+ const res = await fetch(`${base}/api/slicer/model?id=${ID}&format=stl`);
+ expect(res.status).toBe(200);
+ expect(res.headers.get('content-type')).toBe('model/stl');
+ expect(res.headers.get('cache-control')).toMatch(/s-maxage=86400/);
+ expect(res.headers.get('etag')).toMatch(/^"slc-[0-9a-f]{32}"$/);
+ expect(res.headers.get('content-disposition')).toBe('attachment; filename="a-red-test-tetrahedron.stl"');
+ expect(res.headers.get('x-slicer-scale')).toBe('real');
+ const body = Buffer.from(await res.arrayBuffer());
+ expect(Number(res.headers.get('content-length'))).toBe(body.length);
+ const header = readStlHeader(body);
+ expect(header.triangles).toBe(4);
+ expect(body.length).toBe(84 + 4 * 50);
+ // Every vertex: Z >= 0 with the apex at 200 mm (the glTF 0.2 m height).
+ let minZ = Infinity;
+ let maxZ = -Infinity;
+ for (let t = 0; t < 4; t += 1) {
+ for (let v = 0; v < 3; v += 1) {
+ const z = body.readFloatLE(84 + t * 50 + 12 + v * 12 + 8);
+ minZ = Math.min(minZ, z);
+ maxZ = Math.max(maxZ, z);
+ }
+ }
+ expect(minZ).toBeCloseTo(0, 4);
+ expect(maxZ).toBeCloseTo(200, 3);
+ });
+
+ it('honours a requested size and answers a matching ETag with 304 from cache', async () => {
+ const first = await fetch(`${base}/api/slicer/model?id=${ID}&format=stl&size=80`);
+ expect(first.status).toBe(200);
+ expect(first.headers.get('x-slicer-size-mm').split(' x ').map(Number).sort((a, b) => b - a)[0]).toBe(80);
+ await first.arrayBuffer();
+ const before = loads;
+ const again = await fetch(`${base}/api/slicer/model?id=${ID}&format=stl&size=80`, {
+ headers: { 'if-none-match': first.headers.get('etag') },
+ });
+ expect(again.status).toBe(304);
+ expect(loads).toBe(before);
+ });
+
+ it('serves a coloured 3MF package', async () => {
+ const res = await fetch(`${base}/api/slicer/model?id=${ID}&format=3mf`);
+ expect(res.status).toBe(200);
+ expect(res.headers.get('content-type')).toBe('model/3mf');
+ const files = unzipSync(new Uint8Array(await res.arrayBuffer()));
+ const xml = strFromU8(files['3D/3dmodel.model']);
+ expect((xml.match(/<triangle /g) || []).length).toBe(4);
+ expect(xml).toMatch(/A red test tetrahedron/);
+ expect(xml).toMatch(/#FF0000/i);
+ });
+
+ it('rejects bad ids, formats and sizes, and 404s an unknown creation', async () => {
+ expect((await fetch(`${base}/api/slicer/model?id=nope&format=stl`)).status).toBe(400);
+ expect((await fetch(`${base}/api/slicer/model?id=${ID}&format=obj`)).status).toBe(400);
+ expect((await fetch(`${base}/api/slicer/model?id=${ID}&format=stl&size=4`)).status).toBe(400);
+ const missing = await fetch(`${base}/api/slicer/model?id=00000000-0000-4000-8000-000000000000&format=stl`);
+ expect(missing.status).toBe(404);
+ expect((await missing.json()).error).toBe('creation_not_found');
+ });
+
+ it('is reachable at the pretty path through the vercel.json route table', () => {
+ const routes = JSON.parse(readFileSync(resolve(import.meta.dirname, '../vercel.json'), 'utf8')).routes;
+ const rewrite = (path) => {
+ for (const r of routes) {
+ if (!r.src?.startsWith('/api/slicer/')) continue;
+ const m = new RegExp(`^${r.src}$`).exec(path);
+ if (m) return r.dest.replace(/\$(\d)/g, (_, i) => m[Number(i)]);
+ }
+ return null;
+ };
+ expect(rewrite(`/api/slicer/${ID}/model.stl`)).toBe(`/api/slicer/model?id=${ID}&format=stl`);
+ expect(rewrite(`/api/slicer/${ID}/120mm/model.3mf`)).toBe(`/api/slicer/model?id=${ID}&size=120&format=3mf`);
+ expect(rewrite(`/api/slicer/${ID}/model.obj`)).toBeNull();
+ });
+});