computesdk 1.0.0 → 1.0.2

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/index.js CHANGED
@@ -1 +1,534 @@
1
- var n=(h,...e)=>{window?.localStorage?.getItem("DEBUG")==="true"&&console.log("foo",h,...e)},p=class{constructor(e,t){this.ws=e,this.terminalId=t,this.onDataCallbacks=new Set,this.onExitCallbacks=new Set}onData(e){return this.onDataCallbacks.add(e),()=>this.onDataCallbacks.delete(e)}onExit(e){return this.onExitCallbacks.add(e),()=>this.onExitCallbacks.delete(e)}write(e){this.ws.send(JSON.stringify({type:"terminal:input",data:{terminalId:this.terminalId,input:e}}))}resize(e,t){this.ws.send(JSON.stringify({type:"terminal:resize",data:{terminalId:this.terminalId,cols:e,rows:t}}))}_handleData(e){this.onDataCallbacks.forEach(t=>t(e))}_handleExit(e,t){this.onExitCallbacks.forEach(s=>s({exitCode:e,signal:t}))}},w=class{constructor(e,t,s={}){this.ws=e,this.path=t,this.options=s,this.onChangeCallbacks=new Set}onChanged(e){return this.onChangeCallbacks.add(e),()=>this.onChangeCallbacks.delete(e)}_handleChange(e){this.onChangeCallbacks.forEach(t=>t(e))}stop(){this.ws.send(JSON.stringify({type:"file:watch:stop",data:{path:this.path}}))}},m=class{constructor(e,t){this.computeId=e,this.podUrl=t,this.ws=null,this.terminals=new Map,this.fileWatchers=new Map,this.onConnectedCallbacks=new Set,this.onErrorCallbacks=new Set,this.portOpenedCallbacks=new Set,this.serverReadyCallbacks=new Set,this.terminalId=0,this._connect(),typeof window<"u"&&(this._onBeforeUnload=s=>{try{this.ws&&this.ws.readyState===WebSocket.OPEN&&this.ws.close(),this.computeId&&new d().delete(this.computeId),this.ws=null,this.computeId=null}catch(l){console.error("Error during window unload cleanup:",l)}s.preventDefault(),s.returnValue=""},window.addEventListener("beforeunload",this._onBeforeUnload))}async teardown(){try{typeof window<"u"&&this._onBeforeUnload&&(window.removeEventListener("beforeunload",this._onBeforeUnload),this._onBeforeUnload=null),this.ws&&this.ws.readyState===WebSocket.OPEN&&this.ws.close(),this.computeId&&await new d().delete(this.computeId),this.ws=null,this.computeId=null}catch(e){throw console.error("Error during teardown:",e),e}}_connect(){let e=new URL(this.podUrl),t=e.protocol==="https:"?"wss:":"ws:",s=e.pathname==="/"?"/ws":`${e.pathname}/ws`,l=`${t}//${e.host}${s}`;console.log("\u{1F50C} Attempting WebSocket connection to:",l),console.log("Original pod URL was:",this.podUrl),n("\u{1F50C} Attempting WebSocket connection to:",l);let o=0,i=3,c=()=>{console.log(`Connecting WebSocket (attempt ${o+1}/${i+1})...`),this.ws=new WebSocket(l),this.ws.onopen=()=>{console.log("\u2705 WebSocket connection established"),n("\u2705 WebSocket connection established"),o=0,this.onConnectedCallbacks.forEach(a=>a())},this.ws.onerror=a=>{console.error("\u274C WebSocket error:",a),console.error("WebSocket readyState:",this.ws.readyState),this.onErrorCallbacks.forEach(r=>r(a)),o<i&&(o++,console.log(`\u{1F504} Retrying WebSocket connection (${o}/${i})...`),n(`\u{1F504} Retrying WebSocket connection (${o}/${i})...`),setTimeout(c,1e3*o))},this.ws.onclose=a=>{console.log("\u{1F504} WebSocket closed:",a.code,a.reason),n("\u{1F504} WebSocket closed:",a.code,a.reason),a.code!==1e3&&o<i&&(o++,console.log(`\u{1F504} Attempting to reconnect (${o}/${i})...`),n(`\u{1F504} Attempting to reconnect (${o}/${i})...`),setTimeout(c,1e3*o))},this.ws.onmessage=a=>{let r=JSON.parse(a.data);this._handleMessage(r)}};c()}_handleMessage({type:e,data:t}){switch(n("\u{1F4E8} Received message:",{type:e,data:t}),e){case"connected":n("\u{1F3AF} Got connected event with data:",t),this.onConnectedCallbacks.forEach(r=>r(t.port,"connected",t.url));break;case"error":console.error("\u274C Got error event:",t.message),this.onErrorCallbacks.forEach(r=>r(t.message));break;case"terminal:output":n("\u{1F4DD} Got terminal output:",t);let s=this.terminals.get(t.terminalId);s?s._handleData(t.data):console.warn("\u26A0\uFE0F No terminal found for ID:",t.terminalId);break;case"terminal:exit":n("\u{1F6AB} Got terminal exit event:",t);let l=this.terminals.get(t.terminalId);l&&(l._handleExit(t.exitCode,t.signal),this.terminals.delete(t.terminalId));break;case"file:changed":n("\u{1F4C1} Got file changed event:",t);let o=t.path.startsWith("/")?t.path:`/home/project/${t.path}`,i=t.path.replace(/^\/home\/project\//,""),c="/home/project",a=this.fileWatchers.get(o)||this.fileWatchers.get(i)||this.fileWatchers.get(c);a?(n("\u2705 Found watcher for path:",t.path),a._handleChange({...t,path:o})):(console.warn("\u26A0\uFE0F No watcher found for paths:",{original:t.path,full:o,relative:i,base:c}),n("\u{1F4CB} Active watchers:",Array.from(this.fileWatchers.keys())));break;case"port:opened":n("\u2705 Got port opened event:",t),this.portOpenedCallbacks.forEach(r=>r(t.port,new URL(`https://${t.port}-${new URL(this.podUrl).host}`)));break;case"server:ready":n("\u2705 Got server ready event:",t),this.serverReadyCallbacks.forEach(r=>r(t.port,new URL(`https://${t.port}-${new URL(this.podUrl).host}`)));break}}onConnected(e){return this.onConnectedCallbacks=this.onConnectedCallbacks||new Set,this.onConnectedCallbacks.add(e),()=>this.onConnectedCallbacks.delete(e)}onPortOpened(e){return this.portOpenedCallbacks=this.portOpenedCallbacks||new Set,this.portOpenedCallbacks.add(e),()=>this.portOpenedCallbacks.delete(e)}onServerReady(e){return this.serverReadyCallbacks=this.serverReadyCallbacks||new Set,this.serverReadyCallbacks.add(e),()=>this.serverReadyCallbacks.delete(e)}onError(e){return this.onErrorCallbacks=this.onErrorCallbacks||new Set,this.onErrorCallbacks.add(e),()=>this.onErrorCallbacks.delete(e)}async createTerminal({rows:e=24,cols:t=80,command:s=null,args:l=[]}={}){return new Promise(o=>{let i=`terminal-${this.terminalId++}`,c=a=>{let r=JSON.parse(a.data);if(n("\u{1F3AF} Terminal creation message:",r),r.type==="terminal:output"&&r.data.terminalId===i){n("\u2728 Creating new terminal with ID:",r.data.terminalId);let f=new p(this.ws,r.data.terminalId);this.terminals.set(r.data.terminalId,f),this.ws.removeEventListener("message",c),o(f)}};n("\u{1F4E1} Sending terminal create request..."),this.ws.addEventListener("message",c),this.ws.send(JSON.stringify({type:"terminal:create",data:{rows:e,cols:t,command:s,args:l,terminalId:i}}))})}watchFiles({path:e,includeContent:t=!1,ignored:s=[],...l}={}){n("\u{1F50D} Starting file watch for:",e);let o=["**/node_modules/**","**/node_modules",...(Array.isArray(s)?s:[s]).filter(Boolean)],i=new w(this.ws,e,{ignored:o,...l});return this.fileWatchers.set(e,i),this.ws.send(JSON.stringify({type:"file:watch:start",data:{path:e,includeContent:t,ignoredOptions:o,...l}})),n("\u{1F4E4} Sent watch request:",{path:e,includeContent:t,ignoredOptions:o,options:l}),i}async readFile(e){let t=await fetch(`${this.podUrl}/fs/read`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:e})});if(!t.ok)throw new Error(`Failed to read file: ${t.statusText}`);return t.text()}async writeFile(e,t){let s=await fetch(`${this.podUrl}/fs/write`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:e,content:t})});if(!s.ok)throw new Error(`Failed to write file: ${s.statusText}`)}async mkdir(e,{recursive:t=!0}){let s=await fetch(`${this.podUrl}/fs/write`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:e,directory:!0,recursive:t})});if(!s.ok)throw new Error(`Failed to create directory: ${s.statusText}`)}async deleteFile(e){let t=await fetch(`${this.podUrl}/fs/remove`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:e})});if(!t.ok)throw new Error(`Failed to delete file: ${t.statusText}`)}async exec(e,t={}){let s=await fetch(`${this.podUrl}/process/exec`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({command:e,...t})});if(!s.ok)throw new Error(`Failed to execute command: ${s.statusText}`);return s.json()}},d=class{constructor(e={}){this.baseUrl=e.baseUrl||"https://api.computesdk.com"}async create(){n("\u{1F680} Creating compute instance at:",`${this.baseUrl}/api/v1/compute`);let e=await fetch(`${this.baseUrl}/api/v1/compute`,{method:"POST"});if(!e.ok){let s=await e.text();throw console.error("\u274C Failed to create compute:",s),new Error(`Failed to create compute: ${e.statusText} - ${s}`)}let t=await e.json();return n("\u2705 Compute created successfully:",t),new m(t.computeId,t.podInfo.podUrl)}async delete(e){let t=await fetch(`${this.baseUrl}/api/v1/compute/${e}`,{method:"DELETE"});if(!t.ok)throw new Error(`Failed to delete compute: ${t.statusText}`)}};export{m as Compute,d as ComputeClient};
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/index.ts
21
+ var index_exports = {};
22
+ __export(index_exports, {
23
+ AuthenticationError: () => AuthenticationError,
24
+ BaseProvider: () => BaseProvider,
25
+ ComputeError: () => ComputeError,
26
+ ComputeSDK: () => ComputeSDK,
27
+ ConfigurationError: () => ConfigurationError,
28
+ DEFAULT_TIMEOUT: () => DEFAULT_TIMEOUT,
29
+ ENV_KEYS: () => ENV_KEYS,
30
+ ExecutionError: () => ExecutionError,
31
+ ProviderError: () => ProviderError,
32
+ ProviderUnavailableError: () => ProviderUnavailableError,
33
+ TimeoutError: () => TimeoutError,
34
+ autoSelectProvider: () => autoSelectProvider,
35
+ createComputeRegistry: () => createComputeRegistry,
36
+ default: () => index_default,
37
+ detectAvailableProviders: () => detectAvailableProviders,
38
+ executeSandbox: () => executeSandbox,
39
+ getDefaultRuntime: () => getDefaultRuntime,
40
+ isCloudflareWorkers: () => isCloudflareWorkers,
41
+ normalizeContainerConfig: () => normalizeContainerConfig,
42
+ normalizeSandboxConfig: () => normalizeSandboxConfig,
43
+ retry: () => retry,
44
+ validateProviderApiKey: () => validateProviderApiKey
45
+ });
46
+ module.exports = __toCommonJS(index_exports);
47
+
48
+ // src/errors.ts
49
+ var ComputeError = class extends Error {
50
+ /**
51
+ * Create a new ComputeError
52
+ *
53
+ * @param message Error message
54
+ * @param provider Provider identifier
55
+ * @param sandboxId Optional sandbox identifier
56
+ */
57
+ constructor(message, provider, sandboxId) {
58
+ super(message);
59
+ this.name = this.constructor.name;
60
+ this.provider = provider;
61
+ this.sandboxId = sandboxId;
62
+ Object.setPrototypeOf(this, new.target.prototype);
63
+ }
64
+ };
65
+ var ExecutionError = class extends ComputeError {
66
+ /**
67
+ * Create a new ExecutionError
68
+ *
69
+ * @param message Error message
70
+ * @param provider Provider identifier
71
+ * @param exitCode Exit code from the execution
72
+ * @param sandboxId Optional sandbox identifier
73
+ */
74
+ constructor(message, provider, exitCode, sandboxId) {
75
+ super(message, provider, sandboxId);
76
+ /** Error code */
77
+ this.code = "EXECUTION_ERROR";
78
+ /** Execution errors are generally not retryable */
79
+ this.isRetryable = false;
80
+ this.exitCode = exitCode;
81
+ }
82
+ };
83
+ var TimeoutError = class extends ComputeError {
84
+ /**
85
+ * Create a new TimeoutError
86
+ *
87
+ * @param message Error message
88
+ * @param provider Provider identifier
89
+ * @param timeoutMs Timeout duration in milliseconds
90
+ * @param sandboxId Optional sandbox identifier
91
+ */
92
+ constructor(message, provider, timeoutMs, sandboxId) {
93
+ super(message, provider, sandboxId);
94
+ /** Error code */
95
+ this.code = "TIMEOUT_ERROR";
96
+ /** Timeout errors may be retryable with a longer timeout */
97
+ this.isRetryable = true;
98
+ this.timeoutMs = timeoutMs;
99
+ }
100
+ };
101
+ var ProviderError = class extends ComputeError {
102
+ /**
103
+ * Create a new ProviderError
104
+ *
105
+ * @param message Error message
106
+ * @param provider Provider identifier
107
+ * @param originalError Optional original error from the provider
108
+ * @param sandboxId Optional sandbox identifier
109
+ */
110
+ constructor(message, provider, originalError, sandboxId) {
111
+ super(message, provider, sandboxId);
112
+ /** Error code */
113
+ this.code = "PROVIDER_ERROR";
114
+ /** Provider errors may be retryable */
115
+ this.isRetryable = true;
116
+ this.originalError = originalError;
117
+ }
118
+ };
119
+ var ConfigurationError = class extends ComputeError {
120
+ /**
121
+ * Create a new ConfigurationError
122
+ *
123
+ * @param message Error message
124
+ * @param provider Provider identifier
125
+ * @param sandboxId Optional sandbox identifier
126
+ */
127
+ constructor(message, provider, sandboxId) {
128
+ super(message, provider, sandboxId);
129
+ /** Error code */
130
+ this.code = "CONFIGURATION_ERROR";
131
+ /** Configuration errors are not retryable without changes */
132
+ this.isRetryable = false;
133
+ }
134
+ };
135
+ var AuthenticationError = class extends ComputeError {
136
+ /**
137
+ * Create a new AuthenticationError
138
+ *
139
+ * @param message Error message
140
+ * @param provider Provider identifier
141
+ * @param sandboxId Optional sandbox identifier
142
+ */
143
+ constructor(message, provider, sandboxId) {
144
+ super(message, provider, sandboxId);
145
+ /** Error code */
146
+ this.code = "AUTHENTICATION_ERROR";
147
+ /** Authentication errors are not retryable without new credentials */
148
+ this.isRetryable = false;
149
+ }
150
+ };
151
+ var ProviderUnavailableError = class extends ComputeError {
152
+ /**
153
+ * Create a new ProviderUnavailableError
154
+ *
155
+ * @param message Error message
156
+ * @param provider Provider identifier
157
+ * @param sandboxId Optional sandbox identifier
158
+ */
159
+ constructor(message, provider, sandboxId) {
160
+ super(message, provider, sandboxId);
161
+ /** Error code */
162
+ this.code = "PROVIDER_UNAVAILABLE";
163
+ /** Provider unavailability may be temporary */
164
+ this.isRetryable = true;
165
+ }
166
+ };
167
+
168
+ // src/config.ts
169
+ var DEFAULT_TIMEOUT = 3e5;
170
+ var ENV_KEYS = {
171
+ E2B: "E2B_API_KEY",
172
+ VERCEL: "VERCEL_TOKEN",
173
+ CLOUDFLARE: "CLOUDFLARE_API_TOKEN",
174
+ FLY: "FLY_API_TOKEN"
175
+ };
176
+ function isCloudflareWorkers() {
177
+ return typeof DurableObject !== "undefined" && typeof WebSocketPair !== "undefined" && typeof caches !== "undefined";
178
+ }
179
+ function detectAvailableProviders() {
180
+ const available = [];
181
+ if (process.env[ENV_KEYS.E2B]) {
182
+ available.push("e2b");
183
+ }
184
+ if (process.env[ENV_KEYS.VERCEL]) {
185
+ available.push("vercel");
186
+ }
187
+ if (isCloudflareWorkers() || process.env[ENV_KEYS.CLOUDFLARE]) {
188
+ available.push("cloudflare");
189
+ }
190
+ if (process.env[ENV_KEYS.FLY]) {
191
+ available.push("fly");
192
+ }
193
+ return available;
194
+ }
195
+ function autoSelectProvider() {
196
+ const available = detectAvailableProviders();
197
+ return available.length > 0 ? available[0] : void 0;
198
+ }
199
+ function normalizeContainerConfig(container) {
200
+ if (!container) {
201
+ return void 0;
202
+ }
203
+ if (typeof container === "string") {
204
+ return { image: container };
205
+ }
206
+ if (!container.image) {
207
+ throw new ConfigurationError("Container configuration must include an image", "config");
208
+ }
209
+ return container;
210
+ }
211
+ function getDefaultRuntime(provider, runtime) {
212
+ if (runtime) {
213
+ return runtime;
214
+ }
215
+ switch (provider) {
216
+ case "e2b":
217
+ return "python";
218
+ case "vercel":
219
+ return "node";
220
+ case "cloudflare":
221
+ case "fly":
222
+ throw new ConfigurationError(
223
+ `Container-based provider '${provider}' requires explicit runtime or container configuration`,
224
+ provider
225
+ );
226
+ default:
227
+ return "node";
228
+ }
229
+ }
230
+ function validateProviderApiKey(provider) {
231
+ let envKey;
232
+ switch (provider) {
233
+ case "e2b":
234
+ envKey = ENV_KEYS.E2B;
235
+ break;
236
+ case "vercel":
237
+ envKey = ENV_KEYS.VERCEL;
238
+ break;
239
+ case "cloudflare":
240
+ if (isCloudflareWorkers()) {
241
+ return;
242
+ }
243
+ envKey = ENV_KEYS.CLOUDFLARE;
244
+ break;
245
+ case "fly":
246
+ envKey = ENV_KEYS.FLY;
247
+ break;
248
+ case "auto":
249
+ return;
250
+ // Will be handled by auto-selection
251
+ default:
252
+ throw new ConfigurationError(`Unknown provider: ${provider}`, "config");
253
+ }
254
+ if (!process.env[envKey]) {
255
+ const available = detectAvailableProviders();
256
+ const suggestions = available.length > 0 ? `Available providers: ${available.join(", ")}` : `No provider API keys found. Set ${Object.values(ENV_KEYS).join(" or ")} environment variables.`;
257
+ throw new ConfigurationError(
258
+ `Missing API key for provider '${provider}'. ${suggestions}`,
259
+ provider
260
+ );
261
+ }
262
+ }
263
+ function normalizeSandboxConfig(config) {
264
+ const normalized = {
265
+ provider: config?.provider || "auto",
266
+ timeout: config?.timeout || DEFAULT_TIMEOUT
267
+ };
268
+ if (normalized.provider === "auto") {
269
+ const autoProvider = autoSelectProvider();
270
+ if (!autoProvider) {
271
+ throw new ConfigurationError(
272
+ `No provider API keys found. Set one of the following environment variables: ${Object.values(ENV_KEYS).join(", ")}`,
273
+ "config"
274
+ );
275
+ }
276
+ normalized.provider = autoProvider;
277
+ } else {
278
+ validateProviderApiKey(normalized.provider);
279
+ }
280
+ if (config?.runtime) {
281
+ normalized.runtime = config.runtime;
282
+ } else if (!config?.container) {
283
+ normalized.runtime = getDefaultRuntime(normalized.provider);
284
+ }
285
+ if (config?.container) {
286
+ normalized.container = normalizeContainerConfig(config.container);
287
+ }
288
+ return normalized;
289
+ }
290
+
291
+ // src/utils.ts
292
+ async function executeSandbox(params) {
293
+ return await params.sandbox.execute(params.code, params.runtime);
294
+ }
295
+ async function retry(fn, maxRetries = 3, baseDelay = 1e3) {
296
+ let lastError;
297
+ for (let i = 0; i < maxRetries; i++) {
298
+ try {
299
+ return await fn();
300
+ } catch (error) {
301
+ lastError = error instanceof Error ? error : new Error(String(error));
302
+ if (i === maxRetries - 1) {
303
+ throw lastError;
304
+ }
305
+ const delay = baseDelay * Math.pow(2, i);
306
+ await new Promise((resolve) => setTimeout(resolve, delay));
307
+ }
308
+ }
309
+ throw lastError;
310
+ }
311
+
312
+ // src/registry.ts
313
+ function createComputeRegistry(providers) {
314
+ if (!providers || Object.keys(providers).length === 0) {
315
+ throw new ConfigurationError("Provider registry requires at least one provider", "registry");
316
+ }
317
+ function sandbox(id) {
318
+ const parts = id.split(":");
319
+ if (parts.length < 1) {
320
+ throw new ConfigurationError(`Invalid sandbox ID format: ${id}`, "registry");
321
+ }
322
+ const providerName = parts[0];
323
+ const providerFactory = providers[providerName];
324
+ if (!providerFactory) {
325
+ const availableProviders = Object.keys(providers).join(", ");
326
+ throw new ConfigurationError(
327
+ `Provider '${providerName}' not found in registry. Available providers: ${availableProviders}`,
328
+ "registry"
329
+ );
330
+ }
331
+ if (parts.length === 1) {
332
+ return providerFactory();
333
+ } else if (parts.length === 2) {
334
+ const runtimeOrImage = parts[1];
335
+ if (isRuntime(runtimeOrImage)) {
336
+ return providerFactory({ runtime: runtimeOrImage });
337
+ }
338
+ return providerFactory({ container: { image: runtimeOrImage } });
339
+ } else {
340
+ const containerImage = parts.slice(1).join(":");
341
+ return providerFactory({ container: { image: containerImage } });
342
+ }
343
+ }
344
+ return { sandbox };
345
+ }
346
+ function isRuntime(value) {
347
+ return ["node", "python"].includes(value);
348
+ }
349
+
350
+ // src/providers/base.ts
351
+ var import_uuid = require("uuid");
352
+ var BaseProvider = class {
353
+ /**
354
+ * Create a new base provider
355
+ *
356
+ * @param provider Provider identifier
357
+ * @param timeout Execution timeout in milliseconds
358
+ */
359
+ constructor(provider, timeout) {
360
+ /** Specification version */
361
+ this.specificationVersion = "v1";
362
+ this.provider = provider;
363
+ this.sandboxId = (0, import_uuid.v4)();
364
+ this.timeout = timeout;
365
+ }
366
+ /**
367
+ * Execute code in the sandbox
368
+ *
369
+ * @param code Code to execute
370
+ * @param runtime Optional runtime to use
371
+ * @returns Execution result
372
+ */
373
+ async execute(code, runtime) {
374
+ const startTime = Date.now();
375
+ try {
376
+ const timeoutPromise = new Promise((_, reject) => {
377
+ setTimeout(() => {
378
+ reject(new TimeoutError(
379
+ `Execution timed out after ${this.timeout}ms`,
380
+ this.provider,
381
+ this.timeout,
382
+ this.sandboxId
383
+ ));
384
+ }, this.timeout);
385
+ });
386
+ const result = await Promise.race([
387
+ this.doExecute(code, runtime),
388
+ timeoutPromise
389
+ ]);
390
+ const executionTime = Date.now() - startTime;
391
+ return {
392
+ ...result,
393
+ executionTime,
394
+ sandboxId: this.sandboxId,
395
+ provider: this.provider
396
+ };
397
+ } catch (error) {
398
+ if (error instanceof Error && error.name.includes("Error") && "code" in error) {
399
+ throw error;
400
+ }
401
+ throw new ProviderError(
402
+ `Execution failed: ${error instanceof Error ? error.message : String(error)}`,
403
+ this.provider,
404
+ error instanceof Error ? error : void 0,
405
+ this.sandboxId
406
+ );
407
+ }
408
+ }
409
+ /**
410
+ * Kill the sandbox
411
+ *
412
+ * @returns Promise that resolves when the sandbox is killed
413
+ */
414
+ async kill() {
415
+ try {
416
+ await this.doKill();
417
+ } catch (error) {
418
+ throw new ProviderError(
419
+ `Failed to kill sandbox: ${error instanceof Error ? error.message : String(error)}`,
420
+ this.provider,
421
+ error instanceof Error ? error : void 0,
422
+ this.sandboxId
423
+ );
424
+ }
425
+ }
426
+ /**
427
+ * Get information about the sandbox
428
+ *
429
+ * @returns Sandbox information
430
+ */
431
+ async getInfo() {
432
+ try {
433
+ return await this.doGetInfo();
434
+ } catch (error) {
435
+ throw new ProviderError(
436
+ `Failed to get sandbox info: ${error instanceof Error ? error.message : String(error)}`,
437
+ this.provider,
438
+ error instanceof Error ? error : void 0,
439
+ this.sandboxId
440
+ );
441
+ }
442
+ }
443
+ };
444
+
445
+ // src/sdk.ts
446
+ var ComputeSDK = class {
447
+ /**
448
+ * Create a new sandbox with the specified configuration
449
+ *
450
+ * @param config Optional sandbox configuration
451
+ * @returns Configured sandbox instance
452
+ */
453
+ static createSandbox(config) {
454
+ const normalizedConfig = normalizeSandboxConfig(config);
455
+ const providerName = normalizedConfig.provider;
456
+ try {
457
+ const providerPackage = `@computesdk/${providerName}`;
458
+ const provider = require(providerPackage);
459
+ const factory = provider[providerName];
460
+ if (!factory) {
461
+ throw new ConfigurationError(
462
+ `Provider package ${providerPackage} does not export a '${providerName}' function`,
463
+ "sdk"
464
+ );
465
+ }
466
+ if (providerName === "cloudflare") {
467
+ throw new ConfigurationError(
468
+ 'Cloudflare provider requires env parameter with Sandbox namespace. Use createSandbox({ provider: "cloudflare", env: yourEnv }) from within a Worker.',
469
+ "sdk"
470
+ );
471
+ } else if (providerName === "fly") {
472
+ if (!normalizedConfig.container) {
473
+ throw new ConfigurationError(
474
+ `${providerName} provider requires container configuration`,
475
+ "sdk"
476
+ );
477
+ }
478
+ return factory({ ...normalizedConfig, container: normalizedConfig.container });
479
+ } else {
480
+ return factory(normalizedConfig);
481
+ }
482
+ } catch (error) {
483
+ if (error instanceof ConfigurationError) {
484
+ throw error;
485
+ }
486
+ if (error.code === "MODULE_NOT_FOUND") {
487
+ throw new ConfigurationError(
488
+ `Provider '${providerName}' not installed. Run: npm install @computesdk/${providerName}`,
489
+ "sdk"
490
+ );
491
+ }
492
+ throw new ConfigurationError(
493
+ `Failed to load provider '${providerName}': ${error.message}`,
494
+ "sdk"
495
+ );
496
+ }
497
+ }
498
+ /**
499
+ * Detect available providers based on environment variables
500
+ *
501
+ * @returns Array of available provider types
502
+ */
503
+ static detectProviders() {
504
+ return detectAvailableProviders();
505
+ }
506
+ };
507
+
508
+ // src/index.ts
509
+ var index_default = ComputeSDK;
510
+ // Annotate the CommonJS export names for ESM import in node:
511
+ 0 && (module.exports = {
512
+ AuthenticationError,
513
+ BaseProvider,
514
+ ComputeError,
515
+ ComputeSDK,
516
+ ConfigurationError,
517
+ DEFAULT_TIMEOUT,
518
+ ENV_KEYS,
519
+ ExecutionError,
520
+ ProviderError,
521
+ ProviderUnavailableError,
522
+ TimeoutError,
523
+ autoSelectProvider,
524
+ createComputeRegistry,
525
+ detectAvailableProviders,
526
+ executeSandbox,
527
+ getDefaultRuntime,
528
+ isCloudflareWorkers,
529
+ normalizeContainerConfig,
530
+ normalizeSandboxConfig,
531
+ retry,
532
+ validateProviderApiKey
533
+ });
534
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/index.ts","../src/errors.ts","../src/config.ts","../src/utils.ts","../src/registry.ts","../src/providers/base.ts","../src/sdk.ts"],"sourcesContent":["/**\n * ComputeSDK Core\n * \n * A unified abstraction layer for executing code in secure,\n * isolated sandboxed environments across multiple cloud providers.\n */\n\n// Export all types\nexport * from './types';\n\n// Export all errors\nexport * from './errors';\n\n// Export configuration utilities\nexport * from './config';\n\n// Export utilities\nexport { executeSandbox, retry } from './utils';\n\n// Export registry\nexport { createComputeRegistry } from './registry';\n\n// Export base provider for extension\nexport { BaseProvider } from './providers/base';\n\n// Export main SDK class\nexport { ComputeSDK } from './sdk';\n\n// Default export\nimport { ComputeSDK } from './sdk';\nexport default ComputeSDK;\n","/**\n * ComputeSDK Error Handling\n * \n * This file contains standardized error classes for the ComputeSDK.\n */\n\n/**\n * Base error class for all ComputeSDK errors\n */\nexport abstract class ComputeError extends Error {\n /** Error code identifier */\n abstract readonly code: string;\n\n /** Whether the operation can be retried */\n abstract readonly isRetryable: boolean;\n\n /** Provider where the error occurred */\n readonly provider: string;\n\n /** Sandbox ID where the error occurred */\n readonly sandboxId?: string;\n\n /**\n * Create a new ComputeError\n * \n * @param message Error message\n * @param provider Provider identifier\n * @param sandboxId Optional sandbox identifier\n */\n constructor(message: string, provider: string, sandboxId?: string) {\n super(message);\n this.name = this.constructor.name;\n this.provider = provider;\n this.sandboxId = sandboxId;\n\n // Ensure proper prototype chain for instanceof checks\n Object.setPrototypeOf(this, new.target.prototype);\n }\n}\n\n/**\n * Error thrown when code execution fails\n */\nexport class ExecutionError extends ComputeError {\n /** Error code */\n readonly code = 'EXECUTION_ERROR';\n\n /** Execution errors are generally not retryable */\n readonly isRetryable = false;\n\n /** Exit code from the failed execution */\n readonly exitCode: number;\n\n /**\n * Create a new ExecutionError\n * \n * @param message Error message\n * @param provider Provider identifier\n * @param exitCode Exit code from the execution\n * @param sandboxId Optional sandbox identifier\n */\n constructor(message: string, provider: string, exitCode: number, sandboxId?: string) {\n super(message, provider, sandboxId);\n this.exitCode = exitCode;\n }\n}\n\n/**\n * Error thrown when code execution times out\n */\nexport class TimeoutError extends ComputeError {\n /** Error code */\n readonly code = 'TIMEOUT_ERROR';\n\n /** Timeout errors may be retryable with a longer timeout */\n readonly isRetryable = true;\n\n /** Timeout duration in milliseconds */\n readonly timeoutMs: number;\n\n /**\n * Create a new TimeoutError\n * \n * @param message Error message\n * @param provider Provider identifier\n * @param timeoutMs Timeout duration in milliseconds\n * @param sandboxId Optional sandbox identifier\n */\n constructor(message: string, provider: string, timeoutMs: number, sandboxId?: string) {\n super(message, provider, sandboxId);\n this.timeoutMs = timeoutMs;\n }\n}\n\n/**\n * Error thrown when provider-specific operations fail\n */\nexport class ProviderError extends ComputeError {\n /** Error code */\n readonly code = 'PROVIDER_ERROR';\n\n /** Provider errors may be retryable */\n readonly isRetryable = true;\n\n /** Original error from the provider */\n readonly originalError?: Error;\n\n /**\n * Create a new ProviderError\n * \n * @param message Error message\n * @param provider Provider identifier\n * @param originalError Optional original error from the provider\n * @param sandboxId Optional sandbox identifier\n */\n constructor(message: string, provider: string, originalError?: Error, sandboxId?: string) {\n super(message, provider, sandboxId);\n this.originalError = originalError;\n }\n}\n\n/**\n * Error thrown when configuration is invalid\n */\nexport class ConfigurationError extends ComputeError {\n /** Error code */\n readonly code = 'CONFIGURATION_ERROR';\n\n /** Configuration errors are not retryable without changes */\n readonly isRetryable = false;\n\n /**\n * Create a new ConfigurationError\n * \n * @param message Error message\n * @param provider Provider identifier\n * @param sandboxId Optional sandbox identifier\n */\n constructor(message: string, provider: string, sandboxId?: string) {\n super(message, provider, sandboxId);\n }\n}\n\n/**\n * Error thrown when authentication fails\n */\nexport class AuthenticationError extends ComputeError {\n /** Error code */\n readonly code = 'AUTHENTICATION_ERROR';\n\n /** Authentication errors are not retryable without new credentials */\n readonly isRetryable = false;\n\n /**\n * Create a new AuthenticationError\n * \n * @param message Error message\n * @param provider Provider identifier\n * @param sandboxId Optional sandbox identifier\n */\n constructor(message: string, provider: string, sandboxId?: string) {\n super(message, provider, sandboxId);\n }\n}\n\n/**\n * Error thrown when the provider is not available\n */\nexport class ProviderUnavailableError extends ComputeError {\n /** Error code */\n readonly code = 'PROVIDER_UNAVAILABLE';\n\n /** Provider unavailability may be temporary */\n readonly isRetryable = true;\n\n /**\n * Create a new ProviderUnavailableError\n * \n * @param message Error message\n * @param provider Provider identifier\n * @param sandboxId Optional sandbox identifier\n */\n constructor(message: string, provider: string, sandboxId?: string) {\n super(message, provider, sandboxId);\n }\n}\n","/**\n * ComputeSDK Configuration Management\n * \n * This file manages configuration and provider selection logic.\n */\n\nimport { SandboxConfig, ProviderType, Runtime, ContainerConfig } from './types';\nimport { ConfigurationError } from './errors';\n\n// Global type declarations for platform detection\ndeclare global {\n var DurableObject: any;\n var WebSocketPair: any;\n}\n\n// Default configuration values\nexport const DEFAULT_TIMEOUT = 300000; // 5 minutes in milliseconds\n\n/**\n * Environment variable names for provider API keys\n */\nexport const ENV_KEYS = {\n E2B: 'E2B_API_KEY',\n VERCEL: 'VERCEL_TOKEN',\n CLOUDFLARE: 'CLOUDFLARE_API_TOKEN',\n FLY: 'FLY_API_TOKEN',\n};\n\n/**\n * Detect if running in Cloudflare Workers environment\n * \n * @returns True if running in Cloudflare Workers\n */\nexport function isCloudflareWorkers(): boolean {\n return typeof DurableObject !== 'undefined' && \n typeof WebSocketPair !== 'undefined' &&\n typeof caches !== 'undefined';\n}\n\n/**\n * Detect available providers based on environment variables\n * \n * @returns Array of available provider types\n */\nexport function detectAvailableProviders(): ProviderType[] {\n const available: ProviderType[] = [];\n\n if (process.env[ENV_KEYS.E2B]) {\n available.push('e2b');\n }\n\n if (process.env[ENV_KEYS.VERCEL]) {\n available.push('vercel');\n }\n\n // Cloudflare can be detected by environment OR API key\n if (isCloudflareWorkers() || process.env[ENV_KEYS.CLOUDFLARE]) {\n available.push('cloudflare');\n }\n\n if (process.env[ENV_KEYS.FLY]) {\n available.push('fly');\n }\n\n return available;\n}\n\n/**\n * Auto-select the best provider based on available API keys\n * \n * @returns Selected provider type or undefined if none available\n */\nexport function autoSelectProvider(): ProviderType | undefined {\n const available = detectAvailableProviders();\n return available.length > 0 ? available[0] : undefined;\n}\n\n/**\n * Validate and normalize container configuration\n * \n * @param container Container configuration or image string\n * @returns Normalized container configuration\n */\nexport function normalizeContainerConfig(container: string | ContainerConfig | undefined): ContainerConfig | undefined {\n if (!container) {\n return undefined;\n }\n\n if (typeof container === 'string') {\n return { image: container };\n }\n\n if (!container.image) {\n throw new ConfigurationError('Container configuration must include an image', 'config');\n }\n\n return container;\n}\n\n/**\n * Get the appropriate runtime based on provider and configuration\n * \n * @param provider Provider type\n * @param runtime Optional runtime preference\n * @returns Selected runtime\n */\nexport function getDefaultRuntime(provider: ProviderType, runtime?: Runtime): Runtime {\n if (runtime) {\n return runtime;\n }\n\n // Provider-specific defaults\n switch (provider) {\n case 'e2b':\n return 'python';\n case 'vercel':\n return 'node';\n case 'cloudflare':\n case 'fly':\n throw new ConfigurationError(\n `Container-based provider '${provider}' requires explicit runtime or container configuration`,\n provider\n );\n default:\n return 'node';\n }\n}\n\n/**\n * Validate API key for selected provider\n * \n * @param provider Provider type\n * @throws AuthenticationError if API key is missing\n */\nexport function validateProviderApiKey(provider: ProviderType): void {\n let envKey: string;\n\n switch (provider) {\n case 'e2b':\n envKey = ENV_KEYS.E2B;\n break;\n case 'vercel':\n envKey = ENV_KEYS.VERCEL;\n break;\n case 'cloudflare':\n // Cloudflare can work without API key if in Workers environment\n if (isCloudflareWorkers()) {\n return;\n }\n envKey = ENV_KEYS.CLOUDFLARE;\n break;\n case 'fly':\n envKey = ENV_KEYS.FLY;\n break;\n case 'auto':\n return; // Will be handled by auto-selection\n default:\n throw new ConfigurationError(`Unknown provider: ${provider}`, 'config');\n }\n\n if (!process.env[envKey]) {\n const available = detectAvailableProviders();\n const suggestions = available.length > 0\n ? `Available providers: ${available.join(', ')}`\n : `No provider API keys found. Set ${Object.values(ENV_KEYS).join(' or ')} environment variables.`;\n\n throw new ConfigurationError(\n `Missing API key for provider '${provider}'. ${suggestions}`,\n provider\n );\n }\n}\n\n/**\n * Normalize and validate sandbox configuration\n * \n * @param config User-provided configuration\n * @returns Normalized configuration with defaults applied\n */\nexport function normalizeSandboxConfig(config?: Partial<SandboxConfig>): SandboxConfig {\n const normalized: SandboxConfig = {\n provider: config?.provider || 'auto',\n timeout: config?.timeout || DEFAULT_TIMEOUT,\n };\n\n // Handle provider selection\n if (normalized.provider === 'auto') {\n const autoProvider = autoSelectProvider();\n if (!autoProvider) {\n throw new ConfigurationError(\n `No provider API keys found. Set one of the following environment variables: ${Object.values(ENV_KEYS).join(', ')}`,\n 'config'\n );\n }\n normalized.provider = autoProvider;\n } else {\n validateProviderApiKey(normalized.provider!);\n }\n\n // Handle runtime selection\n if (config?.runtime) {\n normalized.runtime = config.runtime;\n } else if (!config?.container) {\n normalized.runtime = getDefaultRuntime(normalized.provider!);\n }\n\n // Handle container configuration\n if (config?.container) {\n normalized.container = normalizeContainerConfig(config.container);\n }\n\n return normalized;\n}\n","/**\n * Utility functions for ComputeSDK\n */\n\nimport type { ExecuteSandboxParams, ExecutionResult, ComputeSandbox } from './types';\n\n/**\n * Execute code in a sandbox\n */\nexport async function executeSandbox(params: ExecuteSandboxParams): Promise<ExecutionResult> {\n return await params.sandbox.execute(params.code, params.runtime);\n}\n\n/**\n * Retry function with exponential backoff\n */\nexport async function retry<T>(\n fn: () => Promise<T>,\n maxRetries: number = 3,\n baseDelay: number = 1000\n): Promise<T> {\n let lastError: Error;\n \n for (let i = 0; i < maxRetries; i++) {\n try {\n return await fn();\n } catch (error) {\n lastError = error instanceof Error ? error : new Error(String(error));\n \n if (i === maxRetries - 1) {\n throw lastError;\n }\n \n // Exponential backoff\n const delay = baseDelay * Math.pow(2, i);\n await new Promise(resolve => setTimeout(resolve, delay));\n }\n }\n \n throw lastError!;\n}","/**\n * ComputeSDK Provider Registry\n * \n * This file implements the provider registry for managing multiple providers.\n */\n\nimport { ComputeSandbox, ProviderMap, ProviderRegistry, Runtime } from './types';\nimport { ConfigurationError } from './errors';\n\n/**\n * Create a provider registry for managing multiple providers\n * \n * @param providers Map of provider factories\n * @returns Provider registry instance\n */\nexport function createComputeRegistry(providers: ProviderMap): ProviderRegistry {\n // Validate provider map\n if (!providers || Object.keys(providers).length === 0) {\n throw new ConfigurationError('Provider registry requires at least one provider', 'registry');\n }\n\n /**\n * Get a sandbox by ID string\n * \n * Format: \"<provider>:<runtime>\" or \"<provider>:<container-image>\"\n * Examples: \"e2b:python\", \"vercel:node\", \"fly:python:3.9\"\n * \n * @param id Sandbox identifier string\n * @returns Configured sandbox instance\n */\n function sandbox(id: string): ComputeSandbox {\n const parts = id.split(':');\n\n if (parts.length < 1) {\n throw new ConfigurationError(`Invalid sandbox ID format: ${id}`, 'registry');\n }\n\n const providerName = parts[0];\n const providerFactory = providers[providerName];\n\n if (!providerFactory) {\n const availableProviders = Object.keys(providers).join(', ');\n throw new ConfigurationError(\n `Provider '${providerName}' not found in registry. Available providers: ${availableProviders}`,\n 'registry'\n );\n }\n\n // Handle different ID formats\n if (parts.length === 1) {\n // Just provider name, use default configuration\n return providerFactory();\n } else if (parts.length === 2) {\n // Provider with runtime or container image\n const runtimeOrImage = parts[1];\n\n // Check if it's a runtime\n if (isRuntime(runtimeOrImage)) {\n return providerFactory({ runtime: runtimeOrImage });\n }\n\n // Otherwise, treat as container image\n return providerFactory({ container: { image: runtimeOrImage } });\n } else {\n // Handle more complex formats (container with tag)\n const containerImage = parts.slice(1).join(':');\n return providerFactory({ container: { image: containerImage } });\n }\n }\n\n return { sandbox };\n}\n\n/**\n * Check if a string is a valid runtime\n * \n * @param value String to check\n * @returns Whether the string is a valid runtime\n */\nfunction isRuntime(value: string): value is Runtime {\n return ['node', 'python'].includes(value);\n}\n","/**\n * ComputeSDK Base Provider\n * \n * This file contains the base provider implementation that all\n * specific provider implementations extend.\n */\n\nimport { v4 as uuidv4 } from 'uuid';\nimport {\n ComputeSpecification,\n ComputeSandbox,\n Runtime,\n ExecutionResult,\n SandboxInfo\n} from '../types';\nimport { ProviderError, TimeoutError } from '../errors';\n\n/**\n * Base implementation of the ComputeSandbox interface\n * \n * Provides common functionality and wraps provider-specific implementations.\n */\nexport abstract class BaseProvider implements ComputeSandbox, ComputeSpecification {\n /** Specification version */\n public readonly specificationVersion = 'v1';\n\n /** Provider identifier */\n public readonly provider: string;\n\n /** Sandbox identifier */\n public readonly sandboxId: string;\n\n /** Execution timeout in milliseconds */\n protected readonly timeout: number;\n\n /**\n * Create a new base provider\n * \n * @param provider Provider identifier\n * @param timeout Execution timeout in milliseconds\n */\n constructor(provider: string, timeout: number) {\n this.provider = provider;\n this.sandboxId = uuidv4();\n this.timeout = timeout;\n }\n\n /**\n * Execute code in the sandbox\n * \n * @param code Code to execute\n * @param runtime Optional runtime to use\n * @returns Execution result\n */\n public async execute(code: string, runtime?: Runtime): Promise<ExecutionResult> {\n const startTime = Date.now();\n\n try {\n // Create a timeout promise that rejects after the timeout\n const timeoutPromise = new Promise<never>((_, reject) => {\n setTimeout(() => {\n reject(new TimeoutError(\n `Execution timed out after ${this.timeout}ms`,\n this.provider,\n this.timeout,\n this.sandboxId\n ));\n }, this.timeout);\n });\n\n // Execute the code with a timeout\n const result = await Promise.race([\n this.doExecute(code, runtime),\n timeoutPromise\n ]);\n\n // Calculate execution time\n const executionTime = Date.now() - startTime;\n\n return {\n ...result,\n executionTime,\n sandboxId: this.sandboxId,\n provider: this.provider\n };\n } catch (error) {\n // If the error is already a ComputeError, rethrow it\n if (error instanceof Error && error.name.includes('Error') && 'code' in error) {\n throw error;\n }\n\n // Otherwise, wrap it in a ProviderError\n throw new ProviderError(\n `Execution failed: ${error instanceof Error ? error.message : String(error)}`,\n this.provider,\n error instanceof Error ? error : undefined,\n this.sandboxId\n );\n }\n }\n\n /**\n * Kill the sandbox\n * \n * @returns Promise that resolves when the sandbox is killed\n */\n public async kill(): Promise<void> {\n try {\n await this.doKill();\n } catch (error) {\n throw new ProviderError(\n `Failed to kill sandbox: ${error instanceof Error ? error.message : String(error)}`,\n this.provider,\n error instanceof Error ? error : undefined,\n this.sandboxId\n );\n }\n }\n\n /**\n * Get information about the sandbox\n * \n * @returns Sandbox information\n */\n public async getInfo(): Promise<SandboxInfo> {\n try {\n return await this.doGetInfo();\n } catch (error) {\n throw new ProviderError(\n `Failed to get sandbox info: ${error instanceof Error ? error.message : String(error)}`,\n this.provider,\n error instanceof Error ? error : undefined,\n this.sandboxId\n );\n }\n }\n\n /**\n * Provider-specific implementation of code execution\n * \n * @param code Code to execute\n * @param runtime Optional runtime to use\n * @returns Execution result\n */\n public abstract doExecute(code: string, runtime?: Runtime): Promise<ExecutionResult>;\n\n /**\n * Provider-specific implementation of sandbox termination\n * \n * @returns Promise that resolves when the sandbox is killed\n */\n public abstract doKill(): Promise<void>;\n\n /**\n * Provider-specific implementation of retrieving sandbox information\n * \n * @returns Sandbox information\n */\n public abstract doGetInfo(): Promise<SandboxInfo>;\n}\n","import type { \n SandboxConfig, \n ComputeSandbox, \n ProviderType,\n Runtime,\n ContainerConfig\n} from './types';\nimport { \n ConfigurationError, \n AuthenticationError \n} from './errors';\nimport { \n normalizeSandboxConfig, \n detectAvailableProviders \n} from './config';\n\nexport class ComputeSDK {\n /**\n * Create a new sandbox with the specified configuration\n * \n * @param config Optional sandbox configuration\n * @returns Configured sandbox instance\n */\n static createSandbox(config?: Partial<SandboxConfig>): ComputeSandbox {\n const normalizedConfig = normalizeSandboxConfig(config);\n \n // Try to dynamically load the provider\n const providerName = normalizedConfig.provider;\n \n try {\n // Attempt to load provider package\n const providerPackage = `@computesdk/${providerName}`;\n const provider = require(providerPackage);\n \n // Get the factory function\n const factory = provider[providerName!];\n if (!factory) {\n throw new ConfigurationError(\n `Provider package ${providerPackage} does not export a '${providerName}' function`,\n 'sdk'\n );\n }\n \n // Create the sandbox based on provider type\n if (providerName === 'cloudflare') {\n // Cloudflare requires env parameter with Durable Object namespace\n // This would need to be passed in from the Worker context\n throw new ConfigurationError(\n 'Cloudflare provider requires env parameter with Sandbox namespace. ' +\n 'Use createSandbox({ provider: \"cloudflare\", env: yourEnv }) from within a Worker.',\n 'sdk'\n );\n } else if (providerName === 'fly') {\n if (!normalizedConfig.container) {\n throw new ConfigurationError(\n `${providerName} provider requires container configuration`,\n 'sdk'\n );\n }\n return factory({ ...normalizedConfig, container: normalizedConfig.container });\n } else {\n return factory(normalizedConfig);\n }\n } catch (error) {\n if (error instanceof ConfigurationError) {\n throw error;\n }\n \n // Check if it's a missing package error\n if ((error as any).code === 'MODULE_NOT_FOUND') {\n throw new ConfigurationError(\n `Provider '${providerName}' not installed. Run: npm install @computesdk/${providerName}`,\n 'sdk'\n );\n }\n \n throw new ConfigurationError(\n `Failed to load provider '${providerName}': ${(error as Error).message}`,\n 'sdk'\n );\n }\n }\n \n /**\n * Detect available providers based on environment variables\n * \n * @returns Array of available provider types\n */\n static detectProviders(): ProviderType[] {\n return detectAvailableProviders();\n }\n}"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACSO,IAAe,eAAf,cAAoC,MAAM;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAoB/C,YAAY,SAAiB,UAAkB,WAAoB;AACjE,UAAM,OAAO;AACb,SAAK,OAAO,KAAK,YAAY;AAC7B,SAAK,WAAW;AAChB,SAAK,YAAY;AAGjB,WAAO,eAAe,MAAM,WAAW,SAAS;AAAA,E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