@defjs/core 0.4.0 → 0.6.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +25 -71
- package/index.d.ts +387 -525
- package/index.js +742 -995
- package/index.min.js +20 -20
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -1,10 +1,8 @@
|
|
|
1
1
|
# @defjs/core
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Design reusable HTTP, SSE, and WebSocket APIs as data, then execute them with an application-owned client.
|
|
4
4
|
|
|
5
|
-
`def` means `define`. SDK
|
|
6
|
-
|
|
7
|
-
This README describes the package version that contains it. Defjs is still pre-1.0, so use the documentation and release notes published for the exact version installed in your application.
|
|
5
|
+
`def` means `define`. An SDK author exports operation definitions and data contracts. The consuming application supplies the endpoint, credentials, interceptors, and transport. Importing a definition starts no request and binds no client.
|
|
8
6
|
|
|
9
7
|
## Install
|
|
10
8
|
|
|
@@ -12,11 +10,11 @@ This README describes the package version that contains it. Defjs is still pre-1
|
|
|
12
10
|
bun add @defjs/core
|
|
13
11
|
```
|
|
14
12
|
|
|
15
|
-
The package is ESM and declares no runtime dependencies.
|
|
13
|
+
The package is ESM and declares no runtime dependencies. Declarations target `ES2022` with `ESNext.Disposable`, `DOM`, and `DOM.Iterable`; those entries supply types only, not polyfills. Defjs is pre-1.0, so use the documentation for the exact version you installed.
|
|
16
14
|
|
|
17
|
-
## Quick
|
|
15
|
+
## Quick start
|
|
18
16
|
|
|
19
|
-
```
|
|
17
|
+
```ts
|
|
20
18
|
// users-sdk.ts — SDK definition
|
|
21
19
|
import { defineRequest, struct } from "@defjs/core";
|
|
22
20
|
|
|
@@ -30,88 +28,44 @@ export const getUser = defineRequest({
|
|
|
30
28
|
});
|
|
31
29
|
```
|
|
32
30
|
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
```typescript
|
|
36
|
-
// app.ts
|
|
31
|
+
```ts
|
|
32
|
+
// app.ts — application-owned client
|
|
37
33
|
import { createClient, withEndpoint } from "@defjs/core";
|
|
38
34
|
import { getUser } from "./users-sdk.ts";
|
|
39
35
|
|
|
40
36
|
const client = createClient(withEndpoint("https://api.example.com"));
|
|
41
37
|
|
|
42
38
|
async function main() {
|
|
43
|
-
const
|
|
44
|
-
const [error, user] = await client.execute(command);
|
|
39
|
+
const [error, user] = await getUser(client, { id: 1 });
|
|
45
40
|
if (error) {
|
|
46
41
|
console.error(String(error), error.code);
|
|
47
42
|
return;
|
|
48
43
|
}
|
|
49
|
-
console.log(user.
|
|
44
|
+
console.log(user.name);
|
|
50
45
|
}
|
|
51
46
|
|
|
52
47
|
void main();
|
|
53
48
|
```
|
|
54
49
|
|
|
55
|
-
`
|
|
56
|
-
|
|
57
|
-
Best practice: `getUser({ id: 1 })` only creates a command. Give it a name, then pass that name to `client.execute`. The call validates, builds, and sends the request using the application's client. When `error` is set, return before reading the success value. When the definitions are published, import `getUser` from your SDK package instead of the local file. See [Build and publish an SDK](https://defjs.lyz.cloud/recipes/publish-http-sdk) for package exports, declarations, and compatible Core dependencies.
|
|
58
|
-
|
|
59
|
-
## Core Boundaries
|
|
60
|
-
|
|
61
|
-
- `defineRequest`, `defineEventStream`, and `defineWebSocket` return reusable endpoints; calling an endpoint creates a typed command for `client.execute`. SDK and application share the Defjs execution contract and a compatible Core version.
|
|
62
|
-
- Structs validate request input and response data at runtime. A `builder` places parsed input onto `path`, `query`, `headers`, and `body`. Every definition with `input` requires an explicit `builder`; only definitions without `input` may omit it. `.alias(name)` is the wire name for a typed value.
|
|
63
|
-
- Expected failures are returned as native `Fault` instances in an error-first tuple; custom interceptors and application callbacks can still throw. A `Fault` is discriminated by one closed set of `code` values whose prefix is the class — `HTTP_STATUS`, `REQ_*`, `NET_*`, `RES_*`, `EXT_*`, `CAP_*`, `ENV_UNSUPPORTED`. `String(error)` renders the fault message; review record keys in structural paths and custom messages before logging. `code` and the variant metadata remain enumerable for structured logs.
|
|
64
|
-
- Default Struct messages name the received kind, never its value, for example `Expected number at email, received string`. `RES_DECODE_FAILED` from a JSON `SyntaxError` says `Response body could not be decoded`. Raw `StructIssue.received` and parser causes remain sensitive; custom `errorMap` and extension messages are used verbatim and need review before logging. Any string from `errorMap`, including `''`, replaces the default, also for bigint/date conversion failures from another Core copy.
|
|
65
|
-
- Faults carry their underlying value on the native `Error` cause chain. Narrow `error.cause instanceof StructError` before calling Struct-only helpers such as `format()`, `flatten()`, or `prettify()`.
|
|
66
|
-
- `isAbortCause(cause)` and `isTimeoutCause(cause)` recognize cancellation sentinels across Core copies through their non-enumerable `Symbol.for` brands. The former also recognizes a `DOMException` named `AbortError`; the latter recognizes a `DOMException` or `Error` named `TimeoutError`. Pass a fault's underlying `cause`, not the fault itself.
|
|
67
|
-
- Server clients that capture cookies, authorization, tenant data, or user data must be created inside the owning request scope.
|
|
68
|
-
- Ordinary HTTP work is request-scoped and is bounded with its execute-time timeout or `AbortSignal`; `Client` is not `AsyncDisposable` and has no global `dispose()` lifecycle.
|
|
69
|
-
- Returned SSE and WebSocket handles are `AsyncDisposable`, so `await using` waits for Defjs-owned teardown. SSE disposal stops Defjs reading/reconnect work and releases its reader lock, but does not wait forever for a provider-controlled `cancel()` promise.
|
|
70
|
-
- WebSocket `closed` is the logical terminal result. Its disposer uses a one-second bounded teardown and may reject with `TimeoutError`; it cannot prove physical TCP closure. Existing `close()` and `closed` APIs remain available for manual lifecycle control.
|
|
71
|
-
- A timeout or cancellation does not prove that a server did not receive a write. Preserve operation identity and use an application/server idempotency contract before replaying writes.
|
|
72
|
-
- OpenAPI generation, full SDK generation, query caching, and GraphQL protocol handling are not included in this release. Define contracts by hand or compose purpose-built tools at the application boundary.
|
|
73
|
-
|
|
74
|
-
For client-local tests, inject a Fetch-compatible function with `withHTTPHandle(...)`. This keeps request interception scoped to one client and still exercises command building, interceptors, status dispatch, and response validation.
|
|
75
|
-
|
|
76
|
-
### WebSocket messages
|
|
77
|
-
|
|
78
|
-
`incoming` and `outgoing` are each one struct. `session.send` encodes that struct (aliases included) and sends JSON. A frame that is not valid JSON, or does not match `incoming`, is reported to `session.onRuntimeError` and is not delivered. Use `struct.discriminatedUnion` when one socket carries several message kinds. Static subprotocols belong on `protocols`.
|
|
79
|
-
|
|
80
|
-
After encoding, values JSON cannot faithfully represent throw `TypeError` before sending or entering the reconnect queue, including non-finite numbers, functions, symbols, `Map`, `Set`, streams, and class instances without a JSON representation. The same serializer protects heartbeat messages; a heartbeat serialization failure ends the session. If setting an injected handle's `binaryType` throws, Core requests best-effort closure before failing the attempt.
|
|
81
|
-
|
|
82
|
-
## Runtime Notes
|
|
83
|
-
|
|
84
|
-
Repository development, testing, and building use Bun `1.4.4`; package release jobs use `npm publish`. The package uses standard Web APIs such as `fetch`, `Request`, `Response`, `Headers`, streams, and `WebSocket` according to the transports enabled by the application. Repository type checking uses `bun check`; declaration files are generated by tsdown.
|
|
85
|
-
|
|
86
|
-
The default HTTP and SSE handles resolve the current global `fetch` on each call, including replacements installed after import. Importing Core without Fetch is valid; default execution reports `ENV_UNSUPPORTED` if it is still missing, while custom handles remain usable. HTTP uses `(url, init)` only for untouched platform Fetch; replaced globals and custom handles receive a `Request`.
|
|
50
|
+
Calling `getUser(client, { id: 1 })` validates, builds, and sends the request. `client({ signal })` returns a `Client` value for one call and does not perform I/O. Return before reading the success value when `error` is set. Once published, import `getUser` from your SDK package instead of the local file — see [Build and publish an SDK](https://defjs.lyz.cloud/recipes/publish-http-sdk).
|
|
87
51
|
|
|
88
|
-
|
|
52
|
+
## Rules that matter
|
|
89
53
|
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
For an application compiled to ESM with an entry at `dist/index.js`, one possible Bun launch command is:
|
|
99
|
-
|
|
100
|
-
```sh
|
|
101
|
-
bun run dist/index.js
|
|
102
|
-
```
|
|
103
|
-
|
|
104
|
-
This is an application launch example, not a repository-tested consumer check.
|
|
105
|
-
|
|
106
|
-
Browser applications use their bundler and the platform Fetch stream and WebSocket capabilities required by the transports they enable.
|
|
54
|
+
- Calling an operation with a client performs I/O. A definition does not capture a client. There is no global client.
|
|
55
|
+
- Per-call options are the seven `RequestOptions` fields: `signal`, `onUploadProgress`, `onDownloadProgress`, `beforeConnect`, `protocols`, `heartbeat`, and `reconnect`. `client(options)` returns a non-callable client value that copies those fields into a fresh object; fields set to `undefined` are omitted. Nested `heartbeat`, `protocols`, and `reconnect` values are kept by reference, so treat them as immutable after passing them. Pass `AbortSignal.timeout(ms)` as `signal` when a call needs a deadline. That reason is `NET_TIMEOUT`; a manual abort is `NET_ABORTED`. A getter that throws does so from `client(options)`, not as a fault. SSE and WebSocket have no startup-only deadline: the signal aborts the whole connection.
|
|
56
|
+
- `input` declares parameters; a synchronous, pure `builder` places them on `path`, `query`, `headers`, and `body`. Every definition with `input` requires an explicit `builder`.
|
|
57
|
+
- Structs validate at runtime. `output` is the 2xx body, `error` every other status; omit a side and that body is never read.
|
|
58
|
+
- Failures are returned as `Fault` instances in an error-first tuple — `HTTP_STATUS`, `REQ_*`, `NET_*`, `RES_*`, `EXT_*`, `CAP_*`, `ENV_UNSUPPORTED`. `String(error)` gives the message; `error.code` and the cause chain stay structured for logs.
|
|
59
|
+
- A timeout or cancellation does not prove the server missed a write. Keep an application idempotency contract before replaying writes.
|
|
60
|
+
- Returned SSE and WebSocket handles are `AsyncDisposable`; WebSocket `closed` is the logical terminal result.
|
|
61
|
+
- Inject a Fetch-compatible function with `withHTTPHandle(...)` to test a client without a server — see [Test with a handle](https://defjs.lyz.cloud/recipes/test-with-handle).
|
|
107
62
|
|
|
108
63
|
## Documentation
|
|
109
64
|
|
|
110
|
-
Guides live on the documentation site, not in the published tarball.
|
|
111
|
-
|
|
112
65
|
- [Getting started](https://defjs.lyz.cloud/docs/start)
|
|
113
|
-
- [
|
|
114
|
-
- [
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
66
|
+
- [Client](https://defjs.lyz.cloud/docs/client) · [Errors](https://defjs.lyz.cloud/docs/errors) · [Struct](https://defjs.lyz.cloud/docs/struct)
|
|
67
|
+
- [HTTP](https://defjs.lyz.cloud/docs/http) · [SSE](https://defjs.lyz.cloud/docs/sse) · [WebSocket](https://defjs.lyz.cloud/docs/web-socket)
|
|
68
|
+
|
|
69
|
+
## License
|
|
70
|
+
|
|
71
|
+
MIT.
|