web-background 1.0.5 โ†’ 1.0.7

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/README.md CHANGED
@@ -117,33 +117,3 @@ type FunctionInBackground<Fn> = (
117
117
  - Web APIs (`fetch`, `localStorage`, etc. have separate worker support)
118
118
  - Non-serializable data (functions, Symbols, undefined, etc.)
119
119
  - ES6 module imports (context passing required in bundler environments)
120
-
121
- ### ๐Ÿ’ก Best Practices
122
-
123
- 1. **Context is optional**:
124
-
125
- ```typescript
126
- // โœ… Pure function without external variables
127
- const pureWorker = background((data) => complexCalculation(data));
128
-
129
- // โœ… Pass context when needed (more stable)
130
- const contextWorker = background((data) => processWithConfig(data, config), {
131
- config,
132
- });
133
- ```
134
-
135
- 2. **Use only for heavy computations**:
136
-
137
- ```typescript
138
- // โŒ Simple operations
139
- const add = background((a, b) => a + b);
140
-
141
- // โœ… CPU intensive operations
142
- const processLargeArray = background((data) => {
143
- // Complex processing logic...
144
- });
145
- ```
146
-
147
- 3. **Keep data size appropriate**:
148
- - Large objects or complex contexts cause serialization overhead
149
- - Pass only necessary data for performance optimization
package/dist/index.js CHANGED
@@ -1 +1 @@
1
- class e extends Worker{postMessage(e){super.postMessage(e)}addEventListener(e,t){super.addEventListener(e,t)}}class t extends e{constructor(e,t){super(e,t)}request(e){return new Promise((t=>{const n=({data:e})=>{t(e),this.removeEventListener("message",n)};this.postMessage(e),this.addEventListener("message",n)}))}}"function"==typeof SuppressedError&&SuppressedError;class n{constructor(){this.store=new Map}get(e){return this.store.get(e)}set(e,t){this.store.set(e,t)}delete(e){this.store.delete(e)}clear(){this.store.clear()}size(){return this.store.size}}const o=new n,r=new class extends n{deleteByPrefix(e){for(const[t,n]of this.store)t.startsWith(e)&&this.delete(t)}},s=new n,i=new n;class c{static increment(e){const t=i.get(e)||0;i.set(e,t+1)}static decrement(e){const t=i.get(e)||0;return t<=1?(i.delete(e),!0):(i.set(e,t-1),!1)}static getCount(e){return i.get(e)||0}}class a{static getContext(e){return o.get(e)}static setContext(e,t){o.set(e,t),c.increment(e)}static getSerialization(e){return r.get(e)}static setSerialization(e,t){r.set(e,t);const n=e.split(":")[0];c.increment(n)}static getIdentifiers(e){return s.get(e)}static setIdentifiers(e,t){s.set(e,t),c.increment(e)}static decrementUsage(e){c.decrement(e)&&(o.delete(e),s.delete(e),r.deleteByPrefix(e+":"),console.log(`'${e.substring(0,50)}...' ํ•จ์ˆ˜ ์บ์‹œ ์ •๋ฆฌ ์™„๋ฃŒ`))}static getCacheStats(){return{contextCacheSize:o.size(),serializationCacheSize:r.size(),identifierCacheSize:s.size(),activeFunctions:i.size()}}static clearAllCaches(){o.clear(),r.clear(),s.clear(),i.clear(),console.log("๋ชจ๋“  ์บ์‹œ๊ฐ€ ์ •๋ฆฌ๋˜์—ˆ์Šต๋‹ˆ๋‹ค")}}const l=new Set(["function","return","var","let","const","if","else","for","while","do","break","continue","switch","case","default","try","catch","finally","throw","new","this","typeof","instanceof","in","of","class","extends","super","async","await","yield","true","false","null","undefined","delete","void","with","export","import","from"]),f=new Set(["console","Math","Date","JSON","Array","Object","String","Number","Boolean","RegExp","Error","Promise","setTimeout","setInterval","clearTimeout","clearInterval","parseInt","parseFloat","isNaN","isFinite","decodeURIComponent","encodeURIComponent","window","document","global","process","self","URL","URLSearchParams","fetch","XMLHttpRequest","localStorage","sessionStorage","location","history","navigator","Blob","File","FileReader","FormData","Headers","Request","Response","AbortController","AbortSignal","crypto","performance","requestAnimationFrame","cancelAnimationFrame","requestIdleCallback","cancelIdleCallback"]);function u(e){const t=a.getIdentifiers(e);if(t)return t;const n=new Set,o=/\b[a-zA-Z_$][a-zA-Z0-9_$]*\b/g;let r;for(;null!==(r=o.exec(e));){const t=r[0];d(t)||p(t,e)||y(t,e)||n.add(t)}const s=Array.from(n);return a.setIdentifiers(e,s),s}function d(e){return l.has(e)}function g(e){return f.has(e)}function p(e,t){return[new RegExp(`function\\s*\\([^)]*\\b${e}\\b[^)]*\\)`),new RegExp(`\\([^)]*\\b${e}\\b[^)]*\\)\\s*=>`),new RegExp(`^\\s*${e}\\s*=>`),new RegExp(`async\\s+\\([^)]*\\b${e}\\b[^)]*\\)\\s*=>`),new RegExp(`async\\s+${e}\\s*=>`)].some((e=>e.test(t)))}function y(e,t){return[new RegExp(`(?:var|let|const)\\s+${e}\\b`),new RegExp(`(?:var|let|const)\\s+\\{[^}]*\\b${e}\\b[^}]*\\}`),new RegExp(`function\\s+${e}\\b`)].some((e=>e.test(t)))}function w(e){if(null==e)return!0;if("boolean"==typeof e||"number"==typeof e||"string"==typeof e)return!0;if("function"==typeof e||"symbol"==typeof e||"bigint"==typeof e)return!1;if(Array.isArray(e))return e.every((e=>w(e)));if("object"==typeof e)try{return JSON.stringify(e),!0}catch(e){return!1}return!1}function h(e,t){const n=`${e.toString()}:${JSON.stringify(t||{})}`,o=a.getSerialization(n);if(o)return o;const r=function(e,t){const n=e.toString();let o="(function() {\n";const r=Object.entries(t),s=r.filter((([,e])=>"function"!=typeof e)),i=r.filter((([,e])=>"function"==typeof e));s.forEach((([e,t])=>{try{o+=` const ${e} = ${JSON.stringify(t)};\n`}catch(t){o+=` const ${e} = undefined;\n`}})),i.forEach((([e,t])=>{"function"==typeof t&&(o+=` const ${e} = ${t.toString()};\n`)})),r.length>0&&(o+="\n");return o+=` return ${n};\n`,o+="})()",o}(e,t||{});return a.setSerialization(n,r),r}class b{static fromModule(e,t){var{module:n,context:o}=t,r=function(e,t){var n={};for(var o in e)Object.prototype.hasOwnProperty.call(e,o)&&t.indexOf(o)<0&&(n[o]=e[o]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(o=Object.getOwnPropertySymbols(e);r<o.length;r++)t.indexOf(o[r])<0&&Object.prototype.propertyIsEnumerable.call(e,o[r])&&(n[o[r]]=e[o[r]])}return n}(t,["module","context"]);const s=o||function(e){const t=u(e.toString()),n={};return t.forEach((e=>{if(!g(e))try{const t=globalThis[e]||("undefined"!=typeof window?window[e]:void 0);void 0!==t&&("function"==typeof t||w(t))&&(n[e]=t)}catch(e){}})),n}(n),i=h(n,s);console.log(i);const c=`\n self.addEventListener('message', async event => {\n const func = ${i};\n const result = await func(${n.length>1?"...event.data":"event.data"});\n self.postMessage(result);\n });\n `.trim(),a=new Blob([c]),l=URL.createObjectURL(a),f=new e(l,r),d=f.terminate;return f.terminate=()=>{d.call(f),URL.revokeObjectURL(l)},f}}const m=new FinalizationRegistry((e=>{e.worker.terminate(),a.decrementUsage(e.funcStr),console.log("์›Œ์ปค ์ •๋ฆฌ ๋ฐ ์บ์‹œ ์ •๋ฆฌ ์™„๋ฃŒ")}));function S(e){const t=e.toString(),n=a.getContext(t);if(n)return console.log("์บ์‹œ๋œ ์ปจํ…์ŠคํŠธ ์‚ฌ์šฉ:",n),n;const o={};console.log("ํ•จ์ˆ˜ ๋ฌธ์ž์—ด:",t);const r=u(t),s=function(e){const t=e.match(/function[^(]*\(([^)]*)\)|^\s*\(([^)]*)\)\s*=>|^\s*([a-zA-Z_$][a-zA-Z0-9_$]*)\s*=>/),n=new Set;t&&(t[1]||t[2]||t[3]||"").split(",").forEach((e=>{const t=e.trim().split("=")[0].trim();t&&/^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(t)&&n.add(t)}));return n}(t),i=function(e){const t=new Set,n=/(?:var|let|const)\s+([a-zA-Z_$][a-zA-Z0-9_$]*)/g;let o;for(;null!==(o=n.exec(e));)t.add(o[1]);return t}(t),c=function(){const e={};return"undefined"!=typeof window&&Object.getOwnPropertyNames(window).forEach((t=>{try{if(!g(t)){const n=Object.getOwnPropertyDescriptor(window,t);if(n&&n.configurable){const n=window[t];void 0!==n&&(e[t]=n)}}}catch(e){}})),"undefined"!=typeof globalThis&&Object.getOwnPropertyNames(globalThis).forEach((t=>{try{g(t)||t in e||(e[t]=globalThis[t])}catch(e){}})),e}();return console.log("์ถ”์ถœ๋œ ์‹๋ณ„์ž๋“ค:",r),console.log("๋งค๊ฐœ๋ณ€์ˆ˜๋“ค:",Array.from(s)),console.log("๋กœ์ปฌ ๋ณ€์ˆ˜๋“ค:",Array.from(i)),console.log("ํ˜ธ์ถœ์ž ์Šค์ฝ”ํ”„:",Object.keys(c)),r.forEach((e=>{if(!(d(e)||g(e)||s.has(e)||i.has(e))){if(console.log(`'${e}' ๊ฒ€์‚ฌ ์ค‘...`),e in c){const t=c[e];return console.log(`ํ˜ธ์ถœ์ž ์Šค์ฝ”ํ”„์—์„œ '${e}' ๋ฐœ๊ฒฌ:`,typeof t),void(("function"==typeof t||w(t))&&(o[e]=t))}try{let t;"undefined"!=typeof window&&e in window?(t=window[e],console.log(`window์—์„œ '${e}' ๋ฐœ๊ฒฌ:`,typeof t)):"undefined"!=typeof globalThis&&e in globalThis&&(t=globalThis[e],console.log(`globalThis์—์„œ '${e}' ๋ฐœ๊ฒฌ:`,typeof t)),void 0!==t&&("function"==typeof t||w(t))&&(o[e]=t)}catch(t){console.log(`'${e}' ์ ‘๊ทผ ์‹คํŒจ:`,t)}}})),console.log("์ตœ์ข… ์ปจํ…์ŠคํŠธ:",o),a.setContext(t,o),o}function $(e,n){const o=void 0!==n?n:S(e);console.log("์ตœ์ข… ์‚ฌ์šฉ๋  ์ปจํ…์ŠคํŠธ:",o);let r=null;return function n(...s){if("undefined"==typeof window)throw new Error("[web-background] You must use background in browser");return null==r&&(r=b.fromModule(t,{module:e,context:o}),m.register(n,{worker:r,funcStr:e.toString()})),r.request.call(r,s.length>1?s:s[0])}}export{$ as background};
1
+ class e extends Worker{postMessage(e){super.postMessage(e)}addEventListener(e,t){super.addEventListener(e,t)}}class t extends e{constructor(e,t){super(e,t)}request(e){return new Promise((t=>{const n=({data:e})=>{t(e),this.removeEventListener("message",n)};this.postMessage(e),this.addEventListener("message",n)}))}}function n(e,t){return function(e,t){const n=e.toString();let r="(function() {\n";const o=Object.entries(t),s=o.filter((([,e])=>"function"!=typeof e)),c=o.filter((([,e])=>"function"==typeof e));s.forEach((([e,t])=>{try{r+=` const ${e} = ${JSON.stringify(t)};\n`}catch(t){r+=` const ${e} = undefined;\n`}})),c.forEach((([e,t])=>{"function"==typeof t&&(r+=` const ${e} = ${t.toString()};\n`)})),o.length>0&&(r+="\n");return r+=` return ${n};\n`,r+="})()",r}(e,t||{})}"function"==typeof SuppressedError&&SuppressedError;class r{static fromModule(e,t){var{module:r,context:o}=t,s=function(e,t){var n={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var o=0;for(r=Object.getOwnPropertySymbols(e);o<r.length;o++)t.indexOf(r[o])<0&&Object.prototype.propertyIsEnumerable.call(e,r[o])&&(n[r[o]]=e[r[o]])}return n}(t,["module","context"]);const c=`\n self.addEventListener('message', async event => {\n const func = ${n(r,o)};\n const result = await func(${r.length>1?"...event.data":"event.data"});\n self.postMessage(result);\n });\n `.trim(),i=new Blob([c]),u=URL.createObjectURL(i),a=new e(u,s),l=a.terminate;return a.terminate=()=>{l.call(a),URL.revokeObjectURL(u)},a}}const o=new FinalizationRegistry((e=>e.terminate()));function s(e,n){let s=null;return function c(...i){if("undefined"==typeof window)throw new Error("[web-background] You must use background in browser");return null==s&&(s=r.fromModule(t,{module:e,context:n}),o.register(c,s)),s.request.call(s,i.length>1?i:i[0])}}export{s as background};
@@ -1,3 +1,2 @@
1
1
  export declare function serializeFunction(func: Function, providedContext?: Record<string, any>): string;
2
2
  export declare function deserializeFunction(serializedFunc: string): Function;
3
- export declare function extractClosureContext(func: Function): Record<string, any>;
@@ -1,4 +1 @@
1
- export declare const workerCleanupRegistry: FinalizationRegistry<{
2
- worker: Worker;
3
- funcStr: string;
4
- }>;
1
+ export declare const workerCleanupRegistry: FinalizationRegistry<Worker>;
package/package.json CHANGED
@@ -7,7 +7,7 @@
7
7
  "Background",
8
8
  "Web Background"
9
9
  ],
10
- "version": "1.0.5",
10
+ "version": "1.0.7",
11
11
  "main": "dist/index.js",
12
12
  "module": "dist/index.js",
13
13
  "type": "module",