@argos-js/net 0.0.0-stage → 0.1.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 (63) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +79 -2
  3. package/dist/adapter.d.ts +66 -0
  4. package/dist/adapter.d.ts.map +1 -0
  5. package/dist/adapter.js +216 -0
  6. package/dist/adapter.js.map +1 -0
  7. package/dist/binary-stream.d.ts +67 -0
  8. package/dist/binary-stream.d.ts.map +1 -0
  9. package/dist/binary-stream.js +201 -0
  10. package/dist/binary-stream.js.map +1 -0
  11. package/dist/context.d.ts +5 -0
  12. package/dist/context.d.ts.map +1 -0
  13. package/dist/context.js +9 -0
  14. package/dist/context.js.map +1 -0
  15. package/dist/errors.d.ts +20 -0
  16. package/dist/errors.d.ts.map +1 -0
  17. package/dist/errors.js +31 -0
  18. package/dist/errors.js.map +1 -0
  19. package/dist/http-status.d.ts +26 -0
  20. package/dist/http-status.d.ts.map +1 -0
  21. package/dist/http-status.js +34 -0
  22. package/dist/http-status.js.map +1 -0
  23. package/dist/index.d.ts +19 -0
  24. package/dist/index.d.ts.map +1 -0
  25. package/dist/index.js +35 -0
  26. package/dist/index.js.map +1 -0
  27. package/dist/inject.d.ts +82 -0
  28. package/dist/inject.d.ts.map +1 -0
  29. package/dist/inject.js +127 -0
  30. package/dist/inject.js.map +1 -0
  31. package/dist/native-bridge.d.ts +63 -0
  32. package/dist/native-bridge.d.ts.map +1 -0
  33. package/dist/native-bridge.js +82 -0
  34. package/dist/native-bridge.js.map +1 -0
  35. package/dist/radix-tree.d.ts +53 -0
  36. package/dist/radix-tree.d.ts.map +1 -0
  37. package/dist/radix-tree.js +152 -0
  38. package/dist/radix-tree.js.map +1 -0
  39. package/dist/router.d.ts +32 -0
  40. package/dist/router.d.ts.map +1 -0
  41. package/dist/router.js +66 -0
  42. package/dist/router.js.map +1 -0
  43. package/dist/server.d.ts +15 -0
  44. package/dist/server.d.ts.map +1 -0
  45. package/dist/server.js +31 -0
  46. package/dist/server.js.map +1 -0
  47. package/dist/tcp-channel.d.ts +56 -0
  48. package/dist/tcp-channel.d.ts.map +1 -0
  49. package/dist/tcp-channel.js +240 -0
  50. package/dist/tcp-channel.js.map +1 -0
  51. package/dist/types.d.ts +190 -0
  52. package/dist/types.d.ts.map +1 -0
  53. package/dist/types.js +547 -0
  54. package/dist/types.js.map +1 -0
  55. package/dist/validation.d.ts +172 -0
  56. package/dist/validation.d.ts.map +1 -0
  57. package/dist/validation.js +468 -0
  58. package/dist/validation.js.map +1 -0
  59. package/dist/websocket-channel.d.ts +47 -0
  60. package/dist/websocket-channel.d.ts.map +1 -0
  61. package/dist/websocket-channel.js +165 -0
  62. package/dist/websocket-channel.js.map +1 -0
  63. package/package.json +33 -3
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Argos-JS Team
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,80 @@
1
- # Temporary Holding Version
1
+ # @argos-js/net
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ High-performance networking and HTTP abstraction layer connecting the Argox native engine to the Argos-JS runtime.
4
+
5
+ ## Overview
6
+
7
+ `@argos-js/net` provides the low-level HTTP bridge between native Rust FFI bindings (`@argos-js/argox-core`) and TypeScript routing/middleware systems. It manages request contexts (`ArgosContext`), header normalization, cookie management, form/multipart parsing, and in-memory request injection.
8
+
9
+ ## Features
10
+
11
+ - ⚡ **Native FFI Bridge**: High-throughput memory exchange with the Argox engine.
12
+ - 📦 **Isolated Request Context (`ArgosContext`)**: Memory-safe execution context per incoming request.
13
+ - 🧪 **Zero-Socket In-Memory Injection (`inject()`)**: Execute and test request pipelines directly in memory without binding network ports.
14
+ - 🍪 **RFC 6265 Cookies & Multipart Form Engine**: Built-in cookie management and binary multipart/form-data parser.
15
+ - 🛡️ **Semantic HTTP Status & Error Handling**: Comprehensive status codes and structured HTTP errors.
16
+
17
+ ---
18
+
19
+ ## In-Memory Request Injection (`adapter.inject`)
20
+
21
+ The networking layer exposes `inject()` for simulating HTTP requests without opening operating system sockets or network interfaces.
22
+
23
+ ### `InjectOptions`
24
+
25
+ ```typescript
26
+ export interface InjectOptions {
27
+ method?: 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE' | string;
28
+ url: string;
29
+ headers?: Record<string, string>;
30
+ payload?: unknown;
31
+ body?: unknown;
32
+ query?: Record<string, string | number | boolean>;
33
+ }
34
+ ```
35
+
36
+ ### `InjectResponse`
37
+
38
+ ```typescript
39
+ export interface InjectResponse {
40
+ statusCode: number;
41
+ headers: Record<string, string | string[]>;
42
+ body: string;
43
+ json<T = any>(): T;
44
+ }
45
+ ```
46
+
47
+ ---
48
+
49
+ ### Fast Testing Example
50
+
51
+ ```typescript
52
+ import { ArgoxNativeAdapter } from '@argos-js/net';
53
+
54
+ const adapter = new ArgoxNativeAdapter();
55
+
56
+ adapter.useHandler(async (ctx) => {
57
+ const [pathname] = ctx.path.split('?');
58
+
59
+ if (pathname === '/api/ping') {
60
+ return ctx.json({ pong: true, time: Date.now() });
61
+ }
62
+
63
+ return ctx.json({ error: 'Not Found' }, 404);
64
+ });
65
+
66
+ // Run simulated in-memory request without binding any TCP port
67
+ const response = await adapter.inject({
68
+ method: 'GET',
69
+ url: '/api/ping',
70
+ });
71
+
72
+ console.log(response.statusCode); // 200
73
+ console.log(response.json()); // { pong: true, time: ... }
74
+ ```
75
+
76
+ ---
77
+
78
+ ## License
79
+
80
+ MIT
@@ -0,0 +1,66 @@
1
+ import * as http from 'node:http';
2
+ import * as net from 'node:net';
3
+ import { type JsHttpRequest, type JsHttpResponse } from '@argos-js/argox-core';
4
+ import { ArgosContext, type RequestHandler } from './types';
5
+ import { type InjectOptions, type InjectResponse } from './inject';
6
+ /**
7
+ * ArgoxNativeAdapter
8
+ *
9
+ * Orchestrates payload translation between native Rust bindings (argox-core)
10
+ * and the high-level TypeScript middleware / routing system.
11
+ */
12
+ export declare class ArgoxNativeAdapter {
13
+ private handler?;
14
+ private server?;
15
+ private upgradeListeners;
16
+ constructor();
17
+ /**
18
+ * Registers the root router dispatch handler.
19
+ */
20
+ useHandler(handler: RequestHandler): void;
21
+ /**
22
+ * Returns the underlying HTTP server instance if active.
23
+ */
24
+ getServer(): http.Server | undefined;
25
+ /**
26
+ * Registers an HTTP upgrade handler (e.g. for WebSocket connections).
27
+ */
28
+ onUpgrade(listener: (req: http.IncomingMessage, socket: net.Socket, head: Buffer) => void): void;
29
+ /**
30
+ * HTTP listener bridge that accepts incoming requests and routes them through the dispatch pipeline.
31
+ * Resolves only after the server socket successfully starts listening.
32
+ *
33
+ * @param port - Resolved target TCP port.
34
+ * @param host - Network interface address to bind against.
35
+ * @param callback - Optional callback invoked once listening starts.
36
+ * @returns A promise resolving to the active bound port and host.
37
+ */
38
+ listen(port: number, host?: string, callback?: (port: number) => void): Promise<{
39
+ port: number;
40
+ host: string;
41
+ }>;
42
+ /**
43
+ * Stops accepting new network connections on the HTTP server.
44
+ */
45
+ close(): Promise<void>;
46
+ /**
47
+ * Transforms a raw native FFI request into an internal ArgosContext.
48
+ */
49
+ createContext(raw: JsHttpRequest & {
50
+ rawBuffer?: Buffer;
51
+ }): ArgosContext;
52
+ /**
53
+ * Dispatches an incoming native request through the framework handler pipeline.
54
+ *
55
+ * @param raw - HttpRequest payload received from Rust core.
56
+ * @returns HttpResponse struct ready for FFI return boundary.
57
+ */
58
+ dispatch(raw: JsHttpRequest & {
59
+ rawBuffer?: Buffer;
60
+ }): Promise<JsHttpResponse>;
61
+ /**
62
+ * In-memory request injection for fast zero-socket testing.
63
+ */
64
+ inject(options: InjectOptions): Promise<InjectResponse>;
65
+ }
66
+ //# sourceMappingURL=adapter.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"adapter.d.ts","sourceRoot":"","sources":["../src/adapter.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,IAAI,MAAM,WAAW,CAAC;AAClC,OAAO,KAAK,GAAG,MAAM,UAAU,CAAC;AAChC,OAAO,EAGL,KAAK,aAAa,EAClB,KAAK,cAAc,EACpB,MAAM,sBAAsB,CAAC;AAC9B,OAAO,EAAE,YAAY,EAAE,KAAK,cAAc,EAAE,MAAM,SAAS,CAAC;AAC5D,OAAO,EAAkB,KAAK,aAAa,EAAE,KAAK,cAAc,EAAE,MAAM,UAAU,CAAC;AAEnF;;;;;GAKG;AACH,qBAAa,kBAAkB;IAC7B,OAAO,CAAC,OAAO,CAAC,CAAiB;IACjC,OAAO,CAAC,MAAM,CAAC,CAAc;IAC7B,OAAO,CAAC,gBAAgB,CAAoF;;IAQ5G;;OAEG;IACI,UAAU,CAAC,OAAO,EAAE,cAAc,GAAG,IAAI;IAIhD;;OAEG;IACI,SAAS,IAAI,IAAI,CAAC,MAAM,GAAG,SAAS;IAI3C;;OAEG;IACI,SAAS,CAAC,QAAQ,EAAE,CAAC,GAAG,EAAE,IAAI,CAAC,eAAe,EAAE,MAAM,EAAE,GAAG,CAAC,MAAM,EAAE,IAAI,EAAE,MAAM,KAAK,IAAI,GAAG,IAAI;IAOvG;;;;;;;;OAQG;IACI,MAAM,CACX,IAAI,EAAE,MAAM,EACZ,IAAI,GAAE,MAAkB,EACxB,QAAQ,CAAC,EAAE,CAAC,IAAI,EAAE,MAAM,KAAK,IAAI,GAChC,OAAO,CAAC;QAAE,IAAI,EAAE,MAAM,CAAC;QAAC,IAAI,EAAE,MAAM,CAAA;KAAE,CAAC;IA0E1C;;OAEG;IACI,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC;IAgB7B;;OAEG;IACI,aAAa,CAAC,GAAG,EAAE,aAAa,GAAG;QAAE,SAAS,CAAC,EAAE,MAAM,CAAA;KAAE,GAAG,YAAY;IAI/E;;;;;OAKG;IACU,QAAQ,CAAC,GAAG,EAAE,aAAa,GAAG;QAAE,SAAS,CAAC,EAAE,MAAM,CAAA;KAAE,GAAG,OAAO,CAAC,cAAc,CAAC;IA8B3F;;OAEG;IACU,MAAM,CAAC,OAAO,EAAE,aAAa,GAAG,OAAO,CAAC,cAAc,CAAC;CAGrE"}
@@ -0,0 +1,216 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.ArgoxNativeAdapter = void 0;
37
+ const http = __importStar(require("node:http"));
38
+ const argox_core_1 = require("@argos-js/argox-core");
39
+ const types_1 = require("./types");
40
+ const inject_1 = require("./inject");
41
+ /**
42
+ * ArgoxNativeAdapter
43
+ *
44
+ * Orchestrates payload translation between native Rust bindings (argox-core)
45
+ * and the high-level TypeScript middleware / routing system.
46
+ */
47
+ class ArgoxNativeAdapter {
48
+ handler;
49
+ server;
50
+ upgradeListeners = [];
51
+ constructor() {
52
+ if (process.env.DEBUG === 'true' || process.env.ARGOX_DEBUG === 'true') {
53
+ console.log(`[ArgoxNativeAdapter] Initialized with core engine v${(0, argox_core_1.engineVersion)()}`);
54
+ }
55
+ }
56
+ /**
57
+ * Registers the root router dispatch handler.
58
+ */
59
+ useHandler(handler) {
60
+ this.handler = handler;
61
+ }
62
+ /**
63
+ * Returns the underlying HTTP server instance if active.
64
+ */
65
+ getServer() {
66
+ return this.server;
67
+ }
68
+ /**
69
+ * Registers an HTTP upgrade handler (e.g. for WebSocket connections).
70
+ */
71
+ onUpgrade(listener) {
72
+ this.upgradeListeners.push(listener);
73
+ if (this.server) {
74
+ this.server.on('upgrade', listener);
75
+ }
76
+ }
77
+ /**
78
+ * HTTP listener bridge that accepts incoming requests and routes them through the dispatch pipeline.
79
+ * Resolves only after the server socket successfully starts listening.
80
+ *
81
+ * @param port - Resolved target TCP port.
82
+ * @param host - Network interface address to bind against.
83
+ * @param callback - Optional callback invoked once listening starts.
84
+ * @returns A promise resolving to the active bound port and host.
85
+ */
86
+ listen(port, host = '0.0.0.0', callback) {
87
+ return new Promise((resolve, reject) => {
88
+ const bindHost = typeof host === 'string' ? host : '0.0.0.0';
89
+ const server = http.createServer((req, res) => {
90
+ const chunks = [];
91
+ req.on('data', (chunk) => {
92
+ chunks.push(typeof chunk === 'string' ? Buffer.from(chunk) : chunk);
93
+ });
94
+ req.on('end', async () => {
95
+ // Formats raw headers strictly as Record<string, string>
96
+ const headersRecord = {};
97
+ for (const [key, value] of Object.entries(req.headers)) {
98
+ if (Array.isArray(value)) {
99
+ headersRecord[key] = value.join(', ');
100
+ }
101
+ else if (typeof value === 'string') {
102
+ headersRecord[key] = value;
103
+ }
104
+ }
105
+ const bodyBuffer = chunks.length > 0 ? Buffer.concat(chunks) : undefined;
106
+ // Constructs base JsHttpRequest compliant with exactOptionalPropertyTypes
107
+ const rawRequest = {
108
+ id: Math.random().toString(36).substring(7),
109
+ method: req.method?.toUpperCase() ?? 'GET',
110
+ path: req.url ?? '/',
111
+ headers: headersRecord,
112
+ query: {},
113
+ params: {},
114
+ };
115
+ // Attach body only if present to respect exactOptionalPropertyTypes
116
+ if (bodyBuffer && bodyBuffer.length > 0) {
117
+ rawRequest.body = bodyBuffer.toString('utf-8');
118
+ rawRequest.rawBuffer = bodyBuffer;
119
+ }
120
+ const nativeResponse = await this.dispatch(rawRequest);
121
+ const responseHeaders = { ...nativeResponse.headers };
122
+ const setCookieHeader = responseHeaders['set-cookie'] || responseHeaders['Set-Cookie'];
123
+ if (typeof setCookieHeader === 'string' && setCookieHeader.includes('\n')) {
124
+ delete responseHeaders['Set-Cookie'];
125
+ responseHeaders['set-cookie'] = setCookieHeader.split('\n');
126
+ }
127
+ res.writeHead(nativeResponse.statusCode, responseHeaders);
128
+ res.end(nativeResponse.body ?? '');
129
+ });
130
+ });
131
+ this.server = server;
132
+ for (const listener of this.upgradeListeners) {
133
+ server.on('upgrade', listener);
134
+ }
135
+ server.once('error', (err) => {
136
+ reject(err);
137
+ });
138
+ server.listen(port, bindHost, () => {
139
+ const address = server.address();
140
+ const boundPort = typeof address === 'object' && address !== null ? address.port : port;
141
+ if (callback) {
142
+ callback(boundPort);
143
+ }
144
+ resolve({ port: boundPort, host: bindHost });
145
+ });
146
+ });
147
+ }
148
+ /**
149
+ * Stops accepting new network connections on the HTTP server.
150
+ */
151
+ close() {
152
+ return new Promise((resolve, reject) => {
153
+ if (!this.server) {
154
+ resolve();
155
+ return;
156
+ }
157
+ this.server.close((err) => {
158
+ if (err) {
159
+ reject(err);
160
+ }
161
+ else {
162
+ resolve();
163
+ }
164
+ });
165
+ });
166
+ }
167
+ /**
168
+ * Transforms a raw native FFI request into an internal ArgosContext.
169
+ */
170
+ createContext(raw) {
171
+ return new types_1.ArgosContext(raw);
172
+ }
173
+ /**
174
+ * Dispatches an incoming native request through the framework handler pipeline.
175
+ *
176
+ * @param raw - HttpRequest payload received from Rust core.
177
+ * @returns HttpResponse struct ready for FFI return boundary.
178
+ */
179
+ async dispatch(raw) {
180
+ if (!this.handler) {
181
+ return (0, argox_core_1.createNativeResponse)(500, 'Internal Server Error: No handler configured in ArgoxNativeAdapter');
182
+ }
183
+ try {
184
+ const ctx = this.createContext(raw);
185
+ return await this.handler(ctx);
186
+ }
187
+ catch (error) {
188
+ if (error && (error.name === 'ValidationError' || error.isValidationError)) {
189
+ const err = error;
190
+ return {
191
+ statusCode: 422,
192
+ headers: {
193
+ 'content-type': 'application/json',
194
+ 'x-powered-by': 'Argos-JS',
195
+ },
196
+ body: JSON.stringify(err.payload || {
197
+ success: false,
198
+ error: err.message || 'Validation failed',
199
+ fields: err.fields || {},
200
+ }),
201
+ };
202
+ }
203
+ const message = error instanceof Error ? error.message : 'Unknown execution fault';
204
+ console.error('[ArgoxNativeAdapter] Unhandled dispatch exception:', error);
205
+ return (0, argox_core_1.createNativeResponse)(500, `Internal Adapter Error: ${message}`);
206
+ }
207
+ }
208
+ /**
209
+ * In-memory request injection for fast zero-socket testing.
210
+ */
211
+ async inject(options) {
212
+ return (0, inject_1.dispatchInject)((raw) => this.dispatch(raw), options);
213
+ }
214
+ }
215
+ exports.ArgoxNativeAdapter = ArgoxNativeAdapter;
216
+ //# sourceMappingURL=adapter.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"adapter.js","sourceRoot":"","sources":["../src/adapter.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,gDAAkC;AAElC,qDAK8B;AAC9B,mCAA4D;AAC5D,qCAAmF;AAEnF;;;;;GAKG;AACH,MAAa,kBAAkB;IACrB,OAAO,CAAkB;IACzB,MAAM,CAAe;IACrB,gBAAgB,GAAiF,EAAE,CAAC;IAE5G;QACE,IAAI,OAAO,CAAC,GAAG,CAAC,KAAK,KAAK,MAAM,IAAI,OAAO,CAAC,GAAG,CAAC,WAAW,KAAK,MAAM,EAAE,CAAC;YACvE,OAAO,CAAC,GAAG,CAAC,sDAAsD,IAAA,0BAAa,GAAE,EAAE,CAAC,CAAC;QACvF,CAAC;IACH,CAAC;IAED;;OAEG;IACI,UAAU,CAAC,OAAuB;QACvC,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC;IACzB,CAAC;IAED;;OAEG;IACI,SAAS;QACd,OAAO,IAAI,CAAC,MAAM,CAAC;IACrB,CAAC;IAED;;OAEG;IACI,SAAS,CAAC,QAA+E;QAC9F,IAAI,CAAC,gBAAgB,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC;QACrC,IAAI,IAAI,CAAC,MAAM,EAAE,CAAC;YAChB,IAAI,CAAC,MAAM,CAAC,EAAE,CAAC,SAAS,EAAE,QAAQ,CAAC,CAAC;QACtC,CAAC;IACH,CAAC;IAED;;;;;;;;OAQG;IACI,MAAM,CACX,IAAY,EACZ,OAAe,SAAS,EACxB,QAAiC;QAEjC,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AA,uBAAc,EAAC,CAAC,GAAG,EAAE,EAAE,CAAC,IAAI,CAAC,QAAQ,CAAC,GAAG,CAAC,EAAE,OAAO,CAAC,CAAC;IAC9D,CAAC;CACF;AA9LD,gDA8LC"}
@@ -0,0 +1,67 @@
1
+ import { EventEmitter } from 'node:events';
2
+ import { type BinaryStreamOptions } from './native-bridge';
3
+ export type BinaryStreamEventMap = {
4
+ chunk: (chunk: Buffer) => void;
5
+ data: (chunk: Buffer) => void;
6
+ drain: () => void;
7
+ end: () => void;
8
+ error: (err: Error) => void;
9
+ };
10
+ /**
11
+ * High-performance Binary Stream Channel with zero-copy circular pool buffer
12
+ * and native backpressure management (ideal for continuous audio, RTP, and PCM streaming).
13
+ */
14
+ export declare class BinaryStream extends EventEmitter {
15
+ private nativeInstance?;
16
+ private _isNative;
17
+ private _isEnded;
18
+ private _isPaused;
19
+ private jsBuffer;
20
+ private jsBufferedBytes;
21
+ private jsHighWaterMark;
22
+ private jsLowWaterMark;
23
+ private jsInBackpressure;
24
+ constructor(options?: BinaryStreamOptions);
25
+ /**
26
+ * Pushes a chunk into the stream buffer.
27
+ * Returns `true` if the buffer is below highWaterMark.
28
+ * Returns `false` if highWaterMark was reached (backpressure triggered; caller should wait for 'drain').
29
+ */
30
+ write(chunk: Uint8Array | Buffer | string): boolean;
31
+ /**
32
+ * Acknowledges that `bytes` were consumed, releasing backpressure and emitting 'drain' if below lowWaterMark.
33
+ */
34
+ ack(bytes: number): void;
35
+ /**
36
+ * Consumes up to `maxBytes` from the buffered pool.
37
+ */
38
+ read(maxBytes?: number): Buffer | null;
39
+ /**
40
+ * Pauses automatic chunk dispatching.
41
+ */
42
+ pause(): void;
43
+ /**
44
+ * Resumes automatic chunk dispatching.
45
+ */
46
+ resume(): void;
47
+ /**
48
+ * Signals the end of the stream.
49
+ */
50
+ end(): void;
51
+ /**
52
+ * Current number of bytes buffered in the pool.
53
+ */
54
+ get bufferedBytes(): number;
55
+ /**
56
+ * Indicates whether this stream uses the native Rust ring-pool buffer.
57
+ */
58
+ get isNative(): boolean;
59
+ /**
60
+ * Indicates whether the stream has ended.
61
+ */
62
+ get isEnded(): boolean;
63
+ on<K extends keyof BinaryStreamEventMap>(event: K, listener: BinaryStreamEventMap[K]): this;
64
+ once<K extends keyof BinaryStreamEventMap>(event: K, listener: BinaryStreamEventMap[K]): this;
65
+ emit<K extends keyof BinaryStreamEventMap>(event: K, ...args: Parameters<BinaryStreamEventMap[K]>): boolean;
66
+ }
67
+ //# sourceMappingURL=binary-stream.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"binary-stream.d.ts","sourceRoot":"","sources":["../src/binary-stream.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AAC3C,OAAO,EAGL,KAAK,mBAAmB,EAEzB,MAAM,iBAAiB,CAAC;AAEzB,MAAM,MAAM,oBAAoB,GAAG;IACjC,KAAK,EAAE,CAAC,KAAK,EAAE,MAAM,KAAK,IAAI,CAAC;IAC/B,IAAI,EAAE,CAAC,KAAK,EAAE,MAAM,KAAK,IAAI,CAAC;IAC9B,KAAK,EAAE,MAAM,IAAI,CAAC;IAClB,GAAG,EAAE,MAAM,IAAI,CAAC;IAChB,KAAK,EAAE,CAAC,GAAG,EAAE,KAAK,KAAK,IAAI,CAAC;CAC7B,CAAC;AAEF;;;GAGG;AACH,qBAAa,YAAa,SAAQ,YAAY;IAC5C,OAAO,CAAC,cAAc,CAAC,CAA6B;IACpD,OAAO,CAAC,SAAS,CAAS;IAC1B,OAAO,CAAC,QAAQ,CAAS;IACzB,OAAO,CAAC,SAAS,CAAS;IAG1B,OAAO,CAAC,QAAQ,CAAgB;IAChC,OAAO,CAAC,eAAe,CAAK;IAC5B,OAAO,CAAC,eAAe,CAAS;IAChC,OAAO,CAAC,cAAc,CAAS;IAC/B,OAAO,CAAC,gBAAgB,CAAS;gBAErB,OAAO,CAAC,EAAE,mBAAmB;IA4CzC;;;;OAIG;IACI,KAAK,CAAC,KAAK,EAAE,UAAU,GAAG,MAAM,GAAG,MAAM,GAAG,OAAO;IAkC1D;;OAEG;IACI,GAAG,CAAC,KAAK,EAAE,MAAM,GAAG,IAAI;IAc/B;;OAEG;IACI,IAAI,CAAC,QAAQ,CAAC,EAAE,MAAM,GAAG,MAAM,GAAG,IAAI;IA2B7C;;OAEG;IACI,KAAK,IAAI,IAAI;IAOpB;;OAEG;IACI,MAAM,IAAI,IAAI;IAcrB;;OAEG;IACI,GAAG,IAAI,IAAI;IAalB;;OAEG;IACH,IAAW,aAAa,IAAI,MAAM,CAKjC;IAED;;OAEG;IACH,IAAW,QAAQ,IAAI,OAAO,CAE7B;IAED;;OAEG;IACH,IAAW,OAAO,IAAI,OAAO,CAE5B;IAGe,EAAE,CAAC,CAAC,SAAS,MAAM,oBAAoB,EACrD,KAAK,EAAE,CAAC,EACR,QAAQ,EAAE,oBAAoB,CAAC,CAAC,CAAC,GAChC,IAAI;IAIS,IAAI,CAAC,CAAC,SAAS,MAAM,oBAAoB,EACvD,KAAK,EAAE,CAAC,EACR,QAAQ,EAAE,oBAAoB,CAAC,CAAC,CAAC,GAChC,IAAI;IAIS,IAAI,CAAC,CAAC,SAAS,MAAM,oBAAoB,EACvD,KAAK,EAAE,CAAC,EACR,GAAG,IAAI,EAAE,UAAU,CAAC,oBAAoB,CAAC,CAAC,CAAC,CAAC,GAC3C,OAAO;CAGX"}
@@ -0,0 +1,201 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.BinaryStream = void 0;
4
+ const node_events_1 = require("node:events");
5
+ const native_bridge_1 = require("./native-bridge");
6
+ /**
7
+ * High-performance Binary Stream Channel with zero-copy circular pool buffer
8
+ * and native backpressure management (ideal for continuous audio, RTP, and PCM streaming).
9
+ */
10
+ class BinaryStream extends node_events_1.EventEmitter {
11
+ nativeInstance;
12
+ _isNative = false;
13
+ _isEnded = false;
14
+ _isPaused = false;
15
+ // JS Fallback state
16
+ jsBuffer = [];
17
+ jsBufferedBytes = 0;
18
+ jsHighWaterMark;
19
+ jsLowWaterMark;
20
+ jsInBackpressure = false;
21
+ constructor(options) {
22
+ super();
23
+ const hwm = options?.highWaterMark ?? 64 * 1024;
24
+ const lwm = options?.lowWaterMark ?? Math.floor(hwm / 4);
25
+ this.jsHighWaterMark = hwm;
26
+ this.jsLowWaterMark = lwm;
27
+ const useNative = !options?.forceJsFallback && (0, native_bridge_1.isNativeNetAvailable)();
28
+ if (useNative) {
29
+ const bindings = (0, native_bridge_1.getNativeNetBindings)();
30
+ try {
31
+ const nativeStream = new bindings.NativeBinaryStream({
32
+ highWaterMark: hwm,
33
+ lowWaterMark: lwm,
34
+ });
35
+ this.nativeInstance = nativeStream;
36
+ this._isNative = true;
37
+ nativeStream.onChunk((buf) => {
38
+ this.emit('chunk', buf);
39
+ this.emit('data', buf);
40
+ });
41
+ nativeStream.onDrain(() => {
42
+ this.emit('drain');
43
+ });
44
+ nativeStream.onEnd(() => {
45
+ this._isEnded = true;
46
+ this.emit('end');
47
+ });
48
+ return;
49
+ }
50
+ catch {
51
+ // Fall back to JavaScript implementation
52
+ }
53
+ }
54
+ this._isNative = false;
55
+ }
56
+ /**
57
+ * Pushes a chunk into the stream buffer.
58
+ * Returns `true` if the buffer is below highWaterMark.
59
+ * Returns `false` if highWaterMark was reached (backpressure triggered; caller should wait for 'drain').
60
+ */
61
+ write(chunk) {
62
+ if (this._isEnded) {
63
+ this.emit('error', new Error('Cannot write to ended BinaryStream'));
64
+ return false;
65
+ }
66
+ const buf = Buffer.isBuffer(chunk)
67
+ ? chunk
68
+ : typeof chunk === 'string'
69
+ ? Buffer.from(chunk, 'utf-8')
70
+ : Buffer.from(chunk);
71
+ if (this._isNative && this.nativeInstance) {
72
+ return this.nativeInstance.pushChunk(buf);
73
+ }
74
+ // JavaScript Fallback
75
+ this.jsBuffer.push(buf);
76
+ this.jsBufferedBytes += buf.length;
77
+ let canContinue = true;
78
+ if (this.jsBufferedBytes >= this.jsHighWaterMark) {
79
+ this.jsInBackpressure = true;
80
+ canContinue = false;
81
+ }
82
+ if (!this._isPaused) {
83
+ this.emit('chunk', buf);
84
+ this.emit('data', buf);
85
+ }
86
+ return canContinue;
87
+ }
88
+ /**
89
+ * Acknowledges that `bytes` were consumed, releasing backpressure and emitting 'drain' if below lowWaterMark.
90
+ */
91
+ ack(bytes) {
92
+ if (this._isNative && this.nativeInstance) {
93
+ this.nativeInstance.ack(bytes);
94
+ return;
95
+ }
96
+ // JavaScript Fallback
97
+ this.jsBufferedBytes = Math.max(0, this.jsBufferedBytes - bytes);
98
+ if (this.jsInBackpressure && this.jsBufferedBytes <= this.jsLowWaterMark) {
99
+ this.jsInBackpressure = false;
100
+ this.emit('drain');
101
+ }
102
+ }
103
+ /**
104
+ * Consumes up to `maxBytes` from the buffered pool.
105
+ */
106
+ read(maxBytes) {
107
+ if (this._isNative && this.nativeInstance) {
108
+ return this.nativeInstance.readChunk(maxBytes);
109
+ }
110
+ // JavaScript Fallback
111
+ if (this.jsBuffer.length === 0) {
112
+ return null;
113
+ }
114
+ const limit = maxBytes ?? 64 * 1024;
115
+ const combined = Buffer.concat(this.jsBuffer);
116
+ const toTake = Math.min(limit, combined.length);
117
+ const result = combined.subarray(0, toTake);
118
+ const remainder = combined.subarray(toTake);
119
+ this.jsBuffer = remainder.length > 0 ? [remainder] : [];
120
+ this.jsBufferedBytes = remainder.length;
121
+ if (this.jsInBackpressure && this.jsBufferedBytes <= this.jsLowWaterMark) {
122
+ this.jsInBackpressure = false;
123
+ this.emit('drain');
124
+ }
125
+ return result;
126
+ }
127
+ /**
128
+ * Pauses automatic chunk dispatching.
129
+ */
130
+ pause() {
131
+ this._isPaused = true;
132
+ if (this._isNative && this.nativeInstance) {
133
+ this.nativeInstance.pause();
134
+ }
135
+ }
136
+ /**
137
+ * Resumes automatic chunk dispatching.
138
+ */
139
+ resume() {
140
+ this._isPaused = false;
141
+ if (this._isNative && this.nativeInstance) {
142
+ this.nativeInstance.resume();
143
+ }
144
+ else {
145
+ // Flush buffered chunks in JS fallback
146
+ while (this.jsBuffer.length > 0 && !this._isPaused) {
147
+ const chunk = this.jsBuffer.shift();
148
+ this.emit('chunk', chunk);
149
+ this.emit('data', chunk);
150
+ }
151
+ }
152
+ }
153
+ /**
154
+ * Signals the end of the stream.
155
+ */
156
+ end() {
157
+ if (this._isEnded) {
158
+ return;
159
+ }
160
+ this._isEnded = true;
161
+ if (this._isNative && this.nativeInstance) {
162
+ this.nativeInstance.end();
163
+ }
164
+ else {
165
+ this.emit('end');
166
+ }
167
+ }
168
+ /**
169
+ * Current number of bytes buffered in the pool.
170
+ */
171
+ get bufferedBytes() {
172
+ if (this._isNative && this.nativeInstance) {
173
+ return this.nativeInstance.bufferedBytes;
174
+ }
175
+ return this.jsBufferedBytes;
176
+ }
177
+ /**
178
+ * Indicates whether this stream uses the native Rust ring-pool buffer.
179
+ */
180
+ get isNative() {
181
+ return this._isNative;
182
+ }
183
+ /**
184
+ * Indicates whether the stream has ended.
185
+ */
186
+ get isEnded() {
187
+ return this._isEnded;
188
+ }
189
+ // Typed EventEmitter overrides
190
+ on(event, listener) {
191
+ return super.on(event, listener);
192
+ }
193
+ once(event, listener) {
194
+ return super.once(event, listener);
195
+ }
196
+ emit(event, ...args) {
197
+ return super.emit(event, ...args);
198
+ }
199
+ }
200
+ exports.BinaryStream = BinaryStream;
201
+ //# sourceMappingURL=binary-stream.js.map