@kitsuden/sdk 0.0.0-stage → 0.9.0-beta

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.
@@ -0,0 +1,2 @@
1
+ "use strict";var a=Object.defineProperty;var o=Object.getOwnPropertyDescriptor;var d=Object.getOwnPropertyNames;var l=Object.prototype.hasOwnProperty;var h=(r,e)=>{for(var t in e)a(r,t,{get:e[t],enumerable:!0})},p=(r,e,t,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of d(e))!l.call(r,n)&&n!==t&&a(r,n,{get:()=>e[n],enumerable:!(s=o(e,n))||s.enumerable});return r};var u=r=>p(a({},"__esModule",{value:!0}),r);var v={};h(v,{KitsudenRealtime:()=>i,createRealtime:()=>g,logSafe:()=>c});module.exports=u(v);function c(r){let e=String(r??"").replace(/\n|\r/g," ").replace(/[\u0000-\u001f\u007f-\u009f\u2028\u2029]/g," ");return e.length>500?`${e.slice(0,500)}\u2026`:e}var i=class{url;ws=null;state="disconnected";clientId=null;userId=null;getClientId(){return this.clientId}getUserId(){return this.userId}channelHandlers=new Map;presenceHandlers=new Map;stateHandlers=new Set;reconnectAttempts=0;maxReconnectAttempts=10;reconnectDelay=1e3;reconnectTimer=null;pendingChannels=new Set;pendingRooms=new Set;pingInterval=null;pingTimeout=3e4;constructor(e){this.url=e}async connect(){if(!(this.state==="connected"||this.state==="connecting"))return new Promise((e,t)=>{this.setState("connecting");try{this.ws=new WebSocket(this.url),this.ws.onopen=()=>{this.reconnectAttempts=0,this.startHeartbeat()},this.ws.onmessage=s=>{this.handleMessage(s.data),this.state==="connecting"&&(this.setState("connected"),this.resubscribe(),e())},this.ws.onclose=()=>{this.stopHeartbeat(),this.state!=="disconnected"&&this.scheduleReconnect()},this.ws.onerror=s=>{console.error("[KitsudenRealtime] WebSocket error"),this.state==="connecting"&&t(new Error("Failed to connect"))}}catch(s){this.setState("disconnected"),t(s)}})}disconnect(){this.setState("disconnected"),this.stopHeartbeat(),this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null),this.ws&&(this.ws.close(),this.ws=null),this.clientId=null,this.userId=null}getState(){return this.state}onStateChange(e){return this.stateHandlers.add(e),()=>{this.stateHandlers.delete(e)}}subscribe(e,t){return this.channelHandlers.has(e)||this.channelHandlers.set(e,new Set),this.channelHandlers.get(e).add(t),this.pendingChannels.add(e),this.state==="connected"&&this.send({type:"subscribe",channel:e}),()=>{let n=this.channelHandlers.get(e);n&&(n.delete(t),n.size===0&&(this.channelHandlers.delete(e),this.pendingChannels.delete(e),this.state==="connected"&&this.send({type:"unsubscribe",channel:e})))}}subscribeToDataset(e,t){return this.subscribe(`table:${e}`,t)}subscribeToEntry(e,t){return this.subscribe(`entry:${e}`,t)}joinRoom(e){this.pendingRooms.add(e),this.state==="connected"&&this.send({type:"presence:join",room:e})}leaveRoom(e){this.pendingRooms.delete(e),this.presenceHandlers.delete(e),this.state==="connected"&&this.send({type:"presence:leave",room:e})}onPresence(e,t){return this.presenceHandlers.has(e)||this.presenceHandlers.set(e,new Set),this.presenceHandlers.get(e).add(t),()=>{let n=this.presenceHandlers.get(e);n&&(n.delete(t),n.size===0&&this.presenceHandlers.delete(e))}}setState(e){if(this.state!==e){this.state=e;for(let t of this.stateHandlers)try{t(e)}catch{}}}send(e){this.ws&&this.ws.readyState===WebSocket.OPEN&&this.ws.send(JSON.stringify(e))}handleMessage(e){let t;try{t=JSON.parse(e)}catch{return}switch(t.type){case"connected":this.clientId=t.clientId??null,this.userId=t.userId??null;break;case"message":if(t.channel&&t.data){let s=this.channelHandlers.get(t.channel);if(s)for(let n of s)try{n(t.data)}catch{}}break;case"presence":if(t.room&&t.users){let s=this.presenceHandlers.get(t.room);if(s)for(let n of s)try{n(t.users)}catch{}}break;case"subscribed":case"unsubscribed":break;case"pong":break;case"error":console.warn("[KitsudenRealtime] Server error:",c(t.message).replace(/\n|\r/g,""));break}}resubscribe(){for(let e of this.pendingChannels)this.send({type:"subscribe",channel:e});for(let e of this.pendingRooms)this.send({type:"presence:join",room:e})}scheduleReconnect(){if(this.reconnectAttempts>=this.maxReconnectAttempts){this.setState("disconnected"),console.error("[KitsudenRealtime] Max reconnection attempts reached");return}this.setState("reconnecting"),this.reconnectAttempts++;let e=Math.min(this.reconnectDelay*Math.pow(2,this.reconnectAttempts-1),3e4);console.log(`[KitsudenRealtime] Reconnecting in ${e}ms (attempt ${this.reconnectAttempts})`),this.reconnectTimer=setTimeout(()=>{this.connect().catch(()=>{})},e)}startHeartbeat(){this.pingInterval=setInterval(()=>{this.send({type:"ping"})},this.pingTimeout)}stopHeartbeat(){this.pingInterval&&(clearInterval(this.pingInterval),this.pingInterval=null)}};function g(r){let e=r.replace(/^http:/,"ws:").replace(/^https:/,"wss:").replace(/\/$/,"")+"/api/realtime";return new i(e)}
2
+ //# sourceMappingURL=realtime.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/realtime.ts"],"sourcesContent":["/**\n * @kitsuden/sdk — Real-time Module\n *\n * Provides WebSocket connection management and Live Query subscriptions.\n *\n * Usage:\n * import { KitsudenRealtime, createRealtime } from '@kitsuden/sdk/realtime';\n *\n * const rt = createRealtime('http://localhost:3000');\n * await rt.connect();\n *\n * // Subscribe to all changes in a dataset\n * const unsub = rt.subscribe('table:matches', (data) => {\n * console.log('Mutation:', data.event, data.entry);\n * });\n *\n * // Presence\n * rt.joinRoom('editor:doc-123');\n * rt.onPresence('editor:doc-123', (users) => {\n * console.log('Users online:', users);\n * });\n *\n * // Cleanup\n * unsub();\n * rt.disconnect();\n */\n\nexport type ConnectionState = \"disconnected\" | \"connecting\" | \"connected\" | \"reconnecting\";\n\nexport interface MutationEvent {\n event: \"insert\" | \"update\" | \"delete\";\n datasetId: string;\n entry: Record<string, unknown>;\n timestamp: number;\n}\n\nexport interface PresenceUser {\n id: string;\n name?: string;\n}\n\nexport interface PresenceEvent {\n room: string;\n users: PresenceUser[];\n count: number;\n}\n\ntype MessageHandler = (data: MutationEvent) => void;\ntype PresenceHandler = (users: PresenceUser[]) => void;\ntype StateHandler = (state: ConnectionState) => void;\n\ninterface InternalMessage {\n type: string;\n channel?: string;\n room?: string;\n data?: unknown;\n users?: PresenceUser[];\n count?: number;\n clientId?: string;\n userId?: string | null;\n message?: string;\n timestamp?: number;\n}\n\n/** Longest server text that reaches the console. */\nconst MAX_LOGGED_LENGTH = 500;\n\n/**\n * Server text made safe for one console line: control characters and line\n * separators become spaces (a message cannot forge extra log lines) and it is capped.\n */\nexport function logSafe(value: unknown): string {\n const text = String(value ?? \"\")\n .replace(/\\n|\\r/g, \" \")\n // eslint-disable-next-line no-control-regex\n .replace(/[\\u0000-\\u001f\\u007f-\\u009f\\u2028\\u2029]/g, \" \");\n return text.length > MAX_LOGGED_LENGTH ? `${text.slice(0, MAX_LOGGED_LENGTH)}…` : text;\n}\n\nexport class KitsudenRealtime {\n private url: string;\n private ws: WebSocket | null = null;\n private state: ConnectionState = \"disconnected\";\n private clientId: string | null = null;\n private userId: string | null = null;\n\n /** Get the server-assigned client ID */\n getClientId(): string | null {\n return this.clientId;\n }\n\n /** Get the authenticated user ID (if any) */\n getUserId(): string | null {\n return this.userId;\n }\n\n // Subscriptions\n private channelHandlers = new Map<string, Set<MessageHandler>>();\n private presenceHandlers = new Map<string, Set<PresenceHandler>>();\n private stateHandlers = new Set<StateHandler>();\n\n // Reconnection\n private reconnectAttempts = 0;\n private readonly maxReconnectAttempts = 10;\n private readonly reconnectDelay = 1000;\n private reconnectTimer: ReturnType<typeof setTimeout> | null = null;\n\n // Pending subscriptions (to restore after reconnect)\n private pendingChannels = new Set<string>();\n private pendingRooms = new Set<string>();\n\n // Heartbeat\n private pingInterval: ReturnType<typeof setInterval> | null = null;\n private readonly pingTimeout = 30000;\n\n constructor(url: string) {\n this.url = url;\n }\n\n // ═══════════════════════════════════════════════════════════\n // Connection Management\n // ═══════════════════════════════════════════════════════════\n\n /**\n * Connect to the WebSocket server.\n * Returns a promise that resolves when connected.\n */\n async connect(): Promise<void> {\n if (this.state === \"connected\" || this.state === \"connecting\") {\n return;\n }\n\n return new Promise((resolve, reject) => {\n this.setState(\"connecting\");\n\n try {\n this.ws = new WebSocket(this.url);\n\n this.ws.onopen = () => {\n this.reconnectAttempts = 0;\n this.startHeartbeat();\n // Wait for \"connected\" message from server\n };\n\n this.ws.onmessage = (event: MessageEvent) => {\n this.handleMessage(event.data as string);\n\n // Resolve promise on first connection\n if (this.state === \"connecting\") {\n this.setState(\"connected\");\n this.resubscribe();\n resolve();\n }\n };\n\n this.ws.onclose = () => {\n this.stopHeartbeat();\n if (this.state !== \"disconnected\") {\n this.scheduleReconnect();\n }\n };\n\n this.ws.onerror = (_error: Event) => {\n console.error(\"[KitsudenRealtime] WebSocket error\");\n if (this.state === \"connecting\") {\n reject(new Error(\"Failed to connect\"));\n }\n };\n } catch (err) {\n this.setState(\"disconnected\");\n reject(err);\n }\n });\n }\n\n /**\n * Disconnect from the WebSocket server.\n */\n disconnect(): void {\n this.setState(\"disconnected\");\n this.stopHeartbeat();\n\n if (this.reconnectTimer) {\n clearTimeout(this.reconnectTimer);\n this.reconnectTimer = null;\n }\n\n if (this.ws) {\n this.ws.close();\n this.ws = null;\n }\n\n this.clientId = null;\n this.userId = null;\n }\n\n /**\n * Get current connection state.\n */\n getState(): ConnectionState {\n return this.state;\n }\n\n /**\n * Listen for connection state changes.\n */\n onStateChange(handler: StateHandler): () => void {\n this.stateHandlers.add(handler);\n return () => {\n this.stateHandlers.delete(handler);\n };\n }\n\n // ═══════════════════════════════════════════════════════════\n // Channel Subscriptions (Live Queries)\n // ═══════════════════════════════════════════════════════════\n\n /**\n * Subscribe to a channel for live updates.\n *\n * @param channel Channel name (e.g., \"table:datasetId\" or \"entry:entryId\")\n * @param handler Callback for mutation events\n * @returns Unsubscribe function\n */\n subscribe(channel: string, handler: MessageHandler): () => void {\n // Track handler\n if (!this.channelHandlers.has(channel)) {\n this.channelHandlers.set(channel, new Set());\n }\n const handlers = this.channelHandlers.get(channel)!;\n handlers.add(handler);\n\n // Track for reconnection\n this.pendingChannels.add(channel);\n\n // Send subscription request if connected\n if (this.state === \"connected\") {\n this.send({ type: \"subscribe\", channel });\n }\n\n // Return unsubscribe function\n return () => {\n const h = this.channelHandlers.get(channel);\n if (h) {\n h.delete(handler);\n if (h.size === 0) {\n this.channelHandlers.delete(channel);\n this.pendingChannels.delete(channel);\n if (this.state === \"connected\") {\n this.send({ type: \"unsubscribe\", channel });\n }\n }\n }\n };\n }\n\n /**\n * Convenience method to subscribe to a dataset's changes.\n */\n subscribeToDataset(datasetId: string, handler: MessageHandler): () => void {\n return this.subscribe(`table:${datasetId}`, handler);\n }\n\n /**\n * Convenience method to subscribe to a single entry's changes.\n */\n subscribeToEntry(entryId: string, handler: MessageHandler): () => void {\n return this.subscribe(`entry:${entryId}`, handler);\n }\n\n // ═══════════════════════════════════════════════════════════\n // Presence\n // ═══════════════════════════════════════════════════════════\n\n /**\n * Join a presence room to track who's online.\n */\n joinRoom(room: string): void {\n this.pendingRooms.add(room);\n if (this.state === \"connected\") {\n this.send({ type: \"presence:join\", room });\n }\n }\n\n /**\n * Leave a presence room.\n */\n leaveRoom(room: string): void {\n this.pendingRooms.delete(room);\n this.presenceHandlers.delete(room);\n if (this.state === \"connected\") {\n this.send({ type: \"presence:leave\", room });\n }\n }\n\n /**\n * Listen for presence updates in a room.\n */\n onPresence(room: string, handler: PresenceHandler): () => void {\n if (!this.presenceHandlers.has(room)) {\n this.presenceHandlers.set(room, new Set());\n }\n const handlers = this.presenceHandlers.get(room)!;\n handlers.add(handler);\n\n return () => {\n const h = this.presenceHandlers.get(room);\n if (h) {\n h.delete(handler);\n if (h.size === 0) {\n this.presenceHandlers.delete(room);\n }\n }\n };\n }\n\n // ═══════════════════════════════════════════════════════════\n // Internal Methods\n // ═══════════════════════════════════════════════════════════\n\n private setState(state: ConnectionState): void {\n if (this.state === state) return;\n this.state = state;\n for (const handler of this.stateHandlers) {\n try {\n handler(state);\n } catch {\n // ignore handler errors\n }\n }\n }\n\n private send(data: Record<string, unknown>): void {\n if (this.ws && this.ws.readyState === WebSocket.OPEN) {\n this.ws.send(JSON.stringify(data));\n }\n }\n\n private handleMessage(raw: string): void {\n let msg: InternalMessage;\n try {\n msg = JSON.parse(raw) as InternalMessage;\n } catch {\n return;\n }\n\n switch (msg.type) {\n case \"connected\":\n this.clientId = msg.clientId ?? null;\n this.userId = msg.userId ?? null;\n break;\n\n case \"message\":\n if (msg.channel && msg.data) {\n const handlers = this.channelHandlers.get(msg.channel);\n if (handlers) {\n for (const handler of handlers) {\n try {\n handler(msg.data as MutationEvent);\n } catch {\n // ignore handler errors\n }\n }\n }\n }\n break;\n\n case \"presence\":\n if (msg.room && msg.users) {\n const handlers = this.presenceHandlers.get(msg.room);\n if (handlers) {\n for (const handler of handlers) {\n try {\n handler(msg.users);\n } catch {\n // ignore handler errors\n }\n }\n }\n }\n break;\n\n case \"subscribed\":\n case \"unsubscribed\":\n // Acknowledgments — could track pending state\n break;\n\n case \"pong\":\n // Heartbeat response\n break;\n\n case \"error\":\n // logSafe already removes line breaks; the replace here is the form CodeQL recognises.\n console.warn(\n \"[KitsudenRealtime] Server error:\",\n logSafe(msg.message).replace(/\\n|\\r/g, \"\")\n );\n break;\n }\n }\n\n private resubscribe(): void {\n // Restore channel subscriptions\n for (const channel of this.pendingChannels) {\n this.send({ type: \"subscribe\", channel });\n }\n\n // Restore presence rooms\n for (const room of this.pendingRooms) {\n this.send({ type: \"presence:join\", room });\n }\n }\n\n private scheduleReconnect(): void {\n if (this.reconnectAttempts >= this.maxReconnectAttempts) {\n this.setState(\"disconnected\");\n console.error(\"[KitsudenRealtime] Max reconnection attempts reached\");\n return;\n }\n\n this.setState(\"reconnecting\");\n this.reconnectAttempts++;\n\n const delay = Math.min(this.reconnectDelay * Math.pow(2, this.reconnectAttempts - 1), 30000);\n\n console.log(\n `[KitsudenRealtime] Reconnecting in ${delay}ms (attempt ${this.reconnectAttempts})`\n );\n\n this.reconnectTimer = setTimeout(() => {\n this.connect().catch(() => {\n // Will retry via onclose\n });\n }, delay);\n }\n\n private startHeartbeat(): void {\n this.pingInterval = setInterval(() => {\n this.send({ type: \"ping\" });\n }, this.pingTimeout);\n }\n\n private stopHeartbeat(): void {\n if (this.pingInterval) {\n clearInterval(this.pingInterval);\n this.pingInterval = null;\n }\n }\n}\n\n// ═══════════════════════════════════════════════════════════════\n// Factory Function\n// ═══════════════════════════════════════════════════════════════\n\n/**\n * Create a KitsudenRealtime instance with sensible defaults.\n *\n * @param baseUrl Base URL of the Kitsuden API (e.g., \"http://localhost:3000\")\n */\nexport function createRealtime(baseUrl: string): KitsudenRealtime {\n const wsUrl =\n baseUrl\n .replace(/^http:/, \"ws:\")\n .replace(/^https:/, \"wss:\")\n .replace(/\\/$/, \"\") + \"/api/realtime\";\n\n return new KitsudenRealtime(wsUrl);\n}\n"],"mappings":"yaAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,sBAAAE,EAAA,mBAAAC,EAAA,YAAAC,IAAA,eAAAC,EAAAL,GAuEO,SAASM,EAAQC,EAAwB,CAC9C,IAAMC,EAAO,OAAOD,GAAS,EAAE,EAC5B,QAAQ,SAAU,GAAG,EAErB,QAAQ,4CAA6C,GAAG,EAC3D,OAAOC,EAAK,OAAS,IAAoB,GAAGA,EAAK,MAAM,EAAG,GAAiB,CAAC,SAAMA,CACpF,CAEO,IAAMC,EAAN,KAAuB,CACpB,IACA,GAAuB,KACvB,MAAyB,eACzB,SAA0B,KAC1B,OAAwB,KAGhC,aAA6B,CAC3B,OAAO,KAAK,QACd,CAGA,WAA2B,CACzB,OAAO,KAAK,MACd,CAGQ,gBAAkB,IAAI,IACtB,iBAAmB,IAAI,IACvB,cAAgB,IAAI,IAGpB,kBAAoB,EACX,qBAAuB,GACvB,eAAiB,IAC1B,eAAuD,KAGvD,gBAAkB,IAAI,IACtB,aAAe,IAAI,IAGnB,aAAsD,KAC7C,YAAc,IAE/B,YAAYC,EAAa,CACvB,KAAK,IAAMA,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AAK,SAAS,cAAc,EAC5B,QAAQ,MAAM,sDAAsD,EACpE,MACF,CAEA,KAAK,SAAS,cAAc,EAC5B,KAAK,oBAEL,IAAMM,EAAQ,KAAK,IAAI,KAAK,eAAiB,KAAK,IAAI,EAAG,KAAK,kBAAoB,CAAC,EAAG,GAAK,EAE3F,QAAQ,IACN,sCAAsCA,CAAK,eAAe,KAAK,iBAAiB,GAClF,EAEA,KAAK,eAAiB,WAAW,IAAM,CACrC,KAAK,QAAQ,EAAE,MAAM,IAAM,CAE3B,CAAC,CACH,EAAGA,CAAK,CACV,CAEQ,gBAAuB,CAC7B,KAAK,aAAe,YAAY,IAAM,CACpC,KAAK,KAAK,CAAE,KAAM,MAAO,CAAC,CAC5B,EAAG,KAAK,WAAW,CACrB,CAEQ,eAAsB,CACxB,KAAK,eACP,cAAc,KAAK,YAAY,EAC/B,KAAK,aAAe,KAExB,CACF,EAWO,SAASC,EAAeC,EAAmC,CAChE,IAAMC,EACJD,EACG,QAAQ,SAAU,KAAK,EACvB,QAAQ,UAAW,MAAM,EACzB,QAAQ,MAAO,EAAE,EAAI,gBAE1B,OAAO,IAAIpB,EAAiBqB,CAAK,CACnC","names":["realtime_exports","__export","KitsudenRealtime","createRealtime","logSafe","__toCommonJS","logSafe","value","text","KitsudenRealtime","url","resolve","reject","event","_error","err","handler","channel","h","datasetId","entryId","room","state","data","raw","msg","handlers","delay","createRealtime","baseUrl","wsUrl"]}
@@ -0,0 +1,133 @@
1
+ /**
2
+ * @kitsuden/sdk — Real-time Module
3
+ *
4
+ * Provides WebSocket connection management and Live Query subscriptions.
5
+ *
6
+ * Usage:
7
+ * import { KitsudenRealtime, createRealtime } from '@kitsuden/sdk/realtime';
8
+ *
9
+ * const rt = createRealtime('http://localhost:3000');
10
+ * await rt.connect();
11
+ *
12
+ * // Subscribe to all changes in a dataset
13
+ * const unsub = rt.subscribe('table:matches', (data) => {
14
+ * console.log('Mutation:', data.event, data.entry);
15
+ * });
16
+ *
17
+ * // Presence
18
+ * rt.joinRoom('editor:doc-123');
19
+ * rt.onPresence('editor:doc-123', (users) => {
20
+ * console.log('Users online:', users);
21
+ * });
22
+ *
23
+ * // Cleanup
24
+ * unsub();
25
+ * rt.disconnect();
26
+ */
27
+ type ConnectionState = "disconnected" | "connecting" | "connected" | "reconnecting";
28
+ interface MutationEvent {
29
+ event: "insert" | "update" | "delete";
30
+ datasetId: string;
31
+ entry: Record<string, unknown>;
32
+ timestamp: number;
33
+ }
34
+ interface PresenceUser {
35
+ id: string;
36
+ name?: string;
37
+ }
38
+ interface PresenceEvent {
39
+ room: string;
40
+ users: PresenceUser[];
41
+ count: number;
42
+ }
43
+ type MessageHandler = (data: MutationEvent) => void;
44
+ type PresenceHandler = (users: PresenceUser[]) => void;
45
+ type StateHandler = (state: ConnectionState) => void;
46
+ /**
47
+ * Server text made safe for one console line: control characters and line
48
+ * separators become spaces (a message cannot forge extra log lines) and it is capped.
49
+ */
50
+ declare function logSafe(value: unknown): string;
51
+ declare class KitsudenRealtime {
52
+ private url;
53
+ private ws;
54
+ private state;
55
+ private clientId;
56
+ private userId;
57
+ /** Get the server-assigned client ID */
58
+ getClientId(): string | null;
59
+ /** Get the authenticated user ID (if any) */
60
+ getUserId(): string | null;
61
+ private channelHandlers;
62
+ private presenceHandlers;
63
+ private stateHandlers;
64
+ private reconnectAttempts;
65
+ private readonly maxReconnectAttempts;
66
+ private readonly reconnectDelay;
67
+ private reconnectTimer;
68
+ private pendingChannels;
69
+ private pendingRooms;
70
+ private pingInterval;
71
+ private readonly pingTimeout;
72
+ constructor(url: string);
73
+ /**
74
+ * Connect to the WebSocket server.
75
+ * Returns a promise that resolves when connected.
76
+ */
77
+ connect(): Promise<void>;
78
+ /**
79
+ * Disconnect from the WebSocket server.
80
+ */
81
+ disconnect(): void;
82
+ /**
83
+ * Get current connection state.
84
+ */
85
+ getState(): ConnectionState;
86
+ /**
87
+ * Listen for connection state changes.
88
+ */
89
+ onStateChange(handler: StateHandler): () => void;
90
+ /**
91
+ * Subscribe to a channel for live updates.
92
+ *
93
+ * @param channel Channel name (e.g., "table:datasetId" or "entry:entryId")
94
+ * @param handler Callback for mutation events
95
+ * @returns Unsubscribe function
96
+ */
97
+ subscribe(channel: string, handler: MessageHandler): () => void;
98
+ /**
99
+ * Convenience method to subscribe to a dataset's changes.
100
+ */
101
+ subscribeToDataset(datasetId: string, handler: MessageHandler): () => void;
102
+ /**
103
+ * Convenience method to subscribe to a single entry's changes.
104
+ */
105
+ subscribeToEntry(entryId: string, handler: MessageHandler): () => void;
106
+ /**
107
+ * Join a presence room to track who's online.
108
+ */
109
+ joinRoom(room: string): void;
110
+ /**
111
+ * Leave a presence room.
112
+ */
113
+ leaveRoom(room: string): void;
114
+ /**
115
+ * Listen for presence updates in a room.
116
+ */
117
+ onPresence(room: string, handler: PresenceHandler): () => void;
118
+ private setState;
119
+ private send;
120
+ private handleMessage;
121
+ private resubscribe;
122
+ private scheduleReconnect;
123
+ private startHeartbeat;
124
+ private stopHeartbeat;
125
+ }
126
+ /**
127
+ * Create a KitsudenRealtime instance with sensible defaults.
128
+ *
129
+ * @param baseUrl Base URL of the Kitsuden API (e.g., "http://localhost:3000")
130
+ */
131
+ declare function createRealtime(baseUrl: string): KitsudenRealtime;
132
+
133
+ export { type ConnectionState, KitsudenRealtime, type MutationEvent, type PresenceEvent, type PresenceUser, createRealtime, logSafe };
@@ -0,0 +1,133 @@
1
+ /**
2
+ * @kitsuden/sdk — Real-time Module
3
+ *
4
+ * Provides WebSocket connection management and Live Query subscriptions.
5
+ *
6
+ * Usage:
7
+ * import { KitsudenRealtime, createRealtime } from '@kitsuden/sdk/realtime';
8
+ *
9
+ * const rt = createRealtime('http://localhost:3000');
10
+ * await rt.connect();
11
+ *
12
+ * // Subscribe to all changes in a dataset
13
+ * const unsub = rt.subscribe('table:matches', (data) => {
14
+ * console.log('Mutation:', data.event, data.entry);
15
+ * });
16
+ *
17
+ * // Presence
18
+ * rt.joinRoom('editor:doc-123');
19
+ * rt.onPresence('editor:doc-123', (users) => {
20
+ * console.log('Users online:', users);
21
+ * });
22
+ *
23
+ * // Cleanup
24
+ * unsub();
25
+ * rt.disconnect();
26
+ */
27
+ type ConnectionState = "disconnected" | "connecting" | "connected" | "reconnecting";
28
+ interface MutationEvent {
29
+ event: "insert" | "update" | "delete";
30
+ datasetId: string;
31
+ entry: Record<string, unknown>;
32
+ timestamp: number;
33
+ }
34
+ interface PresenceUser {
35
+ id: string;
36
+ name?: string;
37
+ }
38
+ interface PresenceEvent {
39
+ room: string;
40
+ users: PresenceUser[];
41
+ count: number;
42
+ }
43
+ type MessageHandler = (data: MutationEvent) => void;
44
+ type PresenceHandler = (users: PresenceUser[]) => void;
45
+ type StateHandler = (state: ConnectionState) => void;
46
+ /**
47
+ * Server text made safe for one console line: control characters and line
48
+ * separators become spaces (a message cannot forge extra log lines) and it is capped.
49
+ */
50
+ declare function logSafe(value: unknown): string;
51
+ declare class KitsudenRealtime {
52
+ private url;
53
+ private ws;
54
+ private state;
55
+ private clientId;
56
+ private userId;
57
+ /** Get the server-assigned client ID */
58
+ getClientId(): string | null;
59
+ /** Get the authenticated user ID (if any) */
60
+ getUserId(): string | null;
61
+ private channelHandlers;
62
+ private presenceHandlers;
63
+ private stateHandlers;
64
+ private reconnectAttempts;
65
+ private readonly maxReconnectAttempts;
66
+ private readonly reconnectDelay;
67
+ private reconnectTimer;
68
+ private pendingChannels;
69
+ private pendingRooms;
70
+ private pingInterval;
71
+ private readonly pingTimeout;
72
+ constructor(url: string);
73
+ /**
74
+ * Connect to the WebSocket server.
75
+ * Returns a promise that resolves when connected.
76
+ */
77
+ connect(): Promise<void>;
78
+ /**
79
+ * Disconnect from the WebSocket server.
80
+ */
81
+ disconnect(): void;
82
+ /**
83
+ * Get current connection state.
84
+ */
85
+ getState(): ConnectionState;
86
+ /**
87
+ * Listen for connection state changes.
88
+ */
89
+ onStateChange(handler: StateHandler): () => void;
90
+ /**
91
+ * Subscribe to a channel for live updates.
92
+ *
93
+ * @param channel Channel name (e.g., "table:datasetId" or "entry:entryId")
94
+ * @param handler Callback for mutation events
95
+ * @returns Unsubscribe function
96
+ */
97
+ subscribe(channel: string, handler: MessageHandler): () => void;
98
+ /**
99
+ * Convenience method to subscribe to a dataset's changes.
100
+ */
101
+ subscribeToDataset(datasetId: string, handler: MessageHandler): () => void;
102
+ /**
103
+ * Convenience method to subscribe to a single entry's changes.
104
+ */
105
+ subscribeToEntry(entryId: string, handler: MessageHandler): () => void;
106
+ /**
107
+ * Join a presence room to track who's online.
108
+ */
109
+ joinRoom(room: string): void;
110
+ /**
111
+ * Leave a presence room.
112
+ */
113
+ leaveRoom(room: string): void;
114
+ /**
115
+ * Listen for presence updates in a room.
116
+ */
117
+ onPresence(room: string, handler: PresenceHandler): () => void;
118
+ private setState;
119
+ private send;
120
+ private handleMessage;
121
+ private resubscribe;
122
+ private scheduleReconnect;
123
+ private startHeartbeat;
124
+ private stopHeartbeat;
125
+ }
126
+ /**
127
+ * Create a KitsudenRealtime instance with sensible defaults.
128
+ *
129
+ * @param baseUrl Base URL of the Kitsuden API (e.g., "http://localhost:3000")
130
+ */
131
+ declare function createRealtime(baseUrl: string): KitsudenRealtime;
132
+
133
+ export { type ConnectionState, KitsudenRealtime, type MutationEvent, type PresenceEvent, type PresenceUser, createRealtime, logSafe };
@@ -0,0 +1,2 @@
1
+ function a(r){let e=String(r??"").replace(/\n|\r/g," ").replace(/[\u0000-\u001f\u007f-\u009f\u2028\u2029]/g," ");return e.length>500?`${e.slice(0,500)}\u2026`:e}var i=class{url;ws=null;state="disconnected";clientId=null;userId=null;getClientId(){return this.clientId}getUserId(){return this.userId}channelHandlers=new Map;presenceHandlers=new Map;stateHandlers=new Set;reconnectAttempts=0;maxReconnectAttempts=10;reconnectDelay=1e3;reconnectTimer=null;pendingChannels=new Set;pendingRooms=new Set;pingInterval=null;pingTimeout=3e4;constructor(e){this.url=e}async connect(){if(!(this.state==="connected"||this.state==="connecting"))return new Promise((e,t)=>{this.setState("connecting");try{this.ws=new WebSocket(this.url),this.ws.onopen=()=>{this.reconnectAttempts=0,this.startHeartbeat()},this.ws.onmessage=n=>{this.handleMessage(n.data),this.state==="connecting"&&(this.setState("connected"),this.resubscribe(),e())},this.ws.onclose=()=>{this.stopHeartbeat(),this.state!=="disconnected"&&this.scheduleReconnect()},this.ws.onerror=n=>{console.error("[KitsudenRealtime] WebSocket error"),this.state==="connecting"&&t(new Error("Failed to connect"))}}catch(n){this.setState("disconnected"),t(n)}})}disconnect(){this.setState("disconnected"),this.stopHeartbeat(),this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null),this.ws&&(this.ws.close(),this.ws=null),this.clientId=null,this.userId=null}getState(){return this.state}onStateChange(e){return this.stateHandlers.add(e),()=>{this.stateHandlers.delete(e)}}subscribe(e,t){return this.channelHandlers.has(e)||this.channelHandlers.set(e,new Set),this.channelHandlers.get(e).add(t),this.pendingChannels.add(e),this.state==="connected"&&this.send({type:"subscribe",channel:e}),()=>{let s=this.channelHandlers.get(e);s&&(s.delete(t),s.size===0&&(this.channelHandlers.delete(e),this.pendingChannels.delete(e),this.state==="connected"&&this.send({type:"unsubscribe",channel:e})))}}subscribeToDataset(e,t){return this.subscribe(`table:${e}`,t)}subscribeToEntry(e,t){return this.subscribe(`entry:${e}`,t)}joinRoom(e){this.pendingRooms.add(e),this.state==="connected"&&this.send({type:"presence:join",room:e})}leaveRoom(e){this.pendingRooms.delete(e),this.presenceHandlers.delete(e),this.state==="connected"&&this.send({type:"presence:leave",room:e})}onPresence(e,t){return this.presenceHandlers.has(e)||this.presenceHandlers.set(e,new Set),this.presenceHandlers.get(e).add(t),()=>{let s=this.presenceHandlers.get(e);s&&(s.delete(t),s.size===0&&this.presenceHandlers.delete(e))}}setState(e){if(this.state!==e){this.state=e;for(let t of this.stateHandlers)try{t(e)}catch{}}}send(e){this.ws&&this.ws.readyState===WebSocket.OPEN&&this.ws.send(JSON.stringify(e))}handleMessage(e){let t;try{t=JSON.parse(e)}catch{return}switch(t.type){case"connected":this.clientId=t.clientId??null,this.userId=t.userId??null;break;case"message":if(t.channel&&t.data){let n=this.channelHandlers.get(t.channel);if(n)for(let s of n)try{s(t.data)}catch{}}break;case"presence":if(t.room&&t.users){let n=this.presenceHandlers.get(t.room);if(n)for(let s of n)try{s(t.users)}catch{}}break;case"subscribed":case"unsubscribed":break;case"pong":break;case"error":console.warn("[KitsudenRealtime] Server error:",a(t.message).replace(/\n|\r/g,""));break}}resubscribe(){for(let e of this.pendingChannels)this.send({type:"subscribe",channel:e});for(let e of this.pendingRooms)this.send({type:"presence:join",room:e})}scheduleReconnect(){if(this.reconnectAttempts>=this.maxReconnectAttempts){this.setState("disconnected"),console.error("[KitsudenRealtime] Max reconnection attempts reached");return}this.setState("reconnecting"),this.reconnectAttempts++;let e=Math.min(this.reconnectDelay*Math.pow(2,this.reconnectAttempts-1),3e4);console.log(`[KitsudenRealtime] Reconnecting in ${e}ms (attempt ${this.reconnectAttempts})`),this.reconnectTimer=setTimeout(()=>{this.connect().catch(()=>{})},e)}startHeartbeat(){this.pingInterval=setInterval(()=>{this.send({type:"ping"})},this.pingTimeout)}stopHeartbeat(){this.pingInterval&&(clearInterval(this.pingInterval),this.pingInterval=null)}};function c(r){let e=r.replace(/^http:/,"ws:").replace(/^https:/,"wss:").replace(/\/$/,"")+"/api/realtime";return new i(e)}export{i as KitsudenRealtime,c as createRealtime,a as logSafe};
2
+ //# sourceMappingURL=realtime.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/realtime.ts"],"sourcesContent":["/**\n * @kitsuden/sdk — Real-time Module\n *\n * Provides WebSocket connection management and Live Query subscriptions.\n *\n * Usage:\n * import { KitsudenRealtime, createRealtime } from '@kitsuden/sdk/realtime';\n *\n * const rt = createRealtime('http://localhost:3000');\n * await rt.connect();\n *\n * // Subscribe to all changes in a dataset\n * const unsub = rt.subscribe('table:matches', (data) => {\n * console.log('Mutation:', data.event, data.entry);\n * });\n *\n * // Presence\n * rt.joinRoom('editor:doc-123');\n * rt.onPresence('editor:doc-123', (users) => {\n * console.log('Users online:', users);\n * });\n *\n * // Cleanup\n * unsub();\n * rt.disconnect();\n */\n\nexport type ConnectionState = \"disconnected\" | \"connecting\" | \"connected\" | \"reconnecting\";\n\nexport interface MutationEvent {\n event: \"insert\" | \"update\" | \"delete\";\n datasetId: string;\n entry: Record<string, unknown>;\n timestamp: number;\n}\n\nexport interface PresenceUser {\n id: string;\n name?: string;\n}\n\nexport interface PresenceEvent {\n room: string;\n users: PresenceUser[];\n count: number;\n}\n\ntype MessageHandler = (data: MutationEvent) => void;\ntype PresenceHandler = (users: PresenceUser[]) => void;\ntype StateHandler = (state: ConnectionState) => void;\n\ninterface InternalMessage {\n type: string;\n channel?: string;\n room?: string;\n data?: unknown;\n users?: PresenceUser[];\n count?: number;\n clientId?: string;\n userId?: string | null;\n message?: string;\n timestamp?: number;\n}\n\n/** Longest server text that reaches the console. */\nconst MAX_LOGGED_LENGTH = 500;\n\n/**\n * Server text made safe for one console line: control characters and line\n * separators become spaces (a message cannot forge extra log lines) and it is capped.\n */\nexport function logSafe(value: unknown): string {\n const text = String(value ?? \"\")\n .replace(/\\n|\\r/g, \" \")\n // eslint-disable-next-line no-control-regex\n .replace(/[\\u0000-\\u001f\\u007f-\\u009f\\u2028\\u2029]/g, \" \");\n return text.length > MAX_LOGGED_LENGTH ? `${text.slice(0, MAX_LOGGED_LENGTH)}…` : text;\n}\n\nexport class KitsudenRealtime {\n private url: string;\n private ws: WebSocket | null = null;\n private state: ConnectionState = \"disconnected\";\n private clientId: string | null = null;\n private userId: string | null = null;\n\n /** Get the server-assigned client ID */\n getClientId(): string | null {\n return this.clientId;\n }\n\n /** Get the authenticated user ID (if any) */\n getUserId(): string | null {\n return this.userId;\n }\n\n // Subscriptions\n private channelHandlers = new Map<string, Set<MessageHandler>>();\n private presenceHandlers = new Map<string, Set<PresenceHandler>>();\n private stateHandlers = new Set<StateHandler>();\n\n // Reconnection\n private reconnectAttempts = 0;\n private readonly maxReconnectAttempts = 10;\n private readonly reconnectDelay = 1000;\n private reconnectTimer: ReturnType<typeof setTimeout> | null = null;\n\n // Pending subscriptions (to restore after reconnect)\n private pendingChannels = new Set<string>();\n private pendingRooms = new Set<string>();\n\n // Heartbeat\n private pingInterval: ReturnType<typeof setInterval> | null = null;\n private readonly pingTimeout = 30000;\n\n constructor(url: string) {\n this.url = url;\n }\n\n // ═══════════════════════════════════════════════════════════\n // Connection Management\n // ═══════════════════════════════════════════════════════════\n\n /**\n * Connect to the WebSocket server.\n * Returns a promise that resolves when connected.\n */\n async connect(): Promise<void> {\n if (this.state === \"connected\" || this.state === \"connecting\") {\n return;\n }\n\n return new Promise((resolve, reject) => {\n this.setState(\"connecting\");\n\n try {\n this.ws = new WebSocket(this.url);\n\n this.ws.onopen = () => {\n this.reconnectAttempts = 0;\n this.startHeartbeat();\n // Wait for \"connected\" message from server\n };\n\n this.ws.onmessage = (event: MessageEvent) => {\n this.handleMessage(event.data as string);\n\n // Resolve promise on first connection\n if (this.state === \"connecting\") {\n this.setState(\"connected\");\n this.resubscribe();\n resolve();\n }\n };\n\n this.ws.onclose = () => {\n this.stopHeartbeat();\n if (this.state !== \"disconnected\") {\n this.scheduleReconnect();\n }\n };\n\n this.ws.onerror = (_error: Event) => {\n console.error(\"[KitsudenRealtime] WebSocket error\");\n if (this.state === \"connecting\") {\n reject(new Error(\"Failed to connect\"));\n }\n };\n } catch (err) {\n this.setState(\"disconnected\");\n reject(err);\n }\n });\n }\n\n /**\n * Disconnect from the WebSocket server.\n */\n disconnect(): void {\n this.setState(\"disconnected\");\n this.stopHeartbeat();\n\n if (this.reconnectTimer) {\n clearTimeout(this.reconnectTimer);\n this.reconnectTimer = null;\n }\n\n if (this.ws) {\n this.ws.close();\n this.ws = null;\n }\n\n this.clientId = null;\n this.userId = null;\n }\n\n /**\n * Get current connection state.\n */\n getState(): ConnectionState {\n return this.state;\n }\n\n /**\n * Listen for connection state changes.\n */\n onStateChange(handler: StateHandler): () => void {\n this.stateHandlers.add(handler);\n return () => {\n this.stateHandlers.delete(handler);\n };\n }\n\n // ═══════════════════════════════════════════════════════════\n // Channel Subscriptions (Live Queries)\n // ═══════════════════════════════════════════════════════════\n\n /**\n * Subscribe to a channel for live updates.\n *\n * @param channel Channel name (e.g., \"table:datasetId\" or \"entry:entryId\")\n * @param handler Callback for mutation events\n * @returns Unsubscribe function\n */\n subscribe(channel: string, handler: MessageHandler): () => void {\n // Track handler\n if (!this.channelHandlers.has(channel)) {\n this.channelHandlers.set(channel, new Set());\n }\n const handlers = this.channelHandlers.get(channel)!;\n handlers.add(handler);\n\n // Track for reconnection\n this.pendingChannels.add(channel);\n\n // Send subscription request if connected\n if (this.state === \"connected\") {\n this.send({ type: \"subscribe\", channel });\n }\n\n // Return unsubscribe function\n return () => {\n const h = this.channelHandlers.get(channel);\n if (h) {\n h.delete(handler);\n if (h.size === 0) {\n this.channelHandlers.delete(channel);\n this.pendingChannels.delete(channel);\n if (this.state === \"connected\") {\n this.send({ type: \"unsubscribe\", channel });\n }\n }\n }\n };\n }\n\n /**\n * Convenience method to subscribe to a dataset's changes.\n */\n subscribeToDataset(datasetId: string, handler: MessageHandler): () => void {\n return this.subscribe(`table:${datasetId}`, handler);\n }\n\n /**\n * Convenience method to subscribe to a single entry's changes.\n */\n subscribeToEntry(entryId: string, handler: MessageHandler): () => void {\n return this.subscribe(`entry:${entryId}`, handler);\n }\n\n // ═══════════════════════════════════════════════════════════\n // Presence\n // ═══════════════════════════════════════════════════════════\n\n /**\n * Join a presence room to track who's online.\n */\n joinRoom(room: string): void {\n this.pendingRooms.add(room);\n if (this.state === \"connected\") {\n this.send({ type: \"presence:join\", room });\n }\n }\n\n /**\n * Leave a presence room.\n */\n leaveRoom(room: string): void {\n this.pendingRooms.delete(room);\n this.presenceHandlers.delete(room);\n if (this.state === \"connected\") {\n this.send({ type: \"presence:leave\", room });\n }\n }\n\n /**\n * Listen for presence updates in a room.\n */\n onPresence(room: string, handler: PresenceHandler): () => void {\n if (!this.presenceHandlers.has(room)) {\n this.presenceHandlers.set(room, new Set());\n }\n const handlers = this.presenceHandlers.get(room)!;\n handlers.add(handler);\n\n return () => {\n const h = this.presenceHandlers.get(room);\n if (h) {\n h.delete(handler);\n if (h.size === 0) {\n this.presenceHandlers.delete(room);\n }\n }\n };\n }\n\n // ═══════════════════════════════════════════════════════════\n // Internal Methods\n // ═══════════════════════════════════════════════════════════\n\n private setState(state: ConnectionState): void {\n if (this.state === state) return;\n this.state = state;\n for (const handler of this.stateHandlers) {\n try {\n handler(state);\n } catch {\n // ignore handler errors\n }\n }\n }\n\n private send(data: Record<string, unknown>): void {\n if (this.ws && this.ws.readyState === WebSocket.OPEN) {\n this.ws.send(JSON.stringify(data));\n }\n }\n\n private handleMessage(raw: string): void {\n let msg: InternalMessage;\n try {\n msg = JSON.parse(raw) as InternalMessage;\n } catch {\n return;\n }\n\n switch (msg.type) {\n case \"connected\":\n this.clientId = msg.clientId ?? null;\n this.userId = msg.userId ?? null;\n break;\n\n case \"message\":\n if (msg.channel && msg.data) {\n const handlers = this.channelHandlers.get(msg.channel);\n if (handlers) {\n for (const handler of handlers) {\n try {\n handler(msg.data as MutationEvent);\n } catch {\n // ignore handler errors\n }\n }\n }\n }\n break;\n\n case \"presence\":\n if (msg.room && msg.users) {\n const handlers = this.presenceHandlers.get(msg.room);\n if (handlers) {\n for (const handler of handlers) {\n try {\n handler(msg.users);\n } catch {\n // ignore handler errors\n }\n }\n }\n }\n break;\n\n case \"subscribed\":\n case \"unsubscribed\":\n // Acknowledgments — could track pending state\n break;\n\n case \"pong\":\n // Heartbeat response\n break;\n\n case \"error\":\n // logSafe already removes line breaks; the replace here is the form CodeQL recognises.\n console.warn(\n \"[KitsudenRealtime] Server error:\",\n logSafe(msg.message).replace(/\\n|\\r/g, \"\")\n );\n break;\n }\n }\n\n private resubscribe(): void {\n // Restore channel subscriptions\n for (const channel of this.pendingChannels) {\n this.send({ type: \"subscribe\", channel });\n }\n\n // Restore presence rooms\n for (const room of this.pendingRooms) {\n this.send({ type: \"presence:join\", room });\n }\n }\n\n private scheduleReconnect(): void {\n if (this.reconnectAttempts >= this.maxReconnectAttempts) {\n this.setState(\"disconnected\");\n console.error(\"[KitsudenRealtime] Max reconnection attempts reached\");\n return;\n }\n\n this.setState(\"reconnecting\");\n this.reconnectAttempts++;\n\n const delay = Math.min(this.reconnectDelay * Math.pow(2, this.reconnectAttempts - 1), 30000);\n\n console.log(\n `[KitsudenRealtime] Reconnecting in ${delay}ms (attempt ${this.reconnectAttempts})`\n );\n\n this.reconnectTimer = setTimeout(() => {\n this.connect().catch(() => {\n // Will retry via onclose\n });\n }, delay);\n }\n\n private startHeartbeat(): void {\n this.pingInterval = setInterval(() => {\n this.send({ type: \"ping\" });\n }, this.pingTimeout);\n }\n\n private stopHeartbeat(): void {\n if (this.pingInterval) {\n clearInterval(this.pingInterval);\n this.pingInterval = null;\n }\n }\n}\n\n// ═══════════════════════════════════════════════════════════════\n// Factory Function\n// ═══════════════════════════════════════════════════════════════\n\n/**\n * Create a KitsudenRealtime instance with sensible defaults.\n *\n * @param baseUrl Base URL of the Kitsuden API (e.g., \"http://localhost:3000\")\n */\nexport function createRealtime(baseUrl: string): KitsudenRealtime {\n const wsUrl =\n baseUrl\n .replace(/^http:/, \"ws:\")\n .replace(/^https:/, \"wss:\")\n .replace(/\\/$/, \"\") + \"/api/realtime\";\n\n return new KitsudenRealtime(wsUrl);\n}\n"],"mappings":"AAuEO,SAASA,EAAQC,EAAwB,CAC9C,IAAMC,EAAO,OAAOD,GAAS,EAAE,EAC5B,QAAQ,SAAU,GAAG,EAErB,QAAQ,4CAA6C,GAAG,EAC3D,OAAOC,EAAK,OAAS,IAAoB,GAAGA,EAAK,MAAM,EAAG,GAAiB,CAAC,SAAMA,CACpF,CAEO,IAAMC,EAAN,KAAuB,CACpB,IACA,GAAuB,KACvB,MAAyB,eACzB,SAA0B,KAC1B,OAAwB,KAGhC,aAA6B,CAC3B,OAAO,KAA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A,KACJ,CACF,CAEQ,aAAoB,CAE1B,QAAWR,KAAW,KAAK,gBACzB,KAAK,KAAK,CAAE,KAAM,YAAa,QAAAA,CAAQ,CAAC,EAI1C,QAAWI,KAAQ,KAAK,aACtB,KAAK,KAAK,CAAE,KAAM,gBAAiB,KAAAA,CAAK,CAAC,CAE7C,CAEQ,mBAA0B,CAChC,GAAI,KAAK,mBAAqB,KAAK,qBAAsB,CACvD,KAAK,SAAS,cAAc,EAC5B,QAAQ,MAAM,sDAAsD,EACpE,MACF,CAEA,KAAK,SAAS,cAAc,EAC5B,KAAK,oBAEL,IAAMM,EAAQ,KAAK,IAAI,KAAK,eAAiB,KAAK,IAAI,EAAG,KAAK,kBAAoB,CAAC,EAAG,GAAK,EAE3F,QAAQ,IACN,sCAAsCA,CAAK,eAAe,KAAK,iBAAiB,GAClF,EAEA,KAAK,eAAiB,WAAW,IAAM,CACrC,KAAK,QAAQ,EAAE,MAAM,IAAM,CAE3B,CAAC,CACH,EAAGA,CAAK,CACV,CAEQ,gBAAuB,CAC7B,KAAK,aAAe,YAAY,IAAM,CACpC,KAAK,KAAK,CAAE,KAAM,MAAO,CAAC,CAC5B,EAAG,KAAK,WAAW,CACrB,CAEQ,eAAsB,CACxB,KAAK,eACP,cAAc,KAAK,YAAY,EAC/B,KAAK,aAAe,KAExB,CACF,EAWO,SAASC,EAAeC,EAAmC,CAChE,IAAMC,EACJD,EACG,QAAQ,SAAU,KAAK,EACvB,QAAQ,UAAW,MAAM,EACzB,QAAQ,MAAO,EAAE,EAAI,gBAE1B,OAAO,IAAIpB,EAAiBqB,CAAK,CACnC","names":["logSafe","value","text","KitsudenRealtime","url","resolve","reject","event","_error","err","handler","channel","h","datasetId","entryId","room","state","data","raw","msg","handlers","delay","createRealtime","baseUrl","wsUrl"]}
@@ -0,0 +1,2 @@
1
+ "use strict";var o=Object.defineProperty;var f=Object.getOwnPropertyDescriptor;var a=Object.getOwnPropertyNames;var s=Object.prototype.hasOwnProperty;var h=(t,e)=>{for(var r in e)o(t,r,{get:e[r],enumerable:!0})},y=(t,e,r,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of a(e))!s.call(t,n)&&n!==r&&o(t,n,{get:()=>e[n],enumerable:!(i=f(e,n))||i.enumerable});return t};var R=t=>y(o({},"__esModule",{value:!0}),t);var g={};h(g,{createRpcClient:()=>d,hc:()=>c.hc});module.exports=R(g);var p=require("hono/client"),c=require("hono/client");function d(t,e={}){let r={...e.headers??{}};return e.apiKey&&(r.Authorization=`Bearer ${e.apiKey}`),(0,p.hc)(t,{headers:r,fetch:e.fetch})}
2
+ //# sourceMappingURL=rpc.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/rpc.ts"],"sourcesContent":["/**\n * @kitsuden/sdk — Hono RPC Client (KITSUDEN architecture §7)\n *\n * Automatic SDK via Hono RPC: it links the `AppType` exported by the\n * server (apps/api/src/index.ts) with `hc<AppType>()` to get a\n * client with strict autocompletion WITHOUT generating intermediate files.\n *\n * `hono` is a peerDependency: the consumer must have it installed\n * (import from \"hono/client\" weighs ~2KB, edge-ready).\n *\n * @example\n * ```typescript\n * import { createRpcClient } from '@kitsuden/sdk/rpc';\n * import type { KitsudenRpcType } from '@kitsuden/api'; // deep RPC type (chained routers)\n * // import type { AppType } from '../../apps/api/src/index';\n *\n * const client = createRpcClient<KitsudenRpcType>('http://localhost:3001', {\n * apiKey: 'kitsuden_agent_xxx',\n * });\n *\n * const res = await client.api.health.$get();\n * const health = await res.json(); // ← typed end-to-end\n * ```\n */\n\nimport type { Hono } from \"hono\";\nimport { hc } from \"hono/client\";\n\nexport interface RpcClientOptions {\n /** Agent NHI token (kitsuden_agent_*) o API key legacy */\n apiKey?: string;\n /** Additional headers */\n headers?: Record<string, string>;\n /** custom fetch (for edge runtimes or testing) */\n fetch?: typeof fetch;\n}\n\n/**\n * Creates a typed Hono RPC client against the server's AppType.\n * No codegen, no build steps: the types flow straight from Hono.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport function createRpcClient<T extends Hono<any, any, any>>(\n baseUrl: string,\n options: RpcClientOptions = {}\n): ReturnType<typeof hc<T>> {\n const headers: Record<string, string> = { ...(options.headers ?? {}) };\n if (options.apiKey) headers[\"Authorization\"] = `Bearer ${options.apiKey}`;\n\n return hc<T>(baseUrl, {\n headers,\n // hono/client accepts a custom fetch; undefined uses the global one\n fetch: options.fetch as never,\n });\n}\n\nexport { hc } from \"hono/client\";\nexport type { InferRequestType, InferResponseType } from \"hono/client\";\n"],"mappings":"yaAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,qBAAAE,EAAA,6BAAAC,EAAAH,GA0BA,IAAAI,EAAmB,uBA8BnBA,EAAmB,uBAdZ,SAASF,EACdG,EACAC,EAA4B,CAAC,EACH,CAC1B,IAAMC,EAAkC,CAAE,GAAID,EAAQ,SAAW,CAAC,CAAG,EACrE,OAAIA,EAAQ,SAAQC,EAAQ,cAAmB,UAAUD,EAAQ,MAAM,OAEhE,MAAMD,EAAS,CACpB,QAAAE,EAEA,MAAOD,EAAQ,KACjB,CAAC,CACH","names":["rpc_exports","__export","createRpcClient","__toCommonJS","import_client","baseUrl","options","headers"]}
@@ -0,0 +1,44 @@
1
+ import { Hono } from 'hono';
2
+ import { hc } from 'hono/client';
3
+ export { InferRequestType, InferResponseType, hc } from 'hono/client';
4
+
5
+ /**
6
+ * @kitsuden/sdk — Hono RPC Client (KITSUDEN architecture §7)
7
+ *
8
+ * Automatic SDK via Hono RPC: it links the `AppType` exported by the
9
+ * server (apps/api/src/index.ts) with `hc<AppType>()` to get a
10
+ * client with strict autocompletion WITHOUT generating intermediate files.
11
+ *
12
+ * `hono` is a peerDependency: the consumer must have it installed
13
+ * (import from "hono/client" weighs ~2KB, edge-ready).
14
+ *
15
+ * @example
16
+ * ```typescript
17
+ * import { createRpcClient } from '@kitsuden/sdk/rpc';
18
+ * import type { KitsudenRpcType } from '@kitsuden/api'; // deep RPC type (chained routers)
19
+ * // import type { AppType } from '../../apps/api/src/index';
20
+ *
21
+ * const client = createRpcClient<KitsudenRpcType>('http://localhost:3001', {
22
+ * apiKey: 'kitsuden_agent_xxx',
23
+ * });
24
+ *
25
+ * const res = await client.api.health.$get();
26
+ * const health = await res.json(); // ← typed end-to-end
27
+ * ```
28
+ */
29
+
30
+ interface RpcClientOptions {
31
+ /** Agent NHI token (kitsuden_agent_*) o API key legacy */
32
+ apiKey?: string;
33
+ /** Additional headers */
34
+ headers?: Record<string, string>;
35
+ /** custom fetch (for edge runtimes or testing) */
36
+ fetch?: typeof fetch;
37
+ }
38
+ /**
39
+ * Creates a typed Hono RPC client against the server's AppType.
40
+ * No codegen, no build steps: the types flow straight from Hono.
41
+ */
42
+ declare function createRpcClient<T extends Hono<any, any, any>>(baseUrl: string, options?: RpcClientOptions): ReturnType<typeof hc<T>>;
43
+
44
+ export { type RpcClientOptions, createRpcClient };
@@ -0,0 +1,44 @@
1
+ import { Hono } from 'hono';
2
+ import { hc } from 'hono/client';
3
+ export { InferRequestType, InferResponseType, hc } from 'hono/client';
4
+
5
+ /**
6
+ * @kitsuden/sdk — Hono RPC Client (KITSUDEN architecture §7)
7
+ *
8
+ * Automatic SDK via Hono RPC: it links the `AppType` exported by the
9
+ * server (apps/api/src/index.ts) with `hc<AppType>()` to get a
10
+ * client with strict autocompletion WITHOUT generating intermediate files.
11
+ *
12
+ * `hono` is a peerDependency: the consumer must have it installed
13
+ * (import from "hono/client" weighs ~2KB, edge-ready).
14
+ *
15
+ * @example
16
+ * ```typescript
17
+ * import { createRpcClient } from '@kitsuden/sdk/rpc';
18
+ * import type { KitsudenRpcType } from '@kitsuden/api'; // deep RPC type (chained routers)
19
+ * // import type { AppType } from '../../apps/api/src/index';
20
+ *
21
+ * const client = createRpcClient<KitsudenRpcType>('http://localhost:3001', {
22
+ * apiKey: 'kitsuden_agent_xxx',
23
+ * });
24
+ *
25
+ * const res = await client.api.health.$get();
26
+ * const health = await res.json(); // ← typed end-to-end
27
+ * ```
28
+ */
29
+
30
+ interface RpcClientOptions {
31
+ /** Agent NHI token (kitsuden_agent_*) o API key legacy */
32
+ apiKey?: string;
33
+ /** Additional headers */
34
+ headers?: Record<string, string>;
35
+ /** custom fetch (for edge runtimes or testing) */
36
+ fetch?: typeof fetch;
37
+ }
38
+ /**
39
+ * Creates a typed Hono RPC client against the server's AppType.
40
+ * No codegen, no build steps: the types flow straight from Hono.
41
+ */
42
+ declare function createRpcClient<T extends Hono<any, any, any>>(baseUrl: string, options?: RpcClientOptions): ReturnType<typeof hc<T>>;
43
+
44
+ export { type RpcClientOptions, createRpcClient };
@@ -0,0 +1,2 @@
1
+ import{hc as n}from"hono/client";import{hc as f}from"hono/client";function i(r,e={}){let t={...e.headers??{}};return e.apiKey&&(t.Authorization=`Bearer ${e.apiKey}`),n(r,{headers:t,fetch:e.fetch})}export{i as createRpcClient,f as hc};
2
+ //# sourceMappingURL=rpc.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/rpc.ts"],"sourcesContent":["/**\n * @kitsuden/sdk — Hono RPC Client (KITSUDEN architecture §7)\n *\n * Automatic SDK via Hono RPC: it links the `AppType` exported by the\n * server (apps/api/src/index.ts) with `hc<AppType>()` to get a\n * client with strict autocompletion WITHOUT generating intermediate files.\n *\n * `hono` is a peerDependency: the consumer must have it installed\n * (import from \"hono/client\" weighs ~2KB, edge-ready).\n *\n * @example\n * ```typescript\n * import { createRpcClient } from '@kitsuden/sdk/rpc';\n * import type { KitsudenRpcType } from '@kitsuden/api'; // deep RPC type (chained routers)\n * // import type { AppType } from '../../apps/api/src/index';\n *\n * const client = createRpcClient<KitsudenRpcType>('http://localhost:3001', {\n * apiKey: 'kitsuden_agent_xxx',\n * });\n *\n * const res = await client.api.health.$get();\n * const health = await res.json(); // ← typed end-to-end\n * ```\n */\n\nimport type { Hono } from \"hono\";\nimport { hc } from \"hono/client\";\n\nexport interface RpcClientOptions {\n /** Agent NHI token (kitsuden_agent_*) o API key legacy */\n apiKey?: string;\n /** Additional headers */\n headers?: Record<string, string>;\n /** custom fetch (for edge runtimes or testing) */\n fetch?: typeof fetch;\n}\n\n/**\n * Creates a typed Hono RPC client against the server's AppType.\n * No codegen, no build steps: the types flow straight from Hono.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport function createRpcClient<T extends Hono<any, any, any>>(\n baseUrl: string,\n options: RpcClientOptions = {}\n): ReturnType<typeof hc<T>> {\n const headers: Record<string, string> = { ...(options.headers ?? {}) };\n if (options.apiKey) headers[\"Authorization\"] = `Bearer ${options.apiKey}`;\n\n return hc<T>(baseUrl, {\n headers,\n // hono/client accepts a custom fetch; undefined uses the global one\n fetch: options.fetch as never,\n });\n}\n\nexport { hc } from \"hono/client\";\nexport type { InferRequestType, InferResponseType } from \"hono/client\";\n"],"mappings":"AA0BA,OAAS,MAAAA,MAAU,cA8BnB,OAAS,MAAAA,MAAU,cAdZ,SAASC,EACdC,EACAC,EAA4B,CAAC,EACH,CAC1B,IAAMC,EAAkC,CAAE,GAAID,EAAQ,SAAW,CAAC,CAAG,EACrE,OAAIA,EAAQ,SAAQC,EAAQ,cAAmB,UAAUD,EAAQ,MAAM,IAEhEH,EAAME,EAAS,CACpB,QAAAE,EAEA,MAAOD,EAAQ,KACjB,CAAC,CACH","names":["hc","createRpcClient","baseUrl","options","headers"]}
@@ -0,0 +1,2 @@
1
+ "use strict";var d=Object.defineProperty;var j=Object.getOwnPropertyDescriptor;var N=Object.getOwnPropertyNames;var T=Object.prototype.hasOwnProperty;var E=(o,e)=>{for(var r in e)d(o,r,{get:e[r],enumerable:!0})},x=(o,e,r,c)=>{if(e&&typeof e=="object"||typeof e=="function")for(let t of N(e))!T.call(o,t)&&t!==r&&d(o,t,{get:()=>e[t],enumerable:!(c=j(e,t))||c.enumerable});return o};var O=o=>x(d({},"__esModule",{value:!0}),o);var m={};E(m,{TOON_PROTOCOL_MIME:()=>b,decodeToonProtocol:()=>R,encodeToonProtocol:()=>S,fetchToon:()=>$});module.exports=O(m);var b="application/vnd.kitsuden.toon+json";function S(o){let e={},r={},c=new Map;function t(n,s){if(n===void 0)return e[s]="undefined",null;if(typeof n=="bigint")return e[s]="BigInt",n.toString();if(typeof n=="number")return Number.isNaN(n)?(e[s]="NaN","NaN"):n===1/0?(e[s]="Infinity","Infinity"):n===-1/0?(e[s]="-Infinity","-Infinity"):n;if(n===null||typeof n!="object")return n;let w=c.get(n);if(w!==void 0)return r[s]=w,null;if(c.set(n,s),n instanceof Date)return e[s]="Date",isNaN(n.getTime())?null:n.toISOString();if(n instanceof RegExp)return e[s]="RegExp",n.toString();if(n instanceof URL)return e[s]="URL",n.href;if(n instanceof Map){e[s]="Map";let u=[],a=0;for(let[g,I]of n.entries())u.push([t(g,`${s}.${a}.0`),t(I,`${s}.${a}.1`)]),a++;return u}if(n instanceof Set){e[s]="Set";let u=[],a=0;for(let g of n.values())u.push(t(g,`${s}.${a}`)),a++;return u}if(Array.isArray(n))return n.map((u,a)=>t(u,`${s}.${a}`));let p={};for(let[u,a]of Object.entries(n))p[u]=t(a,s?`${s}.${u}`:u);return p}let i={json:t(o,"")};return Object.keys(e).length>0&&(i.meta=e),Object.keys(r).length>0&&(i.refs=r),i}var k=new Set(["__proto__","constructor","prototype"]);function y(o,e){if(e==="")return o;let r=o;for(let c of e.split(".")){if(r==null||k.has(c))return;r=r[c]}return r}function l(o,e,r){if(e==="")return r;let c=e.split(".");if(c.some(i=>k.has(i)))return o;let t=o;for(let i=0;i<c.length-1;i++){let n=c[i];if(k.has(n)||t===null||typeof t!="object"||!Object.prototype.hasOwnProperty.call(t,n)||(t=t[n],t==null))return o}let f=c[c.length-1];return t===null||typeof t!="object"||f==="__proto__"||f==="constructor"||f==="prototype"||(t[f]=r),o}function R(o){let e=o.json,r=o.meta??{},c=Object.keys(r).sort((t,f)=>f.split(".").length-t.split(".").length);for(let t of c){let f=r[t],i=y(e,t),n=i;switch(f){case"Date":n=i==null?null:new Date(i);break;case"BigInt":n=BigInt(i);break;case"undefined":n=void 0;break;case"NaN":n=NaN;break;case"Infinity":n=1/0;break;case"-Infinity":n=-1/0;break;case"RegExp":{let s=/^\/(.*)\/([a-z]*)$/s.exec(i);n=s?new RegExp(s[1],s[2]):i;break}case"URL":n=new URL(i);break;case"Map":n=new Map(i);break;case"Set":n=new Set(i);break}e=l(e,t,n)}for(let[t,f]of Object.entries(o.refs??{}))e=l(e,t,y(e,f));return e}async function $(o,e={}){let r=await fetch(o,{...e,headers:{...e.headers??{},Accept:b}});if(!r.ok)throw new Error(`Toon fetch failed: ${r.status} ${r.statusText}`);let c=await r.json();return R(c)}
2
+ //# sourceMappingURL=toon-protocol.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/toon-protocol.ts"],"sourcesContent":["/**\n * @kitsuden/sdk — Toon Protocol (client-side, zero deps)\n *\n * Decoder/encoder of the KITSUDEN serialization protocol with type\n * preservation (KITSUDEN architecture §3). Mirror of the server middleware\n * (apps/api/src/lib/toon-protocol.ts).\n *\n * @example\n * ```typescript\n * import { decodeToonProtocol, TOON_PROTOCOL_MIME } from '@kitsuden/sdk/toon-protocol';\n *\n * const res = await fetch('https://api.example.com/api/graph/games', {\n * headers: { Accept: TOON_PROTOCOL_MIME },\n * });\n * const data = decodeToonProtocol(await res.json());\n * // data.rows[0].createdAt instanceof Date === true 🎉\n * ```\n */\n\nexport const TOON_PROTOCOL_MIME = \"application/vnd.kitsuden.toon+json\";\n\ntype MetaTag =\n | \"Date\"\n | \"BigInt\"\n | \"Map\"\n | \"Set\"\n | \"undefined\"\n | \"RegExp\"\n | \"URL\"\n | \"NaN\"\n | \"Infinity\"\n | \"-Infinity\";\n\nexport interface ToonEnvelope {\n json: unknown;\n meta?: Record<string, MetaTag>;\n refs?: Record<string, string>;\n}\n\n// ═══════════════════════════════════════════════════════════════\n// ENCODER (for outgoing requests with rich types)\n// ═══════════════════════════════════════════════════════════════\n\nexport function encodeToonProtocol(input: unknown): ToonEnvelope {\n const meta: Record<string, MetaTag> = {};\n const refs: Record<string, string> = {};\n const seen = new Map<object, string>();\n\n function walk(value: unknown, path: string): unknown {\n if (value === undefined) {\n meta[path] = \"undefined\";\n return null;\n }\n if (typeof value === \"bigint\") {\n meta[path] = \"BigInt\";\n return value.toString();\n }\n if (typeof value === \"number\") {\n if (Number.isNaN(value)) {\n meta[path] = \"NaN\";\n return \"NaN\";\n }\n if (value === Infinity) {\n meta[path] = \"Infinity\";\n return \"Infinity\";\n }\n if (value === -Infinity) {\n meta[path] = \"-Infinity\";\n return \"-Infinity\";\n }\n return value;\n }\n if (value === null || typeof value !== \"object\") return value;\n\n const existing = seen.get(value as object);\n if (existing !== undefined) {\n refs[path] = existing;\n return null;\n }\n seen.set(value as object, path);\n\n if (value instanceof Date) {\n meta[path] = \"Date\";\n return isNaN(value.getTime()) ? null : value.toISOString();\n }\n if (value instanceof RegExp) {\n meta[path] = \"RegExp\";\n return value.toString();\n }\n if (value instanceof URL) {\n meta[path] = \"URL\";\n return value.href;\n }\n if (value instanceof Map) {\n meta[path] = \"Map\";\n const out: unknown[] = [];\n let i = 0;\n for (const [k, v] of value.entries()) {\n out.push([walk(k, `${path}.${i}.0`), walk(v, `${path}.${i}.1`)]);\n i++;\n }\n return out;\n }\n if (value instanceof Set) {\n meta[path] = \"Set\";\n const out: unknown[] = [];\n let i = 0;\n for (const v of value.values()) {\n out.push(walk(v, `${path}.${i}`));\n i++;\n }\n return out;\n }\n if (Array.isArray(value)) {\n return value.map((v, i) => walk(v, `${path}.${i}`));\n }\n\n const out: Record<string, unknown> = {};\n for (const [k, v] of Object.entries(value as Record<string, unknown>)) {\n out[k] = walk(v, path ? `${path}.${k}` : k);\n }\n return out;\n }\n\n const json = walk(input, \"\");\n const envelope: ToonEnvelope = { json };\n if (Object.keys(meta).length > 0) envelope.meta = meta;\n if (Object.keys(refs).length > 0) envelope.refs = refs;\n return envelope;\n}\n\n// ═══════════════════════════════════════════════════════════════\n// DECODER\n// ═══════════════════════════════════════════════════════════════\n\n/**\n * Path segments that reach an object's prototype. The envelope comes from the\n * network: a `meta` or `refs` path like `__proto__.polluted` is never followed.\n */\nconst UNSAFE_SEGMENTS = new Set([\"__proto__\", \"constructor\", \"prototype\"]);\n\nfunction getByPath(root: unknown, path: string): unknown {\n if (path === \"\") return root;\n let cur = root as Record<string, unknown> | null | undefined;\n for (const seg of path.split(\".\")) {\n if (cur === null || cur === undefined || UNSAFE_SEGMENTS.has(seg)) return undefined;\n cur = cur[seg] as Record<string, unknown>;\n }\n return cur;\n}\n\nfunction setByPath(root: unknown, path: string, value: unknown): unknown {\n if (path === \"\") return value;\n const segs = path.split(\".\");\n if (segs.some((seg) => UNSAFE_SEGMENTS.has(seg))) return root;\n let cur = root as Record<string, unknown> | null | undefined;\n for (let i = 0; i < segs.length - 1; i++) {\n const seg = segs[i]!;\n if (UNSAFE_SEGMENTS.has(seg)) return root;\n // Only the object's own properties: never a path through an inherited one.\n if (\n cur === null ||\n typeof cur !== \"object\" ||\n !Object.prototype.hasOwnProperty.call(cur, seg)\n ) {\n return root;\n }\n cur = cur[seg] as Record<string, unknown>;\n if (cur === null || cur === undefined) return root;\n }\n const last = segs[segs.length - 1]!;\n if (cur === null || typeof cur !== \"object\") return root;\n if (last === \"__proto__\" || last === \"constructor\" || last === \"prototype\") return root;\n (cur as Record<string, unknown>)[last] = value;\n return root;\n}\n\nexport function decodeToonProtocol(envelope: ToonEnvelope): unknown {\n let root: unknown = envelope.json;\n const meta = envelope.meta ?? {};\n\n const paths = Object.keys(meta).sort((a, b) => b.split(\".\").length - a.split(\".\").length);\n\n for (const path of paths) {\n const tag = meta[path]!;\n const raw = getByPath(root, path);\n let revived: unknown = raw;\n\n switch (tag) {\n case \"Date\":\n revived = raw === null || raw === undefined ? null : new Date(raw as string);\n break;\n case \"BigInt\":\n revived = BigInt(raw as string);\n break;\n case \"undefined\":\n revived = undefined;\n break;\n case \"NaN\":\n revived = NaN;\n break;\n case \"Infinity\":\n revived = Infinity;\n break;\n case \"-Infinity\":\n revived = -Infinity;\n break;\n case \"RegExp\": {\n const m = /^\\/(.*)\\/([a-z]*)$/s.exec(raw as string);\n revived = m ? new RegExp(m[1]!, m[2]) : raw;\n break;\n }\n case \"URL\":\n revived = new URL(raw as string);\n break;\n case \"Map\":\n revived = new Map(raw as [unknown, unknown][]);\n break;\n case \"Set\":\n revived = new Set(raw as unknown[]);\n break;\n }\n\n root = setByPath(root, path, revived);\n }\n\n for (const [path, target] of Object.entries(envelope.refs ?? {})) {\n root = setByPath(root, path, getByPath(root, target));\n }\n\n return root;\n}\n\n/**\n * Fetch + decode in one call.\n *\n * @example\n * const data = await fetchToon('https://api.example.com/api/graph/games');\n */\nexport async function fetchToon(url: string, init: RequestInit = {}): Promise<unknown> {\n const res = await fetch(url, {\n ...init,\n headers: { ...(init.headers ?? {}), Accept: TOON_PROTOCOL_MIME },\n });\n if (!res.ok) throw new Error(`Toon fetch failed: ${res.status} ${res.statusText}`);\n const envelope = (await res.json()) as ToonEnvelope;\n return decodeToonProtocol(envelope);\n}\n"],"mappings":"yaAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,wBAAAE,EAAA,uBAAAC,EAAA,uBAAAC,EAAA,cAAAC,IAAA,eAAAC,EAAAN,GAmBO,IAAME,EAAqB,qCAwB3B,SAASE,EAAmBG,EAA8B,CAC/D,IAAMC,EAAgC,CAAC,EACjCC,EAA+B,CAAC,EAChCC,EAAO,IAAI,IAEjB,SAASC,EAAKC,EAAgBC,EAAuB,CACnD,GAAID,IAAU,OACZ,OAAAJ,EAAKK,CAAI,EAAI,YACN,KAET,GAAI,OAAOD,GAAU,SACnB,OAAAJ,EAAKK,CAAI,EAAI,SACND,EAAM,SAAS,EAExB,GAAI,OAAOA,GAAU,SACnB,OAAI,OAAO,MAAMA,CAAK,GACpBJ,EAAKK,CAAI,EAAI,MACN,OAELD,IAAU,KACZJ,EAAKK,CAAI,EAAI,WACN,YAELD,IAAU,MACZJ,EAAKK,CAAI,EAAI,YACN,aAEFD,EAET,GAAIA,IAAU,MAAQ,OAA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AI,MAAM,sBAAsBA,EAAI,MAAM,IAAIA,EAAI,UAAU,EAAE,EACjF,IAAMnB,EAAY,MAAMmB,EAAI,KAAK,EACjC,OAAOnC,EAAmBgB,CAAQ,CACpC","names":["toon_protocol_exports","__export","TOON_PROTOCOL_MIME","decodeToonProtocol","encodeToonProtocol","fetchToon","__toCommonJS","input","meta","refs","seen","walk","value","path","existing","out","i","k","v","envelope","UNSAFE_SEGMENTS","getByPath","root","cur","seg","setByPath","segs","last","paths","a","b","tag","raw","revived","m","target","url","init","res"]}
@@ -0,0 +1,36 @@
1
+ /**
2
+ * @kitsuden/sdk — Toon Protocol (client-side, zero deps)
3
+ *
4
+ * Decoder/encoder of the KITSUDEN serialization protocol with type
5
+ * preservation (KITSUDEN architecture §3). Mirror of the server middleware
6
+ * (apps/api/src/lib/toon-protocol.ts).
7
+ *
8
+ * @example
9
+ * ```typescript
10
+ * import { decodeToonProtocol, TOON_PROTOCOL_MIME } from '@kitsuden/sdk/toon-protocol';
11
+ *
12
+ * const res = await fetch('https://api.example.com/api/graph/games', {
13
+ * headers: { Accept: TOON_PROTOCOL_MIME },
14
+ * });
15
+ * const data = decodeToonProtocol(await res.json());
16
+ * // data.rows[0].createdAt instanceof Date === true 🎉
17
+ * ```
18
+ */
19
+ declare const TOON_PROTOCOL_MIME = "application/vnd.kitsuden.toon+json";
20
+ type MetaTag = "Date" | "BigInt" | "Map" | "Set" | "undefined" | "RegExp" | "URL" | "NaN" | "Infinity" | "-Infinity";
21
+ interface ToonEnvelope {
22
+ json: unknown;
23
+ meta?: Record<string, MetaTag>;
24
+ refs?: Record<string, string>;
25
+ }
26
+ declare function encodeToonProtocol(input: unknown): ToonEnvelope;
27
+ declare function decodeToonProtocol(envelope: ToonEnvelope): unknown;
28
+ /**
29
+ * Fetch + decode in one call.
30
+ *
31
+ * @example
32
+ * const data = await fetchToon('https://api.example.com/api/graph/games');
33
+ */
34
+ declare function fetchToon(url: string, init?: RequestInit): Promise<unknown>;
35
+
36
+ export { TOON_PROTOCOL_MIME, type ToonEnvelope, decodeToonProtocol, encodeToonProtocol, fetchToon };
@@ -0,0 +1,36 @@
1
+ /**
2
+ * @kitsuden/sdk — Toon Protocol (client-side, zero deps)
3
+ *
4
+ * Decoder/encoder of the KITSUDEN serialization protocol with type
5
+ * preservation (KITSUDEN architecture §3). Mirror of the server middleware
6
+ * (apps/api/src/lib/toon-protocol.ts).
7
+ *
8
+ * @example
9
+ * ```typescript
10
+ * import { decodeToonProtocol, TOON_PROTOCOL_MIME } from '@kitsuden/sdk/toon-protocol';
11
+ *
12
+ * const res = await fetch('https://api.example.com/api/graph/games', {
13
+ * headers: { Accept: TOON_PROTOCOL_MIME },
14
+ * });
15
+ * const data = decodeToonProtocol(await res.json());
16
+ * // data.rows[0].createdAt instanceof Date === true 🎉
17
+ * ```
18
+ */
19
+ declare const TOON_PROTOCOL_MIME = "application/vnd.kitsuden.toon+json";
20
+ type MetaTag = "Date" | "BigInt" | "Map" | "Set" | "undefined" | "RegExp" | "URL" | "NaN" | "Infinity" | "-Infinity";
21
+ interface ToonEnvelope {
22
+ json: unknown;
23
+ meta?: Record<string, MetaTag>;
24
+ refs?: Record<string, string>;
25
+ }
26
+ declare function encodeToonProtocol(input: unknown): ToonEnvelope;
27
+ declare function decodeToonProtocol(envelope: ToonEnvelope): unknown;
28
+ /**
29
+ * Fetch + decode in one call.
30
+ *
31
+ * @example
32
+ * const data = await fetchToon('https://api.example.com/api/graph/games');
33
+ */
34
+ declare function fetchToon(url: string, init?: RequestInit): Promise<unknown>;
35
+
36
+ export { TOON_PROTOCOL_MIME, type ToonEnvelope, decodeToonProtocol, encodeToonProtocol, fetchToon };
@@ -0,0 +1,2 @@
1
+ var b="application/vnd.kitsuden.toon+json";function I(i){let e={},r={},c=new Map;function t(n,o){if(n===void 0)return e[o]="undefined",null;if(typeof n=="bigint")return e[o]="BigInt",n.toString();if(typeof n=="number")return Number.isNaN(n)?(e[o]="NaN","NaN"):n===1/0?(e[o]="Infinity","Infinity"):n===-1/0?(e[o]="-Infinity","-Infinity"):n;if(n===null||typeof n!="object")return n;let k=c.get(n);if(k!==void 0)return r[o]=k,null;if(c.set(n,o),n instanceof Date)return e[o]="Date",isNaN(n.getTime())?null:n.toISOString();if(n instanceof RegExp)return e[o]="RegExp",n.toString();if(n instanceof URL)return e[o]="URL",n.href;if(n instanceof Map){e[o]="Map";let u=[],a=0;for(let[g,l]of n.entries())u.push([t(g,`${o}.${a}.0`),t(l,`${o}.${a}.1`)]),a++;return u}if(n instanceof Set){e[o]="Set";let u=[],a=0;for(let g of n.values())u.push(t(g,`${o}.${a}`)),a++;return u}if(Array.isArray(n))return n.map((u,a)=>t(u,`${o}.${a}`));let w={};for(let[u,a]of Object.entries(n))w[u]=t(a,o?`${o}.${u}`:u);return w}let s={json:t(i,"")};return Object.keys(e).length>0&&(s.meta=e),Object.keys(r).length>0&&(s.refs=r),s}var d=new Set(["__proto__","constructor","prototype"]);function p(i,e){if(e==="")return i;let r=i;for(let c of e.split(".")){if(r==null||d.has(c))return;r=r[c]}return r}function y(i,e,r){if(e==="")return r;let c=e.split(".");if(c.some(s=>d.has(s)))return i;let t=i;for(let s=0;s<c.length-1;s++){let n=c[s];if(d.has(n)||t===null||typeof t!="object"||!Object.prototype.hasOwnProperty.call(t,n)||(t=t[n],t==null))return i}let f=c[c.length-1];return t===null||typeof t!="object"||f==="__proto__"||f==="constructor"||f==="prototype"||(t[f]=r),i}function R(i){let e=i.json,r=i.meta??{},c=Object.keys(r).sort((t,f)=>f.split(".").length-t.split(".").length);for(let t of c){let f=r[t],s=p(e,t),n=s;switch(f){case"Date":n=s==null?null:new Date(s);break;case"BigInt":n=BigInt(s);break;case"undefined":n=void 0;break;case"NaN":n=NaN;break;case"Infinity":n=1/0;break;case"-Infinity":n=-1/0;break;case"RegExp":{let o=/^\/(.*)\/([a-z]*)$/s.exec(s);n=o?new RegExp(o[1],o[2]):s;break}case"URL":n=new URL(s);break;case"Map":n=new Map(s);break;case"Set":n=new Set(s);break}e=y(e,t,n)}for(let[t,f]of Object.entries(i.refs??{}))e=y(e,t,p(e,f));return e}async function j(i,e={}){let r=await fetch(i,{...e,headers:{...e.headers??{},Accept:b}});if(!r.ok)throw new Error(`Toon fetch failed: ${r.status} ${r.statusText}`);let c=await r.json();return R(c)}export{b as TOON_PROTOCOL_MIME,R as decodeToonProtocol,I as encodeToonProtocol,j as fetchToon};
2
+ //# sourceMappingURL=toon-protocol.js.map