@iquji-web/web-network 0.0.0-stage → 0.1.1

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 Iquji contributors
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,27 @@
1
- # Temporary Holding Version
1
+ # Web network
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
+ `@iquji-web/web-network` 提供通用 HTTP 传输,不包含认证、业务错误、重试或响应数据协议。它由 Community Web 子仓维护,包名与正式出口保持稳定。
4
+
5
+ 安装使用本目录锁文件,运行 `bun install --frozen-lockfile` 和 `bun run check`。正式入口只导出 `dist` 中的 JavaScript、类型声明,不要求消费者编译本包源码。
6
+
7
+ `@iquji-web/web-network/test-support` 单独提供可注入 FetchRecorder,不从生产主入口导出。
8
+
9
+ ```ts
10
+ import { createHttpTransport } from "@iquji-web/web-network";
11
+
12
+ const request = createHttpTransport({ timeoutMs: 15_000 });
13
+ const controller = new AbortController();
14
+ const response = await request("/api/status", {
15
+ method: "GET",
16
+ credentials: "include",
17
+ signal: controller.signal,
18
+ });
19
+ ```
20
+
21
+ `createHttpTransport({ fetchImplementation?, timeoutMs? })` 返回接受 `RequestInfo | URL` 和 `RequestInit & { timeoutMs?: number }` 的请求函数。它保留请求地址、正文、头部与 fetch 选项,直接返回原始 `Response`,包括非成功状态、响应头、重定向地址和未读取的响应流;状态判断与正文解析由消费者负责。
22
+
23
+ 默认不设置超时。实例与逐请求 `timeoutMs` 接受 0 到 2147483647 的有限毫秒值;逐请求设置覆盖实例,0 关闭超时。超时覆盖等待响应头的阶段,随后清理定时器,不读取消费者正文。超时中止底层信号并抛出 `HttpTimeoutError`,其 `name` 为 `TimeoutError`、`timeoutMs` 为实际设置。调用方取消保留原始原因;请求返回后,调用方取消仍可传递给底层响应流。正文读取的时限由消费者管理。
24
+
25
+ `fetchImplementation` 可注入浏览器 fetch、测试替身或宿主原生传输,并应遵守 fetch 的 `AbortSignal` 语义。代理连接由宿主原生或服务端适配器执行,本包不提供 `proxy` 配置。浏览器 fetch 使用浏览器自身的网络环境,不能通过请求选项指定自定义代理。
26
+
27
+ `createJsonTransport` 在共享原始传输上保留现有合同:规范化 `baseUrl` 与相对路径、合并默认和请求头、序列化 JSON 正文、传递凭据及缓存设置。非成功状态抛出只含状态码的 `JsonTransportError`,成功状态解析 JSON;不读取失败响应正文。该适配器也接受实例与逐请求 `timeoutMs`。
@@ -0,0 +1,13 @@
1
+ export type FetchImplementation = (input: RequestInfo | URL, init?: RequestInit) => Promise<Response>;
2
+ export type HttpTransportOptions = {
3
+ fetchImplementation?: FetchImplementation;
4
+ timeoutMs?: number;
5
+ };
6
+ export type HttpRequestOptions = RequestInit & {
7
+ timeoutMs?: number;
8
+ };
9
+ export declare class HttpTimeoutError extends Error {
10
+ readonly timeoutMs: number;
11
+ constructor(timeoutMs: number);
12
+ }
13
+ export declare function createHttpTransport({ fetchImplementation, timeoutMs, }?: HttpTransportOptions): (input: RequestInfo | URL, options?: HttpRequestOptions) => Promise<Response>;
@@ -0,0 +1,20 @@
1
+ import { type HttpTransportOptions } from "./http-transport.js";
2
+ export { createHttpTransport, type FetchImplementation, type HttpRequestOptions, HttpTimeoutError, type HttpTransportOptions, } from "./http-transport.js";
3
+ export type JsonTransportOptions = HttpTransportOptions & {
4
+ baseUrl: string;
5
+ resolveHeaders?: () => HeadersInit | Promise<HeadersInit>;
6
+ credentials?: RequestCredentials;
7
+ cache?: RequestCache;
8
+ };
9
+ export type JsonRequest = {
10
+ method?: "GET" | "POST" | "PUT" | "PATCH" | "DELETE";
11
+ body?: unknown;
12
+ headers?: HeadersInit;
13
+ signal?: AbortSignal;
14
+ timeoutMs?: number;
15
+ };
16
+ export declare class JsonTransportError extends Error {
17
+ readonly status: number;
18
+ constructor(status: number);
19
+ }
20
+ export declare function createJsonTransport({ baseUrl, fetchImplementation, timeoutMs, resolveHeaders, credentials, cache, }: JsonTransportOptions): <ResponseBody>(path: string, options?: JsonRequest) => Promise<ResponseBody>;
package/dist/index.js ADDED
@@ -0,0 +1,105 @@
1
+ // src/http-transport.ts
2
+ class HttpTimeoutError extends Error {
3
+ timeoutMs;
4
+ constructor(timeoutMs) {
5
+ super(`Request timed out after ${timeoutMs} ms`);
6
+ this.name = "TimeoutError";
7
+ this.timeoutMs = timeoutMs;
8
+ }
9
+ }
10
+ function validateTimeout(timeoutMs) {
11
+ if (timeoutMs !== undefined && (!Number.isFinite(timeoutMs) || timeoutMs < 0 || timeoutMs > 2147483647)) {
12
+ throw new RangeError("HTTP timeout must be between 0 and 2147483647 ms");
13
+ }
14
+ }
15
+ function createHttpTransport({
16
+ fetchImplementation = globalThis.fetch,
17
+ timeoutMs
18
+ } = {}) {
19
+ validateTimeout(timeoutMs);
20
+ return async function request(input, options = {}) {
21
+ const { timeoutMs: requestTimeout = timeoutMs, ...init } = options;
22
+ validateTimeout(requestTimeout);
23
+ const sourceSignal = init.signal === undefined && input instanceof Request ? input.signal : init.signal;
24
+ sourceSignal?.throwIfAborted();
25
+ const timeoutController = requestTimeout ? new AbortController : undefined;
26
+ const signal = timeoutController ? sourceSignal ? AbortSignal.any([sourceSignal, timeoutController.signal]) : timeoutController.signal : sourceSignal;
27
+ if (timeoutController && signal)
28
+ init.signal = signal;
29
+ const timer = timeoutController ? setTimeout(() => timeoutController.abort(new HttpTimeoutError(requestTimeout ?? 0)), requestTimeout) : undefined;
30
+ let abortListener;
31
+ try {
32
+ if (!signal)
33
+ return await fetchImplementation(input, init);
34
+ const aborted = new Promise((_resolve, reject) => {
35
+ abortListener = () => reject(signal.reason);
36
+ signal.addEventListener("abort", abortListener, { once: true });
37
+ });
38
+ return await Promise.race([fetchImplementation(input, init), aborted]);
39
+ } finally {
40
+ clearTimeout(timer);
41
+ if (signal && abortListener)
42
+ signal.removeEventListener("abort", abortListener);
43
+ }
44
+ };
45
+ }
46
+
47
+ // src/index.ts
48
+ class JsonTransportError extends Error {
49
+ status;
50
+ constructor(status) {
51
+ super(`Request failed with status ${status}`);
52
+ this.name = "JsonTransportError";
53
+ this.status = status;
54
+ }
55
+ }
56
+ function createJsonTransport({
57
+ baseUrl,
58
+ fetchImplementation,
59
+ timeoutMs,
60
+ resolveHeaders,
61
+ credentials,
62
+ cache
63
+ }) {
64
+ const normalizedBaseUrl = baseUrl.replace(/\/+$/u, "");
65
+ if (!normalizedBaseUrl)
66
+ throw new Error("A transport base URL is required");
67
+ const transportOptions = {};
68
+ if (fetchImplementation)
69
+ transportOptions.fetchImplementation = fetchImplementation;
70
+ if (timeoutMs !== undefined)
71
+ transportOptions.timeoutMs = timeoutMs;
72
+ const transport = createHttpTransport(transportOptions);
73
+ return async function request(path, options = {}) {
74
+ const headers = new Headers(await resolveHeaders?.());
75
+ new Headers(options.headers).forEach((value, key) => {
76
+ headers.set(key, value);
77
+ });
78
+ const init = {
79
+ method: options.method ?? "GET",
80
+ headers
81
+ };
82
+ if (credentials)
83
+ init.credentials = credentials;
84
+ if (cache)
85
+ init.cache = cache;
86
+ if (options.signal)
87
+ init.signal = options.signal;
88
+ if (options.timeoutMs !== undefined)
89
+ init.timeoutMs = options.timeoutMs;
90
+ if (options.body !== undefined) {
91
+ headers.set("content-type", "application/json");
92
+ init.body = JSON.stringify(options.body);
93
+ }
94
+ const response = await transport(`${normalizedBaseUrl}/${path.replace(/^\/+/, "")}`, init);
95
+ if (!response.ok)
96
+ throw new JsonTransportError(response.status);
97
+ return await response.json();
98
+ };
99
+ }
100
+ export {
101
+ createJsonTransport,
102
+ createHttpTransport,
103
+ JsonTransportError,
104
+ HttpTimeoutError
105
+ };
@@ -0,0 +1,8 @@
1
+ import type { FetchImplementation } from "./index.js";
2
+ export type FetchRecord = {
3
+ request: Request;
4
+ };
5
+ export declare function createFetchRecorder(responder: (request: Request) => Response | Promise<Response>): {
6
+ fetchImplementation: FetchImplementation;
7
+ records: FetchRecord[];
8
+ };
@@ -0,0 +1,13 @@
1
+ // src/test-support.ts
2
+ function createFetchRecorder(responder) {
3
+ const records = [];
4
+ const fetchImplementation = async (input, init) => {
5
+ const request = new Request(input, init);
6
+ records.push({ request });
7
+ return responder(request);
8
+ };
9
+ return { fetchImplementation, records };
10
+ }
11
+ export {
12
+ createFetchRecorder
13
+ };
package/package.json CHANGED
@@ -1,6 +1,37 @@
1
1
  {
2
2
  "name": "@iquji-web/web-network",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.1",
4
+ "license": "MIT",
5
+ "type": "module",
6
+ "files": [
7
+ "dist",
8
+ "README.md",
9
+ "LICENSE"
10
+ ],
11
+ "exports": {
12
+ ".": {
13
+ "types": "./dist/index.d.ts",
14
+ "import": "./dist/index.js"
15
+ },
16
+ "./test-support": {
17
+ "types": "./dist/test-support.d.ts",
18
+ "import": "./dist/test-support.js"
19
+ }
20
+ },
21
+ "sideEffects": false,
22
+ "peerDependencies": {},
23
+ "description": "可注入 fetch 的 HTTP 传输、取消和 JSON 适配器。",
24
+ "publishConfig": {
25
+ "access": "public",
26
+ "registry": "https://registry.npmjs.org/"
27
+ },
28
+ "repository": {
29
+ "type": "git",
30
+ "url": "git+https://github.com/haydardsx/iquji-community-web.git",
31
+ "directory": "network"
32
+ },
33
+ "homepage": "https://community-web.iquji.com",
34
+ "bugs": {
35
+ "url": "https://github.com/haydardsx/iquji-community-web/issues"
36
+ }
37
+ }