@n3rdw1z4rd/core 0.24.0 → 0.26.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 (54) hide show
  1. package/README.md +45 -0
  2. package/dist/astar.js +3 -3
  3. package/dist/desktop.d.ts +37 -0
  4. package/dist/desktop.js +14 -0
  5. package/dist/dungeon-generator.js +4 -4
  6. package/dist/electron/after-pack.cjs +17 -0
  7. package/dist/electron/index.d.ts +110 -0
  8. package/dist/electron/index.js +257 -0
  9. package/dist/electron/preload.cjs +12 -0
  10. package/dist/electron/updater.d.ts +81 -0
  11. package/dist/electron/updater.js +133 -0
  12. package/dist/electron.cjs +416 -0
  13. package/dist/electron.d.cts +189 -0
  14. package/dist/graph/index.d.ts +21 -0
  15. package/dist/graph/subgraph.js +1 -1
  16. package/dist/graph.cjs +2 -2
  17. package/dist/graph.d.cts +21 -0
  18. package/dist/index.cjs +25 -11
  19. package/dist/index.d.cts +48 -0
  20. package/dist/index.d.ts +13 -1
  21. package/dist/index.js +2 -1
  22. package/dist/map2d.js +2 -2
  23. package/dist/math.js +2 -2
  24. package/dist/{rng-edL6atS3.cjs → rng-BtvhTJmM.cjs} +2 -2
  25. package/dist/{spatial-partition-3d-D1uyJVhM.cjs → spatial-partition-3d-qhjqIpcy.cjs} +1 -1
  26. package/dist/three/adaptive-grid.d.ts +1 -1
  27. package/dist/three/adaptive-grid.js +1 -1
  28. package/dist/three/asteroid-mesh.d.ts +1 -1
  29. package/dist/three/camera-rig.js +1 -1
  30. package/dist/three/cube-sphere-geometry.d.ts +1 -1
  31. package/dist/three/index.d.ts +13 -2
  32. package/dist/three/particle-system-3d.js +1 -1
  33. package/dist/three/picking.d.ts +1 -1
  34. package/dist/three/picking.js +1 -1
  35. package/dist/three/starfield.js +4 -4
  36. package/dist/three/texture-atlas.d.ts +1 -1
  37. package/dist/three/texture-atlas.js +1 -1
  38. package/dist/three/texture-utils.js +2 -4
  39. package/dist/three/voxel-geometry.d.ts +44 -10
  40. package/dist/three/voxel-geometry.js +282 -77
  41. package/dist/three/voxel-mesh.d.ts +1 -1
  42. package/dist/three/voxel-mesh.js +1 -1
  43. package/dist/three/world.d.ts +1 -1
  44. package/dist/three/world.js +1 -1
  45. package/dist/three.cjs +290 -87
  46. package/dist/three.d.cts +55 -10
  47. package/dist/vite.cjs +124 -0
  48. package/dist/vite.d.cts +53 -2
  49. package/dist/vite.d.ts +53 -2
  50. package/dist/vite.js +122 -1
  51. package/dist/webgl.js +2 -2
  52. package/package.json +23 -3
  53. package/dist/input/_input.d.ts +0 -23
  54. package/dist/input/_input.js +0 -96
package/README.md CHANGED
@@ -125,6 +125,51 @@ Schemas are what let an editor work with components it has never seen: an inspec
125
125
 
126
126
  For editors: `EditorCamera` (orthographic or perspective; pan, zoom-at-cursor, orbit, fit, with `zoom` in screen px per world unit), `AdaptiveGrid` (a grid that keeps its spacing readable at any zoom), `pickEntity(world, camera, x, y)` (the entity under a screen point) and `Renderer` (a `WebGLRenderer` that uses the device pixel ratio and can size itself to its parent). Also: `CameraRig`, voxel meshing, texture atlases, `AsteroidMesh`, `CubeSphereGeometry`, a starfield and a 3D particle system.
127
127
 
128
+ ## Desktop apps (`@n3rdw1z4rd/core/electron`)
129
+
130
+ The Electron main process for turning a web build into a desktop app: the build served over its own `app://` origin (workers, `fetch` and localStorage behave as on the web), one window, one copy of the app at a time, links kept out of the window, localStorage written to disk before quitting, F11 for full screen, and optionally updating itself from the site the web build is on.
131
+
132
+ ```js
133
+ // electron/main.mjs (package.json: "main": "electron/main.mjs")
134
+ import { createDesktopApp } from "@n3rdw1z4rd/core/electron";
135
+
136
+ createDesktopApp({
137
+ title: "My Game",
138
+ root: new URL("../dist/", import.meta.url), // the Vite build
139
+ host: "my-game", // the page runs at app://my-game (its localStorage belongs to that)
140
+ profile: "game", // or "app": windowed, normal background throttling
141
+ update: { site: "https://my-game.example.com", api: 1 },
142
+ });
143
+ ```
144
+
145
+ The page gets `window.desktop`, typed and `undefined` in a browser:
146
+
147
+ ```ts
148
+ import { desktop } from "@n3rdw1z4rd/core";
149
+
150
+ if (desktop) {
151
+ quitButton.onclick = () => desktop.quit();
152
+ const { build } = await desktop.version();
153
+ }
154
+ ```
155
+
156
+ **Updating:** with `update` set, the app runs the newest complete build it has (one it downloaded, or the bundled one), then checks the site's `version.json`; if the site has a newer build that this app's `api` level can run, it downloads every file, checks each one's size and SHA-256, switches to it and reloads. Anything wrong and it carries on with what it has (see `desktop.log` in the app's user data folder). `--no-update` skips the check, `--bundled` runs the bundled build, `--windowed` starts windowed. Each build needs its `version.json`, from the `buildManifest()` Vite plugin:
157
+
158
+ ```ts
159
+ // vite.config.ts
160
+ import { buildId, buildManifest } from "@n3rdw1z4rd/core/vite";
161
+
162
+ export default defineConfig({
163
+ base: "./",
164
+ define: { __BUILD_ID__: JSON.stringify(buildId()) }, // "0.7.0-6ae4707": package.json's version and the commit
165
+ plugins: [buildManifest({ needs: 1 })],
166
+ });
167
+ ```
168
+
169
+ **Packaging** (electron-builder): the packaged main process imports core at run time, so list `@n3rdw1z4rd/core` in `dependencies`, not `devDependencies`. On Linux, `"afterPack": "node_modules/@n3rdw1z4rd/core/dist/electron/after-pack.cjs"` wraps the executable to start with `--no-sandbox`, which it needs when Steam launches it.
170
+
171
+ `npm run test:electron` runs a small app made with it in Electron (after `npm run build`; `xvfb-run -a npm run test:electron` without a display).
172
+
128
173
  ## Node graphs (`@n3rdw1z4rd/core/graph`)
129
174
 
130
175
  A graph document format, typed pins, node types (built-in or written as scripts) and a lazy, memoized evaluator. It has no DOM, so it runs in a page, a worker or Node.
package/dist/astar.js CHANGED
@@ -1,5 +1,5 @@
1
- import { SQRT2 } from "./math.js";
2
1
  import { Heap } from "heap-js";
2
+ import { SQRT2 } from "./math.js";
3
3
  // src/astar.ts
4
4
  const DEFAULT_MAX_NODES = 1e4;
5
5
  const DIRECTIONS = [
@@ -50,7 +50,7 @@ function findPath(start, goal, cost, options = {}) {
50
50
  const dy = Math.abs(y - goal.y);
51
51
  return diagonal ? Math.max(dx, dy) === 1 : dx + dy === 1;
52
52
  };
53
- const passable = (x, y) => cost(x, y) < Infinity;
53
+ const passable = (x, y) => cost(x, y) < 1e400;
54
54
  if (!adjacent && !partial && !passable(goal.x, goal.y) && !(start.x === goal.x && start.y === goal.y)) return [];
55
55
  let seq = 0;
56
56
  const open = new Heap((a, b) => a.f - b.f || a.h - b.h || a.seq - b.seq);
@@ -84,7 +84,7 @@ function findPath(start, goal, cost, options = {}) {
84
84
  const k = key(x, y);
85
85
  if (closed.has(k)) continue;
86
86
  const stepCost = cost(x, y);
87
- if (!(stepCost < Infinity)) continue;
87
+ if (!(stepCost < 1e400)) continue;
88
88
  const isDiagonal = dx !== 0 && dy !== 0;
89
89
  if (isDiagonal && !cutCorners && (!passable(current.x + dx, current.y) || !passable(current.x, current.y + dy))) continue;
90
90
  const g = current.g + (isDiagonal ? stepCost * SQRT2 : stepCost);
@@ -0,0 +1,37 @@
1
+ /**
2
+ * What the desktop app (`@n3rdw1z4rd/core/electron`) gives the page, as `window.desktop`.
3
+ *
4
+ * @category Desktop
5
+ */
6
+ export interface Desktop {
7
+ /** the site the app was built for (its servers: the page's own origin is app://...); '' if none */
8
+ readonly site: string;
9
+ /** close the app (there's no browser tab to close) */
10
+ quit(): void;
11
+ /** full screen on and off (F11 does too) */
12
+ toggleFullscreen(): void;
13
+ /** the build running (and when it was built), the app's own version and desktop API level, and whether the site has a build that needs a newer app */
14
+ version(): Promise<{
15
+ build: string;
16
+ builtAt: string;
17
+ app: string;
18
+ api: number;
19
+ needsNewerApp: boolean;
20
+ }>;
21
+ /** "Updated to ..." once, right after an update has reloaded the page; otherwise null */
22
+ updateNote(): Promise<string | null>;
23
+ /** look for a newer build now: true if there was one (the page is reloading into it) */
24
+ update(): Promise<boolean>;
25
+ }
26
+ /**
27
+ * The desktop app's {@link Desktop} when running in it; undefined in a browser (and outside one).
28
+ *
29
+ * ```ts
30
+ * import { desktop } from '@n3rdw1z4rd/core';
31
+ *
32
+ * if (desktop) quitButton.onclick = () => desktop.quit();
33
+ * ```
34
+ *
35
+ * @category Desktop
36
+ */
37
+ export declare const desktop: Desktop | undefined;
@@ -0,0 +1,14 @@
1
+ // src/desktop.ts
2
+ /**
3
+ * The desktop app's {@link Desktop} when running in it; undefined in a browser (and outside one).
4
+ *
5
+ * ```ts
6
+ * import { desktop } from '@n3rdw1z4rd/core';
7
+ *
8
+ * if (desktop) quitButton.onclick = () => desktop.quit();
9
+ * ```
10
+ *
11
+ * @category Desktop
12
+ */
13
+ const desktop = typeof window === "undefined" ? void 0 : window.desktop;
14
+ export { desktop };
@@ -1,10 +1,10 @@
1
1
  import { findPath } from "./astar.js";
2
+ import { Heap } from "heap-js";
2
3
  import { Map2D } from "./map2d.js";
3
4
  import { rng } from "./rng.js";
4
5
  import { log } from "./log.js";
5
6
  import { distance2d, squaredDistance } from "./math.js";
6
7
  import { Rectangle } from "./rectangle.js";
7
- import { Heap } from "heap-js";
8
8
  // src/dungeon-generator.ts
9
9
  /**
10
10
  * Tile value for empty (unused) space.
@@ -178,7 +178,7 @@ function _getShortestPathBetweenRects(rectA, rectB) {
178
178
  let paths = {
179
179
  a: edgeA[0],
180
180
  b: edgeB[0],
181
- distance: Infinity
181
+ distance: 1e400
182
182
  };
183
183
  for (const a of edgeA) for (const b of edgeB) {
184
184
  const d = distance2d(a.x, a.y, b.x, b.y);
@@ -195,13 +195,13 @@ function _getShortestPathBetweenRects(rectA, rectB) {
195
195
  }
196
196
  function _generatePaths(map, rooms, params = {}) {
197
197
  const walkable = params.walkableValues ?? [map.defaultValue];
198
- const cost = (x, y) => walkable.includes(map.get(x, y)) ? 1 : Infinity;
198
+ const cost = (x, y) => walkable.includes(map.get(x, y)) ? 1 : 1e400;
199
199
  const paths = [];
200
200
  _generateMST(rooms, params).forEach((rects) => {
201
201
  const { a, b } = _getShortestPathBetweenRects(rects.a, rects.b);
202
202
  paths.push(findPath(a, b, cost, {
203
203
  adjacent: true,
204
- maxNodes: Infinity
204
+ maxNodes: 1e400
205
205
  }));
206
206
  });
207
207
  return paths;
@@ -0,0 +1,17 @@
1
+ // electron-builder afterPack hook (package.json: "build": { "afterPack": "node_modules/@n3rdw1z4rd/core/dist/electron/after-pack.cjs" }).
2
+ // On Linux the app's executable becomes a small script that starts the real one (renamed .bin) with --no-sandbox:
3
+ // launched by Steam (as a non-Steam game, on a Steam Deck, Bazzite...) Chromium's sandbox can't start and the app
4
+ // closes before it opens. Apps made with @n3rdw1z4rd/core/electron only load their own files (app://), so they give
5
+ // nothing up without it.
6
+ const fs = require('node:fs');
7
+ const path = require('node:path');
8
+
9
+ exports.default = async function afterPack(context) {
10
+ if (context.electronPlatformName !== 'linux') return;
11
+
12
+ const name = context.packager.executableName;
13
+ const exe = path.join(context.appOutDir, name);
14
+
15
+ fs.renameSync(exe, `${exe}.bin`);
16
+ fs.writeFileSync(exe, `#!/bin/sh\nexec "$(dirname "$(readlink -f "$0")")/${name}.bin" --no-sandbox "$@"\n`, { mode: 0o755 });
17
+ };
@@ -0,0 +1,110 @@
1
+ /**
2
+ * The Electron main process for a web build as a desktop app: the build served over its own
3
+ * `app://` origin (so workers, fetch and localStorage behave as on the web), one window, one copy
4
+ * of the app at a time, links kept out of it, localStorage written to disk before quitting, and
5
+ * optionally updating itself from the site the web build is on.
6
+ *
7
+ * ```js
8
+ * // electron/main.mjs (package.json: "main": "electron/main.mjs")
9
+ * import { createDesktopApp } from '@n3rdw1z4rd/core/electron';
10
+ *
11
+ * createDesktopApp({
12
+ * title: 'My Game',
13
+ * root: new URL('../dist/', import.meta.url),
14
+ * update: { site: 'https://my-game.example.com' },
15
+ * });
16
+ * ```
17
+ *
18
+ * The page gets {@link Desktop} as `window.desktop` (see `desktop` in the main entry point). The
19
+ * packaged app needs `@n3rdw1z4rd/core` at run time: list it in `dependencies`. Node-only: not
20
+ * exported from the package root.
21
+ *
22
+ * @packageDocumentation
23
+ * @module @n3rdw1z4rd/core/electron
24
+ */
25
+ import { BrowserWindow, MenuItemConstructorOptions } from "electron";
26
+ import { BuildManifest, FetchLike, PickedBuild, UpdateOptions, UpdateResult, downloadUpdate, isUpdateSite, pickBuild, readBuild } from "./updater.js";
27
+ /** @category Desktop */
28
+ export interface DesktopAppOptions {
29
+ /** the window's title, and the name on log lines */
30
+ title: string;
31
+ /** the bundled web build: a folder with index.html (a path, or a file: URL) */
32
+ root: string | URL;
33
+ /**
34
+ * the host of the page's origin, `app://<host>`. The page's localStorage belongs to its
35
+ * origin: changing this later loses what's saved. Default `'app'`.
36
+ */
37
+ host?: string;
38
+ /**
39
+ * `'game'` (default): full-screen the first time, then as it was left; sound without a click
40
+ * first; full speed when the window is behind another one. `'app'`: windowed, and Chromium's
41
+ * usual throttling in the background.
42
+ */
43
+ profile?: 'game' | 'app';
44
+ window?: {
45
+ width?: number;
46
+ height?: number;
47
+ minWidth?: number;
48
+ minHeight?: number;
49
+ /** shown before the page draws; default '#000000' */
50
+ backgroundColor?: string;
51
+ /** relative to `root`; default 'icon-512.png' (if it's there) */
52
+ icon?: string;
53
+ /** `'remember'`: as it was left (F11, or `desktop.toggleFullscreen()`), `first` the first time. Default: `'game'` remembers (full-screen first), `'app'` doesn't */
54
+ fullscreen?: boolean | {
55
+ remember: true;
56
+ first: boolean;
57
+ };
58
+ };
59
+ /** the window's menu; default none */
60
+ menu?: MenuItemConstructorOptions[] | null;
61
+ /** links out of the app: `'browser'` (default) opens https links in the user's browser, `'deny'` opens nothing */
62
+ links?: 'browser' | 'deny';
63
+ /** draw WebGL in software (SwiftShader) where Chromium finds no usable graphics card, rather than not at all. Default true */
64
+ softwareWebGL?: boolean;
65
+ /** the site the page is told about (`desktop.site`); default `update.site` */
66
+ site?: string;
67
+ /**
68
+ * Updating itself from `site`: at start-up it runs the newest complete build it has (one it
69
+ * downloaded, or the bundled one), then looks for a newer one, downloads and checks it, and
70
+ * reloads into it. `--no-update` turns that off for one run, `--bundled` runs the bundled build.
71
+ * Needs `version.json` in each build: see `buildManifest()` in `@n3rdw1z4rd/core/vite`.
72
+ */
73
+ update?: false | {
74
+ /** https://host[:port] the builds come from */
75
+ site: string;
76
+ /** this app's desktop API level: a build that needs more waits for a rebuilt app. Default 1 */
77
+ api?: number;
78
+ /** folder in the app's user data for downloaded builds; default 'builds' */
79
+ folder?: string;
80
+ /** check as soon as the window opens; default true (`desktop.update()` checks any time) */
81
+ onStart?: boolean;
82
+ };
83
+ /** environment variable that overrides the site (update and `desktop.site`) for testing, e.g. 'MY_GAME_SITE' */
84
+ siteEnv?: string;
85
+ /** environment variable that, set to 1, starts windowed (as `--windowed` does) */
86
+ windowedEnv?: string;
87
+ /** the preload script; default core's (which gives the page {@link Desktop}) */
88
+ preload?: string;
89
+ }
90
+ /** What {@link createDesktopApp} returns. */
91
+ export interface DesktopApp {
92
+ /** resolves with the window once it's open */
93
+ readonly ready: Promise<BrowserWindow>;
94
+ /** the window, once it's open */
95
+ readonly window: BrowserWindow | undefined;
96
+ /** the build running now */
97
+ readonly build: PickedBuild;
98
+ /** look for a newer build now; got one: switch to it and reload. Resolves true if it did */
99
+ checkForUpdate(): Promise<boolean>;
100
+ /** to the console and to desktop.log in the app's user data folder */
101
+ log(message: string): void;
102
+ }
103
+ /**
104
+ * Starts the desktop app. Call it once, straight away at start-up (it registers the `app://`
105
+ * scheme, which Electron only allows before the app is ready).
106
+ *
107
+ * @category Desktop
108
+ */
109
+ export declare function createDesktopApp(options: DesktopAppOptions): DesktopApp;
110
+ export { BuildManifest, FetchLike, PickedBuild, UpdateOptions, UpdateResult, downloadUpdate, isUpdateSite, pickBuild, readBuild };
@@ -0,0 +1,257 @@
1
+ import * as fs from "node:fs";
2
+ import * as path from "node:path";
3
+ import { BrowserWindow, Menu, app, ipcMain, net, protocol, session, shell } from "electron";
4
+ import { fileURLToPath, pathToFileURL } from "node:url";
5
+ import { downloadUpdate, isUpdateSite, pickBuild, readBuild } from "./updater.js";
6
+ // src/electron/index.ts
7
+ /**
8
+ * The Electron main process for a web build as a desktop app: the build served over its own
9
+ * `app://` origin (so workers, fetch and localStorage behave as on the web), one window, one copy
10
+ * of the app at a time, links kept out of it, localStorage written to disk before quitting, and
11
+ * optionally updating itself from the site the web build is on.
12
+ *
13
+ * ```js
14
+ * // electron/main.mjs (package.json: "main": "electron/main.mjs")
15
+ * import { createDesktopApp } from '@n3rdw1z4rd/core/electron';
16
+ *
17
+ * createDesktopApp({
18
+ * title: 'My Game',
19
+ * root: new URL('../dist/', import.meta.url),
20
+ * update: { site: 'https://my-game.example.com' },
21
+ * });
22
+ * ```
23
+ *
24
+ * The page gets {@link Desktop} as `window.desktop` (see `desktop` in the main entry point). The
25
+ * packaged app needs `@n3rdw1z4rd/core` at run time: list it in `dependencies`. Node-only: not
26
+ * exported from the package root.
27
+ *
28
+ * @packageDocumentation
29
+ * @module @n3rdw1z4rd/core/electron
30
+ */
31
+ const isFile = (file) => {
32
+ try {
33
+ return fs.statSync(file).isFile();
34
+ } catch {
35
+ return false;
36
+ }
37
+ };
38
+ const toPath = (p) => p instanceof URL ? fileURLToPath(p) : path.resolve(p);
39
+ /** this module's own folder, in the ESM build (dist/electron/) and the CJS one (dist/) alike */
40
+ function defaultPreload() {
41
+ const here = typeof __dirname === "string" ? __dirname : path.dirname(fileURLToPath(import.meta.url));
42
+ const beside = path.join(here, "preload.cjs");
43
+ return fs.existsSync(beside) ? beside : path.join(here, "electron", "preload.cjs");
44
+ }
45
+ /**
46
+ * Starts the desktop app. Call it once, straight away at start-up (it registers the `app://`
47
+ * scheme, which Electron only allows before the app is ready).
48
+ *
49
+ * @category Desktop
50
+ */
51
+ function createDesktopApp(options) {
52
+ const title = options.title;
53
+ const bundledDir = toPath(options.root).replace(/[\\/]+$/, "");
54
+ const host = options.host ?? "app";
55
+ const origin = `app://${host}`;
56
+ const game = (options.profile ?? "game") === "game";
57
+ const argv = process.argv;
58
+ const siteOverride = options.siteEnv ? process.env[options.siteEnv] ?? "" : "";
59
+ const update = options.update || void 0;
60
+ const site = (siteOverride || update?.site || options.site || "").replace(/\/+$/, "");
61
+ const api = update?.api ?? 1;
62
+ const noUpdate = !update || argv.includes("--no-update");
63
+ const bundledOnly = !update || argv.includes("--bundled");
64
+ const forceWindowed = argv.includes("--windowed") || !!options.windowedEnv && process.env[options.windowedEnv] === "1";
65
+ const store = () => path.join(app.getPath("userData"), update?.folder ?? "builds");
66
+ const windowFile = () => path.join(app.getPath("userData"), "window.json");
67
+ const log = (message) => {
68
+ console.log(`[${title}] ${message}`);
69
+ try {
70
+ fs.mkdirSync(app.getPath("userData"), { recursive: true });
71
+ fs.appendFileSync(path.join(app.getPath("userData"), "desktop.log"), `${(/* @__PURE__ */ new Date()).toISOString()} ${message}\n`);
72
+ } catch {}
73
+ };
74
+ protocol.registerSchemesAsPrivileged([{
75
+ scheme: "app",
76
+ privileges: {
77
+ standard: true,
78
+ secure: true,
79
+ supportFetchAPI: true,
80
+ corsEnabled: true,
81
+ stream: true
82
+ }
83
+ }]);
84
+ if (game) app.commandLine.appendSwitch("autoplay-policy", "no-user-gesture-required");
85
+ if (options.softwareWebGL ?? true) app.commandLine.appendSwitch("enable-unsafe-swiftshader");
86
+ if (!app.requestSingleInstanceLock()) app.quit();
87
+ let build = pickBuild({
88
+ bundledDir,
89
+ store: store(),
90
+ api,
91
+ bundledOnly
92
+ });
93
+ let win;
94
+ /** what to tell the page after an update's reloaded it (once) */
95
+ let note = null;
96
+ let needsNewerApp = false;
97
+ const fullscreen = options.window?.fullscreen ?? (game ? {
98
+ remember: true,
99
+ first: true
100
+ } : false);
101
+ const remembering = typeof fullscreen === "object" && !forceWindowed;
102
+ const startFullscreen = () => {
103
+ if (forceWindowed) return false;
104
+ if (typeof fullscreen === "boolean") return fullscreen;
105
+ try {
106
+ return JSON.parse(fs.readFileSync(windowFile(), "utf8")).fullscreen ?? fullscreen.first;
107
+ } catch {
108
+ return fullscreen.first;
109
+ }
110
+ };
111
+ const rememberFullscreen = (on) => {
112
+ if (!remembering) return;
113
+ try {
114
+ fs.writeFileSync(windowFile(), JSON.stringify({ fullscreen: on }));
115
+ } catch {}
116
+ };
117
+ let checking;
118
+ const checkForUpdate = () => {
119
+ if (noUpdate || bundledOnly) return Promise.resolve(false);
120
+ if (!site) {
121
+ log("not updating: no site");
122
+ return Promise.resolve(false);
123
+ }
124
+ checking ??= (async () => {
125
+ try {
126
+ fs.mkdirSync(store(), { recursive: true });
127
+ const result = await downloadUpdate({
128
+ site,
129
+ store: store(),
130
+ current: build,
131
+ bundledDir,
132
+ api,
133
+ log,
134
+ fetch: (url, init) => net.fetch(url, init)
135
+ });
136
+ if (result.status === "needs-newer-app") needsNewerApp = true;
137
+ if (result.status !== "updated") return false;
138
+ build = pickBuild({
139
+ bundledDir,
140
+ store: store(),
141
+ api
142
+ });
143
+ note = `Updated to ${result.version}`;
144
+ win?.webContents.reloadIgnoringCache();
145
+ return true;
146
+ } finally {
147
+ checking = void 0;
148
+ }
149
+ })();
150
+ return checking;
151
+ };
152
+ let resolveReady;
153
+ const ready = new Promise((resolve) => {
154
+ resolveReady = resolve;
155
+ });
156
+ function createWindow() {
157
+ const iconFile = path.join(bundledDir, options.window?.icon ?? "icon-512.png");
158
+ const w = new BrowserWindow({
159
+ width: options.window?.width ?? 1280,
160
+ height: options.window?.height ?? 800,
161
+ minWidth: options.window?.minWidth,
162
+ minHeight: options.window?.minHeight,
163
+ fullscreen: startFullscreen(),
164
+ backgroundColor: options.window?.backgroundColor ?? "#000000",
165
+ title,
166
+ icon: fs.existsSync(iconFile) ? iconFile : void 0,
167
+ autoHideMenuBar: !options.menu,
168
+ webPreferences: {
169
+ preload: options.preload ?? defaultPreload(),
170
+ backgroundThrottling: !game,
171
+ contextIsolation: true,
172
+ sandbox: true
173
+ }
174
+ });
175
+ w.setMenu(options.menu ? Menu.buildFromTemplate(options.menu) : null);
176
+ w.on("enter-full-screen", () => rememberFullscreen(true));
177
+ w.on("leave-full-screen", () => rememberFullscreen(false));
178
+ w.webContents.on("before-input-event", (e, input) => {
179
+ if (input.type === "keyDown" && input.key === "F11") {
180
+ w.setFullScreen(!w.isFullScreen());
181
+ e.preventDefault();
182
+ }
183
+ });
184
+ w.webContents.setWindowOpenHandler(({ url }) => {
185
+ if ((options.links ?? "browser") === "browser" && /^https:\/\//.test(url)) shell.openExternal(url);
186
+ return { action: "deny" };
187
+ });
188
+ w.webContents.on("will-navigate", (e, url) => {
189
+ if (!url.startsWith(`${origin}/`)) e.preventDefault();
190
+ });
191
+ w.loadURL(`${origin}/index.html`);
192
+ return w;
193
+ }
194
+ app.on("second-instance", () => {
195
+ if (!win) return;
196
+ if (win.isMinimized()) win.restore();
197
+ win.focus();
198
+ });
199
+ app.whenReady().then(() => {
200
+ log(`running ${build.info.version} (${build.dir === bundledDir ? "bundled" : "downloaded"})`);
201
+ protocol.handle("app", (request) => {
202
+ const url = new URL(request.url);
203
+ if (url.host !== host) return new Response("not found", { status: 404 });
204
+ const file = path.normalize(path.join(build.dir, decodeURIComponent(url.pathname)));
205
+ if (!file.startsWith(build.dir + path.sep) || !isFile(file)) return new Response("not found", { status: 404 });
206
+ return net.fetch(pathToFileURL(file).toString());
207
+ });
208
+ ipcMain.on("desktop:quit", () => app.quit());
209
+ ipcMain.on("desktop:fullscreen", () => win?.setFullScreen(!win.isFullScreen()));
210
+ ipcMain.on("desktop:site", (e) => {
211
+ e.returnValue = isUpdateSite(site) ? site : "";
212
+ });
213
+ ipcMain.handle("desktop:version", () => ({
214
+ build: build.info.version,
215
+ builtAt: build.info.builtAt,
216
+ app: app.getVersion(),
217
+ api,
218
+ needsNewerApp
219
+ }));
220
+ ipcMain.handle("desktop:update-note", () => {
221
+ const n = note;
222
+ note = null;
223
+ return n;
224
+ });
225
+ ipcMain.handle("desktop:update", () => checkForUpdate());
226
+ win = createWindow();
227
+ resolveReady(win);
228
+ if (update && (update.onStart ?? true)) checkForUpdate();
229
+ });
230
+ app.on("window-all-closed", () => app.quit());
231
+ const flush = () => {
232
+ try {
233
+ session.defaultSession.flushStorageData();
234
+ } catch {}
235
+ };
236
+ let flushed = false;
237
+ app.on("before-quit", (e) => {
238
+ if (flushed) return;
239
+ e.preventDefault();
240
+ flushed = true;
241
+ flush();
242
+ setTimeout(() => app.quit(), 300);
243
+ });
244
+ app.whenReady().then(() => setInterval(flush, 5e3));
245
+ return {
246
+ ready,
247
+ get window() {
248
+ return win;
249
+ },
250
+ get build() {
251
+ return build;
252
+ },
253
+ checkForUpdate,
254
+ log
255
+ };
256
+ }
257
+ export { createDesktopApp, downloadUpdate, isUpdateSite, pickBuild, readBuild };
@@ -0,0 +1,12 @@
1
+ // @n3rdw1z4rd/core/electron's preload: gives the page window.desktop (see Desktop in @n3rdw1z4rd/core). A sandboxed
2
+ // preload can only require('electron'), so this file stands alone.
3
+ const { contextBridge, ipcRenderer } = require('electron');
4
+
5
+ contextBridge.exposeInMainWorld('desktop', {
6
+ site: ipcRenderer.sendSync('desktop:site'),
7
+ quit: () => ipcRenderer.send('desktop:quit'),
8
+ toggleFullscreen: () => ipcRenderer.send('desktop:fullscreen'),
9
+ version: () => ipcRenderer.invoke('desktop:version'),
10
+ updateNote: () => ipcRenderer.invoke('desktop:update-note'),
11
+ update: () => ipcRenderer.invoke('desktop:update'),
12
+ });
@@ -0,0 +1,81 @@
1
+ /**
2
+ * A build's `version.json`, as {@link buildManifest} (in `@n3rdw1z4rd/core/vite`) writes it: which
3
+ * build it is, when it was built, the desktop API level it needs, and every file in it.
4
+ *
5
+ * @category Desktop
6
+ */
7
+ export interface BuildManifest {
8
+ /** the build's id, e.g. "0.7.0-6ae4707": letters, digits, dots and dashes (it names a folder) */
9
+ version: string;
10
+ /** ISO time it was built: a build is newer if it was built later */
11
+ builtAt: string;
12
+ /** the desktop API level it needs (the app's `api` must be at least this); default 1 */
13
+ needs?: number;
14
+ /** every file but version.json itself, paths relative to the build, with `/` */
15
+ files: {
16
+ path: string;
17
+ size: number;
18
+ sha256: string;
19
+ }[];
20
+ }
21
+ /** A build to run: its folder and its manifest (without `files` if it has no version.json: a dev build). */
22
+ export interface PickedBuild {
23
+ dir: string;
24
+ info: Pick<BuildManifest, 'version' | 'builtAt'> & Partial<BuildManifest>;
25
+ }
26
+ /** The part of `fetch`'s response the updater uses. */
27
+ export interface FetchLike {
28
+ (url: string, init: {
29
+ signal: AbortSignal;
30
+ cache?: 'no-store';
31
+ }): Promise<{
32
+ ok: boolean;
33
+ status: number;
34
+ arrayBuffer(): Promise<ArrayBuffer>;
35
+ }>;
36
+ }
37
+ export interface UpdateOptions {
38
+ /** where builds come from: https://host[:port] (http only for localhost) */
39
+ site: string;
40
+ /** where downloaded builds are kept: one folder each, and current.json naming the one to run */
41
+ store: string;
42
+ /** the build running now */
43
+ current: PickedBuild;
44
+ /** the folder of the build that came with the app (never deleted) */
45
+ bundledDir: string;
46
+ /** this app's desktop API level */
47
+ api: number;
48
+ fetch: FetchLike;
49
+ /** ms to wait for version.json; default 15000 (each file gets 60000) */
50
+ timeout?: number;
51
+ log?: (message: string) => void;
52
+ }
53
+ export type UpdateResult = {
54
+ status: 'updated';
55
+ version: string;
56
+ } | {
57
+ status: 'up-to-date' | 'not-newer' | 'needs-newer-app' | 'unavailable' | 'failed';
58
+ reason: string;
59
+ };
60
+ /** Whether `site` is one builds may come from: https, or http on localhost (for tests). */
61
+ export declare function isUpdateSite(site: string): boolean;
62
+ /** A build folder's manifest, if the build is complete (version.json is written last). */
63
+ export declare function readBuild(dir: string): BuildManifest | undefined;
64
+ /**
65
+ * The build to run: the downloaded one `store/current.json` names, if it's complete, works with
66
+ * this app's `api` and is no older than the bundled one (a rebuilt app brings a newer build);
67
+ * otherwise the bundled one.
68
+ */
69
+ export declare function pickBuild(options: {
70
+ bundledDir: string;
71
+ store: string;
72
+ api: number;
73
+ bundledOnly?: boolean;
74
+ }): PickedBuild;
75
+ /**
76
+ * Looks for a newer build on `site`. If there is one (built later than the one running, and not
77
+ * needing a newer app), downloads all of it into a folder of its own, checks every file's size
78
+ * and SHA-256, and only then makes it current (current.json), keeping the build that was running
79
+ * and removing older ones. Anything wrong (offline, a bad file) and nothing changes.
80
+ */
81
+ export declare function downloadUpdate(options: UpdateOptions): Promise<UpdateResult>;