@daytonaio/sdk 0.170.0 → 0.171.0-alpha.3

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 (237) hide show
  1. package/LICENSE +190 -0
  2. package/cjs/CodeInterpreter.d.ts +95 -0
  3. package/cjs/CodeInterpreter.d.ts.map +1 -0
  4. package/cjs/CodeInterpreter.js +297 -0
  5. package/cjs/CodeInterpreter.js.map +1 -0
  6. package/cjs/ComputerUse.d.ts +539 -0
  7. package/cjs/ComputerUse.d.ts.map +1 -0
  8. package/cjs/ComputerUse.js +808 -0
  9. package/cjs/ComputerUse.js.map +1 -0
  10. package/cjs/Daytona.d.ts +355 -0
  11. package/cjs/Daytona.d.ts.map +1 -0
  12. package/cjs/Daytona.js +527 -0
  13. package/cjs/Daytona.js.map +1 -0
  14. package/cjs/FileSystem.d.ts +371 -0
  15. package/cjs/FileSystem.d.ts.map +1 -0
  16. package/cjs/FileSystem.js +489 -0
  17. package/cjs/FileSystem.js.map +1 -0
  18. package/cjs/Git.d.ts +203 -0
  19. package/cjs/Git.d.ts.map +1 -0
  20. package/cjs/Git.js +326 -0
  21. package/cjs/Git.js.map +1 -0
  22. package/cjs/Image.d.ts +265 -0
  23. package/cjs/Image.d.ts.map +1 -0
  24. package/cjs/Image.js +586 -0
  25. package/cjs/Image.js.map +1 -0
  26. package/cjs/LspServer.d.ts +172 -0
  27. package/cjs/LspServer.d.ts.map +1 -0
  28. package/cjs/LspServer.js +259 -0
  29. package/cjs/LspServer.js.map +1 -0
  30. package/cjs/ObjectStorage.d.ts +79 -0
  31. package/cjs/ObjectStorage.d.ts.map +1 -0
  32. package/cjs/ObjectStorage.js +199 -0
  33. package/cjs/ObjectStorage.js.map +1 -0
  34. package/cjs/Process.d.ts +490 -0
  35. package/cjs/Process.d.ts.map +1 -0
  36. package/cjs/Process.js +647 -0
  37. package/cjs/Process.js.map +1 -0
  38. package/cjs/PtyHandle.d.ts +155 -0
  39. package/cjs/PtyHandle.d.ts.map +1 -0
  40. package/cjs/PtyHandle.js +416 -0
  41. package/cjs/PtyHandle.js.map +1 -0
  42. package/cjs/README.md +180 -0
  43. package/cjs/Sandbox.d.ts +476 -0
  44. package/cjs/Sandbox.d.ts.map +1 -0
  45. package/cjs/Sandbox.js +905 -0
  46. package/cjs/Sandbox.js.map +1 -0
  47. package/cjs/Snapshot.d.ts +140 -0
  48. package/cjs/Snapshot.d.ts.map +1 -0
  49. package/cjs/Snapshot.js +248 -0
  50. package/cjs/Snapshot.js.map +1 -0
  51. package/cjs/Volume.d.ts +84 -0
  52. package/cjs/Volume.d.ts.map +1 -0
  53. package/cjs/Volume.js +119 -0
  54. package/cjs/Volume.js.map +1 -0
  55. package/cjs/__tests__/helpers.d.ts +6 -0
  56. package/cjs/__tests__/helpers.d.ts.map +1 -0
  57. package/cjs/__tests__/helpers.js +26 -0
  58. package/cjs/__tests__/helpers.js.map +1 -0
  59. package/cjs/errors/DaytonaError.d.ts +171 -0
  60. package/cjs/errors/DaytonaError.d.ts.map +1 -0
  61. package/cjs/errors/DaytonaError.js +258 -0
  62. package/cjs/errors/DaytonaError.js.map +1 -0
  63. package/cjs/index.d.ts +22 -0
  64. package/cjs/index.d.ts.map +1 -0
  65. package/cjs/index.js +49 -0
  66. package/cjs/index.js.map +1 -0
  67. package/cjs/package.json +3 -0
  68. package/cjs/types/Charts.d.ts +38 -0
  69. package/cjs/types/Charts.d.ts.map +1 -0
  70. package/cjs/types/Charts.js +37 -0
  71. package/cjs/types/Charts.js.map +1 -0
  72. package/cjs/types/CodeInterpreter.d.ts +77 -0
  73. package/cjs/types/CodeInterpreter.d.ts.map +1 -0
  74. package/cjs/types/CodeInterpreter.js +7 -0
  75. package/cjs/types/CodeInterpreter.js.map +1 -0
  76. package/cjs/types/ExecuteResponse.d.ts +26 -0
  77. package/cjs/types/ExecuteResponse.d.ts.map +1 -0
  78. package/cjs/types/ExecuteResponse.js +7 -0
  79. package/cjs/types/ExecuteResponse.js.map +1 -0
  80. package/cjs/types/Pty.d.ts +48 -0
  81. package/cjs/types/Pty.d.ts.map +1 -0
  82. package/cjs/types/Pty.js +7 -0
  83. package/cjs/types/Pty.js.map +1 -0
  84. package/cjs/utils/Binary.d.ts +39 -0
  85. package/cjs/utils/Binary.d.ts.map +1 -0
  86. package/cjs/utils/Binary.js +168 -0
  87. package/cjs/utils/Binary.js.map +1 -0
  88. package/cjs/utils/FileTransfer.d.ts +15 -0
  89. package/cjs/utils/FileTransfer.d.ts.map +1 -0
  90. package/cjs/utils/FileTransfer.js +261 -0
  91. package/cjs/utils/FileTransfer.js.map +1 -0
  92. package/cjs/utils/Import.d.ts +125 -0
  93. package/cjs/utils/Import.d.ts.map +1 -0
  94. package/cjs/utils/Import.js +112 -0
  95. package/cjs/utils/Import.js.map +1 -0
  96. package/cjs/utils/Multipart.d.ts +29 -0
  97. package/cjs/utils/Multipart.d.ts.map +1 -0
  98. package/cjs/utils/Multipart.js +115 -0
  99. package/cjs/utils/Multipart.js.map +1 -0
  100. package/cjs/utils/Runtime.d.ts +44 -0
  101. package/cjs/utils/Runtime.d.ts.map +1 -0
  102. package/cjs/utils/Runtime.js +95 -0
  103. package/cjs/utils/Runtime.js.map +1 -0
  104. package/cjs/utils/Stream.d.ts +20 -0
  105. package/cjs/utils/Stream.d.ts.map +1 -0
  106. package/cjs/utils/Stream.js +364 -0
  107. package/cjs/utils/Stream.js.map +1 -0
  108. package/cjs/utils/WebSocket.d.ts +10 -0
  109. package/cjs/utils/WebSocket.d.ts.map +1 -0
  110. package/cjs/utils/WebSocket.js +26 -0
  111. package/cjs/utils/WebSocket.js.map +1 -0
  112. package/cjs/utils/otel.decorator.d.ts +83 -0
  113. package/cjs/utils/otel.decorator.d.ts.map +1 -0
  114. package/cjs/utils/otel.decorator.js +141 -0
  115. package/cjs/utils/otel.decorator.js.map +1 -0
  116. package/esm/CodeInterpreter.d.ts +95 -0
  117. package/esm/CodeInterpreter.d.ts.map +1 -0
  118. package/esm/CodeInterpreter.js +292 -0
  119. package/esm/CodeInterpreter.js.map +1 -0
  120. package/esm/ComputerUse.d.ts +539 -0
  121. package/esm/ComputerUse.d.ts.map +1 -0
  122. package/esm/ComputerUse.js +799 -0
  123. package/esm/ComputerUse.js.map +1 -0
  124. package/esm/Daytona.d.ts +355 -0
  125. package/esm/Daytona.d.ts.map +1 -0
  126. package/esm/Daytona.js +523 -0
  127. package/esm/Daytona.js.map +1 -0
  128. package/esm/FileSystem.d.ts +371 -0
  129. package/esm/FileSystem.d.ts.map +1 -0
  130. package/esm/FileSystem.js +485 -0
  131. package/esm/FileSystem.js.map +1 -0
  132. package/esm/Git.d.ts +203 -0
  133. package/esm/Git.d.ts.map +1 -0
  134. package/esm/Git.js +322 -0
  135. package/esm/Git.js.map +1 -0
  136. package/esm/Image.d.ts +265 -0
  137. package/esm/Image.d.ts.map +1 -0
  138. package/esm/Image.js +581 -0
  139. package/esm/Image.js.map +1 -0
  140. package/esm/LspServer.d.ts +172 -0
  141. package/esm/LspServer.d.ts.map +1 -0
  142. package/esm/LspServer.js +255 -0
  143. package/esm/LspServer.js.map +1 -0
  144. package/esm/ObjectStorage.d.ts +79 -0
  145. package/esm/ObjectStorage.d.ts.map +1 -0
  146. package/esm/ObjectStorage.js +195 -0
  147. package/esm/ObjectStorage.js.map +1 -0
  148. package/esm/Process.d.ts +490 -0
  149. package/esm/Process.d.ts.map +1 -0
  150. package/esm/Process.js +642 -0
  151. package/esm/Process.js.map +1 -0
  152. package/esm/PtyHandle.d.ts +155 -0
  153. package/esm/PtyHandle.d.ts.map +1 -0
  154. package/esm/PtyHandle.js +412 -0
  155. package/esm/PtyHandle.js.map +1 -0
  156. package/esm/README.md +180 -0
  157. package/esm/Sandbox.d.ts +476 -0
  158. package/esm/Sandbox.d.ts.map +1 -0
  159. package/esm/Sandbox.js +901 -0
  160. package/esm/Sandbox.js.map +1 -0
  161. package/esm/Snapshot.d.ts +140 -0
  162. package/esm/Snapshot.d.ts.map +1 -0
  163. package/esm/Snapshot.js +244 -0
  164. package/esm/Snapshot.js.map +1 -0
  165. package/esm/Volume.d.ts +84 -0
  166. package/esm/Volume.d.ts.map +1 -0
  167. package/esm/Volume.js +115 -0
  168. package/esm/Volume.js.map +1 -0
  169. package/esm/__tests__/helpers.d.ts +6 -0
  170. package/esm/__tests__/helpers.d.ts.map +1 -0
  171. package/esm/__tests__/helpers.js +20 -0
  172. package/esm/__tests__/helpers.js.map +1 -0
  173. package/esm/errors/DaytonaError.d.ts +171 -0
  174. package/esm/errors/DaytonaError.d.ts.map +1 -0
  175. package/esm/errors/DaytonaError.js +243 -0
  176. package/esm/errors/DaytonaError.js.map +1 -0
  177. package/esm/index.d.ts +22 -0
  178. package/esm/index.d.ts.map +1 -0
  179. package/esm/index.js +21 -0
  180. package/esm/index.js.map +1 -0
  181. package/esm/package.json +3 -0
  182. package/esm/types/Charts.d.ts +38 -0
  183. package/esm/types/Charts.d.ts.map +1 -0
  184. package/esm/types/Charts.js +33 -0
  185. package/esm/types/Charts.js.map +1 -0
  186. package/esm/types/CodeInterpreter.d.ts +77 -0
  187. package/esm/types/CodeInterpreter.d.ts.map +1 -0
  188. package/esm/types/CodeInterpreter.js +6 -0
  189. package/esm/types/CodeInterpreter.js.map +1 -0
  190. package/esm/types/ExecuteResponse.d.ts +26 -0
  191. package/esm/types/ExecuteResponse.d.ts.map +1 -0
  192. package/esm/types/ExecuteResponse.js +6 -0
  193. package/esm/types/ExecuteResponse.js.map +1 -0
  194. package/esm/types/Pty.d.ts +48 -0
  195. package/esm/types/Pty.d.ts.map +1 -0
  196. package/esm/types/Pty.js +6 -0
  197. package/esm/types/Pty.js.map +1 -0
  198. package/esm/utils/Binary.d.ts +39 -0
  199. package/esm/utils/Binary.d.ts.map +1 -0
  200. package/esm/utils/Binary.js +157 -0
  201. package/esm/utils/Binary.js.map +1 -0
  202. package/esm/utils/FileTransfer.d.ts +15 -0
  203. package/esm/utils/FileTransfer.d.ts.map +1 -0
  204. package/esm/utils/FileTransfer.js +254 -0
  205. package/esm/utils/FileTransfer.js.map +1 -0
  206. package/esm/utils/Import.d.ts +95 -0
  207. package/esm/utils/Import.d.ts.map +1 -0
  208. package/esm/utils/Import.js +77 -0
  209. package/esm/utils/Import.js.map +1 -0
  210. package/esm/utils/Multipart.d.ts +29 -0
  211. package/esm/utils/Multipart.d.ts.map +1 -0
  212. package/esm/utils/Multipart.js +109 -0
  213. package/esm/utils/Multipart.js.map +1 -0
  214. package/esm/utils/Runtime.d.ts +44 -0
  215. package/esm/utils/Runtime.d.ts.map +1 -0
  216. package/esm/utils/Runtime.js +89 -0
  217. package/esm/utils/Runtime.js.map +1 -0
  218. package/esm/utils/Stream.d.ts +20 -0
  219. package/esm/utils/Stream.d.ts.map +1 -0
  220. package/esm/utils/Stream.js +360 -0
  221. package/esm/utils/Stream.js.map +1 -0
  222. package/esm/utils/WebSocket.d.ts +10 -0
  223. package/esm/utils/WebSocket.d.ts.map +1 -0
  224. package/esm/utils/WebSocket.js +22 -0
  225. package/esm/utils/WebSocket.js.map +1 -0
  226. package/esm/utils/otel.decorator.d.ts +83 -0
  227. package/esm/utils/otel.decorator.d.ts.map +1 -0
  228. package/esm/utils/otel.decorator.js +136 -0
  229. package/esm/utils/otel.decorator.js.map +1 -0
  230. package/package.json +20 -8
  231. package/src/ComputerUse.d.ts +4 -4
  232. package/src/ComputerUse.js +4 -4
  233. package/src/Sandbox.d.ts +1 -18
  234. package/src/Sandbox.js +0 -29
  235. package/src/Sandbox.js.map +1 -1
  236. package/src/__tests__/helpers.js +0 -2
  237. package/src/__tests__/helpers.js.map +1 -1
@@ -0,0 +1,115 @@
1
+ "use strict";
2
+ /*
3
+ * Copyright 2025 Daytona Platforms Inc.
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+ Object.defineProperty(exports, "__esModule", { value: true });
7
+ exports.extractBoundary = extractBoundary;
8
+ exports.parseMultipart = parseMultipart;
9
+ exports.parseMultipartWithFormData = parseMultipartWithFormData;
10
+ exports.getHeader = getHeader;
11
+ const Binary_1 = require("./Binary");
12
+ /**
13
+ * Extracts the boundary from a Content-Type header
14
+ */
15
+ function extractBoundary(contentType) {
16
+ const match = /boundary="?([^";]+)"?/i.exec(contentType || '');
17
+ return match ? match[1] : null;
18
+ }
19
+ /**
20
+ * Extracts a parameter value from Content-Disposition header
21
+ */
22
+ function getDispositionParam(disposition, paramName) {
23
+ const match = disposition.match(new RegExp(`${paramName}\\*?=([^;]+)`, 'i'));
24
+ if (!match)
25
+ return undefined;
26
+ return match[1].replace(/^"|"$/g, '').trim();
27
+ }
28
+ /**
29
+ * Parses multipart/form-data or multipart/mixed response body
30
+ */
31
+ function parseMultipart(body, boundary) {
32
+ const encoder = new TextEncoder();
33
+ const dashBoundary = encoder.encode(`--${boundary}`);
34
+ const crlf = encoder.encode('\r\n');
35
+ const boundaryLine = (0, Binary_1.concatUint8Arrays)([dashBoundary, crlf]);
36
+ const boundaryPositions = (0, Binary_1.findAllBytes)(body, dashBoundary);
37
+ if (boundaryPositions.length === 0)
38
+ return [];
39
+ const parts = [];
40
+ for (let i = 0; i < boundaryPositions.length; i++) {
41
+ const start = boundaryPositions[i];
42
+ // Headers start after "--boundary\r\n"
43
+ const headerStart = (0, Binary_1.indexAfterSequence)(body, start, boundaryLine);
44
+ if (headerStart < 0)
45
+ continue;
46
+ // Part ends before next boundary
47
+ const nextBoundary = boundaryPositions[i + 1] ?? body.length;
48
+ let partEnd = nextBoundary - 2; // Remove trailing CRLF
49
+ if (partEnd < headerStart)
50
+ partEnd = headerStart;
51
+ // Find headers/body separator (\r\n\r\n)
52
+ const separator = (0, Binary_1.findBytesInRange)(body, headerStart, partEnd, encoder.encode('\r\n\r\n'));
53
+ if (separator < 0)
54
+ continue;
55
+ // Parse headers
56
+ const headersText = (0, Binary_1.utf8Decode)(body.subarray(headerStart, separator));
57
+ const headers = {};
58
+ headersText.split(/\r\n/).forEach((line) => {
59
+ const [key, ...valueParts] = line.split(':');
60
+ if (valueParts.length > 0) {
61
+ headers[key.trim().toLowerCase()] = valueParts.join(':').trim();
62
+ }
63
+ });
64
+ // Extract body
65
+ const dataStart = separator + 4;
66
+ const data = body.subarray(dataStart, partEnd);
67
+ // Extract name and filename from Content-Disposition
68
+ const disposition = headers['content-disposition'] || '';
69
+ const name = getDispositionParam(disposition, 'name');
70
+ const filename = getDispositionParam(disposition, 'filename');
71
+ parts.push({ name, filename, headers, data });
72
+ }
73
+ return parts;
74
+ }
75
+ /**
76
+ * Parses multipart response using browser's native FormData API
77
+ * This is more reliable than manual parsing when available
78
+ */
79
+ async function parseMultipartWithFormData(bodyBytes, contentType) {
80
+ const result = [];
81
+ // Create a Blob and parse with FormData API
82
+ const blob = new Blob([bodyBytes.slice()], { type: contentType });
83
+ const formData = await new Response(blob).formData();
84
+ // Process FormData entries (forEach is more universally supported than entries())
85
+ const filePromises = [];
86
+ formData.forEach((value, fieldName) => {
87
+ if ((0, Binary_1.isFile)(value)) {
88
+ filePromises.push((async () => {
89
+ const file = value;
90
+ const arrayBuffer = await file.arrayBuffer();
91
+ result.push({
92
+ fieldName,
93
+ filename: file.name,
94
+ contentType: file.type,
95
+ data: new Uint8Array(arrayBuffer),
96
+ });
97
+ })());
98
+ }
99
+ });
100
+ await Promise.all(filePromises);
101
+ return result;
102
+ }
103
+ /**
104
+ * Extracts a header value from response headers (case-insensitive)
105
+ */
106
+ function getHeader(headers, key) {
107
+ if (!headers)
108
+ return undefined;
109
+ const headerKey = Object.keys(headers).find((h) => h.toLowerCase() === key.toLowerCase());
110
+ if (!headerKey)
111
+ return undefined;
112
+ const value = headers[headerKey];
113
+ return Array.isArray(value) ? value[0] : value;
114
+ }
115
+ //# sourceMappingURL=Multipart.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"Multipart.js","sourceRoot":"","sources":["../../../../../../libs/sdk-typescript/src/utils/Multipart.ts"],"names":[],"mappings":";AAAA;;;GAGG;;AAcH,0CAGC;AAcD,wCAmDC;AAMD,gEA+BC;AAKD,8BAMC;AAhID,qC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,IAAI,UAAU,CAAC,WAAW,CAAC;iBAClC,CAAC,CAAA;YACJ,CAAC,CAAC,EAAE,CACL,CAAA;QACH,CAAC;IACH,CAAC,CAAC,CAAA;IAEF,MAAM,OAAO,CAAC,GAAG,CAAC,YAAY,CAAC,CAAA;IAC/B,OAAO,MAAM,CAAA;AACf,CAAC;AAED;;GAEG;AACH,SAAgB,SAAS,CAAC,OAAY,EAAE,GAAW;IACjD,IAAI,CAAC,OAAO;QAAE,OAAO,SAAS,CAAA;IAC9B,MAAM,SAAS,GAAG,MAAM,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,WAAW,EAAE,KAAK,GAAG,CAAC,WAAW,EAAE,CAAC,CAAA;IACzF,IAAI,CAAC,SAAS;QAAE,OAAO,SAAS,CAAA;IAChC,MAAM,KAAK,GAAG,OAAO,CAAC,SAAS,CAAC,CAAA;IAChC,OAAO,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,KAAK,CAAA;AAChD,CAAC"}
@@ -0,0 +1,44 @@
1
+ declare global {
2
+ /**
3
+ * In Deno this global exists and has a `version.deno` string;
4
+ * in all other runtimes it will be `undefined`.
5
+ */
6
+ var Deno: {
7
+ version: {
8
+ deno: string;
9
+ };
10
+ env: {
11
+ get(name: string): string | undefined;
12
+ toObject(): Record<string, string>;
13
+ };
14
+ } | undefined;
15
+ /**
16
+ * In Bun this global exists and has a `version.bun` string;
17
+ * in all other runtimes it will be `undefined`.
18
+ */
19
+ var Bun: {
20
+ version: {
21
+ bun: string;
22
+ };
23
+ file: (path: string) => File;
24
+ } | undefined;
25
+ }
26
+ export declare enum Runtime {
27
+ NODE = "node",
28
+ DENO = "deno",
29
+ BUN = "bun",
30
+ BROWSER = "browser",
31
+ SERVERLESS = "serverless",
32
+ UNKNOWN = "unknown"
33
+ }
34
+ export declare const RUNTIME: Runtime;
35
+ export declare function getEnvVar(name: string): string | undefined;
36
+ export declare class DaytonaEnvReader {
37
+ private readonly envLocalVars;
38
+ private readonly envVars;
39
+ constructor();
40
+ get(name: string): string | undefined;
41
+ private static parseFileVars;
42
+ }
43
+ export declare function isServerlessRuntime(): boolean;
44
+ //# sourceMappingURL=Runtime.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"Runtime.d.ts","sourceRoot":"","sources":["../../../../../../libs/sdk-typescript/src/utils/Runtime.ts"],"names":[],"mappings":"AAKA,OAAO,CAAC,MAAM,CAAC;IACb;;;OAGG;IACH,IAAI,IAAI,EACJ;QACE,OAAO,EAAE;YAAE,IAAI,EAAE,MAAM,CAAA;SAAE,CAAA;QACzB,GAAG,EAAE;YACH,GAAG,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,GAAG,SAAS,CAAA;YACrC,QAAQ,IAAI,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAA;SACnC,CAAA;KACF,GACD,SAAS,CAAA;IAEb;;;OAGG;IACH,IAAI,GAAG,EACH;QACE,OAAO,EAAE;YAAE,GAAG,EAAE,MAAM,CAAA;SAAE,CAAA;QACxB,IAAI,EAAE,CAAC,IAAI,EAAE,MAAM,KAAK,IAAI,CAAA;KAC7B,GACD,SAAS,CAAA;CACd;AAED,oBAAY,OAAO;IACjB,IAAI,SAAS;IACb,IAAI,SAAS;IACb,GAAG,QAAQ;IACX,OAAO,YAAY;IACnB,UAAU,eAAe;IACzB,OAAO,YAAY;CACpB;AAED,eAAO,MAAM,OAAO,SAWS,CAAA;AAE7B,wBAAgB,SAAS,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,GAAG,SAAS,CAS1D;AAED,qBAAa,gBAAgB;IAC3B,OAAO,CAAC,QAAQ,CAAC,YAAY,CAAwB;IACrD,OAAO,CAAC,QAAQ,CAAC,OAAO,CAAwB;;IAOhD,GAAG,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,GAAG,SAAS;IAarC,OAAO,CAAC,MAAM,CAAC,aAAa;CAQ7B;AAED,wBAAgB,mBAAmB,IAAI,OAAO,CAyB7C"}
@@ -0,0 +1,95 @@
1
+ "use strict";
2
+ /*
3
+ * Copyright 2025 Daytona Platforms Inc.
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+ Object.defineProperty(exports, "__esModule", { value: true });
7
+ exports.DaytonaEnvReader = exports.RUNTIME = exports.Runtime = void 0;
8
+ exports.getEnvVar = getEnvVar;
9
+ exports.isServerlessRuntime = isServerlessRuntime;
10
+ var Runtime;
11
+ (function (Runtime) {
12
+ Runtime["NODE"] = "node";
13
+ Runtime["DENO"] = "deno";
14
+ Runtime["BUN"] = "bun";
15
+ Runtime["BROWSER"] = "browser";
16
+ Runtime["SERVERLESS"] = "serverless";
17
+ Runtime["UNKNOWN"] = "unknown";
18
+ })(Runtime || (exports.Runtime = Runtime = {}));
19
+ exports.RUNTIME = typeof Deno !== 'undefined'
20
+ ? Runtime.DENO
21
+ : typeof Bun !== 'undefined' && !!Bun.version
22
+ ? Runtime.BUN
23
+ : isServerlessRuntime()
24
+ ? Runtime.SERVERLESS
25
+ : typeof window !== 'undefined'
26
+ ? Runtime.BROWSER
27
+ : typeof process !== 'undefined' && !!process.versions?.node
28
+ ? Runtime.NODE
29
+ : Runtime.UNKNOWN;
30
+ function getEnvVar(name) {
31
+ if (exports.RUNTIME === Runtime.NODE || exports.RUNTIME === Runtime.BUN) {
32
+ return process.env[name];
33
+ }
34
+ if (exports.RUNTIME === Runtime.DENO) {
35
+ return Deno.env.get(name);
36
+ }
37
+ return undefined;
38
+ }
39
+ class DaytonaEnvReader {
40
+ envLocalVars;
41
+ envVars;
42
+ constructor() {
43
+ this.envLocalVars = DaytonaEnvReader.parseFileVars('.env.local');
44
+ this.envVars = DaytonaEnvReader.parseFileVars('.env');
45
+ }
46
+ get(name) {
47
+ if (!name.startsWith('DAYTONA_')) {
48
+ throw new Error(`DaytonaEnvReader: variable name must start with 'DAYTONA_', got '${name}'`);
49
+ }
50
+ // 1. Runtime env
51
+ const runtimeVal = getEnvVar(name);
52
+ if (runtimeVal !== undefined)
53
+ return runtimeVal;
54
+ // 2. .env.local
55
+ if (name in this.envLocalVars)
56
+ return this.envLocalVars[name];
57
+ // 3. .env
58
+ return this.envVars[name];
59
+ }
60
+ static parseFileVars(path) {
61
+ if (exports.RUNTIME !== Runtime.NODE || typeof require === 'undefined')
62
+ return {};
63
+ const fs = require('fs');
64
+ if (!fs.existsSync(path))
65
+ return {};
66
+ const dotenv = require('dotenv');
67
+ const parsed = dotenv.parse(fs.readFileSync(path));
68
+ return Object.fromEntries(Object.entries(parsed).filter(([k]) => k.startsWith('DAYTONA_')));
69
+ }
70
+ }
71
+ exports.DaytonaEnvReader = DaytonaEnvReader;
72
+ function isServerlessRuntime() {
73
+ // Safely grab env vars, even if `process` is undeclared
74
+ const env = typeof process !== 'undefined' ? process.env : {};
75
+ // Worker-specific globals
76
+ const globalObj = globalThis;
77
+ return Boolean(
78
+ // Cloudflare Workers (V8 isolate API)
79
+ typeof globalObj.WebSocketPair === 'function' ||
80
+ // Cloudflare Pages
81
+ env.CF_PAGES === '1' ||
82
+ // AWS Lambda (incl. SAM local)
83
+ env.AWS_EXECUTION_ENV?.startsWith('AWS_Lambda') ||
84
+ env.LAMBDA_TASK_ROOT !== undefined ||
85
+ env.AWS_SAM_LOCAL === 'true' ||
86
+ // Azure Functions
87
+ env.FUNCTIONS_WORKER_RUNTIME !== undefined ||
88
+ // Google Cloud Functions / Cloud Run
89
+ (env.FUNCTION_TARGET !== undefined && env.FUNCTION_SIGNATURE_TYPE !== undefined) ||
90
+ // Vercel
91
+ env.VERCEL === '1' ||
92
+ // Netlify Functions
93
+ env.SITE_NAME !== undefined);
94
+ }
95
+ //# sourceMappingURL=Runtime.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"Runtime.js","sourceRoot":"","sources":["../../../../../../libs/sdk-typescript/src/utils/Runtime.ts"],"names":[],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BC;AAED,SAAgB,mBAAmB;IACjC,wDAAwD;IACxD,MAAM,GAAG,GAAG,OAAO,OAAO,KAAK,WAAW,CAAC,CAAC,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,CAAA;IAE7D,0BAA0B;IAC1B,MAAM,SAAS,GAAG,UAAiB,CAAA;IAEnC,OAAO,OAAO;IACZ,sCAAsC;IACtC,OAAO,SAAS,CAAC,aAAa,KAAK,UAAU;QAC3C,mBAAmB;QACnB,GAAG,CAAC,QAAQ,KAAK,GAAG;QACpB,+BAA+B;QAC/B,GAAG,CAAC,iBAAiB,EAAE,UAAU,CAAC,YAAY,CAAC;QAC/C,GAAG,CAAC,gBAAgB,KAAK,SAAS;QAClC,GAAG,CAAC,aAAa,KAAK,MAAM;QAC5B,kBAAkB;QAClB,GAAG,CAAC,wBAAwB,KAAK,SAAS;QAC1C,qCAAqC;QACrC,CAAC,GAAG,CAAC,eAAe,KAAK,SAAS,IAAI,GAAG,CAAC,uBAAuB,KAAK,SAAS,CAAC;QAChF,SAAS;QACT,GAAG,CAAC,MAAM,KAAK,GAAG;QAClB,oBAAoB;QACpB,GAAG,CAAC,SAAS,KAAK,SAAS,CAC9B,CAAA;AACH,CAAC"}
@@ -0,0 +1,20 @@
1
+ import WebSocket from 'isomorphic-ws';
2
+ /**
3
+ * Process a streaming response from fetch(), where getStream() returns a Fetch Response.
4
+ *
5
+ * @param getStream – zero-arg function that does `await fetch(...)` and returns the Response
6
+ * @param onChunk – called with each decoded UTF-8 chunk
7
+ * @param shouldTerminate – pollable; if true for two consecutive timeouts (or once if requireConsecutiveTermination=false), the loop breaks
8
+ * @param chunkTimeout – milliseconds to wait for a new chunk before calling shouldTerminate()
9
+ * @param requireConsecutiveTermination – whether you need two time-outs in a row to break
10
+ */
11
+ export declare function processStreamingResponse(getStream: () => Promise<Response>, onChunk: (chunk: string) => void, shouldTerminate: () => Promise<boolean>, chunkTimeout?: number, requireConsecutiveTermination?: boolean): Promise<void>;
12
+ /**
13
+ * Demultiplexes a WebSocket stream into separate stdout and stderr streams.
14
+ *
15
+ * @param socket - The WebSocket instance to demultiplex.
16
+ * @param onStdout - Callback function for stdout messages.
17
+ * @param onStderr - Callback function for stderr messages.
18
+ */
19
+ export declare function stdDemuxStream(ws: WebSocket, onStdout: (data: string) => void, onStderr: (data: string) => void): Promise<void>;
20
+ //# sourceMappingURL=Stream.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"Stream.d.ts","sourceRoot":"","sources":["../../../../../../libs/sdk-typescript/src/utils/Stream.ts"],"names":[],"mappings":"AAIA,OAAO,SAAS,MAAM,eAAe,CAAA;AAmBrC;;;;;;;;GAQG;AACH,wBAAsB,wBAAwB,CAC5C,SAAS,EAAE,MAAM,OAAO,CAAC,QAAQ,CAAC,EAClC,OAAO,EAAE,CAAC,KAAK,EAAE,MAAM,KAAK,IAAI,EAChC,eAAe,EAAE,MAAM,OAAO,CAAC,OAAO,CAAC,EACvC,YAAY,SAAO,EACnB,6BAA6B,UAAO,GACnC,OAAO,CAAC,IAAI,CAAC,CAoEf;AAED;;;;;;GAMG;AACH,wBAAgB,cAAc,CAC5B,EAAE,EAAE,SAAS,EACb,QAAQ,EAAE,CAAC,IAAI,EAAE,MAAM,KAAK,IAAI,EAChC,QAAQ,EAAE,CAAC,IAAI,EAAE,MAAM,KAAK,IAAI,GAC/B,OAAO,CAAC,IAAI,CAAC,CA2Pf"}
@@ -0,0 +1,364 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.processStreamingResponse = processStreamingResponse;
4
+ exports.stdDemuxStream = stdDemuxStream;
5
+ const Process_1 = require("../Process");
6
+ function isStreamTerminationError(err) {
7
+ if (!err || typeof err !== 'object')
8
+ return false;
9
+ const e = err;
10
+ // Typical Undici / fetch termination cases
11
+ if (e.name === 'AbortError')
12
+ return true;
13
+ if (typeof e.message === 'string' && /terminated/i.test(e.message))
14
+ return true;
15
+ if (e.code === 'UND_ERR_SOCKET')
16
+ return true;
17
+ // Look into nested causes, Undici often nests errors
18
+ if (e.cause)
19
+ return isStreamTerminationError(e.cause);
20
+ return false;
21
+ }
22
+ /**
23
+ * Process a streaming response from fetch(), where getStream() returns a Fetch Response.
24
+ *
25
+ * @param getStream – zero-arg function that does `await fetch(...)` and returns the Response
26
+ * @param onChunk – called with each decoded UTF-8 chunk
27
+ * @param shouldTerminate – pollable; if true for two consecutive timeouts (or once if requireConsecutiveTermination=false), the loop breaks
28
+ * @param chunkTimeout – milliseconds to wait for a new chunk before calling shouldTerminate()
29
+ * @param requireConsecutiveTermination – whether you need two time-outs in a row to break
30
+ */
31
+ async function processStreamingResponse(getStream, onChunk, shouldTerminate, chunkTimeout = 2000, requireConsecutiveTermination = true) {
32
+ const res = await getStream();
33
+ if (!res.body)
34
+ throw new Error('No streaming support');
35
+ const reader = res.body.getReader();
36
+ const decoder = new TextDecoder('utf-8');
37
+ const TIMEOUT = Symbol();
38
+ let exitCheckStreak = 0;
39
+ // Only one pending read promise at a time:
40
+ let readPromise = null;
41
+ try {
42
+ while (true) {
43
+ // Start a read if none in flight
44
+ if (!readPromise) {
45
+ readPromise = reader.read().then((r) => (r.done ? null : (r.value ?? new Uint8Array(0))));
46
+ }
47
+ // Race that single read against your timeout
48
+ const timeoutPromise = new Promise((r) => setTimeout(() => r(TIMEOUT), chunkTimeout));
49
+ const result = await Promise.race([readPromise, timeoutPromise]);
50
+ if (result === TIMEOUT) {
51
+ // no data yet, but the readPromise is still pending
52
+ const stop = await shouldTerminate();
53
+ if (stop) {
54
+ exitCheckStreak++;
55
+ if (!requireConsecutiveTermination || exitCheckStreak > 1) {
56
+ try {
57
+ await reader.cancel();
58
+ }
59
+ catch {
60
+ /* ignore */
61
+ }
62
+ readPromise = null;
63
+ break;
64
+ }
65
+ }
66
+ else {
67
+ exitCheckStreak = 0;
68
+ }
69
+ // loop again—but do NOT overwrite readPromise!
70
+ }
71
+ else {
72
+ // readPromise has resolved
73
+ readPromise = null;
74
+ if (result === null) {
75
+ // stream closed
76
+ break;
77
+ }
78
+ // valid chunk - use {stream: true} to buffer incomplete UTF-8 sequences
79
+ onChunk(decoder.decode(result, { stream: true }));
80
+ exitCheckStreak = 0;
81
+ }
82
+ }
83
+ }
84
+ catch (err) {
85
+ if (!isStreamTerminationError(err)) {
86
+ throw err;
87
+ }
88
+ }
89
+ finally {
90
+ // Flush any remaining buffered bytes from the decoder
91
+ const remaining = decoder.decode();
92
+ if (remaining) {
93
+ onChunk(remaining);
94
+ }
95
+ try {
96
+ await reader.cancel();
97
+ }
98
+ catch {
99
+ /* ignore */
100
+ }
101
+ }
102
+ }
103
+ /**
104
+ * Demultiplexes a WebSocket stream into separate stdout and stderr streams.
105
+ *
106
+ * @param socket - The WebSocket instance to demultiplex.
107
+ * @param onStdout - Callback function for stdout messages.
108
+ * @param onStderr - Callback function for stderr messages.
109
+ */
110
+ function stdDemuxStream(ws, onStdout, onStderr) {
111
+ return new Promise((resolve, reject) => {
112
+ // If running in a browser or any WebSocket supporting binaryType, use ArrayBuffer for binary data
113
+ if ('binaryType' in ws) {
114
+ ws.binaryType = 'arraybuffer'; // ensure binary frames yield ArrayBuffer, not Blob
115
+ }
116
+ // Separate decoders for stdout and stderr to maintain independent UTF-8 decoding state
117
+ const stdoutDecoder = new TextDecoder('utf-8');
118
+ const stderrDecoder = new TextDecoder('utf-8');
119
+ const buf = []; // Buffer to accumulate incoming chunks
120
+ let currentDataType = null; // Track current stream type
121
+ // Helper function to emit payload data
122
+ const emit = (payload) => {
123
+ if (payload.length === 0)
124
+ return;
125
+ // Use {stream: true} to buffer incomplete UTF-8 sequences for the next chunk
126
+ if (currentDataType === 'stdout') {
127
+ const text = stdoutDecoder.decode(payload, { stream: true });
128
+ onStdout(text);
129
+ }
130
+ else if (currentDataType === 'stderr') {
131
+ const text = stderrDecoder.decode(payload, { stream: true });
132
+ onStderr(text);
133
+ }
134
+ // If currentDataType is null, drop unlabeled bytes (shouldn't happen with proper labeling)
135
+ };
136
+ // Helper function to find a subarray within a larger array
137
+ const findSubarray = (haystack, needle) => {
138
+ if (needle.length === 0)
139
+ return 0;
140
+ if (haystack.length < needle.length)
141
+ return -1;
142
+ for (let i = 0; i <= haystack.length - needle.length; i++) {
143
+ let found = true;
144
+ for (let j = 0; j < needle.length; j++) {
145
+ if (haystack[i + j] !== needle[j]) {
146
+ found = false;
147
+ break;
148
+ }
149
+ }
150
+ if (found)
151
+ return i;
152
+ }
153
+ return -1;
154
+ };
155
+ // Event handler for incoming messages (Node: Buffer/ArrayBuffer/String; Browser: event.data etc.)
156
+ const handleMessage = (event) => {
157
+ // Normalize event/data between Node (ws) and browser WebSocket
158
+ const data = event && event instanceof Object && 'data' in event ? event.data : event;
159
+ try {
160
+ // Prepare a Uint8Array for the message data
161
+ let bytes;
162
+ if (typeof data === 'string') {
163
+ // Convert string to bytes for consistent byte-based demuxing
164
+ bytes = new TextEncoder().encode(data);
165
+ }
166
+ else if (data instanceof ArrayBuffer) {
167
+ bytes = new Uint8Array(data);
168
+ }
169
+ else if (ArrayBuffer.isView(data)) {
170
+ // Covers Node.js Buffer (Uint8Array subclass) and other TypedArrays
171
+ bytes = new Uint8Array(data.buffer, data.byteOffset, data.byteLength);
172
+ }
173
+ else if (data instanceof Blob) {
174
+ // Browser binary frames might be Blob if binaryType wasn't set in time. Convert to ArrayBuffer asynchronously.
175
+ data.arrayBuffer().then((buf) => {
176
+ try {
177
+ processChunk(new Uint8Array(buf));
178
+ }
179
+ catch (err) {
180
+ handleError(err);
181
+ }
182
+ }, (err) => {
183
+ handleError(err);
184
+ });
185
+ return; // will continue asynchronously once blob is read
186
+ }
187
+ else {
188
+ throw new Error(`Unsupported message data type: ${Object.prototype.toString.call(data)}`);
189
+ }
190
+ // Process the chunk
191
+ processChunk(bytes);
192
+ }
193
+ catch (err) {
194
+ // On any synchronous error in processing, clean up and reject.
195
+ cleanup();
196
+ try {
197
+ ws.close();
198
+ }
199
+ catch {
200
+ /* ignore if already closed */
201
+ }
202
+ reject(err);
203
+ }
204
+ };
205
+ // Process a chunk of data with buffering and safe region handling
206
+ const processChunk = (chunk) => {
207
+ if (chunk.length === 0)
208
+ return;
209
+ // Add chunk to buffer
210
+ buf.push(...chunk);
211
+ // Process as much as we can, preserving only bytes that could be part of a prefix
212
+ while (true) {
213
+ const bufArray = new Uint8Array(buf);
214
+ // Calculate how many bytes we can safely process
215
+ // We need to keep bytes that could potentially be the start of a prefix marker
216
+ let safeLen = buf.length;
217
+ // Check if the last few bytes could be part of a prefix marker
218
+ if (buf.length >= Process_1.MAX_PREFIX_LEN) {
219
+ // Check if the last byte could be part of a prefix (must be 0x01 or 0x02)
220
+ const lastByte = buf[buf.length - 1];
221
+ if (lastByte !== 0x01 && lastByte !== 0x02) {
222
+ // Last byte can't be part of any prefix, safe to process everything
223
+ safeLen = buf.length;
224
+ }
225
+ else if (buf.length >= Process_1.MAX_PREFIX_LEN + 1) {
226
+ // Check second-to-last byte if buffer is long enough
227
+ const secondLastByte = buf[buf.length - 2];
228
+ if (secondLastByte !== 0x01 && secondLastByte !== 0x02) {
229
+ // Second-to-last byte can't be part of any prefix, safe to process all but last byte
230
+ safeLen = buf.length - 1;
231
+ }
232
+ else {
233
+ // Both last bytes could be part of prefix, keep MAX_PREFIX_LEN - 1 bytes
234
+ safeLen = buf.length - (Process_1.MAX_PREFIX_LEN - 1);
235
+ }
236
+ }
237
+ else {
238
+ // Buffer is exactly MAX_PREFIX_LEN, keep MAX_PREFIX_LEN - 1 bytes
239
+ safeLen = buf.length - (Process_1.MAX_PREFIX_LEN - 1);
240
+ }
241
+ }
242
+ else {
243
+ // Buffer shorter than MAX_PREFIX_LEN, keep MAX_PREFIX_LEN - 1 bytes
244
+ safeLen = buf.length - (Process_1.MAX_PREFIX_LEN - 1);
245
+ }
246
+ if (safeLen <= 0) {
247
+ break;
248
+ }
249
+ // Find earliest next marker within the safe region
250
+ const safeRegion = bufArray.subarray(0, safeLen);
251
+ const stdoutIndex = findSubarray(safeRegion, Process_1.STDOUT_PREFIX_BYTES);
252
+ const stderrIndex = findSubarray(safeRegion, Process_1.STDERR_PREFIX_BYTES);
253
+ let nextIdx = -1;
254
+ let nextKind = null;
255
+ let nextLen = 0;
256
+ if (stdoutIndex !== -1 && (stderrIndex === -1 || stdoutIndex < stderrIndex)) {
257
+ nextIdx = stdoutIndex;
258
+ nextKind = 'stdout';
259
+ nextLen = Process_1.STDOUT_PREFIX_BYTES.length;
260
+ }
261
+ else if (stderrIndex !== -1) {
262
+ nextIdx = stderrIndex;
263
+ nextKind = 'stderr';
264
+ nextLen = Process_1.STDERR_PREFIX_BYTES.length;
265
+ }
266
+ if (nextIdx === -1) {
267
+ // No full marker in safe region: emit everything we safely can as payload
268
+ const toEmit = bufArray.subarray(0, safeLen);
269
+ emit(toEmit);
270
+ buf.splice(0, safeLen);
271
+ break; // wait for more data to resolve any partial marker at the end
272
+ }
273
+ // We found a marker. Emit preceding bytes (if any) under the current stream.
274
+ if (nextIdx > 0) {
275
+ const toEmit = bufArray.subarray(0, nextIdx);
276
+ emit(toEmit);
277
+ }
278
+ // Advance past the marker and switch current stream
279
+ buf.splice(0, nextIdx + nextLen);
280
+ currentDataType = nextKind;
281
+ }
282
+ };
283
+ // Event handler for errors
284
+ const handleError = (error) => {
285
+ // Convert Event or plain error to Error instance for consistency
286
+ const err = error && error instanceof Event ? new Error('WebSocket error') : error;
287
+ cleanup();
288
+ try {
289
+ ws.close();
290
+ }
291
+ catch {
292
+ /* ignore if already closed */
293
+ }
294
+ reject(err);
295
+ };
296
+ // Event handler for socket closure
297
+ const handleClose = () => {
298
+ // Flush any remaining buffered payload on clean close
299
+ if (buf.length > 0 && currentDataType) {
300
+ const remainingBytes = new Uint8Array(buf);
301
+ // Use {stream: false} or omit to flush any buffered incomplete UTF-8 sequences
302
+ if (currentDataType === 'stdout') {
303
+ const text = stdoutDecoder.decode(remainingBytes, { stream: false });
304
+ onStdout(text);
305
+ }
306
+ else if (currentDataType === 'stderr') {
307
+ const text = stderrDecoder.decode(remainingBytes, { stream: false });
308
+ onStderr(text);
309
+ }
310
+ }
311
+ else {
312
+ // Flush any remaining bytes in the decoders even if buf is empty
313
+ const stdoutFlushed = stdoutDecoder.decode();
314
+ const stderrFlushed = stderrDecoder.decode();
315
+ if (stdoutFlushed)
316
+ onStdout(stdoutFlushed);
317
+ if (stderrFlushed)
318
+ onStderr(stderrFlushed);
319
+ }
320
+ cleanup();
321
+ resolve();
322
+ };
323
+ // Cleanup function to remove all listeners to avoid memory leaks
324
+ const cleanup = () => {
325
+ if (ws.removeEventListener) {
326
+ // Browser (EventTarget) style cleanup
327
+ ws.removeEventListener('message', handleMessage);
328
+ ws.removeEventListener('error', handleError);
329
+ ws.removeEventListener('close', handleClose);
330
+ }
331
+ if (ws.off) {
332
+ // Node.js ws (EventEmitter) style cleanup (supported in Node 14+)
333
+ ws.off('message', handleMessage);
334
+ ws.off('error', handleError);
335
+ ws.off('close', handleClose);
336
+ }
337
+ else if (ws.removeListener) {
338
+ // Node.js ws fallback for older Node versions
339
+ ;
340
+ ws.removeListener('message', handleMessage);
341
+ ws.removeListener('error', handleError);
342
+ ws.removeListener('close', handleClose);
343
+ }
344
+ };
345
+ // Attach event listeners in a way compatible with both Node (EventEmitter) and browser (EventTarget):
346
+ if (ws.addEventListener) {
347
+ // Browser or WebSocket implementation with EventTarget interface
348
+ ws.addEventListener('message', handleMessage);
349
+ ws.addEventListener('error', handleError);
350
+ ws.addEventListener('close', handleClose);
351
+ }
352
+ else if (ws.on) {
353
+ // Node.js ws library (EventEmitter) interface
354
+ ws.on('message', handleMessage); // ws@8+ yields Buffer for text frames, which we handle via TextDecoder
355
+ ws.on('error', handleError);
356
+ ws.on('close', handleClose);
357
+ }
358
+ else {
359
+ // Unknown WebSocket interface - should not happen with isomorphic-ws
360
+ throw new Error('Unsupported WebSocket implementation');
361
+ }
362
+ });
363
+ }
364
+ //# sourceMappingURL=Stream.js.map