@dxos/edge-compute 0.0.0

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 (70) hide show
  1. package/LICENSE +105 -0
  2. package/dist/lib/neutral/bundler/index.mjs +213 -0
  3. package/dist/lib/neutral/bundler/index.mjs.map +7 -0
  4. package/dist/lib/neutral/chunk-J5LGTIGS.mjs +10 -0
  5. package/dist/lib/neutral/chunk-J5LGTIGS.mjs.map +7 -0
  6. package/dist/lib/neutral/chunk-RN6KVGN4.mjs +63 -0
  7. package/dist/lib/neutral/chunk-RN6KVGN4.mjs.map +7 -0
  8. package/dist/lib/neutral/index.mjs +343 -0
  9. package/dist/lib/neutral/index.mjs.map +7 -0
  10. package/dist/lib/neutral/meta.json +1 -0
  11. package/dist/lib/neutral/native/index.mjs +186 -0
  12. package/dist/lib/neutral/native/index.mjs.map +7 -0
  13. package/dist/lib/neutral/testing/index.mjs +41 -0
  14. package/dist/lib/neutral/testing/index.mjs.map +7 -0
  15. package/dist/types/src/EdgeOperationInvoker.d.ts +21 -0
  16. package/dist/types/src/EdgeOperationInvoker.d.ts.map +1 -0
  17. package/dist/types/src/EdgeProcessManager.d.ts +14 -0
  18. package/dist/types/src/EdgeProcessManager.d.ts.map +1 -0
  19. package/dist/types/src/EdgeTriggerManager.d.ts +14 -0
  20. package/dist/types/src/EdgeTriggerManager.d.ts.map +1 -0
  21. package/dist/types/src/FunctionsServiceClient.d.ts +65 -0
  22. package/dist/types/src/FunctionsServiceClient.d.ts.map +1 -0
  23. package/dist/types/src/bundler/bundler.d.ts +38 -0
  24. package/dist/types/src/bundler/bundler.d.ts.map +1 -0
  25. package/dist/types/src/bundler/bundler.test.d.ts +2 -0
  26. package/dist/types/src/bundler/bundler.test.d.ts.map +1 -0
  27. package/dist/types/src/bundler/index.d.ts +2 -0
  28. package/dist/types/src/bundler/index.d.ts.map +1 -0
  29. package/dist/types/src/bundler/plugins/embedded-vendored-packages.d.ts +3 -0
  30. package/dist/types/src/bundler/plugins/embedded-vendored-packages.d.ts.map +1 -0
  31. package/dist/types/src/bundler/plugins/http-plugin-esbuild.d.ts +34 -0
  32. package/dist/types/src/bundler/plugins/http-plugin-esbuild.d.ts.map +1 -0
  33. package/dist/types/src/bundler/plugins/index.d.ts +4 -0
  34. package/dist/types/src/bundler/plugins/index.d.ts.map +1 -0
  35. package/dist/types/src/bundler/plugins/r2-vendored-packages.d.ts +5 -0
  36. package/dist/types/src/bundler/plugins/r2-vendored-packages.d.ts.map +1 -0
  37. package/dist/types/src/edge-client.d.ts +39 -0
  38. package/dist/types/src/edge-client.d.ts.map +1 -0
  39. package/dist/types/src/index.d.ts +6 -0
  40. package/dist/types/src/index.d.ts.map +1 -0
  41. package/dist/types/src/native/bundler.d.ts +15 -0
  42. package/dist/types/src/native/bundler.d.ts.map +1 -0
  43. package/dist/types/src/native/index.d.ts +2 -0
  44. package/dist/types/src/native/index.d.ts.map +1 -0
  45. package/dist/types/src/testing/index.d.ts +2 -0
  46. package/dist/types/src/testing/index.d.ts.map +1 -0
  47. package/dist/types/src/testing/logger.d.ts +4 -0
  48. package/dist/types/src/testing/logger.d.ts.map +1 -0
  49. package/dist/types/src/testing/services.d.ts +53 -0
  50. package/dist/types/src/testing/services.d.ts.map +1 -0
  51. package/dist/types/tsconfig.tsbuildinfo +1 -0
  52. package/package.json +95 -0
  53. package/src/EdgeOperationInvoker.ts +65 -0
  54. package/src/EdgeProcessManager.ts +47 -0
  55. package/src/EdgeTriggerManager.ts +70 -0
  56. package/src/FunctionsServiceClient.ts +189 -0
  57. package/src/bundler/bundler.test.ts +108 -0
  58. package/src/bundler/bundler.ts +232 -0
  59. package/src/bundler/index.ts +5 -0
  60. package/src/bundler/plugins/embedded-vendored-packages.ts +39 -0
  61. package/src/bundler/plugins/http-plugin-esbuild.ts +77 -0
  62. package/src/bundler/plugins/index.ts +7 -0
  63. package/src/bundler/plugins/r2-vendored-packages.ts +35 -0
  64. package/src/edge-client.ts +156 -0
  65. package/src/index.ts +9 -0
  66. package/src/native/bundler.ts +231 -0
  67. package/src/native/index.ts +5 -0
  68. package/src/testing/index.ts +5 -0
  69. package/src/testing/logger.ts +14 -0
  70. package/src/testing/services.ts +95 -0
package/LICENSE ADDED
@@ -0,0 +1,105 @@
1
+ # Functional Source License, Version 1.1, ALv2 Future License
2
+
3
+ ## Abbreviation
4
+
5
+ FSL-1.1-Apache-2.0
6
+
7
+ ## Notice
8
+
9
+ Copyright 2026 DXOS
10
+
11
+ ## Terms and Conditions
12
+
13
+ ### Licensor ("We")
14
+
15
+ The party offering the Software under these Terms and Conditions.
16
+
17
+ ### The Software
18
+
19
+ The "Software" is each version of the software that we make available under
20
+ these Terms and Conditions, as indicated by our inclusion of these Terms and
21
+ Conditions with the Software.
22
+
23
+ ### License Grant
24
+
25
+ Subject to your compliance with this License Grant and the Patents,
26
+ Redistribution and Trademark clauses below, we hereby grant you the right to
27
+ use, copy, modify, create derivative works, publicly perform, publicly display
28
+ and redistribute the Software for any Permitted Purpose identified below.
29
+
30
+ ### Permitted Purpose
31
+
32
+ A Permitted Purpose is any purpose other than a Competing Use. A Competing Use
33
+ means making the Software available to others in a commercial product or
34
+ service that:
35
+
36
+ 1. substitutes for the Software;
37
+
38
+ 2. substitutes for any other product or service we offer using the Software
39
+ that exists as of the date we make the Software available; or
40
+
41
+ 3. offers the same or substantially similar functionality as the Software.
42
+
43
+ Permitted Purposes specifically include using the Software:
44
+
45
+ 1. for your internal use and access;
46
+
47
+ 2. for non-commercial education;
48
+
49
+ 3. for non-commercial research; and
50
+
51
+ 4. in connection with professional services that you provide to a licensee
52
+ using the Software in accordance with these Terms and Conditions.
53
+
54
+ ### Patents
55
+
56
+ To the extent your use for a Permitted Purpose would necessarily infringe our
57
+ patents, the license grant above includes a license under our patents. If you
58
+ make a claim against any party that the Software infringes or contributes to
59
+ the infringement of any patent, then your patent license to the Software ends
60
+ immediately.
61
+
62
+ ### Redistribution
63
+
64
+ The Terms and Conditions apply to all copies, modifications and derivatives of
65
+ the Software.
66
+
67
+ If you redistribute any copies, modifications or derivatives of the Software,
68
+ you must include a copy of or a link to these Terms and Conditions and not
69
+ remove any copyright notices provided in or with the Software.
70
+
71
+ ### Disclaimer
72
+
73
+ THE SOFTWARE IS PROVIDED "AS IS" AND WITHOUT WARRANTIES OF ANY KIND, EXPRESS OR
74
+ IMPLIED, INCLUDING WITHOUT LIMITATION WARRANTIES OF FITNESS FOR A PARTICULAR
75
+ PURPOSE, MERCHANTABILITY, TITLE OR NON-INFRINGEMENT.
76
+
77
+ IN NO EVENT WILL WE HAVE ANY LIABILITY TO YOU ARISING OUT OF OR RELATED TO THE
78
+ SOFTWARE, INCLUDING INDIRECT, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES,
79
+ EVEN IF WE HAVE BEEN INFORMED OF THEIR POSSIBILITY IN ADVANCE.
80
+
81
+ ### Trademarks
82
+
83
+ Except for displaying the License Details and identifying us as the origin of
84
+ the Software, you have no right under these Terms and Conditions to use our
85
+ trademarks, trade names, service marks or product names.
86
+
87
+ ## Grant of Future License
88
+
89
+ We hereby irrevocably grant you an additional license to use the Software under
90
+ the Apache License, Version 2.0 that is effective on the second anniversary of
91
+ the date we make the Software available. On or after that date, you may use the
92
+ Software under the Apache License, Version 2.0, in which case the following
93
+ will apply:
94
+
95
+ Licensed under the Apache License, Version 2.0 (the "License"); you may not use
96
+ this file except in compliance with the License.
97
+
98
+ You may obtain a copy of the License at
99
+
100
+ http://www.apache.org/licenses/LICENSE-2.0
101
+
102
+ Unless required by applicable law or agreed to in writing, software distributed
103
+ under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
104
+ CONDITIONS OF ANY KIND, either express or implied. See the License for the
105
+ specific language governing permissions and limitations under the License.
@@ -0,0 +1,213 @@
1
+ import {
2
+ httpPlugin
3
+ } from "../chunk-RN6KVGN4.mjs";
4
+ import "../chunk-J5LGTIGS.mjs";
5
+
6
+ // src/bundler/bundler.ts
7
+ import { build, initialize } from "esbuild-wasm";
8
+ import { subtleCrypto } from "@dxos/crypto";
9
+ import { invariant } from "@dxos/invariant";
10
+ import { isNode, trim } from "@dxos/util";
11
+
12
+ // src/bundler/plugins/r2-vendored-packages.ts
13
+ var DEFAULT_SCRIPT_PACKAGES_BUCKET = "https://pub-5745ae82e450484aa28f75fc6a175935.r2.dev/dev/";
14
+ var PluginR2VendoredPackages = ({ url = DEFAULT_SCRIPT_PACKAGES_BUCKET } = {}) => ({
15
+ name: "r2-vendored-packages",
16
+ setup: (build2) => {
17
+ build2.onResolve({
18
+ filter: /^[^./]/
19
+ }, (args) => {
20
+ if (args.kind === "entry-point") {
21
+ return;
22
+ }
23
+ return {
24
+ // NOTE: Use .js extension for tsdown
25
+ path: new URL(`${args.path}.js`, url).href,
26
+ namespace: "http-url"
27
+ };
28
+ });
29
+ }
30
+ });
31
+
32
+ // src/bundler/bundler.ts
33
+ var __dxlog_file = "/Users/dmaretskyi/Code/dxos/dxos/packages/core/compute/edge-compute/src/bundler/bundler.ts";
34
+ var initialized;
35
+ var initializeBundler = async (options) => {
36
+ await (initialized ??= initialize({
37
+ wasmURL: options.wasmUrl
38
+ }));
39
+ };
40
+ var bundleFunction = async ({ source }) => {
41
+ const sourceHash = Buffer.from(await subtleCrypto.digest("SHA-256", Buffer.from(source)));
42
+ if (!isNode()) {
43
+ invariant(initialized, "Compiler not initialized.", { "~LogMeta": "~LogMeta", F: __dxlog_file, L: 28, S: void 0, A: ["initialized", "'Compiler not initialized.'"] });
44
+ await initialized;
45
+ }
46
+ const outdir = "/tmp/bundle";
47
+ try {
48
+ const result = await build({
49
+ platform: "browser",
50
+ conditions: [
51
+ "workerd",
52
+ "worker",
53
+ "browser"
54
+ ],
55
+ metafile: true,
56
+ write: false,
57
+ entryPoints: {
58
+ // Keep output name stable as `index.js` to preserve API.
59
+ index: "dxos:entrypoint"
60
+ },
61
+ outdir,
62
+ bundle: true,
63
+ // NOTE: Splitting causes an error in Cloudflare-Workers:
64
+ // Disallowed operation called within global scope.
65
+ // Asynchronous I/O (ex: fetch() or connect()), setting a timeout, and generating random values are not allowed within global scope.
66
+ // To fix this error, perform this operation within a handler. https://developers.cloudflare.com/workers/runtime-apis/handlers/
67
+ //
68
+ // Likely, workerd is treating asynchronously-loaded modules as if they were executing in global scope.
69
+ // splitting: true,
70
+ format: "esm",
71
+ target: "esnext",
72
+ supported: {
73
+ "class-private-accessor": true,
74
+ "class-private-brand-check": true,
75
+ "class-private-field": true,
76
+ "class-private-method": true,
77
+ "class-private-static-accessor": true,
78
+ "class-private-static-field": true,
79
+ "class-private-static-method": true
80
+ },
81
+ external: [
82
+ "cloudflare:workers"
83
+ ],
84
+ alias: {
85
+ "node:path": "path"
86
+ },
87
+ plugins: [
88
+ httpPlugin,
89
+ {
90
+ // Provide a virtual entrypoint that wraps the user handler similar to the native bundler.
91
+ name: "entrypoint",
92
+ setup: (build2) => {
93
+ build2.onResolve({
94
+ filter: /^dxos:entrypoint$/
95
+ }, () => ({
96
+ path: "dxos:entrypoint",
97
+ namespace: "dxos:entrypoint"
98
+ }));
99
+ build2.onLoad({
100
+ filter: /^dxos:entrypoint$/,
101
+ namespace: "dxos:entrypoint"
102
+ }, () => {
103
+ return {
104
+ contents: trim`
105
+ export default {
106
+ fetch: async (...args) => {
107
+ const { wrapFunctionHandler } = await import('@dxos/compute-runtime');
108
+ const { wrapHandlerForCloudflare } = await import('@dxos/functions-runtime-cloudflare');
109
+ const { default: handler } = await import('memory:source.tsx');
110
+
111
+ //
112
+ // Wrapper to make the function cloudflare-compatible.
113
+ //
114
+ return wrapHandlerForCloudflare(wrapFunctionHandler(handler))(...args);
115
+ },
116
+ };
117
+ `,
118
+ loader: "ts"
119
+ };
120
+ });
121
+ }
122
+ },
123
+ {
124
+ name: "memory",
125
+ setup: (build2) => {
126
+ build2.onResolve({
127
+ filter: /^memory:/
128
+ }, ({ path }) => {
129
+ return {
130
+ path: path.split(":")[1],
131
+ namespace: "memory"
132
+ };
133
+ });
134
+ build2.onLoad({
135
+ filter: /.*/,
136
+ namespace: "memory"
137
+ }, ({ path }) => {
138
+ switch (path) {
139
+ case "source.tsx":
140
+ return {
141
+ contents: source,
142
+ loader: "tsx"
143
+ };
144
+ case "empty":
145
+ return {
146
+ contents: "",
147
+ loader: "js"
148
+ };
149
+ }
150
+ });
151
+ }
152
+ },
153
+ // PluginESMSh(),
154
+ PluginR2VendoredPackages()
155
+ ]
156
+ });
157
+ const entryPoint = "index.js";
158
+ return {
159
+ timestamp: Date.now(),
160
+ sourceHash,
161
+ imports: analyzeImports(result),
162
+ entryPoint,
163
+ assets: result.outputFiles.reduce((acc, file) => {
164
+ acc[file.path.replace(outdir + "/", "")] = file.contents;
165
+ return acc;
166
+ }, {})
167
+ };
168
+ } catch (err) {
169
+ return {
170
+ timestamp: Date.now(),
171
+ sourceHash,
172
+ error: err
173
+ };
174
+ }
175
+ };
176
+ var analyzeImports = (result) => {
177
+ invariant(result.outputFiles, void 0, { "~LogMeta": "~LogMeta", F: __dxlog_file, L: 166, S: void 0, A: ["result.outputFiles", ""] });
178
+ const parsedImports = allMatches(IMPORT_REGEX, result.outputFiles[0].text);
179
+ return Object.values(result.metafile.outputs)[0].imports.map((entry) => {
180
+ const namedImports = [];
181
+ const parsedImport = parsedImports.find((capture) => capture?.[4] === entry.path);
182
+ if (parsedImport?.[2]) {
183
+ NAMED_IMPORTS_REGEX.lastIndex = 0;
184
+ const namedImportsMatch = NAMED_IMPORTS_REGEX.exec(parsedImport[2]);
185
+ if (namedImportsMatch) {
186
+ namedImportsMatch[1].split(",").forEach((importName) => {
187
+ namedImports.push(importName.trim());
188
+ });
189
+ }
190
+ }
191
+ return {
192
+ moduleUrl: entry.path,
193
+ defaultImport: !!parsedImport?.[1],
194
+ namedImports
195
+ };
196
+ });
197
+ };
198
+ var IMPORT_REGEX = /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;
199
+ var NAMED_IMPORTS_REGEX = /[ \n\t]*{((?:[ \n\t]*[^ \n\t"'{}]+[ \n\t]*,?)+)}[ \n\t]*/gm;
200
+ var allMatches = (regex, str) => {
201
+ let match;
202
+ const matches = [];
203
+ regex.lastIndex = 0;
204
+ while (match = regex.exec(str)) {
205
+ matches.push(match);
206
+ }
207
+ return matches;
208
+ };
209
+ export {
210
+ bundleFunction,
211
+ initializeBundler
212
+ };
213
+ //# sourceMappingURL=index.mjs.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../../../src/bundler/bundler.ts", "../../../../src/bundler/plugins/r2-vendored-packages.ts"],
4
+ "sourcesContent": ["//\n// Copyright 2023 DXOS.org\n//\n\nimport { type BuildResult, type Plugin, type PluginBuild, build, initialize } from 'esbuild-wasm';\n\nimport { subtleCrypto } from '@dxos/crypto';\nimport { invariant } from '@dxos/invariant';\nimport { isNode, trim } from '@dxos/util';\n\nimport { httpPlugin } from './plugins/http-plugin-esbuild';\nimport { PluginR2VendoredPackages } from './plugins/r2-vendored-packages';\n\nexport type Import = {\n moduleUrl: string;\n defaultImport: boolean;\n namedImports: string[];\n};\n\nexport type BundleOptions = {\n /**\n * Source code to bundle.\n */\n source: string;\n};\n\nexport type BundleResult =\n | {\n timestamp: number;\n sourceHash: Buffer;\n error: unknown;\n }\n | {\n timestamp: number;\n sourceHash: Buffer;\n imports: Import[];\n entryPoint: string;\n assets: Record<string, Uint8Array>;\n };\n\nlet initialized: Promise<void>;\n/**\n * Initializes the bundler.\n * Must be called before using the bundler in browser.\n */\nexport const initializeBundler = async (options: { wasmUrl: string }) => {\n await (initialized ??= initialize({\n wasmURL: options.wasmUrl,\n }));\n};\n\n/**\n * ESBuild bundler implemented as a function (parity with native bundler API style).\n * Bundles source code directly, does not really on filesystem or Node APIs.\n *\n * This is browser friendly version of the bundler, but it could also be used in Node environment.\n * `initializeBundler` should be called before using it in browser, not required in Node.\n */\nexport const bundleFunction = async ({ source }: BundleOptions): Promise<BundleResult> => {\n const sourceHash = Buffer.from(await subtleCrypto.digest('SHA-256', Buffer.from(source)));\n\n if (!isNode()) {\n invariant(initialized, 'Compiler not initialized.');\n await initialized;\n }\n const outdir = '/tmp/bundle';\n try {\n const result = await build({\n platform: 'browser',\n conditions: ['workerd', 'worker', 'browser'],\n metafile: true,\n write: false,\n entryPoints: {\n // Keep output name stable as `index.js` to preserve API.\n index: 'dxos:entrypoint',\n },\n outdir,\n bundle: true,\n\n // NOTE: Splitting causes an error in Cloudflare-Workers:\n // Disallowed operation called within global scope.\n // Asynchronous I/O (ex: fetch() or connect()), setting a timeout, and generating random values are not allowed within global scope.\n // To fix this error, perform this operation within a handler. https://developers.cloudflare.com/workers/runtime-apis/handlers/\n //\n // Likely, workerd is treating asynchronously-loaded modules as if they were executing in global scope.\n // splitting: true,\n format: 'esm',\n target: 'esnext',\n supported: {\n 'class-private-accessor': true,\n 'class-private-brand-check': true,\n 'class-private-field': true,\n 'class-private-method': true,\n 'class-private-static-accessor': true,\n 'class-private-static-field': true,\n 'class-private-static-method': true,\n },\n external: ['cloudflare:workers'],\n alias: {\n 'node:path': 'path',\n },\n plugins: [\n httpPlugin as any as Plugin,\n {\n // Provide a virtual entrypoint that wraps the user handler similar to the native bundler.\n name: 'entrypoint',\n setup: (build: PluginBuild) => {\n build.onResolve({ filter: /^dxos:entrypoint$/ }, () => ({\n path: 'dxos:entrypoint',\n namespace: 'dxos:entrypoint',\n }));\n // TODO(dmaretskyi): Move into memory plugin\n build.onLoad({ filter: /^dxos:entrypoint$/, namespace: 'dxos:entrypoint' }, () => {\n return {\n contents: trim`\n export default {\n fetch: async (...args) => {\n const { wrapFunctionHandler } = await import('@dxos/compute-runtime');\n const { wrapHandlerForCloudflare } = await import('@dxos/functions-runtime-cloudflare');\n const { default: handler } = await import('memory:source.tsx');\n\n //\n // Wrapper to make the function cloudflare-compatible.\n //\n return wrapHandlerForCloudflare(wrapFunctionHandler(handler))(...args);\n },\n };\n `,\n loader: 'ts',\n } as const;\n });\n },\n },\n {\n name: 'memory',\n setup: (build) => {\n build.onResolve({ filter: /^memory:/ }, ({ path }) => {\n return { path: path.split(':')[1], namespace: 'memory' };\n });\n\n build.onLoad({ filter: /.*/, namespace: 'memory' }, ({ path }) => {\n switch (path) {\n case 'source.tsx':\n return {\n contents: source,\n loader: 'tsx',\n };\n case 'empty':\n return {\n contents: '',\n loader: 'js',\n };\n }\n });\n },\n },\n // PluginESMSh(),\n PluginR2VendoredPackages(),\n ],\n });\n\n // log.info('Bundling complete', result.metafile);\n // log.info('Output files', { files: result.outputFiles });\n\n const entryPoint = 'index.js';\n return {\n timestamp: Date.now(),\n sourceHash,\n imports: analyzeImports(result),\n entryPoint,\n assets: result.outputFiles.reduce(\n (acc, file) => {\n acc[file.path.replace(outdir + '/', '')] = file.contents;\n return acc;\n },\n {} as Record<string, Uint8Array>,\n ),\n };\n } catch (err) {\n return { timestamp: Date.now(), sourceHash, error: err };\n }\n};\n\n// TODO(dmaretskyi): In the future we can replace the compiler with SWC with plugins running in WASM.\nconst 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 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// 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 let match;\n const matches = [];\n regex.lastIndex = 0;\n while ((match = regex.exec(str))) {\n matches.push(match);\n }\n\n return matches;\n};\n", "//\n// Copyright 2025 DXOS.org\n//\n\nimport type { Plugin } from 'esbuild-wasm';\n\n/*\n\nscript-vendored-packages bucket on R2\n\nhttps://dash.cloudflare.com/950816f3f59b079880a1ae33fb0ec320/r2/default/buckets/script-vendored-packages/settings\n\n'https://pub-5745ae82e450484aa28f75fc6a175935.r2.dev/dev' -- last portion is the env\n\n \n*/\n\nconst DEFAULT_SCRIPT_PACKAGES_BUCKET = 'https://pub-5745ae82e450484aa28f75fc6a175935.r2.dev/dev/';\n\nexport const PluginR2VendoredPackages = ({ url = DEFAULT_SCRIPT_PACKAGES_BUCKET }: { url?: string } = {}): Plugin => ({\n name: 'r2-vendored-packages',\n setup: (build) => {\n build.onResolve({ filter: /^[^./]/ }, (args) => {\n if (args.kind === 'entry-point') {\n return;\n }\n\n return {\n // NOTE: Use .js extension for tsdown\n path: new URL(`${args.path}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UAAID,eAAiB,CAAA;UACnBE,eAAAA,cAA6B,KAAG,CAAA,YAAA,UAAA,CAAA,MAAA,MAAA,IAAA;QAChC,eAAMC,CAAAA,GAAAA;AACN,0BAAIA,YAAmB;YACrBA,oBAAqBC,oBAAoBC,KAAAA,aAAAA,CAAAA,CAAAA;6BAC1BC;AACf,0BAAA,CAAA,EAAA,MAAA,GAAA,EAAA,QAAA,CAAA,eAAA;AACF,uBAAA,KAAA,WAAA,KAAA,CAAA;QACF,CAAA;MAEA;;WAEEC;MACAR,WAAAA,MAAAA;MACF,eAAA,CAAA,CAAA,eAAA,CAAA;MACF;IACF;EAEA,CAAA;AACA;AAWA,IAAMF,eAAcW;IAClB,sBAAIC;IACJ,aAAMC,CAAU,OAAE,QAAA;AAClBF,MAAAA;AACA,QAAQC,UAAQD,CAAAA;QACdE,YAAaD;AACf,SAAA,QAAA,MAAA,KAAA,GAAA,GAAA;AAEA,YAAOC,KAAAA,KAAAA;EACT;;;",
6
+ "names": ["build", "initialize", "subtleCrypto", "invariant", "isNode", "trim", "DEFAULT_SCRIPT_PACKAGES_BUCKET", "PluginR2VendoredPackages", "url", "name", "setup", "build", "onResolve", "filter", "args", "kind", "path", "URL", "href", "namespace", "initialized", "wasmURL", "options", "isNode", "invariant", "outdir", "result", "conditions", "metafile", "write", "entryPoints", "bundle", "supported", "external", "alias", "plugins", "build", "filter", "path", "namespace", "onLoad", "loader", "PluginR2VendoredPackages", "timestamp", "Date", "sourceHash", "imports", "analyzeImports", "entryPoint", "assets", "outputFiles", "reduce", "acc", "err", "error", "parsedImports", "allMatches", "IMPORT_REGEX", "namedImports", "parsedImport", "capture", "NAMED_IMPORTS_REGEX", "namedImportsMatch", "split", "importName", "push", "defaultImport", "regex", "match", "matches"]
7
+ }
@@ -0,0 +1,10 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __export = (target, all) => {
3
+ for (var name in all)
4
+ __defProp(target, name, { get: all[name], enumerable: true });
5
+ };
6
+
7
+ export {
8
+ __export
9
+ };
10
+ //# sourceMappingURL=chunk-J5LGTIGS.mjs.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": [],
4
+ "sourcesContent": [],
5
+ "mappings": "",
6
+ "names": []
7
+ }
@@ -0,0 +1,63 @@
1
+ // src/bundler/plugins/http-plugin-esbuild.ts
2
+ import * as FetchHttpClient from "@effect/platform/FetchHttpClient";
3
+ import * as HttpClient from "@effect/platform/HttpClient";
4
+ import * as Duration from "effect/Duration";
5
+ import * as Effect from "effect/Effect";
6
+ import * as Function from "effect/Function";
7
+ import * as Schedule from "effect/Schedule";
8
+ import { EffectEx } from "@dxos/effect";
9
+ import { BaseError } from "@dxos/errors";
10
+ var MAX_RETRIES = 5;
11
+ var INITIAL_DELAY = 1e3;
12
+ var HttpPluginError = class extends BaseError.extend("HttpPluginError") {
13
+ };
14
+ var LOADERS = {
15
+ js: "js",
16
+ jsx: "jsx",
17
+ ts: "ts",
18
+ tsx: "tsx",
19
+ wasm: "copy"
20
+ };
21
+ var httpPlugin = {
22
+ name: "http",
23
+ setup: (build) => {
24
+ build.onResolve({
25
+ filter: /^https?:\/\//
26
+ }, (args) => ({
27
+ path: args.path,
28
+ namespace: "http-url"
29
+ }));
30
+ build.onResolve({
31
+ filter: /.*/,
32
+ namespace: "http-url"
33
+ }, (args) => ({
34
+ path: new URL(args.path, args.importer).toString(),
35
+ namespace: "http-url"
36
+ }));
37
+ build.onLoad({
38
+ filter: /.*/,
39
+ namespace: "http-url"
40
+ }, async (args) => {
41
+ return Effect.gen(function* () {
42
+ const response = yield* HttpClient.get(args.path);
43
+ if (response.status !== 200) {
44
+ yield* Effect.fail(new HttpPluginError({
45
+ message: `failed to fetch ${args.path}, status: ${response.status}`
46
+ }));
47
+ }
48
+ const contents = new Uint8Array(yield* response.arrayBuffer);
49
+ const extension = new URL(args.path).pathname.split(".").pop() || "";
50
+ const loader = LOADERS[extension.toLowerCase()] ?? "jsx";
51
+ return {
52
+ contents,
53
+ loader
54
+ };
55
+ }).pipe(Effect.retry(Function.pipe(Schedule.exponential(Duration.millis(INITIAL_DELAY)), Schedule.jittered, Schedule.intersect(Schedule.recurs(MAX_RETRIES - 1)))), Effect.provide(FetchHttpClient.layer), EffectEx.runAndForwardErrors);
56
+ });
57
+ }
58
+ };
59
+
60
+ export {
61
+ httpPlugin
62
+ };
63
+ //# sourceMappingURL=chunk-RN6KVGN4.mjs.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../../src/bundler/plugins/http-plugin-esbuild.ts"],
4
+ "sourcesContent": ["//\n// Copyright 2025 DXOS.org\n//\n\nimport * as FetchHttpClient from '@effect/platform/FetchHttpClient';\nimport * as HttpClient from '@effect/platform/HttpClient';\nimport * as Duration from 'effect/Duration';\nimport * as Effect from 'effect/Effect';\nimport * as Function from 'effect/Function';\nimport * as Schedule from 'effect/Schedule';\nimport { type Loader, type Plugin } from 'esbuild';\n\nimport { EffectEx } from '@dxos/effect';\nimport { BaseError } from '@dxos/errors';\n\nconst MAX_RETRIES = 5;\nconst INITIAL_DELAY = 1_000;\n\nexport class HttpPluginError extends BaseError.extend('HttpPluginError') {}\n\nconst LOADERS: Record<string, Loader> = {\n js: 'js',\n jsx: 'jsx',\n ts: 'ts',\n tsx: 'tsx',\n wasm: 'copy',\n} as const;\n\nexport const 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 return Effect.gen(function* () {\n const response = yield* HttpClient.get(args.path);\n if (response.status !== 200) {\n yield* Effect.fail(\n new HttpPluginError({\n message: `failed to fetch ${args.path}, status: ${response.status}`,\n }),\n );\n }\n\n const contents = new Uint8Array(yield* response.arrayBuffer);\n const extension = new URL(args.path).pathname.split('.').pop() || '';\n const loader = LOADERS[extension.toLowerCase()] ?? 'jsx';\n return { contents, loader };\n }).pipe(\n Effect.retry(\n Function.pipe(\n Schedule.exponential(Duration.millis(INITIAL_DELAY)),\n Schedule.jittered,\n Schedule.intersect(Schedule.recurs(MAX_RETRIES - 1)),\n ),\n ),\n Effect.provide(FetchHttpClient.layer),\n EffectEx.runAndForwardErrors,\n );\n });\n },\n};\n"],
5
+ "mappings": ";AAIA,YAAYA,qBAAqB;AACjC,YAAYC,gBAAgB;AAC5B,YAAYC,cAAc;AAC1B,YAAYC,YAAY;AACxB,YAAYC,cAAc;AAC1B,YAAYC,cAAc;AAG1B,SAASC,gBAAgB;AACzB,SAASC,iBAAiB;AAE1B,IAAMC,cAAc;AACpB,IAAMC,gBAAgB;AAEf,IAAMC,kBAAN,cAA8BH,UAAUI,OAAO,iBAAA,EAAA;AAAoB;AAE1E,IAAMC,UAAkC;EACtCC,IAAI;EACJC,KAAK;EACLC,IAAI;EACJC,KAAK;EACLC,MAAM;AACR;AAEO,IAAMC,aAAqB;EAChCC,MAAM;EACNC,OAAO,CAACC,UAAAA;AAGNA,UAAMC,UAAU;MAAEC,QAAQ;IAAe,GAAG,CAACC,UAAU;MACrDC,MAAMD,KAAKC;MACXC,WAAW;IACb,EAAA;AAKAL,UAAMC,UAAU;MAAEC,QAAQ;MAAMG,WAAW;IAAW,GAAG,CAACF,UAAU;MAClEC,MAAM,IAAIE,IAAIH,KAAKC,MAAMD,KAAKI,QAAQ,EAAEC,SAAQ;MAChDH,WAAW;IACb,EAAA;AAIAL,UAAMS,OAAO;MAAEP,QAAQ;MAAMG,WAAW;IAAW,GAAG,OAAOF,SAAAA;AAC3D,aAAcO,WAAI,aAAA;AAChB,cAAMC,WAAW,OAAkBC,eAAIT,KAAKC,IAAI;AAChD,YAAIO,SAASE,WAAW,KAAK;AAC3B,iBAAcC,YACZ,IAAIzB,gBAAgB;YAClB0B,SAAS,mBAAmBZ,KAAKC,IAAI,aAAaO,SAASE,MAAM;UACnE,CAAA,CAAA;QAEJ;AAEA,cAAMG,WAAW,IAAIC,WAAW,OAAON,SAASO,WAAU;AAC1D,cAAMC,YAAY,IAAIb,IAAIH,KAAKC,IAAI,EAAEgB,SAASC,MAAM,GAAA,EAAKC,IAAG,KAAM;AAClE,cAAMC,SAAShC,QAAQ4B,UAAUK,YAAW,CAAA,KAAO;AACnD,eAAO;UAAER;UAAUO;QAAO;MAC5B,CAAA,EAAGE,KACMC,aACID,cACEE,qBAAqBC,gBAAOxC,aAAAA,CAAAA,GAC5ByC,mBACAC,mBAAmBC,gBAAO5C,cAAc,CAAA,CAAA,CAAA,CAAA,GAG9C6C,eAAwBC,qBAAK,GACpChD,SAASiD,mBAAmB;IAEhC,CAAA;EACF;AACF;",
6
+ "names": ["FetchHttpClient", "HttpClient", "Duration", "Effect", "Function", "Schedule", "EffectEx", "BaseError", "MAX_RETRIES", "INITIAL_DELAY", "HttpPluginError", "extend", "LOADERS", "js", "jsx", "ts", "tsx", "wasm", "httpPlugin", "name", "setup", "build", "onResolve", "filter", "args", "path", "namespace", "URL", "importer", "toString", "onLoad", "gen", "response", "get", "status", "fail", "message", "contents", "Uint8Array", "arrayBuffer", "extension", "pathname", "split", "pop", "loader", "toLowerCase", "pipe", "retry", "exponential", "millis", "jittered", "intersect", "recurs", "provide", "layer", "runAndForwardErrors"]
7
+ }