@dxos/functions 0.8.3 → 0.8.4-main.84f28bd

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 (69) hide show
  1. package/dist/lib/browser/bundler/index.mjs +21 -10
  2. package/dist/lib/browser/bundler/index.mjs.map +3 -3
  3. package/dist/lib/browser/{chunk-WEFZUEL2.mjs → chunk-54U464M4.mjs} +79 -19
  4. package/dist/lib/browser/chunk-54U464M4.mjs.map +7 -0
  5. package/dist/lib/browser/edge/index.mjs +2 -2
  6. package/dist/lib/browser/index.mjs +20 -14
  7. package/dist/lib/browser/index.mjs.map +3 -3
  8. package/dist/lib/browser/meta.json +1 -1
  9. package/dist/lib/browser/testing/index.mjs +58 -7
  10. package/dist/lib/browser/testing/index.mjs.map +4 -4
  11. package/dist/lib/node-esm/bundler/index.mjs +21 -10
  12. package/dist/lib/node-esm/bundler/index.mjs.map +3 -3
  13. package/dist/lib/node-esm/{chunk-LIYPMWNQ.mjs → chunk-XDSX35BS.mjs} +79 -19
  14. package/dist/lib/node-esm/chunk-XDSX35BS.mjs.map +7 -0
  15. package/dist/lib/node-esm/edge/index.mjs +2 -2
  16. package/dist/lib/node-esm/index.mjs +20 -14
  17. package/dist/lib/node-esm/index.mjs.map +3 -3
  18. package/dist/lib/node-esm/meta.json +1 -1
  19. package/dist/lib/node-esm/testing/index.mjs +58 -7
  20. package/dist/lib/node-esm/testing/index.mjs.map +4 -4
  21. package/dist/types/src/bundler/bundler.d.ts +1 -2
  22. package/dist/types/src/bundler/bundler.d.ts.map +1 -1
  23. package/dist/types/src/executor/executor.d.ts.map +1 -1
  24. package/dist/types/src/handler.d.ts +3 -6
  25. package/dist/types/src/handler.d.ts.map +1 -1
  26. package/dist/types/src/schema.d.ts +3 -3
  27. package/dist/types/src/services/credentials.d.ts +1 -1
  28. package/dist/types/src/services/credentials.d.ts.map +1 -1
  29. package/dist/types/src/services/database.d.ts +5 -1
  30. package/dist/types/src/services/database.d.ts.map +1 -1
  31. package/dist/types/src/services/index.d.ts +1 -0
  32. package/dist/types/src/services/index.d.ts.map +1 -1
  33. package/dist/types/src/services/queues.d.ts +2 -2
  34. package/dist/types/src/services/queues.d.ts.map +1 -1
  35. package/dist/types/src/services/service-container.d.ts +3 -1
  36. package/dist/types/src/services/service-container.d.ts.map +1 -1
  37. package/dist/types/src/services/tool-resolver.d.ts +14 -0
  38. package/dist/types/src/services/tool-resolver.d.ts.map +1 -0
  39. package/dist/types/src/testing/services.d.ts +67 -9
  40. package/dist/types/src/testing/services.d.ts.map +1 -1
  41. package/dist/types/src/translations.d.ts +9 -9
  42. package/dist/types/src/translations.d.ts.map +1 -1
  43. package/dist/types/tsconfig.tsbuildinfo +1 -1
  44. package/package.json +29 -26
  45. package/src/bundler/bundler.test.ts +1 -1
  46. package/src/bundler/bundler.ts +26 -4
  47. package/src/executor/executor.ts +15 -8
  48. package/src/handler.ts +6 -6
  49. package/src/services/credentials.ts +1 -1
  50. package/src/services/database.ts +23 -1
  51. package/src/services/index.ts +1 -0
  52. package/src/services/queues.ts +9 -4
  53. package/src/services/service-container.ts +21 -3
  54. package/src/services/tool-resolver.ts +31 -0
  55. package/src/testing/services.ts +156 -14
  56. package/src/translations.ts +4 -4
  57. package/dist/lib/browser/chunk-WEFZUEL2.mjs.map +0 -7
  58. package/dist/lib/node/bundler/index.cjs +0 -260
  59. package/dist/lib/node/bundler/index.cjs.map +0 -7
  60. package/dist/lib/node/chunk-IJAE7FZK.cjs +0 -320
  61. package/dist/lib/node/chunk-IJAE7FZK.cjs.map +0 -7
  62. package/dist/lib/node/edge/index.cjs +0 -94
  63. package/dist/lib/node/edge/index.cjs.map +0 -7
  64. package/dist/lib/node/index.cjs +0 -522
  65. package/dist/lib/node/index.cjs.map +0 -7
  66. package/dist/lib/node/meta.json +0 -1
  67. package/dist/lib/node/testing/index.cjs +0 -43
  68. package/dist/lib/node/testing/index.cjs.map +0 -7
  69. package/dist/lib/node-esm/chunk-LIYPMWNQ.mjs.map +0 -7
@@ -1,7 +0,0 @@
1
- {
2
- "version": 3,
3
- "sources": ["../../../src/services/ai.ts", "../../../src/services/database.ts", "../../../src/services/queues.ts", "../../../src/services/credentials.ts", "../../../src/services/event-logger.ts", "../../../src/services/function-call-service.ts", "../../../src/services/tracing.ts", "../../../src/services/service-container.ts"],
4
- "sourcesContent": ["//\n// Copyright 2025 DXOS.org\n//\n\nimport { Context, Layer } from 'effect';\n\nimport type { AiServiceClient } from '@dxos/ai';\n\n// TODO(burdon): Move to @dxos/ai.\nexport class AiService extends Context.Tag('AiService')<\n AiService,\n {\n readonly client: AiServiceClient;\n }\n>() {\n static make = (client: AiServiceClient): Context.Tag.Service<AiService> => {\n return {\n get client() {\n return client;\n },\n };\n };\n\n static makeLayer = (client: AiServiceClient): Layer.Layer<AiService> =>\n Layer.succeed(AiService, AiService.make(client));\n\n static notAvailable = Layer.succeed(AiService, {\n get client(): AiServiceClient {\n throw new Error('AiService not available');\n },\n });\n}\n", "//\n// Copyright 2025 DXOS.org\n//\n\nimport { Context, Layer } from 'effect';\n\nimport type { EchoDatabase } from '@dxos/echo-db';\n\nexport class DatabaseService extends Context.Tag('DatabaseService')<\n DatabaseService,\n {\n readonly db: EchoDatabase;\n }\n>() {\n static notAvailable = Layer.succeed(DatabaseService, {\n get db(): EchoDatabase {\n throw new Error('Database not available');\n },\n });\n\n static make = (db: EchoDatabase): Context.Tag.Service<DatabaseService> => {\n return {\n get db() {\n return db;\n },\n };\n };\n}\n", "//\n// Copyright 2025 DXOS.org\n//\n\nimport { Context, Layer } from 'effect';\n\nimport type { Queue, QueueFactory } from '@dxos/echo-db';\n\nexport class QueueService extends Context.Tag('QueueService')<\n QueueService,\n {\n /**\n * API to access the queues.\n */\n readonly queues: QueueFactory;\n\n /**\n * The queue that is used to store the context of the current research.\n */\n // TODO(dmaretskyi): Is this really part of the queue service?\n readonly contextQueue: Queue | undefined;\n }\n>() {\n static notAvailable = Layer.succeed(QueueService, {\n get queues(): QueueFactory {\n throw new Error('Queues not available');\n },\n contextQueue: undefined,\n });\n\n static make = (queues: QueueFactory, contextQueue: Queue | undefined): Context.Tag.Service<QueueService> => {\n return {\n queues,\n contextQueue,\n };\n };\n}\n", "//\n// Copyright 2025 DXOS.org\n//\n\nimport { Context } from 'effect';\n\ntype CredentialQuery = {\n service?: string;\n};\n\n// TODO(dmaretskyi): Unify with other apis.\n// packages/sdk/schema/src/common/access-token.ts\ntype ServiceCredential = {\n service: string;\n\n // TODO(dmaretskyi): Build out.\n apiKey?: string;\n};\n\nexport class CredentialsService extends Context.Tag('CredentialsService')<\n CredentialsService,\n {\n /**\n * Query all.\n */\n queryCredentials: (query: CredentialQuery) => Promise<ServiceCredential[]>;\n\n /**\n * Get a single credential.\n * @throws {Error} If no credential is found.\n */\n getCredential: (query: CredentialQuery) => Promise<ServiceCredential>;\n }\n>() {}\n\nexport class ConfiguredCredentialsService implements Context.Tag.Service<CredentialsService> {\n constructor(private readonly credentials: ServiceCredential[] = []) {}\n\n addCredentials(credentials: ServiceCredential[]): ConfiguredCredentialsService {\n this.credentials.push(...credentials);\n return this;\n }\n\n async queryCredentials(query: CredentialQuery): Promise<ServiceCredential[]> {\n return this.credentials.filter((credential) => credential.service === query.service);\n }\n\n async getCredential(query: CredentialQuery): Promise<ServiceCredential> {\n const credential = this.credentials.find((credential) => credential.service === query.service);\n if (!credential) {\n throw new Error(`Credential not found for service: ${query.service}`);\n }\n return credential;\n }\n}\n", "//\n// Copyright 2025 DXOS.org\n//\n\nimport { Effect, Context } from 'effect';\n\nimport { invariant } from '@dxos/invariant';\nimport { log, LogLevel } from '@dxos/log';\n\nexport type ComputeEvent =\n | {\n type: 'begin-compute';\n nodeId: string;\n inputs: Record<string, any>;\n }\n | {\n type: 'end-compute';\n nodeId: string;\n outputs: Record<string, any>;\n }\n | {\n type: 'compute-input';\n nodeId: string;\n property: string;\n value: any;\n }\n | {\n type: 'compute-output';\n nodeId: string;\n property: string;\n value: any;\n }\n | {\n type: 'custom';\n nodeId: string;\n event: any;\n };\n\nexport class EventLogger extends Context.Tag('EventLogger')<\n EventLogger,\n { readonly log: (event: ComputeEvent) => void; readonly nodeId: string | undefined }\n>() {\n static noop: Context.Tag.Service<EventLogger> = {\n log: () => {},\n nodeId: undefined,\n };\n}\n\nexport const logCustomEvent = (data: any) =>\n Effect.gen(function* () {\n const logger = yield* EventLogger;\n if (!logger.nodeId) {\n throw new Error('logCustomEvent must be called within a node compute function');\n }\n logger.log({\n type: 'custom',\n nodeId: logger.nodeId,\n event: data,\n });\n });\n\nexport const createDefectLogger = <A, E, R>(): ((self: Effect.Effect<A, E, R>) => Effect.Effect<A, E, R>) =>\n Effect.catchAll((error) =>\n Effect.gen(function* () {\n log.error('unhandled effect error', { error });\n throw error;\n }),\n );\n\nexport const createEventLogger = (level: LogLevel, message: string = 'event'): Context.Tag.Service<EventLogger> => {\n const logFunction = (\n {\n [LogLevel.WARN]: log.warn,\n [LogLevel.VERBOSE]: log.verbose,\n [LogLevel.DEBUG]: log.debug,\n [LogLevel.INFO]: log.info,\n [LogLevel.ERROR]: log.error,\n } as any\n )[level];\n invariant(logFunction);\n return {\n log: (event: ComputeEvent) => {\n logFunction(message, event);\n },\n nodeId: undefined,\n };\n};\n", "//\n// Copyright 2025 DXOS.org\n//\n\nimport { Context } from 'effect';\n\nimport type { SpaceId } from '@dxos/keys';\n\n/**\n * Allows calling into other functions.\n */\nexport class FunctionCallService extends Context.Tag('FunctionCallService')<\n FunctionCallService,\n {\n callFunction(deployedFunctionId: string, input: any, spaceId?: SpaceId): Promise<any>;\n }\n>() {\n static fromClient(baseUrl: string, spaceId: SpaceId): Context.Tag.Service<FunctionCallService> {\n return {\n callFunction: async (deployedFunctionId: string, input: any) => {\n const url = getInvocationUrl(deployedFunctionId, baseUrl, { spaceId });\n const result = await fetch(url, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify(input),\n });\n if (result.status >= 300 || result.status < 200) {\n throw new Error('Failed to invoke function', { cause: new Error(`HTTP error: ${await result.text()}`) });\n }\n return await result.json();\n },\n };\n }\n\n static mock = () => {\n return {\n callFunction: async (deployedFunctionId: string, input: any) => {\n return input;\n },\n };\n };\n}\n\n// TODO(dmaretskyi): Reconcile with `getInvocationUrl` in `@dxos/functions/edge`.\nconst getInvocationUrl = (functionUrl: string, edgeUrl: string, options: InvocationOptions = {}) => {\n const baseUrl = new URL('functions/', edgeUrl);\n\n // Leading slashes cause the URL to be treated as an absolute path.\n const relativeUrl = functionUrl.replace(/^\\//, '');\n const url = new URL(`./${relativeUrl}`, baseUrl.toString());\n options.spaceId && url.searchParams.set('spaceId', options.spaceId);\n options.subjectId && url.searchParams.set('subjectId', options.subjectId);\n url.protocol = isSecure(url.protocol) ? 'https' : 'http';\n return url.toString();\n};\n\nconst isSecure = (protocol: string) => {\n return protocol === 'https:' || protocol === 'wss:';\n};\n\ntype InvocationOptions = {\n spaceId?: SpaceId;\n subjectId?: string;\n};\n", "//\n// Copyright 2025 DXOS.org\n//\n\nimport { Context } from 'effect';\n\nimport type { AnyEchoObject } from '@dxos/echo-schema';\n\nexport class TracingService extends Context.Tag('TracingService')<\n TracingService,\n {\n /**\n * Write an event to the tracing queue.\n * @param event - The event to write. Must be an a typed object.\n */\n write(event: AnyEchoObject): void;\n }\n>() {\n static noop: Context.Tag.Service<TracingService> = { write: () => {} };\n\n static console: Context.Tag.Service<TracingService> = {\n write: (event) => {\n // eslint-disable-next-line no-console\n console.log(event);\n },\n };\n}\n", "//\n// Copyright 2025 DXOS.org\n//\n\nimport { Layer, type Context } from 'effect';\n\nimport { AiService } from './ai';\nimport { ConfiguredCredentialsService, CredentialsService } from './credentials';\nimport { DatabaseService } from './database';\nimport { EventLogger } from './event-logger';\nimport { FunctionCallService } from './function-call-service';\nimport { QueueService } from './queues';\nimport { TracingService } from './tracing';\n\n/**\n * List of all service tags and their names.\n */\nexport interface ServiceTagRecord {\n ai: AiService;\n credentials: CredentialsService;\n database: DatabaseService;\n eventLogger: EventLogger;\n functionCallService: FunctionCallService;\n tracing: TracingService;\n queues: QueueService;\n}\n\n/**\n * List of all services and their runtime types.\n */\nexport type ServiceRecord = {\n [K in keyof ServiceTagRecord]: Context.Tag.Service<ServiceTagRecord[K]>;\n};\n\n/**\n * Union of all services.\n */\nexport type Services = ServiceTagRecord[keyof ServiceTagRecord];\n\nconst SERVICE_MAPPING: Record<string, keyof ServiceRecord> = {\n [AiService.key]: 'ai',\n [CredentialsService.key]: 'credentials',\n [DatabaseService.key]: 'database',\n [EventLogger.key]: 'eventLogger',\n [FunctionCallService.key]: 'functionCallService',\n [QueueService.key]: 'queues',\n [TracingService.key]: 'tracing',\n};\n\nexport const SERVICE_TAGS: Context.Tag<any, any>[] = [\n AiService,\n CredentialsService,\n DatabaseService,\n EventLogger,\n FunctionCallService,\n TracingService,\n QueueService,\n];\n\nconst DEFAULT_SERVICES: Partial<ServiceRecord> = {\n tracing: TracingService.noop,\n};\n\nexport class ServiceContainer {\n private _services: Partial<ServiceRecord> = { ...DEFAULT_SERVICES };\n\n /**\n * Set services.\n * @param services - Services to set.\n * @returns The container instance.\n */\n setServices(services: Partial<ServiceRecord>): this {\n this._services = { ...this._services, ...services };\n return this;\n }\n\n getService<T extends Context.Tag<any, any>>(tag: T): Context.Tag.Service<T> {\n const serviceKey = SERVICE_MAPPING[tag.key];\n const service = serviceKey != null ? this._services[serviceKey] : undefined;\n if (!service) {\n throw new Error(`Service not available: ${tag.key}`);\n }\n return service as Context.Tag.Service<T>;\n }\n\n clone(): ServiceContainer {\n return new ServiceContainer().setServices({ ...this._services });\n }\n\n // TODO(dmaretskyi): `getService` is designed to error at runtime if the service is not available, but layer forces us to provide all services and makes stubs for the ones that are not available.\n createLayer(): Layer.Layer<Services> {\n const ai = this._services.ai != null ? Layer.succeed(AiService, this._services.ai) : AiService.notAvailable;\n const credentials = Layer.succeed(CredentialsService, new ConfiguredCredentialsService());\n const database =\n this._services.database != null\n ? Layer.succeed(DatabaseService, this._services.database)\n : DatabaseService.notAvailable;\n const queues =\n this._services.queues != null ? Layer.succeed(QueueService, this._services.queues) : QueueService.notAvailable;\n const tracing = Layer.succeed(TracingService, this._services.tracing ?? TracingService.noop);\n const eventLogger = Layer.succeed(EventLogger, this._services.eventLogger ?? EventLogger.noop);\n const functionCallService = Layer.succeed(\n FunctionCallService,\n this._services.functionCallService ?? FunctionCallService.mock(),\n );\n\n return Layer.mergeAll(ai, credentials, database, queues, tracing, eventLogger, functionCallService);\n }\n}\n"],
5
- "mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAIA,oBAA+B;ACA/B,IAAAA,iBAA+B;ACA/B,IAAAA,iBAA+B;ACA/B,IAAAA,iBAAwB;ACAxB,IAAAA,iBAAgC;AAEhC,uBAA0B;AAC1B,iBAA8B;ACH9B,IAAAA,iBAAwB;ACAxB,IAAAA,iBAAwB;ACAxB,IAAAA,iBAAoC;APK7B,IAAMC,YAAN,MAAMA,mBAAkBC,sBAAQC,IAAI,WAAA,EAAA,EAAA;EAMzC,OAAA;SAAOC,OAAO,CAACC,WAAAA;AACb,aAAO;QACL,IAAIA,SAAS;AACX,iBAAOA;QACT;MACF;IACF;;EAEA,OAAA;SAAOC,YAAY,CAACD,WAClBE,oBAAMC,QAAQP,YAAWA,WAAUG,KAAKC,MAAAA,CAAAA;;EAE1C,OAAA;SAAOI,eAAeF,oBAAMC,QAAQP,YAAW;MAC7C,IAAII,SAA0B;AAC5B,cAAM,IAAIK,MAAM,yBAAA;MAClB;IACF,CAAA;;AACF;ACvBO,IAAMC,kBAAN,MAAMA,yBAAwBT,eAAAA,QAAQC,IAAI,iBAAA,EAAA,EAAA;EAM/C,OAAA;SAAOM,eAAeF,eAAAA,MAAMC,QAAQG,kBAAiB;MACnD,IAAIC,KAAmB;AACrB,cAAM,IAAIF,MAAM,wBAAA;MAClB;IACF,CAAA;;EAEA,OAAA;SAAON,OAAO,CAACQ,OAAAA;AACb,aAAO;QACL,IAAIA,KAAK;AACP,iBAAOA;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BAAsBxG,eAAAA,MAAMC,QAChCkD,qBACA,KAAK0C,UAAUW,uBAAuBrD,oBAAoBoB,KAAI,CAAA;AAGhE,WAAOvE,eAAAA,MAAMyG,SAASJ,IAAIzF,aAAa0F,UAAU/F,QAAQoF,SAASY,aAAaC,mBAAAA;EACjF;AACF;",
6
- "names": ["import_effect", "AiService", "Context", "Tag", "make", "client", "makeLayer", "Layer", "succeed", "notAvailable", "Error", "DatabaseService", "db", "QueueService", "queues", "contextQueue", "undefined", "CredentialsService", "ConfiguredCredentialsService", "credentials", "addCredentials", "push", "queryCredentials", "query", "filter", "credential", "service", "getCredential", "find", "EventLogger", "noop", "log", "nodeId", "logCustomEvent", "data", "Effect", "gen", "logger", "type", "event", "createDefectLogger", "catchAll", "error", "createEventLogger", "level", "message", "logFunction", "LogLevel", "WARN", "warn", "VERBOSE", "verbose", "DEBUG", "debug", "INFO", "info", "ERROR", "invariant", "FunctionCallService", "fromClient", "baseUrl", "spaceId", "callFunction", "deployedFunctionId", "input", "url", "getInvocationUrl", "result", "fetch", "method", "headers", "body", "JSON", "stringify", "status", "cause", "text", "json", "mock", "functionUrl", "edgeUrl", "options", "URL", "relativeUrl", "replace", "toString", "searchParams", "set", "subjectId", "protocol", "isSecure", "TracingService", "write", "console", "SERVICE_MAPPING", "key", "SERVICE_TAGS", "DEFAULT_SERVICES", "tracing", "ServiceContainer", "_services", "setServices", "services", "getService", "tag", "serviceKey", "clone", "createLayer", "ai", "database", "eventLogger", "functionCallService", "mergeAll"]
7
- }
@@ -1,94 +0,0 @@
1
- "use strict";
2
- var __defProp = Object.defineProperty;
3
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
- var __getOwnPropNames = Object.getOwnPropertyNames;
5
- var __hasOwnProp = Object.prototype.hasOwnProperty;
6
- var __export = (target, all) => {
7
- for (var name in all)
8
- __defProp(target, name, { get: all[name], enumerable: true });
9
- };
10
- var __copyProps = (to, from, except, desc) => {
11
- if (from && typeof from === "object" || typeof from === "function") {
12
- for (let key of __getOwnPropNames(from))
13
- if (!__hasOwnProp.call(to, key) && key !== except)
14
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
- }
16
- return to;
17
- };
18
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
- var edge_exports = {};
20
- __export(edge_exports, {
21
- incrementSemverPatch: () => incrementSemverPatch,
22
- publicKeyToDid: () => publicKeyToDid,
23
- uploadWorkerFunction: () => uploadWorkerFunction
24
- });
25
- module.exports = __toCommonJS(edge_exports);
26
- var import_edge = require("@dxos/client/edge");
27
- var import_edge_client = require("@dxos/edge-client");
28
- var import_invariant = require("@dxos/invariant");
29
- var import_log = require("@dxos/log");
30
- var __dxlog_file = "/home/runner/work/dxos/dxos/packages/core/functions/src/edge/functions.ts";
31
- var uploadWorkerFunction = async ({ client, version, source, name, functionId, ownerPublicKey }) => {
32
- const edgeUrl = client.config.values.runtime?.services?.edge?.url;
33
- (0, import_invariant.invariant)(edgeUrl, "Edge is not configured.", {
34
- F: __dxlog_file,
35
- L: 33,
36
- S: void 0,
37
- A: [
38
- "edgeUrl",
39
- "'Edge is not configured.'"
40
- ]
41
- });
42
- const edgeClient = new import_edge_client.EdgeHttpClient(edgeUrl);
43
- const edgeIdentity = (0, import_edge.createEdgeIdentity)(client);
44
- edgeClient.setIdentity(edgeIdentity);
45
- const response = await edgeClient.uploadFunction({
46
- functionId
47
- }, {
48
- name,
49
- version,
50
- script: source,
51
- ownerPublicKey: ownerPublicKey.toHex()
52
- });
53
- import_log.log.info("Uploaded", {
54
- identityKey: edgeIdentity.identityKey,
55
- functionId,
56
- name,
57
- source: source.length,
58
- response
59
- }, {
60
- F: __dxlog_file,
61
- L: 43,
62
- S: void 0,
63
- C: (f, a) => f(...a)
64
- });
65
- return response;
66
- };
67
- var incrementSemverPatch = (version) => {
68
- const [major, minor, patch] = version.split(".");
69
- const patchNum = Number(patch);
70
- (0, import_invariant.invariant)(!Number.isNaN(patchNum), `Unexpected function version format: ${version}`, {
71
- F: __dxlog_file,
72
- L: 57,
73
- S: void 0,
74
- A: [
75
- "!Number.isNaN(patchNum)",
76
- "`Unexpected function version format: ${version}`"
77
- ]
78
- });
79
- return [
80
- major,
81
- minor,
82
- String(patchNum + 1)
83
- ].join(".");
84
- };
85
- var publicKeyToDid = (key) => {
86
- return `did:key:${key.toHex()}`;
87
- };
88
- // Annotate the CommonJS export names for ESM import in node:
89
- 0 && (module.exports = {
90
- incrementSemverPatch,
91
- publicKeyToDid,
92
- uploadWorkerFunction
93
- });
94
- //# sourceMappingURL=index.cjs.map
@@ -1,7 +0,0 @@
1
- {
2
- "version": 3,
3
- "sources": ["../../../../src/edge/functions.ts"],
4
- "sourcesContent": ["//\n// Copyright 2024 DXOS.org\n//\n\nimport { type DID } from 'iso-did/types';\n\nimport { type Client } from '@dxos/client';\nimport { createEdgeIdentity } from '@dxos/client/edge';\nimport { EdgeHttpClient } from '@dxos/edge-client';\nimport { invariant } from '@dxos/invariant';\nimport type { PublicKey } from '@dxos/keys';\nimport { log } from '@dxos/log';\nimport { type UploadFunctionResponseBody } from '@dxos/protocols';\n\nexport type UploadWorkerArgs = {\n client: Client;\n source: string;\n version: string;\n name?: string;\n functionId?: string;\n ownerPublicKey: PublicKey;\n};\n\nexport const uploadWorkerFunction = async ({\n client,\n version,\n source,\n name,\n functionId,\n ownerPublicKey,\n}: UploadWorkerArgs): Promise<UploadFunctionResponseBody> => {\n const edgeUrl = client.config.values.runtime?.services?.edge?.url;\n invariant(edgeUrl, 'Edge is not configured.');\n const edgeClient = new EdgeHttpClient(edgeUrl);\n const edgeIdentity = createEdgeIdentity(client);\n edgeClient.setIdentity(edgeIdentity);\n const response = await edgeClient.uploadFunction(\n { functionId },\n { name, version, script: source, ownerPublicKey: ownerPublicKey.toHex() },\n );\n\n // TODO(burdon): Edge service log.\n log.info('Uploaded', {\n identityKey: edgeIdentity.identityKey,\n functionId,\n name,\n source: source.length,\n response,\n });\n\n return response;\n};\n\nexport const incrementSemverPatch = (version: string): string => {\n const [major, minor, patch] = version.split('.');\n const patchNum = Number(patch);\n invariant(!Number.isNaN(patchNum), `Unexpected function version format: ${version}`);\n return [major, minor, String(patchNum + 1)].join('.');\n};\n\n// TODO(burdon): Factor out.\nexport const publicKeyToDid = (key: PublicKey): DID => {\n return `did:key:${key.toHex()}`;\n};\n"],
5
- "mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;AAOA,kBAAmC;AACnC,yBAA+B;AAC/B,uBAA0B;AAE1B,iBAAoB;;AAYb,IAAMA,uBAAuB,OAAO,EACzCC,QACAC,SACAC,QACAC,MACAC,YACAC,eAAc,MACG;AACjB,QAAMC,UAAUN,OAAOO,OAAOC,OAAOC,SAASC,UAAUC,MAAMC;AAC9DC,kCAAUP,SAAS,2BAAA;;;;;;;;;AACnB,QAAMQ,aAAa,IAAIC,kCAAeT,OAAAA;AACtC,QAAMU,mBAAeC,gCAAmBjB,MAAAA;AACxCc,aAAWI,YAAYF,YAAAA;AACvB,QAAMG,WAAW,MAAML,WAAWM,eAChC;IAAEhB;EAAW,GACb;IAAED;IAAMF;IAASoB,QAAQnB;IAAQG,gBAAgBA,eAAeiB,MAAK;EAAG,CAAA;AAI1EC,iBAAIC,KAAK,YAAY;IACnBC,aAAaT,aAAaS;IAC1BrB;IACAD;IACAD,QAAQA,OAAOwB;IACfP;EACF,GAAA;;;;;;AAEA,SAAOA;AACT;AAEO,IAAMQ,uBAAuB,CAAC1B,YAAAA;AACnC,QAAM,CAAC2B,OAAOC,OAAOC,KAAAA,IAAS7B,QAAQ8B,MAAM,GAAA;AAC5C,QAAMC,WAAWC,OAAOH,KAAAA;AACxBjB,kCAAU,CAACoB,OAAOC,MAAMF,QAAAA,GAAW,uCAAuC/B,OAAAA,IAAS;;;;;;;;;AACnF,SAAO;IAAC2B;IAAOC;IAAOM,OAAOH,WAAW,CAAA;IAAII,KAAK,GAAA;AACnD;AAGO,IAAMC,iBAAiB,CAACC,QAAAA;AAC7B,SAAO,WAAWA,IAAIhB,MAAK,CAAA;AAC7B;",
6
- "names": ["uploadWorkerFunction", "client", "version", "source", "name", "functionId", "ownerPublicKey", "edgeUrl", "config", "values", "runtime", "services", "edge", "url", "invariant", "edgeClient", "EdgeHttpClient", "edgeIdentity", "createEdgeIdentity", "setIdentity", "response", "uploadFunction", "script", "toHex", "log", "info", "identityKey", "length", "incrementSemverPatch", "major", "minor", "patch", "split", "patchNum", "Number", "isNaN", "String", "join", "publicKeyToDid", "key"]
7
- }
@@ -1,522 +0,0 @@
1
- "use strict";
2
- var __defProp = Object.defineProperty;
3
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
- var __getOwnPropNames = Object.getOwnPropertyNames;
5
- var __hasOwnProp = Object.prototype.hasOwnProperty;
6
- var __export = (target, all) => {
7
- for (var name in all)
8
- __defProp(target, name, { get: all[name], enumerable: true });
9
- };
10
- var __copyProps = (to, from, except, desc) => {
11
- if (from && typeof from === "object" || typeof from === "function") {
12
- for (let key of __getOwnPropNames(from))
13
- if (!__hasOwnProp.call(to, key) && key !== except)
14
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
- }
16
- return to;
17
- };
18
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
- var node_exports = {};
20
- __export(node_exports, {
21
- AiService: () => import_chunk_IJAE7FZK.AiService,
22
- ConfiguredCredentialsService: () => import_chunk_IJAE7FZK.ConfiguredCredentialsService,
23
- CredentialsService: () => import_chunk_IJAE7FZK.CredentialsService,
24
- DatabaseService: () => import_chunk_IJAE7FZK.DatabaseService,
25
- EmailTriggerOutput: () => EmailTriggerOutput,
26
- EventLogger: () => import_chunk_IJAE7FZK.EventLogger,
27
- FUNCTIONS_PRESET_META_KEY: () => FUNCTIONS_PRESET_META_KEY,
28
- FUNCTION_TYPES: () => FUNCTION_TYPES,
29
- FunctionCallService: () => import_chunk_IJAE7FZK.FunctionCallService,
30
- FunctionExecutor: () => FunctionExecutor,
31
- FunctionManifestSchema: () => FunctionManifestSchema,
32
- FunctionTrigger: () => FunctionTrigger,
33
- FunctionTriggerSchema: () => FunctionTriggerSchema,
34
- FunctionType: () => FunctionType,
35
- InvocationOutcome: () => InvocationOutcome,
36
- InvocationTraceEndEvent: () => InvocationTraceEndEvent,
37
- InvocationTraceEventType: () => InvocationTraceEventType,
38
- InvocationTraceStartEvent: () => InvocationTraceStartEvent,
39
- QueueService: () => import_chunk_IJAE7FZK.QueueService,
40
- QueueTriggerOutput: () => QueueTriggerOutput,
41
- SERVICE_TAGS: () => import_chunk_IJAE7FZK.SERVICE_TAGS,
42
- ScriptType: () => ScriptType,
43
- ServiceContainer: () => import_chunk_IJAE7FZK.ServiceContainer,
44
- SubscriptionTriggerOutput: () => SubscriptionTriggerOutput,
45
- TimerTriggerOutput: () => TimerTriggerOutput,
46
- TraceEvent: () => TraceEvent,
47
- TraceEventException: () => TraceEventException,
48
- TraceEventLog: () => TraceEventLog,
49
- TracingService: () => import_chunk_IJAE7FZK.TracingService,
50
- TriggerKind: () => TriggerKind,
51
- TriggerSchema: () => TriggerSchema,
52
- WebhookTriggerOutput: () => WebhookTriggerOutput,
53
- createDefectLogger: () => import_chunk_IJAE7FZK.createDefectLogger,
54
- createEventLogger: () => import_chunk_IJAE7FZK.createEventLogger,
55
- createInvocationSpans: () => createInvocationSpans,
56
- defineFunction: () => defineFunction,
57
- getInvocationUrl: () => getInvocationUrl,
58
- getUserFunctionUrlInMetadata: () => getUserFunctionUrlInMetadata,
59
- logCustomEvent: () => import_chunk_IJAE7FZK.logCustomEvent,
60
- makeFunctionUrl: () => makeFunctionUrl,
61
- setUserFunctionUrlInMetadata: () => setUserFunctionUrlInMetadata
62
- });
63
- module.exports = __toCommonJS(node_exports);
64
- var import_chunk_IJAE7FZK = require("./chunk-IJAE7FZK.cjs");
65
- var import_effect = require("effect");
66
- var import_effect2 = require("effect");
67
- var import_echo = require("@dxos/echo");
68
- var import_echo_schema = require("@dxos/echo-schema");
69
- var import_schema = require("@dxos/schema");
70
- var import_effect3 = require("effect");
71
- var import_echo2 = require("@dxos/echo");
72
- var import_echo_db = require("@dxos/echo-db");
73
- var import_echo_schema2 = require("@dxos/echo-schema");
74
- var import_log = require("@dxos/log");
75
- var import_effect4 = require("effect");
76
- var import_echo_schema3 = require("@dxos/echo-schema");
77
- var import_keys = require("@dxos/keys");
78
- var import_effect5 = require("effect");
79
- var defineFunction = (params) => {
80
- if (!import_effect.Schema.isSchema(params.inputSchema)) {
81
- throw new Error("Input schema must be a valid schema");
82
- }
83
- if (typeof params.handler !== "function") {
84
- throw new Error("Handler must be a function");
85
- }
86
- return {
87
- description: params.description,
88
- inputSchema: params.inputSchema,
89
- outputSchema: params.outputSchema ?? import_effect.Schema.Any,
90
- handler: params.handler
91
- };
92
- };
93
- var ScriptType = import_effect2.Schema.Struct({
94
- name: import_effect2.Schema.optional(import_effect2.Schema.String),
95
- description: import_effect2.Schema.optional(import_effect2.Schema.String),
96
- // TODO(burdon): Change to hash of deployed content.
97
- // Whether source has changed since last deploy.
98
- changed: import_effect2.Schema.optional(import_effect2.Schema.Boolean),
99
- source: (0, import_echo_schema.Ref)(import_schema.DataType.Text)
100
- }).pipe(import_echo.Type.Obj({
101
- typename: "dxos.org/type/Script",
102
- version: "0.1.0"
103
- }), import_echo_schema.LabelAnnotation.set([
104
- "name"
105
- ]));
106
- var FunctionType = import_effect2.Schema.Struct({
107
- // TODO(burdon): Rename to id/uri?
108
- name: import_effect2.Schema.NonEmptyString,
109
- version: import_effect2.Schema.String,
110
- description: import_effect2.Schema.optional(import_effect2.Schema.String),
111
- // Reference to a source script if it exists within ECHO.
112
- // TODO(burdon): Don't ref ScriptType directly (core).
113
- source: import_effect2.Schema.optional((0, import_echo_schema.Ref)(ScriptType)),
114
- inputSchema: import_effect2.Schema.optional(import_echo_schema.JsonSchemaType),
115
- outputSchema: import_effect2.Schema.optional(import_echo_schema.JsonSchemaType),
116
- // Local binding to a function name.
117
- binding: import_effect2.Schema.optional(import_effect2.Schema.String)
118
- }).pipe(import_echo.Type.Obj({
119
- typename: "dxos.org/type/Function",
120
- version: "0.1.0"
121
- }), import_echo_schema.LabelAnnotation.set([
122
- "name"
123
- ]));
124
- var TriggerKind = /* @__PURE__ */ function(TriggerKind2) {
125
- TriggerKind2["Timer"] = "timer";
126
- TriggerKind2["Webhook"] = "webhook";
127
- TriggerKind2["Subscription"] = "subscription";
128
- TriggerKind2["Email"] = "email";
129
- TriggerKind2["Queue"] = "queue";
130
- return TriggerKind2;
131
- }({});
132
- var kindLiteralAnnotations = {
133
- title: "Kind"
134
- };
135
- var TimerTriggerSchema = import_effect4.Schema.Struct({
136
- kind: import_effect4.Schema.Literal("timer").annotations(kindLiteralAnnotations),
137
- cron: import_effect4.Schema.String.annotations({
138
- title: "Cron",
139
- [import_effect4.SchemaAST.ExamplesAnnotationId]: [
140
- "0 0 * * *"
141
- ]
142
- })
143
- }).pipe(import_effect4.Schema.mutable);
144
- var EmailTriggerSchema = import_effect4.Schema.Struct({
145
- kind: import_effect4.Schema.Literal("email").annotations(kindLiteralAnnotations)
146
- }).pipe(import_effect4.Schema.mutable);
147
- var QueueTriggerSchema = import_effect4.Schema.Struct({
148
- kind: import_effect4.Schema.Literal("queue").annotations(kindLiteralAnnotations),
149
- queue: import_keys.DXN.Schema
150
- }).pipe(import_effect4.Schema.mutable);
151
- var WebhookTriggerSchema = import_effect4.Schema.Struct({
152
- kind: import_effect4.Schema.Literal("webhook").annotations(kindLiteralAnnotations),
153
- method: import_effect4.Schema.optional(import_effect4.Schema.String.annotations({
154
- title: "Method",
155
- [import_echo_schema3.OptionsAnnotationId]: [
156
- "GET",
157
- "POST"
158
- ]
159
- })),
160
- port: import_effect4.Schema.optional(import_effect4.Schema.Number.annotations({
161
- title: "Port"
162
- }))
163
- }).pipe(import_effect4.Schema.mutable);
164
- var QuerySchema = import_effect4.Schema.Struct({
165
- type: import_effect4.Schema.optional(import_effect4.Schema.String.annotations({
166
- title: "Type"
167
- })),
168
- props: import_effect4.Schema.optional(import_effect4.Schema.Record({
169
- key: import_effect4.Schema.String,
170
- value: import_effect4.Schema.Any
171
- }))
172
- }).annotations({
173
- title: "Query"
174
- });
175
- var SubscriptionTriggerSchema = import_effect4.Schema.Struct({
176
- kind: import_effect4.Schema.Literal("subscription").annotations(kindLiteralAnnotations),
177
- // TODO(burdon): Define query DSL (from ECHO). Reconcile with Table.Query.
178
- filter: QuerySchema,
179
- options: import_effect4.Schema.optional(import_effect4.Schema.Struct({
180
- // Watch changes to object (not just creation).
181
- deep: import_effect4.Schema.optional(import_effect4.Schema.Boolean.annotations({
182
- title: "Nested"
183
- })),
184
- // Debounce changes (delay in ms).
185
- delay: import_effect4.Schema.optional(import_effect4.Schema.Number.annotations({
186
- title: "Delay"
187
- }))
188
- }).annotations({
189
- title: "Options"
190
- }))
191
- }).pipe(import_effect4.Schema.mutable);
192
- var TriggerSchema = import_effect4.Schema.Union(TimerTriggerSchema, WebhookTriggerSchema, SubscriptionTriggerSchema, EmailTriggerSchema, QueueTriggerSchema).annotations({
193
- title: "Trigger"
194
- });
195
- var EmailTriggerOutput = import_effect4.Schema.mutable(import_effect4.Schema.Struct({
196
- from: import_effect4.Schema.String,
197
- to: import_effect4.Schema.String,
198
- subject: import_effect4.Schema.String,
199
- created: import_effect4.Schema.String,
200
- body: import_effect4.Schema.String
201
- }));
202
- var WebhookTriggerOutput = import_effect4.Schema.mutable(import_effect4.Schema.Struct({
203
- url: import_effect4.Schema.String,
204
- method: import_effect4.Schema.Literal("GET", "POST"),
205
- headers: import_effect4.Schema.Record({
206
- key: import_effect4.Schema.String,
207
- value: import_effect4.Schema.String
208
- }),
209
- bodyText: import_effect4.Schema.String
210
- }));
211
- var QueueTriggerOutput = import_effect4.Schema.mutable(import_effect4.Schema.Struct({
212
- queue: import_keys.DXN.Schema,
213
- item: import_effect4.Schema.Any,
214
- cursor: import_effect4.Schema.String
215
- }));
216
- var SubscriptionTriggerOutput = import_effect4.Schema.mutable(import_effect4.Schema.Struct({
217
- type: import_effect4.Schema.String,
218
- changedObjectId: import_effect4.Schema.String
219
- }));
220
- var TimerTriggerOutput = import_effect4.Schema.mutable(import_effect4.Schema.Struct({
221
- tick: import_effect4.Schema.Number
222
- }));
223
- var FunctionTriggerSchema = import_effect4.Schema.Struct({
224
- /**
225
- * Function or workflow to invoke.
226
- */
227
- // TODO(dmaretskyi): Can be a Ref(FunctionType) or Ref(ComputeGraphType).
228
- function: import_effect4.Schema.optional((0, import_echo_schema3.Ref)(import_echo_schema3.Expando).annotations({
229
- title: "Function"
230
- })),
231
- /**
232
- * Only used for workflowSchema.
233
- * Specifies the input node in the circuit.
234
- * @deprecated Remove and enforce a single input node in all compute graphSchema.
235
- */
236
- inputNodeId: import_effect4.Schema.optional(import_effect4.Schema.String.annotations({
237
- title: "Input Node ID"
238
- })),
239
- enabled: import_effect4.Schema.optional(import_effect4.Schema.Boolean.annotations({
240
- title: "Enabled"
241
- })),
242
- spec: import_effect4.Schema.optional(TriggerSchema),
243
- /**
244
- * Passed as the input data to the function.
245
- * Must match the function's input schema.
246
- *
247
- * @example
248
- * {
249
- * item: '{{$.trigger.event}}',
250
- * instructions: 'Summarize and perform entity-extraction'
251
- * mailbox: { '/': 'dxn:echo:AAA:ZZZ' }
252
- * }
253
- */
254
- input: import_effect4.Schema.optional(import_effect4.Schema.mutable(import_effect4.Schema.Record({
255
- key: import_effect4.Schema.String,
256
- value: import_effect4.Schema.Any
257
- })))
258
- });
259
- var FunctionTrigger = class extends (0, import_echo_schema3.TypedObject)({
260
- typename: "dxos.org/type/FunctionTrigger",
261
- version: "0.2.0"
262
- })(FunctionTriggerSchema.fields) {
263
- };
264
- var FunctionManifestSchema = import_effect4.Schema.Struct({
265
- functions: import_effect4.Schema.optional(import_effect4.Schema.mutable(import_effect4.Schema.Array((0, import_echo_schema3.RawObject)(FunctionType)))),
266
- triggers: import_effect4.Schema.optional(import_effect4.Schema.mutable(import_effect4.Schema.Array((0, import_echo_schema3.RawObject)(FunctionTrigger))))
267
- });
268
- var FUNCTION_TYPES = [
269
- FunctionType,
270
- FunctionTrigger
271
- ];
272
- var __dxlog_file = "/home/runner/work/dxos/dxos/packages/core/functions/src/trace.ts";
273
- var InvocationOutcome = /* @__PURE__ */ function(InvocationOutcome2) {
274
- InvocationOutcome2["SUCCESS"] = "success";
275
- InvocationOutcome2["FAILURE"] = "failure";
276
- InvocationOutcome2["PENDING"] = "pending";
277
- return InvocationOutcome2;
278
- }({});
279
- var InvocationTraceEventType = /* @__PURE__ */ function(InvocationTraceEventType2) {
280
- InvocationTraceEventType2["START"] = "start";
281
- InvocationTraceEventType2["END"] = "end";
282
- return InvocationTraceEventType2;
283
- }({});
284
- var TraceEventException = import_effect3.Schema.Struct({
285
- timestampMs: import_effect3.Schema.Number,
286
- message: import_effect3.Schema.String,
287
- name: import_effect3.Schema.String,
288
- stack: import_effect3.Schema.optional(import_effect3.Schema.String)
289
- });
290
- var InvocationTraceStartEvent = import_effect3.Schema.Struct({
291
- /**
292
- * Queue message id.
293
- */
294
- id: import_echo_schema2.ObjectId,
295
- type: import_effect3.Schema.Literal("start"),
296
- /**
297
- * Invocation id, the same for invocation start and end events.
298
- */
299
- invocationId: import_echo_schema2.ObjectId,
300
- /**
301
- * Event generation time.
302
- */
303
- timestampMs: import_effect3.Schema.Number,
304
- /**
305
- * Data passed to function / workflow as an argument.
306
- */
307
- // TODO(burdon): Input schema?
308
- input: import_effect3.Schema.Object,
309
- /**
310
- * Queue for function/workflow invocation events.
311
- */
312
- invocationTraceQueue: import_echo2.Type.Ref(import_echo_db.Queue),
313
- /**
314
- * DXN of the invoked function/workflow.
315
- */
316
- invocationTarget: import_echo2.Type.Ref(import_echo2.Type.Expando),
317
- /**
318
- * Present for automatic invocations.
319
- */
320
- trigger: import_effect3.Schema.optional(import_echo2.Type.Ref(FunctionTrigger))
321
- }).pipe(import_echo2.Type.Obj({
322
- typename: "dxos.org/type/InvocationTraceStart",
323
- version: "0.1.0"
324
- }));
325
- var InvocationTraceEndEvent = import_effect3.Schema.Struct({
326
- /**
327
- * Trace event id.
328
- */
329
- id: import_echo_schema2.ObjectId,
330
- type: import_effect3.Schema.Literal("end"),
331
- /**
332
- * Invocation id, will be the same for invocation start and end.
333
- */
334
- invocationId: import_echo_schema2.ObjectId,
335
- /**
336
- * Event generation time.
337
- */
338
- // TODO(burdon): Remove ms suffix.
339
- timestampMs: import_effect3.Schema.Number,
340
- outcome: import_effect3.Schema.Enums(InvocationOutcome),
341
- exception: import_effect3.Schema.optional(TraceEventException)
342
- }).pipe(import_echo2.Type.Obj({
343
- typename: "dxos.org/type/InvocationTraceEnd",
344
- version: "0.1.0"
345
- }));
346
- var TraceEventLog = import_effect3.Schema.Struct({
347
- timestampMs: import_effect3.Schema.Number,
348
- level: import_effect3.Schema.String,
349
- message: import_effect3.Schema.String,
350
- context: import_effect3.Schema.optional(import_effect3.Schema.Object)
351
- });
352
- var TraceEvent = import_effect3.Schema.Struct({
353
- id: import_echo_schema2.ObjectId,
354
- // TODO(burdon): Need enum/numeric result (not string).
355
- outcome: import_effect3.Schema.String,
356
- truncated: import_effect3.Schema.Boolean,
357
- /**
358
- * Time when the event was persisted.
359
- */
360
- ingestionTimestampMs: import_effect3.Schema.Number,
361
- logs: import_effect3.Schema.Array(TraceEventLog),
362
- exceptions: import_effect3.Schema.Array(TraceEventException)
363
- }).pipe(import_echo2.Type.Obj({
364
- typename: "dxos.org/type/TraceEvent",
365
- version: "0.1.0"
366
- }));
367
- var createInvocationSpans = (items) => {
368
- if (!items) {
369
- return [];
370
- }
371
- const eventsByInvocationId = /* @__PURE__ */ new Map();
372
- for (const event of items) {
373
- if (!("invocationId" in event)) {
374
- continue;
375
- }
376
- const invocationId = event.invocationId;
377
- const entry = eventsByInvocationId.get(invocationId) || {
378
- start: void 0,
379
- end: void 0
380
- };
381
- if (event.type === "start") {
382
- entry.start = event;
383
- } else if (event.type === "end") {
384
- entry.end = event;
385
- }
386
- eventsByInvocationId.set(invocationId, entry);
387
- }
388
- const now = Date.now();
389
- const result = [];
390
- for (const [invocationId, { start, end }] of eventsByInvocationId.entries()) {
391
- if (!start) {
392
- import_log.log.warn("found end event without matching start", {
393
- invocationId
394
- }, {
395
- F: __dxlog_file,
396
- L: 160,
397
- S: void 0,
398
- C: (f, a) => f(...a)
399
- });
400
- continue;
401
- }
402
- const isInProgress = end === void 0;
403
- result.push({
404
- id: invocationId,
405
- timestampMs: start.timestampMs,
406
- durationMs: isInProgress ? now - start.timestampMs : end.timestampMs - start.timestampMs,
407
- outcome: end?.outcome ?? "pending",
408
- exception: end?.exception,
409
- input: start.input,
410
- invocationTraceQueue: start.invocationTraceQueue,
411
- invocationTarget: start.invocationTarget,
412
- trigger: start.trigger
413
- });
414
- }
415
- return result;
416
- };
417
- var FUNCTIONS_META_KEY = "dxos.org/service/function";
418
- var FUNCTIONS_PRESET_META_KEY = "dxos.org/service/function-preset";
419
- var isSecure = (protocol) => {
420
- return protocol === "https:" || protocol === "wss:";
421
- };
422
- var getUserFunctionUrlInMetadata = (meta) => {
423
- return meta.keys.find((key) => key.source === FUNCTIONS_META_KEY)?.id;
424
- };
425
- var setUserFunctionUrlInMetadata = (meta, functionUrl) => {
426
- const key = meta.keys.find((key2) => key2.source === FUNCTIONS_META_KEY);
427
- if (key) {
428
- if (key.id !== functionUrl) {
429
- throw new Error("Metadata mismatch");
430
- }
431
- } else {
432
- meta.keys.push({
433
- source: FUNCTIONS_META_KEY,
434
- id: functionUrl
435
- });
436
- }
437
- };
438
- var makeFunctionUrl = (fn) => `/${fn.functionId}`;
439
- var getInvocationUrl = (functionUrl, edgeUrl, options = {}) => {
440
- const baseUrl = new URL("functions/", edgeUrl);
441
- const relativeUrl = functionUrl.replace(/^\//, "");
442
- const url = new URL(`./${relativeUrl}`, baseUrl.toString());
443
- options.spaceId && url.searchParams.set("spaceId", options.spaceId);
444
- options.subjectId && url.searchParams.set("subjectId", options.subjectId);
445
- url.protocol = isSecure(url.protocol) ? "https" : "http";
446
- return url.toString();
447
- };
448
- var FunctionExecutor = class {
449
- constructor(_services) {
450
- this._services = _services;
451
- }
452
- // TODO(dmaretskyi): Invocation context: queue, space, etc...
453
- async invoke(fnDef, input) {
454
- const assertInput = fnDef.inputSchema.pipe(import_effect5.Schema.asserts);
455
- assertInput(input);
456
- const context = {
457
- getService: this._services.getService.bind(this._services),
458
- getSpace: async (_spaceId) => {
459
- throw new Error("Not available. Use the database service instead.");
460
- },
461
- space: void 0,
462
- get ai() {
463
- throw new Error("Not available. Use the ai service instead.");
464
- }
465
- };
466
- const result = await fnDef.handler({
467
- context,
468
- data: input
469
- });
470
- const assertOutput = fnDef.outputSchema?.pipe(import_effect5.Schema.asserts);
471
- assertOutput(result);
472
- if (import_effect5.Effect.isEffect(result)) {
473
- return import_effect5.Effect.runPromise(result);
474
- }
475
- return result;
476
- }
477
- };
478
- // Annotate the CommonJS export names for ESM import in node:
479
- 0 && (module.exports = {
480
- AiService,
481
- ConfiguredCredentialsService,
482
- CredentialsService,
483
- DatabaseService,
484
- EmailTriggerOutput,
485
- EventLogger,
486
- FUNCTIONS_PRESET_META_KEY,
487
- FUNCTION_TYPES,
488
- FunctionCallService,
489
- FunctionExecutor,
490
- FunctionManifestSchema,
491
- FunctionTrigger,
492
- FunctionTriggerSchema,
493
- FunctionType,
494
- InvocationOutcome,
495
- InvocationTraceEndEvent,
496
- InvocationTraceEventType,
497
- InvocationTraceStartEvent,
498
- QueueService,
499
- QueueTriggerOutput,
500
- SERVICE_TAGS,
501
- ScriptType,
502
- ServiceContainer,
503
- SubscriptionTriggerOutput,
504
- TimerTriggerOutput,
505
- TraceEvent,
506
- TraceEventException,
507
- TraceEventLog,
508
- TracingService,
509
- TriggerKind,
510
- TriggerSchema,
511
- WebhookTriggerOutput,
512
- createDefectLogger,
513
- createEventLogger,
514
- createInvocationSpans,
515
- defineFunction,
516
- getInvocationUrl,
517
- getUserFunctionUrlInMetadata,
518
- logCustomEvent,
519
- makeFunctionUrl,
520
- setUserFunctionUrlInMetadata
521
- });
522
- //# sourceMappingURL=index.cjs.map