@cossackframework/desktop 0.8.2 → 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.
package/README.md CHANGED
@@ -5,31 +5,75 @@ the renderer and local Cossack SSR/RPC over the private `cossack://app` origin,
5
5
  injecting `ASSETS` and a window-scoped `COSSACK_DESKTOP` shell into request
6
6
  bindings.
7
7
 
8
+ The generated `src/desktop/index.ts` exports its application and bootstrap so
9
+ `desktop:dev` can load server modules through Vite inside Electron:
10
+
8
11
  ```ts
9
- import { createDesktopApp } from '@cossackframework/desktop';
12
+ import { app, createDesktopApp, electronRuntimeAdapter } from '@cossackframework/desktop';
13
+ import { createApp } from '@cossackframework/framework/router';
14
+ import { fileURLToPath } from 'node:url';
15
+ import { App } from '../App';
16
+ import { template } from '../root';
17
+
18
+ export const env = { ...process.env };
19
+ export const frameworkApp = createApp({
20
+ AppComponent: App,
21
+ htmlTemplate: template,
22
+ runtimeAdapter: electronRuntimeAdapter,
23
+ });
10
24
 
11
- async function main() {
12
- await createDesktopApp({
25
+ export async function startDesktop(createApplication = createDesktopApp) {
26
+ const desktop = await createApplication({
13
27
  identifier: 'dev.cossack.my-app',
14
28
  productName: 'My App',
15
- assetsRoot: new URL('../../client/', import.meta.url).pathname,
16
- fetch: (request, env) => app.fetch(request, env),
29
+ assetsRoot: fileURLToPath(new URL('../client/', import.meta.url)),
30
+ env,
31
+ fetch: (request, bindings) => frameworkApp.fetch(request, bindings),
17
32
  });
33
+ // Set up native menus, trays and close behavior here.
34
+ return desktop;
18
35
  }
19
36
 
20
- void main();
37
+ if (!import.meta.env.DEV) {
38
+ void startDesktop().catch(error => { console.error(error); app.exit(1); });
39
+ }
21
40
  ```
22
41
 
23
- Do not top-level `await` `createDesktopApp()` in an ESM entry. Electron fires
24
- `ready` after the main module's first event-loop tick completes, while Desktop
25
- creation waits for `ready`; start an async function without awaiting it at the
26
- module's top level as shown above.
42
+ Do not top-level `await` `createDesktopApp()` in an ESM entry. Electron emits
43
+ `ready` after the main module's first event-loop tick; Desktop creation waits
44
+ for that event. Development calls the exported bootstrap once. Production starts
45
+ it through the guarded call above.
46
+
47
+ `pnpm desktop:dev` requires Vite 8.1.4 or later in the 8.x series. The CLI
48
+ supervises Electron, which runs the development module loader and asset server.
49
+ Pages retain the private origin and native request checks. Source edits reload
50
+ managed windows; changes under `src/desktop/`, to the Vite config or root `.env*`
51
+ files restart Electron. Reloads do not undo application side effects. Page syntax
52
+ errors remain visible and source repair can recover without restarting the CLI.
53
+
54
+ Keep `ssr.noExternal: true` restricted to production Desktop builds:
55
+ `mode === 'desktop' && command === 'build'`. Development needs normal external
56
+ package resolution. Do not register another server that exposes native handlers
57
+ on HTTP. Enable `developmentTraces: true` in `cossackPages()` to use the shared
58
+ inspector and CLI/MCP capture readers.
59
+
60
+ The optional `assets.fetch(request)` provider on `createDesktopApp()` replaces
61
+ filesystem asset lookup. A 404 falls through to application dispatch after its
62
+ body is canceled. The development runner supplies this provider for Vite assets;
63
+ ordinary packaged apps use `assetsRoot`. Native proof headers are stripped
64
+ before either provider or application code receives a request.
27
65
 
28
66
  `createDesktopApp()` forces context isolation and renderer sandboxing, with Node
29
67
  integration and preload bridges disabled. Only same-origin navigation is
30
68
  allowed; valid HTTP(S) popups are opened in the operating-system browser.
31
69
  Desktop pages currently require `@Page({ transport: 'http' })`.
32
70
 
71
+ Use Electron 43.7+ in the 43.x series, or 44.4+. The runtime verifies native
72
+ request initiators and managed window identity before dispatching local actions.
73
+ Cossack reserves the `persist:cossack.<identifier>` session and its
74
+ `onBeforeSendHeaders` hook. Default-session cookies/storage are not migrated.
75
+ Keep the identifier stable; native app files retain their existing paths.
76
+
33
77
  On Linux, `desktop:dev` checks Electron's local `chrome-sandbox` helper. pnpm's
34
78
  download is normally user-owned rather than root-owned/setuid, so the runner
35
79
  prints a warning and applies Electron's testing-only `--no-sandbox` flag to the
@@ -1,4 +1,3 @@
1
- export declare function isSuccessfulBuildOutput(value: string): boolean;
2
1
  export interface SandboxHelperMetadata {
3
2
  uid: number;
4
3
  mode: number;
package/dist/dev.js CHANGED
@@ -3,8 +3,9 @@ import { spawn as e } from "node:child_process";
3
3
  import t from "node:path";
4
4
  import { statSync as n } from "node:fs";
5
5
  import { createRequire as r } from "node:module";
6
+ import { fileURLToPath as i } from "node:url";
6
7
  //#region src/platform.ts
7
- function i(e, t, n = "auto") {
8
+ function a(e, t, n = "auto") {
8
9
  if (e !== "linux") return;
9
10
  if (n !== "auto") return n;
10
11
  let r = t.COSSACK_DESKTOP_OZONE_PLATFORM;
@@ -13,103 +14,57 @@ function i(e, t, n = "auto") {
13
14
  }
14
15
  //#endregion
15
16
  //#region src/dev-signals.ts
16
- function a(e) {
17
- return /built in \d|built in [\d.]+s/i.test(e);
18
- }
19
17
  function o(e, t) {
20
18
  return e === "linux" ? t?.uid === 0 && t.mode & 2048 ? [] : ["--no-sandbox"] : [];
21
19
  }
22
20
  function s(e, t) {
23
21
  if (e !== "linux") return [];
24
- let n = [], r = i(e, t);
22
+ let n = [], r = a(e, t);
25
23
  return r && n.push(`--ozone-platform=${r}`), t.COSSACK_DESKTOP_DEBUG !== "1" && n.push("--log-level=3"), n;
26
24
  }
27
25
  //#endregion
28
26
  //#region src/dev.ts
29
- var c = process.cwd(), l = r(t.join(c, "package.json")), u = t.join(t.dirname(l.resolve("vite/package.json")), "bin", "vite.js"), d = l("electron"), f = t.resolve(c, "dist/desktop/index.js"), p;
27
+ var c = process.cwd(), l = r(t.join(c, "package.json"))("electron"), u;
30
28
  try {
31
- let e = n(t.join(t.dirname(d), "chrome-sandbox"));
32
- p = {
29
+ let e = n(t.join(t.dirname(l), "chrome-sandbox"));
30
+ u = {
33
31
  uid: e.uid,
34
32
  mode: e.mode
35
33
  };
36
34
  } catch {}
37
- var m = [...o(process.platform, p), ...s(process.platform, process.env)];
38
- m.includes("--no-sandbox") && process.stderr.write("[desktop] Linux SUID sandbox helper is not root-owned with mode 4755; using Electron --no-sandbox for desktop:dev only. Packaged installers remain sandboxed.\n");
39
- var h, g = !1, _ = !1, v = !1, y = !1;
40
- function b(e, t, n) {
41
- e.stdout?.on("data", (e) => {
42
- let r = e.toString();
43
- process.stdout.write(`[${t}] ${r}`), a(r) && n();
44
- }), e.stderr?.on("data", (e) => {
45
- let r = e.toString();
46
- process.stderr.write(`[${t}] ${r}`), a(r) && n();
47
- }), e.on("exit", (e) => {
48
- !v && e !== 0 && w(e ?? 1);
49
- });
35
+ var d = [...o(process.platform, u), ...s(process.platform, process.env)];
36
+ d.includes("--no-sandbox") && process.stderr.write("[desktop] Using the development-only Linux --no-sandbox fallback for an unconfigured SUID helper.\n");
37
+ var f, p = !1, m = !1, h;
38
+ function g(e = 0) {
39
+ p || (p = !0, process.exitCode = e, f?.kill("SIGTERM"), f && (h = setTimeout(() => f?.kill("SIGKILL"), 6e3)));
50
40
  }
51
- function x() {
52
- !g || !_ || v || (h = e(d, [...m, f], {
41
+ var _ = process.argv.slice(2);
42
+ _[0] === "--" && _.shift();
43
+ function v() {
44
+ f = e(l, [
45
+ ...d,
46
+ ..._,
47
+ t.join(t.dirname(i(import.meta.url)), "development-runtime.js")
48
+ ], {
53
49
  cwd: c,
54
50
  stdio: [
55
- "inherit",
51
+ "ignore",
56
52
  "inherit",
57
53
  "inherit",
58
54
  "ipc"
59
- ]
60
- }), h.on("exit", (e, t) => {
61
- let n = y;
62
- y = !1, h = void 0, !v && (n ? x() : w(e ?? +!!t));
63
- }));
64
- }
65
- function S() {
66
- if (!h) return x();
67
- y = !0, h.kill();
68
- }
69
- function C() {
70
- h?.connected ? h.send?.({ type: "cossack:renderer-reload" }) : x();
71
- }
72
- function w(e = 0) {
73
- v || (v = !0, T.kill(), E.kill(), h?.kill(), process.exitCode = e);
55
+ ],
56
+ env: {
57
+ ...process.env,
58
+ NODE_ENV: "development",
59
+ ELECTRON_RUN_AS_NODE: ""
60
+ }
61
+ }), f.once("error", (e) => {
62
+ console.error("[desktop]", e), g(1);
63
+ }), f.on("message", (e) => {
64
+ !p && e?.type === "cossack:desktop-restart" && (m = !0, f?.kill("SIGTERM"), h ??= setTimeout(() => f?.kill("SIGKILL"), 6e3));
65
+ }), f.once("exit", (e, t) => {
66
+ clearTimeout(h), h = void 0, f = void 0, !p && (m ? (m = !1, v()) : g(e ?? +!!t));
67
+ });
74
68
  }
75
- var T = e(process.execPath, [
76
- u,
77
- "build",
78
- "--watch"
79
- ], {
80
- cwd: c,
81
- stdio: [
82
- "ignore",
83
- "pipe",
84
- "pipe"
85
- ]
86
- }), E = e(process.execPath, [
87
- u,
88
- "build",
89
- "--mode",
90
- "desktop",
91
- "--ssr",
92
- "src/desktop/index.ts",
93
- "--outDir",
94
- "dist/desktop",
95
- "--watch",
96
- "--minify",
97
- "false"
98
- ], {
99
- cwd: c,
100
- stdio: [
101
- "ignore",
102
- "pipe",
103
- "pipe"
104
- ]
105
- });
106
- b(T, "renderer", () => {
107
- let e = !g;
108
- g = !0, e ? x() : C();
109
- }), b(E, "main", () => {
110
- let e = !_;
111
- _ = !0, e ? x() : S();
112
- }), process.once("SIGINT", () => w(130)), process.once("SIGTERM", () => w(143)), process.once("exit", () => {
113
- v = !0, T.kill(), E.kill(), h?.kill();
114
- });
69
+ process.once("SIGINT", () => g()), process.once("SIGTERM", () => g()), process.once("exit", () => f?.kill("SIGTERM")), v();
115
70
  //#endregion
@@ -0,0 +1,2 @@
1
+ /** Keep Vite connected after a source error without injecting exception text as HTML. */
2
+ export declare function desktopDevelopmentError(error: unknown): Response;
@@ -0,0 +1,2 @@
1
+ /** Inject Vite into document responses without consuming opaque RPC/API bodies. */
2
+ export declare function transformDesktopDocument(request: Request, response: Response, transform: (pathname: string, html: string) => Promise<string>): Promise<Response>;
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,161 @@
1
+ import { a as e, s as t, t as n } from "./src-DHWIBc8l.js";
2
+ import { relative as r } from "node:path";
3
+ import { createServer as i, isRunnableDevEnvironment as a, loadEnv as o } from "vite";
4
+ import { createServer as s } from "node:http";
5
+ //#region src/development-error.ts
6
+ function c(e) {
7
+ let t = (e instanceof Error ? e.stack ?? e.message : String(e)).slice(0, 8192).replace(/[&<>"']/g, (e) => ({
8
+ "&": "&amp;",
9
+ "<": "&lt;",
10
+ ">": "&gt;",
11
+ "\"": "&quot;",
12
+ "'": "&#39;"
13
+ })[e]);
14
+ return new Response(`<!doctype html><html><head><meta charset="utf-8"><title>Desktop development error</title></head><body><h1>Desktop source could not load</h1><pre id="cossack-development-error">${t}</pre><script type="module" src="/@vite/client"><\/script></body></html>`, {
15
+ status: 500,
16
+ headers: {
17
+ "Content-Type": "text/html; charset=utf-8",
18
+ "Cache-Control": "no-store"
19
+ }
20
+ });
21
+ }
22
+ //#endregion
23
+ //#region src/development-response.ts
24
+ async function l(e, t, n) {
25
+ if (e.method !== "GET" || !e.headers.get("accept")?.includes("text/html") || t.headers.get("X-Cossack-Rpc-Response") === "native" || !t.body || !t.headers.get("content-type")?.includes("text/html")) return t;
26
+ let r = await n(new URL(e.url).pathname, await t.text()), i = new Headers(t.headers);
27
+ return i.delete("content-length"), new Response(r, {
28
+ status: t.status,
29
+ statusText: t.statusText,
30
+ headers: i
31
+ });
32
+ }
33
+ //#endregion
34
+ //#region src/development-runtime.ts
35
+ async function u() {
36
+ let u, d, f, p, m = !1, h = !1, g = 0, _, v = !1, y = () => {
37
+ e.exit(0);
38
+ };
39
+ process.once("SIGINT", () => y()), process.once("SIGTERM", () => y()), process.once("disconnect", () => y());
40
+ let b = () => {
41
+ process.connected ? process.send?.({ type: "cossack:desktop-restart" }) : console.error("[desktop] Native configuration changed; restart desktop:dev to apply it.");
42
+ }, x = () => m ? Promise.reject(/* @__PURE__ */ Error("Desktop development is closing")) : f ? Promise.resolve(f) : p ??= (async () => {
43
+ let e = u.environments.ssr;
44
+ if (!a(e)) throw Error("Desktop requires a runnable Vite SSR environment");
45
+ for (; !m;) {
46
+ let t = g;
47
+ h &&= (e.moduleGraph.invalidateAll(), e.runner.clearCache(), !1);
48
+ let n = await e.runner.import("/src/desktop/index.ts");
49
+ if (typeof n.startDesktop != "function" || typeof n.frameworkApp?.fetch != "function") throw TypeError("Desktop entry must export startDesktop(factory) and frameworkApp.fetch. Apply the Desktop bootstrap migration.");
50
+ if (t === g) return f = n, n;
51
+ }
52
+ throw Error("Desktop development is closing");
53
+ })().finally(() => {
54
+ p = void 0;
55
+ }), S = (e) => u.config.logger.error(`[desktop] ${e instanceof Error ? e.stack : e}`), C = {
56
+ name: "cossack-desktop-development",
57
+ enforce: "post",
58
+ hotUpdate({ file: e }) {
59
+ let t = r(u.config.root, e).replaceAll("\\", "/");
60
+ if (!(!(t.startsWith("src/") && /\.(?:[cm]?[jt]sx?|mdx?)$/.test(t)) && !u.environments.ssr.moduleGraph.getModulesByFile(e)?.size)) return this.environment.name === "ssr" ? t.startsWith("src/desktop/") ? (b(), []) : (f = void 0, h = !0, g++, (d ? x().then(() => {
61
+ for (let e of n.getAllWindows()) e.webContents.getURL().startsWith("cossack://app/") && e.webContents.reload();
62
+ }) : j()).catch(S), []) : [];
63
+ }
64
+ }, w = s((e, t) => {
65
+ u ? u.middlewares(e, t) : t.writeHead(503).end();
66
+ });
67
+ await new Promise((e, t) => {
68
+ w.once("error", t), w.listen(0, "127.0.0.1", e);
69
+ });
70
+ let T = w.address();
71
+ if (!T || typeof T == "string") throw Error("Desktop development could not bind its asset server");
72
+ let E = `http://127.0.0.1:${T.port}`;
73
+ u = await i({
74
+ root: process.cwd(),
75
+ mode: "desktop",
76
+ appType: "custom",
77
+ plugins: [C],
78
+ server: {
79
+ host: "127.0.0.1",
80
+ middlewareMode: !0,
81
+ ws: {
82
+ server: w,
83
+ host: "127.0.0.1",
84
+ protocol: "ws",
85
+ clientPort: T.port
86
+ }
87
+ },
88
+ environments: { ssr: { resolve: {
89
+ external: ["electron", "@cossackframework/desktop"],
90
+ noExternal: [
91
+ "@cossackframework/core",
92
+ "@cossackframework/renderer",
93
+ "@cossackframework/framework"
94
+ ]
95
+ } } }
96
+ });
97
+ let D = {
98
+ ...o(u.config.mode, u.config.envDir, ""),
99
+ ...process.env
100
+ }, O = (e) => {
101
+ let t = r(u.config.root, e).replaceAll("\\", "/");
102
+ (e === u.config.configFile || /^\.env(?:\.[^/]+)?$/.test(t)) && b();
103
+ };
104
+ u.watcher.on("change", O).on("add", O).on("unlink", O);
105
+ let k = { async fetch(e) {
106
+ if (e.method !== "GET" && e.method !== "HEAD") return new Response(null, { status: 404 });
107
+ let t = new URL(e.url), n = await fetch(E + t.pathname + t.search, {
108
+ method: e.method,
109
+ signal: e.signal
110
+ }), r = new Headers(n.headers);
111
+ return r.delete("content-encoding"), r.delete("content-length"), r.delete("transfer-encoding"), new Response(n.body, {
112
+ status: n.status,
113
+ statusText: n.statusText,
114
+ headers: r
115
+ });
116
+ } }, A = (e) => t({
117
+ ...e,
118
+ assets: k,
119
+ fetch: async (e, t) => {
120
+ try {
121
+ let n = await x();
122
+ return await l(e, await n.frameworkApp.fetch(e, {
123
+ ...t,
124
+ ...D,
125
+ ...n.env,
126
+ ASSETS: t?.ASSETS,
127
+ COSSACK_DESKTOP: t?.COSSACK_DESKTOP
128
+ }), (e, t) => u.transformIndexHtml(e, t));
129
+ } catch (e) {
130
+ return S(e), c(e);
131
+ }
132
+ }
133
+ });
134
+ function j() {
135
+ return _ ??= x().then(async (e) => {
136
+ !m && !d && (v && u.ws.send({ type: "full-reload" }), v = !1, d = await e.startDesktop(A), console.log(`[desktop] Development ready at cossack://app (assets ${E})`));
137
+ }).catch((e) => {
138
+ throw v = !0, e;
139
+ }).finally(() => {
140
+ _ = void 0;
141
+ });
142
+ }
143
+ let M, N = () => M ??= (async () => {
144
+ m = !0;
145
+ let t = setTimeout(() => e.exit(1), 5e3);
146
+ try {
147
+ await u.close(), w.closeAllConnections(), await new Promise((e) => w.close(() => e())), e.exit(0);
148
+ } finally {
149
+ clearTimeout(t);
150
+ }
151
+ })();
152
+ e.on("before-quit", (e) => {
153
+ e.preventDefault(), N();
154
+ }), y = () => {
155
+ N();
156
+ }, await j().catch(S);
157
+ }
158
+ u().catch((t) => {
159
+ console.error("[desktop] Development startup failed", t), e.exit(1);
160
+ });
161
+ //#endregion
package/dist/index.d.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import electron from 'electron';
2
2
  import type { BrowserWindowConstructorOptions, MessageBoxOptions, NativeImage, WebPreferences } from 'electron';
3
- import type { CossackRuntimeAdapter } from '@cossackframework/framework/runtime-adapter';
3
+ import type { CossackRuntimeAdapter } from '@cossackframework/core';
4
4
  export declare const app: Electron.App, BrowserWindow: typeof electron.BrowserWindow, dialog: Electron.Dialog, Menu: typeof electron.Menu, nativeImage: typeof Electron.NativeImage, Notification: typeof electron.Notification, protocol: Electron.Protocol, electronShell: Electron.Shell, Tray: typeof electron.Tray;
5
5
  export { DesktopUnavailableError } from './error.js';
6
6
  export { electronShell as shell };
@@ -22,6 +22,10 @@ export interface CreateDesktopAppOptions {
22
22
  identifier: string;
23
23
  productName: string;
24
24
  assetsRoot: string;
25
+ /** Optional asset provider. Return 404 to continue to the application router. */
26
+ assets?: {
27
+ fetch(request: Request): Response | Promise<Response>;
28
+ };
25
29
  fetch: DesktopFetch;
26
30
  env?: Record<string, unknown>;
27
31
  startPath?: string;
package/dist/index.js CHANGED
@@ -1,308 +1,2 @@
1
- import { execFile as e } from "node:child_process";
2
- import { readFile as t, stat as n } from "node:fs/promises";
3
- import r from "node:path";
4
- import i from "electron";
5
- //#region src/error.ts
6
- var a = class extends Error {
7
- constructor() {
8
- super("@cossackframework/desktop can only create applications and shells in the Electron main process."), this.name = "DesktopUnavailableError";
9
- }
10
- }, { app: o, BrowserWindow: s, dialog: c, Menu: l, nativeImage: u, Notification: d, protocol: f, shell: p, Tray: m } = typeof i == "object" && i ? i : {}, h = {
11
- name: "electron",
12
- supportedTransports: ["http"],
13
- getClientMetadata: () => ({
14
- platform: "desktop",
15
- adapter: "electron"
16
- })
17
- }, g = "cossack", _ = "cossack://app", v = !1, y, b = 0;
18
- function x(e) {
19
- process.env.COSSACK_DESKTOP_DEBUG === "1" && console.error(`[Cossack Desktop] ${e}`);
20
- }
21
- function S() {
22
- v || f?.registerSchemesAsPrivileged && (f.registerSchemesAsPrivileged([{
23
- scheme: g,
24
- privileges: {
25
- standard: !0,
26
- secure: !0,
27
- supportFetchAPI: !0,
28
- corsEnabled: !1,
29
- stream: !0
30
- }
31
- }]), v = !0);
32
- }
33
- S();
34
- function C() {
35
- if (!process.versions.electron || process.type === "renderer" || !o || !s) throw new a();
36
- }
37
- function w(t, n) {
38
- if (process.platform !== "linux") return;
39
- let r = `org.freedesktop.StatusNotifierItem-${process.pid}-${n}`;
40
- setTimeout(() => {
41
- t.isDestroyed() || e("dbus-send", [
42
- "--session",
43
- "--print-reply",
44
- "--type=method_call",
45
- "--dest=org.kde.StatusNotifierWatcher",
46
- "/StatusNotifierWatcher",
47
- "org.kde.StatusNotifierWatcher.RegisterStatusNotifierItem",
48
- `string:${r}`
49
- ], { timeout: 2e3 }, (e) => {
50
- e && x(`could not repair Linux tray registration: ${e.message}`);
51
- });
52
- }, 4e3).unref();
53
- }
54
- function T(e) {
55
- C();
56
- let t = ++b, n = e.guid ? new m(e.image, e.guid) : new m(e.image);
57
- return e.toolTip && n.setToolTip(e.toolTip), e.menu !== void 0 && n.setContextMenu(e.menu), w(n, t), n;
58
- }
59
- function E(e) {
60
- C();
61
- let t = e.window ?? s.getFocusedWindow() ?? s.getAllWindows()[0];
62
- if (!t) throw new a();
63
- if (e.behavior === "hide-to-tray" && !e.tray) throw TypeError("Desktop hide-to-tray behavior requires a tray.");
64
- let n = !1, r = !1, i = !1, l = () => {
65
- r = !0;
66
- }, u = () => {
67
- r || (r = !0, (e.onQuit ?? (() => o.quit()))());
68
- }, d = {
69
- behavior: e.behavior,
70
- quit: u,
71
- dispose() {
72
- n || (n = !0, t.removeListener("close", f), o.removeListener("before-quit", l));
73
- }
74
- }, f = (a) => {
75
- if (n || r) return;
76
- if (a.preventDefault(), e.behavior === "quit") {
77
- u();
78
- return;
79
- }
80
- if (e.behavior === "hide-to-tray") {
81
- e.tray && !e.tray.isDestroyed() ? t.hide() : u();
82
- return;
83
- }
84
- if (i) return;
85
- i = !0;
86
- let s = o.getName();
87
- c.showMessageBox(t, {
88
- type: "question",
89
- title: s,
90
- message: `Quit ${s}?`,
91
- buttons: ["Quit", "Cancel"],
92
- defaultId: 1,
93
- cancelId: 1,
94
- noLink: !0,
95
- ...e.confirmation
96
- }).then(({ response: t }) => {
97
- t === (e.confirmResponse ?? 0) && u();
98
- }).catch((e) => {
99
- console.error("[Cossack Desktop] Could not show the close confirmation.", e);
100
- }).finally(() => {
101
- i = !1;
102
- });
103
- };
104
- return t.on("close", f), o.on("before-quit", l), d;
105
- }
106
- function D(e) {
107
- let t;
108
- try {
109
- t = decodeURIComponent(e);
110
- } catch {
111
- throw URIError("Malformed Desktop URL path.");
112
- }
113
- if (t.includes("\0") || t.includes("\\")) throw URIError("Unsafe Desktop URL path.");
114
- if (t.split("/").includes("..")) throw URIError("Desktop URL traversal is not allowed.");
115
- return t.replace(/^\/+/, "");
116
- }
117
- function O(e, t) {
118
- let n = r.resolve(e), i = r.resolve(n, t || "__cossack_ssr__"), a = r.relative(n, i);
119
- if (a.startsWith("..") || r.isAbsolute(a)) throw URIError("Desktop URL traversal is not allowed.");
120
- return i;
121
- }
122
- var k = {
123
- ".css": "text/css; charset=utf-8",
124
- ".gif": "image/gif",
125
- ".html": "text/html; charset=utf-8",
126
- ".ico": "image/x-icon",
127
- ".jpeg": "image/jpeg",
128
- ".jpg": "image/jpeg",
129
- ".js": "text/javascript; charset=utf-8",
130
- ".json": "application/json; charset=utf-8",
131
- ".map": "application/json; charset=utf-8",
132
- ".mjs": "text/javascript; charset=utf-8",
133
- ".png": "image/png",
134
- ".svg": "image/svg+xml; charset=utf-8",
135
- ".txt": "text/plain; charset=utf-8",
136
- ".wasm": "application/wasm",
137
- ".webp": "image/webp",
138
- ".woff": "font/woff",
139
- ".woff2": "font/woff2"
140
- };
141
- async function A(e, i) {
142
- if (i.method !== "GET" && i.method !== "HEAD") return;
143
- let a = D(new URL(i.url).pathname);
144
- if (!a) return;
145
- let o = O(e, a);
146
- try {
147
- let e = await n(o);
148
- if (!e.isFile()) return;
149
- let a = new Headers({
150
- "content-type": k[r.extname(o).toLowerCase()] ?? "application/octet-stream",
151
- "content-length": String(e.size)
152
- });
153
- return new Response(i.method === "HEAD" ? null : await t(o), { headers: a });
154
- } catch (e) {
155
- if (e.code === "ENOENT" || e.code === "ENOTDIR") return;
156
- throw e;
157
- }
158
- }
159
- function j(e) {
160
- let t = new URL(e.url), n = new URL(`${t.pathname}${t.search}`, "https://app");
161
- return n.searchParams.delete("__cossack_window"), new Request(n, e);
162
- }
163
- function M(e) {
164
- return e.protocol === `${g}:` && e.hostname === "app" && e.username === "" && e.password === "" && e.port === "";
165
- }
166
- function N(e = {}) {
167
- let { webPreferences: t, ...n } = e;
168
- return {
169
- width: 1e3,
170
- height: 720,
171
- show: !1,
172
- ...n,
173
- webPreferences: {
174
- ...t,
175
- contextIsolation: !0,
176
- sandbox: !0,
177
- nodeIntegration: !1,
178
- nodeIntegrationInWorker: !1,
179
- nodeIntegrationInSubFrames: !1,
180
- webSecurity: !0,
181
- allowRunningInsecureContent: !1,
182
- webviewTag: !1,
183
- preload: void 0
184
- }
185
- };
186
- }
187
- function P(e) {
188
- e.webContents.on("will-navigate", (e, t) => {
189
- try {
190
- let n = new URL(t);
191
- M(n) || (e.preventDefault(), (n.protocol === "https:" || n.protocol === "http:") && p.openExternal(n.href));
192
- } catch {
193
- e.preventDefault();
194
- }
195
- }), e.webContents.setWindowOpenHandler(({ url: e }) => {
196
- try {
197
- let t = new URL(e);
198
- (t.protocol === "https:" || t.protocol === "http:") && p.openExternal(t.href);
199
- } catch {}
200
- return { action: "deny" };
201
- });
202
- }
203
- function F(e = {}) {
204
- C();
205
- let t = e.window ?? s.getFocusedWindow() ?? s.getAllWindows()[0];
206
- if (!t) throw new a();
207
- return {
208
- app: o,
209
- window: t,
210
- Menu: l,
211
- Tray: m,
212
- dialog: c,
213
- Notification: d,
214
- nativeImage: u,
215
- shell: p,
216
- get dock() {
217
- return o.dock;
218
- },
219
- show() {
220
- t.show();
221
- },
222
- hide() {
223
- t.hide();
224
- },
225
- focus() {
226
- t.focus();
227
- },
228
- quit() {
229
- o.quit();
230
- },
231
- setBadge(e) {
232
- return o.setBadgeCount(e === null ? 0 : typeof e == "number" ? e : Number(e) || 0);
233
- },
234
- setOverlayIcon(e, n = "") {
235
- t.setOverlayIcon(e, n);
236
- }
237
- };
238
- }
239
- async function I(e) {
240
- if (C(), x("initializing Electron application"), !e.identifier.trim()) throw TypeError("Desktop identifier is required.");
241
- if (!e.productName.trim()) throw TypeError("Desktop productName is required.");
242
- let t = r.resolve(e.assetsRoot), n = `/${(e.startPath ?? "/").replace(/^\/+/, "")}`, i = !1, a;
243
- o.setName(e.productName), process.platform === "linux" && o.commandLine.appendSwitch("class", e.identifier), process.platform === "win32" && o.setAppUserModelId(e.identifier), x("requesting single-instance lock");
244
- let c = o.requestSingleInstanceLock();
245
- if (x(`single-instance lock ${c ? "acquired" : "unavailable"}`), !c) throw o.quit(), Error(`[Cossack] Another ${e.productName} instance is already running.`);
246
- await o.whenReady(), x("Electron app is ready");
247
- let l = (t = {}) => {
248
- let { path: r = n, ...i } = t, a = new URL(r, `${_}/`);
249
- if (!M(a)) throw TypeError("Desktop window paths must stay within cossack://app.");
250
- let o = new s(N({
251
- ...e.window,
252
- ...i
253
- }));
254
- return x(`created BrowserWindow ${o.id}`), P(o), a.searchParams.set("__cossack_window", String(o.id)), o.loadURL(a.href).then(() => x(`loaded ${a.href}`), (e) => console.error(`[Cossack Desktop] Failed to load ${a.href}`, e)), o.once("ready-to-show", () => o.show()), o;
255
- };
256
- await f.handle(g, async (n) => {
257
- x(`handling ${n.method} ${n.url}`);
258
- let r, i;
259
- try {
260
- if (r = new URL(n.url), !M(r)) return new Response("Forbidden Desktop authority", { status: 403 });
261
- D(r.pathname);
262
- let e = n.headers.get("referer");
263
- if (i = new URL(e || n.url), !M(i)) return new Response("Forbidden Desktop authority", { status: 403 });
264
- } catch {
265
- return new Response("Invalid Desktop URL", { status: 400 });
266
- }
267
- let o = i.searchParams.get("__cossack_window"), c = o ? s.fromId(Number(o)) ?? a : a, l = c ? F({ window: c }) : void 0, u = await A(t, n);
268
- if (u) return u;
269
- let d = { fetch: async (e) => await A(t, e) ?? new Response("Not found", { status: 404 }) };
270
- return e.fetch(j(n), {
271
- ...e.env ?? {},
272
- ASSETS: d,
273
- COSSACK_DESKTOP: l
274
- });
275
- }), x("registered cossack:// protocol handler"), a = l();
276
- let u = F({ window: a }), d = {
277
- app: o,
278
- mainWindow: a,
279
- shell: u,
280
- get quitting() {
281
- return i;
282
- },
283
- createWindow: l,
284
- show() {
285
- a.show(), a.focus();
286
- },
287
- hide() {
288
- a.hide();
289
- },
290
- quit() {
291
- i = !0, o.quit();
292
- }
293
- };
294
- return o.on("before-quit", () => {
295
- i = !0;
296
- }), o.on("activate", () => {
297
- s.getAllWindows().length === 0 ? a = l() : d.show();
298
- }), o.on("second-instance", () => d.show()), process.on("message", (e) => {
299
- if (e?.type === "cossack:renderer-reload") for (let e of s.getAllWindows()) e.webContents.reloadIgnoringCache();
300
- }), d;
301
- }
302
- function L(e) {
303
- return C(), y ??= I(e).catch((e) => {
304
- throw y = void 0, e;
305
- });
306
- }
307
- //#endregion
308
- export { s as BrowserWindow, a as DesktopUnavailableError, l as Menu, d as Notification, m as Tray, o as app, E as configureDesktopClose, L as createDesktopApp, F as createDesktopShell, T as createDesktopTray, c as dialog, h as electronRuntimeAdapter, p as electronShell, p as shell, u as nativeImage, f as protocol };
1
+ import { a as e, c as t, d as n, f as r, h as i, i as a, l as o, m as s, n as c, o as l, p as u, r as d, s as f, t as p, u as m } from "./src-DHWIBc8l.js";
2
+ export { p as BrowserWindow, i as DesktopUnavailableError, c as Menu, d as Notification, a as Tray, e as app, l as configureDesktopClose, f as createDesktopApp, t as createDesktopShell, o as createDesktopTray, m as dialog, n as electronRuntimeAdapter, r as electronShell, r as shell, u as nativeImage, s as protocol };
@@ -0,0 +1,9 @@
1
+ import type { OnBeforeSendHeadersListenerDetails } from 'electron';
2
+ export declare const desktopOrigin = "cossack://app";
3
+ export declare const desktopOwnerHeader = "x-cossack-desktop-owner";
4
+ export declare const desktopTokenHeader = "x-cossack-desktop-token";
5
+ type RequestDetails = Pick<OnBeforeSendHeadersListenerDetails, 'url' | 'method' | 'resourceType' | 'initiatorOrigin' | 'webContentsId' | 'requestHeaders'>;
6
+ export declare function isDesktopAppUrl(url: URL): boolean;
7
+ /** Use native initiator evidence, never renderer-supplied Origin, Referer or query IDs. */
8
+ export declare function authorizeDesktopRequest(details: RequestDetails, owned: boolean, token: string): Record<string, string> | undefined;
9
+ export {};
@@ -0,0 +1,346 @@
1
+ import { randomUUID as e } from "node:crypto";
2
+ import { execFile as t } from "node:child_process";
3
+ import { readFile as n, realpath as r, stat as i } from "node:fs/promises";
4
+ import a from "node:path";
5
+ import o from "electron";
6
+ var s = "x-cossack-desktop-owner", c = "x-cossack-desktop-token";
7
+ function l(e) {
8
+ return e.protocol === "cossack:" && e.hostname === "app" && e.username === "" && e.password === "" && e.port === "";
9
+ }
10
+ function u(e, t, n) {
11
+ if (!t || e.webContentsId === void 0) return;
12
+ try {
13
+ if (!l(new URL(e.url))) return;
14
+ } catch {
15
+ return;
16
+ }
17
+ if (!(e.resourceType === "mainFrame" && e.method === "GET" && e.initiatorOrigin === void 0) && e.initiatorOrigin !== "cossack://app") return;
18
+ let r = new Headers(e.requestHeaders), i = r.get("origin");
19
+ if (!(i !== null && i !== "cossack://app")) return r.set(s, String(e.webContentsId)), r.set(c, n), Object.fromEntries(r);
20
+ }
21
+ //#endregion
22
+ //#region src/error.ts
23
+ var d = class extends Error {
24
+ constructor() {
25
+ super("@cossackframework/desktop can only create applications and shells in the Electron main process."), this.name = "DesktopUnavailableError";
26
+ }
27
+ }, f = typeof o == "object" && o ? o : {}, { app: p, BrowserWindow: m, dialog: h, Menu: g, nativeImage: _, Notification: v, protocol: y, shell: b, Tray: x } = f, S = {
28
+ name: "electron",
29
+ supportedTransports: ["http"],
30
+ getClientMetadata: () => ({
31
+ platform: "desktop",
32
+ adapter: "electron"
33
+ })
34
+ }, C = "cossack", w = "cossack://app", T = !1, E, D = 0;
35
+ function O(e) {
36
+ process.env.COSSACK_DESKTOP_DEBUG === "1" && console.error(`[Cossack Desktop] ${e}`);
37
+ }
38
+ function k() {
39
+ T || y?.registerSchemesAsPrivileged && (y.registerSchemesAsPrivileged([{
40
+ scheme: C,
41
+ privileges: {
42
+ standard: !0,
43
+ secure: !0,
44
+ supportFetchAPI: !0,
45
+ corsEnabled: !0,
46
+ stream: !0
47
+ }
48
+ }]), T = !0);
49
+ }
50
+ k();
51
+ function A() {
52
+ if (!process.versions.electron || process.type === "renderer" || !p || !m) throw new d();
53
+ let [e, t] = process.versions.electron.split(".").map(Number);
54
+ if (e < 43 || e === 43 && t < 7 || e === 44 && t < 4) throw Error("Cossack Desktop requires Electron 43.7+ or 44.4+ for native request initiator verification.");
55
+ }
56
+ function j(e, n) {
57
+ if (process.platform !== "linux") return;
58
+ let r = `org.freedesktop.StatusNotifierItem-${process.pid}-${n}`;
59
+ setTimeout(() => {
60
+ e.isDestroyed() || t("dbus-send", [
61
+ "--session",
62
+ "--print-reply",
63
+ "--type=method_call",
64
+ "--dest=org.kde.StatusNotifierWatcher",
65
+ "/StatusNotifierWatcher",
66
+ "org.kde.StatusNotifierWatcher.RegisterStatusNotifierItem",
67
+ `string:${r}`
68
+ ], { timeout: 2e3 }, (e) => {
69
+ e && O(`could not repair Linux tray registration: ${e.message}`);
70
+ });
71
+ }, 4e3).unref();
72
+ }
73
+ function M(e) {
74
+ A();
75
+ let t = ++D, n = e.guid ? new x(e.image, e.guid) : new x(e.image);
76
+ return e.toolTip && n.setToolTip(e.toolTip), e.menu !== void 0 && n.setContextMenu(e.menu), j(n, t), n;
77
+ }
78
+ function N(e) {
79
+ A();
80
+ let t = e.window ?? m.getFocusedWindow() ?? m.getAllWindows()[0];
81
+ if (!t) throw new d();
82
+ if (e.behavior === "hide-to-tray" && !e.tray) throw TypeError("Desktop hide-to-tray behavior requires a tray.");
83
+ let n = !1, r = !1, i = !1, a = () => {
84
+ r = !0;
85
+ }, o = () => {
86
+ r || (r = !0, (e.onQuit ?? (() => p.quit()))());
87
+ }, s = {
88
+ behavior: e.behavior,
89
+ quit: o,
90
+ dispose() {
91
+ n || (n = !0, t.removeListener("close", c), p.removeListener("before-quit", a));
92
+ }
93
+ }, c = (a) => {
94
+ if (n || r) return;
95
+ if (a.preventDefault(), e.behavior === "quit") {
96
+ o();
97
+ return;
98
+ }
99
+ if (e.behavior === "hide-to-tray") {
100
+ e.tray && !e.tray.isDestroyed() ? t.hide() : o();
101
+ return;
102
+ }
103
+ if (i) return;
104
+ i = !0;
105
+ let s = p.getName();
106
+ h.showMessageBox(t, {
107
+ type: "question",
108
+ title: s,
109
+ message: `Quit ${s}?`,
110
+ buttons: ["Quit", "Cancel"],
111
+ defaultId: 1,
112
+ cancelId: 1,
113
+ noLink: !0,
114
+ ...e.confirmation
115
+ }).then(({ response: t }) => {
116
+ t === (e.confirmResponse ?? 0) && o();
117
+ }).catch((e) => {
118
+ console.error("[Cossack Desktop] Could not show the close confirmation.", e);
119
+ }).finally(() => {
120
+ i = !1;
121
+ });
122
+ };
123
+ return t.on("close", c), p.on("before-quit", a), s;
124
+ }
125
+ function P(e) {
126
+ let t;
127
+ try {
128
+ t = decodeURIComponent(e);
129
+ } catch {
130
+ throw URIError("Malformed Desktop URL path.");
131
+ }
132
+ if (t.includes("\0") || t.includes("\\")) throw URIError("Unsafe Desktop URL path.");
133
+ if (t.split("/").includes("..")) throw URIError("Desktop URL traversal is not allowed.");
134
+ return t.replace(/^\/+/, "");
135
+ }
136
+ function F(e, t) {
137
+ let n = a.resolve(e), r = a.resolve(n, t || "__cossack_ssr__"), i = a.relative(n, r);
138
+ if (i.startsWith("..") || a.isAbsolute(i)) throw URIError("Desktop URL traversal is not allowed.");
139
+ return r;
140
+ }
141
+ var I = {
142
+ ".css": "text/css; charset=utf-8",
143
+ ".gif": "image/gif",
144
+ ".html": "text/html; charset=utf-8",
145
+ ".ico": "image/x-icon",
146
+ ".jpeg": "image/jpeg",
147
+ ".jpg": "image/jpeg",
148
+ ".js": "text/javascript; charset=utf-8",
149
+ ".json": "application/json; charset=utf-8",
150
+ ".map": "application/json; charset=utf-8",
151
+ ".mjs": "text/javascript; charset=utf-8",
152
+ ".png": "image/png",
153
+ ".svg": "image/svg+xml; charset=utf-8",
154
+ ".txt": "text/plain; charset=utf-8",
155
+ ".wasm": "application/wasm",
156
+ ".webp": "image/webp",
157
+ ".woff": "font/woff",
158
+ ".woff2": "font/woff2"
159
+ };
160
+ async function L(e, t) {
161
+ if (t.method !== "GET" && t.method !== "HEAD") return;
162
+ let o = P(new URL(t.url).pathname);
163
+ if (!o) return;
164
+ let s = F(e, o);
165
+ try {
166
+ let [o, c] = await Promise.all([r(e), r(s)]), l = a.relative(o, c);
167
+ if (l === ".." || l.startsWith(`..${a.sep}`) || a.isAbsolute(l)) return;
168
+ let u = await i(c);
169
+ if (!u.isFile()) return;
170
+ let d = new Headers({
171
+ "content-type": I[a.extname(s).toLowerCase()] ?? "application/octet-stream",
172
+ "content-length": String(u.size)
173
+ });
174
+ return new Response(t.method === "HEAD" ? null : await n(c), { headers: d });
175
+ } catch (e) {
176
+ if (e.code === "ENOENT" || e.code === "ENOTDIR") return;
177
+ throw e;
178
+ }
179
+ }
180
+ function R(e) {
181
+ let t = new URL(e.url), n = new URL(`${t.pathname}${t.search}`, "https://app");
182
+ n.searchParams.delete("__cossack_window");
183
+ let r = new Request(n, e);
184
+ return r.headers.delete(s), r.headers.delete(c), r.headers.set("origin", n.origin), r;
185
+ }
186
+ function z(e = {}) {
187
+ let { webPreferences: t, ...n } = e;
188
+ return {
189
+ width: 1e3,
190
+ height: 720,
191
+ show: !1,
192
+ ...n,
193
+ webPreferences: {
194
+ ...t,
195
+ contextIsolation: !0,
196
+ sandbox: !0,
197
+ nodeIntegration: !1,
198
+ nodeIntegrationInWorker: !1,
199
+ nodeIntegrationInSubFrames: !1,
200
+ webSecurity: !0,
201
+ allowRunningInsecureContent: !1,
202
+ webviewTag: !1,
203
+ preload: void 0
204
+ }
205
+ };
206
+ }
207
+ function B(e) {
208
+ e.webContents.on("will-navigate", (e, t) => {
209
+ try {
210
+ let n = new URL(t);
211
+ l(n) || (e.preventDefault(), (n.protocol === "https:" || n.protocol === "http:") && b.openExternal(n.href));
212
+ } catch {
213
+ e.preventDefault();
214
+ }
215
+ }), e.webContents.setWindowOpenHandler(({ url: e }) => {
216
+ try {
217
+ let t = new URL(e);
218
+ (t.protocol === "https:" || t.protocol === "http:") && b.openExternal(t.href);
219
+ } catch {}
220
+ return { action: "deny" };
221
+ });
222
+ }
223
+ function V(e = {}) {
224
+ A();
225
+ let t = e.window ?? m.getFocusedWindow() ?? m.getAllWindows()[0];
226
+ if (!t) throw new d();
227
+ return {
228
+ app: p,
229
+ window: t,
230
+ Menu: g,
231
+ Tray: x,
232
+ dialog: h,
233
+ Notification: v,
234
+ nativeImage: _,
235
+ shell: b,
236
+ get dock() {
237
+ return p.dock;
238
+ },
239
+ show() {
240
+ t.show();
241
+ },
242
+ hide() {
243
+ t.hide();
244
+ },
245
+ focus() {
246
+ t.focus();
247
+ },
248
+ quit() {
249
+ p.quit();
250
+ },
251
+ setBadge(e) {
252
+ return p.setBadgeCount(e === null ? 0 : typeof e == "number" ? e : Number(e) || 0);
253
+ },
254
+ setOverlayIcon(e, n = "") {
255
+ t.setOverlayIcon(e, n);
256
+ }
257
+ };
258
+ }
259
+ async function H(t) {
260
+ if (A(), O("initializing Electron application"), !t.identifier.trim()) throw TypeError("Desktop identifier is required.");
261
+ if (!t.productName.trim()) throw TypeError("Desktop productName is required.");
262
+ let n = a.resolve(t.assetsRoot), r = `/${(t.startPath ?? "/").replace(/^\/+/, "")}`, i = !1, o;
263
+ p.setName(t.productName), process.platform === "linux" && p.commandLine.appendSwitch("class", t.identifier), process.platform === "win32" && p.setAppUserModelId(t.identifier), O("requesting single-instance lock");
264
+ let d = p.requestSingleInstanceLock();
265
+ if (O(`single-instance lock ${d ? "acquired" : "unavailable"}`), !d) throw p.quit(), Error(`[Cossack] Another ${t.productName} instance is already running.`);
266
+ await p.whenReady(), O("Electron app is ready");
267
+ let h = f.session.fromPartition(`persist:cossack.${t.identifier}`), g = /* @__PURE__ */ new Map(), _ = e();
268
+ h.webRequest.onBeforeSendHeaders((e, t) => {
269
+ if (!e.url.startsWith(`${C}:`)) {
270
+ let n = new Headers(e.requestHeaders);
271
+ n.delete(s), n.delete(c), t({ requestHeaders: Object.fromEntries(n) });
272
+ return;
273
+ }
274
+ let n = u(e, g.has(e.webContentsId ?? -1), _);
275
+ n || O(`rejected ${e.resourceType} from ${e.initiatorOrigin ?? "browser"} (owned: ${g.has(e.webContentsId ?? -1)})`), t(n ? { requestHeaders: n } : { cancel: !0 });
276
+ });
277
+ let v = (e = {}) => {
278
+ let { path: n = r, ...i } = e, a = new URL(n, `${w}/`);
279
+ if (!l(a)) throw TypeError("Desktop window paths must stay within cossack://app.");
280
+ let o = z({
281
+ ...t.window,
282
+ ...i
283
+ }), s = new m({
284
+ ...o,
285
+ webPreferences: {
286
+ ...o.webPreferences,
287
+ session: h
288
+ }
289
+ }), c = s.webContents.id;
290
+ return g.set(c, s), s.once("closed", () => g.delete(c)), O(`created BrowserWindow ${s.id}`), B(s), s.loadURL(a.href).then(() => O(`loaded ${a.href}`), (e) => console.error(`[Cossack Desktop] Failed to load ${a.href}`, e)), s.once("ready-to-show", () => s.show()), s;
291
+ };
292
+ await h.protocol.handle(C, async (e) => {
293
+ O(`handling ${e.method} ${e.url}`);
294
+ let r;
295
+ try {
296
+ if (r = new URL(e.url), !l(r)) return new Response("Forbidden Desktop authority", { status: 403 });
297
+ let t = e.headers.get("origin");
298
+ if (t && t !== w) return new Response("Forbidden Desktop origin", { status: 403 });
299
+ P(r.pathname);
300
+ let n = e.headers.get("referer");
301
+ if (!l(new URL(n || e.url))) return new Response("Forbidden Desktop authority", { status: 403 });
302
+ } catch {
303
+ return new Response("Invalid Desktop URL", { status: 400 });
304
+ }
305
+ let i = e.headers.get(s), a = i === null ? void 0 : g.get(Number(i));
306
+ if (e.headers.get("x-cossack-desktop-token") !== _ || !a) return new Response("Unverified Desktop request", { status: 403 });
307
+ let o = V({ window: a }), c = R(e), u = t.assets ?? { fetch: async (e) => await L(n, e) ?? new Response("Not found", { status: 404 }) }, d = await u.fetch(c);
308
+ return d.status === 404 ? (await d.body?.cancel(), t.fetch(c, {
309
+ ...t.env ?? {},
310
+ ASSETS: u,
311
+ COSSACK_DESKTOP: o
312
+ })) : d;
313
+ }), O("registered cossack:// protocol handler"), o = v();
314
+ let y = V({ window: o }), b = {
315
+ app: p,
316
+ mainWindow: o,
317
+ shell: y,
318
+ get quitting() {
319
+ return i;
320
+ },
321
+ createWindow: v,
322
+ show() {
323
+ o.show(), o.focus();
324
+ },
325
+ hide() {
326
+ o.hide();
327
+ },
328
+ quit() {
329
+ i = !0, p.quit();
330
+ }
331
+ };
332
+ return p.on("before-quit", () => {
333
+ i = !0;
334
+ }), p.on("activate", () => {
335
+ m.getAllWindows().length === 0 ? o = v() : b.show();
336
+ }), p.on("second-instance", () => b.show()), process.on("message", (e) => {
337
+ if (e?.type === "cossack:renderer-reload") for (let e of m.getAllWindows()) e.webContents.reloadIgnoringCache();
338
+ }), b;
339
+ }
340
+ function U(e) {
341
+ return A(), E ??= H(e).catch((e) => {
342
+ throw E = void 0, e;
343
+ });
344
+ }
345
+ //#endregion
346
+ export { p as a, V as c, S as d, b as f, d as h, x as i, M as l, y as m, g as n, N as o, _ as p, v as r, U as s, m as t, h as u };
package/docs/guide.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # Cossack Desktop guide
2
2
 
3
- Add the Electron side target to a Cloudflare, Node, or Deno web application:
3
+ Add an Electron target to a Cloudflare or Node.js web application:
4
4
 
5
5
  ```sh
6
6
  cossack add desktop
@@ -10,7 +10,7 @@ pnpm desktop:dev
10
10
 
11
11
  The scaffold creates `src/desktop/index.ts`, `forge.config.ts`, platform icons,
12
12
  and build/package/make scripts. The Electron process always runs on Node even
13
- when the web adapter is Deno or Cloudflare. Bindings such as D1 do not exist in
13
+ when the web adapter is Cloudflare. Bindings such as D1 do not exist in
14
14
  Electron unless the application supplies an Electron-compatible equivalent.
15
15
 
16
16
  `createDesktopApp()` registers and serves `cossack://app`, injects `ASSETS` and
@@ -18,9 +18,20 @@ a window-scoped `COSSACK_DESKTOP`, and starts a sandboxed, context-isolated
18
18
  `BrowserWindow`. Use only HTTP-transport pages. Native work belongs in the
19
19
  bootstrap or ordinary `@Server()` methods:
20
20
 
21
- Do not top-level `await` `createDesktopApp()` from an ESM entry. Invoke an async
22
- `main()` without awaiting it at module scope so Electron can complete the first
23
- event-loop tick and emit `ready`.
21
+ Keep the generated `frameworkApp`, `env` and `startDesktop(factory)` exports.
22
+ Use the supplied factory to create the application and return its Desktop result.
23
+ Put native menus, tray and close handlers inside that bootstrap. The development
24
+ runner calls it once; only production calls it at module scope, guarded by
25
+ `if (!import.meta.env.DEV)`. Do not top-level `await` Desktop creation: Electron
26
+ must complete the first event-loop tick before it emits `ready`.
27
+
28
+ `desktop:dev` runs Vite inside Electron and keeps the renderer on `cossack://app`.
29
+ Page edits reload managed windows; native bootstrap, Vite config and root `.env*`
30
+ changes restart Electron. Page syntax repair recovers the development window. Reloads
31
+ reset in-memory modules, so store durable application data explicitly. The Vite
32
+ asset listener never dispatches native application actions over loopback HTTP.
33
+ Keep `ssr.noExternal: true` limited to `mode === 'desktop' && command === 'build'`.
34
+ See the [bootstrap example](../README.md) when migrating an existing entry.
24
35
 
25
36
  ```ts
26
37
  const shell = this.env.COSSACK_DESKTOP as DesktopShell;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cossackframework/desktop",
3
- "version": "0.8.2",
3
+ "version": "0.9.0",
4
4
  "type": "module",
5
5
  "description": "Secure Electron desktop runtime for Cossack applications",
6
6
  "license": "MIT",
@@ -29,17 +29,23 @@
29
29
  "access": "public"
30
30
  },
31
31
  "dependencies": {
32
- "@cossackframework/framework": "0.8.2"
32
+ "@cossackframework/core": "0.9.0"
33
33
  },
34
34
  "peerDependencies": {
35
- "electron": ">=37.0.0"
35
+ "electron": "^43.7.0 || >=44.4.0",
36
+ "vite": "^8.1.4"
36
37
  },
37
38
  "devDependencies": {
38
39
  "@types/node": "^22.19.0",
39
- "electron": "^43.3.0",
40
+ "electron": "^43.7.0",
40
41
  "typescript": "^7.0.2",
41
42
  "vite": "^8.1.4",
42
- "vitest": "^4.1.10"
43
+ "vitest": "^4.1.11"
44
+ },
45
+ "peerDependenciesMeta": {
46
+ "vite": {
47
+ "optional": true
48
+ }
43
49
  },
44
50
  "scripts": {
45
51
  "build": "vite build && tsc -p tsconfig.declarations.json && chmod +x dist/dev.js",