@dxos/functions 0.8.4-main.406dc2a → 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 (175) hide show
  1. package/dist/lib/browser/index.mjs +598 -1190
  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 +598 -1190
  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 +16 -32
  8. package/dist/types/src/errors.d.ts.map +1 -1
  9. package/dist/types/src/example/fib.d.ts.map +1 -0
  10. package/dist/types/src/example/forex-effect.d.ts +3 -0
  11. package/dist/types/src/example/forex-effect.d.ts.map +1 -0
  12. package/dist/types/src/example/index.d.ts +12 -0
  13. package/dist/types/src/example/index.d.ts.map +1 -0
  14. package/dist/types/src/example/reply.d.ts.map +1 -0
  15. package/dist/types/src/example/sleep.d.ts.map +1 -0
  16. package/dist/types/src/handler.d.ts +28 -55
  17. package/dist/types/src/handler.d.ts.map +1 -1
  18. package/dist/types/src/index.d.ts +2 -6
  19. package/dist/types/src/index.d.ts.map +1 -1
  20. package/dist/types/src/services/credentials.d.ts +1 -1
  21. package/dist/types/src/services/credentials.d.ts.map +1 -1
  22. package/dist/types/src/services/event-logger.d.ts +16 -4
  23. package/dist/types/src/services/event-logger.d.ts.map +1 -1
  24. package/dist/types/src/services/function-invocation-service.d.ts +2 -19
  25. package/dist/types/src/services/function-invocation-service.d.ts.map +1 -1
  26. package/dist/types/src/services/index.d.ts +3 -4
  27. package/dist/types/src/services/index.d.ts.map +1 -1
  28. package/dist/types/src/services/tracing.d.ts +4 -9
  29. package/dist/types/src/services/tracing.d.ts.map +1 -1
  30. package/dist/types/src/types/Function.d.ts +52 -0
  31. package/dist/types/src/types/Function.d.ts.map +1 -0
  32. package/dist/types/src/types/Script.d.ts +28 -0
  33. package/dist/types/src/types/Script.d.ts.map +1 -0
  34. package/dist/types/src/{types.d.ts → types/Trigger.d.ts} +47 -138
  35. package/dist/types/src/types/Trigger.d.ts.map +1 -0
  36. package/dist/types/src/types/TriggerEvent.d.ts +44 -0
  37. package/dist/types/src/types/TriggerEvent.d.ts.map +1 -0
  38. package/dist/types/src/types/index.d.ts +5 -0
  39. package/dist/types/src/types/index.d.ts.map +1 -0
  40. package/dist/types/src/url.d.ts +0 -9
  41. package/dist/types/src/url.d.ts.map +1 -1
  42. package/dist/types/tsconfig.tsbuildinfo +1 -1
  43. package/package.json +12 -59
  44. package/src/example/forex-effect.ts +40 -0
  45. package/src/example/index.ts +13 -0
  46. package/src/handler.ts +45 -69
  47. package/src/index.ts +2 -6
  48. package/src/services/credentials.ts +3 -4
  49. package/src/services/event-logger.ts +8 -2
  50. package/src/services/function-invocation-service.ts +6 -70
  51. package/src/services/index.ts +4 -4
  52. package/src/services/tracing.ts +7 -42
  53. package/src/{schema.ts → types/Function.ts} +11 -26
  54. package/src/types/Script.ts +33 -0
  55. package/src/types/Trigger.ts +139 -0
  56. package/src/types/TriggerEvent.ts +62 -0
  57. package/src/types/index.ts +8 -0
  58. package/src/url.ts +0 -24
  59. package/dist/lib/browser/bundler/index.mjs +0 -269
  60. package/dist/lib/browser/bundler/index.mjs.map +0 -7
  61. package/dist/lib/browser/chunk-J5LGTIGS.mjs +0 -10
  62. package/dist/lib/browser/chunk-J5LGTIGS.mjs.map +0 -7
  63. package/dist/lib/browser/chunk-LKYT2SAL.mjs +0 -665
  64. package/dist/lib/browser/chunk-LKYT2SAL.mjs.map +0 -7
  65. package/dist/lib/browser/edge/index.mjs +0 -83
  66. package/dist/lib/browser/edge/index.mjs.map +0 -7
  67. package/dist/lib/browser/testing/index.mjs +0 -131
  68. package/dist/lib/browser/testing/index.mjs.map +0 -7
  69. package/dist/lib/node-esm/bundler/index.mjs +0 -270
  70. package/dist/lib/node-esm/bundler/index.mjs.map +0 -7
  71. package/dist/lib/node-esm/chunk-HSLMI22Q.mjs +0 -11
  72. package/dist/lib/node-esm/chunk-HSLMI22Q.mjs.map +0 -7
  73. package/dist/lib/node-esm/chunk-NAQIKLZB.mjs +0 -667
  74. package/dist/lib/node-esm/chunk-NAQIKLZB.mjs.map +0 -7
  75. package/dist/lib/node-esm/edge/index.mjs +0 -84
  76. package/dist/lib/node-esm/edge/index.mjs.map +0 -7
  77. package/dist/lib/node-esm/testing/index.mjs +0 -132
  78. package/dist/lib/node-esm/testing/index.mjs.map +0 -7
  79. package/dist/types/src/bundler/bundler.d.ts +0 -49
  80. package/dist/types/src/bundler/bundler.d.ts.map +0 -1
  81. package/dist/types/src/bundler/bundler.test.d.ts +0 -2
  82. package/dist/types/src/bundler/bundler.test.d.ts.map +0 -1
  83. package/dist/types/src/bundler/index.d.ts +0 -2
  84. package/dist/types/src/bundler/index.d.ts.map +0 -1
  85. package/dist/types/src/edge/functions.d.ts +0 -17
  86. package/dist/types/src/edge/functions.d.ts.map +0 -1
  87. package/dist/types/src/edge/index.d.ts +0 -2
  88. package/dist/types/src/edge/index.d.ts.map +0 -1
  89. package/dist/types/src/examples/fib.d.ts.map +0 -1
  90. package/dist/types/src/examples/index.d.ts +0 -4
  91. package/dist/types/src/examples/index.d.ts.map +0 -1
  92. package/dist/types/src/examples/reply.d.ts.map +0 -1
  93. package/dist/types/src/examples/sleep.d.ts.map +0 -1
  94. package/dist/types/src/executor/executor.d.ts +0 -14
  95. package/dist/types/src/executor/executor.d.ts.map +0 -1
  96. package/dist/types/src/executor/index.d.ts +0 -2
  97. package/dist/types/src/executor/index.d.ts.map +0 -1
  98. package/dist/types/src/schema.d.ts +0 -43
  99. package/dist/types/src/schema.d.ts.map +0 -1
  100. package/dist/types/src/services/database.d.ts +0 -67
  101. package/dist/types/src/services/database.d.ts.map +0 -1
  102. package/dist/types/src/services/function-invocation-service.test.d.ts +0 -2
  103. package/dist/types/src/services/function-invocation-service.test.d.ts.map +0 -1
  104. package/dist/types/src/services/local-function-execution.d.ts +0 -34
  105. package/dist/types/src/services/local-function-execution.d.ts.map +0 -1
  106. package/dist/types/src/services/remote-function-execution-service.d.ts +0 -22
  107. package/dist/types/src/services/remote-function-execution-service.d.ts.map +0 -1
  108. package/dist/types/src/services/service-container.d.ts +0 -57
  109. package/dist/types/src/services/service-container.d.ts.map +0 -1
  110. package/dist/types/src/services/service-registry.d.ts +0 -31
  111. package/dist/types/src/services/service-registry.d.ts.map +0 -1
  112. package/dist/types/src/services/service-registry.test.d.ts +0 -2
  113. package/dist/types/src/services/service-registry.test.d.ts.map +0 -1
  114. package/dist/types/src/testing/index.d.ts +0 -3
  115. package/dist/types/src/testing/index.d.ts.map +0 -1
  116. package/dist/types/src/testing/layer.d.ts +0 -18
  117. package/dist/types/src/testing/layer.d.ts.map +0 -1
  118. package/dist/types/src/testing/logger.d.ts +0 -5
  119. package/dist/types/src/testing/logger.d.ts.map +0 -1
  120. package/dist/types/src/testing/persist-database.test.d.ts +0 -2
  121. package/dist/types/src/testing/persist-database.test.d.ts.map +0 -1
  122. package/dist/types/src/testing/services.d.ts +0 -59
  123. package/dist/types/src/testing/services.d.ts.map +0 -1
  124. package/dist/types/src/trace.d.ts +0 -122
  125. package/dist/types/src/trace.d.ts.map +0 -1
  126. package/dist/types/src/translations.d.ts +0 -12
  127. package/dist/types/src/translations.d.ts.map +0 -1
  128. package/dist/types/src/triggers/index.d.ts +0 -4
  129. package/dist/types/src/triggers/index.d.ts.map +0 -1
  130. package/dist/types/src/triggers/input-builder.d.ts +0 -3
  131. package/dist/types/src/triggers/input-builder.d.ts.map +0 -1
  132. package/dist/types/src/triggers/invocation-tracer.d.ts +0 -37
  133. package/dist/types/src/triggers/invocation-tracer.d.ts.map +0 -1
  134. package/dist/types/src/triggers/trigger-dispatcher.d.ts +0 -78
  135. package/dist/types/src/triggers/trigger-dispatcher.d.ts.map +0 -1
  136. package/dist/types/src/triggers/trigger-dispatcher.test.d.ts +0 -2
  137. package/dist/types/src/triggers/trigger-dispatcher.test.d.ts.map +0 -1
  138. package/dist/types/src/triggers/trigger-state-store.d.ts +0 -28
  139. package/dist/types/src/triggers/trigger-state-store.d.ts.map +0 -1
  140. package/dist/types/src/types.d.ts.map +0 -1
  141. package/src/bundler/bundler.test.ts +0 -58
  142. package/src/bundler/bundler.ts +0 -295
  143. package/src/bundler/index.ts +0 -5
  144. package/src/edge/functions.ts +0 -67
  145. package/src/edge/index.ts +0 -9
  146. package/src/examples/index.ts +0 -7
  147. package/src/executor/executor.ts +0 -58
  148. package/src/executor/index.ts +0 -5
  149. package/src/services/database.ts +0 -175
  150. package/src/services/function-invocation-service.test.ts +0 -81
  151. package/src/services/local-function-execution.ts +0 -153
  152. package/src/services/remote-function-execution-service.ts +0 -63
  153. package/src/services/service-container.ts +0 -115
  154. package/src/services/service-registry.test.ts +0 -45
  155. package/src/services/service-registry.ts +0 -63
  156. package/src/testing/index.ts +0 -6
  157. package/src/testing/layer.ts +0 -114
  158. package/src/testing/logger.ts +0 -17
  159. package/src/testing/persist-database.test.ts +0 -87
  160. package/src/testing/services.ts +0 -115
  161. package/src/trace.ts +0 -178
  162. package/src/translations.ts +0 -20
  163. package/src/triggers/index.ts +0 -7
  164. package/src/triggers/input-builder.ts +0 -35
  165. package/src/triggers/invocation-tracer.ts +0 -101
  166. package/src/triggers/trigger-dispatcher.test.ts +0 -665
  167. package/src/triggers/trigger-dispatcher.ts +0 -533
  168. package/src/triggers/trigger-state-store.ts +0 -61
  169. package/src/types.ts +0 -218
  170. /package/dist/types/src/{examples → example}/fib.d.ts +0 -0
  171. /package/dist/types/src/{examples → example}/reply.d.ts +0 -0
  172. /package/dist/types/src/{examples → example}/sleep.d.ts +0 -0
  173. /package/src/{examples → example}/fib.ts +0 -0
  174. /package/src/{examples → example}/reply.ts +0 -0
  175. /package/src/{examples → example}/sleep.ts +0 -0
@@ -1,61 +1,87 @@
1
1
  import { createRequire } from 'node:module';const require = createRequire(import.meta.url);
2
- import {
3
- ComputeEvent,
4
- ComputeEventLogger,
5
- ComputeEventPayload,
6
- ConfiguredCredentialsService,
7
- ContextQueueService,
8
- CredentialsService,
9
- DatabaseService,
10
- FUNCTIONS_META_KEY,
11
- FUNCTIONS_PRESET_META_KEY,
12
- FunctionError,
13
- FunctionNotFoundError,
14
- MESSAGE_PROPERTY_TOOL_CALL_ID,
15
- QueueService,
16
- RemoteFunctionExecutionService,
17
- SERVICE_TAGS,
18
- ServiceContainer,
19
- ServiceNotAvailableError,
20
- TracingService,
21
- TriggerStateNotFoundError,
22
- createDefectLogger,
23
- createEventLogger,
24
- getInvocationUrl,
25
- getUserFunctionIdInMetadata,
26
- logCustomEvent,
27
- setUserFunctionIdInMetadata,
28
- withAuthorization
29
- } from "./chunk-NAQIKLZB.mjs";
30
- import {
31
- __export
32
- } from "./chunk-HSLMI22Q.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
+ };
7
+
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
+ });
18
+ }
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
+ });
28
+ }
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") {
33
+ };
34
+
35
+ // src/example/fib.ts
36
+ import * as Effect2 from "effect/Effect";
37
+ import * as Schema6 from "effect/Schema";
33
38
 
34
39
  // src/handler.ts
35
40
  import * as Effect from "effect/Effect";
36
- import * as Schema2 from "effect/Schema";
37
- import { Obj, Type as Type2 } from "@dxos/echo";
41
+ import * as Schema5 from "effect/Schema";
42
+ import { Obj as Obj5, Type as Type5 } from "@dxos/echo";
38
43
  import { assertArgument } from "@dxos/invariant";
39
44
 
40
- // src/schema.ts
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
+ });
41
61
  import * as Schema from "effect/Schema";
42
- import { Type } from "@dxos/echo";
43
- import { JsonSchemaType, LabelAnnotation, Ref } from "@dxos/echo/internal";
44
- import { DataType } from "@dxos/schema";
45
- var ScriptType = Schema.Struct({
46
- name: Schema.optional(Schema.String),
47
- description: Schema.optional(Schema.String),
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),
48
68
  // TODO(burdon): Change to hash of deployed content.
49
69
  // Whether source has changed since last deploy.
50
- changed: Schema.optional(Schema.Boolean),
51
- source: Ref(DataType.Text)
70
+ changed: Schema.Boolean.pipe(FormAnnotation.set(false), Schema.optional),
71
+ source: Type.Ref(Text.Text).pipe(FormAnnotation.set(false))
52
72
  }).pipe(Type.Obj({
53
73
  typename: "dxos.org/type/Script",
54
74
  version: "0.1.0"
55
75
  }), LabelAnnotation.set([
56
76
  "name"
57
77
  ]));
58
- var FunctionType = Schema.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({
59
85
  /**
60
86
  * Global registry ID.
61
87
  * NOTE: The `key` property refers to the original registry entry.
@@ -63,172 +89,69 @@ var FunctionType = Schema.Struct({
63
89
  // TODO(burdon): Create Format type for DXN-like ids, such as this and schema type.
64
90
  // TODO(dmaretskyi): Consider making it part of ECHO meta.
65
91
  // TODO(dmaretskyi): Make required.
66
- key: Schema.optional(Schema.String).annotations({
92
+ key: Schema2.optional(Schema2.String).annotations({
67
93
  description: "Unique registration key for the blueprint"
68
94
  }),
69
95
  // TODO(burdon): Rename to id/uri?
70
- name: Schema.NonEmptyString,
71
- version: Schema.String,
72
- description: Schema.optional(Schema.String),
96
+ name: Schema2.NonEmptyString,
97
+ version: Schema2.String,
98
+ description: Schema2.optional(Schema2.String),
99
+ /**
100
+ * ISO date string of the last deployment.
101
+ */
102
+ updated: Schema2.optional(Schema2.String),
73
103
  // Reference to a source script if it exists within ECHO.
74
104
  // TODO(burdon): Don't ref ScriptType directly (core).
75
- source: Schema.optional(Ref(ScriptType)),
76
- inputSchema: Schema.optional(JsonSchemaType),
77
- outputSchema: Schema.optional(JsonSchemaType),
105
+ source: Schema2.optional(Ref2(Script)),
106
+ inputSchema: Schema2.optional(JsonSchemaType),
107
+ outputSchema: Schema2.optional(JsonSchemaType),
78
108
  // Local binding to a function name.
79
- binding: Schema.optional(Schema.String)
80
- }).pipe(Type.Obj({
109
+ binding: Schema2.optional(Schema2.String)
110
+ }).pipe(Type2.Obj({
81
111
  typename: "dxos.org/type/Function",
82
112
  version: "0.1.0"
83
- }), LabelAnnotation.set([
113
+ }), LabelAnnotation2.set([
84
114
  "name"
85
115
  ]));
116
+ var make2 = (props) => Obj2.make(Function, props);
86
117
 
87
- // src/handler.ts
88
- var typeId = Symbol.for("@dxos/functions/FunctionDefinition");
89
- var defineFunction = ({ key, name, description, inputSchema, outputSchema = Schema2.Any, handler }) => {
90
- if (!Schema2.isSchema(inputSchema)) {
91
- throw new Error("Input schema must be a valid schema");
92
- }
93
- if (typeof handler !== "function") {
94
- throw new Error("Handler must be a function");
95
- }
96
- const limit = Error.stackTraceLimit;
97
- Error.stackTraceLimit = 2;
98
- const traceError = new Error();
99
- Error.stackTraceLimit = limit;
100
- let cache = false;
101
- const captureStackTrace = () => {
102
- if (cache !== false) {
103
- return cache;
104
- }
105
- if (traceError.stack !== void 0) {
106
- const stack = traceError.stack.split("\n");
107
- if (stack[2] !== void 0) {
108
- cache = stack[2].trim();
109
- return cache;
110
- }
111
- }
112
- };
113
- const handlerWithSpan = (...args) => {
114
- const result = handler(...args);
115
- if (Effect.isEffect(result)) {
116
- return Effect.withSpan(result, `${key ?? name}`, {
117
- captureStackTrace
118
- });
119
- }
120
- return result;
121
- };
122
- return {
123
- [typeId]: true,
124
- key,
125
- name,
126
- description,
127
- inputSchema,
128
- outputSchema,
129
- handler: handlerWithSpan
130
- };
131
- };
132
- var FunctionDefinition = {
133
- make: defineFunction,
134
- isFunction: (value) => {
135
- return typeof value === "object" && value !== null && Symbol.for("@dxos/functions/FunctionDefinition") in value;
136
- },
137
- serialize: (functionDef) => {
138
- assertArgument(FunctionDefinition.isFunction(functionDef), "functionDef");
139
- return serializeFunction(functionDef);
140
- },
141
- deserialize: (functionObj) => {
142
- assertArgument(Obj.instanceOf(FunctionType, functionObj), "functionObj");
143
- return deserializeFunction(functionObj);
144
- }
145
- };
146
- var serializeFunction = (functionDef) => {
147
- const fn6 = Obj.make(FunctionType, {
148
- key: functionDef.key,
149
- name: functionDef.name,
150
- version: "0.1.0",
151
- description: functionDef.description,
152
- inputSchema: Type2.toJsonSchema(functionDef.inputSchema),
153
- outputSchema: !functionDef.outputSchema ? void 0 : Type2.toJsonSchema(functionDef.outputSchema)
154
- });
155
- if (functionDef.meta?.deployedFunctionId) {
156
- setUserFunctionIdInMetadata(Obj.getMeta(fn6), functionDef.meta.deployedFunctionId);
157
- }
158
- return fn6;
159
- };
160
- var deserializeFunction = (functionObj) => {
161
- return {
162
- [typeId]: true,
163
- // TODO(dmaretskyi): Fix key.
164
- key: functionObj.key ?? functionObj.name,
165
- name: functionObj.name,
166
- description: functionObj.description,
167
- inputSchema: !functionObj.inputSchema ? Schema2.Unknown : Type2.toEffectSchema(functionObj.inputSchema),
168
- outputSchema: !functionObj.outputSchema ? void 0 : Type2.toEffectSchema(functionObj.outputSchema),
169
- // TODO(dmaretskyi): This should throw error.
170
- handler: () => {
171
- },
172
- meta: {
173
- deployedFunctionId: getUserFunctionIdInMetadata(Obj.getMeta(functionObj))
174
- }
175
- };
176
- };
177
-
178
- // src/trace.ts
179
- import * as Schema4 from "effect/Schema";
180
- import { Type as Type4 } from "@dxos/echo";
181
- import { ObjectId } from "@dxos/echo/internal";
182
- import { Queue } from "@dxos/echo-db";
183
- import { log } from "@dxos/log";
184
-
185
- // src/types.ts
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
+ });
186
131
  import * as Schema3 from "effect/Schema";
187
132
  import * as SchemaAST from "effect/SchemaAST";
188
- import { Obj as Obj2, QueryAST, Type as Type3 } from "@dxos/echo";
189
- import { Expando, OptionsAnnotationId, RawObject, Ref as Ref2 } from "@dxos/echo/internal";
133
+ import { Obj as Obj3, QueryAST, Type as Type3 } from "@dxos/echo";
134
+ import { Expando, OptionsAnnotationId, Ref as Ref3 } from "@dxos/echo/internal";
190
135
  import { DXN } from "@dxos/keys";
191
- var TriggerKinds = [
192
- "timer",
193
- "webhook",
194
- "subscription",
136
+ var Kinds = [
195
137
  "email",
196
- "queue"
138
+ "queue",
139
+ "subscription",
140
+ "timer",
141
+ "webhook"
197
142
  ];
198
143
  var kindLiteralAnnotations = {
199
144
  title: "Kind"
200
145
  };
201
- var TimerTriggerSchema = Schema3.Struct({
202
- kind: Schema3.Literal("timer").annotations(kindLiteralAnnotations),
203
- cron: Schema3.String.annotations({
204
- title: "Cron",
205
- [SchemaAST.ExamplesAnnotationId]: [
206
- "0 0 * * *"
207
- ]
208
- })
209
- }).pipe(Schema3.mutable);
210
- var EmailTriggerSchema = Schema3.Struct({
146
+ var EmailSpec = Schema3.Struct({
211
147
  kind: Schema3.Literal("email").annotations(kindLiteralAnnotations)
212
148
  }).pipe(Schema3.mutable);
213
- var QueueTriggerSchema = Schema3.Struct({
149
+ var QueueSpec = Schema3.Struct({
214
150
  kind: Schema3.Literal("queue").annotations(kindLiteralAnnotations),
215
151
  // TODO(dmaretskyi): Change to a reference.
216
152
  queue: DXN.Schema
217
153
  }).pipe(Schema3.mutable);
218
- var WebhookTriggerSchema = Schema3.Struct({
219
- kind: Schema3.Literal("webhook").annotations(kindLiteralAnnotations),
220
- method: Schema3.optional(Schema3.String.annotations({
221
- title: "Method",
222
- [OptionsAnnotationId]: [
223
- "GET",
224
- "POST"
225
- ]
226
- })),
227
- port: Schema3.optional(Schema3.Number.annotations({
228
- title: "Port"
229
- }))
230
- }).pipe(Schema3.mutable);
231
- var SubscriptionTriggerSchema = Schema3.Struct({
154
+ var SubscriptionSpec = Schema3.Struct({
232
155
  kind: Schema3.Literal("subscription").annotations(kindLiteralAnnotations),
233
156
  query: Schema3.Struct({
234
157
  raw: Schema3.optional(Schema3.String.annotations({
@@ -249,54 +172,37 @@ var SubscriptionTriggerSchema = Schema3.Struct({
249
172
  title: "Options"
250
173
  }))
251
174
  }).pipe(Schema3.mutable);
252
- var TriggerSchema = Schema3.Union(TimerTriggerSchema, WebhookTriggerSchema, SubscriptionTriggerSchema, EmailTriggerSchema, QueueTriggerSchema).annotations({
175
+ var TimerSpec = Schema3.Struct({
176
+ kind: Schema3.Literal("timer").annotations(kindLiteralAnnotations),
177
+ cron: Schema3.String.annotations({
178
+ title: "Cron",
179
+ [SchemaAST.ExamplesAnnotationId]: [
180
+ "0 0 * * *"
181
+ ]
182
+ })
183
+ }).pipe(Schema3.mutable);
184
+ var WebhookSpec = Schema3.Struct({
185
+ kind: Schema3.Literal("webhook").annotations(kindLiteralAnnotations),
186
+ method: Schema3.optional(Schema3.String.annotations({
187
+ title: "Method",
188
+ [OptionsAnnotationId]: [
189
+ "GET",
190
+ "POST"
191
+ ]
192
+ })),
193
+ port: Schema3.optional(Schema3.Number.annotations({
194
+ title: "Port"
195
+ }))
196
+ }).pipe(Schema3.mutable);
197
+ var Spec = Schema3.Union(EmailSpec, QueueSpec, SubscriptionSpec, TimerSpec, WebhookSpec).annotations({
253
198
  title: "Trigger"
254
199
  });
255
- var EmailTriggerOutput = Schema3.mutable(Schema3.Struct({
256
- from: Schema3.String,
257
- to: Schema3.String,
258
- subject: Schema3.String,
259
- created: Schema3.String,
260
- body: Schema3.String
261
- }));
262
- var WebhookTriggerOutput = Schema3.mutable(Schema3.Struct({
263
- url: Schema3.String,
264
- method: Schema3.Literal("GET", "POST"),
265
- headers: Schema3.Record({
266
- key: Schema3.String,
267
- value: Schema3.String
268
- }),
269
- bodyText: Schema3.String
270
- }));
271
- var QueueTriggerOutput = Schema3.mutable(Schema3.Struct({
272
- queue: DXN.Schema,
273
- item: Schema3.Any,
274
- cursor: Schema3.String
275
- }));
276
- var SubscriptionTriggerOutput = Schema3.Struct({
277
- /**
278
- * Type of the mutation.
279
- */
280
- // TODO(dmaretskyi): Specify enum.
281
- type: Schema3.String,
282
- /**
283
- * Reference to the object that was changed or created.
284
- */
285
- subject: Type3.Ref(Obj2.Any),
286
- /**
287
- * @deprecated
288
- */
289
- changedObjectId: Schema3.optional(Schema3.String)
290
- }).pipe(Schema3.mutable);
291
- var TimerTriggerOutput = Schema3.mutable(Schema3.Struct({
292
- tick: Schema3.Number
293
- }));
294
- var FunctionTrigger_ = Schema3.Struct({
200
+ var Trigger_ = Schema3.Struct({
295
201
  /**
296
202
  * Function or workflow to invoke.
297
203
  */
298
204
  // TODO(dmaretskyi): Can be a Ref(FunctionType) or Ref(ComputeGraphType).
299
- function: Schema3.optional(Ref2(Expando).annotations({
205
+ function: Schema3.optional(Ref3(Expando).annotations({
300
206
  title: "Function"
301
207
  })),
302
208
  /**
@@ -310,7 +216,7 @@ var FunctionTrigger_ = Schema3.Struct({
310
216
  enabled: Schema3.optional(Schema3.Boolean.annotations({
311
217
  title: "Enabled"
312
218
  })),
313
- spec: Schema3.optional(TriggerSchema),
219
+ spec: Schema3.optional(Spec),
314
220
  /**
315
221
  * Passed as the input data to the function.
316
222
  * Must match the function's input schema.
@@ -327,963 +233,189 @@ var FunctionTrigger_ = Schema3.Struct({
327
233
  value: Schema3.Any
328
234
  })))
329
235
  }).pipe(Type3.Obj({
330
- typename: "dxos.org/type/FunctionTrigger",
331
- version: "0.2.0"
236
+ typename: "dxos.org/type/Trigger",
237
+ version: "0.1.0"
332
238
  }));
333
- var FunctionTrigger = FunctionTrigger_;
334
- var FunctionManifestSchema = Schema3.Struct({
335
- functions: Schema3.optional(Schema3.mutable(Schema3.Array(RawObject(FunctionType)))),
336
- triggers: Schema3.optional(Schema3.mutable(Schema3.Array(RawObject(FunctionTrigger))))
337
- });
338
- var FUNCTION_TYPES = [
339
- FunctionType,
340
- FunctionTrigger
341
- ];
239
+ var Trigger = Trigger_;
240
+ var make3 = (props) => Obj3.make(Trigger, props);
342
241
 
343
- // src/trace.ts
344
- var __dxlog_file = "/__w/dxos/dxos/packages/core/functions/src/trace.ts";
345
- var InvocationOutcome = /* @__PURE__ */ (function(InvocationOutcome2) {
346
- InvocationOutcome2["SUCCESS"] = "success";
347
- InvocationOutcome2["FAILURE"] = "failure";
348
- InvocationOutcome2["PENDING"] = "pending";
349
- return InvocationOutcome2;
350
- })({});
351
- var InvocationTraceEventType = /* @__PURE__ */ (function(InvocationTraceEventType2) {
352
- InvocationTraceEventType2["START"] = "start";
353
- InvocationTraceEventType2["END"] = "end";
354
- return InvocationTraceEventType2;
355
- })({});
356
- var TraceEventException = Schema4.Struct({
357
- timestamp: Schema4.Number,
358
- message: Schema4.String,
359
- name: Schema4.String,
360
- 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
361
250
  });
362
- var InvocationTraceStartEvent = Schema4.Struct({
363
- /**
364
- * Queue message id.
365
- */
366
- id: ObjectId,
367
- type: Schema4.Literal("start"),
368
- /**
369
- * Invocation id, the same for invocation start and end events.
370
- */
371
- invocationId: ObjectId,
372
- /**
373
- * Event generation time.
374
- */
375
- timestamp: Schema4.Number,
376
- /**
377
- * Data passed to function / workflow as an argument.
378
- */
379
- // TODO(burdon): Input schema?
380
- input: Schema4.Object,
381
- /**
382
- * Queue for function/workflow invocation events.
383
- */
384
- invocationTraceQueue: Schema4.optional(Type4.Ref(Queue)),
385
- /**
386
- * DXN of the invoked function/workflow.
387
- */
388
- invocationTarget: Schema4.optional(Type4.Ref(Type4.Expando)),
389
- /**
390
- * Present for automatic invocations.
391
- */
392
- trigger: Schema4.optional(Type4.Ref(FunctionTrigger))
393
- }).pipe(Type4.Obj({
394
- typename: "dxos.org/type/InvocationTraceStart",
395
- 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
259
+ }));
260
+ var QueueEvent = Schema4.mutable(Schema4.Struct({
261
+ queue: DXN2.Schema,
262
+ item: Schema4.Any,
263
+ cursor: Schema4.String
396
264
  }));
397
- var InvocationTraceEndEvent = Schema4.Struct({
265
+ var SubscriptionEvent = Schema4.Struct({
398
266
  /**
399
- * Trace event id.
267
+ * Type of the mutation.
400
268
  */
401
- id: ObjectId,
402
- type: Schema4.Literal("end"),
269
+ // TODO(dmaretskyi): Specify enum.
270
+ type: Schema4.String,
403
271
  /**
404
- * Invocation id, will be the same for invocation start and end.
272
+ * Reference to the object that was changed or created.
405
273
  */
406
- invocationId: ObjectId,
274
+ subject: Type4.Ref(Obj4.Any),
407
275
  /**
408
- * Event generation time.
276
+ * @deprecated
409
277
  */
410
- // TODO(burdon): Remove ms suffix.
411
- timestamp: Schema4.Number,
412
- outcome: Schema4.Enums(InvocationOutcome),
413
- exception: Schema4.optional(TraceEventException)
414
- }).pipe(Type4.Obj({
415
- typename: "dxos.org/type/InvocationTraceEnd",
416
- 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
417
282
  }));
418
- var TraceEventLog = Schema4.Struct({
419
- timestamp: Schema4.Number,
420
- level: Schema4.String,
421
- message: Schema4.String,
422
- context: Schema4.optional(Schema4.Object)
423
- });
424
- var TraceEvent = Schema4.Struct({
425
- id: ObjectId,
426
- // TODO(burdon): Need enum/numeric result (not string).
427
- outcome: Schema4.String,
428
- truncated: Schema4.Boolean,
429
- /** Time when the event was persisted. */
430
- ingestionTimestamp: Schema4.Number,
431
- logs: Schema4.Array(TraceEventLog),
432
- exceptions: Schema4.Array(TraceEventException)
433
- }).pipe(Type4.Obj({
434
- typename: "dxos.org/type/TraceEvent",
435
- 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
436
291
  }));
437
- var createInvocationSpans = (items) => {
438
- if (!items) {
439
- return [];
440
- }
441
- const eventsByInvocationId = /* @__PURE__ */ new Map();
442
- for (const event of items) {
443
- if (!("invocationId" in event)) {
444
- continue;
445
- }
446
- const invocationId = event.invocationId;
447
- const entry = eventsByInvocationId.get(invocationId) || {
448
- start: void 0,
449
- end: void 0
450
- };
451
- if (event.type === "start") {
452
- entry.start = event;
453
- } else if (event.type === "end") {
454
- entry.end = event;
455
- }
456
- eventsByInvocationId.set(invocationId, entry);
457
- }
458
- const now = Date.now();
459
- const result = [];
460
- for (const [invocationId, { start, end }] of eventsByInvocationId.entries()) {
461
- if (!start) {
462
- log.warn("found end event without matching start", {
463
- invocationId
464
- }, {
465
- F: __dxlog_file,
466
- L: 158,
467
- S: void 0,
468
- C: (f, a) => f(...a)
469
- });
470
- continue;
292
+
293
+ // src/url.ts
294
+ var FUNCTIONS_META_KEY = "dxos.org/service/function";
295
+ var FUNCTIONS_PRESET_META_KEY = "dxos.org/service/function-preset";
296
+ var getUserFunctionIdInMetadata = (meta) => {
297
+ return meta.keys.find((key) => key.source === FUNCTIONS_META_KEY)?.id;
298
+ };
299
+ var setUserFunctionIdInMetadata = (meta, functionId) => {
300
+ const key = meta.keys.find((key2) => key2.source === FUNCTIONS_META_KEY);
301
+ if (key) {
302
+ if (key.id !== functionId) {
303
+ throw new Error("Metadata mismatch");
471
304
  }
472
- const isInProgress = end === void 0;
473
- result.push({
474
- id: invocationId,
475
- timestamp: start.timestamp,
476
- duration: isInProgress ? now - start.timestamp : end.timestamp - start.timestamp,
477
- outcome: end?.outcome ?? "pending",
478
- exception: end?.exception,
479
- input: start.input,
480
- invocationTraceQueue: start.invocationTraceQueue,
481
- invocationTarget: start.invocationTarget,
482
- trigger: start.trigger
305
+ } else {
306
+ meta.keys.push({
307
+ source: FUNCTIONS_META_KEY,
308
+ id: functionId
483
309
  });
484
310
  }
485
- return result;
486
311
  };
487
312
 
488
- // src/triggers/invocation-tracer.ts
489
- import * as Context3 from "effect/Context";
490
- import * as Effect4 from "effect/Effect";
491
- import * as Layer3 from "effect/Layer";
492
- import { Obj as Obj3, Ref as Ref3 } from "@dxos/echo";
493
- import { DXN as DXN2, ObjectId as ObjectId2 } from "@dxos/keys";
494
-
495
- // src/services/function-invocation-service.ts
496
- import * as Context2 from "effect/Context";
497
- import * as Effect3 from "effect/Effect";
498
- import * as Layer2 from "effect/Layer";
499
- import { AiService as AiService2 } from "@dxos/ai";
500
-
501
- // src/services/local-function-execution.ts
502
- import * as Context from "effect/Context";
503
- import * as Effect2 from "effect/Effect";
504
- import * as Layer from "effect/Layer";
505
- import * as Schema5 from "effect/Schema";
506
- import { AiService } from "@dxos/ai";
507
- import { todo } from "@dxos/debug";
508
- import { log as log2 } from "@dxos/log";
509
- function _define_property(obj, key, value) {
510
- if (key in obj) {
511
- Object.defineProperty(obj, key, {
512
- value,
513
- enumerable: true,
514
- configurable: true,
515
- writable: true
516
- });
517
- } else {
518
- obj[key] = value;
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");
519
318
  }
520
- return obj;
521
- }
522
- var __dxlog_file2 = "/__w/dxos/dxos/packages/core/functions/src/services/local-function-execution.ts";
523
- var _Context_Tag;
524
- var LocalFunctionExecutionService = class extends (_Context_Tag = Context.Tag("@dxos/functions/LocalFunctionExecutionService")()) {
525
- };
526
- _define_property(LocalFunctionExecutionService, "layerLive", Layer.effect(LocalFunctionExecutionService, Effect2.gen(function* () {
527
- const resolver = yield* FunctionImplementationResolver;
528
- const ai = yield* AiService.AiService;
529
- const credentials = yield* CredentialsService;
530
- const database = yield* DatabaseService;
531
- const queues = yield* QueueService;
532
- const functionCallService = yield* RemoteFunctionExecutionService;
533
- return {
534
- // TODO(dmaretskyi): Better error types.
535
- invokeFunction: (functionDef, input) => Effect2.gen(function* () {
536
- const resolved = yield* resolver.resolveFunctionImplementation(functionDef).pipe(Effect2.orDie);
537
- const output = yield* invokeFunction(resolved, input);
538
- return output;
539
- }).pipe(Effect2.provideService(AiService.AiService, ai), Effect2.provideService(CredentialsService, credentials), Effect2.provideService(DatabaseService, database), Effect2.provideService(QueueService, queues), Effect2.provideService(RemoteFunctionExecutionService, functionCallService))
540
- };
541
- })));
542
- _define_property(LocalFunctionExecutionService, "invokeFunction", Effect2.serviceFunctionEffect(LocalFunctionExecutionService, (_) => _.invokeFunction));
543
- var invokeFunction = (functionDef, input) => Effect2.gen(function* () {
544
- try {
545
- const assertInput = functionDef.inputSchema.pipe(Schema5.asserts);
546
- assertInput(input);
547
- } catch (e) {
548
- throw new FunctionError({
549
- message: "Invalid function input",
550
- context: {
551
- name: functionDef.name
552
- },
553
- cause: e
554
- });
319
+ if (typeof handler !== "function") {
320
+ throw new Error("Handler must be a function");
555
321
  }
556
- const context = {
557
- space: void 0,
558
- getService: () => todo(),
559
- getSpace: async (_spaceId) => {
560
- throw new Error("Not available. Use the database service instead.");
561
- }
562
- };
563
- log2.info("invoking function", {
564
- name: functionDef.name,
565
- input
566
- }, {
567
- F: __dxlog_file2,
568
- L: 98,
569
- S: this,
570
- C: (f, a) => f(...a)
571
- });
572
- const data = yield* Effect2.gen(function* () {
573
- const result = functionDef.handler({
574
- context,
575
- data: input
576
- });
577
- if (Effect2.isEffect(result)) {
578
- return yield* result.pipe(Effect2.orDie);
579
- } else if (typeof result === "object" && result !== null && "then" in result && typeof result.then === "function") {
580
- return yield* Effect2.promise(() => result);
581
- } else {
582
- return result;
583
- }
584
- }).pipe(Effect2.orDie, Effect2.catchAllDefect((defect) => Effect2.die(new FunctionError({
585
- context: {
586
- name: functionDef.name
587
- },
588
- cause: defect
589
- }))));
590
- log2.info("completed", {
591
- function: functionDef.name,
592
- input,
593
- data
594
- }, {
595
- F: __dxlog_file2,
596
- L: 122,
597
- S: this,
598
- C: (f, a) => f(...a)
599
- });
600
- try {
601
- const assertOutput = functionDef.outputSchema?.pipe(Schema5.asserts);
602
- assertOutput(data);
603
- } catch (e) {
604
- throw new FunctionError({
605
- message: "Invalid function output",
606
- context: {
607
- name: functionDef.name
608
- },
609
- cause: e
610
- });
611
- }
612
- return data;
613
- }).pipe(Effect2.withSpan("invokeFunction", {
614
- attributes: {
615
- name: functionDef.name
616
- }
617
- }));
618
- var _Context_Tag1;
619
- var FunctionImplementationResolver = class extends (_Context_Tag1 = Context.Tag("@dxos/functions/FunctionImplementationResolver")()) {
620
- };
621
- _define_property(FunctionImplementationResolver, "layerTest", ({ functions }) => Layer.succeed(FunctionImplementationResolver, {
622
- resolveFunctionImplementation: (functionDef) => {
623
- const resolved = functions.find((f) => f.key === functionDef.key);
624
- if (!resolved) {
625
- return Effect2.fail(new FunctionNotFoundError(functionDef.name));
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;
626
330
  }
627
- return Effect2.succeed(resolved);
628
- }
629
- }));
630
-
631
- // src/services/function-invocation-service.ts
632
- function _define_property2(obj, key, value) {
633
- if (key in obj) {
634
- Object.defineProperty(obj, key, {
635
- value,
636
- enumerable: true,
637
- configurable: true,
638
- writable: true
639
- });
640
- } else {
641
- obj[key] = value;
642
- }
643
- return obj;
644
- }
645
- var _Context_Tag2;
646
- var FunctionInvocationService = class extends (_Context_Tag2 = Context2.Tag("@dxos/functions/FunctionInvocationService")()) {
647
- };
648
- _define_property2(FunctionInvocationService, "invokeFunction", Effect3.serviceFunctionEffect(FunctionInvocationService, (_) => _.invokeFunction));
649
- _define_property2(FunctionInvocationService, "layer", Layer2.effect(FunctionInvocationService, Effect3.gen(function* () {
650
- const localExecutioner = yield* LocalFunctionExecutionService;
651
- const remoteExecutioner = yield* RemoteFunctionExecutionService;
652
- return {
653
- invokeFunction: (functionDef, input) => Effect3.gen(function* () {
654
- if (functionDef.meta?.deployedFunctionId) {
655
- return yield* remoteExecutioner.callFunction(functionDef.meta.deployedFunctionId, input);
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;
656
336
  }
657
- return yield* localExecutioner.invokeFunction(functionDef, input);
658
- })
337
+ }
659
338
  };
660
- })));
661
- _define_property2(FunctionInvocationService, "layerTest", ({ functions = [] } = {}) => FunctionInvocationService.layer.pipe(Layer2.provide(LocalFunctionExecutionService.layerLive), Layer2.provide(FunctionImplementationResolver.layerTest({
662
- functions
663
- })), Layer2.provide(RemoteFunctionExecutionService.layerMock)));
664
- _define_property2(FunctionInvocationService, "layerTestMocked", ({ functions }) => FunctionInvocationService.layerTest({
665
- functions
666
- }).pipe(Layer2.provide(AiService2.notAvailable), Layer2.provide(CredentialsService.configuredLayer([])), Layer2.provide(DatabaseService.notAvailable), Layer2.provide(QueueService.notAvailable)));
667
-
668
- // src/triggers/invocation-tracer.ts
669
- function _define_property3(obj, key, value) {
670
- if (key in obj) {
671
- Object.defineProperty(obj, key, {
672
- value,
673
- enumerable: true,
674
- configurable: true,
675
- writable: true
676
- });
677
- } else {
678
- obj[key] = value;
679
- }
680
- return obj;
681
- }
682
- var _Context_Tag3;
683
- var InvocationTracer = class extends (_Context_Tag3 = Context3.Tag("@dxos/functions/InvocationTracer")()) {
684
- };
685
- _define_property3(InvocationTracer, "layerLive", (opts) => Layer3.effect(InvocationTracer, Effect4.gen(function* () {
686
- return {
687
- traceInvocationStart: Effect4.fn("traceInvocationStart")(function* ({ payload, target }) {
688
- const invocationId = ObjectId2.random();
689
- const invocationTraceQueue = yield* QueueService.createQueue({
690
- subspaceTag: "trace"
691
- });
692
- const now = Date.now();
693
- const traceEvent = Obj3.make(InvocationTraceStartEvent, {
694
- type: InvocationTraceEventType.START,
695
- invocationId,
696
- timestamp: now,
697
- // TODO(dmaretskyi): Not json-stringifying this makes ECHO fail when one ECHO object becomes embedded in another ECHO object.
698
- input: JSON.parse(JSON.stringify(payload.data ?? {})),
699
- invocationTraceQueue: Ref3.fromDXN(invocationTraceQueue.dxn),
700
- invocationTarget: target ? Ref3.fromDXN(target) : void 0,
701
- trigger: payload.trigger ? Ref3.fromDXN(DXN2.fromLocalObjectId(payload.trigger.id)) : void 0
702
- });
703
- yield* QueueService.append(opts.invocationTraceQueue, [
704
- traceEvent
705
- ]);
706
- return {
707
- invocationId,
708
- invocationTraceQueue
709
- };
710
- }),
711
- traceInvocationEnd: Effect4.fn("traceInvocationEnd")(function* ({ trace, exception }) {
712
- const now = Date.now();
713
- const traceEvent = Obj3.make(InvocationTraceEndEvent, {
714
- type: InvocationTraceEventType.END,
715
- invocationId: trace.invocationId,
716
- timestamp: now,
717
- outcome: exception ? InvocationOutcome.FAILURE : InvocationOutcome.SUCCESS,
718
- exception: exception ? {
719
- name: exception.constructor.name,
720
- timestamp: now,
721
- message: exception?.message ?? "Unknown error",
722
- stack: exception?.stack
723
- } : void 0
339
+ const handlerWithSpan = (...args) => {
340
+ const result = handler(...args);
341
+ if (Effect.isEffect(result)) {
342
+ return Effect.withSpan(result, `${key ?? name}`, {
343
+ captureStackTrace
724
344
  });
725
- yield* QueueService.append(opts.invocationTraceQueue, [
726
- traceEvent
727
- ]);
728
- })
729
- };
730
- })));
731
- _define_property3(InvocationTracer, "layerTest", Layer3.unwrapEffect(Effect4.gen(function* () {
732
- const queue = yield* QueueService.createQueue({
733
- subspaceTag: "trace"
734
- });
735
- return InvocationTracer.layerLive({
736
- invocationTraceQueue: queue
737
- });
738
- })));
739
-
740
- // src/triggers/trigger-dispatcher.ts
741
- import * as Cause from "effect/Cause";
742
- import * as Context5 from "effect/Context";
743
- import * as Cron from "effect/Cron";
744
- import * as Duration from "effect/Duration";
745
- import * as Effect6 from "effect/Effect";
746
- import * as Either from "effect/Either";
747
- import * as Exit from "effect/Exit";
748
- import * as Fiber from "effect/Fiber";
749
- import * as Layer5 from "effect/Layer";
750
- import * as Option2 from "effect/Option";
751
- import * as Record3 from "effect/Record";
752
- import * as Schedule from "effect/Schedule";
753
- import { DXN as DXN3, Filter, Obj as Obj4, Query } from "@dxos/echo";
754
- import { causeToError } from "@dxos/effect";
755
- import { invariant } from "@dxos/invariant";
756
- import { log as log3 } from "@dxos/log";
757
- import { KEY_QUEUE_POSITION } from "@dxos/protocols";
758
-
759
- // src/triggers/input-builder.ts
760
- var createInvocationPayload = (trigger, event) => {
761
- if (!trigger.input) {
762
- return event;
763
- }
764
- const payload = {};
765
- for (const [key, value] of Object.entries(trigger.input)) {
766
- if (typeof value !== "string" || !(value.startsWith("{{") && value.endsWith("}}"))) {
767
- payload[key] = value;
768
- continue;
769
- }
770
- const propertyPath = value.slice(2, -2);
771
- let valueSubstitution = propertyPath.startsWith("trigger.") ? trigger : propertyPath.startsWith("event.") ? event : void 0;
772
- for (const pathSegment of propertyPath.split(".").slice(1)) {
773
- if (valueSubstitution && typeof valueSubstitution === "object") {
774
- valueSubstitution = valueSubstitution[pathSegment];
775
- }
776
345
  }
777
- payload[key] = valueSubstitution;
778
- }
779
- return payload;
780
- };
781
-
782
- // src/triggers/trigger-state-store.ts
783
- import * as KeyValueStore from "@effect/platform/KeyValueStore";
784
- import * as Context4 from "effect/Context";
785
- import * as Effect5 from "effect/Effect";
786
- import * as Layer4 from "effect/Layer";
787
- import * as Option from "effect/Option";
788
- import * as Schema6 from "effect/Schema";
789
- import { ObjectId as ObjectId3 } from "@dxos/keys";
790
- function _define_property4(obj, key, value) {
791
- if (key in obj) {
792
- Object.defineProperty(obj, key, {
793
- value,
794
- enumerable: true,
795
- configurable: true,
796
- writable: true
797
- });
798
- } else {
799
- obj[key] = value;
800
- }
801
- return obj;
802
- }
803
- var TriggerState = Schema6.Struct({
804
- version: Schema6.Literal("1"),
805
- triggerId: Schema6.String,
806
- state: Schema6.optional(Schema6.Union(Schema6.TaggedStruct("subscription", {
807
- processedVersions: Schema6.Record({
808
- key: ObjectId3,
809
- value: Schema6.String
810
- })
811
- })))
812
- });
813
- var _Context_Tag4;
814
- var TriggerStateStore = class extends (_Context_Tag4 = Context4.Tag("@dxos/functions/TriggerStateStore")()) {
815
- };
816
- _define_property4(TriggerStateStore, "getState", Effect5.serviceFunctionEffect(TriggerStateStore, (_) => _.getState));
817
- _define_property4(TriggerStateStore, "saveState", Effect5.serviceFunctionEffect(TriggerStateStore, (_) => _.saveState));
818
- _define_property4(TriggerStateStore, "layerKv", Layer4.effect(TriggerStateStore, Effect5.gen(function* () {
819
- const kv = yield* KeyValueStore.KeyValueStore;
820
- const schemaStore = kv.forSchema(Schema6.parseJson(TriggerState));
821
- const store = {
822
- getState: Effect5.fn("TriggerStateStore.getState")(function* (triggerId) {
823
- const valueOption = yield* schemaStore.get(triggerId).pipe(Effect5.orDie);
824
- if (Option.isNone(valueOption)) {
825
- return yield* Effect5.fail(new TriggerStateNotFoundError());
826
- }
827
- return valueOption.value;
828
- }),
829
- saveState: Effect5.fn("TriggerStateStore.saveState")(function* (state) {
830
- yield* schemaStore.set(state.triggerId, state).pipe(Effect5.orDie);
831
- })
346
+ return result;
347
+ };
348
+ return {
349
+ [typeId]: true,
350
+ key,
351
+ name,
352
+ description,
353
+ inputSchema,
354
+ outputSchema,
355
+ handler: handlerWithSpan
832
356
  };
833
- return store;
834
- })));
835
- _define_property4(TriggerStateStore, "layerMemory", TriggerStateStore.layerKv.pipe(Layer4.provide(KeyValueStore.layerMemory)));
836
-
837
- // src/triggers/trigger-dispatcher.ts
838
- function _define_property5(obj, key, value) {
839
- if (key in obj) {
840
- Object.defineProperty(obj, key, {
841
- value,
842
- enumerable: true,
843
- configurable: true,
844
- writable: true
845
- });
846
- } else {
847
- obj[key] = value;
848
- }
849
- return obj;
850
- }
851
- var __dxlog_file3 = "/__w/dxos/dxos/packages/core/functions/src/triggers/trigger-dispatcher.ts";
852
- var _Context_Tag5;
853
- var TriggerDispatcher = class extends (_Context_Tag5 = Context5.Tag("@dxos/functions/TriggerDispatcher")()) {
854
357
  };
855
- _define_property5(TriggerDispatcher, "layer", (options) => Layer5.effect(TriggerDispatcher, Effect6.gen(function* () {
856
- return new TriggerDispatcherImpl(options);
857
- })));
858
- var TriggerDispatcherImpl = class {
859
- get running() {
860
- return this._running;
861
- }
862
- constructor(options) {
863
- _define_property5(this, "livePollInterval", void 0);
864
- _define_property5(this, "timeControl", void 0);
865
- _define_property5(this, "_running", false);
866
- _define_property5(this, "_internalTime", void 0);
867
- _define_property5(this, "_timerFiber", void 0);
868
- _define_property5(this, "_scheduledTriggers", /* @__PURE__ */ new Map());
869
- _define_property5(this, "start", () => Effect6.gen(this, function* () {
870
- if (this._running) {
871
- return;
872
- }
873
- this._running = true;
874
- if (this.timeControl === "natural") {
875
- this._timerFiber = yield* this._startNaturalTimeProcessing().pipe(Effect6.tapErrorCause((cause) => {
876
- const error = causeToError(cause);
877
- log3.error("trigger dispatcher error", {
878
- error
879
- }, {
880
- F: __dxlog_file3,
881
- L: 187,
882
- S: this,
883
- C: (f, a) => f(...a)
884
- });
885
- this._running = false;
886
- return Effect6.void;
887
- }), Effect6.forkDaemon);
888
- } else {
889
- return yield* Effect6.dieMessage("TriggerDispatcher started in manual time control mode");
890
- }
891
- log3.info("TriggerDispatcher started", {
892
- timeControl: this.timeControl
893
- }, {
894
- F: __dxlog_file3,
895
- L: 197,
896
- S: this,
897
- C: (f, a) => f(...a)
898
- });
899
- }));
900
- _define_property5(this, "stop", () => Effect6.gen(this, function* () {
901
- if (!this._running) {
902
- return;
903
- }
904
- this._running = false;
905
- if (this._timerFiber) {
906
- yield* Fiber.interrupt(this._timerFiber);
907
- this._timerFiber = void 0;
908
- }
909
- this._scheduledTriggers.clear();
910
- log3.info("TriggerDispatcher stopped", void 0, {
911
- F: __dxlog_file3,
912
- L: 217,
913
- S: this,
914
- C: (f, a) => f(...a)
915
- });
916
- }));
917
- _define_property5(this, "invokeTrigger", (options2) => Effect6.gen(this, function* () {
918
- const { trigger, event } = options2;
919
- log3.info("running trigger", {
920
- triggerId: trigger.id,
921
- spec: trigger.spec,
922
- event
923
- }, {
924
- F: __dxlog_file3,
925
- L: 225,
926
- S: this,
927
- C: (f, a) => f(...a)
928
- });
929
- const tracer = yield* InvocationTracer;
930
- const trace = yield* tracer.traceInvocationStart({
931
- target: trigger.function?.dxn,
932
- payload: {
933
- trigger: {
934
- id: trigger.id,
935
- // TODO(dmaretskyi): Is `spec` always there>
936
- kind: trigger.spec.kind
937
- },
938
- data: event
939
- }
940
- });
941
- const result = yield* Effect6.gen(this, function* () {
942
- if (!trigger.enabled) {
943
- return yield* Effect6.dieMessage("Attempting to invoke disabled trigger");
944
- }
945
- if (!trigger.function) {
946
- return yield* Effect6.dieMessage("Trigger has no function reference");
947
- }
948
- const serialiedFunction = yield* DatabaseService.load(trigger.function).pipe(Effect6.orDie);
949
- invariant(Obj4.instanceOf(FunctionType, serialiedFunction), void 0, {
950
- F: __dxlog_file3,
951
- L: 252,
952
- S: this,
953
- A: [
954
- "Obj.instanceOf(FunctionType, serialiedFunction)",
955
- ""
956
- ]
957
- });
958
- const functionDef = deserializeFunction(serialiedFunction);
959
- const inputData = this._prepareInputData(trigger, event);
960
- return yield* FunctionInvocationService.invokeFunction(functionDef, inputData).pipe(Effect6.provide(ComputeEventLogger.layerFromTracing.pipe(Layer5.provideMerge(TracingService.layerQueue(trace.invocationTraceQueue)))));
961
- }).pipe(Effect6.exit);
962
- const triggerExecutionResult = {
963
- triggerId: trigger.id,
964
- result
965
- };
966
- if (Exit.isSuccess(result)) {
967
- log3.info("trigger execution success", {
968
- triggerId: trigger.id
969
- }, {
970
- F: __dxlog_file3,
971
- L: 273,
972
- S: this,
973
- C: (f, a) => f(...a)
974
- });
975
- } else {
976
- log3.error("trigger execution failure", {
977
- error: causeToError(result.cause)
978
- }, {
979
- F: __dxlog_file3,
980
- L: 277,
981
- S: this,
982
- C: (f, a) => f(...a)
983
- });
984
- }
985
- yield* tracer.traceInvocationEnd({
986
- trace,
987
- // TODO(dmaretskyi): Might miss errors.
988
- exception: Exit.isFailure(result) ? Cause.prettyErrors(result.cause)[0] : void 0
989
- });
990
- return triggerExecutionResult;
991
- }));
992
- _define_property5(this, "invokeScheduledTriggers", ({ kinds = [
993
- "timer",
994
- "queue",
995
- "subscription"
996
- ] } = {}) => Effect6.gen(this, function* () {
997
- const invocations = [];
998
- for (const kind of kinds) {
999
- switch (kind) {
1000
- case "timer":
1001
- {
1002
- yield* this.refreshTriggers();
1003
- const now = this.getCurrentTime();
1004
- const triggersToInvoke = [];
1005
- for (const [triggerId, scheduledTrigger] of this._scheduledTriggers.entries()) {
1006
- if (scheduledTrigger.nextExecution <= now) {
1007
- triggersToInvoke.push(scheduledTrigger.trigger);
1008
- scheduledTrigger.nextExecution = Cron.next(scheduledTrigger.cron, now);
1009
- }
1010
- }
1011
- invocations.push(...yield* Effect6.forEach(triggersToInvoke, (trigger) => this.invokeTrigger({
1012
- trigger,
1013
- event: {
1014
- tick: now.getTime()
1015
- }
1016
- }), {
1017
- concurrency: 1
1018
- }));
1019
- }
1020
- break;
1021
- case "queue": {
1022
- const triggers = yield* this._fetchTriggers();
1023
- for (const trigger of triggers) {
1024
- const spec = trigger.spec;
1025
- if (spec?.kind !== "queue") {
1026
- continue;
1027
- }
1028
- const cursor = Obj4.getKeys(trigger, KEY_QUEUE_CURSOR).at(0)?.id;
1029
- const queue = yield* QueueService.getQueue(DXN3.parse(spec.queue));
1030
- const objects = yield* Effect6.promise(() => queue.queryObjects());
1031
- for (const object of objects) {
1032
- const objectPos = Obj4.getKeys(object, KEY_QUEUE_POSITION).at(0)?.id;
1033
- if (!objectPos || cursor && parseInt(cursor) >= parseInt(objectPos)) {
1034
- continue;
1035
- }
1036
- invocations.push(yield* this.invokeTrigger({
1037
- trigger,
1038
- event: {
1039
- queue: spec.queue,
1040
- item: object,
1041
- cursor: objectPos
1042
- }
1043
- }));
1044
- Obj4.deleteKeys(trigger, KEY_QUEUE_CURSOR);
1045
- Obj4.getMeta(trigger).keys.push({
1046
- source: KEY_QUEUE_CURSOR,
1047
- id: objectPos
1048
- });
1049
- yield* DatabaseService.flush();
1050
- break;
1051
- }
1052
- }
1053
- break;
1054
- }
1055
- case "subscription": {
1056
- const triggers = yield* this._fetchTriggers();
1057
- for (const trigger of triggers) {
1058
- const spec = Obj4.getSnapshot(trigger).spec;
1059
- if (spec?.kind !== "subscription") {
1060
- continue;
1061
- }
1062
- const { objects } = yield* DatabaseService.runQuery(Query.fromAst(spec.query.ast));
1063
- const state = yield* TriggerStateStore.getState(trigger.id).pipe(Effect6.catchTag("TRIGGER_STATE_NOT_FOUND", () => Effect6.succeed({
1064
- version: "1",
1065
- triggerId: trigger.id,
1066
- state: {
1067
- _tag: "subscription",
1068
- processedVersions: {}
1069
- }
1070
- })));
1071
- invariant(state.state?._tag === "subscription", void 0, {
1072
- F: __dxlog_file3,
1073
- L: 390,
1074
- S: this,
1075
- A: [
1076
- "state.state?._tag === 'subscription'",
1077
- ""
1078
- ]
1079
- });
1080
- let updated = false;
1081
- for (const object of objects) {
1082
- const existingVersion = Record3.get(state.state.processedVersions, object.id).pipe(Option2.map(Obj4.decodeVersion));
1083
- const currentVersion = Obj4.version(object);
1084
- const run = Option2.isNone(existingVersion) || Obj4.compareVersions(currentVersion, existingVersion.value) === "different";
1085
- if (!run) {
1086
- continue;
1087
- }
1088
- const { db } = yield* DatabaseService;
1089
- invocations.push(yield* this.invokeTrigger({
1090
- trigger,
1091
- event: {
1092
- // TODO(dmaretskyi): Change type not supported.
1093
- type: "unknown",
1094
- subject: db.ref(Obj4.getDXN(object)),
1095
- changedObjectId: object.id
1096
- }
1097
- }));
1098
- state.state.processedVersions[object.id] = Obj4.encodeVersion(currentVersion);
1099
- updated = true;
1100
- }
1101
- if (updated) {
1102
- yield* TriggerStateStore.saveState(state);
1103
- }
1104
- }
1105
- break;
1106
- }
1107
- default: {
1108
- return yield* Effect6.dieMessage(`Unknown trigger kind: ${kind}`);
1109
- }
1110
- }
1111
- }
1112
- return invocations;
1113
- }));
1114
- _define_property5(this, "advanceTime", (duration) => Effect6.gen(this, function* () {
1115
- if (this.timeControl !== "manual") {
1116
- return yield* Effect6.dieMessage("advanceTime can only be used in manual time control mode");
1117
- }
1118
- const millis = Duration.toMillis(duration);
1119
- this._internalTime = new Date(this._internalTime.getTime() + millis);
1120
- log3("Advanced internal time", {
1121
- newTime: this._internalTime,
1122
- advancedBy: Duration.format(duration)
1123
- }, {
1124
- F: __dxlog_file3,
1125
- L: 447,
1126
- S: this,
1127
- C: (f, a) => f(...a)
1128
- });
1129
- }).pipe(Effect6.orDie));
1130
- _define_property5(this, "getCurrentTime", () => {
1131
- if (this.timeControl === "natural") {
1132
- return /* @__PURE__ */ new Date();
1133
- } else {
1134
- return new Date(this._internalTime);
1135
- }
1136
- });
1137
- _define_property5(this, "refreshTriggers", () => Effect6.gen(this, function* () {
1138
- const triggers = yield* this._fetchTriggers();
1139
- const currentTriggerIds = new Set(triggers.map((t) => t.id));
1140
- for (const triggerId of this._scheduledTriggers.keys()) {
1141
- if (!currentTriggerIds.has(triggerId)) {
1142
- this._scheduledTriggers.delete(triggerId);
1143
- }
1144
- }
1145
- for (const trigger of triggers) {
1146
- if (trigger.spec?.kind === "timer" && trigger.enabled) {
1147
- const timerSpec = trigger.spec;
1148
- const cronEither = Cron.parse(timerSpec.cron);
1149
- if (Either.isRight(cronEither)) {
1150
- const cron = cronEither.right;
1151
- const existing = this._scheduledTriggers.get(trigger.id);
1152
- const now = this.getCurrentTime();
1153
- const nextExecution = existing?.nextExecution ?? Cron.next(cron, now);
1154
- log3("Updated scheduled trigger", {
1155
- triggerId: trigger.id,
1156
- cron: timerSpec.cron,
1157
- nextExecution,
1158
- now
1159
- }, {
1160
- F: __dxlog_file3,
1161
- L: 487,
1162
- S: this,
1163
- C: (f, a) => f(...a)
1164
- });
1165
- this._scheduledTriggers.set(trigger.id, {
1166
- trigger,
1167
- cron,
1168
- nextExecution
1169
- });
1170
- } else {
1171
- log3.error("Invalid cron expression", {
1172
- triggerId: trigger.id,
1173
- cron: timerSpec.cron,
1174
- error: cronEither.left.message
1175
- }, {
1176
- F: __dxlog_file3,
1177
- L: 499,
1178
- S: this,
1179
- C: (f, a) => f(...a)
1180
- });
1181
- }
1182
- }
1183
- }
1184
- log3("Updated scheduled triggers", {
1185
- count: this._scheduledTriggers.size
1186
- }, {
1187
- F: __dxlog_file3,
1188
- L: 508,
1189
- S: this,
1190
- C: (f, a) => f(...a)
1191
- });
1192
- }).pipe(Effect6.withSpan("TriggerDispatcher.refreshTriggers")));
1193
- _define_property5(this, "_fetchTriggers", () => Effect6.gen(this, function* () {
1194
- const { objects } = yield* DatabaseService.runQuery(Filter.type(FunctionTrigger));
1195
- return objects;
1196
- }).pipe(Effect6.withSpan("TriggerDispatcher.fetchTriggers")));
1197
- _define_property5(this, "_startNaturalTimeProcessing", () => Effect6.gen(this, function* () {
1198
- yield* this.invokeScheduledTriggers();
1199
- }).pipe(Effect6.repeat(Schedule.fixed(this.livePollInterval)), Effect6.asVoid));
1200
- _define_property5(this, "_prepareInputData", (trigger, event) => {
1201
- return createInvocationPayload(trigger, event);
1202
- });
1203
- this.timeControl = options.timeControl;
1204
- this.livePollInterval = options.livePollInterval ?? Duration.seconds(1);
1205
- this._internalTime = options.startingTime ?? /* @__PURE__ */ new Date();
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);
1206
370
  }
1207
371
  };
1208
- var KEY_QUEUE_CURSOR = "dxos.org/key/local-trigger-dispatcher/queue-cursor";
1209
-
1210
- // src/executor/executor.ts
1211
- import * as Effect7 from "effect/Effect";
1212
- import * as Schema7 from "effect/Schema";
1213
- import { runAndForwardErrors } from "@dxos/effect";
1214
- function _define_property6(obj, key, value) {
1215
- if (key in obj) {
1216
- Object.defineProperty(obj, key, {
1217
- value,
1218
- enumerable: true,
1219
- configurable: true,
1220
- writable: true
1221
- });
1222
- } else {
1223
- obj[key] = value;
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);
1224
383
  }
1225
- return obj;
1226
- }
1227
- var FunctionExecutor = class {
1228
- /**
1229
- * Invoke function.
1230
- */
1231
- // TODO(dmaretskyi): Invocation context: queue, space, etc...
1232
- async invoke(functionDef, input) {
1233
- const assertInput = functionDef.inputSchema.pipe(Schema7.asserts);
1234
- assertInput(input);
1235
- const context = {
1236
- space: void 0,
1237
- getService: this._services.getService.bind(this._services),
1238
- getSpace: async (_spaceId) => {
1239
- throw new Error("Not available. Use the database service instead.");
1240
- }
1241
- };
1242
- const result = functionDef.handler({
1243
- context,
1244
- data: input
1245
- });
1246
- let data;
1247
- if (Effect7.isEffect(result)) {
1248
- data = await result.pipe(Effect7.provide(this._services.createLayer()), runAndForwardErrors);
1249
- } else {
1250
- data = await result;
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))
1251
400
  }
1252
- const assertOutput = functionDef.outputSchema?.pipe(Schema7.asserts);
1253
- assertOutput(data);
1254
- return data;
1255
- }
1256
- constructor(_services) {
1257
- _define_property6(this, "_services", void 0);
1258
- this._services = _services;
1259
- }
401
+ };
1260
402
  };
1261
403
 
1262
- // src/examples/index.ts
1263
- var examples_exports = {};
1264
- __export(examples_exports, {
1265
- fib: () => fib_default,
1266
- reply: () => reply_default,
1267
- sleep: () => sleep_default
1268
- });
1269
-
1270
- // src/examples/fib.ts
1271
- import * as Effect8 from "effect/Effect";
1272
- import * as Schema8 from "effect/Schema";
404
+ // src/example/fib.ts
1273
405
  var fib_default = defineFunction({
1274
406
  key: "example.org/function/fib",
1275
407
  name: "Fibonacci",
1276
408
  description: "Function that calculates a Fibonacci number",
1277
- inputSchema: Schema8.Struct({
1278
- iterations: Schema8.optional(Schema8.Number).annotations({
409
+ inputSchema: Schema6.Struct({
410
+ iterations: Schema6.optional(Schema6.Number).annotations({
1279
411
  description: "Number of iterations",
1280
412
  default: 1e5
1281
413
  })
1282
414
  }),
1283
- outputSchema: Schema8.Struct({
1284
- result: Schema8.String
415
+ outputSchema: Schema6.Struct({
416
+ result: Schema6.String
1285
417
  }),
1286
- handler: Effect8.fn(function* ({ data: { iterations = 1e5 } }) {
418
+ handler: Effect2.fn(function* ({ data: { iterations = 1e5 } }) {
1287
419
  let a = 0n;
1288
420
  let b = 1n;
1289
421
  for (let i = 0; i < iterations; i++) {
@@ -1296,17 +428,17 @@ var fib_default = defineFunction({
1296
428
  })
1297
429
  });
1298
430
 
1299
- // src/examples/reply.ts
431
+ // src/example/reply.ts
1300
432
  import * as Console from "effect/Console";
1301
- import * as Effect9 from "effect/Effect";
1302
- import * as Schema9 from "effect/Schema";
433
+ import * as Effect3 from "effect/Effect";
434
+ import * as Schema7 from "effect/Schema";
1303
435
  var reply_default = defineFunction({
1304
436
  key: "example.org/function/reply",
1305
437
  name: "Reply",
1306
438
  description: "Function that echoes the input",
1307
- inputSchema: Schema9.Any,
1308
- outputSchema: Schema9.Any,
1309
- handler: Effect9.fn(function* ({ data }) {
439
+ inputSchema: Schema7.Any,
440
+ outputSchema: Schema7.Any,
441
+ handler: Effect3.fn(function* ({ data }) {
1310
442
  yield* Console.log("reply", {
1311
443
  data
1312
444
  });
@@ -1314,24 +446,327 @@ var reply_default = defineFunction({
1314
446
  })
1315
447
  });
1316
448
 
1317
- // src/examples/sleep.ts
1318
- import * as Effect10 from "effect/Effect";
1319
- import * as Schema10 from "effect/Schema";
449
+ // src/example/sleep.ts
450
+ import * as Effect4 from "effect/Effect";
451
+ import * as Schema8 from "effect/Schema";
1320
452
  var sleep_default = defineFunction({
1321
453
  key: "example.org/function/sleep",
1322
454
  name: "Sleep",
1323
455
  description: "Function that sleeps for a given amount of time",
1324
- inputSchema: Schema10.Struct({
1325
- duration: Schema10.optional(Schema10.Number).annotations({
456
+ inputSchema: Schema8.Struct({
457
+ duration: Schema8.optional(Schema8.Number).annotations({
1326
458
  description: "Milliseconds to sleep",
1327
459
  default: 1e5
1328
460
  })
1329
461
  }),
1330
- outputSchema: Schema10.Void,
1331
- handler: Effect10.fn(function* ({ data: { duration = 1e5 } }) {
1332
- yield* Effect10.sleep(duration);
462
+ outputSchema: Schema8.Void,
463
+ handler: Effect4.fn(function* ({ data: { duration = 1e5 } }) {
464
+ yield* Effect4.sleep(duration);
1333
465
  })
1334
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;
552
+ }
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
+ }));
559
+
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");
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));
764
+ };
765
+ var ContextQueueService = class _ContextQueueService extends Context5.Tag("@dxos/functions/ContextQueueService")() {
766
+ static layer = (queue) => Layer4.succeed(_ContextQueueService, {
767
+ queue
768
+ });
769
+ };
1335
770
  export {
1336
771
  ComputeEvent,
1337
772
  ComputeEventLogger,
@@ -1339,54 +774,27 @@ export {
1339
774
  ConfiguredCredentialsService,
1340
775
  ContextQueueService,
1341
776
  CredentialsService,
1342
- DatabaseService,
1343
- EmailTriggerOutput,
777
+ DatabaseService2 as DatabaseService,
778
+ Example,
1344
779
  FUNCTIONS_META_KEY,
1345
780
  FUNCTIONS_PRESET_META_KEY,
1346
- FUNCTION_TYPES,
781
+ Function_exports as Function,
1347
782
  FunctionDefinition,
1348
783
  FunctionError,
1349
- FunctionExecutor,
1350
- FunctionImplementationResolver,
1351
784
  FunctionInvocationService,
1352
- FunctionManifestSchema,
1353
785
  FunctionNotFoundError,
1354
- FunctionTrigger,
1355
- FunctionType,
1356
- InvocationOutcome,
1357
- InvocationTraceEndEvent,
1358
- InvocationTraceEventType,
1359
- InvocationTraceStartEvent,
1360
- InvocationTracer,
1361
- LocalFunctionExecutionService,
1362
786
  MESSAGE_PROPERTY_TOOL_CALL_ID,
1363
787
  QueueService,
1364
- QueueTriggerOutput,
1365
- RemoteFunctionExecutionService,
1366
- SERVICE_TAGS,
1367
- ScriptType,
1368
- ServiceContainer,
788
+ Script_exports as Script,
1369
789
  ServiceNotAvailableError,
1370
- SubscriptionTriggerOutput,
1371
- TimerTriggerOutput,
1372
- TraceEvent,
1373
- TraceEventException,
1374
- TraceEventLog,
1375
790
  TracingService,
1376
- TriggerDispatcher,
1377
- TriggerKinds,
1378
- TriggerSchema,
1379
- TriggerState,
791
+ Trigger_exports as Trigger,
792
+ TriggerEvent_exports as TriggerEvent,
1380
793
  TriggerStateNotFoundError,
1381
- TriggerStateStore,
1382
- WebhookTriggerOutput,
1383
794
  createDefectLogger,
1384
795
  createEventLogger,
1385
- createInvocationSpans,
1386
796
  defineFunction,
1387
797
  deserializeFunction,
1388
- examples_exports as exampleFunctions,
1389
- getInvocationUrl,
1390
798
  getUserFunctionIdInMetadata,
1391
799
  logCustomEvent,
1392
800
  serializeFunction,