export { B as BucketConfig, a as BucketNode, b as BucketRegion, C as CompileResult, D as DatabaseConfig, c as DatabaseNode, E as EnvironmentConfig, F as FUNCTION_SOURCE_MAX_BYTES, d as FunctionConfigInput, e as FunctionRuntime, G as GraphCompileOptions, f as GraphIndex, P as ProjectDefinition, g as ProjectNode, R as RAILWAY_GRAPH_VERSION, h as RailwayGraph, i as RailwayProgram, j as RailwayResourceName, k as RailwayServiceName, l as ResourceAddress, m as ResourceNode, S as ServiceConfigInput, n as ServiceNode, V as VariableValue, o as bucket, p as createRailwayContext, q as database, r as define, s as defineRailway, t as empty, u as fn, v as github, w as group, x as iac, y as image, z as indexGraph, A as mongo, H as mysql, I as postgres, J as project, K as redis, L as ref, M as resourceAddress, N as service, O as template, Q as validateGraph, T as volume } from './index-CweUhAOc.js'; /** * Opt-in verbose logging. A no-op unless enabled, so call sites stay * branch-free: `config.log(...)` does nothing when verbose is off. */ type Logger = (message: string) => void; declare const DEFAULT_RAILWAY_GRAPHQL_ENDPOINT = "https://backboard.railway.com/graphql/v2"; type RailwayAuthType = "bearer" | "project-token"; interface RailwayClientConfig { token?: string; authType?: RailwayAuthType; endpoint?: string; /** Alias used by IaC flows. Prefer endpoint for the stable SDK surface. */ graphqlEndpoint?: string; fetch?: typeof fetch; /** * WebSocket constructor used to stream exec output. Defaults to the global * `WebSocket` (available in Node >= 22, browsers, Deno, and edge runtimes); * pass an implementation (e.g. the `ws` package) where no global exists. */ webSocketImpl?: WebSocketConstructor; /** * tcp-proxy exec WebSocket endpoint. Defaults to the value derived from * `endpoint` (`backboard.` → `wss://ssh.:2226/ws/exec`); * override for non-standard deployments. */ tcpProxyWsEndpoint?: string; /** * Print human-readable progress to stderr (requests, polling, lifecycle). * Also enabled by `RAILWAY_VERBOSE`. Tokens and env values are never logged. */ verbose?: boolean; } /** Structural constructor type satisfied by native WebSocket and the `ws` package. */ type WebSocketConstructor = new (url: string, protocols?: string | string[]) => unknown; interface NormalizedRailwayClientConfig { token: string; authType: RailwayAuthType; endpoint: string; fetch: typeof fetch; webSocketImpl?: WebSocketConstructor | undefined; tcpProxyWsEndpoint: string; log: Logger; } interface RailwayGraphQLErrorItem { message: string; path?: readonly (string | number)[]; extensions?: Record; [key: string]: unknown; } declare class RailwayError extends Error { constructor(message: string, options?: ErrorOptions); } declare class RailwayAuthError extends RailwayError { readonly variable: string; constructor(variable: string, message?: string, options?: ErrorOptions); } /** A WebSocket or network transport failure. */ declare class RailwayConnectionError extends RailwayError { readonly closeCode: number | undefined; constructor(args: { message: string; closeCode?: number; cause?: unknown; }); } /** * The exec connection failed before any command was sent, so nothing ran in the * sandbox and the exec is safe to retry. */ declare class ExecNotStartedError extends RailwayConnectionError { } /** * The tcp-proxy closed the exec socket in answer to `exec_hello` without * advertising capabilities: it predates exec control. No command was sent, but * retrying the same request cannot succeed, so this is not an * `ExecNotStartedError`. */ declare class ExecControlUnsupportedError extends RailwayConnectionError { } /** Stable code backboard sets in error extensions when an apply's base config is stale. */ declare const STALE_ENVIRONMENT_BASE_CODE = "STALE_ENVIRONMENT_BASE"; /** Thrown by IaC apply when the environment changed since the plan's base snapshot. */ declare class StaleEnvironmentError extends RailwayError { } declare class RailwayGraphQLError extends RailwayError { readonly status: number; readonly errors: readonly RailwayGraphQLErrorItem[]; readonly responseBody: unknown; constructor(args: { message: string; status: number; errors?: readonly RailwayGraphQLErrorItem[]; responseBody?: unknown; }); } /** Controls a sandbox's access to the environment's private network. */ type SandboxNetworkIsolation$1 = /** Peer-isolated with public NAT egress only; no access to the environment's private network. Default. */ 'ISOLATED' /** Joins the environment's private network. */ | 'PRIVATE'; /** Whether a session is an interactive shell or a one-off exec command. */ type SandboxSessionKind = 'EXEC' | 'SHELL'; type SandboxStatus$1 = 'CREATING' | 'DESTROYED' | 'DESTROYING' | 'FAILED' | 'RUNNING'; type RailwaySandboxFieldsFragment = { __typename?: 'Sandbox'; id: string; status: SandboxStatus$1; networkIsolation: SandboxNetworkIsolation$1; environmentId: string; region: string; idleTimeoutMinutes?: number | null; createdAt: string; domains: Array<{ __typename?: 'SandboxDomain'; prefix: string; port: number; domain: string; }>; }; type RailwaySandboxCheckpointFieldsFragment = { __typename?: 'SandboxCheckpoint'; id: string; key: string; environmentId: string; createdAt: string; }; type RailwaySandboxSessionFieldsFragment = { __typename?: 'SandboxSession'; name: string; kind: SandboxSessionKind; attached: boolean; command: string; foregroundActive?: boolean | null; createdAt?: string | null; runState: { __typename?: 'SandboxSessionRunState'; running: boolean; exitCode: number; exitedAt?: string | null; }; }; type RailwaySandboxExecMutation = { __typename?: 'Mutation'; sandboxExec: { __typename?: 'SandboxExecResult'; exitCode: number; stdout: string; stderr: string; truncated: boolean; timedOut: boolean; }; }; type SandboxStatus = RailwaySandboxFieldsFragment["status"]; type SandboxNetworkIsolation = RailwaySandboxFieldsFragment["networkIsolation"]; type SandboxDomain = RailwaySandboxFieldsFragment["domains"][number]; type SandboxInfo = RailwaySandboxFieldsFragment; /** Final outcome of an exec; identical shape for short and long-running commands. */ interface ExecResult { /** Process exit code; -1 means terminated by a signal (e.g. after `kill()`). */ exitCode: number | null; stdout: string; stderr: string; /** True when captured stdout or stderr exceeded maxOutputBytes. Callbacks still receive all output. */ truncated: boolean; /** True when the client-side `timeoutSec` deadline killed the command. */ timedOut: boolean; } /** * A bootable snapshot of a sandbox's disk. `key` is the user-given name for * checkpoints captured with `checkpoint`, or the recipe hash for built ones. */ type SandboxCheckpointInfo = RailwaySandboxCheckpointFieldsFragment; /** vCPU and memory for one sandbox. Omitted fields use the workspace's sandbox default. */ interface SandboxResources { /** vCPUs; fractional values such as `0.5` are allowed. Capped at the workspace's VM maximum. */ cpu?: number; /** Memory in decimal GB (1 GB = 1,000,000,000 bytes). Capped at the workspace's VM maximum. */ memoryGB?: number; } /** A shell or exec session inside a sandbox, live or recently exited. */ interface SandboxSessionInfo { /** Stable session name; pass it as `exec({ sessionName })` to reattach. */ name: string; /** `SHELL` for an interactive shell, `EXEC` for a one-off command. */ kind: RailwaySandboxSessionFieldsFragment["kind"]; /** Whether the session's process is still alive. */ running: boolean; /** Exit code once the process has exited; null while it runs. */ exitCode: number | null; /** When the process exited (ISO timestamp); null while it runs. */ exitedAt: string | null; /** Whether a client is connected right now. */ attached: boolean; /** The command an exec session runs; empty for an interactive shell. */ command: string; /** For a shell, whether a foreground program holds the terminal; null when unknown or not a shell. */ foregroundActive: boolean | null; /** When the session started (ISO timestamp); null when the runtime does not report it. */ createdAt: string | null; } /** Options for `sandbox.execHttp`. */ interface ExecHttpOptions { /** Server-side deadline in whole seconds. Defaults to 2 minutes; capped at 10 minutes. */ timeoutSec?: number; } /** * Result of `sandbox.execHttp`. Each stream is cut at 16,000 bytes (`truncated`). On a * server timeout `timedOut` is true and `exitCode` is -1. */ type ExecHttpResult = RailwaySandboxExecMutation["sandboxExec"]; /** Knobs shared by every sandbox-creating call: `create`, `create(template)`, `create(checkpoint)`, and `fork`. */ interface SandboxCreationOptions { /** * Minutes without activity before the sandbox is destroyed. Defaults to the * plan's default. `0` (or any value <= 0) means never idle out; only some plans * allow it, and create fails with the allowed range otherwise. */ idleTimeoutMinutes?: number; /** vCPU and memory. Forks and checkpoint restores take their own value, not the source's. */ resources?: SandboxResources; networkIsolation?: SandboxNetworkIsolation; /** * Railway-provided HTTP domains to publish. Requires `networkIsolation: "PRIVATE"`. * Prefix is generated from the project name when omitted. */ domains?: Array<{ port: number; prefix?: string; }>; /** * Region where the sandbox should run. Uses the platform default when omitted. * Forks, templates and checkpoints boot where their data lives; omit this for * them, since a different region is rejected. */ region?: string; /** Runtime env baked into the sandbox, available to every command. Values may use Railway references (e.g. `${{shared.FOO}}`). */ env?: Record; } interface CreateOptions extends RailwayClientConfig, SandboxCreationOptions { /** * Environment to work in. Defaults to `RAILWAY_ENVIRONMENT_ID`, then to the * project token's environment; required with a bearer (account/workspace) token. */ environmentId?: string; } type ForkOptions = SandboxCreationOptions; interface ConnectOptions extends RailwayClientConfig { /** * Environment to work in. Defaults to `RAILWAY_ENVIRONMENT_ID`, then to the * project token's environment; required with a bearer (account/workspace) token. */ environmentId?: string; } interface ListOptions extends RailwayClientConfig { /** * Environment to work in. Defaults to `RAILWAY_ENVIRONMENT_ID`, then to the * project token's environment; required with a bearer (account/workspace) token. */ environmentId?: string; first?: number; after?: string; } /** Reattach to an exec started earlier (its name comes from `ExecHandle.sessionName`). */ interface ExecReattachTarget { sessionName: string; } type ExecTarget = string | ExecReattachTarget; /** Signal names accepted by `ExecHandle.kill()` (sent to the process group). */ type ExecSignal = "HUP" | "INT" | "QUIT" | "KILL" | "TERM"; /** Host-to-command stdin. Await writes for backpressure; end sends EOF. */ interface ExecStdin { write(data: string | Uint8Array): Promise; end(): Promise; } interface ExecOptions { /** * Kill the command after this many seconds and resolve with * `timedOut: true`. Sends TERM, escalating to KILL after 5 seconds; a * confirmed kill reports `exitCode: -1`, and an unconfirmed one `null`. The * deadline starts once the command has been sent. */ timeoutSec?: number; /** Abort setup or terminate and reject with the signal's reason. Unconfirmed termination rejects with a connection error. */ signal?: AbortSignal; /** * Keep stdin open for handle.stdin.write/end. Defaults to false (immediate EOF). * Requires exec control; an older tcp-proxy rejects with ExecControlUnsupportedError. */ stdin?: boolean; /** * Skip durable session creation. Cannot be reattached or detached. Fresh execs only. * Requires exec control (signal delivery and process-group cleanup when the * attachment disconnects); an older tcp-proxy rejects with ExecControlUnsupportedError. */ ephemeral?: boolean; /** Capture output in the result (default true). Set false for callback-only streaming. */ captureOutput?: boolean; /** * Maximum captured UTF-8 bytes per stream; unbounded by default. Past it the * result sets `truncated`. Callbacks are not capped. */ maxOutputBytes?: number; /** * Working directory for the command (the sandbox default is `/`). * The exec fails if the directory does not exist. * Fresh execs only — rejected on reattach (`exec({ sessionName })`). */ cwd?: string; /** * Extra environment variables for this command, layered over the sandbox's * own env (these take precedence). Fresh execs only — rejected on reattach * (`exec({ sessionName })`). */ env?: Record; /** Receives each stdout chunk as it arrives, even beyond `maxOutputBytes`. A throw rejects the exec. */ onStdout?: (chunk: string) => void; /** Receives each stderr chunk as it arrives, even beyond `maxOutputBytes`. A throw rejects the exec. */ onStderr?: (chunk: string) => void; /** * On reattach (`exec({ sessionName })`), set `true` to resume from the * server's last-read cursor — exact, but lossy if a previous reading client * didn't keep up before detaching. Defaults to `false`: replay all retained * logs for the session (lossless, may repeat output an earlier reader saw). * Ignored on a fresh exec. */ resumeFromLastRead?: boolean; } /** A directory entry or stat result from the sandbox filesystem. */ interface SandboxFileEntry { /** Base name (no directory prefix). */ name: string; /** Size in bytes. */ size: number; /** * File mode. The low 9 bits (`mode & 0o777`) are the POSIX permission * bits; higher bits encode the file type in a non-POSIX layout, so use * `isDir` rather than masking type bits. */ mode: number; isDir: boolean; /** Modification time, RFC 3339 UTC. */ modTime: string; } type FileReadFormat = "text" | "bytes" | "stream"; interface FileReadOptions { /** Start reading at this non-negative byte offset. Mutually exclusive with `fromEnd`. */ offset?: number; /** Read at most this many bytes (to EOF when omitted). Must be positive. */ length?: number; /** Read the last `length` bytes (a tail read). Requires `length`. */ fromEnd?: boolean; } /** * Content accepted by `files.write`. Streams and async iterables upload * without buffering, so pushes larger than memory are safe, but they are * one-shot: a session dropped mid-stream can't be retried. Pass a factory * (`() => stream`) when the content can be produced again; the write is then * retried automatically like the in-memory forms. */ type FileWriteData = string | Uint8Array | ArrayBuffer | Blob | ReadableStream | AsyncIterable | (() => ReadableStream | AsyncIterable); interface FileWriteOptions { /** * POSIX permission bits for the file (e.g. `0o755`), applied right after * the upload completes. Files default to `0644` when omitted. */ mode?: number; } interface TemplateBuildOptions extends RailwayClientConfig { /** * Environment to work in. Defaults to `RAILWAY_ENVIRONMENT_ID`, then to the * project token's environment; required with a bearer (account/workspace) token. */ environmentId?: string; /** Region the build sandbox runs in; sandboxes created from the template boot there. */ region?: string; } /** Connection/environment options for the checkpoint statics (`Sandbox.checkpoints` etc.). */ interface CheckpointOptions extends RailwayClientConfig { /** * Environment to work in. Defaults to `RAILWAY_ENVIRONMENT_ID`, then to the * project token's environment; required with a bearer (account/workspace) token. */ environmentId?: string; } /** Immutable sandbox base recipe returned by `Sandbox.template()`. */ interface SandboxTemplate { /** Add a shell command build step. */ run(command: string): SandboxTemplate; /** Install Debian packages with apt. */ withPackages(...packages: string[]): SandboxTemplate; /** * Set build-time environment variables available to the build instructions. * Values may use Railway references (e.g. `${{shared.FOO}}`), resolved at * build time. Build-time only — runtime env comes from `create({ env })`. */ withEnv(vars: Record): SandboxTemplate; /** Set the working directory for later build steps. */ workdir(dir: string): SandboxTemplate; /** Build the template before creating sandboxes from it. */ build(options?: TemplateBuildOptions): Promise; } /** * An in-flight exec. Awaiting it (or any Promise method) yields the final * `ExecResult`; `sessionName` and `kill()` manage the command while it runs. */ declare class ExecHandle implements Promise { #private; /** Durable session name for this exec; reattach via `exec({ sessionName })`. */ readonly sessionName: Promise; /** Writable only when exec was started with stdin: true. */ readonly stdin: ExecStdin; readonly [Symbol.toStringTag] = "ExecHandle"; /** Constructed by `Sandbox.exec`; not constructible from outside the SDK. */ private constructor(); then(onfulfilled?: ((value: ExecResult) => TResult1 | PromiseLike) | null, onrejected?: ((reason: unknown) => TResult2 | PromiseLike) | null): Promise; catch(onrejected?: ((reason: unknown) => TResult | PromiseLike) | null): Promise; finally(onfinally?: (() => void) | null): Promise; /** The final result as a plain promise; identical to awaiting the handle. */ result(): Promise; /** * Terminate the running command with a signal (default `TERM`) delivered to * its process group — a real kill, regardless of durable sessions. The handle * then settles with the command's exit (a signalled process reports exit code * `-1`). To stop streaming WITHOUT ending the command, use `detach()`. */ kill(signal?: ExecSignal): Promise; /** * Stop streaming and close the WebSocket without ending the command — the * durable session keeps running server-side. Resolves with its `sessionName` * so you can reattach later via `exec({ sessionName })`; rejects if the server * assigned no durable session (reattach is impossible). The handle itself * settles with the output captured up to the detach. */ detach(): Promise; } /** * File operations on a live sandbox, exposed as `sandbox.files`. Operations * run one at a time per file-session connection (the server serves one * request per connection), but connections are pooled: a finished * operation's connection lingers briefly and the next operation reuses it * instead of minting a new token and dialing again. Concurrent operations * still run independently on their own connections. * * Paths are absolute within the sandbox filesystem. Content streams in * 64KB frames both ways: pushes accept streams without buffering, and * `read(path, { format: "stream" })` holds at most one transfer segment in * memory, so files larger than memory transfer safely. */ declare class SandboxFiles { #private; /** Constructed by `Sandbox#files`; not constructible from outside the SDK. */ private constructor(); /** Read a file as text (UTF-8). */ read(path: string, options?: FileReadOptions & { format?: "text"; }): Promise; /** Read a file as raw bytes. */ read(path: string, options: FileReadOptions & { format: "bytes"; }): Promise; /** * Read a file as a stream of byte chunks. Memory stays bounded regardless * of file size: a consumer slower than the network holds back the transfer * rather than buffering it. Cancelling the stream aborts the transfer. * Errors after the stream is returned (including a missing file) surface * through the stream. */ read(path: string, options: FileReadOptions & { format: "stream"; }): Promise>; /** * Write a file, creating it (and truncating any existing content). Missing * parent directories are created automatically. Strings, bytes, blobs, and * factory sources upload with retry if the session drops mid-transfer; * bare streams and async iterables upload unbuffered but are one-shot, so * a session dropped mid-stream surfaces as `RailwayConnectionError` (and a * partial file may remain at `path`). * * Files are created `0644`; pass `mode` to set permissions (applied right * after the upload completes). */ write(path: string, data: FileWriteData, options?: FileWriteOptions): Promise; /** List a directory (entries carry name, size, mode, and modify time). */ list(path: string): Promise; /** Stat a path (follows symlinks). Throws `SandboxFileNotFoundError` if absent. */ stat(path: string): Promise; /** Whether a path exists (file or directory). */ exists(path: string): Promise; /** Create a directory, including missing parents (like `mkdir -p`). */ mkdir(path: string): Promise; /** * Remove a file or empty directory. For recursive deletes use * `sandbox.exec("rm -rf ...")`. */ remove(path: string): Promise; /** Rename (move) a file or directory within the sandbox. */ rename(oldPath: string, newPath: string): Promise; } /** * A live Railway sandbox. There is no separate client: a sandbox always comes * from somewhere — nothing (`Sandbox.create`), an id (`Sandbox.connect`), a * reusable base (`Sandbox.template()`), or a saved checkpoint * (`Sandbox.create(name)`). The constructor is private; use the * static factories. */ declare class Sandbox implements AsyncDisposable { #private; private constructor(); get id(): string; get status(): SandboxStatus; /** Network access mode: `ISOLATED` (NAT egress only) or `PRIVATE` (joins the environment private network). */ get networkIsolation(): SandboxNetworkIsolation; /** Railway-provided HTTP domains published for this sandbox. Empty when none. */ get domains(): SandboxDomain[]; get environmentId(): string; get region(): string; get idleTimeoutMinutes(): number | null; get createdAt(): string; /** Return a new immutable sandbox template. */ static template(): SandboxTemplate; /** Boot from a saved checkpoint (one captured with `checkpoint`). */ static create(checkpointName: string, options?: CreateOptions): Promise; static create(template: SandboxTemplate, options?: CreateOptions): Promise; static create(source: Sandbox, options?: ForkOptions): Promise; static create(options?: CreateOptions): Promise; static connect(id: string, options?: ConnectOptions): Promise; static list(options?: ListOptions): Promise; /** List the environment's named checkpoints (newest first). */ static checkpoints(options?: CheckpointOptions): Promise; /** Rename a checkpoint by id; new sandboxes boot from it via the new name. */ static renameCheckpoint(id: string, name: string, options?: CheckpointOptions): Promise; /** Delete a checkpoint by id (find it by `key` via `Sandbox.checkpoints`). */ static deleteCheckpoint(id: string, options?: CheckpointOptions): Promise; /** * Run a command. Awaiting the handle resolves the final `ExecResult` — * short commands return directly, long-running ones transparently stream * output (see `ExecOptions.onStdout`/`onStderr`) until the command exits. * The handle also exposes `sessionName` and `kill()`. A `timeoutSec` deadline * kills the command and resolves with `timedOut: true` rather than * rejecting. */ exec(command: string, options?: ExecOptions): ExecHandle; /** Reattach to a running exec by session name; resumes the retained output. */ exec(target: ExecReattachTarget, options?: ExecOptions): ExecHandle; /** * File operations on this sandbox's filesystem: `read`, `write`, `list`, * `stat`, `exists`, `mkdir`, `remove`, `rename`. Reads and writes stream, * so files larger than memory transfer safely. */ get files(): SandboxFiles; /** * Fork this running sandbox into a new, independent one. Clones the * filesystem (a fresh boot, not live processes) into the same environment. */ fork(options?: ForkOptions): Promise; /** * Capture this sandbox's current disk into a reusable named checkpoint, * bootable as soon as this resolves. The sandbox must be running. Reusing an * existing name replaces that checkpoint. Boot new sandboxes from it with * `Sandbox.create(name)`; they start in this sandbox's region. */ checkpoint(name: string): Promise; destroy(): Promise; /** * Shells and exec sessions in this sandbox, running or recently exited. * Reattach to one with `exec({ sessionName })`. Resolves null when the * sandbox's runtime cannot report sessions. */ sessions(): Promise; /** * Run a command in one HTTPS request and get its result. No streaming, stdin, * or cancellation: use it where a WebSocket isn't practical (short-lived * functions, HTTP-only harnesses), and `exec` everywhere else. Each stream is cut at 16,000 bytes; the server timeout is * 2 minutes by default and 10 at most. */ execHttp(command: string, options?: ExecHttpOptions): Promise; /** Reset the idle countdown and refresh this handle. Does not change the configured timeout. */ heartbeat(): Promise; /** Re-reads the sandbox to refresh `status` and other fields in place. */ refresh(): Promise; [Symbol.asyncDispose](): Promise; toJSON(): SandboxInfo; } /** The exec transport failed before a valid remote exit; retained output may be incomplete. */ declare class ExecInterruptedError extends RailwayConnectionError { readonly stdout: string; readonly stderr: string; constructor(args: { closeCode?: number; reason: string; stdout: string; stderr: string; cause?: unknown; }); } declare class SandboxNotFoundError extends RailwayError { readonly id: string; readonly environmentId: string; constructor(args: { id: string; environmentId: string; }); } /** A sandbox reached FAILED/DESTROYING/DESTROYED before becoming RUNNING. */ declare class SandboxFailedError extends RailwayError { readonly id: string; readonly status: SandboxStatus; constructor(args: { id: string; status: SandboxStatus; }); } /** A server-side template build finished in the FAILED state. */ declare class SandboxTemplateBuildError extends RailwayError { readonly templateId: string; readonly environmentId: string; constructor(args: { templateId: string; environmentId: string; }); } /** A file operation was rejected by the sandbox (the message is the VM's error text). */ declare class SandboxFilesError extends RailwayError { readonly operation: string; readonly path: string; constructor(args: { operation: string; path: string; message: string; }); } /** The path does not exist in the sandbox. */ declare class SandboxFileNotFoundError extends SandboxFilesError { } /** A readiness wait timed out. */ declare class SandboxTimeoutError extends RailwayError { readonly resource: "sandbox" | "template"; readonly id: string; readonly lastStatus: string; readonly timeoutMs: number; constructor(args: { resource: "sandbox" | "template"; id: string; lastStatus: string; timeoutMs: number; }); } /** Radar-style attribute clause reused by signal expressions. */ type RadarOperator = "eq" | "neq" | "gt" | "lt" | "gte" | "lte" | "in_list" | "not_in_list" | "contains" | "not_contains" | "matches"; interface RadarClause { attr: string; op: RadarOperator; value?: string | number | boolean; list?: string; match?: "exact" | "substring"; } /** Percentage rollout: bucket(attr) compared to a threshold in [0, 1]. */ interface SignalBucketCompare { bucket: { attr: string; salt?: string; }; op: "lt" | "lte" | "gt" | "gte"; value: number; } type SignalExpression = { and: SignalExpression[]; } | { or: SignalExpression[]; } | { not: SignalExpression; } | RadarClause | SignalBucketCompare; type SignalType = "bool" | "string" | "number" | "json"; type SignalSource = { type: "literal"; value: unknown; } | { type: "sandbox"; sandboxId: string; }; interface SignalRule { id: string; expression: SignalExpression; source: SignalSource; } interface SignalRuleset { name: string; type: SignalType; default: unknown; rules: SignalRule[]; version: string; } type SignalResolutionOutcome = "default" | "agreed" | "disagreement" | "no_match"; interface SignalResolutionRuleTrace { ruleId: string; matched: boolean; source: SignalSource; value: unknown | null; } interface SignalResolutionTrace { signalName: string; default: unknown; matchedRules: SignalResolutionRuleTrace[]; outcome: SignalResolutionOutcome; value: unknown; } interface SignalResolveResult { value: unknown; trace: SignalResolutionTrace; } type AttributeValue = string | number | boolean; /** Flat evaluation context. `key` is the stable bucketing identity for splits. */ type Context = { key?: string; } & Record; /** Internal normalized shape used by the resolver pipeline. */ interface FlagEvaluationContext { targetingKey?: string; attributes?: Record; } type Reason = "TARGETING_MATCH" | "SPLIT" | "NO_MATCH" | "CONFLICT" | "NOT_FOUND" | "TYPE_MISMATCH" | "STALE" | "NO_KEY"; interface TraceStep { ruleId: string; matched: boolean; value: unknown | null; } interface Evaluation { value: T; reason: Reason; trace: TraceStep[]; } type FlagsScope = { workspaceId: string; projectId?: never; } | { projectId: string; workspaceId?: never; }; interface FlagsInitOptions { /** * Override token for off-platform/local dev. By default the SDK reads * `RAILWAY_TOKEN` (project token, recommended) and falls back to * `RAILWAY_API_TOKEN` (bearer account/workspace token). */ token?: string; /** Flag scope. Omit with a project token (scope is inferred) or on Railway with `RAILWAY_PROJECT_ID`. */ scope?: FlagsScope; /** Disable background polling after the initial load. */ refresh?: false; /** Bound the initial sync wait (serverless cold starts). */ timeoutMs?: number; /** Reject `init()` when the first registry sync fails. */ required?: true; /** * Auth header mode. Tokens read from `RAILWAY_TOKEN` default to * `project-token`; explicit tokens and `RAILWAY_API_TOKEN` default to * `bearer`. Set this only when passing a project token explicitly. */ authType?: RailwayAuthType; endpoint?: string; fetch?: typeof fetch; verbose?: boolean; } type ConflictReporter = (flagName: string, scopeOwner: string | undefined) => void; declare class FlagsRegistry { #private; readonly scopeOwner: string | undefined; synced: boolean; stale: boolean; constructor(scopeOwner: string | undefined); has(name: string): boolean; list(): string[]; load(config: NormalizedRailwayClientConfig): Promise; markStale(): void; evaluate(name: string, expected: SignalType | null, ctx: Context | undefined, fallback: T, zero: T, onConflict: ConflictReporter): Evaluation; } declare class FlagsReadSurface { private readonly registry; private readonly assertReady; private readonly onConflict; private readonly getConfig; constructor(registry: FlagsRegistry, assertReady: () => void, onConflict: ConflictReporter, getConfig: () => NormalizedRailwayClientConfig); getBoolean(name: string, ctx?: Context, fallback?: boolean): boolean; getString(name: string, ctx?: Context, fallback?: string): string; getNumber(name: string, ctx?: Context, fallback?: number): number; getJson>(name: string, ctx?: Context, fallback?: T): T; /** Untyped read — returns the resolved value as `unknown` (assert at the call site). */ get(name: string, ctx?: Context, fallback?: unknown): unknown; evaluate(name: string, ctx?: Context, fallback?: unknown): Evaluation; evaluateBoolean(name: string, ctx?: Context, fallback?: boolean): Evaluation; evaluateString(name: string, ctx?: Context, fallback?: string): Evaluation; evaluateNumber(name: string, ctx?: Context, fallback?: number): Evaluation; evaluateJson>(name: string, ctx?: Context, fallback?: T): Evaluation; has(name: string): boolean; list(): string[]; refresh(): Promise; } declare class FlagsModule { #private; get ready(): Promise; get synced(): boolean; init(options?: FlagsInitOptions): Promise; scope(scope: FlagsScope): FlagsReadSurface; getBoolean(name: string, ctx?: Context, fallback?: boolean): boolean; getString(name: string, ctx?: Context, fallback?: string): string; getNumber(name: string, ctx?: Context, fallback?: number): number; getJson>(name: string, ctx?: Context, fallback?: T): T; get(name: string, ctx?: Context, fallback?: unknown): unknown; evaluate(name: string, ctx?: Context, fallback?: unknown): Evaluation; evaluateBoolean(name: string, ctx?: Context, fallback?: boolean): Evaluation; evaluateString(name: string, ctx?: Context, fallback?: string): Evaluation; evaluateNumber(name: string, ctx?: Context, fallback?: number): Evaluation; evaluateJson>(name: string, ctx?: Context, fallback?: T): Evaluation; has(name: string): boolean; list(): string[]; refresh(): Promise; close(): void; } /** Module singleton. Call `await flags.init()` once at startup, then read from `flags`. */ declare const flags: FlagsModule; declare const RAILWAY_PROJECT_ID_ENV = "RAILWAY_PROJECT_ID"; declare class FlagsScopeError extends RailwayError { constructor(); } declare function serializeScope(scope: FlagsScope): string; /** Normalize the public flat `Context` into the internal resolver shape. */ declare function normalizeEvaluationContext(raw: unknown): FlagEvaluationContext; declare function evaluateFlagRuleset(ruleset: SignalRuleset, context?: FlagEvaluationContext | Context): Promise; declare function evaluateFlagRulesetSync(ruleset: SignalRuleset, context?: FlagEvaluationContext | Context): SignalResolveResult & { reason: Reason; }; /** Deterministic percentage bucket in [0, 1) for rollout expressions. */ declare function signalBucketRatio(salt: string, subject: string): number; export { type CheckpointOptions, type ConnectOptions, type Context, type CreateOptions, DEFAULT_RAILWAY_GRAPHQL_ENDPOINT, type Evaluation, ExecControlUnsupportedError, ExecHandle, type ExecHttpOptions, type ExecHttpResult, ExecInterruptedError, ExecNotStartedError, type ExecOptions, type ExecReattachTarget, type ExecResult, type ExecSignal, type ExecStdin, type ExecTarget, type FileReadFormat, type FileReadOptions, type FileWriteData, type FileWriteOptions, type FlagEvaluationContext, type FlagsInitOptions, type FlagsScope, FlagsScopeError, type ForkOptions, type ListOptions, RAILWAY_PROJECT_ID_ENV, RailwayAuthError, type RailwayClientConfig, RailwayConnectionError, RailwayError, RailwayGraphQLError, type RailwayGraphQLErrorItem, type Reason, STALE_ENVIRONMENT_BASE_CODE, Sandbox, type SandboxCheckpointInfo, type SandboxDomain, SandboxFailedError, type SandboxFileEntry, SandboxFileNotFoundError, SandboxFiles, SandboxFilesError, type SandboxInfo, type SandboxNetworkIsolation, SandboxNotFoundError, type SandboxResources, type SandboxSessionInfo, type SandboxStatus, type SandboxTemplate, SandboxTemplateBuildError, SandboxTimeoutError, type SignalExpression, type SignalResolutionTrace, type SignalRule, type SignalRuleset, type SignalType, StaleEnvironmentError, type TemplateBuildOptions, type TraceStep, evaluateFlagRuleset, evaluateFlagRulesetSync, flags, normalizeEvaluationContext, serializeScope, signalBucketRatio };