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.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
feat(print): wire the Materialize order flow from upload through quote to checkout
nirholas5c9ddbf5b3a9
diff --git a/api/print/certs/[id].js b/api/print/certs/[id].jsindex 68e87dca7..2f1ed0079 100644--- a/api/print/certs/[id].js+++ b/api/print/certs/[id].js@@ -29,9 +29,10 @@ export default wrap(async (req, res) => {const rl = await limits.mcp3dStatus(clientIp(req));if (!rl.success) return rateLimited(res, rl);- const url = new URL(req.url, 'http://localhost');- const raw = url.searchParams.get('id') || '';- const id = String(raw).trim().toLowerCase();+ // The router injects the `[id]` path segment into req.query; the path itself+ // is the fallback for a direct dispatch that skipped the router.+ const fromPath = String(req.url || '').split('?')[0].split('/').filter(Boolean).pop() || '';+ const id = String(req.query?.id ?? fromPath).trim().toLowerCase();if (!CERT_ID_RE.test(id)) {return json(res, 400, { error: 'invalid certificate id' });}diff --git a/api/print/prepare.js b/api/print/prepare.jsnew file mode 100644index 000000000..52d98a0b0--- /dev/null+++ b/api/print/prepare.js@@ -0,0 +1,214 @@+// POST /api/print/prepare: repair a model and write the files a printer takes.+//+// This is the step between "we measured your mesh" and "a machine can run it".+// It welds and re-winds the surface, fills the holes the generator left, closes+// it into a real solid, scales it to the ordered height, optionally hollows it+// for resin economy, and writes three artifacts to object storage:+//+// .stl binary, millimetres, what every slicer on earth reads+// .3mf the modern package, carrying per-vertex colour when the source had a+// texture, which is what makes a full-colour sandstone print possible+// .glb the repaired model itself, so the buyer can see exactly what will be+// printed rather than the mesh they uploaded+//+// It returns the before and after reports side by side. A repair the buyer+// cannot inspect is a repair the buyer cannot trust, and /materialize renders+// this response as the "what changed" list next to the model.+//+// Free and keyless like analyze: preparing a file costs CPU, not fulfillment,+// and a buyer who can see the repaired result is a buyer who orders.++import { createHash } from 'node:crypto';++import { Document, NodeIO } from '@gltf-transform/core';++import { cors, error, json, method, rateLimited, readJson, wrap } from '../_lib/http.js';+import { clientIp, limits } from '../_lib/rate-limit.js';+import { loadMeshFromUrl, MeshIoError, boundsOf } from '../_lib/print/mesh-io.js';+import { analyzeMesh } from '../_lib/print/analyze.js';+import { repairMesh, hollowSolid, scaleMesh, solidToArrays } from '../_lib/print/repair.js';+import { exportStl } from '../_lib/print/export-stl.js';+import { export3mf } from '../_lib/print/export-3mf.js';+import { findMaterial, loadCatalog } from '../_lib/print/quote.js';+import { getPublicCreation } from '../_lib/forge-store.js';+import { objectStorageConfigured, publicUrl, putObject } from '../_lib/r2.js';++const MESH_ERROR_STATUS = {+ invalid_model: 422,+ no_geometry: 422,+ too_large: 413,+ too_complex: 413,+ invalid_url: 400,+ fetch_failed: 502,+};++const MM_PER_METER = 1000;++/**+ * A minimal GLB carrying exactly the repaired geometry. Deliberately plain: no+ * materials, no textures, no node hierarchy, because its only job is to let the+ * viewer show the solid that will actually be printed. Colour lives in the 3MF,+ * which is the file a colour printer reads.+ */+async function writeGlb({ positions, indices }) {+ const doc = new Document();+ const buffer = doc.createBuffer();+ const vertices = new Float32Array(positions.length);+ for (let i = 0; i < positions.length; i += 1) vertices[i] = positions[i];++ const position = doc.createAccessor().setType('VEC3').setArray(vertices).setBuffer(buffer);+ const index = doc.createAccessor().setType('SCALAR').setArray(Uint32Array.from(indices)).setBuffer(buffer);+ const primitive = doc.createPrimitive().setAttribute('POSITION', position).setIndices(index);+ const mesh = doc.createMesh('prepared').addPrimitive(primitive);+ const node = doc.createNode('prepared').setMesh(mesh);+ doc.createScene('prepared').addChild(node);++ return Buffer.from(await new NodeIO().writeBinary(doc));+}++export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'POST,OPTIONS' })) return;+ if (!method(req, res, ['POST'])) return;++ const rate = await limits.printQuoteIp(clientIp(req));+ if (!rate.success) return rateLimited(res, rate, 'too many prepare requests');++ const body = await readJson(req, 8_000).catch(() => null);+ if (!body || typeof body !== 'object') {+ return error(res, 400, 'validation_error', 'a JSON body is required');+ }++ let sourceUrl = typeof body.glbUrl === 'string' ? body.glbUrl.trim() : '';+ let creationId = null;+ if (typeof body.creationId === 'string' && body.creationId.trim()) {+ const creation = await getPublicCreation({ id: body.creationId.trim() });+ if (!creation?.glb_url) {+ return error(res, 404, 'creation_not_found', 'No finished public creation with that id.');+ }+ sourceUrl = creation.glb_url;+ creationId = creation.id;+ }+ if (!sourceUrl) {+ return error(res, 400, 'validation_error', 'Pass a creationId or a glbUrl to prepare.');+ }++ if (!objectStorageConfigured()) {+ return error(+ res,+ 503,+ 'storage_unavailable',+ 'Object storage is not configured on this deployment, so prepared files cannot be written.',+ );+ }++ const material = body.materialId ? findMaterial(String(body.materialId)) : null;+ if (body.materialId && !material) {+ return error(res, 422, 'unknown_material', `No material with id "${body.materialId}".`);+ }++ let mesh;+ let before;+ try {+ mesh = await loadMeshFromUrl(sourceUrl);+ before = await analyzeMesh(mesh, { sourceUrl });+ } catch (err) {+ if (err instanceof MeshIoError) {+ return error(res, MESH_ERROR_STATUS[err.code] ?? 422, err.code, err.message, err.extra || {});+ }+ throw err;+ }++ const repaired = await repairMesh(mesh);++ // Scale to the ordered height before hollowing: the wall thickness a material+ // asks for is a real millimetre measurement, so the erosion has to happen on+ // the mesh at the size it will be printed, not on the source mesh.+ const targetHeightMm = Number(body.targetHeightMm);+ const nativeHeightMm = (boundsOf(repaired.positions)?.size?.[1] ?? 0) * MM_PER_METER;+ const scale = targetHeightMm > 0 && nativeHeightMm > 0 ? targetHeightMm / nativeHeightMm : 1;++ let positions = scale === 1 ? repaired.positions : scaleMesh(repaired.positions, scale);+ let indices = repaired.indices;+ let hollow = { hollowed: false, reason: 'not-requested' };++ if (body.hollow && material?.hollow?.supported) {+ const scaledSolid = scale === 1 ? repaired.solid : repaired.solid.scale([scale, scale, scale]);+ hollow = hollowSolid(repaired.wasm, scaledSolid, {+ // The catalog's wall is in millimetres; the mesh is in metres.+ wallThickness: material.hollow.wallMm / MM_PER_METER,+ });+ if (hollow.hollowed) {+ const arrays = solidToArrays(hollow.solid);+ positions = arrays.positions;+ indices = arrays.indices;+ }+ } else if (body.hollow) {+ hollow = { hollowed: false, reason: material ? 'material-does-not-hollow' : 'no-material-chosen' };+ }++ const prepared = { positions, indices, colors: null };+ const after = await analyzeMesh(prepared, { sourceUrl });++ const stl = exportStl(prepared, { requireWatertight: true, openEdges: after.open_edges });+ const threeMf = export3mf(prepared, {+ title: creationId ? `three.ws creation ${creationId}` : 'three.ws Materialize print',+ description: `Prepared ${new Date().toISOString().slice(0, 10)} from ${sourceUrl}`,+ });+ const glb = await writeGlb(prepared);++ // One folder per (source, size, hollow) so a re-prepare of the same order+ // overwrites rather than accumulating, and two different sizes never collide.+ const digest = createHash('sha256')+ .update(`${sourceUrl}|${Math.round(targetHeightMm || 0)}|${hollow.hollowed ? 1 : 0}|${material?.id || ''}`)+ .digest('hex')+ .slice(0, 20);+ const prefix = `print/prepared/${digest}`;++ const [stlKey, mfKey, glbKey] = [`${prefix}/model.stl`, `${prefix}/model.3mf`, `${prefix}/model.glb`];+ await Promise.all([+ putObject({ key: stlKey, body: stl, contentType: 'model/stl', metadata: { source: 'materialize' } }),+ putObject({ key: mfKey, body: threeMf, contentType: 'model/3mf', metadata: { source: 'materialize' } }),+ putObject({ key: glbKey, body: glb, contentType: 'model/gltf-binary', metadata: { source: 'materialize' } }),+ ]);++ return json(+ res,+ 200,+ {+ sourceUrl,+ creationId,+ assets: {+ stl: publicUrl(stlKey),+ threemf: publicUrl(mfKey),+ glb: publicUrl(glbKey),+ bytes: { stl: stl.length, threemf: threeMf.length, glb: glb.length },+ },+ before,+ after,+ // Exactly what changed, in the buyer's terms. Every number here was+ // measured, not asserted.+ repair: {+ strategy: repaired.strategy,+ holesFilled: repaired.metrics.holesFilled,+ patchTriangles: repaired.metrics.patchTriangles,+ mergedVertices: repaired.metrics.mergedVertices,+ degenerateRemoved: repaired.metrics.degenerateRemoved,+ duplicateRemoved: repaired.metrics.duplicateRemoved,+ trianglesFlipped: repaired.metrics.trianglesFlipped,+ trianglesBefore: repaired.metrics.trianglesBefore,+ trianglesAfter: repaired.metrics.trianglesAfter,+ shells: repaired.metrics.shells,+ elapsedMs: repaired.metrics.elapsedMs,+ },+ hollow: {+ applied: hollow.hollowed,+ reason: hollow.reason,+ wallMm: hollow.hollowed ? material.hollow.wallMm : null,+ drainHoles: hollow.metrics?.drainHoles ?? 0,+ },+ targetHeightMm: targetHeightMm > 0 ? Math.round(targetHeightMm * 10) / 10 : null,+ catalogVersion: loadCatalog().version,+ },+ { 'cache-control': 'no-store' },+ );+});diff --git a/api/print/upload.js b/api/print/upload.jsnew file mode 100644index 000000000..5d6892997--- /dev/null+++ b/api/print/upload.js@@ -0,0 +1,99 @@+// POST /api/print/upload: a short-lived presigned slot for a model you want printed.+//+// The printability analyzer reads a model by URL, so a .glb sitting on someone's+// laptop needs somewhere to be first. This hands back a presigned PUT straight to+// object storage; the browser sends the bytes there and then passes the returned+// public URL to /api/print/quote. Multi-megabyte meshes never travel through this+// function.+//+// Mirrors api/forge-upload.js, which does the same for /forge reference images:+// same presign helper, same degrade-to-503 when storage is unconfigured, same+// anonymous client scoping so uploads land under a stable prefix without an+// account. The difference is the accepted type (a glTF binary, not an image) and+// the size ceiling, which matches what the analyzer will agree to read.++import { randomUUID } from 'node:crypto';++import { cors, json, method, rateLimited, readJson, wrap } from '../_lib/http.js';+import { clientIp, limits } from '../_lib/rate-limit.js';+import { objectStorageConfigured, presignUpload, publicUrl } from '../_lib/r2.js';+import { hashClient } from '../_lib/forge-store.js';+import { MAX_INPUT_BYTES } from '../_lib/print/mesh-io.js';++// The one type a print pipeline can read. A .gltf with external buffers would+// need its siblings uploaded too, which is a worse experience than telling the+// caller to export a self-contained binary.+const ACCEPTED = Object.freeze({+ 'model/gltf-binary': 'glb',+ 'application/octet-stream': 'glb',+});++export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'POST,OPTIONS' })) return;+ if (!method(req, res, ['POST'])) return;++ if (!objectStorageConfigured()) {+ return json(res, 503, {+ error: 'unconfigured',+ message:+ 'Model upload is not configured on this deployment (object storage missing). ' ++ 'Pass a public .glb URL to /api/print/quote instead.',+ });+ }++ const rl = await limits.upload(`print:${clientIp(req)}`);+ if (!rl.success) return rateLimited(res, rl, 'Upload limit reached. Try again shortly.');++ const body = await readJson(req, 2_000).catch(() => null);+ const contentType = typeof body?.content_type === 'string' ? body.content_type.trim().toLowerCase() : '';+ // Object.hasOwn rather than a truthy lookup: a frozen map still has its+ // prototype, so "constructor" would otherwise resolve to a function and pass.+ const ext = Object.hasOwn(ACCEPTED, contentType) ? ACCEPTED[contentType] : null;+ if (!ext) {+ return json(res, 400, {+ error: 'invalid_content_type',+ message: 'content_type must be model/gltf-binary. Export a self-contained .glb.',+ });+ }++ const size = Number(body?.size_bytes);+ if (!Number.isFinite(size) || size <= 0 || size > MAX_INPUT_BYTES) {+ return json(res, 400, {+ error: 'invalid_size',+ message: `size_bytes must be between 1 and ${MAX_INPUT_BYTES} bytes, the ceiling the analyzer will read.`,+ });+ }++ const checksum =+ typeof body?.checksum_sha256 === 'string' && /^[a-f0-9]{64}$/.test(body.checksum_sha256)+ ? body.checksum_sha256+ : undefined;++ const rawClient = req.headers['x-forge-client'];+ const clientKey = hashClient(Array.isArray(rawClient) ? rawClient[0] : rawClient);+ const key = `print/uploads/${clientKey.slice(0, 12)}/${randomUUID()}.${ext}`;++ let uploadUrl;+ try {+ uploadUrl = await presignUpload({ key, contentType, ...(checksum ? { checksumSha256: checksum } : {}) });+ } catch (err) {+ return json(res, 502, {+ error: 'presign_failed',+ message: `Could not open an upload slot: ${err?.message || 'storage unavailable'}`,+ });+ }++ return json(+ res,+ 200,+ {+ storage_key: key,+ upload_url: uploadUrl,+ public_url: publicUrl(key),+ method: 'PUT',+ headers: { 'content-type': contentType },+ expires_in: 600,+ },+ { 'cache-control': 'no-store' },+ );+});diff --git a/docs/materialize.md b/docs/materialize.mdnew file mode 100644index 000000000..151ea1427--- /dev/null+++ b/docs/materialize.md@@ -0,0 +1,311 @@+# Materialize: turn a generation into a real object++Materialize is the physical lane of the forge. You describe something, three.ws+generates the 3D model, and then Materialize prints it in resin, nylon, colour+sandstone or steel and ships it to your door. The whole loop lives on one page+at [/materialize](https://three.ws/materialize), and every step of it is also an+API, so an autonomous agent can order a physical object of a model it just+generated without a human touching anything.++That last part is the headline. Print bureaus have upload forms and AI 3D+vendors have download buttons; nobody else closes prompt to object in one+surface, and as far as we know this is the first API where an AI agent can pay+for manufacturing.++**New to three.ws 3D?** Generate something first at+[/forge](https://three.ws/forge) ([Forge](./forge.md)), then come back. You can+also print a `.glb` you already have.++---++## The flow++```+ a forge creation a GLB you upload an agent+ /m/:id "Materialize" /materialize POST /api/print/quote+ │ │ │+ └───────────────┬───────────┴───────────────────────────┘+ ▼+ POST /api/print/quote printability report + itemized price+ │ + a signed quote token (24 hours)+ ▼+ POST /api/print/orders human checkout, USDC on Solana+ POST /api/x402/print-order agent checkout, x402, same pipeline+ ▼+ safety screening ──▶ production ──▶ quality check ──▶ shipped+ ▼+ certificate of authenticity, attested on Solana, QR in the box+```++### 1. Analysis, free and keyless++Every model is measured before it is priced. `POST /api/print/quote` with just a+model returns the **printability report**: whether the mesh is a closed solid,+how many separate bodies it contains, where its holes are, the thinnest wall it+has, its exact volume, and a 0-100 score with named deductions written for a+human rather than a mesh engineer.++```bash+curl -s https://three.ws/api/print/quote \+ -H 'content-type: application/json' \+ -d '{"creationId":"<a three.ws creation id>"}'+```++No key, no account, no charge. AI-generated meshes are the worst case the+printing world sees (non-manifold shells, paper-thin decorations, detail that+lives in a texture rather than in geometry), so the report is blunt about what+it found and about what preparation will fix automatically.++### 2. Preparation++`POST /api/print/prepare` reconstructs the mesh as a solid, fills its holes,+scales it to your chosen height, optionally hollows it (with drain holes, which+is what makes a large resin print affordable), and exports the files a bureau+actually loads: binary STL, 3MF, and the repaired GLB. Full-colour materials get+per-vertex colour sampled from the source texture, which is what makes a colour+print possible from a model that only ever had a 2K albedo map.++### 3. Quote++Pick a material, a height and a quantity, and the same endpoint returns an+itemized price and a signed token:++```bash+curl -s https://three.ws/api/print/quote \+ -H 'content-type: application/json' \+ -d '{+ "creationId": "<creation id>",+ "materialId": "resin-standard",+ "targetHeightMm": 120,+ "quantity": 1,+ "country": "US"+ }'+```++Every line is shown: build setup, material with the exact cm3 it was computed+from, finish, quantity break, `$THREE` holder discount, shipping. The token+carries every priced parameter inside its signature and expires in 24 hours, so+a price cannot be replayed stale or edited on its way to checkout.++If the mesh cannot be printed in that material, you get guidance instead of an+error: the measured number, the required number, the fix, and every material+that would take the model as-is.++### 4. Checkout++Payment is **USDC on Solana**. There is no card processor, and the quote panel+says so plainly.++- **People:** `POST /api/print/orders` from the `/materialize` page with the+ token and a shipping address.+- **Agents:** `POST /api/x402/print-order`. See [the agent lane](#the-agent-lane).++### 5. Production and tracking++A paid order moves through `screening` (safety and printability), `submitted`,+`printing`, `quality_check`, `shipped`, `delivered`. Every change appends to a+timeline you can read at `GET /api/print/orders/:id`, and the page at+`/materialize/orders/:id` renders the same thing for humans.++---++## Materials++`GET /api/print/catalog` is the live source of truth. As of catalog version 1:++| Material | Class | Min wall | Height range | Lead time | Colour |+|---|---|---|---|---|---|+| Standard resin | resin | 0.6 mm | 15 to 180 mm | 5 days | no |+| Tough resin | resin | 1.0 mm | 15 to 180 mm | 6 days | no |+| SLS nylon (PA12) | sls_nylon | 0.8 mm | 12 to 280 mm | 7 days | no |+| Full-colour sandstone | full_color | 2.0 mm | 20 to 200 mm | 8 days | yes |+| PLA draft | fdm_draft | 1.2 mm | 20 to 250 mm | 3 days | no |+| 316L stainless steel | metal | 1.0 mm | 10 to 120 mm | 15 days | no |++Standard resin is the default for figures and detailed props. SLS nylon is the+one to pick for something that has to survive being handled. Full-colour+sandstone is the only material that reproduces your model's texture. Steel is+quote-on-request: it is priced as an estimate and never issues a checkout token,+because nothing should be bought at a number an engineer has not confirmed.++**Min wall matters more than anything else.** A model whose thinnest wall is+0.3 mm at 80 mm tall is 0.6 mm at 160 mm tall. The report's+`recommended_min_height_mm` tells you, per material class, exactly how tall the+object has to be printed for its detail to survive, and the page's size slider+is bounded by it so you cannot drag into a rejection.++---++## How pricing works++Every number a buyer sees comes from the quote engine+(`api/_lib/print/quote.js`) reading one file, `data/print-catalog.json`. No+price is ever computed in the browser.++```+total = setup+ + rate_per_cm3 × volume_cm3 × quantity+ + finish fees+ + shipping (volumetric weight, by zone)+ − quantity break (8% at 5 units, 15% at 20)+ − $THREE holder discount (up to 15%, never on shipping)+```++Volume is the number money hangs off, so it comes from the Manifold kernel's+exact volume of the repaired solid, never from an estimate over a broken mesh.+Hollowing changes that volume and therefore the price, visibly, in the same+itemization.++Shipping is zoned: `cn`, `us`, `eu`, `row`, priced on volumetric weight from the+printed bounding box plus packaging. It is passed through, and the holder+discount never touches it.++---++## The agent lane++`POST /api/x402/print-order` is the endpoint where an AI agent pays and a+physical object gets manufactured and shipped.++The order of operations is the product: the quote token and the shipping address+are validated **before** any 402 is issued, so a malformed order is refused for+free with a `422` and a caller never pays for something that was going to be+rejected. The 402 then quotes that token's own total, because every print is its+own object with its own price.++```bash+# 1. Quote (free, keyless). Keep `token` from the response.+curl -s https://three.ws/api/print/quote \+ -H 'content-type: application/json' \+ -d '{"creationId":"<creation id>","materialId":"resin-standard","targetHeightMm":120,"quantity":1,"country":"GB"}'++# 2. Order. The first call answers 402 with the exact amount from that token.+curl -s -X POST https://three.ws/api/x402/print-order \+ -H 'content-type: application/json' \+ -d '{+ "token": "pq1....",+ "shipping": {+ "name": "Ada Lovelace",+ "line1": "12 Analytical Way",+ "city": "London",+ "postal_code": "EC1A 1AA",+ "country": "GB"+ }+ }'++# 3. Settle the 402 the usual x402 way and repeat the call with the payment+# header. The response carries the order id.++# 4. Track it, with no account.+curl -s https://three.ws/api/print/orders/<order id>+```++The shipping block is the minimum a courier needs and is the only personal data+the platform stores for a print. It is never logged and never enters an+analytics event.++See [x402 payments](./a2a-payments.md) for the settlement mechanics, and+[specs/PRINT_PIPELINE.md](../specs/PRINT_PIPELINE.md) for every wire contract.++---++## Certificates++Every shipped print gets a certificate of authenticity, and it is not a printed+card with a logo on it. It is three things:++1. The **SHA-256 of the exact file** that was manufactured, plus the hash of the+ viewable GLB.+2. An **edition number**, enforced in the database, so edition 3 of 25 is+ actually the third one that shipped.+3. A **Solana memo transaction** carrying both, signed by the platform.++The box carries a QR to `/cert/<id>`, which renders the original model spinning,+the prompt lineage that produced it, the edition, and the raw memo payload. That+last part is the point: you verify a print by hashing the file and comparing it+to the string in the transaction, with no dependency on this database, this+company, or any block explorer staying online.++A certificate whose signature is still in flight is a real certificate whose+proof has not landed yet, and the page says exactly that rather than pretending.++---++## Content policy++Physical manufacturing raises the stakes of everything a platform moderates. A+refused image generation costs nothing; a printed firearm component is a crime+in most of the places we ship to, and a printed key to somebody's door is a+burglary tool. So the line is code, not a suggestion.++**three.ws does not manufacture:**++- **Firearm components.** Receivers and frames, trigger and fire-control parts,+ barrels, bolt carriers, slides, conversion devices, and anything sold as an+ unfinished or unserialized firearm.+- **Suppressors**, including the parts marketed as solvent traps that convert+ into them.+- **Ammunition**, ammunition components, magazines and feeding devices.+- **Keys and lock-bypass tools.** A working key, a pick, a shim or a jiggler is+ a burglary tool no matter who orders it.+- **Counterfeit goods**, other parties' brand marks, authentication tags,+ holograms, serial plates and currency.+- **Working weapon mechanisms.** Concealed or spring-loaded blades, automatic+ and butterfly knives, knuckles, garrotes, caltrops and tyre spikes.+- **Drug paraphernalia** and equipment for producing or pressing controlled+ substances.+- **Realistic firearm likenesses at or near life size.**+- Anything the generation content policy already refuses: sexual content,+ graphic gore, and hateful or extremist iconography.++**What is fine, and this is most of what people print:** characters, creatures,+figurines, props, jewellery, ornaments, enclosures, tools, replacement parts,+architectural models, and stylised or fantasy weapons. A tabletop miniature+carrying a weapon prints; the same design at 210 mm does not. A prop sword with+a blunt edge, printed as one piece, prints; a spring-loaded blade does not. Your+own logo prints; somebody else's does not.++### How it is enforced++The gate runs twice, and the second run is the one that matters.++1. **At quote time**, before any money moves, using only deterministic checks+ (the content classifier, a structured denylist with a test per category, and+ the printed size of the object). It never waits on a model, so a refusal is+ instant and a price is never blocked by a third-party outage. A refused+ request gets `HTTP 451` naming the category, linking this policy, and saying+ what is allowed instead.+2. **After payment**, on the way to the printer, a language model reviews the+ same prompt lineage, model title and buyer note. It can add a refusal;+ it can never lift one the denylist made. An order that fails moves to `rejected`,+ which is the refund path, and an operator is told so a human sees every edge+ case.++An order reaches a printer only with a recorded `allow` verdict on it. There is+no path through the operator console that skips this.++If you think a refusal is wrong, the order timeline names the exact category and+matched term, which is what a human needs to overturn it.+[specs/PRINT_PIPELINE.md](../specs/PRINT_PIPELINE.md#4-fabrication-gate-verdict)+documents the verdict shape and, just as importantly, what the gate cannot do.++---++## Limits and what is not built yet++- **Single objects only.** Multi-part assemblies, which need splitting and+ joinery, are not in scope yet. A part larger than the build envelope is+ refused with the reason rather than silently split.+- **No card payments.** USDC on Solana, by design.+- **No paint or finishing marketplace**, no creator royalties on physical sales,+ and no physical goods marketplace. All of those are designed for in the+ schema and none of them are half-built.++---++## Related++- [Forge](./forge.md), where the models come from+- [The Forge pipeline](./forge-pipeline.md), the generation engineering guide+- [specs/PRINT_PIPELINE.md](../specs/PRINT_PIPELINE.md), every wire contract+- [API reference](./api-reference.md), the `/api/print/*` endpointsdiff --git a/pages/materialize-order.html b/pages/materialize-order.htmlnew file mode 100644index 000000000..6bb58cfe8--- /dev/null+++ b/pages/materialize-order.html@@ -0,0 +1,170 @@+<!doctype html>+<html lang="en">+<head>+ <script>/* three.ws theme boot */(function(){document.documentElement.classList.add('js');try{var m=localStorage.getItem('twx_theme');var l=m==='auto'?(window.matchMedia&&window.matchMedia('(prefers-color-scheme: light)').matches):m==='light';document.documentElement.setAttribute('data-theme',l?'light':'dark');}catch(e){document.documentElement.setAttribute('data-theme','dark');}})();</script>+ <meta charset="utf-8" />+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />+ <title>Your print · Materialize · three.ws</title>+ <meta name="description" content="Track a three.ws Materialize print order from quote to doorstep: every status change with its real timestamp, the prepared model, tracking once it ships, and the on-chain certificate." />+ <meta name="robots" content="noindex, follow" />+ <link rel="icon" href="/favicon.ico" sizes="any" />+ <link rel="stylesheet" href="/style.css" />+ <link rel="stylesheet" href="/nav.css" />+ <link rel="stylesheet" href="/fonts/fonts.css" />+ <script src="/model-viewer-meshopt.js"></script>+ <script type="module" src="https://ajax.googleapis.com/ajax/libs/model-viewer/4.0.0/model-viewer.min.js" integrity="sha384-sr9b4Ux0WhAUGclJ0ym0FSY2zSOMmNSn0bP/SA0e6bNCrpn/5W3QL8mm+LdlQMKw" crossorigin="anonymous"></script>+ <style>+ :root {+ --mo-line: rgba(255, 255, 255, 0.09);+ --mo-panel: rgba(255, 255, 255, 0.032);+ --mo-ink-2: rgba(255, 255, 255, 0.6);+ --mo-ink-3: rgba(255, 255, 255, 0.4);+ --mo-done: #2fbf71;+ --mo-warn: #e0a33a;+ --mo-stop: #e05a4a;+ --mo-accent: var(--accent, #7c5cff);+ }+ [data-theme='light'] {+ --mo-line: rgba(0, 0, 0, 0.11);+ --mo-panel: rgba(0, 0, 0, 0.024);+ --mo-ink-2: rgba(0, 0, 0, 0.64);+ --mo-ink-3: rgba(0, 0, 0, 0.46);+ }++ .mo-wrap { max-width: 980px; margin: 0 auto; padding: clamp(1.25rem, 3.5vw, 2.75rem) 1.1rem 5rem; }+ .mo-back { display: inline-flex; align-items: center; gap: 0.4rem; font-size: 12.5px; color: var(--mo-ink-3); text-decoration: none; margin-bottom: 1.1rem; }+ .mo-back:hover { color: inherit; }+ .mo-back:focus-visible { outline: 2px solid var(--mo-accent); outline-offset: 3px; border-radius: 6px; }++ .mo-head { display: grid; grid-template-columns: minmax(0, 300px) minmax(0, 1fr); gap: 1.4rem; align-items: start; margin-bottom: 1.6rem; }+ @media (max-width: 760px) { .mo-head { grid-template-columns: 1fr; } }+ .mo-stage {+ border: 1px solid var(--mo-line); border-radius: 16px; overflow: hidden; aspect-ratio: 1;+ background: radial-gradient(120% 90% at 50% 8%, rgba(255, 255, 255, 0.07), transparent 62%), var(--mo-panel);+ }+ .mo-stage model-viewer { width: 100%; height: 100%; background: transparent; }+ .mo-stage-empty { width: 100%; height: 100%; display: grid; place-content: center; gap: 0.5rem; justify-items: center; color: var(--mo-ink-3); font-size: 12.5px; }++ .mo-eyebrow { font-size: 11px; font-weight: 700; letter-spacing: 0.09em; text-transform: uppercase; color: var(--mo-ink-3); margin: 0 0 0.6rem; }+ .mo-title { font-size: clamp(1.4rem, 3.6vw, 2rem); font-weight: 800; letter-spacing: -0.03em; line-height: 1.1; margin: 0 0 0.7rem; }+ .mo-sub { font-size: 13.5px; line-height: 1.6; color: var(--mo-ink-2); margin: 0 0 1rem; }+ .mo-specs { list-style: none; margin: 0; padding: 0; display: grid; grid-template-columns: repeat(auto-fit, minmax(130px, 1fr)); gap: 0.55rem; }+ .mo-spec { border: 1px solid var(--mo-line); border-radius: 10px; padding: 0.5rem 0.65rem; }+ .mo-spec dt { font-size: 10.5px; font-weight: 700; letter-spacing: 0.06em; text-transform: uppercase; color: var(--mo-ink-3); margin: 0 0 0.15rem; }+ .mo-spec dd { font-size: 13px; margin: 0; font-weight: 600; }++ .mo-panel { border: 1px solid var(--mo-line); border-radius: 16px; background: var(--mo-panel); padding: 1.2rem 1.2rem 1.35rem; }+ .mo-panel + .mo-panel { margin-top: 0.9rem; }+ .mo-h2 { font-size: 13px; font-weight: 700; letter-spacing: 0.06em; text-transform: uppercase; color: var(--mo-ink-3); margin: 0 0 1rem; }++ /* The rail */+ .mo-rail { list-style: none; margin: 0; padding: 0; display: grid; gap: 0; }+ .mo-step { position: relative; display: grid; grid-template-columns: 26px 1fr; gap: 0.85rem; padding-bottom: 1.15rem; }+ .mo-step:last-child { padding-bottom: 0; }+ .mo-step::before {+ content: ''; position: absolute; left: 12px; top: 22px; bottom: 0; width: 2px; background: var(--mo-line);+ }+ .mo-step:last-child::before { display: none; }+ .mo-step.is-done::before { background: var(--mo-done); }+ .mo-dot {+ width: 26px; height: 26px; border-radius: 50%; display: grid; place-content: center; z-index: 1;+ border: 2px solid var(--mo-line); background: var(--bg, #0b0b0f); color: var(--mo-ink-3); font-size: 11px; font-weight: 700;+ }+ .mo-step.is-done .mo-dot { border-color: var(--mo-done); color: var(--mo-done); }+ .mo-step.is-current .mo-dot { border-color: var(--mo-accent); color: var(--mo-accent); box-shadow: 0 0 0 4px rgba(124, 92, 255, 0.16); }+ .mo-step.is-current .mo-dot::after {+ content: ''; width: 8px; height: 8px; border-radius: 50%; background: currentColor; animation: mo-pulse 1.8s ease-in-out infinite;+ }+ @keyframes mo-pulse { 0%, 100% { opacity: 1; transform: scale(1); } 50% { opacity: 0.45; transform: scale(0.75); } }+ @media (prefers-reduced-motion: reduce) { .mo-step.is-current .mo-dot::after { animation: none; } }+ .mo-step.is-stopped { opacity: 0.4; }+ .mo-step-label { font-size: 14px; font-weight: 640; margin: 3px 0 0.15rem; }+ .mo-step-blurb { font-size: 12.5px; line-height: 1.5; color: var(--mo-ink-2); margin: 0; }+ .mo-step-at { font-size: 11.5px; color: var(--mo-ink-3); margin: 0.25rem 0 0; }+ .mo-step-note { font-size: 12.5px; line-height: 1.5; margin: 0.35rem 0 0; padding: 0.45rem 0.6rem; border-left: 2px solid var(--mo-line); color: var(--mo-ink-2); }++ .mo-waiting { display: flex; gap: 0.55rem; align-items: flex-start; font-size: 12.5px; line-height: 1.55; color: var(--mo-ink-2); margin-top: 1.1rem; padding-top: 1rem; border-top: 1px solid var(--mo-line); }+ .mo-waiting svg { flex: none; margin-top: 2px; color: var(--mo-ink-3); }++ .mo-branch { border-left: 3px solid var(--mo-stop); border-radius: 10px; background: rgba(224, 90, 74, 0.08); padding: 0.85rem 0.95rem; margin-bottom: 1.1rem; }+ .mo-branch h3 { font-size: 13.5px; font-weight: 660; margin: 0 0 0.3rem; }+ .mo-branch p { font-size: 12.5px; line-height: 1.55; color: var(--mo-ink-2); margin: 0; }++ .mo-row { display: flex; flex-wrap: wrap; gap: 0.55rem; align-items: center; }+ .mo-btn {+ font: inherit; font-size: 13px; font-weight: 620; padding: 9px 16px; border-radius: 10px; cursor: pointer; text-decoration: none;+ border: 1px solid var(--mo-line); background: transparent; color: inherit; display: inline-flex; align-items: center; gap: 0.4rem;+ transition: border-color 0.16s ease, transform 0.12s ease;+ }+ .mo-btn:hover { border-color: currentColor; transform: translateY(-1px); }+ .mo-btn:focus-visible { outline: 2px solid var(--mo-accent); outline-offset: 2px; }+ .mo-mono { font-family: ui-monospace, SFMono-Regular, Menlo, monospace; font-size: 12px; word-break: break-all; }++ .mo-skel { height: 15px; border-radius: 6px; background: rgba(128, 128, 128, 0.16); animation: mo-fade 1.4s ease-in-out infinite; }+ @keyframes mo-fade { 0%, 100% { opacity: 0.4; } 50% { opacity: 0.8; } }+ @media (prefers-reduced-motion: reduce) { .mo-skel { animation: none; } }+ .mo-notice { border: 1px solid var(--mo-line); border-left-width: 3px; border-left-color: var(--mo-stop); border-radius: 12px; padding: 0.95rem 1rem; font-size: 13.5px; line-height: 1.6; }+ .mo-notice h2 { font-size: 15px; font-weight: 680; margin: 0 0 0.4rem; }+ .mo-notice p { color: var(--mo-ink-2); margin: 0 0 0.7rem; }+ </style>+</head>+<body>+ <div class="mo-wrap">+ <a class="mo-back" href="/materialize">+ <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.4" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M15 18l-6-6 6-6" /></svg>+ Materialize+ </a>++ <div id="mo-loading">+ <div class="mo-panel">+ <div class="mo-skel" style="width: 44%; margin-bottom: 0.9rem;"></div>+ <div class="mo-skel" style="width: 76%; margin-bottom: 0.6rem;"></div>+ <div class="mo-skel" style="width: 62%;"></div>+ </div>+ </div>++ <div id="mo-error" hidden></div>++ <main id="mo-main" hidden>+ <div class="mo-head">+ <div class="mo-stage" id="mo-stage">+ <div class="mo-stage-empty" id="mo-stage-empty">+ <svg width="30" height="30" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.3" aria-hidden="true"><path d="M12 2 3 7v10l9 5 9-5V7z" /><path d="M3 7l9 5 9-5M12 12v10" /></svg>+ <span>Preparing the print file</span>+ </div>+ </div>+ <div>+ <p class="mo-eyebrow" id="mo-eyebrow">Materialize order</p>+ <h1 class="mo-title" id="mo-title">Your print</h1>+ <p class="mo-sub" id="mo-sub"></p>+ <dl class="mo-specs" id="mo-specs"></dl>+ </div>+ </div>++ <div class="mo-panel">+ <h2 class="mo-h2">Progress</h2>+ <div id="mo-branch"></div>+ <ol class="mo-rail" id="mo-rail"></ol>+ <div class="mo-waiting" id="mo-waiting" hidden>+ <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" aria-hidden="true"><circle cx="12" cy="12" r="9" /><path d="M12 7v5l3 2" /></svg>+ <span id="mo-waiting-text"></span>+ </div>+ </div>++ <div class="mo-panel" id="mo-ship-panel" hidden>+ <h2 class="mo-h2">Shipment</h2>+ <div class="mo-row" id="mo-ship-row"></div>+ </div>++ <div class="mo-panel" id="mo-cert-panel" hidden>+ <h2 class="mo-h2">Certificate</h2>+ <p class="mo-sub" id="mo-cert-text"></p>+ <div class="mo-row" id="mo-cert-row"></div>+ </div>+ </main>+ </div>++ <script src="/nav.js"></script>+ <script type="module" src="/src/materialize-order.js"></script>+</body>+</html>diff --git a/specs/PRINT_PIPELINE.md b/specs/PRINT_PIPELINE.mdnew file mode 100644index 000000000..be7c6da0c--- /dev/null+++ b/specs/PRINT_PIPELINE.md@@ -0,0 +1,382 @@+# Materialize print pipeline v1++The wire contracts that turn a three.ws generation into a physical object. Every+shape below is produced or consumed by shipped code, and other code depends on+each one, so this file is a contract rather than a tutorial.++- **Surface:** [Materialize](../docs/materialize.md), routes `/materialize` and `/api/print/*`+- **Companion specs:** [PROVENANCE_3D.md](PROVENANCE_3D.md) (digital provenance), [SERVICE_CATALOG.md](SERVICE_CATALOG.md) (paid endpoint discovery)+- **Implementations:** `api/_lib/print/` (engine, quote, gate, adapters, certificates), `api/_lib/print-store.js` (state machine), `api/print/*` (HTTP)++Six contracts are versioned here. Each one carries its own integer `version` or+`v` field on the wire; a change that removes or repurposes a field is a version+bump, not a tweak.++| Contract | Version field | Owner module |+|---|---|---|+| Printability report | `version: 1` | `api/_lib/print/analyze.js` |+| Quote token | `v: 1` inside the payload | `api/_lib/print/quote.js` |+| Order state machine | statuses are the contract | `api/_lib/print-store.js` |+| Fabrication gate verdict | `version: 1` | `api/_lib/print/gate.js` |+| Adapter interface | method set is the contract | `api/_lib/print/adapters/contract.js` |+| Certificate memo | `v: 1`, `kind: threews.print.v1` | `api/_lib/print/certificate.js` |++---++## 1. Printability report v1++Produced by `POST /api/print/quote` (with no `materialId`, this is the free+analyze call) and frozen onto `print_orders.analysis` when an order is placed.+The frozen copy never changes: a later re-analysis must not alter what was sold.++**Units.** glTF geometry is in meters. Everything the report publishes is in+millimeters (`_mm`), cubic centimeters (`volume_cm3`) or square centimeters+(`surface_area_cm2`), because those are the units a print bureau quotes in.++**Determinism.** The same bytes produce the same report. Every sample is taken+on a fixed stride over the triangle list, never a random draw, and every float+is rounded at a declared precision before it reaches the wire.++### Fields++| Field | Type | Meaning |+|---|---|---|+| `version` | integer | Report schema version. `1`. |+| `manifold` | boolean | The Manifold kernel accepted the mesh as a closed solid. |+| `watertight` | boolean | `manifold` and zero boundary edges. |+| `shells` | integer | Connected components. Each one prints as a separate loose piece. |+| `open_edges` | integer | Edges used by exactly one triangle: hole rims. |+| `non_manifold_edges` | integer | Edges used by three or more triangles. |+| `flipped_edges` | integer | Edges traversed the same way by both faces: one of the pair is wound backwards. |+| `degenerate_triangles` | integer | Zero-area faces dropped before analysis. |+| `self_intersections` | integer | Triangle pairs whose interiors cross. Neighbours (any shared vertex) are excluded. |+| `self_intersections_scan` | `"full"` \| `"sampled"` | Whether every triangle was tested or a fixed stride was. |+| `genus` | integer \| null | Topological genus. Null when the mesh is not a solid. |+| `triangles` | integer | Triangle count after welding and degenerate removal. |+| `vertices` | integer | Vertex count after welding. |+| `source_triangles` | integer | Triangle count as loaded, before welding. |+| `source_vertices` | integer | Vertex count as loaded. |+| `bbox_mm` | object | `{ x, y, z, diagonal }` at the model's own scale. |+| `volume_cm3` | number | Enclosed volume. **This is the number money is computed from.** |+| `volume_source` | `"manifold"` \| `"signed_sum"` | Exact kernel volume, or the divergence-theorem estimate used when the mesh is not a solid. |+| `surface_area_cm2` | number | Total surface area. |+| `min_wall_mm` | number \| null | 5th percentile of the wall-thickness samples. Null when no probe found a back wall. |+| `median_wall_mm` | number \| null | 50th percentile of the same samples. |+| `recommended_min_height_mm` | object \| null | Per material class (`resin`, `sls_nylon`, `full_color`, `fdm_draft`, `metal`), the print height at which `min_wall_mm` clears that process. |+| `has_textures` | boolean | The source carried textures. |+| `color_source` | `"texture"` \| `"material"` \| `"none"` | Where per-vertex color came from, which is what a full-color print reproduces. |+| `materials` | integer \| null | Material count in the source document. |+| `skipped_primitives` | integer | Non-triangle primitives ignored (points, lines, strips). |+| `size_bytes` | integer \| null | Source GLB size. |+| `sampling` | object | What was measured versus estimated. See below. |+| `score` | integer 0-100 | Printability score. |+| `deductions` | array | Named, buyer-readable reasons the score is not 100. |+| `source_url` | string \| null | The mesh the report describes. |++`sampling` carries `weld_tolerance_mm`, `wall_rays_cast`, `wall_rays_hit`,+`wall_percentile`, `self_intersection_triangles_tested` and+`self_intersection_capped`. A consumer that needs to know whether a number was+measured or sampled reads this block rather than guessing.++### Score deductions++Each entry is `{ id, points, detail }`. `detail` is buyer-facing copy and is+rendered verbatim. The score is `100` minus the sum of `points`, floored at `0`.++| `id` | Max points | Fires when |+|---|---|---|+| `non_manifold` | 30 | The kernel refused the mesh as a solid. |+| `open_edges` | 20 | Any boundary edge exists; scaled by the share of the perimeter that is open. |+| `non_manifold_edges` | 12 | Any edge is shared by more than two faces. |+| `self_intersections` | 15 | Any non-neighbouring face pair crosses. |+| `multiple_shells` | 10 | More than one connected body. |+| `degenerate_triangles` | 5 | Zero-area faces were present. |+| `thin_walls` | 18 | `min_wall_mm` is under the 0.6 mm a resin process holds. |+| `triangle_budget` | 4 | Over one million triangles. |++---++## 2. Quote token++`POST /api/print/quote` returns `token` alongside the itemization when the+material is priced (a quote-on-request material returns `token: null`, because+nothing may be checked out at a number an engineer has not confirmed).++**Format:** three dot-separated parts, `pq1.<base64url payload>.<hmac>`. The+HMAC is over the payload string, keyed by the platform signing secret.++**Payload claims,** deliberately single-letter because the token travels in a+request body on every slider drag:++| Claim | Meaning |+|---|---|+| `v` | Token schema version, `1`. |+| `m` | Material id. |+| `f` | Finish id. |+| `h` | Target height, mm. |+| `q` | Quantity. |+| `w` | Hollowed, `1` or `0`. |+| `c` | Destination country. |+| `t` | Total, USDC. |+| `g` | Chargeable volume, cm3. |+| `l` | Lead time, days. |+| `r` | Report hash: sha256 over the report's version, volume, bbox, min wall and triangle count. |+| `u` | Source model URL. |+| `i` | Creation id, or null for a direct upload. |+| `exp` | Expiry, unix seconds. |++Every priced parameter is inside the signature, so checkout cannot be replayed+at a stale price or altered client-side. Checkout verifies the token, not the+request body; a mismatch between the two is a rejected order, not a re-price.++---++## 3. Order states++`print_orders.status`. The database constrains the vocabulary; the legal+transitions live in `api/_lib/print-store.js` as data, next to the events they+emit, and an illegal move throws `PrintStoreError('illegal_transition')`.++```+created ──▶ quoted ──▶ paid ──▶ screening ──▶ submitted ──▶ printing ──▶ quality_check ──▶ shipped ──▶ delivered+```++| From | Legal next |+|---|---|+| `created` | `quoted`, `canceled` |+| `quoted` | `paid`, `canceled` |+| `paid` | `screening`, `canceled`, `refunded` |+| `screening` | `submitted`, `rejected`, `refunded` |+| `submitted` | `printing`, `quality_check`, `canceled`, `refunded` |+| `printing` | `quality_check`, `refunded` |+| `quality_check` | `shipped`, `printing` |+| `shipped` | `delivered`, `refunded` |+| `delivered` | none |+| `rejected` | `refunded` |+| `canceled` | `refunded` |+| `refunded` | none |++Rules that hold for every transition:++- A same-status write is illegal. Absence from the table means illegal.+- Every transition appends a `print_order_events` row (`status`, `note`,+ `actor` in `system | operator | provider | buyer`, `actor_id`). The timeline+ is that table; no column is mutated to represent history.+- The status guard is the concurrency lock. Two writers racing to move the same+ order produce one winner and one `transition_raced` error naming where the+ order actually went.+- A fulfillment adapter may only drive `submitted`, `printing`, `quality_check`,+ `shipped`, `delivered`. Everything before `submitted` is quoting, payment and+ safety; `refunded` is a money decision and stays operator-only.++---++## 4. Fabrication gate verdict++Written to `print_orders.analysis.screening` and returned inline by the quote+endpoint. Produced by `api/_lib/print/gate.js`.++```json+{+ "version": 1,+ "stage": "quote",+ "verdict": "allow",+ "category": null,+ "label": null,+ "layer": null,+ "matched": null,+ "message": null,+ "allowed": null,+ "policy_url": "/docs/materialize#content-policy",+ "checked_at": "2026-09-02T19:04:11.204Z",+ "layers": {+ "upstream": { "verdict": "allow" },+ "denylist": { "verdict": "allow", "soft": [] },+ "geometry": { "longest_mm": 65, "miniature": true, "note": "..." },+ "llm": { "verdict": "skipped", "reason": "deterministic layers only at quote time" }+ }+}+```++| Field | Meaning |+|---|---|+| `verdict` | `allow`, `refuse`, or `review` (held for a human). |+| `stage` | `quote` (pre-payment, deterministic) or `screening` (post-payment, with the model layer). |+| `category` | A stable slug: a denylist rule id, `generation_<category>`, or `fabrication_policy`. Never free-text. |+| `label` | Human name of the category. |+| `layer` | Which layer decided: `upstream`, `denylist`, or `llm`. |+| `matched` | The exact term a denylist rule matched, for audit. |+| `message` | Buyer-facing refusal copy. |+| `allowed` | What the buyer may do instead. |+| `policy_url` | Always present, always a live page. |+| `layers` | Per-layer record, including the model provider and model name when the LLM layer ran. |++### Precedence++The denylist always wins. The model layer can only add a refusal or resolve a+soft rule; it can never lift a refusal the denylist made, and it is not even+called once a hard rule has fired. `submitOrder()` refuses any order whose+stored verdict is not `allow`, so the gate cannot be bypassed from the operator+console.++### Run points++1. **Quote time.** Deterministic layers only, so a price is never gated on a+ third-party model being reachable, and a refusal costs the buyer nothing.+ A refusal is `HTTP 451` with `category`, `allowed` and `policy_url` in the+ body, so an agent lane can branch on the status alone.+2. **Screening.** The paid order is re-screened by+ `api/cron/print-orders-sync.js`, which adds the LLM layer. `refuse` moves the+ order to `rejected` (the refund path) with the category on the timeline;+ `review` leaves it in place and pages the operators.++### Gate limitations++Stated plainly because the alternative is a false sense of coverage.++- **Geometry cannot identify a weapon.** Blade profiles, bore diameters and+ receiver rails are not reliably detectable from a triangle soup: aspect-ratio+ heuristics that claim to find a blade also find a fin, a bookmark and a+ spatula. The only geometric signal this gate uses is **scale**, which is real:+ a tabletop miniature and a life-size component are the same words and+ different objects. The threshold is 120 mm on the longest bounding-box axis.+- **The denylist is language-bound.** It matches whole words in the prompt+ lineage, model title and buyer note. A request phrased entirely in another+ language, or purely as an uploaded mesh with no text at all, reaches only the+ model layer and the scale signal.+- **A direct GLB upload has no lineage.** Orders that skip generation carry no+ prompt history, so the text the gate reads is whatever the buyer typed.+- **The model layer is advisory in one direction only.** When no provider+ answers, an order the deterministic layers had no question about proceeds+ (it cleared the same bar its quote cleared) and an order with an unresolved+ soft flag is held for a human. Nothing is auto-rejected on a provider outage.++---++## 5. Adapter interface++A fulfillment lane is an object satisfying `assertAdapterShape()`. Adapters+speak; the store decides. Every adapter result is normalized before it reaches+the state machine, so a partner changing their payload shape cannot break it.++```js+{+ key: 'manual', // lower-kebab, 2 to 32 chars, unique+ label: 'Manual fulfillment',+ capabilities: {+ materials: '*' , // '*' or an array of catalog material ids+ maxBboxMm: { x, y, z }, // positive numbers+ shipsFrom: 'CN', // ISO 3166-1 alpha-2+ leadTimeDays: 12, // integer 1 to 120+ },+ configured(), // boolean: are this lane's credentials present+ async submit(order, assets),+ async status(order),+ async cancel(order, reason),+ verifyWebhook(rawBody, headers),+ parseWebhook(rawBody, headers),+}+```++Return shapes, after normalization:++| Method | Returns |+|---|---|+| `submit` | `{ providerOrderId, status, note, leadTimeDays, state }` |+| `status` | `{ status \| null, trackingNumber, carrier, note, state }`; `null` means "no news", which is not an error |+| `cancel` | `{ ok, note, state }` |+| `verifyWebhook` | `{ ok, deliveryId, reason }` |+| `parseWebhook` | `{ providerOrderId, status \| null, trackingNumber, carrier, note, state }` |++`state` is the provider's own payload, kept verbatim for diagnostics in+`print_orders.provider_state`. Nothing reads it to make a decision.++---++## 6. Webhook envelope++`POST /api/print/webhook/:provider`. Three properties, enforced in this order.++1. **Authenticity.** The adapter verifies the delivery against the exact bytes+ received, before any parse. The reference partner adapter reads+ `x-print-signature: sha256=<hex>`, an HMAC-SHA256 over the raw body keyed by+ that lane's shared secret, compared in constant time. An unverified delivery+ is `401` and never reaches `JSON.parse`. A lane with no webhook (the manual+ one) refuses every delivery by construction, so it has no unauthenticated+ door.+2. **Idempotency.** The delivery id (`x-print-delivery`, or a stable hash of the+ payload when the provider sends none) is claimed in+ `print_webhook_deliveries` by unique-key insert. A replay is a no-op that+ answers `200`; a `4xx` would make the provider retry forever.+3. **Ordering.** The state machine decides what may follow what. A report that+ arrives out of order is recorded on the timeline as a provider event carrying+ the refusal in its note and answered `200` with `applied: false`.++The response never echoes the payload and never reveals whether an order id+exists to an unverified caller.++---++## 7. Certificate memo++Every shipped print gets a certificate row and a Solana memo transaction. The+memo is the whole point: a buyer verifies a print by hashing the file and+comparing it to the string in the transaction, with no dependency on this+database, this company, or any block explorer staying online.++```json+{+ "v": 1,+ "kind": "threews.print.v1",+ "cert": "9f86d081884c7d659a2feaa0",+ "sha256": "<64 hex, the viewable GLB>",+ "ed": 3,+ "of": 25,+ "ts": 1788370000,+ "creation": "<forge creation uuid, when the print came from a generation>",+ "print": "stl:<64 hex of the exact manufacturing file>"+}+```++| Field | Required | Meaning |+|---|---|---|+| `v` | yes | Memo schema version. |+| `kind` | yes | `threews.print.v1`. |+| `cert` | yes | Certificate id: 24 lowercase hex, the `/cert/:certId` path segment. |+| `sha256` | yes | Hash of the viewable GLB. |+| `ed` | yes | Edition number. |+| `of` | yes | Edition size, or `null` for an open edition. |+| `ts` | yes | Print timestamp, unix seconds. |+| `creation` | when known | The generation this object came from. |+| `print` | when known | `<kind>:<sha256>` of the file the bureau actually loaded (`stl` or `3mf`). |++**Cluster policy.** Devnet is the default and needs no approval. Mainnet is+gated twice: `PRINT_CERT_CLUSTER` must say mainnet **and**+`PRINT_CERT_MAINNET_APPROVAL` must carry the owner's recorded approval. A+missing approval never silently downgrades to devnet, because a devnet signature+printed on a mainnet certificate would be a lie. The certificate is issued+unattested, the reason is recorded, and the sweep retries once approval lands.++**Failure policy.** Issuance never blocks a shipment. The row is written first;+the QR and the memo are best-effort and retried by the reconciliation sweep. A+certificate with a null signature is a real certificate whose proof is still in+flight, and the page says exactly that.++---++## Conformance++An implementation conforms to Materialize print pipeline v1 if:++1. Every price a buyer sees comes from a quote token whose signature verifies+ and whose `exp` has not passed.+2. No order reaches a fulfillment adapter without a recorded gate verdict of+ `allow` on `analysis.screening`.+3. Every status change appends a `print_order_events` row, and no status change+ occurs outside the transition table above.+4. Every webhook delivery is verified against the raw bytes before it is parsed,+ and claimed for idempotency before it is applied.+5. A certificate's `sha256` matches the bytes at the asset it names.++A consumer MUST treat a certificate whose memo signature is null as unattested,+regardless of what the certificate page renders.diff --git a/src/materialize-order.js b/src/materialize-order.jsnew file mode 100644index 000000000..1391347ef--- /dev/null+++ b/src/materialize-order.js@@ -0,0 +1,277 @@+// /materialize/orders/:id: one print order, from quote to doorstep.+//+// Most of an order's life is spent waiting, so the waiting is what this page is+// designed around. The rail shows every step with the real timestamp from the+// order's event log (print_order_events, appended once per transition and never+// mutated), and the step that is happening now says what is happening and what+// happens next, rather than leaving a buyer to guess from a status word.+//+// The page polls while the order is live and stops once it reaches a state that+// no longer changes on its own, so a delivered order sitting open in a tab is+// not a request every ten seconds forever.++import { ORDER_STEPS, formatLeadTime, formatMm, formatUsdc, timelineView } from './materialize-lib.js';++const $ = (id) => document.getElementById(id);++// Live orders are polled; a terminal one is not. The interval is generous+// because the transitions it is watching for are minutes to days apart.+const POLL_MS = 20_000;+const TERMINAL = new Set(['delivered', 'rejected', 'canceled', 'refunded']);++// What the buyer is actually waiting on, in the step's own terms. A status word+// is not an explanation, and "submitted" for three days with no note is how a+// buyer decides an order is lost.+const WAITING_COPY = {+ created: 'The order is open and waiting for payment to settle.',+ quoted: 'Waiting for your USDC payment to land on Solana. The order page updates itself when it does.',+ paid: 'Payment confirmed. The model is being screened against what we can fabricate before it reaches a machine.',+ screening: 'Being screened for fabrication. This is quick, and it happens before anything is sent to the floor.',+ submitted: 'On the print floor queue. Nothing visible happens here until a machine picks it up, which is normal.',+ printing: 'On the machine now. Printing is the longest step and does not report progress from inside the build chamber.',+ quality_check: 'Off the machine, being inspected and finished. If anything failed inspection it is reprinted rather than shipped.',+ shipped: 'In transit. The carrier tracking above updates faster than this page does.',+};++let timer = null;++function orderIdFromPath() {+ const match = location.pathname.match(/\/materialize\/orders\/([0-9a-f-]{36})/i);+ return match ? match[1] : null;+}++function esc(value) {+ return String(value ?? '').replace(/[&<>"']/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' })[c]);+}++/** A timestamp a person reads, with the exact value on hover. */+function when(iso) {+ if (!iso) return '';+ const date = new Date(iso);+ if (Number.isNaN(date.getTime())) return '';+ return date.toLocaleString(undefined, { month: 'short', day: 'numeric', hour: 'numeric', minute: '2-digit' });+}++async function load() {+ const id = orderIdFromPath();+ if (!id) return showError('That is not a valid order link.', 'The address should end in the order id you were given at checkout.');++ try {+ const res = await fetch(`/api/print/orders/${id}`, { credentials: 'include' });+ if (res.status === 401) {+ return showError(+ 'Sign in to see this order',+ 'Orders are visible only to the account that placed them.',+ `<a class="mo-btn" href="/login?next=${encodeURIComponent(location.pathname)}">Sign in</a>`,+ );+ }+ if (res.status === 404) {+ return showError(+ 'No such order',+ 'This order does not exist, or it belongs to another account. Check the link from your checkout confirmation.',+ '<a class="mo-btn" href="/materialize">Start a new print</a>',+ );+ }+ if (!res.ok) throw new Error(`Request failed (${res.status})`);+ const body = await res.json();+ render(body.order, body.events || []);++ if (!TERMINAL.has(body.order.status)) {+ clearTimeout(timer);+ timer = setTimeout(load, POLL_MS);+ }+ } catch (err) {+ // A failed poll on an order already on screen must not blank it out; only+ // the first load has nothing to fall back to.+ if (!$('mo-main').hidden) {+ clearTimeout(timer);+ timer = setTimeout(load, POLL_MS * 2);+ return;+ }+ showError('This order could not be loaded', `${esc(err.message)} It is safe to reload this page.`, '<button type="button" class="mo-btn" onclick="location.reload()">Try again</button>');+ }+}++function showError(title, message, actions = '') {+ $('mo-loading').hidden = true;+ $('mo-main').hidden = true;+ const box = $('mo-error');+ box.hidden = false;+ box.innerHTML = `<div class="mo-notice"><h2>${esc(title)}</h2><p>${message}</p>${actions ? `<div class="mo-row">${actions}</div>` : ''}</div>`;+}++function render(order, events) {+ $('mo-loading').hidden = true;+ $('mo-error').hidden = true;+ $('mo-main').hidden = false;++ const quote = order.quote || {};+ const materialName = quote.material?.name || order.material_id;++ document.title = `${materialName} print · ${order.status} · three.ws`;+ $('mo-eyebrow').textContent = `Materialize order ${order.id.slice(0, 8)}`;+ $('mo-title').textContent = statusHeadline(order);+ $('mo-sub').textContent = subtitleFor(order);++ $('mo-specs').innerHTML = [+ ['Material', materialName],+ ['Size', formatMm(order.target_height_mm)],+ ['Quantity', String(order.quantity)],+ ['Paid', `${formatUsdc(order.price_usdc)} USDC`],+ ['Ordered', when(order.created_at)],+ order.ship_to ? ['Going to', `${order.ship_to.city}, ${order.ship_to.country}`] : null,+ ]+ .filter(Boolean)+ .map(([k, v]) => `<div class="mo-spec"><dt>${esc(k)}</dt><dd>${esc(v)}</dd></div>`)+ .join('');++ renderModel(order);+ renderRail(order, events);+ renderShipment(order);+ renderCertificate(order);+}++function statusHeadline(order) {+ const map = {+ created: 'Your print is waiting on payment',+ quoted: 'Your print is waiting on payment',+ paid: 'Paid. Heading into production',+ screening: 'Being screened for fabrication',+ submitted: 'Queued on the print floor',+ printing: 'On the machine now',+ quality_check: 'Printed. Being inspected',+ shipped: 'On its way to you',+ delivered: 'Delivered',+ rejected: 'This order was not fabricated',+ canceled: 'This order was canceled',+ refunded: 'This order was refunded',+ };+ return map[order.status] || 'Your print';+}++function subtitleFor(order) {+ if (order.status === 'delivered') return 'Printed from your model and delivered. The certificate below links the object back to the exact file it was made from.';+ if (TERMINAL.has(order.status)) return 'Nothing further will happen on this order. Any refund is recorded on the timeline below.';+ return `${formatLeadTime(order.lead_time_days)} from the day it was paid. Every step below carries the moment it actually happened.`;+}++function renderModel(order) {+ // The prepared file is the object being printed; the source creation is the+ // best stand-in until preparation has run. Either way the buyer sees the+ // thing, not a placeholder box.+ const stage = $('mo-stage');+ const url = order.quote?.prepared_glb_url || null;+ if (url) return mountViewer(stage, url);+ if (!order.creation_id) return;+ fetch(`/api/forge-creation?id=${encodeURIComponent(order.creation_id)}`, { credentials: 'include' })+ .then((r) => (r.ok ? r.json() : null))+ .then((body) => {+ const glb = body?.creation?.glb_url || body?.glb_url || null;+ if (glb) mountViewer(stage, glb);+ })+ .catch(() => {+ // The empty state already says the print file is being prepared, which+ // is the honest thing to show when the model cannot be fetched.+ });+}++function mountViewer(stage, url) {+ const viewer = document.createElement('model-viewer');+ viewer.setAttribute('src', url);+ viewer.setAttribute('alt', 'The model being printed');+ viewer.setAttribute('camera-controls', '');+ viewer.setAttribute('auto-rotate', '');+ viewer.setAttribute('rotation-per-second', '16deg');+ viewer.setAttribute('interaction-prompt', 'none');+ viewer.setAttribute('shadow-intensity', '0.8');+ viewer.setAttribute('environment-image', 'neutral');+ viewer.setAttribute('exposure', '1.05');+ viewer.setAttribute('reveal', 'auto');+ stage.replaceChildren(viewer);+}++function renderRail(order, events) {+ const view = timelineView(order, events);+ $('mo-branch').innerHTML = view.branch+ ? `<div class="mo-branch">+ <h3>${esc(view.branch.label)}</h3>+ <p>${esc(view.branch.event?.note || 'Recorded on this order. If money moved, the refund appears on the timeline.')}</p>+ </div>`+ : '';++ $('mo-rail').innerHTML = view.steps+ .map((step, i) => {+ const mark = step.state === 'done' ? '✓' : String(i + 1);+ return `<li class="mo-step is-${step.state}">+ <span class="mo-dot" aria-hidden="true">${step.state === 'current' ? '' : mark}</span>+ <div>+ <p class="mo-step-label">${esc(step.label)}</p>+ <p class="mo-step-blurb">${esc(step.blurb)}</p>+ ${step.at ? `<p class="mo-step-at"><time datetime="${esc(step.at)}" title="${esc(step.at)}">${esc(when(step.at))}</time></p>` : ''}+ ${step.note ? `<p class="mo-step-note">${esc(step.note)}</p>` : ''}+ </div>+ </li>`;+ })+ .join('');++ const waiting = WAITING_COPY[order.status];+ $('mo-waiting').hidden = !waiting;+ if (waiting) $('mo-waiting-text').textContent = waiting;+}++function renderShipment(order) {+ const panel = $('mo-ship-panel');+ if (!order.tracking_number) {+ panel.hidden = true;+ return;+ }+ panel.hidden = false;+ const carrier = order.carrier ? esc(order.carrier) : 'Carrier';+ $('mo-ship-row').innerHTML = `<span class="mo-mono">${carrier} · ${esc(order.tracking_number)}</span>+ <button type="button" class="mo-btn" id="mo-copy-tracking">Copy tracking number</button>`;+ $('mo-copy-tracking')?.addEventListener('click', async (e) => {+ try {+ await navigator.clipboard.writeText(order.tracking_number);+ e.target.textContent = 'Copied';+ setTimeout(() => {+ e.target.textContent = 'Copy tracking number';+ }, 1600);+ } catch {+ e.target.textContent = order.tracking_number;+ }+ });+}++function renderCertificate(order) {+ const panel = $('mo-cert-panel');+ const certId = order.certificate_id || order.quote?.certificate_id || null;+ const shipped = ['shipped', 'delivered'].includes(order.status);+ if (!shipped && !certId) {+ panel.hidden = true;+ return;+ }+ panel.hidden = false;+ $('mo-cert-text').textContent = certId+ ? 'This print carries a certificate: the hash of the exact file it was made from, its edition number, and an attestation on Solana. The QR on the package insert opens the same page.'+ : 'A certificate is issued when the print ships: the hash of the exact file it was made from, its edition number, and an attestation on Solana.';+ $('mo-cert-row').innerHTML = certId+ ? `<a class="mo-btn" href="/cert/${esc(certId)}">Open the certificate</a>`+ : '';+ if (order.payment?.explorer_url) {+ $('mo-cert-row').insertAdjacentHTML(+ 'beforeend',+ `<a class="mo-btn" href="${esc(order.payment.explorer_url)}" target="_blank" rel="noopener">See the payment on Solscan</a>`,+ );+ }+}++// Stop polling while the tab is hidden; resume, with an immediate refresh, when+// the buyer comes back to it.+document.addEventListener('visibilitychange', () => {+ if (document.hidden) clearTimeout(timer);+ else load();+});++load();++export { ORDER_STEPS };diff --git a/src/materialize.js b/src/materialize.jsnew file mode 100644index 000000000..999dfb76c--- /dev/null+++ b/src/materialize.js@@ -0,0 +1,1042 @@+// /materialize: the surface where a generated model becomes a real object.+//+// One screen, no wizard. Pick a model, watch it get measured, choose what it is+// made of and how big it is, see the price move as you decide, put it on your+// desk at true size in AR, and pay in USDC on Solana.+//+// Two rules shape every line below:+//+// 1. No price is computed here. Every amount on this page arrives from+// POST /api/print/quote already decided by the quote engine, and this file+// only chooses how to say it. The same applies to what is printable: the+// server measures the mesh, and the slider ends and material cards are+// rendered from what it measured, so the UI can never promise something+// checkout will refuse.+// 2. Every state is drawn. Nothing picked, loading, a mesh that cannot be+// read, a material that cannot take this model, a price still settling, a+// payment waiting on a phone, and the moment it lands.+//+// The pure parts (scale drawing, slider maths, itemization rows, timeline) live+// in src/materialize-lib.js and are unit-tested.++import {+ SHIPPING_COUNTRIES,+ arScaleAttribute,+ clampHeight,+ defaultHeight,+ formatLeadTime,+ formatMm,+ formatUsdc,+ printabilityView,+ quoteRows,+ rejectionView,+ scaleReference,+ sliderBounds,+ validateShipping,+} from './materialize-lib.js';++const $ = (id) => document.getElementById(id);++// Long enough that dragging the size slider produces one request per pause+// rather than one per pixel, short enough that the price feels live.+const QUOTE_DEBOUNCE_MS = 260;+const CONFIRM_POLL_MS = 4000;+const CONFIRM_TIMEOUT_MS = 15 * 60 * 1000;++const state = {+ catalog: null,+ user: null,+ source: null, // { url, creationId, label }+ report: null,+ fits: [],+ materialId: null,+ finishId: null,+ heightMm: null,+ quantity: 1,+ country: 'US',+ hollow: false,+ quote: null,+ token: null,+ rejection: null,+ prepared: null,+ quoting: false,+ quoteSeq: 0,+};++// ── plumbing ────────────────────────────────────────────────────────────────++function esc(value) {+ return String(value ?? '').replace(/[&<>"']/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' })[c]);+}++async function api(path, options = {}) {+ const res = await fetch(path, { credentials: 'include', ...options });+ let body = null;+ try {+ body = await res.json();+ } catch {+ body = null;+ }+ if (!res.ok) {+ const err = new Error(body?.message || body?.error || `Request failed (${res.status})`);+ err.status = res.status;+ err.code = body?.code || body?.error || null;+ err.body = body;+ throw err;+ }+ return body;+}++async function csrfToken() {+ const body = await api('/api/csrf-token');+ return body?.token || body?.csrfToken || null;+}++/** The anonymous browser handle /forge already mints, so uploads land under a stable prefix. */+function forgeClientKey() {+ const KEY = 'threews_forge_client';+ try {+ let value = localStorage.getItem(KEY);+ if (!value) {+ value = (crypto.randomUUID?.() || String(Math.random()).slice(2)).replace(/-/g, '');+ localStorage.setItem(KEY, value);+ }+ return value;+ } catch {+ return 'anonymous';+ }+}++// ── boot ────────────────────────────────────────────────────────────────────++async function boot() {+ wireStatic();++ const params = new URLSearchParams(location.search);+ const creationId = params.get('creation');+ const glbUrl = params.get('glb');++ // The catalog is what every control is built from, so nothing renders until+ // it lands. A failure here is the one case where the page has nothing to say.+ try {+ state.catalog = await api('/api/print/catalog');+ } catch (err) {+ showLoadError(`The price list could not be loaded, so nothing can be quoted right now. ${esc(err.message)}`);+ return;+ }++ fillCountries();+ loadViewer(); // resolve session + creations rail in the background+ whoAmI();++ if (creationId) selectSource({ creationId, label: 'your creation' });+ else if (glbUrl) selectSource({ url: glbUrl, label: 'a linked model' });+}++function wireStatic() {+ $('mz-browse')?.addEventListener('click', () => $('mz-file').click());+ $('mz-file')?.addEventListener('change', (e) => {+ const file = e.target.files?.[0];+ if (file) uploadAndSelect(file);+ });++ const drop = $('mz-drop');+ if (drop) {+ for (const type of ['dragenter', 'dragover']) {+ drop.addEventListener(type, (e) => {+ e.preventDefault();+ drop.classList.add('is-over');+ });+ }+ for (const type of ['dragleave', 'drop']) {+ drop.addEventListener(type, (e) => {+ e.preventDefault();+ drop.classList.remove('is-over');+ });+ }+ drop.addEventListener('drop', (e) => {+ const file = e.dataTransfer?.files?.[0];+ if (file) uploadAndSelect(file);+ });+ }++ $('mz-url-form')?.addEventListener('submit', (e) => {+ e.preventDefault();+ const url = $('mz-url').value.trim();+ if (url) selectSource({ url, label: 'a linked model' });+ });++ $('mz-change')?.addEventListener('click', () => {+ state.source = null;+ state.report = null;+ state.quote = null;+ state.prepared = null;+ $('mz-studio').hidden = true;+ $('mz-picker').hidden = false;+ history.replaceState(null, '', '/materialize');+ $('mz-drop')?.scrollIntoView({ behavior: 'smooth', block: 'center' });+ });++ $('mz-size')?.addEventListener('input', () => {+ state.heightMm = Number($('mz-size').value);+ renderSizeReadout();+ scheduleQuote();+ });+ $('mz-qty')?.addEventListener('change', () => {+ const n = Math.max(1, Math.min(500, Math.round(Number($('mz-qty').value) || 1)));+ $('mz-qty').value = String(n);+ state.quantity = n;+ scheduleQuote();+ });+ $('mz-country')?.addEventListener('change', () => {+ state.country = $('mz-country').value;+ try {+ localStorage.setItem('mz_country', state.country);+ } catch {+ // A browser with storage disabled simply re-picks the default each visit.+ }+ scheduleQuote();+ });+ $('mz-hollow')?.addEventListener('change', () => {+ state.hollow = $('mz-hollow').checked;+ state.prepared = null;+ scheduleQuote();+ });+ $('mz-finish')?.addEventListener('change', () => {+ state.finishId = $('mz-finish').value;+ scheduleQuote();+ });+ $('mz-repair')?.addEventListener('click', runRepair);+ $('mz-ar-btn')?.addEventListener('click', () => $('mz-viewer')?.activateAR?.());++ $('mz-sheet-close')?.addEventListener('click', closeSheet);+ $('mz-sheet')?.addEventListener('click', (e) => {+ if (e.target === $('mz-sheet')) closeSheet();+ });+ document.addEventListener('keydown', (e) => {+ if (e.key === 'Escape' && !$('mz-sheet').hidden) closeSheet();+ });+}++function fillCountries() {+ const select = $('mz-country');+ if (!select) return;+ let saved = 'US';+ try {+ saved = localStorage.getItem('mz_country') || 'US';+ } catch {+ saved = 'US';+ }+ state.country = SHIPPING_COUNTRIES.some((c) => c.code === saved) ? saved : 'US';+ select.innerHTML = SHIPPING_COUNTRIES.map((c) => `<option value="${c.code}">${esc(c.name)}</option>`).join('');+ select.value = state.country;+}++async function whoAmI() {+ try {+ const body = await api('/api/auth/me');+ state.user = body?.user || body || null;+ } catch {+ state.user = null;+ }+ loadRail();+}++// ── the creations rail ──────────────────────────────────────────────────────++async function loadRail() {+ const rail = $('mz-rail');+ if (!rail) return;+ const username = state.user?.username;+ if (!username) {+ rail.innerHTML = `<p class="mz-rail-empty">Sign in and your own creations appear here, ready to print. Or <a href="/create" style="color:inherit">generate one now</a>, or drop a file on the left.</p>`;+ return;+ }+ try {+ const body = await api(`/api/users/${encodeURIComponent(username)}/creations?type=model`);+ const items = (body?.creations || body?.items || []).filter((c) => c.glb_url || c.model_url);+ if (!items.length) {+ rail.innerHTML = `<p class="mz-rail-empty">Nothing forged yet. <a href="/create" style="color:inherit">Make your first model</a> and it will show up here.</p>`;+ return;+ }+ rail.innerHTML = items+ .slice(0, 12)+ .map((c) => {+ const poster = c.preview_image_url || c.thumbnail_url || '';+ const label = esc((c.prompt || c.title || 'Untitled').slice(0, 70));+ return `<button type="button" class="mz-rail-card" data-creation="${esc(c.id)}" title="${label}">+ ${poster ? `<img src="${esc(poster)}" alt="" loading="lazy" />` : ''}+ <figcaption>${label}</figcaption>+ </button>`;+ })+ .join('');+ for (const card of rail.querySelectorAll('[data-creation]')) {+ card.addEventListener('click', () => selectSource({ creationId: card.dataset.creation, label: 'your creation' }));+ }+ } catch {+ rail.innerHTML = `<p class="mz-rail-empty">Your creations could not be loaded just now. Paste a model URL or drop a file on the left, and try this panel again shortly.</p>`;+ }+}++// ── choosing a model ────────────────────────────────────────────────────────++async function uploadAndSelect(file) {+ if (!/\.glb$/i.test(file.name)) {+ showLoadError('That is not a .glb. Export a self-contained glTF binary and try again.');+ return;+ }+ showLoadError(null);+ const drop = $('mz-drop');+ drop?.setAttribute('aria-busy', 'true');+ try {+ const slot = await api('/api/print/upload', {+ method: 'POST',+ headers: { 'content-type': 'application/json', 'x-forge-client': forgeClientKey() },+ body: JSON.stringify({ content_type: 'model/gltf-binary', size_bytes: file.size }),+ });+ const put = await fetch(slot.upload_url, { method: 'PUT', headers: slot.headers, body: file });+ if (!put.ok) throw new Error(`Upload failed (${put.status})`);+ selectSource({ url: slot.public_url, label: file.name });+ } catch (err) {+ showLoadError(`${esc(err.message)} You can still paste a public .glb URL instead.`);+ } finally {+ drop?.removeAttribute('aria-busy');+ }+}++async function selectSource(source) {+ showLoadError(null);+ state.source = source;+ state.report = null;+ state.quote = null;+ state.token = null;+ state.rejection = null;+ state.prepared = null;++ $('mz-picker').hidden = true;+ $('mz-studio').hidden = false;+ setStageBusy('Measuring the mesh…');+ $('mz-source-note').textContent = source.label ? `Printing ${source.label}` : '';++ const url = new URL(location.href);+ url.search = source.creationId ? `?creation=${source.creationId}` : source.url ? `?glb=${encodeURIComponent(source.url)}` : '';+ history.replaceState(null, '', url.pathname + url.search);++ try {+ const body = await api('/api/print/quote', {+ method: 'POST',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify(source.creationId ? { creationId: source.creationId } : { glbUrl: source.url }),+ });+ state.report = body.report;+ state.fits = body.fits || [];+ state.source = { ...source, url: body.sourceUrl, creation: body.creation || null };+ showModel(body.sourceUrl);+ renderPrintability();+ renderMaterials();+ pickInitialMaterial();+ setStageBusy(null);+ } catch (err) {+ setStageBusy(null);+ $('mz-studio').hidden = true;+ $('mz-picker').hidden = false;+ showLoadError(describeLoadFailure(err));+ }+}++/**+ * Turn an analyzer failure into something a person can act on. Each code is a+ * different problem with a different fix, and saying "could not analyze" for all+ * of them would be the same as saying nothing.+ */+function describeLoadFailure(err) {+ const map = {+ invalid_model: 'That file is not a readable glTF binary. Re-export it as a .glb and try again.',+ no_geometry: 'That model has no triangle geometry, so there is nothing to print. Points and curves cannot be fabricated.',+ too_large: 'That model is larger than the printer pipeline will read. Compress or decimate it first.',+ too_complex: 'That model has more triangles than the pipeline will read. Run it through /inspect to decimate it, then come back.',+ invalid_url: 'That URL cannot be fetched. It has to be a public https link to a .glb.',+ fetch_failed: 'The model could not be downloaded from that URL. Check the link is public and try again.',+ creation_not_found: 'That creation could not be found, or it is not public.',+ creation_has_no_model: 'That creation has not finished generating yet, so there is no model to print.',+ };+ return map[err.code] || `${esc(err.message)}`;+}++function showLoadError(message) {+ const box = $('mz-load-error');+ if (!box) return;+ if (!message) {+ box.hidden = true;+ box.innerHTML = '';+ return;+ }+ box.hidden = false;+ box.innerHTML = `<h3>That model could not be measured</h3><p>${message}</p>`;+}++function showStudioError(message) {+ const box = $('mz-studio-error');+ if (!box) return;+ if (!message) {+ box.hidden = true;+ box.innerHTML = '';+ return;+ }+ box.hidden = false;+ box.innerHTML = `<h3>Something went wrong</h3><p>${esc(message)}</p>`;+}++function setStageBusy(label) {+ const busy = $('mz-stage-busy');+ if (!busy) return;+ busy.hidden = !label;+ if (label) $('mz-stage-busy-label').textContent = label;+}++function loadViewer() {+ // model-viewer is a module script in the head; nothing to do here beyond+ // making sure the element exists before we set attributes on it.+ return $('mz-viewer');+}++function showModel(url) {+ const viewer = $('mz-viewer');+ if (viewer && url) viewer.setAttribute('src', url);+}++// ── printability ────────────────────────────────────────────────────────────++function renderPrintability() {+ const view = printabilityView(state.report);+ if (!view) return;++ const CIRCUMFERENCE = 2 * Math.PI * 19;+ const fill = $('mz-score-fill');+ fill.style.stroke = `var(--mz-${view.tone})`;+ fill.setAttribute('stroke-dasharray', String(CIRCUMFERENCE));+ fill.setAttribute('stroke-dashoffset', String(CIRCUMFERENCE * (1 - view.score / 100)));+ $('mz-score-num').textContent = String(view.score);+ $('mz-score-num').className = `mz-score-num tone-${view.tone}`;+ $('mz-score-label').textContent = view.label;+ $('mz-score-label').className = `mz-score-label tone-${view.tone}`;+ $('mz-score-sub').textContent = view.issues.length+ ? `${view.issues.length} thing${view.issues.length === 1 ? '' : 's'} the analyzer flagged`+ : 'Nothing flagged. This mesh is print-ready as it stands.';++ $('mz-printability-meta').textContent = `${(state.report.triangles || 0).toLocaleString()} triangles · report v${state.report.version}`;++ $('mz-facts').innerHTML = view.facts+ .map(+ (f) => `<div class="mz-fact"><dt>${esc(f.label)}</dt><dd class="${f.ok ? '' : 'tone-fair'}">${esc(f.value)}</dd></div>`,+ )+ .join('');++ $('mz-issues').innerHTML = view.issues.length+ ? view.issues+ .map(+ (i) => `<li class="mz-issue">+ <span class="mz-issue-dot${i.repairable ? ' is-repairable' : ''}"></span>+ <span><b>${esc(i.label)}</b> ${esc(i.detail)}</span>+ </li>`,+ )+ .join('')+ : '';++ const row = $('mz-repair-row');+ row.hidden = view.repairableCount === 0 || Boolean(state.prepared);+ $('mz-repair-note').textContent = view.repairableCount+ ? `${view.repairableCount} of these can be fixed automatically.`+ : '';+ renderRepairMetrics();+}++function renderRepairMetrics() {+ const list = $('mz-repair-metrics');+ const prepared = state.prepared;+ if (!list) return;+ if (!prepared) {+ list.hidden = true;+ list.innerHTML = '';+ return;+ }+ const rows = [+ ['Holes closed', prepared.repair.holesFilled],+ ['Duplicate vertices merged', prepared.repair.mergedVertices],+ ['Sliver triangles removed', prepared.repair.degenerateRemoved + prepared.repair.duplicateRemoved],+ ['Faces re-wound', prepared.repair.trianglesFlipped],+ ['Printability', `${prepared.before.score} to ${prepared.after.score}`],+ ['Solid volume', `${prepared.after.volume_cm3} cm3`],+ ];+ if (prepared.hollow.applied) rows.push(['Hollowed', `${prepared.hollow.wallMm} mm wall, ${prepared.hollow.drainHoles} drain holes`]);+ list.hidden = false;+ list.innerHTML = rows.map(([k, v]) => `<li><span>${esc(k)}</span><b>${esc(String(v))}</b></li>`).join('');+}++async function runRepair() {+ const button = $('mz-repair');+ button.disabled = true;+ setStageBusy('Repairing the mesh…');+ showStudioError(null);+ try {+ const prepared = await api('/api/print/prepare', {+ method: 'POST',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify({+ ...(state.source.creationId ? { creationId: state.source.creationId } : { glbUrl: state.source.url }),+ targetHeightMm: state.heightMm,+ materialId: state.materialId,+ hollow: state.hollow,+ }),+ });+ state.prepared = prepared;+ state.report = prepared.after;+ // The repaired solid is what gets printed, so it is what the viewer shows+ // from here on. The buyer approves the object, not the upload.+ showModel(prepared.assets.glb);+ renderPrintability();+ renderMaterials();+ scheduleQuote(0);+ } catch (err) {+ showStudioError(+ err.code === 'storage_unavailable'+ ? 'Repairs cannot be written on this deployment right now, so the model is unchanged. The original can still be quoted and ordered.'+ : `The repair did not complete: ${err.message}`,+ );+ button.disabled = false;+ } finally {+ setStageBusy(null);+ }+}++// ── material, size, quote ───────────────────────────────────────────────────++function materialById(id) {+ return state.catalog?.materials?.find((m) => m.id === id) || null;+}++function fitById(id) {+ return state.fits.find((f) => f.id === id) || null;+}++function renderMaterials() {+ const wrap = $('mz-mats');+ if (!wrap || !state.catalog) return;+ wrap.innerHTML = state.catalog.materials+ .map((m) => {+ const fit = fitById(m.id);+ const blocked = fit?.blocked || null;+ const range = fit && !blocked ? `${formatMm(fit.minHeightMm)} to ${formatMm(fit.maxHeightMm)} tall` : '';+ const swatch = swatchStyle(m);+ return `<button type="button" class="mz-mat" data-material="${esc(m.id)}"+ aria-pressed="${state.materialId === m.id}" ${blocked ? 'disabled' : ''}+ title="${esc(blocked || m.blurb)}">+ <span class="mz-mat-swatch" style="${swatch}"></span>+ <span class="mz-mat-name">${esc(m.name)}</span>+ <span class="mz-mat-note">${esc(m.quoteOnRequest ? 'Quoted by an engineer' : range)}</span>+ ${blocked ? `<span class="mz-mat-blocked">${esc(blocked)}</span>` : ''}+ </button>`;+ })+ .join('');+ for (const button of wrap.querySelectorAll('[data-material]')) {+ button.addEventListener('click', () => chooseMaterial(button.dataset.material));+ }+}++/** A swatch that reads as the material, built from the catalog's own descriptor. */+function swatchStyle(material) {+ const base = material.swatch?.base || '#999';+ const sheen = material.swatch?.sheen || 'matte';+ if (sheen === 'gloss') return `background: linear-gradient(135deg, #fff 0%, ${base} 42%, #7a7a7a 100%);`;+ if (sheen === 'metal') return `background: linear-gradient(120deg, #f2f4f6 0%, ${base} 30%, #55595e 58%, ${base} 82%);`;+ if (sheen === 'satin') return `background: linear-gradient(140deg, ${base} 0%, #fff2 40%, ${base} 100%);`;+ return `background: ${base};`;+}++function pickInitialMaterial() {+ const usable = state.fits.filter((f) => !f.blocked && !f.quoteOnRequest);+ // Full colour first when the model carries a texture: printing what you see is+ // the thing nobody else does, so it should be the default when it is possible.+ const colour = usable.find((f) => f.class === 'full_color');+ const first = colour || usable.find((f) => f.class === 'resin') || usable[0];+ if (!first) {+ renderQuoteBody(+ `<div class="mz-notice mz-notice-warn"><h3>No material can take this model</h3>+ <p>Every material in the catalog either needs a thicker wall than this mesh has at any printable size, or a smaller footprint than it has. A repair pass thickens thin walls and is the usual fix.</p></div>`,+ );+ return;+ }+ chooseMaterial(first.id);+}++function chooseMaterial(id) {+ const fit = fitById(id);+ if (fit?.blocked) return;+ state.materialId = id;+ state.prepared = state.prepared && state.materialId === id ? state.prepared : state.prepared;++ const material = materialById(id);+ const finishes = material?.finishes || [];+ state.finishId = (finishes.find((f) => f.default) || finishes[0])?.id || null;++ const finishRow = $('mz-finish-row');+ finishRow.hidden = finishes.length < 2;+ $('mz-finish').innerHTML = finishes+ .map((f) => `<option value="${esc(f.id)}">${esc(f.name)}${f.fee ? ` (+${formatUsdc(f.fee)})` : ''}</option>`)+ .join('');+ if (state.finishId) $('mz-finish').value = state.finishId;+ $('mz-finish-note').textContent = material?.blurb || '';++ const hollowLabel = $('mz-hollow-label');+ hollowLabel.hidden = !fit?.hollowSupported;+ if (!fit?.hollowSupported) {+ state.hollow = false;+ $('mz-hollow').checked = false;+ }++ for (const button of $('mz-mats').querySelectorAll('[data-material]')) {+ button.setAttribute('aria-pressed', String(button.dataset.material === id));+ }++ applySliderBounds();+ scheduleQuote(0);+}++function applySliderBounds() {+ const fit = fitById(state.materialId);+ const bounds = sliderBounds(fit);+ const slider = $('mz-size');+ const panel = $('mz-size-panel');+ if (!bounds) {+ panel.hidden = true;+ return;+ }+ panel.hidden = false;+ slider.min = String(bounds.min);+ slider.max = String(bounds.max);+ slider.step = String(bounds.step);+ // Keep the size the buyer chose whenever the new material can hold it, so+ // comparing materials does not silently resize the object.+ state.heightMm = state.heightMm ? clampHeight(state.heightMm, bounds) : defaultHeight(bounds, state.catalog.sizePresets || []);+ slider.value = String(state.heightMm);+ $('mz-size-min').textContent = `${formatMm(bounds.min)} · ${bounds.minNote}`;+ $('mz-size-max').textContent = `${bounds.maxNote} · ${formatMm(bounds.max)}`;++ $('mz-presets').innerHTML = (state.catalog.sizePresets || [])+ .map((p) => {+ const inRange = p.heightMm >= bounds.min && p.heightMm <= bounds.max;+ return `<button type="button" class="mz-chip" data-preset="${p.heightMm}" ${inRange ? '' : 'disabled'}+ aria-pressed="${state.heightMm === p.heightMm}"+ title="${esc(inRange ? p.blurb : `${p.name} is outside what this material can print for this model`)}">+ ${esc(p.name)} · ${formatMm(p.heightMm)}+ </button>`;+ })+ .join('');+ for (const chip of $('mz-presets').querySelectorAll('[data-preset]')) {+ chip.addEventListener('click', () => {+ state.heightMm = clampHeight(Number(chip.dataset.preset), bounds);+ $('mz-size').value = String(state.heightMm);+ renderSizeReadout();+ scheduleQuote(0);+ });+ }+ renderSizeReadout();+}++function renderSizeReadout() {+ $('mz-size-value').textContent = formatMm(state.heightMm);+ for (const chip of $('mz-presets').querySelectorAll('[data-preset]')) {+ chip.setAttribute('aria-pressed', String(Number(chip.dataset.preset) === state.heightMm));+ }+ drawScale();+}++// Simple, legible silhouettes. Real proportions matter more than detail here:+// the drawing's job is to answer "how big is that actually" in one glance.+const REFERENCE_ART = {+ coin: '<svg viewBox="0 0 24 24" preserveAspectRatio="none" fill="currentColor"><circle cx="12" cy="12" r="10"/></svg>',+ mug: '<svg viewBox="0 0 24 40" preserveAspectRatio="none" fill="currentColor"><path d="M3 4h14v32H3z"/><path d="M17 12h3a4 4 0 0 1 0 12h-3z" fill="none" stroke="currentColor" stroke-width="2.5"/></svg>',+ hand: '<svg viewBox="0 0 24 44" preserveAspectRatio="none" fill="currentColor"><path d="M6 20V6a2 2 0 1 1 4 0v12h1V3a2 2 0 1 1 4 0v15h1V6a2 2 0 1 1 4 0v20c0 9-4 18-9 18s-9-6-9-13V17a2 2 0 1 1 4 0z"/></svg>',+ person: '<svg viewBox="0 0 24 64" preserveAspectRatio="none" fill="currentColor"><circle cx="12" cy="7" r="6"/><path d="M6 16h12l3 20h-4l-1 28h-3l-1-20h-2l-1 20H6L5 36H1z" transform="translate(1)"/></svg>',+};++function drawScale() {+ const box = $('mz-scale');+ const caption = $('mz-scale-caption');+ if (!box || !state.heightMm || !state.catalog) return;+ const view = scaleReference(state.heightMm, state.catalog.scaleReferences || [], 190);+ if (!view) {+ box.hidden = true;+ caption.textContent = '';+ return;+ }+ box.hidden = false;+ $('mz-scale-bar').style.height = `${view.modelPx}px`;+ const ref = $('mz-scale-ref');+ ref.style.height = `${view.referencePx}px`;+ ref.innerHTML = REFERENCE_ART[view.reference.id] || REFERENCE_ART.mug;+ $('mz-scale-ref-tag').textContent = view.reference.name;+ caption.textContent = view.caption;+}++let quoteTimer = null;+function scheduleQuote(delay = QUOTE_DEBOUNCE_MS) {+ clearTimeout(quoteTimer);+ quoteTimer = setTimeout(requestQuote, delay);+}++async function requestQuote() {+ if (!state.source || !state.materialId || !state.heightMm) return;+ const seq = (state.quoteSeq += 1);+ state.quoting = true;+ $('mz-quote-meta').innerHTML = '<span class="mz-quote-busy"><span class="mz-spinner"></span>Pricing…</span>';++ try {+ const body = await api('/api/print/quote', {+ method: 'POST',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify({+ ...(state.source.creationId ? { creationId: state.source.creationId } : { glbUrl: state.source.url }),+ materialId: state.materialId,+ finishId: state.finishId,+ targetHeightMm: state.heightMm,+ quantity: state.quantity,+ country: state.country,+ hollow: state.hollow,+ }),+ });+ // A slower earlier request must never overwrite a newer answer.+ if (seq !== state.quoteSeq) return;+ state.quote = body.quote;+ state.token = body.token;+ state.rejection = body.rejection;+ state.fits = body.fits || state.fits;+ applyArScale();+ renderQuote(body);+ } catch (err) {+ if (seq !== state.quoteSeq) return;+ renderQuoteBody(+ `<div class="mz-notice mz-notice-error"><h3>The price could not be refreshed</h3>+ <p>${esc(err.message)}</p>+ <div class="mz-notice-actions"><button type="button" class="mz-btn" id="mz-retry-quote">Try again</button></div></div>`,+ );+ $('mz-retry-quote')?.addEventListener('click', () => scheduleQuote(0));+ } finally {+ if (seq === state.quoteSeq) {+ state.quoting = false;+ $('mz-quote-meta').textContent = state.quote ? `Quoted in ${state.quote.currency} on ${state.quote.chain}` : '';+ }+ }+}++/**+ * Put the object on the buyer's floor at the size they ordered.+ *+ * model-viewer measures AR in glTF units, one unit to the metre, and+ * ar-scale="fixed" stops the viewer resizing what it placed. The factor is the+ * quote's own scale, so what appears on the desk is the object that was priced.+ */+function applyArScale() {+ const viewer = $('mz-viewer');+ const button = $('mz-ar-btn');+ if (!viewer) return;+ const attr = arScaleAttribute(state.quote?.geometry?.scale);+ if (!attr) {+ button.hidden = true;+ return;+ }+ viewer.setAttribute('scale', attr);+ viewer.setAttribute('ar-scale', 'fixed');+ button.hidden = !(viewer.canActivateAR ?? true);+ button.title = `Places it on your floor at ${formatMm(state.heightMm)} tall, the exact size you are ordering.`;+}++function renderQuoteBody(html) {+ $('mz-quote-body').innerHTML = html;+}++function renderQuote(body) {+ if (body.rejection) {+ const view = rejectionView(body.rejection);+ renderQuoteBody(+ `<div class="mz-notice mz-notice-warn">+ <h3>${esc(view.headline)}</h3>+ ${view.fixes.map((f) => `<p>${esc(f.fix)}</p>`).join('')}+ <div class="mz-notice-actions">+ ${view.offerRepair ? '<button type="button" class="mz-btn" id="mz-fix-repair">Repair this model</button>' : ''}+ ${view.alternatives.map((a) => `<button type="button" class="mz-btn" data-switch="${esc(a.id)}">Use ${esc(a.name)}</button>`).join('')}+ </div>+ </div>`,+ );+ $('mz-fix-repair')?.addEventListener('click', runRepair);+ for (const button of $('mz-quote-body').querySelectorAll('[data-switch]')) {+ button.addEventListener('click', () => chooseMaterial(button.dataset.switch));+ }+ return;+ }++ const quote = body.quote;+ if (!quote) return;+ const rows = quoteRows(quote);+ const holderLine = rows.find((r) => r.id === 'holder_discount');++ renderQuoteBody(+ `<ul class="mz-quote-lines">+ ${rows+ .map(+ (r) => `<li class="mz-line${r.credit ? ' is-credit' : ''}">+ <span class="mz-line-label">${esc(r.label)}</span>+ <span class="mz-line-amount">${esc(r.amountText)}</span>+ ${r.detail ? `<p class="mz-line-detail">${esc(r.detail)}</p>` : ''}+ </li>`,+ )+ .join('')}+ </ul>+ <div class="mz-total">+ <span class="mz-total-label">Total${quote.quoteOnRequest ? ' (estimate)' : ''}</span>+ <span class="mz-total-amount">${esc(formatUsdc(quote.total))} <span style="font-size:13px;font-weight:600;">${esc(quote.currency)}</span></span>+ </div>+ <p class="mz-total-note">${esc(formatLeadTime(quote.leadTimeDays))} · ${esc(formatMm(quote.geometry.boxMm.x, { unit: false }))} x ${esc(formatMm(quote.geometry.boxMm.y, { unit: false }))} x ${esc(formatMm(quote.geometry.boxMm.z))} boxed · ${esc(String(quote.geometry.massGramsEach))} g each</p>+ ${+ quote.quoteOnRequest+ ? `<div class="mz-notice mz-notice-info" style="margin-top:0.9rem;"><h3>This one is priced by hand</h3><p>Metal is quoted against the actual geometry by an engineer, not by the calculator. The number above is an estimate; ask for a firm quote and we will come back with it.</p></div>+ <a class="mz-btn mz-btn-block mz-btn-primary" style="margin-top:0.85rem;text-align:center;text-decoration:none;display:block;" href="mailto:[email protected]?subject=${encodeURIComponent(`Metal print quote request (${quote.material.name}, ${formatMm(state.heightMm)})`)}">Ask for a firm quote</a>`+ : `<button type="button" class="mz-btn mz-btn-primary mz-btn-block" id="mz-checkout" style="margin-top:1rem;">Order it for ${esc(formatUsdc(quote.total))} ${esc(quote.currency)}</button>+ <p class="mz-total-note">${+ holderLine+ ? 'Your $THREE holder discount is already applied above.'+ : state.user+ ? 'Hold $THREE and a holder discount applies here automatically.'+ : 'Sign in at checkout. Holding $THREE applies a discount to this price.'+ }</p>`+ }`,+ );+ $('mz-checkout')?.addEventListener('click', openCheckout);+}++// ── checkout ────────────────────────────────────────────────────────────────++let sheetReturnFocus = null;++function openSheet(title, subtitle, html) {+ sheetReturnFocus = document.activeElement;+ $('mz-sheet-title').textContent = title;+ $('mz-sheet-sub').textContent = subtitle;+ $('mz-sheet-body').innerHTML = html;+ $('mz-sheet').hidden = false;+ $('mz-sheet-card').querySelector('input, select, button, a')?.focus();+}++function closeSheet() {+ $('mz-sheet').hidden = true;+ $('mz-sheet-body').innerHTML = '';+ sheetReturnFocus?.focus?.();+}++function openCheckout() {+ if (!state.token) return;+ if (!state.user) {+ openSheet(+ 'Sign in to order',+ 'An order needs somewhere to go and someone to tell when it ships.',+ `<p style="font-size:13.5px;line-height:1.6;color:var(--mz-ink-2);margin:0 0 1rem;">+ Your quote is held for 24 hours. Sign in and you land back here with this exact price, material and size.+ </p>+ <a class="mz-btn mz-btn-primary mz-btn-block" style="text-align:center;text-decoration:none;display:block;" href="/login?next=${encodeURIComponent(location.pathname + location.search)}">Sign in and continue</a>+ <p style="font-size:12px;color:var(--mz-ink-3);margin:0.8rem 0 0;text-align:center;">No account yet? The same link creates one.</p>`,+ );+ return;+ }+ renderShippingStep({});+}++function renderShippingStep(values, errors = {}) {+ const field = (name, label, opts = {}) => {+ const invalid = errors[name] ? ' data-invalid' : '';+ const input = opts.select+ ? `<select name="${name}" ${opts.required ? 'required' : ''}>${SHIPPING_COUNTRIES.map((c) => `<option value="${c.code}" ${values[name] === c.code ? 'selected' : ''}>${esc(c.name)}</option>`).join('')}</select>`+ : `<input name="${name}" type="${opts.type || 'text'}" autocomplete="${opts.autocomplete || 'off'}" value="${esc(values[name] || '')}" ${opts.required ? 'required' : ''} placeholder="${esc(opts.placeholder || '')}" />`;+ return `<label class="mz-input-label"${invalid}>${esc(label)}${input}${errors[name] ? `<span class="mz-error-text">${esc(errors[name])}</span>` : ''}</label>`;+ };++ openSheet(+ 'Where should it go?',+ 'We keep the minimum a courier needs, and nothing else.',+ `<form class="mz-form" id="mz-ship-form" novalidate>+ ${field('name', 'Full name', { required: true, autocomplete: 'name' })}+ ${field('line1', 'Street address', { required: true, autocomplete: 'address-line1' })}+ ${field('line2', 'Apartment, suite, floor (optional)', { autocomplete: 'address-line2' })}+ <div class="mz-grid-2">+ ${field('city', 'City', { required: true, autocomplete: 'address-level2' })}+ ${field('region', 'State or region (optional)', { autocomplete: 'address-level1' })}+ </div>+ <div class="mz-grid-2">+ ${field('postal_code', 'Postal code', { required: true, autocomplete: 'postal-code' })}+ ${field('country', 'Country', { required: true, select: true })}+ </div>+ ${field('phone', 'Phone for the courier (optional)', { type: 'tel', autocomplete: 'tel' })}+ <div class="mz-notice mz-notice-info" id="mz-ship-error" hidden role="alert"></div>+ <button type="submit" class="mz-btn mz-btn-primary mz-btn-block">Continue to payment</button>+ <p style="font-size:11.5px;color:var(--mz-ink-3);margin:0;text-align:center;">+ Changing the country re-prices shipping before you pay.+ </p>+ </form>`,+ );++ const form = $('mz-ship-form');+ form.querySelector('[name="country"]').value = values.country || state.country;+ form.addEventListener('submit', async (e) => {+ e.preventDefault();+ const data = Object.fromEntries(new FormData(form).entries());+ const check = validateShipping(data);+ if (!check.valid) {+ renderShippingStep(data, check.errors);+ return;+ }+ // The quote was priced for a destination. If the buyer typed a different+ // country than the one the quote used, re-price before charging rather+ // than shipping a mismatch to the server for a 422.+ if (data.country !== state.quote.country) {+ state.country = data.country;+ $('mz-country').value = data.country;+ openSheet('Re-pricing for that destination…', 'Shipping is zone-based, so the total moves with the country.', '<div class="mz-quote-busy"><span class="mz-spinner"></span>One moment.</div>');+ await requestQuote();+ if (!state.token) {+ renderShippingStep(data, { country: 'That destination could not be priced. Pick another country.' });+ return;+ }+ }+ submitOrder(data);+ });+}++async function submitOrder(shipping) {+ openSheet('Opening your order…', 'Locking the quoted price against a signed token.', '<div class="mz-quote-busy"><span class="mz-spinner"></span>One moment.</div>');+ try {+ const token = await csrfToken();+ const result = await api('/api/print/orders', {+ method: 'POST',+ headers: { 'content-type': 'application/json', 'x-csrf-token': token },+ body: JSON.stringify({ token: state.token, shipping }),+ });+ renderPaymentStep(result);+ } catch (err) {+ if (err.code === 'quote_invalid') {+ openSheet(+ 'That quote expired',+ 'Prices are held for 24 hours so they cannot drift between the quote and the charge.',+ `<p style="font-size:13.5px;line-height:1.6;color:var(--mz-ink-2);">Nothing was charged. Refresh the price and your order continues from there.</p>+ <button type="button" class="mz-btn mz-btn-primary mz-btn-block" id="mz-refresh-quote">Refresh the price</button>`,+ );+ $('mz-refresh-quote')?.addEventListener('click', async () => {+ closeSheet();+ await requestQuote();+ });+ return;+ }+ openSheet(+ 'The order could not be opened',+ 'Nothing was charged.',+ `<div class="mz-notice mz-notice-error"><p>${esc(err.message)}</p></div>+ <button type="button" class="mz-btn mz-btn-block" id="mz-order-back" style="margin-top:0.9rem;">Back to the address</button>`,+ );+ $('mz-order-back')?.addEventListener('click', () => renderShippingStep(shipping));+ }+}++function renderPaymentStep(result) {+ const { order, payment } = result;+ openSheet(+ 'Pay in USDC on Solana',+ 'The amount is fixed by the quote you approved.',+ `<div class="mz-pay-summary">+ <div><span>Order</span><span class="mz-mono">${esc(order.id.slice(0, 8))}</span></div>+ <div><span>Lead time</span><span>${esc(formatLeadTime(order.lead_time_days))}</span></div>+ <div class="mz-pay-total"><span>Amount</span><span>${esc(payment.amount)} USDC</span></div>+ </div>+ <a class="mz-btn mz-btn-primary mz-btn-block" style="text-align:center;text-decoration:none;display:block;" href="${esc(payment.url)}">Open your wallet</a>+ <canvas class="mz-qr" id="mz-qr" width="240" height="240" aria-label="Solana Pay QR code"></canvas>+ <p style="font-size:12.5px;color:var(--mz-ink-3);text-align:center;margin:0 0 0.9rem;">+ Or scan with a Solana Pay wallet on your phone.+ </p>+ <div class="mz-quote-busy" id="mz-pay-status" style="justify-content:center;"><span class="mz-spinner"></span>Waiting for the payment to land…</div>+ <p style="font-size:11.5px;color:var(--mz-ink-3);text-align:center;margin:0.9rem 0 0;">+ This page watches the chain for you. You can also+ <a href="${esc(result.track_url)}" style="color:inherit;">follow the order</a> and come back.+ </p>`,+ );++ drawQr(payment.url);+ pollPayment(order.id, result.track_url);+}++async function drawQr(url) {+ const canvas = $('mz-qr');+ if (!canvas) return;+ try {+ const mod = await import('qrcode');+ await (mod.default ?? mod).toCanvas(canvas, url, { width: 240, margin: 1 });+ } catch {+ // Without the QR the wallet button above still completes the payment, so+ // the step stays usable rather than blocking on a failed chunk load.+ canvas.replaceWith(+ Object.assign(document.createElement('p'), {+ className: 'mz-mono',+ style: 'text-align:center;margin:0.9rem 0;',+ textContent: url,+ }),+ );+ }+}++async function pollPayment(orderId, trackUrl) {+ const started = Date.now();+ const status = $('mz-pay-status');+ while (Date.now() - started < CONFIRM_TIMEOUT_MS) {+ await new Promise((r) => setTimeout(r, CONFIRM_POLL_MS));+ if ($('mz-sheet').hidden) return;+ try {+ const body = await api(`/api/print/orders/${orderId}/confirm`, {+ method: 'POST',+ headers: { 'content-type': 'application/json', 'x-csrf-token': await csrfToken() },+ });+ if (body?.status === 'confirmed' || body?.order?.status === 'paid' || body?.order?.status === 'screening') {+ renderPaidStep(trackUrl);+ return;+ }+ if (body?.status === 'mismatch') {+ status.innerHTML = `<span class="tone-fair">A payment landed but not for the quoted amount. Our team is looking at it and will reach you at the address on the order.</span>`;+ return;+ }+ } catch (err) {+ if (err.status === 404 || err.status === 401) {+ status.innerHTML = `<span class="tone-fair">We lost track of this order in the browser. <a href="${esc(trackUrl)}" style="color:inherit;">Open its page</a> to continue.</span>`;+ return;+ }+ // A transient RPC or network blip is expected while a payment settles;+ // the loop simply tries again on the next tick.+ }+ }+ status.innerHTML = `<span>Still waiting. <a href="${esc(trackUrl)}" style="color:inherit;">Open the order page</a> and it will update there when the payment confirms.</span>`;+}++function renderPaidStep(trackUrl) {+ openSheet(+ 'Paid. It goes into production.',+ '',+ `<div class="mz-success-mark">+ <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.6" stroke-linecap="round" stroke-linejoin="round"><path d="m4 12.5 5 5L20 6.5" /></svg>+ </div>+ <p style="font-size:13.5px;line-height:1.6;color:var(--mz-ink-2);text-align:center;margin:0 0 1rem;">+ Your USDC settled on Solana and the order is being screened for fabrication now.+ Every step from here writes to the order's timeline, so you can watch it print and ship.+ </p>+ <p style="font-size:13px;line-height:1.6;color:var(--mz-ink-2);text-align:center;margin:0 0 1.2rem;">+ When it ships, the package carries a certificate linking the physical object back to the exact+ model it was printed from, attested on Solana.+ </p>+ <a class="mz-btn mz-btn-primary mz-btn-block" style="text-align:center;text-decoration:none;display:block;" href="${esc(trackUrl)}">Follow this order</a>`,+ );+}++boot();diff --git a/vercel.json b/vercel.jsonindex 708d7ebdc..331c73dcc 100644--- a/vercel.json+++ b/vercel.json@@ -2040,6 +2040,14 @@"src": "/materialize/insert/([0-9a-f]{24})/?","dest": "/print-insert.html"},+ {+ "src": "/materialize/orders/([0-9a-fA-F-]{36})/?",+ "dest": "/materialize-order.html"+ },+ {+ "src": "/materialize/?",+ "dest": "/materialize.html"+ },{"src": "/p/([a-z0-9-]+)/?","dest": "/p/index.html"@@ -6329,10 +6337,6 @@"path": "/api/cron/companion-poll","schedule": "*/2 * * * *"},- {- "path": "/api/cron/print-orders-sync",- "schedule": "17 * * * *"- },{"path": "/api/cron/feedback-triage","schedule": "*/5 * * * *"diff --git a/vite.config.js b/vite.config.jsindex c2d2b03b8..a93e306d9 100644--- a/vite.config.js+++ b/vite.config.js@@ -540,6 +540,8 @@ const appConfig = {'nav-tier-badge': resolve(__dirname, 'src/nav-tier-badge.js'),i18n: resolve(__dirname, 'src/i18n.js'),drops: resolve(__dirname, 'pages/drops.html'),+ materialize: resolve(__dirname, 'pages/materialize.html'),+ 'materialize-order': resolve(__dirname, 'pages/materialize-order.html'),'materialize-ops': resolve(__dirname, 'pages/materialize-ops.html'),'drop-collection': resolve(__dirname, 'pages/drop-collection.html'),spotlight: resolve(__dirname, 'pages/spotlight.html'),@@ -1785,6 +1787,8 @@ const appConfig = {'/likeness-bench/': resolve(root, 'pages/likeness-bench.html'),'/payment-outcomes': resolve(root, 'pages/payment-outcomes.html'),'/payment-outcomes/': resolve(root, 'pages/payment-outcomes.html'),+ '/materialize': resolve(root, 'pages/materialize.html'),+ '/materialize/': resolve(root, 'pages/materialize.html'),'/inspect': resolve(root, 'pages/inspect.html'),'/inspect/': resolve(root, 'pages/inspect.html'),'/render-lab': resolve(root, 'pages/render-lab.html'),@@ -2167,6 +2171,9 @@ const appConfig = {// /materialize/insert/:certId → the printable package insert card (ops).else if (!filePath && /^\/materialize\/insert\/[0-9a-f]{24}\/?$/.test(path))filePath = resolve(root, 'pages/print-insert.html');+ // /materialize/orders/:id → one print order's timeline (uuid).+ else if (!filePath && /^\/materialize\/orders\/[0-9a-fA-F-]{36}\/?$/.test(path))+ filePath = resolve(root, 'pages/materialize-order.html');// /drops/:slug → one generative 3D collection. Declared ahead of the// /drop/:id rule below so the singular sealed-gift route and this// plural collection route can never shadow each other.