kiosko-plugin-3d-printer 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js ADDED
@@ -0,0 +1,1925 @@
1
+ import { createRequire as __pluginRequire } from 'node:module'; const require = __pluginRequire(import.meta.url);
2
+
3
+ // src/index.ts
4
+ import { definePlugin } from "@kiosko/sdk";
5
+
6
+ // src/camera.ts
7
+ import { defineWidget, drawEmpty, t as t2 } from "@kiosko/sdk";
8
+
9
+ // src/demo.ts
10
+ import { localize } from "@kiosko/sdk";
11
+
12
+ // src/i18n.ts
13
+ var L = (en, es, de, hans, hant) => ({ en, es, de, "zh-Hans": hans, "zh-Hant": hant });
14
+ var LANGUAGES = ["en", "es", "de", "zh-Hant", "zh-Hans"];
15
+
16
+ // src/demo.ts
17
+ var MIN = 6e4;
18
+ function demoStatus(now, locale) {
19
+ const name = localize(L("Workshop", "Taller", "Werkstatt", "\u5DE5\u4F5C\u5BA4", "\u5DE5\u4F5C\u5BA4"), locale);
20
+ return {
21
+ configured: true,
22
+ backend: "moonraker",
23
+ name,
24
+ phase: "printing",
25
+ job: { name: "gearbox_housing_PETG", progress: 0.62, startedAt: now - 128 * MIN, elapsedMs: 124 * MIN, leftMs: 72 * MIN, layer: 143, layers: 231 },
26
+ nozzle: { now: 239.6, target: 240 },
27
+ bed: { now: 80.1, target: 80 },
28
+ camera: "http://printer.example/webcam/?action=snapshot",
29
+ at: now,
30
+ demo: true
31
+ };
32
+ }
33
+ var PLASTIC = { top: [242, 140, 40], side: [196, 98, 22], dark: [120, 56, 10] };
34
+ var rgb = (c, k = 1) => `rgb(${c.map((v) => Math.round(Math.min(255, v * k))).join(",")})`;
35
+ function gearRadius(a, teeth, outer, root) {
36
+ const phase = a / (Math.PI * 2) * teeth % 1;
37
+ const f = phase < 0.15 ? phase / 0.15 : phase < 0.45 ? 1 : phase < 0.6 ? 1 - (phase - 0.45) / 0.15 : 0;
38
+ return root + (outer - root) * f;
39
+ }
40
+ function drawGear(g, cx, cy, R, depth, tilt, light = 1) {
41
+ const teeth = 14;
42
+ const root = R * 0.82;
43
+ const bore = R * 0.3;
44
+ const N = 280;
45
+ const pt = (i, r) => {
46
+ const a = i / N * Math.PI * 2;
47
+ const rr = r ?? gearRadius(a, teeth, R, root);
48
+ return [cx + Math.cos(a) * rr, cy + Math.sin(a) * rr * tilt];
49
+ };
50
+ for (let i = 0; i < N; i++) {
51
+ const [x0, y0] = pt(i);
52
+ const [x1, y1] = pt(i + 1);
53
+ const a = (i + 0.5) / N * Math.PI * 2;
54
+ if (Math.sin(a) < -0.05) continue;
55
+ const shade = 0.55 + 0.45 * Math.max(0, Math.cos(a - 0.9));
56
+ g.fillStyle = rgb(PLASTIC.side, shade * light);
57
+ g.beginPath();
58
+ g.moveTo(x0, y0);
59
+ g.lineTo(x1, y1);
60
+ g.lineTo(x1, y1 + depth);
61
+ g.lineTo(x0, y0 + depth);
62
+ g.closePath();
63
+ g.fill();
64
+ }
65
+ g.beginPath();
66
+ for (let i = 0; i <= N; i++) {
67
+ const [x, y] = pt(i);
68
+ if (i === 0) g.moveTo(x, y);
69
+ else g.lineTo(x, y);
70
+ }
71
+ g.closePath();
72
+ const top = g.createLinearGradient(cx - R, cy - R * tilt, cx + R, cy + R * tilt);
73
+ top.addColorStop(0, rgb(PLASTIC.top, 1.08 * light));
74
+ top.addColorStop(1, rgb(PLASTIC.top, 0.86 * light));
75
+ g.fillStyle = top;
76
+ g.fill();
77
+ g.strokeStyle = rgb(PLASTIC.side, 0.9 * light);
78
+ g.lineWidth = Math.max(0.6, R * 0.012);
79
+ for (const k of [0.45, 0.6, 0.72]) {
80
+ g.beginPath();
81
+ g.ellipse(cx, cy, R * k, R * k * tilt, 0, 0, Math.PI * 2);
82
+ g.stroke();
83
+ }
84
+ g.beginPath();
85
+ g.ellipse(cx, cy, bore, bore * tilt, 0, 0, Math.PI * 2);
86
+ g.fillStyle = rgb(PLASTIC.dark, light);
87
+ g.fill();
88
+ g.save();
89
+ g.clip();
90
+ g.fillStyle = rgb(PLASTIC.side, 0.75 * light);
91
+ g.beginPath();
92
+ g.ellipse(cx, cy - Math.min(depth, bore * 1.2) * 0.9, bore, bore * tilt, 0, Math.PI, Math.PI * 2);
93
+ g.ellipse(cx, cy, bore, bore * tilt, 0, Math.PI * 2, Math.PI, true);
94
+ g.fill();
95
+ g.restore();
96
+ }
97
+ var cache = /* @__PURE__ */ new Map();
98
+ function cached(key, make) {
99
+ let c = cache.get(key);
100
+ if (!c) {
101
+ if (cache.size > 24) cache.delete(cache.keys().next().value);
102
+ cache.set(key, c = make());
103
+ }
104
+ return c;
105
+ }
106
+ function demoModel(canvas, size) {
107
+ const s = Math.max(32, Math.min(400, Math.round(size)));
108
+ return cached(`model-${s}`, () => {
109
+ const c = canvas.createCanvas(s, s);
110
+ const g = c.getContext("2d");
111
+ const sh = g.createRadialGradient(s / 2, s * 0.66, 0, s / 2, s * 0.66, s * 0.46);
112
+ sh.addColorStop(0, "rgba(0,0,0,0.35)");
113
+ sh.addColorStop(1, "rgba(0,0,0,0)");
114
+ g.fillStyle = sh;
115
+ g.fillRect(0, 0, s, s);
116
+ drawGear(g, s / 2, s * 0.44, s * 0.4, s * 0.16, 0.55);
117
+ return c;
118
+ });
119
+ }
120
+ function demoCamera(canvas, w, h, progress) {
121
+ const W = Math.max(64, Math.min(1280, Math.round(w)));
122
+ const H = Math.max(48, Math.min(960, Math.round(h)));
123
+ const p = Math.round(Math.max(0.05, Math.min(1, progress)) * 20) / 20;
124
+ return cached(`cam-${W}x${H}-${p}`, () => {
125
+ const c = canvas.createCanvas(W, H);
126
+ const g = c.getContext("2d");
127
+ const bg = g.createLinearGradient(0, 0, 0, H);
128
+ bg.addColorStop(0, "#2a2d33");
129
+ bg.addColorStop(0.55, "#16181c");
130
+ bg.addColorStop(1, "#0c0d10");
131
+ g.fillStyle = bg;
132
+ g.fillRect(0, 0, W, H);
133
+ const u = Math.min(W / 4, H / 3);
134
+ const cx = W / 2;
135
+ const bedY = H * 0.62;
136
+ const near = u * 2.3;
137
+ const far = u * 1.55;
138
+ const depth = u * 0.85;
139
+ g.beginPath();
140
+ g.moveTo(cx - far, bedY - depth);
141
+ g.lineTo(cx + far, bedY - depth);
142
+ g.lineTo(cx + near, bedY + depth * 0.9);
143
+ g.lineTo(cx - near, bedY + depth * 0.9);
144
+ g.closePath();
145
+ const plate = g.createLinearGradient(0, bedY - depth, 0, bedY + depth);
146
+ plate.addColorStop(0, "#5a4a2c");
147
+ plate.addColorStop(1, "#3b311e");
148
+ g.fillStyle = plate;
149
+ g.fill();
150
+ let seed = 7;
151
+ const rnd = () => (seed = seed * 16807 % 2147483647) / 2147483647;
152
+ g.fillStyle = "rgba(255,230,170,0.08)";
153
+ for (let i = 0; i < 260; i++) {
154
+ const t4 = rnd();
155
+ const y = bedY - depth + t4 * depth * 1.9;
156
+ const half = far + (near - far) * t4;
157
+ const x = cx - half + rnd() * half * 2;
158
+ g.fillRect(x, y, Math.max(1, u * 0.012), Math.max(1, u * 0.012));
159
+ }
160
+ const R = u * 0.78;
161
+ const full = u * 0.5;
162
+ const made = full * p;
163
+ g.save();
164
+ g.translate(0, -made);
165
+ drawGear(g, cx, bedY + u * 0.05, R, made, 0.42, 0.95);
166
+ g.restore();
167
+ const topY = bedY + u * 0.05 - made;
168
+ const hx = cx + R * 0.3;
169
+ const bw = u * 0.7;
170
+ const bh = u * 0.62;
171
+ const by = topY - u * 0.1 - bh;
172
+ const rail = g.createLinearGradient(0, by + bh * 0.18, 0, by + bh * 0.42);
173
+ rail.addColorStop(0, "#4a4e56");
174
+ rail.addColorStop(1, "#22252a");
175
+ g.fillStyle = rail;
176
+ g.fillRect(0, by + bh * 0.18, W, bh * 0.24);
177
+ const shroud = g.createLinearGradient(hx - bw / 2, 0, hx + bw / 2, 0);
178
+ shroud.addColorStop(0, "#2c2f35");
179
+ shroud.addColorStop(0.5, "#3a3e45");
180
+ shroud.addColorStop(1, "#1f2126");
181
+ g.fillStyle = shroud;
182
+ g.beginPath();
183
+ g.roundRect(hx - bw / 2, by, bw, bh, u * 0.08);
184
+ g.fill();
185
+ const fr = bw * 0.3;
186
+ const fy = by + bh * 0.48;
187
+ g.fillStyle = "#16181b";
188
+ g.beginPath();
189
+ g.arc(hx, fy, fr, 0, Math.PI * 2);
190
+ g.fill();
191
+ g.strokeStyle = "#3b3f46";
192
+ g.lineWidth = Math.max(1, fr * 0.12);
193
+ for (let i = 0; i < 7; i++) {
194
+ const a = i / 7 * Math.PI * 2;
195
+ g.beginPath();
196
+ g.moveTo(hx + Math.cos(a) * fr * 0.3, fy + Math.sin(a) * fr * 0.3);
197
+ g.lineTo(hx + Math.cos(a + 0.5) * fr * 0.9, fy + Math.sin(a + 0.5) * fr * 0.9);
198
+ g.stroke();
199
+ }
200
+ g.fillStyle = "#2a2d33";
201
+ g.beginPath();
202
+ g.arc(hx, fy, fr * 0.3, 0, Math.PI * 2);
203
+ g.fill();
204
+ g.fillStyle = "#c99a3c";
205
+ g.beginPath();
206
+ g.moveTo(hx - u * 0.07, by + bh);
207
+ g.lineTo(hx + u * 0.07, by + bh);
208
+ g.lineTo(hx, topY - u * 0.015);
209
+ g.closePath();
210
+ g.fill();
211
+ const vig = g.createRadialGradient(cx, H * 0.45, Math.min(W, H) * 0.2, cx, H * 0.5, Math.max(W, H) * 0.75);
212
+ vig.addColorStop(0, "rgba(0,0,0,0)");
213
+ vig.addColorStop(1, "rgba(0,0,0,0.55)");
214
+ g.fillStyle = vig;
215
+ g.fillRect(0, 0, W, H);
216
+ return c;
217
+ });
218
+ }
219
+
220
+ // src/draw.ts
221
+ var MIN_PX = 11;
222
+ var clamp = (v, lo, hi) => Math.max(lo, Math.min(hi, v));
223
+ var lineHeight = (ctx, size) => Math.round(/^zh/i.test(ctx.locale) ? Math.max(size * 1.45, 21) : size * 1.38);
224
+ function clipped(g, box, paint2) {
225
+ g.save();
226
+ g.beginPath();
227
+ g.rect(box.x, box.y, box.w, box.h);
228
+ g.clip();
229
+ try {
230
+ paint2();
231
+ } finally {
232
+ g.restore();
233
+ }
234
+ }
235
+ function fitText(ctx, g, text, maxW, font, min = MIN_PX) {
236
+ const w = ctx.kit.measureTracked(g, text, { ...font, size: 100 });
237
+ let size = w > 0 ? Math.min(font.size, Math.floor(100 * maxW / w)) : font.size;
238
+ while (size > min && ctx.kit.measureTracked(g, text, { ...font, size }) > maxW) size--;
239
+ return Math.max(min, size);
240
+ }
241
+ function phaseColor(ctx, phase) {
242
+ const c = ctx.theme.colors;
243
+ switch (phase) {
244
+ case "printing":
245
+ case "preparing":
246
+ return c.accent;
247
+ case "paused":
248
+ return c.warn;
249
+ case "finished":
250
+ return c.ok;
251
+ case "failed":
252
+ case "error":
253
+ return c.alert;
254
+ default:
255
+ return c.inkDim;
256
+ }
257
+ }
258
+ function percent(locale, p, done = false) {
259
+ const v = done ? 1 : Math.min(0.99, Math.floor(p * 100) / 100);
260
+ try {
261
+ return new Intl.NumberFormat(locale, { style: "percent", maximumFractionDigits: 0 }).format(v);
262
+ } catch {
263
+ return `${Math.round(v * 100)}%`;
264
+ }
265
+ }
266
+ var heating = (t4) => !!t4 && t4.target > 0 && t4.now < t4.target - 3;
267
+ function drawBar(g, ctx, box, p, color, shine2 = 0) {
268
+ const { kit, theme } = ctx;
269
+ const r = box.h / 2;
270
+ const round = (x, w2) => {
271
+ g.beginPath();
272
+ g.roundRect(x, box.y, Math.max(w2, Math.min(box.h, box.w)), box.h, r);
273
+ };
274
+ round(box.x, box.w);
275
+ g.fillStyle = theme.colors.surfaceEdge;
276
+ g.fill();
277
+ const w = Math.round(box.w * clamp(p, 0, 1));
278
+ if (w > 0) {
279
+ round(box.x, w);
280
+ g.fillStyle = color;
281
+ g.fill();
282
+ }
283
+ if (shine2 > 0 && w > 0) {
284
+ const cx = box.x + box.w * shine2;
285
+ const grad = g.createLinearGradient(cx - box.w * 0.18, 0, cx + box.w * 0.18, 0);
286
+ grad.addColorStop(0, kit.css(kit.hex("#ffffff"), 0));
287
+ grad.addColorStop(0.5, kit.css(kit.hex("#ffffff"), 0.55 * Math.sin(Math.PI * shine2)));
288
+ grad.addColorStop(1, kit.css(kit.hex("#ffffff"), 0));
289
+ g.save();
290
+ round(box.x, w);
291
+ g.clip();
292
+ g.fillStyle = grad;
293
+ g.fillRect(box.x, box.y, w, box.h);
294
+ g.restore();
295
+ }
296
+ }
297
+ function drawPicture(g, img, box, fit, radius = 0, bg) {
298
+ const iw = img.width;
299
+ const ih = img.height;
300
+ if (!iw || !ih || box.w <= 0 || box.h <= 0) return;
301
+ g.save();
302
+ g.beginPath();
303
+ if (radius > 0) g.roundRect(box.x, box.y, box.w, box.h, radius);
304
+ else g.rect(box.x, box.y, box.w, box.h);
305
+ g.clip();
306
+ if (bg) {
307
+ g.fillStyle = bg;
308
+ g.fillRect(box.x, box.y, box.w, box.h);
309
+ }
310
+ const s = fit === "cover" ? Math.max(box.w / iw, box.h / ih) : Math.min(box.w / iw, box.h / ih);
311
+ const w = iw * s;
312
+ const h = ih * s;
313
+ g.imageSmoothingEnabled = true;
314
+ g.imageSmoothingQuality = "high";
315
+ g.drawImage(img, box.x + (box.w - w) / 2, box.y + (box.h - h) / 2, w, h);
316
+ g.restore();
317
+ }
318
+ function drawMessage(g, ctx, text, o = {}) {
319
+ const box = o.box ?? ctx.box;
320
+ const { kit, theme } = ctx;
321
+ let size = clamp(Math.round(Math.min(box.h * 0.2, box.w / 12)), MIN_PX, 26);
322
+ let lines = [];
323
+ for (; ; size--) {
324
+ const n = Math.max(1, Math.min(4, Math.floor(box.h / lineHeight(ctx, size))));
325
+ lines = kit.wrapLines(g, text, box.w, n, { size, family: theme.fonts.sans });
326
+ if (size <= MIN_PX || !lines.at(-1)?.endsWith("\u2026")) break;
327
+ }
328
+ const lh = lineHeight(ctx, size);
329
+ const font = { size, family: theme.fonts.sans, color: o.color ?? theme.colors.inkDim };
330
+ let y = box.y + Math.max(0, (box.h - lines.length * lh) / 2) + size * 0.95;
331
+ for (const l of lines) {
332
+ kit.drawTracked(g, l, box.x, y, font);
333
+ y += lh;
334
+ }
335
+ }
336
+ function drawModelOutline(g, ctx, box) {
337
+ const c = ctx.theme.colors;
338
+ const s = Math.min(box.w, box.h) * 0.32;
339
+ const cx = box.x + box.w / 2;
340
+ const cy = box.y + box.h / 2 + s * 0.1;
341
+ const dx = s * 0.87;
342
+ const dy = s * 0.5;
343
+ const top = [
344
+ [cx, cy - s - dy],
345
+ [cx + dx, cy - s],
346
+ [cx, cy - s + dy],
347
+ [cx - dx, cy - s]
348
+ ];
349
+ g.save();
350
+ g.lineJoin = "round";
351
+ g.lineWidth = Math.max(1.5, s * 0.06);
352
+ g.strokeStyle = c.inkFaint;
353
+ g.beginPath();
354
+ g.moveTo(top[0][0], top[0][1]);
355
+ for (const [x, y] of top.slice(1)) g.lineTo(x, y);
356
+ g.closePath();
357
+ g.moveTo(cx - dx, cy - s);
358
+ g.lineTo(cx - dx, cy);
359
+ g.lineTo(cx, cy + dy);
360
+ g.lineTo(cx + dx, cy);
361
+ g.lineTo(cx + dx, cy - s);
362
+ g.moveTo(cx, cy - s + dy);
363
+ g.lineTo(cx, cy + dy);
364
+ g.stroke();
365
+ g.restore();
366
+ }
367
+
368
+ // src/labels.ts
369
+ var PHASE = {
370
+ idle: L("Free", "Libre", "Frei", "\u7A7A\u95F2", "\u9592\u7F6E"),
371
+ offline: L("Off", "Apagada", "Aus", "\u5DF2\u5173\u673A", "\u5DF2\u95DC\u6A5F"),
372
+ preparing: L("Preparing", "Preparando", "Bereitet vor", "\u51C6\u5907\u4E2D", "\u6E96\u5099\u4E2D"),
373
+ printing: L("Printing", "Imprimiendo", "Druckt", "\u6253\u5370\u4E2D", "\u5217\u5370\u4E2D"),
374
+ paused: L("Paused", "En pausa", "Pausiert", "\u5DF2\u6682\u505C", "\u5DF2\u66AB\u505C"),
375
+ finished: L("Finished", "Terminada", "Fertig", "\u5DF2\u5B8C\u6210", "\u5DF2\u5B8C\u6210"),
376
+ cancelled: L("Cancelled", "Cancelada", "Abgebrochen", "\u5DF2\u53D6\u6D88", "\u5DF2\u53D6\u6D88"),
377
+ failed: L("Failed", "Ha fallado", "Fehlgeschlagen", "\u6253\u5370\u5931\u8D25", "\u5217\u5370\u5931\u6557"),
378
+ error: L("Error", "Error", "Fehler", "\u9519\u8BEF", "\u932F\u8AA4")
379
+ };
380
+ var HEATING = L("Heating", "Calentando", "Heizt auf", "\u52A0\u70ED\u4E2D", "\u52A0\u71B1\u4E2D");
381
+ var NOZZLE = L("Nozzle", "Boquilla", "D\xFCse", "\u55B7\u5634", "\u5674\u5634");
382
+ var BED = L("Bed", "Cama", "Bett", "\u70ED\u5E8A", "\u71B1\u5E8A");
383
+ var LEFT = L("{d} left", "Quedan {d}", "Noch {d}", "\u5269\u4F59 {d}", "\u5269\u9918 {d}");
384
+ var DONE_AT = L("Done at {t}", "Termina a las {t}", "Fertig um {t}", "{t} \u5B8C\u6210", "{t} \u5B8C\u6210");
385
+ var TOOK = L("Took {d}", "Ha tardado {d}", "Dauer {d}", "\u7528\u65F6 {d}", "\u7528\u6642 {d}");
386
+ var LAYER = L("Layer {n}/{total}", "Capa {n}/{total}", "Schicht {n}/{total}", "\u7B2C {n}/{total} \u5C42", "\u7B2C {n}/{total} \u5C64");
387
+ var LAYERS = L("{total} layers", "{total} capas", "{total} Schichten", "\u5171 {total} \u5C42", "\u5171 {total} \u5C64");
388
+ var TAKE_OFF = L("Take the part off the bed", "Retira la pieza de la cama", "Teil vom Bett nehmen", "\u8BF7\u53D6\u4E0B\u6A21\u578B", "\u8ACB\u53D6\u4E0B\u6A21\u578B");
389
+ var FREE = L("The printer is free", "La impresora est\xE1 libre", "Der Drucker ist frei", "\u6253\u5370\u673A\u7A7A\u95F2", "\u5370\u8868\u6A5F\u9592\u7F6E");
390
+ var IS_OFF = L("{name} is off", "{name} est\xE1 apagada", "{name} ist aus", "{name} \u5DF2\u5173\u673A", "{name} \u5DF2\u95DC\u6A5F");
391
+ var SET_UP = L(
392
+ "Set the printer up in Settings \u2192 Data sources \u2192 3D printer",
393
+ "Configura la impresora en Ajustes \u2192 Fuentes de datos \u2192 Impresora 3D",
394
+ "Richte den Drucker unter Einstellungen \u2192 Datenquellen \u2192 3D-Drucker ein",
395
+ "\u8BF7\u5728\u201C\u8BBE\u7F6E \u2192 \u6570\u636E\u6E90 \u2192 3D \u6253\u5370\u673A\u201D\u4E2D\u8BBE\u7F6E\u6253\u5370\u673A",
396
+ "\u8ACB\u5728\u300C\u8A2D\u5B9A \u2192 \u8CC7\u6599\u4F86\u6E90 \u2192 3D \u5370\u8868\u6A5F\u300D\u4E2D\u8A2D\u5B9A\u5370\u8868\u6A5F"
397
+ );
398
+ var NO_CAMERA = L("No camera", "Sin c\xE1mara", "Keine Kamera", "\u6CA1\u6709\u6444\u50CF\u5934", "\u6C92\u6709\u651D\u5F71\u6A5F");
399
+ var NO_PICTURE = L("No picture from the camera", "La c\xE1mara no da imagen", "Kein Bild von der Kamera", "\u6444\u50CF\u5934\u6CA1\u6709\u753B\u9762", "\u651D\u5F71\u6A5F\u6C92\u6709\u756B\u9762");
400
+ function fill(t4, text, vars) {
401
+ return t4(text).replace(/\{(\w+)\}/g, (all, k) => k in vars ? String(vars[k]) : all);
402
+ }
403
+
404
+ // src/pictures.ts
405
+ import { readFile } from "node:fs/promises";
406
+
407
+ // src/camera-auth.ts
408
+ var auth = /* @__PURE__ */ new Map();
409
+ function rememberCamera(raw) {
410
+ if (!raw?.trim()) return void 0;
411
+ let s = raw.trim();
412
+ if (!/^[a-z][a-z0-9+.-]*:\/\//i.test(s)) s = `http://${s}`;
413
+ let u;
414
+ try {
415
+ u = new URL(s);
416
+ } catch {
417
+ return void 0;
418
+ }
419
+ if (u.protocol !== "http:" && u.protocol !== "https:") return void 0;
420
+ const user = decodeURIComponent(u.username);
421
+ const password = decodeURIComponent(u.password);
422
+ u.username = "";
423
+ u.password = "";
424
+ const clean = u.href;
425
+ if (user) auth.set(clean, `Basic ${Buffer.from(`${user}:${password}`).toString("base64")}`);
426
+ else auth.delete(clean);
427
+ return clean;
428
+ }
429
+ var authFor = (url) => auth.get(url);
430
+
431
+ // src/version.ts
432
+ var VERSION = "0.1.0";
433
+ var AGENT = `kiosko-plugin-3d-printer/${VERSION} Kiosko (+https://kioskolcd.dev)`;
434
+
435
+ // src/http.ts
436
+ var PrinterError = class extends Error {
437
+ problem;
438
+ status;
439
+ constructor(problem, message, status) {
440
+ super(message);
441
+ this.name = "PrinterError";
442
+ this.problem = problem;
443
+ if (status !== void 0) this.status = status;
444
+ }
445
+ };
446
+ function connOf(url, headers = {}) {
447
+ let raw = url.trim();
448
+ if (!raw) return void 0;
449
+ if (!/^[a-z][a-z0-9+.-]*:\/\//i.test(raw)) raw = `http://${raw}`;
450
+ let u;
451
+ try {
452
+ u = new URL(raw);
453
+ } catch {
454
+ return void 0;
455
+ }
456
+ if (u.protocol !== "http:" && u.protocol !== "https:") return void 0;
457
+ const out = { ...headers };
458
+ if (u.username) out.Authorization = `Basic ${Buffer.from(`${decodeURIComponent(u.username)}:${decodeURIComponent(u.password)}`).toString("base64")}`;
459
+ u.username = "";
460
+ u.password = "";
461
+ const path = u.pathname.replace(/\/+$/, "").replace(/\/(api|server|printer)(\/.*)?$/i, "");
462
+ return { base: `${u.origin}${path}`, headers: out };
463
+ }
464
+ function hostOf(c) {
465
+ try {
466
+ return new URL(typeof c === "string" ? c : c.base).host;
467
+ } catch {
468
+ return typeof c === "string" ? c : c.base;
469
+ }
470
+ }
471
+ function urlOf(conn, path) {
472
+ if (/^https?:\/\//i.test(path)) return path;
473
+ return `${conn.base}${path.startsWith("/") ? "" : "/"}${path}`;
474
+ }
475
+ function failureOf(err, where) {
476
+ if (err instanceof PrinterError) return err;
477
+ const e = err;
478
+ if (e?.name === "AbortError" || e?.name === "TimeoutError") return new PrinterError("timeout", `${where} did not answer in time`);
479
+ const code = e?.cause?.code ?? "";
480
+ if (/ECONNREFUSED|ENOTFOUND|EHOSTUNREACH|ENETUNREACH|EAI_AGAIN|ECONNRESET|ETIMEDOUT|UND_ERR/.test(code) || e?.message === "fetch failed") {
481
+ return new PrinterError("unreachable", `${where} can't be reached${code ? ` (${code})` : ""}`);
482
+ }
483
+ return new PrinterError("unreachable", `${where}: ${e?.message ?? String(err)}`);
484
+ }
485
+ async function getBytes(conn, path, o = {}, fetcher = fetch) {
486
+ const url = urlOf(conn, path);
487
+ const where = hostOf(url);
488
+ let res;
489
+ try {
490
+ res = await fetcher(url, { method: o.method ?? "GET", headers: { "User-Agent": AGENT, ...conn.headers, ...o.headers }, ...o.signal ? { signal: o.signal } : {} });
491
+ } catch (err) {
492
+ throw failureOf(err, where);
493
+ }
494
+ if (!res.ok) {
495
+ await res.body?.cancel().catch(() => void 0);
496
+ if (res.status === 401 || res.status === 403) throw new PrinterError("auth", `${where} refused the key (HTTP ${res.status})`, res.status);
497
+ if (res.status === 404) throw new PrinterError("notfound", `${where} has no ${new URL(url).pathname} (HTTP 404)`, res.status);
498
+ if (res.status === 409 || res.status === 503) throw new PrinterError("busy", `${where} answered HTTP ${res.status}`, res.status);
499
+ throw new PrinterError("status", `${where} answered HTTP ${res.status}`, res.status);
500
+ }
501
+ const max = o.maxBytes ?? 2 * 1024 * 1024;
502
+ const declared = Number(res.headers.get("content-length") ?? NaN);
503
+ if (declared > max) {
504
+ await res.body?.cancel().catch(() => void 0);
505
+ throw new PrinterError("answer", `${where} sent ${declared} bytes, more than the ${max} expected`);
506
+ }
507
+ let body;
508
+ try {
509
+ body = Buffer.from(await res.arrayBuffer());
510
+ } catch (err) {
511
+ throw failureOf(err, where);
512
+ }
513
+ if (body.length > max) throw new PrinterError("answer", `${where} sent more than the ${max} bytes expected`);
514
+ return { body, type: res.headers.get("content-type") ?? "" };
515
+ }
516
+ async function getJson(conn, path, o = {}, fetcher = fetch) {
517
+ const { body } = await getBytes(conn, path, { maxBytes: 512 * 1024, ...o }, fetcher);
518
+ try {
519
+ return JSON.parse(body.toString("utf8"));
520
+ } catch {
521
+ throw new PrinterError("answer", `${hostOf(urlOf(conn, path))} did not answer JSON at ${path.split("?")[0]}`);
522
+ }
523
+ }
524
+ var num = (v) => typeof v === "number" && Number.isFinite(v) ? v : typeof v === "string" && v.trim() !== "" && Number.isFinite(Number(v)) ? Number(v) : void 0;
525
+ function jobName(path) {
526
+ const base = path.split(/[\\/]/).pop() ?? path;
527
+ return base.replace(/\.(gcode\.3mf|3mf|gcode|gco|g|bgcode)$/i, "") || base;
528
+ }
529
+
530
+ // src/pictures.ts
531
+ var thumbs = /* @__PURE__ */ new Map();
532
+ function loadThumb(canvas, thumb) {
533
+ let p = thumbs.get(thumb.key);
534
+ if (!p) {
535
+ p = readFile(thumb.file).then((b) => canvas.loadImage(b));
536
+ p.catch(() => thumbs.delete(thumb.key));
537
+ if (thumbs.size > 8) thumbs.delete(thumbs.keys().next().value);
538
+ thumbs.set(thumb.key, p);
539
+ }
540
+ return p;
541
+ }
542
+ var MAX_SNAPSHOT = 8 * 1024 * 1024;
543
+ async function loadSnapshot(canvas, url, o = {}) {
544
+ const where = hostOf(url);
545
+ const auth2 = authFor(url);
546
+ let res;
547
+ try {
548
+ res = await (o.fetch ?? fetch)(url, { headers: { "User-Agent": AGENT, Accept: "image/jpeg,image/*", ...auth2 ? { Authorization: auth2 } : {} }, ...o.signal ? { signal: o.signal } : {} });
549
+ } catch (err) {
550
+ const e = err;
551
+ if (e?.name === "AbortError" || e?.name === "TimeoutError") throw new PrinterError("timeout", `the camera at ${where} did not answer in time`);
552
+ throw new PrinterError("unreachable", `the camera at ${where} can't be reached${e?.cause?.code ? ` (${e.cause.code})` : ""}`);
553
+ }
554
+ if (!res.ok) {
555
+ await res.body?.cancel().catch(() => void 0);
556
+ throw new PrinterError(res.status === 401 || res.status === 403 ? "auth" : "status", `the camera at ${where} answered HTTP ${res.status}`, res.status);
557
+ }
558
+ const type = res.headers.get("content-type") ?? "";
559
+ if (/multipart\/x-mixed-replace/i.test(type)) {
560
+ await res.body?.cancel().catch(() => void 0);
561
+ throw new PrinterError("answer", `${where} sends a video stream, not a picture: use the snapshot address (?action=snapshot)`);
562
+ }
563
+ const body = Buffer.from(await res.arrayBuffer());
564
+ if (body.length > MAX_SNAPSHOT) throw new PrinterError("answer", `the camera at ${where} sent ${body.length} bytes`);
565
+ if (o.size && canvas.loadImageScaled) return canvas.loadImageScaled(body, { ...o.size, fit: "cover" });
566
+ return canvas.loadImage(body);
567
+ }
568
+
569
+ // src/source.ts
570
+ import { createHash } from "node:crypto";
571
+ import { mkdir, rm, writeFile } from "node:fs/promises";
572
+ import { join } from "node:path";
573
+ import { defineSource, t } from "@kiosko/sdk";
574
+
575
+ // src/backends/bambu.ts
576
+ import { connect as tlsConnect } from "node:tls";
577
+
578
+ // src/backends/mqtt.ts
579
+ import { EventEmitter } from "node:events";
580
+ var MqttType = { CONNECT: 1, CONNACK: 2, PUBLISH: 3, SUBSCRIBE: 8, SUBACK: 9, PINGREQ: 12, PINGRESP: 13, DISCONNECT: 14 };
581
+ var Type = MqttType;
582
+ function encodeLength(n) {
583
+ const out = [];
584
+ do {
585
+ let byte = n % 128;
586
+ n = Math.floor(n / 128);
587
+ if (n > 0) byte |= 128;
588
+ out.push(byte);
589
+ } while (n > 0);
590
+ return Buffer.from(out);
591
+ }
592
+ var str = (s) => {
593
+ const b = Buffer.from(s, "utf8");
594
+ const len = Buffer.alloc(2);
595
+ len.writeUInt16BE(b.length);
596
+ return Buffer.concat([len, b]);
597
+ };
598
+ var packet = (first, body) => Buffer.concat([Buffer.from([first]), encodeLength(body.length), body]);
599
+ function connectPacket(o) {
600
+ let flags = 2;
601
+ if (o.username !== void 0) flags |= 128;
602
+ if (o.password !== void 0) flags |= 64;
603
+ const keep = Buffer.alloc(2);
604
+ keep.writeUInt16BE(o.keepAliveS);
605
+ const body = Buffer.concat([str("MQTT"), Buffer.from([4, flags]), keep, str(o.clientId), ...o.username !== void 0 ? [str(o.username)] : [], ...o.password !== void 0 ? [str(o.password)] : []]);
606
+ return packet(Type.CONNECT << 4, body);
607
+ }
608
+ function subscribePacket(id, topic) {
609
+ const pid = Buffer.alloc(2);
610
+ pid.writeUInt16BE(id);
611
+ return packet(Type.SUBSCRIBE << 4 | 2, Buffer.concat([pid, str(topic), Buffer.from([0])]));
612
+ }
613
+ function publishPacket(topic, payload) {
614
+ return packet(Type.PUBLISH << 4, Buffer.concat([str(topic), typeof payload === "string" ? Buffer.from(payload, "utf8") : payload]));
615
+ }
616
+ var pingPacket = () => Buffer.from([Type.PINGREQ << 4, 0]);
617
+ var disconnectPacket = () => Buffer.from([Type.DISCONNECT << 4, 0]);
618
+ var PacketReader = class {
619
+ buf = Buffer.alloc(0);
620
+ max;
621
+ /** `max`: largest packet accepted. A printer's report is tens of kilobytes; anything near this is not one. */
622
+ constructor(max = 4 * 1024 * 1024) {
623
+ this.max = max;
624
+ }
625
+ push(chunk) {
626
+ this.buf = this.buf.length ? Buffer.concat([this.buf, chunk]) : chunk;
627
+ const out = [];
628
+ for (; ; ) {
629
+ if (this.buf.length < 2) break;
630
+ let len = 0;
631
+ let mul = 1;
632
+ let i = 1;
633
+ let complete = false;
634
+ for (; i < Math.min(this.buf.length, 5); i++) {
635
+ const byte = this.buf[i];
636
+ len += (byte & 127) * mul;
637
+ mul *= 128;
638
+ if (!(byte & 128)) {
639
+ complete = true;
640
+ break;
641
+ }
642
+ }
643
+ if (!complete) {
644
+ if (this.buf.length >= 5) throw new Error("MQTT: malformed length");
645
+ break;
646
+ }
647
+ if (len > this.max) throw new Error(`MQTT: a packet of ${len} bytes`);
648
+ const start = i + 1;
649
+ if (this.buf.length < start + len) break;
650
+ const first = this.buf[0];
651
+ out.push({ type: first >> 4, flags: first & 15, body: this.buf.subarray(start, start + len) });
652
+ this.buf = this.buf.subarray(start + len);
653
+ }
654
+ return out;
655
+ }
656
+ };
657
+ function readPublish(p) {
658
+ const n = p.body.readUInt16BE(0);
659
+ const topic = p.body.subarray(2, 2 + n).toString("utf8");
660
+ const qos = p.flags >> 1 & 3;
661
+ return { topic, payload: p.body.subarray(2 + n + (qos > 0 ? 2 : 0)) };
662
+ }
663
+ var MqttClient = class extends EventEmitter {
664
+ reader = new PacketReader();
665
+ ping;
666
+ closed = false;
667
+ nextId = 1;
668
+ stream;
669
+ constructor(stream) {
670
+ super();
671
+ this.stream = stream;
672
+ stream.on("data", (chunk) => {
673
+ try {
674
+ for (const p of this.reader.push(chunk)) this.handle(p);
675
+ } catch (err) {
676
+ this.close(err);
677
+ }
678
+ });
679
+ stream.on("error", (err) => this.close(err));
680
+ stream.on("close", () => this.close());
681
+ }
682
+ acked;
683
+ connect(o) {
684
+ const keepAliveS = o.keepAliveS ?? 60;
685
+ return new Promise((ok, fail) => {
686
+ const timer = setTimeout(() => fail(new Error("MQTT: no answer to connect")), o.timeoutMs ?? 1e4);
687
+ timer.unref?.();
688
+ this.acked = {
689
+ ok: () => {
690
+ clearTimeout(timer);
691
+ this.ping = setInterval(() => this.write(pingPacket()), keepAliveS * 1e3 / 2);
692
+ this.ping.unref?.();
693
+ ok();
694
+ },
695
+ fail: (e) => {
696
+ clearTimeout(timer);
697
+ fail(e);
698
+ }
699
+ };
700
+ this.once("close", (e) => this.acked?.fail(e ?? new Error("MQTT: connection closed")));
701
+ this.write(connectPacket({ clientId: o.clientId, keepAliveS, ...o.username !== void 0 ? { username: o.username } : {}, ...o.password !== void 0 ? { password: o.password } : {} }));
702
+ });
703
+ }
704
+ subscribe(topic) {
705
+ this.write(subscribePacket(this.nextId++, topic));
706
+ }
707
+ publish(topic, payload) {
708
+ this.write(publishPacket(topic, payload));
709
+ }
710
+ end() {
711
+ if (this.closed) return;
712
+ this.write(disconnectPacket());
713
+ this.stream.end();
714
+ this.close();
715
+ }
716
+ get isClosed() {
717
+ return this.closed;
718
+ }
719
+ write(b) {
720
+ if (!this.closed) this.stream.write(b);
721
+ }
722
+ handle(p) {
723
+ switch (p.type) {
724
+ case Type.CONNACK: {
725
+ const code = p.body[1] ?? 0;
726
+ const why = ["", "unacceptable protocol", "client id refused", "server unavailable", "bad user name or password", "not authorised"][code] ?? `code ${code}`;
727
+ if (code === 0) this.acked?.ok();
728
+ else {
729
+ this.acked?.fail(Object.assign(new Error(`MQTT: ${why}`), { refused: code === 4 || code === 5 }));
730
+ this.close();
731
+ }
732
+ this.acked = void 0;
733
+ break;
734
+ }
735
+ case Type.PUBLISH: {
736
+ const { topic, payload } = readPublish(p);
737
+ this.emit("message", topic, payload);
738
+ break;
739
+ }
740
+ default:
741
+ break;
742
+ }
743
+ }
744
+ close(err) {
745
+ if (this.closed) return;
746
+ this.closed = true;
747
+ if (this.ping) clearInterval(this.ping);
748
+ this.stream.destroy();
749
+ this.emit("close", err);
750
+ }
751
+ };
752
+
753
+ // src/backends/reading.ts
754
+ function tempOf(now, target2) {
755
+ const n = typeof now === "number" && Number.isFinite(now) ? now : void 0;
756
+ if (n === void 0) return void 0;
757
+ const t4 = typeof target2 === "number" && Number.isFinite(target2) ? target2 : 0;
758
+ return { now: Math.round(n * 10) / 10, target: Math.round(t4 * 10) / 10 };
759
+ }
760
+ function cameraUrl(printerBase, raw) {
761
+ if (typeof raw !== "string" || !raw.trim()) return void 0;
762
+ const origin = new URL(printerBase).origin;
763
+ let u;
764
+ try {
765
+ u = new URL(raw.trim(), `${origin}/`);
766
+ } catch {
767
+ return void 0;
768
+ }
769
+ if (u.protocol !== "http:" && u.protocol !== "https:") return void 0;
770
+ if (/^(localhost|127\.0\.0\.1|\[::1\]|0\.0\.0\.0)$/i.test(u.hostname)) {
771
+ const path = u.pathname.startsWith("/webcam") ? u.pathname : `/webcam${u.pathname}`;
772
+ return `${origin}${path}${u.search}`;
773
+ }
774
+ return u.href;
775
+ }
776
+
777
+ // src/backends/bambu.ts
778
+ var CANCELLED = 50348044;
779
+ function statusOf(p) {
780
+ switch ((p.gcode_state ?? "").toUpperCase()) {
781
+ case "PREPARE":
782
+ case "SLICING":
783
+ case "INIT":
784
+ return "preparing";
785
+ case "RUNNING":
786
+ return (num(p.layer_num) ?? 0) === 0 && (num(p.mc_percent) ?? 0) === 0 ? "preparing" : "printing";
787
+ case "PAUSE":
788
+ return "paused";
789
+ case "FINISH":
790
+ return "finished";
791
+ case "FAILED":
792
+ return num(p.print_error) === CANCELLED ? "cancelled" : "failed";
793
+ case "IDLE":
794
+ return "idle";
795
+ default:
796
+ return "idle";
797
+ }
798
+ }
799
+ var errorCode = (n) => {
800
+ const h = (n >>> 0).toString(16).toUpperCase().padStart(8, "0");
801
+ return `${h.slice(0, 4)}-${h.slice(4)}`;
802
+ };
803
+ function readingOf(p, now) {
804
+ const status = statusOf(p);
805
+ const nozzle = tempOf(p.nozzle_temper, p.nozzle_target_temper);
806
+ const bed = tempOf(p.bed_temper, p.bed_target_temper);
807
+ const chamber = tempOf(p.chamber_temper, 0);
808
+ const r = { status, ...nozzle ? { nozzle } : {}, ...bed ? { bed } : {}, ...chamber && chamber.now > 0 ? { chamber } : {} };
809
+ const err = num(p.print_error) ?? 0;
810
+ if ((status === "failed" || status === "paused") && err && err !== CANCELLED) r.message = `HMS ${errorCode(err)}`;
811
+ const file = typeof p.subtask_name === "string" && p.subtask_name || typeof p.gcode_file === "string" && p.gcode_file || "";
812
+ if (file && status !== "idle") {
813
+ const pct = num(p.mc_percent);
814
+ const left = num(p.mc_remaining_time);
815
+ const layers = num(p.total_layer_num);
816
+ const layer = num(p.layer_num);
817
+ const started = num(p.gcode_start_time);
818
+ r.job = {
819
+ file,
820
+ ...pct !== void 0 ? { progress: status === "finished" ? 1 : Math.max(0, Math.min(1, pct / 100)) } : {},
821
+ ...left !== void 0 ? { leftMs: status === "finished" ? 0 : left * 6e4 } : {},
822
+ ...layers ? { layers } : {},
823
+ ...layers && layer !== void 0 ? { layer: Math.min(layer, layers) } : {},
824
+ ...started && started > 1e9 ? { startedAt: started * 1e3, elapsedMs: Math.max(0, now - started * 1e3) } : {}
825
+ };
826
+ }
827
+ return r;
828
+ }
829
+ function merge(into, change) {
830
+ for (const [k, v] of Object.entries(change)) {
831
+ const old = into[k];
832
+ if (v && typeof v === "object" && !Array.isArray(v) && old && typeof old === "object" && !Array.isArray(old)) merge(old, v);
833
+ else into[k] = v;
834
+ }
835
+ return into;
836
+ }
837
+ var openTls = ({ host, port }) => tlsConnect({ host, port, rejectUnauthorized: false, .../^[\d.]+$|:/.test(host) ? {} : { servername: host } });
838
+ var sessions = /* @__PURE__ */ new Map();
839
+ var LINGER_MS = 2 * 6e4;
840
+ function open(key, o) {
841
+ const stream = o.open({ host: o.host, port: o.port });
842
+ const client = new MqttClient(stream);
843
+ const s = { client, state: {}, full: false, lastReadAt: o.now, ready: Promise.resolve() };
844
+ let gotFull = () => void 0;
845
+ const full = new Promise((ok) => gotFull = ok);
846
+ client.on("message", (_topic, payload) => {
847
+ let msg;
848
+ try {
849
+ msg = JSON.parse(payload.toString("utf8"));
850
+ } catch {
851
+ return;
852
+ }
853
+ if (!msg.print || typeof msg.print !== "object") return;
854
+ merge(s.state, msg.print);
855
+ if (msg.print.command === "push_status" && "gcode_state" in msg.print) {
856
+ s.full = true;
857
+ gotFull();
858
+ }
859
+ });
860
+ client.on("close", (err) => {
861
+ s.error = err ?? new Error("closed");
862
+ if (sessions.get(key) === s) sessions.delete(key);
863
+ });
864
+ s.ready = client.connect({ clientId: `kiosko-${Math.random().toString(36).slice(2, 10)}`, username: "bblp", password: o.accessCode, keepAliveS: 60 }).then(() => {
865
+ client.subscribe(`device/${o.serial}/report`);
866
+ client.publish(`device/${o.serial}/request`, JSON.stringify({ pushing: { sequence_id: "0", command: "pushall", version: 1, push_target: 1 } }));
867
+ return full;
868
+ });
869
+ s.timer = setInterval(() => {
870
+ if (Date.now() - s.lastReadAt > LINGER_MS) {
871
+ clearInterval(s.timer);
872
+ client.end();
873
+ }
874
+ }, 3e4);
875
+ s.timer.unref?.();
876
+ return s;
877
+ }
878
+ async function readBambu(o) {
879
+ const port = o.port ?? 8883;
880
+ const key = `${o.host}:${port}|${o.serial}|${o.accessCode}`;
881
+ let s = sessions.get(key);
882
+ if (!s || s.client.isClosed) {
883
+ s = open(key, { host: o.host, port, serial: o.serial, accessCode: o.accessCode, open: o.open ?? openTls, now: o.now });
884
+ sessions.set(key, s);
885
+ }
886
+ s.lastReadAt = Date.now();
887
+ if (!s.full) {
888
+ const wait = o.waitMs ?? 8e3;
889
+ let timer;
890
+ try {
891
+ await Promise.race([
892
+ s.ready,
893
+ new Promise((_, fail) => {
894
+ timer = setTimeout(() => fail(new PrinterError("timeout", `${o.host} sent no report in ${Math.round(wait / 1e3)} s (is the serial number right?)`)), wait);
895
+ }),
896
+ ...o.signal ? [new Promise((_, fail) => o.signal.addEventListener("abort", () => fail(new PrinterError("timeout", `${o.host} did not answer in time`)), { once: true }))] : []
897
+ ]);
898
+ } catch (err) {
899
+ sessions.delete(key);
900
+ s.client.end();
901
+ if (err instanceof PrinterError) throw err;
902
+ const e = err;
903
+ if (e.refused) throw new PrinterError("auth", `${o.host} refused the access code (is LAN mode on, and Developer mode on recent firmware?)`);
904
+ if (/ECONNREFUSED|ENOTFOUND|EHOSTUNREACH|ETIMEDOUT|ENETUNREACH/.test(e.code ?? "")) throw new PrinterError("unreachable", `${o.host} can't be reached on port ${port} (${e.code})`);
905
+ throw new PrinterError("unreachable", `${o.host}: ${e.message}`);
906
+ } finally {
907
+ if (timer) clearTimeout(timer);
908
+ }
909
+ }
910
+ if (s.client.isClosed && s.error) {
911
+ sessions.delete(key);
912
+ throw new PrinterError("unreachable", `${o.host} closed the connection: ${s.error.message}`);
913
+ }
914
+ return readingOf(s.state, o.now);
915
+ }
916
+
917
+ // src/backends/moonraker.ts
918
+ var QUERY = "/printer/objects/query?print_stats&virtual_sdcard&display_status&extruder&heater_bed&webhooks";
919
+ var kept = /* @__PURE__ */ new Map();
920
+ var keptFor = (conn) => {
921
+ let k = kept.get(conn.base);
922
+ if (!k) kept.set(conn.base, k = { infoAt: -Infinity, meta: /* @__PURE__ */ new Map(), ended: /* @__PURE__ */ new Map() });
923
+ return k;
924
+ };
925
+ var filePath = (file) => file.split("/").map(encodeURIComponent).join("/");
926
+ function thumbOf(file, meta) {
927
+ const thumbs2 = (meta?.thumbnails ?? []).filter((t4) => typeof (t4.relative_path ?? t4.thumbnail_path) === "string");
928
+ if (!thumbs2.length) return void 0;
929
+ const width = (t4) => num(t4.width) ?? 0;
930
+ const fit = thumbs2.filter((t4) => width(t4) <= 400).sort((a, b) => width(b) - width(a))[0] ?? thumbs2.sort((a, b) => width(a) - width(b))[0];
931
+ const rel = fit.relative_path ?? fit.thumbnail_path;
932
+ const dir = file.includes("/") ? file.slice(0, file.lastIndexOf("/") + 1) : "";
933
+ return `/server/files/gcodes/${filePath(`${dir}${rel}`)}`;
934
+ }
935
+ var cleanMessage = (m) => m.replace(/^Error evaluating '[^']*':\s*/, "").replace(/^[\w.]*(Command)?Error:\s*/, "").split("\n")[0].trim();
936
+ function statusOf2(o) {
937
+ const klippy = o.webhooks?.state;
938
+ if (klippy === "shutdown" || klippy === "error") return "error";
939
+ const s = o.print_stats?.state;
940
+ switch (s) {
941
+ case "printing": {
942
+ const laid = (num(o.print_stats?.filament_used) ?? 0) > 0 || (num(o.print_stats?.print_duration) ?? 0) > 0;
943
+ const going = (num(o.print_stats?.info?.current_layer) ?? 0) >= 1 || (progressOf(o) ?? 0) >= 0.02;
944
+ return laid || going ? "printing" : "preparing";
945
+ }
946
+ case "paused":
947
+ return "paused";
948
+ case "complete":
949
+ return "finished";
950
+ case "cancelled":
951
+ return "cancelled";
952
+ case "error":
953
+ return "failed";
954
+ default:
955
+ return "idle";
956
+ }
957
+ }
958
+ function progressOf(o) {
959
+ const m73 = num(o.display_status?.progress);
960
+ const file = num(o.virtual_sdcard?.progress);
961
+ const p = m73 !== void 0 && m73 > 0 ? m73 : file;
962
+ return p === void 0 ? void 0 : Math.max(0, Math.min(1, p));
963
+ }
964
+ function printedOf(o) {
965
+ const printed = num(o.print_stats?.print_duration);
966
+ return printed !== void 0 && printed > 0 ? printed : num(o.print_stats?.total_duration) ?? printed;
967
+ }
968
+ function leftOf(o, meta, progress) {
969
+ const printed = printedOf(o) ?? 0;
970
+ const est = num(meta?.estimated_time);
971
+ if (est !== void 0 && est > 0) return Math.max(0, est - printed) * 1e3;
972
+ if (progress !== void 0 && progress > 0.02 && printed > 0) return Math.max(0, printed / progress - printed) * 1e3;
973
+ return void 0;
974
+ }
975
+ async function readMoonraker({ conn, signal, fetch: f, now }) {
976
+ const k = keptFor(conn);
977
+ const get = (path) => getJson(conn, path, { signal }, f).then((r) => r.result);
978
+ let objects;
979
+ try {
980
+ objects = (await get(QUERY)).status ?? {};
981
+ } catch (err) {
982
+ if (err instanceof PrinterError && (err.problem === "busy" || err.status === 500)) {
983
+ const info = await get("/server/info").catch(() => void 0);
984
+ if (info) return { status: info.klippy_state === "startup" ? "offline" : "error", message: info.klippy_state === "startup" ? "Klipper is starting" : `Klipper is ${info.klippy_state ?? "not connected"}` };
985
+ }
986
+ throw err;
987
+ }
988
+ if (now - k.infoAt > 10 * 6e4) {
989
+ k.infoAt = now;
990
+ const [info, cams] = await Promise.all([
991
+ get("/printer/info").catch(() => void 0),
992
+ get("/server/webcams/list").catch(() => void 0)
993
+ ]);
994
+ if (info?.hostname) k.name = info.hostname;
995
+ const cam = cams?.webcams?.find((c) => c.enabled !== false && c.snapshot_url);
996
+ k.camera = cam ? cameraUrl(conn.base, cam.snapshot_url) : void 0;
997
+ }
998
+ const status = statusOf2(objects);
999
+ const ps = objects.print_stats ?? {};
1000
+ const file = typeof ps.filename === "string" ? ps.filename : "";
1001
+ const reading = {
1002
+ status,
1003
+ ...k.name ? { name: k.name } : {},
1004
+ ...k.camera ? { camera: k.camera } : {},
1005
+ ...withTemps(objects)
1006
+ };
1007
+ if (status === "error") {
1008
+ const why = objects.webhooks?.state_message?.split("\n")[0]?.trim();
1009
+ if (why) reading.message = why;
1010
+ } else if (status === "failed" && ps.message) reading.message = cleanMessage(ps.message);
1011
+ if (file && status !== "idle" && status !== "error") {
1012
+ if (!k.meta.has(file)) {
1013
+ k.meta.set(file, await get(`/server/files/metadata?filename=${encodeURIComponent(file)}`).catch(() => null));
1014
+ if (k.meta.size > 20) k.meta.delete(k.meta.keys().next().value);
1015
+ }
1016
+ const meta = k.meta.get(file);
1017
+ const progress = status === "finished" ? 1 : progressOf(objects);
1018
+ const printed = printedOf(objects);
1019
+ const layers = num(ps.info?.total_layer) ?? num(meta?.layer_count);
1020
+ const layer = num(ps.info?.current_layer);
1021
+ const left = status === "finished" ? 0 : leftOf(objects, meta, progress);
1022
+ const started = num(meta?.print_start_time);
1023
+ reading.job = {
1024
+ file,
1025
+ ...progress !== void 0 ? { progress } : {},
1026
+ ...printed !== void 0 ? { elapsedMs: printed * 1e3 } : {},
1027
+ ...left !== void 0 ? { leftMs: left } : {},
1028
+ ...layers ? { layers } : {},
1029
+ ...layers && layer !== void 0 ? { layer: Math.min(layer, layers) } : {},
1030
+ ...started ? { startedAt: started * 1e3 } : num(ps.total_duration) !== void 0 ? { startedAt: now - num(ps.total_duration) * 1e3 } : {}
1031
+ };
1032
+ const thumb = thumbOf(file, meta);
1033
+ if (thumb) reading.thumb = thumb;
1034
+ if (status === "finished" || status === "cancelled" || status === "failed") {
1035
+ if (!k.ended.has(file)) {
1036
+ const last = await get("/server/history/list?limit=1&order=desc").catch(() => void 0);
1037
+ const job2 = last?.jobs?.[0];
1038
+ k.ended.set(file, job2?.filename === file && num(job2.end_time) ? num(job2.end_time) * 1e3 : null);
1039
+ }
1040
+ const ended = k.ended.get(file);
1041
+ if (ended) reading.job.endedAt = ended;
1042
+ } else k.ended.delete(file);
1043
+ }
1044
+ return reading;
1045
+ }
1046
+ function withTemps(o) {
1047
+ const nozzle = tempOf(o.extruder?.temperature, o.extruder?.target);
1048
+ const bed = tempOf(o.heater_bed?.temperature, o.heater_bed?.target);
1049
+ return { ...nozzle ? { nozzle } : {}, ...bed ? { bed } : {} };
1050
+ }
1051
+
1052
+ // src/backends/octoprint.ts
1053
+ function thumbOf2(entry) {
1054
+ const refs = entry?.refs ?? {};
1055
+ const sized = Object.entries(refs).map(([k, v]) => ({ w: Number(/^thumbnail_(\d+)x\d+$/.exec(k)?.[1] ?? NaN), v })).filter((t4) => Number.isFinite(t4.w) && typeof t4.v === "string");
1056
+ const fit = sized.filter((t4) => t4.w <= 400).sort((a, b) => b.w - a.w)[0] ?? sized.sort((a, b) => a.w - b.w)[0];
1057
+ const url = fit?.v ?? refs.thumbnail ?? entry?.thumbnail;
1058
+ return typeof url === "string" && url ? url : null;
1059
+ }
1060
+ var kept2 = /* @__PURE__ */ new Map();
1061
+ var keptFor2 = (conn) => {
1062
+ let k = kept2.get(conn.base);
1063
+ if (!k) kept2.set(conn.base, k = { infoAt: -Infinity, thumbs: /* @__PURE__ */ new Map() });
1064
+ return k;
1065
+ };
1066
+ function statusOf3(job2, printer) {
1067
+ const f = printer?.state?.flags;
1068
+ if (!printer || !f) {
1069
+ const s = (job2.state ?? "").toLowerCase();
1070
+ if (s.startsWith("offline") || s === "closed") return s.includes("error") ? "error" : "offline";
1071
+ if (s.startsWith("error")) return "error";
1072
+ return "offline";
1073
+ }
1074
+ if (f.error) return "error";
1075
+ if (f.closedOrError) return "offline";
1076
+ if (f.paused || f.pausing) return "paused";
1077
+ if (f.cancelling) return "printing";
1078
+ if (f.printing || f.finishing) {
1079
+ const completion = num(job2.progress?.completion) ?? 0;
1080
+ const below = (h) => (num(h?.target) ?? 0) > 0 && (num(h?.actual) ?? 0) < (num(h?.target) ?? 0) - 5;
1081
+ return completion < 5 && (below(printer.temperature?.tool0) || below(printer.temperature?.bed)) ? "preparing" : "printing";
1082
+ }
1083
+ return "idle";
1084
+ }
1085
+ async function readOctoPrint({ conn, signal, fetch: f, now }) {
1086
+ const k = keptFor2(conn);
1087
+ const get = (path2) => getJson(conn, path2, { signal }, f);
1088
+ const [job2, printer] = await Promise.all([
1089
+ get("/api/job"),
1090
+ // 409: no printer connected to OctoPrint (it's off, or its cable out).
1091
+ get("/api/printer?exclude=sd").catch((err) => {
1092
+ if (err instanceof PrinterError && err.problem === "busy") return null;
1093
+ throw err;
1094
+ })
1095
+ ]);
1096
+ if (now - k.infoAt > 10 * 6e4) {
1097
+ k.infoAt = now;
1098
+ const settings = await get("/api/settings").catch(() => void 0);
1099
+ const name = settings?.appearance?.name?.trim();
1100
+ if (name) k.name = name;
1101
+ const snap = settings?.plugins?.classicwebcam?.snapshot || (settings?.webcam?.webcamEnabled !== false ? settings?.webcam?.snapshotUrl : void 0);
1102
+ k.camera = cameraUrl(conn.base, snap);
1103
+ }
1104
+ const status = statusOf3(job2, printer);
1105
+ const tool = tempOf(printer?.temperature?.tool0?.actual, printer?.temperature?.tool0?.target);
1106
+ const bed = tempOf(printer?.temperature?.bed?.actual, printer?.temperature?.bed?.target);
1107
+ const chamber = tempOf(printer?.temperature?.chamber?.actual, printer?.temperature?.chamber?.target);
1108
+ const reading = {
1109
+ status,
1110
+ ...k.name ? { name: k.name } : {},
1111
+ ...k.camera ? { camera: k.camera } : {},
1112
+ ...tool ? { nozzle: tool } : {},
1113
+ ...bed ? { bed } : {},
1114
+ ...chamber ? { chamber } : {}
1115
+ };
1116
+ if (status === "error") {
1117
+ const why = (printer?.state?.error || job2.error || printer?.state?.text || job2.state || "").replace(/^(Offline after error|Error):?\s*/i, "").trim();
1118
+ if (why) reading.message = why;
1119
+ }
1120
+ const file = job2.job?.file;
1121
+ const path = file?.path ?? file?.name ?? "";
1122
+ if (path && status !== "offline" && status !== "error") {
1123
+ const completion = num(job2.progress?.completion);
1124
+ const printed = num(job2.progress?.printTime);
1125
+ const estimate = num(job2.progress?.printTimeLeft);
1126
+ const left = estimate !== void 0 && !(estimate === 0 && (completion ?? 0) < 99) ? estimate : completion !== void 0 && completion > 2 && printed ? printed / (completion / 100) - printed : void 0;
1127
+ reading.job = {
1128
+ file: file?.display || path,
1129
+ ...completion !== void 0 ? { progress: Math.max(0, Math.min(1, completion / 100)) } : {},
1130
+ ...printed !== void 0 ? { elapsedMs: printed * 1e3, startedAt: now - printed * 1e3 } : {},
1131
+ ...left !== void 0 ? { leftMs: left * 1e3 } : {}
1132
+ };
1133
+ const origin = file?.origin === "sdcard" ? "sdcard" : "local";
1134
+ const key = `${origin}/${path}`;
1135
+ if (!k.thumbs.has(key)) {
1136
+ const entry = await get(`/api/files/${origin}/${path.split("/").map(encodeURIComponent).join("/")}`).catch(() => void 0);
1137
+ k.thumbs.set(key, thumbOf2(entry));
1138
+ if (k.thumbs.size > 20) k.thumbs.delete(k.thumbs.keys().next().value);
1139
+ }
1140
+ const thumb = k.thumbs.get(key);
1141
+ if (thumb) reading.thumb = /^https?:/i.test(thumb) ? thumb : `/${thumb.replace(/^\/+/, "")}`;
1142
+ }
1143
+ return reading;
1144
+ }
1145
+
1146
+ // src/state.ts
1147
+ var isEnded = (s) => s === "finished" || s === "cancelled" || s === "failed";
1148
+ function jobOf(r) {
1149
+ const j = r.job;
1150
+ if (!j) return void 0;
1151
+ const { file, ...rest } = j;
1152
+ return { name: jobName(file), ...rest };
1153
+ }
1154
+ function settle(prev, r, now, finishedMs) {
1155
+ const m = { ...prev };
1156
+ const job2 = jobOf(r);
1157
+ const file = r.job?.file;
1158
+ const message = r.message;
1159
+ const out = (phase, j, announce) => ({ phase, ...j ? { job: j } : {}, ...message ? { message } : {}, memory: m, ...announce ? { announce } : {} });
1160
+ if (r.status === "preparing" || r.status === "printing" || r.status === "paused") {
1161
+ m.active = file;
1162
+ if (job2?.progress !== void 0) m.activeProgress = job2.progress;
1163
+ delete m.ended;
1164
+ return out(r.status, job2);
1165
+ }
1166
+ if (r.status === "error" || r.status === "offline") {
1167
+ if (r.status === "error" && m.active) {
1168
+ const at = now;
1169
+ m.ended = { file: m.active, phase: "failed", at, job: { name: jobName(m.active), ...m.activeProgress !== void 0 ? { progress: m.activeProgress } : {}, endedAt: at }, seen: true };
1170
+ delete m.active;
1171
+ delete m.activeProgress;
1172
+ }
1173
+ return out(r.status, void 0);
1174
+ }
1175
+ if (isEnded(r.status) && file) {
1176
+ const same = m.ended?.file === file && m.ended.phase === r.status;
1177
+ const seen = same ? m.ended.seen : m.active === file;
1178
+ const at = (same ? m.ended.at : void 0) ?? r.job?.endedAt ?? now;
1179
+ m.ended = { file, phase: r.status, at, job: { ...job2, endedAt: at }, seen };
1180
+ delete m.active;
1181
+ delete m.activeProgress;
1182
+ return now - at <= finishedMs ? out(r.status, m.ended.job, seen) : out("idle", void 0);
1183
+ }
1184
+ if (m.active) {
1185
+ const done = (job2?.progress ?? m.activeProgress ?? 0) >= 0.999;
1186
+ const ended = { name: jobName(m.active), ...m.activeProgress !== void 0 ? { progress: m.activeProgress } : {}, ...job2 && r.job?.file === m.active ? Object.fromEntries(Object.entries(job2).filter(([, v]) => v !== void 0)) : {} };
1187
+ m.ended = { file: m.active, phase: done ? "finished" : "cancelled", at: now, job: { ...ended, ...done ? { progress: 1, leftMs: 0 } : {}, endedAt: now }, seen: true };
1188
+ delete m.active;
1189
+ delete m.activeProgress;
1190
+ return out(m.ended.phase, m.ended.job, true);
1191
+ }
1192
+ if (m.ended && now - m.ended.at <= finishedMs && (!file || file === m.ended.file)) return out(m.ended.phase, m.ended.job, m.ended.seen);
1193
+ return out("idle", void 0);
1194
+ }
1195
+
1196
+ // src/source.ts
1197
+ var STATUS = "3d-printer/status";
1198
+ var statusOptions = t.object({
1199
+ kind: t.enum(["moonraker", "octoprint", "bambu"], {
1200
+ default: "moonraker",
1201
+ label: L("Printer software", "Software de la impresora", "Drucker-Software", "\u6253\u5370\u673A\u8F6F\u4EF6", "\u5370\u8868\u6A5F\u8EDF\u9AD4"),
1202
+ labels: {
1203
+ moonraker: L("Klipper (Moonraker: Mainsail, Fluidd)", "Klipper (Moonraker: Mainsail, Fluidd)", "Klipper (Moonraker: Mainsail, Fluidd)", "Klipper\uFF08Moonraker\uFF1AMainsail\u3001Fluidd\uFF09", "Klipper\uFF08Moonraker\uFF1AMainsail\u3001Fluidd\uFF09"),
1204
+ octoprint: L("OctoPrint", "OctoPrint", "OctoPrint", "OctoPrint", "OctoPrint"),
1205
+ bambu: L("Bambu Lab (LAN mode)", "Bambu Lab (modo LAN)", "Bambu Lab (LAN-Modus)", "Bambu Lab\uFF08\u5C40\u57DF\u7F51\u6A21\u5F0F\uFF09", "Bambu Lab\uFF08\u5340\u57DF\u7DB2\u8DEF\u6A21\u5F0F\uFF09")
1206
+ }
1207
+ }),
1208
+ url: t.string({
1209
+ risk: "network",
1210
+ placeholder: "http://voron.local",
1211
+ label: L("Address", "Direcci\xF3n", "Adresse", "\u5730\u5740", "\u4F4D\u5740"),
1212
+ help: L(
1213
+ "Where the printer answers on your network: the address of its web page (Mainsail, Fluidd, OctoPrint), or Moonraker's port (http://voron.local:7125). For Bambu Lab, the printer's IP address (on its screen, under Network).",
1214
+ "D\xF3nde responde la impresora en tu red: la direcci\xF3n de su p\xE1gina web (Mainsail, Fluidd, OctoPrint), o el puerto de Moonraker (http://voron.local:7125). En Bambu Lab, la direcci\xF3n IP de la impresora (en su pantalla, en Red).",
1215
+ "Wo der Drucker in deinem Netz antwortet: die Adresse seiner Weboberfl\xE4che (Mainsail, Fluidd, OctoPrint) oder der Port von Moonraker (http://voron.local:7125). Bei Bambu Lab die IP-Adresse des Druckers (auf seinem Display unter Netzwerk).",
1216
+ "\u6253\u5370\u673A\u5728\u5C40\u57DF\u7F51\u4E2D\u7684\u5730\u5740\uFF1A\u5B83\u7684\u7F51\u9875\u5730\u5740\uFF08Mainsail\u3001Fluidd\u3001OctoPrint\uFF09\uFF0C\u6216 Moonraker \u7684\u7AEF\u53E3\uFF08http://voron.local:7125\uFF09\u3002Bambu Lab \u586B\u6253\u5370\u673A\u7684 IP \u5730\u5740\uFF08\u5728\u6253\u5370\u673A\u5C4F\u5E55\u7684\u201C\u7F51\u7EDC\u201D\u4E2D\uFF09\u3002",
1217
+ "\u5370\u8868\u6A5F\u5728\u5340\u57DF\u7DB2\u8DEF\u4E2D\u7684\u4F4D\u5740\uFF1A\u5B83\u7684\u7DB2\u9801\u4F4D\u5740\uFF08Mainsail\u3001Fluidd\u3001OctoPrint\uFF09\uFF0C\u6216 Moonraker \u7684\u9023\u63A5\u57E0\uFF08http://voron.local:7125\uFF09\u3002Bambu Lab \u8ACB\u586B\u5370\u8868\u6A5F\u7684 IP \u4F4D\u5740\uFF08\u5728\u5370\u8868\u6A5F\u87A2\u5E55\u7684\u300C\u7DB2\u8DEF\u300D\u4E2D\uFF09\u3002"
1218
+ )
1219
+ }),
1220
+ apiKey: t.string({
1221
+ secret: true,
1222
+ label: L("API key", "Clave de la API", "API-Schl\xFCssel", "API \u5BC6\u94A5", "API \u91D1\u9470"),
1223
+ help: L(
1224
+ "OctoPrint: make one in Settings \u2192 Application Keys (or use your user's). Klipper: only if Moonraker asks for one (this machine is not in its trusted clients).",
1225
+ "OctoPrint: crea una en Ajustes \u2192 Application Keys (o usa la de tu usuario). Klipper: solo si Moonraker la pide (este equipo no est\xE1 entre sus clientes de confianza).",
1226
+ "OctoPrint: unter Einstellungen \u2192 Application Keys anlegen (oder den deines Benutzers nehmen). Klipper: nur, wenn Moonraker einen verlangt (dieser Rechner steht nicht in seinen vertrauensw\xFCrdigen Clients).",
1227
+ "OctoPrint\uFF1A\u5728\u201C\u8BBE\u7F6E \u2192 Application Keys\u201D\u4E2D\u521B\u5EFA\u4E00\u4E2A\uFF08\u6216\u4F7F\u7528\u4F60\u7528\u6237\u7684\u5BC6\u94A5\uFF09\u3002Klipper\uFF1A\u4EC5\u5F53 Moonraker \u8981\u6C42\u65F6\u586B\u5199\uFF08\u672C\u673A\u4E0D\u5728\u5B83\u7684\u53D7\u4FE1\u4EFB\u5BA2\u6237\u7AEF\u4E2D\uFF09\u3002",
1228
+ "OctoPrint\uFF1A\u5728\u300C\u8A2D\u5B9A \u2192 Application Keys\u300D\u4E2D\u5EFA\u7ACB\u4E00\u500B\uFF08\u6216\u4F7F\u7528\u4F60\u4F7F\u7528\u8005\u7684\u91D1\u9470\uFF09\u3002Klipper\uFF1A\u50C5\u5728 Moonraker \u8981\u6C42\u6642\u586B\u5BEB\uFF08\u672C\u6A5F\u4E0D\u5728\u5B83\u7684\u53D7\u4FE1\u4EFB\u7528\u6236\u7AEF\u4E2D\uFF09\u3002"
1229
+ )
1230
+ }),
1231
+ serial: t.string({
1232
+ placeholder: "01P00A000000000",
1233
+ label: L("Serial number (Bambu Lab)", "N\xFAmero de serie (Bambu Lab)", "Seriennummer (Bambu Lab)", "\u5E8F\u5217\u53F7\uFF08Bambu Lab\uFF09", "\u5E8F\u865F\uFF08Bambu Lab\uFF09"),
1234
+ help: L(
1235
+ "On the printer's screen (Settings \u2192 Device) or in Bambu Studio's device list. Only for Bambu Lab.",
1236
+ "En la pantalla de la impresora (Ajustes \u2192 Dispositivo) o en la lista de dispositivos de Bambu Studio. Solo para Bambu Lab.",
1237
+ "Auf dem Display des Druckers (Einstellungen \u2192 Ger\xE4t) oder in der Ger\xE4teliste von Bambu Studio. Nur f\xFCr Bambu Lab.",
1238
+ "\u5728\u6253\u5370\u673A\u5C4F\u5E55\uFF08\u8BBE\u7F6E \u2192 \u8BBE\u5907\uFF09\u6216 Bambu Studio \u7684\u8BBE\u5907\u5217\u8868\u4E2D\u3002\u4EC5\u7528\u4E8E Bambu Lab\u3002",
1239
+ "\u5728\u5370\u8868\u6A5F\u87A2\u5E55\uFF08\u8A2D\u5B9A \u2192 \u88DD\u7F6E\uFF09\u6216 Bambu Studio \u7684\u88DD\u7F6E\u6E05\u55AE\u4E2D\u3002\u50C5\u7528\u65BC Bambu Lab\u3002"
1240
+ )
1241
+ }),
1242
+ accessCode: t.string({
1243
+ secret: true,
1244
+ label: L("Access code (Bambu Lab)", "C\xF3digo de acceso (Bambu Lab)", "Zugangscode (Bambu Lab)", "\u8BBF\u95EE\u7801\uFF08Bambu Lab\uFF09", "\u5B58\u53D6\u78BC\uFF08Bambu Lab\uFF09"),
1245
+ help: L(
1246
+ "The LAN access code on the printer's screen, under Network. The printer must be in LAN mode, and on recent firmware in Developer mode too.",
1247
+ "El c\xF3digo de acceso LAN de la pantalla de la impresora, en Red. La impresora tiene que estar en modo LAN y, con firmware reciente, tambi\xE9n en modo desarrollador.",
1248
+ "Der LAN-Zugangscode auf dem Display des Druckers unter Netzwerk. Der Drucker muss im LAN-Modus sein, bei neuer Firmware auch im Entwicklermodus.",
1249
+ "\u6253\u5370\u673A\u5C4F\u5E55\u201C\u7F51\u7EDC\u201D\u4E2D\u7684\u5C40\u57DF\u7F51\u8BBF\u95EE\u7801\u3002\u6253\u5370\u673A\u9700\u5F00\u542F\u5C40\u57DF\u7F51\u6A21\u5F0F\uFF0C\u8F83\u65B0\u7684\u56FA\u4EF6\u8FD8\u9700\u5F00\u542F\u5F00\u53D1\u8005\u6A21\u5F0F\u3002",
1250
+ "\u5370\u8868\u6A5F\u87A2\u5E55\u300C\u7DB2\u8DEF\u300D\u4E2D\u7684\u5340\u57DF\u7DB2\u8DEF\u5B58\u53D6\u78BC\u3002\u5370\u8868\u6A5F\u9700\u958B\u555F\u5340\u57DF\u7DB2\u8DEF\u6A21\u5F0F\uFF0C\u8F03\u65B0\u7684\u97CC\u9AD4\u9084\u9700\u958B\u555F\u958B\u767C\u8005\u6A21\u5F0F\u3002"
1251
+ )
1252
+ }),
1253
+ name: t.string({
1254
+ placeholder: "Voron",
1255
+ label: L("Name on the panel", "Nombre en el panel", "Name auf dem Panel", "\u5728\u526F\u5C4F\u4E0A\u7684\u540D\u79F0", "\u5728\u9762\u677F\u4E0A\u7684\u540D\u7A31"),
1256
+ help: L("Empty: the printer's own name, or its address.", "Vac\xEDo: el nombre de la propia impresora, o su direcci\xF3n.", "Leer: der eigene Name des Druckers oder seine Adresse.", "\u7559\u7A7A\uFF1A\u4F7F\u7528\u6253\u5370\u673A\u81EA\u5DF1\u7684\u540D\u79F0\u6216\u5730\u5740\u3002", "\u7559\u7A7A\uFF1A\u4F7F\u7528\u5370\u8868\u6A5F\u81EA\u5DF1\u7684\u540D\u7A31\u6216\u4F4D\u5740\u3002")
1257
+ }),
1258
+ camera: t.string({
1259
+ advanced: true,
1260
+ risk: "network",
1261
+ placeholder: "http://voron.local/webcam/?action=snapshot",
1262
+ label: L("Camera snapshot address", "Direcci\xF3n de la foto de la c\xE1mara", "Adresse des Kamerabilds", "\u6444\u50CF\u5934\u5FEB\u7167\u5730\u5740", "\u651D\u5F71\u6A5F\u5FEB\u7167\u4F4D\u5740"),
1263
+ help: L(
1264
+ "An address that answers with a JPEG picture. Empty: the printer's own webcam, as Moonraker or OctoPrint have it set up.",
1265
+ "Una direcci\xF3n que responda con una foto JPEG. Vac\xEDo: la c\xE1mara de la propia impresora, como la tengan configurada Moonraker u OctoPrint.",
1266
+ "Eine Adresse, die mit einem JPEG-Bild antwortet. Leer: die eigene Webcam des Druckers, wie Moonraker oder OctoPrint sie eingerichtet haben.",
1267
+ "\u4E00\u4E2A\u8FD4\u56DE JPEG \u56FE\u7247\u7684\u5730\u5740\u3002\u7559\u7A7A\uFF1A\u4F7F\u7528 Moonraker \u6216 OctoPrint \u4E2D\u8BBE\u7F6E\u7684\u6253\u5370\u673A\u6444\u50CF\u5934\u3002",
1268
+ "\u4E00\u500B\u56DE\u50B3 JPEG \u5716\u7247\u7684\u4F4D\u5740\u3002\u7559\u7A7A\uFF1A\u4F7F\u7528 Moonraker \u6216 OctoPrint \u4E2D\u8A2D\u5B9A\u7684\u5370\u8868\u6A5F\u651D\u5F71\u6A5F\u3002"
1269
+ )
1270
+ }),
1271
+ finishedMs: t.duration({
1272
+ default: 30 * 6e4,
1273
+ min: 0,
1274
+ max: 24 * 36e5,
1275
+ label: L("Show a finished print for", "Mostrar una impresi\xF3n terminada durante", "Fertigen Druck anzeigen f\xFCr", "\u5B8C\u6210\u7684\u6253\u5370\u663E\u793A\u65F6\u957F", "\u5B8C\u6210\u7684\u5217\u5370\u986F\u793A\u6642\u9593"),
1276
+ help: L(
1277
+ "How long a print that has finished (or was cancelled, or failed) stays on the panel, asking for the part to be taken off. Then the printer counts as free.",
1278
+ "Cu\xE1nto tiempo sigue en el panel una impresi\xF3n terminada (o cancelada, o fallida), pidiendo que retires la pieza. Despu\xE9s la impresora cuenta como libre.",
1279
+ "Wie lange ein fertiger (abgebrochener oder fehlgeschlagener) Druck auf dem Panel bleibt und darum bittet, das Teil abzunehmen. Danach gilt der Drucker als frei.",
1280
+ "\u6253\u5370\u5B8C\u6210\uFF08\u6216\u53D6\u6D88\u3001\u5931\u8D25\uFF09\u540E\u5728\u526F\u5C4F\u4E0A\u4FDD\u7559\u591A\u4E45\uFF0C\u63D0\u9192\u4F60\u53D6\u4E0B\u6A21\u578B\u3002\u4E4B\u540E\u6253\u5370\u673A\u89C6\u4E3A\u7A7A\u95F2\u3002",
1281
+ "\u5217\u5370\u5B8C\u6210\uFF08\u6216\u53D6\u6D88\u3001\u5931\u6557\uFF09\u5F8C\u5728\u9762\u677F\u4E0A\u4FDD\u7559\u591A\u4E45\uFF0C\u63D0\u9192\u4F60\u53D6\u4E0B\u6A21\u578B\u3002\u4E4B\u5F8C\u5370\u8868\u6A5F\u8996\u70BA\u9592\u7F6E\u3002"
1282
+ )
1283
+ })
1284
+ });
1285
+ var kept3 = /* @__PURE__ */ new Map();
1286
+ function target(o) {
1287
+ const headers = o.apiKey.trim() ? { "X-Api-Key": o.apiKey.trim() } : {};
1288
+ if (o.kind === "bambu") {
1289
+ const host = o.url.trim().replace(/^[a-z]+:\/\//i, "").replace(/[/:].*$/, "");
1290
+ return host && o.serial.trim() && o.accessCode.trim() ? { host } : void 0;
1291
+ }
1292
+ const conn = connOf(o.url, headers);
1293
+ return conn ? { conn } : void 0;
1294
+ }
1295
+ async function keepThumb(k, r, o) {
1296
+ if (!r.thumb || !o.conn) return void 0;
1297
+ if (k.thumb?.from === r.thumb) return { file: k.thumb.file, key: k.thumb.key };
1298
+ const { body, type } = await getBytes(o.conn, r.thumb, { maxBytes: 4 * 1024 * 1024, ...o.signal ? { signal: o.signal } : {} }, o.fetch);
1299
+ if (!/^image\//.test(type) && !(body[0] === 137 && body[1] === 80) && !(body[0] === 255 && body[1] === 216)) return void 0;
1300
+ const key = createHash("sha256").update(body).digest("hex").slice(0, 16);
1301
+ const dir = join(o.cacheDir, "thumbs");
1302
+ await mkdir(dir, { recursive: true });
1303
+ const file = join(dir, `${(o.profile ?? "default").replace(/[^a-z0-9_-]/gi, "_")}-${key}.img`);
1304
+ await writeFile(file, body);
1305
+ if (k.thumb && k.thumb.file !== file) await rm(k.thumb.file, { force: true }).catch(() => void 0);
1306
+ k.thumb = { file, key, from: r.thumb };
1307
+ return { file, key };
1308
+ }
1309
+ async function readStatus(ctx, deps = {}) {
1310
+ const o = ctx.options;
1311
+ const backend = o.kind;
1312
+ const where = target(o);
1313
+ const base = { backend, at: ctx.now };
1314
+ if (!where) return { ...base, configured: false, name: o.name.trim() || hostOf(o.url.trim() || "?"), phase: "idle" };
1315
+ const keyOf = `${ctx.profile ?? ""}|${backend}|${o.url.trim()}|${o.serial.trim()}`;
1316
+ let k = kept3.get(keyOf);
1317
+ if (!k) kept3.set(keyOf, k = { memory: {} });
1318
+ const conn = "conn" in where ? where.conn : void 0;
1319
+ const signal = ctx.signal;
1320
+ const reading = backend === "bambu" ? await readBambu({ host: where.host, serial: o.serial.trim(), accessCode: o.accessCode.trim(), now: ctx.now, signal }) : backend === "octoprint" ? await readOctoPrint({ conn, signal, now: ctx.now, ...deps.fetch ? { fetch: deps.fetch } : {} }) : await readMoonraker({ conn, signal, now: ctx.now, ...deps.fetch ? { fetch: deps.fetch } : {} });
1321
+ const settled2 = settle(k.memory, reading, ctx.now, o.finishedMs);
1322
+ k.memory = settled2.memory;
1323
+ const name = o.name.trim() || reading.name || (conn ? hostOf(conn) : where.host);
1324
+ const camera2 = rememberCamera(o.camera.trim() || reading.camera);
1325
+ const thumb = settled2.job ? await keepThumb(k, reading, { conn, cacheDir: ctx.cacheDir, profile: ctx.profile, ...signal ? { signal } : {}, ...deps.fetch ? { fetch: deps.fetch } : {} }).catch(() => void 0) : void 0;
1326
+ return {
1327
+ ...base,
1328
+ configured: true,
1329
+ name,
1330
+ phase: settled2.phase,
1331
+ ...settled2.message ? { message: settled2.message } : {},
1332
+ ...settled2.job ? { job: settled2.job } : {},
1333
+ ...reading.nozzle ? { nozzle: reading.nozzle } : {},
1334
+ ...reading.bed ? { bed: reading.bed } : {},
1335
+ ...reading.chamber ? { chamber: reading.chamber } : {},
1336
+ ...thumb ? { thumb } : {},
1337
+ ...camera2 ? { camera: camera2 } : {},
1338
+ ...settled2.announce ? { announce: true } : {}
1339
+ };
1340
+ }
1341
+ var statusSource = defineSource({
1342
+ id: "status",
1343
+ name: L("3D printer", "Impresora 3D", "3D-Drucker", "3D \u6253\u5370\u673A", "3D \u5370\u8868\u6A5F"),
1344
+ description: L(
1345
+ "A 3D printer on your network: Klipper (through Moonraker), OctoPrint or Bambu Lab in LAN mode. Add a profile for each printer.",
1346
+ "Una impresora 3D de tu red: Klipper (a trav\xE9s de Moonraker), OctoPrint o Bambu Lab en modo LAN. A\xF1ade un perfil por impresora.",
1347
+ "Ein 3D-Drucker in deinem Netz: Klipper (\xFCber Moonraker), OctoPrint oder Bambu Lab im LAN-Modus. Lege f\xFCr jeden Drucker ein Profil an.",
1348
+ "\u5C40\u57DF\u7F51\u4E2D\u7684\u4E00\u53F0 3D \u6253\u5370\u673A\uFF1AKlipper\uFF08\u901A\u8FC7 Moonraker\uFF09\u3001OctoPrint \u6216\u5C40\u57DF\u7F51\u6A21\u5F0F\u7684 Bambu Lab\u3002\u6BCF\u53F0\u6253\u5370\u673A\u6DFB\u52A0\u4E00\u4E2A\u914D\u7F6E\u3002",
1349
+ "\u5340\u57DF\u7DB2\u8DEF\u4E2D\u7684\u4E00\u53F0 3D \u5370\u8868\u6A5F\uFF1AKlipper\uFF08\u900F\u904E Moonraker\uFF09\u3001OctoPrint \u6216\u5340\u57DF\u7DB2\u8DEF\u6A21\u5F0F\u7684 Bambu Lab\u3002\u6BCF\u53F0\u5370\u8868\u6A5F\u65B0\u589E\u4E00\u500B\u8A2D\u5B9A\u6A94\u3002"
1350
+ ),
1351
+ options: statusOptions,
1352
+ profiles: true,
1353
+ intervalMs: 5e3,
1354
+ minIntervalMs: 2e3,
1355
+ timeoutMs: 15e3,
1356
+ background: true,
1357
+ read: (ctx) => readStatus(ctx),
1358
+ alerts: ({ data, now }) => alertsOf(data, now),
1359
+ demo: ({ now, locale }) => demoStatus(now, locale)
1360
+ });
1361
+ function alertsOf(d, now) {
1362
+ if (!d?.configured || d.demo) return [];
1363
+ const source = d.name;
1364
+ const job2 = d.job;
1365
+ if (d.phase === "error") {
1366
+ return [
1367
+ {
1368
+ id: `error-${d.message ?? ""}`,
1369
+ level: "warn",
1370
+ title: L("Printer error", "Error de la impresora", "Druckerfehler", "\u6253\u5370\u673A\u9519\u8BEF", "\u5370\u8868\u6A5F\u932F\u8AA4"),
1371
+ ...d.message ? { text: d.message } : {},
1372
+ source,
1373
+ icon: "triangle-alert"
1374
+ }
1375
+ ];
1376
+ }
1377
+ if (!job2 || !d.announce || job2.endedAt === void 0) return [];
1378
+ const id = `${job2.name}-${job2.endedAt}`;
1379
+ if (d.phase === "failed") {
1380
+ return [
1381
+ {
1382
+ id: `failed-${id}`,
1383
+ level: "warn",
1384
+ title: L("Print failed", "La impresi\xF3n ha fallado", "Druck fehlgeschlagen", "\u6253\u5370\u5931\u8D25", "\u5217\u5370\u5931\u6557"),
1385
+ text: d.message ? `${job2.name} \xB7 ${d.message}` : job2.name,
1386
+ source,
1387
+ icon: "circle-x"
1388
+ }
1389
+ ];
1390
+ }
1391
+ if (d.phase === "finished" && now - job2.endedAt < 15 * 6e4) {
1392
+ return [
1393
+ {
1394
+ id: `finished-${id}`,
1395
+ level: "info",
1396
+ title: L("Print finished", "Impresi\xF3n terminada", "Druck fertig", "\u6253\u5370\u5B8C\u6210", "\u5217\u5370\u5B8C\u6210"),
1397
+ text: job2.name,
1398
+ source,
1399
+ icon: "bell",
1400
+ expiresAt: job2.endedAt + 15 * 6e4
1401
+ }
1402
+ ];
1403
+ }
1404
+ return [];
1405
+ }
1406
+
1407
+ // src/types.ts
1408
+ var ACTIVE = ["preparing", "printing", "paused"];
1409
+ var ENDED = ["finished", "cancelled", "failed"];
1410
+
1411
+ // src/camera.ts
1412
+ var cameraOptions = t2.object({
1413
+ onlyWhilePrinting: t2.boolean({
1414
+ default: true,
1415
+ label: L("Only while printing", "Solo mientras imprime", "Nur w\xE4hrend des Drucks", "\u4EC5\u5728\u6253\u5370\u65F6", "\u50C5\u5728\u5217\u5370\u6642"),
1416
+ help: L(
1417
+ "While a print goes on, and while a finished one waits to be taken off. Off: always, a picture a minute when idle.",
1418
+ "Mientras haya una impresi\xF3n en curso, y mientras una terminada espera a que la retires. Desactivado: siempre, una foto por minuto en reposo.",
1419
+ "Solange ein Druck l\xE4uft und solange ein fertiger darauf wartet, abgenommen zu werden. Aus: immer, im Leerlauf ein Bild pro Minute.",
1420
+ "\u6253\u5370\u8FDB\u884C\u4E2D\uFF0C\u4EE5\u53CA\u5B8C\u6210\u540E\u7B49\u5F85\u53D6\u4E0B\u6A21\u578B\u65F6\u3002\u5173\u95ED\uFF1A\u59CB\u7EC8\u663E\u793A\uFF0C\u7A7A\u95F2\u65F6\u6BCF\u5206\u949F\u4E00\u5F20\u3002",
1421
+ "\u5217\u5370\u9032\u884C\u4E2D\uFF0C\u4EE5\u53CA\u5B8C\u6210\u5F8C\u7B49\u5F85\u53D6\u4E0B\u6A21\u578B\u6642\u3002\u95DC\u9589\uFF1A\u4E00\u5F8B\u986F\u793A\uFF0C\u9592\u7F6E\u6642\u6BCF\u5206\u9418\u4E00\u5F35\u3002"
1422
+ )
1423
+ }),
1424
+ showProgress: t2.boolean({
1425
+ default: true,
1426
+ label: L("Show the progress", "Mostrar el progreso", "Fortschritt anzeigen", "\u663E\u793A\u8FDB\u5EA6", "\u986F\u793A\u9032\u5EA6")
1427
+ })
1428
+ });
1429
+ var SNAP_MS = 1e4;
1430
+ var IDLE_MS = 6e4;
1431
+ var watching = (d) => !!d && (ACTIVE.includes(d.phase) || ENDED.includes(d.phase));
1432
+ function strip(g, ctx, d) {
1433
+ const { box, kit, theme, fmt } = ctx;
1434
+ const job2 = d.job;
1435
+ if (!job2) return;
1436
+ const s = clamp(Math.round(Math.min(box.h * 0.075, box.w / 22)), MIN_PX, 22);
1437
+ const lh = lineHeight(ctx, s);
1438
+ const bh = Math.max(3, Math.round(s * 0.28));
1439
+ const h = lh + bh + Math.round(s * 0.9);
1440
+ if (h > box.h * 0.6) return;
1441
+ const y0 = box.y + box.h - h;
1442
+ const shade = g.createLinearGradient(0, y0 - h * 0.4, 0, box.y + box.h);
1443
+ shade.addColorStop(0, "rgba(0,0,0,0)");
1444
+ shade.addColorStop(0.35, "rgba(0,0,0,0.55)");
1445
+ shade.addColorStop(1, "rgba(0,0,0,0.8)");
1446
+ g.fillStyle = shade;
1447
+ g.fillRect(box.x, Math.max(box.y, y0 - h * 0.4), box.w, box.y + box.h - Math.max(box.y, y0 - h * 0.4));
1448
+ const pad = Math.round(s * 0.6);
1449
+ const done = d.phase === "finished";
1450
+ const left = done || job2.leftMs === void 0 || !ACTIVE.includes(d.phase) ? "" : fill(ctx.t, LEFT, { d: fmt.duration(job2.leftMs, { round: "up" }) });
1451
+ const label = [ctx.t(PHASE[d.phase]), percent(ctx.locale, done ? 1 : job2.progress ?? 0, done)].join(" \xB7 ");
1452
+ const f = { size: s, family: theme.fonts.sansBold, color: "#f4f1ea" };
1453
+ const base = y0 + pad + s * 0.85;
1454
+ const lw = left ? kit.measureTracked(g, left, { ...f, family: theme.fonts.sans }) : 0;
1455
+ kit.drawTracked(g, kit.truncate(g, label, box.w - pad * 2 - (lw ? lw + pad : 0), f), box.x + pad, base, f);
1456
+ if (left && lw + pad * 3 < box.w * 0.7) kit.drawTracked(g, left, box.x + box.w - pad - lw, base, { ...f, family: theme.fonts.sans, color: "rgba(244,241,234,0.85)" });
1457
+ drawBar(g, ctx, { x: box.x + pad, y: box.y + box.h - pad * 0.7 - bh, w: box.w - pad * 2, h: bh }, done ? 1 : job2.progress ?? 0, phaseColor(ctx, d.phase));
1458
+ }
1459
+ function render(g, ctx) {
1460
+ const { box, theme } = ctx;
1461
+ const d = ctx.sources[STATUS];
1462
+ const o = ctx.options;
1463
+ if (!d) return;
1464
+ if (!d.configured) return drawMessage(g, ctx, ctx.t(SET_UP));
1465
+ const data = ctx.data;
1466
+ const img = d.demo ? demoCamera(ctx.canvas, box.w, box.h, d.job?.progress ?? 0.6) : data?.img;
1467
+ if (!img) {
1468
+ if (!d.camera) return drawEmpty(g, ctx, ctx.t(NO_CAMERA));
1469
+ if (o.onlyWhilePrinting && !watching(d)) return drawEmpty(g, ctx, d.phase === "offline" ? fill(ctx.t, IS_OFF, { name: d.name }) : ctx.t(FREE));
1470
+ return drawMessage(g, ctx, data?.error ? `${ctx.t(NO_PICTURE)}: ${data.error}` : ctx.t(NO_PICTURE));
1471
+ }
1472
+ clipped(g, box, () => {
1473
+ drawPicture(g, img, box, "cover", 0, theme.colors.bg);
1474
+ if (o.showProgress && watching(d)) strip(g, ctx, d);
1475
+ });
1476
+ }
1477
+ var camera = defineWidget({
1478
+ id: "camera",
1479
+ name: L("Printer camera", "C\xE1mara de la impresora", "Druckerkamera", "\u6253\u5370\u673A\u6444\u50CF\u5934", "\u5370\u8868\u6A5F\u651D\u5F71\u6A5F"),
1480
+ description: L(
1481
+ "The printer's webcam, a picture every few seconds while it prints, with how far the print is and how long is left. The camera Moonraker or OctoPrint have set up, or any address that answers with a JPEG.",
1482
+ "La c\xE1mara de la impresora, una foto cada pocos segundos mientras imprime, con por d\xF3nde va la impresi\xF3n y cu\xE1nto queda. La c\xE1mara que tengan configurada Moonraker u OctoPrint, o cualquier direcci\xF3n que responda con un JPEG.",
1483
+ "Die Webcam des Druckers, alle paar Sekunden ein Bild w\xE4hrend des Drucks, mit Fortschritt und Restzeit. Die Kamera, die Moonraker oder OctoPrint eingerichtet haben, oder jede Adresse, die mit einem JPEG antwortet.",
1484
+ "\u6253\u5370\u673A\u7684\u6444\u50CF\u5934\uFF0C\u6253\u5370\u65F6\u6BCF\u9694\u51E0\u79D2\u4E00\u5F20\u753B\u9762\uFF0C\u5E76\u663E\u793A\u6253\u5370\u8FDB\u5EA6\u548C\u5269\u4F59\u65F6\u95F4\u3002\u4F7F\u7528 Moonraker \u6216 OctoPrint \u4E2D\u8BBE\u7F6E\u7684\u6444\u50CF\u5934\uFF0C\u6216\u4EFB\u4F55\u8FD4\u56DE JPEG \u7684\u5730\u5740\u3002",
1485
+ "\u5370\u8868\u6A5F\u7684\u651D\u5F71\u6A5F\uFF0C\u5217\u5370\u6642\u6BCF\u9694\u5E7E\u79D2\u4E00\u5F35\u756B\u9762\uFF0C\u4E26\u986F\u793A\u5217\u5370\u9032\u5EA6\u548C\u5269\u9918\u6642\u9593\u3002\u4F7F\u7528 Moonraker \u6216 OctoPrint \u4E2D\u8A2D\u5B9A\u7684\u651D\u5F71\u6A5F\uFF0C\u6216\u4EFB\u4F55\u56DE\u50B3 JPEG \u7684\u4F4D\u5740\u3002"
1486
+ ),
1487
+ icon: "webcam",
1488
+ category: "system",
1489
+ tags: ["3d printer", "webcam", "camera", "klipper", "octoprint"],
1490
+ chrome: "bare",
1491
+ size: { min: { w: 160, h: 100 }, preferred: { w: 480, h: 360 } },
1492
+ sources: [STATUS],
1493
+ options: cameraOptions,
1494
+ fetchSize: true,
1495
+ intervalMs: SNAP_MS,
1496
+ timeoutMs: 15e3,
1497
+ intervalOf: ({ data }) => data?.watching ? SNAP_MS : IDLE_MS,
1498
+ async fetch(ctx) {
1499
+ const d = ctx.sources[STATUS];
1500
+ const on = watching(d);
1501
+ if (!d?.configured || d.demo || !d.camera || ctx.options.onlyWhilePrinting && !on) return { watching: on };
1502
+ const size = ctx.size ? { width: Math.round(ctx.size.width * ctx.size.zoom), height: Math.round(ctx.size.height * ctx.size.zoom) } : { width: 960, height: 720 };
1503
+ try {
1504
+ const img = await loadSnapshot(ctx.canvas, d.camera, { signal: ctx.signal, size });
1505
+ return { img, at: ctx.now, watching: on };
1506
+ } catch (err) {
1507
+ return { error: err instanceof Error ? err.message : String(err), watching: on };
1508
+ }
1509
+ },
1510
+ empty: ({ sources, options }) => {
1511
+ const d = sources[STATUS];
1512
+ if (!d?.configured || d.demo) return false;
1513
+ return !d.camera || options.onlyWhilePrinting && !watching(d);
1514
+ },
1515
+ idle: ({ sources }) => !watching(sources[STATUS]),
1516
+ render: (g, ctx) => render(g, ctx),
1517
+ demo: ({ now, locale }) => ({ sources: { [STATUS]: demoStatus(now, locale) } })
1518
+ });
1519
+
1520
+ // src/job.ts
1521
+ import { defineWidget as defineWidget2, drawEmpty as drawEmpty2, t as t3 } from "@kiosko/sdk";
1522
+
1523
+ // src/temps.ts
1524
+ var settled = (t4) => t4.target <= 0 || Math.abs(t4.now - t4.target) <= 2;
1525
+ var deg = (t4) => `${Math.round(t4.now)} \xB0C`;
1526
+ var withTarget = (t4) => t4.target > 0 ? `${Math.round(t4.now)}/${Math.round(t4.target)} \xB0C` : deg(t4);
1527
+ var short = (t4) => settled(t4) ? deg(t4) : withTarget(t4);
1528
+ function variants(ctx, nozzle, bed) {
1529
+ const heaters = [nozzle && { icon: "nozzle", label: ctx.t(NOZZLE), t: nozzle }, bed && { icon: "bed", label: ctx.t(BED), t: bed }].filter((h) => !!h);
1530
+ if (!heaters.length) return [];
1531
+ const words = (f, sep) => ({ parts: heaters.map((h) => ({ text: `${h.label} ${f(h.t)}` })), sep });
1532
+ const icons = (f, only) => ({ parts: heaters.filter((h) => !only || h.icon === only).map((h) => ({ icon: h.icon, text: f(h.t) })), sep: " " });
1533
+ return [words(withTarget, " "), words(short, " \xB7 "), words(deg, " \xB7 "), icons(short), icons(deg), icons(deg, heaters[0].icon)];
1534
+ }
1535
+ function widthOf(g, ctx, v, font) {
1536
+ const sepW = ctx.kit.measureTracked(g, v.sep, font);
1537
+ return v.parts.reduce((w, p, i) => w + (i ? sepW : 0) + (p.icon ? iconW(font.size) : 0) + ctx.kit.measureTracked(g, p.text, font), 0);
1538
+ }
1539
+ var iconW = (size) => Math.round(size * 1.15);
1540
+ function drawIcon(g, icon, x, baseline, size, color) {
1541
+ const s = size;
1542
+ const top = baseline - s * 0.78;
1543
+ g.save();
1544
+ g.strokeStyle = color;
1545
+ g.fillStyle = color;
1546
+ g.lineWidth = Math.max(1, s * 0.09);
1547
+ g.lineJoin = "round";
1548
+ g.lineCap = "round";
1549
+ if (icon === "nozzle") {
1550
+ const cx = x + s * 0.45;
1551
+ g.strokeRect(cx - s * 0.32, top, s * 0.64, s * 0.42);
1552
+ g.beginPath();
1553
+ g.moveTo(cx - s * 0.2, top + s * 0.42);
1554
+ g.lineTo(cx + s * 0.2, top + s * 0.42);
1555
+ g.lineTo(cx, baseline);
1556
+ g.closePath();
1557
+ g.fill();
1558
+ } else {
1559
+ g.fillRect(x + s * 0.05, baseline - s * 0.14, s * 0.8, s * 0.14);
1560
+ for (const k of [0.18, 0.45, 0.72]) {
1561
+ const wx = x + s * k;
1562
+ g.beginPath();
1563
+ g.moveTo(wx, baseline - s * 0.28);
1564
+ g.quadraticCurveTo(wx + s * 0.12, baseline - s * 0.45, wx, baseline - s * 0.6);
1565
+ g.quadraticCurveTo(wx - s * 0.12, baseline - s * 0.72, wx, baseline - s * 0.85);
1566
+ g.stroke();
1567
+ }
1568
+ }
1569
+ g.restore();
1570
+ }
1571
+ function drawTemps(g, ctx, nozzle, bed, x, y, w, font) {
1572
+ const v = variants(ctx, nozzle, bed).find((c) => widthOf(g, ctx, c, font) <= w);
1573
+ if (!v) return false;
1574
+ let at = x;
1575
+ v.parts.forEach((p, i) => {
1576
+ if (i) at += ctx.kit.drawTracked(g, v.sep, at, y, font);
1577
+ if (p.icon) {
1578
+ drawIcon(g, p.icon, at, y, font.size, font.color);
1579
+ at += iconW(font.size);
1580
+ }
1581
+ at += ctx.kit.drawTracked(g, p.text, at, y, font);
1582
+ });
1583
+ return true;
1584
+ }
1585
+
1586
+ // src/job.ts
1587
+ var jobOptions = t3.object({
1588
+ picture: t3.enum(["model", "camera", "none"], {
1589
+ default: "model",
1590
+ label: L("Picture", "Imagen", "Bild", "\u56FE\u7247", "\u5716\u7247"),
1591
+ labels: {
1592
+ model: L("The model (the slicer's thumbnail, else the camera)", "El modelo (la miniatura del laminador o, si no, la c\xE1mara)", "Das Modell (Vorschaubild des Slicers, sonst die Kamera)", "\u6A21\u578B\uFF08\u5207\u7247\u8F6F\u4EF6\u7684\u7F29\u7565\u56FE\uFF0C\u6CA1\u6709\u5219\u7528\u6444\u50CF\u5934\uFF09", "\u6A21\u578B\uFF08\u5207\u7247\u8EDF\u9AD4\u7684\u7E2E\u5716\uFF0C\u6C92\u6709\u5247\u7528\u651D\u5F71\u6A5F\uFF09"),
1593
+ camera: L("The camera", "La c\xE1mara", "Die Kamera", "\u6444\u50CF\u5934", "\u651D\u5F71\u6A5F"),
1594
+ none: L("None", "Ninguna", "Keines", "\u4E0D\u663E\u793A", "\u4E0D\u986F\u793A")
1595
+ },
1596
+ help: L(
1597
+ "The slicer's thumbnail needs a slicer that writes them into the G-code (PrusaSlicer, OrcaSlicer, Cura, SuperSlicer), and on OctoPrint a plugin that reads them.",
1598
+ "La miniatura necesita un laminador que la escriba en el G-code (PrusaSlicer, OrcaSlicer, Cura, SuperSlicer) y, en OctoPrint, un plugin que la lea.",
1599
+ "Das Vorschaubild braucht einen Slicer, der es in den G-Code schreibt (PrusaSlicer, OrcaSlicer, Cura, SuperSlicer), und bei OctoPrint ein Plugin, das es liest.",
1600
+ "\u7F29\u7565\u56FE\u9700\u8981\u5207\u7247\u8F6F\u4EF6\u628A\u5B83\u5199\u8FDB G-code\uFF08PrusaSlicer\u3001OrcaSlicer\u3001Cura\u3001SuperSlicer\uFF09\uFF0COctoPrint \u8FD8\u9700\u8981\u4E00\u4E2A\u8BFB\u53D6\u5B83\u7684\u63D2\u4EF6\u3002",
1601
+ "\u7E2E\u5716\u9700\u8981\u5207\u7247\u8EDF\u9AD4\u628A\u5B83\u5BEB\u9032 G-code\uFF08PrusaSlicer\u3001OrcaSlicer\u3001Cura\u3001SuperSlicer\uFF09\uFF0COctoPrint \u9084\u9700\u8981\u4E00\u500B\u8B80\u53D6\u5B83\u7684\u5916\u639B\u3002"
1602
+ )
1603
+ }),
1604
+ showTemps: t3.boolean({
1605
+ default: true,
1606
+ label: L("Show the temperatures", "Mostrar las temperaturas", "Temperaturen anzeigen", "\u663E\u793A\u6E29\u5EA6", "\u986F\u793A\u6EAB\u5EA6")
1607
+ })
1608
+ });
1609
+ var isActive = (p) => ACTIVE.includes(p);
1610
+ var isEnded2 = (p) => ENDED.includes(p);
1611
+ function pictureOf(ctx, d, size) {
1612
+ const o = ctx.options;
1613
+ if (o.picture === "none") return void 0;
1614
+ if (d.demo) return o.picture === "camera" ? { img: demoCamera(ctx.canvas, size * 1.33, size, d.job?.progress ?? 0.6), kind: "camera" } : { img: demoModel(ctx.canvas, size), kind: "model" };
1615
+ return ctx.data?.picture;
1616
+ }
1617
+ function wordsOf(ctx, d) {
1618
+ const { fmt } = ctx;
1619
+ const o = ctx.options;
1620
+ const job2 = d.job;
1621
+ const phase = d.phase;
1622
+ const left = job2?.leftMs;
1623
+ const done = phase === "finished";
1624
+ const ago = job2?.endedAt !== void 0 ? fmt.ago(job2.endedAt) : void 0;
1625
+ const phaseWord = phase === "preparing" && (heating(d.nozzle) || heating(d.bed)) ? ctx.t(HEATING) : ctx.t(PHASE[phase]);
1626
+ const detail = isEnded2(phase) && ago ? ago : job2?.layers && job2.layer !== void 0 && (phase === "printing" || phase === "paused") ? fill(ctx.t, LAYER, { n: job2.layer, total: job2.layers }) : job2?.layers && phase === "preparing" ? fill(ctx.t, LAYERS, { total: job2.layers }) : "";
1627
+ return {
1628
+ name: job2?.name ?? d.name,
1629
+ done,
1630
+ progress: done ? 1 : job2?.progress ?? 0,
1631
+ phaseWord,
1632
+ status: [phaseWord, detail].filter(Boolean).join(" \xB7 "),
1633
+ // Under the bar: what to do, or the printer's words, or the temperatures.
1634
+ foot: done ? ctx.t(TAKE_OFF) : (phase === "failed" || phase === "paused" || phase === "error") && d.message ? d.message : "",
1635
+ // Else the temperatures, written as short as the width asks (temps.ts).
1636
+ temps: !done && !((phase === "failed" || phase === "paused" || phase === "error") && d.message) && o.showTemps && !!(d.nozzle || d.bed),
1637
+ times: done ? job2?.elapsedMs ? [fill(ctx.t, TOOK, { d: fmt.duration(job2.elapsedMs) })] : [] : isActive(phase) && left !== void 0 ? [fill(ctx.t, LEFT, { d: fmt.duration(left, { round: "up" }) }), fill(ctx.t, DONE_AT, { t: fmt.time(ctx.now + left) })] : [],
1638
+ pct: job2 ? percent(ctx.locale, done ? 1 : job2.progress ?? 0, done) : ""
1639
+ };
1640
+ }
1641
+ function barColor(ctx, d) {
1642
+ const c = ctx.theme.colors;
1643
+ return d.phase === "finished" ? c.ok : d.phase === "paused" ? c.warn : isEnded2(d.phase) ? c.inkFaint : c.accent;
1644
+ }
1645
+ function drawPic(g, ctx, d, pic) {
1646
+ const p = pictureOf(ctx, d, Math.max(pic.w, pic.h));
1647
+ const r = Math.round(Math.min(pic.w, pic.h) * 0.06);
1648
+ g.fillStyle = ctx.theme.colors.surface;
1649
+ g.beginPath();
1650
+ g.roundRect(pic.x, pic.y, pic.w, pic.h, r);
1651
+ g.fill();
1652
+ if (p?.kind === "camera") drawPicture(g, p.img, pic, "cover", r);
1653
+ else if (p) drawPicture(g, p.img, { x: pic.x + pic.w * 0.06, y: pic.y + pic.h * 0.06, w: pic.w * 0.88, h: pic.h * 0.88 }, "contain");
1654
+ else drawModelOutline(g, ctx, pic);
1655
+ }
1656
+ function paintStrip(g, ctx, d) {
1657
+ const { box, kit, theme } = ctx;
1658
+ const c = theme.colors;
1659
+ const o = ctx.options;
1660
+ const w = wordsOf(ctx, d);
1661
+ let x = box.x;
1662
+ if (o.picture !== "none" && box.h >= 56) {
1663
+ const side = o.picture === "camera" ? Math.round(box.h * 1.33) : box.h;
1664
+ drawPic(g, ctx, d, { x, y: box.y, w: side, h: box.h });
1665
+ x += side + Math.max(8, Math.round(box.h * 0.12));
1666
+ }
1667
+ const area = { x, y: box.y, w: box.x + box.w - x, h: box.h };
1668
+ const bh = Math.max(4, Math.round(box.h * 0.07));
1669
+ const top = { ...area, h: area.h - bh - Math.max(4, Math.round(box.h * 0.1)) };
1670
+ const s = clamp(Math.round(Math.min(top.h * 0.3, area.w / 26)), MIN_PX, 28);
1671
+ const lh = lineHeight(ctx, s);
1672
+ const tf = { size: s, family: theme.fonts.sans, color: c.inkDim };
1673
+ const tw = Math.max(0, ...w.times.map((l) => kit.measureTracked(g, l, tf)));
1674
+ const gap = Math.round(s * 0.9);
1675
+ const pf = { size: Math.round(Math.min(top.h * 0.82, s * 3)), family: theme.fonts.monoBold, color: isActive(d.phase) || w.done ? c.ink : c.inkDim };
1676
+ const pw = w.pct ? kit.measureTracked(g, w.pct, pf) : 0;
1677
+ const showTimes = tw > 0 && area.w - tw - pw - gap * 2 >= area.w * 0.3;
1678
+ const right = area.x + area.w - (showTimes ? tw + gap : 0);
1679
+ const textW = right - area.x - pw - gap;
1680
+ if (w.pct) kit.drawTracked(g, w.pct, right - pw, top.y + Math.round(top.h / 2 + pf.size * 0.36), pf);
1681
+ if (showTimes) {
1682
+ let ty = top.y + Math.round((top.h - w.times.length * lh) / 2) + s;
1683
+ for (const [i, l] of w.times.entries()) {
1684
+ kit.drawTracked(g, l, area.x + area.w - kit.measureTracked(g, l, tf), ty, { ...tf, color: i === 0 ? c.ink : c.inkDim });
1685
+ ty += lh;
1686
+ }
1687
+ }
1688
+ const nf = { size: Math.round(s * 1.1), family: theme.fonts.sansBold, color: c.ink };
1689
+ const two = top.h >= lineHeight(ctx, nf.size) + lh;
1690
+ const status = d.message && (d.phase === "failed" || d.phase === "paused" || d.phase === "error") ? `${w.phaseWord} \xB7 ${d.message}` : w.status;
1691
+ const block = (two ? lineHeight(ctx, nf.size) : 0) + lh;
1692
+ let y = top.y + Math.round((top.h - block) / 2);
1693
+ if (two) {
1694
+ kit.drawTracked(g, kit.truncate(g, w.name, textW, nf), area.x, y + nf.size, nf);
1695
+ y += lineHeight(ctx, nf.size);
1696
+ }
1697
+ const sf = { size: s, family: theme.fonts.sans, color: phaseColor(ctx, d.phase) };
1698
+ kit.drawTracked(g, kit.truncate(g, two ? status : `${w.name} \xB7 ${status}`, textW, sf), area.x, y + s, sf);
1699
+ if (d.job) drawBar(g, ctx, { x: area.x, y: area.y + area.h - bh, w: area.w, h: bh }, w.progress, barColor(ctx, d), shine(ctx));
1700
+ }
1701
+ function paint(g, ctx, d) {
1702
+ const { box, kit, theme } = ctx;
1703
+ const c = theme.colors;
1704
+ const o = ctx.options;
1705
+ const job2 = d.job;
1706
+ const phase = d.phase;
1707
+ const color = phaseColor(ctx, phase);
1708
+ if (box.h < 150 && box.w >= box.h * 3.2) return paintStrip(g, ctx, d);
1709
+ const wide = box.w >= box.h * 1.55;
1710
+ let pic;
1711
+ let info = box;
1712
+ if (o.picture !== "none") {
1713
+ if (wide && box.h >= 72) {
1714
+ const side = Math.round(Math.min(box.h, box.w * 0.36));
1715
+ const pw = o.picture === "camera" ? Math.round(Math.min(side * 1.33, box.w * 0.42)) : side;
1716
+ const gap = Math.max(8, Math.round(side * 0.07));
1717
+ pic = { x: box.x, y: box.y + Math.round((box.h - side) / 2), w: pw, h: side };
1718
+ info = { x: box.x + pw + gap, y: box.y, w: box.w - pw - gap, h: box.h };
1719
+ } else if (!wide && box.h >= 300 && box.w >= 150) {
1720
+ const ph = Math.round(Math.min(box.h * 0.46, box.w * (o.picture === "camera" ? 0.75 : 0.8)));
1721
+ const gap = Math.max(6, Math.round(ph * 0.05));
1722
+ pic = { x: box.x, y: box.y, w: box.w, h: ph };
1723
+ info = { x: box.x, y: box.y + ph + gap, w: box.w, h: box.h - ph - gap };
1724
+ }
1725
+ }
1726
+ if (pic) drawPic(g, ctx, d, pic);
1727
+ const { name, done, progress, status: statusText, foot: footText, temps, times: timeLines, pct } = wordsOf(ctx, d);
1728
+ const plan = (s, keep) => {
1729
+ const rows2 = [];
1730
+ const big = Math.round(s * 2.3);
1731
+ if (keep.kicker && job2) {
1732
+ const f = { size: Math.max(MIN_PX, Math.round(s * 0.72)), family: theme.fonts.sansBold, color: c.inkDim };
1733
+ rows2.push({ h: lineHeight(ctx, f.size), draw: (y2) => kit.drawTracked(g, kit.truncate(g, d.name.toUpperCase(), info.w, f), info.x, y2 + f.size, f) });
1734
+ }
1735
+ const tf = { size: Math.round(s * 1.12), family: theme.fonts.sansBold, color: c.ink };
1736
+ rows2.push({ h: lineHeight(ctx, tf.size), draw: (y2) => kit.drawTracked(g, kit.truncate(g, name, info.w, tf), info.x, y2 + tf.size, tf) });
1737
+ if (keep.status) {
1738
+ const sf = { size: Math.round(s), family: theme.fonts.sans, color };
1739
+ rows2.push({ h: lineHeight(ctx, sf.size), draw: (y2) => kit.drawTracked(g, kit.truncate(g, statusText, info.w, sf), info.x, y2 + sf.size, sf) });
1740
+ }
1741
+ if (job2) {
1742
+ const tl = { size: Math.max(MIN_PX, Math.round(s * 0.9)), family: theme.fonts.sans, color: c.inkDim };
1743
+ const pf = { size: big, family: theme.fonts.monoBold, color: isActive(phase) || done ? c.ink : c.inkDim };
1744
+ const tw = Math.max(0, ...timeLines.map((l) => kit.measureTracked(g, l, tl)));
1745
+ const beside = timeLines.length > 0 && info.w - tw - s * 0.8 >= Math.min(kit.measureTracked(g, pct, pf), info.w * 0.3);
1746
+ const size = fitText(ctx, g, pct, beside ? info.w - tw - Math.round(s * 0.8) : info.w, pf, MIN_PX);
1747
+ const bigH = Math.max(size, beside ? timeLines.length * lineHeight(ctx, tl.size) : 0);
1748
+ rows2.push({
1749
+ h: Math.round(bigH * 1.08),
1750
+ draw: (y2) => {
1751
+ const base = y2 + Math.round(bigH * 0.5 + size * 0.36);
1752
+ kit.drawTracked(g, pct, info.x, base, { ...pf, size });
1753
+ if (!beside) return;
1754
+ const lh = lineHeight(ctx, tl.size);
1755
+ let ty = y2 + Math.round((bigH - timeLines.length * lh) / 2) + tl.size;
1756
+ for (const [i, l] of timeLines.entries()) {
1757
+ const w = kit.measureTracked(g, l, tl);
1758
+ kit.drawTracked(g, l, info.x + info.w - w, ty, { ...tl, color: i === 0 ? c.ink : c.inkDim });
1759
+ ty += lh;
1760
+ }
1761
+ }
1762
+ });
1763
+ const bh = Math.max(4, Math.round(s * 0.5));
1764
+ rows2.push({ h: bh + Math.round(s * 0.55), draw: (y2) => drawBar(g, ctx, { x: info.x, y: y2 + Math.round(s * 0.15), w: info.w, h: bh }, progress, barColor(ctx, d), shine(ctx)) });
1765
+ if (!beside && timeLines.length) {
1766
+ const line = timeLines.join(" \xB7 ");
1767
+ rows2.push({ h: lineHeight(ctx, tl.size), draw: (y2) => kit.drawTracked(g, kit.truncate(g, line, info.w, tl), info.x, y2 + tl.size, { ...tl, color: c.ink }) });
1768
+ }
1769
+ } else if (phase === "error") {
1770
+ const mf = Math.round(s * 1.05);
1771
+ rows2.push({ h: lineHeight(ctx, mf) * 2, draw: (y2) => drawMessage(g, ctx, d.message ?? ctx.t(PHASE.error), { box: { x: info.x, y: y2, w: info.w, h: lineHeight(ctx, mf) * 2 }, color: c.alert }) });
1772
+ }
1773
+ if (keep.foot && footText) {
1774
+ const ff = { size: Math.max(MIN_PX, Math.round(s * 0.88)), family: theme.fonts.sans, color: done ? c.ok : phase === "failed" || phase === "error" ? c.alert : c.inkDim };
1775
+ rows2.push({ h: lineHeight(ctx, ff.size), draw: (y2) => kit.drawTracked(g, kit.truncate(g, footText, info.w, ff), info.x, y2 + ff.size, ff) });
1776
+ } else if (keep.foot && temps) {
1777
+ const ff = { size: Math.max(MIN_PX, Math.round(s * 0.88)), family: theme.fonts.sans, color: c.inkDim };
1778
+ rows2.push({ h: lineHeight(ctx, ff.size), draw: (y2) => void drawTemps(g, ctx, d.nozzle, d.bed, info.x, y2 + ff.size, info.w, ff) });
1779
+ }
1780
+ return rows2;
1781
+ };
1782
+ const total = (rows2) => rows2.reduce((a, r) => a + r.h, 0);
1783
+ const tries = [
1784
+ { kicker: true, status: true, foot: true },
1785
+ { kicker: false, status: true, foot: true },
1786
+ { kicker: false, status: true, foot: false },
1787
+ { kicker: false, status: false, foot: false }
1788
+ ];
1789
+ const cap = clamp(Math.round(Math.min(info.w / 10, info.h / 7, 40)), MIN_PX, 40);
1790
+ let rows = [];
1791
+ for (const keep of tries) {
1792
+ let s = cap;
1793
+ rows = plan(s, keep);
1794
+ while (total(rows) > info.h && s > MIN_PX) rows = plan(--s, keep);
1795
+ if (total(rows) <= info.h) break;
1796
+ }
1797
+ let y = info.y + Math.max(0, Math.round((info.h - total(rows)) / 2));
1798
+ clipped(g, info, () => {
1799
+ for (const r of rows) {
1800
+ r.draw(y);
1801
+ y += r.h;
1802
+ }
1803
+ });
1804
+ }
1805
+ function shine(ctx) {
1806
+ const a = ctx.anim;
1807
+ return a?.plan.id === "done" && a.t > 0 && a.t < 1 ? a.t : 0;
1808
+ }
1809
+ function render2(g, ctx) {
1810
+ const d = ctx.sources[STATUS];
1811
+ if (!d) return;
1812
+ if (!d.configured) return drawMessage(g, ctx, ctx.t(SET_UP));
1813
+ if (d.phase === "idle" || d.phase === "offline") return drawEmpty2(g, ctx, d.phase === "offline" ? fill(ctx.t, IS_OFF, { name: d.name }) : ctx.t(FREE));
1814
+ clipped(g, ctx.box, () => paint(g, ctx, d));
1815
+ }
1816
+ var job = defineWidget2({
1817
+ id: "job",
1818
+ name: L("Print", "Impresi\xF3n", "Druck", "\u6253\u5370\u4EFB\u52A1", "\u5217\u5370\u5DE5\u4F5C"),
1819
+ description: L(
1820
+ "The print going on: the model, how far it is, how long is left and when it will be done, the layer and the temperatures. Finished, failed or paused, it takes its tile over until you see to it; free, it gives its turn to the tile's other widgets.",
1821
+ "La impresi\xF3n en curso: el modelo, por d\xF3nde va, cu\xE1nto queda y a qu\xE9 hora termina, la capa y las temperaturas. Terminada, fallida o en pausa, se queda con su hueco hasta que la atiendas; libre, cede el turno a los dem\xE1s widgets de la tesela.",
1822
+ "Der laufende Druck: das Modell, wie weit er ist, wie lange es noch dauert und wann er fertig ist, die Schicht und die Temperaturen. Fertig, fehlgeschlagen oder pausiert, \xFCbernimmt er seine Kachel, bis du dich darum k\xFCmmerst; frei, l\xE4sst er den anderen Widgets der Kachel den Vortritt.",
1823
+ "\u6B63\u5728\u8FDB\u884C\u7684\u6253\u5370\uFF1A\u6A21\u578B\u3001\u8FDB\u5EA6\u3001\u5269\u4F59\u65F6\u95F4\u548C\u5B8C\u6210\u65F6\u523B\u3001\u5F53\u524D\u5C42\u548C\u6E29\u5EA6\u3002\u6253\u5370\u5B8C\u6210\u3001\u5931\u8D25\u6216\u6682\u505C\u65F6\uFF0C\u4F1A\u4E00\u76F4\u5360\u7528\u683C\u5B50\u76F4\u5230\u4F60\u5904\u7406\uFF1B\u6253\u5370\u673A\u7A7A\u95F2\u65F6\uFF0C\u628A\u683C\u5B50\u8BA9\u7ED9\u5176\u4ED6\u5C0F\u7EC4\u4EF6\u3002",
1824
+ "\u6B63\u5728\u9032\u884C\u7684\u5217\u5370\uFF1A\u6A21\u578B\u3001\u9032\u5EA6\u3001\u5269\u9918\u6642\u9593\u8207\u5B8C\u6210\u6642\u523B\u3001\u76EE\u524D\u5C64\u6578\u548C\u6EAB\u5EA6\u3002\u5217\u5370\u5B8C\u6210\u3001\u5931\u6557\u6216\u66AB\u505C\u6642\uFF0C\u6703\u4E00\u76F4\u4F54\u7528\u65B9\u683C\u76F4\u5230\u4F60\u8655\u7406\uFF1B\u5370\u8868\u6A5F\u9592\u7F6E\u6642\uFF0C\u628A\u65B9\u683C\u8B93\u7D66\u5176\u4ED6\u5C0F\u5DE5\u5177\u3002"
1825
+ ),
1826
+ icon: "printer",
1827
+ category: "system",
1828
+ tags: ["3d printer", "klipper", "moonraker", "octoprint", "bambu lab", "maker"],
1829
+ size: { min: { w: 160, h: 70 }, preferred: { w: 600, h: 300 } },
1830
+ sources: [STATUS],
1831
+ options: jobOptions,
1832
+ intervalMs: 15e3,
1833
+ timeoutMs: 2e4,
1834
+ async fetch(ctx) {
1835
+ const d = ctx.sources[STATUS];
1836
+ const o = ctx.options;
1837
+ if (!d?.configured || d.demo || o.picture === "none" || !d.job) return {};
1838
+ if (o.picture === "model" && d.thumb) {
1839
+ const img = await loadThumb(ctx.canvas, d.thumb).catch(() => void 0);
1840
+ if (img) return { picture: { img, kind: "model" } };
1841
+ }
1842
+ if (d.camera && (isActive(d.phase) || isEnded2(d.phase))) {
1843
+ const img = await loadSnapshot(ctx.canvas, d.camera, { signal: ctx.signal, size: { width: 640, height: 480 } }).catch(() => void 0);
1844
+ if (img) return { picture: { img, kind: "camera" } };
1845
+ }
1846
+ return {};
1847
+ },
1848
+ redraw: ({ sources }) => {
1849
+ const d = sources[STATUS];
1850
+ return d && (isActive(d.phase) || isEnded2(d.phase)) ? "minute" : "never";
1851
+ },
1852
+ urgent: ({ sources }) => {
1853
+ const p = sources[STATUS]?.phase;
1854
+ return p === "paused" || p === "finished" || p === "failed" || p === "error";
1855
+ },
1856
+ empty: ({ sources }) => {
1857
+ const d = sources[STATUS];
1858
+ return !!d?.configured && (d.phase === "idle" || d.phase === "offline");
1859
+ },
1860
+ idle: ({ sources }) => {
1861
+ const p = sources[STATUS]?.phase;
1862
+ return p === "idle" || p === "offline";
1863
+ },
1864
+ // When a print finishes, a light sweeps along its full bar.
1865
+ animationCooldownMs: 6e4,
1866
+ animation: ({ trigger, sources, prev }) => {
1867
+ if (trigger !== "data") return null;
1868
+ const was = prev?.sources[STATUS]?.phase;
1869
+ const now = sources[STATUS]?.phase;
1870
+ return now === "finished" && was && isActive(was) ? { id: "done", frames: 26, fps: 13 } : null;
1871
+ },
1872
+ render: (g, ctx) => render2(g, ctx),
1873
+ demo: ({ now, locale }) => ({ sources: { [STATUS]: demoStatus(now, locale) } })
1874
+ });
1875
+
1876
+ // src/index.ts
1877
+ var index_default = definePlugin({
1878
+ id: "3d-printer",
1879
+ name: L("3D printer", "Impresora 3D", "3D-Drucker", "3D \u6253\u5370\u673A", "3D \u5370\u8868\u6A5F"),
1880
+ version: VERSION,
1881
+ description: L(
1882
+ "Your 3D printer on the panel: the print going on with its model, progress, time left and when it will be done, the layer and the temperatures, and the webcam. A full-screen alert when a print fails, and a reminder to take the part off when it is done. Klipper (Moonraker: Mainsail, Fluidd), OctoPrint and Bambu Lab in LAN mode, on your network, no cloud.",
1883
+ "Tu impresora 3D en el panel: la impresi\xF3n en curso con su modelo, el progreso, cu\xE1nto queda y a qu\xE9 hora termina, la capa y las temperaturas, y la c\xE1mara. Una alerta a pantalla completa si una impresi\xF3n falla, y un aviso para retirar la pieza cuando termina. Klipper (Moonraker: Mainsail, Fluidd), OctoPrint y Bambu Lab en modo LAN, en tu red, sin nube.",
1884
+ "Dein 3D-Drucker auf dem Panel: der laufende Druck mit Modell, Fortschritt, Restzeit und Fertigstellungszeit, Schicht und Temperaturen, und die Webcam. Ein Vollbild-Alarm, wenn ein Druck fehlschl\xE4gt, und eine Erinnerung, das Teil abzunehmen, wenn er fertig ist. Klipper (Moonraker: Mainsail, Fluidd), OctoPrint und Bambu Lab im LAN-Modus, in deinem Netz, ohne Cloud.",
1885
+ "3D \u6253\u5370\u673A\u4E0A\u526F\u5C4F\uFF1A\u6B63\u5728\u8FDB\u884C\u7684\u6253\u5370\uFF0C\u5305\u62EC\u6A21\u578B\u3001\u8FDB\u5EA6\u3001\u5269\u4F59\u65F6\u95F4\u4E0E\u5B8C\u6210\u65F6\u523B\u3001\u5F53\u524D\u5C42\u548C\u6E29\u5EA6\uFF0C\u4EE5\u53CA\u6444\u50CF\u5934\u753B\u9762\u3002\u6253\u5370\u5931\u8D25\u65F6\u5168\u5C4F\u63D0\u9192\uFF0C\u6253\u5370\u5B8C\u6210\u540E\u63D0\u9192\u4F60\u53D6\u4E0B\u6A21\u578B\u3002\u652F\u6301 Klipper\uFF08Moonraker\uFF1AMainsail\u3001Fluidd\uFF09\u3001OctoPrint \u548C\u5C40\u57DF\u7F51\u6A21\u5F0F\u7684 Bambu Lab\uFF0C\u5168\u90E8\u5728\u5C40\u57DF\u7F51\u5185\uFF0C\u4E0D\u7ECF\u8FC7\u4E91\u7AEF\u3002",
1886
+ "3D \u5370\u8868\u6A5F\u4E0A\u9762\u677F\uFF1A\u6B63\u5728\u9032\u884C\u7684\u5217\u5370\uFF0C\u5305\u62EC\u6A21\u578B\u3001\u9032\u5EA6\u3001\u5269\u9918\u6642\u9593\u8207\u5B8C\u6210\u6642\u523B\u3001\u76EE\u524D\u5C64\u6578\u548C\u6EAB\u5EA6\uFF0C\u4EE5\u53CA\u651D\u5F71\u6A5F\u756B\u9762\u3002\u5217\u5370\u5931\u6557\u6642\u5168\u87A2\u5E55\u63D0\u9192\uFF0C\u5217\u5370\u5B8C\u6210\u5F8C\u63D0\u9192\u4F60\u53D6\u4E0B\u6A21\u578B\u3002\u652F\u63F4 Klipper\uFF08Moonraker\uFF1AMainsail\u3001Fluidd\uFF09\u3001OctoPrint \u548C\u5340\u57DF\u7DB2\u8DEF\u6A21\u5F0F\u7684 Bambu Lab\uFF0C\u5168\u90E8\u5728\u5340\u57DF\u7DB2\u8DEF\u5167\uFF0C\u4E0D\u7D93\u904E\u96F2\u7AEF\u3002"
1887
+ ),
1888
+ author: "Loksly",
1889
+ license: "MIT",
1890
+ homepage: "https://github.com/kiosko-lcd/kiosko-plugin-3d-printer#readme",
1891
+ repository: "https://github.com/kiosko-lcd/kiosko-plugin-3d-printer",
1892
+ icon: "printer",
1893
+ sdk: "^0.2.0",
1894
+ platforms: ["linux", "darwin", "win32"],
1895
+ languages: LANGUAGES,
1896
+ permissions: { network: ["user"] },
1897
+ resources: { memoryMb: 30, cpu: "low" },
1898
+ widgets: [job, camera],
1899
+ sources: [statusSource],
1900
+ templates: [
1901
+ {
1902
+ id: "printer",
1903
+ name: L("3D printer", "Impresora 3D", "3D-Drucker", "3D \u6253\u5370\u673A", "3D \u5370\u8868\u6A5F"),
1904
+ icon: "printer",
1905
+ wide: [
1906
+ { x: 0, y: 0, w: 0.62, h: 1, widgets: ["job"] },
1907
+ { x: 0.62, y: 0, w: 0.38, h: 1, widgets: ["camera"], chrome: "bare" }
1908
+ ],
1909
+ square: [
1910
+ { x: 0, y: 0, w: 1, h: 0.55, widgets: ["camera"], chrome: "bare" },
1911
+ { x: 0, y: 0.55, w: 1, h: 0.45, widgets: [["job", { picture: "none" }]] }
1912
+ ],
1913
+ tall: [
1914
+ { x: 0, y: 0, w: 1, h: 0.4, widgets: ["camera"], chrome: "bare" },
1915
+ { x: 0, y: 0.4, w: 1, h: 0.6, widgets: ["job"] }
1916
+ ]
1917
+ }
1918
+ ]
1919
+ });
1920
+ export {
1921
+ camera,
1922
+ index_default as default,
1923
+ job,
1924
+ statusSource
1925
+ };