@bytecodealliance/preview2-shim 0.14.2 → 0.15.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.
@@ -1,341 +0,0 @@
1
- /**
2
- * @typedef {import("../../../types/interfaces/wasi-sockets-network").Network} Network
3
- * @typedef {import("../../../types/interfaces/wasi-sockets-network").ErrorCode} ErrorCode
4
- * @typedef {import("../../../types/interfaces/wasi-sockets-network").IpAddressFamily} IpAddressFamily
5
- * @typedef {import("../../../types/interfaces/wasi-sockets-network").IpAddress} IpAddress
6
- * @typedef {import("../../../types/interfaces/wasi-sockets-tcp").TcpSocket} TcpSocket
7
- * @typedef {import("../../../types/interfaces/wasi-sockets-udp").UdpSocket} UdpSocket
8
- */
9
-
10
- import { isIP } from "net";
11
- import { assert } from "../../common/assert.js";
12
- import {
13
- SOCKET_RESOLVE_ADDRESS_CREATE_REQUEST,
14
- SOCKET_RESOLVE_ADDRESS_DISPOSE_REQUEST,
15
- SOCKET_RESOLVE_ADDRESS_GET_AND_DISPOSE_REQUEST,
16
- } from "../../io/calls.js";
17
- import { ioCall, pollableCreate } from "../../io/worker-io.js";
18
- import { deserializeIpAddress } from "./socket-common.js";
19
- import { TcpSocket, tcpSocketImplCreate } from "./tcp-socket-impl.js";
20
- import { IncomingDatagramStream, OutgoingDatagramStream, UdpSocket, udpSocketImplCreate } from "./udp-socket-impl.js";
21
-
22
- const symbolDispose = Symbol.dispose || Symbol.for("dispose");
23
-
24
- /** @type {ErrorCode} */
25
- export const errorCode = {
26
- // ### GENERAL ERRORS ###
27
-
28
- /// Unknown error
29
- unknown: "unknown",
30
-
31
- /// Access denied.
32
- ///
33
- /// POSIX equivalent: EACCES, EPERM
34
- accessDenied: "access-denied",
35
-
36
- /// The operation is not supported.
37
- ///
38
- /// POSIX equivalent: EOPNOTSUPP
39
- notSupported: "not-supported",
40
-
41
- /// One of the arguments is invalid.
42
- ///
43
- /// POSIX equivalent: EINVAL
44
- invalidArgument: "invalid-argument",
45
-
46
- /// Not enough memory to complete the operation.
47
- ///
48
- /// POSIX equivalent: ENOMEM, ENOBUFS, EAI_MEMORY
49
- outOfMemory: "out-of-memory",
50
-
51
- /// The operation timed out before it could finish completely.
52
- timeout: "timeout",
53
-
54
- /// This operation is incompatible with another asynchronous operation that is already in progress.
55
- ///
56
- /// POSIX equivalent: EALREADY
57
- concurrencyConflict: "concurrency-conflict",
58
-
59
- /// Trying to finish an asynchronous operation that:
60
- /// - has not been started yet, or:
61
- /// - was already finished by a previous `finish-*` call.
62
- ///
63
- /// Note: this is scheduled to be removed when `future`s are natively supported.
64
- notInProgress: "not-in-progress",
65
-
66
- /// The operation has been aborted because it could not be completed immediately.
67
- ///
68
- /// Note: this is scheduled to be removed when `future`s are natively supported.
69
- wouldBlock: "would-block",
70
-
71
- // ### TCP & UDP SOCKET ERRORS ###
72
-
73
- /// The operation is not valid in the socket's current state.
74
- invalidState: "invalid-state",
75
-
76
- /// A new socket resource could not be created because of a system limit.
77
- newSocketLimit: "new-socket-limit",
78
-
79
- /// A bind operation failed because the provided address is not an address that the `network` can bind to.
80
- addressNotBindable: "address-not-bindable",
81
-
82
- /// A bind operation failed because the provided address is already in use or because there are no ephemeral ports available.
83
- addressInUse: "address-in-use",
84
-
85
- /// The remote address is not reachable
86
- remoteUnreachable: "remote-unreachable",
87
-
88
- // ### TCP SOCKET ERRORS ###
89
-
90
- /// The connection was forcefully rejected
91
- connectionRefused: "connection-refused",
92
-
93
- /// The connection was reset.
94
- connectionReset: "connection-reset",
95
-
96
- /// A connection was aborted.
97
- connectionAborted: "connection-aborted",
98
-
99
- // ### UDP SOCKET ERRORS ###
100
- datagramTooLarge: "datagram-too-large",
101
-
102
- // ### NAME LOOKUP ERRORS ###
103
-
104
- /// Name does not exist or has no suitable associated IP addresses.
105
- nameUnresolvable: "name-unresolvable",
106
-
107
- /// A temporary failure in name resolution occurred.
108
- temporaryResolverFailure: "temporary-resolver-failure",
109
-
110
- /// A permanent failure in name resolution occurred.
111
- permanentResolverFailure: "permanent-resolver-failure",
112
- };
113
-
114
- /** @type {IpAddressFamily[]} */
115
- const supportedAddressFamilies = ["ipv4", "ipv6"];
116
-
117
- export const IpAddressFamily = {
118
- ipv4: "ipv4",
119
- ipv6: "ipv6",
120
- };
121
-
122
- export class WasiSockets {
123
- #allowDnsLookup = true;
124
- #allowTcp = true;
125
- #allowUdp = true;
126
- networkCnt = 1;
127
- socketCnt = 1;
128
-
129
- // TODO: figure out what the max number of sockets should be
130
- MAX_SOCKET_INSTANCES = 100;
131
-
132
- /** @type {Network} */ networkInstance = null;
133
- /** @type {Map<number,Network>} */ networks = new Map();
134
- /** @type {Map<number,TcpSocket} */ tcpSockets = new Map();
135
- /** @type {Map<number,UdpSocket} */ udpSockets = new Map();
136
-
137
- constructor() {
138
- const net = this;
139
-
140
- class Network {
141
- constructor() {
142
- this.id = net.networkCnt++;
143
- net.networks.set(this.id, this);
144
- }
145
- }
146
-
147
- this.udp = {
148
- UdpSocket,
149
- OutgoingDatagramStream,
150
- IncomingDatagramStream,
151
- };
152
-
153
- this.tcp = {
154
- TcpSocket,
155
- };
156
-
157
- this.instanceNetwork = {
158
- /**
159
- * @returns {Network}
160
- */
161
- instanceNetwork() {
162
- // TODO: should networkInstance be a singleton?
163
- if (!net.networkInstance) {
164
- net.networkInstance = new Network();
165
- }
166
- return net.networkInstance;
167
- },
168
- };
169
-
170
- this.network = {
171
- errorCode,
172
- IpAddressFamily,
173
- Network,
174
- };
175
-
176
- this.udpCreateSocket = {
177
- createUdpSocket(addressFamily) {
178
- assert(
179
- supportedAddressFamilies.includes(addressFamily) === false,
180
- errorCode.notSupported,
181
- "The specified `address-family` is not supported."
182
- );
183
-
184
- assert(
185
- net.socketCnt + 1 > net.MAX_SOCKET_INSTANCES,
186
- errorCode.newSocketLimit,
187
- "The new socket resource could not be created because of a system limit"
188
- );
189
-
190
- try {
191
- const id = net.socketCnt++;
192
- const udpSocket = udpSocketImplCreate(addressFamily, id);
193
- udpSocket.allowed = () => {
194
- return net.#allowUdp;
195
- };
196
- net.udpSockets.set(id, udpSocket);
197
- return udpSocket;
198
- } catch (err) {
199
- console.log("udp socket create error", {
200
- err,
201
- });
202
- assert(true, errorCode.notSupported, err);
203
- }
204
- },
205
- };
206
-
207
- this.tcpCreateSocket = {
208
- /**
209
- * @param {IpAddressFamily} addressFamily
210
- * @returns {TcpSocket}
211
- * @throws {not-supported} The specified `address-family` is not supported. (EAFNOSUPPORT)
212
- * @throws {new-socket-limit} The new socket resource could not be created because of a system limit. (EMFILE, ENFILE)
213
- */
214
- createTcpSocket(addressFamily) {
215
- assert(
216
- supportedAddressFamilies.includes(addressFamily) === false,
217
- errorCode.notSupported,
218
- "The specified `address-family` is not supported."
219
- );
220
-
221
- assert(
222
- net.socketCnt + 1 > net.MAX_SOCKET_INSTANCES,
223
- errorCode.newSocketLimit,
224
- "The new socket resource could not be created because of a system limit"
225
- );
226
-
227
- try {
228
- const id = net.socketCnt++;
229
- const tcpSocket = tcpSocketImplCreate(addressFamily, id);
230
- tcpSocket.allowed = () => {
231
- return net.#allowTcp;
232
- };
233
- net.tcpSockets.set(id, tcpSocket);
234
- return tcpSocket;
235
- } catch (err) {
236
- console.log("tcp socket create error", {
237
- err,
238
- });
239
- assert(true, errorCode.notSupported, err);
240
- }
241
- },
242
- };
243
-
244
- class ResolveAddressStream {
245
- #pollId;
246
- #data;
247
- #curItem = 0;
248
- #error;
249
- resolveNextAddress() {
250
- if (this.#error) throw this.#error;
251
- if (!this.#data) {
252
- const { value: addresses, error } = ioCall(SOCKET_RESOLVE_ADDRESS_GET_AND_DISPOSE_REQUEST, this.#pollId);
253
- if (error) throw (this.#error = convertResolveAddressError(error));
254
- this.#data = addresses.map((address) => {
255
- const family = `ipv${isIP(address)}`;
256
- return {
257
- tag: family,
258
- val: deserializeIpAddress(address, family),
259
- };
260
- });
261
- }
262
- if (this.#curItem < this.#data.length) return this.#data[this.#curItem++];
263
- return undefined;
264
- }
265
- subscribe() {
266
- if (this.#data) return pollableCreate(0);
267
- return pollableCreate(this.#pollId);
268
- }
269
- [symbolDispose]() {
270
- if (!this.#data) ioCall(SOCKET_RESOLVE_ADDRESS_DISPOSE_REQUEST);
271
- }
272
- static _create(hostname) {
273
- const res = new ResolveAddressStream();
274
- if (hostname === "0.0.0.0") {
275
- res.#pollId = 0;
276
- res.#data = { tag: "ipv4", val: [0, 0, 0, 0] };
277
- return res;
278
- } else if (hostname === "::") {
279
- res.#pollId = 0;
280
- res.#data = { tag: "ipv6", val: [0, 0, 0, 0, 0, 0, 0, 0] };
281
- return res;
282
- } else if (hostname === "::1") {
283
- res.#pollId = 0;
284
- res.#data = { tag: "ipv6", val: [0, 0, 0, 0, 0, 0, 0, 1] };
285
- return res;
286
- }
287
- res.#pollId = ioCall(SOCKET_RESOLVE_ADDRESS_CREATE_REQUEST, null, {
288
- hostname,
289
- });
290
- return res;
291
- }
292
- }
293
-
294
- const resolveAddressStreamCreate = ResolveAddressStream._create;
295
- delete ResolveAddressStream._create;
296
-
297
- this.ipNameLookup = {
298
- ResolveAddressStream,
299
-
300
- /**
301
- *
302
- * @param {Network} network
303
- * @param {string} name
304
- * @returns {ResolveAddressStream}
305
- * @throws {invalid-argument} `name` is a syntactically invalid domain name or IP address.
306
- */
307
- resolveAddresses(network, name) {
308
- if (!net.#allowDnsLookup)
309
- throw 'permanent-resolver-failure';
310
- // TODO: bind to network
311
- return resolveAddressStreamCreate(name);
312
- },
313
- };
314
- }
315
-
316
- static _denyDnsLookup (sockets) {
317
- sockets.#allowDnsLookup = false;
318
- }
319
- static _denyTcp (sockets) {
320
- sockets.#allowTcp = false;
321
- }
322
- static _denyUdp (sockets) {
323
- sockets.#allowUdp = false;
324
- }
325
- }
326
-
327
- export const denyDnsLookup = WasiSockets._denyDnsLookup;
328
- delete WasiSockets._denyDnsLookup;
329
-
330
- export const denyTcp = WasiSockets._denyTcp;
331
- delete WasiSockets._denyTcp;
332
-
333
- export const denyUdp = WasiSockets._denyUdp;
334
- delete WasiSockets._denyUdp;
335
-
336
- function convertResolveAddressError(err) {
337
- switch (err.code) {
338
- default:
339
- return "unknown";
340
- }
341
- }
@@ -1,71 +0,0 @@
1
- /*
2
- MIT License
3
-
4
- Copyright (c) 2021 UnTS
5
-
6
- Permission is hereby granted, free of charge, to any person obtaining a copy
7
- of this software and associated documentation files (the "Software"), to deal
8
- in the Software without restriction, including without limitation the rights
9
- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10
- copies of the Software, and to permit persons to whom the Software is
11
- furnished to do so, subject to the following conditions:
12
-
13
- The above copyright notice and this permission notice shall be included in all
14
- copies or substantial portions of the Software.
15
-
16
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22
- SOFTWARE.
23
- */
24
-
25
- /// <reference types="node" />
26
- import { MessagePort } from "node:worker_threads";
27
- export type AnyFn<R = any, T extends any[] = any[]> = (...args: T) => R;
28
- export type AnyPromise<T = any> = Promise<T>;
29
- export type AnyAsyncFn<T = any> = AnyFn<Promise<T>>;
30
- export type Syncify<T extends AnyAsyncFn> = T extends (
31
- ...args: infer Args
32
- ) => Promise<infer R>
33
- ? (...args: Args) => R
34
- : never;
35
- export type PromiseType<T extends AnyPromise> = T extends Promise<infer R>
36
- ? R
37
- : never;
38
- export interface MainToWorkerMessage<T extends unknown[]> {
39
- sharedBuffer: SharedArrayBuffer;
40
- id: number;
41
- args: T;
42
- }
43
- export interface WorkerData {
44
- workerPort: MessagePort;
45
- }
46
- export interface DataMessage<T> {
47
- result?: T;
48
- error?: unknown;
49
- properties?: unknown;
50
- }
51
- export interface WorkerToMainMessage<T = unknown> extends DataMessage<T> {
52
- id: number;
53
- }
54
- export interface SyncifyOptions {
55
- bufferSize?: number;
56
- timeout?: number;
57
- execArgv?: string[];
58
- }
59
- export declare function createSyncFn<T extends AnyAsyncFn>(
60
- workerPath: string,
61
- bufferSize?: number,
62
- timeout?: number
63
- ): Syncify<T>;
64
- export declare function createSyncFn<T extends AnyAsyncFn>(
65
- workerPath: string,
66
- options?: SyncifyOptions
67
- ): Syncify<T>;
68
- export declare function runAsWorker<
69
- R = unknown,
70
- T extends AnyAsyncFn<R> = AnyAsyncFn<R>
71
- >(fn: T): void;