@n3rdw1z4rd/core 0.25.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.
@@ -0,0 +1,189 @@
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
+ /**
27
+ * A build's `version.json`, as {@link buildManifest} (in `@n3rdw1z4rd/core/vite`) writes it: which
28
+ * build it is, when it was built, the desktop API level it needs, and every file in it.
29
+ *
30
+ * @category Desktop
31
+ */
32
+ export interface BuildManifest {
33
+ /** the build's id, e.g. "0.7.0-6ae4707": letters, digits, dots and dashes (it names a folder) */
34
+ version: string;
35
+ /** ISO time it was built: a build is newer if it was built later */
36
+ builtAt: string;
37
+ /** the desktop API level it needs (the app's `api` must be at least this); default 1 */
38
+ needs?: number;
39
+ /** every file but version.json itself, paths relative to the build, with `/` */
40
+ files: {
41
+ path: string;
42
+ size: number;
43
+ sha256: string;
44
+ }[];
45
+ }
46
+ /** A build to run: its folder and its manifest (without `files` if it has no version.json: a dev build). */
47
+ export interface PickedBuild {
48
+ dir: string;
49
+ info: Pick<BuildManifest, 'version' | 'builtAt'> & Partial<BuildManifest>;
50
+ }
51
+ /** The part of `fetch`'s response the updater uses. */
52
+ export interface FetchLike {
53
+ (url: string, init: {
54
+ signal: AbortSignal;
55
+ cache?: 'no-store';
56
+ }): Promise<{
57
+ ok: boolean;
58
+ status: number;
59
+ arrayBuffer(): Promise<ArrayBuffer>;
60
+ }>;
61
+ }
62
+ export interface UpdateOptions {
63
+ /** where builds come from: https://host[:port] (http only for localhost) */
64
+ site: string;
65
+ /** where downloaded builds are kept: one folder each, and current.json naming the one to run */
66
+ store: string;
67
+ /** the build running now */
68
+ current: PickedBuild;
69
+ /** the folder of the build that came with the app (never deleted) */
70
+ bundledDir: string;
71
+ /** this app's desktop API level */
72
+ api: number;
73
+ fetch: FetchLike;
74
+ /** ms to wait for version.json; default 15000 (each file gets 60000) */
75
+ timeout?: number;
76
+ log?: (message: string) => void;
77
+ }
78
+ export type UpdateResult = {
79
+ status: 'updated';
80
+ version: string;
81
+ } | {
82
+ status: 'up-to-date' | 'not-newer' | 'needs-newer-app' | 'unavailable' | 'failed';
83
+ reason: string;
84
+ };
85
+ /** Whether `site` is one builds may come from: https, or http on localhost (for tests). */
86
+ export declare function isUpdateSite(site: string): boolean;
87
+ /** A build folder's manifest, if the build is complete (version.json is written last). */
88
+ export declare function readBuild(dir: string): BuildManifest | undefined;
89
+ /**
90
+ * The build to run: the downloaded one `store/current.json` names, if it's complete, works with
91
+ * this app's `api` and is no older than the bundled one (a rebuilt app brings a newer build);
92
+ * otherwise the bundled one.
93
+ */
94
+ export declare function pickBuild(options: {
95
+ bundledDir: string;
96
+ store: string;
97
+ api: number;
98
+ bundledOnly?: boolean;
99
+ }): PickedBuild;
100
+ /**
101
+ * Looks for a newer build on `site`. If there is one (built later than the one running, and not
102
+ * needing a newer app), downloads all of it into a folder of its own, checks every file's size
103
+ * and SHA-256, and only then makes it current (current.json), keeping the build that was running
104
+ * and removing older ones. Anything wrong (offline, a bad file) and nothing changes.
105
+ */
106
+ export declare function downloadUpdate(options: UpdateOptions): Promise<UpdateResult>;
107
+ /** @category Desktop */
108
+ export interface DesktopAppOptions {
109
+ /** the window's title, and the name on log lines */
110
+ title: string;
111
+ /** the bundled web build: a folder with index.html (a path, or a file: URL) */
112
+ root: string | URL;
113
+ /**
114
+ * the host of the page's origin, `app://<host>`. The page's localStorage belongs to its
115
+ * origin: changing this later loses what's saved. Default `'app'`.
116
+ */
117
+ host?: string;
118
+ /**
119
+ * `'game'` (default): full-screen the first time, then as it was left; sound without a click
120
+ * first; full speed when the window is behind another one. `'app'`: windowed, and Chromium's
121
+ * usual throttling in the background.
122
+ */
123
+ profile?: 'game' | 'app';
124
+ window?: {
125
+ width?: number;
126
+ height?: number;
127
+ minWidth?: number;
128
+ minHeight?: number;
129
+ /** shown before the page draws; default '#000000' */
130
+ backgroundColor?: string;
131
+ /** relative to `root`; default 'icon-512.png' (if it's there) */
132
+ icon?: string;
133
+ /** `'remember'`: as it was left (F11, or `desktop.toggleFullscreen()`), `first` the first time. Default: `'game'` remembers (full-screen first), `'app'` doesn't */
134
+ fullscreen?: boolean | {
135
+ remember: true;
136
+ first: boolean;
137
+ };
138
+ };
139
+ /** the window's menu; default none */
140
+ menu?: MenuItemConstructorOptions[] | null;
141
+ /** links out of the app: `'browser'` (default) opens https links in the user's browser, `'deny'` opens nothing */
142
+ links?: 'browser' | 'deny';
143
+ /** draw WebGL in software (SwiftShader) where Chromium finds no usable graphics card, rather than not at all. Default true */
144
+ softwareWebGL?: boolean;
145
+ /** the site the page is told about (`desktop.site`); default `update.site` */
146
+ site?: string;
147
+ /**
148
+ * Updating itself from `site`: at start-up it runs the newest complete build it has (one it
149
+ * downloaded, or the bundled one), then looks for a newer one, downloads and checks it, and
150
+ * reloads into it. `--no-update` turns that off for one run, `--bundled` runs the bundled build.
151
+ * Needs `version.json` in each build: see `buildManifest()` in `@n3rdw1z4rd/core/vite`.
152
+ */
153
+ update?: false | {
154
+ /** https://host[:port] the builds come from */
155
+ site: string;
156
+ /** this app's desktop API level: a build that needs more waits for a rebuilt app. Default 1 */
157
+ api?: number;
158
+ /** folder in the app's user data for downloaded builds; default 'builds' */
159
+ folder?: string;
160
+ /** check as soon as the window opens; default true (`desktop.update()` checks any time) */
161
+ onStart?: boolean;
162
+ };
163
+ /** environment variable that overrides the site (update and `desktop.site`) for testing, e.g. 'MY_GAME_SITE' */
164
+ siteEnv?: string;
165
+ /** environment variable that, set to 1, starts windowed (as `--windowed` does) */
166
+ windowedEnv?: string;
167
+ /** the preload script; default core's (which gives the page {@link Desktop}) */
168
+ preload?: string;
169
+ }
170
+ /** What {@link createDesktopApp} returns. */
171
+ export interface DesktopApp {
172
+ /** resolves with the window once it's open */
173
+ readonly ready: Promise<BrowserWindow>;
174
+ /** the window, once it's open */
175
+ readonly window: BrowserWindow | undefined;
176
+ /** the build running now */
177
+ readonly build: PickedBuild;
178
+ /** look for a newer build now; got one: switch to it and reload. Resolves true if it did */
179
+ checkForUpdate(): Promise<boolean>;
180
+ /** to the console and to desktop.log in the app's user data folder */
181
+ log(message: string): void;
182
+ }
183
+ /**
184
+ * Starts the desktop app. Call it once, straight away at start-up (it registers the `app://`
185
+ * scheme, which Electron only allows before the app is ready).
186
+ *
187
+ * @category Desktop
188
+ */
189
+ export declare function createDesktopApp(options: DesktopAppOptions): DesktopApp;
package/dist/index.cjs CHANGED
@@ -536,6 +536,19 @@ function buildColorPalette(grayscaleSteps = 8, colorSteps = 4, ...colors) {
536
536
  for (const rgb of colorList) palette.push(...colorRamp(rgb, colorSteps));
537
537
  return palette;
538
538
  }
539
+ // src/desktop.ts
540
+ /**
541
+ * The desktop app's {@link Desktop} when running in it; undefined in a browser (and outside one).
542
+ *
543
+ * ```ts
544
+ * import { desktop } from '@n3rdw1z4rd/core';
545
+ *
546
+ * if (desktop) quitButton.onclick = () => desktop.quit();
547
+ * ```
548
+ *
549
+ * @category Desktop
550
+ */
551
+ const desktop = typeof window === "undefined" ? void 0 : window.desktop;
539
552
  // src/disposable.ts
540
553
  /**
541
554
  * Collects cleanup functions (e.g. the unsubscribe functions returned by {@link Observable.subscribe}
@@ -4093,6 +4106,7 @@ exports.buildColorPalette = buildColorPalette;
4093
4106
  exports.clamp = require_rng.clamp;
4094
4107
  exports.controlId = controlId;
4095
4108
  exports.degrees = require_rng.degrees;
4109
+ exports.desktop = desktop;
4096
4110
  exports.distance2d = require_rng.distance2d;
4097
4111
  exports.distance3d = require_rng.distance3d;
4098
4112
  exports.ecs = ecs;
package/dist/index.d.cts CHANGED
@@ -360,6 +360,43 @@ export declare class Color {
360
360
  /** new fully transparent black (0, 0, 0, 0) */
361
361
  static get TRANSPARENT(): Color;
362
362
  }
363
+ /**
364
+ * What the desktop app (`@n3rdw1z4rd/core/electron`) gives the page, as `window.desktop`.
365
+ *
366
+ * @category Desktop
367
+ */
368
+ export interface Desktop {
369
+ /** the site the app was built for (its servers: the page's own origin is app://...); '' if none */
370
+ readonly site: string;
371
+ /** close the app (there's no browser tab to close) */
372
+ quit(): void;
373
+ /** full screen on and off (F11 does too) */
374
+ toggleFullscreen(): void;
375
+ /** 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 */
376
+ version(): Promise<{
377
+ build: string;
378
+ builtAt: string;
379
+ app: string;
380
+ api: number;
381
+ needsNewerApp: boolean;
382
+ }>;
383
+ /** "Updated to ..." once, right after an update has reloaded the page; otherwise null */
384
+ updateNote(): Promise<string | null>;
385
+ /** look for a newer build now: true if there was one (the page is reloading into it) */
386
+ update(): Promise<boolean>;
387
+ }
388
+ /**
389
+ * The desktop app's {@link Desktop} when running in it; undefined in a browser (and outside one).
390
+ *
391
+ * ```ts
392
+ * import { desktop } from '@n3rdw1z4rd/core';
393
+ *
394
+ * if (desktop) quitButton.onclick = () => desktop.quit();
395
+ * ```
396
+ *
397
+ * @category Desktop
398
+ */
399
+ export declare const desktop: Desktop | undefined;
363
400
  /**
364
401
  * Collects cleanup functions (e.g. the unsubscribe functions returned by {@link Observable.subscribe}
365
402
  * and {@link Signal.subscribe}) and runs them all at once.
package/dist/index.d.ts CHANGED
@@ -14,6 +14,7 @@ import { CanvasColor, CanvasRenderer, DEFAULT_COLOR, DEFAULT_FONT, DEFAULT_FONT_
14
14
  import { Clock, ClockCallback, ONE_SECOND } from "./clock.js";
15
15
  import { ColorPalette, RGB, buildColorPalette } from "./color-palette.js";
16
16
  import { Color } from "./color.js";
17
+ import { Desktop, desktop } from "./desktop.js";
17
18
  import { Disposable } from "./disposable.js";
18
19
  import { DoorsParams, GenerateDoors, GenerateRooms, GenerateRoomsParams, GenerateWalls, PathsParams, PointPair, RectPair, RoomsParams, TILE_EMPTY, TILE_FLOOR, TILE_PATH } from "./dungeon-generator.js";
19
20
  import { Component, ComponentInstances, ComponentType, ECS, Entity, System, ecs } from "./ecs.js";
@@ -44,4 +45,4 @@ import { Vector } from "./vector.js";
44
45
  import { RendererParams, WebGlRenderer } from "./webgl-renderer.js";
45
46
  import { AttributeInfo, AttributeSource, BindRenderTarget, BufferOptions, CompileShader, CreateBuffer, CreateProgram, CreateProgramInfo, CreateRenderTarget, CreateTexture, CreateVertexArray, CreateWebGlContext, DeleteProgramInfo, DeleteRenderTarget, DeleteTexture, DeleteVertexArray, Draw, DrawOptions, GetProgramLocations, LoadWebGlTexture, ProgramInfo, ProgramLocations, RenderTarget, RenderTargetOptions, ResizeRenderTarget, ResizeWebGlContext, SetUniforms, ShaderType, TextureData, TextureInfo, TextureOptions, UniformInfo, UniformValue, UpdateBuffer, UpdateTexture, VertexArrayInfo } from "./webgl.js";
46
47
  import { WorkerInterface } from "./worker-interface.js";
47
- export { Action, ActionEvent, ActionMap, ActionMapJSON, ActionOptions, ActionPhase, ActionRepeat, AttributeInfo, AttributeSource, BindRenderTarget, Binding, BufferOptions, CanvasColor, CanvasRenderer, CaptureOptions, Clock, ClockCallback, Color, ColorPalette, CompileShader, Component, ComponentInstances, ComponentType, CreateBuffer, CreateProgram, CreateProgramInfo, CreateRenderTarget, CreateTexture, CreateVertexArray, CreateWebGlContext, DEFAULT_COLOR, DEFAULT_DEADZONE, DEFAULT_FONT, DEFAULT_FONT_NAME, DEFAULT_FONT_SIZE, DEFAULT_MAP_2D_VALUE, DEFAULT_MAP_3D_VALUE, DEFAULT_PIXEL_SIZE, DEFAULT_REPEAT, DEFAULT_TEXTALIGN, DEFAULT_TEXTBASELINE, DEG2RAD, DeleteProgramInfo, DeleteRenderTarget, DeleteTexture, DeleteVertexArray, DeviceQuery, Disposable, DoorsParams, Draw, DrawOptions, DrawParams, E, ECS, EPSILON, Emitter, Entity, EventQueue, GAMEPAD_AXES, GAMEPAD_BUTTONS, GESTURES, GamepadAxis, GamepadButton, GamepadInfo, GenerateDoors, GenerateRooms, GenerateRoomsParams, GenerateWalls, Gesture, GestureBinding, GestureEvent, GestureFrame, GestureRecognizer, GestureThresholds, GetProgramLocations, GetUrlParams, HALF_PI, Input, InputActionMap, InputActionMapOptions, InputDevice, InputDeviceType, InputState, KeyBinding, KeyModifiers, KeyValue, LN10, LN2, LOG10E, LOG2E, Listener, LoadWebGlTexture, MAP_2D_MAX_COORD, MAP_2D_MIN_COORD, MAP_3D_MAX_COORD, MAP_3D_MIN_COORD, Map2D, Map2DData, Map3D, Map3DCell, MouseBinding, MouseButton, NoiseFunction3D, ONE_SECOND, Observable, Observer, PI, PadAxisBinding, PadBinding, ParticleRenderer, ParticleSystem2d, PathOptions, PathsParams, PointPair, PointerState, ProgramInfo, ProgramLocations, QUARTER_PI, RAD2DEG, RGB, Random, RectPair, Rectangle, RenderTarget, RenderTargetOptions, RendererParams, ResizeRenderTarget, ResizeWebGlContext, Rng, RoomsParams, SQRT1_2, SQRT2, SetUniforms, ShaderType, Signal, SpatialPartition2d, SpatialPartition3d, SpatialPartitionEntity2d, SpatialPartitionEntity3d, SpriteParams, StepCost, Subscriber, System, TAU, TILE_EMPTY, TILE_FLOOR, TILE_PATH, TextureData, TextureInfo, TextureOptions, Tilemap, TouchPoint, UniformInfo, UniformValue, UpdateBuffer, UpdateTexture, Vector, VertexArrayInfo, WebGlRenderer, WheelBinding, WheelDirection, WorkerInterface, XRAxis, XRAxisBinding, XRBinding, XRButton, XRHand, XRSessionLike, XR_AXES, XR_BUTTONS, XY, XYZ, bindingLabel, bindingsEqual, buildColorPalette, clamp, controlId, degrees, distance2d, distance3d, ecs, findPath, fract, gesture, getRedYellowGreenGradientHex, hash32, hash32mix, inverseLerp, isNullOrUndefined, isPositiveString, k2xy, k2xyz, key, lerp, log, manhattanDistance, mod, mouse, nearlyEqual, normalizeRadians, pad, padAxis, radians, randomMatrix, rng, roundTo, saturate, smoothstep, squaredDistance, wheel, wrap, xr, xrAxis, xy2k, xyz2k };
48
+ export { Action, ActionEvent, ActionMap, ActionMapJSON, ActionOptions, ActionPhase, ActionRepeat, AttributeInfo, AttributeSource, BindRenderTarget, Binding, BufferOptions, CanvasColor, CanvasRenderer, CaptureOptions, Clock, ClockCallback, Color, ColorPalette, CompileShader, Component, ComponentInstances, ComponentType, CreateBuffer, CreateProgram, CreateProgramInfo, CreateRenderTarget, CreateTexture, CreateVertexArray, CreateWebGlContext, DEFAULT_COLOR, DEFAULT_DEADZONE, DEFAULT_FONT, DEFAULT_FONT_NAME, DEFAULT_FONT_SIZE, DEFAULT_MAP_2D_VALUE, DEFAULT_MAP_3D_VALUE, DEFAULT_PIXEL_SIZE, DEFAULT_REPEAT, DEFAULT_TEXTALIGN, DEFAULT_TEXTBASELINE, DEG2RAD, DeleteProgramInfo, DeleteRenderTarget, DeleteTexture, DeleteVertexArray, Desktop, DeviceQuery, Disposable, DoorsParams, Draw, DrawOptions, DrawParams, E, ECS, EPSILON, Emitter, Entity, EventQueue, GAMEPAD_AXES, GAMEPAD_BUTTONS, GESTURES, GamepadAxis, GamepadButton, GamepadInfo, GenerateDoors, GenerateRooms, GenerateRoomsParams, GenerateWalls, Gesture, GestureBinding, GestureEvent, GestureFrame, GestureRecognizer, GestureThresholds, GetProgramLocations, GetUrlParams, HALF_PI, Input, InputActionMap, InputActionMapOptions, InputDevice, InputDeviceType, InputState, KeyBinding, KeyModifiers, KeyValue, LN10, LN2, LOG10E, LOG2E, Listener, LoadWebGlTexture, MAP_2D_MAX_COORD, MAP_2D_MIN_COORD, MAP_3D_MAX_COORD, MAP_3D_MIN_COORD, Map2D, Map2DData, Map3D, Map3DCell, MouseBinding, MouseButton, NoiseFunction3D, ONE_SECOND, Observable, Observer, PI, PadAxisBinding, PadBinding, ParticleRenderer, ParticleSystem2d, PathOptions, PathsParams, PointPair, PointerState, ProgramInfo, ProgramLocations, QUARTER_PI, RAD2DEG, RGB, Random, RectPair, Rectangle, RenderTarget, RenderTargetOptions, RendererParams, ResizeRenderTarget, ResizeWebGlContext, Rng, RoomsParams, SQRT1_2, SQRT2, SetUniforms, ShaderType, Signal, SpatialPartition2d, SpatialPartition3d, SpatialPartitionEntity2d, SpatialPartitionEntity3d, SpriteParams, StepCost, Subscriber, System, TAU, TILE_EMPTY, TILE_FLOOR, TILE_PATH, TextureData, TextureInfo, TextureOptions, Tilemap, TouchPoint, UniformInfo, UniformValue, UpdateBuffer, UpdateTexture, Vector, VertexArrayInfo, WebGlRenderer, WheelBinding, WheelDirection, WorkerInterface, XRAxis, XRAxisBinding, XRBinding, XRButton, XRHand, XRSessionLike, XR_AXES, XR_BUTTONS, XY, XYZ, bindingLabel, bindingsEqual, buildColorPalette, clamp, controlId, degrees, desktop, distance2d, distance3d, ecs, findPath, fract, gesture, getRedYellowGreenGradientHex, hash32, hash32mix, inverseLerp, isNullOrUndefined, isPositiveString, k2xy, k2xyz, key, lerp, log, manhattanDistance, mod, mouse, nearlyEqual, normalizeRadians, pad, padAxis, radians, randomMatrix, rng, roundTo, saturate, smoothstep, squaredDistance, wheel, wrap, xr, xrAxis, xy2k, xyz2k };
package/dist/index.js CHANGED
@@ -3,6 +3,7 @@ import { CanvasRenderer, DEFAULT_COLOR, DEFAULT_FONT, DEFAULT_FONT_NAME, DEFAULT
3
3
  import { Clock, ONE_SECOND } from "./clock.js";
4
4
  import { buildColorPalette } from "./color-palette.js";
5
5
  import { Color } from "./color.js";
6
+ import { desktop } from "./desktop.js";
6
7
  import { Disposable } from "./disposable.js";
7
8
  import { GenerateDoors, GenerateRooms, GenerateWalls, TILE_EMPTY, TILE_FLOOR, TILE_PATH } from "./dungeon-generator.js";
8
9
  import { ECS, ecs } from "./ecs.js";
@@ -32,4 +33,4 @@ import { Vector } from "./vector.js";
32
33
  import { WebGlRenderer } from "./webgl-renderer.js";
33
34
  import { BindRenderTarget, CompileShader, CreateBuffer, CreateProgram, CreateProgramInfo, CreateRenderTarget, CreateTexture, CreateVertexArray, CreateWebGlContext, DeleteProgramInfo, DeleteRenderTarget, DeleteTexture, DeleteVertexArray, Draw, GetProgramLocations, LoadWebGlTexture, ResizeRenderTarget, ResizeWebGlContext, SetUniforms, ShaderType, UpdateBuffer, UpdateTexture } from "./webgl.js";
34
35
  import { WorkerInterface } from "./worker-interface.js";
35
- export { ActionMap, BindRenderTarget, CanvasRenderer, Clock, Color, CompileShader, CreateBuffer, CreateProgram, CreateProgramInfo, CreateRenderTarget, CreateTexture, CreateVertexArray, CreateWebGlContext, DEFAULT_COLOR, DEFAULT_DEADZONE, DEFAULT_FONT, DEFAULT_FONT_NAME, DEFAULT_FONT_SIZE, DEFAULT_MAP_2D_VALUE, DEFAULT_MAP_3D_VALUE, DEFAULT_PIXEL_SIZE, DEFAULT_REPEAT, DEFAULT_TEXTALIGN, DEFAULT_TEXTBASELINE, DEG2RAD, DeleteProgramInfo, DeleteRenderTarget, DeleteTexture, DeleteVertexArray, Disposable, Draw, E, ECS, EPSILON, Emitter, EventQueue, GAMEPAD_AXES, GAMEPAD_BUTTONS, GESTURES, GenerateDoors, GenerateRooms, GenerateWalls, GestureRecognizer, GetProgramLocations, GetUrlParams, HALF_PI, Input, InputActionMap, LN10, LN2, LOG10E, LOG2E, LoadWebGlTexture, MAP_2D_MAX_COORD, MAP_2D_MIN_COORD, MAP_3D_MAX_COORD, MAP_3D_MIN_COORD, Map2D, Map3D, ONE_SECOND, Observable, PI, ParticleRenderer, ParticleSystem2d, QUARTER_PI, RAD2DEG, Random, Rectangle, ResizeRenderTarget, ResizeWebGlContext, Rng, SQRT1_2, SQRT2, SetUniforms, ShaderType, Signal, SpatialPartition2d, SpatialPartition3d, TAU, TILE_EMPTY, TILE_FLOOR, TILE_PATH, Tilemap, UpdateBuffer, UpdateTexture, Vector, WebGlRenderer, WorkerInterface, XR_AXES, XR_BUTTONS, bindingLabel, bindingsEqual, buildColorPalette, clamp, controlId, degrees, distance2d, distance3d, ecs, findPath, fract, gesture, getRedYellowGreenGradientHex, hash32, hash32mix, inverseLerp, isNullOrUndefined, isPositiveString, k2xy, k2xyz, key, lerp, log, manhattanDistance, mod, mouse, nearlyEqual, normalizeRadians, pad, padAxis, radians, randomMatrix, rng, roundTo, saturate, smoothstep, squaredDistance, wheel, wrap, xr, xrAxis, xy2k, xyz2k };
36
+ export { ActionMap, BindRenderTarget, CanvasRenderer, Clock, Color, CompileShader, CreateBuffer, CreateProgram, CreateProgramInfo, CreateRenderTarget, CreateTexture, CreateVertexArray, CreateWebGlContext, DEFAULT_COLOR, DEFAULT_DEADZONE, DEFAULT_FONT, DEFAULT_FONT_NAME, DEFAULT_FONT_SIZE, DEFAULT_MAP_2D_VALUE, DEFAULT_MAP_3D_VALUE, DEFAULT_PIXEL_SIZE, DEFAULT_REPEAT, DEFAULT_TEXTALIGN, DEFAULT_TEXTBASELINE, DEG2RAD, DeleteProgramInfo, DeleteRenderTarget, DeleteTexture, DeleteVertexArray, Disposable, Draw, E, ECS, EPSILON, Emitter, EventQueue, GAMEPAD_AXES, GAMEPAD_BUTTONS, GESTURES, GenerateDoors, GenerateRooms, GenerateWalls, GestureRecognizer, GetProgramLocations, GetUrlParams, HALF_PI, Input, InputActionMap, LN10, LN2, LOG10E, LOG2E, LoadWebGlTexture, MAP_2D_MAX_COORD, MAP_2D_MIN_COORD, MAP_3D_MAX_COORD, MAP_3D_MIN_COORD, Map2D, Map3D, ONE_SECOND, Observable, PI, ParticleRenderer, ParticleSystem2d, QUARTER_PI, RAD2DEG, Random, Rectangle, ResizeRenderTarget, ResizeWebGlContext, Rng, SQRT1_2, SQRT2, SetUniforms, ShaderType, Signal, SpatialPartition2d, SpatialPartition3d, TAU, TILE_EMPTY, TILE_FLOOR, TILE_PATH, Tilemap, UpdateBuffer, UpdateTexture, Vector, WebGlRenderer, WorkerInterface, XR_AXES, XR_BUTTONS, bindingLabel, bindingsEqual, buildColorPalette, clamp, controlId, degrees, desktop, distance2d, distance3d, ecs, findPath, fract, gesture, getRedYellowGreenGradientHex, hash32, hash32mix, inverseLerp, isNullOrUndefined, isPositiveString, k2xy, k2xyz, key, lerp, log, manhattanDistance, mod, mouse, nearlyEqual, normalizeRadians, pad, padAxis, radians, randomMatrix, rng, roundTo, saturate, smoothstep, squaredDistance, wheel, wrap, xr, xrAxis, xy2k, xyz2k };
package/dist/vite.cjs CHANGED
@@ -1,5 +1,30 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
+ let node_child_process = require("node:child_process");
3
+ let node_crypto = require("node:crypto");
4
+ let node_fs = require("node:fs");
5
+ let node_path = require("node:path");
2
6
  // src/vite.ts
7
+ /**
8
+ * Vite plugins: `decorators()` lowers standard (TC39) decorators such as `@field` / `@component`
9
+ * with esbuild; `buildManifest()` writes the `version.json` the desktop app
10
+ * (`@n3rdw1z4rd/core/electron`) updates itself from.
11
+ *
12
+ * Vite 8 compiles TypeScript with Oxc, which only lowers legacy `experimentalDecorators` and
13
+ * passes standard decorators through untouched — no browser can run that yet. This runs
14
+ * first on any source file that uses a decorator; Oxc then sees plain TS/JS.
15
+ *
16
+ * ```ts
17
+ * // vite.config.ts
18
+ * import { decorators } from '@n3rdw1z4rd/core/vite';
19
+ * export default defineConfig({ plugins: [decorators()] });
20
+ * ```
21
+ *
22
+ * Requires `esbuild` to be installed alongside Vite. Node-only: not exported from the
23
+ * package root.
24
+ *
25
+ * @packageDocumentation
26
+ * @module @n3rdw1z4rd/core/vite
27
+ */
3
28
  /** @category Build */
4
29
  function decorators() {
5
30
  const file = /\.[cm]?[jt]sx?$/;
@@ -36,4 +61,103 @@ function decorators() {
36
61
  }
37
62
  };
38
63
  }
64
+ /**
65
+ * The commit a build is made from, 7 characters: from the environment (`GIT_COMMIT`,
66
+ * `SOURCE_COMMIT`, `COMMIT_SHA` or `GITHUB_SHA`, as Docker builds and CI pass it), else git, else
67
+ * the `.git` folder's own files. Without any of those, `local.HHMM` (UTC), so two builds on one
68
+ * day still differ.
69
+ *
70
+ * @category Build
71
+ */
72
+ function buildCommit(cwd = process.cwd()) {
73
+ const env = process.env.GIT_COMMIT || process.env.SOURCE_COMMIT || process.env.COMMIT_SHA || process.env.GITHUB_SHA;
74
+ if (env) return env.slice(0, 7);
75
+ try {
76
+ return (0, node_child_process.execSync)("git rev-parse --short=7 HEAD", {
77
+ cwd,
78
+ stdio: [
79
+ "ignore",
80
+ "pipe",
81
+ "ignore"
82
+ ]
83
+ }).toString().trim();
84
+ } catch {}
85
+ try {
86
+ const git = (0, node_path.join)(cwd, ".git");
87
+ const head = (0, node_fs.readFileSync)((0, node_path.join)(git, "HEAD"), "utf8").trim();
88
+ if (!head.startsWith("ref: ")) return head.slice(0, 7);
89
+ const ref = head.slice(5);
90
+ try {
91
+ return (0, node_fs.readFileSync)((0, node_path.join)(git, ref), "utf8").trim().slice(0, 7);
92
+ } catch {}
93
+ const line = (0, node_fs.readFileSync)((0, node_path.join)(git, "packed-refs"), "utf8").split("\n").find((l) => l.endsWith(` ${ref}`));
94
+ if (line) return line.slice(0, 7);
95
+ } catch {}
96
+ const now = /* @__PURE__ */ new Date();
97
+ return `local.${String(now.getUTCHours()).padStart(2, "0")}${String(now.getUTCMinutes()).padStart(2, "0")}`;
98
+ }
99
+ /**
100
+ * A build's id: package.json's version and the commit it's built from, e.g. "0.7.0-6ae4707"
101
+ * (letters, digits, dots and dashes only: the desktop app names a folder after it).
102
+ *
103
+ * ```ts
104
+ * // vite.config.ts: the page can show it, too
105
+ * export default defineConfig({ define: { __BUILD_ID__: JSON.stringify(buildId()) }, plugins: [buildManifest()] });
106
+ * ```
107
+ *
108
+ * @category Build
109
+ */
110
+ function buildId(cwd = process.cwd()) {
111
+ return `${JSON.parse((0, node_fs.readFileSync)((0, node_path.join)(cwd, "package.json"), "utf8")).version ?? "0.0.0"}-${buildCommit(cwd)}`.replace(/[^\w.-]/g, "-");
112
+ }
113
+ /**
114
+ * Vite plugin: after a build, writes `version.json` into the output folder: the build's id, when
115
+ * it was built, the desktop API level it needs, and every file in it with its size and SHA-256.
116
+ * The desktop app (`@n3rdw1z4rd/core/electron`) reads its own copy to know what it's running, and
117
+ * the site's copy to update itself.
118
+ *
119
+ * @category Build
120
+ */
121
+ function buildManifest(options = {}) {
122
+ let outDir = (0, node_path.resolve)("dist");
123
+ let root = process.cwd();
124
+ return {
125
+ name: "n3rdw1z4rd:build-manifest",
126
+ apply: "build",
127
+ configResolved(config) {
128
+ root = config.root;
129
+ outDir = (0, node_path.resolve)(config.root, config.build.outDir);
130
+ },
131
+ closeBundle(error) {
132
+ if (error || !(0, node_fs.existsSync)(outDir)) return;
133
+ const files = [];
134
+ const walk = (dir) => {
135
+ for (const name of (0, node_fs.readdirSync)(dir)) {
136
+ const full = (0, node_path.join)(dir, name);
137
+ if ((0, node_fs.statSync)(full).isDirectory()) walk(full);
138
+ else if (full !== (0, node_path.join)(outDir, "version.json")) {
139
+ const data = (0, node_fs.readFileSync)(full);
140
+ files.push({
141
+ path: (0, node_path.relative)(outDir, full).split(node_path.sep).join("/"),
142
+ size: data.length,
143
+ sha256: (0, node_crypto.createHash)("sha256").update(data).digest("hex")
144
+ });
145
+ }
146
+ }
147
+ };
148
+ walk(outDir);
149
+ files.sort((a, b) => a.path < b.path ? -1 : a.path > b.path ? 1 : 0);
150
+ const manifest = {
151
+ version: options.version ?? buildId(root),
152
+ builtAt: (/* @__PURE__ */ new Date()).toISOString(),
153
+ needs: options.needs ?? 1,
154
+ files
155
+ };
156
+ (0, node_fs.writeFileSync)((0, node_path.join)(outDir, "version.json"), JSON.stringify(manifest, null, 1));
157
+ }
158
+ };
159
+ }
160
+ exports.buildCommit = buildCommit;
161
+ exports.buildId = buildId;
162
+ exports.buildManifest = buildManifest;
39
163
  exports.decorators = decorators;
package/dist/vite.d.cts CHANGED
@@ -1,5 +1,7 @@
1
1
  /**
2
- * Vite plugin: lowers standard (TC39) decorators such as `@field` / `@component` with esbuild.
2
+ * Vite plugins: `decorators()` lowers standard (TC39) decorators such as `@field` / `@component`
3
+ * with esbuild; `buildManifest()` writes the `version.json` the desktop app
4
+ * (`@n3rdw1z4rd/core/electron`) updates itself from.
3
5
  *
4
6
  * Vite 8 compiles TypeScript with Oxc, which only lowers legacy `experimentalDecorators` and
5
7
  * passes standard decorators through untouched — no browser can run that yet. This runs
@@ -30,4 +32,53 @@ export interface DecoratorsPlugin {
30
32
  } | null>;
31
33
  }
32
34
  /** @category Build */
33
- export declare function decorators(): DecoratorsPlugin;
35
+ export declare function decorators(): DecoratorsPlugin;
36
+ /**
37
+ * The commit a build is made from, 7 characters: from the environment (`GIT_COMMIT`,
38
+ * `SOURCE_COMMIT`, `COMMIT_SHA` or `GITHUB_SHA`, as Docker builds and CI pass it), else git, else
39
+ * the `.git` folder's own files. Without any of those, `local.HHMM` (UTC), so two builds on one
40
+ * day still differ.
41
+ *
42
+ * @category Build
43
+ */
44
+ export declare function buildCommit(cwd?: string): string;
45
+ /**
46
+ * A build's id: package.json's version and the commit it's built from, e.g. "0.7.0-6ae4707"
47
+ * (letters, digits, dots and dashes only: the desktop app names a folder after it).
48
+ *
49
+ * ```ts
50
+ * // vite.config.ts: the page can show it, too
51
+ * export default defineConfig({ define: { __BUILD_ID__: JSON.stringify(buildId()) }, plugins: [buildManifest()] });
52
+ * ```
53
+ *
54
+ * @category Build
55
+ */
56
+ export declare function buildId(cwd?: string): string;
57
+ /** Options for {@link buildManifest}. */
58
+ export interface BuildManifestOptions {
59
+ /** the build's id; default {@link buildId} */
60
+ version?: string;
61
+ /** the desktop API level the build needs (the app's `update.api` must be at least this); default 1 */
62
+ needs?: number;
63
+ }
64
+ /** The part of Vite's `Plugin` {@link buildManifest} uses (structurally compatible: pass it to `plugins`). */
65
+ export interface BuildManifestPlugin {
66
+ name: string;
67
+ apply: 'build';
68
+ configResolved(config: {
69
+ root: string;
70
+ build: {
71
+ outDir: string;
72
+ };
73
+ }): void;
74
+ closeBundle(error?: Error): void;
75
+ }
76
+ /**
77
+ * Vite plugin: after a build, writes `version.json` into the output folder: the build's id, when
78
+ * it was built, the desktop API level it needs, and every file in it with its size and SHA-256.
79
+ * The desktop app (`@n3rdw1z4rd/core/electron`) reads its own copy to know what it's running, and
80
+ * the site's copy to update itself.
81
+ *
82
+ * @category Build
83
+ */
84
+ export declare function buildManifest(options?: BuildManifestOptions): BuildManifestPlugin;
package/dist/vite.d.ts CHANGED
@@ -1,5 +1,7 @@
1
1
  /**
2
- * Vite plugin: lowers standard (TC39) decorators such as `@field` / `@component` with esbuild.
2
+ * Vite plugins: `decorators()` lowers standard (TC39) decorators such as `@field` / `@component`
3
+ * with esbuild; `buildManifest()` writes the `version.json` the desktop app
4
+ * (`@n3rdw1z4rd/core/electron`) updates itself from.
3
5
  *
4
6
  * Vite 8 compiles TypeScript with Oxc, which only lowers legacy `experimentalDecorators` and
5
7
  * passes standard decorators through untouched — no browser can run that yet. This runs
@@ -30,4 +32,53 @@ export interface DecoratorsPlugin {
30
32
  } | null>;
31
33
  }
32
34
  /** @category Build */
33
- export declare function decorators(): DecoratorsPlugin;
35
+ export declare function decorators(): DecoratorsPlugin;
36
+ /**
37
+ * The commit a build is made from, 7 characters: from the environment (`GIT_COMMIT`,
38
+ * `SOURCE_COMMIT`, `COMMIT_SHA` or `GITHUB_SHA`, as Docker builds and CI pass it), else git, else
39
+ * the `.git` folder's own files. Without any of those, `local.HHMM` (UTC), so two builds on one
40
+ * day still differ.
41
+ *
42
+ * @category Build
43
+ */
44
+ export declare function buildCommit(cwd?: string): string;
45
+ /**
46
+ * A build's id: package.json's version and the commit it's built from, e.g. "0.7.0-6ae4707"
47
+ * (letters, digits, dots and dashes only: the desktop app names a folder after it).
48
+ *
49
+ * ```ts
50
+ * // vite.config.ts: the page can show it, too
51
+ * export default defineConfig({ define: { __BUILD_ID__: JSON.stringify(buildId()) }, plugins: [buildManifest()] });
52
+ * ```
53
+ *
54
+ * @category Build
55
+ */
56
+ export declare function buildId(cwd?: string): string;
57
+ /** Options for {@link buildManifest}. */
58
+ export interface BuildManifestOptions {
59
+ /** the build's id; default {@link buildId} */
60
+ version?: string;
61
+ /** the desktop API level the build needs (the app's `update.api` must be at least this); default 1 */
62
+ needs?: number;
63
+ }
64
+ /** The part of Vite's `Plugin` {@link buildManifest} uses (structurally compatible: pass it to `plugins`). */
65
+ export interface BuildManifestPlugin {
66
+ name: string;
67
+ apply: 'build';
68
+ configResolved(config: {
69
+ root: string;
70
+ build: {
71
+ outDir: string;
72
+ };
73
+ }): void;
74
+ closeBundle(error?: Error): void;
75
+ }
76
+ /**
77
+ * Vite plugin: after a build, writes `version.json` into the output folder: the build's id, when
78
+ * it was built, the desktop API level it needs, and every file in it with its size and SHA-256.
79
+ * The desktop app (`@n3rdw1z4rd/core/electron`) reads its own copy to know what it's running, and
80
+ * the site's copy to update itself.
81
+ *
82
+ * @category Build
83
+ */
84
+ export declare function buildManifest(options?: BuildManifestOptions): BuildManifestPlugin;