socket-function 0.59.0 → 0.61.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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "socket-function",
3
- "version": "0.59.0",
3
+ "version": "0.61.0",
4
4
  "main": "index.js",
5
5
  "license": "MIT",
6
6
  "note1": "note on node-forge fork, see https://github.com/digitalbazaar/forge/issues/744 for details",
@@ -2,6 +2,7 @@
2
2
  //# sourceURL=require.js
3
3
 
4
4
  let startTime = Date.now();
5
+ globalThis.BOOT_TIME = startTime;
5
6
 
6
7
  Symbol.dispose = Symbol.dispose || Symbol("dispose");
7
8
  Symbol.asyncDispose = Symbol.asyncDispose || Symbol("asyncDispose");
@@ -12,24 +13,22 @@
12
13
  argv: [],
13
14
  env: {
14
15
  // Mirror the tnode.js setting
15
- NODE_ENV: "production"
16
- },
17
- versions: {
18
-
16
+ NODE_ENV: "production",
19
17
  },
18
+ versions: {},
20
19
  },
21
20
  setImmediate(callback) {
22
21
  setTimeout(callback, 0);
23
22
  },
24
23
  // Ignore flags for now, even though they should work fine if we just hardcoded compileFlags.ts here.
25
- setFlag() { },
24
+ setFlag() {},
26
25
  global: window,
27
26
  });
28
27
 
29
28
  // Not real modules, as we just define their exports
30
29
  const builtInModuleExports = {
31
30
  worker_threads: {
32
- isMainThread: true
31
+ isMainThread: true,
33
32
  },
34
33
  util: {
35
34
  // https://nodejs.org/api/util.html#util_util_inherits_constructor_superconstructor
@@ -42,8 +41,8 @@
42
41
  buffer: { Buffer },
43
42
  stream: {
44
43
  // HACK: Needed to get SAX JS to work correctly.
45
- Stream: function () { },
46
- Transform: function () { },
44
+ Stream: function () {},
45
+ Transform: function () {},
47
46
  },
48
47
  timers: {
49
48
  // TODO: Add all members of timers
@@ -101,11 +100,7 @@
101
100
 
102
101
  window.r = function r(text) {
103
102
  text = text.toLowerCase();
104
- return Object
105
- .values(moduleCache)
106
- .filter(x => x.filename.toLowerCase().includes(text))
107
- [0]
108
- .exports;
103
+ return Object.values(moduleCache).filter((x) => x.filename.toLowerCase().includes(text))[0].exports;
109
104
  };
110
105
 
111
106
  let requireBatch;
@@ -118,7 +113,6 @@
118
113
  }
119
114
  }
120
115
 
121
-
122
116
  if (request in rootRequire.cache) {
123
117
  return rootRequire.cache[request].exports;
124
118
  }
@@ -134,19 +128,24 @@
134
128
  let requests = Object.keys(requireBatch);
135
129
  let callbacks = Object.values(requireBatch).reduce((a, b) => a.concat(b), []);
136
130
  requireBatch = undefined;
137
- void rootRequireMultiple(requests, true).then(() => {
138
- for (let callback of callbacks) {
139
- callback();
131
+ void rootRequireMultiple(requests, true).then(
132
+ () => {
133
+ for (let callback of callbacks) {
134
+ callback();
135
+ }
136
+ },
137
+ (err) => {
138
+ throw err;
140
139
  }
141
- }, err => { throw err; });
140
+ );
142
141
  }, 0);
143
142
  }
144
- return new Promise(resolve => {
143
+ return new Promise((resolve) => {
145
144
  requireBatch[request] = requireBatch[request] || [];
146
145
  requireBatch[request].push(resolve);
147
146
  });
148
147
  } else {
149
- return rootRequireMultiple([request]).then(x => x[0].exports);
148
+ return rootRequireMultiple([request]).then((x) => x[0].exports);
150
149
  }
151
150
  }
152
151
  async function rootRequireMultiple(requests) {
@@ -156,7 +155,7 @@
156
155
 
157
156
  let alreadyHaveRanges;
158
157
  if (alreadyHave) {
159
- let seqNums = Object.keys(alreadyHave.seqNums).map(x => +x);
158
+ let seqNums = Object.keys(alreadyHave.seqNums).map((x) => +x);
160
159
  seqNums.sort((a, b) => a - b);
161
160
  let seqNumRanges = [];
162
161
  alreadyHaveRanges = { requireSeqNumProcessId: alreadyHave.requireSeqNumProcessId, seqNumRanges };
@@ -182,7 +181,10 @@
182
181
  if (new URL(location).searchParams.get("droppermissions") !== null) {
183
182
  args.push(true);
184
183
  }
185
- let requestUrl = location.origin + location.pathname + `?classGuid=RequireController-e2f811f3-14b8-4759-b0d6-73f14516cf1d&functionName=getModules`;
184
+ let requestUrl =
185
+ location.origin +
186
+ location.pathname +
187
+ `?classGuid=RequireController-e2f811f3-14b8-4759-b0d6-73f14516cf1d&functionName=getModules`;
186
188
  let remapImportRequestsClientside = globalThis.remapImportRequestsClientside;
187
189
  if (remapImportRequestsClientside) {
188
190
  for (let fnc of remapImportRequestsClientside) {
@@ -219,10 +221,15 @@
219
221
  }, 0);
220
222
 
221
223
  time = Date.now() - time;
222
- let moduleCount = Object.values(modules).filter(x => x.source).length;
223
- let requireModuleCount = Object.values(modules).filter(x => !x.source).length;
224
+ let moduleCount = Object.values(modules).filter((x) => x.source).length;
225
+ let requireModuleCount = Object.values(modules).filter((x) => !x.source).length;
224
226
  let dependenciesOnlyText = requireModuleCount ? ` (+${requireModuleCount} dependencies only)` : "";
225
- console.log(`%cimport(${requests.join(", ")}) finished download ${time}ms, ${Math.ceil(rawText.length / 1024)}KB, ${moduleCount} modules${dependenciesOnlyText} at ${Date.now() - startTime}ms`, "color: green");
227
+ console.log(
228
+ `%cimport(${requests.join(", ")}) finished download ${time}ms, ${Math.ceil(
229
+ rawText.length / 1024
230
+ )}KB, ${moduleCount} modules${dependenciesOnlyText} at ${Date.now() - startTime}ms`,
231
+ "color: green"
232
+ );
226
233
 
227
234
  time = Date.now();
228
235
 
@@ -237,10 +244,15 @@
237
244
  }
238
245
 
239
246
  try {
240
- return requestsResolvedPaths.map(x => getModule(x));
247
+ return requestsResolvedPaths.map((x) => getModule(x));
241
248
  } finally {
242
249
  time = Date.now() - time;
243
- console.log(`%cimport(${requests.join(", ")}) finished evaluate ${time}ms (${moduleCount} modules) at ${Date.now() - startTime}ms`, "color: lightblue");
250
+ console.log(
251
+ `%cimport(${requests.join(", ")}) finished evaluate ${time}ms (${moduleCount} modules) at ${
252
+ Date.now() - startTime
253
+ }ms`,
254
+ "color: lightblue"
255
+ );
244
256
  }
245
257
  }
246
258
 
@@ -272,9 +284,12 @@
272
284
  } else {
273
285
  if (!(request in serializedModule.requests)) {
274
286
  if (!asyncIsFine && !globalThis.suppressUnexpectedModuleWarning) {
275
- console.warn(`Accessed unexpected module %c${request}%c in %c${module.id}%c\n\tTreating it as an async require.\n\tAll modules require synchronously clientside must be required serverside at a module level.`,
276
- "color: red", "color: unset",
277
- "color: red", "color: unset",
287
+ console.warn(
288
+ `Accessed unexpected module %c${request}%c in %c${module.id}%c\n\tTreating it as an async require.\n\tAll modules require synchronously clientside must be required serverside at a module level.`,
289
+ "color: red",
290
+ "color: unset",
291
+ "color: red",
292
+ "color: unset"
278
293
  );
279
294
  }
280
295
  // NOTE: We should still namespace it to the current folder (if it is a relative path),
@@ -295,9 +310,12 @@
295
310
  }
296
311
  if (resolvedPath !== "NOTALLOWEDCLIENTSIDE" && !serializedModules[resolvedPath]) {
297
312
  if (!asyncIsFine) {
298
- console.warn(`Accessed unexpected module %c${request}%c in %c${module.id}%c\n\tTreating it as an async require.\n\tAll modules require synchronously clientside must be required serverside at a module level.`,
299
- "color: red", "color: unset",
300
- "color: red", "color: unset",
313
+ console.warn(
314
+ `Accessed unexpected module %c${request}%c in %c${module.id}%c\n\tTreating it as an async require.\n\tAll modules require synchronously clientside must be required serverside at a module level.`,
315
+ "color: red",
316
+ "color: unset",
317
+ "color: red",
318
+ "color: unset"
301
319
  );
302
320
  debugger;
303
321
  }
@@ -308,32 +326,48 @@
308
326
  if (resolvedPath === "NOTALLOWEDCLIENTSIDE" || !serializedModules[resolvedPath].allowclient) {
309
327
  let childId = resolvedPath === "NOTALLOWEDCLIENTSIDE" ? request : resolvedPath;
310
328
  if (serializedModules[resolvedPath]?.serveronly) {
311
- exportsOverride = new Proxy({}, {
312
- get(target, property) {
313
- if (property === "__esModule") return undefined;
314
- // NOTE: Return a toString that evaluates to "" so we can EXPLICITLY detect non-loaded modules
315
- if (property === unloadedModule) return true;
316
- if (property === "default") return exportsOverride;
317
-
318
- throw new Error(`Module ${childId} is serverside only. Tried to access ${property} from ${module.id}`);
329
+ exportsOverride = new Proxy(
330
+ {},
331
+ {
332
+ get(target, property) {
333
+ if (property === "__esModule") return undefined;
334
+ // NOTE: Return a toString that evaluates to "" so we can EXPLICITLY detect non-loaded modules
335
+ if (property === unloadedModule) return true;
336
+ if (property === "default") return exportsOverride;
337
+
338
+ throw new Error(
339
+ `Module ${childId} is serverside only. Tried to access ${property} from ${module.id}`
340
+ );
341
+ },
319
342
  }
320
- });
343
+ );
321
344
  } else {
322
- exportsOverride = new Proxy({}, {
323
- get(target, property) {
324
- if (property === "__esModule") return undefined;
325
- // NOTE: Return a toString that evaluates to "" so we can EXPLICITLY detect non-loaded modules
326
- if (property === unloadedModule) return true;
327
- if (property === "default") return exportsOverride;
328
-
329
- console.warn(`Accessed non-whitelisted module %c${childId}%c, specifically property %c${String(property)}%c.\n\tAdd %cmodule.allowclient = true%c to the file to allow access.\n\t(IF it is a 3rd party library, use the global "setFlag" helper (in the file you imported the module) to set properties on other modules (it can even recursively set properties)).\n\n\tFrom ${module.id}`,
330
- "color: red", "color: unset",
331
- "color: red", "color: unset",
332
- "color: red", "color: unset",
333
- );
334
- return undefined;
345
+ exportsOverride = new Proxy(
346
+ {},
347
+ {
348
+ get(target, property) {
349
+ if (property === "__esModule") return undefined;
350
+ // NOTE: Return a toString that evaluates to "" so we can EXPLICITLY detect non-loaded modules
351
+ if (property === unloadedModule) return true;
352
+ if (property === "default") return exportsOverride;
353
+
354
+ console.warn(
355
+ `Accessed non-whitelisted module %c${childId}%c, specifically property %c${String(
356
+ property
357
+ )}%c.\n\tAdd %cmodule.allowclient = true%c to the file to allow access.\n\t(IF it is a 3rd party library, use the global "setFlag" helper (in the file you imported the module) to set properties on other modules (it can even recursively set properties)).\n\n\tFrom ${
358
+ module.id
359
+ }`,
360
+ "color: red",
361
+ "color: unset",
362
+ "color: red",
363
+ "color: unset",
364
+ "color: red",
365
+ "color: unset"
366
+ );
367
+ return undefined;
368
+ },
335
369
  }
336
- });
370
+ );
337
371
  }
338
372
  }
339
373
 
@@ -349,12 +383,12 @@
349
383
 
350
384
  let exports = providerModule.exports;
351
385
  let remapExports = providerModule.remapExports;
352
- if (remapExports && typeof remapExports === "function") {
386
+ if (remapExports && typeof remapExports === "function") {
353
387
  exports = remapExports(exports, module);
354
388
  }
355
389
 
356
390
  return exports;
357
- };
391
+ }
358
392
  }
359
393
 
360
394
  /** Generates the module root function, which can be called to evaluate the module,
@@ -364,26 +398,25 @@
364
398
  function wrapSafe(filename, contents) {
365
399
  // TODO: Have the serverside inform us of the correct loader, or... have it actually emit a .json loader.
366
400
  if (filename.endsWith(".json")) {
367
- return (exports, require, module) => module.exports = contents && JSON.parse(contents);
401
+ return (exports, require, module) => (module.exports = contents && JSON.parse(contents));
368
402
  }
369
403
 
370
404
  // NOTE: debugName only matters during module evaluation. After that the sourcemap should work.
371
- let debugName = (
372
- filename
373
- .replace(/\\/g, "/")
374
- .split("/")
375
- .slice(-1)[0]
376
- .replace(/\./g, "_")
377
- .replace(/[^a-zA-Z_]/g, "")
378
- );
405
+ let debugName = filename
406
+ .replace(/\\/g, "/")
407
+ .split("/")
408
+ .slice(-1)[0]
409
+ .replace(/\./g, "_")
410
+ .replace(/[^a-zA-Z_]/g, "");
379
411
  // NOTE: eval is used instead of new Function, as new Function inject lines, which messes
380
412
  // up our sourcemaps.
381
413
  // NOTE: All on one line, so we don't break sourcemaps by TOO much. We could also parse
382
414
  // the sourcemap and adjust it, but... it is much easier to just not change the line counts.
383
- return eval(`(function ${debugName}(exports, require, module, __filename, __dirname, importDynamic) {${contents}\n })`);
415
+ return eval(
416
+ `(function ${debugName}(exports, require, module, __filename, __dirname, importDynamic) {${contents}\n })`
417
+ );
384
418
  }
385
419
 
386
-
387
420
  const unloadedModule = Symbol("unloadedModule");
388
421
 
389
422
  let currentModuleEvaluationStack = [];
@@ -421,10 +454,12 @@
421
454
  delete alreadyHave.seqNums[serializedModule.seqNum];
422
455
  }
423
456
  // NOTE: There is almost never recovery from module downloading errors, so just don't catch them
424
- return Promise.resolve().then(() => rootRequire(resolvedId, true)).then(async () => {
425
- module.loaded = true;
426
- await load();
427
- });
457
+ return Promise.resolve()
458
+ .then(() => rootRequire(resolvedId, true))
459
+ .then(async () => {
460
+ module.loaded = true;
461
+ await load();
462
+ });
428
463
  }
429
464
 
430
465
  module.requires = serializedModule.requests;
@@ -443,10 +478,9 @@
443
478
  // Import children, as the children may be allowed clientside, and may have side-effects!
444
479
  if (!source) {
445
480
  let requests = Object.keys(serializedModule.requests)
446
- .filter(x => x !== "NOTALLOWEDCLIENTSIDE")
447
- .filter(x => !(x in serializedModule.asyncRequests))
448
- ;
449
- source = requests.map(id => `require(${JSON.stringify(id)});\n`).join("");
481
+ .filter((x) => x !== "NOTALLOWEDCLIENTSIDE")
482
+ .filter((x) => !(x in serializedModule.asyncRequests));
483
+ source = requests.map((id) => `require(${JSON.stringify(id)});\n`).join("");
450
484
  }
451
485
 
452
486
  module.size = source.length;
@@ -490,7 +524,6 @@
490
524
  module.isPreloading = false;
491
525
  currentModuleEvaluationStack.pop();
492
526
  }
493
-
494
527
  }
495
528
 
496
529
  return module;
@@ -520,4 +553,4 @@
520
553
  return await response.text();
521
554
  }
522
555
  }
523
- })();
556
+ })();
@@ -188,57 +188,56 @@ export async function startSocketServer(
188
188
  });
189
189
 
190
190
  let realServer = net.createServer(socket => {
191
- let server = sniServers.get("querysub.com") || mainHTTPSServer;
192
- server.emit("connection", socket);
193
-
194
- // //console.log("Received TCP connection from " + socket.remoteAddress);
195
- // const debug = socket.remoteAddress + ":" + socket.remotePort;
196
- // function handleTLSHello(buffer: Buffer, packetCount: number): void | "more" {
197
- // if (!SocketFunction.silent) {
198
- // console.log(`Received TCP header packet from ${debug}, have ${buffer.length} bytes so far, ${packetCount} packets`);
199
- // }
200
- // // All HTTPS requests start with 22, and no HTTP requests start with 22,
201
- // // so we just need to read the first byte.
202
- // let server: https.Server | http.Server;
203
- // if (buffer[0] !== 22) {
204
- // server = httpServer;
205
- // } else {
206
- // let data = parseTLSHello(buffer);
207
- // if (data.missingBytes > 0) {
208
- // return "more";
209
- // }
210
- // let sni = data.extensions.filter(x => x.type === SNIType).flatMap(x => parseSNIExtension(x.data))[0];
211
- // if (!SocketFunction.silent) {
212
- // console.log(`Received TCP connection with SNI ${JSON.stringify(sni)}`);
213
- // }
214
- // if (!sni) {
215
- // console.warn(`No SNI found in TLS hello from ${debug}, using main server. Packets ${packetCount}`);
216
- // console.log(buffer.toString("base64"));
217
- // }
218
- // server = sniServers.get(sni) || mainHTTPSServer;
219
- // }
191
+ const debug = socket.remoteAddress + ":" + socket.remotePort;
192
+ if (!SocketFunction.silent) {
193
+ console.log(`Received TCP connection from ${debug}`);
194
+ }
195
+ function handleTLSHello(buffer: Buffer, packetCount: number): void | "more" {
196
+ if (!SocketFunction.silent) {
197
+ console.log(`Received TCP header packet from ${debug}, have ${buffer.length} bytes so far, ${packetCount} packets`);
198
+ }
199
+ // All HTTPS requests start with 22, and no HTTP requests start with 22,
200
+ // so we just need to read the first byte.
201
+ let server: https.Server | http.Server;
202
+ if (buffer[0] !== 22) {
203
+ server = httpServer;
204
+ } else {
205
+ let data = parseTLSHello(buffer);
206
+ if (data.missingBytes > 0) {
207
+ return "more";
208
+ }
209
+ let sni = data.extensions.filter(x => x.type === SNIType).flatMap(x => parseSNIExtension(x.data))[0];
210
+ if (!SocketFunction.silent) {
211
+ console.log(`Received TCP connection with SNI ${JSON.stringify(sni)}`);
212
+ }
213
+ if (!sni) {
214
+ console.warn(`No SNI found in TLS hello from ${debug}, using main server. Packets ${packetCount}`);
215
+ console.log(buffer.toString("base64"));
216
+ }
217
+ server = sniServers.get(sni) || mainHTTPSServer;
218
+ }
220
219
 
221
- // // NOTE: Messages aren't dequeued until the current handler finishes, so we don't need to pause the socket or anything.
222
- // server.emit("connection", socket);
223
- // socket.unshift(buffer);
224
- // }
225
- // let buffers: Buffer[] = [];
226
- // function getNextData() {
227
- // // NOTE: ONCE is used, so we only look at the first buffer, and then after that
228
- // // we pipe. This should be very efficient, as pipe has insane throughput
229
- // // (100s of MB/s, easily, even on a terrible machine).
230
- // socket.once("data", buffer => {
231
- // buffers.push(buffer);
232
- // let result = handleTLSHello(Buffer.concat(buffers), buffers.length);
233
- // if (result === "more") {
234
- // getNextData();
235
- // }
236
- // });
237
- // }
238
- // getNextData();
239
- // socket.on("error", (e) => {
240
- // console.error(`Socket error for ${debug}, ${e.stack}`);
241
- // });
220
+ // NOTE: Messages aren't dequeued until the current handler finishes, so we don't need to pause the socket or anything.
221
+ server.emit("connection", socket);
222
+ socket.unshift(buffer);
223
+ }
224
+ let buffers: Buffer[] = [];
225
+ function getNextData() {
226
+ // NOTE: ONCE is used, so we only look at the first buffer, and then after that
227
+ // we pipe. This should be very efficient, as pipe has insane throughput
228
+ // (100s of MB/s, easily, even on a terrible machine).
229
+ socket.once("data", buffer => {
230
+ buffers.push(buffer);
231
+ let result = handleTLSHello(Buffer.concat(buffers), buffers.length);
232
+ if (result === "more") {
233
+ getNextData();
234
+ }
235
+ });
236
+ }
237
+ getNextData();
238
+ socket.on("error", (e) => {
239
+ console.error(`TCP socket error for ${debug}, ${e.stack}`);
240
+ });
242
241
  });
243
242
 
244
243