@squoosh-kit/resize 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.
- package/README.md +71 -0
- package/dist/bridge.d.ts +10 -0
- package/dist/index.d.ts +23 -0
- package/dist/index.js +5 -0
- package/dist/index.js.map +12 -0
- package/dist/resize.worker.d.ts +6 -0
- package/dist/resize.worker.js +6 -0
- package/dist/resize.worker.js.map +10 -0
- package/dist/types.d.ts +9 -0
- package/dist/wasm/squoosh_resize.d.ts +34 -0
- package/dist/wasm/squoosh_resize.js +120 -0
- package/dist/wasm/squoosh_resize_bg.wasm +0 -0
- package/dist/wasm/squoosh_resize_bg.wasm.d.ts +7 -0
- package/package.json +41 -0
package/README.md
ADDED
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
# @squoosh-kit/resize
|
|
2
|
+
|
|
3
|
+
[](https://badge.fury.io/js/%40squoosh-kit%2Fresize)
|
|
4
|
+
|
|
5
|
+
High-quality image resizing functionality from Google's Squoosh, packaged for modern JavaScript environments.
|
|
6
|
+
|
|
7
|
+
This package provides fast image resizing using WebAssembly (Lanczos3), offloading the work to a Web Worker to avoid blocking the main thread.
|
|
8
|
+
|
|
9
|
+
## Installation
|
|
10
|
+
|
|
11
|
+
```bash
|
|
12
|
+
bun add @squoosh-kit/resize
|
|
13
|
+
# or
|
|
14
|
+
npm install @squoosh-kit/resize
|
|
15
|
+
```
|
|
16
|
+
|
|
17
|
+
## Quick Start
|
|
18
|
+
|
|
19
|
+
```typescript
|
|
20
|
+
import { resize, createResizer } from '@squoosh-kit/resize';
|
|
21
|
+
import type { ImageInput, ResizeOptions } from '@squoosh-kit/runtime';
|
|
22
|
+
|
|
23
|
+
// Assume `imageData` is an object like { data: Uint8Array, width: number, height: number }
|
|
24
|
+
const imageData: ImageInput = /* ... */;
|
|
25
|
+
|
|
26
|
+
// Simple, one-off resizing
|
|
27
|
+
const resizedImage = await resize(
|
|
28
|
+
new AbortController().signal,
|
|
29
|
+
null,
|
|
30
|
+
imageData,
|
|
31
|
+
{ width: 800 } // height will be calculated to maintain aspect ratio
|
|
32
|
+
);
|
|
33
|
+
|
|
34
|
+
// For multiple operations, create a persistent resizer
|
|
35
|
+
const resizer = createResizer('worker'); // 'client' also available
|
|
36
|
+
const result = await resizer(
|
|
37
|
+
new AbortController().signal,
|
|
38
|
+
imageData,
|
|
39
|
+
{ width: 1024, height: 768 }
|
|
40
|
+
);
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
## API
|
|
44
|
+
|
|
45
|
+
### `resize(signal, workerBridge, imageData, options)`
|
|
46
|
+
|
|
47
|
+
- `signal`: `AbortSignal` to cancel the operation.
|
|
48
|
+
- `workerBridge`: (Optional) A `WorkerBridge` instance.
|
|
49
|
+
- `imageData`: `ImageInput` to resize.
|
|
50
|
+
- `options`: `ResizeOptions` for resizing.
|
|
51
|
+
- **Returns**: `Promise<ImageInput>`
|
|
52
|
+
|
|
53
|
+
### `createResizer(mode)`
|
|
54
|
+
|
|
55
|
+
- `mode`: `'worker'` or `'client'`.
|
|
56
|
+
- **Returns**: A reusable resizing function.
|
|
57
|
+
|
|
58
|
+
### `ResizeOptions`
|
|
59
|
+
|
|
60
|
+
```typescript
|
|
61
|
+
interface ResizeOptions {
|
|
62
|
+
width?: number;
|
|
63
|
+
height?: number;
|
|
64
|
+
premultiply?: boolean; // default: false
|
|
65
|
+
linearRGB?: boolean; // default: false
|
|
66
|
+
}
|
|
67
|
+
```
|
|
68
|
+
|
|
69
|
+
## License
|
|
70
|
+
|
|
71
|
+
MIT
|
package/dist/bridge.d.ts
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Bridge implementation for the Resize package, handling worker and client modes.
|
|
3
|
+
*/
|
|
4
|
+
import { type ImageInput } from '@squoosh-kit/runtime';
|
|
5
|
+
import type { ResizeOptions } from './types.ts';
|
|
6
|
+
interface ResizeBridge {
|
|
7
|
+
resize(signal: AbortSignal, image: ImageInput, options: ResizeOptions): Promise<ImageInput>;
|
|
8
|
+
}
|
|
9
|
+
export declare function createBridge(mode: 'worker' | 'client'): ResizeBridge;
|
|
10
|
+
export {};
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @squoosh-kit/resize public API
|
|
3
|
+
*/
|
|
4
|
+
import type { ImageInput } from '@squoosh-kit/runtime';
|
|
5
|
+
import type { ResizeOptions } from './types.ts';
|
|
6
|
+
export type { ImageInput, ResizeOptions };
|
|
7
|
+
/**
|
|
8
|
+
* Resizes an image. Defaults to 'worker' mode.
|
|
9
|
+
*
|
|
10
|
+
* @param signal - An AbortSignal to cancel the resizing operation.
|
|
11
|
+
* @param imageData - The image data to resize.
|
|
12
|
+
* @param options - Resize options.
|
|
13
|
+
* @returns A Promise resolving to the resized image data.
|
|
14
|
+
*/
|
|
15
|
+
export declare function resize(signal: AbortSignal, imageData: ImageInput, options: ResizeOptions): Promise<ImageInput>;
|
|
16
|
+
/**
|
|
17
|
+
* Creates a reusable resizer function for a specific execution mode.
|
|
18
|
+
*
|
|
19
|
+
* @param mode - The execution mode, either 'worker' or 'client'.
|
|
20
|
+
* @returns A function that resizes an image.
|
|
21
|
+
*/
|
|
22
|
+
export declare function createResizer(mode?: 'worker' | 'client'): (signal: AbortSignal, image: ImageInput, options: ResizeOptions) => Promise<ImageInput>;
|
|
23
|
+
export { resizeClient } from './resize.worker.js';
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import{a as o}from"./resize.worker.js";var G=0;async function U(i,m,z,u,g){return new Promise((R,W)=>{let P=++G;if(u?.aborted){W(new DOMException("Aborted","AbortError"));return}let c=(t)=>{let I=t.data;if(I.id!==P)return;if(console.log("\uD83D\uDD27 Worker call: Response received",I),B(),I.ok&&I.data!==void 0)console.log("\uD83D\uDD27 Worker call: Response data",I.data),R(I.data);else console.log("\uD83D\uDD27 Worker call: Response error",I.error),W(Error(I.error||"Unknown worker error"))},f=(t)=>{B(),W(Error(`Worker error: ${t.message}`))},x=()=>{B(),W(new DOMException("Aborted","AbortError"))},B=()=>{i.removeEventListener("message",c),i.removeEventListener("error",f),u?.removeEventListener("abort",x)};i.addEventListener("message",c),i.addEventListener("error",f),u?.addEventListener("abort",x);let A={type:m,id:P,payload:z};if(g&&g.length>0)i.postMessage(A,g);else i.postMessage(A)})}class k{async resize(i,m,z){return o(i,m,z)}}class F{worker=null;async getWorker(){if(!this.worker){let i=await import.meta.resolve("@squoosh-kit/resize/resize.worker.js");this.worker=new Worker(i,{type:"module"})}return this.worker}async resize(i,m,z){let u=await this.getWorker();console.log("worker",u);let g=m.data.buffer;console.log("buffer",g);try{let R=await U(u,"resize:run",{image:m,options:z},i,[g]);return console.log("result",R),R}catch(R){throw console.error("error",R),R}}}function O(i){return i==="client"?new k:new F}async function Q(i,m,z){return O("worker").resize(i,m,z)}function S(i="worker"){let m=O(i);return m.resize.bind(m)}export{o as resizeClient,Q as resize,S as createResizer};
|
|
3
|
+
|
|
4
|
+
//# debugId=F4303F2F711C28F164756E2164756E21
|
|
5
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../../runtime/src/worker-call.ts", "../src/bridge.ts", "../src/index.ts"],
|
|
4
|
+
"sourcesContent": [
|
|
5
|
+
"/**\n * Generic worker communication helper with support for transferables and AbortSignal\n */\n\nexport interface WorkerRequest<T = unknown> {\n type: string;\n id: number;\n payload: T;\n}\n\nexport interface WorkerResponse<T = unknown> {\n id: number;\n ok: boolean;\n data?: T;\n error?: string;\n}\n\nlet requestId = 0;\n\n/**\n * Call a worker with a typed request and wait for response\n *\n * @param worker - The worker instance to call\n * @param type - The message type\n * @param payload - The payload to send\n * @param signal - Optional AbortSignal to cancel the operation\n * @param transfer - Optional list of Transferable objects to transfer\n * @returns Promise that resolves with the worker's response data\n */\nexport async function callWorker<TPayload, TResponse>(\n worker: Worker,\n type: string,\n payload: TPayload,\n signal?: AbortSignal,\n transfer?: Transferable[]\n): Promise<TResponse> {\n return new Promise<TResponse>((resolve, reject) => {\n const id = ++requestId;\n\n // Check if already aborted\n if (signal?.aborted) {\n reject(new DOMException('Aborted', 'AbortError'));\n return;\n }\n\n const handleMessage = (event: MessageEvent) => {\n const response = event.data as WorkerResponse<TResponse>;\n if (response.id !== id) return;\n\n console.log('🔧 Worker call: Response received', response);\n cleanup();\n\n if (response.ok && response.data !== undefined) {\n console.log('🔧 Worker call: Response data', response.data);\n resolve(response.data);\n } else {\n console.log('🔧 Worker call: Response error', response.error);\n reject(new Error(response.error || 'Unknown worker error'));\n }\n };\n\n const handleError = (error: ErrorEvent) => {\n cleanup();\n reject(new Error(`Worker error: ${error.message}`));\n };\n\n const handleAbort = () => {\n cleanup();\n reject(new DOMException('Aborted', 'AbortError'));\n };\n\n const cleanup = () => {\n worker.removeEventListener('message', handleMessage);\n worker.removeEventListener('error', handleError);\n signal?.removeEventListener('abort', handleAbort);\n };\n\n // Set up listeners\n worker.addEventListener('message', handleMessage);\n worker.addEventListener('error', handleError);\n signal?.addEventListener('abort', handleAbort);\n\n // Send the request\n const request: WorkerRequest<TPayload> = { type, id, payload };\n\n if (transfer && transfer.length > 0) {\n worker.postMessage(request, transfer);\n } else {\n worker.postMessage(request);\n }\n });\n}\n",
|
|
6
|
+
"/**\n * Bridge implementation for the Resize package, handling worker and client modes.\n */\n\nimport { callWorker, type ImageInput } from '@squoosh-kit/runtime';\nimport { resizeClient } from './resize.worker.ts';\nimport type { ResizeOptions } from './types.ts';\n\ninterface ResizeBridge {\n resize(\n signal: AbortSignal,\n image: ImageInput,\n options: ResizeOptions\n ): Promise<ImageInput>;\n}\n\nclass ResizeClientBridge implements ResizeBridge {\n async resize(\n signal: AbortSignal,\n image: ImageInput,\n options: ResizeOptions\n ): Promise<ImageInput> {\n return resizeClient(signal, image, options);\n }\n}\n\nclass ResizeWorkerBridge implements ResizeBridge {\n private worker: Worker | null = null;\n private async getWorker(): Promise<Worker> {\n if (!this.worker) {\n const workerUrl = await import.meta.resolve(\n '@squoosh-kit/resize/resize.worker.js'\n );\n this.worker = new Worker(workerUrl, { type: 'module' });\n }\n return this.worker;\n }\n async resize(\n signal: AbortSignal,\n image: ImageInput,\n options: ResizeOptions\n ): Promise<ImageInput> {\n const worker = await this.getWorker();\n console.log('worker', worker);\n const buffer = image.data.buffer;\n console.log('buffer', buffer);\n\n try {\n const result = await callWorker<{ image: ImageInput; options: ResizeOptions }, ImageInput>(worker, 'resize:run', { image, options }, signal, [\n buffer as ArrayBuffer,\n ]);\n \n console.log('result', result);\n\n return result;\n } catch (error) {\n console.error('error', error);\n throw error;\n }\n }\n}\n\nexport function createBridge(mode: 'worker' | 'client'): ResizeBridge {\n return mode === 'client'\n ? new ResizeClientBridge()\n : new ResizeWorkerBridge();\n}\n",
|
|
7
|
+
"/**\n * @squoosh-kit/resize public API\n */\n\nimport type { ImageInput } from '@squoosh-kit/runtime';\nimport { createBridge } from './bridge.ts';\nimport type { ResizeOptions } from './types.ts';\n\nexport type { ImageInput, ResizeOptions };\n\n/**\n * Resizes an image. Defaults to 'worker' mode.\n *\n * @param signal - An AbortSignal to cancel the resizing operation.\n * @param imageData - The image data to resize.\n * @param options - Resize options.\n * @returns A Promise resolving to the resized image data.\n */\nexport async function resize(\n signal: AbortSignal,\n imageData: ImageInput,\n options: ResizeOptions\n): Promise<ImageInput> {\n // Always use a worker for a single, one-off call for best performance.\n const bridge = createBridge('worker');\n return bridge.resize(signal, imageData, options);\n}\n\n/**\n * Creates a reusable resizer function for a specific execution mode.\n *\n * @param mode - The execution mode, either 'worker' or 'client'.\n * @returns A function that resizes an image.\n */\nexport function createResizer(mode: 'worker' | 'client' = 'worker') {\n const bridge = createBridge(mode);\n return bridge.resize.bind(bridge);\n}\n\n// Export the client-side implementation for direct use by the bridge.\n// This is not intended for public consumption.\nexport { resizeClient } from './resize.worker.js';\n"
|
|
8
|
+
],
|
|
9
|
+
"mappings": ";uCAiBA,IAAI,EAAY,EAYhB,eAAsB,CAA+B,CACnD,EACA,EACA,EACA,EACA,EACoB,CACpB,OAAO,IAAI,QAAmB,CAAC,EAAS,IAAW,CACjD,IAAM,EAAK,EAAE,EAGb,GAAI,GAAQ,QAAS,CACnB,EAAO,IAAI,aAAa,UAAW,YAAY,CAAC,EAChD,OAGF,IAAM,EAAgB,CAAC,IAAwB,CAC7C,IAAM,EAAW,EAAM,KACvB,GAAI,EAAS,KAAO,EAAI,OAKxB,GAHA,QAAQ,IAAI,8CAAoC,CAAQ,EACxD,EAAQ,EAEJ,EAAS,IAAM,EAAS,OAAS,OACnC,QAAQ,IAAI,0CAAgC,EAAS,IAAI,EACzD,EAAQ,EAAS,IAAI,EAErB,aAAQ,IAAI,2CAAiC,EAAS,KAAK,EAC3D,EAAW,MAAM,EAAS,OAAS,sBAAsB,CAAC,GAIxD,EAAc,CAAC,IAAsB,CACzC,EAAQ,EACR,EAAW,MAAM,iBAAiB,EAAM,SAAS,CAAC,GAG9C,EAAc,IAAM,CACxB,EAAQ,EACR,EAAO,IAAI,aAAa,UAAW,YAAY,CAAC,GAG5C,EAAU,IAAM,CACpB,EAAO,oBAAoB,UAAW,CAAa,EACnD,EAAO,oBAAoB,QAAS,CAAW,EAC/C,GAAQ,oBAAoB,QAAS,CAAW,GAIlD,EAAO,iBAAiB,UAAW,CAAa,EAChD,EAAO,iBAAiB,QAAS,CAAW,EAC5C,GAAQ,iBAAiB,QAAS,CAAW,EAG7C,IAAM,EAAmC,CAAE,OAAM,KAAI,SAAQ,EAE7D,GAAI,GAAY,EAAS,OAAS,EAChC,EAAO,YAAY,EAAS,CAAQ,EAEpC,OAAO,YAAY,CAAO,EAE7B,EC1EH,MAAM,CAA2C,MACzC,OAAM,CACV,EACA,EACA,EACqB,CACrB,OAAO,EAAa,EAAQ,EAAO,CAAO,EAE9C,CAEA,MAAM,CAA2C,CACvC,OAAwB,UAClB,UAAS,EAAoB,CACzC,GAAI,CAAC,KAAK,OAAQ,CAChB,IAAM,EAAY,MAAM,YAAY,QAClC,sCACF,EACA,KAAK,OAAS,IAAI,OAAO,EAAW,CAAE,KAAM,QAAS,CAAC,EAExD,OAAO,KAAK,YAER,OAAM,CACV,EACA,EACA,EACqB,CACrB,IAAM,EAAS,MAAM,KAAK,UAAU,EACpC,QAAQ,IAAI,SAAU,CAAM,EAC5B,IAAM,EAAS,EAAM,KAAK,OAC1B,QAAQ,IAAI,SAAU,CAAM,EAE5B,GAAI,CACF,IAAM,EAAS,MAAM,EAAsE,EAAQ,aAAc,CAAE,QAAO,SAAQ,EAAG,EAAQ,CAC3I,CACF,CAAC,EAID,OAFA,QAAQ,IAAI,SAAU,CAAM,EAErB,EACP,MAAO,EAAO,CAEd,MADA,QAAQ,MAAM,QAAS,CAAK,EACtB,GAGZ,CAEO,SAAS,CAAY,CAAC,EAAyC,CACpE,OAAO,IAAS,SACZ,IAAI,EACJ,IAAI,EC/CV,eAAsB,CAAM,CAC1B,EACA,EACA,EACqB,CAGrB,OADe,EAAa,QAAQ,EACtB,OAAO,EAAQ,EAAW,CAAO,EAS1C,SAAS,CAAa,CAAC,EAA4B,SAAU,CAClE,IAAM,EAAS,EAAa,CAAI,EAChC,OAAO,EAAO,OAAO,KAAK,CAAM",
|
|
10
|
+
"debugId": "F4303F2F711C28F164756E2164756E21",
|
|
11
|
+
"names": []
|
|
12
|
+
}
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Resize processor - single-source worker/client implementation
|
|
3
|
+
*/
|
|
4
|
+
import { type ImageInput } from '@squoosh-kit/runtime';
|
|
5
|
+
import type { ResizeOptions } from './types.ts';
|
|
6
|
+
export declare function resizeClient(signal: AbortSignal, image: ImageInput, options: ResizeOptions): Promise<ImageInput>;
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
var K=null;async function O(){if(K)return;let j=import.meta.url.endsWith(".ts")?"../dist/wasm/resize":"./wasm/resize",x=await import.meta.resolve(`${j}/squoosh_resize.js`),F=await import(x);await F.default(fetch(new URL(`${j}/squoosh_resize_bg.wasm`,x))),K=F.resize}async function L(J,j){if(await O(),!K)throw Error("Resize module not initialized");let{data:x,width:F,height:B}=J,E=j.width??F,G=j.height??B;if(j.width&&!j.height)G=Math.round(B*j.width/F);else if(j.height&&!j.width)E=Math.round(F*j.height/B);if(E<=0||G<=0)throw Error("Invalid output dimensions");let N=x instanceof Uint8ClampedArray?new Uint8Array(x):x;return{data:K(N,F,B,E,G,Q(),j.premultiply?1:0,j.linearRGB?1:0),width:E,height:G}}async function T(J,j,x){if(J.aborted)throw new DOMException("Aborted","AbortError");return L(j,x)}function Q(){return 3}if(typeof self<"u")self.onmessage=async(J)=>{let{id:j,type:x,payload:F}=J.data,B={id:j,ok:!1};try{if(x!=="resize:run")throw Error(`Unknown message type: ${x}`);let E=await L(F.image,F.options);B.ok=!0,B.data=E;let G=E.data.buffer;if(G)self.postMessage(B,[G]);else self.postMessage(B)}catch(E){B.error=E instanceof Error?E.message:String(E),self.postMessage(B)}};export{T as resizeClient};
|
|
3
|
+
export{T as a};
|
|
4
|
+
|
|
5
|
+
//# debugId=A8894B48289E7C6764756E2164756E21
|
|
6
|
+
//# sourceMappingURL=resize.worker.js.map
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../src/resize.worker.ts"],
|
|
4
|
+
"sourcesContent": [
|
|
5
|
+
"/**\n * Resize processor - single-source worker/client implementation\n */\n\nimport {\n hasImageData,\n type WorkerRequest,\n type WorkerResponse,\n type ImageInput,\n} from '@squoosh-kit/runtime';\nimport type { ResizeOptions } from './types.ts';\n\n// Define the type locally to avoid module resolution issues with the linter\ntype SquooshWasmResize = (\n data: Uint8Array,\n input_width: number,\n input_height: number,\n output_width: number,\n output_height: number,\n typ_idx: number,\n premultiply: number,\n color_space_conversion: number,\n) => Uint8Array;\n\nlet wasmResize: SquooshWasmResize | null = null;\n\nasync function init(): Promise<void> {\n if (wasmResize) {\n return;\n }\n\n const isTest = import.meta.url.endsWith('.ts');\n const wasmDirectory = isTest ? '../dist/wasm/resize' : './wasm/resize';\n const modulePath = await import.meta.resolve(\n `${wasmDirectory}/squoosh_resize.js`,\n );\n const module = await import(modulePath);\n\n // Squoosh's WASM modules expect to be initialized with promises\n await module.default(\n fetch(new URL(`${wasmDirectory}/squoosh_resize_bg.wasm`, modulePath)),\n );\n wasmResize = module.resize;\n}\n\nasync function _resizeCore(\n image: ImageInput,\n options: ResizeOptions,\n): Promise<ImageInput> {\n await init();\n if (!wasmResize) {\n throw new Error('Resize module not initialized');\n }\n\n const { data, width: inputWidth, height: inputHeight } = image;\n\n let outputWidth = options.width ?? inputWidth;\n let outputHeight = options.height ?? inputHeight;\n\n if (options.width && !options.height) {\n outputHeight = Math.round((inputHeight * options.width) / inputWidth);\n } else if (options.height && !options.width) {\n outputWidth = Math.round((inputWidth * options.height) / inputHeight);\n }\n\n if (outputWidth <= 0 || outputHeight <= 0) {\n throw new Error('Invalid output dimensions');\n }\n\n const dataArray =\n data instanceof Uint8ClampedArray ? new Uint8Array(data) : data;\n\n const result = wasmResize(\n dataArray,\n inputWidth,\n inputHeight,\n outputWidth,\n outputHeight,\n getResizeMethod(),\n options.premultiply ? 1 : 0,\n options.linearRGB ? 1 : 0,\n );\n\n return {\n data: result,\n width: outputWidth,\n height: outputHeight,\n };\n}\n\nexport async function resizeClient(\n signal: AbortSignal,\n image: ImageInput,\n options: ResizeOptions,\n): Promise<ImageInput> {\n if (signal.aborted) {\n throw new DOMException('Aborted', 'AbortError');\n }\n return _resizeCore(image, options);\n}\n\n/**\n * Map ResizeOptions to the typ_idx parameter for the resize function\n * 0: Triangular, 1: Catrom, 2: Mitchell, 3: Lanczos3\n */\nfunction getResizeMethod(): number {\n // Default to Lanczos3 (highest quality)\n return 3;\n}\n\n/**\n * Worker message handler\n */\nif (typeof self !== 'undefined') {\n self.onmessage = async (\n event: MessageEvent<\n WorkerRequest<{ image: ImageInput; options: ResizeOptions }>\n >,\n ) => {\n const { id, type, payload } = event.data;\n\n const response: WorkerResponse<ImageInput> = { id, ok: false };\n\n try {\n if (type !== 'resize:run') {\n throw new Error(`Unknown message type: ${type}`);\n }\n\n const resultImage = await _resizeCore(payload.image, payload.options);\n\n response.ok = true;\n response.data = resultImage;\n\n const transferable = resultImage.data.buffer;\n if (transferable) {\n self.postMessage(response, [transferable as ArrayBuffer]);\n } else {\n self.postMessage(response);\n }\n } catch (error) {\n response.error = error instanceof Error ? error.message : String(error);\n self.postMessage(response);\n }\n };\n}\n"
|
|
6
|
+
],
|
|
7
|
+
"mappings": ";AAwBA,IAAI,EAAuC,KAE3C,eAAe,CAAI,EAAkB,CACnC,GAAI,EACF,OAIF,IAAM,EADS,YAAY,IAAI,SAAS,KAAK,EACd,sBAAwB,gBACjD,EAAa,MAAM,YAAY,QACnC,GAAG,qBACL,EACM,EAAS,MAAa,UAG5B,MAAM,EAAO,QACX,MAAM,IAAI,IAAI,GAAG,2BAAwC,CAAU,CAAC,CACtE,EACA,EAAa,EAAO,OAGtB,eAAe,CAAW,CACxB,EACA,EACqB,CAErB,GADA,MAAM,EAAK,EACP,CAAC,EACH,MAAU,MAAM,+BAA+B,EAGjD,IAAQ,OAAM,MAAO,EAAY,OAAQ,GAAgB,EAErD,EAAc,EAAQ,OAAS,EAC/B,EAAe,EAAQ,QAAU,EAErC,GAAI,EAAQ,OAAS,CAAC,EAAQ,OAC5B,EAAe,KAAK,MAAO,EAAc,EAAQ,MAAS,CAAU,EAC/D,QAAI,EAAQ,QAAU,CAAC,EAAQ,MACpC,EAAc,KAAK,MAAO,EAAa,EAAQ,OAAU,CAAW,EAGtE,GAAI,GAAe,GAAK,GAAgB,EACtC,MAAU,MAAM,2BAA2B,EAG7C,IAAM,EACJ,aAAgB,kBAAoB,IAAI,WAAW,CAAI,EAAI,EAa7D,MAAO,CACL,KAZa,EACb,EACA,EACA,EACA,EACA,EACA,EAAgB,EAChB,EAAQ,YAAc,EAAI,EAC1B,EAAQ,UAAY,EAAI,CAC1B,EAIE,MAAO,EACP,OAAQ,CACV,EAGF,eAAsB,CAAY,CAChC,EACA,EACA,EACqB,CACrB,GAAI,EAAO,QACT,MAAM,IAAI,aAAa,UAAW,YAAY,EAEhD,OAAO,EAAY,EAAO,CAAO,EAOnC,SAAS,CAAe,EAAW,CAEjC,MAAO,GAMT,GAAI,OAAO,KAAS,IAClB,KAAK,UAAY,MACf,IAGG,CACH,IAAQ,KAAI,OAAM,WAAY,EAAM,KAE9B,EAAuC,CAAE,KAAI,GAAI,EAAM,EAE7D,GAAI,CACF,GAAI,IAAS,aACX,MAAU,MAAM,yBAAyB,GAAM,EAGjD,IAAM,EAAc,MAAM,EAAY,EAAQ,MAAO,EAAQ,OAAO,EAEpE,EAAS,GAAK,GACd,EAAS,KAAO,EAEhB,IAAM,EAAe,EAAY,KAAK,OACtC,GAAI,EACF,KAAK,YAAY,EAAU,CAAC,CAA2B,CAAC,EAExD,UAAK,YAAY,CAAQ,EAE3B,MAAO,EAAO,CACd,EAAS,MAAQ,aAAiB,MAAQ,EAAM,QAAU,OAAO,CAAK,EACtE,KAAK,YAAY,CAAQ",
|
|
8
|
+
"debugId": "A8894B48289E7C6764756E2164756E21",
|
|
9
|
+
"names": []
|
|
10
|
+
}
|
package/dist/types.d.ts
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
/* tslint:disable */
|
|
2
|
+
/* eslint-disable */
|
|
3
|
+
/**
|
|
4
|
+
* @param {Uint8Array} input_image
|
|
5
|
+
* @param {number} input_width
|
|
6
|
+
* @param {number} input_height
|
|
7
|
+
* @param {number} output_width
|
|
8
|
+
* @param {number} output_height
|
|
9
|
+
* @param {number} typ_idx
|
|
10
|
+
* @param {boolean} premultiply
|
|
11
|
+
* @param {boolean} color_space_conversion
|
|
12
|
+
* @returns {Uint8ClampedArray}
|
|
13
|
+
*/
|
|
14
|
+
export function resize(input_image: Uint8Array, input_width: number, input_height: number, output_width: number, output_height: number, typ_idx: number, premultiply: boolean, color_space_conversion: boolean): Uint8ClampedArray;
|
|
15
|
+
|
|
16
|
+
export type InitInput = RequestInfo | URL | Response | BufferSource | WebAssembly.Module;
|
|
17
|
+
|
|
18
|
+
export interface InitOutput {
|
|
19
|
+
readonly memory: WebAssembly.Memory;
|
|
20
|
+
readonly resize: (a: number, b: number, c: number, d: number, e: number, f: number, g: number, h: number, i: number, j: number) => void;
|
|
21
|
+
readonly __wbindgen_add_to_stack_pointer: (a: number) => number;
|
|
22
|
+
readonly __wbindgen_malloc: (a: number) => number;
|
|
23
|
+
readonly __wbindgen_free: (a: number, b: number) => void;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* If `module_or_path` is {RequestInfo} or {URL}, makes a request and
|
|
28
|
+
* for everything else, calls `WebAssembly.instantiate` directly.
|
|
29
|
+
*
|
|
30
|
+
* @param {InitInput | Promise<InitInput>} module_or_path
|
|
31
|
+
*
|
|
32
|
+
* @returns {Promise<InitOutput>}
|
|
33
|
+
*/
|
|
34
|
+
export default function init (module_or_path?: InitInput | Promise<InitInput>): Promise<InitOutput>;
|
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
|
|
2
|
+
let wasm;
|
|
3
|
+
|
|
4
|
+
let cachegetUint8Memory0 = null;
|
|
5
|
+
function getUint8Memory0() {
|
|
6
|
+
if (cachegetUint8Memory0 === null || cachegetUint8Memory0.buffer !== wasm.memory.buffer) {
|
|
7
|
+
cachegetUint8Memory0 = new Uint8Array(wasm.memory.buffer);
|
|
8
|
+
}
|
|
9
|
+
return cachegetUint8Memory0;
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
let WASM_VECTOR_LEN = 0;
|
|
13
|
+
|
|
14
|
+
function passArray8ToWasm0(arg, malloc) {
|
|
15
|
+
const ptr = malloc(arg.length * 1);
|
|
16
|
+
getUint8Memory0().set(arg, ptr / 1);
|
|
17
|
+
WASM_VECTOR_LEN = arg.length;
|
|
18
|
+
return ptr;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
let cachegetInt32Memory0 = null;
|
|
22
|
+
function getInt32Memory0() {
|
|
23
|
+
if (cachegetInt32Memory0 === null || cachegetInt32Memory0.buffer !== wasm.memory.buffer) {
|
|
24
|
+
cachegetInt32Memory0 = new Int32Array(wasm.memory.buffer);
|
|
25
|
+
}
|
|
26
|
+
return cachegetInt32Memory0;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
let cachegetUint8ClampedMemory0 = null;
|
|
30
|
+
function getUint8ClampedMemory0() {
|
|
31
|
+
if (cachegetUint8ClampedMemory0 === null || cachegetUint8ClampedMemory0.buffer !== wasm.memory.buffer) {
|
|
32
|
+
cachegetUint8ClampedMemory0 = new Uint8ClampedArray(wasm.memory.buffer);
|
|
33
|
+
}
|
|
34
|
+
return cachegetUint8ClampedMemory0;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
function getClampedArrayU8FromWasm0(ptr, len) {
|
|
38
|
+
return getUint8ClampedMemory0().subarray(ptr / 1, ptr / 1 + len);
|
|
39
|
+
}
|
|
40
|
+
/**
|
|
41
|
+
* @param {Uint8Array} input_image
|
|
42
|
+
* @param {number} input_width
|
|
43
|
+
* @param {number} input_height
|
|
44
|
+
* @param {number} output_width
|
|
45
|
+
* @param {number} output_height
|
|
46
|
+
* @param {number} typ_idx
|
|
47
|
+
* @param {boolean} premultiply
|
|
48
|
+
* @param {boolean} color_space_conversion
|
|
49
|
+
* @returns {Uint8ClampedArray}
|
|
50
|
+
*/
|
|
51
|
+
export function resize(input_image, input_width, input_height, output_width, output_height, typ_idx, premultiply, color_space_conversion) {
|
|
52
|
+
try {
|
|
53
|
+
const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);
|
|
54
|
+
var ptr0 = passArray8ToWasm0(input_image, wasm.__wbindgen_malloc);
|
|
55
|
+
var len0 = WASM_VECTOR_LEN;
|
|
56
|
+
wasm.resize(retptr, ptr0, len0, input_width, input_height, output_width, output_height, typ_idx, premultiply, color_space_conversion);
|
|
57
|
+
var r0 = getInt32Memory0()[retptr / 4 + 0];
|
|
58
|
+
var r1 = getInt32Memory0()[retptr / 4 + 1];
|
|
59
|
+
var v1 = getClampedArrayU8FromWasm0(r0, r1).slice();
|
|
60
|
+
wasm.__wbindgen_free(r0, r1 * 1);
|
|
61
|
+
return v1;
|
|
62
|
+
} finally {
|
|
63
|
+
wasm.__wbindgen_add_to_stack_pointer(16);
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
async function load(module, imports) {
|
|
68
|
+
if (typeof Response === 'function' && module instanceof Response) {
|
|
69
|
+
if (typeof WebAssembly.instantiateStreaming === 'function') {
|
|
70
|
+
try {
|
|
71
|
+
return await WebAssembly.instantiateStreaming(module, imports);
|
|
72
|
+
|
|
73
|
+
} catch (e) {
|
|
74
|
+
if (module.headers.get('Content-Type') != 'application/wasm') {
|
|
75
|
+
console.warn("`WebAssembly.instantiateStreaming` failed because your server does not serve wasm with `application/wasm` MIME type. Falling back to `WebAssembly.instantiate` which is slower. Original error:\n", e);
|
|
76
|
+
|
|
77
|
+
} else {
|
|
78
|
+
throw e;
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
const bytes = await module.arrayBuffer();
|
|
84
|
+
return await WebAssembly.instantiate(bytes, imports);
|
|
85
|
+
|
|
86
|
+
} else {
|
|
87
|
+
const instance = await WebAssembly.instantiate(module, imports);
|
|
88
|
+
|
|
89
|
+
if (instance instanceof WebAssembly.Instance) {
|
|
90
|
+
return { instance, module };
|
|
91
|
+
|
|
92
|
+
} else {
|
|
93
|
+
return instance;
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
async function init(input) {
|
|
99
|
+
if (typeof input === 'undefined') {
|
|
100
|
+
input = new URL('squoosh_resize_bg.wasm', import.meta.url);
|
|
101
|
+
}
|
|
102
|
+
const imports = {};
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
if (typeof input === 'string' || (typeof Request === 'function' && input instanceof Request) || (typeof URL === 'function' && input instanceof URL)) {
|
|
106
|
+
input = fetch(input);
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
const { instance, module } = await load(await input, imports);
|
|
112
|
+
|
|
113
|
+
wasm = instance.exports;
|
|
114
|
+
init.__wbindgen_wasm_module = module;
|
|
115
|
+
|
|
116
|
+
return wasm;
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
export default init;
|
|
120
|
+
|
|
Binary file
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
/* tslint:disable */
|
|
2
|
+
/* eslint-disable */
|
|
3
|
+
export const memory: WebAssembly.Memory;
|
|
4
|
+
export function resize(a: number, b: number, c: number, d: number, e: number, f: number, g: number, h: number, i: number, j: number): void;
|
|
5
|
+
export function __wbindgen_add_to_stack_pointer(a: number): number;
|
|
6
|
+
export function __wbindgen_malloc(a: number): number;
|
|
7
|
+
export function __wbindgen_free(a: number, b: number): void;
|
package/package.json
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@squoosh-kit/resize",
|
|
3
|
+
"version": "0.0.1",
|
|
4
|
+
"type": "module",
|
|
5
|
+
"entry": "src/index.ts",
|
|
6
|
+
"description": "Image resize module for squoosh-kit.",
|
|
7
|
+
"author": "Bartosz Nowak <bnowak008@gmail.com>",
|
|
8
|
+
"license": "MIT",
|
|
9
|
+
"repository": {
|
|
10
|
+
"type": "git",
|
|
11
|
+
"url": "https://github.com/bnowak008/squoosh-kit.git",
|
|
12
|
+
"directory": "packages/resize"
|
|
13
|
+
},
|
|
14
|
+
"homepage": "https://github.com/bnowak008/squoosh-kit/tree/main/packages/resize#readme",
|
|
15
|
+
"publishConfig": {
|
|
16
|
+
"access": "public",
|
|
17
|
+
"registry": "https://registry.npmjs.org/"
|
|
18
|
+
},
|
|
19
|
+
"exports": {
|
|
20
|
+
".": {
|
|
21
|
+
"types": "./dist/index.d.ts",
|
|
22
|
+
"import": "./dist/index.js"
|
|
23
|
+
},
|
|
24
|
+
"./resize.worker.js": {
|
|
25
|
+
"import": "./dist/resize.worker.js"
|
|
26
|
+
}
|
|
27
|
+
},
|
|
28
|
+
"files": [
|
|
29
|
+
"dist/**",
|
|
30
|
+
"README.md"
|
|
31
|
+
],
|
|
32
|
+
"sideEffects": false,
|
|
33
|
+
"scripts": {
|
|
34
|
+
"build": "bun run scripts/copy-assets.ts && tsc && bun build --sourcemap --minify --format=esm --splitting --target=bun --outdir=dist src/index.ts src/resize.worker.ts",
|
|
35
|
+
"clean:local": "rm -rf dist *.tsbuildinfo",
|
|
36
|
+
"prepack": "bun run build"
|
|
37
|
+
},
|
|
38
|
+
"dependencies": {
|
|
39
|
+
"@squoosh-kit/runtime": "0.1.0"
|
|
40
|
+
}
|
|
41
|
+
}
|