dsh-ccx 0.0.0-stage → 0.9.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 (80) hide show
  1. package/LICENSE +21 -0
  2. package/NOTICE +23 -0
  3. package/README.md +151 -3
  4. package/assets/icon.svg +27 -0
  5. package/assets/preview-home.png +0 -0
  6. package/assets/preview-market.png +0 -0
  7. package/assets/preview-milkyway.png +0 -0
  8. package/assets/preview-mountain.png +0 -0
  9. package/assets/preview-settings.png +0 -0
  10. package/assets/preview-surface.png +0 -0
  11. package/assets/scene-aurora-ionosphere.png +0 -0
  12. package/assets/scene-black-hole.png +0 -0
  13. package/assets/scene-blinking-squares.png +0 -0
  14. package/assets/scene-cloud-train.png +0 -0
  15. package/assets/scene-glow-horizon.png +0 -0
  16. package/assets/scene-heavenly-cloud.png +0 -0
  17. package/assets/scene-milky-way.png +0 -0
  18. package/assets/scene-mountain.png +0 -0
  19. package/assets/scene-particle-image.png +0 -0
  20. package/assets/scene-pixel-sculpt.png +0 -0
  21. package/cordis.patch.yml +16 -0
  22. package/lib/client.js +1481 -0
  23. package/lib/index.js +779 -0
  24. package/lib/vendor/code-codex/ascii-tiles.js +145 -0
  25. package/lib/vendor/code-codex/aurora-ionosphere.js +442 -0
  26. package/lib/vendor/code-codex/black-hole.js +643 -0
  27. package/lib/vendor/code-codex/blinking-squares.js +401 -0
  28. package/lib/vendor/code-codex/cloud-train.js +627 -0
  29. package/lib/vendor/code-codex/galleries.json +101 -0
  30. package/lib/vendor/code-codex/glow-horizon.js +260 -0
  31. package/lib/vendor/code-codex/heavenly-cloud.js +359 -0
  32. package/lib/vendor/code-codex/milky-way.js +304 -0
  33. package/lib/vendor/code-codex/mountain.js +336 -0
  34. package/lib/vendor/code-codex/particle-image/media/CodeCodex-background-particle-image-image-098c5fbaa5c415ec.png +0 -0
  35. package/lib/vendor/code-codex/particle-image/media/CodeCodex-background-particle-image-image-39894de0da1fa952.png +0 -0
  36. package/lib/vendor/code-codex/particle-image/media/CodeCodex-background-particle-image-image-6447780fc6368ce2.png +0 -0
  37. package/lib/vendor/code-codex/particle-image/media/CodeCodex-background-particle-image-image-746ff537a0eca39e.png +0 -0
  38. package/lib/vendor/code-codex/particle-image/media/CodeCodex-background-particle-image-image-89d064cef83721eb.png +0 -0
  39. package/lib/vendor/code-codex/particle-image/media/CodeCodex-background-particle-image-image-e1c658aa459cfcef.png +0 -0
  40. package/lib/vendor/code-codex/particle-image/media/CodeCodex-background-particle-image-thumbnail-098c5fbaa5c415ec.png +0 -0
  41. package/lib/vendor/code-codex/particle-image/media/CodeCodex-background-particle-image-thumbnail-39894de0da1fa952.png +0 -0
  42. package/lib/vendor/code-codex/particle-image/media/CodeCodex-background-particle-image-thumbnail-6447780fc6368ce2.png +0 -0
  43. package/lib/vendor/code-codex/particle-image/media/CodeCodex-background-particle-image-thumbnail-746ff537a0eca39e.png +0 -0
  44. package/lib/vendor/code-codex/particle-image/media/CodeCodex-background-particle-image-thumbnail-89d064cef83721eb.png +0 -0
  45. package/lib/vendor/code-codex/particle-image/media/CodeCodex-background-particle-image-thumbnail-e1c658aa459cfcef.png +0 -0
  46. package/lib/vendor/code-codex/particle-image.js +1099 -0
  47. package/lib/vendor/code-codex/pixel-sculpt/media/CodeCodex-background-pixel-sculpt-image-079ae375628c240b.png +0 -0
  48. package/lib/vendor/code-codex/pixel-sculpt/media/CodeCodex-background-pixel-sculpt-image-0e0ec1222ff7a1bc.png +0 -0
  49. package/lib/vendor/code-codex/pixel-sculpt/media/CodeCodex-background-pixel-sculpt-image-3fde0595509bc4d5.png +0 -0
  50. package/lib/vendor/code-codex/pixel-sculpt.js +438 -0
  51. package/lib/vendor/code-codex/scene-defaults.json +308 -0
  52. package/lib/vendor/code-codex/scene-schemas.json +2965 -0
  53. package/lib/vendor/code-codex/shallow-ocean-thumbnails.json +12 -0
  54. package/lib/vendor/code-codex/shallow-ocean.js +5094 -0
  55. package/lib/vendor/code-codex/spectral-drape.js +172 -0
  56. package/package.json +70 -6
  57. package/src/client/api.ts +90 -0
  58. package/src/client/background/layer.ts +187 -0
  59. package/src/client/background/pixel-sculpt.ts +167 -0
  60. package/src/client/background/scene-runner.ts +317 -0
  61. package/src/client/background/shallow-ocean.ts +344 -0
  62. package/src/client/background/vendor-loader.ts +297 -0
  63. package/src/client/background/wallpaper.ts +87 -0
  64. package/src/client/index.ts +247 -0
  65. package/src/client/surfaces/corner-patch.ts +100 -0
  66. package/src/client/surfaces/surface-css.ts +155 -0
  67. package/src/client/ui/draft.ts +105 -0
  68. package/src/client/ui/icons.ts +47 -0
  69. package/src/client/ui/panel.ts +1524 -0
  70. package/src/client/ui/shallow-ocean-panel.ts +376 -0
  71. package/src/client/ui/styles.ts +1471 -0
  72. package/src/host/fence.ts +78 -0
  73. package/src/host/index.ts +26 -0
  74. package/src/host/routes.ts +367 -0
  75. package/src/host/storage.ts +109 -0
  76. package/src/host/window-chrome.ts +53 -0
  77. package/src/shared/constants.ts +239 -0
  78. package/src/shared/sanitize.ts +110 -0
  79. package/src/shared/types.ts +145 -0
  80. package/tsconfig.json +16 -0
package/lib/index.js ADDED
@@ -0,0 +1,779 @@
1
+ // Built from src/host/index.ts — do not edit lib/index.js directly.
2
+
3
+
4
+ // src/shared/constants.ts
5
+ var PLUGIN_ID = "dsh-ccx";
6
+ var API_BASE = "/dsh-appearances";
7
+ var SCENES = [
8
+ {
9
+ id: "milky-way",
10
+ label: "\u94F6\u6CB3",
11
+ en: "Milky Way",
12
+ cardTitle: "Milky Way Background",
13
+ icon: "milky-way",
14
+ ext: "",
15
+ layerBg: "#02090d",
16
+ storeKey: "code-codex:milky-way-background:v1"
17
+ },
18
+ {
19
+ id: "glow-horizon",
20
+ label: "\u8F89\u5149\u5730\u5E73\u7EBF",
21
+ en: "Glow Horizon",
22
+ cardTitle: "Glow Horizon Background",
23
+ icon: "glow-horizon",
24
+ ext: "ext-glowhorizon",
25
+ layerBg: "#050507",
26
+ storeKey: "code-codex:glow-horizon-background:v1"
27
+ },
28
+ {
29
+ id: "mountain",
30
+ label: "\u5C42\u5CE6",
31
+ en: "Layered Mountain",
32
+ cardTitle: "Layered Mountain Background",
33
+ icon: "mountain",
34
+ ext: "",
35
+ layerBg: "#02090d",
36
+ storeKey: "code-codex:mountain-settings:v1"
37
+ },
38
+ {
39
+ id: "heavenly-cloud",
40
+ label: "\u4E91\u7A79",
41
+ en: "Heavenly Cloud",
42
+ cardTitle: "Heavenly Cloud Background",
43
+ icon: "heavenly-cloud",
44
+ ext: "ext-heavenlycloud",
45
+ layerBg: "#020408",
46
+ storeKey: "code-codex:heavenly-cloud-background:v1"
47
+ },
48
+ {
49
+ id: "aurora-ionosphere",
50
+ label: "\u6781\u5149\u7535\u79BB\u5C42",
51
+ en: "Aurora Ionosphere",
52
+ cardTitle: "Aurora Ionosphere Background",
53
+ icon: "aurora-ionosphere",
54
+ ext: "",
55
+ layerBg: "#02090d",
56
+ storeKey: "code-codex:aurora-ionosphere-background:v1"
57
+ },
58
+ {
59
+ id: "black-hole",
60
+ label: "\u9ED1\u6D1E",
61
+ en: "Black Hole",
62
+ cardTitle: "Black Hole Background",
63
+ icon: "black-hole",
64
+ ext: "ext-blackhole",
65
+ layerBg: "#000000",
66
+ storeKey: "code-codex:black-hole-background:v1"
67
+ },
68
+ {
69
+ id: "cloud-train",
70
+ label: "\u4E91\u5217\u8F66",
71
+ en: "Cloud Train",
72
+ cardTitle: "Cloud Train Background",
73
+ icon: "cloud-train",
74
+ ext: "",
75
+ layerBg: "#02090d",
76
+ storeKey: "code-codex:cloud-train-settings:v1"
77
+ },
78
+ {
79
+ id: "particle-image",
80
+ label: "\u7C92\u5B50\u6210\u50CF",
81
+ en: "Particle Image",
82
+ cardTitle: "Particle Image Background",
83
+ icon: "particle-image",
84
+ ext: "ext-particle",
85
+ layerBg: "#000000",
86
+ bgColorKey: "backgroundColor",
87
+ storeKey: "code-codex:particle-image-background:v1"
88
+ },
89
+ {
90
+ id: "pixel-sculpt",
91
+ label: "\u50CF\u7D20\u96D5\u5851",
92
+ en: "Pixel Sculpt",
93
+ cardTitle: "Pixel Sculpt Background",
94
+ icon: "pixel-sculpt",
95
+ ext: "",
96
+ layerBg: "#02090d",
97
+ storeKey: "code-codex:pixel-sculpt-settings:v1"
98
+ },
99
+ {
100
+ id: "blinking-squares",
101
+ label: "\u95EA\u70C1\u65B9\u5757",
102
+ en: "Blinking Squares",
103
+ cardTitle: "Blinking Squares Background",
104
+ icon: "blinking-squares",
105
+ ext: "",
106
+ layerBg: "#000000",
107
+ bgColorKey: "backgroundColor",
108
+ storeKey: "code-codex:blinking-squares-background:v1"
109
+ },
110
+ {
111
+ id: "ascii-tiles",
112
+ label: "ASCII \u5B57\u7B26\u7816\u5757",
113
+ en: "ASCII Tiles",
114
+ cardTitle: "ASCII Tiles Background",
115
+ icon: "ascii-tiles",
116
+ ext: "ext-asciitiles",
117
+ layerBg: "#000000",
118
+ bgColorKey: "backgroundColor",
119
+ storeKey: "code-codex:ascii-tiles-background:v1"
120
+ },
121
+ {
122
+ id: "shallow-ocean",
123
+ label: "\u6D45\u6D77\u6765\u4FE1",
124
+ en: "Shallow Ocean Letters",
125
+ cardTitle: "Shallow Ocean Letters Background",
126
+ icon: "shallow-ocean",
127
+ ext: "ext-shallowocean",
128
+ layerBg: "#181818",
129
+ storeKey: "code-codex:shallow-ocean-background:v1"
130
+ },
131
+ {
132
+ id: "spectral-drape",
133
+ label: "\u5149\u8C31\u70B9\u9635\u5E37\u5E55",
134
+ en: "Spectral Drape",
135
+ cardTitle: "Spectral Drape Background",
136
+ icon: "spectral-drape",
137
+ ext: "ext-spectraldrape",
138
+ layerBg: "#0a0a0a",
139
+ bgColorKey: "backgroundColor",
140
+ storeKey: "code-codex:spectral-drape-background:v1"
141
+ }
142
+ ];
143
+ var SCENE_IDS = SCENES.map((s) => s.id);
144
+ var SCENE_META_MAP = Object.fromEntries(
145
+ SCENES.map((s) => [s.id, s])
146
+ );
147
+ var STORE_KEYS = Object.fromEntries(
148
+ SCENES.map((s) => [s.id, s.storeKey])
149
+ );
150
+ var SCENE_LAYER_BG = Object.fromEntries(
151
+ SCENES.map((s) => [s.id, s.layerBg])
152
+ );
153
+ var SURFACE_REGIONS = [
154
+ "sidebar",
155
+ "conversation",
156
+ "composer",
157
+ "right"
158
+ ];
159
+ var DEFAULT_SETTINGS = Object.freeze({
160
+ version: 6,
161
+ enabled: true,
162
+ mode: "scene",
163
+ scene: "milky-way",
164
+ wallpaperId: null,
165
+ wallpaperFit: "cover",
166
+ wallpaperPosition: "center",
167
+ surfaces: Object.freeze({
168
+ enabled: true,
169
+ sidebar: 66,
170
+ conversation: 58,
171
+ composer: 86,
172
+ right: 66
173
+ }),
174
+ sceneParams: {},
175
+ dim: 0,
176
+ blur: 0,
177
+ savedAt: 0
178
+ });
179
+ var CLAMPS = {
180
+ dim: [0, 0.8],
181
+ blur: [0, 20]
182
+ };
183
+ var MEDIA_FILE_RE = /^CodeCodex-background-(particle-image|pixel-sculpt)-(image|thumbnail)-[0-9a-f]{16}\.png$/;
184
+ var WALLPAPER_MIMES = {
185
+ ".png": "image/png",
186
+ ".jpg": "image/jpeg",
187
+ ".jpeg": "image/jpeg",
188
+ ".webp": "image/webp",
189
+ ".gif": "image/gif",
190
+ ".bmp": "image/bmp",
191
+ ".avif": "image/avif",
192
+ ".mp4": "video/mp4",
193
+ ".webm": "video/webm",
194
+ ".mov": "video/quicktime"
195
+ };
196
+ var WALLPAPER_MAX_BYTES = 200 * 1024 * 1024;
197
+
198
+ // src/shared/sanitize.ts
199
+ function clamp(value, min, max) {
200
+ return Math.min(max, Math.max(min, value));
201
+ }
202
+ function sanitizeSurfaces(input) {
203
+ const src = input && typeof input === "object" ? input : {};
204
+ const out = { ...DEFAULT_SETTINGS.surfaces };
205
+ out.enabled = src.enabled === true;
206
+ for (const key of SURFACE_REGIONS) {
207
+ const n = Number(src[key]);
208
+ if (Number.isFinite(n)) out[key] = Math.round(clamp(n, 0, 100));
209
+ }
210
+ return out;
211
+ }
212
+ function sanitizeSettings(input) {
213
+ const src = input && typeof input === "object" ? input : {};
214
+ const out = {
215
+ ...DEFAULT_SETTINGS,
216
+ surfaces: { ...DEFAULT_SETTINGS.surfaces },
217
+ sceneParams: {}
218
+ };
219
+ if (typeof src.enabled === "boolean") out.enabled = src.enabled;
220
+ if (src.mode === "scene" || src.mode === "wallpaper" || src.mode === "off") out.mode = src.mode;
221
+ if (typeof src.scene === "string" && SCENE_IDS.includes(src.scene)) out.scene = src.scene;
222
+ if (typeof src.wallpaperId === "string" && /^[\w-]+$/.test(src.wallpaperId)) {
223
+ out.wallpaperId = src.wallpaperId;
224
+ } else if (src.wallpaperId === null) {
225
+ out.wallpaperId = null;
226
+ }
227
+ if (src.wallpaperFit === "cover" || src.wallpaperFit === "contain" || src.wallpaperFit === "tile") {
228
+ out.wallpaperFit = src.wallpaperFit;
229
+ }
230
+ if (src.wallpaperPosition === "center" || src.wallpaperPosition === "top" || src.wallpaperPosition === "bottom" || src.wallpaperPosition === "left" || src.wallpaperPosition === "right") {
231
+ out.wallpaperPosition = src.wallpaperPosition;
232
+ }
233
+ for (const key of Object.keys(CLAMPS)) {
234
+ const n = Number(src[key]);
235
+ if (Number.isFinite(n)) out[key] = clamp(n, CLAMPS[key][0], CLAMPS[key][1]);
236
+ }
237
+ let surfacesSrc = src.surfaces;
238
+ if (!surfacesSrc && Number.isFinite(Number(src.surfaceOpacity))) {
239
+ const legacy = Math.round(clamp(Number(src.surfaceOpacity), 0.05, 1) * 100);
240
+ surfacesSrc = {
241
+ enabled: true,
242
+ sidebar: legacy,
243
+ conversation: legacy,
244
+ composer: Math.min(100, legacy + 20),
245
+ right: legacy
246
+ };
247
+ }
248
+ const paramsSrc = src.sceneParams && typeof src.sceneParams === "object" ? src.sceneParams : {};
249
+ const paramsOut = {};
250
+ for (const key of Object.keys(paramsSrc)) {
251
+ if (!/^[a-z-]+$/.test(key)) continue;
252
+ const val = paramsSrc[key];
253
+ if (val && typeof val === "object" && !Array.isArray(val)) {
254
+ paramsOut[key] = { ...val };
255
+ }
256
+ }
257
+ out.sceneParams = paramsOut;
258
+ out.surfaces = sanitizeSurfaces(surfacesSrc);
259
+ if (Number(src.version) < 6 && out.surfaces.composer === 58) {
260
+ out.surfaces.composer = 86;
261
+ }
262
+ if (Number.isFinite(Number(src.savedAt))) {
263
+ out.savedAt = Number(src.savedAt);
264
+ }
265
+ return out;
266
+ }
267
+
268
+ // src/host/routes.ts
269
+ import fs2 from "node:fs";
270
+ import fsp2 from "node:fs/promises";
271
+ import path2 from "node:path";
272
+ import { fileURLToPath } from "node:url";
273
+
274
+ // src/host/fence.ts
275
+ function isLoopbackHostname(hn) {
276
+ const h = String(hn || "").toLowerCase().replace(/^\[/, "").replace(/\]$/, "");
277
+ if (!h) return false;
278
+ if (h === "localhost" || h.endsWith(".localhost")) return true;
279
+ if (h === "::1") return true;
280
+ const m = /^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/.exec(h);
281
+ if (!m) return false;
282
+ if (Number(m[1]) !== 127) return false;
283
+ return [m[2], m[3], m[4]].every((x) => Number(x) <= 255);
284
+ }
285
+ function getConnectionFence(ctx) {
286
+ try {
287
+ const conn = (typeof ctx.get === "function" ? ctx.get("connection") : null) || ctx.connection;
288
+ if (conn && typeof conn === "object" && "requestRejection" in conn && typeof conn.requestRejection === "function") {
289
+ return conn;
290
+ }
291
+ return null;
292
+ } catch {
293
+ return null;
294
+ }
295
+ }
296
+ function selfRejection(req, ctx) {
297
+ try {
298
+ const headers = req?.headers || {};
299
+ let hostUrl;
300
+ try {
301
+ hostUrl = new URL(`http://${String(headers.host || "")}`);
302
+ } catch {
303
+ return 403;
304
+ }
305
+ const fence = getConnectionFence(ctx);
306
+ if (fence) {
307
+ const delegated = fence.requestRejection(req);
308
+ if (delegated) return delegated;
309
+ } else if (!isLoopbackHostname(hostUrl.hostname)) {
310
+ return 403;
311
+ }
312
+ const site = String(headers["sec-fetch-site"] || "").toLowerCase();
313
+ if (site === "cross-site") return 403;
314
+ const origin = headers.origin;
315
+ if (typeof origin === "string" && origin && origin !== "null") {
316
+ let originUrl;
317
+ try {
318
+ originUrl = new URL(origin);
319
+ } catch {
320
+ return 403;
321
+ }
322
+ if (originUrl.host.toLowerCase() !== hostUrl.host.toLowerCase()) return 403;
323
+ }
324
+ return null;
325
+ } catch {
326
+ return 403;
327
+ }
328
+ }
329
+
330
+ // src/host/storage.ts
331
+ import crypto from "node:crypto";
332
+ import fs from "node:fs";
333
+ import fsp from "node:fs/promises";
334
+ import os from "node:os";
335
+ import path from "node:path";
336
+ function dshHome() {
337
+ return process.env.DSH_HOME || path.join(os.homedir(), ".dsh");
338
+ }
339
+ function dataDir() {
340
+ return path.join(dshHome(), "appearances");
341
+ }
342
+ function wallpapersDir() {
343
+ return path.join(dataDir(), "wallpapers");
344
+ }
345
+ function settingsPath() {
346
+ return path.join(dataDir(), "settings.json");
347
+ }
348
+ function wallpaperUrl(id) {
349
+ return `${API_BASE}/wallpaper?id=${encodeURIComponent(id)}`;
350
+ }
351
+ function cloneDefaultSettings() {
352
+ return {
353
+ ...DEFAULT_SETTINGS,
354
+ surfaces: { ...DEFAULT_SETTINGS.surfaces },
355
+ sceneParams: {}
356
+ };
357
+ }
358
+ function readSettings() {
359
+ try {
360
+ return sanitizeSettings(JSON.parse(fs.readFileSync(settingsPath(), "utf8")));
361
+ } catch {
362
+ return cloneDefaultSettings();
363
+ }
364
+ }
365
+ function writeSettings(value) {
366
+ fs.mkdirSync(dataDir(), { recursive: true });
367
+ const target = settingsPath();
368
+ const tmp = `${target}.tmp-${process.pid}-${Date.now()}`;
369
+ fs.writeFileSync(tmp, JSON.stringify(value, null, 2));
370
+ fs.renameSync(tmp, target);
371
+ }
372
+ function listWallpapers() {
373
+ const dir = wallpapersDir();
374
+ let entries;
375
+ try {
376
+ entries = fs.readdirSync(dir);
377
+ } catch {
378
+ return [];
379
+ }
380
+ const items = [];
381
+ for (const name of entries) {
382
+ const ext = path.extname(name).toLowerCase();
383
+ const mime = WALLPAPER_MIMES[ext];
384
+ if (!mime) continue;
385
+ const id = name.slice(0, name.length - ext.length);
386
+ try {
387
+ const st = fs.statSync(path.join(dir, name));
388
+ if (!st.isFile()) continue;
389
+ items.push({ id, name, mime, size: st.size, mtimeMs: st.mtimeMs, url: wallpaperUrl(id) });
390
+ } catch {
391
+ }
392
+ }
393
+ items.sort((a, b) => (b.mtimeMs ?? 0) - (a.mtimeMs ?? 0));
394
+ return items;
395
+ }
396
+ async function saveWallpaperBytes(ext, bytes) {
397
+ const dir = wallpapersDir();
398
+ await fsp.mkdir(dir, { recursive: true });
399
+ const id = crypto.randomBytes(8).toString("hex");
400
+ const name = id + ext;
401
+ const file = path.join(dir, name);
402
+ const tmp = `${file}.tmp-${process.pid}-${Date.now()}`;
403
+ await fsp.writeFile(tmp, bytes);
404
+ await fsp.rename(tmp, file);
405
+ return {
406
+ id,
407
+ name,
408
+ mime: WALLPAPER_MIMES[ext],
409
+ size: bytes.length,
410
+ url: wallpaperUrl(id)
411
+ };
412
+ }
413
+ async function deleteWallpaperById(id) {
414
+ const item = listWallpapers().find((w) => w.id === id);
415
+ if (!item) return;
416
+ await fsp.rm(path.join(wallpapersDir(), item.name), { force: true });
417
+ }
418
+ async function clearAllWallpapers() {
419
+ const items = listWallpapers();
420
+ await Promise.all(
421
+ items.map((w) => fsp.rm(path.join(wallpapersDir(), w.name), { force: true }))
422
+ );
423
+ }
424
+
425
+ // src/host/window-chrome.ts
426
+ import { createRequire } from "node:module";
427
+ var require2 = createRequire(import.meta.url);
428
+ function withWindows(fn) {
429
+ try {
430
+ const electron = require2("electron");
431
+ const windows = electron?.BrowserWindow ? electron.BrowserWindow.getAllWindows() : [];
432
+ for (const win of windows) {
433
+ try {
434
+ fn(win);
435
+ } catch {
436
+ }
437
+ }
438
+ } catch {
439
+ }
440
+ }
441
+ function hideNativeMenuBar() {
442
+ withWindows((win) => {
443
+ if (typeof win.setAutoHideMenuBar === "function") win.setAutoHideMenuBar(true);
444
+ if (typeof win.setMenuBarVisibility === "function") win.setMenuBarVisibility(false);
445
+ });
446
+ }
447
+ function menuBarDebugInfo() {
448
+ let out = { error: "no-window", platform: process.platform };
449
+ withWindows((win) => {
450
+ out = {
451
+ platform: process.platform,
452
+ menuBarVisible: typeof win.isMenuBarVisible === "function" ? win.isMenuBarVisible() : null,
453
+ menuBarAutoHide: typeof win.isMenuBarAutoHide === "function" ? win.isMenuBarAutoHide() : null,
454
+ bounds: typeof win.getBounds === "function" ? win.getBounds() : null,
455
+ contentBounds: typeof win.getContentBounds === "function" ? win.getContentBounds() : null
456
+ };
457
+ });
458
+ return out;
459
+ }
460
+
461
+ // src/host/routes.ts
462
+ function sendJson(res, status, payload) {
463
+ const body = JSON.stringify(payload);
464
+ res.writeHead(status, {
465
+ "Content-Type": "application/json; charset=utf-8",
466
+ "Cache-Control": "no-store",
467
+ "Content-Length": String(Buffer.byteLength(body))
468
+ });
469
+ res.end(body);
470
+ }
471
+ function readBody(req, maxBytes) {
472
+ return new Promise((resolve, reject) => {
473
+ const chunks = [];
474
+ let total = 0;
475
+ let done = false;
476
+ req.on("data", (chunk) => {
477
+ if (done) return;
478
+ total += chunk.length;
479
+ if (total > maxBytes) {
480
+ done = true;
481
+ reject(new Error("payload too large"));
482
+ req.destroy?.();
483
+ return;
484
+ }
485
+ chunks.push(chunk);
486
+ });
487
+ req.on("end", () => {
488
+ if (!done) resolve(Buffer.concat(chunks));
489
+ });
490
+ req.on("error", (err) => {
491
+ if (!done) reject(err);
492
+ });
493
+ });
494
+ }
495
+ function resolveVendorDir() {
496
+ const here = path2.dirname(fileURLToPath(import.meta.url));
497
+ const direct = path2.join(here, "vendor", "code-codex");
498
+ if (fs2.existsSync(direct)) return direct;
499
+ return path2.resolve(here, "../../lib/vendor/code-codex");
500
+ }
501
+ function parseByteRange(rangeHeader, size) {
502
+ if (!rangeHeader) return null;
503
+ const m = /^bytes=(\d*)-(\d*)$/i.exec(rangeHeader.trim());
504
+ if (!m) return "invalid";
505
+ const rawStart = m[1];
506
+ const rawEnd = m[2];
507
+ if (rawStart === "" && rawEnd === "") return "invalid";
508
+ let start;
509
+ let end;
510
+ if (rawStart === "") {
511
+ const suffixLen = Number(rawEnd);
512
+ if (!Number.isFinite(suffixLen) || suffixLen <= 0) return "invalid";
513
+ start = Math.max(0, size - suffixLen);
514
+ end = size - 1;
515
+ } else {
516
+ start = Number(rawStart);
517
+ end = rawEnd === "" ? size - 1 : Math.min(size - 1, Number(rawEnd));
518
+ if (!Number.isFinite(start) || !Number.isFinite(end) || start < 0 || start > end || start >= size) {
519
+ return "invalid";
520
+ }
521
+ }
522
+ return { start, end };
523
+ }
524
+ async function sendFileRangeAware(req, res, filePath, mime) {
525
+ const st = await fsp2.stat(filePath);
526
+ const size = st.size;
527
+ const range = parseByteRange(req.headers?.range, size);
528
+ if (range === "invalid") {
529
+ res.writeHead(416, { "Content-Range": `bytes */${size}`, "Content-Length": "0" });
530
+ res.end();
531
+ return;
532
+ }
533
+ const canPipe = typeof res.write === "function" && typeof res.on === "function";
534
+ if (range) {
535
+ const len = range.end - range.start + 1;
536
+ res.writeHead(206, {
537
+ "Content-Type": mime,
538
+ "Accept-Ranges": "bytes",
539
+ "Content-Range": `bytes ${range.start}-${range.end}/${size}`,
540
+ "Content-Length": String(len),
541
+ "Cache-Control": "no-store"
542
+ });
543
+ if (canPipe) {
544
+ fs2.createReadStream(filePath, { start: range.start, end: range.end }).pipe(res);
545
+ } else {
546
+ const fh = await fsp2.open(filePath, "r");
547
+ try {
548
+ const buf = Buffer.allocUnsafe(len);
549
+ await fh.read(buf, 0, len, range.start);
550
+ res.end(buf);
551
+ } finally {
552
+ await fh.close();
553
+ }
554
+ }
555
+ return;
556
+ }
557
+ res.writeHead(200, {
558
+ "Content-Type": mime,
559
+ "Accept-Ranges": "bytes",
560
+ "Content-Length": String(size),
561
+ "Cache-Control": "no-store"
562
+ });
563
+ if (canPipe) {
564
+ fs2.createReadStream(filePath).pipe(res);
565
+ } else {
566
+ res.end(await fsp2.readFile(filePath));
567
+ }
568
+ }
569
+ function registerAppearanceRoutes(ctx) {
570
+ const disposers = [];
571
+ const vendorDir = resolveVendorDir();
572
+ function registerRoute(route) {
573
+ const inner = route.handler;
574
+ disposers.push(
575
+ ctx.webServer.register({
576
+ kind: route.kind,
577
+ path: route.path,
578
+ handler: async (req, res) => {
579
+ const code = selfRejection(req, ctx);
580
+ if (code) {
581
+ sendJson(res, code, { ok: false, error: "rejected by trust fence" });
582
+ return;
583
+ }
584
+ return inner(req, res);
585
+ }
586
+ })
587
+ );
588
+ }
589
+ const serveVendorFile = (file, contentType) => async (_req, res) => {
590
+ try {
591
+ const bytes = await fsp2.readFile(path2.join(vendorDir, file));
592
+ res.writeHead(200, {
593
+ "Content-Type": contentType,
594
+ "Cache-Control": "no-store",
595
+ "Content-Length": String(bytes.length)
596
+ });
597
+ res.end(bytes);
598
+ } catch (err) {
599
+ const msg = err instanceof Error ? err.message : String(err);
600
+ sendJson(res, 404, { ok: false, error: msg.slice(0, 120) });
601
+ }
602
+ };
603
+ registerRoute({
604
+ kind: "exact",
605
+ path: `${API_BASE}/wininfo.json`,
606
+ handler: (_req, res) => sendJson(res, 200, { ok: true, win: menuBarDebugInfo() })
607
+ });
608
+ for (const sceneId of SCENE_IDS) {
609
+ registerRoute({
610
+ kind: "exact",
611
+ path: `${API_BASE}/vendor/${sceneId}.js`,
612
+ handler: serveVendorFile(`${sceneId}.js`, "text/javascript; charset=utf-8")
613
+ });
614
+ }
615
+ registerRoute({
616
+ kind: "exact",
617
+ path: `${API_BASE}/vendor-galleries.json`,
618
+ handler: serveVendorFile("galleries.json", "application/json; charset=utf-8")
619
+ });
620
+ registerRoute({
621
+ kind: "exact",
622
+ path: `${API_BASE}/vendor-shallow-ocean-thumbs.json`,
623
+ handler: serveVendorFile("shallow-ocean-thumbnails.json", "application/json; charset=utf-8")
624
+ });
625
+ registerRoute({
626
+ kind: "exact",
627
+ path: `${API_BASE}/vendor-media`,
628
+ handler: async (req, res) => {
629
+ try {
630
+ const u = new URL(req.url || "/", "http://localhost");
631
+ const name = u.searchParams.get("file") || "";
632
+ const match = MEDIA_FILE_RE.exec(name);
633
+ if (!match) throw new Error("bad media file");
634
+ const bytes = await fsp2.readFile(path2.join(vendorDir, match[1], "media", name));
635
+ res.writeHead(200, {
636
+ "Content-Type": "image/png",
637
+ "Cache-Control": "no-store",
638
+ "Content-Length": String(bytes.length)
639
+ });
640
+ res.end(bytes);
641
+ } catch (err) {
642
+ const msg = err instanceof Error ? err.message : String(err);
643
+ sendJson(res, 404, { ok: false, error: msg.slice(0, 120) });
644
+ }
645
+ }
646
+ });
647
+ registerRoute({
648
+ kind: "exact",
649
+ path: `${API_BASE}/scene-schemas.json`,
650
+ handler: serveVendorFile("scene-schemas.json", "application/json; charset=utf-8")
651
+ });
652
+ registerRoute({
653
+ kind: "exact",
654
+ path: `${API_BASE}/state.json`,
655
+ handler: (_req, res) => {
656
+ const settings = readSettings();
657
+ const wallpapers = listWallpapers();
658
+ sendJson(res, 200, {
659
+ ok: true,
660
+ settings,
661
+ defaults: DEFAULT_SETTINGS,
662
+ scenes: SCENE_IDS,
663
+ wallpapers
664
+ });
665
+ }
666
+ });
667
+ registerRoute({
668
+ kind: "exact",
669
+ path: `${API_BASE}/state-save.json`,
670
+ handler: async (req, res) => {
671
+ try {
672
+ const raw = await readBody(req, 64 * 1024);
673
+ const parsed = JSON.parse(raw.toString("utf8"));
674
+ const settings = sanitizeSettings(parsed?.settings ?? parsed);
675
+ settings.savedAt = Date.now();
676
+ writeSettings(settings);
677
+ sendJson(res, 200, { ok: true, settings });
678
+ } catch (err) {
679
+ const msg = err instanceof Error ? err.message : String(err);
680
+ sendJson(res, 400, { ok: false, error: msg.slice(0, 200) });
681
+ }
682
+ }
683
+ });
684
+ registerRoute({
685
+ kind: "exact",
686
+ path: `${API_BASE}/wallpaper-upload`,
687
+ handler: async (req, res) => {
688
+ try {
689
+ if (req.method !== "POST") throw new Error("method not allowed");
690
+ const u = new URL(req.url || "/", "http://localhost");
691
+ const rawName = String(u.searchParams.get("name") || "");
692
+ const ext = path2.extname(rawName).toLowerCase();
693
+ if (!WALLPAPER_MIMES[ext]) throw new Error(`unsupported file type: ${ext || "(none)"}`);
694
+ const bytes = await readBody(req, WALLPAPER_MAX_BYTES);
695
+ if (!bytes.length) throw new Error("empty body");
696
+ const item = await saveWallpaperBytes(ext, bytes);
697
+ sendJson(res, 200, {
698
+ ok: true,
699
+ wallpaper: item,
700
+ wallpapers: listWallpapers()
701
+ });
702
+ } catch (err) {
703
+ const msg = err instanceof Error ? err.message : String(err);
704
+ sendJson(res, 400, { ok: false, error: msg.slice(0, 200) });
705
+ }
706
+ }
707
+ });
708
+ registerRoute({
709
+ kind: "exact",
710
+ path: `${API_BASE}/wallpaper-delete.json`,
711
+ handler: async (req, res) => {
712
+ try {
713
+ const raw = await readBody(req, 4 * 1024);
714
+ const parsed = JSON.parse(raw.toString("utf8"));
715
+ const id = String(parsed?.id ?? "");
716
+ if (!/^[\w-]+$/.test(id)) throw new Error("bad wallpaper id");
717
+ await deleteWallpaperById(id);
718
+ sendJson(res, 200, { ok: true, wallpapers: listWallpapers() });
719
+ } catch (err) {
720
+ const msg = err instanceof Error ? err.message : String(err);
721
+ sendJson(res, 400, { ok: false, error: msg.slice(0, 200) });
722
+ }
723
+ }
724
+ });
725
+ registerRoute({
726
+ kind: "exact",
727
+ path: `${API_BASE}/wallpaper-clear.json`,
728
+ handler: async (_req, res) => {
729
+ try {
730
+ await clearAllWallpapers();
731
+ sendJson(res, 200, { ok: true, wallpapers: [] });
732
+ } catch (err) {
733
+ const msg = err instanceof Error ? err.message : String(err);
734
+ sendJson(res, 400, { ok: false, error: msg.slice(0, 200) });
735
+ }
736
+ }
737
+ });
738
+ const serveWallpaper = async (req, res) => {
739
+ try {
740
+ const u = new URL(req.url || "/", "http://localhost");
741
+ const id = String(u.searchParams.get("id") || "");
742
+ if (!/^[\w-]+$/.test(id)) throw new Error("bad wallpaper id");
743
+ const item = listWallpapers().find((w) => w.id === id);
744
+ if (!item) throw new Error("wallpaper not found");
745
+ await sendFileRangeAware(req, res, path2.join(wallpapersDir(), item.name), item.mime);
746
+ } catch (err) {
747
+ const msg = err instanceof Error ? err.message : String(err);
748
+ sendJson(res, 404, { ok: false, error: msg.slice(0, 200) });
749
+ }
750
+ };
751
+ registerRoute({ kind: "exact", path: `${API_BASE}/wallpaper`, handler: serveWallpaper });
752
+ registerRoute({ kind: "exact", path: `${API_BASE}/wallpaper.png`, handler: serveWallpaper });
753
+ return () => {
754
+ for (const d of disposers) {
755
+ try {
756
+ d();
757
+ } catch {
758
+ }
759
+ }
760
+ };
761
+ }
762
+
763
+ // src/host/index.ts
764
+ var index_default = {
765
+ name: PLUGIN_ID,
766
+ apply(root) {
767
+ hideNativeMenuBar();
768
+ root.inject(["webServer"], (ctx) => {
769
+ const dispose = registerAppearanceRoutes(ctx);
770
+ root.effect(() => dispose, `${PLUGIN_ID}: routes`);
771
+ });
772
+ }
773
+ };
774
+ export {
775
+ DEFAULT_SETTINGS,
776
+ index_default as default,
777
+ sanitizeSettings,
778
+ sanitizeSurfaces
779
+ };