@wevu/web-apis 1.3.6 → 1.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (41) hide show
  1. package/README.md +36 -8
  2. package/dist/abort.d.mts +2 -4
  3. package/dist/abort.mjs +2 -3
  4. package/dist/eventsource-DUCc1iHv.d.mts +82 -0
  5. package/dist/eventsource-ojngrwBI.mjs +340 -0
  6. package/dist/eventsource.d.mts +2 -0
  7. package/dist/eventsource.mjs +2 -0
  8. package/dist/fetch-CQoQx3mz.mjs +301 -0
  9. package/dist/fetch-CSESA-oq.d.mts +33 -0
  10. package/dist/fetch.d.mts +2 -35
  11. package/dist/fetch.mjs +1 -188
  12. package/dist/http-DCCqK1QL.mjs +505 -0
  13. package/dist/{http-CE8-CIHE.d.mts → http-Dd6YCSHK.d.mts} +6 -14
  14. package/dist/http.d.mts +1 -1
  15. package/dist/http.mjs +1 -1
  16. package/dist/index.d.mts +19 -54
  17. package/dist/index.mjs +35 -104
  18. package/dist/networkDefaults.d.mts +1 -3
  19. package/dist/networkDefaults.mjs +1 -2
  20. package/dist/{shared-BI8xrWqd.mjs → shared-CARmZrDA.mjs} +5 -9
  21. package/dist/{shared-Dc42USJC.d.mts → shared-DfU0oEwy.d.mts} +0 -2
  22. package/dist/shared.d.mts +1 -1
  23. package/dist/shared.mjs +1 -1
  24. package/dist/streams-6m8eQfZM.mjs +84 -0
  25. package/dist/streams.d.mts +31 -0
  26. package/dist/streams.mjs +1 -0
  27. package/dist/textCodec-muWByCAW.mjs +132 -0
  28. package/dist/{url-D0ANYIyk.d.mts → url-CEgyUgm2.d.mts} +0 -2
  29. package/dist/{url-CBepYY5Q.mjs → url-DjMmeEth.mjs} +2 -4
  30. package/dist/url.d.mts +1 -1
  31. package/dist/url.mjs +1 -1
  32. package/dist/{web-DRnPgdkX.mjs → web-DDzJNeV3.mjs} +6 -8
  33. package/dist/{web-DNBBg6y9.d.mts → web-DjLufM4u.d.mts} +1 -7
  34. package/dist/web.d.mts +1 -1
  35. package/dist/web.mjs +1 -1
  36. package/dist/websocket.d.mts +2 -4
  37. package/dist/websocket.mjs +4 -5
  38. package/dist/xhr.d.mts +1 -3
  39. package/dist/xhr.mjs +4 -5
  40. package/package.json +17 -5
  41. package/dist/http-DFOOhYXD.mjs +0 -303
@@ -0,0 +1,505 @@
1
+ import { d as normalizeHeaderName, h as isUrlSearchParamsInstance, l as isArrayBufferLike, m as isUrlInstance, n as cloneArrayBuffer, o as encodeText, r as cloneArrayBufferView, u as isBlobLike } from "./shared-CARmZrDA.mjs";
2
+ import { l as nativeStreams, n as ReadableStreamPolyfill, t as ReadableStream } from "./streams-6m8eQfZM.mjs";
3
+ import { t as TextDecoderPolyfill } from "./textCodec-muWByCAW.mjs";
4
+ import { r as BlobPolyfill, t as FormDataPolyfill } from "./web-DDzJNeV3.mjs";
5
+ // src/http/headers.ts
6
+ const SET_COOKIE_HEADER_NAME = "set-cookie";
7
+ function isIterableHeaders(input) {
8
+ return Boolean(input) && typeof input[Symbol.iterator] === "function";
9
+ }
10
+ function isHeaderObject(input) {
11
+ return typeof input === "object" && input !== null;
12
+ }
13
+ var HeadersPolyfill = class {
14
+ store = /* @__PURE__ */ new Map();
15
+ constructor(init) {
16
+ if (!init) return;
17
+ if (isIterableHeaders(init)) {
18
+ for (const [key, value] of init) this.append(key, value);
19
+ return;
20
+ }
21
+ if (typeof init.forEach === "function") {
22
+ init.forEach((value, key) => {
23
+ this.set(key, value);
24
+ });
25
+ return;
26
+ }
27
+ if (isHeaderObject(init)) for (const [key, value] of Object.entries(init)) this.append(key, Array.isArray(value) ? value.join(", ") : String(value));
28
+ }
29
+ append(key, value) {
30
+ const normalized = normalizeHeaderName(key);
31
+ if (!normalized) return;
32
+ const item = this.store.get(normalized);
33
+ if (item) {
34
+ item.values.push(String(value));
35
+ return;
36
+ }
37
+ this.store.set(normalized, {
38
+ key,
39
+ values: [String(value)]
40
+ });
41
+ }
42
+ set(key, value) {
43
+ const normalized = normalizeHeaderName(key);
44
+ if (!normalized) return;
45
+ this.store.set(normalized, {
46
+ key,
47
+ values: [String(value)]
48
+ });
49
+ }
50
+ get(key) {
51
+ return this.store.get(normalizeHeaderName(key))?.values.join(", ") ?? null;
52
+ }
53
+ getSetCookie() {
54
+ return this.store.get(SET_COOKIE_HEADER_NAME)?.values.slice() ?? [];
55
+ }
56
+ has(key) {
57
+ return this.store.has(normalizeHeaderName(key));
58
+ }
59
+ delete(key) {
60
+ this.store.delete(normalizeHeaderName(key));
61
+ }
62
+ forEach(callback, thisArg) {
63
+ for (const { key, values } of this.store.values()) callback.call(thisArg, values.join(", "), key, this);
64
+ }
65
+ entries() {
66
+ return Array.from(this.store.values(), (item) => [item.key, item.values.join(", ")])[Symbol.iterator]();
67
+ }
68
+ keys() {
69
+ return Array.from(this.store.values(), (item) => item.key)[Symbol.iterator]();
70
+ }
71
+ values() {
72
+ return Array.from(this.store.values(), (item) => item.values.join(", "))[Symbol.iterator]();
73
+ }
74
+ [Symbol.iterator]() {
75
+ return this.entries();
76
+ }
77
+ };
78
+ function headersToObject(headers) {
79
+ const result = {};
80
+ headers.forEach((value, key) => {
81
+ result[key] = value;
82
+ });
83
+ return result;
84
+ }
85
+ // src/multipart.ts
86
+ const CRLF = "\r\n";
87
+ /** 复用调用者指定的边界,使请求头与编码后的字节保持一致。 */
88
+ function createMultipartBoundary(contentType) {
89
+ if (contentType && /^multipart\/form-data\s*(?:;|$)/i.test(contentType)) {
90
+ const match = /(?:^|;)\s*boundary=(?:"([^"]+)"|([^;\s]+))/i.exec(contentType);
91
+ const boundary = match?.[1] ?? match?.[2];
92
+ if (boundary) {
93
+ if (!/^[\w'()+,\-./:=? ]{1,70}$/.test(boundary) || boundary.endsWith(" ")) throw new TypeError("Invalid multipart boundary");
94
+ return boundary;
95
+ }
96
+ }
97
+ return `----weapp-vite-formdata-${Math.random().toString(36).slice(2)}${Date.now().toString(36)}`;
98
+ }
99
+ function escapeMultipartName(value) {
100
+ return String(value).replace(/\\/g, "\\\\").replace(/"/g, "\\\"").replace(/\r/g, "%0D").replace(/\n/g, "%0A");
101
+ }
102
+ function concatArrayBuffers(buffers) {
103
+ const totalLength = buffers.reduce((sum, buffer) => sum + buffer.byteLength, 0);
104
+ const merged = new Uint8Array(totalLength);
105
+ let offset = 0;
106
+ for (const buffer of buffers) {
107
+ merged.set(new Uint8Array(buffer), offset);
108
+ offset += buffer.byteLength;
109
+ }
110
+ return merged.buffer;
111
+ }
112
+ function isBlobFormDataValue(value) {
113
+ return typeof value !== "string" && typeof value?.arrayBuffer === "function";
114
+ }
115
+ function getMultipartFilename(value) {
116
+ const name = value.name;
117
+ return typeof name === "string" && name.length > 0 ? name : "blob";
118
+ }
119
+ async function createMultipartPart(name, value) {
120
+ if (!isBlobFormDataValue(value)) return [
121
+ encodeText(`Content-Disposition: form-data; name="${escapeMultipartName(name)}"${CRLF}${CRLF}`),
122
+ encodeText(String(value)),
123
+ encodeText(CRLF)
124
+ ];
125
+ const filename = getMultipartFilename(value);
126
+ const headers = [
127
+ `Content-Disposition: form-data; name="${escapeMultipartName(name)}"; filename="${escapeMultipartName(filename)}"`,
128
+ `Content-Type: ${value.type || "application/octet-stream"}`,
129
+ "",
130
+ ""
131
+ ].join(CRLF);
132
+ return [
133
+ encodeText(headers),
134
+ await value.arrayBuffer(),
135
+ encodeText(CRLF)
136
+ ];
137
+ }
138
+ async function encodeMultipartFormData(formData, boundary = createMultipartBoundary()) {
139
+ const buffers = [];
140
+ for (const [name, value] of formData) {
141
+ buffers.push(encodeText(`--${boundary}${CRLF}`));
142
+ buffers.push(...await createMultipartPart(name, value));
143
+ }
144
+ buffers.push(encodeText(`--${boundary}--${CRLF}`));
145
+ return {
146
+ body: concatArrayBuffers(buffers),
147
+ contentType: `multipart/form-data; boundary=${boundary}`
148
+ };
149
+ }
150
+ // src/streams/ponyfillState.ts
151
+ function isPonyfillStream(value) {
152
+ return value instanceof ReadableStreamPolyfill;
153
+ }
154
+ /**
155
+ * web-streams-polyfill 固定为 4.3.0;其公共 API 未提供 disturbed 查询,因此将版本相关读取限制在此处。
156
+ * 品牌与字段形状必须同时匹配;升级依赖时由包版本测试和消费状态回归共同阻止静默漂移。
157
+ */
158
+ function isPonyfillStreamDisturbed(stream) {
159
+ if (!isPonyfillStream(stream)) throw new TypeError("Expected a web-streams-polyfill ReadableStream");
160
+ const disturbed = Reflect.get(stream, "_disturbed");
161
+ if (typeof disturbed !== "boolean") throw new TypeError("Unsupported web-streams-polyfill state layout; expected version 4.3.0");
162
+ return disturbed;
163
+ }
164
+ // src/streams/bodyTracking.ts
165
+ const nativeStates = /* @__PURE__ */ new WeakMap();
166
+ /** 只观察已支持流族的内部状态;不修改调用者的流、reader 或其原型。 */
167
+ function observeBodyStream(stream) {
168
+ if (isPonyfillStream(stream)) {
169
+ isPonyfillStreamDisturbed(stream);
170
+ return stream;
171
+ }
172
+ if (nativeStates.has(stream)) return stream;
173
+ if (nativeStreams && stream instanceof nativeStreams.ReadableStream) {
174
+ const { Response, bodyUsed } = nativeStreams;
175
+ try {
176
+ const response = new Response(stream);
177
+ if (response.body === stream) {
178
+ nativeStates.set(stream, () => bodyUsed.call(response));
179
+ return stream;
180
+ }
181
+ } catch {
182
+ nativeStates.set(stream, () => true);
183
+ return stream;
184
+ }
185
+ }
186
+ throw new TypeError("Body stream must use the supported native or ponyfill ReadableStream constructor");
187
+ }
188
+ function isBodyStreamDisturbed(stream) {
189
+ if (isPonyfillStream(stream)) return isPonyfillStreamDisturbed(stream);
190
+ return nativeStates.get(stream)?.() === true;
191
+ }
192
+ // src/streams/readBody.ts
193
+ const typedArrayName = Object.getOwnPropertyDescriptor(Object.getPrototypeOf(Uint8Array.prototype), Symbol.toStringTag)?.get;
194
+ /** 以内部类型标签识别跨 realm 字节视图,并复制到当前 realm 独占的 ArrayBuffer。 */
195
+ function copyBodyChunk(value) {
196
+ const tag = typedArrayName ? typedArrayName.call(value) : Object.prototype.toString.call(value).slice(8, -1);
197
+ if (!ArrayBuffer.isView(value) || tag !== "Uint8Array") throw new TypeError("Body stream chunks must be Uint8Array values");
198
+ const copy = new Uint8Array(value.byteLength);
199
+ copy.set(value);
200
+ return copy;
201
+ }
202
+ async function readBodyStream(stream, signal) {
203
+ const reason = () => signal && signal.reason !== void 0 ? signal.reason : Object.assign(/* @__PURE__ */ new Error("The operation was aborted."), { name: "AbortError" });
204
+ if (signal?.aborted) throw reason();
205
+ const reader = stream.getReader();
206
+ const chunks = [];
207
+ let length = 0;
208
+ let aborted = false;
209
+ const onAbort = () => {
210
+ if (!aborted) {
211
+ aborted = true;
212
+ reader.cancel(reason()).catch(() => {});
213
+ }
214
+ };
215
+ signal?.addEventListener("abort", onAbort, { once: true });
216
+ try {
217
+ if (signal?.aborted) onAbort();
218
+ while (true) {
219
+ if (aborted) throw reason();
220
+ const chunk = await reader.read();
221
+ if (aborted) throw reason();
222
+ if (chunk.done) break;
223
+ const copy = copyBodyChunk(chunk.value);
224
+ chunks.push(copy);
225
+ length += copy.byteLength;
226
+ }
227
+ } finally {
228
+ signal?.removeEventListener("abort", onAbort);
229
+ reader.releaseLock();
230
+ }
231
+ const merged = new Uint8Array(length);
232
+ let offset = 0;
233
+ for (const chunk of chunks) {
234
+ merged.set(chunk, offset);
235
+ offset += chunk.byteLength;
236
+ }
237
+ return merged.buffer;
238
+ }
239
+ // src/streams/cloneBody.ts
240
+ /**
241
+ * Body clone 必须隔离两侧的可变字节;普通对象流的 tee 会共享 Uint8Array 引用。
242
+ * 先转换为字节流,再使用 Streams 原生的字节 tee 保留双分支取消与错误传播。
243
+ */
244
+ function cloneBodyStream(stream) {
245
+ const reader = stream.getReader();
246
+ return new ReadableStream({
247
+ type: "bytes",
248
+ async pull(controller) {
249
+ try {
250
+ while (true) {
251
+ const chunk = await reader.read();
252
+ if (chunk.done) {
253
+ controller.close();
254
+ return;
255
+ }
256
+ const copy = copyBodyChunk(chunk.value);
257
+ if (copy.byteLength > 0) {
258
+ controller.enqueue(copy);
259
+ return;
260
+ }
261
+ }
262
+ } catch (error) {
263
+ controller.error(error);
264
+ reader.cancel(error).catch(() => {});
265
+ }
266
+ },
267
+ cancel: (reason) => reader.cancel(reason)
268
+ }).tee();
269
+ }
270
+ // src/http/body.ts
271
+ const bodies = /* @__PURE__ */ new WeakMap();
272
+ const bufferedStreams = /* @__PURE__ */ new WeakSet();
273
+ function isReadableBodyStream(value) {
274
+ return typeof value === "object" && value !== null && typeof value.getReader === "function" && typeof value.tee === "function" && typeof value.locked === "boolean";
275
+ }
276
+ function isFormData(value) {
277
+ return value instanceof FormDataPolyfill || typeof FormData === "function" && value instanceof FormData;
278
+ }
279
+ async function bodyBytes(value, multipartBoundary) {
280
+ if (value == null) return /* @__PURE__ */ new ArrayBuffer(0);
281
+ if (typeof value === "string") return encodeText(value);
282
+ if (isArrayBufferLike(value)) return cloneArrayBuffer(value);
283
+ if (ArrayBuffer.isView(value)) return cloneArrayBufferView(value);
284
+ if (isBlobLike(value)) return cloneArrayBuffer(await value.arrayBuffer());
285
+ if (isReadableBodyStream(value)) return readBodyStream(value);
286
+ return (await encodeMultipartFormData(value, multipartBoundary)).body;
287
+ }
288
+ function initializeBody(owner, input) {
289
+ let value;
290
+ let contentType = "";
291
+ let multipartBoundary;
292
+ if (input == null) value = null;
293
+ else if (isReadableBodyStream(input)) {
294
+ observeBodyStream(input);
295
+ if (input.locked || isBodyStreamDisturbed(input)) throw new TypeError("Body stream is locked or has already been consumed");
296
+ value = input;
297
+ } else if (isArrayBufferLike(input)) value = cloneArrayBuffer(input);
298
+ else if (ArrayBuffer.isView(input)) value = cloneArrayBufferView(input);
299
+ else if (isBlobLike(input)) {
300
+ value = input;
301
+ contentType = input.type ?? "";
302
+ } else if (isFormData(input)) {
303
+ const snapshot = new FormDataPolyfill();
304
+ for (const [name, entry] of input) if (typeof entry === "string") snapshot.append(name, entry);
305
+ else snapshot.append(name, entry);
306
+ value = snapshot;
307
+ multipartBoundary = createMultipartBoundary(owner.headers.get("content-type"));
308
+ contentType = `multipart/form-data; boundary=${multipartBoundary}`;
309
+ } else if (isUrlSearchParamsInstance(input)) {
310
+ value = input.toString();
311
+ contentType = "application/x-www-form-urlencoded;charset=UTF-8";
312
+ } else {
313
+ value = String(input).replace(/[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDFFF]/g, (scalar) => scalar.length === 2 ? scalar : "�");
314
+ contentType = "text/plain;charset=UTF-8";
315
+ }
316
+ if (contentType && !owner.headers.has("content-type")) owner.headers.set("content-type", contentType);
317
+ let stream = null;
318
+ if (isReadableBodyStream(value)) stream = observeBodyStream(value);
319
+ else if (value !== null) {
320
+ const buffered = value;
321
+ stream = observeBodyStream(new ReadableStream({ async pull(controller) {
322
+ try {
323
+ const bytes = new Uint8Array(await bodyBytes(buffered, multipartBoundary));
324
+ if (bytes.byteLength > 0) controller.enqueue(bytes);
325
+ controller.close();
326
+ } catch (error) {
327
+ controller.error(error);
328
+ }
329
+ } }, { highWaterMark: 0 }));
330
+ }
331
+ const buffered = !isReadableBodyStream(value) || bufferedStreams.has(value);
332
+ if (stream && buffered) bufferedStreams.add(stream);
333
+ bodies.set(owner, {
334
+ value,
335
+ stream,
336
+ used: false,
337
+ buffered
338
+ });
339
+ }
340
+ function getBodyValue(owner) {
341
+ return bodies.get(owner)?.value;
342
+ }
343
+ /** 小程序宿主只能发送完整请求体;缓冲 Body 的 clone 分支仍属于有限上传。 */
344
+ function isStreamingRequestBody(owner) {
345
+ return bodies.get(owner)?.buffered === false;
346
+ }
347
+ function assertBodyUnused(owner) {
348
+ const state = bodies.get(owner);
349
+ if (state?.used || state?.stream && (state.stream.locked || isBodyStreamDisturbed(state.stream))) throw new TypeError("Body has already been consumed");
350
+ }
351
+ /** 在异步转换之前同步占用 body,确保并发读取与请求发送共享消费状态。 */
352
+ function consumeBodyValue(owner) {
353
+ assertBodyUnused(owner);
354
+ const state = bodies.get(owner);
355
+ if (state && state.value != null) {
356
+ state.used = true;
357
+ if (!isReadableBodyStream(state.value)) state.stream.getReader().cancel();
358
+ }
359
+ return state?.value;
360
+ }
361
+ /** clone 的两条分支独立消费,但保留底层取消与错误传播。 */
362
+ function cloneBodyValue(owner) {
363
+ assertBodyUnused(owner);
364
+ const state = bodies.get(owner);
365
+ if (!state?.stream) return null;
366
+ const [original, clone] = cloneBodyStream(state.stream);
367
+ state.stream = observeBodyStream(original);
368
+ state.value = original;
369
+ if (state.buffered) {
370
+ bufferedStreams.add(original);
371
+ bufferedStreams.add(clone);
372
+ }
373
+ return clone;
374
+ }
375
+ /** Request 构造的继承是所有权转移;原请求立即失去读取权,新请求按需拉取。 */
376
+ function transferBodyValue(owner) {
377
+ const value = consumeBodyValue(owner);
378
+ if (!isReadableBodyStream(value)) return value;
379
+ const reader = value.getReader();
380
+ const transferred = new ReadableStream({
381
+ async pull(controller) {
382
+ try {
383
+ const chunk = await reader.read();
384
+ if (chunk.done) controller.close();
385
+ else controller.enqueue(chunk.value);
386
+ } catch (error) {
387
+ controller.error(error);
388
+ }
389
+ },
390
+ cancel: (reason) => reader.cancel(reason)
391
+ }, { highWaterMark: 0 });
392
+ if (bodies.get(owner)?.buffered) bufferedStreams.add(transferred);
393
+ return transferred;
394
+ }
395
+ /** 仅供 Request/Response 内部复用,不作为包的公开导出。 */
396
+ var HttpBody = class {
397
+ get body() {
398
+ return bodies.get(this)?.stream ?? null;
399
+ }
400
+ get bodyUsed() {
401
+ const state = bodies.get(this);
402
+ return state?.used === true || Boolean(state?.stream && isBodyStreamDisturbed(state.stream));
403
+ }
404
+ async arrayBuffer() {
405
+ assertBodyUnused(this);
406
+ const state = bodies.get(this);
407
+ if (!state?.stream) return /* @__PURE__ */ new ArrayBuffer(0);
408
+ state.used = true;
409
+ return readBodyStream(state.stream);
410
+ }
411
+ async bytes() {
412
+ return new Uint8Array(await this.arrayBuffer());
413
+ }
414
+ async text() {
415
+ return new TextDecoderPolyfill().decode(await this.arrayBuffer());
416
+ }
417
+ async json() {
418
+ return JSON.parse(await this.text());
419
+ }
420
+ async blob() {
421
+ const bytes = await this.arrayBuffer();
422
+ const contentType = this.headers.get("content-type") ?? "";
423
+ const type = /^[!#$%&'*+.^`|~\w-]+\/[!#$%&'*+.^`|~\w-]+(?:\s*;[^\r\n]*)?$/.test(contentType) ? contentType : "";
424
+ return new (typeof Blob === "function" ? Blob : BlobPolyfill)([bytes], { type });
425
+ }
426
+ async formData() {
427
+ throw new TypeError("formData is not supported in Body polyfill");
428
+ }
429
+ };
430
+ // src/http/request.ts
431
+ var RequestPolyfill = class RequestPolyfill extends HttpBody {
432
+ url;
433
+ method;
434
+ headers;
435
+ signal;
436
+ [Symbol.toStringTag] = "Request";
437
+ constructor(input, init = {}) {
438
+ super();
439
+ const request = input instanceof RequestPolyfill ? input : void 0;
440
+ this.url = typeof input === "string" ? input : isUrlInstance(input) ? input.toString() : request?.url ?? "";
441
+ this.method = String(init.method ?? request?.method ?? "GET").toUpperCase();
442
+ this.headers = new HeadersPolyfill(init.headers ?? request?.headers);
443
+ this.signal = init.signal ?? request?.signal ?? null;
444
+ const inherited = init.body == null && request;
445
+ initializeBody(this, inherited ? transferBodyValue(request) : init.body);
446
+ }
447
+ clone() {
448
+ return new RequestPolyfill(this.url, {
449
+ method: this.method,
450
+ headers: this.headers,
451
+ signal: this.signal,
452
+ body: cloneBodyValue(this)
453
+ });
454
+ }
455
+ };
456
+ function getRequestBodyValue(request) {
457
+ return request ? getBodyValue(request) : void 0;
458
+ }
459
+ // src/http/response.ts
460
+ var ResponsePolyfill = class ResponsePolyfill extends HttpBody {
461
+ headers;
462
+ status;
463
+ statusText;
464
+ ok;
465
+ url;
466
+ redirected = false;
467
+ type;
468
+ [Symbol.toStringTag] = "Response";
469
+ constructor(body, init = {}) {
470
+ super();
471
+ this.status = Number.isFinite(init.status) ? init.status : 200;
472
+ this.statusText = init.statusText ?? "";
473
+ this.ok = this.status >= 200 && this.status < 300;
474
+ this.headers = new HeadersPolyfill(init.headers);
475
+ this.url = init.url ?? "";
476
+ this.type = init.type ?? "basic";
477
+ initializeBody(this, body);
478
+ }
479
+ static error() {
480
+ return new ResponsePolyfill(null, {
481
+ status: 0,
482
+ type: "error"
483
+ });
484
+ }
485
+ static json(data, init = {}) {
486
+ const body = JSON.stringify(data);
487
+ if (body === void 0) throw new TypeError("Failed to execute 'json' on 'Response': data is not JSON serializable");
488
+ const headers = new HeadersPolyfill(init.headers);
489
+ if (!headers.has("content-type")) headers.set("content-type", "application/json");
490
+ return new ResponsePolyfill(body, {
491
+ ...init,
492
+ headers
493
+ });
494
+ }
495
+ clone() {
496
+ return new ResponsePolyfill(cloneBodyValue(this), {
497
+ status: this.status,
498
+ statusText: this.statusText,
499
+ headers: this.headers,
500
+ url: this.url,
501
+ type: this.type
502
+ });
503
+ }
504
+ };
505
+ export { isReadableBodyStream as a, createMultipartBoundary as c, headersToObject as d, consumeBodyValue as i, encodeMultipartFormData as l, RequestPolyfill as n, isStreamingRequestBody as o, getRequestBodyValue as r, readBodyStream as s, ResponsePolyfill as t, HeadersPolyfill as u };
@@ -1,7 +1,6 @@
1
- import { t as RequestGlobalsBlobLike } from "./shared-Dc42USJC.mjs";
2
- import { t as URLPolyfill } from "./url-D0ANYIyk.mjs";
3
- import { n as FormDataPolyfill, o as BlobPolyfill } from "./web-DNBBg6y9.mjs";
4
- //#region src/http/headers.d.ts
1
+ import { t as RequestGlobalsBlobLike } from "./shared-DfU0oEwy.mjs";
2
+ import { t as URLPolyfill } from "./url-CEgyUgm2.mjs";
3
+ import { n as FormDataPolyfill, o as BlobPolyfill } from "./web-DjLufM4u.mjs";
5
4
  type HeaderRecord = Record<string, string>;
6
5
  declare class HeadersPolyfill {
7
6
  private readonly store;
@@ -19,13 +18,11 @@ declare class HeadersPolyfill {
19
18
  [Symbol.iterator](): ArrayIterator<[string, string]>;
20
19
  }
21
20
  declare function headersToObject(headers: HeadersPolyfill | Headers): HeaderRecord;
22
- //#endregion
23
- //#region src/http/body.d.ts
24
- type RequestBodyLike = string | ArrayBuffer | ArrayBufferView | Blob | RequestGlobalsBlobLike | FormData | FormDataPolyfill | null | undefined;
21
+ type RequestBodyLike = string | ArrayBuffer | ArrayBufferView | Blob | RequestGlobalsBlobLike | FormData | FormDataPolyfill | ReadableStream<Uint8Array<ArrayBuffer>> | null | undefined;
25
22
  /** 仅供 Request/Response 内部复用,不作为包的公开导出。 */
26
23
  declare abstract class HttpBody {
27
24
  abstract readonly headers: HeadersPolyfill;
28
- get body(): ReadableStream<Uint8Array> | null;
25
+ get body(): ReadableStream<Uint8Array<ArrayBuffer>> | null;
29
26
  get bodyUsed(): boolean;
30
27
  arrayBuffer(): Promise<ArrayBuffer>;
31
28
  bytes(): Promise<Uint8Array<ArrayBuffer>>;
@@ -34,8 +31,6 @@ declare abstract class HttpBody {
34
31
  blob(): Promise<Blob | BlobPolyfill>;
35
32
  formData(): Promise<FormData>;
36
33
  }
37
- //#endregion
38
- //#region src/http/request.d.ts
39
34
  declare class RequestPolyfill extends HttpBody {
40
35
  readonly url: string;
41
36
  readonly method: string;
@@ -46,8 +41,6 @@ declare class RequestPolyfill extends HttpBody {
46
41
  clone(): RequestPolyfill;
47
42
  }
48
43
  declare function getRequestBodyValue(request?: RequestPolyfill): RequestBodyLike;
49
- //#endregion
50
- //#region src/http/response.d.ts
51
44
  declare class ResponsePolyfill extends HttpBody {
52
45
  readonly headers: HeadersPolyfill;
53
46
  readonly status: number;
@@ -57,10 +50,9 @@ declare class ResponsePolyfill extends HttpBody {
57
50
  readonly redirected = false;
58
51
  readonly type: ResponseType;
59
52
  readonly [Symbol.toStringTag] = "Response";
60
- constructor(body?: RequestBodyLike, init?: Record<string, any>);
53
+ constructor(body?: RequestBodyLike | ReadableStream, init?: Record<string, any>);
61
54
  static error(): ResponsePolyfill;
62
55
  static json(data: unknown, init?: Record<string, any>): ResponsePolyfill;
63
56
  clone(): ResponsePolyfill;
64
57
  }
65
- //#endregion
66
58
  export { headersToObject as a, HeadersPolyfill as i, RequestPolyfill as n, getRequestBodyValue as r, ResponsePolyfill as t };
package/dist/http.d.mts CHANGED
@@ -1,2 +1,2 @@
1
- import { a as headersToObject, i as HeadersPolyfill, n as RequestPolyfill, r as getRequestBodyValue, t as ResponsePolyfill } from "./http-CE8-CIHE.mjs";
1
+ import { a as headersToObject, i as HeadersPolyfill, n as RequestPolyfill, r as getRequestBodyValue, t as ResponsePolyfill } from "./http-Dd6YCSHK.mjs";
2
2
  export { HeadersPolyfill, RequestPolyfill, ResponsePolyfill, getRequestBodyValue, headersToObject };
package/dist/http.mjs CHANGED
@@ -1 +1 @@
1
- export { o as HeadersPolyfill, n as RequestPolyfill, t as ResponsePolyfill, r as getRequestBodyValue, s as headersToObject } from "./http-DFOOhYXD.mjs";
1
+ export { u as HeadersPolyfill, n as RequestPolyfill, t as ResponsePolyfill, r as getRequestBodyValue, d as headersToObject } from "./http-DCCqK1QL.mjs";
package/dist/index.d.mts CHANGED
@@ -1,79 +1,45 @@
1
- import { i as RequestGlobalsEventTarget } from "./shared-Dc42USJC.mjs";
1
+ import { i as RequestGlobalsEventTarget } from "./shared-DfU0oEwy.mjs";
2
2
  import { AbortControllerPolyfill, AbortSignalPolyfill } from "./abort.mjs";
3
+ import { i as EventPolyfill, r as CustomEventPolyfill, t as EventSourcePolyfill } from "./eventsource-DUCc1iHv.mjs";
3
4
  import { MiniProgramNetworkDefaults, RequestGlobalsMiniProgramOptions, WebSocketMiniProgramOptions, getMiniProgramNetworkDefaults, resetMiniProgramNetworkDefaults, setMiniProgramNetworkDefaults } from "./networkDefaults.mjs";
4
- import { n as URLSearchParamsPolyfill, t as URLPolyfill } from "./url-D0ANYIyk.mjs";
5
- import { fetch } from "./fetch.mjs";
6
- import { i as HeadersPolyfill, n as RequestPolyfill, t as ResponsePolyfill } from "./http-CE8-CIHE.mjs";
7
- import { n as FormDataPolyfill, o as BlobPolyfill, r as FilePolyfill } from "./web-DNBBg6y9.mjs";
5
+ import { n as URLSearchParamsPolyfill, t as URLPolyfill } from "./url-CEgyUgm2.mjs";
6
+ import { t as fetch } from "./fetch-CSESA-oq.mjs";
7
+ import { i as HeadersPolyfill, n as RequestPolyfill, t as ResponsePolyfill } from "./http-Dd6YCSHK.mjs";
8
+ import { n as FormDataPolyfill, o as BlobPolyfill, r as FilePolyfill } from "./web-DjLufM4u.mjs";
9
+ import { ReadableStreamPolyfill, TextDecoderStreamPolyfill, TransformStreamPolyfill, WritableStreamPolyfill } from "./streams.mjs";
8
10
  import { WebSocketPolyfill } from "./websocket.mjs";
9
11
  import { XMLHttpRequestPolyfill } from "./xhr.mjs";
10
- //#region src/base64.d.ts
12
+ import { WebRuntimeGlobalTarget } from "@weapp-core/constants";
11
13
  export declare function btoaPolyfill(input?: string): string;
12
14
  export declare function atobPolyfill(input?: string): string;
13
- //#endregion
14
- //#region src/crypto.d.ts
15
15
  type IntegerTypedArray = Int8Array | Uint8Array | Uint8ClampedArray | Int16Array | Uint16Array | Int32Array | Uint32Array | BigInt64Array | BigUint64Array;
16
16
  declare function getRandomValuesPolyfill<T extends IntegerTypedArray>(typedArray: T): (T & Int8Array<ArrayBufferLike>) | (T & Uint8Array<ArrayBufferLike>) | (T & Uint8ClampedArray<ArrayBufferLike>) | (T & Int16Array<ArrayBufferLike>) | (T & Uint16Array<ArrayBufferLike>) | (T & Int32Array<ArrayBufferLike>) | (T & Uint32Array<ArrayBufferLike>) | (T & BigInt64Array<ArrayBufferLike>) | (T & BigUint64Array<ArrayBufferLike>);
17
17
  export declare const cryptoPolyfill: {
18
18
  getRandomValues: typeof getRandomValuesPolyfill;
19
19
  };
20
- //#endregion
21
- //#region src/events.d.ts
22
- interface EventInitPolyfill {
23
- bubbles?: boolean;
24
- cancelable?: boolean;
25
- composed?: boolean;
26
- }
27
- interface CustomEventInitPolyfill<T = any> extends EventInitPolyfill {
28
- detail?: T;
29
- }
30
- export declare class EventPolyfill {
31
- readonly bubbles: boolean;
32
- readonly cancelable: boolean;
33
- readonly composed: boolean;
34
- readonly isTrusted = false;
35
- readonly timeStamp: number;
36
- readonly type: string;
37
- currentTarget: unknown;
38
- target: unknown;
39
- defaultPrevented: boolean;
40
- cancelBubble: boolean;
41
- constructor(type: string, init?: EventInitPolyfill);
42
- composedPath(): {}[];
43
- preventDefault(): void;
44
- stopImmediatePropagation(): void;
45
- stopPropagation(): void;
46
- }
47
- export declare class CustomEventPolyfill<T = any> extends EventPolyfill {
48
- readonly detail: T | null;
49
- constructor(type: string, init?: CustomEventInitPolyfill<T>);
50
- }
51
- //#endregion
52
- //#region src/performance.d.ts
53
20
  declare const performancePolyfill: {
54
21
  __weappVitePerformancePolyfill: boolean;
55
22
  now(): number;
56
23
  timeOrigin: number;
57
24
  };
58
- //#endregion
59
- //#region src/task.d.ts
60
25
  export declare function queueMicrotaskPolyfill(callback: () => void): void;
61
- //#endregion
62
- //#region src/textCodec.d.ts
63
- type TextDecoderInput = ArrayBuffer | ArrayBufferView | null | undefined;
26
+ type TextDecoderInput = AllowSharedBufferSource | undefined;
64
27
  export declare class TextEncoderPolyfill {
65
28
  readonly encoding = "utf-8";
66
29
  encode(input?: string): Uint8Array<ArrayBuffer>;
67
30
  }
68
31
  export declare class TextDecoderPolyfill {
69
32
  readonly encoding = "utf-8";
70
- readonly fatal = false;
71
- readonly ignoreBOM = false;
72
- decode(input?: TextDecoderInput): string;
33
+ readonly fatal: boolean;
34
+ readonly ignoreBOM: boolean;
35
+ private pending;
36
+ private streaming;
37
+ private bomSeen;
38
+ constructor(label?: string, options?: TextDecoderOptions);
39
+ decode(input?: TextDecoderInput, options?: TextDecodeOptions): string;
40
+ get [Symbol.toStringTag](): string;
73
41
  }
74
- //#endregion
75
- //#region src/index.d.ts
76
- export type WeappInjectWebRuntimeGlobalsTarget = 'fetch' | 'Headers' | 'Request' | 'Response' | 'TextEncoder' | 'TextDecoder' | 'AbortController' | 'AbortSignal' | 'XMLHttpRequest' | 'WebSocket' | 'atob' | 'btoa' | 'queueMicrotask' | 'performance' | 'crypto' | 'Event' | 'CustomEvent';
42
+ export type WeappInjectWebRuntimeGlobalsTarget = WebRuntimeGlobalTarget;
77
43
  export type WeappInjectRequestGlobalsTarget = WeappInjectWebRuntimeGlobalsTarget;
78
44
  export interface InstallWebRuntimeGlobalsOptions {
79
45
  targets?: WeappInjectWebRuntimeGlobalsTarget[];
@@ -92,5 +58,4 @@ export declare function installRequestGlobals(options?: InstallRequestGlobalsOpt
92
58
  * @description 仅安装 AbortController 与 AbortSignal 兼容层。
93
59
  */
94
60
  export declare function installAbortGlobals(): Record<string, any>;
95
- //#endregion
96
- export { AbortControllerPolyfill, AbortSignalPolyfill, BlobPolyfill, FilePolyfill, FormDataPolyfill, HeadersPolyfill, type MiniProgramNetworkDefaults, RequestGlobalsEventTarget, type RequestGlobalsMiniProgramOptions, RequestPolyfill, ResponsePolyfill, URLPolyfill, URLSearchParamsPolyfill, type WebSocketMiniProgramOptions, WebSocketPolyfill, XMLHttpRequestPolyfill, fetch, getMiniProgramNetworkDefaults, performancePolyfill, resetMiniProgramNetworkDefaults, setMiniProgramNetworkDefaults };
61
+ export { AbortControllerPolyfill, AbortSignalPolyfill, BlobPolyfill, CustomEventPolyfill, EventPolyfill, EventSourcePolyfill, FilePolyfill, FormDataPolyfill, HeadersPolyfill, type MiniProgramNetworkDefaults, ReadableStreamPolyfill, RequestGlobalsEventTarget, type RequestGlobalsMiniProgramOptions, RequestPolyfill, ResponsePolyfill, TextDecoderStreamPolyfill, TransformStreamPolyfill, URLPolyfill, URLSearchParamsPolyfill, type WebSocketMiniProgramOptions, WebSocketPolyfill, WritableStreamPolyfill, XMLHttpRequestPolyfill, fetch, getMiniProgramNetworkDefaults, performancePolyfill, resetMiniProgramNetworkDefaults, setMiniProgramNetworkDefaults };