@metamask/snaps-execution-environments 0.24.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 (83) hide show
  1. package/LICENSE +20 -0
  2. package/README.md +3 -0
  3. package/dist/common/BaseSnapExecutor.d.ts +68 -0
  4. package/dist/common/BaseSnapExecutor.js +324 -0
  5. package/dist/common/BaseSnapExecutor.js.map +1 -0
  6. package/dist/common/commands.d.ts +30 -0
  7. package/dist/common/commands.js +68 -0
  8. package/dist/common/commands.js.map +1 -0
  9. package/dist/common/endowments/crypto.d.ts +8 -0
  10. package/dist/common/endowments/crypto.js +25 -0
  11. package/dist/common/endowments/crypto.js.map +1 -0
  12. package/dist/common/endowments/index.d.ts +25 -0
  13. package/dist/common/endowments/index.js +122 -0
  14. package/dist/common/endowments/index.js.map +1 -0
  15. package/dist/common/endowments/interval.d.ts +9 -0
  16. package/dist/common/endowments/interval.js +47 -0
  17. package/dist/common/endowments/interval.js.map +1 -0
  18. package/dist/common/endowments/math.d.ts +60 -0
  19. package/dist/common/endowments/math.js +48 -0
  20. package/dist/common/endowments/math.js.map +1 -0
  21. package/dist/common/endowments/network.d.ts +48 -0
  22. package/dist/common/endowments/network.js +362 -0
  23. package/dist/common/endowments/network.js.map +1 -0
  24. package/dist/common/endowments/timeout.d.ts +9 -0
  25. package/dist/common/endowments/timeout.js +50 -0
  26. package/dist/common/endowments/timeout.js.map +1 -0
  27. package/dist/common/globalEvents.d.ts +19 -0
  28. package/dist/common/globalEvents.js +47 -0
  29. package/dist/common/globalEvents.js.map +1 -0
  30. package/dist/common/globalObject.d.ts +9 -0
  31. package/dist/common/globalObject.js +48 -0
  32. package/dist/common/globalObject.js.map +1 -0
  33. package/dist/common/keyring.d.ts +12 -0
  34. package/dist/common/keyring.js +42 -0
  35. package/dist/common/keyring.js.map +1 -0
  36. package/dist/common/lockdown/lockdown-more.d.ts +22 -0
  37. package/dist/common/lockdown/lockdown-more.js +88 -0
  38. package/dist/common/lockdown/lockdown-more.js.map +1 -0
  39. package/dist/common/lockdown/lockdown.d.ts +7 -0
  40. package/dist/common/lockdown/lockdown.js +28 -0
  41. package/dist/common/lockdown/lockdown.js.map +1 -0
  42. package/dist/common/sortParams.d.ts +16 -0
  43. package/dist/common/sortParams.js +32 -0
  44. package/dist/common/sortParams.js.map +1 -0
  45. package/dist/common/utils.d.ts +38 -0
  46. package/dist/common/utils.js +98 -0
  47. package/dist/common/utils.js.map +1 -0
  48. package/dist/common/validation.d.ts +100 -0
  49. package/dist/common/validation.js +110 -0
  50. package/dist/common/validation.js.map +1 -0
  51. package/dist/iframe/IFrameSnapExecutor.d.ts +11 -0
  52. package/dist/iframe/IFrameSnapExecutor.js +41 -0
  53. package/dist/iframe/IFrameSnapExecutor.js.map +1 -0
  54. package/dist/iframe/index.d.ts +1 -0
  55. package/dist/iframe/index.js +9 -0
  56. package/dist/iframe/index.js.map +1 -0
  57. package/dist/iframe-test/index.d.ts +1 -0
  58. package/dist/iframe-test/index.js +8 -0
  59. package/dist/iframe-test/index.js.map +1 -0
  60. package/dist/node-process/ChildProcessSnapExecutor.d.ts +4 -0
  61. package/dist/node-process/ChildProcessSnapExecutor.js +29 -0
  62. package/dist/node-process/ChildProcessSnapExecutor.js.map +1 -0
  63. package/dist/node-process/index.d.ts +1 -0
  64. package/dist/node-process/index.js +9 -0
  65. package/dist/node-process/index.js.map +1 -0
  66. package/dist/node-thread/ThreadSnapExecutor.d.ts +4 -0
  67. package/dist/node-thread/ThreadSnapExecutor.js +29 -0
  68. package/dist/node-thread/ThreadSnapExecutor.js.map +1 -0
  69. package/dist/node-thread/index.d.ts +1 -0
  70. package/dist/node-thread/index.js +9 -0
  71. package/dist/node-thread/index.js.map +1 -0
  72. package/dist/openrpc.json +210 -0
  73. package/dist/webpack/iframe/bundle.js +2 -0
  74. package/dist/webpack/iframe/bundle.js.LICENSE.txt +21 -0
  75. package/dist/webpack/iframe/index.html +10 -0
  76. package/dist/webpack/iframe/lockdown.umd.min.js +1 -0
  77. package/dist/webpack/node-process/bundle.js +1784 -0
  78. package/dist/webpack/node-process/bundle.js.LICENSE.txt +3 -0
  79. package/dist/webpack/node-process/lockdown.umd.min.js +1 -0
  80. package/dist/webpack/node-thread/bundle.js +1784 -0
  81. package/dist/webpack/node-thread/bundle.js.LICENSE.txt +3 -0
  82. package/dist/webpack/node-thread/lockdown.umd.min.js +1 -0
  83. package/package.json +88 -0
@@ -0,0 +1,362 @@
1
+ "use strict";
2
+ var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
3
+ if (kind === "m") throw new TypeError("Private method is not writable");
4
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
5
+ if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
6
+ return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
7
+ };
8
+ var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {
9
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
10
+ if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
11
+ return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
12
+ };
13
+ var _ResponseWrapper_ogResponse;
14
+ Object.defineProperty(exports, "__esModule", { value: true });
15
+ const utils_1 = require("../utils");
16
+ /**
17
+ * This class wraps a Response object.
18
+ * That way, a teardown process can stop any processes left.
19
+ */
20
+ class ResponseWrapper {
21
+ constructor(ogResponse, teardownRef) {
22
+ _ResponseWrapper_ogResponse.set(this, void 0);
23
+ __classPrivateFieldSet(this, _ResponseWrapper_ogResponse, ogResponse, "f");
24
+ this.teardownRef = teardownRef;
25
+ }
26
+ get body() {
27
+ return __classPrivateFieldGet(this, _ResponseWrapper_ogResponse, "f").body;
28
+ }
29
+ get bodyUsed() {
30
+ return __classPrivateFieldGet(this, _ResponseWrapper_ogResponse, "f").bodyUsed;
31
+ }
32
+ get headers() {
33
+ return __classPrivateFieldGet(this, _ResponseWrapper_ogResponse, "f").headers;
34
+ }
35
+ get ok() {
36
+ return __classPrivateFieldGet(this, _ResponseWrapper_ogResponse, "f").ok;
37
+ }
38
+ get redirected() {
39
+ return __classPrivateFieldGet(this, _ResponseWrapper_ogResponse, "f").redirected;
40
+ }
41
+ get status() {
42
+ return __classPrivateFieldGet(this, _ResponseWrapper_ogResponse, "f").status;
43
+ }
44
+ get statusText() {
45
+ return __classPrivateFieldGet(this, _ResponseWrapper_ogResponse, "f").statusText;
46
+ }
47
+ get type() {
48
+ return __classPrivateFieldGet(this, _ResponseWrapper_ogResponse, "f").type;
49
+ }
50
+ get url() {
51
+ return __classPrivateFieldGet(this, _ResponseWrapper_ogResponse, "f").url;
52
+ }
53
+ text() {
54
+ return (0, utils_1.withTeardown)(__classPrivateFieldGet(this, _ResponseWrapper_ogResponse, "f").text(), this);
55
+ }
56
+ arrayBuffer() {
57
+ return (0, utils_1.withTeardown)(__classPrivateFieldGet(this, _ResponseWrapper_ogResponse, "f").arrayBuffer(), this);
58
+ }
59
+ blob() {
60
+ return (0, utils_1.withTeardown)(__classPrivateFieldGet(this, _ResponseWrapper_ogResponse, "f").blob(), this);
61
+ }
62
+ clone() {
63
+ const newResponse = __classPrivateFieldGet(this, _ResponseWrapper_ogResponse, "f").clone();
64
+ return new ResponseWrapper(newResponse, this.teardownRef);
65
+ }
66
+ formData() {
67
+ return (0, utils_1.withTeardown)(__classPrivateFieldGet(this, _ResponseWrapper_ogResponse, "f").formData(), this);
68
+ }
69
+ json() {
70
+ return (0, utils_1.withTeardown)(__classPrivateFieldGet(this, _ResponseWrapper_ogResponse, "f").json(), this);
71
+ }
72
+ }
73
+ _ResponseWrapper_ogResponse = new WeakMap();
74
+ /**
75
+ * Create a network endowment, consisting of a `WebSocket` object and `fetch`
76
+ * function. This allows us to provide a teardown function, so that we can cancel
77
+ * any pending requests, connections, streams, etc. that may be open when a snap
78
+ * is terminated.
79
+ *
80
+ * This wraps the original implementations of `WebSocket` and `fetch`,
81
+ * to ensure that a bad actor cannot get access to the original objects, thus
82
+ * potentially preventing the network requests from being torn down.
83
+ *
84
+ * @returns An object containing a wrapped `WebSocket` class and `fetch`
85
+ * function, as well as a teardown function.
86
+ */
87
+ const createNetwork = () => {
88
+ var _instances, _teardownClose, _createWrapped, _socket, _isTornDown, _events, _onopenOriginal, _onmessageOriginal, _onerrorOriginal, _oncloseOriginal, _a;
89
+ // Open fetch calls or open body streams or open websockets
90
+ const openConnections = new Set();
91
+ // Track last teardown count
92
+ const teardownRef = { lastTeardown: 0 };
93
+ // Remove items from openConnections after they were garbage collected
94
+ const cleanup = new FinalizationRegistry(
95
+ /* istanbul ignore next: can't test garbage collection without modifying node parameters */
96
+ (callback) => callback());
97
+ const _fetch = async (input, init) => {
98
+ const abortController = new AbortController();
99
+ if ((init === null || init === void 0 ? void 0 : init.signal) !== null && (init === null || init === void 0 ? void 0 : init.signal) !== undefined) {
100
+ const originalSignal = init.signal;
101
+ // Merge abort controllers
102
+ originalSignal.addEventListener('abort', () => {
103
+ abortController.abort(originalSignal.reason);
104
+ }, { once: true });
105
+ }
106
+ let res;
107
+ let openFetchConnection;
108
+ try {
109
+ const fetchPromise = fetch(input, Object.assign(Object.assign({}, init), { signal: abortController.signal }));
110
+ openFetchConnection = {
111
+ cancel: async () => {
112
+ abortController.abort();
113
+ try {
114
+ await fetchPromise;
115
+ }
116
+ catch (_a) {
117
+ /* do nothing */
118
+ }
119
+ },
120
+ };
121
+ openConnections.add(openFetchConnection);
122
+ res = new ResponseWrapper(await (0, utils_1.withTeardown)(fetchPromise, teardownRef), teardownRef);
123
+ }
124
+ finally {
125
+ if (openFetchConnection !== undefined) {
126
+ openConnections.delete(openFetchConnection);
127
+ }
128
+ }
129
+ if (res.body !== null) {
130
+ const body = new WeakRef(res.body);
131
+ const openBodyConnection = {
132
+ cancel:
133
+ /* istanbul ignore next: see it.todo('can be torn down during body read') test */
134
+ async () => {
135
+ var _a;
136
+ try {
137
+ await ((_a = body.deref()) === null || _a === void 0 ? void 0 : _a.cancel());
138
+ }
139
+ catch (_b) {
140
+ /* do nothing */
141
+ }
142
+ },
143
+ };
144
+ openConnections.add(openBodyConnection);
145
+ cleanup.register(res.body,
146
+ /* istanbul ignore next: can't test garbage collection without modifying node parameters */
147
+ () => openConnections.delete(openBodyConnection));
148
+ }
149
+ return res;
150
+ };
151
+ /**
152
+ * This class wraps a WebSocket object instead of extending it.
153
+ * That way, a bad actor can't get access to original methods using
154
+ * `socket.prototype`.
155
+ *
156
+ * When modifying this class, ensure that no method calls any other method
157
+ * from the same class (#socket calls are fine). Otherwise, a bad actor could
158
+ * replace one of the implementations
159
+ */
160
+ const _WebSocket = (_a = class {
161
+ constructor(url, protocols) {
162
+ _instances.add(this);
163
+ _socket.set(this, void 0);
164
+ /**
165
+ * After this is set to true, no new event listeners can be added
166
+ */
167
+ _isTornDown.set(this, false);
168
+ _events.set(this, {});
169
+ _onopenOriginal.set(this, null);
170
+ _onmessageOriginal.set(this, null);
171
+ _onerrorOriginal.set(this, null);
172
+ _oncloseOriginal.set(this, null);
173
+ __classPrivateFieldSet(this, _socket, new WebSocket(url, protocols), "f");
174
+ // You can't call ref.deref()?.#teardownClose()
175
+ // But you can capture the close itself
176
+ const ref = new WeakRef(__classPrivateFieldGet(this, _instances, "m", _teardownClose).bind(this));
177
+ const openConnection = {
178
+ cancel: async () => {
179
+ var _a;
180
+ try {
181
+ await ((_a = ref.deref()) === null || _a === void 0 ? void 0 : _a());
182
+ }
183
+ catch (_b) {
184
+ /* do nothing */
185
+ }
186
+ },
187
+ };
188
+ openConnections.add(openConnection);
189
+ cleanup.register(this,
190
+ /* istanbul ignore next: can't test garbage collection without modifying node parameters */
191
+ () => openConnections.delete(openConnection));
192
+ }
193
+ get onclose() {
194
+ return __classPrivateFieldGet(this, _oncloseOriginal, "f");
195
+ }
196
+ set onclose(callback) {
197
+ if (__classPrivateFieldGet(this, _isTornDown, "f") !== true) {
198
+ __classPrivateFieldSet(this, _oncloseOriginal, callback, "f");
199
+ __classPrivateFieldGet(this, _socket, "f").onclose = __classPrivateFieldGet(this, _instances, "m", _createWrapped).call(this, callback);
200
+ }
201
+ }
202
+ get onerror() {
203
+ return __classPrivateFieldGet(this, _onerrorOriginal, "f");
204
+ }
205
+ set onerror(callback) {
206
+ __classPrivateFieldSet(this, _onerrorOriginal, callback, "f");
207
+ __classPrivateFieldGet(this, _socket, "f").onerror = __classPrivateFieldGet(this, _instances, "m", _createWrapped).call(this, callback);
208
+ }
209
+ get onmessage() {
210
+ return __classPrivateFieldGet(this, _onmessageOriginal, "f");
211
+ }
212
+ set onmessage(callback) {
213
+ __classPrivateFieldSet(this, _onmessageOriginal, callback, "f");
214
+ __classPrivateFieldGet(this, _socket, "f").onmessage = __classPrivateFieldGet(this, _instances, "m", _createWrapped).call(this, callback);
215
+ }
216
+ get onopen() {
217
+ return __classPrivateFieldGet(this, _onopenOriginal, "f");
218
+ }
219
+ set onopen(callback) {
220
+ __classPrivateFieldSet(this, _onopenOriginal, callback, "f");
221
+ __classPrivateFieldGet(this, _socket, "f").onopen = __classPrivateFieldGet(this, _instances, "m", _createWrapped).call(this, callback);
222
+ }
223
+ close(code, reason) {
224
+ __classPrivateFieldGet(this, _socket, "f").close(code, reason);
225
+ }
226
+ send(data) {
227
+ __classPrivateFieldGet(this, _socket, "f").send(data);
228
+ }
229
+ get CLOSED() {
230
+ return __classPrivateFieldGet(this, _socket, "f").CLOSED;
231
+ }
232
+ get CLOSING() {
233
+ return __classPrivateFieldGet(this, _socket, "f").CLOSING;
234
+ }
235
+ get CONNECTING() {
236
+ return __classPrivateFieldGet(this, _socket, "f").CONNECTING;
237
+ }
238
+ get OPEN() {
239
+ return __classPrivateFieldGet(this, _socket, "f").OPEN;
240
+ }
241
+ get binaryType() {
242
+ return __classPrivateFieldGet(this, _socket, "f").binaryType;
243
+ }
244
+ set binaryType(value) {
245
+ __classPrivateFieldGet(this, _socket, "f").binaryType = value;
246
+ }
247
+ get bufferedAmount() {
248
+ var _a;
249
+ return (_a = __classPrivateFieldGet(this, _socket, "f").bufferedAmount) !== null && _a !== void 0 ? _a : 0;
250
+ }
251
+ get extensions() {
252
+ var _a;
253
+ return (_a = __classPrivateFieldGet(this, _socket, "f").extensions) !== null && _a !== void 0 ? _a : '';
254
+ }
255
+ get protocol() {
256
+ return __classPrivateFieldGet(this, _socket, "f").protocol;
257
+ }
258
+ get readyState() {
259
+ return __classPrivateFieldGet(this, _socket, "f").readyState;
260
+ }
261
+ get url() {
262
+ return __classPrivateFieldGet(this, _socket, "f").url;
263
+ }
264
+ addEventListener(type, listener, options) {
265
+ if (__classPrivateFieldGet(this, _isTornDown, "f") !== true) {
266
+ if (__classPrivateFieldGet(this, _events, "f")[type] === undefined) {
267
+ __classPrivateFieldGet(this, _events, "f")[type] = new Map();
268
+ }
269
+ const wrapped = __classPrivateFieldGet(this, _instances, "m", _createWrapped).call(this, listener);
270
+ if (wrapped !== null) {
271
+ __classPrivateFieldGet(this, _events, "f")[type].set(listener, wrapped);
272
+ __classPrivateFieldGet(this, _socket, "f").addEventListener(type, wrapped, options);
273
+ }
274
+ }
275
+ }
276
+ removeEventListener(type, listener, options) {
277
+ if (__classPrivateFieldGet(this, _events, "f")[type] !== undefined) {
278
+ const wrapped = __classPrivateFieldGet(this, _events, "f")[type].get(listener);
279
+ if (wrapped !== undefined) {
280
+ __classPrivateFieldGet(this, _events, "f")[type].delete(listener);
281
+ __classPrivateFieldGet(this, _socket, "f").removeEventListener(type, wrapped, options);
282
+ }
283
+ }
284
+ }
285
+ dispatchEvent(event) {
286
+ // Can't call close prematurely before the teardown finishes
287
+ if (event.type !== 'close' || __classPrivateFieldGet(this, _isTornDown, "f") !== true) {
288
+ return __classPrivateFieldGet(this, _socket, "f").dispatchEvent(event);
289
+ }
290
+ return false;
291
+ }
292
+ },
293
+ _socket = new WeakMap(),
294
+ _isTornDown = new WeakMap(),
295
+ _events = new WeakMap(),
296
+ _onopenOriginal = new WeakMap(),
297
+ _onmessageOriginal = new WeakMap(),
298
+ _onerrorOriginal = new WeakMap(),
299
+ _oncloseOriginal = new WeakMap(),
300
+ _instances = new WeakSet(),
301
+ _teardownClose = function _teardownClose() {
302
+ var _a, _b, _c;
303
+ // We clear all close listeners
304
+ __classPrivateFieldGet(this, _socket, "f").onclose = null;
305
+ for (const wrapped of (_b = (_a = __classPrivateFieldGet(this, _events, "f").close) === null || _a === void 0 ? void 0 : _a.values()) !== null && _b !== void 0 ? _b : []) {
306
+ __classPrivateFieldGet(this, _socket, "f").removeEventListener('close', wrapped);
307
+ }
308
+ (_c = __classPrivateFieldGet(this, _events, "f").close) === null || _c === void 0 ? void 0 : _c.clear();
309
+ // We add our own listener
310
+ let onClosedResolve;
311
+ const onClosed = new Promise((r) => (onClosedResolve = r));
312
+ __classPrivateFieldGet(this, _socket, "f").onclose = () => {
313
+ onClosedResolve();
314
+ };
315
+ // No new listeners can be added after this point
316
+ __classPrivateFieldSet(this, _isTornDown, true, "f");
317
+ __classPrivateFieldGet(this, _socket, "f").close();
318
+ return onClosed;
319
+ },
320
+ _createWrapped = function _createWrapped(listener) {
321
+ if (listener === null) {
322
+ return null;
323
+ }
324
+ return (e) => {
325
+ // TODO: Should we migrate this to use a wrapper class?
326
+ const properties = [...(0, utils_1.allProperties)(e)]
327
+ .filter(([_, key]) => key !== 'constructor')
328
+ .reduce((acc, [obj, key]) => {
329
+ const stringKey = key.toString();
330
+ const descriptor = Reflect.getOwnPropertyDescriptor(obj, key);
331
+ if (typeof (descriptor === null || descriptor === void 0 ? void 0 : descriptor.value) === 'function') {
332
+ acc[stringKey] = e[stringKey].bind(this);
333
+ }
334
+ else {
335
+ acc[stringKey] = e[stringKey];
336
+ }
337
+ return acc;
338
+ }, {});
339
+ const event = Object.assign(Object.assign({}, properties), { target: this, currentTarget: this, srcElement: this, ports: [this], source: null, composedPath: () => [this] });
340
+ listener.apply(this, [event]);
341
+ };
342
+ },
343
+ _a);
344
+ const teardownFunction = async () => {
345
+ teardownRef.lastTeardown += 1;
346
+ const promises = [];
347
+ openConnections.forEach(({ cancel }) => promises.push(cancel()));
348
+ openConnections.clear();
349
+ await Promise.all(promises);
350
+ };
351
+ return {
352
+ fetch: _fetch,
353
+ WebSocket: _WebSocket,
354
+ teardownFunction,
355
+ };
356
+ };
357
+ const endowmentModule = {
358
+ names: ['fetch', 'WebSocket'],
359
+ factory: createNetwork,
360
+ };
361
+ exports.default = endowmentModule;
362
+ //# sourceMappingURL=network.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"network.js","sourceRoot":"","sources":["../../../src/common/endowments/network.ts"],"names":[],"mappings":";;;;;;;;;;;;;;AAAA,oCAAuD;AAIvD;;;GAGG;AACH,MAAM,eAAe;IAKnB,YAAY,UAAoB,EAAE,WAAqC;QAFvE,8CAAsB;QAGpB,uBAAA,IAAI,+BAAe,UAAU,MAAA,CAAC;QAC9B,IAAI,CAAC,WAAW,GAAG,WAAW,CAAC;IACjC,CAAC;IAED,IAAI,IAAI;QACN,OAAO,uBAAA,IAAI,mCAAY,CAAC,IAAI,CAAC;IAC/B,CAAC;IAED,IAAI,QAAQ;QACV,OAAO,uBAAA,IAAI,mCAAY,CAAC,QAAQ,CAAC;IACnC,CAAC;IAED,IAAI,OAAO;QACT,OAAO,uBAAA,IAAI,mCAAY,CAAC,OAAO,CAAC;IAClC,CAAC;IAED,IAAI,EAAE;QACJ,OAAO,uBAAA,IAAI,mCAAY,CAAC,EAAE,CAAC;IAC7B,CAAC;IAED,IAAI,UAAU;QACZ,OAAO,uBAAA,IAAI,mCAAY,CAAC,UAAU,CAAC;IACrC,CAAC;IAED,IAAI,MAAM;QACR,OAAO,uBAAA,IAAI,mCAAY,CAAC,MAAM,CAAC;IACjC,CAAC;IAED,IAAI,UAAU;QACZ,OAAO,uBAAA,IAAI,mCAAY,CAAC,UAAU,CAAC;IACrC,CAAC;IAED,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EAAE,UAAU;QACrB,gBAAgB;KACjB,CAAC;AACJ,CAAC,CAAC;AAEF,MAAM,eAAe,GAAG;IACtB,KAAK,EAAE,CAAC,OAAO,EAAE,WAAW,CAAU;IACtC,OAAO,EAAE,aAAa;CACvB,CAAC;AACF,kBAAe,eAAe,CAAC","sourcesContent":["import { allProperties, withTeardown } from '../utils';\n\ntype WebSocketCallback = (this: WebSocket, ev: any) => any;\n\n/**\n * This class wraps a Response object.\n * That way, a teardown process can stop any processes left.\n */\nclass ResponseWrapper implements Response {\n private readonly teardownRef: { lastTeardown: number };\n\n #ogResponse: Response;\n\n constructor(ogResponse: Response, teardownRef: { lastTeardown: number }) {\n this.#ogResponse = ogResponse;\n this.teardownRef = teardownRef;\n }\n\n get body(): ReadableStream<Uint8Array> | null {\n return this.#ogResponse.body;\n }\n\n get bodyUsed() {\n return this.#ogResponse.bodyUsed;\n }\n\n get headers() {\n return this.#ogResponse.headers;\n }\n\n get ok() {\n return this.#ogResponse.ok;\n }\n\n get redirected() {\n return this.#ogResponse.redirected;\n }\n\n get status() {\n return this.#ogResponse.status;\n }\n\n get statusText() {\n return this.#ogResponse.statusText;\n }\n\n get type() {\n return this.#ogResponse.type;\n }\n\n get url() {\n return this.#ogResponse.url;\n }\n\n text() {\n return withTeardown<string>(this.#ogResponse.text(), this as any);\n }\n\n arrayBuffer(): Promise<ArrayBuffer> {\n return withTeardown<ArrayBuffer>(\n this.#ogResponse.arrayBuffer(),\n this as any,\n );\n }\n\n blob(): Promise<Blob> {\n return withTeardown<Blob>(this.#ogResponse.blob(), this as any);\n }\n\n clone(): Response {\n const newResponse = this.#ogResponse.clone();\n return new ResponseWrapper(newResponse, this.teardownRef);\n }\n\n formData(): Promise<FormData> {\n return withTeardown<FormData>(this.#ogResponse.formData(), this as any);\n }\n\n json(): Promise<any> {\n return withTeardown(this.#ogResponse.json(), this as any);\n }\n}\n\n/**\n * Create a network endowment, consisting of a `WebSocket` object and `fetch`\n * function. This allows us to provide a teardown function, so that we can cancel\n * any pending requests, connections, streams, etc. that may be open when a snap\n * is terminated.\n *\n * This wraps the original implementations of `WebSocket` and `fetch`,\n * to ensure that a bad actor cannot get access to the original objects, thus\n * potentially preventing the network requests from being torn down.\n *\n * @returns An object containing a wrapped `WebSocket` class and `fetch`\n * function, as well as a teardown function.\n */\nconst createNetwork = () => {\n // Open fetch calls or open body streams or open websockets\n const openConnections = new Set<{ cancel: () => Promise<void> }>();\n // Track last teardown count\n const teardownRef = { lastTeardown: 0 };\n\n // Remove items from openConnections after they were garbage collected\n const cleanup = new FinalizationRegistry<() => void>(\n /* istanbul ignore next: can't test garbage collection without modifying node parameters */\n (callback) => callback(),\n );\n\n const _fetch: typeof fetch = async (\n input: RequestInfo,\n init?: RequestInit,\n ): Promise<Response> => {\n const abortController = new AbortController();\n if (init?.signal !== null && init?.signal !== undefined) {\n const originalSignal = init.signal;\n // Merge abort controllers\n originalSignal.addEventListener(\n 'abort',\n () => {\n abortController.abort((originalSignal as any).reason);\n },\n { once: true },\n );\n }\n\n let res: Response;\n let openFetchConnection: { cancel: () => Promise<void> } | undefined;\n try {\n const fetchPromise = fetch(input, {\n ...init,\n signal: abortController.signal,\n });\n\n openFetchConnection = {\n cancel: async () => {\n abortController.abort();\n try {\n await fetchPromise;\n } catch {\n /* do nothing */\n }\n },\n };\n openConnections.add(openFetchConnection);\n\n res = new ResponseWrapper(\n await withTeardown(fetchPromise, teardownRef),\n teardownRef,\n );\n } finally {\n if (openFetchConnection !== undefined) {\n openConnections.delete(openFetchConnection);\n }\n }\n\n if (res.body !== null) {\n const body = new WeakRef<ReadableStream>(res.body);\n\n const openBodyConnection = {\n cancel:\n /* istanbul ignore next: see it.todo('can be torn down during body read') test */\n async () => {\n try {\n await body.deref()?.cancel();\n } catch {\n /* do nothing */\n }\n },\n };\n openConnections.add(openBodyConnection);\n cleanup.register(\n res.body,\n /* istanbul ignore next: can't test garbage collection without modifying node parameters */\n () => openConnections.delete(openBodyConnection),\n );\n }\n return res;\n };\n\n /**\n * This class wraps a WebSocket object instead of extending it.\n * That way, a bad actor can't get access to original methods using\n * `socket.prototype`.\n *\n * When modifying this class, ensure that no method calls any other method\n * from the same class (#socket calls are fine). Otherwise, a bad actor could\n * replace one of the implementations\n */\n const _WebSocket = class implements WebSocket {\n constructor(url: string | URL, protocols?: string | string[]) {\n this.#socket = new WebSocket(url, protocols);\n\n // You can't call ref.deref()?.#teardownClose()\n // But you can capture the close itself\n const ref = new WeakRef(this.#teardownClose.bind(this));\n const openConnection = {\n cancel: async () => {\n try {\n await ref.deref()?.();\n } catch {\n /* do nothing */\n }\n },\n };\n openConnections.add(openConnection);\n cleanup.register(\n this,\n /* istanbul ignore next: can't test garbage collection without modifying node parameters */\n () => openConnections.delete(openConnection),\n );\n }\n\n get onclose(): WebSocketCallback | null {\n return this.#oncloseOriginal;\n }\n\n set onclose(callback: WebSocketCallback | null) {\n if (this.#isTornDown !== true) {\n this.#oncloseOriginal = callback;\n this.#socket.onclose = this.#createWrapped(callback);\n }\n }\n\n get onerror(): ((this: WebSocket, ev: Event) => any) | null {\n return this.#onerrorOriginal;\n }\n\n set onerror(callback: ((this: WebSocket, ev: Event) => any) | null) {\n this.#onerrorOriginal = callback;\n this.#socket.onerror = this.#createWrapped(callback);\n }\n\n get onmessage(): ((this: WebSocket, ev: MessageEvent<any>) => any) | null {\n return this.#onmessageOriginal;\n }\n\n set onmessage(\n callback: ((this: WebSocket, ev: MessageEvent<any>) => any) | null,\n ) {\n this.#onmessageOriginal = callback;\n this.#socket.onmessage = this.#createWrapped(callback);\n }\n\n get onopen(): ((this: WebSocket, ev: Event) => any) | null {\n return this.#onopenOriginal;\n }\n\n set onopen(callback: ((this: WebSocket, ev: Event) => any) | null) {\n this.#onopenOriginal = callback;\n this.#socket.onopen = this.#createWrapped(callback);\n }\n\n close(code?: number, reason?: string): void {\n this.#socket.close(code, reason);\n }\n\n send(data: string | Blob | ArrayBufferView | ArrayBufferLike): void {\n this.#socket.send(data);\n }\n\n get CLOSED(): number {\n return this.#socket.CLOSED;\n }\n\n get CLOSING(): number {\n return this.#socket.CLOSING;\n }\n\n get CONNECTING(): number {\n return this.#socket.CONNECTING;\n }\n\n get OPEN(): number {\n return this.#socket.OPEN;\n }\n\n get binaryType(): BinaryType {\n return this.#socket.binaryType;\n }\n\n set binaryType(value: BinaryType) {\n this.#socket.binaryType = value;\n }\n\n get bufferedAmount(): number {\n return this.#socket.bufferedAmount ?? 0;\n }\n\n get extensions(): string {\n return this.#socket.extensions ?? '';\n }\n\n get protocol(): string {\n return this.#socket.protocol;\n }\n\n get readyState(): number {\n return this.#socket.readyState;\n }\n\n get url(): string {\n return this.#socket.url;\n }\n\n addEventListener<K extends keyof WebSocketEventMap>(\n type: K,\n listener: (this: WebSocket, ev: WebSocketEventMap[K]) => any,\n options?: boolean | AddEventListenerOptions,\n ): void;\n\n addEventListener(\n type: string,\n listener: EventListenerOrEventListenerObject,\n options?: boolean | AddEventListenerOptions,\n ): void;\n\n addEventListener(type: any, listener: any, options?: any): void {\n if (this.#isTornDown !== true) {\n if (this.#events[type] === undefined) {\n this.#events[type] = new Map();\n }\n const wrapped = this.#createWrapped(listener);\n if (wrapped !== null) {\n this.#events[type].set(listener, wrapped);\n this.#socket.addEventListener(type, wrapped, options);\n }\n }\n }\n\n removeEventListener<K extends keyof WebSocketEventMap>(\n type: K,\n listener: (this: WebSocket, ev: WebSocketEventMap[K]) => any,\n options?: boolean | EventListenerOptions,\n ): void;\n\n removeEventListener(\n type: string,\n listener: EventListenerOrEventListenerObject,\n options?: boolean | EventListenerOptions,\n ): void;\n\n removeEventListener(type: any, listener: any, options?: any): void {\n if (this.#events[type] !== undefined) {\n const wrapped = this.#events[type].get(listener);\n if (wrapped !== undefined) {\n this.#events[type].delete(listener);\n this.#socket.removeEventListener(type as any, wrapped, options);\n }\n }\n }\n\n dispatchEvent(event: Event): boolean {\n // Can't call close prematurely before the teardown finishes\n if (event.type !== 'close' || this.#isTornDown !== true) {\n return this.#socket.dispatchEvent(event);\n }\n return false;\n }\n\n #teardownClose() {\n // We clear all close listeners\n this.#socket.onclose = null;\n for (const wrapped of this.#events.close?.values() ?? []) {\n this.#socket.removeEventListener('close', wrapped);\n }\n this.#events.close?.clear();\n\n // We add our own listener\n let onClosedResolve: any;\n const onClosed = new Promise<void>((r) => (onClosedResolve = r));\n this.#socket.onclose = () => {\n onClosedResolve();\n };\n\n // No new listeners can be added after this point\n this.#isTornDown = true;\n\n this.#socket.close();\n\n return onClosed;\n }\n\n #createWrapped(listener: WebSocketCallback): WebSocketCallback;\n\n #createWrapped(listener: null): null;\n\n #createWrapped(\n listener: WebSocketCallback | null,\n ): WebSocketCallback | null;\n\n #createWrapped(\n listener: WebSocketCallback | null,\n ): WebSocketCallback | null {\n if (listener === null) {\n return null;\n }\n\n return (e) => {\n // TODO: Should we migrate this to use a wrapper class?\n const properties = [...allProperties(e)]\n .filter(([_, key]) => key !== 'constructor')\n .reduce<Record<string, any>>((acc, [obj, key]) => {\n const stringKey = key.toString();\n const descriptor = Reflect.getOwnPropertyDescriptor(obj, key);\n if (typeof descriptor?.value === 'function') {\n acc[stringKey] = e[stringKey].bind(this);\n } else {\n acc[stringKey] = e[stringKey];\n }\n return acc;\n }, {});\n const event = {\n ...properties,\n target: this,\n currentTarget: this,\n srcElement: this,\n ports: [this],\n source: null,\n composedPath: () => [this],\n };\n listener.apply(this, [event]);\n };\n }\n\n #socket: WebSocket;\n\n /**\n * After this is set to true, no new event listeners can be added\n */\n #isTornDown = false;\n\n #events: Record<string, Map<WebSocketCallback, WebSocketCallback>> = {};\n\n #onopenOriginal: WebSocketCallback | null = null;\n\n #onmessageOriginal: WebSocketCallback | null = null;\n\n #onerrorOriginal: WebSocketCallback | null = null;\n\n #oncloseOriginal: WebSocketCallback | null = null;\n };\n\n const teardownFunction = async () => {\n teardownRef.lastTeardown += 1;\n const promises: Promise<void>[] = [];\n openConnections.forEach(({ cancel }) => promises.push(cancel()));\n openConnections.clear();\n await Promise.all(promises);\n };\n\n return {\n fetch: _fetch,\n WebSocket: _WebSocket,\n teardownFunction,\n };\n};\n\nconst endowmentModule = {\n names: ['fetch', 'WebSocket'] as const,\n factory: createNetwork,\n};\nexport default endowmentModule;\n"]}
@@ -0,0 +1,9 @@
1
+ declare const endowmentModule: {
2
+ names: readonly ["setTimeout", "clearTimeout"];
3
+ factory: () => {
4
+ readonly setTimeout: (handler: TimerHandler, timeout?: number | undefined) => unknown;
5
+ readonly clearTimeout: (handle: unknown) => void;
6
+ readonly teardownFunction: () => void;
7
+ };
8
+ };
9
+ export default endowmentModule;
@@ -0,0 +1,50 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ /**
4
+ * Creates a pair of `setTimeout` and `clearTimeout` functions attenuated such
5
+ * that:
6
+ * - `setTimeout` throws if its "handler" parameter is not a function.
7
+ * - `clearTimeout` only clears timeouts created by its sibling `setTimeout`,
8
+ * or else no-ops.
9
+ *
10
+ * @returns An object with the attenuated `setTimeout` and `clearTimeout`
11
+ * functions.
12
+ */
13
+ const createTimeout = () => {
14
+ const registeredHandles = new Map();
15
+ const _setTimeout = (handler, timeout) => {
16
+ if (typeof handler !== 'function') {
17
+ throw new Error(`The timeout handler must be a function. Received: ${typeof handler}`);
18
+ }
19
+ const handle = Object.freeze({});
20
+ const platformHandle = setTimeout(() => {
21
+ registeredHandles.delete(handle);
22
+ handler();
23
+ }, timeout);
24
+ registeredHandles.set(handle, platformHandle);
25
+ return handle;
26
+ };
27
+ const _clearTimeout = (handle) => {
28
+ const platformHandle = registeredHandles.get(handle);
29
+ if (platformHandle !== undefined) {
30
+ clearTimeout(platformHandle);
31
+ registeredHandles.delete(handle);
32
+ }
33
+ };
34
+ const teardownFunction = () => {
35
+ for (const handle of registeredHandles.keys()) {
36
+ _clearTimeout(handle);
37
+ }
38
+ };
39
+ return {
40
+ setTimeout: _setTimeout,
41
+ clearTimeout: _clearTimeout,
42
+ teardownFunction,
43
+ };
44
+ };
45
+ const endowmentModule = {
46
+ names: ['setTimeout', 'clearTimeout'],
47
+ factory: createTimeout,
48
+ };
49
+ exports.default = endowmentModule;
50
+ //# sourceMappingURL=timeout.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"timeout.js","sourceRoot":"","sources":["../../../src/common/endowments/timeout.ts"],"names":[],"mappings":";;AAAA;;;;;;;;;GASG;AACH,MAAM,aAAa,GAAG,GAAG,EAAE;IACzB,MAAM,iBAAiB,GAAG,IAAI,GAAG,EAAoB,CAAC;IAEtD,MAAM,WAAW,GAAG,CAAC,OAAqB,EAAE,OAAgB,EAAW,EAAE;QACvE,IAAI,OAAO,OAAO,KAAK,UAAU,EAAE;YACjC,MAAM,IAAI,KAAK,CACb,qDAAqD,OAAO,OAAO,EAAE,CACtE,CAAC;SACH;QAED,MAAM,MAAM,GAAG,MAAM,CAAC,MAAM,CAAC,EAAE,CAAC,CAAC;QACjC,MAAM,cAAc,GAAG,UAAU,CAAC,GAAG,EAAE;YACrC,iBAAiB,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC;YACjC,OAAO,EAAE,CAAC;QACZ,CAAC,EAAE,OAAO,CAAC,CAAC;QAEZ,iBAAiB,CAAC,GAAG,CAAC,MAAM,EAAE,cAAc,CAAC,CAAC;QAC9C,OAAO,MAAM,CAAC;IAChB,CAAC,CAAC;IAEF,MAAM,aAAa,GAAG,CAAC,MAAe,EAAQ,EAAE;QAC9C,MAAM,cAAc,GAAG,iBAAiB,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC;QACrD,IAAI,cAAc,KAAK,SAAS,EAAE;YAChC,YAAY,CAAC,cAAqB,CAAC,CAAC;YACpC,iBAAiB,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC;SAClC;IACH,CAAC,CAAC;IAEF,MAAM,gBAAgB,GAAG,GAAS,EAAE;QAClC,KAAK,MAAM,MAAM,IAAI,iBAAiB,CAAC,IAAI,EAAE,EAAE;YAC7C,aAAa,CAAC,MAAM,CAAC,CAAC;SACvB;IACH,CAAC,CAAC;IAEF,OAAO;QACL,UAAU,EAAE,WAAW;QACvB,YAAY,EAAE,aAAa;QAC3B,gBAAgB;KACR,CAAC;AACb,CAAC,CAAC;AAEF,MAAM,eAAe,GAAG;IACtB,KAAK,EAAE,CAAC,YAAY,EAAE,cAAc,CAAU;IAC9C,OAAO,EAAE,aAAa;CACvB,CAAC;AACF,kBAAe,eAAe,CAAC","sourcesContent":["/**\n * Creates a pair of `setTimeout` and `clearTimeout` functions attenuated such\n * that:\n * - `setTimeout` throws if its \"handler\" parameter is not a function.\n * - `clearTimeout` only clears timeouts created by its sibling `setTimeout`,\n * or else no-ops.\n *\n * @returns An object with the attenuated `setTimeout` and `clearTimeout`\n * functions.\n */\nconst createTimeout = () => {\n const registeredHandles = new Map<unknown, unknown>();\n\n const _setTimeout = (handler: TimerHandler, timeout?: number): unknown => {\n if (typeof handler !== 'function') {\n throw new Error(\n `The timeout handler must be a function. Received: ${typeof handler}`,\n );\n }\n\n const handle = Object.freeze({});\n const platformHandle = setTimeout(() => {\n registeredHandles.delete(handle);\n handler();\n }, timeout);\n\n registeredHandles.set(handle, platformHandle);\n return handle;\n };\n\n const _clearTimeout = (handle: unknown): void => {\n const platformHandle = registeredHandles.get(handle);\n if (platformHandle !== undefined) {\n clearTimeout(platformHandle as any);\n registeredHandles.delete(handle);\n }\n };\n\n const teardownFunction = (): void => {\n for (const handle of registeredHandles.keys()) {\n _clearTimeout(handle);\n }\n };\n\n return {\n setTimeout: _setTimeout,\n clearTimeout: _clearTimeout,\n teardownFunction,\n } as const;\n};\n\nconst endowmentModule = {\n names: ['setTimeout', 'clearTimeout'] as const,\n factory: createTimeout,\n};\nexport default endowmentModule;\n"]}
@@ -0,0 +1,19 @@
1
+ /// <reference types="node" />
2
+ /**
3
+ * Adds an event listener platform agnostically, trying both `globalThis.addEventListener` and `globalThis.process.on`
4
+ *
5
+ * @param event - The event to listen for.
6
+ * @param listener - The listener to be triggered when the event occurs.
7
+ * @returns The result of the platform agnostic operation if any.
8
+ * @throws If none of the platform options are present.
9
+ */
10
+ export declare function addEventListener(event: string, listener: (...args: any[]) => void): void | NodeJS.Process;
11
+ /**
12
+ * Removes an event listener platform agnostically, trying both `globalThis.removeEventListener` and `globalThis.process.removeListener`
13
+ *
14
+ * @param event - The event to remove the listener for.
15
+ * @param listener - The currently attached listener.
16
+ * @returns The result of the platform agnostic operation if any.
17
+ * @throws If none of the platform options are present.
18
+ */
19
+ export declare function removeEventListener(event: string, listener: (...args: any[]) => void): void | NodeJS.Process;
@@ -0,0 +1,47 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.removeEventListener = exports.addEventListener = void 0;
4
+ const globalObject_1 = require("./globalObject");
5
+ /**
6
+ * Adds an event listener platform agnostically, trying both `globalThis.addEventListener` and `globalThis.process.on`
7
+ *
8
+ * @param event - The event to listen for.
9
+ * @param listener - The listener to be triggered when the event occurs.
10
+ * @returns The result of the platform agnostic operation if any.
11
+ * @throws If none of the platform options are present.
12
+ */
13
+ function addEventListener(event, listener) {
14
+ if ('addEventListener' in globalObject_1.rootRealmGlobal &&
15
+ typeof globalObject_1.rootRealmGlobal.addEventListener === 'function') {
16
+ return globalObject_1.rootRealmGlobal.addEventListener(event.toLowerCase(), listener);
17
+ }
18
+ if (globalObject_1.rootRealmGlobal.process &&
19
+ 'on' in globalObject_1.rootRealmGlobal.process &&
20
+ typeof globalObject_1.rootRealmGlobal.process.on === 'function') {
21
+ return globalObject_1.rootRealmGlobal.process.on(event, listener);
22
+ }
23
+ throw new Error('Platform agnostic addEventListener failed');
24
+ }
25
+ exports.addEventListener = addEventListener;
26
+ /**
27
+ * Removes an event listener platform agnostically, trying both `globalThis.removeEventListener` and `globalThis.process.removeListener`
28
+ *
29
+ * @param event - The event to remove the listener for.
30
+ * @param listener - The currently attached listener.
31
+ * @returns The result of the platform agnostic operation if any.
32
+ * @throws If none of the platform options are present.
33
+ */
34
+ function removeEventListener(event, listener) {
35
+ if ('removeEventListener' in globalObject_1.rootRealmGlobal &&
36
+ typeof globalObject_1.rootRealmGlobal.removeEventListener === 'function') {
37
+ return globalObject_1.rootRealmGlobal.removeEventListener(event.toLowerCase(), listener);
38
+ }
39
+ if (globalObject_1.rootRealmGlobal.process &&
40
+ 'removeListener' in globalObject_1.rootRealmGlobal.process &&
41
+ typeof globalObject_1.rootRealmGlobal.process.removeListener === 'function') {
42
+ return globalObject_1.rootRealmGlobal.process.removeListener(event, listener);
43
+ }
44
+ throw new Error('Platform agnostic removeEventListener failed');
45
+ }
46
+ exports.removeEventListener = removeEventListener;
47
+ //# sourceMappingURL=globalEvents.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"globalEvents.js","sourceRoot":"","sources":["../../src/common/globalEvents.ts"],"names":[],"mappings":";;;AAAA,iDAAiD;AAEjD;;;;;;;GAOG;AACH,SAAgB,gBAAgB,CAC9B,KAAa,EACb,QAAkC;IAElC,IACE,kBAAkB,IAAI,8BAAe;QACrC,OAAO,8BAAe,CAAC,gBAAgB,KAAK,UAAU,EACtD;QACA,OAAO,8BAAe,CAAC,gBAAgB,CAAC,KAAK,CAAC,WAAW,EAAE,EAAE,QAAQ,CAAC,CAAC;KACxE;IAED,IACE,8BAAe,CAAC,OAAO;QACvB,IAAI,IAAI,8BAAe,CAAC,OAAO;QAC/B,OAAO,8BAAe,CAAC,OAAO,CAAC,EAAE,KAAK,UAAU,EAChD;QACA,OAAO,8BAAe,CAAC,OAAO,CAAC,EAAE,CAAC,KAAK,EAAE,QAAQ,CAAC,CAAC;KACpD;IAED,MAAM,IAAI,KAAK,CAAC,2CAA2C,CAAC,CAAC;AAC/D,CAAC;AApBD,4CAoBC;AAED;;;;;;;GAOG;AACH,SAAgB,mBAAmB,CACjC,KAAa,EACb,QAAkC;IAElC,IACE,qBAAqB,IAAI,8BAAe;QACxC,OAAO,8BAAe,CAAC,mBAAmB,KAAK,UAAU,EACzD;QACA,OAAO,8BAAe,CAAC,mBAAmB,CAAC,KAAK,CAAC,WAAW,EAAE,EAAE,QAAQ,CAAC,CAAC;KAC3E;IAED,IACE,8BAAe,CAAC,OAAO;QACvB,gBAAgB,IAAI,8BAAe,CAAC,OAAO;QAC3C,OAAO,8BAAe,CAAC,OAAO,CAAC,cAAc,KAAK,UAAU,EAC5D;QACA,OAAO,8BAAe,CAAC,OAAO,CAAC,cAAc,CAAC,KAAK,EAAE,QAAQ,CAAC,CAAC;KAChE;IAED,MAAM,IAAI,KAAK,CAAC,8CAA8C,CAAC,CAAC;AAClE,CAAC;AApBD,kDAoBC","sourcesContent":["import { rootRealmGlobal } from './globalObject';\n\n/**\n * Adds an event listener platform agnostically, trying both `globalThis.addEventListener` and `globalThis.process.on`\n *\n * @param event - The event to listen for.\n * @param listener - The listener to be triggered when the event occurs.\n * @returns The result of the platform agnostic operation if any.\n * @throws If none of the platform options are present.\n */\nexport function addEventListener(\n event: string,\n listener: (...args: any[]) => void,\n) {\n if (\n 'addEventListener' in rootRealmGlobal &&\n typeof rootRealmGlobal.addEventListener === 'function'\n ) {\n return rootRealmGlobal.addEventListener(event.toLowerCase(), listener);\n }\n\n if (\n rootRealmGlobal.process &&\n 'on' in rootRealmGlobal.process &&\n typeof rootRealmGlobal.process.on === 'function'\n ) {\n return rootRealmGlobal.process.on(event, listener);\n }\n\n throw new Error('Platform agnostic addEventListener failed');\n}\n\n/**\n * Removes an event listener platform agnostically, trying both `globalThis.removeEventListener` and `globalThis.process.removeListener`\n *\n * @param event - The event to remove the listener for.\n * @param listener - The currently attached listener.\n * @returns The result of the platform agnostic operation if any.\n * @throws If none of the platform options are present.\n */\nexport function removeEventListener(\n event: string,\n listener: (...args: any[]) => void,\n) {\n if (\n 'removeEventListener' in rootRealmGlobal &&\n typeof rootRealmGlobal.removeEventListener === 'function'\n ) {\n return rootRealmGlobal.removeEventListener(event.toLowerCase(), listener);\n }\n\n if (\n rootRealmGlobal.process &&\n 'removeListener' in rootRealmGlobal.process &&\n typeof rootRealmGlobal.process.removeListener === 'function'\n ) {\n return rootRealmGlobal.process.removeListener(event, listener);\n }\n\n throw new Error('Platform agnostic removeEventListener failed');\n}\n"]}
@@ -0,0 +1,9 @@
1
+ /**
2
+ * A platform-agnostic alias for the root realm global object.
3
+ */
4
+ declare const rootRealmGlobal: typeof globalThis;
5
+ /**
6
+ * The string literal corresponding to the name of the root realm global object.
7
+ */
8
+ declare const rootRealmGlobalName: string;
9
+ export { rootRealmGlobal, rootRealmGlobalName };
@@ -0,0 +1,48 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.rootRealmGlobalName = exports.rootRealmGlobal = void 0;
4
+ var GlobalObjectNames;
5
+ (function (GlobalObjectNames) {
6
+ // The globalThis entry is incorrectly identified as shadowing the global
7
+ // globalThis.
8
+ // eslint-disable-next-line @typescript-eslint/no-shadow
9
+ GlobalObjectNames["globalThis"] = "globalThis";
10
+ GlobalObjectNames["global"] = "global";
11
+ GlobalObjectNames["self"] = "self";
12
+ GlobalObjectNames["window"] = "window";
13
+ })(GlobalObjectNames || (GlobalObjectNames = {}));
14
+ let _rootRealmGlobal;
15
+ let _rootRealmGlobalName;
16
+ /* istanbul ignore next */
17
+ /* eslint-disable no-negated-condition */
18
+ if (typeof globalThis !== 'undefined') {
19
+ _rootRealmGlobal = globalThis;
20
+ _rootRealmGlobalName = GlobalObjectNames.globalThis;
21
+ }
22
+ else if (typeof self !== 'undefined') {
23
+ _rootRealmGlobal = self;
24
+ _rootRealmGlobalName = GlobalObjectNames.self;
25
+ }
26
+ else if (typeof window !== 'undefined') {
27
+ _rootRealmGlobal = window;
28
+ _rootRealmGlobalName = GlobalObjectNames.window;
29
+ }
30
+ else if (typeof global !== 'undefined') {
31
+ _rootRealmGlobal = global;
32
+ _rootRealmGlobalName = GlobalObjectNames.global;
33
+ }
34
+ else {
35
+ throw new Error('Unknown realm type; failed to identify global object.');
36
+ }
37
+ /* eslint-enable no-negated-condition */
38
+ /**
39
+ * A platform-agnostic alias for the root realm global object.
40
+ */
41
+ const rootRealmGlobal = _rootRealmGlobal;
42
+ exports.rootRealmGlobal = rootRealmGlobal;
43
+ /**
44
+ * The string literal corresponding to the name of the root realm global object.
45
+ */
46
+ const rootRealmGlobalName = _rootRealmGlobalName;
47
+ exports.rootRealmGlobalName = rootRealmGlobalName;
48
+ //# sourceMappingURL=globalObject.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"globalObject.js","sourceRoot":"","sources":["../../src/common/globalObject.ts"],"names":[],"mappings":";;;AAAA,IAAK,iBAQJ;AARD,WAAK,iBAAiB;IACpB,yEAAyE;IACzE,cAAc;IACd,wDAAwD;IACxD,8CAAyB,CAAA;IACzB,sCAAiB,CAAA;IACjB,kCAAa,CAAA;IACb,sCAAiB,CAAA;AACnB,CAAC,EARI,iBAAiB,KAAjB,iBAAiB,QAQrB;AAED,IAAI,gBAAmC,CAAC;AACxC,IAAI,oBAA4B,CAAC;AAEjC,0BAA0B;AAC1B,yCAAyC;AACzC,IAAI,OAAO,UAAU,KAAK,WAAW,EAAE;IACrC,gBAAgB,GAAG,UAAU,CAAC;IAC9B,oBAAoB,GAAG,iBAAiB,CAAC,UAAU,CAAC;CACrD;KAAM,IAAI,OAAO,IAAI,KAAK,WAAW,EAAE;IACtC,gBAAgB,GAAG,IAAI,CAAC;IACxB,oBAAoB,GAAG,iBAAiB,CAAC,IAAI,CAAC;CAC/C;KAAM,IAAI,OAAO,MAAM,KAAK,WAAW,EAAE;IACxC,gBAAgB,GAAG,MAAM,CAAC;IAC1B,oBAAoB,GAAG,iBAAiB,CAAC,MAAM,CAAC;CACjD;KAAM,IAAI,OAAO,MAAM,KAAK,WAAW,EAAE;IACxC,gBAAgB,GAAG,MAAM,CAAC;IAC1B,oBAAoB,GAAG,iBAAiB,CAAC,MAAM,CAAC;CACjD;KAAM;IACL,MAAM,IAAI,KAAK,CAAC,uDAAuD,CAAC,CAAC;CAC1E;AACD,wCAAwC;AAExC;;GAEG;AACH,MAAM,eAAe,GAAG,gBAAgB,CAAC;AAOhC,0CAAe;AALxB;;GAEG;AACH,MAAM,mBAAmB,GAAG,oBAAoB,CAAC;AAEvB,kDAAmB","sourcesContent":["enum GlobalObjectNames {\n // The globalThis entry is incorrectly identified as shadowing the global\n // globalThis.\n // eslint-disable-next-line @typescript-eslint/no-shadow\n globalThis = 'globalThis',\n global = 'global',\n self = 'self',\n window = 'window',\n}\n\nlet _rootRealmGlobal: typeof globalThis;\nlet _rootRealmGlobalName: string;\n\n/* istanbul ignore next */\n/* eslint-disable no-negated-condition */\nif (typeof globalThis !== 'undefined') {\n _rootRealmGlobal = globalThis;\n _rootRealmGlobalName = GlobalObjectNames.globalThis;\n} else if (typeof self !== 'undefined') {\n _rootRealmGlobal = self;\n _rootRealmGlobalName = GlobalObjectNames.self;\n} else if (typeof window !== 'undefined') {\n _rootRealmGlobal = window;\n _rootRealmGlobalName = GlobalObjectNames.window;\n} else if (typeof global !== 'undefined') {\n _rootRealmGlobal = global;\n _rootRealmGlobalName = GlobalObjectNames.global;\n} else {\n throw new Error('Unknown realm type; failed to identify global object.');\n}\n/* eslint-enable no-negated-condition */\n\n/**\n * A platform-agnostic alias for the root realm global object.\n */\nconst rootRealmGlobal = _rootRealmGlobal;\n\n/**\n * The string literal corresponding to the name of the root realm global object.\n */\nconst rootRealmGlobalName = _rootRealmGlobalName;\n\nexport { rootRealmGlobal, rootRealmGlobalName };\n"]}
@@ -0,0 +1,12 @@
1
+ import { SnapKeyring } from '@metamask/snaps-types';
2
+ import { Json, JsonRpcNotification, JsonRpcRequest } from '@metamask/utils';
3
+ /**
4
+ * Wraps a SnapKeyring class, returning a handler that can route requests to the exposed functions by the class.
5
+ *
6
+ * @param notify - The BaseSnapExecutor notify function, used for event communication.
7
+ * @param keyring - The SnapKeyring instance.
8
+ * @returns A handler function.
9
+ */
10
+ export declare function wrapKeyring(notify: (requestObject: Omit<JsonRpcNotification<Record<string, Json> | Json[]>, 'jsonrpc'>) => void, keyring?: SnapKeyring): ({ request }: {
11
+ request: JsonRpcRequest<Json[]>;
12
+ }) => unknown;