Compare commits
18 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 5cde6d444b | |||
| 74a16fbf88 | |||
| becfafc603 | |||
| 4758fa1076 | |||
| b633f07042 | |||
| f7942d0bd0 | |||
| b34d34dacb | |||
| d42727618e | |||
| 335cb3c757 | |||
| 7ecc4474c5 | |||
| 726a5b922b | |||
| fe1da03f66 | |||
| edfc6cdc80 | |||
| 27360ffae7 | |||
| 8aafdcfb16 | |||
| d0e0e8926c | |||
| 4beaaacf0e | |||
| b79f6c9a4e |
@@ -6,6 +6,9 @@ docs
|
||||
server/data
|
||||
.check
|
||||
.smoke
|
||||
# Experiments and session notes: hundreds of MB that no image needs
|
||||
spike
|
||||
.pi
|
||||
*.log
|
||||
.DS_Store
|
||||
README.md
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
# Verification pipeline for git.maple-street.net (Gitea Actions / act_runner).
|
||||
#
|
||||
# Runs the same gates a release needs, so a broken commit cannot reach main
|
||||
# unnoticed. The container is pinned to the Node major the Dockerfile ships, and
|
||||
# the runner only needs Docker — no Node, Chrome or extra tools on the host.
|
||||
name: CI
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [main]
|
||||
pull_request:
|
||||
|
||||
jobs:
|
||||
verify:
|
||||
runs-on: ubuntu-latest
|
||||
container: node:24-bookworm
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Install dependencies
|
||||
run: npm ci
|
||||
|
||||
- name: Typecheck
|
||||
run: npm run typecheck
|
||||
|
||||
# Includes the server HTTP suite, which starts the real server against a
|
||||
# temporary data directory (auth, ownership, quota, gallery, ranges).
|
||||
- name: Tests
|
||||
run: npm test
|
||||
|
||||
- name: Production build
|
||||
run: npm run build
|
||||
|
||||
- name: Server syntax
|
||||
run: for file in server/*.mjs; do node --check "$file"; done
|
||||
@@ -14,3 +14,19 @@ server/data/
|
||||
.smoke/
|
||||
*.log
|
||||
.DS_Store
|
||||
|
||||
# Experiments and session notes that never ship
|
||||
spike/
|
||||
.pi/
|
||||
HANDOFF-*.md
|
||||
|
||||
# Windows native-window build output
|
||||
windows/launcher/webview2/bin/
|
||||
windows/launcher/webview2/obj/
|
||||
|
||||
# Transfer-only Windows release archives
|
||||
windows/releases/*.zip
|
||||
windows/releases/*.exe
|
||||
|
||||
# Transfer-only macOS release archives
|
||||
macos/releases/
|
||||
|
||||
@@ -4,6 +4,10 @@
|
||||
FROM node:24-bookworm-slim AS deps
|
||||
WORKDIR /app
|
||||
COPY package.json package-lock.json ./
|
||||
# onnxruntime-node's postinstall downloads the CUDA build (hundreds of MB) that
|
||||
# a CPU-only server never loads; the package itself already carries its CPU
|
||||
# binaries, so skip the download in both install stages.
|
||||
ENV ONNXRUNTIME_NODE_INSTALL=skip
|
||||
RUN npm ci
|
||||
|
||||
# ---------------------------------------------------------------------- build
|
||||
@@ -13,12 +17,15 @@ COPY tsconfig.json vite.config.ts index.html ./
|
||||
COPY src ./src
|
||||
# Vite copies public/ into dist/, so the served PDF (in-app Guide link) needs it here.
|
||||
COPY public ./public
|
||||
# The build writes the .br/.gz asset copies the server prefers to send.
|
||||
COPY scripts ./scripts
|
||||
RUN npm run build
|
||||
|
||||
# ------------------------------------------------------- production node_modules
|
||||
FROM node:24-bookworm-slim AS prod-deps
|
||||
WORKDIR /app
|
||||
ENV NODE_ENV=production
|
||||
ENV NODE_ENV=production \
|
||||
ONNXRUNTIME_NODE_INSTALL=skip
|
||||
COPY package.json package-lock.json ./
|
||||
RUN npm ci --omit=dev && npm cache clean --force
|
||||
|
||||
|
||||
@@ -277,7 +277,7 @@ directly and have no legacy alias.
|
||||
|
||||
```bash
|
||||
npm ci
|
||||
npm run build # type-checks and bundles dist/
|
||||
npm run build # type-checks, bundles dist/ and writes .br/.gz copies
|
||||
npm start # serves dist/ and /api from one Node process
|
||||
```
|
||||
|
||||
@@ -360,6 +360,25 @@ Two independent things to back up:
|
||||
`GET /api/admin/catalog`, and restore it with `POST /api/admin/catalog`. This does
|
||||
not include image bytes; keep a file-level backup for those.
|
||||
|
||||
`npm run backup` automates item 1 without stopping the server: it writes a consistent
|
||||
`VACUUM INTO` snapshot of the live catalog (WAL included) to `$LUMINARY_DATA/backups`,
|
||||
re-opens it to run `PRAGMA integrity_check`, records counts in a manifest and prunes to
|
||||
the last 14 snapshots. `--keep`, `--dir` and `LUMINARY_BACKUP_DIR` change that; originals
|
||||
are opt-in because they dwarf the catalog:
|
||||
|
||||
```bash
|
||||
npm run backup # catalog only
|
||||
npm run backup -- --with-originals --keep 30
|
||||
|
||||
# nightly at 02:30, keeping the copy off the data volume
|
||||
30 2 * * * cd /srv/luminary && /usr/bin/npm run backup -- --with-originals --dir /mnt/backups >> /var/log/luminary-backup.log 2>&1
|
||||
```
|
||||
|
||||
To restore, stop the server, copy `catalog-*.db` back as `lumenroom.db` (delete the old
|
||||
`-wal`/`-shm` files first) and copy `originals-*/` back into the storage root. Previews,
|
||||
thumbnails, proofs and denoise renders are regenerable; only `originals/` and
|
||||
`secret.key` must survive.
|
||||
|
||||
---
|
||||
|
||||
## Docker
|
||||
@@ -423,7 +442,7 @@ Node server (node:http, port 8787)
|
||||
raw.mjs LibRaw demosaic, embedded-preview fallback
|
||||
libraw-*.mjs Node <-> browser shim and decoder worker pool
|
||||
imaging.mjs sharp encode/resize, dependency-free PNG fallback
|
||||
denoise.mjs job queue and on-disk render cache
|
||||
denoise.mjs denoise queue, base selection and render cache
|
||||
quota.mjs usage accounting, prune plans, warnings, worker
|
||||
mail.mjs nodemailer transport, admin-editable settings
|
||||
bridge.mjs dashboard token verification and metadata import
|
||||
@@ -434,7 +453,7 @@ Data directory
|
||||
originals/ uploaded files, byte-for-byte, original extension kept
|
||||
previews/ editable JPEG proxies (raw) and normalised previews
|
||||
thumbs/ grid thumbnails (server-rendered proofs are 560 px)
|
||||
denoised/ full-strength denoise renders keyed by pipeline version
|
||||
denoised/ full-strength denoise renders, one per base model
|
||||
proofs/ rendered proofs for client galleries
|
||||
proofThumbs/ thumbnails of those proofs
|
||||
```
|
||||
@@ -515,7 +534,7 @@ that predate workspaces are assigned to the oldest account.
|
||||
| `originals/` | `<photo id>.<original ext>` | Uploaded bytes, untouched; extension preserved |
|
||||
| `previews/` | `<photo id>.jpg` or `.png` | Editable proxies; PNG when `sharp` is unavailable |
|
||||
| `thumbs/` | `<photo id>.jpg` | Grid thumbnails; server-rendered proof thumbnails are 560 px |
|
||||
| `denoised/` | `<photo id>.<key>.jpg` | Key encodes the pipeline version; old keys are pruned |
|
||||
| `denoised/` | `<photo id>.<key>.jpg` | Key encodes the pipeline version and the base model; one render is kept per model |
|
||||
| `proofs/` | `<photo id>.jpg` | Rendered client-gallery proofs |
|
||||
| `proofThumbs/` | `<photo id>.jpg` | Thumbnails of those proofs |
|
||||
|
||||
@@ -577,8 +596,8 @@ routes are public and are gated only by the share token.
|
||||
| GET | `/api/photos/:id/preview` | owner | Stream the editable proxy |
|
||||
| GET | `/api/photos/:id/thumb` | owner | Stream the thumbnail (proof thumbnail first, if present) |
|
||||
| POST | `/api/photos/:id/proof` | owner | Store a rendered JPEG proof and its thumbnail from base64 |
|
||||
| POST | `/api/photos/:id/denoise` | owner | Queue a full-strength denoise render; returns a job id |
|
||||
| GET | `/api/denoise/jobs/:id` | session | Job state: running/done/error, timing, stats, cache hit |
|
||||
| POST | `/api/photos/:id/denoise` | owner | Queue a full-strength render; body `{"base": "guided" \| "scunet" \| "nlm"}`, default `guided`; returns a job id |
|
||||
| GET | `/api/denoise/jobs/:id` | session | Job state: running/done/error, `progress` (`stage`, `done`, `total` tiles), `ms`, `bytes`, `stats` and `cached` for a cache hit |
|
||||
| GET | `/api/photos/:id/denoised?v=<key>` | owner | Stream the cached denoise render |
|
||||
| DELETE | `/api/photos/:id/denoised` | owner | Drop all denoise renders for the photo |
|
||||
| GET | `/api/quota` | session | The caller's quota state |
|
||||
@@ -903,26 +922,52 @@ busy count.
|
||||
|
||||
## Detail-preserving denoise
|
||||
|
||||
`server/denoise/` is a dependency-free pipeline (planes, noise estimation, colour,
|
||||
detail, RGB reconstruction) adapted from the `raw-noise` project. It reconstructs each
|
||||
pixel as a crossfade between the source and a denoised base, so the result is bounded by
|
||||
the original pixels and cannot ring or overshoot: flat noise is replaced, structure is
|
||||
handed back verbatim.
|
||||
`server/denoise/` is Luminary's denoise pipeline: planes, noise estimation, colour,
|
||||
detail and RGB reconstruction, adapted from the `raw-noise` project, driving one of three
|
||||
base denoisers. The result is a per-pixel crossfade between the source and the denoised
|
||||
base, so it is bounded by the original pixels and cannot ring or overshoot: flat noise is
|
||||
replaced, structure is handed back verbatim.
|
||||
|
||||
**Provenance.** `raw-noise` is not published on npm, and no copyright or licence notice
|
||||
for it is included in this repository. Before redistributing Luminary, add the origin's
|
||||
notice and terms to `server/denoise/`, or replace that folder with an independently
|
||||
licensed implementation.
|
||||
The **AI denoise** panel offers the three bases in this order:
|
||||
|
||||
| Base | Implementation | One 256 × 256 test frame |
|
||||
| --- | --- | --- |
|
||||
| **Guided** (default) | Guided filter in the copied pipeline; fastest, keeps the most fine texture | 0.06 s |
|
||||
| **SCUNet** | Learned colour denoiser `server/denoise/scunet_color_25.onnx`, run through `onnxruntime-node` on 256 px tiles with a 32 px overlap | 12.1 s (4 tiles) |
|
||||
| **NLM** | Non-local means in the copied pipeline; slower than Guided, smooths less than SCUNet | 0.43 s |
|
||||
|
||||
Timings are what the three bases measured here on a 256² noisy frame; a full frame costs
|
||||
more in proportion to its area (and SCUNet to its tile count). The base is stored per
|
||||
photo in `aiDenoise.model` and is part of the render key, so switching models does not
|
||||
invalidate another model's render. SCUNet is the only path that needs
|
||||
`onnxruntime-node`; it is imported lazily, so Guided and NLM keep working when the native
|
||||
binding cannot load. The package is pinned to `1.23.0`, the last release that ships both
|
||||
macOS architectures, and its install step is skipped in the Dockerfile and the desktop
|
||||
builds (`ONNXRUNTIME_NODE_INSTALL=skip`) because only the CPU binaries in the package are
|
||||
used.
|
||||
|
||||
**Provenance and licences.** `raw-noise` is not published on npm, and no copyright or
|
||||
licence notice for it is included in this repository. Before redistributing Luminary, add
|
||||
the origin's notice and terms to `server/denoise/`, or replace that folder with an
|
||||
independently licensed implementation. The SCUNet weights are Apache-2.0 (upstream
|
||||
`cszn/SCUNet`, ONNX export by `Heliosoph/scunet-onnx`) and ONNX Runtime is MIT; both are
|
||||
listed in [`THIRD_PARTY_NOTICES.md`](THIRD_PARTY_NOTICES.md).
|
||||
|
||||
- The server always renders the full-strength denoise and the GPU blends it, so the
|
||||
Amount slider is instant, one file serves every amount, and the amount cannot be
|
||||
applied twice.
|
||||
- Renders are cached in `denoised/` under a key that includes `PIPELINE_VERSION`. Bump
|
||||
that constant whenever the copied pipeline changes output, or stale renders will be
|
||||
served as current.
|
||||
- Renders are cached in `denoised/` as `<photo id>.<key>.jpg`, where the key is the first
|
||||
12 hex characters of `sha1(photoId|PIPELINE_VERSION|base)`. One render is kept per
|
||||
model, so switching back to a model is instant; a finished run prunes only keys from an
|
||||
older pipeline version. Bump `PIPELINE_VERSION` in `server/denoise.mjs` whenever the
|
||||
copied pipeline or the SCUNet tiling changes output, or stale renders will be served as
|
||||
current.
|
||||
- Each run is seconds of CPU, so jobs go through a capped queue
|
||||
(`LUMINARY_DENOISE_WORKERS`, default `min(4, cores−1)`). A second request for the same
|
||||
photo joins the run already in progress instead of starting an identical one.
|
||||
photo and base joins the run already in progress instead of starting an identical one,
|
||||
and a request whose render already exists returns at once with `cached: true`.
|
||||
- While a job runs it reports `progress` (`stage` and, for SCUNet, the tile count), which
|
||||
the panel turns into a real status line instead of a spinner.
|
||||
- The job table keeps the newest 40 entries and never drops a queued or running job.
|
||||
|
||||
---
|
||||
@@ -971,15 +1016,31 @@ positions. Camera-lens defaults require both a normalised camera and lens name t
|
||||
| `npm run server:dev` | Server with `node --watch` |
|
||||
| `npm run dev` | Vite HMR on 5173 |
|
||||
| `npm run typecheck` | `tsc --noEmit` |
|
||||
| `npm test` | Vitest, one pass then exit |
|
||||
| `npm test` | Vitest, one pass then exit: pure logic plus the server HTTP suite |
|
||||
| `npm run backup` | Snapshot the catalog (originals optional) without stopping the server |
|
||||
| `npm run precompress` | Write the `.br`/`.gz` asset copies by hand; `npm run build` does this |
|
||||
| `npm run check:render` | Headless Chrome check that the 16-bit sidecar and JPEG proxy upload in the same row order |
|
||||
| `npm run predeploy` | Typecheck, unit suite, render check, then build — run this before pushing a deploy; the build is skipped when only test files changed since the last build |
|
||||
| `npm run deploy` | Predeploy gate, then rsync, remote build, restart and bundle-hash check (see [Production deployment](#production-deployment)) |
|
||||
|
||||
`npm install` also installs `onnxruntime-node` for the SCUNet denoise base. Its install
|
||||
step downloads the CUDA build (~350 MB) unless `ONNXRUNTIME_NODE_INSTALL=skip` is set
|
||||
before the install; the Dockerfile and the desktop builds set it, because only the CPU
|
||||
binaries that ship inside the package are used.
|
||||
|
||||
### Continuous integration
|
||||
|
||||
`.gitea/workflows/ci.yml` runs on every push and pull request: `npm ci`,
|
||||
`npm run typecheck`, `npm test` and `npm run build` inside a `node:24-bookworm`
|
||||
container, then `node --check` on every `server/*.mjs`. It only needs Docker on the
|
||||
runner, so the same gate works on the LAN Gitea instance. Release binaries are still
|
||||
built and attached by hand; the workflow is what keeps `main` buildable.
|
||||
|
||||
Conventions worth knowing before changing code:
|
||||
|
||||
- The server is plain ESM (`.mjs`) with no build step. Keep it framework-free and avoid
|
||||
native modules; `node:sqlite` is deliberate, and `sharp` must stay optional.
|
||||
- The server is plain ESM (`.mjs`) with no build step. Keep it framework-free; native
|
||||
modules stay optional — `node:sqlite` is deliberate, `sharp` must stay optional, and
|
||||
`onnxruntime-node` is loaded lazily and only for SCUNet.
|
||||
- The client is strict TypeScript with `noEmit`; Vite builds only `src/` and `public/`.
|
||||
- Edits are data, not pixels: adding a control means extending `src/types.ts`, the
|
||||
renderer uniforms/shaders, `normalizeEdits()` defaults, the export path and the panel
|
||||
@@ -1007,8 +1068,13 @@ Conventions worth knowing before changing code:
|
||||
| `src/lib/dcp.test.ts` | DCP tag parsing and the camera matrix recipe against LibRaw's own values |
|
||||
| `src/lib/softProof.test.ts` | ICC parsing (including counted lut16 tables), the printer round trip, gamut threshold, rendering-intent selection and CMYK profiles |
|
||||
| `src/lib/dcpLibrary.test.ts` | Per-camera DCP library: validation, replacement, forgetting and camera matching |
|
||||
| `server/http.test.mjs` | Real server on a throwaway data directory: signup/invite rules, cross-owner isolation, upload quota accounting, byte ranges, unreadable files not killing the process, gallery download cap |
|
||||
|
||||
There are no server integration tests; the API is exercised through the UI.
|
||||
`server/http.test.mjs` spawns `server/index.mjs` on a random loopback port with a
|
||||
temporary `LUMINARY_DATA`, drives it with `fetch` and deletes the directory afterwards,
|
||||
so it needs no fixtures and never touches a real catalog. Its permission test (an
|
||||
unreadable original must answer 404 instead of crashing the process) is skipped when the
|
||||
suite runs as root, because root ignores file modes.
|
||||
|
||||
`npm run check:render` covers the one thing the unit suite cannot: what a shader does to
|
||||
real GPU pixels. It encodes a 16-bit sidecar with the server's own encoder, serves it
|
||||
@@ -1179,7 +1245,9 @@ full CC BY-SA 3.0 text. Before distributing Luminary or its container image:
|
||||
(OFL-1.1) and DejaVu Sans Mono (Bitstream Vera licence) — with any redistributed
|
||||
copy.
|
||||
7. Record the terms of the `server/denoise/` pipeline's `raw-noise` origin; it is not
|
||||
published on npm and its licence is currently undocumented here.
|
||||
published on npm and its licence is currently undocumented here. The SCUNet weights
|
||||
and ONNX Runtime are already catalogued in `THIRD_PARTY_NOTICES.md`; ship that file
|
||||
and the model's `.onnx.data` shard with the app.
|
||||
|
||||
### No endorsement
|
||||
|
||||
|
||||
@@ -24,8 +24,17 @@ Versions are those resolved in `package-lock.json`; the lens database pin is
|
||||
| libvips (bundled in `sharp` binaries) | shipped by `sharp` 0.35.5 | LGPL-2.1-or-later | © libvips contributors — https://github.com/libvips/libvips |
|
||||
| `exifr` | 7.1.3 | MIT | © 2020 Mike Kovařík, Mutiny.cz — https://github.com/MikeKovarik/exifr |
|
||||
| `nodemailer` | 7.0.13 | MIT-0 | © 2011-2023 Andris Reinman — https://github.com/nodemailer/nodemailer |
|
||||
| `onnxruntime-node` (ONNX Runtime native libraries) | 1.23.0 | MIT | © Microsoft Corporation — https://github.com/microsoft/onnxruntime |
|
||||
| SCUNet colour-denoise weights (`server/denoise/scunet_color_25.onnx`) | `scunet_color_25` | Apache-2.0 | © Kai Zhang and SCUNet contributors — https://github.com/cszn/SCUNet; ONNX export https://github.com/Heliosoph/scunet-onnx |
|
||||
| React / React DOM | 18.3.1 | MIT | © Facebook, Inc. and its affiliates — https://github.com/facebook/react |
|
||||
|
||||
`onnxruntime-node` is pulled in only by the optional SCUNet denoise base; the Guided and
|
||||
NLM bases are plain TypeScript. Its install step is skipped in the Docker image and the
|
||||
desktop bundles (`ONNXRUNTIME_NODE_INSTALL=skip`), so only the CPU runtime that ships in
|
||||
the package is distributed. The SCUNet model is a converted export of the upstream
|
||||
Apache-2.0 weights and keeps that licence; its `.onnx` file and the external `.onnx.data`
|
||||
shard are one artefact and must travel together.
|
||||
|
||||
The lens database is a separate asset from Luminary's code: CC BY-SA 3.0 applies to
|
||||
Lensfun's calibration data, not to the correction engine that reads it. Attribution and
|
||||
share-alike requirements are summarised in the README under
|
||||
@@ -138,9 +147,9 @@ the following restrictions:
|
||||
|
||||
### Apache-2.0
|
||||
|
||||
Applies to `sharp` and TypeScript. The full text is included verbatim in
|
||||
[`licenses/Apache-2.0.txt`](licenses/Apache-2.0.txt), copied from the licence that
|
||||
`sharp` ships.
|
||||
Applies to `sharp`, TypeScript and the SCUNet denoise weights. The full text is included
|
||||
verbatim in [`licenses/Apache-2.0.txt`](licenses/Apache-2.0.txt), copied from the licence
|
||||
that `sharp` ships.
|
||||
|
||||
### ISC
|
||||
|
||||
@@ -172,6 +181,6 @@ and libvips notices with it.
|
||||
|
||||
## Trademarks
|
||||
|
||||
Lensfun, LibRaw, libvips, sharp, React, Node.js, Debian, Liberation and DejaVu are the
|
||||
marks of their respective owners. They are used only to identify the software
|
||||
Lensfun, LibRaw, libvips, sharp, ONNX Runtime, SCUNet, Microsoft, React, Node.js,
|
||||
Debian, Liberation and DejaVu are the marks of their respective owners. They are used only to identify the software
|
||||
involved; Luminary is not affiliated with or endorsed by any of them.
|
||||
|
||||
|
After Width: | Height: | Size: 488 KiB |
|
Before Width: | Height: | Size: 390 KiB After Width: | Height: | Size: 488 KiB |
|
Before Width: | Height: | Size: 18 KiB After Width: | Height: | Size: 23 KiB |
|
Before Width: | Height: | Size: 17 KiB After Width: | Height: | Size: 43 KiB |
|
Before Width: | Height: | Size: 373 KiB After Width: | Height: | Size: 764 KiB |
|
Before Width: | Height: | Size: 343 KiB After Width: | Height: | Size: 365 KiB |
|
Before Width: | Height: | Size: 342 KiB After Width: | Height: | Size: 651 KiB |
|
Before Width: | Height: | Size: 51 KiB After Width: | Height: | Size: 116 KiB |
|
Before Width: | Height: | Size: 42 KiB After Width: | Height: | Size: 126 KiB |
|
Before Width: | Height: | Size: 174 KiB After Width: | Height: | Size: 187 KiB |
|
Before Width: | Height: | Size: 202 KiB After Width: | Height: | Size: 246 KiB |
|
Before Width: | Height: | Size: 192 KiB After Width: | Height: | Size: 394 KiB |
|
Before Width: | Height: | Size: 146 KiB After Width: | Height: | Size: 343 KiB |
|
Before Width: | Height: | Size: 185 KiB |
|
After Width: | Height: | Size: 501 KiB |
|
After Width: | Height: | Size: 384 KiB |
|
After Width: | Height: | Size: 285 KiB |
|
After Width: | Height: | Size: 226 KiB |
|
After Width: | Height: | Size: 398 KiB |
|
After Width: | Height: | Size: 198 KiB |
|
After Width: | Height: | Size: 111 KiB |
|
After Width: | Height: | Size: 114 KiB |
@@ -0,0 +1,212 @@
|
||||
# Linux (Ubuntu) bundle (optional)
|
||||
|
||||
An additive, self-contained way to produce a double-clickable Linux desktop
|
||||
install of Luminary. The server and Docker workflow stay the source of truth:
|
||||
this folder only *packages* the existing `dist/` + `server/` output, and the
|
||||
build writes its artifacts **outside the checkout** — exactly like
|
||||
[`windows/`](../windows/README.md).
|
||||
|
||||
## Isolation guarantees
|
||||
|
||||
1. **The packaging tree is additive.** There is no `package.json` script for
|
||||
this, and no change to `.gitignore` (beyond ignoring the tarball in
|
||||
`releases/`), `.dockerignore`, `Dockerfile`, `docker-compose.yml` or
|
||||
`scripts/deploy.mjs`. Invoke it directly: `node linux/build.mjs`. The only
|
||||
app-side behaviour used is the opt-in desktop mode in `server/config.mjs` +
|
||||
`server/index.mjs` (`LUMINARY_LOCAL=1`), which the Windows launcher already
|
||||
introduced; it stays off unless the launcher sets it.
|
||||
2. **Artifacts live outside the repo** (default: `~/.cache/luminary-linux`). The
|
||||
script refuses an `--out` inside the checkout, because `scripts/deploy.mjs`
|
||||
rsyncs the worktree to production and `docker build` would pull a ~300 MB
|
||||
bundle into its context.
|
||||
3. **The worktree must be clean outside `linux/`** before and after a build (the
|
||||
untracked `logo.png` is tolerated). `--allow-dirty` overrides it.
|
||||
4. **Nothing in the app changes at run time.** The bundle is the unchanged
|
||||
`server/` + `dist/` + production `node_modules`, started with `PORT`, `HOST`,
|
||||
`NODE_ENV` and `LUMINARY_DATA` — all variables the server already reads.
|
||||
|
||||
## What the end user needs
|
||||
|
||||
Ubuntu 22.04 or 24.04, 64-bit, and a browser. Nothing to install: Node 24 is
|
||||
inside the bundle (`runtime/bin/node`), sharp's Linux binaries are bundled, and
|
||||
there is no deb, no apt step and no root.
|
||||
|
||||
| Piece | What it uses |
|
||||
| --- | --- |
|
||||
| `runtime/bin/node` | the official Node 24 linux-x64 build, SHA-256 checked against nodejs.org |
|
||||
| `sharp` | `@img/sharp-linux-x64` + `@img/sharp-libvips-linux-x64`, installed from this repo's lockfile |
|
||||
| app window | Chrome, Chromium, Edge, Brave or Vivaldi `--app=`; Firefox and the default browser are fallbacks |
|
||||
| Develop module | a browser with WebGL2 |
|
||||
|
||||
## Build
|
||||
|
||||
```bash
|
||||
node linux/build.mjs # npm run build, then the bundle
|
||||
node linux/build.mjs --skip-build # reuse the existing dist/
|
||||
node linux/build.mjs --out /srv/builds/luminary-linux
|
||||
node linux/build.mjs --skip-build --publish
|
||||
```
|
||||
|
||||
Output:
|
||||
|
||||
```
|
||||
<out>/
|
||||
Luminary-0.5.2-linux-x64.tar.gz portable bundle
|
||||
Luminary-0.5.2-linux-amd64.deb Ubuntu package, built from the same bundle
|
||||
stage/Luminary/ the unpacked bundle (kept for inspection)
|
||||
cache/node-v24.22.2-linux-x64.tar.gz
|
||||
cache/SHASUMS256-v24.22.2.txt
|
||||
```
|
||||
|
||||
The build prints the archive size, its SHA-256, the Node version, the .deb size
|
||||
and the staged folder. The tarball keeps the executable bits on `luminary` and
|
||||
`runtime/bin/node`, so extracting it is enough — no `chmod` needed. The `.deb`
|
||||
is built with the `dpkg` package's `dpkg-deb` when it is installed; on a host
|
||||
without it the build prints a warning and produces only the tarball.
|
||||
|
||||
### Installing on Ubuntu
|
||||
|
||||
Easiest: install the `.deb`, which puts the app in `/opt/luminary`, adds
|
||||
`/usr/bin/luminary`, an applications-menu entry and the icon. Your photos and
|
||||
catalog still live in `~/.local/share/luminary`, so removing or upgrading the
|
||||
package never touches them:
|
||||
|
||||
```bash
|
||||
sudo apt install ./Luminary-0.5.2-linux-amd64.deb
|
||||
luminary # or launch Luminary from the applications menu
|
||||
```
|
||||
|
||||
`apt` pulls in the two runtime libraries it needs (`libstdc++6`, `libgomp1`);
|
||||
Node, the server and sharp's Linux binaries are inside the package. Uninstall
|
||||
with `sudo apt remove luminary`; `sudo apt purge luminary` also removes
|
||||
`/opt/luminary` but never the data folder.
|
||||
|
||||
Or stay portable — nothing installed, nothing to root:
|
||||
|
||||
```bash
|
||||
tar -xzf Luminary-0.5.2-linux-x64.tar.gz
|
||||
cd Luminary
|
||||
./luminary # starts desktop mode and opens the app window
|
||||
./install.sh # optional: add Luminary to the applications menu
|
||||
```
|
||||
|
||||
`--publish` copies the tarball and a `SHA256SUMS.txt` into
|
||||
[`releases/`](releases/), the hand-off folder for a USB stick, network share or
|
||||
release upload. That is the only write the builder makes inside the checkout.
|
||||
`scripts/deploy.mjs` rsyncs the worktree, so remove the tarball from `releases/`
|
||||
after transferring if you do not want it on the server.
|
||||
|
||||
## What is in the bundle
|
||||
|
||||
```
|
||||
Luminary/
|
||||
luminary bash launcher: start, health wait, app window
|
||||
install.sh adds ~/.local/share/applications/luminary.desktop
|
||||
Luminary.png 256×256 icon for the menu
|
||||
version.txt version, commit, and the Node pin (version, SHA-256, size)
|
||||
README-linux.txt end-user instructions
|
||||
LICENSE, THIRD_PARTY_NOTICES.md, licenses/
|
||||
runtime/ official Node 24 linux-x64 (bin/node, lib/node_modules)
|
||||
app/
|
||||
server/ unchanged, minus server/data and *.test.mjs
|
||||
dist/ the normal Vite build (UI, lens db, guide PDF)
|
||||
package.json provenance
|
||||
package-lock.json
|
||||
node_modules/ production deps installed with --os=linux --cpu=x64
|
||||
```
|
||||
|
||||
## Running it
|
||||
|
||||
`./luminary` picks a free loopback port from 8787, sets
|
||||
`LUMINARY_DATA=~/.local/share/luminary`, starts the server with
|
||||
`LUMINARY_LOCAL=1`, waits for `/api/health`, then opens a chromeless window:
|
||||
|
||||
```
|
||||
google-chrome --app=http://127.0.0.1:8787 \
|
||||
--user-data-dir=~/.local/share/luminary/window-profile \
|
||||
--class=Luminary
|
||||
```
|
||||
|
||||
No tabs, no address bar, its own profile and window size. `./luminary --browser`
|
||||
opens a normal tab instead (`LUMINARY_WINDOW=browser` works too).
|
||||
|
||||
| Command | What it does |
|
||||
| --- | --- |
|
||||
| `./luminary` | start (or reuse a running server) and open the window |
|
||||
| `./luminary --stop` | stop the server; data stays |
|
||||
| `./luminary --status` | bundle, data folder, pid, URL and `/api/health` |
|
||||
| `./luminary --verify` | list any missing piece of the bundle |
|
||||
| `./luminary --install` | add the applications-menu entry |
|
||||
| `./luminary --uninstall` | remove that entry, keep the catalog |
|
||||
|
||||
The `.deb` installs the same launcher as `/usr/bin/luminary`, so every flag
|
||||
works there too (`luminary --stop`, `--status`, `--verify`). Its data folder is
|
||||
the same `~/.local/share/luminary`.
|
||||
|
||||
### Single-user desktop mode
|
||||
|
||||
The launcher starts the server with `LUMINARY_LOCAL=1`, the same mode the
|
||||
Windows bundle uses:
|
||||
|
||||
- one admin (`local@luminary`) is created on first start and reused afterwards;
|
||||
- `/api/auth/me` answers without a cookie, so the UI never shows signup or
|
||||
sign-in, and registration returns 403;
|
||||
- the account is an admin, so every panel works, with no password to remember;
|
||||
- the server binds `127.0.0.1`, so this is not reachable from the network.
|
||||
Starting with `HOST=0.0.0.0` and `LUMINARY_LOCAL=1` logs a warning at boot.
|
||||
|
||||
## Smoke test
|
||||
|
||||
The automated first pass is [`SMOKE-LINUX.sh`](SMOKE-LINUX.sh). Run it from the
|
||||
extracted bundle (or a `.deb` install):
|
||||
|
||||
```bash
|
||||
./SMOKE-LINUX.sh # bundle in this folder
|
||||
./SMOKE-LINUX.sh --bundle /opt/luminary
|
||||
```
|
||||
|
||||
It reports the distribution, browser and display, checks the bundle files and
|
||||
`luminary --verify`, boots the real server through the launcher in desktop mode
|
||||
(`local:true`, cookieless `/api/auth/me`, closed registration, `/api/sync`),
|
||||
checks `--install`/`--uninstall` write and remove a real `.desktop` file, and
|
||||
confirms `--stop` stops it. It uses a throwaway data folder and a private
|
||||
`XDG_DATA_HOME`, so no real catalog or menu entry is touched, and it writes
|
||||
`smoke-report.txt` next to the bundle. The app window itself stays a visual
|
||||
check (the launcher runs with `LUMINARY_WINDOW=none` during the test).
|
||||
|
||||
## Data, updates and backups
|
||||
|
||||
- Catalog, originals, previews, `secret.key`, logs and the window profile live in
|
||||
`~/.local/share/luminary` (or `$LUMINARY_DATA`), never inside the bundle.
|
||||
- Update: `./luminary --stop`, replace `app/` and `runtime/` from a newer
|
||||
bundle, start again. The SQLite schema migrates on boot.
|
||||
- Back up: copy `~/.local/share/luminary` while Luminary is stopped, including
|
||||
`lumenroom.db`, `lumenroom.db-wal`, `lumenroom.db-shm`.
|
||||
|
||||
## Verifying a build
|
||||
|
||||
```bash
|
||||
cd <out>
|
||||
sha256sum Luminary-0.5.2-linux-x64.tar.gz
|
||||
tar -tzf Luminary-0.5.2-linux-x64.tar.gz | grep -E 'luminary$|runtime/bin/node$|app/server/index.mjs$'
|
||||
tar -xzf Luminary-0.5.2-linux-x64.tar.gz -C /tmp/luminary-check
|
||||
/tmp/luminary-check/Luminary/luminary --verify
|
||||
```
|
||||
|
||||
On a real desktop also check the window opens, the UI is signed in as the local
|
||||
admin, importing a RAW file works, and `--stop` closes the server.
|
||||
|
||||
## Limitations
|
||||
|
||||
- The `.deb` is unsigned (no repository, no signing key), so `apt` installs it
|
||||
locally without verification and there is no auto-update. Only the portable
|
||||
tarball and the `.deb` are produced — no AppImage or Snap in this version — and
|
||||
there is no tray icon.
|
||||
- The app window depends on a Chromium-based browser being installed; without
|
||||
one it falls back to Firefox or the default browser as a normal window.
|
||||
- Wayland compositors may ignore `--class=Luminary`, so the dock icon can be the
|
||||
browser's.
|
||||
- Loopback only by default; set `HOST=0.0.0.0` when starting the server by hand
|
||||
for LAN proofing galleries.
|
||||
- The launcher cannot clean up after a server crash; a stale PID file is ignored
|
||||
on the next start (`--status` reports "stopped").
|
||||
@@ -0,0 +1,277 @@
|
||||
#!/usr/bin/env bash
|
||||
# One-command smoke test for an extracted Luminary Linux bundle.
|
||||
#
|
||||
# Run it from the extracted bundle folder (or pass --bundle):
|
||||
#
|
||||
# ./SMOKE-LINUX.sh
|
||||
# ./SMOKE-LINUX.sh --bundle /opt/luminary
|
||||
#
|
||||
# It writes smoke-report.txt next to the bundle and prints the same lines.
|
||||
# Exit code 0 means every check passed.
|
||||
#
|
||||
# What it covers without a human clicking:
|
||||
# - distro, architecture, glibc, display, and which browser the launcher picks
|
||||
# - the bundle files the launcher needs, and `luminary --verify`
|
||||
# - a real boot through the launcher in desktop mode: /api/health local:true,
|
||||
# /api/auth/me 200 without a cookie, registration closed, /api/sync 200
|
||||
# - the menu entry install/uninstall writing and removing a real .desktop file
|
||||
# - `luminary --stop` actually stopping the server
|
||||
#
|
||||
# It uses a throwaway data folder under $TMPDIR and a private XDG_DATA_HOME, so
|
||||
# it never touches a real catalog or your applications menu. The app window is
|
||||
# not opened (the launcher runs with LUMINARY_WINDOW=none); it is a visual check.
|
||||
|
||||
set -u
|
||||
|
||||
BUNDLE=""
|
||||
while [ "$#" -gt 0 ]; do
|
||||
case "$1" in
|
||||
--bundle)
|
||||
BUNDLE="${2:-}"
|
||||
shift 2
|
||||
;;
|
||||
--help|-h)
|
||||
sed -n '2,20p' "$0" | sed 's/^# \{0,1\}//'
|
||||
exit 0
|
||||
;;
|
||||
*)
|
||||
printf 'unknown option %s (see --help)\n' "$1" >&2
|
||||
exit 2
|
||||
;;
|
||||
esac
|
||||
done
|
||||
[ -n "$BUNDLE" ] || BUNDLE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
||||
BUNDLE="$(readlink -f "$BUNDLE")"
|
||||
|
||||
LINES=()
|
||||
FAILED=0
|
||||
SKIPPED=0
|
||||
|
||||
say() {
|
||||
LINES+=("$*")
|
||||
printf '%s\n' "$*"
|
||||
}
|
||||
|
||||
check() {
|
||||
local name="$1" ok="$2" detail="${3:-}"
|
||||
if [ "$ok" = "0" ]; then
|
||||
say " PASS $name${detail:+ — $detail}"
|
||||
else
|
||||
FAILED=$((FAILED + 1))
|
||||
say " FAIL $name${detail:+ — $detail}"
|
||||
fi
|
||||
}
|
||||
|
||||
skip() {
|
||||
SKIPPED=$((SKIPPED + 1))
|
||||
say " SKIP $1${2:+ — $2}"
|
||||
}
|
||||
|
||||
[ -x "$BUNDLE/runtime/bin/node" ] && NODE="$BUNDLE/runtime/bin/node" || NODE="$(command -v node 2>/dev/null || true)"
|
||||
if [ -z "$NODE" ]; then
|
||||
printf 'Luminary: no Node runtime found in the bundle or on PATH\n' >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
WORK_DIR="$(mktemp -d "${TMPDIR:-/tmp}/luminary-smoke.XXXXXX")" || exit 1
|
||||
export XDG_DATA_HOME="$WORK_DIR/xdg"
|
||||
export LUMINARY_DATA="$WORK_DIR/data"
|
||||
export LUMINARY_WINDOW=none
|
||||
BODY="$WORK_DIR/body.json"
|
||||
URL=""
|
||||
|
||||
cleanup() {
|
||||
if [ -x "$BUNDLE/luminary" ] && [ -f "$LUMINARY_DATA/luminary.pid" ]; then
|
||||
"$BUNDLE/luminary" --stop >/dev/null 2>&1 || true
|
||||
fi
|
||||
rm -rf "$WORK_DIR"
|
||||
}
|
||||
trap cleanup EXIT
|
||||
|
||||
# http <method> <url> [json-body] -> status code on stdout, body in $BODY
|
||||
http() {
|
||||
"$NODE" -e '
|
||||
const [method, url, payload, out] = process.argv.slice(-4);
|
||||
const init = { method };
|
||||
if (payload) {
|
||||
init.headers = { "Content-Type": "application/json" };
|
||||
init.body = payload;
|
||||
}
|
||||
fetch(url, init)
|
||||
.then(async (r) => { require("node:fs").writeFileSync(out, await r.text()); process.stdout.write(String(r.status)); })
|
||||
.catch(() => process.stdout.write("0"));
|
||||
' "$1" "$2" "${3:-}" "$BODY"
|
||||
}
|
||||
|
||||
# jget <dotted.path> -> value from the last response body
|
||||
jget() {
|
||||
"$NODE" -e '
|
||||
const fs = require("node:fs");
|
||||
let value;
|
||||
try { value = JSON.parse(fs.readFileSync(process.argv.slice(-2)[0], "utf8")); } catch { process.exit(0); }
|
||||
for (const key of process.argv.slice(-1)[0].split(".")) value = value == null ? value : value[key];
|
||||
if (value !== undefined && value !== null) process.stdout.write(String(value));
|
||||
' "$BODY" "$1"
|
||||
}
|
||||
|
||||
browser_name() {
|
||||
local name
|
||||
for name in google-chrome google-chrome-stable chromium chromium-browser \
|
||||
microsoft-edge microsoft-edge-stable brave-browser vivaldi-stable firefox; do
|
||||
if command -v "$name" >/dev/null 2>&1; then
|
||||
printf '%s' "$name"
|
||||
return 0
|
||||
fi
|
||||
done
|
||||
return 1
|
||||
}
|
||||
|
||||
say 'Luminary Linux smoke test'
|
||||
say " bundle $BUNDLE"
|
||||
say " time $(date -Is)"
|
||||
|
||||
say ''
|
||||
say 'Environment'
|
||||
if [ -r /etc/os-release ]; then
|
||||
# shellcheck disable=SC1091
|
||||
distro="$(. /etc/os-release && printf '%s' "${PRETTY_NAME:-${NAME:-unknown}}")"
|
||||
else
|
||||
distro="$(uname -s)"
|
||||
fi
|
||||
say " distro $distro"
|
||||
say " arch $(uname -m)"
|
||||
say " kernel $(uname -r)"
|
||||
say " glibc $(ldd --version 2>/dev/null | head -n 1 || printf 'unknown')"
|
||||
say " display ${DISPLAY:-none}${WAYLAND_DISPLAY:+ (wayland $WAYLAND_DISPLAY)}"
|
||||
if browser="$(browser_name)"; then
|
||||
say " browser $browser"
|
||||
else
|
||||
say ' browser none found (the launcher would fall back to the default browser)'
|
||||
fi
|
||||
|
||||
say ''
|
||||
say 'Bundle'
|
||||
check 'luminary launcher present' $([ -x "$BUNDLE/luminary" ] && echo 0 || echo 1)
|
||||
check 'runtime/bin/node present' $([ -x "$BUNDLE/runtime/bin/node" ] && echo 0 || echo 1) "$BUNDLE/runtime/bin/node"
|
||||
check 'app/server/index.mjs present' $([ -f "$BUNDLE/app/server/index.mjs" ] && echo 0 || echo 1)
|
||||
check 'app/dist/index.html present' $([ -f "$BUNDLE/app/dist/index.html" ] && echo 0 || echo 1)
|
||||
check 'app/node_modules present' $([ -d "$BUNDLE/app/node_modules" ] && echo 0 || echo 1)
|
||||
node_version="$("$NODE" --version 2>/dev/null)"
|
||||
check 'node runs' $([ -n "$node_version" ] && echo 0 || echo 1) "$node_version"
|
||||
check 'node is 24 or newer' "$("$NODE" -e 'process.exit(Number(process.versions.node.split(".")[0]) >= 24 ? 0 : 1)' 2>/dev/null; echo $?)"
|
||||
|
||||
if [ -x "$BUNDLE/luminary" ]; then
|
||||
if "$BUNDLE/luminary" --verify >"$WORK_DIR/verify.txt" 2>&1; then
|
||||
check '--verify exits 0' 0
|
||||
else
|
||||
check '--verify exits 0' 1 "$(tr '\n' ' ' <"$WORK_DIR/verify.txt")"
|
||||
fi
|
||||
else
|
||||
check '--verify exits 0' 1 'launcher missing'
|
||||
fi
|
||||
|
||||
say ''
|
||||
say 'Server (desktop mode, via the launcher)'
|
||||
"$BUNDLE/luminary" >"$WORK_DIR/start.txt" 2>&1
|
||||
start_status=$?
|
||||
check 'launcher start exits 0' "$start_status" "$(head -n 1 "$WORK_DIR/start.txt")"
|
||||
|
||||
if [ -f "$LUMINARY_DATA/runtime.json" ]; then
|
||||
check 'runtime.json written' 0
|
||||
URL="http://127.0.0.1:$("$NODE" -p "JSON.parse(require('fs').readFileSync('$LUMINARY_DATA/runtime.json','utf8')).port")"
|
||||
else
|
||||
check 'runtime.json written' 1 "$LUMINARY_DATA/runtime.json"
|
||||
fi
|
||||
|
||||
if [ -n "$URL" ]; then
|
||||
code="$(http GET "$URL/api/health")"
|
||||
check 'health answers' $([ "$code" = "200" ] && echo 0 || echo 1) "HTTP $code"
|
||||
if [ "$code" = "200" ]; then
|
||||
check 'local mode advertised' $([ "$(jget local)" = "true" ] && echo 0 || echo 1) "local=$(jget local)"
|
||||
check 'version advertised' $([ -n "$(jget version)" ] && echo 0 || echo 1) "version=$(jget version)"
|
||||
check 'no setup prompt' $([ "$(jget needsSetup)" = "false" ] && echo 0 || echo 1)
|
||||
check 'registration closed' $([ "$(jget registrationOpen)" = "false" ] && echo 0 || echo 1)
|
||||
check 'libraw ready' $([ "$(jget raw.libraw)" = "true" ] && echo 0 || echo 1)
|
||||
check 'sharp ready' $([ "$(jget raw.sharp)" = "true" ] && echo 0 || echo 1)
|
||||
fi
|
||||
|
||||
code="$(http GET "$URL/api/auth/me")"
|
||||
me_email="$(jget user.email)"
|
||||
me_role="$(jget user.role)"
|
||||
check 'signed in without a cookie' $([ "$code" = "200" ] && echo 0 || echo 1) "HTTP $code $me_email ($me_role)"
|
||||
|
||||
code="$(http POST "$URL/api/auth/register" '{"email":"smoke@example.test","password":"smoke-test-password"}')"
|
||||
check 'registration refused' $([ "$code" = "403" ] && echo 0 || echo 1) "HTTP $code"
|
||||
|
||||
code="$(http GET "$URL/api/sync")"
|
||||
check '/api/sync answers' $([ "$code" = "200" ] && echo 0 || echo 1) "HTTP $code"
|
||||
|
||||
code="$(http GET "$URL/")"
|
||||
check 'UI index served' $([ "$code" = "200" ] && echo 0 || echo 1) "HTTP $code"
|
||||
if [ "$code" = "200" ] && grep -q 'src/assets\|assets/' "$BODY"; then
|
||||
check 'UI references built assets' 0
|
||||
else
|
||||
check 'UI references built assets' 1
|
||||
fi
|
||||
fi
|
||||
|
||||
if "$BUNDLE/luminary" --status 2>/dev/null | grep -q 'Status: running'; then
|
||||
check '--status reports running' 0
|
||||
else
|
||||
check '--status reports running' 1
|
||||
fi
|
||||
|
||||
say ''
|
||||
say 'Menu entry'
|
||||
if XDG_DATA_HOME="$WORK_DIR/xdg" "$BUNDLE/luminary" --install >/dev/null 2>&1 &&
|
||||
[ -f "$WORK_DIR/xdg/applications/luminary.desktop" ]; then
|
||||
check '--install writes a .desktop file' 0
|
||||
if grep -q "^Exec=\"\?$BUNDLE/luminary\"\?$" "$WORK_DIR/xdg/applications/luminary.desktop"; then
|
||||
check 'menu entry points at this bundle' 0
|
||||
else
|
||||
check 'menu entry points at this bundle' 1 "$(grep '^Exec=' "$WORK_DIR/xdg/applications/luminary.desktop")"
|
||||
fi
|
||||
else
|
||||
check '--install writes a .desktop file' 1
|
||||
fi
|
||||
if XDG_DATA_HOME="$WORK_DIR/xdg" "$BUNDLE/luminary" --uninstall >/dev/null 2>&1 &&
|
||||
[ ! -f "$WORK_DIR/xdg/applications/luminary.desktop" ]; then
|
||||
check '--uninstall removes it' 0
|
||||
else
|
||||
check '--uninstall removes it' 1
|
||||
fi
|
||||
|
||||
say ''
|
||||
say 'Stop'
|
||||
"$BUNDLE/luminary" --stop >/dev/null 2>&1
|
||||
if [ -n "$URL" ]; then
|
||||
code="$(http GET "$URL/api/health")"
|
||||
check 'server stopped' $([ "$code" = "0" ] && echo 0 || echo 1) "HTTP $code"
|
||||
else
|
||||
check 'server stopped' 1 'server never started'
|
||||
fi
|
||||
if "$BUNDLE/luminary" --status 2>/dev/null | grep -q 'Status: stopped'; then
|
||||
check '--status reports stopped' 0
|
||||
else
|
||||
check '--status reports stopped' 1
|
||||
fi
|
||||
|
||||
say ''
|
||||
say 'Window'
|
||||
skip 'app window opens' 'visual check; the launcher opened nothing during this run'
|
||||
|
||||
say ''
|
||||
if [ "$FAILED" -eq 0 ]; then
|
||||
say 'RESULT: PASS'
|
||||
else
|
||||
say "RESULT: FAIL ($FAILED check(s))"
|
||||
fi
|
||||
|
||||
report="$BUNDLE/smoke-report.txt"
|
||||
if ! { printf '%s\n' "${LINES[@]}" >"$report"; } 2>/dev/null; then
|
||||
report="$(pwd)/smoke-report.txt"
|
||||
printf '%s\n' "${LINES[@]}" >"$report" 2>/dev/null || true
|
||||
fi
|
||||
[ -f "$report" ] && say " report $report"
|
||||
|
||||
[ "$FAILED" -eq 0 ] && exit 0 || exit 1
|
||||
@@ -0,0 +1,771 @@
|
||||
#!/usr/bin/env node
|
||||
/**
|
||||
* Build the optional Linux (Ubuntu) desktop bundle for Luminary.
|
||||
*
|
||||
* Like windows/build.mjs this is *outside* the main build: it only reads the
|
||||
* repository (`dist/`, `server/`, `package.json`) and writes everything into a
|
||||
* directory outside the checkout. Nothing in `src/`, `server/`, `package.json`,
|
||||
* the Dockerfile, the deploy script or `dist/` is modified by this file, and no
|
||||
* npm script is added for it. Run it directly:
|
||||
*
|
||||
* node linux/build.mjs # build dist/ then the bundle
|
||||
* node linux/build.mjs --skip-build # reuse the existing dist/
|
||||
* node linux/build.mjs --out /srv/lum # choose the output directory
|
||||
*
|
||||
* The bundle keeps the layout the server expects (it derives `DIST_DIR` from
|
||||
* the parent of `server/`), so it is a plain folder plus a launcher:
|
||||
*
|
||||
* <out>/Luminary/
|
||||
* luminary bash launcher: start, health wait, app window
|
||||
* install.sh adds Luminary to the Ubuntu applications menu
|
||||
* Luminary.png icon
|
||||
* runtime/bin/node official Node 24 linux-x64, SHA-256 checked
|
||||
* app/ unchanged server/, dist/, production node_modules/
|
||||
* README-linux.txt
|
||||
* version.txt
|
||||
*/
|
||||
import { createHash } from 'node:crypto';
|
||||
import { spawnSync } from 'node:child_process';
|
||||
import {
|
||||
chmodSync,
|
||||
cpSync,
|
||||
existsSync,
|
||||
lstatSync,
|
||||
mkdirSync,
|
||||
readFileSync,
|
||||
readdirSync,
|
||||
renameSync,
|
||||
rmSync,
|
||||
statSync,
|
||||
symlinkSync,
|
||||
writeFileSync,
|
||||
} from 'node:fs';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
|
||||
const HERE = path.dirname(fileURLToPath(import.meta.url));
|
||||
const ROOT = path.resolve(HERE, '..');
|
||||
const LAUNCHER_FILES = path.join(HERE, 'launcher');
|
||||
const RELEASES_DIR = path.join(HERE, 'releases');
|
||||
const NPM = 'npm';
|
||||
const DEFAULT_NODE = 'v24.22.2';
|
||||
|
||||
const HELP = `Luminary Linux (Ubuntu) bundle
|
||||
|
||||
Usage: node linux/build.mjs [options]
|
||||
|
||||
--out <dir> output directory (default: <cache>/luminary-linux).
|
||||
Must be outside this repository; the bundle is staged in
|
||||
<out>/stage and archived to
|
||||
<out>/Luminary-<ver>-linux-x64.tar.gz.
|
||||
--skip-build reuse the existing dist/ instead of running npm run build
|
||||
--node <version> bundled Node version, e.g. v24.22.2 (must be >= 24)
|
||||
--allow-dirty skip the check that the checkout is clean outside linux/
|
||||
--publish copy the finished tar.gz and .deb to linux/releases (plus
|
||||
a SHA256SUMS.txt) so they can be handed off or uploaded
|
||||
--help print this text
|
||||
|
||||
Nothing in the repository is modified: the only writes outside the output
|
||||
directory are the ones npm and nodejs.org make for their own caches.
|
||||
`;
|
||||
|
||||
function fail(message) {
|
||||
process.stderr.write(`linux: FAILED: ${message}\n`);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
function log(step, message) {
|
||||
process.stdout.write(`linux: ${step.padEnd(9)} ${message}\n`);
|
||||
}
|
||||
|
||||
function warn(message) {
|
||||
process.stderr.write(`linux: warning: ${message}\n`);
|
||||
}
|
||||
|
||||
function defaultOutDir() {
|
||||
return path.join(process.env.XDG_CACHE_HOME || path.join(os.homedir(), '.cache'), 'luminary-linux');
|
||||
}
|
||||
|
||||
function parseArgs(argv) {
|
||||
const options = {
|
||||
out: defaultOutDir(),
|
||||
node: DEFAULT_NODE,
|
||||
build: true,
|
||||
allowDirty: false,
|
||||
publish: false,
|
||||
help: false,
|
||||
};
|
||||
const value = (index, flag) => {
|
||||
const next = argv[index + 1];
|
||||
if (!next || next.startsWith('--')) fail(`${flag} needs a value`);
|
||||
return next;
|
||||
};
|
||||
for (let i = 0; i < argv.length; i++) {
|
||||
const arg = argv[i];
|
||||
if (arg === '--out') {
|
||||
options.out = path.resolve(value(i, arg));
|
||||
i += 1;
|
||||
} else if (arg === '--node') {
|
||||
const version = value(i, arg);
|
||||
options.node = version.startsWith('v') ? version : `v${version}`;
|
||||
i += 1;
|
||||
} else if (arg === '--skip-build') {
|
||||
options.build = false;
|
||||
} else if (arg === '--allow-dirty') {
|
||||
options.allowDirty = true;
|
||||
} else if (arg === '--publish') {
|
||||
options.publish = true;
|
||||
} else if (arg === '--help' || arg === '-h') {
|
||||
options.help = true;
|
||||
} else {
|
||||
fail(`unknown option ${arg} (see --help)`);
|
||||
}
|
||||
}
|
||||
if (!/^v\d+\.\d+\.\d+$/.test(options.node)) {
|
||||
fail(`--node must look like v24.22.2 (got ${options.node})`);
|
||||
}
|
||||
return options;
|
||||
}
|
||||
|
||||
function git(args, { trim = true } = {}) {
|
||||
const result = spawnSync('git', args, { cwd: ROOT, encoding: 'utf8' });
|
||||
if (result.error || result.status !== 0) return null;
|
||||
return trim ? result.stdout.trim() : result.stdout;
|
||||
}
|
||||
|
||||
/**
|
||||
* The bundle must not land in the checkout: a staged Node runtime and
|
||||
* node_modules would otherwise be rsynced to production by scripts/deploy.mjs
|
||||
* and grow the Docker build context.
|
||||
*/
|
||||
function assertOutsideRepo(outDir) {
|
||||
const relative = path.relative(ROOT, outDir);
|
||||
const inside = !relative.startsWith('..') && !path.isAbsolute(relative);
|
||||
if (inside) {
|
||||
fail(
|
||||
`--out resolves inside the repository (${outDir}).\n` +
|
||||
'The bundle is large and would be copied by the deploy rsync; pick an\n' +
|
||||
'output directory outside the checkout, or omit --out to use the cache.',
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Only this folder may be dirty. `logo.png` is a long-standing untracked asset
|
||||
* in this checkout and is not part of the app, so it is tolerated.
|
||||
*/
|
||||
function checkRepoClean(options) {
|
||||
const status = git(['status', '--porcelain'], { trim: false });
|
||||
if (status === null) {
|
||||
warn('git is unavailable here; skipping the worktree check');
|
||||
return;
|
||||
}
|
||||
const unexpected = status
|
||||
.split('\n')
|
||||
.filter((line) => line.length > 3)
|
||||
.map((line) => line.slice(3).replace(/^"|"$/g, '').replace(/^.* -> /, '').trim())
|
||||
.filter((file) => file && !file.startsWith('linux/') && file !== 'logo.png');
|
||||
if (!unexpected.length) return;
|
||||
if (options.allowDirty) {
|
||||
warn(`building from a modified checkout: ${unexpected.join(', ')}`);
|
||||
return;
|
||||
}
|
||||
fail(
|
||||
`the checkout has changes outside linux/:\n ${unexpected.join('\n ')}\n` +
|
||||
'Commit or stash them, or pass --allow-dirty to build anyway.',
|
||||
);
|
||||
}
|
||||
|
||||
function readPackage() {
|
||||
const file = path.join(ROOT, 'package.json');
|
||||
if (!existsSync(file)) fail('run this from a Luminary checkout (package.json missing)');
|
||||
return JSON.parse(readFileSync(file, 'utf8'));
|
||||
}
|
||||
|
||||
function run(command, args, cwd, extraEnv) {
|
||||
log('run', [command, ...args].join(' '));
|
||||
const result = spawnSync(command, args, {
|
||||
cwd,
|
||||
stdio: 'inherit',
|
||||
env: extraEnv ? { ...process.env, ...extraEnv } : process.env,
|
||||
});
|
||||
if (result.error) fail(`${command} could not start: ${result.error.message}`);
|
||||
if (result.status !== 0) fail(`${command} ${args.join(' ')} exited with ${result.status}`);
|
||||
}
|
||||
|
||||
function ensureUi(options) {
|
||||
const dist = path.join(ROOT, 'dist', 'index.html');
|
||||
if (options.build) {
|
||||
log('ui', 'npm run build (typecheck + vite build, the normal artifact)');
|
||||
run(NPM, ['run', 'build'], ROOT);
|
||||
} else {
|
||||
log('ui', 'reusing the existing dist/ (--skip-build)');
|
||||
}
|
||||
if (!existsSync(dist)) {
|
||||
fail('dist/index.html is missing; drop --skip-build or run "npm run build" first');
|
||||
}
|
||||
return dist;
|
||||
}
|
||||
|
||||
function copyServer(bundle) {
|
||||
const server = path.join(bundle, 'app', 'server');
|
||||
cpSync(path.join(ROOT, 'server'), server, {
|
||||
recursive: true,
|
||||
filter: (source) => {
|
||||
const relative = path.relative(path.join(ROOT, 'server'), source).split(path.sep).join('/');
|
||||
// The developer catalog and the test files never belong in a bundle.
|
||||
if (relative === 'data' || relative.startsWith('data/')) return false;
|
||||
if (/\.test\.mjs$/.test(relative)) return false;
|
||||
return true;
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
function copyLegal(bundle) {
|
||||
for (const name of ['LICENSE', 'THIRD_PARTY_NOTICES.md']) {
|
||||
const source = path.join(ROOT, name);
|
||||
if (existsSync(source)) cpSync(source, path.join(bundle, name));
|
||||
}
|
||||
const licenses = path.join(ROOT, 'licenses');
|
||||
if (existsSync(licenses)) cpSync(licenses, path.join(bundle, 'licenses'), { recursive: true });
|
||||
}
|
||||
|
||||
function installLinuxDeps(bundle) {
|
||||
const appDir = path.join(bundle, 'app');
|
||||
cpSync(path.join(ROOT, 'package.json'), path.join(appDir, 'package.json'));
|
||||
cpSync(path.join(ROOT, 'package-lock.json'), path.join(appDir, 'package-lock.json'));
|
||||
log('deps', 'npm ci --omit=dev --os=linux --cpu=x64 (sharp linux-x64 prebuild)');
|
||||
// --ignore-scripts is safe: sharp 0.35 has no install step, it resolves the
|
||||
// prebuilt binary through optionalDependencies. ONNXRUNTIME_NODE_INSTALL=skip
|
||||
// also keeps onnxruntime-node's postinstall from pulling the CUDA libraries;
|
||||
// the package already ships its CPU binaries.
|
||||
run(
|
||||
NPM,
|
||||
['ci', '--omit=dev', '--os=linux', '--cpu=x64', '--no-audit', '--no-fund', '--ignore-scripts'],
|
||||
appDir,
|
||||
{ ONNXRUNTIME_NODE_INSTALL: 'skip' },
|
||||
);
|
||||
// .bin shims are for an interactive shell, not for `node server/index.mjs`.
|
||||
rmSync(path.join(appDir, 'node_modules', '.bin'), { recursive: true, force: true });
|
||||
verifySharp(appDir);
|
||||
}
|
||||
|
||||
function verifySharp(appDir) {
|
||||
const dir = path.join(appDir, 'node_modules', '@img', 'sharp-linux-x64');
|
||||
if (!existsSync(dir)) {
|
||||
warn('@img/sharp-linux-x64 is missing; the server will fall back to PNG proxies');
|
||||
return;
|
||||
}
|
||||
const binaries = [];
|
||||
const walk = (current) => {
|
||||
for (const entry of readdirSync(current, { withFileTypes: true })) {
|
||||
const absolute = path.join(current, entry.name);
|
||||
if (entry.isDirectory()) walk(absolute);
|
||||
else if (/\.(node|so(\.\d+)*)$/i.test(entry.name)) binaries.push(path.relative(dir, absolute));
|
||||
}
|
||||
};
|
||||
walk(dir);
|
||||
if (!binaries.some((file) => file.endsWith('.node'))) {
|
||||
warn('@img/sharp-linux-x64 has no .node binary; check the installed package');
|
||||
} else {
|
||||
log('deps', `sharp linux-x64 ready (${binaries.length} native files)`);
|
||||
}
|
||||
}
|
||||
|
||||
function sha256File(file) {
|
||||
return createHash('sha256').update(readFileSync(file)).digest('hex');
|
||||
}
|
||||
|
||||
async function download(url) {
|
||||
const response = await fetch(url);
|
||||
if (!response.ok) throw new Error(`${response.status} ${response.statusText} from ${url}`);
|
||||
return Buffer.from(await response.arrayBuffer());
|
||||
}
|
||||
|
||||
function extractTar(archive, destination) {
|
||||
mkdirSync(destination, { recursive: true });
|
||||
const result = spawnSync(
|
||||
'tar',
|
||||
['-xzf', archive, '-C', destination, '--strip-components=1'],
|
||||
{ stdio: 'inherit' },
|
||||
);
|
||||
if (result.error || result.status !== 0) {
|
||||
fail(`could not extract ${path.basename(archive)} (is tar installed?)`);
|
||||
}
|
||||
}
|
||||
|
||||
async function ensureNode(outDir, version) {
|
||||
const major = Number(version.slice(1).split('.')[0]);
|
||||
if (major < 24) {
|
||||
fail(`Node ${version} is too old: node:sqlite and type stripping need 24 LTS`);
|
||||
}
|
||||
const cache = path.join(outDir, 'cache');
|
||||
mkdirSync(cache, { recursive: true });
|
||||
const name = `node-${version}-linux-x64.tar.gz`;
|
||||
const archive = path.join(cache, name);
|
||||
const sums = path.join(cache, `SHASUMS256-${version}.txt`);
|
||||
const base = `https://nodejs.org/dist/${version}`;
|
||||
if (!existsSync(archive)) {
|
||||
// Unlike the Windows node.exe, the Linux tarballs sit at the dist root.
|
||||
log('node', `downloading ${base}/${name}`);
|
||||
try {
|
||||
writeFileSync(archive, await download(`${base}/${name}`));
|
||||
} catch (error) {
|
||||
fail(`could not download ${name}: ${error.message}`);
|
||||
}
|
||||
} else {
|
||||
log('node', `using cached ${name}`);
|
||||
}
|
||||
if (!existsSync(sums)) {
|
||||
try {
|
||||
writeFileSync(sums, (await download(`${base}/SHASUMS256.txt`)).toString('utf8'));
|
||||
} catch (error) {
|
||||
warn(`could not fetch SHASUMS256.txt (${error.message}); the cached tarball is unverified`);
|
||||
}
|
||||
}
|
||||
const hash = sha256File(archive);
|
||||
if (existsSync(sums)) {
|
||||
const line = readFileSync(sums, 'utf8')
|
||||
.split('\n')
|
||||
.map((row) => row.trim().split(/\s+/))
|
||||
.find((row) => row[1] === name);
|
||||
if (!line) fail(`SHASUMS256.txt for ${version} has no ${name} entry`);
|
||||
if (hash !== line[0]) {
|
||||
rmSync(archive, { force: true });
|
||||
fail(`${name} failed its SHA-256 check (${hash} != ${line[0]}); re-run to download again`);
|
||||
}
|
||||
log('node', `${version} linux-x64 verified (sha256 ${hash.slice(0, 12)}…)`);
|
||||
} else {
|
||||
warn(`using the Node tarball without a published checksum (sha256 ${hash})`);
|
||||
}
|
||||
return { archive, hash };
|
||||
}
|
||||
|
||||
function installRuntime(bundle, archive) {
|
||||
const runtime = path.join(bundle, 'runtime');
|
||||
rmSync(runtime, { recursive: true, force: true });
|
||||
log('runtime', 'extracting Node into runtime/ (bin/node, lib/node_modules)');
|
||||
extractTar(archive, runtime);
|
||||
const nodeBin = path.join(runtime, 'bin', 'node');
|
||||
if (!existsSync(nodeBin)) fail('the Node tarball did not contain runtime/bin/node');
|
||||
chmodSync(nodeBin, 0o755);
|
||||
const check = spawnSync(nodeBin, ['--version'], { encoding: 'utf8' });
|
||||
if (check.status !== 0) fail(`the bundled node binary does not run here: ${check.stderr || ''}`);
|
||||
log('runtime', `bundled ${check.stdout.trim()} runs on this host`);
|
||||
return nodeBin;
|
||||
}
|
||||
|
||||
function installLauncher(bundle) {
|
||||
const launcher = path.join(bundle, 'luminary');
|
||||
cpSync(path.join(LAUNCHER_FILES, 'luminary'), launcher);
|
||||
chmodSync(launcher, 0o755);
|
||||
const installer = path.join(bundle, 'install.sh');
|
||||
cpSync(path.join(LAUNCHER_FILES, 'install.sh'), installer);
|
||||
chmodSync(installer, 0o755);
|
||||
// Ships with the bundle so the first-run check is one command, and travels
|
||||
// into /opt/luminary in the .deb.
|
||||
const smoke = path.join(HERE, 'SMOKE-LINUX.sh');
|
||||
if (existsSync(smoke)) {
|
||||
cpSync(smoke, path.join(bundle, 'SMOKE-LINUX.sh'));
|
||||
chmodSync(path.join(bundle, 'SMOKE-LINUX.sh'), 0o755);
|
||||
}
|
||||
log('launcher', 'luminary (app window + --stop/--status/--install), install.sh, SMOKE-LINUX.sh');
|
||||
}
|
||||
|
||||
async function writeIcon(bundle) {
|
||||
const logo = path.join(ROOT, 'logo.png');
|
||||
const target = path.join(bundle, 'Luminary.png');
|
||||
if (!existsSync(logo)) {
|
||||
warn('logo.png is missing; the bundle has no menu icon');
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const { default: sharp } = await import('sharp');
|
||||
await sharp(logo).resize(256, 256, { fit: 'cover' }).png().toFile(target);
|
||||
log('icon', `Luminary.png (${(statSync(target).size / 1024).toFixed(0)} KB)`);
|
||||
} catch (error) {
|
||||
cpSync(logo, target);
|
||||
warn(`could not resize logo.png (${error.message}); copied it unchanged`);
|
||||
}
|
||||
}
|
||||
|
||||
function writeVersion(bundle, pkg, nodeVersion, nodeHash, nodeSize) {
|
||||
const commit = git(['rev-parse', '--short', 'HEAD']) ?? 'unknown';
|
||||
const lines = [
|
||||
`Luminary ${pkg.version}`,
|
||||
`commit ${commit}`,
|
||||
`built ${new Date().toISOString()}`,
|
||||
`node ${nodeVersion} linux-x64 sha256 ${nodeHash} size ${nodeSize}`,
|
||||
'launcher luminary (bash)',
|
||||
];
|
||||
writeFileSync(path.join(bundle, 'version.txt'), `${lines.join('\n')}\n`);
|
||||
return { version: pkg.version, commit };
|
||||
}
|
||||
|
||||
function writeBundleReadme(bundle, info) {
|
||||
const body = `Luminary ${info.version} for Linux (x64) — portable bundle
|
||||
==============================================
|
||||
|
||||
Start: ./luminary
|
||||
Stop: ./luminary --stop
|
||||
Menu: ./install.sh (adds Luminary to your applications menu)
|
||||
Open tab: ./luminary --browser
|
||||
Status: ./luminary --status
|
||||
Data: ~/.local/share/luminary (originals, previews, SQLite catalog)
|
||||
Logs: ~/.local/share/luminary/logs/server.out.log and server.err.log
|
||||
Sign-in: none — single-user desktop mode, no account setup
|
||||
|
||||
Requirements
|
||||
- Ubuntu 22.04 or 24.04, 64-bit (any glibc distribution of similar age works).
|
||||
- A Chromium-based browser for the app window: Chrome, Chromium, Edge, Brave
|
||||
or Vivaldi. Firefox is used as a normal window, and the default browser is
|
||||
the last resort. WebGL2 is needed for the Develop module.
|
||||
- Nothing to install: Node.js is included in runtime/, and sharp's Linux
|
||||
binaries are bundled. No root, no apt, no deb package.
|
||||
- About 250 MB free where the data folder lives.
|
||||
|
||||
Extract the tarball anywhere, then run ./luminary from the extracted folder.
|
||||
Nothing is written into /usr or /opt, so moving or deleting the folder is safe;
|
||||
the catalog lives in ~/.local/share/luminary and is not touched on removal.
|
||||
|
||||
./install.sh adds a menu entry (~/.local/share/applications/luminary.desktop)
|
||||
using this folder's absolute path, so install after you have put the folder
|
||||
where you want to keep it. ./luminary --uninstall removes the entry again.
|
||||
|
||||
Back up the catalog by copying ~/.local/share/luminary while Luminary is
|
||||
stopped, including lumenroom.db, lumenroom.db-wal, lumenroom.db-shm and
|
||||
secret.key.
|
||||
|
||||
Updating: stop Luminary, replace app/ and runtime/ from a newer bundle, start
|
||||
again. The data folder is outside the bundle and is untouched.
|
||||
|
||||
Notes
|
||||
- The server listens on 127.0.0.1 only. Set HOST=0.0.0.0 when starting it
|
||||
directly with node if client proofing galleries must reach other devices.
|
||||
- The app window is the browser's own app mode with a private profile, so it
|
||||
has no tabs or address bar. Some Wayland desktops ignore the requested
|
||||
window class; the window still opens.
|
||||
- RAW decoding uses the bundled libraw WebAssembly, so no system codec
|
||||
packages are needed.
|
||||
- Photo libraries on NTFS/exFAT drives work, but SQLite is happiest on a
|
||||
native Linux filesystem.
|
||||
`;
|
||||
writeFileSync(path.join(bundle, 'README-linux.txt'), body);
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ deb ---- */
|
||||
|
||||
function walkBytes(dir) {
|
||||
let total = 0;
|
||||
for (const entry of readdirSync(dir, { withFileTypes: true })) {
|
||||
const absolute = path.join(dir, entry.name);
|
||||
if (entry.isDirectory()) total += walkBytes(absolute);
|
||||
else total += lstatSync(absolute).size;
|
||||
}
|
||||
return total;
|
||||
}
|
||||
|
||||
const DEB_MAINTAINER_SCRIPT = `#!/bin/sh
|
||||
set -e
|
||||
|
||||
# Refresh the menu and icon caches so Luminary appears without a logout.
|
||||
if command -v update-desktop-database >/dev/null 2>&1; then
|
||||
update-desktop-database -q /usr/share/applications || true
|
||||
fi
|
||||
if command -v gtk-update-icon-cache >/dev/null 2>&1; then
|
||||
gtk-update-icon-cache -q -t -f /usr/share/icons/hicolor || true
|
||||
fi
|
||||
|
||||
exit 0
|
||||
`;
|
||||
|
||||
function debControlFile(pkg, installedBytes) {
|
||||
return [
|
||||
'Package: luminary',
|
||||
`Version: ${pkg.version}`,
|
||||
'Architecture: amd64',
|
||||
'Maintainer: Brian Hursey <bhursey@gmail.com>',
|
||||
`Installed-Size: ${Math.ceil(installedBytes / 1024)}`,
|
||||
'Depends: libc6, libstdc++6, libgomp1',
|
||||
'Recommends: chromium | google-chrome-stable | microsoft-edge-stable | firefox',
|
||||
'Section: graphics',
|
||||
'Priority: optional',
|
||||
'Homepage: https://git.maple-street.net/bhursey/luminary',
|
||||
'Description: photo library and raw editor',
|
||||
' Luminary catalogs photos, develops camera raw files and serves client',
|
||||
' proofing galleries. This package bundles the Node runtime and the server,',
|
||||
' so it installs with no other dependencies. Photos and the catalog live in',
|
||||
' ~/.local/share/luminary and are kept when the package is removed.',
|
||||
'',
|
||||
].join('\n');
|
||||
}
|
||||
|
||||
function debDesktopEntry() {
|
||||
return [
|
||||
'[Desktop Entry]',
|
||||
'Type=Application',
|
||||
'Version=1.0',
|
||||
'Name=Luminary',
|
||||
'GenericName=Photo library',
|
||||
'Comment=Photo library and raw editor',
|
||||
'Exec=/usr/bin/luminary',
|
||||
'Path=/opt/luminary',
|
||||
'Icon=luminary',
|
||||
'Terminal=false',
|
||||
'Categories=Graphics;Photography;',
|
||||
'Keywords=photo;raw;catalog;editor;',
|
||||
'StartupNotify=true',
|
||||
'StartupWMClass=Luminary',
|
||||
'',
|
||||
].join('\n');
|
||||
}
|
||||
|
||||
function debCopyright() {
|
||||
return [
|
||||
'Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/',
|
||||
'Upstream-Name: Luminary',
|
||||
'Source: https://git.maple-street.net/bhursey/luminary',
|
||||
'',
|
||||
'Files: *',
|
||||
'Copyright: 2026 Brian Hursey',
|
||||
'License: MIT',
|
||||
' The full MIT licence text is in /opt/luminary/LICENSE.',
|
||||
'',
|
||||
'Files: opt/luminary/app/node_modules/onnxruntime-node/*',
|
||||
'Copyright: Microsoft Corporation',
|
||||
'License: MIT',
|
||||
' ONNX Runtime; see /opt/luminary/THIRD_PARTY_NOTICES.md.',
|
||||
'',
|
||||
'Files: opt/luminary/app/server/denoise/scunet_color_25.onnx*',
|
||||
'Copyright: Kai Zhang and SCUNet contributors',
|
||||
'License: Apache-2.0',
|
||||
' See /opt/luminary/THIRD_PARTY_NOTICES.md.',
|
||||
'',
|
||||
].join('\n');
|
||||
}
|
||||
|
||||
/**
|
||||
* Builds the opt-in Ubuntu package from the same staged bundle. Installed as
|
||||
* /opt/luminary so the bundle layout (and therefore the launcher's bundle
|
||||
* detection) is unchanged; the data folder stays in the user's home.
|
||||
*/
|
||||
function buildDeb(outDir, pkg, bundle) {
|
||||
const probe = spawnSync('dpkg-deb', ['--version'], { encoding: 'utf8' });
|
||||
if (probe.error || probe.status !== 0) {
|
||||
warn('dpkg-deb is not installed; skipping the .deb (install the dpkg package)');
|
||||
return null;
|
||||
}
|
||||
|
||||
const work = path.join(outDir, 'deb.next');
|
||||
rmSync(work, { recursive: true, force: true });
|
||||
const root = path.join(work, 'root');
|
||||
|
||||
log('deb', 'staging /opt/luminary, /usr/bin/luminary and the menu entry');
|
||||
const appTarget = path.join(root, 'opt', 'luminary');
|
||||
mkdirSync(path.dirname(appTarget), { recursive: true });
|
||||
cpSync(bundle, appTarget, { recursive: true });
|
||||
|
||||
const binDir = path.join(root, 'usr', 'bin');
|
||||
mkdirSync(binDir, { recursive: true });
|
||||
// Relative link so the package works whatever the prefix.
|
||||
symlinkSync('../opt/luminary/luminary', path.join(binDir, 'luminary'));
|
||||
|
||||
const appsDir = path.join(root, 'usr', 'share', 'applications');
|
||||
mkdirSync(appsDir, { recursive: true });
|
||||
writeFileSync(path.join(appsDir, 'luminary.desktop'), debDesktopEntry());
|
||||
|
||||
const icon = path.join(bundle, 'Luminary.png');
|
||||
const iconDir = path.join(root, 'usr', 'share', 'icons', 'hicolor', '256x256', 'apps');
|
||||
mkdirSync(iconDir, { recursive: true });
|
||||
if (existsSync(icon)) cpSync(icon, path.join(iconDir, 'luminary.png'));
|
||||
else warn('the bundle has no Luminary.png; the menu entry will use a generic icon');
|
||||
|
||||
const docDir = path.join(root, 'usr', 'share', 'doc', 'luminary');
|
||||
mkdirSync(docDir, { recursive: true });
|
||||
cpSync(path.join(bundle, 'README-linux.txt'), path.join(docDir, 'README-linux.txt'));
|
||||
writeFileSync(path.join(docDir, 'copyright'), debCopyright());
|
||||
|
||||
const installedBytes = walkBytes(root);
|
||||
const controlDir = path.join(root, 'DEBIAN');
|
||||
mkdirSync(controlDir, { recursive: true });
|
||||
writeFileSync(path.join(controlDir, 'control'), debControlFile(pkg, installedBytes));
|
||||
for (const name of ['postinst', 'postrm']) {
|
||||
const file = path.join(controlDir, name);
|
||||
writeFileSync(file, DEB_MAINTAINER_SCRIPT);
|
||||
chmodSync(file, 0o755);
|
||||
}
|
||||
|
||||
const debPath = path.join(outDir, `Luminary-${pkg.version}-linux-amd64.deb`);
|
||||
rmSync(debPath, { force: true });
|
||||
const result = spawnSync(
|
||||
'dpkg-deb',
|
||||
['--root-owner-group', '-Zxz', '--build', root, debPath],
|
||||
{ stdio: 'inherit' },
|
||||
);
|
||||
if (result.error || result.status !== 0) fail('dpkg-deb could not build the package');
|
||||
|
||||
const listed = spawnSync('dpkg-deb', ['--contents', debPath], { encoding: 'utf8' });
|
||||
if (listed.status !== 0) fail('the .deb could not be read back');
|
||||
for (const required of [
|
||||
'opt/luminary/luminary',
|
||||
'opt/luminary/runtime/bin/node',
|
||||
'usr/bin/luminary',
|
||||
'usr/share/applications/luminary.desktop',
|
||||
]) {
|
||||
if (!listed.stdout.includes(required)) fail(`the .deb is missing ${required}`);
|
||||
}
|
||||
|
||||
log('deb', `${path.basename(debPath)} (${(statSync(debPath).size / 1024 / 1024).toFixed(1)} MB)`);
|
||||
rmSync(work, { recursive: true, force: true });
|
||||
return debPath;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ tar ---- */
|
||||
|
||||
function createArchive(workRoot, tarPath) {
|
||||
rmSync(tarPath, { force: true });
|
||||
const deterministic = [
|
||||
'--sort=name',
|
||||
'--owner=0',
|
||||
'--group=0',
|
||||
'--numeric-owner',
|
||||
'--mtime=@1577836800',
|
||||
'-czf',
|
||||
tarPath,
|
||||
'-C',
|
||||
workRoot,
|
||||
'Luminary',
|
||||
];
|
||||
let result = spawnSync('tar', deterministic, { stdio: 'inherit' });
|
||||
if (result.error || result.status !== 0) {
|
||||
warn('this tar has no --sort/--owner support; writing a plain archive instead');
|
||||
result = spawnSync('tar', ['-czf', tarPath, '-C', workRoot, 'Luminary'], { stdio: 'inherit' });
|
||||
}
|
||||
if (result.error || result.status !== 0) fail('tar could not create the archive');
|
||||
const list = spawnSync('tar', ['-tzf', tarPath], { encoding: 'utf8' });
|
||||
if (list.status !== 0) fail('the archive could not be read back');
|
||||
const entries = list.stdout.split('\n').filter(Boolean);
|
||||
for (const required of [
|
||||
'Luminary/luminary',
|
||||
'Luminary/runtime/bin/node',
|
||||
'Luminary/app/server/index.mjs',
|
||||
'Luminary/app/dist/index.html',
|
||||
]) {
|
||||
if (!entries.includes(required)) fail(`the archive is missing ${required}`);
|
||||
}
|
||||
return { files: entries.length, bytes: statSync(tarPath).size };
|
||||
}
|
||||
|
||||
/* ----------------------------------------------------------------- main ---- */
|
||||
|
||||
async function main() {
|
||||
const options = parseArgs(process.argv.slice(2));
|
||||
if (options.help) {
|
||||
process.stdout.write(HELP);
|
||||
return 0;
|
||||
}
|
||||
assertOutsideRepo(options.out);
|
||||
const pkg = readPackage();
|
||||
log('repo', `${pkg.name} ${pkg.version} at ${ROOT}`);
|
||||
log('out', options.out);
|
||||
checkRepoClean(options);
|
||||
ensureUi(options);
|
||||
|
||||
// Build into a sibling and swap at the end, so a failed run never replaces
|
||||
// the last complete bundle with a partial tree.
|
||||
const stageRoot = path.join(options.out, 'stage');
|
||||
const workRoot = path.join(options.out, 'stage.next');
|
||||
const bundle = path.join(workRoot, 'Luminary');
|
||||
rmSync(workRoot, { recursive: true, force: true });
|
||||
mkdirSync(path.join(bundle, 'app'), { recursive: true });
|
||||
|
||||
log('stage', 'copying dist/ and server/ (unchanged layout the server expects)');
|
||||
cpSync(path.join(ROOT, 'dist'), path.join(bundle, 'app', 'dist'), { recursive: true });
|
||||
copyServer(bundle);
|
||||
copyLegal(bundle);
|
||||
installLinuxDeps(bundle);
|
||||
|
||||
const node = await ensureNode(options.out, options.node);
|
||||
const nodeBin = installRuntime(bundle, node.archive);
|
||||
// Remember the size now: the bundle is renamed into stage/ before the summary.
|
||||
const nodeBinSize = statSync(nodeBin).size;
|
||||
|
||||
installLauncher(bundle);
|
||||
await writeIcon(bundle);
|
||||
|
||||
const info = writeVersion(
|
||||
bundle,
|
||||
pkg,
|
||||
options.node,
|
||||
node.hash,
|
||||
statSync(node.archive).size,
|
||||
);
|
||||
writeBundleReadme(bundle, info);
|
||||
|
||||
const tarPath = path.join(options.out, `Luminary-${pkg.version}-linux-x64.tar.gz`);
|
||||
log('tar', path.basename(tarPath));
|
||||
const archive = createArchive(workRoot, tarPath);
|
||||
|
||||
// The .deb is built from the same staged bundle, before it is moved into
|
||||
// stage/, so both artifacts are guaranteed to come from one build.
|
||||
const debPath = buildDeb(options.out, pkg, bundle);
|
||||
|
||||
rmSync(stageRoot, { recursive: true, force: true });
|
||||
renameSync(workRoot, stageRoot);
|
||||
|
||||
// The isolation contract: nothing outside linux/ may have changed.
|
||||
if (!options.allowDirty) checkRepoClean(options);
|
||||
const stagedBundle = path.join(stageRoot, 'Luminary');
|
||||
|
||||
// Hand-off copy. Staging and the archives stay outside the checkout; this is
|
||||
// the one write into the repository, into linux/releases.
|
||||
const published = [];
|
||||
if (options.publish) {
|
||||
mkdirSync(RELEASES_DIR, { recursive: true });
|
||||
const sums = [];
|
||||
for (const artifact of [tarPath, ...(debPath ? [debPath] : [])]) {
|
||||
const target = path.join(RELEASES_DIR, path.basename(artifact));
|
||||
cpSync(artifact, target);
|
||||
sums.push(`${sha256File(target)} ${path.basename(target)}`);
|
||||
log('publish', path.relative(ROOT, target));
|
||||
published.push(target);
|
||||
}
|
||||
writeFileSync(path.join(RELEASES_DIR, 'SHA256SUMS.txt'), `${sums.join('\n')}\n`);
|
||||
}
|
||||
|
||||
process.stdout.write(
|
||||
[
|
||||
'',
|
||||
'linux build PASSED',
|
||||
` artifact ${tarPath}`,
|
||||
` size ${(archive.bytes / 1024 / 1024).toFixed(1)} MB (${archive.files} entries)`,
|
||||
` sha256 ${sha256File(tarPath)}`,
|
||||
` node ${options.node} linux-x64 (${(nodeBinSize / 1024 / 1024).toFixed(0)} MB binary)`,
|
||||
` launcher luminary (bash)`,
|
||||
...(debPath
|
||||
? [
|
||||
` deb ${debPath}`,
|
||||
` deb size ${(statSync(debPath).size / 1024 / 1024).toFixed(1)} MB`,
|
||||
]
|
||||
: []),
|
||||
` staged ${stagedBundle}`,
|
||||
...published.map((file) => ` publish ${path.relative(ROOT, file)}`),
|
||||
'',
|
||||
published.length
|
||||
? 'Only linux/ was written: the archives in linux/releases are ready to transfer.'
|
||||
: 'The repository was not modified; only linux/ and the output directory were touched.',
|
||||
'',
|
||||
].join('\n'),
|
||||
);
|
||||
return 0;
|
||||
}
|
||||
|
||||
main().then(
|
||||
(code) => {
|
||||
process.exitCode = code;
|
||||
},
|
||||
(error) => {
|
||||
fail(error instanceof Error ? error.message : String(error));
|
||||
},
|
||||
);
|
||||
@@ -0,0 +1,10 @@
|
||||
#!/usr/bin/env bash
|
||||
# Add this Luminary bundle to the Ubuntu applications menu.
|
||||
#
|
||||
# Creates ~/.local/share/applications/luminary.desktop pointing at this folder,
|
||||
# so keep the folder where it is (or re-run this after moving it). Photos and the
|
||||
# catalog stay in ~/.local/share/luminary and are never touched by the menu entry.
|
||||
set -euo pipefail
|
||||
|
||||
here="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
||||
exec "$here/luminary" --install
|
||||
@@ -0,0 +1,357 @@
|
||||
#!/usr/bin/env bash
|
||||
# Luminary desktop launcher for Linux.
|
||||
#
|
||||
# Starts the bundled server in single-user desktop mode on a free loopback port,
|
||||
# waits for /api/health, then opens the UI in a chromeless app window (Chrome,
|
||||
# Chromium, Edge, Brave or Vivaldi). Firefox, or the default browser, is the
|
||||
# fallback.
|
||||
#
|
||||
# ./luminary start and open the window
|
||||
# ./luminary --stop stop the running server
|
||||
# ./luminary --status report pid, URL, data folder and health
|
||||
# ./luminary --browser open a normal browser tab instead
|
||||
# ./luminary --verify check that this is a complete bundle
|
||||
# ./luminary --install add Luminary to the applications menu
|
||||
# ./luminary --uninstall remove that menu entry
|
||||
#
|
||||
# Everything the app writes lives in ~/.local/share/luminary (or $LUMINARY_DATA),
|
||||
# never inside this folder, so the bundle can be moved or deleted safely.
|
||||
|
||||
set -u
|
||||
|
||||
SELF="$(readlink -f "${BASH_SOURCE[0]}")"
|
||||
BUNDLE="$(dirname "$SELF")"
|
||||
APP="$BUNDLE/app"
|
||||
DATA_DIR="${LUMINARY_DATA:-${XDG_DATA_HOME:-$HOME/.local/share}/luminary}"
|
||||
LOG_DIR="$DATA_DIR/logs"
|
||||
PID_FILE="$DATA_DIR/luminary.pid"
|
||||
RUNTIME_FILE="$DATA_DIR/runtime.json"
|
||||
FIRST_PORT=8787
|
||||
LAST_PORT=8887
|
||||
WINDOW_MODE="${LUMINARY_WINDOW:-window}"
|
||||
|
||||
say() { printf '%s\n' "$*"; }
|
||||
problem() { printf 'Luminary: %s\n' "$*" >&2; }
|
||||
|
||||
usage() {
|
||||
sed -n '2,18p' "$SELF" | sed 's/^# \{0,1\}//'
|
||||
}
|
||||
|
||||
find_node() {
|
||||
if [ -x "$BUNDLE/runtime/bin/node" ]; then
|
||||
NODE="$BUNDLE/runtime/bin/node"
|
||||
return 0
|
||||
fi
|
||||
if command -v node >/dev/null 2>&1; then
|
||||
NODE="$(command -v node)"
|
||||
return 0
|
||||
fi
|
||||
problem "No Node runtime found: runtime/bin/node is missing and there is no node on PATH."
|
||||
problem "Download this bundle again, or install Node 24 (https://nodejs.org)."
|
||||
return 1
|
||||
}
|
||||
|
||||
node_is_recent() {
|
||||
"$NODE" -e 'process.exit(Number(process.versions.node.split(".")[0]) >= 24 ? 0 : 1)' 2>/dev/null
|
||||
}
|
||||
|
||||
port_free() {
|
||||
! (exec 3<>"/dev/tcp/127.0.0.1/$1") 2>/dev/null
|
||||
}
|
||||
|
||||
choose_port() {
|
||||
local port="$FIRST_PORT"
|
||||
while [ "$port" -le "$LAST_PORT" ]; do
|
||||
if port_free "$port"; then
|
||||
printf '%s' "$port"
|
||||
return 0
|
||||
fi
|
||||
port=$((port + 1))
|
||||
done
|
||||
return 1
|
||||
}
|
||||
|
||||
running_pid() {
|
||||
[ -f "$PID_FILE" ] || return 1
|
||||
local pid
|
||||
pid="$(cat "$PID_FILE" 2>/dev/null)"
|
||||
[ -n "$pid" ] || return 1
|
||||
kill -0 "$pid" 2>/dev/null || return 1
|
||||
printf '%s' "$pid"
|
||||
}
|
||||
|
||||
current_port() {
|
||||
[ -f "$RUNTIME_FILE" ] || return 1
|
||||
sed -n 's/.*"port": *\([0-9][0-9]*\).*/\1/p' "$RUNTIME_FILE" | head -n 1
|
||||
}
|
||||
|
||||
wait_health() {
|
||||
local url="http://127.0.0.1:$1/api/health" tries=0
|
||||
while [ "$tries" -lt 150 ]; do
|
||||
if "$NODE" -e "fetch('$url').then(r => process.exit(r.ok ? 0 : 1)).catch(() => process.exit(1))" >/dev/null 2>&1; then
|
||||
return 0
|
||||
fi
|
||||
tries=$((tries + 1))
|
||||
sleep 0.2
|
||||
done
|
||||
return 1
|
||||
}
|
||||
|
||||
verify_bundle() {
|
||||
local missing=0
|
||||
for rel in runtime/bin/node app/server/index.mjs app/dist/index.html luminary; do
|
||||
if [ ! -e "$BUNDLE/$rel" ]; then
|
||||
problem "missing: $rel"
|
||||
missing=1
|
||||
fi
|
||||
done
|
||||
if [ -d "$APP/node_modules" ]; then
|
||||
say "node_modules: present"
|
||||
else
|
||||
problem "missing: app/node_modules (production dependencies)"
|
||||
missing=1
|
||||
fi
|
||||
if [ "$missing" -ne 0 ]; then
|
||||
problem "This folder is not a complete Luminary bundle; extract the whole tarball."
|
||||
return 1
|
||||
fi
|
||||
say "Bundle: $BUNDLE"
|
||||
say "Version: $(sed -n '1p' "$BUNDLE/version.txt" 2>/dev/null)"
|
||||
if find_node; then
|
||||
say "Node: $("$NODE" --version 2>/dev/null) ($NODE)"
|
||||
fi
|
||||
return 0
|
||||
}
|
||||
|
||||
start() {
|
||||
local pid port
|
||||
pid="$(running_pid)" && {
|
||||
port="$(current_port)"
|
||||
if [ -n "${port:-}" ]; then
|
||||
say "Luminary is already running at http://127.0.0.1:$port (pid $pid)."
|
||||
open_window "http://127.0.0.1:$port"
|
||||
return 0
|
||||
fi
|
||||
say "Luminary is already running (pid $pid)."
|
||||
return 0
|
||||
}
|
||||
|
||||
verify_bundle >/dev/null || return 1
|
||||
find_node || return 1
|
||||
if ! node_is_recent; then
|
||||
problem "Node $("$NODE" --version 2>/dev/null) is too old; Luminary needs Node 24 or newer."
|
||||
return 1
|
||||
fi
|
||||
|
||||
mkdir -p "$DATA_DIR" "$LOG_DIR" || {
|
||||
problem "could not create $DATA_DIR"
|
||||
return 1
|
||||
}
|
||||
chmod 700 "$DATA_DIR" 2>/dev/null || true
|
||||
|
||||
port="$(choose_port)" || {
|
||||
problem "no free loopback port between $FIRST_PORT and $LAST_PORT"
|
||||
return 1
|
||||
}
|
||||
|
||||
(
|
||||
cd "$APP" || exit 1
|
||||
LUMINARY_LOCAL=1 \
|
||||
PORT="$port" \
|
||||
HOST=127.0.0.1 \
|
||||
NODE_ENV=production \
|
||||
LUMINARY_DATA="$DATA_DIR" \
|
||||
nohup "$NODE" server/index.mjs >>"$LOG_DIR/server.out.log" 2>>"$LOG_DIR/server.err.log" &
|
||||
printf '%s\n' "$!" >"$PID_FILE"
|
||||
)
|
||||
|
||||
pid="$(cat "$PID_FILE" 2>/dev/null)"
|
||||
if ! wait_health "$port"; then
|
||||
problem "the server did not answer on /api/health."
|
||||
problem "See $LOG_DIR/server.err.log, or run: cd \"$APP\" && \"$NODE\" server/index.mjs"
|
||||
return 1
|
||||
fi
|
||||
|
||||
printf '{"pid": %s, "port": %s, "url": "http://127.0.0.1:%s", "data": "%s"}\n' \
|
||||
"$pid" "$port" "$port" "$DATA_DIR" >"$RUNTIME_FILE"
|
||||
|
||||
say "Luminary is running at http://127.0.0.1:$port (pid $pid)"
|
||||
say "Data: $DATA_DIR"
|
||||
if [ "$WINDOW_MODE" = "browser" ]; then
|
||||
open_tab "http://127.0.0.1:$port"
|
||||
elif [ "$WINDOW_MODE" = "none" ]; then
|
||||
# Used by SMOKE-LINUX.sh: start the server but do not open anything.
|
||||
:
|
||||
else
|
||||
open_window "http://127.0.0.1:$port" || open_tab "http://127.0.0.1:$port"
|
||||
fi
|
||||
return 0
|
||||
}
|
||||
|
||||
stop() {
|
||||
local pid
|
||||
if ! pid="$(running_pid)"; then
|
||||
rm -f "$PID_FILE" "$RUNTIME_FILE"
|
||||
say "Luminary is not running."
|
||||
return 0
|
||||
fi
|
||||
kill "$pid" 2>/dev/null
|
||||
local tries=0
|
||||
while kill -0 "$pid" 2>/dev/null && [ "$tries" -lt 50 ]; do
|
||||
tries=$((tries + 1))
|
||||
sleep 0.1
|
||||
done
|
||||
if kill -0 "$pid" 2>/dev/null; then
|
||||
kill -9 "$pid" 2>/dev/null
|
||||
fi
|
||||
rm -f "$PID_FILE" "$RUNTIME_FILE"
|
||||
say "Stopped Luminary (pid $pid)."
|
||||
}
|
||||
|
||||
status() {
|
||||
local pid port
|
||||
say "Bundle: $BUNDLE"
|
||||
say "Data: $DATA_DIR"
|
||||
if pid="$(running_pid)"; then
|
||||
port="$(current_port)"
|
||||
say "Status: running (pid $pid)"
|
||||
if [ -n "${port:-}" ]; then
|
||||
say "URL: http://127.0.0.1:$port"
|
||||
find_node >/dev/null 2>&1 &&
|
||||
"$NODE" -e "fetch('http://127.0.0.1:$port/api/health').then(r => process.exit(r.ok ? 0 : 1)).catch(() => process.exit(1))" >/dev/null 2>&1 &&
|
||||
say "Health: ok" || say "Health: unreachable"
|
||||
fi
|
||||
else
|
||||
say "Status: stopped"
|
||||
fi
|
||||
say "Logs: $LOG_DIR"
|
||||
}
|
||||
|
||||
browser_candidates() {
|
||||
printf '%s\n' google-chrome google-chrome-stable chromium chromium-browser \
|
||||
microsoft-edge microsoft-edge-stable brave-browser vivaldi-stable
|
||||
}
|
||||
|
||||
open_window() {
|
||||
local url="$1" name browser
|
||||
while IFS= read -r name; do
|
||||
if browser="$(command -v "$name" 2>/dev/null)"; then
|
||||
say "Opening the app window with $name"
|
||||
setsid "$browser" \
|
||||
--app="$url" \
|
||||
--user-data-dir="$DATA_DIR/window-profile" \
|
||||
--class=Luminary \
|
||||
--no-first-run \
|
||||
--no-default-browser-check \
|
||||
>/dev/null 2>&1 &
|
||||
return 0
|
||||
fi
|
||||
done <<EOF
|
||||
$(browser_candidates)
|
||||
EOF
|
||||
if command -v firefox >/dev/null 2>&1; then
|
||||
say "No Chromium-based browser found; opening Firefox."
|
||||
setsid firefox --new-window "$url" >/dev/null 2>&1 &
|
||||
return 0
|
||||
fi
|
||||
return 1
|
||||
}
|
||||
|
||||
open_tab() {
|
||||
local url="$1"
|
||||
if command -v xdg-open >/dev/null 2>&1; then
|
||||
setsid xdg-open "$url" >/dev/null 2>&1 &
|
||||
say "Opening $url in your browser."
|
||||
return 0
|
||||
fi
|
||||
say "Open $url in your browser."
|
||||
return 0
|
||||
}
|
||||
|
||||
desktop_dir() {
|
||||
printf '%s' "${XDG_DATA_HOME:-$HOME/.local/share}/applications"
|
||||
}
|
||||
|
||||
icon_dir() {
|
||||
printf '%s' "${XDG_DATA_HOME:-$HOME/.local/share}/icons/hicolor/256x256/apps"
|
||||
}
|
||||
|
||||
install_menu_entry() {
|
||||
local apps icons entry
|
||||
apps="$(desktop_dir)"
|
||||
icons="$(icon_dir)"
|
||||
mkdir -p "$apps" "$icons" || {
|
||||
problem "could not create $apps"
|
||||
return 1
|
||||
}
|
||||
if [ -f "$BUNDLE/Luminary.png" ]; then
|
||||
cp "$BUNDLE/Luminary.png" "$icons/luminary.png"
|
||||
fi
|
||||
entry="$apps/luminary.desktop"
|
||||
cat >"$entry" <<EOF
|
||||
[Desktop Entry]
|
||||
Type=Application
|
||||
Version=1.0
|
||||
Name=Luminary
|
||||
GenericName=Photo library
|
||||
Comment=Photo library and raw editor
|
||||
Exec="$SELF"
|
||||
Path=$BUNDLE
|
||||
Icon=$icons/luminary.png
|
||||
Terminal=false
|
||||
Categories=Graphics;Photography;
|
||||
Keywords=photo;raw;catalog;editor;
|
||||
StartupNotify=true
|
||||
StartupWMClass=Luminary
|
||||
EOF
|
||||
chmod +x "$entry"
|
||||
if command -v update-desktop-database >/dev/null 2>&1; then
|
||||
update-desktop-database "$apps" >/dev/null 2>&1 || true
|
||||
fi
|
||||
say "Added Luminary to your applications menu: $entry"
|
||||
say "If it does not appear yet, log out and back in."
|
||||
}
|
||||
|
||||
uninstall_menu_entry() {
|
||||
local entry
|
||||
entry="$(desktop_dir)/luminary.desktop"
|
||||
rm -f "$entry"
|
||||
rm -f "$(icon_dir)/luminary.png"
|
||||
if command -v update-desktop-database >/dev/null 2>&1; then
|
||||
update-desktop-database "$(desktop_dir)" >/dev/null 2>&1 || true
|
||||
fi
|
||||
say "Removed the menu entry. Your photos and catalog in $DATA_DIR were kept."
|
||||
}
|
||||
|
||||
case "${1:-}" in
|
||||
""|--start)
|
||||
start
|
||||
;;
|
||||
--stop)
|
||||
stop
|
||||
;;
|
||||
--status)
|
||||
status
|
||||
;;
|
||||
--browser)
|
||||
WINDOW_MODE=browser
|
||||
start
|
||||
;;
|
||||
--verify)
|
||||
verify_bundle
|
||||
;;
|
||||
--install)
|
||||
install_menu_entry
|
||||
;;
|
||||
--uninstall)
|
||||
uninstall_menu_entry
|
||||
;;
|
||||
--help|-h)
|
||||
usage
|
||||
;;
|
||||
*)
|
||||
problem "unknown option $1"
|
||||
usage >&2
|
||||
exit 2
|
||||
;;
|
||||
esac
|
||||
@@ -0,0 +1,3 @@
|
||||
# Transfer-only release archives: keep the checksums reviewable, not the tarballs.
|
||||
*.tar.gz
|
||||
*.deb
|
||||
@@ -0,0 +1,29 @@
|
||||
# Linux release hand-off
|
||||
|
||||
`node linux/build.mjs --skip-build --publish` drops the finished artifacts here:
|
||||
|
||||
```
|
||||
Luminary-0.5.2-linux-x64.tar.gz portable bundle
|
||||
Luminary-0.5.2-linux-amd64.deb Ubuntu package
|
||||
SHA256SUMS.txt
|
||||
```
|
||||
|
||||
The archives are git-ignored; only `SHA256SUMS.txt` and this note are tracked,
|
||||
so the checksums stay reviewable while the multi-hundred-megabyte archives do
|
||||
not end up in the repository (or in the deploy rsync).
|
||||
|
||||
Verify a copy with:
|
||||
|
||||
```bash
|
||||
sha256sum -c SHA256SUMS.txt
|
||||
tar -tzf Luminary-0.5.2-linux-x64.tar.gz | head
|
||||
dpkg-deb --info Luminary-0.5.2-linux-amd64.deb
|
||||
```
|
||||
|
||||
On Ubuntu the easiest install is `sudo apt install ./Luminary-0.5.2-linux-amd64.deb`,
|
||||
which adds Luminary to the applications menu. The portable route is to extract
|
||||
the whole tarball and run `./luminary` from the extracted `Luminary` folder;
|
||||
`./install.sh` adds that copy to the applications menu.
|
||||
|
||||
After publishing, the product site needs the new `.deb` copied to
|
||||
`luminary-site/downloads/` with the size and SHA-256 in its download card.
|
||||
@@ -0,0 +1,2 @@
|
||||
5e5725d8b918b161d7fd0633049f90fa46d2892ba8930db4230b59c2f556602e Luminary-0.5.2-linux-x64.tar.gz
|
||||
c7a8325e8a1a58880d30cbec167fe1f75feb8877b41fa8857200602e09ac5a96 Luminary-0.5.2-linux-amd64.deb
|
||||
@@ -0,0 +1,34 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
||||
<plist version="1.0">
|
||||
<dict>
|
||||
<key>CFBundleName</key>
|
||||
<string>Luminary</string>
|
||||
<key>CFBundleDisplayName</key>
|
||||
<string>Luminary</string>
|
||||
<key>CFBundleIdentifier</key>
|
||||
<string>__BUNDLE_ID__</string>
|
||||
<key>CFBundleVersion</key>
|
||||
<string>__VERSION__</string>
|
||||
<key>CFBundleShortVersionString</key>
|
||||
<string>__VERSION__</string>
|
||||
<key>CFBundleExecutable</key>
|
||||
<string>Luminary</string>
|
||||
<key>CFBundleIconFile</key>
|
||||
<string>Luminary</string>
|
||||
<key>CFBundlePackageType</key>
|
||||
<string>APPL</string>
|
||||
<key>CFBundleInfoDictionaryVersion</key>
|
||||
<string>6.0</string>
|
||||
<key>CFBundleSignature</key>
|
||||
<string>????</string>
|
||||
<key>LSMinimumSystemVersion</key>
|
||||
<string>__MIN_OS__</string>
|
||||
<key>LSApplicationCategoryType</key>
|
||||
<string>public.app-category.photography</string>
|
||||
<key>NSHighResolutionCapable</key>
|
||||
<true/>
|
||||
<key>NSHumanReadableCopyright</key>
|
||||
<string>MIT licensed. Copyright 2026 Brian Hursey.</string>
|
||||
</dict>
|
||||
</plist>
|
||||
@@ -0,0 +1,63 @@
|
||||
Luminary for macOS
|
||||
==================
|
||||
|
||||
Install
|
||||
1. Open the disk image (or unzip the archive).
|
||||
2. Drag Luminary to the Applications folder.
|
||||
3. Eject the disk image, then open Luminary from Applications.
|
||||
|
||||
First launch (unsigned build)
|
||||
This build is not notarized by Apple, so macOS will say it cannot verify the
|
||||
app. That is expected: it means nobody paid Apple's yearly fee, not that
|
||||
anything is wrong with the file.
|
||||
1. Double-click Luminary and dismiss the warning with Done.
|
||||
2. Open System Settings > Privacy & Security.
|
||||
3. Scroll to Security and click Open Anyway, then authenticate.
|
||||
macOS remembers the choice, so this is a one-time step. The Open Anyway
|
||||
button only appears for about an hour after the blocked attempt; if it is
|
||||
missing, double-click the app again and go back.
|
||||
|
||||
What it needs
|
||||
- macOS 11 Big Sur or newer (the build records its own minimum in
|
||||
Info.plist; 11.0 for the Node 22 build, 13.5 for the Node 24 build).
|
||||
- A browser with WebAssembly and WebGL2. Chrome or Edge is used for the app
|
||||
window when installed; otherwise the default browser opens a normal tab.
|
||||
- Nothing else. Node.js is inside the app, so no Homebrew, no npm install
|
||||
and no administrator password are needed for day-to-day use.
|
||||
|
||||
Start, stop and status
|
||||
Opening Luminary starts the local server and opens the editor. Opening it
|
||||
again reuses the running copy instead of starting a second one.
|
||||
- Stop Luminary.command (next to the app in the disk image) stops the server.
|
||||
- The same commands are available from a terminal:
|
||||
/Applications/Luminary.app/Contents/Resources/launcher.sh --status
|
||||
/Applications/Luminary.app/Contents/Resources/launcher.sh --stop
|
||||
(or run the app with --args --status: open -a Luminary --args --status)
|
||||
|
||||
Where your photos live
|
||||
~/Library/Application Support/Luminary/data
|
||||
That folder holds the SQLite catalog, the originals, previews and thumbnails.
|
||||
Set LUMINARY_DATA before launching to keep it somewhere else, such as an
|
||||
external drive. Back it up by copying the whole folder while Luminary is
|
||||
stopped, including lumenroom.db, lumenroom.db-wal and lumenroom.db-shm.
|
||||
|
||||
Logs
|
||||
~/Library/Application Support/Luminary/data/logs/server.out.log
|
||||
~/Library/Application Support/Luminary/data/logs/server.err.log
|
||||
|
||||
Updating
|
||||
Quit the server (Stop Luminary.command), drag the new Luminary.app over the
|
||||
old one, and start it again. The data folder is outside the app and is not
|
||||
touched. The catalog migrates itself on first start.
|
||||
|
||||
Notes
|
||||
- The server listens on 127.0.0.1 only. For proofing galleries that other
|
||||
devices should reach, run the server yourself with HOST=0.0.0.0.
|
||||
- The app window is Chrome or Edge in app mode, using its own profile in the
|
||||
data folder, so it does not mix with your normal browsing. Set
|
||||
LUMINARY_WINDOW=browser to open a normal tab instead.
|
||||
- This build is single-user desktop mode: it signs in as a local admin
|
||||
without a password and is not meant for several people sharing one Mac
|
||||
account.
|
||||
- The bundle is ad-hoc signed. If you rebuild it yourself with a Developer ID
|
||||
certificate and notarize it, the first-launch step above disappears.
|
||||
@@ -0,0 +1,186 @@
|
||||
# macOS app (optional)
|
||||
|
||||
An additive, self-contained way to produce a double-clickable macOS app of
|
||||
Luminary. The server and Docker workflow stay the source of truth: this folder
|
||||
only *packages* the existing `dist/` + `server/` output, and the build writes
|
||||
its artifacts **outside the checkout**.
|
||||
|
||||
## Isolation guarantees
|
||||
|
||||
1. **The packaging tree is additive.** There is no `package.json` script for
|
||||
this, and no change to `Dockerfile`, `docker-compose.yml` or
|
||||
`scripts/deploy.mjs`. Invoke it directly: `node macos/build.mjs`. The app
|
||||
uses the same desktop mode the Windows launcher uses (`LUMINARY_LOCAL=1`),
|
||||
which is off unless a launcher sets it.
|
||||
2. **Artifacts live outside the repo** (default: `~/Library/Caches/luminary-macos`).
|
||||
The script refuses an `--out` inside the checkout, because
|
||||
`scripts/deploy.mjs` rsyncs the worktree to production and `docker build`
|
||||
would pull the bundle into its context.
|
||||
3. **The worktree must be clean outside `macos/`** before and after a build
|
||||
(the untracked `logo.png` is tolerated). `--allow-dirty` overrides it.
|
||||
4. **Nothing in the app changes at run time.** The bundle is the unchanged
|
||||
`server/` + `dist/` + production `node_modules`, started with `PORT`, `HOST`,
|
||||
`NODE_ENV` and `LUMINARY_DATA` — all variables the server already reads.
|
||||
|
||||
It must run on macOS: the build needs `clang`, `codesign`, `ditto`, `hdiutil`,
|
||||
`sips` and `iconutil`. The Windows bundle is the one that cross-builds from
|
||||
Linux.
|
||||
|
||||
## Quick start
|
||||
|
||||
On a fresh checkout run `npm ci` once: the UI build uses `vite` and `tsc` from
|
||||
the dev dependencies, and the script copies the production dependencies into
|
||||
the app itself.
|
||||
|
||||
```sh
|
||||
node macos/build.mjs # host arch, Node 24, ad-hoc signature, zip + dmg
|
||||
node macos/build.mjs --arch universal # arm64 + x86_64, both sharp slices
|
||||
node macos/build.mjs --node v22.23.5 # minimum macOS 11.0 instead of 13.5
|
||||
node macos/build.mjs --skip-build --sign none
|
||||
```
|
||||
|
||||
Outputs:
|
||||
|
||||
```
|
||||
~/Library/Caches/luminary-macos/
|
||||
stage/Luminary.app
|
||||
Luminary-0.5.2-mac-arm64.zip
|
||||
Luminary-0.5.2-mac-arm64.dmg
|
||||
cache/ # downloaded node tarballs, icon work
|
||||
```
|
||||
|
||||
`--publish` copies the zip and dmg into `macos/releases/` with a
|
||||
`SHA256SUMS.txt`, for transfer to a Mac. `.gitignore` keeps those archives out
|
||||
of git.
|
||||
|
||||
## Bundle layout
|
||||
|
||||
```
|
||||
Luminary.app/Contents/
|
||||
Info.plist, PkgInfo
|
||||
MacOS/Luminary native shim (main.c) -> execs the launcher
|
||||
Resources/
|
||||
launcher.sh start/stop/status/verify (bash)
|
||||
Luminary.icns
|
||||
version.txt, README-macos.txt
|
||||
runtime/node official Node for the built architecture
|
||||
app/
|
||||
server/ unchanged, minus data/ and *.test.*
|
||||
dist/ unchanged, including .br/.gz variants
|
||||
node_modules/ production deps only (sharp for each slice)
|
||||
package.json, LICENSE, THIRD_PARTY_NOTICES.md, licenses/
|
||||
```
|
||||
|
||||
The main executable is a **Mach-O shim**, not a shell script. Apple treats
|
||||
scripts in `Contents/MacOS` as resources, and the notary service rejects a
|
||||
bundle whose main executable is not signed native code; the shim is a few lines
|
||||
of C that execs `bash launcher.sh`, so the launcher stays editable without a
|
||||
rebuild and the bundle can still be signed and notarized.
|
||||
|
||||
## Node and the minimum macOS version
|
||||
|
||||
| Node | Bundled runtime minimum | `LSMinimumSystemVersion` |
|
||||
| --- | --- | --- |
|
||||
| v22.18+ | macOS 11.0 | 11.0 |
|
||||
| v24+ | macOS 13.5 | 13.5 |
|
||||
|
||||
Node 24's official macOS binaries are built against 13.5, so they cannot start
|
||||
on Big Sur or Monterey; a macOS 11 build must bundle Node 22. Both lines run
|
||||
this server: `node:sqlite` is unflagged from 22.13, type stripping (used by
|
||||
`server/denoise-worker.mjs` importing a `.ts` pipeline) from 22.18, and the
|
||||
HTTP integration suite passes under 22.23.5.
|
||||
|
||||
`--node-bin` uses a local binary instead of downloading one; the build warns if
|
||||
`otool -L` shows libraries outside `/usr/lib` and `/System` (a Homebrew node
|
||||
would drag Homebrew's ICU along and fail on a stock Mac).
|
||||
|
||||
## Signing and notarization
|
||||
|
||||
Three modes:
|
||||
|
||||
| `--sign` | What it does | Users see |
|
||||
| --- | --- | --- |
|
||||
| `adhoc` (default) | `codesign --sign -` on every Mach-O, then the bundle | “Apple could not verify …”, one-time Open Anyway |
|
||||
| `none` | no signature | the same, and arm64 Macs may refuse to launch it |
|
||||
| `developer-id` | signs each nested Mach-O with the Developer ID, hardened runtime and JIT entitlements on executables, then the bundle | no warning |
|
||||
|
||||
Notarization needs a paid Apple Developer Program membership:
|
||||
|
||||
```sh
|
||||
xcrun notarytool store-credentials luminary \
|
||||
--apple-id you@example.com --team-id TEAMID --password APP_SPECIFIC_PASSWORD
|
||||
|
||||
node macos/build.mjs --arch universal \
|
||||
--sign developer-id --identity "Developer ID Application: Brian Hursey (TEAMID)" \
|
||||
--notarize luminary --publish
|
||||
```
|
||||
|
||||
The build submits the zip, staples the `.app`, rebuilds the zip, then creates the
|
||||
dmg and submits and staples that too. `entitlements.plist` contains
|
||||
`allow-jit`, `allow-unsigned-executable-memory` and `disable-library-validation`
|
||||
— Node needs the first two under the hardened runtime, and sharp loads libvips
|
||||
as a dylib, which library validation would otherwise reject.
|
||||
|
||||
Without the certificate everything still works; the first-launch instructions in
|
||||
`README-macos.txt` cover the Gatekeeper step. macOS 15 and 26 removed the
|
||||
Control-click → Open bypass, so that text names the System Settings path.
|
||||
|
||||
## Launcher behaviour
|
||||
|
||||
Same rules as the Windows launcher (`windows/launcher/DESIGN.md`):
|
||||
|
||||
- **No mutex.** `runtime.json` in the data folder records pid/port, and
|
||||
`/api/health` is the liveness test: a healthy recorded port is reused, a stale
|
||||
one is replaced.
|
||||
- **Ports** 8787–8887, loopback only. The chosen port is passed as `PORT`.
|
||||
- **Data** defaults to `~/Library/Application Support/Luminary/data`; an
|
||||
existing `LUMINARY_DATA` wins. Logs go to `<data>/logs/`.
|
||||
- **Window**: Chrome or Edge in `--app` mode with its own profile in the data
|
||||
folder; `--browser` or `LUMINARY_WINDOW=browser` opens a normal tab; neither
|
||||
installed falls back to the default browser.
|
||||
- **Server lifetime**: detached, so closing the browser does not stop it and
|
||||
reopening the app reuses it. `--stop` (and `Stop Luminary.command` next to the
|
||||
app in the dmg) terminates it; `--status` prints pid, port, health and paths;
|
||||
`--verify` checks the three files a complete bundle needs.
|
||||
|
||||
## Test checklist (on the Tahoe machine)
|
||||
|
||||
1. `node macos/build.mjs --arch universal --dmg` → zip and dmg exist; summary
|
||||
prints arch, Node version, target and hashes.
|
||||
2. `codesign --verify --deep --strict --verbose=2 stage/Luminary.app` → valid.
|
||||
3. Copy the app out of the dmg, open it → browser/app window opens on the
|
||||
editor, no sign-in screen (desktop mode).
|
||||
4. Launch again while it runs → same port is reused, no second node process;
|
||||
`pgrep -fl 'Resources/runtime/node'` shows one.
|
||||
5. `--stop` → process gone, `runtime.json` removed; `--stop` again says
|
||||
"not running".
|
||||
6. Occupy 8787 with another listener → the app starts on 8788 and opens that
|
||||
URL.
|
||||
7. Import a raw, apply a film look, export → proves libraw WASM, sharp (dylibs
|
||||
load under the signature) and the export path.
|
||||
8. Denoise a photo → proves the `.ts` worker under the bundled Node.
|
||||
9. Quit the browser, reopen the app → the same catalog opens; the data folder
|
||||
holds the SQLite files.
|
||||
10. `--verify` with a renamed `runtime/node` → exit 3 and a dialog, not a silent
|
||||
failure.
|
||||
11. Path with spaces / non-ASCII in `LUMINARY_DATA` → starts and writes there.
|
||||
12. Gatekeeper: download the zip through a browser (quarantine flag), then
|
||||
follow README-macos.txt → one-time Open Anyway, then normal launches.
|
||||
13. On an Intel Mac: the same bundle runs (universal, both sharp slices).
|
||||
14. Optional: notarized build → double-click installs with no warning,
|
||||
`spctl -a -vv -t exec Luminary.app` says `accepted`.
|
||||
|
||||
## Known limits
|
||||
|
||||
- **No Dock menu.** The launcher exits once the browser opens; stopping is
|
||||
`--stop` / `Stop Luminary.command`, not a Quit menu item.
|
||||
- **Ad-hoc signing is per-bundle.** Copying the app with an archiver that drops
|
||||
extended attributes can make macOS call it damaged; the zip is made with
|
||||
`ditto` for that reason.
|
||||
- **Universal builds install sharp twice** (one `npm ci` per architecture) and
|
||||
copy the second slice's `@img` packages across; this is tested for layout, not
|
||||
for runtime, until both architectures are exercised.
|
||||
- **Icon quality depends on the source.** `public/logo.png` is 147×160, so the
|
||||
generated `.icns` is soft; pass `--icon` with a 1024×1024 PNG for a release.
|
||||
- **No auto-update, no file associations, no login item.** Same phase-2 list as
|
||||
Windows.
|
||||
@@ -0,0 +1,858 @@
|
||||
#!/usr/bin/env node
|
||||
/**
|
||||
* Build the optional self-contained macOS app for Luminary.
|
||||
*
|
||||
* Like windows/build.mjs this is deliberately additive: it only reads the
|
||||
* repository (`dist/`, `server/`, `package.json`) and writes everything into a
|
||||
* directory outside the checkout. Nothing in `src/`, `server/`, `package.json`,
|
||||
* the Dockerfile or the deploy script is modified, and no npm script is added.
|
||||
* Run it directly, on macOS:
|
||||
*
|
||||
* node macos/build.mjs # host arch, Node 24, ad-hoc signed
|
||||
* node macos/build.mjs --arch universal --dmg
|
||||
* node macos/build.mjs --node v22.23.5 # minimum macOS 11.0
|
||||
* node macos/build.mjs --skip-build --sign none
|
||||
*
|
||||
* The bundle keeps the layout the server expects (it derives `DIST_DIR` from
|
||||
* the parent of `server/`), with a native shim as the app's main executable:
|
||||
*
|
||||
* Luminary.app/Contents/
|
||||
* Info.plist, PkgInfo
|
||||
* MacOS/Luminary native shim that execs the launcher script
|
||||
* Resources/
|
||||
* launcher.sh start/stop/status/verify logic (bash)
|
||||
* Luminary.icns
|
||||
* version.txt, README-macos.txt
|
||||
* runtime/node official Node for this architecture
|
||||
* app/ unchanged server/, dist/, production deps
|
||||
*/
|
||||
import { createHash } from 'node:crypto';
|
||||
import { spawnSync } from 'node:child_process';
|
||||
import {
|
||||
chmodSync,
|
||||
cpSync,
|
||||
existsSync,
|
||||
mkdirSync,
|
||||
readFileSync,
|
||||
readdirSync,
|
||||
renameSync,
|
||||
rmSync,
|
||||
statSync,
|
||||
symlinkSync,
|
||||
writeFileSync,
|
||||
} from 'node:fs';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
|
||||
const HERE = path.dirname(fileURLToPath(import.meta.url));
|
||||
const ROOT = path.resolve(HERE, '..');
|
||||
const LAUNCHER_DIR = path.join(HERE, 'launcher');
|
||||
const RELEASES_DIR = path.join(HERE, 'releases');
|
||||
const DEFAULT_NODE = 'v24.22.2';
|
||||
const DEFAULT_BUNDLE_ID = 'net.maple-street.luminary';
|
||||
const INFO_PLIST = path.join(HERE, 'Info.plist');
|
||||
const ENTITLEMENTS = path.join(HERE, 'entitlements.plist');
|
||||
|
||||
const HELP = `Luminary macOS app
|
||||
|
||||
Usage: node macos/build.mjs [options]
|
||||
|
||||
--out <dir> output directory (default: ~/Library/Caches/luminary-macos).
|
||||
Must be outside this repository; the app is staged in
|
||||
<out>/stage/Luminary.app and archived next to it.
|
||||
--skip-build reuse the existing dist/ instead of running npm run build
|
||||
--node <version> bundled Node version (default ${DEFAULT_NODE}).
|
||||
v22.18+ gives a macOS 11.0 bundle; v24+ needs macOS 13.5.
|
||||
--node-bin <path> bundle this node binary instead of downloading one
|
||||
--arch <arch> host (default), arm64, x64 or universal
|
||||
--target <ver> minimum macOS version (default: derived from Node;
|
||||
e.g. 11.0 for Node 22, 13.5 for Node 24)
|
||||
--sign <kind> adhoc (default), developer-id or none
|
||||
--identity <name> Developer ID Application identity for --sign developer-id
|
||||
--notarize <name> notarytool keychain profile; implies --sign developer-id
|
||||
--dmg also write a disk image (default)
|
||||
--no-dmg skip the disk image
|
||||
--icon <png> icon source (default: macos/icon-1024.png)
|
||||
--bundle-id <id> CFBundleIdentifier (default ${DEFAULT_BUNDLE_ID})
|
||||
--allow-dirty skip the check that the checkout is clean outside macos/
|
||||
--publish copy the finished zip and dmg to macos/releases
|
||||
--help print this text
|
||||
|
||||
Requires macOS with the Xcode command line tools (clang, codesign, ditto,
|
||||
hdiutil, sips, iconutil). Nothing is written into the repository except with
|
||||
--publish.
|
||||
`;
|
||||
|
||||
function fail(message) {
|
||||
process.stderr.write(`macos: FAILED: ${message}\n`);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
function log(step, message) {
|
||||
process.stdout.write(`macos: ${step.padEnd(9)} ${message}\n`);
|
||||
}
|
||||
|
||||
function warn(message) {
|
||||
process.stderr.write(`macos: warning: ${message}\n`);
|
||||
}
|
||||
|
||||
function capture(command, args, cwd) {
|
||||
return spawnSync(command, args, { cwd, encoding: 'utf8' });
|
||||
}
|
||||
|
||||
function run(command, args, cwd, extraEnv) {
|
||||
log('run', [command, ...args].join(' '));
|
||||
const result = spawnSync(command, args, {
|
||||
cwd,
|
||||
stdio: 'inherit',
|
||||
env: extraEnv ? { ...process.env, ...extraEnv } : process.env,
|
||||
});
|
||||
if (result.error) fail(`${command} could not start: ${result.error.message}`);
|
||||
if (result.status !== 0) fail(`${command} ${args.join(' ')} exited with ${result.status}`);
|
||||
return result;
|
||||
}
|
||||
|
||||
function defaultOutDir() {
|
||||
return path.join(os.homedir(), 'Library', 'Caches', 'luminary-macos');
|
||||
}
|
||||
|
||||
function parseArgs(argv) {
|
||||
const options = {
|
||||
out: defaultOutDir(),
|
||||
node: DEFAULT_NODE,
|
||||
nodeBin: '',
|
||||
arch: 'host',
|
||||
target: '',
|
||||
sign: 'adhoc',
|
||||
identity: '',
|
||||
notarize: '',
|
||||
dmg: true,
|
||||
build: true,
|
||||
icon: path.join(HERE, 'icon-1024.png'),
|
||||
bundleId: DEFAULT_BUNDLE_ID,
|
||||
allowDirty: false,
|
||||
publish: false,
|
||||
help: false,
|
||||
};
|
||||
const value = (index, flag) => {
|
||||
const next = argv[index + 1];
|
||||
if (!next || next.startsWith('--')) fail(`${flag} needs a value`);
|
||||
return next;
|
||||
};
|
||||
for (let i = 0; i < argv.length; i++) {
|
||||
const arg = argv[i];
|
||||
if (arg === '--out') {
|
||||
options.out = path.resolve(value(i, arg));
|
||||
i += 1;
|
||||
} else if (arg === '--node') {
|
||||
const version = value(i, arg);
|
||||
options.node = version.startsWith('v') ? version : `v${version}`;
|
||||
i += 1;
|
||||
} else if (arg === '--node-bin') {
|
||||
options.nodeBin = path.resolve(value(i, arg));
|
||||
i += 1;
|
||||
} else if (arg === '--arch') {
|
||||
options.arch = value(i, arg);
|
||||
i += 1;
|
||||
} else if (arg === '--target') {
|
||||
options.target = value(i, arg);
|
||||
i += 1;
|
||||
} else if (arg === '--sign') {
|
||||
options.sign = value(i, arg);
|
||||
i += 1;
|
||||
} else if (arg === '--identity') {
|
||||
options.identity = value(i, arg);
|
||||
i += 1;
|
||||
} else if (arg === '--notarize') {
|
||||
options.notarize = value(i, arg);
|
||||
i += 1;
|
||||
} else if (arg === '--icon') {
|
||||
options.icon = path.resolve(value(i, arg));
|
||||
i += 1;
|
||||
} else if (arg === '--bundle-id') {
|
||||
options.bundleId = value(i, arg);
|
||||
i += 1;
|
||||
} else if (arg === '--skip-build') {
|
||||
options.build = false;
|
||||
} else if (arg === '--dmg') {
|
||||
options.dmg = true;
|
||||
} else if (arg === '--no-dmg') {
|
||||
options.dmg = false;
|
||||
} else if (arg === '--allow-dirty') {
|
||||
options.allowDirty = true;
|
||||
} else if (arg === '--publish') {
|
||||
options.publish = true;
|
||||
} else if (arg === '--help' || arg === '-h') {
|
||||
options.help = true;
|
||||
} else {
|
||||
fail(`unknown option ${arg} (see --help)`);
|
||||
}
|
||||
}
|
||||
if (!['host', 'arm64', 'x64', 'universal'].includes(options.arch)) {
|
||||
fail(`--arch must be host, arm64, x64 or universal (got ${options.arch})`);
|
||||
}
|
||||
if (!['adhoc', 'developer-id', 'none'].includes(options.sign)) {
|
||||
fail(`--sign must be adhoc, developer-id or none (got ${options.sign})`);
|
||||
}
|
||||
if (!/^v\d+\.\d+\.\d+$/.test(options.node)) {
|
||||
fail(`--node must look like v24.22.2 (got ${options.node})`);
|
||||
}
|
||||
if (options.notarize) options.sign = 'developer-id';
|
||||
if (options.sign === 'developer-id' && !options.identity) {
|
||||
fail('--sign developer-id needs --identity "Developer ID Application: ..."');
|
||||
}
|
||||
if (options.nodeBin && !existsSync(options.nodeBin)) {
|
||||
fail(`--node-bin not found: ${options.nodeBin}`);
|
||||
}
|
||||
return options;
|
||||
}
|
||||
|
||||
/**
|
||||
* The staged app and its runtime must not land in the checkout: scripts/deploy
|
||||
* rsyncs the worktree to production and docker build would pull it into the
|
||||
* context.
|
||||
*/
|
||||
function assertOutsideRepo(outDir) {
|
||||
const relative = path.relative(ROOT, outDir);
|
||||
const inside = !relative.startsWith('..') && !path.isAbsolute(relative);
|
||||
if (inside) {
|
||||
fail(
|
||||
`--out resolves inside the repository (${outDir}).\n` +
|
||||
'Pick a directory outside the checkout, or omit --out to use the cache.',
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
function git(args, { trim = true } = {}) {
|
||||
const result = capture('git', args, ROOT);
|
||||
if (result.error || result.status !== 0) return null;
|
||||
return trim ? result.stdout.trim() : result.stdout;
|
||||
}
|
||||
|
||||
/** Only this folder and the long-standing untracked logo may be dirty. */
|
||||
function checkRepoClean(options) {
|
||||
const status = git(['status', '--porcelain'], { trim: false });
|
||||
if (status === null) {
|
||||
warn('git is unavailable here; skipping the worktree check');
|
||||
return;
|
||||
}
|
||||
const unexpected = status
|
||||
.split('\n')
|
||||
.filter((line) => line.length > 3)
|
||||
.map((line) => line.slice(3).replace(/^"|"$/g, '').replace(/^.* -> /, '').trim())
|
||||
.filter((file) => file && !file.startsWith('macos/') && file !== 'logo.png');
|
||||
if (!unexpected.length) return;
|
||||
if (options.allowDirty) {
|
||||
warn(`building from a modified checkout: ${unexpected.join(', ')}`);
|
||||
return;
|
||||
}
|
||||
fail(
|
||||
`the checkout has changes outside macos/:\n ${unexpected.join('\n ')}\n` +
|
||||
'Commit or stash them, or pass --allow-dirty to build anyway.',
|
||||
);
|
||||
}
|
||||
|
||||
function readPackage() {
|
||||
const file = path.join(ROOT, 'package.json');
|
||||
if (!existsSync(file)) fail('run this from a Luminary checkout (package.json missing)');
|
||||
return JSON.parse(readFileSync(file, 'utf8'));
|
||||
}
|
||||
|
||||
function sha256File(file) {
|
||||
return createHash('sha256').update(readFileSync(file)).digest('hex');
|
||||
}
|
||||
|
||||
async function download(url) {
|
||||
const response = await fetch(url);
|
||||
if (!response.ok) throw new Error(`${response.status} ${response.statusText} from ${url}`);
|
||||
return Buffer.from(await response.arrayBuffer());
|
||||
}
|
||||
|
||||
function fileType(file) {
|
||||
const result = capture('file', ['-b', file]);
|
||||
return result.status === 0 ? result.stdout.trim() : '';
|
||||
}
|
||||
|
||||
function nodeMajor(version) {
|
||||
return Number(version.slice(1).split('.')[0]);
|
||||
}
|
||||
|
||||
function minimumOS(version) {
|
||||
const major = nodeMajor(version);
|
||||
if (major === 22) return '11.0';
|
||||
if (major >= 24) return '13.5';
|
||||
return '11.0';
|
||||
}
|
||||
|
||||
function resolveArchs(requested) {
|
||||
if (requested === 'universal') return ['arm64', 'x64'];
|
||||
if (requested === 'host') return [process.arch === 'arm64' ? 'arm64' : 'x64'];
|
||||
return [requested];
|
||||
}
|
||||
|
||||
function clangArch(arch) {
|
||||
return arch === 'x64' ? 'x86_64' : 'arm64';
|
||||
}
|
||||
|
||||
function ensureUi(options) {
|
||||
const dist = path.join(ROOT, 'dist', 'index.html');
|
||||
if (options.build) {
|
||||
log('ui', 'npm run build (typecheck + vite build + compressed variants)');
|
||||
run('npm', ['run', 'build'], ROOT);
|
||||
} else {
|
||||
log('ui', 'reusing the existing dist/ (--skip-build)');
|
||||
}
|
||||
if (!existsSync(dist)) fail('dist/index.html is missing; drop --skip-build or run "npm run build"');
|
||||
}
|
||||
|
||||
function copyServer(appDir) {
|
||||
cpSync(path.join(ROOT, 'server'), path.join(appDir, 'server'), {
|
||||
recursive: true,
|
||||
filter: (source) => {
|
||||
const relative = path.relative(path.join(ROOT, 'server'), source).split(path.sep).join('/');
|
||||
if (relative === 'data' || relative.startsWith('data/')) return false;
|
||||
if (/\.test\.(mjs|ts)$/.test(relative)) return false;
|
||||
return true;
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
function copyLegal(appDir) {
|
||||
for (const name of ['LICENSE', 'THIRD_PARTY_NOTICES.md']) {
|
||||
const source = path.join(ROOT, name);
|
||||
if (existsSync(source)) cpSync(source, path.join(appDir, name));
|
||||
}
|
||||
const licenses = path.join(ROOT, 'licenses');
|
||||
if (existsSync(licenses)) cpSync(licenses, path.join(appDir, 'licenses'), { recursive: true });
|
||||
}
|
||||
|
||||
function installDeps(appDir, archs, outDir) {
|
||||
cpSync(path.join(ROOT, 'package.json'), path.join(appDir, 'package.json'));
|
||||
cpSync(path.join(ROOT, 'package-lock.json'), path.join(appDir, 'package-lock.json'));
|
||||
|
||||
log('deps', `npm ci --omit=dev --os=darwin --cpu=${archs[0]} (sharp darwin-${archs[0]})`);
|
||||
// sharp resolves its prebuilt binary through optionalDependencies, so npm can
|
||||
// fetch the target architecture's package from any host. The ONNX skip keeps
|
||||
// the postinstall from downloading the CUDA build; CPU binaries ship in the
|
||||
// package.
|
||||
run(
|
||||
'npm',
|
||||
['ci', '--omit=dev', '--os=darwin', `--cpu=${archs[0]}`, '--ignore-scripts', '--no-audit', '--no-fund'],
|
||||
appDir,
|
||||
{ ONNXRUNTIME_NODE_INSTALL: 'skip' },
|
||||
);
|
||||
rmSync(path.join(appDir, 'node_modules', '.bin'), { recursive: true, force: true });
|
||||
|
||||
// A universal app needs both sharp slices; npm's --cpu selects one at a time,
|
||||
// so install the second architecture separately and copy its packages across.
|
||||
for (const arch of archs.slice(1)) {
|
||||
const side = path.join(outDir, `deps-${arch}`);
|
||||
rmSync(side, { recursive: true, force: true });
|
||||
mkdirSync(side, { recursive: true });
|
||||
cpSync(path.join(ROOT, 'package.json'), path.join(side, 'package.json'));
|
||||
cpSync(path.join(ROOT, 'package-lock.json'), path.join(side, 'package-lock.json'));
|
||||
run(
|
||||
'npm',
|
||||
['ci', '--omit=dev', '--os=darwin', `--cpu=${arch}`, '--ignore-scripts', '--no-audit', '--no-fund'],
|
||||
side,
|
||||
{ ONNXRUNTIME_NODE_INSTALL: 'skip' },
|
||||
);
|
||||
for (const pkg of [`@img/sharp-darwin-${arch}`, `@img/sharp-libvips-darwin-${arch}`]) {
|
||||
const from = path.join(side, 'node_modules', pkg);
|
||||
if (!existsSync(from)) fail(`${pkg} was not installed for the ${arch} slice`);
|
||||
rmSync(path.join(appDir, 'node_modules', pkg), { recursive: true, force: true });
|
||||
cpSync(from, path.join(appDir, 'node_modules', pkg), { recursive: true });
|
||||
log('deps', `added ${pkg}`);
|
||||
}
|
||||
rmSync(side, { recursive: true, force: true });
|
||||
}
|
||||
|
||||
verifySharp(appDir, archs);
|
||||
}
|
||||
|
||||
function verifySharp(appDir, archs) {
|
||||
for (const arch of archs) {
|
||||
const dir = path.join(appDir, 'node_modules', '@img', `sharp-darwin-${arch}`);
|
||||
if (!existsSync(dir)) {
|
||||
warn(`@img/sharp-darwin-${arch} is missing; the server will fall back to JPEG proxies`);
|
||||
continue;
|
||||
}
|
||||
const binaries = [];
|
||||
const walk = (current) => {
|
||||
for (const entry of readdirSync(current, { withFileTypes: true })) {
|
||||
const absolute = path.join(current, entry.name);
|
||||
if (entry.isDirectory()) walk(absolute);
|
||||
else if (/\.(node|dylib)$/i.test(entry.name)) binaries.push(path.relative(dir, absolute));
|
||||
}
|
||||
};
|
||||
walk(dir);
|
||||
const libvips = path.join(appDir, 'node_modules', '@img', `sharp-libvips-darwin-${arch}`);
|
||||
log(
|
||||
'deps',
|
||||
binaries.some((file) => file.endsWith('.node'))
|
||||
? `sharp darwin-${arch} ready (${binaries.length} native file(s)${existsSync(libvips) ? ', libvips included' : ''})`
|
||||
: `sharp darwin-${arch} has no .node binary`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
async function ensureNode(options, outDir, archs) {
|
||||
if (options.nodeBin) {
|
||||
const kind = fileType(options.nodeBin);
|
||||
if (!/Mach-O/.test(kind)) fail(`--node-bin is not a Mach-O binary (${kind || 'unknown'})`);
|
||||
const binaryArch = /universal/.test(kind) ? 'universal' : /arm64/.test(kind) ? 'arm64' : 'x64';
|
||||
if (binaryArch !== 'universal' && (archs.length > 1 || binaryArch !== archs[0])) {
|
||||
fail(
|
||||
`--node-bin is ${binaryArch} but --arch needs ${archs.join(' + ')}.\n` +
|
||||
'Use the official nodejs.org tarball, or omit --node-bin to download both slices.',
|
||||
);
|
||||
}
|
||||
log('node', `using ${options.nodeBin} (${binaryArch})`);
|
||||
return { path: options.nodeBin, arch: binaryArch, version: options.node, hash: sha256File(options.nodeBin) };
|
||||
}
|
||||
|
||||
const version = options.node;
|
||||
const major = nodeMajor(version);
|
||||
if (major === 23) fail('Node 23 is not an LTS line; use v22 (macOS 11) or v24 (macOS 13.5)');
|
||||
if (major < 22) fail(`Node ${version} is too old: node:sqlite needs 22.13+ (type stripping 22.18+)`);
|
||||
if (major === 22 && Number(version.split('.')[1]) < 18) {
|
||||
fail(`${version} cannot strip types by default; server/denoise-worker.mjs needs v22.18+`);
|
||||
}
|
||||
|
||||
const cache = path.join(outDir, 'cache', `node-${version}`);
|
||||
mkdirSync(cache, { recursive: true });
|
||||
const sumsFile = path.join(cache, 'SHASUMS256.txt');
|
||||
if (!existsSync(sumsFile)) {
|
||||
log('node', `downloading SHASUMS256.txt for ${version}`);
|
||||
writeFileSync(sumsFile, await download(`https://nodejs.org/dist/${version}/SHASUMS256.txt`));
|
||||
}
|
||||
const sums = new Map(
|
||||
readFileSync(sumsFile, 'utf8')
|
||||
.split('\n')
|
||||
.filter(Boolean)
|
||||
.map((line) => {
|
||||
const [hash, name] = line.trim().split(/\s+/);
|
||||
return [name, hash];
|
||||
}),
|
||||
);
|
||||
|
||||
const binaries = [];
|
||||
for (const arch of archs) {
|
||||
const name = `node-${version}-darwin-${arch}.tar.gz`;
|
||||
const tarball = path.join(cache, name);
|
||||
if (!existsSync(tarball)) {
|
||||
log('node', `downloading ${name}`);
|
||||
try {
|
||||
writeFileSync(tarball, await download(`https://nodejs.org/dist/${version}/${name}`));
|
||||
} catch (error) {
|
||||
fail(`could not download ${name}: ${error.message}`);
|
||||
}
|
||||
}
|
||||
const hash = sha256File(tarball);
|
||||
const expected = sums.get(name);
|
||||
if (expected && expected !== hash) {
|
||||
rmSync(tarball, { force: true });
|
||||
fail(`${name} failed its SHA-256 check (${hash} != ${expected}); re-run to download again`);
|
||||
}
|
||||
if (!expected) warn(`${name} has no published checksum; using it unverified`);
|
||||
|
||||
const dir = path.join(cache, `node-${version}-darwin-${arch}`);
|
||||
const binary = path.join(dir, 'bin', 'node');
|
||||
if (!existsSync(binary)) {
|
||||
mkdirSync(dir, { recursive: true });
|
||||
run('tar', ['-xzf', tarball, '-C', dir, '--strip-components=1']);
|
||||
}
|
||||
const kind = fileType(binary);
|
||||
if (!/Mach-O/.test(kind)) fail(`extracted ${arch} node is not a Mach-O binary (${kind})`);
|
||||
binaries.push(binary);
|
||||
log('node', `${version} darwin-${arch} verified (sha256 ${hash.slice(0, 12)}…)`);
|
||||
}
|
||||
|
||||
if (binaries.length === 1) {
|
||||
return { path: binaries[0], arch: archs[0], version, hash: sha256File(binaries[0]) };
|
||||
}
|
||||
const universal = path.join(cache, `node-${version}-universal`);
|
||||
rmSync(universal, { force: true });
|
||||
run('lipo', ['-create', ...binaries, '-output', universal]);
|
||||
const kind = fileType(universal);
|
||||
if (!/universal binary/.test(kind)) fail(`lipo did not produce a universal binary (${kind})`);
|
||||
chmodSync(universal, 0o755);
|
||||
log('node', `${version} universal (arm64 + x86_64)`);
|
||||
return { path: universal, arch: 'universal', version, hash: sha256File(universal) };
|
||||
}
|
||||
|
||||
function checkNodePortability(binary) {
|
||||
const result = capture('otool', ['-L', binary]);
|
||||
if (result.status !== 0) return;
|
||||
const foreign = result.stdout
|
||||
.split('\n')
|
||||
.slice(1)
|
||||
.map((line) => line.trim().split(' ')[0])
|
||||
.filter((lib) => lib && !lib.startsWith('/usr/lib/') && !lib.startsWith('/System/'));
|
||||
if (foreign.length) {
|
||||
warn(
|
||||
`the bundled node links to libraries outside macOS: ${foreign.join(', ')}.\n` +
|
||||
'Use the official nodejs.org tarball so the app runs on a Mac without Homebrew.',
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
function compileShim(app, archs, target) {
|
||||
const found = capture('xcrun', ['--find', 'clang']);
|
||||
const clang = found.status === 0 ? found.stdout.trim() : '';
|
||||
if (!clang) {
|
||||
fail(
|
||||
'clang is missing. Install the Xcode command line tools:\n' +
|
||||
' xcode-select --install\n' +
|
||||
'and run the build again.',
|
||||
);
|
||||
}
|
||||
const output = path.join(app, 'Contents', 'MacOS', 'Luminary');
|
||||
const args = ['-O2', '-Wall', '-Wextra', `-mmacosx-version-min=${target}`];
|
||||
for (const arch of archs) args.push('-arch', clangArch(arch));
|
||||
args.push('-o', output, path.join(LAUNCHER_DIR, 'main.c'));
|
||||
run(clang, args);
|
||||
chmodSync(output, 0o755);
|
||||
log('launcher', `native shim (${archs.join(' + ')}, macOS ${target}+)`);
|
||||
}
|
||||
|
||||
function renderInfoPlist(app, { version, target, bundleId }) {
|
||||
const text = readFileSync(INFO_PLIST, 'utf8')
|
||||
.replaceAll('__VERSION__', version)
|
||||
.replaceAll('__MIN_OS__', target)
|
||||
.replaceAll('__BUNDLE_ID__', bundleId);
|
||||
writeFileSync(path.join(app, 'Contents', 'Info.plist'), text);
|
||||
writeFileSync(path.join(app, 'Contents', 'PkgInfo'), 'APPL????');
|
||||
}
|
||||
|
||||
function buildIcon(app, source, outDir) {
|
||||
if (!existsSync(source)) {
|
||||
warn(`icon source not found: ${source}; the app will use the generic icon`);
|
||||
return;
|
||||
}
|
||||
const sips = '/usr/bin/sips';
|
||||
const iconutil = '/usr/bin/iconutil';
|
||||
if (!existsSync(sips) || !existsSync(iconutil)) {
|
||||
warn('sips/iconutil are missing; skipping the icon');
|
||||
return;
|
||||
}
|
||||
const probe = capture(sips, ['-g', 'pixelWidth', '-g', 'pixelHeight', source]);
|
||||
const width = Number((probe.stdout.match(/pixelWidth:\s*(\d+)/) ?? [])[1] ?? 0);
|
||||
const height = Number((probe.stdout.match(/pixelHeight:\s*(\d+)/) ?? [])[1] ?? 0);
|
||||
if (!width || !height) {
|
||||
warn(`could not read the icon size of ${source}; skipping the icon`);
|
||||
return;
|
||||
}
|
||||
const square = Math.max(width, height);
|
||||
if (square < 512) {
|
||||
warn(
|
||||
`the icon source is ${width}x${height}; the .icns will look soft.\n` +
|
||||
'Pass --icon with a 1024x1024 PNG for a crisp Dock icon.',
|
||||
);
|
||||
}
|
||||
|
||||
const work = path.join(outDir, 'cache', 'icon');
|
||||
rmSync(work, { recursive: true, force: true });
|
||||
mkdirSync(path.join(work, 'Luminary.iconset'), { recursive: true });
|
||||
const padded = path.join(work, 'square.png');
|
||||
if (width === height) {
|
||||
cpSync(source, padded);
|
||||
} else {
|
||||
run(sips, ['-p', String(square), String(square), '--padColor', '0B0D10', source, '--out', padded]);
|
||||
}
|
||||
|
||||
const iconset = path.join(work, 'Luminary.iconset');
|
||||
for (const size of [16, 32, 128, 256, 512]) {
|
||||
for (const scale of [1, 2]) {
|
||||
const pixels = size * scale;
|
||||
const name = scale === 1 ? `icon_${size}x${size}.png` : `icon_${size}x${size}@2x.png`;
|
||||
run(sips, ['-z', String(pixels), String(pixels), padded, '--out', path.join(iconset, name)]);
|
||||
}
|
||||
}
|
||||
run(iconutil, ['-c', 'icns', iconset, '-o', path.join(app, 'Contents', 'Resources', 'Luminary.icns')]);
|
||||
log('icon', `Luminary.icns from ${path.relative(ROOT, source)} (${width}x${height})`);
|
||||
}
|
||||
|
||||
function writeVersion(resources, info) {
|
||||
const commit = git(['rev-parse', '--short', 'HEAD']) ?? 'unknown';
|
||||
const lines = [
|
||||
`Luminary ${info.version}`,
|
||||
`commit ${commit}`,
|
||||
`built ${new Date().toISOString()}`,
|
||||
`node ${info.nodeVersion} darwin-${info.nodeArch} sha256 ${info.nodeHash} size ${info.nodeSize}`,
|
||||
`arch ${info.archs.join(' + ')}`,
|
||||
`minimum macOS ${info.target}`,
|
||||
'launcher native shim -> launcher.sh',
|
||||
];
|
||||
writeFileSync(path.join(resources, 'version.txt'), `${lines.join('\n')}\n`);
|
||||
return commit;
|
||||
}
|
||||
|
||||
function machOFiles(root) {
|
||||
const found = [];
|
||||
const walk = (current) => {
|
||||
for (const entry of readdirSync(current, { withFileTypes: true })) {
|
||||
const absolute = path.join(current, entry.name);
|
||||
if (entry.isDirectory()) {
|
||||
walk(absolute);
|
||||
continue;
|
||||
}
|
||||
if (!entry.isFile()) continue;
|
||||
// `file` per file would be hundreds of subprocesses across node_modules;
|
||||
// only native modules, dylibs and executables can be Mach-O here.
|
||||
const stat = statSync(absolute);
|
||||
const candidate =
|
||||
/\.(node|dylib|so)$/i.test(entry.name) || (stat.mode & 0o111) !== 0;
|
||||
if (candidate && /Mach-O/.test(fileType(absolute))) found.push(absolute);
|
||||
}
|
||||
};
|
||||
walk(root);
|
||||
return found;
|
||||
}
|
||||
|
||||
function signApp(app, options) {
|
||||
if (options.sign === 'none') {
|
||||
warn(
|
||||
'the app is unsigned: arm64 Macs refuse to launch it at all, and Intel\n' +
|
||||
'Macs show the Gatekeeper warning. Ship adhoc or developer-id instead.',
|
||||
);
|
||||
return;
|
||||
}
|
||||
const nested = machOFiles(app).filter((file) => !file.endsWith('/Contents/MacOS/Luminary'));
|
||||
for (const file of nested) {
|
||||
if (options.sign === 'adhoc') {
|
||||
run('codesign', ['--force', '--sign', '-', file]);
|
||||
continue;
|
||||
}
|
||||
const kind = fileType(file);
|
||||
const executable = /executable/.test(kind) && !/dylib|bundle/.test(kind);
|
||||
const args = ['--force', '--timestamp', '--sign', options.identity];
|
||||
if (executable) args.push('--options', 'runtime', '--entitlements', ENTITLEMENTS);
|
||||
args.push(file);
|
||||
run('codesign', args);
|
||||
}
|
||||
const finalArgs =
|
||||
options.sign === 'adhoc'
|
||||
? ['--force', '--sign', '-', app]
|
||||
: [
|
||||
'--force',
|
||||
'--timestamp',
|
||||
'--options',
|
||||
'runtime',
|
||||
'--entitlements',
|
||||
ENTITLEMENTS,
|
||||
'--sign',
|
||||
options.identity,
|
||||
app,
|
||||
];
|
||||
run('codesign', finalArgs);
|
||||
const verify = capture('codesign', ['--verify', '--deep', '--strict', '--verbose=2', app]);
|
||||
if (verify.status !== 0) fail(`codesign verification failed:\n${verify.stderr.trim()}`);
|
||||
log('sign', options.sign === 'adhoc' ? 'ad-hoc signature verified' : `signed with ${options.identity}`);
|
||||
}
|
||||
|
||||
function zipApp(app, zipPath) {
|
||||
rmSync(zipPath, { force: true });
|
||||
// ditto keeps symlinks, extended attributes and the code signature intact;
|
||||
// `zip -r` corrupts bundles often enough to produce "app is damaged".
|
||||
run('ditto', ['-c', '-k', '--keepParent', '--sequesterRsrc', app, zipPath]);
|
||||
return statSync(zipPath).size;
|
||||
}
|
||||
|
||||
function makeDmg(app, dmgPath, outDir) {
|
||||
const root = path.join(outDir, 'dmg');
|
||||
rmSync(root, { recursive: true, force: true });
|
||||
mkdirSync(root, { recursive: true });
|
||||
cpSync(app, path.join(root, 'Luminary.app'), { recursive: true, verbatimSymlinks: true });
|
||||
symlinkSync('Applications', path.join(root, 'Applications'));
|
||||
cpSync(path.join(HERE, 'README-macos.txt'), path.join(root, 'README-macos.txt'));
|
||||
const stop = path.join(LAUNCHER_DIR, 'Stop Luminary.command');
|
||||
if (existsSync(stop)) {
|
||||
cpSync(stop, path.join(root, 'Stop Luminary.command'));
|
||||
chmodSync(path.join(root, 'Stop Luminary.command'), 0o755);
|
||||
}
|
||||
rmSync(dmgPath, { force: true });
|
||||
run('hdiutil', [
|
||||
'create',
|
||||
'-volname',
|
||||
'Luminary',
|
||||
'-srcfolder',
|
||||
root,
|
||||
'-ov',
|
||||
'-format',
|
||||
'UDZO',
|
||||
dmgPath,
|
||||
]);
|
||||
rmSync(root, { recursive: true, force: true });
|
||||
return statSync(dmgPath).size;
|
||||
}
|
||||
|
||||
function notarize(artifact, profile) {
|
||||
log('notarize', `submitting ${path.basename(artifact)}`);
|
||||
run('xcrun', ['notarytool', 'submit', artifact, '--keychain-profile', profile, '--wait']);
|
||||
}
|
||||
|
||||
function staple(artifact) {
|
||||
run('xcrun', ['stapler', 'staple', artifact]);
|
||||
run('xcrun', ['stapler', 'validate', artifact]);
|
||||
}
|
||||
|
||||
async function main() {
|
||||
const options = parseArgs(process.argv.slice(2));
|
||||
if (options.help) {
|
||||
process.stdout.write(HELP);
|
||||
return 0;
|
||||
}
|
||||
if (process.platform !== 'darwin') {
|
||||
fail(
|
||||
'the macOS app must be built on macOS: it needs clang, codesign, ditto and hdiutil.\n' +
|
||||
'The Windows bundle is the one that cross-builds from Linux.',
|
||||
);
|
||||
}
|
||||
assertOutsideRepo(options.out);
|
||||
const pkg = readPackage();
|
||||
const archs = resolveArchs(options.arch);
|
||||
const target = options.target || minimumOS(options.node);
|
||||
const [targetMajor, targetMinor = 0] = target.split('.').map(Number);
|
||||
if (nodeMajor(options.node) >= 24 && (targetMajor < 13 || (targetMajor === 13 && targetMinor < 5))) {
|
||||
fail(
|
||||
`Node ${options.node} needs macOS 13.5 or newer, but --target is ${target}.\n` +
|
||||
'Build with --node v22.23.5 for a macOS 11.0 bundle.',
|
||||
);
|
||||
}
|
||||
log('repo', `${pkg.name} ${pkg.version} at ${ROOT}`);
|
||||
log('out', options.out);
|
||||
checkRepoClean(options);
|
||||
ensureUi(options);
|
||||
|
||||
const stageRoot = path.join(options.out, 'stage');
|
||||
const workRoot = path.join(options.out, 'stage.next');
|
||||
const app = path.join(workRoot, 'Luminary.app');
|
||||
const contents = path.join(app, 'Contents');
|
||||
const resources = path.join(contents, 'Resources');
|
||||
const appDir = path.join(resources, 'app');
|
||||
rmSync(workRoot, { recursive: true, force: true });
|
||||
for (const dir of [path.join(contents, 'MacOS'), resources, appDir, path.join(resources, 'runtime')]) {
|
||||
mkdirSync(dir, { recursive: true });
|
||||
}
|
||||
|
||||
log('stage', 'copying dist/ and server/ (the layout the server expects)');
|
||||
cpSync(path.join(ROOT, 'dist'), path.join(appDir, 'dist'), { recursive: true });
|
||||
copyServer(appDir);
|
||||
copyLegal(appDir);
|
||||
installDeps(appDir, archs, options.out);
|
||||
|
||||
const node = await ensureNode(options, options.out, archs);
|
||||
checkNodePortability(node.path);
|
||||
cpSync(node.path, path.join(resources, 'runtime', 'node'));
|
||||
chmodSync(path.join(resources, 'runtime', 'node'), 0o755);
|
||||
log('node', `bundled ${path.basename(node.path)} (${(statSync(node.path).size / 1024 / 1024).toFixed(1)} MB)`);
|
||||
|
||||
cpSync(path.join(LAUNCHER_DIR, 'launcher.sh'), path.join(resources, 'launcher.sh'));
|
||||
chmodSync(path.join(resources, 'launcher.sh'), 0o755);
|
||||
cpSync(path.join(HERE, 'README-macos.txt'), path.join(resources, 'README-macos.txt'));
|
||||
|
||||
renderInfoPlist(app, { version: pkg.version, target, bundleId: options.bundleId });
|
||||
compileShim(app, archs, target);
|
||||
buildIcon(app, options.icon, options.out);
|
||||
|
||||
const commit = writeVersion(resources, {
|
||||
version: pkg.version,
|
||||
nodeVersion: options.node,
|
||||
nodeArch: node.arch,
|
||||
nodeHash: node.hash,
|
||||
nodeSize: statSync(node.path).size,
|
||||
archs,
|
||||
target,
|
||||
});
|
||||
|
||||
signApp(app, options);
|
||||
|
||||
const label = archs.length > 1 ? 'universal' : archs[0];
|
||||
const zipPath = path.join(options.out, `Luminary-${pkg.version}-mac-${label}.zip`);
|
||||
let zipBytes = zipApp(app, zipPath);
|
||||
|
||||
if (options.notarize) {
|
||||
notarize(zipPath, options.notarize);
|
||||
staple(app);
|
||||
zipBytes = zipApp(app, zipPath);
|
||||
} else {
|
||||
const assessment = capture('spctl', ['-a', '-vv', '-t', 'exec', app]);
|
||||
if (assessment.status !== 0) {
|
||||
log('gatekeeper', 'not notarized: users must use Privacy & Security > Open Anyway');
|
||||
}
|
||||
}
|
||||
|
||||
let dmgPath = '';
|
||||
let dmgBytes = 0;
|
||||
if (options.dmg) {
|
||||
dmgPath = path.join(options.out, `Luminary-${pkg.version}-mac-${label}.dmg`);
|
||||
dmgBytes = makeDmg(app, dmgPath, options.out);
|
||||
if (options.notarize) {
|
||||
notarize(dmgPath, options.notarize);
|
||||
staple(dmgPath);
|
||||
}
|
||||
log('dmg', `${path.basename(dmgPath)} (${(dmgBytes / 1024 / 1024).toFixed(1)} MB)`);
|
||||
}
|
||||
|
||||
// The isolation contract: nothing outside macos/ may have changed. Checked
|
||||
// before --publish writes anything into the checkout.
|
||||
if (!options.allowDirty) checkRepoClean(options);
|
||||
|
||||
rmSync(stageRoot, { recursive: true, force: true });
|
||||
renameSync(workRoot, stageRoot);
|
||||
|
||||
let published = [];
|
||||
if (options.publish) {
|
||||
mkdirSync(RELEASES_DIR, { recursive: true });
|
||||
const sums = [];
|
||||
for (const artifact of [zipPath, ...(dmgPath ? [dmgPath] : [])]) {
|
||||
const targetPath = path.join(RELEASES_DIR, path.basename(artifact));
|
||||
cpSync(artifact, targetPath);
|
||||
sums.push(`${sha256File(targetPath)} ${path.basename(targetPath)}`);
|
||||
log('publish', path.relative(ROOT, targetPath));
|
||||
}
|
||||
writeFileSync(path.join(RELEASES_DIR, 'SHA256SUMS.txt'), `${sums.join('\n')}\n`);
|
||||
published = sums;
|
||||
}
|
||||
|
||||
process.stdout.write(
|
||||
[
|
||||
'',
|
||||
'macos build PASSED',
|
||||
` app ${path.join(stageRoot, 'Luminary.app')}`,
|
||||
` zip ${zipPath}`,
|
||||
` zip size ${(zipBytes / 1024 / 1024).toFixed(1)} MB`,
|
||||
` zip sha256 ${sha256File(zipPath)}`,
|
||||
...(dmgPath
|
||||
? [
|
||||
` dmg ${dmgPath}`,
|
||||
` dmg size ${(dmgBytes / 1024 / 1024).toFixed(1)} MB`,
|
||||
` dmg sha256 ${sha256File(dmgPath)}`,
|
||||
]
|
||||
: []),
|
||||
` arch ${label}`,
|
||||
` node ${options.node} darwin-${node.arch}`,
|
||||
` target macOS ${target}+`,
|
||||
` signature ${options.sign}${options.identity ? ` (${options.identity})` : ''}`,
|
||||
` commit ${commit}`,
|
||||
...(published.length ? ['', ...published.map((line) => ` publish ${line}`)] : []),
|
||||
'',
|
||||
options.notarize
|
||||
? 'Notarized and stapled: users can open it with a normal double-click.'
|
||||
: 'Not notarized: first launch needs Privacy & Security > Open Anyway (see README-macos.txt).',
|
||||
'',
|
||||
].join('\n'),
|
||||
);
|
||||
return 0;
|
||||
}
|
||||
|
||||
main().then(
|
||||
(code) => {
|
||||
process.exitCode = code;
|
||||
},
|
||||
(error) => {
|
||||
fail(error instanceof Error ? error.message : String(error));
|
||||
},
|
||||
);
|
||||
@@ -0,0 +1,16 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
||||
<plist version="1.0">
|
||||
<dict>
|
||||
<!-- V8 compiles JavaScript at run time; the hardened runtime blocks that
|
||||
unless the process opts in. Node's own documentation names these two. -->
|
||||
<key>com.apple.security.cs.allow-jit</key>
|
||||
<true/>
|
||||
<key>com.apple.security.cs.allow-unsigned-executable-memory</key>
|
||||
<true/>
|
||||
<!-- sharp loads libvips as a dylib from its own package directory; library
|
||||
validation would otherwise reject it when the signatures differ. -->
|
||||
<key>com.apple.security.cs.disable-library-validation</key>
|
||||
<true/>
|
||||
</dict>
|
||||
</plist>
|
||||
|
After Width: | Height: | Size: 363 KiB |
@@ -0,0 +1,35 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="1024" height="1024" viewBox="0 0 1024 1024">
|
||||
<defs>
|
||||
<linearGradient id="tile" x1="0" y1="0" x2="0" y2="1">
|
||||
<stop offset="0" stop-color="#141b25"/>
|
||||
<stop offset="1" stop-color="#07090c"/>
|
||||
</linearGradient>
|
||||
<radialGradient id="glow" cx="50%" cy="36%" r="64%">
|
||||
<stop offset="0" stop-color="#2f6cb5" stop-opacity="0.5"/>
|
||||
<stop offset="0.65" stop-color="#123055" stop-opacity="0.16"/>
|
||||
<stop offset="1" stop-color="#0b0d10" stop-opacity="0"/>
|
||||
</radialGradient>
|
||||
<linearGradient id="bar" x1="0" y1="0" x2="0.35" y2="1">
|
||||
<stop offset="0" stop-color="#a6d2ff"/>
|
||||
<stop offset="0.18" stop-color="#6cb0fb"/>
|
||||
<stop offset="0.38" stop-color="#3d8df0"/>
|
||||
<stop offset="0.58" stop-color="#14509f"/>
|
||||
<stop offset="0.78" stop-color="#0a3272"/>
|
||||
<stop offset="1" stop-color="#021f4c"/>
|
||||
</linearGradient>
|
||||
<clipPath id="tileClip">
|
||||
<rect x="100" y="100" width="824" height="824" rx="185"/>
|
||||
</clipPath>
|
||||
</defs>
|
||||
<g clip-path="url(#tileClip)">
|
||||
<rect x="100" y="100" width="824" height="824" fill="url(#tile)"/>
|
||||
<rect x="100" y="100" width="824" height="824" fill="url(#glow)"/>
|
||||
</g>
|
||||
<rect x="100.5" y="100.5" width="823" height="823" rx="184.5" fill="none" stroke="#ffffff" stroke-opacity="0.10" stroke-width="1"/>
|
||||
<g transform="translate(206 178) scale(4.2)">
|
||||
<path d="M 0 127 Q 0 134 7 134 L 26 134 Q 33 134 33 127 L 33 112.5 A 16.5 16.5 0 0 0 0 112.5 Z" fill="url(#bar)"/>
|
||||
<path d="M 37 127 Q 37 134 44 134 L 62 134 Q 69 134 69 127 L 69 79 A 16 16 0 0 0 37 79 Z" fill="url(#bar)"/>
|
||||
<path d="M 74 126.5 Q 74 133.5 81 133.5 L 99 133.5 Q 106 133.5 106 126.5 L 106 41 A 16 16 0 0 0 74 41 Z" fill="url(#bar)"/>
|
||||
<path d="M 110 126 Q 110 133 117 133 L 134 133 Q 141 133 141 126 L 141 93.5 A 15.5 15.5 0 0 0 110 93.5 Z" fill="url(#bar)"/>
|
||||
</g>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 1.9 KiB |
@@ -0,0 +1,18 @@
|
||||
#!/bin/bash
|
||||
# Stop the Luminary server started by Luminary.app.
|
||||
# Double-clicking a .command file opens Terminal for as long as this runs.
|
||||
set -u
|
||||
|
||||
APP="/Applications/Luminary.app"
|
||||
if [ ! -d "$APP" ]; then
|
||||
APP="$(cd "$(dirname "$0")" && pwd)/Luminary.app"
|
||||
fi
|
||||
|
||||
if [ ! -d "$APP" ]; then
|
||||
echo "Luminary.app was not found in /Applications. Move it there and try again."
|
||||
read -r -p "Press Return to close this window." _
|
||||
exit 1
|
||||
fi
|
||||
|
||||
"$APP/Contents/Resources/launcher.sh" --stop
|
||||
read -r -p "Press Return to close this window." _
|
||||
@@ -0,0 +1,248 @@
|
||||
#!/bin/bash
|
||||
# Luminary.app launcher.
|
||||
#
|
||||
# Called by the native shim in Contents/MacOS/Luminary. Keeps the same rules as
|
||||
# the Windows launcher: pick a loopback port, start the bundled node exactly like
|
||||
# `node server/index.mjs`, wait for /api/health, then open the browser. The
|
||||
# server is detached and keeps running after the app exits, so launching again
|
||||
# reuses it instead of starting a second copy.
|
||||
#
|
||||
# launcher.sh start (or reuse) and open the window
|
||||
# launcher.sh --stop stop the server recorded in runtime.json
|
||||
# launcher.sh --status print pid, port, health and data directory
|
||||
# launcher.sh --verify check that this is a complete bundle (exit 3 if not)
|
||||
# launcher.sh --browser open a normal browser tab instead of an app window
|
||||
set -u
|
||||
|
||||
HERE="$(cd "$(dirname "$0")" && pwd)"
|
||||
APP="$HERE/app"
|
||||
NODE="$HERE/runtime/node"
|
||||
DATA="${LUMINARY_DATA:-$HOME/Library/Application Support/Luminary/data}"
|
||||
STATE="$DATA/runtime.json"
|
||||
LOGS="$DATA/logs"
|
||||
WINDOW="${LUMINARY_WINDOW:-app}"
|
||||
|
||||
say() { printf 'Luminary: %s\n' "$*"; }
|
||||
err() { printf 'Luminary: %s\n' "$*" >&2; }
|
||||
die() { err "$*"; exit 1; }
|
||||
|
||||
# A blocking dialog for launches from Finder, where stderr goes nowhere.
|
||||
dialog() {
|
||||
local message
|
||||
message=$(printf '%s' "$1" | tr '"' "'" | tr '\n' ' ')
|
||||
if command -v osascript >/dev/null 2>&1; then
|
||||
osascript -e "display dialog \"$message\" with title \"Luminary\" buttons {\"OK\"} default button 1 with icon caution" >/dev/null 2>&1 || true
|
||||
fi
|
||||
}
|
||||
|
||||
version_line() {
|
||||
if [ -f "$HERE/version.txt" ]; then head -1 "$HERE/version.txt"; else echo "Luminary (version unknown)"; fi
|
||||
}
|
||||
|
||||
state_port() {
|
||||
[ -f "$STATE" ] || return 0
|
||||
sed -n 's/.*"port"[[:space:]]*:[[:space:]]*\([0-9][0-9]*\).*/\1/p' "$STATE" | head -1
|
||||
}
|
||||
|
||||
state_pid() {
|
||||
[ -f "$STATE" ] || return 0
|
||||
sed -n 's/.*"pid"[[:space:]]*:[[:space:]]*\([0-9][0-9]*\).*/\1/p' "$STATE" | head -1
|
||||
}
|
||||
|
||||
healthy() {
|
||||
curl -fs -m 2 "http://127.0.0.1:$1/api/health" >/dev/null 2>&1
|
||||
}
|
||||
|
||||
# Ask node rather than nc: the bundle always has one, and nc's flags differ
|
||||
# between the BSD tool macOS ships and builds found elsewhere.
|
||||
port_in_use() {
|
||||
"$NODE" -e 'const net=require("net");const s=net.connect(+process.argv[1],"127.0.0.1");s.on("connect",()=>{s.destroy();process.exit(0)});s.on("error",()=>process.exit(1))' "$1" >/dev/null 2>&1
|
||||
}
|
||||
|
||||
tail_logs() {
|
||||
[ -f "$LOGS/server.err.log" ] || return 0
|
||||
err "last lines from $LOGS/server.err.log:"
|
||||
tail -n 20 "$LOGS/server.err.log" >&2 || true
|
||||
}
|
||||
|
||||
open_window() {
|
||||
local url="$1"
|
||||
if [ "$WINDOW" = "browser" ]; then
|
||||
open "$url"
|
||||
return
|
||||
fi
|
||||
if [ -d "/Applications/Google Chrome.app" ] || [ -d "$HOME/Applications/Google Chrome.app" ]; then
|
||||
open -na "Google Chrome" --args \
|
||||
--app="$url" \
|
||||
--user-data-dir="$DATA/window-profile-chrome" \
|
||||
--window-size=1500,950 --no-first-run --no-default-browser-check
|
||||
elif [ -d "/Applications/Microsoft Edge.app" ] || [ -d "$HOME/Applications/Microsoft Edge.app" ]; then
|
||||
open -na "Microsoft Edge" --args \
|
||||
--app="$url" \
|
||||
--user-data-dir="$DATA/window-profile-edge" \
|
||||
--window-size=1500,950 --no-first-run --no-default-browser-check
|
||||
else
|
||||
open "$url"
|
||||
fi
|
||||
}
|
||||
|
||||
verify() {
|
||||
local status=0 file size
|
||||
for file in "$NODE" "$APP/server/index.mjs" "$APP/dist/index.html"; do
|
||||
if [ ! -f "$file" ]; then
|
||||
err "missing: ${file#"$HERE"/}"
|
||||
status=3
|
||||
elif [ ! -s "$file" ]; then
|
||||
err "empty: ${file#"$HERE"/}"
|
||||
status=3
|
||||
else
|
||||
size=$(wc -c <"$file" | tr -d ' ')
|
||||
say "ok: ${file#"$HERE"/} ($size bytes)"
|
||||
fi
|
||||
done
|
||||
say "bundle: $HERE"
|
||||
say "version: $(version_line)"
|
||||
return $status
|
||||
}
|
||||
|
||||
start() {
|
||||
[ -x "$NODE" ] || chmod +x "$NODE" 2>/dev/null || true
|
||||
|
||||
if [ -f "$STATE" ]; then
|
||||
local existing
|
||||
existing=$(state_port)
|
||||
if [ -n "$existing" ] && healthy "$existing"; then
|
||||
say "already running on port $existing"
|
||||
open_window "http://127.0.0.1:$existing"
|
||||
exit 0
|
||||
fi
|
||||
rm -f "$STATE"
|
||||
fi
|
||||
|
||||
if ! verify >/dev/null 2>&1; then
|
||||
verify >&2 || true
|
||||
dialog "This copy of Luminary is incomplete. Copy Luminary.app out of the disk image or zip and try again. If it still fails, download the app again."
|
||||
exit 3
|
||||
fi
|
||||
|
||||
mkdir -p "$DATA" "$LOGS" 2>/dev/null || {
|
||||
dialog "Luminary cannot write to $DATA. Set LUMINARY_DATA to a folder you can write to and try again."
|
||||
exit 1
|
||||
}
|
||||
|
||||
local port=""
|
||||
local candidate
|
||||
# Brace expansion instead of seq: macOS does not ship seq.
|
||||
for candidate in {8787..8887}; do
|
||||
if ! port_in_use "$candidate"; then
|
||||
port="$candidate"
|
||||
break
|
||||
fi
|
||||
done
|
||||
[ -n "$port" ] || { dialog "No free port between 8787 and 8887. Quit the app using one and try again."; exit 1; }
|
||||
|
||||
LUMINARY_DATA="$DATA" \
|
||||
LUMINARY_LOCAL=1 \
|
||||
HOST=127.0.0.1 \
|
||||
PORT="$port" \
|
||||
NODE_ENV=production \
|
||||
nohup "$NODE" --disable-warning=ExperimentalWarning "$APP/server/index.mjs" \
|
||||
>>"$LOGS/server.out.log" 2>>"$LOGS/server.err.log" &
|
||||
local pid=$!
|
||||
|
||||
printf '{\n "pid": %s,\n "port": %s,\n "url": "http://127.0.0.1:%s",\n "data": "%s",\n "started": "%s"\n}\n' \
|
||||
"$pid" "$port" "$port" "$DATA" "$(date -u +%Y-%m-%dT%H:%M:%SZ)" >"$STATE"
|
||||
|
||||
local waited=0
|
||||
while [ "$waited" -lt 240 ]; do
|
||||
if healthy "$port"; then
|
||||
open_window "http://127.0.0.1:$port"
|
||||
exit 0
|
||||
fi
|
||||
if ! kill -0 "$pid" 2>/dev/null; then
|
||||
rm -f "$STATE"
|
||||
tail_logs
|
||||
dialog "Luminary's server stopped while starting. Log: $LOGS/server.err.log"
|
||||
exit 1
|
||||
fi
|
||||
sleep 0.5
|
||||
waited=$((waited + 1))
|
||||
done
|
||||
|
||||
kill "$pid" 2>/dev/null || true
|
||||
rm -f "$STATE"
|
||||
tail_logs
|
||||
dialog "Luminary did not start within 120 seconds. Log: $LOGS/server.err.log"
|
||||
exit 1
|
||||
}
|
||||
|
||||
stop() {
|
||||
if [ ! -f "$STATE" ]; then
|
||||
say "not running"
|
||||
return 0
|
||||
fi
|
||||
local pid
|
||||
pid=$(state_pid)
|
||||
if [ -n "$pid" ] && kill -0 "$pid" 2>/dev/null; then
|
||||
kill -TERM "$pid" 2>/dev/null || true
|
||||
local tick
|
||||
for tick in {1..20}; do
|
||||
kill -0 "$pid" 2>/dev/null || break
|
||||
sleep 0.25
|
||||
done
|
||||
kill -0 "$pid" 2>/dev/null && kill -KILL "$pid" 2>/dev/null || true
|
||||
say "stopped (pid $pid)"
|
||||
else
|
||||
say "not running (removed a stale runtime.json)"
|
||||
fi
|
||||
rm -f "$STATE"
|
||||
}
|
||||
|
||||
status() {
|
||||
local port pid
|
||||
port=$(state_port)
|
||||
pid=$(state_pid)
|
||||
say "version: $(version_line)"
|
||||
say "bundle: $HERE"
|
||||
say "data: $DATA"
|
||||
if [ -n "$pid" ] && kill -0 "$pid" 2>/dev/null; then
|
||||
say "pid: $pid"
|
||||
elif [ -n "$pid" ]; then
|
||||
say "pid: $pid (not running)"
|
||||
else
|
||||
say "pid: -"
|
||||
fi
|
||||
if [ -n "$port" ] && healthy "$port"; then
|
||||
say "health: ok on http://127.0.0.1:$port"
|
||||
elif [ -n "$port" ]; then
|
||||
say "health: no response on port $port"
|
||||
else
|
||||
say "health: not started"
|
||||
fi
|
||||
}
|
||||
|
||||
case "${1:-}" in
|
||||
--stop) stop ;;
|
||||
--status) status ;;
|
||||
--verify) verify; exit $? ;;
|
||||
--browser) WINDOW=browser; start ;;
|
||||
--help | -h)
|
||||
cat <<'USAGE'
|
||||
Luminary.app launcher
|
||||
|
||||
No argument starts the app (or reuses a running copy) and opens the window.
|
||||
--browser open a normal browser tab instead of a Chrome/Edge app window
|
||||
--stop stop the server this bundle started
|
||||
--status print version, pid, port, health and the data directory
|
||||
--verify check that the bundle is complete
|
||||
|
||||
Data: ~/Library/Application Support/Luminary/data (override with LUMINARY_DATA)
|
||||
Logs: <data>/logs/server.out.log and server.err.log
|
||||
USAGE
|
||||
;;
|
||||
"") start ;;
|
||||
*)
|
||||
err "unknown argument: $1 (try --help)"
|
||||
exit 2
|
||||
;;
|
||||
esac
|
||||
@@ -0,0 +1,73 @@
|
||||
/*
|
||||
* Luminary.app main executable.
|
||||
*
|
||||
* The bundle needs a Mach-O main executable so it can be code signed and, if a
|
||||
* certificate is ever bought, notarized: Apple's notary service rejects a
|
||||
* bundle whose CFBundleExecutable is a shell script. This shim resolves its own
|
||||
* path, finds Contents/Resources/launcher.sh next to it, and execs bash on it,
|
||||
* passing every argument through. All the actual launcher logic lives in that
|
||||
* script, where it can be changed without recompiling anything.
|
||||
*/
|
||||
#include <limits.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <unistd.h>
|
||||
|
||||
#ifdef __APPLE__
|
||||
#include <mach-o/dyld.h>
|
||||
#endif
|
||||
|
||||
/** Write this process's executable path into buf, or return -1. */
|
||||
static int executable_path(char *buf, size_t size) {
|
||||
#ifdef __APPLE__
|
||||
uint32_t needed = (uint32_t)size;
|
||||
if (_NSGetExecutablePath(buf, &needed) != 0) return -1;
|
||||
return 0;
|
||||
#else
|
||||
/* Not used in the bundle; kept so the shim can be built and tested when
|
||||
* packaging is exercised from a non-Apple host. */
|
||||
ssize_t length = readlink("/proc/self/exe", buf, size - 1);
|
||||
if (length < 0) return -1;
|
||||
buf[length] = '\0';
|
||||
return 0;
|
||||
#endif
|
||||
}
|
||||
|
||||
int main(int argc, char **argv) {
|
||||
char raw[PATH_MAX];
|
||||
char exe[PATH_MAX];
|
||||
char script[PATH_MAX];
|
||||
|
||||
if (executable_path(raw, sizeof raw) != 0) {
|
||||
fprintf(stderr, "luminary: cannot resolve the application path\n");
|
||||
return 1;
|
||||
}
|
||||
if (realpath(raw, exe) == NULL) {
|
||||
fprintf(stderr, "luminary: cannot resolve %s\n", raw);
|
||||
return 1;
|
||||
}
|
||||
|
||||
/* exe is .../Luminary.app/Contents/MacOS/Luminary */
|
||||
char *slash = strrchr(exe, '/');
|
||||
if (slash == NULL) {
|
||||
fprintf(stderr, "luminary: unexpected executable path %s\n", exe);
|
||||
return 1;
|
||||
}
|
||||
*slash = '\0';
|
||||
|
||||
if (snprintf(script, sizeof script, "%s/../Resources/launcher.sh", exe) >= (int)sizeof script) {
|
||||
fprintf(stderr, "luminary: application path is too long\n");
|
||||
return 1;
|
||||
}
|
||||
|
||||
char *args[argc + 2];
|
||||
args[0] = "/bin/bash";
|
||||
args[1] = script;
|
||||
for (int i = 1; i < argc; i++) args[i + 1] = argv[i];
|
||||
args[argc + 1] = NULL;
|
||||
|
||||
execv("/bin/bash", args);
|
||||
perror("luminary: could not start the launcher");
|
||||
return 1;
|
||||
}
|
||||
@@ -1,17 +1,18 @@
|
||||
{
|
||||
"name": "luminary",
|
||||
"version": "1.0.0",
|
||||
"version": "0.5.2",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "luminary",
|
||||
"version": "1.0.0",
|
||||
"version": "0.5.2",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"exifr": "^7.1.3",
|
||||
"libraw-wasm": "^1.6.0",
|
||||
"nodemailer": "^10.6.1",
|
||||
"onnxruntime-node": "1.23.0",
|
||||
"react": "^18.3.1",
|
||||
"react-dom": "^18.3.1",
|
||||
"sharp": "^0.35.5"
|
||||
@@ -819,9 +820,6 @@
|
||||
"cpu": [
|
||||
"arm"
|
||||
],
|
||||
"libc": [
|
||||
"glibc"
|
||||
],
|
||||
"license": "LGPL-3.0-or-later",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -838,9 +836,6 @@
|
||||
"cpu": [
|
||||
"arm64"
|
||||
],
|
||||
"libc": [
|
||||
"glibc"
|
||||
],
|
||||
"license": "LGPL-3.0-or-later",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -857,9 +852,6 @@
|
||||
"cpu": [
|
||||
"ppc64"
|
||||
],
|
||||
"libc": [
|
||||
"glibc"
|
||||
],
|
||||
"license": "LGPL-3.0-or-later",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -876,9 +868,6 @@
|
||||
"cpu": [
|
||||
"riscv64"
|
||||
],
|
||||
"libc": [
|
||||
"glibc"
|
||||
],
|
||||
"license": "LGPL-3.0-or-later",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -895,9 +884,6 @@
|
||||
"cpu": [
|
||||
"s390x"
|
||||
],
|
||||
"libc": [
|
||||
"glibc"
|
||||
],
|
||||
"license": "LGPL-3.0-or-later",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -914,9 +900,6 @@
|
||||
"cpu": [
|
||||
"x64"
|
||||
],
|
||||
"libc": [
|
||||
"glibc"
|
||||
],
|
||||
"license": "LGPL-3.0-or-later",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -933,9 +916,6 @@
|
||||
"cpu": [
|
||||
"arm64"
|
||||
],
|
||||
"libc": [
|
||||
"musl"
|
||||
],
|
||||
"license": "LGPL-3.0-or-later",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -952,9 +932,6 @@
|
||||
"cpu": [
|
||||
"x64"
|
||||
],
|
||||
"libc": [
|
||||
"musl"
|
||||
],
|
||||
"license": "LGPL-3.0-or-later",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -971,9 +948,6 @@
|
||||
"cpu": [
|
||||
"arm"
|
||||
],
|
||||
"libc": [
|
||||
"glibc"
|
||||
],
|
||||
"license": "Apache-2.0",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -996,9 +970,6 @@
|
||||
"cpu": [
|
||||
"arm64"
|
||||
],
|
||||
"libc": [
|
||||
"glibc"
|
||||
],
|
||||
"license": "Apache-2.0",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -1021,9 +992,6 @@
|
||||
"cpu": [
|
||||
"ppc64"
|
||||
],
|
||||
"libc": [
|
||||
"glibc"
|
||||
],
|
||||
"license": "Apache-2.0",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -1046,9 +1014,6 @@
|
||||
"cpu": [
|
||||
"riscv64"
|
||||
],
|
||||
"libc": [
|
||||
"glibc"
|
||||
],
|
||||
"license": "Apache-2.0",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -1071,9 +1036,6 @@
|
||||
"cpu": [
|
||||
"s390x"
|
||||
],
|
||||
"libc": [
|
||||
"glibc"
|
||||
],
|
||||
"license": "Apache-2.0",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -1096,9 +1058,6 @@
|
||||
"cpu": [
|
||||
"x64"
|
||||
],
|
||||
"libc": [
|
||||
"glibc"
|
||||
],
|
||||
"license": "Apache-2.0",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -1121,9 +1080,6 @@
|
||||
"cpu": [
|
||||
"arm64"
|
||||
],
|
||||
"libc": [
|
||||
"musl"
|
||||
],
|
||||
"license": "Apache-2.0",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -1146,9 +1102,6 @@
|
||||
"cpu": [
|
||||
"x64"
|
||||
],
|
||||
"libc": [
|
||||
"musl"
|
||||
],
|
||||
"license": "Apache-2.0",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -1419,9 +1372,6 @@
|
||||
"arm"
|
||||
],
|
||||
"dev": true,
|
||||
"libc": [
|
||||
"glibc"
|
||||
],
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -1436,9 +1386,6 @@
|
||||
"arm"
|
||||
],
|
||||
"dev": true,
|
||||
"libc": [
|
||||
"musl"
|
||||
],
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -1453,9 +1400,6 @@
|
||||
"arm64"
|
||||
],
|
||||
"dev": true,
|
||||
"libc": [
|
||||
"glibc"
|
||||
],
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -1470,9 +1414,6 @@
|
||||
"arm64"
|
||||
],
|
||||
"dev": true,
|
||||
"libc": [
|
||||
"musl"
|
||||
],
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -1487,9 +1428,6 @@
|
||||
"loong64"
|
||||
],
|
||||
"dev": true,
|
||||
"libc": [
|
||||
"glibc"
|
||||
],
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -1504,9 +1442,6 @@
|
||||
"loong64"
|
||||
],
|
||||
"dev": true,
|
||||
"libc": [
|
||||
"musl"
|
||||
],
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -1521,9 +1456,6 @@
|
||||
"ppc64"
|
||||
],
|
||||
"dev": true,
|
||||
"libc": [
|
||||
"glibc"
|
||||
],
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -1538,9 +1470,6 @@
|
||||
"ppc64"
|
||||
],
|
||||
"dev": true,
|
||||
"libc": [
|
||||
"musl"
|
||||
],
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -1555,9 +1484,6 @@
|
||||
"riscv64"
|
||||
],
|
||||
"dev": true,
|
||||
"libc": [
|
||||
"glibc"
|
||||
],
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -1572,9 +1498,6 @@
|
||||
"riscv64"
|
||||
],
|
||||
"dev": true,
|
||||
"libc": [
|
||||
"musl"
|
||||
],
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -1589,9 +1512,6 @@
|
||||
"s390x"
|
||||
],
|
||||
"dev": true,
|
||||
"libc": [
|
||||
"glibc"
|
||||
],
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -1606,9 +1526,6 @@
|
||||
"x64"
|
||||
],
|
||||
"dev": true,
|
||||
"libc": [
|
||||
"glibc"
|
||||
],
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -1623,9 +1540,6 @@
|
||||
"x64"
|
||||
],
|
||||
"dev": true,
|
||||
"libc": [
|
||||
"musl"
|
||||
],
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -1930,6 +1844,15 @@
|
||||
"url": "https://opencollective.com/vitest"
|
||||
}
|
||||
},
|
||||
"node_modules/adm-zip": {
|
||||
"version": "0.5.18",
|
||||
"resolved": "https://registry.npmjs.org/adm-zip/-/adm-zip-0.5.18.tgz",
|
||||
"integrity": "sha512-ufJnssQGbxzLNS1Ho9bCtX4rQKCCvoVuDLHoJyc3F9dOGDB4BkWs2Ci0kv53lqocAEQ/Cbi+I2XCsNYGqVYqng==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=12.0"
|
||||
}
|
||||
},
|
||||
"node_modules/assertion-error": {
|
||||
"version": "2.0.1",
|
||||
"resolved": "https://registry.npmjs.org/assertion-error/-/assertion-error-2.0.1.tgz",
|
||||
@@ -1953,6 +1876,13 @@
|
||||
"node": ">=6.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/boolean": {
|
||||
"version": "3.2.0",
|
||||
"resolved": "https://registry.npmjs.org/boolean/-/boolean-3.2.0.tgz",
|
||||
"integrity": "sha512-d0II/GO9uf9lfUHH2BQsjxzRJZBdsjgsBiW4BvhWk/3qoKwQFjIDVN19PfX8F2D/r9PCMTtLWjYVCFrpeYUzsw==",
|
||||
"deprecated": "Package no longer supported. Contact Support at https://www.npmjs.com/support for more info.",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/browserslist": {
|
||||
"version": "4.29.6",
|
||||
"resolved": "https://registry.npmjs.org/browserslist/-/browserslist-4.29.6.tgz",
|
||||
@@ -2087,6 +2017,40 @@
|
||||
"node": ">=6"
|
||||
}
|
||||
},
|
||||
"node_modules/define-data-property": {
|
||||
"version": "1.1.4",
|
||||
"resolved": "https://registry.npmjs.org/define-data-property/-/define-data-property-1.1.4.tgz",
|
||||
"integrity": "sha512-rBMvIzlpA8v6E+SJZoo++HAYqsLrkg7MSfIinMPFhmkorw7X+dOXVJQs+QT69zGkzMyfDnIMN2Wid1+NbL3T+A==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"es-define-property": "^1.0.0",
|
||||
"es-errors": "^1.3.0",
|
||||
"gopd": "^1.0.1"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= 0.4"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://github.com/sponsors/ljharb"
|
||||
}
|
||||
},
|
||||
"node_modules/define-properties": {
|
||||
"version": "1.2.1",
|
||||
"resolved": "https://registry.npmjs.org/define-properties/-/define-properties-1.2.1.tgz",
|
||||
"integrity": "sha512-8QmQKqEASLd5nx0U1B1okLElbUuuttJ/AnYmRXbbbGDWh6uS208EjD4Xqq/I9wK7u0v6O08XhTWnt5XtEbR6Dg==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"define-data-property": "^1.0.1",
|
||||
"has-property-descriptors": "^1.0.0",
|
||||
"object-keys": "^1.1.1"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= 0.4"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://github.com/sponsors/ljharb"
|
||||
}
|
||||
},
|
||||
"node_modules/detect-libc": {
|
||||
"version": "2.1.2",
|
||||
"resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.1.2.tgz",
|
||||
@@ -2096,6 +2060,12 @@
|
||||
"node": ">=8"
|
||||
}
|
||||
},
|
||||
"node_modules/detect-node": {
|
||||
"version": "2.1.0",
|
||||
"resolved": "https://registry.npmjs.org/detect-node/-/detect-node-2.1.0.tgz",
|
||||
"integrity": "sha512-T0NIuQpnTvFDATNuHN5roPwSBG83rFsuO+MXXH9/3N1eFbn4wcPjttvjMLEPWJ0RGUYgQE7cGgS3tNxbqCGM7g==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/electron-to-chromium": {
|
||||
"version": "1.5.492",
|
||||
"resolved": "https://registry.npmjs.org/electron-to-chromium/-/electron-to-chromium-1.5.492.tgz",
|
||||
@@ -2103,6 +2073,24 @@
|
||||
"dev": true,
|
||||
"license": "ISC"
|
||||
},
|
||||
"node_modules/es-define-property": {
|
||||
"version": "1.0.1",
|
||||
"resolved": "https://registry.npmjs.org/es-define-property/-/es-define-property-1.0.1.tgz",
|
||||
"integrity": "sha512-e3nRfgfUZ4rNGL232gUgX06QNyyez04KdjFrF+LTRoOXmrOgFKDg4BCdsjW8EnT69eqdYGmRpJwiPVYNrCaW3g==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">= 0.4"
|
||||
}
|
||||
},
|
||||
"node_modules/es-errors": {
|
||||
"version": "1.3.0",
|
||||
"resolved": "https://registry.npmjs.org/es-errors/-/es-errors-1.3.0.tgz",
|
||||
"integrity": "sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">= 0.4"
|
||||
}
|
||||
},
|
||||
"node_modules/es-module-lexer": {
|
||||
"version": "1.7.0",
|
||||
"resolved": "https://registry.npmjs.org/es-module-lexer/-/es-module-lexer-1.7.0.tgz",
|
||||
@@ -2110,6 +2098,12 @@
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/es6-error": {
|
||||
"version": "4.1.1",
|
||||
"resolved": "https://registry.npmjs.org/es6-error/-/es6-error-4.1.1.tgz",
|
||||
"integrity": "sha512-Um/+FxMr9CISWh0bi5Zv0iOD+4cFh5qLeks1qhAopKVAJw3drgKbKySikp7wGhDL0HPeaja0P5ULZrxLkniUVg==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/esbuild": {
|
||||
"version": "0.21.5",
|
||||
"resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.21.5.tgz",
|
||||
@@ -2159,6 +2153,18 @@
|
||||
"node": ">=6"
|
||||
}
|
||||
},
|
||||
"node_modules/escape-string-regexp": {
|
||||
"version": "4.0.0",
|
||||
"resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-4.0.0.tgz",
|
||||
"integrity": "sha512-TtpcNJ3XAzx3Gq8sWRzJaVajRs0uVxA2YAkdb1jm2YkPz4G6egUFAyA3n5vtEIZefPk5Wa4UXbKuS5fKkJWdgA==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=10"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://github.com/sponsors/sindresorhus"
|
||||
}
|
||||
},
|
||||
"node_modules/estree-walker": {
|
||||
"version": "3.0.3",
|
||||
"resolved": "https://registry.npmjs.org/estree-walker/-/estree-walker-3.0.3.tgz",
|
||||
@@ -2210,6 +2216,75 @@
|
||||
"node": ">=6.9.0"
|
||||
}
|
||||
},
|
||||
"node_modules/global-agent": {
|
||||
"version": "3.0.0",
|
||||
"resolved": "https://registry.npmjs.org/global-agent/-/global-agent-3.0.0.tgz",
|
||||
"integrity": "sha512-PT6XReJ+D07JvGoxQMkT6qji/jVNfX/h364XHZOWeRzy64sSFr+xJ5OX7LI3b4MPQzdL4H8Y8M0xzPpsVMwA8Q==",
|
||||
"license": "BSD-3-Clause",
|
||||
"dependencies": {
|
||||
"boolean": "^3.0.1",
|
||||
"es6-error": "^4.1.1",
|
||||
"matcher": "^3.0.0",
|
||||
"roarr": "^2.15.3",
|
||||
"semver": "^7.3.2",
|
||||
"serialize-error": "^7.0.1"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=10.0"
|
||||
}
|
||||
},
|
||||
"node_modules/global-agent/node_modules/semver": {
|
||||
"version": "7.8.6",
|
||||
"resolved": "https://registry.npmjs.org/semver/-/semver-7.8.6.tgz",
|
||||
"integrity": "sha512-9lpSSU4Mly3mrtruwLs1eLK6+gzbzqeBFwRNjIjE+9LuDpWdYctrQlQ3ej1Ilgi7gknpsTRnPoLP8DpCHqHIJw==",
|
||||
"license": "ISC",
|
||||
"bin": {
|
||||
"semver": "bin/semver.js"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=10"
|
||||
}
|
||||
},
|
||||
"node_modules/globalthis": {
|
||||
"version": "1.0.4",
|
||||
"resolved": "https://registry.npmjs.org/globalthis/-/globalthis-1.0.4.tgz",
|
||||
"integrity": "sha512-DpLKbNU4WylpxJykQujfCcwYWiV/Jhm50Goo0wrVILAv5jOr9d+H+UR3PhSCD2rCCEIg0uc+G+muBTwD54JhDQ==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"define-properties": "^1.2.1",
|
||||
"gopd": "^1.0.1"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= 0.4"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://github.com/sponsors/ljharb"
|
||||
}
|
||||
},
|
||||
"node_modules/gopd": {
|
||||
"version": "1.2.0",
|
||||
"resolved": "https://registry.npmjs.org/gopd/-/gopd-1.2.0.tgz",
|
||||
"integrity": "sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">= 0.4"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://github.com/sponsors/ljharb"
|
||||
}
|
||||
},
|
||||
"node_modules/has-property-descriptors": {
|
||||
"version": "1.0.2",
|
||||
"resolved": "https://registry.npmjs.org/has-property-descriptors/-/has-property-descriptors-1.0.2.tgz",
|
||||
"integrity": "sha512-55JNKuIW+vq4Ke1BjOTjM2YctQIvCT7GFzHwmfZPGo5wnrgkid0YQtnAleFSqumZm4az3n2BS+erby5ipJdgrg==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"es-define-property": "^1.0.0"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://github.com/sponsors/ljharb"
|
||||
}
|
||||
},
|
||||
"node_modules/js-tokens": {
|
||||
"version": "4.0.0",
|
||||
"resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz",
|
||||
@@ -2229,6 +2304,12 @@
|
||||
"node": ">=6"
|
||||
}
|
||||
},
|
||||
"node_modules/json-stringify-safe": {
|
||||
"version": "5.0.1",
|
||||
"resolved": "https://registry.npmjs.org/json-stringify-safe/-/json-stringify-safe-5.0.1.tgz",
|
||||
"integrity": "sha512-ZClg6AaYvamvYEE82d3Iyd3vSSIjQ+odgjaTzRuO3s7toCdFKczob2i0zCh7JE8kWn17yvAWhUVxvqGwUalsRA==",
|
||||
"license": "ISC"
|
||||
},
|
||||
"node_modules/json5": {
|
||||
"version": "2.2.3",
|
||||
"resolved": "https://registry.npmjs.org/json5/-/json5-2.2.3.tgz",
|
||||
@@ -2287,6 +2368,18 @@
|
||||
"@jridgewell/sourcemap-codec": "^1.5.5"
|
||||
}
|
||||
},
|
||||
"node_modules/matcher": {
|
||||
"version": "3.0.0",
|
||||
"resolved": "https://registry.npmjs.org/matcher/-/matcher-3.0.0.tgz",
|
||||
"integrity": "sha512-OkeDaAZ/bQCxeFAozM55PKcKU0yJMPGifLwV4Qgjitu+5MoAfSQN4lsLJeXZ1b8w0x+/Emda6MZgXS1jvsapng==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"escape-string-regexp": "^4.0.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=10"
|
||||
}
|
||||
},
|
||||
"node_modules/ms": {
|
||||
"version": "2.1.3",
|
||||
"resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz",
|
||||
@@ -2332,6 +2425,38 @@
|
||||
"node": ">=20.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/object-keys": {
|
||||
"version": "1.1.1",
|
||||
"resolved": "https://registry.npmjs.org/object-keys/-/object-keys-1.1.1.tgz",
|
||||
"integrity": "sha512-NuAESUOUMrlIXOfHKzD6bpPu3tYt3xvjNdRIQ+FeT0lNb4K8WR70CaDxhuNguS2XG+GjkyMwOzsN5ZktImfhLA==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">= 0.4"
|
||||
}
|
||||
},
|
||||
"node_modules/onnxruntime-common": {
|
||||
"version": "1.23.0",
|
||||
"resolved": "https://registry.npmjs.org/onnxruntime-common/-/onnxruntime-common-1.23.0.tgz",
|
||||
"integrity": "sha512-Auz8S9D7vpF8ok7fzTobvD1XdQDftRf/S7pHmjeCr3Xdymi4z1C7zx4vnT6nnUjbpelZdGwda0BmWHCCTMKUTg==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/onnxruntime-node": {
|
||||
"version": "1.23.0",
|
||||
"resolved": "https://registry.npmjs.org/onnxruntime-node/-/onnxruntime-node-1.23.0.tgz",
|
||||
"integrity": "sha512-j7QVuR4ouektZjOopKtXcIGsB3C6R9kVbgS10lc2e5SxoWMUhmCwxNl4qBslpWJaPrFxvrQrQaQLQdqku8V19w==",
|
||||
"hasInstallScript": true,
|
||||
"license": "MIT",
|
||||
"os": [
|
||||
"win32",
|
||||
"darwin",
|
||||
"linux"
|
||||
],
|
||||
"dependencies": {
|
||||
"adm-zip": "^0.5.16",
|
||||
"global-agent": "^3.0.0",
|
||||
"onnxruntime-common": "1.23.0"
|
||||
}
|
||||
},
|
||||
"node_modules/pathe": {
|
||||
"version": "1.1.2",
|
||||
"resolved": "https://registry.npmjs.org/pathe/-/pathe-1.1.2.tgz",
|
||||
@@ -2420,6 +2545,23 @@
|
||||
"node": ">=0.10.0"
|
||||
}
|
||||
},
|
||||
"node_modules/roarr": {
|
||||
"version": "2.15.4",
|
||||
"resolved": "https://registry.npmjs.org/roarr/-/roarr-2.15.4.tgz",
|
||||
"integrity": "sha512-CHhPh+UNHD2GTXNYhPWLnU8ONHdI+5DI+4EYIAOaiD63rHeYlZvyh8P+in5999TTSFgUYuKUAjzRI4mdh/p+2A==",
|
||||
"license": "BSD-3-Clause",
|
||||
"dependencies": {
|
||||
"boolean": "^3.0.1",
|
||||
"detect-node": "^2.0.4",
|
||||
"globalthis": "^1.0.1",
|
||||
"json-stringify-safe": "^5.0.1",
|
||||
"semver-compare": "^1.0.0",
|
||||
"sprintf-js": "^1.1.2"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=8.0"
|
||||
}
|
||||
},
|
||||
"node_modules/rollup": {
|
||||
"version": "4.68.7",
|
||||
"resolved": "https://registry.npmjs.org/rollup/-/rollup-4.68.7.tgz",
|
||||
@@ -2485,6 +2627,27 @@
|
||||
"semver": "bin/semver.js"
|
||||
}
|
||||
},
|
||||
"node_modules/semver-compare": {
|
||||
"version": "1.0.0",
|
||||
"resolved": "https://registry.npmjs.org/semver-compare/-/semver-compare-1.0.0.tgz",
|
||||
"integrity": "sha512-YM3/ITh2MJ5MtzaM429anh+x2jiLVjqILF4m4oyQB18W7Ggea7BfqdH/wGMK7dDiMghv/6WG7znWMwUDzJiXow==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/serialize-error": {
|
||||
"version": "7.0.1",
|
||||
"resolved": "https://registry.npmjs.org/serialize-error/-/serialize-error-7.0.1.tgz",
|
||||
"integrity": "sha512-8I8TjW5KMOKsZQTvoxjuSIa7foAwPWGOts+6o7sgjz41/qMD9VQHEDxi6PBvK2l0MXUmqZyNpUK+T2tQaaElvw==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"type-fest": "^0.13.1"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=10"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://github.com/sponsors/sindresorhus"
|
||||
}
|
||||
},
|
||||
"node_modules/sharp": {
|
||||
"version": "0.35.5",
|
||||
"resolved": "https://registry.npmjs.org/sharp/-/sharp-0.35.5.tgz",
|
||||
@@ -2563,6 +2726,12 @@
|
||||
"node": ">=6.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/sprintf-js": {
|
||||
"version": "1.1.3",
|
||||
"resolved": "https://registry.npmjs.org/sprintf-js/-/sprintf-js-1.1.3.tgz",
|
||||
"integrity": "sha512-Oo+0REFV59/rz3gfJNKQiBlwfHaSESl1pcGyABQsnnIfWOFt6JNj5gCog2U6MLZ//IGYD+nA8nI+mTShREReaA==",
|
||||
"license": "BSD-3-Clause"
|
||||
},
|
||||
"node_modules/stackback": {
|
||||
"version": "0.0.2",
|
||||
"resolved": "https://registry.npmjs.org/stackback/-/stackback-0.0.2.tgz",
|
||||
@@ -2628,6 +2797,18 @@
|
||||
"license": "0BSD",
|
||||
"optional": true
|
||||
},
|
||||
"node_modules/type-fest": {
|
||||
"version": "0.13.1",
|
||||
"resolved": "https://registry.npmjs.org/type-fest/-/type-fest-0.13.1.tgz",
|
||||
"integrity": "sha512-34R7HTnG0XIJcBSn5XhDd7nNFPRcXYRZrBB2O2jdKqYODldSzBAqzsWoZYYvduky73toYS/ESqxPvkDf/F0XMg==",
|
||||
"license": "(MIT OR CC0-1.0)",
|
||||
"engines": {
|
||||
"node": ">=10"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://github.com/sponsors/sindresorhus"
|
||||
}
|
||||
},
|
||||
"node_modules/typescript": {
|
||||
"version": "5.9.3",
|
||||
"resolved": "https://registry.npmjs.org/typescript/-/typescript-5.9.3.tgz",
|
||||
|
||||
@@ -2,13 +2,15 @@
|
||||
"name": "luminary",
|
||||
"private": true,
|
||||
"license": "MIT",
|
||||
"version": "1.0.0",
|
||||
"version": "0.5.2",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
"server": "node server/index.mjs",
|
||||
"server:dev": "node --watch server/index.mjs",
|
||||
"build": "tsc --noEmit && vite build",
|
||||
"build": "tsc --noEmit && vite build && node scripts/precompress.mjs",
|
||||
"precompress": "node scripts/precompress.mjs",
|
||||
"backup": "node scripts/backup.mjs",
|
||||
"start": "node server/index.mjs",
|
||||
"preview": "vite preview",
|
||||
"typecheck": "tsc --noEmit",
|
||||
@@ -22,6 +24,7 @@
|
||||
"exifr": "^7.1.3",
|
||||
"libraw-wasm": "^1.6.0",
|
||||
"nodemailer": "^10.6.1",
|
||||
"onnxruntime-node": "1.23.0",
|
||||
"react": "^18.3.1",
|
||||
"react-dom": "^18.3.1",
|
||||
"sharp": "^0.35.5"
|
||||
|
||||
@@ -0,0 +1,185 @@
|
||||
/**
|
||||
* Catalog backups without stopping the server.
|
||||
*
|
||||
* `VACUUM INTO` writes a consistent copy of the live SQLite database (including
|
||||
* everything still in the WAL), so a backup is safe while people are editing.
|
||||
* Originals are large, so copying them is opt-in: previews, thumbnails and
|
||||
* denoise renders are all regenerable, originals are not.
|
||||
*
|
||||
* npm run backup # database only, keep 14
|
||||
* npm run backup -- --with-originals # also copy originals/ (can be huge)
|
||||
* npm run backup -- --keep 30 --dir /mnt/backups
|
||||
*
|
||||
* Restore: stop the server, put the `catalog-*.db` snapshot back as lumenroom.db
|
||||
* (delete the old -wal/-shm files) and copy the originals snapshot back into the
|
||||
* storage root.
|
||||
*/
|
||||
|
||||
import fs from 'node:fs';
|
||||
import fsp from 'node:fs/promises';
|
||||
import path from 'node:path';
|
||||
import { DatabaseSync } from 'node:sqlite';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
|
||||
const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
|
||||
|
||||
function argValue(name, fallback) {
|
||||
const index = process.argv.indexOf(`--${name}`);
|
||||
if (index < 0) return fallback;
|
||||
const value = process.argv[index + 1];
|
||||
return value && !value.startsWith('--') ? value : fallback;
|
||||
}
|
||||
|
||||
const DATA_DIR = path.resolve(
|
||||
process.env.LUMINARY_DATA || process.env.LUMENROOM_DATA || path.join(ROOT, 'server', 'data'),
|
||||
);
|
||||
const DB_PATH = path.join(DATA_DIR, 'lumenroom.db');
|
||||
const BACKUP_DIR = path.resolve(
|
||||
argValue('dir', process.env.LUMINARY_BACKUP_DIR || path.join(DATA_DIR, 'backups')),
|
||||
);
|
||||
const KEEP = Math.max(1, Number(argValue('keep', process.env.LUMINARY_BACKUP_KEEP || '14')) || 14);
|
||||
const WITH_ORIGINALS = process.argv.includes('--with-originals');
|
||||
|
||||
const pad = (value) => String(value).padStart(2, '0');
|
||||
const now = new Date();
|
||||
const stamp = [
|
||||
now.getFullYear(),
|
||||
pad(now.getMonth() + 1),
|
||||
pad(now.getDate()),
|
||||
'-',
|
||||
pad(now.getHours()),
|
||||
pad(now.getMinutes()),
|
||||
pad(now.getSeconds()),
|
||||
].join('');
|
||||
|
||||
const fmt = (bytes) => {
|
||||
if (bytes >= 1024 ** 3) return `${(bytes / 1024 ** 3).toFixed(2)} GB`;
|
||||
if (bytes >= 1024 ** 2) return `${(bytes / 1024 ** 2).toFixed(1)} MB`;
|
||||
if (bytes >= 1024) return `${Math.round(bytes / 1024)} KB`;
|
||||
return `${bytes} B`;
|
||||
};
|
||||
|
||||
/** The admin may have moved image files out of DATA_DIR; the catalog knows. */
|
||||
function storageRoot() {
|
||||
const db = new DatabaseSync(DB_PATH, { readOnly: true });
|
||||
try {
|
||||
const row = db.prepare("SELECT value FROM kv WHERE key = 'storageRoot'").get();
|
||||
if (!row?.value) return DATA_DIR;
|
||||
const parsed = JSON.parse(row.value);
|
||||
return typeof parsed === 'string' && parsed.trim() ? path.resolve(parsed) : DATA_DIR;
|
||||
} catch {
|
||||
return DATA_DIR;
|
||||
} finally {
|
||||
db.close();
|
||||
}
|
||||
}
|
||||
|
||||
async function prune(prefix, keep) {
|
||||
let names = [];
|
||||
try {
|
||||
names = (await fsp.readdir(BACKUP_DIR)).filter((name) => name.startsWith(prefix));
|
||||
} catch {
|
||||
return 0;
|
||||
}
|
||||
names.sort();
|
||||
const stale = names.slice(0, Math.max(0, names.length - keep));
|
||||
for (const name of stale) {
|
||||
await fsp.rm(path.join(BACKUP_DIR, name), { recursive: true, force: true });
|
||||
}
|
||||
return stale.length;
|
||||
}
|
||||
|
||||
if (!fs.existsSync(DB_PATH)) {
|
||||
console.error(`backup: no catalog at ${DB_PATH}`);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
await fsp.mkdir(BACKUP_DIR, { recursive: true });
|
||||
|
||||
/* --------------------------------------------------------- database snapshot */
|
||||
const snapshot = path.join(BACKUP_DIR, `catalog-${stamp}.db`);
|
||||
const db = new DatabaseSync(DB_PATH);
|
||||
let counts;
|
||||
try {
|
||||
// VACUUM INTO is a consistent point-in-time copy and also compacts it.
|
||||
db.exec(`VACUUM INTO '${snapshot.replaceAll("'", "''")}'`);
|
||||
counts = {
|
||||
users: Number(db.prepare('SELECT COUNT(*) AS n FROM users').get()?.n ?? 0),
|
||||
events: Number(db.prepare('SELECT COUNT(*) AS n FROM events').get()?.n ?? 0),
|
||||
photos: Number(db.prepare('SELECT COUNT(*) AS n FROM photos').get()?.n ?? 0),
|
||||
};
|
||||
} catch (err) {
|
||||
console.error(`backup: could not snapshot the catalog: ${err.message}`);
|
||||
process.exit(1);
|
||||
} finally {
|
||||
db.close();
|
||||
}
|
||||
|
||||
/* Verify the copy opens and is internally consistent before trusting it. */
|
||||
const check = new DatabaseSync(snapshot, { readOnly: true });
|
||||
let integrity = 'unknown';
|
||||
try {
|
||||
integrity = String(check.prepare('PRAGMA integrity_check').get()?.integrity_check ?? 'unknown');
|
||||
} finally {
|
||||
check.close();
|
||||
}
|
||||
if (integrity !== 'ok') {
|
||||
console.error(`backup: snapshot failed its integrity check (${integrity})`);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
const dbBytes = (await fsp.stat(snapshot)).size;
|
||||
let copiedOriginals = null;
|
||||
let originalsBytes = 0;
|
||||
|
||||
/* ---------------------------------------------------------------- originals */
|
||||
if (WITH_ORIGINALS) {
|
||||
const source = path.join(storageRoot(), 'originals');
|
||||
const target = path.join(BACKUP_DIR, `originals-${stamp}`);
|
||||
try {
|
||||
await fsp.cp(source, target, { recursive: true, force: true });
|
||||
for (const name of await fsp.readdir(target)) {
|
||||
const stat = await fsp.stat(path.join(target, name)).catch(() => null);
|
||||
if (stat?.isFile()) originalsBytes += stat.size;
|
||||
}
|
||||
copiedOriginals = target;
|
||||
} catch (err) {
|
||||
console.error(`backup: catalog saved, but copying originals failed: ${err.message}`);
|
||||
process.exitCode = 1;
|
||||
}
|
||||
}
|
||||
|
||||
await fsp.writeFile(
|
||||
path.join(BACKUP_DIR, `manifest-${stamp}.json`),
|
||||
`${JSON.stringify(
|
||||
{
|
||||
kind: 'luminary-backup',
|
||||
version: 1,
|
||||
createdAt: now.toISOString(),
|
||||
catalog: path.basename(snapshot),
|
||||
counts,
|
||||
bytes: dbBytes,
|
||||
originals: copiedOriginals ? { path: path.basename(copiedOriginals), bytes: originalsBytes } : null,
|
||||
storageRoot: storageRoot(),
|
||||
},
|
||||
null,
|
||||
2,
|
||||
)}\n`,
|
||||
);
|
||||
|
||||
const prunedDb = await prune('catalog-', KEEP);
|
||||
const prunedOriginals = WITH_ORIGINALS ? await prune('originals-', KEEP) : 0;
|
||||
const prunedManifests = await prune('manifest-', KEEP);
|
||||
|
||||
console.log(`backup: ${snapshot}`);
|
||||
console.log(
|
||||
` ${fmt(dbBytes)} · ${counts.users} user(s), ${counts.events} event(s), ${counts.photos} photo record(s)`,
|
||||
);
|
||||
if (copiedOriginals) console.log(` originals: ${copiedOriginals} (${fmt(originalsBytes)})`);
|
||||
const pruned = prunedDb + prunedOriginals + prunedManifests;
|
||||
if (pruned) console.log(` pruned ${pruned} old file(s), keeping ${KEEP}`);
|
||||
if (!WITH_ORIGINALS) {
|
||||
console.log(
|
||||
` note: original files were not copied; run with --with-originals or rsync ${path.join(storageRoot(), 'originals')}`,
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,672 @@
|
||||
#!/usr/bin/env node
|
||||
/**
|
||||
* Render film-look sample frames and build the film gallery page.
|
||||
*
|
||||
* Every frame is produced by the app's own WebGL renderer with the preset's real
|
||||
* edits, so the gallery shows what Luminary actually does rather than a mock-up.
|
||||
* Black and white looks are documented with the contrast filter they carry, and
|
||||
* one stock is rendered through every colour filter the editor offers.
|
||||
*
|
||||
* node scripts/film-samples.mjs --photo sample.jpg
|
||||
* node scripts/film-samples.mjs --photo sample.jpg --out /tmp/film --per-category 2
|
||||
*
|
||||
* Output stays outside the checkout (default ~/.cache/luminary-film-gallery):
|
||||
*
|
||||
* <out>/original.jpg the untouched frame
|
||||
* <out>/<preset-id>.jpg one frame per sampled stock
|
||||
* <out>/<preset-id>--<filter>.jpg the black and white filter demo
|
||||
* <out>/film.html the gallery page
|
||||
* <out>/film-looks.json the catalogue data
|
||||
*
|
||||
* Copy the frames to the site's assets/film/ and film.html to the site root.
|
||||
* Needs Chrome/Chromium with WebGL2 (SwiftShader is used when there is no GPU).
|
||||
*/
|
||||
import { spawn } from 'node:child_process';
|
||||
import { existsSync } from 'node:fs';
|
||||
import { mkdir, readFile, rm, writeFile } from 'node:fs/promises';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import sharp from 'sharp';
|
||||
import { createServer } from 'vite';
|
||||
import { FILM_PRESETS } from '../src/lib/presets.ts';
|
||||
|
||||
// Filled from Vite's ssrLoadModule below: edits.ts imports './curves' without an
|
||||
// extension, which Node's own resolver cannot follow from a plain import here.
|
||||
let BW_FILTERS = [];
|
||||
|
||||
const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
|
||||
const DIR = path.join(ROOT, '.film-samples');
|
||||
const PAGE = path.join(DIR, 'index.html');
|
||||
const PORT = 5201;
|
||||
const RENDER_WIDTH = 1000;
|
||||
const RENDER_HEIGHT = 667;
|
||||
const JPEG_QUALITY = 84;
|
||||
|
||||
/** The stock used to show what each B&W contrast filter does. */
|
||||
const BW_DEMO_STOCK = 'film-tri-x-400';
|
||||
|
||||
const FILTER_HINTS = {
|
||||
none: 'No filter: the stock as it renders by default',
|
||||
yellow: 'Mild: slightly darker sky, natural skin',
|
||||
orange: 'Stronger: deeper sky, warmer skin separation',
|
||||
red: 'Dramatic: near-black sky, bright skin and foliage highlights',
|
||||
green: 'Lifts foliage, darkens lips and skin blemishes',
|
||||
blue: 'Lightens haze and shadow detail, darkens skin',
|
||||
};
|
||||
|
||||
const CATEGORY_ORDER = [
|
||||
'Colour Negative',
|
||||
'Colour Slide',
|
||||
'Black & White',
|
||||
'Cinema',
|
||||
'Instant',
|
||||
'Redscale',
|
||||
'Experimental',
|
||||
];
|
||||
|
||||
const CATEGORY_HINTS = {
|
||||
'Colour Negative':
|
||||
'C-41 print films: warm skin, open shadows and the colour people mean by "film".',
|
||||
'Colour Slide':
|
||||
'E-6 and K-14 reversal films: dense blacks, saturated colour and very little latitude.',
|
||||
'Black & White':
|
||||
'Panchromatic stocks and chromogenic B&W, each with its own grain, contrast and colour filter.',
|
||||
Cinema: 'Motion-picture negatives: flat midtones and soft shoulders, built to grade.',
|
||||
Instant: 'Integral and peel-apart instant film: lifted blacks, soft colour, gentle contrast.',
|
||||
Redscale: 'Film exposed through its base: amber highlights, red midtones, deep shadows.',
|
||||
Experimental:
|
||||
'Cross-process, faded print, infrared and other deliberate departures from a normal negative.',
|
||||
};
|
||||
|
||||
/** Three representative stocks per category: the ones people ask for by name. */
|
||||
const SAMPLE_PICKS = {
|
||||
'Colour Negative': ['film-portra-400', 'film-gold-200', 'film-ektar-100'],
|
||||
'Colour Slide': ['film-velvia-50', 'film-provia-100f', 'film-kodachrome-64'],
|
||||
'Black & White': ['film-tri-x-400', 'film-tmax-100', 'film-hp5-plus-400'],
|
||||
Cinema: ['film-cinestill-800t', 'film-vision3-250d', 'film-cinestill-50d'],
|
||||
Instant: ['film-polaroid-600', 'film-instax-mini', 'film-fp-100c'],
|
||||
Redscale: ['film-redscale-xr', 'film-redscale-deep', 'film-redscale-gold-200'],
|
||||
Experimental: ['film-lomochrome-purple', 'film-xpro-cross-process', 'film-aerochrome'],
|
||||
};
|
||||
|
||||
const HELP = `Luminary film gallery generator
|
||||
|
||||
Usage: node scripts/film-samples.mjs --photo <file> [options]
|
||||
|
||||
--photo <file> source frame (JPEG/PNG) to render every look onto
|
||||
--out <dir> output directory (default: <cache>/luminary-film-gallery)
|
||||
--per-category <n> sampled stocks per category (default: 3, max: all picks)
|
||||
--quality <1-100> JPEG quality for the frames (default: ${JPEG_QUALITY})
|
||||
--help print this text
|
||||
|
||||
Frames come from the app's own renderer in headless Chrome, so WebGL2 must work
|
||||
there (SwiftShader is fine). ${BW_DEMO_STOCK} is also rendered through every B&W
|
||||
colour filter. The repository is not modified; the temporary render page is
|
||||
deleted at the end.
|
||||
`;
|
||||
|
||||
const CHROME_CANDIDATES = [
|
||||
process.env.CHROME_PATH,
|
||||
'google-chrome',
|
||||
'google-chrome-stable',
|
||||
'chromium',
|
||||
'chromium-browser',
|
||||
].filter(Boolean);
|
||||
|
||||
function fail(message) {
|
||||
process.stderr.write(`film-samples: FAILED: ${message}\n`);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
function log(step, message) {
|
||||
process.stdout.write(`film-samples: ${step.padEnd(9)} ${message}\n`);
|
||||
}
|
||||
|
||||
function parseArgs(argv) {
|
||||
const options = {
|
||||
photo: null,
|
||||
out: path.join(process.env.XDG_CACHE_HOME || path.join(os.homedir(), '.cache'), 'luminary-film-gallery'),
|
||||
perCategory: 3,
|
||||
quality: JPEG_QUALITY,
|
||||
help: false,
|
||||
};
|
||||
const value = (index, flag) => {
|
||||
const next = argv[index + 1];
|
||||
if (!next || next.startsWith('--')) fail(`${flag} needs a value`);
|
||||
return next;
|
||||
};
|
||||
for (let i = 0; i < argv.length; i++) {
|
||||
const arg = argv[i];
|
||||
if (arg === '--photo') {
|
||||
options.photo = path.resolve(value(i, arg));
|
||||
i += 1;
|
||||
} else if (arg === '--out') {
|
||||
options.out = path.resolve(value(i, arg));
|
||||
i += 1;
|
||||
} else if (arg === '--per-category') {
|
||||
options.perCategory = Number(value(i, arg));
|
||||
i += 1;
|
||||
} else if (arg === '--quality') {
|
||||
options.quality = Number(value(i, arg));
|
||||
i += 1;
|
||||
} else if (arg === '--help' || arg === '-h') {
|
||||
options.help = true;
|
||||
} else {
|
||||
fail(`unknown option ${arg} (see --help)`);
|
||||
}
|
||||
}
|
||||
if (!Number.isInteger(options.perCategory) || options.perCategory < 1) {
|
||||
fail('--per-category must be a positive integer');
|
||||
}
|
||||
if (!Number.isInteger(options.quality) || options.quality < 1 || options.quality > 100) {
|
||||
fail('--quality must be 1-100');
|
||||
}
|
||||
if (!options.help && !options.photo) fail('--photo is required (see --help)');
|
||||
if (options.photo && !existsSync(options.photo)) fail(`photo not found: ${options.photo}`);
|
||||
return options;
|
||||
}
|
||||
|
||||
function sleep(ms) {
|
||||
return new Promise((resolve) => setTimeout(resolve, ms));
|
||||
}
|
||||
|
||||
function spawnSyncOk(bin) {
|
||||
const probe = spawn(bin, ['--version'], { stdio: 'ignore' });
|
||||
return new Promise((resolve) => {
|
||||
probe.on('error', () => resolve(false));
|
||||
probe.on('exit', (code) => resolve(code === 0));
|
||||
});
|
||||
}
|
||||
|
||||
async function findChrome() {
|
||||
for (const candidate of CHROME_CANDIDATES) {
|
||||
if (candidate.includes(path.sep)) {
|
||||
if (existsSync(candidate)) return candidate;
|
||||
continue;
|
||||
}
|
||||
if (await spawnSyncOk(candidate)) return candidate;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
const PAGE_HTML = `<!doctype html>
|
||||
<meta charset="utf-8" />
|
||||
<pre id="out">boot</pre>
|
||||
<script type="module">
|
||||
import { Renderer } from '/src/gl/renderer.ts';
|
||||
import { FILM_PRESETS } from '/src/lib/presets.ts';
|
||||
import { defaultEdits, normalizeEdits } from '/src/lib/edits.ts';
|
||||
|
||||
const pre = document.getElementById('out');
|
||||
try {
|
||||
const canvas = document.createElement('canvas');
|
||||
const renderer = new Renderer(canvas);
|
||||
const blob = await (await fetch('/.film-samples/photo.jpg')).blob();
|
||||
const bitmap = await createImageBitmap(blob, { imageOrientation: 'from-image' });
|
||||
renderer.setImage(bitmap, null);
|
||||
const size = { width: ${RENDER_WIDTH}, height: ${RENDER_HEIGHT} };
|
||||
|
||||
// filter is only used by the B&W strip: it overrides the stock's own filter.
|
||||
window.renderLook = async (id, filter) => {
|
||||
const preset = FILM_PRESETS.find((entry) => entry.id === id);
|
||||
const edits = preset
|
||||
? normalizeEdits(
|
||||
filter
|
||||
? { ...preset.edits, bw: true, bwFilter: filter, bwFilterAmount: 100 }
|
||||
: preset.edits,
|
||||
)
|
||||
: defaultEdits();
|
||||
renderer.render(edits, size);
|
||||
return canvas.toDataURL('image/jpeg', ${JPEG_QUALITY} / 100);
|
||||
};
|
||||
window.ready = true;
|
||||
pre.textContent = 'READY';
|
||||
} catch (error) {
|
||||
pre.textContent = 'ERROR ' + (error && error.message ? error.message : String(error));
|
||||
}
|
||||
</script>
|
||||
`;
|
||||
|
||||
async function drive(chromeBin, url, jobs, outDir, quality) {
|
||||
const port = 9333;
|
||||
const child = spawn(
|
||||
chromeBin,
|
||||
[
|
||||
'--headless=new',
|
||||
'--no-sandbox',
|
||||
'--disable-gpu-sandbox',
|
||||
'--use-gl=angle',
|
||||
'--use-angle=swiftshader',
|
||||
'--enable-unsafe-swiftshader',
|
||||
`--remote-debugging-port=${port}`,
|
||||
`--user-data-dir=${path.join(DIR, 'profile')}`,
|
||||
'about:blank',
|
||||
],
|
||||
{ stdio: 'ignore' },
|
||||
);
|
||||
|
||||
try {
|
||||
let target = null;
|
||||
for (let i = 0; i < 120 && !target; i++) {
|
||||
try {
|
||||
const res = await fetch(`http://127.0.0.1:${port}/json/list`);
|
||||
target = (await res.json()).find((t) => t.type === 'page') ?? null;
|
||||
} catch {
|
||||
/* devtools not up yet */
|
||||
}
|
||||
if (!target) await sleep(250);
|
||||
}
|
||||
if (!target) throw new Error('Chrome DevTools endpoint never came up');
|
||||
|
||||
const ws = new WebSocket(target.webSocketDebuggerUrl);
|
||||
await new Promise((resolve, reject) => {
|
||||
ws.onopen = resolve;
|
||||
ws.onerror = () => reject(new Error('DevTools websocket failed'));
|
||||
});
|
||||
let nextId = 1;
|
||||
const pending = new Map();
|
||||
ws.onmessage = (event) => {
|
||||
const message = JSON.parse(event.data);
|
||||
if (message.id && pending.has(message.id)) {
|
||||
pending.get(message.id)(message);
|
||||
pending.delete(message.id);
|
||||
}
|
||||
};
|
||||
const send = (method, params = {}) => {
|
||||
const id = nextId++;
|
||||
return new Promise((resolve) => {
|
||||
pending.set(id, resolve);
|
||||
ws.send(JSON.stringify({ id, method, params }));
|
||||
});
|
||||
};
|
||||
const evaluate = async (expression, awaitPromise = false) => {
|
||||
const response = await send('Runtime.evaluate', {
|
||||
expression,
|
||||
awaitPromise,
|
||||
returnByValue: true,
|
||||
});
|
||||
if (response.result?.exceptionDetails) {
|
||||
throw new Error(
|
||||
response.result.exceptionDetails.exception?.description ??
|
||||
response.result.exceptionDetails.text,
|
||||
);
|
||||
}
|
||||
return response.result?.result?.value;
|
||||
};
|
||||
|
||||
await send('Page.enable');
|
||||
await send('Runtime.enable');
|
||||
await send('Page.navigate', { url });
|
||||
|
||||
const deadline = Date.now() + 120000;
|
||||
let status = '';
|
||||
while (Date.now() < deadline) {
|
||||
status = (await evaluate("document.getElementById('out')?.textContent ?? ''")) ?? '';
|
||||
if (status.startsWith('READY') || status.startsWith('ERROR')) break;
|
||||
await sleep(400);
|
||||
}
|
||||
if (status.startsWith('ERROR')) throw new Error(status.slice(6));
|
||||
if (!status.startsWith('READY')) throw new Error('the render page never became ready');
|
||||
|
||||
const written = [];
|
||||
for (const job of jobs) {
|
||||
const dataUrl = await evaluate(
|
||||
`window.renderLook(${JSON.stringify(job.id)}, ${JSON.stringify(job.filter ?? null)})`,
|
||||
true,
|
||||
);
|
||||
if (typeof dataUrl !== 'string' || !dataUrl.startsWith('data:image/jpeg;base64,')) {
|
||||
throw new Error(`renderer returned no JPEG for ${job.file}`);
|
||||
}
|
||||
const buffer = Buffer.from(dataUrl.slice('data:image/jpeg;base64,'.length), 'base64');
|
||||
const file = path.join(outDir, job.file);
|
||||
// Re-encode so the frames carry consistent metadata and no EXIF bloat.
|
||||
await sharp(buffer).jpeg({ quality, mozjpeg: true }).toFile(file);
|
||||
log('render', `${job.file} (${(buffer.length / 1024).toFixed(0)} KB)`);
|
||||
written.push(job.file);
|
||||
}
|
||||
ws.close();
|
||||
return written;
|
||||
} finally {
|
||||
child.kill('SIGKILL');
|
||||
await sleep(400);
|
||||
}
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ page ---- */
|
||||
|
||||
function escapeHtml(value) {
|
||||
return String(value)
|
||||
.replace(/&/g, '&')
|
||||
.replace(/</g, '<')
|
||||
.replace(/>/g, '>')
|
||||
.replace(/"/g, '"');
|
||||
}
|
||||
|
||||
function slug(category) {
|
||||
return category
|
||||
.toLowerCase()
|
||||
.replace(/&/g, 'and')
|
||||
.replace(/[^a-z0-9]+/g, '-')
|
||||
.replace(/(^-|-$)/g, '');
|
||||
}
|
||||
|
||||
function filterLabel(id) {
|
||||
return BW_FILTERS.find((filter) => filter.id === id)?.label ?? null;
|
||||
}
|
||||
|
||||
function buildFilterDemo(catalogue) {
|
||||
const group = catalogue.find((entry) => entry.category === 'Black & White');
|
||||
if (!group) return '';
|
||||
const withFilter = group.looks.filter((look) => look.filter && look.filter !== 'none').length;
|
||||
const figures = BW_FILTERS.map(
|
||||
(filter) => `<figure>
|
||||
<img src="assets/film/${BW_DEMO_STOCK}--${filter.id}.jpg" width="${RENDER_WIDTH}" height="${RENDER_HEIGHT}" loading="lazy" alt="${escapeHtml(
|
||||
filter.label,
|
||||
)} filter on ${escapeHtml(group.looks.find((look) => look.id === BW_DEMO_STOCK)?.name ?? 'a black and white film')}">
|
||||
<figcaption>${escapeHtml(filter.label)}</figcaption>
|
||||
<p>${escapeHtml(FILTER_HINTS[filter.id] ?? '')}</p>
|
||||
</figure>`,
|
||||
).join('\n ');
|
||||
|
||||
return ` <div class="film-filter-demo">
|
||||
<h3>Colour filters, the way they were used on the lens</h3>
|
||||
<p class="film-filter-lede">
|
||||
Before digital, contrast in black and white came from screwing a coloured filter onto
|
||||
the lens: it held back its own colour, so a red filter turned a blue sky nearly black
|
||||
while leaving skin bright, and a green one lifted foliage. Each monochrome look here
|
||||
records the filter it was built with, and ${withFilter} of the ${group.looks.length}
|
||||
name one. The same Tri-X 400 frame through every filter:
|
||||
</p>
|
||||
<div class="film-filters">
|
||||
${figures}
|
||||
</div>
|
||||
<p class="fineprint">Filter strength is adjustable in the editor, so a look can be dialled back from the full strength shown here.</p>
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
|
||||
function buildPage(catalogue, framesByCategory) {
|
||||
const total = catalogue.reduce((sum, group) => sum + group.looks.length, 0);
|
||||
const chips = catalogue
|
||||
.map(
|
||||
(group) =>
|
||||
`<a href="#${slug(group.category)}">${escapeHtml(group.category)} <span>${group.looks.length}</span></a>`,
|
||||
)
|
||||
.join('\n ');
|
||||
|
||||
const sections = catalogue
|
||||
.map((group) => {
|
||||
const frames = framesByCategory[group.category] ?? [];
|
||||
const figures = frames
|
||||
.map(
|
||||
(frame) => `<figure class="film-set">
|
||||
<img src="assets/film/${frame.id}.jpg" width="${RENDER_WIDTH}" height="${RENDER_HEIGHT}" loading="lazy" alt="${escapeHtml(frame.name)} applied to the sample photograph">
|
||||
<figcaption>${escapeHtml(frame.name)}${frame.iso ? ` · ISO ${frame.iso}` : ''}${
|
||||
frame.process ? ` · ${escapeHtml(frame.process)}` : ''
|
||||
}</figcaption>
|
||||
</figure>`,
|
||||
)
|
||||
.join('\n ');
|
||||
|
||||
const looks = group.looks
|
||||
.map(
|
||||
(look) => `<li>
|
||||
<span class="film-name">${escapeHtml(look.name)}</span>
|
||||
<span class="film-meta">${[
|
||||
look.iso ? `ISO ${look.iso}` : '',
|
||||
look.process ?? '',
|
||||
look.filter && look.filter !== 'none' ? `${filterLabel(look.filter)} filter` : '',
|
||||
]
|
||||
.filter(Boolean)
|
||||
.join(' · ')}</span>
|
||||
${look.note ? `<span class="film-note">${escapeHtml(look.note)}</span>` : ''}
|
||||
</li>`,
|
||||
)
|
||||
.join('\n ');
|
||||
|
||||
return ` <section class="section${group.index % 2 === 1 ? ' section-alt' : ''}" id="${slug(group.category)}">
|
||||
<div class="wrap">
|
||||
<div class="section-head">
|
||||
<p class="kicker">${escapeHtml(group.category)} · ${group.looks.length} looks</p>
|
||||
<h2>${escapeHtml(group.category)}</h2>
|
||||
<p class="section-lede">${escapeHtml(CATEGORY_HINTS[group.category] ?? '')}</p>
|
||||
</div>
|
||||
${group.category === 'Black & White' ? buildFilterDemo(catalogue) : ''} <div class="film-sets">
|
||||
${figures}
|
||||
</div>
|
||||
<ul class="film-looks">
|
||||
${looks}
|
||||
</ul>
|
||||
</div>
|
||||
</section>`;
|
||||
})
|
||||
.join('\n\n');
|
||||
|
||||
return `<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<title>Luminary film looks: ${total} documented film emulations</title>
|
||||
<meta name="description" content="The full Luminary film pack: ${total} film looks by category, each with the stock, ISO, process and a note on the look, rendered on one frame by Luminary's own editor. Black and white looks also record their contrast filter.">
|
||||
<meta name="theme-color" content="#0c0e11">
|
||||
<meta property="og:title" content="Luminary film looks: ${total} documented emulations">
|
||||
<meta property="og:description" content="Colour negative, slide, black and white, cinema, instant, redscale and experimental looks, with frames rendered by the editor itself and the B&W contrast filters shown side by side.">
|
||||
<meta property="og:type" content="website">
|
||||
<meta property="og:image" content="assets/film/film-portra-400.jpg">
|
||||
<link rel="icon" href="assets/favicon.png" type="image/png">
|
||||
<link rel="apple-touch-icon" href="assets/icon-256.png">
|
||||
<link rel="stylesheet" href="styles.css?v=20261128g">
|
||||
</head>
|
||||
<body>
|
||||
<a class="skip" href="#main">Skip to content</a>
|
||||
|
||||
<header class="site-header">
|
||||
<div class="wrap header-inner">
|
||||
<a class="brand" href="index.html" aria-label="Luminary home">
|
||||
<span class="brand-mark"><img src="assets/icon-256.png" alt="" width="36" height="36"></span>
|
||||
<span class="brand-name">Luminary</span>
|
||||
</a>
|
||||
<nav class="nav" aria-label="Main">
|
||||
<a href="index.html#develop">Raw editing</a>
|
||||
<a href="film.html">Film looks</a>
|
||||
<a href="index.html#library">Organise</a>
|
||||
<a href="index.html#proofing">Galleries</a>
|
||||
<a href="index.html#downloads">Download</a>
|
||||
</nav>
|
||||
<div class="header-actions">
|
||||
<details class="mobile-nav">
|
||||
<summary>Menu</summary>
|
||||
<nav class="mobile-menu" aria-label="Sections">
|
||||
<a href="index.html#develop">Raw editing</a>
|
||||
<a href="film.html">Film looks</a>
|
||||
<a href="index.html#library">Organise</a>
|
||||
<a href="index.html#proofing">Galleries</a>
|
||||
<a href="index.html#downloads">Download</a>
|
||||
<a href="index.html#install">Install</a>
|
||||
</nav>
|
||||
</details>
|
||||
<a class="btn btn-primary btn-small" href="index.html#downloads">Download</a>
|
||||
</div>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<main id="main">
|
||||
<section class="hero film-hero" id="top">
|
||||
<div class="wrap">
|
||||
<p class="eyebrow"><span class="dot"></span> Film pack · ${total} looks</p>
|
||||
<h1>${total} film looks.<br><em>One frame, one engine.</em></h1>
|
||||
<p class="lede">
|
||||
Every frame below was rendered by Luminary's own editor with the look applied to the
|
||||
same photograph — no screenshots from another app, no pasted LUTs. Each entry lists
|
||||
the stock it emulates, its ISO and process, and a note on what it does.
|
||||
</p>
|
||||
<div class="film-cats" aria-label="Categories">
|
||||
${chips}
|
||||
</div>
|
||||
<p class="fineprint">Sample frame: a digital photograph, unedited, rendered at ${RENDER_WIDTH}×${RENDER_HEIGHT}. Grain and colour come from the look itself.</p>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section class="section" id="sample">
|
||||
<div class="wrap">
|
||||
<figure class="film-original">
|
||||
<img src="assets/film/original.jpg" width="${RENDER_WIDTH}" height="${RENDER_HEIGHT}" alt="The sample photograph with no film look applied">
|
||||
<figcaption>The starting frame: no look, no crop, no colour work.</figcaption>
|
||||
</figure>
|
||||
<p class="fineprint">
|
||||
The black and white section also shows the colour-filter technique: the same stock
|
||||
rendered through yellow, orange, red, green and blue filters, the way contrast was
|
||||
shaped on film before digital.
|
||||
</p>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
${sections}
|
||||
</main>
|
||||
|
||||
<footer class="site-footer">
|
||||
<div class="wrap footer-inner">
|
||||
<div class="footer-brand">
|
||||
<span class="brand-mark small"><img src="assets/icon-256.png" alt="" width="28" height="28"></span>
|
||||
<div>
|
||||
<p class="footer-name">Luminary</p>
|
||||
<p class="footer-note">A photo library and raw editor for people who'd rather own their photos. MIT licensed. © 2026 Brian Hursey.</p>
|
||||
</div>
|
||||
</div>
|
||||
<nav class="footer-links" aria-label="Footer">
|
||||
<a href="index.html">Product page</a>
|
||||
<a href="index.html#downloads">Download</a>
|
||||
<a href="index.html#changelog">Changelog</a>
|
||||
<a href="https://git.maple-street.net/bhursey/luminary" target="_blank" rel="noopener">Source</a>
|
||||
<a href="mailto:bhursey@gmail.com?subject=Luminary%20film%20looks">Feedback</a>
|
||||
</nav>
|
||||
</div>
|
||||
</footer>
|
||||
</body>
|
||||
</html>
|
||||
`;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ main ---- */
|
||||
|
||||
function filterDemoJobs() {
|
||||
return BW_FILTERS.map((filter) => ({
|
||||
id: BW_DEMO_STOCK,
|
||||
filter: filter.id,
|
||||
file: `${BW_DEMO_STOCK}--${filter.id}.jpg`,
|
||||
}));
|
||||
}
|
||||
|
||||
async function main() {
|
||||
const options = parseArgs(process.argv.slice(2));
|
||||
if (options.help) {
|
||||
process.stdout.write(HELP);
|
||||
return 0;
|
||||
}
|
||||
|
||||
const chromeBin = await findChrome();
|
||||
if (!chromeBin) {
|
||||
fail('no Chrome/Chromium found; set CHROME_PATH or install one (WebGL2 is required)');
|
||||
}
|
||||
|
||||
const categories = CATEGORY_ORDER.filter((category) =>
|
||||
FILM_PRESETS.some((preset) => preset.category === category),
|
||||
);
|
||||
const catalogue = categories.map((category, index) => ({
|
||||
category,
|
||||
index,
|
||||
looks: FILM_PRESETS.filter((preset) => preset.category === category).map((preset) => ({
|
||||
id: preset.id,
|
||||
name: preset.name,
|
||||
iso: preset.film?.speed ?? null,
|
||||
process: preset.film?.process ?? null,
|
||||
filter: preset.edits.bw ? preset.edits.bwFilter ?? 'none' : null,
|
||||
note: preset.description ?? null,
|
||||
})),
|
||||
}));
|
||||
|
||||
const framesByCategory = {};
|
||||
const jobs = [{ id: 'original', file: 'original.jpg' }];
|
||||
for (const group of catalogue) {
|
||||
const picks = (SAMPLE_PICKS[group.category] ?? [])
|
||||
.filter((id) => group.looks.some((look) => look.id === id))
|
||||
.slice(0, options.perCategory);
|
||||
framesByCategory[group.category] = picks.map((id) => {
|
||||
const look = group.looks.find((entry) => entry.id === id);
|
||||
return { id, name: look.name, iso: look.iso, process: look.process };
|
||||
});
|
||||
for (const id of picks) jobs.push({ id, file: `${id}.jpg` });
|
||||
}
|
||||
|
||||
await mkdir(options.out, { recursive: true });
|
||||
await rm(DIR, { recursive: true, force: true });
|
||||
await mkdir(DIR, { recursive: true });
|
||||
|
||||
// A 3:2 frame keeps every look comparable; the page states the source size.
|
||||
await sharp(options.photo)
|
||||
.rotate()
|
||||
.resize(RENDER_WIDTH, RENDER_HEIGHT, { fit: 'cover', position: 'centre' })
|
||||
.jpeg({ quality: 95, chromaSubsampling: '4:4:4' })
|
||||
.toFile(path.join(DIR, 'photo.jpg'));
|
||||
|
||||
const server = await createServer({
|
||||
root: ROOT,
|
||||
logLevel: 'error',
|
||||
server: { host: '127.0.0.1', port: PORT, strictPort: false },
|
||||
});
|
||||
await server.listen();
|
||||
const base = (server.resolvedUrls?.local?.[0] ?? `http://127.0.0.1:${PORT}/`).replace(/\/$/, '');
|
||||
// The editor's own filter list, so the page cannot drift from the app.
|
||||
BW_FILTERS = (await server.ssrLoadModule('/src/lib/edits.ts')).BW_FILTERS;
|
||||
jobs.push(...filterDemoJobs());
|
||||
await writeFile(PAGE, PAGE_HTML);
|
||||
|
||||
log('photo', `${path.relative(process.cwd(), options.photo)} → ${RENDER_WIDTH}×${RENDER_HEIGHT}`);
|
||||
log('render', `${jobs.length} frames through the editor's renderer`);
|
||||
|
||||
let written;
|
||||
try {
|
||||
written = await drive(chromeBin, `${base}/.film-samples/`, jobs, options.out, options.quality);
|
||||
} finally {
|
||||
await server.close();
|
||||
await rm(DIR, { recursive: true, force: true, maxRetries: 10, retryDelay: 200 }).catch(() => {});
|
||||
}
|
||||
if (written.length !== jobs.length) fail(`only ${written.length} of ${jobs.length} frames rendered`);
|
||||
|
||||
await writeFile(
|
||||
path.join(options.out, 'film-looks.json'),
|
||||
`${JSON.stringify({ total: FILM_PRESETS.length, categories: catalogue }, null, 2)}\n`,
|
||||
);
|
||||
await writeFile(path.join(options.out, 'film.html'), buildPage(catalogue, framesByCategory));
|
||||
|
||||
const bytes = (
|
||||
await Promise.all(written.map((file) => readFile(path.join(options.out, file))))
|
||||
).reduce((sum, buffer) => sum + buffer.length, 0);
|
||||
|
||||
process.stdout.write(
|
||||
[
|
||||
'',
|
||||
'film gallery PASSED',
|
||||
` frames ${written.length} JPEGs, ${(bytes / 1024 / 1024).toFixed(1)} MB`,
|
||||
` looks ${FILM_PRESETS.length} across ${catalogue.length} categories`,
|
||||
` filters ${BW_FILTERS.length} on ${BW_DEMO_STOCK}`,
|
||||
` page ${path.join(options.out, 'film.html')}`,
|
||||
` data ${path.join(options.out, 'film-looks.json')}`,
|
||||
'',
|
||||
'Copy the frames to assets/film/ and film.html to the site root.',
|
||||
'',
|
||||
].join('\n'),
|
||||
);
|
||||
return 0;
|
||||
}
|
||||
|
||||
main().then(
|
||||
(code) => {
|
||||
process.exitCode = code;
|
||||
},
|
||||
(error) => {
|
||||
fail(error instanceof Error ? error.message : String(error));
|
||||
},
|
||||
);
|
||||
@@ -0,0 +1,93 @@
|
||||
/**
|
||||
* Writes `.br` and `.gz` copies of the text assets next to the built files.
|
||||
*
|
||||
* The server serves those directly when a browser offers an encoding, so no
|
||||
* request ever pays for compression: `index-*.js` is ~780 kB raw and ~240 kB
|
||||
* gzipped, which is the difference between a slow and a normal first load.
|
||||
* Images and fonts are already compressed and are left alone.
|
||||
*/
|
||||
|
||||
import fs from 'node:fs';
|
||||
import fsp from 'node:fs/promises';
|
||||
import path from 'node:path';
|
||||
import zlib from 'node:zlib';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
|
||||
const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
|
||||
const DIST = path.join(ROOT, 'dist');
|
||||
const MIN_BYTES = 1024;
|
||||
const COMPRESSIBLE = new Set(['.html', '.js', '.mjs', '.css', '.svg', '.json', '.map', '.txt', '.xml', '.webmanifest']);
|
||||
|
||||
const brotliOptions = {
|
||||
params: {
|
||||
[zlib.constants.BROTLI_PARAM_QUALITY]: 11,
|
||||
[zlib.constants.BROTLI_PARAM_SIZE_HINT]: 0,
|
||||
},
|
||||
};
|
||||
|
||||
async function* walk(dir) {
|
||||
for (const entry of await fsp.readdir(dir, { withFileTypes: true })) {
|
||||
const full = path.join(dir, entry.name);
|
||||
if (entry.isDirectory()) yield* walk(full);
|
||||
else if (entry.isFile()) yield full;
|
||||
}
|
||||
}
|
||||
|
||||
function isStale(source, target) {
|
||||
try {
|
||||
const out = fs.statSync(target);
|
||||
return out.mtimeMs < fs.statSync(source).mtimeMs;
|
||||
} catch {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
async function compressFile(file, totals) {
|
||||
const ext = path.extname(file).toLowerCase();
|
||||
if (!COMPRESSIBLE.has(ext)) return 0;
|
||||
const stat = await fsp.stat(file);
|
||||
if (stat.size < MIN_BYTES) return 0;
|
||||
|
||||
const raw = await fsp.readFile(file);
|
||||
let files = 0;
|
||||
|
||||
for (const variant of ['gz', 'br']) {
|
||||
const target = `${file}.${variant}`;
|
||||
if (!isStale(file, target)) continue;
|
||||
const body =
|
||||
variant === 'gz'
|
||||
? zlib.gzipSync(raw, { level: 9 })
|
||||
: zlib.brotliCompressSync(raw, {
|
||||
...brotliOptions,
|
||||
params: {
|
||||
...brotliOptions.params,
|
||||
[zlib.constants.BROTLI_PARAM_SIZE_HINT]: raw.length,
|
||||
},
|
||||
});
|
||||
// A "compressed" file that is larger than the original is never served.
|
||||
if (body.length >= raw.length) {
|
||||
await fsp.rm(target, { force: true });
|
||||
continue;
|
||||
}
|
||||
await fsp.writeFile(target, body);
|
||||
files += 1;
|
||||
totals[variant] += raw.length - body.length;
|
||||
}
|
||||
return files;
|
||||
}
|
||||
|
||||
if (!fs.existsSync(DIST)) {
|
||||
console.error('precompress: dist/ is missing — run "vite build" first');
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
const totals = { gz: 0, br: 0 };
|
||||
let files = 0;
|
||||
for await (const file of walk(DIST)) {
|
||||
files += await compressFile(file, totals);
|
||||
}
|
||||
|
||||
const kb = (bytes) => `${Math.round(bytes / 1024)} kB`;
|
||||
console.log(
|
||||
`precompress: wrote ${files} variant(s); a full load saves ${kb(totals.gz)} with gzip or ${kb(totals.br)} with brotli`,
|
||||
);
|
||||
@@ -27,6 +27,16 @@ export const HOST = process.env.HOST || '0.0.0.0';
|
||||
/** Shared invite code required to register after the first account exists. */
|
||||
export const INVITE = setting('INVITE');
|
||||
|
||||
/**
|
||||
* Single-user desktop mode, set by the Windows launcher (LUMINARY_LOCAL=1).
|
||||
* The server creates one admin account and treats an unauthenticated request as
|
||||
* that account, so a personal install never shows a signup or sign-in screen.
|
||||
* Only safe on loopback, which is where the launcher binds; the server warns if
|
||||
* it is enabled with a reachable HOST.
|
||||
*/
|
||||
export const LOCAL_MODE = setting('LOCAL') === '1';
|
||||
export const LOCAL_EMAIL = setting('LOCAL_EMAIL', 'local@luminary');
|
||||
|
||||
/** Base URL of the dashboard this editor is bridged to, e.g. http://hub:3000. */
|
||||
export const GLENLOCH_URL = (process.env.GLENLOCH_URL || '').replace(/\/+$/, '');
|
||||
|
||||
|
||||
@@ -10,10 +10,10 @@ import { parentPort, workerData } from 'node:worker_threads';
|
||||
import fs from 'node:fs/promises';
|
||||
import sharp from 'sharp';
|
||||
import { denoiseRgb } from './denoise/rgbPipeline.ts';
|
||||
import { guidedDenoiser } from './denoise/standin.ts';
|
||||
import { createBaseDenoiser } from './denoise/baseDenoiser.ts';
|
||||
|
||||
try {
|
||||
const { sourcePath, outPath } = workerData;
|
||||
const { sourcePath, outPath, base = 'guided' } = workerData;
|
||||
const buffer = await fs.readFile(sourcePath);
|
||||
const { data, info } = await sharp(buffer)
|
||||
.rotate()
|
||||
@@ -37,8 +37,21 @@ try {
|
||||
|
||||
const started = performance.now();
|
||||
// Always full strength: the Amount slider blends on the client, so one render
|
||||
// serves every setting and the cache key does not move with the slider.
|
||||
const out = await denoiseRgb({ rgb, width, height }, { amount: 1 }, guidedDenoiser());
|
||||
// serves every setting and the cache key does not move with the slider. The
|
||||
// base denoiser (guided / nlm / scunet) is chosen by the request; the cache
|
||||
// key already folds it in, so a different model is a different render.
|
||||
//
|
||||
// Progress is the only window the panel has into a 95 s SCUNet run, so both
|
||||
// the stage boundaries and the tile counter are forwarded to the job.
|
||||
const report = (progress) => parentPort?.postMessage({ type: 'progress', progress });
|
||||
const out = await denoiseRgb(
|
||||
{ rgb, width, height },
|
||||
{ amount: 1 },
|
||||
createBaseDenoiser(base, (tiles) =>
|
||||
report({ stage: 'base', done: tiles.done, total: tiles.total }),
|
||||
),
|
||||
(stage) => report({ stage }),
|
||||
);
|
||||
// 4:4:4 so the chroma work is not immediately thrown away by the encoder.
|
||||
const jpeg = await sharp(Buffer.from(out.rgb), { raw: { width, height, channels: 3 } })
|
||||
.jpeg({ quality: 95, chromaSubsampling: '4:4:4' })
|
||||
|
||||
@@ -1,11 +1,13 @@
|
||||
/**
|
||||
* Job runner for the detail-preserving denoise.
|
||||
*
|
||||
* `server/denoise/` is a verbatim copy of the dependency-free pipeline from the
|
||||
* raw-noise package. It reconstructs from a per-pixel crossfade between the
|
||||
* source and a denoised base, so the result is bounded by the original pixels and
|
||||
* cannot ring or overshoot; flat noise is replaced, structure is given back
|
||||
* verbatim. The GPU's own `noise` sliders are a separate, much simpler path.
|
||||
* `server/denoise/` starts from the dependency-free pipeline of the raw-noise
|
||||
* package, which supplies the Guided and NLM bases; SCUNet runs the same stages
|
||||
* around an ONNX model. Every base is reconstructed from a per-pixel crossfade
|
||||
* between the source and the denoised base, so the result is bounded by the
|
||||
* original pixels and cannot ring or overshoot; flat noise is replaced, structure
|
||||
* is given back verbatim. The GPU's own `noise` sliders are a separate, much
|
||||
* simpler path.
|
||||
*
|
||||
* Three things here are deliberate:
|
||||
*
|
||||
@@ -33,6 +35,9 @@ export function clearDenoised(photoId) {
|
||||
return removeDenoised(photoId);
|
||||
}
|
||||
|
||||
/** Every base the picker offers; the cache keeps one render for each of them. */
|
||||
export const DENOISE_BASES = ['guided', 'scunet', 'nlm'];
|
||||
|
||||
/**
|
||||
* Bump whenever the copied modules under `server/denoise/` change output. The key
|
||||
* is the only thing between a fixed pipeline and a stale cached file.
|
||||
@@ -59,23 +64,23 @@ export function getDenoiseJob(id) {
|
||||
return jobs.get(id) ?? null;
|
||||
}
|
||||
|
||||
/** Stable for a photo and a pipeline version -- Amount is the client's business. */
|
||||
export function denoiseKey(photoId) {
|
||||
/** Stable for a photo, a pipeline version and a base denoiser -- Amount is the client's business. */
|
||||
export function denoiseKey(photoId, base = 'guided') {
|
||||
return crypto
|
||||
.createHash('sha1')
|
||||
.update(`${photoId}|${PIPELINE_VERSION}`)
|
||||
.update(`${photoId}|${PIPELINE_VERSION}|${base}`)
|
||||
.digest('hex')
|
||||
.slice(0, 12);
|
||||
}
|
||||
|
||||
export function startDenoise({ photoId, sourcePath }) {
|
||||
const key = denoiseKey(photoId);
|
||||
export function startDenoise({ photoId, sourcePath, base = 'guided' }) {
|
||||
const key = denoiseKey(photoId, base);
|
||||
|
||||
const joined = byKey.get(key);
|
||||
if (joined) return joined;
|
||||
|
||||
const url = `/api/photos/${encodeURIComponent(photoId)}/denoised?v=${key}`;
|
||||
const job = { id: crypto.randomUUID(), photoId, key, state: 'running', startedAt: Date.now() };
|
||||
const job = { id: crypto.randomUUID(), photoId, key, base, state: 'running', startedAt: Date.now() };
|
||||
|
||||
// Re-running after the edit was cleared, or a second browser, should not pay
|
||||
// for the CPU again. The file is the cache; the job just reports it.
|
||||
@@ -108,19 +113,26 @@ function run(job) {
|
||||
active += 1;
|
||||
const outPath = denoisedPath(job.photoId, job.key);
|
||||
const worker = new Worker(new URL('./denoise-worker.mjs', import.meta.url), {
|
||||
workerData: { sourcePath: job.sourcePath, outPath },
|
||||
workerData: { sourcePath: job.sourcePath, outPath, base: job.base },
|
||||
});
|
||||
|
||||
worker.on('message', (message) => {
|
||||
if (message?.type === 'done') {
|
||||
if (message?.type === 'progress') {
|
||||
job.progress = message.progress;
|
||||
} else if (message?.type === 'done') {
|
||||
job.state = 'done';
|
||||
job.progress = null;
|
||||
job.ms = message.ms;
|
||||
job.bytes = message.bytes;
|
||||
job.stats = message.stats;
|
||||
// A version bump (or an older build) leaves its render behind; keep the
|
||||
// current one and drop the rest so the folder cannot grow without bound.
|
||||
// A version bump (or an older build) leaves its render behind. Keep the
|
||||
// current key of every base and drop only the older ones, so switching
|
||||
// models reuses its cached render instead of paying for the CPU again.
|
||||
try {
|
||||
removeDenoised(job.photoId, job.key);
|
||||
removeDenoised(
|
||||
job.photoId,
|
||||
DENOISE_BASES.map((base) => denoiseKey(job.photoId, base)),
|
||||
);
|
||||
} catch {
|
||||
/* cleanup is best effort -- never fail a finished job over it */
|
||||
}
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
/**
|
||||
* Resolve a base denoiser by name -- the slot the pipeline calls as `runBase`.
|
||||
*
|
||||
* Three choices, all occupying the same interface from `standin.ts`:
|
||||
*
|
||||
* - `guided` (default): the classical guided filter. Fast, edge-preserving,
|
||||
* the current shipping path.
|
||||
* - `nlm`: non-local means. Slower, the quality reference the model must beat.
|
||||
* - `scunet`: the learned SCUNet model, run tiled with overlap-add.
|
||||
*
|
||||
* Constructing is free: the ONNX session is created lazily on first use, so the
|
||||
* model selector can show all three even before a run ever picks SCUNet. A
|
||||
* missing model surfaces as a clear error at run time, not at import time.
|
||||
*/
|
||||
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { guidedDenoiser, nlmDenoiser, type BaseDenoiser } from './standin.ts';
|
||||
import { createOnnxBaseDenoiser, type TileProgress } from './onnx.ts';
|
||||
|
||||
export type BaseDenoiserName = 'guided' | 'nlm' | 'scunet';
|
||||
|
||||
/** The SCUNet weights shipped with the server, next to this file. */
|
||||
const SCUNET_MODEL = fileURLToPath(new URL('./scunet_color_25.onnx', import.meta.url));
|
||||
|
||||
export function createBaseDenoiser(
|
||||
base: BaseDenoiserName,
|
||||
onProgress?: (progress: TileProgress) => void,
|
||||
): BaseDenoiser {
|
||||
switch (base) {
|
||||
case 'nlm':
|
||||
return nlmDenoiser();
|
||||
case 'scunet':
|
||||
return createOnnxBaseDenoiser({ modelPath: SCUNET_MODEL, tile: 256, overlap: 32, onProgress });
|
||||
case 'guided':
|
||||
default:
|
||||
return guidedDenoiser();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,205 @@
|
||||
/**
|
||||
* Tiled ONNX inference for the base plane -- the SCUNet path.
|
||||
*
|
||||
* This is the only file that may import `onnxruntime-node`, and it imports it
|
||||
* lazily: nothing here requires a model to exist until a denoiser is actually
|
||||
* asked to run. The classical stand-ins (`guided`, `nlm`) occupy the same slot
|
||||
* and need no model at all, so the model selector is safe to show even before a
|
||||
* run ever selects SCUNet.
|
||||
*
|
||||
* The model contract is fixed and small:
|
||||
*
|
||||
* input 1 x 3 x TILE x TILE float32, RGB in 0..1
|
||||
* output 1 x 3 x TILE x TILE float32, same
|
||||
*
|
||||
* `runTiled` is separated from the session so the tiling, padding, feathering
|
||||
* and normalisation can be reasoned about independently of ORT.
|
||||
*/
|
||||
|
||||
import type { BaseDenoiser, BaseImage } from './standin.ts';
|
||||
|
||||
/** Runs one `tile x tile`, 3-channel tile. Input and output are interleaved RGB. */
|
||||
export type RgbTileRunner = (input: Float32Array, tile: number) => Promise<Float32Array>;
|
||||
|
||||
export interface TileProgress {
|
||||
done: number;
|
||||
total: number;
|
||||
}
|
||||
|
||||
export interface OnnxBaseOptions {
|
||||
modelPath: string;
|
||||
/** Fixed square size the graph was exported at. Must match the graph. */
|
||||
tile?: number;
|
||||
/** Overlap in pixels between neighbouring tiles. */
|
||||
overlap?: number;
|
||||
/** Defaults to physical cores. Keep it below the host's raw decode pool. */
|
||||
intraOpThreads?: number;
|
||||
/** Called after each tile lands, so a long run can report where it is. */
|
||||
onProgress?: (progress: TileProgress) => void;
|
||||
}
|
||||
|
||||
/**
|
||||
* Raised-cosine feather along one axis, floored so no pixel is weighted zero.
|
||||
*
|
||||
* The floor matters: at the image border a tile is the only contributor, and a
|
||||
* zero weight there would divide 0 by 0.
|
||||
*/
|
||||
export function featherWeights(tile: number, overlap: number): Float32Array {
|
||||
const weights = new Float32Array(tile).fill(1);
|
||||
const edge = Math.min(Math.max(0, overlap), Math.floor(tile / 2));
|
||||
for (let i = 0; i < edge; i++) {
|
||||
const t = (i + 0.5) / edge;
|
||||
weights[i] = Math.max(0.5 - 0.5 * Math.cos(Math.PI * t), 1e-3);
|
||||
weights[tile - 1 - i] = weights[i];
|
||||
}
|
||||
return weights;
|
||||
}
|
||||
|
||||
/** Tiled inference with overlap-add and feathering. */
|
||||
export async function runTiled(
|
||||
runTile: RgbTileRunner,
|
||||
image: BaseImage,
|
||||
tile: number,
|
||||
overlap: number,
|
||||
onProgress?: (progress: TileProgress) => void,
|
||||
): Promise<BaseImage> {
|
||||
const { width, height } = image;
|
||||
if (!Number.isInteger(tile) || tile < 8) throw new Error(`tile must be an integer >= 8, got ${tile}`);
|
||||
if (overlap < 0 || overlap >= tile) throw new Error(`overlap must be in [0, tile), got ${overlap}`);
|
||||
|
||||
const expected = 3 * tile * tile;
|
||||
const step = tile - overlap;
|
||||
const weights = featherWeights(tile, overlap);
|
||||
|
||||
const acc = new Float32Array(3 * width * height);
|
||||
const weight = new Float32Array(width * height);
|
||||
const patch = new Float32Array(expected);
|
||||
// Tiles start every `step` pixels, so the last one may hang off the edge.
|
||||
const total = Math.ceil(width / step) * Math.ceil(height / step);
|
||||
let done = 0;
|
||||
|
||||
for (let ty = 0; ty < height; ty += step) {
|
||||
for (let tx = 0; tx < width; tx += step) {
|
||||
// Gather with clamp-to-edge padding; the convolution needs a full tile
|
||||
// even when the tile hangs off the right or bottom edge.
|
||||
for (let y = 0; y < tile; y++) {
|
||||
const sy = ty + y;
|
||||
const cy = sy < 0 ? 0 : sy >= height ? height - 1 : sy;
|
||||
for (let x = 0; x < tile; x++) {
|
||||
const sx = tx + x;
|
||||
const cx = sx < 0 ? 0 : sx >= width ? width - 1 : sx;
|
||||
const src = (cy * width + cx) * 3;
|
||||
const dst = (y * tile + x) * 3;
|
||||
patch[dst] = image.rgb[src];
|
||||
patch[dst + 1] = image.rgb[src + 1];
|
||||
patch[dst + 2] = image.rgb[src + 2];
|
||||
}
|
||||
}
|
||||
|
||||
const out = await runTile(patch, tile);
|
||||
if (out.length !== expected) {
|
||||
throw new Error(`tile runner returned ${out.length} values, expected ${expected}`);
|
||||
}
|
||||
|
||||
for (let y = 0; y < tile; y++) {
|
||||
const sy = ty + y;
|
||||
if (sy < 0 || sy >= height) continue;
|
||||
for (let x = 0; x < tile; x++) {
|
||||
const sx = tx + x;
|
||||
if (sx < 0 || sx >= width) continue;
|
||||
const w = weights[y] * weights[x];
|
||||
const dst = (sy * width + sx) * 3;
|
||||
const src = (y * tile + x) * 3;
|
||||
acc[dst] += out[src] * w;
|
||||
acc[dst + 1] += out[src + 1] * w;
|
||||
acc[dst + 2] += out[src + 2] * w;
|
||||
weight[sy * width + sx] += w;
|
||||
}
|
||||
}
|
||||
done += 1;
|
||||
onProgress?.({ done, total });
|
||||
}
|
||||
}
|
||||
|
||||
const rgb = new Float32Array(3 * width * height);
|
||||
for (let i = 0, p = 0; i < width * height; i++, p += 3) {
|
||||
const w = weight[i] || 1;
|
||||
for (let k = 0; k < 3; k++) {
|
||||
const v = acc[p + k] / w;
|
||||
rgb[p + k] = v < 0 ? 0 : v > 255 ? 255 : v;
|
||||
}
|
||||
}
|
||||
return { rgb, width, height };
|
||||
}
|
||||
|
||||
interface Session {
|
||||
run(feeds: Record<string, unknown>): Promise<Record<string, { data: Float32Array }>>;
|
||||
inputNames: readonly string[];
|
||||
outputNames: readonly string[];
|
||||
}
|
||||
|
||||
/**
|
||||
* Build a `BaseDenoiser` backed by an ONNX model.
|
||||
*
|
||||
* The session is created on first use and memoised, so constructing this is
|
||||
* free and a missing model surfaces as a clear error at run time rather than at
|
||||
* import time.
|
||||
*/
|
||||
export function createOnnxBaseDenoiser(options: OnnxBaseOptions): BaseDenoiser {
|
||||
const tile = options.tile ?? 256;
|
||||
const overlap = options.overlap ?? 32;
|
||||
let sessionPromise: Promise<Session> | null = null;
|
||||
|
||||
const session = (): Promise<Session> => {
|
||||
if (!sessionPromise) {
|
||||
sessionPromise = (async () => {
|
||||
const ort = await import('onnxruntime-node');
|
||||
const created = await ort.InferenceSession.create(options.modelPath, {
|
||||
executionProviders: ['cpu'],
|
||||
graphOptimizationLevel: 'all',
|
||||
intraOpNumThreads: options.intraOpThreads ?? 0,
|
||||
});
|
||||
return created as unknown as Session;
|
||||
})();
|
||||
}
|
||||
return sessionPromise;
|
||||
};
|
||||
|
||||
return async (image: BaseImage): Promise<BaseImage> => {
|
||||
const active = await session();
|
||||
const ort = await import('onnxruntime-node');
|
||||
const inputName = active.inputNames[0];
|
||||
const outputName = active.outputNames[0];
|
||||
if (!inputName || !outputName) throw new Error('model has no input/output');
|
||||
|
||||
// The model expects 0..1; everything above works in 0..255.
|
||||
//
|
||||
// But the two sides disagree about layout: `runTiled` is interleaved (HWC),
|
||||
// while every published denoiser is NCHW (`1x3xTILExTILE`). Handing HWC bytes
|
||||
// to a `[1,3,T,T]` tensor does not throw -- it silently feeds a scrambled
|
||||
// image, so channel 0 holds a third of every row rather than red. The output
|
||||
// needs the mirror transpose for the same reason.
|
||||
const plane = tile * tile;
|
||||
const runTile: RgbTileRunner = async (input, size) => {
|
||||
const normalised = new Float32Array(3 * plane);
|
||||
for (let p = 0, i = 0; p < plane; p++, i += 3) {
|
||||
normalised[p] = input[i] / 255;
|
||||
normalised[plane + p] = input[i + 1] / 255;
|
||||
normalised[2 * plane + p] = input[i + 2] / 255;
|
||||
}
|
||||
const tensor = new ort.Tensor('float32', normalised, [1, 3, size, size]);
|
||||
const result = await active.run({ [inputName]: tensor });
|
||||
const output = result[outputName]?.data;
|
||||
if (!output) throw new Error(`model produced no output named ${outputName}`);
|
||||
const scaled = new Float32Array(output.length);
|
||||
for (let p = 0, i = 0; p < plane; p++, i += 3) {
|
||||
scaled[i] = output[p] * 255;
|
||||
scaled[i + 1] = output[plane + p] * 255;
|
||||
scaled[i + 2] = output[2 * plane + p] * 255;
|
||||
}
|
||||
return scaled;
|
||||
};
|
||||
|
||||
return runTiled(runTile, image, tile, overlap, options.onProgress);
|
||||
};
|
||||
}
|
||||
@@ -105,6 +105,13 @@ export interface DenoiseStats {
|
||||
timings: StageTimings;
|
||||
}
|
||||
|
||||
/**
|
||||
* Where a run currently is. The base stage is the expensive one (SCUNet runs it
|
||||
* tile by tile); the rest are seconds at most, but naming them beats a dead
|
||||
* spinner while the base is between tiles.
|
||||
*/
|
||||
export type DenoiseStage = 'analyse' | 'base' | 'gate' | 'render';
|
||||
|
||||
export interface DenoiseOutput {
|
||||
rgb: Uint8Array;
|
||||
/** Luma of the denoised base, before detail re-injection, for inspection. */
|
||||
@@ -184,6 +191,7 @@ export async function denoiseRgb(
|
||||
image: RgbImage,
|
||||
options: Partial<DenoiseOptions>,
|
||||
runBase: BaseDenoiser,
|
||||
onStage?: (stage: DenoiseStage) => void,
|
||||
): Promise<DenoiseOutput> {
|
||||
const opts: DenoiseOptions = { ...DEFAULT_OPTIONS, ...options, gate: { ...DEFAULT_GATE, ...options.gate } };
|
||||
const started = now();
|
||||
@@ -193,6 +201,7 @@ export async function denoiseRgb(
|
||||
const { y, cb, cr } = toYcc(image);
|
||||
|
||||
let mark = now();
|
||||
onStage?.('analyse');
|
||||
const noise: NoiseModel = estimateNoise(y, width, height);
|
||||
const timings: StageTimings = {
|
||||
noise: now() - mark,
|
||||
@@ -231,6 +240,7 @@ export async function denoiseRgb(
|
||||
const decimatedSigma =
|
||||
backscale > 1.001 ? (prefilterWidth - 1 / 3) / (prefilterWidth * prefilterWidth) : 1;
|
||||
const baseSigma = noise.sigmaAt(110) * decimatedSigma;
|
||||
onStage?.('base');
|
||||
const baseOut = await runBase(baseInput, baseSigma);
|
||||
const baseUp = toYcc(upsampleBase(baseOut, width, height));
|
||||
timings.base = now() - mark;
|
||||
@@ -266,6 +276,7 @@ export async function denoiseRgb(
|
||||
timings.structure = now() - mark;
|
||||
|
||||
mark = now();
|
||||
onStage?.('gate');
|
||||
let gate = detailGate(detail, width, height, sigmaMap, coherence, opts.gate);
|
||||
|
||||
// Second, coarser band: `smooth2 - smooth6` is a band-pass around 3-8 px. It
|
||||
@@ -292,6 +303,7 @@ export async function denoiseRgb(
|
||||
const autoGate = opts.cleanSigma > 0 ? smoothstep(0.8, opts.cleanSigma, noise.global) : 1;
|
||||
const amount = clamp01(opts.amount) * autoGate;
|
||||
|
||||
onStage?.('render');
|
||||
const outY = new Float32Array(pixels);
|
||||
const outCb = new Float32Array(pixels);
|
||||
const outCr = new Float32Array(pixels);
|
||||
|
||||
@@ -0,0 +1,282 @@
|
||||
/**
|
||||
* Server HTTP integration tests.
|
||||
*
|
||||
* The real server is started once against a throwaway data directory, so these
|
||||
* exercise the routing, session, ownership, quota, gallery and file-serving
|
||||
* layers that the pure-logic suite cannot reach. Nothing touches a real catalog.
|
||||
*/
|
||||
|
||||
import { spawn } from 'node:child_process';
|
||||
import fs from 'node:fs';
|
||||
import fsp from 'node:fs/promises';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { afterAll, beforeAll, describe, expect, test } from 'vitest';
|
||||
|
||||
const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
|
||||
const PORT = 18_000 + Math.floor(Math.random() * 20_000);
|
||||
const BASE = `http://127.0.0.1:${PORT}`;
|
||||
|
||||
let child = null;
|
||||
let dataDir = '';
|
||||
let output = '';
|
||||
|
||||
/** One browser: keeps the cookies the server sets for this session. */
|
||||
class Client {
|
||||
cookies = new Map();
|
||||
|
||||
async call(pathname, init = {}) {
|
||||
const headers = { ...(init.headers ?? {}) };
|
||||
if (this.cookies.size) {
|
||||
headers.cookie = [...this.cookies].map(([key, value]) => `${key}=${value}`).join('; ');
|
||||
}
|
||||
const res = await fetch(BASE + pathname, { ...init, headers });
|
||||
for (const raw of res.headers.getSetCookie?.() ?? []) {
|
||||
const [pair] = raw.split(';');
|
||||
const at = pair.indexOf('=');
|
||||
const key = pair.slice(0, at).trim();
|
||||
const value = pair.slice(at + 1).trim();
|
||||
if (!value || /Max-Age=0/i.test(raw)) this.cookies.delete(key);
|
||||
else this.cookies.set(key, value);
|
||||
}
|
||||
return res;
|
||||
}
|
||||
|
||||
async json(pathname, init = {}) {
|
||||
const res = await this.call(pathname, init);
|
||||
const text = await res.text();
|
||||
let body = null;
|
||||
try {
|
||||
body = text ? JSON.parse(text) : null;
|
||||
} catch {
|
||||
body = { raw: text };
|
||||
}
|
||||
return { res, body };
|
||||
}
|
||||
}
|
||||
|
||||
const postJson = (payload) => ({
|
||||
method: 'POST',
|
||||
headers: { 'content-type': 'application/json' },
|
||||
body: JSON.stringify(payload),
|
||||
});
|
||||
const putJson = (payload) => ({ ...postJson(payload), method: 'PUT' });
|
||||
|
||||
const admin = new Client();
|
||||
const member = new Client();
|
||||
const guest = new Client();
|
||||
|
||||
const eventId = 'evt-http-test';
|
||||
const photoId = 'ph-http-test';
|
||||
const photoBytes = Buffer.alloc(8 * 1024, 7);
|
||||
|
||||
function photoRecord(extra = {}) {
|
||||
return {
|
||||
id: photoId,
|
||||
eventId,
|
||||
name: 'audit.jpg',
|
||||
width: 100,
|
||||
height: 80,
|
||||
size: 2,
|
||||
mime: 'image/jpeg',
|
||||
addedAt: Date.now(),
|
||||
edits: {},
|
||||
history: [],
|
||||
rating: 0,
|
||||
flag: 'none',
|
||||
keywords: [],
|
||||
thumb: '',
|
||||
...extra,
|
||||
};
|
||||
}
|
||||
|
||||
beforeAll(async () => {
|
||||
dataDir = await fsp.mkdtemp(path.join(os.tmpdir(), 'luminary-http-'));
|
||||
child = spawn(process.execPath, ['server/index.mjs'], {
|
||||
cwd: ROOT,
|
||||
env: {
|
||||
...process.env,
|
||||
LUMINARY_DATA: dataDir,
|
||||
PORT: String(PORT),
|
||||
HOST: '127.0.0.1',
|
||||
LUMINARY_LOCAL: '',
|
||||
LUMINARY_INVITE: '',
|
||||
},
|
||||
stdio: ['ignore', 'pipe', 'pipe'],
|
||||
});
|
||||
child.stdout.on('data', (chunk) => {
|
||||
output += chunk;
|
||||
});
|
||||
child.stderr.on('data', (chunk) => {
|
||||
output += chunk;
|
||||
});
|
||||
|
||||
const deadline = Date.now() + 30_000;
|
||||
while (Date.now() < deadline) {
|
||||
try {
|
||||
const res = await fetch(`${BASE}/api/health`);
|
||||
if (res.ok) return;
|
||||
} catch {
|
||||
/* not listening yet */
|
||||
}
|
||||
await new Promise((resolve) => setTimeout(resolve, 150));
|
||||
}
|
||||
throw new Error(`server did not start\n${output}`);
|
||||
}, 45_000);
|
||||
|
||||
afterAll(async () => {
|
||||
child?.kill('SIGKILL');
|
||||
if (dataDir) await fsp.rm(dataDir, { recursive: true, force: true }).catch(() => undefined);
|
||||
});
|
||||
|
||||
describe('auth and ownership', () => {
|
||||
test('the first account is the admin and gets a session', async () => {
|
||||
const { res, body } = await admin.json(
|
||||
'/api/auth/register',
|
||||
postJson({ email: 'Admin@Example.com', password: 'password123', name: 'Admin' }),
|
||||
);
|
||||
expect(res.status).toBe(201);
|
||||
expect(body.user.role).toBe('admin');
|
||||
|
||||
const me = await admin.json('/api/auth/me');
|
||||
expect(me.res.status).toBe(200);
|
||||
expect(me.body.user.email).toBe('admin@example.com');
|
||||
});
|
||||
|
||||
test('registration is closed once an account exists', async () => {
|
||||
const { res } = await guest.json(
|
||||
'/api/auth/register',
|
||||
postJson({ email: 'walk-in@example.com', password: 'password123' }),
|
||||
);
|
||||
expect(res.status).toBe(403);
|
||||
});
|
||||
|
||||
test('an invited member cannot reach another owner\'s photo', async () => {
|
||||
const invite = await admin.json(
|
||||
'/api/admin/invites',
|
||||
postJson({ email: 'member@example.com', role: 'member' }),
|
||||
);
|
||||
expect(invite.res.status).toBe(201);
|
||||
|
||||
const registered = await member.json(
|
||||
'/api/auth/register',
|
||||
postJson({
|
||||
email: 'member@example.com',
|
||||
password: 'password123',
|
||||
inviteToken: invite.body.invite.token,
|
||||
}),
|
||||
);
|
||||
expect(registered.res.status).toBe(201);
|
||||
expect(registered.body.user.role).toBe('member');
|
||||
|
||||
const upload = await admin.call(`/api/photos/${photoId}/original?name=audit.jpg&mime=image/jpeg`, {
|
||||
method: 'POST',
|
||||
headers: { 'content-type': 'application/octet-stream' },
|
||||
body: photoBytes,
|
||||
});
|
||||
expect(upload.status).toBe(201);
|
||||
});
|
||||
|
||||
test('a saved record cannot shrink its measured size', async () => {
|
||||
const saved = await admin.json(`/api/photos/${photoId}`, putJson(photoRecord()));
|
||||
expect(saved.res.status).toBe(200);
|
||||
|
||||
const quota = await admin.json('/api/quota');
|
||||
expect(quota.res.status).toBe(200);
|
||||
expect(quota.body.used).toBe(photoBytes.length);
|
||||
});
|
||||
|
||||
test('a member cannot read or overwrite the admin\'s photo', async () => {
|
||||
const preview = await member.call(`/api/photos/${photoId}/preview`);
|
||||
expect(preview.status).toBe(404);
|
||||
|
||||
const overwrite = await member.call(`/api/photos/${photoId}`, putJson({ ...photoRecord(), name: 'stolen.jpg' }));
|
||||
expect(overwrite.status).toBe(404);
|
||||
});
|
||||
|
||||
test('a member cannot park a photo inside another owner\'s event', async () => {
|
||||
const event = await admin.call(`/api/events/${eventId}`, putJson({ id: eventId, name: 'Audit shoot', createdAt: Date.now() }));
|
||||
expect(event.status).toBe(200);
|
||||
|
||||
const sneaky = await member.call('/api/photos/ph-member-1', putJson(photoRecord({ id: 'ph-member-1' })));
|
||||
expect(sneaky.status).toBe(404);
|
||||
});
|
||||
});
|
||||
|
||||
describe('file serving', () => {
|
||||
test('byte ranges resume a download', async () => {
|
||||
const res = await admin.call(`/api/photos/${photoId}/original`, {
|
||||
headers: { range: 'bytes=100-199' },
|
||||
});
|
||||
expect(res.status).toBe(206);
|
||||
expect(res.headers.get('content-range')).toBe(`bytes 100-199/${photoBytes.length}`);
|
||||
expect(res.headers.get('accept-ranges')).toBe('bytes');
|
||||
const body = Buffer.from(await res.arrayBuffer());
|
||||
expect(body.equals(photoBytes.subarray(100, 200))).toBe(true);
|
||||
});
|
||||
|
||||
test('an impossible range is refused without touching other requests', async () => {
|
||||
const res = await admin.call(`/api/photos/${photoId}/original`, {
|
||||
headers: { range: `bytes=${photoBytes.length + 10}-` },
|
||||
});
|
||||
expect(res.status).toBe(416);
|
||||
const health = await fetch(`${BASE}/api/health`);
|
||||
expect(health.status).toBe(200);
|
||||
});
|
||||
|
||||
test('an unreadable original answers 404 and leaves the server running', async () => {
|
||||
if (process.getuid?.() === 0) return; // root ignores file permissions
|
||||
const original = path.join(dataDir, 'originals', `${photoId}.jpg`);
|
||||
fs.chmodSync(original, 0o000);
|
||||
try {
|
||||
const res = await admin.call(`/api/photos/${photoId}/original`);
|
||||
expect(res.status).toBe(404);
|
||||
const health = await fetch(`${BASE}/api/health`);
|
||||
expect(health.status).toBe(200);
|
||||
} finally {
|
||||
fs.chmodSync(original, 0o644);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe('proofing gallery', () => {
|
||||
test('downloads count against the cap only when a file is sent', async () => {
|
||||
const share = await admin.json(`/api/events/${eventId}/share`, { method: 'POST' });
|
||||
expect(share.res.status).toBe(200);
|
||||
const token = share.body.token;
|
||||
|
||||
const settings = await admin.call(
|
||||
`/api/events/${eventId}/share/settings`,
|
||||
putJson({ allowDownloads: true, downloadCap: 2 }),
|
||||
);
|
||||
expect(settings.status).toBe(200);
|
||||
|
||||
const pick = await guest.call(
|
||||
`/api/galleries/${token}/picks`,
|
||||
postJson({ photoId, clientId: 'client-1', clientName: 'Client', picked: true }),
|
||||
);
|
||||
expect(pick.status).toBe(200);
|
||||
|
||||
// First download uses one of the two allowed downloads.
|
||||
const first = await guest.call(`/api/galleries/${token}/photos/${photoId}/download`);
|
||||
expect(first.status).toBe(200);
|
||||
await first.arrayBuffer();
|
||||
|
||||
// A missing render must not consume the remaining allowance.
|
||||
const original = path.join(dataDir, 'originals', `${photoId}.jpg`);
|
||||
// Outside originals/: any `<id>.*` name inside that folder is still an original.
|
||||
const parked = path.join(dataDir, `${photoId}.jpg.parked`);
|
||||
await fsp.rename(original, parked);
|
||||
const missing = await guest.call(`/api/galleries/${token}/photos/${photoId}/download`);
|
||||
expect(missing.status).toBe(404);
|
||||
await fsp.rename(parked, original);
|
||||
|
||||
const second = await guest.call(`/api/galleries/${token}/photos/${photoId}/download`);
|
||||
expect(second.status).toBe(200);
|
||||
await second.arrayBuffer();
|
||||
|
||||
const third = await guest.call(`/api/galleries/${token}/photos/${photoId}/download`);
|
||||
expect(third.status).toBe(403);
|
||||
});
|
||||
});
|
||||
@@ -8,6 +8,8 @@ import {
|
||||
DIST_DIR,
|
||||
HOST,
|
||||
INVITE,
|
||||
LOCAL_EMAIL,
|
||||
LOCAL_MODE,
|
||||
MAX_UPLOAD,
|
||||
PORT,
|
||||
RAW_PREVIEW_EDGE,
|
||||
@@ -56,6 +58,7 @@ import {
|
||||
import {
|
||||
defaultRoot,
|
||||
findOriginal,
|
||||
findOriginals,
|
||||
findPreview,
|
||||
findPreview16,
|
||||
findProof,
|
||||
@@ -78,7 +81,7 @@ import {
|
||||
writeThumb16,
|
||||
} from './storage.mjs';
|
||||
import { previewRebuildTargets, startPreviewRebuild } from './previewRebuild.mjs';
|
||||
import { decodeRaw, isRawName, rawSupport } from './raw.mjs';
|
||||
import { decodeRaw, decodeStill, isRawName, isStillName, rawSupport } from './raw.mjs';
|
||||
import {
|
||||
bridgeConfigured,
|
||||
bridgeForEvent,
|
||||
@@ -124,7 +127,7 @@ import {
|
||||
startImmichImport,
|
||||
} from './immich.mjs';
|
||||
|
||||
const VERSION = '1.0.0';
|
||||
const VERSION = '0.5.2';
|
||||
const COOKIE = 'lumen_session';
|
||||
|
||||
/** Self-only policy; must allow the wasm engines and React inline styles. */
|
||||
@@ -337,6 +340,32 @@ function sessionCookie(req, token, maxAge) {
|
||||
return `${COOKIE}=${token}; Path=/; HttpOnly; SameSite=Lax; Max-Age=${maxAge}${secure}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* LUMINARY_LOCAL=1 (the Windows desktop bundle): one admin account, no signup,
|
||||
* no sign-in, and an unauthenticated request is the local owner. The password
|
||||
* is random and never shown, so the account cannot be signed into over a
|
||||
* network; the launcher also binds loopback only.
|
||||
*/
|
||||
let localOwner = null;
|
||||
|
||||
async function prepareLocalOwner() {
|
||||
if (!LOCAL_MODE) return;
|
||||
const existing = users.byEmail(LOCAL_EMAIL);
|
||||
if (existing) {
|
||||
localOwner = publicUser(existing);
|
||||
return;
|
||||
}
|
||||
const id = crypto.randomUUID();
|
||||
users.create({
|
||||
id,
|
||||
email: LOCAL_EMAIL,
|
||||
name: 'Local',
|
||||
passHash: await hashPassword(crypto.randomBytes(32).toString('hex')),
|
||||
role: 'admin',
|
||||
});
|
||||
localOwner = publicUser(users.byId(id));
|
||||
}
|
||||
|
||||
function currentUser(req) {
|
||||
const cookieToken = parseCookies(req)[COOKIE];
|
||||
if (cookieToken) {
|
||||
@@ -346,7 +375,10 @@ function currentUser(req) {
|
||||
if (user && !user.disabled) return publicUser(user);
|
||||
}
|
||||
}
|
||||
return authenticate(req);
|
||||
const authenticated = authenticate(req);
|
||||
if (authenticated) return authenticated;
|
||||
// A personal, loopback-only install has one owner: no credentials needed.
|
||||
return LOCAL_MODE ? localOwner : null;
|
||||
}
|
||||
|
||||
function requireAdmin(req, res) {
|
||||
@@ -500,7 +532,13 @@ function match(pathname, pattern) {
|
||||
const params = {};
|
||||
for (let i = 0; i < p.length; i++) {
|
||||
if (p[i].startsWith(':')) {
|
||||
params[p[i].slice(1)] = decodeURIComponent(a[i]);
|
||||
// A malformed escape such as %E0%A4%A must not throw URIError out of the
|
||||
// router; it simply cannot match any record.
|
||||
try {
|
||||
params[p[i].slice(1)] = decodeURIComponent(a[i]);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
} else if (p[i] !== a[i]) {
|
||||
return null;
|
||||
}
|
||||
@@ -508,6 +546,40 @@ function match(pathname, pattern) {
|
||||
return params;
|
||||
}
|
||||
|
||||
/** `bytes=start-end` / `bytes=start-` / `bytes=-suffix`, first range only. */
|
||||
function parseRange(header, size) {
|
||||
if (typeof header !== 'string' || !header.startsWith('bytes=')) return null;
|
||||
const spec = header.slice(6).split(',')[0].trim();
|
||||
const match = /^(\d*)-(\d*)$/.exec(spec);
|
||||
if (!match) return null;
|
||||
const [, rawStart, rawEnd] = match;
|
||||
if (!rawStart && !rawEnd) return null;
|
||||
let start;
|
||||
let end;
|
||||
if (!rawStart) {
|
||||
const suffix = Number(rawEnd);
|
||||
if (!Number.isFinite(suffix) || suffix <= 0) return { unsatisfiable: true };
|
||||
start = Math.max(0, size - suffix);
|
||||
end = size - 1;
|
||||
} else {
|
||||
start = Number(rawStart);
|
||||
end = rawEnd ? Number(rawEnd) : size - 1;
|
||||
if (end >= size) end = size - 1;
|
||||
}
|
||||
if (!Number.isFinite(start) || !Number.isFinite(end) || start > end || start >= size) {
|
||||
return { unsatisfiable: true };
|
||||
}
|
||||
return { start, end };
|
||||
}
|
||||
|
||||
/** The precompressed variant the client can take, if this build wrote one. */
|
||||
function acceptedEncoding(req) {
|
||||
const value = String(req.headers['accept-encoding'] ?? '').toLowerCase();
|
||||
if (value.includes('br')) return 'br';
|
||||
if (value.includes('gzip')) return 'gzip';
|
||||
return null;
|
||||
}
|
||||
|
||||
function sendBuffer(res, data, type, cache = 'private, max-age=3600') {
|
||||
res.writeHead(200, {
|
||||
'Content-Type': type,
|
||||
@@ -530,19 +602,59 @@ function bridgeLinkForPhoto(photoId) {
|
||||
|
||||
async function sendFile(req, res, filePath, type, cache = 'private, max-age=86400', extraHeaders = {}) {
|
||||
if (!filePath) return error(res, 404, 'Not found');
|
||||
// Open first, then stat the open handle. A file can vanish or lose its
|
||||
// permissions between a separate stat and open, and a ReadStream error with
|
||||
// no listener is an uncaught exception that takes the whole server down.
|
||||
let handle;
|
||||
try {
|
||||
const stat = await fsp.stat(filePath);
|
||||
res.writeHead(200, {
|
||||
handle = await fsp.open(filePath, 'r');
|
||||
} catch {
|
||||
return error(res, 404, 'Not found');
|
||||
}
|
||||
try {
|
||||
const stat = await handle.stat();
|
||||
// Byte ranges let a 300 MB original resume after a dropped connection
|
||||
// instead of starting over. The whole file is still streamed, never read
|
||||
// into memory.
|
||||
const range = req.method === 'GET' ? parseRange(req.headers.range, stat.size) : null;
|
||||
if (range?.unsatisfiable) {
|
||||
await handle.close();
|
||||
res.writeHead(416, {
|
||||
'Content-Range': `bytes */${stat.size}`,
|
||||
'Accept-Ranges': 'bytes',
|
||||
'Cache-Control': cache,
|
||||
'X-Content-Type-Options': 'nosniff',
|
||||
});
|
||||
return res.end();
|
||||
}
|
||||
const start = range ? range.start : 0;
|
||||
const end = range ? range.end : stat.size - 1;
|
||||
const length = stat.size === 0 ? 0 : end - start + 1;
|
||||
const headers = {
|
||||
'Content-Type': type,
|
||||
'Content-Length': stat.size,
|
||||
'Content-Length': length,
|
||||
'Cache-Control': cache,
|
||||
'X-Content-Type-Options': 'nosniff',
|
||||
'Accept-Ranges': 'bytes',
|
||||
...extraHeaders,
|
||||
});
|
||||
if (req.method === 'HEAD') return res.end();
|
||||
fs.createReadStream(filePath).pipe(res);
|
||||
};
|
||||
if (range) headers['Content-Range'] = `bytes ${start}-${end}/${stat.size}`;
|
||||
res.writeHead(range ? 206 : 200, headers);
|
||||
if (req.method === 'HEAD' || length === 0) {
|
||||
await handle.close();
|
||||
return res.end();
|
||||
}
|
||||
const stream = range ? handle.createReadStream({ start, end }) : handle.createReadStream();
|
||||
// A read that fails mid-transfer (unmounted volume, I/O error) cannot be
|
||||
// turned into an error page once the 200 is on the wire, but it must not
|
||||
// crash the process either.
|
||||
stream.on('error', () => res.destroy());
|
||||
res.on('close', () => stream.destroy());
|
||||
return stream.pipe(res);
|
||||
} catch {
|
||||
error(res, 404, 'Not found');
|
||||
await handle.close().catch(() => undefined);
|
||||
if (!res.headersSent) return error(res, 404, 'Not found');
|
||||
return res.destroy();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -599,8 +711,10 @@ route('GET', '/api/health', async ({ req, res }) => {
|
||||
ok: true,
|
||||
app: 'luminary',
|
||||
version: VERSION,
|
||||
needsSetup: users.count() === 0,
|
||||
registrationOpen: users.count() === 0 || Boolean(INVITE) || invites.pendingCount() > 0,
|
||||
needsSetup: !LOCAL_MODE && users.count() === 0,
|
||||
registrationOpen:
|
||||
!LOCAL_MODE && (users.count() === 0 || Boolean(INVITE) || invites.pendingCount() > 0),
|
||||
local: LOCAL_MODE,
|
||||
photos: stats.photos,
|
||||
bytes: stats.bytes,
|
||||
// The absolute data path is only for signed-in team members.
|
||||
@@ -610,6 +724,9 @@ route('GET', '/api/health', async ({ req, res }) => {
|
||||
});
|
||||
|
||||
route('POST', '/api/auth/register', async ({ req, res }) => {
|
||||
if (LOCAL_MODE) {
|
||||
return error(res, 403, 'This is a single-user desktop install; accounts are not used');
|
||||
}
|
||||
const body = await readJson(req, 64 * 1024);
|
||||
const email = normalizeEmail(body.email);
|
||||
const password = typeof body.password === 'string' ? body.password : '';
|
||||
@@ -665,6 +782,18 @@ route('POST', '/api/auth/register', async ({ req, res }) => {
|
||||
});
|
||||
|
||||
route('POST', '/api/auth/login', async ({ req, res }) => {
|
||||
// Desktop mode has no password; hand out the local session so a stale login
|
||||
// form or bookmark cannot strand the user on a sign-in screen.
|
||||
if (LOCAL_MODE && localOwner) {
|
||||
const token = createSession(localOwner.id);
|
||||
return json(
|
||||
res,
|
||||
200,
|
||||
{ token, user: localOwner },
|
||||
{ 'Set-Cookie': sessionCookie(req, token, 30 * 24 * 3600) },
|
||||
);
|
||||
}
|
||||
|
||||
const ipKey = `login:ip:${clientIp(req)}`;
|
||||
if (authFailures(ipKey) >= LOGIN_IP_LIMIT) {
|
||||
return error(res, 429, 'Too many sign-in attempts. Try again later.', { 'Retry-After': '900' });
|
||||
@@ -800,6 +929,9 @@ route('PATCH', '/api/admin/users/:id', async ({ req, res, params }) => {
|
||||
if (!admin) return;
|
||||
const target = users.byId(params.id);
|
||||
if (!target) return error(res, 404, 'No such account');
|
||||
if (LOCAL_MODE && localOwner && target.id === localOwner.id) {
|
||||
return error(res, 403, 'The local account is managed by the desktop launcher');
|
||||
}
|
||||
|
||||
const body = await readJson(req, 64 * 1024);
|
||||
const patch = {};
|
||||
@@ -872,6 +1004,9 @@ route('DELETE', '/api/admin/users/:id', async ({ req, res, params }) => {
|
||||
if (params.id === admin.id) return error(res, 400, 'You cannot delete your own account');
|
||||
const target = users.byId(params.id);
|
||||
if (!target) return error(res, 404, 'No such account');
|
||||
if (LOCAL_MODE && localOwner && target.id === localOwner.id) {
|
||||
return error(res, 403, 'The local account is managed by the desktop launcher');
|
||||
}
|
||||
if (target.role === 'admin' && users.activeAdmins() <= 1) {
|
||||
return error(res, 400, 'Keep at least one active administrator');
|
||||
}
|
||||
@@ -1711,9 +1846,12 @@ route('GET', '/api/galleries/:token/photos/:id/download', async ({ req, res, par
|
||||
if (!hit) return error(res, 404, 'Not found');
|
||||
const proof = findProof(params.id);
|
||||
const file = proof ?? findPreview(params.id) ?? findOriginal(params.id);
|
||||
if (!file) return error(res, 404, 'Not found');
|
||||
const originalName = String(hit.photo.name || 'photo.jpg');
|
||||
const safe = (proof ? originalName.replace(/\.[^.]+$/, '.jpg') : originalName).replace(/["\\/:*?<>|]+/g, '-');
|
||||
const mime = proof ? 'image/jpeg' : normalizePhotoMime(hit.photo.mime, hit.photo.name);
|
||||
// Count the download only once there is a file to send, so a missing render
|
||||
// does not quietly use up the client's allowance.
|
||||
noteGalleryDownload(params.token);
|
||||
return sendFile(req, res, file, mime, 'private, max-age=3600', {
|
||||
'Content-Disposition': `attachment; filename="${safe}"`,
|
||||
@@ -2026,23 +2164,40 @@ route('POST', '/api/photos/:id/original', async ({ req, res, params }) => {
|
||||
const drop = url.searchParams.get('drop') === '1';
|
||||
const mime = normalizePhotoMime(url.searchParams.get('mime') || '', name);
|
||||
const ext = (name.split('.').pop() || 'bin').toLowerCase();
|
||||
const raw = isRawName(name) || drop;
|
||||
// TIFF is not a raw container, but browsers cannot decode it either. It takes
|
||||
// the same upload path and is turned into a JPEG proxy here with sharp.
|
||||
const still = isStillName(name);
|
||||
const raw = isRawName(name) || drop || still;
|
||||
|
||||
// New ids are part of the normal import flow: the client uploads bytes first
|
||||
// and PUTs the record afterwards. Until that row exists the bytes are charged
|
||||
// to this user's quota, so nobody can fill the disk with unclaimed files.
|
||||
const limit = owner
|
||||
? MAX_UPLOAD
|
||||
: Math.min(MAX_UPLOAD, Math.max(0, quotaState(user.id).remaining - pendingBytes(user.id)));
|
||||
// An existing photo may still be replaced, but the replacement only has the
|
||||
// room its own file frees plus what is left of the quota: an account that is
|
||||
// already full can shrink an original, never grow one past its cap.
|
||||
const replacing = owner !== null ? findOriginal(params.id) : null;
|
||||
const replacedBytes = replacing
|
||||
? ((await fsp.stat(replacing).catch(() => null))?.size ?? 0)
|
||||
: 0;
|
||||
const limit = Math.min(
|
||||
MAX_UPLOAD,
|
||||
Math.max(0, quotaState(user.id).remaining + replacedBytes - pendingBytes(user.id)),
|
||||
);
|
||||
if (limit < 1) {
|
||||
return error(res, 413, 'This account has no storage quota left for a new upload');
|
||||
return error(
|
||||
res,
|
||||
413,
|
||||
owner
|
||||
? 'This account has no storage quota left for this file'
|
||||
: 'This account has no storage quota left for a new upload',
|
||||
);
|
||||
}
|
||||
const announced = Number(req.headers['content-length']);
|
||||
if (Number.isFinite(announced) && announced > limit) {
|
||||
return error(
|
||||
res,
|
||||
413,
|
||||
owner
|
||||
announced > MAX_UPLOAD
|
||||
? `Upload exceeds the ${Math.round(MAX_UPLOAD / (1024 * 1024))} MB limit`
|
||||
: 'This upload does not fit in the remaining storage quota',
|
||||
);
|
||||
@@ -2060,8 +2215,6 @@ route('POST', '/api/photos/:id/original', async ({ req, res, params }) => {
|
||||
}
|
||||
|
||||
const target = originalTarget(params.id, ext);
|
||||
const previous = findOriginal(params.id);
|
||||
if (previous) await fsp.rm(previous, { force: true }).catch(() => undefined);
|
||||
|
||||
let size = 0;
|
||||
try {
|
||||
@@ -2072,7 +2225,7 @@ route('POST', '/api/photos/:id/original', async ({ req, res, params }) => {
|
||||
return error(
|
||||
res,
|
||||
413,
|
||||
owner
|
||||
limit >= MAX_UPLOAD
|
||||
? `Upload exceeds the ${Math.round(MAX_UPLOAD / (1024 * 1024))} MB limit`
|
||||
: 'This upload does not fit in the remaining storage quota',
|
||||
);
|
||||
@@ -2084,6 +2237,15 @@ route('POST', '/api/photos/:id/original', async ({ req, res, params }) => {
|
||||
return error(res, 400, 'Empty upload');
|
||||
}
|
||||
|
||||
// Replace the previous bytes only now that the new file is safely on disk: a
|
||||
// failed or aborted replacement must leave the photo it was replacing
|
||||
// readable. Other extensions are dropped too, so an id never keeps a stale
|
||||
// copy that `findOriginal` might return instead of the new file.
|
||||
for (const previous of findOriginals(params.id)) {
|
||||
if (previous === target) continue;
|
||||
await fsp.rm(previous, { force: true }).catch(() => undefined);
|
||||
}
|
||||
|
||||
recentUploads.set(params.id, {
|
||||
ownerId: user.id,
|
||||
bytes: size,
|
||||
@@ -2094,7 +2256,7 @@ route('POST', '/api/photos/:id/original', async ({ req, res, params }) => {
|
||||
if (raw) {
|
||||
try {
|
||||
const data = await fsp.readFile(target);
|
||||
const decoded = await decodeRaw(data);
|
||||
const decoded = still ? await decodeStill(data) : await decodeRaw(data);
|
||||
await writePreview(params.id, decoded.jpeg, decoded.ext);
|
||||
if (decoded.preview16) {
|
||||
await writePreview16(params.id, decoded.preview16.data);
|
||||
@@ -2107,11 +2269,13 @@ route('POST', '/api/photos/:id/original', async ({ req, res, params }) => {
|
||||
}
|
||||
const info = await jpegInfo(decoded.jpeg);
|
||||
return json(res, 201, {
|
||||
raw: true,
|
||||
raw: isRawName(name) || drop,
|
||||
serverDecoded: still,
|
||||
engine: decoded.engine,
|
||||
width: info?.width || decoded.width,
|
||||
height: info?.height || decoded.height,
|
||||
mime: 'image/jpeg',
|
||||
previewBytes: decoded.jpeg.length,
|
||||
previewUrl: `/api/photos/${params.id}/preview`,
|
||||
thumbUrl: `/api/photos/${params.id}/thumb`,
|
||||
note: decoded.note ?? null,
|
||||
@@ -2311,10 +2475,14 @@ route('POST', '/api/photos/:id/denoise', async ({ req, res, params }) => {
|
||||
if (!ownedBy(photoOwner(params.id), user)) return error(res, 404, 'Not found');
|
||||
// Denoise the proxy the editor actually shows, not the raw: the result has to
|
||||
// line up pixel for pixel with the canvas and with the client's export path.
|
||||
// The Amount slider is the client's: the render is always full strength.
|
||||
// The Amount slider is the client's: the render is always full strength. The
|
||||
// base denoiser (guided / nlm / scunet) is chosen here and folded into the
|
||||
// cache key, so each model renders to its own asset.
|
||||
const source = findPreview(params.id) ?? findOriginal(params.id);
|
||||
if (!source) return error(res, 404, 'Nothing to denoise');
|
||||
const job = startDenoise({ photoId: params.id, sourcePath: source });
|
||||
const body = await readJson(req).catch(() => ({}));
|
||||
const base = body?.base === 'nlm' || body?.base === 'scunet' ? body.base : 'guided';
|
||||
const job = startDenoise({ photoId: params.id, sourcePath: source, base });
|
||||
return json(res, 202, { jobId: job.id, state: job.state });
|
||||
});
|
||||
|
||||
@@ -2332,6 +2500,12 @@ route('GET', '/api/denoise/jobs/:id', async ({ req, res, params }) => {
|
||||
error: job.error ?? null,
|
||||
url: job.url ?? null,
|
||||
stats: job.stats ?? null,
|
||||
// Where a long run is, so the panel can name the stage instead of showing a
|
||||
// spinner with no truth in it.
|
||||
progress: job.progress ?? null,
|
||||
// Without this the panel cannot tell a reused render from a fresh one and
|
||||
// reports "Denoise ready" for both.
|
||||
cached: Boolean(job.cached),
|
||||
});
|
||||
});
|
||||
|
||||
@@ -2399,6 +2573,13 @@ route('PUT', '/api/photos/:id', async ({ req, res, params }) => {
|
||||
if (body.id && body.id !== params.id) return error(res, 400, 'Photo id does not match the URL');
|
||||
const record = { ...body, id: params.id };
|
||||
|
||||
// A photo may only join an event in the same workspace; otherwise a member
|
||||
// could park rows inside someone else's event and skew its totals.
|
||||
const targetEventId = typeof record.eventId === 'string' ? record.eventId : '';
|
||||
if (targetEventId && !ownedBy(eventOwner(targetEventId), user)) {
|
||||
return error(res, 404, 'No such event');
|
||||
}
|
||||
|
||||
// Quota accounting uses bytes the server actually received, not the client's
|
||||
// claim, for an upload that just finished.
|
||||
const upload = recentUploads.get(params.id);
|
||||
@@ -2408,6 +2589,16 @@ route('PUT', '/api/photos/:id', async ({ req, res, params }) => {
|
||||
}
|
||||
record.mime = record.raw ? 'image/jpeg' : normalizePhotoMime(record.mime, record.name);
|
||||
|
||||
// Library totals, quota usage and prune plans are measured from the bytes on
|
||||
// disk, not from what a saved record claims. Without this a client could PUT
|
||||
// size: 2 for a 20 MB original, shrink its reported usage and dodge its quota
|
||||
// while the file stayed on the volume.
|
||||
const storedOriginal = findOriginal(params.id);
|
||||
if (storedOriginal) {
|
||||
const stat = await fsp.stat(storedOriginal).catch(() => null);
|
||||
if (stat) record.size = stat.size;
|
||||
}
|
||||
|
||||
const thumb = decodeDataUrl(record.thumb);
|
||||
if (thumb) {
|
||||
await writeThumb(params.id, thumb.data);
|
||||
@@ -2484,13 +2675,22 @@ async function serveStatic(req, res, url) {
|
||||
if (stat.isFile()) {
|
||||
const ext = path.extname(candidate).toLowerCase();
|
||||
const immutable = pathname.startsWith('/assets/');
|
||||
return sendFile(
|
||||
req,
|
||||
res,
|
||||
candidate,
|
||||
MIME[ext] ?? 'application/octet-stream',
|
||||
immutable ? 'public, max-age=31536000, immutable' : 'no-cache',
|
||||
);
|
||||
const cache = immutable ? 'public, max-age=31536000, immutable' : 'no-cache';
|
||||
const mime = MIME[ext] ?? 'application/octet-stream';
|
||||
// `npm run build` writes .br/.gz copies of the text assets, so the
|
||||
// first request does not pay for compression and every later one is
|
||||
// just a file read.
|
||||
const encoding = acceptedEncoding(req);
|
||||
const variants = encoding === 'br' ? ['br', 'gz'] : encoding === 'gzip' ? ['gz'] : [];
|
||||
for (const variant of variants) {
|
||||
const packed = `${candidate}.${variant}`;
|
||||
if (!fs.existsSync(packed)) continue;
|
||||
return sendFile(req, res, packed, mime, cache, {
|
||||
'Content-Encoding': variant === 'br' ? 'br' : 'gzip',
|
||||
Vary: 'Accept-Encoding',
|
||||
});
|
||||
}
|
||||
return sendFile(req, res, candidate, mime, cache);
|
||||
}
|
||||
} catch {
|
||||
/* fall through to the SPA entry */
|
||||
@@ -2567,6 +2767,13 @@ async function sweepOrphanOriginals() {
|
||||
}
|
||||
}
|
||||
|
||||
await prepareLocalOwner();
|
||||
if (LOCAL_MODE && !['127.0.0.1', 'localhost', '::1'].includes(HOST)) {
|
||||
console.warn(
|
||||
` local: LUMINARY_LOCAL=1 with HOST=${HOST}; every client is treated as the local admin`,
|
||||
);
|
||||
}
|
||||
|
||||
server.listen(PORT, HOST, async () => {
|
||||
startQuotaWorker();
|
||||
const raw = await rawSupport();
|
||||
@@ -2575,7 +2782,11 @@ server.listen(PORT, HOST, async () => {
|
||||
console.log(
|
||||
` raw: libraw ${raw.libraw ? `ready (${raw.workers} parallel worker${raw.workers === 1 ? '' : 's'})` : 'missing'} · jpeg ${raw.sharp ? 'sharp' : 'png fallback'}`,
|
||||
);
|
||||
console.log(` users: ${users.count()} account(s)${users.count() === 0 ? ' — first signup becomes admin' : ''}`);
|
||||
if (LOCAL_MODE) {
|
||||
console.log(` local: ${LOCAL_EMAIL} — sign-in disabled (LUMINARY_LOCAL=1)`);
|
||||
} else {
|
||||
console.log(` users: ${users.count()} account(s)${users.count() === 0 ? ' — first signup becomes admin' : ''}`);
|
||||
}
|
||||
if (!raw.libraw) console.log(' note: install libraw-wasm for full raw demosaic (embedded previews still work)');
|
||||
resumePreviewRebuild();
|
||||
});
|
||||
|
||||
@@ -28,6 +28,26 @@ export function isRawName(name = '') {
|
||||
return RAW_EXTENSIONS.has(ext);
|
||||
}
|
||||
|
||||
/**
|
||||
* Standard images that browsers cannot decode. TIFF takes the raw upload path
|
||||
* (store the original, serve a JPEG proxy) but is decoded by sharp, not LibRaw.
|
||||
*/
|
||||
export const SERVER_IMAGE_EXTENSIONS = new Set(['tif', 'tiff']);
|
||||
|
||||
export function isStillName(name = '') {
|
||||
const ext = name.split('.').pop()?.toLowerCase() ?? '';
|
||||
return SERVER_IMAGE_EXTENSIONS.has(ext);
|
||||
}
|
||||
|
||||
/** Rejects instead of waiting forever when a decoder wedges on one file. */
|
||||
function withTimeout(promise, ms, message) {
|
||||
let timer;
|
||||
const guard = new Promise((_, reject) => {
|
||||
timer = setTimeout(() => reject(new Error(message)), ms);
|
||||
});
|
||||
return Promise.race([promise, guard]).finally(() => clearTimeout(timer));
|
||||
}
|
||||
|
||||
/** True when the buffer starts with a container signature LibRaw can open. */
|
||||
export function looksLikeRaw(buffer) {
|
||||
if (!buffer || buffer.length < 64) return false;
|
||||
@@ -45,6 +65,19 @@ export function looksLikeRaw(buffer) {
|
||||
|
||||
let engineState = 'unloaded';
|
||||
|
||||
export async function decodeStill(buffer) {
|
||||
const proxy = await toJpegProxy(buffer, RAW_PREVIEW_EDGE);
|
||||
if (!proxy) throw new Error('Could not decode this image');
|
||||
const size = await jpegInfo(proxy.data);
|
||||
return {
|
||||
jpeg: proxy.data,
|
||||
width: size?.width || proxy.width,
|
||||
height: size?.height || proxy.height,
|
||||
engine: 'sharp',
|
||||
ext: proxy.ext,
|
||||
};
|
||||
}
|
||||
|
||||
export async function rawEngine() {
|
||||
if (engineState === 'unloaded') {
|
||||
try {
|
||||
@@ -187,10 +220,14 @@ export function extractEmbeddedJpeg(buffer) {
|
||||
async function embeddedPreview(buffer) {
|
||||
if ((await rawEngine()) === 'ready') {
|
||||
try {
|
||||
const thumb = await rawPool.use(async (lib) => {
|
||||
await lib.open(Buffer.from(buffer), { useCameraWb: true });
|
||||
return lib.thumbnailData();
|
||||
});
|
||||
const thumb = await withTimeout(
|
||||
rawPool.use(async (lib) => {
|
||||
await lib.open(Buffer.from(buffer), { useCameraWb: true });
|
||||
return lib.thumbnailData();
|
||||
}),
|
||||
12000,
|
||||
'LibRaw preview timed out',
|
||||
);
|
||||
if (thumb?.data && thumb.format === 'jpeg' && thumb.data.length > 4096) {
|
||||
return Buffer.from(thumb.data);
|
||||
}
|
||||
@@ -209,10 +246,10 @@ export async function decodeRaw(buffer) {
|
||||
let librawError = null;
|
||||
if (looksLikeRaw(buffer)) {
|
||||
try {
|
||||
let frame = await demosaic(buffer, true);
|
||||
let frame = await withTimeout(demosaic(buffer, true), 45000, 'LibRaw timed out on this file');
|
||||
// No usable matrix (an odd body or older engine): decode the familiar sRGB
|
||||
// way instead of shipping camera samples nobody can convert.
|
||||
if (!frame.rgbCam || !frame.rgb16) frame = await demosaic(buffer, false);
|
||||
if (!frame.rgbCam || !frame.rgb16) frame = await withTimeout(demosaic(buffer, false), 45000, 'LibRaw timed out on this file');
|
||||
const { width, height, rgbCam } = frame;
|
||||
// Both buffers are rewritten in place: `rgb` becomes the sRGB proxy and
|
||||
// `rgb16` the camera-native sidecar, sharing one white point.
|
||||
|
||||
@@ -0,0 +1,108 @@
|
||||
import { readFileSync, existsSync } from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import {
|
||||
RAW_EXTENSIONS,
|
||||
decodeRaw,
|
||||
decodeStill,
|
||||
isRawName,
|
||||
isStillName,
|
||||
looksLikeRaw,
|
||||
rawEngine,
|
||||
} from './raw.mjs';
|
||||
|
||||
/** TIFF-family containers: CR2, NEF and DNG all start with the same header. */
|
||||
function tiffHeader() {
|
||||
const buffer = Buffer.alloc(64);
|
||||
Buffer.from('49492a00', 'hex').copy(buffer, 0);
|
||||
return buffer;
|
||||
}
|
||||
|
||||
function withAscii(bytes) {
|
||||
const buffer = Buffer.alloc(64);
|
||||
buffer.write(bytes, 0, 'latin1');
|
||||
return buffer;
|
||||
}
|
||||
|
||||
describe('raw format coverage', () => {
|
||||
it.each(['cr2', 'nef', 'cr3', 'dng'])('routes .%s to the raw decoder', (ext) => {
|
||||
expect(RAW_EXTENSIONS.has(ext)).toBe(true);
|
||||
expect(isRawName(`IMG_0001.${ext}`)).toBe(true);
|
||||
expect(isRawName(`IMG_0001.${ext.toUpperCase()}`)).toBe(true);
|
||||
expect(isStillName(`IMG_0001.${ext}`)).toBe(false);
|
||||
});
|
||||
|
||||
it.each(['tif', 'tiff'])('routes .%s to the still decoder', (ext) => {
|
||||
expect(isStillName(`scan.${ext}`)).toBe(true);
|
||||
expect(isStillName(`scan.${ext.toUpperCase()}`)).toBe(true);
|
||||
expect(isRawName(`scan.${ext}`)).toBe(false);
|
||||
});
|
||||
|
||||
it('recognises the container signatures of the main families', () => {
|
||||
expect(looksLikeRaw(tiffHeader())).toBe(true); // CR2, NEF, DNG
|
||||
const cr3 = Buffer.alloc(64);
|
||||
cr3.write('ftyp', 4, 'latin1');
|
||||
expect(looksLikeRaw(cr3)).toBe(true);
|
||||
expect(looksLikeRaw(withAscii('IIRO'))).toBe(true); // ORF
|
||||
expect(looksLikeRaw(withAscii('IIU\0'))).toBe(true); // RW2
|
||||
expect(looksLikeRaw(withAscii('FUJIFILMCCD-RAW'))).toBe(true); // RAF
|
||||
expect(looksLikeRaw(withAscii('FOVb'))).toBe(true); // X3F
|
||||
expect(looksLikeRaw(Buffer.alloc(64))).toBe(false);
|
||||
expect(looksLikeRaw(Buffer.alloc(8))).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('TIFF decoding', () => {
|
||||
it('turns a TIFF into a JPEG proxy', async () => {
|
||||
const { default: sharp } = await import('sharp');
|
||||
const tiff = await sharp({
|
||||
create: {
|
||||
width: 48,
|
||||
height: 32,
|
||||
channels: 3,
|
||||
background: { r: 20, g: 120, b: 210 },
|
||||
},
|
||||
})
|
||||
.tiff()
|
||||
.toBuffer();
|
||||
const decoded = await decodeStill(tiff);
|
||||
expect(decoded.engine).toBe('sharp');
|
||||
expect(decoded.ext).toBe('jpg');
|
||||
expect(decoded.width).toBe(48);
|
||||
expect(decoded.height).toBe(32);
|
||||
expect(decoded.jpeg.subarray(0, 2)).toEqual(Buffer.from([0xff, 0xd8]));
|
||||
});
|
||||
|
||||
it('rejects a file that is not an image', async () => {
|
||||
await expect(decodeStill(Buffer.from('not a tiff at all'))).rejects.toThrow(
|
||||
/could not decode/i,
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
/**
|
||||
* Real containers are optional: point LUMINARY_RAW_FIXTURES at a directory
|
||||
* holding sample.cr2, sample.nef, sample.cr3 and sample.dng. The samples are
|
||||
* deliberately not committed (they are 10-40 MB each and camera-specific), but
|
||||
* when they are present this exercises the same libraw path an import takes.
|
||||
*/
|
||||
const FIXTURES = process.env.LUMINARY_RAW_FIXTURES;
|
||||
const fixture = (ext) => (FIXTURES ? path.join(FIXTURES, `sample.${ext}`) : '');
|
||||
const available = (ext) => Boolean(FIXTURES) && existsSync(fixture(ext));
|
||||
const rawFormats = ['cr2', 'nef', 'cr3', 'dng'];
|
||||
|
||||
describe.skipIf(!FIXTURES)('real raw containers', () => {
|
||||
it('has libraw available', async () => {
|
||||
expect(await rawEngine()).toBe('ready');
|
||||
});
|
||||
|
||||
for (const ext of rawFormats) {
|
||||
it.skipIf(!available(ext))(`decodes sample.${ext}`, async () => {
|
||||
const decoded = await decodeRaw(readFileSync(fixture(ext)));
|
||||
expect(decoded.jpeg.length).toBeGreaterThan(4096);
|
||||
expect(['libraw', 'embedded']).toContain(decoded.engine);
|
||||
expect(decoded.width).toBeGreaterThan(0);
|
||||
expect(decoded.height).toBeGreaterThan(0);
|
||||
}, 120000);
|
||||
}
|
||||
});
|
||||
@@ -88,15 +88,20 @@ export function originalTarget(id, ext = 'bin') {
|
||||
return originalPath(id, ext);
|
||||
}
|
||||
|
||||
export function findOriginal(id) {
|
||||
export function findOriginals(id) {
|
||||
const safe = lookupId(id);
|
||||
if (!safe) return null;
|
||||
if (!safe) return [];
|
||||
const { originals } = dirs();
|
||||
const prefix = `${safe}.`;
|
||||
for (const name of listFiles(originals)) {
|
||||
if (name.startsWith(prefix)) return path.join(originals, name);
|
||||
}
|
||||
return null;
|
||||
return listFiles(originals)
|
||||
// An interrupted upload leaves `<id>.<ext>.part-xxxx` behind; it is not a
|
||||
// usable original, and returning it would serve a truncated image.
|
||||
.filter((name) => name.startsWith(prefix) && !name.includes('.part-'))
|
||||
.map((name) => path.join(originals, name));
|
||||
}
|
||||
|
||||
export function findOriginal(id) {
|
||||
return findOriginals(id)[0] ?? null;
|
||||
}
|
||||
|
||||
export async function writePreview(id, data, ext = 'jpg') {
|
||||
@@ -194,16 +199,21 @@ export function findDenoised(id, key) {
|
||||
return path.join(dir, names[0]);
|
||||
}
|
||||
|
||||
/** Remove every denoised render for a photo, sparing `keepKey` if given. */
|
||||
export function removeDenoised(id, keepKey) {
|
||||
/**
|
||||
* Remove denoised renders for a photo, sparing the keys named in `keepKeys`.
|
||||
* A single key is accepted too; with none, every render for the photo goes.
|
||||
*/
|
||||
export function removeDenoised(id, keepKeys) {
|
||||
const safe = lookupId(id);
|
||||
if (!safe) return 0;
|
||||
const dir = path.join(storageRoot(), 'denoised');
|
||||
const key = keepKey ? String(keepKey).replace(/[^a-z0-9]/gi, '') : null;
|
||||
const keep = key ? `${safe}.${key}.jpg` : null;
|
||||
const keys = (Array.isArray(keepKeys) ? keepKeys : keepKeys ? [keepKeys] : [])
|
||||
.map((key) => String(key).replace(/[^a-z0-9]/gi, ''))
|
||||
.filter(Boolean);
|
||||
const keep = new Set(keys.map((key) => `${safe}.${key}.jpg`));
|
||||
let removed = 0;
|
||||
for (const name of listFiles(dir)) {
|
||||
if (!name.startsWith(`${safe}.`) || name === keep) continue;
|
||||
if (!name.startsWith(`${safe}.`) || keep.has(name)) continue;
|
||||
fs.rmSync(path.join(dir, name), { force: true });
|
||||
removed += 1;
|
||||
}
|
||||
|
||||
@@ -1,20 +1,15 @@
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
|
||||
import AdminPanel from './components/AdminPanel';
|
||||
import { lazy, Suspense, useCallback, useEffect, useMemo, useRef, useState } from 'react';
|
||||
import AboutModal from './components/AboutModal';
|
||||
import CloudPanel from './components/CloudPanel';
|
||||
import CommandPalette from './components/CommandPalette';
|
||||
import ContextMenu, { type MenuEntry } from './components/ContextMenu';
|
||||
import Develop from './components/Develop';
|
||||
import EventSidebar from './components/EventSidebar';
|
||||
import ExportModal from './components/ExportModal';
|
||||
import CompareView from './components/CompareView';
|
||||
import FilterBar from './components/FilterBar';
|
||||
import ImportModal from './components/ImportModal';
|
||||
import ImmichPanel from './components/ImmichPanel';
|
||||
import LibraryGrid from './components/LibraryGrid';
|
||||
import MergeModal from './components/MergeModal';
|
||||
import PasteSettingsModal from './components/PasteSettingsModal';
|
||||
import PrintModal from './components/PrintModal';
|
||||
import ShareModal from './components/ShareModal';
|
||||
import RawReprocessModal, {
|
||||
type RawReprocessFailure,
|
||||
type RawReprocessJob,
|
||||
@@ -25,6 +20,15 @@ import Shortcuts from './components/Shortcuts';
|
||||
import Stars, { ColorSwatches, FlagButtons } from './components/Stars';
|
||||
import TopBar from './components/TopBar';
|
||||
import { usePersistentState } from './lib/usePersistentState';
|
||||
|
||||
// Only mounted when the user opens them, so they are separate chunks: the grid
|
||||
// and the editor are what the first paint needs.
|
||||
const AdminPanel = lazy(() => import('./components/AdminPanel'));
|
||||
const CompareView = lazy(() => import('./components/CompareView'));
|
||||
const ImmichPanel = lazy(() => import('./components/ImmichPanel'));
|
||||
const MergeModal = lazy(() => import('./components/MergeModal'));
|
||||
const PrintModal = lazy(() => import('./components/PrintModal'));
|
||||
const ShareModal = lazy(() => import('./components/ShareModal'));
|
||||
import {
|
||||
currentUser,
|
||||
deleteEventRemote,
|
||||
@@ -138,6 +142,7 @@ export default function App() {
|
||||
const [undoAction, setUndoAction] = useState<{ message: string; run: () => void } | null>(null);
|
||||
const [menu, setMenu] = useState<{ x: number; y: number; ids: string[] } | null>(null);
|
||||
const [helpOpen, setHelpOpen] = useState(false);
|
||||
const [aboutOpen, setAboutOpen] = useState(false);
|
||||
const [searchOpen, setSearchOpen] = useState(false);
|
||||
const [shareEventId, setShareEventId] = useState<string | null>(null);
|
||||
/** Client proofing picks, keyed to the photos they chose. */
|
||||
@@ -1898,6 +1903,7 @@ export default function App() {
|
||||
mod &&
|
||||
k === 'k' &&
|
||||
!helpOpen &&
|
||||
!aboutOpen &&
|
||||
!importOpen &&
|
||||
!exportOpen &&
|
||||
!cloudOpen &&
|
||||
@@ -1916,7 +1922,7 @@ export default function App() {
|
||||
setHelpOpen((v) => !v);
|
||||
return;
|
||||
}
|
||||
if (helpOpen || importOpen || exportOpen || cloudOpen || adminOpen || compareOpen) return;
|
||||
if (helpOpen || aboutOpen || importOpen || exportOpen || cloudOpen || adminOpen || compareOpen) return;
|
||||
|
||||
if (mod && k === 'i') {
|
||||
e.preventDefault();
|
||||
@@ -2221,6 +2227,11 @@ export default function App() {
|
||||
);
|
||||
}
|
||||
|
||||
// The Windows desktop bundle runs as one local admin (LUMINARY_LOCAL=1).
|
||||
// Accounts and team administration have nothing to manage there, so both
|
||||
// panels and the entry point to them stay out of the UI.
|
||||
const localMode = cloudHealth?.local === true;
|
||||
|
||||
return (
|
||||
<div className="app">
|
||||
<TopBar
|
||||
@@ -2230,6 +2241,7 @@ export default function App() {
|
||||
selectedCount={selected.length}
|
||||
cloudLabel={cloudUser ? cloudUser.name || cloudUser.email : cloudHealth ? 'Sign in' : 'Local only'}
|
||||
cloudOn={!!cloudUser}
|
||||
localMode={localMode}
|
||||
onViewChange={(v) => {
|
||||
setCatalogOpen(false);
|
||||
if (v === 'develop' && !activePhoto) {
|
||||
@@ -2248,6 +2260,7 @@ export default function App() {
|
||||
setCloudOpen(true);
|
||||
}}
|
||||
onHelp={() => setHelpOpen(true)}
|
||||
onAbout={() => setAboutOpen(true)}
|
||||
onSearch={() => setSearchOpen(true)}
|
||||
onCatalog={() => {
|
||||
setView('grid');
|
||||
@@ -2553,32 +2566,38 @@ export default function App() {
|
||||
)}
|
||||
|
||||
{compareOpen && selected.length >= 2 && selected.length <= 4 && (
|
||||
<CompareView
|
||||
photos={selected
|
||||
.map((id) => photos.find((photo) => photo.id === id))
|
||||
.filter((photo): photo is PhotoRecord => Boolean(photo))
|
||||
.slice(0, 4)}
|
||||
onClose={() => setCompareOpen(false)}
|
||||
onOpen={(id) => {
|
||||
setCompareOpen(false);
|
||||
openPhoto(id);
|
||||
}}
|
||||
/>
|
||||
<Suspense fallback={null}>
|
||||
<CompareView
|
||||
photos={selected
|
||||
.map((id) => photos.find((photo) => photo.id === id))
|
||||
.filter((photo): photo is PhotoRecord => Boolean(photo))
|
||||
.slice(0, 4)}
|
||||
onClose={() => setCompareOpen(false)}
|
||||
onOpen={(id) => {
|
||||
setCompareOpen(false);
|
||||
openPhoto(id);
|
||||
}}
|
||||
/>
|
||||
</Suspense>
|
||||
)}
|
||||
|
||||
{printOpen && (
|
||||
<PrintModal
|
||||
photos={photos.filter((photo) => selected.includes(photo.id))}
|
||||
onClose={() => setPrintOpen(false)}
|
||||
/>
|
||||
<Suspense fallback={null}>
|
||||
<PrintModal
|
||||
photos={photos.filter((photo) => selected.includes(photo.id))}
|
||||
onClose={() => setPrintOpen(false)}
|
||||
/>
|
||||
</Suspense>
|
||||
)}
|
||||
|
||||
{mergeOpen && (
|
||||
<MergeModal
|
||||
photos={photos.filter((photo) => selected.includes(photo.id))}
|
||||
onClose={() => setMergeOpen(false)}
|
||||
onDone={(result) => void addMergedPhoto(result)}
|
||||
/>
|
||||
<Suspense fallback={null}>
|
||||
<MergeModal
|
||||
photos={photos.filter((photo) => selected.includes(photo.id))}
|
||||
onClose={() => setMergeOpen(false)}
|
||||
onDone={(result) => void addMergedPhoto(result)}
|
||||
/>
|
||||
</Suspense>
|
||||
)}
|
||||
|
||||
{exportOpen && (
|
||||
@@ -2605,6 +2624,7 @@ export default function App() {
|
||||
)}
|
||||
|
||||
{helpOpen && <Shortcuts onClose={() => setHelpOpen(false)} />}
|
||||
{aboutOpen && <AboutModal onClose={() => setAboutOpen(false)} />}
|
||||
|
||||
{searchOpen && (
|
||||
<CommandPalette
|
||||
@@ -2627,13 +2647,15 @@ export default function App() {
|
||||
const shared = events.find((e) => e.id === shareEventId);
|
||||
if (!shared) return null;
|
||||
return (
|
||||
<ShareModal
|
||||
event={shared}
|
||||
photos={livePhotos.filter((p) => p.eventId === shared.id)}
|
||||
onClose={() => setShareEventId(null)}
|
||||
onToast={setToast}
|
||||
onProofPublished={handleProofPublished}
|
||||
/>
|
||||
<Suspense fallback={null}>
|
||||
<ShareModal
|
||||
event={shared}
|
||||
photos={livePhotos.filter((p) => p.eventId === shared.id)}
|
||||
onClose={() => setShareEventId(null)}
|
||||
onToast={setToast}
|
||||
onProofPublished={handleProofPublished}
|
||||
/>
|
||||
</Suspense>
|
||||
);
|
||||
})()}
|
||||
|
||||
@@ -2646,7 +2668,7 @@ export default function App() {
|
||||
</div>
|
||||
)}
|
||||
|
||||
{cloudOpen && (
|
||||
{cloudOpen && !localMode && (
|
||||
<CloudPanel
|
||||
health={cloudHealth}
|
||||
user={cloudUser}
|
||||
@@ -2669,27 +2691,31 @@ export default function App() {
|
||||
/>
|
||||
)}
|
||||
|
||||
{adminOpen && cloudUser && (
|
||||
<AdminPanel
|
||||
user={cloudUser}
|
||||
onClose={() => setAdminOpen(false)}
|
||||
onChanged={() => {
|
||||
void getHealth().then((health) => setCloudHealth(health));
|
||||
void getImmichStatus().then(setImmichStatus).catch(() => undefined);
|
||||
}}
|
||||
onRestored={() => void refreshCatalogFromServer()}
|
||||
/>
|
||||
{adminOpen && cloudUser && !localMode && (
|
||||
<Suspense fallback={null}>
|
||||
<AdminPanel
|
||||
user={cloudUser}
|
||||
onClose={() => setAdminOpen(false)}
|
||||
onChanged={() => {
|
||||
void getHealth().then((health) => setCloudHealth(health));
|
||||
void getImmichStatus().then(setImmichStatus).catch(() => undefined);
|
||||
}}
|
||||
onRestored={() => void refreshCatalogFromServer()}
|
||||
/>
|
||||
</Suspense>
|
||||
)}
|
||||
|
||||
{immichOpen && cloudUser && (
|
||||
<ImmichPanel
|
||||
onClose={() => setImmichOpen(false)}
|
||||
onChanged={() => {
|
||||
void getImmichStatus().then(setImmichStatus).catch(() => undefined);
|
||||
void refreshCatalogFromServer();
|
||||
}}
|
||||
onToast={setToast}
|
||||
/>
|
||||
<Suspense fallback={null}>
|
||||
<ImmichPanel
|
||||
onClose={() => setImmichOpen(false)}
|
||||
onChanged={() => {
|
||||
void getImmichStatus().then(setImmichStatus).catch(() => undefined);
|
||||
void refreshCatalogFromServer();
|
||||
}}
|
||||
onToast={setToast}
|
||||
/>
|
||||
</Suspense>
|
||||
)}
|
||||
|
||||
{menu &&
|
||||
|
||||
@@ -0,0 +1,68 @@
|
||||
import { useEffect } from 'react';
|
||||
import { APP_VERSION, GUIDE_UPDATED, GUIDE_VERSION } from '../lib/about';
|
||||
|
||||
interface Props {
|
||||
onClose: () => void;
|
||||
}
|
||||
|
||||
export default function AboutModal({ onClose }: Props) {
|
||||
useEffect(() => {
|
||||
const onKey = (e: KeyboardEvent) => {
|
||||
if (e.key === 'Escape') onClose();
|
||||
};
|
||||
window.addEventListener('keydown', onKey);
|
||||
return () => window.removeEventListener('keydown', onKey);
|
||||
}, [onClose]);
|
||||
|
||||
return (
|
||||
<div
|
||||
className="modal-backdrop"
|
||||
onPointerDown={(e) => e.target === e.currentTarget && onClose()}
|
||||
>
|
||||
<div className="modal about-modal" role="dialog" aria-label="About Luminary">
|
||||
<header className="modal-head">
|
||||
<h2>About Luminary</h2>
|
||||
<button className="icon-btn" onClick={onClose} aria-label="Close">
|
||||
✕
|
||||
</button>
|
||||
</header>
|
||||
<div className="modal-body">
|
||||
<div className="about-brand">
|
||||
<img src="/logo.png" alt="" height={28} />
|
||||
<div>
|
||||
<strong>Luminary</strong>
|
||||
<div className="muted small">Version {APP_VERSION} · Beta</div>
|
||||
</div>
|
||||
</div>
|
||||
<dl className="cloud-stats about-facts">
|
||||
<div>
|
||||
<dt>User guide</dt>
|
||||
<dd>Version {GUIDE_VERSION}</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt>Guide updated</dt>
|
||||
<dd>{GUIDE_UPDATED}</dd>
|
||||
</div>
|
||||
</dl>
|
||||
<p className="muted small">
|
||||
The guide covers every screen, panel and setting, with server, Docker and
|
||||
Windows install instructions. Its screenshots are taken from a live catalog.
|
||||
</p>
|
||||
<div className="btn-row">
|
||||
<a
|
||||
className="btn primary"
|
||||
href="/luminary-user-guide.pdf"
|
||||
target="_blank"
|
||||
rel="noreferrer"
|
||||
>
|
||||
Open user guide (PDF)
|
||||
</a>
|
||||
<button className="btn ghost" onClick={onClose}>
|
||||
Close
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,105 @@
|
||||
import { Component, type ErrorInfo, type ReactNode } from 'react';
|
||||
|
||||
interface Props {
|
||||
children: ReactNode;
|
||||
}
|
||||
|
||||
interface State {
|
||||
error: Error | null;
|
||||
componentStack: string;
|
||||
version: string;
|
||||
copied: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* Without this, one exception anywhere in the tree unmounts React and leaves a
|
||||
* blank page with nothing to report. The boundary keeps a way back (reload)
|
||||
* and a way to tell support what happened, and says plainly that the library
|
||||
* itself is untouched.
|
||||
*/
|
||||
export default class ErrorBoundary extends Component<Props, State> {
|
||||
state: State = { error: null, componentStack: '', version: '', copied: false };
|
||||
|
||||
static getDerivedStateFromError(error: Error): Partial<State> {
|
||||
return { error };
|
||||
}
|
||||
|
||||
componentDidCatch(error: Error, info: ErrorInfo) {
|
||||
console.error('Luminary crashed while rendering', error, info.componentStack);
|
||||
this.setState({ componentStack: info.componentStack ?? '' });
|
||||
// The version is a nicety for the diagnostics; the page works without it.
|
||||
fetch('/api/health', { credentials: 'same-origin' })
|
||||
.then((res) => (res.ok ? res.json() : null))
|
||||
.then((body: { version?: string } | null) => {
|
||||
if (body?.version) this.setState({ version: body.version });
|
||||
})
|
||||
.catch(() => undefined);
|
||||
}
|
||||
|
||||
private diagnostics(): string {
|
||||
const error = this.state.error;
|
||||
return [
|
||||
'Luminary crash report',
|
||||
`Version: ${this.state.version || 'unknown'}`,
|
||||
`When: ${new Date().toISOString()}`,
|
||||
`Page: ${window.location.pathname}${window.location.search}`,
|
||||
`Browser: ${navigator.userAgent}`,
|
||||
`Screen: ${window.screen.width}x${window.screen.height} @${window.devicePixelRatio}x`,
|
||||
'',
|
||||
`Error: ${error?.name ?? 'Error'}: ${error?.message ?? 'unknown'}`,
|
||||
error?.stack ?? '',
|
||||
'',
|
||||
'Component stack:',
|
||||
this.state.componentStack,
|
||||
].join('\n');
|
||||
}
|
||||
|
||||
private async copyDiagnostics() {
|
||||
try {
|
||||
await navigator.clipboard.writeText(this.diagnostics());
|
||||
this.setState({ copied: true });
|
||||
window.setTimeout(() => this.setState({ copied: false }), 2500);
|
||||
} catch {
|
||||
// Clipboard access can be denied; the email link still carries the report.
|
||||
this.setState({ copied: false });
|
||||
}
|
||||
}
|
||||
|
||||
render() {
|
||||
const error = this.state.error;
|
||||
if (!error) return this.props.children;
|
||||
|
||||
const subject = encodeURIComponent('Luminary crash report');
|
||||
const body = encodeURIComponent(this.diagnostics().slice(0, 1800));
|
||||
const mailto = `mailto:bhursey@gmail.com?subject=${subject}&body=${body}`;
|
||||
|
||||
return (
|
||||
<section className="crash-screen" role="alert">
|
||||
<div className="crash-card">
|
||||
<h1>Luminary hit an unexpected error</h1>
|
||||
<p>
|
||||
Your photos, edits and catalog are safe on disk — nothing was deleted. Reloading
|
||||
usually clears it. If it keeps happening, send the diagnostics below so it can be
|
||||
fixed.
|
||||
</p>
|
||||
<p className="crash-message">{error.message || 'Unknown error'}</p>
|
||||
<div className="btn-row">
|
||||
<button className="btn primary" onClick={() => window.location.reload()}>
|
||||
Reload Luminary
|
||||
</button>
|
||||
<button className="btn ghost" onClick={() => void this.copyDiagnostics()}>
|
||||
{this.state.copied ? 'Copied' : 'Copy diagnostics'}
|
||||
</button>
|
||||
<a className="btn ghost" href={mailto}>
|
||||
Email support
|
||||
</a>
|
||||
</div>
|
||||
<details className="crash-details">
|
||||
<summary>Technical details</summary>
|
||||
<pre>{this.diagnostics()}</pre>
|
||||
</details>
|
||||
</div>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -3,6 +3,13 @@ import { ASPECTS, BW_FILTERS, HUE_BANDS, identityCurve, MAX_LOCAL_COMPONENTS, MA
|
||||
import { computeAutoEdits, computeAutoWhiteBalance } from '../lib/auto';
|
||||
import { autoNoiseFor } from '../lib/noiseProfile';
|
||||
import { clearDenoised, getDenoiseJob, startDenoise } from '../lib/api';
|
||||
import {
|
||||
DENOISE_MODELS,
|
||||
denoiseProgressLabel,
|
||||
withDenoiseRender,
|
||||
type DenoiseModel,
|
||||
} from '../lib/denoiseModels';
|
||||
import type { DenoiseProgress } from '../lib/api';
|
||||
import { clamp } from '../lib/curves';
|
||||
import type {
|
||||
CurveChannel,
|
||||
@@ -610,34 +617,60 @@ export function EffectsPanel({ edits, photo, set, grainFreeze }: PanelSetProps &
|
||||
export function DetailPanel({ edits, photo, set }: PanelSetProps) {
|
||||
const [aiBusy, setAiBusy] = useState(false);
|
||||
const [aiNote, setAiNote] = useState<string | null>(null);
|
||||
const [aiStartedAt, setAiStartedAt] = useState<number | null>(null);
|
||||
const [aiElapsed, setAiElapsed] = useState(0);
|
||||
const [aiProgress, setAiProgress] = useState<DenoiseProgress | null>(null);
|
||||
const aiActive = Boolean(edits.aiDenoise.key);
|
||||
|
||||
// A render reports no progress of its own, so the elapsed time is the one
|
||||
// honest measurement the panel can show. It ticks only while one is running:
|
||||
// a full-size frame is seconds of solid CPU on the server, not a spinner.
|
||||
useEffect(() => {
|
||||
if (aiStartedAt == null) return;
|
||||
setAiElapsed(0);
|
||||
const timer = window.setInterval(
|
||||
() => setAiElapsed(Math.round((performance.now() - aiStartedAt) / 1000)),
|
||||
1000,
|
||||
);
|
||||
return () => window.clearInterval(timer);
|
||||
}, [aiStartedAt]);
|
||||
|
||||
// Poll rather than stream: the job is seconds long, and a failed poll just
|
||||
// leaves the previous note on screen instead of breaking the panel.
|
||||
const generateAi = async () => {
|
||||
const generateAi = async (base: DenoiseModel = edits.aiDenoise.model) => {
|
||||
if (aiBusy) return;
|
||||
setAiBusy(true);
|
||||
setAiNote('Rendering the denoised version on the server…');
|
||||
setAiStartedAt(performance.now());
|
||||
setAiProgress(null);
|
||||
setAiNote(null);
|
||||
try {
|
||||
const { jobId } = await startDenoise(photo.id);
|
||||
const { jobId } = await startDenoise(photo.id, base);
|
||||
for (let attempt = 0; attempt < 180; attempt++) {
|
||||
await new Promise((resolve) => setTimeout(resolve, 1000));
|
||||
const job = await getDenoiseJob(jobId);
|
||||
// The worker names its stage and counts SCUNet tiles; poll it rather than
|
||||
// inventing a percentage on the client.
|
||||
if (job.state === 'running') setAiProgress(job.progress ?? null);
|
||||
if (job.state === 'done') {
|
||||
set({ aiDenoise: { ...edits.aiDenoise, key: job.key } }, 'AI denoise');
|
||||
// `edits` here is the render captured when the run started -- before
|
||||
// the chip click that picked the model was committed. Spreading it
|
||||
// writes the previous model back, so an SCUNet render would flip the
|
||||
// picker to Guided on completion. The key belongs to one specific
|
||||
// base, so pin the model to the base that actually rendered.
|
||||
set({ aiDenoise: withDenoiseRender(edits.aiDenoise, base, job.key) }, 'AI denoise');
|
||||
// The pipeline tapers itself down on frames it measures as clean. That
|
||||
// taper is in the rendered file now, so report it -- the Amount slider
|
||||
// multiplies it rather than replacing it.
|
||||
const applied = job.stats?.autoGate ?? 1;
|
||||
const base = job.cached
|
||||
const note = job.cached
|
||||
? 'Using the cached version'
|
||||
: job.ms != null
|
||||
? `Cleaned in ${(job.ms / 1000).toFixed(1)}s`
|
||||
: 'Denoise ready';
|
||||
setAiNote(
|
||||
applied < 0.95
|
||||
? `${base} · clean frame, correction reduced to ${Math.round(applied * 100)}%`
|
||||
: base,
|
||||
? `${note} · clean frame, correction reduced to ${Math.round(applied * 100)}%`
|
||||
: note,
|
||||
);
|
||||
return;
|
||||
}
|
||||
@@ -650,6 +683,8 @@ export function DetailPanel({ edits, photo, set }: PanelSetProps) {
|
||||
} catch (err) {
|
||||
setAiNote(err instanceof Error ? err.message : 'Denoise failed');
|
||||
} finally {
|
||||
setAiStartedAt(null);
|
||||
setAiProgress(null);
|
||||
setAiBusy(false);
|
||||
}
|
||||
};
|
||||
@@ -747,12 +782,31 @@ export function DetailPanel({ edits, photo, set }: PanelSetProps) {
|
||||
<button
|
||||
className="chip tiny"
|
||||
disabled={aiBusy}
|
||||
onClick={generateAi}
|
||||
title="Clean up noise while keeping edges and fine texture"
|
||||
onClick={() => void generateAi()}
|
||||
title="Clean up noise with a detail-preserving model"
|
||||
>
|
||||
{aiBusy ? 'Working…' : aiActive ? 'Regenerate' : 'Generate'}
|
||||
</button>
|
||||
</div>
|
||||
<div className="model-picker" role="radiogroup" aria-label="AI denoise model">
|
||||
{/* One render belongs to one model: switching mid-run would leave a chip
|
||||
selected with no render behind it. */}
|
||||
{DENOISE_MODELS.map((opt) => (
|
||||
<button
|
||||
key={opt.value}
|
||||
type="button"
|
||||
disabled={aiBusy}
|
||||
className={`chip small ${edits.aiDenoise.model === opt.value ? 'on' : ''}`}
|
||||
onClick={() => {
|
||||
set({ aiDenoise: { ...edits.aiDenoise, model: opt.value } }, 'AI denoise model');
|
||||
void generateAi(opt.value);
|
||||
}}
|
||||
title={opt.title}
|
||||
>
|
||||
{opt.label}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
{aiActive ? (
|
||||
<Slider
|
||||
label="Amount"
|
||||
@@ -763,10 +817,17 @@ export function DetailPanel({ edits, photo, set }: PanelSetProps) {
|
||||
/>
|
||||
) : null}
|
||||
<p className="muted small panel-hint">
|
||||
{aiNote ??
|
||||
{aiBusy ? (
|
||||
<>
|
||||
{denoiseProgressLabel(aiProgress, edits.aiDenoise.model, aiElapsed)}. A full-size frame
|
||||
can take a minute or two; the picker unlocks when it lands.
|
||||
</>
|
||||
) : (
|
||||
aiNote ??
|
||||
(aiActive
|
||||
? 'Detail-preserving denoise, rendered from the full proxy.'
|
||||
: 'Removes noise only where there is no structure to keep.')}
|
||||
: 'Removes noise only where there is no structure to keep.')
|
||||
)}
|
||||
</p>
|
||||
{aiActive ? (
|
||||
<button
|
||||
@@ -1481,7 +1542,13 @@ export function NavigatorPanel({
|
||||
{photo.name}
|
||||
</div>
|
||||
<div className="muted small navigator-meta">
|
||||
{photo.raw ? (photo.decode === 'embedded' ? 'Raw · camera preview' : 'Raw · demosaiced') : 'JPEG/PNG'}{' '}
|
||||
{photo.raw
|
||||
? photo.decode === 'embedded'
|
||||
? 'Raw · camera preview'
|
||||
: 'Raw · demosaiced'
|
||||
: photo.decode === 'sharp'
|
||||
? 'TIFF · server JPEG'
|
||||
: 'JPEG/PNG'}{' '}
|
||||
· {photo.width}×{photo.height}
|
||||
</div>
|
||||
</div>
|
||||
@@ -2609,10 +2676,22 @@ export function MetadataPanel({
|
||||
const event = events.find((e) => e.id === photo.eventId);
|
||||
const [keyword, setKeyword] = useState('');
|
||||
const [presetId, setPresetId] = useState('');
|
||||
const decodeLabel = photo.raw
|
||||
? photo.decode === 'embedded'
|
||||
? 'LibRaw · camera preview fallback'
|
||||
: 'LibRaw demosaic'
|
||||
: photo.decode === 'sharp'
|
||||
? 'sharp JPEG proxy'
|
||||
: 'Browser';
|
||||
const proxyLabel = `${photo.width} × ${photo.height}${
|
||||
photo.proxyBytes ? ` · ${(photo.proxyBytes / (1024 * 1024)).toFixed(1)} MB` : ''
|
||||
}`;
|
||||
const rows: [string, string][] = [
|
||||
['File', photo.name],
|
||||
['Dimensions', `${photo.width} × ${photo.height}`],
|
||||
['Size', `${(photo.size / (1024 * 1024)).toFixed(2)} MB`],
|
||||
['Decode', decodeLabel],
|
||||
['Proxy', proxyLabel],
|
||||
['Camera', photo.meta.camera ?? '—'],
|
||||
['Lens', photo.meta.lens ?? '—'],
|
||||
['ISO', photo.meta.iso ? String(photo.meta.iso) : '—'],
|
||||
|
||||
@@ -7,11 +7,14 @@ interface Props {
|
||||
selectedCount: number;
|
||||
cloudLabel: string;
|
||||
cloudOn: boolean;
|
||||
/** Desktop mode has no account, so the team-server button is not shown. */
|
||||
localMode?: boolean;
|
||||
onViewChange: (view: ViewMode) => void;
|
||||
onImport: () => void;
|
||||
onExport: () => void;
|
||||
onCloud: () => void;
|
||||
onHelp: () => void;
|
||||
onAbout: () => void;
|
||||
onSearch: () => void;
|
||||
onCatalog: () => void;
|
||||
canShare: boolean;
|
||||
@@ -25,11 +28,13 @@ export default function TopBar({
|
||||
selectedCount,
|
||||
cloudLabel,
|
||||
cloudOn,
|
||||
localMode = false,
|
||||
onViewChange,
|
||||
onImport,
|
||||
onExport,
|
||||
onCloud,
|
||||
onHelp,
|
||||
onAbout,
|
||||
onSearch,
|
||||
onCatalog,
|
||||
canShare,
|
||||
@@ -37,10 +42,16 @@ export default function TopBar({
|
||||
}: Props) {
|
||||
return (
|
||||
<header className="topbar">
|
||||
<div className="brand">
|
||||
<button
|
||||
type="button"
|
||||
className="brand brand-btn"
|
||||
onClick={onAbout}
|
||||
title="About Luminary"
|
||||
aria-label="About Luminary"
|
||||
>
|
||||
<img className="brand-mark" src="/logo.png" alt="" height={20} />
|
||||
Luminary
|
||||
</div>
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className="icon-btn mobile-only catalog-btn"
|
||||
@@ -70,10 +81,12 @@ export default function TopBar({
|
||||
</nav>
|
||||
|
||||
<div className="topbar-actions">
|
||||
<button className={`cloud-pill ${cloudOn ? 'on' : ''}`} onClick={onCloud} title="Team server">
|
||||
<span className="cloud-dot" />
|
||||
{cloudLabel}
|
||||
</button>
|
||||
{!localMode && (
|
||||
<button className={`cloud-pill ${cloudOn ? 'on' : ''}`} onClick={onCloud} title="Team server">
|
||||
<span className="cloud-dot" />
|
||||
{cloudLabel}
|
||||
</button>
|
||||
)}
|
||||
{canShare && (
|
||||
<button className="btn ghost" onClick={onShare} title="Share this event for client proofing">
|
||||
Share
|
||||
|
||||
@@ -0,0 +1,7 @@
|
||||
/**
|
||||
* Versions shown in the About panel. APP_VERSION mirrors package.json; the
|
||||
* guide values are bumped when docs/user-guide/guide.html is republished.
|
||||
*/
|
||||
export const APP_VERSION = '0.5.2';
|
||||
export const GUIDE_VERSION = '0.5';
|
||||
export const GUIDE_UPDATED = 'November 2026';
|
||||
@@ -6,6 +6,8 @@ export interface Health {
|
||||
version: string;
|
||||
needsSetup: boolean;
|
||||
registrationOpen: boolean;
|
||||
/** Single-user desktop mode (LUMINARY_LOCAL=1): no accounts to manage. */
|
||||
local?: boolean;
|
||||
photos: number;
|
||||
bytes: number;
|
||||
storage?: { root: string; custom: boolean };
|
||||
@@ -21,13 +23,15 @@ export interface SessionUser {
|
||||
|
||||
export interface UploadResult {
|
||||
raw: boolean;
|
||||
engine?: 'libraw' | 'embedded';
|
||||
engine?: 'libraw' | 'embedded' | 'sharp';
|
||||
width?: number;
|
||||
height?: number;
|
||||
mime?: string;
|
||||
size?: number;
|
||||
previewUrl?: string;
|
||||
thumbUrl?: string;
|
||||
/** Size of the JPEG proxy the server wrote, when it decoded this file. */
|
||||
previewBytes?: number;
|
||||
note?: string | null;
|
||||
}
|
||||
|
||||
@@ -151,7 +155,7 @@ export function reprocessRawPhoto(
|
||||
): Promise<{
|
||||
width: number;
|
||||
height: number;
|
||||
engine?: 'libraw' | 'embedded';
|
||||
engine?: 'libraw' | 'embedded' | 'sharp';
|
||||
note?: string | null;
|
||||
previewVersion?: number;
|
||||
previewUrl?: string;
|
||||
@@ -176,6 +180,13 @@ export interface ProofUpload {
|
||||
}
|
||||
|
||||
/** Upload a rendered (edited) proof for the client gallery and owner grid. */
|
||||
export interface DenoiseProgress {
|
||||
stage: 'analyse' | 'base' | 'gate' | 'render';
|
||||
/** Tile counter, present while the base model is running. */
|
||||
done?: number;
|
||||
total?: number;
|
||||
}
|
||||
|
||||
export interface DenoiseJob {
|
||||
id: string;
|
||||
key: string;
|
||||
@@ -183,14 +194,20 @@ export interface DenoiseJob {
|
||||
ms: number | null;
|
||||
error: string | null;
|
||||
url: string | null;
|
||||
/** Where the worker is inside the run; null once it finishes. */
|
||||
progress?: DenoiseProgress | null;
|
||||
/** Reported by a job that found the render already on disk. */
|
||||
cached?: boolean;
|
||||
stats: { amount: number; autoGate: number; gate: number; noise: number; baseWidth: number } | null;
|
||||
}
|
||||
|
||||
/** Starts a server-side denoise job; the work runs off the request thread. */
|
||||
export function startDenoise(photoId: string): Promise<{ jobId: string }> {
|
||||
return request(`/api/photos/${encodeURIComponent(photoId)}/denoise`, { method: 'POST' });
|
||||
export function startDenoise(photoId: string, base: 'guided' | 'nlm' | 'scunet' = 'guided'): Promise<{ jobId: string }> {
|
||||
return request(`/api/photos/${encodeURIComponent(photoId)}/denoise`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ base }),
|
||||
});
|
||||
}
|
||||
|
||||
/** Drops the rendered files for a photo; the next run renders from scratch. */
|
||||
|
||||
@@ -0,0 +1,84 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { defaultEdits, normalizeEdits } from './edits';
|
||||
import {
|
||||
DENOISE_MODELS,
|
||||
denoiseModelLabel,
|
||||
denoiseProgressLabel,
|
||||
withDenoiseRender,
|
||||
} from './denoiseModels';
|
||||
|
||||
describe('AI denoise edit normalization', () => {
|
||||
it('keeps the model the user picked', () => {
|
||||
for (const model of ['guided', 'scunet', 'nlm'] as const) {
|
||||
expect(normalizeEdits({ aiDenoise: { model } } as never).aiDenoise.model).toBe(model);
|
||||
}
|
||||
});
|
||||
|
||||
it('defaults an unknown or missing model to guided', () => {
|
||||
expect(normalizeEdits({}).aiDenoise.model).toBe('guided');
|
||||
expect(normalizeEdits({ aiDenoise: {} } as never).aiDenoise.model).toBe('guided');
|
||||
expect(normalizeEdits({ aiDenoise: { model: 'swinir' } } as never).aiDenoise.model).toBe(
|
||||
'guided',
|
||||
);
|
||||
});
|
||||
|
||||
it('keeps the render key and the amount, and drops an unusable key', () => {
|
||||
const kept = normalizeEdits({ aiDenoise: { model: 'nlm', key: 'abc123', amount: 40 } } as never);
|
||||
expect(kept.aiDenoise).toEqual({ model: 'nlm', key: 'abc123', amount: 40 });
|
||||
|
||||
const dropped = normalizeEdits({ aiDenoise: { key: '' } } as never);
|
||||
expect(dropped.aiDenoise.key).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe('AI denoise model selection', () => {
|
||||
it('commits the render under the base that produced it', () => {
|
||||
// The regression: the panel's completion path used to spread a copy of the
|
||||
// edit captured before the chip click, which put the previous model back.
|
||||
const previous = { ...defaultEdits().aiDenoise, model: 'guided' as const, amount: 70 };
|
||||
const next = withDenoiseRender(previous, 'scunet', 'key-scunet');
|
||||
expect(next).toEqual({ model: 'scunet', key: 'key-scunet', amount: 70 });
|
||||
expect(previous).toEqual({ model: 'guided', key: null, amount: 70 });
|
||||
});
|
||||
|
||||
it('keeps a stale picker honest for every base', () => {
|
||||
const previous = { ...defaultEdits().aiDenoise, model: 'guided' as const };
|
||||
for (const option of DENOISE_MODELS) {
|
||||
expect(withDenoiseRender(previous, option.value, `key-${option.value}`).model).toBe(
|
||||
option.value,
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
it('names the stage and tile count a running render reports', () => {
|
||||
expect(denoiseProgressLabel({ stage: 'base', done: 12, total: 40 }, 'scunet', 31)).toBe(
|
||||
'Rendering with SCUNet · denoising 12/40 tiles · 31s elapsed',
|
||||
);
|
||||
expect(denoiseProgressLabel({ stage: 'gate' }, 'guided', 7.4)).toBe(
|
||||
'Rendering with Guided · mapping detail · 7s elapsed',
|
||||
);
|
||||
// No tile counter for the classical models, and no stage at all before the
|
||||
// first poll lands.
|
||||
expect(denoiseProgressLabel({ stage: 'base' }, 'nlm', 2)).toBe(
|
||||
'Rendering with NLM · denoising · 2s elapsed',
|
||||
);
|
||||
expect(denoiseProgressLabel(null, 'scunet', 0)).toBe(
|
||||
'Rendering with SCUNet · starting · 0s elapsed',
|
||||
);
|
||||
// A worker that over-counts cannot report past the end of the run.
|
||||
expect(denoiseProgressLabel({ stage: 'base', done: 99, total: 40 }, 'scunet', 90)).toContain(
|
||||
'40/40 tiles',
|
||||
);
|
||||
});
|
||||
|
||||
it('offers each selectable model exactly once, with a label', () => {
|
||||
const values = DENOISE_MODELS.map((option) => option.value);
|
||||
expect(new Set(values).size).toBe(values.length);
|
||||
expect(values).toEqual(['guided', 'scunet', 'nlm']);
|
||||
for (const option of DENOISE_MODELS) {
|
||||
expect(option.label, option.value).toBeTruthy();
|
||||
expect(option.title, option.value).toBeTruthy();
|
||||
expect(denoiseModelLabel(option.value)).toBe(option.label);
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,57 @@
|
||||
import type { DenoiseProgress } from './api';
|
||||
import type { Edits } from '../types';
|
||||
|
||||
/** One of the base denoisers the AI denoise panel can render with. */
|
||||
export type DenoiseModel = Edits['aiDenoise']['model'];
|
||||
export type AiDenoise = Edits['aiDenoise'];
|
||||
|
||||
/**
|
||||
* The models in panel order. `guided` is the default and the fast one; the two
|
||||
* learned/classical alternates are additive, so the list is also the contract
|
||||
* the picker and the help text are built from.
|
||||
*/
|
||||
export const DENOISE_MODELS: { value: DenoiseModel; label: string; title: string }[] = [
|
||||
{ value: 'guided', label: 'Guided', title: 'Guided filter — fast, keeps the most fine texture' },
|
||||
{ value: 'scunet', label: 'SCUNet', title: 'SCUNet — learned model, removes the most grain, smooths more' },
|
||||
{ value: 'nlm', label: 'NLM', title: 'Non-local means — slower, between Guided and SCUNet' },
|
||||
];
|
||||
|
||||
export function denoiseModelLabel(model: DenoiseModel): string {
|
||||
return DENOISE_MODELS.find((option) => option.value === model)?.label ?? 'Guided';
|
||||
}
|
||||
|
||||
/** Human names for the pipeline stages the worker reports. */
|
||||
const STAGE_LABELS: Record<DenoiseProgress['stage'], string> = {
|
||||
analyse: 'reading the noise profile',
|
||||
base: 'denoising',
|
||||
gate: 'mapping detail',
|
||||
render: 'blending the result',
|
||||
};
|
||||
|
||||
/**
|
||||
* One line describing a running render. The stage names and the tile counter
|
||||
* come from the worker, so this is real progress rather than a spinner -- the
|
||||
* elapsed time is only the fallback for the first second or two.
|
||||
*/
|
||||
export function denoiseProgressLabel(
|
||||
progress: DenoiseProgress | null | undefined,
|
||||
model: DenoiseModel,
|
||||
elapsedSeconds: number,
|
||||
): string {
|
||||
const seconds = Math.max(0, Math.round(elapsedSeconds));
|
||||
const stage = progress?.stage ? (STAGE_LABELS[progress.stage] ?? 'working') : 'starting';
|
||||
const tiles =
|
||||
progress?.stage === 'base' && progress.total
|
||||
? ` ${Math.min(progress.done ?? 0, progress.total)}/${progress.total} tiles`
|
||||
: '';
|
||||
return `Rendering with ${denoiseModelLabel(model)} · ${stage}${tiles} · ${seconds}s elapsed`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Commit a finished render to the edit. The cache key belongs to the base that
|
||||
* produced it, so the picker follows that base: a caller holding an older copy
|
||||
* of the edit cannot put the previous model back in front of a fresh key.
|
||||
*/
|
||||
export function withDenoiseRender(ai: AiDenoise, base: DenoiseModel, key: string): AiDenoise {
|
||||
return { ...ai, model: base, key };
|
||||
}
|
||||
@@ -500,7 +500,10 @@ export function normalizeEdits(input: Partial<Edits> | undefined | null): Edits
|
||||
aiDenoise: {
|
||||
amount: num(aiDenoise.amount, d.aiDenoise.amount, 0, 100),
|
||||
key: typeof aiDenoise.key === 'string' && aiDenoise.key ? aiDenoise.key : null,
|
||||
model: 'guided',
|
||||
model:
|
||||
aiDenoise.model === 'guided' || aiDenoise.model === 'nlm' || aiDenoise.model === 'scunet'
|
||||
? aiDenoise.model
|
||||
: 'guided',
|
||||
},
|
||||
temp: num(input.temp, 0, -100, 100),
|
||||
tint: num(input.tint, 0, -100, 100),
|
||||
@@ -652,6 +655,10 @@ export function normalizePhoto(input: Partial<PhotoRecord> & { id: string }): Ph
|
||||
typeof input.previewVersion === 'number' && Number.isFinite(input.previewVersion)
|
||||
? input.previewVersion
|
||||
: undefined,
|
||||
proxyBytes:
|
||||
typeof input.proxyBytes === 'number' && Number.isFinite(input.proxyBytes)
|
||||
? input.proxyBytes
|
||||
: undefined,
|
||||
proofAt: typeof input.proofAt === 'number' && Number.isFinite(input.proofAt) ? input.proofAt : undefined,
|
||||
name: input.name ?? 'Untitled',
|
||||
width: input.width ?? 0,
|
||||
|
||||
@@ -7,7 +7,11 @@ const cache = new Map<string, ImageBitmap>();
|
||||
|
||||
/** Where to fetch the original (or raw proxy) when it is not cached on this device. */
|
||||
export function remoteAssetUrl(photo: PhotoRecord): string {
|
||||
if (photo.raw) return photo.previewUrl || `/api/photos/${encodeURIComponent(photo.id)}/preview`;
|
||||
// Server-decoded formats (TIFF today) keep a browser-readable JPEG proxy just
|
||||
// like raws; their original cannot be decoded by createImageBitmap.
|
||||
if (photo.raw || photo.decode === 'sharp') {
|
||||
return photo.previewUrl || `/api/photos/${encodeURIComponent(photo.id)}/preview`;
|
||||
}
|
||||
return `/api/photos/${encodeURIComponent(photo.id)}/original`;
|
||||
}
|
||||
|
||||
|
||||
@@ -4,7 +4,7 @@ import type { PhotoMeta, PhotoRecord } from '../types';
|
||||
import { putAsset, putPhoto } from './db';
|
||||
import { defaultEdits, normalizePhoto } from './edits';
|
||||
import { defaultForMeta, loadCameraLensDefaults, type CameraLensDefault } from './lensDefaults';
|
||||
import { isRawFile, RAW_EXTENSIONS } from './raw';
|
||||
import { isRawFile, isTiffFile, RAW_EXTENSIONS } from './raw';
|
||||
|
||||
export interface ImportProgress {
|
||||
done: number;
|
||||
@@ -125,6 +125,8 @@ async function importRaw(
|
||||
keywords: string[],
|
||||
cloud: CloudImport,
|
||||
defaults: CameraLensDefault[],
|
||||
/** TIFF goes through the same proxy path but is not a raw container. */
|
||||
raw = true,
|
||||
): Promise<PhotoRecord> {
|
||||
const id = uid();
|
||||
const upload = await cloud.uploadOriginal(id, file, file.name);
|
||||
@@ -158,8 +160,9 @@ async function importRaw(
|
||||
keywords,
|
||||
edits,
|
||||
history: [{ label: 'Import', ts: Date.now(), edits }],
|
||||
raw: true,
|
||||
raw,
|
||||
decode: upload.engine,
|
||||
proxyBytes: upload.previewBytes,
|
||||
previewUrl,
|
||||
});
|
||||
|
||||
@@ -242,9 +245,10 @@ export async function importFiles(
|
||||
await mapLimit(images, cloud ? IMPORT_CONCURRENCY : 2, async (file, index) => {
|
||||
if (signal?.aborted) return;
|
||||
try {
|
||||
const photo = isRawFile(file)
|
||||
const viaServer = isRawFile(file) || isTiffFile(file);
|
||||
const photo = viaServer
|
||||
? cloud
|
||||
? await importRaw(file, eventId, keywords, cloud, defaults)
|
||||
? await importRaw(file, eventId, keywords, cloud, defaults, isRawFile(file))
|
||||
: (() => {
|
||||
throw new Error('Raw files need the Luminary server. Sign in, then import again.');
|
||||
})()
|
||||
|
||||
@@ -0,0 +1,46 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import {
|
||||
RAW_ACCEPT,
|
||||
RAW_EXTENSIONS,
|
||||
SERVER_IMAGE_EXTENSIONS,
|
||||
isRawFile,
|
||||
isTiffFile,
|
||||
} from './raw';
|
||||
import { isSupportedFile } from './import';
|
||||
|
||||
/** isRawFile/isTiffFile only read the name; isSupportedFile also reads type. */
|
||||
function fakeFile(name: string, type = ''): File {
|
||||
return { name, type } as File;
|
||||
}
|
||||
|
||||
describe('import format routing', () => {
|
||||
it.each(['CR2', 'NEF', 'CR3', 'DNG'])('sends .%s to the server raw decoder', (ext) => {
|
||||
const file = fakeFile(`IMG_0001.${ext}`, 'application/octet-stream');
|
||||
expect(RAW_EXTENSIONS.has(ext.toLowerCase())).toBe(true);
|
||||
expect(isRawFile(file)).toBe(true);
|
||||
expect(isTiffFile(file)).toBe(false);
|
||||
expect(isSupportedFile(file)).toBe(true);
|
||||
});
|
||||
|
||||
it.each(['TIF', 'TIFF'])('sends .%s to the server still decoder', (ext) => {
|
||||
const file = fakeFile(`scan.${ext}`, 'image/tiff');
|
||||
expect(SERVER_IMAGE_EXTENSIONS.has(ext.toLowerCase())).toBe(true);
|
||||
expect(isTiffFile(file)).toBe(true);
|
||||
expect(isRawFile(file)).toBe(false);
|
||||
expect(isSupportedFile(file)).toBe(true);
|
||||
});
|
||||
|
||||
it('still accepts the browser-decoded formats', () => {
|
||||
expect(isSupportedFile(fakeFile('photo.jpg', 'image/jpeg'))).toBe(true);
|
||||
expect(isSupportedFile(fakeFile('photo.png', 'image/png'))).toBe(true);
|
||||
expect(isSupportedFile(fakeFile('photo.webp', 'image/webp'))).toBe(true);
|
||||
expect(isSupportedFile(fakeFile('photo.avif', 'image/avif'))).toBe(true);
|
||||
expect(isSupportedFile(fakeFile('notes.txt', 'text/plain'))).toBe(false);
|
||||
});
|
||||
|
||||
it('offers every supported extension in the file picker', () => {
|
||||
for (const ext of ['cr2', 'nef', 'cr3', 'dng', 'tif', 'tiff', 'sraw']) {
|
||||
expect(RAW_ACCEPT.split(',')).toContain(`.${ext}`);
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -7,12 +7,27 @@ export const RAW_EXTENSIONS = new Set([
|
||||
'rw2', 'raw', 'rwl',
|
||||
'raf',
|
||||
'pef', 'dng',
|
||||
'srw', '3fr', 'fff', 'iiq', 'x3f', 'erf', 'k25', 'kdc', 'dcr', 'mos', 'mrw', 'mef',
|
||||
'srw', '3fr', 'fff', 'iiq', 'x3f', 'erf', 'k25', 'kdc', 'dcr', 'mos', 'mrw', 'mef', 'sraw',
|
||||
]);
|
||||
|
||||
/**
|
||||
* Standard images the browser cannot decode itself. They take the same server
|
||||
* path as raws: the original is stored and the server writes a JPEG proxy.
|
||||
* Chrome and Firefox have no TIFF decoder, so a TIFF left to the browser is a
|
||||
* silent import failure.
|
||||
*/
|
||||
export const SERVER_IMAGE_EXTENSIONS = new Set(['tif', 'tiff']);
|
||||
|
||||
export function isTiffFile(file: File): boolean {
|
||||
const ext = file.name.split('.').pop()?.toLowerCase() ?? '';
|
||||
return SERVER_IMAGE_EXTENSIONS.has(ext);
|
||||
}
|
||||
|
||||
export function isRawFile(file: File): boolean {
|
||||
const ext = file.name.split('.').pop()?.toLowerCase() ?? '';
|
||||
return RAW_EXTENSIONS.has(ext);
|
||||
}
|
||||
|
||||
export const RAW_ACCEPT = [...RAW_EXTENSIONS].map((e) => `.${e}`).join(',');
|
||||
export const RAW_ACCEPT = [...RAW_EXTENSIONS, ...SERVER_IMAGE_EXTENSIONS]
|
||||
.map((e) => `.${e}`)
|
||||
.join(',');
|
||||
|
||||
@@ -1,9 +1,15 @@
|
||||
import { lazy, Suspense } from 'react';
|
||||
import { createRoot } from 'react-dom/client';
|
||||
import App from './App';
|
||||
import ProofingGallery from './components/ProofingGallery';
|
||||
import JoinPage from './components/JoinPage';
|
||||
import ErrorBoundary from './components/ErrorBoundary';
|
||||
import './styles.css';
|
||||
|
||||
// Proofing galleries and invite pages are public and self-contained: loading
|
||||
// them lazily keeps the editor out of the chunk a client downloads to view a
|
||||
// shoot, and keeps the invite page tiny.
|
||||
const ProofingGallery = lazy(() => import('./components/ProofingGallery'));
|
||||
const JoinPage = lazy(() => import('./components/JoinPage'));
|
||||
|
||||
const root = document.getElementById('root');
|
||||
if (!root) throw new Error('root element missing');
|
||||
|
||||
@@ -14,11 +20,15 @@ const galleryMatch = /^\/g\/([A-Za-z0-9_-]+)\/?$/.exec(window.location.pathname)
|
||||
const joinMatch = /^\/join\/([A-Za-z0-9_-]+)\/?$/.exec(window.location.pathname);
|
||||
|
||||
createRoot(root).render(
|
||||
galleryMatch ? (
|
||||
<ProofingGallery token={galleryMatch[1]} />
|
||||
) : joinMatch ? (
|
||||
<JoinPage token={joinMatch[1]} />
|
||||
) : (
|
||||
<App />
|
||||
),
|
||||
<ErrorBoundary>
|
||||
<Suspense fallback={null}>
|
||||
{galleryMatch ? (
|
||||
<ProofingGallery token={galleryMatch[1]} />
|
||||
) : joinMatch ? (
|
||||
<JoinPage token={joinMatch[1]} />
|
||||
) : (
|
||||
<App />
|
||||
)}
|
||||
</Suspense>
|
||||
</ErrorBoundary>,
|
||||
);
|
||||
|
||||
@@ -604,6 +604,21 @@ img {
|
||||
font-size: 11px;
|
||||
}
|
||||
|
||||
.model-picker {
|
||||
display: flex;
|
||||
gap: 3px;
|
||||
padding: 3px;
|
||||
margin: 2px 0 6px;
|
||||
width: fit-content;
|
||||
background: var(--panel-3);
|
||||
border-radius: 6px;
|
||||
}
|
||||
|
||||
.model-picker .chip {
|
||||
border-radius: 3px;
|
||||
font-size: 11px;
|
||||
}
|
||||
|
||||
.color-filter {
|
||||
display: flex;
|
||||
gap: 5px;
|
||||
@@ -3057,6 +3072,24 @@ figcaption {
|
||||
}
|
||||
|
||||
/* Sits beside the ? button: opens the printable guide in a new tab. */
|
||||
/* The brand doubles as the About button; the reset keeps the header metrics. */
|
||||
.brand-btn {
|
||||
padding: 0;
|
||||
border: 0;
|
||||
background: none;
|
||||
color: inherit;
|
||||
font: inherit;
|
||||
letter-spacing: inherit;
|
||||
cursor: pointer;
|
||||
border-radius: 6px;
|
||||
}
|
||||
.brand-btn:hover { color: var(--text); }
|
||||
.brand-btn:focus-visible { outline: 2px solid var(--accent, #4c8dff); outline-offset: 3px; }
|
||||
|
||||
.about-brand { display: flex; align-items: center; gap: 12px; }
|
||||
.about-brand strong { display: block; font-size: 16px; }
|
||||
.about-facts { margin: 0; }
|
||||
|
||||
.guide-btn {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
@@ -6048,3 +6081,78 @@ figcaption {
|
||||
line-height: 1.7;
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
/* ---------------------------------------------------------- crash boundary */
|
||||
/* Shown instead of a blank page when rendering throws. Kept light on purpose:
|
||||
it must not depend on any component that could itself be broken. */
|
||||
.crash-screen {
|
||||
min-height: 100vh;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
padding: 24px;
|
||||
background: var(--bg);
|
||||
color: var(--text);
|
||||
}
|
||||
|
||||
.crash-card {
|
||||
width: min(560px, 100%);
|
||||
padding: 26px 28px;
|
||||
background: var(--panel);
|
||||
border: 1px solid var(--line);
|
||||
border-radius: var(--radius);
|
||||
box-shadow: 0 18px 60px rgba(0, 0, 0, 0.45);
|
||||
}
|
||||
|
||||
.crash-card h1 {
|
||||
margin: 0 0 10px;
|
||||
font-size: 18px;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.crash-card p {
|
||||
margin: 0 0 12px;
|
||||
color: var(--muted);
|
||||
line-height: 1.6;
|
||||
font-size: 13px;
|
||||
}
|
||||
|
||||
.crash-card .crash-message {
|
||||
padding: 10px 12px;
|
||||
border-left: 3px solid var(--danger);
|
||||
background: rgba(224, 93, 93, 0.08);
|
||||
color: var(--text);
|
||||
font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
|
||||
font-size: 12px;
|
||||
word-break: break-word;
|
||||
}
|
||||
|
||||
.crash-details {
|
||||
margin-top: 16px;
|
||||
color: var(--muted);
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
.crash-details summary {
|
||||
cursor: pointer;
|
||||
margin-bottom: 8px;
|
||||
}
|
||||
|
||||
.crash-details pre {
|
||||
max-height: 240px;
|
||||
overflow: auto;
|
||||
padding: 10px 12px;
|
||||
background: var(--bg);
|
||||
border: 1px solid var(--line);
|
||||
border-radius: var(--radius);
|
||||
white-space: pre-wrap;
|
||||
word-break: break-word;
|
||||
font-size: 11px;
|
||||
line-height: 1.5;
|
||||
}
|
||||
|
||||
.crash-card a.btn {
|
||||
text-decoration: none;
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
@@ -224,7 +224,7 @@ export interface Edits {
|
||||
* generated asset and is null until one exists; `amount` blends it over the
|
||||
* source. Separate from `noise`, which is a small GPU-side filter.
|
||||
*/
|
||||
aiDenoise: { amount: number; key: string | null; model: string };
|
||||
aiDenoise: { amount: number; key: string | null; model: 'guided' | 'nlm' | 'scunet' };
|
||||
/** fringe removal amounts for the two casts lens CA produces */
|
||||
defringe: { purple: number; green: number };
|
||||
/** spot healing, applied to the source before grading */
|
||||
@@ -320,13 +320,15 @@ export interface PhotoRecord {
|
||||
/** true when the original is a camera raw decoded by the server */
|
||||
raw?: boolean;
|
||||
/** how the editable proxy was produced */
|
||||
decode?: 'libraw' | 'embedded';
|
||||
decode?: 'libraw' | 'embedded' | 'sharp';
|
||||
/** server URL for the editable proxy (raw only) */
|
||||
previewUrl?: string;
|
||||
/** server URL for the grid thumbnail */
|
||||
thumbUrl?: string;
|
||||
/** Bumped when the stored RAW is re-decoded, to invalidate cached previews. */
|
||||
previewVersion?: number;
|
||||
/** Bytes of the server-written editable proxy (raw and TIFF imports). */
|
||||
proxyBytes?: number;
|
||||
/** set when this photo was imported from an Immich album */
|
||||
immich?: { albumId: string; assetId: string; checksum: string };
|
||||
/** timestamp of the last rendered client proof published to the server */
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
# syntax=docker/dockerfile:1
|
||||
#
|
||||
# Reproducible Windows bundle build on a Linux host.
|
||||
#
|
||||
# This image never touches the app's own Dockerfile or compose file; it exists
|
||||
# so the optional Windows artifact (including Luminary.exe, which needs Go) can
|
||||
# be produced from this machine:
|
||||
#
|
||||
# docker build -f windows/Dockerfile --output type=local,dest=/tmp/luminary-win .
|
||||
#
|
||||
# The output directory must be outside the checkout (see windows/README.md).
|
||||
# BuildKit is required for --output.
|
||||
#
|
||||
# `--output` exports the "artifacts" stage, which is `scratch`: only the bundle
|
||||
# zip, its checksum and the staged tree are copied out.
|
||||
|
||||
FROM node:24-bookworm AS build
|
||||
COPY --from=golang:1.23-bookworm /usr/local/go /usr/local/go
|
||||
ENV PATH="/usr/local/go/bin:${PATH}"
|
||||
|
||||
WORKDIR /src
|
||||
COPY . .
|
||||
|
||||
# Build-time dependencies for vite and tsc; the Windows runtime dependencies are
|
||||
# installed separately by build.mjs with --os=win32 --cpu=x64.
|
||||
RUN ONNXRUNTIME_NODE_INSTALL=skip npm ci --no-audit --no-fund
|
||||
|
||||
# --allow-dirty: the build context has no .git, so the worktree check is skipped.
|
||||
# The Go toolchain makes build.mjs produce Luminary.exe instead of the .cmd/.vbs
|
||||
# pair; pass --launcher ps to force the PowerShell-only launcher.
|
||||
RUN node windows/build.mjs --out /out --allow-dirty
|
||||
|
||||
FROM scratch AS artifacts
|
||||
COPY --from=build /out/ /
|
||||
@@ -0,0 +1,11 @@
|
||||
# Context for windows/Dockerfile. The app's own Dockerfile keeps using the root
|
||||
# .dockerignore; this file only affects Windows bundle builds.
|
||||
.git
|
||||
node_modules
|
||||
dist
|
||||
.check
|
||||
.smoke
|
||||
server/data
|
||||
windows/out
|
||||
*.log
|
||||
logo.png
|
||||
@@ -0,0 +1,372 @@
|
||||
# Windows bundle (optional)
|
||||
|
||||
An additive, self-contained way to produce a double-clickable Windows install of
|
||||
Luminary. The server and Docker workflow stay the source of truth: this folder
|
||||
only *packages* the existing `dist/` + `server/` output, and the build writes
|
||||
its artifacts **outside the checkout**.
|
||||
|
||||
- Design of the launcher: [launcher/DESIGN.md](launcher/DESIGN.md)
|
||||
- Moving this into its own repository: [SEPARATE-REPO.md](SEPARATE-REPO.md)
|
||||
|
||||
## Isolation guarantees
|
||||
|
||||
1. **The packaging tree is additive.** There is no `package.json` script for
|
||||
this, and no change to `.gitignore`, `.dockerignore`, `Dockerfile`,
|
||||
`docker-compose.yml` or `scripts/deploy.mjs`. Invoke it directly:
|
||||
`node windows/build.mjs`. The one app-side addition is an opt-in desktop mode
|
||||
in `server/config.mjs` + `server/index.mjs` (`LUMINARY_LOCAL=1`): a single
|
||||
passwordless local admin. It is off unless the Windows launcher sets it, so
|
||||
Docker and the shared server are unchanged.
|
||||
2. **Artifacts live outside the repo** (default: `~/.cache/luminary-windows`, or
|
||||
`%LOCALAPPDATA%\Luminary\build` on Windows). The script refuses an `--out`
|
||||
inside the checkout, because `scripts/deploy.mjs` rsyncs the worktree to
|
||||
production and `docker build` would pull a ~300 MB bundle into its context.
|
||||
3. **The worktree must be clean outside `windows/`** before and after a build
|
||||
(the untracked `logo.png` is tolerated). `--allow-dirty` overrides it.
|
||||
4. **Nothing in the app changes at run time.** The bundle is the unchanged
|
||||
`server/` + `dist/` + production `node_modules`, started with `PORT`, `HOST`,
|
||||
`NODE_ENV` and `LUMINARY_DATA` — all variables the server already reads.
|
||||
|
||||
## What the end user needs
|
||||
|
||||
Nothing to install. This was audited from the shipped binaries' own PE imports,
|
||||
not assumed:
|
||||
|
||||
| Component | What it needs on the target PC |
|
||||
| --- | --- |
|
||||
| `node.exe` (v24.22.2) | only Windows system DLLs (`KERNEL32`, `ADVAPI32`, `WS2_32`, `CRYPT32`, `USER32`, …) — statically linked C runtime, so **no Visual C++ Redistributable** |
|
||||
| `libvips-42.dll` + `sharp` | the Universal C Runtime (`api-ms-win-crt-*`), included in Windows 10/11; older Windows needs KB2999226 |
|
||||
| `libraw.wasm` | a browser with WebAssembly |
|
||||
| launcher (`.cmd`/`.vbs`) | Windows PowerShell 5.1, included in Windows 10/11 |
|
||||
| Develop module | a current browser with WebGL2 (Edge, Chrome, Firefox) |
|
||||
|
||||
So: a clean Windows 10/11 x64 machine, a browser, and ~250 MB where the data
|
||||
folder lives. No VC++ redist, no .NET, no admin prompt. The setup exe installs
|
||||
for the current user only; the portable zip needs no installer at all.
|
||||
|
||||
What the launcher checks on every start (and `-Status` prints):
|
||||
|
||||
- Windows build ≥ 10240, `PROCESSOR_ARCHITECTURE` of `AMD64`/`ARM64`, UCRT
|
||||
present, and free space on the data drive. Windows older than 10 is refused
|
||||
with a specific message and link, exit code `4`.
|
||||
- Missing `node.exe` → offers to download it from nodejs.org and verifies the
|
||||
SHA-256 in `version.txt` before installing (same code as `-Repair`).
|
||||
- Missing `node.exe` but a system Node 24+ exists → starts on it, says which
|
||||
one, and points at `-Repair`.
|
||||
|
||||
Official links, shown in the dialogs when relevant:
|
||||
[Windows 10/11](https://www.microsoft.com/software-download/windows11) ·
|
||||
[Universal C Runtime / KB2999226](https://support.microsoft.com/help/2999226) ·
|
||||
[Microsoft Edge](https://www.microsoft.com/edge).
|
||||
|
||||
## Requirements (build host)
|
||||
|
||||
| Need | Why |
|
||||
| --- | --- |
|
||||
| Node.js 24 | the builder itself, and `npm run build` for `dist/` |
|
||||
| `npm` with `--os`/`--cpu` support (npm ≥ 10) | installs the `sharp` **win32-x64** prebuild from Linux |
|
||||
| Network | `node.exe` from nodejs.org (SHA-256 checked) and the npm registry |
|
||||
| Optional: Go 1.21+ | builds `Luminary.exe`; without it the PowerShell launcher ships |
|
||||
| Optional: Docker + BuildKit | the reproducible path, and the only way to get the Go exe on Linux |
|
||||
| Optional: NSIS 3 | builds the setup exe; `--installer` unpacks a private copy on Linux when `makensis` is absent |
|
||||
|
||||
No Windows machine is required for either the portable zip or the setup exe:
|
||||
NSIS cross-compiles the installer on Linux and macOS.
|
||||
|
||||
## Build
|
||||
|
||||
```bash
|
||||
node windows/build.mjs # npm run build, then the bundle
|
||||
node windows/build.mjs --skip-build # reuse the existing dist/
|
||||
node windows/build.mjs --out /srv/builds/luminary-win
|
||||
node windows/build.mjs --launcher go # fail unless Go is installed
|
||||
node windows/build.mjs --installer # also build the setup exe (NSIS)
|
||||
node windows/build.mjs --skip-build --publish # copy the zip and setup to windows/releases
|
||||
```
|
||||
|
||||
Output:
|
||||
|
||||
```
|
||||
<out>/
|
||||
Luminary-0.5.2-win-x64.zip the portable deliverable
|
||||
installer/Luminary-0.5.2-win-x64-setup.exe the per-user installer
|
||||
stage/Luminary/ the unpacked bundle (kept for inspection)
|
||||
cache/node-v24.22.2-win-x64.exe pinned runtime, reused next time
|
||||
cache/SHASUMS256-v24.22.2.txt
|
||||
```
|
||||
|
||||
The build prints each artifact's size and SHA-256, the Node version, the
|
||||
launcher kind and the staged folder. The setup exe is built whenever `makensis`
|
||||
is found (or with `--installer`, which fetches NSIS on Linux); otherwise the zip
|
||||
is built alone with a warning.
|
||||
|
||||
### Transferring it to Windows
|
||||
|
||||
`--publish` copies the finished zip and a `SHA256SUMS.txt` into
|
||||
[`releases/`](releases/), which is the hand-off folder for a USB stick, network
|
||||
share or release upload:
|
||||
|
||||
```bash
|
||||
node windows/build.mjs --skip-build --publish
|
||||
```
|
||||
|
||||
It is the only write the builder makes inside the checkout; staging and zipping
|
||||
still happen outside it. On the Windows PC: extract the zip, then run
|
||||
`Luminary.cmd` or `Luminary.vbs` from the extracted `Luminary` folder. Note that
|
||||
`scripts/deploy.mjs` rsyncs the worktree, so remove the zip from `releases/`
|
||||
after transferring if you do not want it on the server.
|
||||
|
||||
### Reproducible path with Docker
|
||||
|
||||
```bash
|
||||
docker build -f windows/Dockerfile --output type=local,dest=/srv/builds/luminary-win .
|
||||
```
|
||||
|
||||
The image has Node 24 **and** Go, so it produces `Luminary.exe`. The final stage
|
||||
is `scratch`, so `--output` exports only the zip, checksum and staged bundle.
|
||||
`windows/Dockerfile.dockerignore` keeps `.git`, `node_modules` and `dist` out of
|
||||
the context; the app's own `Dockerfile` is unaffected.
|
||||
|
||||
### Installer
|
||||
|
||||
`windows/installer.nsi` wraps the same staged bundle in an NSIS setup exe. NSIS
|
||||
is a cross-compiler, so this builds on the Linux host as well as on Windows:
|
||||
|
||||
```bash
|
||||
node windows/build.mjs --installer # or --skip-build --installer
|
||||
```
|
||||
|
||||
`--installer` uses `makensis` from `PATH` or `$MAKENSIS`; if neither exists on
|
||||
Linux it downloads the two Ubuntu `nsis` packages into `<out>/tools/nsis` and
|
||||
runs them from there, so no root install is needed. Install it yourself with
|
||||
`sudo apt install nsis`, `brew install makensis`, or the Windows installer from
|
||||
<https://nsis.sourceforge.io>. Compile by hand with:
|
||||
|
||||
```bash
|
||||
makensis -DAPP_VERSION=0.5.2 -DAPP_VERSION4=0.5.2.0 \
|
||||
-DSOURCE_DIR="$PWD/stage/Luminary" windows/installer.nsi
|
||||
```
|
||||
|
||||
The setup is per-user: **no UAC prompt**, nothing in Program Files. It installs
|
||||
to `%LOCALAPPDATA%\Programs\Luminary`, creates Start-menu shortcuts (Luminary,
|
||||
Stop Luminary, the data folder), an optional desktop shortcut and an optional
|
||||
"start at login" (`HKCU\…\Run`), registers an uninstaller in Apps & features,
|
||||
and **keeps** `%LOCALAPPDATA%\Luminary\data` when uninstalled. Before replacing
|
||||
files it runs the bundle's own `Luminary.ps1 -Stop`, so an upgrade over a
|
||||
running copy works without killing every `node.exe` on the machine.
|
||||
|
||||
Silent install and uninstall, for a script or a school lab image:
|
||||
|
||||
```bat
|
||||
Luminary-0.5.2-win-x64-setup.exe /S
|
||||
"%LOCALAPPDATA%\Programs\Luminary\Uninstall.exe" /S
|
||||
```
|
||||
|
||||
`/D=C:\path` overrides the install folder (last argument, unquoted, as NSIS
|
||||
requires). The installer refuses 32-bit Windows and anything before Windows 10,
|
||||
the same limits as the launcher, but says so before copying 250 MB.
|
||||
|
||||
## What is in the bundle
|
||||
|
||||
```
|
||||
Luminary/
|
||||
node.exe Node 24 win-x64, verified against nodejs.org
|
||||
Luminary.ps1 start / -Stop / -Status / -Verify / -Repair / -Browser
|
||||
Luminary.cmd visible-console entry point
|
||||
Luminary.vbs no-console entry point
|
||||
Stop Luminary.cmd
|
||||
Luminary.exe only with a Go toolchain
|
||||
LuminaryWindow.exe optional native WebView2 window (--webview2)
|
||||
Luminary.ico icon for shortcuts and the installer
|
||||
version.txt version, commit, launcher, and the Node pin (version, SHA-256, size)
|
||||
README-windows.txt end-user instructions
|
||||
LICENSE, THIRD_PARTY_NOTICES.md, licenses/
|
||||
app/
|
||||
server/ unchanged, minus server/data and *.test.mjs
|
||||
dist/ the normal Vite build (UI, lens db, guide PDF)
|
||||
package.json provenance
|
||||
package-lock.json
|
||||
node_modules/ production deps installed with --os=win32 --cpu=x64
|
||||
runtime.json created on first start
|
||||
logs/ created on first start
|
||||
```
|
||||
|
||||
`sharp` is installed from the repository's own lockfile, so the Windows native
|
||||
package (`@img/sharp-win32-x64`) matches the version the app was tested with.
|
||||
The build verifies that its `.node` binary is present and only warns if not —
|
||||
the server degrades to PNG proxies rather than failing to boot.
|
||||
|
||||
## Running it
|
||||
|
||||
Double-click `Luminary.cmd` (brief console) or `Luminary.vbs` (silent). The
|
||||
launcher picks a free loopback port starting at 8787, sets
|
||||
`LUMINARY_DATA=%LOCALAPPDATA%\Luminary\data`, starts `node.exe` hidden, waits for
|
||||
`/api/health`, then opens the browser. `Stop Luminary.cmd` stops it;
|
||||
`Luminary.ps1 -Status` reports PID, URL, runtime and data folder.
|
||||
|
||||
### Single-user desktop mode
|
||||
|
||||
The launcher starts the server with `LUMINARY_LOCAL=1`:
|
||||
|
||||
- one admin (`local@luminary`) is created on first start and reused afterwards;
|
||||
- `/api/auth/me` answers without a cookie, so the UI never shows signup or
|
||||
sign-in, and registration returns 403;
|
||||
- the account is an admin, so every panel works; it cannot be renamed, disabled
|
||||
or deleted from the UI (403), and there is no password to remember;
|
||||
- the password is random and never shown, and the server binds `127.0.0.1`, so
|
||||
this is not reachable from the network. Starting with `HOST=0.0.0.0` and
|
||||
`LUMINARY_LOCAL=1` logs a warning at boot.
|
||||
|
||||
Without the variable, accounts, invites and email behave exactly as before —
|
||||
Docker and the shared server are untouched.
|
||||
|
||||
### App window
|
||||
|
||||
Instead of a tab, the launcher opens a chromeless window from the browser that
|
||||
is already installed:
|
||||
|
||||
```
|
||||
msedge.exe --app=http://127.0.0.1:8787 --user-data-dir=%LOCALAPPDATA%\Luminary\data\window-profile
|
||||
```
|
||||
|
||||
No tabs, no address bar, its own profile, and it remembers its window size.
|
||||
Edge ships with Windows 10/11, so nothing is installed; Chrome is the fallback
|
||||
and the default browser is the last resort. `Luminary.cmd -Browser` (or
|
||||
`LUMINARY_WINDOW=browser`) opens a normal tab instead.
|
||||
|
||||
A fully native window is available too: `windows/launcher/webview2` is a small
|
||||
WinForms host around WebView2 that owns its title bar, taskbar icon and window
|
||||
state. When the bundle contains `LuminaryWindow.exe`, the launcher uses it
|
||||
ahead of the browser window. Build it once (self-contained, no .NET needed on
|
||||
the target machine):
|
||||
|
||||
```bash
|
||||
mkdir -p /tmp/wv
|
||||
docker run --rm -v "$PWD/windows/launcher:/src" -v /tmp/wv:/out \
|
||||
-w /src/webview2 mcr.microsoft.com/dotnet/sdk:8.0 \
|
||||
dotnet publish -c Release -o /out
|
||||
node windows/build.mjs --webview2 /tmp/wv/LuminaryWindow.exe --publish
|
||||
```
|
||||
|
||||
It needs the Microsoft Edge **WebView2 runtime**, which ships with Windows
|
||||
10/11 alongside Edge; if it is ever missing, the window says so and links the
|
||||
Evergreen installer. The exe adds roughly 70 MB to the zip, which is why it is
|
||||
opt-in rather than always shipped.
|
||||
|
||||
Double-clicking `LuminaryWindow.exe` directly is safe too. Without `--url` it
|
||||
starts the bundle launcher and exits; the launcher then starts desktop mode and
|
||||
reopens the window with `--url`. It uses `Luminary.exe` when the Go build ships
|
||||
one, otherwise it runs `Luminary.ps1` through a hidden PowerShell process. That
|
||||
avoids `Luminary.vbs` and Windows Script Host, which some machines disable by
|
||||
policy. If the exe is copied out of a complete bundle, it explains that it is
|
||||
only the window rather than showing a signed-out page.
|
||||
|
||||
`Luminary.cmd -Verify` checks the bundle. `Luminary.cmd -Repair` re-downloads
|
||||
`node.exe` from nodejs.org and installs it only after the SHA-256 matches
|
||||
`version.txt` — the fix for an antivirus that quarantined the runtime. If
|
||||
the bundled `node.exe` is gone and a system Node 24+ exists, the app still
|
||||
starts on that runtime (with a warning) while you decide to repair.
|
||||
|
||||
Full behaviour, edge cases and the test checklist: [launcher/DESIGN.md](launcher/DESIGN.md).
|
||||
|
||||
## Data, updates and backups
|
||||
|
||||
- Catalog, originals, previews and `secret.key` live in
|
||||
`%LOCALAPPDATA%\Luminary\data` — never under `app\`, so an update cannot lose
|
||||
them.
|
||||
- Update: stop Luminary, replace `app\` (and `node.exe` when it changes) from a
|
||||
newer bundle, start again. The SQLite schema migrates on boot.
|
||||
- Back up: copy the whole data folder while Luminary is stopped, including
|
||||
`lumenroom.db`, `lumenroom.db-wal`, `lumenroom.db-shm`.
|
||||
|
||||
## Verifying a build
|
||||
|
||||
```bash
|
||||
cd <out>
|
||||
sha256sum Luminary-0.5.2-win-x64.zip
|
||||
unzip -t Luminary-0.5.2-win-x64.zip | tail -1
|
||||
unzip -l Luminary-0.5.2-win-x64.zip | grep -E 'node.exe|Luminary\.(exe|cmd|vbs)|app/server/index.mjs'
|
||||
```
|
||||
|
||||
On Windows, the real test is the checklist in `launcher/DESIGN.md` §15,
|
||||
especially a machine with **no Node installed**. The automated first pass is
|
||||
[`SMOKE-WINDOWS.ps1`](SMOKE-WINDOWS.ps1), run from the extracted bundle:
|
||||
|
||||
```bat
|
||||
powershell -ExecutionPolicy Bypass -File .\SMOKE-WINDOWS.ps1
|
||||
```
|
||||
|
||||
It checks the OS and WebView2 runtime, `-Verify`, a real desktop-mode boot
|
||||
(`local:true`, cookieless `/api/auth/me`, `/api/sync`), the native window
|
||||
launching and owning a window titled Luminary, and Stop — then writes
|
||||
`smoke-report.txt` next to the bundle.
|
||||
|
||||
## When the launcher says the bundle is incomplete
|
||||
|
||||
The bundle is a folder: `node.exe`, `Luminary.*`, and `app\server`, `app\dist`,
|
||||
`app\node_modules`. The launcher checks those three trees before starting and
|
||||
prints which one is missing:
|
||||
|
||||
- **Opened from the zip preview** — Windows extracts only the file you double-
|
||||
clicked into `%TEMP%`, so `node.exe` and `app\` are absent. Extract the whole
|
||||
zip first (right-click → "Extract All...").
|
||||
- **Antivirus/SmartScreen removed `node.exe`** — common with a freshly
|
||||
downloaded, unsigned Node runtime. Restore it from quarantine, or unblock the
|
||||
zip and extract again. `version.txt` carries the exact SHA-256 so a restored
|
||||
copy can be checked: the build verified the same hash against
|
||||
`nodejs.org/dist/<version>/SHASUMS256.txt`.
|
||||
- **Running the source launcher** — `windows\launcher\Luminary.cmd` is a template
|
||||
for the builder, not an install. Run `node windows/build.mjs` and use the zip.
|
||||
|
||||
`Luminary.cmd -Verify` prints the resolved bundle path, the size of each
|
||||
required file, the pinned Node version and the Luminary version, and exits `3`
|
||||
when something is missing or `node.exe` has the wrong size. The Go launcher
|
||||
shows the same message in a dialog box because it has no console.
|
||||
|
||||
### Repairing `node.exe`
|
||||
|
||||
```bat
|
||||
Luminary.cmd -Repair
|
||||
```
|
||||
|
||||
Reads the version and hash from `version.txt` (falling back to the published
|
||||
`SHASUMS256.txt`), downloads into a temp file, verifies the SHA-256, and only
|
||||
then replaces `node.exe`. It refuses while Luminary is running. Set
|
||||
`LUMINARY_NODE_URL` to use a mirror or an internal copy for air-gapped machines.
|
||||
`Luminary.exe -repair` does the same.
|
||||
|
||||
## Limitations
|
||||
|
||||
- The launcher is unsigned: SmartScreen may ask once, and a strict antivirus
|
||||
policy can quarantine `node.exe`; `-Repair` restores it, and the launcher can
|
||||
fall back to a system Node 24+ in the meantime.
|
||||
- No tray icon and no auto-update in this version (both are launcher features,
|
||||
not app changes).
|
||||
- Loopback only by default; set `HOST=0.0.0.0` for LAN proofing galleries.
|
||||
- The PowerShell launcher cannot clean up after a server crash; a stale
|
||||
`runtime.json` is simply ignored on the next start.
|
||||
- The setup exe cannot be executed on the Linux build host. It is verified by
|
||||
unpacking it and comparing the SHA-256 of every payload file with the staged
|
||||
bundle, plus `SMOKE-WINDOWS.ps1` for the installed tree; a real install and
|
||||
uninstall still needs one pass on Windows.
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
| Symptom | Check |
|
||||
| --- | --- |
|
||||
| "node.exe is missing" / "this folder is not a complete Luminary bundle" | run `Luminary.cmd -Verify`. Usual causes: the zip was opened instead of extracted (right-click → Extract All), antivirus removed `node.exe` after extraction, or `Luminary.cmd` was run from the source `windows\launcher` folder instead of the built bundle. For the antivirus case run `Luminary.cmd -Repair` |
|
||||
| Launch says it is using the system Node | the bundled `node.exe` is missing or truncated; `Luminary.cmd -Repair` restores the pinned runtime |
|
||||
| `Repair failed` | no network, a proxy blocking `nodejs.org`, or a checksum mismatch (nothing is installed in that case). Point `LUMINARY_NODE_URL` at a mirror of `node.exe` |
|
||||
| "Luminary needs Windows 10 or 11" (exit 4) | the launcher read `CurrentBuild` below 10240. The app targets Windows 10/11; there is no Windows 7/8 build |
|
||||
| "The Universal C Runtime is missing" | Windows 8.1 without KB2999226 — install <https://support.microsoft.com/help/2999226> or use Windows 10/11 |
|
||||
| "The data drive has only … GB free" | free space before starting; catalogs and previews grow in `%LOCALAPPDATA%` |
|
||||
| "did not answer on /api/health" | `logs\server.err.log`; run `node app\server\index.mjs` from `app\` to see the failure |
|
||||
| Browser opens an error page | the port was taken between the check and the spawn; start again |
|
||||
| RAW import fails | `app\node_modules\@img\sharp-win32-x64` must contain a `.node` binary; RAW decode itself is wasm |
|
||||
| `node.exe failed its SHA-256 check` | delete `<out>/cache` and rebuild (the download was truncated) |
|
||||
| A sign-in screen appears | the server was started without `LUMINARY_LOCAL=1`, or it is the normal server, not the bundle |
|
||||
| Opens as a normal tab | Edge/Chrome not found, or `-Browser` / `LUMINARY_WINDOW=browser` was used |
|
||||
| Build refuses `--out` | the path is inside the repo; choose one outside |
|
||||
| SmartScreen on first run | unsigned build: "More info" → "Run anyway" (same for the setup exe) |
|
||||
| The setup exe closes immediately on 32-bit Windows | it needs a 64-bit Windows 10/11 install; use the 64-bit build |
|
||||
| Installed, but no catalog after uninstall | that is intentional: `%LOCALAPPDATA%\Luminary\data` is kept |
|
||||
@@ -0,0 +1,149 @@
|
||||
# Separate packaging repository (`luminary-windows`)
|
||||
|
||||
This is the fallback path if the `windows/` folder in this repo ever feels too
|
||||
close to the app: a second repository that builds the same bundle from a pinned
|
||||
upstream tag. It is a plan, not something that exists yet.
|
||||
|
||||
## Why a packaging repo and not a fork
|
||||
|
||||
A fork duplicates the app and forces a merge of every upstream change. Nothing
|
||||
in Luminary is Windows-specific — the server is plain ESM, `node:sqlite` and
|
||||
`sharp`/`libraw-wasm` ship Windows builds, and the only POSIX-ism
|
||||
(`secret.key` mode `0o600`) is ignored by Windows. The Windows work is
|
||||
therefore *packaging*: a fixed folder layout, a Node runtime, a launcher and an
|
||||
artifact. A packaging repo keeps that work under a separate review and release
|
||||
process while consuming the app unchanged.
|
||||
|
||||
A fork remains justified only if a Windows build ever needs an app patch
|
||||
(behaviour, not packaging). If that happens, the change belongs upstream in the
|
||||
main repo first.
|
||||
|
||||
## Repository layout
|
||||
|
||||
```
|
||||
luminary-windows/
|
||||
upstream.txt # pinned tag + commit + expected package version
|
||||
build.mjs # same script as windows/build.mjs, one copy
|
||||
launcher/ # Luminary.ps1, .cmd, .vbs, Stop, go/
|
||||
installer.nsi # NSIS, builds on Linux
|
||||
Dockerfile # Go + Node 24 image for the exe build
|
||||
README.md
|
||||
CHANGELOG.md # per-release: upstream tag, node version, hashes
|
||||
```
|
||||
|
||||
`build.mjs` is copied verbatim from the main repo when it changes; there is no
|
||||
second implementation to drift.
|
||||
|
||||
## Pinning
|
||||
|
||||
`upstream.txt`:
|
||||
|
||||
```
|
||||
repo=https://git.maple-street.net/bhursey/luminary.git
|
||||
tag=v0.5.2
|
||||
commit=fb43ca8f1c2d… # full sha
|
||||
version=0.5.2 # package.json version, checked after fetch
|
||||
node=v24.22.2
|
||||
```
|
||||
|
||||
The build clones the upstream repository at the pinned commit (shallow clone of
|
||||
the tag, then `git rev-parse HEAD` must equal `commit`) into a work directory
|
||||
outside both repos, for example:
|
||||
|
||||
```
|
||||
$TMP/luminary-upstream/
|
||||
```
|
||||
|
||||
If the tag moves or the commit does not match, the build fails rather than
|
||||
silently shipping something else. A `--upstream-ref <sha>` flag allows a
|
||||
one-off build from a newer commit before the pin is updated.
|
||||
|
||||
## Build flow
|
||||
|
||||
```
|
||||
fetch pinned upstream (clone/verify)
|
||||
→ npm ci (dev deps, needed for vite)
|
||||
→ npm run build (typecheck + dist/)
|
||||
→ stage: dist, server, production node_modules (--os=win32 --cpu=x64),
|
||||
node.exe (SHA-256 verified), launcher, licences
|
||||
→ zip + sha256
|
||||
→ optional: iscc installer
|
||||
```
|
||||
|
||||
Exactly the same steps as `windows/build.mjs`; the only difference is where
|
||||
`dist/`, `server/` and `package.json` come from (a work tree, not `../`).
|
||||
|
||||
## CI (Gitea Actions, since the remote is Gitea)
|
||||
|
||||
`.gitea/workflows/windows.yml` in the packaging repo:
|
||||
|
||||
```yaml
|
||||
name: windows-bundle
|
||||
on:
|
||||
workflow_dispatch:
|
||||
push:
|
||||
tags: ['v*']
|
||||
jobs:
|
||||
build:
|
||||
runs-on: ubuntu-latest # or a Windows runner for the installer
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-node@v4
|
||||
with: { node-version: 24 }
|
||||
- run: node build.mjs --out "$RUNNER_TEMP/out"
|
||||
- run: sha256sum Luminary-*.zip >> "$RUNNER_TEMP/out/SHA256SUMS"
|
||||
working-directory: ${{ runner.temp }}/out
|
||||
- uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: luminary-windows-${{ github.ref_name }}
|
||||
path: ${{ runner.temp }}/out/*
|
||||
```
|
||||
|
||||
Optional later steps: `softprops/action-gh-release` to attach the zip and setup
|
||||
exe to a Gitea release. NSIS runs on the Linux runner too (`--installer`), so a
|
||||
Windows runner is not needed for the installer.
|
||||
|
||||
## Release and version policy
|
||||
|
||||
- One packaging release per upstream tag that should be installable on Windows;
|
||||
the artifacts are `Luminary-<version>-win-x64-setup.exe` and the portable
|
||||
`Luminary-<version>-win-x64.zip`.
|
||||
- `CHANGELOG.md` records upstream tag/commit, bundled Node version, artifact
|
||||
SHA-256 and any launcher change.
|
||||
- Security fixes: when upstream ships one, the pin moves, the packaging tag
|
||||
increments (`v1.0.1-win.1` style if needed) and the artifact is rebuilt.
|
||||
- Windows-only changes (launcher, installer) release independently — they do not
|
||||
require an upstream bump, because they never touch `app/`.
|
||||
|
||||
## Updating users
|
||||
|
||||
The bundle is portable: replacing `app\` and `node.exe` is the update. Keep the
|
||||
data folder (`%LOCALAPPDATA%\Luminary\data`) untouched. A future auto-updater
|
||||
would read a small JSON manifest beside the release and download the zip; that
|
||||
is a packaging-repo feature, not an app change.
|
||||
|
||||
## Migration from the in-repo `windows/` folder
|
||||
|
||||
1. Create the new repo.
|
||||
2. Copy `windows/` to its root (`build.mjs`, `launcher/`, `installer.nsi`,
|
||||
`Dockerfile`, this plan and `README.md`), adjusting the input paths in
|
||||
`build.mjs` to the fetched upstream work tree.
|
||||
3. Add `upstream.txt`, the CI workflow, `CHANGELOG.md`.
|
||||
4. Build once from the pinned tag and compare the zip contents with the
|
||||
in-repo build (same files, same launcher) before publishing.
|
||||
5. Optionally delete `windows/` from the main repo afterwards; nothing in the
|
||||
app depends on it.
|
||||
|
||||
## Trade-offs
|
||||
|
||||
| | In-repo `windows/` (current) | Separate repo |
|
||||
| --- | --- | --- |
|
||||
| Upstream awareness | always the local checkout | explicit pin, can lag |
|
||||
| Review/CI noise | one extra folder | separate pipeline |
|
||||
| Release discipline | none required | tag + changelog per artifact |
|
||||
| Risk to the app | none (folder only) | none (no files in the app repo) |
|
||||
| Effort | zero extra repos | one more repo and workflow |
|
||||
|
||||
Stay with the in-repo folder while the Windows build changes infrequently;
|
||||
move to this layout when it needs its own release cadence or a second
|
||||
maintainer.
|
||||
@@ -0,0 +1,179 @@
|
||||
<#
|
||||
One-command smoke test for an extracted Luminary bundle on Windows.
|
||||
|
||||
Run it from the extracted bundle folder (or pass -Bundle):
|
||||
|
||||
powershell -ExecutionPolicy Bypass -File .\SMOKE-WINDOWS.ps1
|
||||
|
||||
It writes smoke-report.txt next to the bundle and prints the same lines.
|
||||
Exit code 0 means every check passed.
|
||||
|
||||
What it covers without a human clicking:
|
||||
- OS version and architecture, and whether the WebView2 runtime is present
|
||||
- the bundle files the launcher needs, and -Verify's own result
|
||||
- a real server boot in desktop mode: /api/health local:true,
|
||||
/api/auth/me 200 without a cookie, /api/sync 200
|
||||
- LuminaryWindow.exe launching, staying alive and owning a window titled
|
||||
Luminary (the native WebView2 path)
|
||||
- Stop actually stopping the server
|
||||
|
||||
It is deliberately conservative: it uses a throwaway data folder under
|
||||
%TEMP% and a port that is unlikely to collide, so it never touches a real
|
||||
catalog.
|
||||
#>
|
||||
[CmdletBinding()]
|
||||
param(
|
||||
[string]$Bundle = (Split-Path -Parent $MyInvocation.MyCommand.Path),
|
||||
[int]$Port = 8912,
|
||||
[int]$WindowSeconds = 8
|
||||
)
|
||||
|
||||
$ErrorActionPreference = 'Stop'
|
||||
$script:lines = @()
|
||||
$script:failed = 0
|
||||
|
||||
function Say([string]$text) {
|
||||
$script:lines += $text
|
||||
Write-Host $text
|
||||
}
|
||||
|
||||
function Check([string]$name, [bool]$ok, [string]$detail = '') {
|
||||
if ($ok) {
|
||||
Say (" PASS {0}{1}" -f $name, $(if ($detail) { " — $detail" } else { '' }))
|
||||
} else {
|
||||
$script:failed += 1
|
||||
Say (" FAIL {0}{1}" -f $name, $(if ($detail) { " — $detail" } else { '' }))
|
||||
}
|
||||
return $ok
|
||||
}
|
||||
|
||||
function Get-WebView2Version {
|
||||
$keys = @(
|
||||
'HKLM:\SOFTWARE\WOW6432Node\Microsoft\EdgeUpdate\Clients\{F3017226-FE2A-4295-8BDF-00C3A9A7E4C5}',
|
||||
'HKLM:\SOFTWARE\Microsoft\EdgeUpdate\Clients\{F3017226-FE2A-4295-8BDF-00C3A9A7E4C5}',
|
||||
'HKCU:\SOFTWARE\Microsoft\EdgeUpdate\Clients\{F3017226-FE2A-4295-8BDF-00C3A9A7E4C5}'
|
||||
)
|
||||
foreach ($key in $keys) {
|
||||
try {
|
||||
$value = (Get-ItemProperty -Path $key -Name pv -ErrorAction Stop).pv
|
||||
if ($value) { return $value }
|
||||
} catch { }
|
||||
}
|
||||
return $null
|
||||
}
|
||||
|
||||
$nodeExe = Join-Path $Bundle 'node.exe'
|
||||
$appDir = Join-Path $Bundle 'app'
|
||||
$entry = Join-Path $appDir 'server\index.mjs'
|
||||
$windowExe = Join-Path $Bundle 'LuminaryWindow.exe'
|
||||
$launcher = Join-Path $Bundle 'Luminary.ps1'
|
||||
$dataDir = Join-Path $env:TEMP ('luminary-smoke-{0}' -f [guid]::NewGuid().ToString('N'))
|
||||
$url = "http://127.0.0.1:$Port"
|
||||
$server = $null
|
||||
$window = $null
|
||||
|
||||
Say 'Luminary Windows smoke test'
|
||||
Say (" bundle {0}" -f $Bundle)
|
||||
Say (" time {0}" -f (Get-Date).ToString('s'))
|
||||
|
||||
try {
|
||||
$os = Get-CimInstance Win32_OperatingSystem
|
||||
Say ''
|
||||
Say 'Environment'
|
||||
Say (" OS {0} (build {1})" -f $os.Caption, $os.BuildNumber)
|
||||
Say (" arch {0}" -f $env:PROCESSOR_ARCHITECTURE)
|
||||
$webview2 = Get-WebView2Version
|
||||
Say (" webview {0}" -f $(if ($webview2) { "runtime $webview2" } else { 'NOT INSTALLED' }))
|
||||
|
||||
Say ''
|
||||
Say 'Bundle'
|
||||
Check 'node.exe present' (Test-Path -LiteralPath $nodeExe) $nodeExe
|
||||
Check 'app\server\index.mjs present' (Test-Path -LiteralPath $entry) $entry
|
||||
Check 'Luminary.ps1 present' (Test-Path -LiteralPath $launcher) $launcher
|
||||
Check 'LuminaryWindow.exe present' (Test-Path -LiteralPath $windowExe) $windowExe
|
||||
if (Test-Path -LiteralPath $launcher) {
|
||||
$verify = Start-Process -FilePath 'powershell.exe' -ArgumentList @(
|
||||
'-NoProfile', '-ExecutionPolicy', 'Bypass', '-File', $launcher, '-Verify'
|
||||
) -Wait -PassThru -WindowStyle Hidden
|
||||
Check '-Verify exits 0' ($verify.ExitCode -eq 0) ("exit {0}" -f $verify.ExitCode)
|
||||
}
|
||||
|
||||
if (-not (Test-Path -LiteralPath $nodeExe)) { throw 'node.exe is missing, cannot start the server' }
|
||||
if (-not (Test-Path -LiteralPath $entry)) { throw 'app\server\index.mjs is missing, cannot start the server' }
|
||||
|
||||
New-Item -ItemType Directory -Force -Path $dataDir | Out-Null
|
||||
$env:PORT = "$Port"
|
||||
$env:HOST = '127.0.0.1'
|
||||
$env:NODE_ENV = 'production'
|
||||
$env:LUMINARY_DATA = $dataDir
|
||||
$env:LUMINARY_LOCAL = '1'
|
||||
|
||||
Say ''
|
||||
Say 'Server (desktop mode)'
|
||||
$server = Start-Process -FilePath $nodeExe -ArgumentList @('"' + $entry + '"') `
|
||||
-WorkingDirectory $appDir -WindowStyle Hidden -PassThru `
|
||||
-RedirectStandardOutput (Join-Path $dataDir 'out.log') `
|
||||
-RedirectStandardError (Join-Path $dataDir 'err.log')
|
||||
|
||||
$deadline = (Get-Date).AddSeconds(90)
|
||||
$health = $null
|
||||
while ((Get-Date) -lt $deadline) {
|
||||
try {
|
||||
$response = Invoke-WebRequest -UseBasicParsing -TimeoutSec 2 -Uri "$url/api/health"
|
||||
if ($response.StatusCode -eq 200) { $health = $response.Content | ConvertFrom-Json; break }
|
||||
} catch { }
|
||||
Start-Sleep -Milliseconds 500
|
||||
}
|
||||
Check 'health answers' ($null -ne $health)
|
||||
if ($health) {
|
||||
Check 'local mode advertised' ($health.local -eq $true) ("local={0}" -f $health.local)
|
||||
Check 'no setup prompt' ($health.needsSetup -eq $false)
|
||||
Check 'registration closed' ($health.registrationOpen -eq $false)
|
||||
}
|
||||
try {
|
||||
$me = Invoke-WebRequest -UseBasicParsing -TimeoutSec 5 -Uri "$url/api/auth/me"
|
||||
$who = $me.Content | ConvertFrom-Json
|
||||
Check 'signed in without a cookie' ($me.StatusCode -eq 200) ("{0} ({1})" -f $who.user.email, $who.user.role)
|
||||
} catch {
|
||||
Check 'signed in without a cookie' $false $_.Exception.Message
|
||||
}
|
||||
try {
|
||||
$sync = Invoke-WebRequest -UseBasicParsing -TimeoutSec 15 -Uri "$url/api/sync"
|
||||
Check '/api/sync answers' ($sync.StatusCode -eq 200)
|
||||
} catch {
|
||||
Check '/api/sync answers' $false $_.Exception.Message
|
||||
}
|
||||
|
||||
Say ''
|
||||
Say 'Window (WebView2)'
|
||||
if (-not (Test-Path -LiteralPath $windowExe)) {
|
||||
Say ' SKIP LuminaryWindow.exe is not in this bundle'
|
||||
} else {
|
||||
$window = Start-Process -FilePath $windowExe -ArgumentList @('--url', $url) -PassThru
|
||||
Start-Sleep -Seconds $WindowSeconds
|
||||
$window.Refresh()
|
||||
$alive = -not $window.HasExited
|
||||
Check 'window process alive' $alive $(if ($alive) { 'pid ' + $window.Id } else { 'exited early' })
|
||||
if ($alive) {
|
||||
$title = $window.MainWindowTitle
|
||||
Check 'window titled Luminary' ($title -eq 'Luminary') ("title '{0}'" -f $title)
|
||||
}
|
||||
if (-not $window.HasExited) { Stop-Process -Id $window.Id -Force }
|
||||
}
|
||||
} catch {
|
||||
Say (" ERROR {0}" -f $_.Exception.Message)
|
||||
$script:failed += 1
|
||||
} finally {
|
||||
if ($window -and -not $window.HasExited) { Stop-Process -Id $window.Id -Force -ErrorAction SilentlyContinue }
|
||||
if ($server -and -not $server.HasExited) { Stop-Process -Id $server.Id -Force -ErrorAction SilentlyContinue }
|
||||
Remove-Item -LiteralPath $dataDir -Recurse -Force -ErrorAction SilentlyContinue
|
||||
|
||||
Say ''
|
||||
if ($script:failed -eq 0) {
|
||||
Say 'RESULT: PASS'
|
||||
} else {
|
||||
Say ("RESULT: FAIL ({0} check(s))" -f $script:failed)
|
||||
}
|
||||
try { $script:lines | Set-Content -LiteralPath (Join-Path $Bundle 'smoke-report.txt') -Encoding UTF8 } catch { }
|
||||
exit $(if ($script:failed -eq 0) { 0 } else { 1 })
|
||||
}
|
||||
@@ -0,0 +1,858 @@
|
||||
#!/usr/bin/env node
|
||||
/**
|
||||
* Build the optional Windows bundle for Luminary.
|
||||
*
|
||||
* This is deliberately *outside* the main build: it only reads the repository
|
||||
* (`dist/`, `server/`, `package.json`) and writes everything into a directory
|
||||
* outside the checkout. Nothing in `src/`, `server/`, `package.json`, the
|
||||
* Dockerfile, the deploy script or `dist/` is modified by this file, and no npm
|
||||
* script is added for it. Run it directly:
|
||||
*
|
||||
* node windows/build.mjs # build dist/ then the bundle
|
||||
* node windows/build.mjs --skip-build # reuse the existing dist/
|
||||
* node windows/build.mjs --out D:\lum # choose the output directory
|
||||
*
|
||||
* The bundle keeps the layout the server expects (it derives `DIST_DIR` from
|
||||
* the parent of `server/`), so it is a plain folder plus a launcher:
|
||||
*
|
||||
* <out>/Luminary/
|
||||
* node.exe official Node 24 win-x64, SHA-256 checked
|
||||
* Luminary.cmd / .vbs PowerShell launcher (start, health wait, browser)
|
||||
* Luminary.exe only when a Go toolchain builds it
|
||||
* Stop Luminary.cmd
|
||||
* Luminary.ps1 start/stop/status logic shared by both launchers
|
||||
* app/ unchanged server/, dist/, production node_modules/
|
||||
* README-windows.txt
|
||||
* version.txt
|
||||
*/
|
||||
import { createHash } from 'node:crypto';
|
||||
import { spawnSync } from 'node:child_process';
|
||||
import {
|
||||
cpSync,
|
||||
existsSync,
|
||||
mkdirSync,
|
||||
readFileSync,
|
||||
readdirSync,
|
||||
renameSync,
|
||||
rmSync,
|
||||
statSync,
|
||||
writeFileSync,
|
||||
} from 'node:fs';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import zlib from 'node:zlib';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
|
||||
const HERE = path.dirname(fileURLToPath(import.meta.url));
|
||||
const ROOT = path.resolve(HERE, '..');
|
||||
const LAUNCHER_FILES = path.join(HERE, 'launcher');
|
||||
const RELEASES_DIR = path.join(HERE, 'releases');
|
||||
const NPM = process.platform === 'win32' ? 'npm.cmd' : 'npm';
|
||||
const DEFAULT_NODE = 'v24.22.2';
|
||||
|
||||
const HELP = `Luminary Windows bundle
|
||||
|
||||
Usage: node windows/build.mjs [options]
|
||||
|
||||
--out <dir> output directory (default: <cache>/luminary-windows).
|
||||
Must be outside this repository; the bundle is staged in
|
||||
<out>/stage and zipped to <out>/Luminary-<ver>-win-x64.zip.
|
||||
--skip-build reuse the existing dist/ instead of running npm run build
|
||||
--node <version> bundled Node version, e.g. v24.22.2 (must be >= 24)
|
||||
--launcher <kind> auto (default), ps or go. "go" needs a Go toolchain and
|
||||
produces Luminary.exe; "ps" always works.
|
||||
--allow-dirty skip the check that the checkout is clean outside windows/
|
||||
--installer also build Luminary-<ver>-win-x64-setup.exe with NSIS
|
||||
(fetches a private NSIS copy on Linux if makensis is absent)
|
||||
--no-installer skip the setup exe even when makensis is installed
|
||||
--publish copy the finished zip and setup exe to windows/releases
|
||||
(plus a SHA256SUMS.txt) so they can be transferred to a PC
|
||||
--webview2 <exe> ship a prebuilt LuminaryWindow.exe (native WebView2 window).
|
||||
Build it with:
|
||||
docker run --rm -v $PWD/windows/launcher:/src \\
|
||||
-v /tmp/wv:/out -w /src/webview2 \\
|
||||
mcr.microsoft.com/dotnet/sdk:8.0 \\
|
||||
dotnet publish -c Release -o /out
|
||||
--help print this text
|
||||
|
||||
Nothing in the repository is modified: the only writes outside the output
|
||||
directory are the ones npm and nodejs.org make for their own caches.
|
||||
`;
|
||||
|
||||
function fail(message) {
|
||||
process.stderr.write(`windows: FAILED: ${message}\n`);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
function log(step, message) {
|
||||
process.stdout.write(`windows: ${step.padEnd(9)} ${message}\n`);
|
||||
}
|
||||
|
||||
function warn(message) {
|
||||
process.stderr.write(`windows: warning: ${message}\n`);
|
||||
}
|
||||
|
||||
function defaultOutDir() {
|
||||
if (process.platform === 'win32') {
|
||||
const base = process.env.LOCALAPPDATA || path.join(os.homedir(), 'AppData', 'Local');
|
||||
return path.join(base, 'Luminary', 'build');
|
||||
}
|
||||
return path.join(process.env.XDG_CACHE_HOME || path.join(os.homedir(), '.cache'), 'luminary-windows');
|
||||
}
|
||||
|
||||
function parseArgs(argv) {
|
||||
const options = {
|
||||
out: defaultOutDir(),
|
||||
node: DEFAULT_NODE,
|
||||
launcher: 'auto',
|
||||
build: true,
|
||||
allowDirty: false,
|
||||
installer: 'auto',
|
||||
publish: false,
|
||||
webview2: null,
|
||||
help: false,
|
||||
};
|
||||
const value = (index, flag) => {
|
||||
const next = argv[index + 1];
|
||||
if (!next || next.startsWith('--')) fail(`${flag} needs a value`);
|
||||
return next;
|
||||
};
|
||||
for (let i = 0; i < argv.length; i++) {
|
||||
const arg = argv[i];
|
||||
if (arg === '--out') {
|
||||
options.out = path.resolve(value(i, arg));
|
||||
i += 1;
|
||||
} else if (arg === '--node') {
|
||||
const version = value(i, arg);
|
||||
options.node = version.startsWith('v') ? version : `v${version}`;
|
||||
i += 1;
|
||||
} else if (arg === '--launcher') {
|
||||
options.launcher = value(i, arg);
|
||||
i += 1;
|
||||
} else if (arg === '--skip-build') {
|
||||
options.build = false;
|
||||
} else if (arg === '--installer') {
|
||||
options.installer = 'yes';
|
||||
} else if (arg === '--no-installer') {
|
||||
options.installer = 'no';
|
||||
} else if (arg === '--allow-dirty') {
|
||||
options.allowDirty = true;
|
||||
} else if (arg === '--publish') {
|
||||
options.publish = true;
|
||||
} else if (arg === '--webview2') {
|
||||
options.webview2 = path.resolve(value(i, arg));
|
||||
i += 1;
|
||||
} else if (arg === '--help' || arg === '-h') {
|
||||
options.help = true;
|
||||
} else {
|
||||
fail(`unknown option ${arg} (see --help)`);
|
||||
}
|
||||
}
|
||||
if (!['auto', 'ps', 'go'].includes(options.launcher)) {
|
||||
fail(`--launcher must be auto, ps or go (got ${options.launcher})`);
|
||||
}
|
||||
if (!/^v\d+\.\d+\.\d+$/.test(options.node)) {
|
||||
fail(`--node must look like v24.22.2 (got ${options.node})`);
|
||||
}
|
||||
return options;
|
||||
}
|
||||
|
||||
function git(args, { trim = true } = {}) {
|
||||
const result = spawnSync('git', args, { cwd: ROOT, encoding: 'utf8' });
|
||||
if (result.error || result.status !== 0) return null;
|
||||
return trim ? result.stdout.trim() : result.stdout;
|
||||
}
|
||||
|
||||
/**
|
||||
* The bundle must not land in the checkout: a staged Windows Node runtime and
|
||||
* node_modules would otherwise be rsynced to production by scripts/deploy.mjs
|
||||
* and grow the Docker build context.
|
||||
*/
|
||||
function assertOutsideRepo(outDir) {
|
||||
const relative = path.relative(ROOT, outDir);
|
||||
const inside = !relative.startsWith('..') && !path.isAbsolute(relative);
|
||||
if (inside) {
|
||||
fail(
|
||||
`--out resolves inside the repository (${outDir}).\n` +
|
||||
'The bundle is large and would be copied by the deploy rsync; pick an\n' +
|
||||
'output directory outside the checkout, or omit --out to use the cache.',
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Only this folder may be dirty. `logo.png` is a long-standing untracked asset
|
||||
* in this checkout and is not part of the app, so it is tolerated.
|
||||
*/
|
||||
function checkRepoClean(options) {
|
||||
// Not trimmed: porcelain lines start with two status columns and a space, and
|
||||
// trimming the output would eat the leading space of the first line, shifting
|
||||
// its path by one character.
|
||||
const status = git(['status', '--porcelain'], { trim: false });
|
||||
if (status === null) {
|
||||
warn('git is unavailable here; skipping the worktree check');
|
||||
return;
|
||||
}
|
||||
const unexpected = status
|
||||
.split('\n')
|
||||
.filter((line) => line.length > 3)
|
||||
.map((line) => line.slice(3).replace(/^"|"$/g, '').replace(/^.* -> /, '').trim())
|
||||
.filter((file) => file && !file.startsWith('windows/') && file !== 'logo.png');
|
||||
if (!unexpected.length) return;
|
||||
if (options.allowDirty) {
|
||||
warn(`building from a modified checkout: ${unexpected.join(', ')}`);
|
||||
return;
|
||||
}
|
||||
fail(
|
||||
`the checkout has changes outside windows/:\n ${unexpected.join('\n ')}\n` +
|
||||
'Commit or stash them, or pass --allow-dirty to build anyway.',
|
||||
);
|
||||
}
|
||||
|
||||
function readPackage() {
|
||||
const file = path.join(ROOT, 'package.json');
|
||||
if (!existsSync(file)) fail('run this from a Luminary checkout (package.json missing)');
|
||||
return JSON.parse(readFileSync(file, 'utf8'));
|
||||
}
|
||||
|
||||
function run(command, args, cwd, extraEnv) {
|
||||
log('run', [command, ...args].join(' '));
|
||||
const result = spawnSync(command, args, {
|
||||
cwd,
|
||||
stdio: 'inherit',
|
||||
env: extraEnv ? { ...process.env, ...extraEnv } : process.env,
|
||||
});
|
||||
if (result.error) fail(`${command} could not start: ${result.error.message}`);
|
||||
if (result.status !== 0) fail(`${command} ${args.join(' ')} exited with ${result.status}`);
|
||||
}
|
||||
|
||||
function ensureUi(options) {
|
||||
const dist = path.join(ROOT, 'dist', 'index.html');
|
||||
if (options.build) {
|
||||
log('ui', 'npm run build (typecheck + vite build, the normal artifact)');
|
||||
run(NPM, ['run', 'build'], ROOT);
|
||||
} else {
|
||||
log('ui', 'reusing the existing dist/ (--skip-build)');
|
||||
}
|
||||
if (!existsSync(dist)) {
|
||||
fail('dist/index.html is missing; drop --skip-build or run "npm run build" first');
|
||||
}
|
||||
return dist;
|
||||
}
|
||||
|
||||
function copyServer(bundle) {
|
||||
const server = path.join(bundle, 'app', 'server');
|
||||
cpSync(path.join(ROOT, 'server'), server, {
|
||||
recursive: true,
|
||||
filter: (source) => {
|
||||
const relative = path.relative(path.join(ROOT, 'server'), source).split(path.sep).join('/');
|
||||
// The developer catalog and the test files never belong in a bundle.
|
||||
if (relative === 'data' || relative.startsWith('data/')) return false;
|
||||
if (/\.test\.mjs$/.test(relative)) return false;
|
||||
return true;
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
function copyLegal(bundle) {
|
||||
for (const name of ['LICENSE', 'THIRD_PARTY_NOTICES.md']) {
|
||||
const source = path.join(ROOT, name);
|
||||
if (existsSync(source)) cpSync(source, path.join(bundle, name));
|
||||
}
|
||||
const licenses = path.join(ROOT, 'licenses');
|
||||
if (existsSync(licenses)) cpSync(licenses, path.join(bundle, 'licenses'), { recursive: true });
|
||||
}
|
||||
|
||||
/** Copies a text file with CRLF endings, which cmd.exe and PowerShell expect. */
|
||||
function copyText(source, dest) {
|
||||
const body = readFileSync(source, 'utf8').replace(/\r?\n/g, '\r\n');
|
||||
writeFileSync(dest, body);
|
||||
}
|
||||
|
||||
function installWindowsDeps(bundle) {
|
||||
const appDir = path.join(bundle, 'app');
|
||||
cpSync(path.join(ROOT, 'package.json'), path.join(appDir, 'package.json'));
|
||||
cpSync(path.join(ROOT, 'package-lock.json'), path.join(appDir, 'package-lock.json'));
|
||||
log('deps', 'npm ci --omit=dev --os=win32 --cpu=x64 (sharp win32-x64 prebuild)');
|
||||
// --ignore-scripts is safe: sharp 0.35 has no install step, it resolves the
|
||||
// prebuilt binary through optionalDependencies, and running a Windows-only
|
||||
// script on the build host would fail for no reason. The ONNX skip keeps the
|
||||
// postinstall from downloading the CUDA build; CPU binaries ship in the package.
|
||||
run(
|
||||
NPM,
|
||||
[
|
||||
'ci',
|
||||
'--omit=dev',
|
||||
'--os=win32',
|
||||
'--cpu=x64',
|
||||
'--no-audit',
|
||||
'--no-fund',
|
||||
'--ignore-scripts',
|
||||
],
|
||||
appDir,
|
||||
{ ONNXRUNTIME_NODE_INSTALL: 'skip' },
|
||||
);
|
||||
// .bin shims are for a shell, not for `node server/index.mjs`; on a Linux
|
||||
// build they would also be POSIX symlinks inside the zip.
|
||||
rmSync(path.join(appDir, 'node_modules', '.bin'), { recursive: true, force: true });
|
||||
verifySharp(appDir);
|
||||
}
|
||||
|
||||
function verifySharp(appDir) {
|
||||
const dir = path.join(appDir, 'node_modules', '@img', 'sharp-win32-x64');
|
||||
if (!existsSync(dir)) {
|
||||
warn('@img/sharp-win32-x64 is missing; the server will fall back to PNG proxies');
|
||||
return;
|
||||
}
|
||||
const binaries = [];
|
||||
const walk = (current) => {
|
||||
for (const entry of readdirSync(current, { withFileTypes: true })) {
|
||||
const absolute = path.join(current, entry.name);
|
||||
if (entry.isDirectory()) walk(absolute);
|
||||
else if (/\.(node|dll)$/i.test(entry.name)) binaries.push(path.relative(dir, absolute));
|
||||
}
|
||||
};
|
||||
walk(dir);
|
||||
if (!binaries.some((file) => file.endsWith('.node'))) {
|
||||
warn('@img/sharp-win32-x64 has no .node binary; check the installed package');
|
||||
} else {
|
||||
log('deps', `sharp win32-x64 ready (${binaries.length} native files)`);
|
||||
}
|
||||
}
|
||||
|
||||
function sha256File(file) {
|
||||
return createHash('sha256').update(readFileSync(file)).digest('hex');
|
||||
}
|
||||
|
||||
async function download(url) {
|
||||
const response = await fetch(url);
|
||||
if (!response.ok) throw new Error(`${response.status} ${response.statusText} from ${url}`);
|
||||
return Buffer.from(await response.arrayBuffer());
|
||||
}
|
||||
|
||||
async function ensureNode(outDir, version) {
|
||||
const major = Number(version.slice(1).split('.')[0]);
|
||||
if (major < 24) {
|
||||
fail(`Node ${version} is too old: node:sqlite and type stripping need 24 LTS`);
|
||||
}
|
||||
const cache = path.join(outDir, 'cache');
|
||||
mkdirSync(cache, { recursive: true });
|
||||
const exe = path.join(cache, `node-${version}-win-x64.exe`);
|
||||
const sums = path.join(cache, `SHASUMS256-${version}.txt`);
|
||||
const base = `https://nodejs.org/dist/${version}`;
|
||||
if (!existsSync(exe)) {
|
||||
log('node', `downloading ${base}/win-x64/node.exe`);
|
||||
try {
|
||||
writeFileSync(exe, await download(`${base}/win-x64/node.exe`));
|
||||
} catch (error) {
|
||||
fail(`could not download node.exe: ${error.message}`);
|
||||
}
|
||||
} else {
|
||||
log('node', `using cached ${path.basename(exe)}`);
|
||||
}
|
||||
if (!existsSync(sums)) {
|
||||
try {
|
||||
writeFileSync(sums, (await download(`${base}/SHASUMS256.txt`)).toString('utf8'));
|
||||
} catch (error) {
|
||||
warn(`could not fetch SHASUMS256.txt (${error.message}); the cached node.exe is unverified`);
|
||||
}
|
||||
}
|
||||
const hash = sha256File(exe);
|
||||
if (existsSync(sums)) {
|
||||
const line = readFileSync(sums, 'utf8')
|
||||
.split('\n')
|
||||
.map((row) => row.trim().split(/\s+/))
|
||||
.find((row) => row[1] === 'win-x64/node.exe');
|
||||
if (!line) fail(`SHASUMS256.txt for ${version} has no win-x64/node.exe entry`);
|
||||
if (hash !== line[0]) {
|
||||
rmSync(exe, { force: true });
|
||||
fail(`node.exe failed its SHA-256 check (${hash} != ${line[0]}); re-run to download again`);
|
||||
}
|
||||
log('node', `${version} win-x64 verified (sha256 ${hash.slice(0, 12)}…)`);
|
||||
} else {
|
||||
warn(`using node.exe without a published checksum (sha256 ${hash})`);
|
||||
}
|
||||
return { exe, hash };
|
||||
}
|
||||
|
||||
function goAvailable() {
|
||||
const result = spawnSync('go', ['version'], { encoding: 'utf8' });
|
||||
return !result.error && result.status === 0;
|
||||
}
|
||||
|
||||
function chooseLauncher(requested) {
|
||||
if (requested === 'ps') return 'ps';
|
||||
if (requested === 'go') {
|
||||
if (!goAvailable()) {
|
||||
fail(
|
||||
'--launcher go needs a Go toolchain (https://go.dev/dl/), or build the exe\n' +
|
||||
'in the container: docker build -f windows/Dockerfile --output type=local,dest=<dir> .',
|
||||
);
|
||||
}
|
||||
return 'go';
|
||||
}
|
||||
return goAvailable() ? 'go' : 'ps';
|
||||
}
|
||||
|
||||
function installLauncher(bundle, kind) {
|
||||
const files = ['Luminary.ps1', 'Stop Luminary.cmd'];
|
||||
if (kind === 'go') {
|
||||
const source = path.join(LAUNCHER_FILES, 'go');
|
||||
log('launcher', 'go build -trimpath -H windowsgui (Luminary.exe)');
|
||||
run(
|
||||
'go',
|
||||
[
|
||||
'build',
|
||||
'-trimpath',
|
||||
'-ldflags',
|
||||
'-s -w -H windowsgui',
|
||||
'-o',
|
||||
path.join(bundle, 'Luminary.exe'),
|
||||
'.',
|
||||
],
|
||||
source,
|
||||
{ GOOS: 'windows', GOARCH: 'amd64', CGO_ENABLED: '0' },
|
||||
);
|
||||
} else {
|
||||
files.push('Luminary.cmd', 'Luminary.vbs');
|
||||
}
|
||||
for (const name of files) {
|
||||
copyText(path.join(LAUNCHER_FILES, name), path.join(bundle, name));
|
||||
}
|
||||
// Binary icon for shortcuts and the installer; no CRLF pass on this one.
|
||||
const icon = path.join(LAUNCHER_FILES, 'Luminary.ico');
|
||||
if (existsSync(icon)) cpSync(icon, path.join(bundle, 'Luminary.ico'));
|
||||
// The PowerShell launcher is always present: it implements the shared
|
||||
// start/stop/status logic and "Stop Luminary.cmd" calls it in both modes.
|
||||
log('launcher', kind === 'go' ? 'Luminary.exe' : 'Luminary.cmd + Luminary.vbs');
|
||||
}
|
||||
|
||||
function writeVersion(bundle, pkg, launcher, nodeVersion, nodeHash, nodeSize) {
|
||||
const commit = git(['rev-parse', '--short', 'HEAD']) ?? 'unknown';
|
||||
// The hash is on the node line so the launcher can quote it verbatim when
|
||||
// node.exe goes missing (antivirus) and the user needs to verify a restore.
|
||||
const lines = [
|
||||
`Luminary ${pkg.version}`,
|
||||
`commit ${commit}`,
|
||||
`built ${new Date().toISOString()}`,
|
||||
`node ${nodeVersion} win-x64 sha256 ${nodeHash} size ${nodeSize}`,
|
||||
`launcher ${launcher === 'go' ? 'Luminary.exe' : 'Luminary.cmd / Luminary.vbs'}`,
|
||||
];
|
||||
const text = `${lines.join('\n')}\n`;
|
||||
writeFileSync(path.join(bundle, 'version.txt'), text);
|
||||
return { version: pkg.version, commit };
|
||||
}
|
||||
|
||||
function writeBundleReadme(bundle, info) {
|
||||
const start = info.launcher === 'go' ? 'Luminary.exe' : 'Luminary.cmd (or Luminary.vbs for no console window)';
|
||||
const body = `Luminary ${info.version} for Windows (x64) — portable bundle
|
||||
=================================================
|
||||
|
||||
Start: double-click ${start}
|
||||
Stop: double-click "Stop Luminary.cmd"
|
||||
Open: the launcher opens http://127.0.0.1:8787 (the next free port if busy)
|
||||
Data: %LOCALAPPDATA%\\Luminary\\data (originals, previews, SQLite catalog)
|
||||
Logs: logs\\server.out.log and logs\\server.err.log
|
||||
Check: "Luminary.cmd -Verify" lists the files a complete bundle needs
|
||||
Repair: "Luminary.cmd -Repair" downloads node.exe again and verifies its sha256
|
||||
Sign-in: none — single-user desktop mode, no account setup
|
||||
Window: opens in its own window (native when bundled, else chromeless Edge/Chrome);
|
||||
"Luminary.cmd -Browser" for a normal tab
|
||||
|
||||
Requirements
|
||||
- Windows 10 or 11, 64-bit.
|
||||
- A current browser (Edge, Chrome or Firefox) with WebGL2 for the Develop
|
||||
module.
|
||||
- Nothing else. Node.js is included as node.exe, and no .NET, Visual C++
|
||||
Redistributable, admin rights or installer is needed.
|
||||
- About 250 MB free where the data folder lives.
|
||||
|
||||
The first launch creates the data folder and the catalog. Nothing is installed
|
||||
and nothing is written next to Windows or Program Files, so you can move this
|
||||
folder anywhere (including a USB drive) as long as it stays writable.
|
||||
|
||||
If an antivirus removes node.exe, the launcher offers to download it on the next
|
||||
start (or run "Luminary.cmd -Repair"). On Windows older than 10 the launcher
|
||||
says so before starting instead of failing halfway.
|
||||
|
||||
Back up the catalog by copying the whole data folder while Luminary is stopped,
|
||||
including lumenroom.db, lumenroom.db-wal, lumenroom.db-shm and secret.key.
|
||||
|
||||
Updating: stop Luminary, replace app\\ and node.exe from a newer bundle, then
|
||||
start it again. The data folder is outside the bundle and is untouched.
|
||||
|
||||
Notes
|
||||
- Extract the whole zip before running anything. A file opened from inside
|
||||
the zip preview is copied out on its own and will not find node.exe.
|
||||
- Windows 8.1 and older also need the Universal C Runtime (KB2999226);
|
||||
Windows 10 and 11 already include it.
|
||||
- This build is single-user: it creates one local admin on first start and
|
||||
opens signed in. It is not meant for several people sharing one Windows
|
||||
login with separate accounts.
|
||||
- The bundle is unsigned, so SmartScreen may ask once ("More info" -> "Run anyway").
|
||||
- The server listens on 127.0.0.1 only. Set HOST=0.0.0.0 before starting if
|
||||
client proofing galleries must be reachable from other devices on the LAN.
|
||||
- RAW decoding uses the bundled libraw WebAssembly; sharp's Windows prebuilt
|
||||
binary is included, so there is nothing else to install.
|
||||
`;
|
||||
writeFileSync(path.join(bundle, 'README-windows.txt'), body.replace(/\r?\n/g, '\r\n'));
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ zip ---- */
|
||||
|
||||
const CRC_TABLE = (() => {
|
||||
const table = new Uint32Array(256);
|
||||
for (let n = 0; n < 256; n++) {
|
||||
let c = n;
|
||||
for (let k = 0; k < 8; k++) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1;
|
||||
table[n] = c >>> 0;
|
||||
}
|
||||
return table;
|
||||
})();
|
||||
|
||||
function crc32(buffer) {
|
||||
let c = 0xffffffff;
|
||||
for (let i = 0; i < buffer.length; i++) c = CRC_TABLE[(c ^ buffer[i]) & 0xff] ^ (c >>> 8);
|
||||
return (c ^ 0xffffffff) >>> 0;
|
||||
}
|
||||
|
||||
function listFiles(dir) {
|
||||
const files = [];
|
||||
const walk = (current) => {
|
||||
const entries = readdirSync(current, { withFileTypes: true }).sort((a, b) =>
|
||||
a.name.localeCompare(b.name),
|
||||
);
|
||||
for (const entry of entries) {
|
||||
const absolute = path.join(current, entry.name);
|
||||
if (entry.isDirectory()) walk(absolute);
|
||||
else if (entry.isFile()) files.push(absolute);
|
||||
}
|
||||
};
|
||||
walk(dir);
|
||||
return files;
|
||||
}
|
||||
|
||||
/**
|
||||
* Minimal ZIP writer (deflate, no zip64). Keeping it here avoids a dependency,
|
||||
* and every entry carries the same fixed timestamp instead of inheriting the
|
||||
* filesystem's, so two builds differ only by the files' own content.
|
||||
*/
|
||||
function writeZip(sourceDir, zipPath) {
|
||||
// 2020-01-01 00:00:00 in MS-DOS date/time form.
|
||||
const time = 0;
|
||||
const date = (40 << 9) | (1 << 5) | 1;
|
||||
const parts = [];
|
||||
const central = [];
|
||||
let offset = 0;
|
||||
for (const absolute of listFiles(sourceDir)) {
|
||||
const name = path.relative(sourceDir, absolute).split(path.sep).join('/');
|
||||
const data = readFileSync(absolute);
|
||||
const crc = crc32(data);
|
||||
const deflated = zlib.deflateRawSync(data, { level: 9 });
|
||||
const useDeflate = deflated.length < data.length;
|
||||
const body = useDeflate ? deflated : data;
|
||||
const method = useDeflate ? 8 : 0;
|
||||
const nameBytes = Buffer.from(name, 'utf8');
|
||||
|
||||
const local = Buffer.alloc(30);
|
||||
local.writeUInt32LE(0x04034b50, 0);
|
||||
local.writeUInt16LE(20, 4);
|
||||
local.writeUInt16LE(0x0800, 6); // UTF-8 names
|
||||
local.writeUInt16LE(method, 8);
|
||||
local.writeUInt16LE(time, 10);
|
||||
local.writeUInt16LE(date, 12);
|
||||
local.writeUInt32LE(crc, 14);
|
||||
local.writeUInt32LE(body.length, 18);
|
||||
local.writeUInt32LE(data.length, 22);
|
||||
local.writeUInt16LE(nameBytes.length, 26);
|
||||
local.writeUInt16LE(0, 28);
|
||||
parts.push(local, nameBytes, body);
|
||||
|
||||
const entry = Buffer.alloc(46);
|
||||
entry.writeUInt32LE(0x02014b50, 0);
|
||||
entry.writeUInt16LE(20, 4);
|
||||
entry.writeUInt16LE(20, 6);
|
||||
entry.writeUInt16LE(0x0800, 8);
|
||||
entry.writeUInt16LE(method, 10);
|
||||
entry.writeUInt16LE(time, 12);
|
||||
entry.writeUInt16LE(date, 14);
|
||||
entry.writeUInt32LE(crc, 16);
|
||||
entry.writeUInt32LE(body.length, 20);
|
||||
entry.writeUInt32LE(data.length, 24);
|
||||
entry.writeUInt16LE(nameBytes.length, 28);
|
||||
entry.writeUInt16LE(0, 30);
|
||||
entry.writeUInt16LE(0, 32);
|
||||
entry.writeUInt16LE(0, 34);
|
||||
entry.writeUInt16LE(0, 36);
|
||||
entry.writeUInt32LE(0, 38);
|
||||
entry.writeUInt32LE(offset, 42);
|
||||
central.push(entry, nameBytes);
|
||||
|
||||
offset += local.length + nameBytes.length + body.length;
|
||||
}
|
||||
const directory = Buffer.concat(central);
|
||||
const end = Buffer.alloc(22);
|
||||
const count = central.length / 2;
|
||||
end.writeUInt32LE(0x06054b50, 0);
|
||||
end.writeUInt16LE(0, 4);
|
||||
end.writeUInt16LE(0, 6);
|
||||
end.writeUInt16LE(count, 8);
|
||||
end.writeUInt16LE(count, 10);
|
||||
end.writeUInt32LE(directory.length, 12);
|
||||
end.writeUInt32LE(offset, 16);
|
||||
end.writeUInt16LE(0, 20);
|
||||
writeFileSync(zipPath, Buffer.concat([...parts, directory, end]));
|
||||
return { files: count, bytes: statSync(zipPath).size };
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------- installer ---- */
|
||||
|
||||
function dirSizeBytes(dir) {
|
||||
let total = 0;
|
||||
for (const entry of readdirSync(dir, { withFileTypes: true })) {
|
||||
const absolute = path.join(dir, entry.name);
|
||||
total += entry.isDirectory() ? dirSizeBytes(absolute) : statSync(absolute).size;
|
||||
}
|
||||
return total;
|
||||
}
|
||||
|
||||
function cachedMakensis(outDir) {
|
||||
const root = path.join(outDir, 'tools', 'nsis');
|
||||
const bin = path.join(root, 'usr', 'bin', 'makensis');
|
||||
if (!existsSync(bin)) return null;
|
||||
return { bin, nsisdir: path.join(root, 'usr', 'share', 'nsis') };
|
||||
}
|
||||
|
||||
function findMakensis(outDir) {
|
||||
if (process.env.MAKENSIS) {
|
||||
return { bin: process.env.MAKENSIS, nsisdir: process.env.NSISDIR || null };
|
||||
}
|
||||
const cached = cachedMakensis(outDir);
|
||||
if (cached) return cached;
|
||||
const which = spawnSync(process.platform === 'win32' ? 'where' : 'which', ['makensis'], {
|
||||
encoding: 'utf8',
|
||||
});
|
||||
const found = !which.error && which.status === 0 ? which.stdout.split(/\r?\n/)[0].trim() : '';
|
||||
return found ? { bin: found, nsisdir: process.env.NSISDIR || null } : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* NSIS is a small cross-compiler: on Linux it produces the same .exe as it
|
||||
* would on Windows. Ubuntu ships it as two .debs, which unpack into the build
|
||||
* cache without root, so a fresh host can build the installer unattended.
|
||||
*/
|
||||
async function fetchMakensis(outDir) {
|
||||
if (process.platform !== 'linux' || process.arch !== 'x64') return null;
|
||||
const dpkg = spawnSync('dpkg-deb', ['--version'], { stdio: 'ignore' });
|
||||
if (dpkg.error || dpkg.status !== 0) return null;
|
||||
const packVersion = '3.09-4ubuntu1';
|
||||
const base = 'http://archive.ubuntu.com/ubuntu/pool/universe/n/nsis';
|
||||
const debs = path.join(outDir, 'cache', 'nsis-debs');
|
||||
const root = path.join(outDir, 'tools', 'nsis');
|
||||
mkdirSync(debs, { recursive: true });
|
||||
rmSync(root, { recursive: true, force: true });
|
||||
for (const name of [`nsis_${packVersion}_amd64.deb`, `nsis-common_${packVersion}_all.deb`]) {
|
||||
const file = path.join(debs, name);
|
||||
if (!existsSync(file)) {
|
||||
try {
|
||||
writeFileSync(file, await download(`${base}/${name}`));
|
||||
} catch (error) {
|
||||
warn(`could not download ${name} (${error.message})`);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
const unpack = spawnSync('dpkg-deb', ['-x', file, root], { encoding: 'utf8' });
|
||||
if (unpack.error || unpack.status !== 0) {
|
||||
warn(`could not unpack ${name}: ${(unpack.stderr || '').trim() || 'dpkg-deb failed'}`);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
return cachedMakensis(outDir);
|
||||
}
|
||||
|
||||
async function resolveMakensis(outDir, required) {
|
||||
const found = findMakensis(outDir);
|
||||
if (found) return found;
|
||||
if (!required) return null;
|
||||
log('nsis', 'makensis not found; unpacking a private NSIS into the build cache');
|
||||
const fetched = await fetchMakensis(outDir);
|
||||
if (fetched) {
|
||||
log('nsis', `NSIS ${packVersionOf(fetched.bin)} ready (no root install needed)`);
|
||||
return fetched;
|
||||
}
|
||||
fail(
|
||||
'NSIS is required for --installer and was not found.\n' +
|
||||
' Ubuntu/Debian: sudo apt install nsis\n' +
|
||||
' macOS: brew install makensis\n' +
|
||||
' Windows: https://nsis.sourceforge.io\n' +
|
||||
' or set MAKENSIS=/path/to/makensis',
|
||||
);
|
||||
}
|
||||
|
||||
function packVersionOf(makensis) {
|
||||
const result = spawnSync(makensis, ['-VERSION'], { encoding: 'utf8' });
|
||||
return !result.error && result.status === 0 ? result.stdout.trim() : 'unknown version';
|
||||
}
|
||||
|
||||
function buildInstaller({ outDir, bundle, pkg, makensis }) {
|
||||
const script = path.join(HERE, 'installer.nsi');
|
||||
if (!existsSync(script)) fail(`installer script missing: ${script}`);
|
||||
const outputDir = path.join(outDir, 'installer');
|
||||
mkdirSync(outputDir, { recursive: true });
|
||||
const setup = path.join(outputDir, `Luminary-${pkg.version}-win-x64-setup.exe`);
|
||||
rmSync(setup, { force: true });
|
||||
|
||||
// NSIS wants four numeric fields; 0.5.1 -> 0.5.1.0
|
||||
const fields = pkg.version.split('.').map((n) => Number(n) || 0);
|
||||
while (fields.length < 4) fields.push(0);
|
||||
const version4 = fields.slice(0, 4).join('.');
|
||||
const installKb = Math.ceil(dirSizeBytes(bundle) / 1024);
|
||||
|
||||
log('installer', `makensis ${path.basename(script)} (${(installKb / 1024).toFixed(0)} MB payload)`);
|
||||
run(
|
||||
makensis.bin,
|
||||
[
|
||||
'-V2',
|
||||
`-DAPP_VERSION=${pkg.version}`,
|
||||
`-DAPP_VERSION4=${version4}`,
|
||||
`-DSOURCE_DIR=${bundle}`,
|
||||
`-DOUTPUT_DIR=${outputDir}`,
|
||||
`-DICON=${path.join(LAUNCHER_FILES, 'Luminary.ico')}`,
|
||||
`-DINSTALL_KB=${installKb}`,
|
||||
script,
|
||||
],
|
||||
ROOT,
|
||||
makensis.nsisdir ? { NSISDIR: makensis.nsisdir } : undefined,
|
||||
);
|
||||
if (!existsSync(setup)) fail('makensis reported success but produced no setup exe');
|
||||
return { path: setup, bytes: statSync(setup).size };
|
||||
}
|
||||
|
||||
/* ----------------------------------------------------------------- main ---- */
|
||||
|
||||
async function main() {
|
||||
const options = parseArgs(process.argv.slice(2));
|
||||
if (options.help) {
|
||||
process.stdout.write(HELP);
|
||||
return 0;
|
||||
}
|
||||
assertOutsideRepo(options.out);
|
||||
const pkg = readPackage();
|
||||
log('repo', `${pkg.name} ${pkg.version} at ${ROOT}`);
|
||||
log('out', options.out);
|
||||
checkRepoClean(options);
|
||||
ensureUi(options);
|
||||
|
||||
// Settle the launcher before anything is copied: a missing Go toolchain
|
||||
// should fail in a second, not after a download and an npm install.
|
||||
const launcher = chooseLauncher(options.launcher);
|
||||
|
||||
// Build into a sibling and swap at the end, so a failed run never replaces
|
||||
// the last complete bundle with a partial tree.
|
||||
const stageRoot = path.join(options.out, 'stage');
|
||||
const workRoot = path.join(options.out, 'stage.next');
|
||||
const bundle = path.join(workRoot, 'Luminary');
|
||||
rmSync(workRoot, { recursive: true, force: true });
|
||||
mkdirSync(path.join(bundle, 'app'), { recursive: true });
|
||||
|
||||
log('stage', 'copying dist/ and server/ (unchanged layout the server expects)');
|
||||
cpSync(path.join(ROOT, 'dist'), path.join(bundle, 'app', 'dist'), { recursive: true });
|
||||
copyServer(bundle);
|
||||
copyLegal(bundle);
|
||||
installWindowsDeps(bundle);
|
||||
|
||||
const node = await ensureNode(options.out, options.node);
|
||||
const bundledNode = path.join(bundle, 'node.exe');
|
||||
cpSync(node.exe, bundledNode);
|
||||
if (statSync(bundledNode).size !== statSync(node.exe).size) {
|
||||
fail('node.exe was truncated while copying it into the bundle');
|
||||
}
|
||||
|
||||
installLauncher(bundle, launcher);
|
||||
if (options.webview2) {
|
||||
if (!existsSync(options.webview2)) fail(`--webview2 file not found: ${options.webview2}`);
|
||||
cpSync(options.webview2, path.join(bundle, 'LuminaryWindow.exe'));
|
||||
log('window', `LuminaryWindow.exe (${(statSync(options.webview2).size / 1024 / 1024).toFixed(1)} MB)`);
|
||||
}
|
||||
|
||||
const info = writeVersion(bundle, pkg, launcher, options.node, node.hash, statSync(bundledNode).size);
|
||||
writeBundleReadme(bundle, { ...info, launcher });
|
||||
|
||||
const zipPath = path.join(options.out, `Luminary-${pkg.version}-win-x64.zip`);
|
||||
rmSync(zipPath, { force: true });
|
||||
log('zip', path.basename(zipPath));
|
||||
const zip = writeZip(workRoot, zipPath);
|
||||
|
||||
rmSync(stageRoot, { recursive: true, force: true });
|
||||
renameSync(workRoot, stageRoot);
|
||||
|
||||
const stagedBundle = path.join(stageRoot, 'Luminary');
|
||||
let installer = null;
|
||||
if (options.installer !== 'no') {
|
||||
const makensis = await resolveMakensis(options.out, options.installer === 'yes');
|
||||
if (makensis) {
|
||||
installer = buildInstaller({ outDir: options.out, bundle: stagedBundle, pkg, makensis });
|
||||
log('installer', `${path.basename(installer.path)} (${(installer.bytes / 1024 / 1024).toFixed(1)} MB)`);
|
||||
} else {
|
||||
warn('makensis is not installed; shipping the zip only (install NSIS for the setup exe)');
|
||||
}
|
||||
}
|
||||
|
||||
// The isolation contract: nothing outside windows/ may have changed.
|
||||
if (!options.allowDirty) checkRepoClean(options);
|
||||
|
||||
// Hand-off copy. The staging and the zip stay outside the checkout; this is
|
||||
// the one write into the repository, into windows/releases, for transfer to a
|
||||
// Windows machine.
|
||||
let published = null;
|
||||
if (options.publish) {
|
||||
mkdirSync(RELEASES_DIR, { recursive: true });
|
||||
const artifacts = [zipPath, ...(installer ? [installer.path] : [])];
|
||||
const sums = [];
|
||||
for (const artifact of artifacts) {
|
||||
const target = path.join(RELEASES_DIR, path.basename(artifact));
|
||||
cpSync(artifact, target);
|
||||
sums.push(`${sha256File(target)} ${path.basename(target)}`);
|
||||
log('publish', path.relative(ROOT, target));
|
||||
}
|
||||
writeFileSync(path.join(RELEASES_DIR, 'SHA256SUMS.txt'), `${sums.join('\n')}\n`);
|
||||
published = path.join(RELEASES_DIR, path.basename(zipPath));
|
||||
}
|
||||
|
||||
process.stdout.write(
|
||||
[
|
||||
'',
|
||||
'windows build PASSED',
|
||||
` artifact ${zipPath}`,
|
||||
` size ${(zip.bytes / 1024 / 1024).toFixed(1)} MB (${zip.files} files)`,
|
||||
` sha256 ${sha256File(zipPath)}`,
|
||||
...(installer
|
||||
? [
|
||||
` setup ${installer.path}`,
|
||||
` setup MB ${(installer.bytes / 1024 / 1024).toFixed(1)}`,
|
||||
` setup sha ${sha256File(installer.path)}`,
|
||||
]
|
||||
: []),
|
||||
` node ${options.node} win-x64`,
|
||||
` launcher ${launcher === 'go' ? 'Luminary.exe' : 'Luminary.cmd / Luminary.vbs'}`,
|
||||
...(options.webview2 ? [` window LuminaryWindow.exe (native WebView2)`] : []),
|
||||
` staged ${stagedBundle}`,
|
||||
...(published ? [` publish ${path.relative(ROOT, published)}`] : []),
|
||||
'',
|
||||
published
|
||||
? 'Only windows/ was written: the zip in windows/releases is ready to transfer.'
|
||||
: 'The repository was not modified; only windows/ and the output directory were touched.',
|
||||
'',
|
||||
].join('\n'),
|
||||
);
|
||||
return 0;
|
||||
}
|
||||
|
||||
main().then(
|
||||
(code) => {
|
||||
process.exitCode = code;
|
||||
},
|
||||
(error) => {
|
||||
fail(error instanceof Error ? error.message : String(error));
|
||||
},
|
||||
);
|
||||
@@ -0,0 +1,212 @@
|
||||
; Per-user installer for the Luminary Windows bundle, built with NSIS 3.
|
||||
;
|
||||
; NSIS runs on Linux, macOS and Windows, so the same build host that produces
|
||||
; the zip also produces the setup executable:
|
||||
;
|
||||
; node windows/build.mjs --installer --publish
|
||||
;
|
||||
; or by hand, from the repository root:
|
||||
;
|
||||
; makensis -DAPP_VERSION=0.5.1 -DAPP_VERSION4=0.5.1.0 \
|
||||
; -DSOURCE_DIR="$PWD/../.cache/stage/Luminary" windows/installer.nsi
|
||||
;
|
||||
; Nothing is installed for all users: no UAC prompt, no Program Files. The
|
||||
; program goes to %LOCALAPPDATA%\Programs\Luminary and the catalog stays in
|
||||
; %LOCALAPPDATA%\Luminary\data, which the uninstaller never touches.
|
||||
|
||||
Unicode true
|
||||
ManifestDPIAware true
|
||||
ManifestSupportedOS win10
|
||||
RequestExecutionLevel user
|
||||
SetCompressor /SOLID lzma
|
||||
SetCompressorDictSize 32
|
||||
CRCCheck on
|
||||
|
||||
!include "MUI2.nsh"
|
||||
!include "x64.nsh"
|
||||
!include "WinVer.nsh"
|
||||
|
||||
!ifndef APP_VERSION
|
||||
!define APP_VERSION "0.5.1"
|
||||
!endif
|
||||
; NSIS wants four numeric fields for the exe's version resource.
|
||||
!ifndef APP_VERSION4
|
||||
!define APP_VERSION4 "0.5.1.0"
|
||||
!endif
|
||||
; Forward slashes throughout: makensis is cross-platform, and this file is
|
||||
; compiled on Linux as often as on Windows.
|
||||
!ifndef SOURCE_DIR
|
||||
!define SOURCE_DIR "${__FILEDIR__}/stage/Luminary"
|
||||
!endif
|
||||
!ifndef OUTPUT_DIR
|
||||
!define OUTPUT_DIR "${__FILEDIR__}/installer-output"
|
||||
!endif
|
||||
!ifndef ICON
|
||||
!define ICON "${__FILEDIR__}/launcher/Luminary.ico"
|
||||
!endif
|
||||
; Size of the installed tree in KB, for Add/Remove Programs. The builder
|
||||
; measures the staged bundle; the fallback is roughly right for a full build.
|
||||
!ifndef INSTALL_KB
|
||||
!define INSTALL_KB "250000"
|
||||
!endif
|
||||
|
||||
!define APP_NAME "Luminary"
|
||||
!define APP_PUBLISHER "Maple Street"
|
||||
!define APP_URL "https://git.maple-street.net/bhursey/luminary"
|
||||
!define UNINST_KEY "Software\Microsoft\Windows\CurrentVersion\Uninstall\Luminary"
|
||||
!define APP_KEY "Software\Luminary"
|
||||
!define RUN_KEY "Software\Microsoft\Windows\CurrentVersion\Run"
|
||||
|
||||
Name "${APP_NAME} ${APP_VERSION}"
|
||||
BrandingText "${APP_NAME} ${APP_VERSION}"
|
||||
OutFile "${OUTPUT_DIR}/Luminary-${APP_VERSION}-win-x64-setup.exe"
|
||||
InstallDir "$LOCALAPPDATA\Programs\Luminary"
|
||||
InstallDirRegKey HKCU "${APP_KEY}" "InstallDir"
|
||||
|
||||
VIProductVersion "${APP_VERSION4}"
|
||||
VIAddVersionKey "ProductName" "${APP_NAME}"
|
||||
VIAddVersionKey "ProductVersion" "${APP_VERSION}"
|
||||
VIAddVersionKey "FileDescription" "${APP_NAME} setup"
|
||||
VIAddVersionKey "FileVersion" "${APP_VERSION}"
|
||||
VIAddVersionKey "CompanyName" "${APP_PUBLISHER}"
|
||||
VIAddVersionKey "LegalCopyright" "MIT licensed"
|
||||
|
||||
!define MUI_ICON "${ICON}"
|
||||
!define MUI_UNICON "${ICON}"
|
||||
!define MUI_ABORTWARNING
|
||||
!define MUI_WELCOMEPAGE_TITLE "Install ${APP_NAME} ${APP_VERSION}"
|
||||
!define MUI_WELCOMEPAGE_TEXT "This installs the Luminary desktop app for your Windows account.$\r$\n$\r$\nNo administrator rights are needed: the app goes in your own AppData folder, and the catalog, previews and originals index stay in %LOCALAPPDATA%\Luminary\data. Uninstalling keeps that folder so you never lose a catalog.$\r$\n$\r$\nNode.js, .NET and the Visual C++ runtime are not required - everything Luminary needs ships inside."
|
||||
!define MUI_FINISHPAGE_TEXT "${APP_NAME} is installed.$\r$\n$\r$\nYour catalog lives in %LOCALAPPDATA%\Luminary\data. Back it up by copying that folder while Luminary is stopped.$\r$\n$\r$\nUninstalling removes the app but not the catalog."
|
||||
!define MUI_FINISHPAGE_SHOWREADME "$INSTDIR\README-windows.txt"
|
||||
!define MUI_FINISHPAGE_SHOWREADME_TEXT "Show the Windows readme"
|
||||
!define MUI_FINISHPAGE_SHOWREADME_NOTCHECKED
|
||||
|
||||
!if /FileExists "${SOURCE_DIR}/Luminary.vbs"
|
||||
!define MUI_FINISHPAGE_RUN "$INSTDIR\Luminary.vbs"
|
||||
!else
|
||||
!define MUI_FINISHPAGE_RUN "$INSTDIR\Luminary.cmd"
|
||||
!endif
|
||||
!define MUI_FINISHPAGE_RUN_TEXT "Start ${APP_NAME}"
|
||||
|
||||
!insertmacro MUI_PAGE_WELCOME
|
||||
!if /FileExists "${SOURCE_DIR}/LICENSE"
|
||||
!insertmacro MUI_PAGE_LICENSE "${SOURCE_DIR}/LICENSE"
|
||||
!endif
|
||||
!insertmacro MUI_PAGE_COMPONENTS
|
||||
!insertmacro MUI_PAGE_DIRECTORY
|
||||
!insertmacro MUI_PAGE_INSTFILES
|
||||
!insertmacro MUI_PAGE_FINISH
|
||||
|
||||
!insertmacro MUI_UNPAGE_CONFIRM
|
||||
!insertmacro MUI_UNPAGE_INSTFILES
|
||||
|
||||
!insertmacro MUI_LANGUAGE "English"
|
||||
|
||||
LangString DESC_Main ${LANG_ENGLISH} "The editor, film looks, bundled Node runtime and documentation. Required."
|
||||
LangString DESC_Desktop ${LANG_ENGLISH} "Put a Luminary shortcut on the desktop."
|
||||
LangString DESC_Startup ${LANG_ENGLISH} "Start Luminary in the background when you sign in to Windows."
|
||||
|
||||
Function .onInit
|
||||
; The launcher refuses these too, but the installer should say so before it
|
||||
; copies 250 MB onto an unsupported PC.
|
||||
${IfNot} ${RunningX64}
|
||||
MessageBox MB_ICONSTOP "${APP_NAME} needs 64-bit Windows 10 or 11. This PC is running a 32-bit copy of Windows."
|
||||
Abort
|
||||
${EndIf}
|
||||
${IfNot} ${AtLeastWin10}
|
||||
MessageBox MB_ICONSTOP "${APP_NAME} needs Windows 10 or 11. Older versions are not supported."
|
||||
Abort
|
||||
${EndIf}
|
||||
FunctionEnd
|
||||
|
||||
; Stop a copy started from this folder, so an upgrade can replace node.exe and
|
||||
; app\ while it is not in use. Uses the launcher's own -Stop path, which reads
|
||||
; runtime.json, rather than killing every node.exe on the machine.
|
||||
!macro StopRunning
|
||||
${If} ${FileExists} "$INSTDIR\Luminary.ps1"
|
||||
DetailPrint "Stopping a running Luminary..."
|
||||
nsExec::ExecToLog 'powershell.exe -NoProfile -ExecutionPolicy Bypass -File "$INSTDIR\Luminary.ps1" -Stop'
|
||||
Pop $0
|
||||
Sleep 1200
|
||||
${EndIf}
|
||||
!macroend
|
||||
|
||||
Section "Luminary (required)" SEC_MAIN
|
||||
SectionIn RO
|
||||
|
||||
!insertmacro StopRunning
|
||||
|
||||
SetOutPath "$INSTDIR"
|
||||
File /r "${SOURCE_DIR}/*.*"
|
||||
|
||||
CreateDirectory "$LOCALAPPDATA\Luminary\data"
|
||||
WriteUninstaller "$INSTDIR\Uninstall.exe"
|
||||
|
||||
CreateDirectory "$SMPROGRAMS\Luminary"
|
||||
!if /FileExists "${SOURCE_DIR}/Luminary.vbs"
|
||||
CreateShortCut "$SMPROGRAMS\Luminary\Luminary.lnk" "$INSTDIR\Luminary.vbs" "" "$INSTDIR\Luminary.ico" 0
|
||||
!else
|
||||
CreateShortCut "$SMPROGRAMS\Luminary\Luminary.lnk" "$INSTDIR\Luminary.cmd" "" "$INSTDIR\Luminary.ico" 0
|
||||
!endif
|
||||
CreateShortCut "$SMPROGRAMS\Luminary\Stop Luminary.lnk" "$INSTDIR\Stop Luminary.cmd" "" "$INSTDIR\Luminary.ico" 0
|
||||
CreateShortCut "$SMPROGRAMS\Luminary\Luminary data folder.lnk" "$LOCALAPPDATA\Luminary\data" "" "$INSTDIR\Luminary.ico" 0
|
||||
|
||||
WriteRegStr HKCU "${APP_KEY}" "InstallDir" "$INSTDIR"
|
||||
WriteRegStr HKCU "${APP_KEY}" "Version" "${APP_VERSION}"
|
||||
|
||||
WriteRegStr HKCU "${UNINST_KEY}" "DisplayName" "${APP_NAME}"
|
||||
WriteRegStr HKCU "${UNINST_KEY}" "DisplayVersion" "${APP_VERSION}"
|
||||
WriteRegStr HKCU "${UNINST_KEY}" "Publisher" "${APP_PUBLISHER}"
|
||||
WriteRegStr HKCU "${UNINST_KEY}" "URLInfoAbout" "${APP_URL}"
|
||||
WriteRegStr HKCU "${UNINST_KEY}" "DisplayIcon" "$INSTDIR\Luminary.ico"
|
||||
WriteRegStr HKCU "${UNINST_KEY}" "InstallLocation" "$INSTDIR"
|
||||
WriteRegStr HKCU "${UNINST_KEY}" "UninstallString" '"$INSTDIR\Uninstall.exe"'
|
||||
WriteRegStr HKCU "${UNINST_KEY}" "QuietUninstallString" '"$INSTDIR\Uninstall.exe" /S'
|
||||
WriteRegDWORD HKCU "${UNINST_KEY}" "EstimatedSize" ${INSTALL_KB}
|
||||
WriteRegDWORD HKCU "${UNINST_KEY}" "NoModify" 1
|
||||
WriteRegDWORD HKCU "${UNINST_KEY}" "NoRepair" 1
|
||||
SectionEnd
|
||||
|
||||
Section "Desktop shortcut" SEC_DESKTOP
|
||||
!if /FileExists "${SOURCE_DIR}/Luminary.vbs"
|
||||
CreateShortCut "$DESKTOP\Luminary.lnk" "$INSTDIR\Luminary.vbs" "" "$INSTDIR\Luminary.ico" 0
|
||||
!else
|
||||
CreateShortCut "$DESKTOP\Luminary.lnk" "$INSTDIR\Luminary.cmd" "" "$INSTDIR\Luminary.ico" 0
|
||||
!endif
|
||||
SectionEnd
|
||||
|
||||
Section "Start Luminary when I sign in" SEC_STARTUP
|
||||
!if /FileExists "${SOURCE_DIR}/Luminary.vbs"
|
||||
WriteRegStr HKCU "${RUN_KEY}" "Luminary" '"$INSTDIR\Luminary.vbs"'
|
||||
!else
|
||||
WriteRegStr HKCU "${RUN_KEY}" "Luminary" '"$INSTDIR\Luminary.cmd"'
|
||||
!endif
|
||||
SectionEnd
|
||||
|
||||
!insertmacro MUI_FUNCTION_DESCRIPTION_BEGIN
|
||||
!insertmacro MUI_DESCRIPTION_TEXT ${SEC_MAIN} $(DESC_Main)
|
||||
!insertmacro MUI_DESCRIPTION_TEXT ${SEC_DESKTOP} $(DESC_Desktop)
|
||||
!insertmacro MUI_DESCRIPTION_TEXT ${SEC_STARTUP} $(DESC_Startup)
|
||||
!insertmacro MUI_FUNCTION_DESCRIPTION_END
|
||||
|
||||
Section "Uninstall"
|
||||
!insertmacro StopRunning
|
||||
|
||||
Delete "$SMPROGRAMS\Luminary\Luminary.lnk"
|
||||
Delete "$SMPROGRAMS\Luminary\Stop Luminary.lnk"
|
||||
Delete "$SMPROGRAMS\Luminary\Luminary data folder.lnk"
|
||||
RMDir "$SMPROGRAMS\Luminary"
|
||||
Delete "$DESKTOP\Luminary.lnk"
|
||||
|
||||
DeleteRegValue HKCU "${RUN_KEY}" "Luminary"
|
||||
DeleteRegKey HKCU "${UNINST_KEY}"
|
||||
DeleteRegKey HKCU "${APP_KEY}"
|
||||
|
||||
; %LOCALAPPDATA%\Luminary\data is deliberately outside $INSTDIR, so this
|
||||
; only removes the program, its logs and its runtime marker.
|
||||
RMDir /r "$INSTDIR"
|
||||
|
||||
IfSilent uninstallDone
|
||||
MessageBox MB_ICONINFORMATION|MB_OK "${APP_NAME} was removed.$\r$\n$\r$\nYour catalog in $LOCALAPPDATA\Luminary\data was kept: delete that folder yourself if you no longer want it."
|
||||
uninstallDone:
|
||||
SectionEnd
|
||||
@@ -0,0 +1,388 @@
|
||||
# Windows launcher design
|
||||
|
||||
The launcher is not part of the app: it only chooses a port, sets environment
|
||||
variables the server already reads, starts `node.exe`, and gets the user to the
|
||||
browser. Nothing here requires a change to `server/` or `src/`.
|
||||
|
||||
Two implementations ship from the same rules:
|
||||
|
||||
| File | Built when | Process lifetime | Console |
|
||||
| --- | --- | --- | --- |
|
||||
| `Luminary.ps1` + `Luminary.cmd` / `Luminary.vbs` | always (no toolchain) | launcher exits after the browser opens, node keeps running | none via `.vbs`, brief via `.cmd` |
|
||||
| `go/main.go` → `Luminary.exe` | a Go toolchain is present (`--launcher go`, or automatically under `windows/Dockerfile`) | launcher stays alive, removes its state file when the server exits | none (`-H windowsgui`) |
|
||||
|
||||
`Luminary.ps1` is always included because `Stop Luminary.cmd` calls it in both
|
||||
modes.
|
||||
|
||||
## Bundle layout the launcher assumes
|
||||
|
||||
```
|
||||
Luminary\
|
||||
node.exe
|
||||
Luminary.exe | Luminary.cmd / Luminary.vbs
|
||||
Luminary.ps1
|
||||
Stop Luminary.cmd
|
||||
runtime.json (created at run time)
|
||||
logs\server.out.log
|
||||
logs\server.err.log
|
||||
logs\launcher.log (Go launcher only)
|
||||
app\server\index.mjs
|
||||
app\dist\
|
||||
app\node_modules\
|
||||
```
|
||||
|
||||
`root` is the folder containing the launcher executable/script, never the
|
||||
current working directory, so shortcuts and "Run as administrator" behave the
|
||||
same.
|
||||
|
||||
## 1. Single instance
|
||||
|
||||
There is no mutex and no named object. The state file `runtime.json` records
|
||||
`{ pid, port, url, data, started }`, and **health is the liveness test**:
|
||||
|
||||
```
|
||||
runtime.json exists
|
||||
└─ GET http://127.0.0.1:<port>/api/health == 200 ?
|
||||
yes → open the browser on that URL, exit 0 (do not start a second server)
|
||||
no → stale entry: start a new server and overwrite runtime.json
|
||||
```
|
||||
|
||||
Why not check the PID: Windows reuses PIDs, and `os.FindProcess`/`Get-Process`
|
||||
can succeed for an unrelated process. A health response from the recorded port
|
||||
also proves the port belongs to *this* server instance.
|
||||
|
||||
Why not a lock file: a crashed server must not lock the user out. The health
|
||||
probe self-heals in one request.
|
||||
|
||||
A second launch while the first server is still booting waits for it instead of
|
||||
racing:
|
||||
|
||||
```
|
||||
runtime.json pid is alive but health is not up yet
|
||||
└─ poll /api/health for up to 120 s
|
||||
ok → open the browser, exit 0 (no second server, no second port)
|
||||
dead → that boot crashed; fall through and start a fresh server
|
||||
alive but still unhealthy after 120 s → dialog with the log location, exit 1
|
||||
```
|
||||
|
||||
The PID is only used to ask "is a boot in progress?", never as proof of life on
|
||||
its own: health still decides whether the recorded server is usable. Two
|
||||
launches landing within the same millisecond can both pass the check before
|
||||
either writes `runtime.json`; they then bind different ports and both serve the
|
||||
same catalog (SQLite WAL tolerates that). A mutex with stale-lock recovery would
|
||||
close that window, at the cost of a failure mode where a crashed boot locks the
|
||||
user out; for a desktop launcher a second browser tab is the better trade.
|
||||
|
||||
## 2. Port policy
|
||||
|
||||
- Preference order: `8787`, then `8788` … `8887` (100 candidates).
|
||||
- A port is taken if a `TcpListener` cannot bind it on `127.0.0.1`
|
||||
(PowerShell) / `net.Listen("tcp", "127.0.0.1:<port>")` (Go).
|
||||
- The chosen port is passed as `PORT`; the server already reads it
|
||||
(`server/config.mjs`), and the browser URL is built from the same value.
|
||||
- Ports are never inherited from the environment: a stale `PORT` exported by a
|
||||
shell must not make the launcher open the wrong URL.
|
||||
- **Loopback only:** `HOST=127.0.0.1` avoids the Windows Firewall prompt and the
|
||||
app is a single-user desktop install. For LAN proofing galleries the user sets
|
||||
`HOST=0.0.0.0` in the environment before starting, or edits `Luminary.ps1` —
|
||||
documented, not the default.
|
||||
|
||||
## 3. Data directory
|
||||
|
||||
Precedence, first match wins:
|
||||
|
||||
1. `LUMINARY_DATA` — already exported (a power user or an installer can pin it).
|
||||
2. `%LOCALAPPDATA%\Luminary\data`.
|
||||
3. `%USERPROFILE%\AppData\Local\Luminary\data` if `LOCALAPPDATA` is empty.
|
||||
|
||||
Never inside `app\`: an update replaces `app\` wholesale, and `%ProgramFiles%`
|
||||
is read-only for a non-admin user. The launcher creates the directory with
|
||||
`MkdirAll`/`New-Item -Force` before starting the server; the server also creates
|
||||
it, but a clear write failure from the launcher is a better error than a stack
|
||||
trace in a hidden log.
|
||||
|
||||
The folder holds the SQLite catalog (plus `-wal`/`-shm`), `secret.key` and all
|
||||
image folders. Backups copy this folder while the server is stopped.
|
||||
|
||||
When the bundle folder is not writable (write-protected USB, `%ProgramFiles%`
|
||||
for a non-admin user) two things move into the data folder: `runtime.json` and
|
||||
the `logs` folder. The launcher probes the bundle folder with a throwaway file
|
||||
before choosing, so checklist case 6 still starts.
|
||||
|
||||
## 4. Environment contract
|
||||
|
||||
Only variables the server already understands are set:
|
||||
|
||||
| Variable | Value |
|
||||
| --- | --- |
|
||||
| `PORT` | chosen port |
|
||||
| `HOST` | `127.0.0.1` |
|
||||
| `NODE_ENV` | `production` |
|
||||
| `LUMINARY_DATA` | resolved data directory |
|
||||
|
||||
`LUMINARY_INVITE`, SMTP, quota and bridge settings are left alone; they are
|
||||
admin-editable in the UI or set by a power user in the environment.
|
||||
|
||||
The child inherits the rest of the environment (`Start-Process` and
|
||||
`cmd.Env = append(os.Environ(), …)`).
|
||||
|
||||
## 5. Start and health wait
|
||||
|
||||
```
|
||||
create data dir → create log dir → pick port → spawn node.exe (hidden)
|
||||
→ write runtime.json
|
||||
→ poll /api/health every 700 ms, up to 120 s
|
||||
ok → open http://127.0.0.1:<port> and return
|
||||
fail → print/record the last 20 lines of stderr, kill the child,
|
||||
remove runtime.json, exit 1
|
||||
```
|
||||
|
||||
- 120 s covers a Defender scan of `node.exe` plus `libraw.wasm` on a cold boot.
|
||||
- The poll interval is short enough that a warm start feels instant (usually the
|
||||
second or third attempt).
|
||||
- The PowerShell launcher checks `$process.HasExited` first, so a crash reports
|
||||
the log instead of waiting the full timeout.
|
||||
- The browser is opened only after health succeeds; opening earlier shows a
|
||||
connection error on slow machines.
|
||||
|
||||
Logs are append-only: `logs\server.out.log` and `logs\server.err.log` from the
|
||||
child, `logs\launcher.log` from the Go launcher. They fall back to
|
||||
`<data>\logs` when the bundle folder is read-only. Rotation is not implemented;
|
||||
the files are small (startup lines plus request errors) and a support note says
|
||||
they can be deleted while the server is stopped.
|
||||
|
||||
## 6. Stop
|
||||
|
||||
`Stop Luminary.cmd` → `Luminary.ps1 -Stop`:
|
||||
|
||||
1. Read `runtime.json`; if absent or the process is gone → "not running"
|
||||
(exit 0, idempotent).
|
||||
2. `taskkill /PID <pid> /T /F` — `/T` also covers any helper processes, `/F`
|
||||
because the server has no shutdown hook to answer a polite close.
|
||||
3. Delete `runtime.json`.
|
||||
|
||||
Because `runtime.json` is written only after a successful spawn, Stop never
|
||||
kills an unrelated process **unless** the file is stale and the PID has been
|
||||
reused. The window is tiny; the health probe in the start path avoids creating
|
||||
that state, and a support note explains deleting `runtime.json` by hand.
|
||||
|
||||
With the Go launcher, Stop kills the child, `cmd.Wait()` returns, the launcher
|
||||
removes `runtime.json` itself and exits 0. The launcher never outlives the
|
||||
server.
|
||||
|
||||
## 7. Status
|
||||
|
||||
`Luminary.ps1 -Status` prints PID, URL, health state and the data directory.
|
||||
Useful for support without opening Task Manager.
|
||||
|
||||
## 8. Upgrade flow
|
||||
|
||||
1. `Stop Luminary.cmd`.
|
||||
2. Replace `app\` (and `node.exe` if the bundle ships a newer runtime) from the
|
||||
new bundle. Keep `runtime.json`, `logs\` and the data folder.
|
||||
3. Start again. The server migrates the SQLite schema on boot.
|
||||
|
||||
The launcher does not version-check; `version.txt` in the bundle root records
|
||||
the Luminary version, commit and Node version for support.
|
||||
|
||||
## 9. Incomplete bundle diagnostics
|
||||
|
||||
The launcher is a few files next to a large `app\` tree, so the three realistic
|
||||
failure modes are a zip that was opened instead of extracted, an antivirus that
|
||||
quarantined `node.exe`, and a launcher copied out of the source tree. All three
|
||||
look identical from the outside ("node.exe is missing"), so the launcher checks
|
||||
`node.exe`, `app\server\index.mjs` and `app\dist\index.html`, treats zero-byte
|
||||
files as missing, and prints the fix for each cause:
|
||||
|
||||
| Entry point | Behaviour |
|
||||
| --- | --- |
|
||||
| `Luminary.cmd -Verify` | prints the bundle path, each required file with its size, the version from `version.txt`, and exits `3` on a problem |
|
||||
| `Luminary.cmd` | same diagnosis on stderr/stdout, then exits `3` instead of pretending to start |
|
||||
| `Luminary.vbs` | a message box before PowerShell is even started, because a silent exit would look like nothing happened |
|
||||
| `Luminary.exe` | a `MessageBoxW` dialog (it is linked with `-H windowsgui`, so there is no console) and a line in `logs\launcher.log` |
|
||||
|
||||
`version.txt` records `node <version> win-x64 sha256 <hash> size <bytes>`, so the
|
||||
help text can quote the exact hash the build verified against nodejs.org, and
|
||||
the launcher can spot a truncated file by size without hashing 94 MB on every
|
||||
launch.
|
||||
|
||||
## 10. Preflight checks
|
||||
|
||||
`Test-Platform` runs before the runtime is resolved, and `-Status` prints the
|
||||
same report. It checks only what the bundle actually needs — taken from the
|
||||
shipped binaries' PE imports, not from a generic checklist:
|
||||
|
||||
| Check | Source | Result |
|
||||
| --- | --- | --- |
|
||||
| Windows 10+ | `HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\CurrentBuild` ≥ 10240 | blocking dialog, exit 4 |
|
||||
| 64-bit | `PROCESSOR_ARCHITECTURE` is `AMD64` or `ARM64` | blocking dialog, exit 4 |
|
||||
| Universal C Runtime | `%SystemRoot%\System32\ucrtbase.dll` | blocking dialog with the KB2999226 link |
|
||||
| free space on the data drive | `DriveInfo.AvailableFreeSpace` | note below 2 GB, blocking below 200 MB |
|
||||
| ARM64 | `PROCESSOR_ARCHITECTURE` | note: x64 emulation, slower RAW decode |
|
||||
|
||||
Why the list is this short:
|
||||
|
||||
- `node.exe` imports only system DLLs (KERNEL32, ADVAPI32, WS2_32, CRYPT32,
|
||||
USER32, …) and links the C runtime statically, so the Visual C++
|
||||
Redistributable is **not** required. Checked with `objdump -p` on the bundled
|
||||
binary.
|
||||
- `libvips-42.dll` imports the UCRT (`api-ms-win-crt-*`), which ships with
|
||||
Windows 10/11. It does not import `vcruntime140.dll` or `msvcp140.dll`.
|
||||
- The only native modules in the bundle are sharp's three files plus
|
||||
`libraw.wasm`; SQLite comes from `node:sqlite`, not a native addon.
|
||||
- PowerShell 5.1 is part of Windows 10/11, and the `.vbs` entry point checks for
|
||||
it explicitly before launching anything.
|
||||
|
||||
The launcher cannot install a Windows update, so a missing UCRT is explained
|
||||
with its KB number and URL rather than "fixed". The one artefact it can fetch
|
||||
itself is `node.exe`: `-Repair` does it, and a launch with no usable runtime
|
||||
offers the same download in a Yes/No dialog.
|
||||
|
||||
## 11. Desktop mode and the app window
|
||||
|
||||
Both launchers set `LUMINARY_LOCAL=1`; nothing else does.
|
||||
|
||||
| Behaviour | Effect |
|
||||
| --- | --- |
|
||||
| boot | `prepareLocalOwner()` creates `local@luminary` (random password, admin) when missing |
|
||||
| request with no session | `currentUser()` returns the local owner |
|
||||
| `GET /api/auth/me` | 200, so the UI never shows the signup or sign-in view |
|
||||
| `POST /api/auth/register` | 403 |
|
||||
| `POST /api/auth/login` | returns the local session, so a stale login form cannot trap the user |
|
||||
| edit/delete the local owner | 403, it is launcher-managed |
|
||||
| `HOST` not loopback | a warning at boot; the random password means there is nothing to guess |
|
||||
|
||||
The app window uses the browser already on the machine:
|
||||
|
||||
```
|
||||
msedge.exe --app=http://127.0.0.1:<port>
|
||||
--user-data-dir=%LOCALAPPDATA%\Luminary\data\window-profile
|
||||
--window-size=1500,950 --no-first-run --no-default-browser-check
|
||||
```
|
||||
|
||||
`--app` removes tabs, the address bar and the browser chrome; the separate
|
||||
profile keeps the app out of the user's normal history and bookmarks.
|
||||
|
||||
Window preference, first match wins:
|
||||
|
||||
1. `LuminaryWindow.exe` in the bundle root — a WinForms + WebView2 host with its
|
||||
own icon, taskbar entry and window state (`--url <url>`). Built from
|
||||
`launcher/webview2` with the .NET 8 SDK, published self-contained, so the
|
||||
target machine needs no .NET; it does need the WebView2 runtime, which ships
|
||||
with Windows 10/11 alongside Edge. Missing runtime → a dialog with the
|
||||
Evergreen link, not a silent exit.
|
||||
2. Edge `--app`, then Chrome `--app`.
|
||||
3. The default browser (`-Browser` / `LUMINARY_WINDOW=browser` forces this).
|
||||
|
||||
The wrapper is only a window: node stays a child of the launcher, Stop still
|
||||
uses `runtime.json`, and the browser window remains the fallback when the exe
|
||||
is absent or fails to start. A direct launch without `--url` forwards to the
|
||||
bundle launcher and exits immediately; that closes the old hole where
|
||||
double-clicking the window opened port 8787 directly and showed a login page
|
||||
(or a dead URL) because no desktop-mode server was running. The handoff prefers
|
||||
the Go `Luminary.exe`, then runs `Luminary.ps1` in a hidden PowerShell process;
|
||||
it does not use `Luminary.vbs`, because Windows Script Host can be disabled on
|
||||
managed machines even when the bundle is healthy.
|
||||
|
||||
## 12. Runtime resolution and repair
|
||||
|
||||
Three states, checked in order:
|
||||
|
||||
| Bundled `node.exe` | Runtime used | What the user sees |
|
||||
| --- | --- | --- |
|
||||
| present, size matches the pin | `node.exe` | nothing |
|
||||
| missing, empty, or wrong size | system Node 24+ from PATH, `%ProgramFiles%\nodejs`, `%ProgramFiles(x86)%\nodejs`, `%LOCALAPPDATA%\Programs\nodejs`, `%NVM_SYMLINK%` | a warning line and one information dialog naming the path, with the repair command |
|
||||
| neither | none | error dialog listing the three causes, exit 3 |
|
||||
|
||||
The fallback is deliberately not silent: an app quietly running a different
|
||||
runtime is a support mystery, and the user should be told to run `-Repair`.
|
||||
Node below 24 is rejected because `server/denoise-worker.mjs` imports a `.ts`
|
||||
module, which needs the type-stripping runtime.
|
||||
|
||||
`-Repair` (PowerShell and `Luminary.exe -repair`) does the following:
|
||||
|
||||
1. refuses while the server is running — the file is locked, and replacing a
|
||||
runtime under a live process is wrong anyway;
|
||||
2. reads the version and hash from `version.txt`, falling back to
|
||||
`nodejs.org/dist/v<version>/SHASUMS256.txt` when the bundle predates the hash
|
||||
line;
|
||||
3. downloads to a temp file (`LUMINARY_NODE_URL` overrides the URL for a mirror
|
||||
or an air-gapped copy);
|
||||
4. hashes the download and refuses to install anything that does not match the
|
||||
pin — a corporate proxy's HTML error page never becomes `node.exe`;
|
||||
5. replaces `node.exe` atomically (`node.exe.new` + rename) and re-runs the
|
||||
bundle check.
|
||||
|
||||
## 13. Security notes
|
||||
|
||||
- Binds loopback by default; no firewall rule is needed.
|
||||
- Everything runs as the logged-in user; the installer is per-user, no UAC.
|
||||
- The launcher is unsigned, so SmartScreen may warn on first run. Signing the
|
||||
launcher (and ideally `node.exe` provenance) is a distribution task, not a
|
||||
code one.
|
||||
- The data folder is protected by normal user-profile ACLs.
|
||||
|
||||
## 14. Known limitations and phase 2
|
||||
|
||||
- **No tray icon.** Closing the browser does not stop the server; Stop is a
|
||||
shortcut. A tray build needs `Shell_NotifyIcon` (Go with Win32 calls, or C#),
|
||||
roughly a day of work, and can be swapped in without touching the app.
|
||||
- **No auto-update.** Replacing `app\` is manual. An updater would read a
|
||||
version manifest next to the release and download a zip.
|
||||
- **No service mode.** Running before login needs WinSW/NSSM and a fixed
|
||||
account/data directory; that is a different install profile, not a launcher
|
||||
change.
|
||||
- **Localhost only.** Multi-device proofing galleries need `HOST=0.0.0.0` and a
|
||||
firewall rule; that is deliberate for a default desktop install.
|
||||
|
||||
## 15. Test checklist (Windows VM, no Node installed)
|
||||
|
||||
1. Fresh double-click → data folder created, browser opens, login page loads.
|
||||
2. Second double-click → the running instance is reused and the browser opens;
|
||||
no second process, whether the first server is answering or still booting.
|
||||
3. `Stop Luminary.cmd` → process gone, `runtime.json` removed, Stop again says
|
||||
"not running".
|
||||
4. Kill node.exe in Task Manager, start again → new port if the old one is held,
|
||||
otherwise the same port, and the catalog is intact.
|
||||
5. Port 8787 occupied by another app → launcher uses 8788 and opens that URL.
|
||||
6. Read-only install folder (Program Files) with data in `%LOCALAPPDATA%` →
|
||||
starts fine (data path is outside the bundle).
|
||||
7. RAW import, denoise (proves the `.ts` worker), export — i.e. the server is
|
||||
fully functional from the bundle.
|
||||
8. Path with spaces and non-ASCII characters (e.g. `C:\Users\Zoë\Luminary`) →
|
||||
the quoted entry point and `-WorkingDirectory` still work.
|
||||
9. Power loss / hard reboot → stale `runtime.json` is ignored and replaced.
|
||||
10. Delete `node.exe`, then `Luminary.cmd -Verify` → exit code 3 and the three
|
||||
causes; `Luminary.vbs` → message box instead of a silent no-op.
|
||||
11. Run `Luminary.cmd` from inside the zip preview → the "not a complete
|
||||
bundle" message, not a missing-file crash.
|
||||
12. On a machine with Node 24 installed: delete `node.exe` → the launcher warns,
|
||||
starts on the system Node and `-Status` names that path; `-Stop` still works.
|
||||
13. Double-click `LuminaryWindow.exe` with no arguments on a machine where
|
||||
VBScript is disabled → it exits, the hidden PowerShell launcher starts
|
||||
desktop mode, and the reopened window is signed in; no login screen and no
|
||||
Windows Script Host error appear.
|
||||
14. On a machine with no Node: delete `node.exe` → the launch offers the 90 MB
|
||||
download; Yes installs and starts, No exits 3; `-Repair` works as well.
|
||||
15. Truncate `node.exe` (keep the first 100 kB) → `-Verify` reports `damaged`,
|
||||
and `-Repair` replaces it. A partial file is the usual antivirus outcome.
|
||||
16. `-Repair` while the server is running → refused with the stop instruction.
|
||||
17. Write-protect the bundle folder (or use `%ProgramFiles%` without admin) →
|
||||
`runtime.json` and `logs` move to the data folder and the app starts.
|
||||
18. Clean Windows 10/11 VM with no Node, no .NET and no VC++ redistributable →
|
||||
the app starts (proves the import analysis above); `-Status` reports the
|
||||
build, architecture and Node source.
|
||||
19. Windows 8.1 (if available) → the UCRT dialog with the KB2999226 link;
|
||||
Windows 7 → the "needs Windows 10 or 11" dialog, exit 4.
|
||||
20. Fresh data folder → no signup and no sign-in screen; the app is signed in
|
||||
as Local, with no account pill in the top bar and no team/admin entry.
|
||||
21. Restart → the same local account and catalog; delete the data folder →
|
||||
a fresh one with no prompt.
|
||||
22. Default launch → chromeless window, no address bar, own window size;
|
||||
`-Browser` → a normal tab.
|
||||
23. Start the server by hand with `HOST=0.0.0.0` and `LUMINARY_LOCAL=1` → the
|
||||
boot log warns that every client is the local admin.
|
||||
24. Bundle with `LuminaryWindow.exe` → native window with the Luminary icon in
|
||||
the title bar and taskbar; `Stop Luminary.cmd` still ends the server.
|
||||
25. Remove the WebView2 runtime (or use an image without it) → the native
|
||||
window shows the download link instead of disappearing.
|
||||
@@ -0,0 +1,12 @@
|
||||
@echo off
|
||||
rem Start Luminary and open it in the default browser.
|
||||
rem The server keeps running in the background; use "Stop Luminary.cmd" to stop it.
|
||||
rem
|
||||
rem Luminary.cmd start
|
||||
rem Luminary.cmd -Verify list the files the bundle must contain
|
||||
rem Luminary.cmd -Status report pid, url, runtime and data folder
|
||||
rem Luminary.cmd -Repair download node.exe again and verify its sha256
|
||||
rem Luminary.cmd -Stop stop the server started from this folder
|
||||
rem Luminary.cmd -Browser open a normal browser tab instead of the app window
|
||||
powershell.exe -NoProfile -ExecutionPolicy Bypass -File "%~dp0Luminary.ps1" %*
|
||||
if errorlevel 1 pause
|
||||
|
After Width: | Height: | Size: 128 KiB |
@@ -0,0 +1,648 @@
|
||||
<#
|
||||
Luminary launcher (PowerShell).
|
||||
|
||||
This is the no-toolchain launcher: it ships in every bundle and is what
|
||||
Luminary.exe replaces when a Go build is available. It owns the three things
|
||||
the server deliberately does not do for itself:
|
||||
|
||||
1. Pick a free loopback port and pass it as PORT.
|
||||
2. Start node.exe hidden with LUMINARY_DATA outside the bundle.
|
||||
3. Wait for /api/health before opening the browser.
|
||||
|
||||
Usage:
|
||||
Luminary.ps1 start (or reuse) the server and open the browser
|
||||
Luminary.ps1 -Stop stop the server started from this folder
|
||||
Luminary.ps1 -Status report what is running and where the data lives
|
||||
Luminary.ps1 -Verify list the files the bundle must contain
|
||||
Luminary.ps1 -Repair re-download node.exe and check it against version.txt
|
||||
Luminary.ps1 -Browser open a normal browser tab instead of the app window
|
||||
|
||||
Runtime resolution: the bundled node.exe is always preferred. If an antivirus
|
||||
removed it, a system Node 24+ is used instead so the app still starts, and the
|
||||
launcher says so; -Repair restores the pinned runtime.
|
||||
|
||||
State is kept in runtime.json next to this script; logs go to logs\ (or to
|
||||
%LOCALAPPDATA%\Luminary\data\logs when the bundle is on read-only media).
|
||||
#>
|
||||
[CmdletBinding()]
|
||||
param(
|
||||
[switch]$Stop,
|
||||
[switch]$Status,
|
||||
[switch]$Verify,
|
||||
[switch]$Repair,
|
||||
[switch]$Browser
|
||||
)
|
||||
|
||||
$ErrorActionPreference = 'Stop'
|
||||
$ProgressPreference = 'SilentlyContinue'
|
||||
|
||||
$root = Split-Path -Parent $MyInvocation.MyCommand.Path
|
||||
$appDir = Join-Path $root 'app'
|
||||
$nodeExe = Join-Path $root 'node.exe'
|
||||
$entry = Join-Path $appDir 'server\index.mjs'
|
||||
$uiFile = Join-Path $appDir 'dist\index.html'
|
||||
$versionFile = Join-Path $root 'version.txt'
|
||||
$logDir = Join-Path $root 'logs'
|
||||
$runtimeFile = $null # resolved below: it moves to the data folder on read-only media
|
||||
$firstPort = 8787
|
||||
$lastPort = 8887
|
||||
$minNodeMajor = 24
|
||||
|
||||
function Show-Dialog([string]$text, [string]$icon) {
|
||||
try {
|
||||
Add-Type -AssemblyName System.Windows.Forms
|
||||
$kind = [System.Windows.Forms.MessageBoxIcon]::Information
|
||||
if ($icon -eq 'Error') { $kind = [System.Windows.Forms.MessageBoxIcon]::Error }
|
||||
[void][System.Windows.Forms.MessageBox]::Show($text, 'Luminary', [System.Windows.Forms.MessageBoxButtons]::OK, $kind)
|
||||
} catch {
|
||||
Write-Host $text
|
||||
}
|
||||
}
|
||||
|
||||
function Show-ErrorDialog([string]$text) {
|
||||
# The .vbs entry point runs PowerShell hidden, so a console-only failure would
|
||||
# look like nothing happened.
|
||||
Show-Dialog $text 'Error'
|
||||
}
|
||||
|
||||
function Show-Question([string]$text) {
|
||||
try {
|
||||
Add-Type -AssemblyName System.Windows.Forms
|
||||
$answer = [System.Windows.Forms.MessageBox]::Show($text, 'Luminary', [System.Windows.Forms.MessageBoxButtons]::YesNo, [System.Windows.Forms.MessageBoxIcon]::Question)
|
||||
return ($answer -eq [System.Windows.Forms.DialogResult]::Yes)
|
||||
} catch {
|
||||
Write-Host $text
|
||||
return $false
|
||||
}
|
||||
}
|
||||
|
||||
function Get-DataDir {
|
||||
if ($env:LUMINARY_DATA) { return $env:LUMINARY_DATA }
|
||||
$base = $env:LOCALAPPDATA
|
||||
if (-not $base) {
|
||||
if ($env:USERPROFILE) {
|
||||
$base = Join-Path $env:USERPROFILE 'AppData\Local'
|
||||
} else {
|
||||
# Neither variable is set: a stripped environment (service account, CI)
|
||||
# rather than a normal desktop login. Never Join-Path a null.
|
||||
$base = [System.IO.Path]::GetTempPath()
|
||||
}
|
||||
}
|
||||
return (Join-Path $base 'Luminary\data')
|
||||
}
|
||||
|
||||
function Read-Runtime {
|
||||
if (-not (Test-Path -LiteralPath $runtimeFile)) { return $null }
|
||||
try { return Get-Content -Raw -LiteralPath $runtimeFile | ConvertFrom-Json } catch { return $null }
|
||||
}
|
||||
|
||||
function Test-Health([int]$port) {
|
||||
try {
|
||||
$response = Invoke-WebRequest -UseBasicParsing -TimeoutSec 2 -Uri ("http://127.0.0.1:{0}/api/health" -f $port)
|
||||
return ($response.StatusCode -eq 200)
|
||||
} catch { return $false }
|
||||
}
|
||||
|
||||
function Test-Process([int]$processId) {
|
||||
try { return $null -ne (Get-Process -Id $processId -ErrorAction Stop) } catch { return $false }
|
||||
}
|
||||
|
||||
function Test-PortFree([int]$port) {
|
||||
$listener = $null
|
||||
try {
|
||||
$listener = New-Object System.Net.Sockets.TcpListener([System.Net.IPAddress]::Loopback, $port)
|
||||
$listener.Start()
|
||||
return $true
|
||||
} catch {
|
||||
return $false
|
||||
} finally {
|
||||
if ($listener) { $listener.Stop() }
|
||||
}
|
||||
}
|
||||
|
||||
function Find-Port {
|
||||
for ($port = $firstPort; $port -le $lastPort; $port++) {
|
||||
if (Test-PortFree $port) { return $port }
|
||||
}
|
||||
throw ("No free TCP port between {0} and {1}." -f $firstPort, $lastPort)
|
||||
}
|
||||
|
||||
function Open-Browser([string]$url) {
|
||||
try { Start-Process $url | Out-Null } catch { Write-Host ("Open {0} in a browser." -f $url) }
|
||||
}
|
||||
|
||||
# Edge is part of Windows 10/11, so a chromeless app window costs no extra
|
||||
# runtime. Chrome is the second choice; anything else falls back to a tab.
|
||||
function Find-AppWindowBrowser {
|
||||
$candidates = @()
|
||||
if (${env:ProgramFiles(x86)}) {
|
||||
$candidates += (Join-Path ${env:ProgramFiles(x86)} 'Microsoft\Edge\Application\msedge.exe')
|
||||
}
|
||||
if ($env:ProgramFiles) {
|
||||
$candidates += (Join-Path $env:ProgramFiles 'Microsoft\Edge\Application\msedge.exe')
|
||||
}
|
||||
if ($env:LOCALAPPDATA) {
|
||||
$candidates += (Join-Path $env:LOCALAPPDATA 'Microsoft\Edge\Application\msedge.exe')
|
||||
$candidates += (Join-Path $env:LOCALAPPDATA 'Google\Chrome\Application\chrome.exe')
|
||||
}
|
||||
if ($env:ProgramFiles) {
|
||||
$candidates += (Join-Path $env:ProgramFiles 'Google\Chrome\Application\chrome.exe')
|
||||
}
|
||||
if (${env:ProgramFiles(x86)}) {
|
||||
$candidates += (Join-Path ${env:ProgramFiles(x86)} 'Google\Chrome\Application\chrome.exe')
|
||||
}
|
||||
foreach ($candidate in $candidates) {
|
||||
if ($candidate -and (Test-Path -LiteralPath $candidate)) { return $candidate }
|
||||
}
|
||||
return $null
|
||||
}
|
||||
|
||||
# --app gives a window with no tabs and no address bar, in its own profile, so
|
||||
# it reads as a desktop app rather than a web page. -Browser opts out.
|
||||
function Open-App([string]$url) {
|
||||
if ($Browser -or $env:LUMINARY_WINDOW -eq 'browser') {
|
||||
Open-Browser $url
|
||||
return
|
||||
}
|
||||
# A native WebView2 host, when the bundle ships one, is the real app window:
|
||||
# its own icon, no browser branding at all.
|
||||
$native = Join-Path $root 'LuminaryWindow.exe'
|
||||
if (Test-Path -LiteralPath $native) {
|
||||
try {
|
||||
Start-Process -FilePath $native -ArgumentList @('--url', $url) | Out-Null
|
||||
return
|
||||
} catch {
|
||||
# fall through to the browser window
|
||||
}
|
||||
}
|
||||
$exe = Find-AppWindowBrowser
|
||||
if (-not $exe) {
|
||||
Open-Browser $url
|
||||
return
|
||||
}
|
||||
$profile = Join-Path (Get-DataDir) 'window-profile'
|
||||
try {
|
||||
New-Item -ItemType Directory -Force -Path $profile | Out-Null
|
||||
Start-Process -FilePath $exe -ArgumentList @(
|
||||
"--app=$url",
|
||||
"--user-data-dir=$profile",
|
||||
'--window-size=1500,950',
|
||||
'--no-first-run',
|
||||
'--no-default-browser-check',
|
||||
'--disable-features=Translate'
|
||||
) | Out-Null
|
||||
} catch {
|
||||
Open-Browser $url
|
||||
}
|
||||
}
|
||||
|
||||
function Get-WindowsBuild {
|
||||
try {
|
||||
$current = Get-ItemProperty -Path 'HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion' -ErrorAction Stop
|
||||
return [int]$current.CurrentBuild
|
||||
} catch { return 0 }
|
||||
}
|
||||
|
||||
# What a customer machine actually needs. Everything else is in the bundle:
|
||||
# node.exe ships with it (and -Repair re-downloads it), libvips needs only the
|
||||
# Universal C Runtime that Windows 10/11 already has, and no admin rights are
|
||||
# involved. Verified against the PE imports of node.exe and libvips-42.dll.
|
||||
function Test-Platform {
|
||||
$problems = @()
|
||||
$notes = @()
|
||||
|
||||
$build = Get-WindowsBuild
|
||||
if ($build -gt 0 -and $build -lt 10240) {
|
||||
$problems += ("Luminary needs Windows 10 or 11. This PC reports build {0}." -f $build)
|
||||
}
|
||||
|
||||
$arch = $env:PROCESSOR_ARCHITECTURE
|
||||
if ($arch -and $arch -ne 'AMD64' -and $arch -ne 'ARM64') {
|
||||
$problems += ("Luminary ships a 64-bit runtime; this PC reports '{0}'." -f $arch)
|
||||
} elseif ($arch -eq 'ARM64') {
|
||||
$notes += 'ARM64 Windows runs the x64 runtime under emulation, so RAW decoding is slower.'
|
||||
}
|
||||
|
||||
if ($env:SystemRoot -and -not (Test-Path -LiteralPath (Join-Path $env:SystemRoot 'System32\ucrtbase.dll'))) {
|
||||
$problems += 'The Universal C Runtime is missing (Windows 8.1 without KB2999226). Install it from support.microsoft.com/help/2999226, or use Windows 10/11.'
|
||||
}
|
||||
|
||||
# ~130 MB unpacked, plus room for catalogs and previews that grow over time.
|
||||
$dataDir = Get-DataDir
|
||||
$qualifier = $null
|
||||
try { $qualifier = Split-Path -Qualifier $dataDir -ErrorAction Stop } catch { }
|
||||
if ($qualifier) {
|
||||
try {
|
||||
$drive = New-Object System.IO.DriveInfo -ArgumentList $qualifier
|
||||
$freeGb = [math]::Round($drive.AvailableFreeSpace / 1GB, 1)
|
||||
if ($drive.AvailableFreeSpace -lt 200MB) {
|
||||
$problems += ("The data drive has only {0} GB free; Luminary needs about 0.25 GB to start." -f $freeGb)
|
||||
} elseif ($drive.AvailableFreeSpace -lt 2GB) {
|
||||
$notes += ("Only {0} GB free on the data drive; catalogs and previews grow from there." -f $freeGb)
|
||||
}
|
||||
} catch { }
|
||||
}
|
||||
|
||||
return @{ ok = ($problems.Count -eq 0); problems = $problems; notes = $notes }
|
||||
}
|
||||
|
||||
# --- runtime resolution -------------------------------------------------------
|
||||
|
||||
function Read-NodePin {
|
||||
$pin = @{ version = $null; sha256 = $null; size = [int64]0 }
|
||||
if (-not (Test-Path -LiteralPath $versionFile)) { return $pin }
|
||||
$line = Get-Content -LiteralPath $versionFile |
|
||||
Where-Object { $_ -match '^node\s+v?\d+\.\d+\.\d+\s+win-x64' } |
|
||||
Select-Object -First 1
|
||||
if (-not $line) { return $pin }
|
||||
if ($line -match '^node\s+v?(\d+\.\d+\.\d+)') { $pin.version = $Matches[1] }
|
||||
if ($line -match 'sha256\s+([0-9a-f]{64})') { $pin.sha256 = $Matches[1] }
|
||||
if ($line -match 'size\s+(\d+)') { $pin.size = [int64]$Matches[1] }
|
||||
return $pin
|
||||
}
|
||||
|
||||
function Get-SystemNode([string]$exe) {
|
||||
if (-not $exe) { return $null }
|
||||
if (-not (Test-Path -LiteralPath $exe)) { return $null }
|
||||
try { $raw = & $exe '--version' 2>$null } catch { return $null }
|
||||
if (-not $raw) { return $null }
|
||||
$raw = "$raw".Trim()
|
||||
if ($raw -notmatch '^v?(\d+)\.') { return $null }
|
||||
if ([int]$Matches[1] -lt $minNodeMajor) { return $null }
|
||||
return $raw
|
||||
}
|
||||
|
||||
# The bundled runtime wins; a system Node 24+ is a fallback, never a preference.
|
||||
function Resolve-Node {
|
||||
if (Test-Path -LiteralPath $nodeExe) {
|
||||
$info = Get-Item -LiteralPath $nodeExe
|
||||
$pin = Read-NodePin
|
||||
$intact = $info.Length -gt 0
|
||||
# A pinned size catches a truncated file that antivirus left behind; the
|
||||
# hash itself is only checked by -Verify and -Repair.
|
||||
if ($intact -and $pin.size -gt 0 -and $info.Length -ne $pin.size) { $intact = $false }
|
||||
if ($intact) { return @{ path = $nodeExe; version = 'bundled'; system = $false } }
|
||||
}
|
||||
|
||||
$candidates = @()
|
||||
$onPath = Get-Command node.exe -CommandType Application -ErrorAction SilentlyContinue | Select-Object -First 1
|
||||
if ($onPath) { $candidates += $onPath.Source }
|
||||
if ($env:ProgramFiles) { $candidates += (Join-Path $env:ProgramFiles 'nodejs\node.exe') }
|
||||
if (${env:ProgramFiles(x86)}) { $candidates += (Join-Path ${env:ProgramFiles(x86)} 'nodejs\node.exe') }
|
||||
if ($env:LOCALAPPDATA) { $candidates += (Join-Path $env:LOCALAPPDATA 'Programs\nodejs\node.exe') }
|
||||
if ($env:NVM_SYMLINK) { $candidates += (Join-Path $env:NVM_SYMLINK 'node.exe') }
|
||||
|
||||
$seen = @{}
|
||||
foreach ($candidate in $candidates) {
|
||||
if (-not $candidate) { continue }
|
||||
$key = $candidate.ToLowerInvariant()
|
||||
if ($seen.ContainsKey($key)) { continue }
|
||||
$seen[$key] = $true
|
||||
$version = Get-SystemNode $candidate
|
||||
if ($version) { return @{ path = $candidate; version = $version; system = $true } }
|
||||
}
|
||||
return $null
|
||||
}
|
||||
|
||||
# --- repair -------------------------------------------------------------------
|
||||
|
||||
function Get-PublishedHash([string]$version) {
|
||||
$uri = "https://nodejs.org/dist/v$version/SHASUMS256.txt"
|
||||
$text = (Invoke-WebRequest -UseBasicParsing -TimeoutSec 30 -Uri $uri).Content
|
||||
foreach ($line in ($text -split "`n")) {
|
||||
$parts = $line.Trim() -split '\s+'
|
||||
if ($parts.Count -ge 2 -and $parts[1] -eq 'win-x64/node.exe') { return $parts[0].ToLowerInvariant() }
|
||||
}
|
||||
return $null
|
||||
}
|
||||
|
||||
function Repair-Node {
|
||||
$pin = Read-NodePin
|
||||
if (-not $pin.version) {
|
||||
throw "version.txt does not record a node version, so there is nothing to re-download. Extract the zip again instead."
|
||||
}
|
||||
|
||||
$expected = $pin.sha256
|
||||
if (-not $expected) {
|
||||
Write-Host ("Fetching the published checksum for node v{0}..." -f $pin.version)
|
||||
$expected = Get-PublishedHash $pin.version
|
||||
}
|
||||
if (-not $expected) {
|
||||
throw "No SHA-256 is available for node v$($pin.version), so the download cannot be verified. Refusing to install it."
|
||||
}
|
||||
|
||||
$url = $env:LUMINARY_NODE_URL
|
||||
if (-not $url) { $url = "https://nodejs.org/dist/v$($pin.version)/win-x64/node.exe" }
|
||||
|
||||
Write-Host ("Downloading {0}" -f $url)
|
||||
$temp = Join-Path ([System.IO.Path]::GetTempPath()) ("luminary-node-{0}.exe" -f [guid]::NewGuid().ToString('N'))
|
||||
try {
|
||||
Invoke-WebRequest -UseBasicParsing -TimeoutSec 600 -Uri $url -OutFile $temp
|
||||
$actual = (Get-FileHash -LiteralPath $temp -Algorithm SHA256).Hash.ToLowerInvariant()
|
||||
if ($actual -ne $expected.ToLowerInvariant()) {
|
||||
throw ("The downloaded node.exe does not match the expected checksum (got {0}, want {1}). Nothing was changed." -f $actual, $expected)
|
||||
}
|
||||
if (Test-Path -LiteralPath $nodeExe) {
|
||||
try { (Get-Item -LiteralPath $nodeExe).IsReadOnly = $false } catch { }
|
||||
}
|
||||
Move-Item -LiteralPath $temp -Destination $nodeExe -Force
|
||||
Write-Host ("node.exe restored: v{0}, sha256 {1}" -f $pin.version, $actual)
|
||||
} finally {
|
||||
if (Test-Path -LiteralPath $temp) { Remove-Item -LiteralPath $temp -Force -ErrorAction SilentlyContinue }
|
||||
}
|
||||
}
|
||||
|
||||
# --- bundle checks ------------------------------------------------------------
|
||||
|
||||
# Prints a line for every file the bundle needs and returns $true when all are
|
||||
# present and non-empty. A zero-byte file is what an antivirus or a half-done
|
||||
# extraction leaves behind, so it is treated as missing.
|
||||
function Test-Bundle {
|
||||
$ok = $true
|
||||
$required = @(
|
||||
@{ Name = 'app\server\index.mjs'; Path = $entry },
|
||||
@{ Name = 'app\dist\index.html'; Path = $uiFile }
|
||||
)
|
||||
foreach ($item in $required) {
|
||||
if (-not (Test-Path -LiteralPath $item.Path)) {
|
||||
Write-Host (" missing {0}" -f $item.Name)
|
||||
$ok = $false
|
||||
} elseif ((Get-Item -LiteralPath $item.Path).Length -eq 0) {
|
||||
Write-Host (" empty {0} ({1})" -f $item.Name, $item.Path)
|
||||
$ok = $false
|
||||
}
|
||||
}
|
||||
return $ok
|
||||
}
|
||||
|
||||
function Write-BundleHelp {
|
||||
$pin = Read-NodePin
|
||||
Write-Host ''
|
||||
Write-Host 'This folder is not a complete Luminary bundle. The usual causes:'
|
||||
Write-Host ''
|
||||
Write-Host ' 1. The zip was opened, not extracted. Close it, right-click the zip,'
|
||||
Write-Host ' choose "Extract All...", then run Luminary.cmd (or Luminary.vbs)'
|
||||
Write-Host ' from the extracted Luminary folder. A file started from inside the'
|
||||
Write-Host ' zip preview is copied out on its own, without node.exe or app\.'
|
||||
Write-Host ''
|
||||
Write-Host ' 2. Antivirus or SmartScreen removed node.exe after extraction.'
|
||||
Write-Host ' Run "Luminary.cmd -Repair" to download it again and verify it'
|
||||
Write-Host ' against the checksum in version.txt.'
|
||||
if ($pin.sha256) { Write-Host (' expected sha256: {0}' -f $pin.sha256) }
|
||||
Write-Host ''
|
||||
Write-Host ' 3. This is the source checkout, not a bundle. In the repository run'
|
||||
Write-Host ' "node windows/build.mjs" and use the zip it prints.'
|
||||
Write-Host ''
|
||||
Write-Host 'Run "Luminary.cmd -Verify" to list every file the launcher needs.'
|
||||
}
|
||||
|
||||
function Get-LogDir([string]$dataDir) {
|
||||
try {
|
||||
New-Item -ItemType Directory -Force -Path $logDir | Out-Null
|
||||
return $logDir
|
||||
} catch {
|
||||
# Read-only media (USB stick with the write-protect switch, a network share
|
||||
# the user cannot write): keep the logs with the data instead of failing.
|
||||
$fallback = Join-Path $dataDir 'logs'
|
||||
New-Item -ItemType Directory -Force -Path $fallback | Out-Null
|
||||
Write-Host ("Logs go to {0} (the bundle folder is not writable)." -f $fallback)
|
||||
return $fallback
|
||||
}
|
||||
}
|
||||
|
||||
# The state file lives in the bundle folder so a copied bundle is self-contained.
|
||||
# On read-only media (write-protected USB, Program Files for a non-admin user) it
|
||||
# moves next to the data, which is always writable.
|
||||
$runtimeFile = Join-Path $root 'runtime.json'
|
||||
try {
|
||||
$probe = Join-Path $root ('.write-test-{0}' -f [guid]::NewGuid().ToString('N'))
|
||||
[System.IO.File]::WriteAllText($probe, '')
|
||||
Remove-Item -LiteralPath $probe -Force
|
||||
} catch {
|
||||
$runtimeFile = Join-Path (Get-DataDir) 'runtime.json'
|
||||
}
|
||||
|
||||
# --- commands -----------------------------------------------------------------
|
||||
|
||||
if ($Verify) {
|
||||
Write-Host ("Bundle: {0}" -f $root)
|
||||
$complete = Test-Bundle
|
||||
$pin = Read-NodePin
|
||||
if (-not (Test-Path -LiteralPath $nodeExe)) {
|
||||
Write-Host ' missing node.exe'
|
||||
$complete = $false
|
||||
} else {
|
||||
$nodeInfo = Get-Item -LiteralPath $nodeExe
|
||||
if ($nodeInfo.Length -eq 0) {
|
||||
Write-Host ' empty node.exe'
|
||||
$complete = $false
|
||||
} elseif ($pin.size -gt 0 -and $nodeInfo.Length -ne $pin.size) {
|
||||
Write-Host (" damaged node.exe ({0:N0} bytes, expected {1:N0})" -f $nodeInfo.Length, $pin.size)
|
||||
$complete = $false
|
||||
}
|
||||
}
|
||||
if ($complete) {
|
||||
foreach ($file in @($nodeExe, $entry, $uiFile)) {
|
||||
$shown = $file.Replace($root + '\', '')
|
||||
Write-Host (" ok {0} ({1:N0} bytes)" -f $shown, (Get-Item -LiteralPath $file).Length)
|
||||
}
|
||||
if ($pin.version) { Write-Host ("Node: v{0} (pinned)" -f $pin.version) }
|
||||
Write-Host 'The bundle is complete.'
|
||||
exit 0
|
||||
}
|
||||
Write-BundleHelp
|
||||
exit 3
|
||||
}
|
||||
|
||||
$runtime = Read-Runtime
|
||||
$running = $runtime -and (Test-Process ([int]$runtime.pid))
|
||||
|
||||
if ($Repair) {
|
||||
if ($running) {
|
||||
Write-Host 'Luminary is running. Stop it first: "Luminary.cmd -Stop".'
|
||||
exit 1
|
||||
}
|
||||
try {
|
||||
Repair-Node
|
||||
} catch {
|
||||
Write-Host ''
|
||||
Write-Host ("Repair failed: {0}" -f $_.Exception.Message)
|
||||
Show-ErrorDialog ("node.exe could not be restored.`n`n" + $_.Exception.Message)
|
||||
exit 1
|
||||
}
|
||||
Write-Host ''
|
||||
if (Test-Bundle) {
|
||||
Write-Host 'The bundle is complete and ready to run.'
|
||||
exit 0
|
||||
}
|
||||
Write-BundleHelp
|
||||
exit 3
|
||||
}
|
||||
|
||||
if ($Status) {
|
||||
if ($running) {
|
||||
$reachable = Test-Health ([int]$runtime.port)
|
||||
$state = 'not answering yet'
|
||||
if ($reachable) { $state = 'ok' }
|
||||
Write-Host ("Luminary is running (pid {0}) at {1}; health {2}." -f $runtime.pid, $runtime.url, $state)
|
||||
} else {
|
||||
Write-Host 'Luminary is not running.'
|
||||
}
|
||||
$platform = Test-Platform
|
||||
Write-Host ("System: Windows build {0}, {1}" -f (Get-WindowsBuild), $env:PROCESSOR_ARCHITECTURE)
|
||||
foreach ($note in $platform.notes) { Write-Host ("Note: {0}" -f $note) }
|
||||
foreach ($problem in $platform.problems) { Write-Host ("Problem: {0}" -f $problem) }
|
||||
$node = Resolve-Node
|
||||
if ($node) {
|
||||
if ($node.system) {
|
||||
Write-Host ("Node: {0} ({1}) - bundled node.exe is missing; run -Repair" -f $node.path, $node.version)
|
||||
} else {
|
||||
Write-Host 'Node: bundled node.exe'
|
||||
}
|
||||
} else {
|
||||
Write-Host 'Node: missing (run -Repair)'
|
||||
}
|
||||
Write-Host ("Data: {0}" -f (Get-DataDir))
|
||||
exit 0
|
||||
}
|
||||
|
||||
if ($Stop) {
|
||||
if (-not $running) {
|
||||
Write-Host 'Luminary is not running.'
|
||||
Remove-Item -LiteralPath $runtimeFile -Force -ErrorAction SilentlyContinue
|
||||
exit 0
|
||||
}
|
||||
& taskkill.exe /PID ([int]$runtime.pid) /T /F | Out-Null
|
||||
Remove-Item -LiteralPath $runtimeFile -Force -ErrorAction SilentlyContinue
|
||||
Write-Host 'Luminary stopped.'
|
||||
exit 0
|
||||
}
|
||||
|
||||
# A second double-click while the first server is still booting must wait for it,
|
||||
# not start a second server on the same catalog.
|
||||
if ($running) {
|
||||
Write-Host 'Luminary is already starting; waiting for it to answer...'
|
||||
$deadline = (Get-Date).AddSeconds(120)
|
||||
while ((Get-Date) -lt $deadline) {
|
||||
if (Test-Health ([int]$runtime.port)) {
|
||||
Write-Host ("Luminary is running at {0}" -f $runtime.url)
|
||||
Open-App ([string]$runtime.url)
|
||||
exit 0
|
||||
}
|
||||
if (-not (Test-Process ([int]$runtime.pid))) { break }
|
||||
Start-Sleep -Milliseconds 700
|
||||
}
|
||||
if (Test-Process ([int]$runtime.pid)) {
|
||||
$logNote = Join-Path (Get-DataDir) 'logs'
|
||||
Show-ErrorDialog ("Luminary has been starting for over two minutes and is not answering on port {0}.`n`nSee {1} for the server log." -f $runtime.port, $logNote)
|
||||
exit 1
|
||||
}
|
||||
}
|
||||
|
||||
if ($runtime -and (Test-Health ([int]$runtime.port))) {
|
||||
Write-Host ("Luminary is already running at {0}" -f $runtime.url)
|
||||
Open-App ([string]$runtime.url)
|
||||
exit 0
|
||||
}
|
||||
|
||||
if (-not (Test-Bundle)) {
|
||||
Write-Host ''
|
||||
Write-Host 'Luminary cannot start: this folder is incomplete.'
|
||||
Write-BundleHelp
|
||||
Show-ErrorDialog 'This folder is not a complete Luminary bundle. See the console for the three usual causes.'
|
||||
exit 3
|
||||
}
|
||||
|
||||
$platform = Test-Platform
|
||||
foreach ($note in $platform.notes) { Write-Host ("Note: {0}" -f $note) }
|
||||
if (-not $platform.ok) {
|
||||
$message = ($platform.problems -join "`n`n") + "`n`nLuminary runs on Windows 10/11 (64-bit) with a current browser (Edge, Chrome or Firefox) for the Develop module. Nothing else needs to be installed."
|
||||
Write-Host $message
|
||||
Show-ErrorDialog $message
|
||||
exit 4
|
||||
}
|
||||
|
||||
$node = Resolve-Node
|
||||
if (-not $node) {
|
||||
# The only download Luminary can need is its own runtime. Offer it here so a
|
||||
# customer who never reads the README still gets a working install.
|
||||
if (Show-Question "Luminary needs its Node.js 24 runtime, but node.exe is missing from this folder.`n`nDownload it now from nodejs.org (about 90 MB)?") {
|
||||
try {
|
||||
Repair-Node
|
||||
$node = Resolve-Node
|
||||
} catch {
|
||||
Write-Host ("Download failed: {0}" -f $_.Exception.Message)
|
||||
Show-ErrorDialog ("The runtime download failed.`n`n" + $_.Exception.Message)
|
||||
exit 3
|
||||
}
|
||||
}
|
||||
if (-not $node) {
|
||||
$message = "Luminary cannot start without node.exe.`n`nRun ""Luminary.cmd -Repair"" to download it, or install Node.js 24 from nodejs.org."
|
||||
Write-Host $message
|
||||
Show-ErrorDialog $message
|
||||
exit 3
|
||||
}
|
||||
}
|
||||
|
||||
if ($node.system) {
|
||||
$warning = ("The bundled node.exe is missing; Luminary is using the system Node {0} at {1}.`n`n" +
|
||||
"Run ""Luminary.cmd -Repair"" to restore the pinned runtime." -f $node.version, $node.path)
|
||||
Write-Host $warning
|
||||
Show-Dialog $warning 'Information'
|
||||
}
|
||||
|
||||
$dataDir = Get-DataDir
|
||||
New-Item -ItemType Directory -Force -Path $dataDir | Out-Null
|
||||
$logsOut = Get-LogDir $dataDir
|
||||
|
||||
$port = Find-Port
|
||||
$url = "http://127.0.0.1:$port"
|
||||
|
||||
# The server reads these from the environment; nothing is written into app\.
|
||||
$env:PORT = "$port"
|
||||
$env:HOST = '127.0.0.1'
|
||||
$env:NODE_ENV = 'production'
|
||||
$env:LUMINARY_DATA = $dataDir
|
||||
# Desktop mode: one local admin, no signup, no sign-in. Loopback only, so this
|
||||
# never exposes a passwordless account to the network.
|
||||
$env:LUMINARY_LOCAL = '1'
|
||||
|
||||
$outLog = Join-Path $logsOut 'server.out.log'
|
||||
$errLog = Join-Path $logsOut 'server.err.log'
|
||||
$process = Start-Process -FilePath $node.path `
|
||||
-ArgumentList ('"' + $entry + '"') `
|
||||
-WorkingDirectory $appDir `
|
||||
-WindowStyle Hidden `
|
||||
-PassThru `
|
||||
-RedirectStandardOutput $outLog `
|
||||
-RedirectStandardError $errLog
|
||||
|
||||
@{
|
||||
pid = $process.Id
|
||||
port = $port
|
||||
url = $url
|
||||
data = $dataDir
|
||||
node = $node.path
|
||||
started = (Get-Date).ToString('o')
|
||||
} | ConvertTo-Json | Set-Content -LiteralPath $runtimeFile -Encoding UTF8
|
||||
|
||||
$deadline = (Get-Date).AddSeconds(120)
|
||||
while ((Get-Date) -lt $deadline) {
|
||||
if ($process.HasExited) { break }
|
||||
if (Test-Health $port) {
|
||||
Write-Host ("Luminary is running at {0}" -f $url)
|
||||
Write-Host ("Data: {0}" -f $dataDir)
|
||||
Open-App $url
|
||||
exit 0
|
||||
}
|
||||
Start-Sleep -Milliseconds 700
|
||||
}
|
||||
|
||||
$tail = ''
|
||||
if (Test-Path -LiteralPath $errLog) { $tail = (Get-Content -LiteralPath $errLog -Tail 20) -join "`n" }
|
||||
Write-Host 'Luminary did not answer on /api/health.'
|
||||
if ($tail) { Write-Host $tail }
|
||||
if (-not $process.HasExited) { & taskkill.exe /PID $process.Id /T /F | Out-Null }
|
||||
Remove-Item -LiteralPath $runtimeFile -Force -ErrorAction SilentlyContinue
|
||||
Show-ErrorDialog ("Luminary did not start.`n`n" + $tail)
|
||||
exit 1
|
||||
@@ -0,0 +1,36 @@
|
||||
' Start Luminary without a console window.
|
||||
' Double-click this file, or use the shortcut an installer creates.
|
||||
Option Explicit
|
||||
|
||||
Dim fso, shell, here, script, nodeExe, powershell
|
||||
Set fso = CreateObject("Scripting.FileSystemObject")
|
||||
Set shell = CreateObject("WScript.Shell")
|
||||
|
||||
here = fso.GetParentFolderName(WScript.ScriptFullName)
|
||||
script = fso.BuildPath(here, "Luminary.ps1")
|
||||
nodeExe = fso.BuildPath(here, "node.exe")
|
||||
powershell = fso.BuildPath(shell.ExpandEnvironmentStrings("%SystemRoot%"), "System32\WindowsPowerShell\v1.0\powershell.exe")
|
||||
|
||||
' Windows 10/11 always has PowerShell; a stripped image may not. Say so instead
|
||||
' of letting WScript report a script error.
|
||||
If Not fso.FileExists(powershell) Then
|
||||
MsgBox "Windows PowerShell is missing, so Luminary cannot start." & vbCrLf & vbCrLf & _
|
||||
"PowerShell 5.1 is included with Windows 10 and 11. On a stripped image, " & _
|
||||
"install it from Microsoft, or run Luminary.cmd on a normal desktop.", _
|
||||
16, "Luminary"
|
||||
WScript.Quit 4
|
||||
End If
|
||||
|
||||
' A file started from inside a zip preview is copied out on its own, so the
|
||||
' launcher is the only thing present. Say so instead of failing silently.
|
||||
If Not fso.FileExists(script) Or Not fso.FileExists(nodeExe) Then
|
||||
MsgBox "This folder is not a complete Luminary bundle." & vbCrLf & vbCrLf & _
|
||||
"Right-click the zip you downloaded, choose ""Extract All..."", then run " & _
|
||||
"Luminary.vbs or Luminary.cmd from the extracted Luminary folder." & vbCrLf & vbCrLf & _
|
||||
"If node.exe is missing after extracting, antivirus or SmartScreen " & _
|
||||
"removed it: run Luminary.ps1 -Repair (or re-extract the zip) to restore it.", _
|
||||
16, "Luminary"
|
||||
WScript.Quit 3
|
||||
End If
|
||||
|
||||
shell.Run """" & powershell & """ -NoProfile -ExecutionPolicy Bypass -WindowStyle Hidden -File """ & script & """", 0, False
|
||||
@@ -0,0 +1,4 @@
|
||||
@echo off
|
||||
rem Stop the Luminary server started from this folder.
|
||||
powershell.exe -NoProfile -ExecutionPolicy Bypass -File "%~dp0Luminary.ps1" -Stop
|
||||
pause
|
||||
@@ -0,0 +1,3 @@
|
||||
module luminary/launcher
|
||||
|
||||
go 1.21
|
||||
@@ -0,0 +1,688 @@
|
||||
//go:build windows
|
||||
|
||||
// Luminary launcher (Go).
|
||||
//
|
||||
// Optional: when a Go toolchain is available, windows/build.mjs compiles this
|
||||
// into Luminary.exe and ships it instead of the PowerShell entry points. It
|
||||
// does the same jobs as Luminary.ps1, with one difference: being a real
|
||||
// process it can stay in the background and clean up after the server exits.
|
||||
//
|
||||
// Usage:
|
||||
//
|
||||
// Luminary.exe start (or reuse) the server and open the browser
|
||||
// Luminary.exe -stop stop the server started from this folder
|
||||
// Luminary.exe -repair re-download node.exe and verify it against version.txt
|
||||
//
|
||||
// The design and the edge cases are described in ../DESIGN.md.
|
||||
package main
|
||||
|
||||
import (
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net"
|
||||
"net/http"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"strconv"
|
||||
"strings"
|
||||
"syscall"
|
||||
"time"
|
||||
"unsafe"
|
||||
)
|
||||
|
||||
const (
|
||||
firstPort = 8787
|
||||
lastPort = 8887
|
||||
healthPath = "/api/health"
|
||||
startupWait = 120 * time.Second
|
||||
pollEvery = 700 * time.Millisecond
|
||||
minNodeMajor = 24
|
||||
// CREATE_NO_WINDOW keeps the console-based node.exe from flashing a window
|
||||
// even though the launcher itself is linked with -H windowsgui.
|
||||
createNoWindow = 0x08000000
|
||||
// PROCESS_QUERY_LIMITED_INFORMATION is enough to tell whether a pid is alive
|
||||
// and needs no debug privilege.
|
||||
processQueryLimitedInformation = 0x1000
|
||||
)
|
||||
|
||||
var (
|
||||
root = bundleRoot()
|
||||
logsDir = filepath.Join(root, "logs")
|
||||
// A -H windowsgui binary has no console, so a missing file would otherwise
|
||||
// fail silently. MessageBoxW is the only feedback a user can see.
|
||||
user32 = syscall.NewLazyDLL("user32.dll")
|
||||
messageBoxW = user32.NewProc("MessageBoxW")
|
||||
|
||||
client = &http.Client{Timeout: 2 * time.Second}
|
||||
downloadClient = &http.Client{Timeout: 10 * time.Minute}
|
||||
nodePinRE = regexp.MustCompile(`^node\s+v?(\d+\.\d+\.\d+)\s+win-x64(?:\s+sha256\s+([0-9a-f]{64}))?(?:\s+size\s+(\d+))?`)
|
||||
)
|
||||
|
||||
type runtimeInfo struct {
|
||||
PID int `json:"pid"`
|
||||
Port int `json:"port"`
|
||||
URL string `json:"url"`
|
||||
Data string `json:"data"`
|
||||
Node string `json:"node"`
|
||||
Started string `json:"started"`
|
||||
}
|
||||
|
||||
type nodeRuntime struct {
|
||||
path string
|
||||
label string
|
||||
system bool
|
||||
}
|
||||
|
||||
var browserOnly = false
|
||||
|
||||
func main() {
|
||||
args := os.Args[1:]
|
||||
browserOnly = hasFlag(args, "-browser", "--browser")
|
||||
switch {
|
||||
case hasFlag(args, "-repair", "--repair", "/repair"):
|
||||
if err := repair(); err != nil {
|
||||
writeLog("launcher.log", "repair: "+err.Error())
|
||||
showError("node.exe could not be restored.\n\n" + err.Error())
|
||||
os.Exit(1)
|
||||
}
|
||||
showInfo("node.exe is restored and matches the checksum in version.txt.\n\n" +
|
||||
filepath.Join(root, "node.exe"))
|
||||
return
|
||||
case hasFlag(args, "-stop", "--stop", "/stop"):
|
||||
if err := stop(); err != nil {
|
||||
showError(err.Error())
|
||||
os.Exit(1)
|
||||
}
|
||||
showInfo("Luminary stopped.")
|
||||
return
|
||||
}
|
||||
|
||||
if err := run(); err != nil {
|
||||
writeLog("launcher.log", "error: "+err.Error())
|
||||
showError(err.Error())
|
||||
os.Exit(1)
|
||||
}
|
||||
}
|
||||
|
||||
func hasFlag(args []string, names ...string) bool {
|
||||
for _, arg := range args {
|
||||
for _, name := range names {
|
||||
if strings.EqualFold(arg, name) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func showError(text string) { showMessage(text, 0x10) }
|
||||
|
||||
func ask(text string) bool {
|
||||
title, titleErr := syscall.UTF16PtrFromString("Luminary")
|
||||
body, bodyErr := syscall.UTF16PtrFromString(text)
|
||||
if titleErr != nil || bodyErr != nil {
|
||||
return false
|
||||
}
|
||||
// MB_YESNO | MB_ICONQUESTION | MB_SETFOREGROUND; IDYES is 6.
|
||||
result, _, _ := messageBoxW.Call(0, uintptr(unsafe.Pointer(body)), uintptr(unsafe.Pointer(title)), 0x04|0x20|0x10000)
|
||||
return result == 6
|
||||
}
|
||||
|
||||
func showInfo(text string) { showMessage(text, 0x40) }
|
||||
|
||||
func showMessage(text string, kind uintptr) {
|
||||
title, titleErr := syscall.UTF16PtrFromString("Luminary")
|
||||
body, bodyErr := syscall.UTF16PtrFromString(text)
|
||||
if titleErr != nil || bodyErr != nil {
|
||||
return
|
||||
}
|
||||
// MB_SETFOREGROUND so the dialog is not hidden behind the browser.
|
||||
messageBoxW.Call(0, uintptr(unsafe.Pointer(body)), uintptr(unsafe.Pointer(title)), kind|0x10000)
|
||||
}
|
||||
|
||||
func run() error {
|
||||
nodeExe := filepath.Join(root, "node.exe")
|
||||
appDir := filepath.Join(root, "app")
|
||||
entry := filepath.Join(appDir, "server", "index.mjs")
|
||||
|
||||
required := []struct {
|
||||
name string
|
||||
path string
|
||||
}{
|
||||
{"app\\server\\index.mjs", entry},
|
||||
{"app\\dist\\index.html", filepath.Join(appDir, "dist", "index.html")},
|
||||
}
|
||||
var missing []string
|
||||
for _, file := range required {
|
||||
info, err := os.Stat(file.path)
|
||||
if err != nil {
|
||||
missing = append(missing, file.name)
|
||||
continue
|
||||
}
|
||||
if info.Size() == 0 {
|
||||
// What a half-done extraction or an antivirus leaves behind.
|
||||
missing = append(missing, file.name+" (empty)")
|
||||
}
|
||||
}
|
||||
if len(missing) > 0 {
|
||||
return fmt.Errorf("this folder is not a complete Luminary bundle (missing: %s).\n\n"+
|
||||
"Right-click the zip you downloaded, choose \"Extract All...\", then run "+
|
||||
"Luminary.exe from the extracted Luminary folder. If files disappeared "+
|
||||
"after extracting, antivirus or SmartScreen removed them: restore them "+
|
||||
"from quarantine and extract again.", strings.Join(missing, ", "))
|
||||
}
|
||||
|
||||
node, err := resolveNode(nodeExe)
|
||||
if err != nil {
|
||||
// The only download Luminary can need is its own runtime. Offer it here
|
||||
// so a customer who never reads the README still gets a working install.
|
||||
if ask("Luminary needs its Node.js 24 runtime, but node.exe is missing from this bundle.\n\n" +
|
||||
"Download it now from nodejs.org (about 90 MB)?") {
|
||||
if repairErr := repair(); repairErr != nil {
|
||||
return fmt.Errorf("the runtime download failed: %w", repairErr)
|
||||
}
|
||||
node, err = resolveNode(nodeExe)
|
||||
}
|
||||
if err != nil {
|
||||
return fmt.Errorf("%w\n\nRun \"Luminary.exe -repair\" to download the pinned runtime "+
|
||||
"again, or install Node.js 24 from nodejs.org.", err)
|
||||
}
|
||||
}
|
||||
if node.system {
|
||||
message := fmt.Sprintf("The bundled node.exe is missing or damaged, so Luminary is using %s.\n\n"+
|
||||
"Run \"Luminary.exe -repair\" to restore the pinned runtime.", node.label)
|
||||
writeLog("launcher.log", "warning: "+message)
|
||||
showInfo(message)
|
||||
}
|
||||
|
||||
// Already running, or still booting: health is the liveness test, so a stale
|
||||
// runtime.json from a crash falls through to a fresh start instead of
|
||||
// blocking it, and a second double-click waits instead of starting a second
|
||||
// server on the same catalog.
|
||||
if info, ok := readRuntime(); ok {
|
||||
if healthy(info.Port) {
|
||||
openApp(info.URL)
|
||||
return nil
|
||||
}
|
||||
if processAlive(info.PID) {
|
||||
deadline := time.Now().Add(startupWait)
|
||||
for time.Now().Before(deadline) {
|
||||
if healthy(info.Port) {
|
||||
openApp(info.URL)
|
||||
return nil
|
||||
}
|
||||
if !processAlive(info.PID) {
|
||||
break
|
||||
}
|
||||
time.Sleep(pollEvery)
|
||||
}
|
||||
if processAlive(info.PID) {
|
||||
return fmt.Errorf("Luminary is already starting (pid %d) but is not answering on port %d. "+
|
||||
"See %s.", info.PID, info.Port, filepath.Join(dataDirectory(), "logs", "server.err.log"))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
dataDir := dataDirectory()
|
||||
if err := os.MkdirAll(dataDir, 0o755); err != nil {
|
||||
return fmt.Errorf("cannot create the data directory %s: %w", dataDir, err)
|
||||
}
|
||||
logDir, err := ensureLogDir(dataDir)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
port, err := freePort()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
url := fmt.Sprintf("http://127.0.0.1:%d", port)
|
||||
|
||||
stdout, err := openLog(logDir, "server.out.log")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer stdout.Close()
|
||||
stderr, err := openLog(logDir, "server.err.log")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer stderr.Close()
|
||||
|
||||
cmd := exec.Command(node.path, entry)
|
||||
cmd.Dir = appDir
|
||||
cmd.Stdout = stdout
|
||||
cmd.Stderr = stderr
|
||||
cmd.Env = append(os.Environ(),
|
||||
"PORT="+strconv.Itoa(port),
|
||||
"HOST=127.0.0.1",
|
||||
"NODE_ENV=production",
|
||||
"LUMINARY_DATA="+dataDir,
|
||||
// Desktop mode: one local admin, no signup or sign-in. Loopback only,
|
||||
// so this never exposes a passwordless account to the network.
|
||||
"LUMINARY_LOCAL=1",
|
||||
)
|
||||
cmd.SysProcAttr = &syscall.SysProcAttr{HideWindow: true, CreationFlags: createNoWindow}
|
||||
if err := cmd.Start(); err != nil {
|
||||
return fmt.Errorf("cannot start %s: %w", node.path, err)
|
||||
}
|
||||
|
||||
info := runtimeInfo{
|
||||
PID: cmd.Process.Pid,
|
||||
Port: port,
|
||||
URL: url,
|
||||
Data: dataDir,
|
||||
Node: node.path,
|
||||
Started: time.Now().Format(time.RFC3339),
|
||||
}
|
||||
writeRuntime(info)
|
||||
|
||||
deadline := time.Now().Add(startupWait)
|
||||
for time.Now().Before(deadline) {
|
||||
if healthy(port) {
|
||||
openApp(url)
|
||||
// Stay alive for the server's lifetime so runtime.json is removed
|
||||
// on quit and a crash is written to the launcher log. The exit
|
||||
// code is deliberately ignored: "Stop" force-kills the child.
|
||||
_ = cmd.Wait()
|
||||
removeRuntime()
|
||||
writeLog("launcher.log", "server exited")
|
||||
return nil
|
||||
}
|
||||
time.Sleep(pollEvery)
|
||||
}
|
||||
|
||||
_ = cmd.Process.Kill()
|
||||
removeRuntime()
|
||||
return fmt.Errorf("Luminary did not answer on %s within %s; see %s",
|
||||
healthPath, startupWait, filepath.Join(logDir, "server.err.log"))
|
||||
}
|
||||
|
||||
// --- runtime resolution -------------------------------------------------------
|
||||
|
||||
func nodePin() (version, hash string, size int64) {
|
||||
data, err := os.ReadFile(filepath.Join(root, "version.txt"))
|
||||
if err != nil {
|
||||
return "", "", 0
|
||||
}
|
||||
for _, line := range strings.Split(string(data), "\n") {
|
||||
match := nodePinRE.FindStringSubmatch(strings.TrimSpace(line))
|
||||
if match == nil {
|
||||
continue
|
||||
}
|
||||
version = match[1]
|
||||
hash = match[2]
|
||||
if match[3] != "" {
|
||||
size, _ = strconv.ParseInt(match[3], 10, 64)
|
||||
}
|
||||
return version, hash, size
|
||||
}
|
||||
return "", "", 0
|
||||
}
|
||||
|
||||
// The bundled runtime wins; a system Node 24+ is a fallback, never a preference.
|
||||
func resolveNode(bundled string) (nodeRuntime, error) {
|
||||
if info, err := os.Stat(bundled); err == nil && info.Size() > 0 {
|
||||
_, _, pinnedSize := nodePin()
|
||||
if pinnedSize == 0 || info.Size() == pinnedSize {
|
||||
return nodeRuntime{path: bundled, label: "the bundled node.exe"}, nil
|
||||
}
|
||||
}
|
||||
|
||||
seen := map[string]bool{}
|
||||
for _, candidate := range systemNodeCandidates() {
|
||||
key := strings.ToLower(candidate)
|
||||
if seen[key] {
|
||||
continue
|
||||
}
|
||||
seen[key] = true
|
||||
info, err := os.Stat(candidate)
|
||||
if err != nil || info.Size() == 0 {
|
||||
continue
|
||||
}
|
||||
if major, ok := nodeMajor(candidate); ok && major >= minNodeMajor {
|
||||
return nodeRuntime{
|
||||
path: candidate,
|
||||
label: fmt.Sprintf("the system Node %d at %s", major, candidate),
|
||||
system: true,
|
||||
}, nil
|
||||
}
|
||||
}
|
||||
|
||||
return nodeRuntime{}, fmt.Errorf("node.exe is missing from the bundle and no Node.js %d+ was found on this machine", minNodeMajor)
|
||||
}
|
||||
|
||||
func systemNodeCandidates() []string {
|
||||
var candidates []string
|
||||
if found, err := exec.LookPath("node.exe"); err == nil {
|
||||
candidates = append(candidates, found)
|
||||
}
|
||||
if found, err := exec.LookPath("node"); err == nil {
|
||||
candidates = append(candidates, found)
|
||||
}
|
||||
if dir := os.Getenv("ProgramFiles"); dir != "" {
|
||||
candidates = append(candidates, filepath.Join(dir, "nodejs", "node.exe"))
|
||||
}
|
||||
if dir := os.Getenv("ProgramFiles(x86)"); dir != "" {
|
||||
candidates = append(candidates, filepath.Join(dir, "nodejs", "node.exe"))
|
||||
}
|
||||
if dir := os.Getenv("LOCALAPPDATA"); dir != "" {
|
||||
candidates = append(candidates, filepath.Join(dir, "Programs", "nodejs", "node.exe"))
|
||||
}
|
||||
if dir := os.Getenv("NVM_SYMLINK"); dir != "" {
|
||||
candidates = append(candidates, filepath.Join(dir, "node.exe"))
|
||||
}
|
||||
return candidates
|
||||
}
|
||||
|
||||
func nodeMajor(exe string) (int, bool) {
|
||||
cmd := exec.Command(exe, "--version")
|
||||
cmd.SysProcAttr = &syscall.SysProcAttr{HideWindow: true, CreationFlags: createNoWindow}
|
||||
out, err := cmd.Output()
|
||||
if err != nil {
|
||||
return 0, false
|
||||
}
|
||||
raw := strings.TrimPrefix(strings.TrimSpace(string(out)), "v")
|
||||
parts := strings.SplitN(raw, ".", 2)
|
||||
major, err := strconv.Atoi(parts[0])
|
||||
if err != nil || major <= 0 {
|
||||
return 0, false
|
||||
}
|
||||
return major, true
|
||||
}
|
||||
|
||||
// --- repair -------------------------------------------------------------------
|
||||
|
||||
func repair() error {
|
||||
nodeExe := filepath.Join(root, "node.exe")
|
||||
if info, ok := readRuntime(); ok && (healthy(info.Port) || processAlive(info.PID)) {
|
||||
return fmt.Errorf("Luminary is running (pid %d). Stop it first: Luminary.exe -stop", info.PID)
|
||||
}
|
||||
|
||||
version, expected, _ := nodePin()
|
||||
if version == "" {
|
||||
return fmt.Errorf("version.txt does not record a node version, so there is nothing to re-download. Extract the zip again instead.")
|
||||
}
|
||||
if expected == "" {
|
||||
hash, err := publishedHash(version)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
expected = hash
|
||||
}
|
||||
|
||||
url := os.Getenv("LUMINARY_NODE_URL")
|
||||
if url == "" {
|
||||
url = fmt.Sprintf("https://nodejs.org/dist/v%s/win-x64/node.exe", version)
|
||||
}
|
||||
writeLog("launcher.log", "repair: downloading "+url)
|
||||
|
||||
response, err := downloadClient.Get(url)
|
||||
if err != nil {
|
||||
return fmt.Errorf("cannot download node.exe: %w", err)
|
||||
}
|
||||
defer response.Body.Close()
|
||||
if response.StatusCode != http.StatusOK {
|
||||
return fmt.Errorf("cannot download node.exe: %s answered %s", url, response.Status)
|
||||
}
|
||||
|
||||
temp := filepath.Join(root, "node.exe.new")
|
||||
file, err := os.Create(temp)
|
||||
if err != nil {
|
||||
return fmt.Errorf("cannot write next to the launcher: %w", err)
|
||||
}
|
||||
hasher := sha256.New()
|
||||
_, copyErr := io.Copy(io.MultiWriter(file, hasher), response.Body)
|
||||
closeErr := file.Close()
|
||||
if copyErr != nil {
|
||||
_ = os.Remove(temp)
|
||||
return fmt.Errorf("the download stopped early: %w", copyErr)
|
||||
}
|
||||
if closeErr != nil {
|
||||
_ = os.Remove(temp)
|
||||
return fmt.Errorf("cannot finish writing node.exe: %w", closeErr)
|
||||
}
|
||||
|
||||
actual := hex.EncodeToString(hasher.Sum(nil))
|
||||
if !strings.EqualFold(actual, expected) {
|
||||
_ = os.Remove(temp)
|
||||
return fmt.Errorf("the downloaded node.exe does not match the expected checksum (got %s, want %s). Nothing was changed.", actual, expected)
|
||||
}
|
||||
|
||||
// Windows will not rename over an existing file; a running server is already
|
||||
// refused above, so the old copy is not in use here.
|
||||
_ = os.Remove(nodeExe)
|
||||
if err := os.Rename(temp, nodeExe); err != nil {
|
||||
_ = os.Remove(temp)
|
||||
return fmt.Errorf("cannot replace node.exe: %w", err)
|
||||
}
|
||||
writeLog("launcher.log", fmt.Sprintf("repair: restored node v%s sha256 %s", version, actual))
|
||||
return nil
|
||||
}
|
||||
|
||||
func publishedHash(version string) (string, error) {
|
||||
url := fmt.Sprintf("https://nodejs.org/dist/v%s/SHASUMS256.txt", version)
|
||||
response, err := downloadClient.Get(url)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("cannot fetch the published checksum: %w", err)
|
||||
}
|
||||
defer response.Body.Close()
|
||||
if response.StatusCode != http.StatusOK {
|
||||
return "", fmt.Errorf("cannot fetch the published checksum: %s answered %s", url, response.Status)
|
||||
}
|
||||
body, err := io.ReadAll(response.Body)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("cannot read the published checksum: %w", err)
|
||||
}
|
||||
for _, line := range strings.Split(string(body), "\n") {
|
||||
fields := strings.Fields(line)
|
||||
if len(fields) >= 2 && fields[1] == "win-x64/node.exe" {
|
||||
return strings.ToLower(fields[0]), nil
|
||||
}
|
||||
}
|
||||
return "", fmt.Errorf("no win-x64/node.exe checksum for v%s", version)
|
||||
}
|
||||
|
||||
// --- commands -----------------------------------------------------------------
|
||||
|
||||
func stop() error {
|
||||
info, ok := readRuntime()
|
||||
if !ok {
|
||||
showInfo("Luminary is not running.")
|
||||
return nil
|
||||
}
|
||||
// /T also takes down sharp's helper processes and the denoise workers.
|
||||
if err := exec.Command("taskkill.exe", "/PID", strconv.Itoa(info.PID), "/T", "/F").Run(); err != nil && processAlive(info.PID) {
|
||||
return fmt.Errorf("cannot stop pid %d: %w", info.PID, err)
|
||||
}
|
||||
removeRuntime()
|
||||
return nil
|
||||
}
|
||||
|
||||
// --- helpers ------------------------------------------------------------------
|
||||
|
||||
func bundleRoot() string {
|
||||
exe, err := os.Executable()
|
||||
if err != nil {
|
||||
return "."
|
||||
}
|
||||
return filepath.Dir(exe)
|
||||
}
|
||||
|
||||
func dataDirectory() string {
|
||||
if dir := strings.TrimSpace(os.Getenv("LUMINARY_DATA")); dir != "" {
|
||||
return dir
|
||||
}
|
||||
base := os.Getenv("LOCALAPPDATA")
|
||||
if base == "" {
|
||||
base = filepath.Join(os.Getenv("USERPROFILE"), "AppData", "Local")
|
||||
}
|
||||
return filepath.Join(base, "Luminary", "data")
|
||||
}
|
||||
|
||||
// A bundle on read-only media still has to boot; the logs move next to the data.
|
||||
func ensureLogDir(dataDir string) (string, error) {
|
||||
if err := os.MkdirAll(logsDir, 0o755); err == nil {
|
||||
return logsDir, nil
|
||||
}
|
||||
fallback := filepath.Join(dataDir, "logs")
|
||||
if err := os.MkdirAll(fallback, 0o755); err != nil {
|
||||
return "", fmt.Errorf("cannot create a log directory: %w", err)
|
||||
}
|
||||
return fallback, nil
|
||||
}
|
||||
|
||||
func freePort() (int, error) {
|
||||
for port := firstPort; port <= lastPort; port++ {
|
||||
listener, err := net.Listen("tcp", fmt.Sprintf("127.0.0.1:%d", port))
|
||||
if err == nil {
|
||||
listener.Close()
|
||||
return port, nil
|
||||
}
|
||||
}
|
||||
return 0, fmt.Errorf("no free TCP port between %d and %d", firstPort, lastPort)
|
||||
}
|
||||
|
||||
func healthy(port int) bool {
|
||||
response, err := client.Get(fmt.Sprintf("http://127.0.0.1:%d%s", port, healthPath))
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
defer response.Body.Close()
|
||||
return response.StatusCode == http.StatusOK
|
||||
}
|
||||
|
||||
func processAlive(pid int) bool {
|
||||
handle, err := syscall.OpenProcess(processQueryLimitedInformation, false, uint32(pid))
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
syscall.CloseHandle(handle)
|
||||
return true
|
||||
}
|
||||
|
||||
func openBrowser(url string) {
|
||||
// FileProtocolHandler goes through the user's default browser without
|
||||
// needing a protocol registration of our own.
|
||||
_ = exec.Command("rundll32", "url.dll,FileProtocolHandler", url).Start()
|
||||
}
|
||||
|
||||
// Edge ships with Windows 10/11, so a chromeless app window costs no extra
|
||||
// runtime. Chrome is the second choice; anything else falls back to a tab.
|
||||
func findAppBrowser() string {
|
||||
candidates := []string{}
|
||||
add := func(dir string, rest ...string) {
|
||||
if dir != "" {
|
||||
candidates = append(candidates, filepath.Join(append([]string{dir}, rest...)...))
|
||||
}
|
||||
}
|
||||
for _, key := range []string{"ProgramFiles(x86)", "ProgramFiles", "LOCALAPPDATA"} {
|
||||
add(os.Getenv(key), "Microsoft", "Edge", "Application", "msedge.exe")
|
||||
}
|
||||
for _, key := range []string{"LOCALAPPDATA", "ProgramFiles", "ProgramFiles(x86)"} {
|
||||
add(os.Getenv(key), "Google", "Chrome", "Application", "chrome.exe")
|
||||
}
|
||||
for _, candidate := range candidates {
|
||||
if info, err := os.Stat(candidate); err == nil && info.Size() > 0 {
|
||||
return candidate
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// --app gives a window with no tabs and no address bar, in its own profile, so
|
||||
// it reads as a desktop app rather than a web page. -browser opts out.
|
||||
func openApp(url string) {
|
||||
if browserOnly || strings.EqualFold(os.Getenv("LUMINARY_WINDOW"), "browser") {
|
||||
openBrowser(url)
|
||||
return
|
||||
}
|
||||
// A native WebView2 host, when the bundle ships one, is the real app window:
|
||||
// its own icon, no browser branding at all.
|
||||
native := filepath.Join(root, "LuminaryWindow.exe")
|
||||
if info, err := os.Stat(native); err == nil && info.Size() > 0 {
|
||||
if err := exec.Command(native, "--url", url).Start(); err == nil {
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
exe := findAppBrowser()
|
||||
if exe == "" {
|
||||
openBrowser(url)
|
||||
return
|
||||
}
|
||||
profile := filepath.Join(dataDirectory(), "window-profile")
|
||||
if err := os.MkdirAll(profile, 0o755); err != nil {
|
||||
openBrowser(url)
|
||||
return
|
||||
}
|
||||
cmd := exec.Command(exe,
|
||||
"--app="+url,
|
||||
"--user-data-dir="+profile,
|
||||
"--window-size=1500,950",
|
||||
"--no-first-run",
|
||||
"--no-default-browser-check",
|
||||
"--disable-features=Translate",
|
||||
)
|
||||
if err := cmd.Start(); err != nil {
|
||||
openBrowser(url)
|
||||
}
|
||||
}
|
||||
|
||||
// The state file lives in the bundle folder so a copied bundle is self-contained.
|
||||
// On read-only media (write-protected USB, Program Files for a non-admin user)
|
||||
// it moves next to the data, which is always writable.
|
||||
func runtimePath() string {
|
||||
probe := filepath.Join(root, ".write-test")
|
||||
if err := os.WriteFile(probe, nil, 0o644); err == nil {
|
||||
_ = os.Remove(probe)
|
||||
return filepath.Join(root, "runtime.json")
|
||||
}
|
||||
return filepath.Join(dataDirectory(), "runtime.json")
|
||||
}
|
||||
|
||||
func readRuntime() (runtimeInfo, bool) {
|
||||
var info runtimeInfo
|
||||
data, err := os.ReadFile(runtimePath())
|
||||
if err != nil {
|
||||
return info, false
|
||||
}
|
||||
if json.Unmarshal(data, &info) != nil || info.PID == 0 || info.Port == 0 {
|
||||
return info, false
|
||||
}
|
||||
return info, true
|
||||
}
|
||||
|
||||
func writeRuntime(info runtimeInfo) {
|
||||
data, err := json.MarshalIndent(info, "", " ")
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
_ = os.WriteFile(runtimePath(), append(data, '\n'), 0o644)
|
||||
}
|
||||
|
||||
func removeRuntime() {
|
||||
_ = os.Remove(runtimePath())
|
||||
}
|
||||
|
||||
func openLog(dir, name string) (*os.File, error) {
|
||||
return os.OpenFile(filepath.Join(dir, name), os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0o644)
|
||||
}
|
||||
|
||||
func writeLog(name, message string) {
|
||||
dir, err := ensureLogDir(dataDirectory())
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
file, err := openLog(dir, name)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
defer file.Close()
|
||||
fmt.Fprintf(file, "%s %s\n", time.Now().Format(time.RFC3339), message)
|
||||
}
|
||||