web-background 0.0.1

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,3 @@
1
+ {
2
+ "typescript.tsdk": "node_modules/typescript/lib"
3
+ }
package/README.md ADDED
@@ -0,0 +1,57 @@
1
+ # Web Background
2
+ This module is implemented as a web walker and is available in web browsers.
3
+ 해당 모듈은 웹 워커로 구현되며 브라우저에서 사용할 수 있습니다.
4
+
5
+ It runs in an isolated environment and cannot be referenced by external variables and external module.
6
+ 격리된 환경에서 실행되므로 외부의 변수에 참조하지 못합니다.
7
+
8
+ In most cases, this module is not required.
9
+ Recommended for long task
10
+ 대부분의 경우 이 모듈을 사용할 필요는 없으나, long task를 처리해야 할 경우 사용할 것을 추천합니다.
11
+
12
+ Most WebAPIs including DOM APIs are cannot be used Becuase they are run in Web Worker.
13
+ WebWorker에서 실행되므로 DOM API를 포함한 WebAPI를 사용하지 못합니다.
14
+
15
+ ## Example
16
+
17
+ **worker**
18
+ ```ts
19
+ async function runLongTask () {
20
+ const getCoordinate = background((imageData: ImageData) => {
21
+ const { data, width } = imageData;
22
+
23
+ let [
24
+ minX, minY,
25
+ maxX, maxY
26
+ ] = [Infinity, Infinity, 0, 0];
27
+
28
+ for(let i = 0, leng = data.length; i < leng; i += 4) {
29
+ const [r, g, b, a] = data.slice(i, i+4);
30
+ const isFilled = Math.max(r, g, b, a) > 0;
31
+
32
+ if(isFilled) {
33
+ const y = Math.floor(i / 4 / width);
34
+ const x = Math.floor(i / 4 - width * y);
35
+
36
+ minX = Math.min(minX, x);
37
+ maxX = Math.max(maxX, x);
38
+
39
+ minY = Math.min(minY, y);
40
+ maxY = Math.max(maxY, y);
41
+ }
42
+ }
43
+
44
+ return {
45
+ x: minX === Infinity ? 0 : minX,
46
+ width: maxX,
47
+ y: minY === Infinity ? 0 : minY,
48
+ height: maxY,
49
+ };
50
+ })
51
+
52
+ const coordiate = await getCoordinate(
53
+ canvas.getContext('2d').getImageData(0, 0, 1000, 1000)
54
+ )
55
+ }
56
+ ```
57
+
@@ -0,0 +1,7 @@
1
+ type ReturnFn<ReturnValue> = () => ReturnValue;
2
+ type ReturnFnWithPayload<Payload, ReturnValue> = (payload: Payload) => ReturnValue;
3
+ export declare function background<Payload = never, ReturnValue = void>(fn: (payload: Payload) => ReturnValue): {
4
+ (): Promise<ReturnValue>;
5
+ (payload: Payload): Promise<ReturnValue>;
6
+ } | (Payload extends never ? ReturnFn<Promise<ReturnValue>> : ReturnFnWithPayload<Payload, Promise<ReturnValue>>);
7
+ export {};
@@ -0,0 +1 @@
1
+ export { background } from './background';
package/dist/index.js ADDED
@@ -0,0 +1,97 @@
1
+ class TypedWorker extends Worker {
2
+ postMessage(payload) {
3
+ super.postMessage(payload);
4
+ }
5
+ addEventListener(type, observer) {
6
+ super.addEventListener(type, observer);
7
+ }
8
+ }
9
+
10
+ class UtilWorker extends TypedWorker {
11
+ constructor(scriptURL, options) {
12
+ super(scriptURL, options);
13
+ }
14
+ subscribe(observer) {
15
+ const onMessage = (event) => {
16
+ observer(event.data);
17
+ };
18
+ this.addEventListener('message', onMessage);
19
+ return () => {
20
+ this.removeEventListener('message', onMessage);
21
+ };
22
+ }
23
+ request(payload) {
24
+ return new Promise(resolve => {
25
+ const onMessage = ({ data }) => {
26
+ resolve(data);
27
+ this.removeEventListener('message', onMessage);
28
+ };
29
+ this.postMessage(payload);
30
+ this.addEventListener('message', onMessage);
31
+ });
32
+ }
33
+ }
34
+
35
+ /******************************************************************************
36
+ Copyright (c) Microsoft Corporation.
37
+
38
+ Permission to use, copy, modify, and/or distribute this software for any
39
+ purpose with or without fee is hereby granted.
40
+
41
+ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
42
+ REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
43
+ AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
44
+ INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
45
+ LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
46
+ OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
47
+ PERFORMANCE OF THIS SOFTWARE.
48
+ ***************************************************************************** */
49
+ /* global Reflect, Promise, SuppressedError, Symbol */
50
+
51
+
52
+ function __rest(s, e) {
53
+ var t = {};
54
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
55
+ t[p] = s[p];
56
+ if (s != null && typeof Object.getOwnPropertySymbols === "function")
57
+ for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
58
+ if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
59
+ t[p[i]] = s[p[i]];
60
+ }
61
+ return t;
62
+ }
63
+
64
+ typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) {
65
+ var e = new Error(message);
66
+ return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
67
+ };
68
+
69
+ class WorkerBuilder {
70
+ static fromModule(Worker, _a) {
71
+ var { module } = _a, options = __rest(_a, ["module"]);
72
+ const code = `
73
+ self.addEventListener('message', event => {
74
+ const result = (${module.toString()})(event.data);
75
+
76
+ self.postMessage(result);
77
+ });
78
+ `.trim();
79
+ const blob = new Blob([code]);
80
+ return new Worker(URL.createObjectURL(blob), options);
81
+ }
82
+ }
83
+
84
+ function background(fn) {
85
+ function createWorker() {
86
+ return WorkerBuilder.fromModule((UtilWorker), { module: fn, type: 'module' });
87
+ }
88
+ if (typeof window === 'undefined') {
89
+ function runWithCreatingWorker(payload) {
90
+ return createWorker().request(payload);
91
+ }
92
+ return runWithCreatingWorker;
93
+ }
94
+ return createWorker().request;
95
+ }
96
+
97
+ export { background };
@@ -0,0 +1,7 @@
1
+ export interface TypedMessageEvent<Data = any> extends MessageEvent {
2
+ data: Data;
3
+ }
4
+ export declare class TypedWorker<Payload, Response> extends Worker {
5
+ postMessage<T = Payload>(payload: T): void;
6
+ addEventListener<R = Response>(type: 'message' | 'error' | 'messageerror', observer: (this: Worker, event: TypedMessageEvent<R>) => void): void;
7
+ }
@@ -0,0 +1,7 @@
1
+ import { TypedWorker } from "./TypedWorker";
2
+ export declare class UtilWorker<Payload = never, Result = void> extends TypedWorker<Payload, Result> {
3
+ constructor(scriptURL: string | URL, options?: WorkerOptions);
4
+ subscribe(observer: (response: Result) => void): () => void;
5
+ request(): Promise<Result>;
6
+ request(payload: Payload): Promise<Result>;
7
+ }
@@ -0,0 +1,11 @@
1
+ interface WorkerConstructor<Worker> {
2
+ new (scriptURL: string | URL, options?: WorkerOptions): Worker;
3
+ prototype: Worker;
4
+ }
5
+ interface Options extends WorkerOptions {
6
+ module: (...args: any[]) => any;
7
+ }
8
+ export declare class WorkerBuilder {
9
+ static fromModule<W extends Worker>(Worker: WorkerConstructor<W>, { module, ...options }: Options): W;
10
+ }
11
+ export {};
package/package.json ADDED
@@ -0,0 +1,27 @@
1
+ {
2
+ "name": "web-background",
3
+ "description": "Running background in browser Worker",
4
+ "keywords": [
5
+ "Web Worker",
6
+ "Worker",
7
+ "Background"
8
+ ],
9
+ "version": "0.0.1",
10
+ "main": "dist/index.js",
11
+ "module": "dist/index.js",
12
+ "type": "module",
13
+ "license": "MIT",
14
+ "scripts": {
15
+ "build": "rollup -c"
16
+ },
17
+ "devDependencies": {
18
+ "@babel/core": "^7.23.3",
19
+ "@babel/preset-env": "^7.23.3",
20
+ "@rollup/plugin-babel": "^6.0.4",
21
+ "@rollup/plugin-node-resolve": "^15.2.3",
22
+ "rollup": "^4.4.0",
23
+ "rollup-plugin-typescript2": "^0.36.0",
24
+ "typescript": "5.2"
25
+ },
26
+ "dependencies": {}
27
+ }