levix-bot 4.3.1 → 4.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (47) hide show
  1. package/README.md +4 -2
  2. package/package.json +1 -1
  3. package/public/dashboard/assets/index-COI8zgqa.css +2 -0
  4. package/public/dashboard/assets/index-IZMBuNAZ.js +505 -0
  5. package/public/dashboard/index.html +2 -2
  6. package/public/dashboard.css +32 -0
  7. package/scheduler.cjs +66 -7
  8. package/src/bootstrap/panel.js +16 -4
  9. package/src/commands/pack.cjs +159 -0
  10. package/src/commands/packs.cjs +47 -0
  11. package/src/commands/send.cjs +1 -18
  12. package/src/commands/sticker.cjs +77 -232
  13. package/src/commands/stickers.cjs +100 -0
  14. package/src/commands/toimage.cjs +88 -0
  15. package/src/config/defaults.cjs +5 -0
  16. package/src/config/settings.cjs +10 -0
  17. package/src/core/events.js +15 -1
  18. package/src/core/session.js +7 -0
  19. package/src/db/db.cjs +387 -0
  20. package/src/db/store.cjs +746 -24
  21. package/src/handlers/command.handler.js +4 -0
  22. package/src/panel/feedback.cjs +43 -14
  23. package/src/routes/dashboard.api.esm.js +172 -20
  24. package/src/routes/stickers.api.esm.js +570 -0
  25. package/src/services/llmDiscovery.cjs +32 -10
  26. package/src/stickers/errors.cjs +239 -0
  27. package/src/stickers/ffmpeg.cjs +133 -0
  28. package/src/stickers/jobs.cjs +183 -0
  29. package/src/stickers/library.cjs +712 -0
  30. package/src/stickers/limits.cjs +60 -0
  31. package/src/stickers/media.cjs +748 -0
  32. package/src/stickers/options.cjs +128 -0
  33. package/src/stickers/owner.cjs +103 -0
  34. package/src/stickers/studio.cjs +473 -0
  35. package/src/stickers/uploads.cjs +263 -0
  36. package/src/stickers/webp.cjs +231 -0
  37. package/src/stickers/zip.cjs +107 -0
  38. package/src/utils/messageContent.cjs +30 -4
  39. package/src/utils/multipart.esm.js +81 -0
  40. package/src/utils/recurrence.cjs +189 -30
  41. package/src/utils/stickerBot.cjs +84 -0
  42. package/src/utils/storage.cjs +3 -0
  43. package/src/utils/storage.esm.js +3 -0
  44. package/views/login.ejs +39 -3
  45. package/views/setup.ejs +21 -0
  46. package/public/dashboard/assets/index-B6RhYFIy.js +0 -446
  47. package/public/dashboard/assets/index-vEwOcxiH.css +0 -2
@@ -0,0 +1,570 @@
1
+ // Sticker Studio HTTP API. Mounted at /dashboard/api behind the same session
2
+ // check as the rest of the panel. The operator shares the linked account's
3
+ // library (`owner.forPanel()`). Errors are the sticker vocabulary; anything else
4
+ // is logged and answered as INTERNAL, never with the exception text.
5
+ //
6
+ // The upload is not JSON. jsonUnlessStickerUpload skips the dashboard parser
7
+ // for that one path so the route can cap the body while it is still a stream.
8
+
9
+ import { Readable } from "node:stream";
10
+ import { Router } from "express";
11
+ import { createRequire } from "module";
12
+ import normalizeJid from "../utils/normalizeJid.esm.js";
13
+
14
+ const require = createRequire(import.meta.url);
15
+ const logger = require("../utils/logger.cjs");
16
+ const settings = require("../config/settings.cjs");
17
+ const library = require("../stickers/library.cjs");
18
+ const uploads = require("../stickers/uploads.cjs");
19
+ const studioModule = require("../stickers/studio.cjs");
20
+ const owner = require("../stickers/owner.cjs");
21
+ const {
22
+ CODES,
23
+ StickerError,
24
+ httpStatus,
25
+ toResponseBody,
26
+ userMessageIn,
27
+ } = require("../stickers/errors.cjs");
28
+ const {
29
+ CANVAS,
30
+ EXPORT_MAX_IDS,
31
+ MAX_INPUT_SIDE,
32
+ PACKS_MAX_PER_OWNER,
33
+ SEND_MAX_IDS,
34
+ STICKER_MAX_SECONDS,
35
+ UPLOAD_MAX_BYTES,
36
+ VIDEO_MAX_SOURCE_SECONDS,
37
+ } = require("../stickers/limits.cjs");
38
+ const { normalizeOptions } = require("../stickers/options.cjs");
39
+
40
+ const ID_RE = /^[0-9a-f]{16}$/;
41
+ const UPLOAD_ID_RE = /^[0-9a-f]{32}$/;
42
+ const JOB_ID_RE = /^[A-Za-z0-9_-]{1,64}$/;
43
+ const JID_RE = /@(s\.whatsapp\.net|g\.us|lid)$/;
44
+ const SORTS = new Set(["newest", "oldest", "name", "recent"]);
45
+ const FILTERS = new Set(["all", "favorites", "recent", "animated", "static"]);
46
+ const ACTIONS = new Set([
47
+ "favorite",
48
+ "unfavorite",
49
+ "delete",
50
+ "addToPack",
51
+ "moveToPack",
52
+ "removeFromPack",
53
+ "touch",
54
+ ]);
55
+ const PNG_SIG = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]);
56
+ const OVERLAY_MAX_BYTES = 4 * 1024 * 1024;
57
+
58
+ const router = Router();
59
+ let session = null;
60
+ let studioOverride = null;
61
+ let mediaOverride = null;
62
+
63
+ export function setSession(manager) {
64
+ session = manager;
65
+ }
66
+
67
+ export function setStudio(instance) {
68
+ studioOverride = instance || null;
69
+ }
70
+
71
+ export function setMedia(mod) {
72
+ mediaOverride = mod || null;
73
+ uploads.setMedia(mod || null);
74
+ }
75
+
76
+ function studio() {
77
+ return studioOverride || studioModule;
78
+ }
79
+
80
+ function media() {
81
+ return mediaOverride || require("../stickers/media.cjs");
82
+ }
83
+
84
+ function currentSocket() {
85
+ return session?.socket ?? null;
86
+ }
87
+
88
+ function panelOwner() {
89
+ return owner.forPanel();
90
+ }
91
+
92
+ export function jsonUnlessStickerUpload(jsonParser) {
93
+ return (req, res, next) => {
94
+ const urlPath = (req.originalUrl || "").split("?")[0];
95
+ if (req.method === "POST" && urlPath.endsWith("/stickers/uploads")) return next();
96
+ return jsonParser(req, res, next);
97
+ };
98
+ }
99
+
100
+ function asyncRoute(handler) {
101
+ return (req, res) => {
102
+ Promise.resolve(handler(req, res)).catch((error) => {
103
+ if (res.headersSent) return;
104
+ if (!(error instanceof StickerError)) {
105
+ logger.error({ err: error }, `[Stickers] ${req.method} ${req.path} failed`);
106
+ }
107
+ res.status(httpStatus(error)).json(toResponseBody(error));
108
+ if (error instanceof StickerError && error.code === "TOO_LARGE") {
109
+ res.on("finish", () => req.destroy());
110
+ }
111
+ });
112
+ };
113
+ }
114
+
115
+ function asPackError(error) {
116
+ if (error instanceof StickerError && error.code === "NOT_FOUND") {
117
+ throw new StickerError("PACK_NOT_FOUND");
118
+ }
119
+ throw error;
120
+ }
121
+
122
+ function bodyOf(req) {
123
+ const body = req.body;
124
+ if (!body || typeof body !== "object" || Array.isArray(body)) {
125
+ throw new StickerError("INVALID_OPTIONS", { field: "body" });
126
+ }
127
+ return body;
128
+ }
129
+
130
+ function parseIds(value, max, { field = "ids", allowEmpty = false } = {}) {
131
+ if (!Array.isArray(value) || value.length > max || (!allowEmpty && value.length === 0)) {
132
+ throw new StickerError("INVALID_OPTIONS", { field });
133
+ }
134
+ const ids = [];
135
+ const seen = new Set();
136
+ for (const id of value) {
137
+ if (typeof id !== "string" || !ID_RE.test(id) || seen.has(id)) {
138
+ throw new StickerError("INVALID_OPTIONS", { field });
139
+ }
140
+ seen.add(id);
141
+ ids.push(id);
142
+ }
143
+ return ids;
144
+ }
145
+
146
+ function requireStickerId(id) {
147
+ if (typeof id !== "string" || !ID_RE.test(id)) {
148
+ throw new StickerError("INVALID_OPTIONS", { field: "id" });
149
+ }
150
+ return id;
151
+ }
152
+
153
+ function contentDisposition(fileName) {
154
+ const ascii = fileName.replace(/[^\x20-\x7e]/g, "_").replace(/"/g, "");
155
+ return `attachment; filename="${ascii}"; filename*=UTF-8''${encodeURIComponent(fileName)}`;
156
+ }
157
+
158
+ function decodeOverlay(value) {
159
+ if (typeof value !== "string" || !value.startsWith("data:image/png;base64,")) {
160
+ throw new StickerError("INVALID_OPTIONS", { field: "overlay" });
161
+ }
162
+ const buffer = Buffer.from(value.slice("data:image/png;base64,".length), "base64");
163
+ if (
164
+ buffer.length < 24 ||
165
+ buffer.length > OVERLAY_MAX_BYTES ||
166
+ !buffer.subarray(0, 8).equals(PNG_SIG)
167
+ ) {
168
+ throw new StickerError("INVALID_OPTIONS", { field: "overlay" });
169
+ }
170
+ if (buffer.toString("ascii", 12, 16) !== "IHDR") {
171
+ throw new StickerError("INVALID_OPTIONS", { field: "overlay" });
172
+ }
173
+ if (buffer.readUInt32BE(16) !== CANVAS || buffer.readUInt32BE(20) !== CANVAS) {
174
+ throw new StickerError("INVALID_OPTIONS", { field: "overlay" });
175
+ }
176
+ return buffer;
177
+ }
178
+
179
+ function jobErrorBody(error) {
180
+ if (!error) return null;
181
+ const code = CODES[error.code] ? error.code : "CONVERSION_FAILED";
182
+ const details = error.details && typeof error.details === "object" ? error.details : {};
183
+ const wrapped = new StickerError(code, details);
184
+ return { code, message: userMessageIn("en", wrapped), ...details };
185
+ }
186
+
187
+ function intQuery(value, fallback, field, min, max) {
188
+ if (value == null || value === "") return fallback;
189
+ if (typeof value !== "string" || !/^\d+$/.test(value)) {
190
+ throw new StickerError("INVALID_OPTIONS", { field });
191
+ }
192
+ const n = Number(value);
193
+ if (n < min || n > max) throw new StickerError("INVALID_OPTIONS", { field });
194
+ return n;
195
+ }
196
+
197
+ router.get(
198
+ "/stickers/capabilities",
199
+ asyncRoute(async (_req, res) => {
200
+ const caps = await media().capabilities();
201
+ res.json({
202
+ webp: !!caps.webp,
203
+ animated: !!caps.animated,
204
+ gif: !!caps.gif,
205
+ mp4: !!caps.mp4,
206
+ backgroundRemoval: Array.isArray(caps.backgroundRemoval) ? caps.backgroundRemoval : [],
207
+ limits: {
208
+ uploadBytes: UPLOAD_MAX_BYTES,
209
+ videoSeconds: VIDEO_MAX_SOURCE_SECONDS,
210
+ stickerSeconds: STICKER_MAX_SECONDS,
211
+ maxSide: MAX_INPUT_SIDE,
212
+ libraryMax: settings.get("sticker_library_limit"),
213
+ packsMax: PACKS_MAX_PER_OWNER,
214
+ },
215
+ });
216
+ }),
217
+ );
218
+
219
+ router.get(
220
+ "/stickers",
221
+ asyncRoute(async (req, res) => {
222
+ const sort = req.query.sort || "newest";
223
+ const filter = req.query.filter || "all";
224
+ if (typeof sort !== "string" || !SORTS.has(sort)) {
225
+ throw new StickerError("INVALID_OPTIONS", { field: "sort" });
226
+ }
227
+ if (typeof filter !== "string" || !FILTERS.has(filter)) {
228
+ throw new StickerError("INVALID_OPTIONS", { field: "filter" });
229
+ }
230
+ const pack = req.query.pack;
231
+ if (pack != null && pack !== "none" && (typeof pack !== "string" || !ID_RE.test(pack))) {
232
+ throw new StickerError("INVALID_OPTIONS", { field: "pack" });
233
+ }
234
+ const q = req.query.q == null ? "" : String(req.query.q);
235
+ res.json(
236
+ library.listStickers(panelOwner(), {
237
+ q,
238
+ sort,
239
+ filter,
240
+ pack: pack ?? null,
241
+ offset: intQuery(req.query.offset, 0, "offset", 0, 1_000_000),
242
+ limit: intQuery(req.query.limit, 60, "limit", 1, 200),
243
+ }),
244
+ );
245
+ }),
246
+ );
247
+
248
+ router.post(
249
+ "/stickers/uploads",
250
+ asyncRoute(async (req, res) => {
251
+ let filename = "";
252
+ const header = req.get("x-filename");
253
+ if (header) {
254
+ try {
255
+ filename = decodeURIComponent(header);
256
+ } catch {
257
+ filename = header;
258
+ }
259
+ }
260
+ const record = await uploads.acceptStream(panelOwner(), req, { filename, media: media() });
261
+ res.status(201).json(record);
262
+ }),
263
+ );
264
+
265
+ // Re-editing a library sticker in the Android host keeps its bytes on the
266
+ // server instead of uploading the WebView's preview Blob through the bridge.
267
+ router.post(
268
+ "/stickers/:id/uploads",
269
+ asyncRoute(async (req, res) => {
270
+ const id = requireStickerId(req.params.id);
271
+ const who = panelOwner();
272
+ const sticker = library.getSticker(who, id);
273
+ const bytes = library.readStickerFile(who, id);
274
+ const record = await uploads.acceptStream(who, Readable.from(bytes), {
275
+ filename: sticker.name,
276
+ media: media(),
277
+ });
278
+ res.status(201).json(record);
279
+ }),
280
+ );
281
+
282
+ router.post(
283
+ "/stickers/jobs",
284
+ asyncRoute(async (req, res) => {
285
+ const body = bodyOf(req);
286
+ if (typeof body.uploadId !== "string" || !UPLOAD_ID_RE.test(body.uploadId)) {
287
+ throw new StickerError("INVALID_OPTIONS", { field: "uploadId" });
288
+ }
289
+ const options = body.options == null ? undefined : normalizeOptions(body.options);
290
+ const overlay = body.overlay == null ? undefined : decodeOverlay(body.overlay);
291
+ if (body.name != null && typeof body.name !== "string") {
292
+ throw new StickerError("INVALID_OPTIONS", { field: "name" });
293
+ }
294
+ if (body.packId != null && (typeof body.packId !== "string" || !ID_RE.test(body.packId))) {
295
+ throw new StickerError("INVALID_OPTIONS", { field: "packId" });
296
+ }
297
+ const source = body.source ?? "PANEL_UPLOAD";
298
+ if (source !== "PANEL_UPLOAD" && source !== "MEDIA_HUB") {
299
+ throw new StickerError("INVALID_OPTIONS", { field: "source" });
300
+ }
301
+ const { jobId } = studio().createFromUpload({
302
+ owner: panelOwner(),
303
+ uploadId: body.uploadId,
304
+ options,
305
+ overlayPng: overlay,
306
+ source,
307
+ packId: body.packId,
308
+ name: body.name,
309
+ });
310
+ res.status(202).json({ jobId });
311
+ }),
312
+ );
313
+
314
+ router.get(
315
+ "/stickers/jobs/:id",
316
+ asyncRoute(async (req, res) => {
317
+ if (!JOB_ID_RE.test(req.params.id)) throw new StickerError("NOT_FOUND");
318
+ const job = studio().getJob(panelOwner(), req.params.id);
319
+ if (!job) throw new StickerError("NOT_FOUND");
320
+ const result = job.result || null;
321
+ res.json({
322
+ id: job.id,
323
+ state: job.state,
324
+ stage: job.stage ?? null,
325
+ progress: job.progress ?? 0,
326
+ error: jobErrorBody(job.error),
327
+ sticker: result?.sticker ?? null,
328
+ created: result ? result.created : null,
329
+ qualityReduced: result ? !!result.qualityReduced : null,
330
+ });
331
+ }),
332
+ );
333
+
334
+ router.post(
335
+ "/stickers/bulk",
336
+ asyncRoute(async (req, res) => {
337
+ const body = bodyOf(req);
338
+ if (!ACTIONS.has(body.action)) throw new StickerError("INVALID_OPTIONS", { field: "action" });
339
+ if (body.confirm !== undefined && typeof body.confirm !== "boolean") {
340
+ throw new StickerError("INVALID_OPTIONS", { field: "confirm" });
341
+ }
342
+ const ids = parseIds(body.ids, EXPORT_MAX_IDS);
343
+ const who = panelOwner();
344
+ if (body.action === "favorite" || body.action === "unfavorite") {
345
+ res.json(library.setFavorite(who, ids, body.action === "favorite"));
346
+ return;
347
+ }
348
+ if (body.action === "touch") {
349
+ res.json(library.touch(who, ids));
350
+ return;
351
+ }
352
+ if (body.action === "delete") {
353
+ let affected = 0;
354
+ const skipped = [];
355
+ for (const id of ids) {
356
+ try {
357
+ const result = library.deleteStickers(who, [id], { confirm: body.confirm === true });
358
+ affected += result.deleted.length;
359
+ } catch (error) {
360
+ if (
361
+ error instanceof StickerError &&
362
+ (error.code === "IN_USE" || error.code === "NOT_FOUND")
363
+ ) {
364
+ skipped.push({ id, code: error.code });
365
+ continue;
366
+ }
367
+ throw error;
368
+ }
369
+ }
370
+ res.json({ affected, skipped });
371
+ return;
372
+ }
373
+ if (typeof body.packId !== "string" || !ID_RE.test(body.packId)) {
374
+ throw new StickerError("INVALID_OPTIONS", { field: "packId" });
375
+ }
376
+ if (
377
+ body.fromPackId != null &&
378
+ (typeof body.fromPackId !== "string" || !ID_RE.test(body.fromPackId))
379
+ ) {
380
+ throw new StickerError("INVALID_OPTIONS", { field: "fromPackId" });
381
+ }
382
+ try {
383
+ if (body.action === "addToPack") res.json(library.addToPack(who, body.packId, ids));
384
+ else if (body.action === "removeFromPack") {
385
+ res.json(library.removeFromPack(who, body.packId, ids));
386
+ } else {
387
+ res.json(library.moveToPack(who, ids, body.packId, { fromPackId: body.fromPackId }));
388
+ }
389
+ } catch (error) {
390
+ asPackError(error);
391
+ }
392
+ }),
393
+ );
394
+
395
+ router.post(
396
+ "/stickers/export",
397
+ asyncRoute(async (req, res) => {
398
+ const body = bodyOf(req);
399
+ if (body.format !== "webp" && body.format !== "png") {
400
+ throw new StickerError("INVALID_OPTIONS", { field: "format" });
401
+ }
402
+ const ids = parseIds(body.ids, EXPORT_MAX_IDS);
403
+ const archive = await studio().exportZip(panelOwner(), ids, body.format);
404
+ res.set("Content-Type", "application/zip");
405
+ res.set("Content-Disposition", contentDisposition("stickers.zip"));
406
+ res.send(archive);
407
+ }),
408
+ );
409
+
410
+ router.post(
411
+ "/stickers/send",
412
+ asyncRoute(async (req, res) => {
413
+ const body = bodyOf(req);
414
+ const ids = parseIds(body.ids, SEND_MAX_IDS);
415
+ const jid = normalizeJid(typeof body.jid === "string" ? body.jid : "");
416
+ if (!jid || !JID_RE.test(jid)) throw new StickerError("INVALID_OPTIONS", { field: "jid" });
417
+ const sock = currentSocket();
418
+ if (!sock) throw new StickerError("NOT_CONNECTED");
419
+ res.json(await studio().sendStickers(panelOwner(), ids, jid, sock));
420
+ }),
421
+ );
422
+
423
+ router.get(
424
+ "/stickers/:id/file",
425
+ asyncRoute(async (req, res) => {
426
+ const buffer = library.readStickerFile(panelOwner(), requireStickerId(req.params.id));
427
+ // Private, and revalidated on every load. Express still answers a matching
428
+ // If-None-Match with 304, so a reload does not resend the bytes.
429
+ res.set("Cache-Control", "private, no-cache");
430
+ res.set("Content-Type", "image/webp");
431
+ res.send(buffer);
432
+ }),
433
+ );
434
+
435
+ router.get(
436
+ "/stickers/:id/thumb",
437
+ asyncRoute(async (req, res) => {
438
+ const buffer = library.readThumbnail(panelOwner(), requireStickerId(req.params.id));
439
+ res.set("Cache-Control", "private, no-cache");
440
+ res.set("Content-Type", "image/webp");
441
+ res.send(buffer);
442
+ }),
443
+ );
444
+
445
+ router.get(
446
+ "/stickers/:id/export",
447
+ asyncRoute(async (req, res) => {
448
+ const format = req.query.format;
449
+ if (format !== "png" && format !== "webp" && format !== "gif") {
450
+ throw new StickerError("INVALID_OPTIONS", { field: "format" });
451
+ }
452
+ const out = await studio().exportImage(panelOwner(), requireStickerId(req.params.id), format);
453
+ res.set("Content-Type", out.mime);
454
+ res.set("Content-Disposition", contentDisposition(out.fileName));
455
+ if (format === "png" && out.animated) res.set("X-Levix-Animated", "1");
456
+ res.send(out.buffer);
457
+ }),
458
+ );
459
+
460
+ router.patch(
461
+ "/stickers/:id",
462
+ asyncRoute(async (req, res) => {
463
+ const body = bodyOf(req);
464
+ const patch = {};
465
+ if (body.name !== undefined) {
466
+ if (typeof body.name !== "string")
467
+ throw new StickerError("INVALID_OPTIONS", { field: "name" });
468
+ patch.name = body.name;
469
+ }
470
+ if (body.favorite !== undefined) {
471
+ if (typeof body.favorite !== "boolean") {
472
+ throw new StickerError("INVALID_OPTIONS", { field: "favorite" });
473
+ }
474
+ patch.favorite = body.favorite;
475
+ }
476
+ res.json(library.updateSticker(panelOwner(), requireStickerId(req.params.id), patch));
477
+ }),
478
+ );
479
+
480
+ router.delete(
481
+ "/stickers/:id",
482
+ asyncRoute(async (req, res) => {
483
+ const confirm = req.query.confirm === "1";
484
+ res.json(library.deleteStickers(panelOwner(), [requireStickerId(req.params.id)], { confirm }));
485
+ }),
486
+ );
487
+
488
+ router.get(
489
+ "/sticker-packs",
490
+ asyncRoute(async (_req, res) => {
491
+ res.json({ packs: library.listPacks(panelOwner()) });
492
+ }),
493
+ );
494
+
495
+ router.post(
496
+ "/sticker-packs",
497
+ asyncRoute(async (req, res) => {
498
+ const body = bodyOf(req);
499
+ if (typeof body.name !== "string") throw new StickerError("INVALID_NAME");
500
+ res.status(201).json(library.createPack(panelOwner(), body.name));
501
+ }),
502
+ );
503
+
504
+ router.get(
505
+ "/sticker-packs/:id",
506
+ asyncRoute(async (req, res) => {
507
+ try {
508
+ res.json(library.getPack(panelOwner(), requireStickerId(req.params.id)));
509
+ } catch (error) {
510
+ asPackError(error);
511
+ }
512
+ }),
513
+ );
514
+
515
+ router.patch(
516
+ "/sticker-packs/:id",
517
+ asyncRoute(async (req, res) => {
518
+ const body = bodyOf(req);
519
+ if (typeof body.name !== "string") throw new StickerError("INVALID_NAME");
520
+ try {
521
+ res.json(library.updatePack(panelOwner(), requireStickerId(req.params.id), body.name));
522
+ } catch (error) {
523
+ asPackError(error);
524
+ }
525
+ }),
526
+ );
527
+
528
+ router.delete(
529
+ "/sticker-packs/:id",
530
+ asyncRoute(async (req, res) => {
531
+ try {
532
+ res.json(
533
+ library.deletePack(panelOwner(), requireStickerId(req.params.id), {
534
+ deleteStickers: req.query.deleteStickers === "1",
535
+ }),
536
+ );
537
+ } catch (error) {
538
+ asPackError(error);
539
+ }
540
+ }),
541
+ );
542
+
543
+ router.put(
544
+ "/sticker-packs/:id/order",
545
+ asyncRoute(async (req, res) => {
546
+ const ids = parseIds(bodyOf(req).ids, 100_000, { allowEmpty: true });
547
+ try {
548
+ res.json(library.reorderPack(panelOwner(), requireStickerId(req.params.id), ids));
549
+ } catch (error) {
550
+ asPackError(error);
551
+ }
552
+ }),
553
+ );
554
+
555
+ router.post(
556
+ "/sticker-packs/:id/merge",
557
+ asyncRoute(async (req, res) => {
558
+ const intoPackId = bodyOf(req).intoPackId;
559
+ if (typeof intoPackId !== "string" || !ID_RE.test(intoPackId)) {
560
+ throw new StickerError("INVALID_OPTIONS", { field: "intoPackId" });
561
+ }
562
+ try {
563
+ res.json(library.mergePacks(panelOwner(), requireStickerId(req.params.id), intoPackId));
564
+ } catch (error) {
565
+ asPackError(error);
566
+ }
567
+ }),
568
+ );
569
+
570
+ export default router;
@@ -49,11 +49,15 @@ async function requestJson(url, { headers, timeoutMs = REQUEST_TIMEOUT_MS } = {}
49
49
  const controller = new AbortController();
50
50
  const timer = setTimeout(() => controller.abort(), timeoutMs);
51
51
  try {
52
- const resp = await safeProviderFetch(url, {
53
- method: "GET",
54
- headers: { Accept: "application/json", ...headers },
55
- signal: controller.signal,
56
- }, { allowLoopback: true });
52
+ const resp = await safeProviderFetch(
53
+ url,
54
+ {
55
+ method: "GET",
56
+ headers: { Accept: "application/json", ...headers },
57
+ signal: controller.signal,
58
+ },
59
+ { allowLoopback: true },
60
+ );
57
61
  return resp;
58
62
  } catch (err) {
59
63
  if (err && err.name === "AbortError") {
@@ -306,10 +310,9 @@ class GeminiDiscoveryAdapter extends BaseDiscoveryAdapter {
306
310
 
307
311
  async discover({ apiKey, baseUrl = "https://generativelanguage.googleapis.com" }) {
308
312
  const key = this.validateCredentials(apiKey);
309
- const rootUrl = assertProviderBaseUrl(
310
- baseUrl || "https://generativelanguage.googleapis.com",
311
- { allowLoopback: true },
312
- );
313
+ const rootUrl = assertProviderBaseUrl(baseUrl || "https://generativelanguage.googleapis.com", {
314
+ allowLoopback: true,
315
+ });
313
316
 
314
317
  const rawList = [];
315
318
  let pageToken = "";
@@ -386,7 +389,13 @@ async function discoverProviderModels(optionsOrProvider = "gemini", maybeOptions
386
389
  options = optionsOrProvider;
387
390
  }
388
391
 
389
- const { provider = "gemini", apiKey = "", baseUrl = "", refresh = false } = options;
392
+ const {
393
+ provider = "gemini",
394
+ apiKey = "",
395
+ baseUrl = "",
396
+ refresh = false,
397
+ cacheOnly = false,
398
+ } = options;
390
399
  const provKey = String(provider || "gemini").toLowerCase();
391
400
  const adapter = ADAPTERS[provKey];
392
401
 
@@ -430,6 +439,19 @@ async function discoverProviderModels(optionsOrProvider = "gemini", maybeOptions
430
439
  }
431
440
  }
432
441
 
442
+ // Opening the panel must not spend a request on the operator's key: with
443
+ // nothing cached it gets the recommended list, and Refresh goes live.
444
+ if (cacheOnly && !refresh) {
445
+ return {
446
+ success: true,
447
+ live: false,
448
+ requiresApiKey: false,
449
+ fallback: true,
450
+ provider: provKey,
451
+ models: getSeedModels(provKey),
452
+ };
453
+ }
454
+
433
455
  try {
434
456
  const liveModels = await adapter.discover({
435
457
  apiKey: cleanKey,