@zephyr3d/scene 0.8.1 → 0.9.0

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 (241) hide show
  1. package/dist/animation/animationset.js +563 -128
  2. package/dist/animation/animationset.js.map +1 -1
  3. package/dist/animation/cloth/gpu_cloth_system.js +2516 -0
  4. package/dist/animation/cloth/gpu_cloth_system.js.map +1 -0
  5. package/dist/animation/fixed_geometry_cache_track.js +138 -0
  6. package/dist/animation/fixed_geometry_cache_track.js.map +1 -0
  7. package/dist/animation/geometry_cache_utils.js +120 -0
  8. package/dist/animation/geometry_cache_utils.js.map +1 -0
  9. package/dist/animation/ik_modifier.js +9 -1
  10. package/dist/animation/ik_modifier.js.map +1 -1
  11. package/dist/animation/joint_dynamics/collision.js +469 -0
  12. package/dist/animation/joint_dynamics/collision.js.map +1 -0
  13. package/dist/animation/joint_dynamics/constraints.js +329 -0
  14. package/dist/animation/joint_dynamics/constraints.js.map +1 -0
  15. package/dist/animation/joint_dynamics/controller.js +699 -0
  16. package/dist/animation/joint_dynamics/controller.js.map +1 -0
  17. package/dist/animation/joint_dynamics/joint_dynamics_system.js +393 -0
  18. package/dist/animation/joint_dynamics/joint_dynamics_system.js.map +1 -0
  19. package/dist/animation/joint_dynamics/solver.js +794 -0
  20. package/dist/animation/joint_dynamics/solver.js.map +1 -0
  21. package/dist/animation/joint_dynamics/types.js +19 -0
  22. package/dist/animation/joint_dynamics/types.js.map +1 -0
  23. package/dist/animation/joint_dynamics/vrm_spring_bone.js +46 -0
  24. package/dist/animation/joint_dynamics/vrm_spring_bone.js.map +1 -0
  25. package/dist/animation/joint_dynamics_modifier.js +51 -0
  26. package/dist/animation/joint_dynamics_modifier.js.map +1 -0
  27. package/dist/animation/pca_geometry_cache_track.js +222 -0
  28. package/dist/animation/pca_geometry_cache_track.js.map +1 -0
  29. package/dist/animation/skeleton.js +1907 -3
  30. package/dist/animation/skeleton.js.map +1 -1
  31. package/dist/animation/skeleton_modifier.js +3 -5
  32. package/dist/animation/skeleton_modifier.js.map +1 -1
  33. package/dist/animation/spring/multi_chain_spring_system.js +2 -0
  34. package/dist/animation/spring/multi_chain_spring_system.js.map +1 -1
  35. package/dist/animation/spring/spring_chain.js +3 -2
  36. package/dist/animation/spring/spring_chain.js.map +1 -1
  37. package/dist/animation/spring/spring_collider.js +35 -5
  38. package/dist/animation/spring/spring_collider.js.map +1 -1
  39. package/dist/animation/spring/spring_particle.js +1 -0
  40. package/dist/animation/spring/spring_particle.js.map +1 -1
  41. package/dist/animation/spring/spring_system.js +325 -28
  42. package/dist/animation/spring/spring_system.js.map +1 -1
  43. package/dist/animation/spring2/collision.js +469 -0
  44. package/dist/animation/spring2/collision.js.map +1 -0
  45. package/dist/animation/spring2/constraints.js +329 -0
  46. package/dist/animation/spring2/constraints.js.map +1 -0
  47. package/dist/animation/spring2/controller.js +434 -0
  48. package/dist/animation/spring2/controller.js.map +1 -0
  49. package/dist/animation/spring2/math.js +16 -0
  50. package/dist/animation/spring2/math.js.map +1 -0
  51. package/dist/animation/spring2/solver.js +624 -0
  52. package/dist/animation/spring2/solver.js.map +1 -0
  53. package/dist/animation/spring2/spring_system.js +118 -0
  54. package/dist/animation/spring2/spring_system.js.map +1 -0
  55. package/dist/animation/spring2/types.js +19 -0
  56. package/dist/animation/spring2/types.js.map +1 -0
  57. package/dist/animation/spring_modifier.js +17 -1
  58. package/dist/animation/spring_modifier.js.map +1 -1
  59. package/dist/app/engine.js +42 -15
  60. package/dist/app/engine.js.map +1 -1
  61. package/dist/app/runtimescript.js +132 -1
  62. package/dist/app/runtimescript.js.map +1 -1
  63. package/dist/app/screen.js +3 -3
  64. package/dist/app/screen.js.map +1 -1
  65. package/dist/app/scriptingsystem.js +69 -37
  66. package/dist/app/scriptingsystem.js.map +1 -1
  67. package/dist/app/scriptregistry.js +157 -146
  68. package/dist/app/scriptregistry.js.map +1 -1
  69. package/dist/asset/assetmanager.js +2 -1
  70. package/dist/asset/assetmanager.js.map +1 -1
  71. package/dist/asset/loaders/zabc/zabc_loader.js +570 -0
  72. package/dist/asset/loaders/zabc/zabc_loader.js.map +1 -0
  73. package/dist/asset/model.js +192 -0
  74. package/dist/asset/model.js.map +1 -1
  75. package/dist/camera/base.js +26 -7
  76. package/dist/camera/base.js.map +1 -1
  77. package/dist/camera/camera.js +146 -24
  78. package/dist/camera/camera.js.map +1 -1
  79. package/dist/camera/fps.js +2 -2
  80. package/dist/camera/fps.js.map +1 -1
  81. package/dist/camera/orbit.js +2 -2
  82. package/dist/camera/orbit.js.map +1 -1
  83. package/dist/index.d.ts +11701 -8506
  84. package/dist/index.js +29 -8
  85. package/dist/index.js.map +1 -1
  86. package/dist/material/lambert.js +1 -1
  87. package/dist/material/lambert.js.map +1 -1
  88. package/dist/material/material.js +9 -3
  89. package/dist/material/material.js.map +1 -1
  90. package/dist/material/meshmaterial.js +54 -7
  91. package/dist/material/meshmaterial.js.map +1 -1
  92. package/dist/material/mixins/lightmodel/blinnphong.js +17 -7
  93. package/dist/material/mixins/lightmodel/blinnphong.js.map +1 -1
  94. package/dist/material/mixins/lightmodel/lambert.js +7 -2
  95. package/dist/material/mixins/lightmodel/lambert.js.map +1 -1
  96. package/dist/material/mixins/lightmodel/pbrblueprintmixin.js +108 -16
  97. package/dist/material/mixins/lightmodel/pbrblueprintmixin.js.map +1 -1
  98. package/dist/material/mixins/lightmodel/pbrmetallicroughness.js +222 -14
  99. package/dist/material/mixins/lightmodel/pbrmetallicroughness.js.map +1 -1
  100. package/dist/material/mixins/lightmodel/pbrspecularglossness.js +24 -12
  101. package/dist/material/mixins/lightmodel/pbrspecularglossness.js.map +1 -1
  102. package/dist/material/mixins/lit.js +11 -8
  103. package/dist/material/mixins/lit.js.map +1 -1
  104. package/dist/material/mixins/pbr/common.js +72 -5
  105. package/dist/material/mixins/pbr/common.js.map +1 -1
  106. package/dist/material/pbrblueprint.js +148 -1
  107. package/dist/material/pbrblueprint.js.map +1 -1
  108. package/dist/material/pbrmr.js +125 -2
  109. package/dist/material/pbrmr.js.map +1 -1
  110. package/dist/material/shader/helper.js +10 -4
  111. package/dist/material/shader/helper.js.map +1 -1
  112. package/dist/material/water.js +2 -2
  113. package/dist/material/water.js.map +1 -1
  114. package/dist/posteffect/coloradjust.js +145 -0
  115. package/dist/posteffect/coloradjust.js.map +1 -0
  116. package/dist/posteffect/taa.js +68 -32
  117. package/dist/posteffect/taa.js.map +1 -1
  118. package/dist/render/cluster_light.js +17 -12
  119. package/dist/render/cluster_light.js.map +1 -1
  120. package/dist/render/deferredlightpass.js +510 -0
  121. package/dist/render/deferredlightpass.js.map +1 -0
  122. package/dist/render/deferredshadowlightpass.js +428 -0
  123. package/dist/render/deferredshadowlightpass.js.map +1 -0
  124. package/dist/render/drawable.js.map +1 -1
  125. package/dist/render/drawable_mixin.js +21 -12
  126. package/dist/render/drawable_mixin.js.map +1 -1
  127. package/dist/render/envlight.js +20 -22
  128. package/dist/render/envlight.js.map +1 -1
  129. package/dist/render/gbufferpass.js +50 -0
  130. package/dist/render/gbufferpass.js.map +1 -0
  131. package/dist/render/lightpass.js +1 -2
  132. package/dist/render/lightpass.js.map +1 -1
  133. package/dist/render/primitive.js +1 -1
  134. package/dist/render/primitive.js.map +1 -1
  135. package/dist/render/render_queue.js +3 -2
  136. package/dist/render/render_queue.js.map +1 -1
  137. package/dist/render/renderer.js +5 -358
  138. package/dist/render/renderer.js.map +1 -1
  139. package/dist/render/rendergraph/executor.js +15 -12
  140. package/dist/render/rendergraph/executor.js.map +1 -1
  141. package/dist/render/rendergraph/forward_plus_builder.js +144 -88
  142. package/dist/render/rendergraph/forward_plus_builder.js.map +1 -1
  143. package/dist/render/rendergraph/history_resource_manager.js +178 -0
  144. package/dist/render/rendergraph/history_resource_manager.js.map +1 -0
  145. package/dist/render/rendergraph/rendergraph.js +12 -1
  146. package/dist/render/rendergraph/rendergraph.js.map +1 -1
  147. package/dist/render/rendergraph/types.js +2 -2
  148. package/dist/render/rendergraph/types.js.map +1 -1
  149. package/dist/render/sky.js +26 -9
  150. package/dist/render/sky.js.map +1 -1
  151. package/dist/scene/basesprite.js +4 -3
  152. package/dist/scene/basesprite.js.map +1 -1
  153. package/dist/scene/batchgroup.js +4 -4
  154. package/dist/scene/environment.js +7 -4
  155. package/dist/scene/environment.js.map +1 -1
  156. package/dist/scene/light.js +184 -18
  157. package/dist/scene/light.js.map +1 -1
  158. package/dist/scene/mesh.js +30 -0
  159. package/dist/scene/mesh.js.map +1 -1
  160. package/dist/scene/particlesys.js +3 -2
  161. package/dist/scene/particlesys.js.map +1 -1
  162. package/dist/scene/raycast_visitor.js +29 -3
  163. package/dist/scene/raycast_visitor.js.map +1 -1
  164. package/dist/scene/scene.js +86 -19
  165. package/dist/scene/scene.js.map +1 -1
  166. package/dist/scene/scene_node.js +87 -31
  167. package/dist/scene/scene_node.js.map +1 -1
  168. package/dist/scene/script_attachment.js +59 -0
  169. package/dist/scene/script_attachment.js.map +1 -0
  170. package/dist/scene/terrain-cm/grass.js +3 -2
  171. package/dist/scene/terrain-cm/grass.js.map +1 -1
  172. package/dist/scene/terrain-cm/terrain-cm.js +4 -3
  173. package/dist/scene/terrain-cm/terrain-cm.js.map +1 -1
  174. package/dist/scene/water.js +3 -2
  175. package/dist/scene/water.js.map +1 -1
  176. package/dist/shaders/shadow.js +2 -2
  177. package/dist/shaders/shadow.js.map +1 -1
  178. package/dist/shadow/shadowmapper.js +74 -4
  179. package/dist/shadow/shadowmapper.js.map +1 -1
  180. package/dist/shapes/box.js +163 -0
  181. package/dist/shapes/box.js.map +1 -1
  182. package/dist/shapes/capsule.js +216 -0
  183. package/dist/shapes/capsule.js.map +1 -0
  184. package/dist/shapes/cylinder.js +91 -0
  185. package/dist/shapes/cylinder.js.map +1 -1
  186. package/dist/shapes/plane.js +32 -0
  187. package/dist/shapes/plane.js.map +1 -1
  188. package/dist/shapes/tetrahedron.js +211 -0
  189. package/dist/shapes/tetrahedron.js.map +1 -1
  190. package/dist/shapes/torus.js +173 -0
  191. package/dist/shapes/torus.js.map +1 -1
  192. package/dist/utility/blueprint/common/math.js +111 -1
  193. package/dist/utility/blueprint/common/math.js.map +1 -1
  194. package/dist/utility/blueprint/material/inputs.js +235 -1
  195. package/dist/utility/blueprint/material/inputs.js.map +1 -1
  196. package/dist/utility/blueprint/material/ir.js +154 -10
  197. package/dist/utility/blueprint/material/ir.js.map +1 -1
  198. package/dist/utility/blueprint/material/texture.js +273 -19
  199. package/dist/utility/blueprint/material/texture.js.map +1 -1
  200. package/dist/utility/serialization/json.js +12 -2
  201. package/dist/utility/serialization/json.js.map +1 -1
  202. package/dist/utility/serialization/manager.js +30 -11
  203. package/dist/utility/serialization/manager.js.map +1 -1
  204. package/dist/utility/serialization/scene/animation.js +250 -7
  205. package/dist/utility/serialization/scene/animation.js.map +1 -1
  206. package/dist/utility/serialization/scene/batch.js +4 -2
  207. package/dist/utility/serialization/scene/batch.js.map +1 -1
  208. package/dist/utility/serialization/scene/camera.js +154 -2
  209. package/dist/utility/serialization/scene/camera.js.map +1 -1
  210. package/dist/utility/serialization/scene/cloth_script.js +834 -0
  211. package/dist/utility/serialization/scene/cloth_script.js.map +1 -0
  212. package/dist/utility/serialization/scene/common.js +7 -0
  213. package/dist/utility/serialization/scene/common.js.map +1 -1
  214. package/dist/utility/serialization/scene/light.js +120 -4
  215. package/dist/utility/serialization/scene/light.js.map +1 -1
  216. package/dist/utility/serialization/scene/material.js +453 -1
  217. package/dist/utility/serialization/scene/material.js.map +1 -1
  218. package/dist/utility/serialization/scene/mesh.js +4 -2
  219. package/dist/utility/serialization/scene/mesh.js.map +1 -1
  220. package/dist/utility/serialization/scene/node.js +298 -10
  221. package/dist/utility/serialization/scene/node.js.map +1 -1
  222. package/dist/utility/serialization/scene/particle.js +4 -2
  223. package/dist/utility/serialization/scene/particle.js.map +1 -1
  224. package/dist/utility/serialization/scene/primitive.js +100 -3
  225. package/dist/utility/serialization/scene/primitive.js.map +1 -1
  226. package/dist/utility/serialization/scene/scene.js +130 -3
  227. package/dist/utility/serialization/scene/scene.js.map +1 -1
  228. package/dist/utility/serialization/scene/script.js +66 -0
  229. package/dist/utility/serialization/scene/script.js.map +1 -0
  230. package/dist/utility/serialization/scene/spring_script.js +596 -0
  231. package/dist/utility/serialization/scene/spring_script.js.map +1 -0
  232. package/dist/utility/serialization/scene/sprite.js +5 -3
  233. package/dist/utility/serialization/scene/sprite.js.map +1 -1
  234. package/dist/utility/serialization/scene/terrain.js +4 -2
  235. package/dist/utility/serialization/scene/terrain.js.map +1 -1
  236. package/dist/utility/serialization/scene/water.js +4 -2
  237. package/dist/utility/serialization/scene/water.js.map +1 -1
  238. package/dist/utility/serialization/types.js.map +1 -1
  239. package/dist/values.js +5 -1
  240. package/dist/values.js.map +1 -1
  241. package/package.json +3 -3
@@ -1 +1 @@
1
- {"version":3,"file":"scriptingsystem.js","sources":["../../src/app/scriptingsystem.ts"],"sourcesContent":["import type { IDisposable, Nullable, VFS } from '@zephyr3d/base';\r\nimport { HttpFS } from '@zephyr3d/base';\r\nimport { ScriptRegistry } from './scriptregistry';\r\nimport { RuntimeScript } from './runtimescript';\r\n\r\n/**\r\n * A host object that supports disposal.\r\n *\r\n * Hosts are objects to which scripts can be attached. They are expected to\r\n * emit a `'dispose'` event compatible with `IDisposable` so that scripts\r\n * can be automatically detached when the host is destroyed.\r\n *\r\n * @public\r\n */\r\nexport type Host = IDisposable;\r\n\r\n/**\r\n * Options for configuring a `ScriptingSystem`.\r\n *\r\n * @public\r\n */\r\nexport type ScriptingSystemOptions = {\r\n /** Virtual file system used by the script registry. Defaults to `new HttpFS('./')`. */\r\n VFS?: VFS;\r\n /** Root path for scripts within the VFS. Defaults to `/`. */\r\n scriptsRoot?: string;\r\n /**\r\n * Optional string appended to dynamic import URLs (e.g., for cache busting).\r\n * Example: `'?v=' + Date.now()`\r\n */\r\n importComment?: string;\r\n /**\r\n * Optional callback invoked when a module fails to load.\r\n * @param e - The error that occurred.\r\n * @param id - The module ID that failed to load.\r\n */\r\n onLoadError?: (e: unknown, id: string) => void;\r\n};\r\n\r\n/**\r\n * Information about a script attached to a host.\r\n *\r\n * @public\r\n */\r\nexport interface IAttachedScript {\r\n /** The logical module identifier used to resolve the script. */\r\n id: string;\r\n /** The resolved runtime URL used for dynamic import. */\r\n url: string;\r\n /** The instantiated runtime script. */\r\n instance: RuntimeScript<any>;\r\n}\r\n\r\n/**\r\n * Script system that resolves, loads, and manages lifecycle of runtime scripts.\r\n *\r\n * Responsibilities:\r\n * - Resolves module IDs to URLs via {@link ScriptRegistry}\r\n * - Dynamically imports modules and instantiates a `RuntimeScript` (default export)\r\n * - Tracks attachments between hosts and script instances\r\n * - Bridges script lifecycle hooks: `onCreated`, `onAttached`, `onDetached`, `onDestroy`, `onUpdate`\r\n * - Auto-detaches scripts when a host is disposed\r\n *\r\n * Notes:\r\n * - Multiple hosts can reference the same `RuntimeScript` instance; destruction\r\n * occurs when the last host detaches.\r\n * - Errors during load/attach/update are caught and logged; an optional\r\n * `onLoadError` callback can be provided.\r\n *\r\n * @public\r\n */\r\nexport class ScriptingSystem {\r\n private _registry: ScriptRegistry;\r\n private _hostScripts: Map<Nullable<Host>, IAttachedScript[]>;\r\n private _scriptHosts: Map<RuntimeScript<any>, Nullable<Host>[]>;\r\n private _onLoadError?: (e: unknown, id: string) => void;\r\n private _importComment?: string;\r\n\r\n /**\r\n * Constructs a new scripting system.\r\n *\r\n * @param opts - Optional configuration.\r\n */\r\n constructor(opts: ScriptingSystemOptions = {}) {\r\n this._registry = new ScriptRegistry(opts.VFS ?? new HttpFS('./'), opts.scriptsRoot ?? '/');\r\n this._hostScripts = new Map();\r\n this._scriptHosts = new Map();\r\n this._importComment = opts.importComment;\r\n this._onLoadError = opts.onLoadError;\r\n }\r\n\r\n /**\r\n * Accessor for the underlying script registry used for module resolution.\r\n */\r\n get registry() {\r\n return this._registry;\r\n }\r\n\r\n /**\r\n * Attaches a script to a host and returns the `RuntimeScript` instance.\r\n *\r\n * Process:\r\n * 1. Resolve module ID to a runtime URL via the registry.\r\n * 2. Dynamically import the module.\r\n * 3. Instantiate the default export if it is a constructor.\r\n * 4. If this is the first time the instance is seen, call `onCreated()`.\r\n * 5. Link the instance to the host, and call `onAttached(host)`.\r\n * 6. Subscribe to the host's `'dispose'` event to auto-detach.\r\n *\r\n * If the module cannot be resolved or does not export a default `RuntimeScript`\r\n * subclass, a warning is logged and `null` is returned.\r\n *\r\n * @typeParam T - Host type.\r\n * @param host - The host object to attach the script to.\r\n * @param module - Module identifier used by the registry (logical ID or path).\r\n * @returns The instantiated `RuntimeScript<T>` or `null` on failure.\r\n */\r\n async attachScript<T extends Host>(host: Nullable<T>, module: string): Promise<Nullable<RuntimeScript<T>>> {\r\n try {\r\n const url = await this._registry.resolveRuntimeUrl(module);\r\n if (!url) {\r\n return null;\r\n }\r\n const mod = await import(url + (this._importComment ?? ''));\r\n let instance: Nullable<RuntimeScript<T>> = null;\r\n if (typeof mod?.default === 'function') {\r\n // default export\r\n instance = new mod.default();\r\n if (instance instanceof RuntimeScript) {\r\n if (!this._scriptHosts.has(instance)) {\r\n const P = instance.onCreated();\r\n if (P instanceof Promise) {\r\n await P;\r\n }\r\n }\r\n } else {\r\n instance = null;\r\n }\r\n }\r\n if (!instance) {\r\n console.warn(`Script '${module}' does not have RuntimeScript class exported as default`);\r\n return null;\r\n }\r\n\r\n let hostList = this._scriptHosts.get(instance);\r\n if (!hostList) {\r\n hostList = [];\r\n this._scriptHosts.set(instance, hostList);\r\n }\r\n if (hostList.includes(host)) {\r\n console.warn(`Script '${module}' already attached`);\r\n return instance;\r\n }\r\n hostList.push(host);\r\n\r\n const P = instance.onAttached(host);\r\n if (P instanceof Promise) {\r\n await P;\r\n }\r\n\r\n const attached: IAttachedScript = {\r\n id: module,\r\n url,\r\n instance\r\n };\r\n\r\n let list = this._hostScripts.get(host);\r\n if (!list) {\r\n list = [];\r\n this._hostScripts.set(host, list);\r\n if (host) {\r\n host.on('dispose', () => {\r\n this.detachScript(host);\r\n });\r\n }\r\n }\r\n list.push(attached);\r\n\r\n return attached.instance;\r\n } catch (e) {\r\n const moduleName = module ? String(module).slice(0, 64) : '';\r\n console.error(`Load module '${moduleName}' failed: ${e}`);\r\n this._onLoadError?.(e, module);\r\n return null;\r\n }\r\n }\r\n\r\n /**\r\n * Detaches script(s) from a host.\r\n *\r\n * Behavior:\r\n * - If `idOrInstance` is omitted, detaches all scripts from the host.\r\n * - If a module ID is provided, detaches only the matching script.\r\n * - If a `RuntimeScript` instance is provided, detaches that instance.\r\n * - Invokes `onDetached(host)` on each detached instance.\r\n * - If the instance has no remaining hosts, invokes `onDestroy()` and disposes tracking.\r\n *\r\n * @typeParam T - Host type.\r\n * @param host - The host to detach from.\r\n * @param idOrInstance - Optional module ID or script instance to target.\r\n */\r\n detachScript<T extends Host>(host: T, idOrInstance?: string | RuntimeScript<T>) {\r\n const list = this._hostScripts.get(host);\r\n if (!list || list.length === 0) {\r\n return;\r\n }\r\n for (let i = list.length - 1; i >= 0; i--) {\r\n const it = list[i];\r\n const hit =\r\n !idOrInstance || typeof idOrInstance === 'string'\r\n ? it.id === idOrInstance\r\n : it.instance === idOrInstance;\r\n if (hit) {\r\n list.splice(i, 1);\r\n try {\r\n it.instance.onDetached(host);\r\n } catch (err) {\r\n console.error(`Error occured at onDetach() of module '${it.id}': ${err}`);\r\n }\r\n\r\n const hostList = this._scriptHosts.get(it.instance);\r\n if (hostList) {\r\n const index = hostList.indexOf(host);\r\n if (index >= 0) {\r\n hostList.splice(index, 1);\r\n }\r\n }\r\n if (!hostList || hostList.length === 0) {\r\n try {\r\n it.instance.onDestroy();\r\n } catch (err) {\r\n console.error(`Error occured at onDestroy() of module '${it.id}': ${err}`);\r\n } finally {\r\n this._scriptHosts.delete(it.instance);\r\n }\r\n }\r\n }\r\n }\r\n if (list.length === 0) {\r\n this._hostScripts.delete(host);\r\n }\r\n }\r\n\r\n /**\r\n * Get all script instances attached to a host.\r\n *\r\n * @typeParam T - Expected script type.\r\n * @param host - The host whose scripts to retrieve.\r\n * @returns Script instances attached to the host, or an empty array if none.\r\n */\r\n getScriptObjects<T extends RuntimeScript<any>>(host: unknown): T[] {\r\n return (this._hostScripts.get(host as Host) as unknown as T[]) || [];\r\n }\r\n\r\n /**\r\n * Ticks all attached script instances.\r\n *\r\n * Calls `onUpdate(deltaTime, elapsedTime)` on every attached script instance\r\n * across all hosts. Exceptions thrown by a script are caught and logged,\r\n * allowing other scripts to continue updating.\r\n *\r\n * @param deltaTime - Time in seconds since last update.\r\n * @param elapsedTime - Total time in seconds since start.\r\n */\r\n update(deltaTime: number, elapsedTime: number) {\r\n if (this._hostScripts.size === 0) {\r\n return;\r\n }\r\n for (const list of this._hostScripts.values()) {\r\n for (const s of list) {\r\n try {\r\n s.instance.onUpdate(deltaTime, elapsedTime);\r\n } catch (err) {\r\n console.error(`Error occured at onUpdate() of module '${s.id}': ${err}`);\r\n }\r\n }\r\n }\r\n }\r\n\r\n /**\r\n * Detaches all scripts from all hosts.\r\n *\r\n * Iteratively calls {@link ScriptingSystem.detachScript} on each host until no attachments remain.\r\n */\r\n detachAllScripts() {\r\n while (this._hostScripts.size > 0) {\r\n for (const entry of this._hostScripts) {\r\n if (entry[0]) {\r\n this.detachScript(entry[0]);\r\n }\r\n }\r\n }\r\n }\r\n}\r\n"],"names":["ScriptingSystem","_registry","_hostScripts","_scriptHosts","_onLoadError","_importComment","opts","ScriptRegistry","VFS","HttpFS","scriptsRoot","Map","importComment","onLoadError","registry","attachScript","host","module","url","resolveRuntimeUrl","mod","instance","default","RuntimeScript","has","P","onCreated","Promise","console","warn","hostList","get","set","includes","push","onAttached","attached","id","list","on","detachScript","e","moduleName","String","slice","error","idOrInstance","length","i","it","hit","splice","onDetached","err","index","indexOf","onDestroy","delete","getScriptObjects","update","deltaTime","elapsedTime","size","values","s","onUpdate","detachAllScripts","entry"],"mappings":";;;;AAqDA;;;;;;;;;;;;;;;;;AAiBC,IACM,MAAMA,eAAAA,CAAAA;IACHC,SAA0B;IAC1BC,Y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tE;AAEA;;;;;;;;;AASC,MACD2C,MAAOC,CAAAA,SAAiB,EAAEC,WAAmB,EAAE;AAC7C,QAAA,IAAI,IAAI,CAAC3D,YAAY,CAAC4D,IAAI,KAAK,CAAG,EAAA;AAChC,YAAA;AACF;AACA,QAAA,KAAK,MAAMxB,IAAQ,IAAA,IAAI,CAACpC,YAAY,CAAC6D,MAAM,EAAI,CAAA;YAC7C,KAAK,MAAMC,KAAK1B,IAAM,CAAA;gBACpB,IAAI;AACF0B,oBAAAA,CAAAA,CAAE3C,QAAQ,CAAC4C,QAAQ,CAACL,SAAWC,EAAAA,WAAAA,CAAAA;AACjC,iBAAA,CAAE,OAAOR,GAAK,EAAA;oBACZzB,OAAQiB,CAAAA,KAAK,CAAC,CAAC,uCAAuC,EAAEmB,EAAE3B,EAAE,CAAC,GAAG,EAAEgB,GAAK,CAAA,CAAA,CAAA;AACzE;AACF;AACF;AACF;AAEA;;;;AAIC,MACDa,gBAAmB,GAAA;AACjB,QAAA,MAAO,IAAI,CAAChE,YAAY,CAAC4D,IAAI,GAAG,CAAG,CAAA;AACjC,YAAA,KAAK,MAAMK,KAAAA,IAAS,IAAI,CAACjE,YAAY,CAAE;gBACrC,IAAIiE,KAAK,CAAC,CAAA,CAAE,EAAE;AACZ,oBAAA,IAAI,CAAC3B,YAAY,CAAC2B,KAAK,CAAC,CAAE,CAAA,CAAA;AAC5B;AACF;AACF;AACF;AACF;;;;"}
1
+ {"version":3,"file":"scriptingsystem.js","sources":["../../src/app/scriptingsystem.ts"],"sourcesContent":["import type { GenericConstructor, IDisposable, Nullable, VFS } from '@zephyr3d/base';\r\nimport { HttpFS } from '@zephyr3d/base';\r\nimport { ScriptRegistry } from './scriptregistry';\r\nimport { applyRuntimeScriptConfig, RuntimeScript, type RuntimeScriptConfig } from './runtimescript';\r\n\r\n/**\r\n * A host object that supports disposal.\r\n *\r\n * Hosts are objects to which scripts can be attached. They are expected to\r\n * emit a `'dispose'` event compatible with `IDisposable` so that scripts\r\n * can be automatically detached when the host is destroyed.\r\n *\r\n * @public\r\n */\r\nexport type Host = IDisposable;\r\n\r\n/**\r\n * Options for configuring a `ScriptingSystem`.\r\n *\r\n * @public\r\n */\r\nexport type ScriptingSystemOptions = {\r\n /** Virtual file system used by the script registry. Defaults to `new HttpFS('./')`. */\r\n VFS?: VFS;\r\n /** Root path for scripts within the VFS. Defaults to `/`. */\r\n scriptsRoot?: string;\r\n /**\r\n * Optional string appended to dynamic import URLs (e.g., for cache busting).\r\n * Example: `'?v=' + Date.now()`\r\n */\r\n importComment?: string;\r\n /**\r\n * Optional callback invoked when a module fails to load.\r\n * @param e - The error that occurred.\r\n * @param id - The module ID that failed to load.\r\n */\r\n onLoadError?: (e: unknown, id: string) => void;\r\n};\r\n\r\n/**\r\n * Information about a script attached to a host.\r\n *\r\n * @public\r\n */\r\nexport interface IAttachedScript {\r\n /** The logical module identifier used to resolve the script. */\r\n id: string;\r\n /** The resolved runtime URL used for dynamic import. */\r\n url: string;\r\n /** The instantiated runtime script. */\r\n instance: RuntimeScript<any>;\r\n}\r\n\r\n/**\r\n * Script system that resolves, loads, and manages lifecycle of runtime scripts.\r\n *\r\n * Responsibilities:\r\n * - Resolves module IDs to URLs via {@link ScriptRegistry}\r\n * - Dynamically imports modules and instantiates a `RuntimeScript` (default export)\r\n * - Tracks attachments between hosts and script instances\r\n * - Bridges script lifecycle hooks: `onCreated`, `onAttached`, `onDetached`, `onDestroy`, `onUpdate`\r\n * - Auto-detaches scripts when a host is disposed\r\n *\r\n * Notes:\r\n * - Multiple hosts can reference the same `RuntimeScript` instance; destruction\r\n * occurs when the last host detaches.\r\n * - Errors during load/attach/update are caught and logged; an optional\r\n * `onLoadError` callback can be provided.\r\n *\r\n * @public\r\n */\r\nexport class ScriptingSystem {\r\n private _registry: ScriptRegistry;\r\n private _hostScripts: Map<Nullable<Host>, IAttachedScript[]>;\r\n private _scriptHosts: Map<RuntimeScript<any>, Nullable<Host>[]>;\r\n private _onLoadError?: (e: unknown, id: string) => void;\r\n private _importComment?: string;\r\n\r\n /**\r\n * Constructs a new scripting system.\r\n *\r\n * @param opts - Optional configuration.\r\n */\r\n constructor(opts: ScriptingSystemOptions = {}) {\r\n this._registry = new ScriptRegistry(opts.VFS ?? new HttpFS('./'), opts.scriptsRoot ?? '/');\r\n this._hostScripts = new Map();\r\n this._scriptHosts = new Map();\r\n this._importComment = opts.importComment;\r\n this._onLoadError = opts.onLoadError;\r\n }\r\n\r\n /**\r\n * Accessor for the underlying script registry used for module resolution.\r\n */\r\n get registry() {\r\n return this._registry;\r\n }\r\n /**\r\n * Loads a runtime script class from file\r\n * @param module - file path\r\n * @returns The runtime script class or null\r\n */\r\n async loadRuntimeScriptClass<T extends Host = Host>(\r\n module: string\r\n ): Promise<\r\n Nullable<{\r\n url: string;\r\n id: string;\r\n cls: GenericConstructor<RuntimeScript<T>>;\r\n }>\r\n > {\r\n let mod: any = null;\r\n const moduleName = module ? String(module).slice(0, 64) : '';\r\n let url = '';\r\n try {\r\n url = await this._registry.resolveRuntimeUrl(module);\r\n if (!url) {\r\n return null;\r\n }\r\n mod = await import(url + (this._importComment ?? ''));\r\n } catch (e) {\r\n console.error(`Load module '${moduleName}' failed: ${e}`);\r\n }\r\n if (mod && typeof mod.default === 'function') {\r\n return { url, id: module, cls: mod.default as GenericConstructor<RuntimeScript<T>> };\r\n } else {\r\n console.error(`No runtime class exported from '${moduleName}'`);\r\n return null;\r\n }\r\n }\r\n /**\r\n * Creates a script from a dynamic loaded class and attachs it to a host and returns the `RuntimeScript` instance.\r\n *\r\n * @typeParam T - Host type.\r\n * @param host - The host object to attach the script to.\r\n * @param classInfo - The dynamic loaded class information\r\n * @returns The instantiated `RuntimeScript<T>` or `null` on failure.\r\n */\r\n async attachScriptIndirect<T extends Host>(\r\n host: Nullable<T>,\r\n classInfo: {\r\n url: string;\r\n id: string;\r\n cls: GenericConstructor<RuntimeScript<T>>;\r\n },\r\n config?: Nullable<RuntimeScriptConfig>\r\n ): Promise<Nullable<RuntimeScript<T>>> {\r\n try {\r\n const { url, id, cls } = classInfo;\r\n let instance: Nullable<RuntimeScript<T>> = new cls();\r\n if (instance instanceof RuntimeScript) {\r\n applyRuntimeScriptConfig(instance, config);\r\n if (!this._scriptHosts.has(instance)) {\r\n const P = instance.onCreated();\r\n if (P instanceof Promise) {\r\n await P;\r\n }\r\n }\r\n } else {\r\n instance = null;\r\n }\r\n if (!instance) {\r\n console.warn(`Script '${url}' does not have RuntimeScript class exported as default`);\r\n return null;\r\n }\r\n\r\n let hostList = this._scriptHosts.get(instance);\r\n if (!hostList) {\r\n hostList = [];\r\n this._scriptHosts.set(instance, hostList);\r\n }\r\n if (hostList.includes(host)) {\r\n console.warn(`Script '${url}' already attached`);\r\n return instance;\r\n }\r\n hostList.push(host);\r\n\r\n const P = instance.onAttached(host);\r\n if (P instanceof Promise) {\r\n await P;\r\n }\r\n\r\n const attached: IAttachedScript = {\r\n id,\r\n url,\r\n instance\r\n };\r\n\r\n let list = this._hostScripts.get(host);\r\n if (!list) {\r\n list = [];\r\n this._hostScripts.set(host, list);\r\n if (host) {\r\n host.on('dispose', () => {\r\n this.detachScript(host);\r\n });\r\n }\r\n }\r\n list.push(attached);\r\n\r\n return attached.instance;\r\n } catch (e) {\r\n const moduleName = classInfo.id ? String(classInfo.id).slice(0, 64) : '';\r\n console.error(`Load module '${moduleName}' failed: ${e}`);\r\n this._onLoadError?.(e, classInfo.id);\r\n return null;\r\n }\r\n }\r\n /**\r\n * Attaches a script to a host and returns the `RuntimeScript` instance.\r\n *\r\n * Process:\r\n * 1. Resolve module ID to a runtime URL via the registry.\r\n * 2. Dynamically import the module.\r\n * 3. Instantiate the default export if it is a constructor.\r\n * 4. If this is the first time the instance is seen, call `onCreated()`.\r\n * 5. Link the instance to the host, and call `onAttached(host)`.\r\n * 6. Subscribe to the host's `'dispose'` event to auto-detach.\r\n *\r\n * If the module cannot be resolved or does not export a default `RuntimeScript`\r\n * subclass, a warning is logged and `null` is returned.\r\n *\r\n * @typeParam T - Host type.\r\n * @param host - The host object to attach the script to.\r\n * @param module - Module identifier used by the registry (logical ID or path).\r\n * @returns The instantiated `RuntimeScript<T>` or `null` on failure.\r\n */\r\n async attachScript<T extends Host>(\r\n host: Nullable<T>,\r\n module: string,\r\n config?: Nullable<RuntimeScriptConfig>\r\n ): Promise<Nullable<RuntimeScript<T>>> {\r\n const info = await this.loadRuntimeScriptClass(module);\r\n return info ? await this.attachScriptIndirect(host, info, config) : null;\r\n }\r\n\r\n /**\r\n * Detaches script(s) from a host.\r\n *\r\n * Behavior:\r\n * - If `idOrInstance` is omitted, detaches all scripts from the host.\r\n * - If a module ID is provided, detaches only the matching script.\r\n * - If a `RuntimeScript` instance is provided, detaches that instance.\r\n * - Invokes `onDetached(host)` on each detached instance.\r\n * - If the instance has no remaining hosts, invokes `onDestroy()` and disposes tracking.\r\n *\r\n * @typeParam T - Host type.\r\n * @param host - The host to detach from.\r\n * @param idOrInstance - Optional module ID or script instance to target.\r\n */\r\n detachScript<T extends Host>(host: T, idOrInstance?: string | RuntimeScript<T>) {\r\n const list = this._hostScripts.get(host);\r\n if (!list || list.length === 0) {\r\n return;\r\n }\r\n for (let i = list.length - 1; i >= 0; i--) {\r\n const it = list[i];\r\n const hit =\r\n !idOrInstance || typeof idOrInstance === 'string'\r\n ? it.id === idOrInstance\r\n : it.instance === idOrInstance;\r\n if (hit) {\r\n list.splice(i, 1);\r\n try {\r\n it.instance.onDetached(host);\r\n } catch (err) {\r\n console.error(`Error occured at onDetach() of module '${it.id}': ${err}`);\r\n }\r\n\r\n const hostList = this._scriptHosts.get(it.instance);\r\n if (hostList) {\r\n const index = hostList.indexOf(host);\r\n if (index >= 0) {\r\n hostList.splice(index, 1);\r\n }\r\n }\r\n if (!hostList || hostList.length === 0) {\r\n try {\r\n it.instance.onDestroy();\r\n } catch (err) {\r\n console.error(`Error occured at onDestroy() of module '${it.id}': ${err}`);\r\n } finally {\r\n this._scriptHosts.delete(it.instance);\r\n }\r\n }\r\n }\r\n }\r\n if (list.length === 0) {\r\n this._hostScripts.delete(host);\r\n }\r\n }\r\n\r\n /**\r\n * Get all script instances attached to a host.\r\n *\r\n * @typeParam T - Expected script type.\r\n * @param host - The host whose scripts to retrieve.\r\n * @returns Script instances attached to the host, or an empty array if none.\r\n */\r\n getScriptObjects<T extends RuntimeScript<any>>(host: unknown): T[] {\r\n return (this._hostScripts.get(host as Host) as unknown as T[]) || [];\r\n }\r\n\r\n /**\r\n * Ticks all attached script instances.\r\n *\r\n * Calls `onUpdate(deltaTime, elapsedTime)` on every attached script instance\r\n * across all hosts. Exceptions thrown by a script are caught and logged,\r\n * allowing other scripts to continue updating.\r\n *\r\n * @param deltaTime - Time in seconds since last update.\r\n * @param elapsedTime - Total time in seconds since start.\r\n */\r\n update(deltaTime: number, elapsedTime: number) {\r\n if (this._hostScripts.size === 0) {\r\n return;\r\n }\r\n for (const list of this._hostScripts.values()) {\r\n for (const s of list) {\r\n try {\r\n s.instance.onUpdate(deltaTime, elapsedTime);\r\n } catch (err) {\r\n console.error(`Error occured at onUpdate() of module '${s.id}': ${err}`);\r\n }\r\n }\r\n }\r\n }\r\n\r\n /**\r\n * Detaches all scripts from all hosts.\r\n *\r\n * Iteratively calls {@link ScriptingSystem.detachScript} on each host until no attachments remain.\r\n */\r\n detachAllScripts() {\r\n while (this._hostScripts.size > 0) {\r\n for (const entry of this._hostScripts) {\r\n if (entry[0]) {\r\n this.detachScript(entry[0]);\r\n }\r\n }\r\n }\r\n }\r\n}\r\n"],"names":["ScriptingSystem","_registry","_hostScripts","_scriptHosts","_onLoadError","_importComment","opts","ScriptRegistry","VFS","HttpFS","scriptsRoot","Map","importComment","onLoadError","registry","loadRuntimeScriptClass","module","mod","moduleName","String","slice","url","resolveRuntimeUrl","e","console","error","default","id","cls","attachScriptIndirect","host","classInfo","config","instance","RuntimeScript","applyRuntimeScriptConfig","has","P","onCreated","Promise","warn","hostList","get","set","includes","push","onAttached","attached","list","on","detachScript","attachScript","info","idOrInstance","length","i","it","hit","splice","onDetached","err","index","indexOf","onDestroy","delete","getScriptObjects","update","deltaTime","elapsedTime","size","values","s","onUpdate","detachAllScripts","entry"],"mappings":";;;;AAqDA;;;;;;;;;;;;;;;;;AAiBC,IACM,MAAMA,eAAAA,CAAAA;IACHC,SAA0B;IAC1BC,YAAqD;IACrDC,YAAwD;IACxDC,YAAgD;IAChDC,cAAwB;AAEhC;;;;AAIC,MACD,WAAYC,CAAAA,IAAAA,GAA+B,EAAE,CAAE;AAC7C,QAAA,IAAI,CAACL,SAAS,GAAG,IAAIM,cAAeD,CAAAA,IAAAA,CAAKE,GAAG,IAAI,IAAIC,MAAAA,CAAO,IAAOH,CAAAA,EAAAA,IAAAA,CAAKI,WAAW,IAAI,GAAA,CAAA;QACtF,IAAI,CAACR,YAAY,GAAG,IAAIS,GAAAA,EAAAA;QACxB,IAAI,CAACR,YAAY,GAAG,IAAIQ,GAAAA,EAAAA;AACxB,QAAA,IAAI,CAACN,cAAc,GAAGC,IAAAA,CAAKM,aAAa;AACxC,QAAA,IAAI,CAACR,YAAY,GAAGE,IAAAA,CAAKO,WAAW;AACtC;AAEA;;AAEC,MACD,IAAIC,QAAW,GAAA;QACb,OAAO,IAAI,CAACb,SAAS;AACvB;AACA;;;;MAKA,MAAMc,sBACJC,CAAAA,MAAc,EAOd;AACA,QAAA,IAAIC,GAAW,GAAA,IAAA;AACf,QAAA,MAAMC,aAAaF,MAASG,GAAAA,MAAAA,CAAOH,QAAQI,KAAK,CAAC,GAAG,EAAM,CAAA,GAAA,EAAA;AAC1D,QAAA,IAAIC,GAAM,GAAA,EAAA;QACV,IAAI;AACFA,YAAAA,GAAAA,GAAM,MAAM,IAAI,CAACpB,SAAS,CAACqB,iBAAiB,CAACN,MAAAA,CAAAA;AAC7C,YAAA,IAAI,CAACK,GAAK,EAAA;gBACR,OAAO,IAAA;AACT;YACAJ,GAAM,GAAA,MAAM,OAAOI,GAAAA,IAAO,IAAI,CAAChB,cAAc,IAAI,EAAC,CA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YAAY,CAACwC,GAAG,CAACZ,SAAoC,EAAE;AACtE;AAEA;;;;;;;;;AASC,MACDoC,MAAOC,CAAAA,SAAiB,EAAEC,WAAmB,EAAE;AAC7C,QAAA,IAAI,IAAI,CAAClE,YAAY,CAACmE,IAAI,KAAK,CAAG,EAAA;AAChC,YAAA;AACF;AACA,QAAA,KAAK,MAAMrB,IAAQ,IAAA,IAAI,CAAC9C,YAAY,CAACoE,MAAM,EAAI,CAAA;YAC7C,KAAK,MAAMC,KAAKvB,IAAM,CAAA;gBACpB,IAAI;AACFuB,oBAAAA,CAAAA,CAAEtC,QAAQ,CAACuC,QAAQ,CAACL,SAAWC,EAAAA,WAAAA,CAAAA;AACjC,iBAAA,CAAE,OAAOR,GAAK,EAAA;oBACZpC,OAAQC,CAAAA,KAAK,CAAC,CAAC,uCAAuC,EAAE8C,EAAE5C,EAAE,CAAC,GAAG,EAAEiC,GAAK,CAAA,CAAA,CAAA;AACzE;AACF;AACF;AACF;AAEA;;;;AAIC,MACDa,gBAAmB,GAAA;AACjB,QAAA,MAAO,IAAI,CAACvE,YAAY,CAACmE,IAAI,GAAG,CAAG,CAAA;AACjC,YAAA,KAAK,MAAMK,KAAAA,IAAS,IAAI,CAACxE,YAAY,CAAE;gBACrC,IAAIwE,KAAK,CAAC,CAAA,CAAE,EAAE;AACZ,oBAAA,IAAI,CAACxB,YAAY,CAACwB,KAAK,CAAC,CAAE,CAAA,CAAA;AAC5B;AACF;AACF;AACF;AACF;;;;"}
@@ -2,69 +2,69 @@ import { textToBase64 } from '@zephyr3d/base';
2
2
  import { init, parse } from '../node_modules/es-module-lexer/dist/lexer.js';
3
3
  import { getApp } from './api.js';
4
4
 
5
- /**
6
- * Converts JavaScript source to a data URL tied to a logical module id.
7
- *
8
- * @param js - The JavaScript source code to embed.
9
- * @param id - Logical module identifier (used only for sourceURL tagging).
10
- * @returns A `data:text/javascript;base64,...` URL with an encoded `#id` suffix.
11
- * @internal
5
+ /**
6
+ * Converts JavaScript source to a data URL tied to a logical module id.
7
+ *
8
+ * @param js - The JavaScript source code to embed.
9
+ * @param id - Logical module identifier (used only for sourceURL tagging).
10
+ * @returns A `data:text/javascript;base64,...` URL with an encoded `#id` suffix.
11
+ * @internal
12
12
  */ function toDataUrl(js, id) {
13
13
  const b64 = textToBase64(js);
14
14
  return `data:text/javascript;base64,${b64}#${encodeURIComponent(String(id))}`;
15
15
  }
16
- /**
17
- * Checks whether a specifier is an absolute HTTP(S) URL.
18
- * @internal
16
+ /**
17
+ * Checks whether a specifier is an absolute HTTP(S) URL.
18
+ * @internal
19
19
  */ function isAbsoluteUrl(spec) {
20
20
  return /^https?:\/\//i.test(spec);
21
21
  }
22
- /**
23
- * Checks whether a specifier is a special URL (data: or blob:).
24
- * @internal
22
+ /**
23
+ * Checks whether a specifier is a special URL (data: or blob:).
24
+ * @internal
25
25
  */ function isSpecialUrl(spec) {
26
26
  return /^(data|blob):/i.test(spec);
27
27
  }
28
- /**
29
- * Checks whether a specifier is a bare module (not starting with ./, ../, /, or #/).
30
- * @internal
28
+ /**
29
+ * Checks whether a specifier is a bare module (not starting with ./, ../, /, or #/).
30
+ * @internal
31
31
  */ function isBareModule(spec) {
32
32
  return !spec.startsWith('./') && !spec.startsWith('../') && !spec.startsWith('/') && !spec.startsWith('#/');
33
33
  }
34
- /**
35
- * Resolves, builds, and serves runtime modules using a VFS.
36
- *
37
- * Responsibilities:
38
- * - Resolve logical module IDs to physical paths or URLs.
39
- * - In editor mode, rewrite import specifiers and serve modules as data URLs after transpile.
40
- * - Transpile TypeScript to JavaScript on the fly (requires `window.ts` TypeScript runtime).
41
- * - Gather static and dynamic import dependencies for tooling.
42
- *
43
- * Modes:
44
- * - Editor mode (`editorMode === true`): modules are rewritten to data URLs after transpile/build.
45
- * - Runtime mode (`editorMode === false`): returns .js URLs directly (with .ts -\> .js mapping).
46
- *
47
- * Caching:
48
- * - Built modules are memoized in `_built` map keyed by logical ID.
49
- *
50
- * @public
34
+ /**
35
+ * Resolves, builds, and serves runtime modules using a VFS.
36
+ *
37
+ * Responsibilities:
38
+ * - Resolve logical module IDs to physical paths or URLs.
39
+ * - In editor mode, rewrite import specifiers and serve modules as data URLs after transpile.
40
+ * - Transpile TypeScript to JavaScript on the fly (requires `window.ts` TypeScript runtime).
41
+ * - Gather static and dynamic import dependencies for tooling.
42
+ *
43
+ * Modes:
44
+ * - Editor mode (`editorMode === true`): modules are rewritten to data URLs after transpile/build.
45
+ * - Runtime mode (`editorMode === false`): returns .js URLs directly (with .ts -\> .js mapping).
46
+ *
47
+ * Caching:
48
+ * - Built modules are memoized in `_built` map keyed by logical ID.
49
+ *
50
+ * @public
51
51
  */ class ScriptRegistry {
52
52
  _vfs;
53
53
  _scriptsRoot;
54
54
  _built;
55
- /**
56
- * @param vfs - The virtual file system for existence checks, reads, and path ops.
57
- * @param scriptsRoot - Root directory for script resolution (used with `#/` specifiers).
58
- * @param editorMode - Whether to build modules to data URLs and rewrite imports.
55
+ /**
56
+ * @param vfs - The virtual file system for existence checks, reads, and path ops.
57
+ * @param scriptsRoot - Root directory for script resolution (used with `#/` specifiers).
58
+ * @param editorMode - Whether to build modules to data URLs and rewrite imports.
59
59
  */ constructor(vfs, scriptsRoot){
60
60
  this._vfs = vfs;
61
61
  this._scriptsRoot = scriptsRoot;
62
62
  this._built = new Map();
63
63
  }
64
- /**
65
- * The active virtual file system.
66
- *
67
- * Assigning a new VFS clears the build cache.
64
+ /**
65
+ * The active virtual file system.
66
+ *
67
+ * Assigning a new VFS clears the build cache.
68
68
  */ get VFS() {
69
69
  return this._vfs;
70
70
  }
@@ -74,23 +74,23 @@ import { getApp } from './api.js';
74
74
  this._built.clear();
75
75
  }
76
76
  }
77
- /**
78
- * The root path used by `#/` specifiers.
77
+ /**
78
+ * The root path used by `#/` specifiers.
79
79
  */ get scriptsRoot() {
80
80
  return this._scriptsRoot;
81
81
  }
82
82
  set scriptsRoot(path) {
83
83
  this._scriptsRoot = path;
84
84
  }
85
- /**
86
- * Fetches raw source for a logical module id by probing known extensions.
87
- *
88
- * Search order:
89
- * - If `id` already ends with `.ts` or `.js` and is a file -\> return it.
90
- * - Else try `.id.ts`, then `.id.js`.
91
- *
92
- * @param id - Logical module identifier (absolute or logical path-like).
93
- * @returns Source code, resolved path, and type (`'js' | 'ts'`), or `undefined` if not found.
85
+ /**
86
+ * Fetches raw source for a logical module id by probing known extensions.
87
+ *
88
+ * Search order:
89
+ * - If `id` already ends with `.ts` or `.js` and is a file -\> return it.
90
+ * - Else try `.id.ts`, then `.id.js`.
91
+ *
92
+ * @param id - Logical module identifier (absolute or logical path-like).
93
+ * @returns Source code, resolved path, and type (`'js' | 'ts'`), or `undefined` if not found.
94
94
  */ async fetchSource(id) {
95
95
  let type = null;
96
96
  let pathWithExt = '';
@@ -139,31 +139,34 @@ import { getApp } from './api.js';
139
139
  };
140
140
  }
141
141
  }
142
- /**
143
- * Resolves a module entry to a URL suitable for dynamic import.
144
- *
145
- * Behavior:
146
- * - In editor mode, builds the module to a data URL.
147
- * - Otherwise, returns `.js` URL directly:
148
- * - If `id` ends with `.js`: return as-is.
149
- * - If `id` ends with `.ts`: map to `.js` (assumes pre-built file exists).
150
- * - Else: append `.js`.
151
- *
152
- * @param entryId - Entry module identifier (logical or path-like).
153
- * @returns A URL string that can be used in `import(...)`.
142
+ /**
143
+ * Resolves a module entry to a URL suitable for dynamic import.
144
+ *
145
+ * Behavior:
146
+ * - In editor mode, builds the module to a data URL.
147
+ * - Otherwise, returns `.js` URL directly:
148
+ * - If `id` ends with `.js`: return as-is.
149
+ * - If `id` ends with `.ts`: map to `.js` (assumes pre-built file exists).
150
+ * - Else: append `.js`.
151
+ *
152
+ * @param entryId - Entry module identifier (logical or path-like).
153
+ * @returns A URL string that can be used in `import(...)`.
154
154
  */ async resolveRuntimeUrl(entryId) {
155
155
  const id = await this.resolveLogicalId(entryId);
156
+ if (id.startsWith('/assets/@builtins/')) {
157
+ return await this.build(String(id));
158
+ }
156
159
  return getApp().editorMode !== 'none' ? await this.build(String(id)) : id.endsWith('.js') ? id : id.endsWith('.ts') ? `${id.slice(0, -3)}.js` : `${id}.js`;
157
160
  }
158
- /**
159
- * Recursively gathers direct static and dynamic import dependencies for a module.
160
- *
161
- * Only relative specifiers (`./` or `../`) are followed. Absolute, special, and bare
162
- * module specifiers are ignored here.
163
- *
164
- * @param entryId - The starting (possibly relative) specifier from `fromId`.
165
- * @param fromId - The logical id of the module containing `entryId`.
166
- * @param dependencies - Output map of `resolvedSourcePath -\> file contents`.
161
+ /**
162
+ * Recursively gathers direct static and dynamic import dependencies for a module.
163
+ *
164
+ * Only relative specifiers (`./` or `../`) are followed. Absolute, special, and bare
165
+ * module specifiers are ignored here.
166
+ *
167
+ * @param entryId - The starting (possibly relative) specifier from `fromId`.
168
+ * @param fromId - The logical id of the module containing `entryId`.
169
+ * @param dependencies - Output map of `resolvedSourcePath -\> file contents`.
167
170
  */ async getDependencies(entryId, fromId, dependencies) {
168
171
  const reStatic = /\b(?:import|export)\s+[^"']*?from\s+(['"])([^'"]+)\1/g;
169
172
  const reDynamic = /\bimport\s*\(\s*(['"])([^'"]+)\1\s*\)/g;
@@ -191,18 +194,18 @@ import { getApp } from './api.js';
191
194
  await gather(code, reStatic);
192
195
  await gather(code, reDynamic);
193
196
  }
194
- /**
195
- * Builds a logical module id into a data URL (editor mode pipeline).
196
- *
197
- * Steps:
198
- * - Resolve source path (.ts/.js) via {@link ScriptRegistry.resolveSourcePath}.
199
- * - Read source code.
200
- * - Rewrite import specifiers via {@link ScriptRegistry.rewriteImports}.
201
- * - Transpile TypeScript if needed via {@link ScriptRegistry.transpile}.
202
- * - Convert to `data:` URL and memoize in `_built`.
203
- *
204
- * @param id - Logical module id to build.
205
- * @returns Data URL string for dynamic import, or empty string if not found.
197
+ /**
198
+ * Builds a logical module id into a data URL (editor mode pipeline).
199
+ *
200
+ * Steps:
201
+ * - Resolve source path (.ts/.js) via {@link ScriptRegistry.resolveSourcePath}.
202
+ * - Read source code.
203
+ * - Rewrite import specifiers via {@link ScriptRegistry.rewriteImports}.
204
+ * - Transpile TypeScript if needed via {@link ScriptRegistry.transpile}.
205
+ * - Convert to `data:` URL and memoize in `_built`.
206
+ *
207
+ * @param id - Logical module id to build.
208
+ * @returns Data URL string for dynamic import, or empty string if not found.
206
209
  */ async build(id) {
207
210
  const key = String(id);
208
211
  const cached = this._built.get(key);
@@ -222,19 +225,19 @@ import { getApp } from './api.js';
222
225
  this._built.set(key, url);
223
226
  return url;
224
227
  }
225
- /**
226
- * Transpiles code to JavaScript and appends sourceURL/sourceMap hints.
227
- *
228
- * Behavior:
229
- * - For `'js'`, returns code with `//# sourceURL=logicalId`.
230
- * - For `'ts'`, requires `window.ts` (TypeScript compiler) to be present and
231
- * transpiles to ES2015/ESNext module with inline source maps.
232
- *
233
- * @param code - Source code to transpile.
234
- * @param _id - Logical module id (used for fileName/sourceURL).
235
- * @param type - Source type (`'js' | 'ts'`).
236
- * @returns Transpiled JavaScript source.
237
- * @throws If TypeScript runtime is not found for TS input.
228
+ /**
229
+ * Transpiles code to JavaScript and appends sourceURL/sourceMap hints.
230
+ *
231
+ * Behavior:
232
+ * - For `'js'`, returns code with `//# sourceURL=logicalId`.
233
+ * - For `'ts'`, requires `window.ts` (TypeScript compiler) to be present and
234
+ * transpiles to ES2015/ESNext module with inline source maps.
235
+ *
236
+ * @param code - Source code to transpile.
237
+ * @param _id - Logical module id (used for fileName/sourceURL).
238
+ * @param type - Source type (`'js' | 'ts'`).
239
+ * @returns Transpiled JavaScript source.
240
+ * @throws If TypeScript runtime is not found for TS input.
238
241
  */ async transpile(code, _id, type) {
239
242
  const logicalId = String(_id);
240
243
  if (type === 'js') {
@@ -263,26 +266,26 @@ import { getApp } from './api.js';
263
266
  out += `\n//# sourceURL=${logicalId}`;
264
267
  return out;
265
268
  }
266
- /**
267
- * Rewrites ESM import specifiers in `code` into runtime-loadable URLs.
268
- *
269
- * Parsing:
270
- * - Uses `es-module-lexer` to find import spans; sorts them ascending by start.
271
- *
272
- * Replacement rules:
273
- * - Skip invalid spans or ones without quoted specifiers.
274
- * - If spec is absolute URL, special URL (data:, blob:), or bare module:
275
- * - If it starts with `@zephyr3d/`, keep as-is (external).
276
- * - Otherwise resolve to a logical id and attempt to `build` it (if available).
277
- * - Else (relative spec), resolve from `fromId` and `build` recursively.
278
- *
279
- * Output:
280
- * - Directly writes the replacement specifier without re-adding quotes,
281
- * so replacements must themselves be quoted or be valid URLs/data URLs.
282
- *
283
- * @param code - Module source code to transform.
284
- * @param fromId - The logical id of the current module (resolution base for relatives).
285
- * @returns Transformed source with rewritten import specifiers.
269
+ /**
270
+ * Rewrites ESM import specifiers in `code` into runtime-loadable URLs.
271
+ *
272
+ * Parsing:
273
+ * - Uses `es-module-lexer` to find import spans; sorts them ascending by start.
274
+ *
275
+ * Replacement rules:
276
+ * - Skip invalid spans or ones without quoted specifiers.
277
+ * - If spec is absolute URL, special URL (data:, blob:), or bare module:
278
+ * - If it starts with `@zephyr3d/`, keep as-is (external).
279
+ * - Otherwise resolve to a logical id and attempt to `build` it (if available).
280
+ * - Else (relative spec), resolve from `fromId` and `build` recursively.
281
+ *
282
+ * Output:
283
+ * - Directly writes the replacement specifier without re-adding quotes,
284
+ * so replacements must themselves be quoted or be valid URLs/data URLs.
285
+ *
286
+ * @param code - Module source code to transform.
287
+ * @param fromId - The logical id of the current module (resolution base for relatives).
288
+ * @returns Transformed source with rewritten import specifiers.
286
289
  */ async rewriteImports(code, fromId) {
287
290
  await init;
288
291
  const [imports] = parse(code);
@@ -292,6 +295,12 @@ import { getApp } from './api.js';
292
295
  let out = '';
293
296
  let last = 0;
294
297
  for (const im of list){
298
+ // Skip import.meta entries reported by es-module-lexer.
299
+ // Their "specifier" span points to the whole "import.meta" expression,
300
+ // which must remain untouched.
301
+ if (im.d === -2) {
302
+ continue;
303
+ }
295
304
  // must have quotes
296
305
  const hasQuote = im.ss != null && im.se != null;
297
306
  if (!hasQuote || im.se <= im.ss) {
@@ -322,21 +331,21 @@ import { getApp } from './api.js';
322
331
  out += code.slice(last);
323
332
  return out;
324
333
  }
325
- /**
326
- * Resolves a specifier to a logical id suitable for further processing.
327
- *
328
- * Resolution rules:
329
- * - `#/path`: resolved against `scriptsRoot` via VFS join/normalize.
330
- * - `./` or `../`: resolved relative to `fromId` directory (requires `fromId`).
331
- * - `/absolute`: treated as absolute from root (normalized).
332
- * - Bare module in editor mode: if `/deps.lock.json` exists and contains an entry,
333
- * map to the dependency's `entry` path; otherwise return as-is.
334
- * - Else (non-editor bare module): return `spec` unchanged (external).
335
- *
336
- * @param spec - Import specifier string.
337
- * @param fromId - Optional base logical id used for relative resolution.
338
- * @returns A normalized logical id or an external specifier string.
339
- * @throws If a relative import is provided without `fromId`.
334
+ /**
335
+ * Resolves a specifier to a logical id suitable for further processing.
336
+ *
337
+ * Resolution rules:
338
+ * - `#/path`: resolved against `scriptsRoot` via VFS join/normalize.
339
+ * - `./` or `../`: resolved relative to `fromId` directory (requires `fromId`).
340
+ * - `/absolute`: treated as absolute from root (normalized).
341
+ * - Bare module in editor mode: if `/deps.lock.json` exists and contains an entry,
342
+ * map to the dependency's `entry` path; otherwise return as-is.
343
+ * - Else (non-editor bare module): return `spec` unchanged (external).
344
+ *
345
+ * @param spec - Import specifier string.
346
+ * @param fromId - Optional base logical id used for relative resolution.
347
+ * @returns A normalized logical id or an external specifier string.
348
+ * @throws If a relative import is provided without `fromId`.
340
349
  */ async resolveLogicalId(spec, fromId) {
341
350
  if (spec.startsWith('#/')) {
342
351
  return this._vfs.normalizePath(this._vfs.join(this._scriptsRoot, spec.slice(2)));
@@ -348,30 +357,32 @@ import { getApp } from './api.js';
348
357
  } else if (spec.startsWith('/')) {
349
358
  return spec.replace(/^\/+/, '/');
350
359
  } else if (getApp().editorMode !== 'none') {
360
+ const libRoot = '/';
351
361
  // naked module, checking if it is a installed module in editor mode
352
- const depsExists = await this._vfs.exists('/libs/deps.lock.json');
362
+ let depsLockPath = this._vfs.normalizePath(this._vfs.join(libRoot, 'libs/deps.lock.json'));
363
+ let depsExists = await this._vfs.exists(depsLockPath);
353
364
  if (depsExists) {
354
- const content = await this._vfs.readFile('/libs/deps.lock.json', {
365
+ const content = await this._vfs.readFile(depsLockPath, {
355
366
  encoding: 'utf8'
356
367
  });
357
368
  const depsInfo = JSON.parse(content);
358
369
  if (depsInfo?.dependencies[spec]) {
359
- return this._vfs.normalizePath(depsInfo.dependencies[spec].entry);
370
+ return this._vfs.normalizePath(this._vfs.join(libRoot, depsInfo.dependencies[spec].entry));
360
371
  }
361
372
  }
362
373
  }
363
374
  return spec;
364
375
  }
365
- /**
366
- * Resolves a logical id to a concrete source path and type by probing extensions.
367
- *
368
- * Rules:
369
- * - If `logicalId` ends with `.ts` or `.js`/`.mjs` and is a file, return it.
370
- * - Else probe `logicalId.ts`, `logicalId.js`, `logicalId.mjs` in that order.
371
- * - Maps `.mjs` to type `'js'`.
372
- *
373
- * @param logicalId - The normalized logical module id (path-like).
374
- * @returns `{ type, path }` or `null` if not found.
376
+ /**
377
+ * Resolves a logical id to a concrete source path and type by probing extensions.
378
+ *
379
+ * Rules:
380
+ * - If `logicalId` ends with `.ts` or `.js`/`.mjs` and is a file, return it.
381
+ * - Else probe `logicalId.ts`, `logicalId.js`, `logicalId.mjs` in that order.
382
+ * - Maps `.mjs` to type `'js'`.
383
+ *
384
+ * @param logicalId - The normalized logical module id (path-like).
385
+ * @returns `{ type, path }` or `null` if not found.
375
386
  */ async resolveSourcePath(logicalId) {
376
387
  let type = null;
377
388
  let pathWithExt = '';
@@ -1 +1 @@
1
- {"version":3,"file":"scriptregistry.js","sources":["../../src/app/scriptregistry.ts"],"sourcesContent":["import type * as TS from 'typescript';\r\nimport type { Nullable, VFS } from '@zephyr3d/base';\r\nimport { textToBase64 } from '@zephyr3d/base';\r\nimport { init, parse } from 'es-module-lexer';\r\nimport { getApp } from './api';\r\n\r\n/**\r\n * Converts JavaScript source to a data URL tied to a logical module id.\r\n *\r\n * @param js - The JavaScript source code to embed.\r\n * @param id - Logical module identifier (used only for sourceURL tagging).\r\n * @returns A `data:text/javascript;base64,...` URL with an encoded `#id` suffix.\r\n * @internal\r\n */\r\nfunction toDataUrl(js: string, id: string) {\r\n const b64 = textToBase64(js);\r\n return `data:text/javascript;base64,${b64}#${encodeURIComponent(String(id))}`;\r\n}\r\n\r\n/**\r\n * Checks whether a specifier is an absolute HTTP(S) URL.\r\n * @internal\r\n */\r\nfunction isAbsoluteUrl(spec: string) {\r\n return /^https?:\\/\\//i.test(spec);\r\n}\r\n\r\n/**\r\n * Checks whether a specifier is a special URL (data: or blob:).\r\n * @internal\r\n */\r\nfunction isSpecialUrl(spec: string) {\r\n return /^(data|blob):/i.test(spec);\r\n}\r\n\r\n/**\r\n * Checks whether a specifier is a bare module (not starting with ./, ../, /, or #/).\r\n * @internal\r\n */\r\nfunction isBareModule(spec: string) {\r\n return !spec.startsWith('./') && !spec.startsWith('../') && !spec.startsWith('/') && !spec.startsWith('#/');\r\n}\r\n\r\n/**\r\n * Resolves, builds, and serves runtime modules using a VFS.\r\n *\r\n * Responsibilities:\r\n * - Resolve logical module IDs to physical paths or URLs.\r\n * - In editor mode, rewrite import specifiers and serve modules as data URLs after transpile.\r\n * - Transpile TypeScript to JavaScript on the fly (requires `window.ts` TypeScript runtime).\r\n * - Gather static and dynamic import dependencies for tooling.\r\n *\r\n * Modes:\r\n * - Editor mode (`editorMode === true`): modules are rewritten to data URLs after transpile/build.\r\n * - Runtime mode (`editorMode === false`): returns .js URLs directly (with .ts -\\> .js mapping).\r\n *\r\n * Caching:\r\n * - Built modules are memoized in `_built` map keyed by logical ID.\r\n *\r\n * @public\r\n */\r\nexport class ScriptRegistry {\r\n private _vfs: VFS;\r\n private _scriptsRoot: string;\r\n private _built: Map<string, string>; // logicalId -> dataURL\r\n\r\n /**\r\n * @param vfs - The virtual file system for existence checks, reads, and path ops.\r\n * @param scriptsRoot - Root directory for script resolution (used with `#/` specifiers).\r\n * @param editorMode - Whether to build modules to data URLs and rewrite imports.\r\n */\r\n constructor(vfs: VFS, scriptsRoot: string) {\r\n this._vfs = vfs;\r\n this._scriptsRoot = scriptsRoot;\r\n this._built = new Map();\r\n }\r\n\r\n /**\r\n * The active virtual file system.\r\n *\r\n * Assigning a new VFS clears the build cache.\r\n */\r\n get VFS() {\r\n return this._vfs;\r\n }\r\n set VFS(vfs: VFS) {\r\n if (vfs !== this._vfs) {\r\n this._vfs = vfs;\r\n this._built.clear();\r\n }\r\n }\r\n\r\n /**\r\n * The root path used by `#/` specifiers.\r\n */\r\n get scriptsRoot() {\r\n return this._scriptsRoot;\r\n }\r\n set scriptsRoot(path: string) {\r\n this._scriptsRoot = path;\r\n }\r\n\r\n /**\r\n * Fetches raw source for a logical module id by probing known extensions.\r\n *\r\n * Search order:\r\n * - If `id` already ends with `.ts` or `.js` and is a file -\\> return it.\r\n * - Else try `.id.ts`, then `.id.js`.\r\n *\r\n * @param id - Logical module identifier (absolute or logical path-like).\r\n * @returns Source code, resolved path, and type (`'js' | 'ts'`), or `undefined` if not found.\r\n */\r\n protected async fetchSource(id: string) {\r\n let type: Nullable<'js' | 'ts'> = null;\r\n let pathWithExt = '';\r\n if (id.endsWith('.ts')) {\r\n pathWithExt = id;\r\n type = 'ts';\r\n } else if (id.endsWith('.js')) {\r\n pathWithExt = id;\r\n type = 'js';\r\n }\r\n if (type) {\r\n const exists = await this._vfs.exists(pathWithExt);\r\n if (!exists) {\r\n type = null;\r\n }\r\n const stat = await this._vfs.stat(pathWithExt);\r\n if (stat.isDirectory) {\r\n type = null;\r\n }\r\n }\r\n const types = ['ts', 'js'] as const;\r\n if (!type) {\r\n for (const t of types) {\r\n pathWithExt = `${id}.${t}`;\r\n const exists = await this._vfs.exists(pathWithExt);\r\n if (exists) {\r\n const stats = await this._vfs.stat(pathWithExt);\r\n if (stats.isFile) {\r\n type = t;\r\n break;\r\n }\r\n }\r\n }\r\n }\r\n if (type) {\r\n const code = (await this._vfs.readFile(pathWithExt, { encoding: 'utf8' })) as string;\r\n return { code, type, path: pathWithExt };\r\n }\r\n }\r\n\r\n /**\r\n * Resolves a module entry to a URL suitable for dynamic import.\r\n *\r\n * Behavior:\r\n * - In editor mode, builds the module to a data URL.\r\n * - Otherwise, returns `.js` URL directly:\r\n * - If `id` ends with `.js`: return as-is.\r\n * - If `id` ends with `.ts`: map to `.js` (assumes pre-built file exists).\r\n * - Else: append `.js`.\r\n *\r\n * @param entryId - Entry module identifier (logical or path-like).\r\n * @returns A URL string that can be used in `import(...)`.\r\n */\r\n async resolveRuntimeUrl(entryId: string) {\r\n const id = await this.resolveLogicalId(entryId);\r\n return getApp().editorMode !== 'none'\r\n ? await this.build(String(id))\r\n : id.endsWith('.js')\r\n ? id\r\n : id.endsWith('.ts')\r\n ? `${id.slice(0, -3)}.js`\r\n : `${id}.js`;\r\n }\r\n\r\n /**\r\n * Recursively gathers direct static and dynamic import dependencies for a module.\r\n *\r\n * Only relative specifiers (`./` or `../`) are followed. Absolute, special, and bare\r\n * module specifiers are ignored here.\r\n *\r\n * @param entryId - The starting (possibly relative) specifier from `fromId`.\r\n * @param fromId - The logical id of the module containing `entryId`.\r\n * @param dependencies - Output map of `resolvedSourcePath -\\> file contents`.\r\n */\r\n async getDependencies(entryId: string, fromId: string, dependencies: Record<string, string>) {\r\n const reStatic = /\\b(?:import|export)\\s+[^\"']*?from\\s+(['\"])([^'\"]+)\\1/g;\r\n const reDynamic = /\\bimport\\s*\\(\\s*(['\"])([^'\"]+)\\1\\s*\\)/g;\r\n\r\n const normalizedId = await this.resolveLogicalId(entryId, fromId);\r\n const srcPath = await this.resolveSourcePath(normalizedId);\r\n if (!srcPath || dependencies[srcPath.path] !== undefined) {\r\n return;\r\n }\r\n const code = (await this._vfs.readFile(srcPath.path, { encoding: 'utf8' })) as string;\r\n dependencies[srcPath.path] = code;\r\n\r\n const gather = async (input: string, re: RegExp) => {\r\n for (;;) {\r\n const m = re.exec(input);\r\n if (!m) {\r\n break;\r\n }\r\n\r\n const spec = m[2];\r\n\r\n if (spec.startsWith('./') || spec.startsWith('../')) {\r\n await this.getDependencies(spec, normalizedId, dependencies);\r\n }\r\n }\r\n };\r\n\r\n await gather(code, reStatic);\r\n await gather(code, reDynamic);\r\n }\r\n\r\n /**\r\n * Builds a logical module id into a data URL (editor mode pipeline).\r\n *\r\n * Steps:\r\n * - Resolve source path (.ts/.js) via {@link ScriptRegistry.resolveSourcePath}.\r\n * - Read source code.\r\n * - Rewrite import specifiers via {@link ScriptRegistry.rewriteImports}.\r\n * - Transpile TypeScript if needed via {@link ScriptRegistry.transpile}.\r\n * - Convert to `data:` URL and memoize in `_built`.\r\n *\r\n * @param id - Logical module id to build.\r\n * @returns Data URL string for dynamic import, or empty string if not found.\r\n */\r\n private async build(id: string) {\r\n const key = String(id);\r\n const cached = this._built.get(key);\r\n if (cached) {\r\n return cached;\r\n }\r\n\r\n const srcPath = await this.resolveSourcePath(key);\r\n if (!srcPath) {\r\n return '';\r\n }\r\n const code = (await this._vfs.readFile(srcPath.path, { encoding: 'utf8' })) as string;\r\n\r\n const rewritten = await this.rewriteImports(code, key);\r\n const js = await this.transpile(rewritten, key, srcPath.type);\r\n const url = toDataUrl(js, key);\r\n this._built.set(key, url);\r\n return url;\r\n }\r\n\r\n /**\r\n * Transpiles code to JavaScript and appends sourceURL/sourceMap hints.\r\n *\r\n * Behavior:\r\n * - For `'js'`, returns code with `//# sourceURL=logicalId`.\r\n * - For `'ts'`, requires `window.ts` (TypeScript compiler) to be present and\r\n * transpiles to ES2015/ESNext module with inline source maps.\r\n *\r\n * @param code - Source code to transpile.\r\n * @param _id - Logical module id (used for fileName/sourceURL).\r\n * @param type - Source type (`'js' | 'ts'`).\r\n * @returns Transpiled JavaScript source.\r\n * @throws If TypeScript runtime is not found for TS input.\r\n */\r\n private async transpile(code: string, _id: string, type: 'js' | 'ts') {\r\n const logicalId = String(_id);\r\n\r\n if (type === 'js') {\r\n return `${code}\\n//# sourceURL=${logicalId}`;\r\n }\r\n\r\n const ts = (window as any).ts as typeof TS;\r\n if (!ts) {\r\n throw new Error('TypeScript runtime (window.ts) not found. Load typescript.js first.');\r\n }\r\n\r\n const res = ts.transpileModule(code, {\r\n compilerOptions: {\r\n target: ts.ScriptTarget.ES2015,\r\n module: ts.ModuleKind.ESNext,\r\n sourceMap: true,\r\n inlineSources: true,\r\n experimentalDecorators: true,\r\n useDefineForClassFields: false\r\n },\r\n fileName: logicalId\r\n });\r\n\r\n let out = res.outputText || '';\r\n if (res.sourceMapText) {\r\n const mapBase64 = btoa(unescape(encodeURIComponent(res.sourceMapText)));\r\n out += `\\n//# sourceMappingURL=data:application/json;base64,${mapBase64}`;\r\n }\r\n out += `\\n//# sourceURL=${logicalId}`;\r\n return out;\r\n }\r\n\r\n /**\r\n * Rewrites ESM import specifiers in `code` into runtime-loadable URLs.\r\n *\r\n * Parsing:\r\n * - Uses `es-module-lexer` to find import spans; sorts them ascending by start.\r\n *\r\n * Replacement rules:\r\n * - Skip invalid spans or ones without quoted specifiers.\r\n * - If spec is absolute URL, special URL (data:, blob:), or bare module:\r\n * - If it starts with `@zephyr3d/`, keep as-is (external).\r\n * - Otherwise resolve to a logical id and attempt to `build` it (if available).\r\n * - Else (relative spec), resolve from `fromId` and `build` recursively.\r\n *\r\n * Output:\r\n * - Directly writes the replacement specifier without re-adding quotes,\r\n * so replacements must themselves be quoted or be valid URLs/data URLs.\r\n *\r\n * @param code - Module source code to transform.\r\n * @param fromId - The logical id of the current module (resolution base for relatives).\r\n * @returns Transformed source with rewritten import specifiers.\r\n */\r\n private async rewriteImports(code: string, fromId: string) {\r\n await init;\r\n const [imports] = parse(code);\r\n const list = [...imports].sort((a, b) => (a.s || 0) - (b.s || 0));\r\n let out = '';\r\n let last = 0;\r\n\r\n for (const im of list) {\r\n // must have quotes\r\n const hasQuote = im.ss != null && im.se != null;\r\n if (!hasQuote || im.se <= im.ss) {\r\n continue;\r\n }\r\n // must have contents\r\n if (im.e <= im.s) {\r\n continue;\r\n }\r\n // append [last, s)\r\n out += code.slice(last, im.s);\r\n\r\n const spec = code.slice(im.s, im.e); // original spec\r\n let replacement = spec;\r\n if (isAbsoluteUrl(spec) || isSpecialUrl(spec) || isBareModule(spec)) {\r\n if (spec.startsWith('@zephyr3d/')) {\r\n replacement = spec;\r\n } else {\r\n const depId = await this.resolveLogicalId(spec);\r\n replacement = await this.build(depId); // try build as dependence\r\n }\r\n } else {\r\n const depId = await this.resolveLogicalId(spec, String(fromId));\r\n replacement = await this.build(depId); // recursively build as dataURL\r\n }\r\n out += replacement; // 不加引号\r\n last = im.e;\r\n }\r\n out += code.slice(last);\r\n return out;\r\n }\r\n\r\n /**\r\n * Resolves a specifier to a logical id suitable for further processing.\r\n *\r\n * Resolution rules:\r\n * - `#/path`: resolved against `scriptsRoot` via VFS join/normalize.\r\n * - `./` or `../`: resolved relative to `fromId` directory (requires `fromId`).\r\n * - `/absolute`: treated as absolute from root (normalized).\r\n * - Bare module in editor mode: if `/deps.lock.json` exists and contains an entry,\r\n * map to the dependency's `entry` path; otherwise return as-is.\r\n * - Else (non-editor bare module): return `spec` unchanged (external).\r\n *\r\n * @param spec - Import specifier string.\r\n * @param fromId - Optional base logical id used for relative resolution.\r\n * @returns A normalized logical id or an external specifier string.\r\n * @throws If a relative import is provided without `fromId`.\r\n */\r\n async resolveLogicalId(spec: string, fromId?: string) {\r\n if (spec.startsWith('#/')) {\r\n return this._vfs.normalizePath(this._vfs.join(this._scriptsRoot, spec.slice(2)));\r\n } else if (spec.startsWith('./') || spec.startsWith('../')) {\r\n if (!fromId) {\r\n throw new Error(`Relative import \"${spec}\" requires fromId`);\r\n }\r\n return this._vfs.normalizePath(\r\n this._vfs.join(this._vfs.dirname(this._vfs.normalizePath(fromId)), spec)\r\n );\r\n } else if (spec.startsWith('/')) {\r\n return spec.replace(/^\\/+/, '/');\r\n } else if (getApp().editorMode !== 'none') {\r\n // naked module, checking if it is a installed module in editor mode\r\n const depsExists = await this._vfs.exists('/libs/deps.lock.json');\r\n if (depsExists) {\r\n const content = (await this._vfs.readFile('/libs/deps.lock.json', { encoding: 'utf8' })) as string;\r\n const depsInfo = JSON.parse(content) as { dependencies: Record<string, { entry: string }> };\r\n if (depsInfo?.dependencies[spec]) {\r\n return this._vfs.normalizePath(depsInfo.dependencies[spec].entry);\r\n }\r\n }\r\n }\r\n return spec;\r\n }\r\n\r\n /**\r\n * Resolves a logical id to a concrete source path and type by probing extensions.\r\n *\r\n * Rules:\r\n * - If `logicalId` ends with `.ts` or `.js`/`.mjs` and is a file, return it.\r\n * - Else probe `logicalId.ts`, `logicalId.js`, `logicalId.mjs` in that order.\r\n * - Maps `.mjs` to type `'js'`.\r\n *\r\n * @param logicalId - The normalized logical module id (path-like).\r\n * @returns `{ type, path }` or `null` if not found.\r\n */\r\n async resolveSourcePath(logicalId: string) {\r\n let type: Nullable<'js' | 'ts'> = null;\r\n let pathWithExt = '';\r\n if (logicalId.endsWith('.ts')) {\r\n pathWithExt = logicalId;\r\n type = 'ts';\r\n } else if (logicalId.endsWith('.js') || logicalId.endsWith('.mjs')) {\r\n pathWithExt = logicalId;\r\n type = 'js';\r\n }\r\n if (type) {\r\n const exists = await this._vfs.exists(pathWithExt);\r\n if (!exists) {\r\n type = null;\r\n }\r\n const stat = await this._vfs.stat(pathWithExt);\r\n if (stat.isDirectory) {\r\n type = null;\r\n }\r\n }\r\n const types = ['ts', 'js', 'mjs'] as const;\r\n if (!type) {\r\n for (const t of types) {\r\n pathWithExt = `${logicalId}.${t}`;\r\n const exists = await this._vfs.exists(pathWithExt);\r\n if (exists) {\r\n const stats = await this._vfs.stat(pathWithExt);\r\n if (stats.isFile) {\r\n type = t === 'ts' ? 'ts' : 'js';\r\n break;\r\n }\r\n }\r\n }\r\n }\r\n return type ? { type, path: pathWithExt } : null;\r\n }\r\n}\r\n"],"names":["toDataUrl","js","id","b64","textToBase64","encodeURIComponent","String","isAbsoluteUrl","spec","test","isSpecialUrl","isBareModule","startsWith","ScriptRegistry","_vfs","_scriptsRoot","_built","vfs","scriptsRoot","Map","VFS","clear","path","fetchSource","type","pathWithExt","endsWith","exists","stat","isDirectory","types","t","stats","isFile","code","readFile","encoding","resolveRuntimeUrl","entryId","resolveLogicalId","getApp","editorMode","build","slice","getDependencies","fromId","dependencies","reStatic","reDynamic","normalizedId","srcPath","resolveSourcePath","undefined","gather","input","re","m","exec","key","cached","get","rewritten","rewriteImports","transpile","url","set","_id","logicalId","ts","window","Error","res","transpileModule","compilerOptions","target","ScriptTarget","ES2015","module","ModuleKind","ESNext","sourceMap","inlineSources","experimentalDecorators","useDefineForClassFields","fileName","out","outputText","sourceMapText","mapBase64","btoa","unescape","init","imports","parse","list","sort","a","b","s","last","im","hasQuote","ss","se","e","replacement","depId","normalizePath","join","dirname","replace","depsExists","content","depsInfo","JSON","entry"],"mappings":";;;;AAMA;;;;;;;AAOC,IACD,SAASA,SAAAA,CAAUC,EAAU,EAAEC,EAAU,EAAA;AACvC,IAAA,MAAMC,MAAMC,YAAaH,CAAAA,EAAAA,CAAAA;IACzB,OAAO,CAAC,4BAA4B,EAAEE,GAAAA,CAAI,CAAC,EAAEE,kBAAAA,CAAmBC,OAAOJ,EAAM,CAAA,CAAA,CAAA,CAAA;AAC/E;AAEA;;;IAIA,SAASK,cAAcC,IAAY,EAAA;IACjC,OAAO,eAAA,CAAgBC,IAAI,CAACD,IAAAA,CAAAA;AAC9B;AAEA;;;IAIA,SAASE,aAAaF,IAAY,EAAA;IAChC,OAAO,gBAAA,CAAiBC,IAAI,CAACD,IAAAA,CAAAA;AAC/B;AAEA;;;IAIA,SAASG,aAAaH,IAAY,EAAA;AAChC,IAAA,OAAO,CAACA,IAAKI,CAAAA,UAAU,CAAC,IAAS,CAAA,IAAA,CAACJ,KAAKI,UAAU,CAAC,KAAU,CAAA,IAAA,CAACJ,KAAKI,UAAU,CAAC,QAAQ,CAACJ,IAAAA,CAAKI,UAAU,CAAC,IAAA,CAAA;AACxG;AAEA;;;;;;;;;;;;;;;;;AAiBC,IACM,MAAMC,cAAAA,CAAAA;IACHC,IAAU;IACV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Q,EAAA;gBACXH,IAAO,GAAA,IAAA;AACT;AACA,YAAA,MAAMI,OAAO,MAAM,IAAI,CAACd,IAAI,CAACc,IAAI,CAACH,WAAAA,CAAAA;YAClC,IAAIG,IAAAA,CAAKC,WAAW,EAAE;gBACpBL,IAAO,GAAA,IAAA;AACT;AACF;AACA,QAAA,MAAMM,KAAQ,GAAA;AAAC,YAAA,IAAA;AAAM,YAAA,IAAA;AAAM,YAAA;AAAM,SAAA;AACjC,QAAA,IAAI,CAACN,IAAM,EAAA;YACT,KAAK,MAAMO,KAAKD,KAAO,CAAA;AACrBL,gBAAAA,WAAAA,GAAc,CAAG0C,EAAAA,SAAAA,CAAU,CAAC,EAAEpC,CAAG,CAAA,CAAA;AACjC,gBAAA,MAAMJ,SAAS,MAAM,IAAI,CAACb,IAAI,CAACa,MAAM,CAACF,WAAAA,CAAAA;AACtC,gBAAA,IAAIE,MAAQ,EAAA;AACV,oBAAA,MAAMK,QAAQ,MAAM,IAAI,CAAClB,IAAI,CAACc,IAAI,CAACH,WAAAA,CAAAA;oBACnC,IAAIO,KAAAA,CAAMC,MAAM,EAAE;wBAChBT,IAAOO,GAAAA,CAAAA,KAAM,OAAO,IAAO,GAAA,IAAA;AAC3B,wBAAA;AACF;AACF;AACF;AACF;AACA,QAAA,OAAOP,IAAO,GAAA;AAAEA,YAAAA,IAAAA;YAAMF,IAAMG,EAAAA;SAAgB,GAAA,IAAA;AAC9C;AACF;;;;"}
1
+ {"version":3,"file":"scriptregistry.js","sources":["../../src/app/scriptregistry.ts"],"sourcesContent":["import type * as TS from 'typescript';\nimport type { Nullable, VFS } from '@zephyr3d/base';\nimport { textToBase64 } from '@zephyr3d/base';\nimport { init, parse } from 'es-module-lexer';\nimport { getApp } from './api';\n\n/**\n * Converts JavaScript source to a data URL tied to a logical module id.\n *\n * @param js - The JavaScript source code to embed.\n * @param id - Logical module identifier (used only for sourceURL tagging).\n * @returns A `data:text/javascript;base64,...` URL with an encoded `#id` suffix.\n * @internal\n */\nfunction toDataUrl(js: string, id: string) {\n const b64 = textToBase64(js);\n return `data:text/javascript;base64,${b64}#${encodeURIComponent(String(id))}`;\n}\n\n/**\n * Checks whether a specifier is an absolute HTTP(S) URL.\n * @internal\n */\nfunction isAbsoluteUrl(spec: string) {\n return /^https?:\\/\\//i.test(spec);\n}\n\n/**\n * Checks whether a specifier is a special URL (data: or blob:).\n * @internal\n */\nfunction isSpecialUrl(spec: string) {\n return /^(data|blob):/i.test(spec);\n}\n\n/**\n * Checks whether a specifier is a bare module (not starting with ./, ../, /, or #/).\n * @internal\n */\nfunction isBareModule(spec: string) {\n return !spec.startsWith('./') && !spec.startsWith('../') && !spec.startsWith('/') && !spec.startsWith('#/');\n}\n\n/**\n * Resolves, builds, and serves runtime modules using a VFS.\n *\n * Responsibilities:\n * - Resolve logical module IDs to physical paths or URLs.\n * - In editor mode, rewrite import specifiers and serve modules as data URLs after transpile.\n * - Transpile TypeScript to JavaScript on the fly (requires `window.ts` TypeScript runtime).\n * - Gather static and dynamic import dependencies for tooling.\n *\n * Modes:\n * - Editor mode (`editorMode === true`): modules are rewritten to data URLs after transpile/build.\n * - Runtime mode (`editorMode === false`): returns .js URLs directly (with .ts -\\> .js mapping).\n *\n * Caching:\n * - Built modules are memoized in `_built` map keyed by logical ID.\n *\n * @public\n */\nexport class ScriptRegistry {\n private _vfs: VFS;\n private _scriptsRoot: string;\n private _built: Map<string, string>; // logicalId -> dataURL\n\n /**\n * @param vfs - The virtual file system for existence checks, reads, and path ops.\n * @param scriptsRoot - Root directory for script resolution (used with `#/` specifiers).\n * @param editorMode - Whether to build modules to data URLs and rewrite imports.\n */\n constructor(vfs: VFS, scriptsRoot: string) {\n this._vfs = vfs;\n this._scriptsRoot = scriptsRoot;\n this._built = new Map();\n }\n\n /**\n * The active virtual file system.\n *\n * Assigning a new VFS clears the build cache.\n */\n get VFS() {\n return this._vfs;\n }\n set VFS(vfs: VFS) {\n if (vfs !== this._vfs) {\n this._vfs = vfs;\n this._built.clear();\n }\n }\n\n /**\n * The root path used by `#/` specifiers.\n */\n get scriptsRoot() {\n return this._scriptsRoot;\n }\n set scriptsRoot(path: string) {\n this._scriptsRoot = path;\n }\n\n /**\n * Fetches raw source for a logical module id by probing known extensions.\n *\n * Search order:\n * - If `id` already ends with `.ts` or `.js` and is a file -\\> return it.\n * - Else try `.id.ts`, then `.id.js`.\n *\n * @param id - Logical module identifier (absolute or logical path-like).\n * @returns Source code, resolved path, and type (`'js' | 'ts'`), or `undefined` if not found.\n */\n protected async fetchSource(id: string) {\n let type: Nullable<'js' | 'ts'> = null;\n let pathWithExt = '';\n if (id.endsWith('.ts')) {\n pathWithExt = id;\n type = 'ts';\n } else if (id.endsWith('.js')) {\n pathWithExt = id;\n type = 'js';\n }\n if (type) {\n const exists = await this._vfs.exists(pathWithExt);\n if (!exists) {\n type = null;\n }\n const stat = await this._vfs.stat(pathWithExt);\n if (stat.isDirectory) {\n type = null;\n }\n }\n const types = ['ts', 'js'] as const;\n if (!type) {\n for (const t of types) {\n pathWithExt = `${id}.${t}`;\n const exists = await this._vfs.exists(pathWithExt);\n if (exists) {\n const stats = await this._vfs.stat(pathWithExt);\n if (stats.isFile) {\n type = t;\n break;\n }\n }\n }\n }\n if (type) {\n const code = (await this._vfs.readFile(pathWithExt, { encoding: 'utf8' })) as string;\n return { code, type, path: pathWithExt };\n }\n }\n\n /**\n * Resolves a module entry to a URL suitable for dynamic import.\n *\n * Behavior:\n * - In editor mode, builds the module to a data URL.\n * - Otherwise, returns `.js` URL directly:\n * - If `id` ends with `.js`: return as-is.\n * - If `id` ends with `.ts`: map to `.js` (assumes pre-built file exists).\n * - Else: append `.js`.\n *\n * @param entryId - Entry module identifier (logical or path-like).\n * @returns A URL string that can be used in `import(...)`.\n */\n async resolveRuntimeUrl(entryId: string) {\n const id = await this.resolveLogicalId(entryId);\n if (id.startsWith('/assets/@builtins/')) {\n return await this.build(String(id));\n }\n return getApp().editorMode !== 'none'\n ? await this.build(String(id))\n : id.endsWith('.js')\n ? id\n : id.endsWith('.ts')\n ? `${id.slice(0, -3)}.js`\n : `${id}.js`;\n }\n\n /**\n * Recursively gathers direct static and dynamic import dependencies for a module.\n *\n * Only relative specifiers (`./` or `../`) are followed. Absolute, special, and bare\n * module specifiers are ignored here.\n *\n * @param entryId - The starting (possibly relative) specifier from `fromId`.\n * @param fromId - The logical id of the module containing `entryId`.\n * @param dependencies - Output map of `resolvedSourcePath -\\> file contents`.\n */\n async getDependencies(entryId: string, fromId: string, dependencies: Record<string, string>) {\n const reStatic = /\\b(?:import|export)\\s+[^\"']*?from\\s+(['\"])([^'\"]+)\\1/g;\n const reDynamic = /\\bimport\\s*\\(\\s*(['\"])([^'\"]+)\\1\\s*\\)/g;\n\n const normalizedId = await this.resolveLogicalId(entryId, fromId);\n const srcPath = await this.resolveSourcePath(normalizedId);\n if (!srcPath || dependencies[srcPath.path] !== undefined) {\n return;\n }\n const code = (await this._vfs.readFile(srcPath.path, { encoding: 'utf8' })) as string;\n dependencies[srcPath.path] = code;\n\n const gather = async (input: string, re: RegExp) => {\n for (;;) {\n const m = re.exec(input);\n if (!m) {\n break;\n }\n\n const spec = m[2];\n\n if (spec.startsWith('./') || spec.startsWith('../')) {\n await this.getDependencies(spec, normalizedId, dependencies);\n }\n }\n };\n\n await gather(code, reStatic);\n await gather(code, reDynamic);\n }\n\n /**\n * Builds a logical module id into a data URL (editor mode pipeline).\n *\n * Steps:\n * - Resolve source path (.ts/.js) via {@link ScriptRegistry.resolveSourcePath}.\n * - Read source code.\n * - Rewrite import specifiers via {@link ScriptRegistry.rewriteImports}.\n * - Transpile TypeScript if needed via {@link ScriptRegistry.transpile}.\n * - Convert to `data:` URL and memoize in `_built`.\n *\n * @param id - Logical module id to build.\n * @returns Data URL string for dynamic import, or empty string if not found.\n */\n private async build(id: string) {\n const key = String(id);\n const cached = this._built.get(key);\n if (cached) {\n return cached;\n }\n\n const srcPath = await this.resolveSourcePath(key);\n if (!srcPath) {\n return '';\n }\n const code = (await this._vfs.readFile(srcPath.path, { encoding: 'utf8' })) as string;\n\n const rewritten = await this.rewriteImports(code, key);\n const js = await this.transpile(rewritten, key, srcPath.type);\n const url = toDataUrl(js, key);\n this._built.set(key, url);\n return url;\n }\n\n /**\n * Transpiles code to JavaScript and appends sourceURL/sourceMap hints.\n *\n * Behavior:\n * - For `'js'`, returns code with `//# sourceURL=logicalId`.\n * - For `'ts'`, requires `window.ts` (TypeScript compiler) to be present and\n * transpiles to ES2015/ESNext module with inline source maps.\n *\n * @param code - Source code to transpile.\n * @param _id - Logical module id (used for fileName/sourceURL).\n * @param type - Source type (`'js' | 'ts'`).\n * @returns Transpiled JavaScript source.\n * @throws If TypeScript runtime is not found for TS input.\n */\n private async transpile(code: string, _id: string, type: 'js' | 'ts') {\n const logicalId = String(_id);\n\n if (type === 'js') {\n return `${code}\\n//# sourceURL=${logicalId}`;\n }\n\n const ts = (window as any).ts as typeof TS;\n if (!ts) {\n throw new Error('TypeScript runtime (window.ts) not found. Load typescript.js first.');\n }\n\n const res = ts.transpileModule(code, {\n compilerOptions: {\n target: ts.ScriptTarget.ES2015,\n module: ts.ModuleKind.ESNext,\n sourceMap: true,\n inlineSources: true,\n experimentalDecorators: true,\n useDefineForClassFields: false\n },\n fileName: logicalId\n });\n\n let out = res.outputText || '';\n if (res.sourceMapText) {\n const mapBase64 = btoa(unescape(encodeURIComponent(res.sourceMapText)));\n out += `\\n//# sourceMappingURL=data:application/json;base64,${mapBase64}`;\n }\n out += `\\n//# sourceURL=${logicalId}`;\n return out;\n }\n\n /**\n * Rewrites ESM import specifiers in `code` into runtime-loadable URLs.\n *\n * Parsing:\n * - Uses `es-module-lexer` to find import spans; sorts them ascending by start.\n *\n * Replacement rules:\n * - Skip invalid spans or ones without quoted specifiers.\n * - If spec is absolute URL, special URL (data:, blob:), or bare module:\n * - If it starts with `@zephyr3d/`, keep as-is (external).\n * - Otherwise resolve to a logical id and attempt to `build` it (if available).\n * - Else (relative spec), resolve from `fromId` and `build` recursively.\n *\n * Output:\n * - Directly writes the replacement specifier without re-adding quotes,\n * so replacements must themselves be quoted or be valid URLs/data URLs.\n *\n * @param code - Module source code to transform.\n * @param fromId - The logical id of the current module (resolution base for relatives).\n * @returns Transformed source with rewritten import specifiers.\n */\n private async rewriteImports(code: string, fromId: string) {\n await init;\n const [imports] = parse(code);\n const list = [...imports].sort((a, b) => (a.s || 0) - (b.s || 0));\n let out = '';\n let last = 0;\n\n for (const im of list) {\n // Skip import.meta entries reported by es-module-lexer.\n // Their \"specifier\" span points to the whole \"import.meta\" expression,\n // which must remain untouched.\n if (im.d === -2) {\n continue;\n }\n // must have quotes\n const hasQuote = im.ss != null && im.se != null;\n if (!hasQuote || im.se <= im.ss) {\n continue;\n }\n // must have contents\n if (im.e <= im.s) {\n continue;\n }\n // append [last, s)\n out += code.slice(last, im.s);\n\n const spec = code.slice(im.s, im.e); // original spec\n let replacement = spec;\n if (isAbsoluteUrl(spec) || isSpecialUrl(spec) || isBareModule(spec)) {\n if (spec.startsWith('@zephyr3d/')) {\n replacement = spec;\n } else {\n const depId = await this.resolveLogicalId(spec);\n replacement = await this.build(depId); // try build as dependence\n }\n } else {\n const depId = await this.resolveLogicalId(spec, String(fromId));\n replacement = await this.build(depId); // recursively build as dataURL\n }\n out += replacement; // 不加引号\n last = im.e;\n }\n out += code.slice(last);\n return out;\n }\n\n /**\n * Resolves a specifier to a logical id suitable for further processing.\n *\n * Resolution rules:\n * - `#/path`: resolved against `scriptsRoot` via VFS join/normalize.\n * - `./` or `../`: resolved relative to `fromId` directory (requires `fromId`).\n * - `/absolute`: treated as absolute from root (normalized).\n * - Bare module in editor mode: if `/deps.lock.json` exists and contains an entry,\n * map to the dependency's `entry` path; otherwise return as-is.\n * - Else (non-editor bare module): return `spec` unchanged (external).\n *\n * @param spec - Import specifier string.\n * @param fromId - Optional base logical id used for relative resolution.\n * @returns A normalized logical id or an external specifier string.\n * @throws If a relative import is provided without `fromId`.\n */\n async resolveLogicalId(spec: string, fromId?: string) {\n if (spec.startsWith('#/')) {\n return this._vfs.normalizePath(this._vfs.join(this._scriptsRoot, spec.slice(2)));\n } else if (spec.startsWith('./') || spec.startsWith('../')) {\n if (!fromId) {\n throw new Error(`Relative import \"${spec}\" requires fromId`);\n }\n return this._vfs.normalizePath(\n this._vfs.join(this._vfs.dirname(this._vfs.normalizePath(fromId)), spec)\n );\n } else if (spec.startsWith('/')) {\n return spec.replace(/^\\/+/, '/');\n } else if (getApp().editorMode !== 'none') {\n const libRoot = '/';\n // naked module, checking if it is a installed module in editor mode\n let depsLockPath = this._vfs.normalizePath(this._vfs.join(libRoot, 'libs/deps.lock.json'));\n let depsExists = await this._vfs.exists(depsLockPath);\n if (depsExists) {\n const content = (await this._vfs.readFile(depsLockPath, { encoding: 'utf8' })) as string;\n const depsInfo = JSON.parse(content) as { dependencies: Record<string, { entry: string }> };\n if (depsInfo?.dependencies[spec]) {\n return this._vfs.normalizePath(this._vfs.join(libRoot, depsInfo.dependencies[spec].entry));\n }\n }\n }\n return spec;\n }\n\n /**\n * Resolves a logical id to a concrete source path and type by probing extensions.\n *\n * Rules:\n * - If `logicalId` ends with `.ts` or `.js`/`.mjs` and is a file, return it.\n * - Else probe `logicalId.ts`, `logicalId.js`, `logicalId.mjs` in that order.\n * - Maps `.mjs` to type `'js'`.\n *\n * @param logicalId - The normalized logical module id (path-like).\n * @returns `{ type, path }` or `null` if not found.\n */\n async resolveSourcePath(logicalId: string) {\n let type: Nullable<'js' | 'ts'> = null;\n let pathWithExt = '';\n if (logicalId.endsWith('.ts')) {\n pathWithExt = logicalId;\n type = 'ts';\n } else if (logicalId.endsWith('.js') || logicalId.endsWith('.mjs')) {\n pathWithExt = logicalId;\n type = 'js';\n }\n if (type) {\n const exists = await this._vfs.exists(pathWithExt);\n if (!exists) {\n type = null;\n }\n const stat = await this._vfs.stat(pathWithExt);\n if (stat.isDirectory) {\n type = null;\n }\n }\n const types = ['ts', 'js', 'mjs'] as const;\n if (!type) {\n for (const t of types) {\n pathWithExt = `${logicalId}.${t}`;\n const exists = await this._vfs.exists(pathWithExt);\n if (exists) {\n const stats = await this._vfs.stat(pathWithExt);\n if (stats.isFile) {\n type = t === 'ts' ? 'ts' : 'js';\n break;\n }\n }\n }\n }\n return type ? { type, path: pathWithExt } : null;\n }\n}\n"],"names":["toDataUrl","js","id","b64","textToBase64","encodeURIComponent","String","isAbsoluteUrl","spec","test","isSpecialUrl","isBareModule","startsWith","ScriptRegistry","_vfs","_scriptsRoot","_built","vfs","scriptsRoot","Map","VFS","clear","path","fetchSource","type","pathWithExt","endsWith","exists","stat","isDirectory","types","t","stats","isFile","code","readFile","encoding","resolveRuntimeUrl","entryId","resolveLogicalId","build","getApp","editorMode","slice","getDependencies","fromId","dependencies","reStatic","reDynamic","normalizedId","srcPath","resolveSourcePath","undefined","gather","input","re","m","exec","key","cached","get","rewritten","rewriteImports","transpile","url","set","_id","logicalId","ts","window","Error","res","transpileModule","compilerOptions","target","ScriptTarget","ES2015","module","ModuleKind","ESNext","sourceMap","inlineSources","experimentalDecorators","useDefineForClassFields","fileName","out","outputText","sourceMapText","mapBase64","btoa","unescape","init","imports","parse","list","sort","a","b","s","last","im","d","hasQuote","ss","se","e","replacement","depId","normalizePath","join","dirname","replace","libRoot","depsLockPath","depsExists","content","depsInfo","JSON","entry"],"mappings":";;;;AAMA;;;;;;;AAOC,IACD,SAASA,SAAAA,CAAUC,EAAU,EAAEC,EAAU,EAAA;AACvC,IAAA,MAAMC,MAAMC,YAAaH,CAAAA,EAAAA,CAAAA;IACzB,OAAO,CAAC,4BAA4B,EAAEE,GAAAA,CAAI,CAAC,EAAEE,kBAAAA,CAAmBC,OAAOJ,EAAM,CAAA,CAAA,CAAA,CAAA;AAC/E;AAEA;;;IAIA,SAASK,cAAcC,IAAY,EAAA;IACjC,OAAO,eAAA,CAAgBC,IAAI,CAACD,IAAAA,CAAAA;AAC9B;AAEA;;;IAIA,SAASE,aAAaF,IAAY,EAAA;IAChC,OAAO,gBAAA,CAAiBC,IA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