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

build-desktop-artifact.test.ts

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