Merge upstream/main (+212): codex Effect-service normalization wave

Catch up to pingdotgg/main (82a9bcc7), resolving 16 conflicts while
preserving the WSL parallel-backend feature set.

Upstream's codex wave normalized Effect services repo-wide: inlined
*Shape interfaces into Context.Service classes, converted errors to
Schema.TaggedErrorClass, switched to namespace imports, and split
make + layer. Our branch keeps DesktopBackendPool + a per-instance
factory (upstream's singleton DesktopBackendManager service does not
exist in this tree).

Resolutions:
- DesktopBackendManager.ts: kept ours (factory model; upstream's
  singleton rewrite does not apply). Re-deleted the superseded
  single-instance DesktopBackendOutputLog.ts and its test.
- DesktopObservability / DesktopBackendConfiguration /
  DesktopLocalEnvironmentAuth / DesktopApp / DesktopWindow /
  DesktopAppSettings: adopted upstream's normalized structure (inline
  service shapes, TaggedErrorClass, make + layer, namespace imports,
  DesktopShutdown module, OTLP tracing) while preserving our WSL
  additions (per-instance log factory, pool-based bearer auth, splash
  and handleBackendReady(httpBaseUrl), WSL settings methods).
- client-runtime EnvironmentRegistry: namespace imports + kept our
  reconcilePlatform / registerPlatform / networkStatus.
- web primary environment: adopted upstream's Schema error classes;
  kept PRIMARY_LOCAL_ENVIRONMENT_ID and the plural
  getLocalEnvironmentBootstraps path.
- Tests: applied the repo-wide *Shape to X["Service"] removal across
  desktop tests; converted singular getLocalEnvironmentBootstrap stubs
  to our plural form; refreshed DesktopAppSettings stubs with the WSL
  methods; restored our factory-based DesktopBackendManager test.

Verified: desktop + web + client-runtime typecheck clean; affected
desktop + web tests pass. The 15 remaining desktop test failures are
pre-existing Windows-only path-separator assertions (forward vs back
slash) and pass on the Linux CI.
This commit is contained in:
Josh Gratton committed 2026-06-21 11:52:55 -04:00
commit 206feb75de
690 files changed
+47246 -20818

No files matched your search

+178 -16
View File
@@ -4,12 +4,23 @@ import * as ConfigProvider from "effect/ConfigProvider";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Sink from "effect/Sink";
import * as Stream from "effect/Stream";
import { ChildProcessSpawner } from "effect/unstable/process";
import {
BuildCommandFailedError,
createStageWorkspaceConfig,
createStagePnpmConfig,
createBuildConfig,
DESKTOP_ASAR_UNPACK,
InvalidMacPasskeyRpDomainError,
InvalidMacPasskeyPublishableKeyError,
InvalidMockUpdateServerPortError,
isMacPasskeySigningConfigurationError,
LinuxIconResizeError,
MacPasskeySigningConfigurationResolutionError,
MissingMacPasskeyProvisioningProfileError,
renderMacPasskeyEntitlements,
resolveClerkPasskeyNativeArtifacts,
resolveMacPasskeySigningConfiguration,
@@ -22,11 +33,49 @@ import {
resolveGitHubPublishConfig,
resolveMockUpdateServerPort,
resolveMockUpdateServerUrl,
stageLinuxIconSize,
STAGE_INSTALL_ARGS,
} from "./build-desktop-artifact.ts";
import { BRAND_ASSET_PATHS } from "./lib/brand-assets.ts";
import { HostProcessArchitecture, HostProcessPlatform } from "@t3tools/shared/hostProcess";
function mockProcess(exitCode: number) {
return ChildProcessSpawner.makeHandle({
pid: ChildProcessSpawner.ProcessId(1),
exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(exitCode)),
isRunning: Effect.succeed(false),
kill: () => Effect.void,
unref: Effect.succeed(Effect.void),
stdin: Sink.drain,
stdout: Stream.empty,
stderr: Stream.empty,
all: Stream.empty,
getInputFd: () => Sink.drain,
getOutputFd: () => Stream.empty,
});
}
function iconResizeSpawnerLayer(
commands: Array<{ readonly command: string; readonly args: ReadonlyArray<string> }>,
exitCodes: ReadonlyArray<number>,
) {
let commandIndex = 0;
return Layer.succeed(
ChildProcessSpawner.ChildProcessSpawner,
ChildProcessSpawner.make((command) => {
const childProcess = command as unknown as {
readonly command: string;
readonly args: ReadonlyArray<string>;
};
commands.push({
command: childProcess.command,
args: childProcess.args,
});
return Effect.succeed(mockProcess(exitCodes[commandIndex++] ?? 0));
}),
);
}
it.layer(NodeServices.layer)("build-desktop-artifact", (it) => {
it("resolves the dedicated nightly updater channel from nightly versions", () => {
assert.equal(resolveDesktopUpdateChannel("0.0.17-nightly.20260413.42"), "nightly");
@@ -189,6 +238,46 @@ it.layer(NodeServices.layer)("build-desktop-artifact", (it) => {
assert.deepStrictEqual(DESKTOP_ASAR_UNPACK, ["node_modules/@ff-labs/fff-bin-*/**/*"]);
});
it.effect("preserves both Linux icon resize failures with structural context", () => {
const commands: Array<{ readonly command: string; readonly args: ReadonlyArray<string> }> = [];
return Effect.gen(function* () {
const error = yield* stageLinuxIconSize("source.png", "target.png", 512, false).pipe(
Effect.provide(iconResizeSpawnerLayer(commands, [1, 2])),
Effect.flip,
);
assert.instanceOf(error, LinuxIconResizeError);
assert.equal(error.operation, "resize");
assert.equal(error.iconSize, 512);
assert.equal(error.primaryTool, "magick");
assert.equal(error.fallbackTool, "convert");
assert.include(error.message, "512x512");
assert.include(error.message, "`magick`");
assert.include(error.message, "`convert`");
assert.notInclude(error.message, "non-zero exit code");
assert.instanceOf(error.cause, AggregateError);
const aggregateCause = error.cause as AggregateError;
assert.lengthOf(aggregateCause.errors, 2);
assert.strictEqual(aggregateCause.cause, aggregateCause.errors[0]);
assert.instanceOf(aggregateCause.errors[0], BuildCommandFailedError);
assert.instanceOf(aggregateCause.errors[1], BuildCommandFailedError);
const primaryError = aggregateCause.errors[0] as BuildCommandFailedError;
const fallbackError = aggregateCause.errors[1] as BuildCommandFailedError;
assert.equal(primaryError.command, "magick linux icon 512x512");
assert.equal(primaryError.exitCode, 1);
assert.include(primaryError.message, "magick linux icon");
assert.equal(fallbackError.command, "convert linux icon 512x512");
assert.equal(fallbackError.exitCode, 2);
assert.include(fallbackError.message, "convert linux icon");
assert.deepStrictEqual(
commands.map(({ command }) => command),
["magick", "convert"],
);
});
});
it("derives macOS passkey signing configuration from the Clerk publishable key", () => {
const configuration = resolveMacPasskeySigningConfiguration({
T3CODE_APPLE_TEAM_ID: "abc1234567",
@@ -224,23 +313,43 @@ it.layer(NodeServices.layer)("build-desktop-artifact", (it) => {
});
it("rejects incomplete macOS passkey signing configuration", () => {
assert.throws(
() =>
resolveMacPasskeySigningConfiguration({
T3CODE_APPLE_TEAM_ID: "ABC1234567",
T3CODE_CLERK_PASSKEY_RP_DOMAINS: "example.clerk.accounts.dev",
}),
/T3CODE_MACOS_PROVISIONING_PROFILE/u,
);
assert.throws(
() =>
resolveMacPasskeySigningConfiguration({
T3CODE_APPLE_TEAM_ID: "ABC1234567",
T3CODE_MACOS_PROVISIONING_PROFILE: "/tmp/t3code.provisionprofile",
T3CODE_CLERK_PASSKEY_RP_DOMAINS: "https://example.clerk.accounts.dev/path",
}),
/Invalid passkey RP domain/u,
const captureError = (env: Readonly<Record<string, string | undefined>>) => {
try {
resolveMacPasskeySigningConfiguration(env);
} catch (error) {
return error;
}
return assert.fail("Expected passkey signing configuration to fail.");
};
const missingProfileError = captureError({
T3CODE_APPLE_TEAM_ID: "ABC1234567",
T3CODE_CLERK_PASSKEY_RP_DOMAINS: "example.clerk.accounts.dev",
});
assert.instanceOf(missingProfileError, MissingMacPasskeyProvisioningProfileError);
assert.equal(
missingProfileError.message,
"T3CODE_MACOS_PROVISIONING_PROFILE must point to an Associated Domains provisioning profile.",
);
const unsafeDomain =
"https://domain-user:[email protected]/path?token=query-secret";
const invalidDomainError = captureError({
T3CODE_APPLE_TEAM_ID: "ABC1234567",
T3CODE_MACOS_PROVISIONING_PROFILE: "/tmp/t3code.provisionprofile",
T3CODE_CLERK_PASSKEY_RP_DOMAINS: unsafeDomain,
});
assert.instanceOf(invalidDomainError, InvalidMacPasskeyRpDomainError);
assert.equal(invalidDomainError.reason, "scheme-not-allowed");
assert.equal(invalidDomainError.inputLength, unsafeDomain.length);
assert.equal(invalidDomainError.message, "Invalid passkey RP domain (scheme-not-allowed).");
assert.notProperty(invalidDomainError, "domain");
assert.notProperty(invalidDomainError, "cause");
const serializedInvalidDomainError = JSON.stringify(invalidDomainError);
assert.notInclude(serializedInvalidDomainError, unsafeDomain);
assert.notInclude(serializedInvalidDomainError, "domain-user");
assert.notInclude(serializedInvalidDomainError, "domain-secret");
assert.notInclude(serializedInvalidDomainError, "query-secret");
assert.throws(
() =>
resolveMacPasskeySigningConfiguration({
@@ -250,6 +359,38 @@ it.layer(NodeServices.layer)("build-desktop-artifact", (it) => {
}),
/Invalid passkey RP domain/u,
);
const invalidPublishableKeyError = captureError({
T3CODE_APPLE_TEAM_ID: "ABC1234567",
T3CODE_MACOS_PROVISIONING_PROFILE: "/tmp/t3code.provisionprofile",
T3CODE_CLERK_PUBLISHABLE_KEY: "pk_test_%",
});
assert.instanceOf(invalidPublishableKeyError, InvalidMacPasskeyPublishableKeyError);
assert.ok(invalidPublishableKeyError.cause);
assert.equal(invalidPublishableKeyError.message, "T3CODE_CLERK_PUBLISHABLE_KEY is invalid.");
assert.notProperty(invalidPublishableKeyError, "publishableKey");
assert.notInclude(invalidPublishableKeyError.message, "pk_test_%");
});
it("preserves known passkey signing configuration errors at the build boundary", () => {
const decodingCause = new Error("publishable-key-decode-failed");
const knownError = new InvalidMacPasskeyPublishableKeyError({ cause: decodingCause });
const error = MacPasskeySigningConfigurationResolutionError.fromCause(knownError);
assert.strictEqual(error, knownError);
assert.instanceOf(error, InvalidMacPasskeyPublishableKeyError);
assert.strictEqual(error.cause, decodingCause);
assert.isTrue(isMacPasskeySigningConfigurationError(error));
});
it("wraps unknown passkey signing configuration defects without copying cause text", () => {
const secret = "pk_test_do-not-retain";
const cause = new Error(secret);
const error = MacPasskeySigningConfigurationResolutionError.fromCause(cause);
assert.instanceOf(error, MacPasskeySigningConfigurationResolutionError);
assert.strictEqual(error.cause, cause);
assert.equal(error.message, "Failed to resolve macOS passkey signing configuration.");
assert.notInclude(error.message, secret);
});
it.effect("adds passkey entitlements and both renderer protocols to signed macOS builds", () =>
@@ -330,6 +471,27 @@ it.layer(NodeServices.layer)("build-desktop-artifact", (it) => {
}),
);
it("classifies invalid configured ports with the decoder's number grammar", () => {
const cause = new Error("invalid configured port");
assert.equal(
InvalidMockUpdateServerPortError.fromConfigValue("0x10", cause).reason,
"not-numeric",
);
assert.equal(
InvalidMockUpdateServerPortError.fromConfigValue("12.5", cause).reason,
"not-integer",
);
assert.equal(
InvalidMockUpdateServerPortError.fromConfigValue("65536", cause).reason,
"out-of-range",
);
assert.strictEqual(
InvalidMockUpdateServerPortError.fromConfigValue("0x10", cause).cause,
cause,
);
});
it.effect("resolves default platform and architecture from host references", () =>
Effect.gen(function* () {
const resolved = yield* resolveBuildOptions({
+473 -97
View File
@@ -1,6 +1,6 @@
#!/usr/bin/env node
import { createRequire } from "node:module";
import * as NodeModule from "node:module";
import { fromYaml } from "@t3tools/shared/schemaYaml";
import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
@@ -18,7 +18,6 @@ import { resolveCatalogDependencies } from "./lib/resolve-catalog.ts";
import * as NodeRuntime from "@effect/platform-node/NodeRuntime";
import * as NodeServices from "@effect/platform-node/NodeServices";
import * as Config from "effect/Config";
import * as Data from "effect/Data";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
@@ -131,10 +130,255 @@ const getDefaultArch = Effect.fn("getDefaultArch")(function* (platform: typeof B
return yield* getDefaultBuildArch(platform, config);
});
class BuildScriptError extends Data.TaggedError("BuildScriptError")<{
readonly message: string;
readonly cause?: unknown;
}> {}
export class MacPasskeySigningConfigurationResolutionError extends Schema.TaggedErrorClass<MacPasskeySigningConfigurationResolutionError>()(
"MacPasskeySigningConfigurationResolutionError",
{
cause: Schema.Defect(),
},
) {
static fromCause(
cause: unknown,
): MacPasskeySigningConfigurationError | MacPasskeySigningConfigurationResolutionError {
return isMacPasskeySigningConfigurationError(cause)
? cause
: new MacPasskeySigningConfigurationResolutionError({ cause });
}
override get message(): string {
return "Failed to resolve macOS passkey signing configuration.";
}
}
export class ClerkPasskeyNativePackageMissingError extends Schema.TaggedErrorClass<ClerkPasskeyNativePackageMissingError>()(
"ClerkPasskeyNativePackageMissingError",
{
packageName: Schema.String,
binaryFileName: Schema.String,
packageEntryPath: Schema.String,
platform: BuildPlatform,
arch: BuildArch,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Clerk passkey native package is missing: ${this.packageName}`;
}
}
export class UnsupportedHostBuildPlatformError extends Schema.TaggedErrorClass<UnsupportedHostBuildPlatformError>()(
"UnsupportedHostBuildPlatformError",
{
hostPlatform: Schema.String,
},
) {
override get message(): string {
return `Unsupported host platform '${this.hostPlatform}'.`;
}
}
const InvalidMockUpdateServerPortReason = Schema.Literals([
"not-numeric",
"not-integer",
"out-of-range",
]);
export class InvalidMockUpdateServerPortError extends Schema.TaggedErrorClass<InvalidMockUpdateServerPortError>()(
"InvalidMockUpdateServerPortError",
{
reason: InvalidMockUpdateServerPortReason,
inputLength: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)),
cause: Schema.Defect(),
},
) {
override get message(): string {
return "Invalid mock update server port.";
}
static fromConfigValue(configuredPort: string, cause: unknown) {
return new InvalidMockUpdateServerPortError({
reason: invalidMockUpdateServerPortReason(configuredPort),
inputLength: configuredPort.length,
cause,
});
}
}
export class BuildCommandFailedError extends Schema.TaggedErrorClass<BuildCommandFailedError>()(
"BuildCommandFailedError",
{
command: Schema.String,
exitCode: Schema.Int,
stdoutTail: Schema.optionalKey(Schema.String),
stderrTail: Schema.optionalKey(Schema.String),
},
) {
override get message(): string {
const outputSections = [
`Command: ${this.command}`,
formatOutputSection("stdout", this.stdoutTail ?? ""),
formatOutputSection("stderr", this.stderrTail ?? ""),
].filter((section): section is string => section !== undefined);
const outputSuffix = outputSections.length > 0 ? `\n\n${outputSections.join("\n\n")}` : "";
return `Command exited with non-zero exit code (${this.exitCode})${outputSuffix}`;
}
}
const desktopIconPlatformNames = {
mac: "macOS",
linux: "Linux",
win: "Windows",
} satisfies Record<typeof BuildPlatform.Type, string>;
export class DesktopIconSourceMissingError extends Schema.TaggedErrorClass<DesktopIconSourceMissingError>()(
"DesktopIconSourceMissingError",
{
platform: BuildPlatform,
sourcePath: Schema.String,
},
) {
override get message(): string {
return `Desktop ${desktopIconPlatformNames[this.platform]} icon source is missing at ${this.sourcePath}`;
}
}
export class BundledClientAssetsMissingError extends Schema.TaggedErrorClass<BundledClientAssetsMissingError>()(
"BundledClientAssetsMissingError",
{
indexPath: Schema.String,
missingFiles: Schema.Array(Schema.String),
},
) {
override get message(): string {
const preview = this.missingFiles.slice(0, 6).join(", ");
const suffix = this.missingFiles.length > 6 ? ` (+${this.missingFiles.length - 6} more)` : "";
return `Bundled client references missing files in ${this.indexPath}: ${preview}${suffix}. Rebuild web/server artifacts.`;
}
}
export class UnsupportedDesktopBuildPlatformError extends Schema.TaggedErrorClass<UnsupportedDesktopBuildPlatformError>()(
"UnsupportedDesktopBuildPlatformError",
{
platform: Schema.String,
},
) {
override get message(): string {
return `Unsupported platform '${this.platform}'.`;
}
}
const dependencyResolutionDescriptions = {
"server-production": "production dependencies",
"workspace-overrides": "overrides",
"desktop-runtime": "desktop runtime dependencies",
} as const;
const DependencyResolutionKind = Schema.Literals([
"server-production",
"workspace-overrides",
"desktop-runtime",
]);
export class DesktopBuildDependencyResolutionError extends Schema.TaggedErrorClass<DesktopBuildDependencyResolutionError>()(
"DesktopBuildDependencyResolutionError",
{
kind: DependencyResolutionKind,
manifestPath: Schema.String,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Could not resolve ${dependencyResolutionDescriptions[this.kind]} from ${this.manifestPath}.`;
}
}
export class MissingServerProductionDependenciesError extends Schema.TaggedErrorClass<MissingServerProductionDependenciesError>()(
"MissingServerProductionDependenciesError",
{
manifestPath: Schema.String,
},
) {
override get message(): string {
return `Could not resolve production dependencies from ${this.manifestPath}.`;
}
}
const DesktopBuildInputArtifact = Schema.Literals([
"desktop-dist",
"desktop-resources",
"server-dist",
"bundled-server-client",
]);
type DesktopBuildInputArtifact = typeof DesktopBuildInputArtifact.Type;
const desktopBuildInputArtifactNames = {
"desktop-dist": "desktopDist",
"desktop-resources": "desktopResources",
"server-dist": "serverDist",
"bundled-server-client": "bundled server client",
} satisfies Record<DesktopBuildInputArtifact, string>;
export class MissingDesktopBuildInputError extends Schema.TaggedErrorClass<MissingDesktopBuildInputError>()(
"MissingDesktopBuildInputError",
{
artifact: DesktopBuildInputArtifact,
artifactPath: Schema.String,
buildCommand: Schema.Literal("vp run build:desktop"),
},
) {
override get message(): string {
return `Missing ${desktopBuildInputArtifactNames[this.artifact]} at ${this.artifactPath}. Run '${this.buildCommand}' first.`;
}
}
export class MacProvisioningProfileNotFoundError extends Schema.TaggedErrorClass<MacProvisioningProfileNotFoundError>()(
"MacProvisioningProfileNotFoundError",
{
provisioningProfilePath: Schema.String,
},
) {
override get message(): string {
return `macOS provisioning profile not found: ${this.provisioningProfilePath}`;
}
}
export class DesktopBuildDistDirectoryMissingError extends Schema.TaggedErrorClass<DesktopBuildDistDirectoryMissingError>()(
"DesktopBuildDistDirectoryMissingError",
{
distPath: Schema.String,
platform: BuildPlatform,
arch: BuildArch,
},
) {
override get message(): string {
return `Build completed but dist directory was not found at ${this.distPath}`;
}
}
export class DesktopBuildNoArtifactsProducedError extends Schema.TaggedErrorClass<DesktopBuildNoArtifactsProducedError>()(
"DesktopBuildNoArtifactsProducedError",
{
distPath: Schema.String,
platform: BuildPlatform,
arch: BuildArch,
},
) {
override get message(): string {
return `Build completed but no files were produced in ${this.distPath}`;
}
}
export class LinuxIconResizeError extends Schema.TaggedErrorClass<LinuxIconResizeError>()(
"LinuxIconResizeError",
{
operation: Schema.Literal("resize"),
iconSize: Schema.Int,
primaryTool: Schema.Literal("magick"),
fallbackTool: Schema.Literal("convert"),
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Failed to ${this.operation} the Linux desktop icon to ${this.iconSize}x${this.iconSize} with \`${this.primaryTool}\` or \`${this.fallbackTool}\`. Install ImageMagick so either tool is available.`;
}
}
const collectStreamAsString = <E>(stream: Stream.Stream<Uint8Array, E>): Effect.Effect<string, E> =>
stream.pipe(
@@ -312,26 +556,128 @@ export interface MacPasskeySigningConfiguration {
readonly provisioningProfilePath: string;
}
export const InvalidMacPasskeyRpDomainReason = Schema.Literals([
"empty",
"scheme-not-allowed",
"parse-failed",
"credentials-not-allowed",
"port-not-allowed",
"path-not-allowed",
"query-not-allowed",
"fragment-not-allowed",
"hostname-mismatch",
]);
export type InvalidMacPasskeyRpDomainReason = typeof InvalidMacPasskeyRpDomainReason.Type;
export class InvalidMacPasskeyRpDomainError extends Schema.TaggedErrorClass<InvalidMacPasskeyRpDomainError>()(
"InvalidMacPasskeyRpDomainError",
{
reason: InvalidMacPasskeyRpDomainReason,
inputLength: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)),
cause: Schema.optionalKey(Schema.Defect()),
},
) {
override get message(): string {
return `Invalid passkey RP domain (${this.reason}).`;
}
}
export class InvalidAppleTeamIdError extends Schema.TaggedErrorClass<InvalidAppleTeamIdError>()(
"InvalidAppleTeamIdError",
{
teamId: Schema.String,
},
) {
override get message(): string {
return `T3CODE_APPLE_TEAM_ID '${this.teamId}' must be a 10-character Apple Developer Team ID.`;
}
}
export class MissingMacPasskeyProvisioningProfileError extends Schema.TaggedErrorClass<MissingMacPasskeyProvisioningProfileError>()(
"MissingMacPasskeyProvisioningProfileError",
{},
) {
override get message(): string {
return "T3CODE_MACOS_PROVISIONING_PROFILE must point to an Associated Domains provisioning profile.";
}
}
export class MissingMacPasskeyDomainConfigurationError extends Schema.TaggedErrorClass<MissingMacPasskeyDomainConfigurationError>()(
"MissingMacPasskeyDomainConfigurationError",
{},
) {
override get message(): string {
return "T3CODE_CLERK_PUBLISHABLE_KEY or T3CODE_CLERK_PASSKEY_RP_DOMAINS is required for signed macOS passkey builds.";
}
}
export class InvalidMacPasskeyPublishableKeyError extends Schema.TaggedErrorClass<InvalidMacPasskeyPublishableKeyError>()(
"InvalidMacPasskeyPublishableKeyError",
{
cause: Schema.Defect(),
},
) {
override get message(): string {
return "T3CODE_CLERK_PUBLISHABLE_KEY is invalid.";
}
}
export class MissingMacPasskeyRpDomainError extends Schema.TaggedErrorClass<MissingMacPasskeyRpDomainError>()(
"MissingMacPasskeyRpDomainError",
{},
) {
override get message(): string {
return "At least one Clerk passkey RP domain is required.";
}
}
export const MacPasskeySigningConfigurationError = Schema.Union([
InvalidMacPasskeyRpDomainError,
InvalidAppleTeamIdError,
MissingMacPasskeyProvisioningProfileError,
MissingMacPasskeyDomainConfigurationError,
InvalidMacPasskeyPublishableKeyError,
MissingMacPasskeyRpDomainError,
]);
export type MacPasskeySigningConfigurationError = typeof MacPasskeySigningConfigurationError.Type;
export const isMacPasskeySigningConfigurationError = Schema.is(MacPasskeySigningConfigurationError);
function normalizePasskeyRpDomain(value: string): string {
const normalized = value.trim().toLowerCase();
const inputLength = value.length;
if (normalized.length === 0) {
throw new InvalidMacPasskeyRpDomainError({ reason: "empty", inputLength });
}
if (/^[a-z][a-z\d+.-]*:\/\//u.test(normalized)) {
throw new InvalidMacPasskeyRpDomainError({
reason: "scheme-not-allowed",
inputLength,
});
}
let parsed: URL;
try {
parsed = new URL(`https://${normalized}`);
} catch {
throw new Error(`Invalid passkey RP domain: ${value}`);
} catch (cause) {
throw new InvalidMacPasskeyRpDomainError({ reason: "parse-failed", inputLength, cause });
}
if (
normalized.length === 0 ||
parsed.host !== normalized ||
parsed.username.length > 0 ||
parsed.password.length > 0 ||
parsed.port.length > 0 ||
parsed.pathname !== "/" ||
parsed.search.length > 0 ||
parsed.hash.length > 0
) {
throw new Error(`Invalid passkey RP domain: ${value}`);
let reason: InvalidMacPasskeyRpDomainReason | undefined;
if (parsed.username.length > 0 || parsed.password.length > 0) {
reason = "credentials-not-allowed";
} else if (parsed.port.length > 0) {
reason = "port-not-allowed";
} else if (parsed.pathname !== "/") {
reason = "path-not-allowed";
} else if (parsed.search.length > 0) {
reason = "query-not-allowed";
} else if (parsed.hash.length > 0) {
reason = "fragment-not-allowed";
} else if (parsed.host !== normalized) {
reason = "hostname-mismatch";
}
if (reason) {
throw new InvalidMacPasskeyRpDomainError({ reason, inputLength });
}
return parsed.hostname;
@@ -342,14 +688,12 @@ export function resolveMacPasskeySigningConfiguration(
): MacPasskeySigningConfiguration {
const teamId = env.T3CODE_APPLE_TEAM_ID?.trim().toUpperCase() ?? "";
if (!APPLE_TEAM_ID_PATTERN.test(teamId)) {
throw new Error("T3CODE_APPLE_TEAM_ID must be a 10-character Apple Developer Team ID.");
throw new InvalidAppleTeamIdError({ teamId });
}
const provisioningProfilePath = env.T3CODE_MACOS_PROVISIONING_PROFILE?.trim() ?? "";
if (provisioningProfilePath.length === 0) {
throw new Error(
"T3CODE_MACOS_PROVISIONING_PROFILE must point to an Associated Domains provisioning profile.",
);
throw new MissingMacPasskeyProvisioningProfileError();
}
const configuredRpDomains = env.T3CODE_CLERK_PASSKEY_RP_DOMAINS?.trim();
@@ -359,18 +703,20 @@ export function resolveMacPasskeySigningConfiguration(
} else {
const publishableKey = env.T3CODE_CLERK_PUBLISHABLE_KEY?.trim();
if (!publishableKey) {
throw new Error(
"T3CODE_CLERK_PUBLISHABLE_KEY or T3CODE_CLERK_PASSKEY_RP_DOMAINS is required for signed macOS passkey builds.",
);
throw new MissingMacPasskeyDomainConfigurationError();
}
rpDomains = [
normalizePasskeyRpDomain(clerkFrontendApiHostnameFromPublishableKey(publishableKey)),
];
let hostname: string;
try {
hostname = clerkFrontendApiHostnameFromPublishableKey(publishableKey);
} catch (cause) {
throw new InvalidMacPasskeyPublishableKeyError({ cause });
}
rpDomains = [normalizePasskeyRpDomain(hostname)];
}
const uniqueRpDomains = [...new Set(rpDomains)];
if (uniqueRpDomains.length === 0) {
throw new Error("At least one Clerk passkey RP domain is required.");
throw new MissingMacPasskeyRpDomainError();
}
return {
@@ -488,14 +834,18 @@ const stageClerkPasskeyNativeBinaries = Effect.fn("stageClerkPasskeyNativeBinari
path.join(stageAppDir, "node_modules", "@clerk", "electron-passkeys", "index.js"),
);
const packageDir = path.dirname(packageEntryPath);
const packageRequire = createRequire(packageEntryPath);
const packageRequire = NodeModule.createRequire(packageEntryPath);
for (const artifact of resolveClerkPasskeyNativeArtifacts(platform, arch)) {
const sourcePath = yield* Effect.try({
try: () => packageRequire.resolve(artifact.packageName),
catch: (cause) =>
new BuildScriptError({
message: `Clerk passkey native package is missing: ${artifact.packageName}`,
new ClerkPasskeyNativePackageMissingError({
packageName: artifact.packageName,
binaryFileName: artifact.binaryFileName,
packageEntryPath,
platform,
arch,
cause,
}),
});
@@ -590,6 +940,18 @@ const MockUpdateServerPortSchema = Schema.NumberFromString.check(
);
const decodeMockUpdateServerPort = Schema.decodeUnknownEffect(MockUpdateServerPortSchema);
function invalidMockUpdateServerPortReason(
configuredPort: string,
): typeof InvalidMockUpdateServerPortReason.Type {
const parsed = Number(configuredPort);
if (!Number.isFinite(parsed)) return "not-numeric";
if (!Number.isInteger(parsed)) return "not-integer";
if (parsed < 1 || parsed > 65535) return "out-of-range";
// This mapper is only called after schema decoding failed. An otherwise
// valid integer therefore used a representation the decoder did not accept.
return "not-numeric";
}
const resolveBooleanFlag = (flag: Option.Option<boolean>, envValue: boolean) =>
Option.getOrElse(flag, () => envValue);
const mergeOptions = <A>(a: Option.Option<A>, b: Option.Option<A>, defaultValue: A) =>
@@ -621,9 +983,7 @@ export const resolveBuildOptions = Effect.fn("resolveBuildOptions")(function* (
);
if (!platform) {
return yield* new BuildScriptError({
message: `Unsupported host platform '${hostPlatform}'.`,
});
return yield* new UnsupportedHostBuildPlatformError({ hostPlatform });
}
const target = mergeOptions(input.target, env.target, PLATFORM_CONFIG[platform].defaultTarget);
@@ -644,17 +1004,16 @@ export const resolveBuildOptions = Effect.fn("resolveBuildOptions")(function* (
const verbose = resolveBooleanFlag(input.verbose, env.verbose);
const mockUpdates = resolveBooleanFlag(input.mockUpdates, env.mockUpdates);
const configuredMockUpdateServerPort = Option.getOrUndefined(env.mockUpdateServerPort);
const mockUpdateServerPort =
Option.getOrUndefined(input.mockUpdateServerPort) ??
(yield* resolveMockUpdateServerPort(Option.getOrUndefined(env.mockUpdateServerPort)).pipe(
Effect.mapError(
(cause) =>
new BuildScriptError({
message: "Invalid mock update server port.",
cause,
}),
),
));
(configuredMockUpdateServerPort === undefined
? undefined
: yield* resolveMockUpdateServerPort(configuredMockUpdateServerPort).pipe(
Effect.mapError((cause) =>
InvalidMockUpdateServerPortError.fromConfigValue(configuredMockUpdateServerPort, cause),
),
));
const wslPrebuild =
Option.getOrUndefined(input.wslPrebuild) ?? Option.getOrUndefined(env.wslPrebuild);
@@ -678,7 +1037,7 @@ export const resolveBuildOptions = Effect.fn("resolveBuildOptions")(function* (
const runCommand = Effect.fn("runCommand")(function* (
command: ChildProcess.Command,
options: {
readonly label?: string;
readonly label: string;
readonly verbose: boolean;
},
) {
@@ -694,14 +1053,11 @@ const runCommand = Effect.fn("runCommand")(function* (
);
if (exitCode !== 0) {
const outputSections = [
options.label ? `Command: ${options.label}` : undefined,
formatOutputSection("stdout", stdout),
formatOutputSection("stderr", stderr),
].filter((section): section is string => section !== undefined);
const outputSuffix = outputSections.length > 0 ? `\n\n${outputSections.join("\n\n")}` : "";
return yield* new BuildScriptError({
message: `Command exited with non-zero exit code (${exitCode})${outputSuffix}`,
return yield* new BuildCommandFailedError({
command: options.label,
exitCode,
...(stdout.trim() ? { stdoutTail: stdout } : {}),
...(stderr.trim() ? { stderrTail: stderr } : {}),
});
}
});
@@ -748,8 +1104,9 @@ function stageMacIcons(stageResourcesDir: string, sourcePng: string, verbose: bo
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
if (!(yield* fs.exists(sourcePng))) {
return yield* new BuildScriptError({
message: `Desktop macOS icon source is missing at ${sourcePng}`,
return yield* new DesktopIconSourceMissingError({
platform: "mac",
sourcePath: sourcePng,
});
}
@@ -774,8 +1131,9 @@ function stageLinuxIcons(stageResourcesDir: string, sourcePng: string, verbose:
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
if (!(yield* fs.exists(sourcePng))) {
return yield* new BuildScriptError({
message: `Desktop Linux icon source is missing at ${sourcePng}`,
return yield* new DesktopIconSourceMissingError({
platform: "linux",
sourcePath: sourcePng,
});
}
@@ -795,7 +1153,7 @@ function stageLinuxIcons(stageResourcesDir: string, sourcePng: string, verbose:
});
}
function stageLinuxIconSize(
export function stageLinuxIconSize(
sourcePng: string,
targetPng: string,
iconSize: number,
@@ -808,13 +1166,20 @@ function stageLinuxIconSize(
);
return resize("magick").pipe(
Effect.catch(() =>
Effect.catch((primaryCause) =>
resize("convert").pipe(
Effect.mapError(
() =>
new BuildScriptError({
message:
"ImageMagick is required to generate Linux desktop icon sizes. Install ImageMagick so either `magick` or `convert` is available.",
(fallbackCause) =>
new LinuxIconResizeError({
operation: "resize",
iconSize,
primaryTool: "magick",
fallbackTool: "convert",
cause: new AggregateError(
[primaryCause, fallbackCause],
"Both Linux icon resize tool attempts failed.",
{ cause: primaryCause },
),
}),
),
),
@@ -827,8 +1192,9 @@ function stageWindowsIcons(stageResourcesDir: string, sourceIco: string) {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
if (!(yield* fs.exists(sourceIco))) {
return yield* new BuildScriptError({
message: `Desktop Windows icon source is missing at ${sourceIco}`,
return yield* new DesktopIconSourceMissingError({
platform: "win",
sourcePath: sourceIco,
});
}
@@ -865,10 +1231,9 @@ function validateBundledClientAssets(clientDir: string) {
}
if (missing.length > 0) {
const preview = missing.slice(0, 6).join(", ");
const suffix = missing.length > 6 ? ` (+${missing.length - 6} more)` : "";
return yield* new BuildScriptError({
message: `Bundled client references missing files in ${indexPath}: ${preview}${suffix}. Rebuild web/server artifacts.`,
return yield* new BundledClientAssetsMissingError({
indexPath,
missingFiles: missing,
});
}
});
@@ -1152,8 +1517,8 @@ const buildDesktopArtifact = Effect.fn("buildDesktopArtifact")(function* (
const platformConfig = PLATFORM_CONFIG[options.platform];
if (!platformConfig) {
return yield* new BuildScriptError({
message: `Unsupported platform '${options.platform}'.`,
return yield* new UnsupportedDesktopBuildPlatformError({
platform: options.platform,
});
}
@@ -1161,16 +1526,17 @@ const buildDesktopArtifact = Effect.fn("buildDesktopArtifact")(function* (
const serverDependencies = serverPackageJson.dependencies;
if (!serverDependencies || Object.keys(serverDependencies).length === 0) {
return yield* new BuildScriptError({
message: "Could not resolve production dependencies from apps/server/package.json.",
return yield* new MissingServerProductionDependenciesError({
manifestPath: "apps/server/package.json",
});
}
const resolvedOverrides = yield* Effect.try({
try: () => resolveCatalogDependencies(workspaceOverrides, workspaceCatalog, "apps/desktop"),
catch: (cause) =>
new BuildScriptError({
message: "Could not resolve overrides from pnpm-workspace.yaml.",
new DesktopBuildDependencyResolutionError({
kind: "workspace-overrides",
manifestPath: "pnpm-workspace.yaml",
cause,
}),
});
@@ -1178,16 +1544,18 @@ const buildDesktopArtifact = Effect.fn("buildDesktopArtifact")(function* (
const resolvedServerDependencies = yield* Effect.try({
try: () => resolveCatalogDependencies(serverDependencies, workspaceCatalog, "apps/server"),
catch: (cause) =>
new BuildScriptError({
message: "Could not resolve production dependencies from apps/server/package.json.",
new DesktopBuildDependencyResolutionError({
kind: "server-production",
manifestPath: "apps/server/package.json",
cause,
}),
});
const resolvedDesktopRuntimeDependencies = yield* Effect.try({
try: () => resolveDesktopRuntimeDependencies(desktopPackageJson.dependencies, workspaceCatalog),
catch: (cause) =>
new BuildScriptError({
message: "Could not resolve desktop runtime dependencies from apps/desktop/package.json.",
new DesktopBuildDependencyResolutionError({
kind: "desktop-runtime",
manifestPath: "apps/desktop/package.json",
cause,
}),
});
@@ -1221,17 +1589,25 @@ const buildDesktopArtifact = Effect.fn("buildDesktopArtifact")(function* (
);
}
for (const [label, dir] of Object.entries(distDirs)) {
if (!(yield* fs.exists(dir))) {
return yield* new BuildScriptError({
message: `Missing ${label} at ${dir}. Run 'vp run build:desktop' first.`,
const requiredBuildInputs = [
{ artifact: "desktop-dist", artifactPath: distDirs.desktopDist },
{ artifact: "desktop-resources", artifactPath: distDirs.desktopResources },
{ artifact: "server-dist", artifactPath: distDirs.serverDist },
] as const;
for (const input of requiredBuildInputs) {
if (!(yield* fs.exists(input.artifactPath))) {
return yield* new MissingDesktopBuildInputError({
...input,
buildCommand: "vp run build:desktop",
});
}
}
if (!(yield* fs.exists(bundledClientEntry))) {
return yield* new BuildScriptError({
message: `Missing bundled server client at ${bundledClientEntry}. Run 'vp run build:desktop' first.`,
return yield* new MissingDesktopBuildInputError({
artifact: "bundled-server-client",
artifactPath: bundledClientEntry,
buildCommand: "vp run build:desktop",
});
}
@@ -1263,11 +1639,7 @@ const buildDesktopArtifact = Effect.fn("buildDesktopArtifact")(function* (
options.platform === "mac" && options.signed
? yield* Effect.try({
try: () => resolveMacPasskeySigningConfiguration(loadRepoEnv({ repoRoot })),
catch: (cause) =>
new BuildScriptError({
message: cause instanceof Error ? cause.message : String(cause),
cause,
}),
catch: MacPasskeySigningConfigurationResolutionError.fromCause,
})
: undefined;
const macPasskeySigning = configuredMacPasskeySigning
@@ -1284,8 +1656,8 @@ const buildDesktopArtifact = Effect.fn("buildDesktopArtifact")(function* (
: undefined;
if (macPasskeySigning && macEntitlementsPath) {
if (!(yield* fs.exists(macPasskeySigning.provisioningProfilePath))) {
return yield* new BuildScriptError({
message: `macOS provisioning profile not found: ${macPasskeySigning.provisioningProfilePath}`,
return yield* new MacProvisioningProfileNotFoundError({
provisioningProfilePath: macPasskeySigning.provisioningProfilePath,
});
}
yield* fs.writeFileString(macEntitlementsPath, renderMacPasskeyEntitlements(macPasskeySigning));
@@ -1441,8 +1813,10 @@ const buildDesktopArtifact = Effect.fn("buildDesktopArtifact")(function* (
const stageDistDir = path.join(stageAppDir, "dist");
if (!(yield* fs.exists(stageDistDir))) {
return yield* new BuildScriptError({
message: `Build completed but dist directory was not found at ${stageDistDir}`,
return yield* new DesktopBuildDistDirectoryMissingError({
distPath: stageDistDir,
platform: options.platform,
arch: options.arch,
});
}
@@ -1461,8 +1835,10 @@ const buildDesktopArtifact = Effect.fn("buildDesktopArtifact")(function* (
}
if (copiedArtifacts.length === 0) {
return yield* new BuildScriptError({
message: `Build completed but no files were produced in ${stageDistDir}`,
return yield* new DesktopBuildNoArtifactsProducedError({
distPath: stageDistDir,
platform: options.platform,
arch: options.arch,
});
}
+206 -11
View File
@@ -1,8 +1,16 @@
import * as NodeServices from "@effect/platform-node/NodeServices";
import * as NodeOS from "node:os";
import * as NetService from "@t3tools/shared/Net";
import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
import { assert, describe, it } from "@effect/vitest";
import * as ConfigProvider from "effect/ConfigProvider";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Path from "effect/Path";
import * as PlatformError from "effect/PlatformError";
import * as Sink from "effect/Sink";
import * as Stream from "effect/Stream";
import { ChildProcessSpawner } from "effect/unstable/process";
import {
checkPortAvailabilityOnHosts,
@@ -11,8 +19,49 @@ import {
getDevRunnerModeArgs,
resolveModePortOffsets,
resolveOffset,
runDevRunnerWithInput,
} from "./dev-runner.ts";
const emptyConfigLayer = ConfigProvider.layer(ConfigProvider.fromEnv({ env: {} }));
const netServiceLayer = Layer.succeed(NetService.NetService, {
canListenOnHost: () => Effect.succeed(true),
isPortAvailableOnLoopback: () => Effect.succeed(true),
reserveLoopbackPort: () => Effect.succeed(49_152),
findAvailablePort: (port) => Effect.succeed(port),
});
function mockProcess(exit: number | PlatformError.PlatformError) {
return ChildProcessSpawner.makeHandle({
pid: ChildProcessSpawner.ProcessId(1),
exitCode:
typeof exit === "number"
? Effect.succeed(ChildProcessSpawner.ExitCode(exit))
: Effect.fail(exit),
isRunning: Effect.succeed(false),
kill: () => Effect.void,
unref: Effect.succeed(Effect.void),
stdin: Sink.drain,
stdout: Stream.empty,
stderr: Stream.empty,
all: Stream.empty,
getInputFd: () => Sink.drain,
getOutputFd: () => Stream.empty,
});
}
const devServerInput = {
mode: "dev:server",
t3Home: "/tmp/t3code-dev-runner",
noBrowser: undefined,
autoBootstrapProjectFromCwd: undefined,
logWebSocketEvents: undefined,
host: undefined,
port: 13_773,
devUrl: undefined,
dryRun: false,
runArgs: ["--inspect", "secret-token-value"],
} as const;
it.layer(NodeServices.layer)("dev-runner", (it) => {
describe("getDevRunnerModeArgs", () => {
it.effect("lets Vite+ honor the desktop dev task graph", () =>
@@ -42,8 +91,8 @@ it.layer(NodeServices.layer)("dev-runner", (it) => {
describe("resolveOffset", () => {
it.effect("uses explicit T3CODE_PORT_OFFSET when provided", () =>
Effect.sync(() => {
const result = resolveOffset({ portOffset: 12, devInstance: undefined });
Effect.gen(function* () {
const result = yield* resolveOffset({ portOffset: 12, devInstance: undefined });
assert.deepStrictEqual(result, {
offset: 12,
source: "T3CODE_PORT_OFFSET=12",
@@ -52,23 +101,27 @@ it.layer(NodeServices.layer)("dev-runner", (it) => {
);
it.effect("hashes non-numeric instance values", () =>
Effect.sync(() => {
const result = resolveOffset({ portOffset: undefined, devInstance: "feature-branch" });
Effect.gen(function* () {
const result = yield* resolveOffset({
portOffset: undefined,
devInstance: "feature-branch",
});
assert.ok(result.offset >= 1);
assert.ok(result.offset <= 3000);
}),
);
it.effect("throws for negative port offset", () =>
it.effect("returns structured context for a negative port offset", () =>
Effect.gen(function* () {
const error = yield* Effect.flip(
Effect.try({
try: () => resolveOffset({ portOffset: -1, devInstance: undefined }),
catch: (cause) => String(cause),
}),
const error = yield* resolveOffset({ portOffset: -1, devInstance: undefined }).pipe(
Effect.flip,
);
assert.ok(error.includes("Invalid T3CODE_PORT_OFFSET"));
assert.equal(error._tag, "DevRunnerInvalidPortOffsetError");
assert.equal(error.configKey, "T3CODE_PORT_OFFSET");
assert.equal(error.portOffset, -1);
assert.equal(error.minimum, 0);
assert.ok(!("cause" in error));
}),
);
});
@@ -289,6 +342,28 @@ it.layer(NodeServices.layer)("dev-runner", (it) => {
assert.equal(offset, 59_802);
}),
);
it.effect("reports the exhausted range and required port set", () =>
Effect.gen(function* () {
const error = yield* findFirstAvailableOffset({
startOffset: 51_763,
requireServerPort: true,
requireWebPort: false,
checkPortAvailability: () => Effect.succeed(true),
}).pipe(Effect.flip);
if (error._tag !== "DevRunnerPortExhaustedError") {
assert.fail(`Unexpected error: ${error._tag}`);
}
assert.equal(error.startOffset, 51_763);
assert.equal(error.requireServerPort, true);
assert.equal(error.requireWebPort, false);
assert.equal(error.baseServerPort, 13_773);
assert.equal(error.baseWebPort, 5_733);
assert.equal(error.maximumPort, 65_535);
assert.ok(!("cause" in error));
}),
);
});
describe("checkPortAvailabilityOnHosts", () => {
@@ -395,4 +470,124 @@ it.layer(NodeServices.layer)("dev-runner", (it) => {
}),
);
});
describe("runDevRunnerWithInput", () => {
it.effect("preserves invalid configuration as the exact cause", () =>
Effect.gen(function* () {
const error = yield* runDevRunnerWithInput({ ...devServerInput, dryRun: true }).pipe(
Effect.provide(
Layer.merge(
netServiceLayer,
ConfigProvider.layer(
ConfigProvider.fromEnv({ env: { T3CODE_PORT_OFFSET: "not-an-integer" } }),
),
),
),
Effect.flip,
);
if (error._tag !== "DevRunnerConfigurationError") {
assert.fail(`Unexpected error: ${error._tag}`);
}
assert.deepStrictEqual(error.configKeys, ["T3CODE_PORT_OFFSET", "T3CODE_DEV_INSTANCE"]);
assert.ok(error.cause !== undefined);
assert.ok(!error.message.includes(String((error.cause as Error).message)));
}),
);
it.effect("preserves process spawn context and the exact platform cause", () => {
const cause = PlatformError.systemError({
_tag: "NotFound",
module: "ChildProcess",
method: "spawn",
description: "vp was not found",
});
const spawnerLayer = Layer.succeed(
ChildProcessSpawner.ChildProcessSpawner,
ChildProcessSpawner.make(() => Effect.fail(cause)),
);
return Effect.gen(function* () {
const error = yield* runDevRunnerWithInput(devServerInput).pipe(
Effect.provide(Layer.mergeAll(emptyConfigLayer, netServiceLayer, spawnerLayer)),
Effect.provideService(HostProcessPlatform, "linux"),
Effect.flip,
);
if (error._tag !== "DevRunnerProcessError") {
assert.fail(`Unexpected error: ${error._tag}`);
}
assert.equal(error.operation, "spawn");
assert.equal(error.mode, "dev:server");
assert.equal(error.executable, "vp");
assert.equal(error.argumentCount, 5);
assert.equal(error.shell, false);
assert.equal(error.cause, cause);
assert.ok(!error.message.includes(cause.message));
assert.notProperty(error, "args");
assert.notInclude(error.message, "secret-token-value");
});
});
it.effect("reports non-zero exits without manufacturing a cause", () => {
const spawnerLayer = Layer.succeed(
ChildProcessSpawner.ChildProcessSpawner,
ChildProcessSpawner.make(() => Effect.succeed(mockProcess(17))),
);
return Effect.gen(function* () {
const error = yield* runDevRunnerWithInput(devServerInput).pipe(
Effect.provide(Layer.mergeAll(emptyConfigLayer, netServiceLayer, spawnerLayer)),
Effect.provideService(HostProcessPlatform, "linux"),
Effect.flip,
);
if (error._tag !== "DevRunnerProcessExitError") {
assert.fail(`Unexpected error: ${error._tag}`);
}
assert.equal(error.mode, "dev:server");
assert.equal(error.executable, "vp");
assert.equal(error.argumentCount, 5);
assert.equal(error.shell, false);
assert.equal(error.exitCode, 17);
assert.ok(!("cause" in error));
assert.notProperty(error, "args");
assert.notInclude(error.message, "secret-token-value");
});
});
it.effect("preserves wait-for-exit failures as the exact cause", () => {
const cause = PlatformError.systemError({
_tag: "Unknown",
module: "ChildProcess",
method: "exitCode",
description: "process status became unavailable",
});
const spawnerLayer = Layer.succeed(
ChildProcessSpawner.ChildProcessSpawner,
ChildProcessSpawner.make(() => Effect.succeed(mockProcess(cause))),
);
return Effect.gen(function* () {
const error = yield* runDevRunnerWithInput(devServerInput).pipe(
Effect.provide(Layer.mergeAll(emptyConfigLayer, netServiceLayer, spawnerLayer)),
Effect.provideService(HostProcessPlatform, "linux"),
Effect.flip,
);
if (error._tag !== "DevRunnerProcessError") {
assert.fail(`Unexpected error: ${error._tag}`);
}
assert.equal(error.operation, "wait-for-exit");
assert.equal(error.mode, "dev:server");
assert.equal(error.executable, "vp");
assert.equal(error.argumentCount, 5);
assert.equal(error.shell, false);
assert.equal(error.cause, cause);
assert.ok(!error.message.includes(cause.message));
assert.notProperty(error, "args");
assert.notInclude(error.message, "secret-token-value");
});
});
});
});
+144 -42
View File
@@ -8,7 +8,6 @@ import * as NetService from "@t3tools/shared/Net";
import { HostProcessEnvironment } from "@t3tools/shared/hostProcess";
import { resolveSpawnCommand } from "@t3tools/shared/shell";
import * as Config from "effect/Config";
import * as Data from "effect/Data";
import * as Effect from "effect/Effect";
import * as Hash from "effect/Hash";
import * as Layer from "effect/Layer";
@@ -57,10 +56,87 @@ export function getDevRunnerModeArgs(mode: DevMode): ReadonlyArray<string> {
return MODE_ARGS[mode];
}
class DevRunnerError extends Data.TaggedError("DevRunnerError")<{
readonly message: string;
readonly cause?: unknown;
}> {}
export class DevRunnerConfigurationError extends Schema.TaggedErrorClass<DevRunnerConfigurationError>()(
"DevRunnerConfigurationError",
{
configKeys: Schema.Array(Schema.String),
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Failed to read dev-runner configuration: ${this.configKeys.join(", ")}.`;
}
}
export class DevRunnerInvalidPortOffsetError extends Schema.TaggedErrorClass<DevRunnerInvalidPortOffsetError>()(
"DevRunnerInvalidPortOffsetError",
{
configKey: Schema.Literal("T3CODE_PORT_OFFSET"),
portOffset: Schema.Number,
minimum: Schema.Number,
},
) {
override get message(): string {
return `${this.configKey} must be at least ${this.minimum}; received ${this.portOffset}.`;
}
}
export class DevRunnerPortExhaustedError extends Schema.TaggedErrorClass<DevRunnerPortExhaustedError>()(
"DevRunnerPortExhaustedError",
{
startOffset: Schema.Number,
requireServerPort: Schema.Boolean,
requireWebPort: Schema.Boolean,
baseServerPort: Schema.Number,
baseWebPort: Schema.Number,
maximumPort: Schema.Number,
},
) {
override get message(): string {
return `No required dev ports were available from offset ${this.startOffset} through maximum port ${this.maximumPort}.`;
}
}
export class DevRunnerProcessError extends Schema.TaggedErrorClass<DevRunnerProcessError>()(
"DevRunnerProcessError",
{
operation: Schema.Literals(["spawn", "wait-for-exit"]),
mode: Schema.Literals(["dev", "dev:server", "dev:web", "dev:desktop"]),
executable: Schema.Literal("vp"),
argumentCount: Schema.Number,
shell: Schema.Boolean,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Dev-runner process operation "${this.operation}" failed for mode "${this.mode}".`;
}
}
export class DevRunnerProcessExitError extends Schema.TaggedErrorClass<DevRunnerProcessExitError>()(
"DevRunnerProcessExitError",
{
mode: Schema.Literals(["dev", "dev:server", "dev:web", "dev:desktop"]),
executable: Schema.Literal("vp"),
argumentCount: Schema.Number,
shell: Schema.Boolean,
exitCode: Schema.Number,
},
) {
override get message(): string {
return `Dev-runner process exited with code ${this.exitCode} in mode "${this.mode}".`;
}
}
export const DevRunnerError = Schema.Union([
DevRunnerConfigurationError,
DevRunnerInvalidPortOffsetError,
DevRunnerPortExhaustedError,
DevRunnerProcessError,
DevRunnerProcessExitError,
]);
export type DevRunnerError = typeof DevRunnerError.Type;
export const isDevRunnerError = Schema.is(DevRunnerError);
const optionalStringConfig = (name: string): Config.Config<string | undefined> =>
Config.string(name).pipe(
@@ -96,28 +172,40 @@ const OffsetConfig = Config.all({
export function resolveOffset(config: {
readonly portOffset: number | undefined;
readonly devInstance: string | undefined;
}): { readonly offset: number; readonly source: string } {
}): Effect.Effect<
{ readonly offset: number; readonly source: string },
DevRunnerInvalidPortOffsetError
> {
if (config.portOffset !== undefined) {
if (config.portOffset < 0) {
throw new Error(`Invalid T3CODE_PORT_OFFSET: ${config.portOffset}`);
return Effect.fail(
new DevRunnerInvalidPortOffsetError({
configKey: "T3CODE_PORT_OFFSET",
portOffset: config.portOffset,
minimum: 0,
}),
);
}
return {
return Effect.succeed({
offset: config.portOffset,
source: `T3CODE_PORT_OFFSET=${config.portOffset}`,
};
});
}
const seed = config.devInstance?.trim();
if (!seed) {
return { offset: 0, source: "default ports" };
return Effect.succeed({ offset: 0, source: "default ports" });
}
if (/^\d+$/.test(seed)) {
return { offset: Number(seed), source: `numeric T3CODE_DEV_INSTANCE=${seed}` };
return Effect.succeed({
offset: Number(seed),
source: `numeric T3CODE_DEV_INSTANCE=${seed}`,
});
}
const offset = ((Hash.string(seed) >>> 0) % MAX_HASH_OFFSET) + 1;
return { offset, source: `hashed T3CODE_DEV_INSTANCE=${seed}` };
return Effect.succeed({ offset, source: `hashed T3CODE_DEV_INSTANCE=${seed}` });
}
function resolveBaseDir(baseDir: string | undefined): Effect.Effect<string, never, Path.Path> {
@@ -275,7 +363,7 @@ export function findFirstAvailableOffset<R = NetService.NetService>({
requireServerPort,
requireWebPort,
checkPortAvailability,
}: FindFirstAvailableOffsetInput<R>): Effect.Effect<number, DevRunnerError, R> {
}: FindFirstAvailableOffsetInput<R>): Effect.Effect<number, DevRunnerPortExhaustedError, R> {
return Effect.gen(function* () {
const checkPort = (checkPortAvailability ??
defaultCheckPortAvailability) as PortAvailabilityCheck<R>;
@@ -311,8 +399,13 @@ export function findFirstAvailableOffset<R = NetService.NetService>({
}
}
return yield* new DevRunnerError({
message: `No available dev ports found from offset ${startOffset}. Tried server=${BASE_SERVER_PORT}+n web=${BASE_WEB_PORT}+n up to port ${MAX_PORT}.`,
return yield* new DevRunnerPortExhaustedError({
startOffset,
requireServerPort,
requireWebPort,
baseServerPort: BASE_SERVER_PORT,
baseWebPort: BASE_WEB_PORT,
maximumPort: MAX_PORT,
});
});
}
@@ -333,7 +426,7 @@ export function resolveModePortOffsets<R = NetService.NetService>({
checkPortAvailability,
}: ResolveModePortOffsetsInput<R>): Effect.Effect<
{ readonly serverOffset: number; readonly webOffset: number },
DevRunnerError,
DevRunnerPortExhaustedError,
R
> {
return Effect.gen(function* () {
@@ -397,21 +490,14 @@ export function runDevRunnerWithInput(input: DevRunnerCliInput) {
const { portOffset, devInstance } = yield* OffsetConfig.pipe(
Effect.mapError(
(cause) =>
new DevRunnerError({
message: "Failed to read T3CODE_PORT_OFFSET/T3CODE_DEV_INSTANCE configuration.",
new DevRunnerConfigurationError({
configKeys: ["T3CODE_PORT_OFFSET", "T3CODE_DEV_INSTANCE"],
cause,
}),
),
);
const { offset, source } = yield* Effect.try({
try: () => resolveOffset({ portOffset, devInstance }),
catch: (cause) =>
new DevRunnerError({
message: cause instanceof Error ? cause.message : String(cause),
cause,
}),
});
const { offset, source } = yield* resolveOffset({ portOffset, devInstance });
const { serverOffset, webOffset } = yield* resolveModePortOffsets({
mode: input.mode,
@@ -453,6 +539,12 @@ export function runDevRunnerWithInput(input: DevRunnerCliInput) {
[...MODE_ARGS[input.mode], ...input.runArgs],
{ env },
);
const processContext = {
mode: input.mode,
executable: "vp" as const,
argumentCount: spawnCommand.args.length,
shell: spawnCommand.shell,
} as const;
const child = yield* ChildProcess.make(spawnCommand.command, spawnCommand.args, {
stdin: "inherit",
stdout: "inherit",
@@ -465,24 +557,34 @@ export function runDevRunnerWithInput(input: DevRunnerCliInput) {
// which would put the runner in a new group and require manual forwarding.
detached: false,
forceKillAfter: "1500 millis",
});
const exitCode = yield* child.exitCode;
if (exitCode !== 0) {
return yield* new DevRunnerError({
message: `vp run exited with code ${exitCode}`,
});
}
}).pipe(
Effect.mapError((cause) =>
cause instanceof DevRunnerError
? cause
: new DevRunnerError({
message: cause instanceof Error ? cause.message : "dev-runner failed",
}).pipe(
Effect.mapError(
(cause) =>
new DevRunnerProcessError({
...processContext,
operation: "spawn",
cause,
}),
),
);
),
);
const exitCode = yield* child.exitCode.pipe(
Effect.mapError(
(cause) =>
new DevRunnerProcessError({
...processContext,
operation: "wait-for-exit",
cause,
}),
),
);
if (exitCode !== 0) {
return yield* new DevRunnerProcessExitError({
...processContext,
exitCode,
});
}
});
}
const devRunnerCli = Command.make("dev-runner", {
+9 -9
View File
@@ -1,7 +1,7 @@
// @effect-diagnostics nodeBuiltinImport:off - Tests exercise root env file precedence directly.
import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import * as NodeFS from "node:fs";
import * as NodeOS from "node:os";
import * as NodePath from "node:path";
import { afterEach, describe, expect, it } from "vite-plus/test";
import { loadRepoEnv, resolvePublicConfig } from "./public-config.ts";
@@ -10,7 +10,7 @@ const temporaryDirectories: string[] = [];
afterEach(() => {
for (const directory of temporaryDirectories.splice(0)) {
rmSync(directory, { recursive: true, force: true });
NodeFS.rmSync(directory, { recursive: true, force: true });
}
});
@@ -43,12 +43,12 @@ describe("loadRepoEnv", () => {
it("applies process, root local, and root precedence in that order", () => {
const repoRoot = makeTemporaryDirectory();
writeFileSync(
join(repoRoot, ".env"),
NodeFS.writeFileSync(
NodePath.join(repoRoot, ".env"),
"T3CODE_CLERK_PUBLISHABLE_KEY=pk_root\nT3CODE_CLERK_JWT_TEMPLATE=template_root\nT3CODE_CLERK_CLI_OAUTH_CLIENT_ID=oauth_root\nT3CODE_RELAY_URL=https://root.example.test\n",
);
writeFileSync(
join(repoRoot, ".env.local"),
NodeFS.writeFileSync(
NodePath.join(repoRoot, ".env.local"),
"T3CODE_CLERK_PUBLISHABLE_KEY=pk_local\nT3CODE_CLERK_JWT_TEMPLATE=template_local\nT3CODE_CLERK_CLI_OAUTH_CLIENT_ID=oauth_local\nT3CODE_RELAY_URL=https://local.example.test\n",
);
@@ -148,7 +148,7 @@ describe("loadRepoEnv", () => {
});
function makeTemporaryDirectory() {
const directory = mkdtempSync(join(tmpdir(), "t3code-public-config-"));
const directory = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3code-public-config-"));
temporaryDirectories.push(directory);
return directory;
}
+20
View File
@@ -0,0 +1,20 @@
import { assert, it } from "@effect/vitest";
import { CatalogDependencyResolutionError, resolveCatalogDependencies } from "./resolve-catalog.ts";
it("reports unresolved catalog dependencies with lookup context", () => {
try {
resolveCatalogDependencies({ effect: "catalog:runtime" }, {}, "apps/server");
assert.fail("Expected catalog resolution to fail.");
} catch (error) {
assert.instanceOf(error, CatalogDependencyResolutionError);
assert.equal(error.workspacePackage, "apps/server");
assert.equal(error.dependencyName, "effect");
assert.equal(error.catalogSpec, "catalog:runtime");
assert.equal(error.catalogKey, "runtime");
assert.equal(
error.message,
"Unable to resolve 'catalog:runtime' for apps/server dependency 'effect'. Expected key 'runtime' in root workspace catalog.",
);
}
});
+23 -4
View File
@@ -1,3 +1,19 @@
import * as Schema from "effect/Schema";
export class CatalogDependencyResolutionError extends Schema.TaggedErrorClass<CatalogDependencyResolutionError>()(
"CatalogDependencyResolutionError",
{
workspacePackage: Schema.String,
dependencyName: Schema.String,
catalogSpec: Schema.String,
catalogKey: Schema.String,
},
) {
override get message(): string {
return `Unable to resolve '${this.catalogSpec}' for ${this.workspacePackage} dependency '${this.dependencyName}'. Expected key '${this.catalogKey}' in root workspace catalog.`;
}
}
/**
* Resolve `catalog:` dependency specs using the workspace catalog.
*
@@ -7,7 +23,7 @@
export function resolveCatalogDependencies(
dependencies: Record<string, string>,
catalog: Record<string, string>,
label: string,
workspacePackage: string,
): Record<string, string> {
return Object.fromEntries(
Object.entries(dependencies).map(([name, spec]) => {
@@ -20,9 +36,12 @@ export function resolveCatalogDependencies(
const resolved = catalog[lookupKey];
if (typeof resolved !== "string" || resolved.length === 0) {
throw new Error(
`Unable to resolve '${spec}' for ${label} dependency '${name}'. Expected key '${lookupKey}' in root workspace catalog.`,
);
throw new CatalogDependencyResolutionError({
workspacePackage,
dependencyName: name,
catalogSpec: spec,
catalogKey: lookupKey,
});
}
return [name, resolved];
+142
View File
@@ -0,0 +1,142 @@
import * as NodeServices from "@effect/platform-node/NodeServices";
import * as HostProcess from "@t3tools/shared/hostProcess";
import { assert, it } from "@effect/vitest";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Path from "effect/Path";
import * as PlatformError from "effect/PlatformError";
import * as Sink from "effect/Sink";
import * as Stream from "effect/Stream";
import { ChildProcessSpawner } from "effect/unstable/process";
import { collectSources, runCommand } from "./mobile-native-static-check.ts";
const processHandle = (
exitCode: Effect.Effect<ChildProcessSpawner.ExitCode, PlatformError.PlatformError>,
) =>
ChildProcessSpawner.makeHandle({
pid: ChildProcessSpawner.ProcessId(1),
exitCode,
isRunning: Effect.succeed(false),
kill: () => Effect.void,
unref: Effect.succeed(Effect.void),
stdin: Sink.drain,
stdout: Stream.empty,
stderr: Stream.empty,
all: Stream.empty,
getInputFd: () => Sink.drain,
getOutputFd: () => Stream.empty,
});
const provideSpawner = (spawn: ChildProcessSpawner.ChildProcessSpawner["Service"]["spawn"]) =>
Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, ChildProcessSpawner.make(spawn));
const runSwiftLint = runCommand("swiftlint", ["lint", "--strict"], "/repo/apps/mobile").pipe(
Effect.provideService(HostProcess.HostProcessPlatform, "linux"),
);
it.layer(NodeServices.layer)("mobile native source discovery", (it) => {
it.effect("preserves the failed discovery operation, path, and exact cause", () =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const root = yield* fs.makeTempDirectoryScoped({ prefix: "mobile-native-static-check-" });
const missingDirectory = path.join(root, "missing");
const error = yield* collectSources(missingDirectory, root).pipe(Effect.flip);
assert.equal(error._tag, "NativeStaticCheckSourceDiscoveryError");
assert.equal(error.operation, "read-directory");
assert.equal(error.path, missingDirectory);
assert.instanceOf(error.cause, PlatformError.PlatformError);
assert.equal(error.message, "Native source discovery operation 'read-directory' failed.");
}),
);
});
it.effect("preserves process spawn context and the exact cause", () => {
const cause = PlatformError.systemError({
_tag: "NotFound",
module: "ChildProcess",
method: "spawn",
description: "swiftlint was not found",
});
return Effect.gen(function* () {
const error = yield* runSwiftLint.pipe(
Effect.provide(provideSpawner(() => Effect.fail(cause))),
Effect.flip,
);
if (error._tag !== "NativeStaticCheckProcessError") {
return assert.fail(`Unexpected error: ${error._tag}`);
}
assert.equal(error.operation, "spawn");
assert.equal(error.command, "swiftlint");
assert.equal(error.argumentCount, 2);
assert.equal(error.cwd, "/repo/apps/mobile");
assert.equal(error.shell, false);
assert.equal(error.cause, cause);
assert.equal(
error.message,
"Native static check process operation 'spawn' failed for command 'swiftlint'.",
);
assert.notProperty(error, "args");
});
});
it.effect("preserves process wait context and the exact cause", () => {
const cause = PlatformError.systemError({
_tag: "Unknown",
module: "ChildProcess",
method: "exitCode",
description: "status unavailable",
});
return Effect.gen(function* () {
const error = yield* runSwiftLint.pipe(
Effect.provide(provideSpawner(() => Effect.succeed(processHandle(Effect.fail(cause))))),
Effect.flip,
);
if (error._tag !== "NativeStaticCheckProcessError") {
return assert.fail(`Unexpected error: ${error._tag}`);
}
assert.equal(error.operation, "wait-for-exit");
assert.equal(error.command, "swiftlint");
assert.equal(error.argumentCount, 2);
assert.equal(error.cwd, "/repo/apps/mobile");
assert.equal(error.shell, false);
assert.equal(error.cause, cause);
assert.equal(
error.message,
"Native static check process operation 'wait-for-exit' failed for command 'swiftlint'.",
);
assert.notProperty(error, "args");
});
});
it.effect("reports non-zero exits without manufacturing a cause", () =>
Effect.gen(function* () {
const error = yield* runSwiftLint.pipe(
Effect.provide(
provideSpawner(() =>
Effect.succeed(processHandle(Effect.succeed(ChildProcessSpawner.ExitCode(2)))),
),
),
Effect.flip,
);
if (error._tag !== "NativeStaticCheckCommandError") {
return assert.fail(`Unexpected error: ${error._tag}`);
}
assert.equal(error.command, "swiftlint");
assert.equal(error.argumentCount, 2);
assert.equal(error.cwd, "/repo/apps/mobile");
assert.equal(error.shell, false);
assert.equal(error.exitCode, 2);
assert.notProperty(error, "cause");
assert.notProperty(error, "args");
}),
);
+117 -20
View File
@@ -4,12 +4,11 @@ import * as NodeRuntime from "@effect/platform-node/NodeRuntime";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { isCommandAvailable, resolveSpawnCommand } from "@t3tools/shared/shell";
import * as Console from "effect/Console";
import * as Data from "effect/Data";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Logger from "effect/Logger";
import * as Path from "effect/Path";
import * as PlatformError from "effect/PlatformError";
import * as Schema from "effect/Schema";
import { Command } from "effect/unstable/cli";
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
@@ -18,9 +17,51 @@ interface NativeStaticTool {
readonly installHint: string;
}
class NativeStaticCheckError extends Data.TaggedError("NativeStaticCheckError")<{
readonly message: string;
}> {}
const NonNegativeInt = Schema.Int.check(Schema.isGreaterThanOrEqualTo(0));
export class NativeStaticCheckSourceDiscoveryError extends Schema.TaggedErrorClass<NativeStaticCheckSourceDiscoveryError>()(
"NativeStaticCheckSourceDiscoveryError",
{
operation: Schema.Literals(["resolve-root", "read-directory", "stat-entry"]),
path: Schema.String,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Native source discovery operation '${this.operation}' failed.`;
}
}
export class NativeStaticCheckProcessError extends Schema.TaggedErrorClass<NativeStaticCheckProcessError>()(
"NativeStaticCheckProcessError",
{
operation: Schema.Literals(["spawn", "wait-for-exit"]),
command: Schema.String,
argumentCount: NonNegativeInt,
cwd: Schema.String,
shell: Schema.Boolean,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Native static check process operation '${this.operation}' failed for command '${this.command}'.`;
}
}
export class NativeStaticCheckCommandError extends Schema.TaggedErrorClass<NativeStaticCheckCommandError>()(
"NativeStaticCheckCommandError",
{
command: Schema.String,
argumentCount: NonNegativeInt,
cwd: Schema.String,
shell: Schema.Boolean,
exitCode: Schema.Int,
},
) {
override get message(): string {
return `Native static check command '${this.command}' exited with code ${this.exitCode}.`;
}
}
const tools = [
{
@@ -49,8 +90,17 @@ const excludedDirectories = new Set([
]);
const generatedNativeProjectDirectories = new Set(["android", "ios"]);
const mobileAppRootUrl = new URL("../apps/mobile", import.meta.url);
const appRoot = Effect.service(Path.Path).pipe(
Effect.flatMap((path) => path.fromFileUrl(new URL("../apps/mobile", import.meta.url))),
Effect.flatMap((path) => path.fromFileUrl(mobileAppRootUrl)),
Effect.mapError(
(cause) =>
new NativeStaticCheckSourceDiscoveryError({
operation: "resolve-root",
path: mobileAppRootUrl.pathname,
cause,
}),
),
);
const commandOutputOptions = {
@@ -67,7 +117,7 @@ const warnMissingTool = (tool: NativeStaticTool, checkName: string) =>
`${tool.command} is not installed; skipping ${checkName}. Install it with '${tool.installHint}' or run 'brew bundle install --file apps/mobile/Brewfile'.`,
);
const runCommand = Effect.fn("runCommand")(function* (
export const runCommand = Effect.fn("runCommand")(function* (
command: string,
args: ReadonlyArray<string>,
cwd: string,
@@ -75,39 +125,86 @@ const runCommand = Effect.fn("runCommand")(function* (
yield* Console.log(`$ ${[command, ...args].join(" ")}`);
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
const spawnCommand = yield* resolveSpawnCommand(command, args);
const child = yield* spawner.spawn(
ChildProcess.make(spawnCommand.command, spawnCommand.args, {
cwd,
...commandOutputOptions,
shell: spawnCommand.shell,
}),
const processContext = {
command,
argumentCount: spawnCommand.args.length,
cwd,
shell: spawnCommand.shell,
} as const;
const child = yield* spawner
.spawn(
ChildProcess.make(spawnCommand.command, spawnCommand.args, {
cwd,
...commandOutputOptions,
shell: spawnCommand.shell,
}),
)
.pipe(
Effect.mapError(
(cause) =>
new NativeStaticCheckProcessError({
...processContext,
operation: "spawn",
cause,
}),
),
);
const exitCode = Number(
yield* child.exitCode.pipe(
Effect.mapError(
(cause) =>
new NativeStaticCheckProcessError({
...processContext,
operation: "wait-for-exit",
cause,
}),
),
),
);
const exitCode = Number(yield* child.exitCode);
if (exitCode !== 0) {
return yield* new NativeStaticCheckError({
message: `Command exited with non-zero exit code (${exitCode})`,
return yield* new NativeStaticCheckCommandError({
...processContext,
exitCode,
});
}
});
function collectSources(
export function collectSources(
directory: string,
root: string,
): Effect.Effect<
ReadonlyArray<string>,
PlatformError.PlatformError,
NativeStaticCheckSourceDiscoveryError,
FileSystem.FileSystem | Path.Path
> {
return Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const entries = yield* fs.readDirectory(directory);
const entries = yield* fs.readDirectory(directory).pipe(
Effect.mapError(
(cause) =>
new NativeStaticCheckSourceDiscoveryError({
operation: "read-directory",
path: directory,
cause,
}),
),
);
const sources: Array<string> = [];
for (const entry of entries) {
const entryPath = path.join(directory, entry);
const stat = yield* fs.stat(entryPath);
const stat = yield* fs.stat(entryPath).pipe(
Effect.mapError(
(cause) =>
new NativeStaticCheckSourceDiscoveryError({
operation: "stat-entry",
path: entryPath,
cause,
}),
),
);
if (stat.type === "Directory") {
const isGeneratedNativeProjectDirectory =
+124 -38
View File
@@ -1,6 +1,25 @@
import { assert, it } from "@effect/vitest";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import { HttpClient, HttpClientError, HttpClientResponse } from "effect/unstable/http";
import { buildDiscordReleaseAnnouncement } from "./notify-discord-release.ts";
import {
buildDiscordReleaseAnnouncement,
isDiscordReleaseAnnouncementError,
postDiscordWebhook,
} from "./notify-discord-release.ts";
const latestAnnouncement = {
target: "latest",
roleId: "222222222222222222",
releaseName: "T3 Code v1.2.3",
version: "1.2.3",
tag: "v1.2.3",
releaseUrl: new URL("https://github.com/t3dotgg/t3-code/releases/tag/v1.2.3"),
timestamp: "2026-05-01T01:41:00.000Z",
} as const;
const webhookUrl = new URL("https://discord.com/api/webhooks/123456/secret-token");
it("builds a prerelease Discord announcement for nightly subscribers", () => {
assert.deepStrictEqual(
@@ -47,42 +66,109 @@ it("builds a prerelease Discord announcement for nightly subscribers", () => {
});
it("builds a latest Discord announcement for stable subscribers", () => {
assert.deepStrictEqual(
buildDiscordReleaseAnnouncement({
target: "latest",
roleId: "222222222222222222",
releaseName: "T3 Code v1.2.3",
version: "1.2.3",
tag: "v1.2.3",
releaseUrl: new URL("https://github.com/t3dotgg/t3-code/releases/tag/v1.2.3"),
timestamp: "2026-05-01T01:41:00.000Z",
}),
{
content: "<@&222222222222222222> Latest published: T3 Code v1.2.3",
allowed_mentions: {
roles: ["222222222222222222"],
},
embeds: [
{
title: "T3 Code v1.2.3",
url: "https://github.com/t3dotgg/t3-code/releases/tag/v1.2.3",
description: "A new T3 Code latest release is available.",
color: 0x2ecc71,
fields: [
{
name: "Version",
value: "1.2.3",
inline: true,
},
{
name: "Tag",
value: "v1.2.3",
inline: true,
},
],
timestamp: "2026-05-01T01:41:00.000Z",
},
],
assert.deepStrictEqual(buildDiscordReleaseAnnouncement(latestAnnouncement), {
content: "<@&222222222222222222> Latest published: T3 Code v1.2.3",
allowed_mentions: {
roles: ["222222222222222222"],
},
);
embeds: [
{
title: "T3 Code v1.2.3",
url: "https://github.com/t3dotgg/t3-code/releases/tag/v1.2.3",
description: "A new T3 Code latest release is available.",
color: 0x2ecc71,
fields: [
{
name: "Version",
value: "1.2.3",
inline: true,
},
{
name: "Tag",
value: "v1.2.3",
inline: true,
},
],
timestamp: "2026-05-01T01:41:00.000Z",
},
],
});
});
it.effect("preserves webhook request context and the full client cause chain", () => {
const payload = buildDiscordReleaseAnnouncement(latestAnnouncement);
const requestCause = new Error("request encoder unavailable");
let clientError: HttpClientError.HttpClientError | undefined;
const httpClientLayer = Layer.succeed(
HttpClient.HttpClient,
HttpClient.make((request) => {
clientError = new HttpClientError.HttpClientError({
reason: new HttpClientError.EncodeError({
request,
cause: requestCause,
}),
});
return Effect.fail(clientError);
}),
);
return Effect.gen(function* () {
const error = yield* postDiscordWebhook(webhookUrl, payload, latestAnnouncement).pipe(
Effect.provide(httpClientLayer),
Effect.flip,
);
if (error._tag !== "DiscordReleaseWebhookRequestError") {
assert.fail(`Unexpected error: ${error._tag}`);
}
assert.equal(error.target, "latest");
assert.equal(error.releaseName, latestAnnouncement.releaseName);
assert.equal(error.version, latestAnnouncement.version);
assert.equal(error.tag, latestAnnouncement.tag);
assert.equal(error.releaseUrl, latestAnnouncement.releaseUrl.href);
assert.equal(error.webhookOrigin, webhookUrl.origin);
assert.equal(error.webhookPathnameSegmentCount, 4);
assert.equal(error.contentLength, payload.content.length);
assert.equal(error.embedCount, 1);
assert.equal(error.allowedRoleMentionCount, 1);
assert.equal(error.hasRoleMentionSyntax, true);
assert.equal(error.cause, clientError);
assert.equal((error.cause as HttpClientError.HttpClientError).cause, requestCause);
assert.ok(!error.message.includes(requestCause.message));
assert.equal(isDiscordReleaseAnnouncementError(error), true);
});
});
it.effect("preserves a non-success response error with structured status context", () => {
const payload = buildDiscordReleaseAnnouncement(latestAnnouncement);
const httpClientLayer = Layer.succeed(
HttpClient.HttpClient,
HttpClient.make((request) =>
Effect.succeed(
HttpClientResponse.fromWeb(request, new Response("invalid webhook", { status: 400 })),
),
),
);
return Effect.gen(function* () {
const error = yield* postDiscordWebhook(webhookUrl, payload, latestAnnouncement).pipe(
Effect.provide(httpClientLayer),
Effect.flip,
);
if (error._tag !== "DiscordReleaseWebhookResponseError") {
assert.fail(`Unexpected error: ${error._tag}`);
}
assert.equal(error.target, "latest");
assert.equal(error.tag, latestAnnouncement.tag);
assert.equal(error.webhookOrigin, webhookUrl.origin);
assert.equal(error.webhookPathnameSegmentCount, 4);
assert.equal(error.status, 400);
if (!HttpClientError.isHttpClientError(error.cause)) {
assert.fail("Expected HttpClientError cause");
}
assert.equal(error.cause.reason._tag, "StatusCodeError");
assert.ok(!error.message.includes(error.cause.message));
assert.equal(isDiscordReleaseAnnouncementError(error), true);
});
});
+68 -14
View File
@@ -3,7 +3,6 @@
import * as NodeRuntime from "@effect/platform-node/NodeRuntime";
import * as NodeServices from "@effect/platform-node/NodeServices";
import * as Config from "effect/Config";
import * as Data from "effect/Data";
import * as DateTime from "effect/DateTime";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
@@ -19,7 +18,7 @@ import {
export type DiscordReleaseTarget = "prerelease" | "latest";
interface DiscordReleaseAnnouncementOptions {
export interface DiscordReleaseAnnouncementOptions {
readonly target: DiscordReleaseTarget;
readonly roleId: string;
readonly releaseName: string;
@@ -52,10 +51,51 @@ const DISCORD_RELEASE_TARGETS = ["prerelease", "latest"] as const;
const DiscordRoleIdSchema = Schema.String.check(Schema.isPattern(/^\d+$/));
const DiscordWebhookUrl = Config.url("DISCORD_WEBHOOK_URL");
class DiscordReleaseAnnouncementError extends Data.TaggedError("DiscordReleaseAnnouncementError")<{
readonly message: string;
readonly cause?: unknown;
}> {}
const discordReleaseErrorContext = {
target: Schema.Literals(["prerelease", "latest"]),
releaseName: Schema.String,
version: Schema.String,
tag: Schema.String,
releaseUrl: Schema.String,
webhookOrigin: Schema.String,
webhookPathnameSegmentCount: Schema.Number,
contentLength: Schema.Number,
embedCount: Schema.Number,
allowedRoleMentionCount: Schema.Number,
hasRoleMentionSyntax: Schema.Boolean,
};
export class DiscordReleaseWebhookRequestError extends Schema.TaggedErrorClass<DiscordReleaseWebhookRequestError>()(
"DiscordReleaseWebhookRequestError",
{
...discordReleaseErrorContext,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Failed to post Discord ${this.target} release announcement for "${this.tag}" to ${this.webhookOrigin}.`;
}
}
export class DiscordReleaseWebhookResponseError extends Schema.TaggedErrorClass<DiscordReleaseWebhookResponseError>()(
"DiscordReleaseWebhookResponseError",
{
...discordReleaseErrorContext,
status: Schema.Number,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Discord ${this.target} release webhook for "${this.tag}" returned status ${this.status}.`;
}
}
export const DiscordReleaseAnnouncementError = Schema.Union([
DiscordReleaseWebhookRequestError,
DiscordReleaseWebhookResponseError,
]);
export type DiscordReleaseAnnouncementError = typeof DiscordReleaseAnnouncementError.Type;
export const isDiscordReleaseAnnouncementError = Schema.is(DiscordReleaseAnnouncementError);
const targetLabels = {
prerelease: "Prerelease",
@@ -117,9 +157,10 @@ export const buildDiscordReleaseAnnouncement = (
],
});
const postDiscordWebhook = Effect.fn("postDiscordWebhook")(function* (
export const postDiscordWebhook = Effect.fn("postDiscordWebhook")(function* (
webhookUrl: URL,
payload: DiscordWebhookPayload,
announcement: DiscordReleaseAnnouncementOptions,
) {
const httpClient = (yield* HttpClient.HttpClient).pipe(
HttpClient.retryTransient({
@@ -135,13 +176,24 @@ const postDiscordWebhook = Effect.fn("postDiscordWebhook")(function* (
}),
);
const errorContext = {
target: announcement.target,
releaseName: announcement.releaseName,
version: announcement.version,
tag: announcement.tag,
releaseUrl: announcement.releaseUrl.href,
webhookOrigin: webhookUrl.origin,
webhookPathnameSegmentCount: webhookUrl.pathname.split("/").filter(Boolean).length,
...summarizePayload(payload),
} as const;
const response = yield* HttpClientRequest.post(webhookUrl).pipe(
HttpClientRequest.bodyJson(payload),
Effect.flatMap(httpClient.execute),
Effect.mapError(
(cause) =>
new DiscordReleaseAnnouncementError({
message: "Failed to post Discord release announcement.",
new DiscordReleaseWebhookRequestError({
...errorContext,
cause,
}),
),
@@ -157,8 +209,9 @@ const postDiscordWebhook = Effect.fn("postDiscordWebhook")(function* (
yield* HttpClientResponse.filterStatusOk(response).pipe(
Effect.mapError(
(cause) =>
new DiscordReleaseAnnouncementError({
message: `Discord webhook returned status ${response.status}.`,
new DiscordReleaseWebhookResponseError({
...errorContext,
status: response.status,
cause,
}),
),
@@ -208,7 +261,7 @@ export const notifyDiscordReleaseCommand = Command.make(
const webhookUrl = yield* DiscordWebhookUrl;
const timestamp = DateTime.formatIso(yield* DateTime.now);
const payload = buildDiscordReleaseAnnouncement({
const announcement = {
target,
roleId,
releaseName,
@@ -216,12 +269,13 @@ export const notifyDiscordReleaseCommand = Command.make(
tag,
releaseUrl,
timestamp,
});
} satisfies DiscordReleaseAnnouncementOptions;
const payload = buildDiscordReleaseAnnouncement(announcement);
yield* Effect.logInfo("discord release announcement payload built").pipe(
Effect.annotateLogs(summarizePayload(payload)),
);
yield* postDiscordWebhook(webhookUrl, payload);
yield* postDiscordWebhook(webhookUrl, payload, announcement);
yield* Effect.logInfo("discord release announcement completed");
}),
).pipe(Command.withDescription("Post a T3 Code release announcement to Discord."));
+62 -64
View File
@@ -1,21 +1,13 @@
// @effect-diagnostics nodeBuiltinImport:off
import { execFileSync } from "node:child_process";
import {
cpSync,
existsSync,
mkdirSync,
mkdtempSync,
readFileSync,
rmSync,
writeFileSync,
} from "node:fs";
import { tmpdir } from "node:os";
import { dirname, join, resolve } from "node:path";
import { fileURLToPath } from "node:url";
import * as NodeChildProcess from "node:child_process";
import * as NodeFS from "node:fs";
import * as NodeOS from "node:os";
import * as NodePath from "node:path";
import * as NodeURL from "node:url";
import * as Console from "effect/Console";
import * as Effect from "effect/Effect";
const repoRoot = resolve(dirname(fileURLToPath(import.meta.url)), "..");
const repoRoot = NodePath.resolve(NodePath.dirname(NodeURL.fileURLToPath(import.meta.url)), "..");
const workspaceFiles = [
"package.json",
@@ -44,26 +36,26 @@ const workspaceFiles = [
function copyWorkspaceManifestFixture(targetRoot: string): void {
for (const relativePath of workspaceFiles) {
const sourcePath = resolve(repoRoot, relativePath);
const destinationPath = resolve(targetRoot, relativePath);
mkdirSync(dirname(destinationPath), { recursive: true });
cpSync(sourcePath, destinationPath);
const sourcePath = NodePath.resolve(repoRoot, relativePath);
const destinationPath = NodePath.resolve(targetRoot, relativePath);
NodeFS.mkdirSync(NodePath.dirname(destinationPath), { recursive: true });
NodeFS.cpSync(sourcePath, destinationPath);
}
const patchesDirectory = resolve(repoRoot, "patches");
if (existsSync(patchesDirectory)) {
cpSync(patchesDirectory, resolve(targetRoot, "patches"), { recursive: true });
const patchesDirectory = NodePath.resolve(repoRoot, "patches");
if (NodeFS.existsSync(patchesDirectory)) {
NodeFS.cpSync(patchesDirectory, NodePath.resolve(targetRoot, "patches"), { recursive: true });
}
}
function writeMacManifestFixtures(targetRoot: string): { arm64Path: string; x64Path: string } {
const assetDirectory = resolve(targetRoot, "release-assets");
mkdirSync(assetDirectory, { recursive: true });
const assetDirectory = NodePath.resolve(targetRoot, "release-assets");
NodeFS.mkdirSync(assetDirectory, { recursive: true });
const arm64Path = resolve(assetDirectory, "latest-mac.yml");
const x64Path = resolve(assetDirectory, "latest-mac-x64.yml");
const arm64Path = NodePath.resolve(assetDirectory, "latest-mac.yml");
const x64Path = NodePath.resolve(assetDirectory, "latest-mac-x64.yml");
writeFileSync(
NodeFS.writeFileSync(
arm64Path,
`version: 9.9.9-smoke.0
files:
@@ -79,7 +71,7 @@ releaseDate: '2026-03-08T10:32:14.587Z'
`,
);
writeFileSync(
NodeFS.writeFileSync(
x64Path,
`version: 9.9.9-smoke.0
files:
@@ -102,13 +94,13 @@ function writeWindowsManifestFixtures(
targetRoot: string,
channel: string,
): { arm64Path: string; x64Path: string } {
const assetDirectory = resolve(targetRoot, "release-assets");
mkdirSync(assetDirectory, { recursive: true });
const assetDirectory = NodePath.resolve(targetRoot, "release-assets");
NodeFS.mkdirSync(assetDirectory, { recursive: true });
const arm64Path = resolve(assetDirectory, `${channel}-win-arm64.yml`);
const x64Path = resolve(assetDirectory, `${channel}-win-x64.yml`);
const arm64Path = NodePath.resolve(assetDirectory, `${channel}-win-arm64.yml`);
const x64Path = NodePath.resolve(assetDirectory, `${channel}-win-x64.yml`);
writeFileSync(
NodeFS.writeFileSync(
arm64Path,
`version: 9.9.9-smoke.0
files:
@@ -124,7 +116,7 @@ releaseDate: '2026-03-08T10:32:14.587Z'
`,
);
writeFileSync(
NodeFS.writeFileSync(
x64Path,
`version: 9.9.9-smoke.0
files:
@@ -147,11 +139,11 @@ function writeWindowsBuilderDebugFixtures(targetRoot: string): {
arm64Path: string;
x64Path: string;
} {
const assetDirectory = resolve(targetRoot, "release-assets");
mkdirSync(assetDirectory, { recursive: true });
const assetDirectory = NodePath.resolve(targetRoot, "release-assets");
NodeFS.mkdirSync(assetDirectory, { recursive: true });
const arm64Path = resolve(assetDirectory, "builder-debug-win-arm64.yml");
const x64Path = resolve(assetDirectory, "builder-debug-win-x64.yml");
const arm64Path = NodePath.resolve(assetDirectory, "builder-debug-win-arm64.yml");
const x64Path = NodePath.resolve(assetDirectory, "builder-debug-win-x64.yml");
const debugFixture = `arm64:
firstOrDefaultFilePatterns:
- '**/*'
@@ -160,8 +152,8 @@ nsis:
!include "example.nsh"
`;
writeFileSync(arm64Path, debugFixture);
writeFileSync(x64Path, debugFixture);
NodeFS.writeFileSync(arm64Path, debugFixture);
NodeFS.writeFileSync(x64Path, debugFixture);
return { arm64Path, x64Path };
}
@@ -172,13 +164,13 @@ function assertContains(haystack: string, needle: string, message: string): void
}
function assertExists(path: string, message: string): void {
if (!existsSync(path)) {
if (!NodeFS.existsSync(path)) {
throw new Error(message);
}
}
function assertPackageVersion(path: string, version: string): void {
const packageJson = JSON.parse(readFileSync(path, "utf8")) as {
const packageJson = JSON.parse(NodeFS.readFileSync(path, "utf8")) as {
readonly version?: unknown;
};
@@ -188,20 +180,20 @@ function assertPackageVersion(path: string, version: string): void {
}
function assertMissing(path: string, message: string): void {
if (existsSync(path)) {
if (NodeFS.existsSync(path)) {
throw new Error(message);
}
}
const tempRoot = mkdtempSync(join(tmpdir(), "t3-release-smoke-"));
const tempRoot = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-release-smoke-"));
try {
copyWorkspaceManifestFixture(tempRoot);
execFileSync(
NodeChildProcess.execFileSync(
process.execPath,
[
resolve(repoRoot, "scripts/update-release-package-versions.ts"),
NodePath.resolve(repoRoot, "scripts/update-release-package-versions.ts"),
"9.9.9-smoke.0",
"--root",
tempRoot,
@@ -212,14 +204,14 @@ try {
},
);
rmSync(resolve(tempRoot, "pnpm-lock.yaml"), { force: true });
NodeFS.rmSync(NodePath.resolve(tempRoot, "pnpm-lock.yaml"), { force: true });
execFileSync("vp", ["install", "--lockfile-only", "--ignore-scripts"], {
NodeChildProcess.execFileSync("vp", ["install", "--lockfile-only", "--ignore-scripts"], {
cwd: tempRoot,
stdio: "inherit",
});
const lockfile = readFileSync(resolve(tempRoot, "pnpm-lock.yaml"), "utf8");
const lockfile = NodeFS.readFileSync(NodePath.resolve(tempRoot, "pnpm-lock.yaml"), "utf8");
assertContains(lockfile, "lockfileVersion:", "Expected pnpm-lock.yaml to be regenerated.");
for (const relativePath of [
@@ -228,13 +220,13 @@ try {
"apps/web/package.json",
"packages/contracts/package.json",
]) {
assertPackageVersion(resolve(tempRoot, relativePath), "9.9.9-smoke.0");
assertPackageVersion(NodePath.resolve(tempRoot, relativePath), "9.9.9-smoke.0");
}
const nightlyReleaseMetadata = execFileSync(
const nightlyReleaseMetadata = NodeChildProcess.execFileSync(
process.execPath,
[
resolve(repoRoot, "scripts/resolve-nightly-release.ts"),
NodePath.resolve(repoRoot, "scripts/resolve-nightly-release.ts"),
"--date",
"20260413",
"--run-number",
@@ -266,10 +258,10 @@ try {
);
const { arm64Path, x64Path } = writeMacManifestFixtures(tempRoot);
execFileSync(
NodeChildProcess.execFileSync(
process.execPath,
[
resolve(repoRoot, "scripts/merge-update-manifests.ts"),
NodePath.resolve(repoRoot, "scripts/merge-update-manifests.ts"),
"--platform",
"mac",
arm64Path,
@@ -281,7 +273,7 @@ try {
},
);
const mergedManifest = readFileSync(arm64Path, "utf8");
const mergedManifest = NodeFS.readFileSync(arm64Path, "utf8");
assertContains(
mergedManifest,
"T3-Code-9.9.9-smoke.0-arm64.zip",
@@ -297,21 +289,21 @@ try {
tempRoot,
"latest",
);
const mergedWindowsManifestPath = resolve(tempRoot, "release-assets/latest.yml");
const mergedWindowsManifestPath = NodePath.resolve(tempRoot, "release-assets/latest.yml");
const { arm64Path: nightlyWinArm64Path, x64Path: nightlyWinX64Path } =
writeWindowsManifestFixtures(tempRoot, "nightly");
const mergedNightlyWindowsManifestPath = resolve(tempRoot, "release-assets/nightly.yml");
const mergedNightlyWindowsManifestPath = NodePath.resolve(tempRoot, "release-assets/nightly.yml");
const { arm64Path: previewWinArm64Path, x64Path: previewWinX64Path } =
writeWindowsManifestFixtures(tempRoot, "preview");
const mergedPreviewWindowsManifestPath = resolve(tempRoot, "release-assets/preview.yml");
const mergedPreviewWindowsManifestPath = NodePath.resolve(tempRoot, "release-assets/preview.yml");
const { arm64Path: winDebugArm64Path, x64Path: winDebugX64Path } =
writeWindowsBuilderDebugFixtures(tempRoot);
execFileSync(
NodeChildProcess.execFileSync(
"bash",
[
"-lc",
`
release_assets_dir=${JSON.stringify(resolve(tempRoot, "release-assets"))}
release_assets_dir=${JSON.stringify(NodePath.resolve(tempRoot, "release-assets"))}
shopt -s nullglob
found_windows_manifest=false
for x64_manifest in "$release_assets_dir"/*-win-x64.yml; do
@@ -327,7 +319,7 @@ try {
fi
found_windows_manifest=true
${JSON.stringify(process.execPath)} ${JSON.stringify(resolve(repoRoot, "scripts/merge-update-manifests.ts"))} --platform win \
${JSON.stringify(process.execPath)} ${JSON.stringify(NodePath.resolve(repoRoot, "scripts/merge-update-manifests.ts"))} --platform win \
"$arm64_manifest" \
"$x64_manifest" \
"$output_manifest"
@@ -346,7 +338,7 @@ try {
},
);
const mergedWindowsManifest = readFileSync(mergedWindowsManifestPath, "utf8");
const mergedWindowsManifest = NodeFS.readFileSync(mergedWindowsManifestPath, "utf8");
assertContains(
mergedWindowsManifest,
"T3-Code-9.9.9-smoke.0-arm64.exe",
@@ -357,7 +349,10 @@ try {
"T3-Code-9.9.9-smoke.0-x64.exe",
"Merged Windows manifest is missing the x64 asset.",
);
const mergedNightlyWindowsManifest = readFileSync(mergedNightlyWindowsManifestPath, "utf8");
const mergedNightlyWindowsManifest = NodeFS.readFileSync(
mergedNightlyWindowsManifestPath,
"utf8",
);
assertContains(
mergedNightlyWindowsManifest,
"T3-Code-9.9.9-smoke.0-arm64.exe",
@@ -368,7 +363,10 @@ try {
"T3-Code-9.9.9-smoke.0-x64.exe",
"Merged nightly Windows manifest is missing the x64 asset.",
);
const mergedPreviewWindowsManifest = readFileSync(mergedPreviewWindowsManifestPath, "utf8");
const mergedPreviewWindowsManifest = NodeFS.readFileSync(
mergedPreviewWindowsManifestPath,
"utf8",
);
assertContains(
mergedPreviewWindowsManifest,
"T3-Code-9.9.9-smoke.0-arm64.exe",
@@ -411,5 +409,5 @@ try {
Effect.runSync(Console.log("Release smoke checks passed."));
} finally {
rmSync(tempRoot, { recursive: true, force: true });
NodeFS.rmSync(tempRoot, { recursive: true, force: true });
}
+95 -5
View File
@@ -1,9 +1,18 @@
import * as NodeServices from "@effect/platform-node/NodeServices";
import { assert, it } from "@effect/vitest";
import * as Config from "effect/Config";
import * as ConfigProvider from "effect/ConfigProvider";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Path from "effect/Path";
import * as PlatformError from "effect/PlatformError";
import {
readDesktopBaseVersion,
resolveNightlyBaseVersion,
resolveNightlyReleaseMetadata,
resolveNightlyTargetVersion,
writeNightlyReleaseOutput,
} from "./resolve-nightly-release.ts";
it("strips prerelease and build metadata when deriving the nightly base version", () => {
@@ -12,11 +21,23 @@ it("strips prerelease and build metadata when deriving the nightly base version"
assert.equal(resolveNightlyBaseVersion("1.2.3-beta.4+build.9"), "1.2.3");
});
it("bumps the patch version before deriving nightly prerelease versions", () => {
assert.equal(resolveNightlyTargetVersion("0.0.17"), "0.0.18");
assert.equal(resolveNightlyTargetVersion("9.9.9-smoke.0"), "9.9.10");
assert.equal(resolveNightlyTargetVersion("1.2.3-beta.4+build.9"), "1.2.4");
});
it.effect("bumps the patch version before deriving nightly prerelease versions", () =>
Effect.gen(function* () {
assert.equal(yield* resolveNightlyTargetVersion("0.0.17"), "0.0.18");
assert.equal(yield* resolveNightlyTargetVersion("9.9.9-smoke.0"), "9.9.10");
assert.equal(yield* resolveNightlyTargetVersion("1.2.3-beta.4+build.9"), "1.2.4");
}),
);
it.effect("reports the invalid desktop package version", () =>
Effect.gen(function* () {
const error = yield* resolveNightlyTargetVersion("nightly").pipe(Effect.flip);
assert.equal(error._tag, "InvalidDesktopPackageVersionError");
assert.equal(error.version, "nightly");
assert.equal(error.message, "Invalid desktop package version 'nightly'.");
}),
);
it("derives nightly metadata including the short commit sha in the release name", () => {
assert.deepStrictEqual(
@@ -30,3 +51,72 @@ it("derives nightly metadata including the short commit sha in the release name"
},
);
});
it.effect("preserves the GITHUB_OUTPUT configuration cause", () => {
const metadata = resolveNightlyReleaseMetadata("1.2.4", "20260620", 42, "abcdef1234567890");
const configCause = new ConfigProvider.SourceError({ message: "environment unavailable" });
return Effect.gen(function* () {
const configError = yield* writeNightlyReleaseOutput(metadata, true).pipe(
Effect.provideService(FileSystem.FileSystem, FileSystem.makeNoop({})),
Effect.provideService(
ConfigProvider.ConfigProvider,
ConfigProvider.make(() => Effect.fail(configCause)),
),
Effect.flip,
);
if (configError._tag !== "NightlyReleaseGitHubOutputConfigError") {
return assert.fail(`Unexpected error: ${configError._tag}`);
}
assert.instanceOf(configError.cause, Config.ConfigError);
assert.strictEqual(configError.cause.cause, configCause);
assert.notInclude(configError.message, configCause.message);
});
});
it.layer(NodeServices.layer)("readDesktopBaseVersion", (it) => {
it.effect("preserves desktop package read context and its platform cause", () =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const rootDir = yield* fs.makeTempDirectoryScoped({
prefix: "resolve-nightly-release-read-",
});
const packageJsonPath = path.join(rootDir, "apps/desktop/package.json");
const error = yield* readDesktopBaseVersion(rootDir).pipe(Effect.flip);
if (error._tag !== "NightlyReleaseDesktopPackageError") {
return assert.fail(`Unexpected error: ${error._tag}`);
}
assert.equal(error.operation, "read");
assert.equal(error.packageJsonPath, packageJsonPath);
assert.instanceOf(error.cause, PlatformError.PlatformError);
assert.notInclude(error.message, String((error.cause as Error).message));
}),
);
it.effect("preserves desktop package decode context and its schema cause", () =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const rootDir = yield* fs.makeTempDirectoryScoped({
prefix: "resolve-nightly-release-decode-",
});
const packageJsonPath = path.join(rootDir, "apps/desktop/package.json");
yield* fs.makeDirectory(path.dirname(packageJsonPath), { recursive: true });
yield* fs.writeFileString(packageJsonPath, "{");
const error = yield* readDesktopBaseVersion(rootDir).pipe(Effect.flip);
if (error._tag !== "NightlyReleaseDesktopPackageError") {
return assert.fail(`Unexpected error: ${error._tag}`);
}
assert.equal(error.operation, "decode");
assert.equal(error.packageJsonPath, packageJsonPath);
assert.ok(error.cause !== undefined);
assert.notInclude(error.message, String((error.cause as Error).message));
}),
);
});
+91 -12
View File
@@ -11,7 +11,7 @@ import * as Path from "effect/Path";
import * as Schema from "effect/Schema";
import { Command, Flag } from "effect/unstable/cli";
interface NightlyReleaseMetadata {
export interface NightlyReleaseMetadata {
readonly baseVersion: string;
readonly version: string;
readonly tag: string;
@@ -29,6 +29,53 @@ const DesktopPackageJsonSchema = Schema.Struct({
version: Schema.NonEmptyString,
});
export class InvalidDesktopPackageVersionError extends Schema.TaggedErrorClass<InvalidDesktopPackageVersionError>()(
"InvalidDesktopPackageVersionError",
{
version: Schema.String,
},
) {
override get message(): string {
return `Invalid desktop package version '${this.version}'.`;
}
}
export class NightlyReleaseDesktopPackageError extends Schema.TaggedErrorClass<NightlyReleaseDesktopPackageError>()(
"NightlyReleaseDesktopPackageError",
{
operation: Schema.Literals(["read", "decode"]),
packageJsonPath: Schema.String,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Failed to ${this.operation} desktop package metadata at ${this.packageJsonPath}.`;
}
}
export class NightlyReleaseGitHubOutputConfigError extends Schema.TaggedErrorClass<NightlyReleaseGitHubOutputConfigError>()(
"NightlyReleaseGitHubOutputConfigError",
{
cause: Schema.Defect(),
},
) {
override get message(): string {
return "Failed to resolve the GITHUB_OUTPUT path for nightly release metadata.";
}
}
export class NightlyReleaseGitHubOutputAppendError extends Schema.TaggedErrorClass<NightlyReleaseGitHubOutputAppendError>()(
"NightlyReleaseGitHubOutputAppendError",
{
outputPath: Schema.String,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Failed to append nightly release metadata to ${this.outputPath}.`;
}
}
const RepoRoot = Effect.service(Path.Path).pipe(
Effect.flatMap((path) => path.fromFileUrl(new URL("..", import.meta.url))),
);
@@ -42,11 +89,11 @@ export const resolveNightlyTargetVersion = (version: string) => {
const stableCore = resolveNightlyBaseVersion(version);
const match = /^(\d+)\.(\d+)\.(\d+)$/.exec(stableCore);
if (!match) {
throw new Error(`Invalid desktop package version '${version}'.`);
return Effect.fail(new InvalidDesktopPackageVersionError({ version }));
}
const [, major, minor, patch] = match;
return `${major}.${minor}.${Number(patch) + 1}`;
return Effect.succeed(`${major}.${minor}.${Number(patch) + 1}`);
};
export const resolveNightlyReleaseMetadata = (
@@ -66,20 +113,37 @@ export const resolveNightlyReleaseMetadata = (
};
};
const readDesktopBaseVersion = Effect.fn("readDesktopBaseVersion")(function* (
export const readDesktopBaseVersion = Effect.fn("readDesktopBaseVersion")(function* (
rootDir: string | undefined,
) {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const workspaceRoot = rootDir ? path.resolve(rootDir) : yield* RepoRoot;
const packageJsonPath = path.join(workspaceRoot, "apps/desktop/package.json");
const packageJson = yield* fs
.readFileString(packageJsonPath)
.pipe(Effect.flatMap(decodeDesktopPackageJson));
return resolveNightlyTargetVersion(packageJson.version);
const packageJsonSource = yield* fs.readFileString(packageJsonPath).pipe(
Effect.mapError(
(cause) =>
new NightlyReleaseDesktopPackageError({
operation: "read",
packageJsonPath,
cause,
}),
),
);
const packageJson = yield* decodeDesktopPackageJson(packageJsonSource).pipe(
Effect.mapError(
(cause) =>
new NightlyReleaseDesktopPackageError({
operation: "decode",
packageJsonPath,
cause,
}),
),
);
return yield* resolveNightlyTargetVersion(packageJson.version);
});
const writeOutput = Effect.fn("writeOutput")(function* (
export const writeNightlyReleaseOutput = Effect.fn("writeNightlyReleaseOutput")(function* (
metadata: NightlyReleaseMetadata,
writeGithubOutput: boolean,
) {
@@ -94,9 +158,24 @@ const writeOutput = Effect.fn("writeOutput")(function* (
] as const;
if (writeGithubOutput) {
const githubOutputPath = yield* Config.nonEmptyString("GITHUB_OUTPUT");
const githubOutputPath = yield* Config.nonEmptyString("GITHUB_OUTPUT").pipe(
Effect.mapError(
(cause) =>
new NightlyReleaseGitHubOutputConfigError({
cause,
}),
),
);
const serialized = entries.map(([key, value]) => `${key}=${value}\n`).join("");
yield* fs.writeFileString(githubOutputPath, serialized, { flag: "a" });
yield* fs.writeFileString(githubOutputPath, serialized, { flag: "a" }).pipe(
Effect.mapError(
(cause) =>
new NightlyReleaseGitHubOutputAppendError({
outputPath: githubOutputPath,
cause,
}),
),
);
} else {
for (const [key, value] of entries) {
yield* Console.log(`${key}=${value}`);
@@ -131,7 +210,7 @@ const command = Command.make(
({ date, runNumber, sha, githubOutput, root }) =>
readDesktopBaseVersion(Option.getOrUndefined(root)).pipe(
Effect.map((baseVersion) => resolveNightlyReleaseMetadata(baseVersion, date, runNumber, sha)),
Effect.flatMap((metadata) => writeOutput(metadata, githubOutput)),
Effect.flatMap((metadata) => writeNightlyReleaseOutput(metadata, githubOutput)),
),
).pipe(Command.withDescription("Resolve nightly release version metadata."));
@@ -0,0 +1,213 @@
import { assert, it } from "@effect/vitest";
import * as ConfigProvider from "effect/ConfigProvider";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as PlatformError from "effect/PlatformError";
import * as Sink from "effect/Sink";
import * as Stream from "effect/Stream";
import { ChildProcessSpawner } from "effect/unstable/process";
import {
listGitTags,
resolvePreviousReleaseTag,
writePreviousReleaseTagOutput,
} from "./resolve-previous-release-tag.ts";
const encoder = new TextEncoder();
function mockHandle(options: {
readonly exitCode: number;
readonly stdout?: string;
readonly stderr?: string;
readonly stdoutError?: PlatformError.PlatformError;
readonly stderrError?: PlatformError.PlatformError;
}) {
return ChildProcessSpawner.makeHandle({
pid: ChildProcessSpawner.ProcessId(1),
exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(options.exitCode)),
isRunning: Effect.succeed(false),
kill: () => Effect.void,
unref: Effect.succeed(Effect.void),
stdin: Sink.drain,
stdout: options.stdoutError
? Stream.fail(options.stdoutError)
: Stream.make(encoder.encode(options.stdout ?? "")),
stderr: options.stderrError
? Stream.fail(options.stderrError)
: Stream.make(encoder.encode(options.stderr ?? "")),
all: Stream.empty,
getInputFd: () => Sink.drain,
getOutputFd: () => Stream.empty,
});
}
it.effect("selects the latest earlier stable tag and ignores nightlies", () =>
Effect.gen(function* () {
const previous = yield* resolvePreviousReleaseTag("stable", "v1.2.0", [
"v1.1.0",
"v1.1.1-nightly.20260619.1",
"v1.1.2",
"v1.2.0",
]);
assert.equal(previous, "v1.1.2");
}),
);
it.effect("accepts legacy nightly tags when selecting the previous nightly", () =>
Effect.gen(function* () {
const previous = yield* resolvePreviousReleaseTag("nightly", "v1.2.0-nightly.20260620.2", [
"nightly-v1.2.0-nightly.20260620.1",
"v1.1.0-nightly.20260619.9",
]);
assert.equal(previous, "nightly-v1.2.0-nightly.20260620.1");
}),
);
it.effect("reports the invalid tag with its release channel", () =>
Effect.gen(function* () {
const error = yield* resolvePreviousReleaseTag("nightly", "v1.2.0", []).pipe(Effect.flip);
assert.equal(error._tag, "InvalidReleaseTagError");
assert.equal(error.channel, "nightly");
assert.equal(error.currentTag, "v1.2.0");
assert.equal(error.message, "Invalid nightly release tag 'v1.2.0'.");
}),
);
it.effect("preserves git tag spawn context and the exact platform cause", () => {
const cause = PlatformError.systemError({
_tag: "NotFound",
module: "ChildProcess",
method: "spawn",
description: "git was not found",
});
return Effect.gen(function* () {
const error = yield* listGitTags("/repo").pipe(
Effect.scoped,
Effect.provideService(
ChildProcessSpawner.ChildProcessSpawner,
ChildProcessSpawner.make(() => Effect.fail(cause)),
),
Effect.flip,
);
if (error._tag !== "ReleaseTagListProcessError") {
return assert.fail(`Unexpected error: ${error._tag}`);
}
assert.equal(error.operation, "spawn");
assert.equal(error.executable, "git");
assert.equal(error.argumentCount, 2);
assert.equal(error.cwd, "/repo");
assert.strictEqual(error.cause, cause);
assert.notProperty(error, "args");
assert.notInclude(error.message, cause.message);
});
});
it.effect("distinguishes stdout and stderr read failures", () =>
Effect.gen(function* () {
for (const [stream, operation] of [
["stdout", "read-stdout"],
["stderr", "read-stderr"],
] as const) {
const cause = PlatformError.systemError({
_tag: "Unknown",
module: "ChildProcess",
method: stream,
description: `${stream} unavailable`,
});
const error = yield* listGitTags("/repo").pipe(
Effect.scoped,
Effect.provideService(
ChildProcessSpawner.ChildProcessSpawner,
ChildProcessSpawner.make(() =>
Effect.succeed(
mockHandle({
exitCode: 0,
...(stream === "stdout" ? { stdoutError: cause } : { stderrError: cause }),
}),
),
),
),
Effect.flip,
);
if (error._tag !== "ReleaseTagListProcessError") {
return assert.fail(`Unexpected error: ${error._tag}`);
}
assert.equal(error.operation, operation);
assert.strictEqual(error.cause, cause);
}
}),
);
it.effect("reports git tag non-zero exits without manufacturing a cause", () =>
Effect.gen(function* () {
const error = yield* listGitTags("/repo").pipe(
Effect.scoped,
Effect.provideService(
ChildProcessSpawner.ChildProcessSpawner,
ChildProcessSpawner.make(() =>
Effect.succeed(
mockHandle({
exitCode: 17,
stdout: "v1.2.3\n",
stderr: "fatal: repository unavailable\n",
}),
),
),
),
Effect.flip,
);
if (error._tag !== "ReleaseTagListProcessExitError") {
return assert.fail(`Unexpected error: ${error._tag}`);
}
assert.equal(error.executable, "git");
assert.equal(error.argumentCount, 2);
assert.equal(error.cwd, "/repo");
assert.equal(error.exitCode, 17);
assert.equal(error.stdoutLength, 7);
assert.equal(error.stderrLength, 30);
assert.notProperty(error, "cause");
assert.notProperty(error, "stdout");
assert.notProperty(error, "stderr");
}),
);
it.effect("preserves the GITHUB_OUTPUT append path and exact cause", () => {
const outputPath = "/tmp/previous-tag-github-output";
const appendCause = PlatformError.systemError({
_tag: "PermissionDenied",
module: "FileSystem",
method: "writeFileString",
pathOrDescriptor: outputPath,
});
return Effect.gen(function* () {
const appendError = yield* writePreviousReleaseTagOutput("v1.2.3", true).pipe(
Effect.provideService(
FileSystem.FileSystem,
FileSystem.makeNoop({
writeFileString: () => Effect.fail(appendCause),
}),
),
Effect.provideService(
ConfigProvider.ConfigProvider,
ConfigProvider.fromEnv({ env: { GITHUB_OUTPUT: outputPath } }),
),
Effect.flip,
);
if (appendError._tag !== "PreviousReleaseTagGitHubOutputAppendError") {
return assert.fail(`Unexpected error: ${appendError._tag}`);
}
assert.equal(appendError.outputPath, outputPath);
assert.strictEqual(appendError.cause, appendCause);
assert.notProperty(appendError, "contents");
assert.notInclude(appendError.message, appendCause.message);
});
});
+185 -38
View File
@@ -2,7 +2,6 @@
import * as NodeRuntime from "@effect/platform-node/NodeRuntime";
import * as NodeServices from "@effect/platform-node/NodeServices";
import * as Array from "effect/Array";
import * as Config from "effect/Config";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
@@ -15,6 +14,76 @@ import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
const ReleaseChannel = Schema.Literals(["stable", "nightly"]);
type ReleaseChannel = typeof ReleaseChannel.Type;
export class InvalidReleaseTagError extends Schema.TaggedErrorClass<InvalidReleaseTagError>()(
"InvalidReleaseTagError",
{
channel: ReleaseChannel,
currentTag: Schema.String,
},
) {
override get message(): string {
return `Invalid ${this.channel} release tag '${this.currentTag}'.`;
}
}
const NonNegativeInt = Schema.Int.check(Schema.isGreaterThanOrEqualTo(0));
const releaseTagListProcessContext = {
executable: Schema.Literal("git"),
argumentCount: NonNegativeInt,
cwd: Schema.String,
};
export class ReleaseTagListProcessError extends Schema.TaggedErrorClass<ReleaseTagListProcessError>()(
"ReleaseTagListProcessError",
{
...releaseTagListProcessContext,
operation: Schema.Literals(["spawn", "read-stdout", "read-stderr", "wait-for-exit"]),
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Failed to list release tags during process operation "${this.operation}".`;
}
}
export class ReleaseTagListProcessExitError extends Schema.TaggedErrorClass<ReleaseTagListProcessExitError>()(
"ReleaseTagListProcessExitError",
{
...releaseTagListProcessContext,
exitCode: Schema.Number,
stdoutLength: NonNegativeInt,
stderrLength: NonNegativeInt,
},
) {
override get message(): string {
return `Release tag listing exited with code ${this.exitCode}.`;
}
}
export class PreviousReleaseTagGitHubOutputConfigError extends Schema.TaggedErrorClass<PreviousReleaseTagGitHubOutputConfigError>()(
"PreviousReleaseTagGitHubOutputConfigError",
{
cause: Schema.Defect(),
},
) {
override get message(): string {
return "Failed to resolve the GITHUB_OUTPUT path for the previous release tag.";
}
}
export class PreviousReleaseTagGitHubOutputAppendError extends Schema.TaggedErrorClass<PreviousReleaseTagGitHubOutputAppendError>()(
"PreviousReleaseTagGitHubOutputAppendError",
{
outputPath: Schema.String,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Failed to append the previous release tag to ${this.outputPath}.`;
}
}
interface StableVersion {
readonly major: number;
readonly minor: number;
@@ -121,59 +190,122 @@ const parseNightlyTag = (tag: string): NightlyVersion | undefined => {
};
};
const resolvePreviousReleaseTag = (
export const resolvePreviousReleaseTag = (
channel: ReleaseChannel,
currentTag: string,
tags: ReadonlyArray<string>,
): string | undefined => {
if (channel === "stable") {
const current = parseStableTag(currentTag);
) =>
Effect.gen(function* () {
if (channel === "stable") {
const current = parseStableTag(currentTag);
if (!current) {
return yield* new InvalidReleaseTagError({ channel, currentTag });
}
const candidates = tags
.map((tag) => ({ tag, parsed: parseStableTag(tag) }))
.filter(
(entry): entry is { tag: string; parsed: StableVersion } => entry.parsed !== undefined,
)
.filter((entry) => compareStableVersions(entry.parsed, current) < 0)
.toSorted((left, right) => compareStableVersions(right.parsed, left.parsed));
return candidates[0]?.tag;
}
const current = parseNightlyTag(currentTag);
if (!current) {
throw new Error(`Invalid stable release tag '${currentTag}'.`);
return yield* new InvalidReleaseTagError({ channel, currentTag });
}
const candidates = tags
.map((tag) => ({ tag, parsed: parseStableTag(tag) }))
.map((tag) => ({ tag, parsed: parseNightlyTag(tag) }))
.filter(
(entry): entry is { tag: string; parsed: StableVersion } => entry.parsed !== undefined,
(entry): entry is { tag: string; parsed: NightlyVersion } => entry.parsed !== undefined,
)
.filter((entry) => compareStableVersions(entry.parsed, current) < 0)
.toSorted((left, right) => compareStableVersions(right.parsed, left.parsed));
.filter((entry) => compareNightlyVersions(entry.parsed, current) < 0)
.toSorted((left, right) => compareNightlyVersions(right.parsed, left.parsed));
return candidates[0]?.tag;
}
});
const current = parseNightlyTag(currentTag);
if (!current) {
throw new Error(`Invalid nightly release tag '${currentTag}'.`);
}
const candidates = tags
.map((tag) => ({ tag, parsed: parseNightlyTag(tag) }))
.filter((entry): entry is { tag: string; parsed: NightlyVersion } => entry.parsed !== undefined)
.filter((entry) => compareNightlyVersions(entry.parsed, current) < 0)
.toSorted((left, right) => compareNightlyVersions(right.parsed, left.parsed));
return candidates[0]?.tag;
};
const listGitTags = Effect.fn("listGitTags")(function* () {
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
const child = yield* spawner.spawn(ChildProcess.make("git", ["tag", "--list"]));
const tags = yield* child.stdout.pipe(
const collectStreamAsString = <E>(stream: Stream.Stream<Uint8Array, E>): Effect.Effect<string, E> =>
stream.pipe(
Stream.decodeText(),
Stream.runFold(
() => "",
(acc, chunk) => acc + chunk,
),
Effect.map(String.split(/\r?\n/)),
Effect.map(Array.map(String.trim)),
Effect.map(Array.filter(String.isNonEmpty)),
);
return tags;
export const listGitTags = Effect.fn("listGitTags")(function* (cwd = process.cwd()) {
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
const args = ["tag", "--list"] as const;
const context = {
executable: "git",
argumentCount: args.length,
cwd,
} as const;
const child = yield* spawner.spawn(ChildProcess.make("git", args, { cwd })).pipe(
Effect.mapError(
(cause) =>
new ReleaseTagListProcessError({
...context,
operation: "spawn",
cause,
}),
),
);
const [stdout, stderr, exitCode] = yield* Effect.all(
[
collectStreamAsString(child.stdout).pipe(
Effect.mapError(
(cause) =>
new ReleaseTagListProcessError({
...context,
operation: "read-stdout",
cause,
}),
),
),
collectStreamAsString(child.stderr).pipe(
Effect.mapError(
(cause) =>
new ReleaseTagListProcessError({
...context,
operation: "read-stderr",
cause,
}),
),
),
child.exitCode.pipe(
Effect.map(Number),
Effect.mapError(
(cause) =>
new ReleaseTagListProcessError({
...context,
operation: "wait-for-exit",
cause,
}),
),
),
],
{ concurrency: "unbounded" },
);
if (exitCode !== 0) {
return yield* new ReleaseTagListProcessExitError({
...context,
exitCode,
stdoutLength: stdout.length,
stderrLength: stderr.length,
});
}
return stdout.split(/\r?\n/).map(String.trim).filter(String.isNonEmpty);
});
const writeOutput = Effect.fn("writeOutput")(function* (
export const writePreviousReleaseTagOutput = Effect.fn("writePreviousReleaseTagOutput")(function* (
previousTag: string | undefined,
writeGithubOutput: boolean,
) {
@@ -181,8 +313,23 @@ const writeOutput = Effect.fn("writeOutput")(function* (
if (writeGithubOutput) {
const fs = yield* FileSystem.FileSystem;
const githubOutputPath = yield* Config.nonEmptyString("GITHUB_OUTPUT");
yield* fs.writeFileString(githubOutputPath, entry, { flag: "a" });
const githubOutputPath = yield* Config.nonEmptyString("GITHUB_OUTPUT").pipe(
Effect.mapError(
(cause) =>
new PreviousReleaseTagGitHubOutputConfigError({
cause,
}),
),
);
yield* fs.writeFileString(githubOutputPath, entry, { flag: "a" }).pipe(
Effect.mapError(
(cause) =>
new PreviousReleaseTagGitHubOutputAppendError({
outputPath: githubOutputPath,
cause,
}),
),
);
return;
}
@@ -205,8 +352,8 @@ const command = Command.make(
},
({ channel, currentTag, githubOutput }) =>
listGitTags().pipe(
Effect.map((tags) => resolvePreviousReleaseTag(channel, currentTag, tags)),
Effect.flatMap((previousTag) => writeOutput(previousTag, githubOutput)),
Effect.flatMap((tags) => resolvePreviousReleaseTag(channel, currentTag, tags)),
Effect.flatMap((previousTag) => writePreviousReleaseTagOutput(previousTag, githubOutput)),
),
).pipe(Command.withDescription("Resolve the previous release tag for a stable or nightly series."));
+131 -9
View File
@@ -19,16 +19,22 @@ const encoder = new TextEncoder();
const effectSmol = referenceRepos[0]!;
const alchemyEffect = referenceRepos[1]!;
function mockHandle() {
function mockHandle(
options: {
readonly exitCode?: number;
readonly stdout?: string;
readonly stderr?: string;
} = {},
) {
return ChildProcessSpawner.makeHandle({
pid: ChildProcessSpawner.ProcessId(1),
exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(0)),
exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(options.exitCode ?? 0)),
isRunning: Effect.succeed(false),
kill: () => Effect.void,
unref: Effect.succeed(Effect.void),
stdin: Sink.drain,
stdout: Stream.make(encoder.encode("done\n")),
stderr: Stream.empty,
stdout: Stream.make(encoder.encode(options.stdout ?? "done\n")),
stderr: Stream.make(encoder.encode(options.stderr ?? "")),
all: Stream.empty,
getInputFd: () => Sink.drain,
getOutputFd: () => Stream.empty,
@@ -37,6 +43,7 @@ function mockHandle() {
function mockSpawnerLayer(
commands: Array<{ readonly command: string; readonly args: ReadonlyArray<string> }>,
handle = mockHandle(),
) {
return Layer.succeed(
ChildProcessSpawner.ChildProcessSpawner,
@@ -49,7 +56,7 @@ function mockSpawnerLayer(
command: childProcess.command,
args: childProcess.args,
});
return Effect.succeed(mockHandle());
return Effect.succeed(handle);
}),
);
}
@@ -85,6 +92,75 @@ it.layer(NodeServices.layer)("sync-reference-repos", (it) => {
}),
);
it.effect("preserves version source read context and the filesystem cause", () =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const rootDir = yield* fs.makeTempDirectoryScoped({
prefix: "sync-reference-repos-read-error-",
});
const sourcePath = path.join(rootDir, effectSmol.versionSourcePath);
const error = yield* resolveReferenceRepoRef(effectSmol, rootDir, false).pipe(Effect.flip);
if (error._tag !== "ReferenceRepoVersionSourceError") {
assert.fail(`Unexpected error: ${error._tag}`);
}
assert.equal(error.operation, "read");
assert.equal(error.repoId, effectSmol.id);
assert.equal(error.sourcePath, sourcePath);
assert.ok(error.cause !== undefined);
assert.ok(!error.message.includes(String((error.cause as Error).message)));
}),
);
it.effect("preserves version source parse context and the schema cause", () =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const rootDir = yield* fs.makeTempDirectoryScoped({
prefix: "sync-reference-repos-parse-error-",
});
const sourcePath = path.join(rootDir, alchemyEffect.versionSourcePath);
yield* fs.makeDirectory(path.dirname(sourcePath), { recursive: true });
yield* fs.writeFileString(sourcePath, "{");
const error = yield* resolveReferenceRepoRef(alchemyEffect, rootDir, false).pipe(Effect.flip);
if (error._tag !== "ReferenceRepoVersionSourceError") {
assert.fail(`Unexpected error: ${error._tag}`);
}
assert.equal(error.operation, "parse");
assert.equal(error.repoId, alchemyEffect.id);
assert.equal(error.sourcePath, sourcePath);
assert.ok(error.cause !== undefined);
assert.ok(!error.message.includes(String((error.cause as Error).message)));
}),
);
it.effect("reports the unresolved package path without inventing a cause", () =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const rootDir = yield* fs.makeTempDirectoryScoped({
prefix: "sync-reference-repos-resolution-error-",
});
const sourcePath = path.join(rootDir, alchemyEffect.versionSourcePath);
yield* fs.makeDirectory(path.dirname(sourcePath), { recursive: true });
yield* fs.writeFileString(sourcePath, '{"dependencies":{}}');
const error = yield* resolveReferenceRepoRef(alchemyEffect, rootDir, false).pipe(Effect.flip);
if (error._tag !== "ReferenceRepoVersionResolutionError") {
assert.fail(`Unexpected error: ${error._tag}`);
}
assert.equal(error.repoId, alchemyEffect.id);
assert.equal(error.sourcePath, sourcePath);
assert.deepStrictEqual(error.packageVersionPath, ["dependencies", "alchemy"]);
assert.ok(!("cause" in error));
}),
);
it.effect("resolves the alchemy-effect tag from the relay package", () =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
@@ -171,10 +247,56 @@ it.layer(NodeServices.layer)("sync-reference-repos", (it) => {
dryRun: true,
}).pipe(Effect.flip);
assert.equal(
error.message,
"Unknown reference repo 'missing'. Expected one of: effect-smol, alchemy-effect.",
);
if (error._tag !== "ReferenceRepoSelectionError") {
assert.fail(`Unexpected error: ${error._tag}`);
}
assert.equal(error.repoId, "missing");
assert.deepStrictEqual(error.expectedRepoIds, ["effect-smol", "alchemy-effect"]);
assert.ok(!("cause" in error));
}),
);
it.effect("reports non-zero git exits without retaining process output", () => {
const commands: Array<{ readonly command: string; readonly args: ReadonlyArray<string> }> = [];
return Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const rootDir = yield* fs.makeTempDirectoryScoped({
prefix: "sync-reference-repos-exit-error-",
});
yield* fs.writeFileString(
path.join(rootDir, "pnpm-workspace.yaml"),
"catalog:\n effect: 4.0.0-beta.73\n",
);
const error = yield* syncReferenceRepos({ rootDir, repoId: "effect-smol" }).pipe(
Effect.provide(
mockSpawnerLayer(
commands,
mockHandle({ exitCode: 23, stderr: "subtree failed secret-token-value\n" }),
),
),
Effect.flip,
);
if (error._tag !== "ReferenceRepoGitSubtreeError") {
assert.fail(`Unexpected error: ${error._tag}`);
}
assert.equal(error.operation, "exit");
assert.equal(error.repoId, effectSmol.id);
assert.equal(error.action, "add");
assert.equal(error.repository, effectSmol.repository);
assert.equal(error.ref, "[email protected]");
assert.equal(error.rootDir, rootDir);
assert.equal(error.argumentCount, commands[0]?.args.length);
assert.equal(error.exitCode, 23);
assert.equal(error.stdoutLength, 5);
assert.equal(error.stderrLength, 34);
assert.notProperty(error, "args");
assert.notProperty(error, "stderr");
assert.notInclude(error.message, "secret-token-value");
assert.ok(!("cause" in error));
});
});
});
+110 -37
View File
@@ -3,7 +3,6 @@
import * as NodeRuntime from "@effect/platform-node/NodeRuntime";
import * as NodeServices from "@effect/platform-node/NodeServices";
import * as Console from "effect/Console";
import * as Data from "effect/Data";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Option from "effect/Option";
@@ -32,10 +31,74 @@ export interface ReferenceRepoSyncPlan {
readonly args: ReadonlyArray<string>;
}
export class ReferenceRepoSyncError extends Data.TaggedError("ReferenceRepoSyncError")<{
readonly message: string;
readonly cause?: unknown;
}> {}
export class ReferenceRepoSelectionError extends Schema.TaggedErrorClass<ReferenceRepoSelectionError>()(
"ReferenceRepoSelectionError",
{
repoId: Schema.String,
expectedRepoIds: Schema.Array(Schema.String),
},
) {
override get message(): string {
return `Unknown reference repo "${this.repoId}". Expected one of: ${this.expectedRepoIds.join(", ")}.`;
}
}
export class ReferenceRepoVersionSourceError extends Schema.TaggedErrorClass<ReferenceRepoVersionSourceError>()(
"ReferenceRepoVersionSourceError",
{
operation: Schema.Literals(["read", "parse"]),
repoId: Schema.String,
sourcePath: Schema.String,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Reference repo "${this.repoId}" version source operation "${this.operation}" failed for ${this.sourcePath}.`;
}
}
export class ReferenceRepoVersionResolutionError extends Schema.TaggedErrorClass<ReferenceRepoVersionResolutionError>()(
"ReferenceRepoVersionResolutionError",
{
repoId: Schema.String,
sourcePath: Schema.String,
packageVersionPath: Schema.Array(Schema.String),
},
) {
override get message(): string {
return `No version was found for reference repo "${this.repoId}" at ${this.sourcePath}:${this.packageVersionPath.join(".")}.`;
}
}
export class ReferenceRepoGitSubtreeError extends Schema.TaggedErrorClass<ReferenceRepoGitSubtreeError>()(
"ReferenceRepoGitSubtreeError",
{
operation: Schema.Literals(["spawn", "communicate", "exit"]),
repoId: Schema.String,
action: Schema.Literals(["add", "pull"]),
repository: Schema.String,
ref: Schema.String,
rootDir: Schema.String,
argumentCount: Schema.Number,
exitCode: Schema.optional(Schema.Number),
stdoutLength: Schema.optional(Schema.Number),
stderrLength: Schema.optional(Schema.Number),
cause: Schema.optional(Schema.Defect()),
},
) {
override get message(): string {
return `Git subtree ${this.action} for reference repo "${this.repoId}" failed during "${this.operation}".`;
}
}
export const ReferenceRepoSyncError = Schema.Union([
ReferenceRepoSelectionError,
ReferenceRepoVersionSourceError,
ReferenceRepoVersionResolutionError,
ReferenceRepoGitSubtreeError,
]);
export type ReferenceRepoSyncError = typeof ReferenceRepoSyncError.Type;
export const isReferenceRepoSyncError = Schema.is(ReferenceRepoSyncError);
const decodeJsonSource = Schema.decodeUnknownEffect(Schema.UnknownFromJsonString);
const decodeYamlSource = Schema.decodeEffect(fromYaml(Schema.Unknown));
@@ -61,26 +124,21 @@ function readNestedString(input: unknown, keys: ReadonlyArray<string>): string |
}
function decodeVersionSource(
repo: ReferenceRepo,
sourcePath: string,
content: string,
): Effect.Effect<unknown, ReferenceRepoSyncError> {
if (sourcePath.endsWith(".yaml") || sourcePath.endsWith(".yml")) {
return decodeYamlSource(content).pipe(
Effect.mapError(
(cause) =>
new ReferenceRepoSyncError({
message: `Unable to parse version source ${sourcePath}.`,
cause,
}),
),
);
}
return decodeJsonSource(content).pipe(
const decode =
repo.versionSourcePath.endsWith(".yaml") || repo.versionSourcePath.endsWith(".yml")
? decodeYamlSource
: decodeJsonSource;
return decode(content).pipe(
Effect.mapError(
(cause) =>
new ReferenceRepoSyncError({
message: `Unable to parse version source ${sourcePath}.`,
new ReferenceRepoVersionSourceError({
operation: "parse",
repoId: repo.id,
sourcePath,
cause,
}),
),
@@ -98,10 +156,9 @@ function getSelectedRepos(
return repo
? Effect.succeed([repo])
: Effect.fail(
new ReferenceRepoSyncError({
message: `Unknown reference repo '${repoId}'. Expected one of: ${referenceRepos
.map((candidate) => candidate.id)
.join(", ")}.`,
new ReferenceRepoSelectionError({
repoId,
expectedRepoIds: referenceRepos.map((candidate) => candidate.id),
}),
);
}
@@ -121,20 +178,22 @@ export const resolveReferenceRepoRef = Effect.fn("resolveReferenceRepoRef")(func
const versionSourceContent = yield* fs.readFileString(versionSourcePath).pipe(
Effect.mapError(
(cause) =>
new ReferenceRepoSyncError({
message: `Unable to read package version for '${repo.id}' from ${versionSourcePath}.`,
new ReferenceRepoVersionSourceError({
operation: "read",
repoId: repo.id,
sourcePath: versionSourcePath,
cause,
}),
),
);
const versionSource = yield* decodeVersionSource(repo.versionSourcePath, versionSourceContent);
const versionSource = yield* decodeVersionSource(repo, versionSourcePath, versionSourceContent);
const version = readNestedString(versionSource, repo.packageVersionPath);
if (!version) {
return yield* new ReferenceRepoSyncError({
message: `Unable to resolve package version for '${repo.id}' at ${repo.versionSourcePath}:${repo.packageVersionPath.join(
".",
)}.`,
return yield* new ReferenceRepoVersionResolutionError({
repoId: repo.id,
sourcePath: versionSourcePath,
packageVersionPath: repo.packageVersionPath,
});
}
@@ -163,11 +222,20 @@ export const planReferenceRepoSync = Effect.fn("planReferenceRepoSync")(function
const runGit = Effect.fn("runGit")(function* (rootDir: string, plan: ReferenceRepoSyncPlan) {
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
const errorContext = {
repoId: plan.repo.id,
action: plan.action,
repository: plan.repo.repository,
ref: plan.ref,
rootDir,
argumentCount: plan.args.length,
} as const;
const child = yield* spawner.spawn(ChildProcess.make("git", plan.args, { cwd: rootDir })).pipe(
Effect.mapError(
(cause) =>
new ReferenceRepoSyncError({
message: `Unable to start git subtree ${plan.action} for '${plan.repo.id}'.`,
new ReferenceRepoGitSubtreeError({
...errorContext,
operation: "spawn",
cause,
}),
),
@@ -182,16 +250,21 @@ const runGit = Effect.fn("runGit")(function* (rootDir: string, plan: ReferenceRe
).pipe(
Effect.mapError(
(cause) =>
new ReferenceRepoSyncError({
message: `Unable to run git subtree ${plan.action} for '${plan.repo.id}'.`,
new ReferenceRepoGitSubtreeError({
...errorContext,
operation: "communicate",
cause,
}),
),
);
if (exitCode !== 0) {
return yield* new ReferenceRepoSyncError({
message: `git subtree ${plan.action} failed for '${plan.repo.id}' with exit code ${exitCode}.\n${stderr.trim()}`,
return yield* new ReferenceRepoGitSubtreeError({
...errorContext,
operation: "exit",
exitCode,
stdoutLength: stdout.length,
stderrLength: stderr.length,
});
}
+107 -1
View File
@@ -1,16 +1,21 @@
import * as NodeServices from "@effect/platform-node/NodeServices";
import { assert, it } from "@effect/vitest";
import * as Config from "effect/Config";
import * as ConfigProvider from "effect/ConfigProvider";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Path from "effect/Path";
import * as PlatformError from "effect/PlatformError";
import * as Schema from "effect/Schema";
import { Command, CliError } from "effect/unstable/cli";
import * as TestConsole from "effect/testing/TestConsole";
import { fromJsonStringPretty } from "@t3tools/shared/schemaJson";
import {
ReleaseGitHubOutputConfigurationError,
ReleaseGitHubOutputWriteError,
ReleasePackageManifestError,
releasePackageFiles,
updateReleasePackageVersions,
updateReleasePackageVersionsCommand,
@@ -103,6 +108,73 @@ it.layer(ScriptTestLayer)("update-release-package-versions", (it) => {
}),
);
it.effect("preserves manifest read context and the filesystem cause", () =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const baseDir = yield* fs.makeTempDirectoryScoped({
prefix: "update-release-package-versions-read-error-",
});
const filePath = path.join(baseDir, releasePackageFiles[0]);
const error = yield* updateReleasePackageVersions("1.2.3", {
rootDir: baseDir,
}).pipe(Effect.flip);
assert.instanceOf(error, ReleasePackageManifestError);
assert.equal(error.operation, "read");
assert.equal(error.filePath, filePath);
assert.instanceOf(error.cause, PlatformError.PlatformError);
assert.equal(error.message, `Failed to read release package manifest '${filePath}'.`);
}),
);
it.effect("preserves manifest decode context and the schema cause", () =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const baseDir = yield* fs.makeTempDirectoryScoped({
prefix: "update-release-package-versions-decode-error-",
});
const filePath = path.join(baseDir, releasePackageFiles[0]);
yield* writePackageJsonFixtures(baseDir, "0.0.1");
yield* fs.writeFileString(filePath, "not json");
const error = yield* updateReleasePackageVersions("1.2.3", {
rootDir: baseDir,
}).pipe(Effect.flip);
assert.equal(error.operation, "decode");
assert.equal(error.filePath, filePath);
assert.isTrue(Schema.isSchemaError(error.cause));
assert.equal(error.message, `Failed to decode release package manifest '${filePath}'.`);
}),
);
it.effect("preserves manifest write context and the filesystem cause", () =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const baseDir = yield* fs.makeTempDirectoryScoped({
prefix: "update-release-package-versions-write-error-",
});
const filePath = path.join(baseDir, releasePackageFiles[0]);
yield* writePackageJsonFixtures(baseDir, "0.0.1");
yield* fs.chmod(filePath, 0o400);
const error = yield* updateReleasePackageVersions("1.2.3", {
rootDir: baseDir,
}).pipe(Effect.flip, Effect.ensuring(fs.chmod(filePath, 0o600).pipe(Effect.orDie)));
assert.equal(error.operation, "write");
assert.equal(error.filePath, filePath);
assert.instanceOf(error.cause, PlatformError.PlatformError);
assert.equal(error.message, `Failed to write release package manifest '${filePath}'.`);
}),
);
it.effect("accepts flags before the version positional and appends changed output", () =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
@@ -164,9 +236,43 @@ it.layer(ScriptTestLayer)("update-release-package-versions", (it) => {
Effect.flip,
);
assert.instanceOf(error, ReleaseGitHubOutputConfigurationError);
assert.instanceOf(error.cause, Config.ConfigError);
assert.equal(
error.message,
'SchemaError(Expected string, got undefined\n at ["GITHUB_OUTPUT"])',
"Failed to resolve GITHUB_OUTPUT for release package version output.",
);
}),
);
it.effect("preserves GITHUB_OUTPUT write context and the filesystem cause", () =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const baseDir = yield* fs.makeTempDirectoryScoped({
prefix: "update-release-package-versions-cli-output-error-",
});
yield* writePackageJsonFixtures(baseDir, "0.0.1");
const error = yield* runCli(["4.0.0", "--root", baseDir, "--github-output"]).pipe(
Effect.provide(
ConfigProvider.layer(
ConfigProvider.fromEnv({
env: {
GITHUB_OUTPUT: baseDir,
},
}),
),
),
Effect.flip,
);
assert.instanceOf(error, ReleaseGitHubOutputWriteError);
assert.equal(error.filePath, baseDir);
assert.instanceOf(error.cause, PlatformError.PlatformError);
assert.equal(
error.message,
`Failed to append release package version output to '${baseDir}'.`,
);
}),
);
+91 -5
View File
@@ -12,6 +12,40 @@ import * as Schema from "effect/Schema";
import { Argument, Command, Flag } from "effect/unstable/cli";
import { fromJsonStringPretty } from "@t3tools/shared/schemaJson";
export class ReleasePackageManifestError extends Schema.TaggedErrorClass<ReleasePackageManifestError>()(
"ReleasePackageManifestError",
{
operation: Schema.Literals(["read", "decode", "encode", "write"]),
filePath: Schema.String,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Failed to ${this.operation} release package manifest '${this.filePath}'.`;
}
}
export class ReleaseGitHubOutputConfigurationError extends Schema.TaggedErrorClass<ReleaseGitHubOutputConfigurationError>()(
"ReleaseGitHubOutputConfigurationError",
{ cause: Schema.Defect() },
) {
override get message(): string {
return "Failed to resolve GITHUB_OUTPUT for release package version output.";
}
}
export class ReleaseGitHubOutputWriteError extends Schema.TaggedErrorClass<ReleaseGitHubOutputWriteError>()(
"ReleaseGitHubOutputWriteError",
{
filePath: Schema.String,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Failed to append release package version output to '${this.filePath}'.`;
}
}
export const releasePackageFiles = [
"apps/server/package.json",
"apps/desktop/package.json",
@@ -39,13 +73,50 @@ export const updateReleasePackageVersions = Effect.fn("updateReleasePackageVersi
for (const relativePath of releasePackageFiles) {
const filePath = path.join(rootDir, relativePath);
const packageJson = yield* fs.readFileString(filePath).pipe(Effect.flatMap(decodePackageJson));
const packageJsonText = yield* fs.readFileString(filePath).pipe(
Effect.mapError(
(cause) =>
new ReleasePackageManifestError({
operation: "read",
filePath,
cause,
}),
),
);
const packageJson = yield* decodePackageJson(packageJsonText).pipe(
Effect.mapError(
(cause) =>
new ReleasePackageManifestError({
operation: "decode",
filePath,
cause,
}),
),
);
if (packageJson.version === version) {
continue;
}
const packageJsonString = yield* encodePackageJson({ ...packageJson, version });
yield* fs.writeFileString(filePath, `${packageJsonString}\n`);
const packageJsonString = yield* encodePackageJson({ ...packageJson, version }).pipe(
Effect.mapError(
(cause) =>
new ReleasePackageManifestError({
operation: "encode",
filePath,
cause,
}),
),
);
yield* fs.writeFileString(filePath, `${packageJsonString}\n`).pipe(
Effect.mapError(
(cause) =>
new ReleasePackageManifestError({
operation: "write",
filePath,
cause,
}),
),
);
changed = true;
}
@@ -54,8 +125,23 @@ export const updateReleasePackageVersions = Effect.fn("updateReleasePackageVersi
const writeGithubOutput = Effect.fn("writeGithubOutput")(function* (changed: boolean) {
const fs = yield* FileSystem.FileSystem;
const githubOutputPath = yield* Config.nonEmptyString("GITHUB_OUTPUT");
yield* fs.writeFileString(githubOutputPath, `changed=${changed}\n`, { flag: "a" });
const githubOutputPath = yield* Config.nonEmptyString("GITHUB_OUTPUT").pipe(
Effect.mapError(
(cause) =>
new ReleaseGitHubOutputConfigurationError({
cause,
}),
),
);
yield* fs.writeFileString(githubOutputPath, `changed=${changed}\n`, { flag: "a" }).pipe(
Effect.mapError(
(cause) =>
new ReleaseGitHubOutputWriteError({
filePath: githubOutputPath,
cause,
}),
),
);
});
export const updateReleasePackageVersionsCommand = Command.make(