@decaf-ts/for-os 0.0.0-stage → 0.2.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (77) hide show
  1. package/LICENSE.md +21 -0
  2. package/README.md +380 -2
  3. package/lib/cjs/errors.cjs +73 -0
  4. package/lib/cjs/errors.cjs.map +1 -0
  5. package/lib/cjs/index.cjs +46 -0
  6. package/lib/cjs/index.cjs.map +1 -0
  7. package/lib/cjs/native/icons.cjs +123 -0
  8. package/lib/cjs/native/icons.cjs.map +1 -0
  9. package/lib/cjs/native/loader.cjs +123 -0
  10. package/lib/cjs/native/loader.cjs.map +1 -0
  11. package/lib/cjs/native/types.cjs +4 -0
  12. package/lib/cjs/native/types.cjs.map +1 -0
  13. package/lib/cjs/notifications/NotificationCenter.cjs +328 -0
  14. package/lib/cjs/notifications/NotificationCenter.cjs.map +1 -0
  15. package/lib/cjs/tray/TrayIcon.cjs +367 -0
  16. package/lib/cjs/tray/TrayIcon.cjs.map +1 -0
  17. package/lib/cjs/tray/assets.cjs +31 -0
  18. package/lib/cjs/tray/assets.cjs.map +1 -0
  19. package/lib/esm/errors.js +65 -0
  20. package/lib/esm/errors.js.map +1 -0
  21. package/lib/esm/index.js +28 -0
  22. package/lib/esm/index.js.map +1 -0
  23. package/lib/esm/native/icons.js +117 -0
  24. package/lib/esm/native/icons.js.map +1 -0
  25. package/lib/esm/native/loader.js +116 -0
  26. package/lib/esm/native/loader.js.map +1 -0
  27. package/lib/esm/native/types.js +8 -0
  28. package/lib/esm/native/types.js.map +1 -0
  29. package/lib/esm/notifications/NotificationCenter.js +322 -0
  30. package/lib/esm/notifications/NotificationCenter.js.map +1 -0
  31. package/lib/esm/tray/TrayIcon.js +362 -0
  32. package/lib/esm/tray/TrayIcon.js.map +1 -0
  33. package/lib/esm/tray/assets.js +26 -0
  34. package/lib/esm/tray/assets.js.map +1 -0
  35. package/lib/types/errors.d.cts +56 -0
  36. package/lib/types/errors.d.mts +56 -0
  37. package/lib/types/index.d.cts +27 -0
  38. package/lib/types/index.d.mts +27 -0
  39. package/lib/types/native/icons.d.cts +71 -0
  40. package/lib/types/native/icons.d.mts +71 -0
  41. package/lib/types/native/loader.d.cts +37 -0
  42. package/lib/types/native/loader.d.mts +37 -0
  43. package/lib/types/native/types.d.cts +104 -0
  44. package/lib/types/native/types.d.mts +104 -0
  45. package/lib/types/notifications/NotificationCenter.d.cts +163 -0
  46. package/lib/types/notifications/NotificationCenter.d.mts +163 -0
  47. package/lib/types/tray/TrayIcon.d.cts +174 -0
  48. package/lib/types/tray/TrayIcon.d.mts +174 -0
  49. package/lib/types/tray/assets.d.cts +25 -0
  50. package/lib/types/tray/assets.d.mts +25 -0
  51. package/native/tray-icon-node/Cargo.lock +1511 -0
  52. package/native/tray-icon-node/Cargo.toml +45 -0
  53. package/native/tray-icon-node/Cross.toml +10 -0
  54. package/native/tray-icon-node/LICENSE +21 -0
  55. package/native/tray-icon-node/UPSTREAM-README.md +281 -0
  56. package/native/tray-icon-node/UPSTREAM.md +213 -0
  57. package/native/tray-icon-node/build-manifest.json +16 -0
  58. package/native/tray-icon-node/build.rs +5 -0
  59. package/native/tray-icon-node/index.d.ts +368 -0
  60. package/native/tray-icon-node/index.js +609 -0
  61. package/native/tray-icon-node/package.json +55 -0
  62. package/native/tray-icon-node/rustfmt.toml +31 -0
  63. package/native/tray-icon-node/source-manifest.json +30 -0
  64. package/native/tray-icon-node/src/common.rs +101 -0
  65. package/native/tray-icon-node/src/icon.rs +255 -0
  66. package/native/tray-icon-node/src/lib.rs +449 -0
  67. package/native/tray-icon-node/src/menu.rs +849 -0
  68. package/native/tray-icon-node/src/tray.rs +251 -0
  69. package/native/tray-icon-node/tray-icon-node.linux-x64-gnu.node +0 -0
  70. package/package.json +131 -4
  71. package/scripts/for-os-build.mjs +60 -0
  72. package/scripts/for-os-init.mjs +327 -0
  73. package/scripts/for-os-install.mjs +47 -0
  74. package/scripts/for-os-integration.mjs +137 -0
  75. package/scripts/for-os-integrity.mjs +51 -0
  76. package/scripts/for-os-package.mjs +49 -0
  77. package/scripts/lib/native.mjs +591 -0
@@ -0,0 +1,591 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * Shared plumbing for the vendored `tray-icon-node` addon.
4
+ *
5
+ * Verifies `native/tray-icon-node` against `source-manifest.json`, builds the
6
+ * NAPI-RS addon with `cargo build --release --locked`, and materializes a
7
+ * verified copy at `node_modules/tray-icon-node`. Nothing downloads a binary
8
+ * and no shell string is constructed: every external command receives an
9
+ * argument vector.
10
+ * @module scripts/lib/native
11
+ */
12
+ import { createHash } from "node:crypto";
13
+ import {
14
+ copyFileSync,
15
+ existsSync,
16
+ mkdirSync,
17
+ readdirSync,
18
+ readFileSync,
19
+ rmSync,
20
+ writeFileSync,
21
+ } from "node:fs";
22
+ import { dirname, join, relative, resolve, sep } from "node:path";
23
+ import { fileURLToPath } from "node:url";
24
+ import { spawnSync } from "node:child_process";
25
+
26
+ const process = globalThis.process;
27
+
28
+ /** Absolute package root of `@decaf-ts/for-os`. */
29
+ export const PACKAGE_ROOT = resolve(dirname(fileURLToPath(import.meta.url)), "..", "..");
30
+
31
+ /** Vendored native source directory. */
32
+ export const NATIVE_DIR = join(PACKAGE_ROOT, "native", "tray-icon-node");
33
+
34
+ /** Checked-in manifest pinning the native source tree. */
35
+ export const SOURCE_MANIFEST = join(NATIVE_DIR, "source-manifest.json");
36
+
37
+ /** File name of the manifest written next to a locally built binary. */
38
+ export const BUILD_MANIFEST = "build-manifest.json";
39
+
40
+ /** Pinned package name of the vendored addon. */
41
+ export const NATIVE_PACKAGE = "tray-icon-node";
42
+
43
+ /** Pinned upstream version of the vendored addon. */
44
+ export const NATIVE_VERSION = "0.1.2";
45
+
46
+ const SKIP_DIRS = new Set(["target", "node_modules", ".git"]);
47
+ const SKIP_FILES = new Set([
48
+ BUILD_MANIFEST,
49
+ "source-manifest.json",
50
+ "source-manifest.json.tmp",
51
+ ]);
52
+ const BINARY_PATTERN = /^tray-icon-node\..+\.node$/;
53
+ export const TARGET_BINARIES = {
54
+ "x86_64-pc-windows-msvc": "tray-icon-node.win32-x64-msvc.node",
55
+ "i686-pc-windows-msvc": "tray-icon-node.win32-ia32-msvc.node",
56
+ "aarch64-apple-darwin": "tray-icon-node.darwin-arm64.node",
57
+ "x86_64-unknown-linux-gnu": "tray-icon-node.linux-x64-gnu.node",
58
+ "aarch64-unknown-linux-gnu": "tray-icon-node.linux-arm64-gnu.node",
59
+ };
60
+
61
+ /**
62
+ * Converts a platform path to the forward-slash manifest form.
63
+ * @param {string} value platform-specific path
64
+ * @returns {string} path using forward slashes
65
+ */
66
+ export function toPosix(value) {
67
+ return value.split(sep).join("/");
68
+ }
69
+
70
+ /**
71
+ * SHA-512 hex digest of arbitrary bytes.
72
+ * @param {string|Buffer|Uint8Array} data bytes to hash
73
+ * @returns {string} lowercase hex digest
74
+ */
75
+ export function sha512(data) {
76
+ return createHash("sha512").update(data).digest("hex");
77
+ }
78
+
79
+ /**
80
+ * SHA-512 hex digest of one file.
81
+ * @param {string} file file path
82
+ * @returns {string} lowercase hex digest of the file contents
83
+ */
84
+ export function sha512File(file) {
85
+ return sha512(readFileSync(file));
86
+ }
87
+
88
+ /**
89
+ * Canonical digest over the sorted `path\0digest` lines.
90
+ * @param {Object<string, string>} files map of manifest path to file digest
91
+ * @returns {string} SHA-512 digest of the canonical listing
92
+ */
93
+ export function sourceDigest(files) {
94
+ const canonical = Object.keys(files)
95
+ .sort()
96
+ .map((path) => `${path}\u0000${files[path]}`)
97
+ .join("\n");
98
+ return sha512(canonical);
99
+ }
100
+
101
+ /**
102
+ * Lists every file that belongs to the native source pin.
103
+ * @param {string} [directory] native source directory; defaults to {@link NATIVE_DIR}
104
+ * @returns {string[]} sorted absolute file paths, excluding build outputs and manifests
105
+ */
106
+ export function listSourceFiles(directory = NATIVE_DIR) {
107
+ const files = [];
108
+ const walk = (dir) => {
109
+ for (const entry of readdirSync(dir, { withFileTypes: true })) {
110
+ const full = join(dir, entry.name);
111
+ if (entry.isSymbolicLink()) {
112
+ throw new Error(`Unexpected symlink in native source: ${full}`);
113
+ }
114
+ if (entry.isDirectory()) {
115
+ if (!SKIP_DIRS.has(entry.name)) walk(full);
116
+ continue;
117
+ }
118
+ if (!entry.isFile()) {
119
+ throw new Error(`Unexpected non-file entry in native source: ${full}`);
120
+ }
121
+ if (SKIP_FILES.has(entry.name) || BINARY_PATTERN.test(entry.name)) continue;
122
+ files.push(full);
123
+ }
124
+ };
125
+ walk(directory);
126
+ return files.sort();
127
+ }
128
+
129
+ /**
130
+ * Hashes the current native source tree.
131
+ * @param {string} [directory] native source directory; defaults to {@link NATIVE_DIR}
132
+ * @returns {Object} `{ files, sourceDigest }` with per-file digests and the canonical digest
133
+ */
134
+ export function recordSourceTree(directory = NATIVE_DIR) {
135
+ const files = {};
136
+ for (const file of listSourceFiles(directory)) {
137
+ files[toPosix(relative(directory, file))] = sha512File(file);
138
+ }
139
+ return { files, sourceDigest: sourceDigest(files) };
140
+ }
141
+
142
+ /**
143
+ * Reads the checked-in source manifest.
144
+ * @param {string} [directory] native source directory; defaults to {@link NATIVE_DIR}
145
+ * @returns {Object} parsed `source-manifest.json`
146
+ */
147
+ export function readSourceManifest(directory = NATIVE_DIR) {
148
+ return JSON.parse(readFileSync(join(directory, "source-manifest.json"), "utf8"));
149
+ }
150
+
151
+ /**
152
+ * Writes `source-manifest.json` for the current native source tree.
153
+ * @param {{upstream?: Record<string, string>}} [options] upstream provenance to keep
154
+ * @return {Record<string, unknown>} the written manifest
155
+ */
156
+ export function writeSourceManifest({ upstream } = {}) {
157
+ const observed = recordSourceTree();
158
+ const existing = existsSync(SOURCE_MANIFEST)
159
+ ? JSON.parse(readFileSync(SOURCE_MANIFEST, "utf8"))
160
+ : {};
161
+ const manifest = {
162
+ package: NATIVE_PACKAGE,
163
+ version: NATIVE_VERSION,
164
+ upstream:
165
+ upstream ??
166
+ existing.upstream ?? {
167
+ repository: "https://github.com/nglmercer/tray-icon-node",
168
+ commit: "cb91e86184ed8612bcdee904277b4d5e78d966c3",
169
+ },
170
+ sourceDigest: observed.sourceDigest,
171
+ files: observed.files,
172
+ };
173
+ writeFileSync(SOURCE_MANIFEST, `${JSON.stringify(manifest, null, 2)}\n`);
174
+ return manifest;
175
+ }
176
+
177
+ /**
178
+ * Verifies the native source tree against `source-manifest.json`.
179
+ * @param {string} [directory] native source directory; defaults to {@link NATIVE_DIR}
180
+ * @returns {Object} `{ manifest, observed }` with the pinned and observed state
181
+ * @throws {Error} when the file set or digest diverges from the manifest
182
+ */
183
+ export function verifySourceTree(directory = NATIVE_DIR) {
184
+ const manifest = readSourceManifest(directory);
185
+ const observed = recordSourceTree(directory);
186
+ if (manifest.sourceDigest !== observed.sourceDigest) {
187
+ const expected = new Set(Object.keys(manifest.files));
188
+ const actual = new Set(Object.keys(observed.files));
189
+ const changed = Object.keys(observed.files).filter(
190
+ (path) => manifest.files[path] !== observed.files[path]
191
+ );
192
+ const missing = [...expected].filter((path) => !actual.has(path));
193
+ const extra = [...actual].filter((path) => !expected.has(path));
194
+ throw new Error(
195
+ `Native source does not match source-manifest.json (changed: [${changed.join(", ")}], missing: [${missing.join(", ")}], extra: [${extra.join(", ")}]). ` +
196
+ "Review the change, then run `npm run for-os:integrity:record`."
197
+ );
198
+ }
199
+ return { manifest, observed };
200
+ }
201
+
202
+ /**
203
+ * Runs a command without a shell and returns a non-throwing result.
204
+ * @param {string} command executable name or path
205
+ * @param {string[]} args argument vector passed verbatim
206
+ * @param {Object} [options] spawn options; `capture: true` pipes stdio instead of inheriting it
207
+ * @returns {Object} `{ ok, status, stdout, stderr }`; `error` is set when the process could not start
208
+ */
209
+ export function run(command, args, options = {}) {
210
+ const result = spawnSync(command, args, {
211
+ encoding: "utf8",
212
+ stdio: options.capture ? "pipe" : "inherit",
213
+ ...options,
214
+ });
215
+ if (result.error && result.status === null) {
216
+ return {
217
+ ok: false,
218
+ status: null,
219
+ error: result.error,
220
+ stdout: result.stdout ?? "",
221
+ stderr: result.stderr ?? "",
222
+ };
223
+ }
224
+ return {
225
+ ok: result.status === 0,
226
+ status: result.status,
227
+ stdout: result.stdout ?? "",
228
+ stderr: result.stderr ?? "",
229
+ };
230
+ }
231
+
232
+ /**
233
+ * Returns the first line of a tool's version output, or undefined.
234
+ * @param {string} command executable name or path
235
+ * @param {string[]} [args] version arguments; defaults to `["--version"]`
236
+ * @returns {string|undefined} first output line, or `undefined` when the command fails
237
+ */
238
+ export function commandVersion(command, args = ["--version"]) {
239
+ const result = run(command, args, { capture: true });
240
+ return result.ok ? (result.stdout || result.stderr).trim().split("\n")[0] : undefined;
241
+ }
242
+
243
+ /**
244
+ * Cargo executable, honoring `$CARGO`.
245
+ * @returns {string} cargo executable name or path
246
+ */
247
+ export function cargoPath() {
248
+ return process.env.CARGO || "cargo";
249
+ }
250
+
251
+ /**
252
+ * Rustc executable, honoring `$RUSTC`.
253
+ * @returns {string} rustc executable name or path
254
+ */
255
+ export function rustcPath() {
256
+ return process.env.RUSTC || "rustc";
257
+ }
258
+
259
+ /**
260
+ * Reads the Rust host target triple from `rustc -vV`.
261
+ * @returns {string} host target triple
262
+ * @throws {Error} when `rustc -vV` fails or reports no host triple
263
+ */
264
+ export function hostTriple() {
265
+ const result = run(rustcPath(), ["-vV"], { capture: true });
266
+ if (!result.ok) {
267
+ throw new Error(
268
+ `Cannot run \`${rustcPath()} -vV\`. Install a Rust stable toolchain (rustup) to build the native addon.`
269
+ );
270
+ }
271
+ const host = result.stdout.match(/^host:\s*(\S+)$/m);
272
+ if (!host) throw new Error("Could not determine the Rust host triple from `rustc -vV`.");
273
+ return host[1];
274
+ }
275
+
276
+ /**
277
+ * Detects a musl Linux host.
278
+ * @param {string} [platform] platform to inspect; defaults to `process.platform`
279
+ * @returns {boolean} `true` when the runtime links against musl libc
280
+ */
281
+ export function isMusl(platform = process.platform) {
282
+ if (platform !== "linux") return false;
283
+ try {
284
+ if (readFileSync("/usr/bin/ldd", "utf8").includes("musl")) return true;
285
+ } catch {
286
+ // fall through to the runtime report
287
+ }
288
+ try {
289
+ const report = process.report?.getReport?.();
290
+ if (report?.header?.glibcVersionRuntime) return false;
291
+ if (
292
+ Array.isArray(report?.sharedObjects) &&
293
+ report.sharedObjects.some((file) => file.includes("libc.musl-") || file.includes("ld-musl-"))
294
+ ) {
295
+ return true;
296
+ }
297
+ } catch {
298
+ // unknown libc: assume glibc like the upstream NAPI loader
299
+ }
300
+ return false;
301
+ }
302
+
303
+ /**
304
+ * NAPI-RS binary file name for a platform/architecture pair.
305
+ * @param {string} [platform] target platform; defaults to `process.platform`
306
+ * @param {string} [arch] target architecture; defaults to `process.arch`
307
+ * @returns {string} NAPI-RS binary file name
308
+ * @throws {Error} for unsupported platforms or architectures
309
+ */
310
+ export function napiBinaryName(platform = process.platform, arch = process.arch) {
311
+ if (platform === "darwin") {
312
+ if (arch === "x64" || arch === "arm64") return `tray-icon-node.darwin-${arch}.node`;
313
+ throw new Error(`Unsupported macOS architecture for the native addon: ${arch}`);
314
+ }
315
+ if (platform === "win32") {
316
+ if (arch === "x64" || arch === "ia32") {
317
+ return `tray-icon-node.win32-${arch}-msvc.node`;
318
+ }
319
+ throw new Error(`Unsupported Windows architecture for the native addon: ${arch}`);
320
+ }
321
+ if (platform === "linux") {
322
+ const suffix = isMusl(platform) ? "musl" : "gnu";
323
+ if (suffix === "gnu" && (arch === "x64" || arch === "arm64")) {
324
+ return `tray-icon-node.linux-${arch}-gnu.node`;
325
+ }
326
+ throw new Error(`Unsupported Linux architecture for the native addon: ${arch}`);
327
+ }
328
+ throw new Error(`The native addon is built for linux, darwin, and win32 only (got ${platform}).`);
329
+ }
330
+
331
+ /**
332
+ * Cargo release artifact file name.
333
+ * @param {string} [platform] target platform; defaults to `process.platform`
334
+ * @returns {string} shared-library file name emitted by cargo
335
+ */
336
+ export function platformArtifactName(platform = process.platform) {
337
+ if (platform === "win32") return "tray_icon_node.dll";
338
+ if (platform === "darwin") return "libtray_icon_node.dylib";
339
+ return "libtray_icon_node.so";
340
+ }
341
+
342
+ /**
343
+ * GTK/AppIndicator pkg-config modules missing on Linux.
344
+ * @returns {string[]} missing pkg-config module names; empty off Linux
345
+ */
346
+ export function missingLinuxNativeModules() {
347
+ if (process.platform !== "linux") return [];
348
+ const modules = ["gtk+-3.0", "ayatana-appindicator3-0.1", "glib-2.0", "x11"];
349
+ return modules.filter(
350
+ (module) => !run("pkg-config", ["--exists", module], { capture: true }).ok
351
+ );
352
+ }
353
+
354
+ /**
355
+ * Reads `build-manifest.json` when present and valid.
356
+ * @param {string} [directory] native source directory; defaults to {@link NATIVE_DIR}
357
+ * @returns {Object|undefined} parsed build manifest, or `undefined` when absent or malformed
358
+ */
359
+ export function readBuildManifest(directory = NATIVE_DIR) {
360
+ const target = join(directory, BUILD_MANIFEST);
361
+ if (!existsSync(target)) return undefined;
362
+ try {
363
+ return JSON.parse(readFileSync(target, "utf8"));
364
+ } catch {
365
+ return undefined;
366
+ }
367
+ }
368
+
369
+ /**
370
+ * Resolves the built binary named by the manifest.
371
+ * @param {string} [directory] native source directory; defaults to {@link NATIVE_DIR}
372
+ * @returns {string|undefined} absolute binary path when the manifest names an existing file
373
+ */
374
+ export function binaryPath(directory = NATIVE_DIR) {
375
+ const manifest = readBuildManifest(directory);
376
+ if (!manifest) return undefined;
377
+ const candidates = manifest.binary ? [manifest.binary] : Object.keys(manifest.binaries ?? {});
378
+ const binary = candidates.find((filename) => existsSync(join(directory, filename)));
379
+ return binary ? join(directory, binary) : undefined;
380
+ }
381
+
382
+ /**
383
+ * Builds the native addon from the verified source.
384
+ * @param {Object} [options] native directory and logger
385
+ * @param {string} [options.directory] native source directory; defaults to {@link NATIVE_DIR}
386
+ * @param {function(string): void} [options.log] log sink; defaults to `console.log`
387
+ * @returns {Object} the written build manifest
388
+ * @throws {Error} when verification, cargo, or the platform toolchain is unavailable
389
+ */
390
+ export function buildNative({ directory = NATIVE_DIR, log = console.log, target } = {}) {
391
+ const { observed } = verifySourceTree(directory);
392
+ const cargo = cargoPath();
393
+ const version = commandVersion(cargo);
394
+ if (!version) {
395
+ throw new Error(
396
+ "Cannot find `cargo`. Run `npm run for-os:init` or install Rust stable from https://rustup.rs."
397
+ );
398
+ }
399
+ const rustcVersion = commandVersion(rustcPath(), ["--version"]);
400
+ const triple = target || hostTriple();
401
+ const architecture = TARGET_BINARIES[triple];
402
+ if (!architecture) throw new Error(`Unsupported native build target: ${triple}`);
403
+ const missingModules = missingLinuxNativeModules();
404
+ if (missingModules.length) {
405
+ throw new Error(
406
+ "Missing Linux native development libraries (" +
407
+ missingModules.join(", ") +
408
+ "). On Ubuntu/Debian install: libgtk-3-dev libayatana-appindicator3-dev " +
409
+ "libglib2.0-dev libxdo-dev libx11-dev libnotify-bin. Run `npm run for-os:init`."
410
+ );
411
+ }
412
+ log(`for-os: building ${NATIVE_PACKAGE}@${NATIVE_VERSION} from native source (${triple})`);
413
+ const args = ["build", "--release", "--locked", "--manifest-path", join(directory, "Cargo.toml")];
414
+ if (target) args.push("--target", target);
415
+ const result = run(cargo, args);
416
+ if (!result.ok) {
417
+ throw new Error(
418
+ `cargo build failed for the native addon (status ${result.status}). ` +
419
+ "Install the platform GUI development libraries listed in native/tray-icon-node/UPSTREAM.md and retry."
420
+ );
421
+ }
422
+ const artifactDirectory = target ? join(directory, "target", target, "release") : join(directory, "target", "release");
423
+ const artifact = join(artifactDirectory, platformArtifactNameForTarget(triple));
424
+ if (!existsSync(artifact)) {
425
+ throw new Error(`cargo build succeeded but ${artifact} does not exist.`);
426
+ }
427
+ const destination = join(directory, architecture);
428
+ copyFileSync(artifact, destination);
429
+ const manifest = {
430
+ version: 1,
431
+ package: NATIVE_PACKAGE,
432
+ packageVersion: NATIVE_VERSION,
433
+ sourceDigest: observed.sourceDigest,
434
+ target: triple,
435
+ platform: triple.includes("windows") ? "win32" : triple.includes("apple") ? "darwin" : "linux",
436
+ arch: triple.startsWith("i686") ? "ia32" : triple.startsWith("x86_64") ? "x64" : "arm64",
437
+ binary: architecture,
438
+ sha512: sha512File(destination),
439
+ builtAt: new Date().toISOString(),
440
+ toolchain: { cargo: version, rustc: rustcVersion },
441
+ };
442
+ writeFileSync(join(directory, BUILD_MANIFEST), `${JSON.stringify(manifest, null, 2)}\n`);
443
+ log(`for-os: built ${architecture} (sha512 ${manifest.sha512})`);
444
+ return manifest;
445
+ }
446
+
447
+ /** Returns the Rust shared-library filename for a target triple. */
448
+ export function platformArtifactNameForTarget(target) {
449
+ if (target.includes("windows")) return "tray_icon_node.dll";
450
+ if (target.includes("apple")) return "libtray_icon_node.dylib";
451
+ if (target.includes("linux")) return "libtray_icon_node.so";
452
+ throw new Error(`Unsupported native build target: ${target}`);
453
+ }
454
+
455
+ /**
456
+ * Reuses a verified build, otherwise rebuilds (or degrades when not required).
457
+ * @param {Object} [options] native directory, logger, and required-build flag
458
+ * @param {string} [options.directory] native source directory; defaults to {@link NATIVE_DIR}
459
+ * @param {function(string): void} [options.log] log sink; defaults to `console.log`
460
+ * @param {boolean} [options.required] when `true`, rethrow build failures instead of degrading
461
+ * @returns {Object|undefined} build manifest, or `undefined` when the build degraded
462
+ */
463
+ export function ensureBuilt({ directory = NATIVE_DIR, log = console.log, required = false } = {}) {
464
+ const { observed } = verifySourceTree(directory);
465
+ const existing = readBuildManifest(directory);
466
+ const existingBinary = binaryPath(directory);
467
+ const architecture = napiBinaryName(process.platform, process.arch);
468
+ if (
469
+ existing &&
470
+ existingBinary &&
471
+ existing.sourceDigest === observed.sourceDigest &&
472
+ existing.sha512 === sha512File(existingBinary) &&
473
+ existing.binary === architecture
474
+ ) {
475
+ log(`for-os: reusing verified build ${existing.binary}`);
476
+ return existing;
477
+ }
478
+ try {
479
+ return buildNative({ directory, log });
480
+ } catch (error) {
481
+ if (required) throw error;
482
+ log(
483
+ `for-os: native build unavailable (${error instanceof Error ? error.message : String(error)}). ` +
484
+ "The tray and notification bridges will report unavailable at runtime. " +
485
+ "Run `npm run for-os:build` after installing the toolchain."
486
+ );
487
+ return undefined;
488
+ }
489
+ }
490
+
491
+ /**
492
+ * Materializes a verified package copy under `node_modules/tray-icon-node`.
493
+ * @param {Object} [options] source directory, destination, logger, and required-build flag
494
+ * @param {string} [options.directory] native source directory; defaults to {@link NATIVE_DIR}
495
+ * @param {string} [options.destination] target package directory; defaults to the package `node_modules`
496
+ * @param {function(string): void} [options.log] log sink; defaults to `console.log`
497
+ * @param {boolean} [options.required] when `true`, fail instead of materializing without a binary
498
+ * @returns {Object} `{ manifest, build, destination }` describing the materialized copy
499
+ */
500
+ export function installNative({
501
+ directory = NATIVE_DIR,
502
+ destination = join(PACKAGE_ROOT, "node_modules", NATIVE_PACKAGE),
503
+ log = console.log,
504
+ required = false,
505
+ } = {}) {
506
+ const { manifest } = verifySourceTree(directory);
507
+ const currentBinaryName = napiBinaryName();
508
+ const currentBinary = join(directory, currentBinaryName);
509
+ const bundledManifest = readBuildManifest(directory);
510
+ const expectedDigest = bundledManifest?.binaries?.[currentBinaryName];
511
+ if (existsSync(currentBinary) && expectedDigest && sha512File(currentBinary) !== expectedDigest) {
512
+ throw new Error(`Bundled native binary integrity check failed for ${currentBinaryName}.`);
513
+ }
514
+ const build = existsSync(currentBinary)
515
+ ? { binary: currentBinaryName, prebuilt: true }
516
+ : ensureBuilt({ directory, log, required });
517
+
518
+ const materialize = (targetDirectory) => {
519
+ rmSync(targetDirectory, { recursive: true, force: true });
520
+ mkdirSync(targetDirectory, { recursive: true });
521
+ for (const relativePath of Object.keys(manifest.files)) {
522
+ const source = join(directory, relativePath);
523
+ const target = join(targetDirectory, relativePath);
524
+ mkdirSync(dirname(target), { recursive: true });
525
+ copyFileSync(source, target);
526
+ }
527
+ for (const filename of readdirSync(directory).filter((name) => BINARY_PATTERN.test(name))) {
528
+ copyFileSync(join(directory, filename), join(targetDirectory, filename));
529
+ }
530
+ if (build) {
531
+ const buildManifest = join(directory, BUILD_MANIFEST);
532
+ if (existsSync(buildManifest)) {
533
+ copyFileSync(buildManifest, join(targetDirectory, BUILD_MANIFEST));
534
+ }
535
+ if (build.binary && existsSync(join(directory, build.binary))) {
536
+ copyFileSync(join(directory, build.binary), join(targetDirectory, build.binary));
537
+ }
538
+ }
539
+ };
540
+
541
+ materialize(destination);
542
+ log(
543
+ build
544
+ ? `for-os: materialized verified ${NATIVE_PACKAGE}@${NATIVE_VERSION} at ${destination}`
545
+ : `for-os: materialized ${NATIVE_PACKAGE}@${NATIVE_VERSION} without a native binary at ${destination}`
546
+ );
547
+
548
+ const initCwd = process.env.INIT_CWD;
549
+ if (initCwd) {
550
+ const projectDestination = join(resolve(initCwd), "node_modules", NATIVE_PACKAGE);
551
+ if (resolve(projectDestination) !== resolve(destination)) {
552
+ try {
553
+ materialize(projectDestination);
554
+ log(`for-os: also materialized the addon at ${projectDestination}`);
555
+ } catch (error) {
556
+ log(
557
+ `for-os: could not materialize the addon at ${projectDestination} (${error instanceof Error ? error.message : String(error)}); ` +
558
+ "set FOR_OS_NATIVE_MODULE to an explicit module path if runtime resolution fails."
559
+ );
560
+ }
561
+ }
562
+ }
563
+
564
+ return { manifest, build, destination };
565
+ }
566
+
567
+ /**
568
+ * Reports source/build state without building (used by `--check`).
569
+ * @param {Object} [options] native directory and logger
570
+ * @param {string} [options.directory] native source directory; defaults to {@link NATIVE_DIR}
571
+ * @param {function(string): void} [options.log] log sink; defaults to `console.log`
572
+ * @returns {Object} `{ manifest, observed, build }` without mutating the source tree
573
+ */
574
+ export function inspectNative({ directory = NATIVE_DIR, log = console.log } = {}) {
575
+ const { manifest, observed } = verifySourceTree(directory);
576
+ const build = readBuildManifest(directory);
577
+ const binary = binaryPath(directory);
578
+ log(
579
+ `for-os: native source verified (${Object.keys(observed.files).length} files, source digest ${observed.sourceDigest}).`
580
+ );
581
+ if (build && binary) {
582
+ if (build.binaries) {
583
+ log(`for-os: package manifest present for ${Object.keys(build.binaries).length} native binaries.`);
584
+ } else {
585
+ log(`for-os: build manifest present for ${build.binary} (${build.target}, sha512 ${build.sha512}).`);
586
+ }
587
+ } else {
588
+ log("for-os: no native binary in the source tree (run `npm run for-os:build`).");
589
+ }
590
+ return { manifest, observed, build };
591
+ }