@dxos/functions-runtime-cloudflare 0.8.4-main.21d9917

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 (52) hide show
  1. package/LICENSE +8 -0
  2. package/README.md +47 -0
  3. package/dist/lib/browser/index.mjs +1137 -0
  4. package/dist/lib/browser/index.mjs.map +7 -0
  5. package/dist/lib/browser/meta.json +1 -0
  6. package/dist/lib/node-esm/index.mjs +1139 -0
  7. package/dist/lib/node-esm/index.mjs.map +7 -0
  8. package/dist/lib/node-esm/meta.json +1 -0
  9. package/dist/types/src/functions-client.d.ts +33 -0
  10. package/dist/types/src/functions-client.d.ts.map +1 -0
  11. package/dist/types/src/index.d.ts +6 -0
  12. package/dist/types/src/index.d.ts.map +1 -0
  13. package/dist/types/src/internal/adapter.d.ts +12 -0
  14. package/dist/types/src/internal/adapter.d.ts.map +1 -0
  15. package/dist/types/src/internal/data-service-impl.d.ts +26 -0
  16. package/dist/types/src/internal/data-service-impl.d.ts.map +1 -0
  17. package/dist/types/src/internal/index.d.ts +2 -0
  18. package/dist/types/src/internal/index.d.ts.map +1 -0
  19. package/dist/types/src/internal/query-service-impl.d.ts +19 -0
  20. package/dist/types/src/internal/query-service-impl.d.ts.map +1 -0
  21. package/dist/types/src/internal/queue-service-impl.d.ts +11 -0
  22. package/dist/types/src/internal/queue-service-impl.d.ts.map +1 -0
  23. package/dist/types/src/internal/service-container.d.ts +27 -0
  24. package/dist/types/src/internal/service-container.d.ts.map +1 -0
  25. package/dist/types/src/internal/utils.d.ts +2 -0
  26. package/dist/types/src/internal/utils.d.ts.map +1 -0
  27. package/dist/types/src/logger.d.ts +2 -0
  28. package/dist/types/src/logger.d.ts.map +1 -0
  29. package/dist/types/src/queues-api.d.ts +22 -0
  30. package/dist/types/src/queues-api.d.ts.map +1 -0
  31. package/dist/types/src/space-proxy.d.ts +26 -0
  32. package/dist/types/src/space-proxy.d.ts.map +1 -0
  33. package/dist/types/src/types.d.ts +31 -0
  34. package/dist/types/src/types.d.ts.map +1 -0
  35. package/dist/types/src/wrap-handler-for-cloudflare.d.ts +6 -0
  36. package/dist/types/src/wrap-handler-for-cloudflare.d.ts.map +1 -0
  37. package/dist/types/tsconfig.tsbuildinfo +1 -0
  38. package/package.json +52 -0
  39. package/src/functions-client.ts +88 -0
  40. package/src/index.ts +9 -0
  41. package/src/internal/adapter.ts +48 -0
  42. package/src/internal/data-service-impl.ts +142 -0
  43. package/src/internal/index.ts +5 -0
  44. package/src/internal/query-service-impl.ts +107 -0
  45. package/src/internal/queue-service-impl.ts +69 -0
  46. package/src/internal/service-container.ts +73 -0
  47. package/src/internal/utils.ts +5 -0
  48. package/src/logger.ts +42 -0
  49. package/src/queues-api.ts +38 -0
  50. package/src/space-proxy.ts +66 -0
  51. package/src/types.ts +40 -0
  52. package/src/wrap-handler-for-cloudflare.ts +132 -0
@@ -0,0 +1,1137 @@
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
+
6
+ // src/internal/data-service-impl.ts
7
+ import { Stream } from "@dxos/codec-protobuf/stream";
8
+ import { raise } from "@dxos/debug";
9
+ import { NotImplementedError, RuntimeServiceError } from "@dxos/errors";
10
+ import { invariant } from "@dxos/invariant";
11
+ import { SpaceId } from "@dxos/keys";
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
+ }
83
+ var __dxlog_file = "/__w/dxos/dxos/packages/core/functions-runtime-cloudflare/src/internal/data-service-impl.ts";
84
+ var DataServiceImpl = class {
85
+ _executionContext;
86
+ _dataService;
87
+ dataSubscriptions = /* @__PURE__ */ new Map();
88
+ constructor(_executionContext, _dataService) {
89
+ this._executionContext = _executionContext;
90
+ this._dataService = _dataService;
91
+ }
92
+ subscribe({ subscriptionId, spaceId }) {
93
+ return new Stream(({ next }) => {
94
+ invariant(SpaceId.isValid(spaceId), void 0, {
95
+ F: __dxlog_file,
96
+ L: 39,
97
+ S: this,
98
+ A: [
99
+ "SpaceId.isValid(spaceId)",
100
+ ""
101
+ ]
102
+ });
103
+ this.dataSubscriptions.set(subscriptionId, {
104
+ spaceId,
105
+ next
106
+ });
107
+ return () => {
108
+ this.dataSubscriptions.delete(subscriptionId);
109
+ };
110
+ });
111
+ }
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
+ }));
119
+ if (addIds) {
120
+ log.info("request documents", {
121
+ count: addIds.length
122
+ }, {
123
+ F: __dxlog_file,
124
+ L: 59,
125
+ S: this,
126
+ C: (f, a) => f(...a)
127
+ });
128
+ for (const documentId of addIds) {
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
140
+ }, {
141
+ F: __dxlog_file,
142
+ L: 63,
143
+ S: this,
144
+ C: (f, a) => f(...a)
145
+ });
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);
172
+ }
173
+ }
174
+ }
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
+ }
197
+ async update({ updates, subscriptionId }) {
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);
216
+ }
217
+ }
218
+ async flush() {
219
+ }
220
+ subscribeSpaceSyncState(_request, _options) {
221
+ throw new NotImplementedError({
222
+ message: "subscribeSpaceSyncState is not implemented."
223
+ });
224
+ }
225
+ async getDocumentHeads({ documentIds: _documentIds }) {
226
+ throw new NotImplementedError({
227
+ message: "getDocumentHeads is not implemented."
228
+ });
229
+ }
230
+ async reIndexHeads({ documentIds: _documentIds }) {
231
+ throw new NotImplementedError({
232
+ message: "reIndexHeads is not implemented."
233
+ });
234
+ }
235
+ async updateIndexes() {
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
+ });
242
+ }
243
+ async waitUntilHeadsReplicated({ heads: _heads }) {
244
+ throw new NotImplementedError({
245
+ message: "waitUntilHeadsReplicated is not implemented."
246
+ });
247
+ }
248
+ };
249
+
250
+ // src/internal/query-service-impl.ts
251
+ import * as Schema from "effect/Schema";
252
+ import { Stream as Stream2 } from "@dxos/codec-protobuf/stream";
253
+ import { QueryAST } from "@dxos/echo-protocol";
254
+ import { NotImplementedError as NotImplementedError2, RuntimeServiceError as RuntimeServiceError2 } from "@dxos/errors";
255
+ import { invariant as invariant3 } from "@dxos/invariant";
256
+ import { PublicKey } from "@dxos/keys";
257
+ import { SpaceId as SpaceId3 } from "@dxos/keys";
258
+ import { log as log2 } from "@dxos/log";
259
+
260
+ // src/internal/adapter.ts
261
+ import { failUndefined } from "@dxos/debug";
262
+ import { invariant as invariant2 } from "@dxos/invariant";
263
+ import { SpaceId as SpaceId2 } from "@dxos/keys";
264
+ var __dxlog_file2 = "/__w/dxos/dxos/packages/core/functions-runtime-cloudflare/src/internal/adapter.ts";
265
+ var queryToDataServiceRequest = (query) => {
266
+ const { filter, options } = isSimpleSelectionQuery(query) ?? failUndefined();
267
+ invariant2(options?.spaceIds?.length === 1, "Only one space is supported", {
268
+ F: __dxlog_file2,
269
+ L: 13,
270
+ S: void 0,
271
+ A: [
272
+ "options?.spaceIds?.length === 1",
273
+ "'Only one space is supported'"
274
+ ]
275
+ });
276
+ invariant2(filter.type === "object", "Only object filters are supported", {
277
+ F: __dxlog_file2,
278
+ L: 14,
279
+ S: void 0,
280
+ A: [
281
+ "filter.type === 'object'",
282
+ "'Only object filters are supported'"
283
+ ]
284
+ });
285
+ const spaceId = options.spaceIds[0];
286
+ invariant2(SpaceId2.isValid(spaceId), void 0, {
287
+ F: __dxlog_file2,
288
+ L: 17,
289
+ S: void 0,
290
+ A: [
291
+ "SpaceId.isValid(spaceId)",
292
+ ""
293
+ ]
294
+ });
295
+ return {
296
+ spaceId,
297
+ type: filter.typename ?? void 0,
298
+ objectIds: [
299
+ ...filter.id ?? []
300
+ ]
301
+ };
302
+ };
303
+ var isSimpleSelectionQuery = (query) => {
304
+ switch (query.type) {
305
+ case "options": {
306
+ const maybeFilter = isSimpleSelectionQuery(query.query);
307
+ if (!maybeFilter) {
308
+ return null;
309
+ }
310
+ return {
311
+ filter: maybeFilter.filter,
312
+ options: query.options
313
+ };
314
+ }
315
+ case "select": {
316
+ return {
317
+ filter: query.filter,
318
+ options: void 0
319
+ };
320
+ }
321
+ default: {
322
+ return null;
323
+ }
324
+ }
325
+ };
326
+
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
+ }
393
+ var __dxlog_file3 = "/__w/dxos/dxos/packages/core/functions-runtime-cloudflare/src/internal/query-service-impl.ts";
394
+ var QueryServiceImpl = class {
395
+ _executionContext;
396
+ _dataService;
397
+ _queryCount = 0;
398
+ constructor(_executionContext, _dataService) {
399
+ this._executionContext = _executionContext;
400
+ this._dataService = _dataService;
401
+ }
402
+ execQuery(request) {
403
+ log2.info("execQuery", {
404
+ request
405
+ }, {
406
+ F: __dxlog_file3,
407
+ L: 34,
408
+ S: this,
409
+ C: (f, a) => f(...a)
410
+ });
411
+ const query = QueryAST.Query.pipe(Schema.decodeUnknownSync)(JSON.parse(request.query));
412
+ const requestedSpaceIds = getTargetSpacesForQuery(query);
413
+ invariant3(requestedSpaceIds.length === 1, "Only one space is supported", {
414
+ F: __dxlog_file3,
415
+ L: 37,
416
+ S: this,
417
+ A: [
418
+ "requestedSpaceIds.length === 1",
419
+ "'Only one space is supported'"
420
+ ]
421
+ });
422
+ const spaceId = requestedSpaceIds[0];
423
+ return Stream2.fromPromise((async () => {
424
+ try {
425
+ const env = {
426
+ stack: [],
427
+ error: void 0,
428
+ hasError: false
429
+ };
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) {
471
+ log2.error("query failed", {
472
+ err: error
473
+ }, {
474
+ F: __dxlog_file3,
475
+ L: 66,
476
+ S: this,
477
+ C: (f, a) => f(...a)
478
+ });
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
+ });
488
+ }
489
+ })());
490
+ }
491
+ async reindex() {
492
+ throw new NotImplementedError2({
493
+ message: "Reindex is not implemented."
494
+ });
495
+ }
496
+ async setConfig() {
497
+ throw new NotImplementedError2({
498
+ message: "SetConfig is not implemented."
499
+ });
500
+ }
501
+ };
502
+ var getTargetSpacesForQuery = (query) => {
503
+ const spaces = /* @__PURE__ */ new Set();
504
+ const visitor = (node) => {
505
+ if (node.type === "options") {
506
+ if (node.options.spaceIds) {
507
+ for (const spaceId of node.options.spaceIds) {
508
+ spaces.add(SpaceId3.make(spaceId));
509
+ }
510
+ }
511
+ }
512
+ };
513
+ QueryAST.visit(query, visitor);
514
+ return [
515
+ ...spaces
516
+ ];
517
+ };
518
+
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";
588
+ var QueueServiceImpl = class {
589
+ _ctx;
590
+ _queueService;
591
+ constructor(_ctx, _queueService) {
592
+ this._ctx = _ctx;
593
+ this._queueService = _queueService;
594
+ }
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
+ }
641
+ }
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
+ }
657
+ }
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
+ });
668
+ }
669
+ };
670
+
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
+ }
737
+ var ServiceContainer = class {
738
+ _executionContext;
739
+ _dataService;
740
+ _queueService;
741
+ _functionsService;
742
+ constructor(_executionContext, _dataService, _queueService, _functionsService) {
743
+ this._executionContext = _executionContext;
744
+ this._dataService = _dataService;
745
+ this._queueService = _queueService;
746
+ this._functionsService = _functionsService;
747
+ }
748
+ async getSpaceMeta(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
+ }
766
+ }
767
+ async createServices() {
768
+ const dataService = new DataServiceImpl(this._executionContext, this._dataService);
769
+ const queryService = new QueryServiceImpl(this._executionContext, this._dataService);
770
+ const queueService = new QueueServiceImpl(this._executionContext, this._queueService);
771
+ return {
772
+ dataService,
773
+ queryService,
774
+ queueService,
775
+ functionsAiService: this._functionsService
776
+ };
777
+ }
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);
821
+ }
822
+ insertIntoQueue(queue, objects) {
823
+ return this._serviceContainer.insertIntoQueue(queue, JSON.parse(JSON.stringify(objects)));
824
+ }
825
+ };
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
+
957
+ // src/types.ts
958
+ var FUNCTION_ROUTE_HEADER = "X-DXOS-Function-Route";
959
+ var FunctionRouteValue = /* @__PURE__ */ (function(FunctionRouteValue2) {
960
+ FunctionRouteValue2["Meta"] = "meta";
961
+ return FunctionRouteValue2;
962
+ })({});
963
+
964
+ // src/wrap-handler-for-cloudflare.ts
965
+ import { invariant as invariant7 } from "@dxos/invariant";
966
+ import { SpaceId as SpaceId4 } from "@dxos/keys";
967
+ import { log as log3 } from "@dxos/log";
968
+ import { EdgeResponse } from "@dxos/protocols";
969
+ var __dxlog_file7 = "/__w/dxos/dxos/packages/core/functions-runtime-cloudflare/src/wrap-handler-for-cloudflare.ts";
970
+ var wrapHandlerForCloudflare = (func) => {
971
+ return async (request, env) => {
972
+ if (request.headers.get(FUNCTION_ROUTE_HEADER) === FunctionRouteValue.Meta) {
973
+ return handleFunctionMetaCall(func, request);
974
+ }
975
+ try {
976
+ const spaceId = new URL(request.url).searchParams.get("spaceId");
977
+ if (spaceId) {
978
+ if (!SpaceId4.isValid(spaceId)) {
979
+ return new Response("Invalid spaceId", {
980
+ status: 400
981
+ });
982
+ }
983
+ }
984
+ const serviceContainer = new ServiceContainer({}, env.DATA_SERVICE, env.QUEUE_SERVICE, env.FUNCTIONS_AI_SERVICE);
985
+ const context = await createFunctionContext({
986
+ serviceContainer,
987
+ contextSpaceId: spaceId
988
+ });
989
+ return EdgeResponse.success(await invokeFunction(func, context, request));
990
+ } catch (error) {
991
+ log3.error("error invoking function", {
992
+ error,
993
+ stack: error.stack
994
+ }, {
995
+ F: __dxlog_file7,
996
+ L: 44,
997
+ S: void 0,
998
+ C: (f, a) => f(...a)
999
+ });
1000
+ return EdgeResponse.failure({
1001
+ message: error?.message ?? "Internal error",
1002
+ error
1003
+ });
1004
+ }
1005
+ };
1006
+ };
1007
+ var invokeFunction = async (func, context, request) => {
1008
+ const { data } = await decodeRequest(request);
1009
+ return func.handler({
1010
+ context,
1011
+ data
1012
+ });
1013
+ };
1014
+ var decodeRequest = async (request) => {
1015
+ const { data: { bodyText, ...rest }, trigger } = await request.json();
1016
+ if (!bodyText) {
1017
+ return {
1018
+ data: rest,
1019
+ trigger
1020
+ };
1021
+ }
1022
+ try {
1023
+ const data = JSON.parse(bodyText);
1024
+ return {
1025
+ data,
1026
+ trigger: {
1027
+ ...trigger,
1028
+ ...rest
1029
+ }
1030
+ };
1031
+ } catch (err) {
1032
+ log3.catch(err, void 0, {
1033
+ F: __dxlog_file7,
1034
+ L: 79,
1035
+ S: void 0,
1036
+ C: (f, a) => f(...a)
1037
+ });
1038
+ return {
1039
+ data: {
1040
+ bodyText,
1041
+ ...rest
1042
+ }
1043
+ };
1044
+ }
1045
+ };
1046
+ var handleFunctionMetaCall = (functionDefinition, request) => {
1047
+ const response = {
1048
+ key: functionDefinition.meta.key,
1049
+ name: functionDefinition.meta.name,
1050
+ description: functionDefinition.meta.description,
1051
+ inputSchema: functionDefinition.meta.inputSchema,
1052
+ outputSchema: functionDefinition.meta.outputSchema
1053
+ };
1054
+ return new Response(JSON.stringify(response), {
1055
+ headers: {
1056
+ "Content-Type": "application/json"
1057
+ }
1058
+ });
1059
+ };
1060
+ var createFunctionContext = async ({ serviceContainer, contextSpaceId }) => {
1061
+ const { dataService, queryService, queueService, functionsAiService } = await serviceContainer.createServices();
1062
+ let spaceKey;
1063
+ let rootUrl;
1064
+ if (contextSpaceId) {
1065
+ const meta = await serviceContainer.getSpaceMeta(contextSpaceId);
1066
+ if (!meta) {
1067
+ throw new Error(`Space not found: ${contextSpaceId}`);
1068
+ }
1069
+ spaceKey = meta.spaceKey;
1070
+ invariant7(!meta.rootDocumentId.startsWith("automerge:"), void 0, {
1071
+ F: __dxlog_file7,
1072
+ L: 117,
1073
+ S: void 0,
1074
+ A: [
1075
+ "!meta.rootDocumentId.startsWith('automerge:')",
1076
+ ""
1077
+ ]
1078
+ });
1079
+ rootUrl = `automerge:${meta.rootDocumentId}`;
1080
+ }
1081
+ return {
1082
+ services: {
1083
+ dataService,
1084
+ queryService,
1085
+ queueService,
1086
+ functionsAiService
1087
+ },
1088
+ spaceId: contextSpaceId,
1089
+ spaceKey,
1090
+ spaceRootUrl: rootUrl
1091
+ };
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
+ };
1128
+ export {
1129
+ FUNCTION_ROUTE_HEADER,
1130
+ FunctionRouteValue,
1131
+ FunctionsClient,
1132
+ ServiceContainer,
1133
+ createClientFromEnv,
1134
+ setupFunctionsLogger,
1135
+ wrapHandlerForCloudflare
1136
+ };
1137
+ //# sourceMappingURL=index.mjs.map