osra 0.1.1 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sources":["../node_modules/uuid/dist/esm-browser/stringify.js","../node_modules/uuid/dist/esm-browser/rng.js","../node_modules/uuid/dist/esm-browser/native.js","../node_modules/uuid/dist/esm-browser/v4.js","../src/types.ts","../src/utils.ts","../src/index.ts"],"sourcesContent":["import validate from './validate.js';\nconst byteToHex = [];\nfor (let i = 0; i < 256; ++i) {\n byteToHex.push((i + 0x100).toString(16).slice(1));\n}\nexport function unsafeStringify(arr, offset = 0) {\n return (byteToHex[arr[offset + 0]] +\n byteToHex[arr[offset + 1]] +\n byteToHex[arr[offset + 2]] +\n byteToHex[arr[offset + 3]] +\n '-' +\n byteToHex[arr[offset + 4]] +\n byteToHex[arr[offset + 5]] +\n '-' +\n byteToHex[arr[offset + 6]] +\n byteToHex[arr[offset + 7]] +\n '-' +\n byteToHex[arr[offset + 8]] +\n byteToHex[arr[offset + 9]] +\n '-' +\n byteToHex[arr[offset + 10]] +\n byteToHex[arr[offset + 11]] +\n byteToHex[arr[offset + 12]] +\n byteToHex[arr[offset + 13]] +\n byteToHex[arr[offset + 14]] +\n byteToHex[arr[offset + 15]]).toLowerCase();\n}\nfunction stringify(arr, offset = 0) {\n const uuid = unsafeStringify(arr, offset);\n if (!validate(uuid)) {\n throw TypeError('Stringified UUID is invalid');\n }\n return uuid;\n}\nexport default stringify;\n","let getRandomValues;\nconst rnds8 = new Uint8Array(16);\nexport default function rng() {\n if (!getRandomValues) {\n if (typeof crypto === 'undefined' || !crypto.getRandomValues) {\n throw new Error('crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported');\n }\n getRandomValues = crypto.getRandomValues.bind(crypto);\n }\n return getRandomValues(rnds8);\n}\n","const randomUUID = typeof crypto !== 'undefined' && crypto.randomUUID && crypto.randomUUID.bind(crypto);\nexport default { randomUUID };\n","import native from './native.js';\nimport rng from './rng.js';\nimport { unsafeStringify } from './stringify.js';\nfunction v4(options, buf, offset) {\n if (native.randomUUID && !buf && !options) {\n return native.randomUUID();\n }\n options = options || {};\n const rnds = options.random || (options.rng || rng)();\n rnds[6] = (rnds[6] & 0x0f) | 0x40;\n rnds[8] = (rnds[8] & 0x3f) | 0x80;\n if (buf) {\n offset = offset || 0;\n for (let i = 0; i < 16; ++i) {\n buf[offset + i] = rnds[i];\n }\n return buf;\n }\n return unsafeStringify(rnds);\n}\nexport default v4;\n","export const OSRA_MESSAGE_PROPERTY = '__OSRA__' as const\r\nexport const OSRA_MESSAGE_KEY = '__OSRA_DEFAULT_KEY__' as const\r\nexport const OSRA_PROXY = '__OSRA_PROXY__' as const\r\n\r\nexport type JsonPropertyKey = string | number\r\nexport type JsonCloneType =\r\n | boolean\r\n | null\r\n | number\r\n | string\r\n | { [key: string]: JsonCloneType }\r\n | Array<JsonCloneType>\r\n\r\nexport type StructuredCloneType =\r\n | JsonCloneType\r\n | void\r\n | undefined\r\n | BigInt\r\n | Date\r\n | RegExp\r\n | Blob\r\n | File\r\n | FileList\r\n | ArrayBuffer\r\n | ArrayBufferView\r\n | ImageBitmap\r\n | ImageData\r\n | { [key: string]: StructuredCloneType }\r\n | Array<StructuredCloneType>\r\n | Map<StructuredCloneType, StructuredCloneType>\r\n | Set<StructuredCloneType>\r\n\r\nexport type TransferableObject =\r\n | SharedArrayBuffer\r\n | ArrayBuffer\r\n | MessagePort\r\n | ReadableStream\r\n /*\r\n | WritableStream\r\n | TransformStream\r\n | ImageBitmap\r\n | AudioData\r\n | VideoFrame\r\n | OffscreenCanvas\r\n */\r\n\r\nexport type StructuredCloneTransferableType =\r\n | StructuredCloneType\r\n | TransferableObject\r\n | { [key: string]: StructuredCloneTransferableType }\r\n | Array<StructuredCloneTransferableType>\r\n | Map<StructuredCloneTransferableType, StructuredCloneTransferableType>\r\n | Set<StructuredCloneTransferableType>\r\n\r\nexport type ProxiableType =\r\n | Promise<StructuredCloneTransferableProxiableType>\r\n | Error\r\n | MessagePort\r\n | ReadableStream\r\n | ((...args: any[]) => Promise<StructuredCloneTransferableProxiableType>)\r\n // | ((...args: StructuredCloneTransferableProxiableType[]) => StructuredCloneTransferableProxiableType)\r\n | { [key: string]: StructuredCloneTransferableProxiableType }\r\n | Array<StructuredCloneTransferableProxiableType>\r\n | Map<StructuredCloneTransferableProxiableType, StructuredCloneTransferableProxiableType>\r\n | Set<StructuredCloneTransferableProxiableType>\r\n\r\nexport type StructuredCloneTransferableProxiableType = ProxiableType | StructuredCloneTransferableType\r\n\r\ntype PortOrJsonPort<JsonOnly extends boolean> = JsonOnly extends true ? { portId: string } : { port: MessagePort }\r\ntype StructuredCloneDataOrJsonData<JsonOnly extends boolean> = JsonOnly extends true ? JsonCloneType : StructuredCloneType\r\n\r\nexport type ProxiedFunctionType<JsonOnly extends boolean> = ({ type: 'function' } & PortOrJsonPort<JsonOnly>)\r\nexport type ProxiedMessagePortType<JsonOnly extends boolean> = ({ type: 'messagePort' } & PortOrJsonPort<JsonOnly>)\r\nexport type ProxiedPromiseType<JsonOnly extends boolean> = ({ type: 'promise' } & PortOrJsonPort<JsonOnly>)\r\nexport type ProxiedReadableStreamType<JsonOnly extends boolean> = ({ type: 'readableStream' } & PortOrJsonPort<JsonOnly>)\r\nexport type ProxiedErrorType = ({ type: 'error', message: string, stack?: string })\r\n\r\nexport type ProxiedType<JsonOnly extends boolean> =\r\n { [OSRA_PROXY]: true } & (\r\n | ProxiedFunctionType<JsonOnly>\r\n | ProxiedMessagePortType<JsonOnly>\r\n | ProxiedPromiseType<JsonOnly>\r\n | ProxiedReadableStreamType<JsonOnly>\r\n | ProxiedErrorType\r\n )\r\nexport type OsraMessage =\r\n { [OSRA_MESSAGE_PROPERTY]: true, key: string } & (\r\n | { type: 'ready', envCheck: { buffer: ArrayBuffer, port: MessagePort } }\r\n | { type: 'init', data: StructuredCloneTransferableType }\r\n | { type: 'message', portId: string, data: any } // message not needed if transferring MessagePort is supported\r\n | { type: 'port-closed', portId: string } // message not needed if transferring MessagePort is supported\r\n )\r\n\r\nexport type RemoteTarget = Window | ServiceWorker | Worker | MessagePort\r\nexport type LocalTarget = WindowEventHandlers | ServiceWorkerContainer | Worker | SharedWorker\r\n","import type {\r\n StructuredCloneTransferableType, TransferableObject, ProxiedErrorType,\r\n ProxiedFunctionType, ProxiedMessagePortType, ProxiedPromiseType,\r\n ProxiedType, StructuredCloneTransferableProxiableType,\r\n} from './types'\r\n\r\nimport { OSRA_PROXY } from './types'\r\n\r\nexport const isClonable = (value: any) =>\r\n globalThis.SharedArrayBuffer && value instanceof globalThis.SharedArrayBuffer ? true\r\n : false\r\n\r\nexport const isTransferable = (value: any) =>\r\n globalThis.ArrayBuffer && value instanceof globalThis.ArrayBuffer ? true\r\n : globalThis.MessagePort && value instanceof globalThis.MessagePort ? true\r\n : globalThis.ReadableStream && value instanceof globalThis.ReadableStream ? true\r\n : globalThis.WritableStream && value instanceof globalThis.WritableStream ? true\r\n : globalThis.TransformStream && value instanceof globalThis.TransformStream ? true\r\n : globalThis.ImageBitmap && value instanceof globalThis.ImageBitmap ? true\r\n : false\r\n\r\nexport const getTransferableObjects = (value: any): TransferableObject[] => {\r\n const transferables: TransferableObject[] = []\r\n const recurse = (value: any) => \r\n isClonable(value) ? undefined\r\n : isTransferable(value) ? transferables.push(value)\r\n : Array.isArray(value) ? value.map(recurse)\r\n : value && typeof value === 'object' ? Object.values(value).map(recurse)\r\n : undefined\r\n\r\n recurse(value)\r\n return transferables\r\n}\r\n\r\nexport type EnvCheck = {\r\n uuid: string\r\n supportsPorts: boolean\r\n jsonOnly: boolean\r\n}\r\n\r\nexport type Context = {\r\n envCheck: EnvCheck\r\n addIncomingProxiedMessagePort: (portId: string) => MessagePort\r\n addOutgoingProxiedMessagePort: (port: MessagePort) => string\r\n finalizationRegistry: FinalizationRegistry<number>\r\n}\r\n\r\nexport const proxiedFunctionToFunction = <JsonOnly extends boolean>(proxiedFunction: ProxiedFunctionType<JsonOnly>, context: Context) => {\r\n const portId = 'portId' in proxiedFunction ? proxiedFunction.portId : undefined\r\n const port =\r\n 'port' in proxiedFunction ? proxiedFunction.port\r\n : portId ? context.addIncomingProxiedMessagePort(portId)\r\n : undefined\r\n if (!port) throw new Error(`No ports received for proxied function`)\r\n\r\n const func = (...args: StructuredCloneTransferableType[]) =>\r\n new Promise((resolve, reject) => {\r\n const { port1: returnValueLocalPort, port2: returnValueRemotePort } = new MessageChannel()\r\n const functionContext = replaceOutgoingProxiedTypes([returnValueRemotePort, args], context)\r\n const functionContextTransferables = getTransferableObjects(functionContext)\r\n const listener = (event: MessageEvent) => {\r\n const result = replaceIncomingProxiedTypes(event.data, context)\r\n if (!(result instanceof Promise)) throw new Error(`Proxied function did not return a promise`)\r\n\r\n result\r\n .then(resolve)\r\n .catch(reject)\r\n .finally(() => returnValueLocalPort.close())\r\n }\r\n returnValueLocalPort.addEventListener('message', listener, { once: true })\r\n returnValueLocalPort.start()\r\n port.postMessage(functionContext, { transfer: functionContextTransferables })\r\n })\r\n\r\n if (portId) {\r\n context.finalizationRegistry.register(func, Number(portId.split('/')[1]))\r\n }\r\n\r\n return func\r\n}\r\n\r\nexport const proxiedMessagePortToMessagePort = <JsonOnly extends boolean>(proxiedMessagePort: ProxiedMessagePortType<JsonOnly>, context: Context) => {\r\n const port =\r\n context.envCheck.supportsPorts && 'port' in proxiedMessagePort ? proxiedMessagePort.port\r\n : 'portId' in proxiedMessagePort ? context.addIncomingProxiedMessagePort(proxiedMessagePort.portId)\r\n : undefined\r\n if (!port) throw new Error(`No ports received for proxied message port`)\r\n return port\r\n}\r\n\r\nexport const proxiedErrorToError = (proxiedError: ProxiedErrorType, context: Context) =>\r\n new Error(proxiedError.message, { cause: proxiedError.stack })\r\n\r\nexport const proxiedPromiseToPromise = <JsonOnly extends boolean>(proxiedPromise: ProxiedPromiseType<JsonOnly>, context: Context) =>\r\n new Promise((resolve, reject) => {\r\n const port =\r\n 'port' in proxiedPromise ? proxiedPromise.port\r\n : 'portId' in proxiedPromise ? context.addIncomingProxiedMessagePort(proxiedPromise.portId)\r\n : undefined\r\n if (!port) throw new Error(`No ports received for proxied promise`)\r\n const listener = async (event: MessageEvent) => {\r\n const result = await replaceIncomingProxiedTypes(event.data, context)\r\n if (result instanceof Error) reject(result)\r\n else resolve(result)\r\n port.close()\r\n }\r\n port.addEventListener('message', listener, { once: true })\r\n port.start()\r\n })\r\n\r\nexport const replaceIncomingProxiedTypes = (value: StructuredCloneTransferableType, context: Context): StructuredCloneTransferableProxiableType =>\r\n replaceRecursive(\r\n value,\r\n (value) => Boolean(\r\n value && typeof value === 'object' && OSRA_PROXY in value && value[OSRA_PROXY]\r\n ),\r\n (proxiedValue: ProxiedType<boolean>) => {\r\n if (proxiedValue.type === 'function') {\r\n return proxiedFunctionToFunction(proxiedValue, context)\r\n } else if (proxiedValue.type === 'error') {\r\n return proxiedErrorToError(proxiedValue, context)\r\n } else if (proxiedValue.type === 'messagePort') {\r\n return proxiedMessagePortToMessagePort(proxiedValue, context)\r\n } else if (proxiedValue.type === 'promise') {\r\n return proxiedPromiseToPromise(proxiedValue, context)\r\n }\r\n throw new Error(`Unknown incoming proxied type: ${value}`)\r\n })\r\n\r\nexport const errorToProxiedError = (error: Error, _: Context) => ({\r\n [OSRA_PROXY]: true,\r\n type: 'error',\r\n message: error.message,\r\n stack: error.stack\r\n})\r\n\r\nexport const messagePortToProxiedMessagePort = (port: MessagePort, context: Context) => ({\r\n [OSRA_PROXY]: true,\r\n type: 'messagePort',\r\n ...context.envCheck.supportsPorts\r\n ? { port }\r\n : { portId: context.addOutgoingProxiedMessagePort(port) }\r\n})\r\n\r\nexport const promiseToProxiedPromise = (promise: Promise<StructuredCloneTransferableType>, context: Context) => {\r\n const { port1: localPort, port2: remotePort } = new MessageChannel()\r\n\r\n const sendResult = (resultOrError: StructuredCloneTransferableType) => {\r\n const proxiedResult = replaceOutgoingProxiedTypes(resultOrError, context)\r\n const transferables = getTransferableObjects(proxiedResult)\r\n localPort.postMessage(proxiedResult, { transfer: transferables })\r\n localPort.close()\r\n }\r\n\r\n promise\r\n .then(sendResult)\r\n .catch(sendResult)\r\n\r\n return {\r\n [OSRA_PROXY]: true,\r\n type: 'promise',\r\n port: replaceOutgoingProxiedTypes(remotePort, context)\r\n }\r\n}\r\n\r\nexport const functionToProxiedFunction = (func: Function, context: Context) => {\r\n const { port1: localPort, port2: remotePort } = new MessageChannel()\r\n localPort.addEventListener('message', async (ev: MessageEvent<[ProxiedType<boolean>, StructuredCloneTransferableType[]]>) => {\r\n const [returnValuePort, args] = replaceIncomingProxiedTypes(ev.data, context) as [MessagePort, StructuredCloneTransferableType[]]\r\n const result = (async () => func(...args))()\r\n const proxiedResult = replaceOutgoingProxiedTypes(result, context)\r\n const transferables = getTransferableObjects(proxiedResult)\r\n returnValuePort.postMessage(proxiedResult, { transfer: transferables })\r\n returnValuePort.close()\r\n })\r\n localPort.start()\r\n return {\r\n [OSRA_PROXY]: true,\r\n type: 'function',\r\n port: replaceOutgoingProxiedTypes(remotePort, context)\r\n }\r\n}\r\n\r\nexport const replaceOutgoingProxiedTypes = <T extends StructuredCloneTransferableProxiableType>(value: T, context: Context) =>\r\n replaceRecursive(\r\n value,\r\n (value) => typeof value === 'function' || value instanceof Error || value instanceof MessagePort || value instanceof Promise,\r\n (value) => {\r\n if (typeof value === 'function') {\r\n return functionToProxiedFunction(value, context)\r\n } else if (value instanceof Error) {\r\n return errorToProxiedError(value, context)\r\n } else if (value instanceof MessagePort) {\r\n return messagePortToProxiedMessagePort(value, context)\r\n } else if (value instanceof Promise) {\r\n return promiseToProxiedPromise(value, context)\r\n }\r\n throw new Error(`Unknown outgoing proxied type: ${value}`)\r\n }\r\n )\r\n\r\nexport const replaceRecursive = <\r\n T extends StructuredCloneTransferableProxiableType,\r\n T2 extends (value: any) => any\r\n>(\r\n value: T,\r\n shouldReplace: (value: Parameters<T2>[0]) => boolean,\r\n replaceFunction: T2\r\n) =>\r\n isClonable(value) ? value\r\n : isTransferable(value) ? value\r\n : shouldReplace(value) ? replaceFunction(value)\r\n : Array.isArray(value) ? value.map(value => replaceRecursive(value, shouldReplace, replaceFunction))\r\n : value && typeof value === 'object' ? (\r\n Object.fromEntries(\r\n Object\r\n .entries(value)\r\n .map(([key, value]) => [\r\n key,\r\n replaceRecursive(value, shouldReplace, replaceFunction)\r\n ])\r\n )\r\n )\r\n : value\r\n\r\nexport const makeNumberAllocator = () => {\r\n let highest = 0\r\n const freedUnused = new Set<number>()\r\n return {\r\n alloc: () => {\r\n if (freedUnused.size > 0) {\r\n const number = freedUnused.values().next().value\r\n if (number === undefined) {\r\n throw new Error(`Tried to allocate number from freedUnused but result was undefined`)\r\n }\r\n freedUnused.delete(number)\r\n return number\r\n }\r\n highest++\r\n return highest\r\n },\r\n free: (number) => {\r\n freedUnused.add(number)\r\n }\r\n }\r\n}\r\n\r\ntype NumberAllocator = ReturnType<typeof makeNumberAllocator>\r\n\r\nexport const makeAllocator = <T>({ numberAllocator }: { numberAllocator: NumberAllocator }) => {\r\n const channels = new Map<number, T>()\r\n\r\n const alloc = (value: T) => {\r\n const id = numberAllocator.alloc()\r\n channels.set(id, value)\r\n return id\r\n }\r\n const get = (id: number) => channels.get(id)\r\n const free = (id: number) => {\r\n channels.delete(id)\r\n numberAllocator.free(id)\r\n }\r\n\r\n return {\r\n alloc,\r\n get,\r\n free\r\n }\r\n}\r\ntype Allocator<T> = ReturnType<typeof makeAllocator<T>>\r\n","import type { RemoteTarget, StructuredCloneTransferableType, LocalTarget, OsraMessage, StructuredCloneTransferableProxiableType } from './types'\r\nimport type { Context, EnvCheck } from './utils'\r\n\r\nimport { v4 as uuidv4 } from 'uuid'\r\n\r\nimport { OSRA_MESSAGE_KEY, OSRA_MESSAGE_PROPERTY } from './types'\r\nimport { getTransferableObjects, makeAllocator, makeNumberAllocator, replaceIncomingProxiedTypes, replaceOutgoingProxiedTypes } from './utils'\r\n\r\nexport * from './utils'\r\n\r\nexport const expose = async <T extends StructuredCloneTransferableProxiableType>(\r\n value: StructuredCloneTransferableProxiableType,\r\n {\r\n remote: _remote,\r\n local: _local,\r\n key = OSRA_MESSAGE_KEY,\r\n origin = '*'\r\n }: {\r\n remote: RemoteTarget | ((osraMessage: OsraMessage, transferables: Transferable[]) => void)\r\n local: LocalTarget | ((listener: (event: MessageEvent<OsraMessage>) => void) => void)\r\n key?: string,\r\n origin?: string\r\n }\r\n): Promise<T> => {\r\n const uuid = uuidv4()\r\n\r\n let envCheck: EnvCheck | undefined\r\n const finalizationRegistry = new FinalizationRegistry<number>((value) => {\r\n const allocCallback = allocator.get(value)\r\n if (!allocCallback) throw new Error(`Osra received a port-closed message with an invalid portId \"${value}\".`)\r\n allocCallback()\r\n allocator.free(value)\r\n })\r\n const idAllocator = makeNumberAllocator()\r\n const allocator = makeAllocator<() => void>({ numberAllocator: idAllocator })\r\n const incomingSerializedPorts = new Map<string, MessagePort>()\r\n\r\n const addIncomingProxiedMessagePort = (portId: string) => {\r\n const { port1, port2 } = new MessageChannel()\r\n incomingSerializedPorts.set(portId, port1)\r\n return port2\r\n }\r\n\r\n const addOutgoingProxiedMessagePort = (port: MessagePort) => {\r\n const id = allocator.alloc(() => {\r\n port.close()\r\n })\r\n port.addEventListener('message', async (ev) => {\r\n remote(\r\n {\r\n [OSRA_MESSAGE_PROPERTY]: true,\r\n key,\r\n type: 'message',\r\n portId: `${uuid}/${id}`,\r\n data: replaceOutgoingProxiedTypes(ev.data, getContext())\r\n },\r\n []\r\n )\r\n })\r\n\r\n port.addEventListener('close', () => {\r\n idAllocator.free(id)\r\n remote(\r\n {\r\n [OSRA_MESSAGE_PROPERTY]: true,\r\n key,\r\n type: 'port-closed',\r\n portId: `${uuid}/${id}`\r\n },\r\n []\r\n )\r\n })\r\n return `${uuid}/${id}`\r\n }\r\n\r\n const getContext = (): Context => {\r\n if (!envCheck) throw new Error(`Osra context was accessed before the ready message was received.`)\r\n return {\r\n addIncomingProxiedMessagePort,\r\n addOutgoingProxiedMessagePort,\r\n envCheck,\r\n finalizationRegistry\r\n }\r\n }\r\n\r\n let resolveRemoteValues, rejectRemoteValues\r\n const remoteValues = new Promise<T2>((res, rej) => {\r\n resolveRemoteValues = res\r\n rejectRemoteValues = rej\r\n })\r\n\r\n const sendReady = () => {\r\n const buffer = new ArrayBuffer(1)\r\n const { port1 } = new MessageChannel()\r\n remote(\r\n {\r\n [OSRA_MESSAGE_PROPERTY]: true,\r\n key,\r\n type: 'ready',\r\n envCheck: { buffer: buffer, port: port1 }\r\n },\r\n [buffer, port1]\r\n )\r\n }\r\n\r\n let receivedReady = false\r\n const listener = async (event: MessageEvent<OsraMessage>) => {\r\n if (!event.data || typeof event.data !== 'object' || !event.data[OSRA_MESSAGE_PROPERTY] || event.data.key !== key) return\r\n const { type } = event.data\r\n\r\n if (type === 'ready' && !receivedReady) {\r\n receivedReady = true\r\n envCheck = {\r\n uuid,\r\n supportsPorts: event.data.envCheck.port instanceof MessagePort,\r\n jsonOnly: event.data.envCheck.buffer instanceof ArrayBuffer\r\n }\r\n sendReady()\r\n\r\n const proxiedValue = replaceOutgoingProxiedTypes(value, getContext())\r\n const transferables = getTransferableObjects(proxiedValue)\r\n remote(\r\n {\r\n [OSRA_MESSAGE_PROPERTY]: true,\r\n key,\r\n type: 'init',\r\n data: proxiedValue\r\n },\r\n transferables\r\n )\r\n return\r\n }\r\n\r\n if (!receivedReady || !envCheck) throw new Error(`Osra received a message before the ready message.`)\r\n\r\n if (type === 'init') {\r\n resolveRemoteValues(\r\n replaceIncomingProxiedTypes(\r\n event.data.data,\r\n getContext()\r\n )\r\n )\r\n return\r\n }\r\n\r\n if (type === 'message') {\r\n const { portId, data } = event.data\r\n const port = incomingSerializedPorts.get(portId)\r\n if (!port) throw new Error(`Osra received a message with portId set to \"${portId}\" but no port was found.`)\r\n port.postMessage(data)\r\n } else if (type === 'port-closed') {\r\n const { portId } = event.data\r\n const [messageUuid, _portNumberId] = portId.split('/')\r\n const messagePortId = Number(_portNumberId)\r\n if (!messagePortId) throw new Error(`Osra received a port-closed message with an invalid portId \"${portId}\".`)\r\n if (messageUuid !== uuid && messageUuid !== envCheck.uuid) throw new Error(`Osra received a port-closed message with an invalid portId's uuid \"${portId}\".`)\r\n\r\n if (messageUuid === uuid) {\r\n const unregisterCallback = allocator.get(messagePortId)\r\n if (!unregisterCallback) throw new Error(`Osra received a port-closed message with an invalid portId \"${portId}\".`)\r\n unregisterCallback()\r\n } else if (messageUuid === envCheck.uuid) {\r\n const port = incomingSerializedPorts.get(portId)\r\n if (!port) throw new Error(`Osra received a message with portId set to \"${portId}\" but no port was found.`)\r\n port.close()\r\n incomingSerializedPorts.delete(portId)\r\n }\r\n }\r\n }\r\n\r\n const remote =\r\n typeof _remote === 'function' ? _remote\r\n : (\r\n (osraMessage: OsraMessage, transferables: Transferable[] = []) =>\r\n _remote.postMessage(osraMessage, { targetOrigin: origin, transfer: transferables })\r\n )\r\n\r\n if (typeof _local === 'function') {\r\n _local(listener)\r\n } else {\r\n _local.addEventListener('message', listener as EventListener)\r\n }\r\n\r\n sendReady()\r\n\r\n return remoteValues\r\n}\r\n"],"names":["byteToHex","i","unsafeStringify","arr","offset","getRandomValues","rnds8","rng","randomUUID","native","v4","options","buf","rnds","OSRA_MESSAGE_PROPERTY","OSRA_MESSAGE_KEY","OSRA_PROXY","isClonable","value","isTransferable","getTransferableObjects","transferables","recurse","proxiedFunctionToFunction","proxiedFunction","context","portId","port","func","args","resolve","reject","returnValueLocalPort","returnValueRemotePort","functionContext","replaceOutgoingProxiedTypes","functionContextTransferables","listener","event","result","replaceIncomingProxiedTypes","proxiedMessagePortToMessagePort","proxiedMessagePort","proxiedErrorToError","proxiedError","proxiedPromiseToPromise","proxiedPromise","replaceRecursive","proxiedValue","errorToProxiedError","error","_","messagePortToProxiedMessagePort","promiseToProxiedPromise","promise","localPort","remotePort","sendResult","resultOrError","proxiedResult","functionToProxiedFunction","ev","returnValuePort","shouldReplace","replaceFunction","key","makeNumberAllocator","highest","freedUnused","number","makeAllocator","numberAllocator","channels","id","expose","_remote","_local","origin","uuid","uuidv4","envCheck","finalizationRegistry","allocCallback","allocator","idAllocator","incomingSerializedPorts","addIncomingProxiedMessagePort","port1","port2","addOutgoingProxiedMessagePort","remote","getContext","resolveRemoteValues","remoteValues","res","rej","sendReady","buffer","receivedReady","type","data","messageUuid","_portNumberId","messagePortId","unregisterCallback","osraMessage"],"mappings":"AACA,MAAMA,IAAY,CAAE;AACpB,SAASC,IAAI,GAAGA,IAAI,KAAK,EAAEA;AACvB,EAAAD,EAAU,MAAMC,IAAI,KAAO,SAAS,EAAE,EAAE,MAAM,CAAC,CAAC;AAE7C,SAASC,EAAgBC,GAAKC,IAAS,GAAG;AAC7C,UAAQJ,EAAUG,EAAIC,IAAS,CAAC,CAAC,IAC7BJ,EAAUG,EAAIC,IAAS,CAAC,CAAC,IACzBJ,EAAUG,EAAIC,IAAS,CAAC,CAAC,IACzBJ,EAAUG,EAAIC,IAAS,CAAC,CAAC,IACzB,MACAJ,EAAUG,EAAIC,IAAS,CAAC,CAAC,IACzBJ,EAAUG,EAAIC,IAAS,CAAC,CAAC,IACzB,MACAJ,EAAUG,EAAIC,IAAS,CAAC,CAAC,IACzBJ,EAAUG,EAAIC,IAAS,CAAC,CAAC,IACzB,MACAJ,EAAUG,EAAIC,IAAS,CAAC,CAAC,IACzBJ,EAAUG,EAAIC,IAAS,CAAC,CAAC,IACzB,MACAJ,EAAUG,EAAIC,IAAS,EAAE,CAAC,IAC1BJ,EAAUG,EAAIC,IAAS,EAAE,CAAC,IAC1BJ,EAAUG,EAAIC,IAAS,EAAE,CAAC,IAC1BJ,EAAUG,EAAIC,IAAS,EAAE,CAAC,IAC1BJ,EAAUG,EAAIC,IAAS,EAAE,CAAC,IAC1BJ,EAAUG,EAAIC,IAAS,EAAE,CAAC,GAAG,YAAa;AAClD;AC1BA,IAAIC;AACJ,MAAMC,IAAQ,IAAI,WAAW,EAAE;AAChB,SAASC,I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uB,MAAgBrB,EAAS,YAAY,IAAI,MAAM,sEAAsEtD,CAAM,IAAI;AAE3J,UAAI2E,MAAgBvB,GAAM;AAClB,cAAA0B,IAAqBrB,EAAU,IAAIoB,CAAa;AACtD,YAAI,CAACC,EAAoB,OAAM,IAAI,MAAM,+DAA+D9E,CAAM,IAAI;AAC/F,QAAA8E,EAAA;AAAA,MAAA,WACVH,MAAgBrB,EAAS,MAAM;AAClC,cAAArD,IAAO0D,EAAwB,IAAI3D,CAAM;AAC/C,YAAI,CAACC,EAAM,OAAM,IAAI,MAAM,+CAA+CD,CAAM,0BAA0B;AAC1G,QAAAC,EAAK,MAAM,GACX0D,EAAwB,OAAO3D,CAAM;AAAA,MAAA;AAAA,IACvC;AAAA,EAEJ,GAEMgE,IACJ,OAAOf,KAAY,aAAaA,IAE9B,CAAC8B,GAA0BpF,IAAgC,CAAA,MACzDsD,EAAQ,YAAY8B,GAAa,EAAE,cAAc5B,GAAQ,UAAUxD,GAAe;AAGpF,SAAA,OAAOuD,KAAW,aACpBA,EAAOvC,CAAQ,IAERuC,EAAA,iBAAiB,WAAWvC,CAAyB,GAGpD2D,EAAA,GAEHH;AACT;","x_google_ignoreList":[0,1,2,3]}
1
+ {"version":3,"file":"index.js","sources":["../src/types.ts","../src/utils/allocator.ts","../src/utils/platform.ts","../src/utils/type-guards.ts","../src/utils/transferable.ts","../src/utils/capabilities.ts","../src/utils/revivable.ts","../src/utils/connection.ts","../node_modules/typescript-event-target/dist/index.mjs","../src/index.ts"],"sourcesContent":["import { TypedEventTarget } from 'typescript-event-target'\r\nimport type { TypedArray, WebExtOnConnect, WebExtOnMessage, WebExtPort, WebExtRuntime, WebExtSender } from './utils/type-guards'\r\n\r\nexport const OSRA_KEY = '__OSRA_KEY__' as const\r\nexport const OSRA_DEFAULT_KEY = '__OSRA_DEFAULT_KEY__' as const\r\nexport const OSRA_BOX = '__OSRA_BOX__' as const\r\n\r\nexport type Uuid = `${string}-${string}-${string}-${string}-${string}`\r\n\r\nexport type Jsonable =\r\n | boolean\r\n | null\r\n | number\r\n | string\r\n | { [key: string]: Jsonable }\r\n | Array<Jsonable>\r\n\r\nexport type Structurable =\r\n | Jsonable\r\n /** not really structureable but here for convenience */\r\n | void\r\n | undefined\r\n | BigInt\r\n | Date\r\n | RegExp\r\n | Blob\r\n | File\r\n | FileList\r\n | ArrayBuffer\r\n | ArrayBufferView\r\n | ImageBitmap\r\n | ImageData\r\n | { [key: string]: Structurable }\r\n | Array<Structurable>\r\n | Map<Structurable, Structurable>\r\n | Set<Structurable>\r\n\r\nexport type TransferBox<T extends Transferable = Transferable> = {\r\n [OSRA_BOX]: 'transferable'\r\n value: T\r\n}\r\n\r\nexport type ReviveBoxBase<T extends RevivableVariant['type'] = RevivableVariant['type']> = {\r\n [OSRA_BOX]: 'revivable'\r\n type: T\r\n value?: RevivableVariantTypeToRevivableVariant<T>\r\n [Symbol.toPrimitive]?: Function\r\n valueOf?: Function\r\n toString?: Function\r\n toJSON?: Function\r\n}\r\n\r\nexport type RevivableMessagePort = {\r\n type: 'messagePort'\r\n portId: string\r\n}\r\n\r\nexport type RevivablePromiseContext =\r\n | {\r\n type: 'resolve'\r\n data: Capable\r\n }\r\n | {\r\n type: 'reject'\r\n error: string\r\n }\r\n\r\nexport type RevivablePromise = {\r\n type: 'promise'\r\n port: MessagePort\r\n}\r\n\r\nexport type RevivableFunctionCallContext = [\r\n /** MessagePort that will be used to send the result of the function call */\r\n MessagePort,\r\n /** Arguments that will be passed to the function call */\r\n Capable[]\r\n]\r\n\r\nexport type RevivableFunction = {\r\n type: 'function'\r\n port: MessagePort\r\n}\r\n\r\nexport type RevivableTypedArray = {\r\n type: 'typedArray'\r\n typedArrayType: 'Int8Array' | 'Uint8Array' | 'Uint8ClampedArray' | 'Int16Array' | 'Uint16Array' | 'Int32Array' | 'Uint32Array' | 'Float16Array' | 'Float32Array' | 'Float64Array' | 'BigInt64Array' | 'BigUint64Array'\r\n arrayBuffer: ArrayBuffer\r\n}\r\n\r\nexport type RevivableArrayBuffer = {\r\n type: 'arrayBuffer'\r\n base64Buffer: string\r\n}\r\n\r\nexport type RevivableReadableStreamPullContext = {\r\n type: 'pull' | 'cancel'\r\n}\r\n\r\nexport type RevivableReadableStream = {\r\n type: 'readableStream'\r\n port: MessagePort\r\n}\r\n\r\nexport type RevivableDate = {\r\n type: 'date'\r\n ISOString: string\r\n}\r\n\r\nexport type RevivableError = {\r\n type: 'error'\r\n message: string\r\n stack: string\r\n}\r\n\r\nexport type RevivableVariant =\r\n | RevivableMessagePort\r\n | RevivablePromise\r\n | RevivableFunction\r\n | RevivableTypedArray\r\n | RevivableArrayBuffer\r\n | RevivableReadableStream\r\n | RevivableDate\r\n | RevivableError\r\n\r\nexport type RevivableVariantType = RevivableVariant['type']\r\n\r\nexport type RevivableVariantTypeToRevivableVariant<T extends RevivableVariantType> =\r\n T extends 'messagePort' ? MessagePort :\r\n T extends 'promise' ? Promise<any> :\r\n T extends 'function' ? Function :\r\n T extends 'typedArray' ? TypedArray :\r\n T extends 'arrayBuffer' ? ArrayBuffer :\r\n T extends 'readableStream' ? ReadableStream :\r\n T extends 'date' ? Date :\r\n T extends 'error' ? Error :\r\n never\r\n\r\nexport type RevivableBox =\r\n | ReviveBoxBase\r\n & RevivableVariant\r\n\r\nexport type Revivable =\r\n | MessagePort\r\n | Promise<Capable>\r\n | TypedArray\r\n | ArrayBuffer\r\n | ReadableStream\r\n | Date\r\n | Error\r\n | ((...args: Capable[]) => Promise<Capable>)\r\n\r\nexport type RevivableToRevivableType<T extends Revivable> =\r\n T extends MessagePort ? 'messagePort' :\r\n T extends Promise<any> ? 'promise' :\r\n T extends Function ? 'function' :\r\n T extends TypedArray ? 'typedArray' :\r\n T extends ArrayBuffer ? 'arrayBuffer' :\r\n T extends ReadableStream ? 'readableStream' :\r\n T extends Date ? 'date' :\r\n T extends Error ? 'error' :\r\n never\r\n\r\nexport type Capable =\r\n | Structurable\r\n | TransferBox\r\n | Transferable\r\n | Revivable\r\n | { [key: string]: Capable }\r\n | Array<Capable>\r\n | Map<Capable, Capable>\r\n | Set<Capable>\r\n\r\nexport type MessageBase = {\r\n [OSRA_KEY]: string\r\n /** UUID of the client that sent the message */\r\n uuid: Uuid\r\n name?: string\r\n}\r\n\r\nexport type ProtocolMessage =\r\n | {\r\n type: 'announce'\r\n /** Only set when acknowledging a remote announcement */\r\n remoteUuid?: Uuid\r\n }\r\n | {\r\n /** uuid already taken, try announcing with another one */\r\n type: 'reject-uuid-taken'\r\n remoteUuid: Uuid\r\n }\r\n | {\r\n type: 'close'\r\n remoteUuid: Uuid\r\n }\r\n\r\nexport type BidirectionalConnectionMessage =\r\n | {\r\n type: 'init'\r\n remoteUuid: Uuid\r\n data: Capable\r\n }\r\n /** message not needed if transferring MessagePort is supported */\r\n | {\r\n type: 'message'\r\n remoteUuid: Uuid\r\n data: Capable\r\n /** uuid of the messagePort that the message was sent through */\r\n portId: Uuid\r\n }\r\n /** message not needed if transferring MessagePort is supported */\r\n | {\r\n type: 'message-port-close'\r\n remoteUuid: Uuid\r\n /** uuid of the messagePort that closed */\r\n portId: string\r\n }\r\n\r\nexport type UnidirectionalConnectionMessage = {\r\n type: 'message'\r\n remoteUuid: Uuid\r\n data: Capable\r\n portId: Uuid\r\n}\r\n\r\nexport type ConnectionMessage =\r\n | BidirectionalConnectionMessage\r\n | UnidirectionalConnectionMessage\r\n\r\nexport type MessageVariant =\r\n | ProtocolMessage\r\n | ConnectionMessage\r\n\r\nexport type Message =\r\n | MessageBase\r\n & MessageVariant\r\n\r\nexport type MessageContext = {\r\n port?: MessagePort | WebExtPort // WebExtension\r\n sender?: WebExtSender // WebExtension\r\n receiveTransport?: ReceivePlatformTransport\r\n source?: MessageEventSource | null // Window, Worker, WebSocket, ect...\r\n}\r\n\r\nexport type MessageEventMap = {\r\n message: CustomEvent<Message>\r\n}\r\nexport type MessageEventTarget = TypedEventTarget<MessageEventMap>\r\n\r\nexport type CustomTransport =\r\n { isJson?: boolean }\r\n & (\r\n | {\r\n receive: ReceivePlatformTransport | ((listener: (event: Message, messageContext: MessageContext) => void) => void)\r\n emit: EmitPlatformTransport | ((message: Message, transferables?: Transferable[]) => void)\r\n }\r\n | { receive: ReceivePlatformTransport | ((listener: (event: Message, messageContext: MessageContext) => void) => void) }\r\n | { emit: EmitPlatformTransport | ((message: Message, transferables?: Transferable[]) => void) }\r\n )\r\n\r\nexport type CustomEmitTransport = Extract<CustomTransport, { emit: any }>\r\nexport type CustomReceiveTransport = Extract<CustomTransport, { receive: any }>\r\n\r\nexport type EmitJsonPlatformTransport =\r\n | WebSocket\r\n | WebExtPort\r\n\r\nexport type ReceiveJsonPlatformTransport =\r\n | WebSocket\r\n | WebExtPort\r\n | WebExtOnConnect\r\n | WebExtOnMessage\r\n\r\nexport type JsonPlatformTransport =\r\n { isJson: true }\r\n & (\r\n | EmitJsonPlatformTransport\r\n | ReceiveJsonPlatformTransport\r\n )\r\n\r\nexport type EmitPlatformTransport =\r\n | EmitJsonPlatformTransport\r\n | Window\r\n | ServiceWorker\r\n | Worker\r\n | SharedWorker\r\n | MessagePort\r\n\r\nexport type ReceivePlatformTransport =\r\n | ReceiveJsonPlatformTransport\r\n | Window\r\n | ServiceWorker\r\n | Worker\r\n | SharedWorker\r\n | MessagePort\r\n\r\nexport type PlatformTransport =\r\n | EmitPlatformTransport\r\n | ReceivePlatformTransport\r\n\r\nexport type EmitTransport = EmitPlatformTransport & Extract<CustomTransport, { emit: any }>\r\nexport type ReceiveTransport = ReceivePlatformTransport & Extract<CustomTransport, { receive: any }>\r\n\r\nexport type Transport =\r\n | PlatformTransport\r\n | CustomTransport\r\n","import type { Message, Uuid } from '../types'\r\nimport type { StrictMessagePort } from './message-channel'\r\n\r\nexport const makeAllocator = <T>() => {\r\n const channels = new Map<string, T>()\r\n\r\n const alloc = (value: T): string => {\r\n let uuid = globalThis.crypto.randomUUID()\r\n while (channels.has(uuid)) {\r\n uuid = globalThis.crypto.randomUUID()\r\n }\r\n channels.set(uuid, value)\r\n return uuid\r\n }\r\n\r\n const has = (uuid: string) => channels.has(uuid)\r\n const get = (uuid: string) => channels.get(uuid)\r\n\r\n const free = (uuid: string) => {\r\n channels.delete(uuid)\r\n }\r\n\r\n const set = (uuid: string, value: T) => {\r\n channels.set(uuid, value)\r\n }\r\n\r\n return {\r\n alloc,\r\n has,\r\n get,\r\n free,\r\n set\r\n }\r\n}\r\n\r\nexport type Allocator<T> = ReturnType<typeof makeAllocator<T>>\r\n\r\ntype AllocatedMessageChannel = {\r\n uuid: Uuid\r\n /** Local port */\r\n port1: StrictMessagePort<Message>\r\n /** Remote port that gets transferred, might be undefined if a remote context created the channel */\r\n port2?: StrictMessagePort<Message>\r\n}\r\n\r\nexport const makeMessageChannelAllocator = () => {\r\n const channels = new Map<string, AllocatedMessageChannel>()\r\n\r\n const result = {\r\n getUniqueUuid: () => {\r\n let uuid: Uuid = globalThis.crypto.randomUUID()\r\n while (channels.has(uuid)) {\r\n uuid = globalThis.crypto.randomUUID()\r\n }\r\n return uuid\r\n },\r\n set: (uuid: Uuid, messagePorts: { port1: MessagePort, port2?: MessagePort }) => {\r\n channels.set(uuid, { uuid, ...messagePorts })\r\n },\r\n alloc: (uuid: Uuid | undefined = result.getUniqueUuid(), messagePorts?: { port1: MessagePort, port2?: MessagePort }) => {\r\n if (messagePorts) {\r\n channels.set(uuid, { uuid, ...messagePorts })\r\n return { uuid, ...messagePorts }\r\n }\r\n const messageChannel = new MessageChannel()\r\n const allocatedMessageChannel = {\r\n uuid,\r\n port1: messageChannel.port1,\r\n port2: messageChannel.port2\r\n } satisfies AllocatedMessageChannel\r\n channels.set(uuid, allocatedMessageChannel)\r\n return allocatedMessageChannel\r\n },\r\n has: (uuid: string) => channels.has(uuid),\r\n get: (uuid: string) => channels.get(uuid),\r\n free: (uuid: string) => channels.delete(uuid),\r\n getOrAlloc: (uuid: Uuid | undefined = result.getUniqueUuid(), messagePorts?: { port1: MessagePort, port2?: MessagePort }) => {\r\n const existingChannel = result.get(uuid)\r\n if (existingChannel) return existingChannel!\r\n return result.alloc(uuid, messagePorts)\r\n }\r\n }\r\n return result\r\n}\r\n\r\nexport type MessageChannelAllocator = ReturnType<typeof makeMessageChannelAllocator>\r\n","import type {\r\n CustomTransport, EmitTransport,\r\n Message, MessageContext,\r\n ReceiveTransport\r\n} from '../types'\r\nimport type { WebExtOnMessage, WebExtPort, WebExtSender } from './type-guards'\r\n\r\nimport { OSRA_KEY } from '../types'\r\nimport {\r\n isOsraMessage, isCustomTransport,\r\n isWebExtensionOnConnect, isWebExtensionOnMessage,\r\n isWebExtensionPort, isWebSocket, isWindow, isSharedWorker\r\n} from './type-guards'\r\n\r\nexport const getWebExtensionGlobal = () => globalThis.browser ?? globalThis.chrome\r\nexport const getWebExtensionRuntime = () => getWebExtensionGlobal().runtime\r\n\r\nexport const checkOsraMessageKey = (message: any, key: string): message is Message =>\r\n isOsraMessage(message)\r\n && message[OSRA_KEY] === key\r\n\r\nexport const registerOsraMessageListener = (\r\n { listener, transport, remoteName, key = OSRA_KEY, unregisterSignal }:\r\n {\r\n listener: (message: Message, messageContext: MessageContext) => Promise<void>\r\n transport: ReceiveTransport\r\n remoteName?: string\r\n key?: string\r\n unregisterSignal?: AbortSignal\r\n }\r\n) => {\r\n const registerListenerOnReceiveTransport = (receiveTransport: Extract<CustomTransport, { receive: any }>['receive']) => {\r\n // Custom function handler\r\n if (typeof receiveTransport === 'function') {\r\n receiveTransport(listener)\r\n // WebExtension handler\r\n } else if (\r\n isWebExtensionPort(receiveTransport)\r\n || isWebExtensionOnConnect(receiveTransport)\r\n || isWebExtensionOnMessage(receiveTransport)\r\n ) {\r\n const listenOnWebExtOnMessage = (onMessage: WebExtOnMessage, port?: WebExtPort) => {\r\n const _listener = (message: object, sender?: WebExtSender) => {\r\n if (!checkOsraMessageKey(message, key)) return\r\n if (remoteName && message.name !== remoteName) return\r\n listener(message, { port, sender })\r\n }\r\n onMessage.addListener(_listener)\r\n if (unregisterSignal) {\r\n unregisterSignal.addEventListener('abort', () =>\r\n onMessage.removeListener(_listener)\r\n )\r\n }\r\n }\r\n\r\n // WebExtOnConnect\r\n if (isWebExtensionOnConnect(receiveTransport)) {\r\n const _listener = (port: WebExtPort) => {\r\n listenOnWebExtOnMessage(port.onMessage, port)\r\n }\r\n receiveTransport.addListener(_listener)\r\n if (unregisterSignal) {\r\n unregisterSignal.addEventListener('abort', () =>\r\n receiveTransport.removeListener(_listener)\r\n )\r\n }\r\n // WebExtOnMessage\r\n } else if (isWebExtensionOnMessage(receiveTransport)) {\r\n listenOnWebExtOnMessage(receiveTransport)\r\n } else { // WebExtPort\r\n listenOnWebExtOnMessage(receiveTransport.onMessage)\r\n }\r\n } else { // Window, Worker, WebSocket, ect...\r\n const _listener = (event: MessageEvent<Message>) => {\r\n if (!checkOsraMessageKey(event.data, key)) return\r\n if (remoteName && event.data.name !== remoteName) return\r\n listener(event.data, { receiveTransport, source: event.source })\r\n }\r\n receiveTransport.addEventListener('message', _listener as unknown as EventListener)\r\n if (unregisterSignal) {\r\n unregisterSignal.addEventListener('abort', () =>\r\n receiveTransport.removeEventListener('message', _listener as unknown as EventListener)\r\n )\r\n }\r\n }\r\n }\r\n if (isCustomTransport(transport)) {\r\n registerListenerOnReceiveTransport(transport.receive)\r\n } else {\r\n registerListenerOnReceiveTransport(transport)\r\n }\r\n}\r\n\r\nexport const sendOsraMessage = (\r\n transport: EmitTransport,\r\n message: Message,\r\n origin = '*',\r\n transferables: Transferable[] = []\r\n) => {\r\n const sendToEmitTransport = (emitTransport: Extract<EmitTransport, { emit: any }>['emit']) => {\r\n if (typeof emitTransport === 'function') {\r\n emitTransport(message, transferables)\r\n } else if (isWebExtensionPort(emitTransport)) {\r\n emitTransport.postMessage(message)\r\n } else if (isWindow(emitTransport)) {\r\n emitTransport.postMessage(message, origin, transferables)\r\n } else if (isWebSocket(emitTransport)) {\r\n emitTransport.send(JSON.stringify(message))\r\n } else if (isSharedWorker(emitTransport)) {\r\n emitTransport.port.postMessage(message, transferables)\r\n } else { // MessagePort | ServiceWorker | Worker\r\n emitTransport.postMessage(message, transferables)\r\n }\r\n }\r\n\r\n if (isCustomTransport(transport)) {\r\n sendToEmitTransport(transport.emit)\r\n } else {\r\n sendToEmitTransport(transport)\r\n }\r\n}\r\n","import type {\r\n CustomEmitTransport, CustomReceiveTransport,\r\n CustomTransport, EmitJsonPlatformTransport,\r\n EmitTransport, JsonPlatformTransport,\r\n Message, ReceiveJsonPlatformTransport,\r\n ReceiveTransport, Revivable, RevivableBox, RevivableToRevivableType, RevivableVariantType, TransferBox, Transport\r\n} from '../types'\r\n\r\nimport { OSRA_BOX, OSRA_KEY } from '../types'\r\nimport { getWebExtensionRuntime } from './platform'\r\n\r\nconst typedArrayConstructors = [\r\n Int8Array,\r\n Uint8Array,\r\n Uint8ClampedArray,\r\n Int16Array,\r\n Uint16Array,\r\n Int32Array,\r\n Uint32Array,\r\n Float16Array,\r\n Float32Array,\r\n Float64Array,\r\n BigInt64Array,\r\n BigUint64Array\r\n]\r\nexport type TypedArrayConstructor = typeof typedArrayConstructors[number]\r\n\r\nconst typedArrays = [\r\n new Int8Array(),\r\n new Uint8Array(),\r\n new Uint8ClampedArray(),\r\n new Int16Array(),\r\n new Uint16Array(),\r\n new Int32Array(),\r\n new Uint32Array(),\r\n new Float16Array(),\r\n new Float32Array(),\r\n new Float64Array(),\r\n new BigInt64Array(),\r\n new BigUint64Array()\r\n]\r\nexport type TypedArray = typeof typedArrays[number]\r\nexport const typedArrayToType = <T extends TypedArray>(value: T) => {\r\n const type =\r\n value instanceof Int8Array ? 'Int8Array' :\r\n value instanceof Uint8Array ? 'Uint8Array' :\r\n value instanceof Uint8ClampedArray ? 'Uint8ClampedArray' :\r\n value instanceof Int16Array ? 'Int16Array' :\r\n value instanceof Uint16Array ? 'Uint16Array' :\r\n value instanceof Int32Array ? 'Int32Array' :\r\n value instanceof Uint32Array ? 'Uint32Array' :\r\n value instanceof Float16Array ? 'Float16Array' :\r\n value instanceof Float32Array ? 'Float32Array' :\r\n value instanceof Float64Array ? 'Float64Array' :\r\n value instanceof BigInt64Array ? 'BigInt64Array' :\r\n value instanceof BigUint64Array ? 'BigUint64Array' :\r\n undefined\r\n if (type === undefined) throw new Error('Unknown typed array type')\r\n return type\r\n}\r\nexport type TypeArrayType = ReturnType<typeof typedArrayToType>\r\nexport const typedArrayTypeToTypedArrayConstructor = (value: TypeArrayType): TypedArrayConstructor => {\r\n const typedArray =\r\n value === 'Int8Array' ? Int8Array :\r\n value === 'Uint8Array' ? Uint8Array :\r\n value === 'Uint8ClampedArray' ? Uint8ClampedArray :\r\n value === 'Int16Array' ? Int16Array :\r\n value === 'Uint16Array' ? Uint16Array :\r\n value === 'Int32Array' ? Int32Array :\r\n value === 'Uint32Array' ? Uint32Array :\r\n value === 'Float16Array' ? Float16Array :\r\n value === 'Float32Array' ? Float32Array :\r\n value === 'Float64Array' ? Float64Array :\r\n value === 'BigInt64Array' ? BigInt64Array :\r\n value === 'BigUint64Array' ? BigUint64Array :\r\n undefined\r\n if (typedArray === undefined) throw new Error('Unknown typed array type')\r\n return typedArray\r\n}\r\n\r\nexport const isTypedArray = (value: any): value is TypedArray => typedArrayConstructors.some(typedArray => value instanceof typedArray)\r\nexport const isWebSocket = (value: any) => value instanceof WebSocket\r\nexport const isServiceWorkerContainer = (value: any): value is ServiceWorkerContainer => globalThis.ServiceWorkerContainer && value instanceof ServiceWorkerContainer\r\nexport const isWorker = (value: any) => value instanceof Worker\r\n// @ts-expect-error\r\nexport const isDedicatedWorker = (value: any): value is DedicatedWorkerGlobalScope => globalThis.DedicatedWorkerGlobalScope && value instanceof DedicatedWorkerGlobalScope\r\nexport const isSharedWorker = (value: any): value is SharedWorker => globalThis.SharedWorker && value instanceof SharedWorker\r\nexport const isMessagePort = (value: any) => value instanceof MessagePort\r\nexport const isPromise = (value: any) => value instanceof Promise\r\nexport const isFunction = (value: any): value is Function => typeof value === 'function'\r\nexport const isArrayBuffer = (value: any) => value instanceof ArrayBuffer\r\nexport const isReadableStream = (value: any) => value instanceof ReadableStream\r\nexport const isDate = (value: any) => value instanceof Date\r\nexport const isError = (value: any) => value instanceof Error\r\n\r\nexport const isAlwaysBox = (value: any): value is Function | Promise<any> | Date | Error =>\r\n isFunction(value)\r\n || isPromise(value)\r\n || isTypedArray(value)\r\n || isDate(value)\r\n || isError(value)\r\n\r\nexport const isOsraMessage = (value: any): value is Message =>\r\n Boolean(\r\n value\r\n && typeof value === 'object'\r\n && (value as Message)[OSRA_KEY]\r\n )\r\n\r\nexport const isClonable = (value: any) =>\r\n globalThis.SharedArrayBuffer && value instanceof globalThis.SharedArrayBuffer ? true\r\n : false\r\n\r\nexport const isTransferable = (value: any): value is Transferable =>\r\n globalThis.ArrayBuffer && value instanceof globalThis.ArrayBuffer ? true\r\n : globalThis.MessagePort && value instanceof globalThis.MessagePort ? true\r\n : globalThis.ReadableStream && value instanceof globalThis.ReadableStream ? true\r\n : globalThis.WritableStream && value instanceof globalThis.WritableStream ? true\r\n : globalThis.TransformStream && value instanceof globalThis.TransformStream ? true\r\n : globalThis.ImageBitmap && value instanceof globalThis.ImageBitmap ? true\r\n : false\r\n\r\nexport const isTransferBox = (value: any): value is TransferBox<any> =>\r\n Boolean(\r\n value\r\n && typeof value === 'object'\r\n && (value as TransferBox<Transferable>)[OSRA_BOX] === 'transferable'\r\n )\r\n\r\nexport type WebExtRuntime = typeof browser.runtime\r\nexport const isWebExtensionRuntime = (value: any): value is WebExtRuntime => {\r\n const runtime = getWebExtensionRuntime()\r\n return Boolean(\r\n value\r\n && typeof value === 'object'\r\n && isWebExtensionOnConnect(runtime.onConnect)\r\n && runtime.id\r\n )\r\n}\r\n\r\nexport type WebExtPort = ReturnType<WebExtRuntime['connect']>\r\nexport const isWebExtensionPort = (value: any, connectPort: boolean = false): value is WebExtPort => {\r\n return Boolean(\r\n value\r\n && typeof value === 'object'\r\n && (value as WebExtPort).name\r\n && (value as WebExtPort).disconnect\r\n && (value as WebExtPort).postMessage\r\n && (\r\n connectPort\r\n // these properties are only present on WebExtPort that were created through runtime.connect()\r\n ? (\r\n (value as WebExtPort).sender\r\n && (value as WebExtPort).onMessage\r\n && (value as WebExtPort).onDisconnect\r\n )\r\n : true\r\n )\r\n )\r\n}\r\n\r\nexport type WebExtSender = NonNullable<WebExtPort['sender']>\r\n\r\nexport type WebExtOnConnect = WebExtRuntime['onConnect']\r\nexport const isWebExtensionOnConnect = (value: any): value is WebExtOnConnect =>\r\n Boolean(\r\n value\r\n && typeof value === 'object'\r\n && (value as WebExtOnConnect).addListener\r\n && (value as WebExtOnConnect).hasListener\r\n && (value as WebExtOnConnect).removeListener\r\n )\r\n\r\nexport type WebExtOnMessage = WebExtRuntime['onMessage']\r\nexport const isWebExtensionOnMessage = (value: any): value is WebExtOnMessage =>\r\n Boolean(\r\n value\r\n && typeof value === 'object'\r\n && (value as WebExtOnMessage).addListener\r\n && (value as WebExtOnMessage).hasListener\r\n && (value as WebExtOnMessage).removeListener\r\n )\r\n\r\nexport const isWindow = (value: any): value is Window => {\r\n return Boolean(\r\n value\r\n && typeof value === 'object'\r\n && (value as Window).document\r\n && (value as Window).location\r\n && (value as Window).navigator\r\n && (value as Window).screen\r\n && (value as Window).history\r\n )\r\n}\r\n\r\nexport type IsEmitJsonOnlyTransport<T extends Transport> = T extends EmitJsonPlatformTransport ? true : false\r\nexport const isEmitJsonOnlyTransport = (value: any): value is EmitJsonPlatformTransport =>\r\n isWebSocket(value)\r\n || isWebExtensionPort(value)\r\n\r\nexport type IsReceiveJsonOnlyTransport<T extends Transport> = T extends ReceiveJsonPlatformTransport ? true : false\r\nexport const isReceiveJsonOnlyTransport = (value: any): value is ReceiveJsonPlatformTransport =>\r\n isWebSocket(value)\r\n || isWebExtensionPort(value)\r\n || isWebExtensionOnConnect(value)\r\n || isWebExtensionOnMessage(value)\r\n\r\nexport type IsJsonOnlyTransport<T extends Transport> = T extends JsonPlatformTransport ? true : false\r\nexport const isJsonOnlyTransport = (value: any): value is JsonPlatformTransport =>\r\n isEmitJsonOnlyTransport(value)\r\n || isReceiveJsonOnlyTransport(value)\r\n\r\nexport type IsEmitTransport<T extends Transport> = T extends EmitTransport ? true : false\r\nexport const isEmitTransport = (value: any): value is EmitTransport =>\r\n isEmitJsonOnlyTransport(value)\r\n || isWindow(value)\r\n || isServiceWorkerContainer(value)\r\n || isWorker(value)\r\n || isDedicatedWorker(value)\r\n || isSharedWorker(value)\r\n || isMessagePort(value)\r\n || isCustomEmitTransport(value)\r\n\r\nexport function assertEmitTransport (transport: Transport): asserts transport is EmitTransport {\r\n if (!isEmitTransport(transport)) throw new Error('Transport is not emitable')\r\n}\r\n\r\n\r\nexport type IsReceiveTransport<T extends Transport> = T extends ReceiveTransport ? true : false\r\nexport const isReceiveTransport = (value: any): value is ReceiveTransport =>\r\n isReceiveJsonOnlyTransport(value)\r\n || isWindow(value)\r\n || isServiceWorkerContainer(value)\r\n || isWorker(value)\r\n || isDedicatedWorker(value)\r\n || isSharedWorker(value)\r\n || isMessagePort(value)\r\n || isCustomReceiveTransport(value)\r\n\r\nexport function assertReceiveTransport (transport: Transport): asserts transport is ReceiveTransport {\r\n if (!isReceiveTransport(transport)) throw new Error('Transport is not receiveable')\r\n}\r\n\r\nexport const isCustomEmitTransport = (value: any): value is CustomEmitTransport =>\r\n Boolean(\r\n value\r\n && typeof value === 'object'\r\n && (\r\n 'emit' in value\r\n && (\r\n isEmitTransport(value.emit)\r\n || typeof value.emit === 'function'\r\n )\r\n )\r\n )\r\n\r\nexport const isCustomReceiveTransport = (value: any): value is CustomReceiveTransport =>\r\n Boolean(\r\n value\r\n && typeof value === 'object'\r\n && (\r\n 'receive' in value\r\n && (\r\n isReceiveTransport(value.receive)\r\n || typeof value.receive === 'function'\r\n )\r\n )\r\n )\r\n\r\nexport type IsCustomTransport<T extends Transport> = T extends CustomTransport ? true : false\r\nexport const isCustomTransport = (value: any): value is CustomTransport =>\r\n isCustomEmitTransport(value)\r\n || isCustomReceiveTransport(value)\r\n\r\nexport const isTransport = (value: any): value is Transport =>\r\n isJsonOnlyTransport(value)\r\n || isEmitTransport(value)\r\n || isReceiveTransport(value)\r\n || isCustomTransport(value)\r\n\r\nexport const isRevivable = (value: any): value is Revivable =>\r\n isMessagePort(value)\r\n || isFunction(value)\r\n || isPromise(value)\r\n || isTypedArray(value)\r\n || isArrayBuffer(value)\r\n || isReadableStream(value)\r\n || isDate(value)\r\n || isError(value)\r\n\r\nexport const isRevivableBox = (value: any): value is RevivableBox =>\r\n value\r\n && typeof value === 'object'\r\n && OSRA_BOX in value\r\n && value[OSRA_BOX] === 'revivable'\r\n\r\nexport const isRevivableMessagePortBox = (value: any): value is RevivableBox & { type: 'messagePort' } =>\r\n isRevivableBox(value) && value.type === 'messagePort'\r\n\r\nexport const isRevivablePromiseBox = (value: any): value is RevivableBox & { type: 'promise' } =>\r\n isRevivableBox(value) && value.type === 'promise'\r\n\r\nexport const isRevivableFunctionBox = (value: any): value is RevivableBox & { type: 'function' } =>\r\n isRevivableBox(value) && value.type === 'function'\r\n\r\nexport const isRevivableTypedArrayBox = (value: any): value is RevivableBox & { type: 'typedArray' } =>\r\n isRevivableBox(value) && value.type === 'typedArray'\r\n\r\nexport const isRevivableArrayBufferBox = (value: any): value is RevivableBox & { type: 'arrayBuffer' } =>\r\n isRevivableBox(value) && value.type === 'arrayBuffer'\r\n\r\nexport const isRevivableReadableStreamBox = (value: any): value is RevivableBox & { type: 'readableStream' } =>\r\n isRevivableBox(value) && value.type === 'readableStream'\r\n\r\nexport const isRevivableErrorBox = (value: any): value is RevivableBox & { type: 'error' } =>\r\n isRevivableBox(value) && value.type === 'error'\r\n\r\nexport const isRevivableDateBox = (value: any): value is RevivableBox & { type: 'date' } =>\r\n isRevivableBox(value) && value.type === 'date'\r\n\r\nexport const revivableBoxToType = (value: RevivableBox) => value.type\r\n\r\nexport const revivableToType = <T extends Revivable>(value: T): RevivableToRevivableType<T> => {\r\n if (isMessagePort(value)) return 'messagePort' as RevivableToRevivableType<T>\r\n if (isFunction(value)) return 'function' as RevivableToRevivableType<T>\r\n if (isPromise(value)) return 'promise' as RevivableToRevivableType<T>\r\n if (isTypedArray(value)) return 'typedArray' as RevivableToRevivableType<T>\r\n if (isArrayBuffer(value)) return 'arrayBuffer' as RevivableToRevivableType<T>\r\n if (isReadableStream(value)) return 'readableStream' as RevivableToRevivableType<T>\r\n if (isDate(value)) return 'date' as RevivableToRevivableType<T>\r\n if (isError(value)) return 'error' as RevivableToRevivableType<T>\r\n throw new Error('Unknown revivable type')\r\n}\r\n","import type { Capable, TransferBox } from '../types'\r\n\r\nimport { OSRA_BOX } from '../types'\r\nimport { deepReplace } from './replace'\r\nimport { isClonable, isTransferable, isTransferBox } from './type-guards'\r\n\r\nexport const getTransferableObjects = (value: any): Transferable[] => {\r\n const transferables: Transferable[] = []\r\n const recurse = (value: any): any =>\r\n isClonable(value) ? undefined\r\n : isTransferable(value) ? transferables.push(value)\r\n : Array.isArray(value) ? value.map(recurse)\r\n : value && typeof value === 'object' ? Object.values(value).map(recurse)\r\n : undefined\r\n\r\n recurse(value)\r\n return transferables\r\n}\r\n\r\nexport const getTransferBoxes = (value: any): TransferBox<Transferable>[] => {\r\n const transferBoxes: TransferBox<any>[] = []\r\n const recurse = (value: any): any =>\r\n isTransferBox(value) ? transferBoxes.push(value)\r\n : Array.isArray(value) ? value.map(recurse)\r\n : value && typeof value === 'object' ? Object.values(value).map(recurse)\r\n : undefined\r\n\r\n recurse(value)\r\n return transferBoxes\r\n}\r\n\r\n/** This box tells the protocol that the value should be copied instead of transfered */\r\nexport const transfer = <T extends Transferable>(value: T) => ({\r\n [OSRA_BOX]: 'transferable',\r\n value\r\n}) as TransferBox<T>\r\n\r\nexport const recursiveTransfer = <T extends Capable>(value: T) =>\r\n deepReplace(\r\n value,\r\n isTransferable,\r\n (value) => transfer(value)\r\n )\r\n","import { getTransferableObjects } from './transferable'\r\n\r\nexport type PlatformCapabilities = {\r\n jsonOnly: boolean\r\n messagePort: boolean\r\n arrayBuffer: boolean\r\n transferable: boolean\r\n transferableStream: boolean\r\n}\r\n\r\nconst probePlatformCapabilityUtil = <T>(value: T, transfer = false): Promise<T> => {\r\n const { port1, port2 } = new MessageChannel()\r\n const result = new Promise<T>(resolve =>\r\n port1.addEventListener('message', message =>\r\n resolve(message.data)\r\n )\r\n )\r\n port1.start()\r\n port2.postMessage(value, transfer ? getTransferableObjects(value) : [])\r\n return result\r\n}\r\n\r\nconst probeMessagePortTransfer = async () => {\r\n const { port1 } = new MessageChannel()\r\n const port = await probePlatformCapabilityUtil(port1, true)\r\n return port instanceof MessagePort\r\n}\r\n\r\nconst probeArrayBufferClone = async () => {\r\n const buffer = new ArrayBuffer(1)\r\n const arrayBuffer = await probePlatformCapabilityUtil(buffer)\r\n return arrayBuffer instanceof ArrayBuffer\r\n}\r\n\r\nconst probeArrayBufferTransfer = async () => {\r\n const buffer = new ArrayBuffer(1)\r\n const arrayBuffer = await probePlatformCapabilityUtil(buffer, true)\r\n return arrayBuffer instanceof ArrayBuffer\r\n}\r\n\r\nconst probeTransferableStream = async () => {\r\n const stream = new ReadableStream({\r\n start(controller) {\r\n controller.enqueue(new Uint8Array(1))\r\n controller.close()\r\n }\r\n })\r\n const transferableStream = await probePlatformCapabilityUtil(stream, true)\r\n return transferableStream instanceof ReadableStream\r\n}\r\n\r\nexport const probePlatformCapabilities = async (): Promise<PlatformCapabilities> => {\r\n const [\r\n messagePort,\r\n arrayBuffer,\r\n transferable,\r\n transferableStream,\r\n ] = await Promise.all([\r\n probeMessagePortTransfer().catch(() => false),\r\n probeArrayBufferClone().catch(() => false),\r\n probeArrayBufferTransfer().catch(() => false),\r\n probeTransferableStream().catch(() => false)\r\n ])\r\n return {\r\n jsonOnly:\r\n !messagePort\r\n && !arrayBuffer\r\n && !transferable\r\n && !transferableStream,\r\n messagePort,\r\n arrayBuffer,\r\n transferable,\r\n transferableStream,\r\n }\r\n}\r\n","import type {\r\n Capable,\r\n Message,\r\n Revivable,\r\n RevivableBox,\r\n RevivableDate,\r\n RevivableError,\r\n RevivableFunction,\r\n RevivableFunctionCallContext,\r\n RevivableMessagePort,\r\n RevivablePromise,\r\n RevivablePromiseContext,\r\n RevivableReadableStream,\r\n RevivableVariant,\r\n RevivableToRevivableType,\r\n ReviveBoxBase,\r\n Uuid,\r\n RevivableArrayBuffer,\r\n RevivableReadableStreamPullContext,\r\n RevivableTypedArray\r\n} from '../types'\r\nimport type { ConnectionRevivableContext } from './connection'\r\nimport type { DeepReplace } from './replace'\r\nimport type { StrictMessagePort } from './message-channel'\r\n\r\nimport { OSRA_BOX } from '../types'\r\nimport {\r\n isAlwaysBox,\r\n isArrayBuffer,\r\n isClonable,\r\n isDate, isError, isFunction,\r\n isMessagePort, isPromise, isReadableStream,\r\n isRevivable, isRevivableArrayBufferBox, isRevivableBox, isRevivableDateBox, isRevivableErrorBox,\r\n isRevivableFunctionBox, isRevivableMessagePortBox, isRevivablePromiseBox,\r\n isRevivableReadableStreamBox, isRevivableTypedArrayBox, isTransferable, isTypedArray, revivableToType,\r\n TypedArray,\r\n typedArrayToType,\r\n typedArrayTypeToTypedArrayConstructor\r\n} from './type-guards'\r\nimport { getTransferableObjects } from './transferable'\r\n\r\nexport const boxMessagePort = (\r\n value: MessagePort,\r\n context: ConnectionRevivableContext\r\n): RevivableVariant & { type: 'messagePort' } => {\r\n const messagePort = value as StrictMessagePort<Capable>\r\n const { uuid: portId } = context.messageChannels.alloc(undefined, { port1: messagePort })\r\n // Since we are in a boxed MessagePort, we want to send a message to the other side through the EmitTransport\r\n messagePort.addEventListener('message', ({ data }) => {\r\n context.sendMessage({\r\n type: 'message',\r\n remoteUuid: context.remoteUuid,\r\n data: isRevivableBox(data) ? data : recursiveBox(data, context),\r\n portId\r\n })\r\n })\r\n messagePort.start()\r\n\r\n // The ReceiveTransport received a message from the other side so we call it on our own side's MessagePort after reviving it\r\n context.eventTarget.addEventListener('message', function listener ({ detail: message }) {\r\n if (message.type === 'message-port-close') {\r\n if (message.portId !== portId) return\r\n context.eventTarget.removeEventListener('message', listener)\r\n messagePort.close()\r\n context.messageChannels.free(portId)\r\n return\r\n }\r\n if (message.type !== 'message' || message.portId !== portId) return\r\n messagePort.postMessage(message.data, getTransferableObjects(message.data))\r\n })\r\n\r\n return {\r\n type: 'messagePort',\r\n portId\r\n }\r\n}\r\n\r\nexport const reviveMessagePort = (value: RevivableMessagePort, context: ConnectionRevivableContext): StrictMessagePort<Capable> => {\r\n const { port1: userPort, port2: internalPort } = new MessageChannel()\r\n // Since we are in a boxed MessagePort, we want to send a message to the other side through the EmitTransport\r\n internalPort.addEventListener('message', ({ data }: MessageEvent<Message & { type: 'message' }>) => {\r\n context.sendMessage({\r\n type: 'message',\r\n remoteUuid: context.remoteUuid,\r\n data: isRevivableBox(data) ? data : recursiveBox(data, context),\r\n portId: value.portId as Uuid\r\n })\r\n })\r\n internalPort.start()\r\n\r\n const existingChannel = context.messageChannels.get(value.portId)\r\n const { port1 } =\r\n existingChannel\r\n ? existingChannel\r\n : context.messageChannels.alloc(value.portId as Uuid)\r\n // The ReceiveTransport received a message from the other side so we call it on our own side's MessagePort after reviving it\r\n port1.addEventListener('message', function listener ({ data: message }) {\r\n if (message.type === 'message-port-close') {\r\n if (message.portId !== value.portId) return\r\n port1.removeEventListener('message', listener)\r\n internalPort.close()\r\n context.messageChannels.free(value.portId)\r\n return\r\n }\r\n if (message.type !== 'message' || message.portId !== value.portId) return\r\n // if the returned messagePort has been registered as internal message port, then we proxy the data without reviving it\r\n if (context.messagePorts.has(userPort)) {\r\n internalPort.postMessage(message.data)\r\n } else { // In this case, userPort is actually passed by the user of osra and we should revive all the message data\r\n const revivedData = recursiveRevive(message.data, context)\r\n internalPort.postMessage(revivedData, getTransferableObjects(revivedData))\r\n }\r\n })\r\n port1.start()\r\n return userPort\r\n}\r\n\r\nexport const boxPromise = (value: Promise<any>, context: ConnectionRevivableContext): RevivableVariant & { type: 'promise' } => {\r\n const { port1: localPort, port2: remotePort } = new MessageChannel()\r\n context.messagePorts.add(remotePort)\r\n\r\n const sendResult = (result: { type: 'resolve', data: Capable } | { type: 'reject', error: string }) => {\r\n const boxedResult = recursiveBox(result, context)\r\n localPort.postMessage(boxedResult, getTransferableObjects(boxedResult))\r\n localPort.close()\r\n }\r\n\r\n value\r\n .then(data => sendResult({ type: 'resolve', data }))\r\n .catch(error => sendResult({ type: 'reject', error: error.stack }))\r\n\r\n return {\r\n type: 'promise',\r\n port: remotePort\r\n }\r\n}\r\n\r\nexport const revivePromise = (value: RevivablePromise, context: ConnectionRevivableContext): Promise<any> => {\r\n context.messagePorts.add(value.port)\r\n return new Promise((resolve, reject) => {\r\n value.port.addEventListener('message', ({ data }: MessageEvent<RevivablePromiseContext>) => {\r\n const result = recursiveRevive(data, context)\r\n if (result.type === 'resolve') {\r\n resolve(result.data)\r\n } else { // result.type === 'reject'\r\n reject(result.error)\r\n }\r\n value.port.close()\r\n }, { once: true })\r\n value.port.start()\r\n })\r\n}\r\n\r\nexport const boxFunction = (value: Function, context: ConnectionRevivableContext): RevivableVariant & { type: 'function' } => {\r\n const { port1: localPort, port2: remotePort } = new MessageChannel()\r\n context.messagePorts.add(remotePort)\r\n localPort.addEventListener('message', ({ data }: MessageEvent<RevivableFunctionCallContext>) => {\r\n const [returnValuePort, args] = recursiveRevive(data, context) as RevivableFunctionCallContext\r\n const result = (async () => value(...args))()\r\n const boxedResult = recursiveBox(result, context)\r\n returnValuePort.postMessage(boxedResult, getTransferableObjects(boxedResult))\r\n })\r\n localPort.start()\r\n\r\n return {\r\n type: 'function',\r\n port: remotePort\r\n }\r\n}\r\n\r\nexport const reviveFunction = (value: RevivableFunction, context: ConnectionRevivableContext): Function => {\r\n const func = (...args: Capable[]) =>\r\n new Promise((resolve, reject) => {\r\n const { port1: returnValueLocalPort, port2: returnValueRemotePort } = new MessageChannel()\r\n context.messagePorts.add(returnValueRemotePort)\r\n const callContext = recursiveBox([returnValueRemotePort, args] as const, context)\r\n value.port.postMessage(callContext, getTransferableObjects(callContext))\r\n\r\n returnValueLocalPort.addEventListener('message', ({ data }: MessageEvent<Capable>) => {\r\n if (!isRevivablePromiseBox(data)) throw new Error(`Proxied function did not return a promise`)\r\n const result = recursiveRevive(data, context) as Promise<Capable>\r\n result\r\n .then(resolve)\r\n .catch(reject)\r\n .finally(() => returnValueLocalPort.close())\r\n })\r\n returnValueLocalPort.start()\r\n })\r\n\r\n return func\r\n}\r\n\r\nexport const boxTypedArray = (value: TypedArray, context: ConnectionRevivableContext): RevivableVariant & { type: 'typedArray' } => {\r\n return {\r\n type: 'typedArray',\r\n typedArrayType: typedArrayToType(value),\r\n arrayBuffer: value.buffer\r\n }\r\n}\r\n\r\nexport const reviveTypedArray = (value: RevivableTypedArray, context: ConnectionRevivableContext): TypedArray => {\r\n const TypedArrayConstructor = typedArrayTypeToTypedArrayConstructor(value.typedArrayType)\r\n const result = new TypedArrayConstructor(value.arrayBuffer)\r\n return result\r\n}\r\n\r\nexport const boxArrayBuffer = (value: ArrayBuffer, context: ConnectionRevivableContext): RevivableVariant & { type: 'arrayBuffer' } => {\r\n return {\r\n type: 'arrayBuffer',\r\n base64Buffer: new Uint8Array(value).toBase64() as string\r\n }\r\n}\r\n\r\nexport const reviveArrayBuffer = (value: RevivableArrayBuffer, context: ConnectionRevivableContext): ArrayBuffer => {\r\n return (Uint8Array.fromBase64(value.base64Buffer) as Uint8Array).buffer as ArrayBuffer\r\n}\r\n\r\nexport const boxError = (value: Error, context: ConnectionRevivableContext): RevivableVariant & { type: 'error' } => {\r\n return {\r\n type: 'error',\r\n message: value.message,\r\n stack: value.stack || value.toString()\r\n }\r\n}\r\n\r\nexport const reviveError = (value: RevivableError, context: ConnectionRevivableContext): Error => {\r\n return new Error(value.message, { cause: value.stack })\r\n}\r\n\r\nexport const boxReadableStream = (value: ReadableStream, context: ConnectionRevivableContext): RevivableVariant & { type: 'readableStream' } => {\r\n const { port1: localPort, port2: remotePort } = new MessageChannel()\r\n context.messagePorts.add(remotePort)\r\n \r\n const reader = value.getReader()\r\n \r\n localPort.addEventListener('message', async ({ data }: MessageEvent<RevivableReadableStreamPullContext>) => {\r\n const { type } = recursiveRevive(data, context) as RevivableReadableStreamPullContext\r\n if (type === 'pull') {\r\n const pullResult = reader.read()\r\n const boxedResult = recursiveBox(pullResult, context)\r\n localPort.postMessage(boxedResult, getTransferableObjects(boxedResult))\r\n } else {\r\n reader.cancel()\r\n localPort.close()\r\n }\r\n })\r\n localPort.start()\r\n\r\n return {\r\n type: 'readableStream',\r\n port: remotePort\r\n }\r\n}\r\n\r\nexport const reviveReadableStream = (value: RevivableReadableStream, context: ConnectionRevivableContext): ReadableStream => {\r\n context.messagePorts.add(value.port)\r\n value.port.start()\r\n return new ReadableStream({\r\n start(controller) {},\r\n pull(controller) {\r\n return new Promise((resolve, reject) => {\r\n value.port.addEventListener('message', async ({ data }: MessageEvent<Capable>) => {\r\n if (!isRevivablePromiseBox(data)) throw new Error(`Proxied function did not return a promise`)\r\n const result = recursiveRevive(data, context) as Promise<ReadableStreamReadResult<any>>\r\n result\r\n .then(result => {\r\n if (result.done) controller.close()\r\n else controller.enqueue(result.value)\r\n resolve()\r\n })\r\n .catch(reject)\r\n }, { once: true })\r\n value.port.postMessage(recursiveBox({ type: 'pull' }, context))\r\n })\r\n },\r\n cancel() {\r\n value.port.postMessage(recursiveBox({ type: 'cancel' }, context))\r\n value.port.close()\r\n }\r\n })\r\n}\r\n\r\nexport const boxDate = (value: Date, context: ConnectionRevivableContext): RevivableVariant & { type: 'date' } => {\r\n return {\r\n type: 'date',\r\n ISOString: value.toISOString()\r\n }\r\n}\r\n\r\nexport const reviveDate = (value: RevivableDate, context: ConnectionRevivableContext): Date => {\r\n return new Date(value.ISOString)\r\n}\r\n\r\nexport const box = (value: Revivable, context: ConnectionRevivableContext) => {\r\n\r\n if (\r\n isAlwaysBox(value)\r\n // WebKit doesn't support transferable streams so we force box them\r\n || isReadableStream(value) && !context.platformCapabilities.transferableStream\r\n ) {\r\n return {\r\n [OSRA_BOX]: 'revivable',\r\n ...(\r\n isFunction(value) ? boxFunction(value, context)\r\n : isPromise(value) ? boxPromise(value, context)\r\n : isTypedArray(value) ? boxTypedArray(value, context)\r\n : isReadableStream(value) ? boxReadableStream(value, context)\r\n : isDate(value) ? boxDate(value, context)\r\n : isError(value) ? boxError(value, context)\r\n : value\r\n ),\r\n } satisfies RevivableBox\r\n }\r\n\r\n return {\r\n [OSRA_BOX]: 'revivable',\r\n ...'isJson' in context.transport && context.transport.isJson\r\n ? (\r\n isMessagePort(value) ? boxMessagePort(value, context)\r\n : isArrayBuffer(value) ? boxArrayBuffer(value, context)\r\n : isReadableStream(value) ? boxReadableStream(value, context)\r\n : { type: 'unknown', value }\r\n )\r\n : {\r\n type:\r\n isMessagePort(value) ? 'messagePort'\r\n : isArrayBuffer(value) ? 'arrayBuffer'\r\n : isReadableStream(value) ? 'readableStream'\r\n : 'unknown',\r\n value\r\n }\r\n } as ReviveBoxBase<RevivableToRevivableType<typeof value>>\r\n}\r\n\r\nexport const recursiveBox = <T extends Capable>(value: T, context: ConnectionRevivableContext): DeepReplace<T, Revivable, RevivableBox> => {\r\n const boxedValue = isRevivable(value) ? box(value, context) : value\r\n return (\r\n Array.isArray(boxedValue) ? boxedValue.map(value => recursiveBox(value, context)) as DeepReplace<T, Revivable, RevivableBox>\r\n : boxedValue && typeof boxedValue === 'object' && Object.getPrototypeOf(boxedValue) === Object.prototype ? (\r\n Object.fromEntries(\r\n Object\r\n .entries(boxedValue)\r\n .map(([key, value]: [string, Capable]) => [\r\n key,\r\n isRevivableBox(boxedValue) && boxedValue.type === 'messagePort' && boxedValue.value instanceof MessagePort\r\n || isRevivableBox(boxedValue) && boxedValue.type === 'arrayBuffer' && boxedValue.value instanceof ArrayBuffer\r\n || isRevivableBox(boxedValue) && boxedValue.type === 'readableStream' && boxedValue.value instanceof ReadableStream\r\n ? value\r\n : recursiveBox(value, context)\r\n ])\r\n )\r\n ) as DeepReplace<T, Revivable, RevivableBox>\r\n : boxedValue as DeepReplace<T, Revivable, RevivableBox>\r\n )\r\n}\r\n\r\nexport const revive = (box: RevivableBox, context: ConnectionRevivableContext) => {\r\n // If the value got properly sent through the protocol as is, we don't need to revive it\r\n if (isRevivable(box.value)) return box.value\r\n\r\n return (\r\n isRevivableMessagePortBox(box) ? reviveMessagePort(box, context)\r\n : isRevivableFunctionBox(box) ? reviveFunction(box, context)\r\n : isRevivablePromiseBox(box) ? revivePromise(box, context)\r\n : isRevivableErrorBox(box) ? reviveError(box, context)\r\n : isRevivableTypedArrayBox(box) ? reviveTypedArray(box, context)\r\n : isRevivableArrayBufferBox(box) ? reviveArrayBuffer(box, context)\r\n : isRevivableReadableStreamBox(box) ? reviveReadableStream(box, context)\r\n : isRevivableDateBox(box) ? reviveDate(box, context)\r\n : box\r\n ) as DeepReplace<RevivableBox, RevivableBox, Revivable>\r\n}\r\n\r\nexport const recursiveRevive = <T extends Capable>(value: T, context: ConnectionRevivableContext): DeepReplace<T, RevivableBox, Revivable> => {\r\n const recursedValue = (\r\n isTransferable(value) ? value\r\n : Array.isArray(value) ? value.map(value => recursiveRevive(value, context)) as DeepReplace<T, RevivableBox, Revivable>\r\n : value && typeof value === 'object' ? (\r\n Object.fromEntries(\r\n Object\r\n .entries(value)\r\n .map(([key, value]: [string, Capable]) => [\r\n key,\r\n recursiveRevive(value, context)\r\n ])\r\n )\r\n ) as DeepReplace<T, RevivableBox, Revivable>\r\n : value as DeepReplace<T, RevivableBox, Revivable>\r\n )\r\n return (isRevivableBox(recursedValue) ? revive(recursedValue, context) : recursedValue) as DeepReplace<T, RevivableBox, Revivable>\r\n}\r\n","import type {\r\n Capable, ConnectionMessage,\r\n Message,\r\n MessageEventTarget,\r\n Transport,\r\n Uuid\r\n} from '../types'\r\nimport type { MessageChannelAllocator } from './allocator'\r\nimport type { PlatformCapabilities } from './capabilities'\r\nimport type { StrictMessagePort } from './message-channel'\r\n\r\nimport { recursiveBox, recursiveRevive } from './revivable'\r\nimport { makeMessageChannelAllocator } from './allocator'\r\n\r\nexport type BidirectionalConnectionContext = {\r\n type: 'bidirectional'\r\n eventTarget: MessageEventTarget\r\n connection: BidirectionalConnection\r\n}\r\nexport type UnidirectionalEmittingConnectionContext = {\r\n type: 'unidirectional-emitting'\r\n connection: UnidirectionalEmittingConnection\r\n}\r\nexport type UnidirectionalReceivingConnectionContext = {\r\n type: 'unidirectional-receiving'\r\n eventTarget: MessageEventTarget\r\n connection: UnidirectionalReceivingConnection\r\n}\r\n\r\nexport type ConnectionContext =\r\n | BidirectionalConnectionContext\r\n | UnidirectionalEmittingConnectionContext\r\n | UnidirectionalReceivingConnectionContext\r\n\r\nexport type ConnectionRevivableContext = {\r\n platformCapabilities: PlatformCapabilities\r\n transport: Transport\r\n remoteUuid: Uuid\r\n messagePorts: Set<MessagePort>\r\n messageChannels: MessageChannelAllocator\r\n sendMessage: (message: ConnectionMessage) => void\r\n eventTarget: MessageEventTarget\r\n}\r\n\r\nexport type BidirectionalConnection<T extends Capable = Capable> = {\r\n revivableContext: ConnectionRevivableContext\r\n close: () => void\r\n remoteValue: Promise<T>\r\n}\r\n\r\nexport const startBidirectionalConnection = <T extends Capable>(\r\n { transport, value, uuid, remoteUuid, platformCapabilities, eventTarget, send, close }:\r\n {\r\n transport: Transport\r\n value: Capable\r\n uuid: Uuid\r\n remoteUuid: Uuid\r\n platformCapabilities: PlatformCapabilities\r\n eventTarget: MessageEventTarget\r\n send: (message: ConnectionMessage) => void\r\n close: () => void\r\n }\r\n) => {\r\n const revivableContext = {\r\n platformCapabilities,\r\n transport,\r\n remoteUuid,\r\n messagePorts: new Set(),\r\n messageChannels: makeMessageChannelAllocator(),\r\n sendMessage: send,\r\n eventTarget\r\n } satisfies ConnectionRevivableContext\r\n let initResolve: ((message: ConnectionMessage & { type: 'init' }) => void)\r\n const initMessage = new Promise<ConnectionMessage & { type: 'init' }>((resolve, reject) => {\r\n initResolve = resolve\r\n })\r\n\r\n eventTarget.addEventListener('message', ({ detail }) => {\r\n if (detail.type === 'init') {\r\n initResolve(detail)\r\n return\r\n } else if (detail.type === 'message') {\r\n const messageChannel = revivableContext.messageChannels.getOrAlloc(detail.portId)\r\n messageChannel.port2?.postMessage(detail)\r\n }\r\n })\r\n\r\n send({\r\n type: 'init',\r\n remoteUuid,\r\n data: recursiveBox(value, revivableContext)\r\n })\r\n\r\n return {\r\n revivableContext,\r\n close: () => {\r\n },\r\n remoteValue:\r\n initMessage\r\n .then(initMessage => recursiveRevive(initMessage.data, revivableContext)) as Promise<T>\r\n } satisfies BidirectionalConnection<T>\r\n}\r\n\r\nexport type UnidirectionalEmittingConnection<T extends Capable = Capable> = {\r\n close: () => void\r\n remoteValueProxy: T\r\n}\r\n\r\nexport const startUnidirectionalEmittingConnection = <T extends Capable>(\r\n { value, uuid, platformCapabilities, send, close }:\r\n {\r\n value: Capable\r\n uuid: Uuid\r\n platformCapabilities: PlatformCapabilities\r\n send: (message: Message) => void\r\n close: () => void\r\n }\r\n) => {\r\n\r\n return {\r\n close: () => {\r\n },\r\n remoteValueProxy: new Proxy(\r\n new Function(),\r\n {\r\n apply: (target, thisArg, args) => {\r\n },\r\n get: (target, prop) => {\r\n }\r\n }\r\n ) as T\r\n }\r\n}\r\n\r\nexport type UnidirectionalReceivingConnection = {\r\n close: () => void\r\n}\r\n\r\nexport const startUnidirectionalReceivingConnection = (\r\n { uuid, remoteUuid, platformCapabilities, close }:\r\n {\r\n uuid: Uuid\r\n remoteUuid?: Uuid\r\n platformCapabilities: PlatformCapabilities\r\n eventTarget: StrictMessagePort<Message>\r\n close: () => void\r\n }\r\n) => {\r\n\r\n return {\r\n close: () => {\r\n }\r\n }\r\n}\r\n","var e=class extends EventTarget{dispatchTypedEvent(s,t){return super.dispatchEvent(t)}};export{e as TypedEventTarget};\n","import type {\r\n EmitTransport, Message,\r\n MessageContext, MessageVariant,\r\n Capable, Transport,\r\n MessageEventTarget,\r\n MessageEventMap\r\n} from './types'\r\nimport type {\r\n PlatformCapabilities, ConnectionContext,\r\n BidirectionalConnectionContext\r\n} from './utils'\r\n\r\nimport { OSRA_DEFAULT_KEY, OSRA_KEY } from './types'\r\nimport {\r\n probePlatformCapabilities,\r\n registerOsraMessageListener,\r\n sendOsraMessage,\r\n startBidirectionalConnection,\r\n isReceiveTransport,\r\n isEmitTransport,\r\n startUnidirectionalEmittingConnection,\r\n getTransferableObjects,\r\n isJsonOnlyTransport,\r\n isCustomTransport\r\n} from './utils'\r\nimport { TypedEventTarget } from 'typescript-event-target'\r\n\r\n/**\r\n * Protocol mode:\r\n * - Bidirectional mode\r\n * - Unidirectional mode\r\n *\r\n * Transport modes:\r\n * - Capable mode\r\n * - Jsonable mode\r\n */\r\nexport const expose = async <T extends Capable>(\r\n value: Capable,\r\n {\r\n transport: _transport,\r\n name,\r\n remoteName,\r\n key = OSRA_DEFAULT_KEY,\r\n origin = '*',\r\n unregisterSignal,\r\n platformCapabilities: _platformCapabilities,\r\n transferAll,\r\n logger\r\n }: {\r\n transport: Transport\r\n name?: string\r\n remoteName?: string\r\n key?: string\r\n origin?: string\r\n unregisterSignal?: AbortSignal\r\n platformCapabilities?: PlatformCapabilities\r\n transferAll?: boolean\r\n logger?: {}\r\n }\r\n): Promise<T> => {\r\n const transport = {\r\n isJson:\r\n 'isJson' in _transport && _transport.isJson !== undefined\r\n ? _transport.isJson\r\n : isJsonOnlyTransport(_transport),\r\n ...(\r\n isCustomTransport(_transport)\r\n ? _transport\r\n : {\r\n emit: _transport,\r\n receive: _transport\r\n }\r\n )\r\n } satisfies Transport\r\n const platformCapabilities = _platformCapabilities ?? await probePlatformCapabilities()\r\n const connectionContexts = new Map<string, ConnectionContext>()\r\n\r\n let resolveRemoteValue: (connection: T) => void\r\n const remoteValuePromise = new Promise<T>((resolve) => {\r\n resolveRemoteValue = resolve\r\n })\r\n\r\n let uuid = globalThis.crypto.randomUUID()\r\n\r\n const sendMessage = (transport: EmitTransport, message: MessageVariant) => {\r\n const transferables = getTransferableObjects(message)\r\n sendOsraMessage(\r\n transport,\r\n {\r\n [OSRA_KEY]: key,\r\n name,\r\n uuid,\r\n ...message\r\n },\r\n origin,\r\n transferables\r\n )\r\n }\r\n\r\n const listener = async (message: Message, messageContext: MessageContext) => {\r\n // means that our own message looped back on the channel\r\n if (message.uuid === uuid) return\r\n // Unidirectional receiving mode\r\n if (!isEmitTransport(transport)) {\r\n // Handle non bidirectional based messages here\r\n throw new Error('Unidirectional receiving mode not implemented')\r\n }\r\n // Bidirectional mode\r\n if (message.type === 'announce') {\r\n if (!message.remoteUuid) {\r\n sendMessage(transport, { type: 'announce', remoteUuid: message.uuid })\r\n return\r\n }\r\n if (message.remoteUuid !== uuid) return\r\n if (connectionContexts.has(message.uuid)) {\r\n sendMessage(\r\n transport,\r\n { type: 'reject-uuid-taken', remoteUuid: message.uuid }\r\n )\r\n return\r\n }\r\n const eventTarget = new TypedEventTarget<MessageEventMap>()\r\n const connectionContext = {\r\n type: 'bidirectional',\r\n eventTarget,\r\n connection:\r\n startBidirectionalConnection({\r\n transport,\r\n value,\r\n uuid,\r\n remoteUuid: message.uuid,\r\n platformCapabilities,\r\n eventTarget,\r\n send: (message: MessageVariant) => sendMessage(transport, message),\r\n close: () => void connectionContexts.delete(message.uuid)\r\n })\r\n } satisfies BidirectionalConnectionContext\r\n connectionContexts.set(message.uuid, connectionContext)\r\n connectionContext.connection.remoteValue.then((remoteValue) =>\r\n resolveRemoteValue(remoteValue as T)\r\n )\r\n } else if (message.type === 'reject-uuid-taken') {\r\n if (message.remoteUuid !== uuid) return\r\n uuid = globalThis.crypto.randomUUID()\r\n sendMessage(transport, { type: 'announce' })\r\n } else if (message.type === 'close') {\r\n if (message.remoteUuid !== uuid) return\r\n const connectionContext = connectionContexts.get(message.uuid)\r\n // We just drop the message if the remote uuid hasn't announced itself\r\n if (!connectionContext) {\r\n console.warn(`Connection not found for remoteUuid: ${message.uuid}`)\r\n return\r\n }\r\n connectionContext.connection.close()\r\n connectionContexts.delete(message.uuid)\r\n } else { // \"init\" | \"message\" | \"message-port-close\"\r\n if (message.remoteUuid !== uuid) return\r\n const connection = connectionContexts.get(message.uuid)\r\n // We just drop the message if the remote uuid hasn't announced itself\r\n if (!connection) {\r\n console.warn(`Connection not found for remoteUuid: ${message.uuid}`)\r\n return\r\n }\r\n if (connection.type !== 'unidirectional-emitting') {\r\n connection.eventTarget.dispatchTypedEvent(\r\n 'message',\r\n new CustomEvent('message', { detail: message })\r\n )\r\n }\r\n }\r\n }\r\n\r\n if (isReceiveTransport(transport)) {\r\n registerOsraMessageListener({\r\n listener,\r\n transport,\r\n remoteName,\r\n key,\r\n unregisterSignal\r\n })\r\n }\r\n\r\n if (isEmitTransport(transport)) {\r\n sendMessage(transport, { type: 'announce' })\r\n }\r\n\r\n // Unidirectional emitting mode\r\n if (isEmitTransport(transport) && !isReceiveTransport(transport)) {\r\n const { remoteValueProxy } = startUnidirectionalEmittingConnection<T>({\r\n value,\r\n uuid,\r\n platformCapabilities,\r\n send: (message: MessageVariant) => sendMessage(transport, message),\r\n close: () => connectionContexts.delete(uuid)\r\n })\r\n return remoteValueProxy\r\n }\r\n\r\n return remoteValuePromise\r\n}\r\n"],"names":["OSRA_KEY","OSRA_DEFAULT_KEY","OSRA_BOX","makeMessageChannelAllocator","channels","result","uuid","messagePorts","messageChannel","allocatedMessageChannel","existingChannel","checkOsraMessageKey","message","key","isOsraMessage","registerOsraMessageListener","listener","transport","remoteName","unregisterSignal","registerListenerOnReceiveTransport","receiveTransport","isWebExtensionPort","isWebExtensionOnConnect","isWebExtensionOnMessage","listenOnWebExtOnMessage","onMessage","port","_listener","sender","event","isCustomTransport","sendOsraMessage","origin","transferables","sendToEmitTransport","emitTransport","isWindow","isWebSocket","isSharedWorker","typedArrayConstructors","typedArrayToType","value","type","typedArrayTypeToTypedArrayConstructor","typedArray","isTypedArray","isServiceWorkerContainer","isWorker","isDedicatedWorker","isMessagePort","isPromise","isFunction","isArrayBuffer","isReadableStream","isDate","isError","isAlwaysBox","isClonable","isTransferable","connectPort","isEmitJsonOnlyTransport","isReceiveJsonOnlyTransport","isJsonOnlyTransport","isEmitTransport","isCustomEmitTransport","isReceiveTransport","isCustomReceiveTransport","isRevivable","isRevivableBox","isRevivableMessagePortBox","isRevivablePromiseBox","isRevivableFunctionBox","isRevivableTypedArrayBox","isRevivableArrayBufferBox","isRevivableReadableStreamBox","isRevivableErrorBox","isRevivableDateBox","getTransferableObjects","recurse","probePlatformCapabilityUtil","transfer","port1","port2","resolve","probeMessagePortTransfer","probeArrayBufferClone","buffer","probeArrayBufferTransfer","probeTransferableStream","stream","controller","probePlatformCapabilities","messagePort","arrayBuffer","transferable","transferableStream","boxMessagePort","context","portId","data","recursiveBox","reviveMessagePort","userPort","internalPort","revivedData","recursiveRevive","boxPromise","localPort","remotePort","sendResult","boxedResult","error","revivePromise","reject","boxFunction","returnValuePort","args","reviveFunction","returnValueLocalPort","returnValueRemotePort","callContext","boxTypedArray","reviveTypedArray","TypedArrayConstructor","boxArrayBuffer","reviveArrayBuffer","boxError","reviveError","boxReadableStream","reader","pullResult","reviveReadableStream","boxDate","reviveDate","box","boxedValue","revive","recursedValue","startBidirectionalConnection","remoteUuid","platformCapabilities","eventTarget","send","close","revivableContext","initResolve","initMessage","detail","startUnidirectionalEmittingConnection","target","thisArg","prop","e","s","t","expose","_transport","name","_platformCapabilities","transferAll","logger","connectionContexts","resolveRemoteValue","remoteValuePromise","sendMessage","messageContext","TypedEventTarget","connectionContext","remoteValue","connection","remoteValueProxy"],"mappings":"AAGO,MAAMA,IAAW,gBACXC,KAAmB,wBACnBC,IAAW,gBCwCXC,KAA8B,MAAM;AAC/C,QAAMC,wBAAe,IAAA,GAEfC,IAAS;AAAA,IACb,eAAe,MAAM;AACnB,UAAIC,IAAa,WAAW,OAAO,WAAA;AACnC,aAAOF,EAAS,IAAIE,CAAI;AACtB,QAAAA,IAAO,WAAW,OAAO,WAAA;AAE3B,aAAOA;AAAA,IACT;AAAA,IACA,KAAK,CAACA,GAAYC,MAA8D;AAC9E,MAAAH,EAAS,IAAIE,GAAM,EAAE,MAAAA,GAAM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GAAG;AAChE,UAAM,EAAE,kBAAA0J,EAAA,IAAqBtB,GAAyC;AAAA,MACpE,OAAA3G;AAAA,MACA,MAAApC;AAAA,MACA,sBAAAuI;AAAA,MACA,MAAM,CAACjI,MAA4ByJ,EAAYpJ,GAAWL,CAAO;AAAA,MACjE,OAAO,MAAMsJ,EAAmB,OAAO5J,CAAI;AAAA,IAAA,CAC5C;AACD,WAAOqK;AAAA,EACT;AAEA,SAAOP;AACT;","x_google_ignoreList":[8]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "osra",
3
- "version": "0.1.1",
3
+ "version": "0.2.0",
4
4
  "description": "Easy communication between workers",
5
5
  "files": [
6
6
  "build"
@@ -8,15 +8,24 @@
8
8
  "main": "build/index.js",
9
9
  "type": "module",
10
10
  "scripts": {
11
- "build": "vite build && tsc",
11
+ "build": "vite build",
12
12
  "build-watch": "vite build --watch",
13
13
  "build-test": "vite build --config vite.test.config.ts",
14
14
  "build-test-watch": "vite build --config vite.test.config.ts --watch",
15
- "dev": "concurrently \"npm run build-watch\" \"npm run build-test-watch\" \"npm run test-watch\"",
15
+ "dev": "concurrently \"npm run build-test-watch\"",
16
+ "_dev": "concurrently \"npm run build-watch\" \"npm run build-test-watch\" \"npm run test-watch\"",
16
17
  "dev2": "concurrently \"npm run build-watch\" \"npm run build-test-watch\" \"npm run test-watch-headful\"",
17
18
  "test": "npx playwright test",
18
19
  "test-watch": "set PWTEST_WATCH=1 & npx playwright test",
19
- "test-watch-headful": "npx playwright test --ui"
20
+ "test-watch-headful": "nodemon --watch build --exec \"npx playwright test --headed\"",
21
+ "test-with-coverage": "npm run build-test && npx playwright test && npm run print-coverage && npm run clean-coverage",
22
+ "print-coverage": "npx nyc report",
23
+ "clean-coverage": "rimraf .nyc_output coverage",
24
+ "type-check": "tsc --noEmit",
25
+ "start-server": "http-server -p 3000",
26
+ "linux-run-playwright": "xhost +local:docker && docker run -it --name playwright -e DISPLAY=$DISPLAY -v /tmp/.X11-unix:/tmp/.X11-unix:rw --network=host --ipc=host --shm-size=2gb --rm mcr.microsoft.com/playwright:v1.55.1-noble npx npx -y playwright@1.55.1 run-server --port 8010 --host 0.0.0.0",
27
+ "linux-test": "PW_TEST_CONNECT_WS_ENDPOINT=ws://127.0.0.1:8010/ npx playwright test -c playwright.linux.config.ts",
28
+ "linux-test-watch-headful": "nodemon --watch build --exec \"PW_TEST_CONNECT_WS_ENDPOINT=ws://127.0.0.1:8010/ npx playwright test -c playwright.linux.config.ts\""
20
29
  },
21
30
  "repository": {
22
31
  "type": "git",
@@ -29,19 +38,23 @@
29
38
  },
30
39
  "homepage": "https://github.com/Banou26/osra#readme",
31
40
  "devDependencies": {
32
- "@playwright/test": "^1.49.1",
33
- "@types/chai": "^5.0.1",
34
- "@types/chai-as-promised": "^8.0.1",
35
- "chai": "^5.1.2",
41
+ "@istanbuljs/nyc-config-typescript": "^1.0.2",
42
+ "@playwright/test": "^1.56.1",
43
+ "@types/chai": "^5.2.3",
44
+ "@types/chai-as-promised": "^8.0.2",
45
+ "@types/chrome": "^0.1.27",
46
+ "@types/firefox-webext-browser": "^120.0.5",
47
+ "chai": "^5.3.3",
36
48
  "chai-as-promised": "^8.0.1",
37
49
  "concurrently": "^9.1.0",
38
- "i": "^0.3.7",
39
- "npm": "^11.0.0",
40
- "playwright": "^1.49.1",
41
- "typescript": "^5.7.2",
42
- "vite": "^6.0.4"
43
- },
44
- "dependencies": {
45
- "uuid": "^11.0.3"
50
+ "http-server": "^14.1.1",
51
+ "nodemon": "^3.1.10",
52
+ "nyc": "^17.1.0",
53
+ "playwright": "^1.56.1",
54
+ "typescript": "^5.9.3",
55
+ "typescript-event-target": "^1.1.1",
56
+ "vite": "^7.2.2",
57
+ "vite-plugin-dts": "^4.5.4",
58
+ "vite-plugin-istanbul": "^7.2.0"
46
59
  }
47
60
  }
package/build/types.d.ts DELETED
@@ -1,66 +0,0 @@
1
- export declare const OSRA_MESSAGE_PROPERTY: "__OSRA__";
2
- export declare const OSRA_MESSAGE_KEY: "__OSRA_DEFAULT_KEY__";
3
- export declare const OSRA_PROXY: "__OSRA_PROXY__";
4
- export type JsonPropertyKey = string | number;
5
- export type JsonCloneType = boolean | null | number | string | {
6
- [key: string]: JsonCloneType;
7
- } | Array<JsonCloneType>;
8
- export type StructuredCloneType = JsonCloneType | void | undefined | BigInt | Date | RegExp | Blob | File | FileList | ArrayBuffer | ArrayBufferView | ImageBitmap | ImageData | {
9
- [key: string]: StructuredCloneType;
10
- } | Array<StructuredCloneType> | Map<StructuredCloneType, StructuredCloneType> | Set<StructuredCloneType>;
11
- export type TransferableObject = SharedArrayBuffer | ArrayBuffer | MessagePort | ReadableStream;
12
- export type StructuredCloneTransferableType = StructuredCloneType | TransferableObject | {
13
- [key: string]: StructuredCloneTransferableType;
14
- } | Array<StructuredCloneTransferableType> | Map<StructuredCloneTransferableType, StructuredCloneTransferableType> | Set<StructuredCloneTransferableType>;
15
- export type ProxiableType = Promise<StructuredCloneTransferableProxiableType> | Error | MessagePort | ReadableStream | ((...args: any[]) => Promise<StructuredCloneTransferableProxiableType>) | {
16
- [key: string]: StructuredCloneTransferableProxiableType;
17
- } | Array<StructuredCloneTransferableProxiableType> | Map<StructuredCloneTransferableProxiableType, StructuredCloneTransferableProxiableType> | Set<StructuredCloneTransferableProxiableType>;
18
- export type StructuredCloneTransferableProxiableType = ProxiableType | StructuredCloneTransferableType;
19
- type PortOrJsonPort<JsonOnly extends boolean> = JsonOnly extends true ? {
20
- portId: string;
21
- } : {
22
- port: MessagePort;
23
- };
24
- export type ProxiedFunctionType<JsonOnly extends boolean> = ({
25
- type: 'function';
26
- } & PortOrJsonPort<JsonOnly>);
27
- export type ProxiedMessagePortType<JsonOnly extends boolean> = ({
28
- type: 'messagePort';
29
- } & PortOrJsonPort<JsonOnly>);
30
- export type ProxiedPromiseType<JsonOnly extends boolean> = ({
31
- type: 'promise';
32
- } & PortOrJsonPort<JsonOnly>);
33
- export type ProxiedReadableStreamType<JsonOnly extends boolean> = ({
34
- type: 'readableStream';
35
- } & PortOrJsonPort<JsonOnly>);
36
- export type ProxiedErrorType = ({
37
- type: 'error';
38
- message: string;
39
- stack?: string;
40
- });
41
- export type ProxiedType<JsonOnly extends boolean> = {
42
- [OSRA_PROXY]: true;
43
- } & (ProxiedFunctionType<JsonOnly> | ProxiedMessagePortType<JsonOnly> | ProxiedPromiseType<JsonOnly> | ProxiedReadableStreamType<JsonOnly> | ProxiedErrorType);
44
- export type OsraMessage = {
45
- [OSRA_MESSAGE_PROPERTY]: true;
46
- key: string;
47
- } & ({
48
- type: 'ready';
49
- envCheck: {
50
- buffer: ArrayBuffer;
51
- port: MessagePort;
52
- };
53
- } | {
54
- type: 'init';
55
- data: StructuredCloneTransferableType;
56
- } | {
57
- type: 'message';
58
- portId: string;
59
- data: any;
60
- } | {
61
- type: 'port-closed';
62
- portId: string;
63
- });
64
- export type RemoteTarget = Window | ServiceWorker | Worker | MessagePort;
65
- export type LocalTarget = WindowEventHandlers | ServiceWorkerContainer | Worker | SharedWorker;
66
- export {};
package/build/utils.d.ts DELETED
@@ -1,60 +0,0 @@
1
- import type { StructuredCloneTransferableType, TransferableObject, ProxiedErrorType, ProxiedFunctionType, ProxiedMessagePortType, ProxiedPromiseType, StructuredCloneTransferableProxiableType } from './types';
2
- export declare const isClonable: (value: any) => boolean;
3
- export declare const isTransferable: (value: any) => boolean;
4
- export declare const getTransferableObjects: (value: any) => TransferableObject[];
5
- export type EnvCheck = {
6
- uuid: string;
7
- supportsPorts: boolean;
8
- jsonOnly: boolean;
9
- };
10
- export type Context = {
11
- envCheck: EnvCheck;
12
- addIncomingProxiedMessagePort: (portId: string) => MessagePort;
13
- addOutgoingProxiedMessagePort: (port: MessagePort) => string;
14
- finalizationRegistry: FinalizationRegistry<number>;
15
- };
16
- export declare const proxiedFunctionToFunction: <JsonOnly extends boolean>(proxiedFunction: ProxiedFunctionType<JsonOnly>, context: Context) => (...args: StructuredCloneTransferableType[]) => Promise<unknown>;
17
- export declare const proxiedMessagePortToMessagePort: <JsonOnly extends boolean>(proxiedMessagePort: ProxiedMessagePortType<JsonOnly>, context: Context) => MessagePort;
18
- export declare const proxiedErrorToError: (proxiedError: ProxiedErrorType, context: Context) => Error;
19
- export declare const proxiedPromiseToPromise: <JsonOnly extends boolean>(proxiedPromise: ProxiedPromiseType<JsonOnly>, context: Context) => Promise<unknown>;
20
- export declare const replaceIncomingProxiedTypes: (value: StructuredCloneTransferableType, context: Context) => StructuredCloneTransferableProxiableType;
21
- export declare const errorToProxiedError: (error: Error, _: Context) => {
22
- __OSRA_PROXY__: boolean;
23
- type: string;
24
- message: string;
25
- stack: string | undefined;
26
- };
27
- export declare const messagePortToProxiedMessagePort: (port: MessagePort, context: Context) => {
28
- port: MessagePort;
29
- __OSRA_PROXY__: boolean;
30
- type: string;
31
- } | {
32
- portId: string;
33
- __OSRA_PROXY__: boolean;
34
- type: string;
35
- };
36
- export declare const promiseToProxiedPromise: (promise: Promise<StructuredCloneTransferableType>, context: Context) => {
37
- __OSRA_PROXY__: boolean;
38
- type: string;
39
- port: any;
40
- };
41
- export declare const functionToProxiedFunction: (func: Function, context: Context) => {
42
- __OSRA_PROXY__: boolean;
43
- type: string;
44
- port: any;
45
- };
46
- export declare const replaceOutgoingProxiedTypes: <T extends StructuredCloneTransferableProxiableType>(value: T, context: Context) => any;
47
- export declare const replaceRecursive: <T extends StructuredCloneTransferableProxiableType, T2 extends (value: any) => any>(value: T, shouldReplace: (value: Parameters<T2>[0]) => boolean, replaceFunction: T2) => any;
48
- export declare const makeNumberAllocator: () => {
49
- alloc: () => number;
50
- free: (number: any) => void;
51
- };
52
- type NumberAllocator = ReturnType<typeof makeNumberAllocator>;
53
- export declare const makeAllocator: <T>({ numberAllocator }: {
54
- numberAllocator: NumberAllocator;
55
- }) => {
56
- alloc: (value: T) => number;
57
- get: (id: number) => T | undefined;
58
- free: (id: number) => void;
59
- };
60
- export {};