@nodetool-ai/sandbox-runtime 0.0.0-stage → 0.8.9-beta.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.
Files changed (218) hide show
  1. package/README.md +24 -2
  2. package/dist/.nodetool-build-stamp +1 -0
  3. package/dist/host-access-gate.d.ts +24 -0
  4. package/dist/host-access-gate.d.ts.map +1 -0
  5. package/dist/host-access-gate.js +31 -0
  6. package/dist/host-access-gate.js.map +1 -0
  7. package/dist/index.d.ts +32 -0
  8. package/dist/index.d.ts.map +1 -0
  9. package/dist/index.js +318 -0
  10. package/dist/index.js.map +1 -0
  11. package/dist/js-sandbox-worker/engine.d.ts +4 -0
  12. package/dist/js-sandbox-worker/engine.d.ts.map +1 -0
  13. package/dist/js-sandbox-worker/engine.js +82 -0
  14. package/dist/js-sandbox-worker/engine.js.map +1 -0
  15. package/dist/js-sandbox-worker/host.d.ts +136 -0
  16. package/dist/js-sandbox-worker/host.d.ts.map +1 -0
  17. package/dist/js-sandbox-worker/host.js +482 -0
  18. package/dist/js-sandbox-worker/host.js.map +1 -0
  19. package/dist/js-sandbox-worker/interpreter.d.ts +276 -0
  20. package/dist/js-sandbox-worker/interpreter.d.ts.map +1 -0
  21. package/dist/js-sandbox-worker/interpreter.js +1318 -0
  22. package/dist/js-sandbox-worker/interpreter.js.map +1 -0
  23. package/dist/js-sandbox-worker/protocol.d.ts +168 -0
  24. package/dist/js-sandbox-worker/protocol.d.ts.map +1 -0
  25. package/dist/js-sandbox-worker/protocol.js +217 -0
  26. package/dist/js-sandbox-worker/protocol.js.map +1 -0
  27. package/dist/js-sandbox-worker/worker-entry.d.ts +26 -0
  28. package/dist/js-sandbox-worker/worker-entry.d.ts.map +1 -0
  29. package/dist/js-sandbox-worker/worker-entry.js +308 -0
  30. package/dist/js-sandbox-worker/worker-entry.js.map +1 -0
  31. package/dist/limits.d.ts +77 -0
  32. package/dist/limits.d.ts.map +1 -0
  33. package/dist/limits.js +56 -0
  34. package/dist/limits.js.map +1 -0
  35. package/dist/sandbox-bootstrap-modules.d.ts +54 -0
  36. package/dist/sandbox-bootstrap-modules.d.ts.map +1 -0
  37. package/dist/sandbox-bootstrap-modules.js +104 -0
  38. package/dist/sandbox-bootstrap-modules.js.map +1 -0
  39. package/dist/sandbox-bytes.d.ts +43 -0
  40. package/dist/sandbox-bytes.d.ts.map +1 -0
  41. package/dist/sandbox-bytes.js +61 -0
  42. package/dist/sandbox-bytes.js.map +1 -0
  43. package/dist/sandbox-canvas-api.d.ts +30 -0
  44. package/dist/sandbox-canvas-api.d.ts.map +1 -0
  45. package/dist/sandbox-canvas-api.js +81 -0
  46. package/dist/sandbox-canvas-api.js.map +1 -0
  47. package/dist/sandbox-constants.d.ts +5 -0
  48. package/dist/sandbox-constants.d.ts.map +1 -0
  49. package/dist/sandbox-constants.js +13 -0
  50. package/dist/sandbox-constants.js.map +1 -0
  51. package/dist/sandbox-json-transport.d.ts +107 -0
  52. package/dist/sandbox-json-transport.d.ts.map +1 -0
  53. package/dist/sandbox-json-transport.js +324 -0
  54. package/dist/sandbox-json-transport.js.map +1 -0
  55. package/dist/timeline-capture.d.ts +21 -0
  56. package/dist/timeline-capture.d.ts.map +1 -0
  57. package/dist/timeline-capture.js +564 -0
  58. package/dist/timeline-capture.js.map +1 -0
  59. package/dist/utils/type-guards.d.ts +26 -0
  60. package/dist/utils/type-guards.d.ts.map +1 -0
  61. package/dist/utils/type-guards.js +44 -0
  62. package/dist/utils/type-guards.js.map +1 -0
  63. package/package.json +138 -4
  64. package/vendor/README.md +17 -0
  65. package/vendor/quickjs/LICENSE +21 -0
  66. package/vendor/quickjs/PROVENANCE.json +8 -0
  67. package/vendor/quickjs/adapter/fetch.d.ts +56 -0
  68. package/vendor/quickjs/adapter/fetch.js +140 -0
  69. package/vendor/quickjs/createTimeInterval.d.ts +9 -0
  70. package/vendor/quickjs/createTimeInterval.js +22 -0
  71. package/vendor/quickjs/createVirtualFileSystem.d.ts +13 -0
  72. package/vendor/quickjs/createVirtualFileSystem.js +191 -0
  73. package/vendor/quickjs/index.d.ts +77 -0
  74. package/vendor/quickjs/index.js +77 -0
  75. package/vendor/quickjs/loadAsyncQuickJs.d.ts +12 -0
  76. package/vendor/quickjs/loadAsyncQuickJs.js +66 -0
  77. package/vendor/quickjs/loadQuickJs.d.ts +12 -0
  78. package/vendor/quickjs/loadQuickJs.js +73 -0
  79. package/vendor/quickjs/modules/assert.d.ts +2 -0
  80. package/vendor/quickjs/modules/assert.js +47 -0
  81. package/vendor/quickjs/modules/buffer.d.ts +2 -0
  82. package/vendor/quickjs/modules/buffer.js +106 -0
  83. package/vendor/quickjs/modules/build/test-lib.js +2 -0
  84. package/vendor/quickjs/modules/events.d.ts +2 -0
  85. package/vendor/quickjs/modules/events.js +4 -0
  86. package/vendor/quickjs/modules/fs.d.ts +2 -0
  87. package/vendor/quickjs/modules/fs.js +76 -0
  88. package/vendor/quickjs/modules/fs_promises.d.ts +2 -0
  89. package/vendor/quickjs/modules/fs_promises.js +328 -0
  90. package/vendor/quickjs/modules/module.d.ts +2 -0
  91. package/vendor/quickjs/modules/module.js +33 -0
  92. package/vendor/quickjs/modules/nodeCompatibility/headers.d.ts +2 -0
  93. package/vendor/quickjs/modules/nodeCompatibility/headers.js +58 -0
  94. package/vendor/quickjs/modules/nodeCompatibility/request.d.ts +2 -0
  95. package/vendor/quickjs/modules/nodeCompatibility/request.js +5 -0
  96. package/vendor/quickjs/modules/nodeCompatibility/response.d.ts +2 -0
  97. package/vendor/quickjs/modules/nodeCompatibility/response.js +5 -0
  98. package/vendor/quickjs/modules/path.d.ts +2 -0
  99. package/vendor/quickjs/modules/path.js +504 -0
  100. package/vendor/quickjs/modules/process.d.ts +2 -0
  101. package/vendor/quickjs/modules/process.js +309 -0
  102. package/vendor/quickjs/modules/punycode.d.ts +2 -0
  103. package/vendor/quickjs/modules/punycode.js +443 -0
  104. package/vendor/quickjs/modules/querystring.d.ts +2 -0
  105. package/vendor/quickjs/modules/querystring.js +15 -0
  106. package/vendor/quickjs/modules/string_decoder.d.ts +2 -0
  107. package/vendor/quickjs/modules/string_decoder.js +223 -0
  108. package/vendor/quickjs/modules/timers.d.ts +2 -0
  109. package/vendor/quickjs/modules/timers.js +10 -0
  110. package/vendor/quickjs/modules/timers_promises.d.ts +2 -0
  111. package/vendor/quickjs/modules/timers_promises.js +40 -0
  112. package/vendor/quickjs/modules/url.d.ts +2 -0
  113. package/vendor/quickjs/modules/url.js +104 -0
  114. package/vendor/quickjs/modules/util.d.ts +2 -0
  115. package/vendor/quickjs/modules/util.js +233 -0
  116. package/vendor/quickjs/package.json +3 -0
  117. package/vendor/quickjs/sandbox/asyncVersion/createAsyncEvalCodeFunction.d.ts +4 -0
  118. package/vendor/quickjs/sandbox/asyncVersion/createAsyncEvalCodeFunction.js +76 -0
  119. package/vendor/quickjs/sandbox/asyncVersion/createAsyncValidateCodeFunction.d.ts +3 -0
  120. package/vendor/quickjs/sandbox/asyncVersion/createAsyncValidateCodeFunction.js +22 -0
  121. package/vendor/quickjs/sandbox/asyncVersion/executeAsyncSandboxFunction.d.ts +12 -0
  122. package/vendor/quickjs/sandbox/asyncVersion/executeAsyncSandboxFunction.js +9 -0
  123. package/vendor/quickjs/sandbox/asyncVersion/getAsyncModuleLoader.d.ts +4 -0
  124. package/vendor/quickjs/sandbox/asyncVersion/getAsyncModuleLoader.js +30 -0
  125. package/vendor/quickjs/sandbox/asyncVersion/modulePathNormalizerAsync.d.ts +2 -0
  126. package/vendor/quickjs/sandbox/asyncVersion/modulePathNormalizerAsync.js +12 -0
  127. package/vendor/quickjs/sandbox/asyncVersion/prepareAsyncNodeCompatibility.d.ts +3 -0
  128. package/vendor/quickjs/sandbox/asyncVersion/prepareAsyncNodeCompatibility.js +11 -0
  129. package/vendor/quickjs/sandbox/asyncVersion/prepareAsyncSandbox.d.ts +4 -0
  130. package/vendor/quickjs/sandbox/asyncVersion/prepareAsyncSandbox.js +10 -0
  131. package/vendor/quickjs/sandbox/expose/expose.d.ts +3 -0
  132. package/vendor/quickjs/sandbox/expose/expose.js +155 -0
  133. package/vendor/quickjs/sandbox/expose/isES2015Class.d.ts +1 -0
  134. package/vendor/quickjs/sandbox/expose/isES2015Class.js +4 -0
  135. package/vendor/quickjs/sandbox/expose/isObject.d.ts +1 -0
  136. package/vendor/quickjs/sandbox/expose/isObject.js +4 -0
  137. package/vendor/quickjs/sandbox/expose/pendingHostPromises.d.ts +6 -0
  138. package/vendor/quickjs/sandbox/expose/pendingHostPromises.js +40 -0
  139. package/vendor/quickjs/sandbox/getMaxIntervalAmount.d.ts +8 -0
  140. package/vendor/quickjs/sandbox/getMaxIntervalAmount.js +12 -0
  141. package/vendor/quickjs/sandbox/getMaxTimeoutAmount.d.ts +8 -0
  142. package/vendor/quickjs/sandbox/getMaxTimeoutAmount.js +12 -0
  143. package/vendor/quickjs/sandbox/handleEvalError.d.ts +2 -0
  144. package/vendor/quickjs/sandbox/handleEvalError.js +21 -0
  145. package/vendor/quickjs/sandbox/handleToNative/handleToNative.d.ts +9 -0
  146. package/vendor/quickjs/sandbox/handleToNative/handleToNative.js +153 -0
  147. package/vendor/quickjs/sandbox/handleToNative/serializer/index.d.ts +10 -0
  148. package/vendor/quickjs/sandbox/handleToNative/serializer/index.js +36 -0
  149. package/vendor/quickjs/sandbox/handleToNative/serializer/serializeArrayBuffer.d.ts +2 -0
  150. package/vendor/quickjs/sandbox/handleToNative/serializer/serializeArrayBuffer.js +4 -0
  151. package/vendor/quickjs/sandbox/handleToNative/serializer/serializeBuffer.d.ts +2 -0
  152. package/vendor/quickjs/sandbox/handleToNative/serializer/serializeBuffer.js +16 -0
  153. package/vendor/quickjs/sandbox/handleToNative/serializer/serializeDate.d.ts +2 -0
  154. package/vendor/quickjs/sandbox/handleToNative/serializer/serializeDate.js +16 -0
  155. package/vendor/quickjs/sandbox/handleToNative/serializer/serializeError.d.ts +2 -0
  156. package/vendor/quickjs/sandbox/handleToNative/serializer/serializeError.js +18 -0
  157. package/vendor/quickjs/sandbox/handleToNative/serializer/serializeHeaders.d.ts +2 -0
  158. package/vendor/quickjs/sandbox/handleToNative/serializer/serializeHeaders.js +17 -0
  159. package/vendor/quickjs/sandbox/handleToNative/serializer/serializeMap.d.ts +2 -0
  160. package/vendor/quickjs/sandbox/handleToNative/serializer/serializeMap.js +18 -0
  161. package/vendor/quickjs/sandbox/handleToNative/serializer/serializeSet.d.ts +2 -0
  162. package/vendor/quickjs/sandbox/handleToNative/serializer/serializeSet.js +16 -0
  163. package/vendor/quickjs/sandbox/handleToNative/serializer/serializeURLSearchParams.d.ts +2 -0
  164. package/vendor/quickjs/sandbox/handleToNative/serializer/serializeURLSearchParams.js +17 -0
  165. package/vendor/quickjs/sandbox/handleToNative/serializer/serializeUrl.d.ts +2 -0
  166. package/vendor/quickjs/sandbox/handleToNative/serializer/serializeUrl.js +17 -0
  167. package/vendor/quickjs/sandbox/helper.d.ts +2 -0
  168. package/vendor/quickjs/sandbox/helper.js +14 -0
  169. package/vendor/quickjs/sandbox/provide/provideConsole.d.ts +6 -0
  170. package/vendor/quickjs/sandbox/provide/provideConsole.js +53 -0
  171. package/vendor/quickjs/sandbox/provide/provideEnv.d.ts +3 -0
  172. package/vendor/quickjs/sandbox/provide/provideEnv.js +10 -0
  173. package/vendor/quickjs/sandbox/provide/provideFs.d.ts +4 -0
  174. package/vendor/quickjs/sandbox/provide/provideFs.js +159 -0
  175. package/vendor/quickjs/sandbox/provide/provideHttp.d.ts +9 -0
  176. package/vendor/quickjs/sandbox/provide/provideHttp.js +42 -0
  177. package/vendor/quickjs/sandbox/provide/provideTimingFunctions.d.ts +7 -0
  178. package/vendor/quickjs/sandbox/provide/provideTimingFunctions.js +119 -0
  179. package/vendor/quickjs/sandbox/setupFileSystem.d.ts +3 -0
  180. package/vendor/quickjs/sandbox/setupFileSystem.js +13 -0
  181. package/vendor/quickjs/sandbox/syncVersion/createEvalCodeFunction.d.ts +4 -0
  182. package/vendor/quickjs/sandbox/syncVersion/createEvalCodeFunction.js +76 -0
  183. package/vendor/quickjs/sandbox/syncVersion/createValidateCodeFunction.d.ts +3 -0
  184. package/vendor/quickjs/sandbox/syncVersion/createValidateCodeFunction.js +22 -0
  185. package/vendor/quickjs/sandbox/syncVersion/executeSandboxFunction.d.ts +12 -0
  186. package/vendor/quickjs/sandbox/syncVersion/executeSandboxFunction.js +9 -0
  187. package/vendor/quickjs/sandbox/syncVersion/getModuleLoader.d.ts +4 -0
  188. package/vendor/quickjs/sandbox/syncVersion/getModuleLoader.js +30 -0
  189. package/vendor/quickjs/sandbox/syncVersion/modulePathNormalizer.d.ts +2 -0
  190. package/vendor/quickjs/sandbox/syncVersion/modulePathNormalizer.js +12 -0
  191. package/vendor/quickjs/sandbox/syncVersion/prepareNodeCompatibility.d.ts +3 -0
  192. package/vendor/quickjs/sandbox/syncVersion/prepareNodeCompatibility.js +11 -0
  193. package/vendor/quickjs/sandbox/syncVersion/prepareSandbox.d.ts +4 -0
  194. package/vendor/quickjs/sandbox/syncVersion/prepareSandbox.js +10 -0
  195. package/vendor/quickjs/types/CodeFunctionInput.d.ts +12 -0
  196. package/vendor/quickjs/types/CodeFunctionInput.js +1 -0
  197. package/vendor/quickjs/types/ErrorResponse.d.ts +9 -0
  198. package/vendor/quickjs/types/ErrorResponse.js +1 -0
  199. package/vendor/quickjs/types/LoadQuickJsOptions.d.ts +3 -0
  200. package/vendor/quickjs/types/LoadQuickJsOptions.js +1 -0
  201. package/vendor/quickjs/types/OkResponse.d.ts +4 -0
  202. package/vendor/quickjs/types/OkResponse.js +1 -0
  203. package/vendor/quickjs/types/OkResponseCheck.d.ts +3 -0
  204. package/vendor/quickjs/types/OkResponseCheck.js +1 -0
  205. package/vendor/quickjs/types/Prettify.d.ts +3 -0
  206. package/vendor/quickjs/types/Prettify.js +1 -0
  207. package/vendor/quickjs/types/RuntimeOptions.d.ts +87 -0
  208. package/vendor/quickjs/types/RuntimeOptions.js +1 -0
  209. package/vendor/quickjs/types/SandboxEvalCode.d.ts +5 -0
  210. package/vendor/quickjs/types/SandboxEvalCode.js +1 -0
  211. package/vendor/quickjs/types/SandboxFunction.d.ts +16 -0
  212. package/vendor/quickjs/types/SandboxFunction.js +1 -0
  213. package/vendor/quickjs/types/SandboxOptions.d.ts +152 -0
  214. package/vendor/quickjs/types/SandboxOptions.js +1 -0
  215. package/vendor/quickjs/types/SandboxValidateCode.d.ts +9 -0
  216. package/vendor/quickjs/types/SandboxValidateCode.js +1 -0
  217. package/vendor/quickjs/types/Serializer.d.ts +2 -0
  218. package/vendor/quickjs/types/Serializer.js +1 -0
@@ -0,0 +1,191 @@
1
+ import { readFileSync } from 'node:fs';
2
+ import { join } from 'node:path';
3
+ import { fileURLToPath } from 'node:url';
4
+ import * as memfsPkg from 'memfs';
5
+ import assertModule from './modules/assert.js';
6
+ import bufferModule from './modules/buffer.js';
7
+ import eventModule from './modules/events.js';
8
+ import fsModule from './modules/fs.js';
9
+ import fsPromisesModule from './modules/fs_promises.js';
10
+ import moduleModule from './modules/module.js';
11
+ import compatibilityHeaders from './modules/nodeCompatibility/headers.js';
12
+ import compatibilityRequest from './modules/nodeCompatibility/request.js';
13
+ import compatibilityResponse from './modules/nodeCompatibility/response.js';
14
+ import pathModule from './modules/path.js';
15
+ import processModule from './modules/process.js';
16
+ import punycodeModule from './modules/punycode.js';
17
+ import queryStringModule from './modules/querystring.js';
18
+ import stringDecoderModule from './modules/string_decoder.js';
19
+ import timersModule from './modules/timers.js';
20
+ import timersPromisesModule from './modules/timers_promises.js';
21
+ import urlModule from './modules/url.js';
22
+ import utilModule from './modules/util.js';
23
+ const getCurrentDirname = () => {
24
+ if (typeof __dirname !== 'undefined') {
25
+ return __dirname;
26
+ }
27
+ const stack = new Error().stack ?? '';
28
+ const stackUrl = stack.match(/(file:\/\/[^\s)]+createVirtualFileSystem\.[cm]?js)/)?.[1];
29
+ if (stackUrl) {
30
+ return fileURLToPath(new URL('.', stackUrl));
31
+ }
32
+ return process.cwd();
33
+ };
34
+ const memfsCompat = memfsPkg;
35
+ const getMemfs = () => (memfsCompat.memfs ?? memfsCompat.default?.memfs ?? memfsCompat.default);
36
+ /**
37
+ * Create the virtual file system for the sandbox
38
+ * Creates a node_modules folder with packages and ensures the src folder
39
+ *
40
+ * @param runtimeOptions
41
+ * @returns filesystem fs and volume vol
42
+ */
43
+ export const createVirtualFileSystem = (runtimeOptions = {}) => {
44
+ const customFileSystem = runtimeOptions.mountFs;
45
+ // setup node_modules folder
46
+ const virtualFS = {
47
+ '/': {
48
+ ...customFileSystem,
49
+ src: {
50
+ // biome-ignore lint/complexity/useLiteralKeys: ok here
51
+ ...(customFileSystem?.['src'] ? customFileSystem?.['src'] : {}),
52
+ },
53
+ node_modules: {
54
+ ...runtimeOptions?.nodeModules,
55
+ '@node_compatibility': {
56
+ headers: compatibilityHeaders,
57
+ request: compatibilityRequest,
58
+ response: compatibilityResponse,
59
+ },
60
+ assert: {
61
+ 'index.js': assertModule,
62
+ },
63
+ async_hooks: {
64
+ 'index.js': "throw new Error('module async_hooks not implemented')",
65
+ },
66
+ buffer: {
67
+ 'index.js': bufferModule,
68
+ },
69
+ child_process: {
70
+ 'index.js': "throw new Error('module child_process not implemented')",
71
+ },
72
+ cluster: {
73
+ 'index.js': "throw new Error('module cluster not implemented')",
74
+ },
75
+ console: {
76
+ 'index.js': "throw new Error('module console not implemented')",
77
+ },
78
+ crypto: {
79
+ 'index.js': "throw new Error('module crypto not implemented')",
80
+ },
81
+ dgram: {
82
+ 'index.js': "throw new Error('module dgram not implemented')",
83
+ },
84
+ dns: {
85
+ 'index.js': "throw new Error('module dns not implemented')",
86
+ },
87
+ domain: {
88
+ 'index.js': "throw new Error('module domain not implemented')",
89
+ },
90
+ events: {
91
+ 'index.js': eventModule,
92
+ },
93
+ fs: {
94
+ 'index.js': fsModule,
95
+ promises: {
96
+ 'index.js': fsPromisesModule,
97
+ },
98
+ },
99
+ http: {
100
+ 'index.js': "throw new Error('module http not implemented')",
101
+ },
102
+ http2: {
103
+ 'index.js': "throw new Error('module http2 not implemented')",
104
+ },
105
+ https: {
106
+ 'index.js': "throw new Error('module https not implemented')",
107
+ },
108
+ inspector: {
109
+ 'index.js': "throw new Error('module inspector not implemented')",
110
+ },
111
+ module: {
112
+ 'index.js': moduleModule,
113
+ },
114
+ net: {
115
+ 'index.js': "throw new Error('module net not implemented')",
116
+ },
117
+ os: {
118
+ 'index.js': "throw new Error('module os not implemented')",
119
+ },
120
+ path: {
121
+ 'index.js': pathModule,
122
+ },
123
+ perf_hooks: {
124
+ 'index.js': "throw new Error('module perf_hooks not implemented')",
125
+ },
126
+ process: {
127
+ 'index.js': processModule,
128
+ },
129
+ punycode: {
130
+ 'index.js': punycodeModule,
131
+ },
132
+ querystring: {
133
+ 'index.js': queryStringModule,
134
+ },
135
+ readline: {
136
+ 'index.js': "throw new Error('module readline not implemented')",
137
+ },
138
+ repl: {
139
+ 'index.js': "throw new Error('module repl not implemented')",
140
+ },
141
+ stream: {
142
+ 'index.js': "throw new Error('module stream not implemented')",
143
+ },
144
+ string_decoder: {
145
+ 'index.js': stringDecoderModule,
146
+ },
147
+ timers: {
148
+ 'index.js': timersModule,
149
+ promises: {
150
+ 'index.js': timersPromisesModule,
151
+ },
152
+ },
153
+ tls: {
154
+ 'index.js': "throw new Error('module tls not implemented')",
155
+ },
156
+ trace_events: {
157
+ 'index.js': "throw new Error('module trace_events not implemented')",
158
+ },
159
+ tty: {
160
+ 'index.js': "throw new Error('module tty not implemented')",
161
+ },
162
+ url: {
163
+ 'index.js': urlModule,
164
+ },
165
+ util: {
166
+ 'index.js': utilModule,
167
+ },
168
+ v8: {
169
+ 'index.js': "throw new Error('module v8 not implemented')",
170
+ },
171
+ vm: {
172
+ 'index.js': "throw new Error('module vm not implemented')",
173
+ },
174
+ worker_threads: {
175
+ 'index.js': "throw new Error('module worker_threads not implemented')",
176
+ },
177
+ zlib: {
178
+ 'index.js': "throw new Error('module zlib not implemented')",
179
+ },
180
+ },
181
+ },
182
+ };
183
+ if (runtimeOptions.enableTestUtils) {
184
+ const currentDirname = getCurrentDirname();
185
+ virtualFS['/'].node_modules.test = {
186
+ 'index.js': readFileSync(join(currentDirname, 'modules', 'build', 'test-lib.js')),
187
+ };
188
+ }
189
+ const { vol, fs } = getMemfs()(virtualFS, '/');
190
+ return { vol, fs };
191
+ };
@@ -0,0 +1,77 @@
1
+ /**
2
+ * QuickJS sandbox for JavaScript/Typescript applications
3
+ *
4
+ * This TypeScript package allows you to safely execute JavaScript code within a WebAssembly sandbox using the QuickJS engine.
5
+ * Perfect for isolating and running untrusted code securely, it leverages the lightweight and fast QuickJS engine compiled to WebAssembly, providing a robust environment for code execution.
6
+ *
7
+ * @author Sebastian Wessel
8
+ * @copyright Sebastian Wessel
9
+ * @license MIT
10
+ * @link https://sebastianwessel.github.io/quickjs/
11
+ * @link https://github.com/sebastianwessel/quickjs
12
+ *
13
+ * @example
14
+ * ```typescript
15
+ * import { type SandboxOptions, loadQuickJs } from '@sebastianwessel/quickjs'
16
+ *
17
+ * // General setup like loading and init of the QuickJS wasm
18
+ * // It is a ressource intensive job and should be done only once if possible
19
+ * const { runSandboxed } = await loadQuickJs(variant)
20
+ *
21
+ * const options: SandboxOptions = {
22
+ * allowFetch: true, // inject fetch and allow the code to fetch data
23
+ * allowFs: true, // mount a virtual file system and provide node:fs module
24
+ * env: {
25
+ * MY_ENV_VAR: 'env var value',
26
+ * },
27
+ * }
28
+ *
29
+ * const code = `
30
+ * import { join } from 'path'
31
+ *
32
+ * const fn = async ()=>{
33
+ * console.log(join('src','dist')) // logs "src/dist" on host system
34
+ *
35
+ * console.log(env.MY_ENV_VAR) // logs "env var value" on host system
36
+ *
37
+ * const url = new URL('https://example.com')
38
+ *
39
+ * const f = await fetch(url)
40
+ *
41
+ * return f.text()
42
+ * }
43
+ *
44
+ * export default await fn()
45
+ * `
46
+ *
47
+ * const result = await runSandboxed(async ({ evalCode }) => evalCode(code), options)
48
+ *
49
+ * console.log(result) // { ok: true, data: '<!doctype html>\n<html>\n[....]</html>\n' }
50
+ * ```
51
+ *
52
+ *
53
+ * @module
54
+ */
55
+ export * from './adapter/fetch.js';
56
+ export * from './createVirtualFileSystem.js';
57
+ export * from './loadAsyncQuickJs.js';
58
+ export * from './loadQuickJs.js';
59
+ export * from './sandbox/asyncVersion/getAsyncModuleLoader.js';
60
+ export * from './sandbox/asyncVersion/modulePathNormalizerAsync.js';
61
+ export * from './sandbox/expose/expose.js';
62
+ export * from './sandbox/handleToNative/handleToNative.js';
63
+ export * from './sandbox/handleToNative/serializer/index.js';
64
+ export * from './sandbox/syncVersion/getModuleLoader.js';
65
+ export * from './sandbox/syncVersion/modulePathNormalizer.js';
66
+ export * from './types/CodeFunctionInput.js';
67
+ export * from './types/ErrorResponse.js';
68
+ export * from './types/LoadQuickJsOptions.js';
69
+ export * from './types/OkResponse.js';
70
+ export * from './types/OkResponseCheck.js';
71
+ export * from './types/Prettify.js';
72
+ export * from './types/RuntimeOptions.js';
73
+ export * from './types/SandboxEvalCode.js';
74
+ export * from './types/SandboxFunction.js';
75
+ export * from './types/SandboxOptions.js';
76
+ export * from './types/SandboxValidateCode.js';
77
+ export * from './types/Serializer.js';
@@ -0,0 +1,77 @@
1
+ /**
2
+ * QuickJS sandbox for JavaScript/Typescript applications
3
+ *
4
+ * This TypeScript package allows you to safely execute JavaScript code within a WebAssembly sandbox using the QuickJS engine.
5
+ * Perfect for isolating and running untrusted code securely, it leverages the lightweight and fast QuickJS engine compiled to WebAssembly, providing a robust environment for code execution.
6
+ *
7
+ * @author Sebastian Wessel
8
+ * @copyright Sebastian Wessel
9
+ * @license MIT
10
+ * @link https://sebastianwessel.github.io/quickjs/
11
+ * @link https://github.com/sebastianwessel/quickjs
12
+ *
13
+ * @example
14
+ * ```typescript
15
+ * import { type SandboxOptions, loadQuickJs } from '@sebastianwessel/quickjs'
16
+ *
17
+ * // General setup like loading and init of the QuickJS wasm
18
+ * // It is a ressource intensive job and should be done only once if possible
19
+ * const { runSandboxed } = await loadQuickJs(variant)
20
+ *
21
+ * const options: SandboxOptions = {
22
+ * allowFetch: true, // inject fetch and allow the code to fetch data
23
+ * allowFs: true, // mount a virtual file system and provide node:fs module
24
+ * env: {
25
+ * MY_ENV_VAR: 'env var value',
26
+ * },
27
+ * }
28
+ *
29
+ * const code = `
30
+ * import { join } from 'path'
31
+ *
32
+ * const fn = async ()=>{
33
+ * console.log(join('src','dist')) // logs "src/dist" on host system
34
+ *
35
+ * console.log(env.MY_ENV_VAR) // logs "env var value" on host system
36
+ *
37
+ * const url = new URL('https://example.com')
38
+ *
39
+ * const f = await fetch(url)
40
+ *
41
+ * return f.text()
42
+ * }
43
+ *
44
+ * export default await fn()
45
+ * `
46
+ *
47
+ * const result = await runSandboxed(async ({ evalCode }) => evalCode(code), options)
48
+ *
49
+ * console.log(result) // { ok: true, data: '<!doctype html>\n<html>\n[....]</html>\n' }
50
+ * ```
51
+ *
52
+ *
53
+ * @module
54
+ */
55
+ export * from './adapter/fetch.js';
56
+ export * from './createVirtualFileSystem.js';
57
+ export * from './loadAsyncQuickJs.js';
58
+ export * from './loadQuickJs.js';
59
+ export * from './sandbox/asyncVersion/getAsyncModuleLoader.js';
60
+ export * from './sandbox/asyncVersion/modulePathNormalizerAsync.js';
61
+ export * from './sandbox/expose/expose.js';
62
+ export * from './sandbox/handleToNative/handleToNative.js';
63
+ export * from './sandbox/handleToNative/serializer/index.js';
64
+ export * from './sandbox/syncVersion/getModuleLoader.js';
65
+ export * from './sandbox/syncVersion/modulePathNormalizer.js';
66
+ export * from './types/CodeFunctionInput.js';
67
+ export * from './types/ErrorResponse.js';
68
+ export * from './types/LoadQuickJsOptions.js';
69
+ export * from './types/OkResponse.js';
70
+ export * from './types/OkResponseCheck.js';
71
+ export * from './types/Prettify.js';
72
+ export * from './types/RuntimeOptions.js';
73
+ export * from './types/SandboxEvalCode.js';
74
+ export * from './types/SandboxFunction.js';
75
+ export * from './types/SandboxOptions.js';
76
+ export * from './types/SandboxValidateCode.js';
77
+ export * from './types/Serializer.js';
@@ -0,0 +1,12 @@
1
+ import type { LoadAsyncQuickJsOptions } from './types/LoadQuickJsOptions.js';
2
+ import type { AsyncSandboxFunction } from './types/SandboxFunction.js';
3
+ import type { SandboxAsyncOptions } from './types/SandboxOptions.js';
4
+ /**
5
+ * Loads the QuickJS async module and returns a sandbox execution function.
6
+ * @param variant - Options for loading the QuickJS module. Defaults to '@jitl/quickjs-ng-wasmfile-release-asyncify'.
7
+ * @returns An object containing the runSandboxed function and the loaded module.
8
+ */
9
+ export declare const loadAsyncQuickJs: (variant: LoadAsyncQuickJsOptions) => Promise<{
10
+ runSandboxed: <T>(sandboxedFunction: AsyncSandboxFunction<T>, sandboxOptions?: SandboxAsyncOptions) => Promise<T>;
11
+ module: import("quickjs-emscripten-core").QuickJSAsyncWASMModule;
12
+ }>;
@@ -0,0 +1,66 @@
1
+ import { newQuickJSAsyncWASMModuleFromVariant, Scope, shouldInterruptAfterDeadline } from 'quickjs-emscripten-core';
2
+ import { executeAsyncSandboxFunction } from './sandbox/asyncVersion/executeAsyncSandboxFunction.js';
3
+ import { getAsyncModuleLoader } from './sandbox/asyncVersion/getAsyncModuleLoader.js';
4
+ import { modulePathNormalizerAsync } from './sandbox/asyncVersion/modulePathNormalizerAsync.js';
5
+ import { prepareAsyncNodeCompatibility } from './sandbox/asyncVersion/prepareAsyncNodeCompatibility.js';
6
+ import { prepareAsyncSandbox } from './sandbox/asyncVersion/prepareAsyncSandbox.js';
7
+ import { setupFileSystem } from './sandbox/setupFileSystem.js';
8
+ /**
9
+ * Loads the QuickJS async module and returns a sandbox execution function.
10
+ * @param variant - Options for loading the QuickJS module. Defaults to '@jitl/quickjs-ng-wasmfile-release-asyncify'.
11
+ * @returns An object containing the runSandboxed function and the loaded module.
12
+ */
13
+ export const loadAsyncQuickJs = async (variant) => {
14
+ const module = await newQuickJSAsyncWASMModuleFromVariant(variant);
15
+ /**
16
+ * Provides a new sandbox and executes the given function.
17
+ * When the function has been finished, the sandbox gets disposed and can longer be used.
18
+ *
19
+ * @param sandboxedFunction
20
+ * @param sandboxOptions
21
+ * @returns
22
+ */
23
+ const runSandboxed = async (sandboxedFunction, sandboxOptions = {}) => {
24
+ const scope = new Scope();
25
+ let ctx;
26
+ try {
27
+ ctx = scope.manage(module.newContext());
28
+ if (sandboxOptions.executionTimeout) {
29
+ ctx.runtime.setInterruptHandler(shouldInterruptAfterDeadline(Date.now() + sandboxOptions.executionTimeout));
30
+ }
31
+ if (sandboxOptions.maxStackSize) {
32
+ ctx.runtime.setMaxStackSize(sandboxOptions.maxStackSize);
33
+ }
34
+ if (sandboxOptions.memoryLimit) {
35
+ ctx.runtime.setMemoryLimit(sandboxOptions.memoryLimit);
36
+ }
37
+ // Virtual File System,
38
+ const fs = setupFileSystem(sandboxOptions);
39
+ const transpileFile = (value) => value;
40
+ // JS Module Loader
41
+ const moduleLoader = sandboxOptions.getModuleLoader
42
+ ? sandboxOptions.getModuleLoader(fs, sandboxOptions)
43
+ : getAsyncModuleLoader(fs, sandboxOptions);
44
+ ctx.runtime.setModuleLoader(moduleLoader, sandboxOptions.modulePathNormalizer ?? modulePathNormalizerAsync);
45
+ // Register Globals to be more Node.js compatible
46
+ await prepareAsyncNodeCompatibility(ctx, sandboxOptions);
47
+ // Prepare the Sandbox
48
+ // Expose Data and Functions to Client
49
+ prepareAsyncSandbox(ctx, scope, sandboxOptions, fs);
50
+ // Run the given Function
51
+ const result = await executeAsyncSandboxFunction({
52
+ ctx,
53
+ fs,
54
+ scope,
55
+ sandboxOptions,
56
+ sandboxedFunction,
57
+ transpileFile,
58
+ });
59
+ return result;
60
+ }
61
+ finally {
62
+ scope.dispose();
63
+ }
64
+ };
65
+ return { runSandboxed, module };
66
+ };
@@ -0,0 +1,12 @@
1
+ import type { LoadQuickJsOptions } from './types/LoadQuickJsOptions.js';
2
+ import type { SandboxFunction } from './types/SandboxFunction.js';
3
+ import type { SandboxOptions } from './types/SandboxOptions.js';
4
+ /**
5
+ * Loads the QuickJS module and returns a sandbox execution function.
6
+ * @param variant - Options for loading the QuickJS module. Defaults to '@jitl/quickjs-ng-wasmfile-release-sync'.
7
+ * @returns An object containing the runSandboxed function and the loaded module.
8
+ */
9
+ export declare const loadQuickJs: (variant: LoadQuickJsOptions) => Promise<{
10
+ runSandboxed: <T>(sandboxedFunction: SandboxFunction<T>, sandboxOptions?: SandboxOptions) => Promise<T>;
11
+ module: import("quickjs-emscripten-core").QuickJSWASMModule;
12
+ }>;
@@ -0,0 +1,73 @@
1
+ import { newQuickJSWASMModuleFromVariant, Scope, shouldInterruptAfterDeadline } from 'quickjs-emscripten-core';
2
+ import { rejectAndFlushPendingHostPromises } from './sandbox/expose/pendingHostPromises.js';
3
+ import { setupFileSystem } from './sandbox/setupFileSystem.js';
4
+ import { executeSandboxFunction } from './sandbox/syncVersion/executeSandboxFunction.js';
5
+ import { getModuleLoader } from './sandbox/syncVersion/getModuleLoader.js';
6
+ import { modulePathNormalizer } from './sandbox/syncVersion/modulePathNormalizer.js';
7
+ import { prepareNodeCompatibility } from './sandbox/syncVersion/prepareNodeCompatibility.js';
8
+ import { prepareSandbox } from './sandbox/syncVersion/prepareSandbox.js';
9
+ /**
10
+ * Loads the QuickJS module and returns a sandbox execution function.
11
+ * @param variant - Options for loading the QuickJS module. Defaults to '@jitl/quickjs-ng-wasmfile-release-sync'.
12
+ * @returns An object containing the runSandboxed function and the loaded module.
13
+ */
14
+ export const loadQuickJs = async (variant) => {
15
+ const module = await newQuickJSWASMModuleFromVariant(variant);
16
+ /**
17
+ * Provides a new sandbox and executes the given function.
18
+ * When the function has been finished, the sandbox gets disposed and can longer be used.
19
+ *
20
+ * @param sandboxedFunction
21
+ * @param sandboxOptions
22
+ * @returns
23
+ */
24
+ const runSandboxed = async (sandboxedFunction, sandboxOptions = {}) => {
25
+ const scope = new Scope();
26
+ let ctx;
27
+ try {
28
+ ctx = scope.manage(module.newContext());
29
+ if (sandboxOptions.executionTimeout) {
30
+ ctx.runtime.setInterruptHandler(shouldInterruptAfterDeadline(Date.now() + sandboxOptions.executionTimeout));
31
+ }
32
+ if (sandboxOptions.maxStackSize) {
33
+ ctx.runtime.setMaxStackSize(sandboxOptions.maxStackSize);
34
+ }
35
+ if (sandboxOptions.memoryLimit) {
36
+ ctx.runtime.setMemoryLimit(sandboxOptions.memoryLimit);
37
+ }
38
+ // Virtual File System,
39
+ const fs = setupFileSystem(sandboxOptions);
40
+ const transpileFile = (value) => value;
41
+ // JS Module Loader
42
+ const moduleLoader = sandboxOptions.getModuleLoader
43
+ ? sandboxOptions.getModuleLoader(fs, sandboxOptions)
44
+ : getModuleLoader(fs, sandboxOptions);
45
+ ctx.runtime.setModuleLoader(moduleLoader, sandboxOptions.modulePathNormalizer ?? modulePathNormalizer);
46
+ // Register Globals to be more Node.js compatible
47
+ prepareNodeCompatibility(ctx, sandboxOptions);
48
+ // Prepare the Sandbox
49
+ // Expose Data and Functions to Client
50
+ prepareSandbox(ctx, scope, sandboxOptions, fs);
51
+ // Run the given Function
52
+ const result = await executeSandboxFunction({
53
+ ctx,
54
+ fs,
55
+ scope,
56
+ sandboxOptions,
57
+ sandboxedFunction,
58
+ transpileFile,
59
+ });
60
+ return result;
61
+ }
62
+ catch (error) {
63
+ throw error instanceof Error ? error : new Error('Internal Error');
64
+ }
65
+ finally {
66
+ if (ctx) {
67
+ await rejectAndFlushPendingHostPromises(ctx);
68
+ }
69
+ scope.dispose();
70
+ }
71
+ };
72
+ return { runSandboxed, module };
73
+ };
@@ -0,0 +1,2 @@
1
+ declare const _default: "\nconst assert = {\n fail(actual, expected, message, operator, stackStartFunction) {\n throw new Error(message || `Expected ${actual} ${operator} ${expected}`);\n },\n ok(value, message) {\n if (!value) throw new Error(message || 'Assertion failed');\n },\n equal(actual, expected, message) {\n if (actual != expected) throw new Error(message || `Expected ${actual} to equal ${expected}`);\n },\n notEqual(actual, expected, message) {\n if (actual == expected) throw new Error(message || `Expected ${actual} to not equal ${expected}`);\n },\n deepEqual(actual, expected, message) {\n if (!isDeepEqual(actual, expected)) throw new Error(message || `Expected ${actual} to deeply equal ${expected}`);\n },\n notDeepEqual(actual, expected, message) {\n if (isDeepEqual(actual, expected)) throw new Error(message || `Expected ${actual} to not deeply equal ${expected}`);\n },\n strictEqual(actual, expected, message) {\n if (actual !== expected) throw new Error(message || `Expected ${actual} to strictly equal ${expected}`);\n },\n notStrictEqual(actual, expected, message) {\n if (actual === expected) throw new Error(message || `Expected ${actual} to not strictly equal ${expected}`);\n }\n};\n\nfunction isDeepEqual(a, b) {\n if (a === b) return true;\n\n if (typeof a !== 'object' || a === null || typeof b !== 'object' || b === null) return false;\n\n const keysA = Object.keys(a);\n const keysB = Object.keys(b);\n\n if (keysA.length !== keysB.length) return false;\n\n for (const key of keysA) {\n if (!keysB.includes(key) || !isDeepEqual(a[key], b[key])) return false;\n }\n\n return true;\n}\n\nexport default assert;\n";
2
+ export default _default;
@@ -0,0 +1,47 @@
1
+ export default `
2
+ const assert = {
3
+ fail(actual, expected, message, operator, stackStartFunction) {
4
+ throw new Error(message || \`Expected \${actual} \${operator} \${expected}\`);
5
+ },
6
+ ok(value, message) {
7
+ if (!value) throw new Error(message || 'Assertion failed');
8
+ },
9
+ equal(actual, expected, message) {
10
+ if (actual != expected) throw new Error(message || \`Expected \${actual} to equal \${expected}\`);
11
+ },
12
+ notEqual(actual, expected, message) {
13
+ if (actual == expected) throw new Error(message || \`Expected \${actual} to not equal \${expected}\`);
14
+ },
15
+ deepEqual(actual, expected, message) {
16
+ if (!isDeepEqual(actual, expected)) throw new Error(message || \`Expected \${actual} to deeply equal \${expected}\`);
17
+ },
18
+ notDeepEqual(actual, expected, message) {
19
+ if (isDeepEqual(actual, expected)) throw new Error(message || \`Expected \${actual} to not deeply equal \${expected}\`);
20
+ },
21
+ strictEqual(actual, expected, message) {
22
+ if (actual !== expected) throw new Error(message || \`Expected \${actual} to strictly equal \${expected}\`);
23
+ },
24
+ notStrictEqual(actual, expected, message) {
25
+ if (actual === expected) throw new Error(message || \`Expected \${actual} to not strictly equal \${expected}\`);
26
+ }
27
+ };
28
+
29
+ function isDeepEqual(a, b) {
30
+ if (a === b) return true;
31
+
32
+ if (typeof a !== 'object' || a === null || typeof b !== 'object' || b === null) return false;
33
+
34
+ const keysA = Object.keys(a);
35
+ const keysB = Object.keys(b);
36
+
37
+ if (keysA.length !== keysB.length) return false;
38
+
39
+ for (const key of keysA) {
40
+ if (!keysB.includes(key) || !isDeepEqual(a[key], b[key])) return false;
41
+ }
42
+
43
+ return true;
44
+ }
45
+
46
+ export default assert;
47
+ `;
@@ -0,0 +1,2 @@
1
+ declare const _default: "\nimport { TextEncoder, TextDecoder } from 'node:util'\n\nclass Buffer extends Uint8Array {\n constructor(arg, encoding) {\n if (typeof arg === 'number') {\n super(arg);\n } else if (typeof arg === 'string') {\n super(Buffer._stringToBytes(arg, encoding));\n } else if (arg instanceof ArrayBuffer) {\n super(new Uint8Array(arg));\n } else if (Array.isArray(arg) || arg instanceof Uint8Array) {\n super(arg);\n } else {\n throw new TypeError('Invalid argument type');\n }\n }\n\n static from(arg, encoding) {\n if (typeof arg === 'string') {\n return new Buffer(Buffer._stringToBytes(arg, encoding));\n } else if (Array.isArray(arg) || arg instanceof Uint8Array) {\n return new Buffer(arg);\n } else if (arg instanceof ArrayBuffer) {\n return new Buffer(new Uint8Array(arg));\n } else {\n throw new TypeError('Invalid argument type');\n }\n }\n\n static alloc(size) {\n return new Buffer(size);\n }\n\n static allocUnsafe(size) {\n return new Buffer(size);\n }\n\n static concat(buffers, totalLength) {\n if (!Array.isArray(buffers)) {\n throw new TypeError('Argument must be an array of Buffers');\n }\n if (buffers.length === 0) {\n return Buffer.alloc(0);\n }\n if (totalLength === undefined) {\n totalLength = buffers.reduce((acc, buf) => acc + buf.length, 0);\n }\n const result = Buffer.allocUnsafe(totalLength);\n let offset = 0;\n for (const buf of buffers) {\n result.set(buf, offset);\n offset += buf.length;\n }\n return result;\n }\n\n toString(encoding) {\n if (encoding === 'base64') {\n return Buffer._bytesToBase64(this);\n } else {\n return Buffer._bytesToString(this, encoding);\n }\n }\n\n static _stringToBytes(string, encoding) {\n if (encoding === 'base64') {\n return Buffer._base64ToBytes(string);\n } else {\n return new TextEncoder().encode(string);\n }\n }\n\n static _bytesToString(bytes, encoding) {\n if (encoding === 'utf-8' || encoding === undefined) {\n return new TextDecoder(encoding).decode(bytes);\n } else {\n throw new TypeError('Unsupported encoding');\n }\n }\n\n static _base64ToBytes(base64) {\n const binaryString = atob(base64);\n const length = binaryString.length;\n const bytes = new Uint8Array(length);\n for (let i = 0; i < length; i++) {\n bytes[i] = binaryString.charCodeAt(i);\n }\n return bytes;\n }\n\n static _bytesToBase64(bytes) {\n let binary = '';\n for (let i = 0; i < bytes.length; i++) {\n binary += String.fromCharCode(bytes[i]);\n }\n return btoa(binary);\n }\n}\n\nglobalThis.Buffer = Buffer\n\nexport { Buffer }\n\nexport default Buffer;\n";
2
+ export default _default;