Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

build-desktop-artifact.test.ts

1,455 lines53.2 KB

1import * as NodeServices from "@effect/platform-node/NodeServices";
2import { assert, it } from "@effect/vitest";
3import * as ConfigProvider from "effect/ConfigProvider";
4import * as FileSystem from "effect/FileSystem";
5import * as Effect from "effect/Effect";
6import * as Layer from "effect/Layer";
7import * as Option from "effect/Option";
8import * as Path from "effect/Path";
9import * as Sink from "effect/Sink";
10import * as Stream from "effect/Stream";
11import { ChildProcessSpawner } from "effect/unstable/process";
12​
13import {
14 BundleNotSelfContainedError,
15 BuildCommandFailedError,
16 DesktopDmgBackgroundSourceMissingError,
17 createStageWorkspaceConfig,
18 createStagePatchedDependencies,
19 createBuildConfig,
20 DESKTOP_ELECTRON_LANGUAGES,
21 DESKTOP_FILE_EXCLUSIONS,
22 DESKTOP_EXTRA_RESOURCES,
23 InvalidMacPasskeyRpDomainError,
24 InvalidMacPasskeyPublishableKeyError,
25 InvalidMockUpdateServerPortError,
26 UnsupportedDesktopBuildArchitectureError,
27 isMacPasskeySigningConfigurationError,
28 LinuxIconResizeError,
29 MacPasskeySigningConfigurationResolutionError,
30 MissingMacPasskeyProvisioningProfileError,
31 packWindowsServerAsar,
32 renderMacPasskeyEntitlements,
33 resolveClerkPasskeyNativeArtifacts,
34 resolveMacPasskeySigningConfiguration,
35 resolveDesktopRuntimeDependencies,
36 resolveFffNativeDependencies,
37 resolveBuildOptions,
38 resolveDesktopBuildIconAssets,
39 resolveDesktopProductName,
40 resolveDesktopUpdateChannel,
41 resolveDesktopWebAssetBrand,
42 resolveResourceMonitorRustTargets,
43 resolveWindowsServerAsarIgnoreGlobs,
44 resourceMonitorExecutableName,
45 resolveGitHubPublishConfig,
46 resolveMockUpdateServerPort,
47 resolveMockUpdateServerUrl,
48 resolvePackageManagerUserAgent,
49 stageLinuxIconSize,
50 stageDesktopDmgBackground,
51 stageResourceMonitor,
52 STAGE_INSTALL_ARGS,
53 ancestorNodeModulesPaths,
54 copyDirectoryPreservingSymlinks,
55 validateWindowsPackagedPayload,
56 WindowsPrimaryNativeProbeError,
57 WindowsPackagedPayloadValidationError,
58 WINDOWS_PACKAGED_PAYLOAD_FILE_LIMIT,
59 WINDOWS_SERVER_ASAR_IGNORE_GLOBS,
60 WINDOWS_SERVER_EXTRA_RESOURCES,
61 WINDOWS_SERVER_ASAR_RESOURCE,
62 WINDOWS_SERVER_ASAR_UNPACK_GLOB,
63 WINDOWS_SERVER_RESOURCE_SOURCE_DIR,
64} from "./build-desktop-artifact.ts";
65import { BRAND_ASSET_PATHS } from "./lib/brand-assets.ts";
66import { HostProcessArchitecture, HostProcessPlatform } from "@t3tools/shared/hostProcess";
67​
68function mockProcess(exitCode: number) {
69 return ChildProcessSpawner.makeHandle({
70 pid: ChildProcessSpawner.ProcessId(1),
71 exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(exitCode)),
72 isRunning: Effect.succeed(false),
73 kill: () => Effect.void,
74 unref: Effect.succeed(Effect.void),
75 stdin: Sink.drain,
76 stdout: Stream.empty,
77 stderr: Stream.empty,
78 all: Stream.empty,
79 getInputFd: () => Sink.drain,
80 getOutputFd: () => Stream.empty,
81 });
83​
84function iconResizeSpawnerLayer(
85 commands: Array<{ readonly command: string; readonly args: ReadonlyArray<string> }>,
86 exitCodes: ReadonlyArray<number>,
87) {
88 let commandIndex = 0;
89 return Layer.succeed(
90 ChildProcessSpawner.ChildProcessSpawner,
91 ChildProcessSpawner.make((command) => {
92 const childProcess = command as unknown as {
93 readonly command: string;
94 readonly args: ReadonlyArray<string>;
95 };
96 commands.push({
97 command: childProcess.command,
98 args: childProcess.args,
99 });
100 return Effect.succeed(mockProcess(exitCodes[commandIndex++] ?? 0));
101 }),
102 );
104​
105const makeWindowsPayloadFixture = Effect.fn("test.makeWindowsPayloadFixture")(function* (input: {
106 readonly copyUnpackedNatives: boolean;
107 readonly serverEntrySource?: string;
108}) {
109 const fs = yield* FileSystem.FileSystem;
110 const path = yield* Path.Path;
111 const tempDir = yield* fs.makeTempDirectoryScoped({
112 prefix: "t3-windows-payload-test-",
113 });
114 const sourceDir = path.join(tempDir, "server-source");
115 const serverEntryPath = path.join(sourceDir, "apps/server/dist/bin.mjs");
116 const nativePath = path.join(sourceDir, "node_modules/native/addon.node");
117 yield* fs.makeDirectory(path.dirname(serverEntryPath), { recursive: true });
118 yield* fs.makeDirectory(path.dirname(nativePath), { recursive: true });
119 yield* fs.writeFileString(serverEntryPath, input.serverEntrySource ?? "console.log('server');\n");
120 yield* fs.writeFileString(nativePath, "native-binary");
121​
122 const generatedAsarPath = path.join(tempDir, WINDOWS_SERVER_ASAR_RESOURCE);
123 yield* packWindowsServerAsar({ sourceDir, asarPath: generatedAsarPath, arch: "x64" });
124​
125 const stageDistDir = path.join(tempDir, "dist");
126 const packagedAppDir = path.join(stageDistDir, "win-unpacked");
127 const resourcesDir = path.join(packagedAppDir, "resources");
128 yield* fs.makeDirectory(path.join(resourcesDir, "resource-monitor"), { recursive: true });
129 yield* fs.copyFile(generatedAsarPath, path.join(resourcesDir, WINDOWS_SERVER_ASAR_RESOURCE));
130 if (input.copyUnpackedNatives) {
131 yield* fs.copy(
132 `${generatedAsarPath}.unpacked`,
133 path.join(resourcesDir, `${WINDOWS_SERVER_ASAR_RESOURCE}.unpacked`),
134 );
135 }
136 yield* fs.writeFileString(
137 path.join(resourcesDir, "resource-monitor/t3-resource-monitor.exe"),
138 "monitor",
139 );
140 const appExecutableName = "t3code.exe";
141 yield* fs.writeFileString(path.join(packagedAppDir, appExecutableName), "electron");
142 yield* fs.writeFileString(path.join(packagedAppDir, "chrome_crashpad_handler.exe"), "crashpad");
143​
144 return {
145 stageDistDir,
146 packagedAppDir,
147 sourceDir,
148 generatedAsarPath,
149 appExecutableName,
150 } as const;
151});
152​
153it.layer(NodeServices.layer)("build-desktop-artifact", (it) => {
154 it("resolves the dedicated nightly updater channel from nightly versions", () => {
155 assert.equal(resolveDesktopUpdateChannel("0.0.17-nightly.20260413.42"), "nightly");
156 assert.equal(resolveDesktopUpdateChannel("0.0.17"), "latest");
157 });
158​
159 it("switches desktop packaging product names to nightly for nightly builds", () => {
160 assert.equal(resolveDesktopProductName("0.0.17"), "T3 Code (Alpha)");
161 assert.equal(resolveDesktopProductName("0.0.17-nightly.20260413.42"), "T3 Code (Nightly)");
162 });
163​
164 it("switches desktop packaging icons to the nightly artwork for nightly versions", () => {
165 assert.deepStrictEqual(resolveDesktopBuildIconAssets("0.0.17"), {
166 macIconPng: BRAND_ASSET_PATHS.productionMacIconPng,
167 linuxIconPng: BRAND_ASSET_PATHS.productionLinuxIconPng,
168 windowsIconIco: BRAND_ASSET_PATHS.productionWindowsIconIco,
169 });
170​
171 assert.deepStrictEqual(resolveDesktopBuildIconAssets("0.0.17-nightly.20260413.42"), {
172 macIconPng: BRAND_ASSET_PATHS.nightlyMacIconPng,
173 linuxIconPng: BRAND_ASSET_PATHS.nightlyLinuxIconPng,
174 windowsIconIco: BRAND_ASSET_PATHS.nightlyWindowsIconIco,
175 });
176 });
177​
178 it("switches the bundled splash and favicon branding for nightly versions", () => {
179 assert.equal(resolveDesktopWebAssetBrand("0.0.17"), "production");
180 assert.equal(resolveDesktopWebAssetBrand("0.0.17-nightly.20260413.42"), "nightly");
181 });
182​
183 it.effect("resolves GitHub desktop publish config from Effect config", () =>
184 Effect.gen(function* () {
185 const latestConfig = yield* resolveGitHubPublishConfig("latest").pipe(
186 Effect.provide(
187 ConfigProvider.layer(
188 ConfigProvider.fromEnv({
189 env: {
190 T3CODE_DESKTOP_UPDATE_REPOSITORY: "pingdotgg/t3code",
191 },
192 }),
193 ),
194 ),
195 );
196 const nightlyConfig = yield* resolveGitHubPublishConfig("nightly").pipe(
197 Effect.provide(
198 ConfigProvider.layer(
199 ConfigProvider.fromEnv({
200 env: {
201 GITHUB_REPOSITORY: "pingdotgg/t3code",
202 },
203 }),
204 ),
205 ),
206 );
207​
208 assert.deepStrictEqual(latestConfig, {
209 provider: "github",
210 owner: "pingdotgg",
211 repo: "t3code",
212 releaseType: "release",
213 });
214 assert.deepStrictEqual(nightlyConfig, {
215 provider: "github",
216 owner: "pingdotgg",
217 repo: "t3code",
218 releaseType: "prerelease",
219 channel: "nightly",
220 });
221 }),
222 );
223​
224 it("omits bundled workspace packages from staged desktop dependencies", () => {
225 assert.deepStrictEqual(
226 resolveDesktopRuntimeDependencies(
227 {
228 "@effect/platform-node": "catalog:",
229 "@t3tools/contracts": "workspace:*",
230 "@t3tools/shared": "workspace:*",
231 "@t3tools/ssh": "workspace:*",
232 "@t3tools/tailscale": "workspace:*",
233 effect: "catalog:",
234 electron: "41.5.0",
235 },
236 {
237 "@effect/platform-node": "4.0.0-beta.59",
238 effect: "4.0.0-beta.59",
239 },
240 ),
241 {
242 "@effect/platform-node": "4.0.0-beta.59",
243 effect: "4.0.0-beta.59",
244 },
245 );
246 });
247​
248 it("carries only staged dependency patch metadata into staged desktop installs", () => {
249 assert.deepStrictEqual(
250 createStagePatchedDependencies(
251 {
252 "@expo/metro-config@56.0.13": "patches/@expo%2Fmetro-config@56.0.13.patch",
253 "@ff-labs/fff-node@0.9.4": "patches/@ff-labs__fff-node@0.9.4.patch",
254 "@pierre/diffs@1.1.20": "patches/@pierre%2Fdiffs@1.1.20.patch",
255 "alchemy@2.0.0-beta.49": "patches/alchemy@2.0.0-beta.49.patch",
256 "effect@4.0.0-beta.73": "patches/effect@4.0.0-beta.73.patch",
257 },
258 {
259 "@ff-labs/fff-node": "0.9.4",
260 "@pierre/diffs": "1.1.20",
261 effect: "4.0.0-beta.73",
262 },
263 ),
264 {
265 "@ff-labs/fff-node@0.9.4": "patches/@ff-labs__fff-node@0.9.4.patch",
266 "@pierre/diffs@1.1.20": "patches/@pierre%2Fdiffs@1.1.20.patch",
267 "effect@4.0.0-beta.73": "patches/effect@4.0.0-beta.73.patch",
268 },
269 );
270​
271 assert.deepStrictEqual(
272 createStagePatchedDependencies(
273 {
274 "@expo/metro-config@56.0.13": "patches/@expo%2Fmetro-config@56.0.13.patch",
275 },
276 { effect: "4.0.0-beta.73" },
277 ),
278 {},
279 );
280 });
281​
282 it("installs optional native dependencies for the target desktop architecture", () => {
283 assert.deepStrictEqual(STAGE_INSTALL_ARGS, ["install", "--prod"]);
284 assert.deepStrictEqual(createStageWorkspaceConfig({ platform: "mac", arch: "x64" }), {
285 supportedArchitectures: {
286 os: ["darwin"],
287 cpu: ["x64"],
288 },
289 });
290 assert.deepStrictEqual(createStageWorkspaceConfig({ platform: "linux", arch: "x64" }), {
291 supportedArchitectures: {
292 os: ["linux"],
293 cpu: ["x64"],
294 libc: ["glibc"],
295 },
296 });
297 // The Windows app stage only serves the desktop main process; the server
298 // sidecar stage is the one that needs Linux natives (below).
299 assert.deepStrictEqual(createStageWorkspaceConfig({ platform: "win", arch: "x64" }), {
300 supportedArchitectures: {
301 os: ["win32"],
302 cpu: ["x64"],
303 },
304 });
305 // The server sidecar stage bundles the same-architecture WSL (Linux,
306 // glibc) backend, so its install must fetch Linux native optional deps
307 // (e.g. ffi-rs) too — and must be hoisted so the tree survives asar
308 // packing and runtime extraction without symlinks.
309 assert.deepStrictEqual(
310 createStageWorkspaceConfig({ platform: "win", arch: "x64", linuxServerBackend: true }),
311 {
312 supportedArchitectures: {
313 os: ["win32", "linux"],
314 cpu: ["x64"],
315 libc: ["glibc"],
316 },
317 nodeLinker: "hoisted",
318 },
319 );
320 assert.deepStrictEqual(
321 createStageWorkspaceConfig({ platform: "win", arch: "arm64", linuxServerBackend: true }),
322 {
323 supportedArchitectures: {
324 os: ["win32", "linux"],
325 cpu: ["arm64"],
326 libc: ["glibc"],
327 },
328 nodeLinker: "hoisted",
329 },
330 );
331 assert.deepStrictEqual(createStageWorkspaceConfig({ platform: "mac", arch: "universal" }), {
332 supportedArchitectures: {
333 os: ["darwin"],
334 cpu: ["arm64", "x64"],
335 },
336 });
337 });
338​
339 it("stages pnpm 11 allowBuilds and patchedDependencies in the workspace yaml", () => {
340 assert.deepStrictEqual(
341 createStageWorkspaceConfig({
342 platform: "linux",
343 arch: "x64",
344 allowBuilds: {
345 electron: true,
346 "node-pty": true,
347 "browser-tabs-lock": false,
348 },
349 patchedDependencies: {
350 "effect@4.0.0-beta.73": "patches/effect@4.0.0-beta.73.patch",
351 },
352 overrides: {
353 effect: "4.0.0-beta.73",
354 },
355 }),
356 {
357 supportedArchitectures: {
358 os: ["linux"],
359 cpu: ["x64"],
360 libc: ["glibc"],
361 },
362 allowBuilds: {
363 electron: true,
364 "node-pty": true,
365 "browser-tabs-lock": false,
366 },
367 patchedDependencies: {
368 "effect@4.0.0-beta.73": "patches/effect@4.0.0-beta.73.patch",
369 },
370 overrides: {
371 effect: "4.0.0-beta.73",
372 },
373 },
374 );
375​
376 // Empty maps must not be written — pnpm would still require reviewed
377 // packages if allowBuilds is present but incomplete, and omitting empty
378 // patchedDependencies keeps the stage yaml minimal.
379 assert.deepStrictEqual(
380 createStageWorkspaceConfig({
381 platform: "mac",
382 arch: "arm64",
383 allowBuilds: {},
384 patchedDependencies: {},
385 overrides: {},
386 }),
387 {
388 supportedArchitectures: {
389 os: ["darwin"],
390 cpu: ["arm64"],
391 },
392 },
393 );
394 });
395​
396 it("limits Electron locales and excludes the unused Claude SDK executable", () => {
397 assert.deepStrictEqual(DESKTOP_ELECTRON_LANGUAGES, ["en-US"]);
398 assert.deepStrictEqual(DESKTOP_FILE_EXCLUSIONS, [
399 "!**/node_modules/@anthropic-ai/claude-agent-sdk-*/**/*",
400 "!apps/desktop/prod-resources/windows-server",
401 "!apps/desktop/prod-resources/windows-server/**/*",
402 ]);
403 assert.equal(WINDOWS_SERVER_RESOURCE_SOURCE_DIR, "apps/desktop/prod-resources/windows-server");
404 assert.deepStrictEqual(WINDOWS_SERVER_EXTRA_RESOURCES, [
405 {
406 from: "apps/desktop/prod-resources/windows-server",
407 to: ".",
408 filter: ["server.asar", "server.asar.unpacked/**/*"],
409 },
410 ]);
411 });
412​
413 it.effect("applies platform-specific packaging to the build config", () =>
414 Effect.gen(function* () {
415 const mac = yield* createBuildConfig(
416 "mac",
417 "dmg",
418 "1.2.3",
419 false,
420 false,
421 undefined,
422 undefined,
423 );
424 const linux = yield* createBuildConfig(
425 "linux",
426 "AppImage",
427 "1.2.3",
428 false,
429 false,
430 undefined,
431 undefined,
432 );
433 const win = yield* createBuildConfig(
434 "win",
435 "nsis",
436 "1.2.3",
437 false,
438 false,
439 undefined,
440 undefined,
441 );
442​
443 // All platforms keep app.asar fully packed; Windows ships the server
444 // tree as the hand-packed server.asar sidecar in extraResources instead
445 // of unpacking thousands of loose files at install time.
446 assert.notProperty(mac, "asarUnpack");
447 assert.notProperty(linux, "asarUnpack");
448 assert.notProperty(win, "asarUnpack");
449 assert.deepStrictEqual(win.extraResources, [
450 {
451 from: "apps/desktop/prod-resources/resource-monitor",
452 to: "resource-monitor",
453 },
454 ...WINDOWS_SERVER_EXTRA_RESOURCES,
455 ]);
456 assert.deepStrictEqual(win.nsis, { differentialPackage: true });
457 // Native binaries and helper executables cannot load from inside an
458 // asar; everything else stays packed. The Claude SDK platform packages
459 // and .bin shims never ship.
460 assert.equal(
461 WINDOWS_SERVER_ASAR_UNPACK_GLOB,
462 "{**/*.node,**/*.dll,**/*.exe,**/*.so,**/*.so.*,**/*.dylib}",
463 );
464 assert.deepStrictEqual(WINDOWS_SERVER_ASAR_IGNORE_GLOBS, [
465 "**/node_modules/@anthropic-ai/claude-agent-sdk-*",
466 "**/node_modules/@anthropic-ai/claude-agent-sdk-*/**",
467 "**/node_modules/.bin",
468 "**/node_modules/.bin/**",
469 ]);
470 assert.deepStrictEqual(mac.dmg, {
471 title: "T3 Code (Alpha) 1.2.3 Installer",
472 background: "dmg/dmg-background-latest.png",
473 window: { width: 540, height: 412 },
474 contents: [
475 { x: 130, y: 220, type: "file" },
476 { x: 410, y: 220, type: "link", path: "/Applications" },
477 ],
478 iconSize: 80,
479 iconTextSize: 12,
480 });
481 // Linux must register the renderer schemes so the generated .desktop
482 // entry advertises MimeType=x-scheme-handler/t3code; for OAuth deep links.
483 assert.deepStrictEqual((linux.linux as Record<string, unknown>).protocols, [
484 { name: "T3 Code", schemes: ["t3code", "t3code-dev"] },
485 ]);
486 for (const config of [mac, linux, win]) {
487 assert.deepStrictEqual(config.electronLanguages, DESKTOP_ELECTRON_LANGUAGES);
488 assert.deepStrictEqual(config.files, DESKTOP_FILE_EXCLUSIONS);
489 }
490 }).pipe(Effect.provide(ConfigProvider.layer(ConfigProvider.fromEnv({ env: {} })))),
491 );
492​
493 it("excludes node-pty binaries for the other Windows architecture", () => {
494 assert.deepStrictEqual(resolveWindowsServerAsarIgnoreGlobs("x64"), [
495 ...WINDOWS_SERVER_ASAR_IGNORE_GLOBS,
496 "**/node_modules/node-pty/prebuilds/win32-arm64",
497 "**/node_modules/node-pty/prebuilds/win32-arm64/**",
498 "**/node_modules/node-pty/third_party/conpty/*/win10-arm64",
499 "**/node_modules/node-pty/third_party/conpty/*/win10-arm64/**",
500 ]);
501 assert.deepStrictEqual(resolveWindowsServerAsarIgnoreGlobs("arm64"), [
502 ...WINDOWS_SERVER_ASAR_IGNORE_GLOBS,
503 "**/node_modules/node-pty/prebuilds/win32-x64",
504 "**/node_modules/node-pty/prebuilds/win32-x64/**",
505 "**/node_modules/node-pty/third_party/conpty/*/win10-x64",
506 "**/node_modules/node-pty/third_party/conpty/*/win10-x64/**",
507 ]);
508 });
509​
510 it.effect(
511 "keeps target and WSL native files while excluding the other Windows architecture",
512 () =>
513 Effect.scoped(
514 Effect.gen(function* () {
515 const fs = yield* FileSystem.FileSystem;
516 const path = yield* Path.Path;
517 const tempDir = yield* fs.makeTempDirectoryScoped({
518 prefix: "t3-windows-architecture-test-",
519 });
520 const sourceDir = path.join(tempDir, "server");
521 const nativeFiles = [
522 "node_modules/node-pty/prebuilds/win32-x64/conpty/OpenConsole.exe",
523 "node_modules/node-pty/prebuilds/win32-arm64/conpty/OpenConsole.exe",
524 "node_modules/node-pty/prebuilds/linux-x64/pty.node",
525 "node_modules/node-pty/third_party/conpty/1.0.0/win10-x64/OpenConsole.exe",
526 "node_modules/node-pty/third_party/conpty/1.0.0/win10-arm64/OpenConsole.exe",
527 ];
528​
529 for (const nativeFile of nativeFiles) {
530 const nativePath = path.join(sourceDir, nativeFile);
531 yield* fs.makeDirectory(path.dirname(nativePath), { recursive: true });
532 yield* fs.writeFileString(nativePath, "native");
533 }
534​
535 const asarPath = path.join(tempDir, "server.asar");
536 yield* packWindowsServerAsar({ sourceDir, asarPath, arch: "x64" });
537 const unpackedRoot = `${asarPath}.unpacked`;
538​
539 assert.isTrue(
540 yield* fs.exists(
541 path.join(
542 unpackedRoot,
543 "node_modules/node-pty/prebuilds/win32-x64/conpty/OpenConsole.exe",
544 ),
545 ),
546 );
547 assert.isTrue(
548 yield* fs.exists(
549 path.join(unpackedRoot, "node_modules/node-pty/prebuilds/linux-x64/pty.node"),
550 ),
551 );
552 assert.isFalse(
553 yield* fs.exists(
554 path.join(unpackedRoot, "node_modules/node-pty/prebuilds/win32-arm64"),
555 ),
556 );
557 assert.isFalse(
558 yield* fs.exists(
559 path.join(unpackedRoot, "node_modules/node-pty/third_party/conpty/1.0.0/win10-arm64"),
560 ),
561 );
562 }),
563 ),
564 );
565​
566 it.effect("stages a cached resource monitor without invoking Cargo", () =>
567 Effect.scoped(
568 Effect.gen(function* () {
569 const fs = yield* FileSystem.FileSystem;
570 const path = yield* Path.Path;
571 const repoRoot = yield* fs.makeTempDirectoryScoped({
572 prefix: "t3-resource-monitor-cache-test-",
573 });
574 const binaryPath = path.join(
575 repoRoot,
576 "native/resource-monitor/target/x86_64-unknown-linux-gnu/release/t3-resource-monitor",
577 );
578 const stageResourcesDir = path.join(repoRoot, "stage");
579 yield* fs.makeDirectory(path.dirname(binaryPath), { recursive: true });
580 yield* fs.writeFileString(binaryPath, "cached monitor");
581​
582 yield* stageResourceMonitor({
583 repoRoot,
584 stageResourcesDir,
585 platform: "linux",
586 arch: "x64",
587 verbose: false,
588 }).pipe(
589 Effect.provide(
590 ConfigProvider.layer(
591 ConfigProvider.fromEnv({
592 env: { T3CODE_DESKTOP_REUSE_RESOURCE_MONITOR: "true" },
593 }),
594 ),
595 ),
596 );
597​
598 assert.equal(
599 yield* fs.readFileString(
600 path.join(stageResourcesDir, "resource-monitor/t3-resource-monitor"),
601 ),
602 "cached monitor",
603 );
604 }),
605 ),
606 );
607​
608 it.effect("validates every ASAR-unpacked native in the packaged Windows payload", () =>
609 Effect.scoped(
610 Effect.gen(function* () {
611 const fs = yield* FileSystem.FileSystem;
612 const path = yield* Path.Path;
613 const fixture = yield* makeWindowsPayloadFixture({ copyUnpackedNatives: true });
614 const result = yield* validateWindowsPackagedPayload({
615 stageDistDir: fixture.stageDistDir,
616 appExecutableName: fixture.appExecutableName,
617 targetArch: "x64",
618 });
619​
620 const secondAsarPath = path.join(path.dirname(fixture.generatedAsarPath), "second.asar");
621 yield* packWindowsServerAsar({
622 sourceDir: fixture.sourceDir,
623 asarPath: secondAsarPath,
624 arch: "x64",
625 });
626 const [firstAsar, secondAsar] = yield* Effect.all([
627 fs.readFile(fixture.generatedAsarPath),
628 fs.readFile(secondAsarPath),
629 ]);
630​
631 assert.equal(result.packagedAppDir, fixture.packagedAppDir);
632 assert.deepStrictEqual(result.unpackedFiles, ["node_modules/native/addon.node"]);
633 assert.isBelow(result.fileCount, WINDOWS_PACKAGED_PAYLOAD_FILE_LIMIT);
634 assert.deepStrictEqual(secondAsar, firstAsar);
635 }),
636 ),
637 );
638​
639 it.effect("probes fff through the packaged Windows primary instead of helper executables", () => {
640 const commands: Array<{
641 readonly command: string;
642 readonly args: ReadonlyArray<string>;
643 readonly options: {
644 readonly cwd?: string;
645 readonly env?: Readonly<Record<string, string | undefined>>;
646 };
647 }> = [];
648 const spawnerLayer = Layer.succeed(
649 ChildProcessSpawner.ChildProcessSpawner,
650 ChildProcessSpawner.make((command) => {
651 commands.push(command as unknown as (typeof commands)[number]);
652 return Effect.succeed(mockProcess(0));
653 }),
654 );
655​
656 return Effect.scoped(
657 Effect.gen(function* () {
658 const path = yield* Path.Path;
659 const fixture = yield* makeWindowsPayloadFixture({ copyUnpackedNatives: true });
660 yield* validateWindowsPackagedPayload({
661 stageDistDir: fixture.stageDistDir,
662 appExecutableName: fixture.appExecutableName,
663 targetArch: "x64",
664 });
665​
666 const primaryProbe = commands.find(
667 (command) => command.options.env?.ELECTRON_RUN_AS_NODE === "1",
668 );
669 if (primaryProbe === undefined) return assert.fail("Windows primary probe was not spawned");
670​
671 assert.equal(
672 primaryProbe.command,
673 path.join(fixture.packagedAppDir, fixture.appExecutableName),
674 );
675 assert.deepStrictEqual(primaryProbe.args.slice(0, 3), [
676 "--no-global-search-paths",
677 "--input-type=module",
678 "--eval",
679 ]);
680 assert.include(primaryProbe.args[3], "FileFinder.create");
681 assert.equal(
682 primaryProbe.args[4],
683 path.join(
684 fixture.packagedAppDir,
685 "resources/server.asar/node_modules/@ff-labs/fff-node/dist/src/index.js",
686 ),
687 );
688 assert.equal(primaryProbe.options.cwd, fixture.packagedAppDir);
689 assert.equal(primaryProbe.options.env?.NODE_PATH, "");
690 }),
691 ).pipe(
692 Effect.provide(
693 Layer.mergeAll(
694 spawnerLayer,
695 Layer.succeed(HostProcessPlatform, "win32"),
696 Layer.succeed(HostProcessArchitecture, "x64"),
697 ),
698 ),
699 );
700 });
701​
702 it.effect("skips the primary native probe for cross-architecture Windows payloads", () => {
703 const commands: Array<{
704 readonly command: string;
705 readonly options: {
706 readonly env?: Readonly<Record<string, string | undefined>>;
707 };
708 }> = [];
709 const spawnerLayer = Layer.succeed(
710 ChildProcessSpawner.ChildProcessSpawner,
711 ChildProcessSpawner.make((command) => {
712 commands.push(command as unknown as (typeof commands)[number]);
713 return Effect.succeed(mockProcess(0));
714 }),
715 );
716​
717 return Effect.scoped(
718 Effect.gen(function* () {
719 const fixture = yield* makeWindowsPayloadFixture({ copyUnpackedNatives: true });
720 yield* validateWindowsPackagedPayload({
721 stageDistDir: fixture.stageDistDir,
722 appExecutableName: fixture.appExecutableName,
723 targetArch: "arm64",
724 });
725​
726 assert.isFalse(
727 commands.some((command) => command.options.env?.ELECTRON_RUN_AS_NODE === "1"),
728 );
729 assert.isTrue(
730 commands.some(
731 (command) =>
732 command.command === process.execPath && command.options.env?.NODE_PATH === "",
733 ),
734 );
735 }),
736 ).pipe(
737 Effect.provide(
738 Layer.mergeAll(
739 spawnerLayer,
740 Layer.succeed(HostProcessPlatform, "win32"),
741 Layer.succeed(HostProcessArchitecture, "x64"),
742 ),
743 ),
744 );
745 });
746​
747 it.effect("rejects a cross-architecture Windows payload without its primary executable", () =>
748 Effect.scoped(
749 Effect.gen(function* () {
750 const fs = yield* FileSystem.FileSystem;
751 const path = yield* Path.Path;
752 const fixture = yield* makeWindowsPayloadFixture({ copyUnpackedNatives: true });
753 const executablePath = path.join(fixture.packagedAppDir, fixture.appExecutableName);
754 yield* fs.remove(executablePath);
755​
756 const error = yield* validateWindowsPackagedPayload({
757 stageDistDir: fixture.stageDistDir,
758 appExecutableName: fixture.appExecutableName,
759 targetArch: "arm64",
760 }).pipe(Effect.flip);
761​
762 assert.instanceOf(error, WindowsPrimaryNativeProbeError);
763 assert.equal(error.executablePath, executablePath);
764 }),
765 ).pipe(
766 Effect.provide(
767 Layer.mergeAll(
768 Layer.succeed(HostProcessPlatform, "win32"),
769 Layer.succeed(HostProcessArchitecture, "x64"),
770 ),
771 ),
772 ),
773 );
774​
775 it.effect("rejects a packaged sidecar whose ASAR-unpacked native is missing", () =>
776 Effect.scoped(
777 Effect.gen(function* () {
778 const fixture = yield* makeWindowsPayloadFixture({ copyUnpackedNatives: false });
779 const error = yield* validateWindowsPackagedPayload({
780 stageDistDir: fixture.stageDistDir,
781 appExecutableName: fixture.appExecutableName,
782 targetArch: "x64",
783 }).pipe(Effect.flip);
784​
785 assert.instanceOf(error, WindowsPackagedPayloadValidationError);
786 assert.equal(error.reason, "unpacked-native-missing");
787 assert.deepStrictEqual(error.missingFiles, [
788 "server.asar.unpacked/node_modules/native/addon.node",
789 ]);
790 }),
791 ),
792 );
793​
794 it.effect("rejects directories in place of packaged executable files", () =>
795 Effect.scoped(
796 Effect.gen(function* () {
797 const fs = yield* FileSystem.FileSystem;
798 const path = yield* Path.Path;
799 const fixture = yield* makeWindowsPayloadFixture({ copyUnpackedNatives: true });
800 const nativePath = path.join(
801 fixture.packagedAppDir,
802 "resources/server.asar.unpacked/node_modules/native/addon.node",
803 );
804 yield* fs.remove(nativePath);
805 yield* fs.makeDirectory(nativePath);
806​
807 const nativeError = yield* validateWindowsPackagedPayload({
808 stageDistDir: fixture.stageDistDir,
809 appExecutableName: fixture.appExecutableName,
810 targetArch: "x64",
811 }).pipe(Effect.flip);
812 assert.instanceOf(nativeError, WindowsPackagedPayloadValidationError);
813 assert.equal(nativeError.reason, "unpacked-native-missing");
814 assert.deepStrictEqual(nativeError.missingFiles, [
815 "server.asar.unpacked/node_modules/native/addon.node",
816 ]);
817​
818 yield* fs.remove(nativePath, { recursive: true });
819 yield* fs.writeFileString(nativePath, "native-binary");
820 const resourceMonitorPath = path.join(
821 fixture.packagedAppDir,
822 "resources/resource-monitor/t3-resource-monitor.exe",
823 );
824 yield* fs.remove(resourceMonitorPath);
825 yield* fs.makeDirectory(resourceMonitorPath);
826​
827 const resourceMonitorError = yield* validateWindowsPackagedPayload({
828 stageDistDir: fixture.stageDistDir,
829 appExecutableName: fixture.appExecutableName,
830 targetArch: "x64",
831 }).pipe(Effect.flip);
832 assert.instanceOf(resourceMonitorError, WindowsPackagedPayloadValidationError);
833 assert.equal(resourceMonitorError.reason, "resource-monitor-missing");
834 assert.deepStrictEqual(resourceMonitorError.missingFiles, [
835 "resource-monitor/t3-resource-monitor.exe",
836 ]);
837 }),
838 ),
839 );
840​
841 it.effect("rejects a Windows payload that regresses above the file-count budget", () =>
842 Effect.scoped(
843 Effect.gen(function* () {
844 const fixture = yield* makeWindowsPayloadFixture({ copyUnpackedNatives: true });
845 const error = yield* validateWindowsPackagedPayload({
846 stageDistDir: fixture.stageDistDir,
847 appExecutableName: fixture.appExecutableName,
848 targetArch: "x64",
849 fileLimit: 2,
850 }).pipe(Effect.flip);
851​
852 assert.instanceOf(error, WindowsPackagedPayloadValidationError);
853 assert.equal(error.reason, "file-limit-exceeded");
854 assert.isAbove(error.fileCount ?? 0, 2);
855 }),
856 ),
857 );
858​
859 it.effect("rejects a sidecar whose extracted server bundle cannot resolve", () =>
860 Effect.scoped(
861 Effect.gen(function* () {
862 const fixture = yield* makeWindowsPayloadFixture({
863 copyUnpackedNatives: true,
864 serverEntrySource: 'import "t3code-deliberately-missing-package";\n',
865 });
866 const error = yield* validateWindowsPackagedPayload({
867 stageDistDir: fixture.stageDistDir,
868 appExecutableName: fixture.appExecutableName,
869 targetArch: "x64",
870 }).pipe(Effect.flip);
871​
872 assert.instanceOf(error, BundleNotSelfContainedError);
873 assert.include(error.output, "t3code-deliberately-missing-package");
874 }),
875 ),
876 );
877​
878 it.effect("preserves both Linux icon resize failures with structural context", () => {
879 const commands: Array<{ readonly command: string; readonly args: ReadonlyArray<string> }> = [];
880​
881 return Effect.gen(function* () {
882 const error = yield* stageLinuxIconSize("source.png", "target.png", 512, false).pipe(
883 Effect.provide(iconResizeSpawnerLayer(commands, [1, 2])),
884 Effect.flip,
885 );
886​
887 assert.instanceOf(error, LinuxIconResizeError);
888 assert.equal(error.operation, "resize");
889 assert.equal(error.iconSize, 512);
890 assert.equal(error.primaryTool, "magick");
891 assert.equal(error.fallbackTool, "convert");
892 assert.include(error.message, "512x512");
893 assert.include(error.message, "`magick`");
894 assert.include(error.message, "`convert`");
895 assert.notInclude(error.message, "non-zero exit code");
896​
897 assert.instanceOf(error.cause, AggregateError);
898 const aggregateCause = error.cause as AggregateError;
899 assert.lengthOf(aggregateCause.errors, 2);
900 assert.strictEqual(aggregateCause.cause, aggregateCause.errors[0]);
901 assert.instanceOf(aggregateCause.errors[0], BuildCommandFailedError);
902 assert.instanceOf(aggregateCause.errors[1], BuildCommandFailedError);
903 const primaryError = aggregateCause.errors[0] as BuildCommandFailedError;
904 const fallbackError = aggregateCause.errors[1] as BuildCommandFailedError;
905 assert.equal(primaryError.command, "magick linux icon 512x512");
906 assert.equal(primaryError.exitCode, 1);
907 assert.include(primaryError.message, "magick linux icon");
908 assert.equal(fallbackError.command, "convert linux icon 512x512");
909 assert.equal(fallbackError.exitCode, 2);
910 assert.include(fallbackError.message, "convert linux icon");
911 assert.deepStrictEqual(
912 commands.map(({ command }) => command),
913 ["magick", "convert"],
914 );
915 });
916 });
917​
918 it.effect("rasterizes staged DMG backgrounds at standard and Retina sizes", () =>
919 Effect.scoped(
920 Effect.gen(function* () {
921 const fs = yield* FileSystem.FileSystem;
922 const path = yield* Path.Path;
923 const stageResourcesDir = yield* fs.makeTempDirectoryScoped({
924 prefix: "t3code-dmg-background-",
925 });
926 const dmgDir = path.join(stageResourcesDir, "dmg");
927 yield* fs.makeDirectory(dmgDir, { recursive: true });
928 const sourcePath = path.join(dmgDir, "dmg-background-nightly.svg");
929 yield* fs.writeFileString(sourcePath, '<svg xmlns="http://www.w3.org/2000/svg"/>');
930 const commands: Array<{ readonly command: string; readonly args: ReadonlyArray<string> }> =
931 [];
932​
933 yield* stageDesktopDmgBackground(stageResourcesDir, "nightly", false).pipe(
934 Effect.provide(iconResizeSpawnerLayer(commands, [0, 0])),
935 );
936​
937 assert.deepStrictEqual(
938 commands.map((command) => [command.command, ...command.args]),
939 [
940 [
941 "sips",
942 "-s",
943 "format",
944 "png",
945 "-z",
946 "380",
947 "540",
948 sourcePath,
949 "--out",
950 path.join(dmgDir, "dmg-background-nightly.png"),
951 ],
952 [
953 "sips",
954 "-s",
955 "format",
956 "png",
957 "-z",
958 "760",
959 "1080",
960 sourcePath,
961 "--out",
962 path.join(dmgDir, "dmg-background-nightly@2x.png"),
963 ],
964 ],
965 );
966 }),
967 ),
968 );
969​
970 it.effect("fails clearly when the selected DMG background source is missing", () =>
971 Effect.scoped(
972 Effect.gen(function* () {
973 const fs = yield* FileSystem.FileSystem;
974 const stageResourcesDir = yield* fs.makeTempDirectoryScoped({
975 prefix: "t3code-dmg-background-missing-",
976 });
977​
978 const error = yield* stageDesktopDmgBackground(stageResourcesDir, "latest", false).pipe(
979 Effect.flip,
980 );
981​
982 assert.instanceOf(error, DesktopDmgBackgroundSourceMissingError);
983 assert.equal(error.channel, "latest");
984 assert.include(error.sourcePath, "dmg-background-latest.svg");
985 }),
986 ),
987 );
988​
989 it("derives macOS passkey signing configuration from the Clerk publishable key", () => {
990 const configuration = resolveMacPasskeySigningConfiguration({
991 T3CODE_APPLE_TEAM_ID: "abc1234567",
992 T3CODE_MACOS_PROVISIONING_PROFILE: "/tmp/t3code.provisionprofile",
993 T3CODE_CLERK_PUBLISHABLE_KEY: `pk_test_${btoa("example.clerk.accounts.dev$")}`,
994 });
995​
996 assert.deepStrictEqual(configuration, {
997 appId: "com.t3tools.t3code",
998 teamId: "ABC1234567",
999 rpDomains: ["example.clerk.accounts.dev"],
1000 provisioningProfilePath: "/tmp/t3code.provisionprofile",
1001 });
1002 });
1003​
1004 it("normalizes explicit macOS passkey RP domains and renders required entitlements", () => {
1005 const configuration = resolveMacPasskeySigningConfiguration({
1006 T3CODE_APPLE_TEAM_ID: "ABC1234567",
1007 T3CODE_MACOS_PROVISIONING_PROFILE: "/tmp/t3code.provisionprofile",
1008 T3CODE_CLERK_PASSKEY_RP_DOMAINS:
1009 " Clerk.Example.com,example.clerk.accounts.dev,clerk.example.com ",
1010 });
1011 const entitlements = renderMacPasskeyEntitlements(configuration);
1012​
1013 assert.deepStrictEqual(configuration.rpDomains, [
1014 "clerk.example.com",
1015 "example.clerk.accounts.dev",
1016 ]);
1017 assert.include(entitlements, "<string>ABC1234567.com.t3tools.t3code</string>");
1018 assert.include(entitlements, "<string>webcredentials:clerk.example.com</string>");
1019 assert.include(entitlements, "<string>webcredentials:example.clerk.accounts.dev</string>");
1020 assert.include(entitlements, "<key>com.apple.security.cs.allow-jit</key>");
1021 });
1022​
1023 it("rejects incomplete macOS passkey signing configuration", () => {
1024 const captureError = (env: Readonly<Record<string, string | undefined>>) => {
1025 try {
1026 resolveMacPasskeySigningConfiguration(env);
1027 } catch (error) {
1028 return error;
1030 return assert.fail("Expected passkey signing configuration to fail.");
1031 };
1032​
1033 const missingProfileError = captureError({
1034 T3CODE_APPLE_TEAM_ID: "ABC1234567",
1035 T3CODE_CLERK_PASSKEY_RP_DOMAINS: "example.clerk.accounts.dev",
1036 });
1037 assert.instanceOf(missingProfileError, MissingMacPasskeyProvisioningProfileError);
1038 assert.equal(
1039 missingProfileError.message,
1040 "T3CODE_MACOS_PROVISIONING_PROFILE must point to an Associated Domains provisioning profile.",
1041 );
1042​
1043 const unsafeDomain =
1044 "https://domain-user:domain-secret@example.clerk.accounts.dev/path?token=query-secret";
1045 const invalidDomainError = captureError({
1046 T3CODE_APPLE_TEAM_ID: "ABC1234567",
1047 T3CODE_MACOS_PROVISIONING_PROFILE: "/tmp/t3code.provisionprofile",
1048 T3CODE_CLERK_PASSKEY_RP_DOMAINS: unsafeDomain,
1049 });
1050 assert.instanceOf(invalidDomainError, InvalidMacPasskeyRpDomainError);
1051 assert.equal(invalidDomainError.reason, "scheme-not-allowed");
1052 assert.equal(invalidDomainError.inputLength, unsafeDomain.length);
1053 assert.equal(invalidDomainError.message, "Invalid passkey RP domain (scheme-not-allowed).");
1054 assert.notProperty(invalidDomainError, "domain");
1055 assert.notProperty(invalidDomainError, "cause");
1056 const serializedInvalidDomainError = JSON.stringify(invalidDomainError);
1057 assert.notInclude(serializedInvalidDomainError, unsafeDomain);
1058 assert.notInclude(serializedInvalidDomainError, "domain-user");
1059 assert.notInclude(serializedInvalidDomainError, "domain-secret");
1060 assert.notInclude(serializedInvalidDomainError, "query-secret");
1061 assert.throws(
1062 () =>
1063 resolveMacPasskeySigningConfiguration({
1064 T3CODE_APPLE_TEAM_ID: "ABC1234567",
1065 T3CODE_MACOS_PROVISIONING_PROFILE: "/tmp/t3code.provisionprofile",
1066 T3CODE_CLERK_PASSKEY_RP_DOMAINS: "example.clerk.accounts.dev:8443",
1067 }),
1068 /Invalid passkey RP domain/u,
1069 );
1070 const invalidPublishableKeyError = captureError({
1071 T3CODE_APPLE_TEAM_ID: "ABC1234567",
1072 T3CODE_MACOS_PROVISIONING_PROFILE: "/tmp/t3code.provisionprofile",
1073 T3CODE_CLERK_PUBLISHABLE_KEY: "pk_test_%",
1074 });
1075 assert.instanceOf(invalidPublishableKeyError, InvalidMacPasskeyPublishableKeyError);
1076 assert.ok(invalidPublishableKeyError.cause);
1077 assert.equal(invalidPublishableKeyError.message, "T3CODE_CLERK_PUBLISHABLE_KEY is invalid.");
1078 assert.notProperty(invalidPublishableKeyError, "publishableKey");
1079 assert.notInclude(invalidPublishableKeyError.message, "pk_test_%");
1080 });
1081​
1082 it("preserves known passkey signing configuration errors at the build boundary", () => {
1083 const decodingCause = new Error("publishable-key-decode-failed");
1084 const knownError = new InvalidMacPasskeyPublishableKeyError({ cause: decodingCause });
1085 const error = MacPasskeySigningConfigurationResolutionError.fromCause(knownError);
1086​
1087 assert.strictEqual(error, knownError);
1088 assert.instanceOf(error, InvalidMacPasskeyPublishableKeyError);
1089 assert.strictEqual(error.cause, decodingCause);
1090 assert.isTrue(isMacPasskeySigningConfigurationError(error));
1091 });
1092​
1093 it("wraps unknown passkey signing configuration defects without copying cause text", () => {
1094 const secret = "pk_test_do-not-retain";
1095 const cause = new Error(secret);
1096 const error = MacPasskeySigningConfigurationResolutionError.fromCause(cause);
1097​
1098 assert.instanceOf(error, MacPasskeySigningConfigurationResolutionError);
1099 assert.strictEqual(error.cause, cause);
1100 assert.equal(error.message, "Failed to resolve macOS passkey signing configuration.");
1101 assert.notInclude(error.message, secret);
1102 });
1103​
1104 it.effect("adds passkey entitlements and both renderer protocols to signed macOS builds", () =>
1105 Effect.gen(function* () {
1106 const config = yield* createBuildConfig("mac", "dmg", "1.2.3", true, false, undefined, {
1107 entitlementsPath: "/tmp/entitlements.mac.plist",
1108 provisioningProfilePath: "/tmp/t3code.provisionprofile",
1109 });
1110​
1111 const mac = config.mac as Record<string, unknown>;
1112 assert.equal(config.appId, "com.t3tools.t3code");
1113 assert.equal(mac.entitlements, "/tmp/entitlements.mac.plist");
1114 assert.equal(mac.provisioningProfile, "/tmp/t3code.provisionprofile");
1115 assert.deepStrictEqual(mac.protocols, [
1116 { name: "T3 Code", schemes: ["t3code", "t3code-dev"] },
1117 ]);
1118 }).pipe(Effect.provide(ConfigProvider.layer(ConfigProvider.fromEnv({ env: {} })))),
1119 );
1120​
1121 it.effect("uses the nightly DMG background for nightly macOS builds", () =>
1122 Effect.gen(function* () {
1123 const config = yield* createBuildConfig(
1124 "mac",
1125 "dmg",
1126 "1.2.3-nightly.20260815.1",
1127 false,
1128 false,
1129 undefined,
1130 undefined,
1131 );
1132​
1133 assert.equal(
1134 (config.dmg as Record<string, unknown>).background,
1135 "dmg/dmg-background-nightly.png",
1136 );
1137 }).pipe(Effect.provide(ConfigProvider.layer(ConfigProvider.fromEnv({ env: {} })))),
1138 );
1139​
1140 it.effect("keeps executable resource editing enabled for unsigned Windows builds", () =>
1141 Effect.gen(function* () {
1142 const config = yield* createBuildConfig(
1143 "win",
1144 "nsis",
1145 "1.2.3",
1146 false,
1147 false,
1148 undefined,
1149 undefined,
1150 );
1151​
1152 const win = config.win as Record<string, unknown>;
1153 assert.equal(win.icon, "icon.ico");
1154 assert.equal(win.signAndEditExecutable, true);
1155 assert.notProperty(win, "azureSignOptions");
1156 }).pipe(Effect.provide(ConfigProvider.layer(ConfigProvider.fromEnv({ env: {} })))),
1157 );
1158​
1159 it("stages the resource monitor as an external executable resource", () => {
1160 assert.deepStrictEqual(DESKTOP_EXTRA_RESOURCES, [
1162 from: "apps/desktop/prod-resources/resource-monitor",
1163 to: "resource-monitor",
1164 },
1165 ]);
1166 assert.deepStrictEqual(resolveResourceMonitorRustTargets("mac", "universal"), [
1167 "aarch64-apple-darwin",
1168 "x86_64-apple-darwin",
1169 ]);
1170 assert.deepStrictEqual(resolveResourceMonitorRustTargets("linux", "x64"), [
1171 "x86_64-unknown-linux-gnu",
1172 ]);
1173 assert.deepStrictEqual(resolveResourceMonitorRustTargets("win", "arm64"), [
1174 "aarch64-pc-windows-msvc",
1175 ]);
1176 assert.equal(resourceMonitorExecutableName("mac"), "t3-resource-monitor");
1177 assert.equal(resourceMonitorExecutableName("win"), "t3-resource-monitor.exe");
1178 });
1179 it("promotes target fff binaries to direct staged dependencies", () => {
1180 assert.deepStrictEqual(resolveFffNativeDependencies("mac", "arm64", "0.9.4"), {
1181 "@ff-labs/fff-bin-darwin-arm64": "0.9.4",
1182 });
1183 assert.deepStrictEqual(resolveFffNativeDependencies("mac", "universal", "0.9.4"), {
1184 "@ff-labs/fff-bin-darwin-arm64": "0.9.4",
1185 "@ff-labs/fff-bin-darwin-x64": "0.9.4",
1186 });
1187 assert.deepStrictEqual(resolveFffNativeDependencies("win", "x64", "0.9.4"), {
1188 "@ff-labs/fff-bin-win32-x64": "0.9.4",
1189 });
1190 assert.deepStrictEqual(resolveFffNativeDependencies("linux", "x64", "0.9.4"), {
1191 "@ff-labs/fff-bin-linux-x64-gnu": "0.9.4",
1192 "@ff-labs/fff-bin-linux-x64-musl": "0.9.4",
1193 });
1194 assert.deepStrictEqual(resolveFffNativeDependencies("linux", "arm64", "0.9.4"), {
1195 "@ff-labs/fff-bin-linux-arm64-gnu": "0.9.4",
1196 "@ff-labs/fff-bin-linux-arm64-musl": "0.9.4",
1197 });
1198 });
1199​
1200 it("resolves target Clerk passkey native artifacts", () => {
1201 assert.deepStrictEqual(resolveClerkPasskeyNativeArtifacts("mac", "universal"), [
1203 packageName: "@clerk/electron-passkeys-darwin-arm64",
1204 binaryFileName: "electron-passkeys.darwin-arm64.node",
1205 },
1207 packageName: "@clerk/electron-passkeys-darwin-x64",
1208 binaryFileName: "electron-passkeys.darwin-x64.node",
1209 },
1210 ]);
1211 assert.deepStrictEqual(resolveClerkPasskeyNativeArtifacts("win", "x64"), [
1213 packageName: "@clerk/electron-passkeys-win32-x64-msvc",
1214 binaryFileName: "electron-passkeys.win32-x64-msvc.node",
1215 },
1216 ]);
1217 assert.deepStrictEqual(resolveClerkPasskeyNativeArtifacts("linux", "x64"), []);
1218 });
1219​
1220 it("falls back to the default mock update port when the configured port is blank", () => {
1221 assert.equal(resolveMockUpdateServerUrl(undefined), "http://localhost:3000");
1222 assert.equal(resolveMockUpdateServerUrl(4123), "http://localhost:4123");
1223 });
1224​
1225 it("derives the electron-builder package manager user agent from packageManager", () => {
1226 assert.equal(resolvePackageManagerUserAgent("pnpm@11.10.0"), "pnpm/11.10.0");
1227 assert.equal(resolvePackageManagerUserAgent(" yarn@4.9.2 "), "yarn/4.9.2");
1228 assert.equal(resolvePackageManagerUserAgent("pnpm"), "pnpm");
1229 });
1230​
1231 it.effect("normalizes mock update server ports from env-style strings", () =>
1232 Effect.gen(function* () {
1233 assert.equal(yield* resolveMockUpdateServerPort(undefined), undefined);
1234 assert.equal(yield* resolveMockUpdateServerPort(""), undefined);
1235 assert.equal(yield* resolveMockUpdateServerPort(" "), undefined);
1236 assert.equal(yield* resolveMockUpdateServerPort("4123"), 4123);
1237 }),
1238 );
1239​
1240 it.effect("rejects non-numeric or out-of-range mock update ports", () =>
1241 Effect.gen(function* () {
1242 const invalidPorts = ["abc", "12.5", "0", "65536"];
1243 for (const port of invalidPorts) {
1244 const exit = yield* Effect.exit(resolveMockUpdateServerPort(port));
1245 assert.equal(exit._tag, "Failure");
1247 }),
1248 );
1249​
1250 it("classifies invalid configured ports with the decoder's number grammar", () => {
1251 const cause = new Error("invalid configured port");
1252​
1253 assert.equal(
1254 InvalidMockUpdateServerPortError.fromConfigValue("0x10", cause).reason,
1255 "not-numeric",
1256 );
1257 assert.equal(
1258 InvalidMockUpdateServerPortError.fromConfigValue("12.5", cause).reason,
1259 "not-integer",
1260 );
1261 assert.equal(
1262 InvalidMockUpdateServerPortError.fromConfigValue("65536", cause).reason,
1263 "out-of-range",
1264 );
1265 assert.strictEqual(
1266 InvalidMockUpdateServerPortError.fromConfigValue("0x10", cause).cause,
1267 cause,
1268 );
1269 });
1270​
1271 it.effect("resolves default platform and architecture from host references", () =>
1272 Effect.gen(function* () {
1273 const resolved = yield* resolveBuildOptions({
1274 platform: Option.none(),
1275 target: Option.none(),
1276 arch: Option.none(),
1277 buildVersion: Option.none(),
1278 outputDir: Option.none(),
1279 skipBuild: Option.none(),
1280 keepStage: Option.none(),
1281 signed: Option.none(),
1282 verbose: Option.none(),
1283 mockUpdates: Option.none(),
1284 mockUpdateServerPort: Option.none(),
1285 wslPrebuild: Option.none(),
1286 }).pipe(
1287 Effect.provide(
1288 Layer.mergeAll(
1289 Layer.succeed(HostProcessPlatform, "win32"),
1290 Layer.succeed(HostProcessArchitecture, "x64"),
1291 ConfigProvider.layer(
1292 ConfigProvider.fromEnv({
1293 env: {
1294 PROCESSOR_ARCHITECTURE: "AMD64",
1295 PROCESSOR_ARCHITEW6432: "ARM64",
1296 },
1297 }),
1298 ),
1299 ),
1300 ),
1301 );
1302​
1303 assert.equal(resolved.platform, "win");
1304 assert.equal(resolved.target, "nsis");
1305 assert.equal(resolved.arch, "arm64");
1306 }),
1307 );
1308​
1309 it.effect("rejects universal builds on Linux and Windows before staging binaries", () =>
1310 Effect.gen(function* () {
1311 for (const platform of ["linux", "win"] as const) {
1312 const error = yield* Effect.flip(
1313 resolveBuildOptions({
1314 platform: Option.some(platform),
1315 target: Option.none(),
1316 arch: Option.some("universal"),
1317 buildVersion: Option.none(),
1318 outputDir: Option.none(),
1319 skipBuild: Option.none(),
1320 keepStage: Option.none(),
1321 signed: Option.none(),
1322 verbose: Option.none(),
1323 mockUpdates: Option.none(),
1324 mockUpdateServerPort: Option.none(),
1325 wslPrebuild: Option.none(),
1326 }),
1327 );
1328​
1329 assert.instanceOf(error, UnsupportedDesktopBuildArchitectureError);
1330 assert.deepStrictEqual(error.supportedArchitectures, ["x64", "arm64"]);
1332 }),
1333 );
1334​
1335 it.effect("preserves explicit false boolean flags over true env defaults", () =>
1336 Effect.gen(function* () {
1337 const resolved = yield* resolveBuildOptions({
1338 platform: Option.some("mac"),
1339 target: Option.none(),
1340 arch: Option.some("arm64"),
1341 buildVersion: Option.none(),
1342 outputDir: Option.some("release-test"),
1343 skipBuild: Option.some(false),
1344 keepStage: Option.some(false),
1345 signed: Option.some(false),
1346 verbose: Option.some(false),
1347 mockUpdates: Option.some(false),
1348 mockUpdateServerPort: Option.none(),
1349 wslPrebuild: Option.none(),
1350 }).pipe(
1351 Effect.provide(
1352 ConfigProvider.layer(
1353 ConfigProvider.fromEnv({
1354 env: {
1355 T3CODE_DESKTOP_SKIP_BUILD: "true",
1356 T3CODE_DESKTOP_KEEP_STAGE: "true",
1357 T3CODE_DESKTOP_SIGNED: "true",
1358 T3CODE_DESKTOP_VERBOSE: "true",
1359 T3CODE_DESKTOP_MOCK_UPDATES: "true",
1360 },
1361 }),
1362 ),
1363 ),
1364 );
1365​
1366 assert.equal(resolved.skipBuild, false);
1367 assert.equal(resolved.keepStage, false);
1368 assert.equal(resolved.signed, false);
1369 assert.equal(resolved.verbose, false);
1370 assert.equal(resolved.mockUpdates, false);
1371 }),
1372 );
1373});
1374​
1375// The self-containment check runs the packaged tree in a scratch directory. Its
1376// own node_modules holds the sidecar externals and must be ignored, but any
1377// node_modules *above* it would let Node's parent walk satisfy an import that is
1378// missing from the package, so the probe refuses to run in that case.
1379it("lists ancestor node_modules, nearest first, excluding the start directory", () => {
1380 assert.deepStrictEqual(ancestorNodeModulesPaths("C:\\tmp\\probe\\app", "\\"), [
1381 "C:\\tmp\\probe\\node_modules",
1382 "C:\\tmp\\node_modules",
1383 "C:\\node_modules",
1384 ]);
1385});
1386​
1387it("includes the filesystem root for posix paths", () => {
1388 assert.deepStrictEqual(ancestorNodeModulesPaths("/tmp/probe", "/"), [
1389 "/tmp/node_modules",
1390 "/node_modules",
1391 ]);
1392});
1393​
1394// A UNC root must keep its \\server\share prefix. Rebuilding it from segments
1395// produced relative paths, which fs.exists resolves against the build cwd, so
1396// the guard checked directories that do not exist and silently passed.
1397it("keeps the prefix of a UNC path instead of going relative", () => {
1398 const paths = ancestorNodeModulesPaths("\\\\server\\share\\tmp\\app", "\\");
1399 for (const candidate of paths) {
1400 assert.ok(candidate.startsWith("\\\\server\\share"), candidate);
1402 assert.deepStrictEqual(paths[0], "\\\\server\\share\\tmp\\node_modules");
1403});
1404​
1405it.effect("rebases packaged links into the isolated tree", () =>
1406 Effect.gen(function* () {
1407 const fs = yield* FileSystem.FileSystem;
1408 const path = yield* Path.Path;
1409 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3code-copy-symlinks-" });
1410 const source = path.join(root, "source");
1411 const destination = path.join(root, "destination");
1412 const packageDir = path.join(source, "node_modules/.pnpm/example@1/node_modules/example");
1413 const relativePackageLink = path.join(source, "node_modules/example-relative");
1414 const absolutePackageLink = path.join(source, "node_modules/example-absolute");
1415​
1416 yield* fs.makeDirectory(packageDir, { recursive: true });
1417 yield* fs.writeFileString(path.join(packageDir, "index.js"), "module.exports = true;\n");
1418 yield* fs.symlink(
1419 path.join(".pnpm", "example@1", "node_modules", "example"),
1420 relativePackageLink,
1421 );
1422 yield* fs.symlink(packageDir, absolutePackageLink);
1423​
1424 yield* copyDirectoryPreservingSymlinks(source, destination);
1425​
1426 const copiedPackage = path.join(
1427 destination,
1428 "node_modules/.pnpm/example@1/node_modules/example",
1429 );
1430 const resolvedCopiedPackage = yield* fs.realPath(copiedPackage);
1431 assert.equal(
1432 yield* fs.readLink(path.join(destination, "node_modules/example-relative")),
1433 copiedPackage,
1434 );
1435 assert.equal(
1436 yield* fs.readLink(path.join(destination, "node_modules/example-absolute")),
1437 copiedPackage,
1438 );
1439 assert.equal(
1440 yield* fs.realPath(path.join(destination, "node_modules/example-relative")),
1441 resolvedCopiedPackage,
1442 );
1443 assert.equal(
1444 yield* fs.realPath(path.join(destination, "node_modules/example-absolute")),
1445 resolvedCopiedPackage,
1446 );
1447 }).pipe(Effect.provide(NodeServices.layer)),
1449​
1450it("ignores trailing separators", () => {
1451 assert.deepStrictEqual(
1452 ancestorNodeModulesPaths("C:\\tmp\\probe\\app\\", "\\"),
1453 ancestorNodeModulesPaths("C:\\tmp\\probe\\app", "\\"),
1454 );
1455});