@gjsify/ipc-channel 0.0.0-stage → 0.64.20
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +43 -2
- package/lib/esm/_virtual/_rolldown/runtime.js +1 -0
- package/lib/esm/gi.js +1 -0
- package/lib/esm/index.js +1 -0
- package/lib/esm/line-channel.js +2 -0
- package/lib/esm/node-channel.js +1 -0
- package/lib/esm/sab-transfer.js +1 -0
- package/lib/esm/structured-clone-wire.js +1 -0
- package/lib/esm/subprocess-port-transport.js +3 -0
- package/lib/esm/wire.js +1 -0
- package/lib/types/gi.d.ts +4 -0
- package/lib/types/index.d.ts +4 -0
- package/lib/types/line-channel.d.ts +29 -0
- package/lib/types/node-channel.d.ts +29 -0
- package/lib/types/sab-transfer.d.ts +57 -0
- package/lib/types/structured-clone-wire.d.ts +21 -0
- package/lib/types/subprocess-port-transport.d.ts +43 -0
- package/lib/types/wire.d.ts +5 -0
- package/package.json +87 -5
package/README.md
CHANGED
|
@@ -1,3 +1,44 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @gjsify/ipc-channel
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
The message channel between two GJS processes: newline-framed JSON over a Gio stream pair, the
|
|
4
|
+
structured-clone wire codec, SharedBuffer fd transfer and cross-process `MessagePort` routing.
|
|
5
|
+
`@gjsify/worker_threads`' `Worker` runs on it, and `child_process.fork` will (ADR 0133). It knows
|
|
6
|
+
nothing about workers or `fork`; those decide what a message means.
|
|
7
|
+
|
|
8
|
+
Part of the [gjsify](https://github.com/gjsify/gjsify) project. GJS only. Most apps never import
|
|
9
|
+
it directly; they use `worker_threads` or `child_process`.
|
|
10
|
+
|
|
11
|
+
## Installation
|
|
12
|
+
|
|
13
|
+
```bash
|
|
14
|
+
gjsify install @gjsify/ipc-channel
|
|
15
|
+
```
|
|
16
|
+
|
|
17
|
+
## Usage
|
|
18
|
+
|
|
19
|
+
```typescript
|
|
20
|
+
import { LineChannel, decode, encode } from '@gjsify/ipc-channel';
|
|
21
|
+
|
|
22
|
+
// `subprocess` is a Gio.Subprocess spawned with STDIN_PIPE | STDOUT_PIPE
|
|
23
|
+
const channel = new LineChannel(subprocess.get_stdin_pipe(), subprocess.get_stdout_pipe());
|
|
24
|
+
channel.startReading(
|
|
25
|
+
(message) => console.log(decode(message.data)),
|
|
26
|
+
() => console.log('peer closed'),
|
|
27
|
+
);
|
|
28
|
+
channel.send({ type: 'message', data: encode(new Map([[1, new Date()]])) });
|
|
29
|
+
```
|
|
30
|
+
|
|
31
|
+
| Export | What it does |
|
|
32
|
+
|---|---|
|
|
33
|
+
| `LineChannel` | One JSON text per line. The read loop ends on EOF or a line that is not JSON, never because a handler threw |
|
|
34
|
+
| `encode` / `decode` | Tagged JSON for the structured-clone types JSON cannot carry (Map, Set, Date, typed arrays, BigInt, Error, shared references) |
|
|
35
|
+
| `createDataCloneError` | The `DataCloneError` the HTML spec throws for an uncloneable value |
|
|
36
|
+
| `extractSharedBuffers` / `materializeSharedBuffers` | Replace `SharedBuffer`s with tagged placeholders, and back, around the SCM_RIGHTS side-channel |
|
|
37
|
+
| `SubprocessPortTransport` | `MessagePort` transport that routes a port's traffic over the channel by port id |
|
|
38
|
+
|
|
39
|
+
Everything but `LineChannel` is also exported from `@gjsify/ipc-channel/wire`, which imports no Gio
|
|
40
|
+
and runs on Node.js and in browsers as well.
|
|
41
|
+
|
|
42
|
+
## License
|
|
43
|
+
|
|
44
|
+
MIT
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
var e=Object.defineProperty,__name=(t,n)=>e(t,`name`,{value:n,configurable:!0});export{__name};
|
package/lib/esm/gi.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import"./_virtual/_rolldown/runtime.js";function gi(){let e=globalThis.imports?.gi;if(!e?.Gio||!e.GLib)throw Error(`@gjsify/ipc-channel needs a GJS host (imports.gi)`);return{Gio:e.Gio,GLib:e.GLib}}const gio=()=>gi().Gio,glib=()=>gi().GLib;export{gio,glib};
|
package/lib/esm/index.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LineChannel as e}from"./line-channel.js";import{isInternalMessage as t,setupNodeChannel as n}from"./node-channel.js";import{createDataCloneError as r,createErrorByName as i,decode as a,encode as o}from"./structured-clone-wire.js";import{extractSharedBuffers as s,isSharedBuffer as c,isSharedBufferPlaceholder as l,materializeSharedBuffers as u}from"./sab-transfer.js";import{SubprocessPortTransport as d,isCrossProcessPortPlaceholder as f,nextChildPortId as p,nextParentPortId as m}from"./subprocess-port-transport.js";import"./wire.js";export{e as LineChannel,d as SubprocessPortTransport,r as createDataCloneError,i as createErrorByName,a as decode,o as encode,s as extractSharedBuffers,f as isCrossProcessPortPlaceholder,t as isInternalMessage,c as isSharedBuffer,l as isSharedBufferPlaceholder,u as materializeSharedBuffers,p as nextChildPortId,m as nextParentPortId,n as setupNodeChannel};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import"./_virtual/_rolldown/runtime.js";import{gio as e,glib as t}from"./gi.js";const n=new TextEncoder;var LineChannel=class{_output;_input;constructor(t,n=null){this._output=t,this._input=n?e().DataInputStream.new(n):null}get writable(){return this._output!==null}writeLine(e){if(!this._output)throw Error(`LineChannel: output is closed`);this._output.write_all(n.encode(e),null)}send(e){this.writeLine(JSON.stringify(e)+`
|
|
2
|
+
`)}startReading(e,n){let r=this._input;if(!r)throw Error(`LineChannel: no input stream`);let readNext=()=>{r.read_line_async(t().PRIORITY_DEFAULT,null,(t,i)=>{let a;try{let[e]=r.read_line_finish_utf8(i);if(e===null){n?.();return}a=JSON.parse(e)}catch{n?.();return}try{e(a)}catch{}finally{readNext()}})};readNext()}closeOutput(){if(this._output){try{this._output.close(null)}catch{}this._output=null}}};export{LineChannel};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import"./_virtual/_rolldown/runtime.js";import{gio as e}from"./gi.js";import{LineChannel as t}from"./line-channel.js";import{acquireMainLoop as n,releaseMainLoop as r}from"@gjsify/utils/main-loop";function codedError(e,t,n){let r=new e(n);return r.code=t,r}function isInternalMessage(e){if(typeof e!=`object`||!e)return!1;let t=e.cmd;return typeof t==`string`&&t.length>4&&t.startsWith(`NODE_`)}function setupNodeChannel(i,a){let o=e().Socket.new_from_fd(a),s=o.connection_factory_create_connection(),c=new t(s.get_output_stream(),s.get_input_stream()),l=!0,u=!0,d=!1,updateHold=()=>{let e=l&&u&&i.listenerCount(`message`)+i.listenerCount(`disconnect`)>0;e!==d&&(d=e,e?n():r())};i.on(`newListener`,e=>{(e===`message`||e===`disconnect`)&&queueMicrotask(updateHold)}),i.on(`removeListener`,e=>{(e===`message`||e===`disconnect`)&&queueMicrotask(updateHold)});let f=!0,release=()=>{try{o.close()}catch{}},close=()=>{if(l){l=!1,i.connected=!1,i.channel=null;try{o.shutdown(!0,!0)}catch{}f||release(),queueMicrotask(()=>{i.emit(`disconnect`),updateHold()})}},send=(e,t,n,r)=>{typeof t==`function`?(r=t,t=void 0):typeof n==`function`&&(r=n);let a=typeof r==`function`?r:void 0;if(!l){let e=codedError(Error,`ERR_IPC_CHANNEL_CLOSED`,`Channel closed`);return queueMicrotask(a?()=>a(e):()=>i.emit(`error`,e)),!1}if(e===void 0)throw codedError(TypeError,`ERR_MISSING_ARGS`,`The "message" argument must be specified`);if(![`string`,`object`,`number`,`boolean`].includes(typeof e))throw codedError(TypeError,`ERR_INVALID_ARG_TYPE`,`The "message" argument must be one of type string, object, number, or boolean. Received type ${typeof e}`);if(t!=null)throw codedError(Error,`ERR_FEATURE_UNAVAILABLE_ON_PLATFORM`,`Sending a handle over the IPC channel is not supported under GJS`);try{c.send(e)}catch(e){let t=e instanceof Error?e:Error(String(e));return queueMicrotask(a?()=>a(t):()=>i.emit(`error`,t)),!1}return a&&queueMicrotask(()=>a(null)),!0},disconnect=()=>{if(!l){i.emit(`error`,codedError(Error,`ERR_IPC_DISCONNECTED`,`IPC channel is already disconnected`));return}close()},p={fd:a,ref(){u=!0,updateHold()},unref(){u=!1,updateHold()}};return Object.assign(i,{send,disconnect,channel:p,connected:!0}),c.startReading(e=>{l&&(isInternalMessage(e)?i.emit(`internalMessage`,e):i.emit(`message`,e,void 0))},()=>{f=!1,close(),release()}),d=!0,n(),queueMicrotask(updateHold),p}export{isInternalMessage,setupNodeChannel};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import"./_virtual/_rolldown/runtime.js";function isSharedBufferPlaceholder(e){return typeof e==`object`&&!!e&&typeof e.__sab==`number`&&typeof e.size==`number`}function isSharedBuffer(e){return typeof e==`object`&&!!e&&e.constructor?.name===`SharedBuffer`}function extractSharedBuffers(e,t){let n=[],r=new Map,i=t;function walk(e,t){if(typeof e!=`object`||!e)return e;if(isSharedBuffer(e)){let t=r.get(e);return t===void 0&&(t=i++,r.set(e,t),n.push({tag:t,buffer:e})),{__sab:t,size:e.byteLength}}if(t.has(e))return t.get(e);if(Array.isArray(e)){let n=[];t.set(e,n);for(let r=0;r<e.length;r++)r in e&&(n[r]=walk(e[r],t));return n}if(Object.prototype.toString.call(e).slice(8,-1)===`Object`){let n={};t.set(e,n);for(let r of Object.keys(e))n[r]=walk(e[r],t);return n}return e}return{value:walk(e,new Map),table:n,nextTag:i}}function materializeSharedBuffers(e,t){function walk(e,n){if(typeof e!=`object`||!e)return e;if(isSharedBufferPlaceholder(e))return t(e.__sab,e.size);if(n.has(e))return n.get(e);if(Array.isArray(e)){n.set(e,e);for(let t=0;t<e.length;t++)t in e&&(e[t]=walk(e[t],n));return e}if(Object.prototype.toString.call(e).slice(8,-1)===`Object`){n.set(e,e);for(let t of Object.keys(e))e[t]=walk(e[t],n);return e}return e}return walk(e,new Map)}export{extractSharedBuffers,isSharedBuffer,isSharedBufferPlaceholder,materializeSharedBuffers};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import"./_virtual/_rolldown/runtime.js";const e=[`Int8Array`,`Uint8Array`,`Uint8ClampedArray`,`Int16Array`,`Uint16Array`,`Int32Array`,`Uint32Array`,`Float32Array`,`Float64Array`,`BigInt64Array`,`BigUint64Array`],t={Error,EvalError,RangeError,ReferenceError,SyntaxError,TypeError,URIError};function createErrorByName(e,n){return new((e===void 0?void 0:t[e])??Error)(n)}const n=`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/`,r=new Uint8Array(128);for(let e=0;e<64;e++)r[n.charCodeAt(e)]=e;function toBase64(e){let t=new Uint8Array(e),r=``;for(let e=0;e<t.length;e+=3){let i=t[e],a=e+1<t.length,o=e+2<t.length,s=i<<16|(a?t[e+1]:0)<<8|(o?t[e+2]:0);r+=n[s>>18&63]+n[s>>12&63]+(a?n[s>>6&63]:`=`)+(o?n[s&63]:`=`)}return r}function fromBase64(e){let t=e.length;for(;t>0&&e.charCodeAt(t-1)===61;)t--;let n=new Uint8Array(t*3>>2),i=0,a=0,o=0;for(let s=0;s<t;s++)i=i<<6|r[e.charCodeAt(s)],a+=6,a>=8&&(a-=8,n[o++]=i>>a&255);return n}function isHoleTag(e){return typeof e==`object`&&!!e&&!Array.isArray(e)&&e.__gjsify===`Hole`}function encode(n,r=new Map){if(n===null)return null;if(n===void 0)return{__gjsify:`Undefined`};switch(typeof n){case`bigint`:return{__gjsify:`BigInt`,value:n.toString()};case`number`:return n===1/0?{__gjsify:`Infinity`}:n===-1/0?{__gjsify:`NegInfinity`}:Number.isNaN(n)?{__gjsify:`NaN`}:Object.is(n,-0)?{__gjsify:`NegZero`}:n;case`string`:case`boolean`:return n;case`function`:case`symbol`:throw createDataCloneError(`${String(n)} could not be cloned.`);default:break}let i=r.get(n);if(i!==void 0)return{__gjsify:`Ref`,id:i};if(r.set(n,r.size),n instanceof Date)return{__gjsify:`Date`,value:n.getTime()};if(n instanceof RegExp){let e=n;return{__gjsify:`RegExp`,source:e.source,flags:e.flags}}if(n instanceof Error){let e=n;return{__gjsify:`Error`,name:t[e.name]===void 0?`Error`:e.name,message:e.message,stack:e.stack}}if(n instanceof Map){let e=[];for(let[t,i]of n)e.push([encode(t,r),encode(i,r)]);return{__gjsify:`Map`,entries:e}}if(n instanceof Set){let e=[];for(let t of n)e.push(encode(t,r));return{__gjsify:`Set`,values:e}}let a=Object.prototype.toString.call(n).slice(8,-1);if(a===`ArrayBuffer`)return{__gjsify:`ArrayBuffer`,data:toBase64(n)};if(a===`DataView`||e.includes(a)){let e=n;return{__gjsify:a,data:toBase64(e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength))}}if(Array.isArray(n)){let e=[];for(let t=0;t<n.length;t++)e.push(t in n?encode(n[t],r):{__gjsify:`Hole`});return e}if(a===`Object`){let e=n,t={};for(let n of Object.keys(e))t[n]=encode(e[n],r);return typeof e.__gjsify==`string`?{__gjsify:`Object`,value:t}:t}throw createDataCloneError(`value could not be cloned.`)}function decode(n,r=[]){if(typeof n!=`object`||!n)return n;if(Array.isArray(n)){let e=[];e.length=n.length,r.push(e);for(let t=0;t<n.length;t++)isHoleTag(n[t])||(e[t]=decode(n[t],r));return e}let i=n;if(typeof i.__gjsify==`string`)switch(i.__gjsify){case`Ref`:return r[i.id];case`Undefined`:return;case`Hole`:return;case`BigInt`:return BigInt(i.value);case`Infinity`:return 1/0;case`NegInfinity`:return-1/0;case`NaN`:return NaN;case`NegZero`:return-0;case`Date`:{let e=new Date(i.value);return r.push(e),e}case`RegExp`:{let e=new RegExp(i.source,i.flags);return r.push(e),e}case`Error`:{let e=new(t[i.name]??Error)(i.message);return i.stack&&(e.stack=i.stack),r.push(e),e}case`Map`:{let e=new Map;r.push(e);for(let[t,n]of i.entries)e.set(decode(t,r),decode(n,r));return e}case`Set`:{let e=new Set;r.push(e);for(let t of i.values)e.add(decode(t,r));return e}case`ArrayBuffer`:{let e=fromBase64(i.data).buffer;return r.push(e),e}case`DataView`:{let e=new DataView(fromBase64(i.data).buffer);return r.push(e),e}case`Object`:{let e=i.value,t={};r.push(t);for(let n of Object.keys(e))t[n]=decode(e[n],r);return t}default:if(e.includes(i.__gjsify)){let e=fromBase64(i.data),t=globalThis[i.__gjsify],n=new t(e.buffer);return r.push(n),n}return r.push(n),n}if(Object.prototype.toString.call(n).slice(8,-1)===`Object`){let e={};r.push(e);for(let t of Object.keys(i))e[t]=decode(i[t],r);return e}return r.push(n),n}function createDataCloneError(e){let t=globalThis.DOMException;if(typeof t==`function`){let n=new t(e,`DataCloneError`);if(n.code===void 0)try{Object.defineProperty(n,"code",{value:25,configurable:!0})}catch{}return n}let n=Error(e);return n.name=`DataCloneError`,n.code=25,n}export{createDataCloneError,createErrorByName,decode,encode};
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
import"./_virtual/_rolldown/runtime.js";import{encode as e}from"./structured-clone-wire.js";var SubprocessPortTransport=class{_sendLine;_registry;constructor(e,t){this._sendLine=e,this._registry=t}send(t,n){let r=JSON.stringify({__msgport:t,op:`send`,data:e(n)})+`
|
|
2
|
+
`;this._sendLine(r)}close(e){let t=JSON.stringify({__msgport:e,op:`close`})+`
|
|
3
|
+
`;try{this._sendLine(t)}catch{}this._registry.delete(e)}};let t=1,n=2;function nextParentPortId(){let e=t;return t+=2,e}function nextChildPortId(){let e=n;return n+=2,e}function isCrossProcessPortPlaceholder(e){return typeof e==`object`&&!!e&&e.__gjsifyTransferredPort===!0&&typeof e.portId==`number`}export{SubprocessPortTransport,isCrossProcessPortPlaceholder,nextChildPortId,nextParentPortId};
|
package/lib/esm/wire.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{createDataCloneError as e,createErrorByName as t,decode as n,encode as r}from"./structured-clone-wire.js";import{extractSharedBuffers as i,isSharedBuffer as a,isSharedBufferPlaceholder as o,materializeSharedBuffers as s}from"./sab-transfer.js";import{SubprocessPortTransport as c,isCrossProcessPortPlaceholder as l,nextChildPortId as u,nextParentPortId as d}from"./subprocess-port-transport.js";export{c as SubprocessPortTransport,e as createDataCloneError,t as createErrorByName,n as decode,r as encode,i as extractSharedBuffers,l as isCrossProcessPortPlaceholder,a as isSharedBuffer,o as isSharedBufferPlaceholder,s as materializeSharedBuffers,u as nextChildPortId,d as nextParentPortId};
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import type Gio from '@girs/gio-2.0';
|
|
2
|
+
export declare class LineChannel {
|
|
3
|
+
private _output;
|
|
4
|
+
private _input;
|
|
5
|
+
/**
|
|
6
|
+
* @param output where lines are written (a child's stdin pipe, a socket's
|
|
7
|
+
* output stream); `null` for a read-only channel.
|
|
8
|
+
* @param input where lines are read from; `null` for a write-only channel.
|
|
9
|
+
*/
|
|
10
|
+
constructor(output: Gio.OutputStream | null, input?: Gio.InputStream | null);
|
|
11
|
+
/** Whether lines can still be written. */
|
|
12
|
+
get writable(): boolean;
|
|
13
|
+
/**
|
|
14
|
+
* Write one already-framed line (it must end in `\n`). Throws when the
|
|
15
|
+
* stream is closed or the write fails; callers that treat a vanished peer
|
|
16
|
+
* as a race catch it themselves.
|
|
17
|
+
*/
|
|
18
|
+
writeLine(line: string): void;
|
|
19
|
+
/** Frame `message` as one JSON line and write it. Throws like {@link writeLine}. */
|
|
20
|
+
send(message: unknown): void;
|
|
21
|
+
/**
|
|
22
|
+
* Start the read loop: every line is parsed as JSON and handed to
|
|
23
|
+
* `onMessage`. The loop ends on EOF or on a line that is not JSON, and then
|
|
24
|
+
* calls `onEnd` once.
|
|
25
|
+
*/
|
|
26
|
+
startReading<T = unknown>(onMessage: (message: T) => void, onEnd?: () => void): void;
|
|
27
|
+
/** Close the output side. The peer reads EOF. Never throws. */
|
|
28
|
+
closeOutput(): void;
|
|
29
|
+
}
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
/** The emitter surface a channel is installed on; `ChildProcess` and `process` both fit. */
|
|
2
|
+
export interface NodeChannelTarget {
|
|
3
|
+
connected?: boolean;
|
|
4
|
+
emit(event: string, ...args: unknown[]): boolean;
|
|
5
|
+
on(event: string, listener: (...args: any[]) => void): unknown;
|
|
6
|
+
once(event: string, listener: (...args: any[]) => void): unknown;
|
|
7
|
+
listenerCount(event: string): number;
|
|
8
|
+
}
|
|
9
|
+
export type SendCallback = (error: Error | null) => void;
|
|
10
|
+
/** `target.channel`, as Node shapes it. */
|
|
11
|
+
export interface NodeChannelHandle {
|
|
12
|
+
readonly fd: number;
|
|
13
|
+
ref(): void;
|
|
14
|
+
unref(): void;
|
|
15
|
+
}
|
|
16
|
+
/**
|
|
17
|
+
* Node routes a message whose `cmd` starts with `NODE_` to `'internalMessage'`
|
|
18
|
+
* (handle passing, cluster), never to `'message'`.
|
|
19
|
+
*/
|
|
20
|
+
export declare function isInternalMessage(message: unknown): boolean;
|
|
21
|
+
/**
|
|
22
|
+
* Install Node's channel API on `target` over the connected stream socket `fd`,
|
|
23
|
+
* which this call takes ownership of, and start reading.
|
|
24
|
+
*
|
|
25
|
+
* The channel holds the main loop while it is connected, not `unref()`ed, and
|
|
26
|
+
* `target` has a `'message'` or `'disconnect'` listener. Measured on Node 24: a
|
|
27
|
+
* forked child with either listener stays alive, a child with neither exits.
|
|
28
|
+
*/
|
|
29
|
+
export declare function setupNodeChannel(target: NodeChannelTarget, fd: number): NodeChannelHandle;
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
import type { SharedBuffer } from '@gjsify/sab-native';
|
|
2
|
+
/**
|
|
3
|
+
* Placeholder for a SharedBuffer instance that has been transferred
|
|
4
|
+
* cross-process. The receiver reconstructs a SharedBuffer from the
|
|
5
|
+
* incoming fd indexed by `__sab` (the tag the sender attached to the
|
|
6
|
+
* SCM_RIGHTS message), with the original byteLength.
|
|
7
|
+
*/
|
|
8
|
+
export interface SharedBufferPlaceholder {
|
|
9
|
+
readonly __sab: number;
|
|
10
|
+
readonly size: number;
|
|
11
|
+
}
|
|
12
|
+
export declare function isSharedBufferPlaceholder(value: unknown): value is SharedBufferPlaceholder;
|
|
13
|
+
/**
|
|
14
|
+
* Detect a SharedBuffer instance without holding a hard runtime reference
|
|
15
|
+
* to the constructor — keeps the check resilient when sab-native's
|
|
16
|
+
* prebuild is unavailable (the import resolves but the class never gets
|
|
17
|
+
* instantiated) and avoids paying the typelib load just to typecheck a
|
|
18
|
+
* message payload.
|
|
19
|
+
*/
|
|
20
|
+
export declare function isSharedBuffer(value: unknown): value is SharedBuffer;
|
|
21
|
+
/**
|
|
22
|
+
* Walk `value`, replace every SharedBuffer instance with a placeholder
|
|
23
|
+
* carrying a freshly-allocated tag, and return the substituted tree
|
|
24
|
+
* alongside the table of (tag, SharedBuffer) pairs the caller must send
|
|
25
|
+
* over the SCM_RIGHTS side-channel before the JSON message itself.
|
|
26
|
+
*
|
|
27
|
+
* The walker handles plain objects + arrays. Other tagged types
|
|
28
|
+
* (Map, Set, …) are passed through unchanged — same constraint Node
|
|
29
|
+
* applies to its in-built clone walker.
|
|
30
|
+
*
|
|
31
|
+
* Tags start at `startTag` and increment per discovery. Callers should
|
|
32
|
+
* thread a per-Worker sequence counter so tags stay unique within a
|
|
33
|
+
* single FdChannel pair's lifetime (4 G tags = 2³² = plenty).
|
|
34
|
+
*/
|
|
35
|
+
export declare function extractSharedBuffers(value: unknown, startTag: number): {
|
|
36
|
+
value: unknown;
|
|
37
|
+
table: {
|
|
38
|
+
tag: number;
|
|
39
|
+
buffer: SharedBuffer;
|
|
40
|
+
}[];
|
|
41
|
+
nextTag: number;
|
|
42
|
+
};
|
|
43
|
+
/**
|
|
44
|
+
* Receiver-side counterpart: walk a tree that may contain
|
|
45
|
+
* SharedBufferPlaceholder leaves and replace each with the corresponding
|
|
46
|
+
* SharedBuffer reconstructed from the fdMap. Mutates the input in place
|
|
47
|
+
* (callers always work on a freshly-parsed JSON tree, so this avoids an
|
|
48
|
+
* extra copy).
|
|
49
|
+
*
|
|
50
|
+
* If a placeholder references a tag that is not yet in `fdMap`, the
|
|
51
|
+
* caller should buffer the message and retry once the recv-loop fills
|
|
52
|
+
* the missing entry. In the current protocol the sender always
|
|
53
|
+
* sends fds before the JSON line, so the map is populated by the time
|
|
54
|
+
* the JSON arrives — but the bootstrap layer is responsible for that
|
|
55
|
+
* ordering.
|
|
56
|
+
*/
|
|
57
|
+
export declare function materializeSharedBuffers(value: unknown, resolveTag: (tag: number, size: number) => SharedBuffer): unknown;
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
/** An error rebuilt from a name and message sent as plain fields (the child's
|
|
2
|
+
* `error` line), with the same interned names as the codec's `Error` tag. */
|
|
3
|
+
export declare function createErrorByName(name: string | undefined, message: string): Error;
|
|
4
|
+
/**
|
|
5
|
+
* Encode `value` into a JSON-safe tree.
|
|
6
|
+
*
|
|
7
|
+
* `refs` is the serialisation memory of §2.7.3: every object gets an id the
|
|
8
|
+
* first time it is reached, and a second sighting becomes a `Ref` to that id.
|
|
9
|
+
* The ids are implicit — pre-order position, assigned by `refs.size` here and
|
|
10
|
+
* by push order in `decode` — so sharing and cycles cost no extra bytes on the
|
|
11
|
+
* wire and need no second pass over the tree.
|
|
12
|
+
*/
|
|
13
|
+
export declare function encode(value: unknown, refs?: Map<object, number>): unknown;
|
|
14
|
+
/**
|
|
15
|
+
* Decode a tree produced by `encode`. `refs` is the deserialisation memory:
|
|
16
|
+
* each object is pushed in the same pre-order the encoder numbered it in, so
|
|
17
|
+
* `Ref` ids resolve by index. Containers are pushed BEFORE their children so
|
|
18
|
+
* that a cycle can point back at a half-built parent.
|
|
19
|
+
*/
|
|
20
|
+
export declare function decode(value: unknown, refs?: unknown[]): unknown;
|
|
21
|
+
export declare function createDataCloneError(message: string): Error;
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
import type { MessagePortTransport } from '@gjsify/message-channel';
|
|
2
|
+
/** Function that writes one already-encoded line to the wire (e.g. parent's
|
|
3
|
+
* `child.stdin.write(line)` or child bootstrap's `process.stdout.write(line)`). */
|
|
4
|
+
export type WireWriter = (line: string) => void;
|
|
5
|
+
/**
|
|
6
|
+
* Per-Worker registry of locally-resident cross-process MessagePort
|
|
7
|
+
* instances, keyed by portId. The wire-side dispatcher (stdout reader on
|
|
8
|
+
* parent, stdin reader on child) looks up the local port by portId and
|
|
9
|
+
* routes incoming `{ __msgport, op: 'send', data }` to
|
|
10
|
+
* `port._inner._receive(data)`. `op: 'close'` calls `port._inner.close()`.
|
|
11
|
+
*
|
|
12
|
+
* Parent-side: keyed by the same portId attached to the SubprocessPortTransport
|
|
13
|
+
* that the OTHER side's port writes from. Child-side bootstrap maintains its
|
|
14
|
+
* own registry with the same shape.
|
|
15
|
+
*/
|
|
16
|
+
export interface CrossProcessPortRegistry extends Map<number, any> {
|
|
17
|
+
}
|
|
18
|
+
export declare class SubprocessPortTransport implements MessagePortTransport {
|
|
19
|
+
private readonly _sendLine;
|
|
20
|
+
private readonly _registry;
|
|
21
|
+
/**
|
|
22
|
+
* @param sendLine writes a JSON-line to the wire (parent: child.stdin;
|
|
23
|
+
* child: process.stdout).
|
|
24
|
+
* @param registry the local registry the port is registered in; on
|
|
25
|
+
* `close()` we drop the entry to keep the registry from
|
|
26
|
+
* growing unbounded across spawn/transfer/terminate
|
|
27
|
+
* cycles.
|
|
28
|
+
*/
|
|
29
|
+
constructor(_sendLine: WireWriter, _registry: CrossProcessPortRegistry);
|
|
30
|
+
send(portId: number, data: unknown): void;
|
|
31
|
+
close(portId: number): void;
|
|
32
|
+
}
|
|
33
|
+
export declare function nextParentPortId(): number;
|
|
34
|
+
export declare function nextChildPortId(): number;
|
|
35
|
+
/** Cross-process MessagePort placeholder. Distinct from the in-process
|
|
36
|
+
* `{ index }` form so the receiver-side materialiser can dispatch on shape. */
|
|
37
|
+
export interface CrossProcessPortPlaceholder {
|
|
38
|
+
readonly __gjsifyTransferredPort: true;
|
|
39
|
+
/** Stable id used by both sides' registries to route subsequent
|
|
40
|
+
* `{ __msgport, op }` lines back to the right local port. */
|
|
41
|
+
readonly portId: number;
|
|
42
|
+
}
|
|
43
|
+
export declare function isCrossProcessPortPlaceholder(value: unknown): value is CrossProcessPortPlaceholder;
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
export { createDataCloneError, createErrorByName, decode, encode } from './structured-clone-wire.ts';
|
|
2
|
+
export { extractSharedBuffers, isSharedBuffer, isSharedBufferPlaceholder, materializeSharedBuffers, } from './sab-transfer.ts';
|
|
3
|
+
export type { SharedBufferPlaceholder } from './sab-transfer.ts';
|
|
4
|
+
export { SubprocessPortTransport, isCrossProcessPortPlaceholder, nextChildPortId, nextParentPortId, } from './subprocess-port-transport.ts';
|
|
5
|
+
export type { CrossProcessPortPlaceholder, CrossProcessPortRegistry, WireWriter } from './subprocess-port-transport.ts';
|
package/package.json
CHANGED
|
@@ -1,6 +1,88 @@
|
|
|
1
1
|
{
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
2
|
+
"name": "@gjsify/ipc-channel",
|
|
3
|
+
"version": "0.64.20",
|
|
4
|
+
"description": "Message channel between two GJS processes: line framing, structured-clone wire codec, SharedBuffer fd transfer, cross-process MessagePort routing",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"module": "lib/esm/index.js",
|
|
7
|
+
"types": "lib/types/index.d.ts",
|
|
8
|
+
"exports": {
|
|
9
|
+
".": {
|
|
10
|
+
"types": "./lib/types/index.d.ts",
|
|
11
|
+
"default": "./lib/esm/index.js"
|
|
12
|
+
},
|
|
13
|
+
"./wire": {
|
|
14
|
+
"types": "./lib/types/wire.d.ts",
|
|
15
|
+
"default": "./lib/esm/wire.js"
|
|
16
|
+
},
|
|
17
|
+
"./node-channel": {
|
|
18
|
+
"types": "./lib/types/node-channel.d.ts",
|
|
19
|
+
"default": "./lib/esm/node-channel.js"
|
|
20
|
+
}
|
|
21
|
+
},
|
|
22
|
+
"files": [
|
|
23
|
+
"lib"
|
|
24
|
+
],
|
|
25
|
+
"scripts": {
|
|
26
|
+
"clear": "gjsify clear lib tsconfig.tsbuildinfo tsconfig.types.tsbuildinfo test.gjs.mjs",
|
|
27
|
+
"check": "gjsify tsc --noEmit",
|
|
28
|
+
"build": "gjsify run build:gjsify && gjsify run build:types",
|
|
29
|
+
"build:gjsify": "gjsify build --library 'src/**/*.{ts,js}' --exclude 'src/**/*.spec.{mts,ts}' 'src/test.{mts,ts}'",
|
|
30
|
+
"build:types": "gjsify tsc",
|
|
31
|
+
"build:test": "gjsify run build:test:gjs",
|
|
32
|
+
"build:test:gjs": "gjsify build src/test.mts --app gjs --outfile test.gjs.mjs",
|
|
33
|
+
"test": "gjsify run build:gjsify && gjsify run build:test && gjsify run test:gjs",
|
|
34
|
+
"test:gjs": "gjsify run test.gjs.mjs"
|
|
35
|
+
},
|
|
36
|
+
"keywords": [
|
|
37
|
+
"gjs",
|
|
38
|
+
"ipc",
|
|
39
|
+
"structured-clone",
|
|
40
|
+
"subprocess"
|
|
41
|
+
],
|
|
42
|
+
"devDependencies": {
|
|
43
|
+
"@gjsify/cli": "^0.64.20",
|
|
44
|
+
"@gjsify/unit": "^0.64.20",
|
|
45
|
+
"@types/node": "^25.9.2",
|
|
46
|
+
"typescript": "^6.0.3"
|
|
47
|
+
},
|
|
48
|
+
"dependencies": {
|
|
49
|
+
"@girs/gio-2.0": "5.4.0",
|
|
50
|
+
"@girs/glib-2.0": "5.4.0",
|
|
51
|
+
"@gjsify/message-channel": "^0.64.20",
|
|
52
|
+
"@gjsify/sab-native": "^0.64.20",
|
|
53
|
+
"@gjsify/utils": "^0.64.20"
|
|
54
|
+
},
|
|
55
|
+
"gjsify": {
|
|
56
|
+
"runtimes": {
|
|
57
|
+
"gjs": "polyfill",
|
|
58
|
+
"node": "none",
|
|
59
|
+
"browser": "none",
|
|
60
|
+
"nativescript": "none"
|
|
61
|
+
},
|
|
62
|
+
"runtimeSubpaths": {
|
|
63
|
+
"./wire": {
|
|
64
|
+
"gjs": "polyfill",
|
|
65
|
+
"node": "polyfill",
|
|
66
|
+
"browser": "polyfill",
|
|
67
|
+
"nativescript": "polyfill"
|
|
68
|
+
},
|
|
69
|
+
"./node-channel": {
|
|
70
|
+
"gjs": "polyfill",
|
|
71
|
+
"node": "partial",
|
|
72
|
+
"browser": "partial",
|
|
73
|
+
"nativescript": "partial"
|
|
74
|
+
}
|
|
75
|
+
},
|
|
76
|
+
"tier": 1
|
|
77
|
+
},
|
|
78
|
+
"license": "MIT",
|
|
79
|
+
"repository": {
|
|
80
|
+
"type": "git",
|
|
81
|
+
"url": "git+https://github.com/gjsify/gjsify.git",
|
|
82
|
+
"directory": "packages/gjs/ipc-channel"
|
|
83
|
+
},
|
|
84
|
+
"bugs": {
|
|
85
|
+
"url": "https://github.com/gjsify/gjsify/issues"
|
|
86
|
+
},
|
|
87
|
+
"homepage": "https://github.com/gjsify/gjsify/tree/main/packages/gjs/ipc-channel#readme"
|
|
88
|
+
}
|