@dxos/functions 0.5.3-main.3d65399 → 0.5.3-main.423e628

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 (97) hide show
  1. package/dist/lib/browser/chunk-P3HPDHNI.mjs +86 -0
  2. package/dist/lib/browser/chunk-P3HPDHNI.mjs.map +7 -0
  3. package/dist/lib/browser/index.mjs +885 -304
  4. package/dist/lib/browser/index.mjs.map +4 -4
  5. package/dist/lib/browser/meta.json +1 -1
  6. package/dist/lib/browser/types.mjs +14 -0
  7. package/dist/lib/browser/types.mjs.map +7 -0
  8. package/dist/lib/node/chunk-KTLM3JNV.cjs +103 -0
  9. package/dist/lib/node/chunk-KTLM3JNV.cjs.map +7 -0
  10. package/dist/lib/node/index.cjs +871 -297
  11. package/dist/lib/node/index.cjs.map +4 -4
  12. package/dist/lib/node/meta.json +1 -1
  13. package/dist/lib/node/types.cjs +35 -0
  14. package/dist/lib/node/types.cjs.map +7 -0
  15. package/dist/types/src/browser/index.d.ts +2 -0
  16. package/dist/types/src/browser/index.d.ts.map +1 -0
  17. package/dist/types/src/function/function-registry.d.ts +24 -0
  18. package/dist/types/src/function/function-registry.d.ts.map +1 -0
  19. package/dist/types/src/function/function-registry.test.d.ts +2 -0
  20. package/dist/types/src/function/function-registry.test.d.ts.map +1 -0
  21. package/dist/types/src/function/index.d.ts +2 -0
  22. package/dist/types/src/function/index.d.ts.map +1 -0
  23. package/dist/types/src/handler.d.ts +33 -12
  24. package/dist/types/src/handler.d.ts.map +1 -1
  25. package/dist/types/src/index.d.ts +3 -1
  26. package/dist/types/src/index.d.ts.map +1 -1
  27. package/dist/types/src/runtime/dev-server.d.ts +15 -7
  28. package/dist/types/src/runtime/dev-server.d.ts.map +1 -1
  29. package/dist/types/src/runtime/dev-server.test.d.ts +2 -0
  30. package/dist/types/src/runtime/dev-server.test.d.ts.map +1 -0
  31. package/dist/types/src/runtime/scheduler.d.ts +15 -15
  32. package/dist/types/src/runtime/scheduler.d.ts.map +1 -1
  33. package/dist/types/src/testing/functions-integration.test.d.ts +2 -0
  34. package/dist/types/src/testing/functions-integration.test.d.ts.map +1 -0
  35. package/dist/types/src/testing/index.d.ts +4 -0
  36. package/dist/types/src/testing/index.d.ts.map +1 -0
  37. package/dist/types/src/testing/setup.d.ts +5 -0
  38. package/dist/types/src/testing/setup.d.ts.map +1 -0
  39. package/dist/types/src/testing/test/handler.d.ts +4 -0
  40. package/dist/types/src/testing/test/handler.d.ts.map +1 -0
  41. package/dist/types/src/testing/test/index.d.ts +3 -0
  42. package/dist/types/src/testing/test/index.d.ts.map +1 -0
  43. package/dist/types/src/testing/types.d.ts +9 -0
  44. package/dist/types/src/testing/types.d.ts.map +1 -0
  45. package/dist/types/src/testing/util.d.ts +3 -0
  46. package/dist/types/src/testing/util.d.ts.map +1 -0
  47. package/dist/types/src/trigger/index.d.ts +2 -0
  48. package/dist/types/src/trigger/index.d.ts.map +1 -0
  49. package/dist/types/src/trigger/trigger-registry.d.ts +40 -0
  50. package/dist/types/src/trigger/trigger-registry.d.ts.map +1 -0
  51. package/dist/types/src/trigger/trigger-registry.test.d.ts +2 -0
  52. package/dist/types/src/trigger/trigger-registry.test.d.ts.map +1 -0
  53. package/dist/types/src/trigger/type/index.d.ts +5 -0
  54. package/dist/types/src/trigger/type/index.d.ts.map +1 -0
  55. package/dist/types/src/trigger/type/subscription-trigger.d.ts +4 -0
  56. package/dist/types/src/trigger/type/subscription-trigger.d.ts.map +1 -0
  57. package/dist/types/src/trigger/type/timer-trigger.d.ts +4 -0
  58. package/dist/types/src/trigger/type/timer-trigger.d.ts.map +1 -0
  59. package/dist/types/src/trigger/type/webhook-trigger.d.ts +4 -0
  60. package/dist/types/src/trigger/type/webhook-trigger.d.ts.map +1 -0
  61. package/dist/types/src/trigger/type/websocket-trigger.d.ts +13 -0
  62. package/dist/types/src/trigger/type/websocket-trigger.d.ts.map +1 -0
  63. package/dist/types/src/types.d.ts +203 -0
  64. package/dist/types/src/types.d.ts.map +1 -0
  65. package/dist/types/tools/schema.d.ts +2 -0
  66. package/dist/types/tools/schema.d.ts.map +1 -0
  67. package/package.json +38 -13
  68. package/schema/functions.json +206 -0
  69. package/src/browser/index.ts +5 -0
  70. package/src/function/function-registry.test.ts +105 -0
  71. package/src/function/function-registry.ts +90 -0
  72. package/src/function/index.ts +5 -0
  73. package/src/handler.ts +56 -26
  74. package/src/index.ts +3 -1
  75. package/src/runtime/dev-server.test.ts +60 -0
  76. package/src/runtime/dev-server.ts +104 -53
  77. package/src/runtime/scheduler.test.ts +154 -21
  78. package/src/runtime/scheduler.ts +87 -150
  79. package/src/testing/functions-integration.test.ts +99 -0
  80. package/src/testing/index.ts +7 -0
  81. package/src/testing/setup.ts +45 -0
  82. package/src/testing/test/handler.ts +15 -0
  83. package/src/testing/test/index.ts +7 -0
  84. package/src/testing/types.ts +9 -0
  85. package/src/testing/util.ts +16 -0
  86. package/src/trigger/index.ts +5 -0
  87. package/src/trigger/trigger-registry.test.ts +255 -0
  88. package/src/trigger/trigger-registry.ts +201 -0
  89. package/src/trigger/type/index.ts +8 -0
  90. package/src/trigger/type/subscription-trigger.ts +80 -0
  91. package/src/trigger/type/timer-trigger.ts +44 -0
  92. package/src/trigger/type/webhook-trigger.ts +47 -0
  93. package/src/trigger/type/websocket-trigger.ts +91 -0
  94. package/src/types.ts +112 -0
  95. package/dist/types/src/manifest.d.ts +0 -26
  96. package/dist/types/src/manifest.d.ts.map +0 -1
  97. package/src/manifest.ts +0 -42
@@ -29,83 +29,206 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
29
29
  var node_exports = {};
30
30
  __export(node_exports, {
31
31
  DevServer: () => DevServer,
32
+ FUNCTION_SCHEMA: () => import_chunk_KTLM3JNV.FUNCTION_SCHEMA,
33
+ FunctionDef: () => import_chunk_KTLM3JNV.FunctionDef,
34
+ FunctionManifestSchema: () => import_chunk_KTLM3JNV.FunctionManifestSchema,
35
+ FunctionRegistry: () => FunctionRegistry,
36
+ FunctionTrigger: () => import_chunk_KTLM3JNV.FunctionTrigger,
32
37
  Scheduler: () => Scheduler,
38
+ TriggerRegistry: () => TriggerRegistry,
33
39
  subscriptionHandler: () => subscriptionHandler
34
40
  });
35
41
  module.exports = __toCommonJS(node_exports);
36
- var import_client = require("@dxos/client");
42
+ var import_chunk_KTLM3JNV = require("./chunk-KTLM3JNV.cjs");
43
+ var import_async = require("@dxos/async");
44
+ var import_echo = require("@dxos/client/echo");
45
+ var import_context = require("@dxos/context");
46
+ var import_keys = require("@dxos/keys");
37
47
  var import_log = require("@dxos/log");
38
48
  var import_util = require("@dxos/util");
49
+ var import_client = require("@dxos/client");
50
+ var import_log2 = require("@dxos/log");
51
+ var import_util2 = require("@dxos/util");
39
52
  var import_express = __toESM(require("express"));
40
53
  var import_get_port_please = require("get-port-please");
41
54
  var import_node_path = require("node:path");
42
- var import_async = require("@dxos/async");
43
- var import_invariant = require("@dxos/invariant");
44
- var import_log2 = require("@dxos/log");
45
- var import_cron = require("cron");
46
- var import_types = require("@braneframe/types");
47
55
  var import_async2 = require("@dxos/async");
48
- var import_echo = require("@dxos/client/echo");
49
- var import_context = require("@dxos/context");
50
- var import_invariant2 = require("@dxos/invariant");
56
+ var import_context2 = require("@dxos/context");
57
+ var import_invariant = require("@dxos/invariant");
51
58
  var import_log3 = require("@dxos/log");
52
- var import_util2 = require("@dxos/util");
53
- var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
54
- get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
55
- }) : x)(function(x) {
56
- if (typeof require !== "undefined")
57
- return require.apply(this, arguments);
58
- throw Error('Dynamic require of "' + x + '" is not supported');
59
- });
60
- var __dxlog_file = "/home/runner/work/dxos/dxos/packages/core/functions/src/handler.ts";
59
+ var import_node_path2 = __toESM(require("node:path"));
60
+ var import_async3 = require("@dxos/async");
61
+ var import_context3 = require("@dxos/context");
62
+ var import_log4 = require("@dxos/log");
63
+ var import_async4 = require("@dxos/async");
64
+ var import_echo2 = require("@dxos/client/echo");
65
+ var import_context4 = require("@dxos/context");
66
+ var import_echo_schema = require("@dxos/echo-schema");
67
+ var import_invariant2 = require("@dxos/invariant");
68
+ var import_keys2 = require("@dxos/keys");
69
+ var import_log5 = require("@dxos/log");
70
+ var import_util3 = require("@dxos/util");
71
+ var import_types = require("@braneframe/types");
72
+ var import_async5 = require("@dxos/async");
73
+ var import_echo_db = require("@dxos/echo-db");
74
+ var import_log6 = require("@dxos/log");
75
+ var import_cron = require("cron");
76
+ var import_async6 = require("@dxos/async");
77
+ var import_log7 = require("@dxos/log");
78
+ var import_get_port_please2 = require("get-port-please");
79
+ var import_node_http = __toESM(require("node:http"));
80
+ var import_log8 = require("@dxos/log");
81
+ var import_ws = __toESM(require("ws"));
82
+ var import_async7 = require("@dxos/async");
83
+ var import_log9 = require("@dxos/log");
84
+ var __dxlog_file = "/home/runner/work/dxos/dxos/packages/core/functions/src/function/function-registry.ts";
85
+ var FunctionRegistry = class extends import_context.Resource {
86
+ constructor(_client) {
87
+ super();
88
+ this._client = _client;
89
+ this._functionBySpaceKey = new import_util.ComplexMap(import_keys.PublicKey.hash);
90
+ this.registered = new import_async.Event();
91
+ }
92
+ getFunctions(space) {
93
+ return this._functionBySpaceKey.get(space.key) ?? [];
94
+ }
95
+ /**
96
+ * Loads function definitions from the manifest into the space.
97
+ * We first load all the definitions from the space to deduplicate by functionId.
98
+ */
99
+ async register(space, functions) {
100
+ (0, import_log.log)("register", {
101
+ space: space.key,
102
+ functions: functions?.length ?? 0
103
+ }, {
104
+ F: __dxlog_file,
105
+ L: 38,
106
+ S: this,
107
+ C: (f, a) => f(...a)
108
+ });
109
+ if (!functions?.length) {
110
+ return;
111
+ }
112
+ if (!space.db.graph.runtimeSchemaRegistry.hasSchema(import_chunk_KTLM3JNV.FunctionDef)) {
113
+ space.db.graph.runtimeSchemaRegistry.registerSchema(import_chunk_KTLM3JNV.FunctionDef);
114
+ }
115
+ const { objects: existing } = await space.db.query(import_echo.Filter.schema(import_chunk_KTLM3JNV.FunctionDef)).run();
116
+ const { added } = (0, import_util.diff)(existing, functions, (a, b) => a.uri === b.uri);
117
+ added.forEach((def) => space.db.add((0, import_echo.create)(import_chunk_KTLM3JNV.FunctionDef, def)));
118
+ }
119
+ async _open() {
120
+ import_log.log.info("opening...", void 0, {
121
+ F: __dxlog_file,
122
+ L: 54,
123
+ S: this,
124
+ C: (f, a) => f(...a)
125
+ });
126
+ const spacesSubscription = this._client.spaces.subscribe(async (spaces) => {
127
+ for (const space of spaces) {
128
+ if (this._functionBySpaceKey.has(space.key)) {
129
+ continue;
130
+ }
131
+ const registered = [];
132
+ this._functionBySpaceKey.set(space.key, registered);
133
+ await space.waitUntilReady();
134
+ if (this._ctx.disposed) {
135
+ break;
136
+ }
137
+ this._ctx.onDispose(space.db.query(import_echo.Filter.schema(import_chunk_KTLM3JNV.FunctionDef)).subscribe(({ objects }) => {
138
+ const { added } = (0, import_util.diff)(registered, objects, (a, b) => a.uri === b.uri);
139
+ if (added.length > 0) {
140
+ registered.push(...added);
141
+ this.registered.emit({
142
+ space,
143
+ added
144
+ });
145
+ }
146
+ }));
147
+ }
148
+ });
149
+ this._ctx.onDispose(() => spacesSubscription.unsubscribe());
150
+ }
151
+ async _close(_) {
152
+ import_log.log.info("closing...", void 0, {
153
+ F: __dxlog_file,
154
+ L: 87,
155
+ S: this,
156
+ C: (f, a) => f(...a)
157
+ });
158
+ this._functionBySpaceKey.clear();
159
+ }
160
+ };
161
+ var __dxlog_file2 = "/home/runner/work/dxos/dxos/packages/core/functions/src/handler.ts";
61
162
  var subscriptionHandler = (handler) => {
62
- return ({ event, context, ...rest }) => {
163
+ return ({ event: { data }, context, ...rest }) => {
63
164
  const { client } = context;
64
- const space = event.space ? client.spaces.get(import_client.PublicKey.from(event.space)) : void 0;
65
- const objects = space && event.objects?.map((id) => space.db.getObjectById(id)).filter(import_util.nonNullable);
66
- if (!!event.space && !space) {
67
- import_log.log.warn("invalid space", {
68
- event
165
+ const space = data.spaceKey ? client.spaces.get(import_client.PublicKey.from(data.spaceKey)) : void 0;
166
+ const objects = space ? data.objects?.map((id) => space.db.getObjectById(id)).filter(import_util2.nonNullable) : [];
167
+ if (!!data.spaceKey && !space) {
168
+ import_log2.log.warn("invalid space", {
169
+ data
69
170
  }, {
70
- F: __dxlog_file,
71
- L: 61,
171
+ F: __dxlog_file2,
172
+ L: 91,
72
173
  S: void 0,
73
174
  C: (f, a) => f(...a)
74
175
  });
75
176
  } else {
76
- import_log.log.info("handler", {
177
+ import_log2.log.info("handler", {
77
178
  space: space?.key.truncate(),
78
179
  objects: objects?.length
79
180
  }, {
80
- F: __dxlog_file,
81
- L: 63,
181
+ F: __dxlog_file2,
182
+ L: 93,
82
183
  S: void 0,
83
184
  C: (f, a) => f(...a)
84
185
  });
85
186
  }
86
187
  return handler({
87
188
  event: {
88
- space,
89
- objects
189
+ data: {
190
+ ...data,
191
+ space,
192
+ objects
193
+ }
90
194
  },
91
195
  context,
92
196
  ...rest
93
197
  });
94
198
  };
95
199
  };
96
- var __dxlog_file2 = "/home/runner/work/dxos/dxos/packages/core/functions/src/runtime/dev-server.ts";
200
+ var __dxlog_file3 = "/home/runner/work/dxos/dxos/packages/core/functions/src/runtime/dev-server.ts";
97
201
  var DevServer = class {
98
- // prettier-ignore
99
- constructor(_client, _options) {
202
+ constructor(_client, _functionsRegistry, _options) {
100
203
  this._client = _client;
204
+ this._functionsRegistry = _functionsRegistry;
101
205
  this._options = _options;
206
+ this._ctx = createContext();
102
207
  this._handlers = {};
103
208
  this._seq = 0;
209
+ this.update = new import_async2.Event();
210
+ this._functionsRegistry.registered.on(async ({ added }) => {
211
+ added.forEach((def) => this._load(def));
212
+ await this._safeUpdateRegistration();
213
+ (0, import_log3.log)("new functions loaded", {
214
+ added
215
+ }, {
216
+ F: __dxlog_file3,
217
+ L: 52,
218
+ S: this,
219
+ C: (f, a) => f(...a)
220
+ });
221
+ });
222
+ }
223
+ get stats() {
224
+ return {
225
+ seq: this._seq
226
+ };
104
227
  }
105
228
  get endpoint() {
106
229
  (0, import_invariant.invariant)(this._port, void 0, {
107
- F: __dxlog_file2,
108
- L: 46,
230
+ F: __dxlog_file3,
231
+ L: 63,
109
232
  S: this,
110
233
  A: [
111
234
  "this._port",
@@ -120,44 +243,46 @@ var DevServer = class {
120
243
  get functions() {
121
244
  return Object.values(this._handlers);
122
245
  }
123
- async initialize() {
124
- for (const def of this._options.manifest.functions) {
125
- try {
126
- await this._load(def);
127
- } catch (err) {
128
- import_log2.log.error("parsing function (check manifest)", err, {
129
- F: __dxlog_file2,
130
- L: 63,
131
- S: this,
132
- C: (f, a) => f(...a)
133
- });
134
- }
135
- }
136
- }
137
246
  async start() {
247
+ (0, import_invariant.invariant)(!this._server, void 0, {
248
+ F: __dxlog_file3,
249
+ L: 76,
250
+ S: this,
251
+ A: [
252
+ "!this._server",
253
+ ""
254
+ ]
255
+ });
256
+ import_log3.log.info("starting...", void 0, {
257
+ F: __dxlog_file3,
258
+ L: 77,
259
+ S: this,
260
+ C: (f, a) => f(...a)
261
+ });
262
+ this._ctx = createContext();
138
263
  const app = (0, import_express.default)();
139
264
  app.use(import_express.default.json());
140
- app.post("/:name", async (req, res) => {
141
- const { name } = req.params;
265
+ app.post("/:path", async (req, res) => {
266
+ const { path: path2 } = req.params;
142
267
  try {
143
- import_log2.log.info("calling", {
144
- name
268
+ import_log3.log.info("calling", {
269
+ path: path2
145
270
  }, {
146
- F: __dxlog_file2,
147
- L: 75,
271
+ F: __dxlog_file3,
272
+ L: 87,
148
273
  S: this,
149
274
  C: (f, a) => f(...a)
150
275
  });
151
276
  if (this._options.reload) {
152
- const { def } = this._handlers[name];
277
+ const { def } = this._handlers["/" + path2];
153
278
  await this._load(def, true);
154
279
  }
155
- res.statusCode = await this._invoke(name, req.body);
280
+ res.statusCode = await this.invoke("/" + path2, req.body);
156
281
  res.end();
157
282
  } catch (err) {
158
- import_log2.log.catch(err, void 0, {
159
- F: __dxlog_file2,
160
- L: 84,
283
+ import_log3.log.catch(err, void 0, {
284
+ F: __dxlog_file3,
285
+ L: 97,
161
286
  S: this,
162
287
  C: (f, a) => f(...a)
163
288
  });
@@ -176,93 +301,195 @@ var DevServer = class {
176
301
  this._server = app.listen(this._port);
177
302
  try {
178
303
  const { registrationId, endpoint } = await this._client.services.services.FunctionRegistryService.register({
179
- endpoint: this.endpoint,
180
- functions: this.functions.map(({ def: { name } }) => ({
181
- name
182
- }))
304
+ endpoint: this.endpoint
183
305
  });
184
- import_log2.log.info("registered", {
185
- registrationId,
306
+ import_log3.log.info("registered", {
186
307
  endpoint
187
308
  }, {
188
- F: __dxlog_file2,
189
- L: 100,
309
+ F: __dxlog_file3,
310
+ L: 112,
190
311
  S: this,
191
312
  C: (f, a) => f(...a)
192
313
  });
193
- this._registrationId = registrationId;
194
314
  this._proxy = endpoint;
315
+ this._functionServiceRegistration = registrationId;
316
+ await this._functionsRegistry.open(this._ctx);
195
317
  } catch (err) {
196
318
  await this.stop();
197
319
  throw new Error("FunctionRegistryService not available (check plugin is configured).");
198
320
  }
321
+ import_log3.log.info("started", {
322
+ port: this._port
323
+ }, {
324
+ F: __dxlog_file3,
325
+ L: 123,
326
+ S: this,
327
+ C: (f, a) => f(...a)
328
+ });
199
329
  }
200
330
  async stop() {
201
- const trigger = new import_async.Trigger();
202
- this._server?.close(async () => {
203
- if (this._registrationId) {
204
- await this._client.services.services.FunctionRegistryService.unregister({
205
- registrationId: this._registrationId
206
- });
207
- import_log2.log.info("unregistered", {
208
- registrationId: this._registrationId
209
- }, {
210
- F: __dxlog_file2,
211
- L: 117,
212
- S: this,
213
- C: (f, a) => f(...a)
214
- });
215
- this._registrationId = void 0;
216
- this._proxy = void 0;
331
+ (0, import_invariant.invariant)(this._server, void 0, {
332
+ F: __dxlog_file3,
333
+ L: 127,
334
+ S: this,
335
+ A: [
336
+ "this._server",
337
+ ""
338
+ ]
339
+ });
340
+ import_log3.log.info("stopping...", void 0, {
341
+ F: __dxlog_file3,
342
+ L: 128,
343
+ S: this,
344
+ C: (f, a) => f(...a)
345
+ });
346
+ const trigger = new import_async2.Trigger();
347
+ this._server.close(async () => {
348
+ import_log3.log.info("server stopped", void 0, {
349
+ F: __dxlog_file3,
350
+ L: 132,
351
+ S: this,
352
+ C: (f, a) => f(...a)
353
+ });
354
+ try {
355
+ if (this._functionServiceRegistration) {
356
+ (0, import_invariant.invariant)(this._client.services.services.FunctionRegistryService, void 0, {
357
+ F: __dxlog_file3,
358
+ L: 135,
359
+ S: this,
360
+ A: [
361
+ "this._client.services.services.FunctionRegistryService",
362
+ ""
363
+ ]
364
+ });
365
+ await this._client.services.services.FunctionRegistryService.unregister({
366
+ registrationId: this._functionServiceRegistration
367
+ });
368
+ import_log3.log.info("unregistered", {
369
+ registrationId: this._functionServiceRegistration
370
+ }, {
371
+ F: __dxlog_file3,
372
+ L: 140,
373
+ S: this,
374
+ C: (f, a) => f(...a)
375
+ });
376
+ this._functionServiceRegistration = void 0;
377
+ this._proxy = void 0;
378
+ }
379
+ trigger.wake();
380
+ } catch (err) {
381
+ trigger.throw(err);
217
382
  }
218
- trigger.wake();
219
383
  });
220
384
  await trigger.wait();
221
385
  this._port = void 0;
222
386
  this._server = void 0;
387
+ import_log3.log.info("stopped", void 0, {
388
+ F: __dxlog_file3,
389
+ L: 154,
390
+ S: this,
391
+ C: (f, a) => f(...a)
392
+ });
223
393
  }
224
394
  /**
225
395
  * Load function.
226
396
  */
227
- async _load(def, flush = false) {
228
- const { id, name, handler } = def;
229
- const path = (0, import_node_path.join)(this._options.directory, handler);
230
- import_log2.log.info("loading", {
231
- id
397
+ async _load(def, force) {
398
+ const { uri, route, handler } = def;
399
+ const filePath = (0, import_node_path.join)(this._options.baseDir, handler);
400
+ import_log3.log.info("loading", {
401
+ uri,
402
+ force
232
403
  }, {
233
- F: __dxlog_file2,
234
- L: 136,
404
+ F: __dxlog_file3,
405
+ L: 163,
235
406
  S: this,
236
407
  C: (f, a) => f(...a)
237
408
  });
238
- if (flush) {
239
- Object.keys(__require.cache).filter((key) => key.startsWith(path)).forEach((key) => delete __require.cache[key]);
409
+ if (force) {
410
+ Object.keys(import_chunk_KTLM3JNV.__require.cache).filter((key) => key.startsWith(filePath)).forEach((key) => {
411
+ delete import_chunk_KTLM3JNV.__require.cache[key];
412
+ });
240
413
  }
241
- const module2 = __require(path);
414
+ const module2 = (0, import_chunk_KTLM3JNV.__require)(filePath);
242
415
  if (typeof module2.default !== "function") {
243
- throw new Error(`Handler must export default function: ${id}`);
416
+ throw new Error(`Handler must export default function: ${uri}`);
244
417
  }
245
- this._handlers[name] = {
418
+ this._handlers[route] = {
246
419
  def,
247
420
  handler: module2.default
248
421
  };
249
422
  }
423
+ async _safeUpdateRegistration() {
424
+ (0, import_invariant.invariant)(this._functionServiceRegistration, void 0, {
425
+ F: __dxlog_file3,
426
+ L: 185,
427
+ S: this,
428
+ A: [
429
+ "this._functionServiceRegistration",
430
+ ""
431
+ ]
432
+ });
433
+ try {
434
+ await this._client.services.services.FunctionRegistryService.updateRegistration({
435
+ registrationId: this._functionServiceRegistration,
436
+ functions: this.functions.map(({ def: { id, route } }) => ({
437
+ id,
438
+ route
439
+ }))
440
+ });
441
+ } catch (e) {
442
+ import_log3.log.catch(e, void 0, {
443
+ F: __dxlog_file3,
444
+ L: 192,
445
+ S: this,
446
+ C: (f, a) => f(...a)
447
+ });
448
+ }
449
+ }
250
450
  /**
251
- * Invoke function handler.
451
+ * Invoke function.
252
452
  */
253
- async _invoke(name, event) {
453
+ async invoke(path2, data) {
254
454
  const seq = ++this._seq;
255
455
  const now = Date.now();
256
- import_log2.log.info("req", {
456
+ import_log3.log.info("req", {
457
+ seq,
458
+ path: path2
459
+ }, {
460
+ F: __dxlog_file3,
461
+ L: 203,
462
+ S: this,
463
+ C: (f, a) => f(...a)
464
+ });
465
+ const statusCode = await this._invoke(path2, {
466
+ data
467
+ });
468
+ import_log3.log.info("res", {
257
469
  seq,
258
- name
470
+ path: path2,
471
+ statusCode,
472
+ duration: Date.now() - now
259
473
  }, {
260
- F: __dxlog_file2,
261
- L: 161,
474
+ F: __dxlog_file3,
475
+ L: 206,
262
476
  S: this,
263
477
  C: (f, a) => f(...a)
264
478
  });
265
- const { handler } = this._handlers[name];
479
+ this.update.emit(statusCode);
480
+ return statusCode;
481
+ }
482
+ async _invoke(path2, event) {
483
+ const { handler } = this._handlers[path2] ?? {};
484
+ (0, import_invariant.invariant)(handler, `invalid path: ${path2}`, {
485
+ F: __dxlog_file3,
486
+ L: 213,
487
+ S: this,
488
+ A: [
489
+ "handler",
490
+ "`invalid path: ${path}`"
491
+ ]
492
+ });
266
493
  const context = {
267
494
  client: this._client,
268
495
  dataDir: this._options.dataDir
@@ -279,253 +506,600 @@ var DevServer = class {
279
506
  event,
280
507
  response
281
508
  });
282
- import_log2.log.info("res", {
283
- seq,
284
- name,
285
- statusCode,
286
- duration: Date.now() - now
287
- }, {
288
- F: __dxlog_file2,
289
- L: 178,
290
- S: this,
291
- C: (f, a) => f(...a)
292
- });
293
509
  return statusCode;
294
510
  }
295
511
  };
296
- var __dxlog_file3 = "/home/runner/work/dxos/dxos/packages/core/functions/src/runtime/scheduler.ts";
512
+ var createContext = () => new import_context2.Context({
513
+ name: "DevServer"
514
+ });
515
+ var __dxlog_file4 = "/home/runner/work/dxos/dxos/packages/core/functions/src/runtime/scheduler.ts";
297
516
  var Scheduler = class {
298
- constructor(_client, _manifest, _options = {}) {
299
- this._client = _client;
300
- this._manifest = _manifest;
517
+ constructor(functions, triggers, _options = {}) {
518
+ this.functions = functions;
519
+ this.triggers = triggers;
301
520
  this._options = _options;
302
- this._mounts = new import_util2.ComplexMap(({ id, spaceKey }) => `${spaceKey.toHex()}:${id}`);
521
+ this._ctx = createContext2();
522
+ this._functionUriToCallMutex = /* @__PURE__ */ new Map();
523
+ this.functions.registered.on(async ({ space, added }) => {
524
+ await this._safeActivateTriggers(space, this.triggers.getInactiveTriggers(space), added);
525
+ });
526
+ this.triggers.registered.on(async ({ space, triggers: triggers2 }) => {
527
+ await this._safeActivateTriggers(space, triggers2, this.functions.getFunctions(space));
528
+ });
303
529
  }
304
530
  async start() {
305
- this._client.spaces.subscribe(async (spaces) => {
306
- for (const space of spaces) {
307
- await space.waitUntilReady();
308
- for (const trigger of this._manifest.triggers ?? []) {
309
- await this.mount(new import_context.Context(), space, trigger);
310
- }
311
- }
312
- });
531
+ await this._ctx.dispose();
532
+ this._ctx = createContext2();
533
+ await this.functions.open(this._ctx);
534
+ await this.triggers.open(this._ctx);
313
535
  }
314
536
  async stop() {
315
- for (const { id, spaceKey } of this._mounts.keys()) {
316
- await this.unmount(id, spaceKey);
317
- }
537
+ await this._ctx.dispose();
538
+ await this.functions.close();
539
+ await this.triggers.close();
318
540
  }
319
- async mount(ctx, space, trigger) {
320
- const key = {
321
- id: trigger.function,
322
- spaceKey: space.key
323
- };
324
- const def = this._manifest.functions.find((config) => config.id === trigger.function);
325
- (0, import_invariant2.invariant)(def, `Function not found: ${trigger.function}`, {
326
- F: __dxlog_file3,
327
- L: 63,
328
- S: this,
329
- A: [
330
- "def",
331
- "`Function not found: ${trigger.function}`"
332
- ]
541
+ // TODO(burdon): Remove and update registries directly.
542
+ async register(space, manifest) {
543
+ await this.functions.register(space, manifest.functions);
544
+ await this.triggers.register(space, manifest);
545
+ }
546
+ async _safeActivateTriggers(space, triggers, functions) {
547
+ const mountTasks = triggers.map((trigger) => {
548
+ return this.activate(space, functions, trigger);
333
549
  });
334
- const exists = this._mounts.get(key);
335
- if (!exists) {
336
- this._mounts.set(key, {
337
- ctx,
338
- trigger
339
- });
340
- (0, import_log3.log)("mount", {
341
- space: space.key,
342
- trigger
550
+ await Promise.all(mountTasks).catch(import_log4.log.catch);
551
+ }
552
+ async activate(space, functions, fnTrigger) {
553
+ const definition = functions.find((def) => def.uri === fnTrigger.function);
554
+ if (!definition) {
555
+ import_log4.log.info("function is not found for trigger", {
556
+ fnTrigger
343
557
  }, {
344
- F: __dxlog_file3,
345
- L: 69,
558
+ F: __dxlog_file4,
559
+ L: 78,
346
560
  S: this,
347
561
  C: (f, a) => f(...a)
348
562
  });
349
- if (ctx.disposed) {
350
- return;
351
- }
352
- if (trigger.schedule) {
353
- this._createTimer(ctx, space, def, trigger);
354
- }
355
- for (const triggerSubscription of trigger.subscriptions ?? []) {
356
- this._createSubscription(ctx, space, def, triggerSubscription);
357
- }
358
- }
359
- }
360
- async unmount(id, spaceKey) {
361
- const key = {
362
- id,
363
- spaceKey
364
- };
365
- const { ctx } = this._mounts.get(key) ?? {};
366
- if (ctx) {
367
- this._mounts.delete(key);
368
- await ctx.dispose();
563
+ return;
369
564
  }
370
- }
371
- _createTimer(ctx, space, def, trigger) {
372
- const task = new import_async2.DeferredTask(ctx, async () => {
373
- await this._execFunction(def, {
374
- space: space.key
565
+ await this.triggers.activate({
566
+ space
567
+ }, fnTrigger, async (args) => {
568
+ const mutex = this._functionUriToCallMutex.get(definition.uri) ?? new import_async3.Mutex();
569
+ this._functionUriToCallMutex.set(definition.uri, mutex);
570
+ import_log4.log.info("function triggered, waiting for mutex", {
571
+ uri: definition.uri
572
+ }, {
573
+ F: __dxlog_file4,
574
+ L: 86,
575
+ S: this,
576
+ C: (f, a) => f(...a)
375
577
  });
376
- });
377
- (0, import_invariant2.invariant)(trigger.schedule, void 0, {
378
- F: __dxlog_file3,
379
- L: 102,
380
- S: this,
381
- A: [
382
- "trigger.schedule",
383
- ""
384
- ]
385
- });
386
- let last = 0;
387
- let run = 0;
388
- const job = import_cron.CronJob.from({
389
- cronTime: trigger.schedule,
390
- runOnInit: false,
391
- onTick: () => {
392
- const now = Date.now();
393
- const delta = last ? now - last : 0;
394
- last = now;
395
- run++;
396
- import_log3.log.info("tick", {
397
- space: space.key.truncate(),
398
- count: run,
399
- delta
578
+ return mutex.executeSynchronized(() => {
579
+ import_log4.log.info("mutex acquired", {
580
+ uri: definition.uri
400
581
  }, {
401
- F: __dxlog_file3,
402
- L: 116,
582
+ F: __dxlog_file4,
583
+ L: 88,
403
584
  S: this,
404
585
  C: (f, a) => f(...a)
405
586
  });
406
- task.schedule();
407
- }
587
+ return this._execFunction(definition, fnTrigger, {
588
+ meta: fnTrigger.meta,
589
+ data: {
590
+ ...args,
591
+ spaceKey: space.key
592
+ }
593
+ });
594
+ });
408
595
  });
409
- job.start();
410
- ctx.onDispose(() => job.stop());
411
- }
412
- _createSubscription(ctx, space, def, triggerSubscription) {
413
- import_log3.log.info("subscription", {
596
+ (0, import_log4.log)("activated trigger", {
414
597
  space: space.key,
415
- triggerSubscription
598
+ trigger: fnTrigger
416
599
  }, {
417
- F: __dxlog_file3,
418
- L: 126,
600
+ F: __dxlog_file4,
601
+ L: 96,
419
602
  S: this,
420
603
  C: (f, a) => f(...a)
421
604
  });
422
- const objectIds = /* @__PURE__ */ new Set();
423
- const task = new import_async2.DeferredTask(ctx, async () => {
424
- await this._execFunction(def, {
425
- space: space.key,
426
- objects: Array.from(objectIds)
427
- });
428
- });
429
- const subscriptions = [];
430
- const subscription = (0, import_echo.createSubscription)(({ added, updated }) => {
431
- import_log3.log.info("updated", {
432
- added: added.length,
433
- updated: updated.length
434
- }, {
435
- F: __dxlog_file3,
436
- L: 139,
437
- S: this,
438
- C: (f, a) => f(...a)
439
- });
440
- for (const object of added) {
441
- objectIds.add(object.id);
442
- }
443
- for (const object of updated) {
444
- objectIds.add(object.id);
445
- }
446
- task.schedule();
447
- });
448
- subscriptions.push(() => subscription.unsubscribe());
449
- const { type, props, deep, delay } = triggerSubscription;
450
- const update = ({ objects }) => {
451
- subscription.update(objects);
452
- if (deep) {
453
- import_log3.log.info("update", {
454
- type,
455
- deep,
456
- objects: objects.length
457
- }, {
458
- F: __dxlog_file3,
459
- L: 159,
460
- S: this,
461
- C: (f, a) => f(...a)
462
- });
463
- for (const object of objects) {
464
- const content = object.content;
465
- if (content instanceof import_types.TextV0Type) {
466
- subscriptions.push((0, import_echo.getAutomergeObjectCore)(content).updates.on((0, import_async2.debounce)(() => subscription.update([
467
- object
468
- ]), 1e3)));
469
- }
470
- }
471
- }
472
- };
473
- const query = space.db.query(import_echo.Filter.typename(type, props));
474
- subscriptions.push(query.subscribe(delay ? (0, import_async2.debounce)(update, delay * 1e3) : update));
475
- ctx.onDispose(() => {
476
- subscriptions.forEach((unsubscribe) => unsubscribe());
477
- });
478
605
  }
479
- async _execFunction(def, data) {
606
+ async _execFunction(def, trigger, { data, meta }) {
607
+ let status = 0;
480
608
  try {
481
- (0, import_log3.log)("request", {
482
- function: def.id
483
- }, {
484
- F: __dxlog_file3,
485
- L: 183,
486
- S: this,
487
- C: (f, a) => f(...a)
488
- });
609
+ const payload = Object.assign({}, meta && {
610
+ meta
611
+ }, data);
489
612
  const { endpoint, callback } = this._options;
490
- let status = 0;
491
613
  if (endpoint) {
492
- const response = await fetch(`${this._options.endpoint}/${def.name}`, {
614
+ const url = import_node_path2.default.join(endpoint, def.route);
615
+ import_log4.log.info("exec", {
616
+ function: def.uri,
617
+ url,
618
+ triggerType: trigger.spec.type
619
+ }, {
620
+ F: __dxlog_file4,
621
+ L: 113,
622
+ S: this,
623
+ C: (f, a) => f(...a)
624
+ });
625
+ const response = await fetch(url, {
493
626
  method: "POST",
494
627
  headers: {
495
628
  "Content-Type": "application/json"
496
629
  },
497
- body: JSON.stringify(data)
630
+ body: JSON.stringify(payload)
498
631
  });
499
632
  status = response.status;
500
633
  } else if (callback) {
501
- status = await callback(data);
634
+ import_log4.log.info("exec", {
635
+ function: def.uri
636
+ }, {
637
+ F: __dxlog_file4,
638
+ L: 124,
639
+ S: this,
640
+ C: (f, a) => f(...a)
641
+ });
642
+ status = await callback(payload) ?? 200;
643
+ }
644
+ if (status && status >= 400) {
645
+ throw new Error(`Response: ${status}`);
502
646
  }
503
- (0, import_log3.log)("result", {
504
- function: def.id,
505
- result: status
647
+ import_log4.log.info("done", {
648
+ function: def.uri,
649
+ status
506
650
  }, {
507
- F: __dxlog_file3,
508
- L: 202,
651
+ F: __dxlog_file4,
652
+ L: 134,
509
653
  S: this,
510
654
  C: (f, a) => f(...a)
511
655
  });
512
656
  } catch (err) {
513
- import_log3.log.error("error", {
514
- function: def.id,
657
+ import_log4.log.error("error", {
658
+ function: def.uri,
515
659
  error: err.message
516
660
  }, {
517
- F: __dxlog_file3,
518
- L: 204,
661
+ F: __dxlog_file4,
662
+ L: 136,
663
+ S: this,
664
+ C: (f, a) => f(...a)
665
+ });
666
+ status = 500;
667
+ }
668
+ return status;
669
+ }
670
+ };
671
+ var createContext2 = () => new import_context3.Context({
672
+ name: "FunctionScheduler"
673
+ });
674
+ var __dxlog_file5 = "/home/runner/work/dxos/dxos/packages/core/functions/src/trigger/type/subscription-trigger.ts";
675
+ var createSubscriptionTrigger = async (ctx, triggerCtx, spec, callback) => {
676
+ const objectIds = /* @__PURE__ */ new Set();
677
+ const task = new import_async5.UpdateScheduler(ctx, async () => {
678
+ if (objectIds.size > 0) {
679
+ const objects = Array.from(objectIds);
680
+ objectIds.clear();
681
+ await callback({
682
+ objects
683
+ });
684
+ }
685
+ }, {
686
+ maxFrequency: 4
687
+ });
688
+ const subscriptions = [];
689
+ const subscription = (0, import_echo_db.createSubscription)(({ added, updated }) => {
690
+ const sizeBefore = objectIds.size;
691
+ for (const object of added) {
692
+ objectIds.add(object.id);
693
+ }
694
+ for (const object of updated) {
695
+ objectIds.add(object.id);
696
+ }
697
+ if (objectIds.size > sizeBefore) {
698
+ import_log6.log.info("updated", {
699
+ added: added.length,
700
+ updated: updated.length
701
+ }, {
702
+ F: __dxlog_file5,
703
+ L: 45,
704
+ S: void 0,
705
+ C: (f, a) => f(...a)
706
+ });
707
+ task.trigger();
708
+ }
709
+ });
710
+ subscriptions.push(() => subscription.unsubscribe());
711
+ const { filter, options: { deep, delay } = {} } = spec;
712
+ const update = ({ objects }) => {
713
+ subscription.update(objects);
714
+ if (deep) {
715
+ import_log6.log.info("update", {
716
+ objects: objects.length
717
+ }, {
718
+ F: __dxlog_file5,
719
+ L: 59,
720
+ S: void 0,
721
+ C: (f, a) => f(...a)
722
+ });
723
+ for (const object of objects) {
724
+ const content = object.content;
725
+ if (content instanceof import_types.TextV0Type) {
726
+ subscriptions.push((0, import_echo_db.getAutomergeObjectCore)(content).updates.on((0, import_async5.debounce)(() => subscription.update([
727
+ object
728
+ ]), 1e3)));
729
+ }
730
+ }
731
+ }
732
+ };
733
+ const query = triggerCtx.space.db.query(import_echo_db.Filter.or(filter.map(({ type, props }) => import_echo_db.Filter.typename(type, props))));
734
+ subscriptions.push(query.subscribe(delay ? (0, import_async5.debounce)(update, delay) : update));
735
+ ctx.onDispose(() => {
736
+ subscriptions.forEach((unsubscribe) => unsubscribe());
737
+ });
738
+ };
739
+ var __dxlog_file6 = "/home/runner/work/dxos/dxos/packages/core/functions/src/trigger/type/timer-trigger.ts";
740
+ var createTimerTrigger = async (ctx, triggerContext, spec, callback) => {
741
+ const task = new import_async6.DeferredTask(ctx, async () => {
742
+ await callback({});
743
+ });
744
+ let last = 0;
745
+ let run = 0;
746
+ const job = import_cron.CronJob.from({
747
+ cronTime: spec.cron,
748
+ runOnInit: false,
749
+ onTick: () => {
750
+ const now = Date.now();
751
+ const delta = last ? now - last : 0;
752
+ last = now;
753
+ run++;
754
+ import_log7.log.info("tick", {
755
+ space: triggerContext.space.key.truncate(),
756
+ count: run,
757
+ delta
758
+ }, {
759
+ F: __dxlog_file6,
760
+ L: 37,
761
+ S: void 0,
762
+ C: (f, a) => f(...a)
763
+ });
764
+ task.schedule();
765
+ }
766
+ });
767
+ job.start();
768
+ ctx.onDispose(() => job.stop());
769
+ };
770
+ var __dxlog_file7 = "/home/runner/work/dxos/dxos/packages/core/functions/src/trigger/type/webhook-trigger.ts";
771
+ var createWebhookTrigger = async (ctx, _, spec, callback) => {
772
+ const server = import_node_http.default.createServer(async (req, res) => {
773
+ if (req.method !== spec.method) {
774
+ res.statusCode = 405;
775
+ return res.end();
776
+ }
777
+ res.statusCode = await callback({});
778
+ res.end();
779
+ });
780
+ const port = await (0, import_get_port_please2.getPort)({
781
+ random: true
782
+ });
783
+ server.listen(port, () => {
784
+ import_log8.log.info("started webhook", {
785
+ port
786
+ }, {
787
+ F: __dxlog_file7,
788
+ L: 40,
789
+ S: void 0,
790
+ C: (f, a) => f(...a)
791
+ });
792
+ spec.port = port;
793
+ });
794
+ ctx.onDispose(() => {
795
+ server.close();
796
+ });
797
+ };
798
+ var __dxlog_file8 = "/home/runner/work/dxos/dxos/packages/core/functions/src/trigger/type/websocket-trigger.ts";
799
+ var createWebsocketTrigger = async (ctx, triggerCtx, spec, callback, options = {
800
+ retryDelay: 2,
801
+ maxAttempts: 5
802
+ }) => {
803
+ const { url, init } = spec;
804
+ let ws;
805
+ for (let attempt = 1; attempt <= options.maxAttempts; attempt++) {
806
+ const open = new import_async7.Trigger();
807
+ ws = new import_ws.default(url);
808
+ Object.assign(ws, {
809
+ onopen: () => {
810
+ import_log9.log.info("opened", {
811
+ url
812
+ }, {
813
+ F: __dxlog_file8,
814
+ L: 39,
815
+ S: void 0,
816
+ C: (f, a) => f(...a)
817
+ });
818
+ if (spec.init) {
819
+ ws.send(new TextEncoder().encode(JSON.stringify(init)));
820
+ }
821
+ open.wake(true);
822
+ },
823
+ onclose: (event) => {
824
+ import_log9.log.info("closed", {
825
+ url,
826
+ code: event.code
827
+ }, {
828
+ F: __dxlog_file8,
829
+ L: 48,
830
+ S: void 0,
831
+ C: (f, a) => f(...a)
832
+ });
833
+ if (event.code === 1006) {
834
+ setTimeout(async () => {
835
+ import_log9.log.info(`reconnecting in ${options.retryDelay}s...`, {
836
+ url
837
+ }, {
838
+ F: __dxlog_file8,
839
+ L: 53,
840
+ S: void 0,
841
+ C: (f, a) => f(...a)
842
+ });
843
+ await createWebsocketTrigger(ctx, triggerCtx, spec, callback, options);
844
+ }, options.retryDelay * 1e3);
845
+ }
846
+ open.wake(false);
847
+ },
848
+ onerror: (event) => {
849
+ import_log9.log.catch(event.error, {
850
+ url
851
+ }, {
852
+ F: __dxlog_file8,
853
+ L: 62,
854
+ S: void 0,
855
+ C: (f, a) => f(...a)
856
+ });
857
+ },
858
+ onmessage: async (event) => {
859
+ try {
860
+ import_log9.log.info("message", void 0, {
861
+ F: __dxlog_file8,
862
+ L: 67,
863
+ S: void 0,
864
+ C: (f, a) => f(...a)
865
+ });
866
+ const data = JSON.parse(new TextDecoder().decode(event.data));
867
+ await callback({
868
+ data
869
+ });
870
+ } catch (err) {
871
+ import_log9.log.catch(err, {
872
+ url
873
+ }, {
874
+ F: __dxlog_file8,
875
+ L: 71,
876
+ S: void 0,
877
+ C: (f, a) => f(...a)
878
+ });
879
+ }
880
+ }
881
+ });
882
+ const isOpen = await open.wait();
883
+ if (isOpen) {
884
+ break;
885
+ } else {
886
+ const wait = Math.pow(attempt, 2) * options.retryDelay;
887
+ if (attempt < options.maxAttempts) {
888
+ import_log9.log.warn(`failed to connect; trying again in ${wait}s`, {
889
+ attempt
890
+ }, {
891
+ F: __dxlog_file8,
892
+ L: 82,
893
+ S: void 0,
894
+ C: (f, a) => f(...a)
895
+ });
896
+ await (0, import_async7.sleep)(wait * 1e3);
897
+ }
898
+ }
899
+ }
900
+ ctx.onDispose(() => {
901
+ ws?.close();
902
+ });
903
+ };
904
+ var __dxlog_file9 = "/home/runner/work/dxos/dxos/packages/core/functions/src/trigger/trigger-registry.ts";
905
+ var triggerHandlers = {
906
+ subscription: createSubscriptionTrigger,
907
+ timer: createTimerTrigger,
908
+ webhook: createWebhookTrigger,
909
+ websocket: createWebsocketTrigger
910
+ };
911
+ var TriggerRegistry = class extends import_context4.Resource {
912
+ constructor(_client, _options) {
913
+ super();
914
+ this._client = _client;
915
+ this._options = _options;
916
+ this._triggersBySpaceKey = new import_util3.ComplexMap(import_keys2.PublicKey.hash);
917
+ this.registered = new import_async4.Event();
918
+ this.removed = new import_async4.Event();
919
+ }
920
+ getActiveTriggers(space) {
921
+ return this._getTriggers(space, (t) => t.activationCtx != null);
922
+ }
923
+ getInactiveTriggers(space) {
924
+ return this._getTriggers(space, (t) => t.activationCtx == null);
925
+ }
926
+ async activate(triggerCtx, trigger, callback) {
927
+ (0, import_log5.log)("activate", {
928
+ space: triggerCtx.space.key,
929
+ trigger
930
+ }, {
931
+ F: __dxlog_file9,
932
+ L: 74,
933
+ S: this,
934
+ C: (f, a) => f(...a)
935
+ });
936
+ const activationCtx = new import_context4.Context({
937
+ name: `trigger_${trigger.function}`
938
+ });
939
+ this._ctx.onDispose(() => activationCtx.dispose());
940
+ const registeredTrigger = this._triggersBySpaceKey.get(triggerCtx.space.key)?.find((reg) => reg.trigger.id === trigger.id);
941
+ (0, import_invariant2.invariant)(registeredTrigger, `Trigger is not registered: ${trigger.function}`, {
942
+ F: __dxlog_file9,
943
+ L: 80,
944
+ S: this,
945
+ A: [
946
+ "registeredTrigger",
947
+ "`Trigger is not registered: ${trigger.function}`"
948
+ ]
949
+ });
950
+ registeredTrigger.activationCtx = activationCtx;
951
+ try {
952
+ const options = this._options?.[trigger.spec.type];
953
+ await triggerHandlers[trigger.spec.type](activationCtx, triggerCtx, trigger.spec, callback, options);
954
+ } catch (err) {
955
+ delete registeredTrigger.activationCtx;
956
+ throw err;
957
+ }
958
+ }
959
+ /**
960
+ * Loads triggers from the manifest into the space.
961
+ */
962
+ async register(space, manifest) {
963
+ (0, import_log5.log)("register", {
964
+ space: space.key
965
+ }, {
966
+ F: __dxlog_file9,
967
+ L: 96,
968
+ S: this,
969
+ C: (f, a) => f(...a)
970
+ });
971
+ if (!manifest.triggers?.length) {
972
+ return;
973
+ }
974
+ if (!space.db.graph.runtimeSchemaRegistry.hasSchema(import_chunk_KTLM3JNV.FunctionTrigger)) {
975
+ space.db.graph.runtimeSchemaRegistry.registerSchema(import_chunk_KTLM3JNV.FunctionTrigger);
976
+ }
977
+ const { objects: existing } = await space.db.query(import_echo2.Filter.schema(import_chunk_KTLM3JNV.FunctionTrigger)).run();
978
+ const { added } = (0, import_util3.diff)(existing, manifest.triggers, (a, b) => {
979
+ const keys = b[import_echo_schema.ECHO_ATTR_META]?.keys ?? [
980
+ (0, import_echo_schema.foreignKey)("manifest", [
981
+ b.function,
982
+ b.spec.type
983
+ ].join("-"))
984
+ ];
985
+ return (0, import_util3.intersection)((0, import_echo2.getMeta)(a)?.keys ?? [], keys, import_echo_schema.foreignKeyEquals).length > 0;
986
+ });
987
+ added.forEach((trigger) => {
988
+ const { meta, object } = (0, import_echo_schema.splitMeta)(trigger);
989
+ space.db.add((0, import_echo2.create)(import_chunk_KTLM3JNV.FunctionTrigger, object, meta));
990
+ });
991
+ }
992
+ async _open() {
993
+ import_log5.log.info("open...", void 0, {
994
+ F: __dxlog_file9,
995
+ L: 121,
996
+ S: this,
997
+ C: (f, a) => f(...a)
998
+ });
999
+ const spaceListSubscription = this._client.spaces.subscribe(async (spaces) => {
1000
+ for (const space of spaces) {
1001
+ if (this._triggersBySpaceKey.has(space.key)) {
1002
+ continue;
1003
+ }
1004
+ const registered = [];
1005
+ this._triggersBySpaceKey.set(space.key, registered);
1006
+ await space.waitUntilReady();
1007
+ if (this._ctx.disposed) {
1008
+ break;
1009
+ }
1010
+ this._ctx.onDispose(space.db.query(import_echo2.Filter.schema(import_chunk_KTLM3JNV.FunctionTrigger)).subscribe(async (triggers) => {
1011
+ import_log5.log.info("update", {
1012
+ space: space.key,
1013
+ triggers: triggers.objects.length
1014
+ }, {
1015
+ F: __dxlog_file9,
1016
+ L: 138,
1017
+ S: this,
1018
+ C: (f, a) => f(...a)
1019
+ });
1020
+ await this._handleRemovedTriggers(space, triggers.objects, registered);
1021
+ this._handleNewTriggers(space, triggers.objects, registered);
1022
+ }));
1023
+ }
1024
+ });
1025
+ this._ctx.onDispose(() => spaceListSubscription.unsubscribe());
1026
+ }
1027
+ async _close(_) {
1028
+ import_log5.log.info("close...", void 0, {
1029
+ F: __dxlog_file9,
1030
+ L: 150,
1031
+ S: this,
1032
+ C: (f, a) => f(...a)
1033
+ });
1034
+ this._triggersBySpaceKey.clear();
1035
+ }
1036
+ _handleNewTriggers(space, allTriggers, registered) {
1037
+ const newTriggers = allTriggers.filter((candidate) => {
1038
+ return registered.find((reg) => reg.trigger.id === candidate.id) == null;
1039
+ });
1040
+ if (newTriggers.length > 0) {
1041
+ const newRegisteredTriggers = newTriggers.map((trigger) => ({
1042
+ trigger
1043
+ }));
1044
+ registered.push(...newRegisteredTriggers);
1045
+ import_log5.log.info("added", () => ({
1046
+ spaceKey: space.key,
1047
+ triggers: newTriggers.map((trigger) => trigger.function)
1048
+ }), {
1049
+ F: __dxlog_file9,
1050
+ L: 162,
519
1051
  S: this,
520
1052
  C: (f, a) => f(...a)
521
1053
  });
1054
+ this.registered.emit({
1055
+ space,
1056
+ triggers: newTriggers
1057
+ });
522
1058
  }
523
1059
  }
1060
+ async _handleRemovedTriggers(space, allTriggers, registered) {
1061
+ const removed = [];
1062
+ for (let i = registered.length - 1; i >= 0; i--) {
1063
+ const wasRemoved = allTriggers.find((trigger) => trigger.id === registered[i].trigger.id) == null;
1064
+ if (wasRemoved) {
1065
+ if (removed.length) {
1066
+ import_log5.log.info("removed", () => ({
1067
+ spaceKey: space.key,
1068
+ triggers: removed.map((trigger) => trigger.function)
1069
+ }), {
1070
+ F: __dxlog_file9,
1071
+ L: 181,
1072
+ S: this,
1073
+ C: (f, a) => f(...a)
1074
+ });
1075
+ }
1076
+ const unregistered = registered.splice(i, 1)[0];
1077
+ await unregistered.activationCtx?.dispose();
1078
+ removed.push(unregistered.trigger);
1079
+ }
1080
+ }
1081
+ if (removed.length > 0) {
1082
+ this.removed.emit({
1083
+ space,
1084
+ triggers: removed
1085
+ });
1086
+ }
1087
+ }
1088
+ _getTriggers(space, predicate) {
1089
+ const allSpaceTriggers = this._triggersBySpaceKey.get(space.key) ?? [];
1090
+ return allSpaceTriggers.filter(predicate).map((trigger) => trigger.trigger);
1091
+ }
524
1092
  };
525
1093
  // Annotate the CommonJS export names for ESM import in node:
526
1094
  0 && (module.exports = {
527
1095
  DevServer,
1096
+ FUNCTION_SCHEMA,
1097
+ FunctionDef,
1098
+ FunctionManifestSchema,
1099
+ FunctionRegistry,
1100
+ FunctionTrigger,
528
1101
  Scheduler,
1102
+ TriggerRegistry,
529
1103
  subscriptionHandler
530
1104
  });
531
1105
  //# sourceMappingURL=index.cjs.map