bởi Milo

Build resilient, stateful RPC services in Node.js and TypeScript using distributed durable async/await. Supports long-running processes, AWS Lambda, Zod validation, OpenTelemetry tracing, and typed clients.
This block provides the Restate TypeScript SDK for Node.js, enabling you to build durable, stateful RPC services backed by the Restate server. It covers service/virtual-object/workflow definitions, the durable execution context API, endpoint creation, and all supporting types. The typical buyer is a backend Node.js engineer who wants reliable, retryable, and stateful service handlers without managing distributed state infrastructure manually.
index.ts — Package entry point; re-exports everything from node.tsnode.ts — Node.js HTTP/HTTP2 endpoint creation helpersfetch.ts — Fetch-based endpoint adapter (Deno/Bun/edge runtimes)lambda.ts — AWS Lambda handler adapterendpoint.ts — RestateEndpointBase interface and endpoint builder typescontext.ts — Context, ObjectContext, WorkflowContext, Request, Target interfacescontext_impl.ts — Concrete implementation of all context interfacespromises.ts — RestatePromise, isRestatePromise, combinator utilitieshooks.ts — Lifecycle hook definitionsio.ts — Low-level input/output pump abstractionsinternal.ts — SDK-internal utilities (not for direct use)user_agent.ts — User-agent string constructionerror_sanitization.ts — Cleans error messages before sending to Restatecommon_api.ts — Shared API helperstypes/errors.ts — TerminalError, RetryableError, CancelledError, TimeoutErrortypes/rpc.ts — Client, SendClient, HandlerKind, RPC proxy factoriesendpoint/ — Endpoint sub-system (discovery, components, fetch/lambda/node adapters)endpoint/handlers/ — Per-protocol request handlers and VM bindingslogging/ — Logger interface, console transport, logger transport abstractionutils/ — CompletablePromise, utilityKhởi chạy sandbox cách ly và chạy phía máy chủ — không cần cài đặt cục bộ.
Tetrees AI Review cho phiên bản này
This Express backend / api completed archive review. Structure, dependency manifests, documentation, functional source, and common risk patterns were checked by the Tetrees verification pipeline; runtime phases are stated separately.
Deterministic AVCP artifact review
Quy trình avcp-2026-08-04.1 · SHA-256 4396f8cb39a036e3…
This version-scoped review deterministically inspects the submitted archive for structure, dependencies, documentation, functional source, and common malicious or high-risk signals. Build and test phases are reported as passed only after an isolated sandbox audition. It is not a guarantee of perfect security.
Đã đánh giá 4 thg 8, 2026
Đưa sản phẩm này thẳng vào AI IDE, trình tạo web hoặc cloud IDE của bạn.
Kết nối Tetrees với AI IDE tương thích để liệt kê sản phẩm bạn sở hữu và nhận ZIP đã xác minh mà không cấp quyền tải lên của người bán.
Chưa có đánh giá.
Sign in to join the discussion
Loading discussion…
randnpm install @restatedev/restate-sdk@1.9.0
npm install @restatedev/restate-sdk-core
The WASM binary (sdk_shared_core_wasm_bindings) is bundled inside the npm package and loaded automatically—no native build steps or pod installs are required. Node.js >= 20.19 is required for the node:timers/promises and native fetch APIs used internally.
Drop the source under packages/libs/restate-sdk/src/ (or any path you prefer) and point imports at the local path or use the published npm package directly.
TypeScript config — ensure moduleResolution is "node16" or "bundler" and module is "node16" or "esnext" so .js extension imports resolve correctly:
{
"compilerOptions": {
"target": "ES2022",
"module": "Node16",
"moduleResolution": "Node16",
"strict": true,
"outDir": "dist"
}
}
Package type — add "type": "module" to your package.json (the SDK is ESM-first).
Environment variables — none are required by the SDK itself. The Restate server URL is provided to the CLI/server, not to this SDK.
Start the endpoint by calling restate.serve(...) or building an endpoint with restate.endpoint().bind(...).listen(port).
serviceimport * as restate from "@restatedev/restate-sdk";
function service<P extends string, M>(definition: {
name: P;
handlers: M;
options?: ServiceOptions;
}): ServiceDefinition<P, M>;
Declares a stateless durable service. Pass the result to endpoint.bind(). Each handler receives a Context as its first argument. Use for operations that do not need per-key state.
RestateEndpointBase.bindinterface RestateEndpointBase<E> {
bind<P extends string, M>(
service:
| ServiceDefinition<P, M>
| VirtualObjectDefinition<P, M>
| WorkflowDefinition<P, M>
): E;
}
Registers a service, virtual object, or workflow with the endpoint. Chain multiple bind() calls. Returns the same endpoint instance for fluent chaining. Call this before listen() or handle().
isRestatePromisefunction isRestatePromise<T>(p: Promise<T>): p is RestatePromise<T>;
Runtime type-guard that returns true when p is a RestatePromise (a durable, journaled promise). Use in handler utilities or middleware that must distinguish Restate-tracked promises from ordinary ones, for example when building combinator logic or custom promise adapters.
TerminalErrorclass TerminalError extends RestateError {
constructor(message: string, options?: { errorCode?: number; cause?: unknown; metadata?: Record<string, string> });
}
Thrown inside a handler to permanently fail an invocation without triggering retries. Any other error causes Restate to retry automatically. Use TerminalError for business-logic failures (e.g. validation, not-found) where retrying would not help.
A minimal stateless service with a single handler, served on port 9080.
import * as restate from "@restatedev/restate-sdk";
import type { Context } from "@restatedev/restate-sdk";
const greeter = restate.service({
name: "greeter",
handlers: {
greet: async (ctx: Context, name: string): Promise<string> => {
return `Hello, ${name}!`;
},
},
});
restate
.endpoint()
.bind(greeter)
.listen(9080);
A virtual object where each key has isolated, persistent state. ObjectContext exposes ctx.get and ctx.set for keyed state.
import * as restate from "@restatedev/restate-sdk";
import type { ObjectContext } from "@restatedev/restate-sdk";
const counter = restate.object({
name: "counter",
handlers: {
increment: async (ctx: ObjectContext): Promise<number> => {
const current = (await ctx.get<number>("count")) ?? 0;
const next = current + 1;
ctx.set("count", next);
return next;
},
reset: async (ctx: ObjectContext): Promise<void> => {
ctx.clear("count");
},
},
});
restate
.endpoint()
.bind(counter)
.listen(9080);
Workflows run exactly once per ID. Use ctx.run to durably execute side-effectful steps that must not replay on retry.
import * as restate from "@restatedev/restate-sdk";
import type { WorkflowContext } from "@restatedev/restate-sdk";
import { TerminalError } from "@restatedev/restate-sdk";
type OrderPayload = { orderId: string; amount: number };
const orderWorkflow = restate.workflow({
name: "orderWorkflow",
handlers: {
run: async (ctx: WorkflowContext, order: OrderPayload): Promise<string> => {
const chargeId = await ctx.run("charge", async () => {
// call payment provider — runs once, result journaled
if (order.amount <= 0) throw new TerminalError("Invalid amount");
return `charge-${order.orderId}-${Date.now()}`;
});
await ctx.run("sendConfirmation", async () => {
console.log(`Order ${order.orderId} charged: ${chargeId}`);
});
return chargeId;
},
},
});
restate
.endpoint()
.bind(orderWorkflow)
.listen(9080);
index.ts — Single re-export of node.ts; the public package entry.node.ts — Exports endpoint() and serve() for Node.js HTTP/HTTP2 servers.fetch.ts — Exports a fetch-compatible handler factory for edge/Bun/Deno environments.lambda.ts — Wraps the endpoint in an AWS Lambda handler shape.endpoint.ts — Declares RestateEndpointBase with bind, withIdentityV1, and default option types.context.ts — Defines Context, ObjectContext, WorkflowContext, Request, Target, DurablePromise, and related interfaces.context_impl.ts — Implements all context interfaces; drives the WASM VM state machine.promises.ts — Implements InternalRestatePromise, CombinatorRestatePromise, ConstRestatePromise, and the isRestatePromise guard.hooks.ts — Lifecycle hooks (startup/shutdown) for the endpoint.io.ts — InputPump/OutputPump abstractions over raw byte streams.internal.ts — SDK-private exports used across sub-modules; avoid importing directly.common_api.ts — Shared helpers used by service/object/workflow factory functions.error_sanitization.ts — Strips internal stack details from errors before propagating to Restate.user_agent.ts — Builds the x-restate-sdk user-agent header string.types/errors.ts — All public error classes: TerminalError, RetryableError, CancelledError, TimeoutError, RestateError.types/rpc.ts — Client<S>, SendClient<S>, HandlerKind, and the RPC proxy factory functions.endpoint/ — Full endpoint subsystem: discovery, component registry, per-runtime adapters.endpoint/handlers/ — Per-protocol handlers (fetch, lambda, generic) and the WASM VM binding layer.logging/ — LoggerTransport interface, ConsoleLoggerTransport, and the Logger wrapper.utils/ — CompletablePromise (manually resolvable promise) and a seeded PRNG via rand.ts..js extensions required: The SDK uses import ... from "./foo.js" internally. If you copy source files, keep the .js extensions in all imports and set "moduleResolution": "Node16" in tsconfig.node:timers/promises (setImmediate) is used internally; minimum Node.js 20.19 is required. Pin your Docker base image to node:20-alpine or later.@restatedev/restate-sdk-core peer not installed: context_impl.ts imports types from this package. Always install both restate-sdk and restate-sdk-core at matching minor versions.endpoint/handlers/vm/ must be resolvable at runtime. Do not exclude *.wasm files in your bundler config; add { loader: { '.wasm': 'file' } } for esbuild or the equivalent.TerminalError vs ordinary throws: Throwing any non-TerminalError causes Restate to retry indefinitely. Wrap unrecoverable business errors in new TerminalError(msg) explicitly.endpoint.withIdentityV1(key), all requests without a valid JWT are rejected. Omit this call in local development to avoid 401 errors from your test client.I have a local copy of the Restate TypeScript SDK source at `packages/libs/restate-sdk/src/`
and a USAGE.md that documents its real API.
Upstream npm package: @restatedev/restate-sdk@1.9.0
Peer package: @restatedev/restate-sdk-core
Please help me integrate this SDK into my existing Node.js/TypeScript project step by step:
1. Install the required npm packages listed in USAGE.md ## Required dependencies.
2. Update my tsconfig.json to use "module": "Node16" and "moduleResolution": "Node16".
3. Create a new file `src/restate-entry.ts` that:
- Imports from `@restatedev/restate-sdk`
- Defines at least one service using `restate.service()`
- Binds it to an endpoint with `restate.endpoint().bind(...).listen(9080)`
4. If I need stateful handlers, show me how to use `ObjectContext` with `ctx.get` and `ctx.set`.
5. If I need a workflow, show me how to use `WorkflowContext` with `ctx.run` for durable side effects.
6. Show me how to throw `TerminalError` to permanently fail an invocation.
7. Point out any WASM bundler configuration I need and remind me about the Node.js >= 20.19 requirement.
Reference USAGE.md and the source under `packages/libs/restate-sdk/src/` for all real type names and import paths.
Do not invent API methods not shown in USAGE.md.
The Restate TypeScript SDK is released under the MIT License. See source/LICENSE if present, or the upstream repository for the full license text. Upstream package: @restatedev/restate-sdk on npm.
This product’s unique contribution is clean room implementation of valuable code block into AVCP compatible standard.
Hướng dẫn cài đặt đầy đủ và prompt tích hợp sẽ mở khóa sau khi mua.
Automation, Utilities & Developer Tools
Miễn phí