cf-workers-native 0.1.5 → 0.1.6

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 (197) hide show
  1. package/README.md +2 -2
  2. package/dist/browser/documents/page-source.js +1 -1
  3. package/dist/browser/headers/index.d.ts +2 -0
  4. package/dist/browser/headers/index.js +5 -0
  5. package/dist/browser/response/index.d.ts +2 -0
  6. package/dist/browser/response/index.js +11 -3
  7. package/dist/browser/structured-clone/index.d.ts +3 -0
  8. package/dist/browser/structured-clone/index.js +75 -7
  9. package/dist/browser/websocket/attachment-size.d.ts +3 -0
  10. package/dist/browser/websocket/attachment-size.js +336 -0
  11. package/dist/browser/websocket/brand.d.ts +4 -0
  12. package/dist/browser/websocket/brand.js +16 -0
  13. package/dist/browser/websocket/close-event.d.ts +7 -0
  14. package/dist/browser/websocket/close-event.js +30 -0
  15. package/dist/browser/websocket/compression.d.ts +5 -0
  16. package/dist/browser/websocket/compression.js +124 -0
  17. package/dist/browser/websocket/conversion.d.ts +2 -0
  18. package/dist/browser/websocket/conversion.js +13 -0
  19. package/dist/browser/websocket/endpoint.d.ts +39 -0
  20. package/dist/browser/websocket/endpoint.js +379 -0
  21. package/dist/browser/websocket/frames.d.ts +21 -0
  22. package/dist/browser/websocket/frames.js +121 -0
  23. package/dist/browser/websocket/native.d.ts +14 -0
  24. package/dist/browser/websocket/native.js +226 -0
  25. package/dist/cloudflare/apis/cloudflare-node/index.js +11 -23
  26. package/dist/compat/crypto/LICENSE-3RD-PARTY.md +20 -0
  27. package/dist/compat/crypto/LICENSE.boringssl +238 -0
  28. package/dist/compat/crypto/LICENSE.ncrypto +21 -0
  29. package/dist/compat/crypto/asymmetric.js +141 -68
  30. package/dist/compat/crypto/cipher-handle.d.ts +27 -0
  31. package/dist/compat/crypto/cipher-handle.js +239 -0
  32. package/dist/compat/crypto/cipher-info.d.ts +12 -0
  33. package/dist/compat/crypto/cipher-info.js +324 -0
  34. package/dist/compat/crypto/constants.d.ts +62 -0
  35. package/dist/compat/crypto/constants.js +68 -0
  36. package/dist/compat/crypto/dh-handle.d.ts +17 -0
  37. package/dist/compat/crypto/dh-handle.js +180 -0
  38. package/dist/compat/crypto/dh.d.ts +53 -0
  39. package/dist/compat/crypto/dh.js +138 -0
  40. package/dist/compat/crypto/digest-stream.d.ts +15 -0
  41. package/dist/compat/crypto/digest-stream.js +213 -0
  42. package/dist/compat/crypto/digests.d.ts +3 -0
  43. package/dist/compat/crypto/digests.js +32 -0
  44. package/dist/compat/crypto/ecdh.d.ts +16 -6
  45. package/dist/compat/crypto/hash-handle.d.ts +23 -0
  46. package/dist/compat/crypto/hash-handle.js +70 -0
  47. package/dist/compat/crypto/hash.d.ts +37 -0
  48. package/dist/compat/crypto/hash.js +218 -0
  49. package/dist/compat/crypto/hkdf.js +40 -14
  50. package/dist/compat/crypto/index.d.cts +168 -1
  51. package/dist/compat/crypto/index.d.ts +191 -8
  52. package/dist/compat/crypto/index.js +36 -23
  53. package/dist/compat/crypto/key-errors.d.ts +10 -0
  54. package/dist/compat/crypto/key-errors.js +17 -0
  55. package/dist/compat/crypto/key-export.d.ts +8 -0
  56. package/dist/compat/crypto/key-export.js +49 -0
  57. package/dist/compat/crypto/key-formats.d.ts +2 -1
  58. package/dist/compat/crypto/key-formats.js +162 -31
  59. package/dist/compat/crypto/key-options.d.ts +1 -0
  60. package/dist/compat/crypto/key-options.js +74 -0
  61. package/dist/compat/crypto/key-state.d.ts +1 -0
  62. package/dist/compat/crypto/keys.d.ts +20 -12
  63. package/dist/compat/crypto/keys.js +125 -56
  64. package/dist/compat/crypto/metadata.d.ts +9 -0
  65. package/dist/compat/crypto/metadata.js +89 -2
  66. package/dist/compat/crypto/native-cipher.d.ts +17 -0
  67. package/dist/compat/crypto/native-cipher.js +192 -0
  68. package/dist/compat/crypto/native-crypto.d.ts +14 -1
  69. package/dist/compat/crypto/native-crypto.js +118 -6
  70. package/dist/compat/crypto/pbkdf2-handle.d.ts +4 -0
  71. package/dist/compat/crypto/pbkdf2-handle.js +26 -0
  72. package/dist/compat/crypto/pbkdf2.d.ts +5 -0
  73. package/dist/compat/crypto/pbkdf2.js +60 -0
  74. package/dist/compat/crypto/prime.js +4 -4
  75. package/dist/compat/crypto/random.d.ts +11 -0
  76. package/dist/compat/crypto/random.js +86 -6
  77. package/dist/compat/crypto/rsa.d.ts +17 -1
  78. package/dist/compat/crypto/rsa.js +8 -4
  79. package/dist/compat/crypto/scrypt.d.ts +3 -3
  80. package/dist/compat/crypto/scrypt.js +25 -23
  81. package/dist/compat/crypto/sign-handle.d.ts +3 -3
  82. package/dist/compat/crypto/sign-handle.js +55 -11
  83. package/dist/compat/crypto/signatures.d.ts +17 -11
  84. package/dist/compat/crypto/subtle-digest.d.ts +1 -0
  85. package/dist/compat/crypto/subtle-digest.js +56 -0
  86. package/dist/compat/crypto/symmetric.d.ts +40 -24
  87. package/dist/compat/crypto/symmetric.js +229 -94
  88. package/dist/compat/crypto/validation.d.ts +4 -0
  89. package/dist/compat/crypto/validation.js +29 -2
  90. package/dist/compat/crypto/webcrypto.d.ts +13 -0
  91. package/dist/compat/crypto/webcrypto.js +51 -0
  92. package/dist/compat/crypto/x509.js +2 -1
  93. package/dist/compat/events/index.js +1 -1
  94. package/dist/compat/fs/LICENSE-3RD-PARTY.md +11 -0
  95. package/dist/compat/fs/LICENSE-APACHE +177 -0
  96. package/dist/compat/fs/directory-backend.d.ts +6 -0
  97. package/dist/compat/fs/directory-backend.js +51 -0
  98. package/dist/compat/fs/directory.d.ts +37 -0
  99. package/dist/compat/fs/directory.js +137 -0
  100. package/dist/compat/fs/embedded.d.ts +1 -1
  101. package/dist/compat/fs/embedded.js +7 -2
  102. package/dist/compat/fs/file-handle.d.ts +75 -0
  103. package/dist/compat/fs/file-handle.js +226 -0
  104. package/dist/compat/fs/glob-internal.d.ts +15 -0
  105. package/dist/compat/fs/glob-internal.js +417 -0
  106. package/dist/compat/fs/glob.d.ts +10 -0
  107. package/dist/compat/fs/glob.js +71 -0
  108. package/dist/compat/fs/index.d.ts +6 -3
  109. package/dist/compat/fs/index.js +582 -50
  110. package/dist/compat/fs/io-validation.d.ts +14 -0
  111. package/dist/compat/fs/io-validation.js +130 -0
  112. package/dist/compat/fs/io.d.ts +1 -0
  113. package/dist/compat/fs/io.js +282 -0
  114. package/dist/compat/fs/promises/index.d.ts +3 -1
  115. package/dist/compat/fs/public-types.d.ts +120 -0
  116. package/dist/compat/fs/public-types.js +1 -0
  117. package/dist/compat/fs/stream-errors.d.ts +6 -0
  118. package/dist/compat/fs/stream-errors.js +8 -0
  119. package/dist/compat/fs/stream-utils.d.ts +16 -0
  120. package/dist/compat/fs/stream-utils.js +29 -0
  121. package/dist/compat/fs/streams.d.ts +104 -0
  122. package/dist/compat/fs/streams.js +794 -0
  123. package/dist/compat/fs/writable.d.ts +8 -0
  124. package/dist/compat/fs/writable.js +412 -22
  125. package/dist/compat/http/index.d.ts +11 -28
  126. package/dist/compat/http/index.js +81 -125
  127. package/dist/compat/http/server-options.d.ts +1 -0
  128. package/dist/compat/http/server-options.js +87 -0
  129. package/dist/compat/http/unique-headers.d.ts +1 -0
  130. package/dist/compat/http/unique-headers.js +21 -0
  131. package/dist/compat/http-outgoing/index.d.ts +2 -1
  132. package/dist/compat/http-outgoing/index.js +2 -17
  133. package/dist/compat/http-server/index.d.ts +2 -2
  134. package/dist/compat/http-server/index.js +4 -85
  135. package/dist/compat/https/index.d.ts +4 -2
  136. package/dist/compat/net/sockets.js +98 -20
  137. package/dist/compat/net/validators.d.ts +1 -0
  138. package/dist/compat/net/validators.js +8 -0
  139. package/dist/compat/process/configuration.d.ts +113 -0
  140. package/dist/compat/process/configuration.js +115 -0
  141. package/dist/compat/process/directory.d.ts +4 -0
  142. package/dist/compat/process/directory.js +28 -0
  143. package/dist/compat/process/files.d.ts +3 -0
  144. package/dist/compat/process/files.js +10 -0
  145. package/dist/compat/process/index.d.ts +15 -13
  146. package/dist/compat/process/index.js +47 -74
  147. package/dist/compat/process/scheduling.d.ts +2 -0
  148. package/dist/compat/process/scheduling.js +60 -0
  149. package/dist/compat/process/state.js +1 -0
  150. package/dist/compat/process/stdio.d.ts +18 -0
  151. package/dist/compat/process/stdio.js +66 -0
  152. package/dist/compat/stream/destroy.d.ts +1 -0
  153. package/dist/compat/stream/destroy.js +21 -1
  154. package/dist/compat/stream/readable.js +10 -2
  155. package/dist/compat/tls/jsstream.js +16 -6
  156. package/dist/compat/tls/wrap.d.ts +1 -1
  157. package/dist/compat/tls/wrap.js +0 -3
  158. package/dist/compat/util/inspect.js +5 -1
  159. package/dist/compat/zlib/LICENSE-3RD-PARTY.md +11 -0
  160. package/dist/compat/zlib/LICENSE-APACHE +177 -0
  161. package/dist/compat/zlib/LICENSE.zlib +22 -0
  162. package/dist/compat/zlib/classic-base.cjs +600 -0
  163. package/dist/compat/zlib/classic-base.d.cts +39 -0
  164. package/dist/compat/zlib/classic-binding.d.ts +28 -0
  165. package/dist/compat/zlib/classic-binding.js +105 -0
  166. package/dist/compat/zlib/classic.d.ts +44 -0
  167. package/dist/compat/zlib/classic.js +199 -0
  168. package/dist/compat/zlib/codec-binding.d.ts +33 -0
  169. package/dist/compat/zlib/codec-binding.js +141 -0
  170. package/dist/compat/zlib/compression.d.ts +22 -51
  171. package/dist/compat/zlib/compression.js +129 -218
  172. package/dist/compat/zlib/errors.d.ts +21 -0
  173. package/dist/compat/zlib/errors.js +32 -0
  174. package/dist/compat/zlib/index.d.ts +367 -3
  175. package/dist/compat/zlib/index.js +28 -11
  176. package/dist/compat/zlib/input.d.ts +16 -0
  177. package/dist/compat/zlib/input.js +132 -0
  178. package/dist/compat/zlib/native-codecs.d.ts +7 -0
  179. package/dist/compat/zlib/native-codecs.js +22 -10
  180. package/dist/compat/zlib/native-zlib.d.ts +5 -0
  181. package/dist/compat/zlib/native-zlib.js +52 -0
  182. package/dist/compat/zlib/public-types.d.ts +48 -0
  183. package/dist/compat/zlib/public-types.js +1 -0
  184. package/dist/compat/zlib/validators.d.ts +3 -0
  185. package/dist/compat/zlib/validators.js +18 -0
  186. package/dist/shared/buffer-source.d.ts +5 -0
  187. package/dist/shared/buffer-source.js +70 -0
  188. package/dist/shared/globals/platform.d.ts +8 -0
  189. package/dist/shared/globals/platform.js +1 -0
  190. package/dist/shared/globals/web.js +5 -0
  191. package/dist/shared/request-context.d.ts +2 -0
  192. package/dist/shared/request-context.js +11 -0
  193. package/dist/shared/request-scope.js +4 -1
  194. package/dist/tooling/shared.js +6 -0
  195. package/dist/tooling/vite.js +4 -0
  196. package/native/android/src/main/java/jp/rdlabo/workerscapacitor/WorkerSockets.java +38 -7
  197. package/package.json +2 -2
@@ -2,6 +2,8 @@
2
2
  export declare function immutableHeaders(headers: Headers): Headers;
3
3
  export declare function cloneHeaders(headers: Headers): Headers;
4
4
  export type HeadersInit = Headers | Iterable<Iterable<unknown>> | Record<string, unknown>;
5
+ /** Internal serialization preserves separate values before display joins them. */
6
+ export declare let serializedHeaderFields: (headers: Headers) => [string, string[]][];
5
7
  export declare class Headers {
6
8
  #private;
7
9
  constructor(init?: HeadersInit | undefined);
@@ -73,8 +73,13 @@ function value(input) {
73
73
  // an invalid three-byte sequence, with one replacement per invalid byte.
74
74
  return result.replace(/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/g, "���");
75
75
  }
76
+ /** Internal serialization preserves separate values before display joins them. */
77
+ export let serializedHeaderFields;
76
78
  export class Headers {
77
79
  #fields = new Map();
80
+ static {
81
+ serializedHeaderFields = (headers) => [...headers.#fields].map(([name, values]) => [name, [...values]]);
82
+ }
78
83
  constructor(init = undefined) {
79
84
  if (init === undefined)
80
85
  return;
@@ -12,6 +12,7 @@ export declare function responseEncoding(response: Response): "automatic" | "man
12
12
  export interface StructuredCloneResponseSnapshot {
13
13
  status: number;
14
14
  statusText: string;
15
+ serializedStatusText?: string;
15
16
  headers: Headers;
16
17
  cf: Record<string, unknown> | undefined;
17
18
  webSocket: WebSocket | null;
@@ -41,3 +42,4 @@ export declare class Response extends Body {
41
42
  static redirect(url: string | URL, status?: number): Response;
42
43
  static json(value: unknown, init?: ResponseInit): Response;
43
44
  }
45
+ import type { WebSocket } from "../websocket/endpoint.js";
@@ -12,6 +12,7 @@ export let networkResponse;
12
12
  export class Response extends Body {
13
13
  #status;
14
14
  #statusText;
15
+ #serializedStatusText;
15
16
  #headers;
16
17
  #cf;
17
18
  #webSocket;
@@ -28,6 +29,7 @@ export class Response extends Body {
28
29
  structuredCloneResponseSnapshot = (response) => ({
29
30
  status: response.#status,
30
31
  statusText: response.#statusText,
32
+ serializedStatusText: response.#serializedStatusText,
31
33
  headers: response.#headers,
32
34
  cf: response.#cf,
33
35
  webSocket: response.#webSocket,
@@ -48,6 +50,7 @@ export class Response extends Body {
48
50
  encodeBody: snapshot.encodeBody,
49
51
  });
50
52
  response.#headers = snapshot.headers;
53
+ response.#serializedStatusText = snapshot.serializedStatusText;
51
54
  setBodyHeaders(response, snapshot.headers);
52
55
  response.#cf = snapshot.cf;
53
56
  response.#url = snapshot.url;
@@ -60,15 +63,16 @@ export class Response extends Body {
60
63
  init = dictionary(init);
61
64
  const status = init.status === undefined ? 200 : Math.trunc(Number(init.status));
62
65
  const webSocket = init.webSocket ?? null;
63
- if (webSocket !== null && !(webSocket instanceof WebSocket))
66
+ if (webSocket !== null && !isWebSocket(webSocket))
64
67
  throw new TypeError("webSocket must be a WebSocket");
65
68
  if (webSocket === null ? !(status >= 200 && status <= 599) : status !== 101)
66
69
  throw new RangeError(webSocket === null
67
70
  ? "Responses may only be constructed with status codes in the range 200 to 599, inclusive."
68
71
  : "Responses with a WebSocket must have status code 101.");
69
- const text = init.statusText === undefined
72
+ const suppliedStatusText = init.statusText;
73
+ const text = suppliedStatusText === undefined
70
74
  ? statusText(status)
71
- : webString(init.statusText);
75
+ : webString(suppliedStatusText);
72
76
  if (/[\x00-\x1f]/.test(text))
73
77
  throw new TypeError("Invalid statusText");
74
78
  const bodyEncoding = init instanceof Response
@@ -92,6 +96,8 @@ export class Response extends Body {
92
96
  super(body, headers);
93
97
  this.#status = status;
94
98
  this.#statusText = text;
99
+ this.#serializedStatusText =
100
+ suppliedStatusText === undefined ? undefined : text;
95
101
  this.#headers = headers;
96
102
  this.#cf = cloneValue(init.cf);
97
103
  this.#webSocket = webSocket;
@@ -138,6 +144,7 @@ export class Response extends Body {
138
144
  encodeBody: encoding.get(this),
139
145
  });
140
146
  copy.#headers = cloneHeaders(this.#headers);
147
+ copy.#serializedStatusText = this.#serializedStatusText;
141
148
  setBodyHeaders(copy, copy.#headers);
142
149
  copy.#url = this.#url;
143
150
  copy.#redirected = this.#redirected;
@@ -190,3 +197,4 @@ Object.defineProperty(Response.prototype, Symbol.toStringTag, {
190
197
  for (const key of Object.getOwnPropertyNames(Response.prototype))
191
198
  if (key !== "constructor")
192
199
  Object.defineProperty(Response.prototype, key, { enumerable: true });
200
+ import { isWebSocket } from "../websocket/brand.js";
@@ -1 +1,4 @@
1
1
  export declare function structuredClone<T>(value: T, options?: StructuredSerializeOptions): T;
2
+ /** Attachment bytes omit the shared-memory external table. Retain only the
3
+ * brand while validating/counting; deserializeAttachment always rejects it. */
4
+ export declare function cloneAttachment<T>(value: T): T;
@@ -1,4 +1,6 @@
1
1
  import { isURLInstance } from "../../compat/url/brand.js";
2
+ import { isSharedBuffer } from "../../shared/buffer-source.js";
3
+ import { isWebSocketPair } from "../websocket/brand.js";
2
4
  import { platform } from "../../shared/globals/platform.js";
3
5
  import { cloneHeaders, Headers } from "../headers/index.js";
4
6
  import { Request, structuredCloneRequestSnapshot } from "../request/index.js";
@@ -63,8 +65,9 @@ function nativeValue(value) {
63
65
  value instanceof RegExp ||
64
66
  value instanceof Blob ||
65
67
  value instanceof ArrayBuffer ||
66
- (typeof SharedArrayBuffer === "function" &&
67
- value instanceof SharedArrayBuffer) ||
68
+ isSharedBuffer(value) ||
69
+ value instanceof WebAssembly.Module ||
70
+ value instanceof WebAssembly.Memory ||
68
71
  ArrayBuffer.isView(value));
69
72
  }
70
73
  function errorName(error) {
@@ -98,6 +101,47 @@ function encode(value, tag, metadata, seen, transferred, markers) {
98
101
  throw dataCloneError("[object Symbol] could not be cloned.");
99
102
  if (seen.has(value))
100
103
  return seen.get(value);
104
+ const wasmMemoryBuffer = value instanceof WebAssembly.Memory
105
+ ? Object.getOwnPropertyDescriptor(WebAssembly.Memory.prototype, "buffer").get.call(value)
106
+ : undefined;
107
+ if (wasmMemoryBuffer && !isSharedBuffer(wasmMemoryBuffer))
108
+ throw dataCloneError("#<Memory> could not be cloned.");
109
+ for (const [name, Constructor] of [
110
+ ["Instance", WebAssembly.Instance],
111
+ ["Table", WebAssembly.Table],
112
+ ["Global", WebAssembly.Global],
113
+ ])
114
+ if (value instanceof Constructor)
115
+ throw dataCloneError(`#<${name}> could not be cloned.`);
116
+ if (metadata.attachment &&
117
+ (value instanceof WebAssembly.Module ||
118
+ value instanceof WebAssembly.Memory ||
119
+ isSharedBuffer(value) ||
120
+ (ArrayBuffer.isView(value) && isSharedBuffer(viewField(value, "buffer"))))) {
121
+ const marker = { [tag]: metadata.length };
122
+ markers.push(marker);
123
+ seen.set(value, marker);
124
+ metadata.push({
125
+ type: "shared-attachment",
126
+ value: value,
127
+ });
128
+ return marker;
129
+ }
130
+ for (const [name, matches] of [
131
+ ["WebSocketPair", isWebSocketPair(value)],
132
+ [
133
+ "CryptoKey",
134
+ typeof CryptoKey === "function" && value instanceof CryptoKey,
135
+ ],
136
+ ["FormData", value instanceof FormData],
137
+ [
138
+ "MessageChannel",
139
+ typeof MessageChannel === "function" && value instanceof MessageChannel,
140
+ ],
141
+ ["Event", value instanceof Event],
142
+ ])
143
+ if (matches)
144
+ throw dataCloneError(`Could not serialize object of type "${name}". This type does not support serialization.`);
101
145
  if (value instanceof WorkersFile)
102
146
  throw dataCloneError('Could not serialize object of type "File". This type does not support serialization.');
103
147
  if (value instanceof WorkersBlob) {
@@ -183,11 +227,22 @@ function encode(value, tag, metadata, seen, transferred, markers) {
183
227
  marker.cause = encode(value.cause, tag, metadata, seen, transferred, markers);
184
228
  if (value instanceof AggregateError)
185
229
  marker.errors = encode(value.errors, tag, metadata, seen, transferred, markers);
186
- for (const key of Object.keys(value)) {
230
+ for (const key of Object.getOwnPropertyNames(value)) {
187
231
  if (["stack", "message", "cause", "errors"].includes(key))
188
232
  continue;
233
+ const index = Number(key);
234
+ if (Number.isInteger(index) &&
235
+ index >= 0 &&
236
+ index < 0xffffffff &&
237
+ String(index) === key)
238
+ continue;
189
239
  marker.properties ??= {};
190
- marker.properties[key] = encode(value[key], tag, metadata, seen, transferred, markers);
240
+ Object.defineProperty(marker.properties, key, {
241
+ enumerable: true,
242
+ configurable: true,
243
+ writable: true,
244
+ value: encode(value[key], tag, metadata, seen, transferred, markers),
245
+ });
191
246
  }
192
247
  return marker;
193
248
  }
@@ -204,6 +259,8 @@ function encode(value, tag, metadata, seen, transferred, markers) {
204
259
  }
205
260
  if (value instanceof AbortSignal)
206
261
  throw dataCloneError("AbortSignal serialization is not enabled.");
262
+ if (value instanceof EventTarget)
263
+ throw dataCloneError(`Could not serialize object of type "${value.constructor.name}". This type does not support serialization.`);
207
264
  for (const [type, Constructor] of [
208
265
  ["ReadableStream", ReadableStream],
209
266
  ["WritableStream", WritableStream],
@@ -266,7 +323,9 @@ function encode(value, tag, metadata, seen, transferred, markers) {
266
323
  }
267
324
  if (value instanceof WeakMap ||
268
325
  value instanceof WeakSet ||
269
- value instanceof Promise)
326
+ value instanceof Promise ||
327
+ value instanceof WeakRef ||
328
+ value instanceof FinalizationRegistry)
270
329
  return platformStructuredClone(value);
271
330
  if (value instanceof Map) {
272
331
  const result = new Map();
@@ -378,7 +437,7 @@ function decode(value, tag, metadata, seen, markers) {
378
437
  return error;
379
438
  }
380
439
  const entry = metadata[Number(id)];
381
- if (entry.type === "blob") {
440
+ if (entry.type === "blob" || entry.type === "shared-attachment") {
382
441
  seen.set(value, entry.value);
383
442
  return entry.value;
384
443
  }
@@ -400,6 +459,7 @@ function decode(value, tag, metadata, seen, markers) {
400
459
  cf: decode(marker.cf, tag, metadata, seen, markers),
401
460
  fetcher: null,
402
461
  cache: entry.value.cache,
462
+ encodeResponseBody: entry.value.encodeResponseBody,
403
463
  });
404
464
  seen.set(value, request);
405
465
  return request;
@@ -467,8 +527,16 @@ function transfers(options) {
467
527
  export function structuredClone(value, options) {
468
528
  if (arguments.length === 0)
469
529
  throw new TypeError("Failed to execute 'structuredClone' on 'ServiceWorkerGlobalScope': parameter 1 is not of type 'Value'.");
470
- const transfer = transfers(options);
530
+ return snapshot(value, transfers(options));
531
+ }
532
+ /** Attachment bytes omit the shared-memory external table. Retain only the
533
+ * brand while validating/counting; deserializeAttachment always rejects it. */
534
+ export function cloneAttachment(value) {
535
+ return snapshot(value, [], true);
536
+ }
537
+ function snapshot(value, transfer, attachment = false) {
471
538
  const metadata = [];
539
+ metadata.attachment = attachment;
472
540
  const tag = "__workers_capacitor_clone__";
473
541
  const markers = [];
474
542
  const encoded = encode(value, tag, metadata, new Map(), new Set(transfer), markers);
@@ -0,0 +1,3 @@
1
+ export declare function attachmentSize(value: unknown, externals?: {
2
+ shared: boolean;
3
+ }): number;
@@ -0,0 +1,336 @@
1
+ /** Canonical V8 wire-format-15 byte accounting; see README.md for the narrowly
2
+ * approved storage-representation boundary. Values must already be snapshotted.
3
+ * This counts wire tags, lengths, references and payloads, not JSON text. */
4
+ import { Blob } from "../../compat/buffer/blob.js";
5
+ import { isSharedBuffer } from "../../shared/buffer-source.js";
6
+ import { Headers, serializedHeaderFields } from "../headers/index.js";
7
+ import { Request, structuredCloneRequestSnapshot } from "../request/index.js";
8
+ import { Response, structuredCloneResponseSnapshot, } from "../response/index.js";
9
+ const commonHeaders = new Set(`accept-charset accept-encoding accept-language accept-ranges accept access-control-allow-origin age allow authorization cache-control content-disposition content-encoding content-language content-length content-location content-range content-type cookie date etag expect expires from host if-match if-modified-since if-none-match if-range if-unmodified-since last-modified link location max-forwards proxy-authenticate proxy-authorization range referer refresh retry-after server set-cookie strict-transport-security transfer-encoding user-agent vary via www-authenticate`.split(" "));
10
+ export function attachmentSize(value, externals) {
11
+ let size = 2; // Version marker and version 15.
12
+ const seen = new Map();
13
+ let sharedCount = 0;
14
+ const wasmBuffers = new Set();
15
+ const uint = (value) => {
16
+ let bytes = 1;
17
+ while (value >= 128) {
18
+ bytes++;
19
+ value = Math.floor(value / 128);
20
+ }
21
+ return bytes;
22
+ };
23
+ const string = (value) => {
24
+ let latin = true;
25
+ for (let i = 0; i < value.length; i++)
26
+ if (value.charCodeAt(i) > 255) {
27
+ latin = false;
28
+ break;
29
+ }
30
+ const bytes = value.length * (latin ? 1 : 2);
31
+ const prefix = 1 + uint(bytes);
32
+ if (!latin && (size + prefix) % 2)
33
+ size++;
34
+ size += prefix + bytes;
35
+ };
36
+ const rawString = (value) => {
37
+ const bytes = new TextEncoder().encode(value).length;
38
+ size += uint(bytes) + bytes;
39
+ };
40
+ const bigint = (value) => {
41
+ const magnitude = value < 0n ? -value : value;
42
+ const bytes = magnitude === 0n ? 0 : Math.ceil(magnitude.toString(2).length / 64) * 8;
43
+ size += 1 + uint(bytes * 2 + Number(value < 0n)) + bytes;
44
+ };
45
+ const property = (key, value) => {
46
+ const index = Number(key);
47
+ if (Number.isInteger(index) &&
48
+ index >= 0 &&
49
+ index < 0xffffffff &&
50
+ String(index) === key) {
51
+ // Index property names are unsigned integers in the serializer.
52
+ size += 1 + uint(index);
53
+ }
54
+ else
55
+ string(key);
56
+ write(value);
57
+ };
58
+ const write = (value) => {
59
+ if (value === null || value === undefined || typeof value === "boolean") {
60
+ size++;
61
+ return;
62
+ }
63
+ if (typeof value === "string") {
64
+ string(value);
65
+ return;
66
+ }
67
+ if (typeof value === "number") {
68
+ size +=
69
+ Number.isInteger(value) &&
70
+ !Object.is(value, -0) &&
71
+ value >= -2147483648 &&
72
+ value <= 2147483647
73
+ ? 1 + uint(((value << 1) ^ (value >> 31)) >>> 0)
74
+ : 9;
75
+ return;
76
+ }
77
+ if (typeof value === "bigint") {
78
+ bigint(value);
79
+ return;
80
+ }
81
+ if (typeof value !== "object")
82
+ throw new DOMException(`${String(value)} could not be cloned.`, "DataCloneError");
83
+ const id = seen.get(value);
84
+ if (id !== undefined) {
85
+ size += 1 + uint(id);
86
+ return;
87
+ }
88
+ // A view's backing buffer receives its reference ID before the view does.
89
+ if (ArrayBuffer.isView(value)) {
90
+ const prototype = value instanceof DataView
91
+ ? DataView.prototype
92
+ : Object.getPrototypeOf(Uint8Array.prototype);
93
+ const field = (key) => Object.getOwnPropertyDescriptor(prototype, key).get.call(value);
94
+ write(field("buffer"));
95
+ seen.set(value, seen.size);
96
+ size += 2 + uint(field("byteOffset")) + uint(field("byteLength")) + 1;
97
+ return;
98
+ }
99
+ seen.set(value, seen.size);
100
+ if (value instanceof WebAssembly.Module) {
101
+ // workerd has no Wasm-module transfer delegate: no payload is written,
102
+ // and subsequent deserialization fails for the absent external module.
103
+ if (externals)
104
+ externals.shared = true;
105
+ return;
106
+ }
107
+ if (value instanceof WebAssembly.Memory) {
108
+ const buffer = Object.getOwnPropertyDescriptor(WebAssembly.Memory.prototype, "buffer").get.call(value);
109
+ if (!isSharedBuffer(buffer))
110
+ throw new DOMException("#<Memory> could not be cloned.", "DataCloneError");
111
+ // Maximum capacity is private metadata. Canonical accounting uses current
112
+ // capacity for this opaque, non-deserializable attachment (see README).
113
+ size += 2 + uint((buffer.byteLength / 65536) * 2);
114
+ wasmBuffers.add(buffer);
115
+ write(buffer);
116
+ return;
117
+ }
118
+ // workerd host tags and payloads, pinned to the profile's source revision.
119
+ if (value instanceof Blob) {
120
+ size += 2;
121
+ rawString(value.type);
122
+ size += uint(value.size) + value.size;
123
+ return;
124
+ }
125
+ if (value instanceof Headers) {
126
+ const fields = serializedHeaderFields(value);
127
+ size +=
128
+ 3 + uint(fields.reduce((sum, [, entries]) => sum + entries.length, 0));
129
+ for (const [name, entries] of fields)
130
+ for (const entry of entries) {
131
+ size++;
132
+ if (!commonHeaders.has(name))
133
+ size += uint(name.length) + name.length;
134
+ rawString(entry);
135
+ }
136
+ return;
137
+ }
138
+ if (value instanceof Request) {
139
+ const s = structuredCloneRequestSnapshot(value);
140
+ size += 2;
141
+ rawString(s.url);
142
+ write({
143
+ method: s.method === "GET" ? undefined : s.method,
144
+ headers: s.headers,
145
+ body: undefined,
146
+ redirect: s.redirect === "manual" ? "manual" : undefined,
147
+ fetcher: undefined,
148
+ cf: s.cf,
149
+ cache: s.cache,
150
+ integrity: undefined,
151
+ signal: undefined,
152
+ encodeResponseBody: s.encodeResponseBody === "manual" ? "manual" : undefined,
153
+ });
154
+ return;
155
+ }
156
+ if (value instanceof Response) {
157
+ const s = structuredCloneResponseSnapshot(value);
158
+ size += 2;
159
+ write(null);
160
+ write({
161
+ status: s.status === 200 ? undefined : s.status,
162
+ statusText: s.serializedStatusText,
163
+ headers: s.headers,
164
+ cf: s.cf,
165
+ webSocket: undefined,
166
+ encodeBody: s.encodeBody === "manual" ? "manual" : undefined,
167
+ });
168
+ return;
169
+ }
170
+ if (value instanceof DOMException) {
171
+ size += 2;
172
+ rawString(value.name);
173
+ rawString(value.message);
174
+ rawString(typeof value.stack === "string" ? value.stack : "");
175
+ return;
176
+ }
177
+ if (value instanceof ArrayBuffer) {
178
+ const resizable = Object.getOwnPropertyDescriptor(ArrayBuffer.prototype, "resizable")?.get?.call(value);
179
+ const length = Object.getOwnPropertyDescriptor(ArrayBuffer.prototype, "byteLength").get.call(value);
180
+ size += 1 + uint(length) + length;
181
+ if (resizable)
182
+ size += uint(Object.getOwnPropertyDescriptor(ArrayBuffer.prototype, "maxByteLength").get.call(value));
183
+ return;
184
+ }
185
+ if (isSharedBuffer(value)) {
186
+ // The external backing-store table is not persisted with an attachment.
187
+ // Serialization itself is allowed; deserialization must reject separately.
188
+ if (externals)
189
+ externals.shared = true;
190
+ size += 1 + uint(sharedCount++);
191
+ if (wasmBuffers.has(value))
192
+ size += 1 + uint(value.byteLength);
193
+ return;
194
+ }
195
+ if (value instanceof Date) {
196
+ size += 9;
197
+ return;
198
+ }
199
+ if (value instanceof RegExp) {
200
+ size++;
201
+ string(Object.getOwnPropertyDescriptor(RegExp.prototype, "source").get.call(value));
202
+ let flags = 0;
203
+ for (const [flag, bit] of [
204
+ ["global", 1],
205
+ ["ignoreCase", 2],
206
+ ["multiline", 4],
207
+ ["sticky", 8],
208
+ ["unicode", 16],
209
+ ["dotAll", 32],
210
+ ["hasIndices", 128],
211
+ ["unicodeSets", 256],
212
+ ])
213
+ if (Object.getOwnPropertyDescriptor(RegExp.prototype, flag)?.get?.call(value))
214
+ flags |= bit;
215
+ size += uint(flags);
216
+ return;
217
+ }
218
+ if (value instanceof Number) {
219
+ size += 9;
220
+ return;
221
+ }
222
+ if (value instanceof Boolean) {
223
+ size++;
224
+ return;
225
+ }
226
+ if (value instanceof String) {
227
+ size++;
228
+ string(String.prototype.valueOf.call(value));
229
+ return;
230
+ }
231
+ try {
232
+ const unboxed = BigInt.prototype.valueOf.call(value);
233
+ bigint(unboxed);
234
+ return;
235
+ }
236
+ catch {
237
+ /* Not a boxed BigInt. */
238
+ }
239
+ if (value instanceof Map) {
240
+ size++;
241
+ let count = 0;
242
+ for (const [key, item] of Map.prototype.entries.call(value)) {
243
+ write(key);
244
+ write(item);
245
+ count += 2;
246
+ }
247
+ size += 1 + uint(count);
248
+ return;
249
+ }
250
+ if (value instanceof Set) {
251
+ size++;
252
+ let count = 0;
253
+ for (const item of Set.prototype.values.call(value)) {
254
+ write(item);
255
+ count++;
256
+ }
257
+ size += 1 + uint(count);
258
+ return;
259
+ }
260
+ if (value instanceof Error) {
261
+ // The profile enables workerd's enhanced error serialization, which
262
+ // includes non-enumerable own fields in a host payload (not V8's r tag).
263
+ size += 3;
264
+ if (![
265
+ "Error",
266
+ "TypeError",
267
+ "RangeError",
268
+ "ReferenceError",
269
+ "SyntaxError",
270
+ "CompileError",
271
+ "LinkError",
272
+ "RuntimeError",
273
+ "SuspendError",
274
+ "EvalError",
275
+ "URIError",
276
+ "AggregateError",
277
+ "SuppressedError",
278
+ ].includes(value.name))
279
+ write(value.name);
280
+ write(value.message);
281
+ const properties = {};
282
+ for (const key of Object.getOwnPropertyNames(value)) {
283
+ const index = Number(key);
284
+ if (key === "name" ||
285
+ key === "message" ||
286
+ (Number.isInteger(index) &&
287
+ index >= 0 &&
288
+ index < 0xffffffff &&
289
+ String(index) === key))
290
+ continue;
291
+ Object.defineProperty(properties, key, {
292
+ value: value[key],
293
+ enumerable: true,
294
+ });
295
+ }
296
+ write(properties);
297
+ return;
298
+ }
299
+ const keys = Object.keys(value);
300
+ if (Array.isArray(value)) {
301
+ // Choose dense encoding from observable own indices, never engine-private
302
+ // packed/holey storage. Sparse arrays retain holes without iterating them.
303
+ const indices = keys.filter((key) => String(Number(key)) === key &&
304
+ Number(key) >= 0 &&
305
+ Number(key) < value.length &&
306
+ Number.isInteger(Number(key)));
307
+ const indexKeys = new Set(indices);
308
+ const dense = indices.length === value.length;
309
+ size += 1 + uint(value.length);
310
+ let count = 0;
311
+ if (dense) {
312
+ for (let i = 0; i < value.length; i++)
313
+ write(value[i]);
314
+ for (const key of keys)
315
+ if (!indexKeys.has(key)) {
316
+ property(key, value[key]);
317
+ count++;
318
+ }
319
+ }
320
+ else {
321
+ for (const key of keys) {
322
+ property(key, value[key]);
323
+ count++;
324
+ }
325
+ }
326
+ size += 1 + uint(count) + uint(value.length);
327
+ return;
328
+ }
329
+ size++;
330
+ for (const key of keys)
331
+ property(key, value[key]);
332
+ size += 1 + uint(keys.length);
333
+ };
334
+ write(value);
335
+ return size;
336
+ }
@@ -0,0 +1,4 @@
1
+ export declare function markWebSocketPair(pair: object): void;
2
+ export declare function isWebSocketPair(value: unknown): boolean;
3
+ export declare function markWebSocket(socket: object): void;
4
+ export declare function isWebSocket(value: unknown): boolean;
@@ -0,0 +1,16 @@
1
+ // Kept separate from the transport so Response validation does not pull native
2
+ // TLS/Wasm into the document-navigation bridge's lightweight page script.
3
+ const sockets = new WeakSet();
4
+ const pairs = new WeakSet();
5
+ export function markWebSocketPair(pair) {
6
+ pairs.add(pair);
7
+ }
8
+ export function isWebSocketPair(value) {
9
+ return typeof value === "object" && value !== null && pairs.has(value);
10
+ }
11
+ export function markWebSocket(socket) {
12
+ sockets.add(socket);
13
+ }
14
+ export function isWebSocket(value) {
15
+ return typeof value === "object" && value !== null && sockets.has(value);
16
+ }
@@ -0,0 +1,7 @@
1
+ /** Workers exposes these fields as readonly own properties, not DOM getters. */
2
+ export declare class CloseEvent extends Event {
3
+ readonly wasClean: boolean;
4
+ readonly reason: string;
5
+ readonly code: number;
6
+ constructor(type: string, init?: CloseEventInit);
7
+ }
@@ -0,0 +1,30 @@
1
+ import { int32 } from "./conversion.js";
2
+ import { dictionary, webString } from "../body/index.js";
3
+ /** Workers exposes these fields as readonly own properties, not DOM getters. */
4
+ export class CloseEvent extends Event {
5
+ constructor(type, init = {}) {
6
+ if (!arguments.length)
7
+ throw new TypeError("Failed to construct 'CloseEvent': constructor parameter 1 is not of type 'string'.");
8
+ const name = webString(type);
9
+ const options = dictionary(init ?? {});
10
+ super(name, options);
11
+ const codeValue = options.code;
12
+ const code = codeValue === undefined ? 0 : int32(codeValue);
13
+ const reasonValue = options.reason;
14
+ const reason = reasonValue === undefined ? "" : webString(reasonValue);
15
+ const wasClean = Boolean(options.wasClean);
16
+ for (const [key, value] of Object.entries({ wasClean, reason, code }))
17
+ Object.defineProperty(this, key, {
18
+ value,
19
+ enumerable: true,
20
+ configurable: true,
21
+ writable: false,
22
+ });
23
+ }
24
+ }
25
+ Object.defineProperty(CloseEvent, "length", { value: 0 });
26
+ Object.defineProperty(CloseEvent, "name", { value: "CloseEvent" });
27
+ Object.defineProperty(CloseEvent.prototype, Symbol.toStringTag, {
28
+ value: "CloseEvent",
29
+ configurable: true,
30
+ });
@@ -0,0 +1,5 @@
1
+ export declare function negotiateCompression(header: string): {
2
+ encode: (bytes: Uint8Array) => Uint8Array<ArrayBufferLike>;
3
+ decode: (bytes: Uint8Array) => Uint8Array<ArrayBufferLike>;
4
+ dispose(): void;
5
+ };