tensorlake 0.5.131 → 0.5.133

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 (50) hide show
  1. package/README.md +27 -0
  2. package/dist/applications/index.cjs +492 -708
  3. package/dist/applications/index.cjs.map +1 -1
  4. package/dist/applications/index.d.cts +3 -3
  5. package/dist/applications/index.d.ts +3 -3
  6. package/dist/applications/index.js +493 -713
  7. package/dist/applications/index.js.map +1 -1
  8. package/dist/function-agent/main.cjs +5 -2
  9. package/dist/function-agent/main.cjs.map +1 -1
  10. package/dist/function-agent/main.js +6 -3
  11. package/dist/function-agent/main.js.map +1 -1
  12. package/dist/function-executor/main.cjs +6 -3
  13. package/dist/function-executor/main.cjs.map +1 -1
  14. package/dist/function-executor/main.js +7 -4
  15. package/dist/function-executor/main.js.map +1 -1
  16. package/dist/index.cjs +121 -418
  17. package/dist/index.cjs.map +1 -1
  18. package/dist/index.d.cts +8 -22
  19. package/dist/index.d.ts +8 -22
  20. package/dist/index.js +122 -423
  21. package/dist/index.js.map +1 -1
  22. package/dist/native-worker.cjs +1 -0
  23. package/dist/native-worker.cjs.map +1 -1
  24. package/dist/native-worker.js +1 -0
  25. package/dist/native-worker.js.map +1 -1
  26. package/dist/{remote-DRCCuRth.d.cts → remote-D95Y6Czr.d.cts} +1 -1
  27. package/dist/{remote-0dzBqScB.d.ts → remote-omwTzbfj.d.ts} +1 -1
  28. package/dist/{sandbox-image-Bf5bcxtO.d.cts → sandbox-image-ChzWDeZy.d.cts} +2 -0
  29. package/dist/{sandbox-image-Bf5bcxtO.d.ts → sandbox-image-ChzWDeZy.d.ts} +2 -0
  30. package/dist/sandbox-image.cjs +476 -453
  31. package/dist/sandbox-image.cjs.map +1 -1
  32. package/dist/sandbox-image.d.cts +1 -1
  33. package/dist/sandbox-image.d.ts +1 -1
  34. package/dist/sandbox-image.js +475 -456
  35. package/dist/sandbox-image.js.map +1 -1
  36. package/package.json +8 -8
  37. package/runtime/function-executor/manifest.json +14 -14
  38. package/runtime/function-executor/package/dist/function-executor/main.js +7 -4
  39. package/runtime/function-executor/package/dist/function-executor/main.js.map +1 -1
  40. package/runtime/function-executor/package/dist/native-worker.cjs +1 -0
  41. package/runtime/function-executor/package/dist/native-worker.cjs.map +1 -1
  42. package/runtime/function-executor/package/npm-shrinkwrap.json +2 -12
  43. package/runtime/function-executor/package/package.json +1 -2
  44. package/runtime/typescript-function-runner/manifest.json +13 -13
  45. package/runtime/typescript-function-runner/package/dist/function-agent/main.js +6 -3
  46. package/runtime/typescript-function-runner/package/dist/function-agent/main.js.map +1 -1
  47. package/runtime/typescript-function-runner/package/dist/native-worker.cjs +1 -0
  48. package/runtime/typescript-function-runner/package/dist/native-worker.cjs.map +1 -1
  49. package/runtime/typescript-function-runner/package/npm-shrinkwrap.json +20 -29
  50. package/runtime/typescript-function-runner/package/package.json +7 -7
package/dist/index.cjs CHANGED
@@ -44,12 +44,12 @@ var init_cjs_shims = __esm({
44
44
  });
45
45
 
46
46
  // src/defaults.ts
47
- var SDK_VERSION, API_URL, API_KEY, NAMESPACE, SANDBOX_PROXY_URL, DEFAULT_HTTP_TIMEOUT_MS, MAX_RETRIES, RETRY_BACKOFF_MS, RETRYABLE_STATUS_CODES;
47
+ var SDK_VERSION, API_URL, API_KEY, NAMESPACE, SANDBOX_PROXY_URL, DEFAULT_HTTP_TIMEOUT_MS, MAX_RETRIES, RETRY_BACKOFF_MS;
48
48
  var init_defaults = __esm({
49
49
  "src/defaults.ts"() {
50
50
  "use strict";
51
51
  init_cjs_shims();
52
- SDK_VERSION = "0.5.131";
52
+ SDK_VERSION = "0.5.133";
53
53
  API_URL = process.env.TENSORLAKE_API_URL ?? "https://api.tensorlake.ai";
54
54
  API_KEY = process.env.TENSORLAKE_API_KEY ?? void 0;
55
55
  NAMESPACE = process.env.INDEXIFY_NAMESPACE ?? "default";
@@ -57,33 +57,10 @@ var init_defaults = __esm({
57
57
  DEFAULT_HTTP_TIMEOUT_MS = 3e5;
58
58
  MAX_RETRIES = 3;
59
59
  RETRY_BACKOFF_MS = 500;
60
- RETRYABLE_STATUS_CODES = /* @__PURE__ */ new Set([429, 502, 503, 504]);
61
60
  }
62
61
  });
63
62
 
64
63
  // src/errors.ts
65
- function describeError(err) {
66
- const parts = [];
67
- const seen = /* @__PURE__ */ new Set();
68
- let current = err;
69
- for (let depth = 0; depth < 6; depth++) {
70
- if (current == null || typeof current !== "object" || seen.has(current)) {
71
- break;
72
- }
73
- seen.add(current);
74
- const e = current;
75
- const message = typeof e.message === "string" ? e.message.trim() : "";
76
- const code = typeof e.code === "string" ? e.code : void 0;
77
- let segment = message;
78
- if (code && (!message || !message.includes(code))) {
79
- segment = segment ? `${segment} (${code})` : code;
80
- }
81
- if (segment && !parts.includes(segment)) parts.push(segment);
82
- current = e.cause;
83
- }
84
- if (parts.length > 0) return parts.join(": ");
85
- return err instanceof Error ? err.message : String(err);
86
- }
87
64
  function formatErrorDetails(errorDetails) {
88
65
  if (errorDetails == null) return void 0;
89
66
  if (typeof errorDetails === "string") {
@@ -284,6 +261,11 @@ var init_url = __esm({
284
261
  // src/native-worker-client.ts
285
262
  function createWorkerBinding(runtime) {
286
263
  return {
264
+ NativeCloudClient: class {
265
+ constructor(...args) {
266
+ return runtime.handle("NativeCloudClient", args);
267
+ }
268
+ },
287
269
  NativeSandboxClient: class {
288
270
  constructor(...args) {
289
271
  return runtime.handle("NativeSandboxClient", args);
@@ -401,7 +383,10 @@ var init_native_worker_client = __esm({
401
383
  getWorker() {
402
384
  if (this.worker) return this.worker;
403
385
  const worker = new import_node_worker_threads.Worker(this.workerPath(), {
404
- env: import_node_worker_threads.SHARE_ENV,
386
+ // The bundled worker needs no application loaders or telemetry preloads.
387
+ // NODE_OPTIONS is parsed independently of execArgv by Node.
388
+ execArgv: [],
389
+ env: { ...process.env, NODE_OPTIONS: "" },
405
390
  name: "tensorlake-native"
406
391
  });
407
392
  this.worker = worker;
@@ -475,7 +460,7 @@ var init_native_worker_client = __esm({
475
460
  }
476
461
  };
477
462
  runtimeKey = /* @__PURE__ */ Symbol.for(
478
- `tensorlake.native.worker.${false ? "source" : "0.5.131"}.v1`
463
+ `tensorlake.native.worker.${false ? "source" : "0.5.133"}.v1`
479
464
  );
480
465
  runtimes = globalThis;
481
466
  }
@@ -5297,370 +5282,87 @@ var init_client = __esm({
5297
5282
  }
5298
5283
  });
5299
5284
 
5300
- // src/http.ts
5301
- function withTraceId(value, traceId) {
5302
- if (value == null) {
5303
- return { traceId };
5304
- }
5305
- return Object.assign(value, { traceId });
5306
- }
5307
- function hasHeader(headers, name) {
5308
- const lowered = name.toLowerCase();
5309
- return Object.keys(headers).some((key) => key.toLowerCase() === lowered);
5310
- }
5311
- function normalizeRequestBody(body) {
5312
- if (body == null) {
5313
- return void 0;
5314
- }
5315
- if (body instanceof Uint8Array) {
5316
- return Uint8Array.from(body).buffer;
5317
- }
5318
- return body;
5319
- }
5320
- function stripPathPayload(path3) {
5321
- const queryStart = path3.search(/[?#]/);
5322
- return queryStart === -1 ? path3 : path3.slice(0, queryStart);
5323
- }
5324
- function throwMappedError(status, body, path3) {
5325
- let message = body;
5326
- try {
5327
- const parsed = JSON.parse(body);
5328
- if (parsed.message) message = parsed.message;
5329
- else if (parsed.error) message = parsed.error;
5330
- } catch {
5331
- }
5332
- if (status === 404) {
5333
- if (path3.includes("sandbox-pools") || path3.includes("pools")) {
5334
- const match = path3.match(/sandbox-pools\/([^/]+)/);
5335
- if (match) throw new PoolNotFoundError(match[1]);
5336
- }
5337
- if (path3.includes("sandboxes")) {
5338
- const match = path3.match(/sandboxes\/([^/]+)/);
5339
- if (match) throw new SandboxNotFoundError(match[1]);
5340
- }
5341
- throw new RemoteAPIError(404, message);
5342
- }
5343
- if (status === 409) {
5344
- if (path3.includes("sandbox-pools") || path3.includes("pools")) {
5345
- const match = path3.match(/sandbox-pools\/([^/]+)/);
5346
- if (match) throw new PoolInUseError(match[1], message);
5347
- }
5348
- }
5349
- throw new RemoteAPIError(status, message);
5350
- }
5351
- function anySignal(signals) {
5352
- const controller = new AbortController();
5353
- for (const signal of signals) {
5354
- if (signal.aborted) {
5355
- controller.abort(signal.reason);
5356
- return controller.signal;
5357
- }
5358
- signal.addEventListener("abort", () => controller.abort(signal.reason), {
5359
- once: true
5360
- });
5361
- }
5362
- return controller.signal;
5363
- }
5364
- function sleep3(ms) {
5365
- return new Promise((resolve2) => setTimeout(resolve2, ms));
5366
- }
5367
- var import_undici, REQUEST_TIMEOUT_HEADER, HttpClient;
5368
- var init_http = __esm({
5369
- "src/http.ts"() {
5285
+ // src/native-cloud.ts
5286
+ async function serializeRequest(method, path3, options) {
5287
+ const headers = { ...options?.headers };
5288
+ let body = options?.body;
5289
+ if (options?.json !== void 0) {
5290
+ body = JSON.stringify(options.json);
5291
+ if (!Object.keys(headers).some((key) => key.toLowerCase() === "content-type")) {
5292
+ headers["Content-Type"] = "application/json";
5293
+ }
5294
+ }
5295
+ const request = {
5296
+ method,
5297
+ path: path3,
5298
+ headersJson: JSON.stringify(headers),
5299
+ statusOnlyCodes: [...options?.statusOnlyCodes ?? []]
5300
+ };
5301
+ if (body instanceof FormData) {
5302
+ request.parts = [];
5303
+ for (const [name, value] of body.entries()) {
5304
+ request.parts.push(typeof value === "string" ? { name, data: Buffer.from(value) } : { name, data: Buffer.from(await value.arrayBuffer()), filename: value.name, contentType: value.type || "application/octet-stream" });
5305
+ }
5306
+ } else if (body !== void 0) {
5307
+ if (body instanceof Blob) request.body = Buffer.from(await body.arrayBuffer());
5308
+ else if (typeof body === "string") request.body = Buffer.from(body);
5309
+ else if (body instanceof ArrayBuffer) request.body = Buffer.from(new Uint8Array(body));
5310
+ else request.body = Buffer.from(body);
5311
+ }
5312
+ return request;
5313
+ }
5314
+ var NativeCloudTransport;
5315
+ var init_native_cloud = __esm({
5316
+ "src/native-cloud.ts"() {
5370
5317
  "use strict";
5371
5318
  init_cjs_shims();
5372
- import_undici = require("undici");
5373
- init_defaults();
5374
- init_errors();
5375
- init_sdk_timings();
5376
- REQUEST_TIMEOUT_HEADER = "X-Tensorlake-Request-Timeout-Ms";
5377
- (0, import_undici.setGlobalDispatcher)(
5378
- new import_undici.Agent({
5379
- keepAliveTimeout: 6e4,
5380
- allowH2: true
5381
- })
5382
- );
5383
- HttpClient = class _HttpClient {
5384
- baseUrl;
5385
- headers;
5386
- maxRetries;
5387
- retryBackoffMs;
5388
- timeoutMs;
5389
- abortController = null;
5319
+ init_native_sandbox();
5320
+ init_native_worker_client();
5321
+ NativeCloudTransport = class {
5390
5322
  constructor(options) {
5391
- const url = options.baseUrl;
5392
- this.baseUrl = url.endsWith("/") ? url.slice(0, -1) : url;
5393
- this.maxRetries = options.maxRetries ?? MAX_RETRIES;
5394
- this.retryBackoffMs = options.retryBackoffMs ?? RETRY_BACKOFF_MS;
5395
- this.timeoutMs = options.timeoutMs === void 0 ? DEFAULT_HTTP_TIMEOUT_MS : options.timeoutMs;
5396
- this.headers = {
5397
- "User-Agent": `tensorlake-typescript-sdk/${SDK_VERSION}`
5398
- };
5399
- if (this.timeoutMs != null) {
5400
- this.headers[REQUEST_TIMEOUT_HEADER] = String(this.timeoutMs);
5401
- }
5402
- if (options.apiKey) {
5403
- this.headers["Authorization"] = `Bearer ${options.apiKey}`;
5404
- }
5405
- if (options.organizationId) {
5406
- this.headers["X-Forwarded-Organization-Id"] = options.organizationId;
5407
- }
5408
- if (options.projectId) {
5409
- this.headers["X-Forwarded-Project-Id"] = options.projectId;
5410
- }
5411
- if (options.hostHeader) {
5412
- this.headers["Host"] = options.hostHeader;
5413
- }
5414
- if (options.sandboxIdHeader) {
5415
- this.headers["X-Tensorlake-Sandbox-Id"] = options.sandboxIdHeader;
5323
+ this.options = options;
5324
+ if (!Number.isSafeInteger(options.maxRetries) || options.maxRetries < 0 || options.maxRetries > 4294967295) {
5325
+ throw new RangeError("maxRetries must be a non-negative 32-bit integer");
5416
5326
  }
5417
- if (options.routingHint) {
5418
- this.headers["X-Tensorlake-Route-Hint"] = options.routingHint;
5327
+ if (!Number.isFinite(options.retryBackoffMs) || options.retryBackoffMs < 0) {
5328
+ throw new RangeError("retryBackoffMs must be a non-negative finite number");
5419
5329
  }
5420
5330
  }
5331
+ native;
5332
+ closed = false;
5333
+ client() {
5334
+ if (this.closed) throw new Error("Tensorlake native client is closed");
5335
+ if (this.native) return this.native;
5336
+ const ctor = loadNativeSandboxBinding().NativeCloudClient;
5337
+ if (!ctor) throw new Error("Native binding does not export NativeCloudClient; rebuild with 'npm run build:native'");
5338
+ return this.native = new ctor(JSON.stringify(this.options));
5339
+ }
5421
5340
  close() {
5422
- this.abortController?.abort();
5423
- this.abortController = null;
5424
- }
5425
- /** Make a JSON request, returning the parsed response body. */
5426
- async requestJson(method, path3, options) {
5427
- const response = await this.requestResponse(method, path3, {
5428
- json: options?.body,
5429
- headers: options?.headers,
5430
- signal: options?.signal,
5431
- retryableStatusCodes: options?.retryableStatusCodes,
5432
- allowedErrorStatusCodes: options?.allowedErrorStatusCodes,
5433
- allowHttpErrors: options?.allowHttpErrors
5434
- });
5435
- const text = await response.text();
5436
- const data = text ? JSON.parse(text) : void 0;
5437
- return withTraceId(data, response.traceId);
5438
- }
5439
- /** Make a request returning raw bytes. */
5440
- async requestBytes(method, path3, options) {
5441
- const headers = { ...options?.headers ?? {} };
5442
- if (options?.contentType) {
5443
- headers["Content-Type"] = options.contentType;
5444
- }
5445
- const response = await this.requestResponse(method, path3, {
5446
- body: options?.body,
5447
- headers,
5448
- signal: options?.signal
5449
- });
5450
- const buffer = await response.arrayBuffer();
5451
- return withTraceId(new Uint8Array(buffer), response.traceId);
5452
- }
5453
- /** Make a request and return the response body as an SSE stream. */
5454
- async requestStream(method, path3, options) {
5455
- const response = await this.requestResponse(method, path3, {
5456
- json: options?.json,
5457
- headers: { Accept: "text/event-stream" },
5458
- signal: options?.signal
5459
- });
5460
- if (!response.body) {
5461
- throw new RemoteAPIError(
5462
- response.status,
5463
- "No response body for SSE stream"
5464
- );
5465
- }
5466
- return withTraceId(response.body, response.traceId);
5341
+ this.closed = true;
5342
+ releaseNativeHandle(this.native ?? null);
5343
+ this.native = void 0;
5467
5344
  }
5468
- /** Make a request and return the raw Response. */
5469
5345
  async requestResponse(method, path3, options) {
5470
- const headers = {
5471
- ...this.headers,
5472
- ...options?.headers ?? {}
5473
- };
5474
- const hasJsonBody = options?.json !== void 0;
5475
- if (hasJsonBody && !hasHeader(headers, "Content-Type")) {
5476
- headers["Content-Type"] = "application/json";
5477
- }
5478
- const body = hasJsonBody ? JSON.stringify(options?.json) : normalizeRequestBody(options?.body);
5479
- const { response, traceId } = await this.doFetch(
5480
- method,
5481
- path3,
5482
- body,
5483
- headers,
5484
- options?.signal,
5485
- options?.allowHttpErrors ?? false,
5486
- options?.retryableStatusCodes ?? RETRYABLE_STATUS_CODES,
5487
- options?.allowedErrorStatusCodes ?? /* @__PURE__ */ new Set()
5488
- );
5489
- return withTraceId(response, traceId);
5490
- }
5491
- static makeTraceparent() {
5492
- const randomHex = (bytes) => Array.from(crypto.getRandomValues(new Uint8Array(bytes))).map((b) => b.toString(16).padStart(2, "0")).join("");
5493
- const traceId = randomHex(16);
5494
- const spanId = randomHex(8);
5495
- return { traceparent: `00-${traceId}-${spanId}-01`, traceId };
5496
- }
5497
- async doFetch(method, path3, body, headers, signal, allowHttpErrors = false, retryableStatusCodes = RETRYABLE_STATUS_CODES, allowedErrorStatusCodes = /* @__PURE__ */ new Set()) {
5498
- const url = `${this.baseUrl}${path3}`;
5499
- const { traceparent, traceId } = _HttpClient.makeTraceparent();
5500
- headers["traceparent"] = traceparent;
5501
- let lastError;
5502
- const operationStart = nowMs();
5503
- const timingPath = sdkTimingPayloadsEnabled() ? path3 : stripPathPayload(path3);
5504
- for (let attempt = 0; attempt <= this.maxRetries; attempt++) {
5505
- if (attempt > 0) {
5506
- const delay = this.retryBackoffMs * Math.pow(2, attempt - 1);
5507
- logSdkTimingEvent("http.request", "retry_sleep_start", {
5508
- method,
5509
- path: timingPath,
5510
- attempt,
5511
- delay_ms: delay,
5512
- server_trace_id: traceId
5513
- });
5514
- await sleep3(delay);
5515
- }
5516
- this.abortController = new AbortController();
5517
- let timedOut = false;
5518
- const timeoutId = this.timeoutMs == null ? null : setTimeout(() => {
5519
- timedOut = true;
5520
- this.abortController?.abort();
5521
- }, this.timeoutMs);
5522
- const combinedSignal = signal ? anySignal([signal, this.abortController.signal]) : this.abortController.signal;
5523
- const attemptStart = nowMs();
5524
- try {
5525
- const response = await (0, import_undici.fetch)(url, {
5526
- method,
5527
- headers,
5528
- body,
5529
- signal: combinedSignal
5530
- });
5531
- if (timeoutId != null) clearTimeout(timeoutId);
5532
- logSdkTiming("http.request", "headers", attemptStart, {
5533
- method,
5534
- path: timingPath,
5535
- status: response.status,
5536
- attempt,
5537
- server_trace_id: traceId
5538
- });
5539
- if (response.ok) {
5540
- logSdkTiming("http.request", "complete", operationStart, {
5541
- method,
5542
- path: timingPath,
5543
- status: response.status,
5544
- attempts: attempt + 1,
5545
- server_trace_id: traceId
5546
- });
5547
- return { response, traceId };
5548
- }
5549
- if (retryableStatusCodes.has(response.status) && attempt < this.maxRetries) {
5550
- lastError = new RemoteAPIError(
5551
- response.status,
5552
- await response.text().catch(() => "")
5553
- );
5554
- logSdkTimingEvent("http.request", "retryable_status", {
5555
- method,
5556
- path: timingPath,
5557
- status: response.status,
5558
- attempt,
5559
- server_trace_id: traceId
5560
- });
5561
- continue;
5562
- }
5563
- if (allowHttpErrors || allowedErrorStatusCodes.has(response.status)) {
5564
- logSdkTiming("http.request", "complete", operationStart, {
5565
- method,
5566
- path: timingPath,
5567
- status: response.status,
5568
- attempts: attempt + 1,
5569
- server_trace_id: traceId
5570
- });
5571
- return { response, traceId };
5572
- }
5573
- const errorBody = await response.text().catch(() => "");
5574
- throwMappedError(response.status, errorBody, path3);
5575
- } catch (err) {
5576
- if (timeoutId != null) clearTimeout(timeoutId);
5577
- if (err instanceof RemoteAPIError || err instanceof SandboxNotFoundError || err instanceof PoolNotFoundError || err instanceof PoolInUseError) {
5578
- throw err;
5579
- }
5580
- if (signal?.aborted && !timedOut) {
5581
- throw new SandboxConnectionError("request aborted by caller", {
5582
- cause: err
5583
- });
5584
- }
5585
- lastError = err instanceof Error ? err : new Error(String(err));
5586
- logSdkTiming("http.request", "error", attemptStart, {
5587
- method,
5588
- path: timingPath,
5589
- attempt,
5590
- server_trace_id: traceId,
5591
- error: timedOut ? `request timed out after ${this.timeoutMs}ms` : describeError(err)
5592
- });
5593
- if (attempt >= this.maxRetries) {
5594
- const detail = timedOut ? `request timed out after ${this.timeoutMs}ms` : describeError(err);
5595
- throw new SandboxConnectionError(detail, { cause: err });
5596
- }
5597
- }
5598
- }
5599
- throw new SandboxConnectionError(
5600
- lastError ? describeError(lastError) : "request failed",
5601
- { cause: lastError }
5346
+ const request = await serializeRequest(method, path3, options);
5347
+ const raw = await callNative(() => this.client().request(request));
5348
+ const response = new Response(
5349
+ [204, 205, 304].includes(raw.status) ? null : Uint8Array.from(raw.data).buffer,
5350
+ { status: raw.status, headers: JSON.parse(raw.headersJson) }
5602
5351
  );
5352
+ return Object.assign(response, { traceId: raw.traceId });
5603
5353
  }
5604
- };
5605
- }
5606
- });
5607
-
5608
- // src/sse.ts
5609
- async function* parseSSEMessages(stream, signal) {
5610
- const reader = stream.getReader();
5611
- const decoder = new TextDecoder();
5612
- let buffer = "";
5613
- try {
5614
- while (true) {
5615
- if (signal?.aborted) break;
5616
- const { done, value } = await reader.read();
5617
- if (done) break;
5618
- buffer += decoder.decode(value, { stream: true });
5619
- const parts = buffer.split(/\r?\n\r?\n/);
5620
- buffer = parts.pop() ?? "";
5621
- for (const part of parts) {
5622
- const lines = part.split(/\r?\n/);
5623
- const dataLines = [];
5624
- let event;
5625
- let id;
5626
- for (const line of lines) {
5627
- if (!line || line.startsWith(":")) continue;
5628
- const separator = line.indexOf(":");
5629
- const field = separator === -1 ? line : line.slice(0, separator);
5630
- let value2 = separator === -1 ? "" : line.slice(separator + 1);
5631
- if (value2.startsWith(" ")) {
5632
- value2 = value2.slice(1);
5633
- }
5634
- if (field === "data") {
5635
- dataLines.push(value2);
5636
- } else if (field === "event") {
5637
- event = value2;
5638
- } else if (field === "id") {
5639
- id = value2;
5640
- }
5641
- }
5642
- if (dataLines.length > 0 || event || id) {
5643
- yield { data: dataLines.join("\n"), event, id };
5644
- }
5354
+ async requestJson(method, path3) {
5355
+ const response = await this.requestResponse(method, path3);
5356
+ const text = await response.text();
5357
+ const value = text ? JSON.parse(text) : null;
5358
+ return Object.assign(value ?? {}, { traceId: response.traceId });
5645
5359
  }
5646
- }
5647
- } finally {
5648
- reader.releaseLock();
5649
- }
5650
- }
5651
- async function* parseSSEStream(stream, signal) {
5652
- for await (const message of parseSSEMessages(stream, signal)) {
5653
- if (!message.data) continue;
5654
- try {
5655
- yield JSON.parse(message.data);
5656
- } catch {
5657
- }
5658
- }
5659
- }
5660
- var init_sse = __esm({
5661
- "src/sse.ts"() {
5662
- "use strict";
5663
- init_cjs_shims();
5360
+ async *stream(method, path3, signal) {
5361
+ if (signal?.aborted) return;
5362
+ const request = await serializeRequest(method, path3, { headers: { Accept: "text/event-stream" } });
5363
+ yield* nativeEventStream((emit) => this.client().stream(request, emit), void 0, signal);
5364
+ }
5365
+ };
5664
5366
  }
5665
5367
  });
5666
5368
 
@@ -5763,11 +5465,10 @@ var init_cloud_client = __esm({
5763
5465
  init_cjs_shims();
5764
5466
  import_nanoid = require("nanoid");
5765
5467
  init_defaults();
5766
- init_http();
5468
+ init_native_cloud();
5767
5469
  init_models();
5768
- init_sse();
5769
5470
  CloudClient = class _CloudClient {
5770
- http;
5471
+ transport;
5771
5472
  organizationId;
5772
5473
  projectId;
5773
5474
  namespace;
@@ -5775,20 +5476,22 @@ var init_cloud_client = __esm({
5775
5476
  this.organizationId = options?.organizationId;
5776
5477
  this.projectId = options?.projectId;
5777
5478
  this.namespace = options?.namespace ?? NAMESPACE;
5778
- this.http = new HttpClient({
5479
+ this.transport = new NativeCloudTransport({
5779
5480
  baseUrl: options?.apiUrl ?? API_URL,
5780
5481
  apiKey: options?.apiKey ?? API_KEY,
5781
5482
  organizationId: this.organizationId,
5782
5483
  projectId: this.projectId,
5783
5484
  maxRetries: options?.maxRetries ?? MAX_RETRIES,
5784
- retryBackoffMs: options?.retryBackoffMs ?? RETRY_BACKOFF_MS
5485
+ retryBackoffMs: options?.retryBackoffMs ?? RETRY_BACKOFF_MS,
5486
+ timeoutMs: DEFAULT_HTTP_TIMEOUT_MS,
5487
+ userAgent: `tensorlake-typescript-sdk/${SDK_VERSION}`
5785
5488
  });
5786
5489
  }
5787
5490
  static forCloud(options) {
5788
5491
  return new _CloudClient(options);
5789
5492
  }
5790
5493
  close() {
5791
- this.http.close();
5494
+ this.transport.close();
5792
5495
  }
5793
5496
  async upsertApplication(manifest, codeZip, upgradeRunningRequests = false) {
5794
5497
  const applicationManifest = { ...manifest };
@@ -5816,18 +5519,18 @@ var init_cloud_client = __esm({
5816
5519
  "upgrade_requests_to_latest_code",
5817
5520
  String(upgradeRunningRequests)
5818
5521
  );
5819
- await this.http.requestResponse("POST", this.namespacePath("applications"), {
5522
+ await this.transport.requestResponse("POST", this.namespacePath("applications"), {
5820
5523
  body: form
5821
5524
  });
5822
5525
  }
5823
5526
  async deleteApplication(applicationName) {
5824
- await this.http.requestResponse(
5527
+ await this.transport.requestResponse(
5825
5528
  "DELETE",
5826
5529
  this.namespacePath(`applications/${encodeURIComponent(applicationName)}`)
5827
5530
  );
5828
5531
  }
5829
5532
  async deleteSandboxImage(imageName) {
5830
- await this.http.requestResponse(
5533
+ await this.transport.requestResponse(
5831
5534
  "DELETE",
5832
5535
  this.namespacePath(`sandbox-images/${encodeURIComponent(imageName)}`)
5833
5536
  );
@@ -5846,10 +5549,10 @@ var init_cloud_client = __esm({
5846
5549
  options?.organizationId,
5847
5550
  options?.projectId
5848
5551
  );
5849
- const response = await this.http.requestResponse(
5552
+ const response = await this.transport.requestResponse(
5850
5553
  "GET",
5851
5554
  `${base}/by-name/${encodeURIComponent(imageName)}`,
5852
- { allowedErrorStatusCodes: /* @__PURE__ */ new Set([404]) }
5555
+ { statusOnlyCodes: /* @__PURE__ */ new Set([404]) }
5853
5556
  );
5854
5557
  if (response.status === 404) {
5855
5558
  return null;
@@ -5871,7 +5574,7 @@ var init_cloud_client = __esm({
5871
5574
  let path3 = `${base}?pageSize=100`;
5872
5575
  const templates = [];
5873
5576
  while (path3 !== null) {
5874
- const page = await this.http.requestJson(
5577
+ const page = await this.transport.requestJson(
5875
5578
  "GET",
5876
5579
  path3
5877
5580
  );
@@ -5884,7 +5587,7 @@ var init_cloud_client = __esm({
5884
5587
  return templates;
5885
5588
  }
5886
5589
  async applications() {
5887
- const raw = await this.http.requestJson(
5590
+ const raw = await this.transport.requestJson(
5888
5591
  "GET",
5889
5592
  this.namespacePath("applications")
5890
5593
  );
@@ -5893,7 +5596,7 @@ var init_cloud_client = __esm({
5893
5596
  );
5894
5597
  }
5895
5598
  async applicationManifest(applicationName) {
5896
- const raw = await this.http.requestJson(
5599
+ const raw = await this.transport.requestJson(
5897
5600
  "GET",
5898
5601
  this.namespacePath(`applications/${encodeURIComponent(applicationName)}`)
5899
5602
  );
@@ -5903,10 +5606,10 @@ var init_cloud_client = __esm({
5903
5606
  const path3 = this.namespacePath(
5904
5607
  `applications/${encodeURIComponent(applicationName)}`
5905
5608
  );
5906
- const response = inputs.length === 0 ? await this.http.requestResponse("POST", path3, {
5609
+ const response = inputs.length === 0 ? await this.transport.requestResponse("POST", path3, {
5907
5610
  body: new Uint8Array(),
5908
5611
  headers: { Accept: "application/json" }
5909
- }) : inputs.length === 1 && inputs[0].name === "0" ? await this.http.requestResponse("POST", path3, {
5612
+ }) : inputs.length === 1 && inputs[0].name === "0" ? await this.transport.requestResponse("POST", path3, {
5910
5613
  body: toRequestBody(inputs[0].data),
5911
5614
  headers: {
5912
5615
  Accept: "application/json",
@@ -5921,13 +5624,13 @@ var init_cloud_client = __esm({
5921
5624
  return requestId;
5922
5625
  }
5923
5626
  async waitOnRequestCompletion(applicationName, requestId) {
5924
- const stream = await this.http.requestStream(
5627
+ const stream = this.transport.stream(
5925
5628
  "GET",
5926
5629
  this.namespacePath(
5927
5630
  `applications/${encodeURIComponent(applicationName)}/requests/${encodeURIComponent(requestId)}/progress`
5928
5631
  )
5929
5632
  );
5930
- for await (const event of parseSSEStream(stream)) {
5633
+ for await (const event of stream) {
5931
5634
  if (Object.prototype.hasOwnProperty.call(event, "RequestFinished")) {
5932
5635
  return;
5933
5636
  }
@@ -5935,7 +5638,7 @@ var init_cloud_client = __esm({
5935
5638
  throw new Error("progress stream ended before request completion");
5936
5639
  }
5937
5640
  async requestMetadata(applicationName, requestId) {
5938
- const raw = await this.http.requestJson(
5641
+ const raw = await this.transport.requestJson(
5939
5642
  "GET",
5940
5643
  this.namespacePath(
5941
5644
  `applications/${encodeURIComponent(applicationName)}/requests/${encodeURIComponent(requestId)}`
@@ -5944,7 +5647,7 @@ var init_cloud_client = __esm({
5944
5647
  return fromSnakeKeys(raw);
5945
5648
  }
5946
5649
  async requestOutput(applicationName, requestId) {
5947
- const response = await this.http.requestResponse(
5650
+ const response = await this.transport.requestResponse(
5948
5651
  "GET",
5949
5652
  this.namespacePath(
5950
5653
  `applications/${encodeURIComponent(applicationName)}/requests/${encodeURIComponent(requestId)}/output`
@@ -5962,7 +5665,7 @@ var init_cloud_client = __esm({
5962
5665
  options?.organizationId,
5963
5666
  options?.projectId
5964
5667
  );
5965
- const raw = await this.http.requestJson("GET", base);
5668
+ const raw = await this.transport.requestJson("GET", base);
5966
5669
  const pageSize = Math.max(0, options?.pageSize ?? 100);
5967
5670
  return Object.assign(
5968
5671
  {
@@ -5977,7 +5680,7 @@ var init_cloud_client = __esm({
5977
5680
  options?.organizationId,
5978
5681
  options?.projectId
5979
5682
  );
5980
- const raw = await this.http.requestJson(
5683
+ const raw = await this.transport.requestJson(
5981
5684
  "GET",
5982
5685
  `${base}/${encodeURIComponent(secretId)}`
5983
5686
  );
@@ -6002,24 +5705,24 @@ var init_cloud_client = __esm({
6002
5705
  options?.organizationId,
6003
5706
  options?.projectId
6004
5707
  );
6005
- await this.http.requestResponse(
5708
+ await this.transport.requestResponse(
6006
5709
  "DELETE",
6007
5710
  `${base}/${encodeURIComponent(secretId)}`
6008
5711
  );
6009
5712
  }
6010
5713
  async upsertSecret(base, secret) {
6011
- let response = await this.http.requestResponse("POST", base, {
5714
+ let response = await this.transport.requestResponse("POST", base, {
6012
5715
  json: secret,
6013
5716
  headers: { "Idempotency-Key": (0, import_nanoid.nanoid)() },
6014
- allowedErrorStatusCodes: /* @__PURE__ */ new Set([409])
5717
+ statusOnlyCodes: /* @__PURE__ */ new Set([409])
6015
5718
  });
6016
5719
  if (response.status === 409) {
6017
5720
  const prefix = base.slice(0, -"/secrets".length);
6018
- const existing = await this.http.requestJson(
5721
+ const existing = await this.transport.requestJson(
6019
5722
  "GET",
6020
5723
  `${prefix}/secret-names/${encodeURIComponent(secret.name)}`
6021
5724
  );
6022
- response = await this.http.requestResponse(
5725
+ response = await this.transport.requestResponse(
6023
5726
  "POST",
6024
5727
  `${base}/${encodeURIComponent(existing.id)}/versions`,
6025
5728
  {
@@ -6045,7 +5748,7 @@ var init_cloud_client = __esm({
6045
5748
  new Blob([toBlobPart(request.buildContext)]),
6046
5749
  "context.tar.gz"
6047
5750
  );
6048
- const response = await this.http.requestResponse(
5751
+ const response = await this.transport.requestResponse(
6049
5752
  "PUT",
6050
5753
  `${trimTrailingSlashes2(buildServicePath)}/builds`,
6051
5754
  { body: form }
@@ -6055,7 +5758,7 @@ var init_cloud_client = __esm({
6055
5758
  }
6056
5759
  async createApplicationBuild(buildServicePath, request, imageContexts) {
6057
5760
  const form = createApplicationBuildForm(request, imageContexts);
6058
- const response = await this.http.requestResponse(
5761
+ const response = await this.transport.requestResponse(
6059
5762
  "POST",
6060
5763
  trimTrailingSlashes2(buildServicePath),
6061
5764
  { body: form }
@@ -6064,39 +5767,39 @@ var init_cloud_client = __esm({
6064
5767
  return fromSnakeKeys(raw);
6065
5768
  }
6066
5769
  async applicationBuildInfo(buildServicePath, applicationBuildId) {
6067
- const raw = await this.http.requestJson(
5770
+ const raw = await this.transport.requestJson(
6068
5771
  "GET",
6069
5772
  `${trimTrailingSlashes2(buildServicePath)}/${encodeURIComponent(applicationBuildId)}`
6070
5773
  );
6071
5774
  return fromSnakeKeys(raw);
6072
5775
  }
6073
5776
  async cancelApplicationBuild(buildServicePath, applicationBuildId) {
6074
- const raw = await this.http.requestJson(
5777
+ const raw = await this.transport.requestJson(
6075
5778
  "POST",
6076
5779
  `${trimTrailingSlashes2(buildServicePath)}/${encodeURIComponent(applicationBuildId)}/cancel`
6077
5780
  );
6078
5781
  return fromSnakeKeys(raw);
6079
5782
  }
6080
5783
  async buildInfo(buildServicePath, buildId) {
6081
- const raw = await this.http.requestJson(
5784
+ const raw = await this.transport.requestJson(
6082
5785
  "GET",
6083
5786
  `${trimTrailingSlashes2(buildServicePath)}/builds/${encodeURIComponent(buildId)}`
6084
5787
  );
6085
5788
  return fromSnakeKeys(raw);
6086
5789
  }
6087
5790
  async cancelBuild(buildServicePath, buildId) {
6088
- await this.http.requestResponse(
5791
+ await this.transport.requestResponse(
6089
5792
  "POST",
6090
5793
  `${trimTrailingSlashes2(buildServicePath)}/builds/${encodeURIComponent(buildId)}/cancel`
6091
5794
  );
6092
5795
  }
6093
5796
  async *streamBuildLogs(buildServicePath, buildId, signal) {
6094
- const stream = await this.http.requestStream(
5797
+ const stream = this.transport.stream(
6095
5798
  "GET",
6096
5799
  `${trimTrailingSlashes2(buildServicePath)}/builds/${encodeURIComponent(buildId)}/logs`,
6097
- { signal }
5800
+ signal
6098
5801
  );
6099
- for await (const event of parseSSEStream(stream, signal)) {
5802
+ for await (const event of stream) {
6100
5803
  yield fromSnakeKeys(event);
6101
5804
  }
6102
5805
  }
@@ -6109,7 +5812,7 @@ var init_cloud_client = __esm({
6109
5812
  input.name
6110
5813
  );
6111
5814
  }
6112
- return this.http.requestResponse("POST", path3, {
5815
+ return this.transport.requestResponse("POST", path3, {
6113
5816
  body: form,
6114
5817
  headers: { Accept: "application/json" }
6115
5818
  });
@@ -6118,10 +5821,10 @@ var init_cloud_client = __esm({
6118
5821
  return `/v1/namespaces/${encodeURIComponent(this.namespace)}/${subpath.replace(/^\/+/, "")}`;
6119
5822
  }
6120
5823
  async existingApplicationPublicEndpointId(applicationName) {
6121
- const response = await this.http.requestResponse(
5824
+ const response = await this.transport.requestResponse(
6122
5825
  "GET",
6123
5826
  this.namespacePath(`applications/${encodeURIComponent(applicationName)}`),
6124
- { allowedErrorStatusCodes: /* @__PURE__ */ new Set([404]) }
5827
+ { statusOnlyCodes: /* @__PURE__ */ new Set([404]) }
6125
5828
  );
6126
5829
  if (response.status === 404) {
6127
5830
  return void 0;