@syncular/server-hono 0.37.0 → 0.39.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 (3) hide show
  1. package/dist/index.js +50 -32
  2. package/package.json +3 -3
  3. package/src/index.ts +71 -33
package/dist/index.js CHANGED
@@ -4,7 +4,7 @@
4
4
  * Mounts the §1.1 routes including sync, registered operations, segments, and
5
5
  * blobs. Realtime upgrades are runtime-specific and stay with the host.
6
6
  */
7
- import { adapterSyncError, composeEvents, encodeSegmentBody, encodeSegmentStream, errorBody, handleBlobDownload, handleBlobUpload, handleBlobUploadGrant, openSegmentDownload, handleRemoteOperation, handleSyncRequest, RealtimeHub, RingBufferEvents, SEGMENT_STREAM_THRESHOLD_BYTES, SSP2_CONTENT_TYPE, SyncError, SyncularAdmin, } from '@syncular/server';
7
+ import { adapterSyncError, composeEvents, decodeRequestBody, encodeBody, encodeStream, errorBody, handleBlobDownload, handleBlobUpload, handleBlobUploadGrant, openSegmentDownload, handleRemoteOperation, handleSyncRequest, RealtimeHub, RingBufferEvents, SEGMENT_STREAM_THRESHOLD_BYTES, SSP2_CONTENT_TYPE, SyncError, SyncularAdmin, varyOnAcceptEncoding, } from '@syncular/server';
8
8
  import { Hono } from 'hono';
9
9
  import { createSyncularAdminRoutes } from './admin.js';
10
10
  export * from './admin.js';
@@ -41,6 +41,32 @@ export function createSyncularHono(options) {
41
41
  });
42
42
  return c.newResponse(response.body, response);
43
43
  };
44
+ // §1.3: a client MAY gzip its request body; any other declared
45
+ // `Content-Encoding` is refused with 415 instead of being misread.
46
+ const unsupportedEncoding = (c, route) => c.json(errorBody(new SyncError(route === 'sync'
47
+ ? 'sync.invalid_request'
48
+ : 'operation.invalid_request', 'unsupported content encoding')), 415);
49
+ // §1.3: every buffered body — a sync round, an operation result, a blob, a
50
+ // segment — is encoded per the request's `Accept-Encoding` (zstd preferred,
51
+ // gzip fallback, identity otherwise) and carries `Vary: Accept-Encoding`.
52
+ // Headers are built through the Hono context so host middleware headers
53
+ // survive; `encodeBody: 'manual'` marks the body as already encoded, so
54
+ // workerd does not encode it a second time (see ALREADY_ENCODED).
55
+ const encodedResponse = async (c, bytes, headers) => {
56
+ const encoded = await encodeBody(bytes, c.req.header('accept-encoding'));
57
+ const out = c.newResponse(null, 200, {
58
+ ...headers,
59
+ ...(encoded.contentEncoding !== undefined
60
+ ? { 'Content-Encoding': encoded.contentEncoding }
61
+ : {}),
62
+ }).headers;
63
+ varyOnAcceptEncoding(out);
64
+ return new Response(encoded.bytes.slice().buffer, {
65
+ status: 200,
66
+ headers: out,
67
+ ...ALREADY_ENCODED,
68
+ });
69
+ };
44
70
  // Throws outside a route's own try, such as from `authenticate`.
45
71
  app.onError((error, c) => {
46
72
  const segment = c.req.path.split('/')[1];
@@ -58,12 +84,14 @@ export function createSyncularHono(options) {
58
84
  if (auth === null)
59
85
  return errorResponse(c, new SyncError('sync.auth_required'));
60
86
  try {
61
- const bytes = new Uint8Array(await c.req.arrayBuffer());
87
+ const bytes = await decodeRequestBody(c.req.raw);
88
+ if (bytes === undefined)
89
+ return unsupportedEncoding(c, 'sync');
62
90
  const out = await handleSyncRequest(bytes, {
63
91
  ...config,
64
92
  ...auth,
65
93
  });
66
- return c.body(out.slice().buffer, 200, {
94
+ return await encodedResponse(c, out, {
67
95
  'Content-Type': SSP2_CONTENT_TYPE,
68
96
  });
69
97
  }
@@ -83,9 +111,11 @@ export function createSyncularHono(options) {
83
111
  if (auth === null)
84
112
  return errorResponse(c, new SyncError('sync.auth_required'));
85
113
  try {
86
- const bytes = new Uint8Array(await c.req.arrayBuffer());
114
+ const bytes = await decodeRequestBody(c.req.raw);
115
+ if (bytes === undefined)
116
+ return unsupportedEncoding(c, 'operations');
87
117
  const out = await handleRemoteOperation(bytes, { ...config, ...auth }, options.operations);
88
- return c.body(out.slice().buffer, 200, {
118
+ return await encodedResponse(c, out, {
89
119
  'Content-Type': 'application/vnd.syncular.operations.v1+json',
90
120
  });
91
121
  }
@@ -109,8 +139,8 @@ export function createSyncularHono(options) {
109
139
  const acceptEncoding = c.req.header('accept-encoding');
110
140
  if (result.byteLength > SEGMENT_STREAM_THRESHOLD_BYTES) {
111
141
  // A large segment (a sqlite image) is relayed without buffering;
112
- // only a streaming codec applies (§5.8).
113
- const encoded = encodeSegmentStream(result.body, acceptEncoding);
142
+ // only a streaming codec applies (§1.3).
143
+ const encoded = encodeStream(result.body, acceptEncoding);
114
144
  return new Response(encoded.body, {
115
145
  status: 200,
116
146
  headers: c.newResponse(null, 200, {
@@ -122,22 +152,12 @@ export function createSyncularHono(options) {
122
152
  ...ALREADY_ENCODED,
123
153
  });
124
154
  }
125
- // §5.8 shipped default: compress the body per Accept-Encoding
126
- // (zstd preferred, gzip fallback, identity otherwise). Content
127
- // addresses are over the uncompressed bytes (§5.1) — fetch
128
- // decodes transparently on the client.
155
+ // §1.3: compress the body per Accept-Encoding (zstd preferred, gzip
156
+ // fallback, identity otherwise). Content addresses are over the
157
+ // uncompressed bytes (§5.1) — fetch decodes transparently on the
158
+ // client.
129
159
  const bytes = new Uint8Array(await new Response(result.body).arrayBuffer());
130
- const encoded = encodeSegmentBody(bytes, acceptEncoding);
131
- return new Response(encoded.bytes.slice().buffer, {
132
- status: 200,
133
- headers: c.newResponse(null, 200, {
134
- ...result.headers,
135
- ...(encoded.contentEncoding !== undefined
136
- ? { 'Content-Encoding': encoded.contentEncoding }
137
- : {}),
138
- }).headers,
139
- ...ALREADY_ENCODED,
140
- });
160
+ return await encodedResponse(c, bytes, result.headers);
141
161
  }
142
162
  catch (error) {
143
163
  return errorResponse(c, error, 'segments');
@@ -200,10 +220,7 @@ export function createSyncularHono(options) {
200
220
  if (c.req.header('if-none-match') === result.headers.ETag) {
201
221
  return c.body(null, 304, result.headers);
202
222
  }
203
- const bytes = result.bytes ?? new Uint8Array(0);
204
- return c.body(bytes.slice().buffer, 200, {
205
- ...result.headers,
206
- });
223
+ return await encodedResponse(c, result.bytes ?? new Uint8Array(0), result.headers);
207
224
  }
208
225
  catch (error) {
209
226
  return errorResponse(c, error, 'blobs');
@@ -212,13 +229,14 @@ export function createSyncularHono(options) {
212
229
  return app;
213
230
  }
214
231
  /**
215
- * The segment route encodes its own body (§5.8) and declares
216
- * `Content-Encoding`. workerd encodes every response that declares one again
217
- * unless `encodeBody: 'manual'` marks the body as encoded, so a Workers client
218
- * would decode gzip inside gzip and fail §5.1 verification
219
- * (SYNCULAR-WORKERS-SEGMENT-ENCODING-001). Other runtimes ignore the member.
232
+ * Every buffered route — sync, operations, blobs and segments — encodes its
233
+ * own body (§1.3) and declares `Content-Encoding`. workerd encodes every
234
+ * response that declares one again unless `encodeBody: 'manual'` marks the
235
+ * body as encoded, so a Workers client would decode gzip inside gzip and fail
236
+ * §5.1 verification (SYNCULAR-WORKERS-SEGMENT-ENCODING-001). Other runtimes
237
+ * ignore the member.
220
238
  */
221
- // Build segment headers through the Hono context, then keep this runtime-specific
239
+ // Build response headers through the Hono context, then keep this runtime-specific
222
240
  // Response init. Hono newResponse/body discard encodeBody from their init.
223
241
  const ALREADY_ENCODED = {
224
242
  encodeBody: 'manual',
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@syncular/server-hono",
3
- "version": "0.37.0",
3
+ "version": "0.39.0",
4
4
  "description": "Hono adapter for the Syncular sync server",
5
5
  "license": "Apache-2.0",
6
6
  "author": "Benjamin Kniffler",
@@ -45,11 +45,11 @@
45
45
  "!dist/**/*.test.d.ts"
46
46
  ],
47
47
  "dependencies": {
48
- "@syncular/server": "0.37.0",
48
+ "@syncular/server": "0.39.0",
49
49
  "hono": "^4.13.11"
50
50
  },
51
51
  "devDependencies": {
52
- "@syncular/core": "0.37.0",
52
+ "@syncular/core": "0.39.0",
53
53
  "happy-dom": "^20.0.0"
54
54
  }
55
55
  }
package/src/index.ts CHANGED
@@ -7,8 +7,9 @@
7
7
  import {
8
8
  adapterSyncError,
9
9
  composeEvents,
10
- encodeSegmentBody,
11
- encodeSegmentStream,
10
+ decodeRequestBody,
11
+ encodeBody,
12
+ encodeStream,
12
13
  errorBody,
13
14
  handleBlobDownload,
14
15
  handleBlobUpload,
@@ -26,6 +27,7 @@ import {
26
27
  SyncularAdmin,
27
28
  type SyncularErrorRoute,
28
29
  type SyncServerConfig,
30
+ varyOnAcceptEncoding,
29
31
  } from '@syncular/server';
30
32
  import { Hono, type Context } from 'hono';
31
33
  import { createSyncularAdminRoutes, type SyncularAdminGuards } from './admin';
@@ -104,6 +106,48 @@ export function createSyncularHono(options: SyncularHonoOptions): Hono {
104
106
  });
105
107
  return c.newResponse(response.body, response);
106
108
  };
109
+ // §1.3: a client MAY gzip its request body; any other declared
110
+ // `Content-Encoding` is refused with 415 instead of being misread.
111
+ const unsupportedEncoding = (
112
+ c: Context,
113
+ route: 'sync' | 'operations',
114
+ ): Response =>
115
+ c.json(
116
+ errorBody(
117
+ new SyncError(
118
+ route === 'sync'
119
+ ? 'sync.invalid_request'
120
+ : 'operation.invalid_request',
121
+ 'unsupported content encoding',
122
+ ),
123
+ ),
124
+ 415,
125
+ );
126
+ // §1.3: every buffered body — a sync round, an operation result, a blob, a
127
+ // segment — is encoded per the request's `Accept-Encoding` (zstd preferred,
128
+ // gzip fallback, identity otherwise) and carries `Vary: Accept-Encoding`.
129
+ // Headers are built through the Hono context so host middleware headers
130
+ // survive; `encodeBody: 'manual'` marks the body as already encoded, so
131
+ // workerd does not encode it a second time (see ALREADY_ENCODED).
132
+ const encodedResponse = async (
133
+ c: Context,
134
+ bytes: Uint8Array,
135
+ headers: Record<string, string>,
136
+ ): Promise<Response> => {
137
+ const encoded = await encodeBody(bytes, c.req.header('accept-encoding'));
138
+ const out = c.newResponse(null, 200, {
139
+ ...headers,
140
+ ...(encoded.contentEncoding !== undefined
141
+ ? { 'Content-Encoding': encoded.contentEncoding }
142
+ : {}),
143
+ }).headers;
144
+ varyOnAcceptEncoding(out);
145
+ return new Response(encoded.bytes.slice().buffer as ArrayBuffer, {
146
+ status: 200,
147
+ headers: out,
148
+ ...ALREADY_ENCODED,
149
+ });
150
+ };
107
151
  // Throws outside a route's own try, such as from `authenticate`.
108
152
  app.onError((error, c) => {
109
153
  const segment = c.req.path.split('/')[1];
@@ -131,12 +175,13 @@ export function createSyncularHono(options: SyncularHonoOptions): Hono {
131
175
  if (auth === null)
132
176
  return errorResponse(c, new SyncError('sync.auth_required'));
133
177
  try {
134
- const bytes = new Uint8Array(await c.req.arrayBuffer());
178
+ const bytes = await decodeRequestBody(c.req.raw);
179
+ if (bytes === undefined) return unsupportedEncoding(c, 'sync');
135
180
  const out = await handleSyncRequest(bytes, {
136
181
  ...config,
137
182
  ...auth,
138
183
  });
139
- return c.body(out.slice().buffer as ArrayBuffer, 200, {
184
+ return await encodedResponse(c, out, {
140
185
  'Content-Type': SSP2_CONTENT_TYPE,
141
186
  });
142
187
  } catch (error) {
@@ -156,13 +201,14 @@ export function createSyncularHono(options: SyncularHonoOptions): Hono {
156
201
  if (auth === null)
157
202
  return errorResponse(c, new SyncError('sync.auth_required'));
158
203
  try {
159
- const bytes = new Uint8Array(await c.req.arrayBuffer());
204
+ const bytes = await decodeRequestBody(c.req.raw);
205
+ if (bytes === undefined) return unsupportedEncoding(c, 'operations');
160
206
  const out = await handleRemoteOperation(
161
207
  bytes,
162
208
  { ...config, ...auth },
163
209
  options.operations,
164
210
  );
165
- return c.body(out.slice().buffer as ArrayBuffer, 200, {
211
+ return await encodedResponse(c, out, {
166
212
  'Content-Type': 'application/vnd.syncular.operations.v1+json',
167
213
  });
168
214
  } catch (error) {
@@ -189,8 +235,8 @@ export function createSyncularHono(options: SyncularHonoOptions): Hono {
189
235
  const acceptEncoding = c.req.header('accept-encoding');
190
236
  if (result.byteLength > SEGMENT_STREAM_THRESHOLD_BYTES) {
191
237
  // A large segment (a sqlite image) is relayed without buffering;
192
- // only a streaming codec applies (§5.8).
193
- const encoded = encodeSegmentStream(result.body, acceptEncoding);
238
+ // only a streaming codec applies (§1.3).
239
+ const encoded = encodeStream(result.body, acceptEncoding);
194
240
  return new Response(encoded.body, {
195
241
  status: 200,
196
242
  headers: c.newResponse(null, 200, {
@@ -202,24 +248,14 @@ export function createSyncularHono(options: SyncularHonoOptions): Hono {
202
248
  ...ALREADY_ENCODED,
203
249
  });
204
250
  }
205
- // §5.8 shipped default: compress the body per Accept-Encoding
206
- // (zstd preferred, gzip fallback, identity otherwise). Content
207
- // addresses are over the uncompressed bytes (§5.1) — fetch
208
- // decodes transparently on the client.
251
+ // §1.3: compress the body per Accept-Encoding (zstd preferred, gzip
252
+ // fallback, identity otherwise). Content addresses are over the
253
+ // uncompressed bytes (§5.1) — fetch decodes transparently on the
254
+ // client.
209
255
  const bytes = new Uint8Array(
210
256
  await new Response(result.body).arrayBuffer(),
211
257
  );
212
- const encoded = encodeSegmentBody(bytes, acceptEncoding);
213
- return new Response(encoded.bytes.slice().buffer as ArrayBuffer, {
214
- status: 200,
215
- headers: c.newResponse(null, 200, {
216
- ...result.headers,
217
- ...(encoded.contentEncoding !== undefined
218
- ? { 'Content-Encoding': encoded.contentEncoding }
219
- : {}),
220
- }).headers,
221
- ...ALREADY_ENCODED,
222
- });
258
+ return await encodedResponse(c, bytes, result.headers);
223
259
  } catch (error) {
224
260
  return errorResponse(c, error, 'segments');
225
261
  }
@@ -297,10 +333,11 @@ export function createSyncularHono(options: SyncularHonoOptions): Hono {
297
333
  if (c.req.header('if-none-match') === result.headers.ETag) {
298
334
  return c.body(null, 304, result.headers);
299
335
  }
300
- const bytes = result.bytes ?? new Uint8Array(0);
301
- return c.body(bytes.slice().buffer as ArrayBuffer, 200, {
302
- ...result.headers,
303
- });
336
+ return await encodedResponse(
337
+ c,
338
+ result.bytes ?? new Uint8Array(0),
339
+ result.headers,
340
+ );
304
341
  } catch (error) {
305
342
  return errorResponse(c, error, 'blobs');
306
343
  }
@@ -309,13 +346,14 @@ export function createSyncularHono(options: SyncularHonoOptions): Hono {
309
346
  return app;
310
347
  }
311
348
  /**
312
- * The segment route encodes its own body (§5.8) and declares
313
- * `Content-Encoding`. workerd encodes every response that declares one again
314
- * unless `encodeBody: 'manual'` marks the body as encoded, so a Workers client
315
- * would decode gzip inside gzip and fail §5.1 verification
316
- * (SYNCULAR-WORKERS-SEGMENT-ENCODING-001). Other runtimes ignore the member.
349
+ * Every buffered route — sync, operations, blobs and segments — encodes its
350
+ * own body (§1.3) and declares `Content-Encoding`. workerd encodes every
351
+ * response that declares one again unless `encodeBody: 'manual'` marks the
352
+ * body as encoded, so a Workers client would decode gzip inside gzip and fail
353
+ * §5.1 verification (SYNCULAR-WORKERS-SEGMENT-ENCODING-001). Other runtimes
354
+ * ignore the member.
317
355
  */
318
- // Build segment headers through the Hono context, then keep this runtime-specific
356
+ // Build response headers through the Hono context, then keep this runtime-specific
319
357
  // Response init. Hono newResponse/body discard encodeBody from their init.
320
358
  const ALREADY_ENCODED: { readonly encodeBody: 'manual' } = {
321
359
  encodeBody: 'manual',