diff --git a/.changeset/old-ladybugs-roll.md b/.changeset/old-ladybugs-roll.md
new file mode 100644
index 000000000..2f114c513
--- /dev/null
+++ b/.changeset/old-ladybugs-roll.md
@@ -0,0 +1,24 @@
+---
+'@astrojs/image': minor
+---
+
+Adds a new built-in image service based on web assembly libraries :drum: web container support!
+
+**Migration:** Happy with the previous image service based on [`sharp`](https://sharp.pixelplumbing.com/)? No problem! Install `sharp` in your project and update your Astro config to match.
+
+```sh
+npm install sharp
+```
+
+```astro title="astro.config.mjs"
+---
+import image from '@astrojs/image';
+
+export default {
+ // ...
+ integrations: [image({
+ serviceEntryPoint: '@astrojs/image/sharp'
+ })],
+}
+---
+```
diff --git a/packages/integrations/image/README.md b/packages/integrations/image/README.md
index 497479302..dc8fd77bc 100644
--- a/packages/integrations/image/README.md
+++ b/packages/integrations/image/README.md
@@ -18,7 +18,7 @@ This **[Astro integration][astro-integration]** makes it easy to optimize images
Images play a big role in overall site performance and usability. Serving properly sized images makes all the difference but is often tricky to automate.
-This integration provides `` and `
+> This is not supported by the default Squoosh service. See the [installation section](#installing-sharp-optional) for details on using the `sharp` service instead.
+
The background color is used to fill the remaining background when using `contain` for the `fit` property.
The background color is also used for replacing the alpha channel with `sharp`'s `flatten` method. In case the output format
@@ -215,6 +242,8 @@ color representation with 3 or 6 hexadecimal characters in the form `#123[abc]`,
**Default:** `'cover'`
+> This is not supported by the default Squoosh service. See the [installation section](#installing-sharp-optional) for details on using the `sharp` service instead.
+
How the image should be resized to fit both `height` and `width`.
#### position
@@ -225,6 +254,8 @@ How the image should be resized to fit both `height` and `width`.
**Default:** `'centre'`
+> This is not supported by the default Squoosh service. See the [installation section](#installing-sharp-optional) for details on using the `sharp` service instead.
+
Position of the crop when fit is `cover` or `contain`.
### ``
@@ -316,6 +347,8 @@ The output formats to be used in the optimized image. If not provided, `webp` an
**Default:** `undefined`
+> This is not supported by the default Squoosh service. See the [installation section](#installing-sharp-optional) for details on using the `sharp` service instead.
+
The background color to use for replacing the alpha channel with `sharp`'s `flatten` method. In case the output format
doesn't support transparency (i.e. `jpeg`), it's advisable to include a background color, otherwise black will be used
as default replacement for transparent pixels.
@@ -334,6 +367,8 @@ color representation with 3 or 6 hexadecimal characters in the form `#123[abc]`,
**Default:** `'cover'`
+> This is not supported by the default Squoosh service. See the [installation section](#installing-sharp-optional) for details on using the `sharp` service instead.
+
How the image should be resized to fit both `height` and `width`.
#### position
@@ -346,6 +381,8 @@ How the image should be resized to fit both `height` and `width`.
**Default:** `'centre'`
+> This is not supported by the default Squoosh service. See the [installation section](#installing-sharp-optional) for details on using the `sharp` service instead.
+
Position of the crop when fit is `cover` or `contain`.
### `getImage`
@@ -380,12 +417,12 @@ This helper takes in an object with the same properties as the `` com
The integration can be configured to run with a different image service, either a hosted image service or a full image transformer that runs locally in your build or SSR deployment.
-> During development, local images may not have been published yet and would not be available to hosted image services. Local images will always use the built-in `sharp` service when using `astro dev`.
+> During development, local images may not have been published yet and would not be available to hosted image services. Local images will always use the built-in image service when using `astro dev`.
### config.serviceEntryPoint
-The `serviceEntryPoint` should resolve to the image service installed from NPM. The default entry point is `@astrojs/image/sharp`, which resolves to the entry point exported from this integration's `package.json`.
+The `serviceEntryPoint` should resolve to the image service installed from NPM. The default entry point is `@astrojs/image/squoosh`, which resolves to the entry point exported from this integration's `package.json`.
```js
// astro.config.mjs
diff --git a/packages/integrations/image/package.json b/packages/integrations/image/package.json
index a41e4732c..f1e36f0d3 100644
--- a/packages/integrations/image/package.json
+++ b/packages/integrations/image/package.json
@@ -23,6 +23,7 @@
".": "./dist/index.js",
"./endpoint": "./dist/endpoint.js",
"./sharp": "./dist/loaders/sharp.js",
+ "./squoosh": "./dist/loaders/squoosh.js",
"./components": "./components/index.js",
"./package.json": "./package.json",
"./client": "./client.d.ts",
@@ -34,8 +35,9 @@
"client.d.ts"
],
"scripts": {
- "build": "astro-scripts build \"src/**/*.ts\" && tsc",
- "build:ci": "astro-scripts build \"src/**/*.ts\"",
+ "build": "astro-scripts build \"src/**/*.ts\" && tsc && pnpm run postbuild",
+ "build:ci": "astro-scripts build \"src/**/*.ts\" && pnpm run postbuild",
+ "postbuild": "astro-scripts copy \"src/**/*.wasm\"",
"dev": "astro-scripts dev \"src/**/*.ts\"",
"test": "mocha --exit --timeout 20000 test"
},
@@ -43,13 +45,14 @@
"@altano/tiny-async-pool": "^1.0.2",
"image-size": "^1.0.2",
"magic-string": "^0.25.9",
- "mime": "^3.0.0",
- "sharp": "^0.30.6"
+ "mime": "^3.0.0"
},
"devDependencies": {
"@types/sharp": "^0.30.5",
"astro": "workspace:*",
"astro-scripts": "workspace:*",
- "kleur": "^4.1.4"
+ "kleur": "^4.1.4",
+ "rollup-plugin-copy": "^3.4.0",
+ "web-streams-polyfill": "^3.2.1"
}
}
diff --git a/packages/integrations/image/src/build/ssg.ts b/packages/integrations/image/src/build/ssg.ts
index 9219b9afd..c3cc75642 100644
--- a/packages/integrations/image/src/build/ssg.ts
+++ b/packages/integrations/image/src/build/ssg.ts
@@ -6,10 +6,31 @@ import OS from 'node:os';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import type { SSRImageService, TransformOptions } from '../loaders/index.js';
-import { loadLocalImage, loadRemoteImage } from '../utils/images.js';
import { debug, info, LoggerLevel, warn } from '../utils/logger.js';
import { isRemoteImage } from '../utils/paths.js';
+async function loadLocalImage(src: string | URL) {
+ try {
+ return await fs.readFile(src);
+ } catch {
+ return undefined;
+ }
+}
+
+async function loadRemoteImage(src: string) {
+ try {
+ const res = await fetch(src);
+
+ if (!res.ok) {
+ return undefined;
+ }
+
+ return Buffer.from(await res.arrayBuffer());
+ } catch {
+ return undefined;
+ }
+}
+
function getTimeStat(timeStart: number, timeEnd: number) {
const buildTime = timeEnd - timeStart;
return buildTime < 750 ? `${Math.round(buildTime)}ms` : `${(buildTime / 1000).toFixed(2)}s`;
@@ -39,8 +60,6 @@ export async function ssgBuild({ loader, staticImages, config, outDir, logLevel
)}`,
});
- const inputFiles = new Set();
-
async function processStaticImage([src, transformsMap]: [
string,
Map
@@ -61,9 +80,6 @@ export async function ssgBuild({ loader, staticImages, config, outDir, logLevel
const inputFileURL = new URL(`.${src}`, outDir);
inputFile = fileURLToPath(inputFileURL);
inputBuffer = await loadLocalImage(inputFile);
-
- // track the local file used so the original can be copied over
- inputFiles.add(inputFile);
}
if (!inputBuffer) {
diff --git a/packages/integrations/image/src/endpoint.ts b/packages/integrations/image/src/endpoint.ts
index bb634cf0c..872403226 100644
--- a/packages/integrations/image/src/endpoint.ts
+++ b/packages/integrations/image/src/endpoint.ts
@@ -48,6 +48,7 @@ export const get: APIRoute = async ({ request }) => {
},
});
} catch (err: unknown) {
+ console.error(err);
return new Response(`Server Error: ${err}`, { status: 500 });
}
};
diff --git a/packages/integrations/image/src/index.ts b/packages/integrations/image/src/index.ts
index 38c654354..f41b943d2 100644
--- a/packages/integrations/image/src/index.ts
+++ b/packages/integrations/image/src/index.ts
@@ -1,9 +1,10 @@
-import type { AstroConfig, AstroIntegration } from 'astro';
+import type { AstroConfig, AstroIntegration, BuildConfig } from 'astro';
import { ssgBuild } from './build/ssg.js';
-import type { ImageService, TransformOptions } from './loaders/index.js';
+import type { ImageService, SSRImageService, TransformOptions } from './loaders/index.js';
import type { LoggerLevel } from './utils/logger.js';
import { joinPaths, prependForwardSlash, propsToFilename } from './utils/paths.js';
import { createPlugin } from './vite-plugin-astro-image.js';
+import { copyWasmFiles } from './vendor/squoosh/copy-wasm.js';
export { getImage } from './lib/get-image.js';
export { getPicture } from './lib/get-picture.js';
@@ -13,12 +14,13 @@ const ROUTE_PATTERN = '/_image';
interface ImageIntegration {
loader?: ImageService;
+ defaultLoader: SSRImageService;
addStaticImage?: (transform: TransformOptions) => string;
}
declare global {
// eslint-disable-next-line no-var
- var astroImage: ImageIntegration | undefined;
+ var astroImage: ImageIntegration;
}
export interface IntegrationOptions {
@@ -31,12 +33,13 @@ export interface IntegrationOptions {
export default function integration(options: IntegrationOptions = {}): AstroIntegration {
const resolvedOptions = {
- serviceEntryPoint: '@astrojs/image/sharp',
+ serviceEntryPoint: '@astrojs/image/squoosh',
logLevel: 'info' as LoggerLevel,
...options,
};
let _config: AstroConfig;
+ let _buildConfig: BuildConfig;
// During SSG builds, this is used to track all transformed images required.
const staticImages = new Map>();
@@ -45,18 +48,26 @@ export default function integration(options: IntegrationOptions = {}): AstroInte
return {
plugins: [createPlugin(_config, resolvedOptions)],
optimizeDeps: {
- include: ['image-size', 'sharp'],
+ include: [
+ 'image-size',
+ ].filter(Boolean),
},
+ build: {
+ rollupOptions: {
+ external: ["sharp"]
+ }
+ },
ssr: {
noExternal: ['@astrojs/image', resolvedOptions.serviceEntryPoint],
},
+ assetsInclude: ['**/*.wasm']
};
}
return {
name: PKG_NAME,
hooks: {
- 'astro:config:setup': ({ command, config, updateConfig, injectRoute }) => {
+ 'astro:config:setup': async ({ command, config, updateConfig, injectRoute }) => {
_config = config;
updateConfig({ vite: getViteConfiguration() });
@@ -67,8 +78,20 @@ export default function integration(options: IntegrationOptions = {}): AstroInte
entryPoint: '@astrojs/image/endpoint',
});
}
+
+ const { default: defaultLoader } = await import(resolvedOptions.serviceEntryPoint === '@astrojs/image/sharp'
+ ? './loaders/sharp.js'
+ : './loaders/squoosh.js'
+ );
+
+ globalThis.astroImage = {
+ defaultLoader
+ }
},
- 'astro:build:setup': () => {
+ 'astro:build:start': async ({ buildConfig }) => {
+ _buildConfig = buildConfig
+ },
+ 'astro:build:setup': async () => {
// Used to cache all images rendered to HTML
// Added to globalThis to share the same map in Node and Vite
function addStaticImage(transform: TransformOptions) {
@@ -89,29 +112,36 @@ export default function integration(options: IntegrationOptions = {}): AstroInte
}
// Helpers for building static images should only be available for SSG
- globalThis.astroImage =
- _config.output === 'static'
- ? {
- addStaticImage,
- }
- : {};
- },
- 'astro:build:done': async ({ dir }) => {
if (_config.output === 'static') {
- // for SSG builds, build all requested image transforms to dist
- const loader = globalThis?.astroImage?.loader;
-
- if (loader && 'transform' in loader && staticImages.size > 0) {
- await ssgBuild({
- loader,
- staticImages,
- config: _config,
- outDir: dir,
- logLevel: resolvedOptions.logLevel,
- });
- }
+ globalThis.astroImage.addStaticImage = addStaticImage;
}
},
+ 'astro:build:generated': async ({ dir }) => {
+ // for SSG builds, build all requested image transforms to dist
+ const loader = globalThis?.astroImage?.loader;
+
+ if (resolvedOptions.serviceEntryPoint === '@astrojs/image/squoosh') {
+ // For the Squoosh service, copy all wasm files to dist/chunks.
+ // Because the default loader is dynamically imported (above),
+ // Vite will bundle squoosh to dist/chunks and expect to find the wasm files there
+ await copyWasmFiles(new URL('./chunks', dir));
+ }
+
+ if (loader && 'transform' in loader && staticImages.size > 0) {
+ await ssgBuild({
+ loader,
+ staticImages,
+ config: _config,
+ outDir: dir,
+ logLevel: resolvedOptions.logLevel,
+ });
+ }
+ },
+ 'astro:build:ssr': async () => {
+ if (resolvedOptions.serviceEntryPoint === '@astrojs/image/squoosh') {
+ await copyWasmFiles(_buildConfig.server);
+ }
+ }
},
};
}
diff --git a/packages/integrations/image/src/lib/get-image.ts b/packages/integrations/image/src/lib/get-image.ts
index 856f9f8c6..5e7f4d0a4 100644
--- a/packages/integrations/image/src/lib/get-image.ts
+++ b/packages/integrations/image/src/lib/get-image.ts
@@ -6,7 +6,6 @@ import type {
TransformOptions,
} from '../loaders/index.js';
import { isSSRService, parseAspectRatio } from '../loaders/index.js';
-import sharp from '../loaders/sharp.js';
import { isRemoteImage } from '../utils/paths.js';
import type { ImageMetadata } from '../vite-plugin-astro-image.js';
@@ -131,7 +130,7 @@ export async function getImage(
const isDev = import.meta.env?.DEV;
const isLocalImage = !isRemoteImage(resolved.src);
- const _loader = isDev && isLocalImage ? sharp : loader;
+ const _loader = isDev && isLocalImage ? globalThis.astroImage.defaultLoader : loader;
if (!_loader) {
throw new Error('@astrojs/image: loader not found!');
@@ -139,7 +138,7 @@ export async function getImage(
const { searchParams } = isSSRService(_loader)
? _loader.serializeTransform(resolved)
- : sharp.serializeTransform(resolved);
+ : globalThis.astroImage.defaultLoader.serializeTransform(resolved);
let src: string;
diff --git a/packages/integrations/image/src/lib/get-picture.ts b/packages/integrations/image/src/lib/get-picture.ts
index 132d93ee1..e3b07b505 100644
--- a/packages/integrations/image/src/lib/get-picture.ts
+++ b/packages/integrations/image/src/lib/get-picture.ts
@@ -1,9 +1,9 @@
///
import mime from 'mime';
-import { extname } from 'node:path';
import { OutputFormat, parseAspectRatio, TransformOptions } from '../loaders/index.js';
import { ImageMetadata } from '../vite-plugin-astro-image.js';
import { getImage } from './get-image.js';
+import { extname } from '../utils/paths.js';
export interface GetPictureParams {
src: string | ImageMetadata | Promise<{ default: ImageMetadata }>;
diff --git a/packages/integrations/image/src/loaders/index.ts b/packages/integrations/image/src/loaders/index.ts
index 2f3279a5a..30ccb879f 100644
--- a/packages/integrations/image/src/loaders/index.ts
+++ b/packages/integrations/image/src/loaders/index.ts
@@ -1,4 +1,5 @@
-import { htmlColorNames, type NamedColor } from './colornames.js';
+import { AstroConfig } from 'astro';
+import { htmlColorNames, type NamedColor } from '../utils/colornames.js';
///
export type InputFormat =
@@ -13,7 +14,7 @@ export type InputFormat =
| 'gif';
export type OutputFormatSupportsAlpha = 'avif' | 'png' | 'webp';
-export type OutputFormat = OutputFormatSupportsAlpha | 'jpeg';
+export type OutputFormat = OutputFormatSupportsAlpha | 'jpeg' | 'jpg';
export type ColorDefinition =
| NamedColor
@@ -49,7 +50,7 @@ export type CropPosition =
| 'attention';
export function isOutputFormat(value: string): value is OutputFormat {
- return ['avif', 'jpeg', 'png', 'webp'].includes(value);
+ return ['avif', 'jpeg', 'jpg', 'png', 'webp'].includes(value);
}
export function isOutputFormatSupportsAlpha(value: string): value is OutputFormatSupportsAlpha {
@@ -194,3 +195,109 @@ export function isHostedService(service: ImageService): service is ImageService
export function isSSRService(service: ImageService): service is SSRImageService {
return 'transform' in service;
}
+
+export abstract class BaseSSRService implements SSRImageService {
+ async getImageAttributes(transform: TransformOptions) {
+ // strip off the known attributes
+ const { width, height, src, format, quality, aspectRatio, ...rest } = transform;
+
+ return {
+ ...rest,
+ width: width,
+ height: height,
+ };
+ }
+
+ serializeTransform(transform: TransformOptions) {
+ const searchParams = new URLSearchParams();
+
+ if (transform.quality) {
+ searchParams.append('q', transform.quality.toString());
+ }
+
+ if (transform.format) {
+ searchParams.append('f', transform.format);
+ }
+
+ if (transform.width) {
+ searchParams.append('w', transform.width.toString());
+ }
+
+ if (transform.height) {
+ searchParams.append('h', transform.height.toString());
+ }
+
+ if (transform.aspectRatio) {
+ searchParams.append('ar', transform.aspectRatio.toString());
+ }
+
+ if (transform.fit) {
+ searchParams.append('fit', transform.fit);
+ }
+
+ if (transform.background) {
+ searchParams.append('bg', transform.background);
+ }
+
+ if (transform.position) {
+ searchParams.append('p', encodeURI(transform.position));
+ }
+
+ searchParams.append('href', transform.src);
+
+ return { searchParams };
+ }
+
+ parseTransform(searchParams: URLSearchParams) {
+ if (!searchParams.has('href')) {
+ return undefined;
+ }
+
+ let transform: TransformOptions = { src: searchParams.get('href')! };
+
+ if (searchParams.has('q')) {
+ transform.quality = parseInt(searchParams.get('q')!);
+ }
+
+ if (searchParams.has('f')) {
+ const format = searchParams.get('f')!;
+ if (isOutputFormat(format)) {
+ transform.format = format;
+ }
+ }
+
+ if (searchParams.has('w')) {
+ transform.width = parseInt(searchParams.get('w')!);
+ }
+
+ if (searchParams.has('h')) {
+ transform.height = parseInt(searchParams.get('h')!);
+ }
+
+ if (searchParams.has('ar')) {
+ const ratio = searchParams.get('ar')!;
+
+ if (isAspectRatioString(ratio)) {
+ transform.aspectRatio = ratio;
+ } else {
+ transform.aspectRatio = parseFloat(ratio);
+ }
+ }
+
+ if (searchParams.has('fit')) {
+ transform.fit = searchParams.get('fit') as typeof transform.fit;
+ }
+
+ if (searchParams.has('p')) {
+ transform.position = decodeURI(searchParams.get('p')!) as typeof transform.position;
+ }
+
+ if (searchParams.has('bg')) {
+ transform.background = searchParams.get('bg') as ColorDefinition;
+ }
+
+ return transform;
+ }
+
+ abstract transform(inputBuffer: Buffer, transform: TransformOptions): Promise<{ data: Buffer, format: OutputFormat }>;
+}
diff --git a/packages/integrations/image/src/loaders/sharp.ts b/packages/integrations/image/src/loaders/sharp.ts
index e7ef57aa0..dd58aacb0 100644
--- a/packages/integrations/image/src/loaders/sharp.ts
+++ b/packages/integrations/image/src/loaders/sharp.ts
@@ -1,110 +1,9 @@
import sharp from 'sharp';
-import {
- ColorDefinition,
- isAspectRatioString,
- isOutputFormat,
- isOutputFormatSupportsAlpha,
-} from '../loaders/index.js';
-import type { OutputFormat, SSRImageService, TransformOptions } from './index.js';
-
-class SharpService implements SSRImageService {
- async getImageAttributes(transform: TransformOptions) {
- // strip off the known attributes
- const { width, height, src, format, quality, aspectRatio, fit, position, background, ...rest } =
- transform;
-
- return {
- ...rest,
- width: width,
- height: height,
- };
- }
-
- serializeTransform(transform: TransformOptions) {
- const searchParams = new URLSearchParams();
-
- if (transform.quality) {
- searchParams.append('q', transform.quality.toString());
- }
-
- if (transform.format) {
- searchParams.append('f', transform.format);
- }
-
- if (transform.width) {
- searchParams.append('w', transform.width.toString());
- }
-
- if (transform.height) {
- searchParams.append('h', transform.height.toString());
- }
-
- if (transform.aspectRatio) {
- searchParams.append('ar', transform.aspectRatio.toString());
- }
-
- if (transform.fit) {
- searchParams.append('fit', transform.fit);
- }
-
- if (transform.background) {
- searchParams.append('bg', transform.background);
- }
-
- if (transform.position) {
- searchParams.append('p', encodeURI(transform.position));
- }
-
- return { searchParams };
- }
-
- parseTransform(searchParams: URLSearchParams) {
- let transform: TransformOptions = { src: searchParams.get('href')! };
-
- if (searchParams.has('q')) {
- transform.quality = parseInt(searchParams.get('q')!);
- }
-
- if (searchParams.has('f')) {
- const format = searchParams.get('f')!;
- if (isOutputFormat(format)) {
- transform.format = format;
- }
- }
-
- if (searchParams.has('w')) {
- transform.width = parseInt(searchParams.get('w')!);
- }
-
- if (searchParams.has('h')) {
- transform.height = parseInt(searchParams.get('h')!);
- }
-
- if (searchParams.has('ar')) {
- const ratio = searchParams.get('ar')!;
-
- if (isAspectRatioString(ratio)) {
- transform.aspectRatio = ratio;
- } else {
- transform.aspectRatio = parseFloat(ratio);
- }
- }
-
- if (searchParams.has('fit')) {
- transform.fit = searchParams.get('fit') as typeof transform.fit;
- }
-
- if (searchParams.has('p')) {
- transform.position = decodeURI(searchParams.get('p')!) as typeof transform.position;
- }
-
- if (searchParams.has('bg')) {
- transform.background = searchParams.get('bg') as ColorDefinition | undefined;
- }
-
- return transform;
- }
+import { BaseSSRService, isOutputFormatSupportsAlpha } from '../loaders/index.js';
+import type { SSRImageService } from '../loaders/index.js';
+import type { OutputFormat, TransformOptions } from './index.js';
+class SharpService extends BaseSSRService {
async transform(inputBuffer: Buffer, transform: TransformOptions) {
const sharpImage = sharp(inputBuffer, { failOnError: false, pages: -1 });
diff --git a/packages/integrations/image/src/loaders/squoosh.ts b/packages/integrations/image/src/loaders/squoosh.ts
new file mode 100644
index 000000000..b4e9d636a
--- /dev/null
+++ b/packages/integrations/image/src/loaders/squoosh.ts
@@ -0,0 +1,122 @@
+// @ts-ignore
+import { red } from 'kleur/colors';
+import { BaseSSRService } from './index.js';
+import { error } from '../utils/logger.js';
+import { metadata } from '../utils/metadata.js';
+import { isRemoteImage } from '../utils/paths.js';
+import type { OutputFormat, TransformOptions } from './index.js';
+import { processBuffer } from '../vendor/squoosh/image-pool.js';
+import type { Operation } from '../vendor/squoosh/image.js';
+
+class SquooshService extends BaseSSRService {
+ async processAvif(image: any, transform: TransformOptions) {
+ const encodeOptions = transform.quality
+ ? { avif: { quality: transform.quality } }
+ : { avif: {} };
+ await image.encode(encodeOptions);
+ const data = await image.encodedWith.avif;
+
+ return {
+ data: data.binary,
+ format: 'avif' as OutputFormat,
+ };
+ }
+
+ async processJpeg(image: any, transform: TransformOptions) {
+ const encodeOptions = transform.quality
+ ? { mozjpeg: { quality: transform.quality } }
+ : { mozjpeg: {} };
+ await image.encode(encodeOptions);
+ const data = await image.encodedWith.mozjpeg;
+
+ return {
+ data: data.binary,
+ format: 'jpeg' as OutputFormat,
+ };
+ }
+
+ async processPng(image: any, transform: TransformOptions) {
+ await image.encode({ oxipng: {} });
+ const data = await image.encodedWith.oxipng;
+
+ return {
+ data: data.binary,
+ format: 'png' as OutputFormat,
+ };
+ }
+
+ async processWebp(image: any, transform: TransformOptions) {
+ const encodeOptions = transform.quality
+ ? { webp: { quality: transform.quality } }
+ : { webp: {} };
+ await image.encode(encodeOptions);
+ const data = await image.encodedWith.webp;
+
+ return {
+ data: data.binary,
+ format: 'webp' as OutputFormat,
+ };
+ }
+
+ async autorotate(transform: TransformOptions, inputBuffer: Buffer): Promise {
+ // check EXIF orientation data and rotate the image if needed
+ try {
+ const meta = await metadata(transform.src, inputBuffer);
+
+ switch (meta?.orientation) {
+ case 3:
+ case 4:
+ return { type: 'rotate', numRotations: 2 };
+ case 5:
+ case 6:
+ return { type: 'rotate', numRotations: 1 };
+ case 7:
+ case 8:
+ return { type: 'rotate', numRotations: 3 };
+ }
+ } catch { }
+ }
+
+ async transform(inputBuffer: Buffer, transform: TransformOptions) {
+ const operations: Operation[] = [];
+
+ if (!isRemoteImage(transform.src)) {
+ const autorotate = await this.autorotate(transform, inputBuffer)
+
+ if (autorotate) {
+ operations.push(autorotate);
+ }
+ }
+
+ if (transform.width || transform.height) {
+ const width = transform.width && Math.round(transform.width);
+ const height = transform.height && Math.round(transform.height);
+
+ operations.push({
+ type: 'resize',
+ width,
+ height,
+ })
+ }
+
+ if (!transform.format) {
+ error({
+ level: 'info',
+ prefix: false,
+ message: red(`Unknown image output: "${transform.format}" used for ${transform.src}`),
+ });
+ throw new Error(`Unknown image output: "${transform.format}" used for ${transform.src}`);
+ }
+
+ const data = await processBuffer(inputBuffer, operations, transform.format, transform.quality || 100);
+
+ return {
+ data: Buffer.from(data),
+ format: transform.format
+ }
+ }
+}
+
+const service = new SquooshService();
+
+export default service;
diff --git a/packages/integrations/image/src/loaders/colornames.ts b/packages/integrations/image/src/utils/colornames.ts
similarity index 100%
rename from packages/integrations/image/src/loaders/colornames.ts
rename to packages/integrations/image/src/utils/colornames.ts
diff --git a/packages/integrations/image/src/utils/execOnce.ts b/packages/integrations/image/src/utils/execOnce.ts
new file mode 100644
index 000000000..1a9a7ba68
--- /dev/null
+++ b/packages/integrations/image/src/utils/execOnce.ts
@@ -0,0 +1,14 @@
+export default function execOnce ReturnType>(
+ fn: T
+): T {
+ let used = false
+ let result: ReturnType
+
+ return ((...args: any[]) => {
+ if (!used) {
+ used = true
+ result = fn(...args)
+ }
+ return result
+ }) as T
+}
diff --git a/packages/integrations/image/src/utils/images.ts b/packages/integrations/image/src/utils/images.ts
deleted file mode 100644
index f9b94b1e8..000000000
--- a/packages/integrations/image/src/utils/images.ts
+++ /dev/null
@@ -1,23 +0,0 @@
-import fs from 'node:fs/promises';
-
-export async function loadLocalImage(src: string | URL) {
- try {
- return await fs.readFile(src);
- } catch {
- return undefined;
- }
-}
-
-export async function loadRemoteImage(src: string) {
- try {
- const res = await fetch(src);
-
- if (!res.ok) {
- return undefined;
- }
-
- return Buffer.from(await res.arrayBuffer());
- } catch {
- return undefined;
- }
-}
diff --git a/packages/integrations/image/src/utils/metadata.ts b/packages/integrations/image/src/utils/metadata.ts
index 1c3bebdf0..23e83b614 100644
--- a/packages/integrations/image/src/utils/metadata.ts
+++ b/packages/integrations/image/src/utils/metadata.ts
@@ -4,8 +4,12 @@ import { fileURLToPath } from 'node:url';
import { InputFormat } from '../loaders/index.js';
import { ImageMetadata } from '../vite-plugin-astro-image.js';
-export async function metadata(src: URL): Promise {
- const file = await fs.readFile(src);
+export interface Metadata extends ImageMetadata {
+ orientation?: number;
+}
+
+export async function metadata(src: URL | string, data?: Buffer): Promise {
+ const file = data || await fs.readFile(src);
const { width, height, type, orientation } = await sizeOf(file);
const isPortrait = (orientation || 0) >= 5;
@@ -19,5 +23,6 @@ export async function metadata(src: URL): Promise {
width: isPortrait ? height : width,
height: isPortrait ? width : height,
format: type as InputFormat,
+ orientation,
};
}
diff --git a/packages/integrations/image/src/utils/paths.ts b/packages/integrations/image/src/utils/paths.ts
index 1f691f35a..1ebf3ece7 100644
--- a/packages/integrations/image/src/utils/paths.ts
+++ b/packages/integrations/image/src/utils/paths.ts
@@ -10,14 +10,15 @@ function removeQueryString(src: string) {
return index > 0 ? src.substring(0, index) : src;
}
-function extname(src: string, format?: OutputFormat) {
- const index = src.lastIndexOf('.');
+export function extname(src: string) {
+ const base = basename(src);
+ const index = base.lastIndexOf('.');
if (index <= 0) {
return '';
}
- return src.substring(index);
+ return src.substring(src.length - (base.length - index));
}
function removeExtname(src: string) {
diff --git a/packages/integrations/image/src/utils/workerPool.ts b/packages/integrations/image/src/utils/workerPool.ts
new file mode 100644
index 000000000..5b6b75829
--- /dev/null
+++ b/packages/integrations/image/src/utils/workerPool.ts
@@ -0,0 +1,125 @@
+/* tslint-disable ban-types */
+import { Worker, parentPort } from 'worker_threads';
+import { TransformStream } from 'web-streams-polyfill';
+
+function uuid() {
+ return Array.from({ length: 16 }, () =>
+ Math.floor(Math.random() * 256).toString(16),
+ ).join('');
+}
+
+interface Job {
+ msg: I;
+ resolve: (result: any) => void;
+ reject: (reason: any) => void;
+}
+
+export default class WorkerPool {
+ public numWorkers: number;
+ public jobQueue: TransformStream, Job>;
+ public workerQueue: TransformStream;
+ public done: Promise;
+
+ constructor(numWorkers: number, workerFile: string) {
+ this.numWorkers = numWorkers;
+ this.jobQueue = new TransformStream();
+ this.workerQueue = new TransformStream();
+
+ const writer = this.workerQueue.writable.getWriter();
+ for (let i = 0; i < numWorkers; i++) {
+ writer.write(new Worker(workerFile));
+ }
+ writer.releaseLock();
+
+ this.done = this._readLoop();
+ }
+
+ async _readLoop() {
+ const reader = this.jobQueue.readable.getReader();
+ while (true) {
+ const { value, done } = await reader.read();
+ if (done) {
+ await this._terminateAll();
+ return;
+ }
+
+ if (!value) {
+ throw new Error('Reader did not return any value');
+ }
+
+ const { msg, resolve, reject } = value;
+ const worker = await this._nextWorker();
+ this.jobPromise(worker, msg)
+ .then((result) => resolve(result))
+ .catch((reason) => reject(reason))
+ .finally(() => {
+ // Return the worker to the pool
+ const writer = this.workerQueue.writable.getWriter();
+ writer.write(worker);
+ writer.releaseLock();
+ });
+ }
+ }
+
+ async _nextWorker() {
+ const reader = this.workerQueue.readable.getReader();
+ const { value } = await reader.read();
+ reader.releaseLock();
+ if (!value) {
+ throw new Error('No worker left');
+ }
+
+ return value;
+ }
+
+ async _terminateAll() {
+ for (let n = 0; n < this.numWorkers; n++) {
+ const worker = await this._nextWorker();
+ worker.terminate();
+ }
+ this.workerQueue.writable.close();
+ }
+
+ async join() {
+ this.jobQueue.writable.getWriter().close();
+ await this.done;
+ }
+
+ dispatchJob(msg: I): Promise {
+ return new Promise((resolve, reject) => {
+ const writer = this.jobQueue.writable.getWriter();
+ writer.write({ msg, resolve, reject });
+ writer.releaseLock();
+ });
+ }
+
+ private jobPromise(worker: Worker, msg: I) {
+ return new Promise((resolve, reject) => {
+ const id = uuid();
+ worker.postMessage({ msg, id });
+ worker.on('message', function f({ error, result, id: rid }) {
+ if (rid !== id) {
+ return;
+ }
+ if (error) {
+ reject(error);
+ return;
+ }
+ worker.off('message', f);
+ resolve(result);
+ });
+ });
+ }
+
+ static useThisThreadAsWorker(cb: (msg: I) => O) {
+ parentPort!.on('message', async (data) => {
+ const { msg, id } = data;
+ try {
+ const result = await cb(msg);
+ parentPort!.postMessage({ result, id });
+ } catch (e: any) {
+ parentPort!.postMessage({ error: e.message, id });
+ }
+ });
+ }
+}
diff --git a/packages/integrations/image/src/vendor/squoosh/LICENSE b/packages/integrations/image/src/vendor/squoosh/LICENSE
new file mode 100644
index 000000000..fe27d9324
--- /dev/null
+++ b/packages/integrations/image/src/vendor/squoosh/LICENSE
@@ -0,0 +1,245 @@
+
+Skip to content
+Pull requests
+Issues
+Marketplace
+Explore
+@tony-sull
+vercel /
+next.js
+Public
+
+Code
+Issues 1.1k
+Pull requests 216
+Discussions
+Actions
+Security 8
+
+ Insights
+
+next.js/packages/next/server/lib/squoosh/LICENSE
+@timneutkens
+timneutkens Move next-server directory files to server directory (#26756)
+Latest commit 5b9ad8d on Jun 30, 2021
+History
+1 contributor
+202 lines (169 sloc) 11.1 KB
+
+ Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+ 1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+ 2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+ 3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+ 4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+ 6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+ 7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+ 8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+ 9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+ END OF TERMS AND CONDITIONS
+
+ APPENDIX: How to apply the Apache License to your work.
+
+ To apply the Apache License to your work, attach the following
+ boilerplate notice, with the fields enclosed by brackets "[]"
+ replaced with your own identifying information. (Don't include
+ the brackets!) The text should be enclosed in the appropriate
+ comment syntax for the file format. We also recommend that a
+ file or class name and description of purpose be included on the
+ same "printed page" as the copyright notice for easier
+ identification within third-party archives.
+
+ Copyright [yyyy] [name of copyright owner]
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+Footer
+© 2022 GitHub, Inc.
+Footer navigation
+
+ Terms
+ Privacy
+ Security
+ Status
+ Docs
+ Contact GitHub
+ Pricing
+ API
+ Training
+ Blog
+ About
+
diff --git a/packages/integrations/image/src/vendor/squoosh/avif/avif_enc.d.ts b/packages/integrations/image/src/vendor/squoosh/avif/avif_enc.d.ts
new file mode 100644
index 000000000..d91bbf36e
--- /dev/null
+++ b/packages/integrations/image/src/vendor/squoosh/avif/avif_enc.d.ts
@@ -0,0 +1,32 @@
+// eslint-disable-next-line no-shadow
+export const enum AVIFTune {
+ auto,
+ psnr,
+ ssim,
+}
+
+export interface EncodeOptions {
+ cqLevel: number
+ denoiseLevel: number
+ cqAlphaLevel: number
+ tileRowsLog2: number
+ tileColsLog2: number
+ speed: number
+ subsample: number
+ chromaDeltaQ: boolean
+ sharpness: number
+ tune: AVIFTune
+}
+
+export interface AVIFModule extends EmscriptenWasm.Module {
+ encode(
+ data: BufferSource,
+ width: number,
+ height: number,
+ options: EncodeOptions
+ ): Uint8Array
+}
+
+declare var moduleFactory: EmscriptenWasm.ModuleFactory
+
+export default moduleFactory
diff --git a/packages/integrations/image/src/vendor/squoosh/avif/avif_node_dec.ts b/packages/integrations/image/src/vendor/squoosh/avif/avif_node_dec.ts
new file mode 100644
index 000000000..44f9ab33d
--- /dev/null
+++ b/packages/integrations/image/src/vendor/squoosh/avif/avif_node_dec.ts
@@ -0,0 +1,1799 @@
+/* eslint-disable */
+// @ts-nocheck
+import { createRequire } from 'module';
+const require = createRequire(import.meta.url);
+import { dirname } from '../emscripten-utils.js';
+
+var Module = (function () {
+ return function (Module) {
+ Module = Module || {}
+
+ var Module = typeof Module !== 'undefined' ? Module : {}
+ var readyPromiseResolve, readyPromiseReject
+ Module['ready'] = new Promise(function (resolve, reject) {
+ readyPromiseResolve = resolve
+ readyPromiseReject = reject
+ })
+ var moduleOverrides = {}
+ var key
+ for (key in Module) {
+ if (Module.hasOwnProperty(key)) {
+ moduleOverrides[key] = Module[key]
+ }
+ }
+ var arguments_ = []
+ var thisProgram = './this.program'
+ var quit_ = function (status, toThrow) {
+ throw toThrow
+ }
+ var ENVIRONMENT_IS_WEB = false
+ var ENVIRONMENT_IS_WORKER = false
+ var ENVIRONMENT_IS_NODE = true
+ var scriptDirectory = ''
+ function locateFile(path) {
+ if (Module['locateFile']) {
+ return Module['locateFile'](path, scriptDirectory)
+ }
+ return scriptDirectory + path
+ }
+ var read_, readBinary
+ var nodeFS
+ var nodePath
+ if (ENVIRONMENT_IS_NODE) {
+ if (ENVIRONMENT_IS_WORKER) {
+ scriptDirectory = require('path').dirname(scriptDirectory) + '/'
+ } else {
+ scriptDirectory = dirname(import.meta.url) + '/'
+ }
+ read_ = function shell_read(filename, binary) {
+ if (!nodeFS) nodeFS = require('fs')
+ if (!nodePath) nodePath = require('path')
+ filename = nodePath['normalize'](filename)
+ return nodeFS['readFileSync'](filename, binary ? null : 'utf8')
+ }
+ readBinary = function readBinary(filename) {
+ var ret = read_(filename, true)
+ if (!ret.buffer) {
+ ret = new Uint8Array(ret)
+ }
+ assert(ret.buffer)
+ return ret
+ }
+ if (process['argv'].length > 1) {
+ thisProgram = process['argv'][1].replace(/\\/g, '/')
+ }
+ arguments_ = process['argv'].slice(2)
+ quit_ = function (status) {
+ process['exit'](status)
+ }
+ Module['inspect'] = function () {
+ return '[Emscripten Module object]'
+ }
+ } else {
+ }
+ var out = Module['print'] || console.log.bind(console)
+ var err = Module['printErr'] || console.warn.bind(console)
+ for (key in moduleOverrides) {
+ if (moduleOverrides.hasOwnProperty(key)) {
+ Module[key] = moduleOverrides[key]
+ }
+ }
+ moduleOverrides = null
+ if (Module['arguments']) arguments_ = Module['arguments']
+ if (Module['thisProgram']) thisProgram = Module['thisProgram']
+ if (Module['quit']) quit_ = Module['quit']
+ var tempRet0 = 0
+ var setTempRet0 = function (value) {
+ tempRet0 = value
+ }
+ var getTempRet0 = function () {
+ return tempRet0
+ }
+ var wasmBinary
+ if (Module['wasmBinary']) wasmBinary = Module['wasmBinary']
+ var noExitRuntime = Module['noExitRuntime'] || true
+ if (typeof WebAssembly !== 'object') {
+ abort('no native wasm support detected')
+ }
+ var wasmMemory
+ var ABORT = false
+ var EXITSTATUS
+ function assert(condition, text) {
+ if (!condition) {
+ abort('Assertion failed: ' + text)
+ }
+ }
+ var UTF8Decoder = new TextDecoder('utf8')
+ function UTF8ArrayToString(heap, idx, maxBytesToRead) {
+ var endIdx = idx + maxBytesToRead
+ var endPtr = idx
+ while (heap[endPtr] && !(endPtr >= endIdx)) ++endPtr
+ return UTF8Decoder.decode(
+ heap.subarray
+ ? heap.subarray(idx, endPtr)
+ : new Uint8Array(heap.slice(idx, endPtr))
+ )
+ }
+ function UTF8ToString(ptr, maxBytesToRead) {
+ if (!ptr) return ''
+ var maxPtr = ptr + maxBytesToRead
+ for (var end = ptr; !(end >= maxPtr) && HEAPU8[end]; ) ++end
+ return UTF8Decoder.decode(HEAPU8.subarray(ptr, end))
+ }
+ function stringToUTF8Array(str, heap, outIdx, maxBytesToWrite) {
+ if (!(maxBytesToWrite > 0)) return 0
+ var startIdx = outIdx
+ var endIdx = outIdx + maxBytesToWrite - 1
+ for (var i = 0; i < str.length; ++i) {
+ var u = str.charCodeAt(i)
+ if (u >= 55296 && u <= 57343) {
+ var u1 = str.charCodeAt(++i)
+ u = (65536 + ((u & 1023) << 10)) | (u1 & 1023)
+ }
+ if (u <= 127) {
+ if (outIdx >= endIdx) break
+ heap[outIdx++] = u
+ } else if (u <= 2047) {
+ if (outIdx + 1 >= endIdx) break
+ heap[outIdx++] = 192 | (u >> 6)
+ heap[outIdx++] = 128 | (u & 63)
+ } else if (u <= 65535) {
+ if (outIdx + 2 >= endIdx) break
+ heap[outIdx++] = 224 | (u >> 12)
+ heap[outIdx++] = 128 | ((u >> 6) & 63)
+ heap[outIdx++] = 128 | (u & 63)
+ } else {
+ if (outIdx + 3 >= endIdx) break
+ heap[outIdx++] = 240 | (u >> 18)
+ heap[outIdx++] = 128 | ((u >> 12) & 63)
+ heap[outIdx++] = 128 | ((u >> 6) & 63)
+ heap[outIdx++] = 128 | (u & 63)
+ }
+ }
+ heap[outIdx] = 0
+ return outIdx - startIdx
+ }
+ function stringToUTF8(str, outPtr, maxBytesToWrite) {
+ return stringToUTF8Array(str, HEAPU8, outPtr, maxBytesToWrite)
+ }
+ function lengthBytesUTF8(str) {
+ var len = 0
+ for (var i = 0; i < str.length; ++i) {
+ var u = str.charCodeAt(i)
+ if (u >= 55296 && u <= 57343)
+ u = (65536 + ((u & 1023) << 10)) | (str.charCodeAt(++i) & 1023)
+ if (u <= 127) ++len
+ else if (u <= 2047) len += 2
+ else if (u <= 65535) len += 3
+ else len += 4
+ }
+ return len
+ }
+ var UTF16Decoder = new TextDecoder('utf-16le')
+ function UTF16ToString(ptr, maxBytesToRead) {
+ var endPtr = ptr
+ var idx = endPtr >> 1
+ var maxIdx = idx + maxBytesToRead / 2
+ while (!(idx >= maxIdx) && HEAPU16[idx]) ++idx
+ endPtr = idx << 1
+ return UTF16Decoder.decode(HEAPU8.subarray(ptr, endPtr))
+ var str = ''
+ for (var i = 0; !(i >= maxBytesToRead / 2); ++i) {
+ var codeUnit = HEAP16[(ptr + i * 2) >> 1]
+ if (codeUnit == 0) break
+ str += String.fromCharCode(codeUnit)
+ }
+ return str
+ }
+ function stringToUTF16(str, outPtr, maxBytesToWrite) {
+ if (maxBytesToWrite === undefined) {
+ maxBytesToWrite = 2147483647
+ }
+ if (maxBytesToWrite < 2) return 0
+ maxBytesToWrite -= 2
+ var startPtr = outPtr
+ var numCharsToWrite =
+ maxBytesToWrite < str.length * 2 ? maxBytesToWrite / 2 : str.length
+ for (var i = 0; i < numCharsToWrite; ++i) {
+ var codeUnit = str.charCodeAt(i)
+ HEAP16[outPtr >> 1] = codeUnit
+ outPtr += 2
+ }
+ HEAP16[outPtr >> 1] = 0
+ return outPtr - startPtr
+ }
+ function lengthBytesUTF16(str) {
+ return str.length * 2
+ }
+ function UTF32ToString(ptr, maxBytesToRead) {
+ var i = 0
+ var str = ''
+ while (!(i >= maxBytesToRead / 4)) {
+ var utf32 = HEAP32[(ptr + i * 4) >> 2]
+ if (utf32 == 0) break
+ ++i
+ if (utf32 >= 65536) {
+ var ch = utf32 - 65536
+ str += String.fromCharCode(55296 | (ch >> 10), 56320 | (ch & 1023))
+ } else {
+ str += String.fromCharCode(utf32)
+ }
+ }
+ return str
+ }
+ function stringToUTF32(str, outPtr, maxBytesToWrite) {
+ if (maxBytesToWrite === undefined) {
+ maxBytesToWrite = 2147483647
+ }
+ if (maxBytesToWrite < 4) return 0
+ var startPtr = outPtr
+ var endPtr = startPtr + maxBytesToWrite - 4
+ for (var i = 0; i < str.length; ++i) {
+ var codeUnit = str.charCodeAt(i)
+ if (codeUnit >= 55296 && codeUnit <= 57343) {
+ var trailSurrogate = str.charCodeAt(++i)
+ codeUnit =
+ (65536 + ((codeUnit & 1023) << 10)) | (trailSurrogate & 1023)
+ }
+ HEAP32[outPtr >> 2] = codeUnit
+ outPtr += 4
+ if (outPtr + 4 > endPtr) break
+ }
+ HEAP32[outPtr >> 2] = 0
+ return outPtr - startPtr
+ }
+ function lengthBytesUTF32(str) {
+ var len = 0
+ for (var i = 0; i < str.length; ++i) {
+ var codeUnit = str.charCodeAt(i)
+ if (codeUnit >= 55296 && codeUnit <= 57343) ++i
+ len += 4
+ }
+ return len
+ }
+ function alignUp(x, multiple) {
+ if (x % multiple > 0) {
+ x += multiple - (x % multiple)
+ }
+ return x
+ }
+ var buffer,
+ HEAP8,
+ HEAPU8,
+ HEAP16,
+ HEAPU16,
+ HEAP32,
+ HEAPU32,
+ HEAPF32,
+ HEAPF64
+ function updateGlobalBufferAndViews(buf) {
+ buffer = buf
+ Module['HEAP8'] = HEAP8 = new Int8Array(buf)
+ Module['HEAP16'] = HEAP16 = new Int16Array(buf)
+ Module['HEAP32'] = HEAP32 = new Int32Array(buf)
+ Module['HEAPU8'] = HEAPU8 = new Uint8Array(buf)
+ Module['HEAPU16'] = HEAPU16 = new Uint16Array(buf)
+ Module['HEAPU32'] = HEAPU32 = new Uint32Array(buf)
+ Module['HEAPF32'] = HEAPF32 = new Float32Array(buf)
+ Module['HEAPF64'] = HEAPF64 = new Float64Array(buf)
+ }
+ var INITIAL_MEMORY = Module['INITIAL_MEMORY'] || 16777216
+ var wasmTable
+ var __ATPRERUN__ = []
+ var __ATINIT__ = []
+ var __ATPOSTRUN__ = []
+ var runtimeInitialized = false
+ function preRun() {
+ if (Module['preRun']) {
+ if (typeof Module['preRun'] == 'function')
+ Module['preRun'] = [Module['preRun']]
+ while (Module['preRun'].length) {
+ addOnPreRun(Module['preRun'].shift())
+ }
+ }
+ callRuntimeCallbacks(__ATPRERUN__)
+ }
+ function initRuntime() {
+ runtimeInitialized = true
+ callRuntimeCallbacks(__ATINIT__)
+ }
+ function postRun() {
+ if (Module['postRun']) {
+ if (typeof Module['postRun'] == 'function')
+ Module['postRun'] = [Module['postRun']]
+ while (Module['postRun'].length) {
+ addOnPostRun(Module['postRun'].shift())
+ }
+ }
+ callRuntimeCallbacks(__ATPOSTRUN__)
+ }
+ function addOnPreRun(cb) {
+ __ATPRERUN__.unshift(cb)
+ }
+ function addOnInit(cb) {
+ __ATINIT__.unshift(cb)
+ }
+ function addOnPostRun(cb) {
+ __ATPOSTRUN__.unshift(cb)
+ }
+ var runDependencies = 0
+ var runDependencyWatcher = null
+ var dependenciesFulfilled = null
+ function addRunDependency(id) {
+ runDependencies++
+ if (Module['monitorRunDependencies']) {
+ Module['monitorRunDependencies'](runDependencies)
+ }
+ }
+ function removeRunDependency(id) {
+ runDependencies--
+ if (Module['monitorRunDependencies']) {
+ Module['monitorRunDependencies'](runDependencies)
+ }
+ if (runDependencies == 0) {
+ if (runDependencyWatcher !== null) {
+ clearInterval(runDependencyWatcher)
+ runDependencyWatcher = null
+ }
+ if (dependenciesFulfilled) {
+ var callback = dependenciesFulfilled
+ dependenciesFulfilled = null
+ callback()
+ }
+ }
+ }
+ Module['preloadedImages'] = {}
+ Module['preloadedAudios'] = {}
+ function abort(what) {
+ if (Module['onAbort']) {
+ Module['onAbort'](what)
+ }
+ what += ''
+ err(what)
+ ABORT = true
+ EXITSTATUS = 1
+ what = 'abort(' + what + '). Build with -s ASSERTIONS=1 for more info.'
+ var e = new WebAssembly.RuntimeError(what)
+ readyPromiseReject(e)
+ throw e
+ }
+ var dataURIPrefix = 'data:application/octet-stream;base64,'
+ function isDataURI(filename) {
+ return filename.startsWith(dataURIPrefix)
+ }
+ if (Module['locateFile']) {
+ var wasmBinaryFile = 'avif_node_dec.wasm'
+ if (!isDataURI(wasmBinaryFile)) {
+ wasmBinaryFile = locateFile(wasmBinaryFile)
+ }
+ } else {
+ throw new Error('invariant')
+ }
+ function getBinary(file) {
+ try {
+ if (file == wasmBinaryFile && wasmBinary) {
+ return new Uint8Array(wasmBinary)
+ }
+ if (readBinary) {
+ return readBinary(file)
+ } else {
+ throw 'both async and sync fetching of the wasm failed'
+ }
+ } catch (err) {
+ abort(err)
+ }
+ }
+ function getBinaryPromise() {
+ if (!wasmBinary && (ENVIRONMENT_IS_WEB || ENVIRONMENT_IS_WORKER)) {
+ if (typeof fetch === 'function') {
+ return fetch(wasmBinaryFile, { credentials: 'same-origin' })
+ .then(function (response) {
+ if (!response['ok']) {
+ throw (
+ "failed to load wasm binary file at '" + wasmBinaryFile + "'"
+ )
+ }
+ return response['arrayBuffer']()
+ })
+ .catch(function () {
+ return getBinary(wasmBinaryFile)
+ })
+ }
+ }
+ return Promise.resolve().then(function () {
+ return getBinary(wasmBinaryFile)
+ })
+ }
+ function createWasm() {
+ var info = { a: asmLibraryArg }
+ function receiveInstance(instance, module) {
+ var exports = instance.exports
+ Module['asm'] = exports
+ wasmMemory = Module['asm']['C']
+ updateGlobalBufferAndViews(wasmMemory.buffer)
+ wasmTable = Module['asm']['L']
+ addOnInit(Module['asm']['D'])
+ removeRunDependency('wasm-instantiate')
+ }
+ addRunDependency('wasm-instantiate')
+ function receiveInstantiationResult(result) {
+ receiveInstance(result['instance'])
+ }
+ function instantiateArrayBuffer(receiver) {
+ return getBinaryPromise()
+ .then(function (binary) {
+ var result = WebAssembly.instantiate(binary, info)
+ return result
+ })
+ .then(receiver, function (reason) {
+ err('failed to asynchronously prepare wasm: ' + reason)
+ abort(reason)
+ })
+ }
+ function instantiateAsync() {
+ if (
+ !wasmBinary &&
+ typeof WebAssembly.instantiateStreaming === 'function' &&
+ !isDataURI(wasmBinaryFile) &&
+ typeof fetch === 'function'
+ ) {
+ return fetch(wasmBinaryFile, { credentials: 'same-origin' }).then(
+ function (response) {
+ var result = WebAssembly.instantiateStreaming(response, info)
+ return result.then(receiveInstantiationResult, function (reason) {
+ err('wasm streaming compile failed: ' + reason)
+ err('falling back to ArrayBuffer instantiation')
+ return instantiateArrayBuffer(receiveInstantiationResult)
+ })
+ }
+ )
+ } else {
+ return instantiateArrayBuffer(receiveInstantiationResult)
+ }
+ }
+ if (Module['instantiateWasm']) {
+ try {
+ var exports = Module['instantiateWasm'](info, receiveInstance)
+ return exports
+ } catch (e) {
+ err('Module.instantiateWasm callback failed with error: ' + e)
+ return false
+ }
+ }
+ instantiateAsync().catch(readyPromiseReject)
+ return {}
+ }
+ function callRuntimeCallbacks(callbacks) {
+ while (callbacks.length > 0) {
+ var callback = callbacks.shift()
+ if (typeof callback == 'function') {
+ callback(Module)
+ continue
+ }
+ var func = callback.func
+ if (typeof func === 'number') {
+ if (callback.arg === undefined) {
+ wasmTable.get(func)()
+ } else {
+ wasmTable.get(func)(callback.arg)
+ }
+ } else {
+ func(callback.arg === undefined ? null : callback.arg)
+ }
+ }
+ }
+ function _atexit(func, arg) {}
+ function ___cxa_thread_atexit(a0, a1) {
+ return _atexit(a0, a1)
+ }
+ function __embind_register_bigint(
+ primitiveType,
+ name,
+ size,
+ minRange,
+ maxRange
+ ) {}
+ function getShiftFromSize(size) {
+ switch (size) {
+ case 1:
+ return 0
+ case 2:
+ return 1
+ case 4:
+ return 2
+ case 8:
+ return 3
+ default:
+ throw new TypeError('Unknown type size: ' + size)
+ }
+ }
+ function embind_init_charCodes() {
+ var codes = new Array(256)
+ for (var i = 0; i < 256; ++i) {
+ codes[i] = String.fromCharCode(i)
+ }
+ embind_charCodes = codes
+ }
+ var embind_charCodes = undefined
+ function readLatin1String(ptr) {
+ var ret = ''
+ var c = ptr
+ while (HEAPU8[c]) {
+ ret += embind_charCodes[HEAPU8[c++]]
+ }
+ return ret
+ }
+ var awaitingDependencies = {}
+ var registeredTypes = {}
+ var typeDependencies = {}
+ var char_0 = 48
+ var char_9 = 57
+ function makeLegalFunctionName(name) {
+ if (undefined === name) {
+ return '_unknown'
+ }
+ name = name.replace(/[^a-zA-Z0-9_]/g, '$')
+ var f = name.charCodeAt(0)
+ if (f >= char_0 && f <= char_9) {
+ return '_' + name
+ } else {
+ return name
+ }
+ }
+ function createNamedFunction(name, body) {
+ name = makeLegalFunctionName(name)
+ return new Function(
+ 'body',
+ 'return function ' +
+ name +
+ '() {\n' +
+ ' "use strict";' +
+ ' return body.apply(this, arguments);\n' +
+ '};\n'
+ )(body)
+ }
+ function extendError(baseErrorType, errorName) {
+ var errorClass = createNamedFunction(errorName, function (message) {
+ this.name = errorName
+ this.message = message
+ var stack = new Error(message).stack
+ if (stack !== undefined) {
+ this.stack =
+ this.toString() + '\n' + stack.replace(/^Error(:[^\n]*)?\n/, '')
+ }
+ })
+ errorClass.prototype = Object.create(baseErrorType.prototype)
+ errorClass.prototype.constructor = errorClass
+ errorClass.prototype.toString = function () {
+ if (this.message === undefined) {
+ return this.name
+ } else {
+ return this.name + ': ' + this.message
+ }
+ }
+ return errorClass
+ }
+ var BindingError = undefined
+ function throwBindingError(message) {
+ throw new BindingError(message)
+ }
+ var InternalError = undefined
+ function throwInternalError(message) {
+ throw new InternalError(message)
+ }
+ function whenDependentTypesAreResolved(
+ myTypes,
+ dependentTypes,
+ getTypeConverters
+ ) {
+ myTypes.forEach(function (type) {
+ typeDependencies[type] = dependentTypes
+ })
+ function onComplete(typeConverters) {
+ var myTypeConverters = getTypeConverters(typeConverters)
+ if (myTypeConverters.length !== myTypes.length) {
+ throwInternalError('Mismatched type converter count')
+ }
+ for (var i = 0; i < myTypes.length; ++i) {
+ registerType(myTypes[i], myTypeConverters[i])
+ }
+ }
+ var typeConverters = new Array(dependentTypes.length)
+ var unregisteredTypes = []
+ var registered = 0
+ dependentTypes.forEach(function (dt, i) {
+ if (registeredTypes.hasOwnProperty(dt)) {
+ typeConverters[i] = registeredTypes[dt]
+ } else {
+ unregisteredTypes.push(dt)
+ if (!awaitingDependencies.hasOwnProperty(dt)) {
+ awaitingDependencies[dt] = []
+ }
+ awaitingDependencies[dt].push(function () {
+ typeConverters[i] = registeredTypes[dt]
+ ++registered
+ if (registered === unregisteredTypes.length) {
+ onComplete(typeConverters)
+ }
+ })
+ }
+ })
+ if (0 === unregisteredTypes.length) {
+ onComplete(typeConverters)
+ }
+ }
+ function registerType(rawType, registeredInstance, options) {
+ options = options || {}
+ if (!('argPackAdvance' in registeredInstance)) {
+ throw new TypeError(
+ 'registerType registeredInstance requires argPackAdvance'
+ )
+ }
+ var name = registeredInstance.name
+ if (!rawType) {
+ throwBindingError(
+ 'type "' + name + '" must have a positive integer typeid pointer'
+ )
+ }
+ if (registeredTypes.hasOwnProperty(rawType)) {
+ if (options.ignoreDuplicateRegistrations) {
+ return
+ } else {
+ throwBindingError("Cannot register type '" + name + "' twice")
+ }
+ }
+ registeredTypes[rawType] = registeredInstance
+ delete typeDependencies[rawType]
+ if (awaitingDependencies.hasOwnProperty(rawType)) {
+ var callbacks = awaitingDependencies[rawType]
+ delete awaitingDependencies[rawType]
+ callbacks.forEach(function (cb) {
+ cb()
+ })
+ }
+ }
+ function __embind_register_bool(
+ rawType,
+ name,
+ size,
+ trueValue,
+ falseValue
+ ) {
+ var shift = getShiftFromSize(size)
+ name = readLatin1String(name)
+ registerType(rawType, {
+ name: name,
+ fromWireType: function (wt) {
+ return !!wt
+ },
+ toWireType: function (destructors, o) {
+ return o ? trueValue : falseValue
+ },
+ argPackAdvance: 8,
+ readValueFromPointer: function (pointer) {
+ var heap
+ if (size === 1) {
+ heap = HEAP8
+ } else if (size === 2) {
+ heap = HEAP16
+ } else if (size === 4) {
+ heap = HEAP32
+ } else {
+ throw new TypeError('Unknown boolean type size: ' + name)
+ }
+ return this['fromWireType'](heap[pointer >> shift])
+ },
+ destructorFunction: null,
+ })
+ }
+ var emval_free_list = []
+ var emval_handle_array = [
+ {},
+ { value: undefined },
+ { value: null },
+ { value: true },
+ { value: false },
+ ]
+ function __emval_decref(handle) {
+ if (handle > 4 && 0 === --emval_handle_array[handle].refcount) {
+ emval_handle_array[handle] = undefined
+ emval_free_list.push(handle)
+ }
+ }
+ function count_emval_handles() {
+ var count = 0
+ for (var i = 5; i < emval_handle_array.length; ++i) {
+ if (emval_handle_array[i] !== undefined) {
+ ++count
+ }
+ }
+ return count
+ }
+ function get_first_emval() {
+ for (var i = 5; i < emval_handle_array.length; ++i) {
+ if (emval_handle_array[i] !== undefined) {
+ return emval_handle_array[i]
+ }
+ }
+ return null
+ }
+ function init_emval() {
+ Module['count_emval_handles'] = count_emval_handles
+ Module['get_first_emval'] = get_first_emval
+ }
+ function __emval_register(value) {
+ switch (value) {
+ case undefined: {
+ return 1
+ }
+ case null: {
+ return 2
+ }
+ case true: {
+ return 3
+ }
+ case false: {
+ return 4
+ }
+ default: {
+ var handle = emval_free_list.length
+ ? emval_free_list.pop()
+ : emval_handle_array.length
+ emval_handle_array[handle] = { refcount: 1, value: value }
+ return handle
+ }
+ }
+ }
+ function simpleReadValueFromPointer(pointer) {
+ return this['fromWireType'](HEAPU32[pointer >> 2])
+ }
+ function __embind_register_emval(rawType, name) {
+ name = readLatin1String(name)
+ registerType(rawType, {
+ name: name,
+ fromWireType: function (handle) {
+ var rv = emval_handle_array[handle].value
+ __emval_decref(handle)
+ return rv
+ },
+ toWireType: function (destructors, value) {
+ return __emval_register(value)
+ },
+ argPackAdvance: 8,
+ readValueFromPointer: simpleReadValueFromPointer,
+ destructorFunction: null,
+ })
+ }
+ function _embind_repr(v) {
+ if (v === null) {
+ return 'null'
+ }
+ var t = typeof v
+ if (t === 'object' || t === 'array' || t === 'function') {
+ return v.toString()
+ } else {
+ return '' + v
+ }
+ }
+ function floatReadValueFromPointer(name, shift) {
+ switch (shift) {
+ case 2:
+ return function (pointer) {
+ return this['fromWireType'](HEAPF32[pointer >> 2])
+ }
+ case 3:
+ return function (pointer) {
+ return this['fromWireType'](HEAPF64[pointer >> 3])
+ }
+ default:
+ throw new TypeError('Unknown float type: ' + name)
+ }
+ }
+ function __embind_register_float(rawType, name, size) {
+ var shift = getShiftFromSize(size)
+ name = readLatin1String(name)
+ registerType(rawType, {
+ name: name,
+ fromWireType: function (value) {
+ return value
+ },
+ toWireType: function (destructors, value) {
+ if (typeof value !== 'number' && typeof value !== 'boolean') {
+ throw new TypeError(
+ 'Cannot convert "' + _embind_repr(value) + '" to ' + this.name
+ )
+ }
+ return value
+ },
+ argPackAdvance: 8,
+ readValueFromPointer: floatReadValueFromPointer(name, shift),
+ destructorFunction: null,
+ })
+ }
+ function new_(constructor, argumentList) {
+ if (!(constructor instanceof Function)) {
+ throw new TypeError(
+ 'new_ called with constructor type ' +
+ typeof constructor +
+ ' which is not a function'
+ )
+ }
+ var dummy = createNamedFunction(
+ constructor.name || 'unknownFunctionName',
+ function () {}
+ )
+ dummy.prototype = constructor.prototype
+ var obj = new dummy()
+ var r = constructor.apply(obj, argumentList)
+ return r instanceof Object ? r : obj
+ }
+ function runDestructors(destructors) {
+ while (destructors.length) {
+ var ptr = destructors.pop()
+ var del = destructors.pop()
+ del(ptr)
+ }
+ }
+ function craftInvokerFunction(
+ humanName,
+ argTypes,
+ classType,
+ cppInvokerFunc,
+ cppTargetFunc
+ ) {
+ var argCount = argTypes.length
+ if (argCount < 2) {
+ throwBindingError(
+ "argTypes array size mismatch! Must at least get return value and 'this' types!"
+ )
+ }
+ var isClassMethodFunc = argTypes[1] !== null && classType !== null
+ var needsDestructorStack = false
+ for (var i = 1; i < argTypes.length; ++i) {
+ if (
+ argTypes[i] !== null &&
+ argTypes[i].destructorFunction === undefined
+ ) {
+ needsDestructorStack = true
+ break
+ }
+ }
+ var returns = argTypes[0].name !== 'void'
+ var argsList = ''
+ var argsListWired = ''
+ for (var i = 0; i < argCount - 2; ++i) {
+ argsList += (i !== 0 ? ', ' : '') + 'arg' + i
+ argsListWired += (i !== 0 ? ', ' : '') + 'arg' + i + 'Wired'
+ }
+ var invokerFnBody =
+ 'return function ' +
+ makeLegalFunctionName(humanName) +
+ '(' +
+ argsList +
+ ') {\n' +
+ 'if (arguments.length !== ' +
+ (argCount - 2) +
+ ') {\n' +
+ "throwBindingError('function " +
+ humanName +
+ " called with ' + arguments.length + ' arguments, expected " +
+ (argCount - 2) +
+ " args!');\n" +
+ '}\n'
+ if (needsDestructorStack) {
+ invokerFnBody += 'var destructors = [];\n'
+ }
+ var dtorStack = needsDestructorStack ? 'destructors' : 'null'
+ var args1 = [
+ 'throwBindingError',
+ 'invoker',
+ 'fn',
+ 'runDestructors',
+ 'retType',
+ 'classParam',
+ ]
+ var args2 = [
+ throwBindingError,
+ cppInvokerFunc,
+ cppTargetFunc,
+ runDestructors,
+ argTypes[0],
+ argTypes[1],
+ ]
+ if (isClassMethodFunc) {
+ invokerFnBody +=
+ 'var thisWired = classParam.toWireType(' + dtorStack + ', this);\n'
+ }
+ for (var i = 0; i < argCount - 2; ++i) {
+ invokerFnBody +=
+ 'var arg' +
+ i +
+ 'Wired = argType' +
+ i +
+ '.toWireType(' +
+ dtorStack +
+ ', arg' +
+ i +
+ '); // ' +
+ argTypes[i + 2].name +
+ '\n'
+ args1.push('argType' + i)
+ args2.push(argTypes[i + 2])
+ }
+ if (isClassMethodFunc) {
+ argsListWired =
+ 'thisWired' + (argsListWired.length > 0 ? ', ' : '') + argsListWired
+ }
+ invokerFnBody +=
+ (returns ? 'var rv = ' : '') +
+ 'invoker(fn' +
+ (argsListWired.length > 0 ? ', ' : '') +
+ argsListWired +
+ ');\n'
+ if (needsDestructorStack) {
+ invokerFnBody += 'runDestructors(destructors);\n'
+ } else {
+ for (var i = isClassMethodFunc ? 1 : 2; i < argTypes.length; ++i) {
+ var paramName = i === 1 ? 'thisWired' : 'arg' + (i - 2) + 'Wired'
+ if (argTypes[i].destructorFunction !== null) {
+ invokerFnBody +=
+ paramName +
+ '_dtor(' +
+ paramName +
+ '); // ' +
+ argTypes[i].name +
+ '\n'
+ args1.push(paramName + '_dtor')
+ args2.push(argTypes[i].destructorFunction)
+ }
+ }
+ }
+ if (returns) {
+ invokerFnBody +=
+ 'var ret = retType.fromWireType(rv);\n' + 'return ret;\n'
+ } else {
+ }
+ invokerFnBody += '}\n'
+ args1.push(invokerFnBody)
+ var invokerFunction = new_(Function, args1).apply(null, args2)
+ return invokerFunction
+ }
+ function ensureOverloadTable(proto, methodName, humanName) {
+ if (undefined === proto[methodName].overloadTable) {
+ var prevFunc = proto[methodName]
+ proto[methodName] = function () {
+ if (
+ !proto[methodName].overloadTable.hasOwnProperty(arguments.length)
+ ) {
+ throwBindingError(
+ "Function '" +
+ humanName +
+ "' called with an invalid number of arguments (" +
+ arguments.length +
+ ') - expects one of (' +
+ proto[methodName].overloadTable +
+ ')!'
+ )
+ }
+ return proto[methodName].overloadTable[arguments.length].apply(
+ this,
+ arguments
+ )
+ }
+ proto[methodName].overloadTable = []
+ proto[methodName].overloadTable[prevFunc.argCount] = prevFunc
+ }
+ }
+ function exposePublicSymbol(name, value, numArguments) {
+ if (Module.hasOwnProperty(name)) {
+ if (
+ undefined === numArguments ||
+ (undefined !== Module[name].overloadTable &&
+ undefined !== Module[name].overloadTable[numArguments])
+ ) {
+ throwBindingError("Cannot register public name '" + name + "' twice")
+ }
+ ensureOverloadTable(Module, name, name)
+ if (Module.hasOwnProperty(numArguments)) {
+ throwBindingError(
+ 'Cannot register multiple overloads of a function with the same number of arguments (' +
+ numArguments +
+ ')!'
+ )
+ }
+ Module[name].overloadTable[numArguments] = value
+ } else {
+ Module[name] = value
+ if (undefined !== numArguments) {
+ Module[name].numArguments = numArguments
+ }
+ }
+ }
+ function heap32VectorToArray(count, firstElement) {
+ var array = []
+ for (var i = 0; i < count; i++) {
+ array.push(HEAP32[(firstElement >> 2) + i])
+ }
+ return array
+ }
+ function replacePublicSymbol(name, value, numArguments) {
+ if (!Module.hasOwnProperty(name)) {
+ throwInternalError('Replacing nonexistant public symbol')
+ }
+ if (
+ undefined !== Module[name].overloadTable &&
+ undefined !== numArguments
+ ) {
+ Module[name].overloadTable[numArguments] = value
+ } else {
+ Module[name] = value
+ Module[name].argCount = numArguments
+ }
+ }
+ function dynCallLegacy(sig, ptr, args) {
+ var f = Module['dynCall_' + sig]
+ return args && args.length
+ ? f.apply(null, [ptr].concat(args))
+ : f.call(null, ptr)
+ }
+ function dynCall(sig, ptr, args) {
+ if (sig.includes('j')) {
+ return dynCallLegacy(sig, ptr, args)
+ }
+ return wasmTable.get(ptr).apply(null, args)
+ }
+ function getDynCaller(sig, ptr) {
+ var argCache = []
+ return function () {
+ argCache.length = arguments.length
+ for (var i = 0; i < arguments.length; i++) {
+ argCache[i] = arguments[i]
+ }
+ return dynCall(sig, ptr, argCache)
+ }
+ }
+ function embind__requireFunction(signature, rawFunction) {
+ signature = readLatin1String(signature)
+ function makeDynCaller() {
+ if (signature.includes('j')) {
+ return getDynCaller(signature, rawFunction)
+ }
+ return wasmTable.get(rawFunction)
+ }
+ var fp = makeDynCaller()
+ if (typeof fp !== 'function') {
+ throwBindingError(
+ 'unknown function pointer with signature ' +
+ signature +
+ ': ' +
+ rawFunction
+ )
+ }
+ return fp
+ }
+ var UnboundTypeError = undefined
+ function getTypeName(type) {
+ var ptr = ___getTypeName(type)
+ var rv = readLatin1String(ptr)
+ _free(ptr)
+ return rv
+ }
+ function throwUnboundTypeError(message, types) {
+ var unboundTypes = []
+ var seen = {}
+ function visit(type) {
+ if (seen[type]) {
+ return
+ }
+ if (registeredTypes[type]) {
+ return
+ }
+ if (typeDependencies[type]) {
+ typeDependencies[type].forEach(visit)
+ return
+ }
+ unboundTypes.push(type)
+ seen[type] = true
+ }
+ types.forEach(visit)
+ throw new UnboundTypeError(
+ message + ': ' + unboundTypes.map(getTypeName).join([', '])
+ )
+ }
+ function __embind_register_function(
+ name,
+ argCount,
+ rawArgTypesAddr,
+ signature,
+ rawInvoker,
+ fn
+ ) {
+ var argTypes = heap32VectorToArray(argCount, rawArgTypesAddr)
+ name = readLatin1String(name)
+ rawInvoker = embind__requireFunction(signature, rawInvoker)
+ exposePublicSymbol(
+ name,
+ function () {
+ throwUnboundTypeError(
+ 'Cannot call ' + name + ' due to unbound types',
+ argTypes
+ )
+ },
+ argCount - 1
+ )
+ whenDependentTypesAreResolved([], argTypes, function (argTypes) {
+ var invokerArgsArray = [argTypes[0], null].concat(argTypes.slice(1))
+ replacePublicSymbol(
+ name,
+ craftInvokerFunction(name, invokerArgsArray, null, rawInvoker, fn),
+ argCount - 1
+ )
+ return []
+ })
+ }
+ function integerReadValueFromPointer(name, shift, signed) {
+ switch (shift) {
+ case 0:
+ return signed
+ ? function readS8FromPointer(pointer) {
+ return HEAP8[pointer]
+ }
+ : function readU8FromPointer(pointer) {
+ return HEAPU8[pointer]
+ }
+ case 1:
+ return signed
+ ? function readS16FromPointer(pointer) {
+ return HEAP16[pointer >> 1]
+ }
+ : function readU16FromPointer(pointer) {
+ return HEAPU16[pointer >> 1]
+ }
+ case 2:
+ return signed
+ ? function readS32FromPointer(pointer) {
+ return HEAP32[pointer >> 2]
+ }
+ : function readU32FromPointer(pointer) {
+ return HEAPU32[pointer >> 2]
+ }
+ default:
+ throw new TypeError('Unknown integer type: ' + name)
+ }
+ }
+ function __embind_register_integer(
+ primitiveType,
+ name,
+ size,
+ minRange,
+ maxRange
+ ) {
+ name = readLatin1String(name)
+ if (maxRange === -1) {
+ maxRange = 4294967295
+ }
+ var shift = getShiftFromSize(size)
+ var fromWireType = function (value) {
+ return value
+ }
+ if (minRange === 0) {
+ var bitshift = 32 - 8 * size
+ fromWireType = function (value) {
+ return (value << bitshift) >>> bitshift
+ }
+ }
+ var isUnsignedType = name.includes('unsigned')
+ registerType(primitiveType, {
+ name: name,
+ fromWireType: fromWireType,
+ toWireType: function (destructors, value) {
+ if (typeof value !== 'number' && typeof value !== 'boolean') {
+ throw new TypeError(
+ 'Cannot convert "' + _embind_repr(value) + '" to ' + this.name
+ )
+ }
+ if (value < minRange || value > maxRange) {
+ throw new TypeError(
+ 'Passing a number "' +
+ _embind_repr(value) +
+ '" from JS side to C/C++ side to an argument of type "' +
+ name +
+ '", which is outside the valid range [' +
+ minRange +
+ ', ' +
+ maxRange +
+ ']!'
+ )
+ }
+ return isUnsignedType ? value >>> 0 : value | 0
+ },
+ argPackAdvance: 8,
+ readValueFromPointer: integerReadValueFromPointer(
+ name,
+ shift,
+ minRange !== 0
+ ),
+ destructorFunction: null,
+ })
+ }
+ function __embind_register_memory_view(rawType, dataTypeIndex, name) {
+ var typeMapping = [
+ Int8Array,
+ Uint8Array,
+ Int16Array,
+ Uint16Array,
+ Int32Array,
+ Uint32Array,
+ Float32Array,
+ Float64Array,
+ ]
+ var TA = typeMapping[dataTypeIndex]
+ function decodeMemoryView(handle) {
+ handle = handle >> 2
+ var heap = HEAPU32
+ var size = heap[handle]
+ var data = heap[handle + 1]
+ return new TA(buffer, data, size)
+ }
+ name = readLatin1String(name)
+ registerType(
+ rawType,
+ {
+ name: name,
+ fromWireType: decodeMemoryView,
+ argPackAdvance: 8,
+ readValueFromPointer: decodeMemoryView,
+ },
+ { ignoreDuplicateRegistrations: true }
+ )
+ }
+ function __embind_register_std_string(rawType, name) {
+ name = readLatin1String(name)
+ var stdStringIsUTF8 = name === 'std::string'
+ registerType(rawType, {
+ name: name,
+ fromWireType: function (value) {
+ var length = HEAPU32[value >> 2]
+ var str
+ if (stdStringIsUTF8) {
+ var decodeStartPtr = value + 4
+ for (var i = 0; i <= length; ++i) {
+ var currentBytePtr = value + 4 + i
+ if (i == length || HEAPU8[currentBytePtr] == 0) {
+ var maxRead = currentBytePtr - decodeStartPtr
+ var stringSegment = UTF8ToString(decodeStartPtr, maxRead)
+ if (str === undefined) {
+ str = stringSegment
+ } else {
+ str += String.fromCharCode(0)
+ str += stringSegment
+ }
+ decodeStartPtr = currentBytePtr + 1
+ }
+ }
+ } else {
+ var a = new Array(length)
+ for (var i = 0; i < length; ++i) {
+ a[i] = String.fromCharCode(HEAPU8[value + 4 + i])
+ }
+ str = a.join('')
+ }
+ _free(value)
+ return str
+ },
+ toWireType: function (destructors, value) {
+ if (value instanceof ArrayBuffer) {
+ value = new Uint8Array(value)
+ }
+ var getLength
+ var valueIsOfTypeString = typeof value === 'string'
+ if (
+ !(
+ valueIsOfTypeString ||
+ value instanceof Uint8Array ||
+ value instanceof Uint8ClampedArray ||
+ value instanceof Int8Array
+ )
+ ) {
+ throwBindingError('Cannot pass non-string to std::string')
+ }
+ if (stdStringIsUTF8 && valueIsOfTypeString) {
+ getLength = function () {
+ return lengthBytesUTF8(value)
+ }
+ } else {
+ getLength = function () {
+ return value.length
+ }
+ }
+ var length = getLength()
+ var ptr = _malloc(4 + length + 1)
+ HEAPU32[ptr >> 2] = length
+ if (stdStringIsUTF8 && valueIsOfTypeString) {
+ stringToUTF8(value, ptr + 4, length + 1)
+ } else {
+ if (valueIsOfTypeString) {
+ for (var i = 0; i < length; ++i) {
+ var charCode = value.charCodeAt(i)
+ if (charCode > 255) {
+ _free(ptr)
+ throwBindingError(
+ 'String has UTF-16 code units that do not fit in 8 bits'
+ )
+ }
+ HEAPU8[ptr + 4 + i] = charCode
+ }
+ } else {
+ for (var i = 0; i < length; ++i) {
+ HEAPU8[ptr + 4 + i] = value[i]
+ }
+ }
+ }
+ if (destructors !== null) {
+ destructors.push(_free, ptr)
+ }
+ return ptr
+ },
+ argPackAdvance: 8,
+ readValueFromPointer: simpleReadValueFromPointer,
+ destructorFunction: function (ptr) {
+ _free(ptr)
+ },
+ })
+ }
+ function __embind_register_std_wstring(rawType, charSize, name) {
+ name = readLatin1String(name)
+ var decodeString, encodeString, getHeap, lengthBytesUTF, shift
+ if (charSize === 2) {
+ decodeString = UTF16ToString
+ encodeString = stringToUTF16
+ lengthBytesUTF = lengthBytesUTF16
+ getHeap = function () {
+ return HEAPU16
+ }
+ shift = 1
+ } else if (charSize === 4) {
+ decodeString = UTF32ToString
+ encodeString = stringToUTF32
+ lengthBytesUTF = lengthBytesUTF32
+ getHeap = function () {
+ return HEAPU32
+ }
+ shift = 2
+ }
+ registerType(rawType, {
+ name: name,
+ fromWireType: function (value) {
+ var length = HEAPU32[value >> 2]
+ var HEAP = getHeap()
+ var str
+ var decodeStartPtr = value + 4
+ for (var i = 0; i <= length; ++i) {
+ var currentBytePtr = value + 4 + i * charSize
+ if (i == length || HEAP[currentBytePtr >> shift] == 0) {
+ var maxReadBytes = currentBytePtr - decodeStartPtr
+ var stringSegment = decodeString(decodeStartPtr, maxReadBytes)
+ if (str === undefined) {
+ str = stringSegment
+ } else {
+ str += String.fromCharCode(0)
+ str += stringSegment
+ }
+ decodeStartPtr = currentBytePtr + charSize
+ }
+ }
+ _free(value)
+ return str
+ },
+ toWireType: function (destructors, value) {
+ if (!(typeof value === 'string')) {
+ throwBindingError(
+ 'Cannot pass non-string to C++ string type ' + name
+ )
+ }
+ var length = lengthBytesUTF(value)
+ var ptr = _malloc(4 + length + charSize)
+ HEAPU32[ptr >> 2] = length >> shift
+ encodeString(value, ptr + 4, length + charSize)
+ if (destructors !== null) {
+ destructors.push(_free, ptr)
+ }
+ return ptr
+ },
+ argPackAdvance: 8,
+ readValueFromPointer: simpleReadValueFromPointer,
+ destructorFunction: function (ptr) {
+ _free(ptr)
+ },
+ })
+ }
+ function __embind_register_void(rawType, name) {
+ name = readLatin1String(name)
+ registerType(rawType, {
+ isVoid: true,
+ name: name,
+ argPackAdvance: 0,
+ fromWireType: function () {
+ return undefined
+ },
+ toWireType: function (destructors, o) {
+ return undefined
+ },
+ })
+ }
+ var emval_symbols = {}
+ function getStringOrSymbol(address) {
+ var symbol = emval_symbols[address]
+ if (symbol === undefined) {
+ return readLatin1String(address)
+ } else {
+ return symbol
+ }
+ }
+ function emval_get_global() {
+ if (typeof globalThis === 'object') {
+ return globalThis
+ }
+ return (function () {
+ return Function
+ })()('return this')()
+ }
+ function __emval_get_global(name) {
+ if (name === 0) {
+ return __emval_register(emval_get_global())
+ } else {
+ name = getStringOrSymbol(name)
+ return __emval_register(emval_get_global()[name])
+ }
+ }
+ function __emval_incref(handle) {
+ if (handle > 4) {
+ emval_handle_array[handle].refcount += 1
+ }
+ }
+ function requireRegisteredType(rawType, humanName) {
+ var impl = registeredTypes[rawType]
+ if (undefined === impl) {
+ throwBindingError(
+ humanName + ' has unknown type ' + getTypeName(rawType)
+ )
+ }
+ return impl
+ }
+ function craftEmvalAllocator(argCount) {
+ var argsList = ''
+ for (var i = 0; i < argCount; ++i) {
+ argsList += (i !== 0 ? ', ' : '') + 'arg' + i
+ }
+ var functionBody =
+ 'return function emval_allocator_' +
+ argCount +
+ '(constructor, argTypes, args) {\n'
+ for (var i = 0; i < argCount; ++i) {
+ functionBody +=
+ 'var argType' +
+ i +
+ " = requireRegisteredType(Module['HEAP32'][(argTypes >>> 2) + " +
+ i +
+ '], "parameter ' +
+ i +
+ '");\n' +
+ 'var arg' +
+ i +
+ ' = argType' +
+ i +
+ '.readValueFromPointer(args);\n' +
+ 'args += argType' +
+ i +
+ "['argPackAdvance'];\n"
+ }
+ functionBody +=
+ 'var obj = new constructor(' +
+ argsList +
+ ');\n' +
+ 'return __emval_register(obj);\n' +
+ '}\n'
+ return new Function(
+ 'requireRegisteredType',
+ 'Module',
+ '__emval_register',
+ functionBody
+ )(requireRegisteredType, Module, __emval_register)
+ }
+ var emval_newers = {}
+ function requireHandle(handle) {
+ if (!handle) {
+ throwBindingError('Cannot use deleted val. handle = ' + handle)
+ }
+ return emval_handle_array[handle].value
+ }
+ function __emval_new(handle, argCount, argTypes, args) {
+ handle = requireHandle(handle)
+ var newer = emval_newers[argCount]
+ if (!newer) {
+ newer = craftEmvalAllocator(argCount)
+ emval_newers[argCount] = newer
+ }
+ return newer(handle, argTypes, args)
+ }
+ function _abort() {
+ abort()
+ }
+ function _longjmp(env, value) {
+ _setThrew(env, value || 1)
+ throw 'longjmp'
+ }
+ function _emscripten_longjmp(a0, a1) {
+ return _longjmp(a0, a1)
+ }
+ function _emscripten_memcpy_big(dest, src, num) {
+ HEAPU8.copyWithin(dest, src, src + num)
+ }
+ function emscripten_realloc_buffer(size) {
+ try {
+ wasmMemory.grow((size - buffer.byteLength + 65535) >>> 16)
+ updateGlobalBufferAndViews(wasmMemory.buffer)
+ return 1
+ } catch (e) {}
+ }
+ function _emscripten_resize_heap(requestedSize) {
+ var oldSize = HEAPU8.length
+ requestedSize = requestedSize >>> 0
+ var maxHeapSize = 2147483648
+ if (requestedSize > maxHeapSize) {
+ return false
+ }
+ for (var cutDown = 1; cutDown <= 4; cutDown *= 2) {
+ var overGrownHeapSize = oldSize * (1 + 0.2 / cutDown)
+ overGrownHeapSize = Math.min(
+ overGrownHeapSize,
+ requestedSize + 100663296
+ )
+ var newSize = Math.min(
+ maxHeapSize,
+ alignUp(Math.max(requestedSize, overGrownHeapSize), 65536)
+ )
+ var replacement = emscripten_realloc_buffer(newSize)
+ if (replacement) {
+ return true
+ }
+ }
+ return false
+ }
+ var SYSCALLS = {
+ mappings: {},
+ buffers: [null, [], []],
+ printChar: function (stream, curr) {
+ var buffer = SYSCALLS.buffers[stream]
+ if (curr === 0 || curr === 10) {
+ ;(stream === 1 ? out : err)(UTF8ArrayToString(buffer, 0))
+ buffer.length = 0
+ } else {
+ buffer.push(curr)
+ }
+ },
+ varargs: undefined,
+ get: function () {
+ SYSCALLS.varargs += 4
+ var ret = HEAP32[(SYSCALLS.varargs - 4) >> 2]
+ return ret
+ },
+ getStr: function (ptr) {
+ var ret = UTF8ToString(ptr)
+ return ret
+ },
+ get64: function (low, high) {
+ return low
+ },
+ }
+ function _fd_close(fd) {
+ return 0
+ }
+ function _fd_seek(fd, offset_low, offset_high, whence, newOffset) {}
+ function _fd_write(fd, iov, iovcnt, pnum) {
+ var num = 0
+ for (var i = 0; i < iovcnt; i++) {
+ var ptr = HEAP32[(iov + i * 8) >> 2]
+ var len = HEAP32[(iov + (i * 8 + 4)) >> 2]
+ for (var j = 0; j < len; j++) {
+ SYSCALLS.printChar(fd, HEAPU8[ptr + j])
+ }
+ num += len
+ }
+ HEAP32[pnum >> 2] = num
+ return 0
+ }
+ function _getTempRet0() {
+ return getTempRet0()
+ }
+ function _setTempRet0(val) {
+ setTempRet0(val)
+ }
+ embind_init_charCodes()
+ BindingError = Module['BindingError'] = extendError(Error, 'BindingError')
+ InternalError = Module['InternalError'] = extendError(
+ Error,
+ 'InternalError'
+ )
+ init_emval()
+ UnboundTypeError = Module['UnboundTypeError'] = extendError(
+ Error,
+ 'UnboundTypeError'
+ )
+ var asmLibraryArg = {
+ j: ___cxa_thread_atexit,
+ v: __embind_register_bigint,
+ r: __embind_register_bool,
+ B: __embind_register_emval,
+ q: __embind_register_float,
+ t: __embind_register_function,
+ e: __embind_register_integer,
+ d: __embind_register_memory_view,
+ m: __embind_register_std_string,
+ l: __embind_register_std_wstring,
+ s: __embind_register_void,
+ h: __emval_decref,
+ i: __emval_get_global,
+ n: __emval_incref,
+ o: __emval_new,
+ a: _abort,
+ g: _emscripten_longjmp,
+ y: _emscripten_memcpy_big,
+ k: _emscripten_resize_heap,
+ A: _fd_close,
+ u: _fd_seek,
+ z: _fd_write,
+ b: _getTempRet0,
+ f: invoke_iii,
+ w: invoke_iiiii,
+ p: invoke_viiii,
+ x: invoke_viiiiiii,
+ c: _setTempRet0,
+ }
+ var asm = createWasm()
+ var ___wasm_call_ctors = (Module['___wasm_call_ctors'] = function () {
+ return (___wasm_call_ctors = Module['___wasm_call_ctors'] =
+ Module['asm']['D']).apply(null, arguments)
+ })
+ var _malloc = (Module['_malloc'] = function () {
+ return (_malloc = Module['_malloc'] = Module['asm']['E']).apply(
+ null,
+ arguments
+ )
+ })
+ var _free = (Module['_free'] = function () {
+ return (_free = Module['_free'] = Module['asm']['F']).apply(
+ null,
+ arguments
+ )
+ })
+ var ___getTypeName = (Module['___getTypeName'] = function () {
+ return (___getTypeName = Module['___getTypeName'] =
+ Module['asm']['G']).apply(null, arguments)
+ })
+ var ___embind_register_native_and_builtin_types = (Module[
+ '___embind_register_native_and_builtin_types'
+ ] = function () {
+ return (___embind_register_native_and_builtin_types = Module[
+ '___embind_register_native_and_builtin_types'
+ ] =
+ Module['asm']['H']).apply(null, arguments)
+ })
+ var stackSave = (Module['stackSave'] = function () {
+ return (stackSave = Module['stackSave'] = Module['asm']['I']).apply(
+ null,
+ arguments
+ )
+ })
+ var stackRestore = (Module['stackRestore'] = function () {
+ return (stackRestore = Module['stackRestore'] = Module['asm']['J']).apply(
+ null,
+ arguments
+ )
+ })
+ var _setThrew = (Module['_setThrew'] = function () {
+ return (_setThrew = Module['_setThrew'] = Module['asm']['K']).apply(
+ null,
+ arguments
+ )
+ })
+ var dynCall_iiijii = (Module['dynCall_iiijii'] = function () {
+ return (dynCall_iiijii = Module['dynCall_iiijii'] =
+ Module['asm']['M']).apply(null, arguments)
+ })
+ var dynCall_jiji = (Module['dynCall_jiji'] = function () {
+ return (dynCall_jiji = Module['dynCall_jiji'] = Module['asm']['N']).apply(
+ null,
+ arguments
+ )
+ })
+ function invoke_viiiiiii(index, a1, a2, a3, a4, a5, a6, a7) {
+ var sp = stackSave()
+ try {
+ wasmTable.get(index)(a1, a2, a3, a4, a5, a6, a7)
+ } catch (e) {
+ stackRestore(sp)
+ if (e !== e + 0 && e !== 'longjmp') throw e
+ _setThrew(1, 0)
+ }
+ }
+ function invoke_viiii(index, a1, a2, a3, a4) {
+ var sp = stackSave()
+ try {
+ wasmTable.get(index)(a1, a2, a3, a4)
+ } catch (e) {
+ stackRestore(sp)
+ if (e !== e + 0 && e !== 'longjmp') throw e
+ _setThrew(1, 0)
+ }
+ }
+ function invoke_iii(index, a1, a2) {
+ var sp = stackSave()
+ try {
+ return wasmTable.get(index)(a1, a2)
+ } catch (e) {
+ stackRestore(sp)
+ if (e !== e + 0 && e !== 'longjmp') throw e
+ _setThrew(1, 0)
+ }
+ }
+ function invoke_iiiii(index, a1, a2, a3, a4) {
+ var sp = stackSave()
+ try {
+ return wasmTable.get(index)(a1, a2, a3, a4)
+ } catch (e) {
+ stackRestore(sp)
+ if (e !== e + 0 && e !== 'longjmp') throw e
+ _setThrew(1, 0)
+ }
+ }
+ var calledRun
+ dependenciesFulfilled = function runCaller() {
+ if (!calledRun) run()
+ if (!calledRun) dependenciesFulfilled = runCaller
+ }
+ function run(args) {
+ args = args || arguments_
+ if (runDependencies > 0) {
+ return
+ }
+ preRun()
+ if (runDependencies > 0) {
+ return
+ }
+ function doRun() {
+ if (calledRun) return
+ calledRun = true
+ Module['calledRun'] = true
+ if (ABORT) return
+ initRuntime()
+ readyPromiseResolve(Module)
+ if (Module['onRuntimeInitialized']) Module['onRuntimeInitialized']()
+ postRun()
+ }
+ if (Module['setStatus']) {
+ Module['setStatus']('Running...')
+ setTimeout(function () {
+ setTimeout(function () {
+ Module['setStatus']('')
+ }, 1)
+ doRun()
+ }, 1)
+ } else {
+ doRun()
+ }
+ }
+ Module['run'] = run
+ if (Module['preInit']) {
+ if (typeof Module['preInit'] == 'function')
+ Module['preInit'] = [Module['preInit']]
+ while (Module['preInit'].length > 0) {
+ Module['preInit'].pop()()
+ }
+ }
+ run()
+
+ return Module.ready
+ }
+})()
+export default Module
diff --git a/packages/integrations/image/src/vendor/squoosh/avif/avif_node_dec.wasm b/packages/integrations/image/src/vendor/squoosh/avif/avif_node_dec.wasm
new file mode 100644
index 000000000..1cd4e1b03
Binary files /dev/null and b/packages/integrations/image/src/vendor/squoosh/avif/avif_node_dec.wasm differ
diff --git a/packages/integrations/image/src/vendor/squoosh/avif/avif_node_enc.ts b/packages/integrations/image/src/vendor/squoosh/avif/avif_node_enc.ts
new file mode 100644
index 000000000..d785563d3
--- /dev/null
+++ b/packages/integrations/image/src/vendor/squoosh/avif/avif_node_enc.ts
@@ -0,0 +1,2066 @@
+/* eslint-disable */
+// @ts-nocheck
+import { createRequire } from 'module';
+const require = createRequire(import.meta.url);
+import { dirname } from '../emscripten-utils.js';
+
+var Module = (function () {
+ return function (Module) {
+ Module = Module || {}
+
+ var Module = typeof Module !== 'undefined' ? Module : {}
+ var readyPromiseResolve, readyPromiseReject
+ Module['ready'] = new Promise(function (resolve, reject) {
+ readyPromiseResolve = resolve
+ readyPromiseReject = reject
+ })
+ var moduleOverrides = {}
+ var key
+ for (key in Module) {
+ if (Module.hasOwnProperty(key)) {
+ moduleOverrides[key] = Module[key]
+ }
+ }
+ var arguments_ = []
+ var thisProgram = './this.program'
+ var quit_ = function (status, toThrow) {
+ throw toThrow
+ }
+ var ENVIRONMENT_IS_WEB = false
+ var ENVIRONMENT_IS_WORKER = false
+ var ENVIRONMENT_IS_NODE = true
+ var scriptDirectory = ''
+ function locateFile(path) {
+ if (Module['locateFile']) {
+ return Module['locateFile'](path, scriptDirectory)
+ }
+ return scriptDirectory + path
+ }
+ var read_, readBinary
+ var nodeFS
+ var nodePath
+ if (ENVIRONMENT_IS_NODE) {
+ if (ENVIRONMENT_IS_WORKER) {
+ scriptDirectory = require('path').dirname(scriptDirectory) + '/'
+ } else {
+ scriptDirectory = dirname(import.meta.url) + '/'
+ }
+ read_ = function shell_read(filename, binary) {
+ if (!nodeFS) nodeFS = require('fs')
+ if (!nodePath) nodePath = require('path')
+ filename = nodePath['normalize'](filename)
+ return nodeFS['readFileSync'](filename, binary ? null : 'utf8')
+ }
+ readBinary = function readBinary(filename) {
+ var ret = read_(filename, true)
+ if (!ret.buffer) {
+ ret = new Uint8Array(ret)
+ }
+ assert(ret.buffer)
+ return ret
+ }
+ if (process['argv'].length > 1) {
+ thisProgram = process['argv'][1].replace(/\\/g, '/')
+ }
+ arguments_ = process['argv'].slice(2)
+ quit_ = function (status) {
+ process['exit'](status)
+ }
+ Module['inspect'] = function () {
+ return '[Emscripten Module object]'
+ }
+ } else {
+ }
+ var out = Module['print'] || console.log.bind(console)
+ var err = Module['printErr'] || console.warn.bind(console)
+ for (key in moduleOverrides) {
+ if (moduleOverrides.hasOwnProperty(key)) {
+ Module[key] = moduleOverrides[key]
+ }
+ }
+ moduleOverrides = null
+ if (Module['arguments']) arguments_ = Module['arguments']
+ if (Module['thisProgram']) thisProgram = Module['thisProgram']
+ if (Module['quit']) quit_ = Module['quit']
+ var tempRet0 = 0
+ var setTempRet0 = function (value) {
+ tempRet0 = value
+ }
+ var getTempRet0 = function () {
+ return tempRet0
+ }
+ var wasmBinary
+ if (Module['wasmBinary']) wasmBinary = Module['wasmBinary']
+ var noExitRuntime = Module['noExitRuntime'] || true
+ if (typeof WebAssembly !== 'object') {
+ abort('no native wasm support detected')
+ }
+ var wasmMemory
+ var ABORT = false
+ var EXITSTATUS
+ function assert(condition, text) {
+ if (!condition) {
+ abort('Assertion failed: ' + text)
+ }
+ }
+ var UTF8Decoder = new TextDecoder('utf8')
+ function UTF8ArrayToString(heap, idx, maxBytesToRead) {
+ var endIdx = idx + maxBytesToRead
+ var endPtr = idx
+ while (heap[endPtr] && !(endPtr >= endIdx)) ++endPtr
+ return UTF8Decoder.decode(
+ heap.subarray
+ ? heap.subarray(idx, endPtr)
+ : new Uint8Array(heap.slice(idx, endPtr))
+ )
+ }
+ function UTF8ToString(ptr, maxBytesToRead) {
+ if (!ptr) return ''
+ var maxPtr = ptr + maxBytesToRead
+ for (var end = ptr; !(end >= maxPtr) && HEAPU8[end]; ) ++end
+ return UTF8Decoder.decode(HEAPU8.subarray(ptr, end))
+ }
+ function stringToUTF8Array(str, heap, outIdx, maxBytesToWrite) {
+ if (!(maxBytesToWrite > 0)) return 0
+ var startIdx = outIdx
+ var endIdx = outIdx + maxBytesToWrite - 1
+ for (var i = 0; i < str.length; ++i) {
+ var u = str.charCodeAt(i)
+ if (u >= 55296 && u <= 57343) {
+ var u1 = str.charCodeAt(++i)
+ u = (65536 + ((u & 1023) << 10)) | (u1 & 1023)
+ }
+ if (u <= 127) {
+ if (outIdx >= endIdx) break
+ heap[outIdx++] = u
+ } else if (u <= 2047) {
+ if (outIdx + 1 >= endIdx) break
+ heap[outIdx++] = 192 | (u >> 6)
+ heap[outIdx++] = 128 | (u & 63)
+ } else if (u <= 65535) {
+ if (outIdx + 2 >= endIdx) break
+ heap[outIdx++] = 224 | (u >> 12)
+ heap[outIdx++] = 128 | ((u >> 6) & 63)
+ heap[outIdx++] = 128 | (u & 63)
+ } else {
+ if (outIdx + 3 >= endIdx) break
+ heap[outIdx++] = 240 | (u >> 18)
+ heap[outIdx++] = 128 | ((u >> 12) & 63)
+ heap[outIdx++] = 128 | ((u >> 6) & 63)
+ heap[outIdx++] = 128 | (u & 63)
+ }
+ }
+ heap[outIdx] = 0
+ return outIdx - startIdx
+ }
+ function stringToUTF8(str, outPtr, maxBytesToWrite) {
+ return stringToUTF8Array(str, HEAPU8, outPtr, maxBytesToWrite)
+ }
+ function lengthBytesUTF8(str) {
+ var len = 0
+ for (var i = 0; i < str.length; ++i) {
+ var u = str.charCodeAt(i)
+ if (u >= 55296 && u <= 57343)
+ u = (65536 + ((u & 1023) << 10)) | (str.charCodeAt(++i) & 1023)
+ if (u <= 127) ++len
+ else if (u <= 2047) len += 2
+ else if (u <= 65535) len += 3
+ else len += 4
+ }
+ return len
+ }
+ var UTF16Decoder = new TextDecoder('utf-16le')
+ function UTF16ToString(ptr, maxBytesToRead) {
+ var endPtr = ptr
+ var idx = endPtr >> 1
+ var maxIdx = idx + maxBytesToRead / 2
+ while (!(idx >= maxIdx) && HEAPU16[idx]) ++idx
+ endPtr = idx << 1
+ return UTF16Decoder.decode(HEAPU8.subarray(ptr, endPtr))
+ var str = ''
+ for (var i = 0; !(i >= maxBytesToRead / 2); ++i) {
+ var codeUnit = HEAP16[(ptr + i * 2) >> 1]
+ if (codeUnit == 0) break
+ str += String.fromCharCode(codeUnit)
+ }
+ return str
+ }
+ function stringToUTF16(str, outPtr, maxBytesToWrite) {
+ if (maxBytesToWrite === undefined) {
+ maxBytesToWrite = 2147483647
+ }
+ if (maxBytesToWrite < 2) return 0
+ maxBytesToWrite -= 2
+ var startPtr = outPtr
+ var numCharsToWrite =
+ maxBytesToWrite < str.length * 2 ? maxBytesToWrite / 2 : str.length
+ for (var i = 0; i < numCharsToWrite; ++i) {
+ var codeUnit = str.charCodeAt(i)
+ HEAP16[outPtr >> 1] = codeUnit
+ outPtr += 2
+ }
+ HEAP16[outPtr >> 1] = 0
+ return outPtr - startPtr
+ }
+ function lengthBytesUTF16(str) {
+ return str.length * 2
+ }
+ function UTF32ToString(ptr, maxBytesToRead) {
+ var i = 0
+ var str = ''
+ while (!(i >= maxBytesToRead / 4)) {
+ var utf32 = HEAP32[(ptr + i * 4) >> 2]
+ if (utf32 == 0) break
+ ++i
+ if (utf32 >= 65536) {
+ var ch = utf32 - 65536
+ str += String.fromCharCode(55296 | (ch >> 10), 56320 | (ch & 1023))
+ } else {
+ str += String.fromCharCode(utf32)
+ }
+ }
+ return str
+ }
+ function stringToUTF32(str, outPtr, maxBytesToWrite) {
+ if (maxBytesToWrite === undefined) {
+ maxBytesToWrite = 2147483647
+ }
+ if (maxBytesToWrite < 4) return 0
+ var startPtr = outPtr
+ var endPtr = startPtr + maxBytesToWrite - 4
+ for (var i = 0; i < str.length; ++i) {
+ var codeUnit = str.charCodeAt(i)
+ if (codeUnit >= 55296 && codeUnit <= 57343) {
+ var trailSurrogate = str.charCodeAt(++i)
+ codeUnit =
+ (65536 + ((codeUnit & 1023) << 10)) | (trailSurrogate & 1023)
+ }
+ HEAP32[outPtr >> 2] = codeUnit
+ outPtr += 4
+ if (outPtr + 4 > endPtr) break
+ }
+ HEAP32[outPtr >> 2] = 0
+ return outPtr - startPtr
+ }
+ function lengthBytesUTF32(str) {
+ var len = 0
+ for (var i = 0; i < str.length; ++i) {
+ var codeUnit = str.charCodeAt(i)
+ if (codeUnit >= 55296 && codeUnit <= 57343) ++i
+ len += 4
+ }
+ return len
+ }
+ function alignUp(x, multiple) {
+ if (x % multiple > 0) {
+ x += multiple - (x % multiple)
+ }
+ return x
+ }
+ var buffer,
+ HEAP8,
+ HEAPU8,
+ HEAP16,
+ HEAPU16,
+ HEAP32,
+ HEAPU32,
+ HEAPF32,
+ HEAPF64
+ function updateGlobalBufferAndViews(buf) {
+ buffer = buf
+ Module['HEAP8'] = HEAP8 = new Int8Array(buf)
+ Module['HEAP16'] = HEAP16 = new Int16Array(buf)
+ Module['HEAP32'] = HEAP32 = new Int32Array(buf)
+ Module['HEAPU8'] = HEAPU8 = new Uint8Array(buf)
+ Module['HEAPU16'] = HEAPU16 = new Uint16Array(buf)
+ Module['HEAPU32'] = HEAPU32 = new Uint32Array(buf)
+ Module['HEAPF32'] = HEAPF32 = new Float32Array(buf)
+ Module['HEAPF64'] = HEAPF64 = new Float64Array(buf)
+ }
+ var INITIAL_MEMORY = Module['INITIAL_MEMORY'] || 16777216
+ var wasmTable
+ var __ATPRERUN__ = []
+ var __ATINIT__ = []
+ var __ATPOSTRUN__ = []
+ var runtimeInitialized = false
+ function preRun() {
+ if (Module['preRun']) {
+ if (typeof Module['preRun'] == 'function')
+ Module['preRun'] = [Module['preRun']]
+ while (Module['preRun'].length) {
+ addOnPreRun(Module['preRun'].shift())
+ }
+ }
+ callRuntimeCallbacks(__ATPRERUN__)
+ }
+ function initRuntime() {
+ runtimeInitialized = true
+ callRuntimeCallbacks(__ATINIT__)
+ }
+ function postRun() {
+ if (Module['postRun']) {
+ if (typeof Module['postRun'] == 'function')
+ Module['postRun'] = [Module['postRun']]
+ while (Module['postRun'].length) {
+ addOnPostRun(Module['postRun'].shift())
+ }
+ }
+ callRuntimeCallbacks(__ATPOSTRUN__)
+ }
+ function addOnPreRun(cb) {
+ __ATPRERUN__.unshift(cb)
+ }
+ function addOnInit(cb) {
+ __ATINIT__.unshift(cb)
+ }
+ function addOnPostRun(cb) {
+ __ATPOSTRUN__.unshift(cb)
+ }
+ var runDependencies = 0
+ var runDependencyWatcher = null
+ var dependenciesFulfilled = null
+ function addRunDependency(id) {
+ runDependencies++
+ if (Module['monitorRunDependencies']) {
+ Module['monitorRunDependencies'](runDependencies)
+ }
+ }
+ function removeRunDependency(id) {
+ runDependencies--
+ if (Module['monitorRunDependencies']) {
+ Module['monitorRunDependencies'](runDependencies)
+ }
+ if (runDependencies == 0) {
+ if (runDependencyWatcher !== null) {
+ clearInterval(runDependencyWatcher)
+ runDependencyWatcher = null
+ }
+ if (dependenciesFulfilled) {
+ var callback = dependenciesFulfilled
+ dependenciesFulfilled = null
+ callback()
+ }
+ }
+ }
+ Module['preloadedImages'] = {}
+ Module['preloadedAudios'] = {}
+ function abort(what) {
+ if (Module['onAbort']) {
+ Module['onAbort'](what)
+ }
+ what += ''
+ err(what)
+ ABORT = true
+ EXITSTATUS = 1
+ what = 'abort(' + what + '). Build with -s ASSERTIONS=1 for more info.'
+ var e = new WebAssembly.RuntimeError(what)
+ readyPromiseReject(e)
+ throw e
+ }
+ var dataURIPrefix = 'data:application/octet-stream;base64,'
+ function isDataURI(filename) {
+ return filename.startsWith(dataURIPrefix)
+ }
+ if (Module['locateFile']) {
+ var wasmBinaryFile = 'avif_node_enc.wasm'
+ if (!isDataURI(wasmBinaryFile)) {
+ wasmBinaryFile = locateFile(wasmBinaryFile)
+ }
+ } else {
+ throw new Error('invariant')
+ }
+ function getBinary(file) {
+ try {
+ if (file == wasmBinaryFile && wasmBinary) {
+ return new Uint8Array(wasmBinary)
+ }
+ if (readBinary) {
+ return readBinary(file)
+ } else {
+ throw 'both async and sync fetching of the wasm failed'
+ }
+ } catch (err) {
+ abort(err)
+ }
+ }
+ function getBinaryPromise() {
+ if (!wasmBinary && (ENVIRONMENT_IS_WEB || ENVIRONMENT_IS_WORKER)) {
+ if (typeof fetch === 'function') {
+ return fetch(wasmBinaryFile, { credentials: 'same-origin' })
+ .then(function (response) {
+ if (!response['ok']) {
+ throw (
+ "failed to load wasm binary file at '" + wasmBinaryFile + "'"
+ )
+ }
+ return response['arrayBuffer']()
+ })
+ .catch(function () {
+ return getBinary(wasmBinaryFile)
+ })
+ }
+ }
+ return Promise.resolve().then(function () {
+ return getBinary(wasmBinaryFile)
+ })
+ }
+ function createWasm() {
+ var info = { a: asmLibraryArg }
+ function receiveInstance(instance, module) {
+ var exports = instance.exports
+ Module['asm'] = exports
+ wasmMemory = Module['asm']['P']
+ updateGlobalBufferAndViews(wasmMemory.buffer)
+ wasmTable = Module['asm']['Y']
+ addOnInit(Module['asm']['Q'])
+ removeRunDependency('wasm-instantiate')
+ }
+ addRunDependency('wasm-instantiate')
+ function receiveInstantiationResult(result) {
+ receiveInstance(result['instance'])
+ }
+ function instantiateArrayBuffer(receiver) {
+ return getBinaryPromise()
+ .then(function (binary) {
+ var result = WebAssembly.instantiate(binary, info)
+ return result
+ })
+ .then(receiver, function (reason) {
+ err('failed to asynchronously prepare wasm: ' + reason)
+ abort(reason)
+ })
+ }
+ function instantiateAsync() {
+ if (
+ !wasmBinary &&
+ typeof WebAssembly.instantiateStreaming === 'function' &&
+ !isDataURI(wasmBinaryFile) &&
+ typeof fetch === 'function'
+ ) {
+ return fetch(wasmBinaryFile, { credentials: 'same-origin' }).then(
+ function (response) {
+ var result = WebAssembly.instantiateStreaming(response, info)
+ return result.then(receiveInstantiationResult, function (reason) {
+ err('wasm streaming compile failed: ' + reason)
+ err('falling back to ArrayBuffer instantiation')
+ return instantiateArrayBuffer(receiveInstantiationResult)
+ })
+ }
+ )
+ } else {
+ return instantiateArrayBuffer(receiveInstantiationResult)
+ }
+ }
+ if (Module['instantiateWasm']) {
+ try {
+ var exports = Module['instantiateWasm'](info, receiveInstance)
+ return exports
+ } catch (e) {
+ err('Module.instantiateWasm callback failed with error: ' + e)
+ return false
+ }
+ }
+ instantiateAsync().catch(readyPromiseReject)
+ return {}
+ }
+ function callRuntimeCallbacks(callbacks) {
+ while (callbacks.length > 0) {
+ var callback = callbacks.shift()
+ if (typeof callback == 'function') {
+ callback(Module)
+ continue
+ }
+ var func = callback.func
+ if (typeof func === 'number') {
+ if (callback.arg === undefined) {
+ wasmTable.get(func)()
+ } else {
+ wasmTable.get(func)(callback.arg)
+ }
+ } else {
+ func(callback.arg === undefined ? null : callback.arg)
+ }
+ }
+ }
+ function _atexit(func, arg) {}
+ function ___cxa_thread_atexit(a0, a1) {
+ return _atexit(a0, a1)
+ }
+ var SYSCALLS = {
+ mappings: {},
+ buffers: [null, [], []],
+ printChar: function (stream, curr) {
+ var buffer = SYSCALLS.buffers[stream]
+ if (curr === 0 || curr === 10) {
+ ;(stream === 1 ? out : err)(UTF8ArrayToString(buffer, 0))
+ buffer.length = 0
+ } else {
+ buffer.push(curr)
+ }
+ },
+ varargs: undefined,
+ get: function () {
+ SYSCALLS.varargs += 4
+ var ret = HEAP32[(SYSCALLS.varargs - 4) >> 2]
+ return ret
+ },
+ getStr: function (ptr) {
+ var ret = UTF8ToString(ptr)
+ return ret
+ },
+ get64: function (low, high) {
+ return low
+ },
+ }
+ function ___sys_fcntl64(fd, cmd, varargs) {
+ SYSCALLS.varargs = varargs
+ return 0
+ }
+ function ___sys_ioctl(fd, op, varargs) {
+ SYSCALLS.varargs = varargs
+ return 0
+ }
+ function ___sys_open(path, flags, varargs) {
+ SYSCALLS.varargs = varargs
+ }
+ var structRegistrations = {}
+ function runDestructors(destructors) {
+ while (destructors.length) {
+ var ptr = destructors.pop()
+ var del = destructors.pop()
+ del(ptr)
+ }
+ }
+ function simpleReadValueFromPointer(pointer) {
+ return this['fromWireType'](HEAPU32[pointer >> 2])
+ }
+ var awaitingDependencies = {}
+ var registeredTypes = {}
+ var typeDependencies = {}
+ var char_0 = 48
+ var char_9 = 57
+ function makeLegalFunctionName(name) {
+ if (undefined === name) {
+ return '_unknown'
+ }
+ name = name.replace(/[^a-zA-Z0-9_]/g, '$')
+ var f = name.charCodeAt(0)
+ if (f >= char_0 && f <= char_9) {
+ return '_' + name
+ } else {
+ return name
+ }
+ }
+ function createNamedFunction(name, body) {
+ name = makeLegalFunctionName(name)
+ return new Function(
+ 'body',
+ 'return function ' +
+ name +
+ '() {\n' +
+ ' "use strict";' +
+ ' return body.apply(this, arguments);\n' +
+ '};\n'
+ )(body)
+ }
+ function extendError(baseErrorType, errorName) {
+ var errorClass = createNamedFunction(errorName, function (message) {
+ this.name = errorName
+ this.message = message
+ var stack = new Error(message).stack
+ if (stack !== undefined) {
+ this.stack =
+ this.toString() + '\n' + stack.replace(/^Error(:[^\n]*)?\n/, '')
+ }
+ })
+ errorClass.prototype = Object.create(baseErrorType.prototype)
+ errorClass.prototype.constructor = errorClass
+ errorClass.prototype.toString = function () {
+ if (this.message === undefined) {
+ return this.name
+ } else {
+ return this.name + ': ' + this.message
+ }
+ }
+ return errorClass
+ }
+ var InternalError = undefined
+ function throwInternalError(message) {
+ throw new InternalError(message)
+ }
+ function whenDependentTypesAreResolved(
+ myTypes,
+ dependentTypes,
+ getTypeConverters
+ ) {
+ myTypes.forEach(function (type) {
+ typeDependencies[type] = dependentTypes
+ })
+ function onComplete(typeConverters) {
+ var myTypeConverters = getTypeConverters(typeConverters)
+ if (myTypeConverters.length !== myTypes.length) {
+ throwInternalError('Mismatched type converter count')
+ }
+ for (var i = 0; i < myTypes.length; ++i) {
+ registerType(myTypes[i], myTypeConverters[i])
+ }
+ }
+ var typeConverters = new Array(dependentTypes.length)
+ var unregisteredTypes = []
+ var registered = 0
+ dependentTypes.forEach(function (dt, i) {
+ if (registeredTypes.hasOwnProperty(dt)) {
+ typeConverters[i] = registeredTypes[dt]
+ } else {
+ unregisteredTypes.push(dt)
+ if (!awaitingDependencies.hasOwnProperty(dt)) {
+ awaitingDependencies[dt] = []
+ }
+ awaitingDependencies[dt].push(function () {
+ typeConverters[i] = registeredTypes[dt]
+ ++registered
+ if (registered === unregisteredTypes.length) {
+ onComplete(typeConverters)
+ }
+ })
+ }
+ })
+ if (0 === unregisteredTypes.length) {
+ onComplete(typeConverters)
+ }
+ }
+ function __embind_finalize_value_object(structType) {
+ var reg = structRegistrations[structType]
+ delete structRegistrations[structType]
+ var rawConstructor = reg.rawConstructor
+ var rawDestructor = reg.rawDestructor
+ var fieldRecords = reg.fields
+ var fieldTypes = fieldRecords
+ .map(function (field) {
+ return field.getterReturnType
+ })
+ .concat(
+ fieldRecords.map(function (field) {
+ return field.setterArgumentType
+ })
+ )
+ whenDependentTypesAreResolved(
+ [structType],
+ fieldTypes,
+ function (fieldTypes) {
+ var fields = {}
+ fieldRecords.forEach(function (field, i) {
+ var fieldName = field.fieldName
+ var getterReturnType = fieldTypes[i]
+ var getter = field.getter
+ var getterContext = field.getterContext
+ var setterArgumentType = fieldTypes[i + fieldRecords.length]
+ var setter = field.setter
+ var setterContext = field.setterContext
+ fields[fieldName] = {
+ read: function (ptr) {
+ return getterReturnType['fromWireType'](
+ getter(getterContext, ptr)
+ )
+ },
+ write: function (ptr, o) {
+ var destructors = []
+ setter(
+ setterContext,
+ ptr,
+ setterArgumentType['toWireType'](destructors, o)
+ )
+ runDestructors(destructors)
+ },
+ }
+ })
+ return [
+ {
+ name: reg.name,
+ fromWireType: function (ptr) {
+ var rv = {}
+ for (var i in fields) {
+ rv[i] = fields[i].read(ptr)
+ }
+ rawDestructor(ptr)
+ return rv
+ },
+ toWireType: function (destructors, o) {
+ for (var fieldName in fields) {
+ if (!(fieldName in o)) {
+ throw new TypeError('Missing field: "' + fieldName + '"')
+ }
+ }
+ var ptr = rawConstructor()
+ for (fieldName in fields) {
+ fields[fieldName].write(ptr, o[fieldName])
+ }
+ if (destructors !== null) {
+ destructors.push(rawDestructor, ptr)
+ }
+ return ptr
+ },
+ argPackAdvance: 8,
+ readValueFromPointer: simpleReadValueFromPointer,
+ destructorFunction: rawDestructor,
+ },
+ ]
+ }
+ )
+ }
+ function __embind_register_bigint(
+ primitiveType,
+ name,
+ size,
+ minRange,
+ maxRange
+ ) {}
+ function getShiftFromSize(size) {
+ switch (size) {
+ case 1:
+ return 0
+ case 2:
+ return 1
+ case 4:
+ return 2
+ case 8:
+ return 3
+ default:
+ throw new TypeError('Unknown type size: ' + size)
+ }
+ }
+ function embind_init_charCodes() {
+ var codes = new Array(256)
+ for (var i = 0; i < 256; ++i) {
+ codes[i] = String.fromCharCode(i)
+ }
+ embind_charCodes = codes
+ }
+ var embind_charCodes = undefined
+ function readLatin1String(ptr) {
+ var ret = ''
+ var c = ptr
+ while (HEAPU8[c]) {
+ ret += embind_charCodes[HEAPU8[c++]]
+ }
+ return ret
+ }
+ var BindingError = undefined
+ function throwBindingError(message) {
+ throw new BindingError(message)
+ }
+ function registerType(rawType, registeredInstance, options) {
+ options = options || {}
+ if (!('argPackAdvance' in registeredInstance)) {
+ throw new TypeError(
+ 'registerType registeredInstance requires argPackAdvance'
+ )
+ }
+ var name = registeredInstance.name
+ if (!rawType) {
+ throwBindingError(
+ 'type "' + name + '" must have a positive integer typeid pointer'
+ )
+ }
+ if (registeredTypes.hasOwnProperty(rawType)) {
+ if (options.ignoreDuplicateRegistrations) {
+ return
+ } else {
+ throwBindingError("Cannot register type '" + name + "' twice")
+ }
+ }
+ registeredTypes[rawType] = registeredInstance
+ delete typeDependencies[rawType]
+ if (awaitingDependencies.hasOwnProperty(rawType)) {
+ var callbacks = awaitingDependencies[rawType]
+ delete awaitingDependencies[rawType]
+ callbacks.forEach(function (cb) {
+ cb()
+ })
+ }
+ }
+ function __embind_register_bool(
+ rawType,
+ name,
+ size,
+ trueValue,
+ falseValue
+ ) {
+ var shift = getShiftFromSize(size)
+ name = readLatin1String(name)
+ registerType(rawType, {
+ name: name,
+ fromWireType: function (wt) {
+ return !!wt
+ },
+ toWireType: function (destructors, o) {
+ return o ? trueValue : falseValue
+ },
+ argPackAdvance: 8,
+ readValueFromPointer: function (pointer) {
+ var heap
+ if (size === 1) {
+ heap = HEAP8
+ } else if (size === 2) {
+ heap = HEAP16
+ } else if (size === 4) {
+ heap = HEAP32
+ } else {
+ throw new TypeError('Unknown boolean type size: ' + name)
+ }
+ return this['fromWireType'](heap[pointer >> shift])
+ },
+ destructorFunction: null,
+ })
+ }
+ var emval_free_list = []
+ var emval_handle_array = [
+ {},
+ { value: undefined },
+ { value: null },
+ { value: true },
+ { value: false },
+ ]
+ function __emval_decref(handle) {
+ if (handle > 4 && 0 === --emval_handle_array[handle].refcount) {
+ emval_handle_array[handle] = undefined
+ emval_free_list.push(handle)
+ }
+ }
+ function count_emval_handles() {
+ var count = 0
+ for (var i = 5; i < emval_handle_array.length; ++i) {
+ if (emval_handle_array[i] !== undefined) {
+ ++count
+ }
+ }
+ return count
+ }
+ function get_first_emval() {
+ for (var i = 5; i < emval_handle_array.length; ++i) {
+ if (emval_handle_array[i] !== undefined) {
+ return emval_handle_array[i]
+ }
+ }
+ return null
+ }
+ function init_emval() {
+ Module['count_emval_handles'] = count_emval_handles
+ Module['get_first_emval'] = get_first_emval
+ }
+ function __emval_register(value) {
+ switch (value) {
+ case undefined: {
+ return 1
+ }
+ case null: {
+ return 2
+ }
+ case true: {
+ return 3
+ }
+ case false: {
+ return 4
+ }
+ default: {
+ var handle = emval_free_list.length
+ ? emval_free_list.pop()
+ : emval_handle_array.length
+ emval_handle_array[handle] = { refcount: 1, value: value }
+ return handle
+ }
+ }
+ }
+ function __embind_register_emval(rawType, name) {
+ name = readLatin1String(name)
+ registerType(rawType, {
+ name: name,
+ fromWireType: function (handle) {
+ var rv = emval_handle_array[handle].value
+ __emval_decref(handle)
+ return rv
+ },
+ toWireType: function (destructors, value) {
+ return __emval_register(value)
+ },
+ argPackAdvance: 8,
+ readValueFromPointer: simpleReadValueFromPointer,
+ destructorFunction: null,
+ })
+ }
+ function _embind_repr(v) {
+ if (v === null) {
+ return 'null'
+ }
+ var t = typeof v
+ if (t === 'object' || t === 'array' || t === 'function') {
+ return v.toString()
+ } else {
+ return '' + v
+ }
+ }
+ function floatReadValueFromPointer(name, shift) {
+ switch (shift) {
+ case 2:
+ return function (pointer) {
+ return this['fromWireType'](HEAPF32[pointer >> 2])
+ }
+ case 3:
+ return function (pointer) {
+ return this['fromWireType'](HEAPF64[pointer >> 3])
+ }
+ default:
+ throw new TypeError('Unknown float type: ' + name)
+ }
+ }
+ function __embind_register_float(rawType, name, size) {
+ var shift = getShiftFromSize(size)
+ name = readLatin1String(name)
+ registerType(rawType, {
+ name: name,
+ fromWireType: function (value) {
+ return value
+ },
+ toWireType: function (destructors, value) {
+ if (typeof value !== 'number' && typeof value !== 'boolean') {
+ throw new TypeError(
+ 'Cannot convert "' + _embind_repr(value) + '" to ' + this.name
+ )
+ }
+ return value
+ },
+ argPackAdvance: 8,
+ readValueFromPointer: floatReadValueFromPointer(name, shift),
+ destructorFunction: null,
+ })
+ }
+ function new_(constructor, argumentList) {
+ if (!(constructor instanceof Function)) {
+ throw new TypeError(
+ 'new_ called with constructor type ' +
+ typeof constructor +
+ ' which is not a function'
+ )
+ }
+ var dummy = createNamedFunction(
+ constructor.name || 'unknownFunctionName',
+ function () {}
+ )
+ dummy.prototype = constructor.prototype
+ var obj = new dummy()
+ var r = constructor.apply(obj, argumentList)
+ return r instanceof Object ? r : obj
+ }
+ function craftInvokerFunction(
+ humanName,
+ argTypes,
+ classType,
+ cppInvokerFunc,
+ cppTargetFunc
+ ) {
+ var argCount = argTypes.length
+ if (argCount < 2) {
+ throwBindingError(
+ "argTypes array size mismatch! Must at least get return value and 'this' types!"
+ )
+ }
+ var isClassMethodFunc = argTypes[1] !== null && classType !== null
+ var needsDestructorStack = false
+ for (var i = 1; i < argTypes.length; ++i) {
+ if (
+ argTypes[i] !== null &&
+ argTypes[i].destructorFunction === undefined
+ ) {
+ needsDestructorStack = true
+ break
+ }
+ }
+ var returns = argTypes[0].name !== 'void'
+ var argsList = ''
+ var argsListWired = ''
+ for (var i = 0; i < argCount - 2; ++i) {
+ argsList += (i !== 0 ? ', ' : '') + 'arg' + i
+ argsListWired += (i !== 0 ? ', ' : '') + 'arg' + i + 'Wired'
+ }
+ var invokerFnBody =
+ 'return function ' +
+ makeLegalFunctionName(humanName) +
+ '(' +
+ argsList +
+ ') {\n' +
+ 'if (arguments.length !== ' +
+ (argCount - 2) +
+ ') {\n' +
+ "throwBindingError('function " +
+ humanName +
+ " called with ' + arguments.length + ' arguments, expected " +
+ (argCount - 2) +
+ " args!');\n" +
+ '}\n'
+ if (needsDestructorStack) {
+ invokerFnBody += 'var destructors = [];\n'
+ }
+ var dtorStack = needsDestructorStack ? 'destructors' : 'null'
+ var args1 = [
+ 'throwBindingError',
+ 'invoker',
+ 'fn',
+ 'runDestructors',
+ 'retType',
+ 'classParam',
+ ]
+ var args2 = [
+ throwBindingError,
+ cppInvokerFunc,
+ cppTargetFunc,
+ runDestructors,
+ argTypes[0],
+ argTypes[1],
+ ]
+ if (isClassMethodFunc) {
+ invokerFnBody +=
+ 'var thisWired = classParam.toWireType(' + dtorStack + ', this);\n'
+ }
+ for (var i = 0; i < argCount - 2; ++i) {
+ invokerFnBody +=
+ 'var arg' +
+ i +
+ 'Wired = argType' +
+ i +
+ '.toWireType(' +
+ dtorStack +
+ ', arg' +
+ i +
+ '); // ' +
+ argTypes[i + 2].name +
+ '\n'
+ args1.push('argType' + i)
+ args2.push(argTypes[i + 2])
+ }
+ if (isClassMethodFunc) {
+ argsListWired =
+ 'thisWired' + (argsListWired.length > 0 ? ', ' : '') + argsListWired
+ }
+ invokerFnBody +=
+ (returns ? 'var rv = ' : '') +
+ 'invoker(fn' +
+ (argsListWired.length > 0 ? ', ' : '') +
+ argsListWired +
+ ');\n'
+ if (needsDestructorStack) {
+ invokerFnBody += 'runDestructors(destructors);\n'
+ } else {
+ for (var i = isClassMethodFunc ? 1 : 2; i < argTypes.length; ++i) {
+ var paramName = i === 1 ? 'thisWired' : 'arg' + (i - 2) + 'Wired'
+ if (argTypes[i].destructorFunction !== null) {
+ invokerFnBody +=
+ paramName +
+ '_dtor(' +
+ paramName +
+ '); // ' +
+ argTypes[i].name +
+ '\n'
+ args1.push(paramName + '_dtor')
+ args2.push(argTypes[i].destructorFunction)
+ }
+ }
+ }
+ if (returns) {
+ invokerFnBody +=
+ 'var ret = retType.fromWireType(rv);\n' + 'return ret;\n'
+ } else {
+ }
+ invokerFnBody += '}\n'
+ args1.push(invokerFnBody)
+ var invokerFunction = new_(Function, args1).apply(null, args2)
+ return invokerFunction
+ }
+ function ensureOverloadTable(proto, methodName, humanName) {
+ if (undefined === proto[methodName].overloadTable) {
+ var prevFunc = proto[methodName]
+ proto[methodName] = function () {
+ if (
+ !proto[methodName].overloadTable.hasOwnProperty(arguments.length)
+ ) {
+ throwBindingError(
+ "Function '" +
+ humanName +
+ "' called with an invalid number of arguments (" +
+ arguments.length +
+ ') - expects one of (' +
+ proto[methodName].overloadTable +
+ ')!'
+ )
+ }
+ return proto[methodName].overloadTable[arguments.length].apply(
+ this,
+ arguments
+ )
+ }
+ proto[methodName].overloadTable = []
+ proto[methodName].overloadTable[prevFunc.argCount] = prevFunc
+ }
+ }
+ function exposePublicSymbol(name, value, numArguments) {
+ if (Module.hasOwnProperty(name)) {
+ if (
+ undefined === numArguments ||
+ (undefined !== Module[name].overloadTable &&
+ undefined !== Module[name].overloadTable[numArguments])
+ ) {
+ throwBindingError("Cannot register public name '" + name + "' twice")
+ }
+ ensureOverloadTable(Module, name, name)
+ if (Module.hasOwnProperty(numArguments)) {
+ throwBindingError(
+ 'Cannot register multiple overloads of a function with the same number of arguments (' +
+ numArguments +
+ ')!'
+ )
+ }
+ Module[name].overloadTable[numArguments] = value
+ } else {
+ Module[name] = value
+ if (undefined !== numArguments) {
+ Module[name].numArguments = numArguments
+ }
+ }
+ }
+ function heap32VectorToArray(count, firstElement) {
+ var array = []
+ for (var i = 0; i < count; i++) {
+ array.push(HEAP32[(firstElement >> 2) + i])
+ }
+ return array
+ }
+ function replacePublicSymbol(name, value, numArguments) {
+ if (!Module.hasOwnProperty(name)) {
+ throwInternalError('Replacing nonexistant public symbol')
+ }
+ if (
+ undefined !== Module[name].overloadTable &&
+ undefined !== numArguments
+ ) {
+ Module[name].overloadTable[numArguments] = value
+ } else {
+ Module[name] = value
+ Module[name].argCount = numArguments
+ }
+ }
+ function dynCallLegacy(sig, ptr, args) {
+ var f = Module['dynCall_' + sig]
+ return args && args.length
+ ? f.apply(null, [ptr].concat(args))
+ : f.call(null, ptr)
+ }
+ function dynCall(sig, ptr, args) {
+ if (sig.includes('j')) {
+ return dynCallLegacy(sig, ptr, args)
+ }
+ return wasmTable.get(ptr).apply(null, args)
+ }
+ function getDynCaller(sig, ptr) {
+ var argCache = []
+ return function () {
+ argCache.length = arguments.length
+ for (var i = 0; i < arguments.length; i++) {
+ argCache[i] = arguments[i]
+ }
+ return dynCall(sig, ptr, argCache)
+ }
+ }
+ function embind__requireFunction(signature, rawFunction) {
+ signature = readLatin1String(signature)
+ function makeDynCaller() {
+ if (signature.includes('j')) {
+ return getDynCaller(signature, rawFunction)
+ }
+ return wasmTable.get(rawFunction)
+ }
+ var fp = makeDynCaller()
+ if (typeof fp !== 'function') {
+ throwBindingError(
+ 'unknown function pointer with signature ' +
+ signature +
+ ': ' +
+ rawFunction
+ )
+ }
+ return fp
+ }
+ var UnboundTypeError = undefined
+ function getTypeName(type) {
+ var ptr = ___getTypeName(type)
+ var rv = readLatin1String(ptr)
+ _free(ptr)
+ return rv
+ }
+ function throwUnboundTypeError(message, types) {
+ var unboundTypes = []
+ var seen = {}
+ function visit(type) {
+ if (seen[type]) {
+ return
+ }
+ if (registeredTypes[type]) {
+ return
+ }
+ if (typeDependencies[type]) {
+ typeDependencies[type].forEach(visit)
+ return
+ }
+ unboundTypes.push(type)
+ seen[type] = true
+ }
+ types.forEach(visit)
+ throw new UnboundTypeError(
+ message + ': ' + unboundTypes.map(getTypeName).join([', '])
+ )
+ }
+ function __embind_register_function(
+ name,
+ argCount,
+ rawArgTypesAddr,
+ signature,
+ rawInvoker,
+ fn
+ ) {
+ var argTypes = heap32VectorToArray(argCount, rawArgTypesAddr)
+ name = readLatin1String(name)
+ rawInvoker = embind__requireFunction(signature, rawInvoker)
+ exposePublicSymbol(
+ name,
+ function () {
+ throwUnboundTypeError(
+ 'Cannot call ' + name + ' due to unbound types',
+ argTypes
+ )
+ },
+ argCount - 1
+ )
+ whenDependentTypesAreResolved([], argTypes, function (argTypes) {
+ var invokerArgsArray = [argTypes[0], null].concat(argTypes.slice(1))
+ replacePublicSymbol(
+ name,
+ craftInvokerFunction(name, invokerArgsArray, null, rawInvoker, fn),
+ argCount - 1
+ )
+ return []
+ })
+ }
+ function integerReadValueFromPointer(name, shift, signed) {
+ switch (shift) {
+ case 0:
+ return signed
+ ? function readS8FromPointer(pointer) {
+ return HEAP8[pointer]
+ }
+ : function readU8FromPointer(pointer) {
+ return HEAPU8[pointer]
+ }
+ case 1:
+ return signed
+ ? function readS16FromPointer(pointer) {
+ return HEAP16[pointer >> 1]
+ }
+ : function readU16FromPointer(pointer) {
+ return HEAPU16[pointer >> 1]
+ }
+ case 2:
+ return signed
+ ? function readS32FromPointer(pointer) {
+ return HEAP32[pointer >> 2]
+ }
+ : function readU32FromPointer(pointer) {
+ return HEAPU32[pointer >> 2]
+ }
+ default:
+ throw new TypeError('Unknown integer type: ' + name)
+ }
+ }
+ function __embind_register_integer(
+ primitiveType,
+ name,
+ size,
+ minRange,
+ maxRange
+ ) {
+ name = readLatin1String(name)
+ if (maxRange === -1) {
+ maxRange = 4294967295
+ }
+ var shift = getShiftFromSize(size)
+ var fromWireType = function (value) {
+ return value
+ }
+ if (minRange === 0) {
+ var bitshift = 32 - 8 * size
+ fromWireType = function (value) {
+ return (value << bitshift) >>> bitshift
+ }
+ }
+ var isUnsignedType = name.includes('unsigned')
+ registerType(primitiveType, {
+ name: name,
+ fromWireType: fromWireType,
+ toWireType: function (destructors, value) {
+ if (typeof value !== 'number' && typeof value !== 'boolean') {
+ throw new TypeError(
+ 'Cannot convert "' + _embind_repr(value) + '" to ' + this.name
+ )
+ }
+ if (value < minRange || value > maxRange) {
+ throw new TypeError(
+ 'Passing a number "' +
+ _embind_repr(value) +
+ '" from JS side to C/C++ side to an argument of type "' +
+ name +
+ '", which is outside the valid range [' +
+ minRange +
+ ', ' +
+ maxRange +
+ ']!'
+ )
+ }
+ return isUnsignedType ? value >>> 0 : value | 0
+ },
+ argPackAdvance: 8,
+ readValueFromPointer: integerReadValueFromPointer(
+ name,
+ shift,
+ minRange !== 0
+ ),
+ destructorFunction: null,
+ })
+ }
+ function __embind_register_memory_view(rawType, dataTypeIndex, name) {
+ var typeMapping = [
+ Int8Array,
+ Uint8Array,
+ Int16Array,
+ Uint16Array,
+ Int32Array,
+ Uint32Array,
+ Float32Array,
+ Float64Array,
+ ]
+ var TA = typeMapping[dataTypeIndex]
+ function decodeMemoryView(handle) {
+ handle = handle >> 2
+ var heap = HEAPU32
+ var size = heap[handle]
+ var data = heap[handle + 1]
+ return new TA(buffer, data, size)
+ }
+ name = readLatin1String(name)
+ registerType(
+ rawType,
+ {
+ name: name,
+ fromWireType: decodeMemoryView,
+ argPackAdvance: 8,
+ readValueFromPointer: decodeMemoryView,
+ },
+ { ignoreDuplicateRegistrations: true }
+ )
+ }
+ function __embind_register_std_string(rawType, name) {
+ name = readLatin1String(name)
+ var stdStringIsUTF8 = name === 'std::string'
+ registerType(rawType, {
+ name: name,
+ fromWireType: function (value) {
+ var length = HEAPU32[value >> 2]
+ var str
+ if (stdStringIsUTF8) {
+ var decodeStartPtr = value + 4
+ for (var i = 0; i <= length; ++i) {
+ var currentBytePtr = value + 4 + i
+ if (i == length || HEAPU8[currentBytePtr] == 0) {
+ var maxRead = currentBytePtr - decodeStartPtr
+ var stringSegment = UTF8ToString(decodeStartPtr, maxRead)
+ if (str === undefined) {
+ str = stringSegment
+ } else {
+ str += String.fromCharCode(0)
+ str += stringSegment
+ }
+ decodeStartPtr = currentBytePtr + 1
+ }
+ }
+ } else {
+ var a = new Array(length)
+ for (var i = 0; i < length; ++i) {
+ a[i] = String.fromCharCode(HEAPU8[value + 4 + i])
+ }
+ str = a.join('')
+ }
+ _free(value)
+ return str
+ },
+ toWireType: function (destructors, value) {
+ if (value instanceof ArrayBuffer) {
+ value = new Uint8Array(value)
+ }
+ var getLength
+ var valueIsOfTypeString = typeof value === 'string'
+ if (
+ !(
+ valueIsOfTypeString ||
+ value instanceof Uint8Array ||
+ value instanceof Uint8ClampedArray ||
+ value instanceof Int8Array
+ )
+ ) {
+ throwBindingError('Cannot pass non-string to std::string')
+ }
+ if (stdStringIsUTF8 && valueIsOfTypeString) {
+ getLength = function () {
+ return lengthBytesUTF8(value)
+ }
+ } else {
+ getLength = function () {
+ return value.length
+ }
+ }
+ var length = getLength()
+ var ptr = _malloc(4 + length + 1)
+ HEAPU32[ptr >> 2] = length
+ if (stdStringIsUTF8 && valueIsOfTypeString) {
+ stringToUTF8(value, ptr + 4, length + 1)
+ } else {
+ if (valueIsOfTypeString) {
+ for (var i = 0; i < length; ++i) {
+ var charCode = value.charCodeAt(i)
+ if (charCode > 255) {
+ _free(ptr)
+ throwBindingError(
+ 'String has UTF-16 code units that do not fit in 8 bits'
+ )
+ }
+ HEAPU8[ptr + 4 + i] = charCode
+ }
+ } else {
+ for (var i = 0; i < length; ++i) {
+ HEAPU8[ptr + 4 + i] = value[i]
+ }
+ }
+ }
+ if (destructors !== null) {
+ destructors.push(_free, ptr)
+ }
+ return ptr
+ },
+ argPackAdvance: 8,
+ readValueFromPointer: simpleReadValueFromPointer,
+ destructorFunction: function (ptr) {
+ _free(ptr)
+ },
+ })
+ }
+ function __embind_register_std_wstring(rawType, charSize, name) {
+ name = readLatin1String(name)
+ var decodeString, encodeString, getHeap, lengthBytesUTF, shift
+ if (charSize === 2) {
+ decodeString = UTF16ToString
+ encodeString = stringToUTF16
+ lengthBytesUTF = lengthBytesUTF16
+ getHeap = function () {
+ return HEAPU16
+ }
+ shift = 1
+ } else if (charSize === 4) {
+ decodeString = UTF32ToString
+ encodeString = stringToUTF32
+ lengthBytesUTF = lengthBytesUTF32
+ getHeap = function () {
+ return HEAPU32
+ }
+ shift = 2
+ }
+ registerType(rawType, {
+ name: name,
+ fromWireType: function (value) {
+ var length = HEAPU32[value >> 2]
+ var HEAP = getHeap()
+ var str
+ var decodeStartPtr = value + 4
+ for (var i = 0; i <= length; ++i) {
+ var currentBytePtr = value + 4 + i * charSize
+ if (i == length || HEAP[currentBytePtr >> shift] == 0) {
+ var maxReadBytes = currentBytePtr - decodeStartPtr
+ var stringSegment = decodeString(decodeStartPtr, maxReadBytes)
+ if (str === undefined) {
+ str = stringSegment
+ } else {
+ str += String.fromCharCode(0)
+ str += stringSegment
+ }
+ decodeStartPtr = currentBytePtr + charSize
+ }
+ }
+ _free(value)
+ return str
+ },
+ toWireType: function (destructors, value) {
+ if (!(typeof value === 'string')) {
+ throwBindingError(
+ 'Cannot pass non-string to C++ string type ' + name
+ )
+ }
+ var length = lengthBytesUTF(value)
+ var ptr = _malloc(4 + length + charSize)
+ HEAPU32[ptr >> 2] = length >> shift
+ encodeString(value, ptr + 4, length + charSize)
+ if (destructors !== null) {
+ destructors.push(_free, ptr)
+ }
+ return ptr
+ },
+ argPackAdvance: 8,
+ readValueFromPointer: simpleReadValueFromPointer,
+ destructorFunction: function (ptr) {
+ _free(ptr)
+ },
+ })
+ }
+ function __embind_register_value_object(
+ rawType,
+ name,
+ constructorSignature,
+ rawConstructor,
+ destructorSignature,
+ rawDestructor
+ ) {
+ structRegistrations[rawType] = {
+ name: readLatin1String(name),
+ rawConstructor: embind__requireFunction(
+ constructorSignature,
+ rawConstructor
+ ),
+ rawDestructor: embind__requireFunction(
+ destructorSignature,
+ rawDestructor
+ ),
+ fields: [],
+ }
+ }
+ function __embind_register_value_object_field(
+ structType,
+ fieldName,
+ getterReturnType,
+ getterSignature,
+ getter,
+ getterContext,
+ setterArgumentType,
+ setterSignature,
+ setter,
+ setterContext
+ ) {
+ structRegistrations[structType].fields.push({
+ fieldName: readLatin1String(fieldName),
+ getterReturnType: getterReturnType,
+ getter: embind__requireFunction(getterSignature, getter),
+ getterContext: getterContext,
+ setterArgumentType: setterArgumentType,
+ setter: embind__requireFunction(setterSignature, setter),
+ setterContext: setterContext,
+ })
+ }
+ function __embind_register_void(rawType, name) {
+ name = readLatin1String(name)
+ registerType(rawType, {
+ isVoid: true,
+ name: name,
+ argPackAdvance: 0,
+ fromWireType: function () {
+ return undefined
+ },
+ toWireType: function (destructors, o) {
+ return undefined
+ },
+ })
+ }
+ var emval_symbols = {}
+ function getStringOrSymbol(address) {
+ var symbol = emval_symbols[address]
+ if (symbol === undefined) {
+ return readLatin1String(address)
+ } else {
+ return symbol
+ }
+ }
+ function emval_get_global() {
+ if (typeof globalThis === 'object') {
+ return globalThis
+ }
+ return (function () {
+ return Function
+ })()('return this')()
+ }
+ function __emval_get_global(name) {
+ if (name === 0) {
+ return __emval_register(emval_get_global())
+ } else {
+ name = getStringOrSymbol(name)
+ return __emval_register(emval_get_global()[name])
+ }
+ }
+ function __emval_incref(handle) {
+ if (handle > 4) {
+ emval_handle_array[handle].refcount += 1
+ }
+ }
+ function requireRegisteredType(rawType, humanName) {
+ var impl = registeredTypes[rawType]
+ if (undefined === impl) {
+ throwBindingError(
+ humanName + ' has unknown type ' + getTypeName(rawType)
+ )
+ }
+ return impl
+ }
+ function craftEmvalAllocator(argCount) {
+ var argsList = ''
+ for (var i = 0; i < argCount; ++i) {
+ argsList += (i !== 0 ? ', ' : '') + 'arg' + i
+ }
+ var functionBody =
+ 'return function emval_allocator_' +
+ argCount +
+ '(constructor, argTypes, args) {\n'
+ for (var i = 0; i < argCount; ++i) {
+ functionBody +=
+ 'var argType' +
+ i +
+ " = requireRegisteredType(Module['HEAP32'][(argTypes >>> 2) + " +
+ i +
+ '], "parameter ' +
+ i +
+ '");\n' +
+ 'var arg' +
+ i +
+ ' = argType' +
+ i +
+ '.readValueFromPointer(args);\n' +
+ 'args += argType' +
+ i +
+ "['argPackAdvance'];\n"
+ }
+ functionBody +=
+ 'var obj = new constructor(' +
+ argsList +
+ ');\n' +
+ 'return __emval_register(obj);\n' +
+ '}\n'
+ return new Function(
+ 'requireRegisteredType',
+ 'Module',
+ '__emval_register',
+ functionBody
+ )(requireRegisteredType, Module, __emval_register)
+ }
+ var emval_newers = {}
+ function requireHandle(handle) {
+ if (!handle) {
+ throwBindingError('Cannot use deleted val. handle = ' + handle)
+ }
+ return emval_handle_array[handle].value
+ }
+ function __emval_new(handle, argCount, argTypes, args) {
+ handle = requireHandle(handle)
+ var newer = emval_newers[argCount]
+ if (!newer) {
+ newer = craftEmvalAllocator(argCount)
+ emval_newers[argCount] = newer
+ }
+ return newer(handle, argTypes, args)
+ }
+ function _abort() {
+ abort()
+ }
+ function _longjmp(env, value) {
+ _setThrew(env, value || 1)
+ throw 'longjmp'
+ }
+ function _emscripten_longjmp(a0, a1) {
+ return _longjmp(a0, a1)
+ }
+ function _emscripten_memcpy_big(dest, src, num) {
+ HEAPU8.copyWithin(dest, src, src + num)
+ }
+ function emscripten_realloc_buffer(size) {
+ try {
+ wasmMemory.grow((size - buffer.byteLength + 65535) >>> 16)
+ updateGlobalBufferAndViews(wasmMemory.buffer)
+ return 1
+ } catch (e) {}
+ }
+ function _emscripten_resize_heap(requestedSize) {
+ var oldSize = HEAPU8.length
+ requestedSize = requestedSize >>> 0
+ var maxHeapSize = 2147483648
+ if (requestedSize > maxHeapSize) {
+ return false
+ }
+ for (var cutDown = 1; cutDown <= 4; cutDown *= 2) {
+ var overGrownHeapSize = oldSize * (1 + 0.2 / cutDown)
+ overGrownHeapSize = Math.min(
+ overGrownHeapSize,
+ requestedSize + 100663296
+ )
+ var newSize = Math.min(
+ maxHeapSize,
+ alignUp(Math.max(requestedSize, overGrownHeapSize), 65536)
+ )
+ var replacement = emscripten_realloc_buffer(newSize)
+ if (replacement) {
+ return true
+ }
+ }
+ return false
+ }
+ function _fd_close(fd) {
+ return 0
+ }
+ function _fd_read(fd, iov, iovcnt, pnum) {
+ var stream = SYSCALLS.getStreamFromFD(fd)
+ var num = SYSCALLS.doReadv(stream, iov, iovcnt)
+ HEAP32[pnum >> 2] = num
+ return 0
+ }
+ function _fd_seek(fd, offset_low, offset_high, whence, newOffset) {}
+ function _fd_write(fd, iov, iovcnt, pnum) {
+ var num = 0
+ for (var i = 0; i < iovcnt; i++) {
+ var ptr = HEAP32[(iov + i * 8) >> 2]
+ var len = HEAP32[(iov + (i * 8 + 4)) >> 2]
+ for (var j = 0; j < len; j++) {
+ SYSCALLS.printChar(fd, HEAPU8[ptr + j])
+ }
+ num += len
+ }
+ HEAP32[pnum >> 2] = num
+ return 0
+ }
+ function _getTempRet0() {
+ return getTempRet0()
+ }
+ function _setTempRet0(val) {
+ setTempRet0(val)
+ }
+ function _time(ptr) {
+ var ret = (Date.now() / 1e3) | 0
+ if (ptr) {
+ HEAP32[ptr >> 2] = ret
+ }
+ return ret
+ }
+ InternalError = Module['InternalError'] = extendError(
+ Error,
+ 'InternalError'
+ )
+ embind_init_charCodes()
+ BindingError = Module['BindingError'] = extendError(Error, 'BindingError')
+ init_emval()
+ UnboundTypeError = Module['UnboundTypeError'] = extendError(
+ Error,
+ 'UnboundTypeError'
+ )
+ var asmLibraryArg = {
+ O: ___cxa_thread_atexit,
+ r: ___sys_fcntl64,
+ G: ___sys_ioctl,
+ H: ___sys_open,
+ x: __embind_finalize_value_object,
+ B: __embind_register_bigint,
+ K: __embind_register_bool,
+ J: __embind_register_emval,
+ t: __embind_register_float,
+ w: __embind_register_function,
+ i: __embind_register_integer,
+ e: __embind_register_memory_view,
+ u: __embind_register_std_string,
+ o: __embind_register_std_wstring,
+ z: __embind_register_value_object,
+ g: __embind_register_value_object_field,
+ L: __embind_register_void,
+ j: __emval_decref,
+ N: __emval_get_global,
+ v: __emval_incref,
+ D: __emval_new,
+ f: _abort,
+ d: _emscripten_longjmp,
+ E: _emscripten_memcpy_big,
+ n: _emscripten_resize_heap,
+ s: _fd_close,
+ F: _fd_read,
+ A: _fd_seek,
+ I: _fd_write,
+ b: _getTempRet0,
+ l: invoke_iiiii,
+ p: invoke_iiiiiiiii,
+ q: invoke_iiiiiiiiii,
+ C: invoke_iiiiiiiiiiii,
+ y: invoke_ijiii,
+ m: invoke_vi,
+ h: invoke_vii,
+ c: invoke_viiii,
+ k: invoke_viiiiiiiiii,
+ a: _setTempRet0,
+ M: _time,
+ }
+ var asm = createWasm()
+ var ___wasm_call_ctors = (Module['___wasm_call_ctors'] = function () {
+ return (___wasm_call_ctors = Module['___wasm_call_ctors'] =
+ Module['asm']['Q']).apply(null, arguments)
+ })
+ var _malloc = (Module['_malloc'] = function () {
+ return (_malloc = Module['_malloc'] = Module['asm']['R']).apply(
+ null,
+ arguments
+ )
+ })
+ var _free = (Module['_free'] = function () {
+ return (_free = Module['_free'] = Module['asm']['S']).apply(
+ null,
+ arguments
+ )
+ })
+ var ___getTypeName = (Module['___getTypeName'] = function () {
+ return (___getTypeName = Module['___getTypeName'] =
+ Module['asm']['T']).apply(null, arguments)
+ })
+ var ___embind_register_native_and_builtin_types = (Module[
+ '___embind_register_native_and_builtin_types'
+ ] = function () {
+ return (___embind_register_native_and_builtin_types = Module[
+ '___embind_register_native_and_builtin_types'
+ ] =
+ Module['asm']['U']).apply(null, arguments)
+ })
+ var stackSave = (Module['stackSave'] = function () {
+ return (stackSave = Module['stackSave'] = Module['asm']['V']).apply(
+ null,
+ arguments
+ )
+ })
+ var stackRestore = (Module['stackRestore'] = function () {
+ return (stackRestore = Module['stackRestore'] = Module['asm']['W']).apply(
+ null,
+ arguments
+ )
+ })
+ var _setThrew = (Module['_setThrew'] = function () {
+ return (_setThrew = Module['_setThrew'] = Module['asm']['X']).apply(
+ null,
+ arguments
+ )
+ })
+ var dynCall_jiiiiiiiii = (Module['dynCall_jiiiiiiiii'] = function () {
+ return (dynCall_jiiiiiiiii = Module['dynCall_jiiiiiiiii'] =
+ Module['asm']['Z']).apply(null, arguments)
+ })
+ var dynCall_ijiii = (Module['dynCall_ijiii'] = function () {
+ return (dynCall_ijiii = Module['dynCall_ijiii'] =
+ Module['asm']['_']).apply(null, arguments)
+ })
+ var dynCall_jiji = (Module['dynCall_jiji'] = function () {
+ return (dynCall_jiji = Module['dynCall_jiji'] = Module['asm']['$']).apply(
+ null,
+ arguments
+ )
+ })
+ var dynCall_jiiiiiiii = (Module['dynCall_jiiiiiiii'] = function () {
+ return (dynCall_jiiiiiiii = Module['dynCall_jiiiiiiii'] =
+ Module['asm']['aa']).apply(null, arguments)
+ })
+ var dynCall_jiiiiii = (Module['dynCall_jiiiiii'] = function () {
+ return (dynCall_jiiiiii = Module['dynCall_jiiiiii'] =
+ Module['asm']['ba']).apply(null, arguments)
+ })
+ var dynCall_jiiiii = (Module['dynCall_jiiiii'] = function () {
+ return (dynCall_jiiiii = Module['dynCall_jiiiii'] =
+ Module['asm']['ca']).apply(null, arguments)
+ })
+ var dynCall_iiijii = (Module['dynCall_iiijii'] = function () {
+ return (dynCall_iiijii = Module['dynCall_iiijii'] =
+ Module['asm']['da']).apply(null, arguments)
+ })
+ function invoke_vi(index, a1) {
+ var sp = stackSave()
+ try {
+ wasmTable.get(index)(a1)
+ } catch (e) {
+ stackRestore(sp)
+ if (e !== e + 0 && e !== 'longjmp') throw e
+ _setThrew(1, 0)
+ }
+ }
+ function invoke_viiii(index, a1, a2, a3, a4) {
+ var sp = stackSave()
+ try {
+ wasmTable.get(index)(a1, a2, a3, a4)
+ } catch (e) {
+ stackRestore(sp)
+ if (e !== e + 0 && e !== 'longjmp') throw e
+ _setThrew(1, 0)
+ }
+ }
+ function invoke_vii(index, a1, a2) {
+ var sp = stackSave()
+ try {
+ wasmTable.get(index)(a1, a2)
+ } catch (e) {
+ stackRestore(sp)
+ if (e !== e + 0 && e !== 'longjmp') throw e
+ _setThrew(1, 0)
+ }
+ }
+ function invoke_iiiiiiiiii(index, a1, a2, a3, a4, a5, a6, a7, a8, a9) {
+ var sp = stackSave()
+ try {
+ return wasmTable.get(index)(a1, a2, a3, a4, a5, a6, a7, a8, a9)
+ } catch (e) {
+ stackRestore(sp)
+ if (e !== e + 0 && e !== 'longjmp') throw e
+ _setThrew(1, 0)
+ }
+ }
+ function invoke_iiiiiiiiiiii(
+ index,
+ a1,
+ a2,
+ a3,
+ a4,
+ a5,
+ a6,
+ a7,
+ a8,
+ a9,
+ a10,
+ a11
+ ) {
+ var sp = stackSave()
+ try {
+ return wasmTable.get(index)(
+ a1,
+ a2,
+ a3,
+ a4,
+ a5,
+ a6,
+ a7,
+ a8,
+ a9,
+ a10,
+ a11
+ )
+ } catch (e) {
+ stackRestore(sp)
+ if (e !== e + 0 && e !== 'longjmp') throw e
+ _setThrew(1, 0)
+ }
+ }
+ function invoke_iiiii(index, a1, a2, a3, a4) {
+ var sp = stackSave()
+ try {
+ return wasmTable.get(index)(a1, a2, a3, a4)
+ } catch (e) {
+ stackRestore(sp)
+ if (e !== e + 0 && e !== 'longjmp') throw e
+ _setThrew(1, 0)
+ }
+ }
+ function invoke_viiiiiiiiii(
+ index,
+ a1,
+ a2,
+ a3,
+ a4,
+ a5,
+ a6,
+ a7,
+ a8,
+ a9,
+ a10
+ ) {
+ var sp = stackSave()
+ try {
+ wasmTable.get(index)(a1, a2, a3, a4, a5, a6, a7, a8, a9, a10)
+ } catch (e) {
+ stackRestore(sp)
+ if (e !== e + 0 && e !== 'longjmp') throw e
+ _setThrew(1, 0)
+ }
+ }
+ function invoke_iiiiiiiii(index, a1, a2, a3, a4, a5, a6, a7, a8) {
+ var sp = stackSave()
+ try {
+ return wasmTable.get(index)(a1, a2, a3, a4, a5, a6, a7, a8)
+ } catch (e) {
+ stackRestore(sp)
+ if (e !== e + 0 && e !== 'longjmp') throw e
+ _setThrew(1, 0)
+ }
+ }
+ function invoke_ijiii(index, a1, a2, a3, a4, a5) {
+ var sp = stackSave()
+ try {
+ return dynCall_ijiii(index, a1, a2, a3, a4, a5)
+ } catch (e) {
+ stackRestore(sp)
+ if (e !== e + 0 && e !== 'longjmp') throw e
+ _setThrew(1, 0)
+ }
+ }
+ var calledRun
+ dependenciesFulfilled = function runCaller() {
+ if (!calledRun) run()
+ if (!calledRun) dependenciesFulfilled = runCaller
+ }
+ function run(args) {
+ args = args || arguments_
+ if (runDependencies > 0) {
+ return
+ }
+ preRun()
+ if (runDependencies > 0) {
+ return
+ }
+ function doRun() {
+ if (calledRun) return
+ calledRun = true
+ Module['calledRun'] = true
+ if (ABORT) return
+ initRuntime()
+ readyPromiseResolve(Module)
+ if (Module['onRuntimeInitialized']) Module['onRuntimeInitialized']()
+ postRun()
+ }
+ if (Module['setStatus']) {
+ Module['setStatus']('Running...')
+ setTimeout(function () {
+ setTimeout(function () {
+ Module['setStatus']('')
+ }, 1)
+ doRun()
+ }, 1)
+ } else {
+ doRun()
+ }
+ }
+ Module['run'] = run
+ if (Module['preInit']) {
+ if (typeof Module['preInit'] == 'function')
+ Module['preInit'] = [Module['preInit']]
+ while (Module['preInit'].length > 0) {
+ Module['preInit'].pop()()
+ }
+ }
+ run()
+
+ return Module.ready
+ }
+})()
+export default Module
diff --git a/packages/integrations/image/src/vendor/squoosh/avif/avif_node_enc.wasm b/packages/integrations/image/src/vendor/squoosh/avif/avif_node_enc.wasm
new file mode 100644
index 000000000..6a19f18bf
Binary files /dev/null and b/packages/integrations/image/src/vendor/squoosh/avif/avif_node_enc.wasm differ
diff --git a/packages/integrations/image/src/vendor/squoosh/codecs.ts b/packages/integrations/image/src/vendor/squoosh/codecs.ts
new file mode 100644
index 000000000..f4b231591
--- /dev/null
+++ b/packages/integrations/image/src/vendor/squoosh/codecs.ts
@@ -0,0 +1,373 @@
+import { promises as fsp } from 'node:fs'
+import { instantiateEmscriptenWasm, pathify } from './emscripten-utils.js'
+
+interface DecodeModule extends EmscriptenWasm.Module {
+ decode: (data: Uint8Array) => ImageData
+}
+
+type DecodeModuleFactory = EmscriptenWasm.ModuleFactory
+
+interface RotateModuleInstance {
+ exports: {
+ memory: WebAssembly.Memory
+ rotate(width: number, height: number, rotate: number): void
+ }
+}
+
+interface ResizeWithAspectParams {
+ input_width: number
+ input_height: number
+ target_width?: number
+ target_height?: number
+}
+
+export interface ResizeOptions {
+ width?: number
+ height?: number
+ method: 'triangle' | 'catrom' | 'mitchell' | 'lanczos3'
+ premultiply: boolean
+ linearRGB: boolean
+}
+
+export interface RotateOptions {
+ numRotations: number
+}
+
+// MozJPEG
+import type { MozJPEGModule as MozJPEGEncodeModule } from './mozjpeg/mozjpeg_enc'
+// @ts-ignore
+import mozEnc from './mozjpeg/mozjpeg_node_enc.js'
+const mozEncWasm = new URL('./mozjpeg/mozjpeg_node_enc.wasm', import.meta.url)
+// @ts-ignore
+import mozDec from './mozjpeg/mozjpeg_node_dec.js'
+const mozDecWasm = new URL('./mozjpeg/mozjpeg_node_dec.wasm', import.meta.url)
+
+// WebP
+import type { WebPModule as WebPEncodeModule } from './webp/webp_enc'
+// @ts-ignore
+import webpEnc from './webp/webp_node_enc.js'
+const webpEncWasm = new URL('./webp/webp_node_enc.wasm', import.meta.url)
+// @ts-ignore
+import webpDec from './webp/webp_node_dec.js'
+const webpDecWasm = new URL('./webp/webp_node_dec.wasm', import.meta.url)
+
+// AVIF
+import type { AVIFModule as AVIFEncodeModule } from './avif/avif_enc'
+// @ts-ignore
+import avifEnc from './avif/avif_node_enc.js'
+const avifEncWasm = new URL('./avif/avif_node_enc.wasm', import.meta.url)
+// @ts-ignore
+import avifDec from './avif/avif_node_dec.js'
+const avifDecWasm = new URL('./avif/avif_node_dec.wasm', import.meta.url)
+
+// PNG
+// @ts-ignore
+import * as pngEncDec from './png/squoosh_png.js'
+const pngEncDecWasm = new URL('./png/squoosh_png_bg.wasm', import.meta.url)
+const pngEncDecInit = () =>
+ pngEncDec.default(fsp.readFile(pathify(pngEncDecWasm.toString())))
+
+// OxiPNG
+// @ts-ignore
+import * as oxipng from './png/squoosh_oxipng.js'
+const oxipngWasm = new URL('./png/squoosh_oxipng_bg.wasm', import.meta.url)
+const oxipngInit = () => oxipng.default(fsp.readFile(pathify(oxipngWasm.toString())))
+
+// Resize
+// @ts-ignore
+import * as resize from './resize/squoosh_resize.js'
+const resizeWasm = new URL('./resize/squoosh_resize_bg.wasm', import.meta.url)
+const resizeInit = () => resize.default(fsp.readFile(pathify(resizeWasm.toString())))
+
+// rotate
+const rotateWasm = new URL('./rotate/rotate.wasm', import.meta.url)
+
+// Our decoders currently rely on a `ImageData` global.
+import ImageData from './image_data.js';
+(global as any).ImageData = ImageData
+
+function resizeNameToIndex(
+ name: 'triangle' | 'catrom' | 'mitchell' | 'lanczos3'
+) {
+ switch (name) {
+ case 'triangle':
+ return 0
+ case 'catrom':
+ return 1
+ case 'mitchell':
+ return 2
+ case 'lanczos3':
+ return 3
+ default:
+ throw Error(`Unknown resize algorithm "${name}"`)
+ }
+}
+
+function resizeWithAspect({
+ input_width,
+ input_height,
+ target_width,
+ target_height,
+}: ResizeWithAspectParams): { width: number; height: number } {
+ if (!target_width && !target_height) {
+ throw Error('Need to specify at least width or height when resizing')
+ }
+
+ if (target_width && target_height) {
+ return { width: target_width, height: target_height }
+ }
+
+ if (!target_width) {
+ return {
+ width: Math.round((input_width / input_height) * target_height!),
+ height: target_height!,
+ }
+ }
+
+ return {
+ width: target_width,
+ height: Math.round((input_height / input_width) * target_width),
+ }
+}
+
+export const preprocessors = {
+ resize: {
+ name: 'Resize',
+ description: 'Resize the image before compressing',
+ instantiate: async () => {
+ await resizeInit()
+ return (
+ buffer: Uint8Array,
+ input_width: number,
+ input_height: number,
+ { width, height, method, premultiply, linearRGB }: ResizeOptions
+ ) => {
+ ;({ width, height } = resizeWithAspect({
+ input_width,
+ input_height,
+ target_width: width,
+ target_height: height,
+ }))
+ const imageData = new ImageData(
+ resize.resize(
+ buffer,
+ input_width,
+ input_height,
+ width,
+ height,
+ resizeNameToIndex(method),
+ premultiply,
+ linearRGB
+ ),
+ width,
+ height
+ )
+ resize.cleanup()
+ return imageData
+ }
+ },
+ defaultOptions: {
+ method: 'lanczos3',
+ fitMethod: 'stretch',
+ premultiply: true,
+ linearRGB: true,
+ },
+ },
+ rotate: {
+ name: 'Rotate',
+ description: 'Rotate image',
+ instantiate: async () => {
+ return async (
+ buffer: Uint8Array,
+ width: number,
+ height: number,
+ { numRotations }: RotateOptions
+ ) => {
+ const degrees = (numRotations * 90) % 360
+ const sameDimensions = degrees === 0 || degrees === 180
+ const size = width * height * 4
+ const instance = (
+ await WebAssembly.instantiate(await fsp.readFile(pathify(rotateWasm.toString())))
+ ).instance as RotateModuleInstance
+ const { memory } = instance.exports
+ const additionalPagesNeeded = Math.ceil(
+ (size * 2 - memory.buffer.byteLength + 8) / (64 * 1024)
+ )
+ if (additionalPagesNeeded > 0) {
+ memory.grow(additionalPagesNeeded)
+ }
+ const view = new Uint8ClampedArray(memory.buffer)
+ view.set(buffer, 8)
+ instance.exports.rotate(width, height, degrees)
+ return new ImageData(
+ view.slice(size + 8, size * 2 + 8),
+ sameDimensions ? width : height,
+ sameDimensions ? height : width
+ )
+ }
+ },
+ defaultOptions: {
+ numRotations: 0,
+ },
+ },
+} as const
+
+export const codecs = {
+ mozjpeg: {
+ name: 'MozJPEG',
+ extension: 'jpg',
+ detectors: [/^\xFF\xD8\xFF/],
+ dec: () =>
+ instantiateEmscriptenWasm(mozDec as DecodeModuleFactory, mozDecWasm.toString()),
+ enc: () =>
+ instantiateEmscriptenWasm(
+ mozEnc as EmscriptenWasm.ModuleFactory,
+ mozEncWasm.toString()
+ ),
+ defaultEncoderOptions: {
+ quality: 75,
+ baseline: false,
+ arithmetic: false,
+ progressive: true,
+ optimize_coding: true,
+ smoothing: 0,
+ color_space: 3 /*YCbCr*/,
+ quant_table: 3,
+ trellis_multipass: false,
+ trellis_opt_zero: false,
+ trellis_opt_table: false,
+ trellis_loops: 1,
+ auto_subsample: true,
+ chroma_subsample: 2,
+ separate_chroma_quality: false,
+ chroma_quality: 75,
+ },
+ autoOptimize: {
+ option: 'quality',
+ min: 0,
+ max: 100,
+ },
+ },
+ webp: {
+ name: 'WebP',
+ extension: 'webp',
+ detectors: [/^RIFF....WEBPVP8[LX ]/s],
+ dec: () =>
+ instantiateEmscriptenWasm(webpDec as DecodeModuleFactory, webpDecWasm.toString()),
+ enc: () =>
+ instantiateEmscriptenWasm(
+ webpEnc as EmscriptenWasm.ModuleFactory,
+ webpEncWasm.toString()
+ ),
+ defaultEncoderOptions: {
+ quality: 75,
+ target_size: 0,
+ target_PSNR: 0,
+ method: 4,
+ sns_strength: 50,
+ filter_strength: 60,
+ filter_sharpness: 0,
+ filter_type: 1,
+ partitions: 0,
+ segments: 4,
+ pass: 1,
+ show_compressed: 0,
+ preprocessing: 0,
+ autofilter: 0,
+ partition_limit: 0,
+ alpha_compression: 1,
+ alpha_filtering: 1,
+ alpha_quality: 100,
+ lossless: 0,
+ exact: 0,
+ image_hint: 0,
+ emulate_jpeg_size: 0,
+ thread_level: 0,
+ low_memory: 0,
+ near_lossless: 100,
+ use_delta_palette: 0,
+ use_sharp_yuv: 0,
+ },
+ autoOptimize: {
+ option: 'quality',
+ min: 0,
+ max: 100,
+ },
+ },
+ avif: {
+ name: 'AVIF',
+ extension: 'avif',
+ // eslint-disable-next-line no-control-regex
+ detectors: [/^\x00\x00\x00 ftypavif\x00\x00\x00\x00/],
+ dec: () =>
+ instantiateEmscriptenWasm(avifDec as DecodeModuleFactory, avifDecWasm.toString()),
+ enc: async () => {
+ return instantiateEmscriptenWasm(
+ avifEnc as EmscriptenWasm.ModuleFactory,
+ avifEncWasm.toString()
+ )
+ },
+ defaultEncoderOptions: {
+ cqLevel: 33,
+ cqAlphaLevel: -1,
+ denoiseLevel: 0,
+ tileColsLog2: 0,
+ tileRowsLog2: 0,
+ speed: 6,
+ subsample: 1,
+ chromaDeltaQ: false,
+ sharpness: 0,
+ tune: 0 /* AVIFTune.auto */,
+ },
+ autoOptimize: {
+ option: 'cqLevel',
+ min: 62,
+ max: 0,
+ },
+ },
+ oxipng: {
+ name: 'OxiPNG',
+ extension: 'png',
+ // eslint-disable-next-line no-control-regex
+ detectors: [/^\x89PNG\x0D\x0A\x1A\x0A/],
+ dec: async () => {
+ await pngEncDecInit()
+ return {
+ decode: (buffer: Buffer | Uint8Array) => {
+ const imageData = pngEncDec.decode(buffer)
+ pngEncDec.cleanup()
+ return imageData
+ },
+ }
+ },
+ enc: async () => {
+ await pngEncDecInit()
+ await oxipngInit()
+ return {
+ encode: (
+ buffer: Uint8ClampedArray | ArrayBuffer,
+ width: number,
+ height: number,
+ opts: { level: number }
+ ) => {
+ const simplePng = pngEncDec.encode(
+ new Uint8Array(buffer),
+ width,
+ height
+ )
+ const imageData = oxipng.optimise(simplePng, opts.level, false)
+ oxipng.cleanup()
+ return imageData
+ },
+ }
+ },
+ defaultEncoderOptions: {
+ level: 2,
+ },
+ autoOptimize: {
+ option: 'level',
+ min: 6,
+ max: 1,
+ },
+ },
+} as const
diff --git a/packages/integrations/image/src/vendor/squoosh/copy-wasm.ts b/packages/integrations/image/src/vendor/squoosh/copy-wasm.ts
new file mode 100644
index 000000000..1c742f3ea
--- /dev/null
+++ b/packages/integrations/image/src/vendor/squoosh/copy-wasm.ts
@@ -0,0 +1,24 @@
+import fs from 'node:fs/promises';
+import path from 'node:path';
+import { fileURLToPath } from 'node:url';
+
+export async function copyWasmFiles(dir: URL) {
+ const src = new URL('./', import.meta.url);
+ await copyDir(fileURLToPath(src), fileURLToPath(dir));
+}
+
+async function copyDir(src: string, dest: string) {
+ const itemNames = await fs.readdir(src);
+ await Promise.all(itemNames.map(async (srcName) => {
+ const srcPath = path.join(src, srcName);
+ const destPath = path.join(dest, srcName);
+ const s = await fs.stat(srcPath);
+ if (s.isFile() && /.wasm$/.test(srcPath)) {
+ await fs.mkdir(path.dirname(destPath), { recursive: true });
+ await fs.copyFile(srcPath, destPath);
+ }
+ else if (s.isDirectory()) {
+ await copyDir(srcPath, destPath);
+ }
+ }));
+}
diff --git a/packages/integrations/image/src/vendor/squoosh/emscripten-types.d.ts b/packages/integrations/image/src/vendor/squoosh/emscripten-types.d.ts
new file mode 100644
index 000000000..639787229
--- /dev/null
+++ b/packages/integrations/image/src/vendor/squoosh/emscripten-types.d.ts
@@ -0,0 +1,121 @@
+// These types roughly model the object that the JS files generated by Emscripten define. Copied from https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/emscripten/index.d.ts and turned into a type definition rather than a global to support our way of using Emscripten.
+declare namespace EmscriptenWasm {
+ type ModuleFactory = (
+ moduleOverrides?: ModuleOpts
+ ) => Promise
+
+ type EnvironmentType = 'WEB' | 'NODE' | 'SHELL' | 'WORKER'
+
+ // Options object for modularized Emscripten files. Shoe-horned by @surma.
+ // FIXME: This an incomplete definition!
+ interface ModuleOpts {
+ mainScriptUrlOrBlob?: string
+ noInitialRun?: boolean
+ locateFile?: (url: string) => string
+ onRuntimeInitialized?: () => void
+ }
+
+ interface Module {
+ print(str: string): void
+ printErr(str: string): void
+ arguments: string[]
+ environment: EnvironmentType
+ preInit: { (): void }[]
+ preRun: { (): void }[]
+ postRun: { (): void }[]
+ preinitializedWebGLContext: WebGLRenderingContext
+ noInitialRun: boolean
+ noExitRuntime: boolean
+ logReadFiles: boolean
+ filePackagePrefixURL: string
+ wasmBinary: ArrayBuffer
+
+ destroy(object: object): void
+ getPreloadedPackage(
+ remotePackageName: string,
+ remotePackageSize: number
+ ): ArrayBuffer
+ instantiateWasm(
+ imports: WebAssembly.Imports,
+ successCallback: (module: WebAssembly.Module) => void
+ ): WebAssembly.Exports
+ locateFile(url: string): string
+ onCustomMessage(event: MessageEvent): void
+
+ Runtime: any
+
+ ccall(
+ ident: string,
+ returnType: string | null,
+ argTypes: string[],
+ args: any[]
+ ): any
+ cwrap(ident: string, returnType: string | null, argTypes: string[]): any
+
+ setValue(ptr: number, value: any, type: string, noSafe?: boolean): void
+ getValue(ptr: number, type: string, noSafe?: boolean): number
+
+ ALLOC_NORMAL: number
+ ALLOC_STACK: number
+ ALLOC_STATIC: number
+ ALLOC_DYNAMIC: number
+ ALLOC_NONE: number
+
+ allocate(slab: any, types: string, allocator: number, ptr: number): number
+ allocate(slab: any, types: string[], allocator: number, ptr: number): number
+
+ Pointer_stringify(ptr: number, length?: number): string
+ UTF16ToString(ptr: number): string
+ stringToUTF16(str: string, outPtr: number): void
+ UTF32ToString(ptr: number): string
+ stringToUTF32(str: string, outPtr: number): void
+
+ // USE_TYPED_ARRAYS == 1
+ HEAP: Int32Array
+ IHEAP: Int32Array
+ FHEAP: Float64Array
+
+ // USE_TYPED_ARRAYS == 2
+ HEAP8: Int8Array
+ HEAP16: Int16Array
+ HEAP32: Int32Array
+ HEAPU8: Uint8Array
+ HEAPU16: Uint16Array
+ HEAPU32: Uint32Array
+ HEAPF32: Float32Array
+ HEAPF64: Float64Array
+
+ TOTAL_STACK: number
+ TOTAL_MEMORY: number
+ FAST_MEMORY: number
+
+ addOnPreRun(cb: () => any): void
+ addOnInit(cb: () => any): void
+ addOnPreMain(cb: () => any): void
+ addOnExit(cb: () => any): void
+ addOnPostRun(cb: () => any): void
+
+ // Tools
+ intArrayFromString(
+ stringy: string,
+ dontAddNull?: boolean,
+ length?: number
+ ): number[]
+ intArrayToString(array: number[]): string
+ writeStringToMemory(str: string, buffer: number, dontAddNull: boolean): void
+ writeArrayToMemory(array: number[], buffer: number): void
+ writeAsciiToMemory(str: string, buffer: number, dontAddNull: boolean): void
+
+ addRunDependency(id: any): void
+ removeRunDependency(id: any): void
+
+ preloadedImages: any
+ preloadedAudios: any
+
+ _malloc(size: number): number
+ _free(ptr: number): void
+
+ // Augmentations below by @surma.
+ onRuntimeInitialized: () => void | null
+ }
+}
diff --git a/packages/integrations/image/src/vendor/squoosh/emscripten-utils.ts b/packages/integrations/image/src/vendor/squoosh/emscripten-utils.ts
new file mode 100644
index 000000000..2e335fd2d
--- /dev/null
+++ b/packages/integrations/image/src/vendor/squoosh/emscripten-utils.ts
@@ -0,0 +1,31 @@
+//
+import { fileURLToPath } from 'node:url'
+
+export function pathify(path: string): string {
+ if (path.startsWith('file://')) {
+ path = fileURLToPath(path)
+ }
+ return path
+}
+
+export function instantiateEmscriptenWasm(
+ factory: EmscriptenWasm.ModuleFactory,
+ path: string,
+ workerJS = ''
+): Promise {
+ return factory({
+ locateFile(requestPath) {
+ // The glue code generated by emscripten uses the original
+ // file names of the worker file and the wasm binary.
+ // These will have changed in the bundling process and
+ // we need to inject them here.
+ if (requestPath.endsWith('.wasm')) return pathify(path)
+ if (requestPath.endsWith('.worker.js')) return pathify(workerJS)
+ return requestPath
+ },
+ })
+}
+
+export function dirname(url: string) {
+ return url.substring(0, url.lastIndexOf('/'))
+}
diff --git a/packages/integrations/image/src/vendor/squoosh/image-pool.ts b/packages/integrations/image/src/vendor/squoosh/image-pool.ts
new file mode 100644
index 000000000..b390c50b9
--- /dev/null
+++ b/packages/integrations/image/src/vendor/squoosh/image-pool.ts
@@ -0,0 +1,139 @@
+import { cpus } from 'os'
+import { isMainThread } from 'node:worker_threads';
+import WorkerPool from '../../utils/workerPool.js';
+import type { Operation } from './image.js';
+import * as impl from './impl.js';
+import execOnce from '../../utils/execOnce.js';
+import type { OutputFormat } from '../../loaders/index.js';
+
+const getWorker = execOnce(
+ () => {
+ return new WorkerPool(
+ // There will be at most 7 workers needed since each worker will take
+ // at least 1 operation type.
+ Math.max(1, Math.min(cpus().length - 1, 7)),
+ './node_modules/@astrojs/image/dist/vendor/squoosh/image-pool.js'
+ );
+ }
+)
+
+type DecodeParams = {
+ operation: 'decode',
+ buffer: Buffer
+};
+type ResizeParams = {
+ operation: 'resize',
+ imageData: ImageData,
+ height?: number,
+ width?: number
+};
+type RotateParams = {
+ operation: 'rotate',
+ imageData: ImageData,
+ numRotations: number
+};
+type EncodeAvifParams = {
+ operation: 'encodeavif',
+ imageData: ImageData,
+ quality: number
+}
+type EncodeJpegParams = {
+ operation: 'encodejpeg',
+ imageData: ImageData,
+ quality: number
+}
+type EncodePngParams = {
+ operation: 'encodepng',
+ imageData: ImageData
+}
+type EncodeWebpParams = {
+ operation: 'encodewebp',
+ imageData: ImageData,
+ quality: number
+}
+type JobMessage = DecodeParams | ResizeParams | RotateParams | EncodeAvifParams | EncodeJpegParams | EncodePngParams | EncodeWebpParams
+
+function handleJob(params: JobMessage) {
+ switch (params.operation) {
+ case 'decode':
+ return impl.decodeBuffer(params.buffer)
+ case 'resize':
+ return impl.resize({ image: params.imageData as any, width: params.width, height: params.height })
+ case 'rotate':
+ return impl.rotate(params.imageData as any, params.numRotations);
+ case 'encodeavif':
+ return impl.encodeAvif(params.imageData as any, { quality: params.quality })
+ case 'encodejpeg':
+ return impl.encodeJpeg(params.imageData as any, { quality: params.quality })
+ case 'encodepng':
+ return impl.encodePng(params.imageData as any)
+ case 'encodewebp':
+ return impl.encodeWebp(params.imageData as any, { quality: params.quality })
+ default:
+ throw Error(`Invalid job "${(params as any).operation}"`);
+ }
+}
+
+export async function processBuffer(
+ buffer: Buffer,
+ operations: Operation[],
+ encoding: OutputFormat,
+ quality: number
+): Promise {
+ // @ts-ignore
+ const worker = await getWorker()
+
+ let imageData = await worker.dispatchJob({
+ operation: 'decode',
+ buffer,
+ })
+ for (const operation of operations) {
+ if (operation.type === 'rotate') {
+ imageData = await worker.dispatchJob({
+ operation: 'rotate',
+ imageData,
+ numRotations: operation.numRotations
+ });
+ } else if (operation.type === 'resize') {
+ imageData = await worker.dispatchJob({
+ operation: 'resize',
+ imageData,
+ height: operation.height,
+ width: operation.width
+ })
+ }
+ }
+
+ switch (encoding) {
+ case 'avif':
+ return await worker.dispatchJob({
+ operation: 'encodeavif',
+ imageData,
+ quality: quality || 100
+ }) as Uint8Array;
+ case 'jpeg':
+ case 'jpg':
+ return await worker.dispatchJob({
+ operation: 'encodejpeg',
+ imageData,
+ quality: quality || 100,
+ }) as Uint8Array;
+ case 'png':
+ return await worker.dispatchJob({
+ operation: 'encodepng',
+ imageData,
+ }) as Uint8Array;
+ case 'webp':
+ return await worker.dispatchJob({
+ operation: 'encodewebp',
+ imageData,
+ quality: quality || 100,
+ }) as Uint8Array;
+ default:
+ throw Error(`Unsupported encoding format`)
+ }
+}
+
+if (!isMainThread) {
+ WorkerPool.useThisThreadAsWorker(handleJob);
+}
diff --git a/packages/integrations/image/src/vendor/squoosh/image.ts b/packages/integrations/image/src/vendor/squoosh/image.ts
new file mode 100644
index 000000000..2d9394822
--- /dev/null
+++ b/packages/integrations/image/src/vendor/squoosh/image.ts
@@ -0,0 +1,43 @@
+import * as impl from './impl.js';
+import type { OutputFormat } from '../../loaders/index.js';
+
+type RotateOperation = {
+ type: 'rotate'
+ numRotations: number
+}
+type ResizeOperation = {
+ type: 'resize'
+ width?: number
+ height?: number
+}
+export type Operation = RotateOperation | ResizeOperation
+
+export async function processBuffer(
+ buffer: Buffer,
+ operations: Operation[],
+ encoding: OutputFormat,
+ quality: number
+): Promise {
+ let imageData = await impl.decodeBuffer(buffer)
+ for (const operation of operations) {
+ if (operation.type === 'rotate') {
+ imageData = await impl.rotate(imageData, operation.numRotations);
+ } else if (operation.type === 'resize') {
+ imageData = await impl.resize({ image: imageData, width: operation.width, height: operation.height })
+ }
+ }
+
+ switch (encoding) {
+ case 'avif':
+ return await impl.encodeAvif(imageData, { quality: quality }) as Uint8Array;
+ case 'jpeg':
+ case 'jpg':
+ return await impl.encodeJpeg(imageData, { quality }) as Uint8Array;
+ case 'png':
+ return await impl.encodePng(imageData) as Uint8Array;
+ case 'webp':
+ return await impl.encodeWebp(imageData, { quality }) as Uint8Array;
+ default:
+ throw Error(`Unsupported encoding format`)
+ }
+}
diff --git a/packages/integrations/image/src/vendor/squoosh/image_data.ts b/packages/integrations/image/src/vendor/squoosh/image_data.ts
new file mode 100644
index 000000000..16936b60e
--- /dev/null
+++ b/packages/integrations/image/src/vendor/squoosh/image_data.ts
@@ -0,0 +1,33 @@
+export default class ImageData {
+ static from(input: ImageData): ImageData {
+ return new ImageData(input.data || input._data, input.width, input.height)
+ }
+
+ private _data: Buffer | Uint8Array | Uint8ClampedArray
+ width: number
+ height: number
+
+ get data(): Buffer {
+ if (Object.prototype.toString.call(this._data) === '[object Object]') {
+ return Buffer.from(Object.values(this._data))
+ }
+ if (
+ this._data instanceof Buffer ||
+ this._data instanceof Uint8Array ||
+ this._data instanceof Uint8ClampedArray
+ ) {
+ return Buffer.from(this._data)
+ }
+ throw new Error('invariant')
+ }
+
+ constructor(
+ data: Buffer | Uint8Array | Uint8ClampedArray,
+ width: number,
+ height: number
+ ) {
+ this._data = data
+ this.width = width
+ this.height = height
+ }
+}
diff --git a/packages/integrations/image/src/vendor/squoosh/impl.ts b/packages/integrations/image/src/vendor/squoosh/impl.ts
new file mode 100644
index 000000000..722336807
--- /dev/null
+++ b/packages/integrations/image/src/vendor/squoosh/impl.ts
@@ -0,0 +1,135 @@
+import { codecs as supportedFormats, preprocessors } from './codecs.js'
+import ImageData from './image_data.js'
+
+type EncoderKey = keyof typeof supportedFormats
+
+const DELAY_MS = 1000
+let _promise: Promise | undefined
+
+function delayOnce(ms: number): Promise {
+ if (!_promise) {
+ _promise = new Promise((resolve) => {
+ setTimeout(resolve, ms)
+ })
+ }
+ return _promise
+}
+
+function maybeDelay(): Promise {
+ const isAppleM1 = process.arch === 'arm64' && process.platform === 'darwin'
+ if (isAppleM1) {
+ return delayOnce(DELAY_MS)
+ }
+ return Promise.resolve()
+}
+
+export async function decodeBuffer(
+ _buffer: Buffer | Uint8Array
+): Promise {
+ const buffer = Buffer.from(_buffer)
+ const firstChunk = buffer.slice(0, 16)
+ const firstChunkString = Array.from(firstChunk)
+ .map((v) => String.fromCodePoint(v))
+ .join('')
+ const key = Object.entries(supportedFormats).find(([, { detectors }]) =>
+ detectors.some((detector) => detector.exec(firstChunkString))
+ )?.[0] as EncoderKey | undefined
+ if (!key) {
+ throw Error(`Buffer has an unsupported format`)
+ }
+ const encoder = supportedFormats[key]
+ const mod = await encoder.dec()
+ const rgba = mod.decode(new Uint8Array(buffer))
+ // @ts-ignore
+ return rgba
+}
+
+export async function rotate(
+ image: ImageData,
+ numRotations: number
+): Promise {
+ image = ImageData.from(image)
+
+ const m = await preprocessors['rotate'].instantiate()
+ return await m(image.data, image.width, image.height, { numRotations })
+}
+
+type ResizeOpts = { image: ImageData } & { width?: number; height?: number }
+
+export async function resize({ image, width, height }: ResizeOpts) {
+ image = ImageData.from(image)
+
+ const p = preprocessors['resize']
+ const m = await p.instantiate()
+ await maybeDelay()
+ return await m(image.data, image.width, image.height, {
+ ...p.defaultOptions,
+ width,
+ height,
+ })
+}
+
+export async function encodeJpeg(
+ image: ImageData,
+ { quality }: { quality: number }
+): Promise {
+ image = ImageData.from(image)
+
+ const e = supportedFormats['mozjpeg']
+ const m = await e.enc()
+ await maybeDelay()
+ const r = await m.encode(image.data, image.width, image.height, {
+ ...e.defaultEncoderOptions,
+ quality,
+ })
+ return r
+}
+
+export async function encodeWebp(
+ image: ImageData,
+ { quality }: { quality: number }
+): Promise {
+ image = ImageData.from(image)
+
+ const e = supportedFormats['webp']
+ const m = await e.enc()
+ await maybeDelay()
+ const r = await m.encode(image.data, image.width, image.height, {
+ ...e.defaultEncoderOptions,
+ quality,
+ })
+ return r
+}
+
+export async function encodeAvif(
+ image: ImageData,
+ { quality }: { quality: number }
+): Promise {
+ image = ImageData.from(image)
+
+ const e = supportedFormats['avif']
+ const m = await e.enc()
+ await maybeDelay()
+ const val = e.autoOptimize.min
+ const r = await m.encode(image.data, image.width, image.height, {
+ ...e.defaultEncoderOptions,
+ // Think of cqLevel as the "amount" of quantization (0 to 62),
+ // so a lower value yields higher quality (0 to 100).
+ cqLevel: quality === 0 ? val : Math.round(val - (quality / 100) * val),
+ })
+ return r
+}
+
+export async function encodePng(
+ image: ImageData
+): Promise {
+ image = ImageData.from(image)
+
+ const e = supportedFormats['oxipng']
+ const m = await e.enc()
+ await maybeDelay()
+ const r = await m.encode(image.data, image.width, image.height, {
+ ...e.defaultEncoderOptions,
+ })
+ return r
+}
diff --git a/packages/integrations/image/src/vendor/squoosh/mozjpeg/mozjpeg_enc.d.ts b/packages/integrations/image/src/vendor/squoosh/mozjpeg/mozjpeg_enc.d.ts
new file mode 100644
index 000000000..87b697a11
--- /dev/null
+++ b/packages/integrations/image/src/vendor/squoosh/mozjpeg/mozjpeg_enc.d.ts
@@ -0,0 +1,38 @@
+// eslint-disable-next-line no-shadow
+export const enum MozJpegColorSpace {
+ GRAYSCALE = 1,
+ RGB,
+ YCbCr,
+}
+
+export interface EncodeOptions {
+ quality: number
+ baseline: boolean
+ arithmetic: boolean
+ progressive: boolean
+ optimize_coding: boolean
+ smoothing: number
+ color_space: MozJpegColorSpace
+ quant_table: number
+ trellis_multipass: boolean
+ trellis_opt_zero: boolean
+ trellis_opt_table: boolean
+ trellis_loops: number
+ auto_subsample: boolean
+ chroma_subsample: number
+ separate_chroma_quality: boolean
+ chroma_quality: number
+}
+
+export interface MozJPEGModule extends EmscriptenWasm.Module {
+ encode(
+ data: BufferSource,
+ width: number,
+ height: number,
+ options: EncodeOptions
+ ): Uint8Array
+}
+
+declare var moduleFactory: EmscriptenWasm.ModuleFactory
+
+export default moduleFactory
diff --git a/packages/integrations/image/src/vendor/squoosh/mozjpeg/mozjpeg_node_dec.ts b/packages/integrations/image/src/vendor/squoosh/mozjpeg/mozjpeg_node_dec.ts
new file mode 100644
index 000000000..b95b293c2
--- /dev/null
+++ b/packages/integrations/image/src/vendor/squoosh/mozjpeg/mozjpeg_node_dec.ts
@@ -0,0 +1,1809 @@
+/* eslint-disable */
+// @ts-nocheck
+import { dirname } from '../emscripten-utils.js';
+import { createRequire } from 'module';
+const require = createRequire(import.meta.url);
+
+var Module = (function () {
+ return function (Module) {
+ Module = Module || {}
+
+ var Module = typeof Module !== 'undefined' ? Module : {}
+ var readyPromiseResolve, readyPromiseReject
+ Module['ready'] = new Promise(function (resolve, reject) {
+ readyPromiseResolve = resolve
+ readyPromiseReject = reject
+ })
+ var moduleOverrides = {}
+ var key
+ for (key in Module) {
+ if (Module.hasOwnProperty(key)) {
+ moduleOverrides[key] = Module[key]
+ }
+ }
+ var arguments_ = []
+ var thisProgram = './this.program'
+ var quit_ = function (status, toThrow) {
+ throw toThrow
+ }
+ var ENVIRONMENT_IS_WEB = false
+ var ENVIRONMENT_IS_WORKER = false
+ var ENVIRONMENT_IS_NODE = true
+ var scriptDirectory = ''
+ function locateFile(path) {
+ if (Module['locateFile']) {
+ return Module['locateFile'](path, scriptDirectory)
+ }
+ return scriptDirectory + path
+ }
+ var read_, readBinary
+ var nodeFS
+ var nodePath
+ if (ENVIRONMENT_IS_NODE) {
+ if (ENVIRONMENT_IS_WORKER) {
+ scriptDirectory = require('path').dirname(scriptDirectory) + '/'
+ } else {
+ scriptDirectory = dirname(import.meta.url) + '/'
+ }
+ read_ = function shell_read(filename, binary) {
+ if (!nodeFS) nodeFS = require('fs')
+ if (!nodePath) nodePath = require('path')
+ filename = nodePath['normalize'](filename)
+ return nodeFS['readFileSync'](filename, binary ? null : 'utf8')
+ }
+ readBinary = function readBinary(filename) {
+ var ret = read_(filename, true)
+ if (!ret.buffer) {
+ ret = new Uint8Array(ret)
+ }
+ assert(ret.buffer)
+ return ret
+ }
+ if (process['argv'].length > 1) {
+ thisProgram = process['argv'][1].replace(/\\/g, '/')
+ }
+ arguments_ = process['argv'].slice(2)
+ quit_ = function (status) {
+ process['exit'](status)
+ }
+ Module['inspect'] = function () {
+ return '[Emscripten Module object]'
+ }
+ } else {
+ }
+ var out = Module['print'] || console.log.bind(console)
+ var err = Module['printErr'] || console.warn.bind(console)
+ for (key in moduleOverrides) {
+ if (moduleOverrides.hasOwnProperty(key)) {
+ Module[key] = moduleOverrides[key]
+ }
+ }
+ moduleOverrides = null
+ if (Module['arguments']) arguments_ = Module['arguments']
+ if (Module['thisProgram']) thisProgram = Module['thisProgram']
+ if (Module['quit']) quit_ = Module['quit']
+ var tempRet0 = 0
+ var setTempRet0 = function (value) {
+ tempRet0 = value
+ }
+ var wasmBinary
+ if (Module['wasmBinary']) wasmBinary = Module['wasmBinary']
+ var noExitRuntime = Module['noExitRuntime'] || true
+ if (typeof WebAssembly !== 'object') {
+ abort('no native wasm support detected')
+ }
+ var wasmMemory
+ var ABORT = false
+ var EXITSTATUS
+ function assert(condition, text) {
+ if (!condition) {
+ abort('Assertion failed: ' + text)
+ }
+ }
+ var UTF8Decoder = new TextDecoder('utf8')
+ function UTF8ArrayToString(heap, idx, maxBytesToRead) {
+ var endIdx = idx + maxBytesToRead
+ var endPtr = idx
+ while (heap[endPtr] && !(endPtr >= endIdx)) ++endPtr
+ return UTF8Decoder.decode(
+ heap.subarray
+ ? heap.subarray(idx, endPtr)
+ : new Uint8Array(heap.slice(idx, endPtr))
+ )
+ }
+ function UTF8ToString(ptr, maxBytesToRead) {
+ if (!ptr) return ''
+ var maxPtr = ptr + maxBytesToRead
+ for (var end = ptr; !(end >= maxPtr) && HEAPU8[end]; ) ++end
+ return UTF8Decoder.decode(HEAPU8.subarray(ptr, end))
+ }
+ function stringToUTF8Array(str, heap, outIdx, maxBytesToWrite) {
+ if (!(maxBytesToWrite > 0)) return 0
+ var startIdx = outIdx
+ var endIdx = outIdx + maxBytesToWrite - 1
+ for (var i = 0; i < str.length; ++i) {
+ var u = str.charCodeAt(i)
+ if (u >= 55296 && u <= 57343) {
+ var u1 = str.charCodeAt(++i)
+ u = (65536 + ((u & 1023) << 10)) | (u1 & 1023)
+ }
+ if (u <= 127) {
+ if (outIdx >= endIdx) break
+ heap[outIdx++] = u
+ } else if (u <= 2047) {
+ if (outIdx + 1 >= endIdx) break
+ heap[outIdx++] = 192 | (u >> 6)
+ heap[outIdx++] = 128 | (u & 63)
+ } else if (u <= 65535) {
+ if (outIdx + 2 >= endIdx) break
+ heap[outIdx++] = 224 | (u >> 12)
+ heap[outIdx++] = 128 | ((u >> 6) & 63)
+ heap[outIdx++] = 128 | (u & 63)
+ } else {
+ if (outIdx + 3 >= endIdx) break
+ heap[outIdx++] = 240 | (u >> 18)
+ heap[outIdx++] = 128 | ((u >> 12) & 63)
+ heap[outIdx++] = 128 | ((u >> 6) & 63)
+ heap[outIdx++] = 128 | (u & 63)
+ }
+ }
+ heap[outIdx] = 0
+ return outIdx - startIdx
+ }
+ function stringToUTF8(str, outPtr, maxBytesToWrite) {
+ return stringToUTF8Array(str, HEAPU8, outPtr, maxBytesToWrite)
+ }
+ function lengthBytesUTF8(str) {
+ var len = 0
+ for (var i = 0; i < str.length; ++i) {
+ var u = str.charCodeAt(i)
+ if (u >= 55296 && u <= 57343)
+ u = (65536 + ((u & 1023) << 10)) | (str.charCodeAt(++i) & 1023)
+ if (u <= 127) ++len
+ else if (u <= 2047) len += 2
+ else if (u <= 65535) len += 3
+ else len += 4
+ }
+ return len
+ }
+ var UTF16Decoder = new TextDecoder('utf-16le')
+ function UTF16ToString(ptr, maxBytesToRead) {
+ var endPtr = ptr
+ var idx = endPtr >> 1
+ var maxIdx = idx + maxBytesToRead / 2
+ while (!(idx >= maxIdx) && HEAPU16[idx]) ++idx
+ endPtr = idx << 1
+ return UTF16Decoder.decode(HEAPU8.subarray(ptr, endPtr))
+ var str = ''
+ for (var i = 0; !(i >= maxBytesToRead / 2); ++i) {
+ var codeUnit = HEAP16[(ptr + i * 2) >> 1]
+ if (codeUnit == 0) break
+ str += String.fromCharCode(codeUnit)
+ }
+ return str
+ }
+ function stringToUTF16(str, outPtr, maxBytesToWrite) {
+ if (maxBytesToWrite === undefined) {
+ maxBytesToWrite = 2147483647
+ }
+ if (maxBytesToWrite < 2) return 0
+ maxBytesToWrite -= 2
+ var startPtr = outPtr
+ var numCharsToWrite =
+ maxBytesToWrite < str.length * 2 ? maxBytesToWrite / 2 : str.length
+ for (var i = 0; i < numCharsToWrite; ++i) {
+ var codeUnit = str.charCodeAt(i)
+ HEAP16[outPtr >> 1] = codeUnit
+ outPtr += 2
+ }
+ HEAP16[outPtr >> 1] = 0
+ return outPtr - startPtr
+ }
+ function lengthBytesUTF16(str) {
+ return str.length * 2
+ }
+ function UTF32ToString(ptr, maxBytesToRead) {
+ var i = 0
+ var str = ''
+ while (!(i >= maxBytesToRead / 4)) {
+ var utf32 = HEAP32[(ptr + i * 4) >> 2]
+ if (utf32 == 0) break
+ ++i
+ if (utf32 >= 65536) {
+ var ch = utf32 - 65536
+ str += String.fromCharCode(55296 | (ch >> 10), 56320 | (ch & 1023))
+ } else {
+ str += String.fromCharCode(utf32)
+ }
+ }
+ return str
+ }
+ function stringToUTF32(str, outPtr, maxBytesToWrite) {
+ if (maxBytesToWrite === undefined) {
+ maxBytesToWrite = 2147483647
+ }
+ if (maxBytesToWrite < 4) return 0
+ var startPtr = outPtr
+ var endPtr = startPtr + maxBytesToWrite - 4
+ for (var i = 0; i < str.length; ++i) {
+ var codeUnit = str.charCodeAt(i)
+ if (codeUnit >= 55296 && codeUnit <= 57343) {
+ var trailSurrogate = str.charCodeAt(++i)
+ codeUnit =
+ (65536 + ((codeUnit & 1023) << 10)) | (trailSurrogate & 1023)
+ }
+ HEAP32[outPtr >> 2] = codeUnit
+ outPtr += 4
+ if (outPtr + 4 > endPtr) break
+ }
+ HEAP32[outPtr >> 2] = 0
+ return outPtr - startPtr
+ }
+ function lengthBytesUTF32(str) {
+ var len = 0
+ for (var i = 0; i < str.length; ++i) {
+ var codeUnit = str.charCodeAt(i)
+ if (codeUnit >= 55296 && codeUnit <= 57343) ++i
+ len += 4
+ }
+ return len
+ }
+ function writeAsciiToMemory(str, buffer, dontAddNull) {
+ for (var i = 0; i < str.length; ++i) {
+ HEAP8[buffer++ >> 0] = str.charCodeAt(i)
+ }
+ if (!dontAddNull) HEAP8[buffer >> 0] = 0
+ }
+ function alignUp(x, multiple) {
+ if (x % multiple > 0) {
+ x += multiple - (x % multiple)
+ }
+ return x
+ }
+ var buffer,
+ HEAP8,
+ HEAPU8,
+ HEAP16,
+ HEAPU16,
+ HEAP32,
+ HEAPU32,
+ HEAPF32,
+ HEAPF64
+ function updateGlobalBufferAndViews(buf) {
+ buffer = buf
+ Module['HEAP8'] = HEAP8 = new Int8Array(buf)
+ Module['HEAP16'] = HEAP16 = new Int16Array(buf)
+ Module['HEAP32'] = HEAP32 = new Int32Array(buf)
+ Module['HEAPU8'] = HEAPU8 = new Uint8Array(buf)
+ Module['HEAPU16'] = HEAPU16 = new Uint16Array(buf)
+ Module['HEAPU32'] = HEAPU32 = new Uint32Array(buf)
+ Module['HEAPF32'] = HEAPF32 = new Float32Array(buf)
+ Module['HEAPF64'] = HEAPF64 = new Float64Array(buf)
+ }
+ var INITIAL_MEMORY = Module['INITIAL_MEMORY'] || 16777216
+ var wasmTable
+ var __ATPRERUN__ = []
+ var __ATINIT__ = []
+ var __ATPOSTRUN__ = []
+ var runtimeInitialized = false
+ var runtimeExited = false
+ function preRun() {
+ if (Module['preRun']) {
+ if (typeof Module['preRun'] == 'function')
+ Module['preRun'] = [Module['preRun']]
+ while (Module['preRun'].length) {
+ addOnPreRun(Module['preRun'].shift())
+ }
+ }
+ callRuntimeCallbacks(__ATPRERUN__)
+ }
+ function initRuntime() {
+ runtimeInitialized = true
+ callRuntimeCallbacks(__ATINIT__)
+ }
+ function exitRuntime() {
+ runtimeExited = true
+ }
+ function postRun() {
+ if (Module['postRun']) {
+ if (typeof Module['postRun'] == 'function')
+ Module['postRun'] = [Module['postRun']]
+ while (Module['postRun'].length) {
+ addOnPostRun(Module['postRun'].shift())
+ }
+ }
+ callRuntimeCallbacks(__ATPOSTRUN__)
+ }
+ function addOnPreRun(cb) {
+ __ATPRERUN__.unshift(cb)
+ }
+ function addOnInit(cb) {
+ __ATINIT__.unshift(cb)
+ }
+ function addOnPostRun(cb) {
+ __ATPOSTRUN__.unshift(cb)
+ }
+ var runDependencies = 0
+ var runDependencyWatcher = null
+ var dependenciesFulfilled = null
+ function addRunDependency(id) {
+ runDependencies++
+ if (Module['monitorRunDependencies']) {
+ Module['monitorRunDependencies'](runDependencies)
+ }
+ }
+ function removeRunDependency(id) {
+ runDependencies--
+ if (Module['monitorRunDependencies']) {
+ Module['monitorRunDependencies'](runDependencies)
+ }
+ if (runDependencies == 0) {
+ if (runDependencyWatcher !== null) {
+ clearInterval(runDependencyWatcher)
+ runDependencyWatcher = null
+ }
+ if (dependenciesFulfilled) {
+ var callback = dependenciesFulfilled
+ dependenciesFulfilled = null
+ callback()
+ }
+ }
+ }
+ Module['preloadedImages'] = {}
+ Module['preloadedAudios'] = {}
+ function abort(what) {
+ if (Module['onAbort']) {
+ Module['onAbort'](what)
+ }
+ what += ''
+ err(what)
+ ABORT = true
+ EXITSTATUS = 1
+ what = 'abort(' + what + '). Build with -s ASSERTIONS=1 for more info.'
+ var e = new WebAssembly.RuntimeError(what)
+ readyPromiseReject(e)
+ throw e
+ }
+ var dataURIPrefix = 'data:application/octet-stream;base64,'
+ function isDataURI(filename) {
+ return filename.startsWith(dataURIPrefix)
+ }
+ if (Module['locateFile']) {
+ var wasmBinaryFile = 'mozjpeg_node_dec.wasm'
+ if (!isDataURI(wasmBinaryFile)) {
+ wasmBinaryFile = locateFile(wasmBinaryFile)
+ }
+ } else {
+ throw new Error('invariant')
+ }
+ function getBinary(file) {
+ try {
+ if (file == wasmBinaryFile && wasmBinary) {
+ return new Uint8Array(wasmBinary)
+ }
+ if (readBinary) {
+ return readBinary(file)
+ } else {
+ throw 'both async and sync fetching of the wasm failed'
+ }
+ } catch (err) {
+ abort(err)
+ }
+ }
+ function getBinaryPromise() {
+ if (!wasmBinary && (ENVIRONMENT_IS_WEB || ENVIRONMENT_IS_WORKER)) {
+ if (typeof fetch === 'function') {
+ return fetch(wasmBinaryFile, { credentials: 'same-origin' })
+ .then(function (response) {
+ if (!response['ok']) {
+ throw (
+ "failed to load wasm binary file at '" + wasmBinaryFile + "'"
+ )
+ }
+ return response['arrayBuffer']()
+ })
+ .catch(function () {
+ return getBinary(wasmBinaryFile)
+ })
+ }
+ }
+ return Promise.resolve().then(function () {
+ return getBinary(wasmBinaryFile)
+ })
+ }
+ function createWasm() {
+ var info = { a: asmLibraryArg }
+ function receiveInstance(instance, module) {
+ var exports = instance.exports
+ Module['asm'] = exports
+ wasmMemory = Module['asm']['z']
+ updateGlobalBufferAndViews(wasmMemory.buffer)
+ wasmTable = Module['asm']['F']
+ addOnInit(Module['asm']['A'])
+ removeRunDependency('wasm-instantiate')
+ }
+ addRunDependency('wasm-instantiate')
+ function receiveInstantiationResult(result) {
+ receiveInstance(result['instance'])
+ }
+ function instantiateArrayBuffer(receiver) {
+ return getBinaryPromise()
+ .then(function (binary) {
+ var result = WebAssembly.instantiate(binary, info)
+ return result
+ })
+ .then(receiver, function (reason) {
+ err('failed to asynchronously prepare wasm: ' + reason)
+ abort(reason)
+ })
+ }
+ function instantiateAsync() {
+ if (
+ !wasmBinary &&
+ typeof WebAssembly.instantiateStreaming === 'function' &&
+ !isDataURI(wasmBinaryFile) &&
+ typeof fetch === 'function'
+ ) {
+ return fetch(wasmBinaryFile, { credentials: 'same-origin' }).then(
+ function (response) {
+ var result = WebAssembly.instantiateStreaming(response, info)
+ return result.then(receiveInstantiationResult, function (reason) {
+ err('wasm streaming compile failed: ' + reason)
+ err('falling back to ArrayBuffer instantiation')
+ return instantiateArrayBuffer(receiveInstantiationResult)
+ })
+ }
+ )
+ } else {
+ return instantiateArrayBuffer(receiveInstantiationResult)
+ }
+ }
+ if (Module['instantiateWasm']) {
+ try {
+ var exports = Module['instantiateWasm'](info, receiveInstance)
+ return exports
+ } catch (e) {
+ err('Module.instantiateWasm callback failed with error: ' + e)
+ return false
+ }
+ }
+ instantiateAsync().catch(readyPromiseReject)
+ return {}
+ }
+ function callRuntimeCallbacks(callbacks) {
+ while (callbacks.length > 0) {
+ var callback = callbacks.shift()
+ if (typeof callback == 'function') {
+ callback(Module)
+ continue
+ }
+ var func = callback.func
+ if (typeof func === 'number') {
+ if (callback.arg === undefined) {
+ wasmTable.get(func)()
+ } else {
+ wasmTable.get(func)(callback.arg)
+ }
+ } else {
+ func(callback.arg === undefined ? null : callback.arg)
+ }
+ }
+ }
+ var runtimeKeepaliveCounter = 0
+ function keepRuntimeAlive() {
+ return noExitRuntime || runtimeKeepaliveCounter > 0
+ }
+ function _atexit(func, arg) {}
+ function ___cxa_thread_atexit(a0, a1) {
+ return _atexit(a0, a1)
+ }
+ function __embind_register_bigint(
+ primitiveType,
+ name,
+ size,
+ minRange,
+ maxRange
+ ) {}
+ function getShiftFromSize(size) {
+ switch (size) {
+ case 1:
+ return 0
+ case 2:
+ return 1
+ case 4:
+ return 2
+ case 8:
+ return 3
+ default:
+ throw new TypeError('Unknown type size: ' + size)
+ }
+ }
+ function embind_init_charCodes() {
+ var codes = new Array(256)
+ for (var i = 0; i < 256; ++i) {
+ codes[i] = String.fromCharCode(i)
+ }
+ embind_charCodes = codes
+ }
+ var embind_charCodes = undefined
+ function readLatin1String(ptr) {
+ var ret = ''
+ var c = ptr
+ while (HEAPU8[c]) {
+ ret += embind_charCodes[HEAPU8[c++]]
+ }
+ return ret
+ }
+ var awaitingDependencies = {}
+ var registeredTypes = {}
+ var typeDependencies = {}
+ var char_0 = 48
+ var char_9 = 57
+ function makeLegalFunctionName(name) {
+ if (undefined === name) {
+ return '_unknown'
+ }
+ name = name.replace(/[^a-zA-Z0-9_]/g, '$')
+ var f = name.charCodeAt(0)
+ if (f >= char_0 && f <= char_9) {
+ return '_' + name
+ } else {
+ return name
+ }
+ }
+ function createNamedFunction(name, body) {
+ name = makeLegalFunctionName(name)
+ return new Function(
+ 'body',
+ 'return function ' +
+ name +
+ '() {\n' +
+ ' "use strict";' +
+ ' return body.apply(this, arguments);\n' +
+ '};\n'
+ )(body)
+ }
+ function extendError(baseErrorType, errorName) {
+ var errorClass = createNamedFunction(errorName, function (message) {
+ this.name = errorName
+ this.message = message
+ var stack = new Error(message).stack
+ if (stack !== undefined) {
+ this.stack =
+ this.toString() + '\n' + stack.replace(/^Error(:[^\n]*)?\n/, '')
+ }
+ })
+ errorClass.prototype = Object.create(baseErrorType.prototype)
+ errorClass.prototype.constructor = errorClass
+ errorClass.prototype.toString = function () {
+ if (this.message === undefined) {
+ return this.name
+ } else {
+ return this.name + ': ' + this.message
+ }
+ }
+ return errorClass
+ }
+ var BindingError = undefined
+ function throwBindingError(message) {
+ throw new BindingError(message)
+ }
+ var InternalError = undefined
+ function throwInternalError(message) {
+ throw new InternalError(message)
+ }
+ function whenDependentTypesAreResolved(
+ myTypes,
+ dependentTypes,
+ getTypeConverters
+ ) {
+ myTypes.forEach(function (type) {
+ typeDependencies[type] = dependentTypes
+ })
+ function onComplete(typeConverters) {
+ var myTypeConverters = getTypeConverters(typeConverters)
+ if (myTypeConverters.length !== myTypes.length) {
+ throwInternalError('Mismatched type converter count')
+ }
+ for (var i = 0; i < myTypes.length; ++i) {
+ registerType(myTypes[i], myTypeConverters[i])
+ }
+ }
+ var typeConverters = new Array(dependentTypes.length)
+ var unregisteredTypes = []
+ var registered = 0
+ dependentTypes.forEach(function (dt, i) {
+ if (registeredTypes.hasOwnProperty(dt)) {
+ typeConverters[i] = registeredTypes[dt]
+ } else {
+ unregisteredTypes.push(dt)
+ if (!awaitingDependencies.hasOwnProperty(dt)) {
+ awaitingDependencies[dt] = []
+ }
+ awaitingDependencies[dt].push(function () {
+ typeConverters[i] = registeredTypes[dt]
+ ++registered
+ if (registered === unregisteredTypes.length) {
+ onComplete(typeConverters)
+ }
+ })
+ }
+ })
+ if (0 === unregisteredTypes.length) {
+ onComplete(typeConverters)
+ }
+ }
+ function registerType(rawType, registeredInstance, options) {
+ options = options || {}
+ if (!('argPackAdvance' in registeredInstance)) {
+ throw new TypeError(
+ 'registerType registeredInstance requires argPackAdvance'
+ )
+ }
+ var name = registeredInstance.name
+ if (!rawType) {
+ throwBindingError(
+ 'type "' + name + '" must have a positive integer typeid pointer'
+ )
+ }
+ if (registeredTypes.hasOwnProperty(rawType)) {
+ if (options.ignoreDuplicateRegistrations) {
+ return
+ } else {
+ throwBindingError("Cannot register type '" + name + "' twice")
+ }
+ }
+ registeredTypes[rawType] = registeredInstance
+ delete typeDependencies[rawType]
+ if (awaitingDependencies.hasOwnProperty(rawType)) {
+ var callbacks = awaitingDependencies[rawType]
+ delete awaitingDependencies[rawType]
+ callbacks.forEach(function (cb) {
+ cb()
+ })
+ }
+ }
+ function __embind_register_bool(
+ rawType,
+ name,
+ size,
+ trueValue,
+ falseValue
+ ) {
+ var shift = getShiftFromSize(size)
+ name = readLatin1String(name)
+ registerType(rawType, {
+ name: name,
+ fromWireType: function (wt) {
+ return !!wt
+ },
+ toWireType: function (destructors, o) {
+ return o ? trueValue : falseValue
+ },
+ argPackAdvance: 8,
+ readValueFromPointer: function (pointer) {
+ var heap
+ if (size === 1) {
+ heap = HEAP8
+ } else if (size === 2) {
+ heap = HEAP16
+ } else if (size === 4) {
+ heap = HEAP32
+ } else {
+ throw new TypeError('Unknown boolean type size: ' + name)
+ }
+ return this['fromWireType'](heap[pointer >> shift])
+ },
+ destructorFunction: null,
+ })
+ }
+ var emval_free_list = []
+ var emval_handle_array = [
+ {},
+ { value: undefined },
+ { value: null },
+ { value: true },
+ { value: false },
+ ]
+ function __emval_decref(handle) {
+ if (handle > 4 && 0 === --emval_handle_array[handle].refcount) {
+ emval_handle_array[handle] = undefined
+ emval_free_list.push(handle)
+ }
+ }
+ function count_emval_handles() {
+ var count = 0
+ for (var i = 5; i < emval_handle_array.length; ++i) {
+ if (emval_handle_array[i] !== undefined) {
+ ++count
+ }
+ }
+ return count
+ }
+ function get_first_emval() {
+ for (var i = 5; i < emval_handle_array.length; ++i) {
+ if (emval_handle_array[i] !== undefined) {
+ return emval_handle_array[i]
+ }
+ }
+ return null
+ }
+ function init_emval() {
+ Module['count_emval_handles'] = count_emval_handles
+ Module['get_first_emval'] = get_first_emval
+ }
+ function __emval_register(value) {
+ switch (value) {
+ case undefined: {
+ return 1
+ }
+ case null: {
+ return 2
+ }
+ case true: {
+ return 3
+ }
+ case false: {
+ return 4
+ }
+ default: {
+ var handle = emval_free_list.length
+ ? emval_free_list.pop()
+ : emval_handle_array.length
+ emval_handle_array[handle] = { refcount: 1, value: value }
+ return handle
+ }
+ }
+ }
+ function simpleReadValueFromPointer(pointer) {
+ return this['fromWireType'](HEAPU32[pointer >> 2])
+ }
+ function __embind_register_emval(rawType, name) {
+ name = readLatin1String(name)
+ registerType(rawType, {
+ name: name,
+ fromWireType: function (handle) {
+ var rv = emval_handle_array[handle].value
+ __emval_decref(handle)
+ return rv
+ },
+ toWireType: function (destructors, value) {
+ return __emval_register(value)
+ },
+ argPackAdvance: 8,
+ readValueFromPointer: simpleReadValueFromPointer,
+ destructorFunction: null,
+ })
+ }
+ function _embind_repr(v) {
+ if (v === null) {
+ return 'null'
+ }
+ var t = typeof v
+ if (t === 'object' || t === 'array' || t === 'function') {
+ return v.toString()
+ } else {
+ return '' + v
+ }
+ }
+ function floatReadValueFromPointer(name, shift) {
+ switch (shift) {
+ case 2:
+ return function (pointer) {
+ return this['fromWireType'](HEAPF32[pointer >> 2])
+ }
+ case 3:
+ return function (pointer) {
+ return this['fromWireType'](HEAPF64[pointer >> 3])
+ }
+ default:
+ throw new TypeError('Unknown float type: ' + name)
+ }
+ }
+ function __embind_register_float(rawType, name, size) {
+ var shift = getShiftFromSize(size)
+ name = readLatin1String(name)
+ registerType(rawType, {
+ name: name,
+ fromWireType: function (value) {
+ return value
+ },
+ toWireType: function (destructors, value) {
+ if (typeof value !== 'number' && typeof value !== 'boolean') {
+ throw new TypeError(
+ 'Cannot convert "' + _embind_repr(value) + '" to ' + this.name
+ )
+ }
+ return value
+ },
+ argPackAdvance: 8,
+ readValueFromPointer: floatReadValueFromPointer(name, shift),
+ destructorFunction: null,
+ })
+ }
+ function new_(constructor, argumentList) {
+ if (!(constructor instanceof Function)) {
+ throw new TypeError(
+ 'new_ called with constructor type ' +
+ typeof constructor +
+ ' which is not a function'
+ )
+ }
+ var dummy = createNamedFunction(
+ constructor.name || 'unknownFunctionName',
+ function () {}
+ )
+ dummy.prototype = constructor.prototype
+ var obj = new dummy()
+ var r = constructor.apply(obj, argumentList)
+ return r instanceof Object ? r : obj
+ }
+ function runDestructors(destructors) {
+ while (destructors.length) {
+ var ptr = destructors.pop()
+ var del = destructors.pop()
+ del(ptr)
+ }
+ }
+ function craftInvokerFunction(
+ humanName,
+ argTypes,
+ classType,
+ cppInvokerFunc,
+ cppTargetFunc
+ ) {
+ var argCount = argTypes.length
+ if (argCount < 2) {
+ throwBindingError(
+ "argTypes array size mismatch! Must at least get return value and 'this' types!"
+ )
+ }
+ var isClassMethodFunc = argTypes[1] !== null && classType !== null
+ var needsDestructorStack = false
+ for (var i = 1; i < argTypes.length; ++i) {
+ if (
+ argTypes[i] !== null &&
+ argTypes[i].destructorFunction === undefined
+ ) {
+ needsDestructorStack = true
+ break
+ }
+ }
+ var returns = argTypes[0].name !== 'void'
+ var argsList = ''
+ var argsListWired = ''
+ for (var i = 0; i < argCount - 2; ++i) {
+ argsList += (i !== 0 ? ', ' : '') + 'arg' + i
+ argsListWired += (i !== 0 ? ', ' : '') + 'arg' + i + 'Wired'
+ }
+ var invokerFnBody =
+ 'return function ' +
+ makeLegalFunctionName(humanName) +
+ '(' +
+ argsList +
+ ') {\n' +
+ 'if (arguments.length !== ' +
+ (argCount - 2) +
+ ') {\n' +
+ "throwBindingError('function " +
+ humanName +
+ " called with ' + arguments.length + ' arguments, expected " +
+ (argCount - 2) +
+ " args!');\n" +
+ '}\n'
+ if (needsDestructorStack) {
+ invokerFnBody += 'var destructors = [];\n'
+ }
+ var dtorStack = needsDestructorStack ? 'destructors' : 'null'
+ var args1 = [
+ 'throwBindingError',
+ 'invoker',
+ 'fn',
+ 'runDestructors',
+ 'retType',
+ 'classParam',
+ ]
+ var args2 = [
+ throwBindingError,
+ cppInvokerFunc,
+ cppTargetFunc,
+ runDestructors,
+ argTypes[0],
+ argTypes[1],
+ ]
+ if (isClassMethodFunc) {
+ invokerFnBody +=
+ 'var thisWired = classParam.toWireType(' + dtorStack + ', this);\n'
+ }
+ for (var i = 0; i < argCount - 2; ++i) {
+ invokerFnBody +=
+ 'var arg' +
+ i +
+ 'Wired = argType' +
+ i +
+ '.toWireType(' +
+ dtorStack +
+ ', arg' +
+ i +
+ '); // ' +
+ argTypes[i + 2].name +
+ '\n'
+ args1.push('argType' + i)
+ args2.push(argTypes[i + 2])
+ }
+ if (isClassMethodFunc) {
+ argsListWired =
+ 'thisWired' + (argsListWired.length > 0 ? ', ' : '') + argsListWired
+ }
+ invokerFnBody +=
+ (returns ? 'var rv = ' : '') +
+ 'invoker(fn' +
+ (argsListWired.length > 0 ? ', ' : '') +
+ argsListWired +
+ ');\n'
+ if (needsDestructorStack) {
+ invokerFnBody += 'runDestructors(destructors);\n'
+ } else {
+ for (var i = isClassMethodFunc ? 1 : 2; i < argTypes.length; ++i) {
+ var paramName = i === 1 ? 'thisWired' : 'arg' + (i - 2) + 'Wired'
+ if (argTypes[i].destructorFunction !== null) {
+ invokerFnBody +=
+ paramName +
+ '_dtor(' +
+ paramName +
+ '); // ' +
+ argTypes[i].name +
+ '\n'
+ args1.push(paramName + '_dtor')
+ args2.push(argTypes[i].destructorFunction)
+ }
+ }
+ }
+ if (returns) {
+ invokerFnBody +=
+ 'var ret = retType.fromWireType(rv);\n' + 'return ret;\n'
+ } else {
+ }
+ invokerFnBody += '}\n'
+ args1.push(invokerFnBody)
+ var invokerFunction = new_(Function, args1).apply(null, args2)
+ return invokerFunction
+ }
+ function ensureOverloadTable(proto, methodName, humanName) {
+ if (undefined === proto[methodName].overloadTable) {
+ var prevFunc = proto[methodName]
+ proto[methodName] = function () {
+ if (
+ !proto[methodName].overloadTable.hasOwnProperty(arguments.length)
+ ) {
+ throwBindingError(
+ "Function '" +
+ humanName +
+ "' called with an invalid number of arguments (" +
+ arguments.length +
+ ') - expects one of (' +
+ proto[methodName].overloadTable +
+ ')!'
+ )
+ }
+ return proto[methodName].overloadTable[arguments.length].apply(
+ this,
+ arguments
+ )
+ }
+ proto[methodName].overloadTable = []
+ proto[methodName].overloadTable[prevFunc.argCount] = prevFunc
+ }
+ }
+ function exposePublicSymbol(name, value, numArguments) {
+ if (Module.hasOwnProperty(name)) {
+ if (
+ undefined === numArguments ||
+ (undefined !== Module[name].overloadTable &&
+ undefined !== Module[name].overloadTable[numArguments])
+ ) {
+ throwBindingError("Cannot register public name '" + name + "' twice")
+ }
+ ensureOverloadTable(Module, name, name)
+ if (Module.hasOwnProperty(numArguments)) {
+ throwBindingError(
+ 'Cannot register multiple overloads of a function with the same number of arguments (' +
+ numArguments +
+ ')!'
+ )
+ }
+ Module[name].overloadTable[numArguments] = value
+ } else {
+ Module[name] = value
+ if (undefined !== numArguments) {
+ Module[name].numArguments = numArguments
+ }
+ }
+ }
+ function heap32VectorToArray(count, firstElement) {
+ var array = []
+ for (var i = 0; i < count; i++) {
+ array.push(HEAP32[(firstElement >> 2) + i])
+ }
+ return array
+ }
+ function replacePublicSymbol(name, value, numArguments) {
+ if (!Module.hasOwnProperty(name)) {
+ throwInternalError('Replacing nonexistant public symbol')
+ }
+ if (
+ undefined !== Module[name].overloadTable &&
+ undefined !== numArguments
+ ) {
+ Module[name].overloadTable[numArguments] = value
+ } else {
+ Module[name] = value
+ Module[name].argCount = numArguments
+ }
+ }
+ function dynCallLegacy(sig, ptr, args) {
+ var f = Module['dynCall_' + sig]
+ return args && args.length
+ ? f.apply(null, [ptr].concat(args))
+ : f.call(null, ptr)
+ }
+ function dynCall(sig, ptr, args) {
+ if (sig.includes('j')) {
+ return dynCallLegacy(sig, ptr, args)
+ }
+ return wasmTable.get(ptr).apply(null, args)
+ }
+ function getDynCaller(sig, ptr) {
+ var argCache = []
+ return function () {
+ argCache.length = arguments.length
+ for (var i = 0; i < arguments.length; i++) {
+ argCache[i] = arguments[i]
+ }
+ return dynCall(sig, ptr, argCache)
+ }
+ }
+ function embind__requireFunction(signature, rawFunction) {
+ signature = readLatin1String(signature)
+ function makeDynCaller() {
+ if (signature.includes('j')) {
+ return getDynCaller(signature, rawFunction)
+ }
+ return wasmTable.get(rawFunction)
+ }
+ var fp = makeDynCaller()
+ if (typeof fp !== 'function') {
+ throwBindingError(
+ 'unknown function pointer with signature ' +
+ signature +
+ ': ' +
+ rawFunction
+ )
+ }
+ return fp
+ }
+ var UnboundTypeError = undefined
+ function getTypeName(type) {
+ var ptr = ___getTypeName(type)
+ var rv = readLatin1String(ptr)
+ _free(ptr)
+ return rv
+ }
+ function throwUnboundTypeError(message, types) {
+ var unboundTypes = []
+ var seen = {}
+ function visit(type) {
+ if (seen[type]) {
+ return
+ }
+ if (registeredTypes[type]) {
+ return
+ }
+ if (typeDependencies[type]) {
+ typeDependencies[type].forEach(visit)
+ return
+ }
+ unboundTypes.push(type)
+ seen[type] = true
+ }
+ types.forEach(visit)
+ throw new UnboundTypeError(
+ message + ': ' + unboundTypes.map(getTypeName).join([', '])
+ )
+ }
+ function __embind_register_function(
+ name,
+ argCount,
+ rawArgTypesAddr,
+ signature,
+ rawInvoker,
+ fn
+ ) {
+ var argTypes = heap32VectorToArray(argCount, rawArgTypesAddr)
+ name = readLatin1String(name)
+ rawInvoker = embind__requireFunction(signature, rawInvoker)
+ exposePublicSymbol(
+ name,
+ function () {
+ throwUnboundTypeError(
+ 'Cannot call ' + name + ' due to unbound types',
+ argTypes
+ )
+ },
+ argCount - 1
+ )
+ whenDependentTypesAreResolved([], argTypes, function (argTypes) {
+ var invokerArgsArray = [argTypes[0], null].concat(argTypes.slice(1))
+ replacePublicSymbol(
+ name,
+ craftInvokerFunction(name, invokerArgsArray, null, rawInvoker, fn),
+ argCount - 1
+ )
+ return []
+ })
+ }
+ function integerReadValueFromPointer(name, shift, signed) {
+ switch (shift) {
+ case 0:
+ return signed
+ ? function readS8FromPointer(pointer) {
+ return HEAP8[pointer]
+ }
+ : function readU8FromPointer(pointer) {
+ return HEAPU8[pointer]
+ }
+ case 1:
+ return signed
+ ? function readS16FromPointer(pointer) {
+ return HEAP16[pointer >> 1]
+ }
+ : function readU16FromPointer(pointer) {
+ return HEAPU16[pointer >> 1]
+ }
+ case 2:
+ return signed
+ ? function readS32FromPointer(pointer) {
+ return HEAP32[pointer >> 2]
+ }
+ : function readU32FromPointer(pointer) {
+ return HEAPU32[pointer >> 2]
+ }
+ default:
+ throw new TypeError('Unknown integer type: ' + name)
+ }
+ }
+ function __embind_register_integer(
+ primitiveType,
+ name,
+ size,
+ minRange,
+ maxRange
+ ) {
+ name = readLatin1String(name)
+ if (maxRange === -1) {
+ maxRange = 4294967295
+ }
+ var shift = getShiftFromSize(size)
+ var fromWireType = function (value) {
+ return value
+ }
+ if (minRange === 0) {
+ var bitshift = 32 - 8 * size
+ fromWireType = function (value) {
+ return (value << bitshift) >>> bitshift
+ }
+ }
+ var isUnsignedType = name.includes('unsigned')
+ registerType(primitiveType, {
+ name: name,
+ fromWireType: fromWireType,
+ toWireType: function (destructors, value) {
+ if (typeof value !== 'number' && typeof value !== 'boolean') {
+ throw new TypeError(
+ 'Cannot convert "' + _embind_repr(value) + '" to ' + this.name
+ )
+ }
+ if (value < minRange || value > maxRange) {
+ throw new TypeError(
+ 'Passing a number "' +
+ _embind_repr(value) +
+ '" from JS side to C/C++ side to an argument of type "' +
+ name +
+ '", which is outside the valid range [' +
+ minRange +
+ ', ' +
+ maxRange +
+ ']!'
+ )
+ }
+ return isUnsignedType ? value >>> 0 : value | 0
+ },
+ argPackAdvance: 8,
+ readValueFromPointer: integerReadValueFromPointer(
+ name,
+ shift,
+ minRange !== 0
+ ),
+ destructorFunction: null,
+ })
+ }
+ function __embind_register_memory_view(rawType, dataTypeIndex, name) {
+ var typeMapping = [
+ Int8Array,
+ Uint8Array,
+ Int16Array,
+ Uint16Array,
+ Int32Array,
+ Uint32Array,
+ Float32Array,
+ Float64Array,
+ ]
+ var TA = typeMapping[dataTypeIndex]
+ function decodeMemoryView(handle) {
+ handle = handle >> 2
+ var heap = HEAPU32
+ var size = heap[handle]
+ var data = heap[handle + 1]
+ return new TA(buffer, data, size)
+ }
+ name = readLatin1String(name)
+ registerType(
+ rawType,
+ {
+ name: name,
+ fromWireType: decodeMemoryView,
+ argPackAdvance: 8,
+ readValueFromPointer: decodeMemoryView,
+ },
+ { ignoreDuplicateRegistrations: true }
+ )
+ }
+ function __embind_register_std_string(rawType, name) {
+ name = readLatin1String(name)
+ var stdStringIsUTF8 = name === 'std::string'
+ registerType(rawType, {
+ name: name,
+ fromWireType: function (value) {
+ var length = HEAPU32[value >> 2]
+ var str
+ if (stdStringIsUTF8) {
+ var decodeStartPtr = value + 4
+ for (var i = 0; i <= length; ++i) {
+ var currentBytePtr = value + 4 + i
+ if (i == length || HEAPU8[currentBytePtr] == 0) {
+ var maxRead = currentBytePtr - decodeStartPtr
+ var stringSegment = UTF8ToString(decodeStartPtr, maxRead)
+ if (str === undefined) {
+ str = stringSegment
+ } else {
+ str += String.fromCharCode(0)
+ str += stringSegment
+ }
+ decodeStartPtr = currentBytePtr + 1
+ }
+ }
+ } else {
+ var a = new Array(length)
+ for (var i = 0; i < length; ++i) {
+ a[i] = String.fromCharCode(HEAPU8[value + 4 + i])
+ }
+ str = a.join('')
+ }
+ _free(value)
+ return str
+ },
+ toWireType: function (destructors, value) {
+ if (value instanceof ArrayBuffer) {
+ value = new Uint8Array(value)
+ }
+ var getLength
+ var valueIsOfTypeString = typeof value === 'string'
+ if (
+ !(
+ valueIsOfTypeString ||
+ value instanceof Uint8Array ||
+ value instanceof Uint8ClampedArray ||
+ value instanceof Int8Array
+ )
+ ) {
+ throwBindingError('Cannot pass non-string to std::string')
+ }
+ if (stdStringIsUTF8 && valueIsOfTypeString) {
+ getLength = function () {
+ return lengthBytesUTF8(value)
+ }
+ } else {
+ getLength = function () {
+ return value.length
+ }
+ }
+ var length = getLength()
+ var ptr = _malloc(4 + length + 1)
+ HEAPU32[ptr >> 2] = length
+ if (stdStringIsUTF8 && valueIsOfTypeString) {
+ stringToUTF8(value, ptr + 4, length + 1)
+ } else {
+ if (valueIsOfTypeString) {
+ for (var i = 0; i < length; ++i) {
+ var charCode = value.charCodeAt(i)
+ if (charCode > 255) {
+ _free(ptr)
+ throwBindingError(
+ 'String has UTF-16 code units that do not fit in 8 bits'
+ )
+ }
+ HEAPU8[ptr + 4 + i] = charCode
+ }
+ } else {
+ for (var i = 0; i < length; ++i) {
+ HEAPU8[ptr + 4 + i] = value[i]
+ }
+ }
+ }
+ if (destructors !== null) {
+ destructors.push(_free, ptr)
+ }
+ return ptr
+ },
+ argPackAdvance: 8,
+ readValueFromPointer: simpleReadValueFromPointer,
+ destructorFunction: function (ptr) {
+ _free(ptr)
+ },
+ })
+ }
+ function __embind_register_std_wstring(rawType, charSize, name) {
+ name = readLatin1String(name)
+ var decodeString, encodeString, getHeap, lengthBytesUTF, shift
+ if (charSize === 2) {
+ decodeString = UTF16ToString
+ encodeString = stringToUTF16
+ lengthBytesUTF = lengthBytesUTF16
+ getHeap = function () {
+ return HEAPU16
+ }
+ shift = 1
+ } else if (charSize === 4) {
+ decodeString = UTF32ToString
+ encodeString = stringToUTF32
+ lengthBytesUTF = lengthBytesUTF32
+ getHeap = function () {
+ return HEAPU32
+ }
+ shift = 2
+ }
+ registerType(rawType, {
+ name: name,
+ fromWireType: function (value) {
+ var length = HEAPU32[value >> 2]
+ var HEAP = getHeap()
+ var str
+ var decodeStartPtr = value + 4
+ for (var i = 0; i <= length; ++i) {
+ var currentBytePtr = value + 4 + i * charSize
+ if (i == length || HEAP[currentBytePtr >> shift] == 0) {
+ var maxReadBytes = currentBytePtr - decodeStartPtr
+ var stringSegment = decodeString(decodeStartPtr, maxReadBytes)
+ if (str === undefined) {
+ str = stringSegment
+ } else {
+ str += String.fromCharCode(0)
+ str += stringSegment
+ }
+ decodeStartPtr = currentBytePtr + charSize
+ }
+ }
+ _free(value)
+ return str
+ },
+ toWireType: function (destructors, value) {
+ if (!(typeof value === 'string')) {
+ throwBindingError(
+ 'Cannot pass non-string to C++ string type ' + name
+ )
+ }
+ var length = lengthBytesUTF(value)
+ var ptr = _malloc(4 + length + charSize)
+ HEAPU32[ptr >> 2] = length >> shift
+ encodeString(value, ptr + 4, length + charSize)
+ if (destructors !== null) {
+ destructors.push(_free, ptr)
+ }
+ return ptr
+ },
+ argPackAdvance: 8,
+ readValueFromPointer: simpleReadValueFromPointer,
+ destructorFunction: function (ptr) {
+ _free(ptr)
+ },
+ })
+ }
+ function __embind_register_void(rawType, name) {
+ name = readLatin1String(name)
+ registerType(rawType, {
+ isVoid: true,
+ name: name,
+ argPackAdvance: 0,
+ fromWireType: function () {
+ return undefined
+ },
+ toWireType: function (destructors, o) {
+ return undefined
+ },
+ })
+ }
+ var emval_symbols = {}
+ function getStringOrSymbol(address) {
+ var symbol = emval_symbols[address]
+ if (symbol === undefined) {
+ return readLatin1String(address)
+ } else {
+ return symbol
+ }
+ }
+ function emval_get_global() {
+ if (typeof globalThis === 'object') {
+ return globalThis
+ }
+ return (function () {
+ return Function
+ })()('return this')()
+ }
+ function __emval_get_global(name) {
+ if (name === 0) {
+ return __emval_register(emval_get_global())
+ } else {
+ name = getStringOrSymbol(name)
+ return __emval_register(emval_get_global()[name])
+ }
+ }
+ function __emval_incref(handle) {
+ if (handle > 4) {
+ emval_handle_array[handle].refcount += 1
+ }
+ }
+ function requireRegisteredType(rawType, humanName) {
+ var impl = registeredTypes[rawType]
+ if (undefined === impl) {
+ throwBindingError(
+ humanName + ' has unknown type ' + getTypeName(rawType)
+ )
+ }
+ return impl
+ }
+ function craftEmvalAllocator(argCount) {
+ var argsList = ''
+ for (var i = 0; i < argCount; ++i) {
+ argsList += (i !== 0 ? ', ' : '') + 'arg' + i
+ }
+ var functionBody =
+ 'return function emval_allocator_' +
+ argCount +
+ '(constructor, argTypes, args) {\n'
+ for (var i = 0; i < argCount; ++i) {
+ functionBody +=
+ 'var argType' +
+ i +
+ " = requireRegisteredType(Module['HEAP32'][(argTypes >>> 2) + " +
+ i +
+ '], "parameter ' +
+ i +
+ '");\n' +
+ 'var arg' +
+ i +
+ ' = argType' +
+ i +
+ '.readValueFromPointer(args);\n' +
+ 'args += argType' +
+ i +
+ "['argPackAdvance'];\n"
+ }
+ functionBody +=
+ 'var obj = new constructor(' +
+ argsList +
+ ');\n' +
+ 'return __emval_register(obj);\n' +
+ '}\n'
+ return new Function(
+ 'requireRegisteredType',
+ 'Module',
+ '__emval_register',
+ functionBody
+ )(requireRegisteredType, Module, __emval_register)
+ }
+ var emval_newers = {}
+ function requireHandle(handle) {
+ if (!handle) {
+ throwBindingError('Cannot use deleted val. handle = ' + handle)
+ }
+ return emval_handle_array[handle].value
+ }
+ function __emval_new(handle, argCount, argTypes, args) {
+ handle = requireHandle(handle)
+ var newer = emval_newers[argCount]
+ if (!newer) {
+ newer = craftEmvalAllocator(argCount)
+ emval_newers[argCount] = newer
+ }
+ return newer(handle, argTypes, args)
+ }
+ function _abort() {
+ abort()
+ }
+ function _emscripten_memcpy_big(dest, src, num) {
+ HEAPU8.copyWithin(dest, src, src + num)
+ }
+ function emscripten_realloc_buffer(size) {
+ try {
+ wasmMemory.grow((size - buffer.byteLength + 65535) >>> 16)
+ updateGlobalBufferAndViews(wasmMemory.buffer)
+ return 1
+ } catch (e) {}
+ }
+ function _emscripten_resize_heap(requestedSize) {
+ var oldSize = HEAPU8.length
+ requestedSize = requestedSize >>> 0
+ var maxHeapSize = 2147483648
+ if (requestedSize > maxHeapSize) {
+ return false
+ }
+ for (var cutDown = 1; cutDown <= 4; cutDown *= 2) {
+ var overGrownHeapSize = oldSize * (1 + 0.2 / cutDown)
+ overGrownHeapSize = Math.min(
+ overGrownHeapSize,
+ requestedSize + 100663296
+ )
+ var newSize = Math.min(
+ maxHeapSize,
+ alignUp(Math.max(requestedSize, overGrownHeapSize), 65536)
+ )
+ var replacement = emscripten_realloc_buffer(newSize)
+ if (replacement) {
+ return true
+ }
+ }
+ return false
+ }
+ var ENV = {}
+ function getExecutableName() {
+ return thisProgram || './this.program'
+ }
+ function getEnvStrings() {
+ if (!getEnvStrings.strings) {
+ var lang =
+ (
+ (typeof navigator === 'object' &&
+ navigator.languages &&
+ navigator.languages[0]) ||
+ 'C'
+ ).replace('-', '_') + '.UTF-8'
+ var env = {
+ USER: 'web_user',
+ LOGNAME: 'web_user',
+ PATH: '/',
+ PWD: '/',
+ HOME: '/home/web_user',
+ LANG: lang,
+ _: getExecutableName(),
+ }
+ for (var x in ENV) {
+ env[x] = ENV[x]
+ }
+ var strings = []
+ for (var x in env) {
+ strings.push(x + '=' + env[x])
+ }
+ getEnvStrings.strings = strings
+ }
+ return getEnvStrings.strings
+ }
+ var SYSCALLS = {
+ mappings: {},
+ buffers: [null, [], []],
+ printChar: function (stream, curr) {
+ var buffer = SYSCALLS.buffers[stream]
+ if (curr === 0 || curr === 10) {
+ ;(stream === 1 ? out : err)(UTF8ArrayToString(buffer, 0))
+ buffer.length = 0
+ } else {
+ buffer.push(curr)
+ }
+ },
+ varargs: undefined,
+ get: function () {
+ SYSCALLS.varargs += 4
+ var ret = HEAP32[(SYSCALLS.varargs - 4) >> 2]
+ return ret
+ },
+ getStr: function (ptr) {
+ var ret = UTF8ToString(ptr)
+ return ret
+ },
+ get64: function (low, high) {
+ return low
+ },
+ }
+ function _environ_get(__environ, environ_buf) {
+ var bufSize = 0
+ getEnvStrings().forEach(function (string, i) {
+ var ptr = environ_buf + bufSize
+ HEAP32[(__environ + i * 4) >> 2] = ptr
+ writeAsciiToMemory(string, ptr)
+ bufSize += string.length + 1
+ })
+ return 0
+ }
+ function _environ_sizes_get(penviron_count, penviron_buf_size) {
+ var strings = getEnvStrings()
+ HEAP32[penviron_count >> 2] = strings.length
+ var bufSize = 0
+ strings.forEach(function (string) {
+ bufSize += string.length + 1
+ })
+ HEAP32[penviron_buf_size >> 2] = bufSize
+ return 0
+ }
+ function _exit(status) {
+ exit(status)
+ }
+ function _fd_close(fd) {
+ return 0
+ }
+ function _fd_seek(fd, offset_low, offset_high, whence, newOffset) {}
+ function _fd_write(fd, iov, iovcnt, pnum) {
+ var num = 0
+ for (var i = 0; i < iovcnt; i++) {
+ var ptr = HEAP32[(iov + i * 8) >> 2]
+ var len = HEAP32[(iov + (i * 8 + 4)) >> 2]
+ for (var j = 0; j < len; j++) {
+ SYSCALLS.printChar(fd, HEAPU8[ptr + j])
+ }
+ num += len
+ }
+ HEAP32[pnum >> 2] = num
+ return 0
+ }
+ function _setTempRet0(val) {
+ setTempRet0(val)
+ }
+ embind_init_charCodes()
+ BindingError = Module['BindingError'] = extendError(Error, 'BindingError')
+ InternalError = Module['InternalError'] = extendError(
+ Error,
+ 'InternalError'
+ )
+ init_emval()
+ UnboundTypeError = Module['UnboundTypeError'] = extendError(
+ Error,
+ 'UnboundTypeError'
+ )
+ var asmLibraryArg = {
+ e: ___cxa_thread_atexit,
+ q: __embind_register_bigint,
+ m: __embind_register_bool,
+ x: __embind_register_emval,
+ l: __embind_register_float,
+ o: __embind_register_function,
+ b: __embind_register_integer,
+ a: __embind_register_memory_view,
+ h: __embind_register_std_string,
+ g: __embind_register_std_wstring,
+ n: __embind_register_void,
+ c: __emval_decref,
+ d: __emval_get_global,
+ i: __emval_incref,
+ j: __emval_new,
+ k: _abort,
+ s: _emscripten_memcpy_big,
+ f: _emscripten_resize_heap,
+ t: _environ_get,
+ u: _environ_sizes_get,
+ y: _exit,
+ w: _fd_close,
+ p: _fd_seek,
+ v: _fd_write,
+ r: _setTempRet0,
+ }
+ var asm = createWasm()
+ var ___wasm_call_ctors = (Module['___wasm_call_ctors'] = function () {
+ return (___wasm_call_ctors = Module['___wasm_call_ctors'] =
+ Module['asm']['A']).apply(null, arguments)
+ })
+ var _malloc = (Module['_malloc'] = function () {
+ return (_malloc = Module['_malloc'] = Module['asm']['B']).apply(
+ null,
+ arguments
+ )
+ })
+ var _free = (Module['_free'] = function () {
+ return (_free = Module['_free'] = Module['asm']['C']).apply(
+ null,
+ arguments
+ )
+ })
+ var ___getTypeName = (Module['___getTypeName'] = function () {
+ return (___getTypeName = Module['___getTypeName'] =
+ Module['asm']['D']).apply(null, arguments)
+ })
+ var ___embind_register_native_and_builtin_types = (Module[
+ '___embind_register_native_and_builtin_types'
+ ] = function () {
+ return (___embind_register_native_and_builtin_types = Module[
+ '___embind_register_native_and_builtin_types'
+ ] =
+ Module['asm']['E']).apply(null, arguments)
+ })
+ var dynCall_jiji = (Module['dynCall_jiji'] = function () {
+ return (dynCall_jiji = Module['dynCall_jiji'] = Module['asm']['G']).apply(
+ null,
+ arguments
+ )
+ })
+ var calledRun
+ function ExitStatus(status) {
+ this.name = 'ExitStatus'
+ this.message = 'Program terminated with exit(' + status + ')'
+ this.status = status
+ }
+ dependenciesFulfilled = function runCaller() {
+ if (!calledRun) run()
+ if (!calledRun) dependenciesFulfilled = runCaller
+ }
+ function run(args) {
+ args = args || arguments_
+ if (runDependencies > 0) {
+ return
+ }
+ preRun()
+ if (runDependencies > 0) {
+ return
+ }
+ function doRun() {
+ if (calledRun) return
+ calledRun = true
+ Module['calledRun'] = true
+ if (ABORT) return
+ initRuntime()
+ readyPromiseResolve(Module)
+ if (Module['onRuntimeInitialized']) Module['onRuntimeInitialized']()
+ postRun()
+ }
+ if (Module['setStatus']) {
+ Module['setStatus']('Running...')
+ setTimeout(function () {
+ setTimeout(function () {
+ Module['setStatus']('')
+ }, 1)
+ doRun()
+ }, 1)
+ } else {
+ doRun()
+ }
+ }
+ Module['run'] = run
+ function exit(status, implicit) {
+ EXITSTATUS = status
+ if (implicit && keepRuntimeAlive() && status === 0) {
+ return
+ }
+ if (keepRuntimeAlive()) {
+ } else {
+ exitRuntime()
+ if (Module['onExit']) Module['onExit'](status)
+ ABORT = true
+ }
+ quit_(status, new ExitStatus(status))
+ }
+ if (Module['preInit']) {
+ if (typeof Module['preInit'] == 'function')
+ Module['preInit'] = [Module['preInit']]
+ while (Module['preInit'].length > 0) {
+ Module['preInit'].pop()()
+ }
+ }
+ run()
+
+ return Module.ready
+ }
+})()
+export default Module
diff --git a/packages/integrations/image/src/vendor/squoosh/mozjpeg/mozjpeg_node_dec.wasm b/packages/integrations/image/src/vendor/squoosh/mozjpeg/mozjpeg_node_dec.wasm
new file mode 100644
index 000000000..abf13d75f
Binary files /dev/null and b/packages/integrations/image/src/vendor/squoosh/mozjpeg/mozjpeg_node_dec.wasm differ
diff --git a/packages/integrations/image/src/vendor/squoosh/mozjpeg/mozjpeg_node_enc.ts b/packages/integrations/image/src/vendor/squoosh/mozjpeg/mozjpeg_node_enc.ts
new file mode 100644
index 000000000..a68b08afc
--- /dev/null
+++ b/packages/integrations/image/src/vendor/squoosh/mozjpeg/mozjpeg_node_enc.ts
@@ -0,0 +1,1935 @@
+/* eslint-disable */
+// @ts-nocheck
+import { createRequire } from 'module';
+const require = createRequire(import.meta.url);
+import { dirname } from '../emscripten-utils.js';
+
+var Module = (function () {
+ return function (Module) {
+ Module = Module || {}
+
+ var Module = typeof Module !== 'undefined' ? Module : {}
+ var readyPromiseResolve, readyPromiseReject
+ Module['ready'] = new Promise(function (resolve, reject) {
+ readyPromiseResolve = resolve
+ readyPromiseReject = reject
+ })
+ var moduleOverrides = {}
+ var key
+ for (key in Module) {
+ if (Module.hasOwnProperty(key)) {
+ moduleOverrides[key] = Module[key]
+ }
+ }
+ var arguments_ = []
+ var thisProgram = './this.program'
+ var quit_ = function (status, toThrow) {
+ throw toThrow
+ }
+ var ENVIRONMENT_IS_WEB = false
+ var ENVIRONMENT_IS_WORKER = false
+ var ENVIRONMENT_IS_NODE = true
+ var scriptDirectory = ''
+ function locateFile(path) {
+ if (Module['locateFile']) {
+ return Module['locateFile'](path, scriptDirectory)
+ }
+ return scriptDirectory + path
+ }
+ var read_, readBinary
+ var nodeFS
+ var nodePath
+ if (ENVIRONMENT_IS_NODE) {
+ if (ENVIRONMENT_IS_WORKER) {
+ scriptDirectory = require('path').dirname(scriptDirectory) + '/'
+ } else {
+ scriptDirectory = dirname(import.meta.url) + '/'
+ }
+ read_ = function shell_read(filename, binary) {
+ if (!nodeFS) nodeFS = require('fs')
+ if (!nodePath) nodePath = require('path')
+ filename = nodePath['normalize'](filename)
+ return nodeFS['readFileSync'](filename, binary ? null : 'utf8')
+ }
+ readBinary = function readBinary(filename) {
+ var ret = read_(filename, true)
+ if (!ret.buffer) {
+ ret = new Uint8Array(ret)
+ }
+ assert(ret.buffer)
+ return ret
+ }
+ if (process['argv'].length > 1) {
+ thisProgram = process['argv'][1].replace(/\\/g, '/')
+ }
+ arguments_ = process['argv'].slice(2)
+ quit_ = function (status) {
+ process['exit'](status)
+ }
+ Module['inspect'] = function () {
+ return '[Emscripten Module object]'
+ }
+ } else {
+ }
+ var out = Module['print'] || console.log.bind(console)
+ var err = Module['printErr'] || console.warn.bind(console)
+ for (key in moduleOverrides) {
+ if (moduleOverrides.hasOwnProperty(key)) {
+ Module[key] = moduleOverrides[key]
+ }
+ }
+ moduleOverrides = null
+ if (Module['arguments']) arguments_ = Module['arguments']
+ if (Module['thisProgram']) thisProgram = Module['thisProgram']
+ if (Module['quit']) quit_ = Module['quit']
+ var tempRet0 = 0
+ var setTempRet0 = function (value) {
+ tempRet0 = value
+ }
+ var wasmBinary
+ if (Module['wasmBinary']) wasmBinary = Module['wasmBinary']
+ var noExitRuntime = Module['noExitRuntime'] || true
+ if (typeof WebAssembly !== 'object') {
+ abort('no native wasm support detected')
+ }
+ var wasmMemory
+ var ABORT = false
+ var EXITSTATUS
+ function assert(condition, text) {
+ if (!condition) {
+ abort('Assertion failed: ' + text)
+ }
+ }
+ var UTF8Decoder = new TextDecoder('utf8')
+ function UTF8ArrayToString(heap, idx, maxBytesToRead) {
+ var endIdx = idx + maxBytesToRead
+ var endPtr = idx
+ while (heap[endPtr] && !(endPtr >= endIdx)) ++endPtr
+ return UTF8Decoder.decode(
+ heap.subarray
+ ? heap.subarray(idx, endPtr)
+ : new Uint8Array(heap.slice(idx, endPtr))
+ )
+ }
+ function UTF8ToString(ptr, maxBytesToRead) {
+ if (!ptr) return ''
+ var maxPtr = ptr + maxBytesToRead
+ for (var end = ptr; !(end >= maxPtr) && HEAPU8[end]; ) ++end
+ return UTF8Decoder.decode(HEAPU8.subarray(ptr, end))
+ }
+ function stringToUTF8Array(str, heap, outIdx, maxBytesToWrite) {
+ if (!(maxBytesToWrite > 0)) return 0
+ var startIdx = outIdx
+ var endIdx = outIdx + maxBytesToWrite - 1
+ for (var i = 0; i < str.length; ++i) {
+ var u = str.charCodeAt(i)
+ if (u >= 55296 && u <= 57343) {
+ var u1 = str.charCodeAt(++i)
+ u = (65536 + ((u & 1023) << 10)) | (u1 & 1023)
+ }
+ if (u <= 127) {
+ if (outIdx >= endIdx) break
+ heap[outIdx++] = u
+ } else if (u <= 2047) {
+ if (outIdx + 1 >= endIdx) break
+ heap[outIdx++] = 192 | (u >> 6)
+ heap[outIdx++] = 128 | (u & 63)
+ } else if (u <= 65535) {
+ if (outIdx + 2 >= endIdx) break
+ heap[outIdx++] = 224 | (u >> 12)
+ heap[outIdx++] = 128 | ((u >> 6) & 63)
+ heap[outIdx++] = 128 | (u & 63)
+ } else {
+ if (outIdx + 3 >= endIdx) break
+ heap[outIdx++] = 240 | (u >> 18)
+ heap[outIdx++] = 128 | ((u >> 12) & 63)
+ heap[outIdx++] = 128 | ((u >> 6) & 63)
+ heap[outIdx++] = 128 | (u & 63)
+ }
+ }
+ heap[outIdx] = 0
+ return outIdx - startIdx
+ }
+ function stringToUTF8(str, outPtr, maxBytesToWrite) {
+ return stringToUTF8Array(str, HEAPU8, outPtr, maxBytesToWrite)
+ }
+ function lengthBytesUTF8(str) {
+ var len = 0
+ for (var i = 0; i < str.length; ++i) {
+ var u = str.charCodeAt(i)
+ if (u >= 55296 && u <= 57343)
+ u = (65536 + ((u & 1023) << 10)) | (str.charCodeAt(++i) & 1023)
+ if (u <= 127) ++len
+ else if (u <= 2047) len += 2
+ else if (u <= 65535) len += 3
+ else len += 4
+ }
+ return len
+ }
+ var UTF16Decoder = new TextDecoder('utf-16le')
+ function UTF16ToString(ptr, maxBytesToRead) {
+ var endPtr = ptr
+ var idx = endPtr >> 1
+ var maxIdx = idx + maxBytesToRead / 2
+ while (!(idx >= maxIdx) && HEAPU16[idx]) ++idx
+ endPtr = idx << 1
+ return UTF16Decoder.decode(HEAPU8.subarray(ptr, endPtr))
+ var str = ''
+ for (var i = 0; !(i >= maxBytesToRead / 2); ++i) {
+ var codeUnit = HEAP16[(ptr + i * 2) >> 1]
+ if (codeUnit == 0) break
+ str += String.fromCharCode(codeUnit)
+ }
+ return str
+ }
+ function stringToUTF16(str, outPtr, maxBytesToWrite) {
+ if (maxBytesToWrite === undefined) {
+ maxBytesToWrite = 2147483647
+ }
+ if (maxBytesToWrite < 2) return 0
+ maxBytesToWrite -= 2
+ var startPtr = outPtr
+ var numCharsToWrite =
+ maxBytesToWrite < str.length * 2 ? maxBytesToWrite / 2 : str.length
+ for (var i = 0; i < numCharsToWrite; ++i) {
+ var codeUnit = str.charCodeAt(i)
+ HEAP16[outPtr >> 1] = codeUnit
+ outPtr += 2
+ }
+ HEAP16[outPtr >> 1] = 0
+ return outPtr - startPtr
+ }
+ function lengthBytesUTF16(str) {
+ return str.length * 2
+ }
+ function UTF32ToString(ptr, maxBytesToRead) {
+ var i = 0
+ var str = ''
+ while (!(i >= maxBytesToRead / 4)) {
+ var utf32 = HEAP32[(ptr + i * 4) >> 2]
+ if (utf32 == 0) break
+ ++i
+ if (utf32 >= 65536) {
+ var ch = utf32 - 65536
+ str += String.fromCharCode(55296 | (ch >> 10), 56320 | (ch & 1023))
+ } else {
+ str += String.fromCharCode(utf32)
+ }
+ }
+ return str
+ }
+ function stringToUTF32(str, outPtr, maxBytesToWrite) {
+ if (maxBytesToWrite === undefined) {
+ maxBytesToWrite = 2147483647
+ }
+ if (maxBytesToWrite < 4) return 0
+ var startPtr = outPtr
+ var endPtr = startPtr + maxBytesToWrite - 4
+ for (var i = 0; i < str.length; ++i) {
+ var codeUnit = str.charCodeAt(i)
+ if (codeUnit >= 55296 && codeUnit <= 57343) {
+ var trailSurrogate = str.charCodeAt(++i)
+ codeUnit =
+ (65536 + ((codeUnit & 1023) << 10)) | (trailSurrogate & 1023)
+ }
+ HEAP32[outPtr >> 2] = codeUnit
+ outPtr += 4
+ if (outPtr + 4 > endPtr) break
+ }
+ HEAP32[outPtr >> 2] = 0
+ return outPtr - startPtr
+ }
+ function lengthBytesUTF32(str) {
+ var len = 0
+ for (var i = 0; i < str.length; ++i) {
+ var codeUnit = str.charCodeAt(i)
+ if (codeUnit >= 55296 && codeUnit <= 57343) ++i
+ len += 4
+ }
+ return len
+ }
+ function writeAsciiToMemory(str, buffer, dontAddNull) {
+ for (var i = 0; i < str.length; ++i) {
+ HEAP8[buffer++ >> 0] = str.charCodeAt(i)
+ }
+ if (!dontAddNull) HEAP8[buffer >> 0] = 0
+ }
+ function alignUp(x, multiple) {
+ if (x % multiple > 0) {
+ x += multiple - (x % multiple)
+ }
+ return x
+ }
+ var buffer,
+ HEAP8,
+ HEAPU8,
+ HEAP16,
+ HEAPU16,
+ HEAP32,
+ HEAPU32,
+ HEAPF32,
+ HEAPF64
+ function updateGlobalBufferAndViews(buf) {
+ buffer = buf
+ Module['HEAP8'] = HEAP8 = new Int8Array(buf)
+ Module['HEAP16'] = HEAP16 = new Int16Array(buf)
+ Module['HEAP32'] = HEAP32 = new Int32Array(buf)
+ Module['HEAPU8'] = HEAPU8 = new Uint8Array(buf)
+ Module['HEAPU16'] = HEAPU16 = new Uint16Array(buf)
+ Module['HEAPU32'] = HEAPU32 = new Uint32Array(buf)
+ Module['HEAPF32'] = HEAPF32 = new Float32Array(buf)
+ Module['HEAPF64'] = HEAPF64 = new Float64Array(buf)
+ }
+ var INITIAL_MEMORY = Module['INITIAL_MEMORY'] || 16777216
+ var wasmTable
+ var __ATPRERUN__ = []
+ var __ATINIT__ = []
+ var __ATPOSTRUN__ = []
+ var runtimeInitialized = false
+ var runtimeExited = false
+ function preRun() {
+ if (Module['preRun']) {
+ if (typeof Module['preRun'] == 'function')
+ Module['preRun'] = [Module['preRun']]
+ while (Module['preRun'].length) {
+ addOnPreRun(Module['preRun'].shift())
+ }
+ }
+ callRuntimeCallbacks(__ATPRERUN__)
+ }
+ function initRuntime() {
+ runtimeInitialized = true
+ callRuntimeCallbacks(__ATINIT__)
+ }
+ function exitRuntime() {
+ runtimeExited = true
+ }
+ function postRun() {
+ if (Module['postRun']) {
+ if (typeof Module['postRun'] == 'function')
+ Module['postRun'] = [Module['postRun']]
+ while (Module['postRun'].length) {
+ addOnPostRun(Module['postRun'].shift())
+ }
+ }
+ callRuntimeCallbacks(__ATPOSTRUN__)
+ }
+ function addOnPreRun(cb) {
+ __ATPRERUN__.unshift(cb)
+ }
+ function addOnInit(cb) {
+ __ATINIT__.unshift(cb)
+ }
+ function addOnPostRun(cb) {
+ __ATPOSTRUN__.unshift(cb)
+ }
+ var runDependencies = 0
+ var runDependencyWatcher = null
+ var dependenciesFulfilled = null
+ function addRunDependency(id) {
+ runDependencies++
+ if (Module['monitorRunDependencies']) {
+ Module['monitorRunDependencies'](runDependencies)
+ }
+ }
+ function removeRunDependency(id) {
+ runDependencies--
+ if (Module['monitorRunDependencies']) {
+ Module['monitorRunDependencies'](runDependencies)
+ }
+ if (runDependencies == 0) {
+ if (runDependencyWatcher !== null) {
+ clearInterval(runDependencyWatcher)
+ runDependencyWatcher = null
+ }
+ if (dependenciesFulfilled) {
+ var callback = dependenciesFulfilled
+ dependenciesFulfilled = null
+ callback()
+ }
+ }
+ }
+ Module['preloadedImages'] = {}
+ Module['preloadedAudios'] = {}
+ function abort(what) {
+ if (Module['onAbort']) {
+ Module['onAbort'](what)
+ }
+ what += ''
+ err(what)
+ ABORT = true
+ EXITSTATUS = 1
+ what = 'abort(' + what + '). Build with -s ASSERTIONS=1 for more info.'
+ var e = new WebAssembly.RuntimeError(what)
+ readyPromiseReject(e)
+ throw e
+ }
+ var dataURIPrefix = 'data:application/octet-stream;base64,'
+ function isDataURI(filename) {
+ return filename.startsWith(dataURIPrefix)
+ }
+ if (Module['locateFile']) {
+ var wasmBinaryFile = 'mozjpeg_node_enc.wasm'
+ if (!isDataURI(wasmBinaryFile)) {
+ wasmBinaryFile = locateFile(wasmBinaryFile)
+ }
+ } else {
+ throw new Error('invariant')
+ }
+ function getBinary(file) {
+ try {
+ if (file == wasmBinaryFile && wasmBinary) {
+ return new Uint8Array(wasmBinary)
+ }
+ if (readBinary) {
+ return readBinary(file)
+ } else {
+ throw 'both async and sync fetching of the wasm failed'
+ }
+ } catch (err) {
+ abort(err)
+ }
+ }
+ function getBinaryPromise() {
+ if (!wasmBinary && (ENVIRONMENT_IS_WEB || ENVIRONMENT_IS_WORKER)) {
+ if (typeof fetch === 'function') {
+ return fetch(wasmBinaryFile, { credentials: 'same-origin' })
+ .then(function (response) {
+ if (!response['ok']) {
+ throw (
+ "failed to load wasm binary file at '" + wasmBinaryFile + "'"
+ )
+ }
+ return response['arrayBuffer']()
+ })
+ .catch(function () {
+ return getBinary(wasmBinaryFile)
+ })
+ }
+ }
+ return Promise.resolve().then(function () {
+ return getBinary(wasmBinaryFile)
+ })
+ }
+ function createWasm() {
+ var info = { a: asmLibraryArg }
+ function receiveInstance(instance, module) {
+ var exports = instance.exports
+ Module['asm'] = exports
+ wasmMemory = Module['asm']['C']
+ updateGlobalBufferAndViews(wasmMemory.buffer)
+ wasmTable = Module['asm']['I']
+ addOnInit(Module['asm']['D'])
+ removeRunDependency('wasm-instantiate')
+ }
+ addRunDependency('wasm-instantiate')
+ function receiveInstantiationResult(result) {
+ receiveInstance(result['instance'])
+ }
+ function instantiateArrayBuffer(receiver) {
+ return getBinaryPromise()
+ .then(function (binary) {
+ var result = WebAssembly.instantiate(binary, info)
+ return result
+ })
+ .then(receiver, function (reason) {
+ err('failed to asynchronously prepare wasm: ' + reason)
+ abort(reason)
+ })
+ }
+ function instantiateAsync() {
+ if (
+ !wasmBinary &&
+ typeof WebAssembly.instantiateStreaming === 'function' &&
+ !isDataURI(wasmBinaryFile) &&
+ typeof fetch === 'function'
+ ) {
+ return fetch(wasmBinaryFile, { credentials: 'same-origin' }).then(
+ function (response) {
+ var result = WebAssembly.instantiateStreaming(response, info)
+ return result.then(receiveInstantiationResult, function (reason) {
+ err('wasm streaming compile failed: ' + reason)
+ err('falling back to ArrayBuffer instantiation')
+ return instantiateArrayBuffer(receiveInstantiationResult)
+ })
+ }
+ )
+ } else {
+ return instantiateArrayBuffer(receiveInstantiationResult)
+ }
+ }
+ if (Module['instantiateWasm']) {
+ try {
+ var exports = Module['instantiateWasm'](info, receiveInstance)
+ return exports
+ } catch (e) {
+ err('Module.instantiateWasm callback failed with error: ' + e)
+ return false
+ }
+ }
+ instantiateAsync().catch(readyPromiseReject)
+ return {}
+ }
+ function callRuntimeCallbacks(callbacks) {
+ while (callbacks.length > 0) {
+ var callback = callbacks.shift()
+ if (typeof callback == 'function') {
+ callback(Module)
+ continue
+ }
+ var func = callback.func
+ if (typeof func === 'number') {
+ if (callback.arg === undefined) {
+ wasmTable.get(func)()
+ } else {
+ wasmTable.get(func)(callback.arg)
+ }
+ } else {
+ func(callback.arg === undefined ? null : callback.arg)
+ }
+ }
+ }
+ var runtimeKeepaliveCounter = 0
+ function keepRuntimeAlive() {
+ return noExitRuntime || runtimeKeepaliveCounter > 0
+ }
+ function _atexit(func, arg) {}
+ function ___cxa_thread_atexit(a0, a1) {
+ return _atexit(a0, a1)
+ }
+ var structRegistrations = {}
+ function runDestructors(destructors) {
+ while (destructors.length) {
+ var ptr = destructors.pop()
+ var del = destructors.pop()
+ del(ptr)
+ }
+ }
+ function simpleReadValueFromPointer(pointer) {
+ return this['fromWireType'](HEAPU32[pointer >> 2])
+ }
+ var awaitingDependencies = {}
+ var registeredTypes = {}
+ var typeDependencies = {}
+ var char_0 = 48
+ var char_9 = 57
+ function makeLegalFunctionName(name) {
+ if (undefined === name) {
+ return '_unknown'
+ }
+ name = name.replace(/[^a-zA-Z0-9_]/g, '$')
+ var f = name.charCodeAt(0)
+ if (f >= char_0 && f <= char_9) {
+ return '_' + name
+ } else {
+ return name
+ }
+ }
+ function createNamedFunction(name, body) {
+ name = makeLegalFunctionName(name)
+ return new Function(
+ 'body',
+ 'return function ' +
+ name +
+ '() {\n' +
+ ' "use strict";' +
+ ' return body.apply(this, arguments);\n' +
+ '};\n'
+ )(body)
+ }
+ function extendError(baseErrorType, errorName) {
+ var errorClass = createNamedFunction(errorName, function (message) {
+ this.name = errorName
+ this.message = message
+ var stack = new Error(message).stack
+ if (stack !== undefined) {
+ this.stack =
+ this.toString() + '\n' + stack.replace(/^Error(:[^\n]*)?\n/, '')
+ }
+ })
+ errorClass.prototype = Object.create(baseErrorType.prototype)
+ errorClass.prototype.constructor = errorClass
+ errorClass.prototype.toString = function () {
+ if (this.message === undefined) {
+ return this.name
+ } else {
+ return this.name + ': ' + this.message
+ }
+ }
+ return errorClass
+ }
+ var InternalError = undefined
+ function throwInternalError(message) {
+ throw new InternalError(message)
+ }
+ function whenDependentTypesAreResolved(
+ myTypes,
+ dependentTypes,
+ getTypeConverters
+ ) {
+ myTypes.forEach(function (type) {
+ typeDependencies[type] = dependentTypes
+ })
+ function onComplete(typeConverters) {
+ var myTypeConverters = getTypeConverters(typeConverters)
+ if (myTypeConverters.length !== myTypes.length) {
+ throwInternalError('Mismatched type converter count')
+ }
+ for (var i = 0; i < myTypes.length; ++i) {
+ registerType(myTypes[i], myTypeConverters[i])
+ }
+ }
+ var typeConverters = new Array(dependentTypes.length)
+ var unregisteredTypes = []
+ var registered = 0
+ dependentTypes.forEach(function (dt, i) {
+ if (registeredTypes.hasOwnProperty(dt)) {
+ typeConverters[i] = registeredTypes[dt]
+ } else {
+ unregisteredTypes.push(dt)
+ if (!awaitingDependencies.hasOwnProperty(dt)) {
+ awaitingDependencies[dt] = []
+ }
+ awaitingDependencies[dt].push(function () {
+ typeConverters[i] = registeredTypes[dt]
+ ++registered
+ if (registered === unregisteredTypes.length) {
+ onComplete(typeConverters)
+ }
+ })
+ }
+ })
+ if (0 === unregisteredTypes.length) {
+ onComplete(typeConverters)
+ }
+ }
+ function __embind_finalize_value_object(structType) {
+ var reg = structRegistrations[structType]
+ delete structRegistrations[structType]
+ var rawConstructor = reg.rawConstructor
+ var rawDestructor = reg.rawDestructor
+ var fieldRecords = reg.fields
+ var fieldTypes = fieldRecords
+ .map(function (field) {
+ return field.getterReturnType
+ })
+ .concat(
+ fieldRecords.map(function (field) {
+ return field.setterArgumentType
+ })
+ )
+ whenDependentTypesAreResolved(
+ [structType],
+ fieldTypes,
+ function (fieldTypes) {
+ var fields = {}
+ fieldRecords.forEach(function (field, i) {
+ var fieldName = field.fieldName
+ var getterReturnType = fieldTypes[i]
+ var getter = field.getter
+ var getterContext = field.getterContext
+ var setterArgumentType = fieldTypes[i + fieldRecords.length]
+ var setter = field.setter
+ var setterContext = field.setterContext
+ fields[fieldName] = {
+ read: function (ptr) {
+ return getterReturnType['fromWireType'](
+ getter(getterContext, ptr)
+ )
+ },
+ write: function (ptr, o) {
+ var destructors = []
+ setter(
+ setterContext,
+ ptr,
+ setterArgumentType['toWireType'](destructors, o)
+ )
+ runDestructors(destructors)
+ },
+ }
+ })
+ return [
+ {
+ name: reg.name,
+ fromWireType: function (ptr) {
+ var rv = {}
+ for (var i in fields) {
+ rv[i] = fields[i].read(ptr)
+ }
+ rawDestructor(ptr)
+ return rv
+ },
+ toWireType: function (destructors, o) {
+ for (var fieldName in fields) {
+ if (!(fieldName in o)) {
+ throw new TypeError('Missing field: "' + fieldName + '"')
+ }
+ }
+ var ptr = rawConstructor()
+ for (fieldName in fields) {
+ fields[fieldName].write(ptr, o[fieldName])
+ }
+ if (destructors !== null) {
+ destructors.push(rawDestructor, ptr)
+ }
+ return ptr
+ },
+ argPackAdvance: 8,
+ readValueFromPointer: simpleReadValueFromPointer,
+ destructorFunction: rawDestructor,
+ },
+ ]
+ }
+ )
+ }
+ function __embind_register_bigint(
+ primitiveType,
+ name,
+ size,
+ minRange,
+ maxRange
+ ) {}
+ function getShiftFromSize(size) {
+ switch (size) {
+ case 1:
+ return 0
+ case 2:
+ return 1
+ case 4:
+ return 2
+ case 8:
+ return 3
+ default:
+ throw new TypeError('Unknown type size: ' + size)
+ }
+ }
+ function embind_init_charCodes() {
+ var codes = new Array(256)
+ for (var i = 0; i < 256; ++i) {
+ codes[i] = String.fromCharCode(i)
+ }
+ embind_charCodes = codes
+ }
+ var embind_charCodes = undefined
+ function readLatin1String(ptr) {
+ var ret = ''
+ var c = ptr
+ while (HEAPU8[c]) {
+ ret += embind_charCodes[HEAPU8[c++]]
+ }
+ return ret
+ }
+ var BindingError = undefined
+ function throwBindingError(message) {
+ throw new BindingError(message)
+ }
+ function registerType(rawType, registeredInstance, options) {
+ options = options || {}
+ if (!('argPackAdvance' in registeredInstance)) {
+ throw new TypeError(
+ 'registerType registeredInstance requires argPackAdvance'
+ )
+ }
+ var name = registeredInstance.name
+ if (!rawType) {
+ throwBindingError(
+ 'type "' + name + '" must have a positive integer typeid pointer'
+ )
+ }
+ if (registeredTypes.hasOwnProperty(rawType)) {
+ if (options.ignoreDuplicateRegistrations) {
+ return
+ } else {
+ throwBindingError("Cannot register type '" + name + "' twice")
+ }
+ }
+ registeredTypes[rawType] = registeredInstance
+ delete typeDependencies[rawType]
+ if (awaitingDependencies.hasOwnProperty(rawType)) {
+ var callbacks = awaitingDependencies[rawType]
+ delete awaitingDependencies[rawType]
+ callbacks.forEach(function (cb) {
+ cb()
+ })
+ }
+ }
+ function __embind_register_bool(
+ rawType,
+ name,
+ size,
+ trueValue,
+ falseValue
+ ) {
+ var shift = getShiftFromSize(size)
+ name = readLatin1String(name)
+ registerType(rawType, {
+ name: name,
+ fromWireType: function (wt) {
+ return !!wt
+ },
+ toWireType: function (destructors, o) {
+ return o ? trueValue : falseValue
+ },
+ argPackAdvance: 8,
+ readValueFromPointer: function (pointer) {
+ var heap
+ if (size === 1) {
+ heap = HEAP8
+ } else if (size === 2) {
+ heap = HEAP16
+ } else if (size === 4) {
+ heap = HEAP32
+ } else {
+ throw new TypeError('Unknown boolean type size: ' + name)
+ }
+ return this['fromWireType'](heap[pointer >> shift])
+ },
+ destructorFunction: null,
+ })
+ }
+ var emval_free_list = []
+ var emval_handle_array = [
+ {},
+ { value: undefined },
+ { value: null },
+ { value: true },
+ { value: false },
+ ]
+ function __emval_decref(handle) {
+ if (handle > 4 && 0 === --emval_handle_array[handle].refcount) {
+ emval_handle_array[handle] = undefined
+ emval_free_list.push(handle)
+ }
+ }
+ function count_emval_handles() {
+ var count = 0
+ for (var i = 5; i < emval_handle_array.length; ++i) {
+ if (emval_handle_array[i] !== undefined) {
+ ++count
+ }
+ }
+ return count
+ }
+ function get_first_emval() {
+ for (var i = 5; i < emval_handle_array.length; ++i) {
+ if (emval_handle_array[i] !== undefined) {
+ return emval_handle_array[i]
+ }
+ }
+ return null
+ }
+ function init_emval() {
+ Module['count_emval_handles'] = count_emval_handles
+ Module['get_first_emval'] = get_first_emval
+ }
+ function __emval_register(value) {
+ switch (value) {
+ case undefined: {
+ return 1
+ }
+ case null: {
+ return 2
+ }
+ case true: {
+ return 3
+ }
+ case false: {
+ return 4
+ }
+ default: {
+ var handle = emval_free_list.length
+ ? emval_free_list.pop()
+ : emval_handle_array.length
+ emval_handle_array[handle] = { refcount: 1, value: value }
+ return handle
+ }
+ }
+ }
+ function __embind_register_emval(rawType, name) {
+ name = readLatin1String(name)
+ registerType(rawType, {
+ name: name,
+ fromWireType: function (handle) {
+ var rv = emval_handle_array[handle].value
+ __emval_decref(handle)
+ return rv
+ },
+ toWireType: function (destructors, value) {
+ return __emval_register(value)
+ },
+ argPackAdvance: 8,
+ readValueFromPointer: simpleReadValueFromPointer,
+ destructorFunction: null,
+ })
+ }
+ function _embind_repr(v) {
+ if (v === null) {
+ return 'null'
+ }
+ var t = typeof v
+ if (t === 'object' || t === 'array' || t === 'function') {
+ return v.toString()
+ } else {
+ return '' + v
+ }
+ }
+ function floatReadValueFromPointer(name, shift) {
+ switch (shift) {
+ case 2:
+ return function (pointer) {
+ return this['fromWireType'](HEAPF32[pointer >> 2])
+ }
+ case 3:
+ return function (pointer) {
+ return this['fromWireType'](HEAPF64[pointer >> 3])
+ }
+ default:
+ throw new TypeError('Unknown float type: ' + name)
+ }
+ }
+ function __embind_register_float(rawType, name, size) {
+ var shift = getShiftFromSize(size)
+ name = readLatin1String(name)
+ registerType(rawType, {
+ name: name,
+ fromWireType: function (value) {
+ return value
+ },
+ toWireType: function (destructors, value) {
+ if (typeof value !== 'number' && typeof value !== 'boolean') {
+ throw new TypeError(
+ 'Cannot convert "' + _embind_repr(value) + '" to ' + this.name
+ )
+ }
+ return value
+ },
+ argPackAdvance: 8,
+ readValueFromPointer: floatReadValueFromPointer(name, shift),
+ destructorFunction: null,
+ })
+ }
+ function new_(constructor, argumentList) {
+ if (!(constructor instanceof Function)) {
+ throw new TypeError(
+ 'new_ called with constructor type ' +
+ typeof constructor +
+ ' which is not a function'
+ )
+ }
+ var dummy = createNamedFunction(
+ constructor.name || 'unknownFunctionName',
+ function () {}
+ )
+ dummy.prototype = constructor.prototype
+ var obj = new dummy()
+ var r = constructor.apply(obj, argumentList)
+ return r instanceof Object ? r : obj
+ }
+ function craftInvokerFunction(
+ humanName,
+ argTypes,
+ classType,
+ cppInvokerFunc,
+ cppTargetFunc
+ ) {
+ var argCount = argTypes.length
+ if (argCount < 2) {
+ throwBindingError(
+ "argTypes array size mismatch! Must at least get return value and 'this' types!"
+ )
+ }
+ var isClassMethodFunc = argTypes[1] !== null && classType !== null
+ var needsDestructorStack = false
+ for (var i = 1; i < argTypes.length; ++i) {
+ if (
+ argTypes[i] !== null &&
+ argTypes[i].destructorFunction === undefined
+ ) {
+ needsDestructorStack = true
+ break
+ }
+ }
+ var returns = argTypes[0].name !== 'void'
+ var argsList = ''
+ var argsListWired = ''
+ for (var i = 0; i < argCount - 2; ++i) {
+ argsList += (i !== 0 ? ', ' : '') + 'arg' + i
+ argsListWired += (i !== 0 ? ', ' : '') + 'arg' + i + 'Wired'
+ }
+ var invokerFnBody =
+ 'return function ' +
+ makeLegalFunctionName(humanName) +
+ '(' +
+ argsList +
+ ') {\n' +
+ 'if (arguments.length !== ' +
+ (argCount - 2) +
+ ') {\n' +
+ "throwBindingError('function " +
+ humanName +
+ " called with ' + arguments.length + ' arguments, expected " +
+ (argCount - 2) +
+ " args!');\n" +
+ '}\n'
+ if (needsDestructorStack) {
+ invokerFnBody += 'var destructors = [];\n'
+ }
+ var dtorStack = needsDestructorStack ? 'destructors' : 'null'
+ var args1 = [
+ 'throwBindingError',
+ 'invoker',
+ 'fn',
+ 'runDestructors',
+ 'retType',
+ 'classParam',
+ ]
+ var args2 = [
+ throwBindingError,
+ cppInvokerFunc,
+ cppTargetFunc,
+ runDestructors,
+ argTypes[0],
+ argTypes[1],
+ ]
+ if (isClassMethodFunc) {
+ invokerFnBody +=
+ 'var thisWired = classParam.toWireType(' + dtorStack + ', this);\n'
+ }
+ for (var i = 0; i < argCount - 2; ++i) {
+ invokerFnBody +=
+ 'var arg' +
+ i +
+ 'Wired = argType' +
+ i +
+ '.toWireType(' +
+ dtorStack +
+ ', arg' +
+ i +
+ '); // ' +
+ argTypes[i + 2].name +
+ '\n'
+ args1.push('argType' + i)
+ args2.push(argTypes[i + 2])
+ }
+ if (isClassMethodFunc) {
+ argsListWired =
+ 'thisWired' + (argsListWired.length > 0 ? ', ' : '') + argsListWired
+ }
+ invokerFnBody +=
+ (returns ? 'var rv = ' : '') +
+ 'invoker(fn' +
+ (argsListWired.length > 0 ? ', ' : '') +
+ argsListWired +
+ ');\n'
+ if (needsDestructorStack) {
+ invokerFnBody += 'runDestructors(destructors);\n'
+ } else {
+ for (var i = isClassMethodFunc ? 1 : 2; i < argTypes.length; ++i) {
+ var paramName = i === 1 ? 'thisWired' : 'arg' + (i - 2) + 'Wired'
+ if (argTypes[i].destructorFunction !== null) {
+ invokerFnBody +=
+ paramName +
+ '_dtor(' +
+ paramName +
+ '); // ' +
+ argTypes[i].name +
+ '\n'
+ args1.push(paramName + '_dtor')
+ args2.push(argTypes[i].destructorFunction)
+ }
+ }
+ }
+ if (returns) {
+ invokerFnBody +=
+ 'var ret = retType.fromWireType(rv);\n' + 'return ret;\n'
+ } else {
+ }
+ invokerFnBody += '}\n'
+ args1.push(invokerFnBody)
+ var invokerFunction = new_(Function, args1).apply(null, args2)
+ return invokerFunction
+ }
+ function ensureOverloadTable(proto, methodName, humanName) {
+ if (undefined === proto[methodName].overloadTable) {
+ var prevFunc = proto[methodName]
+ proto[methodName] = function () {
+ if (
+ !proto[methodName].overloadTable.hasOwnProperty(arguments.length)
+ ) {
+ throwBindingError(
+ "Function '" +
+ humanName +
+ "' called with an invalid number of arguments (" +
+ arguments.length +
+ ') - expects one of (' +
+ proto[methodName].overloadTable +
+ ')!'
+ )
+ }
+ return proto[methodName].overloadTable[arguments.length].apply(
+ this,
+ arguments
+ )
+ }
+ proto[methodName].overloadTable = []
+ proto[methodName].overloadTable[prevFunc.argCount] = prevFunc
+ }
+ }
+ function exposePublicSymbol(name, value, numArguments) {
+ if (Module.hasOwnProperty(name)) {
+ if (
+ undefined === numArguments ||
+ (undefined !== Module[name].overloadTable &&
+ undefined !== Module[name].overloadTable[numArguments])
+ ) {
+ throwBindingError("Cannot register public name '" + name + "' twice")
+ }
+ ensureOverloadTable(Module, name, name)
+ if (Module.hasOwnProperty(numArguments)) {
+ throwBindingError(
+ 'Cannot register multiple overloads of a function with the same number of arguments (' +
+ numArguments +
+ ')!'
+ )
+ }
+ Module[name].overloadTable[numArguments] = value
+ } else {
+ Module[name] = value
+ if (undefined !== numArguments) {
+ Module[name].numArguments = numArguments
+ }
+ }
+ }
+ function heap32VectorToArray(count, firstElement) {
+ var array = []
+ for (var i = 0; i < count; i++) {
+ array.push(HEAP32[(firstElement >> 2) + i])
+ }
+ return array
+ }
+ function replacePublicSymbol(name, value, numArguments) {
+ if (!Module.hasOwnProperty(name)) {
+ throwInternalError('Replacing nonexistant public symbol')
+ }
+ if (
+ undefined !== Module[name].overloadTable &&
+ undefined !== numArguments
+ ) {
+ Module[name].overloadTable[numArguments] = value
+ } else {
+ Module[name] = value
+ Module[name].argCount = numArguments
+ }
+ }
+ function dynCallLegacy(sig, ptr, args) {
+ var f = Module['dynCall_' + sig]
+ return args && args.length
+ ? f.apply(null, [ptr].concat(args))
+ : f.call(null, ptr)
+ }
+ function dynCall(sig, ptr, args) {
+ if (sig.includes('j')) {
+ return dynCallLegacy(sig, ptr, args)
+ }
+ return wasmTable.get(ptr).apply(null, args)
+ }
+ function getDynCaller(sig, ptr) {
+ var argCache = []
+ return function () {
+ argCache.length = arguments.length
+ for (var i = 0; i < arguments.length; i++) {
+ argCache[i] = arguments[i]
+ }
+ return dynCall(sig, ptr, argCache)
+ }
+ }
+ function embind__requireFunction(signature, rawFunction) {
+ signature = readLatin1String(signature)
+ function makeDynCaller() {
+ if (signature.includes('j')) {
+ return getDynCaller(signature, rawFunction)
+ }
+ return wasmTable.get(rawFunction)
+ }
+ var fp = makeDynCaller()
+ if (typeof fp !== 'function') {
+ throwBindingError(
+ 'unknown function pointer with signature ' +
+ signature +
+ ': ' +
+ rawFunction
+ )
+ }
+ return fp
+ }
+ var UnboundTypeError = undefined
+ function getTypeName(type) {
+ var ptr = ___getTypeName(type)
+ var rv = readLatin1String(ptr)
+ _free(ptr)
+ return rv
+ }
+ function throwUnboundTypeError(message, types) {
+ var unboundTypes = []
+ var seen = {}
+ function visit(type) {
+ if (seen[type]) {
+ return
+ }
+ if (registeredTypes[type]) {
+ return
+ }
+ if (typeDependencies[type]) {
+ typeDependencies[type].forEach(visit)
+ return
+ }
+ unboundTypes.push(type)
+ seen[type] = true
+ }
+ types.forEach(visit)
+ throw new UnboundTypeError(
+ message + ': ' + unboundTypes.map(getTypeName).join([', '])
+ )
+ }
+ function __embind_register_function(
+ name,
+ argCount,
+ rawArgTypesAddr,
+ signature,
+ rawInvoker,
+ fn
+ ) {
+ var argTypes = heap32VectorToArray(argCount, rawArgTypesAddr)
+ name = readLatin1String(name)
+ rawInvoker = embind__requireFunction(signature, rawInvoker)
+ exposePublicSymbol(
+ name,
+ function () {
+ throwUnboundTypeError(
+ 'Cannot call ' + name + ' due to unbound types',
+ argTypes
+ )
+ },
+ argCount - 1
+ )
+ whenDependentTypesAreResolved([], argTypes, function (argTypes) {
+ var invokerArgsArray = [argTypes[0], null].concat(argTypes.slice(1))
+ replacePublicSymbol(
+ name,
+ craftInvokerFunction(name, invokerArgsArray, null, rawInvoker, fn),
+ argCount - 1
+ )
+ return []
+ })
+ }
+ function integerReadValueFromPointer(name, shift, signed) {
+ switch (shift) {
+ case 0:
+ return signed
+ ? function readS8FromPointer(pointer) {
+ return HEAP8[pointer]
+ }
+ : function readU8FromPointer(pointer) {
+ return HEAPU8[pointer]
+ }
+ case 1:
+ return signed
+ ? function readS16FromPointer(pointer) {
+ return HEAP16[pointer >> 1]
+ }
+ : function readU16FromPointer(pointer) {
+ return HEAPU16[pointer >> 1]
+ }
+ case 2:
+ return signed
+ ? function readS32FromPointer(pointer) {
+ return HEAP32[pointer >> 2]
+ }
+ : function readU32FromPointer(pointer) {
+ return HEAPU32[pointer >> 2]
+ }
+ default:
+ throw new TypeError('Unknown integer type: ' + name)
+ }
+ }
+ function __embind_register_integer(
+ primitiveType,
+ name,
+ size,
+ minRange,
+ maxRange
+ ) {
+ name = readLatin1String(name)
+ if (maxRange === -1) {
+ maxRange = 4294967295
+ }
+ var shift = getShiftFromSize(size)
+ var fromWireType = function (value) {
+ return value
+ }
+ if (minRange === 0) {
+ var bitshift = 32 - 8 * size
+ fromWireType = function (value) {
+ return (value << bitshift) >>> bitshift
+ }
+ }
+ var isUnsignedType = name.includes('unsigned')
+ registerType(primitiveType, {
+ name: name,
+ fromWireType: fromWireType,
+ toWireType: function (destructors, value) {
+ if (typeof value !== 'number' && typeof value !== 'boolean') {
+ throw new TypeError(
+ 'Cannot convert "' + _embind_repr(value) + '" to ' + this.name
+ )
+ }
+ if (value < minRange || value > maxRange) {
+ throw new TypeError(
+ 'Passing a number "' +
+ _embind_repr(value) +
+ '" from JS side to C/C++ side to an argument of type "' +
+ name +
+ '", which is outside the valid range [' +
+ minRange +
+ ', ' +
+ maxRange +
+ ']!'
+ )
+ }
+ return isUnsignedType ? value >>> 0 : value | 0
+ },
+ argPackAdvance: 8,
+ readValueFromPointer: integerReadValueFromPointer(
+ name,
+ shift,
+ minRange !== 0
+ ),
+ destructorFunction: null,
+ })
+ }
+ function __embind_register_memory_view(rawType, dataTypeIndex, name) {
+ var typeMapping = [
+ Int8Array,
+ Uint8Array,
+ Int16Array,
+ Uint16Array,
+ Int32Array,
+ Uint32Array,
+ Float32Array,
+ Float64Array,
+ ]
+ var TA = typeMapping[dataTypeIndex]
+ function decodeMemoryView(handle) {
+ handle = handle >> 2
+ var heap = HEAPU32
+ var size = heap[handle]
+ var data = heap[handle + 1]
+ return new TA(buffer, data, size)
+ }
+ name = readLatin1String(name)
+ registerType(
+ rawType,
+ {
+ name: name,
+ fromWireType: decodeMemoryView,
+ argPackAdvance: 8,
+ readValueFromPointer: decodeMemoryView,
+ },
+ { ignoreDuplicateRegistrations: true }
+ )
+ }
+ function __embind_register_std_string(rawType, name) {
+ name = readLatin1String(name)
+ var stdStringIsUTF8 = name === 'std::string'
+ registerType(rawType, {
+ name: name,
+ fromWireType: function (value) {
+ var length = HEAPU32[value >> 2]
+ var str
+ if (stdStringIsUTF8) {
+ var decodeStartPtr = value + 4
+ for (var i = 0; i <= length; ++i) {
+ var currentBytePtr = value + 4 + i
+ if (i == length || HEAPU8[currentBytePtr] == 0) {
+ var maxRead = currentBytePtr - decodeStartPtr
+ var stringSegment = UTF8ToString(decodeStartPtr, maxRead)
+ if (str === undefined) {
+ str = stringSegment
+ } else {
+ str += String.fromCharCode(0)
+ str += stringSegment
+ }
+ decodeStartPtr = currentBytePtr + 1
+ }
+ }
+ } else {
+ var a = new Array(length)
+ for (var i = 0; i < length; ++i) {
+ a[i] = String.fromCharCode(HEAPU8[value + 4 + i])
+ }
+ str = a.join('')
+ }
+ _free(value)
+ return str
+ },
+ toWireType: function (destructors, value) {
+ if (value instanceof ArrayBuffer) {
+ value = new Uint8Array(value)
+ }
+ var getLength
+ var valueIsOfTypeString = typeof value === 'string'
+ if (
+ !(
+ valueIsOfTypeString ||
+ value instanceof Uint8Array ||
+ value instanceof Uint8ClampedArray ||
+ value instanceof Int8Array
+ )
+ ) {
+ throwBindingError('Cannot pass non-string to std::string')
+ }
+ if (stdStringIsUTF8 && valueIsOfTypeString) {
+ getLength = function () {
+ return lengthBytesUTF8(value)
+ }
+ } else {
+ getLength = function () {
+ return value.length
+ }
+ }
+ var length = getLength()
+ var ptr = _malloc(4 + length + 1)
+ HEAPU32[ptr >> 2] = length
+ if (stdStringIsUTF8 && valueIsOfTypeString) {
+ stringToUTF8(value, ptr + 4, length + 1)
+ } else {
+ if (valueIsOfTypeString) {
+ for (var i = 0; i < length; ++i) {
+ var charCode = value.charCodeAt(i)
+ if (charCode > 255) {
+ _free(ptr)
+ throwBindingError(
+ 'String has UTF-16 code units that do not fit in 8 bits'
+ )
+ }
+ HEAPU8[ptr + 4 + i] = charCode
+ }
+ } else {
+ for (var i = 0; i < length; ++i) {
+ HEAPU8[ptr + 4 + i] = value[i]
+ }
+ }
+ }
+ if (destructors !== null) {
+ destructors.push(_free, ptr)
+ }
+ return ptr
+ },
+ argPackAdvance: 8,
+ readValueFromPointer: simpleReadValueFromPointer,
+ destructorFunction: function (ptr) {
+ _free(ptr)
+ },
+ })
+ }
+ function __embind_register_std_wstring(rawType, charSize, name) {
+ name = readLatin1String(name)
+ var decodeString, encodeString, getHeap, lengthBytesUTF, shift
+ if (charSize === 2) {
+ decodeString = UTF16ToString
+ encodeString = stringToUTF16
+ lengthBytesUTF = lengthBytesUTF16
+ getHeap = function () {
+ return HEAPU16
+ }
+ shift = 1
+ } else if (charSize === 4) {
+ decodeString = UTF32ToString
+ encodeString = stringToUTF32
+ lengthBytesUTF = lengthBytesUTF32
+ getHeap = function () {
+ return HEAPU32
+ }
+ shift = 2
+ }
+ registerType(rawType, {
+ name: name,
+ fromWireType: function (value) {
+ var length = HEAPU32[value >> 2]
+ var HEAP = getHeap()
+ var str
+ var decodeStartPtr = value + 4
+ for (var i = 0; i <= length; ++i) {
+ var currentBytePtr = value + 4 + i * charSize
+ if (i == length || HEAP[currentBytePtr >> shift] == 0) {
+ var maxReadBytes = currentBytePtr - decodeStartPtr
+ var stringSegment = decodeString(decodeStartPtr, maxReadBytes)
+ if (str === undefined) {
+ str = stringSegment
+ } else {
+ str += String.fromCharCode(0)
+ str += stringSegment
+ }
+ decodeStartPtr = currentBytePtr + charSize
+ }
+ }
+ _free(value)
+ return str
+ },
+ toWireType: function (destructors, value) {
+ if (!(typeof value === 'string')) {
+ throwBindingError(
+ 'Cannot pass non-string to C++ string type ' + name
+ )
+ }
+ var length = lengthBytesUTF(value)
+ var ptr = _malloc(4 + length + charSize)
+ HEAPU32[ptr >> 2] = length >> shift
+ encodeString(value, ptr + 4, length + charSize)
+ if (destructors !== null) {
+ destructors.push(_free, ptr)
+ }
+ return ptr
+ },
+ argPackAdvance: 8,
+ readValueFromPointer: simpleReadValueFromPointer,
+ destructorFunction: function (ptr) {
+ _free(ptr)
+ },
+ })
+ }
+ function __embind_register_value_object(
+ rawType,
+ name,
+ constructorSignature,
+ rawConstructor,
+ destructorSignature,
+ rawDestructor
+ ) {
+ structRegistrations[rawType] = {
+ name: readLatin1String(name),
+ rawConstructor: embind__requireFunction(
+ constructorSignature,
+ rawConstructor
+ ),
+ rawDestructor: embind__requireFunction(
+ destructorSignature,
+ rawDestructor
+ ),
+ fields: [],
+ }
+ }
+ function __embind_register_value_object_field(
+ structType,
+ fieldName,
+ getterReturnType,
+ getterSignature,
+ getter,
+ getterContext,
+ setterArgumentType,
+ setterSignature,
+ setter,
+ setterContext
+ ) {
+ structRegistrations[structType].fields.push({
+ fieldName: readLatin1String(fieldName),
+ getterReturnType: getterReturnType,
+ getter: embind__requireFunction(getterSignature, getter),
+ getterContext: getterContext,
+ setterArgumentType: setterArgumentType,
+ setter: embind__requireFunction(setterSignature, setter),
+ setterContext: setterContext,
+ })
+ }
+ function __embind_register_void(rawType, name) {
+ name = readLatin1String(name)
+ registerType(rawType, {
+ isVoid: true,
+ name: name,
+ argPackAdvance: 0,
+ fromWireType: function () {
+ return undefined
+ },
+ toWireType: function (destructors, o) {
+ return undefined
+ },
+ })
+ }
+ var emval_symbols = {}
+ function getStringOrSymbol(address) {
+ var symbol = emval_symbols[address]
+ if (symbol === undefined) {
+ return readLatin1String(address)
+ } else {
+ return symbol
+ }
+ }
+ function emval_get_global() {
+ if (typeof globalThis === 'object') {
+ return globalThis
+ }
+ return (function () {
+ return Function
+ })()('return this')()
+ }
+ function __emval_get_global(name) {
+ if (name === 0) {
+ return __emval_register(emval_get_global())
+ } else {
+ name = getStringOrSymbol(name)
+ return __emval_register(emval_get_global()[name])
+ }
+ }
+ function __emval_incref(handle) {
+ if (handle > 4) {
+ emval_handle_array[handle].refcount += 1
+ }
+ }
+ function requireRegisteredType(rawType, humanName) {
+ var impl = registeredTypes[rawType]
+ if (undefined === impl) {
+ throwBindingError(
+ humanName + ' has unknown type ' + getTypeName(rawType)
+ )
+ }
+ return impl
+ }
+ function craftEmvalAllocator(argCount) {
+ var argsList = ''
+ for (var i = 0; i < argCount; ++i) {
+ argsList += (i !== 0 ? ', ' : '') + 'arg' + i
+ }
+ var functionBody =
+ 'return function emval_allocator_' +
+ argCount +
+ '(constructor, argTypes, args) {\n'
+ for (var i = 0; i < argCount; ++i) {
+ functionBody +=
+ 'var argType' +
+ i +
+ " = requireRegisteredType(Module['HEAP32'][(argTypes >>> 2) + " +
+ i +
+ '], "parameter ' +
+ i +
+ '");\n' +
+ 'var arg' +
+ i +
+ ' = argType' +
+ i +
+ '.readValueFromPointer(args);\n' +
+ 'args += argType' +
+ i +
+ "['argPackAdvance'];\n"
+ }
+ functionBody +=
+ 'var obj = new constructor(' +
+ argsList +
+ ');\n' +
+ 'return __emval_register(obj);\n' +
+ '}\n'
+ return new Function(
+ 'requireRegisteredType',
+ 'Module',
+ '__emval_register',
+ functionBody
+ )(requireRegisteredType, Module, __emval_register)
+ }
+ var emval_newers = {}
+ function requireHandle(handle) {
+ if (!handle) {
+ throwBindingError('Cannot use deleted val. handle = ' + handle)
+ }
+ return emval_handle_array[handle].value
+ }
+ function __emval_new(handle, argCount, argTypes, args) {
+ handle = requireHandle(handle)
+ var newer = emval_newers[argCount]
+ if (!newer) {
+ newer = craftEmvalAllocator(argCount)
+ emval_newers[argCount] = newer
+ }
+ return newer(handle, argTypes, args)
+ }
+ function _abort() {
+ abort()
+ }
+ function _emscripten_memcpy_big(dest, src, num) {
+ HEAPU8.copyWithin(dest, src, src + num)
+ }
+ function emscripten_realloc_buffer(size) {
+ try {
+ wasmMemory.grow((size - buffer.byteLength + 65535) >>> 16)
+ updateGlobalBufferAndViews(wasmMemory.buffer)
+ return 1
+ } catch (e) {}
+ }
+ function _emscripten_resize_heap(requestedSize) {
+ var oldSize = HEAPU8.length
+ requestedSize = requestedSize >>> 0
+ var maxHeapSize = 2147483648
+ if (requestedSize > maxHeapSize) {
+ return false
+ }
+ for (var cutDown = 1; cutDown <= 4; cutDown *= 2) {
+ var overGrownHeapSize = oldSize * (1 + 0.2 / cutDown)
+ overGrownHeapSize = Math.min(
+ overGrownHeapSize,
+ requestedSize + 100663296
+ )
+ var newSize = Math.min(
+ maxHeapSize,
+ alignUp(Math.max(requestedSize, overGrownHeapSize), 65536)
+ )
+ var replacement = emscripten_realloc_buffer(newSize)
+ if (replacement) {
+ return true
+ }
+ }
+ return false
+ }
+ var ENV = {}
+ function getExecutableName() {
+ return thisProgram || './this.program'
+ }
+ function getEnvStrings() {
+ if (!getEnvStrings.strings) {
+ var lang =
+ (
+ (typeof navigator === 'object' &&
+ navigator.languages &&
+ navigator.languages[0]) ||
+ 'C'
+ ).replace('-', '_') + '.UTF-8'
+ var env = {
+ USER: 'web_user',
+ LOGNAME: 'web_user',
+ PATH: '/',
+ PWD: '/',
+ HOME: '/home/web_user',
+ LANG: lang,
+ _: getExecutableName(),
+ }
+ for (var x in ENV) {
+ env[x] = ENV[x]
+ }
+ var strings = []
+ for (var x in env) {
+ strings.push(x + '=' + env[x])
+ }
+ getEnvStrings.strings = strings
+ }
+ return getEnvStrings.strings
+ }
+ var SYSCALLS = {
+ mappings: {},
+ buffers: [null, [], []],
+ printChar: function (stream, curr) {
+ var buffer = SYSCALLS.buffers[stream]
+ if (curr === 0 || curr === 10) {
+ ;(stream === 1 ? out : err)(UTF8ArrayToString(buffer, 0))
+ buffer.length = 0
+ } else {
+ buffer.push(curr)
+ }
+ },
+ varargs: undefined,
+ get: function () {
+ SYSCALLS.varargs += 4
+ var ret = HEAP32[(SYSCALLS.varargs - 4) >> 2]
+ return ret
+ },
+ getStr: function (ptr) {
+ var ret = UTF8ToString(ptr)
+ return ret
+ },
+ get64: function (low, high) {
+ return low
+ },
+ }
+ function _environ_get(__environ, environ_buf) {
+ var bufSize = 0
+ getEnvStrings().forEach(function (string, i) {
+ var ptr = environ_buf + bufSize
+ HEAP32[(__environ + i * 4) >> 2] = ptr
+ writeAsciiToMemory(string, ptr)
+ bufSize += string.length + 1
+ })
+ return 0
+ }
+ function _environ_sizes_get(penviron_count, penviron_buf_size) {
+ var strings = getEnvStrings()
+ HEAP32[penviron_count >> 2] = strings.length
+ var bufSize = 0
+ strings.forEach(function (string) {
+ bufSize += string.length + 1
+ })
+ HEAP32[penviron_buf_size >> 2] = bufSize
+ return 0
+ }
+ function _exit(status) {
+ exit(status)
+ }
+ function _fd_close(fd) {
+ return 0
+ }
+ function _fd_seek(fd, offset_low, offset_high, whence, newOffset) {}
+ function _fd_write(fd, iov, iovcnt, pnum) {
+ var num = 0
+ for (var i = 0; i < iovcnt; i++) {
+ var ptr = HEAP32[(iov + i * 8) >> 2]
+ var len = HEAP32[(iov + (i * 8 + 4)) >> 2]
+ for (var j = 0; j < len; j++) {
+ SYSCALLS.printChar(fd, HEAPU8[ptr + j])
+ }
+ num += len
+ }
+ HEAP32[pnum >> 2] = num
+ return 0
+ }
+ function _setTempRet0(val) {
+ setTempRet0(val)
+ }
+ InternalError = Module['InternalError'] = extendError(
+ Error,
+ 'InternalError'
+ )
+ embind_init_charCodes()
+ BindingError = Module['BindingError'] = extendError(Error, 'BindingError')
+ init_emval()
+ UnboundTypeError = Module['UnboundTypeError'] = extendError(
+ Error,
+ 'UnboundTypeError'
+ )
+ var asmLibraryArg = {
+ B: ___cxa_thread_atexit,
+ l: __embind_finalize_value_object,
+ p: __embind_register_bigint,
+ y: __embind_register_bool,
+ x: __embind_register_emval,
+ i: __embind_register_float,
+ f: __embind_register_function,
+ c: __embind_register_integer,
+ b: __embind_register_memory_view,
+ j: __embind_register_std_string,
+ e: __embind_register_std_wstring,
+ m: __embind_register_value_object,
+ a: __embind_register_value_object_field,
+ z: __embind_register_void,
+ g: __emval_decref,
+ u: __emval_get_global,
+ k: __emval_incref,
+ n: __emval_new,
+ h: _abort,
+ r: _emscripten_memcpy_big,
+ d: _emscripten_resize_heap,
+ s: _environ_get,
+ t: _environ_sizes_get,
+ A: _exit,
+ w: _fd_close,
+ o: _fd_seek,
+ v: _fd_write,
+ q: _setTempRet0,
+ }
+ var asm = createWasm()
+ var ___wasm_call_ctors = (Module['___wasm_call_ctors'] = function () {
+ return (___wasm_call_ctors = Module['___wasm_call_ctors'] =
+ Module['asm']['D']).apply(null, arguments)
+ })
+ var _malloc = (Module['_malloc'] = function () {
+ return (_malloc = Module['_malloc'] = Module['asm']['E']).apply(
+ null,
+ arguments
+ )
+ })
+ var _free = (Module['_free'] = function () {
+ return (_free = Module['_free'] = Module['asm']['F']).apply(
+ null,
+ arguments
+ )
+ })
+ var ___getTypeName = (Module['___getTypeName'] = function () {
+ return (___getTypeName = Module['___getTypeName'] =
+ Module['asm']['G']).apply(null, arguments)
+ })
+ var ___embind_register_native_and_builtin_types = (Module[
+ '___embind_register_native_and_builtin_types'
+ ] = function () {
+ return (___embind_register_native_and_builtin_types = Module[
+ '___embind_register_native_and_builtin_types'
+ ] =
+ Module['asm']['H']).apply(null, arguments)
+ })
+ var dynCall_jiji = (Module['dynCall_jiji'] = function () {
+ return (dynCall_jiji = Module['dynCall_jiji'] = Module['asm']['J']).apply(
+ null,
+ arguments
+ )
+ })
+ var calledRun
+ function ExitStatus(status) {
+ this.name = 'ExitStatus'
+ this.message = 'Program terminated with exit(' + status + ')'
+ this.status = status
+ }
+ dependenciesFulfilled = function runCaller() {
+ if (!calledRun) run()
+ if (!calledRun) dependenciesFulfilled = runCaller
+ }
+ function run(args) {
+ args = args || arguments_
+ if (runDependencies > 0) {
+ return
+ }
+ preRun()
+ if (runDependencies > 0) {
+ return
+ }
+ function doRun() {
+ if (calledRun) return
+ calledRun = true
+ Module['calledRun'] = true
+ if (ABORT) return
+ initRuntime()
+ readyPromiseResolve(Module)
+ if (Module['onRuntimeInitialized']) Module['onRuntimeInitialized']()
+ postRun()
+ }
+ if (Module['setStatus']) {
+ Module['setStatus']('Running...')
+ setTimeout(function () {
+ setTimeout(function () {
+ Module['setStatus']('')
+ }, 1)
+ doRun()
+ }, 1)
+ } else {
+ doRun()
+ }
+ }
+ Module['run'] = run
+ function exit(status, implicit) {
+ EXITSTATUS = status
+ if (implicit && keepRuntimeAlive() && status === 0) {
+ return
+ }
+ if (keepRuntimeAlive()) {
+ } else {
+ exitRuntime()
+ if (Module['onExit']) Module['onExit'](status)
+ ABORT = true
+ }
+ quit_(status, new ExitStatus(status))
+ }
+ if (Module['preInit']) {
+ if (typeof Module['preInit'] == 'function')
+ Module['preInit'] = [Module['preInit']]
+ while (Module['preInit'].length > 0) {
+ Module['preInit'].pop()()
+ }
+ }
+ run()
+
+ return Module.ready
+ }
+})()
+export default Module
diff --git a/packages/integrations/image/src/vendor/squoosh/mozjpeg/mozjpeg_node_enc.wasm b/packages/integrations/image/src/vendor/squoosh/mozjpeg/mozjpeg_node_enc.wasm
new file mode 100644
index 000000000..4dc36264b
Binary files /dev/null and b/packages/integrations/image/src/vendor/squoosh/mozjpeg/mozjpeg_node_enc.wasm differ
diff --git a/packages/integrations/image/src/vendor/squoosh/png/squoosh_oxipng.ts b/packages/integrations/image/src/vendor/squoosh/png/squoosh_oxipng.ts
new file mode 100644
index 000000000..90a12b389
--- /dev/null
+++ b/packages/integrations/image/src/vendor/squoosh/png/squoosh_oxipng.ts
@@ -0,0 +1,120 @@
+// @ts-nocheck
+let wasm
+
+let cachedTextDecoder = new TextDecoder('utf-8', {
+ ignoreBOM: true,
+ fatal: true,
+})
+
+cachedTextDecoder.decode()
+
+let cachegetUint8Memory0 = null
+function getUint8Memory0() {
+ if (
+ cachegetUint8Memory0 === null ||
+ cachegetUint8Memory0.buffer !== wasm.memory.buffer
+ ) {
+ cachegetUint8Memory0 = new Uint8Array(wasm.memory.buffer)
+ }
+ return cachegetUint8Memory0
+}
+
+function getStringFromWasm0(ptr, len) {
+ return cachedTextDecoder.decode(getUint8Memory0().subarray(ptr, ptr + len))
+}
+
+let WASM_VECTOR_LEN = 0
+
+function passArray8ToWasm0(arg, malloc) {
+ const ptr = malloc(arg.length * 1)
+ getUint8Memory0().set(arg, ptr / 1)
+ WASM_VECTOR_LEN = arg.length
+ return ptr
+}
+
+let cachegetInt32Memory0 = null
+function getInt32Memory0() {
+ if (
+ cachegetInt32Memory0 === null ||
+ cachegetInt32Memory0.buffer !== wasm.memory.buffer
+ ) {
+ cachegetInt32Memory0 = new Int32Array(wasm.memory.buffer)
+ }
+ return cachegetInt32Memory0
+}
+
+function getArrayU8FromWasm0(ptr, len) {
+ return getUint8Memory0().subarray(ptr / 1, ptr / 1 + len)
+}
+/**
+ * @param {Uint8Array} data
+ * @param {number} level
+ * @param {boolean} interlace
+ * @returns {Uint8Array}
+ */
+export function optimise(data, level, interlace) {
+ try {
+ const retptr = wasm.__wbindgen_add_to_stack_pointer(-16)
+ const ptr0 = passArray8ToWasm0(data, wasm.__wbindgen_malloc)
+ const len0 = WASM_VECTOR_LEN
+ wasm.optimise(retptr, ptr0, len0, level, interlace)
+ const r0 = getInt32Memory0()[retptr / 4 + 0]
+ const r1 = getInt32Memory0()[retptr / 4 + 1]
+ const v1 = getArrayU8FromWasm0(r0, r1).slice()
+ wasm.__wbindgen_free(r0, r1 * 1)
+ return v1
+ } finally {
+ wasm.__wbindgen_add_to_stack_pointer(16)
+ }
+}
+
+async function load(module, imports) {
+ if (typeof Response === 'function' && module instanceof Response) {
+ if (typeof WebAssembly.instantiateStreaming === 'function') {
+ return await WebAssembly.instantiateStreaming(module, imports)
+ }
+
+ const bytes = await module.arrayBuffer()
+ return await WebAssembly.instantiate(bytes, imports)
+ } else {
+ const instance = await WebAssembly.instantiate(module, imports)
+
+ if (instance instanceof WebAssembly.Instance) {
+ return { instance, module }
+ } else {
+ return instance
+ }
+ }
+}
+
+async function init(input) {
+ const imports = {}
+ imports.wbg = {}
+ imports.wbg.__wbindgen_throw = function (arg0, arg1) {
+ throw new Error(getStringFromWasm0(arg0, arg1))
+ }
+
+ if (
+ typeof input === 'string' ||
+ (typeof Request === 'function' && input instanceof Request) ||
+ (typeof URL === 'function' && input instanceof URL)
+ ) {
+ input = fetch(input)
+ }
+
+ const { instance, module } = await load(await input, imports)
+
+ wasm = instance.exports
+ init.__wbindgen_wasm_module = module
+
+ return wasm
+}
+
+export default init
+
+// Manually remove the wasm and memory references to trigger GC
+export function cleanup() {
+ wasm = null
+ cachegetUint8Memory0 = null
+ cachegetInt32Memory0 = null
+}
diff --git a/packages/integrations/image/src/vendor/squoosh/png/squoosh_oxipng_bg.wasm b/packages/integrations/image/src/vendor/squoosh/png/squoosh_oxipng_bg.wasm
new file mode 100644
index 000000000..92ec1d896
Binary files /dev/null and b/packages/integrations/image/src/vendor/squoosh/png/squoosh_oxipng_bg.wasm differ
diff --git a/packages/integrations/image/src/vendor/squoosh/png/squoosh_png.ts b/packages/integrations/image/src/vendor/squoosh/png/squoosh_png.ts
new file mode 100644
index 000000000..09cbed9ff
--- /dev/null
+++ b/packages/integrations/image/src/vendor/squoosh/png/squoosh_png.ts
@@ -0,0 +1,184 @@
+// @ts-nocheck
+let wasm
+
+let cachedTextDecoder = new TextDecoder('utf-8', {
+ ignoreBOM: true,
+ fatal: true,
+})
+
+cachedTextDecoder.decode()
+
+let cachegetUint8Memory0 = null
+function getUint8Memory0() {
+ if (
+ cachegetUint8Memory0 === null ||
+ cachegetUint8Memory0.buffer !== wasm.memory.buffer
+ ) {
+ cachegetUint8Memory0 = new Uint8Array(wasm.memory.buffer)
+ }
+ return cachegetUint8Memory0
+}
+
+function getStringFromWasm0(ptr, len) {
+ return cachedTextDecoder.decode(getUint8Memory0().subarray(ptr, ptr + len))
+}
+
+let cachegetUint8ClampedMemory0 = null
+function getUint8ClampedMemory0() {
+ if (
+ cachegetUint8ClampedMemory0 === null ||
+ cachegetUint8ClampedMemory0.buffer !== wasm.memory.buffer
+ ) {
+ cachegetUint8ClampedMemory0 = new Uint8ClampedArray(wasm.memory.buffer)
+ }
+ return cachegetUint8ClampedMemory0
+}
+
+function getClampedArrayU8FromWasm0(ptr, len) {
+ return getUint8ClampedMemory0().subarray(ptr / 1, ptr / 1 + len)
+}
+
+const heap = new Array(32).fill(undefined)
+
+heap.push(undefined, null, true, false)
+
+let heap_next = heap.length
+
+function addHeapObject(obj) {
+ if (heap_next === heap.length) heap.push(heap.length + 1)
+ const idx = heap_next
+ heap_next = heap[idx]
+
+ heap[idx] = obj
+ return idx
+}
+
+let WASM_VECTOR_LEN = 0
+
+function passArray8ToWasm0(arg, malloc) {
+ const ptr = malloc(arg.length * 1)
+ getUint8Memory0().set(arg, ptr / 1)
+ WASM_VECTOR_LEN = arg.length
+ return ptr
+}
+
+let cachegetInt32Memory0 = null
+function getInt32Memory0() {
+ if (
+ cachegetInt32Memory0 === null ||
+ cachegetInt32Memory0.buffer !== wasm.memory.buffer
+ ) {
+ cachegetInt32Memory0 = new Int32Array(wasm.memory.buffer)
+ }
+ return cachegetInt32Memory0
+}
+
+function getArrayU8FromWasm0(ptr, len) {
+ return getUint8Memory0().subarray(ptr / 1, ptr / 1 + len)
+}
+/**
+ * @param {Uint8Array} data
+ * @param {number} width
+ * @param {number} height
+ * @returns {Uint8Array}
+ */
+export function encode(data, width, height) {
+ try {
+ const retptr = wasm.__wbindgen_add_to_stack_pointer(-16)
+ const ptr0 = passArray8ToWasm0(data, wasm.__wbindgen_malloc)
+ const len0 = WASM_VECTOR_LEN
+ wasm.encode(retptr, ptr0, len0, width, height)
+ const r0 = getInt32Memory0()[retptr / 4 + 0]
+ const r1 = getInt32Memory0()[retptr / 4 + 1]
+ const v1 = getArrayU8FromWasm0(r0, r1).slice()
+ wasm.__wbindgen_free(r0, r1 * 1)
+ return v1
+ } finally {
+ wasm.__wbindgen_add_to_stack_pointer(16)
+ }
+}
+
+function getObject(idx) {
+ return heap[idx]
+}
+
+function dropObject(idx) {
+ if (idx < 36) return
+ heap[idx] = heap_next
+ heap_next = idx
+}
+
+function takeObject(idx) {
+ const ret = getObject(idx)
+ dropObject(idx)
+ return ret
+}
+/**
+ * @param {Uint8Array} data
+ * @returns {ImageData}
+ */
+export function decode(data) {
+ const ptr0 = passArray8ToWasm0(data, wasm.__wbindgen_malloc)
+ const len0 = WASM_VECTOR_LEN
+ const ret = wasm.decode(ptr0, len0)
+ return takeObject(ret)
+}
+
+async function load(module, imports) {
+ if (typeof Response === 'function' && module instanceof Response) {
+ if (typeof WebAssembly.instantiateStreaming === 'function') {
+ return await WebAssembly.instantiateStreaming(module, imports)
+ }
+
+ const bytes = await module.arrayBuffer()
+ return await WebAssembly.instantiate(bytes, imports)
+ } else {
+ const instance = await WebAssembly.instantiate(module, imports)
+
+ if (instance instanceof WebAssembly.Instance) {
+ return { instance, module }
+ } else {
+ return instance
+ }
+ }
+}
+
+async function init(input) {
+ const imports = {}
+ imports.wbg = {}
+ imports.wbg.__wbg_newwithownedu8clampedarrayandsh_787b2db8ea6bfd62 =
+ function (arg0, arg1, arg2, arg3) {
+ const v0 = getClampedArrayU8FromWasm0(arg0, arg1).slice()
+ wasm.__wbindgen_free(arg0, arg1 * 1)
+ const ret = new ImageData(v0, arg2 >>> 0, arg3 >>> 0)
+ return addHeapObject(ret)
+ }
+ imports.wbg.__wbindgen_throw = function (arg0, arg1) {
+ throw new Error(getStringFromWasm0(arg0, arg1))
+ }
+
+ if (
+ typeof input === 'string' ||
+ (typeof Request === 'function' && input instanceof Request) ||
+ (typeof URL === 'function' && input instanceof URL)
+ ) {
+ input = fetch(input)
+ }
+
+ const { instance, module } = await load(await input, imports)
+
+ wasm = instance.exports
+ init.__wbindgen_wasm_module = module
+
+ return wasm
+}
+
+export default init
+
+// Manually remove the wasm and memory references to trigger GC
+export function cleanup() {
+ wasm = null
+ cachegetUint8ClampedMemory0 = null
+ cachegetUint8Memory0 = null
+ cachegetInt32Memory0 = null
+}
diff --git a/packages/integrations/image/src/vendor/squoosh/png/squoosh_png_bg.wasm b/packages/integrations/image/src/vendor/squoosh/png/squoosh_png_bg.wasm
new file mode 100644
index 000000000..cc5cf3660
Binary files /dev/null and b/packages/integrations/image/src/vendor/squoosh/png/squoosh_png_bg.wasm differ
diff --git a/packages/integrations/image/src/vendor/squoosh/resize/squoosh_resize.ts b/packages/integrations/image/src/vendor/squoosh/resize/squoosh_resize.ts
new file mode 100644
index 000000000..1204db18f
--- /dev/null
+++ b/packages/integrations/image/src/vendor/squoosh/resize/squoosh_resize.ts
@@ -0,0 +1,141 @@
+// @ts-nocheck
+let wasm
+
+let cachegetUint8Memory0 = null
+function getUint8Memory0() {
+ if (
+ cachegetUint8Memory0 === null ||
+ cachegetUint8Memory0.buffer !== wasm.memory.buffer
+ ) {
+ cachegetUint8Memory0 = new Uint8Array(wasm.memory.buffer)
+ }
+ return cachegetUint8Memory0
+}
+
+let WASM_VECTOR_LEN = 0
+
+function passArray8ToWasm0(arg, malloc) {
+ const ptr = malloc(arg.length * 1)
+ getUint8Memory0().set(arg, ptr / 1)
+ WASM_VECTOR_LEN = arg.length
+ return ptr
+}
+
+let cachegetInt32Memory0 = null
+function getInt32Memory0() {
+ if (
+ cachegetInt32Memory0 === null ||
+ cachegetInt32Memory0.buffer !== wasm.memory.buffer
+ ) {
+ cachegetInt32Memory0 = new Int32Array(wasm.memory.buffer)
+ }
+ return cachegetInt32Memory0
+}
+
+let cachegetUint8ClampedMemory0 = null
+function getUint8ClampedMemory0() {
+ if (
+ cachegetUint8ClampedMemory0 === null ||
+ cachegetUint8ClampedMemory0.buffer !== wasm.memory.buffer
+ ) {
+ cachegetUint8ClampedMemory0 = new Uint8ClampedArray(wasm.memory.buffer)
+ }
+ return cachegetUint8ClampedMemory0
+}
+
+function getClampedArrayU8FromWasm0(ptr, len) {
+ return getUint8ClampedMemory0().subarray(ptr / 1, ptr / 1 + len)
+}
+/**
+ * @param {Uint8Array} input_image
+ * @param {number} input_width
+ * @param {number} input_height
+ * @param {number} output_width
+ * @param {number} output_height
+ * @param {number} typ_idx
+ * @param {boolean} premultiply
+ * @param {boolean} color_space_conversion
+ * @returns {Uint8ClampedArray}
+ */
+export function resize(
+ input_image,
+ input_width,
+ input_height,
+ output_width,
+ output_height,
+ typ_idx,
+ premultiply,
+ color_space_conversion
+) {
+ try {
+ const retptr = wasm.__wbindgen_add_to_stack_pointer(-16)
+ const ptr0 = passArray8ToWasm0(input_image, wasm.__wbindgen_malloc)
+ const len0 = WASM_VECTOR_LEN
+ wasm.resize(
+ retptr,
+ ptr0,
+ len0,
+ input_width,
+ input_height,
+ output_width,
+ output_height,
+ typ_idx,
+ premultiply,
+ color_space_conversion
+ )
+ const r0 = getInt32Memory0()[retptr / 4 + 0]
+ const r1 = getInt32Memory0()[retptr / 4 + 1]
+ const v1 = getClampedArrayU8FromWasm0(r0, r1).slice()
+ wasm.__wbindgen_free(r0, r1 * 1)
+ return v1
+ } finally {
+ wasm.__wbindgen_add_to_stack_pointer(16)
+ }
+}
+
+async function load(module, imports) {
+ if (typeof Response === 'function' && module instanceof Response) {
+ if (typeof WebAssembly.instantiateStreaming === 'function') {
+ return await WebAssembly.instantiateStreaming(module, imports)
+ }
+
+ const bytes = await module.arrayBuffer()
+ return await WebAssembly.instantiate(bytes, imports)
+ } else {
+ const instance = await WebAssembly.instantiate(module, imports)
+
+ if (instance instanceof WebAssembly.Instance) {
+ return { instance, module }
+ } else {
+ return instance
+ }
+ }
+}
+
+async function init(input) {
+ const imports = {}
+
+ if (
+ typeof input === 'string' ||
+ (typeof Request === 'function' && input instanceof Request) ||
+ (typeof URL === 'function' && input instanceof URL)
+ ) {
+ input = fetch(input)
+ }
+
+ const { instance, module } = await load(await input, imports)
+
+ wasm = instance.exports
+ init.__wbindgen_wasm_module = module
+
+ return wasm
+}
+
+export default init
+
+// Manually remove the wasm and memory references to trigger GC
+export function cleanup() {
+ wasm = null
+ cachegetUint8Memory0 = null
+ cachegetInt32Memory0 = null
+}
diff --git a/packages/integrations/image/src/vendor/squoosh/resize/squoosh_resize_bg.wasm b/packages/integrations/image/src/vendor/squoosh/resize/squoosh_resize_bg.wasm
new file mode 100644
index 000000000..b910c97b0
Binary files /dev/null and b/packages/integrations/image/src/vendor/squoosh/resize/squoosh_resize_bg.wasm differ
diff --git a/packages/integrations/image/src/vendor/squoosh/rotate/rotate.wasm b/packages/integrations/image/src/vendor/squoosh/rotate/rotate.wasm
new file mode 100644
index 000000000..8c7122c9f
Binary files /dev/null and b/packages/integrations/image/src/vendor/squoosh/rotate/rotate.wasm differ
diff --git a/packages/integrations/image/src/vendor/squoosh/webp/webp_enc.d.ts b/packages/integrations/image/src/vendor/squoosh/webp/webp_enc.d.ts
new file mode 100644
index 000000000..3c4506829
--- /dev/null
+++ b/packages/integrations/image/src/vendor/squoosh/webp/webp_enc.d.ts
@@ -0,0 +1,42 @@
+export interface EncodeOptions {
+ quality: number
+ target_size: number
+ target_PSNR: number
+ method: number
+ sns_strength: number
+ filter_strength: number
+ filter_sharpness: number
+ filter_type: number
+ partitions: number
+ segments: number
+ pass: number
+ show_compressed: number
+ preprocessing: number
+ autofilter: number
+ partition_limit: number
+ alpha_compression: number
+ alpha_filtering: number
+ alpha_quality: number
+ lossless: number
+ exact: number
+ image_hint: number
+ emulate_jpeg_size: number
+ thread_level: number
+ low_memory: number
+ near_lossless: number
+ use_delta_palette: number
+ use_sharp_yuv: number
+}
+
+export interface WebPModule extends EmscriptenWasm.Module {
+ encode(
+ data: BufferSource,
+ width: number,
+ height: number,
+ options: EncodeOptions
+ ): Uint8Array
+}
+
+declare var moduleFactory: EmscriptenWasm.ModuleFactory
+
+export default moduleFactory
diff --git a/packages/integrations/image/src/vendor/squoosh/webp/webp_node_dec.ts b/packages/integrations/image/src/vendor/squoosh/webp/webp_node_dec.ts
new file mode 100644
index 000000000..6188bc3a9
--- /dev/null
+++ b/packages/integrations/image/src/vendor/squoosh/webp/webp_node_dec.ts
@@ -0,0 +1,1648 @@
+/* eslint-disable */
+// @ts-nocheck
+import { createRequire } from 'module';
+const require = createRequire(import.meta.url);
+import { dirname } from '../emscripten-utils.js';
+
+var Module = (function () {
+ return function (Module) {
+ Module = Module || {}
+
+ var Module = typeof Module !== 'undefined' ? Module : {}
+ var readyPromiseResolve, readyPromiseReject
+ Module['ready'] = new Promise(function (resolve, reject) {
+ readyPromiseResolve = resolve
+ readyPromiseReject = reject
+ })
+ var moduleOverrides = {}
+ var key
+ for (key in Module) {
+ if (Module.hasOwnProperty(key)) {
+ moduleOverrides[key] = Module[key]
+ }
+ }
+ var arguments_ = []
+ var thisProgram = './this.program'
+ var quit_ = function (status, toThrow) {
+ throw toThrow
+ }
+ var ENVIRONMENT_IS_WEB = false
+ var ENVIRONMENT_IS_WORKER = false
+ var ENVIRONMENT_IS_NODE = true
+ var scriptDirectory = ''
+ function locateFile(path) {
+ if (Module['locateFile']) {
+ return Module['locateFile'](path, scriptDirectory)
+ }
+ return scriptDirectory + path
+ }
+ var read_, readBinary
+ var nodeFS
+ var nodePath
+ if (ENVIRONMENT_IS_NODE) {
+ if (ENVIRONMENT_IS_WORKER) {
+ scriptDirectory = require('path').dirname(scriptDirectory) + '/'
+ } else {
+ scriptDirectory = dirname(import.meta.url) + '/'
+ }
+ read_ = function shell_read(filename, binary) {
+ if (!nodeFS) nodeFS = require('fs')
+ if (!nodePath) nodePath = require('path')
+ filename = nodePath['normalize'](filename)
+ return nodeFS['readFileSync'](filename, binary ? null : 'utf8')
+ }
+ readBinary = function readBinary(filename) {
+ var ret = read_(filename, true)
+ if (!ret.buffer) {
+ ret = new Uint8Array(ret)
+ }
+ assert(ret.buffer)
+ return ret
+ }
+ if (process['argv'].length > 1) {
+ thisProgram = process['argv'][1].replace(/\\/g, '/')
+ }
+ arguments_ = process['argv'].slice(2)
+ quit_ = function (status) {
+ process['exit'](status)
+ }
+ Module['inspect'] = function () {
+ return '[Emscripten Module object]'
+ }
+ } else {
+ }
+ var out = Module['print'] || console.log.bind(console)
+ var err = Module['printErr'] || console.warn.bind(console)
+ for (key in moduleOverrides) {
+ if (moduleOverrides.hasOwnProperty(key)) {
+ Module[key] = moduleOverrides[key]
+ }
+ }
+ moduleOverrides = null
+ if (Module['arguments']) arguments_ = Module['arguments']
+ if (Module['thisProgram']) thisProgram = Module['thisProgram']
+ if (Module['quit']) quit_ = Module['quit']
+ var wasmBinary
+ if (Module['wasmBinary']) wasmBinary = Module['wasmBinary']
+ var noExitRuntime = Module['noExitRuntime'] || true
+ if (typeof WebAssembly !== 'object') {
+ abort('no native wasm support detected')
+ }
+ var wasmMemory
+ var ABORT = false
+ var EXITSTATUS
+ function assert(condition, text) {
+ if (!condition) {
+ abort('Assertion failed: ' + text)
+ }
+ }
+ var UTF8Decoder = new TextDecoder('utf8')
+ function UTF8ToString(ptr, maxBytesToRead) {
+ if (!ptr) return ''
+ var maxPtr = ptr + maxBytesToRead
+ for (var end = ptr; !(end >= maxPtr) && HEAPU8[end]; ) ++end
+ return UTF8Decoder.decode(HEAPU8.subarray(ptr, end))
+ }
+ function stringToUTF8Array(str, heap, outIdx, maxBytesToWrite) {
+ if (!(maxBytesToWrite > 0)) return 0
+ var startIdx = outIdx
+ var endIdx = outIdx + maxBytesToWrite - 1
+ for (var i = 0; i < str.length; ++i) {
+ var u = str.charCodeAt(i)
+ if (u >= 55296 && u <= 57343) {
+ var u1 = str.charCodeAt(++i)
+ u = (65536 + ((u & 1023) << 10)) | (u1 & 1023)
+ }
+ if (u <= 127) {
+ if (outIdx >= endIdx) break
+ heap[outIdx++] = u
+ } else if (u <= 2047) {
+ if (outIdx + 1 >= endIdx) break
+ heap[outIdx++] = 192 | (u >> 6)
+ heap[outIdx++] = 128 | (u & 63)
+ } else if (u <= 65535) {
+ if (outIdx + 2 >= endIdx) break
+ heap[outIdx++] = 224 | (u >> 12)
+ heap[outIdx++] = 128 | ((u >> 6) & 63)
+ heap[outIdx++] = 128 | (u & 63)
+ } else {
+ if (outIdx + 3 >= endIdx) break
+ heap[outIdx++] = 240 | (u >> 18)
+ heap[outIdx++] = 128 | ((u >> 12) & 63)
+ heap[outIdx++] = 128 | ((u >> 6) & 63)
+ heap[outIdx++] = 128 | (u & 63)
+ }
+ }
+ heap[outIdx] = 0
+ return outIdx - startIdx
+ }
+ function stringToUTF8(str, outPtr, maxBytesToWrite) {
+ return stringToUTF8Array(str, HEAPU8, outPtr, maxBytesToWrite)
+ }
+ function lengthBytesUTF8(str) {
+ var len = 0
+ for (var i = 0; i < str.length; ++i) {
+ var u = str.charCodeAt(i)
+ if (u >= 55296 && u <= 57343)
+ u = (65536 + ((u & 1023) << 10)) | (str.charCodeAt(++i) & 1023)
+ if (u <= 127) ++len
+ else if (u <= 2047) len += 2
+ else if (u <= 65535) len += 3
+ else len += 4
+ }
+ return len
+ }
+ var UTF16Decoder = new TextDecoder('utf-16le')
+ function UTF16ToString(ptr, maxBytesToRead) {
+ var endPtr = ptr
+ var idx = endPtr >> 1
+ var maxIdx = idx + maxBytesToRead / 2
+ while (!(idx >= maxIdx) && HEAPU16[idx]) ++idx
+ endPtr = idx << 1
+ return UTF16Decoder.decode(HEAPU8.subarray(ptr, endPtr))
+ var str = ''
+ for (var i = 0; !(i >= maxBytesToRead / 2); ++i) {
+ var codeUnit = HEAP16[(ptr + i * 2) >> 1]
+ if (codeUnit == 0) break
+ str += String.fromCharCode(codeUnit)
+ }
+ return str
+ }
+ function stringToUTF16(str, outPtr, maxBytesToWrite) {
+ if (maxBytesToWrite === undefined) {
+ maxBytesToWrite = 2147483647
+ }
+ if (maxBytesToWrite < 2) return 0
+ maxBytesToWrite -= 2
+ var startPtr = outPtr
+ var numCharsToWrite =
+ maxBytesToWrite < str.length * 2 ? maxBytesToWrite / 2 : str.length
+ for (var i = 0; i < numCharsToWrite; ++i) {
+ var codeUnit = str.charCodeAt(i)
+ HEAP16[outPtr >> 1] = codeUnit
+ outPtr += 2
+ }
+ HEAP16[outPtr >> 1] = 0
+ return outPtr - startPtr
+ }
+ function lengthBytesUTF16(str) {
+ return str.length * 2
+ }
+ function UTF32ToString(ptr, maxBytesToRead) {
+ var i = 0
+ var str = ''
+ while (!(i >= maxBytesToRead / 4)) {
+ var utf32 = HEAP32[(ptr + i * 4) >> 2]
+ if (utf32 == 0) break
+ ++i
+ if (utf32 >= 65536) {
+ var ch = utf32 - 65536
+ str += String.fromCharCode(55296 | (ch >> 10), 56320 | (ch & 1023))
+ } else {
+ str += String.fromCharCode(utf32)
+ }
+ }
+ return str
+ }
+ function stringToUTF32(str, outPtr, maxBytesToWrite) {
+ if (maxBytesToWrite === undefined) {
+ maxBytesToWrite = 2147483647
+ }
+ if (maxBytesToWrite < 4) return 0
+ var startPtr = outPtr
+ var endPtr = startPtr + maxBytesToWrite - 4
+ for (var i = 0; i < str.length; ++i) {
+ var codeUnit = str.charCodeAt(i)
+ if (codeUnit >= 55296 && codeUnit <= 57343) {
+ var trailSurrogate = str.charCodeAt(++i)
+ codeUnit =
+ (65536 + ((codeUnit & 1023) << 10)) | (trailSurrogate & 1023)
+ }
+ HEAP32[outPtr >> 2] = codeUnit
+ outPtr += 4
+ if (outPtr + 4 > endPtr) break
+ }
+ HEAP32[outPtr >> 2] = 0
+ return outPtr - startPtr
+ }
+ function lengthBytesUTF32(str) {
+ var len = 0
+ for (var i = 0; i < str.length; ++i) {
+ var codeUnit = str.charCodeAt(i)
+ if (codeUnit >= 55296 && codeUnit <= 57343) ++i
+ len += 4
+ }
+ return len
+ }
+ function alignUp(x, multiple) {
+ if (x % multiple > 0) {
+ x += multiple - (x % multiple)
+ }
+ return x
+ }
+ var buffer,
+ HEAP8,
+ HEAPU8,
+ HEAP16,
+ HEAPU16,
+ HEAP32,
+ HEAPU32,
+ HEAPF32,
+ HEAPF64
+ function updateGlobalBufferAndViews(buf) {
+ buffer = buf
+ Module['HEAP8'] = HEAP8 = new Int8Array(buf)
+ Module['HEAP16'] = HEAP16 = new Int16Array(buf)
+ Module['HEAP32'] = HEAP32 = new Int32Array(buf)
+ Module['HEAPU8'] = HEAPU8 = new Uint8Array(buf)
+ Module['HEAPU16'] = HEAPU16 = new Uint16Array(buf)
+ Module['HEAPU32'] = HEAPU32 = new Uint32Array(buf)
+ Module['HEAPF32'] = HEAPF32 = new Float32Array(buf)
+ Module['HEAPF64'] = HEAPF64 = new Float64Array(buf)
+ }
+ var INITIAL_MEMORY = Module['INITIAL_MEMORY'] || 16777216
+ var wasmTable
+ var __ATPRERUN__ = []
+ var __ATINIT__ = []
+ var __ATPOSTRUN__ = []
+ var runtimeInitialized = false
+ function preRun() {
+ if (Module['preRun']) {
+ if (typeof Module['preRun'] == 'function')
+ Module['preRun'] = [Module['preRun']]
+ while (Module['preRun'].length) {
+ addOnPreRun(Module['preRun'].shift())
+ }
+ }
+ callRuntimeCallbacks(__ATPRERUN__)
+ }
+ function initRuntime() {
+ runtimeInitialized = true
+ callRuntimeCallbacks(__ATINIT__)
+ }
+ function postRun() {
+ if (Module['postRun']) {
+ if (typeof Module['postRun'] == 'function')
+ Module['postRun'] = [Module['postRun']]
+ while (Module['postRun'].length) {
+ addOnPostRun(Module['postRun'].shift())
+ }
+ }
+ callRuntimeCallbacks(__ATPOSTRUN__)
+ }
+ function addOnPreRun(cb) {
+ __ATPRERUN__.unshift(cb)
+ }
+ function addOnInit(cb) {
+ __ATINIT__.unshift(cb)
+ }
+ function addOnPostRun(cb) {
+ __ATPOSTRUN__.unshift(cb)
+ }
+ var runDependencies = 0
+ var runDependencyWatcher = null
+ var dependenciesFulfilled = null
+ function addRunDependency(id) {
+ runDependencies++
+ if (Module['monitorRunDependencies']) {
+ Module['monitorRunDependencies'](runDependencies)
+ }
+ }
+ function removeRunDependency(id) {
+ runDependencies--
+ if (Module['monitorRunDependencies']) {
+ Module['monitorRunDependencies'](runDependencies)
+ }
+ if (runDependencies == 0) {
+ if (runDependencyWatcher !== null) {
+ clearInterval(runDependencyWatcher)
+ runDependencyWatcher = null
+ }
+ if (dependenciesFulfilled) {
+ var callback = dependenciesFulfilled
+ dependenciesFulfilled = null
+ callback()
+ }
+ }
+ }
+ Module['preloadedImages'] = {}
+ Module['preloadedAudios'] = {}
+ function abort(what) {
+ if (Module['onAbort']) {
+ Module['onAbort'](what)
+ }
+ what += ''
+ err(what)
+ ABORT = true
+ EXITSTATUS = 1
+ what = 'abort(' + what + '). Build with -s ASSERTIONS=1 for more info.'
+ var e = new WebAssembly.RuntimeError(what)
+ readyPromiseReject(e)
+ throw e
+ }
+ var dataURIPrefix = 'data:application/octet-stream;base64,'
+ function isDataURI(filename) {
+ return filename.startsWith(dataURIPrefix)
+ }
+ if (Module['locateFile']) {
+ var wasmBinaryFile = 'webp_node_dec.wasm'
+ if (!isDataURI(wasmBinaryFile)) {
+ wasmBinaryFile = locateFile(wasmBinaryFile)
+ }
+ } else {
+ throw new Error('invariant')
+ }
+ function getBinary(file) {
+ try {
+ if (file == wasmBinaryFile && wasmBinary) {
+ return new Uint8Array(wasmBinary)
+ }
+ if (readBinary) {
+ return readBinary(file)
+ } else {
+ throw 'both async and sync fetching of the wasm failed'
+ }
+ } catch (err) {
+ abort(err)
+ }
+ }
+ function getBinaryPromise() {
+ if (!wasmBinary && (ENVIRONMENT_IS_WEB || ENVIRONMENT_IS_WORKER)) {
+ if (typeof fetch === 'function') {
+ return fetch(wasmBinaryFile, { credentials: 'same-origin' })
+ .then(function (response) {
+ if (!response['ok']) {
+ throw (
+ "failed to load wasm binary file at '" + wasmBinaryFile + "'"
+ )
+ }
+ return response['arrayBuffer']()
+ })
+ .catch(function () {
+ return getBinary(wasmBinaryFile)
+ })
+ }
+ }
+ return Promise.resolve().then(function () {
+ return getBinary(wasmBinaryFile)
+ })
+ }
+ function createWasm() {
+ var info = { a: asmLibraryArg }
+ function receiveInstance(instance, module) {
+ var exports = instance.exports
+ Module['asm'] = exports
+ wasmMemory = Module['asm']['s']
+ updateGlobalBufferAndViews(wasmMemory.buffer)
+ wasmTable = Module['asm']['y']
+ addOnInit(Module['asm']['t'])
+ removeRunDependency('wasm-instantiate')
+ }
+ addRunDependency('wasm-instantiate')
+ function receiveInstantiationResult(result) {
+ receiveInstance(result['instance'])
+ }
+ function instantiateArrayBuffer(receiver) {
+ return getBinaryPromise()
+ .then(function (binary) {
+ var result = WebAssembly.instantiate(binary, info)
+ return result
+ })
+ .then(receiver, function (reason) {
+ err('failed to asynchronously prepare wasm: ' + reason)
+ abort(reason)
+ })
+ }
+ function instantiateAsync() {
+ if (
+ !wasmBinary &&
+ typeof WebAssembly.instantiateStreaming === 'function' &&
+ !isDataURI(wasmBinaryFile) &&
+ typeof fetch === 'function'
+ ) {
+ return fetch(wasmBinaryFile, { credentials: 'same-origin' }).then(
+ function (response) {
+ var result = WebAssembly.instantiateStreaming(response, info)
+ return result.then(receiveInstantiationResult, function (reason) {
+ err('wasm streaming compile failed: ' + reason)
+ err('falling back to ArrayBuffer instantiation')
+ return instantiateArrayBuffer(receiveInstantiationResult)
+ })
+ }
+ )
+ } else {
+ return instantiateArrayBuffer(receiveInstantiationResult)
+ }
+ }
+ if (Module['instantiateWasm']) {
+ try {
+ var exports = Module['instantiateWasm'](info, receiveInstance)
+ return exports
+ } catch (e) {
+ err('Module.instantiateWasm callback failed with error: ' + e)
+ return false
+ }
+ }
+ instantiateAsync().catch(readyPromiseReject)
+ return {}
+ }
+ function callRuntimeCallbacks(callbacks) {
+ while (callbacks.length > 0) {
+ var callback = callbacks.shift()
+ if (typeof callback == 'function') {
+ callback(Module)
+ continue
+ }
+ var func = callback.func
+ if (typeof func === 'number') {
+ if (callback.arg === undefined) {
+ wasmTable.get(func)()
+ } else {
+ wasmTable.get(func)(callback.arg)
+ }
+ } else {
+ func(callback.arg === undefined ? null : callback.arg)
+ }
+ }
+ }
+ function _atexit(func, arg) {}
+ function ___cxa_thread_atexit(a0, a1) {
+ return _atexit(a0, a1)
+ }
+ function __embind_register_bigint(
+ primitiveType,
+ name,
+ size,
+ minRange,
+ maxRange
+ ) {}
+ function getShiftFromSize(size) {
+ switch (size) {
+ case 1:
+ return 0
+ case 2:
+ return 1
+ case 4:
+ return 2
+ case 8:
+ return 3
+ default:
+ throw new TypeError('Unknown type size: ' + size)
+ }
+ }
+ function embind_init_charCodes() {
+ var codes = new Array(256)
+ for (var i = 0; i < 256; ++i) {
+ codes[i] = String.fromCharCode(i)
+ }
+ embind_charCodes = codes
+ }
+ var embind_charCodes = undefined
+ function readLatin1String(ptr) {
+ var ret = ''
+ var c = ptr
+ while (HEAPU8[c]) {
+ ret += embind_charCodes[HEAPU8[c++]]
+ }
+ return ret
+ }
+ var awaitingDependencies = {}
+ var registeredTypes = {}
+ var typeDependencies = {}
+ var char_0 = 48
+ var char_9 = 57
+ function makeLegalFunctionName(name) {
+ if (undefined === name) {
+ return '_unknown'
+ }
+ name = name.replace(/[^a-zA-Z0-9_]/g, '$')
+ var f = name.charCodeAt(0)
+ if (f >= char_0 && f <= char_9) {
+ return '_' + name
+ } else {
+ return name
+ }
+ }
+ function createNamedFunction(name, body) {
+ name = makeLegalFunctionName(name)
+ return new Function(
+ 'body',
+ 'return function ' +
+ name +
+ '() {\n' +
+ ' "use strict";' +
+ ' return body.apply(this, arguments);\n' +
+ '};\n'
+ )(body)
+ }
+ function extendError(baseErrorType, errorName) {
+ var errorClass = createNamedFunction(errorName, function (message) {
+ this.name = errorName
+ this.message = message
+ var stack = new Error(message).stack
+ if (stack !== undefined) {
+ this.stack =
+ this.toString() + '\n' + stack.replace(/^Error(:[^\n]*)?\n/, '')
+ }
+ })
+ errorClass.prototype = Object.create(baseErrorType.prototype)
+ errorClass.prototype.constructor = errorClass
+ errorClass.prototype.toString = function () {
+ if (this.message === undefined) {
+ return this.name
+ } else {
+ return this.name + ': ' + this.message
+ }
+ }
+ return errorClass
+ }
+ var BindingError = undefined
+ function throwBindingError(message) {
+ throw new BindingError(message)
+ }
+ var InternalError = undefined
+ function throwInternalError(message) {
+ throw new InternalError(message)
+ }
+ function whenDependentTypesAreResolved(
+ myTypes,
+ dependentTypes,
+ getTypeConverters
+ ) {
+ myTypes.forEach(function (type) {
+ typeDependencies[type] = dependentTypes
+ })
+ function onComplete(typeConverters) {
+ var myTypeConverters = getTypeConverters(typeConverters)
+ if (myTypeConverters.length !== myTypes.length) {
+ throwInternalError('Mismatched type converter count')
+ }
+ for (var i = 0; i < myTypes.length; ++i) {
+ registerType(myTypes[i], myTypeConverters[i])
+ }
+ }
+ var typeConverters = new Array(dependentTypes.length)
+ var unregisteredTypes = []
+ var registered = 0
+ dependentTypes.forEach(function (dt, i) {
+ if (registeredTypes.hasOwnProperty(dt)) {
+ typeConverters[i] = registeredTypes[dt]
+ } else {
+ unregisteredTypes.push(dt)
+ if (!awaitingDependencies.hasOwnProperty(dt)) {
+ awaitingDependencies[dt] = []
+ }
+ awaitingDependencies[dt].push(function () {
+ typeConverters[i] = registeredTypes[dt]
+ ++registered
+ if (registered === unregisteredTypes.length) {
+ onComplete(typeConverters)
+ }
+ })
+ }
+ })
+ if (0 === unregisteredTypes.length) {
+ onComplete(typeConverters)
+ }
+ }
+ function registerType(rawType, registeredInstance, options) {
+ options = options || {}
+ if (!('argPackAdvance' in registeredInstance)) {
+ throw new TypeError(
+ 'registerType registeredInstance requires argPackAdvance'
+ )
+ }
+ var name = registeredInstance.name
+ if (!rawType) {
+ throwBindingError(
+ 'type "' + name + '" must have a positive integer typeid pointer'
+ )
+ }
+ if (registeredTypes.hasOwnProperty(rawType)) {
+ if (options.ignoreDuplicateRegistrations) {
+ return
+ } else {
+ throwBindingError("Cannot register type '" + name + "' twice")
+ }
+ }
+ registeredTypes[rawType] = registeredInstance
+ delete typeDependencies[rawType]
+ if (awaitingDependencies.hasOwnProperty(rawType)) {
+ var callbacks = awaitingDependencies[rawType]
+ delete awaitingDependencies[rawType]
+ callbacks.forEach(function (cb) {
+ cb()
+ })
+ }
+ }
+ function __embind_register_bool(
+ rawType,
+ name,
+ size,
+ trueValue,
+ falseValue
+ ) {
+ var shift = getShiftFromSize(size)
+ name = readLatin1String(name)
+ registerType(rawType, {
+ name: name,
+ fromWireType: function (wt) {
+ return !!wt
+ },
+ toWireType: function (destructors, o) {
+ return o ? trueValue : falseValue
+ },
+ argPackAdvance: 8,
+ readValueFromPointer: function (pointer) {
+ var heap
+ if (size === 1) {
+ heap = HEAP8
+ } else if (size === 2) {
+ heap = HEAP16
+ } else if (size === 4) {
+ heap = HEAP32
+ } else {
+ throw new TypeError('Unknown boolean type size: ' + name)
+ }
+ return this['fromWireType'](heap[pointer >> shift])
+ },
+ destructorFunction: null,
+ })
+ }
+ var emval_free_list = []
+ var emval_handle_array = [
+ {},
+ { value: undefined },
+ { value: null },
+ { value: true },
+ { value: false },
+ ]
+ function __emval_decref(handle) {
+ if (handle > 4 && 0 === --emval_handle_array[handle].refcount) {
+ emval_handle_array[handle] = undefined
+ emval_free_list.push(handle)
+ }
+ }
+ function count_emval_handles() {
+ var count = 0
+ for (var i = 5; i < emval_handle_array.length; ++i) {
+ if (emval_handle_array[i] !== undefined) {
+ ++count
+ }
+ }
+ return count
+ }
+ function get_first_emval() {
+ for (var i = 5; i < emval_handle_array.length; ++i) {
+ if (emval_handle_array[i] !== undefined) {
+ return emval_handle_array[i]
+ }
+ }
+ return null
+ }
+ function init_emval() {
+ Module['count_emval_handles'] = count_emval_handles
+ Module['get_first_emval'] = get_first_emval
+ }
+ function __emval_register(value) {
+ switch (value) {
+ case undefined: {
+ return 1
+ }
+ case null: {
+ return 2
+ }
+ case true: {
+ return 3
+ }
+ case false: {
+ return 4
+ }
+ default: {
+ var handle = emval_free_list.length
+ ? emval_free_list.pop()
+ : emval_handle_array.length
+ emval_handle_array[handle] = { refcount: 1, value: value }
+ return handle
+ }
+ }
+ }
+ function simpleReadValueFromPointer(pointer) {
+ return this['fromWireType'](HEAPU32[pointer >> 2])
+ }
+ function __embind_register_emval(rawType, name) {
+ name = readLatin1String(name)
+ registerType(rawType, {
+ name: name,
+ fromWireType: function (handle) {
+ var rv = emval_handle_array[handle].value
+ __emval_decref(handle)
+ return rv
+ },
+ toWireType: function (destructors, value) {
+ return __emval_register(value)
+ },
+ argPackAdvance: 8,
+ readValueFromPointer: simpleReadValueFromPointer,
+ destructorFunction: null,
+ })
+ }
+ function _embind_repr(v) {
+ if (v === null) {
+ return 'null'
+ }
+ var t = typeof v
+ if (t === 'object' || t === 'array' || t === 'function') {
+ return v.toString()
+ } else {
+ return '' + v
+ }
+ }
+ function floatReadValueFromPointer(name, shift) {
+ switch (shift) {
+ case 2:
+ return function (pointer) {
+ return this['fromWireType'](HEAPF32[pointer >> 2])
+ }
+ case 3:
+ return function (pointer) {
+ return this['fromWireType'](HEAPF64[pointer >> 3])
+ }
+ default:
+ throw new TypeError('Unknown float type: ' + name)
+ }
+ }
+ function __embind_register_float(rawType, name, size) {
+ var shift = getShiftFromSize(size)
+ name = readLatin1String(name)
+ registerType(rawType, {
+ name: name,
+ fromWireType: function (value) {
+ return value
+ },
+ toWireType: function (destructors, value) {
+ if (typeof value !== 'number' && typeof value !== 'boolean') {
+ throw new TypeError(
+ 'Cannot convert "' + _embind_repr(value) + '" to ' + this.name
+ )
+ }
+ return value
+ },
+ argPackAdvance: 8,
+ readValueFromPointer: floatReadValueFromPointer(name, shift),
+ destructorFunction: null,
+ })
+ }
+ function new_(constructor, argumentList) {
+ if (!(constructor instanceof Function)) {
+ throw new TypeError(
+ 'new_ called with constructor type ' +
+ typeof constructor +
+ ' which is not a function'
+ )
+ }
+ var dummy = createNamedFunction(
+ constructor.name || 'unknownFunctionName',
+ function () {}
+ )
+ dummy.prototype = constructor.prototype
+ var obj = new dummy()
+ var r = constructor.apply(obj, argumentList)
+ return r instanceof Object ? r : obj
+ }
+ function runDestructors(destructors) {
+ while (destructors.length) {
+ var ptr = destructors.pop()
+ var del = destructors.pop()
+ del(ptr)
+ }
+ }
+ function craftInvokerFunction(
+ humanName,
+ argTypes,
+ classType,
+ cppInvokerFunc,
+ cppTargetFunc
+ ) {
+ var argCount = argTypes.length
+ if (argCount < 2) {
+ throwBindingError(
+ "argTypes array size mismatch! Must at least get return value and 'this' types!"
+ )
+ }
+ var isClassMethodFunc = argTypes[1] !== null && classType !== null
+ var needsDestructorStack = false
+ for (var i = 1; i < argTypes.length; ++i) {
+ if (
+ argTypes[i] !== null &&
+ argTypes[i].destructorFunction === undefined
+ ) {
+ needsDestructorStack = true
+ break
+ }
+ }
+ var returns = argTypes[0].name !== 'void'
+ var argsList = ''
+ var argsListWired = ''
+ for (var i = 0; i < argCount - 2; ++i) {
+ argsList += (i !== 0 ? ', ' : '') + 'arg' + i
+ argsListWired += (i !== 0 ? ', ' : '') + 'arg' + i + 'Wired'
+ }
+ var invokerFnBody =
+ 'return function ' +
+ makeLegalFunctionName(humanName) +
+ '(' +
+ argsList +
+ ') {\n' +
+ 'if (arguments.length !== ' +
+ (argCount - 2) +
+ ') {\n' +
+ "throwBindingError('function " +
+ humanName +
+ " called with ' + arguments.length + ' arguments, expected " +
+ (argCount - 2) +
+ " args!');\n" +
+ '}\n'
+ if (needsDestructorStack) {
+ invokerFnBody += 'var destructors = [];\n'
+ }
+ var dtorStack = needsDestructorStack ? 'destructors' : 'null'
+ var args1 = [
+ 'throwBindingError',
+ 'invoker',
+ 'fn',
+ 'runDestructors',
+ 'retType',
+ 'classParam',
+ ]
+ var args2 = [
+ throwBindingError,
+ cppInvokerFunc,
+ cppTargetFunc,
+ runDestructors,
+ argTypes[0],
+ argTypes[1],
+ ]
+ if (isClassMethodFunc) {
+ invokerFnBody +=
+ 'var thisWired = classParam.toWireType(' + dtorStack + ', this);\n'
+ }
+ for (var i = 0; i < argCount - 2; ++i) {
+ invokerFnBody +=
+ 'var arg' +
+ i +
+ 'Wired = argType' +
+ i +
+ '.toWireType(' +
+ dtorStack +
+ ', arg' +
+ i +
+ '); // ' +
+ argTypes[i + 2].name +
+ '\n'
+ args1.push('argType' + i)
+ args2.push(argTypes[i + 2])
+ }
+ if (isClassMethodFunc) {
+ argsListWired =
+ 'thisWired' + (argsListWired.length > 0 ? ', ' : '') + argsListWired
+ }
+ invokerFnBody +=
+ (returns ? 'var rv = ' : '') +
+ 'invoker(fn' +
+ (argsListWired.length > 0 ? ', ' : '') +
+ argsListWired +
+ ');\n'
+ if (needsDestructorStack) {
+ invokerFnBody += 'runDestructors(destructors);\n'
+ } else {
+ for (var i = isClassMethodFunc ? 1 : 2; i < argTypes.length; ++i) {
+ var paramName = i === 1 ? 'thisWired' : 'arg' + (i - 2) + 'Wired'
+ if (argTypes[i].destructorFunction !== null) {
+ invokerFnBody +=
+ paramName +
+ '_dtor(' +
+ paramName +
+ '); // ' +
+ argTypes[i].name +
+ '\n'
+ args1.push(paramName + '_dtor')
+ args2.push(argTypes[i].destructorFunction)
+ }
+ }
+ }
+ if (returns) {
+ invokerFnBody +=
+ 'var ret = retType.fromWireType(rv);\n' + 'return ret;\n'
+ } else {
+ }
+ invokerFnBody += '}\n'
+ args1.push(invokerFnBody)
+ var invokerFunction = new_(Function, args1).apply(null, args2)
+ return invokerFunction
+ }
+ function ensureOverloadTable(proto, methodName, humanName) {
+ if (undefined === proto[methodName].overloadTable) {
+ var prevFunc = proto[methodName]
+ proto[methodName] = function () {
+ if (
+ !proto[methodName].overloadTable.hasOwnProperty(arguments.length)
+ ) {
+ throwBindingError(
+ "Function '" +
+ humanName +
+ "' called with an invalid number of arguments (" +
+ arguments.length +
+ ') - expects one of (' +
+ proto[methodName].overloadTable +
+ ')!'
+ )
+ }
+ return proto[methodName].overloadTable[arguments.length].apply(
+ this,
+ arguments
+ )
+ }
+ proto[methodName].overloadTable = []
+ proto[methodName].overloadTable[prevFunc.argCount] = prevFunc
+ }
+ }
+ function exposePublicSymbol(name, value, numArguments) {
+ if (Module.hasOwnProperty(name)) {
+ if (
+ undefined === numArguments ||
+ (undefined !== Module[name].overloadTable &&
+ undefined !== Module[name].overloadTable[numArguments])
+ ) {
+ throwBindingError("Cannot register public name '" + name + "' twice")
+ }
+ ensureOverloadTable(Module, name, name)
+ if (Module.hasOwnProperty(numArguments)) {
+ throwBindingError(
+ 'Cannot register multiple overloads of a function with the same number of arguments (' +
+ numArguments +
+ ')!'
+ )
+ }
+ Module[name].overloadTable[numArguments] = value
+ } else {
+ Module[name] = value
+ if (undefined !== numArguments) {
+ Module[name].numArguments = numArguments
+ }
+ }
+ }
+ function heap32VectorToArray(count, firstElement) {
+ var array = []
+ for (var i = 0; i < count; i++) {
+ array.push(HEAP32[(firstElement >> 2) + i])
+ }
+ return array
+ }
+ function replacePublicSymbol(name, value, numArguments) {
+ if (!Module.hasOwnProperty(name)) {
+ throwInternalError('Replacing nonexistant public symbol')
+ }
+ if (
+ undefined !== Module[name].overloadTable &&
+ undefined !== numArguments
+ ) {
+ Module[name].overloadTable[numArguments] = value
+ } else {
+ Module[name] = value
+ Module[name].argCount = numArguments
+ }
+ }
+ function dynCallLegacy(sig, ptr, args) {
+ var f = Module['dynCall_' + sig]
+ return args && args.length
+ ? f.apply(null, [ptr].concat(args))
+ : f.call(null, ptr)
+ }
+ function dynCall(sig, ptr, args) {
+ if (sig.includes('j')) {
+ return dynCallLegacy(sig, ptr, args)
+ }
+ return wasmTable.get(ptr).apply(null, args)
+ }
+ function getDynCaller(sig, ptr) {
+ var argCache = []
+ return function () {
+ argCache.length = arguments.length
+ for (var i = 0; i < arguments.length; i++) {
+ argCache[i] = arguments[i]
+ }
+ return dynCall(sig, ptr, argCache)
+ }
+ }
+ function embind__requireFunction(signature, rawFunction) {
+ signature = readLatin1String(signature)
+ function makeDynCaller() {
+ if (signature.includes('j')) {
+ return getDynCaller(signature, rawFunction)
+ }
+ return wasmTable.get(rawFunction)
+ }
+ var fp = makeDynCaller()
+ if (typeof fp !== 'function') {
+ throwBindingError(
+ 'unknown function pointer with signature ' +
+ signature +
+ ': ' +
+ rawFunction
+ )
+ }
+ return fp
+ }
+ var UnboundTypeError = undefined
+ function getTypeName(type) {
+ var ptr = ___getTypeName(type)
+ var rv = readLatin1String(ptr)
+ _free(ptr)
+ return rv
+ }
+ function throwUnboundTypeError(message, types) {
+ var unboundTypes = []
+ var seen = {}
+ function visit(type) {
+ if (seen[type]) {
+ return
+ }
+ if (registeredTypes[type]) {
+ return
+ }
+ if (typeDependencies[type]) {
+ typeDependencies[type].forEach(visit)
+ return
+ }
+ unboundTypes.push(type)
+ seen[type] = true
+ }
+ types.forEach(visit)
+ throw new UnboundTypeError(
+ message + ': ' + unboundTypes.map(getTypeName).join([', '])
+ )
+ }
+ function __embind_register_function(
+ name,
+ argCount,
+ rawArgTypesAddr,
+ signature,
+ rawInvoker,
+ fn
+ ) {
+ var argTypes = heap32VectorToArray(argCount, rawArgTypesAddr)
+ name = readLatin1String(name)
+ rawInvoker = embind__requireFunction(signature, rawInvoker)
+ exposePublicSymbol(
+ name,
+ function () {
+ throwUnboundTypeError(
+ 'Cannot call ' + name + ' due to unbound types',
+ argTypes
+ )
+ },
+ argCount - 1
+ )
+ whenDependentTypesAreResolved([], argTypes, function (argTypes) {
+ var invokerArgsArray = [argTypes[0], null].concat(argTypes.slice(1))
+ replacePublicSymbol(
+ name,
+ craftInvokerFunction(name, invokerArgsArray, null, rawInvoker, fn),
+ argCount - 1
+ )
+ return []
+ })
+ }
+ function integerReadValueFromPointer(name, shift, signed) {
+ switch (shift) {
+ case 0:
+ return signed
+ ? function readS8FromPointer(pointer) {
+ return HEAP8[pointer]
+ }
+ : function readU8FromPointer(pointer) {
+ return HEAPU8[pointer]
+ }
+ case 1:
+ return signed
+ ? function readS16FromPointer(pointer) {
+ return HEAP16[pointer >> 1]
+ }
+ : function readU16FromPointer(pointer) {
+ return HEAPU16[pointer >> 1]
+ }
+ case 2:
+ return signed
+ ? function readS32FromPointer(pointer) {
+ return HEAP32[pointer >> 2]
+ }
+ : function readU32FromPointer(pointer) {
+ return HEAPU32[pointer >> 2]
+ }
+ default:
+ throw new TypeError('Unknown integer type: ' + name)
+ }
+ }
+ function __embind_register_integer(
+ primitiveType,
+ name,
+ size,
+ minRange,
+ maxRange
+ ) {
+ name = readLatin1String(name)
+ if (maxRange === -1) {
+ maxRange = 4294967295
+ }
+ var shift = getShiftFromSize(size)
+ var fromWireType = function (value) {
+ return value
+ }
+ if (minRange === 0) {
+ var bitshift = 32 - 8 * size
+ fromWireType = function (value) {
+ return (value << bitshift) >>> bitshift
+ }
+ }
+ var isUnsignedType = name.includes('unsigned')
+ registerType(primitiveType, {
+ name: name,
+ fromWireType: fromWireType,
+ toWireType: function (destructors, value) {
+ if (typeof value !== 'number' && typeof value !== 'boolean') {
+ throw new TypeError(
+ 'Cannot convert "' + _embind_repr(value) + '" to ' + this.name
+ )
+ }
+ if (value < minRange || value > maxRange) {
+ throw new TypeError(
+ 'Passing a number "' +
+ _embind_repr(value) +
+ '" from JS side to C/C++ side to an argument of type "' +
+ name +
+ '", which is outside the valid range [' +
+ minRange +
+ ', ' +
+ maxRange +
+ ']!'
+ )
+ }
+ return isUnsignedType ? value >>> 0 : value | 0
+ },
+ argPackAdvance: 8,
+ readValueFromPointer: integerReadValueFromPointer(
+ name,
+ shift,
+ minRange !== 0
+ ),
+ destructorFunction: null,
+ })
+ }
+ function __embind_register_memory_view(rawType, dataTypeIndex, name) {
+ var typeMapping = [
+ Int8Array,
+ Uint8Array,
+ Int16Array,
+ Uint16Array,
+ Int32Array,
+ Uint32Array,
+ Float32Array,
+ Float64Array,
+ ]
+ var TA = typeMapping[dataTypeIndex]
+ function decodeMemoryView(handle) {
+ handle = handle >> 2
+ var heap = HEAPU32
+ var size = heap[handle]
+ var data = heap[handle + 1]
+ return new TA(buffer, data, size)
+ }
+ name = readLatin1String(name)
+ registerType(
+ rawType,
+ {
+ name: name,
+ fromWireType: decodeMemoryView,
+ argPackAdvance: 8,
+ readValueFromPointer: decodeMemoryView,
+ },
+ { ignoreDuplicateRegistrations: true }
+ )
+ }
+ function __embind_register_std_string(rawType, name) {
+ name = readLatin1String(name)
+ var stdStringIsUTF8 = name === 'std::string'
+ registerType(rawType, {
+ name: name,
+ fromWireType: function (value) {
+ var length = HEAPU32[value >> 2]
+ var str
+ if (stdStringIsUTF8) {
+ var decodeStartPtr = value + 4
+ for (var i = 0; i <= length; ++i) {
+ var currentBytePtr = value + 4 + i
+ if (i == length || HEAPU8[currentBytePtr] == 0) {
+ var maxRead = currentBytePtr - decodeStartPtr
+ var stringSegment = UTF8ToString(decodeStartPtr, maxRead)
+ if (str === undefined) {
+ str = stringSegment
+ } else {
+ str += String.fromCharCode(0)
+ str += stringSegment
+ }
+ decodeStartPtr = currentBytePtr + 1
+ }
+ }
+ } else {
+ var a = new Array(length)
+ for (var i = 0; i < length; ++i) {
+ a[i] = String.fromCharCode(HEAPU8[value + 4 + i])
+ }
+ str = a.join('')
+ }
+ _free(value)
+ return str
+ },
+ toWireType: function (destructors, value) {
+ if (value instanceof ArrayBuffer) {
+ value = new Uint8Array(value)
+ }
+ var getLength
+ var valueIsOfTypeString = typeof value === 'string'
+ if (
+ !(
+ valueIsOfTypeString ||
+ value instanceof Uint8Array ||
+ value instanceof Uint8ClampedArray ||
+ value instanceof Int8Array
+ )
+ ) {
+ throwBindingError('Cannot pass non-string to std::string')
+ }
+ if (stdStringIsUTF8 && valueIsOfTypeString) {
+ getLength = function () {
+ return lengthBytesUTF8(value)
+ }
+ } else {
+ getLength = function () {
+ return value.length
+ }
+ }
+ var length = getLength()
+ var ptr = _malloc(4 + length + 1)
+ HEAPU32[ptr >> 2] = length
+ if (stdStringIsUTF8 && valueIsOfTypeString) {
+ stringToUTF8(value, ptr + 4, length + 1)
+ } else {
+ if (valueIsOfTypeString) {
+ for (var i = 0; i < length; ++i) {
+ var charCode = value.charCodeAt(i)
+ if (charCode > 255) {
+ _free(ptr)
+ throwBindingError(
+ 'String has UTF-16 code units that do not fit in 8 bits'
+ )
+ }
+ HEAPU8[ptr + 4 + i] = charCode
+ }
+ } else {
+ for (var i = 0; i < length; ++i) {
+ HEAPU8[ptr + 4 + i] = value[i]
+ }
+ }
+ }
+ if (destructors !== null) {
+ destructors.push(_free, ptr)
+ }
+ return ptr
+ },
+ argPackAdvance: 8,
+ readValueFromPointer: simpleReadValueFromPointer,
+ destructorFunction: function (ptr) {
+ _free(ptr)
+ },
+ })
+ }
+ function __embind_register_std_wstring(rawType, charSize, name) {
+ name = readLatin1String(name)
+ var decodeString, encodeString, getHeap, lengthBytesUTF, shift
+ if (charSize === 2) {
+ decodeString = UTF16ToString
+ encodeString = stringToUTF16
+ lengthBytesUTF = lengthBytesUTF16
+ getHeap = function () {
+ return HEAPU16
+ }
+ shift = 1
+ } else if (charSize === 4) {
+ decodeString = UTF32ToString
+ encodeString = stringToUTF32
+ lengthBytesUTF = lengthBytesUTF32
+ getHeap = function () {
+ return HEAPU32
+ }
+ shift = 2
+ }
+ registerType(rawType, {
+ name: name,
+ fromWireType: function (value) {
+ var length = HEAPU32[value >> 2]
+ var HEAP = getHeap()
+ var str
+ var decodeStartPtr = value + 4
+ for (var i = 0; i <= length; ++i) {
+ var currentBytePtr = value + 4 + i * charSize
+ if (i == length || HEAP[currentBytePtr >> shift] == 0) {
+ var maxReadBytes = currentBytePtr - decodeStartPtr
+ var stringSegment = decodeString(decodeStartPtr, maxReadBytes)
+ if (str === undefined) {
+ str = stringSegment
+ } else {
+ str += String.fromCharCode(0)
+ str += stringSegment
+ }
+ decodeStartPtr = currentBytePtr + charSize
+ }
+ }
+ _free(value)
+ return str
+ },
+ toWireType: function (destructors, value) {
+ if (!(typeof value === 'string')) {
+ throwBindingError(
+ 'Cannot pass non-string to C++ string type ' + name
+ )
+ }
+ var length = lengthBytesUTF(value)
+ var ptr = _malloc(4 + length + charSize)
+ HEAPU32[ptr >> 2] = length >> shift
+ encodeString(value, ptr + 4, length + charSize)
+ if (destructors !== null) {
+ destructors.push(_free, ptr)
+ }
+ return ptr
+ },
+ argPackAdvance: 8,
+ readValueFromPointer: simpleReadValueFromPointer,
+ destructorFunction: function (ptr) {
+ _free(ptr)
+ },
+ })
+ }
+ function __embind_register_void(rawType, name) {
+ name = readLatin1String(name)
+ registerType(rawType, {
+ isVoid: true,
+ name: name,
+ argPackAdvance: 0,
+ fromWireType: function () {
+ return undefined
+ },
+ toWireType: function (destructors, o) {
+ return undefined
+ },
+ })
+ }
+ var emval_symbols = {}
+ function getStringOrSymbol(address) {
+ var symbol = emval_symbols[address]
+ if (symbol === undefined) {
+ return readLatin1String(address)
+ } else {
+ return symbol
+ }
+ }
+ function emval_get_global() {
+ if (typeof globalThis === 'object') {
+ return globalThis
+ }
+ return (function () {
+ return Function
+ })()('return this')()
+ }
+ function __emval_get_global(name) {
+ if (name === 0) {
+ return __emval_register(emval_get_global())
+ } else {
+ name = getStringOrSymbol(name)
+ return __emval_register(emval_get_global()[name])
+ }
+ }
+ function __emval_incref(handle) {
+ if (handle > 4) {
+ emval_handle_array[handle].refcount += 1
+ }
+ }
+ function requireRegisteredType(rawType, humanName) {
+ var impl = registeredTypes[rawType]
+ if (undefined === impl) {
+ throwBindingError(
+ humanName + ' has unknown type ' + getTypeName(rawType)
+ )
+ }
+ return impl
+ }
+ function craftEmvalAllocator(argCount) {
+ var argsList = ''
+ for (var i = 0; i < argCount; ++i) {
+ argsList += (i !== 0 ? ', ' : '') + 'arg' + i
+ }
+ var functionBody =
+ 'return function emval_allocator_' +
+ argCount +
+ '(constructor, argTypes, args) {\n'
+ for (var i = 0; i < argCount; ++i) {
+ functionBody +=
+ 'var argType' +
+ i +
+ " = requireRegisteredType(Module['HEAP32'][(argTypes >>> 2) + " +
+ i +
+ '], "parameter ' +
+ i +
+ '");\n' +
+ 'var arg' +
+ i +
+ ' = argType' +
+ i +
+ '.readValueFromPointer(args);\n' +
+ 'args += argType' +
+ i +
+ "['argPackAdvance'];\n"
+ }
+ functionBody +=
+ 'var obj = new constructor(' +
+ argsList +
+ ');\n' +
+ 'return __emval_register(obj);\n' +
+ '}\n'
+ return new Function(
+ 'requireRegisteredType',
+ 'Module',
+ '__emval_register',
+ functionBody
+ )(requireRegisteredType, Module, __emval_register)
+ }
+ var emval_newers = {}
+ function requireHandle(handle) {
+ if (!handle) {
+ throwBindingError('Cannot use deleted val. handle = ' + handle)
+ }
+ return emval_handle_array[handle].value
+ }
+ function __emval_new(handle, argCount, argTypes, args) {
+ handle = requireHandle(handle)
+ var newer = emval_newers[argCount]
+ if (!newer) {
+ newer = craftEmvalAllocator(argCount)
+ emval_newers[argCount] = newer
+ }
+ return newer(handle, argTypes, args)
+ }
+ function _abort() {
+ abort()
+ }
+ function _emscripten_memcpy_big(dest, src, num) {
+ HEAPU8.copyWithin(dest, src, src + num)
+ }
+ function emscripten_realloc_buffer(size) {
+ try {
+ wasmMemory.grow((size - buffer.byteLength + 65535) >>> 16)
+ updateGlobalBufferAndViews(wasmMemory.buffer)
+ return 1
+ } catch (e) {}
+ }
+ function _emscripten_resize_heap(requestedSize) {
+ var oldSize = HEAPU8.length
+ requestedSize = requestedSize >>> 0
+ var maxHeapSize = 2147483648
+ if (requestedSize > maxHeapSize) {
+ return false
+ }
+ for (var cutDown = 1; cutDown <= 4; cutDown *= 2) {
+ var overGrownHeapSize = oldSize * (1 + 0.2 / cutDown)
+ overGrownHeapSize = Math.min(
+ overGrownHeapSize,
+ requestedSize + 100663296
+ )
+ var newSize = Math.min(
+ maxHeapSize,
+ alignUp(Math.max(requestedSize, overGrownHeapSize), 65536)
+ )
+ var replacement = emscripten_realloc_buffer(newSize)
+ if (replacement) {
+ return true
+ }
+ }
+ return false
+ }
+ embind_init_charCodes()
+ BindingError = Module['BindingError'] = extendError(Error, 'BindingError')
+ InternalError = Module['InternalError'] = extendError(
+ Error,
+ 'InternalError'
+ )
+ init_emval()
+ UnboundTypeError = Module['UnboundTypeError'] = extendError(
+ Error,
+ 'UnboundTypeError'
+ )
+ var asmLibraryArg = {
+ e: ___cxa_thread_atexit,
+ p: __embind_register_bigint,
+ n: __embind_register_bool,
+ r: __embind_register_emval,
+ m: __embind_register_float,
+ i: __embind_register_function,
+ b: __embind_register_integer,
+ a: __embind_register_memory_view,
+ h: __embind_register_std_string,
+ f: __embind_register_std_wstring,
+ o: __embind_register_void,
+ c: __emval_decref,
+ d: __emval_get_global,
+ j: __emval_incref,
+ k: __emval_new,
+ l: _abort,
+ q: _emscripten_memcpy_big,
+ g: _emscripten_resize_heap,
+ }
+ var asm = createWasm()
+ var ___wasm_call_ctors = (Module['___wasm_call_ctors'] = function () {
+ return (___wasm_call_ctors = Module['___wasm_call_ctors'] =
+ Module['asm']['t']).apply(null, arguments)
+ })
+ var _malloc = (Module['_malloc'] = function () {
+ return (_malloc = Module['_malloc'] = Module['asm']['u']).apply(
+ null,
+ arguments
+ )
+ })
+ var _free = (Module['_free'] = function () {
+ return (_free = Module['_free'] = Module['asm']['v']).apply(
+ null,
+ arguments
+ )
+ })
+ var ___getTypeName = (Module['___getTypeName'] = function () {
+ return (___getTypeName = Module['___getTypeName'] =
+ Module['asm']['w']).apply(null, arguments)
+ })
+ var ___embind_register_native_and_builtin_types = (Module[
+ '___embind_register_native_and_builtin_types'
+ ] = function () {
+ return (___embind_register_native_and_builtin_types = Module[
+ '___embind_register_native_and_builtin_types'
+ ] =
+ Module['asm']['x']).apply(null, arguments)
+ })
+ var calledRun
+ dependenciesFulfilled = function runCaller() {
+ if (!calledRun) run()
+ if (!calledRun) dependenciesFulfilled = runCaller
+ }
+ function run(args) {
+ args = args || arguments_
+ if (runDependencies > 0) {
+ return
+ }
+ preRun()
+ if (runDependencies > 0) {
+ return
+ }
+ function doRun() {
+ if (calledRun) return
+ calledRun = true
+ Module['calledRun'] = true
+ if (ABORT) return
+ initRuntime()
+ readyPromiseResolve(Module)
+ if (Module['onRuntimeInitialized']) Module['onRuntimeInitialized']()
+ postRun()
+ }
+ if (Module['setStatus']) {
+ Module['setStatus']('Running...')
+ setTimeout(function () {
+ setTimeout(function () {
+ Module['setStatus']('')
+ }, 1)
+ doRun()
+ }, 1)
+ } else {
+ doRun()
+ }
+ }
+ Module['run'] = run
+ if (Module['preInit']) {
+ if (typeof Module['preInit'] == 'function')
+ Module['preInit'] = [Module['preInit']]
+ while (Module['preInit'].length > 0) {
+ Module['preInit'].pop()()
+ }
+ }
+ run()
+
+ return Module.ready
+ }
+})()
+export default Module
diff --git a/packages/integrations/image/src/vendor/squoosh/webp/webp_node_dec.wasm b/packages/integrations/image/src/vendor/squoosh/webp/webp_node_dec.wasm
new file mode 100644
index 000000000..5df324336
Binary files /dev/null and b/packages/integrations/image/src/vendor/squoosh/webp/webp_node_dec.wasm differ
diff --git a/packages/integrations/image/src/vendor/squoosh/webp/webp_node_enc.ts b/packages/integrations/image/src/vendor/squoosh/webp/webp_node_enc.ts
new file mode 100644
index 000000000..70f98b730
--- /dev/null
+++ b/packages/integrations/image/src/vendor/squoosh/webp/webp_node_enc.ts
@@ -0,0 +1,1833 @@
+/* eslint-disable */
+// @ts-nocheck
+import { createRequire } from 'module';
+const require = createRequire(import.meta.url);
+import { dirname } from '../emscripten-utils.js';
+
+var Module = (function () {
+ return function (Module) {
+ Module = Module || {}
+
+ var Module = typeof Module !== 'undefined' ? Module : {}
+ var readyPromiseResolve, readyPromiseReject
+ Module['ready'] = new Promise(function (resolve, reject) {
+ readyPromiseResolve = resolve
+ readyPromiseReject = reject
+ })
+ var moduleOverrides = {}
+ var key
+ for (key in Module) {
+ if (Module.hasOwnProperty(key)) {
+ moduleOverrides[key] = Module[key]
+ }
+ }
+ var arguments_ = []
+ var thisProgram = './this.program'
+ var quit_ = function (status, toThrow) {
+ throw toThrow
+ }
+ var ENVIRONMENT_IS_WEB = false
+ var ENVIRONMENT_IS_WORKER = false
+ var ENVIRONMENT_IS_NODE = true
+ var scriptDirectory = ''
+ function locateFile(path) {
+ if (Module['locateFile']) {
+ return Module['locateFile'](path, scriptDirectory)
+ }
+ return scriptDirectory + path
+ }
+ var read_, readBinary
+ var nodeFS
+ var nodePath
+ if (ENVIRONMENT_IS_NODE) {
+ if (ENVIRONMENT_IS_WORKER) {
+ scriptDirectory = require('path').dirname(scriptDirectory) + '/'
+ } else {
+ scriptDirectory = dirname(import.meta.url) + '/'
+ }
+ read_ = function shell_read(filename, binary) {
+ if (!nodeFS) nodeFS = require('fs')
+ if (!nodePath) nodePath = require('path')
+ filename = nodePath['normalize'](filename)
+ return nodeFS['readFileSync'](filename, binary ? null : 'utf8')
+ }
+ readBinary = function readBinary(filename) {
+ var ret = read_(filename, true)
+ if (!ret.buffer) {
+ ret = new Uint8Array(ret)
+ }
+ assert(ret.buffer)
+ return ret
+ }
+ if (process['argv'].length > 1) {
+ thisProgram = process['argv'][1].replace(/\\/g, '/')
+ }
+ arguments_ = process['argv'].slice(2)
+ quit_ = function (status) {
+ process['exit'](status)
+ }
+ Module['inspect'] = function () {
+ return '[Emscripten Module object]'
+ }
+ } else {
+ }
+ var out = Module['print'] || console.log.bind(console)
+ var err = Module['printErr'] || console.warn.bind(console)
+ for (key in moduleOverrides) {
+ if (moduleOverrides.hasOwnProperty(key)) {
+ Module[key] = moduleOverrides[key]
+ }
+ }
+ moduleOverrides = null
+ if (Module['arguments']) arguments_ = Module['arguments']
+ if (Module['thisProgram']) thisProgram = Module['thisProgram']
+ if (Module['quit']) quit_ = Module['quit']
+ var wasmBinary
+ if (Module['wasmBinary']) wasmBinary = Module['wasmBinary']
+ var noExitRuntime = Module['noExitRuntime'] || true
+ if (typeof WebAssembly !== 'object') {
+ abort('no native wasm support detected')
+ }
+ var wasmMemory
+ var ABORT = false
+ var EXITSTATUS
+ function assert(condition, text) {
+ if (!condition) {
+ abort('Assertion failed: ' + text)
+ }
+ }
+ var UTF8Decoder = new TextDecoder('utf8')
+ function UTF8ToString(ptr, maxBytesToRead) {
+ if (!ptr) return ''
+ var maxPtr = ptr + maxBytesToRead
+ for (var end = ptr; !(end >= maxPtr) && HEAPU8[end]; ) ++end
+ return UTF8Decoder.decode(HEAPU8.subarray(ptr, end))
+ }
+ function stringToUTF8Array(str, heap, outIdx, maxBytesToWrite) {
+ if (!(maxBytesToWrite > 0)) return 0
+ var startIdx = outIdx
+ var endIdx = outIdx + maxBytesToWrite - 1
+ for (var i = 0; i < str.length; ++i) {
+ var u = str.charCodeAt(i)
+ if (u >= 55296 && u <= 57343) {
+ var u1 = str.charCodeAt(++i)
+ u = (65536 + ((u & 1023) << 10)) | (u1 & 1023)
+ }
+ if (u <= 127) {
+ if (outIdx >= endIdx) break
+ heap[outIdx++] = u
+ } else if (u <= 2047) {
+ if (outIdx + 1 >= endIdx) break
+ heap[outIdx++] = 192 | (u >> 6)
+ heap[outIdx++] = 128 | (u & 63)
+ } else if (u <= 65535) {
+ if (outIdx + 2 >= endIdx) break
+ heap[outIdx++] = 224 | (u >> 12)
+ heap[outIdx++] = 128 | ((u >> 6) & 63)
+ heap[outIdx++] = 128 | (u & 63)
+ } else {
+ if (outIdx + 3 >= endIdx) break
+ heap[outIdx++] = 240 | (u >> 18)
+ heap[outIdx++] = 128 | ((u >> 12) & 63)
+ heap[outIdx++] = 128 | ((u >> 6) & 63)
+ heap[outIdx++] = 128 | (u & 63)
+ }
+ }
+ heap[outIdx] = 0
+ return outIdx - startIdx
+ }
+ function stringToUTF8(str, outPtr, maxBytesToWrite) {
+ return stringToUTF8Array(str, HEAPU8, outPtr, maxBytesToWrite)
+ }
+ function lengthBytesUTF8(str) {
+ var len = 0
+ for (var i = 0; i < str.length; ++i) {
+ var u = str.charCodeAt(i)
+ if (u >= 55296 && u <= 57343)
+ u = (65536 + ((u & 1023) << 10)) | (str.charCodeAt(++i) & 1023)
+ if (u <= 127) ++len
+ else if (u <= 2047) len += 2
+ else if (u <= 65535) len += 3
+ else len += 4
+ }
+ return len
+ }
+ var UTF16Decoder = new TextDecoder('utf-16le')
+ function UTF16ToString(ptr, maxBytesToRead) {
+ var endPtr = ptr
+ var idx = endPtr >> 1
+ var maxIdx = idx + maxBytesToRead / 2
+ while (!(idx >= maxIdx) && HEAPU16[idx]) ++idx
+ endPtr = idx << 1
+ return UTF16Decoder.decode(HEAPU8.subarray(ptr, endPtr))
+ var str = ''
+ for (var i = 0; !(i >= maxBytesToRead / 2); ++i) {
+ var codeUnit = HEAP16[(ptr + i * 2) >> 1]
+ if (codeUnit == 0) break
+ str += String.fromCharCode(codeUnit)
+ }
+ return str
+ }
+ function stringToUTF16(str, outPtr, maxBytesToWrite) {
+ if (maxBytesToWrite === undefined) {
+ maxBytesToWrite = 2147483647
+ }
+ if (maxBytesToWrite < 2) return 0
+ maxBytesToWrite -= 2
+ var startPtr = outPtr
+ var numCharsToWrite =
+ maxBytesToWrite < str.length * 2 ? maxBytesToWrite / 2 : str.length
+ for (var i = 0; i < numCharsToWrite; ++i) {
+ var codeUnit = str.charCodeAt(i)
+ HEAP16[outPtr >> 1] = codeUnit
+ outPtr += 2
+ }
+ HEAP16[outPtr >> 1] = 0
+ return outPtr - startPtr
+ }
+ function lengthBytesUTF16(str) {
+ return str.length * 2
+ }
+ function UTF32ToString(ptr, maxBytesToRead) {
+ var i = 0
+ var str = ''
+ while (!(i >= maxBytesToRead / 4)) {
+ var utf32 = HEAP32[(ptr + i * 4) >> 2]
+ if (utf32 == 0) break
+ ++i
+ if (utf32 >= 65536) {
+ var ch = utf32 - 65536
+ str += String.fromCharCode(55296 | (ch >> 10), 56320 | (ch & 1023))
+ } else {
+ str += String.fromCharCode(utf32)
+ }
+ }
+ return str
+ }
+ function stringToUTF32(str, outPtr, maxBytesToWrite) {
+ if (maxBytesToWrite === undefined) {
+ maxBytesToWrite = 2147483647
+ }
+ if (maxBytesToWrite < 4) return 0
+ var startPtr = outPtr
+ var endPtr = startPtr + maxBytesToWrite - 4
+ for (var i = 0; i < str.length; ++i) {
+ var codeUnit = str.charCodeAt(i)
+ if (codeUnit >= 55296 && codeUnit <= 57343) {
+ var trailSurrogate = str.charCodeAt(++i)
+ codeUnit =
+ (65536 + ((codeUnit & 1023) << 10)) | (trailSurrogate & 1023)
+ }
+ HEAP32[outPtr >> 2] = codeUnit
+ outPtr += 4
+ if (outPtr + 4 > endPtr) break
+ }
+ HEAP32[outPtr >> 2] = 0
+ return outPtr - startPtr
+ }
+ function lengthBytesUTF32(str) {
+ var len = 0
+ for (var i = 0; i < str.length; ++i) {
+ var codeUnit = str.charCodeAt(i)
+ if (codeUnit >= 55296 && codeUnit <= 57343) ++i
+ len += 4
+ }
+ return len
+ }
+ function alignUp(x, multiple) {
+ if (x % multiple > 0) {
+ x += multiple - (x % multiple)
+ }
+ return x
+ }
+ var buffer,
+ HEAP8,
+ HEAPU8,
+ HEAP16,
+ HEAPU16,
+ HEAP32,
+ HEAPU32,
+ HEAPF32,
+ HEAPF64
+ function updateGlobalBufferAndViews(buf) {
+ buffer = buf
+ Module['HEAP8'] = HEAP8 = new Int8Array(buf)
+ Module['HEAP16'] = HEAP16 = new Int16Array(buf)
+ Module['HEAP32'] = HEAP32 = new Int32Array(buf)
+ Module['HEAPU8'] = HEAPU8 = new Uint8Array(buf)
+ Module['HEAPU16'] = HEAPU16 = new Uint16Array(buf)
+ Module['HEAPU32'] = HEAPU32 = new Uint32Array(buf)
+ Module['HEAPF32'] = HEAPF32 = new Float32Array(buf)
+ Module['HEAPF64'] = HEAPF64 = new Float64Array(buf)
+ }
+ var INITIAL_MEMORY = Module['INITIAL_MEMORY'] || 16777216
+ var wasmTable
+ var __ATPRERUN__ = []
+ var __ATINIT__ = []
+ var __ATPOSTRUN__ = []
+ var runtimeInitialized = false
+ function preRun() {
+ if (Module['preRun']) {
+ if (typeof Module['preRun'] == 'function')
+ Module['preRun'] = [Module['preRun']]
+ while (Module['preRun'].length) {
+ addOnPreRun(Module['preRun'].shift())
+ }
+ }
+ callRuntimeCallbacks(__ATPRERUN__)
+ }
+ function initRuntime() {
+ runtimeInitialized = true
+ callRuntimeCallbacks(__ATINIT__)
+ }
+ function postRun() {
+ if (Module['postRun']) {
+ if (typeof Module['postRun'] == 'function')
+ Module['postRun'] = [Module['postRun']]
+ while (Module['postRun'].length) {
+ addOnPostRun(Module['postRun'].shift())
+ }
+ }
+ callRuntimeCallbacks(__ATPOSTRUN__)
+ }
+ function addOnPreRun(cb) {
+ __ATPRERUN__.unshift(cb)
+ }
+ function addOnInit(cb) {
+ __ATINIT__.unshift(cb)
+ }
+ function addOnPostRun(cb) {
+ __ATPOSTRUN__.unshift(cb)
+ }
+ var runDependencies = 0
+ var runDependencyWatcher = null
+ var dependenciesFulfilled = null
+ function addRunDependency(id) {
+ runDependencies++
+ if (Module['monitorRunDependencies']) {
+ Module['monitorRunDependencies'](runDependencies)
+ }
+ }
+ function removeRunDependency(id) {
+ runDependencies--
+ if (Module['monitorRunDependencies']) {
+ Module['monitorRunDependencies'](runDependencies)
+ }
+ if (runDependencies == 0) {
+ if (runDependencyWatcher !== null) {
+ clearInterval(runDependencyWatcher)
+ runDependencyWatcher = null
+ }
+ if (dependenciesFulfilled) {
+ var callback = dependenciesFulfilled
+ dependenciesFulfilled = null
+ callback()
+ }
+ }
+ }
+ Module['preloadedImages'] = {}
+ Module['preloadedAudios'] = {}
+ function abort(what) {
+ if (Module['onAbort']) {
+ Module['onAbort'](what)
+ }
+ what += ''
+ err(what)
+ ABORT = true
+ EXITSTATUS = 1
+ what = 'abort(' + what + '). Build with -s ASSERTIONS=1 for more info.'
+ var e = new WebAssembly.RuntimeError(what)
+ readyPromiseReject(e)
+ throw e
+ }
+ var dataURIPrefix = 'data:application/octet-stream;base64,'
+ function isDataURI(filename) {
+ return filename.startsWith(dataURIPrefix)
+ }
+ if (Module['locateFile']) {
+ var wasmBinaryFile = 'webp_node_enc.wasm'
+ if (!isDataURI(wasmBinaryFile)) {
+ wasmBinaryFile = locateFile(wasmBinaryFile)
+ }
+ } else {
+ throw new Error('invariant')
+ }
+ function getBinary(file) {
+ try {
+ if (file == wasmBinaryFile && wasmBinary) {
+ return new Uint8Array(wasmBinary)
+ }
+ if (readBinary) {
+ return readBinary(file)
+ } else {
+ throw 'both async and sync fetching of the wasm failed'
+ }
+ } catch (err) {
+ abort(err)
+ }
+ }
+ function getBinaryPromise() {
+ if (!wasmBinary && (ENVIRONMENT_IS_WEB || ENVIRONMENT_IS_WORKER)) {
+ if (typeof fetch === 'function') {
+ return fetch(wasmBinaryFile, { credentials: 'same-origin' })
+ .then(function (response) {
+ if (!response['ok']) {
+ throw (
+ "failed to load wasm binary file at '" + wasmBinaryFile + "'"
+ )
+ }
+ return response['arrayBuffer']()
+ })
+ .catch(function () {
+ return getBinary(wasmBinaryFile)
+ })
+ }
+ }
+ return Promise.resolve().then(function () {
+ return getBinary(wasmBinaryFile)
+ })
+ }
+ function createWasm() {
+ var info = { a: asmLibraryArg }
+ function receiveInstance(instance, module) {
+ var exports = instance.exports
+ Module['asm'] = exports
+ wasmMemory = Module['asm']['x']
+ updateGlobalBufferAndViews(wasmMemory.buffer)
+ wasmTable = Module['asm']['D']
+ addOnInit(Module['asm']['y'])
+ removeRunDependency('wasm-instantiate')
+ }
+ addRunDependency('wasm-instantiate')
+ function receiveInstantiationResult(result) {
+ receiveInstance(result['instance'])
+ }
+ function instantiateArrayBuffer(receiver) {
+ return getBinaryPromise()
+ .then(function (binary) {
+ var result = WebAssembly.instantiate(binary, info)
+ return result
+ })
+ .then(receiver, function (reason) {
+ err('failed to asynchronously prepare wasm: ' + reason)
+ abort(reason)
+ })
+ }
+ function instantiateAsync() {
+ if (
+ !wasmBinary &&
+ typeof WebAssembly.instantiateStreaming === 'function' &&
+ !isDataURI(wasmBinaryFile) &&
+ typeof fetch === 'function'
+ ) {
+ return fetch(wasmBinaryFile, { credentials: 'same-origin' }).then(
+ function (response) {
+ var result = WebAssembly.instantiateStreaming(response, info)
+ return result.then(receiveInstantiationResult, function (reason) {
+ err('wasm streaming compile failed: ' + reason)
+ err('falling back to ArrayBuffer instantiation')
+ return instantiateArrayBuffer(receiveInstantiationResult)
+ })
+ }
+ )
+ } else {
+ return instantiateArrayBuffer(receiveInstantiationResult)
+ }
+ }
+ if (Module['instantiateWasm']) {
+ try {
+ var exports = Module['instantiateWasm'](info, receiveInstance)
+ return exports
+ } catch (e) {
+ err('Module.instantiateWasm callback failed with error: ' + e)
+ return false
+ }
+ }
+ instantiateAsync().catch(readyPromiseReject)
+ return {}
+ }
+ function callRuntimeCallbacks(callbacks) {
+ while (callbacks.length > 0) {
+ var callback = callbacks.shift()
+ if (typeof callback == 'function') {
+ callback(Module)
+ continue
+ }
+ var func = callback.func
+ if (typeof func === 'number') {
+ if (callback.arg === undefined) {
+ wasmTable.get(func)()
+ } else {
+ wasmTable.get(func)(callback.arg)
+ }
+ } else {
+ func(callback.arg === undefined ? null : callback.arg)
+ }
+ }
+ }
+ function _atexit(func, arg) {}
+ function ___cxa_thread_atexit(a0, a1) {
+ return _atexit(a0, a1)
+ }
+ var structRegistrations = {}
+ function runDestructors(destructors) {
+ while (destructors.length) {
+ var ptr = destructors.pop()
+ var del = destructors.pop()
+ del(ptr)
+ }
+ }
+ function simpleReadValueFromPointer(pointer) {
+ return this['fromWireType'](HEAPU32[pointer >> 2])
+ }
+ var awaitingDependencies = {}
+ var registeredTypes = {}
+ var typeDependencies = {}
+ var char_0 = 48
+ var char_9 = 57
+ function makeLegalFunctionName(name) {
+ if (undefined === name) {
+ return '_unknown'
+ }
+ name = name.replace(/[^a-zA-Z0-9_]/g, '$')
+ var f = name.charCodeAt(0)
+ if (f >= char_0 && f <= char_9) {
+ return '_' + name
+ } else {
+ return name
+ }
+ }
+ function createNamedFunction(name, body) {
+ name = makeLegalFunctionName(name)
+ return new Function(
+ 'body',
+ 'return function ' +
+ name +
+ '() {\n' +
+ ' "use strict";' +
+ ' return body.apply(this, arguments);\n' +
+ '};\n'
+ )(body)
+ }
+ function extendError(baseErrorType, errorName) {
+ var errorClass = createNamedFunction(errorName, function (message) {
+ this.name = errorName
+ this.message = message
+ var stack = new Error(message).stack
+ if (stack !== undefined) {
+ this.stack =
+ this.toString() + '\n' + stack.replace(/^Error(:[^\n]*)?\n/, '')
+ }
+ })
+ errorClass.prototype = Object.create(baseErrorType.prototype)
+ errorClass.prototype.constructor = errorClass
+ errorClass.prototype.toString = function () {
+ if (this.message === undefined) {
+ return this.name
+ } else {
+ return this.name + ': ' + this.message
+ }
+ }
+ return errorClass
+ }
+ var InternalError = undefined
+ function throwInternalError(message) {
+ throw new InternalError(message)
+ }
+ function whenDependentTypesAreResolved(
+ myTypes,
+ dependentTypes,
+ getTypeConverters
+ ) {
+ myTypes.forEach(function (type) {
+ typeDependencies[type] = dependentTypes
+ })
+ function onComplete(typeConverters) {
+ var myTypeConverters = getTypeConverters(typeConverters)
+ if (myTypeConverters.length !== myTypes.length) {
+ throwInternalError('Mismatched type converter count')
+ }
+ for (var i = 0; i < myTypes.length; ++i) {
+ registerType(myTypes[i], myTypeConverters[i])
+ }
+ }
+ var typeConverters = new Array(dependentTypes.length)
+ var unregisteredTypes = []
+ var registered = 0
+ dependentTypes.forEach(function (dt, i) {
+ if (registeredTypes.hasOwnProperty(dt)) {
+ typeConverters[i] = registeredTypes[dt]
+ } else {
+ unregisteredTypes.push(dt)
+ if (!awaitingDependencies.hasOwnProperty(dt)) {
+ awaitingDependencies[dt] = []
+ }
+ awaitingDependencies[dt].push(function () {
+ typeConverters[i] = registeredTypes[dt]
+ ++registered
+ if (registered === unregisteredTypes.length) {
+ onComplete(typeConverters)
+ }
+ })
+ }
+ })
+ if (0 === unregisteredTypes.length) {
+ onComplete(typeConverters)
+ }
+ }
+ function __embind_finalize_value_object(structType) {
+ var reg = structRegistrations[structType]
+ delete structRegistrations[structType]
+ var rawConstructor = reg.rawConstructor
+ var rawDestructor = reg.rawDestructor
+ var fieldRecords = reg.fields
+ var fieldTypes = fieldRecords
+ .map(function (field) {
+ return field.getterReturnType
+ })
+ .concat(
+ fieldRecords.map(function (field) {
+ return field.setterArgumentType
+ })
+ )
+ whenDependentTypesAreResolved(
+ [structType],
+ fieldTypes,
+ function (fieldTypes) {
+ var fields = {}
+ fieldRecords.forEach(function (field, i) {
+ var fieldName = field.fieldName
+ var getterReturnType = fieldTypes[i]
+ var getter = field.getter
+ var getterContext = field.getterContext
+ var setterArgumentType = fieldTypes[i + fieldRecords.length]
+ var setter = field.setter
+ var setterContext = field.setterContext
+ fields[fieldName] = {
+ read: function (ptr) {
+ return getterReturnType['fromWireType'](
+ getter(getterContext, ptr)
+ )
+ },
+ write: function (ptr, o) {
+ var destructors = []
+ setter(
+ setterContext,
+ ptr,
+ setterArgumentType['toWireType'](destructors, o)
+ )
+ runDestructors(destructors)
+ },
+ }
+ })
+ return [
+ {
+ name: reg.name,
+ fromWireType: function (ptr) {
+ var rv = {}
+ for (var i in fields) {
+ rv[i] = fields[i].read(ptr)
+ }
+ rawDestructor(ptr)
+ return rv
+ },
+ toWireType: function (destructors, o) {
+ for (var fieldName in fields) {
+ if (!(fieldName in o)) {
+ throw new TypeError('Missing field: "' + fieldName + '"')
+ }
+ }
+ var ptr = rawConstructor()
+ for (fieldName in fields) {
+ fields[fieldName].write(ptr, o[fieldName])
+ }
+ if (destructors !== null) {
+ destructors.push(rawDestructor, ptr)
+ }
+ return ptr
+ },
+ argPackAdvance: 8,
+ readValueFromPointer: simpleReadValueFromPointer,
+ destructorFunction: rawDestructor,
+ },
+ ]
+ }
+ )
+ }
+ function __embind_register_bigint(
+ primitiveType,
+ name,
+ size,
+ minRange,
+ maxRange
+ ) {}
+ function getShiftFromSize(size) {
+ switch (size) {
+ case 1:
+ return 0
+ case 2:
+ return 1
+ case 4:
+ return 2
+ case 8:
+ return 3
+ default:
+ throw new TypeError('Unknown type size: ' + size)
+ }
+ }
+ function embind_init_charCodes() {
+ var codes = new Array(256)
+ for (var i = 0; i < 256; ++i) {
+ codes[i] = String.fromCharCode(i)
+ }
+ embind_charCodes = codes
+ }
+ var embind_charCodes = undefined
+ function readLatin1String(ptr) {
+ var ret = ''
+ var c = ptr
+ while (HEAPU8[c]) {
+ ret += embind_charCodes[HEAPU8[c++]]
+ }
+ return ret
+ }
+ var BindingError = undefined
+ function throwBindingError(message) {
+ throw new BindingError(message)
+ }
+ function registerType(rawType, registeredInstance, options) {
+ options = options || {}
+ if (!('argPackAdvance' in registeredInstance)) {
+ throw new TypeError(
+ 'registerType registeredInstance requires argPackAdvance'
+ )
+ }
+ var name = registeredInstance.name
+ if (!rawType) {
+ throwBindingError(
+ 'type "' + name + '" must have a positive integer typeid pointer'
+ )
+ }
+ if (registeredTypes.hasOwnProperty(rawType)) {
+ if (options.ignoreDuplicateRegistrations) {
+ return
+ } else {
+ throwBindingError("Cannot register type '" + name + "' twice")
+ }
+ }
+ registeredTypes[rawType] = registeredInstance
+ delete typeDependencies[rawType]
+ if (awaitingDependencies.hasOwnProperty(rawType)) {
+ var callbacks = awaitingDependencies[rawType]
+ delete awaitingDependencies[rawType]
+ callbacks.forEach(function (cb) {
+ cb()
+ })
+ }
+ }
+ function __embind_register_bool(
+ rawType,
+ name,
+ size,
+ trueValue,
+ falseValue
+ ) {
+ var shift = getShiftFromSize(size)
+ name = readLatin1String(name)
+ registerType(rawType, {
+ name: name,
+ fromWireType: function (wt) {
+ return !!wt
+ },
+ toWireType: function (destructors, o) {
+ return o ? trueValue : falseValue
+ },
+ argPackAdvance: 8,
+ readValueFromPointer: function (pointer) {
+ var heap
+ if (size === 1) {
+ heap = HEAP8
+ } else if (size === 2) {
+ heap = HEAP16
+ } else if (size === 4) {
+ heap = HEAP32
+ } else {
+ throw new TypeError('Unknown boolean type size: ' + name)
+ }
+ return this['fromWireType'](heap[pointer >> shift])
+ },
+ destructorFunction: null,
+ })
+ }
+ var emval_free_list = []
+ var emval_handle_array = [
+ {},
+ { value: undefined },
+ { value: null },
+ { value: true },
+ { value: false },
+ ]
+ function __emval_decref(handle) {
+ if (handle > 4 && 0 === --emval_handle_array[handle].refcount) {
+ emval_handle_array[handle] = undefined
+ emval_free_list.push(handle)
+ }
+ }
+ function count_emval_handles() {
+ var count = 0
+ for (var i = 5; i < emval_handle_array.length; ++i) {
+ if (emval_handle_array[i] !== undefined) {
+ ++count
+ }
+ }
+ return count
+ }
+ function get_first_emval() {
+ for (var i = 5; i < emval_handle_array.length; ++i) {
+ if (emval_handle_array[i] !== undefined) {
+ return emval_handle_array[i]
+ }
+ }
+ return null
+ }
+ function init_emval() {
+ Module['count_emval_handles'] = count_emval_handles
+ Module['get_first_emval'] = get_first_emval
+ }
+ function __emval_register(value) {
+ switch (value) {
+ case undefined: {
+ return 1
+ }
+ case null: {
+ return 2
+ }
+ case true: {
+ return 3
+ }
+ case false: {
+ return 4
+ }
+ default: {
+ var handle = emval_free_list.length
+ ? emval_free_list.pop()
+ : emval_handle_array.length
+ emval_handle_array[handle] = { refcount: 1, value: value }
+ return handle
+ }
+ }
+ }
+ function __embind_register_emval(rawType, name) {
+ name = readLatin1String(name)
+ registerType(rawType, {
+ name: name,
+ fromWireType: function (handle) {
+ var rv = emval_handle_array[handle].value
+ __emval_decref(handle)
+ return rv
+ },
+ toWireType: function (destructors, value) {
+ return __emval_register(value)
+ },
+ argPackAdvance: 8,
+ readValueFromPointer: simpleReadValueFromPointer,
+ destructorFunction: null,
+ })
+ }
+ function ensureOverloadTable(proto, methodName, humanName) {
+ if (undefined === proto[methodName].overloadTable) {
+ var prevFunc = proto[methodName]
+ proto[methodName] = function () {
+ if (
+ !proto[methodName].overloadTable.hasOwnProperty(arguments.length)
+ ) {
+ throwBindingError(
+ "Function '" +
+ humanName +
+ "' called with an invalid number of arguments (" +
+ arguments.length +
+ ') - expects one of (' +
+ proto[methodName].overloadTable +
+ ')!'
+ )
+ }
+ return proto[methodName].overloadTable[arguments.length].apply(
+ this,
+ arguments
+ )
+ }
+ proto[methodName].overloadTable = []
+ proto[methodName].overloadTable[prevFunc.argCount] = prevFunc
+ }
+ }
+ function exposePublicSymbol(name, value, numArguments) {
+ if (Module.hasOwnProperty(name)) {
+ if (
+ undefined === numArguments ||
+ (undefined !== Module[name].overloadTable &&
+ undefined !== Module[name].overloadTable[numArguments])
+ ) {
+ throwBindingError("Cannot register public name '" + name + "' twice")
+ }
+ ensureOverloadTable(Module, name, name)
+ if (Module.hasOwnProperty(numArguments)) {
+ throwBindingError(
+ 'Cannot register multiple overloads of a function with the same number of arguments (' +
+ numArguments +
+ ')!'
+ )
+ }
+ Module[name].overloadTable[numArguments] = value
+ } else {
+ Module[name] = value
+ if (undefined !== numArguments) {
+ Module[name].numArguments = numArguments
+ }
+ }
+ }
+ function enumReadValueFromPointer(name, shift, signed) {
+ switch (shift) {
+ case 0:
+ return function (pointer) {
+ var heap = signed ? HEAP8 : HEAPU8
+ return this['fromWireType'](heap[pointer])
+ }
+ case 1:
+ return function (pointer) {
+ var heap = signed ? HEAP16 : HEAPU16
+ return this['fromWireType'](heap[pointer >> 1])
+ }
+ case 2:
+ return function (pointer) {
+ var heap = signed ? HEAP32 : HEAPU32
+ return this['fromWireType'](heap[pointer >> 2])
+ }
+ default:
+ throw new TypeError('Unknown integer type: ' + name)
+ }
+ }
+ function __embind_register_enum(rawType, name, size, isSigned) {
+ var shift = getShiftFromSize(size)
+ name = readLatin1String(name)
+ function ctor() {}
+ ctor.values = {}
+ registerType(rawType, {
+ name: name,
+ constructor: ctor,
+ fromWireType: function (c) {
+ return this.constructor.values[c]
+ },
+ toWireType: function (destructors, c) {
+ return c.value
+ },
+ argPackAdvance: 8,
+ readValueFromPointer: enumReadValueFromPointer(name, shift, isSigned),
+ destructorFunction: null,
+ })
+ exposePublicSymbol(name, ctor)
+ }
+ function getTypeName(type) {
+ var ptr = ___getTypeName(type)
+ var rv = readLatin1String(ptr)
+ _free(ptr)
+ return rv
+ }
+ function requireRegisteredType(rawType, humanName) {
+ var impl = registeredTypes[rawType]
+ if (undefined === impl) {
+ throwBindingError(
+ humanName + ' has unknown type ' + getTypeName(rawType)
+ )
+ }
+ return impl
+ }
+ function __embind_register_enum_value(rawEnumType, name, enumValue) {
+ var enumType = requireRegisteredType(rawEnumType, 'enum')
+ name = readLatin1String(name)
+ var Enum = enumType.constructor
+ var Value = Object.create(enumType.constructor.prototype, {
+ value: { value: enumValue },
+ constructor: {
+ value: createNamedFunction(
+ enumType.name + '_' + name,
+ function () {}
+ ),
+ },
+ })
+ Enum.values[enumValue] = Value
+ Enum[name] = Value
+ }
+ function _embind_repr(v) {
+ if (v === null) {
+ return 'null'
+ }
+ var t = typeof v
+ if (t === 'object' || t === 'array' || t === 'function') {
+ return v.toString()
+ } else {
+ return '' + v
+ }
+ }
+ function floatReadValueFromPointer(name, shift) {
+ switch (shift) {
+ case 2:
+ return function (pointer) {
+ return this['fromWireType'](HEAPF32[pointer >> 2])
+ }
+ case 3:
+ return function (pointer) {
+ return this['fromWireType'](HEAPF64[pointer >> 3])
+ }
+ default:
+ throw new TypeError('Unknown float type: ' + name)
+ }
+ }
+ function __embind_register_float(rawType, name, size) {
+ var shift = getShiftFromSize(size)
+ name = readLatin1String(name)
+ registerType(rawType, {
+ name: name,
+ fromWireType: function (value) {
+ return value
+ },
+ toWireType: function (destructors, value) {
+ if (typeof value !== 'number' && typeof value !== 'boolean') {
+ throw new TypeError(
+ 'Cannot convert "' + _embind_repr(value) + '" to ' + this.name
+ )
+ }
+ return value
+ },
+ argPackAdvance: 8,
+ readValueFromPointer: floatReadValueFromPointer(name, shift),
+ destructorFunction: null,
+ })
+ }
+ function new_(constructor, argumentList) {
+ if (!(constructor instanceof Function)) {
+ throw new TypeError(
+ 'new_ called with constructor type ' +
+ typeof constructor +
+ ' which is not a function'
+ )
+ }
+ var dummy = createNamedFunction(
+ constructor.name || 'unknownFunctionName',
+ function () {}
+ )
+ dummy.prototype = constructor.prototype
+ var obj = new dummy()
+ var r = constructor.apply(obj, argumentList)
+ return r instanceof Object ? r : obj
+ }
+ function craftInvokerFunction(
+ humanName,
+ argTypes,
+ classType,
+ cppInvokerFunc,
+ cppTargetFunc
+ ) {
+ var argCount = argTypes.length
+ if (argCount < 2) {
+ throwBindingError(
+ "argTypes array size mismatch! Must at least get return value and 'this' types!"
+ )
+ }
+ var isClassMethodFunc = argTypes[1] !== null && classType !== null
+ var needsDestructorStack = false
+ for (var i = 1; i < argTypes.length; ++i) {
+ if (
+ argTypes[i] !== null &&
+ argTypes[i].destructorFunction === undefined
+ ) {
+ needsDestructorStack = true
+ break
+ }
+ }
+ var returns = argTypes[0].name !== 'void'
+ var argsList = ''
+ var argsListWired = ''
+ for (var i = 0; i < argCount - 2; ++i) {
+ argsList += (i !== 0 ? ', ' : '') + 'arg' + i
+ argsListWired += (i !== 0 ? ', ' : '') + 'arg' + i + 'Wired'
+ }
+ var invokerFnBody =
+ 'return function ' +
+ makeLegalFunctionName(humanName) +
+ '(' +
+ argsList +
+ ') {\n' +
+ 'if (arguments.length !== ' +
+ (argCount - 2) +
+ ') {\n' +
+ "throwBindingError('function " +
+ humanName +
+ " called with ' + arguments.length + ' arguments, expected " +
+ (argCount - 2) +
+ " args!');\n" +
+ '}\n'
+ if (needsDestructorStack) {
+ invokerFnBody += 'var destructors = [];\n'
+ }
+ var dtorStack = needsDestructorStack ? 'destructors' : 'null'
+ var args1 = [
+ 'throwBindingError',
+ 'invoker',
+ 'fn',
+ 'runDestructors',
+ 'retType',
+ 'classParam',
+ ]
+ var args2 = [
+ throwBindingError,
+ cppInvokerFunc,
+ cppTargetFunc,
+ runDestructors,
+ argTypes[0],
+ argTypes[1],
+ ]
+ if (isClassMethodFunc) {
+ invokerFnBody +=
+ 'var thisWired = classParam.toWireType(' + dtorStack + ', this);\n'
+ }
+ for (var i = 0; i < argCount - 2; ++i) {
+ invokerFnBody +=
+ 'var arg' +
+ i +
+ 'Wired = argType' +
+ i +
+ '.toWireType(' +
+ dtorStack +
+ ', arg' +
+ i +
+ '); // ' +
+ argTypes[i + 2].name +
+ '\n'
+ args1.push('argType' + i)
+ args2.push(argTypes[i + 2])
+ }
+ if (isClassMethodFunc) {
+ argsListWired =
+ 'thisWired' + (argsListWired.length > 0 ? ', ' : '') + argsListWired
+ }
+ invokerFnBody +=
+ (returns ? 'var rv = ' : '') +
+ 'invoker(fn' +
+ (argsListWired.length > 0 ? ', ' : '') +
+ argsListWired +
+ ');\n'
+ if (needsDestructorStack) {
+ invokerFnBody += 'runDestructors(destructors);\n'
+ } else {
+ for (var i = isClassMethodFunc ? 1 : 2; i < argTypes.length; ++i) {
+ var paramName = i === 1 ? 'thisWired' : 'arg' + (i - 2) + 'Wired'
+ if (argTypes[i].destructorFunction !== null) {
+ invokerFnBody +=
+ paramName +
+ '_dtor(' +
+ paramName +
+ '); // ' +
+ argTypes[i].name +
+ '\n'
+ args1.push(paramName + '_dtor')
+ args2.push(argTypes[i].destructorFunction)
+ }
+ }
+ }
+ if (returns) {
+ invokerFnBody +=
+ 'var ret = retType.fromWireType(rv);\n' + 'return ret;\n'
+ } else {
+ }
+ invokerFnBody += '}\n'
+ args1.push(invokerFnBody)
+ var invokerFunction = new_(Function, args1).apply(null, args2)
+ return invokerFunction
+ }
+ function heap32VectorToArray(count, firstElement) {
+ var array = []
+ for (var i = 0; i < count; i++) {
+ array.push(HEAP32[(firstElement >> 2) + i])
+ }
+ return array
+ }
+ function replacePublicSymbol(name, value, numArguments) {
+ if (!Module.hasOwnProperty(name)) {
+ throwInternalError('Replacing nonexistant public symbol')
+ }
+ if (
+ undefined !== Module[name].overloadTable &&
+ undefined !== numArguments
+ ) {
+ Module[name].overloadTable[numArguments] = value
+ } else {
+ Module[name] = value
+ Module[name].argCount = numArguments
+ }
+ }
+ function dynCallLegacy(sig, ptr, args) {
+ var f = Module['dynCall_' + sig]
+ return args && args.length
+ ? f.apply(null, [ptr].concat(args))
+ : f.call(null, ptr)
+ }
+ function dynCall(sig, ptr, args) {
+ if (sig.includes('j')) {
+ return dynCallLegacy(sig, ptr, args)
+ }
+ return wasmTable.get(ptr).apply(null, args)
+ }
+ function getDynCaller(sig, ptr) {
+ var argCache = []
+ return function () {
+ argCache.length = arguments.length
+ for (var i = 0; i < arguments.length; i++) {
+ argCache[i] = arguments[i]
+ }
+ return dynCall(sig, ptr, argCache)
+ }
+ }
+ function embind__requireFunction(signature, rawFunction) {
+ signature = readLatin1String(signature)
+ function makeDynCaller() {
+ if (signature.includes('j')) {
+ return getDynCaller(signature, rawFunction)
+ }
+ return wasmTable.get(rawFunction)
+ }
+ var fp = makeDynCaller()
+ if (typeof fp !== 'function') {
+ throwBindingError(
+ 'unknown function pointer with signature ' +
+ signature +
+ ': ' +
+ rawFunction
+ )
+ }
+ return fp
+ }
+ var UnboundTypeError = undefined
+ function throwUnboundTypeError(message, types) {
+ var unboundTypes = []
+ var seen = {}
+ function visit(type) {
+ if (seen[type]) {
+ return
+ }
+ if (registeredTypes[type]) {
+ return
+ }
+ if (typeDependencies[type]) {
+ typeDependencies[type].forEach(visit)
+ return
+ }
+ unboundTypes.push(type)
+ seen[type] = true
+ }
+ types.forEach(visit)
+ throw new UnboundTypeError(
+ message + ': ' + unboundTypes.map(getTypeName).join([', '])
+ )
+ }
+ function __embind_register_function(
+ name,
+ argCount,
+ rawArgTypesAddr,
+ signature,
+ rawInvoker,
+ fn
+ ) {
+ var argTypes = heap32VectorToArray(argCount, rawArgTypesAddr)
+ name = readLatin1String(name)
+ rawInvoker = embind__requireFunction(signature, rawInvoker)
+ exposePublicSymbol(
+ name,
+ function () {
+ throwUnboundTypeError(
+ 'Cannot call ' + name + ' due to unbound types',
+ argTypes
+ )
+ },
+ argCount - 1
+ )
+ whenDependentTypesAreResolved([], argTypes, function (argTypes) {
+ var invokerArgsArray = [argTypes[0], null].concat(argTypes.slice(1))
+ replacePublicSymbol(
+ name,
+ craftInvokerFunction(name, invokerArgsArray, null, rawInvoker, fn),
+ argCount - 1
+ )
+ return []
+ })
+ }
+ function integerReadValueFromPointer(name, shift, signed) {
+ switch (shift) {
+ case 0:
+ return signed
+ ? function readS8FromPointer(pointer) {
+ return HEAP8[pointer]
+ }
+ : function readU8FromPointer(pointer) {
+ return HEAPU8[pointer]
+ }
+ case 1:
+ return signed
+ ? function readS16FromPointer(pointer) {
+ return HEAP16[pointer >> 1]
+ }
+ : function readU16FromPointer(pointer) {
+ return HEAPU16[pointer >> 1]
+ }
+ case 2:
+ return signed
+ ? function readS32FromPointer(pointer) {
+ return HEAP32[pointer >> 2]
+ }
+ : function readU32FromPointer(pointer) {
+ return HEAPU32[pointer >> 2]
+ }
+ default:
+ throw new TypeError('Unknown integer type: ' + name)
+ }
+ }
+ function __embind_register_integer(
+ primitiveType,
+ name,
+ size,
+ minRange,
+ maxRange
+ ) {
+ name = readLatin1String(name)
+ if (maxRange === -1) {
+ maxRange = 4294967295
+ }
+ var shift = getShiftFromSize(size)
+ var fromWireType = function (value) {
+ return value
+ }
+ if (minRange === 0) {
+ var bitshift = 32 - 8 * size
+ fromWireType = function (value) {
+ return (value << bitshift) >>> bitshift
+ }
+ }
+ var isUnsignedType = name.includes('unsigned')
+ registerType(primitiveType, {
+ name: name,
+ fromWireType: fromWireType,
+ toWireType: function (destructors, value) {
+ if (typeof value !== 'number' && typeof value !== 'boolean') {
+ throw new TypeError(
+ 'Cannot convert "' + _embind_repr(value) + '" to ' + this.name
+ )
+ }
+ if (value < minRange || value > maxRange) {
+ throw new TypeError(
+ 'Passing a number "' +
+ _embind_repr(value) +
+ '" from JS side to C/C++ side to an argument of type "' +
+ name +
+ '", which is outside the valid range [' +
+ minRange +
+ ', ' +
+ maxRange +
+ ']!'
+ )
+ }
+ return isUnsignedType ? value >>> 0 : value | 0
+ },
+ argPackAdvance: 8,
+ readValueFromPointer: integerReadValueFromPointer(
+ name,
+ shift,
+ minRange !== 0
+ ),
+ destructorFunction: null,
+ })
+ }
+ function __embind_register_memory_view(rawType, dataTypeIndex, name) {
+ var typeMapping = [
+ Int8Array,
+ Uint8Array,
+ Int16Array,
+ Uint16Array,
+ Int32Array,
+ Uint32Array,
+ Float32Array,
+ Float64Array,
+ ]
+ var TA = typeMapping[dataTypeIndex]
+ function decodeMemoryView(handle) {
+ handle = handle >> 2
+ var heap = HEAPU32
+ var size = heap[handle]
+ var data = heap[handle + 1]
+ return new TA(buffer, data, size)
+ }
+ name = readLatin1String(name)
+ registerType(
+ rawType,
+ {
+ name: name,
+ fromWireType: decodeMemoryView,
+ argPackAdvance: 8,
+ readValueFromPointer: decodeMemoryView,
+ },
+ { ignoreDuplicateRegistrations: true }
+ )
+ }
+ function __embind_register_std_string(rawType, name) {
+ name = readLatin1String(name)
+ var stdStringIsUTF8 = name === 'std::string'
+ registerType(rawType, {
+ name: name,
+ fromWireType: function (value) {
+ var length = HEAPU32[value >> 2]
+ var str
+ if (stdStringIsUTF8) {
+ var decodeStartPtr = value + 4
+ for (var i = 0; i <= length; ++i) {
+ var currentBytePtr = value + 4 + i
+ if (i == length || HEAPU8[currentBytePtr] == 0) {
+ var maxRead = currentBytePtr - decodeStartPtr
+ var stringSegment = UTF8ToString(decodeStartPtr, maxRead)
+ if (str === undefined) {
+ str = stringSegment
+ } else {
+ str += String.fromCharCode(0)
+ str += stringSegment
+ }
+ decodeStartPtr = currentBytePtr + 1
+ }
+ }
+ } else {
+ var a = new Array(length)
+ for (var i = 0; i < length; ++i) {
+ a[i] = String.fromCharCode(HEAPU8[value + 4 + i])
+ }
+ str = a.join('')
+ }
+ _free(value)
+ return str
+ },
+ toWireType: function (destructors, value) {
+ if (value instanceof ArrayBuffer) {
+ value = new Uint8Array(value)
+ }
+ var getLength
+ var valueIsOfTypeString = typeof value === 'string'
+ if (
+ !(
+ valueIsOfTypeString ||
+ value instanceof Uint8Array ||
+ value instanceof Uint8ClampedArray ||
+ value instanceof Int8Array
+ )
+ ) {
+ throwBindingError('Cannot pass non-string to std::string')
+ }
+ if (stdStringIsUTF8 && valueIsOfTypeString) {
+ getLength = function () {
+ return lengthBytesUTF8(value)
+ }
+ } else {
+ getLength = function () {
+ return value.length
+ }
+ }
+ var length = getLength()
+ var ptr = _malloc(4 + length + 1)
+ HEAPU32[ptr >> 2] = length
+ if (stdStringIsUTF8 && valueIsOfTypeString) {
+ stringToUTF8(value, ptr + 4, length + 1)
+ } else {
+ if (valueIsOfTypeString) {
+ for (var i = 0; i < length; ++i) {
+ var charCode = value.charCodeAt(i)
+ if (charCode > 255) {
+ _free(ptr)
+ throwBindingError(
+ 'String has UTF-16 code units that do not fit in 8 bits'
+ )
+ }
+ HEAPU8[ptr + 4 + i] = charCode
+ }
+ } else {
+ for (var i = 0; i < length; ++i) {
+ HEAPU8[ptr + 4 + i] = value[i]
+ }
+ }
+ }
+ if (destructors !== null) {
+ destructors.push(_free, ptr)
+ }
+ return ptr
+ },
+ argPackAdvance: 8,
+ readValueFromPointer: simpleReadValueFromPointer,
+ destructorFunction: function (ptr) {
+ _free(ptr)
+ },
+ })
+ }
+ function __embind_register_std_wstring(rawType, charSize, name) {
+ name = readLatin1String(name)
+ var decodeString, encodeString, getHeap, lengthBytesUTF, shift
+ if (charSize === 2) {
+ decodeString = UTF16ToString
+ encodeString = stringToUTF16
+ lengthBytesUTF = lengthBytesUTF16
+ getHeap = function () {
+ return HEAPU16
+ }
+ shift = 1
+ } else if (charSize === 4) {
+ decodeString = UTF32ToString
+ encodeString = stringToUTF32
+ lengthBytesUTF = lengthBytesUTF32
+ getHeap = function () {
+ return HEAPU32
+ }
+ shift = 2
+ }
+ registerType(rawType, {
+ name: name,
+ fromWireType: function (value) {
+ var length = HEAPU32[value >> 2]
+ var HEAP = getHeap()
+ var str
+ var decodeStartPtr = value + 4
+ for (var i = 0; i <= length; ++i) {
+ var currentBytePtr = value + 4 + i * charSize
+ if (i == length || HEAP[currentBytePtr >> shift] == 0) {
+ var maxReadBytes = currentBytePtr - decodeStartPtr
+ var stringSegment = decodeString(decodeStartPtr, maxReadBytes)
+ if (str === undefined) {
+ str = stringSegment
+ } else {
+ str += String.fromCharCode(0)
+ str += stringSegment
+ }
+ decodeStartPtr = currentBytePtr + charSize
+ }
+ }
+ _free(value)
+ return str
+ },
+ toWireType: function (destructors, value) {
+ if (!(typeof value === 'string')) {
+ throwBindingError(
+ 'Cannot pass non-string to C++ string type ' + name
+ )
+ }
+ var length = lengthBytesUTF(value)
+ var ptr = _malloc(4 + length + charSize)
+ HEAPU32[ptr >> 2] = length >> shift
+ encodeString(value, ptr + 4, length + charSize)
+ if (destructors !== null) {
+ destructors.push(_free, ptr)
+ }
+ return ptr
+ },
+ argPackAdvance: 8,
+ readValueFromPointer: simpleReadValueFromPointer,
+ destructorFunction: function (ptr) {
+ _free(ptr)
+ },
+ })
+ }
+ function __embind_register_value_object(
+ rawType,
+ name,
+ constructorSignature,
+ rawConstructor,
+ destructorSignature,
+ rawDestructor
+ ) {
+ structRegistrations[rawType] = {
+ name: readLatin1String(name),
+ rawConstructor: embind__requireFunction(
+ constructorSignature,
+ rawConstructor
+ ),
+ rawDestructor: embind__requireFunction(
+ destructorSignature,
+ rawDestructor
+ ),
+ fields: [],
+ }
+ }
+ function __embind_register_value_object_field(
+ structType,
+ fieldName,
+ getterReturnType,
+ getterSignature,
+ getter,
+ getterContext,
+ setterArgumentType,
+ setterSignature,
+ setter,
+ setterContext
+ ) {
+ structRegistrations[structType].fields.push({
+ fieldName: readLatin1String(fieldName),
+ getterReturnType: getterReturnType,
+ getter: embind__requireFunction(getterSignature, getter),
+ getterContext: getterContext,
+ setterArgumentType: setterArgumentType,
+ setter: embind__requireFunction(setterSignature, setter),
+ setterContext: setterContext,
+ })
+ }
+ function __embind_register_void(rawType, name) {
+ name = readLatin1String(name)
+ registerType(rawType, {
+ isVoid: true,
+ name: name,
+ argPackAdvance: 0,
+ fromWireType: function () {
+ return undefined
+ },
+ toWireType: function (destructors, o) {
+ return undefined
+ },
+ })
+ }
+ var emval_symbols = {}
+ function getStringOrSymbol(address) {
+ var symbol = emval_symbols[address]
+ if (symbol === undefined) {
+ return readLatin1String(address)
+ } else {
+ return symbol
+ }
+ }
+ function emval_get_global() {
+ if (typeof globalThis === 'object') {
+ return globalThis
+ }
+ return (function () {
+ return Function
+ })()('return this')()
+ }
+ function __emval_get_global(name) {
+ if (name === 0) {
+ return __emval_register(emval_get_global())
+ } else {
+ name = getStringOrSymbol(name)
+ return __emval_register(emval_get_global()[name])
+ }
+ }
+ function __emval_incref(handle) {
+ if (handle > 4) {
+ emval_handle_array[handle].refcount += 1
+ }
+ }
+ function craftEmvalAllocator(argCount) {
+ var argsList = ''
+ for (var i = 0; i < argCount; ++i) {
+ argsList += (i !== 0 ? ', ' : '') + 'arg' + i
+ }
+ var functionBody =
+ 'return function emval_allocator_' +
+ argCount +
+ '(constructor, argTypes, args) {\n'
+ for (var i = 0; i < argCount; ++i) {
+ functionBody +=
+ 'var argType' +
+ i +
+ " = requireRegisteredType(Module['HEAP32'][(argTypes >>> 2) + " +
+ i +
+ '], "parameter ' +
+ i +
+ '");\n' +
+ 'var arg' +
+ i +
+ ' = argType' +
+ i +
+ '.readValueFromPointer(args);\n' +
+ 'args += argType' +
+ i +
+ "['argPackAdvance'];\n"
+ }
+ functionBody +=
+ 'var obj = new constructor(' +
+ argsList +
+ ');\n' +
+ 'return __emval_register(obj);\n' +
+ '}\n'
+ return new Function(
+ 'requireRegisteredType',
+ 'Module',
+ '__emval_register',
+ functionBody
+ )(requireRegisteredType, Module, __emval_register)
+ }
+ var emval_newers = {}
+ function requireHandle(handle) {
+ if (!handle) {
+ throwBindingError('Cannot use deleted val. handle = ' + handle)
+ }
+ return emval_handle_array[handle].value
+ }
+ function __emval_new(handle, argCount, argTypes, args) {
+ handle = requireHandle(handle)
+ var newer = emval_newers[argCount]
+ if (!newer) {
+ newer = craftEmvalAllocator(argCount)
+ emval_newers[argCount] = newer
+ }
+ return newer(handle, argTypes, args)
+ }
+ function _abort() {
+ abort()
+ }
+ function _emscripten_memcpy_big(dest, src, num) {
+ HEAPU8.copyWithin(dest, src, src + num)
+ }
+ function emscripten_realloc_buffer(size) {
+ try {
+ wasmMemory.grow((size - buffer.byteLength + 65535) >>> 16)
+ updateGlobalBufferAndViews(wasmMemory.buffer)
+ return 1
+ } catch (e) {}
+ }
+ function _emscripten_resize_heap(requestedSize) {
+ var oldSize = HEAPU8.length
+ requestedSize = requestedSize >>> 0
+ var maxHeapSize = 2147483648
+ if (requestedSize > maxHeapSize) {
+ return false
+ }
+ for (var cutDown = 1; cutDown <= 4; cutDown *= 2) {
+ var overGrownHeapSize = oldSize * (1 + 0.2 / cutDown)
+ overGrownHeapSize = Math.min(
+ overGrownHeapSize,
+ requestedSize + 100663296
+ )
+ var newSize = Math.min(
+ maxHeapSize,
+ alignUp(Math.max(requestedSize, overGrownHeapSize), 65536)
+ )
+ var replacement = emscripten_realloc_buffer(newSize)
+ if (replacement) {
+ return true
+ }
+ }
+ return false
+ }
+ InternalError = Module['InternalError'] = extendError(
+ Error,
+ 'InternalError'
+ )
+ embind_init_charCodes()
+ BindingError = Module['BindingError'] = extendError(Error, 'BindingError')
+ init_emval()
+ UnboundTypeError = Module['UnboundTypeError'] = extendError(
+ Error,
+ 'UnboundTypeError'
+ )
+ var asmLibraryArg = {
+ w: ___cxa_thread_atexit,
+ l: __embind_finalize_value_object,
+ p: __embind_register_bigint,
+ s: __embind_register_bool,
+ r: __embind_register_emval,
+ n: __embind_register_enum,
+ d: __embind_register_enum_value,
+ j: __embind_register_float,
+ h: __embind_register_function,
+ c: __embind_register_integer,
+ b: __embind_register_memory_view,
+ k: __embind_register_std_string,
+ g: __embind_register_std_wstring,
+ m: __embind_register_value_object,
+ a: __embind_register_value_object_field,
+ t: __embind_register_void,
+ f: __emval_decref,
+ v: __emval_get_global,
+ u: __emval_incref,
+ o: __emval_new,
+ i: _abort,
+ q: _emscripten_memcpy_big,
+ e: _emscripten_resize_heap,
+ }
+ var asm = createWasm()
+ var ___wasm_call_ctors = (Module['___wasm_call_ctors'] = function () {
+ return (___wasm_call_ctors = Module['___wasm_call_ctors'] =
+ Module['asm']['y']).apply(null, arguments)
+ })
+ var _malloc = (Module['_malloc'] = function () {
+ return (_malloc = Module['_malloc'] = Module['asm']['z']).apply(
+ null,
+ arguments
+ )
+ })
+ var _free = (Module['_free'] = function () {
+ return (_free = Module['_free'] = Module['asm']['A']).apply(
+ null,
+ arguments
+ )
+ })
+ var ___getTypeName = (Module['___getTypeName'] = function () {
+ return (___getTypeName = Module['___getTypeName'] =
+ Module['asm']['B']).apply(null, arguments)
+ })
+ var ___embind_register_native_and_builtin_types = (Module[
+ '___embind_register_native_and_builtin_types'
+ ] = function () {
+ return (___embind_register_native_and_builtin_types = Module[
+ '___embind_register_native_and_builtin_types'
+ ] =
+ Module['asm']['C']).apply(null, arguments)
+ })
+ var calledRun
+ dependenciesFulfilled = function runCaller() {
+ if (!calledRun) run()
+ if (!calledRun) dependenciesFulfilled = runCaller
+ }
+ function run(args) {
+ args = args || arguments_
+ if (runDependencies > 0) {
+ return
+ }
+ preRun()
+ if (runDependencies > 0) {
+ return
+ }
+ function doRun() {
+ if (calledRun) return
+ calledRun = true
+ Module['calledRun'] = true
+ if (ABORT) return
+ initRuntime()
+ readyPromiseResolve(Module)
+ if (Module['onRuntimeInitialized']) Module['onRuntimeInitialized']()
+ postRun()
+ }
+ if (Module['setStatus']) {
+ Module['setStatus']('Running...')
+ setTimeout(function () {
+ setTimeout(function () {
+ Module['setStatus']('')
+ }, 1)
+ doRun()
+ }, 1)
+ } else {
+ doRun()
+ }
+ }
+ Module['run'] = run
+ if (Module['preInit']) {
+ if (typeof Module['preInit'] == 'function')
+ Module['preInit'] = [Module['preInit']]
+ while (Module['preInit'].length > 0) {
+ Module['preInit'].pop()()
+ }
+ }
+ run()
+
+ return Module.ready
+ }
+})()
+export default Module
diff --git a/packages/integrations/image/src/vendor/squoosh/webp/webp_node_enc.wasm b/packages/integrations/image/src/vendor/squoosh/webp/webp_node_enc.wasm
new file mode 100644
index 000000000..762105416
Binary files /dev/null and b/packages/integrations/image/src/vendor/squoosh/webp/webp_node_enc.wasm differ
diff --git a/packages/integrations/image/src/vite-plugin-astro-image.ts b/packages/integrations/image/src/vite-plugin-astro-image.ts
index f19c557c3..8aa249e48 100644
--- a/packages/integrations/image/src/vite-plugin-astro-image.ts
+++ b/packages/integrations/image/src/vite-plugin-astro-image.ts
@@ -8,7 +8,6 @@ import slash from 'slash';
import type { Plugin, ResolvedConfig } from 'vite';
import type { IntegrationOptions } from './index.js';
import type { InputFormat } from './loaders/index.js';
-import sharp from './loaders/sharp.js';
import { metadata } from './utils/metadata.js';
export interface ImageMetadata {
@@ -90,13 +89,13 @@ export function createPlugin(config: AstroConfig, options: Required
-
+