@cjser/make-synchronous 2.1.0-cjser.2

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.
@@ -0,0 +1,80 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
3
+ var __getOwnPropNames = Object.getOwnPropertyNames;
4
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
5
+ var __export = (target, all) => {
6
+ for (var name in all)
7
+ __defProp(target, name, { get: all[name], enumerable: true });
8
+ };
9
+ var __copyProps = (to, from, except, desc) => {
10
+ if (from && typeof from === "object" || typeof from === "function") {
11
+ for (let key of __getOwnPropNames(from))
12
+ if (!__hasOwnProp.call(to, key) && key !== except)
13
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
14
+ }
15
+ return to;
16
+ };
17
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
18
+
19
+ // packages/@cjser/make-synchronous.tmp-26-1778153404829/index.js
20
+ var index_exports = {};
21
+ __export(index_exports, {
22
+ default: () => index_default
23
+ });
24
+ module.exports = __toCommonJS(index_exports);
25
+ var import_node_worker_threads = require("node:worker_threads");
26
+ var import_meta = {};
27
+ var IS_WORKER_MARK = "is-make-synchronous-worker";
28
+ var _a;
29
+ var IS_WORKER = (_a = import_node_worker_threads.workerData) == null ? void 0 : _a[IS_WORKER_MARK];
30
+ function setupWorker(function_) {
31
+ const { workerPort } = import_node_worker_threads.workerData;
32
+ import_node_worker_threads.parentPort.on("message", async ({ arguments_, semaphore }) => {
33
+ try {
34
+ workerPort.postMessage({ result: await function_(...arguments_) });
35
+ } catch (error) {
36
+ workerPort.postMessage({ error });
37
+ } finally {
38
+ Atomics.store(semaphore, 0, 1);
39
+ Atomics.notify(semaphore, 0, 1);
40
+ }
41
+ });
42
+ }
43
+ function makeSynchronous(function_) {
44
+ let cache;
45
+ function createWorker() {
46
+ if (!cache) {
47
+ const { port1: mainThreadPort, port2: workerPort } = new MessageChannel();
48
+ mainThreadPort.unref();
49
+ workerPort.unref();
50
+ const code = `
51
+ import setupWorker from ${JSON.stringify(import_meta.url)};
52
+
53
+ setupWorker(${function_});
54
+ `;
55
+ const worker = new import_node_worker_threads.Worker(code, {
56
+ eval: true,
57
+ workerData: {
58
+ workerPort,
59
+ [IS_WORKER_MARK]: true
60
+ },
61
+ transferList: [workerPort]
62
+ });
63
+ worker.unref();
64
+ cache = { worker, mainThreadPort };
65
+ }
66
+ return cache;
67
+ }
68
+ return (...arguments_) => {
69
+ const { worker, mainThreadPort } = createWorker();
70
+ const semaphore = new Int32Array(new SharedArrayBuffer(Int32Array.BYTES_PER_ELEMENT));
71
+ worker.postMessage({ arguments_, semaphore });
72
+ Atomics.wait(semaphore, 0, 0);
73
+ const { error, result } = (0, import_node_worker_threads.receiveMessageOnPort)(mainThreadPort).message;
74
+ if (error) {
75
+ throw error;
76
+ }
77
+ return result;
78
+ };
79
+ }
80
+ var index_default = IS_WORKER ? setupWorker : makeSynchronous;
@@ -0,0 +1,87 @@
1
+ var __create = Object.create;
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __getProtoOf = Object.getPrototypeOf;
6
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
7
+ var __export = (target, all) => {
8
+ for (var name in all)
9
+ __defProp(target, name, { get: all[name], enumerable: true });
10
+ };
11
+ var __copyProps = (to, from, except, desc) => {
12
+ if (from && typeof from === "object" || typeof from === "function") {
13
+ for (let key of __getOwnPropNames(from))
14
+ if (!__hasOwnProp.call(to, key) && key !== except)
15
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
16
+ }
17
+ return to;
18
+ };
19
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
20
+ // If the importer is in node compatibility mode or this is not an ESM
21
+ // file that has been converted to a CommonJS file using a Babel-
22
+ // compatible transform (i.e. "__esModule" has not been set), then set
23
+ // "default" to the CommonJS "module.exports" for node compatibility.
24
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
25
+ mod
26
+ ));
27
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
28
+
29
+ // packages/@cjser/make-synchronous.tmp-26-1778153404829/subprocess.js
30
+ var subprocess_exports = {};
31
+ __export(subprocess_exports, {
32
+ default: () => makeSynchronous
33
+ });
34
+ module.exports = __toCommonJS(subprocess_exports);
35
+ var import_node_buffer = require("node:buffer");
36
+ var import_node_child_process = __toESM(require("node:child_process"), 1);
37
+ var import_node_v8 = __toESM(require("node:v8"), 1);
38
+ var import_node_process = __toESM(require("node:process"), 1);
39
+ var import_subsume = __toESM(require("@cjser/subsume"), 1);
40
+ var HUNDRED_MEGABYTES = 1e3 * 1e3 * 100;
41
+ function makeSynchronous(function_) {
42
+ return (...arguments_) => {
43
+ const serializedArguments = import_node_v8.default.serialize(arguments_).toString("hex");
44
+ const subsume = new import_subsume.default();
45
+ const input = `
46
+ import v8 from 'node:v8';
47
+ import Subsume from '@cjser/subsume';
48
+
49
+ const subsume = new Subsume('${subsume.id}');
50
+
51
+ const send = value => {
52
+ const serialized = v8.serialize(value).toString('hex');
53
+ process.stdout.write(subsume.compose(serialized));
54
+ };
55
+
56
+ try {
57
+ const arguments_ = v8.deserialize(Buffer.from('${serializedArguments}', 'hex'));
58
+ const result = await (${function_})(...arguments_);
59
+ send({result});
60
+ } catch (error) {
61
+ send({error});
62
+ }
63
+ `;
64
+ const env = { ...import_node_process.default.env, ELECTRON_RUN_AS_NODE: "1" };
65
+ env.NODE_OPTIONS &&= env.NODE_OPTIONS.split(/\s+/).filter((option) => !/^--(?:inspect|debug)/.test(option)).join(" ");
66
+ const { error: subprocessError, stdout, stderr } = import_node_child_process.default.spawnSync(import_node_process.default.execPath, ["--input-type=module", "-"], {
67
+ input,
68
+ encoding: "utf8",
69
+ maxBuffer: HUNDRED_MEGABYTES,
70
+ env
71
+ });
72
+ if (subprocessError) {
73
+ throw subprocessError;
74
+ }
75
+ const { data, rest } = subsume.parse(stdout);
76
+ import_node_process.default.stdout.write(rest);
77
+ import_node_process.default.stderr.write(stderr);
78
+ if (!data) {
79
+ return;
80
+ }
81
+ const { error, result } = import_node_v8.default.deserialize(import_node_buffer.Buffer.from(data, "hex"));
82
+ if (error) {
83
+ throw error;
84
+ }
85
+ return result;
86
+ };
87
+ }
package/index.d.ts ADDED
@@ -0,0 +1,39 @@
1
+ import type {AsyncReturnType} from 'type-fest';
2
+
3
+ // TODO: Move these to https://github.com/sindresorhus/type-fest
4
+ type AnyAsyncFunction = (...argumentsList: any[]) => Promise<unknown | void>;
5
+ type ReplaceReturnType<T extends (...arguments_: any) => unknown, NewReturnType> = (...arguments_: Parameters<T>) => NewReturnType;
6
+
7
+ /**
8
+ Returns a wrapped version of the given async function or a string representation to a async function which executes synchronously. This means no other code will execute (not even async code) until the given async function is done.
9
+
10
+ The function is executed in a worker or subprocess, so you cannot access variables or imports from outside its scope. Use `await import(…)` to import dependencies inside the function.
11
+
12
+ Uses [`MessagePort#postMessage()`](https://nodejs.org/api/worker_threads.html#portpostmessagevalue-transferlist) or the V8 serialization API to transfer arguments, return values, errors between the worker or subprocess and the current process. Most values are supported — except functions and symbols.
13
+
14
+ @example
15
+ ```
16
+ import makeSynchronous from '@cjser/make-synchronous';
17
+
18
+ const fn = makeSynchronous(async number => {
19
+ const {default: delay} = await import('delay');
20
+
21
+ await delay(100);
22
+
23
+ return number * 2;
24
+ });
25
+
26
+ console.log(fn(2));
27
+ //=> 4
28
+ ```
29
+
30
+ @example
31
+ ```
32
+ import makeSynchronous from '@cjser/make-synchronous/subprocess';
33
+
34
+ makeSynchronous(async () => {
35
+ // Runs in a subprocess.
36
+ });
37
+ ```
38
+ */
39
+ export default function makeSynchronous<T extends AnyAsyncFunction = AnyAsyncFunction>(asyncFunction: T | string): ReplaceReturnType<T, AsyncReturnType<T>>;
package/index.js ADDED
@@ -0,0 +1,74 @@
1
+ import {
2
+ workerData,
3
+ receiveMessageOnPort,
4
+ parentPort,
5
+ Worker,
6
+ } from 'node:worker_threads';
7
+
8
+ // Not using `isMainThread` so it can be used in another worker.
9
+ const IS_WORKER_MARK = 'is-make-synchronous-worker';
10
+ const IS_WORKER = workerData?.[IS_WORKER_MARK];
11
+
12
+ function setupWorker(function_) {
13
+ const {workerPort} = workerData;
14
+ parentPort.on('message', async ({arguments_, semaphore}) => {
15
+ try {
16
+ workerPort.postMessage({result: await function_(...arguments_)});
17
+ } catch (error) {
18
+ workerPort.postMessage({error});
19
+ } finally {
20
+ Atomics.store(semaphore, 0, 1);
21
+ Atomics.notify(semaphore, 0, 1);
22
+ }
23
+ });
24
+ }
25
+
26
+ function makeSynchronous(function_) {
27
+ let cache;
28
+
29
+ function createWorker() {
30
+ if (!cache) {
31
+ const {port1: mainThreadPort, port2: workerPort} = new MessageChannel();
32
+ mainThreadPort.unref();
33
+ workerPort.unref();
34
+
35
+ const code = `
36
+ import setupWorker from ${JSON.stringify(import.meta.url)};
37
+
38
+ setupWorker(${function_});
39
+ `;
40
+
41
+ const worker = new Worker(code, {
42
+ eval: true,
43
+ workerData: {
44
+ workerPort,
45
+ [IS_WORKER_MARK]: true,
46
+ },
47
+ transferList: [workerPort],
48
+ });
49
+ worker.unref();
50
+
51
+ cache = {worker, mainThreadPort};
52
+ }
53
+
54
+ return cache;
55
+ }
56
+
57
+ return (...arguments_) => {
58
+ const {worker, mainThreadPort} = createWorker();
59
+ const semaphore = new Int32Array(new SharedArrayBuffer(Int32Array.BYTES_PER_ELEMENT));
60
+
61
+ worker.postMessage({arguments_, semaphore});
62
+ Atomics.wait(semaphore, 0, 0);
63
+
64
+ const {error, result} = receiveMessageOnPort(mainThreadPort).message;
65
+
66
+ if (error) {
67
+ throw error;
68
+ }
69
+
70
+ return result;
71
+ };
72
+ }
73
+
74
+ export default IS_WORKER ? setupWorker : makeSynchronous;
package/license ADDED
@@ -0,0 +1,9 @@
1
+ MIT License
2
+
3
+ Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (https://sindresorhus.com)
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
6
+
7
+ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
8
+
9
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
package/package.json ADDED
@@ -0,0 +1,100 @@
1
+ {
2
+ "name": "@cjser/make-synchronous",
3
+ "version": "2.1.0-cjser.2",
4
+ "description": "Make an asynchronous function synchronous",
5
+ "license": "MIT",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "https://code.moenext.com/3rdeye/cjser.git"
9
+ },
10
+ "funding": "https://github.com/sponsors/sindresorhus",
11
+ "author": {
12
+ "name": "Sindre Sorhus",
13
+ "email": "sindresorhus@gmail.com",
14
+ "url": "https://sindresorhus.com"
15
+ },
16
+ "type": "module",
17
+ "exports": {
18
+ ".": {
19
+ "types": "./index.d.ts",
20
+ "require": "./dist-cjser/index.cjs",
21
+ "default": "./index.js"
22
+ },
23
+ "./subprocess": {
24
+ "types": "./index.d.ts",
25
+ "require": "./dist-cjser/subprocess.cjs",
26
+ "default": "./subprocess.js"
27
+ }
28
+ },
29
+ "sideEffects": false,
30
+ "engines": {
31
+ "node": ">=20"
32
+ },
33
+ "scripts": {
34
+ "test": "xo && ava && tsd"
35
+ },
36
+ "files": [
37
+ "index.js",
38
+ "subprocess.js",
39
+ "index.d.ts",
40
+ "dist-cjser"
41
+ ],
42
+ "keywords": [
43
+ "function",
44
+ "synchronous",
45
+ "sync",
46
+ "block",
47
+ "main",
48
+ "thread",
49
+ "deasync",
50
+ "fiber",
51
+ "asynchronous",
52
+ "async",
53
+ "worker"
54
+ ],
55
+ "dependencies": {
56
+ "type-fest": "^4.40.1",
57
+ "@cjser/subsume": "4.0.0-cjser.2"
58
+ },
59
+ "devDependencies": {
60
+ "ava": "^6.2.0",
61
+ "delay": "^6.0.0",
62
+ "in-range": "^3.0.0",
63
+ "time-span": "^5.1.0",
64
+ "tsd": "^0.32.0",
65
+ "xo": "^0.60.0"
66
+ },
67
+ "types": "./index.d.ts",
68
+ "main": "./dist-cjser/index.cjs",
69
+ "cjser": {
70
+ "sourceVersion": "2.1.0",
71
+ "cjserVersion": 2,
72
+ "original": {
73
+ "name": "make-synchronous",
74
+ "version": "2.1.0",
75
+ "exports": {
76
+ ".": {
77
+ "types": "./index.d.ts",
78
+ "default": "./index.js"
79
+ },
80
+ "./subprocess": {
81
+ "types": "./index.d.ts",
82
+ "default": "./subprocess.js"
83
+ }
84
+ },
85
+ "repository": "sindresorhus/make-synchronous",
86
+ "dependencies": {
87
+ "subsume": "^4.0.0",
88
+ "type-fest": "^4.40.1"
89
+ },
90
+ "files": [
91
+ "index.js",
92
+ "subprocess.js",
93
+ "index.d.ts"
94
+ ],
95
+ "scripts": {
96
+ "test": "xo && ava && tsd"
97
+ }
98
+ }
99
+ }
100
+ }
package/readme.md ADDED
@@ -0,0 +1,67 @@
1
+ # make-synchronous
2
+
3
+ > Make an asynchronous function synchronous
4
+
5
+ **This is the wrong tool for most tasks!** Prefer async APIs whenever possible.
6
+
7
+ The benefit of this package over packages like [`deasync`](https://github.com/abbr/deasync) is that this one is not a native Node.js addon (which comes with a lot of problems). Instead, this package executes the given function synchronously in a [`worker`](https://nodejs.org/api/worker_threads.html) or [`subprocess`](https://nodejs.org/api/child_process.html).
8
+
9
+ Works in Node.js only — not the browser.
10
+
11
+ ## Install
12
+
13
+ ```sh
14
+ npm install make-synchronous
15
+ ```
16
+
17
+ ## Usage
18
+
19
+ Runs in a worker thread by default:
20
+
21
+ ```js
22
+ import makeSynchronous from 'make-synchronous';
23
+
24
+ const fn = makeSynchronous(async number => {
25
+ const {default: delay} = await import('delay');
26
+
27
+ await delay(100);
28
+
29
+ return number * 2;
30
+ });
31
+
32
+ console.log(fn(2));
33
+ //=> 4
34
+ ```
35
+
36
+ To run in a subprocess instead:
37
+
38
+ ```js
39
+ import makeSynchronous from 'make-synchronous/subprocess';
40
+
41
+ makeSynchronous(async () => {
42
+ // Runs in a subprocess.
43
+ });
44
+ ```
45
+
46
+ Subprocess execution is slower, but has the benefit of full process isolation.
47
+
48
+ ## API
49
+
50
+ ### makeSynchronous(asyncFunction | string)
51
+
52
+ Returns a wrapped version of the given async function or a string representation to a async function which executes synchronously. This means no other code will execute (not even async code) until the given async function is done.
53
+
54
+ The function is executed in a worker or subprocess, so you cannot access variables or imports from outside its scope. Use `await import(…)` to import dependencies inside the function.
55
+
56
+ Uses [`MessagePort#postMessage()`](https://nodejs.org/api/worker_threads.html#portpostmessagevalue-transferlist) or the V8 serialization API to transfer arguments, return values, errors between the worker or subprocess and the current process. Most values are supported — except functions and symbols.
57
+
58
+ ## Related
59
+
60
+ - [make-asynchronous](https://github.com/sindresorhus/make-asynchronous) - Make a synchronous function asynchronous by running it in a worker
61
+ - [sleep-synchronously](https://github.com/sindresorhus/sleep-synchronously) - Block the main thread for a given amount of time
62
+ - [make-synchronized](https://github.com/fisker/make-synchronized) - For advanced cases like fully synchronizing an existing module or needing top-level imports
63
+
64
+ ## cjser
65
+
66
+ This package is a CommonJS-compatible build generated by cjser for projects that still need `require()` support. The source version matches the original npm package version, with a cjser prerelease suffix for this generated build.
67
+ Original repository: https://github.com/sindresorhus/make-synchronous
package/subprocess.js ADDED
@@ -0,0 +1,70 @@
1
+ import {Buffer} from 'node:buffer';
2
+ import childProcess from 'node:child_process';
3
+ import v8 from 'node:v8';
4
+ import process from 'node:process';
5
+ import Subsume from '@cjser/subsume';
6
+
7
+ const HUNDRED_MEGABYTES = 1000 * 1000 * 100;
8
+
9
+ export default function makeSynchronous(function_) {
10
+ return (...arguments_) => {
11
+ const serializedArguments = v8.serialize(arguments_).toString('hex');
12
+ const subsume = new Subsume();
13
+
14
+ const input = `
15
+ import v8 from 'node:v8';
16
+ import Subsume from '@cjser/subsume';
17
+
18
+ const subsume = new Subsume('${subsume.id}');
19
+
20
+ const send = value => {
21
+ const serialized = v8.serialize(value).toString('hex');
22
+ process.stdout.write(subsume.compose(serialized));
23
+ };
24
+
25
+ try {
26
+ const arguments_ = v8.deserialize(Buffer.from('${serializedArguments}', 'hex'));
27
+ const result = await (${function_})(...arguments_);
28
+ send({result});
29
+ } catch (error) {
30
+ send({error});
31
+ }
32
+ `;
33
+
34
+ const env = {...process.env, ELECTRON_RUN_AS_NODE: '1'};
35
+
36
+ // Prevent debugger flags from the parent from forcing the child to open a debug port.
37
+ env.NODE_OPTIONS &&= env.NODE_OPTIONS
38
+ .split(/\s+/)
39
+ .filter(option => !/^--(?:inspect|debug)/.test(option))
40
+ .join(' ');
41
+
42
+ const {error: subprocessError, stdout, stderr} = childProcess.spawnSync(process.execPath, ['--input-type=module', '-'], {
43
+ input,
44
+ encoding: 'utf8',
45
+ maxBuffer: HUNDRED_MEGABYTES,
46
+ env,
47
+ });
48
+
49
+ if (subprocessError) {
50
+ throw subprocessError;
51
+ }
52
+
53
+ const {data, rest} = subsume.parse(stdout);
54
+
55
+ process.stdout.write(rest);
56
+ process.stderr.write(stderr);
57
+
58
+ if (!data) {
59
+ return;
60
+ }
61
+
62
+ const {error, result} = v8.deserialize(Buffer.from(data, 'hex'));
63
+
64
+ if (error) {
65
+ throw error;
66
+ }
67
+
68
+ return result;
69
+ };
70
+ }