@itk-wasm/image-io
Version:
Input and output for scientific and medical image file formats.
1,573 lines (1,550 loc) • 450 kB
JavaScript
var __defProp = Object.defineProperty;
var __export = (target, all3) => {
for (var name in all3)
__defProp(target, name, { get: all3[name], enumerable: true });
};
// src/extension-to-image-io.ts
var extensionToImageIo = /* @__PURE__ */ new Map([
["bmp", "bmp"],
["dcm", "gdcm"],
["gipl", "gipl"],
["gipl.gz", "gipl"],
["hdf5", "hdf5"],
["jpg", "jpeg"],
["jpeg", "jpeg"],
["iwi", "wasm"],
["iwi.cbor", "wasm"],
["iwi.cbor.zst", "wasmZstd"],
["lsm", "lsm"],
["mnc", "mnc"],
["mnc.gz", "mnc"],
["mnc2", "mnc"],
["mgh", "mgh"],
["mgz", "mgh"],
["mgh.gz", "mgh"],
["mha", "meta"],
["mhd", "meta"],
["mrc", "mrc"],
["nia", "nifti"],
["nii", "nifti"],
["nii.gz", "nifti"],
["hdr", "nifti"],
["nrrd", "nrrd"],
["nhdr", "nrrd"],
["png", "png"],
["pic", "bioRad"],
["tif", "tiff"],
["tiff", "tiff"],
["vtk", "vtk"],
["isq", "scanco"],
["aim", "scanco"],
["fdf", "fdf"]
]);
var extension_to_image_io_default = extensionToImageIo;
// ../../core/typescript/itk-wasm/dist/interface-types/int-types.js
var IntTypes = {
Int8: "int8",
UInt8: "uint8",
Int16: "int16",
UInt16: "uint16",
Int32: "int32",
UInt32: "uint32",
Int64: "int64",
UInt64: "uint64",
SizeValueType: "uint64",
IdentifierType: "uint64",
IndexValueType: "int64",
OffsetValueType: "int64"
};
var int_types_default = IntTypes;
// ../../core/typescript/itk-wasm/dist/interface-types/float-types.js
var FloatTypes = {
Float32: "float32",
Float64: "float64",
SpacePrecisionType: "float64"
};
var float_types_default = FloatTypes;
// ../../core/typescript/itk-wasm/dist/buffer-to-typed-array.js
function bufferToTypedArray(wasmType, buffer) {
let typedArray = null;
switch (wasmType) {
case int_types_default.UInt8: {
typedArray = new Uint8Array(buffer);
break;
}
case int_types_default.Int8: {
typedArray = new Int8Array(buffer);
break;
}
case int_types_default.UInt16: {
typedArray = new Uint16Array(buffer);
break;
}
case int_types_default.Int16: {
typedArray = new Int16Array(buffer);
break;
}
case int_types_default.UInt32: {
typedArray = new Uint32Array(buffer);
break;
}
case int_types_default.Int32: {
typedArray = new Int32Array(buffer);
break;
}
case int_types_default.UInt64: {
if (typeof globalThis.BigUint64Array === "function") {
typedArray = new BigUint64Array(buffer);
} else {
typedArray = new Uint8Array(buffer);
}
break;
}
case int_types_default.Int64: {
if (typeof globalThis.BigInt64Array === "function") {
typedArray = new BigInt64Array(buffer);
} else {
typedArray = new Uint8Array(buffer);
}
break;
}
case float_types_default.Float32: {
typedArray = new Float32Array(buffer);
break;
}
case float_types_default.Float64: {
typedArray = new Float64Array(buffer);
break;
}
case "null": {
typedArray = null;
break;
}
case null: {
typedArray = null;
break;
}
default:
throw new Error("Type is not supported as a TypedArray");
}
return typedArray;
}
var buffer_to_typed_array_default = bufferToTypedArray;
// ../../core/typescript/itk-wasm/dist/interface-types/pixel-types.js
var PixelTypes = {
Unknown: "Unknown",
Scalar: "Scalar",
RGB: "RGB",
RGBA: "RGBA",
Offset: "Offset",
Vector: "Vector",
Point: "Point",
CovariantVector: "CovariantVector",
SymmetricSecondRankTensor: "SymmetricSecondRankTensor",
DiffusionTensor3D: "DiffusionTensor3D",
Complex: "Complex",
FixedArray: "FixedArray",
Array: "Array",
Matrix: "Matrix",
VariableLengthVector: "VariableLengthVector",
VariableSizeMatrix: "VariableSizeMatrix"
};
var pixel_types_default = PixelTypes;
// ../../core/typescript/itk-wasm/dist/interface-types/image-type.js
var ImageType = class {
dimension;
componentType;
pixelType;
components;
constructor(dimension = 2, componentType = int_types_default.UInt8, pixelType = pixel_types_default.Scalar, components = 1) {
this.dimension = dimension;
this.componentType = componentType;
this.pixelType = pixelType;
this.components = components;
}
};
var image_type_default = ImageType;
// ../../core/typescript/itk-wasm/dist/set-matrix-element.js
function setMatrixElement(matrixData, columns, row, column, value) {
matrixData[column + row * columns] = value;
}
var set_matrix_element_default = setMatrixElement;
// ../../core/typescript/itk-wasm/dist/interface-types/image.js
var Image = class {
imageType;
name = "Image";
origin;
spacing;
direction;
size;
metadata;
data;
constructor(imageType = new image_type_default()) {
this.imageType = imageType;
const dimension = imageType.dimension;
this.origin = new Array(dimension);
this.origin.fill(0);
this.spacing = new Array(dimension);
this.spacing.fill(1);
this.direction = new Float64Array(dimension * dimension);
this.direction.fill(0);
for (let ii = 0; ii < dimension; ii++) {
set_matrix_element_default(this.direction, dimension, ii, ii, 1);
}
this.size = new Array(dimension);
this.size.fill(0);
this.metadata = /* @__PURE__ */ new Map();
this.data = null;
}
};
var image_default = Image;
// ../../core/typescript/itk-wasm/dist/copy-image.js
function copyImage(image) {
const copy = new image_default(image.imageType);
copy.name = image.name;
copy.origin = Array.from(image.origin);
copy.spacing = Array.from(image.spacing);
copy.direction = image.direction.slice();
copy.size = Array.from(image.size);
if (image.data !== null) {
const CTor = image.data.constructor;
copy.data = new CTor(image.data.length);
if (copy.data != null) {
copy.data.set(image.data, 0);
}
}
return copy;
}
var copy_image_default = copyImage;
// ../../core/typescript/itk-wasm/dist/stack-images.js
function stackImages(images) {
if (images.length < 1) {
throw Error("At least one images is required.");
}
const firstImage = images[0];
if (firstImage.data === null) {
throw Error("Image data is null.");
}
const result = new image_default(firstImage.imageType);
result.origin = Array.from(firstImage.origin);
result.spacing = Array.from(firstImage.spacing);
const dimension = result.imageType.dimension;
result.direction = firstImage.direction.slice();
const stackOn = dimension - 1;
result.size = Array.from(firstImage.size);
const stackedSize = images.reduce((accumulator, currentValue) => {
return accumulator + currentValue.size[stackOn];
}, 0);
result.size[stackOn] = stackedSize;
const dataSize = result.size.reduce((accumulator, currentValue) => {
return accumulator * currentValue;
}, 1) * result.imageType.components;
const CTor = firstImage.data.constructor;
result.data = new CTor(dataSize);
let offsetBase = result.imageType.components;
for (let subIndex = 0; subIndex < result.size.length - 1; subIndex++) {
offsetBase *= result.size[subIndex];
}
let stackIndex = 0;
if (result.data != null) {
for (let index = 0; index < images.length; index++) {
result.data.set(images[index].data, offsetBase * stackIndex);
stackIndex += images[index].size[stackOn];
}
} else {
throw Error("Could not create result image data.");
}
return result;
}
var stack_images_default = stackImages;
// ../../core/typescript/itk-wasm/dist/get-file-extension.js
function getFileExtension(filePath) {
let extension = filePath.slice((filePath.lastIndexOf(".") - 1 >>> 0) + 2);
if (extension.toLowerCase() === "gz") {
const index = filePath.slice(0, -3).lastIndexOf(".");
extension = filePath.slice((index - 1 >>> 0) + 2);
} else if (extension.toLowerCase() === "cbor") {
const index = filePath.slice(0, -5).lastIndexOf(".");
extension = filePath.slice((index - 1 >>> 0) + 2);
} else if (extension.toLowerCase() === "zst") {
const index = filePath.slice(0, -10).lastIndexOf(".");
extension = filePath.slice((index - 1 >>> 0) + 2);
} else if (extension.toLowerCase() === "zip") {
const index = filePath.slice(0, -4).lastIndexOf(".");
extension = filePath.slice((index - 1 >>> 0) + 2);
}
return extension;
}
var get_file_extension_default = getFileExtension;
// ../../core/typescript/itk-wasm/dist/cast-image.js
function castImage(inputImage, options) {
const outputImageType = { ...inputImage.imageType };
if (typeof options !== "undefined" && typeof options.pixelType !== "undefined") {
outputImageType.pixelType = options.pixelType;
if (options.pixelType === pixel_types_default.Scalar && outputImageType.components !== 1) {
throw new Error("Cannot cast multi-component image to a scalar image");
}
}
if (typeof options !== "undefined" && typeof options.componentType !== "undefined" && options.componentType !== inputImage.imageType.componentType) {
outputImageType.componentType = options.componentType;
}
const outputImage = new image_default(outputImageType);
outputImage.name = inputImage.name;
outputImage.origin = Array.from(inputImage.origin);
outputImage.spacing = Array.from(inputImage.spacing);
outputImage.direction = inputImage.direction.slice();
outputImage.size = Array.from(inputImage.size);
outputImage.metadata = new Map(JSON.parse(JSON.stringify(Array.from(inputImage.metadata))));
if (inputImage.data !== null) {
if (typeof options !== "undefined" && typeof options.componentType !== "undefined" && options.componentType !== inputImage.imageType.componentType) {
switch (inputImage.imageType.componentType) {
case int_types_default.UInt8:
case int_types_default.Int8:
case int_types_default.UInt16:
case int_types_default.Int16:
case int_types_default.UInt32:
case int_types_default.Int32:
case float_types_default.Float32:
case float_types_default.Float64:
switch (outputImage.imageType.componentType) {
case int_types_default.UInt8:
outputImage.data = new Uint8Array(inputImage.data);
break;
case int_types_default.Int8:
outputImage.data = new Int8Array(inputImage.data);
break;
case int_types_default.UInt16:
outputImage.data = new Uint16Array(inputImage.data);
break;
case int_types_default.Int16:
outputImage.data = new Int16Array(inputImage.data);
break;
case int_types_default.UInt32:
outputImage.data = new Uint32Array(inputImage.data);
break;
case int_types_default.Int32:
outputImage.data = new Int32Array(inputImage.data);
break;
case float_types_default.Float32:
outputImage.data = new Float32Array(inputImage.data);
break;
case float_types_default.Float64:
outputImage.data = new Float64Array(inputImage.data);
break;
case int_types_default.UInt64:
outputImage.data = new BigUint64Array(inputImage.data.length);
for (let idx = 0; idx < outputImage.data.length; idx++) {
outputImage.data[idx] = BigInt.asIntN(64, BigInt(inputImage.data[idx]));
}
break;
case int_types_default.Int64:
outputImage.data = new BigInt64Array(inputImage.data.length);
for (let idx = 0; idx < outputImage.data.length; idx++) {
outputImage.data[idx] = BigInt.asUintN(64, BigInt(inputImage.data[idx]));
}
break;
}
break;
case int_types_default.UInt64:
case int_types_default.Int64:
switch (outputImage.imageType.componentType) {
case int_types_default.UInt8:
outputImage.data = new Uint8Array(inputImage.data.length);
for (let idx = 0; idx < outputImage.data.length; idx++) {
outputImage.data[idx] = Number(inputImage.data[idx]);
}
break;
case int_types_default.Int8:
outputImage.data = new Int8Array(inputImage.data.length);
for (let idx = 0; idx < outputImage.data.length; idx++) {
outputImage.data[idx] = Number(inputImage.data[idx]);
}
break;
case int_types_default.UInt16:
outputImage.data = new Uint16Array(inputImage.data.length);
for (let idx = 0; idx < outputImage.data.length; idx++) {
outputImage.data[idx] = Number(inputImage.data[idx]);
}
break;
case int_types_default.Int16:
outputImage.data = new Int16Array(inputImage.data.length);
for (let idx = 0; idx < outputImage.data.length; idx++) {
outputImage.data[idx] = Number(inputImage.data[idx]);
}
break;
case int_types_default.UInt32:
outputImage.data = new Uint32Array(inputImage.data.length);
for (let idx = 0; idx < outputImage.data.length; idx++) {
outputImage.data[idx] = Number(inputImage.data[idx]);
}
break;
case int_types_default.Int32:
outputImage.data = new Int32Array(inputImage.data.length);
for (let idx = 0; idx < outputImage.data.length; idx++) {
outputImage.data[idx] = Number(inputImage.data[idx]);
}
break;
case float_types_default.Float32:
outputImage.data = new Float32Array(inputImage.data.length);
for (let idx = 0; idx < outputImage.data.length; idx++) {
outputImage.data[idx] = Number(inputImage.data[idx]);
}
break;
case float_types_default.Float64:
outputImage.data = new Float64Array(inputImage.data.length);
for (let idx = 0; idx < outputImage.data.length; idx++) {
outputImage.data[idx] = Number(inputImage.data[idx]);
}
break;
case int_types_default.UInt64:
outputImage.data = new BigUint64Array(inputImage.data);
break;
case int_types_default.Int64:
outputImage.data = new BigInt64Array(inputImage.data);
break;
}
break;
}
} else {
const CTor = inputImage.data.constructor;
outputImage.data = new CTor(inputImage.data.length);
if (outputImage.data != null) {
outputImage.data.set(inputImage.data, 0);
}
}
}
return outputImage;
}
var cast_image_default = castImage;
// ../../core/typescript/itk-wasm/dist/worker-pool/worker-pool.js
var WorkerPool = class {
fcn;
workerQueue;
runInfo;
/*
* poolSize is the maximum number of web workers to create in the pool.
*
* The function, `fcn,` must accept in its last argument an options object with a
* `webWorker` property that is a web worker to use for computation. The
* function must also return a promise that resolves to an object with the
* with the results of the computation and the used worker in the `webWorker`
* property.
*
**/
constructor(poolSize, fcn) {
this.fcn = fcn;
this.workerQueue = new Array(poolSize);
this.workerQueue.fill(null);
this.runInfo = [];
}
/*
* Run the tasks specified by the arguments in the taskArgsArray that will
* be passed to the pool fcn.
*
* An optional progressCallback will be called with the number of complete
* tasks and the total number of tasks as arguments every time a task has
* completed.
*
* Returns an object containing a promise ('promise') to communicate results
* as well as an id ('runId') which can be used to cancel any remaining pending
* tasks before they complete.
*/
runTasks(taskArgsArray, progressCallback = null) {
const info = {
taskQueue: [],
results: [],
addingTasks: false,
postponed: false,
runningWorkers: 0,
index: 0,
completedTasks: 0,
progressCallback,
canceled: false
};
this.runInfo.push(info);
info.index = this.runInfo.length - 1;
return {
promise: new Promise((resolve, reject) => {
info.resolve = resolve;
info.reject = reject;
info.results = new Array(taskArgsArray.length);
info.completedTasks = 0;
info.addingTasks = true;
taskArgsArray.forEach((taskArg, index) => {
this.addTask(info.index, index, taskArg);
});
info.addingTasks = false;
}),
runId: info.index
};
}
terminateWorkers() {
for (let index = 0; index < this.workerQueue.length; index++) {
const worker = this.workerQueue[index];
if (worker != null) {
worker.terminate();
}
this.workerQueue[index] = null;
}
}
cancel(runId) {
const info = this.runInfo[runId];
if (info !== null && info !== void 0) {
info.canceled = true;
}
}
addTask(infoIndex, resultIndex, taskArgs) {
const info = this.runInfo[infoIndex];
if (info?.canceled === true) {
info.reject("Remaining tasks canceled");
this.clearTask(info.index);
return;
}
if (this.workerQueue.length > 0) {
const worker = this.workerQueue.pop();
info.runningWorkers++;
taskArgs[taskArgs.length - 1].webWorker = worker;
this.fcn(...taskArgs).then(({ webWorker, ...result }) => {
this.workerQueue.push(webWorker);
if (this.runInfo[infoIndex] !== null) {
info.runningWorkers--;
info.results[resultIndex] = result;
info.completedTasks++;
if (info.progressCallback != null) {
info.progressCallback(info.completedTasks, info.results.length);
}
if (info.taskQueue.length > 0) {
const reTask = info.taskQueue.shift();
this.addTask(infoIndex, reTask[0], reTask[1]);
} else if (!info.addingTasks && info.runningWorkers === 0) {
const results = info.results;
info.resolve(results);
this.clearTask(info.index);
}
}
}).catch((error) => {
info.reject(error);
this.clearTask(info.index);
});
} else {
if (info.runningWorkers !== 0 || info.postponed) {
info.taskQueue.push([resultIndex, taskArgs]);
} else {
info.postponed = true;
setTimeout(() => {
info.postponed = false;
this.addTask(info.index, resultIndex, taskArgs);
}, 50);
}
}
}
clearTask(clearIndex) {
this.runInfo[clearIndex].results = [];
this.runInfo[clearIndex].taskQueue = [];
this.runInfo[clearIndex].progressCallback = null;
this.runInfo[clearIndex].canceled = null;
this.runInfo[clearIndex].reject = () => {
};
this.runInfo[clearIndex].resolve = () => {
};
}
};
var worker_pool_default = WorkerPool;
// ../../core/typescript/itk-wasm/dist/interface-types/interface-types.js
var InterfaceTypes = {
TextFile: "TextFile",
BinaryFile: "BinaryFile",
TextStream: "TextStream",
BinaryStream: "BinaryStream",
Image: "Image",
PointSet: "PointSet",
Mesh: "Mesh",
PolyData: "PolyData",
TransformList: "TransformList",
JsonCompatible: "JsonCompatible"
};
var interface_types_default = InterfaceTypes;
// ../../../node_modules/.pnpm/comlink@4.4.1/node_modules/comlink/dist/esm/comlink.mjs
var proxyMarker = Symbol("Comlink.proxy");
var createEndpoint = Symbol("Comlink.endpoint");
var releaseProxy = Symbol("Comlink.releaseProxy");
var finalizer = Symbol("Comlink.finalizer");
var throwMarker = Symbol("Comlink.thrown");
var isObject = (val) => typeof val === "object" && val !== null || typeof val === "function";
var proxyTransferHandler = {
canHandle: (val) => isObject(val) && val[proxyMarker],
serialize(obj) {
const { port1, port2 } = new MessageChannel();
expose(obj, port1);
return [port2, [port2]];
},
deserialize(port) {
port.start();
return wrap(port);
}
};
var throwTransferHandler = {
canHandle: (value) => isObject(value) && throwMarker in value,
serialize({ value }) {
let serialized;
if (value instanceof Error) {
serialized = {
isError: true,
value: {
message: value.message,
name: value.name,
stack: value.stack
}
};
} else {
serialized = { isError: false, value };
}
return [serialized, []];
},
deserialize(serialized) {
if (serialized.isError) {
throw Object.assign(new Error(serialized.value.message), serialized.value);
}
throw serialized.value;
}
};
var transferHandlers = /* @__PURE__ */ new Map([
["proxy", proxyTransferHandler],
["throw", throwTransferHandler]
]);
function isAllowedOrigin(allowedOrigins, origin2) {
for (const allowedOrigin of allowedOrigins) {
if (origin2 === allowedOrigin || allowedOrigin === "*") {
return true;
}
if (allowedOrigin instanceof RegExp && allowedOrigin.test(origin2)) {
return true;
}
}
return false;
}
function expose(obj, ep = globalThis, allowedOrigins = ["*"]) {
ep.addEventListener("message", function callback(ev) {
if (!ev || !ev.data) {
return;
}
if (!isAllowedOrigin(allowedOrigins, ev.origin)) {
console.warn(`Invalid origin '${ev.origin}' for comlink proxy`);
return;
}
const { id, type, path } = Object.assign({ path: [] }, ev.data);
const argumentList = (ev.data.argumentList || []).map(fromWireValue);
let returnValue;
try {
const parent = path.slice(0, -1).reduce((obj2, prop) => obj2[prop], obj);
const rawValue = path.reduce((obj2, prop) => obj2[prop], obj);
switch (type) {
case "GET":
{
returnValue = rawValue;
}
break;
case "SET":
{
parent[path.slice(-1)[0]] = fromWireValue(ev.data.value);
returnValue = true;
}
break;
case "APPLY":
{
returnValue = rawValue.apply(parent, argumentList);
}
break;
case "CONSTRUCT":
{
const value = new rawValue(...argumentList);
returnValue = proxy(value);
}
break;
case "ENDPOINT":
{
const { port1, port2 } = new MessageChannel();
expose(obj, port2);
returnValue = transfer(port1, [port1]);
}
break;
case "RELEASE":
{
returnValue = void 0;
}
break;
default:
return;
}
} catch (value) {
returnValue = { value, [throwMarker]: 0 };
}
Promise.resolve(returnValue).catch((value) => {
return { value, [throwMarker]: 0 };
}).then((returnValue2) => {
const [wireValue, transferables] = toWireValue(returnValue2);
ep.postMessage(Object.assign(Object.assign({}, wireValue), { id }), transferables);
if (type === "RELEASE") {
ep.removeEventListener("message", callback);
closeEndPoint(ep);
if (finalizer in obj && typeof obj[finalizer] === "function") {
obj[finalizer]();
}
}
}).catch((error) => {
const [wireValue, transferables] = toWireValue({
value: new TypeError("Unserializable return value"),
[throwMarker]: 0
});
ep.postMessage(Object.assign(Object.assign({}, wireValue), { id }), transferables);
});
});
if (ep.start) {
ep.start();
}
}
function isMessagePort(endpoint) {
return endpoint.constructor.name === "MessagePort";
}
function closeEndPoint(endpoint) {
if (isMessagePort(endpoint))
endpoint.close();
}
function wrap(ep, target) {
return createProxy(ep, [], target);
}
function throwIfProxyReleased(isReleased) {
if (isReleased) {
throw new Error("Proxy has been released and is not useable");
}
}
function releaseEndpoint(ep) {
return requestResponseMessage(ep, {
type: "RELEASE"
}).then(() => {
closeEndPoint(ep);
});
}
var proxyCounter = /* @__PURE__ */ new WeakMap();
var proxyFinalizers = "FinalizationRegistry" in globalThis && new FinalizationRegistry((ep) => {
const newCount = (proxyCounter.get(ep) || 0) - 1;
proxyCounter.set(ep, newCount);
if (newCount === 0) {
releaseEndpoint(ep);
}
});
function registerProxy(proxy2, ep) {
const newCount = (proxyCounter.get(ep) || 0) + 1;
proxyCounter.set(ep, newCount);
if (proxyFinalizers) {
proxyFinalizers.register(proxy2, ep, proxy2);
}
}
function unregisterProxy(proxy2) {
if (proxyFinalizers) {
proxyFinalizers.unregister(proxy2);
}
}
function createProxy(ep, path = [], target = function() {
}) {
let isProxyReleased = false;
const proxy2 = new Proxy(target, {
get(_target, prop) {
throwIfProxyReleased(isProxyReleased);
if (prop === releaseProxy) {
return () => {
unregisterProxy(proxy2);
releaseEndpoint(ep);
isProxyReleased = true;
};
}
if (prop === "then") {
if (path.length === 0) {
return { then: () => proxy2 };
}
const r = requestResponseMessage(ep, {
type: "GET",
path: path.map((p) => p.toString())
}).then(fromWireValue);
return r.then.bind(r);
}
return createProxy(ep, [...path, prop]);
},
set(_target, prop, rawValue) {
throwIfProxyReleased(isProxyReleased);
const [value, transferables] = toWireValue(rawValue);
return requestResponseMessage(ep, {
type: "SET",
path: [...path, prop].map((p) => p.toString()),
value
}, transferables).then(fromWireValue);
},
apply(_target, _thisArg, rawArgumentList) {
throwIfProxyReleased(isProxyReleased);
const last = path[path.length - 1];
if (last === createEndpoint) {
return requestResponseMessage(ep, {
type: "ENDPOINT"
}).then(fromWireValue);
}
if (last === "bind") {
return createProxy(ep, path.slice(0, -1));
}
const [argumentList, transferables] = processArguments(rawArgumentList);
return requestResponseMessage(ep, {
type: "APPLY",
path: path.map((p) => p.toString()),
argumentList
}, transferables).then(fromWireValue);
},
construct(_target, rawArgumentList) {
throwIfProxyReleased(isProxyReleased);
const [argumentList, transferables] = processArguments(rawArgumentList);
return requestResponseMessage(ep, {
type: "CONSTRUCT",
path: path.map((p) => p.toString()),
argumentList
}, transferables).then(fromWireValue);
}
});
registerProxy(proxy2, ep);
return proxy2;
}
function myFlat(arr) {
return Array.prototype.concat.apply([], arr);
}
function processArguments(argumentList) {
const processed = argumentList.map(toWireValue);
return [processed.map((v) => v[0]), myFlat(processed.map((v) => v[1]))];
}
var transferCache = /* @__PURE__ */ new WeakMap();
function transfer(obj, transfers) {
transferCache.set(obj, transfers);
return obj;
}
function proxy(obj) {
return Object.assign(obj, { [proxyMarker]: true });
}
function toWireValue(value) {
for (const [name, handler] of transferHandlers) {
if (handler.canHandle(value)) {
const [serializedValue, transferables] = handler.serialize(value);
return [
{
type: "HANDLER",
name,
value: serializedValue
},
transferables
];
}
}
return [
{
type: "RAW",
value
},
transferCache.get(value) || []
];
}
function fromWireValue(value) {
switch (value.type) {
case "HANDLER":
return transferHandlers.get(value.name).deserialize(value.value);
case "RAW":
return value.value;
}
}
function requestResponseMessage(ep, msg, transfers) {
return new Promise((resolve) => {
const id = generateUUID();
ep.addEventListener("message", function l(ev) {
if (!ev.data || !ev.data.id || ev.data.id !== id) {
return;
}
ep.removeEventListener("message", l);
resolve(ev.data);
});
if (ep.start) {
ep.start();
}
ep.postMessage(Object.assign({ id }, msg), transfers);
});
}
function generateUUID() {
return new Array(4).fill(0).map(() => Math.floor(Math.random() * Number.MAX_SAFE_INTEGER).toString(16)).join("-");
}
// ../../../node_modules/.pnpm/axios@1.7.4_debug@4.3.5/node_modules/axios/lib/helpers/bind.js
function bind(fn, thisArg) {
return function wrap2() {
return fn.apply(thisArg, arguments);
};
}
// ../../../node_modules/.pnpm/axios@1.7.4_debug@4.3.5/node_modules/axios/lib/utils.js
var { toString } = Object.prototype;
var { getPrototypeOf } = Object;
var kindOf = /* @__PURE__ */ ((cache) => (thing) => {
const str = toString.call(thing);
return cache[str] || (cache[str] = str.slice(8, -1).toLowerCase());
})(/* @__PURE__ */ Object.create(null));
var kindOfTest = (type) => {
type = type.toLowerCase();
return (thing) => kindOf(thing) === type;
};
var typeOfTest = (type) => (thing) => typeof thing === type;
var { isArray } = Array;
var isUndefined = typeOfTest("undefined");
function isBuffer(val) {
return val !== null && !isUndefined(val) && val.constructor !== null && !isUndefined(val.constructor) && isFunction(val.constructor.isBuffer) && val.constructor.isBuffer(val);
}
var isArrayBuffer = kindOfTest("ArrayBuffer");
function isArrayBufferView(val) {
let result;
if (typeof ArrayBuffer !== "undefined" && ArrayBuffer.isView) {
result = ArrayBuffer.isView(val);
} else {
result = val && val.buffer && isArrayBuffer(val.buffer);
}
return result;
}
var isString = typeOfTest("string");
var isFunction = typeOfTest("function");
var isNumber = typeOfTest("number");
var isObject2 = (thing) => thing !== null && typeof thing === "object";
var isBoolean = (thing) => thing === true || thing === false;
var isPlainObject = (val) => {
if (kindOf(val) !== "object") {
return false;
}
const prototype3 = getPrototypeOf(val);
return (prototype3 === null || prototype3 === Object.prototype || Object.getPrototypeOf(prototype3) === null) && !(Symbol.toStringTag in val) && !(Symbol.iterator in val);
};
var isDate = kindOfTest("Date");
var isFile = kindOfTest("File");
var isBlob = kindOfTest("Blob");
var isFileList = kindOfTest("FileList");
var isStream = (val) => isObject2(val) && isFunction(val.pipe);
var isFormData = (thing) => {
let kind;
return thing && (typeof FormData === "function" && thing instanceof FormData || isFunction(thing.append) && ((kind = kindOf(thing)) === "formdata" || // detect form-data instance
kind === "object" && isFunction(thing.toString) && thing.toString() === "[object FormData]"));
};
var isURLSearchParams = kindOfTest("URLSearchParams");
var [isReadableStream, isRequest, isResponse, isHeaders] = ["ReadableStream", "Request", "Response", "Headers"].map(kindOfTest);
var trim = (str) => str.trim ? str.trim() : str.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, "");
function forEach(obj, fn, { allOwnKeys = false } = {}) {
if (obj === null || typeof obj === "undefined") {
return;
}
let i;
let l;
if (typeof obj !== "object") {
obj = [obj];
}
if (isArray(obj)) {
for (i = 0, l = obj.length; i < l; i++) {
fn.call(null, obj[i], i, obj);
}
} else {
const keys = allOwnKeys ? Object.getOwnPropertyNames(obj) : Object.keys(obj);
const len = keys.length;
let key;
for (i = 0; i < len; i++) {
key = keys[i];
fn.call(null, obj[key], key, obj);
}
}
}
function findKey(obj, key) {
key = key.toLowerCase();
const keys = Object.keys(obj);
let i = keys.length;
let _key;
while (i-- > 0) {
_key = keys[i];
if (key === _key.toLowerCase()) {
return _key;
}
}
return null;
}
var _global = (() => {
if (typeof globalThis !== "undefined") return globalThis;
return typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : global;
})();
var isContextDefined = (context) => !isUndefined(context) && context !== _global;
function merge() {
const { caseless } = isContextDefined(this) && this || {};
const result = {};
const assignValue = (val, key) => {
const targetKey = caseless && findKey(result, key) || key;
if (isPlainObject(result[targetKey]) && isPlainObject(val)) {
result[targetKey] = merge(result[targetKey], val);
} else if (isPlainObject(val)) {
result[targetKey] = merge({}, val);
} else if (isArray(val)) {
result[targetKey] = val.slice();
} else {
result[targetKey] = val;
}
};
for (let i = 0, l = arguments.length; i < l; i++) {
arguments[i] && forEach(arguments[i], assignValue);
}
return result;
}
var extend = (a, b, thisArg, { allOwnKeys } = {}) => {
forEach(b, (val, key) => {
if (thisArg && isFunction(val)) {
a[key] = bind(val, thisArg);
} else {
a[key] = val;
}
}, { allOwnKeys });
return a;
};
var stripBOM = (content) => {
if (content.charCodeAt(0) === 65279) {
content = content.slice(1);
}
return content;
};
var inherits = (constructor, superConstructor, props, descriptors2) => {
constructor.prototype = Object.create(superConstructor.prototype, descriptors2);
constructor.prototype.constructor = constructor;
Object.defineProperty(constructor, "super", {
value: superConstructor.prototype
});
props && Object.assign(constructor.prototype, props);
};
var toFlatObject = (sourceObj, destObj, filter2, propFilter) => {
let props;
let i;
let prop;
const merged = {};
destObj = destObj || {};
if (sourceObj == null) return destObj;
do {
props = Object.getOwnPropertyNames(sourceObj);
i = props.length;
while (i-- > 0) {
prop = props[i];
if ((!propFilter || propFilter(prop, sourceObj, destObj)) && !merged[prop]) {
destObj[prop] = sourceObj[prop];
merged[prop] = true;
}
}
sourceObj = filter2 !== false && getPrototypeOf(sourceObj);
} while (sourceObj && (!filter2 || filter2(sourceObj, destObj)) && sourceObj !== Object.prototype);
return destObj;
};
var endsWith = (str, searchString, position) => {
str = String(str);
if (position === void 0 || position > str.length) {
position = str.length;
}
position -= searchString.length;
const lastIndex = str.indexOf(searchString, position);
return lastIndex !== -1 && lastIndex === position;
};
var toArray = (thing) => {
if (!thing) return null;
if (isArray(thing)) return thing;
let i = thing.length;
if (!isNumber(i)) return null;
const arr = new Array(i);
while (i-- > 0) {
arr[i] = thing[i];
}
return arr;
};
var isTypedArray = /* @__PURE__ */ ((TypedArray2) => {
return (thing) => {
return TypedArray2 && thing instanceof TypedArray2;
};
})(typeof Uint8Array !== "undefined" && getPrototypeOf(Uint8Array));
var forEachEntry = (obj, fn) => {
const generator = obj && obj[Symbol.iterator];
const iterator = generator.call(obj);
let result;
while ((result = iterator.next()) && !result.done) {
const pair = result.value;
fn.call(obj, pair[0], pair[1]);
}
};
var matchAll = (regExp, str) => {
let matches;
const arr = [];
while ((matches = regExp.exec(str)) !== null) {
arr.push(matches);
}
return arr;
};
var isHTMLForm = kindOfTest("HTMLFormElement");
var toCamelCase = (str) => {
return str.toLowerCase().replace(
/[-_\s]([a-z\d])(\w*)/g,
function replacer(m, p1, p2) {
return p1.toUpperCase() + p2;
}
);
};
var hasOwnProperty = (({ hasOwnProperty: hasOwnProperty2 }) => (obj, prop) => hasOwnProperty2.call(obj, prop))(Object.prototype);
var isRegExp = kindOfTest("RegExp");
var reduceDescriptors = (obj, reducer) => {
const descriptors2 = Object.getOwnPropertyDescriptors(obj);
const reducedDescriptors = {};
forEach(descriptors2, (descriptor, name) => {
let ret;
if ((ret = reducer(descriptor, name, obj)) !== false) {
reducedDescriptors[name] = ret || descriptor;
}
});
Object.defineProperties(obj, reducedDescriptors);
};
var freezeMethods = (obj) => {
reduceDescriptors(obj, (descriptor, name) => {
if (isFunction(obj) && ["arguments", "caller", "callee"].indexOf(name) !== -1) {
return false;
}
const value = obj[name];
if (!isFunction(value)) return;
descriptor.enumerable = false;
if ("writable" in descriptor) {
descriptor.writable = false;
return;
}
if (!descriptor.set) {
descriptor.set = () => {
throw Error("Can not rewrite read-only method '" + name + "'");
};
}
});
};
var toObjectSet = (arrayOrString, delimiter) => {
const obj = {};
const define = (arr) => {
arr.forEach((value) => {
obj[value] = true;
});
};
isArray(arrayOrString) ? define(arrayOrString) : define(String(arrayOrString).split(delimiter));
return obj;
};
var noop = () => {
};
var toFiniteNumber = (value, defaultValue) => {
return value != null && Number.isFinite(value = +value) ? value : defaultValue;
};
var ALPHA = "abcdefghijklmnopqrstuvwxyz";
var DIGIT = "0123456789";
var ALPHABET = {
DIGIT,
ALPHA,
ALPHA_DIGIT: ALPHA + ALPHA.toUpperCase() + DIGIT
};
var generateString = (size = 16, alphabet = ALPHABET.ALPHA_DIGIT) => {
let str = "";
const { length } = alphabet;
while (size--) {
str += alphabet[Math.random() * length | 0];
}
return str;
};
function isSpecCompliantForm(thing) {
return !!(thing && isFunction(thing.append) && thing[Symbol.toStringTag] === "FormData" && thing[Symbol.iterator]);
}
var toJSONObject = (obj) => {
const stack = new Array(10);
const visit = (source, i) => {
if (isObject2(source)) {
if (stack.indexOf(source) >= 0) {
return;
}
if (!("toJSON" in source)) {
stack[i] = source;
const target = isArray(source) ? [] : {};
forEach(source, (value, key) => {
const reducedValue = visit(value, i + 1);
!isUndefined(reducedValue) && (target[key] = reducedValue);
});
stack[i] = void 0;
return target;
}
}
return source;
};
return visit(obj, 0);
};
var isAsyncFn = kindOfTest("AsyncFunction");
var isThenable = (thing) => thing && (isObject2(thing) || isFunction(thing)) && isFunction(thing.then) && isFunction(thing.catch);
var _setImmediate = ((setImmediateSupported, postMessageSupported) => {
if (setImmediateSupported) {
return setImmediate;
}
return postMessageSupported ? ((token, callbacks) => {
_global.addEventListener("message", ({ source, data }) => {
if (source === _global && data === token) {
callbacks.length && callbacks.shift()();
}
}, false);
return (cb) => {
callbacks.push(cb);
_global.postMessage(token, "*");
};
})(`axios@${Math.random()}`, []) : (cb) => setTimeout(cb);
})(
typeof setImmediate === "function",
isFunction(_global.postMessage)
);
var asap = typeof queueMicrotask !== "undefined" ? queueMicrotask.bind(_global) : typeof process !== "undefined" && process.nextTick || _setImmediate;
var utils_default = {
isArray,
isArrayBuffer,
isBuffer,
isFormData,
isArrayBufferView,
isString,
isNumber,
isBoolean,
isObject: isObject2,
isPlainObject,
isReadableStream,
isRequest,
isResponse,
isHeaders,
isUndefined,
isDate,
isFile,
isBlob,
isRegExp,
isFunction,
isStream,
isURLSearchParams,
isTypedArray,
isFileList,
forEach,
merge,
extend,
trim,
stripBOM,
inherits,
toFlatObject,
kindOf,
kindOfTest,
endsWith,
toArray,
forEachEntry,
matchAll,
isHTMLForm,
hasOwnProperty,
hasOwnProp: hasOwnProperty,
// an alias to avoid ESLint no-prototype-builtins detection
reduceDescriptors,
freezeMethods,
toObjectSet,
toCamelCase,
noop,
toFiniteNumber,
findKey,
global: _global,
isContextDefined,
ALPHABET,
generateString,
isSpecCompliantForm,
toJSONObject,
isAsyncFn,
isThenable,
setImmediate: _setImmediate,
asap
};
// ../../../node_modules/.pnpm/axios@1.7.4_debug@4.3.5/node_modules/axios/lib/core/AxiosError.js
function AxiosError(message, code, config, request, response) {
Error.call(this);
if (Error.captureStackTrace) {
Error.captureStackTrace(this, this.constructor);
} else {
this.stack = new Error().stack;
}
this.message = message;
this.name = "AxiosError";
code && (this.code = code);
config && (this.config = config);
request && (this.request = request);
response && (this.response = response);
}
utils_default.inherits(AxiosError, Error, {
toJSON: function toJSON() {
return {
// Standard
message: this.message,
name: this.name,
// Microsoft
description: this.description,
number: this.number,
// Mozilla
fileName: this.fileName,
lineNumber: this.lineNumber,
columnNumber: this.columnNumber,
stack: this.stack,
// Axios
config: utils_default.toJSONObject(this.config),
code: this.code,
status: this.response && this.response.status ? this.response.status : null
};
}
});
var prototype = AxiosError.prototype;
var descriptors = {};
[
"ERR_BAD_OPTION_VALUE",
"ERR_BAD_OPTION",
"ECONNABORTED",
"ETIMEDOUT",
"ERR_NETWORK",
"ERR_FR_TOO_MANY_REDIRECTS",
"ERR_DEPRECATED",
"ERR_BAD_RESPONSE",
"ERR_BAD_REQUEST",
"ERR_CANCELED",
"ERR_NOT_SUPPORT",
"ERR_INVALID_URL"
// eslint-disable-next-line func-names
].forEach((code) => {
descriptors[code] = { value: code };
});
Object.defineProperties(AxiosError, descriptors);
Object.defineProperty(prototype, "isAxiosError", { value: true });
AxiosError.from = (error, code, config, request, response, customProps) => {
const axiosError = Object.create(prototype);
utils_default.toFlatObject(error, axiosError, function filter2(obj) {
return obj !== Error.prototype;
}, (prop) => {
return prop !== "isAxiosError";
});
AxiosError.call(axiosError, error.message, code, config, request, response);
axiosError.cause = error;
axiosError.name = error.name;
customProps && Object.assign(axiosError, customProps);
return axiosError;
};
var AxiosError_default = AxiosError;
// ../../../node_modules/.pnpm/axios@1.7.4_debug@4.3.5/node_modules/axios/lib/helpers/null.js
var null_default = null;
// ../../../node_modules/.pnpm/axios@1.7.4_debug@4.3.5/node_modules/axios/lib/helpers/toFormData.js
function isVisitable(thing) {
return utils_default.isPlainObject(thing) || utils_default.isArray(thing);
}
function removeBrackets(key) {
return utils_default.endsWith(key, "[]") ? key.slice(0, -2) : key;
}
function renderKey(path, key, dots) {
if (!path) return key;
return path.concat(key).map(function each(token, i) {
token = removeBrackets(token);
return !dots && i ? "[" + token + "]" : token;
}).join(dots ? "." : "");
}
function isFlatArray(arr) {
return utils_default.isArray(arr) && !arr.some(isVisitable);
}
var predicates = utils_default.toFlatObject(utils_default, {}, null, function filter(prop) {
return /^is[A-Z]/.test(prop);
});
function toFormData(obj, formData, options) {
if (!utils_default.isObject(obj)) {
throw new TypeError("target must be an object");
}
formData = formData || new (null_default || FormData)();
options = utils_default.toFlatObject(options, {
metaTokens: true,
dots: false,
indexes: false
}, false, function defined(option, source) {
return !utils_default.isUndefined(source[option]);
});
const metaTokens = options.metaTokens;
const visitor = options.visitor || defaultVisitor;
const dots = options.dots;
const indexes = options.indexes;
const _Blob = options.Blob || typeof Blob !== "undefined" && Blob;
const useBlob = _Blob && utils_default.isSpecCompliantForm(formData);
if (!utils_default.isFunction(visitor)) {
throw new TypeError("visitor must be a function");
}
function convertValue(value) {
if (value === null) return "";
if (utils_default.isDate(value)) {
return value.toISOString();
}
if (!useBlob && utils_default.isBlob(value)) {
throw new AxiosError_default("Blob is not supported. Use a Buffer instead.");
}
if (utils_default.isArrayBuffer(value) || utils_default.isTypedArray(value)) {
return useBlob && typeof Blob === "function" ? new Blob([value]) : Buffer.from(value);
}
return value;
}
function defaultVisitor(value, key, path) {
let arr = value;
if (value && !path && typeof value === "object") {
if (utils_default.endsWith(key, "{}")) {
key = metaTokens ? key : key.slice(0, -2);
value = JSON.stringify(value);
} else if (utils_default.isArray(value) && isFlatArray(value) || (utils_default.isFileList(value) || utils_default.endsWith(key, "[]")) && (arr = utils_default.toArray(value))) {
key = removeBrackets(key);
arr.forEach(function each(el, index) {
!(utils_default.isUndefined(el) || el === null) && formData.append(
// eslint-disable-next-line no-nested-ternary
indexes === true ? renderKey([key], index, dots) : indexes === null ? key : key + "[]",
convertValue(el)
);
});
return false;
}
}
if (isVisitable(value)) {
return true;
}
formData.append(renderKey(path, key, dots), convertValue(value));
return false;
}
const stack = [];
const exposedHelpers = Object.assign(predicates, {
defaultVisitor,
convertValue,
isVisitable
});
function build(value, path) {
if (utils_default.isUndefined(value)) return;
if (stack.indexOf(value) !== -1) {
throw Error("Circular reference detected in " + path.join("."));
}
stack.push(value);
utils_default.forEach(value, function each(el, key) {
const result = !(utils_default.isUndefined(el) || el === null) && visitor.call(
formData,
el,
utils_default.isString(key) ? key.trim() : key,
path,
exposedHelpers
);
if (result === true) {
build(el, path ? path.concat(key) : [key]);
}
});
stack.pop();
}
if (!utils_default.isObject(obj)) {
throw new TypeError("data must be an object");
}
build(obj);
return formData;
}
var toFormData_default = toFormData;
// ../../../node_modules/.pnpm/axios@1.7.4_debug@4.3.5/node_modules/axios/lib/helpers/AxiosURLSearchParams.js
function encode(str) {
const charMap = {
"!": "%21",
"'": "%27",
"(": "%28",
")": "%29",
"~": "%7E",
"%20": "+",
"%00": "\0"
};
return encodeURIComponent(str).replace(/[!'()~]|%20|%00/g, function replacer(match) {
return charMap[match];
});
}
function AxiosURLSearchParams(params, options) {
this._pairs = [];
params && toFormData_default(params, this, options);
}
var prototype2 = AxiosURLSearchParams.prototype;
prototype2.append = function append(name, value) {
this._pairs.push([name, value]);
};
prototype2.toString = function toString2(encoder2) {
const _encode = encoder2 ? function(value) {
return encoder2.call(this, value, encode);
} : encode;
return this._pairs.map(function each(pair) {
return _encode(pair[0]) + "=" + _encode(pair[1]);
}, "").join("&");
};
var AxiosURLSearchParams_default = AxiosURLSearchParams;
// ../../../node_modules/.pnpm/axios@1.7.4_debug@4.3.5/node_modules/axios/lib/helpers/buildURL.js
function encode2(val) {
return encodeURIComponent(val).replace(/%3A/gi, ":").replace(/%24/g, "$").replace(/%2C/gi, ",").replace(/%20/g, "+").replace(/%5B/gi, "[").replace(/%5D/gi, "]");
}
function buildURL(url, params, options) {
if (!params) {
return url;
}
const _encode = options && options.encode || encode2;
const serializeFn = options && options.serialize;
let serializedParams;
if (serializeFn) {
serializedParams = serializeFn(params, options);
} else {
serializedParams = utils_default.isURLSearchParams(params) ? params.toString() : new AxiosURLSearchParams_default(params, options).toString(_encode);
}
if (serializedParams) {
const hashmarkIndex = url.indexOf("#");
if (hashmarkIndex !== -1) {
url = url.slice(0, hashmarkIndex);
}
url += (url.indexOf("?") === -1 ? "?" : "&") + serializedParams;
}
return url;
}
// ../../../node_modules/.pnpm/axios@1.7.4_debug@4.3.5/node_modules/axios/lib/core/InterceptorManager.js
var InterceptorManager = class {
constructor() {
this.handlers = [];
}
/**
* Add a new interceptor to the stack
*
* @param {Function} fulfilled The function to handle `then` for a `Promise`
* @param {Function} rejected The function to handle `reject` for a `Promise`
*
* @return {Number} An ID used to remove interceptor later
*/
use(fulfilled, rejected, options) {
this.handlers.push({
fulfilled,
rejected,
synchronous: options ? options.synchronous : false,
runWhen: options ? options.runWhen : null
});
return this.handlers.length - 1;
}
/**
* Remove an interceptor from the stack
*
* @param {Number} id The ID that was returned by `use`
*
* @returns {Boolean} `true` if the interceptor was removed, `false` otherwise
*/
eject(id) {
if (this.handlers[id]) {
this.handlers[id] = null;
}
}
/**
* Clear all interceptors from the stack
*
* @returns {void}
*/
clear() {
if (this.handlers) {
this.handlers = [];
}
}
/**
* Iterate over all the registered interceptors
*
* This method is particularly useful for skipping over any
* interceptors that