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