@syncular/server-hono 0.0.6-95 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (104) hide show
  1. package/README.md +5 -23
  2. package/dist/admin-page.d.ts +14 -0
  3. package/dist/admin-page.js +217 -0
  4. package/dist/admin.d.ts +39 -0
  5. package/dist/admin.js +142 -0
  6. package/dist/index.d.ts +16 -14
  7. package/dist/index.js +134 -23
  8. package/package.json +19 -53
  9. package/src/admin-page.ts +217 -0
  10. package/src/admin.ts +193 -0
  11. package/src/index.ts +175 -31
  12. package/dist/api-key-auth.d.ts +0 -49
  13. package/dist/api-key-auth.d.ts.map +0 -1
  14. package/dist/api-key-auth.js +0 -110
  15. package/dist/api-key-auth.js.map +0 -1
  16. package/dist/blobs.d.ts +0 -69
  17. package/dist/blobs.d.ts.map +0 -1
  18. package/dist/blobs.js +0 -383
  19. package/dist/blobs.js.map +0 -1
  20. package/dist/console/gateway.d.ts +0 -33
  21. package/dist/console/gateway.d.ts.map +0 -1
  22. package/dist/console/gateway.js +0 -2534
  23. package/dist/console/gateway.js.map +0 -1
  24. package/dist/console/index.d.ts +0 -11
  25. package/dist/console/index.d.ts.map +0 -1
  26. package/dist/console/index.js +0 -11
  27. package/dist/console/index.js.map +0 -1
  28. package/dist/console/routes.d.ts +0 -33
  29. package/dist/console/routes.d.ts.map +0 -1
  30. package/dist/console/routes.js +0 -2890
  31. package/dist/console/routes.js.map +0 -1
  32. package/dist/console/schemas.d.ts +0 -490
  33. package/dist/console/schemas.d.ts.map +0 -1
  34. package/dist/console/schemas.js +0 -303
  35. package/dist/console/schemas.js.map +0 -1
  36. package/dist/console/types.d.ts +0 -142
  37. package/dist/console/types.d.ts.map +0 -1
  38. package/dist/console/types.js +0 -2
  39. package/dist/console/types.js.map +0 -1
  40. package/dist/console/ui.d.ts +0 -38
  41. package/dist/console/ui.d.ts.map +0 -1
  42. package/dist/console/ui.js +0 -43
  43. package/dist/console/ui.js.map +0 -1
  44. package/dist/create-server.d.ts +0 -68
  45. package/dist/create-server.d.ts.map +0 -1
  46. package/dist/create-server.js +0 -109
  47. package/dist/create-server.js.map +0 -1
  48. package/dist/index.d.ts.map +0 -1
  49. package/dist/index.js.map +0 -1
  50. package/dist/openapi.d.ts +0 -45
  51. package/dist/openapi.d.ts.map +0 -1
  52. package/dist/openapi.js +0 -59
  53. package/dist/openapi.js.map +0 -1
  54. package/dist/proxy/connection-manager.d.ts +0 -78
  55. package/dist/proxy/connection-manager.d.ts.map +0 -1
  56. package/dist/proxy/connection-manager.js +0 -251
  57. package/dist/proxy/connection-manager.js.map +0 -1
  58. package/dist/proxy/index.d.ts +0 -8
  59. package/dist/proxy/index.d.ts.map +0 -1
  60. package/dist/proxy/index.js +0 -8
  61. package/dist/proxy/index.js.map +0 -1
  62. package/dist/proxy/routes.d.ts +0 -74
  63. package/dist/proxy/routes.d.ts.map +0 -1
  64. package/dist/proxy/routes.js +0 -147
  65. package/dist/proxy/routes.js.map +0 -1
  66. package/dist/rate-limit.d.ts +0 -101
  67. package/dist/rate-limit.d.ts.map +0 -1
  68. package/dist/rate-limit.js +0 -186
  69. package/dist/rate-limit.js.map +0 -1
  70. package/dist/routes.d.ts +0 -145
  71. package/dist/routes.d.ts.map +0 -1
  72. package/dist/routes.js +0 -1471
  73. package/dist/routes.js.map +0 -1
  74. package/dist/ws.d.ts +0 -235
  75. package/dist/ws.d.ts.map +0 -1
  76. package/dist/ws.js +0 -614
  77. package/dist/ws.js.map +0 -1
  78. package/src/__tests__/blob-routes.test.ts +0 -424
  79. package/src/__tests__/console-gateway-live-routes.test.ts +0 -297
  80. package/src/__tests__/console-gateway-routes.test.ts +0 -1364
  81. package/src/__tests__/console-routes.test.ts +0 -1543
  82. package/src/__tests__/console-ui.test.ts +0 -114
  83. package/src/__tests__/create-server.test.ts +0 -342
  84. package/src/__tests__/pull-chunk-storage.test.ts +0 -576
  85. package/src/__tests__/rate-limit.test.ts +0 -78
  86. package/src/__tests__/realtime-bridge.test.ts +0 -135
  87. package/src/__tests__/sync-rate-limit-routing.test.ts +0 -185
  88. package/src/__tests__/ws-connection-manager.test.ts +0 -176
  89. package/src/api-key-auth.ts +0 -179
  90. package/src/blobs.ts +0 -534
  91. package/src/console/gateway.ts +0 -3603
  92. package/src/console/index.ts +0 -11
  93. package/src/console/routes.ts +0 -3748
  94. package/src/console/schemas.ts +0 -434
  95. package/src/console/types.ts +0 -151
  96. package/src/console/ui.ts +0 -100
  97. package/src/create-server.ts +0 -206
  98. package/src/openapi.ts +0 -74
  99. package/src/proxy/connection-manager.ts +0 -340
  100. package/src/proxy/index.ts +0 -8
  101. package/src/proxy/routes.ts +0 -223
  102. package/src/rate-limit.ts +0 -321
  103. package/src/routes.ts +0 -2007
  104. package/src/ws.ts +0 -802
@@ -1,114 +0,0 @@
1
- import { afterEach, describe, expect, it } from 'bun:test';
2
- import { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises';
3
- import { tmpdir } from 'node:os';
4
- import path from 'node:path';
5
- import {
6
- CONSOLE_BASEPATH_META,
7
- CONSOLE_SERVER_URL_META,
8
- CONSOLE_TOKEN_META,
9
- } from '@syncular/console/runtime-config';
10
- import { Hono } from 'hono';
11
- import { mountConsoleUi } from '../console/ui';
12
-
13
- const tempDirs: string[] = [];
14
-
15
- async function createStaticFixture(): Promise<string> {
16
- const staticDir = await mkdtemp(path.join(tmpdir(), 'syncular-console-ui-'));
17
- tempDirs.push(staticDir);
18
-
19
- await mkdir(path.join(staticDir, 'assets'), { recursive: true });
20
- await writeFile(
21
- path.join(staticDir, 'index.html'),
22
- `<!doctype html>
23
- <html>
24
- <head>
25
- <meta name="${CONSOLE_BASEPATH_META}" content="" />
26
- <meta name="${CONSOLE_SERVER_URL_META}" content="" />
27
- <meta name="${CONSOLE_TOKEN_META}" content="" />
28
- <link rel="stylesheet" href="/assets/console.css" />
29
- </head>
30
- <body>
31
- <script type="module" src="/assets/main.js"></script>
32
- </body>
33
- </html>`
34
- );
35
- await writeFile(
36
- path.join(staticDir, 'assets', 'main.js'),
37
- 'console.log(1);\n'
38
- );
39
- await writeFile(path.join(staticDir, 'assets', 'console.css'), 'body{}\n');
40
-
41
- return staticDir;
42
- }
43
-
44
- afterEach(async () => {
45
- await Promise.all(
46
- tempDirs.splice(0).map((dir) => rm(dir, { recursive: true, force: true }))
47
- );
48
- });
49
-
50
- describe('mountConsoleUi', () => {
51
- it('serves console UI with default prefill derived from mount/api paths', async () => {
52
- const staticDir = await createStaticFixture();
53
- const app = new Hono();
54
-
55
- mountConsoleUi(app, {
56
- mountPath: 'console',
57
- apiBasePath: 'api',
58
- staticDir,
59
- });
60
-
61
- const response = await app.request('http://example.test/console');
62
- const html = await response.text();
63
-
64
- expect(response.status).toBe(200);
65
- expect(html).toContain(
66
- `<meta name="${CONSOLE_BASEPATH_META}" content="/console" />`
67
- );
68
- expect(html).toContain(
69
- `<meta name="${CONSOLE_SERVER_URL_META}" content="http://example.test/api" />`
70
- );
71
- expect(html).toContain(`<meta name="${CONSOLE_TOKEN_META}" content="" />`);
72
- expect(html).toContain('href="/console/assets/console.css"');
73
- expect(html).toContain('src="/console/assets/main.js"');
74
-
75
- const asset = await app.request(
76
- 'http://example.test/console/assets/main.js'
77
- );
78
- expect(asset.status).toBe(200);
79
- expect(await asset.text()).toContain('console.log(1);');
80
- });
81
-
82
- it('merges resolvePrefill and allows resolveToken to override token', async () => {
83
- const staticDir = await createStaticFixture();
84
- const app = new Hono();
85
-
86
- mountConsoleUi(app, {
87
- mountPath: '/ops-console',
88
- apiBasePath: '/api/internal',
89
- staticDir,
90
- resolvePrefill: async () => ({
91
- basePath: '/prefilled',
92
- serverUrl: 'https://prefill.example/api',
93
- token: 'prefill-token',
94
- }),
95
- resolveToken: async () => 'resolver-token',
96
- });
97
-
98
- const response = await app.request('http://localhost/ops-console');
99
- const html = await response.text();
100
-
101
- expect(response.status).toBe(200);
102
- expect(html).toContain(
103
- `<meta name="${CONSOLE_BASEPATH_META}" content="/prefilled" />`
104
- );
105
- expect(html).toContain(
106
- `<meta name="${CONSOLE_SERVER_URL_META}" content="https://prefill.example/api" />`
107
- );
108
- expect(html).toContain(
109
- `<meta name="${CONSOLE_TOKEN_META}" content="resolver-token" />`
110
- );
111
- expect(html).toContain('href="/prefilled/assets/console.css"');
112
- expect(html).toContain('src="/prefilled/assets/main.js"');
113
- });
114
- });
@@ -1,342 +0,0 @@
1
- import { afterEach, beforeEach, describe, expect, it } from 'bun:test';
2
- import { createDatabase } from '@syncular/core';
3
- import { createPgliteDialect } from '@syncular/dialect-pglite';
4
- import {
5
- createServerHandler,
6
- ensureSyncSchema,
7
- type SyncCoreDb,
8
- } from '@syncular/server';
9
- import { createPostgresServerDialect } from '@syncular/server-dialect-postgres';
10
- import { Hono } from 'hono';
11
- import { defineWebSocketHelper } from 'hono/ws';
12
- import type { Kysely } from 'kysely';
13
- import { createSyncServer } from '../create-server';
14
- import { getSyncWebSocketConnectionManager } from '../routes';
15
- import type { WebSocketConnection } from '../ws';
16
-
17
- interface TasksTable {
18
- id: string;
19
- user_id: string;
20
- title: string;
21
- server_version: number;
22
- }
23
-
24
- interface ServerDb extends SyncCoreDb {
25
- tasks: TasksTable;
26
- }
27
-
28
- interface ClientDb {
29
- tasks: TasksTable;
30
- }
31
-
32
- describe('createSyncServer console configuration', () => {
33
- let db: Kysely<ServerDb>;
34
- let previousConsoleToken: string | undefined;
35
-
36
- beforeEach(async () => {
37
- db = createDatabase<ServerDb>({
38
- dialect: createPgliteDialect(),
39
- family: 'postgres',
40
- });
41
- await ensureSyncSchema(db, createPostgresServerDialect());
42
- await db.schema
43
- .createTable('tasks')
44
- .ifNotExists()
45
- .addColumn('id', 'text', (col) => col.primaryKey())
46
- .addColumn('user_id', 'text', (col) => col.notNull())
47
- .addColumn('title', 'text', (col) => col.notNull())
48
- .addColumn('server_version', 'integer', (col) =>
49
- col.notNull().defaultTo(0)
50
- )
51
- .execute();
52
- previousConsoleToken = process.env.SYNC_CONSOLE_TOKEN;
53
- delete process.env.SYNC_CONSOLE_TOKEN;
54
- });
55
-
56
- afterEach(async () => {
57
- if (previousConsoleToken === undefined) {
58
- delete process.env.SYNC_CONSOLE_TOKEN;
59
- } else {
60
- process.env.SYNC_CONSOLE_TOKEN = previousConsoleToken;
61
- }
62
- await db.destroy();
63
- });
64
-
65
- function createTestHandler() {
66
- return createServerHandler<ServerDb, ClientDb, 'tasks'>({
67
- table: 'tasks',
68
- scopes: ['user:{user_id}'],
69
- resolveScopes: async (ctx) => ({ user_id: [ctx.actorId] }),
70
- });
71
- }
72
-
73
- function createOptions() {
74
- return {
75
- db,
76
- dialect: createPostgresServerDialect(),
77
- sync: {
78
- handlers: [createTestHandler()],
79
- authenticate: async () => ({ actorId: 'u1' }),
80
- },
81
- };
82
- }
83
-
84
- function createConn(args: {
85
- actorId: string;
86
- clientId: string;
87
- }): WebSocketConnection {
88
- return {
89
- actorId: args.actorId,
90
- clientId: args.clientId,
91
- transportPath: 'direct',
92
- get isOpen() {
93
- return true;
94
- },
95
- sendSync() {},
96
- sendHeartbeat() {},
97
- sendPresence() {},
98
- sendError() {},
99
- close() {},
100
- };
101
- }
102
-
103
- function createPushRequest(): Request {
104
- return new Request('http://localhost/sync', {
105
- method: 'POST',
106
- headers: { 'content-type': 'application/json' },
107
- body: JSON.stringify({
108
- clientId: 'client-1',
109
- push: {
110
- clientCommitId: 'commit-1',
111
- schemaVersion: 1,
112
- operations: [
113
- {
114
- table: 'tasks',
115
- row_id: 'task-1',
116
- op: 'upsert',
117
- payload: {
118
- id: 'task-1',
119
- user_id: 'u1',
120
- title: 'Task 1',
121
- server_version: 0,
122
- },
123
- },
124
- ],
125
- },
126
- }),
127
- });
128
- }
129
-
130
- it('keeps console routes disabled when console config is omitted', () => {
131
- const server = createSyncServer(createOptions());
132
- expect(server.consoleRoutes).toBeUndefined();
133
- });
134
-
135
- it('throws when console is enabled without a token', () => {
136
- const options = createOptions();
137
- expect(() =>
138
- createSyncServer({
139
- ...options,
140
- console: {},
141
- })
142
- ).toThrow(
143
- 'Console is enabled but no token is configured. Set `console.token` or SYNC_CONSOLE_TOKEN.'
144
- );
145
- });
146
-
147
- it('accepts SYNC_CONSOLE_TOKEN when console token is omitted', () => {
148
- process.env.SYNC_CONSOLE_TOKEN = 'env-token';
149
- const options = createOptions();
150
- const server = createSyncServer({
151
- ...options,
152
- console: {},
153
- });
154
- expect(server.consoleRoutes).toBeDefined();
155
- });
156
-
157
- it('accepts an explicit console token', () => {
158
- process.env.SYNC_CONSOLE_TOKEN = 'env-token';
159
- const options = createOptions();
160
- const server = createSyncServer({
161
- ...options,
162
- console: { token: 'explicit-token' },
163
- });
164
- expect(server.consoleRoutes).toBeDefined();
165
- });
166
-
167
- it('returns not implemented when blobBucket is not configured', async () => {
168
- const options = createOptions();
169
- const server = createSyncServer({
170
- ...options,
171
- console: {
172
- token: 'console-token',
173
- },
174
- });
175
-
176
- const app = new Hono();
177
- app.route('/console', server.consoleRoutes!);
178
-
179
- const response = await app.request('http://localhost/console/storage', {
180
- headers: { Authorization: 'Bearer console-token' },
181
- });
182
-
183
- expect(response.status).toBe(501);
184
- expect(await response.json()).toEqual({
185
- error: 'BLOB_STORAGE_NOT_CONFIGURED',
186
- });
187
- });
188
-
189
- it('enables storage console routes when blobBucket is configured', async () => {
190
- const options = createOptions();
191
- const server = createSyncServer({
192
- ...options,
193
- console: {
194
- token: 'blob-token',
195
- blobBucket: {
196
- list: async () => ({
197
- objects: [
198
- {
199
- key: 'hello.txt',
200
- size: 12,
201
- uploaded: new Date('2025-01-01T00:00:00.000Z'),
202
- httpMetadata: { contentType: 'text/plain' },
203
- },
204
- ],
205
- truncated: false,
206
- cursor: undefined,
207
- }),
208
- get: async () => null,
209
- delete: async () => {},
210
- head: async () => null,
211
- },
212
- },
213
- });
214
-
215
- const app = new Hono();
216
- app.route('/console', server.consoleRoutes!);
217
-
218
- const unauthenticated = await app.request(
219
- 'http://localhost/console/storage'
220
- );
221
- expect(unauthenticated.status).toBe(401);
222
-
223
- const response = await app.request('http://localhost/console/storage', {
224
- headers: { Authorization: 'Bearer blob-token' },
225
- });
226
- expect(response.status).toBe(200);
227
- expect(await response.json()).toEqual({
228
- items: [
229
- {
230
- key: 'hello.txt',
231
- size: 12,
232
- uploaded: '2025-01-01T00:00:00.000Z',
233
- httpMetadata: { contentType: 'text/plain' },
234
- },
235
- ],
236
- truncated: false,
237
- cursor: null,
238
- });
239
- });
240
-
241
- it('forwards maxConnectionsPerClient from factory to realtime route', async () => {
242
- const options = createOptions();
243
- const upgradeWebSocket = defineWebSocketHelper(async () => {});
244
-
245
- const server = createSyncServer({
246
- ...options,
247
- upgradeWebSocket,
248
- routes: {
249
- websocket: {
250
- maxConnectionsPerClient: 1,
251
- },
252
- },
253
- });
254
-
255
- const manager = getSyncWebSocketConnectionManager(server.syncRoutes);
256
- if (!manager) {
257
- throw new Error('Expected websocket manager to be enabled.');
258
- }
259
- manager.register(createConn({ actorId: 'u1', clientId: 'client-1' }), []);
260
-
261
- const app = new Hono();
262
- app.route('/sync', server.syncRoutes);
263
-
264
- const response = await app.request(
265
- 'http://localhost/sync/realtime?clientId=client-1'
266
- );
267
- expect(response.status).toBe(429);
268
- expect(await response.json()).toEqual({
269
- error: 'WEBSOCKET_CONNECTION_LIMIT_CLIENT',
270
- });
271
- });
272
-
273
- it('forwards maxConnectionsTotal from factory to realtime route', async () => {
274
- const options = createOptions();
275
- const upgradeWebSocket = defineWebSocketHelper(async () => {});
276
-
277
- const server = createSyncServer({
278
- ...options,
279
- upgradeWebSocket,
280
- routes: {
281
- websocket: {
282
- maxConnectionsTotal: 1,
283
- },
284
- },
285
- });
286
-
287
- const manager = getSyncWebSocketConnectionManager(server.syncRoutes);
288
- if (!manager) {
289
- throw new Error('Expected websocket manager to be enabled.');
290
- }
291
- manager.register(createConn({ actorId: 'u1', clientId: 'client-1' }), []);
292
-
293
- const app = new Hono();
294
- app.route('/sync', server.syncRoutes);
295
-
296
- const response = await app.request(
297
- 'http://localhost/sync/realtime?clientId=client-2'
298
- );
299
- expect(response.status).toBe(429);
300
- expect(await response.json()).toEqual({
301
- error: 'WEBSOCKET_CONNECTION_LIMIT_TOTAL',
302
- });
303
- });
304
-
305
- it('emits live console events from sync lifecycle when console is enabled', async () => {
306
- process.env.SYNC_CONSOLE_TOKEN = 'env-token';
307
- const options = createOptions();
308
- const server = createSyncServer({
309
- ...options,
310
- console: {},
311
- });
312
-
313
- const liveEvents: Array<{
314
- type: string;
315
- data: Record<string, unknown>;
316
- }> = [];
317
- const listener = (event: {
318
- type: 'push' | 'pull' | 'commit' | 'client_update';
319
- timestamp: string;
320
- data: Record<string, unknown>;
321
- }) => {
322
- liveEvents.push({ type: event.type, data: event.data });
323
- };
324
-
325
- server.consoleEventEmitter?.addListener(listener);
326
- const app = new Hono();
327
- app.route('/sync', server.syncRoutes);
328
-
329
- const response = await app.request(createPushRequest());
330
- expect(response.status).toBe(200);
331
-
332
- const emittedTypes = liveEvents.map((event) => event.type);
333
- expect(emittedTypes).toContain('push');
334
- expect(emittedTypes).toContain('commit');
335
-
336
- const pushEvent = liveEvents.find((event) => event.type === 'push');
337
- expect(pushEvent?.data.actorId).toBe('u1');
338
- expect(pushEvent?.data.clientId).toBe('client-1');
339
-
340
- server.consoleEventEmitter?.removeListener(listener);
341
- });
342
- });