@dxos/functions 0.8.4-main.3f58842 → 0.8.4-main.548089c

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 (144) hide show
  1. package/dist/lib/browser/index.mjs +663 -363
  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 +663 -363
  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/errors.d.ts +81 -28
  8. package/dist/types/src/errors.d.ts.map +1 -1
  9. package/dist/types/src/example/fib.d.ts +7 -0
  10. package/dist/types/src/example/fib.d.ts.map +1 -0
  11. package/dist/types/src/example/forex-effect.d.ts +3 -0
  12. package/dist/types/src/example/forex-effect.d.ts.map +1 -0
  13. package/dist/types/src/example/index.d.ts +12 -0
  14. package/dist/types/src/example/index.d.ts.map +1 -0
  15. package/dist/types/src/example/reply.d.ts +3 -0
  16. package/dist/types/src/example/reply.d.ts.map +1 -0
  17. package/dist/types/src/example/sleep.d.ts +5 -0
  18. package/dist/types/src/example/sleep.d.ts.map +1 -0
  19. package/dist/types/src/handler.d.ts +56 -36
  20. package/dist/types/src/handler.d.ts.map +1 -1
  21. package/dist/types/src/index.d.ts +3 -5
  22. package/dist/types/src/index.d.ts.map +1 -1
  23. package/dist/types/src/services/credentials.d.ts +20 -3
  24. package/dist/types/src/services/credentials.d.ts.map +1 -1
  25. package/dist/types/src/services/event-logger.d.ts +80 -30
  26. package/dist/types/src/services/event-logger.d.ts.map +1 -1
  27. package/dist/types/src/services/function-invocation-service.d.ts +11 -0
  28. package/dist/types/src/services/function-invocation-service.d.ts.map +1 -0
  29. package/dist/types/src/services/index.d.ts +6 -5
  30. package/dist/types/src/services/index.d.ts.map +1 -1
  31. package/dist/types/src/services/queues.d.ts +23 -6
  32. package/dist/types/src/services/queues.d.ts.map +1 -1
  33. package/dist/types/src/services/tracing.d.ts +35 -6
  34. package/dist/types/src/services/tracing.d.ts.map +1 -1
  35. package/dist/types/src/types/Function.d.ts +52 -0
  36. package/dist/types/src/types/Function.d.ts.map +1 -0
  37. package/dist/types/src/types/Script.d.ts +28 -0
  38. package/dist/types/src/types/Script.d.ts.map +1 -0
  39. package/dist/types/src/types/Trigger.d.ts +139 -0
  40. package/dist/types/src/types/Trigger.d.ts.map +1 -0
  41. package/dist/types/src/types/TriggerEvent.d.ts +44 -0
  42. package/dist/types/src/types/TriggerEvent.d.ts.map +1 -0
  43. package/dist/types/src/types/index.d.ts +5 -0
  44. package/dist/types/src/types/index.d.ts.map +1 -0
  45. package/dist/types/src/url.d.ts +7 -12
  46. package/dist/types/src/url.d.ts.map +1 -1
  47. package/dist/types/tsconfig.tsbuildinfo +1 -1
  48. package/package.json +17 -68
  49. package/src/errors.ts +13 -5
  50. package/src/example/fib.ts +32 -0
  51. package/src/example/forex-effect.ts +40 -0
  52. package/src/example/index.ts +13 -0
  53. package/src/example/reply.ts +21 -0
  54. package/src/example/sleep.ts +24 -0
  55. package/src/handler.ts +145 -64
  56. package/src/index.ts +3 -7
  57. package/src/services/credentials.ts +85 -3
  58. package/src/services/event-logger.ts +77 -37
  59. package/src/services/function-invocation-service.ts +20 -0
  60. package/src/services/index.ts +7 -5
  61. package/src/services/queues.ts +39 -10
  62. package/src/services/tracing.ts +82 -16
  63. package/src/types/Function.ts +56 -0
  64. package/src/types/Script.ts +33 -0
  65. package/src/types/Trigger.ts +139 -0
  66. package/src/types/TriggerEvent.ts +62 -0
  67. package/src/types/index.ts +8 -0
  68. package/src/url.ts +12 -33
  69. package/dist/lib/browser/bundler/index.mjs +0 -247
  70. package/dist/lib/browser/bundler/index.mjs.map +0 -7
  71. package/dist/lib/browser/chunk-3NGCSUEW.mjs +0 -328
  72. package/dist/lib/browser/chunk-3NGCSUEW.mjs.map +0 -7
  73. package/dist/lib/browser/edge/index.mjs +0 -69
  74. package/dist/lib/browser/edge/index.mjs.map +0 -7
  75. package/dist/lib/browser/testing/index.mjs +0 -91
  76. package/dist/lib/browser/testing/index.mjs.map +0 -7
  77. package/dist/lib/node-esm/bundler/index.mjs +0 -249
  78. package/dist/lib/node-esm/bundler/index.mjs.map +0 -7
  79. package/dist/lib/node-esm/chunk-FJ2MU7TL.mjs +0 -330
  80. package/dist/lib/node-esm/chunk-FJ2MU7TL.mjs.map +0 -7
  81. package/dist/lib/node-esm/edge/index.mjs +0 -71
  82. package/dist/lib/node-esm/edge/index.mjs.map +0 -7
  83. package/dist/lib/node-esm/testing/index.mjs +0 -92
  84. package/dist/lib/node-esm/testing/index.mjs.map +0 -7
  85. package/dist/types/src/bundler/bundler.d.ts +0 -50
  86. package/dist/types/src/bundler/bundler.d.ts.map +0 -1
  87. package/dist/types/src/bundler/bundler.test.d.ts +0 -2
  88. package/dist/types/src/bundler/bundler.test.d.ts.map +0 -1
  89. package/dist/types/src/bundler/index.d.ts +0 -2
  90. package/dist/types/src/bundler/index.d.ts.map +0 -1
  91. package/dist/types/src/edge/functions.d.ts +0 -16
  92. package/dist/types/src/edge/functions.d.ts.map +0 -1
  93. package/dist/types/src/edge/index.d.ts +0 -2
  94. package/dist/types/src/edge/index.d.ts.map +0 -1
  95. package/dist/types/src/executor/executor.d.ts +0 -8
  96. package/dist/types/src/executor/executor.d.ts.map +0 -1
  97. package/dist/types/src/executor/index.d.ts +0 -2
  98. package/dist/types/src/executor/index.d.ts.map +0 -1
  99. package/dist/types/src/schema.d.ts +0 -38
  100. package/dist/types/src/schema.d.ts.map +0 -1
  101. package/dist/types/src/services/database.d.ts +0 -29
  102. package/dist/types/src/services/database.d.ts.map +0 -1
  103. package/dist/types/src/services/function-call-service.d.ts +0 -16
  104. package/dist/types/src/services/function-call-service.d.ts.map +0 -1
  105. package/dist/types/src/services/service-container.d.ts +0 -56
  106. package/dist/types/src/services/service-container.d.ts.map +0 -1
  107. package/dist/types/src/services/service-registry.d.ts +0 -29
  108. package/dist/types/src/services/service-registry.d.ts.map +0 -1
  109. package/dist/types/src/services/service-registry.test.d.ts +0 -2
  110. package/dist/types/src/services/service-registry.test.d.ts.map +0 -1
  111. package/dist/types/src/testing/index.d.ts +0 -3
  112. package/dist/types/src/testing/index.d.ts.map +0 -1
  113. package/dist/types/src/testing/layer.d.ts +0 -10
  114. package/dist/types/src/testing/layer.d.ts.map +0 -1
  115. package/dist/types/src/testing/logger.d.ts +0 -5
  116. package/dist/types/src/testing/logger.d.ts.map +0 -1
  117. package/dist/types/src/testing/services.d.ts +0 -70
  118. package/dist/types/src/testing/services.d.ts.map +0 -1
  119. package/dist/types/src/trace.d.ts +0 -124
  120. package/dist/types/src/trace.d.ts.map +0 -1
  121. package/dist/types/src/translations.d.ts +0 -12
  122. package/dist/types/src/translations.d.ts.map +0 -1
  123. package/dist/types/src/types.d.ts +0 -411
  124. package/dist/types/src/types.d.ts.map +0 -1
  125. package/src/bundler/bundler.test.ts +0 -59
  126. package/src/bundler/bundler.ts +0 -292
  127. package/src/bundler/index.ts +0 -5
  128. package/src/edge/functions.ts +0 -64
  129. package/src/edge/index.ts +0 -9
  130. package/src/executor/executor.ts +0 -54
  131. package/src/executor/index.ts +0 -5
  132. package/src/schema.ts +0 -57
  133. package/src/services/database.ts +0 -70
  134. package/src/services/function-call-service.ts +0 -64
  135. package/src/services/service-container.ts +0 -113
  136. package/src/services/service-registry.test.ts +0 -42
  137. package/src/services/service-registry.ts +0 -56
  138. package/src/testing/index.ts +0 -6
  139. package/src/testing/layer.ts +0 -31
  140. package/src/testing/logger.ts +0 -16
  141. package/src/testing/services.ts +0 -168
  142. package/src/trace.ts +0 -180
  143. package/src/translations.ts +0 -20
  144. package/src/types.ts +0 -211
@@ -1,98 +1,178 @@
1
1
  import { createRequire } from 'node:module';const require = createRequire(import.meta.url);
2
- import {
3
- ConfiguredCredentialsService,
4
- ContextQueueService,
5
- CredentialsService,
6
- DatabaseService,
7
- EventLogger,
8
- FunctionCallService,
9
- QueueService,
10
- SERVICE_TAGS,
11
- ServiceContainer,
12
- TracingService,
13
- createDefectLogger,
14
- createEventLogger,
15
- logCustomEvent
16
- } from "./chunk-FJ2MU7TL.mjs";
2
+ var __defProp = Object.defineProperty;
3
+ var __export = (target, all) => {
4
+ for (var name in all)
5
+ __defProp(target, name, { get: all[name], enumerable: true });
6
+ };
17
7
 
18
- // src/handler.ts
19
- import { Schema } from "effect";
20
- var defineFunction = ({ name, description, inputSchema, outputSchema = Schema.Any, handler }) => {
21
- if (!Schema.isSchema(inputSchema)) {
22
- throw new Error("Input schema must be a valid schema");
8
+ // src/errors.ts
9
+ import { BaseError } from "@dxos/errors";
10
+ var ServiceNotAvailableError = class extends BaseError.extend("SERVICE_NOT_AVAILABLE", "Service not available") {
11
+ constructor(service, options) {
12
+ super({
13
+ context: {
14
+ service
15
+ },
16
+ ...options
17
+ });
23
18
  }
24
- if (typeof handler !== "function") {
25
- throw new Error("Handler must be a function");
19
+ };
20
+ var FunctionNotFoundError = class extends BaseError.extend("FUNCTION_NOT_FOUND", "Function not found") {
21
+ constructor(functionKey, options) {
22
+ super({
23
+ context: {
24
+ function: functionKey
25
+ },
26
+ ...options
27
+ });
26
28
  }
27
- return {
28
- name,
29
- description,
30
- inputSchema,
31
- outputSchema,
32
- handler
33
- };
29
+ };
30
+ var FunctionError = class extends BaseError.extend("FUNCTION_ERROR", "Function invocation error") {
31
+ };
32
+ var TriggerStateNotFoundError = class extends BaseError.extend("TRIGGER_STATE_NOT_FOUND", "Trigger state not found") {
34
33
  };
35
34
 
36
- // src/schema.ts
37
- import { Schema as Schema2 } from "effect";
38
- import { Type } from "@dxos/echo";
39
- import { JsonSchemaType, LabelAnnotation, Ref } from "@dxos/echo-schema";
40
- import { DataType } from "@dxos/schema";
41
- var ScriptType = Schema2.Struct({
42
- name: Schema2.optional(Schema2.String),
43
- description: Schema2.optional(Schema2.String),
35
+ // src/example/fib.ts
36
+ import * as Effect2 from "effect/Effect";
37
+ import * as Schema6 from "effect/Schema";
38
+
39
+ // src/handler.ts
40
+ import * as Effect from "effect/Effect";
41
+ import * as Schema5 from "effect/Schema";
42
+ import { Obj as Obj5, Type as Type5 } from "@dxos/echo";
43
+ import { assertArgument } from "@dxos/invariant";
44
+
45
+ // src/types/Function.ts
46
+ var Function_exports = {};
47
+ __export(Function_exports, {
48
+ Function: () => Function,
49
+ make: () => make2
50
+ });
51
+ import * as Schema2 from "effect/Schema";
52
+ import { Obj as Obj2, Type as Type2 } from "@dxos/echo";
53
+ import { JsonSchemaType, LabelAnnotation as LabelAnnotation2, Ref as Ref2 } from "@dxos/echo/internal";
54
+
55
+ // src/types/Script.ts
56
+ var Script_exports = {};
57
+ __export(Script_exports, {
58
+ Script: () => Script,
59
+ make: () => make
60
+ });
61
+ import * as Schema from "effect/Schema";
62
+ import { Obj, Ref, Type } from "@dxos/echo";
63
+ import { FormAnnotation, LabelAnnotation } from "@dxos/echo/internal";
64
+ import { Text } from "@dxos/schema";
65
+ var Script = Schema.Struct({
66
+ name: Schema.String.pipe(Schema.optional),
67
+ description: Schema.String.pipe(Schema.optional),
44
68
  // TODO(burdon): Change to hash of deployed content.
45
69
  // Whether source has changed since last deploy.
46
- changed: Schema2.optional(Schema2.Boolean),
47
- source: Ref(DataType.Text)
70
+ changed: Schema.Boolean.pipe(FormAnnotation.set(false), Schema.optional),
71
+ source: Type.Ref(Text.Text).pipe(FormAnnotation.set(false))
48
72
  }).pipe(Type.Obj({
49
73
  typename: "dxos.org/type/Script",
50
74
  version: "0.1.0"
51
75
  }), LabelAnnotation.set([
52
76
  "name"
53
77
  ]));
54
- var FunctionType = Schema2.Struct({
78
+ var make = ({ source = "", ...props } = {}) => Obj.make(Script, {
79
+ ...props,
80
+ source: Ref.make(Text.make(source))
81
+ });
82
+
83
+ // src/types/Function.ts
84
+ var Function = Schema2.Struct({
85
+ /**
86
+ * Global registry ID.
87
+ * NOTE: The `key` property refers to the original registry entry.
88
+ */
89
+ // TODO(burdon): Create Format type for DXN-like ids, such as this and schema type.
90
+ // TODO(dmaretskyi): Consider making it part of ECHO meta.
91
+ // TODO(dmaretskyi): Make required.
92
+ key: Schema2.optional(Schema2.String).annotations({
93
+ description: "Unique registration key for the blueprint"
94
+ }),
55
95
  // TODO(burdon): Rename to id/uri?
56
96
  name: Schema2.NonEmptyString,
57
97
  version: Schema2.String,
58
98
  description: Schema2.optional(Schema2.String),
99
+ /**
100
+ * ISO date string of the last deployment.
101
+ */
102
+ updated: Schema2.optional(Schema2.String),
59
103
  // Reference to a source script if it exists within ECHO.
60
104
  // TODO(burdon): Don't ref ScriptType directly (core).
61
- source: Schema2.optional(Ref(ScriptType)),
105
+ source: Schema2.optional(Ref2(Script)),
62
106
  inputSchema: Schema2.optional(JsonSchemaType),
63
107
  outputSchema: Schema2.optional(JsonSchemaType),
64
108
  // Local binding to a function name.
65
109
  binding: Schema2.optional(Schema2.String)
66
- }).pipe(Type.Obj({
110
+ }).pipe(Type2.Obj({
67
111
  typename: "dxos.org/type/Function",
68
112
  version: "0.1.0"
69
- }), LabelAnnotation.set([
113
+ }), LabelAnnotation2.set([
70
114
  "name"
71
115
  ]));
116
+ var make2 = (props) => Obj2.make(Function, props);
72
117
 
73
- // src/trace.ts
74
- import { Schema as Schema4 } from "effect";
75
- import { Type as Type2 } from "@dxos/echo";
76
- import { Queue } from "@dxos/echo-db";
77
- import { ObjectId } from "@dxos/echo-schema";
78
- import { log } from "@dxos/log";
79
-
80
- // src/types.ts
81
- import { Schema as Schema3, SchemaAST } from "effect";
82
- import { Expando, OptionsAnnotationId, TypedObject, Ref as Ref2, RawObject } from "@dxos/echo-schema";
118
+ // src/types/Trigger.ts
119
+ var Trigger_exports = {};
120
+ __export(Trigger_exports, {
121
+ EmailSpec: () => EmailSpec,
122
+ Kinds: () => Kinds,
123
+ QueueSpec: () => QueueSpec,
124
+ Spec: () => Spec,
125
+ SubscriptionSpec: () => SubscriptionSpec,
126
+ TimerSpec: () => TimerSpec,
127
+ Trigger: () => Trigger,
128
+ WebhookSpec: () => WebhookSpec,
129
+ make: () => make3
130
+ });
131
+ import * as Schema3 from "effect/Schema";
132
+ import * as SchemaAST from "effect/SchemaAST";
133
+ import { Obj as Obj3, QueryAST, Type as Type3 } from "@dxos/echo";
134
+ import { Expando, OptionsAnnotationId, Ref as Ref3 } from "@dxos/echo/internal";
83
135
  import { DXN } from "@dxos/keys";
84
- var TriggerKind = /* @__PURE__ */ function(TriggerKind2) {
85
- TriggerKind2["Timer"] = "timer";
86
- TriggerKind2["Webhook"] = "webhook";
87
- TriggerKind2["Subscription"] = "subscription";
88
- TriggerKind2["Email"] = "email";
89
- TriggerKind2["Queue"] = "queue";
90
- return TriggerKind2;
91
- }({});
136
+ var Kinds = [
137
+ "email",
138
+ "queue",
139
+ "subscription",
140
+ "timer",
141
+ "webhook"
142
+ ];
92
143
  var kindLiteralAnnotations = {
93
144
  title: "Kind"
94
145
  };
95
- var TimerTriggerSchema = Schema3.Struct({
146
+ var EmailSpec = Schema3.Struct({
147
+ kind: Schema3.Literal("email").annotations(kindLiteralAnnotations)
148
+ }).pipe(Schema3.mutable);
149
+ var QueueSpec = Schema3.Struct({
150
+ kind: Schema3.Literal("queue").annotations(kindLiteralAnnotations),
151
+ // TODO(dmaretskyi): Change to a reference.
152
+ queue: DXN.Schema
153
+ }).pipe(Schema3.mutable);
154
+ var SubscriptionSpec = Schema3.Struct({
155
+ kind: Schema3.Literal("subscription").annotations(kindLiteralAnnotations),
156
+ query: Schema3.Struct({
157
+ raw: Schema3.optional(Schema3.String.annotations({
158
+ title: "Query"
159
+ })),
160
+ ast: QueryAST.Query
161
+ }).pipe(Schema3.mutable),
162
+ options: Schema3.optional(Schema3.Struct({
163
+ // Watch changes to object (not just creation).
164
+ deep: Schema3.optional(Schema3.Boolean.annotations({
165
+ title: "Nested"
166
+ })),
167
+ // Debounce changes (delay in ms).
168
+ delay: Schema3.optional(Schema3.Number.annotations({
169
+ title: "Delay"
170
+ }))
171
+ }).annotations({
172
+ title: "Options"
173
+ }))
174
+ }).pipe(Schema3.mutable);
175
+ var TimerSpec = Schema3.Struct({
96
176
  kind: Schema3.Literal("timer").annotations(kindLiteralAnnotations),
97
177
  cron: Schema3.String.annotations({
98
178
  title: "Cron",
@@ -101,14 +181,7 @@ var TimerTriggerSchema = Schema3.Struct({
101
181
  ]
102
182
  })
103
183
  }).pipe(Schema3.mutable);
104
- var EmailTriggerSchema = Schema3.Struct({
105
- kind: Schema3.Literal("email").annotations(kindLiteralAnnotations)
106
- }).pipe(Schema3.mutable);
107
- var QueueTriggerSchema = Schema3.Struct({
108
- kind: Schema3.Literal("queue").annotations(kindLiteralAnnotations),
109
- queue: DXN.Schema
110
- }).pipe(Schema3.mutable);
111
- var WebhookTriggerSchema = Schema3.Struct({
184
+ var WebhookSpec = Schema3.Struct({
112
185
  kind: Schema3.Literal("webhook").annotations(kindLiteralAnnotations),
113
186
  method: Schema3.optional(Schema3.String.annotations({
114
187
  title: "Method",
@@ -121,71 +194,15 @@ var WebhookTriggerSchema = Schema3.Struct({
121
194
  title: "Port"
122
195
  }))
123
196
  }).pipe(Schema3.mutable);
124
- var QuerySchema = Schema3.Struct({
125
- type: Schema3.optional(Schema3.String.annotations({
126
- title: "Type"
127
- })),
128
- props: Schema3.optional(Schema3.Record({
129
- key: Schema3.String,
130
- value: Schema3.Any
131
- }))
132
- }).annotations({
133
- title: "Query"
134
- });
135
- var SubscriptionTriggerSchema = Schema3.Struct({
136
- kind: Schema3.Literal("subscription").annotations(kindLiteralAnnotations),
137
- // TODO(burdon): Define query DSL (from ECHO). Reconcile with Table.Query.
138
- filter: QuerySchema,
139
- options: Schema3.optional(Schema3.Struct({
140
- // Watch changes to object (not just creation).
141
- deep: Schema3.optional(Schema3.Boolean.annotations({
142
- title: "Nested"
143
- })),
144
- // Debounce changes (delay in ms).
145
- delay: Schema3.optional(Schema3.Number.annotations({
146
- title: "Delay"
147
- }))
148
- }).annotations({
149
- title: "Options"
150
- }))
151
- }).pipe(Schema3.mutable);
152
- var TriggerSchema = Schema3.Union(TimerTriggerSchema, WebhookTriggerSchema, SubscriptionTriggerSchema, EmailTriggerSchema, QueueTriggerSchema).annotations({
197
+ var Spec = Schema3.Union(EmailSpec, QueueSpec, SubscriptionSpec, TimerSpec, WebhookSpec).annotations({
153
198
  title: "Trigger"
154
199
  });
155
- var EmailTriggerOutput = Schema3.mutable(Schema3.Struct({
156
- from: Schema3.String,
157
- to: Schema3.String,
158
- subject: Schema3.String,
159
- created: Schema3.String,
160
- body: Schema3.String
161
- }));
162
- var WebhookTriggerOutput = Schema3.mutable(Schema3.Struct({
163
- url: Schema3.String,
164
- method: Schema3.Literal("GET", "POST"),
165
- headers: Schema3.Record({
166
- key: Schema3.String,
167
- value: Schema3.String
168
- }),
169
- bodyText: Schema3.String
170
- }));
171
- var QueueTriggerOutput = Schema3.mutable(Schema3.Struct({
172
- queue: DXN.Schema,
173
- item: Schema3.Any,
174
- cursor: Schema3.String
175
- }));
176
- var SubscriptionTriggerOutput = Schema3.mutable(Schema3.Struct({
177
- type: Schema3.String,
178
- changedObjectId: Schema3.String
179
- }));
180
- var TimerTriggerOutput = Schema3.mutable(Schema3.Struct({
181
- tick: Schema3.Number
182
- }));
183
- var FunctionTriggerSchema = Schema3.Struct({
200
+ var Trigger_ = Schema3.Struct({
184
201
  /**
185
202
  * Function or workflow to invoke.
186
203
  */
187
204
  // TODO(dmaretskyi): Can be a Ref(FunctionType) or Ref(ComputeGraphType).
188
- function: Schema3.optional(Ref2(Expando).annotations({
205
+ function: Schema3.optional(Ref3(Expando).annotations({
189
206
  title: "Function"
190
207
  })),
191
208
  /**
@@ -199,7 +216,7 @@ var FunctionTriggerSchema = Schema3.Struct({
199
216
  enabled: Schema3.optional(Schema3.Boolean.annotations({
200
217
  title: "Enabled"
201
218
  })),
202
- spec: Schema3.optional(TriggerSchema),
219
+ spec: Schema3.optional(Spec),
203
220
  /**
204
221
  * Passed as the input data to the function.
205
222
  * Must match the function's input schema.
@@ -215,290 +232,573 @@ var FunctionTriggerSchema = Schema3.Struct({
215
232
  key: Schema3.String,
216
233
  value: Schema3.Any
217
234
  })))
218
- });
219
- var FunctionTrigger = class extends TypedObject({
220
- typename: "dxos.org/type/FunctionTrigger",
221
- version: "0.2.0"
222
- })(FunctionTriggerSchema.fields) {
223
- };
224
- var FunctionManifestSchema = Schema3.Struct({
225
- functions: Schema3.optional(Schema3.mutable(Schema3.Array(RawObject(FunctionType)))),
226
- triggers: Schema3.optional(Schema3.mutable(Schema3.Array(RawObject(FunctionTrigger))))
227
- });
228
- var FUNCTION_TYPES = [
229
- FunctionType,
230
- FunctionTrigger
231
- ];
235
+ }).pipe(Type3.Obj({
236
+ typename: "dxos.org/type/Trigger",
237
+ version: "0.1.0"
238
+ }));
239
+ var Trigger = Trigger_;
240
+ var make3 = (props) => Obj3.make(Trigger, props);
232
241
 
233
- // src/trace.ts
234
- var __dxlog_file = "/__w/dxos/dxos/packages/core/functions/src/trace.ts";
235
- var InvocationOutcome = /* @__PURE__ */ function(InvocationOutcome2) {
236
- InvocationOutcome2["SUCCESS"] = "success";
237
- InvocationOutcome2["FAILURE"] = "failure";
238
- InvocationOutcome2["PENDING"] = "pending";
239
- return InvocationOutcome2;
240
- }({});
241
- var InvocationTraceEventType = /* @__PURE__ */ function(InvocationTraceEventType2) {
242
- InvocationTraceEventType2["START"] = "start";
243
- InvocationTraceEventType2["END"] = "end";
244
- return InvocationTraceEventType2;
245
- }({});
246
- var TraceEventException = Schema4.Struct({
247
- timestampMs: Schema4.Number,
248
- message: Schema4.String,
249
- name: Schema4.String,
250
- stack: Schema4.optional(Schema4.String)
242
+ // src/types/TriggerEvent.ts
243
+ var TriggerEvent_exports = {};
244
+ __export(TriggerEvent_exports, {
245
+ EmailEvent: () => EmailEvent,
246
+ QueueEvent: () => QueueEvent,
247
+ SubscriptionEvent: () => SubscriptionEvent,
248
+ TimerEvent: () => TimerEvent,
249
+ WebhookEvent: () => WebhookEvent
251
250
  });
252
- var InvocationTraceStartEvent = Schema4.Struct({
253
- /**
254
- * Queue message id.
255
- */
256
- id: ObjectId,
257
- type: Schema4.Literal("start"),
258
- /**
259
- * Invocation id, the same for invocation start and end events.
260
- */
261
- invocationId: ObjectId,
262
- /**
263
- * Event generation time.
264
- */
265
- timestampMs: Schema4.Number,
266
- /**
267
- * Data passed to function / workflow as an argument.
268
- */
269
- // TODO(burdon): Input schema?
270
- input: Schema4.Object,
271
- /**
272
- * Queue for function/workflow invocation events.
273
- */
274
- invocationTraceQueue: Type2.Ref(Queue),
275
- /**
276
- * DXN of the invoked function/workflow.
277
- */
278
- invocationTarget: Type2.Ref(Type2.Expando),
279
- /**
280
- * Present for automatic invocations.
281
- */
282
- trigger: Schema4.optional(Type2.Ref(FunctionTrigger))
283
- }).pipe(Type2.Obj({
284
- typename: "dxos.org/type/InvocationTraceStart",
285
- version: "0.1.0"
251
+ import * as Schema4 from "effect/Schema";
252
+ import { DXN as DXN2, Obj as Obj4, Type as Type4 } from "@dxos/echo";
253
+ var EmailEvent = Schema4.mutable(Schema4.Struct({
254
+ from: Schema4.String,
255
+ to: Schema4.String,
256
+ subject: Schema4.String,
257
+ created: Schema4.String,
258
+ body: Schema4.String
286
259
  }));
287
- var InvocationTraceEndEvent = Schema4.Struct({
260
+ var QueueEvent = Schema4.mutable(Schema4.Struct({
261
+ queue: DXN2.Schema,
262
+ item: Schema4.Any,
263
+ cursor: Schema4.String
264
+ }));
265
+ var SubscriptionEvent = Schema4.Struct({
288
266
  /**
289
- * Trace event id.
267
+ * Type of the mutation.
290
268
  */
291
- id: ObjectId,
292
- type: Schema4.Literal("end"),
269
+ // TODO(dmaretskyi): Specify enum.
270
+ type: Schema4.String,
293
271
  /**
294
- * Invocation id, will be the same for invocation start and end.
272
+ * Reference to the object that was changed or created.
295
273
  */
296
- invocationId: ObjectId,
274
+ subject: Type4.Ref(Obj4.Any),
297
275
  /**
298
- * Event generation time.
276
+ * @deprecated
299
277
  */
300
- // TODO(burdon): Remove ms suffix.
301
- timestampMs: Schema4.Number,
302
- outcome: Schema4.Enums(InvocationOutcome),
303
- exception: Schema4.optional(TraceEventException)
304
- }).pipe(Type2.Obj({
305
- typename: "dxos.org/type/InvocationTraceEnd",
306
- version: "0.1.0"
278
+ changedObjectId: Schema4.optional(Schema4.String)
279
+ }).pipe(Schema4.mutable);
280
+ var TimerEvent = Schema4.mutable(Schema4.Struct({
281
+ tick: Schema4.Number
307
282
  }));
308
- var TraceEventLog = Schema4.Struct({
309
- timestampMs: Schema4.Number,
310
- level: Schema4.String,
311
- message: Schema4.String,
312
- context: Schema4.optional(Schema4.Object)
313
- });
314
- var TraceEvent = Schema4.Struct({
315
- id: ObjectId,
316
- // TODO(burdon): Need enum/numeric result (not string).
317
- outcome: Schema4.String,
318
- truncated: Schema4.Boolean,
319
- /**
320
- * Time when the event was persisted.
321
- */
322
- ingestionTimestampMs: Schema4.Number,
323
- logs: Schema4.Array(TraceEventLog),
324
- exceptions: Schema4.Array(TraceEventException)
325
- }).pipe(Type2.Obj({
326
- typename: "dxos.org/type/TraceEvent",
327
- version: "0.1.0"
283
+ var WebhookEvent = Schema4.mutable(Schema4.Struct({
284
+ url: Schema4.String,
285
+ method: Schema4.Literal("GET", "POST"),
286
+ headers: Schema4.Record({
287
+ key: Schema4.String,
288
+ value: Schema4.String
289
+ }),
290
+ bodyText: Schema4.String
328
291
  }));
329
- var createInvocationSpans = (items) => {
330
- if (!items) {
331
- return [];
332
- }
333
- const eventsByInvocationId = /* @__PURE__ */ new Map();
334
- for (const event of items) {
335
- if (!("invocationId" in event)) {
336
- continue;
337
- }
338
- const invocationId = event.invocationId;
339
- const entry = eventsByInvocationId.get(invocationId) || {
340
- start: void 0,
341
- end: void 0
342
- };
343
- if (event.type === "start") {
344
- entry.start = event;
345
- } else if (event.type === "end") {
346
- entry.end = event;
347
- }
348
- eventsByInvocationId.set(invocationId, entry);
349
- }
350
- const now = Date.now();
351
- const result = [];
352
- for (const [invocationId, { start, end }] of eventsByInvocationId.entries()) {
353
- if (!start) {
354
- log.warn("found end event without matching start", {
355
- invocationId
356
- }, {
357
- F: __dxlog_file,
358
- L: 160,
359
- S: void 0,
360
- C: (f, a) => f(...a)
361
- });
362
- continue;
363
- }
364
- const isInProgress = end === void 0;
365
- result.push({
366
- id: invocationId,
367
- timestampMs: start.timestampMs,
368
- durationMs: isInProgress ? now - start.timestampMs : end.timestampMs - start.timestampMs,
369
- outcome: end?.outcome ?? "pending",
370
- exception: end?.exception,
371
- input: start.input,
372
- invocationTraceQueue: start.invocationTraceQueue,
373
- invocationTarget: start.invocationTarget,
374
- trigger: start.trigger
375
- });
376
- }
377
- return result;
378
- };
379
292
 
380
293
  // src/url.ts
381
294
  var FUNCTIONS_META_KEY = "dxos.org/service/function";
382
295
  var FUNCTIONS_PRESET_META_KEY = "dxos.org/service/function-preset";
383
- var isSecure = (protocol) => {
384
- return protocol === "https:" || protocol === "wss:";
385
- };
386
- var getUserFunctionUrlInMetadata = (meta) => {
296
+ var getUserFunctionIdInMetadata = (meta) => {
387
297
  return meta.keys.find((key) => key.source === FUNCTIONS_META_KEY)?.id;
388
298
  };
389
- var setUserFunctionUrlInMetadata = (meta, functionUrl) => {
299
+ var setUserFunctionIdInMetadata = (meta, functionId) => {
390
300
  const key = meta.keys.find((key2) => key2.source === FUNCTIONS_META_KEY);
391
301
  if (key) {
392
- if (key.id !== functionUrl) {
302
+ if (key.id !== functionId) {
393
303
  throw new Error("Metadata mismatch");
394
304
  }
395
305
  } else {
396
306
  meta.keys.push({
397
307
  source: FUNCTIONS_META_KEY,
398
- id: functionUrl
308
+ id: functionId
399
309
  });
400
310
  }
401
311
  };
402
- var makeFunctionUrl = (fn) => `/${fn.functionId}`;
403
- var getInvocationUrl = (functionUrl, edgeUrl, options = {}) => {
404
- const baseUrl = new URL("functions/", edgeUrl);
405
- const relativeUrl = functionUrl.replace(/^\//, "");
406
- const url = new URL(`./${relativeUrl}`, baseUrl.toString());
407
- options.spaceId && url.searchParams.set("spaceId", options.spaceId);
408
- options.subjectId && url.searchParams.set("subjectId", options.subjectId);
409
- url.protocol = isSecure(url.protocol) ? "https" : "http";
410
- return url.toString();
411
- };
412
312
 
413
- // src/executor/executor.ts
414
- import { Effect, Schema as Schema5 } from "effect";
415
- import { runAndForwardErrors } from "@dxos/effect";
416
- var FunctionExecutor = class {
417
- constructor(_services) {
418
- this._services = _services;
313
+ // src/handler.ts
314
+ var typeId = Symbol.for("@dxos/functions/FunctionDefinition");
315
+ var defineFunction = ({ key, name, description, inputSchema, outputSchema = Schema5.Any, handler }) => {
316
+ if (!Schema5.isSchema(inputSchema)) {
317
+ throw new Error("Input schema must be a valid schema");
419
318
  }
420
- // TODO(dmaretskyi): Invocation context: queue, space, etc...
421
- async invoke(fnDef, input) {
422
- const assertInput = fnDef.inputSchema.pipe(Schema5.asserts);
423
- assertInput(input);
424
- const context = {
425
- getService: this._services.getService.bind(this._services),
426
- getSpace: async (_spaceId) => {
427
- throw new Error("Not available. Use the database service instead.");
428
- },
429
- space: void 0,
430
- get ai() {
431
- throw new Error("Not available. Use the ai service instead.");
319
+ if (typeof handler !== "function") {
320
+ throw new Error("Handler must be a function");
321
+ }
322
+ const limit = Error.stackTraceLimit;
323
+ Error.stackTraceLimit = 2;
324
+ const traceError = new Error();
325
+ Error.stackTraceLimit = limit;
326
+ let cache = false;
327
+ const captureStackTrace = () => {
328
+ if (cache !== false) {
329
+ return cache;
330
+ }
331
+ if (traceError.stack !== void 0) {
332
+ const stack = traceError.stack.split("\n");
333
+ if (stack[2] !== void 0) {
334
+ cache = stack[2].trim();
335
+ return cache;
432
336
  }
433
- };
434
- const result = fnDef.handler({
435
- context,
436
- data: input
437
- });
438
- let data;
337
+ }
338
+ };
339
+ const handlerWithSpan = (...args) => {
340
+ const result = handler(...args);
439
341
  if (Effect.isEffect(result)) {
440
- data = await result.pipe(Effect.provide(this._services.createLayer()), runAndForwardErrors);
441
- } else {
442
- data = await result;
342
+ return Effect.withSpan(result, `${key ?? name}`, {
343
+ captureStackTrace
344
+ });
345
+ }
346
+ return result;
347
+ };
348
+ return {
349
+ [typeId]: true,
350
+ key,
351
+ name,
352
+ description,
353
+ inputSchema,
354
+ outputSchema,
355
+ handler: handlerWithSpan
356
+ };
357
+ };
358
+ var FunctionDefinition = {
359
+ make: defineFunction,
360
+ isFunction: (value2) => {
361
+ return typeof value2 === "object" && value2 !== null && Symbol.for("@dxos/functions/FunctionDefinition") in value2;
362
+ },
363
+ serialize: (functionDef) => {
364
+ assertArgument(FunctionDefinition.isFunction(functionDef), "functionDef");
365
+ return serializeFunction(functionDef);
366
+ },
367
+ deserialize: (functionObj) => {
368
+ assertArgument(Obj5.instanceOf(Function_exports.Function, functionObj), "functionObj");
369
+ return deserializeFunction(functionObj);
370
+ }
371
+ };
372
+ var serializeFunction = (functionDef) => {
373
+ const fn4 = Function_exports.make({
374
+ key: functionDef.key,
375
+ name: functionDef.name,
376
+ version: "0.1.0",
377
+ description: functionDef.description,
378
+ inputSchema: Type5.toJsonSchema(functionDef.inputSchema),
379
+ outputSchema: !functionDef.outputSchema ? void 0 : Type5.toJsonSchema(functionDef.outputSchema)
380
+ });
381
+ if (functionDef.meta?.deployedFunctionId) {
382
+ setUserFunctionIdInMetadata(Obj5.getMeta(fn4), functionDef.meta.deployedFunctionId);
383
+ }
384
+ return fn4;
385
+ };
386
+ var deserializeFunction = (functionObj) => {
387
+ return {
388
+ [typeId]: true,
389
+ // TODO(dmaretskyi): Fix key.
390
+ key: functionObj.key ?? functionObj.name,
391
+ name: functionObj.name,
392
+ description: functionObj.description,
393
+ inputSchema: !functionObj.inputSchema ? Schema5.Unknown : Type5.toEffectSchema(functionObj.inputSchema),
394
+ outputSchema: !functionObj.outputSchema ? void 0 : Type5.toEffectSchema(functionObj.outputSchema),
395
+ // TODO(dmaretskyi): This should throw error.
396
+ handler: () => {
397
+ },
398
+ meta: {
399
+ deployedFunctionId: getUserFunctionIdInMetadata(Obj5.getMeta(functionObj))
400
+ }
401
+ };
402
+ };
403
+
404
+ // src/example/fib.ts
405
+ var fib_default = defineFunction({
406
+ key: "example.org/function/fib",
407
+ name: "Fibonacci",
408
+ description: "Function that calculates a Fibonacci number",
409
+ inputSchema: Schema6.Struct({
410
+ iterations: Schema6.optional(Schema6.Number).annotations({
411
+ description: "Number of iterations",
412
+ default: 1e5
413
+ })
414
+ }),
415
+ outputSchema: Schema6.Struct({
416
+ result: Schema6.String
417
+ }),
418
+ handler: Effect2.fn(function* ({ data: { iterations = 1e5 } }) {
419
+ let a = 0n;
420
+ let b = 1n;
421
+ for (let i = 0; i < iterations; i++) {
422
+ a += b;
423
+ b = a - b;
443
424
  }
444
- const assertOutput = fnDef.outputSchema?.pipe(Schema5.asserts);
445
- assertOutput(data);
425
+ return {
426
+ result: a.toString()
427
+ };
428
+ })
429
+ });
430
+
431
+ // src/example/reply.ts
432
+ import * as Console from "effect/Console";
433
+ import * as Effect3 from "effect/Effect";
434
+ import * as Schema7 from "effect/Schema";
435
+ var reply_default = defineFunction({
436
+ key: "example.org/function/reply",
437
+ name: "Reply",
438
+ description: "Function that echoes the input",
439
+ inputSchema: Schema7.Any,
440
+ outputSchema: Schema7.Any,
441
+ handler: Effect3.fn(function* ({ data }) {
442
+ yield* Console.log("reply", {
443
+ data
444
+ });
446
445
  return data;
446
+ })
447
+ });
448
+
449
+ // src/example/sleep.ts
450
+ import * as Effect4 from "effect/Effect";
451
+ import * as Schema8 from "effect/Schema";
452
+ var sleep_default = defineFunction({
453
+ key: "example.org/function/sleep",
454
+ name: "Sleep",
455
+ description: "Function that sleeps for a given amount of time",
456
+ inputSchema: Schema8.Struct({
457
+ duration: Schema8.optional(Schema8.Number).annotations({
458
+ description: "Milliseconds to sleep",
459
+ default: 1e5
460
+ })
461
+ }),
462
+ outputSchema: Schema8.Void,
463
+ handler: Effect4.fn(function* ({ data: { duration = 1e5 } }) {
464
+ yield* Effect4.sleep(duration);
465
+ })
466
+ });
467
+
468
+ // src/example/index.ts
469
+ (function(Example2) {
470
+ Example2.fib = fib_default;
471
+ Example2.reply = reply_default;
472
+ Example2.sleep = sleep_default;
473
+ })(Example || (Example = {}));
474
+ var Example;
475
+
476
+ // src/services/index.ts
477
+ import { DatabaseService as DatabaseService2 } from "@dxos/echo-db";
478
+
479
+ // src/services/credentials.ts
480
+ import * as HttpClient from "@effect/platform/HttpClient";
481
+ import * as HttpClientRequest from "@effect/platform/HttpClientRequest";
482
+ import * as Context from "effect/Context";
483
+ import * as Effect5 from "effect/Effect";
484
+ import * as Layer from "effect/Layer";
485
+ import * as Redacted from "effect/Redacted";
486
+ import { Query } from "@dxos/echo";
487
+ import { DatabaseService } from "@dxos/echo-db";
488
+ import { AccessToken } from "@dxos/types";
489
+ var CredentialsService = class _CredentialsService extends Context.Tag("@dxos/functions/CredentialsService")() {
490
+ static getCredential = (query) => Effect5.gen(function* () {
491
+ const credentials = yield* _CredentialsService;
492
+ return yield* Effect5.promise(() => credentials.getCredential(query));
493
+ });
494
+ static getApiKey = (query) => Effect5.gen(function* () {
495
+ const credential = yield* _CredentialsService.getCredential(query);
496
+ if (!credential.apiKey) {
497
+ throw new Error(`API key not found for service: ${query.service}`);
498
+ }
499
+ return Redacted.make(credential.apiKey);
500
+ });
501
+ static configuredLayer = (credentials) => Layer.succeed(_CredentialsService, new ConfiguredCredentialsService(credentials));
502
+ static layerConfig = (credentials) => Layer.effect(_CredentialsService, Effect5.gen(function* () {
503
+ const serviceCredentials = yield* Effect5.forEach(credentials, ({ service, apiKey }) => Effect5.gen(function* () {
504
+ return {
505
+ service,
506
+ apiKey: Redacted.value(yield* apiKey)
507
+ };
508
+ }));
509
+ return new ConfiguredCredentialsService(serviceCredentials);
510
+ }));
511
+ static layerFromDatabase = () => Layer.effect(_CredentialsService, Effect5.gen(function* () {
512
+ const dbService = yield* DatabaseService;
513
+ const queryCredentials = async (query) => {
514
+ const { objects: accessTokens } = await dbService.db.query(Query.type(AccessToken.AccessToken)).run();
515
+ return accessTokens.filter((accessToken) => accessToken.source === query.service).map((accessToken) => ({
516
+ service: accessToken.source,
517
+ apiKey: accessToken.token
518
+ }));
519
+ };
520
+ return {
521
+ getCredential: async (query) => {
522
+ const credentials = await queryCredentials(query);
523
+ if (credentials.length === 0) {
524
+ throw new Error(`Credential not found for service: ${query.service}`);
525
+ }
526
+ return credentials[0];
527
+ },
528
+ queryCredentials: async (query) => {
529
+ return queryCredentials(query);
530
+ }
531
+ };
532
+ }));
533
+ };
534
+ var ConfiguredCredentialsService = class {
535
+ credentials;
536
+ constructor(credentials = []) {
537
+ this.credentials = credentials;
538
+ }
539
+ addCredentials(credentials) {
540
+ this.credentials.push(...credentials);
541
+ return this;
542
+ }
543
+ async queryCredentials(query) {
544
+ return this.credentials.filter((credential) => credential.service === query.service);
545
+ }
546
+ async getCredential(query) {
547
+ const credential = this.credentials.find((credential2) => credential2.service === query.service);
548
+ if (!credential) {
549
+ throw new Error(`Credential not found for service: ${query.service}`);
550
+ }
551
+ return credential;
447
552
  }
448
553
  };
554
+ var withAuthorization = (query, kind) => HttpClient.mapRequestEffect(Effect5.fnUntraced(function* (request) {
555
+ const key = yield* CredentialsService.getApiKey(query).pipe(Effect5.map(Redacted.value));
556
+ const authorization = kind ? `${kind} ${key}` : key;
557
+ return HttpClientRequest.setHeader(request, "Authorization", authorization);
558
+ }));
449
559
 
450
- // src/errors.ts
451
- import { BaseError } from "@dxos/errors";
452
- var ServiceNotAvailableError = class extends BaseError.extend("SERVICE_NOT_AVAILABLE") {
453
- constructor(serviceName) {
454
- super(`Service not available: ${serviceName}`);
560
+ // src/services/event-logger.ts
561
+ import * as Context3 from "effect/Context";
562
+ import * as Effect7 from "effect/Effect";
563
+ import * as Layer3 from "effect/Layer";
564
+ import * as Schema9 from "effect/Schema";
565
+ import { Obj as Obj7, Type as Type6 } from "@dxos/echo";
566
+ import { invariant } from "@dxos/invariant";
567
+ import { LogLevel, log as log2 } from "@dxos/log";
568
+
569
+ // src/services/tracing.ts
570
+ import * as Context2 from "effect/Context";
571
+ import * as Effect6 from "effect/Effect";
572
+ import * as Layer2 from "effect/Layer";
573
+ import { AgentStatus } from "@dxos/ai";
574
+ import { Obj as Obj6 } from "@dxos/echo";
575
+ import { Message } from "@dxos/types";
576
+ var TracingService = class _TracingService extends Context2.Tag("@dxos/functions/TracingService")() {
577
+ static noop = {
578
+ getTraceContext: () => ({}),
579
+ write: () => {
580
+ }
581
+ };
582
+ static layerNoop = Layer2.succeed(_TracingService, _TracingService.noop);
583
+ /**
584
+ * Creates a TracingService layer that emits events to the parent tracing service.
585
+ */
586
+ static layerSubframe = (mapContext) => Layer2.effect(_TracingService, Effect6.gen(function* () {
587
+ const tracing = yield* _TracingService;
588
+ const context = mapContext(tracing.getTraceContext());
589
+ return {
590
+ write: (event) => tracing.write(event),
591
+ getTraceContext: () => context
592
+ };
593
+ }));
594
+ /**
595
+ * Emit the current human-readable execution status.
596
+ */
597
+ static emitStatus = Effect6.fnUntraced(function* (data) {
598
+ const tracing = yield* _TracingService;
599
+ tracing.write(Obj6.make(AgentStatus, {
600
+ parentMessage: tracing.getTraceContext().parentMessage,
601
+ toolCallId: tracing.getTraceContext().toolCallId,
602
+ created: (/* @__PURE__ */ new Date()).toISOString(),
603
+ ...data
604
+ }));
605
+ });
606
+ static emitConverationMessage = Effect6.fnUntraced(function* (data) {
607
+ const tracing = yield* _TracingService;
608
+ tracing.write(Obj6.make(Message.Message, {
609
+ parentMessage: tracing.getTraceContext().parentMessage,
610
+ ...data,
611
+ properties: {
612
+ [MESSAGE_PROPERTY_TOOL_CALL_ID]: tracing.getTraceContext().toolCallId,
613
+ ...data.properties
614
+ }
615
+ }));
616
+ });
617
+ };
618
+ var MESSAGE_PROPERTY_TOOL_CALL_ID = "toolCallId";
619
+
620
+ // src/services/event-logger.ts
621
+ var __dxlog_file = "/__w/dxos/dxos/packages/core/functions/src/services/event-logger.ts";
622
+ var ComputeEventPayload = Schema9.Union(Schema9.Struct({
623
+ type: Schema9.Literal("begin-compute"),
624
+ nodeId: Schema9.String,
625
+ /**
626
+ * Names of the inputs begin computed.
627
+ */
628
+ inputs: Schema9.Array(Schema9.String)
629
+ }), Schema9.Struct({
630
+ type: Schema9.Literal("end-compute"),
631
+ nodeId: Schema9.String,
632
+ /**
633
+ * Names of the outputs computed.
634
+ */
635
+ outputs: Schema9.Array(Schema9.String)
636
+ }), Schema9.Struct({
637
+ type: Schema9.Literal("compute-input"),
638
+ nodeId: Schema9.String,
639
+ property: Schema9.String,
640
+ value: Schema9.Any
641
+ }), Schema9.Struct({
642
+ type: Schema9.Literal("compute-output"),
643
+ nodeId: Schema9.String,
644
+ property: Schema9.String,
645
+ value: Schema9.Any
646
+ }), Schema9.Struct({
647
+ type: Schema9.Literal("custom"),
648
+ nodeId: Schema9.String,
649
+ event: Schema9.Any
650
+ }));
651
+ var ComputeEvent = Schema9.Struct({
652
+ payload: ComputeEventPayload
653
+ }).pipe(Type6.Obj({
654
+ typename: "dxos.org/type/ComputeEvent",
655
+ version: "0.1.0"
656
+ }));
657
+ var ComputeEventLogger = class _ComputeEventLogger extends Context3.Tag("@dxos/functions/ComputeEventLogger")() {
658
+ static noop = {
659
+ log: () => {
660
+ },
661
+ nodeId: void 0
662
+ };
663
+ /**
664
+ * Implements ComputeEventLogger using TracingService.
665
+ */
666
+ static layerFromTracing = Layer3.effect(_ComputeEventLogger, Effect7.gen(function* () {
667
+ const tracing = yield* TracingService;
668
+ return {
669
+ log: (event) => {
670
+ tracing.write(Obj7.make(ComputeEvent, {
671
+ payload: event
672
+ }));
673
+ },
674
+ nodeId: void 0
675
+ };
676
+ }));
677
+ };
678
+ var logCustomEvent = (data) => Effect7.gen(function* () {
679
+ const logger = yield* ComputeEventLogger;
680
+ if (!logger.nodeId) {
681
+ throw new Error("logCustomEvent must be called within a node compute function");
455
682
  }
683
+ logger.log({
684
+ type: "custom",
685
+ nodeId: logger.nodeId,
686
+ event: data
687
+ });
688
+ });
689
+ var createDefectLogger = () => Effect7.catchAll((error) => Effect7.gen(function* () {
690
+ log2.error("unhandled effect error", {
691
+ error
692
+ }, {
693
+ F: __dxlog_file,
694
+ L: 102,
695
+ S: this,
696
+ C: (f, a) => f(...a)
697
+ });
698
+ throw error;
699
+ }));
700
+ var createEventLogger = (level, message = "event") => {
701
+ const logFunction = {
702
+ [LogLevel.WARN]: log2.warn,
703
+ [LogLevel.VERBOSE]: log2.verbose,
704
+ [LogLevel.DEBUG]: log2.debug,
705
+ [LogLevel.INFO]: log2.info,
706
+ [LogLevel.ERROR]: log2.error
707
+ }[level];
708
+ invariant(logFunction, void 0, {
709
+ F: __dxlog_file,
710
+ L: 120,
711
+ S: void 0,
712
+ A: [
713
+ "logFunction",
714
+ ""
715
+ ]
716
+ });
717
+ return {
718
+ log: (event) => {
719
+ logFunction(message, event);
720
+ },
721
+ nodeId: void 0
722
+ };
723
+ };
724
+
725
+ // src/services/function-invocation-service.ts
726
+ import * as Context4 from "effect/Context";
727
+ import * as Effect8 from "effect/Effect";
728
+ var FunctionInvocationService = class _FunctionInvocationService extends Context4.Tag("@dxos/functions/FunctionInvocationService")() {
729
+ static invokeFunction = (functionDef, input) => Effect8.serviceFunctionEffect(_FunctionInvocationService, (service) => service.invokeFunction)(functionDef, input);
730
+ };
731
+
732
+ // src/services/queues.ts
733
+ import * as Context5 from "effect/Context";
734
+ import * as Effect9 from "effect/Effect";
735
+ import * as Layer4 from "effect/Layer";
736
+ var QueueService = class _QueueService extends Context5.Tag("@dxos/functions/QueueService")() {
737
+ static notAvailable = Layer4.succeed(_QueueService, {
738
+ queues: {
739
+ get(_dxn) {
740
+ throw new Error("Queues not available");
741
+ },
742
+ create() {
743
+ throw new Error("Queues not available");
744
+ }
745
+ },
746
+ queue: void 0
747
+ });
748
+ static make = (queues, queue) => {
749
+ return {
750
+ queues,
751
+ queue
752
+ };
753
+ };
754
+ static layer = (queues, queue) => Layer4.succeed(_QueueService, _QueueService.make(queues, queue));
755
+ /**
756
+ * Gets a queue by its DXN.
757
+ */
758
+ static getQueue = (dxn) => _QueueService.pipe(Effect9.map(({ queues }) => queues.get(dxn)));
759
+ /**
760
+ * Creates a new queue.
761
+ */
762
+ static createQueue = (options) => _QueueService.pipe(Effect9.map(({ queues }) => queues.create(options)));
763
+ static append = (queue, objects) => Effect9.promise(() => queue.append(objects));
456
764
  };
457
- var FunctionError = class extends BaseError.extend("FUNCTION_ERROR") {
765
+ var ContextQueueService = class _ContextQueueService extends Context5.Tag("@dxos/functions/ContextQueueService")() {
766
+ static layer = (queue) => Layer4.succeed(_ContextQueueService, {
767
+ queue
768
+ });
458
769
  };
459
770
  export {
771
+ ComputeEvent,
772
+ ComputeEventLogger,
773
+ ComputeEventPayload,
460
774
  ConfiguredCredentialsService,
461
775
  ContextQueueService,
462
776
  CredentialsService,
463
- DatabaseService,
464
- EmailTriggerOutput,
465
- EventLogger,
777
+ DatabaseService2 as DatabaseService,
778
+ Example,
779
+ FUNCTIONS_META_KEY,
466
780
  FUNCTIONS_PRESET_META_KEY,
467
- FUNCTION_TYPES,
468
- FunctionCallService,
781
+ Function_exports as Function,
782
+ FunctionDefinition,
469
783
  FunctionError,
470
- FunctionExecutor,
471
- FunctionManifestSchema,
472
- FunctionTrigger,
473
- FunctionTriggerSchema,
474
- FunctionType,
475
- InvocationOutcome,
476
- InvocationTraceEndEvent,
477
- InvocationTraceEventType,
478
- InvocationTraceStartEvent,
784
+ FunctionInvocationService,
785
+ FunctionNotFoundError,
786
+ MESSAGE_PROPERTY_TOOL_CALL_ID,
479
787
  QueueService,
480
- QueueTriggerOutput,
481
- SERVICE_TAGS,
482
- ScriptType,
483
- ServiceContainer,
788
+ Script_exports as Script,
484
789
  ServiceNotAvailableError,
485
- SubscriptionTriggerOutput,
486
- TimerTriggerOutput,
487
- TraceEvent,
488
- TraceEventException,
489
- TraceEventLog,
490
790
  TracingService,
491
- TriggerKind,
492
- TriggerSchema,
493
- WebhookTriggerOutput,
791
+ Trigger_exports as Trigger,
792
+ TriggerEvent_exports as TriggerEvent,
793
+ TriggerStateNotFoundError,
494
794
  createDefectLogger,
495
795
  createEventLogger,
496
- createInvocationSpans,
497
796
  defineFunction,
498
- getInvocationUrl,
499
- getUserFunctionUrlInMetadata,
797
+ deserializeFunction,
798
+ getUserFunctionIdInMetadata,
500
799
  logCustomEvent,
501
- makeFunctionUrl,
502
- setUserFunctionUrlInMetadata
800
+ serializeFunction,
801
+ setUserFunctionIdInMetadata,
802
+ withAuthorization
503
803
  };
504
804
  //# sourceMappingURL=index.mjs.map