mimium-web 4.0.0-alpha.4 → 4.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -67,11 +67,11 @@ mimium is a statically typed language but the most of type annotations can be om
67
67
 
68
68
  ### Live Coding
69
69
 
70
- mimium can describe digital signal processing algorithm from very low-level, like Faust. Moreover, mimium can update source code without audio interruption, which enables **full-scratch dsp livecoding** performance.
70
+ mimium can describe digital signal processing algorithm from very low-level, like Faust. Moreover, mimium can update source code without an audio discontinuity and keeps tail of delay and reverb, which enables **full-scratch dsp livecoding** performance.
71
71
 
72
72
  ### Extensibility
73
73
 
74
- mimium's VM design is inspired by Lua, that can be easily embedded on Rust application through the plugin system. External functions(closures) defined in Rust can be easily called from mimium.
74
+ mimium's VM design is inspired by Lua, that can be easily embedded on Rust application through the plugin system. External functions (closures) defined in Rust can be easily called from mimium.
75
75
 
76
76
  ## Installation
77
77
 
@@ -87,7 +87,7 @@ See [Development](./Development) section.
87
87
 
88
88
  ## Contributing
89
89
 
90
- There's no concrete way for contributing to the mimium project for now but any type of contribution (bugfix, code refactoring, documentation, showing the usecases, etc).
90
+ Any type of contribution (bugfix, code refactoring, documentation, showing the usecases, etc) are welcome.
91
91
 
92
92
  (However, because the mimium is still early stage of the development and there's much things to do, the proposal or request for new feature without Pull Request may not be accepted.)
93
93
 
@@ -123,6 +123,7 @@ This list contains the contributers from v1 development, documentation and finan
123
123
  - [kyo](https://github.com/syougikakugenn)
124
124
  - [Inqb8tr-jp](https://github.com/Inqb8tr-jp)
125
125
  - [zakuro9715](https://github.com/zakuro9715)
126
+ - [kuroboshi](https://github.com/kuroboshi)
126
127
 
127
128
  #### Other forms of Contributions
128
129
 
package/mimium_web.d.ts CHANGED
@@ -18,8 +18,10 @@ export class Context {
18
18
  clear_virtual_file_cache(): void;
19
19
  compile(src: string): Promise<void>;
20
20
  compile_direct(src: string): void;
21
+ export_virtual_file_cache_json(): string;
21
22
  get_input_channels(): number;
22
23
  get_output_channels(): number;
24
+ import_virtual_file_cache_json(payload: string): void;
23
25
  init_github_lib_cache(): Promise<void>;
24
26
  init_lib_cache_with_base_url(base_url: string): Promise<void>;
25
27
  constructor(config: Config);
@@ -55,8 +57,10 @@ export interface InitOutput {
55
57
  readonly context_clear_virtual_file_cache: (a: number) => [number, number];
56
58
  readonly context_compile: (a: number, b: number, c: number) => any;
57
59
  readonly context_compile_direct: (a: number, b: number, c: number) => [number, number];
60
+ readonly context_export_virtual_file_cache_json: (a: number) => [number, number, number, number];
58
61
  readonly context_get_input_channels: (a: number) => number;
59
62
  readonly context_get_output_channels: (a: number) => number;
63
+ readonly context_import_virtual_file_cache_json: (a: number, b: number, c: number) => [number, number];
60
64
  readonly context_init_github_lib_cache: (a: number) => any;
61
65
  readonly context_init_lib_cache_with_base_url: (a: number, b: number, c: number) => any;
62
66
  readonly context_new: (a: number) => number;
@@ -65,9 +69,9 @@ export interface InitOutput {
65
69
  readonly context_recompile: (a: number, b: number, c: number) => any;
66
70
  readonly context_recompile_direct: (a: number, b: number, c: number) => [number, number];
67
71
  readonly context_set_module_base_url: (a: number, b: number, c: number) => [number, number];
68
- readonly wasm_bindgen__closure__destroy__hab95d7be7d8a5a60: (a: number, b: number) => void;
69
- readonly wasm_bindgen__convert__closures_____invoke__ha0f31ef339bf6681: (a: number, b: number, c: any) => [number, number];
70
- readonly wasm_bindgen__convert__closures_____invoke__h0d15b73cb2272b2b: (a: number, b: number, c: any, d: any) => void;
72
+ readonly wasm_bindgen__closure__destroy__hbd36d0a93d842323: (a: number, b: number) => void;
73
+ readonly wasm_bindgen__convert__closures_____invoke__h1e1f82066e0a305f: (a: number, b: number, c: any) => [number, number];
74
+ readonly wasm_bindgen__convert__closures_____invoke__h88f23ffac03dc2c6: (a: number, b: number, c: any, d: any) => void;
71
75
  readonly __wbindgen_exn_store: (a: number) => void;
72
76
  readonly __externref_table_alloc: () => number;
73
77
  readonly __wbindgen_externrefs: WebAssembly.Table;
package/mimium_web.js CHANGED
@@ -1,5 +1,5 @@
1
1
  /* @ts-self-types="./mimium_web.d.ts" */
2
- import { __mimium_test_clear_cache, __mimium_test_put_cache, preload_mimium_lib_cache, preload_user_module_cache, read_file, set_module_base_url } from './snippets/mimium-lang-282ca0d5e596d829/src/utils/fileloader.mjs';
2
+ import { __mimium_test_clear_cache, __mimium_test_put_cache, export_virtual_file_cache_json, get_env, has_network_api, import_virtual_file_cache_json, preload_mimium_lib_cache, preload_user_module_cache, read_file, set_module_base_url } from './snippets/mimium-lang-73347f1c047dac3b/src/utils/fileloader.mjs';
3
3
 
4
4
  export class Config {
5
5
  static __wrap(ptr) {
@@ -119,6 +119,27 @@ export class Context {
119
119
  throw takeFromExternrefTable0(ret[0]);
120
120
  }
121
121
  }
122
+ /**
123
+ * @returns {string}
124
+ */
125
+ export_virtual_file_cache_json() {
126
+ let deferred2_0;
127
+ let deferred2_1;
128
+ try {
129
+ const ret = wasm.context_export_virtual_file_cache_json(this.__wbg_ptr);
130
+ var ptr1 = ret[0];
131
+ var len1 = ret[1];
132
+ if (ret[3]) {
133
+ ptr1 = 0; len1 = 0;
134
+ throw takeFromExternrefTable0(ret[2]);
135
+ }
136
+ deferred2_0 = ptr1;
137
+ deferred2_1 = len1;
138
+ return getStringFromWasm0(ptr1, len1);
139
+ } finally {
140
+ wasm.__wbindgen_free(deferred2_0, deferred2_1, 1);
141
+ }
142
+ }
122
143
  /**
123
144
  * @returns {number}
124
145
  */
@@ -133,6 +154,17 @@ export class Context {
133
154
  const ret = wasm.context_get_output_channels(this.__wbg_ptr);
134
155
  return ret >>> 0;
135
156
  }
157
+ /**
158
+ * @param {string} payload
159
+ */
160
+ import_virtual_file_cache_json(payload) {
161
+ const ptr0 = passStringToWasm0(payload, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
162
+ const len0 = WASM_VECTOR_LEN;
163
+ const ret = wasm.context_import_virtual_file_cache_json(this.__wbg_ptr, ptr0, len0);
164
+ if (ret[1]) {
165
+ throw takeFromExternrefTable0(ret[0]);
166
+ }
167
+ }
136
168
  /**
137
169
  * @returns {Promise<void>}
138
170
  */
@@ -231,10 +263,10 @@ if (Symbol.dispose) Context.prototype[Symbol.dispose] = Context.prototype.free;
231
263
  function __wbg_get_imports() {
232
264
  const import0 = {
233
265
  __proto__: null,
234
- __wbg___mimium_test_clear_cache_15bc783b03d49d3f: function() { return handleError(function () {
266
+ __wbg___mimium_test_clear_cache_42c842e7aaa6df4f: function() { return handleError(function () {
235
267
  __mimium_test_clear_cache();
236
268
  }, arguments); },
237
- __wbg___mimium_test_put_cache_6e930cf841a82463: function() { return handleError(function (arg0, arg1, arg2, arg3) {
269
+ __wbg___mimium_test_put_cache_763c7b5c193bb757: function() { return handleError(function (arg0, arg1, arg2, arg3) {
238
270
  __mimium_test_put_cache(getStringFromWasm0(arg0, arg1), getStringFromWasm0(arg2, arg3));
239
271
  }, arguments); },
240
272
  __wbg___wbindgen_copy_to_typed_array_d2f20acdab8e0740: function(arg0, arg1, arg2) {
@@ -276,6 +308,27 @@ function __wbg_get_imports() {
276
308
  wasm.__wbindgen_free(deferred0_0, deferred0_1, 1);
277
309
  }
278
310
  },
311
+ __wbg_export_virtual_file_cache_json_d54d717044e38a30: function() { return handleError(function (arg0) {
312
+ const ret = export_virtual_file_cache_json();
313
+ const ptr1 = passStringToWasm0(ret, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
314
+ const len1 = WASM_VECTOR_LEN;
315
+ getDataViewMemory0().setInt32(arg0 + 4 * 1, len1, true);
316
+ getDataViewMemory0().setInt32(arg0 + 4 * 0, ptr1, true);
317
+ }, arguments); },
318
+ __wbg_get_env_48ab6ace7e57ac23: function() { return handleError(function (arg0, arg1, arg2) {
319
+ const ret = get_env(getStringFromWasm0(arg1, arg2));
320
+ const ptr1 = passStringToWasm0(ret, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
321
+ const len1 = WASM_VECTOR_LEN;
322
+ getDataViewMemory0().setInt32(arg0 + 4 * 1, len1, true);
323
+ getDataViewMemory0().setInt32(arg0 + 4 * 0, ptr1, true);
324
+ }, arguments); },
325
+ __wbg_has_network_api_2766ae838a8e3ad1: function() { return handleError(function () {
326
+ const ret = has_network_api();
327
+ return ret;
328
+ }, arguments); },
329
+ __wbg_import_virtual_file_cache_json_92707598f2ce5309: function() { return handleError(function (arg0, arg1) {
330
+ import_virtual_file_cache_json(getStringFromWasm0(arg0, arg1));
331
+ }, arguments); },
279
332
  __wbg_new_227d7c05414eb861: function() {
280
333
  const ret = new Error();
281
334
  return ret;
@@ -287,7 +340,7 @@ function __wbg_get_imports() {
287
340
  const a = state0.a;
288
341
  state0.a = 0;
289
342
  try {
290
- return wasm_bindgen__convert__closures_____invoke__h0d15b73cb2272b2b(a, state0.b, arg0, arg1);
343
+ return wasm_bindgen__convert__closures_____invoke__h88f23ffac03dc2c6(a, state0.b, arg0, arg1);
291
344
  } finally {
292
345
  state0.a = a;
293
346
  }
@@ -298,11 +351,11 @@ function __wbg_get_imports() {
298
351
  state0.a = state0.b = 0;
299
352
  }
300
353
  },
301
- __wbg_preload_mimium_lib_cache_0a73db4b652312b0: function() { return handleError(function (arg0, arg1) {
354
+ __wbg_preload_mimium_lib_cache_24f83cfbe8c162e2: function() { return handleError(function (arg0, arg1) {
302
355
  const ret = preload_mimium_lib_cache(getStringFromWasm0(arg0, arg1));
303
356
  return ret;
304
357
  }, arguments); },
305
- __wbg_preload_user_module_cache_385c142315bc1d3f: function() { return handleError(function (arg0, arg1, arg2, arg3) {
358
+ __wbg_preload_user_module_cache_3800312a47ab99a5: function() { return handleError(function (arg0, arg1, arg2, arg3) {
306
359
  const ret = preload_user_module_cache(getStringFromWasm0(arg0, arg1), getStringFromWasm0(arg2, arg3));
307
360
  return ret;
308
361
  }, arguments); },
@@ -313,7 +366,7 @@ function __wbg_get_imports() {
313
366
  __wbg_queueMicrotask_a082d78ce798393e: function(arg0) {
314
367
  queueMicrotask(arg0);
315
368
  },
316
- __wbg_read_file_265a82e26644b785: function() { return handleError(function (arg0, arg1, arg2) {
369
+ __wbg_read_file_7988f955dd7ca793: function() { return handleError(function (arg0, arg1, arg2) {
317
370
  const ret = read_file(getStringFromWasm0(arg1, arg2));
318
371
  const ptr1 = passStringToWasm0(ret, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
319
372
  const len1 = WASM_VECTOR_LEN;
@@ -324,7 +377,7 @@ function __wbg_get_imports() {
324
377
  const ret = Promise.resolve(arg0);
325
378
  return ret;
326
379
  },
327
- __wbg_set_module_base_url_32604e1e603e53b4: function() { return handleError(function (arg0, arg1) {
380
+ __wbg_set_module_base_url_e2ab546fcbbd65d0: function() { return handleError(function (arg0, arg1) {
328
381
  set_module_base_url(getStringFromWasm0(arg0, arg1));
329
382
  }, arguments); },
330
383
  __wbg_stack_3b0d974bbf31e44f: function(arg0, arg1) {
@@ -359,8 +412,8 @@ function __wbg_get_imports() {
359
412
  return ret;
360
413
  },
361
414
  __wbindgen_cast_0000000000000001: function(arg0, arg1) {
362
- // Cast intrinsic for `Closure(Closure { dtor_idx: 601, function: Function { arguments: [Externref], shim_idx: 602, ret: Result(Unit), inner_ret: Some(Result(Unit)) }, mutable: true }) -> Externref`.
363
- const ret = makeMutClosure(arg0, arg1, wasm.wasm_bindgen__closure__destroy__hab95d7be7d8a5a60, wasm_bindgen__convert__closures_____invoke__ha0f31ef339bf6681);
415
+ // Cast intrinsic for `Closure(Closure { dtor_idx: 628, function: Function { arguments: [Externref], shim_idx: 629, ret: Result(Unit), inner_ret: Some(Result(Unit)) }, mutable: true }) -> Externref`.
416
+ const ret = makeMutClosure(arg0, arg1, wasm.wasm_bindgen__closure__destroy__hbd36d0a93d842323, wasm_bindgen__convert__closures_____invoke__h1e1f82066e0a305f);
364
417
  return ret;
365
418
  },
366
419
  __wbindgen_cast_0000000000000002: function(arg0, arg1) {
@@ -384,15 +437,15 @@ function __wbg_get_imports() {
384
437
  };
385
438
  }
386
439
 
387
- function wasm_bindgen__convert__closures_____invoke__ha0f31ef339bf6681(arg0, arg1, arg2) {
388
- const ret = wasm.wasm_bindgen__convert__closures_____invoke__ha0f31ef339bf6681(arg0, arg1, arg2);
440
+ function wasm_bindgen__convert__closures_____invoke__h1e1f82066e0a305f(arg0, arg1, arg2) {
441
+ const ret = wasm.wasm_bindgen__convert__closures_____invoke__h1e1f82066e0a305f(arg0, arg1, arg2);
389
442
  if (ret[1]) {
390
443
  throw takeFromExternrefTable0(ret[0]);
391
444
  }
392
445
  }
393
446
 
394
- function wasm_bindgen__convert__closures_____invoke__h0d15b73cb2272b2b(arg0, arg1, arg2, arg3) {
395
- wasm.wasm_bindgen__convert__closures_____invoke__h0d15b73cb2272b2b(arg0, arg1, arg2, arg3);
447
+ function wasm_bindgen__convert__closures_____invoke__h88f23ffac03dc2c6(arg0, arg1, arg2, arg3) {
448
+ wasm.wasm_bindgen__convert__closures_____invoke__h88f23ffac03dc2c6(arg0, arg1, arg2, arg3);
396
449
  }
397
450
 
398
451
  const ConfigFinalization = (typeof FinalizationRegistry === 'undefined')
Binary file
package/package.json CHANGED
@@ -5,7 +5,7 @@
5
5
  "Tomoya Matsuura <me@matsuuratomoya.com>"
6
6
  ],
7
7
  "description": "mimium wasm binding package.",
8
- "version": "4.0.0-alpha.4",
8
+ "version": "4.0.1",
9
9
  "license": "MPL-2.0",
10
10
  "repository": {
11
11
  "type": "git",
@@ -82,6 +82,10 @@ function normalizeBaseUrlCandidate(baseUrlCandidate) {
82
82
  }
83
83
  }
84
84
 
85
+ function has_network_api() {
86
+ return typeof globalThis.fetch === 'function' || typeof XMLHttpRequest !== 'undefined';
87
+ }
88
+
85
89
  function putMemoryAliases(filename, content) {
86
90
  const normalized = normalizePath(filename);
87
91
  if (!normalized) {
@@ -143,6 +147,11 @@ function getTagFromBaseUrl(baseUrl) {
143
147
  return tag || DEFAULT_GITHUB_TAG;
144
148
  }
145
149
 
150
+ function isMutableGitRefTag(tag) {
151
+ const normalized = (tag || '').toLowerCase();
152
+ return normalized === 'dev' || normalized === 'main' || normalized === 'master' || normalized === 'head';
153
+ }
154
+
146
155
  function getCacheDirName() {
147
156
  return `mimium-lib-${getTagFromBaseUrl(globalThis.__mimium_lib_base_url || '')}`;
148
157
  }
@@ -172,13 +181,42 @@ async function writeToOpfs(filename, content) {
172
181
  await writable.close();
173
182
  }
174
183
 
184
+ async function requestText(url) {
185
+ if (typeof globalThis.fetch === 'function') {
186
+ const response = await globalThis.fetch(url, { cache: 'no-cache' });
187
+ if (!response.ok) {
188
+ throw new Error(`Failed to fetch ${url}: ${response.status} ${response.statusText}`);
189
+ }
190
+ return response.text();
191
+ }
192
+
193
+ if (typeof XMLHttpRequest !== 'undefined') {
194
+ return new Promise((resolve, reject) => {
195
+ const xhr = new XMLHttpRequest();
196
+ xhr.open('GET', url, true);
197
+ xhr.onreadystatechange = () => {
198
+ if (xhr.readyState !== 4) {
199
+ return;
200
+ }
201
+ if (xhr.status >= 200 && xhr.status < 300) {
202
+ resolve(xhr.responseText);
203
+ return;
204
+ }
205
+ reject(new Error(`Failed to fetch ${url}: ${xhr.status} ${xhr.statusText}`));
206
+ };
207
+ xhr.onerror = () => reject(new Error(`Failed to fetch ${url}: network error`));
208
+ xhr.send();
209
+ });
210
+ }
211
+
212
+ throw new Error(
213
+ 'Network API is unavailable: neither fetch nor XMLHttpRequest exists in this runtime.'
214
+ );
215
+ }
216
+
175
217
  async function fetchLibFile(baseUrl, filename) {
176
218
  const url = `${baseUrl}${filename}`;
177
- const response = await fetch(url, { cache: 'no-cache' });
178
- if (!response.ok) {
179
- throw new Error(`Failed to fetch ${url}: ${response.status} ${response.statusText}`);
180
- }
181
- return response.text();
219
+ return requestText(url);
182
220
  }
183
221
 
184
222
  function collectDependencies(source) {
@@ -206,11 +244,7 @@ function getModuleBaseUrl(base_url) {
206
244
 
207
245
  async function fetchSourceFromBaseUrl(baseUrl, relativePath) {
208
246
  const url = new URL(relativePath, baseUrl).toString();
209
- const response = await fetch(url, { cache: 'no-cache' });
210
- if (!response.ok) {
211
- throw new Error(`Failed to fetch ${url}: ${response.status} ${response.statusText}`);
212
- }
213
- return response.text();
247
+ return requestText(url);
214
248
  }
215
249
 
216
250
  async function preload_user_module_cache(source, base_url) {
@@ -260,6 +294,8 @@ async function preload_mimium_lib_cache(base_url) {
260
294
  : `${DEFAULT_GITHUB_LIB_BASE}${DEFAULT_GITHUB_TAG}/lib/`;
261
295
  const normalizedBaseUrl = normalizeBaseUrlCandidate(baseUrlCandidate);
262
296
  const baseUrl = normalizedBaseUrl.endsWith('/') ? normalizedBaseUrl : `${normalizedBaseUrl}/`;
297
+ const resolvedTag = getTagFromBaseUrl(baseUrl);
298
+ const shouldRefreshMutableRef = isMutableGitRefTag(resolvedTag);
263
299
  globalThis.__mimium_lib_base_url = baseUrl;
264
300
  lastPreloadBaseUrl = baseUrl;
265
301
 
@@ -275,14 +311,23 @@ async function preload_mimium_lib_cache(base_url) {
275
311
  }
276
312
 
277
313
  const fromOpfs = await readFromOpfs(filename);
278
- if (fromOpfs !== null) {
314
+ if (!shouldRefreshMutableRef && fromOpfs !== null) {
279
315
  putMemoryAliases(filename, fromOpfs);
280
316
  continue;
281
317
  }
282
318
 
283
- const fetched = await fetchLibFile(baseUrl, filename);
284
- putMemoryAliases(filename, fetched);
285
- await writeToOpfs(filename, fetched);
319
+ try {
320
+ const fetched = await fetchLibFile(baseUrl, filename);
321
+ putMemoryAliases(filename, fetched);
322
+ await writeToOpfs(filename, fetched);
323
+ } catch (e) {
324
+ // Keep mutable refs fresh when online, but remain usable offline via OPFS fallback.
325
+ if (fromOpfs !== null) {
326
+ putMemoryAliases(filename, fromOpfs);
327
+ continue;
328
+ }
329
+ throw e;
330
+ }
286
331
  }
287
332
  }
288
333
 
@@ -306,6 +351,37 @@ function __mimium_test_get_last_module_preload_base_url() {
306
351
  return lastModulePreloadBaseUrl;
307
352
  }
308
353
 
354
+ function export_virtual_file_cache_json() {
355
+ const entries = [];
356
+ const seen = new Set();
357
+ for (const [key, value] of memoryCache.entries()) {
358
+ const normalized = normalizePath(key);
359
+ if (!normalized || seen.has(normalized)) {
360
+ continue;
361
+ }
362
+ seen.add(normalized);
363
+ entries.push([normalized, value]);
364
+ }
365
+ return JSON.stringify(entries);
366
+ }
367
+
368
+ function import_virtual_file_cache_json(payload) {
369
+ const parsed = JSON.parse(payload);
370
+ if (!Array.isArray(parsed)) {
371
+ throw new Error('Invalid cache payload: expected array entries');
372
+ }
373
+ parsed.forEach((entry) => {
374
+ if (!Array.isArray(entry) || entry.length !== 2) {
375
+ throw new Error('Invalid cache payload entry');
376
+ }
377
+ const [path, content] = entry;
378
+ if (typeof path !== 'string' || typeof content !== 'string') {
379
+ throw new Error('Invalid cache payload types');
380
+ }
381
+ putMemoryAliases(path, content);
382
+ });
383
+ }
384
+
309
385
  function set_module_base_url(base_url) {
310
386
  const normalized = getModuleBaseUrl(base_url);
311
387
  if (!normalized) {
@@ -318,9 +394,12 @@ function set_module_base_url(base_url) {
318
394
  export {
319
395
  read_file,
320
396
  get_env,
397
+ has_network_api,
321
398
  preload_mimium_lib_cache,
322
399
  preload_user_module_cache,
323
400
  set_module_base_url,
401
+ export_virtual_file_cache_json,
402
+ import_virtual_file_cache_json,
324
403
  __mimium_test_put_cache,
325
404
  __mimium_test_clear_cache,
326
405
  __mimium_test_get_last_preload_base_url,
@@ -1,181 +0,0 @@
1
-
2
- const isNode = typeof process !== "undefined" && !!(process.versions && process.versions.node);
3
- const fs = isNode && typeof require === "function" ? require("fs") : null;
4
-
5
- const DEFAULT_GITHUB_LIB_BASE = "https://raw.githubusercontent.com/mimium-org/mimium-rs/";
6
- const DEFAULT_GITHUB_TAG = "dev";
7
- const LIB_FILES = [
8
- "core.mmm",
9
- "delay.mmm",
10
- "env.mmm",
11
- "filter.mmm",
12
- "math.mmm",
13
- "noise.mmm",
14
- "osc.mmm",
15
- "reactive.mmm",
16
- "reverb.mmm",
17
- ];
18
-
19
- const memoryCache = new Map();
20
- let lastPreloadBaseUrl = "";
21
-
22
- function normalizePath(path) {
23
- if (typeof path !== "string") {
24
- return "";
25
- }
26
- const slash = path.replace(/\\/g, "/").trim();
27
- const withoutPrefix = slash
28
- .replace(/^\/+/, "")
29
- .replace(/^\.\//, "")
30
- .replace(/^lib\//, "");
31
- const collapsed = withoutPrefix
32
- .split("/")
33
- .filter((seg) => seg.length > 0 && seg !== ".")
34
- .join("/");
35
- return collapsed;
36
- }
37
-
38
- function putMemoryAliases(filename, content) {
39
- const normalized = normalizePath(filename);
40
- if (!normalized) {
41
- return;
42
- }
43
- memoryCache.set(normalized, content);
44
- memoryCache.set(`./${normalized}`, content);
45
- memoryCache.set(`lib/${normalized}`, content);
46
- memoryCache.set(`/lib/${normalized}`, content);
47
- }
48
-
49
- export function read_file(path) {
50
- if (isNode && fs) {
51
- return fs.readFileSync(path, { encoding: "utf8" });
52
- }
53
-
54
- const normalized = normalizePath(path);
55
- const cached =
56
- memoryCache.get(path) ??
57
- memoryCache.get(normalized) ??
58
- memoryCache.get(`./${normalized}`) ??
59
- memoryCache.get(`lib/${normalized}`) ??
60
- memoryCache.get(`/lib/${normalized}`);
61
-
62
- if (cached !== undefined) {
63
- return cached;
64
- }
65
-
66
- throw new Error(
67
- `Include target not found in browser cache: ${path}. Call preload_mimium_lib_cache() before compile().`
68
- );
69
- }
70
-
71
- export function get_env(key) {
72
- if (isNode) {
73
- return process.env[key];
74
- }
75
- return undefined;
76
- }
77
-
78
- async function getOpfsLibDirectory() {
79
- const cacheDirName = getCacheDirName();
80
- if (!globalThis.navigator || !navigator.storage || !navigator.storage.getDirectory) {
81
- return null;
82
- }
83
- const root = await navigator.storage.getDirectory();
84
- return root.getDirectoryHandle(cacheDirName, { create: true });
85
- }
86
-
87
- function getTagFromBaseUrl(baseUrl) {
88
- const normalized = (baseUrl || "").replace(/\/+$/, "");
89
- const marker = "raw.githubusercontent.com/mimium-org/mimium-rs/";
90
- const markerIdx = normalized.indexOf(marker);
91
- if (markerIdx < 0) {
92
- return DEFAULT_GITHUB_TAG;
93
- }
94
- const suffix = normalized.slice(markerIdx + marker.length);
95
- const tag = suffix.split("/")[0];
96
- return tag || DEFAULT_GITHUB_TAG;
97
- }
98
-
99
- function getCacheDirName() {
100
- return `mimium-lib-${getTagFromBaseUrl(globalThis.__mimium_lib_base_url || "")}`;
101
- }
102
-
103
- async function readFromOpfs(filename) {
104
- const dir = await getOpfsLibDirectory();
105
- if (!dir) {
106
- return null;
107
- }
108
- try {
109
- const handle = await dir.getFileHandle(filename, { create: false });
110
- const file = await handle.getFile();
111
- return await file.text();
112
- } catch {
113
- return null;
114
- }
115
- }
116
-
117
- async function writeToOpfs(filename, content) {
118
- const dir = await getOpfsLibDirectory();
119
- if (!dir) {
120
- return;
121
- }
122
- const handle = await dir.getFileHandle(filename, { create: true });
123
- const writable = await handle.createWritable();
124
- await writable.write(content);
125
- await writable.close();
126
- }
127
-
128
- async function fetchLibFile(baseUrl, filename) {
129
- const url = `${baseUrl}${filename}`;
130
- const response = await fetch(url, { cache: "no-cache" });
131
- if (!response.ok) {
132
- throw new Error(`Failed to fetch ${url}: ${response.status} ${response.statusText}`);
133
- }
134
- return response.text();
135
- }
136
-
137
- export async function preload_mimium_lib_cache(base_url) {
138
- const baseUrlCandidate =
139
- base_url && base_url.length > 0
140
- ? base_url
141
- : `${DEFAULT_GITHUB_LIB_BASE}${DEFAULT_GITHUB_TAG}/lib/`;
142
- const baseUrl = baseUrlCandidate.endsWith("/") ? baseUrlCandidate : `${baseUrlCandidate}/`;
143
- globalThis.__mimium_lib_base_url = baseUrl;
144
- lastPreloadBaseUrl = baseUrl;
145
-
146
- if (isNode) {
147
- return;
148
- }
149
-
150
- for (const filename of LIB_FILES) {
151
- const fromMemory = memoryCache.get(filename);
152
- if (fromMemory !== undefined) {
153
- putMemoryAliases(filename, fromMemory);
154
- continue;
155
- }
156
-
157
- const fromOpfs = await readFromOpfs(filename);
158
- if (fromOpfs !== null) {
159
- putMemoryAliases(filename, fromOpfs);
160
- continue;
161
- }
162
-
163
- const fetched = await fetchLibFile(baseUrl, filename);
164
- putMemoryAliases(filename, fetched);
165
- await writeToOpfs(filename, fetched);
166
- }
167
- }
168
-
169
- export function __mimium_test_put_cache(path, content) {
170
- putMemoryAliases(path, content);
171
- }
172
-
173
- export function __mimium_test_clear_cache() {
174
- memoryCache.clear();
175
- lastPreloadBaseUrl = "";
176
- delete globalThis.__mimium_lib_base_url;
177
- }
178
-
179
- export function __mimium_test_get_last_preload_base_url() {
180
- return lastPreloadBaseUrl;
181
- }
@@ -1,189 +0,0 @@
1
- let fs = null;
2
- const isNode = typeof process !== "undefined" && !!(process.versions && process.versions.node);
3
- if (isNode) {
4
- fs = require("fs");
5
- }
6
-
7
- const DEFAULT_GITHUB_LIB_BASE = "https://raw.githubusercontent.com/mimium-org/mimium-rs/";
8
- const DEFAULT_GITHUB_TAG = "dev";
9
- const LIB_FILES = [
10
- "core.mmm",
11
- "delay.mmm",
12
- "env.mmm",
13
- "filter.mmm",
14
- "math.mmm",
15
- "noise.mmm",
16
- "osc.mmm",
17
- "reactive.mmm",
18
- "reverb.mmm",
19
- ];
20
-
21
- const memoryCache = new Map();
22
- let lastPreloadBaseUrl = "";
23
-
24
- function normalizePath(path) {
25
- if (typeof path !== "string") {
26
- return "";
27
- }
28
- const slash = path.replace(/\\/g, "/").trim();
29
- const withoutPrefix = slash
30
- .replace(/^\/+/, "")
31
- .replace(/^\.\//, "")
32
- .replace(/^lib\//, "");
33
- const collapsed = withoutPrefix
34
- .split("/")
35
- .filter((seg) => seg.length > 0 && seg !== ".")
36
- .join("/");
37
- return collapsed;
38
- }
39
-
40
- function putMemoryAliases(filename, content) {
41
- const normalized = normalizePath(filename);
42
- if (!normalized) {
43
- return;
44
- }
45
- memoryCache.set(normalized, content);
46
- memoryCache.set(`./${normalized}`, content);
47
- memoryCache.set(`lib/${normalized}`, content);
48
- memoryCache.set(`/lib/${normalized}`, content);
49
- }
50
-
51
- function read_file(path) {
52
- if (isNode) {
53
- return fs.readFileSync(path, { encoding: "utf8" });
54
- }
55
-
56
- const normalized = normalizePath(path);
57
- const cached =
58
- memoryCache.get(path) ??
59
- memoryCache.get(normalized) ??
60
- memoryCache.get(`./${normalized}`) ??
61
- memoryCache.get(`lib/${normalized}`) ??
62
- memoryCache.get(`/lib/${normalized}`);
63
-
64
- if (cached !== undefined) {
65
- return cached;
66
- }
67
-
68
- throw new Error(
69
- `Include target not found in browser cache: ${path}. Call preload_mimium_lib_cache() before compile().`
70
- );
71
- }
72
- exports.read_file = read_file;
73
-
74
- function get_env(key) {
75
- if (isNode) {
76
- return process.env[key];
77
- }
78
- return undefined;
79
- }
80
- exports.get_env = get_env;
81
-
82
- async function getOpfsLibDirectory() {
83
- const cacheDirName = getCacheDirName();
84
- if (!globalThis.navigator || !navigator.storage || !navigator.storage.getDirectory) {
85
- return null;
86
- }
87
- const root = await navigator.storage.getDirectory();
88
- return root.getDirectoryHandle(cacheDirName, { create: true });
89
- }
90
-
91
- function getTagFromBaseUrl(baseUrl) {
92
- const normalized = (baseUrl || "").replace(/\/+$/, "");
93
- const marker = "raw.githubusercontent.com/mimium-org/mimium-rs/";
94
- const markerIdx = normalized.indexOf(marker);
95
- if (markerIdx < 0) {
96
- return DEFAULT_GITHUB_TAG;
97
- }
98
- const suffix = normalized.slice(markerIdx + marker.length);
99
- const tag = suffix.split("/")[0];
100
- return tag || DEFAULT_GITHUB_TAG;
101
- }
102
-
103
- function getCacheDirName() {
104
- return `mimium-lib-${getTagFromBaseUrl(globalThis.__mimium_lib_base_url || "")}`;
105
- }
106
-
107
- async function readFromOpfs(filename) {
108
- const dir = await getOpfsLibDirectory();
109
- if (!dir) {
110
- return null;
111
- }
112
- try {
113
- const handle = await dir.getFileHandle(filename, { create: false });
114
- const file = await handle.getFile();
115
- return await file.text();
116
- } catch {
117
- return null;
118
- }
119
- }
120
-
121
- async function writeToOpfs(filename, content) {
122
- const dir = await getOpfsLibDirectory();
123
- if (!dir) {
124
- return;
125
- }
126
- const handle = await dir.getFileHandle(filename, { create: true });
127
- const writable = await handle.createWritable();
128
- await writable.write(content);
129
- await writable.close();
130
- }
131
-
132
- async function fetchLibFile(baseUrl, filename) {
133
- const url = `${baseUrl}${filename}`;
134
- const response = await fetch(url, { cache: "no-cache" });
135
- if (!response.ok) {
136
- throw new Error(`Failed to fetch ${url}: ${response.status} ${response.statusText}`);
137
- }
138
- return response.text();
139
- }
140
-
141
- async function preload_mimium_lib_cache(base_url) {
142
- const baseUrlCandidate =
143
- base_url && base_url.length > 0
144
- ? base_url
145
- : `${DEFAULT_GITHUB_LIB_BASE}${DEFAULT_GITHUB_TAG}/lib/`;
146
- const baseUrl = baseUrlCandidate.endsWith("/") ? baseUrlCandidate : `${baseUrlCandidate}/`;
147
- globalThis.__mimium_lib_base_url = baseUrl;
148
- lastPreloadBaseUrl = baseUrl;
149
-
150
- if (isNode) {
151
- return;
152
- }
153
-
154
- for (const filename of LIB_FILES) {
155
- const fromMemory = memoryCache.get(filename);
156
- if (fromMemory !== undefined) {
157
- putMemoryAliases(filename, fromMemory);
158
- continue;
159
- }
160
-
161
- const fromOpfs = await readFromOpfs(filename);
162
- if (fromOpfs !== null) {
163
- putMemoryAliases(filename, fromOpfs);
164
- continue;
165
- }
166
-
167
- const fetched = await fetchLibFile(baseUrl, filename);
168
- putMemoryAliases(filename, fetched);
169
- await writeToOpfs(filename, fetched);
170
- }
171
- }
172
- exports.preload_mimium_lib_cache = preload_mimium_lib_cache;
173
-
174
- function __mimium_test_put_cache(path, content) {
175
- putMemoryAliases(path, content);
176
- }
177
- exports.__mimium_test_put_cache = __mimium_test_put_cache;
178
-
179
- function __mimium_test_clear_cache() {
180
- memoryCache.clear();
181
- lastPreloadBaseUrl = "";
182
- delete globalThis.__mimium_lib_base_url;
183
- }
184
- exports.__mimium_test_clear_cache = __mimium_test_clear_cache;
185
-
186
- function __mimium_test_get_last_preload_base_url() {
187
- return lastPreloadBaseUrl;
188
- }
189
- exports.__mimium_test_get_last_preload_base_url = __mimium_test_get_last_preload_base_url;
@@ -1,189 +0,0 @@
1
- let fs = null;
2
- const isNode = typeof process !== "undefined" && !!(process.versions && process.versions.node);
3
- if (isNode) {
4
- fs = require("fs");
5
- }
6
-
7
- const DEFAULT_GITHUB_LIB_BASE = "https://raw.githubusercontent.com/mimium-org/mimium-rs/";
8
- const DEFAULT_GITHUB_TAG = "dev";
9
- const LIB_FILES = [
10
- "core.mmm",
11
- "delay.mmm",
12
- "env.mmm",
13
- "filter.mmm",
14
- "math.mmm",
15
- "noise.mmm",
16
- "osc.mmm",
17
- "reactive.mmm",
18
- "reverb.mmm",
19
- ];
20
-
21
- const memoryCache = new Map();
22
- let lastPreloadBaseUrl = "";
23
-
24
- function normalizePath(path) {
25
- if (typeof path !== "string") {
26
- return "";
27
- }
28
- const slash = path.replace(/\\/g, "/").trim();
29
- const withoutPrefix = slash
30
- .replace(/^\/+/, "")
31
- .replace(/^\.\//, "")
32
- .replace(/^lib\//, "");
33
- const collapsed = withoutPrefix
34
- .split("/")
35
- .filter((seg) => seg.length > 0 && seg !== ".")
36
- .join("/");
37
- return collapsed;
38
- }
39
-
40
- function putMemoryAliases(filename, content) {
41
- const normalized = normalizePath(filename);
42
- if (!normalized) {
43
- return;
44
- }
45
- memoryCache.set(normalized, content);
46
- memoryCache.set(`./${normalized}`, content);
47
- memoryCache.set(`lib/${normalized}`, content);
48
- memoryCache.set(`/lib/${normalized}`, content);
49
- }
50
-
51
- function read_file(path) {
52
- if (isNode) {
53
- return fs.readFileSync(path, { encoding: "utf8" });
54
- }
55
-
56
- const normalized = normalizePath(path);
57
- const cached =
58
- memoryCache.get(path) ??
59
- memoryCache.get(normalized) ??
60
- memoryCache.get(`./${normalized}`) ??
61
- memoryCache.get(`lib/${normalized}`) ??
62
- memoryCache.get(`/lib/${normalized}`);
63
-
64
- if (cached !== undefined) {
65
- return cached;
66
- }
67
-
68
- throw new Error(
69
- `Include target not found in browser cache: ${path}. Call preload_mimium_lib_cache() before compile().`
70
- );
71
- }
72
- exports.read_file = read_file;
73
-
74
- function get_env(key) {
75
- if (isNode) {
76
- return process.env[key];
77
- }
78
- return undefined;
79
- }
80
- exports.get_env = get_env;
81
-
82
- async function getOpfsLibDirectory() {
83
- const cacheDirName = getCacheDirName();
84
- if (!globalThis.navigator || !navigator.storage || !navigator.storage.getDirectory) {
85
- return null;
86
- }
87
- const root = await navigator.storage.getDirectory();
88
- return root.getDirectoryHandle(cacheDirName, { create: true });
89
- }
90
-
91
- function getTagFromBaseUrl(baseUrl) {
92
- const normalized = (baseUrl || "").replace(/\/+$/, "");
93
- const marker = "raw.githubusercontent.com/mimium-org/mimium-rs/";
94
- const markerIdx = normalized.indexOf(marker);
95
- if (markerIdx < 0) {
96
- return DEFAULT_GITHUB_TAG;
97
- }
98
- const suffix = normalized.slice(markerIdx + marker.length);
99
- const tag = suffix.split("/")[0];
100
- return tag || DEFAULT_GITHUB_TAG;
101
- }
102
-
103
- function getCacheDirName() {
104
- return `mimium-lib-${getTagFromBaseUrl(globalThis.__mimium_lib_base_url || "")}`;
105
- }
106
-
107
- async function readFromOpfs(filename) {
108
- const dir = await getOpfsLibDirectory();
109
- if (!dir) {
110
- return null;
111
- }
112
- try {
113
- const handle = await dir.getFileHandle(filename, { create: false });
114
- const file = await handle.getFile();
115
- return await file.text();
116
- } catch {
117
- return null;
118
- }
119
- }
120
-
121
- async function writeToOpfs(filename, content) {
122
- const dir = await getOpfsLibDirectory();
123
- if (!dir) {
124
- return;
125
- }
126
- const handle = await dir.getFileHandle(filename, { create: true });
127
- const writable = await handle.createWritable();
128
- await writable.write(content);
129
- await writable.close();
130
- }
131
-
132
- async function fetchLibFile(baseUrl, filename) {
133
- const url = `${baseUrl}${filename}`;
134
- const response = await fetch(url, { cache: "no-cache" });
135
- if (!response.ok) {
136
- throw new Error(`Failed to fetch ${url}: ${response.status} ${response.statusText}`);
137
- }
138
- return response.text();
139
- }
140
-
141
- async function preload_mimium_lib_cache(base_url) {
142
- const baseUrlCandidate =
143
- base_url && base_url.length > 0
144
- ? base_url
145
- : `${DEFAULT_GITHUB_LIB_BASE}${DEFAULT_GITHUB_TAG}/lib/`;
146
- const baseUrl = baseUrlCandidate.endsWith("/") ? baseUrlCandidate : `${baseUrlCandidate}/`;
147
- globalThis.__mimium_lib_base_url = baseUrl;
148
- lastPreloadBaseUrl = baseUrl;
149
-
150
- if (isNode) {
151
- return;
152
- }
153
-
154
- for (const filename of LIB_FILES) {
155
- const fromMemory = memoryCache.get(filename);
156
- if (fromMemory !== undefined) {
157
- putMemoryAliases(filename, fromMemory);
158
- continue;
159
- }
160
-
161
- const fromOpfs = await readFromOpfs(filename);
162
- if (fromOpfs !== null) {
163
- putMemoryAliases(filename, fromOpfs);
164
- continue;
165
- }
166
-
167
- const fetched = await fetchLibFile(baseUrl, filename);
168
- putMemoryAliases(filename, fetched);
169
- await writeToOpfs(filename, fetched);
170
- }
171
- }
172
- exports.preload_mimium_lib_cache = preload_mimium_lib_cache;
173
-
174
- function __mimium_test_put_cache(path, content) {
175
- putMemoryAliases(path, content);
176
- }
177
- exports.__mimium_test_put_cache = __mimium_test_put_cache;
178
-
179
- function __mimium_test_clear_cache() {
180
- memoryCache.clear();
181
- lastPreloadBaseUrl = "";
182
- delete globalThis.__mimium_lib_base_url;
183
- }
184
- exports.__mimium_test_clear_cache = __mimium_test_clear_cache;
185
-
186
- function __mimium_test_get_last_preload_base_url() {
187
- return lastPreloadBaseUrl;
188
- }
189
- exports.__mimium_test_get_last_preload_base_url = __mimium_test_get_last_preload_base_url;
@@ -1,315 +0,0 @@
1
- let fs = null;
2
- const isNode = typeof process !== 'undefined' && !!(process.versions && process.versions.node);
3
- if (isNode) {
4
- const nodeModule = await import('node:fs');
5
- fs = nodeModule.default ?? nodeModule;
6
- }
7
-
8
- const DEFAULT_GITHUB_LIB_BASE = 'https://raw.githubusercontent.com/mimium-org/mimium-rs/';
9
- const DEFAULT_GITHUB_TAG = 'dev';
10
- const LIB_FILES = [
11
- 'core.mmm',
12
- 'delay.mmm',
13
- 'env.mmm',
14
- 'filter.mmm',
15
- 'math.mmm',
16
- 'noise.mmm',
17
- 'osc.mmm',
18
- 'reactive.mmm',
19
- 'reverb.mmm'
20
- ];
21
-
22
- const memoryCache = new Map();
23
- let lastPreloadBaseUrl = '';
24
- let lastModulePreloadBaseUrl = '';
25
-
26
- function normalizePath(path) {
27
- if (typeof path !== 'string') {
28
- return '';
29
- }
30
- const slash = path.replace(/\\/g, '/').trim();
31
- const withoutPrefix = slash.replace(/^\/+/, '').replace(/^\.\//, '').replace(/^lib\//, '');
32
- const collapsed = withoutPrefix
33
- .split('/')
34
- .filter((seg) => seg.length > 0 && seg !== '.')
35
- .join('/');
36
- return collapsed;
37
- }
38
-
39
- function normalizeBaseUrlCandidate(baseUrlCandidate) {
40
- if (!baseUrlCandidate || baseUrlCandidate.length === 0) {
41
- return '';
42
- }
43
-
44
- let resolved = baseUrlCandidate;
45
- if (typeof location !== 'undefined') {
46
- resolved = new URL(baseUrlCandidate, location.href).toString();
47
- }
48
-
49
- try {
50
- const parsed = new URL(resolved);
51
- if (parsed.hostname !== 'github.com') {
52
- return resolved;
53
- }
54
-
55
- const segments = parsed.pathname.split('/').filter((segment) => segment.length > 0);
56
- const [owner, repo, mode, ref, ...rest] = segments;
57
- if (!owner || !repo || !mode || !ref) {
58
- return resolved;
59
- }
60
- if (mode !== 'tree' && mode !== 'blob') {
61
- return resolved;
62
- }
63
-
64
- const restPath = rest.join('/');
65
- const rawPath = restPath.length > 0 ? `/${owner}/${repo}/${ref}/${restPath}` : `/${owner}/${repo}/${ref}`;
66
- return `https://raw.githubusercontent.com${rawPath}`;
67
- } catch {
68
- return resolved;
69
- }
70
- }
71
-
72
- function putMemoryAliases(filename, content) {
73
- const normalized = normalizePath(filename);
74
- if (!normalized) {
75
- return;
76
- }
77
- memoryCache.set(normalized, content);
78
- memoryCache.set(`./${normalized}`, content);
79
- memoryCache.set(`lib/${normalized}`, content);
80
- memoryCache.set(`/lib/${normalized}`, content);
81
- }
82
-
83
- function read_file(path) {
84
- if (isNode) {
85
- return fs.readFileSync(path, { encoding: 'utf8' });
86
- }
87
-
88
- const normalized = normalizePath(path);
89
- const cached =
90
- memoryCache.get(path) ??
91
- memoryCache.get(normalized) ??
92
- memoryCache.get(`./${normalized}`) ??
93
- memoryCache.get(`lib/${normalized}`) ??
94
- memoryCache.get(`/lib/${normalized}`);
95
-
96
- if (cached !== undefined) {
97
- return cached;
98
- }
99
-
100
- throw new Error(
101
- `Include target not found in browser cache: ${path}. Call preload_mimium_lib_cache() before compile().`
102
- );
103
- }
104
-
105
- function get_env(key) {
106
- if (isNode) {
107
- return process.env[key];
108
- }
109
- return undefined;
110
- }
111
-
112
- async function getOpfsLibDirectory() {
113
- const cacheDirName = getCacheDirName();
114
- if (!globalThis.navigator || !navigator.storage || !navigator.storage.getDirectory) {
115
- return null;
116
- }
117
- const root = await navigator.storage.getDirectory();
118
- return root.getDirectoryHandle(cacheDirName, { create: true });
119
- }
120
-
121
- function getTagFromBaseUrl(baseUrl) {
122
- const normalized = (baseUrl || '').replace(/\/+$/, '');
123
- const marker = 'raw.githubusercontent.com/mimium-org/mimium-rs/';
124
- const markerIdx = normalized.indexOf(marker);
125
- if (markerIdx < 0) {
126
- return DEFAULT_GITHUB_TAG;
127
- }
128
- const suffix = normalized.slice(markerIdx + marker.length);
129
- const tag = suffix.split('/')[0];
130
- return tag || DEFAULT_GITHUB_TAG;
131
- }
132
-
133
- function getCacheDirName() {
134
- return `mimium-lib-${getTagFromBaseUrl(globalThis.__mimium_lib_base_url || '')}`;
135
- }
136
-
137
- async function readFromOpfs(filename) {
138
- const dir = await getOpfsLibDirectory();
139
- if (!dir) {
140
- return null;
141
- }
142
- try {
143
- const handle = await dir.getFileHandle(filename, { create: false });
144
- const file = await handle.getFile();
145
- return await file.text();
146
- } catch {
147
- return null;
148
- }
149
- }
150
-
151
- async function writeToOpfs(filename, content) {
152
- const dir = await getOpfsLibDirectory();
153
- if (!dir) {
154
- return;
155
- }
156
- const handle = await dir.getFileHandle(filename, { create: true });
157
- const writable = await handle.createWritable();
158
- await writable.write(content);
159
- await writable.close();
160
- }
161
-
162
- async function fetchLibFile(baseUrl, filename) {
163
- const url = `${baseUrl}${filename}`;
164
- const response = await fetch(url, { cache: 'no-cache' });
165
- if (!response.ok) {
166
- throw new Error(`Failed to fetch ${url}: ${response.status} ${response.statusText}`);
167
- }
168
- return response.text();
169
- }
170
-
171
- function collectDependencies(source) {
172
- const moduleDeps = [...source.matchAll(/^\s*mod\s+([A-Za-z_][A-Za-z0-9_]*)\s*$/gm)].map(
173
- (match) => `${match[1]}.mmm`
174
- );
175
- const includeDeps = [...source.matchAll(/^\s*include\(\s*"([^"]+)"\s*\)\s*$/gm)].map(
176
- (match) => match[1]
177
- );
178
- return [...new Set([...moduleDeps, ...includeDeps])];
179
- }
180
-
181
- function getModuleBaseUrl(base_url) {
182
- const candidate =
183
- base_url && base_url.length > 0
184
- ? base_url
185
- : globalThis.__mimium_module_base_url ||
186
- (typeof location !== 'undefined' ? new URL('.', location.href).toString() : '');
187
- if (!candidate) {
188
- return '';
189
- }
190
- const normalized = normalizeBaseUrlCandidate(candidate);
191
- return normalized.endsWith('/') ? normalized : `${normalized}/`;
192
- }
193
-
194
- async function fetchSourceFromBaseUrl(baseUrl, relativePath) {
195
- const url = new URL(relativePath, baseUrl).toString();
196
- const response = await fetch(url, { cache: 'no-cache' });
197
- if (!response.ok) {
198
- throw new Error(`Failed to fetch ${url}: ${response.status} ${response.statusText}`);
199
- }
200
- return response.text();
201
- }
202
-
203
- async function preload_user_module_cache(source, base_url) {
204
- if (isNode) {
205
- return;
206
- }
207
-
208
- const baseUrl = getModuleBaseUrl(base_url);
209
- if (!baseUrl) {
210
- return;
211
- }
212
- globalThis.__mimium_module_base_url = baseUrl;
213
- lastModulePreloadBaseUrl = baseUrl;
214
-
215
- const pending = collectDependencies(source);
216
- const visited = new Set();
217
-
218
- while (pending.length > 0) {
219
- const depPath = pending.pop();
220
- const normalized = normalizePath(depPath || '');
221
- if (!normalized || visited.has(normalized)) {
222
- continue;
223
- }
224
- visited.add(normalized);
225
-
226
- const cached =
227
- memoryCache.get(depPath) ??
228
- memoryCache.get(normalized) ??
229
- memoryCache.get(`./${normalized}`) ??
230
- memoryCache.get(`lib/${normalized}`) ??
231
- memoryCache.get(`/lib/${normalized}`);
232
- if (cached !== undefined) {
233
- collectDependencies(cached).forEach((nestedDep) => pending.push(nestedDep));
234
- continue;
235
- }
236
-
237
- const fetched = await fetchSourceFromBaseUrl(baseUrl, depPath);
238
- putMemoryAliases(depPath, fetched);
239
- collectDependencies(fetched).forEach((nestedDep) => pending.push(nestedDep));
240
- }
241
- }
242
-
243
- async function preload_mimium_lib_cache(base_url) {
244
- const baseUrlCandidate =
245
- base_url && base_url.length > 0
246
- ? base_url
247
- : `${DEFAULT_GITHUB_LIB_BASE}${DEFAULT_GITHUB_TAG}/lib/`;
248
- const normalizedBaseUrl = normalizeBaseUrlCandidate(baseUrlCandidate);
249
- const baseUrl = normalizedBaseUrl.endsWith('/') ? normalizedBaseUrl : `${normalizedBaseUrl}/`;
250
- globalThis.__mimium_lib_base_url = baseUrl;
251
- lastPreloadBaseUrl = baseUrl;
252
-
253
- if (isNode) {
254
- return;
255
- }
256
-
257
- for (const filename of LIB_FILES) {
258
- const fromMemory = memoryCache.get(filename);
259
- if (fromMemory !== undefined) {
260
- putMemoryAliases(filename, fromMemory);
261
- continue;
262
- }
263
-
264
- const fromOpfs = await readFromOpfs(filename);
265
- if (fromOpfs !== null) {
266
- putMemoryAliases(filename, fromOpfs);
267
- continue;
268
- }
269
-
270
- const fetched = await fetchLibFile(baseUrl, filename);
271
- putMemoryAliases(filename, fetched);
272
- await writeToOpfs(filename, fetched);
273
- }
274
- }
275
-
276
- function __mimium_test_put_cache(path, content) {
277
- putMemoryAliases(path, content);
278
- }
279
-
280
- function __mimium_test_clear_cache() {
281
- memoryCache.clear();
282
- lastPreloadBaseUrl = '';
283
- lastModulePreloadBaseUrl = '';
284
- delete globalThis.__mimium_lib_base_url;
285
- delete globalThis.__mimium_module_base_url;
286
- }
287
-
288
- function __mimium_test_get_last_preload_base_url() {
289
- return lastPreloadBaseUrl;
290
- }
291
-
292
- function __mimium_test_get_last_module_preload_base_url() {
293
- return lastModulePreloadBaseUrl;
294
- }
295
-
296
- function set_module_base_url(base_url) {
297
- const normalized = getModuleBaseUrl(base_url);
298
- if (!normalized) {
299
- delete globalThis.__mimium_module_base_url;
300
- return;
301
- }
302
- globalThis.__mimium_module_base_url = normalized;
303
- }
304
-
305
- export {
306
- read_file,
307
- get_env,
308
- preload_mimium_lib_cache,
309
- preload_user_module_cache,
310
- set_module_base_url,
311
- __mimium_test_put_cache,
312
- __mimium_test_clear_cache,
313
- __mimium_test_get_last_preload_base_url,
314
- __mimium_test_get_last_module_preload_base_url
315
- };