-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.d.ts
More file actions
490 lines (431 loc) · 14.7 KB
/
index.d.ts
File metadata and controls
490 lines (431 loc) · 14.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
// Type definitions for api-ape
// Project: https://github.com/codemeasandwich/api-ape
import { Server as HttpServer } from 'http'
import { IncomingMessage } from 'http'
/**
* WebSocket instance type (compatible with ws library and native implementations)
*/
export interface ApeWebSocket {
send(data: string | Buffer): void
close(code?: number, reason?: string): void
on(event: 'message', handler: (data: Buffer) => void): this
on(event: 'close', handler: () => void): this
on(event: 'error', handler: (err: Error) => void): this
readonly readyState: number
readonly CONNECTING: 0
readonly OPEN: 1
readonly CLOSING: 2
readonly CLOSED: 3
}
// =============================================================================
// SERVER TYPES
// =============================================================================
/**
* Controller context available as `this` inside controller functions
*/
export interface ControllerContext {
/** Publish to channel subscribers */
publish(channel: string, data: any): void
/** Get count of connected clients */
online(): number
/** Get array of connected clientIds */
getClients(): string[]
/** Unique ID of the calling client (generated by api-ape) */
clientId: string
/** Session ID from cookie (set by outer framework, may be null) */
sessionId: string | null
/** Original HTTP request */
req: IncomingMessage
/** WebSocket instance */
socket: ApeWebSocket
/** Parsed user-agent info */
agent: {
browser: { name?: string; version?: string }
os: { name?: string; version?: string }
device: { type?: string; vendor?: string; model?: string }
}
/** Custom embedded values from onConnect */
[key: string]: any
}
/**
* Controller function type
*/
export type ControllerFunction<T = any, R = any> = (
this: ControllerContext,
data: T
) => R | Promise<R>
/**
* Send function provided to onConnect
*/
export type SendFunction = {
(type: string, data: any): void
toString(): string
}
/**
* After hook returned from onReceive/onSend
*/
export type AfterHook = (err: Error | null, result: any) => void
/**
* Connection lifecycle hooks returned from onConnect
*/
export interface ConnectionHandlers {
/** Values to embed into controller context */
embed?: Record<string, any>
/** Called before processing incoming message, return after hook */
onReceive?: (queryId: string, data: any, type: string) => AfterHook | void
/** Called before sending message, return after hook */
onSend?: (data: any, type: string) => AfterHook | void
/** Called on error */
onError?: (errorString: string) => void
/** Called when client disconnects */
onDisconnect?: () => void
}
/**
* onConnect callback signature
*/
export type OnConnectCallback = (
socket: ApeWebSocket,
req: IncomingMessage,
send: SendFunction
) => ConnectionHandlers | void
/**
* Server options for ape()
*/
export interface ApeServerOptions {
/** Directory containing controller files */
where: string
/** Connection lifecycle hook */
onConnect?: OnConnectCallback
}
// =============================================================================
// 🌲 FOREST - DISTRIBUTED MESH TYPES
// =============================================================================
/**
* Supported database client types for Forest adapters
*/
export type ForestDatabaseClient =
| RedisClient
| MongoClient
| PostgresPool
| SupabaseClient
| FirebaseDatabase
| ForestCustomAdapter
/** Redis client (node-redis or ioredis) */
export interface RedisClient {
duplicate(): RedisClient
publish(channel: string, message: string): Promise<number>
subscribe(channel: string): Promise<void>
on(event: string, handler: (...args: any[]) => void): void
}
/** MongoDB client */
export interface MongoClient {
db(name?: string): any
}
/** PostgreSQL pool (pg) */
export interface PostgresPool {
query(text: string, values?: any[]): Promise<any>
connect(): Promise<any>
}
/** Supabase client */
export interface SupabaseClient {
from(table: string): any
channel(name: string): any
removeChannel(channel: any): Promise<void>
}
/** Firebase Realtime Database */
export interface FirebaseDatabase {
ref(path: string): any
goOnline?(): void
app?: any
}
/**
* Forest adapter instance interface
*/
export interface ForestAdapterInstance {
/** This server's unique ID */
readonly serverId: string
/** Join the distributed mesh */
join(serverId?: string): Promise<void>
/** Leave the mesh and cleanup */
leave(): Promise<void>
/** Client-to-server lookup operations */
lookup: {
/** Register a client on this server */
add(clientId: string): Promise<void>
/** Find which server owns a client */
read(clientId: string): Promise<string | null>
/** Remove a client mapping (must own it) */
remove(clientId: string): Promise<void>
}
/** Inter-server channel operations */
channels: {
/** Push message to a server's channel (empty string = broadcast) */
push(serverId: string, message: any): Promise<void>
/** Subscribe to a server's channel, returns unsubscribe function */
pull(serverId: string, handler: (message: any, senderServerId: string) => void): Promise<() => Promise<void>>
}
}
/**
* Custom adapter interface for implementing your own Forest adapter
*/
export interface ForestCustomAdapter {
join(serverId: string): Promise<void>
leave(): Promise<void>
lookup: {
add(clientId: string): Promise<void>
read(clientId: string): Promise<string | null>
remove(clientId: string): Promise<void>
}
channels: {
push(serverId: string, message: any): Promise<void>
pull(serverId: string, handler: (message: any, senderServerId: string) => void): Promise<() => Promise<void>>
}
}
/**
* Options for joinVia()
*/
export interface ForestOptions {
/** Prefix for keys/tables (default: 'apes') */
namespace?: string
/** Custom server ID (default: auto-generated) */
serverId?: string
}
/**
* Initialize api-ape on a Node.js HTTP/HTTPS server
*
* V3 Breaking Change:
* Old: const ape = require('api-ape')
* New: const { ape } = require('api-ape')
*/
declare function ape(server: HttpServer, options: ApeServerOptions): void
declare namespace ape {
/**
* Publish to channel subscribers
* Supports chained syntax: ape.publish.channel.name(data)
* Or direct call: ape.publish('/channel', data)
*/
export const publish: {
(channel: string, data: any): void
[key: string]: any
}
/**
* Read-only Map of connected clients
* Each ClientWrapper provides: clientId, sessionId, embed, agent, send(type, data)
*/
export const clients: ReadonlyMap<string, ClientWrapper>
// =========================================================================
// 🌲 FOREST - DISTRIBUTED MESH
// =========================================================================
/**
* Join the distributed mesh for multi-server coordination.
* Pass any supported database client - APE auto-detects the type.
*
* @example
* // Redis
* ape.joinVia(redisClient);
*
* // With options
* ape.joinVia(mongoClient, { namespace: 'myapp', serverId: 'srv-1' });
*
* // Custom adapter
* ape.joinVia({ join, leave, lookup, channels });
*/
export function joinVia(client: ForestDatabaseClient, options?: ForestOptions): Promise<ForestAdapterInstance>
/**
* Leave the distributed mesh gracefully.
* Removes all client mappings and unsubscribes from channels.
*/
export function leaveCluster(): Promise<void>
/**
* Current Forest adapter instance (null if not joined)
*/
export const cluster: ForestAdapterInstance | null
/**
* This server's ID in the cluster (null if not joined)
*/
export const serverId: string | null
// Browser client methods (available when imported in browser context)
/** Subscribe to broadcasts from the server */
export function on<T = any>(type: string, handler: (message: { err?: Error; type: string; data: T }) => void): void
/** Subscribe to connection state changes. Returns unsubscribe function. */
export function onConnectionChange(handler: (state: 'offline' | 'walled' | 'disconnected' | 'connecting' | 'connected') => void): () => void
/** Current transport type (read-only) */
export const transport: 'websocket' | 'polling' | null
/** Call any server function dynamically (browser only) */
export function message<T = any, R = any>(data?: T): Promise<R>
}
// =============================================================================
// SERVER-SIDE CLIENT (api - same interface as browser)
// =============================================================================
/**
* Server-side client for connecting to other api-ape servers
* 100% identical interface to the browser client
*
* @example
* import api from 'api-ape'
*
* // Configure connection (or set APE_SERVER env)
* api.connect('other-server', 3000) // → ws://other-server:3000/api/ape
*
* // Same usage as browser
* const result = await api.hello('World')
* api.on('message', (data) => console.log(data))
*/
export interface ApeServerClient extends ApeSender {
/** Subscribe to broadcasts from the remote server */
on<T = any>(type: string, handler: MessageHandler<T>): void
on(handler: MessageHandler): void
/** Subscribe to connection state changes */
onConnectionChange(handler: (state: ConnectionState) => void): () => void
/** Connect to a server using host and port */
connect(host: string, port: number): void
/** Close the connection */
close(): void
/** Current transport type (read-only) */
readonly transport: 'websocket' | null
}
/**
* The api client - works identically on browser and server
*/
declare const api: ApeServerClient
// Named export for V3 (Server usage: const { ape } = require('api-ape'))
export { ape, api }
// Default export: api client (same interface on browser and server)
export default api
// =============================================================================
// BROWSER CLIENT (Default export in browser context)
// =============================================================================
/**
* Unified browser client - auto-initializing Proxy that buffers calls until ready.
*
* In browser context (via bundler or direct import), `import api from 'api-ape'`
* returns this client instead of the server function.
*
* Usage:
* import api from 'api-ape'
* api.message({ text: 'Hello!' }) // Buffered until connected
* api.on('message', (data) => {}) // Listen for broadcasts
* api.onConnectionChange((state) => {}) // Connection state updates
*/
export interface ApeBrowserClient extends ApeSender {
/** Subscribe to broadcasts from the server */
on<T = any>(type: string, handler: MessageHandler<T>): void
/** Subscribe to connection state changes. Returns unsubscribe function. */
onConnectionChange(handler: (state: ConnectionState) => void): () => void
/** Current transport type (read-only) */
readonly transport: TransportType | null
}
// =============================================================================
// CLIENT TYPES
// =============================================================================
/**
* Connection state enum values
*/
export type ConnectionState = 'offline' | 'walled' | 'disconnected' | 'connecting' | 'connected' | 'closing'
/**
* Connection state enum object
*/
export declare const ConnectionState: {
Offline: 'offline'
Walled: 'walled'
Disconnected: 'disconnected'
Connecting: 'connecting'
Connected: 'connected'
Closing: 'closing'
}
/**
* Message received from server
*/
export interface ReceivedMessage<T = any> {
err?: Error | string
type: string
data: T
}
/**
* Message handler callback
*/
export type MessageHandler<T = any> = (message: ReceivedMessage<T>) => void
/**
* Proxy-based sender - any property access creates a callable path
* Example: sender.users.list() calls type="/users/list"
*/
export interface ApeSender {
[key: string]: ApeSender & (<T = any, R = any>(data?: T) => Promise<R>)
}
/**
* Set receiver for specific message type or all messages
*/
export type SetOnReceiver = {
(type: string, handler: MessageHandler): void
(handler: MessageHandler): void
}
/**
* Connected client interface
*/
export interface ApeClient {
sender: ApeSender
setOnReceiver: SetOnReceiver
/** Subscribe to connection state changes. Returns unsubscribe function. */
onConnectionChange: (handler: (state: ConnectionState) => void) => () => void
/** Current transport type (read-only) */
readonly transport: TransportType | null
}
/**
* Transport type for connection
*/
export type TransportType = 'websocket' | 'polling'
/**
* Connect socket function with configuration methods
*/
export interface ConnectSocket {
(): ApeClient
/** Enable auto-reconnection on disconnect */
autoReconnect(): void
/** Connection state enum */
ConnectionState: typeof ConnectionState
}
/**
* Client module default export
*/
declare const connectSocket: ConnectSocket
export { connectSocket }
// =============================================================================
// CLIENTS MODULE
// =============================================================================
export declare const clients: ReadonlyMap<string, ClientWrapper>
/**
* Chainable send function for client.send
* Supports both direct and chained syntax:
* - client.send('news/banking', data)
* - client.send.news.banking(data)
*/
export interface ClientSendFunction {
/** Direct call: send(type, data) */
(type: string, data: any): void
/** Chained access for path building */
[key: string]: ClientSendFunction & ((data?: any) => void)
}
/**
* Client wrapper providing client info and send function
*/
export interface ClientWrapper {
/** Unique client identifier */
readonly clientId: string
/** Session ID from cookie (set by outer framework) */
readonly sessionId: string | null
/** Embedded values from onConnect */
readonly embed: Record<string, any>
/** Parsed user-agent info */
readonly agent: {
browser: { name?: string; version?: string }
os: { name?: string; version?: string }
device: { type?: string; vendor?: string; model?: string }
}
/**
* Send a message to this specific client
* Supports both direct and chained syntax:
* - client.send('news/banking', data)
* - client.send.news.banking(data)
*/
send: ClientSendFunction
}