首次提交
This commit is contained in:
+21
@@ -0,0 +1,21 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2026 Christoph Guttandin
|
||||
|
||||
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:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
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.
|
||||
+5
@@ -0,0 +1,5 @@
|
||||
# broker-factory
|
||||
|
||||
**A little factory function to create a broker for a JSON-RPC based Web Worker.**
|
||||
|
||||
[](https://www.npmjs.com/package/broker-factory)
|
||||
+69
@@ -0,0 +1,69 @@
|
||||
{
|
||||
"author": "Christoph Guttandin",
|
||||
"bugs": {
|
||||
"url": "https://github.com/chrisguttandin/broker-factory/issues"
|
||||
},
|
||||
"config": {
|
||||
"commitizen": {
|
||||
"path": "cz-conventional-changelog"
|
||||
}
|
||||
},
|
||||
"dependencies": {
|
||||
"@babel/runtime": "^7.29.2",
|
||||
"fast-unique-numbers": "^9.0.27",
|
||||
"tslib": "^2.8.1",
|
||||
"worker-factory": "^7.0.49"
|
||||
},
|
||||
"description": "A little factory function to create a broker for a JSON-RPC based Web Worker.",
|
||||
"devDependencies": {
|
||||
"@babel/core": "^7.29.0",
|
||||
"@babel/plugin-external-helpers": "^7.27.1",
|
||||
"@babel/plugin-transform-runtime": "^7.29.0",
|
||||
"@babel/preset-env": "^7.29.2",
|
||||
"@commitlint/cli": "^20.5.0",
|
||||
"@commitlint/config-angular": "^20.5.0",
|
||||
"@rollup/plugin-babel": "^7.0.0",
|
||||
"@vitest/browser-webdriverio": "^4.0.18",
|
||||
"commitizen": "^4.3.1",
|
||||
"cz-conventional-changelog": "^3.3.0",
|
||||
"eslint": "^8.57.0",
|
||||
"eslint-config-holy-grail": "^61.0.11",
|
||||
"husky": "^9.1.7",
|
||||
"lint-staged": "^16.4.0",
|
||||
"prettier": "^3.8.1",
|
||||
"rimraf": "^6.1.3",
|
||||
"rollup": "^4.59.0",
|
||||
"tsconfig-holy-grail": "^15.0.3",
|
||||
"tslint": "^6.1.3",
|
||||
"tslint-config-holy-grail": "^56.0.7",
|
||||
"typescript": "^5.9.3",
|
||||
"vitest": "^4.0.18"
|
||||
},
|
||||
"files": [
|
||||
"build/es2019/",
|
||||
"build/es5/",
|
||||
"src/"
|
||||
],
|
||||
"homepage": "https://github.com/chrisguttandin/broker-factory",
|
||||
"license": "MIT",
|
||||
"main": "build/es5/bundle.js",
|
||||
"module": "build/es2019/module.js",
|
||||
"name": "broker-factory",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "https://github.com/chrisguttandin/broker-factory.git"
|
||||
},
|
||||
"scripts": {
|
||||
"build": "rimraf build/* && tsc --project src/tsconfig.json && rollup --config config/rollup/bundle.mjs",
|
||||
"lint": "npm run lint:config && npm run lint:src && npm run lint:test",
|
||||
"lint:config": "eslint --config config/eslint/config.json --ext .cjs --ext .js --ext .mjs --report-unused-disable-directives config/",
|
||||
"lint:src": "tslint --config config/tslint/src.json --project src/tsconfig.json src/*.ts src/**/*.ts",
|
||||
"lint:test": "eslint --config config/eslint/test.json --ext .js --report-unused-disable-directives test/",
|
||||
"prepare": "husky",
|
||||
"prepublishOnly": "npm run build",
|
||||
"test": "npm run lint && npm run build && npm run test:unit",
|
||||
"test:unit": "if [ \"$TYPE\" = \"\" -o \"$TYPE\" = \"unit\" ]; then npx vitest --config config/vitest/unit.ts; fi"
|
||||
},
|
||||
"types": "build/es2019/module.d.ts",
|
||||
"version": "3.1.14"
|
||||
}
|
||||
+69
@@ -0,0 +1,69 @@
|
||||
import type { generateUniqueNumber as generateUniqueNumberFunction } from 'fast-unique-numbers';
|
||||
import { IWorkerDefinition, IWorkerErrorMessage, IWorkerResultMessage } from 'worker-factory';
|
||||
import type { isMessagePort as isMessagePortFunction } from '../guards/message-port';
|
||||
import { IBrokerDefinition, IDefaultBrokerDefinition, IWorkerEvent } from '../interfaces';
|
||||
import { TBrokerImplementation } from '../types';
|
||||
import type { createCreateOrGetOngoingRequests } from './create-or-get-ongoing-requests';
|
||||
import type { createExtendBrokerImplementation } from './extend-broker-implementation';
|
||||
|
||||
export const createBrokerFactory =
|
||||
(
|
||||
createOrGetOngoingRequests: ReturnType<typeof createCreateOrGetOngoingRequests>,
|
||||
extendBrokerImplementation: ReturnType<typeof createExtendBrokerImplementation>,
|
||||
generateUniqueNumber: typeof generateUniqueNumberFunction,
|
||||
isMessagePort: typeof isMessagePortFunction
|
||||
) =>
|
||||
<T extends IBrokerDefinition, U extends IWorkerDefinition>(
|
||||
brokerImplementation: TBrokerImplementation<T, U>
|
||||
): ((sender: MessagePort | Worker) => T & IDefaultBrokerDefinition) => {
|
||||
const fullBrokerImplementation = extendBrokerImplementation(brokerImplementation);
|
||||
|
||||
return (sender: MessagePort | Worker) => {
|
||||
const ongoingRequests = createOrGetOngoingRequests(sender);
|
||||
|
||||
sender.addEventListener('message', <EventListener>(({ data: message }: IWorkerEvent) => {
|
||||
const { id } = message;
|
||||
|
||||
if (id !== null && ongoingRequests.has(id)) {
|
||||
const { reject, resolve } = <{ reject: Function; resolve: Function }>ongoingRequests.get(id);
|
||||
|
||||
ongoingRequests.delete(id);
|
||||
|
||||
if ((<IWorkerErrorMessage>message).error === undefined) {
|
||||
resolve((<IWorkerResultMessage>message).result);
|
||||
} else {
|
||||
reject(new Error((<IWorkerErrorMessage>message).error.message));
|
||||
}
|
||||
}
|
||||
}));
|
||||
|
||||
if (isMessagePort(sender)) {
|
||||
sender.start();
|
||||
}
|
||||
|
||||
const call = <V extends keyof U>(method: V, params: U[V]['params'] = null, transferables: U[V]['transferables'] = []) => {
|
||||
return new Promise<U[V]['response']['result']>((resolve, reject) => {
|
||||
const id = generateUniqueNumber(ongoingRequests);
|
||||
|
||||
ongoingRequests.set(id, { reject, resolve });
|
||||
|
||||
if (params === null) {
|
||||
sender.postMessage({ id, method }, <Transferable[]>transferables);
|
||||
} else {
|
||||
sender.postMessage({ id, method, params }, <Transferable[]>transferables);
|
||||
}
|
||||
});
|
||||
};
|
||||
const notify = <V extends keyof U>(method: V, params: U[V]['params'], transferables: U[V]['transferables'] = []) => {
|
||||
sender.postMessage({ id: null, method, params }, <Transferable[]>transferables);
|
||||
};
|
||||
|
||||
let functions: object = {};
|
||||
|
||||
for (const [key, handler] of Object.entries(fullBrokerImplementation)) {
|
||||
functions = { ...functions, [key]: handler({ call, notify }) };
|
||||
}
|
||||
|
||||
return <T & IDefaultBrokerDefinition>{ ...functions };
|
||||
};
|
||||
};
|
||||
Generated
Vendored
+14
@@ -0,0 +1,14 @@
|
||||
export const createCreateOrGetOngoingRequests =
|
||||
(ongoingRequestsMap: WeakMap<MessagePort | Worker, Map<number, { reject: Function; resolve: Function }>>) =>
|
||||
(sender: MessagePort | Worker): Map<number, { reject: Function; resolve: Function }> => {
|
||||
if (ongoingRequestsMap.has(sender)) {
|
||||
// @todo TypeScript needs to be convinced that has() works as expected.
|
||||
return <Map<number, { reject: Function; resolve: Function }>>ongoingRequestsMap.get(sender);
|
||||
}
|
||||
|
||||
const ongoingRequests: Map<number, { reject: Function; resolve: Function }> = new Map();
|
||||
|
||||
ongoingRequestsMap.set(sender, ongoingRequests);
|
||||
|
||||
return ongoingRequests;
|
||||
};
|
||||
Generated
Vendored
+37
@@ -0,0 +1,37 @@
|
||||
import { IWorkerDefinition } from 'worker-factory';
|
||||
import { IBrokerDefinition, IDefaultBrokerDefinition } from '../interfaces';
|
||||
import { TBrokerImplementation } from '../types';
|
||||
|
||||
export const createExtendBrokerImplementation =
|
||||
(portMap: WeakMap<MessagePort, number>) =>
|
||||
<T extends IBrokerDefinition, U extends IWorkerDefinition>(
|
||||
partialBrokerImplementation: TBrokerImplementation<T, U>
|
||||
): TBrokerImplementation<T & IDefaultBrokerDefinition, U> =>
|
||||
<TBrokerImplementation<T & IDefaultBrokerDefinition, U>>{
|
||||
...partialBrokerImplementation,
|
||||
connect: ({ call }) => {
|
||||
return async (): Promise<MessagePort> => {
|
||||
const { port1, port2 } = new MessageChannel();
|
||||
|
||||
const portId = <number>await call('connect', { port: port1 }, [port1]);
|
||||
|
||||
portMap.set(port2, portId);
|
||||
|
||||
return port2;
|
||||
};
|
||||
},
|
||||
disconnect: ({ call }) => {
|
||||
return async (port: MessagePort): Promise<void> => {
|
||||
const portId = portMap.get(port);
|
||||
|
||||
if (portId === undefined) {
|
||||
throw new Error('The given port is not connected.');
|
||||
}
|
||||
|
||||
await call('disconnect', { portId });
|
||||
};
|
||||
},
|
||||
isSupported: ({ call }) => {
|
||||
return () => call('isSupported');
|
||||
}
|
||||
};
|
||||
+3
@@ -0,0 +1,3 @@
|
||||
export const isMessagePort = (sender: MessagePort | Worker): sender is MessagePort => {
|
||||
return typeof (<MessagePort>sender).start === 'function';
|
||||
};
|
||||
+7
@@ -0,0 +1,7 @@
|
||||
import { IWorkerDefinition } from 'worker-factory';
|
||||
|
||||
export interface IBrokerActions<T extends IWorkerDefinition> {
|
||||
call<U extends keyof T>(method: U, params?: T[U]['params'], transferables?: T[U]['transferables']): Promise<T[U]['response']['result']>;
|
||||
|
||||
notify<U extends keyof T>(method: U, params: T[U]['params'], transferables?: T[U]['transferables']): void;
|
||||
}
|
||||
+3
@@ -0,0 +1,3 @@
|
||||
export interface IBrokerDefinition {
|
||||
[method: string]: (...args: any[]) => any; // tslint:disable-line:invalid-void
|
||||
}
|
||||
Generated
Vendored
+9
@@ -0,0 +1,9 @@
|
||||
import { IBrokerDefinition } from './broker-definition';
|
||||
|
||||
export interface IDefaultBrokerDefinition extends IBrokerDefinition {
|
||||
connect(): Promise<MessagePort>;
|
||||
|
||||
disconnect(port: MessagePort): Promise<void>;
|
||||
|
||||
isSupported(): Promise<boolean>;
|
||||
}
|
||||
+4
@@ -0,0 +1,4 @@
|
||||
export * from './broker-actions';
|
||||
export * from './broker-definition';
|
||||
export * from './default-broker-definition';
|
||||
export * from './worker-event';
|
||||
+5
@@ -0,0 +1,5 @@
|
||||
import { TWorkerMessage } from 'worker-factory';
|
||||
|
||||
export interface IWorkerEvent extends Event {
|
||||
data: TWorkerMessage;
|
||||
}
|
||||
+19
@@ -0,0 +1,19 @@
|
||||
import { generateUniqueNumber } from 'fast-unique-numbers';
|
||||
import { createBrokerFactory } from './factories/create-broker';
|
||||
import { createCreateOrGetOngoingRequests } from './factories/create-or-get-ongoing-requests';
|
||||
import { createExtendBrokerImplementation } from './factories/extend-broker-implementation';
|
||||
import { isMessagePort } from './guards/message-port';
|
||||
|
||||
/*
|
||||
* @todo Explicitly referencing the barrel file seems to be necessary when enabling the
|
||||
* isolatedModules compiler option.
|
||||
*/
|
||||
export * from './interfaces/index';
|
||||
export * from './types/index';
|
||||
|
||||
export const createBroker = createBrokerFactory(
|
||||
createCreateOrGetOngoingRequests(new WeakMap<MessagePort | Worker, Map<number, { reject: Function; resolve: Function }>>()),
|
||||
createExtendBrokerImplementation(new WeakMap<MessagePort, number>()),
|
||||
generateUniqueNumber,
|
||||
isMessagePort
|
||||
);
|
||||
+6
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"isolatedModules": true
|
||||
},
|
||||
"extends": "tsconfig-holy-grail/src/tsconfig-browser"
|
||||
}
|
||||
+6
@@ -0,0 +1,6 @@
|
||||
import { IWorkerDefinition } from 'worker-factory';
|
||||
import { IBrokerActions, IBrokerDefinition } from '../interfaces';
|
||||
|
||||
export type TBrokerImplementation<T extends IBrokerDefinition, U extends IWorkerDefinition> = {
|
||||
[P in keyof T]: (actions: IBrokerActions<U>) => T[P];
|
||||
};
|
||||
+1
@@ -0,0 +1 @@
|
||||
export * from './broker-implementation';
|
||||
Reference in New Issue
Block a user