@dxos/functions-runtime-cloudflare 0.8.4-main.70d3990 → 0.8.4-main.937b3ca

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 (40) hide show
  1. package/dist/lib/browser/index.mjs +766 -109
  2. package/dist/lib/browser/index.mjs.map +4 -4
  3. package/dist/lib/browser/meta.json +1 -1
  4. package/dist/lib/node-esm/index.mjs +766 -109
  5. package/dist/lib/node-esm/index.mjs.map +4 -4
  6. package/dist/lib/node-esm/meta.json +1 -1
  7. package/dist/types/src/functions-client.d.ts +1 -0
  8. package/dist/types/src/functions-client.d.ts.map +1 -1
  9. package/dist/types/src/index.d.ts +2 -0
  10. package/dist/types/src/index.d.ts.map +1 -1
  11. package/dist/types/src/internal/data-service-impl.d.ts +7 -6
  12. package/dist/types/src/internal/data-service-impl.d.ts.map +1 -1
  13. package/dist/types/src/internal/query-service-impl.d.ts +1 -0
  14. package/dist/types/src/internal/query-service-impl.d.ts.map +1 -1
  15. package/dist/types/src/internal/queue-service-impl.d.ts +4 -5
  16. package/dist/types/src/internal/queue-service-impl.d.ts.map +1 -1
  17. package/dist/types/src/internal/service-container.d.ts +5 -3
  18. package/dist/types/src/internal/service-container.d.ts.map +1 -1
  19. package/dist/types/src/internal/utils.d.ts +2 -0
  20. package/dist/types/src/internal/utils.d.ts.map +1 -0
  21. package/dist/types/src/logger.d.ts +2 -0
  22. package/dist/types/src/logger.d.ts.map +1 -0
  23. package/dist/types/src/queues-api.d.ts +3 -3
  24. package/dist/types/src/queues-api.d.ts.map +1 -1
  25. package/dist/types/src/space-proxy.d.ts +3 -2
  26. package/dist/types/src/space-proxy.d.ts.map +1 -1
  27. package/dist/types/src/wrap-handler-for-cloudflare.d.ts.map +1 -1
  28. package/dist/types/tsconfig.tsbuildinfo +1 -1
  29. package/package.json +20 -15
  30. package/src/functions-client.ts +8 -1
  31. package/src/index.ts +2 -0
  32. package/src/internal/data-service-impl.ts +66 -17
  33. package/src/internal/query-service-impl.ts +24 -8
  34. package/src/internal/queue-service-impl.ts +54 -8
  35. package/src/internal/service-container.ts +25 -6
  36. package/src/internal/utils.ts +5 -0
  37. package/src/logger.ts +42 -0
  38. package/src/queues-api.ts +3 -3
  39. package/src/space-proxy.ts +4 -3
  40. package/src/wrap-handler-for-cloudflare.ts +3 -3
@@ -1,9 +1,85 @@
1
+ // src/functions-client.ts
2
+ import { Resource as Resource2 } from "@dxos/context";
3
+ import { EchoClient } from "@dxos/echo-db";
4
+ import { invariant as invariant6 } from "@dxos/invariant";
5
+
1
6
  // src/internal/data-service-impl.ts
2
7
  import { Stream } from "@dxos/codec-protobuf/stream";
3
8
  import { raise } from "@dxos/debug";
9
+ import { NotImplementedError, RuntimeServiceError } from "@dxos/errors";
4
10
  import { invariant } from "@dxos/invariant";
5
11
  import { SpaceId } from "@dxos/keys";
6
12
  import { log } from "@dxos/log";
13
+
14
+ // src/internal/utils.ts
15
+ var copyUint8Array = (value) => new Uint8Array(value);
16
+
17
+ // src/internal/data-service-impl.ts
18
+ function _ts_add_disposable_resource(env, value, async) {
19
+ if (value !== null && value !== void 0) {
20
+ if (typeof value !== "object" && typeof value !== "function") throw new TypeError("Object expected.");
21
+ var dispose, inner;
22
+ if (async) {
23
+ if (!Symbol.asyncDispose) throw new TypeError("Symbol.asyncDispose is not defined.");
24
+ dispose = value[Symbol.asyncDispose];
25
+ }
26
+ if (dispose === void 0) {
27
+ if (!Symbol.dispose) throw new TypeError("Symbol.dispose is not defined.");
28
+ dispose = value[Symbol.dispose];
29
+ if (async) inner = dispose;
30
+ }
31
+ if (typeof dispose !== "function") throw new TypeError("Object not disposable.");
32
+ if (inner) dispose = function() {
33
+ try {
34
+ inner.call(this);
35
+ } catch (e) {
36
+ return Promise.reject(e);
37
+ }
38
+ };
39
+ env.stack.push({
40
+ value,
41
+ dispose,
42
+ async
43
+ });
44
+ } else if (async) {
45
+ env.stack.push({
46
+ async: true
47
+ });
48
+ }
49
+ return value;
50
+ }
51
+ function _ts_dispose_resources(env) {
52
+ var _SuppressedError = typeof SuppressedError === "function" ? SuppressedError : function(error, suppressed, message) {
53
+ var e = new Error(message);
54
+ return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
55
+ };
56
+ return (_ts_dispose_resources = function _ts_dispose_resources5(env2) {
57
+ function fail(e) {
58
+ env2.error = env2.hasError ? new _SuppressedError(e, env2.error, "An error was suppressed during disposal.") : e;
59
+ env2.hasError = true;
60
+ }
61
+ var r, s = 0;
62
+ function next() {
63
+ while (r = env2.stack.pop()) {
64
+ try {
65
+ if (!r.async && s === 1) return s = 0, env2.stack.push(r), Promise.resolve().then(next);
66
+ if (r.dispose) {
67
+ var result = r.dispose.call(r.value);
68
+ if (r.async) return s |= 2, Promise.resolve(result).then(next, function(e) {
69
+ fail(e);
70
+ return next();
71
+ });
72
+ } else s |= 1;
73
+ } catch (e) {
74
+ fail(e);
75
+ }
76
+ }
77
+ if (s === 1) return env2.hasError ? Promise.reject(env2.error) : Promise.resolve();
78
+ if (env2.hasError) throw env2.error;
79
+ }
80
+ return next();
81
+ })(env);
82
+ }
7
83
  var __dxlog_file = "/__w/dxos/dxos/packages/core/functions-runtime-cloudflare/src/internal/data-service-impl.ts";
8
84
  var DataServiceImpl = class {
9
85
  _executionContext;
@@ -17,7 +93,7 @@ var DataServiceImpl = class {
17
93
  return new Stream(({ next }) => {
18
94
  invariant(SpaceId.isValid(spaceId), void 0, {
19
95
  F: __dxlog_file,
20
- L: 34,
96
+ L: 39,
21
97
  S: this,
22
98
  A: [
23
99
  "SpaceId.isValid(spaceId)",
@@ -33,74 +109,141 @@ var DataServiceImpl = class {
33
109
  };
34
110
  });
35
111
  }
36
- async updateSubscription({ subscriptionId, addIds, removeIds }) {
37
- const sub = this.dataSubscriptions.get(subscriptionId) ?? raise(new Error("Subscription not found"));
112
+ async updateSubscription({ subscriptionId, addIds }) {
113
+ const sub = this.dataSubscriptions.get(subscriptionId) ?? raise(new RuntimeServiceError({
114
+ message: "Subscription not found.",
115
+ context: {
116
+ subscriptionId
117
+ }
118
+ }));
38
119
  if (addIds) {
39
120
  log.info("request documents", {
40
121
  count: addIds.length
41
122
  }, {
42
123
  F: __dxlog_file,
43
- L: 47,
124
+ L: 59,
44
125
  S: this,
45
126
  C: (f, a) => f(...a)
46
127
  });
47
128
  for (const documentId of addIds) {
48
- const document = await this._dataService.getDocument(this._executionContext, sub.spaceId, documentId);
49
- log.info("document loaded", {
50
- documentId,
51
- spaceId: sub.spaceId,
52
- found: !!document
53
- }, {
54
- F: __dxlog_file,
55
- L: 51,
56
- S: this,
57
- C: (f, a) => f(...a)
58
- });
59
- if (!document) {
60
- log.warn("not found", {
61
- documentId
129
+ const env = {
130
+ stack: [],
131
+ error: void 0,
132
+ hasError: false
133
+ };
134
+ try {
135
+ const document = _ts_add_disposable_resource(env, await this._dataService.getDocument(this._executionContext, sub.spaceId, documentId), false);
136
+ log.info("document loaded", {
137
+ documentId,
138
+ spaceId: sub.spaceId,
139
+ found: !!document
62
140
  }, {
63
141
  F: __dxlog_file,
64
- L: 53,
142
+ L: 63,
65
143
  S: this,
66
144
  C: (f, a) => f(...a)
67
145
  });
68
- continue;
146
+ if (!document) {
147
+ log.warn("not found", {
148
+ documentId
149
+ }, {
150
+ F: __dxlog_file,
151
+ L: 65,
152
+ S: this,
153
+ C: (f, a) => f(...a)
154
+ });
155
+ continue;
156
+ }
157
+ sub.next({
158
+ updates: [
159
+ {
160
+ documentId,
161
+ // Copy returned object to avoid hanging RPC stub
162
+ // See https://developers.cloudflare.com/workers/runtime-apis/rpc/lifecycle/
163
+ mutation: copyUint8Array(document.data)
164
+ }
165
+ ]
166
+ });
167
+ } catch (e) {
168
+ env.error = e;
169
+ env.hasError = true;
170
+ } finally {
171
+ _ts_dispose_resources(env);
69
172
  }
70
- sub.next({
71
- updates: [
72
- {
73
- documentId,
74
- mutation: document.data
75
- }
76
- ]
77
- });
78
173
  }
79
174
  }
80
175
  }
176
+ async createDocument({ spaceId, initialValue }) {
177
+ const env = {
178
+ stack: [],
179
+ error: void 0,
180
+ hasError: false
181
+ };
182
+ try {
183
+ const response = _ts_add_disposable_resource(env, await this._dataService.createDocument(this._executionContext, {
184
+ spaceId,
185
+ initialValue
186
+ }), false);
187
+ return {
188
+ documentId: response.documentId
189
+ };
190
+ } catch (e) {
191
+ env.error = e;
192
+ env.hasError = true;
193
+ } finally {
194
+ _ts_dispose_resources(env);
195
+ }
196
+ }
81
197
  async update({ updates, subscriptionId }) {
82
- const sub = this.dataSubscriptions.get(subscriptionId) ?? raise(new Error("Subscription not found"));
83
- for (const update of updates ?? []) {
84
- await this._dataService.changeDocument(this._executionContext, sub.spaceId, update.documentId, update.mutation);
198
+ const sub = this.dataSubscriptions.get(subscriptionId) ?? raise(new RuntimeServiceError({
199
+ message: "Subscription not found.",
200
+ context: {
201
+ subscriptionId
202
+ }
203
+ }));
204
+ try {
205
+ for (const update of updates ?? []) {
206
+ await this._dataService.changeDocument(this._executionContext, sub.spaceId, update.documentId, update.mutation);
207
+ }
208
+ } catch (error) {
209
+ throw RuntimeServiceError.wrap({
210
+ message: "Failed to apply document updates.",
211
+ context: {
212
+ subscriptionId
213
+ },
214
+ ifTypeDiffers: true
215
+ })(error);
85
216
  }
86
- throw new Error("Method not implemented.");
87
217
  }
88
218
  async flush() {
89
219
  }
90
- subscribeSpaceSyncState(request, options) {
91
- throw new Error("Method not implemented.");
220
+ subscribeSpaceSyncState(_request, _options) {
221
+ throw new NotImplementedError({
222
+ message: "subscribeSpaceSyncState is not implemented."
223
+ });
92
224
  }
93
- async getDocumentHeads({ documentIds }) {
94
- throw new Error("Method not implemented.");
225
+ async getDocumentHeads({ documentIds: _documentIds }) {
226
+ throw new NotImplementedError({
227
+ message: "getDocumentHeads is not implemented."
228
+ });
95
229
  }
96
- async reIndexHeads({ documentIds }) {
97
- throw new Error("Method not implemented.");
230
+ async reIndexHeads({ documentIds: _documentIds }) {
231
+ throw new NotImplementedError({
232
+ message: "reIndexHeads is not implemented."
233
+ });
98
234
  }
99
235
  async updateIndexes() {
100
- throw new Error("Method not implemented.");
236
+ log.error("updateIndexes is not available in EDGE env.", void 0, {
237
+ F: __dxlog_file,
238
+ L: 133,
239
+ S: this,
240
+ C: (f, a) => f(...a)
241
+ });
101
242
  }
102
- async waitUntilHeadsReplicated({ heads }) {
103
- throw new Error("Method not implemented.");
243
+ async waitUntilHeadsReplicated({ heads: _heads }) {
244
+ throw new NotImplementedError({
245
+ message: "waitUntilHeadsReplicated is not implemented."
246
+ });
104
247
  }
105
248
  };
106
249
 
@@ -108,6 +251,7 @@ var DataServiceImpl = class {
108
251
  import * as Schema from "effect/Schema";
109
252
  import { Stream as Stream2 } from "@dxos/codec-protobuf/stream";
110
253
  import { QueryAST } from "@dxos/echo-protocol";
254
+ import { NotImplementedError as NotImplementedError2, RuntimeServiceError as RuntimeServiceError2 } from "@dxos/errors";
111
255
  import { invariant as invariant3 } from "@dxos/invariant";
112
256
  import { PublicKey } from "@dxos/keys";
113
257
  import { SpaceId as SpaceId3 } from "@dxos/keys";
@@ -181,10 +325,76 @@ var isSimpleSelectionQuery = (query) => {
181
325
  };
182
326
 
183
327
  // src/internal/query-service-impl.ts
328
+ function _ts_add_disposable_resource2(env, value, async) {
329
+ if (value !== null && value !== void 0) {
330
+ if (typeof value !== "object" && typeof value !== "function") throw new TypeError("Object expected.");
331
+ var dispose, inner;
332
+ if (async) {
333
+ if (!Symbol.asyncDispose) throw new TypeError("Symbol.asyncDispose is not defined.");
334
+ dispose = value[Symbol.asyncDispose];
335
+ }
336
+ if (dispose === void 0) {
337
+ if (!Symbol.dispose) throw new TypeError("Symbol.dispose is not defined.");
338
+ dispose = value[Symbol.dispose];
339
+ if (async) inner = dispose;
340
+ }
341
+ if (typeof dispose !== "function") throw new TypeError("Object not disposable.");
342
+ if (inner) dispose = function() {
343
+ try {
344
+ inner.call(this);
345
+ } catch (e) {
346
+ return Promise.reject(e);
347
+ }
348
+ };
349
+ env.stack.push({
350
+ value,
351
+ dispose,
352
+ async
353
+ });
354
+ } else if (async) {
355
+ env.stack.push({
356
+ async: true
357
+ });
358
+ }
359
+ return value;
360
+ }
361
+ function _ts_dispose_resources2(env) {
362
+ var _SuppressedError = typeof SuppressedError === "function" ? SuppressedError : function(error, suppressed, message) {
363
+ var e = new Error(message);
364
+ return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
365
+ };
366
+ return (_ts_dispose_resources2 = function _ts_dispose_resources5(env2) {
367
+ function fail(e) {
368
+ env2.error = env2.hasError ? new _SuppressedError(e, env2.error, "An error was suppressed during disposal.") : e;
369
+ env2.hasError = true;
370
+ }
371
+ var r, s = 0;
372
+ function next() {
373
+ while (r = env2.stack.pop()) {
374
+ try {
375
+ if (!r.async && s === 1) return s = 0, env2.stack.push(r), Promise.resolve().then(next);
376
+ if (r.dispose) {
377
+ var result = r.dispose.call(r.value);
378
+ if (r.async) return s |= 2, Promise.resolve(result).then(next, function(e) {
379
+ fail(e);
380
+ return next();
381
+ });
382
+ } else s |= 1;
383
+ } catch (e) {
384
+ fail(e);
385
+ }
386
+ }
387
+ if (s === 1) return env2.hasError ? Promise.reject(env2.error) : Promise.resolve();
388
+ if (env2.hasError) throw env2.error;
389
+ }
390
+ return next();
391
+ })(env);
392
+ }
184
393
  var __dxlog_file3 = "/__w/dxos/dxos/packages/core/functions-runtime-cloudflare/src/internal/query-service-impl.ts";
185
394
  var QueryServiceImpl = class {
186
395
  _executionContext;
187
396
  _dataService;
397
+ _queryCount = 0;
188
398
  constructor(_executionContext, _dataService) {
189
399
  this._executionContext = _executionContext;
190
400
  this._dataService = _dataService;
@@ -194,7 +404,7 @@ var QueryServiceImpl = class {
194
404
  request
195
405
  }, {
196
406
  F: __dxlog_file3,
197
- L: 30,
407
+ L: 34,
198
408
  S: this,
199
409
  C: (f, a) => f(...a)
200
410
  });
@@ -202,7 +412,7 @@ var QueryServiceImpl = class {
202
412
  const requestedSpaceIds = getTargetSpacesForQuery(query);
203
413
  invariant3(requestedSpaceIds.length === 1, "Only one space is supported", {
204
414
  F: __dxlog_file3,
205
- L: 33,
415
+ L: 37,
206
416
  S: this,
207
417
  A: [
208
418
  "requestedSpaceIds.length === 1",
@@ -212,53 +422,81 @@ var QueryServiceImpl = class {
212
422
  const spaceId = requestedSpaceIds[0];
213
423
  return Stream2.fromPromise((async () => {
214
424
  try {
215
- log2.info("begin query", {
216
- spaceId
217
- }, {
218
- F: __dxlog_file3,
219
- L: 39,
220
- S: this,
221
- C: (f, a) => f(...a)
222
- });
223
- const queryResponse = await this._dataService.queryDocuments(this._executionContext, queryToDataServiceRequest(query));
224
- log2.info("query response", {
225
- spaceId,
226
- filter: request.filter,
227
- resultCount: queryResponse.results.length
228
- }, {
229
- F: __dxlog_file3,
230
- L: 44,
231
- S: this,
232
- C: (f, a) => f(...a)
233
- });
234
- return {
235
- results: queryResponse.results.map((object) => ({
236
- id: object.objectId,
237
- spaceId,
238
- spaceKey: PublicKey.ZERO,
239
- documentId: object.document.documentId,
240
- rank: 0,
241
- documentAutomerge: object.document.data
242
- }))
425
+ const env = {
426
+ stack: [],
427
+ error: void 0,
428
+ hasError: false
243
429
  };
244
- } catch (err) {
430
+ try {
431
+ this._queryCount++;
432
+ log2.info("begin query", {
433
+ spaceId
434
+ }, {
435
+ F: __dxlog_file3,
436
+ L: 44,
437
+ S: this,
438
+ C: (f, a) => f(...a)
439
+ });
440
+ const queryResponse = _ts_add_disposable_resource2(env, await this._dataService.queryDocuments(this._executionContext, queryToDataServiceRequest(query)), false);
441
+ log2.info("query response", {
442
+ spaceId,
443
+ filter: request.filter,
444
+ resultCount: queryResponse.results.length
445
+ }, {
446
+ F: __dxlog_file3,
447
+ L: 49,
448
+ S: this,
449
+ C: (f, a) => f(...a)
450
+ });
451
+ return {
452
+ results: queryResponse.results.map((object) => ({
453
+ id: object.objectId,
454
+ spaceId,
455
+ spaceKey: PublicKey.ZERO,
456
+ documentId: object.document.documentId,
457
+ // Rank 1 for predicate matches where ranking is not determined.
458
+ rank: 1,
459
+ // Copy returned object to avoid hanging RPC stub.
460
+ // See https://developers.cloudflare.com/workers/runtime-apis/rpc/lifecycle/
461
+ documentAutomerge: copyUint8Array(object.document.data)
462
+ }))
463
+ };
464
+ } catch (e) {
465
+ env.error = e;
466
+ env.hasError = true;
467
+ } finally {
468
+ _ts_dispose_resources2(env);
469
+ }
470
+ } catch (error) {
245
471
  log2.error("query failed", {
246
- err
472
+ err: error
247
473
  }, {
248
474
  F: __dxlog_file3,
249
- L: 58,
475
+ L: 66,
250
476
  S: this,
251
477
  C: (f, a) => f(...a)
252
478
  });
253
- throw err;
479
+ throw new RuntimeServiceError2({
480
+ message: `Query execution failed (queryCount=${this._queryCount})`,
481
+ context: {
482
+ spaceId,
483
+ filter: request.filter,
484
+ queryCount: this._queryCount
485
+ },
486
+ cause: error
487
+ });
254
488
  }
255
489
  })());
256
490
  }
257
491
  async reindex() {
258
- throw new Error("Method not implemented.");
492
+ throw new NotImplementedError2({
493
+ message: "Reindex is not implemented."
494
+ });
259
495
  }
260
496
  async setConfig() {
261
- throw new Error("Method not implemented.");
497
+ throw new NotImplementedError2({
498
+ message: "SetConfig is not implemented."
499
+ });
262
500
  }
263
501
  };
264
502
  var getTargetSpacesForQuery = (query) => {
@@ -279,6 +517,74 @@ var getTargetSpacesForQuery = (query) => {
279
517
  };
280
518
 
281
519
  // src/internal/queue-service-impl.ts
520
+ import { NotImplementedError as NotImplementedError3, RuntimeServiceError as RuntimeServiceError3 } from "@dxos/errors";
521
+ import { invariant as invariant4 } from "@dxos/invariant";
522
+ function _ts_add_disposable_resource3(env, value, async) {
523
+ if (value !== null && value !== void 0) {
524
+ if (typeof value !== "object" && typeof value !== "function") throw new TypeError("Object expected.");
525
+ var dispose, inner;
526
+ if (async) {
527
+ if (!Symbol.asyncDispose) throw new TypeError("Symbol.asyncDispose is not defined.");
528
+ dispose = value[Symbol.asyncDispose];
529
+ }
530
+ if (dispose === void 0) {
531
+ if (!Symbol.dispose) throw new TypeError("Symbol.dispose is not defined.");
532
+ dispose = value[Symbol.dispose];
533
+ if (async) inner = dispose;
534
+ }
535
+ if (typeof dispose !== "function") throw new TypeError("Object not disposable.");
536
+ if (inner) dispose = function() {
537
+ try {
538
+ inner.call(this);
539
+ } catch (e) {
540
+ return Promise.reject(e);
541
+ }
542
+ };
543
+ env.stack.push({
544
+ value,
545
+ dispose,
546
+ async
547
+ });
548
+ } else if (async) {
549
+ env.stack.push({
550
+ async: true
551
+ });
552
+ }
553
+ return value;
554
+ }
555
+ function _ts_dispose_resources3(env) {
556
+ var _SuppressedError = typeof SuppressedError === "function" ? SuppressedError : function(error, suppressed, message) {
557
+ var e = new Error(message);
558
+ return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
559
+ };
560
+ return (_ts_dispose_resources3 = function _ts_dispose_resources5(env2) {
561
+ function fail(e) {
562
+ env2.error = env2.hasError ? new _SuppressedError(e, env2.error, "An error was suppressed during disposal.") : e;
563
+ env2.hasError = true;
564
+ }
565
+ var r, s = 0;
566
+ function next() {
567
+ while (r = env2.stack.pop()) {
568
+ try {
569
+ if (!r.async && s === 1) return s = 0, env2.stack.push(r), Promise.resolve().then(next);
570
+ if (r.dispose) {
571
+ var result = r.dispose.call(r.value);
572
+ if (r.async) return s |= 2, Promise.resolve(result).then(next, function(e) {
573
+ fail(e);
574
+ return next();
575
+ });
576
+ } else s |= 1;
577
+ } catch (e) {
578
+ fail(e);
579
+ }
580
+ }
581
+ if (s === 1) return env2.hasError ? Promise.reject(env2.error) : Promise.resolve();
582
+ if (env2.hasError) throw env2.error;
583
+ }
584
+ return next();
585
+ })(env);
586
+ }
587
+ var __dxlog_file4 = "/__w/dxos/dxos/packages/core/functions-runtime-cloudflare/src/internal/queue-service-impl.ts";
282
588
  var QueueServiceImpl = class {
283
589
  _ctx;
284
590
  _queueService;
@@ -286,29 +592,177 @@ var QueueServiceImpl = class {
286
592
  this._ctx = _ctx;
287
593
  this._queueService = _queueService;
288
594
  }
289
- queryQueue(subspaceTag, spaceId, { queueId, ...query }) {
290
- return this._queueService.query(this._ctx, `dxn:queue:${subspaceTag}:${spaceId}:${queueId}`, query);
595
+ async queryQueue(request) {
596
+ const { query } = request;
597
+ const { queueIds, ...filter } = query;
598
+ const spaceId = query.spaceId;
599
+ const queueId = queueIds?.[0];
600
+ invariant4(request.query.queuesNamespace, void 0, {
601
+ F: __dxlog_file4,
602
+ L: 26,
603
+ S: this,
604
+ A: [
605
+ "request.query.queuesNamespace",
606
+ ""
607
+ ]
608
+ });
609
+ try {
610
+ const env = {
611
+ stack: [],
612
+ error: void 0,
613
+ hasError: false
614
+ };
615
+ try {
616
+ const result = _ts_add_disposable_resource3(env, await this._queueService.query(this._ctx, `dxn:queue:${request.query.queuesNamespace}:${spaceId}:${queueId}`, filter), false);
617
+ return {
618
+ // Copy returned object to avoid hanging RPC stub
619
+ // See https://developers.cloudflare.com/workers/runtime-apis/rpc/lifecycle/
620
+ objects: structuredClone(result.objects),
621
+ nextCursor: result.nextCursor,
622
+ prevCursor: result.prevCursor
623
+ };
624
+ } catch (e) {
625
+ env.error = e;
626
+ env.hasError = true;
627
+ } finally {
628
+ _ts_dispose_resources3(env);
629
+ }
630
+ } catch (error) {
631
+ throw RuntimeServiceError3.wrap({
632
+ message: "Queue query failed.",
633
+ context: {
634
+ subspaceTag: request.query.queuesNamespace,
635
+ spaceId,
636
+ queueId
637
+ },
638
+ ifTypeDiffers: true
639
+ })(error);
640
+ }
291
641
  }
292
- insertIntoQueue(subspaceTag, spaceId, queueId, objects) {
293
- return this._queueService.append(this._ctx, `dxn:queue:${subspaceTag}:${spaceId}:${queueId}`, objects);
642
+ async insertIntoQueue(request) {
643
+ const { subspaceTag, spaceId, queueId, objects } = request;
644
+ try {
645
+ await this._queueService.append(this._ctx, `dxn:queue:${subspaceTag}:${spaceId}:${queueId}`, objects ?? []);
646
+ } catch (error) {
647
+ throw RuntimeServiceError3.wrap({
648
+ message: "Queue append failed.",
649
+ context: {
650
+ subspaceTag,
651
+ spaceId,
652
+ queueId
653
+ },
654
+ ifTypeDiffers: true
655
+ })(error);
656
+ }
294
657
  }
295
- deleteFromQueue(subspaceTag, spaceId, queueId, objectIds) {
296
- throw new Error("Deleting from queue is not supported.");
658
+ deleteFromQueue(request) {
659
+ const { subspaceTag, spaceId, queueId } = request;
660
+ throw new NotImplementedError3({
661
+ message: "Deleting from queue is not supported.",
662
+ context: {
663
+ subspaceTag,
664
+ spaceId,
665
+ queueId
666
+ }
667
+ });
297
668
  }
298
669
  };
299
670
 
300
671
  // src/internal/service-container.ts
672
+ function _ts_add_disposable_resource4(env, value, async) {
673
+ if (value !== null && value !== void 0) {
674
+ if (typeof value !== "object" && typeof value !== "function") throw new TypeError("Object expected.");
675
+ var dispose, inner;
676
+ if (async) {
677
+ if (!Symbol.asyncDispose) throw new TypeError("Symbol.asyncDispose is not defined.");
678
+ dispose = value[Symbol.asyncDispose];
679
+ }
680
+ if (dispose === void 0) {
681
+ if (!Symbol.dispose) throw new TypeError("Symbol.dispose is not defined.");
682
+ dispose = value[Symbol.dispose];
683
+ if (async) inner = dispose;
684
+ }
685
+ if (typeof dispose !== "function") throw new TypeError("Object not disposable.");
686
+ if (inner) dispose = function() {
687
+ try {
688
+ inner.call(this);
689
+ } catch (e) {
690
+ return Promise.reject(e);
691
+ }
692
+ };
693
+ env.stack.push({
694
+ value,
695
+ dispose,
696
+ async
697
+ });
698
+ } else if (async) {
699
+ env.stack.push({
700
+ async: true
701
+ });
702
+ }
703
+ return value;
704
+ }
705
+ function _ts_dispose_resources4(env) {
706
+ var _SuppressedError = typeof SuppressedError === "function" ? SuppressedError : function(error, suppressed, message) {
707
+ var e = new Error(message);
708
+ return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
709
+ };
710
+ return (_ts_dispose_resources4 = function _ts_dispose_resources5(env2) {
711
+ function fail(e) {
712
+ env2.error = env2.hasError ? new _SuppressedError(e, env2.error, "An error was suppressed during disposal.") : e;
713
+ env2.hasError = true;
714
+ }
715
+ var r, s = 0;
716
+ function next() {
717
+ while (r = env2.stack.pop()) {
718
+ try {
719
+ if (!r.async && s === 1) return s = 0, env2.stack.push(r), Promise.resolve().then(next);
720
+ if (r.dispose) {
721
+ var result = r.dispose.call(r.value);
722
+ if (r.async) return s |= 2, Promise.resolve(result).then(next, function(e) {
723
+ fail(e);
724
+ return next();
725
+ });
726
+ } else s |= 1;
727
+ } catch (e) {
728
+ fail(e);
729
+ }
730
+ }
731
+ if (s === 1) return env2.hasError ? Promise.reject(env2.error) : Promise.resolve();
732
+ if (env2.hasError) throw env2.error;
733
+ }
734
+ return next();
735
+ })(env);
736
+ }
301
737
  var ServiceContainer = class {
302
738
  _executionContext;
303
739
  _dataService;
304
740
  _queueService;
305
- constructor(_executionContext, _dataService, _queueService) {
741
+ _functionsService;
742
+ constructor(_executionContext, _dataService, _queueService, _functionsService) {
306
743
  this._executionContext = _executionContext;
307
744
  this._dataService = _dataService;
308
745
  this._queueService = _queueService;
746
+ this._functionsService = _functionsService;
309
747
  }
310
748
  async getSpaceMeta(spaceId) {
311
- return this._dataService.getSpaceMeta(this._executionContext, spaceId);
749
+ const env = {
750
+ stack: [],
751
+ error: void 0,
752
+ hasError: false
753
+ };
754
+ try {
755
+ const result = _ts_add_disposable_resource4(env, await this._dataService.getSpaceMeta(this._executionContext, spaceId), false);
756
+ return result ? {
757
+ spaceKey: result.spaceKey,
758
+ rootDocumentId: result.rootDocumentId
759
+ } : void 0;
760
+ } catch (e) {
761
+ env.error = e;
762
+ env.hasError = true;
763
+ } finally {
764
+ _ts_dispose_resources4(env);
765
+ }
312
766
  }
313
767
  async createServices() {
314
768
  const dataService = new DataServiceImpl(this._executionContext, this._dataService);
@@ -317,17 +771,189 @@ var ServiceContainer = class {
317
771
  return {
318
772
  dataService,
319
773
  queryService,
320
- queueService
774
+ queueService,
775
+ functionsAiService: this._functionsService
321
776
  };
322
777
  }
323
- queryQueue(queue) {
324
- return this._queueService.query({}, queue.toString(), {});
778
+ async queryQueue(queue) {
779
+ const env = {
780
+ stack: [],
781
+ error: void 0,
782
+ hasError: false
783
+ };
784
+ try {
785
+ const { spaceId } = queue.asQueueDXN() ?? {};
786
+ const result = _ts_add_disposable_resource4(env, await this._queueService.query({}, queue.toString(), {
787
+ spaceId
788
+ }), false);
789
+ return {
790
+ objects: structuredClone(result.objects),
791
+ nextCursor: result.nextCursor ?? null,
792
+ prevCursor: result.prevCursor ?? null
793
+ };
794
+ } catch (e) {
795
+ env.error = e;
796
+ env.hasError = true;
797
+ } finally {
798
+ _ts_dispose_resources4(env);
799
+ }
800
+ }
801
+ async insertIntoQueue(queue, objects) {
802
+ await this._queueService.append({}, queue.toString(), objects);
803
+ }
804
+ };
805
+
806
+ // src/space-proxy.ts
807
+ import { Resource } from "@dxos/context";
808
+ import { invariant as invariant5 } from "@dxos/invariant";
809
+ import { PublicKey as PublicKey2 } from "@dxos/keys";
810
+
811
+ // src/queues-api.ts
812
+ var QueuesAPIImpl = class {
813
+ _serviceContainer;
814
+ _spaceId;
815
+ constructor(_serviceContainer, _spaceId) {
816
+ this._serviceContainer = _serviceContainer;
817
+ this._spaceId = _spaceId;
818
+ }
819
+ queryQueue(queue, options) {
820
+ return this._serviceContainer.queryQueue(queue);
325
821
  }
326
822
  insertIntoQueue(queue, objects) {
327
- return this._queueService.append({}, queue.toString(), objects);
823
+ return this._serviceContainer.insertIntoQueue(queue, JSON.parse(JSON.stringify(objects)));
328
824
  }
329
825
  };
330
826
 
827
+ // src/space-proxy.ts
828
+ var __dxlog_file5 = "/__w/dxos/dxos/packages/core/functions-runtime-cloudflare/src/space-proxy.ts";
829
+ var SpaceProxy = class extends Resource {
830
+ _serviceContainer;
831
+ _echoClient;
832
+ _id;
833
+ _db = void 0;
834
+ _queuesApi;
835
+ constructor(_serviceContainer, _echoClient, _id) {
836
+ super(), this._serviceContainer = _serviceContainer, this._echoClient = _echoClient, this._id = _id;
837
+ this._queuesApi = new QueuesAPIImpl(this._serviceContainer, this._id);
838
+ }
839
+ get id() {
840
+ return this._id;
841
+ }
842
+ get db() {
843
+ invariant5(this._db, void 0, {
844
+ F: __dxlog_file5,
845
+ L: 35,
846
+ S: this,
847
+ A: [
848
+ "this._db",
849
+ ""
850
+ ]
851
+ });
852
+ return this._db;
853
+ }
854
+ /**
855
+ * @deprecated Use db API.
856
+ */
857
+ get crud() {
858
+ invariant5(this._db, void 0, {
859
+ F: __dxlog_file5,
860
+ L: 43,
861
+ S: this,
862
+ A: [
863
+ "this._db",
864
+ ""
865
+ ]
866
+ });
867
+ return this._db.coreDatabase;
868
+ }
869
+ get queues() {
870
+ return this._queuesApi;
871
+ }
872
+ async _open() {
873
+ const meta = await this._serviceContainer.getSpaceMeta(this._id);
874
+ if (!meta) {
875
+ throw new Error(`Space not found: ${this._id}`);
876
+ }
877
+ this._db = this._echoClient.constructDatabase({
878
+ spaceId: this._id,
879
+ spaceKey: PublicKey2.from(meta.spaceKey),
880
+ reactiveSchemaQuery: false,
881
+ owningObject: this
882
+ });
883
+ await this._db.coreDatabase.open({
884
+ rootUrl: meta.rootDocumentId
885
+ });
886
+ }
887
+ };
888
+
889
+ // src/functions-client.ts
890
+ var __dxlog_file6 = "/__w/dxos/dxos/packages/core/functions-runtime-cloudflare/src/functions-client.ts";
891
+ var FunctionsClient = class extends Resource2 {
892
+ _serviceContainer;
893
+ _echoClient;
894
+ _executionContext = {};
895
+ _spaces = /* @__PURE__ */ new Map();
896
+ constructor(services) {
897
+ super();
898
+ invariant6(typeof services.dataService !== "undefined", "DataService is required", {
899
+ F: __dxlog_file6,
900
+ L: 33,
901
+ S: this,
902
+ A: [
903
+ "typeof services.dataService !== 'undefined'",
904
+ "'DataService is required'"
905
+ ]
906
+ });
907
+ invariant6(typeof services.queueService !== "undefined", "QueueService is required", {
908
+ F: __dxlog_file6,
909
+ L: 34,
910
+ S: this,
911
+ A: [
912
+ "typeof services.queueService !== 'undefined'",
913
+ "'QueueService is required'"
914
+ ]
915
+ });
916
+ this._serviceContainer = new ServiceContainer(this._executionContext, services.dataService, services.queueService, services.functionsAiService);
917
+ this._echoClient = new EchoClient({});
918
+ }
919
+ get echo() {
920
+ return this._echoClient;
921
+ }
922
+ async _open() {
923
+ const { dataService, queryService } = await this._serviceContainer.createServices();
924
+ this._echoClient.connectToService({
925
+ dataService,
926
+ queryService
927
+ });
928
+ await this._echoClient.open();
929
+ }
930
+ async _close() {
931
+ for (const space of this._spaces.values()) {
932
+ await space.close();
933
+ }
934
+ this._spaces.clear();
935
+ await this._echoClient.close();
936
+ }
937
+ async getSpace(spaceId) {
938
+ if (!this._spaces.has(spaceId)) {
939
+ const space2 = new SpaceProxy(this._serviceContainer, this._echoClient, spaceId);
940
+ this._spaces.set(spaceId, space2);
941
+ }
942
+ const space = this._spaces.get(spaceId);
943
+ await space.open();
944
+ return space;
945
+ }
946
+ };
947
+ var createClientFromEnv = async (env) => {
948
+ const client = new FunctionsClient({
949
+ dataService: env.DATA_SERVICE,
950
+ queueService: env.QUEUE_SERVICE,
951
+ functionsAiService: env.FUNCTIONS_AI_SERVICE
952
+ });
953
+ await client.open();
954
+ return client;
955
+ };
956
+
331
957
  // src/types.ts
332
958
  var FUNCTION_ROUTE_HEADER = "X-DXOS-Function-Route";
333
959
  var FunctionRouteValue = /* @__PURE__ */ (function(FunctionRouteValue2) {
@@ -336,22 +962,14 @@ var FunctionRouteValue = /* @__PURE__ */ (function(FunctionRouteValue2) {
336
962
  })({});
337
963
 
338
964
  // src/wrap-handler-for-cloudflare.ts
339
- import { invariant as invariant4 } from "@dxos/invariant";
965
+ import { invariant as invariant7 } from "@dxos/invariant";
340
966
  import { SpaceId as SpaceId4 } from "@dxos/keys";
341
967
  import { log as log3 } from "@dxos/log";
342
968
  import { EdgeResponse } from "@dxos/protocols";
343
- var __dxlog_file4 = "/__w/dxos/dxos/packages/core/functions-runtime-cloudflare/src/wrap-handler-for-cloudflare.ts";
969
+ var __dxlog_file7 = "/__w/dxos/dxos/packages/core/functions-runtime-cloudflare/src/wrap-handler-for-cloudflare.ts";
344
970
  var wrapHandlerForCloudflare = (func) => {
345
971
  return async (request, env) => {
346
972
  if (request.headers.get(FUNCTION_ROUTE_HEADER) === FunctionRouteValue.Meta) {
347
- log3.info(">>> meta", {
348
- func
349
- }, {
350
- F: __dxlog_file4,
351
- L: 25,
352
- S: void 0,
353
- C: (f, a) => f(...a)
354
- });
355
973
  return handleFunctionMetaCall(func, request);
356
974
  }
357
975
  try {
@@ -363,7 +981,7 @@ var wrapHandlerForCloudflare = (func) => {
363
981
  });
364
982
  }
365
983
  }
366
- const serviceContainer = new ServiceContainer({}, env.DATA_SERVICE, env.QUEUE_SERVICE);
984
+ const serviceContainer = new ServiceContainer({}, env.DATA_SERVICE, env.QUEUE_SERVICE, env.FUNCTIONS_AI_SERVICE);
367
985
  const context = await createFunctionContext({
368
986
  serviceContainer,
369
987
  contextSpaceId: spaceId
@@ -374,8 +992,8 @@ var wrapHandlerForCloudflare = (func) => {
374
992
  error,
375
993
  stack: error.stack
376
994
  }, {
377
- F: __dxlog_file4,
378
- L: 45,
995
+ F: __dxlog_file7,
996
+ L: 44,
379
997
  S: void 0,
380
998
  C: (f, a) => f(...a)
381
999
  });
@@ -412,8 +1030,8 @@ var decodeRequest = async (request) => {
412
1030
  };
413
1031
  } catch (err) {
414
1032
  log3.catch(err, void 0, {
415
- F: __dxlog_file4,
416
- L: 80,
1033
+ F: __dxlog_file7,
1034
+ L: 79,
417
1035
  S: void 0,
418
1036
  C: (f, a) => f(...a)
419
1037
  });
@@ -440,7 +1058,7 @@ var handleFunctionMetaCall = (functionDefinition, request) => {
440
1058
  });
441
1059
  };
442
1060
  var createFunctionContext = async ({ serviceContainer, contextSpaceId }) => {
443
- const { dataService, queryService, queueService } = await serviceContainer.createServices();
1061
+ const { dataService, queryService, queueService, functionsAiService } = await serviceContainer.createServices();
444
1062
  let spaceKey;
445
1063
  let rootUrl;
446
1064
  if (contextSpaceId) {
@@ -449,9 +1067,9 @@ var createFunctionContext = async ({ serviceContainer, contextSpaceId }) => {
449
1067
  throw new Error(`Space not found: ${contextSpaceId}`);
450
1068
  }
451
1069
  spaceKey = meta.spaceKey;
452
- invariant4(!meta.rootDocumentId.startsWith("automerge:"), void 0, {
453
- F: __dxlog_file4,
454
- L: 118,
1070
+ invariant7(!meta.rootDocumentId.startsWith("automerge:"), void 0, {
1071
+ F: __dxlog_file7,
1072
+ L: 117,
455
1073
  S: void 0,
456
1074
  A: [
457
1075
  "!meta.rootDocumentId.startsWith('automerge:')",
@@ -464,17 +1082,56 @@ var createFunctionContext = async ({ serviceContainer, contextSpaceId }) => {
464
1082
  services: {
465
1083
  dataService,
466
1084
  queryService,
467
- queueService
1085
+ queueService,
1086
+ functionsAiService
468
1087
  },
469
1088
  spaceId: contextSpaceId,
470
1089
  spaceKey,
471
1090
  spaceRootUrl: rootUrl
472
1091
  };
473
1092
  };
1093
+
1094
+ // src/logger.ts
1095
+ import { LogLevel, log as log4, shouldLog } from "@dxos/log";
1096
+ var setupFunctionsLogger = () => {
1097
+ log4.runtimeConfig.processors.length = 0;
1098
+ log4.runtimeConfig.processors.push(functionLogProcessor);
1099
+ };
1100
+ var functionLogProcessor = (config, entry) => {
1101
+ if (!shouldLog(entry, config.filters)) {
1102
+ return;
1103
+ }
1104
+ switch (entry.level) {
1105
+ case LogLevel.DEBUG:
1106
+ console.debug(entry.message, entry.context);
1107
+ break;
1108
+ case LogLevel.TRACE:
1109
+ console.debug(entry.message, entry.context);
1110
+ break;
1111
+ case LogLevel.VERBOSE:
1112
+ console.log(entry.message, entry.context);
1113
+ break;
1114
+ case LogLevel.INFO:
1115
+ console.info(entry.message, entry.context);
1116
+ break;
1117
+ case LogLevel.WARN:
1118
+ console.warn(entry.message, entry.context);
1119
+ break;
1120
+ case LogLevel.ERROR:
1121
+ console.error(entry.message, entry.context);
1122
+ break;
1123
+ default:
1124
+ console.log(entry.message, entry.context);
1125
+ break;
1126
+ }
1127
+ };
474
1128
  export {
475
1129
  FUNCTION_ROUTE_HEADER,
476
1130
  FunctionRouteValue,
1131
+ FunctionsClient,
477
1132
  ServiceContainer,
1133
+ createClientFromEnv,
1134
+ setupFunctionsLogger,
478
1135
  wrapHandlerForCloudflare
479
1136
  };
480
1137
  //# sourceMappingURL=index.mjs.map