@dxos/functions 0.7.5-labs.8a82073 → 0.7.5-labs.c0e040f

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dxos/functions",
3
- "version": "0.7.5-labs.8a82073",
3
+ "version": "0.7.5-labs.c0e040f",
4
4
  "description": "Functions API and runtime.",
5
5
  "homepage": "https://dxos.org",
6
6
  "bugs": "https://github.com/dxos/dxos/issues",
@@ -13,6 +13,11 @@
13
13
  "browser": "./dist/lib/browser/index.mjs",
14
14
  "node": "./dist/lib/node-esm/index.mjs"
15
15
  },
16
+ "./bundler": {
17
+ "types": "./dist/types/src/bundler/index.d.ts",
18
+ "browser": "./dist/lib/browser/bundler/index.mjs",
19
+ "node": "./dist/lib/node-esm/bundler/index.mjs"
20
+ },
16
21
  "./edge": {
17
22
  "types": "./dist/types/src/edge/index.d.ts",
18
23
  "browser": "./dist/lib/browser/edge/index.mjs",
@@ -32,6 +37,12 @@
32
37
  "types": "dist/types/src/index.d.ts",
33
38
  "typesVersions": {
34
39
  "*": {
40
+ "bundler": [
41
+ "dist/types/src/bundler/index.d.ts"
42
+ ],
43
+ "edge": [
44
+ "dist/types/src/edge/index.d.ts"
45
+ ],
35
46
  "testing": [
36
47
  "dist/types/src/testing/index.d.ts"
37
48
  ],
@@ -50,30 +61,32 @@
50
61
  "@preact/signals-core": "^1.6.0",
51
62
  "cron": "^3.1.6",
52
63
  "effect": "^3.12.3",
64
+ "esbuild-wasm": "^0.16.14",
53
65
  "express": "^4.19.2",
54
66
  "get-port-please": "^3.1.1",
55
67
  "iso-did": "^1.6.0",
56
68
  "ws": "^8.14.2",
57
- "@dxos/async": "0.7.5-labs.8a82073",
58
- "@dxos/context": "0.7.5-labs.8a82073",
59
- "@dxos/client": "0.7.5-labs.8a82073",
60
- "@dxos/echo-db": "0.7.5-labs.8a82073",
61
- "@dxos/echo-protocol": "0.7.5-labs.8a82073",
62
- "@dxos/echo-schema": "0.7.5-labs.8a82073",
63
- "@dxos/invariant": "0.7.5-labs.8a82073",
64
- "@dxos/keys": "0.7.5-labs.8a82073",
65
- "@dxos/edge-client": "0.7.5-labs.8a82073",
66
- "@dxos/live-object": "0.7.5-labs.8a82073",
67
- "@dxos/log": "0.7.5-labs.8a82073",
68
- "@dxos/node-std": "0.7.5-labs.8a82073",
69
- "@dxos/protocols": "0.7.5-labs.8a82073",
70
- "@dxos/util": "0.7.5-labs.8a82073",
71
- "@dxos/schema": "0.7.5-labs.8a82073"
69
+ "@dxos/async": "0.7.5-labs.c0e040f",
70
+ "@dxos/client": "0.7.5-labs.c0e040f",
71
+ "@dxos/context": "0.7.5-labs.c0e040f",
72
+ "@dxos/crypto": "0.7.5-labs.c0e040f",
73
+ "@dxos/echo-db": "0.7.5-labs.c0e040f",
74
+ "@dxos/echo-schema": "0.7.5-labs.c0e040f",
75
+ "@dxos/echo-protocol": "0.7.5-labs.c0e040f",
76
+ "@dxos/edge-client": "0.7.5-labs.c0e040f",
77
+ "@dxos/invariant": "0.7.5-labs.c0e040f",
78
+ "@dxos/keys": "0.7.5-labs.c0e040f",
79
+ "@dxos/live-object": "0.7.5-labs.c0e040f",
80
+ "@dxos/node-std": "0.7.5-labs.c0e040f",
81
+ "@dxos/log": "0.7.5-labs.c0e040f",
82
+ "@dxos/schema": "0.7.5-labs.c0e040f",
83
+ "@dxos/util": "0.7.5-labs.c0e040f",
84
+ "@dxos/protocols": "0.7.5-labs.c0e040f"
72
85
  },
73
86
  "devDependencies": {
74
87
  "@types/express": "^4.17.17",
75
88
  "@types/ws": "^7.4.0",
76
- "@dxos/agent": "0.7.5-labs.8a82073"
89
+ "@dxos/agent": "0.7.5-labs.c0e040f"
77
90
  },
78
91
  "publishConfig": {
79
92
  "access": "public"
@@ -0,0 +1,59 @@
1
+ //
2
+ // Copyright 2022 DXOS.org
3
+ //
4
+
5
+ // @ts-ignore
6
+ import wasmUrl from 'esbuild-wasm/esbuild.wasm?url';
7
+ import { 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
+ expect(result.bundle).to.exist;
24
+ expect(result.error).to.not.exist;
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
+ expect(result.bundle).to.exist;
37
+ expect(result.error).to.not.exist;
38
+ });
39
+
40
+ // TODO(dmaretskyi): Flaky on CI: https://cloud.nx.app/runs/Hjcifa8Ccq/task/plugin-script%3Atest
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
+ expect(result.bundle).to.exist;
50
+ expect(result.error).to.not.exist;
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
+ expect(result.bundle).to.not.exist;
57
+ expect(result.error).to.exist;
58
+ });
59
+ });
@@ -0,0 +1,264 @@
1
+ //
2
+ // Copyright 2023 DXOS.org
3
+ //
4
+
5
+ import { type BuildOptions } from 'esbuild';
6
+ import { build, initialize, type BuildResult, type Plugin } from 'esbuild-wasm';
7
+
8
+ import { subtleCrypto } from '@dxos/crypto';
9
+ import { invariant } from '@dxos/invariant';
10
+ import { log } from '@dxos/log';
11
+
12
+ export type Import = {
13
+ moduleUrl: string;
14
+ defaultImport: boolean;
15
+ namedImports: string[];
16
+ };
17
+
18
+ export type BundleOptions = {
19
+ /**
20
+ * Path to the source file on the local file system.
21
+ * If provided, the path will be used instead of the `source` code.
22
+ */
23
+ path?: string;
24
+
25
+ /**
26
+ * Source code to bundle.
27
+ * Required if `path` is not provided.
28
+ */
29
+ source?: string;
30
+ };
31
+
32
+ export type BundleResult = {
33
+ timestamp: number;
34
+ sourceHash?: Buffer;
35
+ imports?: Import[];
36
+ bundle?: string;
37
+ error?: any;
38
+ };
39
+
40
+ export type BundlerOptions = {
41
+ platform: BuildOptions['platform'];
42
+ sandboxedModules: string[];
43
+ remoteModules: Record<string, string>;
44
+ };
45
+
46
+ let initialized: Promise<void>;
47
+ export const initializeBundler = async (options: { wasmUrl: string }) => {
48
+ await (initialized ??= initialize({
49
+ wasmURL: options.wasmUrl,
50
+ }));
51
+ };
52
+
53
+ /**
54
+ * ESBuild bundler.
55
+ */
56
+ export class Bundler {
57
+ constructor(private readonly _options: BundlerOptions) {}
58
+
59
+ async bundle({ path, source }: BundleOptions): Promise<BundleResult> {
60
+ const { sandboxedModules: providedModules, ...options } = this._options;
61
+
62
+ const createResult = async (result?: Partial<BundleResult>) => {
63
+ return {
64
+ timestamp: Date.now(),
65
+ sourceHash: source ? Buffer.from(await subtleCrypto.digest('SHA-256', Buffer.from(source))) : undefined,
66
+ ...result,
67
+ };
68
+ };
69
+
70
+ if (this._options.platform === 'browser') {
71
+ invariant(initialized, 'Compiler not initialized.');
72
+ await initialized;
73
+ }
74
+
75
+ const imports = source ? analyzeSourceFileImports(source) : [];
76
+
77
+ // https://esbuild.github.io/api/#build
78
+ try {
79
+ const result = await build({
80
+ platform: options.platform,
81
+ conditions: ['workerd', 'browser'],
82
+ metafile: true,
83
+ write: false,
84
+ entryPoints: [path ?? 'memory:main.tsx'],
85
+ bundle: true,
86
+ format: 'esm',
87
+ plugins: [
88
+ {
89
+ name: 'memory',
90
+ setup: (build) => {
91
+ build.onResolve({ filter: /^\.\/runtime\.js$/ }, ({ path }) => {
92
+ return { path, external: true };
93
+ });
94
+
95
+ build.onResolve({ filter: /^dxos:functions$/ }, ({ path }) => {
96
+ return { path: './runtime.js', external: true };
97
+ });
98
+
99
+ build.onResolve({ filter: /^memory:/ }, ({ path }) => {
100
+ return { path: path.split(':')[1], namespace: 'memory' };
101
+ });
102
+
103
+ build.onLoad({ filter: /.*/, namespace: 'memory' }, ({ path }) => {
104
+ if (path === 'main.tsx') {
105
+ return {
106
+ contents: source,
107
+ loader: 'tsx',
108
+ };
109
+ }
110
+ });
111
+
112
+ for (const module of providedModules) {
113
+ build.onResolve({ filter: new RegExp(`^${module}$`) }, ({ path }) => {
114
+ return { path, namespace: 'injected-module' };
115
+ });
116
+ }
117
+
118
+ build.onLoad({ filter: /.*/, namespace: 'injected-module' }, ({ path }) => {
119
+ const namedImports = imports.find((entry) => entry.moduleIdentifier === path)?.namedImports ?? [];
120
+ return {
121
+ contents: `
122
+ const { ${namedImports.join(',')} } = window.__DXOS_SANDBOX_MODULES__[${JSON.stringify(path)}];
123
+ export { ${namedImports.join(',')} };
124
+ export default window.__DXOS_SANDBOX_MODULES__[${JSON.stringify(path)}].default;
125
+ `,
126
+ loader: 'tsx',
127
+ };
128
+ });
129
+ },
130
+ },
131
+ httpPlugin,
132
+ ],
133
+ });
134
+
135
+ log('compile complete', result.metafile);
136
+
137
+ return await createResult({
138
+ imports: this.analyzeImports(result),
139
+ bundle: result.outputFiles![0].text,
140
+ });
141
+ } catch (err) {
142
+ return await createResult({ error: err });
143
+ }
144
+ }
145
+
146
+ // TODO(dmaretskyi): In the future we can replace the compiler with SWC with plugins running in WASM.
147
+ analyzeImports(result: BuildResult): Import[] {
148
+ invariant(result.outputFiles);
149
+
150
+ // TODO(dmaretskyi): Support import aliases and wildcard imports.
151
+ const parsedImports = allMatches(IMPORT_REGEX, result.outputFiles[0].text);
152
+ return Object.values(result.metafile!.outputs)[0].imports.map((entry): Import => {
153
+ const namedImports: string[] = [];
154
+
155
+ const parsedImport = parsedImports.find((capture) => capture?.[4] === entry.path);
156
+ if (parsedImport?.[2]) {
157
+ NAMED_IMPORTS_REGEX.lastIndex = 0;
158
+ const namedImportsMatch = NAMED_IMPORTS_REGEX.exec(parsedImport[2]);
159
+ if (namedImportsMatch) {
160
+ namedImportsMatch[1].split(',').forEach((importName) => {
161
+ namedImports.push(importName.trim());
162
+ });
163
+ }
164
+ }
165
+
166
+ return {
167
+ moduleUrl: entry.path,
168
+ defaultImport: !!parsedImport?.[1],
169
+ namedImports,
170
+ };
171
+ });
172
+ }
173
+
174
+ analyzeSourceFileImports(code: string) {
175
+ // TODO(dmaretskyi): Support import aliases and wildcard imports.
176
+ const parsedImports = allMatches(IMPORT_REGEX, code);
177
+ return parsedImports.map((capture) => {
178
+ return {
179
+ defaultImportName: capture[1],
180
+ namedImports: capture[2]?.split(',').map((importName) => importName.trim()),
181
+ wildcardImportName: capture[3],
182
+ moduleIdentifier: capture[4],
183
+ quotes: capture[5],
184
+ };
185
+ });
186
+ }
187
+ }
188
+
189
+ // https://regex101.com/r/FEN5ks/1
190
+ // https://stackoverflow.com/a/73265022
191
+ // $1 = default import name (can be non-existent)
192
+ // $2 = destructured exports (can be non-existent)
193
+ // $3 = wildcard import name (can be non-existent)
194
+ // $4 = module identifier
195
+ // $5 = quotes used (either ' or ")
196
+ const IMPORT_REGEX =
197
+ /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;
198
+
199
+ const NAMED_IMPORTS_REGEX = /[ \n\t]*{((?:[ \n\t]*[^ \n\t"'{}]+[ \n\t]*,?)+)}[ \n\t]*/gm;
200
+
201
+ const allMatches = (regex: RegExp, str: string) => {
202
+ regex.lastIndex = 0;
203
+
204
+ let match;
205
+ const matches = [];
206
+ while ((match = regex.exec(str))) {
207
+ matches.push(match);
208
+ }
209
+
210
+ return matches;
211
+ };
212
+
213
+ type ParsedImport = {
214
+ defaultImportName?: string;
215
+ namedImports: string[];
216
+ wildcardImportName?: string;
217
+ moduleIdentifier: string;
218
+ quotes: string;
219
+ };
220
+
221
+ const analyzeSourceFileImports = (code: string): ParsedImport[] => {
222
+ // TODO(dmaretskyi): Support import aliases and wildcard imports.
223
+ const parsedImports = allMatches(IMPORT_REGEX, code);
224
+ return parsedImports.map((capture) => {
225
+ return {
226
+ defaultImportName: capture[1],
227
+ namedImports: capture[2]
228
+ ?.trim()
229
+ .slice(1, -1)
230
+ .split(',')
231
+ .map((importName) => importName.trim()),
232
+ wildcardImportName: capture[3],
233
+ moduleIdentifier: capture[4],
234
+ quotes: capture[5],
235
+ };
236
+ });
237
+ };
238
+
239
+ const httpPlugin: Plugin = {
240
+ name: 'http',
241
+ setup: (build) => {
242
+ // Intercept import paths starting with "http:" and "https:" so esbuild doesn't attempt to map them to a file system location.
243
+ // Tag them with the "http-url" namespace to associate them with this plugin.
244
+ build.onResolve({ filter: /^https?:\/\// }, (args) => ({
245
+ path: args.path,
246
+ namespace: 'http-url',
247
+ }));
248
+
249
+ // We also want to intercept all import paths inside downloaded files and resolve them against the original URL.
250
+ // All of these files will be in the "http-url" namespace.
251
+ // Make sure to keep the newly resolved URL in the "http-url" namespace so imports inside it will also be resolved as URLs recursively.
252
+ build.onResolve({ filter: /.*/, namespace: 'http-url' }, (args) => ({
253
+ path: new URL(args.path, args.importer).toString(),
254
+ namespace: 'http-url',
255
+ }));
256
+
257
+ // When a URL is loaded, we want to actually download the content from the internet.
258
+ // 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.
259
+ build.onLoad({ filter: /.*/, namespace: 'http-url' }, async (args) => {
260
+ const response = await fetch(args.path);
261
+ return { contents: await response.text(), loader: 'jsx' };
262
+ });
263
+ },
264
+ };
@@ -0,0 +1,5 @@
1
+ //
2
+ // Copyright 2023 DXOS.org
3
+ //
4
+
5
+ export * from './bundler';
package/src/handler.ts CHANGED
@@ -8,7 +8,7 @@ import { type Client, PublicKey } from '@dxos/client';
8
8
  import { type Space, type SpaceId } from '@dxos/client/echo';
9
9
  import type { CoreDatabase, ReactiveEchoObject } from '@dxos/echo-db';
10
10
  import { log } from '@dxos/log';
11
- import { nonNullable } from '@dxos/util';
11
+ import { isNonNullable } from '@dxos/util';
12
12
 
13
13
  // TODO(burdon): Model after http request. Ref Lambda/OpenFaaS.
14
14
  // https://docs.aws.amazon.com/lambda/latest/dg/typescript-handler.html
@@ -136,7 +136,9 @@ export const subscriptionHandler = <TMeta>(
136
136
 
137
137
  registerTypes(space, types);
138
138
  const objects = space
139
- ? data.objects?.map<ReactiveEchoObject<any> | undefined>((id) => space!.db.getObjectById(id)).filter(nonNullable)
139
+ ? data.objects
140
+ ?.map<ReactiveEchoObject<any> | undefined>((id) => space!.db.getObjectById(id))
141
+ .filter(isNonNullable)
140
142
  : [];
141
143
 
142
144
  if (!!data.spaceKey && !space) {