@vielzeug/mesh 3.0.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.
Files changed (92) hide show
  1. package/README.md +50 -0
  2. package/dist/_base45.cjs +2 -0
  3. package/dist/_base45.cjs.map +1 -0
  4. package/dist/_base45.d.ts +3 -0
  5. package/dist/_base45.d.ts.map +1 -0
  6. package/dist/_base45.js +38 -0
  7. package/dist/_base45.js.map +1 -0
  8. package/dist/_base64.cjs +2 -0
  9. package/dist/_base64.cjs.map +1 -0
  10. package/dist/_base64.d.ts +9 -0
  11. package/dist/_base64.d.ts.map +1 -0
  12. package/dist/_base64.js +33 -0
  13. package/dist/_base64.js.map +1 -0
  14. package/dist/_node.cjs +2 -0
  15. package/dist/_node.cjs.map +1 -0
  16. package/dist/_node.d.ts +56 -0
  17. package/dist/_node.d.ts.map +1 -0
  18. package/dist/_node.js +195 -0
  19. package/dist/_node.js.map +1 -0
  20. package/dist/_proof.cjs +2 -0
  21. package/dist/_proof.cjs.map +1 -0
  22. package/dist/_proof.d.ts +11 -0
  23. package/dist/_proof.d.ts.map +1 -0
  24. package/dist/_proof.js +22 -0
  25. package/dist/_proof.js.map +1 -0
  26. package/dist/_random.cjs +2 -0
  27. package/dist/_random.cjs.map +1 -0
  28. package/dist/_random.d.ts +9 -0
  29. package/dist/_random.d.ts.map +1 -0
  30. package/dist/_random.js +16 -0
  31. package/dist/_random.js.map +1 -0
  32. package/dist/_rtc.cjs +4 -0
  33. package/dist/_rtc.cjs.map +1 -0
  34. package/dist/_rtc.d.ts +24 -0
  35. package/dist/_rtc.d.ts.map +1 -0
  36. package/dist/_rtc.js +42 -0
  37. package/dist/_rtc.js.map +1 -0
  38. package/dist/_sdp.cjs +3 -0
  39. package/dist/_sdp.cjs.map +1 -0
  40. package/dist/_sdp.d.ts +40 -0
  41. package/dist/_sdp.d.ts.map +1 -0
  42. package/dist/_sdp.js +55 -0
  43. package/dist/_sdp.js.map +1 -0
  44. package/dist/_wire.cjs +2 -0
  45. package/dist/_wire.cjs.map +1 -0
  46. package/dist/_wire.d.ts +20 -0
  47. package/dist/_wire.d.ts.map +1 -0
  48. package/dist/_wire.js +21 -0
  49. package/dist/_wire.js.map +1 -0
  50. package/dist/codec.cjs +2 -0
  51. package/dist/codec.cjs.map +1 -0
  52. package/dist/codec.d.ts +25 -0
  53. package/dist/codec.d.ts.map +1 -0
  54. package/dist/codec.js +35 -0
  55. package/dist/codec.js.map +1 -0
  56. package/dist/errors.cjs +2 -0
  57. package/dist/errors.cjs.map +1 -0
  58. package/dist/errors.d.ts +47 -0
  59. package/dist/errors.d.ts.map +1 -0
  60. package/dist/errors.js +19 -0
  61. package/dist/errors.js.map +1 -0
  62. package/dist/guest.cjs +2 -0
  63. package/dist/guest.cjs.map +1 -0
  64. package/dist/guest.d.ts +7 -0
  65. package/dist/guest.d.ts.map +1 -0
  66. package/dist/guest.js +165 -0
  67. package/dist/guest.js.map +1 -0
  68. package/dist/host.cjs +2 -0
  69. package/dist/host.cjs.map +1 -0
  70. package/dist/host.d.ts +7 -0
  71. package/dist/host.d.ts.map +1 -0
  72. package/dist/host.js +241 -0
  73. package/dist/host.js.map +1 -0
  74. package/dist/index.cjs +1 -0
  75. package/dist/index.d.ts +7 -0
  76. package/dist/index.d.ts.map +1 -0
  77. package/dist/index.js +6 -0
  78. package/dist/mesh.cjs +5 -0
  79. package/dist/mesh.cjs.map +1 -0
  80. package/dist/mesh.iife.js +5 -0
  81. package/dist/mesh.iife.js.map +1 -0
  82. package/dist/mesh.js +5 -0
  83. package/dist/mesh.js.map +1 -0
  84. package/dist/qr-codec.cjs +2 -0
  85. package/dist/qr-codec.cjs.map +1 -0
  86. package/dist/qr-codec.d.ts +8 -0
  87. package/dist/qr-codec.d.ts.map +1 -0
  88. package/dist/qr-codec.js +68 -0
  89. package/dist/qr-codec.js.map +1 -0
  90. package/dist/types.d.ts +300 -0
  91. package/dist/types.d.ts.map +1 -0
  92. package/package.json +50 -0
@@ -0,0 +1 @@
1
+ {"version":3,"file":"_rtc.cjs","names":[],"sources":["../src/_rtc.ts"],"sourcesContent":["import { MeshConnectionError, MeshDisposedError, MeshTimeoutError, MeshUnsupportedError } from './errors';\nimport type { MeshRtcFactory, RTCDataChannelLike, RTCPeerConnectionLike } from './types';\n\n/**\n * Wraps `globalThis.RTCPeerConnection`. Evaluated lazily at first use so\n * importing the package never throws in non-WebRTC environments.\n */\nexport const nativeRtcFactory: MeshRtcFactory = {\n createPeerConnection(config) {\n const Ctor = (globalThis as { RTCPeerConnection?: typeof RTCPeerConnection }).RTCPeerConnection;\n if (!Ctor) {\n throw new MeshUnsupportedError('WebRTC is unavailable in this environment — inject an `rtc` factory');\n }\n return new Ctor(config);\n },\n};\n\n/**\n * Textareas, clipboards, and share sheets normalize CRLF→LF;\n * `setRemoteDescription` requires CRLF line endings.\n */\nexport function normalizeSdp(sdp: string): string {\n const normalized = sdp.replace(/\\r?\\n/g, '\\r\\n');\n return normalized.endsWith('\\r\\n') ? normalized : `${normalized}\\r\\n`;\n}\n\n/**\n * Resolves `'complete'` when ICE gathering finishes, or `'timeout'` after\n * `timeoutMs` — the caller proceeds with whatever candidates were gathered\n * (non-trickle semantics).\n */\nexport function waitIceGathering(pc: RTCPeerConnectionLike, timeoutMs: number): Promise<'complete' | 'timeout'> {\n if (pc.iceGatheringState === 'complete') return Promise.resolve('complete');\n return new Promise((resolve) => {\n const cleanup = () => {\n clearTimeout(timer);\n pc.removeEventListener('icegatheringstatechange', onChange);\n };\n const onChange = () => {\n if (pc.iceGatheringState === 'complete') {\n cleanup();\n resolve('complete');\n }\n };\n const timer = setTimeout(() => {\n cleanup();\n resolve('timeout');\n }, timeoutMs);\n pc.addEventListener('icegatheringstatechange', onChange);\n });\n}\n\n/**\n * Resolves when the data channel opens. Rejects with `MeshTimeoutError` after\n * `timeoutMs`, `MeshConnectionError` when the channel or ICE transport dies\n * first, and `MeshDisposedError` when `disposalSignal` aborts.\n */\nexport function waitChannelOpen(\n dc: RTCDataChannelLike,\n pc: RTCPeerConnectionLike,\n timeoutMs: number,\n peerId: string,\n disposalSignal: AbortSignal,\n): Promise<void> {\n if (dc.readyState === 'open') return Promise.resolve();\n return new Promise((resolve, reject) => {\n const fail = (error: Error) => {\n cleanup();\n reject(error);\n };\n const cleanup = () => {\n clearTimeout(timer);\n dc.removeEventListener('open', onOpen);\n dc.removeEventListener('close', onClose);\n pc.removeEventListener('iceconnectionstatechange', onIce);\n disposalSignal.removeEventListener('abort', onDispose);\n };\n const onOpen = () => {\n cleanup();\n resolve();\n };\n const onClose = () => fail(new MeshConnectionError('Data channel closed before opening', peerId));\n const onIce = () => {\n const state = pc.iceConnectionState;\n if (state === 'failed' || state === 'closed' || state === 'disconnected') {\n fail(new MeshConnectionError(`ICE connection ${state} before channel open`, peerId));\n }\n };\n const onDispose = () => fail(new MeshDisposedError());\n const timer = setTimeout(\n () => fail(new MeshTimeoutError(`Timed out waiting ${timeoutMs}ms for the data channel to open`)),\n timeoutMs,\n );\n dc.addEventListener('open', onOpen);\n dc.addEventListener('close', onClose);\n pc.addEventListener('iceconnectionstatechange', onIce);\n disposalSignal.addEventListener('abort', onDispose, { once: true });\n });\n}\n"],"mappings":"gCAOA,IAAa,EAAmC,CAC9C,qBAAqB,EAAQ,CAC3B,IAAM,EAAQ,WAAgE,kBAC9E,GAAI,CAAC,EACH,MAAM,IAAI,EAAA,qBAAqB,qEAAqE,EAEtG,OAAO,IAAI,EAAK,CAAM,CACxB,CACF,EAMA,SAAgB,EAAa,EAAqB,CAChD,IAAM,EAAa,EAAI,QAAQ,SAAU;CAAM,EAC/C,OAAO,EAAW,SAAS;CAAM,EAAI,EAAa,GAAG,EAAW,KAClE,CAOA,SAAgB,EAAiB,EAA2B,EAAoD,CAE9G,OADI,EAAG,oBAAsB,WAAmB,QAAQ,QAAQ,UAAU,EACnE,IAAI,QAAS,GAAY,CAC9B,IAAM,MAAgB,CACpB,aAAa,CAAK,EAClB,EAAG,oBAAoB,0BAA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This.RTCPeerConnection`. Evaluated lazily at first use so
4
+ * importing the package never throws in non-WebRTC environments.
5
+ */
6
+ export declare const nativeRtcFactory: MeshRtcFactory;
7
+ /**
8
+ * Textareas, clipboards, and share sheets normalize CRLF→LF;
9
+ * `setRemoteDescription` requires CRLF line endings.
10
+ */
11
+ export declare function normalizeSdp(sdp: string): string;
12
+ /**
13
+ * Resolves `'complete'` when ICE gathering finishes, or `'timeout'` after
14
+ * `timeoutMs` — the caller proceeds with whatever candidates were gathered
15
+ * (non-trickle semantics).
16
+ */
17
+ export declare function waitIceGathering(pc: RTCPeerConnectionLike, timeoutMs: number): Promise<'complete' | 'timeout'>;
18
+ /**
19
+ * Resolves when the data channel opens. Rejects with `MeshTimeoutError` after
20
+ * `timeoutMs`, `MeshConnectionError` when the channel or ICE transport dies
21
+ * first, and `MeshDisposedError` when `disposalSignal` aborts.
22
+ */
23
+ export declare function waitChannelOpen(dc: RTCDataChannelLike, pc: RTCPeerConnectionLike, timeoutMs: number, peerId: string, disposalSignal: AbortSignal): Promise<void>;
24
+ //# sourceMappingURL=_rtc.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"_rtc.d.ts","sourceRoot":"","sources":["../src/_rtc.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,cAAc,EAAE,kBAAkB,EAAE,qBAAqB,EAAE,MAAM,SAAS,CAAC;AAEzF;;;GAGG;AACH,eAAO,MAAM,gBAAgB,EAAE,cAQ9B,CAAC;AAEF;;;GAGG;AACH,wBAAgB,YAAY,CAAC,GAAG,EAAE,MAAM,GAAG,MAAM,CAGhD;AAED;;;;GAIG;AACH,wBAAgB,gBAAgB,CAAC,EAAE,EAAE,qBAAqB,EAAE,SAAS,EAAE,MAAM,GAAG,OAAO,CAAC,UAAU,GAAG,SAAS,CAAC,CAmB9G;AAED;;;;GAIG;AACH,wBAAgB,eAAe,CAC7B,EAAE,EAAE,kBAAkB,EACtB,EAAE,EAAE,qBAAqB,EACzB,SAAS,EAAE,MAAM,EACjB,MAAM,EAAE,MAAM,EACd,cAAc,EAAE,WAAW,GAC1B,OAAO,CAAC,IAAI,CAAC,CAmCf"}
package/dist/_rtc.js ADDED
@@ -0,0 +1,42 @@
1
+ import { MeshConnectionError as e, MeshDisposedError as t, MeshTimeoutError as n, MeshUnsupportedError as r } from "./errors.js";
2
+ //#region src/_rtc.ts
3
+ var i = { createPeerConnection(e) {
4
+ let t = globalThis.RTCPeerConnection;
5
+ if (!t) throw new r("WebRTC is unavailable in this environment — inject an `rtc` factory");
6
+ return new t(e);
7
+ } };
8
+ function a(e) {
9
+ let t = e.replace(/\r?\n/g, "\r\n");
10
+ return t.endsWith("\r\n") ? t : `${t}\r\n`;
11
+ }
12
+ function o(e, t) {
13
+ return e.iceGatheringState === "complete" ? Promise.resolve("complete") : new Promise((n) => {
14
+ let r = () => {
15
+ clearTimeout(a), e.removeEventListener("icegatheringstatechange", i);
16
+ }, i = () => {
17
+ e.iceGatheringState === "complete" && (r(), n("complete"));
18
+ }, a = setTimeout(() => {
19
+ r(), n("timeout");
20
+ }, t);
21
+ e.addEventListener("icegatheringstatechange", i);
22
+ });
23
+ }
24
+ function s(r, i, a, o, s) {
25
+ return r.readyState === "open" ? Promise.resolve() : new Promise((c, l) => {
26
+ let u = (e) => {
27
+ d(), l(e);
28
+ }, d = () => {
29
+ clearTimeout(g), r.removeEventListener("open", f), r.removeEventListener("close", p), i.removeEventListener("iceconnectionstatechange", m), s.removeEventListener("abort", h);
30
+ }, f = () => {
31
+ d(), c();
32
+ }, p = () => u(new e("Data channel closed before opening", o)), m = () => {
33
+ let t = i.iceConnectionState;
34
+ (t === "failed" || t === "closed" || t === "disconnected") && u(new e(`ICE connection ${t} before channel open`, o));
35
+ }, h = () => u(new t()), g = setTimeout(() => u(new n(`Timed out waiting ${a}ms for the data channel to open`)), a);
36
+ r.addEventListener("open", f), r.addEventListener("close", p), i.addEventListener("iceconnectionstatechange", m), s.addEventListener("abort", h, { once: !0 });
37
+ });
38
+ }
39
+ //#endregion
40
+ export { i as nativeRtcFactory, a as normalizeSdp, s as waitChannelOpen, o as waitIceGathering };
41
+
42
+ //# sourceMappingURL=_rtc.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"_rtc.js","names":[],"sources":["../src/_rtc.ts"],"sourcesContent":["import { MeshConnectionError, MeshDisposedError, MeshTimeoutError, MeshUnsupportedError } from './errors';\nimport type { MeshRtcFactory, RTCDataChannelLike, RTCPeerConnectionLike } from './types';\n\n/**\n * Wraps `globalThis.RTCPeerConnection`. Evaluated lazily at first use so\n * importing the package never throws in non-WebRTC environments.\n */\nexport const nativeRtcFactory: MeshRtcFactory = {\n createPeerConnection(config) {\n const Ctor = (globalThis as { RTCPeerConnection?: typeof RTCPeerConnection }).RTCPeerConnection;\n if (!Ctor) {\n throw new MeshUnsupportedError('WebRTC is unavailable in this environment — inject an `rtc` factory');\n }\n return new Ctor(config);\n },\n};\n\n/**\n * Textareas, clipboards, and share sheets normalize CRLF→LF;\n * `setRemoteDescription` requires CRLF line endings.\n */\nexport function normalizeSdp(sdp: string): string {\n const normalized = sdp.replace(/\\r?\\n/g, '\\r\\n');\n return normalized.endsWith('\\r\\n') ? normalized : `${normalized}\\r\\n`;\n}\n\n/**\n * Resolves `'complete'` when ICE gathering finishes, or `'timeout'` after\n * `timeoutMs` — the caller proceeds with whatever candidates were gathered\n * (non-trickle semantics).\n */\nexport function waitIceGathering(pc: RTCPeerConnectionLike, timeoutMs: number): Promise<'complete' | 'timeout'> {\n if (pc.iceGatheringState === 'complete') return Promise.resolve('complete');\n return new Promise((resolve) => {\n const cleanup = () => {\n clearTimeout(timer);\n pc.removeEventListener('icegatheringstatechange', onChange);\n };\n const onChange = () => {\n if (pc.iceGatheringState === 'complete') {\n cleanup();\n resolve('complete');\n }\n };\n const timer = setTimeout(() => {\n cleanup();\n resolve('timeout');\n }, timeoutMs);\n pc.addEventListener('icegatheringstatechange', onChange);\n });\n}\n\n/**\n * Resolves when the data channel opens. Rejects with `MeshTimeoutError` after\n * `timeoutMs`, `MeshConnectionError` when the channel or ICE transport dies\n * first, and `MeshDisposedError` when `disposalSignal` aborts.\n */\nexport function waitChannelOpen(\n dc: RTCDataChannelLike,\n pc: RTCPeerConnectionLike,\n timeoutMs: number,\n peerId: string,\n disposalSignal: AbortSignal,\n): Promise<void> {\n if (dc.readyState === 'open') return Promise.resolve();\n return new Promise((resolve, reject) => {\n const fail = (error: Error) => {\n cleanup();\n reject(error);\n };\n const cleanup = () => {\n clearTimeout(timer);\n dc.removeEventListener('open', onOpen);\n dc.removeEventListener('close', onClose);\n pc.removeEventListener('iceconnectionstatechange', onIce);\n disposalSignal.removeEventListener('abort', onDispose);\n };\n const onOpen = () => {\n cleanup();\n resolve();\n };\n const onClose = () => fail(new MeshConnectionError('Data channel closed before opening', peerId));\n const onIce = () => {\n const state = pc.iceConnectionState;\n if (state === 'failed' || state === 'closed' || state === 'disconnected') {\n fail(new MeshConnectionError(`ICE connection ${state} before channel open`, peerId));\n }\n };\n const onDispose = () => fail(new MeshDisposedError());\n const timer = setTimeout(\n () => fail(new MeshTimeoutError(`Timed out waiting ${timeoutMs}ms for the data channel to open`)),\n timeoutMs,\n );\n dc.addEventListener('open', onOpen);\n dc.addEventListener('close', onClose);\n pc.addEventListener('iceconnectionstatechange', onIce);\n disposalSignal.addEventListener('abort', onDispose, { once: true });\n });\n}\n"],"mappings":";;AAOA,IAAa,IAAmC,EAC9C,qBAAqB,GAAQ;CAC3B,IAAM,IAAQ,WAAgE;CAC9E,IAAI,CAAC,GACH,MAAM,IAAI,EAAqB,qEAAqE;CAEtG,OAAO,IAAI,EAAK,CAAM;AACxB,EACF;AAMA,SAAgB,EAAa,GAAqB;CAChD,IAAM,IAAa,EAAI,QAAQ,UAAU,MAAM;CAC/C,OAAO,EAAW,SAAS,MAAM,IAAI,IAAa,GAAG,EAAW;AAClE;AAOA,SAAgB,EAAiB,GAA2B,GAAoD;CAE9G,OADI,EAAG,sBAAsB,aAAmB,QAAQ,Q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AACH"}
package/dist/_sdp.cjs ADDED
@@ -0,0 +1,3 @@
1
+ const e=require("./errors.cjs");function t(e){if(typeof e!=`object`||!e)return!1;let t=e;return typeof t.u==`string`&&typeof t.p==`string`&&typeof t.f==`string`&&typeof t.s==`string`&&typeof t.m==`string`&&Array.isArray(t.c)&&t.c.every(e=>typeof e==`string`)}function n(n){if(typeof n==`string`)return n;if(t(n))return a(n);throw new e.MeshPairingError(`Malformed pairing payload`)}function r(e){let t=``,n=``,r=``,i=``,a=`0`,o,s,c=[],l=0;for(let u of e.split(/\r?\n/))u.startsWith(`m=`)?l+=1:u.startsWith(`a=ice-ufrag:`)?t=u.slice(12):u.startsWith(`a=ice-pwd:`)?n=u.slice(10):u.startsWith(`a=fingerprint:sha-256 `)?r=u.slice(22).replaceAll(`:`,``).toUpperCase():u.startsWith(`a=setup:`)?i=u.slice(8):u.startsWith(`a=mid:`)?a=u.slice(6):u.startsWith(`a=sctp-port:`)?o=Number(u.slice(12)):u.startsWith(`a=max-message-size:`)?s=Number(u.slice(19)):u.startsWith(`a=candidate:`)&&c.push(u.slice(12));return l!==1||!t||!n||!r?null:{c,f:r,m:a,p:n,s:i||`actpass`,...s?{mm:s}:{},...o?{sp:o}:{},u:t}}function i(e){let t=r(e);return t?JSON.stringify(t):e}function a(e){let t=e.f.replace(/(..)/g,`$1:`).slice(0,-1);return`${[`v=0`,`o=- 0 2 IN IP4 0.0.0.0`,`s=-`,`t=0 0`,`a=group:BUNDLE ${e.m}`,`m=application 9 UDP/DTLS/SCTP webrtc-datachannel`,`c=IN IP4 0.0.0.0`,`a=ice-ufrag:${e.u}`,`a=ice-pwd:${e.p}`,`a=fingerprint:sha-256 ${t}`,`a=setup:${e.s}`,`a=mid:${e.m}`,`a=sctp-port:${e.sp??5e3}`,...e.mm?[`a=max-message-size:${e.mm}`]:[],...e.c.map(e=>`a=candidate:${e}`),``].join(`\r
2
+ `)}`}exports.canonicalSdp=i,exports.compactSdp=r,exports.expandSdp=a,exports.restoreSdp=n;
3
+ //# sourceMappingURL=_sdp.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"_sdp.cjs","names":[],"sources":["../src/_sdp.ts"],"sourcesContent":["import { MeshPairingError } from './errors';\n\n/**\n * Compact SDP serialization for pairing payloads. A data-channel-only\n * SDP is mostly boilerplate; the remote side only needs the ICE credentials,\n * DTLS fingerprint, setup role, mid, and candidates. `compactSdp` extracts\n * those fields and `expandSdp` rebuilds a minimal valid SDP for\n * `setRemoteDescription`.\n *\n * `compactSdp` returns `null` for shapes it cannot safely represent\n * (multiple m-lines, missing credentials), letting callers keep the raw SDP.\n */\n\nexport interface CompactSdp {\n /** `a=candidate:` lines, prefix stripped. */\n c: string[];\n /** sha-256 fingerprint, hex without colons. */\n f: string;\n /** `a=mid`. */\n m: string;\n /** `a=max-message-size`. */\n mm?: number;\n /** `a=ice-pwd`. */\n p: string;\n /** `a=setup` role. */\n s: string;\n /** `a=sctp-port`. */\n sp?: number;\n /** `a=ice-ufrag`. */\n u: string;\n}\n\nfunction isCompactSdp(value: unknown): value is CompactSdp {\n if (typeof value !== 'object' || value === null) return false;\n const c = value as Record<string, unknown>;\n return (\n typeof c.u === 'string' &&\n typeof c.p === 'string' &&\n typeof c.f === 'string' &&\n typeof c.s === 'string' &&\n typeof c.m === 'string' &&\n Array.isArray(c.c) &&\n c.c.every((line) => typeof line === 'string')\n );\n}\n\n/** Returns the expanded SDP unchanged when `value` is already a string. */\nexport function restoreSdp(value: unknown): string {\n if (typeof value === 'string') return value;\n if (isCompactSdp(value)) return expandSdp(value);\n throw new MeshPairingError('Malformed pairing payload');\n}\n\nexport function compactSdp(sdp: string): CompactSdp | null {\n let ufrag = '';\n let pwd = '';\n let fingerprint = '';\n let setup = '';\n let mid = '0';\n let sctpPort: number | undefined;\n let maxMessageSize: number | undefined;\n const candidates: string[] = [];\n let mLines = 0;\n\n for (const line of sdp.split(/\\r?\\n/)) {\n if (line.startsWith('m=')) mLines += 1;\n else if (line.startsWith('a=ice-ufrag:')) ufrag = line.slice(12);\n else if (line.startsWith('a=ice-pwd:')) pwd = line.slice(10);\n else if (line.startsWith('a=fingerprint:sha-256 ')) fingerprint = line.slice(22).replaceAll(':', '').toUpperCase();\n else if (line.startsWith('a=setup:')) setup = line.slice(8);\n else if (line.startsWith('a=mid:')) mid = line.slice(6);\n else if (line.startsWith('a=sctp-port:')) sctpPort = Number(line.slice(12));\n else if (line.startsWith('a=max-message-size:')) maxMessageSize = Number(line.slice(19));\n else if (line.startsWith('a=candidate:')) candidates.push(line.slice(12));\n }\n\n if (mLines !== 1 || !ufrag || !pwd || !fingerprint) return null;\n return {\n c: candidates,\n f: fingerprint,\n m: mid,\n p: pwd,\n s: setup || 'actpass',\n ...(maxMessageSize ? { mm: maxMessageSize } : {}),\n ...(sctpPort ? { sp: sctpPort } : {}),\n u: ufrag,\n };\n}\n\n/**\n * Canonical signing form: the compact serialization when the SDP is\n * recognizable, else the raw text. `compactSdp` is lossless over the fields\n * it keeps, so the rebuilt `mq2.` SDP canonicalizes identically to the\n * original — a proof computed over one verifies against the other.\n */\nexport function canonicalSdp(sdp: string): string {\n const compact = compactSdp(sdp);\n return compact ? JSON.stringify(compact) : sdp;\n}\n\nexport function expandSdp(compact: CompactSdp): string {\n const colonHex = compact.f.replace(/(..)/g, '$1:').slice(0, -1);\n return `${[\n 'v=0',\n 'o=- 0 2 IN IP4 0.0.0.0',\n 's=-',\n 't=0 0',\n `a=group:BUNDLE ${compact.m}`,\n 'm=application 9 UDP/DTLS/SCTP webrtc-datachannel',\n 'c=IN IP4 0.0.0.0',\n `a=ice-ufrag:${compact.u}`,\n `a=ice-pwd:${compact.p}`,\n `a=fingerprint:sha-256 ${colonHex}`,\n `a=setup:${compact.s}`,\n `a=mid:${compact.m}`,\n `a=sctp-port:${compact.sp ?? 5000}`,\n ...(compact.mm ? [`a=max-message-size:${compact.mm}`] : []),\n ...compact.c.map((line) => `a=candidate:${line}`),\n '',\n ].join('\\r\\n')}`;\n}\n"],"mapp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AS,CAAC,GAAO,CAAC,EAAoB,KACpD,CACF,EACH,EAAG,EACH,EAAG,EACH,EAAG,EACH,EAAG,GAAS,UACZ,GAAI,EAAiB,CAAE,GAAI,CAAe,EAAI,CAAC,EAC/C,GAAI,EAAW,CAAE,GAAI,CAAS,EAAI,CAAC,EACnC,EAAG,CACL,CACF,CAQA,SAAgB,EAAa,EAAqB,CAChD,IAAM,EAAU,EAAW,CAAG,EAC9B,OAAO,EAAU,KAAK,UAAU,CAAO,EAAI,CAC7C,CAEA,SAAgB,EAAU,EAA6B,CACrD,IAAM,EAAW,EAAQ,EAAE,QAAQ,QAAS,KAAK,CAAC,CAAC,MAAM,EAAG,EAAE,EAC9D,MAAO,GAAG,CACR,MACA,yBACA,MACA,QACA,kBAAkB,EAAQ,IAC1B,mDACA,mBACA,eAAe,EAAQ,IACvB,aAAa,EAAQ,IACrB,yBAAyB,IACzB,WAAW,EAAQ,IACnB,SAAS,EAAQ,IACjB,eAAe,EAAQ,IAAM,MAC7B,GAAI,EAAQ,GAAK,CAAC,sBAAsB,EAAQ,IAAI,EAAI,CAAC,EACzD,GAAG,EAAQ,EAAE,IAAK,GAAS,eAAe,GAAM,EAChD,EACF,CAAC,CAAC,KAAK;CAAM,GACf"}
package/dist/_sdp.d.ts ADDED
@@ -0,0 +1,40 @@
1
+ /**
2
+ * Compact SDP serialization for pairing payloads. A data-channel-only
3
+ * SDP is mostly boilerplate; the remote side only needs the ICE credentials,
4
+ * DTLS fingerprint, setup role, mid, and candidates. `compactSdp` extracts
5
+ * those fields and `expandSdp` rebuilds a minimal valid SDP for
6
+ * `setRemoteDescription`.
7
+ *
8
+ * `compactSdp` returns `null` for shapes it cannot safely represent
9
+ * (multiple m-lines, missing credentials), letting callers keep the raw SDP.
10
+ */
11
+ export interface CompactSdp {
12
+ /** `a=candidate:` lines, prefix stripped. */
13
+ c: string[];
14
+ /** sha-256 fingerprint, hex without colons. */
15
+ f: string;
16
+ /** `a=mid`. */
17
+ m: string;
18
+ /** `a=max-message-size`. */
19
+ mm?: number;
20
+ /** `a=ice-pwd`. */
21
+ p: string;
22
+ /** `a=setup` role. */
23
+ s: string;
24
+ /** `a=sctp-port`. */
25
+ sp?: number;
26
+ /** `a=ice-ufrag`. */
27
+ u: string;
28
+ }
29
+ /** Returns the expanded SDP unchanged when `value` is already a string. */
30
+ export declare function restoreSdp(value: unknown): string;
31
+ export declare function compactSdp(sdp: string): CompactSdp | null;
32
+ /**
33
+ * Canonical signing form: the compact serialization when the SDP is
34
+ * recognizable, else the raw text. `compactSdp` is lossless over the fields
35
+ * it keeps, so the rebuilt `mq2.` SDP canonicalizes identically to the
36
+ * original — a proof computed over one verifies against the other.
37
+ */
38
+ export declare function canonicalSdp(sdp: string): string;
39
+ export declare function expandSdp(compact: CompactSdp): string;
40
+ //# sourceMappingURL=_sdp.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"_sdp.d.ts","sourceRoot":"","sources":["../src/_sdp.ts"],"names":[],"mappings":"AAEA;;;;;;;;;GASG;AAEH,MAAM,WAAW,UAAU;IACzB,6CAA6C;IAC7C,CAAC,EAAE,MAAM,EAAE,CAAC;IACZ,+CAA+C;IAC/C,CAAC,EAAE,MAAM,CAAC;IACV,eAAe;IACf,CAAC,EAAE,MAAM,CAAC;IACV,4BAA4B;IAC5B,EAAE,CAAC,EAAE,MAAM,CAAC;IACZ,mBAAmB;IACnB,CAAC,EAAE,MAAM,CAAC;IACV,sBAAsB;IACtB,CAAC,EAAE,MAAM,CAAC;IACV,qBAAqB;IACrB,EAAE,CAAC,EAAE,MAAM,CAAC;IACZ,qBAAqB;IACrB,CAAC,EAAE,MAAM,CAAC;CACX;AAgBD,2EAA2E;AAC3E,wBAAgB,UAAU,CAAC,KAAK,EAAE,OAAO,GAAG,MAAM,CAIjD;AAED,wBAAgB,UAAU,CAAC,GAAG,EAAE,MAAM,GAAG,UAAU,GAAG,IAAI,CAkCzD;AAED;;;;;GAKG;AACH,wBAAgB,YAAY,CAAC,GAAG,EAAE,MAAM,GAAG,MAAM,CAGhD;AAED,wBAAgB,SAAS,CAAC,OAAO,EAAE,UAAU,GAAG,MAAM,CAoBrD"}
package/dist/_sdp.js ADDED
@@ -0,0 +1,55 @@
1
+ import { MeshPairingError as e } from "./errors.js";
2
+ //#region src/_sdp.ts
3
+ function t(e) {
4
+ if (typeof e != "object" || !e) return !1;
5
+ let t = e;
6
+ return typeof t.u == "string" && typeof t.p == "string" && typeof t.f == "string" && typeof t.s == "string" && typeof t.m == "string" && Array.isArray(t.c) && t.c.every((e) => typeof e == "string");
7
+ }
8
+ function n(n) {
9
+ if (typeof n == "string") return n;
10
+ if (t(n)) return a(n);
11
+ throw new e("Malformed pairing payload");
12
+ }
13
+ function r(e) {
14
+ let t = "", n = "", r = "", i = "", a = "0", o, s, c = [], l = 0;
15
+ for (let u of e.split(/\r?\n/)) u.startsWith("m=") ? l += 1 : u.startsWith("a=ice-ufrag:") ? t = u.slice(12) : u.startsWith("a=ice-pwd:") ? n = u.slice(10) : u.startsWith("a=fingerprint:sha-256 ") ? r = u.slice(22).replaceAll(":", "").toUpperCase() : u.startsWith("a=setup:") ? i = u.slice(8) : u.startsWith("a=mid:") ? a = u.slice(6) : u.startsWith("a=sctp-port:") ? o = Number(u.slice(12)) : u.startsWith("a=max-message-size:") ? s = Number(u.slice(19)) : u.startsWith("a=candidate:") && c.push(u.slice(12));
16
+ return l !== 1 || !t || !n || !r ? null : {
17
+ c,
18
+ f: r,
19
+ m: a,
20
+ p: n,
21
+ s: i || "actpass",
22
+ ...s ? { mm: s } : {},
23
+ ...o ? { sp: o } : {},
24
+ u: t
25
+ };
26
+ }
27
+ function i(e) {
28
+ let t = r(e);
29
+ return t ? JSON.stringify(t) : e;
30
+ }
31
+ function a(e) {
32
+ let t = e.f.replace(/(..)/g, "$1:").slice(0, -1);
33
+ return `${[
34
+ "v=0",
35
+ "o=- 0 2 IN IP4 0.0.0.0",
36
+ "s=-",
37
+ "t=0 0",
38
+ `a=group:BUNDLE ${e.m}`,
39
+ "m=application 9 UDP/DTLS/SCTP webrtc-datachannel",
40
+ "c=IN IP4 0.0.0.0",
41
+ `a=ice-ufrag:${e.u}`,
42
+ `a=ice-pwd:${e.p}`,
43
+ `a=fingerprint:sha-256 ${t}`,
44
+ `a=setup:${e.s}`,
45
+ `a=mid:${e.m}`,
46
+ `a=sctp-port:${e.sp ?? 5e3}`,
47
+ ...e.mm ? [`a=max-message-size:${e.mm}`] : [],
48
+ ...e.c.map((e) => `a=candidate:${e}`),
49
+ ""
50
+ ].join("\r\n")}`;
51
+ }
52
+ //#endregion
53
+ export { i as canonicalSdp, r as compactSdp, a as expandSdp, n as restoreSdp };
54
+
55
+ //# sourceMappingURL=_sdp.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"_sdp.js","names":[],"sources":["../src/_sdp.ts"],"sourcesContent":["import { MeshPairingError } from './errors';\n\n/**\n * Compact SDP serialization for pairing payloads. A data-channel-only\n * SDP is mostly boilerplate; the remote side only needs the ICE credentials,\n * DTLS fingerprint, setup role, mid, and candidates. `compactSdp` extracts\n * those fields and `expandSdp` rebuilds a minimal valid SDP for\n * `setRemoteDescription`.\n *\n * `compactSdp` returns `null` for shapes it cannot safely represent\n * (multiple m-lines, missing credentials), letting callers keep the raw SDP.\n */\n\nexport interface CompactSdp {\n /** `a=candidate:` lines, prefix stripped. */\n c: string[];\n /** sha-256 fingerprint, hex without colons. */\n f: string;\n /** `a=mid`. */\n m: string;\n /** `a=max-message-size`. */\n mm?: number;\n /** `a=ice-pwd`. */\n p: string;\n /** `a=setup` role. */\n s: string;\n /** `a=sctp-port`. */\n sp?: number;\n /** `a=ice-ufrag`. */\n u: string;\n}\n\nfunction isCompactSdp(value: unknown): value is CompactSdp {\n if (typeof value !== 'object' || value === null) return false;\n const c = value as Record<string, unknown>;\n return (\n typeof c.u === 'string' &&\n typeof c.p === 'string' &&\n typeof c.f === 'string' &&\n typeof c.s === 'string' &&\n typeof c.m === 'string' &&\n Array.isArray(c.c) &&\n c.c.every((line) => typeof line === 'string')\n );\n}\n\n/** Returns the expanded SDP unchanged when `value` is already a string. */\nexport function restoreSdp(value: unknown): string {\n if (typeof value === 'string') return value;\n if (isCompactSdp(value)) return expandSdp(value);\n throw new MeshPairingError('Malformed pairing payload');\n}\n\nexport function compactSdp(sdp: string): CompactSdp | null {\n let ufrag = '';\n let pwd = '';\n let fingerprint = '';\n let setup = '';\n let mid = '0';\n let sctpPort: number | undefined;\n let maxMessageSize: number | undefined;\n const candidates: string[] = [];\n let mLines = 0;\n\n for (const line of sdp.split(/\\r?\\n/)) {\n if (line.startsWith('m=')) mLines += 1;\n else if (line.startsWith('a=ice-ufrag:')) ufrag = line.slice(12);\n else if (line.startsWith('a=ice-pwd:')) pwd = line.slice(10);\n else if (line.startsWith('a=fingerprint:sha-256 ')) fingerprint = line.slice(22).replaceAll(':', '').toUpperCase();\n else if (line.startsWith('a=setup:')) setup = line.slice(8);\n else if (line.startsWith('a=mid:')) mid = line.slice(6);\n else if (line.startsWith('a=sctp-port:')) sctpPort = Number(line.slice(12));\n else if (line.startsWith('a=max-message-size:')) maxMessageSize = Number(line.slice(19));\n else if (line.startsWith('a=candidate:')) candidates.push(line.slice(12));\n }\n\n if (mLines !== 1 || !ufrag || !pwd || !fingerprint) return null;\n return {\n c: candidates,\n f: fingerprint,\n m: mid,\n p: pwd,\n s: setup || 'actpass',\n ...(maxMessageSize ? { mm: maxMessageSize } : {}),\n ...(sctpPort ? { sp: sctpPort } : {}),\n u: ufrag,\n };\n}\n\n/**\n * Canonical signing form: the compact serialization when the SDP is\n * recognizable, else the raw text. `compactSdp` is lossless over the fields\n * it keeps, so the rebuilt `mq2.` SDP canonicalizes identically to the\n * original — a proof computed over one verifies against the other.\n */\nexport function canonicalSdp(sdp: string): string {\n const compact = compactSdp(sdp);\n return compact ? JSON.stringify(compact) : sdp;\n}\n\nexport function expandSdp(compact: CompactSdp): string {\n const colonHex = compact.f.replace(/(..)/g, '$1:').slice(0, -1);\n return `${[\n 'v=0',\n 'o=- 0 2 IN IP4 0.0.0.0',\n 's=-',\n 't=0 0',\n `a=group:BUNDLE ${compact.m}`,\n 'm=application 9 UDP/DTLS/SCTP webrtc-datachannel',\n 'c=IN IP4 0.0.0.0',\n `a=ice-ufrag:${compact.u}`,\n `a=ice-pwd:${compact.p}`,\n `a=fingerprint:sha-256 ${colonHex}`,\n `a=setup:${compact.s}`,\n `a=mid:${compact.m}`,\n `a=sctp-port:${compact.sp ?? 5000}`,\n ...(compact.mm ? [`a=max-message-size:${compact.mm}`] : []),\n ...compact.c.map((line) => `a=candidate:${line}`),\n '',\n ].join('\\r\\n')}`;\n}\n"],"mappings":";;AAgCA,SAAS,EAAa,GAAqC;CACzD,IAAI,OAAO,KAAU,aAAY,GAAgB,OAAO;CACxD,IAAM,IAAI;CACV,OACE,OAAO,EAAE,KAAM,YACf,OAAO,EAAE,KAAM,YACf,OAAO,EAAE,KAAM,YACf,OAAO,EAAE,KAAM,YACf,OAAO,EAAE,KAAM,YACf,MAAM,QAAQ,EAAE,CAAC,KACjB,EAAE,EAAE,OAAO,MAAS,OAAO,KAAS,QAAQ;AAEhD;AAGA,SAAgB,EAAW,GAAwB;CACjD,IAAI,OAAO,KAAU,UAAU,OAAO;CACtC,IAAI,EAAa,CAAK,GAAG,OAAO,EAAU,CAAK;CAC/C,MAAM,IAAI,EAAiB,2BAA2B;AACxD;AAEA,SAAgB,EAAW,GAAgC;CACzD,IAAI,IAAQ,IACR,IAAM,IACN,IAAc,IACd,IAAQ,IACR,IAAM,KACN,GACA,GACE,IAAuB,CAAC,GAC1B,IAAS;CAEb,KAAK,IAAM,KAAQ,EAAI,MAAM,OAAO,GAClC,AAAI,EAAK,WAAW,IAAI,IAAG,KAAU,IAC5B,EAAK,WAAW,cAAc,IAAG,IAAQ,EAAK,MAAM,EAAE,IACtD,EAAK,WAAW,YAAY,IAAG,IAAM,EAAK,MAAM,EAAE,IAClD,EAAK,WAAW,wBAAwB,IAAG,IAAc,EAAK,MA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=`object`||!e)return null;let t=e;return t.v!==1||typeof t.id!=`string`||typeof t.t!=`string`||typeof t.ts!=`number`?null:e}var t=class{seen=new Set;order=[];capacity;constructor(e=256){this.capacity=e}check(e){return!this.seen.has(e)&&(this.seen.add(e),this.order.push(e),this.order.length>this.capacity&&this.seen.delete(this.order.shift()),!0)}};exports.MessageDedupe=t,exports.toEnvelope=e;
2
+ //# sourceMappingURL=_wire.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"_wire.cjs","names":[],"sources":["../src/_wire.ts"],"sourcesContent":["/** Wire envelope serialized through the configured `serialize` function. */\nexport interface WireEnvelope {\n readonly id: string;\n readonly p: unknown;\n readonly t: string;\n readonly ts: number;\n readonly v: 1;\n}\n\n/** Returns the envelope, or `null` when the value violates the wire shape. */\nexport function toEnvelope(value: unknown): WireEnvelope | null {\n if (typeof value !== 'object' || value === null) return null;\n const env = value as Record<string, unknown>;\n if (env.v !== 1 || typeof env.id !== 'string' || typeof env.t !== 'string' || typeof env.ts !== 'number') return null;\n return value as WireEnvelope;\n}\n\n/** Per-peer duplicate guard: remembers the last `capacity` message ids (LRU). */\nexport class MessageDedupe {\n private readonly seen = new Set<string>();\n private readonly order: string[] = [];\n private readonly capacity: number;\n\n constructor(capacity = 256) {\n this.capacity = capacity;\n }\n\n /** `true` when the id is new (and records it); `false` for duplicates. */\n check(id: string): boolean {\n if (this.seen.has(id)) return false;\n this.seen.add(id);\n this.order.push(id);\n if (this.order.length > this.capacity) this.seen.delete(this.order.shift()!);\n return true;\n }\n}\n"],"mappings":"AAUA,SAAgB,EAAW,EAAqC,CAC9D,GAAI,OAAO,GAAU,WAAY,EAAgB,OAAO,KACxD,IAAM,EAAM,EAEZ,OADI,EAAI,IAAM,GAAK,OAAO,EAAI,IAAO,UAAY,OAAO,EAAI,GAAM,UAAY,OAAO,EAAI,IAAO,SAAiB,KAC1G,CACT,CAGA,IAAa,EAAb,KAA2B,CACzB,KAAwB,IAAI,IAC5B,MAAmC,CAAC,EACpC,SAEA,YAAY,EAAW,IAAK,CAC1B,KAAK,SAAW,CAClB,CAGA,MAAM,EAAqB,CAKzB,MAJA,CAAI,KAAK,KAAK,IAAI,CAAE,IACpB,KAAK,KAAK,IAAI,CAAE,EAChB,KAAK,MAAM,KAAK,CAAE,EACd,KAAK,MAAM,OAAS,KAAK,UAAU,KAAK,KAAK,OAAO,KAAK,MAAM,MAAM,CAAE,EACpE,GACT,CACF"}
@@ -0,0 +1,20 @@
1
+ /** Wire envelope serialized through the configured `serialize` function. */
2
+ export interface WireEnvelope {
3
+ readonly id: string;
4
+ readonly p: unknown;
5
+ readonly t: string;
6
+ readonly ts: number;
7
+ readonly v: 1;
8
+ }
9
+ /** Returns the envelope, or `null` when the value violates the wire shape. */
10
+ export declare function toEnvelope(value: unknown): WireEnvelope | null;
11
+ /** Per-peer duplicate guard: remembers the last `capacity` message ids (LRU). */
12
+ export declare class MessageDedupe {
13
+ private readonly seen;
14
+ private readonly order;
15
+ private readonly capacity;
16
+ constructor(capacity?: number);
17
+ /** `true` when the id is new (and records it); `false` for duplicates. */
18
+ check(id: string): boolean;
19
+ }
20
+ //# sourceMappingURL=_wire.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"_wire.d.ts","sourceRoot":"","sources":["../src/_wire.ts"],"names":[],"mappings":"AAAA,4EAA4E;AAC5E,MAAM,WAAW,YAAY;IAC3B,QAAQ,CAAC,EAAE,EAAE,MAAM,CAAC;IACpB,QAAQ,CAAC,CAAC,EAAE,OAAO,CAAC;IACpB,QAAQ,CAAC,CAAC,EAAE,MAAM,CAAC;IACnB,QAAQ,CAAC,EAAE,EAAE,MAAM,CAAC;IACpB,QAAQ,CAAC,CAAC,EAAE,CAAC,CAAC;CACf;AAED,8EAA8E;AAC9E,wBAAgB,UAAU,CAAC,KAAK,EAAE,OAAO,GAAG,YAAY,GAAG,IAAI,CAK9D;AAED,iFAAiF;AACjF,qBAAa,aAAa;IACxB,OAAO,CAAC,QAAQ,CAAC,IAAI,CAAqB;IAC1C,OAAO,CAAC,QAAQ,CAAC,KAAK,CAAgB;IACtC,OAAO,CAAC,QAAQ,CAAC,QAAQ,CAAS;gBAEtB,QAAQ,SAAM;IAI1B,0EAA0E;IAC1E,KAAK,CAAC,EAAE,EAAE,MAAM,GAAG,OAAO;CAO3B"}
package/dist/_wire.js ADDED
@@ -0,0 +1,21 @@
1
+ //#region src/_wire.ts
2
+ function e(e) {
3
+ if (typeof e != "object" || !e) return null;
4
+ let t = e;
5
+ return t.v !== 1 || typeof t.id != "string" || typeof t.t != "string" || typeof t.ts != "number" ? null : e;
6
+ }
7
+ var t = class {
8
+ seen = /* @__PURE__ */ new Set();
9
+ order = [];
10
+ capacity;
11
+ constructor(e = 256) {
12
+ this.capacity = e;
13
+ }
14
+ check(e) {
15
+ return !this.seen.has(e) && (this.seen.add(e), this.order.push(e), this.order.length > this.capacity && this.seen.delete(this.order.shift()), !0);
16
+ }
17
+ };
18
+ //#endregion
19
+ export { t as MessageDedupe, e as toEnvelope };
20
+
21
+ //# sourceMappingURL=_wire.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"_wire.js","names":[],"sources":["../src/_wire.ts"],"sourcesContent":["/** Wire envelope serialized through the configured `serialize` function. */\nexport interface WireEnvelope {\n readonly id: string;\n readonly p: unknown;\n readonly t: string;\n readonly ts: number;\n readonly v: 1;\n}\n\n/** Returns the envelope, or `null` when the value violates the wire shape. */\nexport function toEnvelope(value: unknown): WireEnvelope | null {\n if (typeof value !== 'object' || value === null) return null;\n const env = value as Record<string, unknown>;\n if (env.v !== 1 || typeof env.id !== 'string' || typeof env.t !== 'string' || typeof env.ts !== 'number') return null;\n return value as WireEnvelope;\n}\n\n/** Per-peer duplicate guard: remembers the last `capacity` message ids (LRU). */\nexport class MessageDedupe {\n private readonly seen = new Set<string>();\n private readonly order: string[] = [];\n private readonly capacity: number;\n\n constructor(capacity = 256) {\n this.capacity = capacity;\n }\n\n /** `true` when the id is new (and records it); `false` for duplicates. */\n check(id: string): boolean {\n if (this.seen.has(id)) return false;\n this.seen.add(id);\n this.order.push(id);\n if (this.order.length > this.capacity) this.seen.delete(this.order.shift()!);\n return true;\n }\n}\n"],"mappings":";AAUA,SAAgB,EAAW,GAAqC;CAC9D,IAAI,OAAO,KAAU,aAAY,GAAgB,OAAO;CACxD,IAAM,IAAM;CAEZ,OADI,EAAI,MAAM,KAAK,OAAO,EAAI,MAAO,YAAY,OAAO,EAAI,KAAM,YAAY,OAAO,EAAI,MAAO,WAAiB,OAC1G;AACT;AAGA,IAAa,IAAb,MAA2B;CACzB,uBAAwB,IAAI,IAAY;CACxC,QAAmC,CAAC;CACpC;CAEA,YAAY,IAAW,KAAK;EAC1B,KAAK,WAAW;CAClB;CAGA,MAAM,GAAqB;EAKzB,OAJA,CAAI,KAAK,KAAK,IAAI,CAAE,MACpB,KAAK,KAAK,IAAI,CAAE,GAChB,KAAK,MAAM,KAAK,CAAE,GACd,KAAK,MAAM,SAAS,KAAK,YAAU,KAAK,KAAK,OAAO,KAAK,MAAM,MAAM,CAAE,GACpE;CACT;AACF"}
package/dist/codec.cjs ADDED
@@ -0,0 +1,2 @@
1
+ const e=require("./_base64.cjs"),t=require("./errors.cjs");function n(e){return typeof e==`object`&&!!e}function r(e){return e.v===1&&typeof e.sessionId==`string`&&typeof e.secret==`string`&&typeof e.expiresAt==`number`&&typeof e.sdp==`string`}function i(e){return e.v===1&&typeof e.sessionId==`string`&&typeof e.proof==`string`&&n(e.peer)&&typeof e.peer.id==`string`&&(e.peer.name===void 0||typeof e.peer.name==`string`)&&typeof e.sdp==`string`}function a(e){if(!n(e)||e.v!==1)throw new t.MeshPairingError(`Unsupported pairing payload version`);if(r(e)||i(e))return e;throw new t.MeshPairingError(`Unrecognized pairing payload shape`)}var o={decode(n){let r;try{r=JSON.parse(e.base64UrlToText(n.trim()))}catch(e){throw new t.MeshPairingError(`Malformed pairing payload`,{cause:e})}return a(r)},encode(t){return e.textToBase64Url(JSON.stringify(t))}};exports.meshCodec=o,exports.parsePairingPayload=a;
2
+ //# sourceMappingURL=codec.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"codec.cjs","names":[],"sources":["../src/codec.ts"],"sourcesContent":["import { base64UrlToText, textToBase64Url } from './_base64';\nimport { MeshPairingError } from './errors';\nimport type { MeshAnswer, MeshCodec, MeshInvitation } from './types';\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null;\n}\n\nfunction isInvitation(value: Record<string, unknown>): value is Record<string, unknown> & MeshInvitation {\n return (\n value.v === 1 &&\n typeof value.sessionId === 'string' &&\n typeof value.secret === 'string' &&\n typeof value.expiresAt === 'number' &&\n typeof value.sdp === 'string'\n );\n}\n\nfunction isAnswer(value: Record<string, unknown>): value is Record<string, unknown> & MeshAnswer {\n return (\n value.v === 1 &&\n typeof value.sessionId === 'string' &&\n typeof value.proof === 'string' &&\n isRecord(value.peer) &&\n typeof value.peer.id === 'string' &&\n (value.peer.name === undefined || typeof value.peer.name === 'string') &&\n typeof value.sdp === 'string'\n );\n}\n\n/**\n * Compact JSON → base64url codec for pairing payloads. Pure and transport-free\n * so alternative encodings (compressed, QR-optimized) can be added later\n * without touching the transport.\n *\n * @example\n * ```ts\n * const invitation = await host.createInvitation();\n * const text = meshCodec.encode(invitation); // copy/paste or navigator.share\n * const answer = await guest.acceptInvitation(meshCodec.decode(text));\n * await host.acceptAnswer(meshCodec.decode(meshCodec.encode(answer)));\n * ```\n *\n * @throws {MeshPairingError} On malformed text or unsupported payload shape/version.\n */\n/**\n * Validate a decoded pairing payload. Shared by `meshCodec` and `meshQrCodec`\n * so both encodings enforce the same shape/version contract.\n *\n * @throws {MeshPairingError} On unsupported version or unrecognized shape.\n */\nexport function parsePairingPayload(parsed: unknown): MeshInvitation | MeshAnswer {\n if (!isRecord(parsed) || parsed.v !== 1) {\n throw new MeshPairingError('Unsupported pairing payload version');\n }\n if (isInvitation(parsed) || isAnswer(parsed)) {\n return parsed;\n }\n throw new MeshPairingError('Unrecognized pairing payload shape');\n}\n\nexport const meshCodec: MeshCodec = {\n decode(text) {\n let parsed: unknown;\n try {\n parsed = JSON.parse(base64UrlToText(text.trim()));\n } catch (cause) {\n throw new MeshPairingError('Malformed pairing payload', { cause });\n }\n return parsePairingPayload(parsed);\n },\n encode(payload) {\n return textToBase64Url(JSON.stringify(payload));\n },\n};\n"],"mappings":"2DAIA,SAAS,EAAS,EAAkD,CAClE,OAAO,OAAO,GAAU,YAAY,CACtC,CAEA,SAAS,EAAa,EAAmF,CACvG,OACE,EAAM,IAAM,GACZ,OAAO,EAAM,WAAc,UAC3B,OAAO,EAAM,QAAW,UACxB,OAAO,EAAM,WAAc,UAC3B,OAAO,EAAM,KAAQ,QAEzB,CAEA,SAAS,EAAS,EAA+E,CAC/F,OACE,EAAM,IAAM,GACZ,OAAO,EAAM,WAAc,UAC3B,OAAO,EAAM,OAAU,UACvB,EAAS,EAAM,IAAI,GACnB,OAAO,EAAM,KAAK,IAAO,WACxB,EAAM,KAAK,OAAS,IAAA,IAAa,OAAO,EAAM,KAAK,MAAS,WAC7D,OAAO,EAAM,KAAQ,QAEzB,CAuBA,SAAgB,EAAoB,EAA8C,CAChF,GAAI,CAAC,EAAS,CAAM,GAAK,EAAO,IAAM,EACpC,MAAM,IAAI,EAAA,iBAAiB,qCAAqC,EAElE,GAAI,EAAa,CAAM,GAAK,EAAS,CAAM,EACzC,OAAO,EAET,MAAM,IAAI,EAAA,iBAAiB,oCAAoC,CACjE,CAEA,IAAa,EAAuB,CAClC,OAAO,EAAM,CACX,IAAI,EACJ,GAAI,CACF,EAAS,KAAK,MAAM,EAAA,gBAAgB,EAAK,KAAK,CAAC,CAAC,CAClD,OAAS,EAAO,CACd,MAAM,IAAI,EAAA,iBAAiB,4BAA6B,CAAE,OAAM,CAAC,CACnE,CACA,OAAO,EAAoB,CAAM,CACnC,EACA,OAAO,EAAS,CACd,OAAO,EAAA,gBAAgB,KAAK,UAAU,CAAO,CAAC,CAChD,CACF"}
@@ -0,0 +1,25 @@
1
+ import type { MeshAnswer, MeshCodec, MeshInvitation } from './types';
2
+ /**
3
+ * Compact JSON → base64url codec for pairing payloads. Pure and transport-free
4
+ * so alternative encodings (compressed, QR-optimized) can be added later
5
+ * without touching the transport.
6
+ *
7
+ * @example
8
+ * ```ts
9
+ * const invitation = await host.createInvitation();
10
+ * const text = meshCodec.encode(invitation); // copy/paste or navigator.share
11
+ * const answer = await guest.acceptInvitation(meshCodec.decode(text));
12
+ * await host.acceptAnswer(meshCodec.decode(meshCodec.encode(answer)));
13
+ * ```
14
+ *
15
+ * @throws {MeshPairingError} On malformed text or unsupported payload shape/version.
16
+ */
17
+ /**
18
+ * Validate a decoded pairing payload. Shared by `meshCodec` and `meshQrCodec`
19
+ * so both encodings enforce the same shape/version contract.
20
+ *
21
+ * @throws {MeshPairingError} On unsupported version or unrecognized shape.
22
+ */
23
+ export declare function parsePairingPayload(parsed: unknown): MeshInvitation | MeshAnswer;
24
+ export declare const meshCodec: MeshCodec;
25
+ //# sourceMappingURL=codec.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"codec.d.ts","sourceRoot":"","sources":["../src/codec.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,UAAU,EAAE,SAAS,EAAE,cAAc,EAAE,MAAM,SAAS,CAAC;AA4BrE;;;;;;;;;;;;;;GAcG;AACH;;;;;GAKG;AACH,wBAAgB,mBAAmB,CAAC,MAAM,EAAE,OAAO,GAAG,cAAc,GAAG,UAAU,CAQhF;AAED,eAAO,MAAM,SAAS,EAAE,SAavB,CAAC"}
package/dist/codec.js ADDED
@@ -0,0 +1,35 @@
1
+ import { base64UrlToText as e, textToBase64Url as t } from "./_base64.js";
2
+ import { MeshPairingError as n } from "./errors.js";
3
+ //#region src/codec.ts
4
+ function r(e) {
5
+ return typeof e == "object" && !!e;
6
+ }
7
+ function i(e) {
8
+ return e.v === 1 && typeof e.sessionId == "string" && typeof e.secret == "string" && typeof e.expiresAt == "number" && typeof e.sdp == "string";
9
+ }
10
+ function a(e) {
11
+ return e.v === 1 && typeof e.sessionId == "string" && typeof e.proof == "string" && r(e.peer) && typeof e.peer.id == "string" && (e.peer.name === void 0 || typeof e.peer.name == "string") && typeof e.sdp == "string";
12
+ }
13
+ function o(e) {
14
+ if (!r(e) || e.v !== 1) throw new n("Unsupported pairing payload version");
15
+ if (i(e) || a(e)) return e;
16
+ throw new n("Unrecognized pairing payload shape");
17
+ }
18
+ var s = {
19
+ decode(t) {
20
+ let r;
21
+ try {
22
+ r = JSON.parse(e(t.trim()));
23
+ } catch (e) {
24
+ throw new n("Malformed pairing payload", { cause: e });
25
+ }
26
+ return o(r);
27
+ },
28
+ encode(e) {
29
+ return t(JSON.stringify(e));
30
+ }
31
+ };
32
+ //#endregion
33
+ export { s as meshCodec, o as parsePairingPayload };
34
+
35
+ //# sourceMappingURL=codec.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"codec.js","names":[],"sources":["../src/codec.ts"],"sourcesContent":["import { base64UrlToText, textToBase64Url } from './_base64';\nimport { MeshPairingError } from './errors';\nimport type { MeshAnswer, MeshCodec, MeshInvitation } from './types';\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null;\n}\n\nfunction isInvitation(value: Record<string, unknown>): value is Record<string, unknown> & MeshInvitation {\n return (\n value.v === 1 &&\n typeof value.sessionId === 'string' &&\n typeof value.secret === 'string' &&\n typeof value.expiresAt === 'number' &&\n typeof value.sdp === 'string'\n );\n}\n\nfunction isAnswer(value: Record<string, unknown>): value is Record<string, unknown> & MeshAnswer {\n return (\n value.v === 1 &&\n typeof value.sessionId === 'string' &&\n typeof value.proof === 'string' &&\n isRecord(value.peer) &&\n typeof value.peer.id === 'string' &&\n (value.peer.name === undefined || typeof value.peer.name === 'string') &&\n typeof value.sdp === 'string'\n );\n}\n\n/**\n * Compact JSON → base64url codec for pairing payloads. Pure and transport-free\n * so alternative encodings (compressed, QR-optimized) can be added later\n * without touching the transport.\n *\n * @example\n * ```ts\n * const invitation = await host.createInvitation();\n * const text = meshCodec.encode(invitation); // copy/paste or navigator.share\n * const answer = await guest.acceptInvitation(meshCodec.decode(text));\n * await host.acceptAnswer(meshCodec.decode(meshCodec.encode(answer)));\n * ```\n *\n * @throws {MeshPairingError} On malformed text or unsupported payload shape/version.\n */\n/**\n * Validate a decoded pairing payload. Shared by `meshCodec` and `meshQrCodec`\n * so both encodings enforce the same shape/version contract.\n *\n * @throws {MeshPairingError} On unsupported version or unrecognized shape.\n */\nexport function parsePairingPayload(parsed: unknown): MeshInvitation | MeshAnswer {\n if (!isRecord(parsed) || parsed.v !== 1) {\n throw new MeshPairingError('Unsupported pairing payload version');\n }\n if (isInvitation(parsed) || isAnswer(parsed)) {\n return parsed;\n }\n throw new MeshPairingError('Unrecognized pairing payload shape');\n}\n\nexport const meshCodec: MeshCodec = {\n decode(text) {\n let parsed: unknown;\n try {\n parsed = JSON.parse(base64UrlToText(text.trim()));\n } catch (cause) {\n throw new MeshPairingError('Malformed pairing payload', { cause });\n }\n return parsePairingPayload(parsed);\n },\n encode(payload) {\n return textToBase64Url(JSON.stringify(payload));\n },\n};\n"],"mappings":";;;AAIA,SAAS,EAAS,GAAkD;CAClE,OAAO,OAAO,KAAU,cAAY;AACtC;AAEA,SAAS,EAAa,GAAmF;CACvG,OACE,EAAM,MAAM,KACZ,OAAO,EAAM,aAAc,YAC3B,OAAO,EAAM,UAAW,YACxB,OAAO,EAAM,aAAc,YAC3B,OAAO,EAAM,OAAQ;AAEzB;AAEA,SAAS,EAAS,GAA+E;CAC/F,OACE,EAAM,MAAM,KACZ,OAAO,EAAM,aAAc,YAC3B,OAAO,EAAM,SAAU,YACvB,EAAS,EAAM,IAAI,KACnB,OAAO,EAAM,KAAK,MAAO,aACxB,EAAM,KAAK,SAAS,KAAA,KAAa,OAAO,EAAM,KAAK,QAAS,aAC7D,OAAO,EAAM,OAAQ;AAEzB;AAuBA,SAAgB,EAAoB,GAA8C;CAChF,IAAI,CAAC,EAAS,CAAM,KAAK,EAAO,MAAM,GACpC,MAAM,IAAI,EAAiB,qCAAqC;CAElE,IAAI,EAAa,CAAM,KAAK,EAAS,CAAM,GACzC,OAAO;CAET,MAAM,IAAI,EAAiB,oCAAoC;AACjE;AAEA,IAAa,IAAuB;CAClC,OAAO,GAAM;EACX,IAAI;EACJ,IAAI;GACF,IAAS,KAAK,MAAM,EAAgB,EAAK,KAAK,CAAC,CAAC;EAClD,SAAS,GAAO;GACd,MAAM,IAAI,EAAiB,6BAA6B,EAAE,SAAM,CAAC;EACnE;EACA,OAAO,EAAoB,CAAM;CACnC;CACA,OAAO,GAAS;EACd,OAAO,EAAgB,KAAK,UAAU,CAAO,CAAC;CAChD;AACF"}
@@ -0,0 +1,2 @@
1
+ var e=class extends Error{constructor(e,t){super(e,t),this.name=new.target.name,Object.setPrototypeOf(this,new.target.prototype)}},t=class extends e{},n=class extends e{peerId;constructor(e,t=null,n){super(e,n),this.peerId=t}},r=class extends e{},i=class extends e{},a=class extends e{constructor(e=`Mesh node`,t){super(`${e} is disposed`,t)}},o=class extends e{};exports.MeshConnectionError=n,exports.MeshDisposedError=a,exports.MeshError=e,exports.MeshPairingError=t,exports.MeshPayloadError=r,exports.MeshTimeoutError=i,exports.MeshUnsupportedError=o;
2
+ //# sourceMappingURL=errors.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"errors.cjs","names":[],"sources":["../src/errors.ts"],"sourcesContent":["/**\n * Base class for all mesh errors.\n * Use `instanceof MeshError` to catch any mesh-originated error in one branch.\n */\nexport class MeshError extends Error {\n constructor(message: string, opts?: ErrorOptions) {\n super(message, opts);\n this.name = new.target.name;\n Object.setPrototypeOf(this, new.target.prototype);\n }\n}\n\n/**\n * Thrown when a pairing payload is malformed, expired, unknown, already\n * consumed, carries a mismatched proof, or is rejected by the host's\n * `approvePeer` hook.\n */\nexport class MeshPairingError extends MeshError {}\n\n/**\n * Thrown when the peer connection fails (ICE/DTLS failure, channel closed\n * unexpectedly) or a send targets an unknown or unconnected peer.\n */\nexport class MeshConnectionError extends MeshError {\n readonly peerId: string | null;\n\n constructor(message: string, peerId: string | null = null, opts?: ErrorOptions) {\n super(message, opts);\n this.peerId = peerId;\n }\n}\n\n/**\n * Thrown when an outbound message exceeds `maxMessageBytes` or cannot be\n * serialized.\n */\nexport class MeshPayloadError extends MeshError {}\n\n/**\n * Thrown when ICE gathering or the data-channel open handshake exceeds the\n * configured timeout.\n */\nexport class MeshTimeoutError extends MeshError {}\n\n/**\n * Thrown when a method is called on a disposed mesh node.\n */\nexport class MeshDisposedError extends MeshError {\n constructor(target = 'Mesh node', opts?: ErrorOptions) {\n super(`${target} is disposed`, opts);\n }\n}\n\n/**\n * Thrown when WebRTC is unavailable in the current environment and no `rtc`\n * factory was injected. Raised at first use, never at import time.\n */\nexport class MeshUnsupportedError extends MeshError {}\n"],"mappings":"AAIA,IAAa,EAAb,cAA+B,KAAM,CACnC,YAAY,EAAiB,EAAqB,CAChD,MAAM,EAAS,CAAI,EACnB,KAAK,KAAO,WAAW,KACvB,OAAO,eAAe,KAAM,WAAW,SAAS,CAClD,CACF,EAOa,EAAb,cAAsC,CAAU,CAAC,EAMpC,EAAb,cAAyC,CAAU,CACjD,OAEA,YAAY,EAAiB,EAAwB,KAAM,EAAqB,CAC9E,MAAM,EAAS,CAAI,EACnB,KAAK,OAAS,CAChB,CACF,EAMa,EAAb,cAAsC,CAAU,CAAC,EAMpC,EAAb,cAAsC,CAAU,CAAC,EAKpC,EAAb,cAAuC,CAAU,CAC/C,YAAY,EAAS,YAAa,EAAqB,CACrD,MAAM,GAAG,EAAO,cAAe,CAAI,CACrC,CACF,EAMa,EAAb,cAA0C,CAAU,CAAC"}
@@ -0,0 +1,47 @@
1
+ /**
2
+ * Base class for all mesh errors.
3
+ * Use `instanceof MeshError` to catch any mesh-originated error in one branch.
4
+ */
5
+ export declare class MeshError extends Error {
6
+ constructor(message: string, opts?: ErrorOptions);
7
+ }
8
+ /**
9
+ * Thrown when a pairing payload is malformed, expired, unknown, already
10
+ * consumed, carries a mismatched proof, or is rejected by the host's
11
+ * `approvePeer` hook.
12
+ */
13
+ export declare class MeshPairingError extends MeshError {
14
+ }
15
+ /**
16
+ * Thrown when the peer connection fails (ICE/DTLS failure, channel closed
17
+ * unexpectedly) or a send targets an unknown or unconnected peer.
18
+ */
19
+ export declare class MeshConnectionError extends MeshError {
20
+ readonly peerId: string | null;
21
+ constructor(message: string, peerId?: string | null, opts?: ErrorOptions);
22
+ }
23
+ /**
24
+ * Thrown when an outbound message exceeds `maxMessageBytes` or cannot be
25
+ * serialized.
26
+ */
27
+ export declare class MeshPayloadError extends MeshError {
28
+ }
29
+ /**
30
+ * Thrown when ICE gathering or the data-channel open handshake exceeds the
31
+ * configured timeout.
32
+ */
33
+ export declare class MeshTimeoutError extends MeshError {
34
+ }
35
+ /**
36
+ * Thrown when a method is called on a disposed mesh node.
37
+ */
38
+ export declare class MeshDisposedError extends MeshError {
39
+ constructor(target?: string, opts?: ErrorOptions);
40
+ }
41
+ /**
42
+ * Thrown when WebRTC is unavailable in the current environment and no `rtc`
43
+ * factory was injected. Raised at first use, never at import time.
44
+ */
45
+ export declare class MeshUnsupportedError extends MeshError {
46
+ }
47
+ //# sourceMappingURL=errors.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"errors.d.ts","sourceRoot":"","sources":["../src/errors.ts"],"names":[],"mappings":"AAAA;;;GAGG;AACH,qBAAa,SAAU,SAAQ,KAAK;gBACtB,OAAO,EAAE,MAAM,EAAE,IAAI,CAAC,EAAE,YAAY;CAKjD;AAED;;;;GAIG;AACH,qBAAa,gBAAiB,SAAQ,SAAS;CAAG;AAElD;;;GAGG;AACH,qBAAa,mBAAoB,SAAQ,SAAS;IAChD,QAAQ,CAAC,MAAM,EAAE,MAAM,GAAG,IAAI,CAAC;gBAEnB,OAAO,EAAE,MAAM,EAAE,MAAM,GAAE,MAAM,GAAG,IAAW,EAAE,IAAI,CAAC,EAAE,YAAY;CAI/E;AAED;;;GAGG;AACH,qBAAa,gBAAiB,SAAQ,SAAS;CAAG;AAElD;;;GAGG;AACH,qBAAa,gBAAiB,SAAQ,SAAS;CAAG;AAElD;;GAEG;AACH,qBAAa,iBAAkB,SAAQ,SAAS;gBAClC,MAAM,SAAc,EAAE,IAAI,CAAC,EAAE,YAAY;CAGtD;AAED;;;GAGG;AACH,qBAAa,oBAAqB,SAAQ,SAAS;CAAG"}
package/dist/errors.js ADDED
@@ -0,0 +1,19 @@
1
+ //#region src/errors.ts
2
+ var e = class extends Error {
3
+ constructor(e, t) {
4
+ super(e, t), this.name = new.target.name, Object.setPrototypeOf(this, new.target.prototype);
5
+ }
6
+ }, t = class extends e {}, n = class extends e {
7
+ peerId;
8
+ constructor(e, t = null, n) {
9
+ super(e, n), this.peerId = t;
10
+ }
11
+ }, r = class extends e {}, i = class extends e {}, a = class extends e {
12
+ constructor(e = "Mesh node", t) {
13
+ super(`${e} is disposed`, t);
14
+ }
15
+ }, o = class extends e {};
16
+ //#endregion
17
+ export { n as MeshConnectionError, a as MeshDisposedError, e as MeshError, t as MeshPairingError, r as MeshPayloadError, i as MeshTimeoutError, o as MeshUnsupportedError };
18
+
19
+ //# sourceMappingURL=errors.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"errors.js","names":[],"sources":["../src/errors.ts"],"sourcesContent":["/**\n * Base class for all mesh errors.\n * Use `instanceof MeshError` to catch any mesh-originated error in one branch.\n */\nexport class MeshError extends Error {\n constructor(message: string, opts?: ErrorOptions) {\n super(message, opts);\n this.name = new.target.name;\n Object.setPrototypeOf(this, new.target.prototype);\n }\n}\n\n/**\n * Thrown when a pairing payload is malformed, expired, unknown, already\n * consumed, carries a mismatched proof, or is rejected by the host's\n * `approvePeer` hook.\n */\nexport class MeshPairingError extends MeshError {}\n\n/**\n * Thrown when the peer connection fails (ICE/DTLS failure, channel closed\n * unexpectedly) or a send targets an unknown or unconnected peer.\n */\nexport class MeshConnectionError extends MeshError {\n readonly peerId: string | null;\n\n constructor(message: string, peerId: string | null = null, opts?: ErrorOptions) {\n super(message, opts);\n this.peerId = peerId;\n }\n}\n\n/**\n * Thrown when an outbound message exceeds `maxMessageBytes` or cannot be\n * serialized.\n */\nexport class MeshPayloadError extends MeshError {}\n\n/**\n * Thrown when ICE gathering or the data-channel open handshake exceeds the\n * configured timeout.\n */\nexport class MeshTimeoutError extends MeshError {}\n\n/**\n * Thrown when a method is called on a disposed mesh node.\n */\nexport class MeshDisposedError extends MeshError {\n constructor(target = 'Mesh node', opts?: ErrorOptions) {\n super(`${target} is disposed`, opts);\n }\n}\n\n/**\n * Thrown when WebRTC is unavailable in the current environment and no `rtc`\n * factory was injected. Raised at first use, never at import time.\n */\nexport class MeshUnsupportedError extends MeshError {}\n"],"mappings":";AAIA,IAAa,IAAb,cAA+B,MAAM;CACnC,YAAY,GAAiB,GAAqB;EAGhD,AAFA,MAAM,GAAS,CAAI,GACnB,KAAK,OAAO,WAAW,MACvB,OAAO,eAAe,MAAM,WAAW,SAAS;CAClD;AACF,GAOa,IAAb,cAAsC,EAAU,CAAC,GAMpC,IAAb,cAAyC,EAAU;CACjD;CAEA,YAAY,GAAiB,IAAwB,MAAM,GAAqB;EAE9E,AADA,MAAM,GAAS,CAAI,GACnB,KAAK,SAAS;CAChB;AACF,GAMa,IAAb,cAAsC,EAAU,CAAC,GAMpC,IAAb,cAAsC,EAAU,CAAC,GAKpC,IAAb,cAAuC,EAAU;CAC/C,YAAY,IAAS,aAAa,GAAqB;EACrD,MAAM,GAAG,EAAO,eAAe,CAAI;CACrC;AACF,GAMa,IAAb,cAA0C,EAAU,CAAC"}
package/dist/guest.cjs ADDED
@@ -0,0 +1,2 @@
1
+ const e=require("./errors.cjs"),t=require("./_random.cjs"),n=require("./_node.cjs"),r=require("./_proof.cjs"),i=require("./_rtc.cjs");var a=6e4,o=65536,s=5e3;function c(c={}){let l=c.rtc??i.nativeRtcFactory,u=c.clock??(()=>Date.now()),d=c.serialize??JSON.stringify,f=c.deserialize??JSON.parse,p=c.maxMessageBytes??o,m=c.channelOpenTimeoutMs??a,h=c.iceGatheringTimeoutMs??s,g=n.createNodeCore(t.randomId(c.random),c.signal),_=n.createMessenger({clock:u,deserialize:f,emitTap:g.emitTap,maxMessageBytes:p,peerIdOf:e=>e.id,random:c.random,serialize:d}),v=null,y=null,b=!1;function x(){b||(b=!0,g.emitTap({reason:`SubtleCrypto unavailable — proof uses a non-cryptographic hash`,type:`security-downgrade`}))}function S(e,t){g.disposed||e.status===`failed`||(e.status=`failed`,y&&=(clearTimeout(y),null),setTimeout(()=>{e.dc?.close(),e.pc?.close()},0),g.emitTap({peerId:e.id,status:`failed`,type:`status-change`}),g.emitTap({error:t,type:`error`}),g.emitTap({peerId:e.id,reason:t.message,type:`peer-left`}),g.setStatus(`failed`))}function C(e,t){g.disposed||e.status===`disconnected`||e.status===`failed`||(e.status=`disconnected`,e.pc?.close(),g.emitTap({peerId:e.id,status:`disconnected`,type:`status-change`}),g.emitTap({peerId:e.id,reason:t,type:`peer-left`}),g.setStatus(`disconnected`))}function w(t,n,r){t.dc=r,r.addEventListener(`open`,()=>{g.disposed||(y&&=(clearTimeout(y),null),t.status=`connected`,g.emitTap({peerId:t.id,status:`connected`,type:`status-change`}),g.emitTap({peerId:t.id,type:`peer-joined`}),g.setStatus(`connected`))}),r.addEventListener(`message`,e=>{g.disposed||_.handleInbound(t,e.data)}),r.addEventListener(`close`,()=>{g.disposed||(t.status===`connecting`?S(t,y?new e.MeshTimeoutError(`Timed out waiting for the data channel to open`):new e.MeshConnectionError(`channel closed before opening`,t.id)):C(t,`channel closed`))}),r.addEventListener(`error`,()=>{g.disposed||S(t,new e.MeshConnectionError(`channel error`,t.id))}),n.addEventListener(`iceconnectionstatechange`,()=>{if(g.disposed)return;let r=n.iceConnectionState;g.emitTap({peerId:t.id,state:r,type:`ice-state`}),r===`failed`||r===`closed`?S(t,new e.MeshConnectionError(`ice ${r}`,t.id)):r===`disconnected`&&t.status===`connected`&&C(t,`ice disconnected`)})}return{async acceptInvitation(a,o){if(g.ensureLive(),v)throw new e.MeshPairingError(`Guest is already paired`);if(a?.v!==1)throw new e.MeshPairingError(`Unsupported invitation version`);if(u()>=a.expiresAt)throw new e.MeshPairingError(`Invitation expired`);g.setStatus(`pairing`);let s;try{s=l.createPeerConnection({iceServers:[...c.iceServers??[]]})}catch(e){throw g.setStatus(`idle`),e}let d=n.createPeerRecord(a.sessionId,void 0,`host`);d.pc=s,v=d,s.addEventListener(`datachannel`,e=>{w(d,s,e.channel)}),s.addEventListener(`iceconnectionstatechange`,()=>{g.disposed||g.emitTap({peerId:d.id,state:s.iceConnectionState,type:`ice-state`})});try{await s.setRemoteDescription({sdp:i.normalizeSdp(a.sdp),type:`offer`})}catch(t){throw v=null,g.setStatus(`idle`),new e.MeshPairingError(`Invalid invitation SDP`,{cause:t})}let f;try{await s.setLocalDescription(await s.createAnswer()),await i.waitIceGathering(s,h),f=s.localDescription?.sdp??``}catch(t){throw v=null,s.close(),g.setStatus(`idle`),new e.MeshConnectionError(`Failed to create answer`,null,{cause:t})}if(g.disposed)throw s.close(),new e.MeshDisposedError;if(!f)throw v=null,s.close(),g.setStatus(`idle`),new e.MeshConnectionError(`Local description has no SDP`);let p=t.randomId(c.random),_=await r.createProof(a.secret,f,x);return g.setStatus(`connecting`),y=setTimeout(()=>{v?.status===`connecting`&&S(v,new e.MeshTimeoutError(`Timed out waiting for the data channel to open`))},m),{peer:o?.name===void 0?{id:p}:{id:p,name:o.name},proof:_,sdp:f,sessionId:a.sessionId,v:1}},get disposalSignal(){return g.disposalCtrl.signal},dispose(){g.disposed||(g.markDisposed(),y&&=(clearTimeout(y),null),v&&(v.dc?.close(),v.pc?.close(),v.status=`disposed`),_.clear())},get disposed(){return g.disposed},get host(){return v?.publicPeer??null},get id(){return g.id},on(e,t){return g.ensureLive(),_.on(e,t)},send(t,n){if(g.ensureLive(),!v)throw new e.MeshConnectionError(`Guest is not paired`);_.sendTo(v,t,n)},get status(){return g.status},tap(e,t){return g.tap(e,t)},[Symbol.dispose](){this.dispose()}}}exports.createMeshGuest=c;
2
+ //# sourceMappingURL=guest.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"guest.cjs","names":[],"sources":["../src/guest.ts"],"sourcesContent":["import { createMessenger, createNodeCore, createPeerRecord, type PeerRecord } from './_node';\nimport { createProof } from './_proof';\nimport { randomId } from './_random';\nimport { nativeRtcFactory, normalizeSdp, waitIceGathering } from './_rtc';\nimport { MeshConnectionError, MeshDisposedError, type MeshError, MeshPairingError, MeshTimeoutError } from './errors';\nimport type {\n MeshGuest,\n MeshGuestOptions,\n MeshInbound,\n MeshPeer,\n MeshProtocol,\n RTCDataChannelLike,\n RTCPeerConnectionLike,\n} from './types';\n\nconst DEFAULT_CHANNEL_OPEN_TIMEOUT_MS = 60_000;\nconst DEFAULT_MAX_MESSAGE_BYTES = 65_536;\nconst DEFAULT_ICE_GATHERING_TIMEOUT_MS = 5_000;\n\n/**\n * Create a guest mesh node. The guest pairs with one host by consuming an\n * out-of-band invitation and returning an answer.\n */\nexport function createMeshGuest<P extends MeshProtocol>(options: MeshGuestOptions = {}): MeshGuest<P> {\n const rtc = options.rtc ?? nativeRtcFactory;\n const clock = options.clock ?? (() => Date.now());\n const serialize = options.serialize ?? JSON.stringify;\n const deserialize = options.deserialize ?? JSON.parse;\n const maxMessageBytes = options.maxMessageBytes ?? DEFAULT_MAX_MESSAGE_BYTES;\n const channelOpenTimeoutMs = options.channelOpenTimeoutMs ?? DEFAULT_CHANNEL_OPEN_TIMEOUT_MS;\n const iceGatheringTimeoutMs = options.iceGatheringTimeoutMs ?? DEFAULT_ICE_GATHERING_TIMEOUT_MS;\n\n const core = createNodeCore(randomId(options.random), options.signal);\n const messenger = createMessenger({\n clock,\n deserialize,\n emitTap: core.emitTap,\n maxMessageBytes,\n peerIdOf: (peer) => peer.id,\n random: options.random,\n serialize,\n });\n\n let hostPeer: PeerRecord | null = null;\n let openTimer: ReturnType<typeof setTimeout> | null = null;\n let downgradeNotified = false;\n\n function onSecurityDowngrade(): void {\n if (downgradeNotified) return;\n downgradeNotified = true;\n core.emitTap({\n reason: 'SubtleCrypto unavailable — proof uses a non-cryptographic hash',\n type: 'security-downgrade',\n });\n }\n\n function failPeer(peer: PeerRecord, error: MeshError): void {\n if (core.disposed || peer.status === 'failed') return;\n peer.status = 'failed';\n if (openTimer) {\n clearTimeout(openTimer);\n openTimer = null;\n }\n // Teardown is deferred a macrotask so a peer racing its own open\n // deadline reports its timeout rather than this hangup.\n setTimeout(() => {\n peer.dc?.close();\n peer.pc?.close();\n }, 0);\n core.emitTap({ peerId: peer.id, status: 'failed', type: 'status-change' });\n core.emitTap({ error, type: 'error' });\n core.emitTap({ peerId: peer.id, reason: error.message, type: 'peer-left' });\n core.setStatus('failed');\n }\n\n function disconnectPeer(peer: PeerRecord, reason: string): void {\n if (core.disposed || peer.status === 'disconnected' || peer.status === 'failed') return;\n peer.status = 'disconnected';\n peer.pc?.close();\n core.emitTap({ peerId: peer.id, status: 'disconnected', type: 'status-change' });\n core.emitTap({ peerId: peer.id, reason, type: 'peer-left' });\n core.setStatus('disconnected');\n }\n\n function wireChannel(peer: PeerRecord, pc: RTCPeerConnectionLike, dc: RTCDataChannelLike): void {\n peer.dc = dc;\n\n dc.addEventListener('open', () => {\n if (core.disposed) return;\n if (openTimer) {\n clearTimeout(openTimer);\n openTimer = null;\n }\n peer.status = 'connected';\n core.emitTap({ peerId: peer.id, status: 'connected', type: 'status-change' });\n core.emitTap({ peerId: peer.id, type: 'peer-joined' });\n core.setStatus('connected');\n });\n dc.addEventListener('message', (event) => {\n if (core.disposed) return;\n messenger.handleInbound(peer, event.data);\n });\n dc.addEventListener('close', () => {\n if (core.disposed) return;\n if (peer.status === 'connecting')\n failPeer(\n peer,\n openTimer\n ? new MeshTimeoutError('Timed out waiting for the data channel to open')\n : new MeshConnectionError('channel closed before opening', peer.id),\n );\n else disconnectPeer(peer, 'channel closed');\n });\n dc.addEventListener('error', () => {\n if (core.disposed) return;\n failPeer(peer, new MeshConnectionError('channel error', peer.id));\n });\n\n pc.addEventListener('iceconnectionstatechange', () => {\n if (core.disposed) return;\n const state = pc.iceConnectionState;\n core.emitTap({ peerId: peer.id, state, type: 'ice-state' });\n if (state === 'failed' || state === 'closed') {\n failPeer(peer, new MeshConnectionError(`ice ${state}`, peer.id));\n } else if (state === 'disconnected' && peer.status === 'connected') {\n disconnectPeer(peer, 'ice disconnected');\n }\n });\n }\n\n const guest: MeshGuest<P> = {\n async acceptInvitation(invitation, meta) {\n core.ensureLive();\n if (hostPeer) throw new MeshPairingError('Guest is already paired');\n if (invitation?.v !== 1) throw new MeshPairingError('Unsupported invitation version');\n if (clock() >= invitation.expiresAt) throw new MeshPairingError('Invitation expired');\n\n core.setStatus('pairing');\n let pc: RTCPeerConnectionLike;\n try {\n pc = rtc.createPeerConnection({ iceServers: [...(options.iceServers ?? [])] });\n } catch (error) {\n core.setStatus('idle');\n throw error;\n }\n\n // The invitation carries no host identity — the session id doubles as\n // the host-side peer id for inbound metadata and tap events.\n const peer = createPeerRecord(invitation.sessionId, undefined, 'host');\n peer.pc = pc;\n hostPeer = peer;\n\n pc.addEventListener('datachannel', (event) => {\n wireChannel(peer, pc, event.channel);\n });\n pc.addEventListener('iceconnectionstatechange', () => {\n if (core.disposed) return;\n core.emitTap({ peerId: peer.id, state: pc.iceConnectionState, type: 'ice-state' });\n });\n\n try {\n await pc.setRemoteDescription({ sdp: normalizeSdp(invitation.sdp), type: 'offer' });\n } catch (cause) {\n hostPeer = null;\n core.setStatus('idle');\n throw new MeshPairingError('Invalid invitation SDP', { cause });\n }\n\n let answerSdp: string;\n try {\n await pc.setLocalDescription(await pc.createAnswer());\n await waitIceGathering(pc, iceGatheringTimeoutMs);\n answerSdp = pc.localDescription?.sdp ?? '';\n } catch (cause) {\n hostPeer = null;\n pc.close();\n core.setStatus('idle');\n throw new MeshConnectionError('Failed to create answer', null, { cause });\n }\n if (core.disposed) {\n pc.close();\n throw new MeshDisposedError();\n }\n if (!answerSdp) {\n hostPeer = null;\n pc.close();\n core.setStatus('idle');\n throw new MeshConnectionError('Local description has no SDP');\n }\n\n const peerId = randomId(options.random);\n const proof = await createProof(invitation.secret, answerSdp, onSecurityDowngrade);\n core.setStatus('connecting');\n\n // If the channel never opens (host never accepts the answer), fail loudly\n // instead of hanging in 'connecting' forever. The deadline must cover\n // the human carry-back of the answer, not just machine negotiation.\n openTimer = setTimeout(() => {\n if (hostPeer?.status === 'connecting') {\n failPeer(hostPeer, new MeshTimeoutError('Timed out waiting for the data channel to open'));\n }\n }, channelOpenTimeoutMs);\n\n return {\n peer: meta?.name === undefined ? { id: peerId } : { id: peerId, name: meta.name },\n proof,\n sdp: answerSdp,\n sessionId: invitation.sessionId,\n v: 1,\n };\n },\n get disposalSignal() {\n return core.disposalCtrl.signal;\n },\n\n dispose() {\n if (core.disposed) return;\n core.markDisposed();\n if (openTimer) {\n clearTimeout(openTimer);\n openTimer = null;\n }\n if (hostPeer) {\n hostPeer.dc?.close();\n hostPeer.pc?.close();\n hostPeer.status = 'disposed';\n }\n messenger.clear();\n },\n get disposed() {\n return core.disposed;\n },\n get host(): MeshPeer | null {\n return hostPeer?.publicPeer ?? null;\n },\n get id() {\n return core.id;\n },\n\n on(type, handler) {\n core.ensureLive();\n return messenger.on(type, handler as (message: MeshInbound<unknown>) => void);\n },\n\n send(type, payload) {\n core.ensureLive();\n if (!hostPeer) throw new MeshConnectionError('Guest is not paired');\n messenger.sendTo(hostPeer, type, payload);\n },\n get status() {\n return core.status;\n },\n\n tap(handler, tapOptions) {\n return core.tap(handler, tapOptions);\n },\n\n [Symbol.dispose]() {\n this.dispose();\n },\n };\n\n return guest;\n}\n"],"mappings":"sIAeA,IAAM,EAAkC,IAClC,EAA4B,MAC5B,EAAmC,IAMzC,SAAgB,EAAwC,EAA4B,CAAC,EAAiB,CACpG,IAAM,EAAM,EAAQ,KAAO,EAAA,iBACrB,EAAQ,EAAQ,YAAgB,KAAK,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h node. The guest pairs with one host by consuming an
4
+ * out-of-band invitation and returning an answer.
5
+ */
6
+ export declare function createMeshGuest<P extends MeshProtocol>(options?: MeshGuestOptions): MeshGuest<P>;
7
+ //# sourceMappingURL=guest.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"guest.d.ts","sourceRoot":"","sources":["../src/guest.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EACV,SAAS,EACT,gBAAgB,EAGhB,YAAY,EAGb,MAAM,SAAS,CAAC;AAMjB;;;GAGG;AACH,wBAAgB,eAAe,CAAC,CAAC,SAAS,YAAY,EAAE,OAAO,GAAE,gBAAqB,GAAG,SAAS,CAAC,CAAC,CAAC,CAgPpG"}