@dxos/functions 0.8.2-main.fbd8ed0 → 0.8.2-staging.4d6ad0f

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 (55) hide show
  1. package/dist/lib/browser/bundler/index.mjs.map +3 -3
  2. package/dist/lib/browser/index.mjs +175 -32
  3. package/dist/lib/browser/index.mjs.map +4 -4
  4. package/dist/lib/browser/meta.json +1 -1
  5. package/dist/lib/node/bundler/index.cjs.map +3 -3
  6. package/dist/lib/node/index.cjs +167 -30
  7. package/dist/lib/node/index.cjs.map +4 -4
  8. package/dist/lib/node/meta.json +1 -1
  9. package/dist/lib/node-esm/bundler/index.mjs.map +3 -3
  10. package/dist/lib/node-esm/index.mjs +175 -32
  11. package/dist/lib/node-esm/index.mjs.map +4 -4
  12. package/dist/lib/node-esm/meta.json +1 -1
  13. package/dist/types/src/bundler/bundler.d.ts.map +1 -1
  14. package/dist/types/src/executor/executor.d.ts +8 -0
  15. package/dist/types/src/executor/executor.d.ts.map +1 -0
  16. package/dist/types/src/executor/index.d.ts +2 -0
  17. package/dist/types/src/executor/index.d.ts.map +1 -0
  18. package/dist/types/src/handler.d.ts +7 -3
  19. package/dist/types/src/handler.d.ts.map +1 -1
  20. package/dist/types/src/index.d.ts +2 -0
  21. package/dist/types/src/index.d.ts.map +1 -1
  22. package/dist/types/src/schema.d.ts.map +1 -1
  23. package/dist/types/src/services/ai.d.ts +9 -0
  24. package/dist/types/src/services/ai.d.ts.map +1 -0
  25. package/dist/types/src/services/credentials.d.ts +30 -0
  26. package/dist/types/src/services/credentials.d.ts.map +1 -0
  27. package/dist/types/src/services/database.d.ts +9 -0
  28. package/dist/types/src/services/database.d.ts.map +1 -0
  29. package/dist/types/src/services/index.d.ts +7 -0
  30. package/dist/types/src/services/index.d.ts.map +1 -0
  31. package/dist/types/src/services/queues.d.ts +10 -0
  32. package/dist/types/src/services/queues.d.ts.map +1 -0
  33. package/dist/types/src/services/service-container.d.ts +25 -0
  34. package/dist/types/src/services/service-container.d.ts.map +1 -0
  35. package/dist/types/src/services/tracing.d.ts +15 -0
  36. package/dist/types/src/services/tracing.d.ts.map +1 -0
  37. package/dist/types/src/trace.d.ts +9 -8
  38. package/dist/types/src/trace.d.ts.map +1 -1
  39. package/dist/types/src/types.d.ts.map +1 -1
  40. package/package.json +20 -20
  41. package/src/bundler/bundler.ts +7 -1
  42. package/src/executor/executor.ts +47 -0
  43. package/src/executor/index.ts +5 -0
  44. package/src/handler.ts +8 -3
  45. package/src/index.ts +4 -0
  46. package/src/schema.ts +8 -9
  47. package/src/services/ai.ts +15 -0
  48. package/src/services/credentials.ts +55 -0
  49. package/src/services/database.ts +14 -0
  50. package/src/services/index.ts +10 -0
  51. package/src/services/queues.ts +16 -0
  52. package/src/services/service-container.ts +58 -0
  53. package/src/services/tracing.ts +27 -0
  54. package/src/trace.ts +4 -4
  55. package/src/types.ts +17 -16
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../src/bundler/bundler.ts"],
4
- "sourcesContent": ["//\n// Copyright 2023 DXOS.org\n//\n\nimport { type BuildOptions } from 'esbuild';\nimport { build, initialize, type BuildResult, type Plugin } from 'esbuild-wasm';\n\nimport { subtleCrypto } from '@dxos/crypto';\nimport { invariant } from '@dxos/invariant';\nimport { log } from '@dxos/log';\n\nexport type Import = {\n moduleUrl: string;\n defaultImport: boolean;\n namedImports: string[];\n};\n\nexport type BundleOptions = {\n /**\n * Path to the source file on the local file system.\n * If provided, the path will be used instead of the `source` code.\n */\n path?: string;\n\n /**\n * Source code to bundle.\n * Required if `path` is not provided.\n */\n source?: string;\n};\n\nexport type BundleResult = {\n timestamp: number;\n sourceHash?: Buffer;\n imports?: Import[];\n bundle?: string;\n error?: any;\n};\n\nexport type BundlerOptions = {\n platform: BuildOptions['platform'];\n sandboxedModules: string[];\n remoteModules: Record<string, string>;\n};\n\nlet initialized: Promise<void>;\nexport const initializeBundler = async (options: { wasmUrl: string }) => {\n await (initialized ??= initialize({\n wasmURL: options.wasmUrl,\n }));\n};\n\n/**\n * ESBuild bundler.\n */\nexport class Bundler {\n constructor(private readonly _options: BundlerOptions) {}\n\n async bundle({ path, source }: BundleOptions): Promise<BundleResult> {\n const { sandboxedModules: providedModules, ...options } = this._options;\n\n const createResult = async (result?: Partial<BundleResult>) => {\n return {\n timestamp: Date.now(),\n sourceHash: source ? Buffer.from(await subtleCrypto.digest('SHA-256', Buffer.from(source))) : undefined,\n ...result,\n };\n };\n\n if (this._options.platform === 'browser') {\n invariant(initialized, 'Compiler not initialized.');\n await initialized;\n }\n\n const imports = source ? analyzeSourceFileImports(source) : [];\n\n // https://esbuild.github.io/api/#build\n try {\n const result = await build({\n platform: options.platform,\n conditions: ['workerd', 'browser'],\n metafile: true,\n write: false,\n entryPoints: [path ?? 'memory:main.tsx'],\n bundle: true,\n format: 'esm',\n plugins: [\n {\n name: 'memory',\n setup: (build) => {\n build.onResolve({ filter: /^\\.\\/runtime\\.js$/ }, ({ path }) => {\n return { path, external: true };\n });\n\n build.onResolve({ filter: /^dxos:functions$/ }, ({ path }) => {\n return { path: './runtime.js', external: true };\n });\n\n build.onResolve({ filter: /^memory:/ }, ({ path }) => {\n return { path: path.split(':')[1], namespace: 'memory' };\n });\n\n build.onLoad({ filter: /.*/, namespace: 'memory' }, ({ path }) => {\n if (path === 'main.tsx') {\n return {\n contents: source,\n loader: 'tsx',\n };\n }\n });\n\n for (const module of providedModules) {\n build.onResolve({ filter: new RegExp(`^${module}$`) }, ({ path }) => {\n return { path, namespace: 'injected-module' };\n });\n }\n\n build.onLoad({ filter: /.*/, namespace: 'injected-module' }, ({ path }) => {\n const namedImports = imports.find((entry) => entry.moduleIdentifier === path)?.namedImports ?? [];\n return {\n contents: `\n const { ${namedImports.join(',')} } = window.__DXOS_SANDBOX_MODULES__[${JSON.stringify(path)}];\n export { ${namedImports.join(',')} };\n export default window.__DXOS_SANDBOX_MODULES__[${JSON.stringify(path)}].default;\n `,\n loader: 'tsx',\n };\n });\n },\n },\n httpPlugin,\n ],\n });\n\n log('compile complete', result.metafile);\n\n return await createResult({\n imports: this.analyzeImports(result),\n bundle: result.outputFiles![0].text,\n });\n } catch (err) {\n return await createResult({ error: err });\n }\n }\n\n // TODO(dmaretskyi): In the future we can replace the compiler with SWC with plugins running in WASM.\n analyzeImports(result: BuildResult): Import[] {\n invariant(result.outputFiles);\n\n // TODO(dmaretskyi): Support import aliases and wildcard imports.\n const parsedImports = allMatches(IMPORT_REGEX, result.outputFiles[0].text);\n return Object.values(result.metafile!.outputs)[0].imports.map((entry): Import => {\n const namedImports: string[] = [];\n\n const parsedImport = parsedImports.find((capture) => capture?.[4] === entry.path);\n if (parsedImport?.[2]) {\n NAMED_IMPORTS_REGEX.lastIndex = 0;\n const namedImportsMatch = NAMED_IMPORTS_REGEX.exec(parsedImport[2]);\n if (namedImportsMatch) {\n namedImportsMatch[1].split(',').forEach((importName) => {\n namedImports.push(importName.trim());\n });\n }\n }\n\n return {\n moduleUrl: entry.path,\n defaultImport: !!parsedImport?.[1],\n namedImports,\n };\n });\n }\n\n analyzeSourceFileImports(code: string) {\n // TODO(dmaretskyi): Support import aliases and wildcard imports.\n const parsedImports = allMatches(IMPORT_REGEX, code);\n return parsedImports.map((capture) => {\n return {\n defaultImportName: capture[1],\n namedImports: capture[2]?.split(',').map((importName) => importName.trim()),\n wildcardImportName: capture[3],\n moduleIdentifier: capture[4],\n quotes: capture[5],\n };\n });\n }\n}\n\n// https://regex101.com/r/FEN5ks/1\n// https://stackoverflow.com/a/73265022\n// $1 = default import name (can be non-existent)\n// $2 = destructured exports (can be non-existent)\n// $3 = wildcard import name (can be non-existent)\n// $4 = module identifier\n// $5 = quotes used (either ' or \")\nconst IMPORT_REGEX =\n /import(?:(?:(?:[ \\n\\t]+([^ *\\n\\t{},]+)[ \\n\\t]*(?:,|[ \\n\\t]+))?([ \\n\\t]*{(?:[ \\n\\t]*[^ \\n\\t\"'{}]+[ \\n\\t]*,?)+})?[ \\n\\t]*)|[ \\n\\t]*\\*[ \\n\\t]*as[ \\n\\t]+([^ \\n\\t{}]+)[ \\n\\t]+)from[ \\n\\t]*(?:['\"])([^'\"\\n]+)(['\"])/gm;\n\nconst NAMED_IMPORTS_REGEX = /[ \\n\\t]*{((?:[ \\n\\t]*[^ \\n\\t\"'{}]+[ \\n\\t]*,?)+)}[ \\n\\t]*/gm;\n\nconst allMatches = (regex: RegExp, str: string) => {\n regex.lastIndex = 0;\n\n let match;\n const matches = [];\n while ((match = regex.exec(str))) {\n matches.push(match);\n }\n\n return matches;\n};\n\ntype ParsedImport = {\n defaultImportName?: string;\n namedImports: string[];\n wildcardImportName?: string;\n moduleIdentifier: string;\n quotes: string;\n};\n\nconst analyzeSourceFileImports = (code: string): ParsedImport[] => {\n // TODO(dmaretskyi): Support import aliases and wildcard imports.\n const parsedImports = allMatches(IMPORT_REGEX, code);\n return parsedImports.map((capture) => {\n return {\n defaultImportName: capture[1],\n namedImports: capture[2]\n ?.trim()\n .slice(1, -1)\n .split(',')\n .map((importName) => importName.trim()),\n wildcardImportName: capture[3],\n moduleIdentifier: capture[4],\n quotes: capture[5],\n };\n });\n};\n\nconst httpPlugin: Plugin = {\n name: 'http',\n setup: (build) => {\n // Intercept import paths starting with \"http:\" and \"https:\" so esbuild doesn't attempt to map them to a file system location.\n // Tag them with the \"http-url\" namespace to associate them with this plugin.\n build.onResolve({ filter: /^https?:\\/\\// }, (args) => ({\n path: args.path,\n namespace: 'http-url',\n }));\n\n // We also want to intercept all import paths inside downloaded files and resolve them against the original URL.\n // All of these files will be in the \"http-url\" namespace.\n // Make sure to keep the newly resolved URL in the \"http-url\" namespace so imports inside it will also be resolved as URLs recursively.\n build.onResolve({ filter: /.*/, namespace: 'http-url' }, (args) => ({\n path: new URL(args.path, args.importer).toString(),\n namespace: 'http-url',\n }));\n\n // When a URL is loaded, we want to actually download the content from the internet.\n // This has just enough logic to be able to handle the example import from unpkg.com but in reality this would probably need to be more complex.\n build.onLoad({ filter: /.*/, namespace: 'http-url' }, async (args) => {\n const response = await fetch(args.path);\n return { contents: await response.text(), loader: 'jsx' };\n });\n },\n};\n"],
5
- "mappings": ";AAKA,SAASA,OAAOC,kBAAiD;AAEjE,SAASC,oBAAoB;AAC7B,SAASC,iBAAiB;AAC1B,SAASC,WAAW;;AAoCpB,IAAIC;AACG,IAAMC,oBAAoB,OAAOC,YAAAA;AACtC,SAAOF,gBAAgBJ,WAAW;IAChCO,SAASD,QAAQE;EACnB,CAAA;AACF;AAKO,IAAMC,UAAN,MAAMA;EACXC,YAA6BC,UAA0B;SAA1BA,WAAAA;EAA2B;EAExD,MAAMC,OAAO,EAAEC,MAAMC,OAAM,GAA0C;AACnE,UAAM,EAAEC,kBAAkBC,iBAAiB,GAAGV,QAAAA,IAAY,KAAKK;AAE/D,UAAMM,eAAe,OAAOC,WAAAA;AAC1B,aAAO;QACLC,WAAWC,KAAKC,IAAG;QACnBC,YAAYR,SAASS,OAAOC,KAAK,MAAMvB,aAAawB,OAAO,WAAWF,OAAOC,KAAKV,MAAAA,CAAAA,CAAAA,IAAYY;QAC9F,GAAGR;MACL;IACF;AAEA,QAAI,KAAKP,SAASgB,aAAa,WAAW;AACxCzB,gBAAUE,aAAa,6BAAA;;;;;;;;;AACvB,YAAMA;IACR;AAEA,UAAMwB,UAAUd,SAASe,yBAAyBf,MAAAA,IAAU,CAAA;AAG5D,QAAI;AACF,YAAMI,SAAS,MAAMnB,MAAM;QACzB4B,UAAUrB,QAAQqB;QAClBG,YAAY;UAAC;UAAW;;QACxBC,UAAU;QACVC,OAAO;QACPC,aAAa;UAACpB,QAAQ;;QACtBD,QAAQ;QACRsB,QAAQ;QACRC,SAAS;UACP;YACEC,MAAM;YACNC,OAAO,CAACtC,WAAAA;AACNA,cAAAA,OAAMuC,UAAU;gBAAEC,QAAQ;cAAoB,GAAG,CAAC,EAAE1B,MAAAA,MAAI,MAAE;AACxD,uBAAO;kBAAEA,MAAAA;kBAAM2B,UAAU;g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O+C,SAAAA;AAC3D,YAAMI,WAAW,MAAMC,MAAML,KAAK5E,IAAI;AACtC,aAAO;QAAE+B,UAAU,MAAMiD,SAASnC,KAAI;QAAIb,QAAQ;MAAM;IAC1D,CAAA;EACF;AACF;",
6
- "names": ["build", "initialize", "subtleCrypto", "invariant", "log", "initialized", "initializeBundler", "options", "wasmURL", "wasmUrl", "Bundler", "constructor", "_options", "bundle", "path", "source", "sandboxedModules", "providedModules", "createResult", "result", "timestamp", "Date", "now", "sourceHash", "Buffer", "from", "digest", "undefined", "platform", "imports", "analyzeSourceFileImports", "conditions", "metafile", "write", "entryPoints", "format", "plugins", "name", "setup", "onResolve", "filter", "external", "split", "namespace", "onLoad", "contents", "loader", "module", "RegExp", "namedImports", "find", "entry", "moduleIdentifier", "join", "JSON", "stringify", "httpPlugin", "analyzeImports", "outputFiles", "text", "err", "error", "parsedImports", "allMatches", "IMPORT_REGEX", "Object", "values", "outputs", "map", "parsedImport", "capture", "NAMED_IMPORTS_REGEX", "lastIndex", "namedImportsMatch", "exec", "forEach", "importName", "push", "trim", "moduleUrl", "defaultImport", "code", "defaultImportName", "wildcardImportName", "quotes", "regex", "str", "match", "matches", "slice", "args", "URL", "importer", "toString", "response", "fetch"]
4
+ "sourcesContent": ["//\n// Copyright 2023 DXOS.org\n//\n\nimport { type BuildOptions } from 'esbuild';\nimport { build, initialize, type BuildResult, type Plugin } from 'esbuild-wasm';\n\nimport { subtleCrypto } from '@dxos/crypto';\nimport { invariant } from '@dxos/invariant';\nimport { log } from '@dxos/log';\n\nexport type Import = {\n moduleUrl: string;\n defaultImport: boolean;\n namedImports: string[];\n};\n\nexport type BundleOptions = {\n /**\n * Path to the source file on the local file system.\n * If provided, the path will be used instead of the `source` code.\n */\n path?: string;\n\n /**\n * Source code to bundle.\n * Required if `path` is not provided.\n */\n source?: string;\n};\n\nexport type BundleResult = {\n timestamp: number;\n sourceHash?: Buffer;\n imports?: Import[];\n bundle?: string;\n error?: any;\n};\n\nexport type BundlerOptions = {\n platform: BuildOptions['platform'];\n sandboxedModules: string[];\n remoteModules: Record<string, string>;\n};\n\nlet initialized: Promise<void>;\nexport const initializeBundler = async (options: { wasmUrl: string }) => {\n await (initialized ??= initialize({\n wasmURL: options.wasmUrl,\n }));\n};\n\n/**\n * ESBuild bundler.\n */\nexport class Bundler {\n constructor(private readonly _options: BundlerOptions) {}\n\n async bundle({ path, source }: BundleOptions): Promise<BundleResult> {\n const { sandboxedModules: providedModules, ...options } = this._options;\n\n const createResult = async (result?: Partial<BundleResult>) => {\n return {\n timestamp: Date.now(),\n sourceHash: source ? Buffer.from(await subtleCrypto.digest('SHA-256', Buffer.from(source))) : undefined,\n ...result,\n };\n };\n\n if (this._options.platform === 'browser') {\n invariant(initialized, 'Compiler not initialized.');\n await initialized;\n }\n\n const imports = source ? analyzeSourceFileImports(source) : [];\n\n // https://esbuild.github.io/api/#build\n try {\n const result = await build({\n platform: options.platform,\n conditions: ['workerd', 'browser'],\n metafile: true,\n write: false,\n entryPoints: [path ?? 'memory:main.tsx'],\n bundle: true,\n format: 'esm',\n plugins: [\n {\n name: 'memory',\n setup: (build) => {\n build.onResolve({ filter: /^\\.\\/runtime\\.js$/ }, ({ path }) => {\n return { path, external: true };\n });\n\n build.onResolve({ filter: /^dxos:functions$/ }, ({ path }) => {\n return { path: './runtime.js', external: true };\n });\n\n build.onResolve({ filter: /^memory:/ }, ({ path }) => {\n return { path: path.split(':')[1], namespace: 'memory' };\n });\n\n build.onLoad({ filter: /.*/, namespace: 'memory' }, ({ path }) => {\n if (path === 'main.tsx') {\n return {\n contents: source,\n loader: 'tsx',\n };\n }\n });\n\n for (const module of providedModules) {\n build.onResolve({ filter: new RegExp(`^${module}$`) }, ({ path }) => {\n return { path, namespace: 'injected-module' };\n });\n }\n\n build.onLoad({ filter: /.*/, namespace: 'injected-module' }, ({ path }) => {\n const namedImports = imports.find((entry) => entry.moduleIdentifier === path)?.namedImports ?? [];\n return {\n contents: `\n const { ${namedImports.join(',')} } = window.__DXOS_SANDBOX_MODULES__[${JSON.stringify(path)}];\n export { ${namedImports.join(',')} };\n export default window.__DXOS_SANDBOX_MODULES__[${JSON.stringify(path)}].default;\n `,\n loader: 'tsx',\n };\n });\n },\n },\n httpPlugin,\n ],\n });\n\n log('compile complete', result.metafile);\n\n return await createResult({\n imports: this.analyzeImports(result),\n bundle: result.outputFiles![0].text,\n });\n } catch (err) {\n return await createResult({ error: err });\n }\n }\n\n // TODO(dmaretskyi): In the future we can replace the compiler with SWC with plugins running in WASM.\n analyzeImports(result: BuildResult): Import[] {\n invariant(result.outputFiles);\n\n // TODO(dmaretskyi): Support import aliases and wildcard imports.\n const parsedImports = allMatches(IMPORT_REGEX, result.outputFiles[0].text);\n return Object.values(result.metafile!.outputs)[0].imports.map((entry): Import => {\n const namedImports: string[] = [];\n\n const parsedImport = parsedImports.find((capture) => capture?.[4] === entry.path);\n if (parsedImport?.[2]) {\n NAMED_IMPORTS_REGEX.lastIndex = 0;\n const namedImportsMatch = NAMED_IMPORTS_REGEX.exec(parsedImport[2]);\n if (namedImportsMatch) {\n namedImportsMatch[1].split(',').forEach((importName) => {\n namedImports.push(importName.trim());\n });\n }\n }\n\n return {\n moduleUrl: entry.path,\n defaultImport: !!parsedImport?.[1],\n namedImports,\n };\n });\n }\n\n analyzeSourceFileImports(code: string): {\n defaultImportName: string;\n namedImports: string[];\n wildcardImportName: string;\n moduleIdentifier: string;\n quotes: string;\n }[] {\n // TODO(dmaretskyi): Support import aliases and wildcard imports.\n const parsedImports = allMatches(IMPORT_REGEX, code);\n return parsedImports.map((capture) => {\n return {\n defaultImportName: capture[1],\n namedImports: capture[2]?.split(',').map((importName) => importName.trim()),\n wildcardImportName: capture[3],\n moduleIdentifier: capture[4],\n quotes: capture[5],\n };\n });\n }\n}\n\n// https://regex101.com/r/FEN5ks/1\n// https://stackoverflow.com/a/73265022\n// $1 = default import name (can be non-existent)\n// $2 = destructured exports (can be non-existent)\n// $3 = wildcard import name (can be non-existent)\n// $4 = module identifier\n// $5 = quotes used (either ' or \")\nconst IMPORT_REGEX =\n /import(?:(?:(?:[ \\n\\t]+([^ *\\n\\t{},]+)[ \\n\\t]*(?:,|[ \\n\\t]+))?([ \\n\\t]*{(?:[ \\n\\t]*[^ \\n\\t\"'{}]+[ \\n\\t]*,?)+})?[ \\n\\t]*)|[ \\n\\t]*\\*[ \\n\\t]*as[ \\n\\t]+([^ \\n\\t{}]+)[ \\n\\t]+)from[ \\n\\t]*(?:['\"])([^'\"\\n]+)(['\"])/gm;\n\nconst NAMED_IMPORTS_REGEX = /[ \\n\\t]*{((?:[ \\n\\t]*[^ \\n\\t\"'{}]+[ \\n\\t]*,?)+)}[ \\n\\t]*/gm;\n\nconst allMatches = (regex: RegExp, str: string) => {\n regex.lastIndex = 0;\n\n let match;\n const matches = [];\n while ((match = regex.exec(str))) {\n matches.push(match);\n }\n\n return matches;\n};\n\ntype ParsedImport = {\n defaultImportName?: string;\n namedImports: string[];\n wildcardImportName?: string;\n moduleIdentifier: string;\n quotes: string;\n};\n\nconst analyzeSourceFileImports = (code: string): ParsedImport[] => {\n // TODO(dmaretskyi): Support import aliases and wildcard imports.\n const parsedImports = allMatches(IMPORT_REGEX, code);\n return parsedImports.map((capture) => {\n return {\n defaultImportName: capture[1],\n namedImports: capture[2]\n ?.trim()\n .slice(1, -1)\n .split(',')\n .map((importName) => importName.trim()),\n wildcardImportName: capture[3],\n moduleIdentifier: capture[4],\n quotes: capture[5],\n };\n });\n};\n\nconst httpPlugin: Plugin = {\n name: 'http',\n setup: (build) => {\n // Intercept import paths starting with \"http:\" and \"https:\" so esbuild doesn't attempt to map them to a file system location.\n // Tag them with the \"http-url\" namespace to associate them with this plugin.\n build.onResolve({ filter: /^https?:\\/\\// }, (args) => ({\n path: args.path,\n namespace: 'http-url',\n }));\n\n // We also want to intercept all import paths inside downloaded files and resolve them against the original URL.\n // All of these files will be in the \"http-url\" namespace.\n // Make sure to keep the newly resolved URL in the \"http-url\" namespace so imports inside it will also be resolved as URLs recursively.\n build.onResolve({ filter: /.*/, namespace: 'http-url' }, (args) => ({\n path: new URL(args.path, args.importer).toString(),\n namespace: 'http-url',\n }));\n\n // When a URL is loaded, we want to actually download the content from the internet.\n // This has just enough logic to be able to handle the example import from unpkg.com but in reality this would probably need to be more complex.\n build.onLoad({ filter: /.*/, namespace: 'http-url' }, async (args) => {\n const response = await fetch(args.path);\n return { contents: await response.text(), loader: 'jsx' };\n });\n },\n};\n"],
5
+ "mappings": ";AAKA,SAASA,OAAOC,kBAAiD;AAEjE,SAASC,oBAAoB;AAC7B,SAASC,iBAAiB;AAC1B,SAASC,WAAW;;AAoCpB,IAAIC;AACG,IAAMC,oBAAoB,OAAOC,YAAAA;AACtC,SAAOF,gBAAgBJ,WAAW;IAChCO,SAASD,QAAQE;EACnB,CAAA;AACF;AAKO,IAAMC,UAAN,MAAMA;EACX,YAA6BC,UAA0B;SAA1BA,WAAAA;EAA2B;EAExD,MAAMC,OAAO,EAAEC,MAAMC,OAAM,GAA0C;AACnE,UAAM,EAAEC,kBAAkBC,iBAAiB,GAAGT,QAAAA,IAAY,KAAKI;AAE/D,UAAMM,eAAe,OAAOC,WAAAA;AAC1B,aAAO;QACLC,WAAWC,KAAKC,IAAG;QACnBC,YAAYR,SAASS,OAAOC,KAAK,MAAMtB,aAAauB,OAAO,WAAWF,OAAOC,KAAKV,MAAAA,CAAAA,CAAAA,IAAYY;QAC9F,GAAGR;MACL;IACF;AAEA,QAAI,KAAKP,SAASgB,aAAa,WAAW;AACxCxB,gBAAUE,aAAa,6BAAA;;;;;;;;;AACvB,YAAMA;IACR;AAEA,UAAMuB,UAAUd,SAASe,yBAAyBf,MAAAA,IAAU,CAAA;AAG5D,QAAI;AACF,YAAMI,SAAS,MAAMlB,MAAM;QACzB2B,UAAUpB,QAAQoB;QAClBG,YAAY;UAAC;UAAW;;QACxBC,UAAU;QACVC,OAAO;QACPC,aAAa;UAACpB,QAAQ;;QACtBD,QAAQ;QACRsB,QAAQ;QACRC,S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+C,UAAU;MAClE5E,MAAM,IAAI6E,IAAID,KAAK5E,MAAM4E,KAAKE,QAAQ,EAAEC,SAAQ;MAChDlD,WAAW;IACb,EAAA;AAIA1C,IAAAA,OAAM2C,OAAO;MAAEJ,QAAQ;MAAMG,WAAW;IAAW,GAAG,OAAO+C,SAAAA;AAC3D,YAAMI,WAAW,MAAMC,MAAML,KAAK5E,IAAI;AACtC,aAAO;QAAE+B,UAAU,MAAMiD,SAASnC,KAAI;QAAIb,QAAQ;MAAM;IAC1D,CAAA;EACF;AACF;",
6
+ "names": ["build", "initialize", "subtleCrypto", "invariant", "log", "initialized", "initializeBundler", "options", "wasmURL", "wasmUrl", "Bundler", "_options", "bundle", "path", "source", "sandboxedModules", "providedModules", "createResult", "result", "timestamp", "Date", "now", "sourceHash", "Buffer", "from", "digest", "undefined", "platform", "imports", "analyzeSourceFileImports", "conditions", "metafile", "write", "entryPoints", "format", "plugins", "name", "setup", "onResolve", "filter", "external", "split", "namespace", "onLoad", "contents", "loader", "module", "RegExp", "namedImports", "find", "entry", "moduleIdentifier", "join", "JSON", "stringify", "httpPlugin", "analyzeImports", "outputFiles", "text", "err", "error", "parsedImports", "allMatches", "IMPORT_REGEX", "Object", "values", "outputs", "map", "parsedImport", "capture", "NAMED_IMPORTS_REGEX", "lastIndex", "namedImportsMatch", "exec", "forEach", "importName", "push", "trim", "moduleUrl", "defaultImport", "code", "defaultImportName", "wildcardImportName", "quotes", "regex", "str", "match", "matches", "slice", "args", "URL", "importer", "toString", "response", "fetch"]
7
7
  }
@@ -17,7 +17,7 @@ var defineFunction = (params) => {
17
17
 
18
18
  // packages/core/functions/src/schema.ts
19
19
  import { Schema as Schema2 } from "effect";
20
- import { EchoObject, JsonSchemaType, LabelAnnotationId, Ref, TypedObject } from "@dxos/echo-schema";
20
+ import { EchoObject, JsonSchemaType, LabelAnnotation, Ref, TypedObject } from "@dxos/echo-schema";
21
21
  import { DataType } from "@dxos/schema";
22
22
  var ScriptType = Schema2.Struct({
23
23
  name: Schema2.optional(Schema2.String),
@@ -26,12 +26,12 @@ var ScriptType = Schema2.Struct({
26
26
  // Whether source has changed since last deploy.
27
27
  changed: Schema2.optional(Schema2.Boolean),
28
28
  source: Ref(DataType.Text)
29
- }).annotations({
30
- [LabelAnnotationId]: "name"
31
29
  }).pipe(EchoObject({
32
30
  typename: "dxos.org/type/Script",
33
31
  version: "0.1.0"
34
- }));
32
+ }), LabelAnnotation.set([
33
+ "name"
34
+ ]));
35
35
  var FunctionType = class extends TypedObject({
36
36
  typename: "dxos.org/type/Function",
37
37
  version: "0.1.0"
@@ -52,27 +52,29 @@ var FunctionType = class extends TypedObject({
52
52
 
53
53
  // packages/core/functions/src/trace.ts
54
54
  import { Schema as Schema4 } from "effect";
55
+ import { Queue } from "@dxos/echo-db";
55
56
  import { EchoObject as EchoObject2, Expando as Expando2, ObjectId, Ref as Ref3 } from "@dxos/echo-schema";
56
57
  import { log } from "@dxos/log";
57
58
 
58
59
  // packages/core/functions/src/types.ts
59
60
  import { Schema as Schema3, SchemaAST } from "effect";
60
- import { Expando, OptionsAnnotationId, TypedObject as TypedObject2, DXN, Ref as Ref2, RawObject } from "@dxos/echo-schema";
61
- var TriggerKind;
62
- (function(TriggerKind2) {
61
+ import { Expando, OptionsAnnotationId, TypedObject as TypedObject2, Ref as Ref2, RawObject } from "@dxos/echo-schema";
62
+ import { DXN } from "@dxos/keys";
63
+ var TriggerKind = /* @__PURE__ */ function(TriggerKind2) {
63
64
  TriggerKind2["Timer"] = "timer";
64
65
  TriggerKind2["Webhook"] = "webhook";
65
66
  TriggerKind2["Subscription"] = "subscription";
66
67
  TriggerKind2["Email"] = "email";
67
68
  TriggerKind2["Queue"] = "queue";
68
- })(TriggerKind || (TriggerKind = {}));
69
+ return TriggerKind2;
70
+ }({});
69
71
  var kindLiteralAnnotations = {
70
- [SchemaAST.TitleAnnotationId]: "Kind"
72
+ title: "Kind"
71
73
  };
72
74
  var TimerTriggerSchema = Schema3.Struct({
73
75
  kind: Schema3.Literal("timer").annotations(kindLiteralAnnotations),
74
76
  cron: Schema3.String.annotations({
75
- [SchemaAST.TitleAnnotationId]: "Cron",
77
+ title: "Cron",
76
78
  [SchemaAST.ExamplesAnnotationId]: [
77
79
  "0 0 * * *"
78
80
  ]
@@ -83,31 +85,31 @@ var EmailTriggerSchema = Schema3.Struct({
83
85
  }).pipe(Schema3.mutable);
84
86
  var QueueTriggerSchema = Schema3.Struct({
85
87
  kind: Schema3.Literal("queue").annotations(kindLiteralAnnotations),
86
- queue: DXN
88
+ queue: DXN.Schema
87
89
  }).pipe(Schema3.mutable);
88
90
  var WebhookTriggerSchema = Schema3.Struct({
89
91
  kind: Schema3.Literal("webhook").annotations(kindLiteralAnnotations),
90
92
  method: Schema3.optional(Schema3.String.annotations({
91
- [SchemaAST.TitleAnnotationId]: "Method",
93
+ title: "Method",
92
94
  [OptionsAnnotationId]: [
93
95
  "GET",
94
96
  "POST"
95
97
  ]
96
98
  })),
97
99
  port: Schema3.optional(Schema3.Number.annotations({
98
- [SchemaAST.TitleAnnotationId]: "Port"
100
+ title: "Port"
99
101
  }))
100
102
  }).pipe(Schema3.mutable);
101
103
  var QuerySchema = Schema3.Struct({
102
104
  type: Schema3.optional(Schema3.String.annotations({
103
- [SchemaAST.TitleAnnotationId]: "Type"
105
+ title: "Type"
104
106
  })),
105
107
  props: Schema3.optional(Schema3.Record({
106
108
  key: Schema3.String,
107
109
  value: Schema3.Any
108
110
  }))
109
111
  }).annotations({
110
- [SchemaAST.TitleAnnotationId]: "Query"
112
+ title: "Query"
111
113
  });
112
114
  var SubscriptionTriggerSchema = Schema3.Struct({
113
115
  kind: Schema3.Literal("subscription").annotations(kindLiteralAnnotations),
@@ -116,18 +118,18 @@ var SubscriptionTriggerSchema = Schema3.Struct({
116
118
  options: Schema3.optional(Schema3.Struct({
117
119
  // Watch changes to object (not just creation).
118
120
  deep: Schema3.optional(Schema3.Boolean.annotations({
119
- [SchemaAST.TitleAnnotationId]: "Nested"
121
+ title: "Nested"
120
122
  })),
121
123
  // Debounce changes (delay in ms).
122
124
  delay: Schema3.optional(Schema3.Number.annotations({
123
- [SchemaAST.TitleAnnotationId]: "Delay"
125
+ title: "Delay"
124
126
  }))
125
127
  }).annotations({
126
- [SchemaAST.TitleAnnotationId]: "Options"
128
+ title: "Options"
127
129
  }))
128
130
  }).pipe(Schema3.mutable);
129
131
  var TriggerSchema = Schema3.Union(TimerTriggerSchema, WebhookTriggerSchema, SubscriptionTriggerSchema, EmailTriggerSchema, QueueTriggerSchema).annotations({
130
- [SchemaAST.TitleAnnotationId]: "Trigger"
132
+ title: "Trigger"
131
133
  });
132
134
  var EmailTriggerOutput = Schema3.mutable(Schema3.Struct({
133
135
  from: Schema3.String,
@@ -146,7 +148,7 @@ var WebhookTriggerOutput = Schema3.mutable(Schema3.Struct({
146
148
  bodyText: Schema3.String
147
149
  }));
148
150
  var QueueTriggerOutput = Schema3.mutable(Schema3.Struct({
149
- queue: DXN,
151
+ queue: DXN.Schema,
150
152
  item: Schema3.Any,
151
153
  cursor: Schema3.String
152
154
  }));
@@ -163,7 +165,7 @@ var FunctionTriggerSchema = Schema3.Struct({
163
165
  */
164
166
  // TODO(dmaretskyi): Can be a Ref(FunctionType) or Ref(ComputeGraphType).
165
167
  function: Schema3.optional(Ref2(Expando).annotations({
166
- [SchemaAST.TitleAnnotationId]: "Function"
168
+ title: "Function"
167
169
  })),
168
170
  /**
169
171
  * Only used for workflowSchema.
@@ -171,10 +173,10 @@ var FunctionTriggerSchema = Schema3.Struct({
171
173
  * @deprecated Remove and enforce a single input node in all compute graphSchema.
172
174
  */
173
175
  inputNodeId: Schema3.optional(Schema3.String.annotations({
174
- [SchemaAST.TitleAnnotationId]: "Input Node ID"
176
+ title: "Input Node ID"
175
177
  })),
176
178
  enabled: Schema3.optional(Schema3.Boolean.annotations({
177
- [SchemaAST.TitleAnnotationId]: "Enabled"
179
+ title: "Enabled"
178
180
  })),
179
181
  spec: Schema3.optional(TriggerSchema),
180
182
  /**
@@ -209,17 +211,17 @@ var FUNCTION_TYPES = [
209
211
 
210
212
  // packages/core/functions/src/trace.ts
211
213
  var __dxlog_file = "/home/runner/work/dxos/dxos/packages/core/functions/src/trace.ts";
212
- var InvocationOutcome;
213
- (function(InvocationOutcome2) {
214
+ var InvocationOutcome = /* @__PURE__ */ function(InvocationOutcome2) {
214
215
  InvocationOutcome2["SUCCESS"] = "success";
215
216
  InvocationOutcome2["FAILURE"] = "failure";
216
217
  InvocationOutcome2["PENDING"] = "pending";
217
- })(InvocationOutcome || (InvocationOutcome = {}));
218
- var InvocationTraceEventType;
219
- (function(InvocationTraceEventType2) {
218
+ return InvocationOutcome2;
219
+ }({});
220
+ var InvocationTraceEventType = /* @__PURE__ */ function(InvocationTraceEventType2) {
220
221
  InvocationTraceEventType2["START"] = "start";
221
222
  InvocationTraceEventType2["END"] = "end";
222
- })(InvocationTraceEventType || (InvocationTraceEventType = {}));
223
+ return InvocationTraceEventType2;
224
+ }({});
223
225
  var TraceEventException = Schema4.Struct({
224
226
  timestampMs: Schema4.Number,
225
227
  message: Schema4.String,
@@ -246,10 +248,9 @@ var InvocationTraceStartEvent = Schema4.Struct({
246
248
  // TODO(burdon): Input schema?
247
249
  input: Schema4.Object,
248
250
  /**
249
- * Queue DXN for function/workflow invocation events.
251
+ * Queue for function/workflow invocation events.
250
252
  */
251
- // TODO(burdon): Need reference type for queue. vs. string?
252
- invocationTraceQueue: Ref3(Expando2),
253
+ invocationTraceQueue: Ref3(Queue),
253
254
  /**
254
255
  * DXN of the invoked function/workflow.
255
256
  */
@@ -387,10 +388,149 @@ var getInvocationUrl = (functionUrl, edgeUrl, options = {}) => {
387
388
  url.protocol = isSecure(url.protocol) ? "https" : "http";
388
389
  return url.toString();
389
390
  };
391
+
392
+ // packages/core/functions/src/services/ai.ts
393
+ import { Context } from "effect";
394
+ var AiService = class extends Context.Tag("AiService")() {
395
+ };
396
+
397
+ // packages/core/functions/src/services/database.ts
398
+ import { Context as Context2 } from "effect";
399
+ var DatabaseService = class extends Context2.Tag("DatabaseService")() {
400
+ };
401
+
402
+ // packages/core/functions/src/services/queues.ts
403
+ import { Context as Context3 } from "effect";
404
+ var QueuesService = class extends Context3.Tag("QueuesService")() {
405
+ };
406
+
407
+ // packages/core/functions/src/services/credentials.ts
408
+ import { Context as Context4 } from "effect";
409
+ var CredentialsService = class extends Context4.Tag("CredentialsService")() {
410
+ };
411
+ var ConfiguredCredentialsService = class {
412
+ constructor(credentials = []) {
413
+ this.credentials = credentials;
414
+ }
415
+ addCredentials(credentials) {
416
+ this.credentials.push(...credentials);
417
+ return this;
418
+ }
419
+ async queryCredentials(query) {
420
+ return this.credentials.filter((credential) => credential.service === query.service);
421
+ }
422
+ async getCredential(query) {
423
+ const credential = this.credentials.find((credential2) => credential2.service === query.service);
424
+ if (!credential) {
425
+ throw new Error(`Credential not found for service: ${query.service}`);
426
+ }
427
+ return credential;
428
+ }
429
+ };
430
+
431
+ // packages/core/functions/src/services/tracing.ts
432
+ import { Context as Context5 } from "effect";
433
+ var TracingService = class extends Context5.Tag("TracingService")() {
434
+ static {
435
+ this.noop = {
436
+ write: () => {
437
+ }
438
+ };
439
+ }
440
+ static {
441
+ this.console = {
442
+ write: (event) => {
443
+ console.log(event);
444
+ }
445
+ };
446
+ }
447
+ };
448
+
449
+ // packages/core/functions/src/services/service-container.ts
450
+ var SERVICE_MAPPING = {
451
+ [DatabaseService.key]: "database",
452
+ [AiService.key]: "ai",
453
+ [QueuesService.key]: "queues",
454
+ [CredentialsService.key]: "credentials",
455
+ [TracingService.key]: "tracing"
456
+ };
457
+ var DEFAULT_SERVICES = {
458
+ tracing: TracingService.noop
459
+ };
460
+ var ServiceContainer = class _ServiceContainer {
461
+ constructor() {
462
+ this._services = {
463
+ ...DEFAULT_SERVICES
464
+ };
465
+ }
466
+ /**
467
+ * Set services.
468
+ * @param services - Services to set.
469
+ * @returns The container instance.
470
+ */
471
+ setServices(services) {
472
+ this._services = {
473
+ ...this._services,
474
+ ...services
475
+ };
476
+ return this;
477
+ }
478
+ getService(tag) {
479
+ const serviceKey = SERVICE_MAPPING[tag.key];
480
+ const service = serviceKey != null ? this._services[serviceKey] : void 0;
481
+ if (!service) {
482
+ throw new Error(`Service not available: ${tag.key}`);
483
+ }
484
+ return service;
485
+ }
486
+ clone() {
487
+ return new _ServiceContainer().setServices({
488
+ ...this._services
489
+ });
490
+ }
491
+ };
492
+
493
+ // packages/core/functions/src/executor/executor.ts
494
+ import { Effect, Schema as Schema5 } from "effect";
495
+ var FunctionExecutor = class {
496
+ constructor(_services) {
497
+ this._services = _services;
498
+ }
499
+ // TODO(dmaretskyi): Invocation context: queue, space, etc...
500
+ async invoke(fnDef, input) {
501
+ const assertInput = fnDef.inputSchema.pipe(Schema5.asserts);
502
+ assertInput(input);
503
+ const context = {
504
+ getService: this._services.getService.bind(this._services),
505
+ getSpace: async (_spaceId) => {
506
+ throw new Error("Not available. Use the database service instead.");
507
+ },
508
+ space: void 0,
509
+ get ai() {
510
+ throw new Error("Not available. Use the ai service instead.");
511
+ }
512
+ };
513
+ const result = await fnDef.handler({
514
+ context,
515
+ data: input
516
+ });
517
+ const assertOutput = fnDef.outputSchema?.pipe(Schema5.asserts);
518
+ assertOutput(result);
519
+ if (Effect.isEffect(result)) {
520
+ return Effect.runPromise(result);
521
+ }
522
+ return result;
523
+ }
524
+ };
390
525
  export {
526
+ AiService,
527
+ ConfiguredCredentialsService,
528
+ CredentialsService,
529
+ DatabaseService,
391
530
  EmailTriggerOutput,
392
531
  FUNCTIONS_PRESET_META_KEY,
393
532
  FUNCTION_TYPES,
533
+ FunctionExecutor,
394
534
  FunctionManifestSchema,
395
535
  FunctionTrigger,
396
536
  FunctionTriggerSchema,
@@ -400,12 +540,15 @@ export {
400
540
  InvocationTraceEventType,
401
541
  InvocationTraceStartEvent,
402
542
  QueueTriggerOutput,
543
+ QueuesService,
403
544
  ScriptType,
545
+ ServiceContainer,
404
546
  SubscriptionTriggerOutput,
405
547
  TimerTriggerOutput,
406
548
  TraceEvent,
407
549
  TraceEventException,
408
550
  TraceEventLog,
551
+ TracingService,
409
552
  TriggerKind,
410
553
  TriggerSchema,
411
554
  WebhookTriggerOutput,