@dxos/functions 0.8.4-main.c4373fc → 0.8.4-main.c85a9c8dae

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 (205) hide show
  1. package/README.md +4 -6
  2. package/dist/lib/neutral/index.mjs +1240 -0
  3. package/dist/lib/neutral/index.mjs.map +7 -0
  4. package/dist/lib/neutral/meta.json +1 -0
  5. package/dist/types/src/errors.d.ts +44 -60
  6. package/dist/types/src/errors.d.ts.map +1 -1
  7. package/dist/types/src/{examples → example}/fib.d.ts +1 -1
  8. package/dist/types/src/example/fib.d.ts.map +1 -0
  9. package/dist/types/src/example/forex-effect.d.ts +3 -0
  10. package/dist/types/src/example/forex-effect.d.ts.map +1 -0
  11. package/dist/types/src/example/index.d.ts +12 -0
  12. package/dist/types/src/example/index.d.ts.map +1 -0
  13. package/dist/types/src/{examples → example}/reply.d.ts +1 -1
  14. package/dist/types/src/example/reply.d.ts.map +1 -0
  15. package/dist/types/src/{examples → example}/sleep.d.ts +1 -1
  16. package/dist/types/src/example/sleep.d.ts.map +1 -0
  17. package/dist/types/src/index.d.ts +4 -8
  18. package/dist/types/src/index.d.ts.map +1 -1
  19. package/dist/types/src/operation-compatibility.test.d.ts +2 -0
  20. package/dist/types/src/operation-compatibility.test.d.ts.map +1 -0
  21. package/dist/types/src/protocol/functions-ai-http-client.d.ts +12 -0
  22. package/dist/types/src/protocol/functions-ai-http-client.d.ts.map +1 -0
  23. package/dist/types/src/protocol/index.d.ts +2 -0
  24. package/dist/types/src/protocol/index.d.ts.map +1 -0
  25. package/dist/types/src/protocol/protocol.d.ts +7 -0
  26. package/dist/types/src/protocol/protocol.d.ts.map +1 -0
  27. package/dist/types/src/protocol/protocol.test.d.ts +2 -0
  28. package/dist/types/src/protocol/protocol.test.d.ts.map +1 -0
  29. package/dist/types/src/sdk.d.ts +117 -0
  30. package/dist/types/src/sdk.d.ts.map +1 -0
  31. package/dist/types/src/services/credentials.d.ts +6 -4
  32. package/dist/types/src/services/credentials.d.ts.map +1 -1
  33. package/dist/types/src/services/event-logger.d.ts +33 -27
  34. package/dist/types/src/services/event-logger.d.ts.map +1 -1
  35. package/dist/types/src/services/function-invocation-service.d.ts +7 -19
  36. package/dist/types/src/services/function-invocation-service.d.ts.map +1 -1
  37. package/dist/types/src/services/index.d.ts +2 -4
  38. package/dist/types/src/services/index.d.ts.map +1 -1
  39. package/dist/types/src/services/queues.d.ts +4 -4
  40. package/dist/types/src/services/queues.d.ts.map +1 -1
  41. package/dist/types/src/services/tracing.d.ts +41 -12
  42. package/dist/types/src/services/tracing.d.ts.map +1 -1
  43. package/dist/types/src/types/Function.d.ts +52 -0
  44. package/dist/types/src/types/Function.d.ts.map +1 -0
  45. package/dist/types/src/types/Script.d.ts +21 -0
  46. package/dist/types/src/types/Script.d.ts.map +1 -0
  47. package/dist/types/src/types/Trigger.d.ts +122 -0
  48. package/dist/types/src/types/Trigger.d.ts.map +1 -0
  49. package/dist/types/src/types/TriggerEvent.d.ts +75 -0
  50. package/dist/types/src/types/TriggerEvent.d.ts.map +1 -0
  51. package/dist/types/src/types/index.d.ts +6 -0
  52. package/dist/types/src/types/index.d.ts.map +1 -0
  53. package/dist/types/src/types/url.d.ts +13 -0
  54. package/dist/types/src/types/url.d.ts.map +1 -0
  55. package/dist/types/tsconfig.tsbuildinfo +1 -1
  56. package/package.json +24 -63
  57. package/src/errors.ts +4 -4
  58. package/src/{examples → example}/fib.ts +1 -1
  59. package/src/example/forex-effect.ts +40 -0
  60. package/src/example/index.ts +13 -0
  61. package/src/{examples → example}/reply.ts +1 -1
  62. package/src/{examples → example}/sleep.ts +1 -1
  63. package/src/index.ts +4 -8
  64. package/src/operation-compatibility.test.ts +185 -0
  65. package/src/protocol/functions-ai-http-client.ts +67 -0
  66. package/src/{executor → protocol}/index.ts +1 -1
  67. package/src/protocol/protocol.test.ts +59 -0
  68. package/src/protocol/protocol.ts +258 -0
  69. package/src/sdk.ts +297 -0
  70. package/src/services/credentials.ts +32 -17
  71. package/src/services/event-logger.ts +10 -4
  72. package/src/services/function-invocation-service.ts +23 -70
  73. package/src/services/index.ts +2 -4
  74. package/src/services/queues.ts +5 -7
  75. package/src/services/tracing.ts +68 -44
  76. package/src/types/Function.ts +83 -0
  77. package/src/types/Script.ts +34 -0
  78. package/src/types/Trigger.ts +153 -0
  79. package/src/types/TriggerEvent.ts +62 -0
  80. package/src/types/index.ts +9 -0
  81. package/src/types/url.ts +32 -0
  82. package/dist/lib/browser/bundler/index.mjs +0 -269
  83. package/dist/lib/browser/bundler/index.mjs.map +0 -7
  84. package/dist/lib/browser/chunk-J5LGTIGS.mjs +0 -10
  85. package/dist/lib/browser/chunk-J5LGTIGS.mjs.map +0 -7
  86. package/dist/lib/browser/chunk-LKYT2SAL.mjs +0 -665
  87. package/dist/lib/browser/chunk-LKYT2SAL.mjs.map +0 -7
  88. package/dist/lib/browser/edge/index.mjs +0 -83
  89. package/dist/lib/browser/edge/index.mjs.map +0 -7
  90. package/dist/lib/browser/index.mjs +0 -1395
  91. package/dist/lib/browser/index.mjs.map +0 -7
  92. package/dist/lib/browser/meta.json +0 -1
  93. package/dist/lib/browser/testing/index.mjs +0 -131
  94. package/dist/lib/browser/testing/index.mjs.map +0 -7
  95. package/dist/lib/node-esm/bundler/index.mjs +0 -270
  96. package/dist/lib/node-esm/bundler/index.mjs.map +0 -7
  97. package/dist/lib/node-esm/chunk-HSLMI22Q.mjs +0 -11
  98. package/dist/lib/node-esm/chunk-HSLMI22Q.mjs.map +0 -7
  99. package/dist/lib/node-esm/chunk-NAQIKLZB.mjs +0 -667
  100. package/dist/lib/node-esm/chunk-NAQIKLZB.mjs.map +0 -7
  101. package/dist/lib/node-esm/edge/index.mjs +0 -84
  102. package/dist/lib/node-esm/edge/index.mjs.map +0 -7
  103. package/dist/lib/node-esm/index.mjs +0 -1396
  104. package/dist/lib/node-esm/index.mjs.map +0 -7
  105. package/dist/lib/node-esm/meta.json +0 -1
  106. package/dist/lib/node-esm/testing/index.mjs +0 -132
  107. package/dist/lib/node-esm/testing/index.mjs.map +0 -7
  108. package/dist/types/src/bundler/bundler.d.ts +0 -49
  109. package/dist/types/src/bundler/bundler.d.ts.map +0 -1
  110. package/dist/types/src/bundler/bundler.test.d.ts +0 -2
  111. package/dist/types/src/bundler/bundler.test.d.ts.map +0 -1
  112. package/dist/types/src/bundler/index.d.ts +0 -2
  113. package/dist/types/src/bundler/index.d.ts.map +0 -1
  114. package/dist/types/src/edge/functions.d.ts +0 -17
  115. package/dist/types/src/edge/functions.d.ts.map +0 -1
  116. package/dist/types/src/edge/index.d.ts +0 -2
  117. package/dist/types/src/edge/index.d.ts.map +0 -1
  118. package/dist/types/src/examples/fib.d.ts.map +0 -1
  119. package/dist/types/src/examples/index.d.ts +0 -4
  120. package/dist/types/src/examples/index.d.ts.map +0 -1
  121. package/dist/types/src/examples/reply.d.ts.map +0 -1
  122. package/dist/types/src/examples/sleep.d.ts.map +0 -1
  123. package/dist/types/src/executor/executor.d.ts +0 -14
  124. package/dist/types/src/executor/executor.d.ts.map +0 -1
  125. package/dist/types/src/executor/index.d.ts +0 -2
  126. package/dist/types/src/executor/index.d.ts.map +0 -1
  127. package/dist/types/src/handler.d.ts +0 -109
  128. package/dist/types/src/handler.d.ts.map +0 -1
  129. package/dist/types/src/schema.d.ts +0 -43
  130. package/dist/types/src/schema.d.ts.map +0 -1
  131. package/dist/types/src/services/database.d.ts +0 -67
  132. package/dist/types/src/services/database.d.ts.map +0 -1
  133. package/dist/types/src/services/function-invocation-service.test.d.ts +0 -2
  134. package/dist/types/src/services/function-invocation-service.test.d.ts.map +0 -1
  135. package/dist/types/src/services/local-function-execution.d.ts +0 -34
  136. package/dist/types/src/services/local-function-execution.d.ts.map +0 -1
  137. package/dist/types/src/services/remote-function-execution-service.d.ts +0 -22
  138. package/dist/types/src/services/remote-function-execution-service.d.ts.map +0 -1
  139. package/dist/types/src/services/service-container.d.ts +0 -57
  140. package/dist/types/src/services/service-container.d.ts.map +0 -1
  141. package/dist/types/src/services/service-registry.d.ts +0 -31
  142. package/dist/types/src/services/service-registry.d.ts.map +0 -1
  143. package/dist/types/src/services/service-registry.test.d.ts +0 -2
  144. package/dist/types/src/services/service-registry.test.d.ts.map +0 -1
  145. package/dist/types/src/testing/index.d.ts +0 -3
  146. package/dist/types/src/testing/index.d.ts.map +0 -1
  147. package/dist/types/src/testing/layer.d.ts +0 -18
  148. package/dist/types/src/testing/layer.d.ts.map +0 -1
  149. package/dist/types/src/testing/logger.d.ts +0 -5
  150. package/dist/types/src/testing/logger.d.ts.map +0 -1
  151. package/dist/types/src/testing/persist-database.test.d.ts +0 -2
  152. package/dist/types/src/testing/persist-database.test.d.ts.map +0 -1
  153. package/dist/types/src/testing/services.d.ts +0 -59
  154. package/dist/types/src/testing/services.d.ts.map +0 -1
  155. package/dist/types/src/trace.d.ts +0 -122
  156. package/dist/types/src/trace.d.ts.map +0 -1
  157. package/dist/types/src/translations.d.ts +0 -12
  158. package/dist/types/src/translations.d.ts.map +0 -1
  159. package/dist/types/src/triggers/index.d.ts +0 -4
  160. package/dist/types/src/triggers/index.d.ts.map +0 -1
  161. package/dist/types/src/triggers/input-builder.d.ts +0 -3
  162. package/dist/types/src/triggers/input-builder.d.ts.map +0 -1
  163. package/dist/types/src/triggers/invocation-tracer.d.ts +0 -37
  164. package/dist/types/src/triggers/invocation-tracer.d.ts.map +0 -1
  165. package/dist/types/src/triggers/trigger-dispatcher.d.ts +0 -78
  166. package/dist/types/src/triggers/trigger-dispatcher.d.ts.map +0 -1
  167. package/dist/types/src/triggers/trigger-dispatcher.test.d.ts +0 -2
  168. package/dist/types/src/triggers/trigger-dispatcher.test.d.ts.map +0 -1
  169. package/dist/types/src/triggers/trigger-state-store.d.ts +0 -28
  170. package/dist/types/src/triggers/trigger-state-store.d.ts.map +0 -1
  171. package/dist/types/src/types.d.ts +0 -230
  172. package/dist/types/src/types.d.ts.map +0 -1
  173. package/dist/types/src/url.d.ts +0 -21
  174. package/dist/types/src/url.d.ts.map +0 -1
  175. package/src/bundler/bundler.test.ts +0 -58
  176. package/src/bundler/bundler.ts +0 -295
  177. package/src/bundler/index.ts +0 -5
  178. package/src/edge/functions.ts +0 -67
  179. package/src/edge/index.ts +0 -9
  180. package/src/examples/index.ts +0 -7
  181. package/src/executor/executor.ts +0 -58
  182. package/src/handler.ts +0 -225
  183. package/src/schema.ts +0 -71
  184. package/src/services/database.ts +0 -175
  185. package/src/services/function-invocation-service.test.ts +0 -81
  186. package/src/services/local-function-execution.ts +0 -153
  187. package/src/services/remote-function-execution-service.ts +0 -63
  188. package/src/services/service-container.ts +0 -115
  189. package/src/services/service-registry.test.ts +0 -45
  190. package/src/services/service-registry.ts +0 -63
  191. package/src/testing/index.ts +0 -6
  192. package/src/testing/layer.ts +0 -114
  193. package/src/testing/logger.ts +0 -17
  194. package/src/testing/persist-database.test.ts +0 -87
  195. package/src/testing/services.ts +0 -115
  196. package/src/trace.ts +0 -178
  197. package/src/translations.ts +0 -20
  198. package/src/triggers/index.ts +0 -7
  199. package/src/triggers/input-builder.ts +0 -35
  200. package/src/triggers/invocation-tracer.ts +0 -101
  201. package/src/triggers/trigger-dispatcher.test.ts +0 -665
  202. package/src/triggers/trigger-dispatcher.ts +0 -533
  203. package/src/triggers/trigger-state-store.ts +0 -61
  204. package/src/types.ts +0 -218
  205. package/src/url.ts +0 -55
@@ -1,21 +0,0 @@
1
- import { type ObjectMeta } from '@dxos/echo/internal';
2
- import { type SpaceId } from '@dxos/keys';
3
- export declare const FUNCTIONS_META_KEY = "dxos.org/service/function";
4
- export declare const FUNCTIONS_PRESET_META_KEY = "dxos.org/service/function-preset";
5
- /**
6
- * NOTE: functionId is backend ID, not ECHO object id.
7
- */
8
- export declare const getUserFunctionIdInMetadata: (meta: ObjectMeta) => string | undefined;
9
- /**
10
- * NOTE: functionId is backend ID, not ECHO object id.
11
- */
12
- export declare const setUserFunctionIdInMetadata: (meta: ObjectMeta, functionId: string) => void;
13
- /**
14
- * NOTE: functionId is backend ID, not ECHO object id.
15
- */
16
- export declare const getInvocationUrl: (functionId: string, edgeUrl: string, options?: InvocationOptions) => string;
17
- export type InvocationOptions = {
18
- spaceId?: SpaceId;
19
- subjectId?: string;
20
- };
21
- //# sourceMappingURL=url.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"url.d.ts","sourceRoot":"","sources":["../../../src/url.ts"],"names":[],"mappings":"AAIA,OAAO,EAAE,KAAK,UAAU,EAAE,MAAM,qBAAqB,CAAC;AACtD,OAAO,EAAE,KAAK,OAAO,EAAE,MAAM,YAAY,CAAC;AAG1C,eAAO,MAAM,kBAAkB,8BAA8B,CAAC;AAE9D,eAAO,MAAM,yBAAyB,qCAAqC,CAAC;AAM5E;;GAEG;AACH,eAAO,MAAM,2BAA2B,GAAI,MAAM,UAAU,uBAE3D,CAAC;AAEF;;GAEG;AACH,eAAO,MAAM,2BAA2B,GAAI,MAAM,UAAU,EAAE,YAAY,MAAM,SAS/E,CAAC;AAEF;;GAEG;AACH,eAAO,MAAM,gBAAgB,GAAI,YAAY,MAAM,EAAE,SAAS,MAAM,EAAE,UAAS,iBAAsB,WASpG,CAAC;AAEF,MAAM,MAAM,iBAAiB,GAAG;IAC9B,OAAO,CAAC,EAAE,OAAO,CAAC;IAClB,SAAS,CAAC,EAAE,MAAM,CAAC;CACpB,CAAC"}
@@ -1,58 +0,0 @@
1
- //
2
- // Copyright 2022 DXOS.org
3
- //
4
-
5
- // @ts-ignore
6
- import wasmUrl from 'esbuild-wasm/esbuild.wasm?url';
7
- import { assert, beforeAll, describe, expect, test } from 'vitest';
8
-
9
- import { isNode } from '@dxos/util';
10
-
11
- import { Bundler, initializeBundler } from './bundler';
12
-
13
- describe('Bundler', () => {
14
- beforeAll(async () => {
15
- if (!isNode()) {
16
- await initializeBundler({ wasmUrl });
17
- }
18
- });
19
-
20
- test('Basic', async () => {
21
- const bundler = new Bundler({ platform: 'node', sandboxedModules: [], remoteModules: {} });
22
- const result = await bundler.bundle({ source: 'const x = 100' }); // TODO(burdon): Test import.
23
- assert(!('error' in result), 'error should not exist');
24
- expect(result.asset).toBeDefined();
25
- });
26
-
27
- test('Import', async () => {
28
- const bundler = new Bundler({ platform: 'node', sandboxedModules: [], remoteModules: {} });
29
- const result = await bundler.bundle({
30
- source: `
31
- import { Filter } from './runtime.js';
32
-
33
- const query = Filter.typename('dxos.org/type/Example');
34
- `,
35
- });
36
- assert(!('error' in result), 'error should not exist');
37
- expect(result.asset).toBeDefined();
38
- });
39
-
40
- // TODO(dmaretskyi): Flaky on CI.
41
- test.skip('HTTPS Import', async () => {
42
- const bundler = new Bundler({ platform: 'node', sandboxedModules: [], remoteModules: {} });
43
- const result = await bundler.bundle({
44
- source: `
45
- import { invariant } from 'https://esm.sh/@dxos/invariant';
46
- invariant(true);
47
- `,
48
- });
49
- assert(!('error' in result), 'error should not exist');
50
- expect(result.asset).toBeDefined();
51
- });
52
-
53
- test('Error', async () => {
54
- const bundler = new Bundler({ platform: 'node', sandboxedModules: [], remoteModules: {} });
55
- const result = await bundler.bundle({ source: "import missing from './module'; missing();" });
56
- assert('error' in result, 'error should exist');
57
- });
58
- });
@@ -1,295 +0,0 @@
1
- //
2
- // Copyright 2023 DXOS.org
3
- //
4
-
5
- import * as FetchHttpClient from '@effect/platform/FetchHttpClient';
6
- import * as HttpClient from '@effect/platform/HttpClient';
7
- import * as Duration from 'effect/Duration';
8
- import * as Effect from 'effect/Effect';
9
- import * as Function from 'effect/Function';
10
- import * as Schedule from 'effect/Schedule';
11
- import { type BuildOptions, type BuildResult, type Loader, type Plugin, build, initialize } from 'esbuild-wasm';
12
-
13
- import { subtleCrypto } from '@dxos/crypto';
14
- import { runAndForwardErrors } from '@dxos/effect';
15
- import { invariant } from '@dxos/invariant';
16
- import { log } from '@dxos/log';
17
-
18
- export type Import = {
19
- moduleUrl: string;
20
- defaultImport: boolean;
21
- namedImports: string[];
22
- };
23
-
24
- export type BundleOptions = {
25
- /**
26
- * Source code to bundle.
27
- */
28
- source: string;
29
- };
30
-
31
- export type BundleResult =
32
- | {
33
- timestamp: number;
34
- sourceHash: Buffer;
35
- error: unknown;
36
- }
37
- | {
38
- timestamp: number;
39
- sourceHash: Buffer;
40
- imports: Import[];
41
- entryPoint: string;
42
- asset: Uint8Array;
43
- bundle: string;
44
- };
45
-
46
- export type BundlerOptions = {
47
- platform: BuildOptions['platform'];
48
- sandboxedModules: string[];
49
- remoteModules: Record<string, string>;
50
- };
51
-
52
- let initialized: Promise<void>;
53
- export const initializeBundler = async (options: { wasmUrl: string }) => {
54
- await (initialized ??= initialize({
55
- wasmURL: options.wasmUrl,
56
- }));
57
- };
58
-
59
- /**
60
- * ESBuild bundler.
61
- */
62
- export class Bundler {
63
- constructor(private readonly _options: BundlerOptions) {}
64
-
65
- async bundle({ source }: BundleOptions): Promise<BundleResult> {
66
- const { sandboxedModules: providedModules, ...options } = this._options;
67
- const sourceHash = Buffer.from(await subtleCrypto.digest('SHA-256', Buffer.from(source)));
68
-
69
- if (this._options.platform === 'browser') {
70
- invariant(initialized, 'Compiler not initialized.');
71
- await initialized;
72
- }
73
-
74
- const imports = source ? analyzeSourceFileImports(source) : [];
75
-
76
- // https://esbuild.github.io/api/#build
77
- try {
78
- const result = await build({
79
- platform: options.platform,
80
- conditions: ['workerd', 'browser'],
81
- metafile: true,
82
- write: false,
83
- entryPoints: {
84
- // Gets mapped to `userFunc.js` by esbuild.
85
- userFunc: 'memory:main.tsx',
86
- },
87
- bundle: true,
88
- format: 'esm',
89
- plugins: [
90
- {
91
- name: 'memory',
92
- setup: (build) => {
93
- build.onResolve({ filter: /^\.\/runtime\.js$/ }, ({ path }) => {
94
- return { path, external: true };
95
- });
96
-
97
- build.onResolve({ filter: /^dxos:functions$/ }, ({ path }) => {
98
- return { path: './runtime.js', external: true };
99
- });
100
-
101
- build.onResolve({ filter: /^memory:/ }, ({ path }) => {
102
- return { path: path.split(':')[1], namespace: 'memory' };
103
- });
104
-
105
- build.onLoad({ filter: /.*/, namespace: 'memory' }, ({ path }) => {
106
- if (path === 'main.tsx') {
107
- return {
108
- contents: source,
109
- loader: 'tsx',
110
- };
111
- }
112
- });
113
-
114
- for (const module of providedModules) {
115
- build.onResolve({ filter: new RegExp(`^${module}$`) }, ({ path }) => {
116
- return { path, namespace: 'injected-module' };
117
- });
118
- }
119
-
120
- build.onLoad({ filter: /.*/, namespace: 'injected-module' }, ({ path }) => {
121
- const namedImports = imports.find((entry) => entry.moduleIdentifier === path)?.namedImports ?? [];
122
- return {
123
- contents: `
124
- const { ${namedImports.join(',')} } = window.__DXOS_SANDBOX_MODULES__[${JSON.stringify(path)}];
125
- export { ${namedImports.join(',')} };
126
- export default window.__DXOS_SANDBOX_MODULES__[${JSON.stringify(path)}].default;
127
- `,
128
- loader: 'tsx',
129
- };
130
- });
131
- },
132
- },
133
- httpPlugin,
134
- ],
135
- });
136
-
137
- log('compile complete', result.metafile);
138
-
139
- const entryPoint = 'userFunc.js';
140
- return {
141
- timestamp: Date.now(),
142
- sourceHash,
143
- imports: this.analyzeImports(result),
144
- entryPoint,
145
- asset: result.outputFiles![0].contents,
146
- bundle: result.outputFiles![0].text,
147
- };
148
- } catch (err) {
149
- return { timestamp: Date.now(), sourceHash, error: err };
150
- }
151
- }
152
-
153
- // TODO(dmaretskyi): In the future we can replace the compiler with SWC with plugins running in WASM.
154
- analyzeImports(result: BuildResult): Import[] {
155
- invariant(result.outputFiles);
156
-
157
- // TODO(dmaretskyi): Support import aliases and wildcard imports.
158
- const parsedImports = allMatches(IMPORT_REGEX, result.outputFiles[0].text);
159
- return Object.values(result.metafile!.outputs)[0].imports.map((entry): Import => {
160
- const namedImports: string[] = [];
161
- const parsedImport = parsedImports.find((capture) => capture?.[4] === entry.path);
162
- if (parsedImport?.[2]) {
163
- NAMED_IMPORTS_REGEX.lastIndex = 0;
164
- const namedImportsMatch = NAMED_IMPORTS_REGEX.exec(parsedImport[2]);
165
- if (namedImportsMatch) {
166
- namedImportsMatch[1].split(',').forEach((importName) => {
167
- namedImports.push(importName.trim());
168
- });
169
- }
170
- }
171
-
172
- return {
173
- moduleUrl: entry.path,
174
- defaultImport: !!parsedImport?.[1],
175
- namedImports,
176
- };
177
- });
178
- }
179
-
180
- analyzeSourceFileImports(code: string): {
181
- defaultImportName: string;
182
- namedImports: string[];
183
- wildcardImportName: string;
184
- moduleIdentifier: string;
185
- quotes: string;
186
- }[] {
187
- // TODO(dmaretskyi): Support import aliases and wildcard imports.
188
- const parsedImports = allMatches(IMPORT_REGEX, code);
189
- return parsedImports.map((capture) => {
190
- return {
191
- defaultImportName: capture[1],
192
- namedImports: capture[2]?.split(',').map((importName) => importName.trim()),
193
- wildcardImportName: capture[3],
194
- moduleIdentifier: capture[4],
195
- quotes: capture[5],
196
- };
197
- });
198
- }
199
- }
200
-
201
- // https://regex101.com/r/FEN5ks/1
202
- // https://stackoverflow.com/a/73265022
203
- // $1 = default import name (can be non-existent)
204
- // $2 = destructured exports (can be non-existent)
205
- // $3 = wildcard import name (can be non-existent)
206
- // $4 = module identifier
207
- // $5 = quotes used (either ' or ")
208
- const IMPORT_REGEX =
209
- /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;
210
-
211
- const NAMED_IMPORTS_REGEX = /[ \n\t]*{((?:[ \n\t]*[^ \n\t"'{}]+[ \n\t]*,?)+)}[ \n\t]*/gm;
212
-
213
- const allMatches = (regex: RegExp, str: string) => {
214
- let match;
215
- const matches = [];
216
- regex.lastIndex = 0;
217
- while ((match = regex.exec(str))) {
218
- matches.push(match);
219
- }
220
-
221
- return matches;
222
- };
223
-
224
- type ParsedImport = {
225
- defaultImportName?: string;
226
- namedImports: string[];
227
- wildcardImportName?: string;
228
- moduleIdentifier: string;
229
- quotes: string;
230
- };
231
-
232
- const analyzeSourceFileImports = (code: string): ParsedImport[] => {
233
- // TODO(dmaretskyi): Support import aliases and wildcard imports.
234
- const parsedImports = allMatches(IMPORT_REGEX, code);
235
- return parsedImports.map((capture) => {
236
- return {
237
- defaultImportName: capture[1],
238
- namedImports: capture[2]
239
- ?.trim()
240
- .slice(1, -1)
241
- .split(',')
242
- .map((importName) => importName.trim()),
243
- wildcardImportName: capture[3],
244
- moduleIdentifier: capture[4],
245
- quotes: capture[5],
246
- };
247
- });
248
- };
249
-
250
- const MAX_RETRIES = 5;
251
- const INITIAL_DELAY = 1_000;
252
-
253
- const httpPlugin: Plugin = {
254
- name: 'http',
255
- setup: (build) => {
256
- // Intercept import paths starting with "http:" and "https:" so esbuild doesn't attempt to map them to a file system location.
257
- // Tag them with the "http-url" namespace to associate them with this plugin.
258
- build.onResolve({ filter: /^https?:\/\// }, (args) => ({
259
- path: args.path,
260
- namespace: 'http-url',
261
- }));
262
-
263
- // We also want to intercept all import paths inside downloaded files and resolve them against the original URL.
264
- // All of these files will be in the "http-url" namespace.
265
- // Make sure to keep the newly resolved URL in the "http-url" namespace so imports inside it will also be resolved as URLs recursively.
266
- build.onResolve({ filter: /.*/, namespace: 'http-url' }, (args) => ({
267
- path: new URL(args.path, args.importer).toString(),
268
- namespace: 'http-url',
269
- }));
270
-
271
- // When a URL is loaded, we want to actually download the content from the internet.
272
- // 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.
273
- build.onLoad({ filter: /.*/, namespace: 'http-url' }, async (args) => {
274
- return Effect.gen(function* () {
275
- const response = yield* HttpClient.get(args.path);
276
- if (response.status !== 200) {
277
- throw new Error(`failed to fetch: ${response.status}`);
278
- }
279
-
280
- const text = yield* response.text;
281
- return { contents: text, loader: 'jsx' as Loader };
282
- }).pipe(
283
- Effect.retry(
284
- Function.pipe(
285
- Schedule.exponential(Duration.millis(INITIAL_DELAY)),
286
- Schedule.jittered,
287
- Schedule.intersect(Schedule.recurs(MAX_RETRIES - 1)),
288
- ),
289
- ),
290
- Effect.provide(FetchHttpClient.layer),
291
- runAndForwardErrors,
292
- );
293
- });
294
- },
295
- };
@@ -1,5 +0,0 @@
1
- //
2
- // Copyright 2023 DXOS.org
3
- //
4
-
5
- export * from './bundler';
@@ -1,67 +0,0 @@
1
- //
2
- // Copyright 2024 DXOS.org
3
- //
4
-
5
- import { type DID } from 'iso-did/types';
6
-
7
- import { type Client } from '@dxos/client';
8
- import { createEdgeIdentity } from '@dxos/client/edge';
9
- import { EdgeHttpClient } from '@dxos/edge-client';
10
- import { invariant } from '@dxos/invariant';
11
- import { type PublicKey } from '@dxos/keys';
12
- import { log } from '@dxos/log';
13
- import { type UploadFunctionResponseBody } from '@dxos/protocols';
14
-
15
- export type UploadWorkerArgs = {
16
- client: Client;
17
- version: string;
18
- name?: string;
19
- functionId?: string;
20
- ownerPublicKey: PublicKey;
21
- entryPoint: string;
22
- assets: Record<string, Uint8Array>;
23
- };
24
-
25
- export const uploadWorkerFunction = async ({
26
- client,
27
- version,
28
- name,
29
- functionId,
30
- ownerPublicKey,
31
- entryPoint,
32
- assets,
33
- }: UploadWorkerArgs): Promise<UploadFunctionResponseBody> => {
34
- log('uploading function', { functionId, name, version, ownerPublicKey });
35
- const edgeUrl = client.config.values.runtime?.services?.edge?.url;
36
- invariant(edgeUrl, 'Edge is not configured.');
37
- const edgeClient = new EdgeHttpClient(edgeUrl);
38
- const edgeIdentity = createEdgeIdentity(client);
39
- edgeClient.setIdentity(edgeIdentity);
40
- const response = await edgeClient.uploadFunction(
41
- { functionId },
42
- { name, version, ownerPublicKey: ownerPublicKey.toHex(), entryPoint, assets },
43
- );
44
-
45
- // TODO(burdon): Edge service log.
46
- log('uploaded', {
47
- identityKey: edgeIdentity.identityKey,
48
- functionId,
49
- name,
50
- version,
51
- response,
52
- });
53
-
54
- return response;
55
- };
56
-
57
- export const incrementSemverPatch = (version: string): string => {
58
- const [major, minor, patch] = version.split('.');
59
- const patchNum = Number(patch);
60
- invariant(!Number.isNaN(patchNum), `Unexpected function version format: ${version}`);
61
- return [major, minor, String(patchNum + 1)].join('.');
62
- };
63
-
64
- // TODO(burdon): Factor out.
65
- export const publicKeyToDid = (key: PublicKey): DID => {
66
- return `did:key:${key.toHex()}`;
67
- };
package/src/edge/index.ts DELETED
@@ -1,9 +0,0 @@
1
- //
2
- // Copyright 2024 DXOS.org
3
- //
4
-
5
- // NOTE: This module is separate because it uses the edge client.
6
- // This means it cannot be used on edge itself.
7
- // TODO(wittjosiah): Factor out.
8
-
9
- export * from './functions';
@@ -1,7 +0,0 @@
1
- //
2
- // Copyright 2025 DXOS.org
3
- //
4
-
5
- export { default as fib } from './fib';
6
- export { default as reply } from './reply';
7
- export { default as sleep } from './sleep';
@@ -1,58 +0,0 @@
1
- //
2
- // Copyright 2025 DXOS.org
3
- //
4
-
5
- import * as Effect from 'effect/Effect';
6
- import * as Schema from 'effect/Schema';
7
-
8
- import { type SpaceId } from '@dxos/client/echo';
9
- import { runAndForwardErrors } from '@dxos/effect';
10
-
11
- import type { FunctionContext, FunctionDefinition } from '../handler';
12
- import type { ServiceContainer, Services } from '../services';
13
-
14
- /**
15
- * @deprecated Use `FunctionInvocationService`
16
- */
17
- export class FunctionExecutor {
18
- constructor(private readonly _services: ServiceContainer) {}
19
-
20
- /**
21
- * Invoke function.
22
- */
23
- // TODO(dmaretskyi): Invocation context: queue, space, etc...
24
- async invoke<F extends FunctionDefinition<any, any>>(
25
- functionDef: F,
26
- input: F extends FunctionDefinition<infer I, infer _O> ? I : never,
27
- ): Promise<F extends FunctionDefinition<infer _I, infer O> ? O : never> {
28
- // Assert input matches schema
29
- const assertInput = functionDef.inputSchema.pipe(Schema.asserts);
30
- (assertInput as any)(input);
31
-
32
- const context: FunctionContext = {
33
- space: undefined,
34
- getService: this._services.getService.bind(this._services),
35
- getSpace: async (_spaceId: SpaceId) => {
36
- throw new Error('Not available. Use the database service instead.');
37
- },
38
- };
39
-
40
- const result = functionDef.handler({ context, data: input });
41
-
42
- let data: unknown;
43
- if (Effect.isEffect(result)) {
44
- data = await (result as Effect.Effect<unknown, unknown, Services>).pipe(
45
- Effect.provide(this._services.createLayer()),
46
- runAndForwardErrors,
47
- );
48
- } else {
49
- data = await result;
50
- }
51
-
52
- // Assert output matches schema
53
- const assertOutput = functionDef.outputSchema?.pipe(Schema.asserts);
54
- (assertOutput as any)(data);
55
-
56
- return data as any;
57
- }
58
- }