@iadev93/zuno-elysia 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,9 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Ibrahim Aftab
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
6
+
7
+ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
8
+
9
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,55 @@
1
+ # @iadev93/zuno-elysia
2
+
3
+ Elysia adapter for [Zuno](https://github.com/iadev93/zuno), providing seamless state synchronization for ElysiaJS applications.
4
+
5
+ ## Installation
6
+
7
+ ```bash
8
+ pnpm add @iadev93/zuno-elysia
9
+ ```
10
+
11
+ ## Usage
12
+
13
+ ```typescript
14
+ import { Elysia } from 'elysia'
15
+ import { cors } from '@elysiajs/cors'
16
+ import { createZunoElysia } from '@iadev93/zuno-elysia'
17
+
18
+ const app = new Elysia()
19
+ .use(cors())
20
+
21
+ const zuno = createZunoElysia()
22
+
23
+ // Register Zuno handlers
24
+ app.get('/zuno/sse', zuno.sse)
25
+ app.post('/zuno/sync', zuno.sync)
26
+ app.get('/zuno/snapshot', zuno.snapshot)
27
+
28
+ app.listen(3002)
29
+ ```
30
+
31
+ ## API
32
+
33
+ ### `createZunoElysia()`
34
+
35
+ Returns an object containing the following handlers:
36
+
37
+ #### `sse` (GET)
38
+ An async generator handler for Server-Sent Events. It automatically handles:
39
+ - Connection keep-alive and heartbeats.
40
+ - Reconnection logic via `last-event-id`.
41
+ - Initial state snapshots for fresh connections.
42
+
43
+ #### `sync` (POST)
44
+ Validates and applies incoming state events to the Zuno universe. Handles version conflicts and broadcasts updates to all connected SSE clients.
45
+
46
+ #### `snapshot` (GET)
47
+ Returns the current full state of the universe, the current version, and the last event ID.
48
+
49
+ ## Features
50
+ - **Native SSE**: Uses Elysia's optimized streaming capabilities with async generators.
51
+ - **Lightweight**: Zero runtime dependencies on Elysia itself (uses structural typing).
52
+ - **Type Safe**: Fully written in TypeScript with comprehensive docstrings.
53
+
54
+ ## License
55
+ MIT
@@ -0,0 +1,66 @@
1
+ import type { ZunoStateEvent } from "@iadev93/zuno";
2
+ /**
3
+ * Creates a Zuno Elysia instance.
4
+ * @returns {Object} An object with the following properties:
5
+ * - sse: An async generator function that handles SSE connections for Elysia.
6
+ * @property {Object} set - Elysia response object.
7
+ * @property {Object} headers - Elysia request headers.
8
+ * @property {Object} query - Elysia request query parameters.
9
+ * - sync: A function that handles sync POST requests for Elysia.
10
+ * @property {Object} body - Elysia request body.
11
+ * @property {Object} set - Elysia response object.
12
+ * - snapshot: A function that handles snapshot GET requests for Elysia.
13
+ */
14
+ export declare function createZunoElysia(): {
15
+ /**
16
+ * Handles SSE connections for Elysia using an async generator.
17
+ * @param {Object} param - Elysia request object.
18
+ * @param {Object} param.set - Elysia response object.
19
+ * @param {Object} param.headers - Elysia request headers.
20
+ * @param {Object} param.query - Elysia request query parameters.
21
+ */
22
+ sse: ({ set, headers, query }: any) => AsyncGenerator<string | {
23
+ readonly data: string;
24
+ }, never, unknown>;
25
+ /**
26
+ * Handles sync POST requests for Elysia.
27
+ * @param {Object} param - Elysia request object.
28
+ * @param {Object} param.body - Elysia request body.
29
+ * @param {Object} param.set - Elysia response object.
30
+ * @returns {Object} An object with the following properties:
31
+ * - ok: A boolean indicating whether the sync was successful.
32
+ * - event: The event that was applied to the universe.
33
+ */
34
+ sync: ({ body, set }: any) => {
35
+ ok: boolean;
36
+ reason: "VERSION_CONFLICT";
37
+ current: {
38
+ state: any;
39
+ version: number;
40
+ };
41
+ event?: undefined;
42
+ } | {
43
+ ok: boolean;
44
+ event: ZunoStateEvent;
45
+ reason?: undefined;
46
+ current?: undefined;
47
+ };
48
+ /**
49
+ * Handles snapshot GET requests for Elysia.
50
+ * @returns {Object} An object with the following properties:
51
+ * - state: The current state of the universe.
52
+ * - version: The version of the universe.
53
+ * - lastEventId: The ID of the last event in the universe.
54
+ */
55
+ snapshot: () => {
56
+ state: {
57
+ [k: string]: {
58
+ state: any;
59
+ version: number;
60
+ };
61
+ };
62
+ version: any;
63
+ lastEventId: number;
64
+ };
65
+ };
66
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,eAAe,CAAC;AAUpD;;;;;;;;;;;GAWG;AACH,wBAAgB,gBAAgB;IAE5B;;;;;;OAMG;mCAC4C,GAAG;;;IA8DlD;;;;;;;;OAQG;0BACmB,GAAG;;;;;;;;;;;;;;IAgBzB;;;;;;OAMG;;;;;;;;;;;EASN"}
package/dist/index.js ADDED
@@ -0,0 +1,116 @@
1
+ import { applyStateEvent, getEventsAfter, getLastEventId, getUniverseState, subscribeToStateEvents, } from "@iadev93/zuno/server";
2
+ import { sse as elysiaSSE } from "elysia";
3
+ /**
4
+ * Creates a Zuno Elysia instance.
5
+ * @returns {Object} An object with the following properties:
6
+ * - sse: An async generator function that handles SSE connections for Elysia.
7
+ * @property {Object} set - Elysia response object.
8
+ * @property {Object} headers - Elysia request headers.
9
+ * @property {Object} query - Elysia request query parameters.
10
+ * - sync: A function that handles sync POST requests for Elysia.
11
+ * @property {Object} body - Elysia request body.
12
+ * @property {Object} set - Elysia response object.
13
+ * - snapshot: A function that handles snapshot GET requests for Elysia.
14
+ */
15
+ export function createZunoElysia() {
16
+ return {
17
+ /**
18
+ * Handles SSE connections for Elysia using an async generator.
19
+ * @param {Object} param - Elysia request object.
20
+ * @param {Object} param.set - Elysia response object.
21
+ * @param {Object} param.headers - Elysia request headers.
22
+ * @param {Object} param.query - Elysia request query parameters.
23
+ */
24
+ sse: async function* ({ set, headers, query }) {
25
+ set.headers["Content-Type"] = "text/event-stream";
26
+ set.headers["Cache-Control"] = "no-cache";
27
+ set.headers["Connection"] = "keep-alive";
28
+ yield elysiaSSE(": connected\n");
29
+ yield elysiaSSE(":" + " ".repeat(2048) + "\n\n"); // Padding to bypass browser buffering
30
+ // Get last event id
31
+ const rawLastEventId = headers["last-event-id"] || query?.lastEventId;
32
+ const lastEventId = Number.parseInt(rawLastEventId || "0", 10) || 0;
33
+ if (lastEventId > 0) {
34
+ const missed = getEventsAfter(lastEventId);
35
+ for (const event of missed) {
36
+ yield elysiaSSE(`id: ${event.eventId}\nevent: state\ndata: ${JSON.stringify(event)}\n\n`);
37
+ }
38
+ }
39
+ else {
40
+ const snapshot = getUniverseState();
41
+ yield elysiaSSE(`event: snapshot\ndata: ${JSON.stringify(snapshot)}\n\n`);
42
+ }
43
+ // Buffer queue for events
44
+ const queue = [];
45
+ let resolve = null;
46
+ // Subscribe to events
47
+ const unsubscribe = subscribeToStateEvents((event) => {
48
+ queue.push(`id: ${event.eventId}\nevent: state\ndata: ${JSON.stringify(event)}\n\n`);
49
+ if (resolve) {
50
+ resolve();
51
+ resolve = null;
52
+ }
53
+ });
54
+ // Heartbeat interval
55
+ const heartbeat = setInterval(() => {
56
+ queue.push(`: ping ${Date.now()}\n\n`);
57
+ if (resolve) {
58
+ resolve();
59
+ resolve = null;
60
+ }
61
+ }, 15000);
62
+ try {
63
+ while (true) {
64
+ if (queue.length === 0) {
65
+ await new Promise((r) => {
66
+ resolve = r;
67
+ });
68
+ }
69
+ while (queue.length > 0) {
70
+ yield queue.shift();
71
+ }
72
+ }
73
+ }
74
+ finally {
75
+ clearInterval(heartbeat);
76
+ unsubscribe();
77
+ }
78
+ },
79
+ /**
80
+ * Handles sync POST requests for Elysia.
81
+ * @param {Object} param - Elysia request object.
82
+ * @param {Object} param.body - Elysia request body.
83
+ * @param {Object} param.set - Elysia response object.
84
+ * @returns {Object} An object with the following properties:
85
+ * - ok: A boolean indicating whether the sync was successful.
86
+ * - event: The event that was applied to the universe.
87
+ */
88
+ sync: ({ body, set }) => {
89
+ const incoming = body;
90
+ const result = applyStateEvent(incoming);
91
+ if (!result.ok) {
92
+ set.status = 409;
93
+ return {
94
+ ok: false,
95
+ reason: result.reason,
96
+ current: result.current,
97
+ };
98
+ }
99
+ return { ok: true, event: result.event };
100
+ },
101
+ /**
102
+ * Handles snapshot GET requests for Elysia.
103
+ * @returns {Object} An object with the following properties:
104
+ * - state: The current state of the universe.
105
+ * - version: The version of the universe.
106
+ * - lastEventId: The ID of the last event in the universe.
107
+ */
108
+ snapshot: () => {
109
+ return {
110
+ state: getUniverseState(),
111
+ version: getUniverseState().version ?? 0,
112
+ lastEventId: getLastEventId(),
113
+ };
114
+ },
115
+ };
116
+ }
package/package.json ADDED
@@ -0,0 +1,29 @@
1
+ {
2
+ "name": "@iadev93/zuno-elysia",
3
+ "version": "0.0.1",
4
+ "main": "./dist/index.js",
5
+ "types": "./dist/index.d.ts",
6
+ "files": [
7
+ "dist"
8
+ ],
9
+ "exports": {
10
+ ".": {
11
+ "types": "./dist/index.d.ts",
12
+ "default": "./dist/index.js"
13
+ }
14
+ },
15
+ "peerDependencies": {
16
+ "elysia": ">=1.0.0",
17
+ "@iadev93/zuno": "0.0.5"
18
+ },
19
+ "devDependencies": {
20
+ "elysia": "^1.2.10",
21
+ "typescript": "^5.9.3",
22
+ "@iadev93/zuno": "0.0.5"
23
+ },
24
+ "author": "Ibrahim Aftab",
25
+ "license": "MIT",
26
+ "scripts": {
27
+ "build": "tsc -p tsconfig.json"
28
+ }
29
+ }