@qzcurious/http-connect 0.0.0-stage → 0.0.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 qzcurious
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,173 @@
1
- # Temporary Holding Version
1
+ # http-connect
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ English · [台灣繁體中文](./README.zh-TW.md)
4
+
5
+ `http-connect` lets a TypeScript application record what it expects from a backend route and use that contract to call the API. Each endpoint describes one request and the responses you have observed. Callers get typed input and results. If the backend returns an unfamiliar status or changes the shape of its data, the fetcher reports the mismatch at runtime.
6
+
7
+ ## Quick start
8
+
9
+ Install the library and Zod for this example.
10
+
11
+ ```sh
12
+ npm install @qzcurious/http-connect zod
13
+ ```
14
+
15
+ Read a todo from JSONPlaceholder using Zod and a runtime with Fetch support.
16
+
17
+ ```ts
18
+ import { codecs, createTransport, endpoint, path } from "@qzcurious/http-connect";
19
+ import { z } from "zod";
20
+
21
+ const api = createTransport({ baseUrl: "https://jsonplaceholder.typicode.com", codecs });
22
+ const todo = endpoint({
23
+ method: "GET",
24
+ path: path("/todos/:id", z.object({ id: z.string() })),
25
+ request: {},
26
+ response: {
27
+ status: 200,
28
+ decodeAs: "json",
29
+ body: z.object({ title: z.string(), completed: z.boolean() }),
30
+ },
31
+ });
32
+
33
+ const getTodo = api.createFetcher(todo);
34
+ const { body } = await getTodo({ params: { id: "1" } });
35
+ console.log(body.title);
36
+ ```
37
+
38
+ This calls `GET /todos/1` and prints its title after validating the JSON response. To use your own API, change the base URL, path, and response schema.
39
+
40
+ ## Add query parameters, headers, and a 404 response
41
+
42
+ Suppose `GET /workspaces/:workspaceId/notes` returns a JSON list of notes, or a JSON error when the workspace is missing. The following example uses Zod for validation and a fetch-compatible runtime. Replace the example origin with your API’s origin.
43
+
44
+ ```ts
45
+ import { codecs, createTransport, endpoint, path, type CallInput } from "@qzcurious/http-connect";
46
+ import { z } from "zod";
47
+
48
+ const transport = createTransport({
49
+ baseUrl: "https://api.example.com",
50
+ codecs,
51
+ });
52
+
53
+ const workspaceNotes = path(
54
+ "/workspaces/:workspaceId/notes",
55
+ z.object({ workspaceId: z.string().min(1) }),
56
+ );
57
+
58
+ const listNotesContract = endpoint({
59
+ method: "GET",
60
+ path: workspaceNotes,
61
+ request: {
62
+ query: z.object({ page: z.number().int().positive(), tag: z.array(z.string()).optional() }),
63
+ headers: z.object({ "accept-language": z.string() }),
64
+ },
65
+ response: [
66
+ {
67
+ status: 200,
68
+ decodeAs: "json",
69
+ body: z.array(z.object({ id: z.string(), title: z.string() })),
70
+ },
71
+ {
72
+ status: 404,
73
+ decodeAs: "json",
74
+ body: z.object({ code: z.literal("workspace_not_found"), message: z.string() }),
75
+ },
76
+ ],
77
+ });
78
+
79
+ const listNotes = transport.createFetcher(listNotesContract);
80
+ type ListNotesInput = CallInput<typeof listNotesContract>;
81
+
82
+ const input: ListNotesInput = {
83
+ params: { workspaceId: "acme" },
84
+ query: { page: 1 },
85
+ headers: { "accept-language": "en" },
86
+ };
87
+
88
+ const result = await listNotes(input);
89
+ if (result.status === 200) {
90
+ console.log(result.body.map((note) => note.title));
91
+ } else {
92
+ console.log(result.body.message); // Validated 404 response
93
+ }
94
+ ```
95
+
96
+ This sends `GET /workspaces/acme/notes?page=1` with the header `accept-language: en`. Checking `result.status` narrows the body type to the schema for that status. You can define endpoints beside the features that use them and bind each to the same transport.
97
+
98
+ ## Send a request body
99
+
100
+ To create a note on the same route, declare a POST endpoint. Pair the body schema with `encodeAs` to choose how the transport serializes the validated value.
101
+
102
+ ```ts
103
+ const createNoteContract = endpoint({
104
+ method: "POST",
105
+ path: workspaceNotes,
106
+ request: {
107
+ encodeAs: "json",
108
+ body: z.string().trim().min(1).transform((title) => ({ title })),
109
+ },
110
+ response: { status: 204 },
111
+ });
112
+
113
+ const createNote = transport.createFetcher(createNoteContract);
114
+ await createNote({ params: { workspaceId: "acme" }, body: " First note " });
115
+ ```
116
+
117
+ The caller supplies a string. The schema trims it and produces an object, so the JSON encoder sends `{"title":"First note"}`. Declaring `{ status: 204 }` is enough for a response with no body to decode.
118
+
119
+ Other request encodings include `text`, `form-urlencoded`, `form-data`, `binary`, and `stream`. For a file upload, use `encodeAs: "form-data"` and a schema such as `z.object({ image: z.file(), alt: z.string() })`. Pass a `File` and its description in `body`. Leave `Content-Type` unset so Fetch can generate the multipart boundary. The playground includes the complete upload contract and call. [Endpoint with transport](./playground/endpoint-with-transport.ts)
120
+
121
+ ## Shape the call
122
+
123
+ - **Path parameters.** Use `path("/health")` for a static route. For a parameterized route, pass a schema whose output keys match the placeholders. Both `:id` and `{id}` are supported. Use one style per path. The fetcher validates and encodes each parameter as a path segment.
124
+ - **Input and options.** Supply each declared section (`params`, `query`, `headers`, or `body`) in the input object. Individual fields can be optional, like `tag` above. To cancel a call, pass an abort signal in the second argument, as in `listNotes(input, { signal })`. For an endpoint with no input sections, call its fetcher with no arguments or pass `{ signal }` as the first argument.
125
+ - **Response alternatives.** Use one response object or an array of alternatives. For multiple shapes with the same status, the fetcher tries them in declaration order and returns the first that validates. Use `Awaited<ReturnType<typeof listNotes>>` when you need to name the inferred result type.
126
+
127
+ ## Handle failures
128
+
129
+ A declared HTTP error such as the 404 above is a normal result when its schema matches. Use the error classes exported by `@qzcurious/http-connect` to distinguish invalid input from an unexpected response.
130
+
131
+ | Outcome | What the caller receives |
132
+ | --- | --- |
133
+ | A call input schema reports validation issues | `CallInputValidationError` with the failing `section` and its `issues`. The request has not been sent. |
134
+ | The status is undeclared, or none of its shapes can decode and validate the response | `UnknownResponseError` with the observed `status`. For example, a 200 with malformed JSON fails the list contract above. |
135
+ | Fetch rejects, for example because of a network failure or cancellation | The original rejection from the fetch implementation. |
136
+
137
+ ## Configure the transport
138
+
139
+ `createTransport` uses `globalThis.fetch` by default. Supply a `fetch` function to customize dispatch. It receives the assembled Web Platform `Request` and returns a promise for a `Response`.
140
+
141
+ ```ts
142
+ function authenticatedTransport(baseUrl: string, token: string) {
143
+ return createTransport({
144
+ baseUrl,
145
+ codecs,
146
+ fetch(request) {
147
+ request.headers.set("Authorization", `Bearer ${token}`);
148
+ return fetch(request);
149
+ },
150
+ });
151
+ }
152
+ ```
153
+
154
+ Passing `codecs` opts into the built-in query and body encoders and response decoders. To register only what a contract uses, configure codecs on the transport or in the second argument to `createFetcher`. Fetcher-level codecs override the corresponding transport entries. For example, the list endpoint needs a query encoder and a JSON decoder.
155
+
156
+ ```ts
157
+ const api = createTransport({ baseUrl: "https://api.example.com" });
158
+ const fetchNotes = api.createFetcher(listNotesContract, {
159
+ codecs: {
160
+ encoders: { query: codecs.encoders.query },
161
+ decoders: { json: codecs.decoders.json },
162
+ },
163
+ });
164
+ ```
165
+
166
+ ## More examples
167
+
168
+ - Follow the main workflow from listing notes to creating a note and attaching an image. [Endpoint with transport](./playground/endpoint-with-transport.ts)
169
+ - Use an endpoint contract with your own fetch logic. [Endpoint with manual fetch](./playground/endpoint-with-manual-fetch.ts)
170
+ - Define request and response shapes independently. [Standalone shapes](./playground/standalone-shapes.ts)
171
+ - Choose between JSON and text when a route accepts both. [Multiple request shapes](./playground/multiple-request-shapes.ts)
172
+
173
+ For the project’s scope and design rationale, see the [product goals](./docs/goals.md) and [maintainer documentation](./docs/README.md).
@@ -0,0 +1,173 @@
1
+ # http-connect
2
+
3
+ [English](./README.md) · 台灣繁體中文
4
+
5
+ 使用 `http-connect`,你可以在 TypeScript 應用程式裡,把後端路由接受的請求和你實際觀察到的回應寫成端點契約,再依照契約呼叫 API。TypeScript 會從契約推導呼叫時的輸入與回傳型別。如果後端傳回未宣告的狀態碼,或回應資料的結構有變,產生的請求函式(fetcher)會在執行時回報不符之處。
6
+
7
+ ## 快速開始
8
+
9
+ 安裝 `http-connect` 和範例使用的驗證套件 Zod。
10
+
11
+ ```sh
12
+ npm install @qzcurious/http-connect zod
13
+ ```
14
+
15
+ 在支援 Fetch 的執行環境中,從 JSONPlaceholder 讀取一筆待辦事項,並用 Zod 驗證回應。
16
+
17
+ ```ts
18
+ import { codecs, createTransport, endpoint, path } from "@qzcurious/http-connect";
19
+ import { z } from "zod";
20
+
21
+ const api = createTransport({ baseUrl: "https://jsonplaceholder.typicode.com", codecs });
22
+ const todo = endpoint({
23
+ method: "GET",
24
+ path: path("/todos/:id", z.object({ id: z.string() })),
25
+ request: {},
26
+ response: {
27
+ status: 200,
28
+ decodeAs: "json",
29
+ body: z.object({ title: z.string(), completed: z.boolean() }),
30
+ },
31
+ });
32
+
33
+ const getTodo = api.createFetcher(todo);
34
+ const { body } = await getTodo({ params: { id: "1" } });
35
+ console.log(body.title);
36
+ ```
37
+
38
+ 這段程式會呼叫 `GET /todos/1`,驗證 JSON 回應後印出待辦事項的標題。要改用自己的 API,請調整基底網址、路徑和回應的驗證規則(schema)。
39
+
40
+ ## 加入查詢參數、請求標頭與 404 回應
41
+
42
+ 假設 `GET /workspaces/:workspaceId/notes` 會以 JSON 傳回筆記清單,找不到工作區時則傳回 JSON 格式的錯誤訊息。以下範例同樣使用 Zod 和支援 Fetch 的執行環境。請將 `https://api.example.com` 換成你的 API 網址。
43
+
44
+ ```ts
45
+ import { codecs, createTransport, endpoint, path, type CallInput } from "@qzcurious/http-connect";
46
+ import { z } from "zod";
47
+
48
+ const transport = createTransport({
49
+ baseUrl: "https://api.example.com",
50
+ codecs,
51
+ });
52
+
53
+ const workspaceNotes = path(
54
+ "/workspaces/:workspaceId/notes",
55
+ z.object({ workspaceId: z.string().min(1) }),
56
+ );
57
+
58
+ const listNotesContract = endpoint({
59
+ method: "GET",
60
+ path: workspaceNotes,
61
+ request: {
62
+ query: z.object({ page: z.number().int().positive(), tag: z.array(z.string()).optional() }),
63
+ headers: z.object({ "accept-language": z.string() }),
64
+ },
65
+ response: [
66
+ {
67
+ status: 200,
68
+ decodeAs: "json",
69
+ body: z.array(z.object({ id: z.string(), title: z.string() })),
70
+ },
71
+ {
72
+ status: 404,
73
+ decodeAs: "json",
74
+ body: z.object({ code: z.literal("workspace_not_found"), message: z.string() }),
75
+ },
76
+ ],
77
+ });
78
+
79
+ const listNotes = transport.createFetcher(listNotesContract);
80
+ type ListNotesInput = CallInput<typeof listNotesContract>;
81
+
82
+ const input: ListNotesInput = {
83
+ params: { workspaceId: "acme" },
84
+ query: { page: 1 },
85
+ headers: { "accept-language": "en" },
86
+ };
87
+
88
+ const result = await listNotes(input);
89
+ if (result.status === 200) {
90
+ console.log(result.body.map((note) => note.title));
91
+ } else {
92
+ console.log(result.body.message); // 已通過驗證的 404 回應
93
+ }
94
+ ```
95
+
96
+ 這個呼叫會送出 `GET /workspaces/acme/notes?page=1`,並帶上 `accept-language: en` 標頭。檢查 `result.status` 後,TypeScript 會將 `result.body` 的型別縮小為該狀態碼對應的資料型別。你可以在各功能的程式碼旁定義所需的端點,再用同一個 transport 為各端點建立請求函式。
97
+
98
+ ## 傳送請求本文
99
+
100
+ 要在同一路徑新增筆記,可以宣告一個 POST 端點。使用 `body` 的 schema 驗證輸入,再用 `encodeAs` 指定 transport 如何將驗證後的值編碼。
101
+
102
+ ```ts
103
+ const createNoteContract = endpoint({
104
+ method: "POST",
105
+ path: workspaceNotes,
106
+ request: {
107
+ encodeAs: "json",
108
+ body: z.string().trim().min(1).transform((title) => ({ title })),
109
+ },
110
+ response: { status: 204 },
111
+ });
112
+
113
+ const createNote = transport.createFetcher(createNoteContract);
114
+ await createNote({ params: { workspaceId: "acme" }, body: " First note " });
115
+ ```
116
+
117
+ 呼叫端傳入字串後,schema 會去除頭尾空白,再將標題轉成物件,因此 JSON 編碼器實際送出的內容是 `{"title":"First note"}`。如果回應沒有本文需要解碼,只要宣告 `{ status: 204 }` 即可。
118
+
119
+ 請求本文也支援 `text`、`form-urlencoded`、`form-data`、`binary` 和 `stream`。上傳檔案時,可以搭配 `encodeAs: "form-data"` 和 `z.object({ image: z.file(), alt: z.string() })`,並在 `body` 傳入 `File` 物件及其文字說明。請讓 Fetch 自動設定 `Content-Type`,以便產生分隔 multipart 各部分所需的 boundary。完整的上傳契約與呼叫方式請見[檔案上傳範例](./playground/endpoint-with-transport.ts)。
120
+
121
+ ## 設定端點與呼叫方式
122
+
123
+ - **路徑參數**:固定路徑可直接寫成 `path("/health")`。路徑含有參數時,請傳入 schema,並讓輸出物件的鍵名與路徑中的參數名稱一致。支援 `:id` 和 `{id}` 兩種寫法,每條路徑擇一使用。請求函式會逐一驗證參數,並將每個值編碼成單一路徑區段。
124
+ - **輸入與選項**:在輸入物件中提供契約宣告的各個部分(`params`、`query`、`headers` 或 `body`)。其中的個別欄位可以是選填,例如前例的 `tag`。若要取消呼叫,可在第二個引數傳入中止訊號,例如 `listNotes(input, { signal })`。如果端點沒有宣告任何輸入,可以直接呼叫請求函式,也可以將 `{ signal }` 當作第一個引數傳入。
125
+ - **多種回應格式**:可以用一個物件宣告單一回應格式,也可以用陣列列出多種格式。如果同一狀態碼對應多種資料結構,請求函式會依宣告順序嘗試,並傳回第一個通過驗證的結果。需要為推導出的結果型別命名時,可使用 `Awaited<ReturnType<typeof listNotes>>`。
126
+
127
+ ## 處理錯誤
128
+
129
+ 像前例的 404,只要狀態碼已在契約中宣告,且回應通過驗證,請求函式就會正常傳回結果。你可以使用 `@qzcurious/http-connect` 匯出的錯誤類別,分辨是呼叫時的輸入有誤,還是後端回應不符合契約。
130
+
131
+ | 情況 | 呼叫端收到的結果 |
132
+ | --- | --- |
133
+ | 輸入未通過 schema 驗證 | 拋出 `CallInputValidationError`。`section` 指出哪個部分驗證失敗,`issues` 列出詳細原因。此時請求尚未送出。 |
134
+ | 狀態碼未宣告,或該狀態碼的所有格式都無法成功解碼並驗證回應 | 拋出 `UnknownResponseError`,其中的 `status` 是實際收到的狀態碼。例如,前例的清單端點即使傳回 200,只要 JSON 語法有誤,仍會觸發這個錯誤。 |
135
+ | Fetch 因網路錯誤或呼叫遭取消等原因而失敗 | 呼叫端會收到底層 Fetch 實作原本的拒絕原因。 |
136
+
137
+ ## 設定 transport
138
+
139
+ `createTransport` 預設使用 `globalThis.fetch`。你也可以傳入自訂的 `fetch` 函式,調整請求的傳送方式。這個函式會收到已組裝好的 Web 平台 `Request` 物件,並傳回 `Promise<Response>`。
140
+
141
+ ```ts
142
+ function authenticatedTransport(baseUrl: string, token: string) {
143
+ return createTransport({
144
+ baseUrl,
145
+ codecs,
146
+ fetch(request) {
147
+ request.headers.set("Authorization", `Bearer ${token}`);
148
+ return fetch(request);
149
+ },
150
+ });
151
+ }
152
+ ```
153
+
154
+ 傳入 `codecs` 即可使用內建的查詢參數編碼器、請求本文編碼器與回應解碼器。如果只想註冊契約用得到的項目,可以在 transport 上設定,也可以透過 `createFetcher` 的第二個引數設定。請求函式上的設定會覆寫 transport 上的對應項目。例如,前面的筆記清單端點只需要查詢參數編碼器和 JSON 解碼器。
155
+
156
+ ```ts
157
+ const api = createTransport({ baseUrl: "https://api.example.com" });
158
+ const fetchNotes = api.createFetcher(listNotesContract, {
159
+ codecs: {
160
+ encoders: { query: codecs.encoders.query },
161
+ decoders: { json: codecs.decoders.json },
162
+ },
163
+ });
164
+ ```
165
+
166
+ ## 更多範例
167
+
168
+ - [使用 transport 呼叫端點](./playground/endpoint-with-transport.ts) 示範如何列出筆記、新增筆記並附上圖片。
169
+ - [自行使用 Fetch 傳送請求](./playground/endpoint-with-manual-fetch.ts) 示範如何將端點契約搭配自訂的請求邏輯。
170
+ - [獨立定義資料結構](./playground/standalone-shapes.ts) 示範如何分別定義請求與回應的格式。
171
+ - [宣告多種請求格式](./playground/multiple-request-shapes.ts) 示範如何在同一路由支援 JSON 和純文字時選擇要傳送的格式。
172
+
173
+ 關於專案範圍與設計考量,請參閱[產品目標](./docs/goals.md)與[維護者文件](./docs/README.md)。
@@ -0,0 +1,384 @@
1
+ import { StandardSchemaV1, StandardTypedV1 } from "@standard-schema/spec";
2
+ /**
3
+ * Makes types easier to read in editor hovers and error messages.
4
+ *
5
+ * @example <caption>Hovers show all fields together in one object.</caption>
6
+ * type User = { id: string } & { name: string };
7
+ * // Hover: { id: string } & { name: string }
8
+ *
9
+ * type ReadableUser = Prettify<User>;
10
+ * // Hover: { id: string; name: string }
11
+ *
12
+ * @example <caption>Errors list allowed values without looking up the type.</caption>
13
+ * type Method = "GET" | "POST";
14
+ * const method: Method = "PUT";
15
+ * // Error: Type '"PUT"' is not assignable to type 'Method'.
16
+ *
17
+ * type ReadableMethod = Prettify<"GET" | "POST">;
18
+ * const readableMethod: ReadableMethod = "PUT";
19
+ * // Error: Type '"PUT"' is not assignable to type '"GET" | "POST"'.
20
+ */
21
+ type Prettify<T, Result = { [K in keyof T]: T[K]; } & {}> = [T] extends [object] ? Result : Result & ({} | null | undefined);
22
+ /** A declared field whose runtime value is omitted when it is undefined.
23
+ * Declaration presence must be checked separately; never is a required value.
24
+ */
25
+ type DefinedField<Name extends PropertyKey, Value> = undefined extends Value ? { [Key in Name]?: Value; } : { [Key in Name]: Value; };
26
+ type ExtraPropertyKeys<Actual, AllowedKeys extends PropertyKey> = Actual extends unknown ? Exclude<keyof Actual, AllowedKeys> : never;
27
+ type NoExtraPropertiesConstraint<Actual, AllowedKeys extends PropertyKey> = [ExtraPropertyKeys<Actual, AllowedKeys>] extends [never] ? {} : { [Key in ExtraPropertyKeys<Actual, AllowedKeys>]: Invalid<Key extends string | number ? `Error: unknown property: ${Key}` : "Error: unknown symbol property">; };
28
+ type ExpectedObject<T, Item extends object> = { [K in keyof T]: K extends keyof Item ? (T[K] extends Item[K] ? T[K] : Item[K]) : T[K]; } & Item;
29
+ /**
30
+ * Detect whole-type unions, allowing unions within fields and tuple elements.
31
+ * Check with `true extends IsUnion<T>`: overlapping members can yield boolean.
32
+ * never stays never; any/unknown and normalized single types yield false.
33
+ */
34
+ type IsUnion<T, Whole = T> = T extends unknown ? [Whole] extends [T] ? false : true : never;
35
+ declare const invalid: unique symbol;
36
+ /**
37
+ * A custom type-level error when native TypeScript errors do not explain the rule.
38
+ * Supports intersecting independent failures; diagnostic formatting is compiler-controlled.
39
+ *
40
+ * @example
41
+ * type NonEmpty<S extends string> = S extends ""
42
+ * ? Invalid<"Value must not be empty">
43
+ * : S;
44
+ */
45
+ interface Invalid<Message extends string> {
46
+ readonly [invalid]: { readonly [Key in Message]: never; };
47
+ }
48
+ type StandardObjectSchema = StandardSchemaV1<Record<string, unknown>, Record<string, unknown>>;
49
+ type ConstrainedObjectSchema<Schema extends StandardObjectSchema, OutputAllowedValue, InputAllowedValue> = StandardTypedV1<{ [Key in keyof StandardSchemaV1.InferInput<Schema>]: InputAllowedValue; }, { [Key in keyof StandardSchemaV1.InferOutput<Schema>]: OutputAllowedValue; }>;
50
+ type ExpectedObjectSchema<Schema extends StandardObjectSchema, OutputAllowedValue, InputAllowedValue> = [Schema] extends [ConstrainedObjectSchema<Schema, OutputAllowedValue, InputAllowedValue>] ? Schema : ConstrainedObjectSchema<Schema, OutputAllowedValue, InputAllowedValue>;
51
+ type JsonValue = null | boolean | number | string | readonly (JsonValue | undefined)[] | {
52
+ readonly [key: string]: JsonValue | undefined;
53
+ };
54
+ type PathParamValue = Prettify<string | number>;
55
+ type PathShape = {
56
+ template: string;
57
+ params: StandardObjectSchema | undefined;
58
+ };
59
+ export declare function path<const T extends string>(template: T & ExpectedPath<T> & ([PathParamNames<T>[number]] extends [never] ? unknown : Invalid<"Error: params is required when path contains placeholders.">)): Readonly<{
60
+ template: T;
61
+ params: undefined;
62
+ }>;
63
+ export declare function path<const T extends string, const S extends StandardObjectSchema>(template: T & ExpectedPath<T>, params: S & ExpectedPathParams<NoInfer<T>, S>): Readonly<{
64
+ template: T;
65
+ params: S;
66
+ }>;
67
+ /** Computes substitution for a path already validated during contract authoring. */
68
+ type ResolvedPath<Path extends string, Params extends Record<string, PathParamValue>> = Path extends `${string}:${string}` ? ResolveColonPath<Path, Params> : ResolveBracePath<Path, Params>;
69
+ /**
70
+ * Extracts path placeholder names as a tuple in source order.
71
+ *
72
+ * Repeated placeholder names are preserved. Index the tuple with `number` to
73
+ * obtain a union of its parameter names.
74
+ * Names follow `[A-Za-z_][A-Za-z0-9_]*`: colon placeholders stop at the first
75
+ * other character; brace placeholders require an immediate closing brace.
76
+ * Malformed placeholders and mixed styles produce `never`.
77
+ *
78
+ * @example
79
+ * type ParamNames = PathParamNames<"/users/{userId}/posts/{postId}">;
80
+ * // ["userId", "postId"]
81
+ *
82
+ * type ParamName = ParamNames[number];
83
+ * // "userId" | "postId"
84
+ */
85
+ type PathParamNames<Path extends string> = Path extends unknown ? PathPlaceholderStyle<Path> extends "mixed" ? never : PathPlaceholderStyle<Path> extends "colon" ? ColonPathParamNameTuple<Path> : PathPlaceholderStyle<Path> extends "brace" ? BracePathParamNameTuple<Path> : [] : never;
86
+ /** Whether a literal name matches `[A-Za-z_][A-Za-z0-9_]*` in full. */
87
+ type IsValidPathParamName<Name extends string> = string extends Name ? false : Name extends `${infer First}${infer Rest}` ? ContainsOnlyCharacters<First, PathParamNameStart> extends true ? ContainsOnlyCharacters<Rest, PathParamNameCharacter> : false : false;
88
+ type ContainsOnlyCharacters<Value extends string, AllowedCharacter extends string> = Value extends "" ? true : Value extends `${infer Character}${infer Rest}` ? Character extends AllowedCharacter ? ContainsOnlyCharacters<Rest, AllowedCharacter> : false : false;
89
+ type ExpectedPath<Path extends string> = Path extends unknown ? {} extends Record<Path, never> ? Invalid<"Error: path must be a string literal."> : Path extends `//${string}` ? Invalid<'Error: path must not start with "//".'> : Path extends `/${string}` ? ExpectedPathWithValidPlaceholders<Path> : Invalid<"Error: path must start with '/'."> : never;
90
+ type ExpectedPathWithValidPlaceholders<Path extends string> = Path extends unknown ? PathPlaceholderStyle<Path> extends "mixed" ? Invalid<'Error: path must not mix ":id" and "{id}" placeholder styles.'> : [PathParamNames<Path>] extends [never] ? Invalid<"Error: path contains an invalid placeholder."> : Path : never;
91
+ type ExpectedPathParams<Path extends string, Params extends StandardObjectSchema | undefined> = [PathParamNames<Path>[number]] extends [never] ? Params extends StandardObjectSchema ? Invalid<"Error: params may only be declared when path contains placeholders."> : undefined : Params extends StandardObjectSchema ? ExpectedPathParamsSchema<Path, Params> : Invalid<"Error: params is required when path contains placeholders.">;
92
+ type ExpectedPathParamsSchema<Path extends string, Schema extends StandardObjectSchema> = ExpectedObjectSchema<Schema, PathParamValue, unknown> extends Schema ? [MissingPathParamKeys<Path, Schema>] extends [never] ? [ExtraPathParamKeys<Path, Schema>] extends [never] ? StandardSchemaV1.InferOutput<Schema> extends Record<PathParamNames<Path>[number], PathParamValue> ? Schema : Invalid<"Error: params schema must output a required value for every path parameter."> : Invalid<`Error: params schema has keys that do not match declared path parameters: ${ExtraPathParamKeys<Path, Schema> & string}`> : Invalid<`Error: params schema is missing path parameters: ${MissingPathParamKeys<Path, Schema> & string}`> : ExpectedObjectSchema<Schema, PathParamValue, unknown>;
93
+ type MissingPathParamKeys<Path extends string, Schema extends StandardObjectSchema> = Exclude<PathParamNames<Path>[number], Extract<keyof StandardSchemaV1.InferOutput<Schema>, string>>;
94
+ type ExtraPathParamKeys<Path extends string, Schema extends StandardObjectSchema> = Exclude<Extract<keyof StandardSchemaV1.InferOutput<Schema>, string>, PathParamNames<Path>[number]>;
95
+ type PathPlaceholderStyle<Path extends string> = Path extends `${string}:${string}` ? Path extends `${string}${"{" | "}"}${string}` ? "mixed" : "colon" : Path extends `${string}${"{" | "}"}${string}` ? "brace" : "plain";
96
+ type ColonPathParamNameTuple<Path extends string> = Path extends `${string}:${infer After}` ? ReadPathParamName<After> extends [infer Name extends string, infer Rest extends string] ? IsValidPathParamName<Name> extends true ? [Name, ...ColonPathParamNameTuple<Rest>] : never : never : [];
97
+ type BracePathParamNameTuple<Path extends string> = Path extends `${infer Prefix}{${infer Name}}${infer Rest}` ? Prefix extends `${string}${"{" | "}"}${string}` ? never : IsValidPathParamName<Name> extends true ? [Name, ...BracePathParamNameTuple<Rest>] : never : Path extends `${string}${"{" | "}"}${string}` ? never : [];
98
+ type ResolveColonPath<Path extends string, Params extends Record<string, PathParamValue>> = Path extends `${infer Prefix}:${infer After}` ? ReadPathParamName<After> extends [infer Name extends string, infer Rest extends string] ? `${Prefix}${Params[Name]}${ResolveColonPath<Rest, Params>}` : never : Path;
99
+ type ResolveBracePath<Path extends string, Params extends Record<string, PathParamValue>> = Path extends `${infer Prefix}{${infer Name}}${infer Rest}` ? `${Prefix}${Params[Name]}${ResolveBracePath<Rest, Params>}` : Path;
100
+ type ReadPathParamName<Value extends string, Name extends string = ""> = Value extends `${infer Character}${infer Rest}` ? Character extends PathParamNameCharacter ? ReadPathParamName<Rest, `${Name}${Character}`> : [Name, Value] : [Name, Value];
101
+ type PathParamNameStart = StringCharacters<"abcdefghijklmnopqrstuvwxyz"> | StringCharacters<"ABCDEFGHIJKLMNOPQRSTUVWXYZ"> | "_";
102
+ type PathParamNameCharacter = PathParamNameStart | StringCharacters<"0123456789">;
103
+ type StringCharacters<Value extends string> = Value extends `${infer Character}${infer Rest}` ? Character | StringCharacters<Rest> : never;
104
+ type FormDataPrimitive = string | number | boolean | null | Blob;
105
+ type FormDataPrimitiveArray = readonly (FormDataPrimitive | undefined)[];
106
+ type FormDataStructuredArray = readonly (FormDataObject | FormDataPrimitiveArray | FormDataStructuredArray | undefined)[];
107
+ type FormDataValue = FormDataPrimitive | undefined | FormDataPrimitiveArray | FormDataStructuredArray | FormDataObject;
108
+ type FormDataObject = {
109
+ readonly [key: string]: FormDataValue;
110
+ };
111
+ export declare function toFormData(value: FormData | FormDataObject): FormData;
112
+ type URLSearchParamsNativeInput = NonNullable<ConstructorParameters<typeof URLSearchParams>[0]>;
113
+ type URLSearchParamsPrimitive = Prettify<string | number | boolean | null>;
114
+ type URLSearchParamsPrimitiveArray = readonly (URLSearchParamsPrimitive | undefined)[];
115
+ type URLSearchParamsStructuredArray = readonly (URLSearchParamsObject | URLSearchParamsPrimitiveArray | URLSearchParamsStructuredArray | undefined)[];
116
+ type URLSearchParamsValue = URLSearchParamsPrimitive | undefined | URLSearchParamsPrimitiveArray | URLSearchParamsStructuredArray | URLSearchParamsObject;
117
+ type URLSearchParamsObject = {
118
+ readonly [key: string]: URLSearchParamsValue;
119
+ };
120
+ export declare function toURLSearchParams(value: URLSearchParamsNativeInput | URLSearchParamsObject): URLSearchParams;
121
+ type RequestEncoderInputMap = {
122
+ json: JsonValue;
123
+ text: string;
124
+ "form-data": FormData | FormDataObject;
125
+ "form-urlencoded": URLSearchParams | URLSearchParamsNativeInput | URLSearchParamsObject;
126
+ binary: Blob | ArrayBuffer | Uint8Array;
127
+ stream: ReadableStream<Uint8Array>;
128
+ };
129
+ type RequestEncoderOutputMap = {
130
+ json: string;
131
+ text: string;
132
+ "form-data": FormData;
133
+ "form-urlencoded": URLSearchParams;
134
+ binary: Blob | ArrayBuffer;
135
+ stream: ReadableStream<Uint8Array>;
136
+ };
137
+ type ResponseDecoderOutputMap = {
138
+ json: unknown;
139
+ text: string;
140
+ blob: Blob;
141
+ arrayBuffer: ArrayBuffer;
142
+ bytes: Uint8Array;
143
+ formData: FormData;
144
+ };
145
+ type MaybePromise<T> = T | Promise<T>;
146
+ type Encoders = {
147
+ query: (query: URLSearchParamsObject) => URLSearchParams;
148
+ } & { [K in keyof RequestEncoderInputMap]: (value: RequestEncoderInputMap[K]) => MaybePromise<RequestEncoderOutputMap[K]>; };
149
+ type Decoders = { [K in keyof ResponseDecoderOutputMap]: (response: Response) => MaybePromise<ResponseDecoderOutputMap[K]>; };
150
+ type Codecs = {
151
+ encoders?: Partial<Encoders>;
152
+ decoders?: Partial<Decoders>;
153
+ };
154
+ export declare const codecs: {
155
+ encoders: {
156
+ query: typeof toURLSearchParams;
157
+ json: (value: JsonValue) => string;
158
+ text: (value: string) => string;
159
+ "form-data": typeof toFormData;
160
+ "form-urlencoded": typeof toURLSearchParams;
161
+ binary: (value: ArrayBuffer | Blob | Uint8Array<ArrayBufferLike>) => ArrayBuffer | Blob;
162
+ stream: (value: ReadableStream<Uint8Array<ArrayBufferLike>>) => ReadableStream<Uint8Array<ArrayBufferLike>>;
163
+ };
164
+ decoders: {
165
+ json: (response: Response) => Promise<unknown>;
166
+ text: (response: Response) => Promise<string>;
167
+ blob: (response: Response) => Promise<Blob>;
168
+ arrayBuffer: (response: Response) => Promise<ArrayBuffer>;
169
+ bytes: (response: Response) => Promise<Uint8Array<ArrayBuffer>>;
170
+ formData: (response: Response) => Promise<FormData>;
171
+ };
172
+ };
173
+ type ElementOrSelf<T> = T extends readonly (infer Item)[] ? Item : T;
174
+ type RequiredProperty<T, P extends PropertyKey> = T extends Record<P, infer Key extends PropertyKey> ? Key : never;
175
+ type EndpointEncoders<E extends EndpointContract> = Pick<Encoders, RequiredProperty<E["request"], "encodeAs"> | (E["request"] extends EndpointContract["request"] & {
176
+ query?: undefined;
177
+ } ? never : "query")>;
178
+ type ResponseDecoders<Shapes extends EndpointContract["response"]> = Pick<Decoders, RequiredProperty<ElementOrSelf<Shapes>, "decodeAs">>;
179
+ type CodecOverrides<Needed, Available> = Partial<Needed> & { [K in keyof Needed as [Available] extends [Pick<Needed, K>] ? never : K]: Needed[K]; };
180
+ type CodecField<Name extends string, Value> = keyof Value extends never ? {} : {} extends Value ? { [K in Name]?: Value; } : { [K in Name]: Value; };
181
+ /** Endpoint-specific overrides, with registrations missing from defaults required. */
182
+ type RequiredCodecs<Endpoint extends EndpointContract, Defaults extends Codecs = {}> = CodecField<"encoders", CodecOverrides<EndpointEncoders<Endpoint>, Defaults["encoders"]>> & CodecField<"decoders", CodecOverrides<ResponseDecoders<Endpoint["response"]>, Defaults["decoders"]>>;
183
+ type FetcherOptions<Overrides> = keyof Overrides extends never ? [] : {} extends Overrides ? [options?: {
184
+ codecs?: Overrides;
185
+ }] : [options: {
186
+ codecs: Overrides;
187
+ }];
188
+ type CodecOptions<Endpoint extends EndpointContract, Defaults extends Codecs> = FetcherOptions<RequiredCodecs<Endpoint, Defaults>>;
189
+ type RequestEncoderKey = Prettify<keyof RequestEncoderInputMap>;
190
+ type RequestShapeInput = {
191
+ query?: StandardObjectSchema;
192
+ headers?: StandardObjectSchema;
193
+ encodeAs?: RequestEncoderKey;
194
+ body?: StandardSchemaV1;
195
+ };
196
+ type RequestShape = RequestShapeInput & ({
197
+ encodeAs?: never;
198
+ body?: never;
199
+ } | {
200
+ encodeAs: RequestEncoderKey;
201
+ body: StandardSchemaV1;
202
+ });
203
+ export declare function request<const Shape extends RequestShapeInput>(shape: Shape & (true extends IsUnion<Shape> ? Invalid<"Error: unions of Request Shapes are not supported."> : RequestShapeConstraint<Shape>)): Readonly<Shape>;
204
+ type RequestShapeConstraint<T extends RequestShapeInput> = [T] extends [RequestShape] ? NoExtraPropertiesConstraint<T, keyof RequestShape> & QueryRequestConstraint<T> & HeadersRequestConstraint<T> & BodyRequestConstraint<T> : RequestShape;
205
+ type QueryRequestConstraint<T extends RequestShape> = T extends {
206
+ query: StandardObjectSchema;
207
+ } ? {
208
+ query: ExpectedObjectSchema<T["query"], URLSearchParamsValue, unknown>;
209
+ } : {};
210
+ type RequestHeaderValue = Prettify<string | number | boolean | undefined>;
211
+ type HeadersRequestConstraint<T extends RequestShape> = T extends {
212
+ headers: StandardObjectSchema;
213
+ } ? {
214
+ headers: ExpectedRequestHeaderSchema<T["headers"], T extends {
215
+ encodeAs: infer Encoding;
216
+ } ? Encoding : never>;
217
+ } : {};
218
+ type ExpectedRequestHeaderSchema<Schema extends StandardObjectSchema, Encoding> = ExpectedObjectSchema<Schema, RequestHeaderValue, unknown> & ("form-data" extends Encoding ? Extract<Lowercase<Extract<KeysOfUnion$1<StandardSchemaV1.InferOutput<Schema>> | KeysOfUnion$1<StandardSchemaV1.InferInput<Schema>>, string>>, "content-type"> extends never ? unknown : Invalid<"Error: form-data generates its own Content-Type header."> : unknown);
219
+ type KeysOfUnion$1<T> = T extends unknown ? keyof T : never;
220
+ type BodyRequestConstraint<T extends RequestShape> = T extends {
221
+ encodeAs: RequestEncoderKey;
222
+ body: StandardSchemaV1;
223
+ } ? {
224
+ body: ExpectedRequestBodySchema<T["encodeAs"], T["body"]>;
225
+ } : {};
226
+ type ExpectedRequestBodySchema<Key extends RequestEncoderKey, Schema extends StandardSchemaV1> = [Key extends unknown ? SupportsEncoding<Key, StandardSchemaV1.InferOutput<Schema>> : never] extends [true] ? Schema : Invalid<`Error: all request body schema outputs must support "${Key}".`>;
227
+ type SupportsEncoding<Key extends RequestEncoderKey, Output> = false extends Certain<Output> ? false : Key extends "json" ? undefined extends Output ? false : false extends JsonCompatible<Output> ? false : true : [Output] extends [RequestEncoderInputMap[Key]] ? true : false;
228
+ type SeenType<T, Seen extends readonly unknown[]> = Seen extends readonly [infer Head, ...infer Tail] ? (<V>() => V extends T ? 1 : 2) extends (<V>() => (V extends Head ? 1 : 2)) ? true : SeenType<T, Tail> : false;
229
+ type Certain<T, Seen extends readonly unknown[] = []> = 0 extends 1 & T ? false : unknown extends T ? false : T extends unknown ? SeenType<T, Seen> extends true ? true : T extends ReadableStream<infer Chunk> ? Certain<Chunk, [...Seen, T]> : T extends Blob | ArrayBuffer | Uint8Array | FormData | URLSearchParams ? true : T extends readonly (infer V)[] ? Certain<V, [...Seen, T]> : T extends object ? { [K in keyof T]-?: Certain<T[K], [...Seen, T]>; }[keyof T] : true : never;
230
+ type JsonCompatible<T, Seen extends readonly unknown[] = []> = T extends unknown ? SeenType<T, Seen> extends true ? true : T extends null | boolean | number | string | undefined ? true : T extends ((...args: never[]) => unknown) ? false : T extends readonly (infer Value)[] ? JsonCompatible<Value, [...Seen, T]> : T extends object ? keyof T extends never ? false : { [K in keyof T]-?: JsonCompatible<T[K], [...Seen, T]>; }[keyof T] : false : never;
231
+ type Digit = 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9;
232
+ type StatusClassDigit = 1 | 2 | 3 | 4 | 5;
233
+ type HttpStatusCode = `${StatusClassDigit}${Digit}${Digit}` extends `${infer Code extends number}` ? Code : never;
234
+ type ResponseDecoderKey = Prettify<keyof ResponseDecoderOutputMap>;
235
+ type ResponseShapeInput = {
236
+ status: HttpStatusCode;
237
+ headers?: StandardObjectSchema;
238
+ decodeAs?: ResponseDecoderKey;
239
+ body?: StandardSchemaV1;
240
+ };
241
+ type ResponseShape = ResponseShapeInput & ({
242
+ decodeAs?: never;
243
+ body?: never;
244
+ } | {
245
+ decodeAs: ResponseDecoderKey;
246
+ body: StandardSchemaV1;
247
+ });
248
+ export declare function response<const Shape extends ResponseShapeInput>(shape: Shape & (true extends IsUnion<Shape> ? Invalid<"Error: unions of Response Shapes are not supported."> : ResponseShapeConstraint<Shape>)): Readonly<Shape>;
249
+ type ResponseShapeConstraint<T extends ResponseShapeInput> = [T] extends [ResponseShape] ? NoExtraPropertiesConstraint<T, keyof ResponseShape> & HeadersResponseConstraint<T> & ResponseBodyConstraint<T> : ResponseShape;
250
+ type HeadersResponseConstraint<T extends ResponseShape> = T extends {
251
+ headers: StandardObjectSchema;
252
+ } ? {
253
+ headers: ExpectedResponseHeaderSchema<T["headers"]>;
254
+ } : {};
255
+ type ExpectedResponseHeaderSchema<Schema extends StandardObjectSchema> = ExpectedObjectSchema<Schema, unknown, string | undefined>;
256
+ type ResponseBodyConstraint<T extends ResponseShape> = T extends {
257
+ decodeAs: ResponseDecoderKey;
258
+ body: StandardSchemaV1;
259
+ } ? {
260
+ body: ExpectedResponseBodySchema<T["decodeAs"], T["body"]>;
261
+ } : {};
262
+ type ExpectedResponseBodySchema<DecodeAs extends string, Schema extends StandardSchemaV1> = DecodeAs extends keyof ResponseDecoderOutputMap ? StandardSchemaV1.InferInput<Schema> extends ResponseDecoderOutputMap[DecodeAs] ? Schema : Invalid<`Error: response body schema input is incompatible with "${DecodeAs}".`> : Schema;
263
+ type HttpMethod = Prettify<"GET" | "HEAD" | "OPTIONS" | "POST" | "PUT" | "PATCH" | "DELETE">;
264
+ interface EndpointContract {
265
+ method: HttpMethod;
266
+ path: PathShape;
267
+ request: RequestShape;
268
+ response: ResponseShape | readonly ResponseShape[];
269
+ }
270
+ /** Preserve the Request Shape and single or alternative Response Shapes. */
271
+ export declare function endpoint<const Method extends HttpMethod, const Path extends EndpointContract["path"], const Request extends RequestShapeInput, const Responses, const Contract extends {
272
+ method: Method;
273
+ path: Path;
274
+ request: Request;
275
+ response: Extract<Responses, readonly []> extends never ? [Responses] extends [EndpointContract["response"]] ? Responses : EndpointContract["response"] : EndpointContract["response"] & Invalid<"Error: endpoint response must contain at least one response.">;
276
+ }>(contract: Contract & NoExtraPropertiesConstraint<Contract, keyof EndpointContract> & {
277
+ method: Method;
278
+ path: Path;
279
+ request: true extends IsUnion<Request> ? Invalid<"Error: unions of Request Shapes are not supported."> : Request & RequestShapeConstraint<Request>;
280
+ response: CheckedResponses<Responses>;
281
+ }): Readonly<Contract>;
282
+ type CheckedResponses<Responses> = Responses extends readonly unknown[] ? { [Key in keyof Responses]: CheckedResponseItem<Responses[Key]>; } : CheckedResponseItem<Responses>;
283
+ type CheckedResponseItem<T> = T extends ResponseShape ? T & ResponseShapeConstraint<T> : ExpectedObject<T, ResponseShape>;
284
+ type CallInput<Endpoint extends EndpointContract> = Endpoint extends unknown ? Prettify<PathInput<Endpoint["path"]> & RequestInput<Endpoint["request"]>> : never;
285
+ type PathInput<Path extends EndpointContract["path"]> = Path extends {
286
+ params: infer S extends StandardSchemaV1;
287
+ } ? {
288
+ params: StandardSchemaV1.InferInput<S>;
289
+ } : {};
290
+ type RequestInput<Request extends RequestShape> = Request extends unknown ? Prettify<QueryCallInput<Request> & HeadersCallInput<Request> & BodyCallInput<Request>> : never;
291
+ type QueryCallInput<Request extends RequestShape> = Request extends {
292
+ query: StandardSchemaV1;
293
+ } ? {
294
+ query: StandardSchemaV1.InferInput<Request["query"]>;
295
+ } : {};
296
+ type HeadersCallInput<Request extends RequestShape> = Request extends {
297
+ headers: StandardSchemaV1;
298
+ } ? {
299
+ headers: StandardSchemaV1.InferInput<Request["headers"]>;
300
+ } : {};
301
+ type BodyCallInput<Request extends RequestShape> = Request extends {
302
+ body: StandardSchemaV1;
303
+ } ? {
304
+ body: StandardSchemaV1.InferInput<Request["body"]>;
305
+ } : {};
306
+ /** A Call Input section failed Standard Schema validation before transport execution. */
307
+ export declare class CallInputValidationError extends Error {
308
+ readonly section: "params" | "query" | "headers" | "body";
309
+ readonly issues: readonly StandardSchemaV1.Issue[];
310
+ constructor(section: "params" | "query" | "headers" | "body", issues: readonly StandardSchemaV1.Issue[]);
311
+ }
312
+ type TransportConfig = {
313
+ baseUrl: string;
314
+ fetch?: (request: Request, init?: RequestInit) => Promise<Response>;
315
+ codecs?: Codecs;
316
+ };
317
+ type FetchCompatibleShape = {
318
+ method: Exclude<EndpointContract["method"], "GET" | "HEAD">;
319
+ } | {
320
+ request: Extract<EndpointContract["request"], {
321
+ body?: never;
322
+ }>;
323
+ };
324
+ type CompatibleEndpoint<E extends EndpointContract> = E & ([E] extends [FetchCompatibleShape] ? {} : {
325
+ request: Invalid<"Error: Fetch cannot send GET or HEAD requests with a body.">;
326
+ });
327
+ interface Transport<C extends Codecs = {}> {
328
+ createFetcher<const Endpoint extends EndpointContract>(endpoint: CompatibleEndpoint<Endpoint>, ...options: CodecOptions<NoInfer<Endpoint>, C>): Fetcher<Endpoint>;
329
+ }
330
+ export declare function createTransport<const Config extends TransportConfig>(config: Config): Transport<Config extends {
331
+ codecs: infer C extends Codecs;
332
+ } ? C : {}>;
333
+ type FetchOptions = Omit<RequestInit, "method" | "headers" | "body" | "duplex">;
334
+ type KeysOfUnion<T> = T extends unknown ? keyof T : never;
335
+ type Fetcher<Endpoint extends EndpointContract> = KeysOfUnion<CallInput<Endpoint>> extends never ? (options?: FetchOptions) => Promise<RuntimeResult<Endpoint>> : (input: CallInput<Endpoint>, options?: FetchOptions) => Promise<RuntimeResult<Endpoint>>;
336
+ type RuntimeResult<Endpoint extends EndpointContract = EndpointContract> = ResponseResult<Endpoint["response"]>;
337
+ /** The observed HTTP response matched none of the declared Response Shapes. */
338
+ export declare class UnknownResponseError extends Error {
339
+ readonly status: number;
340
+ constructor(status: number);
341
+ }
342
+ type ResponseField<Shape, Name extends "headers" | "body"> = Shape extends Record<Name, StandardSchemaV1> ? DefinedField<Name, StandardSchemaV1.InferOutput<Shape[Name]>> : {};
343
+ type ResponseResult<Declaration extends EndpointContract["response"], Shape = Declaration extends readonly (infer Item)[] ? Item : Declaration> = Shape extends {
344
+ status: number;
345
+ } ? Prettify<{
346
+ status: Shape["status"];
347
+ } & ResponseField<Shape, "headers"> & ResponseField<Shape, "body">> : never;
348
+ export declare function prepareRequest<const Contract extends EndpointContract>(endpoint: Contract, callInput?: CallInput<Contract>): Promise<PreparedRequestFor<Contract>>;
349
+ type PreparedRequestFor<Contract extends EndpointContract> = Contract extends unknown ? ExactPreparedRequest<Contract, Contract["request"]> : never;
350
+ type ExactPathParams<Path extends EndpointContract["path"]> = Path extends {
351
+ params: StandardSchemaV1;
352
+ } ? Extract<StandardSchemaV1.InferOutput<Path["params"]>, Record<string, PathParamValue>> : never;
353
+ type ExactPreparedQuery<Request extends RequestShape> = Request extends {
354
+ query: StandardSchemaV1;
355
+ } ? {
356
+ query: StandardSchemaV1.InferOutput<Request["query"]>;
357
+ } : {};
358
+ type ExactPreparedHeaders<Request extends RequestShape> = Request extends {
359
+ headers: StandardSchemaV1;
360
+ } ? {
361
+ headers: StandardSchemaV1.InferOutput<Request["headers"]>;
362
+ } : {};
363
+ type ExactPreparedBody<Request extends RequestShape> = Request extends {
364
+ body: StandardSchemaV1;
365
+ } ? {
366
+ encodeAs: Request["encodeAs"];
367
+ body: StandardSchemaV1.InferOutput<Request["body"]>;
368
+ } : {};
369
+ type ExactPreparedRequest<Contract extends EndpointContract, Request extends RequestShape> = Prettify<{
370
+ method: Contract["method"];
371
+ resolvedPath: ResolvedPath<Contract["path"]["template"], ExactPathParams<Contract["path"]>>;
372
+ } & ExactPreparedQuery<Request> & ExactPreparedHeaders<Request> & ExactPreparedBody<Request>>;
373
+ export declare function validateResponse({ shape, response, decoders }: {
374
+ shape: ResponseShape;
375
+ response: Response;
376
+ decoders: NonNullable<Codecs["decoders"]>;
377
+ }): Promise<{
378
+ status: 100 | 101 | 102 | 103 | 104 | 105 | 106 | 107 | 108 | 109 | 110 | 111 | 112 | 113 | 114 | 115 | 116 | 117 | 118 | 119 | 120 | 121 | 122 | 123 | 124 | 125 | 126 | 127 | 128 | 129 | 130 | 131 | 132 | 133 | 134 | 135 | 136 | 137 | 138 | 139 | 140 | 141 | 142 | 143 | 144 | 145 | 146 | 147 | 148 | 149 | 150 | 151 | 152 | 153 | 154 | 155 | 156 | 157 | 158 | 159 | 160 | 161 | 162 | 163 | 164 | 165 | 166 | 167 | 168 | 169 | 170 | 171 | 172 | 173 | 174 | 175 | 176 | 177 | 178 | 179 | 180 | 181 | 182 | 183 | 184 | 185 | 186 | 187 | 188 | 189 | 190 | 191 | 192 | 193 | 194 | 195 | 196 | 197 | 198 | 199 | 200 | 201 | 202 | 203 | 204 | 205 | 206 | 207 | 208 | 209 | 210 | 211 | 212 | 213 | 214 | 215 | 216 | 217 | 218 | 219 | 220 | 221 | 222 | 223 | 224 | 225 | 226 | 227 | 228 | 229 | 230 | 231 | 232 | 233 | 234 | 235 | 236 | 237 | 238 | 239 | 240 | 241 | 242 | 243 | 244 | 245 | 246 | 247 | 248 | 249 | 250 | 251 | 252 | 253 | 254 | 255 | 256 | 257 | 258 | 259 | 260 | 261 | 262 | 263 | 264 | 265 | 266 | 267 | 268 | 269 | 270 | 271 | 272 | 273 | 274 | 275 | 276 | 277 | 278 | 279 | 280 | 281 | 282 | 283 | 284 | 285 | 286 | 287 | 288 | 289 | 290 | 291 | 292 | 293 | 294 | 295 | 296 | 297 | 298 | 299 | 300 | 301 | 302 | 303 | 304 | 305 | 306 | 307 | 308 | 309 | 310 | 311 | 312 | 313 | 314 | 315 | 316 | 317 | 318 | 319 | 320 | 321 | 322 | 323 | 324 | 325 | 326 | 327 | 328 | 329 | 330 | 331 | 332 | 333 | 334 | 335 | 336 | 337 | 338 | 339 | 340 | 341 | 342 | 343 | 344 | 345 | 346 | 347 | 348 | 349 | 350 | 351 | 352 | 353 | 354 | 355 | 356 | 357 | 358 | 359 | 360 | 361 | 362 | 363 | 364 | 365 | 366 | 367 | 368 | 369 | 370 | 371 | 372 | 373 | 374 | 375 | 376 | 377 | 378 | 379 | 380 | 381 | 382 | 383 | 384 | 385 | 386 | 387 | 388 | 389 | 390 | 391 | 392 | 393 | 394 | 395 | 396 | 397 | 398 | 399 | 400 | 401 | 402 | 403 | 404 | 405 | 406 | 407 | 408 | 409 | 410 | 411 | 412 | 413 | 414 | 415 | 416 | 417 | 418 | 419 | 420 | 421 | 422 | 423 | 424 | 425 | 426 | 427 | 428 | 429 | 430 | 431 | 432 | 433 | 434 | 435 | 436 | 437 | 438 | 439 | 440 | 441 | 442 | 443 | 444 | 445 | 446 | 447 | 448 | 449 | 450 | 451 | 452 | 453 | 454 | 455 | 456 | 457 | 458 | 459 | 460 | 461 | 462 | 463 | 464 | 465 | 466 | 467 | 468 | 469 | 470 | 471 | 472 | 473 | 474 | 475 | 476 | 477 | 478 | 479 | 480 | 481 | 482 | 483 | 484 | 485 | 486 | 487 | 488 | 489 | 490 | 491 | 492 | 493 | 494 | 495 | 496 | 497 | 498 | 499 | 500 | 501 | 502 | 503 | 504 | 505 | 506 | 507 | 508 | 509 | 510 | 511 | 512 | 513 | 514 | 515 | 516 | 517 | 518 | 519 | 520 | 521 | 522 | 523 | 524 | 525 | 526 | 527 | 528 | 529 | 530 | 531 | 532 | 533 | 534 | 535 | 536 | 537 | 538 | 539 | 540 | 541 | 542 | 543 | 544 | 545 | 546 | 547 | 548 | 549 | 550 | 551 | 552 | 553 | 554 | 555 | 556 | 557 | 558 | 559 | 560 | 561 | 562 | 563 | 564 | 565 | 566 | 567 | 568 | 569 | 570 | 571 | 572 | 573 | 574 | 575 | 576 | 577 | 578 | 579 | 580 | 581 | 582 | 583 | 584 | 585 | 586 | 587 | 588 | 589 | 590 | 591 | 592 | 593 | 594 | 595 | 596 | 597 | 598 | 599;
379
+ headers?: {} | null | undefined;
380
+ body?: {} | null | undefined;
381
+ } | undefined>;
382
+ type ParamsArgument<Params> = StandardObjectSchema extends Params ? [params?: unknown] : Params extends StandardObjectSchema ? [params: StandardSchemaV1.InferInput<Params>] : [];
383
+ export declare function resolvePath<Path extends PathShape>(path: Path, ...args: ParamsArgument<NoInfer<Path["params"]>>): Promise<string>;
384
+ export type { CallInput, Codecs, FormDataObject, PathInput, RequestInput, RuntimeResult, URLSearchParamsObject };
package/dist/public.js ADDED
@@ -0,0 +1,260 @@
1
+ // src/contract/endpoint.ts
2
+ function e(e) {
3
+ return e;
4
+ }
5
+ // src/contract/path.ts
6
+ function t(e, t) {
7
+ return {
8
+ template: e,
9
+ params: t
10
+ };
11
+ }
12
+ // src/contract/request.ts
13
+ function n(e) {
14
+ return e;
15
+ }
16
+ // src/contract/response.ts
17
+ function r(e) {
18
+ return e;
19
+ }
20
+ // src/codec/form-data.ts
21
+ function i(e) {
22
+ if (e instanceof FormData) return e;
23
+ let t = Object.entries(e).flatMap(([e, t]) => a(e, t)), n = new FormData();
24
+ for (let e of t) n.append(e.key, e.value);
25
+ return n;
26
+ }
27
+ function a(e, t, n = "auto") {
28
+ return t === void 0 ? [] : t === null ? [{
29
+ key: e,
30
+ value: ""
31
+ }] : t instanceof Blob ? [{
32
+ key: e,
33
+ value: t
34
+ }] : s(t) ? [{
35
+ key: e,
36
+ value: String(t)
37
+ }] : Array.isArray(t) ? o(e, t, n) : Object.entries(t).flatMap(([t, n]) => a(`${e}[${t}]`, n));
38
+ }
39
+ function o(e, t, n) {
40
+ let r = n === "indexed" || t.some((e) => e != null && !s(e) && !(e instanceof Blob));
41
+ return t.flatMap((t, n) => a(r ? `${e}[${n}]` : e, t, r && Array.isArray(t) ? "indexed" : "auto"));
42
+ }
43
+ function s(e) {
44
+ return typeof e == "string" || typeof e == "number" || typeof e == "boolean";
45
+ }
46
+ // src/codec/search-params.ts
47
+ function c(e) {
48
+ if (e instanceof URLSearchParams) return e;
49
+ if (typeof e == "string" || Array.isArray(e)) return new URLSearchParams(e);
50
+ let t = Object.entries(e).flatMap(([e, t]) => l(e, t)), n = new URLSearchParams();
51
+ for (let e of t) n.append(e.key, e.value);
52
+ return n;
53
+ }
54
+ function l(e, t, n = "auto") {
55
+ return t === void 0 ? [] : t === null ? [{
56
+ key: e,
57
+ value: ""
58
+ }] : d(t) ? [{
59
+ key: e,
60
+ value: String(t)
61
+ }] : Array.isArray(t) ? u(e, t, n) : Object.entries(t).flatMap(([t, n]) => l(`${e}[${t}]`, n));
62
+ }
63
+ function u(e, t, n) {
64
+ let r = n === "indexed" || t.some((e) => e != null && !d(e));
65
+ return t.flatMap((t, n) => l(r ? `${e}[${n}]` : e, t, r && Array.isArray(t) ? "indexed" : "auto"));
66
+ }
67
+ function d(e) {
68
+ return typeof e == "string" || typeof e == "number" || typeof e == "boolean";
69
+ }
70
+ // src/internal.ts
71
+ function f(e) {
72
+ return e.map((e) => !e.path || e.path.length === 0 ? e.message : `${e.path.map((e) => typeof e == "object" && e && "key" in e ? String(e.key) : String(e)).join(".")}: ${e.message}`).join("; ");
73
+ }
74
+ function p(...e) {
75
+ let t = {};
76
+ for (let n of e) for (let e in n) {
77
+ if (!Object.hasOwn(n, e)) continue;
78
+ let r = n[e];
79
+ r !== void 0 && (t[e] = r);
80
+ }
81
+ return t;
82
+ }
83
+ // src/transport/call-input.ts
84
+ var m = class extends Error {
85
+ section;
86
+ issues;
87
+ constructor(e, t) {
88
+ super(`Invalid call input for "${e}": ${f(t)}`), this.section = e, this.issues = t, this.name = "CallInputValidationError";
89
+ }
90
+ };
91
+ // src/transport/resolve-path.ts
92
+ async function h(e, t) {
93
+ if (!e.params) return e.template;
94
+ let n = await e.params["~standard"].validate(t);
95
+ if (n.issues) throw new m("params", n.issues);
96
+ return e.template.replace(/:([A-Za-z_][A-Za-z0-9_]*)|\{([A-Za-z_][A-Za-z0-9_]*)\}/gu, (e, t, r) => encodeURIComponent(String(n.value[t ?? r])));
97
+ }
98
+ // src/transport/prepare-request.ts
99
+ async function g(e, t) {
100
+ let n = e.request, r = t ?? {}, i = await h(e.path, r.params), a;
101
+ if (n.query !== void 0) {
102
+ let e = await n.query["~standard"].validate(r.query);
103
+ if (e.issues) throw new m("query", e.issues);
104
+ a = e.value;
105
+ }
106
+ let o;
107
+ if (n.headers !== void 0) {
108
+ let e = await n.headers["~standard"].validate(r.headers);
109
+ if (e.issues) throw new m("headers", e.issues);
110
+ o = e.value;
111
+ }
112
+ let s = {};
113
+ if (n.body !== void 0) {
114
+ let e = await n.body["~standard"].validate(r.body);
115
+ if (e.issues) throw new m("body", e.issues);
116
+ s = {
117
+ encodeAs: n.encodeAs,
118
+ body: e.value
119
+ };
120
+ }
121
+ return {
122
+ ...n.query === void 0 ? {} : { query: a },
123
+ ...n.headers === void 0 ? {} : { headers: o },
124
+ ...s,
125
+ method: e.method,
126
+ resolvedPath: i
127
+ };
128
+ }
129
+ // src/transport/validate-response.ts
130
+ function _(e) {
131
+ return new Proxy({}, {
132
+ get(t, n) {
133
+ if (typeof n == "string") return e.get(n) ?? void 0;
134
+ },
135
+ has(t, n) {
136
+ return typeof n == "string" && e.has(n);
137
+ },
138
+ ownKeys() {
139
+ return [...e.keys()];
140
+ },
141
+ getOwnPropertyDescriptor(t, n) {
142
+ if (typeof n != "string") return;
143
+ let r = e.get(n);
144
+ if (r !== null) return {
145
+ configurable: !0,
146
+ enumerable: !0,
147
+ value: r
148
+ };
149
+ }
150
+ });
151
+ }
152
+ function v(e) {
153
+ e.body && !e.body.locked && e.body.cancel().catch(() => {});
154
+ }
155
+ async function y({ shape: e, response: t, decoders: n }) {
156
+ if (e.status !== t.status) return;
157
+ let r;
158
+ if (e.headers) {
159
+ let n = await e.headers["~standard"].validate(_(t.headers));
160
+ if (n.issues) return;
161
+ r = n.value;
162
+ }
163
+ let i;
164
+ if (e.body) {
165
+ let r = n[e.decodeAs];
166
+ if (!r) return;
167
+ let a, o;
168
+ try {
169
+ o = t.clone(), a = await r(o);
170
+ } catch {
171
+ return;
172
+ } finally {
173
+ o && v(o);
174
+ }
175
+ let s = await e.body["~standard"].validate(a);
176
+ if (s.issues) return;
177
+ i = s.value;
178
+ }
179
+ return {
180
+ status: e.status,
181
+ ...r === void 0 ? {} : { headers: r },
182
+ ...i === void 0 ? {} : { body: i }
183
+ };
184
+ }
185
+ // src/transport/fetcher.ts
186
+ function b(e, { baseUrl: t, fetch: n, codecs: r }) {
187
+ let { encoders: i = {}, decoders: a = {} } = r, o = "status" in e.response ? [e.response] : e.response, s = e.request, c = e.path.params !== void 0 || s.query !== void 0 || s.headers !== void 0 || s.body !== void 0;
188
+ async function l(...r) {
189
+ let s = c ? r[0] : void 0, l = c ? r[1] : r[0], u = await g(e, s), d = new URL(u.resolvedPath, t);
190
+ u.query && i.query && (d.search = i.query(u.query).toString());
191
+ let f = x(u), p = await (u.encodeAs && i[u.encodeAs])?.(u.body), m = {
192
+ ...l,
193
+ method: u.method,
194
+ headers: f,
195
+ body: p
196
+ };
197
+ p instanceof ReadableStream && (m.duplex = "half");
198
+ let h = await n(new Request(d, m));
199
+ try {
200
+ for (let e of o) {
201
+ let t = await y({
202
+ shape: e,
203
+ response: h,
204
+ decoders: a
205
+ });
206
+ if (t !== void 0) return t;
207
+ }
208
+ throw new S(h.status);
209
+ } finally {
210
+ v(h);
211
+ }
212
+ }
213
+ return l;
214
+ }
215
+ function x(e) {
216
+ let t = new Headers();
217
+ for (let [n, r] of Object.entries(e.headers ?? {})) r !== void 0 && (e.encodeAs === "form-data" && n.toLowerCase() === "content-type" ? console.warn("Ignoring supplied Content-Type because Fetch generates the form-data boundary.") : t.set(n, String(r)));
218
+ return e.encodeAs === "json" && !t.has("content-type") && t.set("content-type", "application/json"), t;
219
+ }
220
+ var S = class extends Error {
221
+ status;
222
+ constructor(e) {
223
+ super(`No declared response shape matched the response with status ${e}.`), this.status = e, this.name = "UnknownResponseError";
224
+ }
225
+ }, C = {
226
+ encoders: {
227
+ query: c,
228
+ json: (e) => JSON.stringify(e),
229
+ text: (e) => e,
230
+ "form-data": i,
231
+ "form-urlencoded": c,
232
+ binary: (e) => e instanceof Uint8Array ? Uint8Array.from(e).buffer : e,
233
+ stream: (e) => e
234
+ },
235
+ decoders: {
236
+ json: (e) => e.json(),
237
+ text: (e) => e.text(),
238
+ blob: (e) => e.blob(),
239
+ arrayBuffer: (e) => e.arrayBuffer(),
240
+ bytes: async (e) => new Uint8Array(await e.arrayBuffer()),
241
+ formData: (e) => e.formData()
242
+ }
243
+ };
244
+ // src/transport/transport.ts
245
+ function w(e) {
246
+ let t = e.fetch ?? globalThis.fetch;
247
+ return { createFetcher(n, r) {
248
+ return b(n, {
249
+ baseUrl: e.baseUrl,
250
+ fetch: t,
251
+ codecs: {
252
+ encoders: p(e.codecs?.encoders, r?.codecs?.encoders),
253
+ decoders: p(e.codecs?.decoders, r?.codecs?.decoders)
254
+ }
255
+ });
256
+ } };
257
+ }
258
+ export { m as CallInputValidationError, S as UnknownResponseError, C as codecs, w as createTransport, e as endpoint, t as path, g as prepareRequest, n as request, h as resolvePath, r as response, i as toFormData, c as toURLSearchParams, y as validateResponse };
259
+
260
+ //# sourceMappingURL=public.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"public.js","names":["endpoint","contract","path","request","shape","response","toFormData","value","entries","key","fieldValue","formDataFieldEntries","formData","entry","isFormDataScalar","formDataArrayEntries","arrayEncodingMode","childKey","childValue","hasStructuredValue","item","index","toURLSearchParams","urlSearchParamFieldEntries","searchParams","isURLSearchParamsScalar","urlSearchParamArrayEntries","formatValidationIssues","issues","issue","segment","shallowMergeDefined","layers","merged","layer","CallInputValidationError","section","resolvePath","result","params","colon","brace","prepareRequest","input","callInput","resolvedPath","query","headers","preparedBody","createCaseInsensitiveHeaders","property","discardResponseBody","validateResponse","validatedHeaders","headerResult","validatedBody","decode","decoders","decoded","candidate","bodyResult","createFetcher","codecs","responseShapes","hasCallInput","fetcher","rawArgs","options","preparedRequest","url","baseUrl","encoders","normalizeHeaders","body","init","fetch","UnknownResponseError","name","status","createTransport","dispatch","config"],"sources":["../src/contract/endpoint.ts","../src/contract/path.ts","../src/contract/request.ts","../src/contract/response.ts","../src/codec/form-data.ts","../src/codec/search-params.ts","../src/internal.ts","../src/transport/call-input.ts","../src/transport/resolve-path.ts","../src/transport/prepare-request.ts","../src/transport/validate-response.ts","../src/transport/fetcher.ts","../src/codec/codecs.ts","../src/transport/transport.ts"],"sourcesContent":["import type {\n ExpectedObject,\n Invalid,\n IsUnion,\n NoExtraPropertiesConstraint,\n Prettify,\n} from \"../internal\";\nimport type { PathShape } from \"./path\";\nimport type { RequestShape, RequestShapeConstraint, RequestShapeInput } from \"./request\";\nimport type { ResponseShape, ResponseShapeConstraint } from \"./response\";\n\nexport type HttpMethod = Prettify<\"GET\" | \"HEAD\" | \"OPTIONS\" | \"POST\" | \"PUT\" | \"PATCH\" | \"DELETE\">;\n\nexport interface EndpointContract {\n method: HttpMethod;\n path: PathShape;\n request: RequestShape;\n response: ResponseShape | readonly ResponseShape[];\n}\n\n/** Preserve the Request Shape and single or alternative Response Shapes. */\nexport function endpoint<\n // Infer each side independently so an invalid response cannot widen the request.\n const Method extends HttpMethod,\n const Path extends EndpointContract[\"path\"],\n const Request extends RequestShapeInput,\n const Responses,\n const Contract extends {\n method: Method;\n path: Path;\n request: Request;\n // Retain independent response inference when the request is invalid and let\n // the per-item check supply expected types for invalid response fields.\n response: Extract<Responses, readonly []> extends never\n ? [Responses] extends [EndpointContract[\"response\"]]\n ? Responses\n : EndpointContract[\"response\"]\n : EndpointContract[\"response\"] &\n Invalid<\"Error: endpoint response must contain at least one response.\">;\n },\n>(\n contract: Contract &\n NoExtraPropertiesConstraint<Contract, keyof EndpointContract> & {\n method: Method;\n path: Path;\n request: true extends IsUnion<Request>\n ? Invalid<\"Error: unions of Request Shapes are not supported.\">\n : Request & RequestShapeConstraint<Request>;\n response: CheckedResponses<Responses>;\n },\n): Readonly<Contract> {\n return contract;\n}\n\ntype CheckedResponses<Responses> = Responses extends readonly unknown[]\n ? { [Key in keyof Responses]: CheckedResponseItem<Responses[Key]> }\n : CheckedResponseItem<Responses>;\n\n// Keep direct inference for valid shapes (including unions). For invalid shapes,\n// ExpectedObject supplies field expectations without intersecting invalid literals back in.\ntype CheckedResponseItem<T> = T extends ResponseShape\n ? T & ResponseShapeConstraint<T>\n : ExpectedObject<T, ResponseShape>;\n","import type { StandardSchemaV1 } from \"@standard-schema/spec\";\nimport type { Invalid, Prettify, ExpectedObjectSchema, StandardObjectSchema } from \"../internal\";\n\nexport type PathParamValue = Prettify<string | number>;\n\nexport type PathShape = {\n template: string;\n params: StandardObjectSchema | undefined;\n};\n\nexport function path<const T extends string>(\n template: T &\n ExpectedPath<T> &\n ([PathParamNames<T>[number]] extends [never]\n ? unknown\n : Invalid<\"Error: params is required when path contains placeholders.\">),\n): Readonly<{ template: T; params: undefined }>;\nexport function path<const T extends string, const S extends StandardObjectSchema>(\n template: T & ExpectedPath<T>,\n params: S & ExpectedPathParams<NoInfer<T>, S>,\n): Readonly<{ template: T; params: S }>;\nexport function path(template: string, params?: StandardObjectSchema): PathShape {\n return { template, params };\n}\n\n/** Computes substitution for a path already validated during contract authoring. */\nexport type ResolvedPath<\n Path extends string,\n Params extends Record<string, PathParamValue>,\n> = Path extends `${string}:${string}`\n ? ResolveColonPath<Path, Params>\n : ResolveBracePath<Path, Params>;\n\n/**\n * Extracts path placeholder names as a tuple in source order.\n *\n * Repeated placeholder names are preserved. Index the tuple with `number` to\n * obtain a union of its parameter names.\n * Names follow `[A-Za-z_][A-Za-z0-9_]*`: colon placeholders stop at the first\n * other character; brace placeholders require an immediate closing brace.\n * Malformed placeholders and mixed styles produce `never`.\n *\n * @example\n * type ParamNames = PathParamNames<\"/users/{userId}/posts/{postId}\">;\n * // [\"userId\", \"postId\"]\n *\n * type ParamName = ParamNames[number];\n * // \"userId\" | \"postId\"\n */\nexport type PathParamNames<Path extends string> = Path extends unknown\n ? PathPlaceholderStyle<Path> extends \"mixed\"\n ? never\n : PathPlaceholderStyle<Path> extends \"colon\"\n ? ColonPathParamNameTuple<Path>\n : PathPlaceholderStyle<Path> extends \"brace\"\n ? BracePathParamNameTuple<Path>\n : []\n : never;\n\n/** Whether a literal name matches `[A-Za-z_][A-Za-z0-9_]*` in full. */\nexport type IsValidPathParamName<Name extends string> = string extends Name\n ? false\n : Name extends `${infer First}${infer Rest}`\n ? ContainsOnlyCharacters<First, PathParamNameStart> extends true\n ? ContainsOnlyCharacters<Rest, PathParamNameCharacter>\n : false\n : false;\n\ntype ContainsOnlyCharacters<\n Value extends string,\n AllowedCharacter extends string,\n> = Value extends \"\"\n ? true\n : Value extends `${infer Character}${infer Rest}`\n ? Character extends AllowedCharacter\n ? ContainsOnlyCharacters<Rest, AllowedCharacter>\n : false\n : false;\n\n// Concrete literals produce required record keys; open patterns produce index\n// signatures. Distribute over unions to validate every member.\nexport type ExpectedPath<Path extends string> = Path extends unknown\n ? {} extends Record<Path, never>\n ? Invalid<\"Error: path must be a string literal.\">\n : Path extends `//${string}`\n ? Invalid<'Error: path must not start with \"//\".'>\n : Path extends `/${string}`\n ? ExpectedPathWithValidPlaceholders<Path>\n : Invalid<\"Error: path must start with '/'.\">\n : never;\n\n// Keep the diagnostic for each invalid union member during contract authoring.\ntype ExpectedPathWithValidPlaceholders<Path extends string> = Path extends unknown\n ? PathPlaceholderStyle<Path> extends \"mixed\"\n ? Invalid<'Error: path must not mix \":id\" and \"{id}\" placeholder styles.'>\n : [PathParamNames<Path>] extends [never]\n ? Invalid<\"Error: path contains an invalid placeholder.\">\n : Path\n : never;\n\ntype ExpectedPathParams<\n Path extends string,\n Params extends StandardObjectSchema | undefined,\n> = [PathParamNames<Path>[number]] extends [never]\n ? Params extends StandardObjectSchema\n ? Invalid<\"Error: params may only be declared when path contains placeholders.\">\n : undefined\n : Params extends StandardObjectSchema\n ? ExpectedPathParamsSchema<Path, Params>\n : Invalid<\"Error: params is required when path contains placeholders.\">;\n\ntype ExpectedPathParamsSchema<Path extends string, Schema extends StandardObjectSchema> =\n ExpectedObjectSchema<Schema, PathParamValue, unknown> extends Schema\n ? [MissingPathParamKeys<Path, Schema>] extends [never]\n ? [ExtraPathParamKeys<Path, Schema>] extends [never]\n ? StandardSchemaV1.InferOutput<Schema> extends Record<\n PathParamNames<Path>[number],\n PathParamValue\n >\n ? Schema\n : Invalid<\"Error: params schema must output a required value for every path parameter.\">\n : Invalid<`Error: params schema has keys that do not match declared path parameters: ${ExtraPathParamKeys<\n Path,\n Schema\n > &\n string}`>\n : Invalid<`Error: params schema is missing path parameters: ${MissingPathParamKeys<\n Path,\n Schema\n > &\n string}`>\n : ExpectedObjectSchema<Schema, PathParamValue, unknown>;\n\ntype MissingPathParamKeys<Path extends string, Schema extends StandardObjectSchema> = Exclude<\n PathParamNames<Path>[number],\n Extract<keyof StandardSchemaV1.InferOutput<Schema>, string>\n>;\n\ntype ExtraPathParamKeys<Path extends string, Schema extends StandardObjectSchema> = Exclude<\n Extract<keyof StandardSchemaV1.InferOutput<Schema>, string>,\n PathParamNames<Path>[number]\n>;\n\n// Classify before parsing so recursive helpers only handle their own syntax.\n// Unmatched braces count too: malformed paths cannot bypass this boundary.\ntype PathPlaceholderStyle<Path extends string> = Path extends `${string}:${string}`\n ? Path extends `${string}${\"{\" | \"}\"}${string}`\n ? \"mixed\"\n : \"colon\"\n : Path extends `${string}${\"{\" | \"}\"}${string}`\n ? \"brace\"\n : \"plain\";\n\ntype ColonPathParamNameTuple<Path extends string> = Path extends `${string}:${infer After}`\n ? ReadPathParamName<After> extends [infer Name extends string, infer Rest extends string]\n ? IsValidPathParamName<Name> extends true\n ? [Name, ...ColonPathParamNameTuple<Rest>]\n : never\n : never\n : [];\n\ntype BracePathParamNameTuple<Path extends string> =\n Path extends `${infer Prefix}{${infer Name}}${infer Rest}`\n ? Prefix extends `${string}${\"{\" | \"}\"}${string}`\n ? never\n : IsValidPathParamName<Name> extends true\n ? [Name, ...BracePathParamNameTuple<Rest>]\n : never\n : Path extends `${string}${\"{\" | \"}\"}${string}`\n ? never\n : [];\n\ntype ResolveColonPath<\n Path extends string,\n Params extends Record<string, PathParamValue>,\n> = Path extends `${infer Prefix}:${infer After}`\n ? ReadPathParamName<After> extends [infer Name extends string, infer Rest extends string]\n ? `${Prefix}${Params[Name]}${ResolveColonPath<Rest, Params>}`\n : never\n : Path;\n\ntype ResolveBracePath<\n Path extends string,\n Params extends Record<string, PathParamValue>,\n> = Path extends `${infer Prefix}{${infer Name}}${infer Rest}`\n ? `${Prefix}${Params[Name]}${ResolveBracePath<Rest, Params>}`\n : Path;\n\ntype ReadPathParamName<\n Value extends string,\n Name extends string = \"\",\n> = Value extends `${infer Character}${infer Rest}`\n ? Character extends PathParamNameCharacter\n ? ReadPathParamName<Rest, `${Name}${Character}`>\n : [Name, Value]\n : [Name, Value];\n\ntype PathParamNameStart =\n | StringCharacters<\"abcdefghijklmnopqrstuvwxyz\">\n | StringCharacters<\"ABCDEFGHIJKLMNOPQRSTUVWXYZ\">\n | \"_\";\n\ntype PathParamNameCharacter = PathParamNameStart | StringCharacters<\"0123456789\">;\n\ntype StringCharacters<Value extends string> = Value extends `${infer Character}${infer Rest}`\n ? Character | StringCharacters<Rest>\n : never;\n","import type { StandardSchemaV1 } from \"@standard-schema/spec\";\nimport type { RequestEncoderInputMap } from \"../codec/codecs\";\nimport type { URLSearchParamsValue } from \"../codec/search-params\";\nimport type {\n ExpectedObjectSchema,\n Invalid,\n IsUnion,\n NoExtraPropertiesConstraint,\n Prettify,\n StandardObjectSchema,\n} from \"../internal\";\n\nexport type RequestEncoderKey = Prettify<keyof RequestEncoderInputMap>;\n\nexport type RequestShapeInput = {\n query?: StandardObjectSchema;\n headers?: StandardObjectSchema;\n encodeAs?: RequestEncoderKey;\n body?: StandardSchemaV1;\n};\n\nexport type RequestShape = RequestShapeInput &\n ({ encodeAs?: never; body?: never } | { encodeAs: RequestEncoderKey; body: StandardSchemaV1 });\n\nexport function request<const Shape extends RequestShapeInput>(\n shape: Shape &\n (true extends IsUnion<Shape>\n ? Invalid<\"Error: unions of Request Shapes are not supported.\">\n : RequestShapeConstraint<Shape>),\n): Readonly<Shape> {\n return shape;\n}\n\nexport type RequestShapeConstraint<T extends RequestShapeInput> = [T] extends [RequestShape]\n ? NoExtraPropertiesConstraint<T, keyof RequestShape> &\n QueryRequestConstraint<T> &\n HeadersRequestConstraint<T> &\n BodyRequestConstraint<T>\n : RequestShape;\n\ntype QueryRequestConstraint<T extends RequestShape> = T extends {\n query: StandardObjectSchema;\n}\n ? { query: ExpectedObjectSchema<T[\"query\"], URLSearchParamsValue, unknown> }\n : {};\n\ntype RequestHeaderValue = Prettify<string | number | boolean | undefined>;\n\nexport type RequestHeaders = {\n readonly [name: string]: RequestHeaderValue;\n};\n\ntype HeadersRequestConstraint<T extends RequestShape> = T extends {\n headers: StandardObjectSchema;\n}\n ? {\n headers: ExpectedRequestHeaderSchema<\n T[\"headers\"],\n T extends { encodeAs: infer Encoding } ? Encoding : never\n >;\n }\n : {};\n\ntype ExpectedRequestHeaderSchema<\n Schema extends StandardObjectSchema,\n Encoding,\n> = ExpectedObjectSchema<Schema, RequestHeaderValue, unknown> &\n (\"form-data\" extends Encoding\n ? Extract<\n Lowercase<\n Extract<\n | KeysOfUnion<StandardSchemaV1.InferOutput<Schema>>\n | KeysOfUnion<StandardSchemaV1.InferInput<Schema>>,\n string\n >\n >,\n \"content-type\"\n > extends never\n ? unknown\n : Invalid<\"Error: form-data generates its own Content-Type header.\">\n : unknown);\n\ntype KeysOfUnion<T> = T extends unknown ? keyof T : never;\n\ntype BodyRequestConstraint<T extends RequestShape> = T extends {\n encodeAs: RequestEncoderKey;\n body: StandardSchemaV1;\n}\n ? { body: ExpectedRequestBodySchema<T[\"encodeAs\"], T[\"body\"]> }\n : {};\n\ntype ExpectedRequestBodySchema<Key extends RequestEncoderKey, Schema extends StandardSchemaV1> = [\n Key extends unknown ? SupportsEncoding<Key, StandardSchemaV1.InferOutput<Schema>> : never,\n] extends [true]\n ? Schema\n : Invalid<`Error: all request body schema outputs must support \"${Key}\".`>;\n\ntype SupportsEncoding<Key extends RequestEncoderKey, Output> =\n false extends Certain<Output>\n ? false\n : Key extends \"json\"\n ? undefined extends Output\n ? false\n : false extends JsonCompatible<Output>\n ? false\n : true\n : [Output] extends [RequestEncoderInputMap[Key]]\n ? true\n : false;\n\n// A subtype can add unsafe properties. Only an exact prior type is a recursive\n// revisit; assignability to an ancestor is not enough to stop inspecting it.\ntype SeenType<T, Seen extends readonly unknown[]> = Seen extends readonly [\n infer Head,\n ...infer Tail,\n]\n ? (<V>() => V extends T ? 1 : 2) extends <V>() => V extends Head ? 1 : 2\n ? true\n : SeenType<T, Tail>\n : false;\n\n// Assignability alone admits any inside structured values. Inspect certainty\n// separately, terminating on recursive types and treating native values as leaves.\ntype Certain<T, Seen extends readonly unknown[] = []> = 0 extends 1 & T\n ? false\n : unknown extends T\n ? false\n : T extends unknown\n ? SeenType<T, Seen> extends true\n ? true\n : T extends ReadableStream<infer Chunk>\n ? Certain<Chunk, [...Seen, T]>\n : T extends Blob | ArrayBuffer | Uint8Array | FormData | URLSearchParams\n ? true\n : T extends readonly (infer V)[]\n ? Certain<V, [...Seen, T]>\n : T extends object\n ? { [K in keyof T]-?: Certain<T[K], [...Seen, T]> }[keyof T]\n : true\n : never;\n\n// Check properties structurally so interface-based schemas do not need an\n// artificial string index signature. Optional/nested undefined stays supported.\ntype JsonCompatible<T, Seen extends readonly unknown[] = []> = T extends unknown\n ? SeenType<T, Seen> extends true\n ? true\n : T extends null | boolean | number | string | undefined\n ? true\n : T extends (...args: never[]) => unknown\n ? false\n : T extends readonly (infer Value)[]\n ? JsonCompatible<Value, [...Seen, T]>\n : T extends object\n ? keyof T extends never\n ? false\n : {\n [K in keyof T]-?: JsonCompatible<T[K], [...Seen, T]>;\n }[keyof T]\n : false\n : never;\n","import type { ResponseDecoderOutputMap } from \"../codec/codecs\";\nimport type { StandardSchemaV1 } from \"@standard-schema/spec\";\nimport type {\n ExpectedObjectSchema,\n Invalid,\n IsUnion,\n NoExtraPropertiesConstraint,\n Prettify,\n StandardObjectSchema,\n} from \"../internal\";\n\ntype Digit = 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9;\ntype StatusClassDigit = 1 | 2 | 3 | 4 | 5;\n\nexport type HttpStatusCode =\n `${StatusClassDigit}${Digit}${Digit}` extends `${infer Code extends number}` ? Code : never;\n\nexport type ResponseDecoderKey = Prettify<keyof ResponseDecoderOutputMap>;\n\ntype ResponseShapeInput = {\n status: HttpStatusCode;\n headers?: StandardObjectSchema;\n decodeAs?: ResponseDecoderKey;\n body?: StandardSchemaV1;\n};\n\nexport type ResponseShape = ResponseShapeInput &\n ({ decodeAs?: never; body?: never } | { decodeAs: ResponseDecoderKey; body: StandardSchemaV1 });\n\nexport function response<const Shape extends ResponseShapeInput>(\n shape: Shape &\n (true extends IsUnion<Shape>\n ? Invalid<\"Error: unions of Response Shapes are not supported.\">\n : ResponseShapeConstraint<Shape>),\n): Readonly<Shape> {\n return shape;\n}\n\nexport type ResponseShapeConstraint<T extends ResponseShapeInput> = [T] extends [ResponseShape]\n ? NoExtraPropertiesConstraint<T, keyof ResponseShape> &\n HeadersResponseConstraint<T> &\n ResponseBodyConstraint<T>\n : ResponseShape;\n\ntype HeadersResponseConstraint<T extends ResponseShape> = T extends {\n headers: StandardObjectSchema;\n}\n ? { headers: ExpectedResponseHeaderSchema<T[\"headers\"]> }\n : {};\n\ntype ExpectedResponseHeaderSchema<Schema extends StandardObjectSchema> = ExpectedObjectSchema<\n Schema,\n unknown,\n string | undefined\n>;\n\ntype ResponseBodyConstraint<T extends ResponseShape> = T extends {\n decodeAs: ResponseDecoderKey;\n body: StandardSchemaV1;\n}\n ? { body: ExpectedResponseBodySchema<T[\"decodeAs\"], T[\"body\"]> }\n : {};\n\ntype ExpectedResponseBodySchema<\n DecodeAs extends string,\n Schema extends StandardSchemaV1,\n> = DecodeAs extends keyof ResponseDecoderOutputMap\n ? StandardSchemaV1.InferInput<Schema> extends ResponseDecoderOutputMap[DecodeAs]\n ? Schema\n : Invalid<`Error: response body schema input is incompatible with \"${DecodeAs}\".`>\n : Schema;\n","type FormDataPrimitive = string | number | boolean | null | Blob;\n\ntype FormDataPrimitiveArray = readonly (FormDataPrimitive | undefined)[];\n\ntype FormDataStructuredArray = readonly (\n | FormDataObject\n | FormDataPrimitiveArray\n | FormDataStructuredArray\n | undefined\n)[];\n\ntype FormDataValue =\n | FormDataPrimitive\n | undefined\n | FormDataPrimitiveArray\n | FormDataStructuredArray\n | FormDataObject;\n\nexport type FormDataObject = {\n readonly [key: string]: FormDataValue;\n};\n\ntype ArrayEncodingMode = \"auto\" | \"indexed\";\n\ntype FormDataEntry = {\n key: string;\n value: string | Blob;\n};\n\nexport function toFormData(value: FormData | FormDataObject): FormData {\n if (value instanceof FormData) {\n return value;\n }\n\n const entries = Object.entries(value).flatMap(([key, fieldValue]) =>\n formDataFieldEntries(key, fieldValue),\n );\n\n const formData = new FormData();\n for (const entry of entries) {\n formData.append(entry.key, entry.value);\n }\n\n return formData;\n}\n\nfunction formDataFieldEntries(\n key: string,\n value: FormDataValue,\n arrayEncodingMode: ArrayEncodingMode = \"auto\",\n): FormDataEntry[] {\n if (value === undefined) {\n return [];\n }\n\n if (value === null) {\n return [{ key, value: \"\" }];\n }\n\n if (value instanceof Blob) {\n return [{ key, value }];\n }\n\n if (isFormDataScalar(value)) {\n return [{ key, value: String(value) }];\n }\n\n if (Array.isArray(value)) {\n return formDataArrayEntries(key, value, arrayEncodingMode);\n }\n\n return Object.entries(value).flatMap(([childKey, childValue]) =>\n formDataFieldEntries(`${key}[${childKey}]`, childValue),\n );\n}\n\nfunction formDataArrayEntries(\n key: string,\n value: readonly FormDataValue[],\n arrayEncodingMode: ArrayEncodingMode,\n): FormDataEntry[] {\n const hasStructuredValue =\n arrayEncodingMode === \"indexed\" ||\n value.some(\n (item) =>\n item !== undefined && item !== null && !isFormDataScalar(item) && !(item instanceof Blob),\n );\n\n return value.flatMap((item, index) => {\n const itemKey = hasStructuredValue ? `${key}[${index}]` : key;\n\n return formDataFieldEntries(\n itemKey,\n item,\n hasStructuredValue && Array.isArray(item) ? \"indexed\" : \"auto\",\n );\n });\n}\n\nfunction isFormDataScalar(value: unknown): value is string | number | boolean {\n return typeof value === \"string\" || typeof value === \"number\" || typeof value === \"boolean\";\n}\n","import type { Prettify } from \"../internal\";\n\nexport type URLSearchParamsNativeInput = NonNullable<\n ConstructorParameters<typeof URLSearchParams>[0]\n>;\n\ntype URLSearchParamsPrimitive = Prettify<string | number | boolean | null>;\n\ntype URLSearchParamsPrimitiveArray = readonly (URLSearchParamsPrimitive | undefined)[];\n\ntype URLSearchParamsStructuredArray = readonly (\n | URLSearchParamsObject\n | URLSearchParamsPrimitiveArray\n | URLSearchParamsStructuredArray\n | undefined\n)[];\n\nexport type URLSearchParamsValue =\n | URLSearchParamsPrimitive\n | undefined\n | URLSearchParamsPrimitiveArray\n | URLSearchParamsStructuredArray\n | URLSearchParamsObject;\n\nexport type URLSearchParamsObject = {\n readonly [key: string]: URLSearchParamsValue;\n};\n\ntype ArrayEncodingMode = \"auto\" | \"indexed\";\n\ntype URLSearchParamEntry = {\n key: string;\n value: string;\n};\n\nexport function toURLSearchParams(\n value: URLSearchParamsNativeInput | URLSearchParamsObject,\n): URLSearchParams {\n if (value instanceof URLSearchParams) {\n return value;\n }\n\n if (typeof value === \"string\" || Array.isArray(value)) {\n return new URLSearchParams(value);\n }\n\n const entries = Object.entries(value).flatMap(([key, fieldValue]) =>\n urlSearchParamFieldEntries(key, fieldValue),\n );\n\n const searchParams = new URLSearchParams();\n for (const entry of entries) {\n searchParams.append(entry.key, entry.value);\n }\n\n return searchParams;\n}\n\nfunction urlSearchParamFieldEntries(\n key: string,\n value: URLSearchParamsValue,\n arrayEncodingMode: ArrayEncodingMode = \"auto\",\n): URLSearchParamEntry[] {\n if (value === undefined) {\n return [];\n }\n\n if (value === null) {\n return [{ key, value: \"\" }];\n }\n\n if (isURLSearchParamsScalar(value)) {\n return [{ key, value: String(value) }];\n }\n\n if (Array.isArray(value)) {\n return urlSearchParamArrayEntries(key, value, arrayEncodingMode);\n }\n\n return Object.entries(value).flatMap(([childKey, childValue]) =>\n urlSearchParamFieldEntries(`${key}[${childKey}]`, childValue),\n );\n}\n\nfunction urlSearchParamArrayEntries(\n key: string,\n value: readonly URLSearchParamsValue[],\n arrayEncodingMode: ArrayEncodingMode,\n): URLSearchParamEntry[] {\n const hasStructuredValue =\n arrayEncodingMode === \"indexed\" ||\n value.some((item) => item !== undefined && item !== null && !isURLSearchParamsScalar(item));\n\n return value.flatMap((item, index) => {\n const itemKey = hasStructuredValue ? `${key}[${index}]` : key;\n\n return urlSearchParamFieldEntries(\n itemKey,\n item,\n hasStructuredValue && Array.isArray(item) ? \"indexed\" : \"auto\",\n );\n });\n}\n\nfunction isURLSearchParamsScalar(value: unknown): value is string | number | boolean {\n return typeof value === \"string\" || typeof value === \"number\" || typeof value === \"boolean\";\n}\n","import type { StandardSchemaV1, StandardTypedV1 } from \"@standard-schema/spec\";\n\n/**\n * Makes types easier to read in editor hovers and error messages.\n *\n * @example <caption>Hovers show all fields together in one object.</caption>\n * type User = { id: string } & { name: string };\n * // Hover: { id: string } & { name: string }\n *\n * type ReadableUser = Prettify<User>;\n * // Hover: { id: string; name: string }\n *\n * @example <caption>Errors list allowed values without looking up the type.</caption>\n * type Method = \"GET\" | \"POST\";\n * const method: Method = \"PUT\";\n * // Error: Type '\"PUT\"' is not assignable to type 'Method'.\n *\n * type ReadableMethod = Prettify<\"GET\" | \"POST\">;\n * const readableMethod: ReadableMethod = \"PUT\";\n * // Error: Type '\"PUT\"' is not assignable to type '\"GET\" | \"POST\"'.\n */\nexport type Prettify<T, Result = { [K in keyof T]: T[K] } & {}> = [T] extends [object]\n ? Result\n : Result & ({} | null | undefined);\n\n/** A declared field whose runtime value is omitted when it is undefined.\n * Declaration presence must be checked separately; never is a required value.\n */\nexport type DefinedField<Name extends PropertyKey, Value> = undefined extends Value\n ? { [Key in Name]?: Value }\n : { [Key in Name]: Value };\n\n// Collect extra keys from every union member before building the constraint.\ntype ExtraPropertyKeys<Actual, AllowedKeys extends PropertyKey> = Actual extends unknown\n ? Exclude<keyof Actual, AllowedKeys>\n : never;\n\nexport type NoExtraPropertiesConstraint<Actual, AllowedKeys extends PropertyKey> = [\n ExtraPropertyKeys<Actual, AllowedKeys>,\n] extends [never]\n ? {}\n : {\n [Key in ExtraPropertyKeys<Actual, AllowedKeys>]: Invalid<\n Key extends string | number\n ? `Error: unknown property: ${Key}`\n : \"Error: unknown symbol property\"\n >;\n };\n\n/**\n * Infer one object or a flat collection without retaining invalid field values\n * in the expected type. The item intersection also preserves union relations\n * (for example, two fields that must be declared together).\n * Dependent constraints and exact-key checks belong to the caller.\n * Union inputs also need a direct inference source for validated shapes;\n * reverse mapping alone may infer only their first member.\n */\nexport type ExpectedObjectOrArray<T, Item extends object> = T extends readonly unknown[]\n ? { [K in keyof T]: ExpectedObjectOrArray<T[K], Item> & Item }\n : ExpectedObject<T, Item>;\n\nexport type ExpectedObject<T, Item extends object> = {\n [K in keyof T]: K extends keyof Item ? (T[K] extends Item[K] ? T[K] : Item[K]) : T[K];\n} & Item;\n\n/**\n * Detect whole-type unions, allowing unions within fields and tuple elements.\n * Check with `true extends IsUnion<T>`: overlapping members can yield boolean.\n * never stays never; any/unknown and normalized single types yield false.\n */\nexport type IsUnion<T, Whole = T> = T extends unknown\n ? [Whole] extends [T]\n ? false\n : true\n : never;\n\ndeclare const invalid: unique symbol;\n\n/**\n * A custom type-level error when native TypeScript errors do not explain the rule.\n * Supports intersecting independent failures; diagnostic formatting is compiler-controlled.\n *\n * @example\n * type NonEmpty<S extends string> = S extends \"\"\n * ? Invalid<\"Value must not be empty\">\n * : S;\n */\nexport interface Invalid<Message extends string> {\n readonly [invalid]: { readonly [Key in Message]: never };\n}\n\nexport function formatValidationIssues(issues: readonly StandardSchemaV1.Issue[]): string {\n return issues\n .map((issue) => {\n if (!issue.path || issue.path.length === 0) {\n return issue.message;\n }\n\n const path = issue.path\n .map((segment) =>\n typeof segment === \"object\" && segment !== null && \"key\" in segment\n ? String(segment.key)\n : String(segment),\n )\n .join(\".\");\n\n return `${path}: ${issue.message}`;\n })\n .join(\"; \");\n}\n\nexport type StandardObjectSchema = StandardSchemaV1<\n Record<string, unknown>,\n Record<string, unknown>\n>;\n\ntype ConstrainedObjectSchema<\n Schema extends StandardObjectSchema,\n OutputAllowedValue,\n InputAllowedValue,\n> = StandardTypedV1<\n { [Key in keyof StandardSchemaV1.InferInput<Schema>]: InputAllowedValue },\n { [Key in keyof StandardSchemaV1.InferOutput<Schema>]: OutputAllowedValue }\n>;\n\nexport type ExpectedObjectSchema<\n Schema extends StandardObjectSchema,\n OutputAllowedValue,\n InputAllowedValue,\n> = [Schema] extends [ConstrainedObjectSchema<Schema, OutputAllowedValue, InputAllowedValue>]\n ? Schema\n : ConstrainedObjectSchema<Schema, OutputAllowedValue, InputAllowedValue>;\n\nexport type JsonValue =\n | null\n | boolean\n | number\n | string\n | readonly (JsonValue | undefined)[]\n | { readonly [key: string]: JsonValue | undefined };\n\nexport function shallowMergeDefined<T extends object>(...layers: (T | undefined)[]): Partial<T> {\n const merged: Partial<T> = {};\n for (const layer of layers) {\n for (const key in layer) {\n if (!Object.hasOwn(layer, key)) continue;\n const value = layer[key];\n if (value !== undefined) merged[key] = value;\n }\n }\n return merged;\n}\n","import type { StandardSchemaV1 } from \"@standard-schema/spec\";\nimport type { EndpointContract } from \"../contract/endpoint\";\nimport type { RequestShape } from \"../contract/request\";\nimport { formatValidationIssues, type Prettify } from \"../internal\";\n\nexport type CallInput<Endpoint extends EndpointContract> = Endpoint extends unknown\n ? Prettify<PathInput<Endpoint[\"path\"]> & RequestInput<Endpoint[\"request\"]>>\n : never;\n\nexport type PathInput<Path extends EndpointContract[\"path\"]> = Path extends {\n params: infer S extends StandardSchemaV1;\n}\n ? { params: StandardSchemaV1.InferInput<S> }\n : {};\n\nexport type RequestInput<Request extends RequestShape> = Request extends unknown\n ? Prettify<QueryCallInput<Request> & HeadersCallInput<Request> & BodyCallInput<Request>>\n : never;\n\ntype QueryCallInput<Request extends RequestShape> = Request extends {\n query: StandardSchemaV1;\n}\n ? { query: StandardSchemaV1.InferInput<Request[\"query\"]> }\n : {};\n\ntype HeadersCallInput<Request extends RequestShape> = Request extends {\n headers: StandardSchemaV1;\n}\n ? { headers: StandardSchemaV1.InferInput<Request[\"headers\"]> }\n : {};\n\ntype BodyCallInput<Request extends RequestShape> = Request extends {\n body: StandardSchemaV1;\n}\n ? { body: StandardSchemaV1.InferInput<Request[\"body\"]> }\n : {};\n\n/** A Call Input section failed Standard Schema validation before transport execution. */\nexport class CallInputValidationError extends Error {\n constructor(\n readonly section: \"params\" | \"query\" | \"headers\" | \"body\",\n readonly issues: readonly StandardSchemaV1.Issue[],\n ) {\n super(`Invalid call input for \"${section}\": ${formatValidationIssues(issues)}`);\n this.name = \"CallInputValidationError\";\n }\n}\n","import { CallInputValidationError } from \"./call-input\";\nimport type { StandardSchemaV1 } from \"@standard-schema/spec\";\nimport type { PathShape } from \"../contract/path\";\nimport type { StandardObjectSchema } from \"../internal\";\n\ntype ParamsArgument<Params> = StandardObjectSchema extends Params\n ? [params?: unknown]\n : Params extends StandardObjectSchema\n ? [params: StandardSchemaV1.InferInput<Params>]\n : [];\n\nexport function resolvePath<Path extends PathShape>(\n path: Path,\n ...args: ParamsArgument<NoInfer<Path[\"params\"]>>\n): Promise<string>;\nexport async function resolvePath(path: PathShape, params?: unknown): Promise<string> {\n if (!path.params) return path.template;\n\n const result = await path.params[\"~standard\"].validate(params);\n if (result.issues) {\n throw new CallInputValidationError(\"params\", result.issues);\n }\n\n return path.template.replace(\n /:([A-Za-z_][A-Za-z0-9_]*)|\\{([A-Za-z_][A-Za-z0-9_]*)\\}/gu,\n (_, colon: string | undefined, brace: string) =>\n encodeURIComponent(String(result.value[colon ?? brace])),\n );\n}\n","import { resolvePath } from \"./resolve-path\";\nimport type { StandardSchemaV1 } from \"@standard-schema/spec\";\nimport type { URLSearchParamsObject } from \"../codec/search-params\";\nimport type { EndpointContract } from \"../contract/endpoint\";\nimport type { PathParamValue, ResolvedPath } from \"../contract/path\";\nimport type { RequestEncoderKey, RequestHeaders, RequestShape } from \"../contract/request\";\nimport type { Prettify } from \"../internal\";\nimport { CallInputValidationError, type CallInput } from \"./call-input\";\n\nexport async function prepareRequest<const Contract extends EndpointContract>(\n endpoint: Contract,\n callInput?: CallInput<Contract>,\n): Promise<PreparedRequestFor<Contract>> {\n const shape = endpoint.request;\n const input = (callInput ?? {}) as Partial<\n Record<\"params\" | \"query\" | \"headers\" | \"body\", unknown>\n >;\n\n const resolvedPath = await resolvePath(endpoint.path, input.params);\n\n let query: URLSearchParamsObject | undefined;\n if (shape.query !== undefined) {\n const result = await shape.query[\"~standard\"].validate(input.query);\n\n if (result.issues) {\n throw new CallInputValidationError(\"query\", result.issues);\n }\n\n query = result.value as URLSearchParamsObject;\n }\n\n let headers: RequestHeaders | undefined;\n if (shape.headers !== undefined) {\n const result = await shape.headers[\"~standard\"].validate(input.headers);\n\n if (result.issues) {\n throw new CallInputValidationError(\"headers\", result.issues);\n }\n\n headers = result.value as RequestHeaders;\n }\n\n let preparedBody: PreparedRequestBody = {};\n if (shape.body !== undefined) {\n const result = await shape.body[\"~standard\"].validate(input.body);\n\n if (result.issues) {\n throw new CallInputValidationError(\"body\", result.issues);\n }\n\n preparedBody = {\n encodeAs: shape.encodeAs,\n body: result.value,\n };\n }\n\n const preparedRequest: PreparedRequest = {\n ...(shape.query !== undefined ? { query } : {}),\n ...(shape.headers !== undefined ? { headers } : {}),\n ...preparedBody,\n method: endpoint.method,\n resolvedPath,\n };\n\n return preparedRequest as PreparedRequestFor<Contract>;\n}\n\nexport type PreparedRequestFor<Contract extends EndpointContract> = Contract extends unknown\n ? ExactPreparedRequest<Contract, Contract[\"request\"]>\n : never;\n\nexport type PreparedRequest = {\n readonly method: EndpointContract[\"method\"];\n readonly resolvedPath: string;\n readonly query?: URLSearchParamsObject;\n readonly headers?: RequestHeaders;\n} & PreparedRequestBody;\n\ntype PreparedRequestBody =\n | {\n readonly encodeAs: RequestEncoderKey;\n readonly body: unknown;\n }\n | {\n readonly encodeAs?: never;\n readonly body?: never;\n };\n\ntype ExactPathParams<Path extends EndpointContract[\"path\"]> = Path extends {\n params: StandardSchemaV1;\n}\n ? Extract<StandardSchemaV1.InferOutput<Path[\"params\"]>, Record<string, PathParamValue>>\n : never;\n\ntype ExactPreparedQuery<Request extends RequestShape> = Request extends {\n query: StandardSchemaV1;\n}\n ? { query: StandardSchemaV1.InferOutput<Request[\"query\"]> }\n : {};\n\ntype ExactPreparedHeaders<Request extends RequestShape> = Request extends {\n headers: StandardSchemaV1;\n}\n ? { headers: StandardSchemaV1.InferOutput<Request[\"headers\"]> }\n : {};\n\ntype ExactPreparedBody<Request extends RequestShape> = Request extends {\n body: StandardSchemaV1;\n}\n ? {\n encodeAs: Request[\"encodeAs\"];\n body: StandardSchemaV1.InferOutput<Request[\"body\"]>;\n }\n : {};\n\ntype ExactPreparedRequest<\n Contract extends EndpointContract,\n Request extends RequestShape,\n> = Prettify<\n {\n method: Contract[\"method\"];\n resolvedPath: ResolvedPath<Contract[\"path\"][\"template\"], ExactPathParams<Contract[\"path\"]>>;\n } & ExactPreparedQuery<Request> &\n ExactPreparedHeaders<Request> &\n ExactPreparedBody<Request>\n>;\n","import type { Codecs } from \"../codec/codecs\";\nimport type { ResponseShape } from \"../contract/response\";\n\nfunction createCaseInsensitiveHeaders(headers: Headers): Record<string, string> {\n return new Proxy<Record<string, string>>({} as Record<string, string>, {\n get(_, property) {\n if (typeof property !== \"string\") {\n return undefined;\n }\n\n return headers.get(property) ?? undefined;\n },\n has(_, property) {\n return typeof property === \"string\" && headers.has(property);\n },\n ownKeys() {\n return [...headers.keys()];\n },\n getOwnPropertyDescriptor(_, property) {\n if (typeof property !== \"string\") {\n return undefined;\n }\n\n const value = headers.get(property);\n if (value === null) {\n return undefined;\n }\n\n return {\n configurable: true,\n enumerable: true,\n value,\n };\n },\n });\n}\n\nexport function discardResponseBody(response: Response) {\n if (response.body && !response.body.locked) {\n void response.body.cancel().catch(() => {});\n }\n}\n\nexport async function validateResponse({\n shape,\n response,\n decoders,\n}: {\n shape: ResponseShape;\n response: Response;\n decoders: NonNullable<Codecs[\"decoders\"]>;\n}) {\n if (shape.status !== response.status) return undefined;\n\n let validatedHeaders: unknown = undefined;\n\n if (shape.headers) {\n const headerResult = await shape.headers[\"~standard\"].validate(\n createCaseInsensitiveHeaders(response.headers),\n );\n\n if (headerResult.issues) {\n return undefined;\n }\n\n validatedHeaders = headerResult.value;\n }\n\n let validatedBody: unknown = undefined;\n\n if (shape.body) {\n const decode = decoders[shape.decodeAs];\n if (!decode) return undefined;\n\n let decoded: unknown;\n let candidate: Response | undefined;\n try {\n candidate = response.clone();\n decoded = await decode(candidate);\n } catch {\n return undefined;\n } finally {\n if (candidate) discardResponseBody(candidate);\n }\n\n const bodyResult = await shape.body[\"~standard\"].validate(decoded);\n\n if (bodyResult.issues) {\n return undefined;\n }\n\n validatedBody = bodyResult.value;\n }\n\n return {\n status: shape.status,\n ...(validatedHeaders !== undefined ? { headers: validatedHeaders } : {}),\n ...(validatedBody !== undefined ? { body: validatedBody } : {}),\n };\n}\n","import type { EndpointContract } from \"../contract/endpoint\";\nimport type { RequiredCodecs } from \"../codec/codecs\";\nimport type { CallInput } from \"./call-input\";\nimport { prepareRequest, type PreparedRequest } from \"./prepare-request\";\nimport type { StandardSchemaV1 } from \"@standard-schema/spec\";\nimport type { DefinedField, Prettify } from \"../internal\";\nimport type { TransportConfig } from \"./transport\";\nimport { discardResponseBody, validateResponse } from \"./validate-response\";\n\nexport type FetchOptions = Omit<RequestInit, \"method\" | \"headers\" | \"body\" | \"duplex\">;\n\ntype KeysOfUnion<T> = T extends unknown ? keyof T : never;\n\nexport type Fetcher<Endpoint extends EndpointContract> =\n KeysOfUnion<CallInput<Endpoint>> extends never\n ? (options?: FetchOptions) => Promise<RuntimeResult<Endpoint>>\n : (input: CallInput<Endpoint>, options?: FetchOptions) => Promise<RuntimeResult<Endpoint>>;\n\nexport function createFetcher<const Endpoint extends EndpointContract>(\n endpoint: Endpoint,\n {\n baseUrl,\n fetch,\n codecs,\n }: Required<TransportConfig> & { codecs: NoInfer<RequiredCodecs<Endpoint>> },\n): Fetcher<Endpoint> {\n const { encoders = {}, decoders = {} } = codecs;\n const responseShapes = \"status\" in endpoint.response ? [endpoint.response] : endpoint.response;\n const shape = endpoint.request;\n const hasCallInput =\n endpoint.path.params !== undefined ||\n shape.query !== undefined ||\n shape.headers !== undefined ||\n shape.body !== undefined;\n\n async function fetcher(...rawArgs: unknown[]): Promise<RuntimeResult<Endpoint>> {\n const callInput = hasCallInput ? (rawArgs[0] as CallInput<Endpoint> | undefined) : undefined;\n const options = (hasCallInput ? rawArgs[1] : rawArgs[0]) as FetchOptions | undefined;\n\n const preparedRequest: PreparedRequest = await prepareRequest(endpoint, callInput);\n\n const url = new URL(preparedRequest.resolvedPath, baseUrl);\n if (preparedRequest.query && encoders.query) {\n url.search = encoders.query(preparedRequest.query).toString();\n }\n\n const headers = normalizeHeaders(preparedRequest);\n\n const encoder = preparedRequest.encodeAs && encoders[preparedRequest.encodeAs];\n const body = await encoder?.(preparedRequest.body as never);\n\n const init: RequestInit & { duplex?: \"half\" } = {\n ...options,\n method: preparedRequest.method,\n headers,\n body,\n };\n if (body instanceof ReadableStream) init.duplex = \"half\";\n\n const response = await fetch(new Request(url, init));\n\n try {\n for (const shape of responseShapes) {\n const result = await validateResponse({ shape, response, decoders });\n if (result !== undefined) return result as RuntimeResult<Endpoint>;\n }\n\n throw new UnknownResponseError(response.status);\n } finally {\n discardResponseBody(response);\n }\n }\n\n return fetcher as Fetcher<Endpoint>;\n}\n\nfunction normalizeHeaders(preparedRequest: PreparedRequest): Headers {\n const headers = new Headers();\n for (const [name, value] of Object.entries(preparedRequest.headers ?? {})) {\n if (value === undefined) continue;\n if (preparedRequest.encodeAs === \"form-data\" && name.toLowerCase() === \"content-type\") {\n console.warn(\"Ignoring supplied Content-Type because Fetch generates the form-data boundary.\");\n continue;\n }\n headers.set(name, String(value));\n }\n if (preparedRequest.encodeAs === \"json\" && !headers.has(\"content-type\")) {\n headers.set(\"content-type\", \"application/json\");\n }\n return headers;\n}\n\nexport type RuntimeResult<Endpoint extends EndpointContract = EndpointContract> = ResponseResult<\n Endpoint[\"response\"]\n>;\n\n/** The observed HTTP response matched none of the declared Response Shapes. */\nexport class UnknownResponseError extends Error {\n constructor(readonly status: number) {\n super(`No declared response shape matched the response with status ${status}.`);\n this.name = \"UnknownResponseError\";\n }\n}\n\ntype ResponseField<Shape, Name extends \"headers\" | \"body\"> =\n Shape extends Record<Name, StandardSchemaV1>\n ? DefinedField<Name, StandardSchemaV1.InferOutput<Shape[Name]>>\n : {};\n\ntype ResponseResult<\n Declaration extends EndpointContract[\"response\"],\n Shape = Declaration extends readonly (infer Item)[] ? Item : Declaration,\n> = Shape extends { status: number }\n ? Prettify<\n { status: Shape[\"status\"] } & ResponseField<Shape, \"headers\"> & ResponseField<Shape, \"body\">\n >\n : never;\n","import type { JsonValue } from \"../internal\";\nimport type { EndpointContract } from \"../contract/endpoint\";\nimport { toFormData, type FormDataObject } from \"./form-data\";\nimport {\n toURLSearchParams,\n type URLSearchParamsNativeInput,\n type URLSearchParamsObject,\n} from \"./search-params\";\n\nexport type RequestEncoderInputMap = {\n json: JsonValue;\n text: string;\n \"form-data\": FormData | FormDataObject;\n \"form-urlencoded\": URLSearchParams | URLSearchParamsNativeInput | URLSearchParamsObject;\n binary: Blob | ArrayBuffer | Uint8Array;\n stream: ReadableStream<Uint8Array>;\n};\n\ntype RequestEncoderOutputMap = {\n json: string;\n text: string;\n \"form-data\": FormData;\n \"form-urlencoded\": URLSearchParams;\n binary: Blob | ArrayBuffer;\n stream: ReadableStream<Uint8Array>;\n};\n\nexport type ResponseDecoderOutputMap = {\n json: unknown;\n text: string;\n blob: Blob;\n arrayBuffer: ArrayBuffer;\n bytes: Uint8Array;\n formData: FormData;\n};\n\ntype MaybePromise<T> = T | Promise<T>;\n\ntype Encoders = { query: (query: URLSearchParamsObject) => URLSearchParams } & {\n [K in keyof RequestEncoderInputMap]: (\n value: RequestEncoderInputMap[K],\n ) => MaybePromise<RequestEncoderOutputMap[K]>;\n};\ntype Decoders = {\n [K in keyof ResponseDecoderOutputMap]: (\n response: Response,\n ) => MaybePromise<ResponseDecoderOutputMap[K]>;\n};\n\nexport type Codecs = {\n encoders?: Partial<Encoders>;\n decoders?: Partial<Decoders>;\n};\n\nexport const codecs = {\n encoders: {\n query: toURLSearchParams,\n json: (value) => JSON.stringify(value),\n text: (value) => value,\n \"form-data\": toFormData,\n \"form-urlencoded\": toURLSearchParams,\n binary: (value) => (value instanceof Uint8Array ? Uint8Array.from(value).buffer : value),\n stream: (value) => value,\n },\n decoders: {\n json: (response) => response.json() as Promise<unknown>,\n text: (response) => response.text(),\n blob: (response) => response.blob(),\n arrayBuffer: (response) => response.arrayBuffer(),\n bytes: async (response) => new Uint8Array(await response.arrayBuffer()),\n formData: (response) => response.formData(),\n },\n} satisfies { encoders: Encoders; decoders: Decoders };\n\ntype ElementOrSelf<T> = T extends readonly (infer Item)[] ? Item : T;\ntype RequiredProperty<T, P extends PropertyKey> =\n T extends Record<P, infer Key extends PropertyKey> ? Key : never;\n\ntype EndpointEncoders<E extends EndpointContract> = Pick<\n Encoders,\n | RequiredProperty<E[\"request\"], \"encodeAs\">\n | (E[\"request\"] extends EndpointContract[\"request\"] & { query?: undefined } ? never : \"query\")\n>;\n\ntype ResponseDecoders<Shapes extends EndpointContract[\"response\"]> = Pick<\n Decoders,\n RequiredProperty<ElementOrSelf<Shapes>, \"decodeAs\">\n>;\n\n// A registration covers a key only if every possible registration provides it.\ntype CodecOverrides<Needed, Available> = Partial<Needed> & {\n [K in keyof Needed as [Available] extends [Pick<Needed, K>] ? never : K]: Needed[K];\n};\n\n// Omit empty groups and require a group only when it has required members.\ntype CodecField<Name extends string, Value> = keyof Value extends never\n ? {}\n : {} extends Value\n ? { [K in Name]?: Value }\n : { [K in Name]: Value };\n\n/** Endpoint-specific overrides, with registrations missing from defaults required. */\nexport type RequiredCodecs<\n Endpoint extends EndpointContract,\n Defaults extends Codecs = {},\n> = CodecField<\"encoders\", CodecOverrides<EndpointEncoders<Endpoint>, Defaults[\"encoders\"]>> &\n CodecField<\n \"decoders\",\n CodecOverrides<ResponseDecoders<Endpoint[\"response\"]>, Defaults[\"decoders\"]>\n >;\n\ntype FetcherOptions<Overrides> = keyof Overrides extends never\n ? []\n : {} extends Overrides\n ? [options?: { codecs?: Overrides }]\n : [options: { codecs: Overrides }];\n\nexport type CodecOptions<\n Endpoint extends EndpointContract,\n Defaults extends Codecs,\n> = FetcherOptions<RequiredCodecs<Endpoint, Defaults>>;\n","import type { EndpointContract } from \"../contract/endpoint\";\nimport { shallowMergeDefined, type Invalid } from \"../internal\";\nimport type { CodecOptions, Codecs, RequiredCodecs } from \"../codec/codecs\";\nimport { createFetcher, type Fetcher } from \"./fetcher\";\n\nexport type TransportConfig = {\n baseUrl: string;\n fetch?: (request: Request, init?: RequestInit) => Promise<Response>;\n codecs?: Codecs;\n};\n\ntype FetchCompatibleShape =\n | { method: Exclude<EndpointContract[\"method\"], \"GET\" | \"HEAD\"> }\n | { request: Extract<EndpointContract[\"request\"], { body?: never }> };\n\ntype CompatibleEndpoint<E extends EndpointContract> = E &\n ([E] extends [FetchCompatibleShape]\n ? {}\n : { request: Invalid<\"Error: Fetch cannot send GET or HEAD requests with a body.\"> });\n\ninterface Transport<C extends Codecs = {}> {\n createFetcher<const Endpoint extends EndpointContract>(\n endpoint: CompatibleEndpoint<Endpoint>,\n ...options: CodecOptions<NoInfer<Endpoint>, C>\n ): Fetcher<Endpoint>;\n}\n\nexport function createTransport<const Config extends TransportConfig>(\n config: Config,\n): Transport<Config extends { codecs: infer C extends Codecs } ? C : {}>;\nexport function createTransport(config: TransportConfig): Transport {\n const dispatch = config.fetch ?? globalThis.fetch;\n return {\n createFetcher<const Endpoint extends EndpointContract>(\n endpoint: CompatibleEndpoint<Endpoint>,\n options?: Pick<TransportConfig, \"codecs\">,\n ) {\n return createFetcher<Endpoint>(endpoint, {\n baseUrl: config.baseUrl,\n fetch: dispatch,\n codecs: {\n encoders: shallowMergeDefined(config.codecs?.encoders, options?.codecs?.encoders),\n decoders: shallowMergeDefined(config.codecs?.decoders, options?.codecs?.decoders),\n } as RequiredCodecs<Endpoint>,\n });\n },\n };\n}\n"],"mappings":";AAqBA,SAAgBA,EAoBd,GASoB;CACpB,OAAOC;AACT;;AC/BA,SAAgBC,EAAK,GAAkB,GAA0C;CAC/E,OAAO;EAAE;EAAU;CAAO;AAC5B;;ACCA,SAAgBC,EACd,GAIiB;CACjB,OAAOC;AACT;;ACFA,SAAgBC,EACd,GAIiB;CACjB,OAAOD;AACT;;ACPA,SAAgBE,EAAW,GAA4C;CACrE,IAAIC,a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ACrB,EAAQ,IAAI,cAAc,KACpEA,EAAQ,IAAI,gBAAgB,kBAAkB,GAEzCA;AACT;AAOA,IAAa6B,IAAb,cAA0C,MAAM;CACzB;CAArB,YAAY,GAAyB;EAEnC,AADA,MAAM,+DAA+DE,EAAO,EAAE,GAD3D,KAAA,SAAAA,GAEnB,KAAK,OAAO;CACd;AACF,GChDahB,IAAS;CACpB,UAAU;EACR,OAAOxC;EACP,OAAO,MAAU,KAAK,UAAUf,CAAK;EACrC,OAAO,MAAUA;EACjB,aAAaD;EACb,mBAAmBgB;EACnB,SAAS,MAAWf,aAAiB,aAAa,WAAW,KAAKA,CAAK,CAAC,CAAC,SAASA;EAClF,SAAS,MAAUA;CACrB;CACA,UAAU;EACR,OAAO,MAAaF,EAAS,KAAK;EAClC,OAAO,MAAaA,EAAS,KAAK;EAClC,OAAO,MAAaA,EAAS,KAAK;EAClC,cAAc,MAAaA,EAAS,YAAY;EAChD,OAAO,OAAO,MAAa,IAAI,WAAW,MAAMA,EAAS,YAAY,CAAC;EACtE,WAAW,MAAaA,EAAS,SAAS;CAC5C;AACF;;AC1CA,SAAgB0E,EAAgB,GAAoC;CAClE,IAAMC,IAAWC,EAAO,SAAS,WAAW;CAC5C,OAAO,EACL,cACE,GACA,GACA;EACA,OAAOpB,EAAwB7D,GAAU;GACvC,SAASiF,EAAO;GAChB,OAAOD;GACP,QAAQ;IACN,UAAUjD,EAAoBkD,EAAO,QAAQ,UAAUd,GAAS,QAAQ,QAAQ;IAChF,UAAUpC,EAAoBkD,EAAO,QAAQ,UAAUd,GAAS,QAAQ,QAAQ;GAClF;EACF,CAAC;CACH,EACF;AACF"}
package/package.json CHANGED
@@ -1,6 +1,43 @@
1
1
  {
2
2
  "name": "@qzcurious/http-connect",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.0.0",
4
+ "license": "MIT",
5
+ "publishConfig": {
6
+ "access": "public"
7
+ },
8
+ "files": [
9
+ "dist"
10
+ ],
11
+ "type": "module",
12
+ "types": "./dist/public.d.ts",
13
+ "exports": {
14
+ ".": {
15
+ "types": "./dist/public.d.ts",
16
+ "import": "./dist/public.js"
17
+ }
18
+ },
19
+ "scripts": {
20
+ "build": "vite build",
21
+ "prepack": "pnpm run build",
22
+ "format": "oxfmt",
23
+ "lint": "oxlint playground",
24
+ "typecheck": "tsc --noEmit",
25
+ "test": "vitest run",
26
+ "test:watch": "vitest"
27
+ },
28
+ "dependencies": {
29
+ "@standard-schema/spec": "^1.1.0"
30
+ },
31
+ "devDependencies": {
32
+ "@types/node": "^26.6.10",
33
+ "oxfmt": "^0.80.0",
34
+ "oxlint": "^1.95.0",
35
+ "rolldown-plugin-dts": "^0.30.2",
36
+ "typescript": "^7.0.2",
37
+ "vite": "^8.3.8",
38
+ "vitest": "^5.1.1",
39
+ "vscode-jsonrpc": "^10.0.1",
40
+ "zod": "^4.6.7"
41
+ },
42
+ "packageManager": "pnpm@12.23.0"
43
+ }