slicer-studio 0.1.1 → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -10,16 +10,21 @@ it costs to print. Staff can slice models and inspect the G-code.
10
10
  It is a standard custom element, so it works on any stack. It brings its own React, and a shadow root keeps its styles
11
11
  and your page's apart.
12
12
 
13
+ The studio is the interface only. It needs a [slicer backend](#slicer-backend) that you run: headless OrcaSlicer behind a
14
+ small web server, which does the slicing and holds your printers and prices.
15
+
13
16
  **The price page** (`mode="quote"`, the default) takes up to 10 models at once and shows each one in 3D. Customers choose
14
17
  the material, finish, strength and number of copies, then see the price, weight and print time. SLA and SLS jobs get an
15
18
  email button to your lab instead of a price.
16
19
 
17
- **Advanced** (`mode="advanced"`) is for staff. It offers every OrcaSlicer printer and preset, slices models, and shows the
18
- G-code layer by layer. It also opens G-code and sliced 3MF files in the browser, with no upload.
20
+ **Advanced** (`mode="advanced"`) is for staff. It offers every printer and preset your backend lists, slices models, and
21
+ shows the G-code layer by layer. It also opens G-code and sliced 3MF files in the browser, with no upload. You can
22
+ [limit it to people your own servers approve](#staff-access).
19
23
 
20
24
  ## Contents
21
25
 
22
26
  - [How it works](#how-it-works)
27
+ - [Slicer backend](#slicer-backend)
23
28
  - [Setup](#setup)
24
29
  - [Frameworks](#frameworks)
25
30
  - [Attributes](#attributes)
@@ -37,97 +42,264 @@ G-code layer by layer. It also opens G-code and sliced 3MF files in the browser,
37
42
  ```text
38
43
  Your website Your server
39
44
  +---------------------------+ +-----------------------------+
40
- | <slicer-studio> | model | slicer-api (Docker) |
41
- | upload, choices, | ----------> | OrcaSlicer |
45
+ | <slicer-studio> | model | Your slicer backend |
46
+ | upload, choices, | ----------> | headless OrcaSlicer |
42
47
  | 3D view, price | <---------- | your printers and prices |
43
48
  +---------------------------+ weight, +-----------------------------+
44
49
  print time
45
50
  ```
46
51
 
47
- - **This package is the interface.** Slicing is done by
48
- [slicer-api](https://github.com/kerala-startup-mission/slicer-api), which you run yourself. Each API has one set of
49
- printers and prices, so a lab runs one API.
50
- - **Models go only to your API.** The studio makes no other network calls.
51
- - **Prices are worked out in the browser.** The API returns weight and time, and the studio multiplies the weight by
52
- your price per gram. So you can change prices from your page, but you must not trust them when you charge
52
+ - **This package is the interface.** Your [slicer backend](#slicer-backend) does the slicing. Each backend has one set
53
+ of printers and prices, so a lab runs one backend.
54
+ - **Models go only to your backend.** The studio's only other calls are to your own servers, and only if you
55
+ [limit Advanced](#staff-access). Those carry no models.
56
+ - **Prices are worked out in the browser.** The backend returns weight and time, and the studio multiplies the weight
57
+ by your price per gram. So you can change prices from your page, but you must not trust them when you charge
53
58
  (see [Taking orders](#taking-orders)).
54
59
  - **The package is already built.** You get ready-made JavaScript in `dist/`, and `npm install` adds no other packages.
55
60
 
56
- ## Setup
61
+ ## Slicer backend
57
62
 
58
- You need Docker on the server that runs the API. On your website you need either npm or a page whose HTML you can edit.
63
+ The backend is a headless OrcaSlicer setup. The studio does no slicing itself, so it can't price anything without a backend.
59
64
 
60
- ### 1. Run slicer-api
65
+ The studio only talks to the five [routes](#routes) below, so the web server can be in any language.
66
+ [Headless OrcaSlicer](#headless-orcaslicer) shows how to set up the slicing behind them.
61
67
 
62
- ```bash
63
- git clone https://github.com/kerala-startup-mission/slicer-api.git
64
- cd slicer-api
65
- docker compose up --build -d
66
- ```
68
+ ### What each feature needs
69
+
70
+ | To use | The backend needs |
71
+ |---|---|
72
+ | Price page with `estimate` | `/health`, `/api/config` and `/api/quote`, working out weight and time from the model's shape. Also `/api/options` if you set a `defaultPrinter` |
73
+ | Price page with `exact` | The same, with a real slicer |
74
+ | Advanced slicing | A real slicer, G-code from `/api/quote`, and `/api/options`. Also `/api/printers` to offer more than your own printers |
75
+ | Opening G-code files in Advanced | Nothing. They stay in the browser |
67
76
 
68
- The first build downloads OrcaSlicer (about 150 MB) and takes a few minutes. Then check that it is running:
77
+ ### Routes
69
78
 
70
- ```bash
71
- curl http://localhost:3000/health
79
+ | Route | Used for |
80
+ |---|---|
81
+ | [`GET /health`](#get-health) | Is the backend up, and can it slice? |
82
+ | [`GET /api/config`](#get-apiconfig) | Your printers, prices and contact details |
83
+ | [`POST /api/quote`](#post-apiquote) | A model's weight, time and size, and its G-code |
84
+ | [`GET /api/options`](#get-apioptions) | What one printer offers |
85
+ | [`GET /api/printers`](#get-apiprinters) | Every printer you can slice for |
86
+
87
+ Every answer is JSON. If something fails, answer with an error status and a message, which the studio shows as it is:
88
+
89
+ ```json
90
+ { "error": "This model is too big for the printer's bed" }
72
91
  ```
73
92
 
74
- You should get `{"ok":true,"slicer":true}`.
93
+ `401` is special: the studio then asks for a key, and sends it as an `x-api-key` header (see
94
+ [Backend keys](#backend-keys)).
75
95
 
76
- ### 2. Set your printers and prices
96
+ #### `GET /health`
77
97
 
78
- Edit `config/printers.json` in slicer-api. Changes apply on the next page load, with no restart.
98
+ ```json
99
+ { "ok": true, "slicer": true }
100
+ ```
101
+
102
+ Set `slicer` to `false` if the backend can only estimate. Advanced then can't slice, and a price page on `exact` can't
103
+ give a price.
104
+
105
+ #### `GET /api/config`
79
106
 
80
107
  ```json
81
108
  {
82
- "currency": "INR",
83
- "pricePerGram": { "PLA": 6, "PETG": 7, "ABS": 8, "TPU": 7 },
84
- "priceRange": 20,
85
- "printers": [
86
- { "name": "Bambu Lab A1 0.4 nozzle", "default": true },
87
- { "name": "Bambu Lab P1S 0.4 nozzle" }
88
- ],
109
+ "printers": ["Bambu Lab A1 0.4 nozzle", "Bambu Lab P1S 0.4 nozzle"],
110
+ "defaultPrinter": "Bambu Lab A1 0.4 nozzle",
111
+ "pricing": { "currency": "INR", "perGram": { "PLA": 6, "PETG": 7, "ABS": 8, "TPU": 7 }, "range": 20 },
89
112
  "regularMode": { "supports": true, "mode": "estimate" },
90
113
  "contact": { "name": "Acme Labs", "email": "hello@example.com" }
91
114
  }
92
115
  ```
93
116
 
94
- Printer names must match OrcaSlicer's exactly. To find yours:
117
+ | Key | Meaning |
118
+ |---|---|
119
+ | `printers` | Your printers, listed first in Advanced. Use `[]` for none |
120
+ | `defaultPrinter` | The printer every price uses. `null` lets the backend pick |
121
+ | `pricing` | `currency`, `perGram` by material, and `range`, the percent the page adds on top. `null` shows no prices |
122
+ | `regularMode` | `supports`: whether prices include supports. `mode`: `estimate`, `exact` or `auto`, which means `exact` when `/health` says it can slice |
123
+ | `contact` | Your lab's `name`, and the `email` that SLA and SLS enquiries go to. Use `""` for neither |
95
124
 
96
- ```bash
97
- curl "http://localhost:3000/api/printers?q=bambu"
125
+ Your page can override everything here except `printers`, see [Options](#options).
126
+
127
+ #### `POST /api/quote`
128
+
129
+ The studio sends one request per file, as `multipart/form-data`:
130
+
131
+ | Field | Value | Sent by |
132
+ |---|---|---|
133
+ | `model` | The file: `.stl`, `.3mf`, `.obj`, `.step`, `.stp`, `.iges` or `.igs`, up to 50 MB | Always |
134
+ | `material` | Such as `PLA` | Always |
135
+ | `printer` | A printer's name | Whenever one is chosen |
136
+ | `quality` | `standard` (0.2 mm), `medium` (0.15 mm) or `high` (0.1 mm) | Price page. Advanced when set |
137
+ | `infill` | A percentage: `10`, `15`, `20`, `30`, `40`, `50`, `60`, `70`, `80` or `90` | Price page. Advanced when set |
138
+ | `walls` | `1` to `6` | Price page. Advanced when set |
139
+ | `supports` | `true` or `false` | Price page. Advanced when set |
140
+ | `rotX`, `rotY`, `rotZ` | `90`, `180` or `270`, the degrees to turn the model around each axis, in that order | When it's turned |
141
+ | `mode` | `estimate` or `exact` | Price page |
142
+ | `process`, `filament` | A preset's name, from `/api/options` | Advanced, when chosen |
143
+ | `gcode` | `true`: send the G-code back | Advanced |
144
+
145
+ Anything left out is yours to decide. Advanced leaves out `mode`, so slice for real.
146
+
147
+ ```json
148
+ {
149
+ "stats": { "weightG": 12.33, "seconds": 1437, "sizeMm": [30, 30, 30], "estimated": true },
150
+ "used": { "printer": "Bambu Lab A1 0.4 nozzle", "process": "0.20mm Standard", "filament": "Bambu PLA Basic" },
151
+ "gcode": "; the whole file as text\nG1 X10 Y10 E1\n"
152
+ }
98
153
  ```
99
154
 
100
- [Options](#options) explains each value. Your page can override all of them except `printers`.
155
+ | Key | Meaning |
156
+ |---|---|
157
+ | `stats.weightG` | Weight in grams, for one copy |
158
+ | `stats.seconds` | Print time in seconds, for one copy |
159
+ | `stats.sizeMm` | Width, depth and height in millimetres |
160
+ | `stats.estimated` | `true` if this came from the model's shape, not a slicer. Leave it out otherwise |
161
+ | `used` | Optional. What was really used, shown after slicing |
162
+ | `gcode` | Only when asked for. Comment lines such as `;TYPE:Outer wall` and `;LAYER_CHANGE`, as OrcaSlicer writes them, let the view colour features and split layers |
101
163
 
102
- ### 3. Allow your website
164
+ #### `GET /api/options`
103
165
 
104
- Browsers block calls to the API from other sites until you allow them. Set these in slicer-api's `docker-compose.yml`:
166
+ The studio asks this with `?printer=Bambu%20Lab%20A1%200.4%20nozzle&material=PLA`.
105
167
 
106
- ```yaml
107
- services:
108
- print-quote-api:
109
- environment:
110
- ALLOWED_ORIGINS: "https://www.example.com,https://example.com"
111
- RATE_LIMIT_PER_MIN: "30"
112
- TRUST_PROXY: "1"
168
+ ```json
169
+ {
170
+ "printer": "Bambu Lab A1 0.4 nozzle",
171
+ "defaultProcess": "0.20mm Standard",
172
+ "materials": ["PLA", "PETG", "ABS", "TPU"],
173
+ "processes": ["0.20mm Standard", "0.16mm High Quality"],
174
+ "filaments": [{ "name": "Bambu PLA Basic", "material": "PLA" }]
175
+ }
113
176
  ```
114
177
 
115
- | Setting | What it does |
178
+ `materials` is what the printer can use, and the studio offers no others. `filaments` lists the presets for the requested
179
+ material.
180
+
181
+ #### `GET /api/printers`
182
+
183
+ ```json
184
+ {
185
+ "printers": [{ "name": "Bambu Lab A1 0.4 nozzle", "vendor": "Bambu Lab", "model": "Bambu Lab A1", "nozzleMm": 0.4 }]
186
+ }
187
+ ```
188
+
189
+ Advanced groups these by brand, model and nozzle. Answer with an error if you have no list, and it offers only your own
190
+ printers and the backend's default.
191
+
192
+ ### Headless OrcaSlicer
193
+
194
+ OrcaSlicer is a desktop app, but it can also slice from the command line. On a server with no screen, the setup has four
195
+ parts:
196
+
197
+ | Part | What it does |
198
+ |---|---|
199
+ | OrcaSlicer | Slices the model. Use the Linux AppImage, unpacked so it doesn't need FUSE |
200
+ | System libraries | What OrcaSlicer needs to start, such as GTK and OpenGL |
201
+ | Xvfb | A virtual display, because OrcaSlicer needs one on Linux even from the command line |
202
+ | Your web server | Answers the routes, runs OrcaSlicer for each request, and reads the result |
203
+
204
+ A container keeps these together. This installs everything except your web server, on x86-64. For arm64, use the file
205
+ with `aarch64` before the version in its name.
206
+
207
+ ```dockerfile
208
+ FROM ubuntu:24.04
209
+
210
+ RUN apt-get update && apt-get install -y --no-install-recommends \
211
+ ca-certificates curl xvfb xauth \
212
+ libgtk-3-0t64 libwebkit2gtk-4.1-0 libgl1 libglu1-mesa libegl1 libosmesa6 \
213
+ libxkbcommon0 libdbus-1-3 libsecret-1-0 libnss3
214
+
215
+ RUN curl -fL https://github.com/OrcaSlicer/OrcaSlicer/releases/download/v2.4.2/OrcaSlicer_Linux_AppImage_Ubuntu2404_V2.4.2.AppImage -o /tmp/orca.AppImage \
216
+ && chmod +x /tmp/orca.AppImage \
217
+ && cd /tmp && ./orca.AppImage --appimage-extract >/dev/null \
218
+ && mv /tmp/squashfs-root /opt/orca \
219
+ && rm /tmp/orca.AppImage
220
+ ```
221
+
222
+ **To slice a model,** start from a 3MF project saved in OrcaSlicer's desktop app. A 3MF is a zip, so for each request copy
223
+ that template, put the customer's mesh in it, and run this in a new folder. `HOME` must be a writable folder.
224
+
225
+ ```bash
226
+ HOME=/tmp/orca-home xvfb-run -a /opt/orca/AppRun --slice 1 --outputdir /tmp/job --export-3mf out.gcode.3mf \
227
+ --sparse-infill-density=15% --layer-height=0.2 --wall-loops=3 --enable-support=1 \
228
+ /tmp/job/job.3mf
229
+ ```
230
+
231
+ That writes `plate_1.gcode` to the output folder, with a `result.json` whose `error_string` says why if it fails. Inside
232
+ the 3MF, the mesh is in `3D/Objects/`, its position is in `3D/3dmodel.model` and `Metadata/model_settings.config`, and
233
+ the printer and presets are in `Metadata/project_settings.config`.
234
+
235
+ **Each part of an answer** comes from here:
236
+
237
+ | The studio needs | Where it comes from |
116
238
  |---|---|
117
- | `ALLOWED_ORIGINS` | The sites that embed the studio, comma-separated. An origin is the scheme, host and port, with no path, such as `http://localhost:5173`. |
118
- | `RATE_LIMIT_PER_MIN` | Quotes per minute per visitor. Slices run one at a time, so turn this on for any public API. Each file is one request and a customer can send 10 at once, so 30 is a fair start. |
119
- | `TRUST_PROXY` | How many proxies sit in front of the API. Without it, all visitors behind a proxy share one rate limit. |
239
+ | `slicer` in `/health` | Whether OrcaSlicer is installed |
240
+ | `/api/printers`, `/api/options` | OrcaSlicer's own presets: JSON files in `/opt/orca/resources/profiles/<vendor>/`, under `machine`, `process` and `filament`. Follow each preset's `inherits` to get all its values |
241
+ | `infill`, `quality`, `walls`, `supports` | The `--sparse-infill-density`, `--layer-height`, `--wall-loops` and `--enable-support` flags |
242
+ | `printer`, `process`, `filament` | Those presets' values, merged into the project's `Metadata/project_settings.config` |
243
+ | `weightG` | The G-code line `; filament used [g] = 4.00` |
244
+ | `seconds` | The G-code line `; estimated printing time (normal mode) = 9m 54s`, or `model printing time:` on Bambu printers |
245
+ | `gcode` | The text of `plate_1.gcode` |
246
+ | `.3mf` and `.obj` uploads | `--export-stl --outputdir <folder> <file>` writes STL files to `<folder>/stl`, ready for the template |
247
+ | `.step` and `.iges` uploads | A CAD reader such as `occt-import-js`, which turns them into a mesh |
248
+ | `mode=estimate` | Not OrcaSlicer. Work weight and time out from the mesh's volume, which is instant |
249
+
250
+ **To keep it reliable:**
251
+
252
+ - **Slice one at a time.** OrcaSlicer is heavy, so queue requests and let them wait their turn.
253
+ - **Stop a slice that runs too long.** Kill it after a limit, such as 3 minutes, and answer with an error.
254
+ - **Delete each job's folder** afterwards.
255
+ - **Check the model fits first.** `printable_area` and `printable_height` in the `machine` preset give the printer's size.
256
+ - **Expect a few bad presets.** Some vendor presets fail OrcaSlicer's own checks. Its log names the value, so you can
257
+ correct it and try again.
258
+
259
+ ## Setup
260
+
261
+ You need a server to run the backend. On your website you need either npm or a page whose HTML you can edit.
262
+
263
+ ### 1. Run a slicer backend
120
264
 
121
- Then apply the changes:
265
+ Set up [headless OrcaSlicer](#headless-orcaslicer) behind a web server that answers the [routes](#routes), then check that
266
+ it answers:
122
267
 
123
268
  ```bash
124
- docker compose up -d
269
+ curl http://localhost:3000/health
270
+ ```
271
+
272
+ You should get `{"ok":true,"slicer":true}`.
273
+
274
+ ### 2. Set your printers and prices
275
+
276
+ Make [`/api/config`](#get-apiconfig) answer with your own printers, prices and contact details. The studio reads this
277
+ each time a page loads, so changes need no update to your site.
278
+
279
+ ### 3. Allow your website
280
+
281
+ Browsers block calls to the backend from other sites until it allows them. Have every route answer with your site's
282
+ exact origin, which is its scheme, host and port, with no path:
283
+
284
+ ```text
285
+ Access-Control-Allow-Origin: https://www.example.com
286
+ Vary: Origin
287
+ ```
288
+
289
+ Uploads need nothing more. If you use a [key](#backend-keys), also answer `OPTIONS` requests with these:
290
+
291
+ ```text
292
+ Access-Control-Allow-Methods: GET, POST
293
+ Access-Control-Allow-Headers: x-api-key
125
294
  ```
126
295
 
127
- ### 4. Serve the API over HTTPS
296
+ You can skip this step by forwarding `/api/` and `/health` from your own domain. The studio then calls your site's own
297
+ origin, so leave out `api-url`.
298
+
299
+ ### 4. Serve it over HTTPS
128
300
 
129
- A page on `https://` can't call an `http://` API, so a live site needs HTTPS on the API too. Put a proxy in front of it.
130
- With nginx:
301
+ A page on `https://` can't call an `http://` backend, so a live site needs HTTPS on the backend too. Put a proxy in front
302
+ of it. With nginx:
131
303
 
132
304
  ```nginx
133
305
  server {
@@ -138,7 +310,7 @@ server {
138
310
  client_max_body_size 55m; # models can be up to 50 MB
139
311
 
140
312
  location / {
141
- proxy_pass http://127.0.0.1:3000;
313
+ proxy_pass http://127.0.0.1:3000; # your backend
142
314
  proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
143
315
  proxy_read_timeout 300s; # a slice can wait for others in the queue
144
316
  proxy_send_timeout 300s;
@@ -146,10 +318,17 @@ server {
146
318
  }
147
319
  ```
148
320
 
149
- You can also forward `/api/` and `/health` from your own domain. The studio then calls your site's own origin, so leave
150
- out `api-url` and `ALLOWED_ORIGINS`.
321
+ ### 5. Set its limits
322
+
323
+ Slicing is heavy, and anyone can call a public backend, so set these however your server does:
324
+
325
+ | Limit | Why |
326
+ |---|---|
327
+ | Requests per visitor | Each file is one request and a customer can send 10 at once, so 30 a minute is a fair start |
328
+ | 50 MB per upload | The studio won't send more than this, so everything in front of the backend must accept it |
329
+ | At least 300 seconds per request | A slice can take minutes, more so when it waits for others |
151
330
 
152
- ### 5. Add the studio to your page
331
+ ### 6. Add the studio to your page
153
332
 
154
333
  ```bash
155
334
  npm install slicer-studio
@@ -167,7 +346,7 @@ import 'slicer-studio';
167
346
 
168
347
  [Frameworks](#frameworks) shows this for your stack, including how to use it without npm.
169
348
 
170
- ### 6. Check that it works
349
+ ### 7. Check that it works
171
350
 
172
351
  1. Open your page. The studio should appear.
173
352
  2. Drop an STL file on it.
@@ -175,9 +354,14 @@ import 'slicer-studio';
175
354
 
176
355
  If it doesn't, see [Troubleshooting](#troubleshooting). Your browser's console usually names the problem.
177
356
 
357
+ ### 8. Limit Advanced to staff
358
+
359
+ This step is optional. Until you do it, anyone who sets `mode="advanced"` can open Advanced. See
360
+ [Staff access](#staff-access).
361
+
178
362
  ## Frameworks
179
363
 
180
- Every example sets the same two options and logs the price. Replace `https://api.example.com` with your API.
364
+ Every example sets the same two options and logs the price. Replace `https://api.example.com` with your backend.
181
365
 
182
366
  Tested on Vite 8, React 18.3 and 19.3, Next.js 16, Vue 3.5, Nuxt 4, Angular 20, Svelte 5 and Laravel 13.
183
367
 
@@ -186,7 +370,7 @@ Tested on Vite 8, React 18.3 and 19.3, Next.js 16, Vue 3.5, Nuxt 4, Angular 20,
186
370
  No npm or build step. Load it from a CDN:
187
371
 
188
372
  ```html
189
- <script type="module" src="https://cdn.jsdelivr.net/npm/slicer-studio@0.1.0/dist/slicer-studio.js"></script>
373
+ <script type="module" src="https://cdn.jsdelivr.net/npm/slicer-studio@0.2.0/dist/slicer-studio.js"></script>
190
374
 
191
375
  <slicer-studio api-url="https://api.example.com"></slicer-studio>
192
376
 
@@ -385,7 +569,7 @@ import 'slicer-studio';
385
569
  document.querySelector('slicer-studio')?.addEventListener('estimate', e => console.log(e.detail));
386
570
  ```
387
571
 
388
- Add the API's address to `.env`, and read it in `config/services.php`:
572
+ Add the backend's address to `.env`, and read it in `config/services.php`:
389
573
 
390
574
  ```dotenv
391
575
  SLICER_API_URL=https://api.example.com
@@ -459,7 +643,7 @@ const studio = useRef<SlicerStudioElement>(null);
459
643
 
460
644
  | Attribute | Values | Default |
461
645
  |---|---|---|
462
- | `api-url` | The address of your slicer-api | Your page's own origin |
646
+ | `api-url` | The address of your [slicer backend](#slicer-backend) | Your page's own origin |
463
647
  | `mode` | `quote` (the price page) or `advanced` (the staff tools) | `quote` |
464
648
  | `theme` | `light`, `dark` or `system`. Setting it hides the theme switch | Follows the device, and visitors can switch |
465
649
  | `config` | JSON of the [options](#options) | Nothing overridden |
@@ -468,12 +652,12 @@ You can change any of them at any time. Changing `api-url` or `mode` clears the
468
652
 
469
653
  ## Options
470
654
 
471
- Options override slicer-api's `printers.json` for this page. Every key is optional. Set them as a property, which is
472
- easiest from JavaScript, or as JSON in the `config` attribute, which suits server templates.
655
+ Options override your backend's [`/api/config`](#get-apiconfig) for this page. Every key is optional. Set them as a
656
+ property, which is easiest from JavaScript, or as JSON in the `config` attribute, which suits server templates.
473
657
 
474
658
  ```js
475
659
  document.querySelector('slicer-studio').config = {
476
- // the same names as printers.json, and they win over it
660
+ // these win over your backend's /api/config
477
661
  currency: 'INR',
478
662
  pricePerGram: { PLA: 5, PETG: 6 },
479
663
  priceRange: 15,
@@ -486,6 +670,12 @@ document.querySelector('slicer-studio').config = {
486
670
 
487
671
  // the cards to show; all of them when left out
488
672
  cards: ['model', 'files', 'material', 'cost'],
673
+
674
+ // the servers that approve Advanced; anyone can open it when left out
675
+ advanced: {
676
+ authUrl: 'https://www.example.com/slicer-token',
677
+ verifyUrl: 'https://www.example.com/slicer-verify',
678
+ },
489
679
  };
490
680
  ```
491
681
 
@@ -495,21 +685,23 @@ document.querySelector('slicer-studio').config = {
495
685
  | `pricePerGram` | Price per gram by material. Only the materials you list change |
496
686
  | `priceRange` | Shows cost, weight and time as a range, from the calculated figure up to this percent more. `0` shows exact figures |
497
687
  | `regularMode.supports` | `true` if estimates include supports |
498
- | `regularMode.mode` | `estimate` is instant, from the model's shape. `exact` is sliced by OrcaSlicer, and takes seconds to minutes per file. `auto` uses `exact` when the server has OrcaSlicer |
688
+ | `regularMode.mode` | `estimate` is instant, from the model's shape. `exact` is sliced for real, and takes seconds to minutes per file. `auto` uses `exact` when `/health` says the backend can slice |
499
689
  | `contact` | Your lab's `name`, and the `email` that SLA and SLS enquiries go to. The email button hides while no email is set |
500
- | `defaultPrinter` | The printer for estimates, which must be one the API has profiles for |
690
+ | `defaultPrinter` | The printer for estimates, which must be one your backend knows |
501
691
  | `defaults.material` | `PLA`, `PETG`, `ABS` or `TPU`. If the printer doesn't offer it, the first one it does offer is used |
502
692
  | `defaults.quality` | `standard` (0.2 mm), `medium` (0.15 mm) or `high` (0.1 mm) |
503
693
  | `defaults.infill` | `10`, `15`, `20`, `30`, `40`, `50`, `60`, `70`, `80` or `90` |
504
694
  | `defaults.walls` | `1` to `6` |
505
695
  | `cards` | Which [cards](#cards) to show |
696
+ | `advanced` | The two servers that approve Advanced, see [Staff access](#staff-access) |
506
697
 
507
698
  - Setting `config` replaces the whole object, so include everything you want each time.
508
- - `pricePerGram`, `regularMode` and `contact` merge with the API's values key by key.
699
+ - `pricePerGram`, `regularMode` and `contact` merge with your backend's values key by key.
509
700
  - `defaults` apply to files added after they are set.
510
- - Anything invalid is left out, with a `slicer-studio:` warning in the console.
511
- - In `advanced` mode, only `defaultPrinter` has an effect, and only until someone picks a printer. The studio then
512
- remembers their choice.
701
+ - Anything invalid is left out, with a `slicer-studio:` warning in the console. The exception is `advanced`: if it's
702
+ there without both URLs, Advanced stays closed.
703
+ - In `advanced` mode, only `defaultPrinter` and `advanced` have an effect, and `defaultPrinter` only until someone picks a
704
+ printer. The studio then remembers their choice.
513
705
 
514
706
  ### Cards
515
707
 
@@ -567,14 +759,20 @@ With `priceRange` at `0`, `low` and `high` are the same exact figure. Otherwise
567
759
 
568
760
  ### `modechange`
569
761
 
570
- Fires when someone uses the Simple / Advanced switch, with `{ mode }` in `detail`. The switch only appears in `advanced`
571
- mode, and setting the attribute yourself doesn't fire the event.
762
+ Fires when someone uses the Simple / Advanced switch, or a refused visitor is sent back to the price page, with `{ mode }`
763
+ in `detail`. The switch only appears in `advanced` mode, and setting the attribute yourself doesn't fire the event.
764
+
765
+ ### `advanceddenied`
766
+
767
+ Fires when your servers don't approve a visitor for Advanced, just before the studio returns to the price page. Use it to
768
+ show your own sign-in. `e.detail.reason` is `refused`, `unreachable` or `not-set-up`, see
769
+ [When the check fails](#when-the-check-fails).
572
770
 
573
771
  ### `getPrice()`
574
772
 
575
773
  Prices every file that needs it, and `estimate` fires when it's done. If everything is already priced, `estimate` fires
576
774
  again. It does nothing while there are no files, while SLA or SLS is selected, while a price is being worked out, or
577
- when the API can't be reached.
775
+ when the backend can't be reached.
578
776
 
579
777
  The element needs to be loaded first, so wait for it if your code might run earlier:
580
778
 
@@ -632,7 +830,7 @@ orderButton.addEventListener('click', async () => {
632
830
  });
633
831
  ```
634
832
 
635
- Then have your server ask slicer-api for each file's weight, with the same settings:
833
+ Then have your server ask your backend for each file's weight, with the same settings:
636
834
 
637
835
  ```bash
638
836
  curl https://api.example.com/api/quote \
@@ -644,7 +842,7 @@ curl https://api.example.com/api/quote \
644
842
  ```
645
843
 
646
844
  ```json
647
- { "stats": { "weightG": 12.33, "seconds": 1437, "sizeMm": [30, 30, 30], "volumeCm3": 27, "watertight": true, "estimated": true } }
845
+ { "stats": { "weightG": 12.33, "seconds": 1437, "sizeMm": [30, 30, 30], "estimated": true } }
648
846
  ```
649
847
 
650
848
  - The studio's `settings` leave out the printer, supports and mode. Send your `defaultPrinter`, `regularMode.supports` and
@@ -654,13 +852,184 @@ curl https://api.example.com/api/quote \
654
852
 
655
853
  ## Staff access
656
854
 
657
- `mode="advanced"` is not a lock. Anyone can change an attribute in their browser's tools, so put staff pages behind your
658
- own login.
855
+ Anyone can open Advanced until you set `advanced` in the [options](#options). With it set, the studio asks your own
856
+ servers before it shows Advanced to a visitor.
857
+
858
+ **This controls what the studio shows. It doesn't protect your backend.** A visitor can change the config in their
859
+ browser's tools and open Advanced anyway. Anyone can also call a public backend directly, including with `gcode=true`,
860
+ unless the backend itself refuses. If slicing must stay private, keep the backend private behind a
861
+ [key](#backend-keys), with no public price page.
862
+
863
+ ### How it works
864
+
865
+ Your site decides who gets in. The studio only asks it and acts on the answer, and your slicer backend takes no part.
866
+
867
+ ```text
868
+ Staff member signs in to your site (your login, your cookie)
869
+ |
870
+ Your page sets mode="advanced"
871
+ |
872
+ Studio shows "Checking your access…" (Advanced isn't loaded yet)
873
+ |
874
+ 1. POST authUrl, with cookies, body {}
875
+ | Your server checks the login
876
+ | Staff: 200 { "token": "..." }, signed with your private key
877
+ | Not staff: 403
878
+ |
879
+ 2. POST verifyUrl, no cookies, body { "token": "..." }
880
+ | Your server checks the signature and expiry with your public key
881
+ | Valid: 200 { "valid": true }
882
+ | Not valid: 403
883
+ |
884
+ 3. Both passed: Advanced opens
885
+ Anything else: back to the price page
886
+ ```
887
+
888
+ | Who | Holds |
889
+ |---|---|
890
+ | Your page | The two URLs |
891
+ | Your servers | Your login, the private key and the public key |
892
+ | The studio | No keys. It passes the token along, then forgets it |
893
+ | Your slicer backend | Nothing. It never sees the token |
894
+
895
+ Once Advanced is open, slicing goes to your backend as usual. Nothing checks again while it stays open, even after the
896
+ token expires. When someone leaves Advanced and comes back the whole check runs again, which is automatic if they're
897
+ still signed in.
898
+
899
+ ### When the check fails
900
+
901
+ The visitor sees a toast and goes back to the price page, and [`advanceddenied`](#advanceddenied) fires with the reason.
902
+ To try again, set `mode="advanced"` again.
903
+
904
+ | Reason | What happened | Toast |
905
+ |---|---|---|
906
+ | `refused` | A server said no, or gave a bad answer | `Advanced is for staff. Sign in and try again.` |
907
+ | `unreachable` | A server was down or blocked, or took over 8 seconds | `We couldn’t check your access. Please try again.` |
908
+ | `not-set-up` | `advanced` is missing a URL | `Advanced isn’t set up on this page.` |
909
+
910
+ ### Set it up
911
+
912
+ Name your two servers, then set `mode`. They can be the same server, and either can be a path on your own site, such as
913
+ `/slicer-token`.
914
+
915
+ ```js
916
+ studio.config = {
917
+ advanced: {
918
+ authUrl: 'https://www.example.com/slicer-token',
919
+ verifyUrl: 'https://www.example.com/slicer-verify',
920
+ },
921
+ };
922
+ studio.setAttribute('mode', 'advanced');
923
+ ```
924
+
925
+ Set `config` first, or use the JSON attribute. If `mode` comes first, Advanced can show for a moment before the check
926
+ starts.
927
+
928
+ Then add two routes. Any other answer refuses the visitor, and each call has 8 seconds.
929
+
930
+ | Route | The studio sends | Your answer to approve |
931
+ |---|---|---|
932
+ | `authUrl` | `POST` with cookies, body `{}` | `200` with `{ "token": "..." }` |
933
+ | `verifyUrl` | `POST` without cookies, body `{ "token": "..." }` | `200` with `{ "valid": true }` |
934
+
935
+ The token's format is up to you. The studio only passes it along, and doesn't keep it. A short signed JWT works well, so
936
+ make a key pair and keep both keys on your servers:
937
+
938
+ ```bash
939
+ openssl ecparam -name prime256v1 -genkey -noout -out slicer-private.pem
940
+ ```
941
+
942
+ ```bash
943
+ openssl ec -in slicer-private.pem -pubout -out slicer-public.pem
944
+ ```
945
+
946
+ In these examples, replace the staff check with your own.
947
+
948
+ **Laravel,** with `firebase/php-jwt`, in `routes/web.php`:
949
+
950
+ ```php
951
+ use Firebase\JWT\JWT;
952
+ use Firebase\JWT\Key;
953
+ use Illuminate\Http\Request;
954
+
955
+ Route::post('/slicer-token', function (Request $request) {
956
+ abort_unless($request->user()?->is_staff, 403);
957
+
958
+ $token = JWT::encode(
959
+ ['sub' => (string) $request->user()->id, 'iat' => time(), 'exp' => time() + 900],
960
+ file_get_contents(storage_path('slicer-private.pem')),
961
+ 'ES256',
962
+ );
963
+
964
+ return response()->json(['token' => $token])->header('Cache-Control', 'no-store');
965
+ });
966
+
967
+ Route::post('/slicer-verify', function (Request $request) {
968
+ try {
969
+ JWT::decode((string) $request->input('token'), new Key(file_get_contents(storage_path('slicer-public.pem')), 'ES256'));
970
+ } catch (Throwable) {
971
+ return response()->json(['valid' => false], 403);
972
+ }
973
+
974
+ return response()->json(['valid' => true]);
975
+ });
976
+ ```
977
+
978
+ The studio can't send a CSRF token, so exempt both routes in `bootstrap/app.php`:
979
+
980
+ ```php
981
+ ->withMiddleware(function (Middleware $middleware) {
982
+ $middleware->validateCsrfTokens(except: ['slicer-token', 'slicer-verify']);
983
+ })
984
+ ```
985
+
986
+ **Node,** with `express` and `jsonwebtoken`:
987
+
988
+ ```js
989
+ import fs from 'node:fs';
990
+ import express from 'express';
991
+ import jwt from 'jsonwebtoken';
992
+
993
+ const privateKey = fs.readFileSync('slicer-private.pem');
994
+ const publicKey = fs.readFileSync('slicer-public.pem');
995
+
996
+ app.post('/slicer-token', requireStaff, (req, res) => {
997
+ const token = jwt.sign({ sub: String(req.user.id) }, privateKey, { algorithm: 'ES256', expiresIn: 900 });
998
+ res.set('Cache-Control', 'no-store').json({ token });
999
+ });
1000
+
1001
+ app.post('/slicer-verify', express.json(), (req, res) => {
1002
+ try {
1003
+ jwt.verify(req.body.token, publicKey, { algorithms: ['ES256'] });
1004
+ res.json({ valid: true });
1005
+ } catch {
1006
+ res.status(403).json({ valid: false });
1007
+ }
1008
+ });
1009
+ ```
1010
+
1011
+ ### Keep `authUrl` safe
1012
+
1013
+ - **Only answer `POST`,** with `Cache-Control: no-store`.
1014
+ - **On another origin, allow your page's exact origin.** Send `Access-Control-Allow-Credentials: true`, and allow the
1015
+ `content-type` header. Never echo the request's `Origin` back, or any site could get a token for your signed-in staff.
1016
+ - **Use `SameSite=Lax` cookies,** and keep `authUrl` on the same site as the page. In a cross-site iframe the browser sends
1017
+ no cookies, so staff are refused.
1018
+ - **Keep tokens short.** 15 minutes is plenty. The studio checks each time someone enters Advanced, and doesn't close it
1019
+ when a token expires.
1020
+
1021
+ `verifyUrl` on another origin only needs your page's origin and the `content-type` header.
1022
+
1023
+ ### Backend keys
1024
+
1025
+ A backend can require a key, which is a separate choice from the check above.
659
1026
 
660
- - **Don't use `API_KEY` on an API that serves a public price page.** The studio could load but not price anything, and a
661
- key in a page's source isn't secret. That is why there is no attribute for one.
662
- - **`API_KEY` does suit a staff-only API.** Advanced shows a key button, and keeps the key in that browser.
663
- - **`ALLOWED_ORIGINS` limits browsers, not scripts,** so a public API still needs `RATE_LIMIT_PER_MIN`.
1027
+ - **Don't require one on a backend that serves a public price page.** The studio could load but not price anything, and
1028
+ a key in a page's source isn't secret. That is why there is no attribute for one.
1029
+ - **It does suit a staff-only backend.** Advanced has a key button, keeps the key in that browser, and sends it as
1030
+ `x-api-key` to `/api/printers`, `/api/options` and `/api/quote`. Keep `/health` and `/api/config` open, because the
1031
+ studio sends no key to them.
1032
+ - **CORS limits browsers, not scripts,** so a public backend still needs a limit per visitor.
664
1033
 
665
1034
  ## Content Security Policy
666
1035
 
@@ -677,7 +1046,7 @@ worker-src blob:;
677
1046
  | Directive | Why |
678
1047
  |---|---|
679
1048
  | `script-src` | Add `https://cdn.jsdelivr.net` if you load the package from the CDN |
680
- | `connect-src` | Your API. Leave it as `'self'` if the API is on your own origin |
1049
+ | `connect-src` | Your backend, and `authUrl` and `verifyUrl` if you set them. Use `'self'` for anything on your own origin |
681
1050
  | `img-src` | Model pictures on the file cards |
682
1051
  | `font-src` | The fonts are built in as data URIs. Without this the studio uses system fonts |
683
1052
  | `worker-src` | Advanced's G-code reader. Without this it shows `Could not read this G-code: parser failed` |
@@ -690,12 +1059,17 @@ from the toast library. They are harmless, because the studio's styles don't dep
690
1059
  | What you see | Cause | Fix |
691
1060
  |---|---|---|
692
1061
  | Nothing on the page, and the tag has no size | The package didn't load | Run `customElements.get('slicer-studio')` in the console. If it's `undefined`, check your import or script tag |
693
- | `The server can't be reached.` and `blocked by CORS policy` in the console | Your site isn't allowed | Add its exact origin to `ALLOWED_ORIGINS`, then run `docker compose up -d` |
694
- | `The server can't be reached.` and `ERR_CONNECTION_REFUSED` in the console | Wrong `api-url`, or the API is down | Check `https://your-api/health` in a browser |
695
- | `The server can't be reached.` and `Mixed Content` in the console | An `https://` page is calling an `http://` API | [Serve the API over HTTPS](#4-serve-the-api-over-https) |
1062
+ | `The server can't be reached.` and `blocked by CORS policy` in the console | Your site isn't allowed | Have the backend send your exact origin, see [Allow your website](#3-allow-your-website) |
1063
+ | `The server can't be reached.` and `ERR_CONNECTION_REFUSED` in the console | Wrong `api-url`, or the backend is down | Check `https://your-backend/health` in a browser |
1064
+ | `The server can't be reached.` and `Mixed Content` in the console | An `https://` page is calling an `http://` backend | [Serve it over HTTPS](#4-serve-it-over-https) |
1065
+ | `Prices can't be worked out right now.` | The price page is on `exact`, and `/health` says `slicer: false` | Fix the slicer, or use `estimate` |
1066
+ | `Slicing is off on this server.` in Advanced | `/health` says `slicer: false` | Fix the slicer. G-code files still open |
696
1067
  | `No price set for PLA yet` | That material has no price | Add it to `pricePerGram` |
697
- | `Missing or wrong x-api-key` | The API has `API_KEY` set | Remove it from a public API, see [Staff access](#staff-access) |
698
- | `Too many requests. Try again in a minute.` | The rate limit was reached | Raise `RATE_LIMIT_PER_MIN` |
1068
+ | `This server needs an API key.` | The backend answered `401` | Remove the key from a public backend, see [Backend keys](#backend-keys) |
1069
+ | `Advanced is for staff. Sign in and try again.` for someone who is signed in | `authUrl` got no cookie, or a server said no | Check both calls in the Network tab, and see [Keep `authUrl` safe](#keep-authurl-safe) |
1070
+ | `We couldn't check your access. Please try again.` | CORS, CSP, a wrong URL, or a server took over 8 seconds | The console names it. Check the CORS headers and `connect-src` |
1071
+ | `Advanced isn't set up on this page.` | `advanced` is missing a URL | Set both, see [Staff access](#staff-access) |
1072
+ | Your backend's own message about too many requests | Your limit per visitor is too low | Raise it. Each file is one request |
699
1073
  | A large file fails, with status 413 in the browser's Network tab | Your proxy's upload limit is too low | Raise `client_max_body_size` in nginx |
700
1074
  | `slicer-studio: config is not valid JSON` | An object reached the `config` attribute as `[object Object]` | Set the `config` property in an effect, or use `JSON.stringify` |
701
1075
  | `slicer-studio: unknown config key` | A typo in an option's name | Check it against [Options](#options) |
@@ -708,8 +1082,8 @@ from the toast library. They are harmless, because the studio's styles don't dep
708
1082
  ## Good to know
709
1083
 
710
1084
  - **Browsers:** Chrome and Edge 111+, Firefox 128+, Safari 16.4+. The 3D views need WebGL.
711
- - **Files:** STL, 3MF, OBJ, STEP and IGES, up to 10 at once and 50 MB each, with at most 500,000 triangles. STEP and IGES
712
- are priced but have no 3D preview. A model too big for the printer's bed gets an error on its card.
1085
+ - **Files:** STL, 3MF, OBJ, STEP and IGES, up to 10 at once and 50 MB each. STEP and IGES are priced but have no 3D
1086
+ preview. If your backend refuses a file, its message shows on that file's card.
713
1087
  - **Size:** about 210 kB gzipped to start, with the 3D view (about 250 kB) and the fonts (about 240 kB) loading after.
714
1088
  - **Server rendering:** importing the package on a server is safe, and does nothing. The studio has no server-rendered
715
1089
  content, so set `config` and listeners in browser code, or give `config` as a JSON attribute.
@@ -720,7 +1094,7 @@ from the toast library. They are harmless, because the studio's styles don't dep
720
1094
  - **What it stores:** in `localStorage`, the visitor's theme (`print-preview.theme`) and, in Advanced, the last printer
721
1095
  (`print-preview.printer`) and the API key (`gcode-viewer.api-key`).
722
1096
  - **Updating:** run `npm update slicer-studio`, or change the version in your CDN link. Price and printer changes need no
723
- update, because the studio reads them from the API.
1097
+ update, because the studio reads them from your backend.
724
1098
 
725
1099
  ## License
726
1100