由 lost in a tab 出售

Connect to remote or embedded SurrealDB instances from any JavaScript runtime. Supports WebSocket, HTTP, WebAssembly, and native Node.js engines with type-safe query builders and live subscriptions.
This block provides the full source of the SurrealDB JavaScript SDK (surrealdb), enabling connections to SurrealDB instances over WebSocket and HTTP from Node.js, Deno, and browser environments. It covers authentication, CRUD operations, live queries, CBOR serialization, and custom engine wiring. The typical buyer is a backend or full-stack TypeScript developer integrating SurrealDB as their primary database.
api/ - High-level database API surface: Surreal class, session management, queryable interface, transactions, export utilitiescbor/ - CBOR codec for binary serialization/deserialization of SurrealDB wire messagescontroller/ - Internal connection controller managing state machine, reconnection, auth, and feature negotiationengine/ - Transport layer: WebSocket engine, HTTP engine, RPC base, diagnostics wrapperflatbuffer/ - FlatBuffer codec support for alternative binary serializationinspect/ - Server-side inspection utilitiesinternal/ - Private helpers: JWT parsing, RPC auth building, promise dispatch, path normalization, error parsing, range utilitiesquery/ - Typed query builders for select, create, update, upsert, delete, insert, relate, live, and raw queriestypes/ - TypeScript type definitions: auth, diagnostics, expressions, live messages, patch operations, RPC types, Surreal interfacesutils/ - Utility functions: bound queries, channel iterators, equality checks, escaping, feature flags, expression builders, frame utilitiesvalue/ - SurrealDB value types (e.g., Uuid, record IDs)errors.ts - Typed error classes: AuthenticationError, ConnectionUnavailableError, ServerError, and othersindex.ts - Main entry point; re-exports everything from all subdirectoriesindex.server.ts - Server-specific entry pointnpm install surrealdb
No native modules, pod installs, or binary build steps are required. The SDK is pure TypeScript/JavaScript with no C++ addons. For Node.js environments, ws may be required as a polyfill if your runtime lacks a native WebSocket global:
启动隔离沙箱并在服务器端直接运行 — 无需本地配置。
此版本的 Tetrees AI Review
This TypeScript cli / script 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
管道 avcp-2026-08-04.1 · SHA-256 9c1e144baf9b8cc6…
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.
审查日期 2026年8月4日
将此产品直接导入你的 AI IDE、网页构建器或云端 IDE。
将 Tetrees 连接到兼容的 AI IDE,列出你拥有的产品并获取已验证 ZIP,同时不会开放卖家上传权限。
暂无评价。
Sign in to join the discussion
Loading discussion…
npm install ws
For bundlers (Vite, Webpack, esbuild), no special configuration is needed beyond standard ESM support.
Copy source: Place the contents of source/ into src/surrealdb/ in your project, or import directly from the published surrealdb package. If vendoring, ensure your build tool resolves .ts files.
TypeScript config: Ensure moduleResolution is set to bundler, node16, or nodenext in tsconfig.json:
{
"compilerOptions": {
"moduleResolution": "bundler",
"target": "ES2020",
"module": "ESNext",
"strict": true
}
}
{
"compilerOptions": {
"paths": {
"surrealdb": ["./src/surrealdb/index.ts"]
}
}
}
.env:SURREALDB_URL=ws://localhost:8000
SURREALDB_USER=root
SURREALDB_PASS=root
SURREALDB_NS=myapp
SURREALDB_DB=production
WebSocket is not globally available (Node.js < 22), patch it before connecting:import { WebSocket } from "ws";
(globalThis as any).WebSocket = WebSocket;
Surrealimport { Surreal } from "surrealdb";
const db = new Surreal();
await db.connect(url: string, opts?: ConnectOptions): Promise<void>;
await db.signin({ username, password }: AnyAuth): Promise<Token>;
await db.use({ namespace, database }: NamespaceDatabase): Promise<void>;
await db.query<T>(sql: string, vars?: Record<string, unknown>): Promise<T>;
await db.close(): Promise<void>;
The primary class for all database interactions. Instantiate once per connection context, call connect, authenticate, select a namespace/database, then issue queries. Safe to reuse across the lifetime of your application.
createRemoteEnginesimport { createRemoteEngines } from "surrealdb";
const engines = createRemoteEngines(): Engines;
// Returns { ws, wss, http, https } engine factories
Returns the default engine map supporting ws://, wss://, http://, and https:// protocols. Pass to the Surreal constructor's engines option to explicitly configure transports, or use applyDiagnostics to wrap them.
applyDiagnosticsimport { applyDiagnostics, createRemoteEngines } from "surrealdb";
import type { DiagnosticsCallback } from "surrealdb";
const engines = applyDiagnostics(
createRemoteEngines(),
callback: DiagnosticsCallback
): Engines;
Wraps engine implementations to emit internal RPC/transport events to a callback. Use during development and debugging. Not recommended for production due to performance overhead and API instability across versions.
CborCodecimport { CborCodec } from "surrealdb";
const codec = new CborCodec();
Handles CBOR binary encoding/decoding for the SurrealDB wire protocol. Used automatically by the engine layer; exposed if you need to implement a custom engine or serialize SurrealDB values outside a live connection.
Connect to a local SurrealDB instance using root credentials, select a namespace and database, and run a raw SurrealQL query.
import { Surreal } from "surrealdb";
const db = new Surreal();
async function main() {
await db.connect("ws://localhost:8000");
await db.signin({ username: "root", password: "root" });
await db.use({ namespace: "myapp", database: "production" });
const result = await db.query<[{ id: string; name: string }[]]>(
"SELECT * FROM user WHERE active = true LIMIT 10"
);
console.log(result[0]);
await db.close();
}
main().catch(console.error);
Wire up remote engines manually and attach a diagnostics callback to log all internal RPC operations for debugging.
import { Surreal, createRemoteEngines, applyDiagnostics } from "surrealdb";
import type { DiagnosticsCallback } from "surrealdb";
const onDiagnostic: DiagnosticsCallback = (event) => {
console.debug("[surreal:diag]", JSON.stringify(event));
};
const db = new Surreal({
engines: applyDiagnostics(createRemoteEngines(), onDiagnostic),
});
async function main() {
await db.connect("ws://localhost:8000");
await db.signin({ username: "root", password: "root" });
await db.use({ namespace: "test", database: "test" });
const rows = await db.query("SELECT * FROM product LIMIT 5");
console.log(rows);
await db.close();
}
main().catch(console.error);
Catch specific SDK error types to handle authentication failures and missing namespace/database configuration separately from generic server errors.
import {
Surreal,
AuthenticationError,
ConnectionUnavailableError,
MissingNamespaceDatabaseError,
ServerError,
} from "surrealdb";
const db = new Surreal();
async function runQuery() {
try {
await db.connect("ws://localhost:8000");
await db.signin({ username: "admin", password: "wrong_password" });
await db.use({ namespace: "myapp", database: "production" });
return await db.query("SELECT * FROM order");
} catch (err) {
if (err instanceof AuthenticationError) {
console.error("Bad credentials:", err.message);
} else if (err instanceof ConnectionUnavailableError) {
console.error("Cannot reach SurrealDB:", err.message);
} else if (err instanceof MissingNamespaceDatabaseError) {
console.error("Must call db.use() first:", err.message);
} else if (err instanceof ServerError) {
console.error("SurrealDB server error:", err.message);
} else {
throw err;
}
} finally {
await db.close();
}
}
runQuery();
api/ - Houses Surreal class, session types, transaction support, queryable interface, and export helpers. Start here for all user-facing database operations.cbor/ - CborCodec class that encodes/decodes SurrealDB's binary CBOR wire format. Used internally by engines.controller/ - Connection state machine; manages connect/disconnect lifecycle, reconnect logic, JWT parsing, and feature negotiation with the server.engine/ - Concrete transport implementations (WebSocketEngine, HttpEngine), the abstract RpcEngine base, and DiagnosticsEngine wrapper. Exposes createRemoteEngines and applyDiagnostics.flatbuffer/ - Alternative binary codec using FlatBuffers; used for specific server communication paths.inspect/ - Server-side inspection helpers, primarily for internal SDK tooling.internal/ - Private utilities not part of the public API: JWT fast-parse, incremental IDs, RPC auth construction, HTTP helpers, error parsing, reconnect logic, input validation.query/ - Typed query builder modules for each DML operation (select, create, update, upsert, delete, insert, relate, live, raw query, run).types/ - All TypeScript interfaces and type aliases used throughout the SDK: AnyAuth, ConnectOptions, Session, LiveMessage, Patch, RpcRequest, etc.utils/ - Standalone helpers: Publisher (event emitter), Features, isVersionSupported, BoundQuery, channel-based async iterators, escape functions.value/ - SurrealDB scalar value representations such as Uuid and record ID types.errors.ts - All exported error classes with typed constructors for precise catch blocks.index.ts - Barrel export; re-exports every public symbol from all subdirectories.index.server.ts - Server-only entry point for environments where browser-specific code must be excluded.WebSocket in Node.js < 22: The SDK requires a global WebSocket; fix by adding (globalThis as any).WebSocket = require("ws") before any SDK import."moduleResolution": "node16" in tsconfig and use dynamic import() or a bundler that handles ESM.query before use(): Queries against tables that require a namespace/database will throw MissingNamespaceDatabaseError; always call db.use() after db.signin().await db.close() in shutdown handlers; unclosed WebSocket connections can prevent Node.js from exiting cleanly.applyDiagnostics wraps every engine call and emits verbose events; remove it before deploying to production to avoid memory and CPU overhead.MINIMUM_VERSION / MAXIMUM_VERSION); connecting to an incompatible server throws UnsupportedVersionError. Match your server version to the SDK release.I have the SurrealDB JavaScript SDK source in `src/surrealdb/` (from the `surrealdb` npm package).
I also have a USAGE.md guide at `USAGE.md` that documents all real exports and working code patterns.
Please integrate SurrealDB into my existing TypeScript/Node.js project step by step:
1. Read USAGE.md and the source files in `src/surrealdb/` to understand the real API.
2. Create a singleton connection module that connects using environment variables
(SURREALDB_URL, SURREALDB_USER, SURREALDB_PASS, SURREALDB_NS, SURREALDB_DB).
3. Use the `Surreal` class from `src/surrealdb/index.ts` (or `surrealdb` if installed as a package).
4. Add typed error handling using `AuthenticationError`, `ConnectionUnavailableError`,
`MissingNamespaceDatabaseError`, and `ServerError` from `src/surrealdb/errors.ts`.
5. Wire `createRemoteEngines` explicitly in the `Surreal` constructor.
6. Expose helper functions for the CRUD operations my application needs.
7. Add graceful shutdown that calls `db.close()`.
8. Do not invent any API methods; only use exports visible in USAGE.md and the source files.
The SurrealDB JavaScript SDK is released under the Apache 2.0 license. See source/LICENSE if present, or refer to the upstream repository for the full license text. Upstream package: surrealdb on npm.
This product’s unique contribution is clean room implementation of valuable code block into AVCP compatible standard.
完整安装指南与集成提示词将在购买后解锁。
Automation, Utilities & Developer Tools
免费