@dxos/functions 0.7.5-labs.ea4b4c2 → 0.7.5-labs.f400bbc
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.
- package/dist/lib/browser/bundler/index.mjs +20 -20
- package/dist/lib/browser/bundler/index.mjs.map +3 -3
- package/dist/lib/browser/{chunk-PI2DP37S.mjs → chunk-IXJNRWJP.mjs} +40 -10
- package/dist/lib/browser/chunk-IXJNRWJP.mjs.map +7 -0
- package/dist/lib/browser/{chunk-JNWHUD6Z.mjs → chunk-XLM3CJXO.mjs} +2 -2
- package/dist/lib/browser/index.mjs +23 -7
- package/dist/lib/browser/index.mjs.map +3 -3
- package/dist/lib/browser/meta.json +1 -1
- package/dist/lib/browser/testing/index.mjs +2 -2
- package/dist/lib/browser/types/index.mjs +1 -1
- package/dist/lib/node/bundler/index.cjs +20 -20
- package/dist/lib/node/bundler/index.cjs.map +3 -3
- package/dist/lib/node/{chunk-PGFJYL6Q.cjs → chunk-MGCKR53Q.cjs} +41 -13
- package/dist/lib/node/chunk-MGCKR53Q.cjs.map +7 -0
- package/dist/lib/node/{chunk-2ASAZ4AS.cjs → chunk-TLSUCABH.cjs} +15 -15
- package/dist/lib/node/index.cjs +36 -19
- package/dist/lib/node/index.cjs.map +3 -3
- package/dist/lib/node/meta.json +1 -1
- package/dist/lib/node/testing/index.cjs +7 -7
- package/dist/lib/node/types/index.cjs +10 -10
- package/dist/lib/node/types/index.cjs.map +1 -1
- package/dist/lib/node-esm/bundler/index.mjs +20 -20
- package/dist/lib/node-esm/bundler/index.mjs.map +3 -3
- package/dist/lib/node-esm/{chunk-LNBGGB6Z.mjs → chunk-CKTHJQ7M.mjs} +2 -2
- package/dist/lib/node-esm/{chunk-IOAKDIT3.mjs → chunk-FCZGNRNF.mjs} +40 -10
- package/dist/lib/node-esm/chunk-FCZGNRNF.mjs.map +7 -0
- package/dist/lib/node-esm/index.mjs +23 -7
- package/dist/lib/node-esm/index.mjs.map +3 -3
- package/dist/lib/node-esm/meta.json +1 -1
- package/dist/lib/node-esm/testing/index.mjs +2 -2
- package/dist/lib/node-esm/types/index.mjs +1 -1
- package/dist/types/src/bundler/bundler.d.ts +15 -3
- package/dist/types/src/bundler/bundler.d.ts.map +1 -1
- package/dist/types/src/handler.d.ts +30 -4
- package/dist/types/src/handler.d.ts.map +1 -1
- package/dist/types/src/testing/types.d.ts +2 -2
- package/dist/types/src/types/index.d.ts +1 -0
- package/dist/types/src/types/index.d.ts.map +1 -1
- package/dist/types/src/types/schema.d.ts +16 -16
- package/dist/types/src/types/schema.d.ts.map +1 -1
- package/dist/types/src/types/trace.d.ts +103 -0
- package/dist/types/src/types/trace.d.ts.map +1 -0
- package/dist/types/src/types/types.d.ts +8 -8
- package/dist/types/src/types/types.d.ts.map +1 -1
- package/package.json +21 -20
- package/src/bundler/bundler.test.ts +10 -6
- package/src/bundler/bundler.ts +21 -7
- package/src/handler.ts +58 -9
- package/src/types/index.ts +1 -0
- package/src/types/schema.ts +0 -1
- package/src/types/trace.ts +49 -0
- package/src/types/types.ts +1 -1
- package/dist/lib/browser/chunk-PI2DP37S.mjs.map +0 -7
- package/dist/lib/node/chunk-PGFJYL6Q.cjs.map +0 -7
- package/dist/lib/node-esm/chunk-IOAKDIT3.mjs.map +0 -7
- /package/dist/lib/browser/{chunk-JNWHUD6Z.mjs.map → chunk-XLM3CJXO.mjs.map} +0 -0
- /package/dist/lib/node/{chunk-2ASAZ4AS.cjs.map → chunk-TLSUCABH.cjs.map} +0 -0
- /package/dist/lib/node-esm/{chunk-LNBGGB6Z.mjs.map → chunk-CKTHJQ7M.mjs.map} +0 -0
|
@@ -17,19 +17,19 @@ var Bundler = class {
|
|
|
17
17
|
constructor(_options) {
|
|
18
18
|
this._options = _options;
|
|
19
19
|
}
|
|
20
|
-
async bundle(source) {
|
|
20
|
+
async bundle({ path, source }) {
|
|
21
21
|
const { sandboxedModules: providedModules, ...options } = this._options;
|
|
22
22
|
const createResult = async (result) => {
|
|
23
23
|
return {
|
|
24
24
|
timestamp: Date.now(),
|
|
25
|
-
sourceHash: Buffer.from(await subtleCrypto.digest("SHA-256", Buffer.from(source))),
|
|
25
|
+
sourceHash: source ? Buffer.from(await subtleCrypto.digest("SHA-256", Buffer.from(source))) : void 0,
|
|
26
26
|
...result
|
|
27
27
|
};
|
|
28
28
|
};
|
|
29
29
|
if (this._options.platform === "browser") {
|
|
30
30
|
invariant(initialized, "Compiler not initialized.", {
|
|
31
31
|
F: __dxlog_file,
|
|
32
|
-
L:
|
|
32
|
+
L: 71,
|
|
33
33
|
S: this,
|
|
34
34
|
A: [
|
|
35
35
|
"initialized",
|
|
@@ -38,7 +38,7 @@ var Bundler = class {
|
|
|
38
38
|
});
|
|
39
39
|
await initialized;
|
|
40
40
|
}
|
|
41
|
-
const imports = analyzeSourceFileImports(source);
|
|
41
|
+
const imports = source ? analyzeSourceFileImports(source) : [];
|
|
42
42
|
try {
|
|
43
43
|
const result = await build({
|
|
44
44
|
platform: options.platform,
|
|
@@ -49,7 +49,7 @@ var Bundler = class {
|
|
|
49
49
|
metafile: true,
|
|
50
50
|
write: false,
|
|
51
51
|
entryPoints: [
|
|
52
|
-
"memory:main.tsx"
|
|
52
|
+
path ?? "memory:main.tsx"
|
|
53
53
|
],
|
|
54
54
|
bundle: true,
|
|
55
55
|
format: "esm",
|
|
@@ -59,15 +59,15 @@ var Bundler = class {
|
|
|
59
59
|
setup: (build2) => {
|
|
60
60
|
build2.onResolve({
|
|
61
61
|
filter: /^\.\/runtime\.js$/
|
|
62
|
-
}, ({ path }) => {
|
|
62
|
+
}, ({ path: path2 }) => {
|
|
63
63
|
return {
|
|
64
|
-
path,
|
|
64
|
+
path: path2,
|
|
65
65
|
external: true
|
|
66
66
|
};
|
|
67
67
|
});
|
|
68
68
|
build2.onResolve({
|
|
69
69
|
filter: /^dxos:functions$/
|
|
70
|
-
}, ({ path }) => {
|
|
70
|
+
}, ({ path: path2 }) => {
|
|
71
71
|
return {
|
|
72
72
|
path: "./runtime.js",
|
|
73
73
|
external: true
|
|
@@ -75,17 +75,17 @@ var Bundler = class {
|
|
|
75
75
|
});
|
|
76
76
|
build2.onResolve({
|
|
77
77
|
filter: /^memory:/
|
|
78
|
-
}, ({ path }) => {
|
|
78
|
+
}, ({ path: path2 }) => {
|
|
79
79
|
return {
|
|
80
|
-
path:
|
|
80
|
+
path: path2.split(":")[1],
|
|
81
81
|
namespace: "memory"
|
|
82
82
|
};
|
|
83
83
|
});
|
|
84
84
|
build2.onLoad({
|
|
85
85
|
filter: /.*/,
|
|
86
86
|
namespace: "memory"
|
|
87
|
-
}, ({ path }) => {
|
|
88
|
-
if (
|
|
87
|
+
}, ({ path: path2 }) => {
|
|
88
|
+
if (path2 === "main.tsx") {
|
|
89
89
|
return {
|
|
90
90
|
contents: source,
|
|
91
91
|
loader: "tsx"
|
|
@@ -95,9 +95,9 @@ var Bundler = class {
|
|
|
95
95
|
for (const module of providedModules) {
|
|
96
96
|
build2.onResolve({
|
|
97
97
|
filter: new RegExp(`^${module}$`)
|
|
98
|
-
}, ({ path }) => {
|
|
98
|
+
}, ({ path: path2 }) => {
|
|
99
99
|
return {
|
|
100
|
-
path,
|
|
100
|
+
path: path2,
|
|
101
101
|
namespace: "injected-module"
|
|
102
102
|
};
|
|
103
103
|
});
|
|
@@ -105,13 +105,13 @@ var Bundler = class {
|
|
|
105
105
|
build2.onLoad({
|
|
106
106
|
filter: /.*/,
|
|
107
107
|
namespace: "injected-module"
|
|
108
|
-
}, ({ path }) => {
|
|
109
|
-
const namedImports = imports.find((entry) => entry.moduleIdentifier ===
|
|
108
|
+
}, ({ path: path2 }) => {
|
|
109
|
+
const namedImports = imports.find((entry) => entry.moduleIdentifier === path2)?.namedImports ?? [];
|
|
110
110
|
return {
|
|
111
111
|
contents: `
|
|
112
|
-
const { ${namedImports.join(",")} } = window.__DXOS_SANDBOX_MODULES__[${JSON.stringify(
|
|
112
|
+
const { ${namedImports.join(",")} } = window.__DXOS_SANDBOX_MODULES__[${JSON.stringify(path2)}];
|
|
113
113
|
export { ${namedImports.join(",")} };
|
|
114
|
-
export default window.__DXOS_SANDBOX_MODULES__[${JSON.stringify(
|
|
114
|
+
export default window.__DXOS_SANDBOX_MODULES__[${JSON.stringify(path2)}].default;
|
|
115
115
|
`,
|
|
116
116
|
loader: "tsx"
|
|
117
117
|
};
|
|
@@ -123,7 +123,7 @@ var Bundler = class {
|
|
|
123
123
|
});
|
|
124
124
|
log("compile complete", result.metafile, {
|
|
125
125
|
F: __dxlog_file,
|
|
126
|
-
L:
|
|
126
|
+
L: 135,
|
|
127
127
|
S: this,
|
|
128
128
|
C: (f, a) => f(...a)
|
|
129
129
|
});
|
|
@@ -141,7 +141,7 @@ var Bundler = class {
|
|
|
141
141
|
analyzeImports(result) {
|
|
142
142
|
invariant(result.outputFiles, void 0, {
|
|
143
143
|
F: __dxlog_file,
|
|
144
|
-
L:
|
|
144
|
+
L: 148,
|
|
145
145
|
S: this,
|
|
146
146
|
A: [
|
|
147
147
|
"result.outputFiles",
|
|
@@ -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
|
|
5
|
-
"mappings": ";;;;AAKA,SAASA,OAAOC,kBAAiD;AAEjE,SAASC,oBAAoB;AAC7B,SAASC,iBAAiB;AAC1B,SAASC,WAAW;;
|
|
6
|
-
"names": ["build", "initialize", "subtleCrypto", "invariant", "log", "initialized", "initializeBundler", "options", "wasmURL", "wasmUrl", "Bundler", "constructor", "_options", "bundle", "source", "sandboxedModules", "providedModules", "createResult", "result", "timestamp", "Date", "now", "sourceHash", "Buffer", "from", "digest", "platform", "imports", "analyzeSourceFileImports", "conditions", "metafile", "write", "entryPoints", "format", "plugins", "name", "setup", "onResolve", "filter", "
|
|
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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AI,CAACE,YAAAA;AACxB,WAAO;MACLY,mBAAmBZ,QAAQ,CAAA;MAC3BrB,cAAcqB,QAAQ,CAAA,GAClBQ,KAAAA,EACDW,MAAM,GAAG,EAAC,EACV/C,MAAM,GAAA,EACN0B,IAAI,CAACQ,eAAeA,WAAWE,KAAI,CAAA;MACtCK,oBAAoBb,QAAQ,CAAA;MAC5BlB,kBAAkBkB,QAAQ,CAAA;MAC1Bc,QAAQd,QAAQ,CAAA;IAClB;EACF,CAAA;AACF;AAEA,IAAMd,aAAqB;EACzBnB,MAAM;EACNC,OAAO,CAACtC,WAAAA;AAGNA,IAAAA,OAAMuC,UAAU;MAAEC,QAAQ;IAAe,GAAG,CAACkD,UAAU;MACrD5E,MAAM4E,KAAK5E;MACX6B,WAAW;IACb,EAAA;AAKA3C,IAAAA,OAAMuC,UAAU;MAAEC,QAAQ;MAAMG,WAAW;IAAW,GAAG,CAAC+C,UAAU;MAClE5E,MAAM,IAAI6E,IAAID,KAAK5E,MAAM4E,KAAKE,QAAQ,EAAEC,SAAQ;MAChDlD,WAAW;IACb,EAAA;AAIA3C,IAAAA,OAAM4C,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", "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"]
|
|
7
7
|
}
|
|
@@ -7,7 +7,6 @@ var ScriptType = class extends TypedObject({
|
|
|
7
7
|
typename: "dxos.org/type/Script",
|
|
8
8
|
version: "0.1.0"
|
|
9
9
|
})({
|
|
10
|
-
// TODO(burdon): Change to URI?
|
|
11
10
|
name: S.optional(S.String),
|
|
12
11
|
description: S.optional(S.String),
|
|
13
12
|
// TODO(burdon): Change to hash of deployed content.
|
|
@@ -104,18 +103,12 @@ var SubscriptionTriggerSchema = S2.Struct({
|
|
|
104
103
|
[AST.TitleAnnotationId]: "Options"
|
|
105
104
|
}))
|
|
106
105
|
}).pipe(S2.mutable);
|
|
107
|
-
var TriggerSchema = S2.Union(
|
|
108
|
-
//
|
|
109
|
-
TimerTriggerSchema,
|
|
110
|
-
WebhookTriggerSchema,
|
|
111
|
-
SubscriptionTriggerSchema,
|
|
112
|
-
EmailTriggerSchema,
|
|
113
|
-
QueueTriggerSchema
|
|
114
|
-
).annotations({
|
|
106
|
+
var TriggerSchema = S2.Union(TimerTriggerSchema, WebhookTriggerSchema, SubscriptionTriggerSchema, EmailTriggerSchema, QueueTriggerSchema).annotations({
|
|
115
107
|
[AST.TitleAnnotationId]: "Trigger"
|
|
116
108
|
});
|
|
117
109
|
var FunctionTriggerSchema = S2.Struct({
|
|
118
110
|
// TODO(burdon): What type does this reference.
|
|
111
|
+
// TODO(wittjosiah): This should probably be a Ref?
|
|
119
112
|
function: S2.optional(S2.String.annotations({
|
|
120
113
|
[AST.TitleAnnotationId]: "Function"
|
|
121
114
|
})),
|
|
@@ -155,6 +148,43 @@ var FUNCTION_TYPES = [
|
|
|
155
148
|
FunctionTrigger
|
|
156
149
|
];
|
|
157
150
|
|
|
151
|
+
// packages/core/functions/src/types/trace.ts
|
|
152
|
+
import { EchoObject, Expando, ObjectId, Ref as Ref2, S as S3 } from "@dxos/echo-schema";
|
|
153
|
+
var InvocationTrace = S3.Struct({
|
|
154
|
+
id: ObjectId,
|
|
155
|
+
/**
|
|
156
|
+
* Queue DXN for function/workflow invocation events.
|
|
157
|
+
*/
|
|
158
|
+
invocationTraceQueue: Ref2(Expando),
|
|
159
|
+
/**
|
|
160
|
+
* DXN of the invoked function/workflow.
|
|
161
|
+
*/
|
|
162
|
+
invocationTarget: Ref2(Expando),
|
|
163
|
+
/**
|
|
164
|
+
* Present for automatic invocations.
|
|
165
|
+
*/
|
|
166
|
+
trigger: S3.optional(Ref2(FunctionTrigger))
|
|
167
|
+
}).pipe(EchoObject("dxos.org/type/InvocationTrace", "0.1.0"));
|
|
168
|
+
var TraceEventLog = S3.Struct({
|
|
169
|
+
timestampMs: S3.Number,
|
|
170
|
+
level: S3.String,
|
|
171
|
+
message: S3.String,
|
|
172
|
+
context: S3.optional(S3.Object)
|
|
173
|
+
});
|
|
174
|
+
var TraceEventException = S3.Struct({
|
|
175
|
+
timestampMs: S3.Number,
|
|
176
|
+
message: S3.String,
|
|
177
|
+
name: S3.String,
|
|
178
|
+
stack: S3.optional(S3.String)
|
|
179
|
+
});
|
|
180
|
+
var TraceEvent = S3.Struct({
|
|
181
|
+
id: ObjectId,
|
|
182
|
+
outcome: S3.String,
|
|
183
|
+
truncated: S3.Boolean,
|
|
184
|
+
logs: S3.Array(TraceEventLog),
|
|
185
|
+
exceptions: S3.Array(TraceEventException)
|
|
186
|
+
}).pipe(EchoObject("dxos.org/type/TraceEvent", "0.1.0"));
|
|
187
|
+
|
|
158
188
|
export {
|
|
159
189
|
ScriptType,
|
|
160
190
|
FunctionType,
|
|
@@ -166,4 +196,4 @@ export {
|
|
|
166
196
|
FunctionManifestSchema,
|
|
167
197
|
FUNCTION_TYPES
|
|
168
198
|
};
|
|
169
|
-
//# sourceMappingURL=chunk-
|
|
199
|
+
//# sourceMappingURL=chunk-IXJNRWJP.mjs.map
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../../../src/types/schema.ts", "../../../src/types/types.ts", "../../../src/types/trace.ts"],
|
|
4
|
+
"sourcesContent": ["//\n// Copyright 2024 DXOS.org\n//\n\nimport { JsonSchemaType, Ref, S, TypedObject } from '@dxos/echo-schema';\nimport { TextType } from '@dxos/schema';\n\n/**\n * Source script.\n */\nexport class ScriptType extends TypedObject({\n typename: 'dxos.org/type/Script',\n version: '0.1.0',\n})({\n name: S.optional(S.String),\n description: S.optional(S.String),\n // TODO(burdon): Change to hash of deployed content.\n // Whether source has changed since last deploy.\n changed: S.optional(S.Boolean),\n source: Ref(TextType),\n}) {}\n\n/**\n * Function deployment.\n */\n// TODO(burdon): Move to core/functions.\nexport class FunctionType extends TypedObject({\n typename: 'dxos.org/type/Function',\n version: '0.1.0',\n})({\n // TODO(burdon): Rename to id/uri?\n name: S.NonEmptyString,\n version: S.String,\n\n description: S.optional(S.String),\n\n // Reference to a source script if it exists within ECHO.\n // TODO(burdon): Don't ref ScriptType directly (core).\n source: S.optional(Ref(ScriptType)),\n\n inputSchema: S.optional(JsonSchemaType),\n outputSchema: S.optional(JsonSchemaType),\n\n // Local binding to a function name.\n binding: S.optional(S.String),\n}) {}\n", "//\n// Copyright 2023 DXOS.org\n//\n\nimport { AST, OptionsAnnotationId, RawObject, S, TypedObject, DXN } from '@dxos/echo-schema';\n\n/**\n * Type discriminator for TriggerType.\n * Every spec has a type field of type TriggerKind that we can use to understand which type we're working with.\n * https://www.typescriptlang.org/docs/handbook/2/narrowing.html#discriminated-unions\n */\nexport enum TriggerKind {\n Timer = 'timer',\n Webhook = 'webhook',\n Subscription = 'subscription',\n Email = 'email',\n Queue = 'queue',\n}\n\n// TODO(burdon): Rename prop kind.\nconst typeLiteralAnnotations = { [AST.TitleAnnotationId]: 'Type' };\n\n/**\n * Cron timer.\n */\nconst TimerTriggerSchema = S.Struct({\n type: S.Literal(TriggerKind.Timer).annotations(typeLiteralAnnotations),\n cron: S.String.annotations({\n [AST.TitleAnnotationId]: 'Cron',\n [AST.ExamplesAnnotationId]: ['0 0 * * *'],\n }),\n}).pipe(S.mutable);\n\nexport type TimerTrigger = S.Schema.Type<typeof TimerTriggerSchema>;\n\nconst EmailTriggerSchema = S.Struct({\n type: S.Literal(TriggerKind.Email).annotations(typeLiteralAnnotations),\n}).pipe(S.mutable);\n\nexport type EmailTrigger = S.Schema.Type<typeof EmailTriggerSchema>;\n\nconst QueueTriggerSchema = S.Struct({\n type: S.Literal(TriggerKind.Queue).annotations(typeLiteralAnnotations),\n queue: DXN,\n}).pipe(S.mutable);\n\nexport type QueueTrigger = S.Schema.Type<typeof QueueTriggerSchema>;\n\n/**\n * Webhook.\n */\nconst WebhookTriggerSchema = S.Struct({\n type: S.Literal(TriggerKind.Webhook).annotations(typeLiteralAnnotations),\n method: S.optional(\n S.String.annotations({\n [AST.TitleAnnotationId]: 'Method',\n [OptionsAnnotationId]: ['GET', 'POST'],\n }),\n ),\n port: S.optional(\n S.Number.annotations({\n [AST.TitleAnnotationId]: 'Port',\n }),\n ),\n}).pipe(S.mutable);\n\nexport type WebhookTrigger = S.Schema.Type<typeof WebhookTriggerSchema>;\n\n// TODO(burdon): Use ECHO definition (from https://github.com/dxos/dxos/pull/8233).\nconst QuerySchema = S.Struct({\n type: S.optional(S.String.annotations({ [AST.TitleAnnotationId]: 'Type' })),\n props: S.optional(S.Record({ key: S.String, value: S.Any })),\n}).annotations({ [AST.TitleAnnotationId]: 'Query' });\n\n/**\n * Subscription.\n */\nconst SubscriptionTriggerSchema = S.Struct({\n type: S.Literal(TriggerKind.Subscription).annotations(typeLiteralAnnotations),\n // TODO(burdon): Define query DSL (from ECHO). Reconcile with Table.Query.\n filter: QuerySchema,\n options: S.optional(\n S.Struct({\n // Watch changes to object (not just creation).\n deep: S.optional(S.Boolean.annotations({ [AST.TitleAnnotationId]: 'Nested' })),\n // Debounce changes (delay in ms).\n delay: S.optional(S.Number.annotations({ [AST.TitleAnnotationId]: 'Delay' })),\n }).annotations({ [AST.TitleAnnotationId]: 'Options' }),\n ),\n}).pipe(S.mutable);\n\nexport type SubscriptionTrigger = S.Schema.Type<typeof SubscriptionTriggerSchema>;\n\n/**\n * Trigger schema (discriminated union).\n */\nexport const TriggerSchema = S.Union(\n TimerTriggerSchema,\n WebhookTriggerSchema,\n SubscriptionTriggerSchema,\n EmailTriggerSchema,\n QueueTriggerSchema,\n).annotations({\n [AST.TitleAnnotationId]: 'Trigger',\n});\n\nexport type TriggerType = S.Schema.Type<typeof TriggerSchema>;\n\n/**\n * Function trigger.\n */\nexport const FunctionTriggerSchema = S.Struct({\n // TODO(burdon): What type does this reference.\n // TODO(wittjosiah): This should probably be a Ref?\n function: S.optional(S.String.annotations({ [AST.TitleAnnotationId]: 'Function' })),\n\n enabled: S.optional(S.Boolean.annotations({ [AST.TitleAnnotationId]: 'Enabled' })),\n\n // TODO(burdon): Flatten entire schema.\n spec: S.optional(TriggerSchema),\n\n // TODO(burdon): Get meta from function.\n // The `meta` property is merged into the event data passed to the function.\n meta: S.optional(S.mutable(S.Record({ key: S.String, value: S.Any }))),\n});\n\nexport type FunctionTriggerType = S.Schema.Type<typeof FunctionTriggerSchema>;\n\n/**\n * Function trigger.\n */\nexport class FunctionTrigger extends TypedObject({\n typename: 'dxos.org/type/FunctionTrigger',\n version: '0.1.0',\n})(FunctionTriggerSchema.fields) {}\n\n/**\n * Function definition.\n * @deprecated (Use dxos.org/type/Function)\n */\n// TODO(burdon): Reconcile with FunctionType.\nexport class FunctionDef extends TypedObject({\n typename: 'dxos.org/type/FunctionDef',\n version: '0.1.0',\n})({\n uri: S.String,\n description: S.optional(S.String),\n route: S.String,\n handler: S.String,\n}) {}\n\n/**\n * Function manifest file.\n */\nexport const FunctionManifestSchema = S.Struct({\n functions: S.optional(S.mutable(S.Array(RawObject(FunctionDef)))),\n triggers: S.optional(S.mutable(S.Array(RawObject(FunctionTrigger)))),\n});\n\nexport type FunctionManifest = S.Schema.Type<typeof FunctionManifestSchema>;\n\nexport const FUNCTION_TYPES = [FunctionDef, FunctionTrigger];\n", "//\n// Copyright 2025 DXOS.org\n//\n\nimport { EchoObject, Expando, ObjectId, Ref, S } from '@dxos/echo-schema';\n\nimport { FunctionTrigger } from './types';\n\nconst InvocationTrace = S.Struct({\n id: ObjectId,\n /**\n * Queue DXN for function/workflow invocation events.\n */\n invocationTraceQueue: Ref(Expando),\n /**\n * DXN of the invoked function/workflow.\n */\n invocationTarget: Ref(Expando),\n /**\n * Present for automatic invocations.\n */\n trigger: S.optional(Ref(FunctionTrigger)),\n}).pipe(EchoObject('dxos.org/type/InvocationTrace', '0.1.0'));\n\nexport type InvocationTraceEvent = S.Schema.Type<typeof InvocationTrace>;\n\nconst TraceEventLog = S.Struct({\n timestampMs: S.Number,\n level: S.String,\n message: S.String,\n context: S.optional(S.Object),\n});\n\nconst TraceEventException = S.Struct({\n timestampMs: S.Number,\n message: S.String,\n name: S.String,\n stack: S.optional(S.String),\n});\n\nconst TraceEvent = S.Struct({\n id: ObjectId,\n outcome: S.String,\n truncated: S.Boolean,\n logs: S.Array(TraceEventLog),\n exceptions: S.Array(TraceEventException),\n}).pipe(EchoObject('dxos.org/type/TraceEvent', '0.1.0'));\n\nexport type TraceEvent = S.Schema.Type<typeof TraceEvent>;\n"],
|
|
5
|
+
"mappings": ";;;AAIA,SAASA,gBAAgBC,KAAKC,GAAGC,mBAAmB;AACpD,SAASC,gBAAgB;AAKlB,IAAMC,aAAN,cAAyBC,YAAY;EAC1CC,UAAU;EACVC,SAAS;AACX,CAAA,EAAG;EACDC,MAAMC,EAAEC,SAASD,EAAEE,MAAM;EACzBC,aAAaH,EAAEC,SAASD,EAAEE,MAAM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AAIC;;;;EAIJC,sBAAsBC,KAAIC,OAAAA;;;;EAI1BC,kBAAkBF,KAAIC,OAAAA;;;;EAItBE,SAASR,GAAES,SAASJ,KAAIK,eAAAA,CAAAA;AAC1B,CAAA,EAAGC,KAAKC,WAAW,iCAAiC,OAAA,CAAA;AAIpD,IAAMC,gBAAgBb,GAAEC,OAAO;EAC7Ba,aAAad,GAAEe;EACfC,OAAOhB,GAAEiB;EACTC,SAASlB,GAAEiB;EACXE,SAASnB,GAAES,SAAST,GAAEoB,MAAM;AAC9B,CAAA;AAEA,IAAMC,sBAAsBrB,GAAEC,OAAO;EACnCa,aAAad,GAAEe;EACfG,SAASlB,GAAEiB;EACXK,MAAMtB,GAAEiB;EACRM,OAAOvB,GAAES,SAAST,GAAEiB,MAAM;AAC5B,CAAA;AAEA,IAAMO,aAAaxB,GAAEC,OAAO;EAC1BC,IAAIC;EACJsB,SAASzB,GAAEiB;EACXS,WAAW1B,GAAE2B;EACbC,MAAM5B,GAAE6B,MAAMhB,aAAAA;EACdiB,YAAY9B,GAAE6B,MAAMR,mBAAAA;AACtB,CAAA,EAAGV,KAAKC,WAAW,4BAA4B,OAAA,CAAA;",
|
|
6
|
+
"names": ["JsonSchemaType", "Ref", "S", "TypedObject", "TextType", "ScriptType", "TypedObject", "typename", "version", "name", "S", "optional", "String", "description", "changed", "Boolean", "source", "Ref", "TextType", "FunctionType", "NonEmptyString", "inputSchema", "JsonSchemaType", "outputSchema", "binding", "AST", "OptionsAnnotationId", "RawObject", "S", "TypedObject", "DXN", "TriggerKind", "typeLiteralAnnotations", "AST", "TitleAnnotationId", "TimerTriggerSchema", "S", "Struct", "type", "Literal", "annotations", "cron", "String", "ExamplesAnnotationId", "pipe", "mutable", "EmailTriggerSchema", "QueueTriggerSchema", "queue", "DXN", "WebhookTriggerSchema", "method", "optional", "OptionsAnnotationId", "port", "Number", "QuerySchema", "props", "Record", "key", "value", "Any", "SubscriptionTriggerSchema", "filter", "options", "deep", "Boolean", "delay", "TriggerSchema", "Union", "FunctionTriggerSchema", "function", "enabled", "spec", "meta", "FunctionTrigger", "TypedObject", "typename", "version", "fields", "FunctionDef", "uri", "description", "route", "handler", "FunctionManifestSchema", "functions", "Array", "RawObject", "triggers", "FUNCTION_TYPES", "EchoObject", "Expando", "ObjectId", "Ref", "S", "InvocationTrace", "S", "Struct", "id", "ObjectId", "invocationTraceQueue", "Ref", "Expando", "invocationTarget", "trigger", "optional", "FunctionTrigger", "pipe", "EchoObject", "TraceEventLog", "timestampMs", "Number", "level", "String", "message", "context", "Object", "TraceEventException", "name", "stack", "TraceEvent", "outcome", "truncated", "Boolean", "logs", "Array", "exceptions"]
|
|
7
|
+
}
|
|
@@ -2,7 +2,7 @@ import "@dxos/node-std/globals";
|
|
|
2
2
|
import {
|
|
3
3
|
FunctionDef,
|
|
4
4
|
FunctionTrigger
|
|
5
|
-
} from "./chunk-
|
|
5
|
+
} from "./chunk-IXJNRWJP.mjs";
|
|
6
6
|
|
|
7
7
|
// packages/core/functions/src/function/function-registry.ts
|
|
8
8
|
import { Event } from "@dxos/async";
|
|
@@ -477,4 +477,4 @@ export {
|
|
|
477
477
|
createTimerTrigger,
|
|
478
478
|
TriggerRegistry
|
|
479
479
|
};
|
|
480
|
-
//# sourceMappingURL=chunk-
|
|
480
|
+
//# sourceMappingURL=chunk-XLM3CJXO.mjs.map
|
|
@@ -13,7 +13,7 @@ import {
|
|
|
13
13
|
TriggerRegistry,
|
|
14
14
|
createSubscriptionTrigger,
|
|
15
15
|
createTimerTrigger
|
|
16
|
-
} from "./chunk-
|
|
16
|
+
} from "./chunk-XLM3CJXO.mjs";
|
|
17
17
|
import {
|
|
18
18
|
FUNCTION_TYPES,
|
|
19
19
|
FunctionDef,
|
|
@@ -24,14 +24,29 @@ import {
|
|
|
24
24
|
ScriptType,
|
|
25
25
|
TriggerKind,
|
|
26
26
|
TriggerSchema
|
|
27
|
-
} from "./chunk-
|
|
27
|
+
} from "./chunk-IXJNRWJP.mjs";
|
|
28
28
|
import "./chunk-XRCXIG74.mjs";
|
|
29
29
|
|
|
30
30
|
// packages/core/functions/src/handler.ts
|
|
31
|
+
import { Schema as S } from "@effect/schema";
|
|
31
32
|
import { PublicKey } from "@dxos/client";
|
|
32
33
|
import { log } from "@dxos/log";
|
|
33
|
-
import {
|
|
34
|
+
import { isNonNullable } from "@dxos/util";
|
|
34
35
|
var __dxlog_file = "/home/runner/work/dxos/dxos/packages/core/functions/src/handler.ts";
|
|
36
|
+
var defineFunction = (params) => {
|
|
37
|
+
if (!S.isSchema(params.inputSchema)) {
|
|
38
|
+
throw new Error("Input schema must be a valid schema");
|
|
39
|
+
}
|
|
40
|
+
if (typeof params.handler !== "function") {
|
|
41
|
+
throw new Error("Handler must be a function");
|
|
42
|
+
}
|
|
43
|
+
return {
|
|
44
|
+
description: params.description,
|
|
45
|
+
inputSchema: params.inputSchema,
|
|
46
|
+
outputSchema: params.outputSchema ?? S.Any,
|
|
47
|
+
handler: params.handler
|
|
48
|
+
};
|
|
49
|
+
};
|
|
35
50
|
var subscriptionHandler = (handler, types) => {
|
|
36
51
|
return async ({ event: { data }, context, response, ...rest }) => {
|
|
37
52
|
const { client } = context;
|
|
@@ -39,20 +54,20 @@ var subscriptionHandler = (handler, types) => {
|
|
|
39
54
|
if (!space) {
|
|
40
55
|
log.error("Invalid space", void 0, {
|
|
41
56
|
F: __dxlog_file,
|
|
42
|
-
L:
|
|
57
|
+
L: 180,
|
|
43
58
|
S: void 0,
|
|
44
59
|
C: (f, a) => f(...a)
|
|
45
60
|
});
|
|
46
61
|
return response.status(500);
|
|
47
62
|
}
|
|
48
63
|
registerTypes(space, types);
|
|
49
|
-
const objects = space ? data.objects?.map((id) => space.db.getObjectById(id)).filter(
|
|
64
|
+
const objects = space ? data.objects?.map((id) => space.db.getObjectById(id)).filter(isNonNullable) : [];
|
|
50
65
|
if (!!data.spaceKey && !space) {
|
|
51
66
|
log.warn("invalid space", {
|
|
52
67
|
data
|
|
53
68
|
}, {
|
|
54
69
|
F: __dxlog_file,
|
|
55
|
-
L:
|
|
70
|
+
L: 192,
|
|
56
71
|
S: void 0,
|
|
57
72
|
C: (f, a) => f(...a)
|
|
58
73
|
});
|
|
@@ -62,7 +77,7 @@ var subscriptionHandler = (handler, types) => {
|
|
|
62
77
|
objects: objects?.length
|
|
63
78
|
}, {
|
|
64
79
|
F: __dxlog_file,
|
|
65
|
-
L:
|
|
80
|
+
L: 194,
|
|
66
81
|
S: void 0,
|
|
67
82
|
C: (f, a) => f(...a)
|
|
68
83
|
});
|
|
@@ -106,6 +121,7 @@ export {
|
|
|
106
121
|
TriggerSchema,
|
|
107
122
|
createSubscriptionTrigger,
|
|
108
123
|
createTimerTrigger,
|
|
124
|
+
defineFunction,
|
|
109
125
|
getInvocationUrl,
|
|
110
126
|
getUserFunctionUrlInMetadata,
|
|
111
127
|
incrementSemverPatch,
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../src/handler.ts"],
|
|
4
|
-
"sourcesContent": ["//\n// Copyright 2023 DXOS.org\n//\n\nimport {
|
|
5
|
-
"mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
|
|
6
|
-
"names": ["PublicKey", "log", "
|
|
4
|
+
"sourcesContent": ["//\n// Copyright 2023 DXOS.org\n//\n\nimport { Schema as S } from '@effect/schema';\nimport { type Effect } from 'effect';\n\nimport { type Client, PublicKey } from '@dxos/client';\nimport { type Space, type SpaceId } from '@dxos/client/echo';\nimport type { CoreDatabase, EchoDatabase, ReactiveEchoObject } from '@dxos/echo-db';\nimport { type HasId } from '@dxos/echo-schema';\nimport { type DXN } from '@dxos/keys';\nimport { log } from '@dxos/log';\nimport { type QueryResult } from '@dxos/protocols';\nimport { isNonNullable } from '@dxos/util';\n\n// TODO(burdon): Model after http request. Ref Lambda/OpenFaaS.\n// https://docs.aws.amazon.com/lambda/latest/dg/typescript-handler.html\n// https://www.serverless.com/framework/docs/providers/aws/guide/serverless.yml/#functions\n// https://www.npmjs.com/package/aws-lambda\n\n/**\n * Function handler.\n */\nexport type FunctionHandler<TData = {}, TMeta = {}, TOutput = any> = (params: {\n context: FunctionContext;\n event: FunctionEvent<TData, TMeta>;\n /**\n * @deprecated\n */\n response: FunctionResponse;\n}) => TOutput | Promise<TOutput> | Effect.Effect<TOutput, any>;\n\n/**\n * Function context.\n */\nexport interface FunctionContext {\n getSpace: (spaceId: SpaceId) => Promise<SpaceAPI>;\n\n /**\n * Space from which the function was invoked.\n */\n space: SpaceAPI | undefined;\n\n ai: FunctionContextAi;\n\n /**\n * @deprecated\n */\n // TODO(burdon): Limit access to individual space.\n client: Client;\n /**\n * @deprecated\n */\n // TODO(burdon): Replace with storage service abstraction.\n dataDir?: string;\n}\n\nexport interface FunctionContextAi {\n // TODO(dmaretskyi): Refer to cloudflare AI docs for more comprehensive typedefs.\n run(model: string, inputs: any, options?: any): Promise<any>;\n}\n\n/**\n * Event payload.\n */\n// TODO(dmaretskyi): Update type definitions to match the actual payload.\nexport type FunctionEvent<TData = {}, TMeta = {}> = {\n data: FunctionEventMeta<TMeta> & TData;\n};\n\n/**\n * Metadata from trigger.\n */\nexport type FunctionEventMeta<TMeta = {}> = {\n meta: TMeta;\n};\n\n/**\n * Function response.\n */\nexport type FunctionResponse = {\n status(code: number): FunctionResponse;\n};\n\n//\n// API.\n//\n\n// TODO(dmaretskyi): Temporary API to get the queues working.\n// TODO(dmaretskyi): To be replaced with integrating queues into echo.\nexport interface QueuesAPI {\n queryQueue(queue: DXN, options?: {}): Promise<QueryResult>;\n insertIntoQueue(queue: DXN, objects: HasId[]): Promise<void>;\n}\n\n/**\n * Space interface available to functions.\n */\nexport interface SpaceAPI {\n get id(): SpaceId;\n /**\n * @deprecated\n */\n get crud(): CoreDatabase;\n get db(): EchoDatabase;\n // TODO(dmaretskyi): Align with echo api --- queues.get(id).append(items);\n get queues(): QueuesAPI;\n}\n\n// TODO(wittjosiah): Fix this.\nconst __assertFunctionSpaceIsCompatibleWithTheClientSpace = () => {\n // const _: SpaceAPI = {} as Space;\n};\n\nexport type FunctionDefinition = {\n description?: string;\n inputSchema: S.Schema.AnyNoContext;\n outputSchema?: S.Schema.AnyNoContext;\n handler: FunctionHandler<any>;\n};\n\nexport type DefineFunctionParams<T, O = any> = {\n description?: string;\n inputSchema: S.Schema<T, any>;\n outputSchema?: S.Schema<O, any>;\n handler: FunctionHandler<T, any, O>;\n};\n\n// TODO(dmaretskyi): Bind input type to function handler.\nexport const defineFunction = <T, O>(params: DefineFunctionParams<T, O>): FunctionDefinition => {\n if (!S.isSchema(params.inputSchema)) {\n throw new Error('Input schema must be a valid schema');\n }\n if (typeof params.handler !== 'function') {\n throw new Error('Handler must be a function');\n }\n\n return {\n description: params.description,\n inputSchema: params.inputSchema,\n outputSchema: params.outputSchema ?? S.Any,\n handler: params.handler,\n };\n};\n\n//\n// Subscription utils.\n//\n\nexport type RawSubscriptionData = {\n spaceKey?: string;\n objects?: string[];\n};\n\nexport type SubscriptionData = {\n space?: Space;\n objects?: ReactiveEchoObject<any>[];\n};\n\n/**\n * Handler wrapper for subscription events; extracts space and objects.\n *\n * To test:\n * ```\n * curl -s -X POST -H \"Content-Type: application/json\" --data '{\"space\": \"0446...1cbb\"}' http://localhost:7100/dev/email-extractor\n * ```\n *\n * NOTE: Get space key from devtools or `dx space list --json`\n */\n// TODO(burdon): Evolve into plugin definition like Composer.\nexport const subscriptionHandler = <TMeta>(\n handler: FunctionHandler<SubscriptionData, TMeta>,\n types?: S.Schema<any>[],\n): FunctionHandler<RawSubscriptionData, TMeta> => {\n return async ({ event: { data }, context, response, ...rest }) => {\n const { client } = context;\n const space = data.spaceKey ? client.spaces.get(PublicKey.from(data.spaceKey)) : undefined;\n if (!space) {\n log.error('Invalid space');\n return response.status(500);\n }\n\n registerTypes(space, types);\n const objects = space\n ? data.objects\n ?.map<ReactiveEchoObject<any> | undefined>((id) => space!.db.getObjectById(id))\n .filter(isNonNullable)\n : [];\n\n if (!!data.spaceKey && !space) {\n log.warn('invalid space', { data });\n } else {\n log.info('handler', { space: space?.key.truncate(), objects: objects?.length });\n }\n\n return handler({ event: { data: { ...data, space, objects } }, context, response, ...rest });\n };\n};\n\n// TODO(burdon): Evolve types as part of function metadata.\nconst registerTypes = (space: Space, types: S.Schema<any>[] = []) => {\n const registry = space.db.graph.schemaRegistry;\n for (const type of types) {\n if (!registry.hasSchema(type)) {\n registry.addSchema([type]);\n }\n }\n};\n"],
|
|
5
|
+
"mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAIA,SAASA,UAAUC,SAAS;AAG5B,SAAsBC,iBAAiB;AAKvC,SAASC,WAAW;AAEpB,SAASC,qBAAqB;;AAoHvB,IAAMC,iBAAiB,CAAOC,WAAAA;AACnC,MAAI,CAACC,EAAEC,SAASF,OAAOG,WAAW,GAAG;AACnC,UAAM,IAAIC,MAAM,qCAAA;EAClB;AACA,MAAI,OAAOJ,OAAOK,YAAY,YAAY;AACxC,UAAM,IAAID,MAAM,4BAAA;EAClB;AAEA,SAAO;IACLE,aAAaN,OAAOM;IACpBH,aAAaH,OAAOG;IACpBI,cAAcP,OAAOO,gBAAgBN,EAAEO;IACvCH,SAASL,OAAOK;EAClB;AACF;AA2BO,IAAMI,sBAAsB,CACjCJ,SACAK,UAAAA;AAEA,SAAO,OAAO,EAAEC,OAAO,EAAEC,KAAI,GAAIC,SAASC,UAAU,GAAGC,KAAAA,MAAM;AAC3D,UAAM,EAAEC,OAAM,IAAKH;AACnB,UAAMI,QAAQL,KAAKM,WAAWF,OAAOG,OAAOC,IAAIC,UAAUC,KAAKV,KAAKM,QAAQ,CAAA,IAAKK;AACjF,QAAI,CAACN,OAAO;AACVO,UAAIC,MAAM,iBAAA,QAAA;;;;;;AACV,aAAOX,SAASY,OAAO,GAAA;IACzB;AAEAC,kBAAcV,OAAOP,KAAAA;AACrB,UAAMkB,UAAUX,QACZL,KAAKgB,SACDC,IAAyC,CAACC,OAAOb,MAAOc,GAAGC,cAAcF,EAAAA,CAAAA,EAC1EG,OAAOC,aAAAA,IACV,CAAA;AAEJ,QAAI,CAAC,CAACtB,KAAKM,YAAY,CAACD,OAAO;AAC7BO,UAAIW,KAAK,iBAAiB;QAAEvB;MAAK,GAAA;;;;;;IACnC,OAAO;AACLY,UAAIY,KAAK,WAAW;QAAEnB,OAAOA,OAAOoB,IAAIC,SAAAA;QAAYV,SAASA,SAASW;MAAO,GAAA;;;;;;IAC/E;AAEA,WAAOlC,QAAQ;MAAEM,OAAO;QAAEC,MAAM;UAAE,GAAGA;UAAMK;UAAOW;QAAQ;MAAE;MAAGf;MAASC;MAAU,GAAGC;IAAK,CAAA;EAC5F;AACF;AAGA,IAAMY,gBAAgB,CAACV,OAAcP,QAAyB,CAAA,MAAE;AAC9D,QAAM8B,WAAWvB,MAAMc,GAAGU,MAAMC;AAChC,aAAWC,QAAQjC,OAAO;AACxB,QAAI,CAAC8B,SAASI,UAAUD,IAAAA,GAAO;AAC7BH,eAASK,UAAU;QAACF;OAAK;IAC3B;EACF;AACF;",
|
|
6
|
+
"names": ["Schema", "S", "PublicKey", "log", "isNonNullable", "defineFunction", "params", "S", "isSchema", "inputSchema", "Error", "handler", "description", "outputSchema", "Any", "subscriptionHandler", "types", "event", "data", "context", "response", "rest", "client", "space", "spaceKey", "spaces", "get", "PublicKey", "from", "undefined", "log", "error", "status", "registerTypes", "objects", "map", "id", "db", "getObjectById", "filter", "isNonNullable", "warn", "info", "key", "truncate", "length", "registry", "graph", "schemaRegistry", "type", "hasSchema", "addSchema"]
|
|
7
7
|
}
|