@dxos/functions 0.8.4-main.5ad4a44 → 0.8.4-main.66e292d

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 (191) hide show
  1. package/dist/lib/browser/index.mjs +830 -1195
  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 +830 -1195
  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 +28 -36
  8. package/dist/types/src/errors.d.ts.map +1 -1
  9. package/dist/types/src/{examples → example}/fib.d.ts +1 -1
  10. package/dist/types/src/example/fib.d.ts.map +1 -0
  11. package/dist/types/src/example/forex-effect.d.ts +3 -0
  12. package/dist/types/src/example/forex-effect.d.ts.map +1 -0
  13. package/dist/types/src/example/index.d.ts +12 -0
  14. package/dist/types/src/example/index.d.ts.map +1 -0
  15. package/dist/types/src/{examples → example}/reply.d.ts +1 -1
  16. package/dist/types/src/example/reply.d.ts.map +1 -0
  17. package/dist/types/src/{examples → example}/sleep.d.ts +1 -1
  18. package/dist/types/src/example/sleep.d.ts.map +1 -0
  19. package/dist/types/src/index.d.ts +4 -8
  20. package/dist/types/src/index.d.ts.map +1 -1
  21. package/dist/types/src/protocol/index.d.ts +2 -0
  22. package/dist/types/src/protocol/index.d.ts.map +1 -0
  23. package/dist/types/src/protocol/protocol.d.ts +7 -0
  24. package/dist/types/src/protocol/protocol.d.ts.map +1 -0
  25. package/dist/types/src/protocol/protocol.test.d.ts +2 -0
  26. package/dist/types/src/protocol/protocol.test.d.ts.map +1 -0
  27. package/dist/types/src/sdk.d.ts +100 -0
  28. package/dist/types/src/sdk.d.ts.map +1 -0
  29. package/dist/types/src/services/credentials.d.ts +1 -1
  30. package/dist/types/src/services/credentials.d.ts.map +1 -1
  31. package/dist/types/src/services/event-logger.d.ts +16 -4
  32. package/dist/types/src/services/event-logger.d.ts.map +1 -1
  33. package/dist/types/src/services/function-invocation-service.d.ts +3 -20
  34. package/dist/types/src/services/function-invocation-service.d.ts.map +1 -1
  35. package/dist/types/src/services/index.d.ts +3 -4
  36. package/dist/types/src/services/index.d.ts.map +1 -1
  37. package/dist/types/src/services/queues.d.ts +4 -4
  38. package/dist/types/src/services/queues.d.ts.map +1 -1
  39. package/dist/types/src/services/tracing.d.ts +5 -10
  40. package/dist/types/src/services/tracing.d.ts.map +1 -1
  41. package/dist/types/src/types/Function.d.ts +63 -0
  42. package/dist/types/src/types/Function.d.ts.map +1 -0
  43. package/dist/types/src/types/Script.d.ts +28 -0
  44. package/dist/types/src/types/Script.d.ts.map +1 -0
  45. package/dist/types/src/types/Trigger.d.ts +141 -0
  46. package/dist/types/src/types/Trigger.d.ts.map +1 -0
  47. package/dist/types/src/types/TriggerEvent.d.ts +43 -0
  48. package/dist/types/src/types/TriggerEvent.d.ts.map +1 -0
  49. package/dist/types/src/types/index.d.ts +6 -0
  50. package/dist/types/src/types/index.d.ts.map +1 -0
  51. package/dist/types/src/{url.d.ts → types/url.d.ts} +0 -9
  52. package/dist/types/src/types/url.d.ts.map +1 -0
  53. package/dist/types/tsconfig.tsbuildinfo +1 -1
  54. package/package.json +15 -59
  55. package/src/{examples → example}/fib.ts +1 -1
  56. package/src/example/forex-effect.ts +40 -0
  57. package/src/example/index.ts +13 -0
  58. package/src/{examples → example}/reply.ts +1 -1
  59. package/src/{examples → example}/sleep.ts +1 -1
  60. package/src/index.ts +4 -8
  61. package/src/{executor → protocol}/index.ts +1 -1
  62. package/src/protocol/protocol.test.ts +59 -0
  63. package/src/protocol/protocol.ts +156 -0
  64. package/src/{handler.ts → sdk.ts} +96 -81
  65. package/src/services/credentials.ts +3 -4
  66. package/src/services/event-logger.ts +8 -2
  67. package/src/services/function-invocation-service.ts +10 -71
  68. package/src/services/index.ts +4 -4
  69. package/src/services/queues.ts +5 -7
  70. package/src/services/tracing.ts +8 -43
  71. package/src/types/Function.ts +80 -0
  72. package/src/types/Script.ts +33 -0
  73. package/src/types/Trigger.ts +140 -0
  74. package/src/types/TriggerEvent.ts +62 -0
  75. package/src/types/index.ts +9 -0
  76. package/src/{url.ts → types/url.ts} +0 -24
  77. package/dist/lib/browser/bundler/index.mjs +0 -269
  78. package/dist/lib/browser/bundler/index.mjs.map +0 -7
  79. package/dist/lib/browser/chunk-J5LGTIGS.mjs +0 -10
  80. package/dist/lib/browser/chunk-J5LGTIGS.mjs.map +0 -7
  81. package/dist/lib/browser/chunk-LKYT2SAL.mjs +0 -665
  82. package/dist/lib/browser/chunk-LKYT2SAL.mjs.map +0 -7
  83. package/dist/lib/browser/edge/index.mjs +0 -83
  84. package/dist/lib/browser/edge/index.mjs.map +0 -7
  85. package/dist/lib/browser/testing/index.mjs +0 -131
  86. package/dist/lib/browser/testing/index.mjs.map +0 -7
  87. package/dist/lib/node-esm/bundler/index.mjs +0 -270
  88. package/dist/lib/node-esm/bundler/index.mjs.map +0 -7
  89. package/dist/lib/node-esm/chunk-HSLMI22Q.mjs +0 -11
  90. package/dist/lib/node-esm/chunk-HSLMI22Q.mjs.map +0 -7
  91. package/dist/lib/node-esm/chunk-NAQIKLZB.mjs +0 -667
  92. package/dist/lib/node-esm/chunk-NAQIKLZB.mjs.map +0 -7
  93. package/dist/lib/node-esm/edge/index.mjs +0 -84
  94. package/dist/lib/node-esm/edge/index.mjs.map +0 -7
  95. package/dist/lib/node-esm/testing/index.mjs +0 -132
  96. package/dist/lib/node-esm/testing/index.mjs.map +0 -7
  97. package/dist/types/src/bundler/bundler.d.ts +0 -49
  98. package/dist/types/src/bundler/bundler.d.ts.map +0 -1
  99. package/dist/types/src/bundler/bundler.test.d.ts +0 -2
  100. package/dist/types/src/bundler/bundler.test.d.ts.map +0 -1
  101. package/dist/types/src/bundler/index.d.ts +0 -2
  102. package/dist/types/src/bundler/index.d.ts.map +0 -1
  103. package/dist/types/src/edge/functions.d.ts +0 -17
  104. package/dist/types/src/edge/functions.d.ts.map +0 -1
  105. package/dist/types/src/edge/index.d.ts +0 -2
  106. package/dist/types/src/edge/index.d.ts.map +0 -1
  107. package/dist/types/src/examples/fib.d.ts.map +0 -1
  108. package/dist/types/src/examples/index.d.ts +0 -4
  109. package/dist/types/src/examples/index.d.ts.map +0 -1
  110. package/dist/types/src/examples/reply.d.ts.map +0 -1
  111. package/dist/types/src/examples/sleep.d.ts.map +0 -1
  112. package/dist/types/src/executor/executor.d.ts +0 -14
  113. package/dist/types/src/executor/executor.d.ts.map +0 -1
  114. package/dist/types/src/executor/index.d.ts +0 -2
  115. package/dist/types/src/executor/index.d.ts.map +0 -1
  116. package/dist/types/src/handler.d.ts +0 -109
  117. package/dist/types/src/handler.d.ts.map +0 -1
  118. package/dist/types/src/schema.d.ts +0 -43
  119. package/dist/types/src/schema.d.ts.map +0 -1
  120. package/dist/types/src/services/database.d.ts +0 -67
  121. package/dist/types/src/services/database.d.ts.map +0 -1
  122. package/dist/types/src/services/function-invocation-service.test.d.ts +0 -2
  123. package/dist/types/src/services/function-invocation-service.test.d.ts.map +0 -1
  124. package/dist/types/src/services/local-function-execution.d.ts +0 -34
  125. package/dist/types/src/services/local-function-execution.d.ts.map +0 -1
  126. package/dist/types/src/services/remote-function-execution-service.d.ts +0 -22
  127. package/dist/types/src/services/remote-function-execution-service.d.ts.map +0 -1
  128. package/dist/types/src/services/service-container.d.ts +0 -57
  129. package/dist/types/src/services/service-container.d.ts.map +0 -1
  130. package/dist/types/src/services/service-registry.d.ts +0 -31
  131. package/dist/types/src/services/service-registry.d.ts.map +0 -1
  132. package/dist/types/src/services/service-registry.test.d.ts +0 -2
  133. package/dist/types/src/services/service-registry.test.d.ts.map +0 -1
  134. package/dist/types/src/testing/index.d.ts +0 -3
  135. package/dist/types/src/testing/index.d.ts.map +0 -1
  136. package/dist/types/src/testing/layer.d.ts +0 -18
  137. package/dist/types/src/testing/layer.d.ts.map +0 -1
  138. package/dist/types/src/testing/logger.d.ts +0 -5
  139. package/dist/types/src/testing/logger.d.ts.map +0 -1
  140. package/dist/types/src/testing/persist-database.test.d.ts +0 -2
  141. package/dist/types/src/testing/persist-database.test.d.ts.map +0 -1
  142. package/dist/types/src/testing/services.d.ts +0 -59
  143. package/dist/types/src/testing/services.d.ts.map +0 -1
  144. package/dist/types/src/trace.d.ts +0 -122
  145. package/dist/types/src/trace.d.ts.map +0 -1
  146. package/dist/types/src/translations.d.ts +0 -12
  147. package/dist/types/src/translations.d.ts.map +0 -1
  148. package/dist/types/src/triggers/index.d.ts +0 -4
  149. package/dist/types/src/triggers/index.d.ts.map +0 -1
  150. package/dist/types/src/triggers/input-builder.d.ts +0 -3
  151. package/dist/types/src/triggers/input-builder.d.ts.map +0 -1
  152. package/dist/types/src/triggers/invocation-tracer.d.ts +0 -37
  153. package/dist/types/src/triggers/invocation-tracer.d.ts.map +0 -1
  154. package/dist/types/src/triggers/trigger-dispatcher.d.ts +0 -78
  155. package/dist/types/src/triggers/trigger-dispatcher.d.ts.map +0 -1
  156. package/dist/types/src/triggers/trigger-dispatcher.test.d.ts +0 -2
  157. package/dist/types/src/triggers/trigger-dispatcher.test.d.ts.map +0 -1
  158. package/dist/types/src/triggers/trigger-state-store.d.ts +0 -28
  159. package/dist/types/src/triggers/trigger-state-store.d.ts.map +0 -1
  160. package/dist/types/src/types.d.ts +0 -230
  161. package/dist/types/src/types.d.ts.map +0 -1
  162. package/dist/types/src/url.d.ts.map +0 -1
  163. package/src/bundler/bundler.test.ts +0 -58
  164. package/src/bundler/bundler.ts +0 -295
  165. package/src/bundler/index.ts +0 -5
  166. package/src/edge/functions.ts +0 -67
  167. package/src/edge/index.ts +0 -9
  168. package/src/examples/index.ts +0 -7
  169. package/src/executor/executor.ts +0 -58
  170. package/src/schema.ts +0 -71
  171. package/src/services/database.ts +0 -175
  172. package/src/services/function-invocation-service.test.ts +0 -81
  173. package/src/services/local-function-execution.ts +0 -153
  174. package/src/services/remote-function-execution-service.ts +0 -63
  175. package/src/services/service-container.ts +0 -115
  176. package/src/services/service-registry.test.ts +0 -45
  177. package/src/services/service-registry.ts +0 -63
  178. package/src/testing/index.ts +0 -6
  179. package/src/testing/layer.ts +0 -114
  180. package/src/testing/logger.ts +0 -17
  181. package/src/testing/persist-database.test.ts +0 -87
  182. package/src/testing/services.ts +0 -115
  183. package/src/trace.ts +0 -178
  184. package/src/translations.ts +0 -20
  185. package/src/triggers/index.ts +0 -7
  186. package/src/triggers/input-builder.ts +0 -35
  187. package/src/triggers/invocation-tracer.ts +0 -101
  188. package/src/triggers/trigger-dispatcher.test.ts +0 -665
  189. package/src/triggers/trigger-dispatcher.ts +0 -533
  190. package/src/triggers/trigger-state-store.ts +0 -61
  191. package/src/types.ts +0 -218
@@ -1,60 +1,87 @@
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
- // src/handler.ts
38
+ // src/sdk.ts
34
39
  import * as Effect from "effect/Effect";
40
+ import * as Schema5 from "effect/Schema";
41
+ import { Obj as Obj5, Type as Type5 } from "@dxos/echo";
42
+ import { assertArgument, failedInvariant } from "@dxos/invariant";
43
+
44
+ // src/types/Function.ts
45
+ var Function_exports = {};
46
+ __export(Function_exports, {
47
+ Function: () => Function,
48
+ make: () => make2,
49
+ setFrom: () => setFrom
50
+ });
35
51
  import * as Schema2 from "effect/Schema";
36
- import { Obj, Type as Type2 } from "@dxos/echo";
37
- import { assertArgument } from "@dxos/invariant";
52
+ import { Annotation as Annotation2, JsonSchema, Obj as Obj2, Type as Type2 } from "@dxos/echo";
53
+ import { SystemTypeAnnotation } from "@dxos/echo/internal";
38
54
 
39
- // src/schema.ts
55
+ // src/types/Script.ts
56
+ var Script_exports = {};
57
+ __export(Script_exports, {
58
+ Script: () => Script,
59
+ make: () => make
60
+ });
40
61
  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),
62
+ import { Annotation, Obj, Ref, Type } from "@dxos/echo";
63
+ import { FormInputAnnotation } 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),
47
68
  // TODO(burdon): Change to hash of deployed content.
48
69
  // Whether source has changed since last deploy.
49
- changed: Schema.optional(Schema.Boolean),
50
- source: Ref(DataType.Text)
70
+ changed: Schema.Boolean.pipe(FormInputAnnotation.set(false), Schema.optional),
71
+ source: Type.Ref(Text.Text).pipe(FormInputAnnotation.set(false))
51
72
  }).pipe(Type.Obj({
52
73
  typename: "dxos.org/type/Script",
53
74
  version: "0.1.0"
54
- }), LabelAnnotation.set([
75
+ }), Annotation.LabelAnnotation.set([
55
76
  "name"
56
77
  ]));
57
- 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({
58
85
  /**
59
86
  * Global registry ID.
60
87
  * NOTE: The `key` property refers to the original registry entry.
@@ -62,175 +89,86 @@ var FunctionType = Schema.Struct({
62
89
  // TODO(burdon): Create Format type for DXN-like ids, such as this and schema type.
63
90
  // TODO(dmaretskyi): Consider making it part of ECHO meta.
64
91
  // TODO(dmaretskyi): Make required.
65
- key: Schema.optional(Schema.String).annotations({
92
+ key: Schema2.optional(Schema2.String).annotations({
66
93
  description: "Unique registration key for the blueprint"
67
94
  }),
68
- // 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(Type2.Ref(Script)),
105
+ inputSchema: Schema2.optional(JsonSchema.JsonSchema),
106
+ outputSchema: Schema2.optional(JsonSchema.JsonSchema),
107
+ /**
108
+ * List of required services.
109
+ * Match the Context.Tag keys of the FunctionServices variants.
110
+ */
111
+ services: Schema2.optional(Schema2.Array(Schema2.String)),
77
112
  // Local binding to a function name.
78
- binding: Schema.optional(Schema.String)
79
- }).pipe(Type.Obj({
113
+ binding: Schema2.optional(Schema2.String)
114
+ }).pipe(Type2.Obj({
80
115
  typename: "dxos.org/type/Function",
81
116
  version: "0.1.0"
82
- }), LabelAnnotation.set([
117
+ }), Annotation2.LabelAnnotation.set([
83
118
  "name"
84
- ]));
85
-
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
- };
119
+ ]), SystemTypeAnnotation.set(true));
120
+ var make2 = (props) => Obj2.make(Function, props);
121
+ var setFrom = (target, source) => {
122
+ target.key = source.key ?? target.key;
123
+ target.name = source.name ?? target.name;
124
+ target.version = source.version;
125
+ target.description = source.description;
126
+ target.updated = source.updated;
127
+ target.inputSchema = source.inputSchema ? JSON.parse(JSON.stringify(source.inputSchema)) : void 0;
128
+ target.outputSchema = source.outputSchema ? JSON.parse(JSON.stringify(source.outputSchema)) : void 0;
129
+ Obj2.getMeta(target).keys = JSON.parse(JSON.stringify(Obj2.getMeta(source).keys));
175
130
  };
176
131
 
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
132
+ // src/types/Trigger.ts
133
+ var Trigger_exports = {};
134
+ __export(Trigger_exports, {
135
+ EmailSpec: () => EmailSpec,
136
+ Kinds: () => Kinds,
137
+ QueueSpec: () => QueueSpec,
138
+ Spec: () => Spec,
139
+ SubscriptionSpec: () => SubscriptionSpec,
140
+ TimerSpec: () => TimerSpec,
141
+ Trigger: () => Trigger,
142
+ WebhookSpec: () => WebhookSpec,
143
+ make: () => make3
144
+ });
185
145
  import * as Schema3 from "effect/Schema";
186
146
  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";
147
+ import { Obj as Obj3, QueryAST, Type as Type3 } from "@dxos/echo";
148
+ import { OptionsAnnotationId, SystemTypeAnnotation as SystemTypeAnnotation2 } from "@dxos/echo/internal";
189
149
  import { DXN } from "@dxos/keys";
190
- var TriggerKinds = [
191
- "timer",
192
- "webhook",
193
- "subscription",
150
+ var Kinds = [
194
151
  "email",
195
- "queue"
152
+ "queue",
153
+ "subscription",
154
+ "timer",
155
+ "webhook"
196
156
  ];
197
157
  var kindLiteralAnnotations = {
198
158
  title: "Kind"
199
159
  };
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({
160
+ var EmailSpec = Schema3.Struct({
210
161
  kind: Schema3.Literal("email").annotations(kindLiteralAnnotations)
211
162
  }).pipe(Schema3.mutable);
212
- var QueueTriggerSchema = Schema3.Struct({
163
+ var QueueSpec = Schema3.Struct({
213
164
  kind: Schema3.Literal("queue").annotations(kindLiteralAnnotations),
214
165
  // TODO(dmaretskyi): Change to a reference.
215
166
  queue: DXN.Schema
216
167
  }).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({
168
+ var SubscriptionSpec = Schema3.Struct({
231
169
  kind: Schema3.Literal("subscription").annotations(kindLiteralAnnotations),
232
170
  query: Schema3.Struct({
233
- string: Schema3.optional(Schema3.String.annotations({
171
+ raw: Schema3.optional(Schema3.String.annotations({
234
172
  title: "Query"
235
173
  })),
236
174
  ast: QueryAST.Query
@@ -248,54 +186,37 @@ var SubscriptionTriggerSchema = Schema3.Struct({
248
186
  title: "Options"
249
187
  }))
250
188
  }).pipe(Schema3.mutable);
251
- var TriggerSchema = Schema3.Union(TimerTriggerSchema, WebhookTriggerSchema, SubscriptionTriggerSchema, EmailTriggerSchema, QueueTriggerSchema).annotations({
189
+ var TimerSpec = Schema3.Struct({
190
+ kind: Schema3.Literal("timer").annotations(kindLiteralAnnotations),
191
+ cron: Schema3.String.annotations({
192
+ title: "Cron",
193
+ [SchemaAST.ExamplesAnnotationId]: [
194
+ "0 0 * * *"
195
+ ]
196
+ })
197
+ }).pipe(Schema3.mutable);
198
+ var WebhookSpec = Schema3.Struct({
199
+ kind: Schema3.Literal("webhook").annotations(kindLiteralAnnotations),
200
+ method: Schema3.optional(Schema3.String.annotations({
201
+ title: "Method",
202
+ [OptionsAnnotationId]: [
203
+ "GET",
204
+ "POST"
205
+ ]
206
+ })),
207
+ port: Schema3.optional(Schema3.Number.annotations({
208
+ title: "Port"
209
+ }))
210
+ }).pipe(Schema3.mutable);
211
+ var Spec = Schema3.Union(EmailSpec, QueueSpec, SubscriptionSpec, TimerSpec, WebhookSpec).annotations({
252
212
  title: "Trigger"
253
213
  });
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({
214
+ var Trigger_ = Schema3.Struct({
294
215
  /**
295
216
  * Function or workflow to invoke.
296
217
  */
297
218
  // TODO(dmaretskyi): Can be a Ref(FunctionType) or Ref(ComputeGraphType).
298
- function: Schema3.optional(Ref2(Expando).annotations({
219
+ function: Schema3.optional(Type3.Ref(Type3.Expando).annotations({
299
220
  title: "Function"
300
221
  })),
301
222
  /**
@@ -309,7 +230,7 @@ var FunctionTrigger_ = Schema3.Struct({
309
230
  enabled: Schema3.optional(Schema3.Boolean.annotations({
310
231
  title: "Enabled"
311
232
  })),
312
- spec: Schema3.optional(TriggerSchema),
233
+ spec: Schema3.optional(Spec),
313
234
  /**
314
235
  * Passed as the input data to the function.
315
236
  * Must match the function's input schema.
@@ -326,963 +247,203 @@ var FunctionTrigger_ = Schema3.Struct({
326
247
  value: Schema3.Any
327
248
  })))
328
249
  }).pipe(Type3.Obj({
329
- typename: "dxos.org/type/FunctionTrigger",
330
- version: "0.2.0"
331
- }));
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
- ];
250
+ typename: "dxos.org/type/Trigger",
251
+ version: "0.1.0"
252
+ }), SystemTypeAnnotation2.set(true));
253
+ var Trigger = Trigger_;
254
+ var make3 = (props) => Obj3.make(Trigger, props);
341
255
 
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)
256
+ // src/types/TriggerEvent.ts
257
+ var TriggerEvent_exports = {};
258
+ __export(TriggerEvent_exports, {
259
+ EmailEvent: () => EmailEvent,
260
+ QueueEvent: () => QueueEvent,
261
+ SubscriptionEvent: () => SubscriptionEvent,
262
+ TimerEvent: () => TimerEvent,
263
+ WebhookEvent: () => WebhookEvent
360
264
  });
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"
265
+ import * as Schema4 from "effect/Schema";
266
+ import { DXN as DXN2, Obj as Obj4, Type as Type4 } from "@dxos/echo";
267
+ var EmailEvent = Schema4.mutable(Schema4.Struct({
268
+ from: Schema4.String,
269
+ to: Schema4.String,
270
+ subject: Schema4.String,
271
+ created: Schema4.String,
272
+ body: Schema4.String
395
273
  }));
396
- var InvocationTraceEndEvent = Schema4.Struct({
274
+ var QueueEvent = Schema4.mutable(Schema4.Struct({
275
+ queue: DXN2.Schema,
276
+ item: Schema4.Any,
277
+ cursor: Schema4.String
278
+ }));
279
+ var SubscriptionEvent = Schema4.Struct({
397
280
  /**
398
- * Trace event id.
281
+ * Type of the mutation.
399
282
  */
400
- id: ObjectId,
401
- type: Schema4.Literal("end"),
283
+ // TODO(dmaretskyi): Specify enum.
284
+ type: Schema4.String,
402
285
  /**
403
- * Invocation id, will be the same for invocation start and end.
286
+ * Reference to the object that was changed or created.
404
287
  */
405
- invocationId: ObjectId,
288
+ subject: Type4.Ref(Obj4.Any),
406
289
  /**
407
- * Event generation time.
290
+ * @deprecated
408
291
  */
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"
292
+ changedObjectId: Schema4.optional(Schema4.String)
293
+ }).pipe(Schema4.mutable);
294
+ var TimerEvent = Schema4.mutable(Schema4.Struct({
295
+ tick: Schema4.Number
416
296
  }));
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"
297
+ var WebhookEvent = Schema4.mutable(Schema4.Struct({
298
+ url: Schema4.String,
299
+ method: Schema4.Literal("GET", "POST"),
300
+ headers: Schema4.Record({
301
+ key: Schema4.String,
302
+ value: Schema4.String
303
+ }),
304
+ bodyText: Schema4.String
435
305
  }));
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;
306
+
307
+ // src/types/url.ts
308
+ var FUNCTIONS_META_KEY = "dxos.org/service/function";
309
+ var FUNCTIONS_PRESET_META_KEY = "dxos.org/service/function-preset";
310
+ var getUserFunctionIdInMetadata = (meta) => {
311
+ return meta.keys.find((key) => key.source === FUNCTIONS_META_KEY)?.id;
312
+ };
313
+ var setUserFunctionIdInMetadata = (meta, functionId) => {
314
+ const key = meta.keys.find((key2) => key2.source === FUNCTIONS_META_KEY);
315
+ if (key) {
316
+ if (key.id !== functionId) {
317
+ throw new Error("Metadata mismatch");
470
318
  }
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
319
+ } else {
320
+ meta.keys.push({
321
+ source: FUNCTIONS_META_KEY,
322
+ id: functionId
482
323
  });
483
324
  }
484
- return result;
485
325
  };
486
326
 
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;
327
+ // src/sdk.ts
328
+ var typeId = Symbol.for("@dxos/functions/FunctionDefinition");
329
+ var defineFunction = ({ key, name, description, inputSchema, outputSchema = Schema5.Any, handler, types, services }) => {
330
+ if (!Schema5.isSchema(inputSchema)) {
331
+ throw new Error("Input schema must be a valid schema");
518
332
  }
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
- });
333
+ if (typeof handler !== "function") {
334
+ throw new Error("Handler must be a function");
554
335
  }
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));
336
+ const limit = Error.stackTraceLimit;
337
+ Error.stackTraceLimit = 2;
338
+ const traceError = new Error();
339
+ Error.stackTraceLimit = limit;
340
+ let cache = false;
341
+ const captureStackTrace = () => {
342
+ if (cache !== false) {
343
+ return cache;
625
344
  }
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);
345
+ if (traceError.stack !== void 0) {
346
+ const stack = traceError.stack.split("\n");
347
+ if (stack[2] !== void 0) {
348
+ cache = stack[2].trim();
349
+ return cache;
655
350
  }
656
- return yield* localExecutioner.invokeFunction(functionDef, input);
657
- })
351
+ }
658
352
  };
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
353
+ const handlerWithSpan = (...args) => {
354
+ const result = handler(...args);
355
+ if (Effect.isEffect(result)) {
356
+ return Effect.withSpan(result, `${key ?? name}`, {
357
+ captureStackTrace
723
358
  });
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
359
  }
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
- }
776
- payload[key] = valueSubstitution;
777
- }
778
- return payload;
360
+ return result;
361
+ };
362
+ return {
363
+ [typeId]: true,
364
+ key,
365
+ name,
366
+ description,
367
+ inputSchema,
368
+ outputSchema,
369
+ handler: handlerWithSpan,
370
+ types: types ?? [],
371
+ services: !services ? [] : getServiceKeys(services)
372
+ };
779
373
  };
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")()) {
374
+ var getServiceKeys = (services) => {
375
+ return services.map((tag) => {
376
+ if (typeof tag.key === "string") {
377
+ return tag.key;
378
+ }
379
+ console.log(tag);
380
+ failedInvariant();
381
+ });
814
382
  };
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
- })
831
- };
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;
383
+ var FunctionDefinition = {
384
+ make: defineFunction,
385
+ isFunction: (value2) => {
386
+ return typeof value2 === "object" && value2 !== null && Symbol.for("@dxos/functions/FunctionDefinition") in value2;
387
+ },
388
+ serialize: (functionDef) => {
389
+ assertArgument(FunctionDefinition.isFunction(functionDef), "functionDef");
390
+ return serializeFunction(functionDef);
391
+ },
392
+ deserialize: (functionObj) => {
393
+ assertArgument(Obj5.instanceOf(Function_exports.Function, functionObj), "functionObj");
394
+ return deserializeFunction(functionObj);
847
395
  }
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
396
  };
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();
397
+ var serializeFunction = (functionDef) => {
398
+ const fn4 = Function_exports.make({
399
+ key: functionDef.key,
400
+ name: functionDef.name,
401
+ version: "0.1.0",
402
+ description: functionDef.description,
403
+ inputSchema: Type5.toJsonSchema(functionDef.inputSchema),
404
+ outputSchema: !functionDef.outputSchema ? void 0 : Type5.toJsonSchema(functionDef.outputSchema),
405
+ services: functionDef.services
406
+ });
407
+ if (functionDef.meta?.deployedFunctionId) {
408
+ setUserFunctionIdInMetadata(Obj5.getMeta(fn4), functionDef.meta.deployedFunctionId);
1205
409
  }
410
+ return fn4;
1206
411
  };
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;
1223
- }
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;
412
+ var deserializeFunction = (functionObj) => {
413
+ return {
414
+ [typeId]: true,
415
+ // TODO(dmaretskyi): Fix key.
416
+ key: functionObj.key ?? functionObj.name,
417
+ name: functionObj.name,
418
+ description: functionObj.description,
419
+ inputSchema: !functionObj.inputSchema ? Schema5.Unknown : Type5.toEffectSchema(functionObj.inputSchema),
420
+ outputSchema: !functionObj.outputSchema ? void 0 : Type5.toEffectSchema(functionObj.outputSchema),
421
+ // TODO(dmaretskyi): This should throw error.
422
+ handler: () => {
423
+ },
424
+ services: functionObj.services ?? [],
425
+ types: [],
426
+ meta: {
427
+ deployedFunctionId: getUserFunctionIdInMetadata(Obj5.getMeta(functionObj))
1250
428
  }
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
- }
429
+ };
1259
430
  };
1260
431
 
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";
432
+ // src/example/fib.ts
1272
433
  var fib_default = defineFunction({
1273
434
  key: "example.org/function/fib",
1274
435
  name: "Fibonacci",
1275
436
  description: "Function that calculates a Fibonacci number",
1276
- inputSchema: Schema8.Struct({
1277
- iterations: Schema8.optional(Schema8.Number).annotations({
437
+ inputSchema: Schema6.Struct({
438
+ iterations: Schema6.optional(Schema6.Number).annotations({
1278
439
  description: "Number of iterations",
1279
440
  default: 1e5
1280
441
  })
1281
442
  }),
1282
- outputSchema: Schema8.Struct({
1283
- result: Schema8.String
443
+ outputSchema: Schema6.Struct({
444
+ result: Schema6.String
1284
445
  }),
1285
- handler: Effect8.fn(function* ({ data: { iterations = 1e5 } }) {
446
+ handler: Effect2.fn(function* ({ data: { iterations = 1e5 } }) {
1286
447
  let a = 0n;
1287
448
  let b = 1n;
1288
449
  for (let i = 0; i < iterations; i++) {
@@ -1295,17 +456,17 @@ var fib_default = defineFunction({
1295
456
  })
1296
457
  });
1297
458
 
1298
- // src/examples/reply.ts
459
+ // src/example/reply.ts
1299
460
  import * as Console from "effect/Console";
1300
- import * as Effect9 from "effect/Effect";
1301
- import * as Schema9 from "effect/Schema";
461
+ import * as Effect3 from "effect/Effect";
462
+ import * as Schema7 from "effect/Schema";
1302
463
  var reply_default = defineFunction({
1303
464
  key: "example.org/function/reply",
1304
465
  name: "Reply",
1305
466
  description: "Function that echoes the input",
1306
- inputSchema: Schema9.Any,
1307
- outputSchema: Schema9.Any,
1308
- handler: Effect9.fn(function* ({ data }) {
467
+ inputSchema: Schema7.Any,
468
+ outputSchema: Schema7.Any,
469
+ handler: Effect3.fn(function* ({ data }) {
1309
470
  yield* Console.log("reply", {
1310
471
  data
1311
472
  });
@@ -1313,24 +474,524 @@ var reply_default = defineFunction({
1313
474
  })
1314
475
  });
1315
476
 
1316
- // src/examples/sleep.ts
1317
- import * as Effect10 from "effect/Effect";
1318
- import * as Schema10 from "effect/Schema";
477
+ // src/example/sleep.ts
478
+ import * as Effect4 from "effect/Effect";
479
+ import * as Schema8 from "effect/Schema";
1319
480
  var sleep_default = defineFunction({
1320
481
  key: "example.org/function/sleep",
1321
482
  name: "Sleep",
1322
483
  description: "Function that sleeps for a given amount of time",
1323
- inputSchema: Schema10.Struct({
1324
- duration: Schema10.optional(Schema10.Number).annotations({
484
+ inputSchema: Schema8.Struct({
485
+ duration: Schema8.optional(Schema8.Number).annotations({
1325
486
  description: "Milliseconds to sleep",
1326
487
  default: 1e5
1327
488
  })
1328
489
  }),
1329
- outputSchema: Schema10.Void,
1330
- handler: Effect10.fn(function* ({ data: { duration = 1e5 } }) {
1331
- yield* Effect10.sleep(duration);
490
+ outputSchema: Schema8.Void,
491
+ handler: Effect4.fn(function* ({ data: { duration = 1e5 } }) {
492
+ yield* Effect4.sleep(duration);
1332
493
  })
1333
494
  });
495
+
496
+ // src/example/index.ts
497
+ (function(Example2) {
498
+ Example2.fib = fib_default;
499
+ Example2.reply = reply_default;
500
+ Example2.sleep = sleep_default;
501
+ })(Example || (Example = {}));
502
+ var Example;
503
+
504
+ // src/services/index.ts
505
+ import { DatabaseService as DatabaseService2 } from "@dxos/echo-db";
506
+
507
+ // src/services/credentials.ts
508
+ import * as HttpClient from "@effect/platform/HttpClient";
509
+ import * as HttpClientRequest from "@effect/platform/HttpClientRequest";
510
+ import * as Context from "effect/Context";
511
+ import * as Effect5 from "effect/Effect";
512
+ import * as Layer from "effect/Layer";
513
+ import * as Redacted from "effect/Redacted";
514
+ import { Query } from "@dxos/echo";
515
+ import { DatabaseService } from "@dxos/echo-db";
516
+ import { AccessToken } from "@dxos/types";
517
+ var CredentialsService = class _CredentialsService extends Context.Tag("@dxos/functions/CredentialsService")() {
518
+ static getCredential = (query) => Effect5.gen(function* () {
519
+ const credentials = yield* _CredentialsService;
520
+ return yield* Effect5.promise(() => credentials.getCredential(query));
521
+ });
522
+ static getApiKey = (query) => Effect5.gen(function* () {
523
+ const credential = yield* _CredentialsService.getCredential(query);
524
+ if (!credential.apiKey) {
525
+ throw new Error(`API key not found for service: ${query.service}`);
526
+ }
527
+ return Redacted.make(credential.apiKey);
528
+ });
529
+ static configuredLayer = (credentials) => Layer.succeed(_CredentialsService, new ConfiguredCredentialsService(credentials));
530
+ static layerConfig = (credentials) => Layer.effect(_CredentialsService, Effect5.gen(function* () {
531
+ const serviceCredentials = yield* Effect5.forEach(credentials, ({ service, apiKey }) => Effect5.gen(function* () {
532
+ return {
533
+ service,
534
+ apiKey: Redacted.value(yield* apiKey)
535
+ };
536
+ }));
537
+ return new ConfiguredCredentialsService(serviceCredentials);
538
+ }));
539
+ static layerFromDatabase = () => Layer.effect(_CredentialsService, Effect5.gen(function* () {
540
+ const dbService = yield* DatabaseService;
541
+ const queryCredentials = async (query) => {
542
+ const { objects: accessTokens } = await dbService.db.query(Query.type(AccessToken.AccessToken)).run();
543
+ return accessTokens.filter((accessToken) => accessToken.source === query.service).map((accessToken) => ({
544
+ service: accessToken.source,
545
+ apiKey: accessToken.token
546
+ }));
547
+ };
548
+ return {
549
+ getCredential: async (query) => {
550
+ const credentials = await queryCredentials(query);
551
+ if (credentials.length === 0) {
552
+ throw new Error(`Credential not found for service: ${query.service}`);
553
+ }
554
+ return credentials[0];
555
+ },
556
+ queryCredentials: async (query) => {
557
+ return queryCredentials(query);
558
+ }
559
+ };
560
+ }));
561
+ };
562
+ var ConfiguredCredentialsService = class {
563
+ credentials;
564
+ constructor(credentials = []) {
565
+ this.credentials = credentials;
566
+ }
567
+ addCredentials(credentials) {
568
+ this.credentials.push(...credentials);
569
+ return this;
570
+ }
571
+ async queryCredentials(query) {
572
+ return this.credentials.filter((credential) => credential.service === query.service);
573
+ }
574
+ async getCredential(query) {
575
+ const credential = this.credentials.find((credential2) => credential2.service === query.service);
576
+ if (!credential) {
577
+ throw new Error(`Credential not found for service: ${query.service}`);
578
+ }
579
+ return credential;
580
+ }
581
+ };
582
+ var withAuthorization = (query, kind) => HttpClient.mapRequestEffect(Effect5.fnUntraced(function* (request) {
583
+ const key = yield* CredentialsService.getApiKey(query).pipe(Effect5.map(Redacted.value));
584
+ const authorization = kind ? `${kind} ${key}` : key;
585
+ return HttpClientRequest.setHeader(request, "Authorization", authorization);
586
+ }));
587
+
588
+ // src/services/event-logger.ts
589
+ import * as Context3 from "effect/Context";
590
+ import * as Effect7 from "effect/Effect";
591
+ import * as Layer3 from "effect/Layer";
592
+ import * as Schema9 from "effect/Schema";
593
+ import { Obj as Obj7, Type as Type6 } from "@dxos/echo";
594
+ import { invariant } from "@dxos/invariant";
595
+ import { LogLevel, log as log2 } from "@dxos/log";
596
+
597
+ // src/services/tracing.ts
598
+ import * as Context2 from "effect/Context";
599
+ import * as Effect6 from "effect/Effect";
600
+ import * as Layer2 from "effect/Layer";
601
+ import { AgentStatus } from "@dxos/ai";
602
+ import { Obj as Obj6 } from "@dxos/echo";
603
+ import { Message } from "@dxos/types";
604
+ var TracingService = class _TracingService extends Context2.Tag("@dxos/functions/TracingService")() {
605
+ static noop = {
606
+ getTraceContext: () => ({}),
607
+ write: () => {
608
+ }
609
+ };
610
+ static layerNoop = Layer2.succeed(_TracingService, _TracingService.noop);
611
+ /**
612
+ * Creates a TracingService layer that emits events to the parent tracing service.
613
+ */
614
+ static layerSubframe = (mapContext) => Layer2.effect(_TracingService, Effect6.gen(function* () {
615
+ const tracing = yield* _TracingService;
616
+ const context = mapContext(tracing.getTraceContext());
617
+ return {
618
+ write: (event) => tracing.write(event),
619
+ getTraceContext: () => context
620
+ };
621
+ }));
622
+ /**
623
+ * Emit the current human-readable execution status.
624
+ */
625
+ static emitStatus = Effect6.fnUntraced(function* (data) {
626
+ const tracing = yield* _TracingService;
627
+ tracing.write(Obj6.make(AgentStatus, {
628
+ parentMessage: tracing.getTraceContext().parentMessage,
629
+ toolCallId: tracing.getTraceContext().toolCallId,
630
+ created: (/* @__PURE__ */ new Date()).toISOString(),
631
+ ...data
632
+ }));
633
+ });
634
+ static emitConverationMessage = Effect6.fnUntraced(function* (data) {
635
+ const tracing = yield* _TracingService;
636
+ tracing.write(Obj6.make(Message.Message, {
637
+ parentMessage: tracing.getTraceContext().parentMessage,
638
+ ...data,
639
+ properties: {
640
+ [MESSAGE_PROPERTY_TOOL_CALL_ID]: tracing.getTraceContext().toolCallId,
641
+ ...data.properties
642
+ }
643
+ }));
644
+ });
645
+ };
646
+ var MESSAGE_PROPERTY_TOOL_CALL_ID = "toolCallId";
647
+
648
+ // src/services/event-logger.ts
649
+ var __dxlog_file = "/__w/dxos/dxos/packages/core/functions/src/services/event-logger.ts";
650
+ var ComputeEventPayload = Schema9.Union(Schema9.Struct({
651
+ type: Schema9.Literal("begin-compute"),
652
+ nodeId: Schema9.String,
653
+ /**
654
+ * Names of the inputs begin computed.
655
+ */
656
+ inputs: Schema9.Array(Schema9.String)
657
+ }), Schema9.Struct({
658
+ type: Schema9.Literal("end-compute"),
659
+ nodeId: Schema9.String,
660
+ /**
661
+ * Names of the outputs computed.
662
+ */
663
+ outputs: Schema9.Array(Schema9.String)
664
+ }), Schema9.Struct({
665
+ type: Schema9.Literal("compute-input"),
666
+ nodeId: Schema9.String,
667
+ property: Schema9.String,
668
+ value: Schema9.Any
669
+ }), Schema9.Struct({
670
+ type: Schema9.Literal("compute-output"),
671
+ nodeId: Schema9.String,
672
+ property: Schema9.String,
673
+ value: Schema9.Any
674
+ }), Schema9.Struct({
675
+ type: Schema9.Literal("custom"),
676
+ nodeId: Schema9.String,
677
+ event: Schema9.Any
678
+ }));
679
+ var ComputeEvent = Schema9.Struct({
680
+ payload: ComputeEventPayload
681
+ }).pipe(Type6.Obj({
682
+ typename: "dxos.org/type/ComputeEvent",
683
+ version: "0.1.0"
684
+ }));
685
+ var ComputeEventLogger = class _ComputeEventLogger extends Context3.Tag("@dxos/functions/ComputeEventLogger")() {
686
+ static noop = {
687
+ log: () => {
688
+ },
689
+ nodeId: void 0
690
+ };
691
+ /**
692
+ * Implements ComputeEventLogger using TracingService.
693
+ */
694
+ static layerFromTracing = Layer3.effect(_ComputeEventLogger, Effect7.gen(function* () {
695
+ const tracing = yield* TracingService;
696
+ return {
697
+ log: (event) => {
698
+ tracing.write(Obj7.make(ComputeEvent, {
699
+ payload: event
700
+ }));
701
+ },
702
+ nodeId: void 0
703
+ };
704
+ }));
705
+ };
706
+ var logCustomEvent = (data) => Effect7.gen(function* () {
707
+ const logger = yield* ComputeEventLogger;
708
+ if (!logger.nodeId) {
709
+ throw new Error("logCustomEvent must be called within a node compute function");
710
+ }
711
+ logger.log({
712
+ type: "custom",
713
+ nodeId: logger.nodeId,
714
+ event: data
715
+ });
716
+ });
717
+ var createDefectLogger = () => Effect7.catchAll((error) => Effect7.gen(function* () {
718
+ log2.error("unhandled effect error", {
719
+ error
720
+ }, {
721
+ F: __dxlog_file,
722
+ L: 102,
723
+ S: this,
724
+ C: (f, a) => f(...a)
725
+ });
726
+ throw error;
727
+ }));
728
+ var createEventLogger = (level, message = "event") => {
729
+ const logFunction = {
730
+ [LogLevel.WARN]: log2.warn,
731
+ [LogLevel.VERBOSE]: log2.verbose,
732
+ [LogLevel.DEBUG]: log2.debug,
733
+ [LogLevel.INFO]: log2.info,
734
+ [LogLevel.ERROR]: log2.error
735
+ }[level];
736
+ invariant(logFunction, void 0, {
737
+ F: __dxlog_file,
738
+ L: 120,
739
+ S: void 0,
740
+ A: [
741
+ "logFunction",
742
+ ""
743
+ ]
744
+ });
745
+ return {
746
+ log: (event) => {
747
+ logFunction(message, event);
748
+ },
749
+ nodeId: void 0
750
+ };
751
+ };
752
+
753
+ // src/services/function-invocation-service.ts
754
+ import * as Context4 from "effect/Context";
755
+ import * as Effect8 from "effect/Effect";
756
+ var FunctionInvocationService = class _FunctionInvocationService extends Context4.Tag("@dxos/functions/FunctionInvocationService")() {
757
+ static invokeFunction = (functionDef, input) => Effect8.serviceFunctionEffect(_FunctionInvocationService, (service) => service.invokeFunction)(functionDef, input);
758
+ };
759
+
760
+ // src/services/queues.ts
761
+ import * as Context5 from "effect/Context";
762
+ import * as Effect9 from "effect/Effect";
763
+ import * as Layer4 from "effect/Layer";
764
+ var QueueService = class _QueueService extends Context5.Tag("@dxos/functions/QueueService")() {
765
+ static notAvailable = Layer4.succeed(_QueueService, {
766
+ queues: {
767
+ get(_dxn) {
768
+ throw new Error("Queues not available");
769
+ },
770
+ create() {
771
+ throw new Error("Queues not available");
772
+ }
773
+ },
774
+ queue: void 0
775
+ });
776
+ static make = (queues, queue) => {
777
+ return {
778
+ queues,
779
+ queue
780
+ };
781
+ };
782
+ static layer = (queues, queue) => Layer4.succeed(_QueueService, _QueueService.make(queues, queue));
783
+ /**
784
+ * Gets a queue by its DXN.
785
+ */
786
+ static getQueue = (dxn) => _QueueService.pipe(Effect9.map(({ queues }) => queues.get(dxn)));
787
+ /**
788
+ * Creates a new queue.
789
+ */
790
+ static createQueue = (options) => _QueueService.pipe(Effect9.map(({ queues }) => queues.create(options)));
791
+ static append = (queue, objects) => Effect9.promise(() => queue.append(objects));
792
+ };
793
+ var ContextQueueService = class _ContextQueueService extends Context5.Tag("@dxos/functions/ContextQueueService")() {
794
+ static layer = (queue) => Layer4.succeed(_ContextQueueService, {
795
+ queue
796
+ });
797
+ };
798
+
799
+ // src/protocol/protocol.ts
800
+ import * as Effect10 from "effect/Effect";
801
+ import * as Layer5 from "effect/Layer";
802
+ import * as Schema10 from "effect/Schema";
803
+ import * as SchemaAST2 from "effect/SchemaAST";
804
+ import { AiService } from "@dxos/ai";
805
+ import { LifecycleState, Resource } from "@dxos/context";
806
+ import { Type as Type7 } from "@dxos/echo";
807
+ import { EchoClient } from "@dxos/echo-db";
808
+ import { assertState, failedInvariant as failedInvariant2, invariant as invariant2 } from "@dxos/invariant";
809
+ import { PublicKey } from "@dxos/keys";
810
+ function _ts_add_disposable_resource(env, value2, async) {
811
+ if (value2 !== null && value2 !== void 0) {
812
+ if (typeof value2 !== "object" && typeof value2 !== "function") throw new TypeError("Object expected.");
813
+ var dispose, inner;
814
+ if (async) {
815
+ if (!Symbol.asyncDispose) throw new TypeError("Symbol.asyncDispose is not defined.");
816
+ dispose = value2[Symbol.asyncDispose];
817
+ }
818
+ if (dispose === void 0) {
819
+ if (!Symbol.dispose) throw new TypeError("Symbol.dispose is not defined.");
820
+ dispose = value2[Symbol.dispose];
821
+ if (async) inner = dispose;
822
+ }
823
+ if (typeof dispose !== "function") throw new TypeError("Object not disposable.");
824
+ if (inner) dispose = function() {
825
+ try {
826
+ inner.call(this);
827
+ } catch (e) {
828
+ return Promise.reject(e);
829
+ }
830
+ };
831
+ env.stack.push({
832
+ value: value2,
833
+ dispose,
834
+ async
835
+ });
836
+ } else if (async) {
837
+ env.stack.push({
838
+ async: true
839
+ });
840
+ }
841
+ return value2;
842
+ }
843
+ function _ts_dispose_resources(env) {
844
+ var _SuppressedError = typeof SuppressedError === "function" ? SuppressedError : function(error, suppressed, message) {
845
+ var e = new Error(message);
846
+ return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
847
+ };
848
+ return (_ts_dispose_resources = function _ts_dispose_resources2(env2) {
849
+ function fail(e) {
850
+ env2.error = env2.hasError ? new _SuppressedError(e, env2.error, "An error was suppressed during disposal.") : e;
851
+ env2.hasError = true;
852
+ }
853
+ var r, s = 0;
854
+ function next() {
855
+ while (r = env2.stack.pop()) {
856
+ try {
857
+ if (!r.async && s === 1) return s = 0, env2.stack.push(r), Promise.resolve().then(next);
858
+ if (r.dispose) {
859
+ var result = r.dispose.call(r.value);
860
+ if (r.async) return s |= 2, Promise.resolve(result).then(next, function(e) {
861
+ fail(e);
862
+ return next();
863
+ });
864
+ } else s |= 1;
865
+ } catch (e) {
866
+ fail(e);
867
+ }
868
+ }
869
+ if (s === 1) return env2.hasError ? Promise.reject(env2.error) : Promise.resolve();
870
+ if (env2.hasError) throw env2.error;
871
+ }
872
+ return next();
873
+ })(env);
874
+ }
875
+ var __dxlog_file2 = "/__w/dxos/dxos/packages/core/functions/src/protocol/protocol.ts";
876
+ var wrapFunctionHandler = (func) => {
877
+ if (!FunctionDefinition.isFunction(func)) {
878
+ throw new TypeError("Invalid function definition");
879
+ }
880
+ return {
881
+ meta: {
882
+ key: func.key,
883
+ name: func.name,
884
+ description: func.description,
885
+ inputSchema: Type7.toJsonSchema(func.inputSchema),
886
+ outputSchema: func.outputSchema === void 0 ? void 0 : Type7.toJsonSchema(func.outputSchema),
887
+ services: func.services
888
+ },
889
+ handler: async ({ data, context }) => {
890
+ if ((func.services.includes(DatabaseService2.key) || func.services.includes(QueueService.key)) && (!context.services.dataService || !context.services.queryService)) {
891
+ throw new FunctionError({
892
+ message: "Services not provided: dataService, queryService"
893
+ });
894
+ }
895
+ try {
896
+ const env = {
897
+ stack: [],
898
+ error: void 0,
899
+ hasError: false
900
+ };
901
+ try {
902
+ if (!SchemaAST2.isAnyKeyword(func.inputSchema.ast)) {
903
+ try {
904
+ Schema10.validateSync(func.inputSchema)(data);
905
+ } catch (error) {
906
+ throw new FunctionError({
907
+ message: "Invalid input schema",
908
+ cause: error
909
+ });
910
+ }
911
+ }
912
+ const funcContext = _ts_add_disposable_resource(env, await new FunctionContext(context).open(), true);
913
+ if (func.types.length > 0) {
914
+ invariant2(funcContext.db, "Database is required for functions with types", {
915
+ F: __dxlog_file2,
916
+ L: 63,
917
+ S: void 0,
918
+ A: [
919
+ "funcContext.db",
920
+ "'Database is required for functions with types'"
921
+ ]
922
+ });
923
+ funcContext.db.graph.schemaRegistry.addSchema(func.types);
924
+ }
925
+ let result = await func.handler({
926
+ // TODO(dmaretskyi): Fix the types.
927
+ context,
928
+ data
929
+ });
930
+ if (Effect10.isEffect(result)) {
931
+ result = await Effect10.runPromise(result.pipe(Effect10.orDie, Effect10.provide(funcContext.createLayer())));
932
+ }
933
+ if (func.outputSchema && !SchemaAST2.isAnyKeyword(func.outputSchema.ast)) {
934
+ Schema10.validateSync(func.outputSchema)(result);
935
+ }
936
+ return result;
937
+ } catch (e) {
938
+ env.error = e;
939
+ env.hasError = true;
940
+ } finally {
941
+ const result = _ts_dispose_resources(env);
942
+ if (result) await result;
943
+ }
944
+ } catch (error) {
945
+ throw error;
946
+ }
947
+ }
948
+ };
949
+ };
950
+ var FunctionContext = class extends Resource {
951
+ context;
952
+ client;
953
+ db;
954
+ queues;
955
+ constructor(context) {
956
+ super();
957
+ this.context = context;
958
+ if (context.services.dataService && context.services.queryService) {
959
+ this.client = new EchoClient().connectToService({
960
+ dataService: context.services.dataService,
961
+ queryService: context.services.queryService,
962
+ queueService: context.services.queueService
963
+ });
964
+ }
965
+ }
966
+ async _open() {
967
+ await this.client?.open();
968
+ this.db = this.client && this.context.spaceId ? this.client.constructDatabase({
969
+ spaceId: this.context.spaceId ?? failedInvariant2(),
970
+ spaceKey: PublicKey.fromHex(this.context.spaceKey ?? failedInvariant2("spaceKey missing in context")),
971
+ reactiveSchemaQuery: false
972
+ }) : void 0;
973
+ await this.db?.setSpaceRoot(this.context.spaceRootUrl ?? failedInvariant2("spaceRootUrl missing in context"));
974
+ await this.db?.open();
975
+ this.queues = this.client && this.context.spaceId ? this.client.constructQueueFactory(this.context.spaceId) : void 0;
976
+ }
977
+ async _close() {
978
+ await this.db?.close();
979
+ await this.client?.close();
980
+ }
981
+ createLayer() {
982
+ assertState(this._lifecycleState === LifecycleState.OPEN, "FunctionContext is not open");
983
+ const dbLayer = this.db ? DatabaseService2.layer(this.db) : DatabaseService2.notAvailable;
984
+ const queuesLayer = this.queues ? QueueService.layer(this.queues) : QueueService.notAvailable;
985
+ const credentials = dbLayer ? CredentialsService.layerFromDatabase().pipe(Layer5.provide(dbLayer)) : CredentialsService.configuredLayer([]);
986
+ const functionInvocationService = MockedFunctionInvocationService;
987
+ const aiService = AiService.notAvailable;
988
+ const tracing = TracingService.layerNoop;
989
+ return Layer5.mergeAll(dbLayer, queuesLayer, credentials, functionInvocationService, aiService, tracing);
990
+ }
991
+ };
992
+ var MockedFunctionInvocationService = Layer5.succeed(FunctionInvocationService, {
993
+ invokeFunction: () => Effect10.die("Calling functions from functions is not implemented yet.")
994
+ });
1334
995
  export {
1335
996
  ComputeEvent,
1336
997
  ComputeEventLogger,
@@ -1338,58 +999,32 @@ export {
1338
999
  ConfiguredCredentialsService,
1339
1000
  ContextQueueService,
1340
1001
  CredentialsService,
1341
- DatabaseService,
1342
- EmailTriggerOutput,
1002
+ DatabaseService2 as DatabaseService,
1003
+ Example,
1343
1004
  FUNCTIONS_META_KEY,
1344
1005
  FUNCTIONS_PRESET_META_KEY,
1345
- FUNCTION_TYPES,
1006
+ Function_exports as Function,
1346
1007
  FunctionDefinition,
1347
1008
  FunctionError,
1348
- FunctionExecutor,
1349
- FunctionImplementationResolver,
1350
1009
  FunctionInvocationService,
1351
- FunctionManifestSchema,
1352
1010
  FunctionNotFoundError,
1353
- FunctionTrigger,
1354
- FunctionType,
1355
- InvocationOutcome,
1356
- InvocationTraceEndEvent,
1357
- InvocationTraceEventType,
1358
- InvocationTraceStartEvent,
1359
- InvocationTracer,
1360
- LocalFunctionExecutionService,
1361
1011
  MESSAGE_PROPERTY_TOOL_CALL_ID,
1362
1012
  QueueService,
1363
- QueueTriggerOutput,
1364
- RemoteFunctionExecutionService,
1365
- SERVICE_TAGS,
1366
- ScriptType,
1367
- ServiceContainer,
1013
+ Script_exports as Script,
1368
1014
  ServiceNotAvailableError,
1369
- SubscriptionTriggerOutput,
1370
- TimerTriggerOutput,
1371
- TraceEvent,
1372
- TraceEventException,
1373
- TraceEventLog,
1374
1015
  TracingService,
1375
- TriggerDispatcher,
1376
- TriggerKinds,
1377
- TriggerSchema,
1378
- TriggerState,
1016
+ Trigger_exports as Trigger,
1017
+ TriggerEvent_exports as TriggerEvent,
1379
1018
  TriggerStateNotFoundError,
1380
- TriggerStateStore,
1381
- WebhookTriggerOutput,
1382
1019
  createDefectLogger,
1383
1020
  createEventLogger,
1384
- createInvocationSpans,
1385
1021
  defineFunction,
1386
1022
  deserializeFunction,
1387
- examples_exports as exampleFunctions,
1388
- getInvocationUrl,
1389
1023
  getUserFunctionIdInMetadata,
1390
1024
  logCustomEvent,
1391
1025
  serializeFunction,
1392
1026
  setUserFunctionIdInMetadata,
1393
- withAuthorization
1027
+ withAuthorization,
1028
+ wrapFunctionHandler
1394
1029
  };
1395
1030
  //# sourceMappingURL=index.mjs.map