@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.
Files changed (5) hide show
  1. package/README.md +25 -71
  2. package/index.d.ts +387 -525
  3. package/index.js +742 -995
  4. package/index.min.js +20 -20
  5. package/package.json +1 -1
package/README.md CHANGED
@@ -1,10 +1,8 @@
1
1
  # @defjs/core
2
2
 
3
- Designed for better TypeScript SDKs: define reusable HTTP, SSE, and WebSocket APIs, then execute them with an application-owned client.
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 authors export operation definitions and data contracts; consuming applications configure service addresses, authentication, interceptors, and transport. The definitions can live in a shared module or a published npm package without capturing a particular client instance.
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. Its tarball retains this `README.md` and the repository `LICENSE`; repository-wide guides and examples remain outside the package.
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 Start
15
+ ## Quick start
18
16
 
19
- ```typescript
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
- The application imports the definition and supplies its own client:
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 command = getUser({ id: 1 });
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.id, user.name);
44
+ console.log(user.name);
50
45
  }
51
46
 
52
47
  void main();
53
48
  ```
54
49
 
55
- `output` is one Struct for the 2xx body; `error` is one Struct for everything else. `ok` is the only fork, and only one side ever decodes. Omit a side and that body is never read.
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
- Server-side FormData upload progress reads the serialized stream directly without whole-body Blob buffering and preserves its multipart boundary. The total is unknown unless a valid explicit `Content-Length` supplies it. Explicit content types survive body replacement and upload conversion, with FormData's actual boundary as the exception. Downloads with non-identity encoding report `lengthComputable: false` and `total: 0`; `loaded` counts stream bytes, which Fetch may already have decompressed. In a Window or Worker, XSRF injection checks the resolved origin against `location.origin`; cookie lookup separately requires `document`.
52
+ ## Rules that matter
89
53
 
90
- The supported minimum compiler/lib contract uses `target: 'ES2022'` with `lib: ['ES2022', 'ESNext.Disposable', 'DOM', 'DOM.Iterable']`. TypeScript 7 is the current repository tooling baseline; older compiler versions are not promised. The repository currently uses `ESNext` and does not automatically verify this minimum consumer lib set. These entries supply types only — not runtime Web API polyfills.
91
-
92
- CI runs the Bun `verify` gate and Core's `core-server` and OpenTelemetry tests on Node 26. Package release jobs typecheck their build configurations and assert required files with `npm pack --dry-run`; they do not install tarballs into an external consumer for declaration or runtime verification.
93
-
94
- **SSE reconnect behavior change:** without `withSSEReconnect(...)`, SSE no longer retries network/stream-read failures. Pass `withSSEReconnect({ attempts: 3 })` (or another reviewed budget per outage) to retry those failures. SSE and WebSocket both reset the retry budget and backoff exponent after a successful handshake. `delayMs` must be finite and non-negative; `maxDelayMs` accepts a non-negative finite number or positive `Infinity`, which removes only the configured cap. The final delay after jitter and rounding is still bounded by `2_147_483_647` ms; zero bases stay zero and valid-number overflow saturates. Invalid numeric reconnect options fail before transport with `REQ_OPTIONS_INVALID`; WebSocket `attempts: 0` disables subsequent retries but still validates all explicitly supplied reconnect fields before the initial connection, as SSE does. SSE sends `Last-Event-ID` as UTF-8 bytes and strips only the physical stream's leading BOM, preserving U+FEFF in field values.
95
-
96
- When using a checkout through `file:` or a workspace link, run `bun run build` in the checkout before compiling or running the external consumer. The checkout manifest points to generated `dist/` files; published packages already contain those files.
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
- - [Build and publish an SDK](https://defjs.lyz.cloud/recipes/publish-http-sdk)
114
- - [Client](https://defjs.lyz.cloud/docs/client)
115
- - [HTTP](https://defjs.lyz.cloud/docs/http)
116
- - [SSE](https://defjs.lyz.cloud/docs/sse)
117
- - [WebSocket](https://defjs.lyz.cloud/docs/web-socket)
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.