@dxos/functions 0.8.4-main.2e9d522 → 0.8.4-main.3c1ae3b

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